Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Lower the whole X1 shared cache ahead of time and add fold posture (work in progress)

Jacky4dcfb720aa54
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 77151259..2b1e483d 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -206,6 +206,55 @@
> donor tree only into its installed identity. No new kernel instruction patch.
> See [HomePod mini support](Firmware/homepod_mini_support.md) for evidence,
> validation status and limitations.
+
+> **VirtualAudio device-state guard (2026-10-23):**
+> `system-virtualaudio-cfw-device_state_guard` (guest system set, iOS 27, on
+> in `standard`, blocked in `tvos` and `tvos-4k`; verb `cfw
+> patch-virtualaudio-device-state-guard`, riding the shared staged copy with
+> the other four VirtualAudio verbs) stands down the two device-state updates
+> that read the DeviceStateManager singleton before deferred initialization
+> publishes it — the audiomxd crash loop on the iPhone Duo guest, ~0.6 s
+> after every launch, once the four speaker-route patches let the route
+> through. Each gate's `cbz w0, <skip>` becomes an unconditional `b` to the
+> same target. The plugin header gates the patch to arm64e.x1 (cpusubtype 12,
+> iOS 27.1's iPhone19,4): the 26.6.2 and 27.0 plugins are plain arm64e and
+> are left byte-identical. The five other TheInstance callers are
+> HapticAttenuationIODelegate's and are not touched — see the full section
+> below. Live validation on `duotest-m5` is pending a bundle install.
+
+> **ARM64E_X1 whole-cache lowering (2026-10-23):** `dyld-cfw-arm64e_x1_cache`
+> (guest system set, iOS 27, on in `standard`, blocked in `tvos` and
+> `tvos-4k`; verb `cfw patch-arm64e-x1-cache`) lowers the X1 instructions of
+> every shared-cache image outside `dyld-boot-arm64e_x1_bootstrap`'s 38-image
+> closure, with the same planner and replacement table, and re-attests each
+> modified page. Without it every other image faults into launchd's
+> single-threaded on-demand handler once per site per process; on iPhone19,4
+> 27.1 (24A94425) that left launchd at 685 CPU-seconds 18 minutes after boot
+> and FrontBoard killing SwiftUI-heavy extensions at the 10-second scene
+> watchdog. On that cache it writes 24,606,083 instructions in 212,573 page
+> runs across 4,508 images, skips none, and leaves 250,443 unvisited
+> candidates to the on-demand handler; a full pass takes about 95 s on an
+> M5 Pro. The planner's speedups (parallel images, thread-local locale,
+> word-keyed decode cache, verified PC-relative moves, bitmap sets) were each
+> checked to produce byte-identical caches, including the bootstrap patch's
+> output against HEAD. The 27.1 VirtualAudio reveal now accepts
+> `PACIBSPPC`/`RETABSPPC` prologues and returns; the audiomxd crash those
+> four patches triggered on 27.1 is root-caused as the pre-init
+> DeviceStateManager read and fixed by
+> `system-virtualaudio-cfw-device_state_guard` above.
+> See [Duo bring-up](Guest/iphone_duo_bringup.md).
+
+> **Foldable VM sub-type (2026-10-23):** `preboot-cfw-devicetree_foldable_vm_subtype`
+> (guest system set, Preboot device-tree repair, on in `standard`, blocked in
+> `tvos` and `tvos-4k`, not applicable to boards without an entry; verb
+> `cfw patch-dt-foldable-vm-subtype`) rewrites the installed tree's root
+> `target-sub-type` from `V68AP` to Apple's `V68VM2025` during `cfw install`
+> and `cfw update-environment`, never during restore. SpringBoardFoundation
+> then takes its VM path for the fold pose (restore at launch, persist after
+> transitions). vphoned's new `display.posture` drives the pose through the
+> test-automation override (`com.apple.springboard.testautomation` added to
+> `VPhoneDaemon.entitlements`). See [Duo bring-up](Guest/iphone_duo_bringup.md#fold-posture-2026-10-23).
+
> **iPhone Duo bring-up (2026-10-23, first boot fails):**
> `iPhone19,4` / V68AP, iOS 27.1 (24A94425), is registered with one outer
> display and paired with cloudOS 26.4 (23E5207q). Its device tree reports
@@ -4049,3 +4098,79 @@ stderr/stdin streams, legacy fixed-address NAT reporting, patch catalog and reci
consistency, plus full bundle/Launchpad builds. Firmware fixture tests still
require the separately held reference IPSWs; a build or synthetic test is not a
claim that every newly supported OS has been restored and booted on this host.
+
+## VirtualAudio's device-state guard — the null singleton before deferred init (2026-10-23)
+
+`system-virtualaudio-cfw-device_state_guard` (new), same
+`VirtualAudio.plugin` binary, verb `cfw patch-virtualaudio-device-state-guard`,
+riding the same `patchMachO` staged copy as the other four VirtualAudio
+verbs in both `cfw install` and `cfw update-environment`. Patcher:
+`FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift`
+(`patchDeviceStateGuard`, anchoring in `locateDeviceStateGuard` and
+`gatedDeviceStateSite`).
+
+**Fault.** With the four speaker-route patches live on iPhone19,4 27.1
+(24A94425, arm64e.x1), audiomxd segfaults (EXC_BAD_ACCESS far=0) ~0.6 s
+after every launch, on queue AudioControl, in the plugin at 0xa16b0
+reached `HALS_AHPPlugIn::ObjectSetPropertyData` ←
+`__vaemVADSerializationListener_block_invoke`. Publishing the route wakes
+`VirtualAudio_Device`'s update (function at 0xa08bc), which pushes the
+route's state at `DeviceStateManager` twice, each push behind its own
+capability gate (checks at 0xfe810 and 0x225b88): gate `bl`, `cbz w0,
+<skip>`, `bl` TheInstance (0x2b2988), `mov x20, x0`, `ldr x21, [x0]` —
+the faulting unchecked read. The singleton's global (0x74ff28) is stored
+only at 0x3ad0a8, inside "Deferred Initialization", after a wait of up to
+8 s for a haptic actuator port a VM does not have; asked earlier,
+TheInstance logs "TheInstance() called before SetInstance()" and returns
+null. The saved VAD serialization state replays the same property write
+into every launch, so one fault is a crash loop. 27.0 carries the same
+gated code (update at 0xa1ee4, TheInstance at 0x2b64ec) but its graph
+never takes the path; none of the other four patches' sites is on it.
+
+**Reveal** (all Capstone-decoded, no literal address). TheInstance is
+found from its own diagnostic: the "TheInstance() called before
+SetInstance()" cstring, referenced exactly once in `__text`; the prologue
+above the reference (`pacibsppc`) is TheInstance's entry. Every direct
+`bl` to that entry — six on 27.1 — is filtered to the gated shape above:
+a call at −8 (the gate check), a `cbz w0` at −4 whose decoded target
+skips forward past the whole update (target beyond the `ldr` at +8), the
+return moved aside at +4 (`mov xN, x0`), and the unchecked dereference at
++8 (`ldr xM, [x0]`). Exactly two callers carry the shape; a build with a
+different count is refused rather than half-patched. The plugin header
+gates everything first: cputype arm64 and cpusubtype (masked of the
+LIB64 bit) 12 — arm64e.x1. Any other subtype reports "nothing to do" and
+writes nothing, which is what keeps 26.6.2 and 27.0 byte-identical; a
+file that is not a thin arm64 image falls through to the anchor's own
+refusal.
+
+**The write.** Each gate's `cbz w0, <skip>` becomes an unconditional `b`
+to the same target (`ARM64Encoder.encodeB`): the gate-check call still
+runs, its answer is no longer read, and the device-state update is
+skipped exactly as when the gate's check answers false — the state the
+VM is always in before SetInstance. After deferred initialization
+completes, TheInstance answers a real singleton and every later update
+reaches the manager. Idempotent: a re-run finds the unconditional branch
+in the gate slot, requires it to skip past the dereference, and writes
+nothing. Verified on the real binaries: 27.1 resolves TheInstance at
+0x2b2988 and rewrites exactly the two gates (0xa16a4 `cbz w0, 0xa16d8`
+→ `b 0xa16d8`, 0x340001a0 → 0x1400000d; 0xa16e0 `cbz w0, 0xa1720` →
+`b 0xa1720`, 0x34000200 → 0x14000010) — six bytes move, a second run is
+byte-identical — and the 27.0 and 26.6.2 plugins report "not an
+arm64e.x1 plugin" with unchanged SHA-256s.
+
+**The callers left alone.** The other five TheInstance callers
+(0x4f7b94, 0x4f7dec, 0x4f9114, 0x5013ac, and the coordinator) all live
+in `HapticAttenuationIODelegate.mm`. The 0x4f7dec caller dereferences
+the singleton unguarded exactly like the crash site (`mov x20, x0; ldr
+x21, [x0]`, field 0x170), but its whole block sits behind a capability
+flag (`tbz w8, #0` at 0x4f7d0c skipping past it) that reads false
+without a Taptic Engine — the same absence that makes deferred
+initialization time out; the other three pass the singleton into
+0x2b30b4, which does dereference unchecked (0x2b30d8) but is reached
+only through the coordinator's activation ("Coordinator active
+(subscriptions set)"), which needs an actuator port. Across the observed
+crash loop neither path ever faulted — every crash is the device-state
+site — so they are unpatched; if a future build ever faults there, the
+guard's matcher refuses (it requires the gate shape) and the site gets
+its own patch. Research detail:
+`Research/Guest/virtualaudio_speaker_route_throws.md`.
diff --git a/Research/Guest/iphone_duo_bringup.md b/Research/Guest/iphone_duo_bringup.md
index 9f29eae7..19c523e5 100644
--- a/Research/Guest/iphone_duo_bringup.md
+++ b/Research/Guest/iphone_duo_bringup.md
@@ -108,3 +108,152 @@ The original manifests and device tree were extracted by HTTP ranges with
the repository's `VPhoneRemoteZip`. Raw logs and scratch artifacts remain
local; host paths, per-machine identifiers and runtime addresses are not
included in this research record.
+
+## Boot on a host with CSSC (2026-10-23)
+
+**Result: boots to SpringBoard.** On a Mac17,9 (M5 Pro), macOS 27.0.1
+(26A434), `hw.optional.arm.FEAT_CSSC` is 1; `FEAT_CPA`, `FEAT_CPA2` and
+`FEAT_PAuth_LR` are 0. Scalar `UMIN`/`UMAX`/`CTZ` execute on the host. The
+same IPSW, the same standard preset and a Core Bundle containing this
+document's first commit (no CSSC lowering) completed every `vm create
+--device iPhone19,4 --no-template` step, including template setup, which
+waits for vphoned. The home screen rendered at 1398 x 2034. Its side dock and
+status column on the right are the Duo's outer-display design, not a fault.
+CSSC is therefore the blocker on hosts without it; PAuth_LR and CPA remain
+covered by X1 lowering.
+
+### On-demand X1 handling stalled the userland
+
+That boot was barely usable: windows took seconds to draw, widgets stayed
+blank, and FrontBoard killed extensions. 18 minutes after boot, launchd
+(PID 1) had used 685 CPU-seconds. Crash reports showed `MercuryPosterExtension`
+(43 reports), `WidgetRenderer_Default`, `DockFolderViewService` and others
+ending in `scene-create watchdog transgression … 10.00 seconds`, many with a
+pending `EXC_BAD_INSTRUCTION` whose code is the X1 word itself:
+`0xdac1a7fe` (`PACIBSPPC`) in SwiftUI and `/usr/lib/usd/libusd_ms.dylib`,
+`0x5520031f` (`RETABSPPC`) in `libusd_ms.dylib`.
+
+The cause is the design of the X1 path, not a missing instruction form.
+`dyld-boot-arm64e_x1_bootstrap` lowers only the 38 cache images needed
+before launchd installs its exception service; every other image faults
+into that service, which runs on one thread in PID 1, suspends the task,
+makes a private copy of the page and lowers one instruction. A private copy
+means each process re-faults every site it executes, so SwiftUI-heavy
+extensions queue on launchd until the 10-second scene watchdog fires, and
+the poster extension's restarts keep the queue full.
+
+### Lowering the rest of the cache ahead of time
+
+`dyld-cfw-arm64e_x1_cache` (guest system set, iOS 27, on in `standard`,
+blocked in both tvOS presets; verb `vphone-cli cfw patch-arm64e-x1-cache`)
+runs the bootstrap patch's planner over every X1 image outside the
+bootstrap closure, writes through the undo-capturing chunk set and
+re-attests every modified page. An image the planner cannot plan is left to
+the on-demand handler and logged; none were on 24A94425.
+
+| 24A94425 cache | Value |
+| --- | --- |
+| Images | 4,664 (4,508 with X1 code, 0 skipped) |
+| Instruction rewrites | 24,606,083 in 212,573 page runs |
+| Left to the on-demand handler (unvisited candidates) | 250,443 |
+| Examples | UIKitCore 235,776; `libusd_ms.dylib` 353,431; SwiftUI 134,497; SwiftUICore 116,029 |
+
+The installed guest receives 24,606,071 rewrites, 12 fewer: other dyld
+patches already occupy those sites.
+
+The planner needed changes to be affordable at this size; each was checked
+by patching a stock copy of the cache and comparing all 81 cache files with
+the previous version's output (and, for the bootstrap patch, with the bytes
+HEAD wrote), and every comparison was identical:
+
+| Change | Full pass on M5 Pro |
+| --- | --- |
+| Serial, page-decoding planner | about 26 min (dry run) |
+| Parallel images, thread-local C locale (Capstone's `vsnprintf` serialized every thread on the global locale), one-word decodes instead of a 16-page cache that thrashed | 8.5 min |
+| Decode cache keyed by instruction word; code ranges unpacked to `[UInt32]` once (a generic `loadLE` across PatchKit's resilient boundary cost a metadata lookup per word) | 200 s |
+| Bitmap visited/scheduled sets, largest images first, PC-relative words cached once Capstone confirms a single address/page/no move at a second address, top-byte gates before mnemonic comparisons | 95 s |
+| One decoder per worker reused across images; branch, literal and ADR/ADRP words keyed by family (offset field cleared, target computed from the encoding, the operand's aliased register/memory views rebuilt), each family trusted only after Capstone agrees at a second target; planning readers map each chunk once | 1,241 → 914 user CPU-s (wall time not comparable: load average 24–31) |
+
+The planning core, `CustomFirmwareArm64eX1.planCode`, is shared with the
+standalone-executable patches; its output is unchanged by these edits.
+
+After `vm set-bundle … --update-environment` applied the patch to the
+existing guest, launchd had used 14.8 CPU-seconds two minutes after boot,
+no poster or widget-renderer watchdog kills recurred, and Settings drew its
+first screen within seconds of launch. Standalone X1 binaries outside the
+cache (app executables, plug-ins such as `VirtualAudio.plugin`, daemons)
+still use the on-demand handler.
+
+### VirtualAudio on 27.1
+
+The four VirtualAudio CFW patches failed on 24A94425 because every function
+there starts with `PACIBSPPC` and returns with `RETABSPPC <label>`; the
+reveal knew only `PACIBSP`/`RETAB`. The patcher now accepts both families
+and requires a labelled return to name the function being walked. Capstone
+reports that label as `#0`, so it is read from the decoded word's field.
+All nine sites patch on 27.1 and the 26.6.2 and 27.0 sites are unchanged.
+With them live, audiomxd crash-looped on this guest (a null read in
+`VirtualAudio.plugin` reached from `SetPropertyData`): the device update
+reads the DeviceStateManager singleton before deferred initialization
+publishes it. Root-caused and fixed by
+`system-virtualaudio-cfw-device_state_guard` (stand each gated
+device-state update down while the singleton is absent; arm64e.x1
+plugins only, earlier builds byte-identical) — see
+`Research/Guest/virtualaudio_speaker_route_throws.md` § "Layer 5" and
+`Research/0_binary_patch_comparison.md`. Offline validation is done;
+live validation on this VM is pending a bundle install.
+
+## Fold posture (2026-10-23)
+
+Static analysis of the 24A94425 cache, then a live run on `duotest-m5`
+(M5 Pro) with `preboot-cfw-devicetree_foldable_vm_subtype` and
+`display.posture` installed:
+
+- The repair logged `target-sub-type: 'V68AP' -> 'V68VM2025'`, and after boot
+ SpringBoard had created `SBFDevicePoseLastKnownCMAngle` and
+ `SBFDevicePoseLastKnownCMMagicPose` in `com.apple.springboard` (still all
+ zero: it persists after display-mode transitions, which a single display
+ never makes).
+- `display.posture {hinge: "partially-open"}` was accepted: SpringBoard
+ logged `[SBTestAutomationService] Received client request to set device pose
+ override`, `Ambient magic pose event detected [ … hingeState : PO ;
+ deviceOrientation : Po … ]`, and `hinge MOTION STARTED` … `hinge SETTLED
+ after 1.03s`, with the home and lock screens deferring and resuming
+ snapshots around it. Closed, partially open and open flat produced the same
+ home screen: with only the outer panel there is no inner surface to move
+ content to. StandBy reported `isMagicPoseSupported : NO`.
+
+**Where the pose comes from.** `SBFDevicePoseProvider` (SpringBoardFoundation)
+reads `BKSAccelerometer`, `CMAngleManager` and `CMMagicPoseManager`.
+SpringBoard's own CoreMotion hosts `CLAngleNotifier` (HID event type 0x2C,
+`IOHIDEventCreateHingeAngleEvent`, virtual service 0xFF0C/0x21) and
+`CLDeviceStateNotifier` (8-byte vendor event `{2, orientation ×3, hinge
+state, tabletop pose, stable state, simulated}`, virtual service 0xFF0C/0x22).
+CoreMotion skips physical sensors when MobileGestalt reports a virtual device.
+
+**Why a virtual hinge HID service is not enough today.** SpringBoard starts
+CoreMotion pose updates only when the angle and magic-pose managers are
+available *and* `FBDisplayManager.alwaysConnectedIdentities.count >= 2`.
+Availability comes from CoreMotion's motion-capability bits, selected by the
+device tree's `/product/product-id`; the guest keeps vphone600's id, which
+CoreMotion does not know, so both are false. One display fails the second
+gate. The HID route belongs with dual-display work, together with V68's
+`product-id` (which also turns on the Duo checks in UIKit, Photos,
+Accessibility and other frameworks).
+
+**What works now.** `-[SBSTestAutomationService setDevicePoseOverride:]`
+bypasses both gates: SpringBoard (`SBTestAutomationService`, client
+entitlement `com.apple.springboard.testautomation`) builds an
+`SBFSyntheticMagicPoseEvent` from the device orientation, hinge state and
+tabletop pose and derives the angle from the hinge state. vphoned exposes it
+as `display.posture` (see `Research/vphoned_http_api.md`).
+
+**Apple's VM sub-type.** SpringBoard treats a device whose `TargetSubType` is
+`V68VM2025` as a VM: at launch it restores the angle and magic pose from
+`com.apple.springboard` defaults `SBFDevicePoseLastKnownCMAngle` and
+`SBFDevicePoseLastKnownCMMagicPose`, and `_persistDevicePoseIfNeeded` writes
+them back after display-mode transitions. `preboot-cfw-devicetree_foldable_vm_subtype`
+rewrites the installed Preboot tree's `target-sub-type` from `V68AP` to
+`V68VM2025` after restore (restore keeps the board's value). The only other
+reader of `V68AP` in the cache is Sharing's `SFDeviceHasFaceIDProxy`; the
+framework `isV68` checks key on `product-id` and are unaffected.
diff --git a/Research/Guest/virtualaudio_speaker_route_throws.md b/Research/Guest/virtualaudio_speaker_route_throws.md
index 9e57d837..6befdc7f 100644
--- a/Research/Guest/virtualaudio_speaker_route_throws.md
+++ b/Research/Guest/virtualaudio_speaker_route_throws.md
@@ -685,3 +685,99 @@ its I/O context is `PuffinOutput (VAD [vdef] AggDev N)`. Volume adjusts
(`Setting hardware volume to -11.97 dB` on device `PuffinOutput`). What still
kept the tone silent after that was not routing: see `virtio_sound.md` §6 for
the plugin faults and §7 for the haptic track.
+
+## Layer 5 — the null DeviceStateManager singleton on arm64e.x1 (2026-10-23, decoded)
+
+On iPhone19,4 iOS 27.1 (24A94425) — the arm64e.x1 userland — all four
+patches above apply cleanly (the reveal now reads `pacibsppc` /
+`retabsppc <label>` frames) and the route goes through, and audiomxd
+then segfaults ~0.6 s after every launch: EXC_BAD_ACCESS far=0, queue
+AudioControl, plugin offset 0xa16b0, reached
+`HALS_AHPPlugIn::ObjectSetPropertyData` ←
+`__vaemVADSerializationListener_block_invoke`. Both saved crash reports
+fault at exactly that offset.
+
+The faulting function is `VirtualAudio_Device`'s update (0xa08bc; its
+`retabsppc` names it). After the route is published it pushes the
+route's state at `DeviceStateManager` **twice**, each push gated by a
+capability check:
+
+```
+a169c ldr x0, [x19, #0x368] ; the HAL device
+a16a0 bl 0xfe810 ; gate 1: DSP-graph property check
+a16a4 cbz w0, 0xa16d8 ; skip the update when false
+a16a8 bl 0x2b2988 ; DeviceStateManager::TheInstance()
+a16ac mov x20, x0
+a16b0 ldr x21, [x0] ; <-- faults: singleton is null
+ … lock / ldr w20,[vtable+0x150] / unlock / bl 0x225748 …
+a16d8 ldr x0, [x19, #0x368]
+a16dc bl 0x225b88 ; gate 2: capability check
+a16e0 cbz w0, 0xa1720
+a16e4 bl 0x2b2988 ; TheInstance again
+a16ec ldr x21, [x0] ; same unchecked read
+ … lock / read / unlock / ldarb global / bl 0x2259b4 …
+a1720 add x0, sp, #0xf ; past both gates
+```
+
+`TheInstance()` (0x2b2988) loads the global at 0x74ff28 and returns it
+on the fast path; when the global is null it logs
+"TheInstance() called before SetInstance()", reloads the global and
+returns that — null. The global is stored exactly once, at 0x3ad0a8
+inside "Deferred Initialization", *after* waiting up to 8 s for a
+haptic actuator port the VM does not have. So the ordering on a 27.1
+guest is: route published → serialization listener pushes saved state →
+device update runs → TheInstance is null → fault. The saved state
+replays on every launch: the crash loop. None of the four patches'
+sites is on this path, and 27.0 (update at 0xa1ee4, TheInstance at
+0x2b64ec, same gated shape) never takes it — its graph's gates answer
+false before the singleton is read.
+
+**The fix** is the fifth binary patch,
+`system-virtualaudio-cfw-device_state_guard` (verb
+`cfw patch-virtualaudio-device-state-guard`, declared in
+FirmwareGuestSystemPatchSet, on in `standard` for iOS 27, blocked for
+tvOS; see `Research/0_binary_patch_comparison.md` for the entry): each
+gate's `cbz w0, <skip>` becomes an unconditional `b` to the same target
+— 0xa16a4: `cbz w0, 0xa16d8` → `b 0xa16d8` (0x340001a0 → 0x1400000d)
+and 0xa16e0: `cbz w0, 0x1720` → `b 0xa1720` (0x34000200 → 0x14000010).
+The gate-check calls still run; their answers are no longer read, and
+both device-state updates are skipped exactly as when a gate answers
+false. Once deferred initialization finishes, TheInstance answers a
+real singleton and every later update reaches the manager.
+
+**Anchoring** follows the file's rules: nothing is a literal address.
+The "TheInstance() called before SetInstance()" cstring is referenced
+exactly once in `__text`; the prologue above that reference is
+TheInstance. Every direct `bl` to it (six on 27.1) is filtered to the
+gated shape — call at −8, `cbz w0` at −4 skipping past the whole
+update, `mov xN, x0` at +4, `ldr xM, [x0]` at +8 — and exactly two
+callers match; any other count refuses. The plugin header gates the
+whole patch to arm64e.x1 (cputype arm64, cpusubtype masked of the
+LIB64 bit == 12): the 26.6.2 and 27.0 plugins (cpusubtype 2) report
+"not an arm64e.x1 plugin", exit 0 and keep their SHA-256s, so the
+installer's shared staged copy costs them nothing.
+
+**The other five callers, examined and left alone.** All are in
+`HapticAttenuationIODelegate.mm`:
+
+| Call | Shape | Why it cannot fault pre-init on this guest |
+| --- | --- | --- |
+| 0x4f7dec | `mov x20,x0; ldr x21,[x0]` — unguarded deref like ours, field 0x170 | The whole block sits behind a capability flag (`tbz w8,#0` @0x4f7d0c skips past it) that reads false without a Taptic Engine — the same absence that makes deferred init time out. |
+| 0x4f7b94, 0x4f9114, 0x5013ac | pass the singleton into 0x2b30b4, which derefs unchecked at 0x2b30d8 | Reached only through the coordinator's activation ("Coordinator active (subscriptions set)" @0x4f91a8), which needs an actuator port to subscribe to. |
+| 0x4f7b94's sibling reads | — | Same coordinator. |
+
+Across the whole observed crash loop neither path ever faulted — both
+crash reports are the device-state site — so they stay unpatched. The
+guard's matcher would refuse them anyway: it requires the `cbz w0` gate
+under the call, which is exactly what distinguishes the two device-state
+updates. If a future build ever faults in the delegate, that site needs
+its own patch.
+
+**Status.** Patcher, declaration, verb, installer wiring, tvOS block
+lists and unit tests are in; the verb patches a copy of the stock 27.1
+plugin (six bytes, the two gate words above) and a second run is
+byte-identical; the 27.0 and 26.6.2 copies are untouched.
+`FirmwarePatcherTests` shows no new failures against a HEAD baseline
+(the fixture suites fail identically on both trees). Not yet done:
+live validation on `duotest-m5` through a bundle install +
+`vphone-launchpad-cli vm set-bundle duotest-m5 <ver> --update-environment`.
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index 23c1ee3c..cf447cd7 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -371,7 +371,7 @@ request carries `"force": true`.
| Area | Methods |
| --- | --- |
| Device | `device.snapshot`, `device.info` (snapshot plus network, screen, rotation, brightness, volume, low power, Developer Mode, agent, `device_name` `{name, own_name}`: the pinned name and the guest's own ComputerName), `device.screen`, `device.network`, `device.ioreg {plane}`, `device.environment`, `device.basebin {archive?}` |
-| Display, audio | `display.brightness {value?}`, `display.rotation {orientation?}`, `display.orientation` (`{degrees, source}`: SpringBoard's interface orientation without a screen capture, for polling; `degrees` is null while SpringBoard has no answer; capability `display_orientation`), `display.rotation_lock {locked}`, `display.auto_lock` (`{auto_lock_seconds, never, lock_screen_minimum_seconds}`), `display.auto_lock.set {seconds}` (writes the mobile UserSettings input through cfprefsd, posts profiled's effective-settings notification, and returns an immediate readback; the caller must verify the effective value), `screen.unlock {passcode?, timeout?}` (`{locked, screen_off, was_locked, was_screen_off}`: the display on and the Lock Screen passed, see below; capability `screen_unlock`), `audio.volume {value?, category?}`, `audio.state` |
+| Display, audio | `display.brightness {value?}`, `display.rotation {orientation?}`, `display.posture {hinge, orientation?, tabletop?}` (a foldable guest's pose through SpringBoard's test-automation override, see below; capability `device_pose`), `display.orientation` (`{degrees, source}`: SpringBoard's interface orientation without a screen capture, for polling; `degrees` is null while SpringBoard has no answer; capability `display_orientation`), `display.rotation_lock {locked}`, `display.auto_lock` (`{auto_lock_seconds, never, lock_screen_minimum_seconds}`), `display.auto_lock.set {seconds}` (writes the mobile UserSettings input through cfprefsd, posts profiled's effective-settings notification, and returns an immediate readback; the caller must verify the effective value), `screen.unlock {passcode?, timeout?}` (`{locked, screen_off, was_locked, was_screen_off}`: the display on and the Lock Screen passed, see below; capability `screen_unlock`), `audio.volume {value?, category?}`, `audio.state` |
| Input | `input.touch`, `input.hid`, `input.button {name}`, `input.key {name}`, `input.type {text, delay_ms?}`, `input.paste {text}`, `input.tap`, `input.double_tap`, `input.long_press`, `input.swipe`, `input.drag {points}`, `input.touch_sequence {events}` — gesture coordinates are screen points; `input.pointer {x, y, seq?, buttons?}`, `input.scroll {phase, dx?, dy?, x?, y?}` (capabilities `pointer_scroll` and `pointer_buttons`, see below) |
| UI | `ui.tree` (alias `accessibility.tree`), `ui.element_at`, `ui.tap_element`, `ui.wait`, `ui.wait_gone`, `ui.ocr {languages?, min_confidence?}`, `ui.describe`, `screen.screenshot` |
| Processes | `processes.list {filter?}`, `processes.kill {pid, signal?}` **force**, `memory.jetsam`, `memory.pressure` (only the three kernel memory sysctls, for polling) |
@@ -1053,3 +1053,26 @@ The listener accepts the address specified by the user. For local-only use,
pass `127.0.0.1` or `[::1]`. Any other address prints a warning: every machine
that can reach it needs only the token, which travels in clear text over
plain HTTP, so use it only on a trusted network.
+
+## Device pose
+
+`display.posture` sets a foldable guest's pose (iPhone Duo). A VM has no
+hinge, and SpringBoard consumes CoreMotion's hinge angle and magic pose only
+when CoreMotion recognizes the board's `product-id` and the device has two
+always-connected displays, so a virtual hinge HID service would not be read
+on today's single-display guest. vphoned instead calls
+`-[SBSTestAutomationService setDevicePoseOverride:]`, which SpringBoard
+accepts from a client entitled `com.apple.springboard.testautomation`; the
+server builds a synthetic magic pose and derives the hinge angle from the
+hinge state (0, 0, 90, 180 and 180 degrees for states 0–4).
+
+| Param | Values |
+| --- | --- |
+| `hinge` (required) | `ambiguous` 0, `closed` 1, `partially-open` 2, `open-flat` 3, `open` 4 |
+| `orientation` | `ambiguous` 0, `portrait` 1 (default), `upside-down` 2, `landscape-left` 3, `landscape-right` 4, `face-up` 5, `face-down` 6 |
+| `tabletop` | 0–10 (default 0, ambiguous) |
+
+The reply echoes the numeric values. The override does not survive a
+SpringBoard restart unless the guest also reports Apple's VM sub-type
+(`preboot-cfw-devicetree_foldable_vm_subtype`), with which SpringBoard
+persists the pose after display-mode transitions and restores it at launch.
diff --git a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements
index 031cbfa9..6eb60a7a 100644
--- a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements
+++ b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements
@@ -550,6 +550,8 @@
<true/>
<key>com.apple.springboard.openurlswhenlocked</key>
<true/>
+ <key>com.apple.springboard.testautomation</key>
+ <true/>
<key>com.apple.timed</key>
<true/>
<key>com.apple.timed.sources</key>
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Device.swift b/VPhoneDaemon/Daemon/GuestAPI+Device.swift
index 9abb90c2..41abc2e8 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Device.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Device.swift
@@ -108,6 +108,8 @@ extension GuestAPI {
return rotation
case "display.orientation":
return interfaceOrientation()
+ case "display.posture":
+ return try setDevicePose(params)
case "display.rotation_lock":
guard let locked = params["locked"] as? Bool else {
throw GuestAPIError.invalidRequest("locked must be true or false")
@@ -162,6 +164,46 @@ extension GuestAPI {
]
}
+ // MARK: Device pose
+
+ /// CoreMotion's magic-pose values, by name. SpringBoard derives the hinge
+ /// angle from the hinge state with a five-entry table, so the hinge stops
+ /// at "open" (open, ambiguous); "transitioning" is not accepted.
+ static let poseHingeStates = ["ambiguous": 0, "closed": 1, "partially-open": 2, "open-flat": 3, "open": 4]
+ static let poseOrientations = [
+ "ambiguous": 0, "portrait": 1, "upside-down": 2, "landscape-left": 3,
+ "landscape-right": 4, "face-up": 5, "face-down": 6,
+ ]
+
+ /// Set a foldable guest's pose through SpringBoard's test-automation
+ /// override: `hinge` (a name or 0–4), `orientation` (a name or 0–6,
+ /// default portrait) and `tabletop` (0–10, default 0, ambiguous).
+ private static func setDevicePose(_ params: [String: Any]) throws -> [String: Any] {
+ func value(_ key: String, names: [String: Int], range: ClosedRange<Int>, default fallback: Int?) throws -> Int {
+ if let name = params[key] as? String {
+ guard let value = names[name.lowercased()] else {
+ throw GuestAPIError.invalidRequest("\(key) must be one of \(names.keys.sorted().joined(separator: ", "))")
+ }
+ return value
+ }
+ if let number = params[key] as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() {
+ guard range.contains(number.intValue), Double(number.intValue) == number.doubleValue else {
+ throw GuestAPIError.invalidRequest("\(key) must be an integer in \(range.lowerBound)...\(range.upperBound)")
+ }
+ return number.intValue
+ }
+ guard params[key] == nil, let fallback else { throw GuestAPIError.invalidRequest("\(key) is required") }
+ return fallback
+ }
+ let hinge = try value("hinge", names: poseHingeStates, range: 0 ... 4, default: nil)
+ let orientation = try value("orientation", names: poseOrientations, range: 0 ... 6, default: 1)
+ let tabletop = try value("tabletop", names: [:], range: 0 ... 10, default: 0)
+ guard vp_device_pose_set(Int32(orientation), Int32(hinge), Int32(tabletop)) else {
+ throw GuestAPIError.operationFailed("SpringBoardServices has no device pose override on this guest")
+ }
+ return ["hinge": hinge, "orientation": orientation, "tabletop": tabletop]
+ }
+
private static func brightnessState() -> [String: Any] {
["value": brightness(), "auto": autoBrightness().map { $0 as Any } ?? NSNull()]
}
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index d663c289..28c43fcc 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -118,6 +118,7 @@ enum GuestAPI {
"display",
"display_orientation",
"display_auto_lock",
+ "device_pose",
"screen_unlock",
"audio",
"input_gestures",
diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.h
index 3ff65b10..594186e6 100644
--- a/VPhoneDaemon/Native/Include/VphonedNative.h
+++ b/VPhoneDaemon/Native/Include/VphonedNative.h
@@ -46,6 +46,7 @@ void vp_hid_touch_edge(int phase, double x, double y, int edge);
/// Turn the display on without pressing a button. False when
/// SpringBoardServices has no SBSUndimScreen.
bool vp_screen_undim(void);
+bool vp_device_pose_set(int deviceOrientation, int hingeState, int tabletopPose);
/// Ask launchd to shut the guest down and halt. Returns 0 once the request is
/// accepted, otherwise an errno value. Needs root.
diff --git a/VPhoneDaemon/Native/vphoned_pose.m b/VPhoneDaemon/Native/vphoned_pose.m
new file mode 100644
index 00000000..049b6923
--- /dev/null
+++ b/VPhoneDaemon/Native/vphoned_pose.m
@@ -0,0 +1,43 @@
+/*
+ * vphoned_pose — set a foldable guest's device pose.
+ *
+ * A VM has no hinge, and SpringBoard only consumes CoreMotion's hinge angle
+ * and magic pose on a board CoreMotion recognizes with two always-connected
+ * displays. SpringBoardServices' test-automation client sets the pose
+ * directly: SpringBoard builds a synthetic magic pose from the device
+ * orientation, hinge state and tabletop pose, and derives the hinge angle
+ * from the hinge state. The server checks the client for
+ * com.apple.springboard.testautomation, which vphoned carries.
+ *
+ * The class is resolved at run time, so a base without it reports false.
+ */
+
+#import "Include/VphonedNative.h"
+
+#include <dlfcn.h>
+#include <objc/message.h>
+
+/// The override `-[SBSTestAutomationService setDevicePoseOverride:]` takes, as
+/// SpringBoard's handler reads it: a 64-bit orientation, then the device
+/// orientation, hinge state and tabletop pose as 32-bit values.
+typedef struct {
+ int64_t orientation;
+ int32_t deviceOrientation;
+ int32_t hingeState;
+ int32_t tabletopPose;
+} VPDevicePoseOverride;
+
+bool vp_device_pose_set(int deviceOrientation, int hingeState, int tabletopPose) {
+ static Class service;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ dlopen("/System/Library/PrivateFrameworks/SpringBoardServices.framework/SpringBoardServices", RTLD_NOW);
+ service = NSClassFromString(@"SBSTestAutomationService");
+ });
+ SEL selector = NSSelectorFromString(@"setDevicePoseOverride:");
+ if (!service || ![service instancesRespondToSelector:selector]) return false;
+ id client = [service new];
+ VPDevicePoseOverride pose = {deviceOrientation, deviceOrientation, hingeState, tabletopPose};
+ ((void (*)(id, SEL, VPDevicePoseOverride))objc_msgSend)(client, selector, pose);
+ return true;
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift
index d13351eb..fbc49c78 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift
@@ -471,6 +471,44 @@ public enum CustomFirmwarePostRestoreDeviceTree {
return (serializeNode(root), records, delta)
}
+ /// Apple's own VM sub-types for foldable boards, by the board's
+ /// `target-sub-type`. SpringBoardFoundation's `SBFDevicePoseProvider`
+ /// marks the device a VM when MobileGestalt's `TargetSubType` is the VM
+ /// value, and `SBFDisplayContentModeResolver` then restores the fold pose
+ /// ("Restore pose on VM") instead of waiting for hinge hardware.
+ public static let foldableVMSubtypes = ["V68AP": "V68VM2025"]
+
+ /// `blob` with its root `target-sub-type` replaced by the board's VM
+ /// sub-type. A tree whose sub-type has none, or already has it, comes back
+ /// unchanged.
+ public static func withFoldableVMSubtype(_ blob: Data) throws -> (Data, [Change], Int) {
+ let root = try parseTree(blob, label: "DT")
+ guard let property = root.properties.first(where: { $0.name == "target-sub-type" }) else {
+ return (blob, [], 0)
+ }
+ let before = String(decoding: property.value.prefix { $0 != 0 }, as: UTF8.self)
+ guard let vm = foldableVMSubtypes[before] else { return (blob, [], 0) }
+ let value = Data(vm.utf8) + [0]
+ let delta = align4(value.count) - align4(property.value.count)
+ property.value = value
+ property.flags = 0
+ return (serializeNode(root), [Change(property: "target-sub-type", before: before, after: vm)], delta)
+ }
+
+ /// Give a foldable guest's `devicetree.img4` (or bare `.im4p`) the board's
+ /// VM sub-type, in place. See `withFoldableVMSubtype`.
+ @discardableResult
+ public static func presentFoldableVMSubtype(
+ at url: URL,
+ dryRun: Bool = false,
+ verbose: Bool = true,
+ ) throws -> Outcome {
+ try rewrite(at: url, dryRun: dryRun, verbose: verbose) { blob in
+ let (newBlob, changes, delta) = try withFoldableVMSubtype(blob)
+ return (newBlob, changes, blob.count + delta)
+ }
+ }
+
/// The root of a flat tree that must fill `blob` exactly.
private static func parseTree(_ blob: Data, label: String) throws -> DeviceTreePatcher.DTNode {
let (root, end) = try parseNode(blob, at: 0)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareArm64eX1.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareArm64eX1.swift
index 5535a7d6..636d1841 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareArm64eX1.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareArm64eX1.swift
@@ -5,7 +5,7 @@ import MachO
import VPhonePatchKit
public enum CustomFirmwareArm64eX1 {
- public struct Result {
+ public struct Result: Sendable {
public let records: [PatchRecord]
public let unvisitedCandidates: Int
public let unvisitedExamples: [Int]
@@ -22,6 +22,122 @@ public enum CustomFirmwareArm64eX1 {
"autia171615", "autib171615",
]
+ /// Top bytes of every word `VPhoneArm64eX1Lowering` lowers or refuses.
+ static let loweredTopBytes = topByteTable([0x44, 0x55, 0x9A, 0x9B, 0xD6, 0xDA, 0xF3])
+
+ /// Top bytes of every word the walk follows or stops at: B, BL, B.cond,
+ /// CBZ/CBNZ/TBZ/TBNZ, BR and its authenticated forms, the RET family,
+ /// BRK, HLT and UDF.
+ static let flowTopBytes = topByteTable([
+ 0x00, 0x14, 0x15, 0x16, 0x17, 0x34, 0x35, 0x36, 0x37, 0x54, 0x55,
+ 0x94, 0x95, 0x96, 0x97, 0xB4, 0xB5, 0xB6, 0xB7, 0xD4, 0xD6, 0xD7,
+ ])
+
+ private static func topByteTable(_ bytes: Set<UInt8>) -> [Bool] {
+ (0 ... 255).map { bytes.contains(UInt8($0)) }
+ }
+
+ /// Encodings whose operands depend on the instruction's address: immediate
+ /// branches, compare-and-branch, ADR/ADRP, literal loads, and the labelled
+ /// PAuth_LR return and authenticate forms (top bytes 0x55 and 0xF3).
+ static func isPCRelative(_ word: UInt32) -> Bool {
+ word & 0x7C00_0000 == 0x1400_0000 || // B, BL
+ word >> 24 == 0x54 || // B.cond, BC.cond
+ word & 0x7C00_0000 == 0x3400_0000 || // CBZ, CBNZ, TBZ, TBNZ
+ word & 0x7E00_0000 == 0x7400_0000 || // CB<cc>
+ word & 0x1F00_0000 == 0x1000_0000 || // ADR, ADRP
+ word & 0x3B00_0000 == 0x1800_0000 || // LDR, LDRSW, PRFM (literal)
+ word >> 24 == 0x55 || word >> 24 == 0xF3
+ }
+
+ /// How a PC-relative decode follows its word to another address: not at
+ /// all, its target operand by the address delta, or by the page delta.
+ enum Move: CaseIterable { case none, address, page }
+
+ /// The PC-relative families whose target the encoding states outright:
+ /// the word with its offset field cleared, and the target it names at
+ /// `address`. Two words of one family decode alike but for that target.
+ static func targetFamily(_ word: UInt32, at address: Int) -> (key: UInt32, target: Int64)? {
+ func signed(_ value: UInt32, bits: Int) -> Int64 {
+ Int64(Int32(bitPattern: value << UInt32(32 - bits)) >> Int32(32 - bits))
+ }
+ let pc = Int64(address)
+ if word & 0x7C00_0000 == 0x1400_0000 { // B, BL
+ return (word & 0xFC00_0000, pc + signed(word & 0x03FF_FFFF, bits: 26) * 4)
+ }
+ if word >> 24 == 0x54 || word & 0x7E00_0000 == 0x3400_0000 || word & 0x3B00_0000 == 0x1800_0000 {
+ // B.cond, BC.cond, CBZ, CBNZ, LDR/LDRSW/PRFM (literal): imm19.
+ return (word & 0xFF00_001F, pc + signed((word >> 5) & 0x7FFFF, bits: 19) * 4)
+ }
+ if word & 0x7E00_0000 == 0x3600_0000 { // TBZ, TBNZ: imm14
+ return (word & 0xFFF8_001F, pc + signed((word >> 5) & 0x3FFF, bits: 14) * 4)
+ }
+ if word & 0x1F00_0000 == 0x1000_0000 { // ADR, ADRP
+ let immediate = signed(((word >> 5) & 0x7FFFF) << 2 | (word >> 29) & 3, bits: 21)
+ return word >> 31 == 0
+ ? (word & 0x9F00_001F, pc + immediate)
+ : (word & 0x9F00_001F, (pc & ~0xFFF) + immediate << 12)
+ }
+ return nil
+ }
+
+ /// `item` as Capstone would decode it at `address` under `move`, or nil
+ /// when its shape is not one a move can rebuild exactly: a last immediate
+ /// operand that ends the operand text, and no flags a rebuild would drop.
+ static func moved(_ item: ARM64Instruction, by move: Move, to address: Int) -> ARM64Instruction? {
+ guard move != .none else {
+ return ARM64Instruction(isDecoded: item.isDecoded, address: UInt64(address), size: item.size,
+ bytes: item.bytes, mnemonic: item.mnemonic, operandString: item.operandString,
+ detail: item.detail, isJump: item.isJump, isCall: item.isCall, isReturn: item.isReturn)
+ }
+ let from = Int64(item.address), to = Int64(address)
+ let delta = move == .page ? (to & ~0xFFF) - (from & ~0xFFF) : to - from
+ return retargeted(item, bytes: item.bytes, to: address, delta: delta)
+ }
+
+ /// `item` at `address` with `bytes`, its target operand shifted by `delta`;
+ /// nil unless the target is a last immediate operand that ends the operand
+ /// text and no flag a rebuild would drop is set.
+ static func retargeted(_ item: ARM64Instruction, bytes: [UInt8], to address: Int, delta: Int64) -> ARM64Instruction? {
+ guard let detail = item.detail, !detail.writeback, let last = detail.operands.last,
+ last.type == .immediate, !last.writesRegister, last.imm >= 0,
+ item.operandString.hasSuffix("0x" + String(last.imm, radix: 16))
+ else { return nil }
+ let (target, overflow) = last.imm.addingReportingOverflow(delta)
+ guard !overflow, target >= 0 else { return nil }
+ let text = item.operandString.dropLast(String(last.imm, radix: 16).count) + String(target, radix: 16)
+ // Capstone's operand is a union: an immediate's register and memory
+ // views alias its low and high words, and the decode copies them all.
+ let low = ARM64Register(rawValue: UInt32(truncatingIfNeeded: target))
+ let high = ARM64Register(rawValue: UInt32(truncatingIfNeeded: target >> 32))
+ let operands = detail.operands.dropLast() + [ARM64Operand(
+ type: .immediate, reg: low, imm: target,
+ mem: ARM64MemoryOperand(base: low, index: high, disp: last.mem.disp), shift: last.shift,
+ )]
+ return ARM64Instruction(isDecoded: item.isDecoded, address: UInt64(address), size: item.size,
+ bytes: bytes, mnemonic: item.mnemonic, operandString: String(text),
+ detail: ARM64InstructionDetail(conditionCode: detail.conditionCode, updatesFlags: detail.updatesFlags,
+ postIndex: detail.postIndex, operands: Array(operands)),
+ isJump: item.isJump, isCall: item.isCall, isReturn: item.isReturn)
+ }
+
+ /// Every field the planner and its callers read, compared exactly.
+ static func sameDecode(_ lhs: ARM64Instruction, _ rhs: ARM64Instruction) -> Bool {
+ guard lhs.isDecoded == rhs.isDecoded, lhs.address == rhs.address, lhs.size == rhs.size,
+ lhs.bytes == rhs.bytes, lhs.mnemonic == rhs.mnemonic, lhs.operandString == rhs.operandString,
+ lhs.isJump == rhs.isJump, lhs.isCall == rhs.isCall, lhs.isReturn == rhs.isReturn
+ else { return false }
+ guard let left = lhs.detail, let right = rhs.detail else { return lhs.detail == nil && rhs.detail == nil }
+ return left.conditionCode == right.conditionCode && left.updatesFlags == right.updatesFlags &&
+ left.postIndex == right.postIndex && left.writeback == right.writeback &&
+ left.operands.count == right.operands.count &&
+ zip(left.operands, right.operands).allSatisfy { a, b in
+ a.type == b.type && a.reg == b.reg && a.imm == b.imm && a.writesRegister == b.writesRegister &&
+ a.mem.base == b.mem.base && a.mem.index == b.mem.index && a.mem.disp == b.mem.disp &&
+ a.shift.type == b.shift.type && a.shift.amount == b.shift.amount
+ }
+ }
+
public static func lower(_ data: inout Data) throws -> Result {
try lower(&data, identifier: FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap)
}
@@ -83,58 +199,55 @@ public enum CustomFirmwareArm64eX1 {
static func planCode(ranges: [(address: Int, data: Data)], seeds: [Int], excluded: [Range<Int>], identifier: String,
readMemory: ((Int, Int) throws -> Data)? = nil,
- authenticatedPointer: ((UInt64, UInt16) throws -> UInt64?)? = nil) throws -> Result {
- let decoder = ARM64Disassembler()
+ authenticatedPointer: ((UInt64, UInt16) throws -> UInt64?)? = nil,
+ decoder words: Decoder = Decoder()) throws -> Result {
+ let decoder = words.capstone
+ func decode(_ word: UInt32, at address: Int) -> ARM64Instruction? { words.decode(word, at: address) }
+ // Unpacked once: a generic load per word crosses PatchKit's resilient
+ // boundary and costs a metadata lookup on every call.
+ let rangeWords: [[UInt32]] = ranges.map { range in
+ range.data.withUnsafeBytes { raw in
+ (0 ..< raw.count / 4).map { UInt32(littleEndian: raw.loadUnaligned(fromByteOffset: $0 * 4, as: UInt32.self)) }
+ }
+ }
var dataRanges = excluded
var candidates: [Int] = [], frameEntries: [Int] = []
// Recover coalesced entries from return-PAC plus an SP frame setup.
- for range in ranges {
- for block in stride(from: 0, to: range.data.count, by: 0x4000) {
- let end = min(range.data.count, block + 0x4004)
- let decoded = decoder.disassemble(range.data.subdata(in: block ..< end), at: UInt64(range.address + block))
- for (index, item) in decoded.enumerated() where item.address < UInt64(range.address + block + 0x4000) {
- let address = Int(item.address)
- guard !excluded.contains(where: { $0.contains(address) }) else { continue }
- if loweredMnemonics.contains(item.mnemonic) { candidates.append(address) }
- if ["pacibsppc", "paciasppc", "pacnbibsppc", "pacnbiasppc", "pacibsp", "paciasp"].contains(item.mnemonic), index + 1 < decoded.count {
- let next = decoded[index + 1], ops = next.detail?.operands ?? []
- let savesFrame = ["stp", "str"].contains(next.mnemonic) && ops.last?.type == .memory && ops.last?.mem.base == .sp
- let allocatesFrame = next.mnemonic == "sub" && ops.count == 3 && ops[0].reg == .sp && ops[1].reg == .sp && ops[2].type == .immediate
- if savesFrame || allocatesFrame { frameEntries.append(address) }
- }
+ for (range, words) in zip(ranges, rangeWords) {
+ for index in 0 ..< words.count {
+ // Every lowered form and PAC prologue has one of these top
+ // bytes; Capstone still decides, but only for words that could
+ // match, which keeps a whole-cache scan affordable.
+ switch words[index] >> 24 {
+ case 0x55, 0x9A, 0x9B, 0xD5, 0xD6, 0xDA, 0xF3: break
+ default: continue
+ }
+ let address = range.address + index * 4
+ guard !excluded.contains(where: { $0.contains(address) }),
+ let item = decode(words[index], at: address)
+ else { continue }
+ if loweredMnemonics.contains(item.mnemonic) { candidates.append(address) }
+ if ["pacibsppc", "paciasppc", "pacnbibsppc", "pacnbiasppc", "pacibsp", "paciasp"].contains(item.mnemonic), index + 1 < words.count,
+ let next = decode(words[index + 1], at: address + 4) {
+ let ops = next.detail?.operands ?? []
+ let savesFrame = ["stp", "str"].contains(next.mnemonic) && ops.last?.type == .memory && ops.last?.mem.base == .sp
+ let allocatesFrame = next.mnemonic == "sub" && ops.count == 3 && ops[0].reg == .sp && ops[1].reg == .sp && ops[2].type == .immediate
+ if savesFrame || allocatesFrame { frameEntries.append(address) }
}
}
}
- var decodedPage: [ARM64Instruction] = [], pageAddress = -1
- var pages: [Int: [ARM64Instruction]] = [:], pageUses: [Int: Int] = [:], tick = 0
+ // SKIPDATA gives every word its own 4-byte entry, so one word decodes
+ // exactly as it would inside its page. Decoding whole pages behind a
+ // small cache thrashed on large cache images, whose traversal jumps
+ // between distant pages.
func decodedInstruction(at address: Int) -> ARM64Instruction? {
- guard !dataRanges.contains(where: { $0.contains(address) }),
- let range = ranges.first(where: { address >= $0.address && address < $0.address + $0.data.count }) else { return nil }
- let relative = address - range.address
- let block = relative / 0x4000 * 0x4000
- if pageAddress != range.address + block {
- pageAddress = range.address + block
- tick += 1
- pageUses[pageAddress] = tick
- if let cached = pages[pageAddress] {
- decodedPage = cached
- } else {
- let end = min(range.data.count, block + 0x4000)
- decodedPage = decoder.disassemble(range.data.subdata(in: block ..< end), at: UInt64(pageAddress))
- if pages.count >= 16, let oldest = pageUses.filter({ $0.key != pageAddress }).min(by: { $0.value < $1.value })?.key {
- pages.removeValue(forKey: oldest)
- pageUses.removeValue(forKey: oldest)
- }
- pages[pageAddress] = decodedPage
- }
- }
- let index = (address - pageAddress) / 4
- guard address & 3 == 0, index < decodedPage.count,
- decodedPage[index].address == UInt64(address) else { return nil }
- return decodedPage[index]
+ guard address & 3 == 0, !dataRanges.contains(where: { $0.contains(address) }),
+ let index = ranges.firstIndex(where: { address >= $0.address && address + 4 <= $0.address + $0.data.count }) else { return nil }
+ return decode(rangeWords[index][(address - ranges[index].address) / 4], at: address)
}
- var scheduled = Set(seeds + frameEntries)
- var pending = scheduled.sorted(by: >), visited = Set<Int>()
+ var scheduled = AddressSet(ranges: ranges.map { ($0.address, $0.data.count) }), visited = scheduled
+ var pending = Set(seeds + frameEntries).sorted(by: >)
+ for entry in pending { _ = scheduled.insert(entry) }
func schedule(_ address: Int) {
if !visited.contains(address), scheduled.insert(address).inserted {
pending.append(address)
@@ -144,7 +257,11 @@ public enum CustomFirmwareArm64eX1 {
while let entry = pending.popLast() {
var offset = entry
while visited.insert(offset).inserted, let instruction = decodedInstruction(at: offset), instruction.isDecoded, instruction.size == 4 {
- if let replacement = try replacement(for: instruction) {
+ // The top byte rules out most words before any mnemonic is
+ // compared: only these can be lowered or refused, or end or
+ // redirect the walk.
+ let top = instruction.bytes[3]
+ if Self.loweredTopBytes[Int(top)], let replacement = try replacement(for: instruction) {
let after = decoder.disassembleOne(replacement, at: instruction.address)
records.append(PatchRecord(patchID: identifier + ".\(offset)", component: "Mach-O", fileOffset: offset,
originalBytes: Data(instruction.bytes), patchedBytes: replacement,
@@ -152,6 +269,10 @@ public enum CustomFirmwareArm64eX1 {
afterDisasm: "\(after?.mnemonic ?? "?") \(after?.operandString ?? "")",
description: "X1 compatibility lowering; PC PAC/CPA checks reduced"))
}
+ guard Self.flowTopBytes[Int(top)] else {
+ offset += 4
+ continue
+ }
let mnemonic = instruction.mnemonic
if mnemonic == "br", let readMemory,
let table = try switchTable(at: offset, instructionAt: decodedInstruction(at:), readMemory: readMemory) {
@@ -539,3 +660,113 @@ public enum CustomFirmwareArm64eX1 {
return (seeds, excluded)
}
}
+
+// MARK: - Address Set
+
+/// A set of instruction addresses: one bit per word inside the planned code
+/// ranges, and a plain set for anything else. A whole-cache traversal inserts
+/// hundreds of millions of addresses, where hashing each one dominated.
+struct AddressSet {
+ private let ranges: [(address: Int, count: Int)]
+ private var bits: [[UInt64]]
+ private var others = Set<Int>()
+
+ init(ranges: [(address: Int, count: Int)]) {
+ self.ranges = ranges
+ bits = ranges.map { [UInt64](repeating: 0, count: ($0.count / 4 + 63) / 64) }
+ }
+
+ private func slot(_ address: Int) -> (range: Int, word: Int, mask: UInt64)? {
+ guard address & 3 == 0,
+ let range = ranges.firstIndex(where: { address >= $0.address && address - $0.address < $0.count / 4 * 4 })
+ else { return nil }
+ let index = (address - ranges[range].address) / 4
+ return (range, index / 64, 1 << UInt64(index % 64))
+ }
+
+ func contains(_ address: Int) -> Bool {
+ guard let slot = slot(address) else { return others.contains(address) }
+ return bits[slot.range][slot.word] & slot.mask != 0
+ }
+
+ @discardableResult
+ mutating func insert(_ address: Int) -> (inserted: Bool, memberAfterInsert: Int) {
+ guard let slot = slot(address) else { return others.insert(address) }
+ let inserted = bits[slot.range][slot.word] & slot.mask == 0
+ bits[slot.range][slot.word] |= slot.mask
+ return (inserted, address)
+ }
+}
+
+// MARK: - Decoder
+
+extension CustomFirmwareArm64eX1 {
+ /// Capstone behind two word-keyed caches, kept for as long as its owner
+ /// plans: one worker reuses it across every image it takes.
+ ///
+ /// Most words decode the same at any address, and a few prologue,
+ /// epilogue and move words make up much of every image. A PC-relative
+ /// word is reused only once Capstone, decoding it at a second address,
+ /// agrees field for field with one of the moves; a word no move reproduces
+ /// always goes back to Capstone. The caps bound memory; the plain cache
+ /// starts over when full, so a long run keeps the current image's words.
+ final class Decoder {
+ let capstone = ARM64Disassembler()
+ private var plain: [UInt32: ARM64Instruction] = [:]
+ private var relative: [UInt32: (item: ARM64Instruction, move: Move?, settled: Bool)] = [:]
+ private var families: [UInt32: (item: ARM64Instruction, target: Int64, settled: Bool, agrees: Bool)] = [:]
+
+ func decode(_ word: UInt32, at address: Int) -> ARM64Instruction? {
+ if let known = plain[word] { return moved(known, by: .none, to: address) }
+ // A family template moves to any word of its family once Capstone,
+ // at a second instance naming another target, agreed with the move.
+ if let family = targetFamily(word, at: address) {
+ let bytes = [UInt8](ARM64.encodeU32(word))
+ if let known = families[family.key], known.settled {
+ if known.agrees, let item = retargeted(known.item, bytes: bytes, to: address,
+ delta: family.target - known.target)
+ {
+ return item
+ }
+ }
+ guard let item = capstone.disassembleOne(ARM64.encodeU32(word), at: UInt64(address)) else { return nil }
+ if let known = families[family.key] {
+ if !known.settled, family.target != known.target {
+ let agrees = retargeted(known.item, bytes: bytes, to: address,
+ delta: family.target - known.target).map { sameDecode($0, item) } ?? false
+ families[family.key] = (known.item, known.target, true, agrees)
+ }
+ } else if families.count < 1 << 19 {
+ families[family.key] = (item, family.target, false, false)
+ }
+ return item
+ }
+ let isRelative = isPCRelative(word)
+ if isRelative, let known = relative[word], known.settled,
+ let move = known.move, let item = moved(known.item, by: move, to: address)
+ {
+ return item
+ }
+ guard let item = capstone.disassembleOne(ARM64.encodeU32(word), at: UInt64(address)) else { return nil }
+ if !isRelative {
+ if plain.count >= 1 << 19 { plain.removeAll(keepingCapacity: true) }
+ plain[word] = item
+ } else if let known = relative[word] {
+ // Only a pair differing in both page and page offset tells the
+ // three moves apart; a move that cannot be rebuilt then counts
+ // as a mismatch, and a single match settles the word.
+ if !known.settled, known.item.address >> 12 != item.address >> 12,
+ known.item.address & 0xFFF != item.address & 0xFFF
+ {
+ let matches = Move.allCases.filter { move in
+ moved(known.item, by: move, to: address).map { sameDecode($0, item) } ?? false
+ }
+ if matches.count <= 1 { relative[word] = (known.item, matches.first, true) }
+ }
+ } else if relative.count < 1 << 19 {
+ relative[word] = (item, nil, false)
+ }
+ return item
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift
index 9a8649d0..68b04256 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift
@@ -43,6 +43,13 @@
// guard-checked pop sequence ending in `retab`, and its shape is verified
// instruction by instruction before the branch is encoded.
//
+// An arm64e.x1 userland (iOS 27.1 on iPhone19,4) is built with FEAT_PAuth_LR:
+// functions open with `pacibsppc` and return with `retabsppc <label>`, whose
+// label names the `pacibsppc` that signed. The plugin is patched in that
+// native form, so a prologue is either signing instruction and an epilogue
+// ends in either return, and a `retabsppc` must name the prologue of the
+// function the patch walked — the epilogue is the function's own.
+//
// The mute-set throw
// ------------------
// Establishing the route also asks the HAL device itself to unmute:
@@ -64,7 +71,8 @@
// the "Unable to set property data." EXCEPTION log a few instructions above
// it; iOS 27's wrapper holds a second, unrelated CAException (the
// deactivated-device throw), and that log window is what tells them apart.
-// The epilogue is the wrapper's single `retab`, walked back to its entry.
+// The epilogue is the wrapper's single `retab` (`retabsppc` on X1), walked
+// back to its entry.
//
// The speaker-protection gate
// ---------------------------
@@ -125,6 +133,42 @@
// branch back to the comparison's fall-through, which reloads everything
// it reads from memory and never re-reads the value the test examined, on
// either supported build.
+//
+// The device-state guard
+// ----------------------
+// With the route quieted end to end, one ordering fault is left, and it
+// belongs to the arm64e.x1 build alone. Publishing the route wakes
+// VirtualAudio_Device's update, which asks DeviceStateManager for its
+// singleton twice — each ask behind its own capability gate — and pushes
+// the route's state into the manager. The singleton is published only at
+// the end of "Deferred Initialization", which first waits up to 8 s for a
+// haptic actuator port a VM does not have; asked earlier, TheInstance()
+// logs "TheInstance() called before SetInstance()" and returns null, and
+// the update dereferences that null — the audiomxd crash loop on an
+// iPhone Duo guest, ~0.6 s after every launch.
+//
+// The patch stands the two device-state updates down: each gate's
+// `cbz w0, <skip>` — the branch that already skips the update when the
+// gate's check answers false — becomes an unconditional `b` to the same
+// target. Nothing else in either block changes; the gate-check call still
+// runs, its answer is simply no longer read, and the device-state update
+// the manager would have received before it exists never happens — the
+// same nothing the gates already do when their check fails. After
+// deferred initialization completes, TheInstance answers a real singleton
+// again and the manager takes every later update.
+//
+// Anchoring: the singleton is found from its own diagnostic — the
+// "TheInstance() called before SetInstance()" log format, referenced once
+// in __text; the prologue above that reference is TheInstance's entry.
+// Every direct `bl` to that entry is then filtered to the gated shape
+// both device-state updates share: a gate-check call, its `cbz w0`
+// skipping forward past the whole update, the singleton's return moved
+// aside (`mov xN, x0`), and the unchecked dereference of that return
+// (`ldr xM, [x0]`) — the instruction that faults. Exactly two callers
+// carry the shape; both are rewritten. The plugin is touched only where
+// iOS 27.1's arm64e.x1 build carries it: a header check (cputype arm64,
+// cpusubtype 12 — 26.x and 27.0 are cpusubtype 2) reports "nothing to do"
+// on every other build, so their bytes never move.
import Foundation
import VPhonePatchKit
@@ -212,6 +256,14 @@ public enum CustomFirmwareVirtualAudio {
/// Record identity for the volume-gate patch.
public static let volumeGatePatchID = "system-virtualaudio-cfw-volume_mode_precondition"
+ /// The singleton's own diagnostic, and the anchor for the device-state
+ /// guard: the log DeviceStateManager's accessor prints when it is asked
+ /// for an instance nobody published yet.
+ public static let deviceStateInstanceMissing = "TheInstance() called before SetInstance()"
+
+ /// Record identity for the device-state guard.
+ public static let deviceStateGuardPatchID = "system-virtualaudio-cfw-device_state_guard"
+
/// Where progress goes when the caller does not say.
public static let stdoutLog: @Sendable (String) -> Void = { print($0) }
@@ -224,6 +276,9 @@ public enum CustomFirmwareVirtualAudio {
case wouldPatch
/// The branch was written and its page re-attested.
case patched
+ /// The plugin is not an arm64e.x1 image: the device-state guard
+ /// applies to nothing, and nothing was written.
+ case notArm64EX1
}
/// The resolved pair the patch writes between.
@@ -298,6 +353,28 @@ public enum CustomFirmwareVirtualAudio {
public let slotRehashes: [CustomFirmwareSlotRehash]
}
+ /// One gated device-state update: the gate branch the patch rewrites
+ /// and the singleton call it stands over.
+ public struct DeviceStateGuardAnchor: Sendable, Equatable {
+ /// The `cbz w0` gate — the instruction the patch rewrites.
+ public let gateFileOffset: Int
+ public let gateVMA: UInt64
+ /// The `bl TheInstance` the gate stands over.
+ public let callFileOffset: Int
+ public let callVMA: UInt64
+ /// Where the gate skips to — the rewrite's own target.
+ public let skipTargetVMA: UInt64
+ }
+
+ public struct DeviceStateGuardReport: Sendable {
+ public let outcome: Outcome
+ /// TheInstance's entry, resolved from its own diagnostic.
+ public let theInstanceVMA: UInt64
+ public let sites: [DeviceStateGuardAnchor]
+ public let records: [PatchRecord]
+ public let slotRehashes: [CustomFirmwareSlotRehash]
+ }
+
// MARK: - Patching
/// Patch the VirtualAudio Mach-O at `url` in place.
@@ -806,6 +883,148 @@ public enum CustomFirmwareVirtualAudio {
)
}
+ // MARK: - Device-state guard patching
+
+ /// Patch the VirtualAudio Mach-O at `url` in place, standing down the
+ /// two gated device-state updates that dereference the
+ /// DeviceStateManager singleton before deferred initialization
+ /// publishes it.
+ ///
+ /// Each gate's `cbz w0, <skip>` — the branch that already skips its
+ /// update when the gate's check answers false — becomes an
+ /// unconditional `b` to the same target. The gate-check call keeps
+ /// running; its answer is no longer read. Applies only to an arm64e.x1
+ /// (cpusubtype 12) plugin: every other build reports
+ /// ``Outcome/notArm64EX1`` and keeps its bytes.
+ ///
+ /// Idempotent: a second run recognises its own branches, reports
+ /// ``Outcome/alreadyPatched`` and leaves the file byte-identical.
+ ///
+ /// - Parameters:
+ /// - url: the `VirtualAudio` plugin binary.
+ /// - reattest: recompute the code-directory slot hash of the touched
+ /// page. `false` when the caller re-signs the whole binary right
+ /// after, which is what both install paths do.
+ /// - dryRun: locate and report, write nothing.
+ @discardableResult
+ public static func patchDeviceStateGuard(
+ fileAt url: URL,
+ reattest: Bool = true,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = stdoutLog,
+ ) throws -> DeviceStateGuardReport {
+ guard FileManager.default.fileExists(atPath: url.path) else {
+ throw PatcherError.fileNotFound(url.path)
+ }
+ var data = try Data(contentsOfFileToRewrite: url)
+ let before = data
+ let report = try patchDeviceStateGuard(&data, reattest: reattest, dryRun: dryRun, log: log)
+ if data != before {
+ try data.write(to: url)
+ }
+ return report
+ }
+
+ /// In-memory form of ``patchDeviceStateGuard(fileAt:reattest:dryRun:log:)``.
+ @discardableResult
+ public static func patchDeviceStateGuard(
+ _ data: inout Data,
+ reattest: Bool = true,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = stdoutLog,
+ ) throws -> DeviceStateGuardReport {
+ if data.startIndex != 0 {
+ data = Data(data)
+ }
+
+ switch arm64Subtype(of: data) {
+ case .x1:
+ break
+ case .other:
+ log?(" [·] VirtualAudio: not an arm64e.x1 plugin — the device-state guard has nothing to do")
+ return DeviceStateGuardReport(
+ outcome: .notArm64EX1,
+ theInstanceVMA: 0,
+ sites: [],
+ records: [],
+ slotRehashes: [],
+ )
+ case .notArm64:
+ break // not a thin arm64 image; the anchor below refuses it
+ }
+
+ let located = try locateDeviceStateGuard(in: data)
+ log?(" [.] TheInstance 0x\(hex(located.theInstanceVMA)); \(located.sites.count) gated device-state update(s)")
+ let anchors = located.sites.map { site in
+ DeviceStateGuardAnchor(
+ gateFileOffset: site.gate,
+ gateVMA: located.vma(site.gate),
+ callFileOffset: site.call,
+ callVMA: located.vma(site.call),
+ skipTargetVMA: site.target,
+ )
+ }
+
+ var records: [PatchRecord] = []
+ var written: [Int] = []
+ var alreadyPatched = 0
+ for site in located.sites {
+ let gate = site.gate
+ let gateVMA = located.vma(gate)
+ let gateInstruction = located.disasm.disassembleOne(in: data, at: gate, address: gateVMA)
+ if site.alreadySkips {
+ alreadyPatched += 1
+ log?(" [=] 0x\(hex(gateVMA)): the gate already skips the device-state update")
+ continue
+ }
+ guard let branch = ARM64Encoder.encodeB(from: Int(gateVMA), to: Int(site.target)) else {
+ throw PatcherError.patchSiteNotFound(
+ "\(component): the skip at 0x\(hex(site.target)) is out of branch range "
+ + "of the gate at 0x\(hex(gateVMA))",
+ )
+ }
+ let original = Data(data[gate ..< gate + 4])
+ if dryRun {
+ log?(" [.] dry-run — would branch 0x\(hex(gateVMA)) -> 0x\(hex(site.target))")
+ continue
+ }
+ data.replaceSubrange(gate ..< gate + 4, with: branch)
+ written.append(gate)
+ records.append(PatchRecord(
+ patchID: deviceStateGuardPatchID,
+ component: component,
+ fileOffset: gate,
+ virtualAddress: gateVMA,
+ originalBytes: original,
+ patchedBytes: branch,
+ beforeDisasm: gateInstruction?.description ?? "",
+ afterDisasm: branch.map { String(format: "%02x", $0) }.joined(separator: " "),
+ description: "device-state gate -> unconditional skip",
+ ))
+ log?(" [+] 0x\(hex(gateVMA)): \(gateInstruction?.description ?? "") -> b 0x\(hex(site.target))")
+ }
+
+ if records.isEmpty, !dryRun {
+ log?(" [=] all \(alreadyPatched) gate(s) already skip the device-state update")
+ }
+
+ var rehashes: [CustomFirmwareSlotRehash] = []
+ if reattest, !written.isEmpty {
+ rehashes = try CustomFirmwareMachOCodeSignature.reattest(&data, modifiedOffsets: written)
+ if !rehashes.isEmpty {
+ log?(" [+] re-attested \(rehashes.count) stale slot(s)")
+ }
+ }
+ let outcome: Outcome = dryRun ? .wouldPatch : (records.isEmpty ? .alreadyPatched : .patched)
+ return DeviceStateGuardReport(
+ outcome: outcome,
+ theInstanceVMA: located.theInstanceVMA,
+ sites: anchors,
+ records: records,
+ slotRehashes: rehashes,
+ )
+ }
+
// MARK: - Anchoring
/// Resolve the throw block and the epilogue, or say why not.
@@ -876,7 +1095,9 @@ public enum CustomFirmwareVirtualAudio {
"\(component): no terminator branch after the exception constructor",
)
}
- let epilogueOffset = try locateEpilogue(in: data, disasm: disasm, after: terminator, textEnd: walkerEnd)
+ let epilogueOffset = try locateEpilogue(
+ in: data, disasm: disasm, after: terminator, prologue: walkerStart, textEnd: walkerEnd,
+ )
// Every throw block in the walker: a `mov w0, #<size>` whose next
// instruction calls the exception allocator, followed within a short
@@ -1030,24 +1251,32 @@ public enum CustomFirmwareVirtualAudio {
)
}
- // The epilogue: the wrapper's only `retab`, walked back to its entry.
- // The mute-set throw sits *below* the epilogue, so the forward search
- // the walker patch uses cannot apply — the retab must be enumerated
- // within the function's own bounds.
- var retabs: [Int] = []
+ // The epilogue: the wrapper's only authenticated return (`retab`, or
+ // `retabsppc` on an arm64e.x1 build), walked back to its entry. The
+ // mute-set throw sits *below* the epilogue, so the forward search the
+ // walker patch uses cannot apply — the return must be enumerated
+ // within the function's own bounds, and a `retabsppc` must name the
+ // wrapper's own prologue.
+ var returns: [Int] = []
offset = functionStart
while offset + 4 <= functionEnd {
- if let insn = disasm.disassembleOne(in: data, at: offset), insn.mnemonic == "retab" {
- retabs.append(offset)
+ if let insn = disasm.disassembleOne(in: data, at: offset), isAuthenticatedReturn(insn) {
+ guard returnCloses(insn, at: offset, prologue: functionStart) else {
+ throw PatcherError.patchSiteNotFound(
+ "\(component): `\(insn.mnemonic)` at 0x\(hex(text.address + UInt64(offset - textStart))) "
+ + "in the mute-set wrapper does not close the wrapper's own prologue",
+ )
+ }
+ returns.append(offset)
}
offset += 4
}
- guard retabs.count == 1, let retab = retabs.first else {
+ guard returns.count == 1, let ret = returns.first else {
throw PatcherError.patchSiteNotFound(
- "\(component): expected exactly 1 `retab` in the mute-set wrapper, found \(retabs.count)",
+ "\(component): expected exactly 1 `retab`/`retabsppc` in the mute-set wrapper, found \(returns.count)",
)
}
- let epilogueOffset = try epilogueEntry(in: data, disasm: disasm, retab: retab)
+ let epilogueOffset = try epilogueEntry(in: data, disasm: disasm, retab: ret)
return MuteSetPlan(
disasm: disasm,
@@ -1272,7 +1501,7 @@ public enum CustomFirmwareVirtualAudio {
// the head safe — nothing else arrives at the block expecting the
// os_log the head used to open.
guard let above = handler.disasm.disassembleOne(in: data, at: gate.head - 4),
- above.mnemonic == "brk" || ["ret", "retab"].contains(above.mnemonic)
+ above.mnemonic == "brk" || returnMnemonics.contains(above.mnemonic)
|| (above.isJump && !above.isCall && above.detail?.conditionCode == nil)
else {
throw PatcherError.invalidFormat(
@@ -1421,7 +1650,7 @@ public enum CustomFirmwareVirtualAudio {
// makes rewriting the head safe — nothing else arrives at the block
// expecting the os_log the head used to open.
guard let above = handler.disasm.disassembleOne(in: data, at: gate.head - 4),
- above.mnemonic == "brk" || ["ret", "retab"].contains(above.mnemonic)
+ above.mnemonic == "brk" || returnMnemonics.contains(above.mnemonic)
|| (above.isJump && !above.isCall && above.detail?.conditionCode == nil)
else {
throw PatcherError.invalidFormat(
@@ -1475,6 +1704,199 @@ public enum CustomFirmwareVirtualAudio {
return false
}
+ // MARK: - Device-state guard anchoring
+
+ /// One gated device-state update, in file-offset terms.
+ struct DeviceStateGuardSite: Sendable {
+ /// The gate branch — the instruction the patch rewrites.
+ let gate: Int
+ /// The `bl TheInstance` the gate stands over.
+ let call: Int
+ /// Where the gate skips to — the rewrite's own target.
+ let target: UInt64
+ /// The gate already skips unconditionally: this patch's own earlier
+ /// write, recognised rather than repeated.
+ let alreadySkips: Bool
+ }
+
+ /// Everything the device-state guard needs: TheInstance's own entry and
+ /// the gated callers that dereference its answer.
+ struct DeviceStateGuardPlan: Sendable {
+ let disasm: ARM64Disassembler
+ let textStart: Int
+ let textAddress: UInt64
+ let theInstanceOffset: Int
+ let sites: [DeviceStateGuardSite]
+
+ var theInstanceVMA: UInt64 {
+ vma(theInstanceOffset)
+ }
+
+ func vma(_ offset: Int) -> UInt64 {
+ textAddress + UInt64(offset - textStart)
+ }
+ }
+
+ /// How many direct callers of TheInstance must carry the gated shape —
+ /// one per device-state update VirtualAudio_Device pushes at the
+ /// manager. A build with a different count is refused, not half-patched.
+ private static let deviceStateGuardSiteCount = 2
+
+ /// Resolve TheInstance and its gated device-state callers, or say why
+ /// not. The singleton is found from its own diagnostic — the log it
+ /// prints when asked for an instance nobody published — and the callers
+ /// from the shape every device-state update shares around its `bl`.
+ static func locateDeviceStateGuard(in data: Data) throws -> DeviceStateGuardPlan {
+ let sections = MachOParser.parseSections(from: data)
+ guard let text = sections["__TEXT,__text"] else {
+ throw PatcherError.invalidFormat("\(component): no __TEXT,__text section")
+ }
+ let textStart = Int(text.fileOffset)
+ let textEnd = textStart + Int(text.size)
+ let disasm = ARM64Disassembler()
+ func vma(_ offset: Int) -> UInt64 {
+ text.address + UInt64(offset - textStart)
+ }
+
+ // TheInstance, from its own diagnostic: the null-answer log is
+ // referenced exactly once in __text, by the singleton's accessor.
+ let anchors = cStringVMAs(containing: deviceStateInstanceMissing, in: data, sections: sections)
+ guard !anchors.isEmpty else {
+ throw PatcherError.patchSiteNotFound(
+ "\(component): the string \"\(deviceStateInstanceMissing)\" is nowhere in the binary's sections",
+ )
+ }
+ let references = adrpAddReferences(
+ to: 0,
+ formingAnyOf: anchors,
+ in: data,
+ textStart: textStart,
+ textEnd: textEnd,
+ )
+ guard references.count == 1 else {
+ throw PatcherError.patchSiteNotFound(
+ "\(component): expected exactly 1 reference to \"\(deviceStateInstanceMissing)\", "
+ + "found \(references.count)",
+ )
+ }
+ guard let theInstance = nearestPrologue(
+ in: data, disasm: disasm, below: references[0].adrp, floor: textStart,
+ ) else {
+ throw PatcherError.patchSiteNotFound(
+ "\(component): no function prologue above the \"\(deviceStateInstanceMissing)\" reference",
+ )
+ }
+
+ // Every direct caller, kept where the gated device-state shape
+ // holds around the call.
+ var sites: [DeviceStateGuardSite] = []
+ var offset = textStart
+ while offset + 4 <= textEnd {
+ defer { offset += 4 }
+ guard let insn = disasm.disassembleOne(in: data, at: offset), insn.isCall,
+ let word = wordAt(data, offset),
+ let target = ARM64Encoder.decodeBranchTarget(insn: word, pc: vma(offset)),
+ target == vma(theInstance)
+ else { continue }
+ if let site = gatedDeviceStateSite(in: data, disasm: disasm, call: offset, vma: vma) {
+ sites.append(site)
+ }
+ }
+ guard sites.count == deviceStateGuardSiteCount else {
+ throw PatcherError.patchSiteNotFound(
+ "\(component): expected exactly \(deviceStateGuardSiteCount) gated device-state "
+ + "updates around TheInstance at 0x\(hex(vma(theInstance))), found \(sites.count)",
+ )
+ }
+
+ return DeviceStateGuardPlan(
+ disasm: disasm,
+ textStart: textStart,
+ textAddress: text.address,
+ theInstanceOffset: theInstance,
+ sites: sites.sorted { $0.gate < $1.gate },
+ )
+ }
+
+ /// Whether a direct `bl` to TheInstance sits in the gated device-state
+ /// shape: a gate-check call, its `cbz w0` skipping forward past the
+ /// whole update (or the unconditional branch this patch wrote over it),
+ /// the singleton's return moved aside, and that return dereferenced
+ /// unchecked — the read that faults before SetInstance runs. The
+ /// singleton's other callers either test its answer or live behind the
+ /// haptic attenuation delegate's own capability flag, and match nothing
+ /// here.
+ static func gatedDeviceStateSite(
+ in data: Data,
+ disasm: ARM64Disassembler,
+ call: Int,
+ vma: (Int) -> UInt64,
+ ) -> DeviceStateGuardSite? {
+ guard call >= 8 else { return nil }
+
+ // The singleton's answer, moved aside and then read unchecked:
+ // `mov xN, x0` directly above `ldr xM, [x0]`.
+ guard let saved = disasm.disassembleOne(in: data, at: call + 4),
+ saved.mnemonic == "mov",
+ let savedOps = saved.detail?.operands, savedOps.count == 2,
+ savedOps[0].type == .register, savedOps[1].type == .register,
+ savedOps[1].reg == ARM64Register.x(0),
+ let deref = disasm.disassembleOne(in: data, at: call + 8),
+ deref.mnemonic == "ldr",
+ let derefOps = deref.detail?.operands, derefOps.count == 2,
+ derefOps[0].type == .register,
+ derefOps[1].type == .memory, derefOps[1].mem.base == ARM64Register.x(0)
+ else { return nil }
+
+ // The gate: a call whose answer picks, then the branch that skips
+ // the update when the answer is false.
+ guard disasm.disassembleOne(in: data, at: call - 8)?.isCall == true else { return nil }
+ let gate = call - 4
+ guard let gateInsn = disasm.disassembleOne(in: data, at: gate),
+ let gateWord = wordAt(data, gate)
+ else { return nil }
+ var alreadySkips = false
+ let target: UInt64?
+ if gateInsn.mnemonic == "cbz",
+ let operands = gateInsn.detail?.operands, operands.count == 2,
+ operands[0].type == .register, operands[0].reg == ARM64Register.w(0)
+ {
+ target = decodeConditionalBranchTarget(insn: gateWord, pc: vma(gate))
+ } else if gateInsn.isJump, !gateInsn.isCall, gateInsn.detail?.conditionCode == nil {
+ // An unconditional skip is this patch's own earlier write. Some
+ // other branch of exactly that shape is indistinguishable from
+ // it, and for either the safe answer is to leave the word alone.
+ alreadySkips = true
+ target = ARM64Encoder.decodeBranchTarget(insn: gateWord, pc: vma(gate))
+ } else {
+ return nil
+ }
+ // The skip must clear the dereference: the branch and its target
+ // bracket the whole device-state update the patch stands down.
+ guard let target, target > vma(call + 8) else { return nil }
+ return DeviceStateGuardSite(gate: gate, call: call, target: target, alreadySkips: alreadySkips)
+ }
+
+ /// The arm64 ABI a thin plugin is built for: arm64e.x1 (the X1
+ /// extension, iOS 27.1's iPhone19,4 userland), any other arm64 subtype
+ /// (plain arm64e covers 26.x and 27.0), or not an arm64 image at all —
+ /// in which case the caller's own anchoring refuses the file. The
+ /// subtype is masked the way the X1 bootstrap patcher masks fat slices:
+ /// the LIB64 bit is not part of the ABI number.
+ enum PluginArm64Subtype {
+ case x1
+ case other
+ case notArm64
+ }
+
+ static func arm64Subtype(of data: Data) -> PluginArm64Subtype {
+ guard let magic = wordAt(data, 0), magic == 0xFEED_FACF,
+ let cpuType = wordAt(data, 4), cpuType == 0x0100_000C,
+ let cpuSubtype = wordAt(data, 8)
+ else { return .notArm64 }
+ return cpuSubtype & 0x00FF_FFFF == 12 ? .x1 : .other
+ }
+
/// The target of a jump word, whichever immediate family encodes it:
/// `ARM64Encoder.decodeBranchTarget` reads `b`/`bl`, this adds nothing
/// for them and defers to ``decodeConditionalBranchTarget`` for the
@@ -1720,11 +2142,76 @@ public enum CustomFirmwareVirtualAudio {
return UInt32(bytes[0]) | UInt32(bytes[1]) << 8 | UInt32(bytes[2]) << 16 | UInt32(bytes[3]) << 24
}
- /// The nearest function prologue (`pacibsp`) at or before `below`.
- private static func nearestPrologue(in data: Data, disasm: ARM64Disassembler, below: Int, floor: Int) -> Int? {
+ // MARK: - Frame signing
+
+ /// The instructions that sign LR with the B key against SP as a function
+ /// opens. arm64e builds use `pacibsp`; an arm64e.x1 userland (iOS 27.1's
+ /// iPhone19,4) is built with FEAT_PAuth_LR and opens every function with
+ /// `pacibsppc`, which adds the signing instruction's own address to the
+ /// modifier. VirtualAudio is patched before any X1 lowering, so it is
+ /// read in its native form.
+ static let prologueMnemonics: Set<String> = ["pacibsp", "pacibsppc", "pacnbibsppc"]
+
+ /// The returns that authenticate an LR signed by one of
+ /// `prologueMnemonics`: `retab`, or its PAuth_LR forms — `retabsppc
+ /// <label>`, whose label is the `pacibsppc` that signed, and the register
+ /// form, which Capstone also names `retabsppc` (`retabsppcr` is LLVM's
+ /// name, kept for a decoder that uses it). A plain `ret`, a `retaa*` or
+ /// an `autib*` + `ret` pair closes something else, and is not an
+ /// epilogue these patches branch to.
+ static let authenticatedReturnMnemonics: Set<String> = ["retab", "retabsppc", "retabsppcr"]
+
+ /// Every return, of either key and either PAuth form: an instruction
+ /// that never falls through to the one after it.
+ static let returnMnemonics: Set<String> = [
+ "ret", "retaa", "retab", "retaasppc", "retabsppc", "retaasppcr", "retabsppcr",
+ ]
+
+ static func isPrologue(_ insn: ARM64Instruction?) -> Bool {
+ guard let insn else { return false }
+ return prologueMnemonics.contains(insn.mnemonic)
+ }
+
+ static func isAuthenticatedReturn(_ insn: ARM64Instruction?) -> Bool {
+ guard let insn else { return false }
+ return authenticatedReturnMnemonics.contains(insn.mnemonic)
+ }
+
+ /// Whether the return at `offset` closes the function whose prologue is
+ /// at `prologue`. The label form of `retabsppc` names its signing
+ /// instruction, and it must be that prologue — a return that
+ /// authenticates against another frame is refused. `retab` and the
+ /// register form (`retabsppc xN`) carry no label and are taken as they
+ /// are, bounded by the function the caller already walked.
+ static func returnCloses(_ insn: ARM64Instruction, at offset: Int, prologue: Int) -> Bool {
+ guard insn.mnemonic == "retabsppc",
+ insn.detail?.operands.first?.type != .register
+ else { return true }
+ return retabsppcLabel(insn, at: offset) == prologue
+ }
+
+ /// Where the label form of `retabsppc` at `offset` points: the
+ /// `pacibsppc` whose address entered the LR's signature. The label is
+ /// `imm16` words *back* from the return (bits 20-5, unsigned), which
+ /// Capstone decodes as `#0` whatever the field holds — its PAuth_LR
+ /// support stops at the mnemonic — so the field is read off the word
+ /// Capstone already identified. Analysis only: this assembles nothing.
+ static func retabsppcLabel(_ insn: ARM64Instruction, at offset: Int) -> Int? {
+ guard insn.mnemonic == "retabsppc", insn.bytes.count == 4 else { return nil }
+ let word = UInt32(insn.bytes[0]) | UInt32(insn.bytes[1]) << 8
+ | UInt32(insn.bytes[2]) << 16 | UInt32(insn.bytes[3]) << 24
+ // RETABSPPC <label>: 0101_0101_0010_0000 | imm16 << 5 | 11111 — the
+ // B-key form (bit 21) of the PC-relative return; anything else is
+ // the register form or not this instruction.
+ guard word & 0xFFE0_001F == 0x5520_001F else { return nil }
+ return offset - Int((word >> 5) & 0xFFFF) * 4
+ }
+
+ /// The nearest function prologue at or before `below`.
+ static func nearestPrologue(in data: Data, disasm: ARM64Disassembler, below: Int, floor: Int) -> Int? {
var offset = min(below, floor + ((below - floor) & ~3))
while offset >= floor {
- if let insn = disasm.disassembleOne(in: data, at: offset), insn.mnemonic == "pacibsp" {
+ if isPrologue(disasm.disassembleOne(in: data, at: offset)) {
return offset
}
offset -= 4
@@ -1733,10 +2220,10 @@ public enum CustomFirmwareVirtualAudio {
}
/// The nearest function prologue at or after `atOrAfter`.
- private static func nearestPrologue(in data: Data, disasm: ARM64Disassembler, atOrAfter: Int, ceiling: Int) -> Int? {
+ static func nearestPrologue(in data: Data, disasm: ARM64Disassembler, atOrAfter: Int, ceiling: Int) -> Int? {
var offset = atOrAfter
while offset + 4 <= ceiling {
- if let insn = disasm.disassembleOne(in: data, at: offset), insn.mnemonic == "pacibsp" {
+ if isPrologue(disasm.disassembleOne(in: data, at: offset)) {
return offset
}
offset += 4
@@ -1931,39 +2418,47 @@ public enum CustomFirmwareVirtualAudio {
/// The function epilogue's entry, found after the throw: the stack-guard
/// load when the function is built with the protector (iOS 26), or the
/// first frame restore when it is not (iOS 27).
- private static func locateEpilogue(
+ static func locateEpilogue(
in data: Data,
disasm: ARM64Disassembler,
after offset: Int,
+ prologue: Int,
textEnd: Int,
) throws -> Int {
- // The first `retab` after the throw ends the epilogue.
- var retabOffset: Int?
+ // The first authenticated return after the throw ends the epilogue —
+ // `retab`, or `retabsppc` on an arm64e.x1 build — and it must be the
+ // function's own: a `retabsppc` names the prologue that signed.
+ var returnOffset: Int?
var cursor = offset + 4
while cursor + 4 <= textEnd {
defer { cursor += 4 }
- if let insn = disasm.disassembleOne(in: data, at: cursor),
- insn.mnemonic == "retab"
- {
- retabOffset = cursor
+ if let insn = disasm.disassembleOne(in: data, at: cursor), isAuthenticatedReturn(insn) {
+ guard returnCloses(insn, at: cursor, prologue: prologue) else {
+ throw PatcherError.patchSiteNotFound(
+ "\(component): the first return after the throw at 0x\(hex(UInt64(offset))), "
+ + "`\(insn.mnemonic)` at 0x\(hex(UInt64(cursor))), does not close the function "
+ + "at 0x\(hex(UInt64(prologue)))",
+ )
+ }
+ returnOffset = cursor
break
}
}
- guard let retab = retabOffset else {
+ guard let ret = returnOffset else {
throw PatcherError.patchSiteNotFound(
- "\(component): no `retab` after the throw at 0x\(hex(UInt64(offset)))",
+ "\(component): no `retab` or `retabsppc` after the throw at 0x\(hex(UInt64(offset)))",
)
}
- return try epilogueEntry(in: data, disasm: disasm, retab: retab)
+ return try epilogueEntry(in: data, disasm: disasm, retab: ret)
}
- /// The entry of the epilogue a known `retab` closes: the stack-guard load
- /// when the function is built with the protector, or the first frame
- /// restore when it is not. Shared by both VirtualAudio patches — the
- /// walker patch reaches the retab forwards from its throw, the mute-set
- /// patch enumerates the wrapper's own retab because its throw sits below
- /// the epilogue.
- private static func epilogueEntry(
+ /// The entry of the epilogue a known authenticated return (`retab` or
+ /// `retabsppc`) closes: the stack-guard load when the function is built
+ /// with the protector, or the first frame restore when it is not. Shared
+ /// by both VirtualAudio patches — the walker patch reaches the return
+ /// forwards from its throw, the mute-set patch enumerates the wrapper's
+ /// own return because its throw sits below the epilogue.
+ static func epilogueEntry(
in data: Data,
disasm: ARM64Disassembler,
retab: Int,
@@ -1980,7 +2475,7 @@ public enum CustomFirmwareVirtualAudio {
addOps[0].reg == addOps[1].reg
else {
throw PatcherError.invalidFormat(
- "\(component): no `add sp` directly before the epilogue's `retab`",
+ "\(component): no `add sp` directly before the epilogue's return",
)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
index c3e36562..9c510cc5 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
@@ -108,7 +108,7 @@ public final class DyldSharedCacheChunkSet {
private let architecture: String
- /// Guards the three pieces of mutable state below.
+ /// Guards the mutable state below.
private let stateLock = NSLock()
private var writeLog: [DyldSharedCacheWriteSpan] = []
private var loadedLocalSymbols: DyldSharedCacheLocalSymbolTable?
@@ -119,6 +119,10 @@ public final class DyldSharedCacheChunkSet {
/// default and what every read-only or throwaway use of this type wants.
private var undoCaptureLog: DyldSharedCacheUndoLog?
+ /// Chunk files mapped once, for a read-only set opened with `mappedReads`.
+ /// Nil keeps the default: every read opens, seeks and closes the file.
+ private var mappedChunks: [URL: Data]?
+
// MARK: - Construction
/// Open the cache under `directory`.
@@ -128,7 +132,11 @@ public final class DyldSharedCacheChunkSet {
/// - architecture: explicit suffix, or nil to discover the cache.
/// - captureUndo: start capturing the original bytes of every write into
/// an undo log, retrievable with ``takeUndoLog()``. Off by default.
- public init(directory: URL, architecture: String? = nil, captureUndo: Bool = false) throws {
+ /// - mappedReads: serve reads from chunk files mapped once, for a set that
+ /// only reads, such as a planner's; its reads do not see later writes
+ /// made through another set. Off by default.
+ public init(directory: URL, architecture: String? = nil, captureUndo: Bool = false, mappedReads: Bool = false) throws {
+ mappedChunks = mappedReads ? [:] : nil
self.directory = directory
let architecture = String(Self.mainCacheURL(in: directory, architecture: architecture).lastPathComponent
.dropFirst("dyld_shared_cache_".count))
@@ -272,7 +280,7 @@ public final class DyldSharedCacheChunkSet {
public func bytesAtVMA(_ vma: UInt64, length: Int) throws -> Data {
guard length > 0 else { return Data() }
let (chunkURL, range) = try fileRange(of: DyldSharedCacheWriteSpan(vma: vma, length: length))
- let data = try Self.read(url: chunkURL, offset: UInt64(range.lowerBound), length: length)
+ let data = try readBytes(url: chunkURL, offset: UInt64(range.lowerBound), length: length)
guard data.count == length else {
throw DyldSharedCacheError.shortRead(vma: vma, wanted: length, got: data.count)
}
@@ -298,7 +306,7 @@ public final class DyldSharedCacheChunkSet {
} else {
throw DyldSharedCacheError.addressSpanCrossesChunk(vma: vma, length: length)
}
- return try Self.read(url: run.chunkURL, offset: run.fileOffset, length: wanted)
+ return try readBytes(url: run.chunkURL, offset: run.fileOffset, length: wanted)
}
// MARK: - Writing
@@ -587,6 +595,23 @@ public final class DyldSharedCacheChunkSet {
}
}
+ /// `read(url:offset:length:)`, or a copy out of the chunk mapped once when
+ /// this set was opened with `mappedReads`.
+ private func readBytes(url: URL, offset: UInt64, length: Int) throws -> Data {
+ guard length > 0 else { return Data() }
+ let mapped: Data? = try stateLock.withLock {
+ guard mappedChunks != nil else { return nil }
+ if let file = mappedChunks?[url] { return file }
+ let file = try Data(contentsOf: url, options: .alwaysMapped)
+ mappedChunks?[url] = file
+ return file
+ }
+ guard let file = mapped else { return try Self.read(url: url, offset: offset, length: length) }
+ let lower = file.startIndex + Int(clamping: offset)
+ guard lower < file.endIndex else { return Data() }
+ return Data(file[lower ..< min(file.endIndex, lower + length)])
+ }
+
/// A bounded read: a seek and a copy of `length` bytes.
///
/// Right for the small reads — a load command, a page, a run of a few
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheArm64eX1BootstrapPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheArm64eX1BootstrapPatcher.swift
index 83396bb2..414514c2 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheArm64eX1BootstrapPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheArm64eX1BootstrapPatcher.swift
@@ -1,14 +1,22 @@
import CryptoKit
import Foundation
import MachOKit
+import Synchronization
import VPhonePatchKit
public enum DyldSharedCacheArm64eX1BootstrapPatcher {
- struct Write {
+ struct Write: Sendable {
let address: UInt64
let word: UInt32
}
+ /// One image's plan, reduced to its writes: a full cache holds tens of
+ /// millions of rewrites, too many to keep as patch records.
+ struct ImagePlan: Sendable {
+ let writes: [Write]
+ let unvisitedCandidates: Int
+ }
+
/// Cold-boot evidence for this closure is recorded in Research/0_binary_patch_comparison.md.
static let bootstrapImages: Set<String> = [
"/usr/lib/libSystem.B.dylib",
@@ -57,13 +65,63 @@ public enum DyldSharedCacheArm64eX1BootstrapPatcher {
captureUndo: Bool = false,
onUndo: (DyldSharedCacheUndoLog) -> Void = { _ in },
log: @escaping (String) -> Void = { print($0) },
+ ) throws {
+ try lower(
+ directory: directory, dryRun: dryRun, captureUndo: captureUndo, onUndo: onUndo, log: log,
+ patchID: FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap, label: "X1 bootstrap cache",
+ ) { paths in
+ let missing = bootstrapImages.subtracting(paths)
+ guard missing.isEmpty else {
+ throw PatcherError.invalidFormat(
+ "required X1 bootstrap cache images are missing: \(missing.sorted().joined(separator: ", "))",
+ )
+ }
+ return bootstrapImages
+ } finish: { chunks, selected in
+ let coreCrypto = selected.first { $0.path == "/usr/lib/system/libcorecrypto.dylib" }!
+ try refreshCoreCryptoIntegrity(at: coreCrypto.address, in: chunks, log: log)
+ }
+ }
+
+ /// Lowers every X1 image the bootstrap closure leaves to launchd's
+ /// on-demand handler. That handler is one thread in PID 1 and patches a
+ /// private page copy per process, so each process re-faults every site it
+ /// runs; SwiftUI-heavy extensions then exhaust FrontBoard's watchdog. An
+ /// image this planner cannot lower stays on the on-demand path.
+ public static func patchRemaining(
+ directory: URL,
+ dryRun: Bool = false,
+ captureUndo: Bool = false,
+ onUndo: (DyldSharedCacheUndoLog) -> Void = { _ in },
+ log: @escaping (String) -> Void = { print($0) },
+ ) throws {
+ try lower(
+ directory: directory, dryRun: dryRun, captureUndo: captureUndo, onUndo: onUndo, log: log,
+ patchID: FirmwareGuestSystemPatchSet.arm64eX1CacheRemaining, label: "X1 cache",
+ skipsUnplannable: true,
+ ) { paths in
+ paths.subtracting(bootstrapImages)
+ } finish: { _, _ in }
+ }
+
+ private static func lower(
+ directory: URL,
+ dryRun: Bool,
+ captureUndo: Bool,
+ onUndo: (DyldSharedCacheUndoLog) -> Void,
+ log: @escaping (String) -> Void,
+ patchID: String,
+ label: String,
+ skipsUnplannable: Bool = false,
+ select: (Set<String>) throws -> Set<String>,
+ finish: (DyldSharedCacheChunkSet, [(address: UInt64, path: String)]) throws -> Void,
) throws {
let chunks = try DyldSharedCacheChunkSet(
directory: directory,
captureUndo: captureUndo || !dryRun,
)
guard chunks.mainCacheURL.lastPathComponent.hasSuffix("arm64e_x1") else {
- log(" [·] X1 bootstrap cache: not an X1 cache")
+ log(" [·] \(label): not an X1 cache")
return
}
@@ -71,35 +129,88 @@ public enum DyldSharedCacheArm64eX1BootstrapPatcher {
guard let infos = cache.imageInfos else {
throw PatcherError.invalidFormat("X1 cache has no images")
}
- var selected: [(address: UInt64, path: String)] = []
+ var images: [(address: UInt64, path: String)] = []
var seen = Set<UInt64>()
for info in infos where seen.insert(info.address).inserted {
- guard let path = info.path(in: cache), bootstrapImages.contains(path) else { continue }
- selected.append((info.address, path))
+ guard let path = info.path(in: cache) else { continue }
+ images.append((info.address, path))
}
- guard Set(selected.map(\.path)) == bootstrapImages else {
- let missing = bootstrapImages.subtracting(selected.map(\.path)).sorted()
- throw PatcherError.invalidFormat(
- "required X1 bootstrap cache images are missing: \(missing.joined(separator: ", "))",
- )
+ let wanted = try select(Set(images.map(\.path)))
+ let selected = images.filter { wanted.contains($0.path) }
+
+ // Planning only reads; each worker gets its own chunk set and Capstone
+ // handle, and results keep image order so the writes are deterministic.
+ let workers = max(1, min(ProcessInfo.processInfo.activeProcessorCount, selected.count))
+ // Largest first, sized by the gap to the next image, so the last few
+ // workers are not left with UIKitCore while the rest sit idle.
+ let starts = images.map(\.address).sorted()
+ var spans: [UInt64: UInt64] = [:]
+ for (start, next) in zip(starts, starts.dropFirst()) { spans[start] = next - start }
+ let order = selected.indices.sorted { spans[selected[$0].address, default: 0] > spans[selected[$1].address, default: 0] }
+ let readers = try (0 ..< workers).map { _ in try DyldSharedCacheChunkSet(directory: directory, mappedReads: true) }
+ // One decoder per worker, reused across its images: cached decodes
+ // belong to the word, not to the image.
+ let decoders = (0 ..< workers).map { _ in CustomFirmwareArm64eX1.Decoder() }
+ let queue = Mutex((
+ next: 0,
+ plans: [Result<ImagePlan, any Error>?](repeating: nil, count: selected.count),
+ ))
+ DispatchQueue.concurrentPerform(iterations: workers) { worker in
+ // Capstone formats operands with vsnprintf, which serializes every
+ // worker on the global locale's lock; a thread locale avoids it.
+ let locale = newlocale(LC_NUMERIC_MASK, "C", nil)
+ let previous = uselocale(locale)
+ defer {
+ uselocale(previous)
+ freelocale(locale)
+ }
+ while true {
+ let next = queue.withLock { state in
+ defer { state.next += 1 }
+ return state.next
+ }
+ guard next < order.count else { return }
+ let index = order[next]
+ let plan = Result {
+ let result = try planImage(at: selected[index].address, in: readers[worker], identifier: patchID,
+ decoder: decoders[worker])
+ return ImagePlan(
+ writes: result.records.map {
+ Write(
+ address: UInt64($0.fileOffset),
+ word: $0.patchedBytes.loadLE(UInt32.self, at: 0),
+ )
+ },
+ unvisitedCandidates: result.unvisitedCandidates,
+ )
+ }
+ queue.withLock { $0.plans[index] = plan }
+ }
}
- let coreCrypto = selected.first { $0.path == "/usr/lib/system/libcorecrypto.dylib" }!
+ let plans = queue.withLock { $0.plans }
var writes: [Write] = []
var unvisited = 0
- for image in selected {
- let result = try planImage(at: image.address, in: chunks)
+ var lowered = 0
+ var skipped: [String] = []
+ for (image, plan) in zip(selected, plans) {
+ let result: ImagePlan
+ do {
+ result = try plan!.get()
+ } catch where skipsUnplannable {
+ skipped.append(image.path)
+ log(" [!] \(label): \(image.path): left to the on-demand handler: \(error)")
+ continue
+ }
unvisited += result.unvisitedCandidates
- writes += result.records.map {
- Write(
- address: UInt64($0.fileOffset),
- word: $0.patchedBytes.loadLE(UInt32.self, at: 0),
- )
+ if !result.writes.isEmpty { lowered += 1 }
+ writes += result.writes
+ if !skipsUnplannable || !result.writes.isEmpty {
+ log(" [.] \(label): \(image.path): \(result.writes.count) instructions, \(result.unvisitedCandidates) unvisited")
}
- log(" [.] X1 bootstrap cache: \(image.path): \(result.records.count) instructions, \(result.unvisitedCandidates) unvisited")
}
writes.sort { $0.address < $1.address }
- log(" [*] X1 bootstrap cache: \(selected.count) image(s), \(writes.count) rewrites, \(unvisited) unvisited candidates")
+ log(" [*] \(label): \(selected.count) image(s), \(lowered) with X1 code, \(skipped.count) skipped, \(writes.count) rewrites, \(unvisited) unvisited candidates")
guard !dryRun else { return }
do {
@@ -115,7 +226,7 @@ public enum DyldSharedCacheArm64eX1BootstrapPatcher {
pageSize = known
} else {
guard let directory = try DyldSharedCacheCodeSignature.readCodeDirectory(ofChunk: firstChunk) else {
- throw PatcherError.invalidFormat("X1 bootstrap code chunk has no supported signature")
+ throw PatcherError.invalidFormat("\(label) code chunk has no supported signature")
}
pageSize = directory.pageSize
pageSizes[firstChunk] = pageSize
@@ -126,7 +237,7 @@ public enum DyldSharedCacheArm64eX1BootstrapPatcher {
let next = writes[index]
if next.address == previous.address {
guard next.word == previous.word else {
- throw PatcherError.invalidFormat("conflicting X1 bootstrap rewrites")
+ throw PatcherError.invalidFormat("conflicting \(label) rewrites")
}
index += 1
continue
@@ -153,22 +264,24 @@ public enum DyldSharedCacheArm64eX1BootstrapPatcher {
if before != after {
try chunks.write(at: start, after)
groups += 1
- log(" 0x\(String(start, radix: 16)): \(changed) instruction(s) [\(FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap)]")
+ if !skipsUnplannable {
+ log(" 0x\(String(start, radix: 16)): \(changed) instruction(s) [\(patchID)]")
+ }
}
}
- try refreshCoreCryptoIntegrity(at: coreCrypto.address, in: chunks, log: log)
+ try finish(chunks, selected)
let attestation = try DyldSharedCacheCodeSignature.reattestRecordedWrites(in: chunks, log: log)
guard attestation.isFullyAttested else {
throw PatcherError.invalidFormat(
- "X1 bootstrap re-attestation skipped \(attestation.skipped.count) pages",
+ "\(label) re-attestation skipped \(attestation.skipped.count) pages",
)
}
onUndo(chunks.takeUndoLog()!)
- log(" [+] X1 bootstrap cache: \(writes.count) instruction rewrites in \(groups) page run(s)")
+ log(" [+] \(label): \(writes.count) instruction rewrites in \(groups) page run(s)")
} catch {
var undo = chunks.takeUndoLog()!
if !undo.records.isEmpty {
- undo.stamp(patchID: FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap)
+ undo.stamp(patchID: patchID)
let spans = try undo.restore(patchIDs: undo.patchIDs, in: directory, log: log)
_ = try DyldSharedCacheCodeSignature.reattest(
in: chunks,
@@ -216,6 +329,8 @@ public enum DyldSharedCacheArm64eX1BootstrapPatcher {
static func planImage(
at address: UInt64,
in chunks: DyldSharedCacheChunkSet,
+ identifier: String = FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
+ decoder: CustomFirmwareArm64eX1.Decoder = .init(),
) throws -> CustomFirmwareArm64eX1.Result {
let prefix = try chunks.bytesAtVMA(address, length: 32)
guard prefix.loadLE(UInt32.self, at: 0) == 0xFEED_FACF else {
@@ -338,7 +453,7 @@ public enum DyldSharedCacheArm64eX1BootstrapPatcher {
ranges: ranges,
seeds: seeds,
excluded: excluded,
- identifier: FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
+ identifier: identifier,
readMemory: { address, length in
return try chunks.bytesAtVMA(UInt64(address), length: length)
},
@@ -369,6 +484,7 @@ public enum DyldSharedCacheArm64eX1BootstrapPatcher {
diversity: diversity,
)
},
+ decoder: decoder,
)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index f0c58820..150d049a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -28,6 +28,7 @@ public enum FirmwareGuestSystemPatchSet {
public static let attitude = "system-apps-cfw-attitude"
public static let arm64eX1DyldBootstrap = "system-dyld-boot-arm64e_x1_bootstrap"
public static let arm64eX1CacheBootstrap = "dyld-boot-arm64e_x1_bootstrap"
+ public static let arm64eX1CacheRemaining = "dyld-cfw-arm64e_x1_cache"
public static let arm64eX1LaunchdBootstrap = "system-launchd-boot-arm64e_x1_bootstrap"
public static let arm64eX1FsckBootstrap = "system-fsck-boot-arm64e_x1_bootstrap"
public static let arm64eX1MountBootstrap = "system-mount-boot-arm64e_x1_bootstrap"
@@ -216,6 +217,13 @@ public enum FirmwareGuestSystemPatchSet {
applicability: ios27,
bootEssential: true,
),
+ VPhonePatchDeclaration(
+ identifier: arm64eX1CacheRemaining,
+ title: "ARM64E_X1 cache lowering",
+ summary: "Lowers X1 instructions in every other shared-cache image ahead of time, so apps and extensions do not queue on launchd's on-demand handler until FrontBoard's watchdog kills them.",
+ target: .dyldSharedCache,
+ applicability: ios27,
+ ),
VPhonePatchDeclaration(
identifier: arm64eX1LaunchdBootstrap,
title: "ARM64E_X1 launchd bootstrap",
@@ -485,6 +493,24 @@ public enum FirmwareGuestSystemPatchSet {
""",
target: .guestExecutable(path: "/Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio"),
),
+ VPhonePatchDeclaration(
+ identifier: virtualAudioDeviceStateGuard,
+ title: "VirtualAudio device-state guard",
+ summary: """
+ Stands down the two device-state updates VirtualAudio_Device pushes at \
+ DeviceStateManager while the manager's singleton does not exist yet. \
+ The singleton is published only at the end of deferred initialization, \
+ which first waits for a haptic actuator port a VM does not have; with \
+ the speaker-route patches on, the published route reaches the update \
+ first, and its unchecked read of the null singleton crash-loops \
+ audiomxd about half a second after every launch. Each gate's \
+ skip-when-false branch is made unconditional, so both updates wait for \
+ the manager like every later one. Applies only to the arm64e.x1 \
+ plugin (iOS 27.1's iPhone19,4); earlier builds are left byte-identical.
+ """,
+ target: .guestExecutable(path: "/Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio"),
+ applicability: VPhonePatchApplicability(iOSBase: .major(27)),
+ ),
VPhonePatchDeclaration(
identifier: virtualAudioGraphConfigurations,
title: "VirtualAudio speaker graph chains",
@@ -552,6 +578,17 @@ public enum FirmwareGuestSystemPatchSet {
""",
target: .prebootDeviceTree,
),
+ VPhonePatchDeclaration(
+ identifier: prebootFoldableVMSubtype,
+ title: "Foldable VM sub-type",
+ summary: """
+ Reports Apple's own VM sub-type for a foldable board in the restored Preboot device \
+ tree (iPhone Duo's V68AP becomes V68VM2025). SpringBoard then treats the device as a \
+ VM and restores its fold pose from settings, instead of waiting for hinge hardware \
+ the VM does not have. Restore keeps the board's own sub-type.
+ """,
+ target: .prebootDeviceTree,
+ ),
VPhonePatchDeclaration(
identifier: prebootHaptics,
title: "Haptics node",
@@ -614,6 +651,12 @@ public enum FirmwareGuestSystemPatchSet {
/// the virtio aggregate it already built.
public static let virtualAudioVolumeModePrecondition = "system-virtualaudio-cfw-volume_mode_precondition"
+ /// The two gated device-state updates that read the DeviceStateManager
+ /// singleton before deferred initialization publishes it, stood down so
+ /// audiomxd cannot crash on the null singleton an arm64e.x1 guest is
+ /// always asked about first.
+ public static let virtualAudioDeviceStateGuard = "system-virtualaudio-cfw-device_state_guard"
+
/// The speaker chains in graph_configurations.plist, moved onto the
/// generic graph path so the DSP chain factory never needs the physical
/// Speaker device a VM does not have.
@@ -646,6 +689,10 @@ public enum FirmwareGuestSystemPatchSet {
/// taken from the iPhone's own tree: see `DeviceTreePatcher.presentPhoneProduct`.
public static let prebootIPhoneProduct = "preboot-cfw-devicetree_iphone_product"
+ /// Apple's VM sub-type for a foldable board in the restored Preboot
+ /// device tree.
+ public static let prebootFoldableVMSubtype = "preboot-cfw-devicetree_foldable_vm_subtype"
+
/// The haptics node removal in the restored Preboot device tree, for any
/// VM patched before `fw patch` removed it from every guest's tree.
public static let prebootHaptics = "preboot-cfw-devicetree_haptics"
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index 71cbe361..15bfdbd6 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -236,6 +236,7 @@ public enum FirmwarePatchSetCatalog {
public static let tvOSBlockedPatches: Set<String> = [
paravirtTask3Patch,
FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1CacheRemaining,
FirmwareGuestSystemPatchSet.virtualBluetooth,
"dyld-boot-iomfb_force_kern",
"dyld-boot-iomfb_swapend",
@@ -248,6 +249,7 @@ public enum FirmwarePatchSetCatalog {
"preboot-cfw-devicetree_board_audio",
"preboot-cfw-devicetree_haptics",
"preboot-cfw-devicetree_iphone_product",
+ "preboot-cfw-devicetree_foldable_vm_subtype",
"preboot-cfw-devicetree_microphone_array",
RestoreRamDiskSealPatcher.patchIdentifier,
"system-apps-cfw-attitude",
@@ -271,6 +273,7 @@ public enum FirmwarePatchSetCatalog {
"system-systemhook-cfw-metal_cache_reuse",
"system-systemversion-cfw-build_version",
"system-virtiosound-cfw-hal_plugin",
+ "system-virtualaudio-cfw-device_state_guard",
"system-virtualaudio-cfw-microphone_graph_chains",
"system-virtualaudio-cfw-mute_set_throw",
"system-virtualaudio-cfw-speaker_graph_chains",
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareIPhoneProductTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareIPhoneProductTests.swift
index e971efe7..7039cf75 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareIPhoneProductTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareIPhoneProductTests.swift
@@ -108,3 +108,36 @@ struct CustomFirmwareIPhoneProductTests {
#expect(patched == presented)
}
}
+
+@Suite("Foldable VM sub-type")
+struct CustomFirmwareFoldableVMSubtypeTests {
+ private typealias Node = FlatDeviceTreeNode
+
+ private static func tree(subtype: String) -> Data {
+ Node("device-tree", [
+ ("model", Data("iPhone19,4\0".utf8)),
+ ("target-sub-type", Data("\(subtype)\0".utf8)),
+ ("target-type", Data("V68\0".utf8)),
+ ], children: [Node("product", [("product-name", Data("iPhone\0".utf8))])]).serialized
+ }
+
+ @Test func `a foldable board takes Apple's VM sub-type`() throws {
+ let original = Self.tree(subtype: "V68AP")
+ let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withFoldableVMSubtype(original)
+ #expect(changes.map(\.property) == ["target-sub-type"])
+ #expect(changes.first?.before == "V68AP")
+ #expect(changes.first?.after == "V68VM2025")
+ #expect(patched.count == original.count + delta)
+ #expect(patched == Self.tree(subtype: "V68VM2025"))
+ }
+
+ @Test func `other boards and a second run are left alone`() throws {
+ for subtype in ["D47AP", "V63AP", "V68VM2025"] {
+ let original = Self.tree(subtype: subtype)
+ let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withFoldableVMSubtype(original)
+ #expect(changes.isEmpty)
+ #expect(delta == 0)
+ #expect(patched == original)
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift
index edda2d8b..e5c5d603 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift
@@ -8,7 +8,8 @@
// located-and-patched behaviour on both real builds (iPadOS 26.6.2 and
// iOS 27.0) was verified by hand while the patcher was written and is
// recorded in `Research/Guest/virtio_sound.md` — that covers the mute-set
-// patch this suite's second half names.
+// patch this suite's second half names. The arm64e.x1 frame forms
+// (iOS 27.1, iPhone19,4) are tested below on words read off that build.
@testable import FirmwarePatcher
import Foundation
@@ -188,4 +189,379 @@ struct CustomFirmwareVirtualAudioTests {
// A PAUTH BC.cond — bit 24 set, a register operand, not an offset.
#expect(CustomFirmwareVirtualAudio.decodeConditionalBranchTarget(insn: 0x5500_0FE0, pc: 0) == nil)
}
+
+ // MARK: - arm64e.x1 (FEAT_PAuth_LR) frames
+
+ // iOS 27.1's iPhone19,4 userland is arm64e.x1: functions open with
+ // `pacibsppc` and return with `retabsppc <label>`. Every word below was
+ // read off that build's VirtualAudio (24A94425) and checked against
+ // llvm-objdump, except the fixture returns, which are built from their
+ // fields.
+
+ /// `pacibsppc` — the speaker-route walker's prologue at 0x1717bc.
+ static let x1Prologue: UInt32 = 0xDAC1_A7FE
+ /// `ldp x29, x30, [sp, #0x130]` / `ldp x20, x19, [sp, #0x120]` /
+ /// `add sp, sp, #0x140` — the walker's epilogue at 0x172044.
+ static let framePop: UInt32 = 0xA953_7BFD
+ static let calleePop: UInt32 = 0xA952_4FF4
+ static let stackRelease: UInt32 = 0x9105_03FF
+ /// `b 0x172198` — the no-default-VAD throw's terminator at 0x171cd0.
+ static let terminator: UInt32 = 0x1400_0132
+
+ /// RETABSPPC <label>: the label is `imm16` words back from the return.
+ static func retabsppc(back words: UInt32) -> UInt32 {
+ 0x5520_001F | (words & 0xFFFF) << 5
+ }
+
+ static func instruction(_ word: UInt32, at offset: Int = 0) -> ARM64Instruction? {
+ ARM64Disassembler().disassembleOne(in: ARM64.encodeU32(word), at: 0, address: UInt64(offset))
+ }
+
+ /// A walker tail: prologue, the throw's terminator, the pops, the
+ /// return. The epilogue's entry is the frame-pair pop at 0xC.
+ static func walkerTail(prologue: Data, return ret: Data) -> Data {
+ var data = prologue + ARM64.nop
+ data += ARM64.encodeU32(terminator)
+ data += ARM64.encodeU32(framePop) + ARM64.encodeU32(calleePop) + ARM64.encodeU32(stackRelease)
+ return data + ret
+ }
+
+ @Test
+ func `both signing prologues and both B-key returns are recognised, a plain ret is not`() {
+ #expect(CustomFirmwareVirtualAudio.isPrologue(Self.instruction(Self.x1Prologue)))
+ #expect(CustomFirmwareVirtualAudio.isPrologue(Self.instruction(ARM64.pacibspU32)))
+ #expect(!CustomFirmwareVirtualAudio.isPrologue(Self.instruction(ARM64.nopU32)))
+
+ let x1Return = Self.instruction(0x5520_455F, at: 0x172064)
+ #expect(x1Return?.mnemonic == "retabsppc")
+ #expect(CustomFirmwareVirtualAudio.isAuthenticatedReturn(x1Return))
+ #expect(CustomFirmwareVirtualAudio.isAuthenticatedReturn(
+ ARM64Disassembler().disassembleOne(ARM64.retab),
+ ))
+ // `ret` — closes a leaf or an `autibsppc` pair, never these frames.
+ #expect(!CustomFirmwareVirtualAudio.isAuthenticatedReturn(Self.instruction(0xD65F_03C0)))
+ #expect(CustomFirmwareVirtualAudio.returnMnemonics.contains("ret"))
+ #expect(CustomFirmwareVirtualAudio.returnMnemonics.isSuperset(of: CustomFirmwareVirtualAudio.authenticatedReturnMnemonics))
+ }
+
+ /// Capstone decodes the label as `#0` whatever the field holds, so the
+ /// label is read off the word: the walker's return at 0x172064 names
+ /// 0x1717bc, the mute-set wrapper's at 0x110ae4 names 0x110478 — both
+ /// the prologues the patcher's own walk found.
+ @Test
+ func `the retabsppc label is read off the real returns`() throws {
+ let walker = try #require(Self.instruction(0x5520_455F, at: 0x172064))
+ #expect(CustomFirmwareVirtualAudio.retabsppcLabel(walker, at: 0x172064) == 0x1717BC)
+ #expect(CustomFirmwareVirtualAudio.returnCloses(walker, at: 0x172064, prologue: 0x1717BC))
+ #expect(!CustomFirmwareVirtualAudio.returnCloses(walker, at: 0x172064, prologue: 0x1725E4))
+
+ let muteSet = try #require(Self.instruction(0x5520_337F, at: 0x110AE4))
+ #expect(CustomFirmwareVirtualAudio.retabsppcLabel(muteSet, at: 0x110AE4) == 0x110478)
+
+ // `retab` names no frame: nothing to read, and nothing to refuse.
+ let retab = try #require(ARM64Disassembler().disassembleOne(ARM64.retab))
+ #expect(CustomFirmwareVirtualAudio.retabsppcLabel(retab, at: 0) == nil)
+ #expect(CustomFirmwareVirtualAudio.returnCloses(retab, at: 0x40, prologue: 0))
+ }
+
+ @Test
+ func `an x1 epilogue ending in retabsppc is found from the throw`() throws {
+ let data = Self.walkerTail(prologue: ARM64.encodeU32(Self.x1Prologue), return: ARM64.encodeU32(Self.retabsppc(back: 6)))
+ let disasm = ARM64Disassembler()
+ #expect(CustomFirmwareVirtualAudio.nearestPrologue(in: data, disasm: disasm, below: 0x14, floor: 0) == 0)
+ let entry = try CustomFirmwareVirtualAudio.locateEpilogue(
+ in: data, disasm: disasm, after: 0x8, prologue: 0, textEnd: data.count,
+ )
+ #expect(entry == 0xC)
+ }
+
+ @Test
+ func `an arm64e epilogue ending in retab is found as before`() throws {
+ let data = Self.walkerTail(prologue: ARM64.pacibsp, return: ARM64.retab)
+ let disasm = ARM64Disassembler()
+ #expect(CustomFirmwareVirtualAudio.nearestPrologue(in: data, disasm: disasm, below: 0x14, floor: 0) == 0)
+ let entry = try CustomFirmwareVirtualAudio.locateEpilogue(
+ in: data, disasm: disasm, after: 0x8, prologue: 0, textEnd: data.count,
+ )
+ #expect(entry == 0xC)
+ }
+
+ /// A `retabsppc` that authenticates against another frame's signature is
+ /// not this function's epilogue, and branching to it would fault — the
+ /// search stops and refuses rather than looking further.
+ @Test
+ func `a retabsppc naming another prologue is refused`() {
+ // Five words back from 0x18 is the `nop` at 0x4, not the prologue.
+ let data = Self.walkerTail(prologue: ARM64.encodeU32(Self.x1Prologue), return: ARM64.encodeU32(Self.retabsppc(back: 5)))
+ #expect(throws: PatcherError.self) {
+ try CustomFirmwareVirtualAudio.locateEpilogue(
+ in: data, disasm: ARM64Disassembler(), after: 0x8, prologue: 0, textEnd: data.count,
+ )
+ }
+ }
+
+ // MARK: - Device-state guard
+
+ @Test(
+ arguments: [Self.junk, Data()],
+ )
+ func `a binary without the singleton diagnostic is refused, not searched past`(_ input: Data) throws {
+ var data = input
+ #expect(throws: PatcherError.self) {
+ try CustomFirmwareVirtualAudio.patchDeviceStateGuard(
+ &data,
+ reattest: false,
+ dryRun: true,
+ log: nil,
+ )
+ }
+ }
+
+ @Test
+ func `the device-state anchor strings and record identity are stable`() {
+ #expect(CustomFirmwareVirtualAudio.deviceStateInstanceMissing == "TheInstance() called before SetInstance()")
+ #expect(CustomFirmwareVirtualAudio.deviceStateGuardPatchID == "system-virtualaudio-cfw-device_state_guard")
+ }
+
+ /// The arm64e.x1 header word iOS 27.1's plugin carries, and the plain
+ /// arm64e one 26.6.2 and 27.0 carry — both read off those builds, LIB64
+ /// bit included.
+ static let x1Subtype: UInt32 = 0x8000_000C
+ static let arm64eSubtype: UInt32 = 0x8000_0002
+
+ @Test
+ func `the plugin subtype gate tells the three arm64 worlds apart`() {
+ func header(_ subtype: UInt32) -> Data {
+ var data = Data()
+ for word: UInt32 in [0xFEED_FACF, 0x0100_000C, subtype, 6, 0, 0, 0, 0] {
+ withUnsafeBytes(of: word.littleEndian) { data.append(contentsOf: $0) }
+ }
+ return data
+ }
+ #expect(CustomFirmwareVirtualAudio.arm64Subtype(of: header(Self.x1Subtype)) == .x1)
+ #expect(CustomFirmwareVirtualAudio.arm64Subtype(of: header(Self.arm64eSubtype)) == .other)
+ #expect(CustomFirmwareVirtualAudio.arm64Subtype(of: Self.junk) == .notArm64)
+ #expect(CustomFirmwareVirtualAudio.arm64Subtype(of: Data()) == .notArm64)
+ }
+
+ // A synthetic plugin carrying the guarded device-state shape: TheInstance
+ // with its diagnostic reference, two gated updates, and the two callers
+ // the shape must refuse — the haptic delegate's unguarded deref and a
+ // caller that passes the singleton on. Every instruction comes from the
+ // encoder or the frozen constants, and the layout is fixed so the gate,
+ // call and skip addresses are the same in every test.
+ //
+ // text+0x00 pacibsppc TheInstance
+ // text+0x04 adrp x3, <cstring> the diagnostic's reference
+ // text+0x08 add x3, x3, #0
+ // text+0x0c retab
+ // text+0x10 bl retab gate check, site 1
+ // text+0x14 cbz w0, +0x20 the gate the patch rewrites
+ // text+0x18 bl TheInstance
+ // text+0x1c mov x20, x0
+ // text+0x20 ldr x21, [x0] the deref that faults
+ // text+0x24-0x2c nops the rest of the update
+ // text+0x30 …site 2, the same shape…
+ // text+0x58 bl retab the haptic caller's release call
+ // text+0x5c bl TheInstance unguarded: no gate above it
+ // text+0x60 mov x20, x0
+ // text+0x64 ldr x21, [x0]
+ // text+0x68 nop
+ // text+0x6c bl TheInstance pass-through caller: no deref after
+ static let deviceStateTextStart = 0x108
+ static let deviceStateGate1 = 0x11C
+ static let deviceStateCall1 = 0x120
+ static let deviceStateSkip1 = 0x13C
+ static let deviceStateGate2 = 0x140
+ static let deviceStateCall2 = 0x144
+ static let deviceStateSkip2 = 0x160
+ static let deviceStateHapticStart = 0x160
+
+ /// The guarded plugin image. `gatedSites` builds only that many gated
+ /// updates (the refusal test wants fewer than two); the two mismatching
+ /// callers ride along every time.
+ static func deviceStateImage(cpuSubtype: UInt32, gatedSites: Int = 2) throws -> Data {
+ func word(_ encoded: Data?) throws -> UInt32 {
+ guard let encoded, encoded.count == 4 else {
+ throw PatcherError.invalidFormat("the test build could not encode an instruction")
+ }
+ return UInt32(encoded[encoded.startIndex])
+ | UInt32(encoded[encoded.startIndex + 1]) << 8
+ | UInt32(encoded[encoded.startIndex + 2]) << 16
+ | UInt32(encoded[encoded.startIndex + 3]) << 24
+ }
+
+ let theInstance = deviceStateTextStart
+ let stub = theInstance + 0xC
+ func gatedSite(start: Int) throws -> [UInt32] {
+ let gate = start + 4
+ let call = start + 8
+ let skip = call + 0x1C
+ return [
+ try word(ARM64Encoder.encodeBL(from: start, to: stub)),
+ try word(ARM64Encoder.encodeCompareBranch(nonzero: false, register: 0, from: gate, to: skip)),
+ try word(ARM64Encoder.encodeBL(from: call, to: theInstance)),
+ try word(ARM64Encoder.encodeMovX(rd: 20, rm: 0)),
+ try word(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 21, rn: 0, offset: 0)),
+ ARM64.nopU32, ARM64.nopU32, ARM64.nopU32,
+ ]
+ }
+
+ var code: [UInt32] = [
+ Self.x1Prologue,
+ try word(ARM64Encoder.encodeADRP(rd: 3, pc: UInt64(theInstance + 4), target: 0x2000)),
+ try word(ARM64Encoder.encodeAddImm12(rd: 3, rn: 3, imm12: 0)),
+ ARM64.retabU32,
+ ]
+ for index in 0 ..< gatedSites {
+ code += try gatedSite(start: deviceStateTextStart + 0x10 + index * 0x24)
+ // The gap word the 0x24 spacing runs through — a call, like the
+ // release call the real haptic site carries above its own.
+ let gap = deviceStateTextStart + 0x30 + index * 0x24
+ code += [try word(ARM64Encoder.encodeBL(from: gap, to: stub))]
+ }
+ // The haptic delegate's shape: the same unguarded deref, but the
+ // instruction above the call is a release call, not a gate; then a
+ // caller that passes the singleton on instead of reading it, closed
+ // by two nops so the scan reads deterministic words past it.
+ let haptic = deviceStateHapticStart
+ code += [
+ try word(ARM64Encoder.encodeBL(from: haptic, to: stub)),
+ try word(ARM64Encoder.encodeBL(from: haptic + 4, to: theInstance)),
+ try word(ARM64Encoder.encodeMovX(rd: 20, rm: 0)),
+ try word(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 21, rn: 0, offset: 0)),
+ ARM64.nopU32,
+ try word(ARM64Encoder.encodeBL(from: haptic + 0x14, to: theInstance)),
+ ARM64.nopU32, ARM64.nopU32,
+ ]
+ return pluginImage(cpuSubtype: cpuSubtype, text: code)
+ }
+
+ /// A thin arm64 plugin image: one __TEXT segment carrying `text` as
+ /// __text (address == file offset, like the real plugin) and the
+ /// singleton's diagnostic as __cstring at 0x2000.
+ static func pluginImage(cpuSubtype: UInt32, text: [UInt32]) -> Data {
+ let textOffset = 32 + 72 + 2 * 80
+ let cstringOffset = textOffset + text.count * 4
+ let diagnostic = Array("TheInstance() called before SetInstance()\0".utf8)
+ let total = cstringOffset + diagnostic.count
+
+ func padded(_ name: String) -> [UInt8] {
+ Array(name.utf8) + Array(repeating: 0, count: 16 - name.utf8.count)
+ }
+ func word32(_ value: [UInt32]) -> [UInt8] {
+ value.flatMap { withUnsafeBytes(of: $0.littleEndian) { Array($0) } }
+ }
+ func word64(_ value: [UInt64]) -> [UInt8] {
+ value.flatMap { withUnsafeBytes(of: $0.littleEndian) { Array($0) } }
+ }
+
+ var command = word32([0x19, 72 + 160])
+ command += padded("__TEXT")
+ command += word64([0, UInt64(total), 0, UInt64(total)])
+ command += word32([0b111, 0b111, 2, 0])
+ // __text
+ command += padded("__text") + padded("__TEXT")
+ command += word64([UInt64(textOffset), UInt64(text.count * 4)])
+ command += word32([UInt32(textOffset), 2, 0, 0, 0x8000_0400, 0, 0, 0])
+ // __cstring
+ command += padded("__cstring") + padded("__TEXT")
+ command += word64([0x2000, UInt64(diagnostic.count)])
+ command += word32([UInt32(cstringOffset), 3, 0, 0, 2, 0, 0, 0])
+
+ var image = word32([0xFEED_FACF, 0x0100_000C, cpuSubtype, 6, 1, UInt32(command.count), 0, 0])
+ image += command
+ image += text.flatMap { withUnsafeBytes(of: $0.littleEndian) { Array($0) } }
+ image += diagnostic
+ image += Array(repeating: 0, count: total - image.count)
+ return Data(image)
+ }
+
+ private static func word(_ data: Data, _ offset: Int) -> UInt32? {
+ guard offset + 4 <= data.count else { return nil }
+ return UInt32(data[data.startIndex + offset])
+ | UInt32(data[data.startIndex + offset + 1]) << 8
+ | UInt32(data[data.startIndex + offset + 2]) << 16
+ | UInt32(data[data.startIndex + offset + 3]) << 24
+ }
+
+ @Test
+ func `the guard rewrites exactly the two gates and is idempotent`() throws {
+ var data = try Self.deviceStateImage(cpuSubtype: Self.x1Subtype)
+ let pristine = data
+
+ let report = try CustomFirmwareVirtualAudio.patchDeviceStateGuard(
+ &data, reattest: false, dryRun: false, log: nil,
+ )
+ #expect(report.outcome == .patched)
+ #expect(report.records.count == 2)
+ #expect(report.records.map(\.patchID) == [
+ CustomFirmwareVirtualAudio.deviceStateGuardPatchID,
+ CustomFirmwareVirtualAudio.deviceStateGuardPatchID,
+ ])
+
+ // Each gate's `cbz w0` became an unconditional `b` to its own skip;
+ // every byte that moved lies inside a gate's word. (The two words can
+ // share a byte — both hold 0x00 in their high half — so the count is
+ // not the whole test.)
+ let changed = zip(pristine, data).enumerated().filter { $0.element.0 != $0.element.1 }.map(\.offset)
+ #expect(!changed.isEmpty)
+ let gates = [(Self.deviceStateGate1, Self.deviceStateSkip1), (Self.deviceStateGate2, Self.deviceStateSkip2)]
+ #expect(changed.allSatisfy { offset in gates.contains { gate, _ in gate <= offset && offset < gate + 4 } })
+ for (gate, skip) in gates {
+ let branch = try #require(ARM64Encoder.encodeB(from: gate, to: skip))
+ #expect(Data(data[gate ..< gate + 4]) == branch)
+ let patchedWord = try #require(Self.word(data, gate))
+ #expect(ARM64Encoder.decodeBranchTarget(insn: patchedWord, pc: UInt64(gate)) == UInt64(skip))
+ }
+
+ // A second run recognises its own branches and writes nothing.
+ let once = data
+ let again = try CustomFirmwareVirtualAudio.patchDeviceStateGuard(
+ &data, reattest: false, dryRun: false, log: nil,
+ )
+ #expect(again.outcome == .alreadyPatched)
+ #expect(again.records.isEmpty)
+ #expect(data == once)
+ }
+
+ @Test
+ func `a dry run locates both sites and writes nothing`() throws {
+ var data = try Self.deviceStateImage(cpuSubtype: Self.x1Subtype)
+ let pristine = data
+ let report = try CustomFirmwareVirtualAudio.patchDeviceStateGuard(
+ &data, reattest: false, dryRun: true, log: nil,
+ )
+ #expect(report.outcome == .wouldPatch)
+ #expect(report.records.isEmpty)
+ #expect(data == pristine)
+ #expect(report.sites.map(\.gateVMA) == [UInt64(Self.deviceStateGate1), UInt64(Self.deviceStateGate2)])
+ #expect(report.sites.map(\.skipTargetVMA) == [UInt64(Self.deviceStateSkip1), UInt64(Self.deviceStateSkip2)])
+ #expect(report.theInstanceVMA == UInt64(Self.deviceStateTextStart))
+ }
+
+ @Test
+ func `a plain arm64e plugin is reported and left byte-identical`() throws {
+ var data = try Self.deviceStateImage(cpuSubtype: Self.arm64eSubtype)
+ let pristine = data
+ let report = try CustomFirmwareVirtualAudio.patchDeviceStateGuard(
+ &data, reattest: false, dryRun: false, log: nil,
+ )
+ #expect(report.outcome == .notArm64EX1)
+ #expect(report.records.isEmpty)
+ #expect(report.sites.isEmpty)
+ #expect(data == pristine)
+ }
+
+ @Test
+ func `fewer gated updates than the plugin carries are refused, not half-patched`() throws {
+ var data = try Self.deviceStateImage(cpuSubtype: Self.x1Subtype, gatedSites: 1)
+ let pristine = data
+ #expect(throws: PatcherError.self) {
+ try CustomFirmwareVirtualAudio.patchDeviceStateGuard(
+ &data, reattest: false, dryRun: false, log: nil,
+ )
+ }
+ #expect(data == pristine)
+ }
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheArm64eX1BootstrapTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheArm64eX1BootstrapTests.swift
index 68bf622e..faed3baf 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheArm64eX1BootstrapTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheArm64eX1BootstrapTests.swift
@@ -103,6 +103,14 @@ struct DyldSharedCacheArm64eX1BootstrapTests {
#expect(plan.records.first?.fileOffset == Int(imageAddress + 0x200))
#expect(plan.records.first?.patchedBytes == ARM64.pacibsp)
#expect(plan.records.last?.patchedBytes == ARM64.retab)
+ #expect(plan.records.allSatisfy { $0.patchID.hasPrefix(FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap + ".") })
+ let remaining = try DyldSharedCacheArm64eX1BootstrapPatcher.planImage(
+ at: imageAddress,
+ in: chunks,
+ identifier: FirmwareGuestSystemPatchSet.arm64eX1CacheRemaining,
+ )
+ #expect(remaining.records.map(\.patchedBytes) == plan.records.map(\.patchedBytes))
+ #expect(remaining.records.allSatisfy { $0.patchID.hasPrefix(FirmwareGuestSystemPatchSet.arm64eX1CacheRemaining + ".") })
#expect(try Data(contentsOf: url) == cache)
put32(0x9000, 0x1000 + 192)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchArm64eX1Tests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchArm64eX1Tests.swift
index f325c3d1..a5dc0dbc 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchArm64eX1Tests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelCustomFirmwarePatchArm64eX1Tests.swift
@@ -96,6 +96,7 @@ struct KernelCustomFirmwarePatchArm64eX1Tests {
"kernel-boot-arm64e_x1",
FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap,
FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1CacheRemaining,
FirmwareGuestSystemPatchSet.arm64eX1LaunchdBootstrap,
FirmwareGuestSystemPatchSet.arm64eX1FsckBootstrap,
FirmwareGuestSystemPatchSet.arm64eX1MountBootstrap,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
index ff438a04..c1f8016a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
@@ -220,6 +220,7 @@ struct FirmwareGuestPatchResolutionTests {
#expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: tv4K27.enabled, arm64eUserland: true).isEmpty)
let x1Patches: Set<String> = [
FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
+ FirmwareGuestSystemPatchSet.arm64eX1CacheRemaining,
FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap,
FirmwareGuestSystemPatchSet.arm64eX1FsckBootstrap,
FirmwareGuestSystemPatchSet.arm64eX1LaunchdBootstrap,
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
index 0ad180e7..f61b3c90 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift
@@ -76,6 +76,7 @@ enum VPhoneCustomFirmwareDyldSharedCacheVerbs {
[
VPhoneCustomFirmwarePatchSettingsSoftwareUpdateCommand.self,
VPhoneCustomFirmwarePatchArm64eX1BootstrapCacheCommand.self,
+ VPhoneCustomFirmwarePatchArm64eX1CacheCommand.self,
VPhoneCustomFirmwareDyldSharedCacheRevertCommand.self,
VPhoneCustomFirmwarePatchHypervisorVirtualMachineDyldSharedCacheCommand.self,
VPhoneCustomFirmwarePatchIOMFBSwapEndCommand.self,
@@ -141,6 +142,29 @@ struct VPhoneCustomFirmwarePatchArm64eX1BootstrapCacheCommand: ParsableCommand {
}
}
+struct VPhoneCustomFirmwarePatchArm64eX1CacheCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "patch-arm64e-x1-cache",
+ abstract: "Lower the X1 code in every cache image outside the bootstrap closure",
+ )
+
+ @Argument(transform: URL.init(fileURLWithPath:)) var directory: URL
+ @Flag(name: .customLong("dry-run")) var dryRun = false
+ @OptionGroup var undo: DyldSharedCacheUndoOptions
+
+ func run() throws {
+ var captured = DyldSharedCacheUndoLog()
+ try DyldSharedCacheArm64eX1BootstrapPatcher.patchRemaining(
+ directory: directory,
+ dryRun: dryRun,
+ captureUndo: undo.captures,
+ onUndo: { captured.merge($0) },
+ log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,
+ )
+ try undo.persist(captured, dryRun: dryRun)
+ }
+}
+
// MARK: - patch-hv-vmm-dsc
struct VPhoneCustomFirmwarePatchHypervisorVirtualMachineDyldSharedCacheCommand: ParsableCommand {
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index cad45cb6..94a3f448 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -564,6 +564,9 @@ struct VPhoneCustomFirmwareInstaller {
if device.family != .homePod {
notApplicableGuest.insert(FirmwareGuestSystemPatchSet.homePodAudioProduct)
}
+ if !Self.isFoldable(device) {
+ notApplicableGuest.insert(FirmwareGuestSystemPatchSet.prebootFoldableVMSubtype)
+ }
if !device.usesTVOS {
notApplicableGuest.insert(FirmwareGuestSystemPatchSet.tvTPRO)
}
@@ -1542,6 +1545,7 @@ struct VPhoneCustomFirmwareInstaller {
if version.hasPrefix("27.") {
dyld += [
(FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap, "patch-arm64e-x1-bootstrap-cache", [dsc]),
+ (FirmwareGuestSystemPatchSet.arm64eX1CacheRemaining, "patch-arm64e-x1-cache", [dsc]),
("dyld-boot-iomfb_force_kern", "patch-iomfb-force-kern", [dsc]),
("dyld-boot-maxslide", "patch-dsc-maxslide", [dsc]),
("dyld-boot-lsd_embedded_reg", "patch-lsd-embedded-reg", [dsc]),
@@ -1764,14 +1768,17 @@ struct VPhoneCustomFirmwareInstaller {
}
}
- // The VirtualAudio HAL plugin: four sub-patches ride one staged copy
+ // The VirtualAudio HAL plugin: five sub-patches ride one staged copy
// (`patchMachO` stages from the pristine backup, so two calls would not
// compose). On when any is on; reverted from `.bak` when all are off.
+ // The device-state guard reports "nothing to do" on the non-X1
+ // plugins, so sharing the stage costs them nothing.
let virtualAudio: [(id: String, verb: String)] = [
(FirmwareGuestSystemPatchSet.virtualAudioSpeakerRouteThrows, "patch-virtualaudio"),
(FirmwareGuestSystemPatchSet.virtualAudioMuteSetThrow, "patch-virtualaudio-mute"),
(FirmwareGuestSystemPatchSet.virtualAudioSpeakerProtectionGate, "patch-virtualaudio-sp-gate"),
(FirmwareGuestSystemPatchSet.virtualAudioVolumeModePrecondition, "patch-virtualaudio-volume-gate"),
+ (FirmwareGuestSystemPatchSet.virtualAudioDeviceStateGuard, "patch-virtualaudio-device-state-guard"),
]
let virtualAudioBundle = "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin"
let virtualAudioBinary = "\(virtualAudioBundle)/VirtualAudio"
@@ -1927,6 +1934,11 @@ struct VPhoneCustomFirmwareInstaller {
return live
}
+ /// A guest whose board has an Apple VM sub-type for its fold pose.
+ static func isFoldable(_ device: VPhoneGuestDevice) -> Bool {
+ CustomFirmwarePostRestoreDeviceTree.foldableVMSubtypes.keys.contains(device.deviceClass.uppercased())
+ }
+
/// Idempotent dyld patches whose receipts cannot identify stale implementations.
private static let dyldPatchesRerunWhenLive: Set<String> = [
"dyld-boot-maxslide",
@@ -2930,6 +2942,9 @@ struct VPhoneCustomFirmwareInstaller {
repairGroup.append((FirmwareGuestSystemPatchSet.homePodAudioProduct, "patch-dt-homepod-audio-product",
boardDeviceTree.map { [$0.path] } ?? []))
}
+ if Self.isFoldable(guestDevice) {
+ repairGroup.append((FirmwareGuestSystemPatchSet.prebootFoldableVMSubtype, "patch-dt-foldable-vm-subtype", []))
+ }
repairGroup.append((FirmwareGuestSystemPatchSet.prebootHaptics, "patch-dt-haptics", []))
repairGroup.append((FirmwareGuestSystemPatchSet.prebootMicrophoneArray, "patch-dt-microphone-array", []))
let repairsOn = repairGroup.filter { enabled($0.id) }
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
index 99a6fec2..375bae84 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
@@ -351,7 +351,8 @@ struct VPhoneCustomFirmwarePatchVirtualAudioMuteCommand: ParsableCommand {
"Unable to set property data." EXCEPTION log directly above the
throw — iOS 27's wrapper holds a second, unrelated CAException that
the window rules out. The epilogue is the wrapper's single `retab`
- walked back to its entry. No address is literal.
+ (`retabsppc` on an X1 userland) walked back to its entry. No address
+ is literal.
Idempotent: a site already holding the branch is reported and left
alone, byte for byte.
@@ -489,6 +490,68 @@ struct VPhoneCustomFirmwarePatchVirtualAudioVolumeGateCommand: ParsableCommand {
}
}
+// MARK: - patch-virtualaudio-device-state-guard
+
+struct VPhoneCustomFirmwarePatchVirtualAudioDeviceStateGuardCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "patch-virtualaudio-device-state-guard",
+ abstract: "Keep VirtualAudio's device-state updates off the null DeviceStateManager singleton",
+ discussion: """
+ Publishing the speaker route wakes VirtualAudio_Device's update,
+ which pushes the route's state at DeviceStateManager — but the
+ manager's singleton is published only at the end of deferred
+ initialization, which first waits for a haptic actuator port a VM
+ does not have. Asked earlier, the singleton's accessor logs
+ "TheInstance() called before SetInstance()", returns null, and the
+ update dereferences it: audiomxd crash-loops seconds after every
+ launch on an arm64e.x1 guest once the speaker-route patches let
+ the route through.
+
+ The patch stands the two device-state updates down. Each sits
+ behind its own gate — a capability check whose `cbz w0` already
+ skips the whole update when the check answers false — and that
+ branch is made unconditional, to the same target. The gate-check
+ call keeps running; its answer is no longer read. After deferred
+ initialization completes, the singleton exists and every later
+ update reaches the manager.
+
+ The sites are anchored on the singleton's own diagnostic string,
+ whose reference lives inside the accessor; every direct call to it
+ is then filtered to the gated shape both updates share — the
+ gate-check call, its `cbz w0` skipping forward past the update, the
+ singleton's return moved aside, and that return dereferenced
+ unchecked. Exactly two callers carry the shape; both are
+ rewritten. No address is literal.
+
+ Applies only to an arm64e.x1 plugin (cpusubtype 12 — iOS 27.1's
+ iPhone19,4). Every other build is reported and left byte-identical,
+ and the verb still exits 0: the install shares one staged copy
+ between all five VirtualAudio patches, and the earlier builds are
+ meant to keep their bytes.
+
+ Idempotent: a gate already holding the unconditional skip is
+ reported and left alone, byte for byte.
+ """,
+ )
+
+ @Argument(help: "Path to the VirtualAudio plugin Mach-O, patched in place", transform: URL.init(fileURLWithPath:))
+ var binary: URL
+
+ @Flag(name: .customLong("dry-run"), help: "Report the sites and write nothing")
+ var dryRun = false
+
+ func run() throws {
+ try requireUntruncatedMachO(at: binary)
+ // reattest: false — the caller re-signs.
+ try CustomFirmwareVirtualAudio.patchDeviceStateGuard(
+ fileAt: binary,
+ reattest: false,
+ dryRun: dryRun,
+ log: machOVerbLog,
+ )
+ }
+}
+
// MARK: - patch-virtualaudio
struct VPhoneCustomFirmwarePatchVirtualAudioCommand: ParsableCommand {
@@ -586,6 +649,7 @@ enum VPhoneCustomFirmwareMachOVerbs {
VPhoneCustomFirmwarePatchVirtualAudioMuteCommand.self,
VPhoneCustomFirmwarePatchVirtualAudioSPGateCommand.self,
VPhoneCustomFirmwarePatchVirtualAudioVolumeGateCommand.self,
+ VPhoneCustomFirmwarePatchVirtualAudioDeviceStateGuardCommand.self,
VPhoneCustomFirmwarePatchParavirtGPUIndexOffsetCommand.self,
]
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift
index 263f44ef..e8adb029 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift
@@ -577,6 +577,34 @@ struct VPhoneCustomFirmwarePatchIPhoneProductCommand: ParsableCommand {
}
}
+// MARK: - patch-dt-foldable-vm-subtype
+
+struct VPhoneCustomFirmwarePatchFoldableVMSubtypeCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "patch-dt-foldable-vm-subtype",
+ abstract: "Give a foldable guest's device tree Apple's VM sub-type",
+ discussion: """
+ Replaces the root target-sub-type of a foldable board (V68AP, iPhone
+ Duo) with Apple's own VM sub-type (V68VM2025), in place, preserving the
+ container's compression, manifest and restore info. SpringBoard's
+ device-pose code keys its virtual-machine path on that value. Any other
+ tree, or one that already has it, is left as it is.
+
+ Takes a devicetree.img4 (preferred) or a bare .im4p.
+ """,
+ )
+
+ @Argument(help: "Path to devicetree.img4 or devicetree.im4p", transform: URL.init(fileURLWithPath:))
+ var deviceTree: URL
+
+ @Flag(name: .customLong("dry-run"), help: "Report what would change and exit")
+ var dryRun = false
+
+ func run() throws {
+ try CustomFirmwarePostRestoreDeviceTree.presentFoldableVMSubtype(at: deviceTree, dryRun: dryRun, verbose: true)
+ }
+}
+
// MARK: - patch-dt-haptics
struct VPhoneCustomFirmwarePatchHapticsCommand: ParsableCommand {
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
index 637b9d55..e53459d1 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
@@ -256,6 +256,7 @@ struct VPhoneCustomFirmwareCommand: ParsableCommand {
VPhoneCustomFirmwarePatchBoardAudioCommand.self,
VPhoneCustomFirmwarePatchHomePodAudioProductCommand.self,
VPhoneCustomFirmwarePatchIPhoneProductCommand.self,
+ VPhoneCustomFirmwarePatchFoldableVMSubtypeCommand.self,
VPhoneCustomFirmwarePatchHapticsCommand.self,
VPhoneCustomFirmwarePatchMicrophoneArrayCommand.self,
] + VPhoneCustomFirmwareMachOVerbs.all + VPhoneCustomFirmwareDyldSharedCacheVerbs.all,
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
index f12453c9..0335d759 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
@@ -97,10 +97,12 @@
<string>dyld-boot-arm64e_x1_bootstrap</string>
<string>dyld-boot-iomfb_swapend</string>
<string>dyld-cfw-camera</string>
+ <string>dyld-cfw-arm64e_x1_cache</string>
<string>kernel-boot-arm64e_x1</string>
<string>preboot-cfw-devicetree_board_audio</string>
<string>preboot-cfw-devicetree_haptics</string>
<string>preboot-cfw-devicetree_iphone_product</string>
+ <string>preboot-cfw-devicetree_foldable_vm_subtype</string>
<string>preboot-cfw-devicetree_microphone_array</string>
<string>preboot-homepod-exp-audio_product</string>
<string>restoreramdisk-boot-apfs_sha3_hash</string>
@@ -133,6 +135,7 @@
<string>system-virtualaudio-cfw-speaker_raw_chains</string>
<string>system-virtualaudio-cfw-speaker_route_throws</string>
<string>system-virtualaudio-cfw-volume_mode_precondition</string>
+ <string>system-virtualaudio-cfw-device_state_guard</string>
<string>system-dyld-exp-tv_tpro</string>
<string>kernel-exp-tv_tpro_pagers</string>
</array>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
index 8ca0f78f..bb790b23 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
@@ -104,10 +104,12 @@
<string>dyld-boot-arm64e_x1_bootstrap</string>
<string>dyld-boot-iomfb_swapend</string>
<string>dyld-cfw-camera</string>
+ <string>dyld-cfw-arm64e_x1_cache</string>
<string>kernel-boot-arm64e_x1</string>
<string>preboot-cfw-devicetree_board_audio</string>
<string>preboot-cfw-devicetree_haptics</string>
<string>preboot-cfw-devicetree_iphone_product</string>
+ <string>preboot-cfw-devicetree_foldable_vm_subtype</string>
<string>preboot-cfw-devicetree_microphone_array</string>
<string>restoreramdisk-boot-apfs_sha3_hash</string>
<string>system-apps-cfw-attitude</string>
@@ -131,6 +133,7 @@
<string>system-systemhook-cfw-metal_cache_reuse</string>
<string>system-systemversion-cfw-build_version</string>
<string>system-virtiosound-cfw-hal_plugin</string>
+ <string>system-virtualaudio-cfw-device_state_guard</string>
<string>system-virtualaudio-cfw-microphone_graph_chains</string>
<string>system-virtualaudio-cfw-mute_set_throw</string>
<string>system-virtualaudio-cfw-speaker_graph_chains</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
index 53706d4f..74647695 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
@@ -108,10 +108,12 @@
<string>dyld-boot-maxslide</string>
<string>dyld-boot-xpc_lwcr</string>
<string>dyld-cfw-camera</string>
+ <string>dyld-cfw-arm64e_x1_cache</string>
<string>kernel-boot-arm64e_x1</string>
<string>preboot-cfw-devicetree_board_audio</string>
<string>preboot-cfw-devicetree_haptics</string>
<string>preboot-cfw-devicetree_iphone_product</string>
+ <string>preboot-cfw-devicetree_foldable_vm_subtype</string>
<string>preboot-cfw-devicetree_microphone_array</string>
<string>restoreramdisk-boot-apfs_sha3_hash</string>
<string>system-apps-cfw-attitude</string>
@@ -136,6 +138,7 @@
<string>system-systemhook-cfw-metal_cache_reuse</string>
<string>system-systemversion-cfw-build_version</string>
<string>system-virtiosound-cfw-hal_plugin</string>
+ <string>system-virtualaudio-cfw-device_state_guard</string>
<string>system-virtualaudio-cfw-microphone_graph_chains</string>
<string>system-virtualaudio-cfw-mute_set_throw</string>
<string>system-virtualaudio-cfw-speaker_graph_chains</string>