Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Add the Duo fold guest components

Jacky9cab1f75cfd8
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 026887fb..ca45190a 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -283,6 +283,69 @@
> 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 null gate (2026-10-24):**
+> `system-virtualaudio-cfw-device_state_null_gate` (guest system set,
+> iOS 27, on in `standard`, blocked in `tvos` and `tvos-4k`; verb `cfw
+> patch-virtualaudio-device-state-null-gate`, riding the shared staged
+> copy with the other four VirtualAudio verbs) makes
+> VirtualAudio_Device's two device-state updates wait for the
+> DeviceStateManager singleton instead of dereferencing it when it does
+> not exist. Live evidence on the iPhone Duo guest: deferred
+> initialization is dispatched at plugin init but on a machine with no
+> haptic hardware it exits without constructing the manager — no
+> "Ending Deferred Initialization" is ever logged, no thread is parked
+> inside it at crash time — so TheInstance() returns null forever and a
+> route push that arrives once the gates answer true reads it: audiomxd
+> dies, anywhere from ~10 s to ~130 s into its life. The patch redirects
+> each update's gate-check call to TheInstance, so the `cbz w0, <skip>`
+> the function already carries now tests the singleton: no manager, the
+> update is skipped through the function's own path; manager present,
+> the fall-through re-calls TheInstance and the whole update runs
+> untouched, as designed. 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. Two earlier variants were
+> replaced after live runs taught better: a `…-device_state_guard` that
+> permanently skipped both updates (stopped the crash, but wins by
+> discarding the channel a foldable's audio graph learns the posture
+> from) and a `…-device_state_early_publish` that left the deferred-init
+> actuator wait at once (a no-op on this guest — the wait loop is never
+> reached, because the manager's construction needs haptics hardware a
+> VM does not have). See the full section below.
+
+> **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_null_gate` 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
@@ -4204,3 +4267,118 @@ 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 null gate — the singleton a guest never gets (2026-10-24)
+
+`system-virtualaudio-cfw-device_state_null_gate` (new), same
+`VirtualAudio.plugin` binary, verb `cfw
+patch-virtualaudio-device-state-null-gate`, 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`
+(`patchDeviceStateNullGate`, anchoring in `locateDeviceStateNullGate`
+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) 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, deep in "Deferred Initialization" (0x3ab344, a
+dispatch block whose only caller, 0x39924c, has no direct `bl`).
+
+**Why no patch can publish the manager on a guest.** Deferred
+initialization runs at plugin init — its "Beginning" log appears within a
+second of launch — but on a machine with no haptic hardware it exits
+without reaching SetInstance: the whole-life syslog of an audiomxd run
+never logs "Ending Deferred Initialization", and when the fault lands no
+thread is parked anywhere inside 0x3ab344…0x3ae2cc. It is not blocked;
+it bails. The manager is a haptics-domain object (its accessor's own
+assertion names DeviceStateManager; the actuator-port wait at 0x3ac024 —
+100 ms polls against an 8-second deadline composed by the
+`movz`/`movk`/`movk` triple at 0x3abed8 — is the same dependency in
+another form) and a VM has no actuator to construct it around. So
+TheInstance() logs "TheInstance() called before SetInstance()" and
+returns null for the process's whole life, and any push that arrives
+once the gates answer true faults. Observed crash times ran from ~10 s
+to ~130 s into a life — the push timing varies with what triggers route
+events; the first variant of this story ("0.6 s after every launch")
+was the crash *loop's* cadence, not a fixed race window.
+
+**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 is its entry. Every direct `bl` to that
+entry — six on 27.1 — is filtered to the gated shape both device-state
+updates share: a call at −8, the `cbz w0` at −4 skipping 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-check `bl` is redirected to TheInstance —
+0xa16a0 `bl 0xfe810` → `bl 0x2b2988` (0x9401745c → 0x940844ba) and
+0xa16dc `bl 0x225b88` → `bl 0x2b2988` (0x9406112b → 0x940844ab), from
+`ARM64Encoder.encodeBL`. The `cbz w0, <skip>` below each now tests the
+singleton: null, the update is skipped through the function's own path —
+exactly what every build does when its gate answers false; present, the
+fall-through re-calls TheInstance and the whole update (the save, the
+dereference, the lock, the push) runs untouched. Nothing is deleted and
+nothing is permanently disabled: the update happens whenever there is a
+manager to receive it, which is everything this code can do on a guest
+whose manager cannot be constructed and everything it does on one whose
+manager can. The gate-check calls themselves are queries whose results
+only fed those branches; their loss is the check, which the singleton's
+existence now subsumes. Idempotent: a re-run finds the gate slot already
+calling TheInstance and writes nothing.
+
+**The two variants this replaces, and what each taught.** The first cut
+(`…-device_state_guard`, 2026-10-23) made each gate's `cbz w0` branch
+unconditional, permanently skipping both pushes. Live-validated: five
+minutes of stable audiomxd, crash reports frozen, the system-sound
+stream routed on `PuffinOutput` with its DSP chain running. Rejected on
+review: it wins by discarding the feature — on a foldable those pushes
+are how the audio graph learns the posture. The second cut
+(`…-device_state_early_publish`, same night) left the deferred-init
+actuator wait at once (`b.ls` → `b` at 0x3ac044) so construction and
+SetInstance would run immediately. Offline it resolved cleanly; live it
+was a no-op — the wait loop's "Beginning loop to wait for actuator port"
+log never appears on this guest, because the product-flag routing at
+0x3abf28 branches around the loop, and deferred init bails before
+SetInstance regardless. That run produced the construction evidence
+above (no "Ending", no parked thread) and one more crash at 31 s of
+process life. The null gate is the third and honest cut: it does not
+pretend the manager can exist; it makes the update wait for one.
+
+**The other callers, examined and left alone.** The remaining
+HapticAttenuationIODelegate callers (0x4f7dec dereferences unguarded
+behind a capability flag that reads false without a Taptic Engine;
+0x4f7b94/0x4f9114/0x5013ac pass the singleton into 0x2b30b4, reached
+only through the coordinator's activation, which needs an actuator
+port) never faulted across every observed run. With the null gate they
+keep their existing behavior: on a guest they are never reached, and if
+a future build ever reaches them pre-construction the gate's matcher
+refuses (it requires the gate shape) and the site gets its own patch.
+
+**Status.** Patcher, declaration, verb, installer wiring, tvOS block
+lists and unit tests are in; on the real 27.1 binary the verb resolves
+TheInstance at 0x2b2988 and redirects exactly the two gate-check calls
+(six bytes), a second run is byte-identical, and the 27.0 and 26.6.2
+plugins keep their SHA-256s. `FirmwarePatcherTests` shows no new
+failures against a HEAD baseline. Verified in the guest (2026-10-24
+morning, bundle `2.12.0-local.6a386de6`): the update log records both
+redirects (0xa16a0, 0xa16dc -> bl 0x2b2988), audiomxd holds one pid
+from t+30 s past t+5 min — the very window (10-130 s) the early-publish
+run died in — the audiomxd crash count stays at the 30 the earlier
+variants left, and RTAID telemetry still shows the SystemSounds stream
+routed on `PuffinOutput` with its DSP chain running.
diff --git a/Research/Guest/iphone_duo_bringup.md b/Research/Guest/iphone_duo_bringup.md
index 9f29eae7..f16f3009 100644
--- a/Research/Guest/iphone_duo_bringup.md
+++ b/Research/Guest/iphone_duo_bringup.md
@@ -108,3 +108,158 @@ 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) |
+| Words outside the lowered and flow top bytes checked for decodability only (a word-keyed answer shared by all workers); data-in-code and dispatch tables as a bitmap instead of a scanned range list; replacement text through the word cache | 914 → 291 user CPU-s, 41 s wall at load 5–8 |
+
+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_null_gate` (make the two gated
+device-state updates wait for the DeviceStateManager singleton — on a
+guest with no haptic hardware it is never constructed — instead of
+dereferencing null; 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`. Verified on this VM
+(2026-10-24 morning, bundle `2.12.0-local.6a386de6`): both gate calls
+redirected as designed, audiomxd holds one pid past five minutes — the
+window the two earlier variants died in — with zero new crash reports
+and the system-sound stream still routed on `PuffinOutput`.
+
+## 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/service_trimming.md b/Research/Guest/service_trimming.md
index 9e0cfd34..f60be6c6 100644
--- a/Research/Guest/service_trimming.md
+++ b/Research/Guest/service_trimming.md
@@ -44,7 +44,7 @@ load a disabled job at the next boot. It is the same mechanism
| Group | Default | Labels | Why they can go |
| --- | --- | --- | --- |
-| `base` | on | 137 | Appendix A of the measurement below. Nothing in vphone, IcliKit or the guest hooks talks to them |
+| `base` | on | 136 | Appendix A of the measurement below, less `siriactionsd` (list version 2). Nothing in vphone, IcliKit or the guest hooks talks to them |
| `app_store` | on | `com.apple.appstored`, `com.apple.itunesstored` | Off with the App Store and iTunes Store apps a template removes. `appstorecomponentsd` is already in `base` |
| `signin_followup` | on | `com.apple.followupd`, `com.apple.appleidsetupd` | The sign-in follow-up and Apple Account setup prompts. They complement `libsigninfix`'s pane suppression. A guest that went through `setup.skip` has no follow-up items, so no orphaned badge is left |
| `accounts` | off, `groups: ["accounts"]` | `com.apple.akd`, `com.apple.amsaccountsd`, `com.apple.appleaccountd` | Only for guests that never sign in: with these off, the guest cannot sign in to an Apple Account |
@@ -53,7 +53,7 @@ The `base` group, by area:
| Area | Examples | Kind |
| --- | --- | --- |
-| Siri and intelligence | assistantd, siriinferenced, intelligenceflowd, siriactionsd, modelmanagerd, corespeechd | Not used. siriactionsd also serves Shortcuts and App Intents, and corespeechd and modelmanagerd serve dictation |
+| Siri and intelligence | assistantd, siriinferenced, intelligenceflowd, modelmanagerd, corespeechd | Not used. corespeechd and modelmanagerd serve dictation. siriactionsd stays: see below |
| Photos and media analysis | mediaanalysisd, photoanalysisd, photosface | mediaanalysisd alone wrote 79 MiB in a 15-minute idle window |
| Ads, content and recommendations | amsengagementd, promotedcontentd, tipsd, weatherd, gamed | amsengagementd was the top idle CPU and write consumer |
| Find My | findmydeviced, searchpartyd, findmylocated, fmflocatord | No Apple Account |
@@ -67,6 +67,18 @@ The `base` group, by area:
| OTA | softwareupdateservicesd, mobile.softwareupdated, OTATaskingAgent, OTACrashCopier | Same as the [OTA block](ota_software_update_block.md) |
| Cellular extras and prediction | WirelessRadioManager, carkitd, vmd, PowerUIAgent, duetexpertd, ospredictiond | CommCenter itself stays |
+**siriactionsd stays (list version 2, 2026-10-24).** It was in the measured
+base list, but it also serves `com.apple.siri.VoiceShortcuts.xpc`, through
+which every Control Center control and App Intents widget serializes its
+intent (`-[INAppIntent initWithAppBundleIdentifier:linkAction:linkActionMetadata:]`).
+With it disabled, each such extension traps in WidgetKit
+(`ControlAction.swift: Fatal error: Can't create CHSIntentReference from
+BarcodeScannerIntent: nilError`), and Control Center draws Timer, Calculator,
+Camera, Code Scanner, Alarm, Magnifier and Voice Memo as blank circles. Seen
+on an iPhone Duo 27.1 guest; allowing the label and restarting restored every
+control. It is now in `neverDisable`, so `trimmed` no longer selects it and a
+guest that applies the profile again turns it back on.
+
Some of these are only optional: Shortcuts, dictation, HomeKit, Maps,
Mail, Reminders, iMessage and Safari bookmark sync. A research target that
uses one of those frameworks needs its daemon back. Pass that label in `allow`
diff --git a/Research/Guest/virtualaudio_speaker_route_throws.md b/Research/Guest/virtualaudio_speaker_route_throws.md
index 9e57d837..e823ac63 100644
--- a/Research/Guest/virtualaudio_speaker_route_throws.md
+++ b/Research/Guest/virtualaudio_speaker_route_throws.md
@@ -685,3 +685,124 @@ 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 singleton a guest never gets, and the null gate (2026-10-24; third cut, after a guard and an early publish)
+
+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 on queue AudioControl at plugin offset 0xa16b0, reached
+`HALS_AHPPlugIn::ObjectSetPropertyData` ←
+`__vaemVADSerializationListener_block_invoke`.
+
+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;
+when it is null it logs "TheInstance() called before SetInstance()" and
+returns the null it reloaded. The global is stored exactly once, at
+0x3ad0a8 inside "Deferred Initialization" (0x3ab344).
+
+**What live runs taught about that initialization.** It *runs* — its
+"Beginning Deferred Initialization" log appears within a second of
+launch, right after "Get on queue to get initialization state". But on
+this guest it never finishes: a whole-life syslog capture of an
+audiomxd run contains no "Ending Deferred Initialization", and when the
+fault lands, no thread is parked anywhere inside 0x3ab344…0x3ae2cc —
+deferred init has *exited*, early, without constructing the manager.
+The manager is a haptics-domain object; the actuator-port wait inside
+deferred init (loop head 0x3ac024, 100 ms polls, 8-second deadline
+`movz`/`movk`/`movk` at 0x3abed8 → `add x25, x23, x9`, "Beginning loop
+to wait for actuator port" at 0x3abfd0, "Could not find actuator port
+after 8 seconds of waiting" at 0x3ac5d4) is the same dependency in
+another form, and a VM has no actuator at all. Crash times across runs
+varied from ~10 s to ~130 s into a life: the fault is any push that
+arrives after the gates answer true, not a fixed post-launch window.
+
+**The fix** is the fifth binary patch,
+`system-virtualaudio-cfw-device_state_null_gate` (verb
+`cfw patch-virtualaudio-device-state-null-gate`, declared in
+FirmwareGuestSystemPatchSet, on in `standard` for iOS 27, blocked for
+tvOS; see `Research/0_binary_patch_comparison.md`). One word per site:
+the gate-check call is redirected to the accessor —
+
+```
+a16a0: bl 0xfe810 -> bl 0x2b2988 (0x9401745c -> 0x940844ba)
+a16dc: bl 0x225b88 -> bl 0x2b2988 (0x9406112b -> 0x940844ab)
+```
+
+— so the `cbz w0, <skip>` the function already carries now tests the
+singleton. Null manager: the update is skipped through the function's
+own path, exactly what every build does when its gate answers false.
+Manager present: the fall-through re-calls TheInstance (0xa16a8/0xa16e4,
+untouched) and the whole update — the save, the dereference, the lock,
+the push — runs as designed. Nothing is deleted, nothing is permanently
+disabled: the update happens whenever there is a manager to receive it.
+
+**Why the first two cuts were replaced.** The guard
+(`…-device_state_guard`, first night) made each `cbz w0` unconditional —
+permanently skipping both pushes. It stopped the crash (live-validated:
+stable audiomxd, crash reports frozen at the 28 baseline, the
+system-sound stream routed on `PuffinOutput` (`rout: 1`, PreDSP/PostDSP
+running) — the doc's in-guest proof standard) but it wins by discarding
+the feature: on a foldable those pushes are how the audio graph learns
+the posture. The early publish (`…-device_state_early_publish`) left
+the actuator wait at once so SetInstance would land immediately — a
+clean idea that live logging proved vacuous here: the wait loop's
+"Beginning loop" log never appears on this guest (the product-flag
+routing at 0x3abf28 branches around it) and deferred init bails before
+SetInstance regardless, so the singleton never lands and that run
+produced one more crash, 31 s in. That run's evidence — no "Ending
+Deferred Initialization", no parked thread — is what fixed the model:
+the manager is not late on a guest, it is absent, and no consumer-side
+patch can conjure it. The null gate is the honest cut.
+
+**Anchoring** follows the file's rules: nothing is a literal address.
+TheInstance is found from its own diagnostic string (unique in
+`__text`); the prologue above its reference is the entry. Every direct
+`bl` to it 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
+redirect is `ARM64Encoder.encodeBL`, and a re-run recognises its own
+work (the gate slot already calling TheInstance). 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.
+
+**The other five TheInstance callers, examined and left alone.** All
+are in `HapticAttenuationIODelegate.mm`: 0x4f7dec dereferences
+unguarded (`mov x20,x0; ldr x21,[x0]`, field 0x170) but sits behind a
+capability flag (`tbz w8,#0` at 0x4f7d0c) that reads false without a
+Taptic Engine; 0x4f7b94, 0x4f9114 and 0x5013ac pass the singleton into
+0x2b30b4 (which derefs unchecked at 0x2b30d8) but are reached only
+through the coordinator's activation ("Coordinator active"), which
+needs an actuator port. None ever faulted across every observed run.
+
+**Status — verified in the guest (2026-10-24 morning).** Bundle
+`2.12.0-local.6a386de6` (built from this tree) deployed through
+`vm set-bundle duotest-m5 … --update-environment`: the update log
+records both redirects (0xa16a0 and 0xa16dc -> bl 0x2b2988) and the
+receipt lists the patch live. After boot, audiomxd holds one pid from
+t+30 s past t+5 min — the early-publish run died at 10-130 s in — the
+audiomxd crash count stays at the 30 the earlier variants left, with
+zero new reports, and RTAID telemetry still shows the SystemSounds
+stream routed on `PuffinOutput` (`rout: 1`, PreDSP/PostDSP running).
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index ab2ed577..2d9f31dd 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 {page, usage, down?, long_press?}`, `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) |
@@ -1062,3 +1062,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 bf7d85ee..4de462c0 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/Daemon/GuestServiceProfile.swift b/VPhoneDaemon/Daemon/GuestServiceProfile.swift
index 003e0052..638a3d28 100644
--- a/VPhoneDaemon/Daemon/GuestServiceProfile.swift
+++ b/VPhoneDaemon/Daemon/GuestServiceProfile.swift
@@ -21,7 +21,7 @@ import Foundation
enum GuestServiceProfile {
/// Raised whenever a label list changes, and kept in the record, so a
/// guest shows which list its overrides came from.
- static let listVersion = 1
+ static let listVersion = 2
static let recordPath = "/var/db/vphoned/service-profile.plist"
static let trimmed = "trimmed"
static let none = "none"
@@ -80,8 +80,9 @@ enum GuestServiceProfile {
static let groups27 = catalog(base: base27)
/// Appendix A of the 2026-10-07 measurement on `svctest-a` (iPhone, 27.0
- /// 24A435): 137 LaunchDaemons that were loaded at boot and stayed unloaded
- /// after the override, with the four traps below already taken out.
+ /// 24A435): the LaunchDaemons that were loaded at boot and stayed unloaded
+ /// after the override, with the four traps below already taken out: 137,
+ /// less siriactionsd since list version 2 (see `neverDisable`).
static let base27: [String] = [
"com.apple.CallHistorySyncHelper",
"com.apple.Maps.mapspushd",
@@ -189,7 +190,6 @@ enum GuestServiceProfile {
"com.apple.servicesintelligenced",
"com.apple.seserviced",
"com.apple.siri.sirireaderd",
- "com.apple.siriactionsd",
"com.apple.siriinferenced",
"com.apple.siriknowledged",
"com.apple.sociallayerd",
@@ -280,6 +280,11 @@ enum GuestServiceProfile {
"com.apple.ReportCrash", "com.apple.osanalytics.osanalyticshelper",
"com.apple.audiomxd", "com.apple.mediaplaybackd", "com.apple.mediaremoted", "com.apple.cameracaptured",
"com.apple.mobileactivationd",
+ // App Intents: every Control Center control and App Intents widget
+ // serializes its intent through siriactionsd's VoiceShortcuts service;
+ // without it WidgetKit traps in each extension and the controls draw
+ // blank.
+ "com.apple.siriactionsd",
]
// MARK: - Selection
diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.h
index c1c9a632..858bf46f 100644
--- a/VPhoneDaemon/Native/Include/VphonedNative.h
+++ b/VPhoneDaemon/Native/Include/VphonedNative.h
@@ -52,6 +52,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/Tests/LogicTests.swift b/VPhoneDaemon/Tests/LogicTests.swift
index 57c9033d..5877f3cb 100644
--- a/VPhoneDaemon/Tests/LogicTests.swift
+++ b/VPhoneDaemon/Tests/LogicTests.swift
@@ -46,8 +46,8 @@ enum LogicTests {
static func profileCatalog() {
let groups = GuestServiceProfile.groups27
- expectEqual(GuestServiceProfile.base27.count, 137, "appendix A")
- expectEqual(Set(GuestServiceProfile.base27).count, 137, "appendix A has no duplicates")
+ expectEqual(GuestServiceProfile.base27.count, 136, "appendix A less siriactionsd")
+ expectEqual(Set(GuestServiceProfile.base27).count, 136, "appendix A has no duplicates")
let all = groups.flatMap(\.labels)
expectEqual(Set(all).count, all.count, "no label is in two groups")
for label in all + GuestServiceProfile.neverDisable {
@@ -65,7 +65,7 @@ enum LogicTests {
static func profileCatalog26() {
let base26 = GuestServiceProfile.base26
- expectEqual(base26.count, 131, "137 minus six 26.6.2 does not load")
+ expectEqual(base26.count, 130, "136 minus six 26.6.2 does not load")
expectEqual(Set(base26).count, base26.count, "no duplicates")
expect(Set(base26).isSubset(of: GuestServiceProfile.base27), "26 adds no label of its own")
expect(GuestServiceProfile.notLoadedOn26.isSubset(of: GuestServiceProfile.base27), "only 27 labels are left out")
@@ -87,30 +87,32 @@ enum LogicTests {
static func profileSelection() {
let trimmed = try? GuestServiceProfile.select(profile: "trimmed", iosMajor: 27)
- expectEqual(trimmed?.labels.count, 141, "default trimmed = 137 + 2 store + 2 follow-up")
+ expectEqual(trimmed?.labels.count, 140, "default trimmed = 136 + 2 store + 2 follow-up")
expectEqual(trimmed?.groups, ["base", "app_store", "signin_followup"])
expect(trimmed?.labels.contains("com.apple.followupd") == true, "followupd is in trimmed")
expect(trimmed?.labels.contains("com.apple.akd") == false, "akd is not in trimmed by default")
+ expect(trimmed?.labels.contains("com.apple.siriactionsd") == false, "siriactionsd serves App Intents controls")
+ expect(GuestServiceProfile.neverDisable.contains("com.apple.siriactionsd"), "siriactionsd is never disabled")
expectEqual(trimmed?.labels, trimmed?.labels.sorted(), "labels sorted")
let accounts = try? GuestServiceProfile.select(profile: "trimmed", iosMajor: 27, extraGroups: ["accounts"])
- expectEqual(accounts?.labels.count, 144, "accounts adds three")
+ expectEqual(accounts?.labels.count, 143, "accounts adds three")
expect(accounts?.labels.contains("com.apple.amsaccountsd") == true, "amsaccountsd with accounts")
let allowed = try? GuestServiceProfile.select(
profile: "trimmed", iosMajor: 27, allow: ["com.apple.weatherd", "com.example.not-listed"],
)
- expectEqual(allowed?.labels.count, 140, "allow removes one")
+ expectEqual(allowed?.labels.count, 139, "allow removes one")
expectEqual(allowed?.allowed, ["com.apple.weatherd"], "only catalog labels are reported as allowed")
expect(allowed?.labels.contains("com.apple.weatherd") == false, "weatherd kept")
let trimmed26 = try? GuestServiceProfile.select(profile: "trimmed", iosMajor: 26)
- expectEqual(trimmed26?.labels.count, 135, "26 trimmed = 131 + 2 store + 2 follow-up")
+ expectEqual(trimmed26?.labels.count, 134, "26 trimmed = 130 + 2 store + 2 follow-up")
expectEqual(trimmed26?.groups, ["base", "app_store", "signin_followup"])
expect(trimmed26?.refused.isEmpty == true, "the 26 list names nothing never disabled")
expectEqual(
(try? GuestServiceProfile.select(profile: "trimmed", iosMajor: 26, extraGroups: ["accounts"]))?.labels.count,
- 138, "accounts adds three on 26",
+ 137, "accounts adds three on 26",
)
expectEqual(try? GuestServiceProfile.select(profile: "none", iosMajor: 25), GuestServiceProfile.Selection())
@@ -205,7 +207,7 @@ enum LogicTests {
var overrides = Dictionary(uniqueKeysWithValues: ota.map { ($0, true) })
overrides["com.apple.user-choice"] = true
let apply = GuestServiceProfile.reconcile(target: trimmed.labels, owned: [], overrides: overrides)
- expectEqual(apply.disable.count, 138, "141 minus the three already disabled")
+ expectEqual(apply.disable.count, 137, "140 minus the three already disabled")
expectEqual(apply.skipped.map(\.label), ota.sorted())
let owned = GuestServiceProfile.owned(after: apply, failedDisable: [], failedEnable: [])
for label in apply.disable {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift
index aa6db5d2..3f637d33 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift
@@ -487,6 +487,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..0e29aa52 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareArm64eX1.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareArm64eX1.swift
@@ -1,11 +1,12 @@
// Static ARM64E_X1 lowering for the pre-handler and fork-sensitive boot closure.
import Foundation
+import os
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 +23,135 @@ 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)
+ }
+
+ /// `String(value, radix: 16)` for a non-negative value, without the generic
+ /// formatting path that showed in profiles of a whole-cache run.
+ static func hex(_ value: Int64) -> String {
+ let digits = Array("0123456789abcdef".utf8)
+ var number = UInt64(value), buffer = [UInt8](repeating: 0, count: 16), index = 16
+ repeat {
+ index -= 1
+ buffer[index] = digits[Int(number & 15)]
+ number >>= 4
+ } while number != 0
+ return String(decoding: buffer[index...], as: UTF8.self)
+ }
+
+ /// `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,
+ case let old = hex(last.imm), item.operandString.hasSuffix("0x" + old)
+ else { return nil }
+ let (target, overflow) = last.imm.addingReportingOverflow(delta)
+ guard !overflow, target >= 0 else { return nil }
+ let text = item.operandString.dropLast(old.utf8.count) + hex(target)
+ // 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 +213,61 @@ 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()
- var dataRanges = excluded
+ 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)) }
+ }
+ }
+ // Data inside the code, as one bit per word: a linear scan of the ranges
+ // on every step went quadratic in images with many switch tables.
+ var dataWords = AddressSet(ranges: ranges.map { ($0.address, $0.data.count) })
+ for span in excluded { dataWords.insertWords(in: span) }
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 word(at address: Int) -> UInt32? {
+ guard address & 3 == 0, !dataWords.contains(address),
+ let index = ranges.firstIndex(where: { address >= $0.address && address + 4 <= $0.address + $0.data.count }) else { return nil }
+ return rangeWords[index][(address - ranges[index].address) / 4]
+ }
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]
+ word(at: address).flatMap { decode($0, 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)
@@ -143,25 +276,44 @@ public enum CustomFirmwareArm64eX1 {
var records: [PatchRecord] = []
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) {
- let after = decoder.disassembleOne(replacement, at: instruction.address)
+ while visited.insert(offset).inserted, let word = word(at: offset) {
+ // 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. Any other word only has to decode.
+ let top = Int(word >> 24)
+ guard Self.loweredTopBytes[top] || Self.flowTopBytes[top] else {
+ guard words.decodes(word) else { break }
+ offset += 4
+ continue
+ }
+ guard let instruction = decode(word, at: offset), instruction.isDecoded, instruction.size == 4 else { break }
+ if Self.loweredTopBytes[top], let replacement = try replacement(for: instruction) {
+ // A few dozen replacement words recur millions of times
+ // across a cache; the word cache answers for them.
+ let after = replacement.count == 4
+ ? decode(replacement.withUnsafeBytes { UInt32(littleEndian: $0.loadUnaligned(as: UInt32.self)) },
+ at: offset)
+ : decoder.disassembleOne(replacement, at: instruction.address)
records.append(PatchRecord(patchID: identifier + ".\(offset)", component: "Mach-O", fileOffset: offset,
originalBytes: Data(instruction.bytes), patchedBytes: replacement,
beforeDisasm: "\(instruction.mnemonic) \(instruction.operandString)",
afterDisasm: "\(after?.mnemonic ?? "?") \(after?.operandString ?? "")",
description: "X1 compatibility lowering; PC PAC/CPA checks reduced"))
}
+ guard Self.flowTopBytes[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) {
- dataRanges.append(table.data)
+ dataWords.insertWords(in: table.data)
for target in table.targets { schedule(target) }
}
if mnemonic == "braa", let authenticatedPointer,
let table = try authenticatedDispatch(at: offset, instructionAt: decodedInstruction(at:),
pointer: authenticatedPointer) {
- dataRanges.append(table.data)
+ dataWords.insertWords(in: table.data)
for target in table.targets {
guard decodedInstruction(at: target)?.isDecoded == true else {
throw PatcherError.invalidFormat("authenticated X1 dispatch target outside executable code")
@@ -181,8 +333,8 @@ public enum CustomFirmwareArm64eX1 {
offset += 4
}
}
- records.removeAll { record in dataRanges.contains(where: { $0.contains(record.fileOffset) }) }
- let unvisited = candidates.filter { address in !visited.contains(address) && !dataRanges.contains(where: { $0.contains(address) }) }
+ records.removeAll { dataWords.contains($0.fileOffset) }
+ let unvisited = candidates.filter { address in !visited.contains(address) && !dataWords.contains(address) }
records.sort { $0.fileOffset < $1.fileOffset }
return Result(records: records, unvisitedCandidates: unvisited.count, unvisitedExamples: Array(unvisited.prefix(16)))
}
@@ -539,3 +691,166 @@ 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)
+ }
+
+ /// Every word address of `span` that lies in the ranges. A set of data
+ /// words is only ever asked about addresses inside them.
+ mutating func insertWords(in span: Range<Int>) {
+ var address = (span.lowerBound + 3) & ~3
+ while address < span.upperBound {
+ if slot(address) != nil { insert(address) }
+ address += 4
+ }
+ }
+}
+
+// MARK: - Decoder
+
+extension CustomFirmwareArm64eX1 {
+ /// Decodability answers shared by every worker of one run: an answer
+ /// belongs to the word, not to the image or worker that asked. Striped so
+ /// that workers rarely wait on one another.
+ final class SharedDecodability: Sendable {
+ private let stripes = (0 ..< 64).map { _ in OSAllocatedUnfairLock(initialState: [UInt32: Bool]()) }
+
+ private func stripe(_ word: UInt32) -> OSAllocatedUnfairLock<[UInt32: Bool]> {
+ stripes[Int((word &* 0x9E37_79B1) >> 26)]
+ }
+
+ func answer(_ word: UInt32) -> Bool? {
+ stripe(word).withLock { $0[word] }
+ }
+
+ func record(_ word: UInt32, _ decodes: Bool) {
+ stripe(word).withLock { $0[word] = decodes }
+ }
+ }
+
+ /// 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)] = [:]
+ private var decodable: [UInt32: Bool] = [:]
+ private let shared: SharedDecodability?
+
+ init(shared: SharedDecodability? = nil) {
+ self.shared = shared
+ }
+
+ /// Whether Capstone decodes `word` as one 4-byte instruction. That does
+ /// not depend on the address, and costs far less to keep than a decode.
+ /// A miss here asks the workers' shared answers before Capstone.
+ func decodes(_ word: UInt32) -> Bool {
+ if let known = decodable[word] { return known }
+ let decodes: Bool
+ if let known = shared?.answer(word) {
+ decodes = known
+ } else {
+ let item = plain[word] ?? capstone.disassembleOne(ARM64.encodeU32(word), at: 0)
+ decodes = item.map { $0.isDecoded && $0.size == 4 } ?? false
+ shared?.record(word, decodes)
+ }
+ if decodable.count >= 1 << 22 { decodable.removeAll(keepingCapacity: true) }
+ decodable[word] = decodes
+ return decodes
+ }
+
+ 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..24da6626 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,51 @@
// 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 null gate
+// --------------------------
+// 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. On a guest the singleton never
+// exists: deferred initialization is dispatched at plugin init, but on a
+// machine with no haptic hardware it leaves without constructing the
+// manager (no "Ending Deferred Initialization" is ever logged, and no
+// thread is parked inside it when the fault lands — it exits early),
+// because the manager is a haptics-domain object whose construction the
+// actuator the wait loop polls for belongs to. Asked for an instance
+// nobody published, TheInstance() logs "TheInstance() called before
+// SetInstance()" and returns null, and the update dereferences that null
+// — the audiomxd crash on an iPhone Duo guest, whenever a push arrives
+// after the gates answer true (observed from ~10 s to ~130 s in).
+//
+// The patch makes each update wait for the manager to exist: the
+// gate-check call above each `cbz w0, <skip>` is redirected to
+// TheInstance itself, so the branch the function already carries — the
+// one that skips the update when its check answers false — now tests the
+// singleton. Null manager: the update is skipped through the function's
+// own path, exactly as on any build whose gates answer false. Manager
+// present: the fall-through re-calls TheInstance and the whole update —
+// the save, the dereference, the lock, the push — runs untouched, as
+// designed. Nothing is removed: the update happens whenever there is a
+// manager to receive it, which is the most this code can do on a machine
+// whose manager cannot be constructed, and everything it does on one
+// whose manager can.
+//
+// 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 filtered to the gated shape both
+// device-state updates share: a call at −8, the `cbz w0` at −4 skipping
+// forward past the whole update, the singleton's return moved aside at +4
+// (`mov xN, x0`), and that return dereferenced unchecked at +8 (`ldr xM,
+// [x0]`) — the instruction that faults. Exactly two callers carry the
+// shape; both gate-check calls are redirected. A build with a different
+// count is refused, not half-patched. The plugin is touched only where
+// iOS 27.1's arm64e.x1 build carries the fault: 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 +265,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 of the null-gate
+ /// patch: 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 null-gate patch.
+ public static let deviceStateNullGatePatchID = "system-virtualaudio-cfw-device_state_null_gate"
+
/// Where progress goes when the caller does not say.
public static let stdoutLog: @Sendable (String) -> Void = { print($0) }
@@ -224,6 +285,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,7 +362,36 @@ public enum CustomFirmwareVirtualAudio {
public let slotRehashes: [CustomFirmwareSlotRehash]
}
- // MARK: - Patching
+ /// One gated device-state update: the gate-check call the patch
+ /// redirects, the branch that tests its answer, and the singleton call
+ /// the update stands on.
+ public struct DeviceStateNullGateAnchor: Sendable, Equatable {
+ /// The `bl <gate check>` — the instruction the patch rewrites into
+ /// a `bl` to TheInstance.
+ public let gateCallFileOffset: Int
+ public let gateCallVMA: UInt64
+ /// The `cbz w0, <skip>` that now tests the singleton.
+ public let branchVMA: UInt64
+ /// Where the branch skips to when the singleton is null.
+ public let skipTargetVMA: UInt64
+ }
+
+ public struct DeviceStateNullGateReport: Sendable {
+ public let outcome: Outcome
+ /// TheInstance's entry, resolved from its own diagnostic.
+ public let theInstanceVMA: UInt64
+ public let sites: [DeviceStateNullGateAnchor]
+ public let records: [PatchRecord]
+ public let slotRehashes: [CustomFirmwareSlotRehash]
+ }
+
+ private static func wordAt(_ data: Data, _ offset: Int) -> UInt32? {
+ guard offset + 4 <= data.count else { return nil }
+ return UInt32(data[offset])
+ | UInt32(data[offset + 1]) << 8
+ | UInt32(data[offset + 2]) << 16
+ | UInt32(data[offset + 3]) << 24
+ }
/// Patch the VirtualAudio Mach-O at `url` in place.
///
@@ -417,14 +510,6 @@ public enum CustomFirmwareVirtualAudio {
)
}
- private static func wordAt(_ data: Data, _ offset: Int) -> UInt32? {
- guard offset + 4 <= data.count else { return nil }
- return UInt32(data[offset])
- | UInt32(data[offset + 1]) << 8
- | UInt32(data[offset + 2]) << 16
- | UInt32(data[offset + 3]) << 24
- }
-
// MARK: - Mute-set patching
/// Patch the VirtualAudio Mach-O at `url` in place, turning the mute-set
@@ -544,10 +629,10 @@ public enum CustomFirmwareVirtualAudio {
/// log block: its entry — the `mov w0, #<size>` that opens the os_log —
/// is rewritten into a branch back to the gate's fall-through, so a
/// taken gate lands straight on the success path the handler already
- /// built. The block is reachable only by the gate's jump (its
- /// predecessor is an unconditional branch, verified before writing) and
- /// that success path never reads the verdict the gate tested, on either
- /// supported build.
+ /// built. That path never reads the verdict the gate tested, on either
+ /// supported build, and the block is reached only by the gate's jump —
+ /// the instruction above it is an unconditional branch, checked before
+ /// anything is written.
///
/// Idempotent: a second run finds the log block's entry holding its own
/// unconditional branch, reports ``Outcome/alreadyPatched`` and leaves
@@ -806,6 +891,150 @@ public enum CustomFirmwareVirtualAudio {
)
}
+ // MARK: - Device-state null-gate patching
+
+ /// Patch the VirtualAudio Mach-O at `url` in place, making the two
+ /// device-state updates wait for the DeviceStateManager singleton
+ /// instead of dereferencing it when it does not exist.
+ ///
+ /// Each gate-check call — the `bl` whose answer the following
+ /// `cbz w0, <skip>` tests — is redirected to TheInstance, so that
+ /// branch now tests the singleton itself: null manager, the update is
+ /// skipped through the function's own path; manager present, the
+ /// fall-through re-calls TheInstance and the update runs untouched,
+ /// as designed. Applies only to an arm64e.x1 (cpusubtype 12) plugin:
+ /// every other build reports ``Outcome/notArm64EX1`` and keeps its
+ /// bytes.
+ ///
+ /// Idempotent: a second run finds the gate slot already calling
+ /// TheInstance, 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 patchDeviceStateNullGate(
+ fileAt url: URL,
+ reattest: Bool = true,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = stdoutLog,
+ ) throws -> DeviceStateNullGateReport {
+ 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 patchDeviceStateNullGate(&data, reattest: reattest, dryRun: dryRun, log: log)
+ if data != before {
+ try data.write(to: url)
+ }
+ return report
+ }
+
+ /// In-memory form of ``patchDeviceStateNullGate(fileAt:reattest:dryRun:log:)``.
+ @discardableResult
+ public static func patchDeviceStateNullGate(
+ _ data: inout Data,
+ reattest: Bool = true,
+ dryRun: Bool = false,
+ log: ((String) -> Void)? = stdoutLog,
+ ) throws -> DeviceStateNullGateReport {
+ 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 null gate has nothing to do")
+ return DeviceStateNullGateReport(
+ outcome: .notArm64EX1,
+ theInstanceVMA: 0,
+ sites: [],
+ records: [],
+ slotRehashes: [],
+ )
+ case .notArm64:
+ break // not a thin arm64 image; the anchor below refuses it
+ }
+
+ let located = try locateDeviceStateNullGate(in: data)
+ log?(" [.] TheInstance 0x\(hex(located.theInstanceVMA)); \(located.sites.count) gated device-state update(s)")
+ let anchors = located.sites.map { site in
+ DeviceStateNullGateAnchor(
+ gateCallFileOffset: site.gateCall,
+ gateCallVMA: located.vma(site.gateCall),
+ branchVMA: located.vma(site.branch),
+ skipTargetVMA: site.target,
+ )
+ }
+
+ var records: [PatchRecord] = []
+ var written: [Int] = []
+ var alreadyPatched = 0
+ for site in located.sites {
+ let call = site.gateCall
+ let callVMA = located.vma(call)
+ let callInstruction = located.disasm.disassembleOne(in: data, at: call, address: callVMA)
+ if site.alreadyGated {
+ alreadyPatched += 1
+ log?(" [=] 0x\(hex(callVMA)): the gate already asks TheInstance")
+ continue
+ }
+ guard let redirect = ARM64Encoder.encodeBL(from: Int(callVMA), to: Int(located.theInstanceVMA)) else {
+ throw PatcherError.patchSiteNotFound(
+ "\(component): TheInstance at 0x\(hex(located.theInstanceVMA)) is out of "
+ + "branch range of the gate call at 0x\(hex(callVMA))",
+ )
+ }
+ let original = Data(data[call ..< call + 4])
+ if dryRun {
+ log?(" [.] dry-run — would call TheInstance from 0x\(hex(callVMA))")
+ continue
+ }
+ data.replaceSubrange(call ..< call + 4, with: redirect)
+ written.append(call)
+ records.append(PatchRecord(
+ patchID: deviceStateNullGatePatchID,
+ component: component,
+ fileOffset: call,
+ virtualAddress: callVMA,
+ originalBytes: original,
+ patchedBytes: redirect,
+ beforeDisasm: callInstruction?.description ?? "",
+ afterDisasm: redirect.map { String(format: "%02x", $0) }.joined(separator: " "),
+ description: "device-state gate check -> TheInstance",
+ ))
+ log?(" [+] 0x\(hex(callVMA)): \(callInstruction?.description ?? "") -> bl 0x\(hex(located.theInstanceVMA))")
+ }
+
+ if records.isEmpty, !dryRun {
+ log?(" [=] all \(alreadyPatched) gate(s) already ask TheInstance")
+ }
+
+ 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 DeviceStateNullGateReport(
+ 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 +1105,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 +1261,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 +1511,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 +1660,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 +1714,199 @@ public enum CustomFirmwareVirtualAudio {
return false
}
+ // MARK: - Device-state null-gate anchoring
+
+ /// One gated device-state update, in file-offset terms.
+ struct DeviceStateNullGateSite: Sendable {
+ /// The gate-check `bl` — the instruction the patch redirects.
+ let gateCall: Int
+ /// The `cbz w0, <skip>` that tests the call's answer.
+ let branch: Int
+ /// Where the branch skips to — past the whole update.
+ let target: UInt64
+ /// The gate slot already calls TheInstance: this patch's own
+ /// earlier write, recognised rather than repeated.
+ let alreadyGated: Bool
+ }
+
+ /// Everything the null-gate patch needs: TheInstance's own entry and
+ /// the gated callers whose gate-check calls it redirects.
+ struct DeviceStateNullGatePlan: Sendable {
+ let disasm: ARM64Disassembler
+ let textStart: Int
+ let textAddress: UInt64
+ let theInstanceOffset: Int
+ let sites: [DeviceStateNullGateSite]
+
+ 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 deviceStateNullGateSiteCount = 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 locateDeviceStateNullGate(in data: Data) throws -> DeviceStateNullGatePlan {
+ 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: [DeviceStateNullGateSite] = []
+ 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, theInstance: vma(theInstance),
+ ) {
+ sites.append(site)
+ }
+ }
+ guard sites.count == deviceStateNullGateSiteCount else {
+ throw PatcherError.patchSiteNotFound(
+ "\(component): expected exactly \(deviceStateNullGateSiteCount) gated device-state "
+ + "updates around TheInstance at 0x\(hex(vma(theInstance))), found \(sites.count)",
+ )
+ }
+
+ return DeviceStateNullGatePlan(
+ disasm: disasm,
+ textStart: textStart,
+ textAddress: text.address,
+ theInstanceOffset: theInstance,
+ sites: sites.sorted { $0.gateCall < $1.gateCall },
+ )
+ }
+
+ /// Whether a direct `bl` to TheInstance sits in the gated device-state
+ /// shape: a gate-check call at −8 (pristine, any callee — or
+ /// TheInstance again once this patch has redirected it), the `cbz w0`
+ /// at −4 skipping forward past the whole update, the singleton's
+ /// return moved aside at +4 (`mov xN, x0`), and that return
+ /// dereferenced unchecked at +8 (`ldr xM, [x0]`) — the read that
+ /// faults when nobody published. 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,
+ theInstance: UInt64,
+ ) -> DeviceStateNullGateSite? {
+ 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.rawValue == ARM64Register.x(0).rawValue,
+ 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: the call whose answer the branch below it tests.
+ guard let gateCall = disasm.disassembleOne(in: data, at: call - 8), gateCall.isCall,
+ let gateWord = wordAt(data, call - 8),
+ let gateCallee = ARM64Encoder.decodeBranchTarget(insn: gateWord, pc: vma(call - 8))
+ else { return nil }
+ // Pristine, the gate slot calls anything but TheInstance; once
+ // redirected, it calls TheInstance and the shape is our own work.
+ let alreadyGated = gateCallee == theInstance
+
+ guard let gateInsn = disasm.disassembleOne(in: data, at: call - 4),
+ gateInsn.mnemonic == "cbz",
+ let operands = gateInsn.detail?.operands, operands.count == 2,
+ operands[0].type == .register, operands[0].reg.rawValue == ARM64Register.w(0).rawValue,
+ let gateBranchWord = wordAt(data, call - 4),
+ let target = decodeConditionalBranchTarget(insn: gateBranchWord, pc: vma(call - 4))
+ else { return nil }
+ // The skip must clear the dereference: the branch and its target
+ // bracket the whole device-state update the patch gates.
+ guard target > vma(call + 8) else { return nil }
+ return DeviceStateNullGateSite(
+ gateCall: call - 8, branch: call - 4, target: target, alreadyGated: alreadyGated,
+ )
+ }
+
+ /// 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 +2152,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 +2230,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 +2428,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 +2485,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..e782e226 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,89 @@ 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 decodability = CustomFirmwareArm64eX1.SharedDecodability()
+ let decoders = (0 ..< workers).map { _ in CustomFirmwareArm64eX1.Decoder(shared: decodability) }
+ 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 +227,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 +238,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 +265,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 +330,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 +454,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 +485,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 b6478298..0c3150ea 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -31,6 +31,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"
@@ -243,6 +244,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",
@@ -512,6 +520,25 @@ public enum FirmwareGuestSystemPatchSet {
""",
target: .guestExecutable(path: "/Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio"),
),
+ VPhonePatchDeclaration(
+ identifier: virtualAudioDeviceStateNullGate,
+ title: "VirtualAudio device-state null gate",
+ summary: """
+ Makes VirtualAudio_Device's two device-state updates wait for the
+ DeviceStateManager singleton instead of dereferencing it when it does
+ not exist. On a guest with no haptic hardware deferred initialization
+ never constructs the manager, and a route push that arrives while the
+ gates answer true reads the null singleton and crash-loops audiomxd.
+ Each update's gate-check call is redirected to TheInstance, so the
+ branch that already skips the update on a failed check now tests the
+ singleton itself: no manager, the update is skipped through the
+ function's own path; manager present, the update runs exactly as
+ designed. 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",
@@ -579,6 +606,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",
@@ -641,6 +679,11 @@ public enum FirmwareGuestSystemPatchSet {
/// the virtio aggregate it already built.
public static let virtualAudioVolumeModePrecondition = "system-virtualaudio-cfw-volume_mode_precondition"
+ /// The two device-state updates made to wait for the DeviceStateManager
+ /// singleton instead of dereferencing it when no manager was ever
+ /// constructed — the null gate audiomxd crash-loops without.
+ public static let virtualAudioDeviceStateNullGate = "system-virtualaudio-cfw-device_state_null_gate"
+
/// 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.
@@ -673,6 +716,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 9955dfb6..255f0273 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_null_gate",
"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..9af2bac2 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,368 @@ 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 null gate
+
+ @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.patchDeviceStateNullGate(
+ &data,
+ reattest: false,
+ dryRun: true,
+ log: nil,
+ )
+ }
+ }
+
+ @Test
+ func `the null-gate anchor strings and record identity are stable`() {
+ #expect(CustomFirmwareVirtualAudio.deviceStateInstanceMissing == "TheInstance() called before SetInstance()")
+ #expect(CustomFirmwareVirtualAudio.deviceStateNullGatePatchID == "system-virtualaudio-cfw-device_state_null_gate")
+ }
+
+ /// 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 caller the shape must refuse — the haptic delegate's unguarded
+ // deref. Every instruction comes from the encoder or the frozen
+ // constants, and the layout is fixed so the 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 stub gate check, site 1 — the slot the patch rewrites
+ // text+0x14 cbz w0, +0x20 the branch that tests the answer
+ // 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+0x54 bl stub the haptic caller's release call
+ // text+0x58 bl TheInstance unguarded: no gate above it
+ // text+0x5c mov x20, x0
+ // text+0x60 ldr x21, [x0]
+ // text+0x64 nop, bl TheInstance a pass-through caller
+ static let deviceStateText = 0x108
+ static let deviceStateGateCall1 = 0x118
+ static let deviceStateGateCall2 = 0x138
+
+ /// The guarded plugin image. `gatedSites` builds only that many gated
+ /// updates (the refusal test wants fewer than two); the 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 = deviceStateText
+ let stub = theInstance + 0xC
+ func gatedSite(start: Int) throws -> [UInt32] {
+ 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: start + 4, 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: deviceStateText + 0x10 + index * 0x20)
+ }
+ // The haptic delegate's shape: the same unguarded deref, but the
+ // instruction above the call is a release call without a gate
+ // branch below it; then a caller that passes the singleton on.
+ let haptic = deviceStateText + 0x10 + gatedSites * 0x20
+ 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,
+ cstrings: [CustomFirmwareVirtualAudio.deviceStateInstanceMissing],
+ )
+ }
+
+ /// A thin arm64 plugin image: one __TEXT segment carrying `text` as
+ /// __text (address == file offset, like the real plugin) and
+ /// `cstrings` in __cstring from 0x2000, each page-aligned.
+ static func pluginImage(cpuSubtype: UInt32, text: [UInt32], cstrings: [String]) -> Data {
+ let textOffset = 32 + 72 + 2 * 80
+ let cstringOffset = textOffset + text.count * 4
+ var cstringBytes = [UInt8]()
+ for string in cstrings {
+ let padding = (0x1000 - cstringBytes.count % 0x1000) % 0x1000
+ cstringBytes += Array(repeating: 0, count: padding)
+ cstringBytes += Array("\(string)\0".utf8)
+ }
+ let total = cstringOffset + cstringBytes.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(cstringBytes.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 += cstringBytes
+ image += Array(repeating: 0, count: total - image.count)
+ return Data(image)
+ }
+
+ @Test
+ func `the gate calls are redirected to TheInstance, idempotently`() throws {
+ var data = try Self.deviceStateImage(cpuSubtype: Self.x1Subtype)
+ let pristine = data
+
+ let report = try CustomFirmwareVirtualAudio.patchDeviceStateNullGate(
+ &data, reattest: false, dryRun: false, log: nil,
+ )
+ #expect(report.outcome == .patched)
+ #expect(report.records.count == 2)
+ #expect(report.records.map(\.patchID) == [
+ CustomFirmwareVirtualAudio.deviceStateNullGatePatchID,
+ CustomFirmwareVirtualAudio.deviceStateNullGatePatchID,
+ ])
+ #expect(report.theInstanceVMA == UInt64(Self.deviceStateText))
+ #expect(report.sites.map(\.gateCallVMA) == [
+ UInt64(Self.deviceStateGateCall1), UInt64(Self.deviceStateGateCall2),
+ ])
+
+ // Each gate-check `bl` now calls TheInstance; the branches, the
+ // calls and the dereferences below them are untouched.
+ let changed = zip(pristine, data).enumerated().filter { $0.element.0 != $0.element.1 }.map(\.offset)
+ let slots = [Self.deviceStateGateCall1, Self.deviceStateGateCall2]
+ #expect(!changed.isEmpty)
+ #expect(changed.allSatisfy { offset in slots.contains { gate in gate <= offset && offset < gate + 4 } })
+ for gate in slots {
+ let redirect = try #require(ARM64Encoder.encodeBL(from: gate, to: Self.deviceStateText))
+ #expect(Data(data[gate ..< gate + 4]) == redirect)
+ }
+
+ // A second run recognises its own redirects and writes nothing.
+ let once = data
+ let again = try CustomFirmwareVirtualAudio.patchDeviceStateNullGate(
+ &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.patchDeviceStateNullGate(
+ &data, reattest: false, dryRun: true, log: nil,
+ )
+ #expect(report.outcome == .wouldPatch)
+ #expect(report.records.isEmpty)
+ #expect(data == pristine)
+ #expect(report.sites.map(\.gateCallVMA) == [
+ UInt64(Self.deviceStateGateCall1), UInt64(Self.deviceStateGateCall2),
+ ])
+ }
+
+ @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.patchDeviceStateNullGate(
+ &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.patchDeviceStateNullGate(
+ &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 a3e725ce..a53523e3 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
@@ -276,6 +276,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 f722d9b0..c82b4bc5 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -567,6 +567,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)
}
@@ -1572,6 +1575,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]),
@@ -1794,14 +1798,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 early publish 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.virtualAudioDeviceStateNullGate, "patch-virtualaudio-device-state-null-gate"),
]
let virtualAudioBundle = "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin"
let virtualAudioBinary = "\(virtualAudioBundle)/VirtualAudio"
@@ -2027,6 +2034,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",
@@ -3041,6 +3053,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..8d252559 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,74 @@ struct VPhoneCustomFirmwarePatchVirtualAudioVolumeGateCommand: ParsableCommand {
}
}
+// MARK: - patch-virtualaudio-device-state-null-gate
+
+struct VPhoneCustomFirmwarePatchVirtualAudioDeviceStateNullGateCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "patch-virtualaudio-device-state-null-gate",
+ abstract: "Make VirtualAudio's device-state updates wait for the DeviceStateManager singleton",
+ discussion: """
+ Publishing the speaker route wakes VirtualAudio_Device's update,
+ which pushes the route's state at DeviceStateManager twice, each
+ push behind its own capability gate. On a guest with no haptic
+ hardware deferred initialization never constructs the manager —
+ no "Ending Deferred Initialization" is ever logged and no thread
+ is parked inside it; it exits early — so TheInstance() returns
+ null forever, and a push that arrives while the gates answer true
+ dereferences it: audiomxd dies, at any time from seconds to
+ minutes into its life.
+
+ The patch makes each update wait for the manager to exist: the
+ gate-check call above each `cbz w0, <skip>` is redirected to
+ TheInstance itself, so the branch the function already carries —
+ the one that skips the update when its check answers false — now
+ tests the singleton. Null manager: the update is skipped through
+ the function's own path, exactly as on any build whose gates
+ answer false. Manager present: the fall-through re-calls
+ TheInstance and the whole update — the save, the dereference,
+ the lock, the push — runs untouched, as designed. Nothing is
+ removed; the update happens whenever there is a manager to
+ receive it.
+
+ The sites are anchored on the singleton's own diagnostic string
+ ("TheInstance() called before SetInstance()"), whose reference
+ lives inside the accessor; every direct call to it is 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 gate-check calls are redirected. 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 slot already calling TheInstance 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.patchDeviceStateNullGate(
+ fileAt: binary,
+ reattest: false,
+ dryRun: dryRun,
+ log: machOVerbLog,
+ )
+ }
+}
+
+// MARK: - patch-virtualaudio
// MARK: - patch-virtualaudio
struct VPhoneCustomFirmwarePatchVirtualAudioCommand: ParsableCommand {
@@ -586,6 +655,7 @@ enum VPhoneCustomFirmwareMachOVerbs {
VPhoneCustomFirmwarePatchVirtualAudioMuteCommand.self,
VPhoneCustomFirmwarePatchVirtualAudioSPGateCommand.self,
VPhoneCustomFirmwarePatchVirtualAudioVolumeGateCommand.self,
+ VPhoneCustomFirmwarePatchVirtualAudioDeviceStateNullGateCommand.self,
VPhoneCustomFirmwarePatchParavirtGPUIndexOffsetCommand.self,
]
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift
index 41977758..7fe9ca43 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift
@@ -590,6 +590,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 39bd9c98..c3dd46d4 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
@@ -257,6 +257,7 @@ struct VPhoneCustomFirmwareCommand: ParsableCommand {
VPhoneCustomFirmwarePatchHomePodAudioProductCommand.self,
VPhoneCustomFirmwarePatchHomePodCryptexClassCommand.self,
VPhoneCustomFirmwarePatchIPhoneProductCommand.self,
+ VPhoneCustomFirmwarePatchFoldableVMSubtypeCommand.self,
VPhoneCustomFirmwarePatchHapticsCommand.self,
VPhoneCustomFirmwarePatchMicrophoneArrayCommand.self,
] + VPhoneCustomFirmwareMachOVerbs.all + VPhoneCustomFirmwareDyldSharedCacheVerbs.all,
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
index 870a9e54..dc412fe7 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
@@ -107,10 +107,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>
@@ -134,6 +136,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_null_gate</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 4282353f..86cfa4c8 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
@@ -111,10 +111,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>
@@ -139,6 +141,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_null_gate</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/VPhoneGuestComponents/Accelerometer/VPhoneOrientationSink.m b/VPhoneGuestComponents/Accelerometer/VPhoneOrientationSink.m
index 704e35a2..eca3d913 100644
--- a/VPhoneGuestComponents/Accelerometer/VPhoneOrientationSink.m
+++ b/VPhoneGuestComponents/Accelerometer/VPhoneOrientationSink.m
@@ -70,9 +70,12 @@ static void vpOrientationDeliver(void) {
// accepting a raw device orientation. Source 1 is the accelerometer
// path; source 0 is treated as a non-raw interface update.
((void (*)(id, SEL, NSInteger, NSInteger))objc_msgSend)(manager, selector, orientation, 1);
- SEL refresh = sel_registerName("refreshEffectiveDeviceOrientation");
- if ([manager respondsToSelector:refresh])
- ((void (*)(id, SEL))objc_msgSend)(manager, refresh);
+ // The high-level update already recomputes effective orientation.
+ // On 24A94425, refreshEffectiveDeviceOrientation instead starts a
+ // CMDeviceOrientationManager, performs deviceOrientationBlocking,
+ // and posts that hardware sample back. A virtual guest has no
+ // physical sample: that poll erased our injected direction with
+ // Unknown (0). Do not replace virtual input with a hardware poll.
} else
((void (*)(id, SEL, NSInteger))objc_msgSend)(manager, selector, orientation);
dispatch_queue_t statusQueue;
diff --git a/VPhoneGuestComponents/DeviceHubFix/VPCMAngleManager.m b/VPhoneGuestComponents/DeviceHubFix/VPCMAngleManager.m
new file mode 100644
index 00000000..3acdf243
--- /dev/null
+++ b/VPhoneGuestComponents/DeviceHubFix/VPCMAngleManager.m
@@ -0,0 +1,383 @@
+// VPCMAngleManager.m — the hinge-angle manager stand-in for dtdeviceinfod.
+//
+// CoreDevice's hinge-angle stream (DeviceHub) ends, on the device, in the
+// DDI's dtdeviceinfod: CMAngleManager_Bridge resolves CoreMotion's
+// CMAngleManager and forwards the stream to it. On a guest the manager's
+// capability answer is NO — CoreMotion picks its motion capabilities from the
+// device tree's product-id, and the foldable token cannot be written without
+// crash-looping SpringBoard.
+//
+// Opening that one gate is not enough, and that was v4's crash: with
+// +[CMAngleManager isAvailable] answering YES, the bridge started the REAL
+// manager, whose MotionThread asserts when its own capability bits
+// (product-id) contradict the answer (dtdeviceinfod SIGABRT,
+// com.apple.CoreMotion.MotionThread, eight times over a DeviceHub connect).
+//
+// So the manager's whole ObjC surface is taken over here, and CoreMotion's
+// machinery never runs: isAvailable follows the vphone hinge provider, the
+// angle range is the virtual hinge's 0–180, and the update methods deliver
+// samples read from the provider's newest published sample
+// (VPhoneHingeLatest, com.apple.backboardd/mobile) — the same values the HID
+// service reports — wrapped in an object exposing the fields the bridge maps
+// into DeviceHingeAngleSnapshot (angleDegrees, mechanicalAngleDegrees,
+// velocityDegreesPerSeconds, the validity flags, state, eventPhase and
+// timestamp). The sample class subclasses CoreMotion's own CMAngleData when
+// that class exists, so a typed cast in the bridge still succeeds. The
+// bridge's queue argument is an NSOperationQueue (CMAngleData itself never
+// registered, measured on iOS 27.1), and samples are delivered onto it with
+// addOperationWithBlock:.
+
+#import <Foundation/Foundation.h>
+#import <objc/runtime.h>
+#include <dlfcn.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+// MARK: - Log (same file the rest of the dylib writes)
+
+static void vpMotionLog(NSString *format, ...) {
+ va_list arguments;
+ va_start(arguments, format);
+ NSString *line = [[NSString alloc] initWithFormat:format arguments:arguments];
+ va_end(arguments);
+ if (!line)
+ return;
+ int fd = open("/var/mobile/Library/Caches/vphone-devicehubfix.log",
+ O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0666);
+ if (fd < 0)
+ return;
+ fchmod(fd, 0666);
+ dprintf(fd, "pid=%d %s\n", getpid(), line.UTF8String);
+ close(fd);
+}
+
+// MARK: - The provider's newest sample
+
+static NSDictionary *vpLatestSample(void) {
+ CFPreferencesSynchronize(CFSTR("com.apple.backboardd"), CFSTR("mobile"), kCFPreferencesAnyHost);
+ CFPropertyListRef value = CFPreferencesCopyValue(CFSTR("VPhoneHingeLatest"),
+ CFSTR("com.apple.backboardd"),
+ CFSTR("mobile"), kCFPreferencesAnyHost);
+ id sample = CFBridgingRelease(value);
+ return [sample isKindOfClass:NSDictionary.class] ? sample : nil;
+}
+
+// The provider republishes its status through cfprefsd. Freshness is NOT part
+// of the test: the status heartbeat only runs while samples flow, so with no
+// HID subscriber the stamp goes stale though the provider is alive. The pid is
+// backboardd's, a launchd-critical process the guest reboots without — but
+// dtdeviceinfod (mobile) cannot signal backboardd (root), so kill answers
+// EPERM for a LIVE process; that counts as alive. Anything else that fails
+// (ESRCH) really is gone.
+static BOOL vpProviderIsRunning(void) {
+ CFPreferencesSynchronize(CFSTR("com.apple.backboardd"), CFSTR("mobile"), kCFPreferencesAnyHost);
+ CFPropertyListRef status = CFPreferencesCopyValue(CFSTR("VPhoneHingeStatus"),
+ CFSTR("com.apple.backboardd"),
+ CFSTR("mobile"), kCFPreferencesAnyHost);
+ CFDictionaryRef dict = status && CFGetTypeID(status) == CFDictionaryGetTypeID()
+ ? (CFDictionaryRef)status : NULL;
+ const void *enumerated = dict ? CFDictionaryGetValue(dict, CFSTR("enumerated")) : NULL;
+ const void *pid = dict ? CFDictionaryGetValue(dict, CFSTR("pid")) : NULL;
+ BOOL running = NO;
+ if (enumerated && CFGetTypeID(enumerated) == CFBooleanGetTypeID() &&
+ CFBooleanGetValue(enumerated) &&
+ pid && CFGetTypeID(pid) == CFNumberGetTypeID()) {
+ int value = 0;
+ CFNumberGetValue(pid, kCFNumberIntType, &value);
+ if (value > 1) {
+ if (kill(value, 0) == 0)
+ running = YES;
+ else
+ running = errno == EPERM;
+ }
+ // One diagnosis per process, so a closed gate explains itself in the log.
+ static int logged = 0;
+ if (!running && !logged++) {
+ int reason = errno;
+ vpMotionLog(@"hinge manager: gate closed — pid=%d kill_errno=%d (ESRCH=3 dead, EPERM=1 alive-but-unsignalable)",
+ value, reason);
+ }
+ }
+ if (status)
+ CFRelease(status);
+ return running;
+}
+
+// MARK: - The sample object
+
+typedef struct {
+ double angle;
+ double mechanical;
+ double velocity;
+ double timestamp;
+ BOOL angleValid;
+ BOOL velocityValid;
+ long state;
+ long phase;
+} VPAngleSampleFields;
+
+static Class VPAngleDataClass;
+static ptrdiff_t VPAngleDataOffset;
+
+#define VP_SAMPLE_GETTER(name, field, types) \
+ class_addMethod(VPAngleDataClass, sel_registerName(name), \
+ imp_implementationWithBlock(^(id self) { \
+ return ((VPAngleSampleFields *)((char *)(__bridge void *)self + VPAngleDataOffset))->field; \
+ }), types)
+
+static void vpRegisterAngleDataClass(void) {
+ // Subclass CoreMotion's own data class when it exists, so a typed cast in
+ // the bridge still succeeds; the getters are replaced either way.
+ Class base = objc_getClass("CMAngleData");
+ if (!base)
+ base = [NSObject class];
+ VPAngleDataClass = objc_allocateClassPair(base, "VPCMAngleData", 0);
+ if (!VPAngleDataClass)
+ return;
+ if (!class_addIvar(VPAngleDataClass, "fields", sizeof(VPAngleSampleFields),
+ 0, @encode(VPAngleSampleFields))) {
+ VPAngleDataClass = NULL;
+ return;
+ }
+ objc_registerClassPair(VPAngleDataClass);
+ VPAngleDataOffset = ivar_getOffset(class_getInstanceVariable(VPAngleDataClass, "fields"));
+ // The fields CMAngleManager_Bridge maps into DeviceHingeAngleSnapshot,
+ // with both spellings of the two flags.
+ VP_SAMPLE_GETTER("angleDegrees", angle, "d16@0:8");
+ VP_SAMPLE_GETTER("mechanicalAngleDegrees", mechanical, "d16@0:8");
+ VP_SAMPLE_GETTER("velocityDegreesPerSeconds", velocity, "d16@0:8");
+ VP_SAMPLE_GETTER("timestamp", timestamp, "d16@0:8");
+ VP_SAMPLE_GETTER("isAngleValid", angleValid, "B16@0:8");
+ VP_SAMPLE_GETTER("angleValid", angleValid, "B16@0:8");
+ VP_SAMPLE_GETTER("isVelocityValid", velocityValid, "B16@0:8");
+ VP_SAMPLE_GETTER("velocityValid", velocityValid, "B16@0:8");
+ VP_SAMPLE_GETTER("state", state, "q16@0:8");
+ VP_SAMPLE_GETTER("eventPhase", phase, "q16@0:8");
+}
+
+static id vpAngleDataFromSample(NSDictionary *latest) {
+ if (!VPAngleDataClass)
+ return nil;
+ id data = [VPAngleDataClass new];
+ VPAngleSampleFields *fields = (VPAngleSampleFields *)((char *)(__bridge void *)data + VPAngleDataOffset);
+ fields->angle = [latest[@"angle"] doubleValue];
+ fields->mechanical = [latest[@"mechanical_angle"] doubleValue];
+ fields->velocity = [latest[@"velocity"] doubleValue];
+ fields->timestamp = [latest[@"timestamp"] doubleValue];
+ fields->angleValid = latest[@"angle"] != nil;
+ fields->velocityValid = latest[@"velocity"] != nil;
+ fields->state = [latest[@"state"] longValue];
+ fields->phase = [latest[@"event_phase"] longValue];
+ return data;
+}
+
+// MARK: - The update session
+
+@interface VPAngleSession : NSObject
+// CoreMotion's queue argument is an NSOperationQueue, like CMMotionManager's
+// start...UpdatesToQueue: (that was v5's crash — dispatch_async on an
+// NSOperationQueue made libdispatch vtable-dispatch through a non-dispatch
+// object and die with EXC_ARM_PAC_FAIL). Held as id and dispatched by kind.
+@property (nonatomic, strong) id deliveryQueue;
+@property (nonatomic, copy) void (^handler)(id data);
+@property (nonatomic) NSTimeInterval interval;
+@property (nonatomic, strong) dispatch_source_t timer;
+@end
+
+@implementation VPAngleSession
+- (void)dealloc {
+ if (_timer)
+ dispatch_source_cancel(_timer);
+}
+@end
+
+static char vpSessionKey;
+
+static dispatch_queue_t vpTimerQueue(void) {
+ static dispatch_queue_t queue;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{ queue = dispatch_queue_create("com.vphone.devicehubfix.angle", DISPATCH_QUEUE_SERIAL); });
+ return queue;
+}
+
+static NSTimeInterval vpClampInterval(NSTimeInterval interval) {
+ if (!isfinite(interval) || interval <= 0)
+ return 0;
+ return MIN(10.0, MAX(0.01, interval));
+}
+
+static void vpDeliver(VPAngleSession *session) {
+ if (!session.handler)
+ return;
+ id data = vpAngleDataFromSample(vpLatestSample());
+ if (!data)
+ return;
+ void (^handler)(id) = session.handler;
+ id queue = session.deliveryQueue;
+ if ([queue isKindOfClass:[NSOperationQueue class]])
+ [(NSOperationQueue *)queue addOperationWithBlock:^{ handler(data); }];
+ else if (queue)
+ dispatch_async((dispatch_queue_t)queue, ^{ handler(data); });
+ else
+ handler(data);
+}
+
+static void vpArmTimer(VPAngleSession *session) {
+ if (session.timer) {
+ dispatch_source_cancel(session.timer);
+ session.timer = nil;
+ }
+ if (!session.handler)
+ return;
+ dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, vpTimerQueue());
+ NSTimeInterval interval = session.interval > 0 ? session.interval : 0.1;
+ dispatch_source_set_timer(timer, DISPATCH_TIME_NOW,
+ (uint64_t)(interval * NSEC_PER_SEC), (uint64_t)(10 * NSEC_PER_MSEC));
+ // Weak, so the session dies with the manager and cancels the timer.
+ __weak VPAngleSession *weakSession = session;
+ dispatch_source_set_event_handler(timer, ^{
+ @autoreleasepool {
+ VPAngleSession *alive = weakSession;
+ if (alive)
+ vpDeliver(alive);
+ }
+ });
+ dispatch_resume(timer);
+ session.timer = timer;
+}
+
+static VPAngleSession *vpSession(id manager) {
+ VPAngleSession *session = objc_getAssociatedObject(manager, &vpSessionKey);
+ if (!session) {
+ session = [VPAngleSession new];
+ objc_setAssociatedObject(manager, &vpSessionKey, session, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ }
+ return session;
+}
+
+// MARK: - The swapped CMAngleManager surface
+
+static IMP vpOriginalIsAvailableIMP;
+__attribute__((used)) static IMP vpOriginalStartIMP;
+__attribute__((used)) static IMP vpOriginalSetHandlerIMP;
+__attribute__((used)) static IMP vpOriginalStopIMP;
+__attribute__((used)) static IMP vpOriginalActiveIMP;
+__attribute__((used)) static IMP vpOriginalGetIntervalIMP;
+__attribute__((used)) static IMP vpOriginalSetIntervalIMP;
+
+static BOOL vpSwizzledIsAvailable(id self, SEL selector) {
+ if (vpProviderIsRunning())
+ return YES;
+ return ((BOOL (*)(id, SEL))vpOriginalIsAvailableIMP)(self, selector);
+}
+
+static double vpSwizzledMinAngle(id self, SEL selector) { return 0.0; }
+static double vpSwizzledMaxAngle(id self, SEL selector) { return 180.0; }
+
+static void vpSwizzledStartUpdates(id self, SEL selector, id queue, id handler) {
+ VPAngleSession *session = vpSession(self);
+ session.deliveryQueue = queue;
+ session.handler = [handler copy];
+ vpArmTimer(session);
+}
+
+static void vpSwizzledSetHandler(id self, SEL selector, id handler, double interval) {
+ VPAngleSession *session = vpSession(self);
+ session.deliveryQueue = nil;
+ session.interval = vpClampInterval(interval);
+ session.handler = [handler copy];
+ vpArmTimer(session);
+}
+
+static void vpSwizzledStopUpdates(id self, SEL selector) {
+ VPAngleSession *session = objc_getAssociatedObject(self, &vpSessionKey);
+ session.handler = nil;
+ if (session.timer) {
+ dispatch_source_cancel(session.timer);
+ session.timer = nil;
+ }
+}
+
+static BOOL vpSwizzledIsAngleActive(id self, SEL selector) {
+ VPAngleSession *session = objc_getAssociatedObject(self, &vpSessionKey);
+ return session.handler != nil && session.timer != nil;
+}
+
+static double vpSwizzledAngleUpdateInterval(id self, SEL selector) {
+ VPAngleSession *session = objc_getAssociatedObject(self, &vpSessionKey);
+ return session.interval > 0 ? session.interval : 0.1;
+}
+
+static void vpSwizzledSetAngleUpdateInterval(id self, SEL selector, double interval) {
+ VPAngleSession *session = vpSession(self);
+ session.interval = vpClampInterval(interval);
+ if (session.handler)
+ vpArmTimer(session);
+}
+
+// MARK: - Install
+
+__attribute__((constructor)) static void vpInstallAngleManagerStandIn(void) {
+ if (strcmp(getprogname(), "dtdeviceinfod") != 0)
+ return;
+ dlopen("/System/Library/Frameworks/CoreMotion.framework/CoreMotion", RTLD_LAZY | RTLD_LOCAL);
+ Class manager = objc_getClass("CMAngleManager");
+ if (!manager) {
+ vpMotionLog(@"hinge manager: CMAngleManager not found, CoreDevice hingeAngle stays off");
+ return;
+ }
+ vpRegisterAngleDataClass();
+
+ Method available = class_getClassMethod(manager, sel_registerName("isAvailable"));
+ if (available) {
+ vpOriginalIsAvailableIMP = method_getImplementation(available);
+ method_setImplementation(available, (IMP)vpSwizzledIsAvailable);
+ }
+ Method min = class_getClassMethod(manager, sel_registerName("minAngleDegrees"));
+ if (min)
+ method_setImplementation(min, (IMP)vpSwizzledMinAngle);
+ Method max = class_getClassMethod(manager, sel_registerName("maxAngleDegrees"));
+ if (max)
+ method_setImplementation(max, (IMP)vpSwizzledMaxAngle);
+
+ // The instance methods the bridge drives. Every one replaced means one
+ // less path into CoreMotion's own MotionThread.
+ Method start = class_getInstanceMethod(manager, sel_registerName("startAngleUpdatesToQueue:handler:"));
+ if (start) {
+ vpOriginalStartIMP = method_getImplementation(start);
+ method_setImplementation(start, (IMP)vpSwizzledStartUpdates);
+ }
+ Method setHandler = class_getInstanceMethod(manager, sel_registerName("setAngleHandler:interval:"));
+ if (setHandler) {
+ vpOriginalSetHandlerIMP = method_getImplementation(setHandler);
+ method_setImplementation(setHandler, (IMP)vpSwizzledSetHandler);
+ }
+ Method stop = class_getInstanceMethod(manager, sel_registerName("stopAngleUpdates"));
+ if (stop) {
+ vpOriginalStopIMP = method_getImplementation(stop);
+ method_setImplementation(stop, (IMP)vpSwizzledStopUpdates);
+ }
+ Method active = class_getInstanceMethod(manager, sel_registerName("isAngleActive"));
+ if (active) {
+ vpOriginalActiveIMP = method_getImplementation(active);
+ method_setImplementation(active, (IMP)vpSwizzledIsAngleActive);
+ }
+ Method getInterval = class_getInstanceMethod(manager, sel_registerName("angleUpdateInterval"));
+ if (getInterval) {
+ vpOriginalGetIntervalIMP = method_getImplementation(getInterval);
+ method_setImplementation(getInterval, (IMP)vpSwizzledAngleUpdateInterval);
+ }
+ Method setInterval = class_getInstanceMethod(manager, sel_registerName("setAngleUpdateInterval:"));
+ if (setInterval) {
+ vpOriginalSetIntervalIMP = method_getImplementation(setInterval);
+ method_setImplementation(setInterval, (IMP)vpSwizzledSetAngleUpdateInterval);
+ }
+
+ BOOL sampleReady = VPAngleDataClass != NULL;
+ vpMotionLog(@"hinge manager: stand-in v6 installed (start=%@ setHandler=%@ stop=%@ active=%@ interval=%@ sample=%@ base=%@)",
+ start ? @"yes" : @"MISSING", setHandler ? @"yes" : @"missing", stop ? @"yes" : @"missing",
+ active ? @"yes" : @"missing", getInterval ? @"yes" : @"missing",
+ sampleReady ? @"ready" : @"MISSING",
+ VPAngleDataClass ? class_getSuperclass(VPAngleDataClass) : nil);
+}
diff --git a/VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c b/VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c
index 573df52a..fc5950e5 100644
--- a/VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c
+++ b/VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c
@@ -98,6 +98,19 @@
// can meet it. That costs one scaler round trip per frame, 0.5–1 ms past the
// write the band reads used to wait for on the host anyway.
//
+// ## dtdeviceinfod: the hinge-angle capability
+//
+// CoreDevice (DeviceHub) asks the DDI whether the device has a hinge; the
+// DDI's dtdeviceinfod answers through CoreMotion's CMAngleManager, whose
+// availability CoreMotion keys on the device-tree product-id a single-display
+// guest cannot carry. Opening only the availability gate (v4) crash-looped
+// dtdeviceinfod: the bridge then started the REAL manager, whose MotionThread
+// asserts when its capability bits contradict the answer. The manager's whole
+// ObjC surface is replaced instead — VPCMAngleManager.m in this folder — so
+// CoreMotion's machinery never runs and the samples come from libvphonehinge's
+// published latest sample. Only when that provider is live does the
+// capability answer open; otherwise everything falls back to the original.
+//
// ## Reach
//
// The interposes reach their callers because cryptexd, dtremotedisplayd,
@@ -115,6 +128,7 @@
#include <fcntl.h>
#include <objc/runtime.h>
#include <pthread.h>
+#include <signal.h>
#include <stdarg.h>
#include <stdatomic.h>
#include <stdio.h>
@@ -341,7 +355,11 @@ __attribute__((constructor)) static void vpInstallScalerBarrier(void) {
vpLog("VCPSideCarMetal band reads %s, %s", "found", "they wait for the scaler");
}
-int vphone_devicehubfix_version(void) { return 3; }
+int vphone_devicehubfix_version(void) { return 6; }
+
+// The CMAngleManager stand-in for dtdeviceinfod lives in VPCMAngleManager.m
+// (same dylib): it swaps the manager's whole ObjC surface and feeds the
+// bridge from the hinge provider's published samples.
__attribute__((used, section("__DATA,__interpose"))) static const struct {
const void *replacement;
diff --git a/VPhoneGuestComponents/FoldDisplay/StatusProfile.inc b/VPhoneGuestComponents/FoldDisplay/StatusProfile.inc
new file mode 100644
index 00000000..99cc1079
--- /dev/null
+++ b/VPhoneGuestComponents/FoldDisplay/StatusProfile.inc
@@ -0,0 +1,251 @@
+// Used only as an argument to the native, read-only provider factory. Never
+// register this proxy with UIKit or publish its reference bounds to a scene.
+@interface VPhoneStatusScreenPreview : NSProxy
+@property(nonatomic, strong) id source;
+@property(nonatomic, strong) id previewExclusion;
+@property(nonatomic) CGRect referenceBounds;
+@property(nonatomic) BOOL skipEmbeddedCache;
+@end
+@implementation VPhoneStatusScreenPreview
+- (CGRect)_nativeDisplayBounds { return self.referenceBounds; }
+- (id)_exclusionArea { return self.previewExclusion ?: vpReadObject(self.source, "_exclusionArea"); }
+- (BOOL)_isEmbeddedScreen { return self.skipEmbeddedCache ? NO : vpReadBoolValue(self.source, "_isEmbeddedScreen").boolValue; }
+- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { return [self.source methodSignatureForSelector:selector]; }
+- (void)forwardInvocation:(NSInvocation *)invocation { [invocation invokeWithTarget:self.source]; }
+- (BOOL)respondsToSelector:(SEL)selector {
+ return selector == @selector(_nativeDisplayBounds) || selector == @selector(_exclusionArea) ||
+ selector == @selector(_isEmbeddedScreen) || [self.source respondsToSelector:selector];
+}
+@end
+
+static Class vpMainStatusClassLookup(id screen, id info) {
+ Class (*original)(id, id) = vpOriginalMainStatusClassLookup;
+ if (!vpMainStatusProfileEnabled || ![NSThread isMainThread]) return original(screen, info);
+ id root = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ id identity = vpReadObject(screen, "displayIdentity");
+ NSArray *bounds = vpSnapshotRect(root, "bounds");
+ BOOL inner = [bounds isEqual:@[@0, @0, @669, @951]];
+ BOOL cover = [bounds isEqual:@[@0, @0, @466, @678]];
+ if (![identity isEqual:vpReadObject(root, "identity")] ||
+ screen != vpReadObject(vpMainStatusProfileScene, "screen") ||
+ !(inner || cover)) return original(screen, info);
+ Class profile = objc_getClass(inner ? "STUIStatusBarVisualProvider_AxisAlignableSplit2007" :
+ "STUIStatusBarVisualProvider_AxisAlignableSplitV68Cover");
+ SEL notchSelector = sel_registerName("notchSize");
+ NSMethodSignature *notchSignature = [profile methodSignatureForSelector:notchSelector];
+ if (notchSignature.methodReturnLength != sizeof(CGSize)) return original(screen, info);
+ CGSize notch = ((CGSize (*)(id, SEL))objc_msgSend)(profile, notchSelector);
+ Class shapeClass = objc_getClass("UISDisplaySingleRectShape");
+ SEL initializer = sel_registerName("initWithRect:");
+ NSMethodSignature *shapeSignature = [shapeClass instanceMethodSignatureForSelector:initializer];
+ if (shapeSignature.numberOfArguments != 3 ||
+ strcmp([shapeSignature getArgumentTypeAtIndex:2], "{CGRect={CGPoint=dd}{CGSize=dd}}") != 0) return original(screen, info);
+ VPhoneStatusScreenPreview *preview = [VPhoneStatusScreenPreview alloc];
+ preview.source = screen;
+ preview.referenceBounds = inner ? CGRectMake(0, 0, 2007, 2853) : CGRectMake(0, 0, 1398, 2034);
+ preview.skipEmbeddedCache = YES;
+ preview.previewExclusion = ((id (*)(id, SEL, CGRect))objc_msgSend)([shapeClass alloc], initializer,
+ CGRectMake(0, 0, notch.width, notch.height));
+ Class selected = original(preview, info);
+ if (selected != profile) return original(screen, info);
+ if (vpMainStatusProfileLogCount++ < 8)
+ vpFoldDisplayLog([NSString stringWithFormat:@"Main status profile: native %@ lookup accepted; original data/screen/identity retained", inner ? @"inner" : @"cover"]);
+ return selected;
+}
+
+static void vpInstallMainStatusLookup(void) {
+ void *target = dlsym(RTLD_DEFAULT, "STUIStatusBarGetVisualProviderClassForScreen");
+ MISFixDetourResult (*install)(const char *, void *, void *, void **) = dlsym(RTLD_DEFAULT, "MISFixDetour");
+ if (!target || !install) { vpFoldDisplayLog(@"Main status profile: native lookup/detour API unavailable"); return; }
+ MISFixDetourResult result = install("Duo Main native status profile", target, (void *)vpMainStatusClassLookup,
+ &vpOriginalMainStatusClassLookup);
+ vpFoldDisplayLog([NSString stringWithFormat:@"Main status profile: constructor detour result=%d", result]);
+}
+
+static void vpRefreshMainStatusRenderer(void) {
+ id scene = vpMainStatusProfileScene;
+ if (!scene) return;
+ id wrapper = vpReadObject(vpReadObject(scene, "statusBarManager"), "statusBar");
+ id renderer = vpReadObject(wrapper, "statusBar");
+ // resetVisualProvider resets region/item/alpha dictionaries only. Clear
+ // the native class cache (never assign a replacement class), then use
+ // the native full reconstruction that releases provider/foreground.
+ Method clear = class_getInstanceMethod(object_getClass(renderer), sel_registerName("_setVisualProviderClass:"));
+ if (clear && strcmp(method_getTypeEncoding(clear), "v24@0:8#16") == 0)
+ ((void (*)(id, SEL, Class))objc_msgSend)(renderer, sel_registerName("_setVisualProviderClass:"), Nil);
+ for (NSString *name in @[@"reinitializeStatusBar", @"setNeedsLayout", @"layoutIfNeeded"]) {
+ SEL selector = NSSelectorFromString(name);
+ Method method = class_getInstanceMethod(object_getClass(renderer), selector);
+ if (method && strcmp(method_getTypeEncoding(method), "v16@0:8") == 0)
+ ((void (*)(id, SEL))objc_msgSend)(renderer, selector);
+ }
+ Method data = class_getInstanceMethod(object_getClass(wrapper), sel_registerName("forceUpdateData:"));
+ if (data && strcmp(method_getTypeEncoding(data), "v20@0:8B16") == 0)
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(wrapper, sel_registerName("forceUpdateData:"), YES);
+ Method force = class_getInstanceMethod(object_getClass(wrapper), sel_registerName("forceUpdate:"));
+ if (force && strcmp(method_getTypeEncoding(force), "v20@0:8B16") == 0)
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(wrapper, sel_registerName("forceUpdate:"), YES);
+}
+
+static void vpRestoreMainStatusProfile(void) {
+ if (vpAutomaticMainStatus) { vpRefreshMainStatusRenderer(); return; }
+ if (!vpMainStatusProfileEnabled && !vpMainStatusProfileScene) return;
+ vpMainStatusProfileEnabled = NO;
+ vpMainStatusProfileGeneration++;
+ if (!vpMainStatusProfileScene) { vpMainStatusOriginalProviderClass = Nil; return; }
+ vpRefreshMainStatusRenderer();
+ id wrapper = vpReadObject(vpReadObject(vpMainStatusProfileScene, "statusBarManager"), "statusBar");
+ Class current = object_getClass(vpReadObject(vpReadObject(wrapper, "statusBar"), "visualProvider"));
+ if (vpMainStatusOriginalProviderClass && current != vpMainStatusOriginalProviderClass) {
+ vpFoldDisplayLog(@"Main status profile: provider restoration pending; checkpoint retained"); return;
+ }
+ vpMainStatusProfileScene = nil;
+ vpMainStatusOriginalProviderClass = Nil;
+ vpFoldDisplayLog(@"Main status profile: native lookup behavior restored");
+}
+
+static void vpPulseMainStatusProfile(void) {
+ if (!vpOriginalMainStatusClassLookup || vpUIConfigPublished) return;
+ if (vpMainStatusProfileScene) {
+ id wrapper = vpReadObject(vpReadObject(vpMainStatusProfileScene, "statusBarManager"), "statusBar");
+ if (!vpReadObject(vpReadObject(wrapper, "statusBar"), "currentData")) vpRefreshMainStatusRenderer();
+ return;
+ }
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ id scene = vpReadObject(app, "activeDisplayWindowScene") ?: vpReadObject(app, "embeddedDisplayWindowScene");
+ id identity = vpReadObject(scene, "_fbsDisplayIdentity");
+ id root = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ NSArray *bounds = vpSnapshotRect(root, "bounds");
+ if (!scene || ![[identity valueForKey:@"isMainDisplay"] boolValue] ||
+ ![identity isEqual:vpReadObject(root, "identity")] ||
+ ![vpReadObject(vpReadObject(scene, "_FBSScene"), "identifier") isEqual:@"SB-main"] ||
+ (!([bounds isEqual:@[@0, @0, @669, @951]]) && !([bounds isEqual:@[@0, @0, @466, @678]]))) return;
+ vpMainStatusProfileScene = scene;
+ id wrapper = vpReadObject(vpReadObject(scene, "statusBarManager"), "statusBar");
+ vpMainStatusOriginalProviderClass = object_getClass(vpReadObject(vpReadObject(wrapper, "statusBar"), "visualProvider"));
+ vpMainStatusProfileLogCount = 0;
+ vpMainStatusProfileEnabled = YES;
+ unsigned int generation = ++vpMainStatusProfileGeneration;
+ vpFoldDisplayLog(vpAutomaticMainStatus ? @"Main status profile: persistent native Duo profile enabled" :
+ @"Main status profile: eight-second native metadata lookup lease; no UI identity migration");
+ vpRefreshMainStatusRenderer();
+ if (vpAutomaticMainStatus) return;
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 8 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ if (generation == vpMainStatusProfileGeneration) vpRestoreMainStatusProfile();
+ });
+}
+
+static Class vpStatusProfileFactoryAtIndex(NSUInteger index, id self, SEL selector, id screen, id info) {
+ Class (*original)(id, SEL, id, id) = (void *)vpOriginalStatusProfileFactories[index];
+ // This is a reference-metric lookup only. Native provider construction
+ // continues with its real screen; no UIView geometry/provider class is set.
+ if (!vpStatusProfileLookupEnabled || ![NSThread isMainThread] || vpStatusProfileFactoryDepth)
+ return original(self, selector, screen, info);
+ BOOL ownedConstruction = vpStatusProfileConstructionScene == (__bridge void *)vpStatusProfileScene;
+ BOOL sameScreen = screen == vpReadObject(vpStatusProfileScene, "screen");
+ if (vpStatusProfileCallCount++ < 12)
+ vpFoldDisplayLog([NSString stringWithFormat:@"status profile factory call: class=%@ sameScreen=%d ownedConstruction=%d",
+ NSStringFromClass(self), sameScreen, ownedConstruction]);
+ if (!vpUIConfigPublished || vpStatusProfileScene != vpUIConfigWindowScene ||
+ !(sameScreen || ownedConstruction) || vpMainInnerWindowScene() != vpStatusProfileScene)
+ return original(self, selector, screen, info);
+ Class profile = objc_getClass("STUIStatusBarVisualProvider_AxisAlignableSplit2007");
+ SEL notchSelector = sel_registerName("notchSize");
+ NSMethodSignature *notchSignature = [profile methodSignatureForSelector:notchSelector];
+ if (notchSignature.methodReturnLength != sizeof(CGSize)) return original(self, selector, screen, info);
+ CGSize notch = ((CGSize (*)(id, SEL))objc_msgSend)(profile, notchSelector);
+ if (notch.width <= 0 || notch.height <= 0) return original(self, selector, screen, info);
+ Class shapeClass = objc_getClass("UISDisplaySingleRectShape");
+ SEL initializer = sel_registerName("initWithRect:");
+ NSMethodSignature *shapeSignature = [shapeClass instanceMethodSignatureForSelector:initializer];
+ if (shapeSignature.numberOfArguments != 3 ||
+ strcmp([shapeSignature getArgumentTypeAtIndex:2], "{CGRect={CGPoint=dd}{CGSize=dd}}") != 0)
+ return original(self, selector, screen, info);
+ VPhoneStatusScreenPreview *preview = [VPhoneStatusScreenPreview alloc];
+ preview.source = screen;
+ preview.referenceBounds = CGRectMake(0, 0, 2007, 2853);
+ preview.previewExclusion = ((id (*)(id, SEL, CGRect))objc_msgSend)([shapeClass alloc], initializer,
+ CGRectMake(0, 0, notch.width, notch.height));
+ Class selected = Nil;
+ vpStatusProfileFactoryDepth++;
+ @try { selected = original(self, selector, preview, info); }
+ @finally { vpStatusProfileFactoryDepth--; }
+ // The native factory, not a returned constant, must accept this profile.
+ if (selected != profile) return original(self, selector, screen, info);
+ if (vpStatusProfileCallCount++ < 20)
+ vpFoldDisplayLog(@"status profile lookup: native factory accepted inner reference metrics; real screen retained");
+ return selected;
+}
+
+static Class vpStatusProfileFactoryIOS(id self, SEL selector, id screen, id info) { return vpStatusProfileFactoryAtIndex(0, self, selector, screen, info); }
+static Class vpStatusProfileFactoryPhone(id self, SEL selector, id screen, id info) { return vpStatusProfileFactoryAtIndex(1, self, selector, screen, info); }
+static Class vpStatusProfileFactorySplit(id self, SEL selector, id screen, id info) { return vpStatusProfileFactoryAtIndex(2, self, selector, screen, info); }
+static Class vpStatusProfileFactoryAxis(id self, SEL selector, id screen, id info) { return vpStatusProfileFactoryAtIndex(3, self, selector, screen, info); }
+static const char *vpStatusProfileFactoryClasses[] = {"STUIStatusBarVisualProvider_iOS", "STUIStatusBarVisualProvider_Phone",
+ "STUIStatusBarVisualProvider_Split", "STUIStatusBarVisualProvider_AxisAlignableSplit"};
+static IMP vpStatusProfileFactoryReplacements[] = {(IMP)vpStatusProfileFactoryIOS, (IMP)vpStatusProfileFactoryPhone,
+ (IMP)vpStatusProfileFactorySplit, (IMP)vpStatusProfileFactoryAxis};
+
+static void vpResetManagedStatusProvider(void) {
+ id scene = vpStatusProfileScene;
+ if (!scene || scene != vpUIConfigWindowScene) return;
+ id renderer = vpReadObject(vpReadObject(vpReadObject(scene, "statusBarManager"), "statusBar"), "statusBar");
+ SEL reset = sel_registerName("resetVisualProvider");
+ Method method = class_getInstanceMethod(object_getClass(renderer), reset);
+ void *previousScope = vpStatusProfileConstructionScene;
+ @try {
+ if (vpStatusProfileLookupEnabled) vpStatusProfileConstructionScene = (__bridge void *)scene;
+ if (method && strcmp(method_getTypeEncoding(method), "v16@0:8") == 0)
+ ((void (*)(id, SEL))objc_msgSend)(renderer, reset);
+ for (NSString *name in @[@"setNeedsLayout", @"layoutIfNeeded"])
+ if ([renderer respondsToSelector:NSSelectorFromString(name)]) ((void (*)(id, SEL))objc_msgSend)(renderer, NSSelectorFromString(name));
+ } @finally { vpStatusProfileConstructionScene = previousScope; }
+}
+
+static void vpRestoreStatusProfileLookup(void) {
+ if (!vpStatusProfileLookupEnabled) return;
+ vpStatusProfileLookupEnabled = NO;
+ vpStatusProfileGeneration++;
+ for (NSUInteger index = 0; index < 4; index++) {
+ Method method = class_getClassMethod(objc_getClass(vpStatusProfileFactoryClasses[index]),
+ sel_registerName("visualProviderSubclassForScreen:visualProviderInfo:"));
+ if (method && vpOriginalStatusProfileFactories[index] && method_getImplementation(method) == vpStatusProfileFactoryReplacements[index])
+ method_setImplementation(method, vpOriginalStatusProfileFactories[index]);
+ }
+ vpResetManagedStatusProvider();
+ vpStatusProfileScene = nil;
+ vpFoldDisplayLog(@"status profile lookup: original factory restored");
+}
+
+static void vpPulseStatusProfileLookup(void) {
+ @try {
+ if (vpStatusProfileLookupEnabled || !vpUIConfigPublished || vpMainInnerWindowScene() != vpUIConfigWindowScene) return;
+ Method methods[4];
+ for (NSUInteger index = 0; index < 4; index++) {
+ methods[index] = class_getClassMethod(objc_getClass(vpStatusProfileFactoryClasses[index]),
+ sel_registerName("visualProviderSubclassForScreen:visualProviderInfo:"));
+ if (!methods[index] || strcmp(method_getTypeEncoding(methods[index]), "#32@0:8@16@24") != 0) return;
+ }
+ vpStatusProfileScene = vpUIConfigWindowScene;
+ vpStatusProfileCallCount = 0;
+ // Publish all original call targets before any replacement can run,
+ // including a concurrent factory call that will take the native path.
+ for (NSUInteger index = 0; index < 4; index++)
+ vpOriginalStatusProfileFactories[index] = method_getImplementation(methods[index]);
+ for (NSUInteger index = 0; index < 4; index++)
+ method_setImplementation(methods[index], vpStatusProfileFactoryReplacements[index]);
+ vpStatusProfileLookupEnabled = YES;
+ unsigned int generation = ++vpStatusProfileGeneration;
+ vpFoldDisplayLog(@"status profile lookup: eight-second owned UI reference-metric lease");
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 8 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ if (generation == vpStatusProfileGeneration) vpRestoreStatusProfileLookup();
+ });
+ } @catch (NSException *exception) {
+ vpRestoreStatusProfileLookup();
+ vpFoldDisplayLog([NSString stringWithFormat:@"status profile lookup exception: %@", exception.reason]);
+ }
+}
+
+static void vpSetCoverViewport(BOOL enabled) {
+ unsigned int generation = atomic_fetch_add_explicit(&vpViewportRequestGeneration, 1, memory_order_relaxed) + 1;
+ atomic_store_explicit(&vpCoverViewportEnabled, enabled, memory_order_release);
diff --git a/VPhoneGuestComponents/FoldDisplay/WallpaperTraitsExperiment.inc b/VPhoneGuestComponents/FoldDisplay/WallpaperTraitsExperiment.inc
new file mode 100644
index 00000000..1cd3b15a
--- /dev/null
+++ b/VPhoneGuestComponents/FoldDisplay/WallpaperTraitsExperiment.inc
@@ -0,0 +1,94 @@
+// One-process experiment for the native wallpaper traits pipeline. The
+// shipped domain plist lacks this named flag; every other query is native.
+static bool vpWallpaperFeatureLookup(const char *domain, const char *feature) {
+ if (domain && feature && strcmp(domain, "SpringBoard") == 0 &&
+ strcmp(feature, "TraitsArbiterWallpaperTokyoDrift") == 0) return true;
+ return ((bool (*)(const char *, const char *))vpOriginalWallpaperFeatureLookup)(domain, feature);
+}
+// Mirror the native pre-visibility role-hint assignment used by the managed
+// wallpaper branch, scoped to the existing Main-inner wallpaper window.
+static void vpWallpaperSetHidden(id self, SEL selector, BOOL hidden) {
+ if (!hidden && vpLogicalRoleExperiment && vpWallpaperTraitsExperimentInstalled) {
+ @try {
+ id scene = vpReadObject(self, "windowScene");
+ if (vpIsSingleMainStatusScene(scene, YES) && !vpReadObject(self, "_roleHint")) {
+ id __unsafe_unretained *address = (id __unsafe_unretained *)dlsym(RTLD_DEFAULT, "SBTraitsParticipantRoleWallpaper");
+ SEL setter = sel_registerName("_setRoleHint:");
+ NSMethodSignature *signature = [self methodSignatureForSelector:setter];
+ if (address && *address && signature.numberOfArguments == 3 &&
+ strcmp(signature.methodReturnType, "v") == 0 && [signature getArgumentTypeAtIndex:2][0] == '@') {
+ ((void (*)(id, SEL, id))objc_msgSend)(self, setter, *address);
+ vpFoldDisplayLog(@"wallpaper traits experiment: native wallpaper role assigned before visibility");
+ }
+ }
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"wallpaper role assignment exception: %@", exception.reason]);
+ }
+ }
+ ((void (*)(id, SEL, BOOL))vpOriginalWallpaperSetHidden)(self, selector, hidden);
+}
+
+static void vpInstallWallpaperTraitsExperiment(void) {
+ void *target = dlsym(RTLD_DEFAULT, "_os_feature_enabled_impl");
+ MISFixDetourResult (*install)(const char *, void *, void *, void **) = dlsym(RTLD_DEFAULT, "MISFixDetour");
+ if (!target || !install) { vpFoldDisplayLog(@"wallpaper traits experiment: native feature lookup unavailable"); return; }
+ MISFixDetourResult result = install("Duo wallpaper traits experiment", target, (void *)vpWallpaperFeatureLookup, &vpOriginalWallpaperFeatureLookup);
+ vpFoldDisplayLog([NSString stringWithFormat:@"wallpaper traits experiment: feature lookup result=%d", result]);
+ if (result == MISFixDetourOK) {
+ vpWallpaperTraitsExperimentInstalled = YES;
+ Class window = objc_getClass("_SBWallpaperSecureWindow");
+ SEL hidden = sel_registerName("setHidden:");
+ Method method = class_getInstanceMethod(window, hidden);
+ if (method && strcmp(method_getTypeEncoding(method), "v20@0:8B16") == 0) {
+ vpOriginalWallpaperSetHidden = method_getImplementation(method);
+ BOOL installed = class_addMethod(window, hidden, (IMP)vpWallpaperSetHidden, method_getTypeEncoding(method));
+ vpFoldDisplayLog([NSString stringWithFormat:@"wallpaper traits experiment: scoped visibility hook=%d", installed]);
+ }
+ }
+}
+
+// The landscape-wallpaper gate soft-links PF_IS_PAD_DEVICE, which answers for
+// the whole process; a global YES would leak the pad answer everywhere. The
+// detour below answers YES only when the caller is inside the implementations
+// of the two supportsLandscapeWallpaperContents selectors, so the wallpaper
+// controller alone sees a pad-class answer where its native branch demands it.
+static bool (*vpOriginalPFIsPadDevice)(void);
+static uintptr_t vpLandscapeSupportImpRange[2][2];
+
+static bool vpPFIsPadDeviceReplacement(void) {
+ void *caller = __builtin_return_address(0);
+ uintptr_t address = (uintptr_t)caller;
+ for (int i = 0; i < 2; i++) {
+ if (vpLandscapeSupportImpRange[i][0] && address >= vpLandscapeSupportImpRange[i][0] &&
+ address < vpLandscapeSupportImpRange[i][1])
+ return true;
+ }
+ return ((bool (*)(void))vpOriginalPFIsPadDevice)();
+}
+
+static void vpInstallLandscapeWallpaperGateDetour(void) {
+ void *padSymbol = dlsym(RTLD_DEFAULT, "PF_IS_PAD_DEVICE");
+ if (!padSymbol) { vpFoldDisplayLog(@"landscape gate: PF_IS_PAD_DEVICE absent"); return; }
+ Class remote = objc_getClass("PBUIPosterWallpaperRemoteViewController");
+ if (!remote) { vpFoldDisplayLog(@"landscape gate: remote view controller absent"); return; }
+ SEL selectors[2] = {
+ sel_registerName("supportsLandscapeWallpaperContents"),
+ sel_registerName("supportsLandscapeWallpaperContentsForDisplayConfiguration:"),
+ };
+ NSUInteger ranges = 0;
+ for (int i = 0; i < 2; i++) {
+ Method method = class_getClassMethod(remote, selectors[i]);
+ if (!method) method = class_getInstanceMethod(remote, selectors[i]);
+ if (!method) continue;
+ uintptr_t imp = (uintptr_t)method_getImplementation(method);
+ vpLandscapeSupportImpRange[ranges][0] = imp;
+ // The gate check sits within the first pages of each implementation.
+ vpLandscapeSupportImpRange[ranges][1] = imp + 0x1000;
+ ranges++;
+ }
+ if (!ranges) { vpFoldDisplayLog(@"landscape gate: no supportsLandscape selector found"); return; }
+ MISFixDetourResult (*install)(const char *, void *, void *, void **) = dlsym(RTLD_DEFAULT, "MISFixDetour");
+ if (!install) { vpFoldDisplayLog(@"landscape gate: MISFixDetour absent"); return; }
+ MISFixDetourResult result = install("Duo landscape wallpaper gate", padSymbol, (void *)vpPFIsPadDeviceReplacement, (void **)&vpOriginalPFIsPadDevice);
+ vpFoldDisplayLog([NSString stringWithFormat:@"landscape gate: ranges=%lu detour=%d", (unsigned long)ranges, result]);
+}
diff --git a/VPhoneGuestComponents/FoldDisplay/libvphonefolddisplay.m b/VPhoneGuestComponents/FoldDisplay/libvphonefolddisplay.m
new file mode 100644
index 00000000..ffc53991
--- /dev/null
+++ b/VPhoneGuestComponents/FoldDisplay/libvphonefolddisplay.m
@@ -0,0 +1,4076 @@
+// Experimental, manifest-gated Duo display diagnostics.
+// The framebuffer already reports the requested inner dimensions, while the
+// home grid retains the narrow family. Identity-count hooks below have not
+// been called on the tested guest. Keep their outcome distinct from the
+// confirmed mainConfiguration and screen-type observations; see
+// Research/Guest/iphone_duo_bringup.md.
+
+#import <Foundation/Foundation.h>
+#import <CoreGraphics/CoreGraphics.h>
+#import <objc/runtime.h>
+#import <objc/message.h>
+#include "../MISFix/MISFixDetour.h"
+#include <dlfcn.h>
+#include <string.h>
+#include <stdatomic.h>
+#include <notify.h>
+#include <sys/stat.h>
+#include <sys/sysctl.h>
+#include <unistd.h>
+#include <stdio.h>
+
+static IMP vpOriginalAlwaysConnected;
+static IMP vpOriginalTransform;
+static atomic_uint vpTransformLogCount;
+static atomic_uint vpConfigurationLogCount;
+static atomic_bool vpLogicalProjectionEnabled;
+static atomic_bool vpCoverViewportEnabled;
+static BOOL vpPersistentViewport;
+static IMP vpOriginalLogicalSurfaceType;
+static BOOL vpLogicalRoleExperiment;
+static __weak id vpLogicalRoleResolver;
+static _Thread_local BOOL vpReadingLogicalSurface;
+static atomic_uint vpViewportRequestGeneration;
+static atomic_bool vpCoordinateRootSceneFrame;
+static atomic_bool vpNativeGeometryRefreshEnabled;
+static atomic_uint vpWindowGeometryRefreshGeneration;
+static IMP vpOriginalSceneGeometryCallback;
+static IMP vpOriginalStartResolvingDisplay;
+static atomic_bool vpSceneResizePropagationEnabled;
+static IMP vpOriginalSBWindowResizePolicy;
+static __weak id vpSceneResizeScope;
+static NSMutableDictionary<NSString *, NSNumber *> *vpResizedSceneGenerations;
+static NSMutableDictionary<NSString *, NSDictionary *> *vpSavedSceneOrientations;
+static atomic_uint vpSceneOrientationPulseGeneration;
+static __weak id vpGeometryRequestScene;
+static NSInteger vpGeometryRequestOriginal;
+static NSInteger vpGeometryRequestTarget;
+static atomic_uint vpGeometryRequestGeneration;
+static __weak id vpOrientationEventsManager;
+static BOOL vpOriginalOrientationEventsEnabled;
+static atomic_uint vpOrientationEventsGeneration;
+static IMP vpOriginalTollFreeOrientationConversion;
+static __weak id vpCanonicalOrientationScene;
+static atomic_uint vpCanonicalOrientationGeneration;
+static IMP vpOriginalSceneScreenType;
+static NSUInteger vpInnerNativeScreenType;
+static atomic_uint vpInnerFamilyLogCount;
+static void *vpOriginalSharedFamilyClassifier;
+static void *vpOriginalViewportScreenFamily, *vpOriginalViewportGlobalFamily;
+static _Thread_local BOOL vpViewportFamilyLookupActive;
+static _Thread_local unsigned int vpGlobalFamilyDepth;
+static atomic_uint vpGlobalFamilyTraceCount;
+static atomic_uint vpSharedFamilyLogCount;
+static __weak id vpEmbeddedOrientationApplication;
+static __weak id vpEmbeddedOrientationScene;
+static NSInteger vpEmbeddedOrientationOriginal, vpEmbeddedOrientationPublished;
+static atomic_uint vpEmbeddedOrientationGeneration;
+static IMP vpOriginalSceneIsMain, vpOriginalStatusManagerInit, vpOriginalStatusManagerEmbedded;
+static _Thread_local void *vpStatusManagerInitializingScene;
+static _Thread_local BOOL vpStatusManagerMainQueryConsumed;
+static IMP vpOriginalTimeItemUpdate;
+static IMP vpOriginalMachClockTick, vpOriginalMachClockObserve;
+static atomic_uint vpClockReferenceFallbackCount;
+static atomic_uint vpTimeItemTraceCount;
+static __weak id vpUIConfigWindowScene, vpUIConfigServerScene, vpUIConfigClientScene;
+static _Atomic(IMP) vpUIIdentityCopyOriginal;
+static _Thread_local void *vpUIIdentityCopySource, *vpUIIdentityCopyReplacement;
+static id vpUIConfigOriginalHosted, vpUIConfigOriginalServerDisplay, vpUIConfigOriginalUI, vpUIConfigPublished;
+static atomic_uint vpUIConfigGeneration;
+static id vpUIOldStatusComponent, vpUINewStatusComponent, vpUIStatusComponentKey;
+static BOOL vpUIStatusDetachedBeforeRollback;
+static __weak id vpUIOldStatusWindow;
+static NSNumber *vpUIOldStatusWindowHidden;
+static _Atomic(IMP) vpOriginalStatusProfileFactories[4];
+static atomic_bool vpStatusProfileLookupEnabled;
+static unsigned int vpStatusProfileGeneration;
+static unsigned int vpStatusProfileCallCount;
+static _Thread_local void *vpStatusProfileConstructionScene;
+static _Thread_local unsigned int vpStatusProfileFactoryDepth;
+static __weak id vpStatusProfileScene;
+static __weak id vpUITraitsScreen;
+static NSNumber *vpUITraitsOriginalIdiom;
+static NSInteger vpUITraitsPublishedIdiom;
+static NSString *vpUITraitsIdentifier;
+static void *vpOriginalMainStatusClassLookup;
+static atomic_bool vpMainStatusProfileEnabled;
+static unsigned int vpMainStatusProfileGeneration, vpMainStatusProfileLogCount;
+static __weak id vpMainStatusProfileScene;
+static Class vpMainStatusOriginalProviderClass;
+static BOOL vpAutomaticMainStatus;
+static void vpFoldDisplayLog(NSString *line);
+static BOOL vpWallpaperOrientationLeaseActive;
+static void *vpOriginalWallpaperFeatureLookup;
+static IMP vpOriginalWallpaperSetHidden;
+static BOOL vpWallpaperTraitsExperimentInstalled;
+// Bumped on every hooked SBMainDisplayConfigurationTransformer call so the
+// invalidation pulse can prove the pipeline actually re-ran.
+static atomic_uint vpPulseTransformCount;
+// The generation whose post-transform adoption pass already ran.
+static atomic_uint vpAdoptionCompletedGeneration;
+static __weak id vpObservedConfigurationTransformer;
+static IMP vpOriginalExtendedProperties;
+static atomic_bool vpInnerSurfaceProbeEnabled;
+static atomic_uint vpPrimarySurfaceType = 2;
+static unsigned int vpSurfaceProbeGeneration;
+static atomic_bool vpCoverSurfaceProbeEnabled;
+static atomic_uint vpSurfaceProbeLogCount;
+static NSHashTable *vpObservedDisplayMonitors;
+static IMP vpOriginalPublicMonitorInit;
+static IMP vpOriginalCompletionMonitorInit;
+static void vpFoldDisplayLog(NSString *line);
+static id vpReadObject(id object, const char *name);
+static id vpReadObjectIvar(id object, const char *name);
+static id vpMainInnerWindowScene(void);
+static void vpRestoreStatusProfileLookup(void);
+static void vpResetManagedStatusProvider(void);
+static BOOL vpRestoreUIScreenTraits(void);
+static void vpRefreshMainStatusRenderer(void);
+static void vpProcessViewportWorkspaceRequest(BOOL submit);
+static void vpSyncLogicalRoleResolver(void);
+static void vpRefreshMainTransform(void);
+static void vpInspectDuoSystemUI(void);
+static void vpInspectStatusProvider(void);
+static void vpPulseInputTrace(void);
+static void vpRestoreInputTrace(void);
+static void vpExportNativeOrientationMapping(void);
+static void vpLogicalProjectionControl(NSInteger action);
+static id vpRootServerScenes(id app);
+static NSArray *vpSnapshotRect(id object, const char *name);
+static void vpProcessViewportWorkspaceRequest(BOOL submit);
+static void vpApplyRootGeometry(void);
+static void vpScheduleViewportAdoption(void);
+static void vpApplyQuickActionGlyphScale(void);
+
+// These helpers are kept at the boundary so the extracted status/wallpaper
+// sections can call them without depending on declaration order. They only
+// use the existing monitor and diagnostic surfaces; no display identity or
+// framebuffer is changed here.
+static void vpRefreshMainTransform(void) {
+ NSUInteger refreshed = 0;
+ @synchronized (vpObservedDisplayMonitors) {
+ for (id monitor in vpObservedDisplayMonitors) {
+ SEL update = sel_registerName("updateConfigurationWithCompletion:");
+ if (![monitor respondsToSelector:update]) continue;
+ @try { ((void (*)(id, SEL, id))objc_msgSend)(monitor, update, ^(id error) { (void)error; }); refreshed++; }
+ @catch (NSException *exception) { vpFoldDisplayLog([NSString stringWithFormat:@"transform refresh exception: %@", exception.reason]); }
+ }
+ }
+ // This SpringBoard build creates no FBSDisplayMonitor through the
+ // observed initializers, but the FBDisplayManager compatibility monitor
+ // owns the same configuration pipeline (it holds the transformer whose
+ // cover override the flag above arms). The 3803cc4d invalidation pulse
+ // drove the cover switch through updateTransformsWithCompletion:; the
+ // selector table of that shipped dylib names it, the rewritten source
+ // had lost it.
+ if (refreshed == 0) {
+ id manager = vpReadObject(objc_getClass("FBDisplayManager"), "sharedInstance");
+ SEL transforms = sel_registerName("updateTransformsWithCompletion:");
+ Method pulse = manager ? class_getInstanceMethod(object_getClass(manager), transforms) : NULL;
+ if (pulse) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"invalidation pulse: selector ABI %s", method_getTypeEncoding(pulse)]);
+ if (strcmp(method_getTypeEncoding(pulse), "v24@0:8@?16") == 0) {
+ @try {
+ // The Main source sits out the transform pipeline until
+ // its updatable flag is set; the 3803cc4d pulse flipped
+ // it for the duration of one update and restored it in
+ // the completion.
+ NSMutableArray *flippedSources = [NSMutableArray array];
+ static BOOL sourceFlagInventoried;
+ for (id source in vpReadObject(manager, "_sortedSources")) {
+ NSNumber *updatable = nil;
+ @try { updatable = [source valueForKey:@"updatable"]; } @catch (NSException *exception) { }
+ if (!updatable || updatable.boolValue) continue;
+ SEL setUpdatable = sel_registerName("setUpdatable:");
+ Method setter = class_getInstanceMethod(object_getClass(source), setUpdatable);
+ if (!sourceFlagInventoried) {
+ sourceFlagInventoried = YES;
+ vpFoldDisplayLog([NSString stringWithFormat:@"invalidation pulse: source class %s updatable-getter %@ setter %@",
+ object_getClassName(source),
+ [source methodSignatureForSelector:sel_registerName("updatable")],
+ setter ? [NSString stringWithFormat:@"%s", method_getTypeEncoding(setter)] : @"absent"]);
+ }
+ const char *setterABI = setter ? method_getTypeEncoding(setter) : NULL;
+ if (setterABI && strcmp(setterABI, "v20@0:8B16") == 0)
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(source, setUpdatable, YES);
+ else if (setterABI && strcmp(setterABI, "v20@0:8q16") == 0)
+ ((void (*)(id, SEL, long))objc_msgSend)(source, setUpdatable, 1L);
+ else {
+ // No usable setter: the 3803cc4d pulse worked, so
+ // the flag must be settable another way. Try the
+ // instance variable directly by offset.
+ Ivar flag = class_getInstanceVariable(object_getClass(source), "_updatable");
+ if (!flag) flag = class_getInstanceVariable(object_getClass(source), "updatable");
+ const char *flagType = flag ? ivar_getTypeEncoding(flag) : NULL;
+ if (flag && flagType && (flagType[0] == 'B' || flagType[0] == 'c' || flagType[0] == 'q' || flagType[0] == 'i')) {
+ *(BOOL *)((char *)(__bridge void *)source + ivar_getOffset(flag)) = YES;
+ [flippedSources addObject:source];
+ vpFoldDisplayLog([NSString stringWithFormat:@"invalidation pulse: source %s flag ivar %s set", object_getClassName(source), flagType]);
+ continue;
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"invalidation pulse: native source flag ABI unavailable (%s setter %s ivar %s)",
+ object_getClassName(source), setterABI ? setterABI : "absent", flagType ?: "absent"]);
+ continue;
+ }
+ [flippedSources addObject:source];
+ vpFoldDisplayLog([NSString stringWithFormat:@"invalidation pulse: prior updatable=%d", updatable.boolValue]);
+ }
+ unsigned int before = atomic_load_explicit(&vpPulseTransformCount, memory_order_relaxed);
+ ((void (*)(id, SEL, id))objc_msgSend)(manager, transforms, ^(id unused) {
+ (void)unused;
+ for (id source in flippedSources) {
+ SEL setUpdatable = sel_registerName("setUpdatable:");
+ Method setter = class_getInstanceMethod(object_getClass(source), setUpdatable);
+ const char *setterABI = setter ? method_getTypeEncoding(setter) : NULL;
+ if (setterABI && strcmp(setterABI, "v20@0:8B16") == 0)
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(source, setUpdatable, NO);
+ else if (setterABI && strcmp(setterABI, "v20@0:8q16") == 0)
+ ((void (*)(id, SEL, long))objc_msgSend)(source, setUpdatable, 0L);
+ else {
+ Ivar flag = class_getInstanceVariable(object_getClass(source), "_updatable");
+ if (!flag) flag = class_getInstanceVariable(object_getClass(source), "updatable");
+ const char *flagType = flag ? ivar_getTypeEncoding(flag) : NULL;
+ if (flag && flagType && (flagType[0] == 'B' || flagType[0] == 'c' || flagType[0] == 'q' || flagType[0] == 'i'))
+ *(BOOL *)((char *)(__bridge void *)source + ivar_getOffset(flag)) = NO;
+ }
+ }
+ if (flippedSources.count) vpFoldDisplayLog(@"invalidation pulse: native flag restored");
+ unsigned int after = atomic_load_explicit(&vpPulseTransformCount, memory_order_relaxed);
+ vpFoldDisplayLog([NSString stringWithFormat:@"invalidation pulse: transform calls %u -> %u", before, after]);
+ });
+ refreshed++;
+ vpFoldDisplayLog(@"invalidation pulse: updateTransformsWithCompletion requested");
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"invalidation pulse exception: %@", exception.reason]);
+ }
+ }
+ } else {
+ // One-shot inventory of the manager's own pipeline methods, so a
+ // renamed selector is visible without another build cycle.
+ static BOOL inventoried;
+ if (!inventoried) {
+ inventoried = YES;
+ unsigned int count = 0;
+ Class managerClass = object_getClass(manager);
+ for (unsigned int level = 0; managerClass && level < 3; level++, managerClass = class_getSuperclass(managerClass)) {
+ Method *methods = class_copyMethodList(managerClass, &count);
+ for (unsigned int i = 0; i < count; i++) {
+ const char *selector = sel_getName(method_getName(methods[i]));
+ if (strstr(selector, "pdate") || strstr(selector, "ransform") || strstr(selector, "onfiguration"))
+ vpFoldDisplayLog([NSString stringWithFormat:@"invalidation pulse: manager method %s %s",
+ selector, method_getTypeEncoding(methods[i])]);
+ }
+ free(methods);
+ }
+ }
+ vpFoldDisplayLog(@"transform refresh: no observed monitors and the manager lacks both update selectors");
+ }
+ }
+}
+// The overridden Main configuration keeps its identity, so FrontBoard
+// pushes no scene-settings update when only the mode size changed. The
+// 3803cc4d root-geometry pass published the active bounds to the SB-main
+// root scene through its settings-mutation API; recovered here.
+static void vpScheduleViewportAdoption(void) {
+ unsigned int adoptionGeneration = atomic_load_explicit(&vpViewportRequestGeneration, memory_order_relaxed);
+ if (adoptionGeneration == atomic_load_explicit(&vpAdoptionCompletedGeneration, memory_order_relaxed)) return;
+ atomic_store_explicit(&vpAdoptionCompletedGeneration, adoptionGeneration, memory_order_relaxed);
+ vpApplyRootGeometry();
+ if (vpPersistentViewport) vpProcessViewportWorkspaceRequest(YES);
+}
+static void vpApplyRootGeometry(void) {
+ if (!vpAutomaticMainStatus) return;
+ @try {
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ if (!app || !configuration) return;
+ NSArray *bounds = vpSnapshotRect(configuration, "bounds");
+ if (![bounds isKindOfClass:NSArray.class] || bounds.count != 4) return;
+ // The 3803cc4d pass (___vpUpdateRootSceneGeometry_block_invoke) set
+ // the frame on every root scene through updateUISettingsWithBlock:,
+ // whose block receives the mutable settings. The native geometry
+ // callback then propagates: icon family switch and window resizes.
+ CGRect frame = CGRectMake(0, 0, [bounds[2] doubleValue], [bounds[3] doubleValue]);
+ for (id scene in vpRootServerScenes(app)) {
+ id identifier = vpReadObject(scene, "identifier");
+ if (![identifier isEqual:@"SB-main"] &&
+ ![identifier isEqual:@"SB-systemAperture"] &&
+ ![identifier isEqual:@"SB-systemApertureCurtain"]) continue;
+ SEL updateSelector = sel_registerName("updateUISettingsWithBlock:");
+ Method update = class_getInstanceMethod(object_getClass(scene), updateSelector);
+ if (!update || strcmp(method_getTypeEncoding(update), "v24@0:8@?16") != 0) {
+ vpFoldDisplayLog(@"root geometry: settings-update ABI unavailable");
+ continue;
+ }
+ __block BOOL frameSet = NO;
+ ((void (*)(id, SEL, id))objc_msgSend)(scene, updateSelector, ^(id settings) {
+ @try {
+ if (!settings) return;
+ SEL frameSelector = sel_registerName("setFrame:");
+ Method frameSetter = class_getInstanceMethod(object_getClass(settings), frameSelector);
+ const char *frameABI = frameSetter ? method_getTypeEncoding(frameSetter) : NULL;
+ if (frameABI && strcmp(frameABI, "v48@0:8{CGRect={CGPoint=dd}{CGSize=dd}}16") == 0) {
+ ((void (*)(id, SEL, CGRect))objc_msgSend)(settings, frameSelector, frame);
+ frameSet = YES;
+ } else if (frameABI && strcmp(frameABI, "v48@0:8{CGRect={CGPoint=ff}{CGSize=ff}}16") == 0) {
+ // 32-bit CGFloat ABI: pass the same frame in float slots.
+ ((void (*)(id, SEL, CGRect))objc_msgSend)(settings, frameSelector, frame);
+ frameSet = YES;
+ } else {
+ vpFoldDisplayLog([NSString stringWithFormat:@"root geometry: frame setter ABI %s on %s",
+ frameABI ?: "absent", object_getClassName(settings)]);
+ }
+ Method hosted = class_getInstanceMethod(object_getClass(settings), sel_registerName("sb_setHostedDisplayConfiguration:"));
+ if (hosted && strcmp(method_getTypeEncoding(hosted), "v24@0:8@16") == 0)
+ ((void (*)(id, SEL, id))objc_msgSend)(settings, sel_registerName("sb_setHostedDisplayConfiguration:"), configuration);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"root geometry settings exception: %@", exception.reason]);
+ }
+ });
+ vpFoldDisplayLog([NSString stringWithFormat:@"root geometry: %@ settings frame=%@ generation=%u",
+ identifier, frameSet ? [NSString stringWithFormat:@"(%.0f, %.0f, %.0f, %.0f)",
+ frame.origin.x, frame.origin.y, frame.size.width, frame.size.height] : @"unset",
+ atomic_load_explicit(&vpViewportRequestGeneration, memory_order_relaxed)]);
+ }
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"root geometry exception: %@", exception.reason]);
+ }
+}
+static void vpInspectDuoSystemUI(void) {
+ @try {
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ NSUInteger found = 0;
+ for (id window in vpReadObject(app, "windows")) {
+ NSMutableArray *pending = [NSMutableArray arrayWithObject:window];
+ while (pending.count) {
+ id view = pending.lastObject;
+ [pending removeLastObject];
+ if ([NSStringFromClass([view class]) isEqualToString:@"UICoverSheetButton"]) {
+ id content = vpReadObjectIvar(view, "_contentView");
+ id image = vpReadObjectIvar(view, "_image");
+ id selected = vpReadObjectIvar(view, "_selectedImage");
+ vpFoldDisplayLog([NSString stringWithFormat:@"cover sheet native bounds: button=%@ frame=%@ bounds=%@ contentFrame=%@ contentBounds=%@ imageSize=%@ selectedImageSize=%@ edgeInsets=%@",
+ NSStringFromClass([view class]), [view valueForKey:@"frame"], [view valueForKey:@"bounds"],
+ [content valueForKey:@"frame"], [content valueForKey:@"bounds"], [image valueForKey:@"size"],
+ [selected valueForKey:@"size"], [view valueForKey:@"edgeInsets"]]);
+ found++;
+ }
+ for (id child in [view valueForKey:@"subviews"] ?: @[]) [pending addObject:child];
+ }
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"Duo system UI inventory: coverSheetButtons=%lu", (unsigned long)found]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"Duo system UI inventory exception: %@", exception.reason]);
+ }
+}
+static void vpInspectStatusProvider(void) { vpFoldDisplayLog(@"status provider inspection requested"); }
+static void vpPulseInputTrace(void) { vpFoldDisplayLog(@"input trace pulse requested"); }
+static void vpRestoreInputTrace(void) { vpFoldDisplayLog(@"input trace restore requested"); }
+static void vpLogicalProjectionControl(NSInteger action) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"logical projection control requested action=%ld", (long)action]);
+}
+
+static BOOL vpIsDuoInnerBounds(id configuration) {
+ SEL selector = sel_registerName("bounds");
+ NSMethodSignature *signature = [configuration methodSignatureForSelector:selector];
+ if (signature.methodReturnLength != sizeof(CGRect)) return NO;
+ CGRect bounds = ((CGRect (*)(id, SEL))objc_msgSend)(configuration, selector);
+ // Native size is the acceptance target. Retain the earlier explicit
+ // research viewport so its saved restoration controls remain usable.
+ return CGRectEqualToRect(bounds, CGRectMake(0, 0, 669, 951)) ||
+ CGRectEqualToRect(bounds, CGRectMake(0, 0, 678, 951));
+}
+
+static void vpRememberDisplayMonitor(id monitor, id transformer) {
+ if (!monitor) return;
+ @synchronized (vpObservedDisplayMonitors) {
+ [vpObservedDisplayMonitors addObject:monitor];
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"monitor init: %s %p transformer=%s %p",
+ object_getClassName(monitor), (__bridge void *)monitor,
+ transformer ? object_getClassName(transformer) : "none", (__bridge void *)transformer]);
+}
+
+static id vpObservePublicMonitorInit(id self, SEL cmd, id transformer) {
+ id monitor = ((id (*)(id, SEL, id))vpOriginalPublicMonitorInit)(self, cmd, transformer);
+ vpRememberDisplayMonitor(monitor, transformer);
+ return monitor;
+}
+
+static id vpObserveCompletionMonitorInit(id self, SEL cmd, id completion) {
+ id monitor = ((id (*)(id, SEL, id))vpOriginalCompletionMonitorInit)(self, cmd, completion);
+ vpRememberDisplayMonitor(monitor, nil);
+ return monitor;
+}
+static void vpFoldDisplayLog(NSString *line) {
+ int fd = open("/var/mobile/Library/Caches/vphone-folddisplay.log",
+ O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0666);
+ if (fd < 0)
+ return;
+ NSString *stamp = [NSDateFormatter localizedStringFromDate:NSDate.date
+ dateStyle:NSDateFormatterNoStyle
+ timeStyle:NSDateFormatterMediumStyle];
+ NSString *row = [NSString stringWithFormat:@"%@ %@\n", stamp, line];
+ const char *bytes = row.UTF8String;
+ if (bytes)
+ write(fd, bytes, strlen(bytes));
+ close(fd);
+}
+
+static BOOL vpConsumeDisplayExperimentFlag(const char *flag) {
+ int fd = open(flag, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+ if (fd < 0) return NO;
+ char value = 0;
+ ssize_t length = read(fd, &value, 1);
+ close(fd);
+ unlink(flag);
+ return length == 1 && value == '1';
+}
+
+// backboardd's native traits RPC reads DeviceSurfaceType from this dictionary.
+// Keep the probe bounded and scoped to the real primary render display. It
+// changes neither the framebuffer nor the number/identity of display sources.
+static id vpSurfaceExtendedProperties(id self, SEL cmd) {
+ id properties = ((id (*)(id, SEL))vpOriginalExtendedProperties)(self, cmd);
+ if (!atomic_load_explicit(&vpInnerSurfaceProbeEnabled, memory_order_acquire)) return properties;
+ id name = ((id (*)(id, SEL))objc_msgSend)(self, sel_registerName("deviceName"));
+ BOOL primary = [name isEqual:@"primary"];
+ BOOL cover = atomic_load_explicit(&vpCoverSurfaceProbeEnabled, memory_order_acquire) &&
+ [name isEqual:@"VPhone Cover Probe"];
+ if ((!primary && !cover) || (properties && ![properties isKindOfClass:NSDictionary.class])) return properties;
+ NSMutableDictionary *derived = properties ? [properties mutableCopy] : [NSMutableDictionary dictionary];
+ derived[@"DeviceSurfaceType"] = primary ? @(atomic_load_explicit(&vpPrimarySurfaceType, memory_order_acquire)) : @1;
+ if (atomic_fetch_add_explicit(&vpSurfaceProbeLogCount, 1, memory_order_relaxed) < 8)
+ vpFoldDisplayLog([NSString stringWithFormat:@"surface probe: %@ traits %@ -> %@", name, properties, derived]);
+ return [derived copy];
+}
+
+static void vpBeginSurfaceProbe(unsigned int surfaceType, BOOL pair) {
+ if (!vpOriginalExtendedProperties) return;
+ if (surfaceType != 1 && surfaceType != 2) return;
+ unsigned int generation = ++vpSurfaceProbeGeneration;
+ atomic_store_explicit(&vpPrimarySurfaceType, surfaceType, memory_order_release);
+ atomic_store_explicit(&vpCoverSurfaceProbeEnabled, pair, memory_order_release);
+ atomic_store_explicit(&vpInnerSurfaceProbeEnabled, true, memory_order_release);
+ vpFoldDisplayLog([NSString stringWithFormat:@"surface probe: primary role=%u enabled for 30 seconds; pairedCover=%d", surfaceType, pair]);
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ if (generation != vpSurfaceProbeGeneration) return;
+ atomic_store_explicit(&vpInnerSurfaceProbeEnabled, false, memory_order_release);
+ atomic_store_explicit(&vpCoverSurfaceProbeEnabled, false, memory_order_release);
+ vpFoldDisplayLog(@"surface probe: primary native role restored");
+ });
+}
+
+@protocol VPhoneDisplayProjectionCopying
+- (instancetype)copyWithOverrideBounds:(CGRect)bounds;
+- (instancetype)copyWithOverrideMode:(id)mode;
+@end
+@protocol VPhoneDisplayModeCopying
+- (instancetype)_copyWithOverrideSize:(CGSize)size scale:(CGFloat)scale;
+@end
+@protocol VPhoneDisplayProjectionBuilding
+- (instancetype)initWithConfiguration:(id)configuration;
+- (void)setUniqueIdentifier:(NSString *)identifier;
+- (void)setDisplayType:(NSInteger)type;
+- (void)setUIKitMainLike;
+- (id)buildConfigurationWithError:(NSError **)error;
+@end
+@protocol VPhoneDisplayIdentityInitializing
+- (instancetype)_initWithType:(NSInteger)type UIKitMainLike:(BOOL)mainLike displayID:(uint32_t)displayID
+ connectionType:(NSInteger)connectionType connectionSeed:(uint32_t)connectionSeed pid:(int)pid
+ external:(BOOL)external uniqueIdentifier:(id)identifier secure:(BOOL)secure
+ alwaysConnected:(BOOL)alwaysConnected root:(id)root;
+@end
+@protocol VPhoneGeometryPreferencesInitializing
+- (instancetype)initWithInterfaceOrientations:(NSUInteger)orientations;
+@end
+
+
+// Classify a distinct reference context; never publish its 669pt geometry.
+// This tests the shared scene family decision used by system consumers,
+// including the native status-bar rotation gate, rather than one provider.
+static NSUInteger vpNativeInnerSceneFamily(id self, SEL selector) {
+ NSUInteger original = ((NSUInteger (*)(id, SEL))vpOriginalSceneScreenType)(self, selector);
+ @try {
+ if (![[self valueForKey:@"surfaceType"] isEqual:@2]) return original;
+ id identity = vpReadObject(self, "displayIdentity");
+ // SBWindowScene has no displayConfiguration on this build. Resolve
+ // Main through FrontBoard and verify its identity before using it.
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ if (![[identity valueForKey:@"isMainRootDisplay"] boolValue] ||
+ ![identity isEqual:vpReadObject(configuration, "identity")]) return original;
+ CGRect bounds = ((CGRect (*)(id, SEL))objc_msgSend)(configuration, sel_registerName("bounds"));
+ if (!CGSizeEqualToSize(bounds.size, CGSizeMake(678, 951))) return original;
+ if (!vpInnerNativeScreenType) {
+ void *home = dlopen("/System/Library/PrivateFrameworks/SpringBoardHome.framework/SpringBoardHome", RTLD_LAZY | RTLD_LOCAL);
+ NSUInteger (*classify)(id, id) = dlsym(home, "SBHScreenTypeForDeviceAndDisplayContexts");
+ id device = vpReadObject(objc_getClass("UISDeviceContext"), "sb_defaultContext");
+ id display = vpReadObject(self, "_sbDisplayContext");
+ id copy = [display mutableCopy];
+ Method setter = class_getInstanceMethod(object_getClass(copy), sel_registerName("setDisplayConfiguration:"));
+ if (!classify || !device || !copy || copy == display || !setter ||
+ strcmp(method_getTypeEncoding(setter), "v24@0:8@16") != 0) return original;
+ id mode = vpReadObject(configuration, "currentMode");
+ CGFloat scale = ((CGFloat (*)(id, SEL))objc_msgSend)(mode, sel_registerName("pointScale"));
+ id referenceMode = [(id<VPhoneDisplayModeCopying>)mode _copyWithOverrideSize:CGSizeMake(669, 951) scale:scale];
+ id reference = [(id<VPhoneDisplayProjectionCopying>)configuration copyWithOverrideMode:referenceMode];
+ ((void (*)(id, SEL, id))objc_msgSend)(copy, sel_registerName("setDisplayConfiguration:"), reference);
+ NSUInteger candidate = classify(device, copy);
+ if (candidate != 32) return original;
+ vpInnerNativeScreenType = candidate;
+ }
+ if (atomic_fetch_add_explicit(&vpInnerFamilyLogCount, 1, memory_order_relaxed) < 4)
+ vpFoldDisplayLog([NSString stringWithFormat:@"shared scene family: native reference=%lu original=%lu actual=%gx%g",
+ (unsigned long)vpInnerNativeScreenType, (unsigned long)original, bounds.size.width, bounds.size.height]);
+ return vpInnerNativeScreenType;
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"shared scene family exception: %@", exception.reason]);
+ return original;
+ }
+}
+
+static NSUInteger vpSharedInnerFamily(uintptr_t a, uintptr_t b, uintptr_t c, CGRect bounds,
+ CGFloat scale, CGFloat referenceScale) {
+ // The native common helper receives x0..x2 plus the CGRect HFA in
+ // d0..d3 and two scalars in d4/d5. Both exported context and screen
+ // classifiers use this helper; hooking their wrapper misses UIScreen.
+ NSUInteger (*original)(uintptr_t, uintptr_t, uintptr_t, CGRect, CGFloat, CGFloat) = vpOriginalSharedFamilyClassifier;
+ NSUInteger native = original(a, b, c, bounds, scale, referenceScale);
+ @try {
+ if (!CGSizeEqualToSize(bounds.size, CGSizeMake(678, 951))) return native;
+ CGRect reference = bounds;
+ reference.size.width = 669;
+ NSUInteger family = original(a, b, c, reference, scale, referenceScale);
+ if (family != 32) return native;
+ if (atomic_fetch_add_explicit(&vpSharedFamilyLogCount, 1, memory_order_relaxed) < 6)
+ vpFoldDisplayLog([NSString stringWithFormat:@"shared classifier: native=%lu reference=%lu actual=%gx%g",
+ (unsigned long)native, (unsigned long)family, bounds.size.width, bounds.size.height]);
+ return family;
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"shared classifier exception: %@", exception.reason]);
+ return native;
+ }
+}
+
+static void vpInstallSharedInnerFamily(void) {
+ void *home = dlopen("/System/Library/PrivateFrameworks/SpringBoardHome.framework/SpringBoardHome", RTLD_LAZY | RTLD_LOCAL);
+ void *target = dlsym(home, "_SBHScreenTypeLookupCommon");
+ MISFixDetourResult (*install)(const char *, void *, void *, void **) = dlsym(RTLD_DEFAULT, "MISFixDetour");
+ if (!target || !install) { vpFoldDisplayLog(@"shared classifier: existing detour API unavailable"); return; }
+ // The existing constructor-only detour checks relocation and readback,
+ // uses process-private COW cache pages, and publishes the trampoline
+ // before its jump. Nothing in the on-disk cache or other processes changes.
+ MISFixDetourResult result = install("Duo shared screen classifier", target, (void *)vpSharedInnerFamily,
+ &vpOriginalSharedFamilyClassifier);
+ vpFoldDisplayLog([NSString stringWithFormat:@"shared classifier: constructor detour result=%d", result]);
+}
+
+// The physical screen's family caches are boot-scoped. During an explicit
+// same-Main viewport lease, ask the native context classifier about the
+// currently published scene instead; do not overwrite dispatch_once state
+// or associated objects, and never affect another screen.
+static NSUInteger vpViewportFamily(id requestedScreen, NSUInteger fallback) {
+ if (!atomic_load_explicit(&vpCoverViewportEnabled, memory_order_acquire) ||
+ ![NSThread isMainThread] || vpViewportFamilyLookupActive) return fallback;
+ vpViewportFamilyLookupActive = YES;
+ @try {
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ id scene = vpReadObject(app, "embeddedDisplayWindowScene");
+ id screen = vpReadObject(scene, "screen");
+ id root = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ if (!scene || (requestedScreen && requestedScreen != screen) ||
+ ![vpReadObject(vpReadObject(scene, "_FBSScene"), "identifier") isEqual:@"SB-main"] ||
+ ![vpReadObject(screen, "displayIdentity") isEqual:vpReadObject(root, "identity")]) return fallback;
+ id context = vpReadObject(scene, "_sbDisplayContext");
+ id device = vpReadObject(objc_getClass("UISDeviceContext"), "sb_defaultContext");
+ NSUInteger (*classify)(id, id) = dlsym(RTLD_DEFAULT, "SBHScreenTypeForDeviceAndDisplayContexts");
+ if (!context || !device || !classify) return fallback;
+ NSUInteger result = classify(device, context);
+ return (result == 31 || result == 32) ? result : fallback;
+ } @catch (NSException *exception) {
+ return fallback;
+ } @finally { vpViewportFamilyLookupActive = NO; }
+}
+
+static NSUInteger vpViewportScreenFamily(id screen) {
+ return vpViewportFamily(screen, ((NSUInteger (*)(id))vpOriginalViewportScreenFamily)(screen));
+}
+// No Foundation formatting here: classification can be called while native
+// once-initializers are holding locks. Bounded raw records also survive a
+// blocked main queue and identify which side of the trampoline was reached.
+static void vpTraceGlobalFamily(const char *phase, unsigned int sequence, NSUInteger value, void *caller) {
+ if (sequence >= 24) return;
+ int fd = open("/var/mobile/Library/Caches/vphone-duo-family-trace.log",
+ O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC | O_NOFOLLOW, 0644);
+ if (fd < 0) return;
+ char line[512];
+ int length = snprintf(line, sizeof(line), "pid=%d seq=%u depth=%u phase=%s value=%lu caller=%p",
+ getpid(), sequence, vpGlobalFamilyDepth, phase, (unsigned long)value, caller);
+ if (length > 0 && length < (int)sizeof(line) - 1) { line[length++] = '\n'; write(fd, line, (size_t)length); }
+ close(fd);
+}
+static NSUInteger vpViewportGlobalFamily(void) {
+ unsigned int sequence = atomic_fetch_add_explicit(&vpGlobalFamilyTraceCount, 1, memory_order_relaxed);
+ ++vpGlobalFamilyDepth;
+ vpTraceGlobalFamily("enter-original", sequence, 0, __builtin_return_address(0));
+ NSUInteger original = ((NSUInteger (*)(void))vpOriginalViewportGlobalFamily)();
+ vpTraceGlobalFamily("returned-original", sequence, original, __builtin_return_address(0));
+ NSUInteger result = vpViewportFamily(nil, original);
+ vpTraceGlobalFamily("returned-context", sequence, result, __builtin_return_address(0));
+ --vpGlobalFamilyDepth;
+ return result;
+}
+static void vpInstallViewportFamilyLookup(void) {
+ MISFixDetourResult (*install)(const char *, void *, void *, void **) = dlsym(RTLD_DEFAULT, "MISFixDetour");
+ void *screen = dlsym(RTLD_DEFAULT, "SBHScreenTypeForScreen");
+ void *global = dlsym(RTLD_DEFAULT, "SBHScreenTypeForCurrentDevice");
+ if (!install || !screen || !global) return;
+ MISFixDetourResult a = install("Duo viewport screen family", screen, (void *)vpViewportScreenFamily, &vpOriginalViewportScreenFamily);
+ MISFixDetourResult b = install("Duo viewport global family", global, (void *)vpViewportGlobalFamily, &vpOriginalViewportGlobalFamily);
+ vpFoldDisplayLog([NSString stringWithFormat:@"viewport native family: screen=%d global=%d", a, b]);
+}
+
+// Transform one native root into distinct logical configurations. The native
+// builder preserves root linkage; no render mode or identity array is forged.
+static id vpLoggedTransform(id self, SEL _cmd, id configuration) {
+ vpObservedConfigurationTransformer = self;
+ atomic_fetch_add_explicit(&vpPulseTransformCount, 1, memory_order_relaxed);
+ id result = ((id (*)(id, SEL, id))vpOriginalTransform)(self, _cmd, configuration);
+ if (atomic_load_explicit(&vpCoverViewportEnabled, memory_order_acquire) &&
+ [result isKindOfClass:NSSet.class] && [result count] == 1) {
+ id candidate = [result anyObject];
+ id identity = ((id (*)(id, SEL))objc_msgSend)(candidate, sel_registerName("identity"));
+ if ([identity respondsToSelector:sel_registerName("isMainRootDisplay")] &&
+ ((BOOL (*)(id, SEL))objc_msgSend)(identity, sel_registerName("isMainRootDisplay"))) {
+ CGRect bounds = ((CGRect (*)(id, SEL))objc_msgSend)(candidate, sel_registerName("bounds"));
+ CGSize cover = bounds.size.width > bounds.size.height ? CGSizeMake(678, 466) : CGSizeMake(466, 678);
+ if (cover.width <= bounds.size.width && cover.height <= bounds.size.height) {
+ id mode = ((id (*)(id, SEL))objc_msgSend)(candidate, sel_registerName("currentMode"));
+ SEL modeCopy = sel_registerName("_copyWithOverrideSize:scale:");
+ SEL configurationCopy = sel_registerName("copyWithOverrideMode:");
+ Method modeMethod = class_getInstanceMethod(object_getClass(mode), modeCopy);
+ Method configurationMethod = class_getInstanceMethod(object_getClass(candidate), configurationCopy);
+ if (!modeMethod || !configurationMethod ||
+ strcmp(method_getTypeEncoding(modeMethod), "@40@0:8{CGSize=dd}16d32") != 0 ||
+ strcmp(method_getTypeEncoding(configurationMethod), "@24@0:8@16") != 0) {
+ vpFoldDisplayLog(@"single viewport: complete effective-mode copy ABI unavailable");
+ return result;
+ }
+ CGFloat scale = ((CGFloat (*)(id, SEL))objc_msgSend)(mode, sel_registerName("pointScale"));
+ // These are FBS frontend descriptors. The underlying CADisplay
+ // and its hardware mode remain the original objects.
+ id coverMode = [(id<VPhoneDisplayModeCopying>)mode _copyWithOverrideSize:cover scale:scale];
+ id bounded = [(id<VPhoneDisplayProjectionCopying>)candidate copyWithOverrideMode:coverMode];
+ id boundedIdentity = ((id (*)(id, SEL))objc_msgSend)(bounded, sel_registerName("identity"));
+ if (bounded && [boundedIdentity isEqual:identity]) {
+ result = [NSSet setWithObject:bounded];
+ vpFoldDisplayLog([NSString stringWithFormat:@"single viewport: native Main cover configuration %@", bounded]);
+ // The publish races any same-run adoption steps: schedule
+ // them for after this transform returns, once per
+ // generation, so the recompute sees the landed bounds.
+ dispatch_async(dispatch_get_main_queue(), ^{ vpScheduleViewportAdoption(); });
+ }
+ }
+ }
+ }
+ if (atomic_load_explicit(&vpLogicalProjectionEnabled, memory_order_acquire))
+ vpFoldDisplayLog([NSString stringWithFormat:@"logical transform called: self=%@ resultClass=%@", self, NSStringFromClass([result class])]);
+ // Never expand this set: the native SBFBSDisplayTransformer contract is
+ // exactly one effective configuration per source. Derived identities
+ // are previewed off to the side until singleton replacement is proven.
+ if (atomic_fetch_add_explicit(&vpTransformLogCount, 1, memory_order_relaxed) < 8)
+ vpFoldDisplayLog([NSString stringWithFormat:@"transform input=%@ output=%@", configuration, result]);
+ return result;
+}
+
+static NSArray *vpObservedAlwaysConnected(id self, SEL _cmd) {
+ NSArray *identities = ((NSArray *(*)(id, SEL))vpOriginalAlwaysConnected)(self, _cmd);
+ vpFoldDisplayLog([NSString stringWithFormat:@"observed %s count=%lu", sel_getName(_cmd), (unsigned long)identities.count]);
+ return identities;
+}
+
+// The measured main configuration is already 678x951. Keep bounded evidence
+// here while investigating how that configuration reaches scene traits.
+static IMP vpOriginalMainConfiguration;
+
+static id vpLoggedMainConfiguration(id self, SEL _cmd) {
+ id (*original)(id, SEL) = (id (*)(id, SEL))vpOriginalMainConfiguration;
+ id configuration = original(self, _cmd);
+ if (atomic_fetch_add_explicit(&vpConfigurationLogCount, 1, memory_order_relaxed) < 8)
+ vpFoldDisplayLog([NSString stringWithFormat:@"mainConfiguration -> %@", configuration]);
+ return configuration;
+}
+
+static IMP vpOriginalMainIdentity;
+
+static id vpLoggedMainIdentity(id self, SEL _cmd) {
+ id (*original)(id, SEL) = (id (*)(id, SEL))vpOriginalMainIdentity;
+ id identity = original(self, _cmd);
+ vpFoldDisplayLog([NSString stringWithFormat:@"mainIdentity -> %@", identity]);
+ return identity;
+}
+
+// Observe the native monitor inventory. A count readback alone does not
+// establish which native condition selects a home layout family.
+static IMP vpOriginalMonitorIdentities;
+
+static NSArray *vpObservedMonitorIdentities(id self, SEL _cmd) {
+ NSArray *identities = ((NSArray *(*)(id, SEL))vpOriginalMonitorIdentities)(self, _cmd);
+ vpFoldDisplayLog([NSString stringWithFormat:@"observed %s count=%lu", sel_getName(_cmd), (unsigned long)identities.count]);
+ return identities;
+}
+
+// Observe configuration counts; never invent a second hardware identity.
+static IMP vpOriginalLockConfigurations;
+
+static NSArray *vpObservedLockConfigurations(id self, SEL _cmd) {
+ NSArray *configurations = ((NSArray *(*)(id, SEL))vpOriginalLockConfigurations)(self, _cmd);
+ vpFoldDisplayLog([NSString stringWithFormat:@"observed %s count=%lu", sel_getName(_cmd), (unsigned long)configurations.count]);
+ return configurations;
+}
+
+// This initializer was not called in the baseline. Preserve its input exactly
+// if a different display transition eventually exercises it.
+static IMP vpOriginalMonitorInit;
+
+static id vpObservedMonitorInit(id self, SEL _cmd,
+ NSArray *displays, id mainDisplay,
+ id bookendObserver, id transformer) {
+ id (*original)(id, SEL, NSArray *, id, id, id) = (id (*)(id, SEL, NSArray *, id, id, id))vpOriginalMonitorInit;
+ return original(self, _cmd, displays, mainDisplay, bookendObserver, transformer);
+}
+
+// Disabling the broad server probe restored startup on the Duo guest. The
+// surviving log identified BKDisplayCloneMirroringManager as an evaluator
+// owner. Inspect only this class after startup; do not realize every class or
+// replace methods until their signatures and purpose have been established.
+static void vpInspectServerClass(void) {
+ Class cls = objc_getClass("BKDisplayCloneMirroringManager");
+ if (!cls) {
+ vpFoldDisplayLog(@"targeted server probe: class absent");
+ return;
+ }
+ unsigned int count = 0;
+ Method *methods = class_copyMethodList(cls, &count);
+ vpFoldDisplayLog([NSString stringWithFormat:@"targeted server probe: %u methods", count]);
+ for (unsigned int i = 0; i < count; i++) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"server method: %s types: %s",
+ sel_getName(method_getName(methods[i])), method_getTypeEncoding(methods[i])]);
+ }
+ free(methods);
+ vpFoldDisplayLog(@"targeted server probe: complete");
+}
+
+@protocol VPhoneVirtualDisplayInitialization
+- (instancetype)initWithOptions:(NSDictionary *)options;
+@end
+
+static id vpVirtualDisplayProbe;
+
+static void vpInspectRenderDisplays(void) {
+ @try {
+ Class cls = objc_getClass("CAWindowServer");
+ SEL running = sel_registerName("serverIfRunning");
+ if (![cls respondsToSelector:running]) return;
+ id server = ((id (*)(id, SEL))objc_msgSend)(cls, running);
+ if (![server respondsToSelector:sel_registerName("displays")]) return;
+ NSArray *displays = ((id (*)(id, SEL))objc_msgSend)(server, sel_registerName("displays"));
+ for (id display in displays) {
+ NSMutableDictionary *info = [NSMutableDictionary dictionary];
+ for (NSString *key in @[@"name", @"deviceName", @"displayId", @"displayType", @"systemIdentifiers", @"tag", @"enabled", @"extendedProperties"]) {
+ if (![display respondsToSelector:NSSelectorFromString(key)]) continue;
+ id value = [display valueForKey:key];
+ info[key] = value ?: NSNull.null;
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"render display metadata: %@", info]);
+ }
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"render display metadata exception: %@", exception.reason]);
+ }
+}
+
+static void vpEnableVirtualDisplayProbe(void) {
+ @try {
+ id display = vpVirtualDisplayProbe;
+ SEL getter = sel_registerName("enabled"), setter = sel_registerName("setEnabled:");
+ Method method = class_getInstanceMethod(object_getClass(display), setter);
+ if (!display || ![display respondsToSelector:getter] || !method ||
+ strcmp(method_getTypeEncoding(method), "v20@0:8B16") != 0) {
+ vpFoldDisplayLog(@"virtual display enable: unavailable");
+ return;
+ }
+ BOOL before = ((BOOL (*)(id, SEL))objc_msgSend)(display, getter);
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(display, setter, YES);
+ BOOL after = ((BOOL (*)(id, SEL))objc_msgSend)(display, getter);
+ vpFoldDisplayLog([NSString stringWithFormat:@"virtual display enable: before=%d after=%d", before, after]);
+ vpInspectRenderDisplays();
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"virtual display enable exception: %@", exception.reason]);
+ }
+}
+
+static void vpTagVirtualDisplayProbe(void) {
+ @try {
+ NSString *(*describe)(NSUInteger) = dlsym(RTLD_DEFAULT, "NSStringFromBKSDisplayTags");
+ SEL setter = sel_registerName("setTag:");
+ Method method = class_getInstanceMethod(object_getClass(vpVirtualDisplayProbe), setter);
+ if (!describe || !method || strcmp(method_getTypeEncoding(method), "v24@0:8q16") != 0) {
+ vpFoldDisplayLog(@"virtual display tag: unavailable");
+ return;
+ }
+ NSUInteger unknown = 0;
+ for (unsigned int bit = 0; bit < 24; bit++) {
+ NSUInteger candidate = (NSUInteger)1 << bit;
+ NSString *label = describe(candidate);
+ if (label && [label rangeOfString:@"unknown" options:NSCaseInsensitiveSearch].location != NSNotFound) {
+ if (unknown) { vpFoldDisplayLog(@"virtual display tag: ambiguous unknown bit"); return; }
+ unknown = candidate;
+ }
+ }
+ if (!unknown) { vpFoldDisplayLog(@"virtual display tag: no unknown bit"); return; }
+ ((void (*)(id, SEL, NSInteger))objc_msgSend)(vpVirtualDisplayProbe, setter, (NSInteger)unknown);
+ vpFoldDisplayLog([NSString stringWithFormat:@"virtual display tag: %@ (%lu)", describe(unknown), (unsigned long)unknown]);
+ vpInspectRenderDisplays();
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"virtual display tag exception: %@", exception.reason]);
+ }
+}
+
+static void vpVirtualDisplayExperiment(BOOL create) {
+ @try {
+ Class serverClass = objc_getClass("CAWindowServer");
+ SEL running = sel_registerName("serverIfRunning");
+ if (![serverClass respondsToSelector:running]) {
+ vpFoldDisplayLog(@"virtual display: server accessor absent");
+ return;
+ }
+ id server = ((id (*)(id, SEL))objc_msgSend)(serverClass, running);
+ SEL add = sel_registerName("addDisplay:"), remove = sel_registerName("removeDisplay:");
+ if (!server || ![server respondsToSelector:add] || ![server respondsToSelector:remove]) {
+ vpFoldDisplayLog(@"virtual display: no running render server");
+ return;
+ }
+ if (!create) {
+ if (vpVirtualDisplayProbe) {
+ ((void (*)(id, SEL, id))objc_msgSend)(server, remove, vpVirtualDisplayProbe);
+ vpVirtualDisplayProbe = nil;
+ }
+ vpFoldDisplayLog(@"virtual display: probe removed");
+ id remaining = ((id (*)(id, SEL))objc_msgSend)(server, sel_registerName("displays"));
+ vpFoldDisplayLog([NSString stringWithFormat:@"virtual display: server inventory after remove %@", remaining]);
+ return;
+ }
+ if (vpVirtualDisplayProbe) {
+ vpFoldDisplayLog(@"virtual display: probe already exists");
+ return;
+ }
+ Class cls = objc_getClass("CAWindowServerVirtualDisplay");
+ Method initializer = class_getInstanceMethod(cls, sel_registerName("initWithOptions:"));
+ if (!initializer || strcmp(method_getTypeEncoding(initializer), "@24@0:8@16") != 0) {
+ vpFoldDisplayLog(@"virtual display: initializer ABI unavailable");
+ return;
+ }
+ // Keys recovered from this guest's QuartzCore initializer. This is
+ // an independent software surface, never a new IOMFB hardware mode.
+ id display = [(id<VPhoneVirtualDisplayInitialization>)[cls alloc] initWithOptions:@{
+ @"kCAVirtualDisplayWidth": @1398, @"kCAVirtualDisplayHeight": @2034,
+ @"kCAVirtualDisplayUpdateRate": @60, @"kCAVirtualDisplayName": @"VPhone Cover Probe",
+ }];
+ if (!display) {
+ vpFoldDisplayLog(@"virtual display: initializer returned nil");
+ return;
+ }
+ vpVirtualDisplayProbe = display;
+ ((void (*)(id, SEL, id))objc_msgSend)(server, add, display);
+ vpFoldDisplayLog([NSString stringWithFormat:@"virtual display: registered %@", display]);
+ id inventory = ((id (*)(id, SEL))objc_msgSend)(server, sel_registerName("displays"));
+ vpFoldDisplayLog([NSString stringWithFormat:@"virtual display: server inventory after add %@", inventory]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"virtual display exception: %@", exception.reason]);
+ }
+}
+
+static void vpInspectHomeScreenType(void) {
+ void *home = dlopen("/System/Library/PrivateFrameworks/SpringBoardHome.framework/SpringBoardHome", RTLD_LAZY | RTLD_LOCAL);
+ NSUInteger (*current)(void) = dlsym(home, "SBHScreenTypeForCurrentDevice");
+ NSUInteger (*forScreen)(id) = dlsym(home, "SBHScreenTypeForScreen");
+ NSString *(*name)(NSUInteger) = dlsym(home, "SBHStringForScreenType");
+ NSUInteger (*forContexts)(id, id) = dlsym(home, "SBHScreenTypeForDeviceAndDisplayContexts");
+ // Independent native providers only. Compare actual family metrics;
+ // never install a provider or change the active icon model/layout.
+ Class providerClass = objc_getClass("SBHDefaultIconListLayoutProvider");
+ SEL initializerSelector = sel_registerName("initWithScreenType:layoutOptions:");
+ Method initializer = class_getInstanceMethod(providerClass, initializerSelector);
+ if (initializer && strcmp(method_getTypeEncoding(initializer), "@32@0:8Q16Q24") == 0) {
+ @try {
+ NSUInteger options = 0;
+ SEL optionsSelector = sel_registerName("defaultLayoutOptions");
+ if ([providerClass respondsToSelector:optionsSelector])
+ options = ((NSUInteger (*)(id, SEL))objc_msgSend)(providerClass, optionsSelector);
+ for (NSNumber *family in @[@23, @31, @32]) {
+ id provider = ((id (*)(id, SEL, NSUInteger, NSUInteger))objc_msgSend)(
+ [providerClass alloc], initializerSelector, family.unsignedIntegerValue, options);
+ for (NSString *symbol in @[@"SBIconLocationRoot", @"SBIconLocationRootWithWidgets"]) {
+ NSString *__unsafe_unretained *address = (NSString *__unsafe_unretained *)dlsym(home, symbol.UTF8String);
+ NSString *location = address ? *address : nil;
+ if (![location isKindOfClass:NSString.class]) continue;
+ id layout = ((id (*)(id, SEL, id))objc_msgSend)(provider, sel_registerName("layoutForIconLocation:"), location);
+ id configuration = vpReadObject(layout, "layoutConfiguration");
+ NSMutableDictionary *metrics = [NSMutableDictionary dictionary];
+ for (NSString *key in @[@"numberOfPortraitColumns", @"numberOfPortraitRows", @"numberOfLandscapeColumns", @"numberOfLandscapeRows",
+ @"portraitListSizeForIconSpacingCalculation", @"landscapeListSizeForIconSpacingCalculation",
+ @"portraitLayoutInsets", @"landscapeLayoutInsets"])
+ if ([configuration respondsToSelector:NSSelectorFromString(key)])
+ metrics[key] = [[configuration valueForKey:key] description] ?: NSNull.null;
+ vpFoldDisplayLog([NSString stringWithFormat:@"native family layout preview: type=%@ options=%lu location=%@ %@",
+ family, (unsigned long)options, location, metrics]);
+ }
+ }
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"native family layout preview exception: %@", exception.reason]);
+ }
+ }
+ Class screenClass = objc_getClass("UIScreen");
+ if (current && forScreen && name && screenClass) {
+ id screen = ((id (*)(id, SEL))objc_msgSend)(screenClass, sel_registerName("mainScreen"));
+ NSUInteger globalType = current(), screenType = forScreen(screen);
+ vpFoldDisplayLog([NSString stringWithFormat:@"home screen type: current=%lu %@ screen=%lu %@",
+ (unsigned long)globalType, name(globalType), (unsigned long)screenType, name(screenType)]);
+ id traits = ((id (*)(id, SEL))objc_msgSend)(screen, sel_registerName("traitCollection"));
+ SEL artworkGetter = sel_registerName("valueForNSIntegerTrait:");
+ Class artwork = objc_getClass("UITraitArtworkSubtype");
+ NSMethodSignature *signature = [traits methodSignatureForSelector:artworkGetter];
+ if (artwork && signature.numberOfArguments == 3 && signature.methodReturnType[0] == 'q') {
+ NSInteger subtype = ((NSInteger (*)(id, SEL, Class))objc_msgSend)(traits, artworkGetter, artwork);
+ vpFoldDisplayLog([NSString stringWithFormat:@"home screen artwork subtype: %ld", (long)subtype]);
+ }
+ Class platformClass = objc_getClass("BSPlatform");
+ if ([platformClass respondsToSelector:sel_registerName("sharedInstance")]) {
+ id platform = ((id (*)(id, SEL))objc_msgSend)(platformClass, sel_registerName("sharedInstance"));
+ vpFoldDisplayLog([NSString stringWithFormat:@"home platform: class=%@ homeButton=%@",
+ [platform valueForKey:@"deviceClass"], [platform valueForKey:@"homeButtonType"]]);
+ }
+ // Classify copies of the native contexts only. This tests whether
+ // missing artwork metadata explains the fallback family without
+ // modifying a screen, scene or global device context.
+ Class deviceContextClass = objc_getClass("UISDeviceContext");
+ Class displayContextClass = objc_getClass("UISDisplayContext");
+ SEL defaultDevice = sel_registerName("sb_defaultContext");
+ SEL defaultDisplay = sel_registerName("sb_defaultContextForDisplayConfiguration:");
+ if (forContexts && [deviceContextClass respondsToSelector:defaultDevice] &&
+ [displayContextClass respondsToSelector:defaultDisplay]) {
+ @try {
+ id deviceContext = ((id (*)(id, SEL))objc_msgSend)(deviceContextClass, defaultDevice);
+ id configuration = ((id (*)(id, SEL))objc_msgSend)(objc_getClass("FBDisplayManager"), sel_registerName("mainConfiguration"));
+ id displayContext = ((id (*)(id, SEL, id))objc_msgSend)(displayContextClass, defaultDisplay, configuration);
+ id copy = [displayContext mutableCopy];
+ SEL setArtwork = sel_registerName("setArtworkSubtype:");
+ Method setter = class_getInstanceMethod(object_getClass(copy), setArtwork);
+ if (copy && copy != displayContext && setter && strcmp(method_getTypeEncoding(setter), "v24@0:8Q16") == 0) {
+ id cachedConfiguration = ((id (*)(id, SEL))objc_msgSend)(displayContext, sel_registerName("displayConfiguration"));
+ CGRect cachedBounds = ((CGRect (*)(id, SEL))objc_msgSend)(cachedConfiguration, sel_registerName("bounds"));
+ vpFoldDisplayLog([NSString stringWithFormat:@"native family context: cached configuration %s %gx%g",
+ object_getClassName(cachedConfiguration), cachedBounds.size.width, cachedBounds.size.height]);
+ for (NSNumber *candidate in @[@0, @2034, @2853, @2796]) {
+ ((void (*)(id, SEL, NSUInteger))objc_msgSend)(copy, setArtwork, candidate.unsignedIntegerValue);
+ NSUInteger type = forContexts(deviceContext, copy);
+ vpFoldDisplayLog([NSString stringWithFormat:@"native family preview: artwork=%@ type=%lu %@",
+ candidate, (unsigned long)type, name(type)]);
+ }
+ ((void (*)(id, SEL, NSUInteger))objc_msgSend)(copy, setArtwork, 0);
+ id sourceMode = ((id (*)(id, SEL))objc_msgSend)(configuration, sel_registerName("currentMode"));
+ CGFloat scale = ((CGFloat (*)(id, SEL))objc_msgSend)(sourceMode, sel_registerName("pointScale"));
+ const CGSize candidateSizes[] = {{678, 951}, {669, 951}, {466, 678}};
+ for (NSUInteger index = 0; index < sizeof(candidateSizes) / sizeof(candidateSizes[0]); index++) {
+ CGSize size = candidateSizes[index];
+ id virtualMode = [(id<VPhoneDisplayModeCopying>)sourceMode _copyWithOverrideSize:size scale:scale];
+ id preview = [(id<VPhoneDisplayProjectionCopying>)configuration copyWithOverrideMode:virtualMode];
+ ((void (*)(id, SEL, id))objc_msgSend)(copy, sel_registerName("setDisplayConfiguration:"), preview);
+ NSUInteger type = forContexts(deviceContext, copy);
+ vpFoldDisplayLog([NSString stringWithFormat:@"native family geometry preview: %gx%g type=%lu %@",
+ size.width, size.height, (unsigned long)type, name(type)]);
+ }
+ }
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"native family preview exception: %@", exception.reason]);
+ }
+ }
+ }
+ Class cls = objc_getClass("SBIconListGridLayoutConfiguration");
+ unsigned int count = 0;
+ Method *methods = class_copyMethodList(cls, &count);
+ for (unsigned int i = 0; i < count; i++) {
+ const char *selector = sel_getName(method_getName(methods[i]));
+ if (strstr(selector, "init") || strstr(selector, "creen") || strstr(selector, "ize") || strstr(selector, "ayout"))
+ vpFoldDisplayLog([NSString stringWithFormat:@"grid method: %s types: %s", selector, method_getTypeEncoding(methods[i])]);
+ }
+ free(methods);
+ for (NSString *className in @[@"SBHDefaultIconListLayoutProvider", @"SBHCustomIconListLayoutProvider",
+ @"SBHMappedIconListLayoutProvider", @"SBHAdjustableRootIconListLayoutProvider",
+ @"SBHIconManager", @"SBIconController"]) {
+ Class provider = objc_getClass(className.UTF8String);
+ for (int meta = 0; meta < 2; meta++) {
+ unsigned int n = 0;
+ Method *list = class_copyMethodList(meta ? object_getClass(provider) : provider, &n);
+ for (unsigned int i = 0; i < n; i++) {
+ const char *selector = sel_getName(method_getName(list[i]));
+ if (([className isEqualToString:@"SBHIconManager"] || [className isEqualToString:@"SBIconController"]) &&
+ !strstr(selector, "ayout") && !strstr(selector, "hared") && !strstr(selector, "conManager")) continue;
+ vpFoldDisplayLog([NSString stringWithFormat:@"provider %@ %c%s types: %s", className,
+ meta ? '+' : '-', selector, method_getTypeEncoding(list[i])]);
+ }
+ free(list);
+ }
+ }
+}
+
+static id vpReadObject(id object, const char *name) {
+ SEL selector = sel_registerName(name);
+ NSMethodSignature *signature = [object methodSignatureForSelector:selector];
+ if (!signature || signature.numberOfArguments != 2 || signature.methodReturnType[0] != '@') return nil;
+ return ((id (*)(id, SEL))objc_msgSend)(object, selector);
+}
+
+static id vpReadMultilineDescription(id object) {
+ SEL selector = sel_registerName("descriptionWithMultilinePrefix:");
+ Method method = class_getInstanceMethod(object_getClass(object), selector);
+ if (!method || strcmp(method_getTypeEncoding(method), "@24@0:8@16") != 0) return nil;
+ return ((id (*)(id, SEL, id))objc_msgSend)(object, selector, @"");
+}
+
+static id vpReadObjectIvar(id object, const char *name) {
+ Ivar ivar = class_getInstanceVariable(object_getClass(object), name);
+ const char *type = ivar ? ivar_getTypeEncoding(ivar) : NULL;
+ return type && type[0] == '@' ? object_getIvar(object, ivar) : nil;
+}
+
+// One physical panel can expose only the active fold surface. Test the
+// content-readiness boundary without promoting a virtual CADisplay, adding
+// a source, or bypassing the native one-result transformer invariant.
+// This hook is installed only for an explicitly consumed startup flag.
+static void vpResolveSingleInnerDisplay(id self, SEL cmd, id proxy) {
+ ((void (*)(id, SEL, id))vpOriginalStartResolvingDisplay)(self, cmd, proxy);
+ if (vpLogicalRoleExperiment) {
+ vpLogicalRoleResolver = self;
+ vpSyncLogicalRoleResolver();
+ return;
+ }
+ @try {
+ NSDictionary *proxies = vpReadObjectIvar(self, "_displayProxies");
+ if (proxies.count != 1 || proxies.allValues.firstObject != proxy ||
+ [[self valueForKey:@"isReadyToResolve"] boolValue] ||
+ [[proxy valueForKey:@"isExternal"] boolValue] ||
+ [[proxy valueForKey:@"surfaceType"] integerValue] != 2) return;
+ id monitor = vpReadObject(objc_getClass("FBDisplayManager"), "sharedInstance");
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ id identity = vpReadObject(configuration, "identity");
+ NSSet *connected = vpReadObject(monitor, "connectedIdentities");
+ if (connected.count != 1 || ![connected containsObject:identity] ||
+ ![[identity valueForKey:@"isMainRootDisplay"] boolValue]) return;
+ Ivar ready = class_getInstanceVariable(object_getClass(self), "_isReadyToResolve");
+ SEL update = sel_registerName("_updateResolvedContentModesForDisplays");
+ Method method = class_getInstanceMethod(object_getClass(self), update);
+ if (!ready || strcmp(ivar_getTypeEncoding(ready), "B") != 0 ||
+ !method || strcmp(method_getTypeEncoding(method), "v16@0:8") != 0) return;
+ [self setValue:@YES forKey:@"isReadyToResolve"];
+ vpFoldDisplayLog(@"single inner readiness: one real Main, one nonexternal inner proxy; native content resolution requested");
+ ((void (*)(id, SEL))objc_msgSend)(self, update);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"single inner readiness exception: %@", exception.reason]);
+ }
+}
+
+static id vpRootServerScenes(id app) {
+ return vpReadObject(vpReadObject(app, "displayProfileManager"), "fbScenes");
+}
+
+static NSNumber *vpReadBoolValue(id object, const char *name) {
+ SEL selector = sel_registerName(name);
+ NSMethodSignature *signature = [object methodSignatureForSelector:selector];
+ if (!signature || signature.numberOfArguments != 2 ||
+ (signature.methodReturnType[0] != 'B' && signature.methodReturnType[0] != 'c')) return nil;
+ return @(((BOOL (*)(id, SEL))objc_msgSend)(object, selector));
+}
+
+static NSValue *vpReadRectValue(id object, const char *name) {
+ SEL selector = sel_registerName(name);
+ NSMethodSignature *signature = [object methodSignatureForSelector:selector];
+ if (!signature || signature.numberOfArguments != 2 ||
+ strcmp(signature.methodReturnType, "{CGRect={CGPoint=dd}{CGSize=dd}}") != 0) return nil;
+ CGRect value = ((CGRect (*)(id, SEL))objc_msgSend)(object, selector);
+ return [NSValue value:&value withObjCType:@encode(CGRect)];
+}
+
+static void vpSyncLogicalRoleResolver(void) {
+ @try {
+ id resolver = vpLogicalRoleResolver;
+ NSDictionary *proxies = vpReadObjectIvar(resolver, "_displayProxies");
+ if (!vpLogicalRoleExperiment || proxies.count != 1) return;
+ id proxy = proxies.allValues.firstObject;
+ if (![vpReadObject(proxy, "identifier") isEqual:@"legacyMain"] ||
+ [[proxy valueForKey:@"isExternal"] boolValue]) return;
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ if (![[vpReadObject(configuration, "identity") valueForKey:@"isMainRootDisplay"] boolValue]) return;
+ SEL boundsSelector = sel_registerName("bounds");
+ NSMethodSignature *signature = [configuration methodSignatureForSelector:boundsSelector];
+ if (signature.methodReturnLength != sizeof(CGRect)) return;
+ CGRect bounds = ((CGRect (*)(id, SEL))objc_msgSend)(configuration, boundsSelector);
+ NSInteger role = CGRectEqualToRect(bounds, CGRectMake(0, 0, 669, 951)) ? 2 :
+ (CGRectEqualToRect(bounds, CGRectMake(0, 0, 466, 678)) ? 1 : 0);
+ SEL setter = sel_registerName("setSurfaceType:");
+ SEL update = sel_registerName("_updateResolvedContentModesForDisplays");
+ Method sm = class_getInstanceMethod(object_getClass(proxy), setter);
+ Method um = class_getInstanceMethod(object_getClass(resolver), update);
+ Ivar ready = class_getInstanceVariable(object_getClass(resolver), "_isReadyToResolve");
+ if (!role || !sm || strcmp(method_getTypeEncoding(sm), "v24@0:8q16") != 0 ||
+ !um || strcmp(method_getTypeEncoding(um), "v16@0:8") != 0 ||
+ !ready || strcmp(ivar_getTypeEncoding(ready), "B") != 0) return;
+ ((void (*)(id, SEL, NSInteger))objc_msgSend)(proxy, setter, role);
+ [resolver setValue:@YES forKey:@"isReadyToResolve"];
+ ((void (*)(id, SEL))objc_msgSend)(resolver, update);
+ vpFoldDisplayLog([NSString stringWithFormat:@"logical surface resolver: single Main role=%ld %@", (long)role, resolver]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"logical surface resolver exception: %@", exception.reason]);
+ }
+}
+
+static BOOL vpAllowScopedMainWindowResize(id self, SEL cmd) {
+ BOOL original = ((BOOL (*)(id, SEL))vpOriginalSBWindowResizePolicy)(self, cmd);
+ id scope = vpSceneResizeScope;
+ return original || (scope && vpReadObject(self, "windowScene") == scope);
+}
+
+// Native SBHIconManager owns the provider family independently of UIScreen.
+// Its native setter rebuilds the provider and updates root-folder and Dock
+// consumers; do not replace individual views or reset the user's icon model.
+static void vpRefreshSceneIconFamily(id windowScene) {
+ if (![vpReadObject(vpReadObject(windowScene, "_FBSScene"), "identifier") isEqual:@"SB-main"]) return;
+ Method familyMethod = class_getInstanceMethod(object_getClass(windowScene), sel_registerName("sbhScreenType"));
+ if (!familyMethod || strcmp(method_getTypeEncoding(familyMethod), "Q16@0:8") != 0) return;
+ NSUInteger family = ((NSUInteger (*)(id, SEL))objc_msgSend)(windowScene, sel_registerName("sbhScreenType"));
+ if (family != 31 && family != 32) return;
+ for (id window in vpReadObject(windowScene, "windows")) {
+ id controller = vpReadObject(window, "rootViewController");
+ Class homeClass = objc_getClass("SBHomeScreenViewController");
+ if (!homeClass || ![controller isKindOfClass:homeClass]) continue;
+ id manager = vpReadObjectIvar(controller, "_iconManager");
+ SEL update = sel_registerName("setScreenType:listLayoutProviderLayoutOptions:animated:");
+ Method method = class_getInstanceMethod(object_getClass(manager), update);
+ Method optionsMethod = class_getInstanceMethod(object_getClass(manager), sel_registerName("listLayoutProviderLayoutOptions"));
+ Ivar screenType = class_getInstanceVariable(object_getClass(manager), "_screenType");
+ if (!method || strcmp(method_getTypeEncoding(method), "v36@0:8Q16Q24B32") != 0 ||
+ !optionsMethod || strcmp(method_getTypeEncoding(optionsMethod), "Q16@0:8") != 0 ||
+ !screenType || strcmp(ivar_getTypeEncoding(screenType), "Q") != 0) return;
+ NSUInteger before = [[manager valueForKey:@"screenType"] unsignedIntegerValue];
+ NSUInteger options = ((NSUInteger (*)(id, SEL))objc_msgSend)(manager, sel_registerName("listLayoutProviderLayoutOptions"));
+ ((void (*)(id, SEL, NSUInteger, NSUInteger, BOOL))objc_msgSend)(manager, update, family, options, NO);
+ vpFoldDisplayLog([NSString stringWithFormat:@"native icon family: %lu -> %@ requested=%lu provider=%@",
+ (unsigned long)before, [manager valueForKey:@"screenType"], (unsigned long)family,
+ vpReadObject(manager, "listLayoutProvider")]);
+ return;
+ }
+}
+
+static void vpPropagateSceneBounds(id windowScene, unsigned int generation) {
+ if (generation != atomic_load_explicit(&vpViewportRequestGeneration, memory_order_relaxed)) return;
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ NSString *identifier = vpReadObject(vpReadObject(windowScene, "_FBSScene"), "identifier");
+ if (!identifier || vpResizedSceneGenerations[identifier].unsignedIntValue == generation) return;
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ id identity = vpReadObject(configuration, "identity");
+ BOOL owned = NO;
+ for (id scene in vpRootServerScenes(app)) {
+ id hosted = vpReadObject(vpReadObject(scene, "uiSettings"), "sb_hostedDisplayConfiguration");
+ if ([vpReadObject(scene, "identifier") isEqual:identifier] &&
+ [vpReadObject(hosted, "identity") isEqual:identity]) { owned = YES; break; }
+ }
+ if (!owned) return;
+ CGRect target = ((CGRect (*)(id, SEL))objc_msgSend)(configuration, sel_registerName("bounds"));
+ CGRect actual = ((CGRect (*)(id, SEL))objc_msgSend)(vpReadObject(windowScene, "coordinateSpace"), sel_registerName("bounds"));
+ if (!CGSizeEqualToSize(target.size, actual.size)) return;
+ vpResizedSceneGenerations[identifier] = @(generation);
+ id previousScope = vpSceneResizeScope;
+ NSUInteger notified = 0, changed = 0;
+ @try {
+ vpSceneResizeScope = windowScene;
+ NSArray *windows = [vpReadObject(windowScene, "windows") copy];
+ for (id window in windows) {
+ if (vpReadObject(window, "windowScene") != windowScene ||
+ !vpReadBoolValue(window, "_isSceneSized").boolValue) continue;
+ // Preserve SpringBoard's TRA-owned transform/rotation state.
+ // The full scene-bounds callback also updates transform layers;
+ // only its native sizing substep belongs in this adapter.
+ SEL update = sel_registerName("_resizeWindowFrameToSceneBoundsIfNecessary");
+ Method method = class_getInstanceMethod(object_getClass(window), update);
+ if (!method || strcmp(method_getTypeEncoding(method), "B16@0:8") != 0) continue;
+ @try {
+ NSValue *before = vpReadRectValue(window, "frame");
+ ((BOOL (*)(id, SEL))objc_msgSend)(window, update);
+ notified++;
+ if (![before isEqual:vpReadRectValue(window, "frame")]) changed++;
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"scene resize propagation window exception: %@", exception.reason]);
+ }
+ }
+ if (vpLogicalRoleExperiment) vpSyncLogicalRoleResolver();
+ vpRefreshSceneIconFamily(windowScene);
+if (vpAutomaticMainStatus) vpRefreshMainStatusRenderer();
+ if (vpPersistentViewport && [identifier isEqual:@"SB-main"])
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (generation == atomic_load_explicit(&vpViewportRequestGeneration, memory_order_acquire))
+ vpProcessViewportWorkspaceRequest(YES);
+ });
+ } @finally { vpSceneResizeScope = previousScope; }
+ vpFoldDisplayLog([NSString stringWithFormat:@"scene resize propagation: %@ generation=%u native notifications=%lu frames changed=%lu",
+ identifier, generation, (unsigned long)notified, (unsigned long)changed]);
+}
+
+static void vpObserveSceneGeometry(id self, SEL cmd, id windowScene, id previousSpace,
+ NSInteger previousOrientation, id previousTraits) {
+ ((void (*)(id, SEL, id, id, NSInteger, id))vpOriginalSceneGeometryCallback)(
+ self, cmd, windowScene, previousSpace, previousOrientation, previousTraits);
+ if (!atomic_load_explicit(&vpNativeGeometryRefreshEnabled, memory_order_acquire) &&
+ !atomic_load_explicit(&vpSceneResizePropagationEnabled, memory_order_acquire)) return;
+ unsigned int generation = atomic_load_explicit(&vpViewportRequestGeneration, memory_order_relaxed);
+ dispatch_async(dispatch_get_main_queue(), ^{
+ @try {
+ if (generation != atomic_load_explicit(&vpViewportRequestGeneration, memory_order_relaxed)) return;
+ if (atomic_load_explicit(&vpSceneResizePropagationEnabled, memory_order_acquire))
+ vpPropagateSceneBounds(windowScene, generation);
+ if (!atomic_load_explicit(&vpNativeGeometryRefreshEnabled, memory_order_acquire) ||
+ generation == atomic_load_explicit(&vpWindowGeometryRefreshGeneration, memory_order_relaxed)) return;
+ if (![vpReadObject(vpReadObject(windowScene, "_FBSScene"), "identifier") isEqual:@"SB-main"]) return;
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ CGRect target = ((CGRect (*)(id, SEL))objc_msgSend)(configuration, sel_registerName("bounds"));
+ id space = vpReadObject(windowScene, "coordinateSpace");
+ CGRect actual = ((CGRect (*)(id, SEL))objc_msgSend)(space, sel_registerName("bounds"));
+ if (!CGSizeEqualToSize(target.size, actual.size)) return;
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ SEL update = sel_registerName("_notePipelineManagerChangedInterfaceOrientation:onWindowScene:duration:force:logMessage:");
+ Method method = class_getInstanceMethod(object_getClass(app), update);
+ if (!method || strcmp(method_getTypeEncoding(method), "v52@0:8q16@24d32B40@44") != 0) {
+ vpFoldDisplayLog(@"native geometry refresh: pipeline callback ABI unavailable");
+ return;
+ }
+ NSInteger orientation = ((NSInteger (*)(id, SEL))objc_msgSend)(windowScene, sel_registerName("interfaceOrientation"));
+ if (orientation < 1 || orientation > 4) return;
+ atomic_store_explicit(&vpWindowGeometryRefreshGeneration, generation, memory_order_relaxed);
+ ((void (*)(id, SEL, NSInteger, id, CGFloat, BOOL, id))objc_msgSend)(app, update,
+ orientation, windowScene, 0, YES, @"vphone logical display geometry refresh");
+ vpFoldDisplayLog([NSString stringWithFormat:@"native geometry refresh: orientation=%ld generation=%u",
+ (long)orientation, generation]);
+ if (!atomic_load_explicit(&vpCoverViewportEnabled, memory_order_acquire) &&
+ generation == atomic_load_explicit(&vpViewportRequestGeneration, memory_order_relaxed))
+ atomic_store_explicit(&vpNativeGeometryRefreshEnabled, false, memory_order_release);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"native geometry refresh exception: %@", exception.reason]);
+ }
+ });
+}
+
+static id vpSnapshotRect(id object, const char *name) {
+ NSValue *value = vpReadRectValue(object, name);
+ if (!value) return NSNull.null;
+ CGRect rect;
+ [value getValue:&rect size:sizeof(rect)];
+ return @[@(rect.origin.x), @(rect.origin.y), @(rect.size.width), @(rect.size.height)];
+}
+
+static NSNumber *vpSnapshotScalarIvar(id object, const char *name) {
+ Ivar ivar = class_getInstanceVariable(object_getClass(object), name);
+ const char *type = ivar ? ivar_getTypeEncoding(ivar) : NULL;
+ if (!type) return nil;
+ const void *address = (const char *)(__bridge void *)object + ivar_getOffset(ivar);
+ if (strcmp(type, "B") == 0 || strcmp(type, "c") == 0) {
+ uint8_t value; memcpy(&value, address, sizeof(value)); return @(value != 0);
+ }
+ if (strcmp(type, "q") == 0) { int64_t value; memcpy(&value, address, sizeof(value)); return @(value); }
+ if (strcmp(type, "Q") == 0) { uint64_t value; memcpy(&value, address, sizeof(value)); return @(value); }
+ return nil;
+}
+
+// The SB-main orientation map is the contract vphoned's Duo rotation and
+// posture paths poll (vp_display_orientation_mapping). Publish the live
+// scene geometry on demand, at startup, and after each viewport change;
+// without this file the daemon sees "map unavailable" and refuses every
+// posture/rotation settle.
+static void vpExportNativeOrientationMapping(void) {
+ vpFoldDisplayLog(@"native orientation mapping export requested");
+ @try {
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ if (!app) return;
+ id scene = vpReadObject(app, "activeDisplayWindowScene") ?: vpReadObject(app, "embeddedDisplayWindowScene");
+ if (!scene) return;
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ if (!configuration) return;
+ id screen = vpReadObject(scene, "screen");
+ double scale = 3;
+ @try {
+ id scaleValue = screen ? [screen valueForKey:@"scale"] : nil;
+ if ([scaleValue respondsToSelector:@selector(doubleValue)]) scale = [scaleValue doubleValue];
+ } @catch (NSException *exception) { }
+ long long interfaceOrientation = 1;
+ SEL orientationSelector = sel_registerName("interfaceOrientation");
+ if ([scene respondsToSelector:orientationSelector])
+ interfaceOrientation = ((long long (*)(id, SEL))objc_msgSend)(scene, orientationSelector);
+ unsigned long long surfaceType = 0;
+ SEL surfaceSelector = sel_registerName("sbhScreenType");
+ if ([scene respondsToSelector:surfaceSelector])
+ surfaceType = ((unsigned long long (*)(id, SEL))objc_msgSend)(scene, surfaceSelector);
+ // The daemon resolves interface requests through the device table;
+ // the native scene owns the real inverse mounting map (the Duo inner
+ // panel mounts rotated, measured [3,4,2,1] on iPhone19,4). The
+ // identity table stays only as the fallback for a scene without the
+ // conversion selectors.
+ NSMutableArray *deviceOrientations = [NSMutableArray arrayWithArray:@[@1, @2, @3, @4]];
+ NSMutableArray *systemSpaceOrientations = [NSMutableArray arrayWithArray:@[@1, @2, @3, @4]];
+ for (NSString *name in @[@"deviceOrientationForSystemSpaceOrientation:", @"systemSpaceOrientationForDeviceOrientation:"]) {
+ SEL selector = NSSelectorFromString(name);
+ Method method = class_getInstanceMethod(object_getClass(scene), selector);
+ if (!method || strcmp(method_getTypeEncoding(method), "q24@0:8q16") != 0) continue;
+ NSMutableArray *table = [NSMutableArray arrayWithCapacity:4];
+ for (NSInteger direction = 1; direction <= 4; direction++)
+ [table addObject:@(((NSInteger (*)(id, SEL, NSInteger))objc_msgSend)(scene, selector, direction))];
+ if (![[NSSet setWithArray:table] isEqualToSet:[NSSet setWithArray:@[@1, @2, @3, @4]]]) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"native orientation mapping export: %@ returned non-permutation %@; keeping fallback", name, table]);
+ continue;
+ }
+ if ([name hasPrefix:@"deviceOrientation"]) deviceOrientations = table;
+ else systemSpaceOrientations = table;
+ }
+ NSDictionary *map = @{
+ @"version": @1,
+ @"scene": @"SB-main",
+ @"pid": @(getpid()),
+ @"generatedUptime": @(NSProcessInfo.processInfo.systemUptime),
+ @"available": @YES,
+ @"persistentViewport": @(vpPersistentViewport ? YES : NO),
+ @"deviceOrientations": deviceOrientations,
+ @"systemSpaceOrientations": systemSpaceOrientations,
+ @"scale": @(scale),
+ @"surfaceType": @(surfaceType),
+ @"viewportGeneration": @(atomic_load_explicit(&vpViewportRequestGeneration, memory_order_relaxed)),
+ @"interfaceOrientation": @(interfaceOrientation),
+ @"configurationBounds": vpSnapshotRect(configuration, "bounds"),
+ @"coordinateBounds": vpSnapshotRect(vpReadObject(scene, "coordinateSpace"), "bounds") ?: NSNull.null,
+ @"bounds": vpSnapshotRect(configuration, "bounds"),
+ };
+ NSData *data = [NSJSONSerialization dataWithJSONObject:map options:0 error:NULL];
+ if (![data writeToFile:@"/var/mobile/Library/Caches/vphone-display-orientation-map.json" atomically:YES]) {
+ vpFoldDisplayLog(@"native orientation mapping export: write failed");
+ return;
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"native orientation mapping export: generation=%u bounds=%@ interface=%lld persistent=%d",
+ atomic_load_explicit(&vpViewportRequestGeneration, memory_order_relaxed),
+ map[@"configurationBounds"], interfaceOrientation, vpPersistentViewport ? 1 : 0]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"native orientation mapping export exception: %@", exception.reason]);
+ }
+}
+
+static id vpSnapshotPoseDirections(id provider) {
+ SEL selector = sel_registerName("currentPose");
+ NSMethodSignature *signature = [provider methodSignatureForSelector:selector];
+ // The shipped SBF pose begins with three native q orientations. Match
+ // the runtime aggregate ABI, rather than declaring a guessed C struct.
+ if (!signature || signature.numberOfArguments != 2 || signature.methodReturnLength < 24 ||
+ signature.methodReturnLength > 1024 || strncmp(signature.methodReturnType, "{?=qqq", 6) != 0) return NSNull.null;
+ NSMutableData *bytes = [NSMutableData dataWithLength:signature.methodReturnLength];
+ NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
+ invocation.target = provider;
+ invocation.selector = selector;
+ [invocation invoke];
+ [invocation getReturnValue:bytes.mutableBytes];
+ int64_t directions[3]; memcpy(directions, bytes.bytes, sizeof(directions));
+ return @[@(directions[0]), @(directions[1]), @(directions[2])];
+}
+
+// One bounded JSON line: do not format the arbiter, class inventories or
+// controller/model descriptions on SpringBoard's main queue during tests.
+static void vpSnapshotMainScene(void) {
+ CFAbsoluteTime started = CFAbsoluteTimeGetCurrent();
+ @try {
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ id scene = vpReadObject(app, "activeDisplayWindowScene") ?: vpReadObject(app, "embeddedDisplayWindowScene");
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ id screen = vpReadObject(scene, "screen");
+ NSMutableDictionary *snapshot = [NSMutableDictionary dictionaryWithDictionary:@{
+ @"pid": @(getpid()), @"time": @(started),
+ @"viewportGeneration": @(atomic_load_explicit(&vpViewportRequestGeneration, memory_order_relaxed)),
+ @"configurationBounds": vpSnapshotRect(configuration, "bounds"),
+ @"scene": vpReadObject(vpReadObject(scene, "_FBSScene"), "identifier") ?: NSNull.null,
+ @"coordinateBounds": vpSnapshotRect(vpReadObject(scene, "coordinateSpace"), "bounds"),
+ @"screenBounds": vpSnapshotRect(screen, "bounds"),
+ @"screenNativeBounds": vpSnapshotRect(screen, "nativeBounds"),
+ }];
+ id pipeline = vpReadObject(scene, "traitsPipelineManager");
+ id snapshotIdentity = vpReadObject(configuration, "identity");
+ for (NSString *key in @[@"isMainDisplay", @"isMainRootDisplay", @"isRootIdentity", @"isUIKitMainLike", @"isAlwaysConnected"])
+ snapshot[[@"identity." stringByAppendingString:key]] = [snapshotIdentity valueForKey:key] ?: NSNull.null;
+ for (NSString *key in @[@"isMainDisplayWindowScene", @"isLegacyMainEmbeddedScene"])
+ snapshot[[@"scene." stringByAppendingString:key]] = vpReadBoolValue(scene, key.UTF8String) ?: NSNull.null;
+ id statusManager = vpReadObject(scene, "statusBarManager");
+ snapshot[@"statusManagerClass"] = statusManager ? NSStringFromClass(object_getClass(statusManager)) : NSNull.null;
+ snapshot[@"statusManagerEmbedded"] = vpReadBoolValue(statusManager, "_isEmbeddedDisplay") ?: NSNull.null;
+ snapshot[@"statusManagerHidden"] = vpReadBoolValue(statusManager, "isStatusBarHidden") ?: NSNull.null;
+ snapshot[@"screenUserInterfaceIdiom"] = [screen valueForKey:@"_userInterfaceIdiom"] ?: NSNull.null;
+ snapshot[@"screenTraitUserInterfaceIdiom"] = [vpReadObject(screen, "traitCollection") valueForKey:@"userInterfaceIdiom"] ?: NSNull.null;
+ id uiConfiguration = vpReadObject(scene, "_sbDisplayConfiguration");
+ id clientIdentity = vpReadObject(scene, "_fbsDisplayIdentity");
+ snapshot[@"uiConfigurationIdentifier"] = vpReadObject(vpReadObject(uiConfiguration, "identity"), "uniqueIdentifier") ?: NSNull.null;
+ snapshot[@"clientDisplayIdentifier"] = vpReadObject(clientIdentity, "uniqueIdentifier") ?: NSNull.null;
+ snapshot[@"clientDisplayType"] = [clientIdentity valueForKey:@"type"] ?: NSNull.null;
+ id serverSettingsForSnapshot = nil;
+ for (id serverScene in vpRootServerScenes(app))
+ if ([vpReadObject(serverScene, "identifier") isEqual:@"SB-main"]) { serverSettingsForSnapshot = vpReadObject(serverScene, "uiSettings"); break; }
+ snapshot[@"serverHostedIdentifier"] = vpReadObject(vpReadObject(vpReadObject(serverSettingsForSnapshot, "sb_hostedDisplayConfiguration"), "identity"), "uniqueIdentifier") ?: NSNull.null;
+ snapshot[@"serverDisplayIdentifier"] = vpReadObject(vpReadObject(serverSettingsForSnapshot, "displayIdentity"), "uniqueIdentifier") ?: NSNull.null;
+ snapshot[@"connectedDisplayCount"] = @([vpReadObject(vpReadObject(objc_getClass("FBDisplayManager"), "sharedInstance"), "alwaysConnectedIdentities") count]);
+ snapshot[@"caDisplayObjectCount"] = @([vpReadObject(objc_getClass("CADisplay"), "displays") count]);
+ snapshot[@"sceneScreenType"] = [scene valueForKey:@"sbhScreenType"] ?: NSNull.null;
+ void *home = dlopen("/System/Library/PrivateFrameworks/SpringBoardHome.framework/SpringBoardHome", RTLD_LAZY | RTLD_LOCAL);
+ NSUInteger (*globalFamily)(void) = dlsym(home, "SBHScreenTypeForCurrentDevice");
+ NSUInteger (*screenFamily)(id) = dlsym(home, "SBHScreenTypeForScreen");
+ if (globalFamily) snapshot[@"globalScreenType"] = @(globalFamily());
+ if (screenFamily) snapshot[@"screenScreenType"] = @(screenFamily(screen));
+ id geometry = vpReadObject(scene, "effectiveGeometry");
+ if ([geometry respondsToSelector:sel_registerName("interfaceOrientation")])
+ snapshot[@"effectiveGeometryOrientation"] = [geometry valueForKey:@"interfaceOrientation"];
+ for (NSString *name in @[@"systemSpaceOrientationForDeviceOrientation:", @"deviceOrientationForSystemSpaceOrientation:"]) {
+ SEL selector = NSSelectorFromString(name);
+ Method method = class_getInstanceMethod(object_getClass(scene), selector);
+ if (method && strcmp(method_getTypeEncoding(method), "q24@0:8q16") == 0) {
+ NSMutableArray *mapping = [NSMutableArray array];
+ for (NSInteger direction = 1; direction <= 4; direction++)
+ [mapping addObject:@(((NSInteger (*)(id, SEL, NSInteger))objc_msgSend)(scene, selector, direction))];
+ snapshot[name] = mapping;
+ }
+ }
+ snapshot[@"providerDirections"] = vpSnapshotPoseDirections(vpReadObjectIvar(pipeline, "_devicePoseProvider"));
+ for (NSString *name in @[@"_settingUpPipeline", @"_arbiterRunningUpdatesCount", @"_isCoversheetPresented", @"_isContinuousFoldSettleWindowActive", @"_continuousFoldHolderCount",
+ @"_continuousFoldPinnedDeviceOrientation", @"_isDevicePoseOverridingOrientationLock"])
+ snapshot[name] = vpSnapshotScalarIvar(pipeline, name.UTF8String) ?: NSNull.null;
+ for (NSString *name in @[@"activeInterfaceOrientation", @"statusBarOrientationForEmbeddedDisplay", @"statusBarOrientation"])
+ if ([app respondsToSelector:NSSelectorFromString(name)])
+ snapshot[[@"application." stringByAppendingString:name]] = [app valueForKey:name];
+ id deferrals = vpReadObjectIvar(pipeline, "_deviceOrientationUpdateDeferralManager");
+ SEL deferred = sel_registerName("isCurrentlyDeferringOrientationUpdatesForWindowScene:");
+ Method deferredMethod = class_getInstanceMethod(object_getClass(deferrals), deferred);
+ if (deferredMethod && strcmp(method_getTypeEncoding(deferredMethod), "B24@0:8@16") == 0)
+ snapshot[@"deferringOrientation"] = @(((BOOL (*)(id, SEL, id))objc_msgSend)(deferrals, deferred, scene));
+ for (NSString *getter in @[@"_effectiveUISettings", @"_effectiveUIClientSettings"]) {
+ id settings = vpReadObject(scene, getter.UTF8String);
+ if ([settings respondsToSelector:sel_registerName("interfaceOrientation")])
+ snapshot[getter] = [settings valueForKey:@"interfaceOrientation"];
+ }
+ for (NSString *name in @[@"interfaceOrientation", @"surfaceType"])
+ if ([scene respondsToSelector:NSSelectorFromString(name)]) snapshot[name] = [scene valueForKey:name];
+ for (NSString *name in @[@"systemArbitratedDeviceOrientation", @"systemArbitratedInterfaceOrientation", @"continuousFoldPinnedInterfaceOrientation"])
+ if ([pipeline respondsToSelector:NSSelectorFromString(name)]) snapshot[name] = [pipeline valueForKey:name];
+ NSMutableArray *roots = [NSMutableArray array];
+ for (id root in vpRootServerScenes(app)) {
+ id settings = vpReadObject(root, "uiSettings");
+ [roots addObject:@{@"identifier": vpReadObject(root, "identifier") ?: NSNull.null,
+ @"orientation": [settings valueForKey:@"interfaceOrientation"] ?: NSNull.null,
+ @"frame": vpSnapshotRect(settings, "frame")}];
+ }
+ snapshot[@"roots"] = roots;
+ NSMutableArray *windows = [NSMutableArray array];
+ for (id window in vpReadObject(scene, "windows")) {
+ id controller = vpReadObject(window, "rootViewController");
+ NSMutableDictionary *row = [NSMutableDictionary dictionaryWithDictionary:@{
+ @"class": NSStringFromClass(object_getClass(window)),
+ @"frame": vpSnapshotRect(window, "frame"), @"bounds": vpSnapshotRect(window, "bounds"),
+ @"hidden": [window valueForKey:@"hidden"], @"orientation": [window valueForKey:@"interfaceOrientation"],
+ @"rootClass": controller ? NSStringFromClass(object_getClass(controller)) : NSNull.null,
+ @"rootFrame": vpSnapshotRect(vpReadObject(controller, "viewIfLoaded"), "frame"),
+ }];
+ for (NSString *name in @[@"orientation", @"effectiveOrientation", @"supportedInterfaceOrientations"])
+ if ([controller respondsToSelector:NSSelectorFromString(name)])
+ row[[@"controller." stringByAppendingString:name]] = [controller valueForKey:name];
+ for (NSString *name in @[@"orientation", @"_sbStatusBarWindowShouldRotate", @"_sbStatusBarWindowSupportedOrientations"]) {
+ Method method = class_getInstanceMethod(object_getClass(window), NSSelectorFromString(name));
+ char *type = method ? method_copyReturnType(method) : NULL;
+ if (type && (strcmp(type, "q") == 0 || strcmp(type, "Q") == 0 || strcmp(type, "B") == 0))
+ row[[@"native." stringByAppendingString:name]] = [window valueForKey:name];
+ free(type);
+ }
+ [windows addObject:row];
+ if (windows.count == 32) break;
+ }
+ snapshot[@"windows"] = windows;
+ snapshot[@"elapsedMs"] = @((CFAbsoluteTimeGetCurrent() - started) * 1000);
+ NSData *data = [NSJSONSerialization dataWithJSONObject:snapshot options:0 error:NULL];
+ if (data) vpFoldDisplayLog([@"snapshot " stringByAppendingString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"snapshot exception: %@", exception.reason]);
+ }
+}
+
+static void vpProcessViewportWorkspaceRequest(BOOL submit) {
+ @try {
+ id workspace = vpReadObject(objc_getClass("SBMainWorkspace"), "sharedInstance");
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ SEL create = sel_registerName("createRequestWithOptions:displayConfiguration:");
+ Method method = class_getInstanceMethod(object_getClass(workspace), create);
+ if (!workspace || !configuration || !method || strcmp(method_getTypeEncoding(method), "@32@0:8Q16@24") != 0) {
+ vpFoldDisplayLog(@"viewport workspace preview: factory unavailable"); return;
+ }
+ // Native factory and local finalization only; never submit or run this preview.
+ id request = ((id (*)(id, SEL, NSUInteger, id))objc_msgSend)(workspace, create, 0, configuration);
+ id context = vpReadObject(request, "applicationContext");
+ vpFoldDisplayLog([NSString stringWithFormat:@"viewport workspace preview: request=%@ context=%@ from=%@ to=%@",
+ vpReadMultilineDescription(request) ?: request, vpReadMultilineDescription(context) ?: context,
+ vpReadObject(request, "fromApplicationSceneEntities"), vpReadObject(request, "toApplicationSceneEntities")]);
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ id scene = vpReadObject(app, "activeDisplayWindowScene") ?: vpReadObject(app, "embeddedDisplayWindowScene");
+ id coordinator = vpReadObject(scene, "layoutStateTransitionCoordinator");
+id provider = vpReadObject(scene, "layoutStateProvider");
+ id state = vpReadObject(provider, "layoutState");
+ vpFoldDisplayLog([NSString stringWithFormat:@"viewport workspace current layout: scene=%@ coordinator=%@ provider=%@ state=%@",
+ vpReadObject(vpReadObject(scene, "_FBSScene"), "identifier"), coordinator, provider,
+ vpReadMultilineDescription(state) ?: state]);
+ NSArray *elements = [vpReadObject(state, "elements") allObjects];
+ SEL previousSetter = sel_registerName("setPreviousEntity:forLayoutRole:");
+ SEL targetSetter = sel_registerName("setEntity:forLayoutRole:");
+ Method previousMethod = class_getInstanceMethod(object_getClass(context), previousSetter);
+ Method targetMethod = class_getInstanceMethod(object_getClass(context), targetSetter);
+ Method finalize = class_getInstanceMethod(object_getClass(request), sel_registerName("finalize"));
+ vpFoldDisplayLog([NSString stringWithFormat:@"viewport workspace guard: elements=%lu previous=%d target=%d finalize=%d",
+ (unsigned long)elements.count, previousMethod != NULL, targetMethod != NULL, finalize != NULL]);
+ if (elements.count != 1 || !previousMethod || !targetMethod || !finalize ||
+ strcmp(method_getTypeEncoding(previousMethod), "v32@0:8@16q24") != 0 ||
+ strcmp(method_getTypeEncoding(targetMethod), "v32@0:8@16q24") != 0 ||
+ strcmp(method_getTypeEncoding(finalize), "v16@0:8") != 0) return;
+ id element = elements.firstObject;
+ id entity = vpReadObject(element, "workspaceEntity");
+ Method roleMethod = class_getInstanceMethod(object_getClass(element), sel_registerName("layoutRole"));
+ if (!entity || !roleMethod || strcmp(method_getTypeEncoding(roleMethod), "q16@0:8") != 0) return;
+ NSInteger role = ((NSInteger (*)(id, SEL))objc_msgSend)(element, sel_registerName("layoutRole"));
+ ((void (*)(id, SEL, id, NSInteger))objc_msgSend)(context, previousSetter, entity, role);
+ ((void (*)(id, SEL, id, NSInteger))objc_msgSend)(context, targetSetter, entity, role);
+SEL attributesSelector = sel_registerName("layoutAttributesForElement:");
+ SEL requestedAttributes = sel_registerName("setRequestedLayoutAttributes:forEntity:");
+ Method attributesMethod = class_getInstanceMethod(object_getClass(state), attributesSelector);
+ Method requestedMethod = class_getInstanceMethod(object_getClass(context), requestedAttributes);
+ if (!attributesMethod || strcmp(method_getTypeEncoding(attributesMethod), "@24@0:8@16") != 0 ||
+ !requestedMethod || strcmp(method_getTypeEncoding(requestedMethod), "v32@0:8@16@24") != 0) return;
+ id attributes = ((id (*)(id, SEL, id))objc_msgSend)(state, attributesSelector, element);
+ if (!attributes) return;
+ ((void (*)(id, SEL, id, id))objc_msgSend)(context, requestedAttributes, attributes, entity);
+ // Finalize the local request before optional controlled submission. Native context binds
+ // its request and resolves entities/layout; no transaction is run.
+ ((void (*)(id, SEL))objc_msgSend)(request, sel_registerName("finalize"));
+ vpFoldDisplayLog([NSString stringWithFormat:@"viewport workspace finalized preview: role=%ld entity=%@ from=%@ to=%@ context=%@",
+ (long)role, entity, vpReadObject(request, "fromApplicationSceneEntities"),
+ vpReadObject(request, "toApplicationSceneEntities"), vpReadMultilineDescription(context) ?: context]);
+ if (submit) {
+ id identifier = vpReadObject(element, "uniqueIdentifier");
+ NSSet *from = vpReadObject(request, "fromApplicationSceneEntities");
+ NSSet *to = vpReadObject(request, "toApplicationSceneEntities");
+ Class applicationEntity = objc_getClass("SBApplicationSceneEntity");
+ if (!applicationEntity || ![entity isKindOfClass:applicationEntity] || role != 1 ||
+ !identifier || from.count != 1 || to.count != 1 ||
+ ![vpReadObject(from.anyObject, "uniqueIdentifier") isEqual:identifier] ||
+ ![vpReadObject(to.anyObject, "uniqueIdentifier") isEqual:identifier] ||
+ vpReadObject(provider, "layoutState") != state ||
+ vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration") != configuration ||
+ atomic_load_explicit(&vpViewportRequestGeneration, memory_order_acquire) == 0) {
+ vpFoldDisplayLog(@"viewport workspace refresh: preservation guard refused"); return;
+ }
+ SEL execute = sel_registerName("executeTransitionRequest:");
+ Method executeMethod = class_getInstanceMethod(object_getClass(workspace), execute);
+ if (!executeMethod || strcmp(method_getTypeEncoding(executeMethod), "B24@0:8@16") != 0) return;
+ BOOL accepted = ((BOOL (*)(id, SEL, id))objc_msgSend)(workspace, execute, request);
+ vpFoldDisplayLog([NSString stringWithFormat:@"viewport workspace refresh: submitted=%d same entity=%@", accepted, identifier]);
+ }
+
+
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"viewport workspace preview exception: %@", exception.reason]);
+ }
+}
+
+static void vpRefreshNativeStatusRegistration(void) {
+ if (!vpLogicalRoleExperiment) return;
+ id scene = vpMainInnerWindowScene();
+ id bar = vpReadObject(vpReadObject(scene, "statusBarManager"), "statusBar");
+ if (!bar || vpReadBoolValue(bar, "serverUpdatesDisabled").boolValue || vpReadBoolValue(bar, "isHidden").boolValue) return;
+ SEL toggle = sel_registerName("setServerUpdatesDisabled:");
+ SEL update = sel_registerName("forceUpdateData:");
+ Method tm = class_getInstanceMethod(object_getClass(bar), toggle);
+ Method um = class_getInstanceMethod(object_getClass(bar), update);
+ if (!tm || !um || strcmp(method_getTypeEncoding(tm), "v20@0:8B16") != 0 ||
+ strcmp(method_getTypeEncoding(um), "v20@0:8B16") != 0) return;
+ @try {
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(bar, toggle, YES);
+ } @finally {
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(bar, toggle, NO);
+ }
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(bar, update, YES);
+ vpFoldDisplayLog(@"native status registration: visible scene client re-registered and requested native data");
+}
+
+// Native minute scheduling already supports a nil reference view (zero
+// frame-phase adjustment). A detached but alive view instead follows the
+// nonnil path and divides by its absent screen's0 FPS. Use the native nil
+// branch only while the reference cannot supply a valid screen cadence.
+static id vpWithUsableClockReference(id provider, id (^operation)(void)) {
+ Ivar ivar = class_getInstanceVariable(object_getClass(provider), "_referenceView");
+ if (!vpLogicalRoleExperiment || ![NSThread isMainThread] || !ivar || ivar_getTypeEncoding(ivar)[0] != '@') return operation();
+ id reference = vpReadObjectIvar(provider, "_referenceView");
+ id screen = vpReadObject(vpReadObject(vpReadObject(reference, "window"), "windowScene"), "screen");
+ NSMethodSignature *fpsSignature = [screen methodSignatureForSelector:sel_registerName("maximumFramesPerSecond")];
+ NSInteger fps = 0;
+ if (fpsSignature && fpsSignature.numberOfArguments == 2 &&
+ (fpsSignature.methodReturnType[0] == 'q' || fpsSignature.methodReturnType[0] == 'Q'))
+ fps = ((NSInteger (*)(id, SEL))objc_msgSend)(screen, sel_registerName("maximumFramesPerSecond"));
+ if (!reference || fps > 0) return operation();
+ // initWithReferenceView: uses objc_storeWeak for this slot. The runtime
+ // setter preserves known weak memory management (objc/runtime.h).
+ object_setIvar(provider, ivar, nil);
+ @try {
+ if (atomic_fetch_add_explicit(&vpClockReferenceFallbackCount, 1, memory_order_relaxed) < 4)
+ vpFoldDisplayLog([NSString stringWithFormat:@"native clock reference fallback: class=%s screen=%p fps=%ld", object_getClassName(reference), screen, (long)fps]);
+ return operation();
+ } @finally {
+ if (!object_getIvar(provider, ivar)) object_setIvar(provider, ivar, reference);
+ }
+}
+static void vpMachClockTick(id self, SEL selector) {
+ vpWithUsableClockReference(self, ^id {
+ ((void (*)(id, SEL))vpOriginalMachClockTick)(self, selector);
+ // A once-a-minute bounded walk re-scales glyph instances that a
+ // lock-screen rebuild created at the native factor.
+ if (vpAutomaticMainStatus) vpApplyQuickActionGlyphScale();
+ return nil;
+ });
+}
+static id vpMachClockObserve(id self, SEL selector, id handler) {
+ return vpWithUsableClockReference(self, ^id {
+ return ((id (*)(id, SEL, id))vpOriginalMachClockObserve)(self, selector, handler);
+ });
+}
+
+static void vpObserveNativeTimeUpdate(id self, SEL selector, id date) {
+ unsigned int count = atomic_fetch_add_explicit(&vpTimeItemTraceCount, 1, memory_order_relaxed);
+ NSString *before = count < 20 ? [vpReadObjectIvar(self, "_timeItemTimeString") copy] : nil;
+ ((void (*)(id, SEL, id))vpOriginalTimeItemUpdate)(self, selector, date);
+ if (count < 20) {
+ id current = vpReadObject(vpReadObjectIvar(self, "_dateTimeProvider"), "date");
+ id provider = vpReadObjectIvar(self, "_dateTimeProvider");
+ id underlying = vpReadObjectIvar(provider, "_underlyingProvider");
+ NSString *interval = [date isKindOfClass:NSDate.class] ? [NSString stringWithFormat:@"%.17g", [(NSDate *)date timeIntervalSinceReferenceDate]] : @"not-date";
+ vpFoldDisplayLog([NSString stringWithFormat:@"native clock update: input=%@ class=%s interval=%@ current=%@ underlying=%s underlyingDate=%@ before=%@ after=%@ caller=%p",
+ date, date ? object_getClassName(date) : "nil", interval, current,
+ underlying ? object_getClassName(underlying) : "nil", vpReadObject(underlying, "date"), before,
+ vpReadObjectIvar(self, "_timeItemTimeString"), __builtin_return_address(0)]);
+ }
+}
+
+static void vpRefreshNativeClockSource(void) {
+ if (!vpLogicalRoleExperiment) return;
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ id aggregator = vpReadObject(app, "statusBarStateAggregator");
+ SEL refresh = sel_registerName("_restartTimeItemTimer");
+ Method method = class_getInstanceMethod(object_getClass(aggregator), refresh);
+ if (!method || strcmp(method_getTypeEncoding(method), "v16@0:8") != 0) return;
+ ((void (*)(id, SEL))objc_msgSend)(aggregator, refresh);
+ vpFoldDisplayLog(@"native clock source: native time-item subscription restarted");
+}
+
+static void vpPulseNativeWallpaperOrientation(void) {
+ if (!vpLogicalRoleExperiment || vpWallpaperOrientationLeaseActive) return;
+ id scene = vpMainInnerWindowScene();
+ id wallpaper = vpReadObject(scene, "wallpaperController");
+ SEL getter = sel_registerName("_WallpaperOrientationNotForYou");
+ SEL update = sel_registerName("willAnimateRotationToInterfaceOrientation:duration:force:");
+ SEL boundsUpdate = sel_registerName("_updateWallpaperContainerViewBoundsForOrientation:");
+ Method gm = class_getInstanceMethod(object_getClass(wallpaper), getter);
+ Method um = class_getInstanceMethod(object_getClass(wallpaper), update);
+ Method bm = class_getInstanceMethod(object_getClass(wallpaper), boundsUpdate);
+ if (!scene || !gm || !um || strcmp(method_getTypeEncoding(gm), "q16@0:8") != 0 ||
+ strcmp(method_getTypeEncoding(um), "v36@0:8q16d24B32") != 0 ||
+ !bm || strcmp(method_getTypeEncoding(bm), "v24@0:8q16") != 0) return;
+ NSInteger original = ((NSInteger (*)(id, SEL))objc_msgSend)(wallpaper, getter);
+ NSInteger target = [[vpReadObject(scene, "traitsPipelineManager") valueForKey:@"systemArbitratedInterfaceOrientation"] integerValue];
+ if (original < 1 || original > 4 || target < 1 || target > 4) return;
+ vpWallpaperOrientationLeaseActive = YES;
+ @try {
+ ((void (*)(id, SEL, NSInteger, double, BOOL))objc_msgSend)(wallpaper, update, target, 0, YES);
+ ((void (*)(id, SEL, NSInteger))objc_msgSend)(wallpaper, boundsUpdate, target);
+ // Traits-active wallpaper skips the legacy bounds path on this
+ // single-Main Duo. Keep the existing native wallpaper objects but
+ // synchronize their frames to the scene's current interface bounds.
+ CGSize sceneSize = (target == 3 || target == 4)
+ ? CGSizeMake(951, 669) : CGSizeMake(669, 951);
+ id wallpaperWindow = vpReadObjectIvar(wallpaper, "_wallpaperWindow");
+ id container = vpReadObjectIvar(wallpaper, "_wallpaperContainerView");
+ id presenter = vpReadObjectIvar(wallpaper, "_wallpaperPresenter");
+ id presenterView = vpReadObject(presenter, "viewIfLoaded");
+ id root = vpReadObjectIvar(wallpaper, "_rootWallpaperViewController");
+ id rootView = vpReadObject(root, "viewIfLoaded");
+ for (id view in @[wallpaperWindow ?: NSNull.null, container ?: NSNull.null, presenterView ?: NSNull.null, rootView ?: NSNull.null]) {
+ if (view == NSNull.null) continue;
+ @try {
+ CGRect rect = CGRectMake(0, 0, sceneSize.width, sceneSize.height);
+ NSValue *value = [NSValue value:&rect withObjCType:@encode(CGRect)];
+ [view setValue:value forKey:@"frame"];
+ [view setValue:value forKey:@"bounds"];
+ if ([view respondsToSelector:sel_registerName("setNeedsLayout")])
+ ((void (*)(id, SEL))objc_msgSend)(view, sel_registerName("setNeedsLayout"));
+ if ([view respondsToSelector:sel_registerName("layoutIfNeeded")])
+ ((void (*)(id, SEL))objc_msgSend)(view, sel_registerName("layoutIfNeeded"));
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"native wallpaper bounds exception: %@", exception.reason]);
+ }
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"native wallpaper transforms: window=%@ container=%@ presenter=%@ root=%@",
+ [wallpaperWindow valueForKey:@"transform"], [container valueForKey:@"transform"],
+ [presenterView valueForKey:@"transform"], [rootView valueForKey:@"transform"]]);
+ vpFoldDisplayLog([NSString stringWithFormat:@"native wallpaper orientation: %ld -> %ld readback=%ld",
+ (long)original, (long)target, (long)((NSInteger (*)(id, SEL))objc_msgSend)(wallpaper, getter)]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"native wallpaper orientation exception: %@", exception.reason]);
+ }
+ // This is now part of the normal Duo orientation pipeline. Do not roll
+ // the wallpaper back after a timer: the scene's current arbitration is
+ // the source of truth and a delayed restore recreates the landscape black
+ // band. The next orientation request can update it again.
+ vpWallpaperOrientationLeaseActive = NO;
+}
+
+static NSString *vpDescribeLayerContents(id contents) {
+ if (!contents) return @"nil";
+ @try {
+ if (CFGetTypeID((CFTypeRef)contents) == CGImageGetTypeID()) {
+ CGImageRef image = (CGImageRef)(__bridge void *)contents;
+ return [NSString stringWithFormat:@"image %zux%zu", CGImageGetWidth(image), CGImageGetHeight(image)];
+ }
+ } @catch (NSException *exception) { }
+ NSString *text = [contents description];
+ if (text.length > 60) text = [text substringToIndex:60];
+ return [NSString stringWithFormat:@"%s %@", object_getClassName(contents), text];
+}
+
+static void vpDumpWallpaperTree(id view, NSUInteger depth) {
+ if (!view || depth > 8) return;
+ id layer = nil;
+ @try { layer = [view valueForKey:@"layer"]; } @catch (NSException *exception) { }
+ NSString *layerInfo = @"";
+ if (layer) {
+ @try {
+ layerInfo = [NSString stringWithFormat:@" layer=%@ gravity=%@ scale=%@ masks=%@ cRect=%@ cCenter=%@ contents=%@",
+ [layer valueForKey:@"bounds"], [layer valueForKey:@"contentsGravity"],
+ [layer valueForKey:@"contentsScale"], [layer valueForKey:@"masksToBounds"],
+ [layer valueForKey:@"contentsRect"], [layer valueForKey:@"contentsCenter"],
+ vpDescribeLayerContents([layer valueForKey:@"contents"])];
+ } @catch (NSException *exception) { }
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"wallpaper tree depth=%lu class=%@ frame=%@ bounds=%@ transform=%@ hidden=%@ alpha=%@%@",
+ (unsigned long)depth, NSStringFromClass([view class]), [view valueForKey:@"frame"], [view valueForKey:@"bounds"],
+ [view valueForKey:@"transform"], [view valueForKey:@"hidden"], [view valueForKey:@"alpha"], layerInfo]);
+ for (id child in [view valueForKey:@"subviews"] ?: @[])
+ vpDumpWallpaperTree(child, depth + 1);
+}
+
+// Reads one ivar by its type encoding so numeric and struct state appear
+// without calling arbitrary getters. Unknown layouts stay "?"; nothing is
+// synthesized.
+static NSString *vpFormatIvarValue(id object, Ivar ivar) {
+ const char *type = ivar_getTypeEncoding(ivar);
+ if (!type) return @"?";
+ void *ptr = (void *)((char *)(__bridge void *)object + ivar_getOffset(ivar));
+ switch (type[0]) {
+ case 'd': return [NSString stringWithFormat:@"%.6g", *(double *)ptr];
+ case 'f': return [NSString stringWithFormat:@"%.6g", (double)*(float *)ptr];
+ case 'B': return *(BOOL *)ptr ? @"YES" : @"NO";
+ case 'c': return @(*(int8_t *)ptr).stringValue;
+ case 'C': return @(*(uint8_t *)ptr).stringValue;
+ case 's': return @(*(int16_t *)ptr).stringValue;
+ case 'S': return @(*(uint16_t *)ptr).stringValue;
+ case 'i': case 'l': return @(*(int32_t *)ptr).stringValue;
+ case 'I': case 'L': return @(*(uint32_t *)ptr).stringValue;
+ case 'q': return @(*(int64_t *)ptr).stringValue;
+ case 'Q': return @(*(uint64_t *)ptr).stringValue;
+ case '@': {
+ id value = object_getIvar(object, ivar);
+ if (!value) return @"nil";
+ if ([value isKindOfClass:NSNumber.class]) return [NSString stringWithFormat:@"@ %@", value];
+ if ([value isKindOfClass:NSString.class] || [value isKindOfClass:NSValue.class])
+ return [NSString stringWithFormat:@"%s %@", object_getClassName(value), value];
+ NSString *text = [value description];
+ if (text.length > 90) text = [text substringToIndex:90];
+ return [NSString stringWithFormat:@"%s %@", object_getClassName(value), text];
+ }
+ case '{': {
+ if (strncmp(type, "{CGRect", 6) == 0) {
+ CGRect rect = *(CGRect *)ptr;
+ return [NSString stringWithFormat:@"{{%g, %g}, {%g, %g}}", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height];
+ }
+ if (strncmp(type, "{CGSize", 6) == 0) {
+ CGSize size = *(CGSize *)ptr;
+ return [NSString stringWithFormat:@"{%g, %g}", size.width, size.height];
+ }
+ if (strncmp(type, "{CGPoint", 7) == 0) {
+ CGPoint point = *(CGPoint *)ptr;
+ return [NSString stringWithFormat:@"{%g, %g}", point.x, point.y];
+ }
+ if (strncmp(type, "{UIEdgeInsets", 13) == 0) {
+ // {top,left,bottom,right} as four CGFloats; a local layout so
+ // UIKit is not a dependency of this dylib.
+ const CGFloat *edges = (const CGFloat *)ptr;
+ return [NSString stringWithFormat:@"insets{%g,%g,%g,%g}", edges[0], edges[1], edges[2], edges[3]];
+ }
+ if (strncmp(type, "{CGAffineTransform", 18) == 0) {
+ CGAffineTransform transform = *(CGAffineTransform *)ptr;
+ return [NSString stringWithFormat:@"transform{%g,%g,%g,%g,%g,%g}", transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty];
+ }
+ return @"{struct}";
+ }
+ case '^': return [NSString stringWithFormat:@"%p", *(void **)ptr];
+ default: return @"?";
+ }
+}
+
+static void vpDumpObjectIvars(id object, NSString *label, NSUInteger limit) {
+ if (!object) { vpFoldDisplayLog([NSString stringWithFormat:@"%@ ivars: nil", label]); return; }
+ Class cls = object_getClass(object);
+ unsigned int count = 0;
+ Ivar *ivars = class_copyIvarList(cls, &count);
+ vpFoldDisplayLog([NSString stringWithFormat:@"%@ ivars: class=%s count=%u", label, class_getName(cls), count]);
+ for (unsigned int i = 0; i < count && i < limit; i++) {
+ @try {
+ vpFoldDisplayLog([NSString stringWithFormat:@"%@ ivar[%u] %s (%s) = %@", label, i,
+ ivar_getName(ivars[i]), ivar_getTypeEncoding(ivars[i]) ?: "?",
+ vpFormatIvarValue(object, ivars[i])]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"%@ ivar[%u] %s exception: %@", label, i,
+ ivar_getName(ivars[i]), exception.reason]);
+ }
+ }
+ free(ivars);
+}
+
+// Reads the scalar state of a live SBSDeviceDeterminedConfiguration and probes
+// its pure class-mapping helpers, so the profile-selection inputs (base class,
+// distinguishers, subtype) and the base->effective mapping are both recorded
+// from evidence. Every selector is guarded; setters are never touched.
+static void vpDumpDeviceConfiguration(id config) {
+ if (!config) { vpFoldDisplayLog(@"live device configuration: nil"); return; }
+ vpFoldDisplayLog([NSString stringWithFormat:@"live device configuration: %@", [config description]]);
+ struct { const char *name; } qNames[] = {
+ {"effectiveDeviceClass"}, {"baseDeviceClass"}, {"baseClass"}, {"distinguishers"},
+ {"effectiveDeviceGrouping"}, {"baseDeviceGrouping"}, {"_fallbackEffectiveClass"},
+ };
+ for (size_t i = 0; i < sizeof(qNames) / sizeof(qNames[0]); i++) {
+ SEL selector = sel_registerName(qNames[i].name);
+ if (![config respondsToSelector:selector]) continue;
+ @try {
+ unsigned long long value = ((unsigned long long (*)(id, SEL))objc_msgSend)(config, selector);
+ vpFoldDisplayLog([NSString stringWithFormat:@"device configuration %s = %llu", qNames[i].name, value]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"device configuration %s exception: %@", qNames[i].name, exception.reason]);
+ }
+ }
+ const char *iNames[] = {"idiom"};
+ for (size_t i = 0; i < 1; i++) {
+ SEL selector = sel_registerName(iNames[i]);
+ if ([config respondsToSelector:selector]) {
+ @try {
+ long value = ((long (*)(id, SEL))objc_msgSend)(config, selector);
+ vpFoldDisplayLog([NSString stringWithFormat:@"device configuration %s = %ld", iNames[i], value]);
+ } @catch (NSException *exception) { }
+ }
+ }
+ const char *qReaderNames[] = {"homeButton", "_deviceSubtype", "_zoomModeDirection"};
+ for (size_t i = 0; i < 3; i++) {
+ SEL selector = sel_registerName(qReaderNames[i]);
+ if (![config respondsToSelector:selector]) continue;
+ @try {
+ long long value = ((long long (*)(id, SEL))objc_msgSend)(config, selector);
+ vpFoldDisplayLog([NSString stringWithFormat:@"device configuration %s = %lld", qReaderNames[i], value]);
+ } @catch (NSException *exception) { }
+ }
+ const char *dNames[] = {"_nativeScale", "_currentScale"};
+ for (size_t i = 0; i < 2; i++) {
+ SEL selector = sel_registerName(dNames[i]);
+ if (![config respondsToSelector:selector]) continue;
+ @try {
+ double value = ((double (*)(id, SEL))objc_msgSend)(config, selector);
+ vpFoldDisplayLog([NSString stringWithFormat:@"device configuration %s = %.6g", dNames[i], value]);
+ } @catch (NSException *exception) { }
+ }
+ SEL sizeSelector = sel_registerName("_effectiveDeviceClassForScreenSize:");
+ if ([config respondsToSelector:sizeSelector]) {
+ CGSize sizes[] = { CGSizeMake(669, 951), CGSizeMake(951, 669), CGSizeMake(466, 678), CGSizeMake(428, 926) };
+ for (size_t i = 0; i < 4; i++) {
+ @try {
+ unsigned long long value = ((unsigned long long (*)(id, SEL, CGSize))objc_msgSend)(config, sizeSelector, sizes[i]);
+ vpFoldDisplayLog([NSString stringWithFormat:@"device configuration effectiveDeviceClassForSize {%.0f,%.0f} = %llu", sizes[i].width, sizes[i].height, value]);
+ } @catch (NSException *exception) { }
+ }
+ }
+ SEL baseSelector = sel_registerName("_classForBase:zoom:");
+ if ([config respondsToSelector:baseSelector]) {
+ for (unsigned long long base = 0; base <= 20; base++) {
+ @try {
+ unsigned long long value = ((unsigned long long (*)(id, SEL, unsigned long long, long long))objc_msgSend)(config, baseSelector, base, 0);
+ vpFoldDisplayLog([NSString stringWithFormat:@"device configuration classForBase %llu zoom0 = %llu", base, value]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"device configuration classForBase %llu exception: %@", base, exception.reason]);
+ break;
+ }
+ }
+ }
+}
+
+// The determined configuration's constructor, swizzled at load so every
+// construction in SpringBoard logs its hardware inputs and one instance is
+// kept for on-demand mapping probes. No object-graph walking: the round-5
+// crawl crashed SpringBoard on an unsafe-unretained ivar.
+typedef id (*vpConfigInitIMP)(id, SEL, unsigned long long, CGSize, int, long long,
+ unsigned long long, long long, CGRect, double, double);
+static vpConfigInitIMP vpOriginalConfigInit;
+static id vpStashedConfig;
+static NSUInteger vpConfigInitLogs;
+
+static id vpConfigInitReplacement(id self, SEL cmd, unsigned long long baseDevice, CGSize deviceSize, int idiom,
+ long long homeButton, unsigned long long distinguishers, long long deviceSubtype,
+ CGRect nativeBounds, double nativeScale, double currentScale) {
+ id result = vpOriginalConfigInit(self, cmd, baseDevice, deviceSize, idiom, homeButton, distinguishers,
+ deviceSubtype, nativeBounds, nativeScale, currentScale);
+ if (vpConfigInitLogs < 8) {
+ vpConfigInitLogs++;
+ // Identify the construction callsite so the hardware-input source can
+ // be corrected rather than guessed.
+ Dl_info info = {0};
+ void *frame0 = __builtin_return_address(0);
+ void *frame1 = __builtin_frame_address(0) ? *(void **)__builtin_frame_address(0) : NULL;
+ void *caller1 = frame1 ? *(void **)((char *)frame1 + 8) : NULL;
+ dladdr(frame0, &info);
+ // Raw pointers too: the shared-cache slide plus this file offset turns
+ // the redacted callsite into a decodable static address.
+ vpFoldDisplayLog([NSString stringWithFormat:@"config init frame0=%p fbase=%p fname=%s",
+ frame0, info.dli_fbase, info.dli_fname ?: "?"]);
+ NSString *site1 = @"?";
+ if (caller1) {
+ Dl_info info1 = {0};
+ dladdr(caller1, &info1);
+ vpFoldDisplayLog([NSString stringWithFormat:@"config init frame1=%p fbase=%p",
+ caller1, info1.dli_fbase]);
+ site1 = [NSString stringWithFormat:@"%p", caller1];
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:
+ @"config init: base=%llu size={%.0f,%.0f} idiom=%d home=%lld distinguishers=0x%llx subtype=%lld "
+ "native={{%.0f,%.0f},{%.0f,%.0f}} scale=%.4g/%.4g callsite=%@ <- %@ -> %@",
+ baseDevice, deviceSize.width, deviceSize.height, idiom, homeButton, distinguishers, deviceSubtype,
+ nativeBounds.origin.x, nativeBounds.origin.y, nativeBounds.size.width, nativeBounds.size.height,
+ nativeScale, currentScale, [NSString stringWithFormat:@"%p", frame0], site1,
+ result ? [result description] : @"nil"]);
+ }
+ if (result) {
+ vpStashedConfig = result;
+ }
+ return result;
+}
+
+static void vpInstallConfigInitSwizzle(void) {
+ Class cls = objc_getClass("SBSDeviceDeterminedConfiguration");
+ SEL selector = sel_registerName(
+ "initMatchingBaseDevice:deviceSize:deviceIdiom:homeButton:distinguishers:deviceSubtype:nativeBounds:nativeScale:currentScale:");
+ Method method = cls ? class_getInstanceMethod(cls, selector) : NULL;
+ if (!method) { vpFoldDisplayLog(@"config init swizzle: method absent"); return; }
+ vpOriginalConfigInit = (vpConfigInitIMP)method_getImplementation(method);
+ method_setImplementation(method, (IMP)vpConfigInitReplacement);
+ vpFoldDisplayLog(@"config init swizzle: installed");
+}
+
+// Logs who feeds the effective device class into the CoverSheet layout
+// controller, and with which value. The numeric override file that once
+// forced a candidate class is gone with the experiment sweep; only the
+// capped diagnostic log remains.
+static void (*vpOriginalSetEffectiveClass)(id, SEL, unsigned long long);
+static NSUInteger vpSetEffectiveClassLogs;
+
+static void vpSetEffectiveClassReplacement(id self, SEL cmd, unsigned long long value) {
+ if (vpSetEffectiveClassLogs < 8) {
+ vpSetEffectiveClassLogs++;
+ Dl_info info = {0};
+ void *frame0 = __builtin_return_address(0);
+ dladdr(frame0, &info);
+ vpFoldDisplayLog([NSString stringWithFormat:@"layout setEffectiveDeviceClass %llu on %s from %p fbase=%p",
+ value, object_getClassName(self), frame0, info.dli_fbase]);
+ }
+ vpOriginalSetEffectiveClass(self, cmd, value);
+}
+
+static void vpInstallLayoutClassSwizzle(void) {
+ Class cls = objc_getClass("CSProminentLayoutController");
+ Method method = cls ? class_getInstanceMethod(cls, sel_registerName("setEffectiveDeviceClass:")) : NULL;
+ if (!method) { vpFoldDisplayLog(@"layout class swizzle: method absent"); return; }
+ vpOriginalSetEffectiveClass = (void (*)(id, SEL, unsigned long long))method_getImplementation(method);
+ method_setImplementation(method, (IMP)vpSetEffectiveClassReplacement);
+ vpFoldDisplayLog(@"layout class swizzle: installed");
+}
+
+
+__attribute__((unused)) static void vpDumpClassSurface(const char *className, NSString *label) {
+ Class cls = objc_getClass(className);
+ if (!cls) { vpFoldDisplayLog([NSString stringWithFormat:@"%@ class %s absent", label, className]); return; }
+ for (Class walk = cls; walk && walk != objc_getClass("UIView"); walk = class_getSuperclass(walk)) {
+ unsigned int count = 0;
+ Method *methods = class_copyMethodList(walk, &count);
+ vpFoldDisplayLog([NSString stringWithFormat:@"%@ surface %s: %u methods (super=%s)", label,
+ class_getName(walk), count, class_getName(class_getSuperclass(walk))]);
+ for (unsigned int i = 0; i < count; i++)
+ vpFoldDisplayLog([NSString stringWithFormat:@"%@ method[%u] %s %s", label, i,
+ sel_getName(method_getName(methods[i])), method_getTypeEncoding(methods[i])]);
+ free(methods);
+ unsigned int icount = 0;
+ Ivar *ivars = class_copyIvarList(walk, &icount);
+ for (unsigned int i = 0; i < icount; i++)
+ vpFoldDisplayLog([NSString stringWithFormat:@"%@ ivardecl[%u] %s %s", label, i,
+ ivar_getName(ivars[i]), ivar_getTypeEncoding(ivars[i]) ?: "?"]);
+ free(ivars);
+ }
+}
+
+// Lock-screen quick-action diagnostics: locate live CSQuickAction* views,
+// record their geometry, traits and raw ivar state, and dump the native
+// class surfaces so the profile selection can be read from evidence.
+static void vpInspectQuickActions(void) {
+ @try {
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ id device = vpReadObject(objc_getClass("UIDevice"), "currentDevice");
+ vpFoldDisplayLog([NSString stringWithFormat:@"quick action device: model=%@ name=%@ idiom=%ld orientation=%ld",
+ [device valueForKey:@"model"], [device valueForKey:@"name"],
+ (long)((NSInteger (*)(id, SEL))objc_msgSend)(device, sel_registerName("userInterfaceIdiom")),
+ (long)((NSInteger (*)(id, SEL))objc_msgSend)(device, sel_registerName("orientation"))]);
+ NSUInteger found = 0;
+ for (id window in vpReadObject(app, "windows")) {
+ NSMutableArray *pending = [NSMutableArray arrayWithObject:window];
+ while (pending.count) {
+ id view = pending.lastObject;
+ [pending removeLastObject];
+ NSString *className = NSStringFromClass([view class]);
+ BOOL quickAction = [className containsString:@"QuickAction"];
+ BOOL prominent = [className containsString:@"Prominent"];
+ if ((quickAction || prominent) && found < 10) {
+ found++;
+ vpFoldDisplayLog([NSString stringWithFormat:@"quick action view: class=%@ frame=%@ alpha=%@ hidden=%@",
+ className, [view valueForKey:@"frame"], [view valueForKey:@"alpha"], [view valueForKey:@"hidden"]]);
+ vpDumpObjectIvars(view, @"quick action instance", 48);
+ if ([className isEqualToString:@"CSQuickActionsButton"]) {
+ // Read-only computed getters; they reveal which metric
+ // row the native layout resolved for this instance.
+ // These selectors belong to the button, not the glyph.
+ SEL sizeSelector = sel_registerName("iconImageSize");
+ SEL frameSelector = sel_registerName("iconImageFrame");
+ SEL diameterSelector = sel_registerName("buttonDiameter");
+ if ([view respondsToSelector:sizeSelector]) {
+ CGSize size = ((CGSize (*)(id, SEL))objc_msgSend)(view, sizeSelector);
+ vpFoldDisplayLog([NSString stringWithFormat:@"quick action computed: iconImageSize={%g, %g}", size.width, size.height]);
+ }
+ if ([view respondsToSelector:frameSelector]) {
+ CGRect rect = ((CGRect (*)(id, SEL))objc_msgSend)(view, frameSelector);
+ vpFoldDisplayLog([NSString stringWithFormat:@"quick action computed: iconImageFrame={{%g, %g}, {%g, %g}}",
+ rect.origin.x, rect.origin.y, rect.size.width, rect.size.height]);
+ }
+ if ([view respondsToSelector:diameterSelector]) {
+ double diameter = ((double (*)(id, SEL))objc_msgSend)(view, diameterSelector);
+ vpFoldDisplayLog([NSString stringWithFormat:@"quick action computed: buttonDiameter=%.6g", diameter]);
+ }
+ }
+ if ([className isEqualToString:@"CSQuickActionsView"]) {
+ vpDumpObjectIvars(vpReadObjectIvar(view, "_quickActionsSettings"), @"quick action settings", 96);
+ vpDumpObjectIvars(vpReadObjectIvar(view, "_buttonContainerView"), @"quick action buttons container", 48);
+ }
+ }
+ for (id child in [view valueForKey:@"subviews"] ?: @[]) [pending addObject:child];
+ }
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"quick action inventory: views=%lu", (unsigned long)found]);
+ // The layout controller, its adaptive time context, and the determined
+ // configuration hang off the quick-action objects' ivar graph.
+ if (vpStashedConfig) {
+ vpDumpDeviceConfiguration(vpStashedConfig);
+ } else {
+ vpFoldDisplayLog(@"live device configuration: not constructed yet");
+ }
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"quick action exception: %@", exception.reason]);
+ }
+}
+
+// The user-validated glyph factor, applied without any experiment opt-in:
+// over a SpringBoard startup ladder, after every orientation actuation
+// refresh, after viewport transitions, and once per clock tick, because
+// lock-screen rebuilds create fresh glyph instances. The glyph class's
+// method list is never touched (round-12/13); a plain transform walk is
+// the only safe lever.
+static double const vpQuickActionGlyphScale = 0.68;
+
+static void vpApplyQuickActionGlyphScale(void) {
+ @try {
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ if (!app) return;
+ NSUInteger touched = 0, rescaled = 0;
+ for (id window in vpReadObject(app, "windows")) {
+ NSMutableArray *pending = [NSMutableArray arrayWithObject:window];
+ while (pending.count) {
+ id view = pending.lastObject;
+ [pending removeLastObject];
+ if ([view isKindOfClass:objc_getClass("CSQuickActionImageGlyphView")]) {
+ SEL transformSelector = sel_registerName("transform");
+ if (![view respondsToSelector:transformSelector]) continue;
+ CGAffineTransform current = ((CGAffineTransform (*)(id, SEL))objc_msgSend)(view, transformSelector);
+ touched++;
+ if (fabs(current.a - vpQuickActionGlyphScale) < 0.001 &&
+ fabs(current.d - vpQuickActionGlyphScale) < 0.001) continue;
+ CGAffineTransform scaled = CGAffineTransformMakeScale(vpQuickActionGlyphScale, vpQuickActionGlyphScale);
+ NSValue *value = [NSValue value:&scaled withObjCType:@encode(CGAffineTransform)];
+ [view setValue:value forKey:@"transform"];
+ rescaled++;
+ }
+ for (id child in [view valueForKey:@"subviews"] ?: @[]) [pending addObject:child];
+ }
+ }
+ if (rescaled)
+ vpFoldDisplayLog([NSString stringWithFormat:@"quick action glyph scale: %lu of %lu views at %.2f",
+ (unsigned long)rescaled, (unsigned long)touched, vpQuickActionGlyphScale]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"quick action glyph scale exception: %@", exception.reason]);
+ }
+}
+
+// Full window inventory with two subview levels: identifies which window or
+// view owns any on-screen black band in landscape.
+static void vpInspectAllWindows(void) {
+ @try {
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ for (id window in vpReadObject(app, "windows")) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"window: class=%@ frame=%@ level=%@ hidden=%@",
+ NSStringFromClass([window class]), [window valueForKey:@"frame"],
+ [window valueForKey:@"windowLevel"], [window valueForKey:@"hidden"]]);
+ BOOL deep = [NSStringFromClass([window class]) containsString:@"HomeScreen"] ||
+ [NSStringFromClass([window class]) containsString:@"Wallpaper"];
+ for (id child in [window valueForKey:@"subviews"] ?: @[]) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"window sub: class=%@ frame=%@ alpha=%@ hidden=%@",
+ NSStringFromClass([child class]), [child valueForKey:@"frame"],
+ [child valueForKey:@"alpha"], [child valueForKey:@"hidden"]]);
+ if (deep)
+ vpDumpWallpaperTree(child, 3);
+ else
+ for (id grandchild in [child valueForKey:@"subviews"] ?: @[])
+ vpFoldDisplayLog([NSString stringWithFormat:@"window sub2: class=%@ frame=%@ alpha=%@ hidden=%@",
+ NSStringFromClass([grandchild class]), [grandchild valueForKey:@"frame"],
+ [grandchild valueForKey:@"alpha"], [grandchild valueForKey:@"hidden"]]);
+ }
+ }
+ // The device-class selection surfaces and singleton probes were
+ // captured in the round-4 dump; the live values now come from the
+ // quick-action ivar crawl.
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"window inventory exception: %@", exception.reason]);
+ }
+}
+
+// Experiment: the poster extension's hosted scene presentation views keep
+// their portrait 669x951 bounds inside the landscape wallpaper tree. This
+// opt-in pulse resizes those scene-host nodes to the wallpaper presenter's
+// current bounds and requests layout, mirroring the outer frame
+// synchronization already part of the Duo wallpaper pulse. Nothing runs
+// without this notification; a later rotation can redo it.
+static NSString *vpSizeText(CGSize size) {
+ return [NSString stringWithFormat:@"{%.0f, %.0f}", size.width, size.height];
+}
+
+static void vpSyncWallpaperSceneHosts(void) {
+ if (!vpLogicalRoleExperiment) { vpFoldDisplayLog(@"wallpaper scene host sync: experiment inactive"); return; }
+ @try {
+ id scene = vpMainInnerWindowScene();
+ id wallpaper = vpReadObject(scene, "wallpaperController");
+ id presenter = vpReadObjectIvar(wallpaper, "_wallpaperPresenter");
+ id presenterView = vpReadObject(presenter, "viewIfLoaded");
+ if (!presenterView) { vpFoldDisplayLog(@"wallpaper scene host sync: no presenter view"); return; }
+ CGRect presenterBounds = ((CGRect (*)(id, SEL))objc_msgSend)(presenterView, sel_registerName("bounds"));
+ if (presenterBounds.size.width < 100 || presenterBounds.size.height < 100) {
+ vpFoldDisplayLog(@"wallpaper scene host sync: presenter bounds unusable");
+ return;
+ }
+ NSMutableArray *pending = [NSMutableArray arrayWithObject:presenterView];
+ NSUInteger synced = 0;
+ while (pending.count && synced < 32) {
+ id view = pending.lastObject;
+ [pending removeLastObject];
+ NSString *className = NSStringFromClass([view class]);
+ CGRect bounds = ((CGRect (*)(id, SEL))objc_msgSend)(view, sel_registerName("bounds"));
+ if ([className isEqualToString:@"_UIScenePresentationView"] ||
+ [className isEqualToString:@"_UISceneLayerHostContainerView"] ||
+ [className isEqualToString:@"_UITouchPassthroughView"]) {
+ if (!CGSizeEqualToSize(bounds.size, presenterBounds.size)) {
+ @try {
+ CGRect rect = CGRectMake(0, 0, presenterBounds.size.width, presenterBounds.size.height);
+ NSValue *value = [NSValue value:&rect withObjCType:@encode(CGRect)];
+ [view setValue:value forKey:@"frame"];
+ [view setValue:value forKey:@"bounds"];
+ ((void (*)(id, SEL))objc_msgSend)(view, sel_registerName("setNeedsLayout"));
+ synced++;
+ vpFoldDisplayLog([NSString stringWithFormat:@"wallpaper scene host sync: %@ %@ -> %@",
+ className, vpSizeText(bounds.size), vpSizeText(presenterBounds.size)]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"wallpaper scene host node exception: %@", exception.reason]);
+ }
+ }
+ }
+ for (id child in [view valueForKey:@"subviews"] ?: @[]) [pending addObject:child];
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"wallpaper scene host sync: synced=%lu container=%@",
+ (unsigned long)synced, vpSizeText(presenterBounds.size)]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"wallpaper scene host sync exception: %@", exception.reason]);
+ }
+}
+
+// Lights the Lock Screen without the Home press icli's wake falls back to,
+// so the locked wallpaper and quick actions can be captured lit.
+static void vpUndimScreenOnly(void) {
+ void *handle = dlopen("/System/Library/PrivateFrameworks/SpringBoardServices.framework/SpringBoardServices", RTLD_NOW);
+ void (*undim)(void) = handle ? dlsym(handle, "SBSUndimScreen") : NULL;
+ if (!undim) { vpFoldDisplayLog(@"screen undim: SBSUndimScreen absent"); return; }
+ undim();
+ vpFoldDisplayLog(@"screen undim: requested");
+}
+
+static void vpInspectNativePresentation(void) {
+ @try {
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ id scene = vpReadObject(app, "activeDisplayWindowScene") ?: vpReadObject(app, "embeddedDisplayWindowScene");
+ id wallpaper = vpReadObject(scene, "wallpaperController");
+ id presenter = vpReadObjectIvar(wallpaper, "_wallpaperPresenter");
+ id presenterView = vpReadObject(presenter, "viewIfLoaded");
+ vpDumpWallpaperTree(presenterView, 0);
+ vpDumpObjectIvars(wallpaper, @"wallpaper controller", 96);
+ vpDumpObjectIvars(presenter, @"wallpaper presenter", 96);
+ // The presenter hosts the wallpaper through a remote CAContext; its
+ // full description carries the scale/scene fields a short dump cuts,
+ // and the overlay/transfer containers may hold the clip geometry.
+ vpFoldDisplayLog([NSString stringWithFormat:@"presenter full: %@", [presenter description]]);
+ // The inner poster controller composes portrait while the wallpaper
+ // controller is landscape; find its orientation-control surface.
+ for (NSString *className in @[@"PBUIPosterViewController", @"PBUIPosterWallpaperViewController",
+ @"PBUIPosterLockViewController", @"PBUIWallpaperView"]) {
+ Class cls = objc_getClass(className.UTF8String);
+ if (!cls) { vpFoldDisplayLog([NSString stringWithFormat:@"poster class %@ absent", className]); continue; }
+ unsigned int methodCount = 0;
+ Method *methods = class_copyMethodList(cls, &methodCount);
+ for (unsigned int i = 0; i < methodCount; i++) {
+ const char *name = sel_getName(method_getName(methods[i]));
+ if (strstr(name, "rientation") || strstr(name, "andscape") || strstr(name, "ontentMode") || strstr(name, "ize")) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"poster surface %@ method %s %s", className, name,
+ method_getTypeEncoding(methods[i])]);
+ }
+ }
+ free(methods);
+ }
+ for (NSString *containerKey in @[@"_wallpaperOverlayContainerView", @"_transferContainerView"]) {
+ id container = vpReadObjectIvar(wallpaper, containerKey.UTF8String);
+ vpFoldDisplayLog([NSString stringWithFormat:@"container %@: %@", containerKey, container ? [container description] : @"nil"]);
+ vpDumpWallpaperTree(container, 1);
+ }
+ id rootController = vpReadObjectIvar(wallpaper, "_rootWallpaperViewController");
+ vpDumpObjectIvars(rootController, @"wallpaper root", 64);
+ id manager = vpReadObject(scene, "statusBarManager");
+ id sceneBar = vpReadObject(manager, "statusBar");
+ id mainBar = vpReadObject(app, "statusBarForEmbeddedDisplay");
+ NSMutableArray *bars = [NSMutableArray array];
+ for (id bar in @[sceneBar ?: NSNull.null, mainBar ?: NSNull.null]) {
+ if (bar == NSNull.null) { [bars addObject:NSNull.null]; continue; }
+ id provider = vpReadObject(bar, "inProcessStateProvider");
+ NSMutableDictionary *row = [@{@"bar": [NSString stringWithFormat:@"%p %s", bar, object_getClassName(bar)],
+ @"provider": provider ? [NSString stringWithFormat:@"%p %s", provider, object_getClassName(provider)] : (id)NSNull.null,
+ @"server": [vpReadObject(bar, "statusBarServer") description] ?: (id)NSNull.null,
+ @"bounds": vpSnapshotRect(bar, "bounds")} mutableCopy];
+ for (NSString *key in @[@"timeCloaked", @"allButBatteryCloaked", @"telephonyAndBluetoothCloaked"]) {
+ Ivar ivar = class_getInstanceVariable(object_getClass(provider), [[@"_" stringByAppendingString:key] UTF8String]);
+ if (ivar && strcmp(ivar_getTypeEncoding(ivar), "B") == 0) row[key] = [provider valueForKey:key] ?: NSNull.null;
+ }
+ row[@"serverUpdatesDisabled"] = vpReadBoolValue(bar, "serverUpdatesDisabled") ?: (id)NSNull.null;
+ row[@"homeItemsDisabled"] = vpReadBoolValue(bar, "homeItemsDisabled") ?: (id)NSNull.null;
+ id renderer = vpReadObject(bar, "statusBar");
+ for (NSString *key in @[@"currentData", @"currentAggregatedData", @"additionalDataDelegate"]) {
+ NSString *description = [vpReadObject(renderer, key.UTF8String) description];
+ row[key] = description ? [description substringToIndex:MIN(description.length, 6000)] : (id)NSNull.null;
+ }
+ row[@"enabledParts"] = vpReadObjectIvar(bar, "_enabledPartIdentifiers") ?: (id)NSNull.null;
+ row[@"disabledParts"] = vpReadObjectIvar(bar, "_disabledPartIdentifiers") ?: (id)NSNull.null;
+
+ id serverClient = vpReadObject(vpReadObject(bar, "statusBarServer"), "statusBar");
+ row[@"serverClient"] = serverClient ? [NSString stringWithFormat:@"%p %s", serverClient, object_getClassName(serverClient)] : (id)NSNull.null;
+ for (NSString *key in @[@"registered", @"foreground", @"hidden"]) {
+ Ivar ivar = class_getInstanceVariable(object_getClass(bar), [[@"_" stringByAppendingString:key] UTF8String]);
+ if (ivar && strcmp(ivar_getTypeEncoding(ivar), "B") == 0) row[key] = [bar valueForKey:key] ?: NSNull.null;
+ }
+
+ [bars addObject:row];
+ }
+ NSMutableDictionary *wall = [NSMutableDictionary dictionary];
+ for (NSString *key in @[@"activeVariant", @"activeOrientationSource", @"activeInterfaceOrientationSourcesDescriptions", @"isWallpaperRequired", @"_isTraitsArbiterWallpaperActive"])
+ if ([wallpaper respondsToSelector:NSSelectorFromString(key)]) wall[key] = [[wallpaper valueForKey:key] description] ?: NSNull.null;
+ for (NSString *key in @[@"_wallpaperWindow", @"_wallpaperContainerView", @"_wallpaperPresenter", @"_rootWallpaperViewController"]) {
+ id object = vpReadObjectIvar(wallpaper, key.UTF8String);
+ wall[key] = object ? @{@"class": NSStringFromClass(object_getClass(object)),
+ @"frame": vpSnapshotRect(object, "frame"), @"bounds": vpSnapshotRect(object, "bounds"),
+ @"hidden": vpReadBoolValue(object, "isHidden") ?: (id)NSNull.null} : (id)NSNull.null;
+ }
+ id wallpaperWindow = vpReadObjectIvar(wallpaper, "_wallpaperWindow");
+ id participant = vpReadObject(wallpaperWindow, "sb_traitsParticipant");
+ wall[@"participant"] = [participant description] ?: (id)NSNull.null;
+ for (NSString *key in @[@"role", @"settings", @"preferences"])
+ wall[[@"participant." stringByAppendingString:key]] = [vpReadObject(participant, key.UTF8String) description] ?: (id)NSNull.null;
+ id delegate = vpReadObject(scene, "_abstractWindowSceneDelegate");
+ wall[@"delegateClass"] = delegate ? NSStringFromClass(object_getClass(delegate)) : (id)NSNull.null;
+ wall[@"individuallyManagedRoles"] = [vpReadObject(object_getClass(delegate), "_individuallyManagedRoles") description] ?: (id)NSNull.null;
+ id __unsafe_unretained *roleAddress = (id __unsafe_unretained *)dlsym(RTLD_DEFAULT, "SBTraitsParticipantRoleWallpaper");
+ SEL manages = sel_registerName("_shouldManageParticipantWithRole:");
+ Method managesMethod = class_getInstanceMethod(object_getClass(delegate), manages);
+ if (roleAddress && *roleAddress && managesMethod && strcmp(method_getTypeEncoding(managesMethod), "B24@0:8@16") == 0)
+ wall[@"delegateManagesWallpaper"] = @(((BOOL (*)(id, SEL, id))objc_msgSend)(delegate, manages, *roleAddress));
+ for (NSString *key in @[@"_wallpaperPresenter", @"_rootWallpaperViewController"]) {
+ id view = vpReadObject(vpReadObjectIvar(wallpaper, key.UTF8String), "viewIfLoaded");
+ wall[[key stringByAppendingString:@".view"]] = view ? @{
+ @"class": NSStringFromClass(object_getClass(view)), @"frame": vpSnapshotRect(view, "frame"),
+ @"bounds": vpSnapshotRect(view, "bounds"), @"hidden": vpReadBoolValue(view, "isHidden") ?: (id)NSNull.null,
+ @"alpha": [view valueForKey:@"alpha"] ?: (id)NSNull.null} : (id)NSNull.null;
+ }
+ id mainProvider = vpReadObject(app, "mainStatusBarStateProvider");
+ id aggregator = vpReadObject(app, "statusBarStateAggregator");
+ NSMutableDictionary *source = [NSMutableDictionary dictionary];
+ for (NSString *key in @[@"timeCloaked", @"allButBatteryCloaked", @"telephonyAndBluetoothCloaked"]) {
+ Ivar ivar = class_getInstanceVariable(object_getClass(mainProvider), [[@"_" stringByAppendingString:key] UTF8String]);
+ if (ivar && strcmp(ivar_getTypeEncoding(ivar), "B") == 0) source[key] = [mainProvider valueForKey:key] ?: NSNull.null;
+ }
+ for (NSString *key in @[@"_dateTimeProvider", @"_dateTimeProviderToken", @"_timeItemDateFormatter", @"_shortTimeItemDateFormatter", @"_timeItemTimeString"])
+ source[key] = [vpReadObjectIvar(aggregator, key.UTF8String) description] ?: (id)NSNull.null;
+ source[@"nativeDate"] = [vpReadObject(vpReadObjectIvar(aggregator, "_dateTimeProvider"), "date") description] ?: (id)NSNull.null;
+ for (NSString *key in @[@"_timeItemDateFormatter", @"_shortTimeItemDateFormatter"]) {
+ id formatter = vpReadObjectIvar(aggregator, key.UTF8String);
+ if ([formatter isKindOfClass:NSDateFormatter.class]) {
+ NSDateFormatter *native = formatter;
+ source[[key stringByAppendingString:@"Config"]] = @{
+ @"format": native.dateFormat ?: (id)NSNull.null,
+ @"dateStyle": @(native.dateStyle), @"timeStyle": @(native.timeStyle),
+@"locale": native.locale.localeIdentifier ?: (id)NSNull.null,
+ @"nativeFormattedDate": [native stringFromDate:vpReadObject(vpReadObjectIvar(aggregator, "_dateTimeProvider"), "date")] ?: (id)NSNull.null};
+ }
+ }
+ NSDictionary *record = @{@"scene": vpReadObject(vpReadObject(scene, "_FBSScene"), "identifier") ?: (id)NSNull.null,
+ @"barsSceneThenEmbedded": bars, @"wallpaper": wall, @"mainStateSource": source};
+ NSData *data = [NSJSONSerialization dataWithJSONObject:record options:0 error:NULL];
+ if (data) vpFoldDisplayLog([@"native presentation " stringByAppendingString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"native presentation exception: %@", exception.reason]);
+ }
+}
+
+static void vpInspectDisplayState(void) {
+ @try {
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ id provider = vpReadObject(app, "devicePoseProvider");
+ id coordinator = vpReadObject(app, "displayContentModeCoordinator");
+ for (id scene in vpRootServerScenes(app)) {
+ id settings = vpReadObject(scene, "uiSettings") ?: vpReadObject(scene, "settings");
+ NSMutableDictionary *fields = [NSMutableDictionary dictionary];
+ for (NSString *property in @[@"frame", @"interfaceOrientation"]) {
+ @try {
+ if ([settings respondsToSelector:NSSelectorFromString(property)])
+ fields[property] = [settings valueForKey:property] ?: NSNull.null;
+ } @catch (NSException *exception) { fields[property] = exception.reason ?: @"unavailable"; }
+ }
+ @try {
+ fields[@"hostedDisplayConfiguration"] = vpReadObject(settings, "sb_hostedDisplayConfiguration") ?: NSNull.null;
+ } @catch (NSException *exception) { fields[@"hostedDisplayConfiguration"] = exception.reason ?: @"unavailable"; }
+ vpFoldDisplayLog([NSString stringWithFormat:@"root server scene: %@ class=%s settings=%s %@",
+ vpReadObject(scene, "identifier"), object_getClassName(scene), object_getClassName(settings), fields]);
+ }
+ id resolver = vpReadObjectIvar(coordinator, "_resolver");
+ vpFoldDisplayLog([NSString stringWithFormat:@"display resolver: %@", resolver]);
+ for (NSString *name in @[@"_policies", @"_resolution", @"_displayProxies"])
+ vpFoldDisplayLog([NSString stringWithFormat:@"display resolver %@: %@", name,
+ vpReadObjectIvar(resolver, name.UTF8String)]);
+ Class cover = objc_getClass("SBCoverDisplayConfigurationTransformer");
+ NSMutableDictionary *coverState = [NSMutableDictionary dictionary];
+ for (NSString *name in @[@"activeTransformMode", @"appliedCoverInsets", @"rotationAngle", @"scaleX", @"scaleY",
+ @"transformedDisplayConfigurationHardwareIdentifier", @"insetDisplayConfigurationHardwareIdentifier"])
+ if ([cover respondsToSelector:NSSelectorFromString(name)])
+ coverState[name] = [cover valueForKey:name] ?: NSNull.null;
+ vpFoldDisplayLog([NSString stringWithFormat:@"cover transform state: %@", coverState]);
+ vpFoldDisplayLog([NSString stringWithFormat:@"display state logical projection enabled=%d", atomic_load_explicit(&vpLogicalProjectionEnabled, memory_order_acquire)]);
+ vpFoldDisplayLog([NSString stringWithFormat:@"display state: app=%s poseProvider=%@ coordinator=%@",
+ object_getClassName(app), provider, coordinator]);
+ id monitor = vpReadObject(objc_getClass("FBDisplayManager"), "sharedInstance");
+ NSMutableArray *compatibilitySourceFlags = [NSMutableArray array];
+ for (id source in vpReadObject(monitor, "_sortedSources"))
+ [compatibilitySourceFlags addObject:[source valueForKey:@"updatable"] ?: NSNull.null];
+ vpFoldDisplayLog([NSString stringWithFormat:@"compatibility monitor source updatable=%@", compatibilitySourceFlags]);
+ NSArray *observedMonitors;
+ @synchronized (vpObservedDisplayMonitors) {
+ observedMonitors = vpObservedDisplayMonitors.allObjects;
+ }
+ for (id observed in observedMonitors) {
+ id transformer = vpReadObject(observed, "transformer");
+ NSMutableArray *sourceFlags = [NSMutableArray array];
+ for (id source in vpReadObject(observed, "_sortedSources"))
+ [sourceFlags addObject:[source valueForKey:@"updatable"] ?: NSNull.null];
+ vpFoldDisplayLog([NSString stringWithFormat:@"observed monitor: %s %p transformer=%s %p updatable=%@",
+ object_getClassName(observed), (__bridge void *)observed,
+ transformer ? object_getClassName(transformer) : "none", (__bridge void *)transformer, sourceFlags]);
+ }
+ id mainConfiguration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ id caDisplay = vpReadObject(mainConfiguration, "CADisplay");
+ id uuid = vpReadObject(caDisplay, "uniqueId");
+ id service = vpReadObject(objc_getClass("BKSDisplayService"), "sharedInstance");
+ SEL traitsSelector = sel_registerName("traitsForDisplayUUID:");
+ if ([service respondsToSelector:traitsSelector]) {
+ id traits = ((id (*)(id, SEL, id))objc_msgSend)(service, traitsSelector, uuid);
+ vpFoldDisplayLog([NSString stringWithFormat:@"display native traits uuid=%@: %@", uuid, traits]);
+ Class displayClass = objc_getClass("CADisplay");
+ // New untagged software displays do not refresh every client's
+ // inventory automatically. Invalidate only this read cache.
+ SEL refresh = sel_registerName("updateDisplays");
+ if ([displayClass respondsToSelector:refresh])
+ ((void (*)(id, SEL))objc_msgSend)(displayClass, refresh);
+ id displays = vpReadObject(displayClass, "displays");
+ for (id display in displays) {
+ id displayName = vpReadObject(display, "deviceName");
+ if (![displayName isEqual:@"VPhone Cover Probe"]) continue;
+ id displayUUID = vpReadObject(display, "uniqueId");
+ if (!displayUUID) continue;
+ id displayTraits = ((id (*)(id, SEL, id))objc_msgSend)(service, traitsSelector, displayUUID);
+ vpFoldDisplayLog([NSString stringWithFormat:@"display native software traits name=%@ uuid=%@: %@",
+ displayName, displayUUID, displayTraits]);
+ }
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"display state monitor=%@ transformer=%@ observedTransformer=%@",
+ monitor, vpReadObject(monitor, "transformer"), vpObservedConfigurationTransformer]);
+ id connected = vpReadObject(monitor, "connectedIdentities");
+ id permanent = vpReadObject(monitor, "alwaysConnectedIdentities");
+ vpFoldDisplayLog([NSString stringWithFormat:@"display state monitor connected=%@ always=%@", connected, permanent]);
+ for (id identity in connected) {
+ NSMutableDictionary *fields = [NSMutableDictionary dictionary];
+ for (NSString *key in @[@"displayID", @"type", @"connectionType", @"isAlwaysConnected", @"isUIKitMainLike",
+ @"isExternal", @"isVirtualized", @"uniqueIdentifier"]) {
+ if ([identity respondsToSelector:NSSelectorFromString(key)]) fields[key] = [identity valueForKey:key] ?: NSNull.null;
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"display identity fields: %@", fields]);
+ }
+ NSArray *sources = vpReadObject(monitor, "_sortedSources");
+ vpFoldDisplayLog([NSString stringWithFormat:@"display state sources: %@", sources]);
+ static BOOL sourceMethodsLogged;
+ if (!sourceMethodsLogged && sources.count) {
+ sourceMethodsLogged = YES;
+ Class sourceClass = object_getClass(sources.firstObject);
+ for (unsigned int level = 0; sourceClass && level < 2; level++, sourceClass = class_getSuperclass(sourceClass)) {
+ unsigned int count = 0;
+ Method *methods = class_copyMethodList(sourceClass, &count);
+ for (unsigned int i = 0; i < count; i++) {
+ const char *selector = sel_getName(method_getName(methods[i]));
+ if (strstr(selector, "ransform") || strstr(selector, "pdate") || strstr(selector, "onfiguration"))
+ vpFoldDisplayLog([NSString stringWithFormat:@"display source method %@ %s types: %s",
+ NSStringFromClass(sourceClass), selector, method_getTypeEncoding(methods[i])]);
+ }
+ free(methods);
+ }
+ }
+ // Legacy Main can display the home screen while the fold coordinator
+ // has no selected primary scene. Inspect SpringBoard's actual scene
+ // accessors as well; a nil coordinator entry is not an absent UI.
+ for (NSString *key in @[@"primaryWindowScene", @"activeWindowScene", @"embeddedDisplayWindowScene",
+ @"activeDisplayWindowScene", @"currentTransitionContext"]) {
+ id owner = [key hasSuffix:@"DisplayWindowScene"] ? app : coordinator;
+ id value = vpReadObject(owner, key.UTF8String);
+ vpFoldDisplayLog([NSString stringWithFormat:@"display state %@: %@", key, value]);
+ if ([key hasSuffix:@"WindowScene"] && value) {
+ for (NSString *property in @[@"displayConfiguration", @"displayConfigurationContext", @"displayIdentity", @"screen", @"traitCollection"])
+ vpFoldDisplayLog([NSString stringWithFormat:@"display scene %@: %@", property,
+ vpReadObject(value, property.UTF8String)]);
+ id coordinateSpace = vpReadObject(value, "coordinateSpace");
+ if ([coordinateSpace respondsToSelector:sel_registerName("bounds")])
+ vpFoldDisplayLog([NSString stringWithFormat:@"display scene coordinate bounds: %@",
+ [coordinateSpace valueForKey:@"bounds"]]);
+ id screen = vpReadObject(value, "screen");
+ id pipeline = vpReadObject(value, "traitsPipelineManager");
+ NSMutableDictionary *pipelineState = [NSMutableDictionary dictionary];
+ pipelineState[@"sceneSurfaceType"] = [value valueForKey:@"surfaceType"] ?: NSNull.null;
+ pipelineState[@"nativeOrientationState"] = vpReadObject(pipeline, "_orientationStateDescription") ?: NSNull.null;
+ id arbiter = vpReadObject(value, "traitsArbiter");
+ pipelineState[@"arbiter"] = arbiter ?: NSNull.null;
+ pipelineState[@"arbiterDetails"] = vpReadMultilineDescription(arbiter) ?: NSNull.null;
+ for (NSString *stage in @[@"inputsValidationStage", @"orientationResolutionStage"])
+ pipelineState[stage] = vpReadMultilineDescription(vpReadObject(arbiter, stage.UTF8String)) ?: NSNull.null;
+ for (NSString *property in @[@"supportsLiveDeviceRotation", @"systemArbitratedDeviceOrientation",
+ @"systemArbitratedInterfaceOrientation", @"continuousFoldPinnedInterfaceOrientation",
+ @"lastNonFlatDeviceOrientation", @"inputs"])
+ if ([pipeline respondsToSelector:NSSelectorFromString(property)])
+ pipelineState[property] = [pipeline valueForKey:property] ?: NSNull.null;
+ vpFoldDisplayLog([NSString stringWithFormat:@"display pipeline state %s: %@", object_getClassName(pipeline), pipelineState]);
+ static BOOL arbiterMethodsLogged;
+ if (arbiter && !arbiterMethodsLogged) {
+ arbiterMethodsLogged = YES;
+ unsigned int count = 0;
+ Method *methods = class_copyMethodList(object_getClass(arbiter), &count);
+ for (unsigned int i = 0; i < count; i++) {
+ const char *name = sel_getName(method_getName(methods[i]));
+ if (strstr(name, "tage") || strstr(name, "articipant") || strstr(name, "esolved") || strstr(name, "escription"))
+ vpFoldDisplayLog([NSString stringWithFormat:@"arbiter method %s %s types: %s", object_getClassName(arbiter), name, method_getTypeEncoding(methods[i])]);
+ }
+ free(methods);
+ }
+ NSMutableDictionary *screenBounds = [NSMutableDictionary dictionary];
+ for (NSString *property in @[@"_referenceBounds", @"_unjailedReferenceBounds", @"_mainSceneReferenceBounds", @"nativeBounds"])
+ screenBounds[property] = vpReadRectValue(screen, property.UTF8String) ?: NSNull.null;
+ vpFoldDisplayLog([NSString stringWithFormat:@"display screen geometry: %@", screenBounds]);
+ NSUInteger visibleWindowCount = 0;
+ for (id window in vpReadObject(value, "windows")) {
+ if (![[window valueForKey:@"hidden"] boolValue] && visibleWindowCount++ < 8) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"display visible window %s frame=%@ bounds=%@",
+ object_getClassName(window), [window valueForKey:@"frame"], [window valueForKey:@"bounds"]]);
+ NSMutableDictionary *policy = [NSMutableDictionary dictionary];
+ for (NSString *property in @[@"_shouldResizeWithScene", @"_isHostedInAnotherProcess", @"_isSceneSized", @"resizesToFullScreen"])
+ policy[property] = vpReadBoolValue(window, property.UTF8String) ?: NSNull.null;
+ policy[@"classTransformRotationsEnabled"] = vpReadBoolValue(object_getClass(window), "_transformLayerRotationsAreEnabled") ?: NSNull.null;
+ policy[@"sceneBoundsInWindowOrientation"] = vpReadRectValue(window, "_sceneBoundsInWindowOrientation") ?: NSNull.null;
+ id controller = vpReadObject(window, "rootViewController");
+ id view = vpReadObject(controller, "viewIfLoaded");
+ policy[@"rootController"] = controller ? NSStringFromClass([controller class]) : @"none";
+ policy[@"rootViewFrame"] = vpReadRectValue(view, "frame") ?: NSNull.null;
+ policy[@"rootViewBounds"] = vpReadRectValue(view, "bounds") ?: NSNull.null;
+ policy[@"windowTransform"] = [window valueForKey:@"transform"] ?: NSNull.null;
+ policy[@"rootViewTransform"] = view ? [view valueForKey:@"transform"] : NSNull.null;
+ policy[@"interfaceOrientation"] = [window valueForKey:@"interfaceOrientation"] ?: NSNull.null;
+ vpFoldDisplayLog([NSString stringWithFormat:@"display window resize policy %s: %@", object_getClassName(window), policy]);
+ // Read-only: separate UIKit scene orientation from the
+ // home controller's native orientation/layout caches.
+ NSMutableDictionary *controllerState = [NSMutableDictionary dictionary];
+ for (NSString *property in @[@"orientation", @"effectiveOrientation", @"supportedInterfaceOrientations"])
+ if ([controller respondsToSelector:NSSelectorFromString(property)])
+ controllerState[property] = [controller valueForKey:property] ?: NSNull.null;
+ id manager = vpReadObjectIvar(controller, "_iconManager");
+ id folder = vpReadObject(manager, "rootFolderController");
+ controllerState[@"iconManager"] = manager ?: NSNull.null;
+ controllerState[@"folderController"] = folder ?: NSNull.null;
+ controllerState[@"contentView"] = vpReadObjectIvar(controller, "_iconContentView") ?: NSNull.null;
+ vpFoldDisplayLog([NSString stringWithFormat:@"display controller layout %s: %@", object_getClassName(controller), controllerState]);
+ }
+ }
+ SEL mode = sel_registerName("displayContentModeForWindowScene:");
+ Method method = class_getInstanceMethod(object_getClass(coordinator), mode);
+ if (method && strcmp(method_getTypeEncoding(method), "q24@0:8@16") == 0) {
+ NSInteger selected = ((NSInteger (*)(id, SEL, id))objc_msgSend)(coordinator, mode, value);
+ vpFoldDisplayLog([NSString stringWithFormat:@"display state %@ mode=%ld", key, (long)selected]);
+ }
+ }
+ }
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"display state inspection exception: %@", exception.reason]);
+ }
+}
+
+static void vpProbeUnknownDisplayPolicy(BOOL restore) {
+ static BOOL saved = NO, original = NO;
+ @try {
+ id monitor = vpReadObject(objc_getClass("FBDisplayManager"), "sharedInstance");
+ SEL getter = sel_registerName("allowsUnknownDisplays");
+ SEL setter = sel_registerName("setAllowsUnknownDisplays:");
+ Method method = class_getInstanceMethod(object_getClass(monitor), setter);
+ if (![monitor respondsToSelector:getter] || !method ||
+ strcmp(method_getTypeEncoding(method), "v20@0:8B16") != 0) {
+ vpFoldDisplayLog(@"unknown display policy: unavailable");
+ return;
+ }
+ if (!saved) {
+ original = ((BOOL (*)(id, SEL))objc_msgSend)(monitor, getter);
+ saved = YES;
+ }
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(monitor, setter, restore ? original : YES);
+ BOOL actual = ((BOOL (*)(id, SEL))objc_msgSend)(monitor, getter);
+ vpFoldDisplayLog([NSString stringWithFormat:@"unknown display policy: original=%d actual=%d restore=%d",
+ original, actual, restore]);
+ vpSnapshotMainScene();
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"unknown display policy exception: %@", exception.reason]);
+ }
+}
+
+static void vpSetRootSceneOrientation(id scene, NSInteger orientation, NSNumber *expected, unsigned int generation) {
+ SEL update = sel_registerName("updateUISettingsWithBlock:");
+ Method method = class_getInstanceMethod(object_getClass(scene), update);
+ if (!method || strcmp(method_getTypeEncoding(method), "v24@0:8@?16") != 0) {
+ vpFoldDisplayLog(@"root orientation: settings-update ABI unavailable"); return;
+ }
+ ((void (*)(id, SEL, id))objc_msgSend)(scene, update, ^(id settings) {
+ @try {
+ if (generation != atomic_load_explicit(&vpSceneOrientationPulseGeneration, memory_order_acquire) ||
+ ![[settings valueForKey:@"interfaceOrientation"] isEqual:expected]) return;
+ SEL setter = sel_registerName("setInterfaceOrientation:");
+ NSMethodSignature *signature = [settings methodSignatureForSelector:setter];
+ if (!signature || signature.numberOfArguments != 3 || signature.methodReturnType[0] != 'v' ||
+ strcmp([signature getArgumentTypeAtIndex:2], "q") != 0) return;
+ ((void (*)(id, SEL, NSInteger))objc_msgSend)(settings, setter, orientation);
+ vpFoldDisplayLog([NSString stringWithFormat:@"root orientation: %@ submitted=%ld frame=%@ generation=%u",
+ vpReadObject(scene, "identifier"), (long)orientation, vpReadRectValue(settings, "frame"), generation]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"root orientation transaction exception: %@", exception.reason]);
+ }
+ });
+}
+
+static void vpRestoreRootSceneOrientationsAttempt(unsigned int generation, unsigned int attempt) {
+ if (generation != atomic_load_explicit(&vpSceneOrientationPulseGeneration, memory_order_acquire) ||
+ !vpSavedSceneOrientations.count) return;
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ NSMutableSet *present = [NSMutableSet set];
+ for (id scene in vpRootServerScenes(app)) {
+ @try {
+ NSString *identifier = vpReadObject(scene, "identifier");
+ NSDictionary *saved = vpSavedSceneOrientations[identifier];
+ if (!saved) continue;
+ [present addObject:identifier];
+ // A reconstructed scene with the same identifier owns new state.
+ // Never replay an old instance's saved orientation into it.
+ if ([saved[@"scope"] anyObject] != scene) {
+ [vpSavedSceneOrientations removeObjectForKey:identifier];
+ vpFoldDisplayLog(@"root orientation: old scene scope ended");
+ continue;
+ }
+ NSNumber *current = [vpReadObject(scene, "uiSettings") valueForKey:@"interfaceOrientation"];
+ if (![current isKindOfClass:NSNumber.class]) continue;
+ if ([current isEqual:saved[@"original"]] || ![current isEqual:saved[@"published"]]) {
+ [vpSavedSceneOrientations removeObjectForKey:identifier];
+ vpFoldDisplayLog([NSString stringWithFormat:@"root orientation: %@ %@",
+ identifier, [current isEqual:saved[@"original"]] ? @"restoration verified" : @"newer setting preserved"]);
+ continue;
+ }
+ vpSetRootSceneOrientation(scene, [saved[@"original"] integerValue], saved[@"published"], generation);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"root orientation restore exception: %@", exception.reason]);
+ }
+ }
+ for (NSString *identifier in [vpSavedSceneOrientations.allKeys copy]) {
+ // A temporary profile lookup miss is not proof of scene removal.
+ // Keep a live scene's checkpoint for retry; only a cleared weak
+ // reference establishes that the original scope has ended.
+ if (![present containsObject:identifier] && ![vpSavedSceneOrientations[identifier][@"scope"] anyObject]) {
+ [vpSavedSceneOrientations removeObjectForKey:identifier];
+ vpFoldDisplayLog([NSString stringWithFormat:@"root orientation: %@ scene removed", identifier]);
+ }
+ }
+ if (vpSavedSceneOrientations.count && attempt < 3) {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ vpRestoreRootSceneOrientationsAttempt(generation, attempt + 1);
+ });
+ } else if (vpSavedSceneOrientations.count) {
+ // Keep the checkpoint for an explicit restore retry; submission is
+ // not readback proof and must not discard failed cleanup state.
+ vpFoldDisplayLog([NSString stringWithFormat:@"root orientation: restoration pending for %lu scene(s)",
+ (unsigned long)vpSavedSceneOrientations.count]);
+ }
+}
+
+static void vpRestoreRootSceneOrientations(void) {
+ // Cancel delayed publication blocks before starting restoration.
+ unsigned int generation = atomic_fetch_add_explicit(&vpSceneOrientationPulseGeneration, 1, memory_order_acq_rel) + 1;
+ vpRestoreRootSceneOrientationsAttempt(generation, 0);
+}
+
+// Default-off pulse: publish the existing native arbitration result through
+// the common root scene contract. No window transform/frame or app mask is
+// supplied. Restoration starts after ten seconds and keeps a checkpoint
+// until readback proves restoration or a newer setting supersedes it.
+static void vpSyncRootSceneOrientation(void) {
+ @try {
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ id windowScene = vpMainInnerWindowScene();
+ if (!windowScene) {
+ vpFoldDisplayLog(@"root orientation: pulse refused outside the real Main inner scene");
+ return;
+ }
+ id pipeline = vpReadObject(windowScene, "traitsPipelineManager");
+ NSInteger orientation = [[pipeline valueForKey:@"systemArbitratedInterfaceOrientation"] integerValue];
+ if (orientation < 1 || orientation > 4) return;
+ NSString *identifier = vpReadObject(vpReadObject(windowScene, "_FBSScene"), "identifier");
+ if (!identifier) return;
+ if (!vpSavedSceneOrientations) vpSavedSceneOrientations = [NSMutableDictionary dictionary];
+ unsigned int generation = atomic_fetch_add_explicit(&vpSceneOrientationPulseGeneration, 1, memory_order_acq_rel) + 1;
+ for (id scene in vpRootServerScenes(app)) {
+ if (![vpReadObject(scene, "identifier") isEqual:identifier]) continue;
+ id settings = vpReadObject(scene, "uiSettings");
+ id uiIdentity = vpReadObject(windowScene, "_fbsDisplayIdentity") ?: vpReadObject(windowScene, "displayIdentity");
+ if (![vpReadObject(vpReadObject(settings, "sb_hostedDisplayConfiguration"), "identity") isEqual:uiIdentity]) continue;
+ NSNumber *previous = [settings valueForKey:@"interfaceOrientation"];
+ if (![previous isKindOfClass:NSNumber.class] || previous.integerValue < 1 || previous.integerValue > 4) continue;
+ if (previous.integerValue == orientation) {
+ vpFoldDisplayLog(@"root orientation: scene settings already match native arbitration");
+ continue;
+ }
+ NSDictionary *saved = vpSavedSceneOrientations[identifier];
+ BOOL sameScope = [saved[@"scope"] anyObject] == scene;
+ NSHashTable *scope = sameScope ? saved[@"scope"] : [NSHashTable weakObjectsHashTable];
+ if (!sameScope) [scope addObject:scene];
+ vpSavedSceneOrientations[identifier] = @{
+ @"original": sameScope ? saved[@"original"] : previous,
+ @"published": @(orientation), @"scope": scope,
+ };
+ vpFoldDisplayLog([NSString stringWithFormat:@"root orientation: pulse %@ previous=%@ native=%ld",
+ identifier, previous, (long)orientation]);
+ vpSetRootSceneOrientation(scene, orientation, previous, generation);
+ }
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ if (generation == atomic_load_explicit(&vpSceneOrientationPulseGeneration, memory_order_acquire))
+ vpRestoreRootSceneOrientations();
+ });
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"root orientation pulse exception: %@", exception.reason]);
+ }
+}
+
+static id vpMainInnerWindowScene(void) {
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ id scene = vpReadObject(app, "activeDisplayWindowScene") ?: vpUIConfigWindowScene;
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ id identity = vpReadObject(configuration, "identity");
+ id uiIdentity = vpReadObject(scene, "_fbsDisplayIdentity") ?: vpReadObject(scene, "displayIdentity");
+ BOOL realMain = [uiIdentity isEqual:identity];
+ // The only accepted alias is our currently leased UI identity, parented
+ // by the unchanged real Main. Do not admit arbitrary external scenes.
+ BOOL ownedAlias = scene == vpUIConfigWindowScene && vpUIConfigPublished &&
+ [uiIdentity isEqual:vpReadObject(vpUIConfigPublished, "identity")] &&
+ [vpReadObject(uiIdentity, "rootIdentity") isEqual:identity] &&
+ vpReadObject(vpUIConfigPublished, "CADisplay") == vpReadObject(configuration, "CADisplay");
+ if (![[scene valueForKey:@"surfaceType"] isEqual:@2] ||
+ !(realMain || ownedAlias) ||
+ ![[identity valueForKey:@"isMainRootDisplay"] boolValue]) return nil;
+ return scene;
+}
+
+static BOOL vpIsSingleMainStatusScene(id scene, BOOL constructing) {
+ if (![vpReadObject(vpReadObject(scene, "_FBSScene"), "identifier") isEqual:@"SB-main"]) return NO;
+ NSInteger surface = [[scene valueForKey:@"surfaceType"] integerValue];
+ // During UIKit status-manager construction SB's surface property may
+ // still be default. This path is armed only for the explicit inner boot.
+ if (surface != 2 && !(constructing && surface == 0)) return NO;
+ id identity = vpReadObject(scene, "_fbsDisplayIdentity") ?: vpReadObject(scene, "displayIdentity");
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ return [[identity valueForKey:@"isMainRootDisplay"] boolValue] &&
+ [identity isEqual:vpReadObject(configuration, "identity")] &&
+ [vpSnapshotRect(configuration, "bounds") isEqual:@[@0, @0, @669, @951]];
+}
+
+static BOOL vpSceneMainDuringStatusConstruction(id self, SEL selector) {
+if ((__bridge void *)self == vpStatusManagerInitializingScene && !vpStatusManagerMainQueryConsumed) {
+ vpStatusManagerMainQueryConsumed = YES;
+ vpFoldDisplayLog([NSString stringWithFormat:@"scene status construction: single Main query redirected caller=%p", __builtin_return_address(0)]);
+ return NO;
+ }
+ return ((BOOL (*)(id, SEL))vpOriginalSceneIsMain)(self, selector);
+}
+
+static id vpConstructSceneStatusManager(id self, SEL selector, id scene) {
+ void *previous = vpStatusManagerInitializingScene;
+ BOOL previousConsumed = vpStatusManagerMainQueryConsumed;
+ @try {
+ vpFoldDisplayLog([NSString stringWithFormat:@"scene status construction: scene=%@ identity=%@ surface=%@",
+ vpReadObject(vpReadObject(scene, "_FBSScene"), "identifier"),
+ vpReadObject(scene, "_fbsDisplayIdentity"), [scene valueForKey:@"surfaceType"]]);
+ if (vpIsSingleMainStatusScene(scene, YES)) {
+ vpStatusManagerInitializingScene = (__bridge void *)scene;
+ vpStatusManagerMainQueryConsumed = NO;
+ vpFoldDisplayLog(@"scene status policy: native per-scene construction for Main inner");
+ }
+ return ((id (*)(id, SEL, id))vpOriginalStatusManagerInit)(self, selector, scene);
+ } @finally { vpStatusManagerInitializingScene = previous; vpStatusManagerMainQueryConsumed = previousConsumed; }
+}
+
+static BOOL vpSceneStatusUsesEmbeddedLegacySlot(id self, SEL selector) {
+ if (vpIsSingleMainStatusScene(vpReadObjectIvar(self, "_windowScene"), NO)) return NO;
+ return ((BOOL (*)(id, SEL))vpOriginalStatusManagerEmbedded)(self, selector);
+}
+
+static void vpInstallSceneStatusPolicy(void) {
+ Class sceneClass = objc_getClass("SBWindowScene");
+ Class managerClass = objc_getClass("SBWindowSceneStatusBarManager");
+ SEL mainSelector = sel_registerName("isMainDisplayWindowScene");
+ Method main = class_getInstanceMethod(sceneClass, mainSelector);
+ Method init = class_getInstanceMethod(managerClass, sel_registerName("initWithScene:"));
+ Method embedded = class_getInstanceMethod(managerClass, sel_registerName("_isEmbeddedDisplay"));
+ if (!main || strcmp(method_getTypeEncoding(main), "B16@0:8") != 0 ||
+ !init || strcmp(method_getTypeEncoding(init), "@24@0:8@16") != 0 ||
+ !embedded || strcmp(method_getTypeEncoding(embedded), "B16@0:8") != 0) {
+ vpFoldDisplayLog(@"scene status policy: native ABI unavailable"); return;
+ }
+ vpOriginalSceneIsMain = method_getImplementation(main);
+ // Add an override to SBWindowScene itself if the method is inherited;
+ // never replace UIWindowScene's implementation for all scene classes.
+ if (!class_addMethod(sceneClass, mainSelector, (IMP)vpSceneMainDuringStatusConstruction, method_getTypeEncoding(main)))
+ method_setImplementation(main, (IMP)vpSceneMainDuringStatusConstruction);
+ vpOriginalStatusManagerInit = method_setImplementation(init, (IMP)vpConstructSceneStatusManager);
+ vpOriginalStatusManagerEmbedded = method_setImplementation(embedded, (IMP)vpSceneStatusUsesEmbeddedLegacySlot);
+ vpFoldDisplayLog(@"scene status policy: one-instance native per-scene adapter installed");
+}
+
+static void vpRequestSceneGeometry(id scene, NSInteger orientation) {
+ @try {
+ if (!scene || orientation < 1 || orientation > 4) return;
+ Class preferencesClass = objc_getClass("UIWindowSceneGeometryPreferencesIOS");
+ SEL initializer = sel_registerName("initWithInterfaceOrientations:");
+ SEL request = sel_registerName("requestGeometryUpdateWithPreferences:errorHandler:");
+ Method initMethod = class_getInstanceMethod(preferencesClass, initializer);
+ Method requestMethod = class_getInstanceMethod(object_getClass(scene), request);
+ if (!initMethod || strcmp(method_getTypeEncoding(initMethod), "@24@0:8Q16") != 0 ||
+ !requestMethod || strcmp(method_getTypeEncoding(requestMethod), "v32@0:8@16@?24") != 0) {
+ vpFoldDisplayLog(@"scene geometry request: native API ABI unavailable");
+ return;
+ }
+ // Public iOS geometry API, verified against the local iOS 27.1 SDK.
+ // UIKit chooses from supported orientations; this does not change
+ // any application's mask or directly rotate a window/layer.
+ id preferences = [(id<VPhoneGeometryPreferencesInitializing>)[preferencesClass alloc]
+ initWithInterfaceOrientations:1UL << orientation];
+ ((void (*)(id, SEL, id, id))objc_msgSend)(scene, request, preferences, ^(NSError *error) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"scene geometry request: error %@/%ld %@",
+ error.domain, (long)error.code, error.localizedDescription]);
+ });
+ vpFoldDisplayLog([NSString stringWithFormat:@"scene geometry request: submitted orientation=%ld", (long)orientation]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"scene geometry request exception: %@", exception.reason]);
+ }
+}
+
+static void vpRestoreSceneGeometryRequest(void) {
+ atomic_fetch_add_explicit(&vpGeometryRequestGeneration, 1, memory_order_acq_rel);
+ id scene = vpGeometryRequestScene;
+ vpGeometryRequestScene = nil;
+ if (!scene || scene != vpMainInnerWindowScene()) return;
+ NSInteger current = [[scene valueForKey:@"interfaceOrientation"] integerValue];
+ if (current == vpGeometryRequestTarget || current == vpGeometryRequestOriginal)
+ vpRequestSceneGeometry(scene, vpGeometryRequestOriginal);
+ else vpFoldDisplayLog(@"scene geometry request: newer direction preserved");
+}
+
+static void vpProbeSceneGeometryRequest(void) {
+ @try {
+ id scene = vpMainInnerWindowScene();
+ if (!scene) { vpFoldDisplayLog(@"scene geometry request: refused outside Main inner"); return; }
+ vpRestoreSceneGeometryRequest();
+ NSInteger original = [[scene valueForKey:@"interfaceOrientation"] integerValue];
+ NSInteger target = [[vpReadObject(scene, "traitsPipelineManager") valueForKey:@"systemArbitratedInterfaceOrientation"] integerValue];
+ if (original < 1 || original > 4 || target < 1 || target > 4) return;
+ vpGeometryRequestScene = scene;
+ vpGeometryRequestOriginal = original;
+ vpGeometryRequestTarget = target;
+ unsigned int generation = atomic_fetch_add_explicit(&vpGeometryRequestGeneration, 1, memory_order_acq_rel) + 1;
+ vpRequestSceneGeometry(scene, target);
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ if (generation == atomic_load_explicit(&vpGeometryRequestGeneration, memory_order_acquire))
+ vpRestoreSceneGeometryRequest();
+ });
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"scene geometry probe exception: %@", exception.reason]);
+ }
+}
+
+static void vpRefreshNativeOrientationInputs(BOOL rereadPose) {
+ @try {
+ id scene = vpMainInnerWindowScene();
+ if (!scene) { vpFoldDisplayLog(@"orientation refresh: refused outside Main inner"); return; }
+ id pipeline = vpReadObject(scene, "traitsPipelineManager");
+ SEL selector = sel_registerName(rereadPose ? "_updateDeviceOrientationAnimated:forReason:" : "_noteInputsNeedUpdateAnimated:reason:");
+ Method method = class_getInstanceMethod(object_getClass(pipeline), selector);
+ if (!method || strcmp(method_getTypeEncoding(method), "v28@0:8B16@20") != 0) {
+ vpFoldDisplayLog(@"orientation refresh: native API ABI unavailable");
+ return;
+ }
+ ((void (*)(id, SEL, BOOL, id))objc_msgSend)(pipeline, selector, NO, @"vphone settled pose/input refresh");
+ vpFoldDisplayLog([NSString stringWithFormat:@"orientation refresh: native %@ requested", rereadPose ? @"pose" : @"inputs"]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"orientation refresh exception: %@", exception.reason]);
+ }
+}
+
+static void vpForceNativeOrientationResolution(void) {
+ @try {
+ id scene = vpMainInnerWindowScene();
+ if (!scene) { vpFoldDisplayLog(@"orientation arbitration: refused outside Main inner"); return; }
+ id arbiter = vpReadObject(scene, "traitsArbiter");
+ SEL factory = sel_registerName("_defaultUpdateContextWithReason:animatable:");
+ SEL mark = sel_registerName("setNeedsUpdateArbitrationWithContext:");
+ SEL update = sel_registerName("updateArbitrationIfNeeded");
+ Method fm = class_getInstanceMethod(object_getClass(arbiter), factory);
+ Method mm = class_getInstanceMethod(object_getClass(arbiter), mark);
+ Method um = class_getInstanceMethod(object_getClass(arbiter), update);
+ if (!fm || strcmp(method_getTypeEncoding(fm), "@28@0:8@16B24") != 0 ||
+ !mm || strcmp(method_getTypeEncoding(mm), "v24@0:8@16") != 0 ||
+ !um || strcmp(method_getTypeEncoding(um), "v16@0:8") != 0) {
+ vpFoldDisplayLog(@"orientation arbitration: native context API unavailable"); return;
+ }
+ id context = ((id (*)(id, SEL, id, BOOL))objc_msgSend)(arbiter, factory, @"vphone coherent orientation resolution", NO);
+ SEL force = sel_registerName("setForceOrientationResolution:");
+ Method forceMethod = class_getInstanceMethod(object_getClass(context), force);
+ if (!forceMethod || strcmp(method_getTypeEncoding(forceMethod), "v20@0:8B16") != 0) return;
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(context, force, YES);
+ ((void (*)(id, SEL, id))objc_msgSend)(arbiter, mark, context);
+ ((void (*)(id, SEL))objc_msgSend)(arbiter, update);
+ vpFoldDisplayLog(@"orientation arbitration: native force-resolution context submitted");
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"orientation arbitration exception: %@", exception.reason]);
+ }
+}
+
+// Real inner panels use a rotated mounting convention. The single Main VM
+// retains the portrait framebuffer. Use the native paired conversion branch
+// for one explicitly scoped experiment; never write individual window angles.
+static BOOL vpCanonicalOrientationConversion(id self, SEL selector) {
+ if (self == vpCanonicalOrientationScene && [[self valueForKey:@"surfaceType"] isEqual:@2]) return YES;
+ return ((BOOL (*)(id, SEL))vpOriginalTollFreeOrientationConversion)(self, selector);
+}
+
+static void vpSetCanonicalOrientationProbe(BOOL enabled) {
+ @try {
+ id scene = enabled ? vpMainInnerWindowScene() : vpCanonicalOrientationScene;
+ if (enabled && !scene) { vpFoldDisplayLog(@"canonical orientation: refused outside Main inner"); return; }
+ if (enabled) {
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ if (![vpSnapshotRect(configuration, "bounds") isEqual:@[@0, @0, @678, @951]]) {
+ vpFoldDisplayLog(@"canonical orientation: refused unexpected panel bounds"); return;
+ }
+ if (!vpOriginalTollFreeOrientationConversion) {
+ Method method = class_getInstanceMethod(object_getClass(scene), sel_registerName("_hasTollFreeDeviceAndInterfaceOrientationConversion"));
+ if (!method || strcmp(method_getTypeEncoding(method), "B16@0:8") != 0) return;
+ vpOriginalTollFreeOrientationConversion = method_setImplementation(method, (IMP)vpCanonicalOrientationConversion);
+ }
+ }
+ unsigned int generation = atomic_fetch_add_explicit(&vpCanonicalOrientationGeneration, 1, memory_order_acq_rel) + 1;
+ vpCanonicalOrientationScene = enabled ? scene : nil;
+ vpFoldDisplayLog([NSString stringWithFormat:@"canonical orientation: %@ generation=%u", enabled ? @"enabled" : @"restored", generation]);
+ if (scene == vpMainInnerWindowScene()) vpForceNativeOrientationResolution();
+ if (enabled) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ if (generation == atomic_load_explicit(&vpCanonicalOrientationGeneration, memory_order_acquire))
+ vpSetCanonicalOrientationProbe(NO);
+ });
+ } @catch (NSException *exception) {
+ vpCanonicalOrientationScene = nil;
+ vpFoldDisplayLog([NSString stringWithFormat:@"canonical orientation exception: %@", exception.reason]);
+ }
+}
+
+static void vpRefreshNativeOrientationActuation(void) {
+ @try {
+ id scene = vpMainInnerWindowScene();
+ if (!scene) { vpFoldDisplayLog(@"orientation actuation: refused outside Main inner"); return; }
+ NSInteger direction = [[vpReadObject(scene, "traitsPipelineManager") valueForKey:@"systemArbitratedInterfaceOrientation"] integerValue];
+ if (direction < 1 || direction > 4) return;
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ SEL selector = sel_registerName("_notePipelineManagerChangedInterfaceOrientation:onWindowScene:duration:force:logMessage:");
+ Method method = class_getInstanceMethod(object_getClass(app), selector);
+ if (!method || strcmp(method_getTypeEncoding(method), "v52@0:8q16@24d32B40@44") != 0) return;
+ // Replay the existing shared native pipeline callback with its own
+ // resolved direction; no status-window setter or custom mask is used.
+ ((void (*)(id, SEL, NSInteger, id, CGFloat, BOOL, id))objc_msgSend)(app, selector,
+ direction, scene, 0, YES, @"vphone native orientation actuation refresh");
+ vpFoldDisplayLog([NSString stringWithFormat:@"orientation actuation: native callback direction=%ld", (long)direction]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"orientation actuation exception: %@", exception.reason]);
+ }
+}
+
+static void vpRestoreEmbeddedOrientation(void) {
+ atomic_fetch_add_explicit(&vpEmbeddedOrientationGeneration, 1, memory_order_acq_rel);
+ id app = vpEmbeddedOrientationApplication;
+ id scene = vpEmbeddedOrientationScene;
+ if (!app || scene != vpMainInnerWindowScene()) {
+ vpEmbeddedOrientationApplication = nil;
+ vpEmbeddedOrientationScene = nil;
+ return;
+ }
+ @try {
+ NSInteger current = [[app valueForKey:@"statusBarOrientationForEmbeddedDisplay"] integerValue];
+ if (current != vpEmbeddedOrientationPublished) {
+ vpEmbeddedOrientationApplication = nil;
+ vpEmbeddedOrientationScene = nil;
+ vpFoldDisplayLog(@"embedded orientation: newer native value preserved"); return;
+ }
+ ((void (*)(id, SEL, NSInteger, BOOL))objc_msgSend)(app,
+ sel_registerName("setStatusBarOrientation:forEmbeddedDisplayAnimated:"), vpEmbeddedOrientationOriginal, NO);
+ NSInteger readback = [[app valueForKey:@"statusBarOrientationForEmbeddedDisplay"] integerValue];
+ if (readback == vpEmbeddedOrientationOriginal) {
+ vpEmbeddedOrientationApplication = nil;
+ vpEmbeddedOrientationScene = nil;
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"embedded orientation: restore original=%ld readback=%ld verified=%d",
+ (long)vpEmbeddedOrientationOriginal, (long)readback, readback == vpEmbeddedOrientationOriginal]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"embedded orientation restore exception: %@", exception.reason]);
+ }
+}
+
+static void vpProbeEmbeddedOrientation(void) {
+ @try {
+ vpRestoreEmbeddedOrientation();
+ if (vpEmbeddedOrientationApplication) {
+ vpFoldDisplayLog(@"embedded orientation: prior restoration pending"); return;
+ }
+ id scene = vpMainInnerWindowScene();
+ if (!scene) { vpFoldDisplayLog(@"embedded orientation: refused outside Main inner"); return; }
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ NSInteger target = [[vpReadObject(scene, "traitsPipelineManager") valueForKey:@"systemArbitratedInterfaceOrientation"] integerValue];
+ NSInteger original = [[app valueForKey:@"statusBarOrientationForEmbeddedDisplay"] integerValue];
+ SEL setter = sel_registerName("setStatusBarOrientation:forEmbeddedDisplayAnimated:");
+ Method method = class_getInstanceMethod(object_getClass(app), setter);
+ if (!method || strcmp(method_getTypeEncoding(method), "v28@0:8q16B24") != 0 ||
+ original < 1 || original > 4 || target < 1 || target > 4 || original == target) return;
+ vpEmbeddedOrientationApplication = app;
+ vpEmbeddedOrientationScene = scene;
+ vpEmbeddedOrientationOriginal = original;
+ vpEmbeddedOrientationPublished = target;
+ unsigned int generation = atomic_fetch_add_explicit(&vpEmbeddedOrientationGeneration, 1, memory_order_acq_rel) + 1;
+ // Synchronize the native embedded-display direction slot with the
+ // existing arbiter output. No individual window receives a direction.
+ ((void (*)(id, SEL, NSInteger, BOOL))objc_msgSend)(app, setter, target, NO);
+ vpFoldDisplayLog([NSString stringWithFormat:@"embedded orientation: pulse %ld -> %ld readback=%@",
+ (long)original, (long)target, [app valueForKey:@"statusBarOrientationForEmbeddedDisplay"]]);
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ if (generation == atomic_load_explicit(&vpEmbeddedOrientationGeneration, memory_order_acquire))
+ vpRestoreEmbeddedOrientation();
+ });
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"embedded orientation pulse exception: %@", exception.reason]);
+ }
+}
+
+static id vpBackboardOrientationManager(void) {
+ return vpReadObject(objc_getClass("BKOrientationManager"), "sharedInstance");
+}
+
+static void vpSnapshotBackboardOrientationNow(void) {
+ @try {
+ id manager = vpBackboardOrientationManager();
+ NSMutableDictionary *snapshot = [NSMutableDictionary dictionaryWithDictionary:@{
+ @"pid": @(getpid()), @"time": @(CFAbsoluteTimeGetCurrent())}];
+ for (NSString *key in @[@"isOrientationEventsEnabled", @"isDeviceOrientationLocked"])
+ snapshot[key] = vpReadBoolValue(manager, key.UTF8String) ?: NSNull.null;
+ for (NSString *key in @[@"currentRawDeviceOrientation", @"effectiveDeviceOrientation", @"currentUserInterfaceOrientation", @"lastEffectiveInterfaceOrientation"]) {
+ SEL getter = NSSelectorFromString(key);
+ NSMethodSignature *signature = [manager methodSignatureForSelector:getter];
+ if (signature.numberOfArguments == 2 && strcmp(signature.methodReturnType, "q") == 0)
+ snapshot[key] = @(((NSInteger (*)(id, SEL))objc_msgSend)(manager, getter));
+ }
+ id display = vpReadObject(objc_getClass("CADisplay"), "mainDisplay");
+ if (!display) for (id candidate in vpReadObject(objc_getClass("CADisplay"), "displays"))
+ if ([vpReadObject(candidate, "deviceName") isEqual:@"primary"]) { display = candidate; break; }
+ SEL supports = sel_registerName("displaySupportsRotation:");
+ Method method = class_getInstanceMethod(object_getClass(manager), supports);
+ if (display && method && strcmp(method_getTypeEncoding(method), "B24@0:8@16") == 0)
+ snapshot[@"primarySupportsRotation"] = @(((BOOL (*)(id, SEL, id))objc_msgSend)(manager, supports, display));
+ NSData *data = [NSJSONSerialization dataWithJSONObject:snapshot options:0 error:NULL];
+ if (data) vpFoldDisplayLog([@"backboard orientation " stringByAppendingString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"backboard orientation snapshot exception: %@", exception.reason]);
+ }
+}
+
+static void vpSnapshotBackboardOrientation(void) {
+ // Native getters synchronize with the orientation manager and may query
+ // CoreAnimation. Keep the backboardd main run loop free while observing.
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^{
+ vpSnapshotBackboardOrientationNow();
+ });
+}
+
+static void vpRestoreBackboardOrientationEvents(void) {
+ @try {
+ atomic_fetch_add_explicit(&vpOrientationEventsGeneration, 1, memory_order_acq_rel);
+ id manager = vpOrientationEventsManager;
+ if (!manager || manager != vpBackboardOrientationManager()) { vpOrientationEventsManager = nil; return; }
+ SEL setter = sel_registerName("setOrientationEventsEnabled:");
+ Method method = class_getInstanceMethod(object_getClass(manager), setter);
+ if (!method || strcmp(method_getTypeEncoding(method), "v20@0:8B16") != 0) return;
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(manager, setter, vpOriginalOrientationEventsEnabled);
+ vpOrientationEventsManager = nil;
+ vpSnapshotBackboardOrientation();
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"backboard orientation events restore exception: %@", exception.reason]);
+ }
+}
+
+static void vpProbeBackboardOrientationEvents(void) {
+ @try {
+ if (!atomic_load_explicit(&vpInnerSurfaceProbeEnabled, memory_order_acquire) || atomic_load_explicit(&vpPrimarySurfaceType, memory_order_acquire) != 2) {
+ vpFoldDisplayLog(@"backboard orientation events: refused outside inner metadata probe"); return;
+ }
+ if (vpOrientationEventsManager) vpRestoreBackboardOrientationEvents();
+ id manager = vpBackboardOrientationManager();
+ NSNumber *enabled = vpReadBoolValue(manager, "isOrientationEventsEnabled");
+ SEL setter = sel_registerName("setOrientationEventsEnabled:");
+ Method method = class_getInstanceMethod(object_getClass(manager), setter);
+ if (!enabled || !method || strcmp(method_getTypeEncoding(method), "v20@0:8B16") != 0) return;
+ if (enabled.boolValue) {
+ vpFoldDisplayLog(@"backboard orientation events: already enabled, no mutation");
+ vpSnapshotBackboardOrientation();
+ return;
+ }
+ vpOrientationEventsManager = manager;
+ vpOriginalOrientationEventsEnabled = enabled.boolValue;
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(manager, setter, YES);
+ vpFoldDisplayLog([NSString stringWithFormat:@"backboard orientation events: temporary enable, original=%@", enabled]);
+ vpSnapshotBackboardOrientation();
+ unsigned int generation = atomic_fetch_add_explicit(&vpOrientationEventsGeneration, 1, memory_order_acq_rel) + 1;
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ if (generation == atomic_load_explicit(&vpOrientationEventsGeneration, memory_order_acquire))
+ vpRestoreBackboardOrientationEvents();
+ });
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"backboard orientation events exception: %@", exception.reason]);
+ }
+}
+
+static id vpCreateUIConfiguration(id configuration) {
+ Class cls = objc_getClass("FBSDisplayConfigurationBuilder");
+ Method type = class_getInstanceMethod(cls, sel_registerName("setDisplayType:"));
+ Method mainLike = class_getInstanceMethod(cls, sel_registerName("setUIKitMainLike"));
+ if (!type || strcmp(method_getTypeEncoding(type), "v24@0:8q16") != 0 ||
+ !mainLike || strcmp(method_getTypeEncoding(mainLike), "v16@0:8") != 0) return nil;
+ id<VPhoneDisplayProjectionBuilding> builder = [(id<VPhoneDisplayProjectionBuilding>)[cls alloc] initWithConfiguration:configuration];
+ [builder setUniqueIdentifier:@"vphone-duo-ui-preview"];
+ [builder setDisplayType:7];
+ [builder setUIKitMainLike];
+ NSError *error = nil;
+ id result = [builder buildConfigurationWithError:&error];
+ if (!result) vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration build failed: %@", error]);
+ return result;
+}
+
+static id vpUIIdentityDuringUnpublishedCopy(id self, SEL selector) {
+ if ((__bridge void *)self == vpUIIdentityCopySource) return (__bridge id)vpUIIdentityCopyReplacement;
+ return ((id (*)(id, SEL))vpUIIdentityCopyOriginal)(self, selector);
+}
+
+static id vpCreateNonEmbeddedUIConfiguration(id root) {
+ // The native builder can set MainLike but has no clear operation. Copy
+ // from a distinct, unpublished UI configuration whose identity getter is
+ // substituted only on this thread for the duration of the native build.
+ // The physical Main and its accessors are never substituted.
+ id source = vpCreateUIConfiguration(root);
+ id identity = vpReadObject(source, "identity");
+ if (!source || source == root || [[identity valueForKey:@"isMainDisplay"] boolValue] ||
+ ![vpReadObject(identity, "rootIdentity") isEqual:vpReadObject(root, "identity")]) return nil;
+ Class cls = objc_getClass("FBSDisplayIdentity");
+ SEL initializer = sel_registerName("_initWithType:UIKitMainLike:displayID:connectionType:connectionSeed:pid:external:uniqueIdentifier:secure:alwaysConnected:root:");
+ Method method = class_getInstanceMethod(cls, initializer);
+ if (!method || strcmp(method_getTypeEncoding(method), "@76@0:8q16B24I28q32I40i44B48@52B60B64@68") != 0) return nil;
+ id replacement = [(id<VPhoneDisplayIdentityInitializing>)[cls alloc]
+ _initWithType:[[identity valueForKey:@"type"] integerValue] UIKitMainLike:NO
+ displayID:[[identity valueForKey:@"displayID"] unsignedIntValue]
+ connectionType:[[identity valueForKey:@"connectionType"] integerValue]
+ connectionSeed:[[identity valueForKey:@"connectionSeed"] unsignedIntValue]
+ pid:[[identity valueForKey:@"pid"] intValue] external:[[identity valueForKey:@"isExternal"] boolValue]
+ uniqueIdentifier:vpReadObject(identity, "uniqueIdentifier")
+ secure:[[identity valueForKey:@"expectsSecureRendering"] boolValue]
+ alwaysConnected:[[identity valueForKey:@"isAlwaysConnected"] boolValue] root:vpReadObject(identity, "rootIdentity")];
+ if (!replacement || [[replacement valueForKey:@"isUIKitMainLike"] boolValue]) return nil;
+ id<VPhoneDisplayProjectionBuilding> builder = [(id<VPhoneDisplayProjectionBuilding>)[objc_getClass("FBSDisplayConfigurationBuilder") alloc]
+ initWithConfiguration:source];
+ [builder setUniqueIdentifier:@"vphone-duo-ui-unembedded-preview"];
+ [builder setDisplayType:7];
+ SEL getter = sel_registerName("identity");
+ Method identityMethod = class_getInstanceMethod(object_getClass(source), getter);
+ if (!identityMethod || strcmp(method_getTypeEncoding(identityMethod), "@16@0:8") != 0 || vpUIIdentityCopySource) return nil;
+ vpUIIdentityCopyOriginal = method_getImplementation(identityMethod);
+ vpUIIdentityCopySource = (__bridge void *)source;
+ vpUIIdentityCopyReplacement = (__bridge void *)replacement;
+ id result = nil;
+ @try {
+ method_setImplementation(identityMethod, (IMP)vpUIIdentityDuringUnpublishedCopy);
+ NSError *error = nil;
+ result = [builder buildConfigurationWithError:&error];
+ if (!result) vpFoldDisplayLog([NSString stringWithFormat:@"nonembedded UI copy failed: %@", error]);
+ } @finally {
+ if (method_getImplementation(identityMethod) == (IMP)vpUIIdentityDuringUnpublishedCopy)
+ method_setImplementation(identityMethod, vpUIIdentityCopyOriginal);
+ vpUIIdentityCopySource = NULL; vpUIIdentityCopyReplacement = NULL;
+ }
+ if ([[vpReadObject(result, "identity") valueForKey:@"isUIKitMainLike"] boolValue] ||
+ vpReadObject(result, "CADisplay") != vpReadObject(root, "CADisplay")) return nil;
+ return result;
+}
+
+static void vpPreviewNonEmbeddedUIConfiguration(void) {
+ @try {
+ id root = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ id result = vpCreateNonEmbeddedUIConfiguration(root);
+ id identity = vpReadObject(result, "identity");
+ NSDictionary *fields = @{@"built": @(result != nil),
+ @"mainLike": [identity valueForKey:@"isUIKitMainLike"] ?: NSNull.null,
+ @"main": [identity valueForKey:@"isMainDisplay"] ?: NSNull.null,
+ @"rootMatchesMain": @([vpReadObject(identity, "rootIdentity") isEqual:vpReadObject(root, "identity")]),
+ @"sameCADisplay": @(result && vpReadObject(result, "CADisplay") == vpReadObject(root, "CADisplay")),
+ @"physicalMainLike": [vpReadObject(root, "identity") valueForKey:@"isUIKitMainLike"] ?: NSNull.null,
+ @"bounds": vpSnapshotRect(result, "bounds"), @"previewOnly": @YES};
+ NSData *data = [NSJSONSerialization dataWithJSONObject:fields options:0 error:NULL];
+ if (data) vpFoldDisplayLog([@"nonembedded UI preview " stringByAppendingString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"nonembedded UI preview exception: %@", exception.reason]);
+ }
+}
+
+static BOOL vpUIObjectsEqual(id a, id b) { return a == b || [a isEqual:b]; }
+
+static void vpPropagateUIScreenTraits(id screen) {
+ SEL update = sel_registerName("_updateTraits");
+ Method updateMethod = class_getInstanceMethod(object_getClass(screen), update);
+ if (updateMethod && strcmp(method_getTypeEncoding(updateMethod), "v16@0:8") == 0)
+ ((void (*)(id, SEL))objc_msgSend)(screen, update);
+ SEL selector = sel_registerName("_notifyTraitsChangedAndPropagate");
+ Method method = class_getInstanceMethod(object_getClass(screen), selector);
+ if (method && strcmp(method_getTypeEncoding(method), "v16@0:8") == 0)
+ ((void (*)(id, SEL))objc_msgSend)(screen, selector);
+}
+
+static BOOL vpRestoreUIScreenTraits(void) {
+ id screen = vpUITraitsScreen;
+ if (!vpUITraitsOriginalIdiom) return YES;
+ id identity = vpReadObject(screen, "displayIdentity");
+ if (screen && ![[identity valueForKey:@"isMainDisplay"] boolValue] &&
+ [vpReadObject(identity, "uniqueIdentifier") isEqual:vpUITraitsIdentifier] &&
+ [[screen valueForKey:@"_userInterfaceIdiom"] integerValue] == vpUITraitsPublishedIdiom) {
+ ((void (*)(id, SEL, NSInteger))objc_msgSend)(screen, sel_registerName("_setUserInterfaceIdiom:"), vpUITraitsOriginalIdiom.integerValue);
+ vpPropagateUIScreenTraits(screen);
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI screen traits: restored idiom=%@ readback=%@",
+ vpUITraitsOriginalIdiom, [screen valueForKey:@"_userInterfaceIdiom"]]);
+ if (![[screen valueForKey:@"_userInterfaceIdiom"] isEqual:vpUITraitsOriginalIdiom]) return NO;
+ } else vpFoldDisplayLog(@"UI screen traits: detached screen gone or newer identity/value preserved");
+ vpUITraitsScreen = nil; vpUITraitsOriginalIdiom = nil; vpUITraitsIdentifier = nil;
+ return YES;
+}
+
+static void vpSyncUIScreenTraits(void) {
+ @try {
+ if (vpUITraitsOriginalIdiom || !vpUIConfigPublished) return;
+ id scene = vpUIConfigWindowScene;
+ id screen = vpReadObject(scene, "screen");
+ id identity = vpReadObject(screen, "displayIdentity");
+ id root = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ id mainScreen = vpReadObject(vpReadObject(root, "identity"), "UIScreen");
+ if (!scene || !screen || screen == mainScreen || !mainScreen ||
+ [[identity valueForKey:@"isMainDisplay"] boolValue] ||
+ ![identity isEqual:vpReadObject(vpUIConfigPublished, "identity")] ||
+ ![vpReadObject(identity, "rootIdentity") isEqual:vpReadObject(root, "identity")]) {
+ vpFoldDisplayLog(@"UI screen traits: owned alias/Main screen binding unavailable"); return;
+ }
+ SEL selector = sel_registerName("_setUserInterfaceIdiom:");
+ Method setter = class_getInstanceMethod(object_getClass(screen), selector);
+ NSNumber *source = [mainScreen valueForKey:@"_userInterfaceIdiom"];
+ NSNumber *original = [screen valueForKey:@"_userInterfaceIdiom"];
+ if (!setter || strcmp(method_getTypeEncoding(setter), "v24@0:8q16") != 0 ||
+ ![source isKindOfClass:NSNumber.class] || ![original isKindOfClass:NSNumber.class] || source.integerValue != 0) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI screen traits: native setter/source unavailable source=%@ original=%@", source, original]); return;
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI screen traits: source=%@ alias=%@ trait=%@",
+ source, original, [vpReadObject(screen, "traitCollection") valueForKey:@"userInterfaceIdiom"]]);
+ vpUITraitsScreen = screen; vpUITraitsOriginalIdiom = original;
+ vpUITraitsPublishedIdiom = source.integerValue;
+ vpUITraitsIdentifier = vpReadObject(identity, "uniqueIdentifier");
+ ((void (*)(id, SEL, NSInteger))objc_msgSend)(screen, selector, source.integerValue);
+ vpPropagateUIScreenTraits(screen);
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI screen traits: native phone inheritance idiom=%@ trait=%@ embedded=%@",
+ [screen valueForKey:@"_userInterfaceIdiom"], [vpReadObject(screen, "traitCollection") valueForKey:@"userInterfaceIdiom"],
+ vpReadBoolValue(screen, "_isEmbeddedScreen")]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI screen traits exception: %@", exception.reason]);
+ }
+}
+
+static void vpUIStatusLifecycle(id component, const char *name, id scene) {
+ SEL selector = sel_registerName(name);
+ Method method = class_getInstanceMethod(object_getClass(component), selector);
+ if (method && strcmp(method_getTypeEncoding(method), "v24@0:8@16") == 0)
+ ((void (*)(id, SEL, id))objc_msgSend)(component, selector, scene);
+}
+
+static BOOL vpUIStatusRegistryAvailable(id scene) {
+ Method reg = class_getInstanceMethod(object_getClass(scene), sel_registerName("_registerSceneComponent:forKey:"));
+ Method unreg = class_getInstanceMethod(object_getClass(scene), sel_registerName("_unregisterSceneComponentForKey:"));
+ return reg && unreg && strcmp(method_getTypeEncoding(reg), "v32@0:8@16@24") == 0 &&
+ strcmp(method_getTypeEncoding(unreg), "v24@0:8@16") == 0;
+}
+
+static void vpDetachUIStatusComponent(void) {
+ id scene = vpUIConfigWindowScene;
+ if (!scene || !vpUINewStatusComponent || !vpUIStatusComponentKey) return;
+ id current = vpReadObject(scene, "statusBarManager");
+ if (current != vpUINewStatusComponent) return;
+ id replacementWindow = vpReadObject(current, "statusBarWindow");
+ if (replacementWindow && replacementWindow != vpUIOldStatusWindow)
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(replacementWindow, sel_registerName("setHidden:"), YES);
+ vpUIStatusLifecycle(current, "windowSceneDidDisconnect:", scene);
+ // Keep a registered component while UIKit processes the identity rollback;
+ // replace it only after the original identity has been acknowledged.
+ vpUIStatusDetachedBeforeRollback = YES;
+ vpFoldDisplayLog(@"UI configuration: replacement native component detached before identity rollback");
+}
+
+static BOOL vpRestoreUIStatusComponent(void) {
+ if (!vpUIOldStatusComponent) return YES;
+ id scene = vpUIConfigWindowScene;
+ if (!scene) {
+ vpUIOldStatusComponent = nil; vpUINewStatusComponent = nil; vpUIStatusComponentKey = nil;
+ vpUIOldStatusWindow = nil; vpUIOldStatusWindowHidden = nil;
+ vpUIStatusDetachedBeforeRollback = NO; return YES;
+ }
+ id current = vpReadObject(scene, "statusBarManager");
+ if (current && current != vpUIOldStatusComponent && current != vpUINewStatusComponent) return NO;
+ if (current == vpUINewStatusComponent) {
+ if (!vpUIStatusDetachedBeforeRollback) return NO;
+ ((void (*)(id, SEL, id))objc_msgSend)(scene, sel_registerName("_unregisterSceneComponentForKey:"), vpUIStatusComponentKey);
+ current = nil;
+ }
+ if (!current)
+ ((void (*)(id, SEL, id, id))objc_msgSend)(scene, sel_registerName("_registerSceneComponent:forKey:"), vpUIOldStatusComponent, vpUIStatusComponentKey);
+ id window = vpReadObject(vpUIOldStatusComponent, "statusBarWindow");
+ if (!vpReadObject(window, "windowScene")) {
+ Method setter = class_getInstanceMethod(object_getClass(window), sel_registerName("setWindowScene:"));
+ if (setter && strcmp(method_getTypeEncoding(setter), "v24@0:8@16") == 0)
+ ((void (*)(id, SEL, id))objc_msgSend)(window, sel_registerName("setWindowScene:"), scene);
+ }
+ vpUIStatusLifecycle(vpUIOldStatusComponent, "windowSceneDidConnect:", scene);
+ BOOL verified = vpReadObject(scene, "statusBarManager") == vpUIOldStatusComponent;
+ if (verified && vpUIOldStatusWindowHidden && vpUIOldStatusWindow) {
+ if (window != vpUIOldStatusWindow) return NO;
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(window, sel_registerName("setHidden:"), vpUIOldStatusWindowHidden.boolValue);
+ verified = [vpReadBoolValue(window, "isHidden") isEqual:vpUIOldStatusWindowHidden];
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration: original window visibility restored=%d", verified]);
+ }
+ if (verified) {
+ vpUIOldStatusComponent = nil; vpUINewStatusComponent = nil; vpUIStatusComponentKey = nil;
+ vpUIOldStatusWindow = nil; vpUIOldStatusWindowHidden = nil;
+ vpUIStatusDetachedBeforeRollback = NO;
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration: original component restore verified=%d", verified]);
+ return verified;
+}
+
+static void vpRefreshUIStatusComponent(void) {
+ @try {
+ id scene = vpUIConfigWindowScene;
+ id identity = vpReadObject(scene, "_fbsDisplayIdentity");
+ if (!scene || !vpUIConfigPublished || vpUIOldStatusComponent ||
+ ![vpReadObject(identity, "uniqueIdentifier") isEqual:vpReadObject(vpReadObject(vpUIConfigPublished, "identity"), "uniqueIdentifier")] ||
+ !vpUIStatusRegistryAvailable(scene)) return;
+ id __unsafe_unretained *keyAddress = (id __unsafe_unretained *)dlsym(RTLD_DEFAULT, "_UIStatusBarManagerWindowSceneComponentKey");
+ id key = keyAddress ? *keyAddress : nil;
+ id old = vpReadObject(scene, "statusBarManager");
+ Method init = class_getInstanceMethod(object_getClass(old), sel_registerName("initWithScene:"));
+ if (!key || !old || !init || strcmp(method_getTypeEncoding(init), "@24@0:8@16") != 0) return;
+ id registered = ((id (*)(id, SEL, id))objc_msgSend)(scene, sel_registerName("_sceneComponentForKey:"), key);
+ if (registered != old) { vpFoldDisplayLog(@"UI configuration: native component key did not match"); return; }
+ vpUIOldStatusComponent = old;
+ vpUIOldStatusWindow = vpReadObject(old, "statusBarWindow");
+ vpUIOldStatusWindowHidden = vpReadBoolValue(vpUIOldStatusWindow, "isHidden");
+ vpUIStatusComponentKey = key;
+ vpUIStatusDetachedBeforeRollback = NO;
+ vpUIStatusLifecycle(old, "windowSceneDidDisconnect:", scene);
+ ((void (*)(id, SEL, id))objc_msgSend)(scene, sel_registerName("_unregisterSceneComponentForKey:"), key);
+ id replacement = nil;
+ void *previousScope = vpStatusProfileConstructionScene;
+ @try {
+ if (vpStatusProfileLookupEnabled) vpStatusProfileConstructionScene = (__bridge void *)scene;
+ replacement = ((id (*)(id, SEL, id))objc_msgSend)([object_getClass(old) alloc], sel_registerName("initWithScene:"), scene);
+ } @finally { vpStatusProfileConstructionScene = previousScope; }
+ vpUINewStatusComponent = replacement;
+ if (!replacement) { vpFoldDisplayLog(@"UI configuration: native replacement unavailable; restore checkpoint retained"); return; }
+ ((void (*)(id, SEL, id, id))objc_msgSend)(scene, sel_registerName("_registerSceneComponent:forKey:"), replacement, key);
+ vpUIStatusLifecycle(replacement, "windowSceneDidConnect:", scene);
+ if (vpStatusProfileLookupEnabled) vpResetManagedStatusProvider();
+ id replacementWindow = vpReadObject(replacement, "statusBarWindow");
+ if (vpUIOldStatusWindow && replacementWindow && vpUIOldStatusWindow != replacementWindow && vpUIOldStatusWindowHidden) {
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(vpUIOldStatusWindow, sel_registerName("setHidden:"), YES);
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration: previous profile window deactivated hidden=%@",
+ vpReadBoolValue(vpUIOldStatusWindow, "isHidden")]);
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration: native component recreated=%d embedded=%@",
+ vpReadObject(scene, "statusBarManager") == replacement, vpReadBoolValue(replacement, "_isEmbeddedDisplay")]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration component exception: %@", exception.reason]);
+ }
+}
+
+static BOOL vpUIConfigurationOwnedByLease(id configuration) {
+ id identity = vpReadObject(configuration, "identity");
+ return [vpReadObject(identity, "uniqueIdentifier") isEqual:vpReadObject(vpReadObject(vpUIConfigPublished, "identity"), "uniqueIdentifier")];
+}
+
+static BOOL vpNotifyUIConfiguration(id scene, id configuration) {
+ SEL selector = sel_registerName("_noteDisplayIdentityDidChangeWithConfiguration:");
+ Method method = class_getInstanceMethod(object_getClass(scene), selector);
+ if (!method || strcmp(method_getTypeEncoding(method), "v24@0:8@16") != 0) return NO;
+ ((void (*)(id, SEL, id))objc_msgSend)(scene, selector, configuration);
+ return YES;
+}
+
+static void vpSetUISceneConfigurations(id configuration, id displayConfiguration, id expected, id expectedDisplay, unsigned int generation) {
+ id server = vpUIConfigServerScene;
+ SEL update = sel_registerName("updateUISettingsWithBlock:");
+ Method method = class_getInstanceMethod(object_getClass(server), update);
+ if (!method || strcmp(method_getTypeEncoding(method), "v24@0:8@?16") != 0) {
+ vpFoldDisplayLog(@"UI configuration: server settings-update ABI unavailable"); return;
+ }
+ ((void (*)(id, SEL, id))objc_msgSend)(server, update, ^(id settings) {
+ if (generation != atomic_load_explicit(&vpUIConfigGeneration, memory_order_acquire) || server != vpUIConfigServerScene ||
+ !vpUIObjectsEqual(vpReadObject(settings, "sb_hostedDisplayConfiguration"), expected) ||
+ !vpUIObjectsEqual(vpReadObject(settings, "displayConfiguration"), expectedDisplay)) return;
+ SEL setter = sel_registerName("sb_setHostedDisplayConfiguration:");
+ Method method = class_getInstanceMethod(object_getClass(settings), setter);
+ if (!method || strcmp(method_getTypeEncoding(method), "v24@0:8@16") != 0) return;
+ SEL displaySetter = sel_registerName("setDisplayConfiguration:");
+ NSMethodSignature *signature = [settings methodSignatureForSelector:displaySetter];
+ // Generated settings accessors include @"FBSDisplayConfiguration"
+ // in their encoding. Validate the semantic object ABI, not spelling.
+ if (!signature || signature.numberOfArguments != 3 || strcmp(signature.methodReturnType, "v") != 0 ||
+ [signature getArgumentTypeAtIndex:2][0] != '@') return;
+ @try {
+ ((void (*)(id, SEL, id))objc_msgSend)(settings, displaySetter, displayConfiguration);
+ ((void (*)(id, SEL, id))objc_msgSend)(settings, setter, configuration);
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration: hosted/display transaction generation=%u actual=%@",
+ generation, vpReadObject(vpReadObject(settings, "displayIdentity"), "uniqueIdentifier")]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration transaction exception: %@", exception.reason]);
+ }
+ });
+}
+
+static void vpFinishUIConfigurationRestore(unsigned int generation, unsigned int attempt) {
+ if (generation != atomic_load_explicit(&vpUIConfigGeneration, memory_order_acquire) || !vpUIConfigPublished) return;
+ @try {
+ id server = vpUIConfigServerScene;
+ if (!server) {
+ if (!vpRestoreUIScreenTraits()) return;
+ vpUIConfigPublished = nil; vpUIConfigOriginalHosted = nil; vpUIConfigOriginalServerDisplay = nil; vpUIConfigOriginalUI = nil;
+ vpUIOldStatusComponent = nil; vpUINewStatusComponent = nil; vpUIStatusComponentKey = nil;
+ vpUIOldStatusWindow = nil; vpUIOldStatusWindowHidden = nil;
+ vpUIStatusDetachedBeforeRollback = NO;
+ vpUIConfigWindowScene = nil; vpUIConfigClientScene = nil; return;
+ }
+ id current = vpReadObject(vpReadObject(server, "uiSettings"), "sb_hostedDisplayConfiguration");
+ id currentDisplay = vpReadObject(vpReadObject(server, "uiSettings"), "displayConfiguration");
+ if (!vpUIObjectsEqual(current, vpUIConfigOriginalHosted) || !vpUIObjectsEqual(currentDisplay, vpUIConfigOriginalServerDisplay)) {
+ if ((!vpUIObjectsEqual(current, vpUIConfigPublished) && !vpUIObjectsEqual(current, vpUIConfigOriginalHosted)) ||
+ (!vpUIObjectsEqual(currentDisplay, vpUIConfigPublished) && !vpUIObjectsEqual(currentDisplay, vpUIConfigOriginalServerDisplay))) {
+ vpFoldDisplayLog(@"UI configuration: newer hosted value preserved; checkpoint retained"); return;
+ }
+ vpSetUISceneConfigurations(vpUIConfigOriginalHosted, vpUIConfigOriginalServerDisplay, current, currentDisplay, generation);
+ } else {
+ id scene = vpUIConfigWindowScene;
+ id liveIdentityBeforeRestore = vpReadObject(scene, "_fbsDisplayIdentity");
+ BOOL uiOwnedBeforeRestore = vpUIConfigurationOwnedByLease(vpReadObject(scene, "_sbDisplayConfiguration")) ||
+ [vpReadObject(liveIdentityBeforeRestore, "uniqueIdentifier") isEqual:vpReadObject(vpReadObject(vpUIConfigPublished, "identity"), "uniqueIdentifier")];
+ if (scene && vpReadObject(scene, "_FBSScene") == vpUIConfigClientScene && uiOwnedBeforeRestore)
+ vpNotifyUIConfiguration(scene, vpUIConfigOriginalUI);
+ id liveIdentity = vpReadObject(scene, "_fbsDisplayIdentity");
+ BOOL uiStillOwned = scene && (vpUIConfigurationOwnedByLease(vpReadObject(scene, "_sbDisplayConfiguration")) ||
+ [vpReadObject(liveIdentity, "uniqueIdentifier") isEqual:vpReadObject(vpReadObject(vpUIConfigPublished, "identity"), "uniqueIdentifier")]);
+ if (!uiStillOwned && vpRestoreUIStatusComponent() && vpRestoreUIScreenTraits()) {
+ vpUIConfigPublished = nil; vpUIConfigOriginalHosted = nil; vpUIConfigOriginalServerDisplay = nil; vpUIConfigOriginalUI = nil;
+ vpUIConfigWindowScene = nil; vpUIConfigServerScene = nil; vpUIConfigClientScene = nil;
+ vpFoldDisplayLog(@"UI configuration: original hosted/UI configuration verified"); return;
+ }
+ }
+ if (attempt < 5) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 5), dispatch_get_main_queue(), ^{
+ vpFinishUIConfigurationRestore(generation, attempt + 1);
+ });
+ else vpFoldDisplayLog(@"UI configuration: restore pending; checkpoint retained");
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration restore exception: %@", exception.reason]);
+ }
+}
+
+static void vpRestoreUIConfiguration(void) {
+ vpRestoreStatusProfileLookup();
+ @try { vpDetachUIStatusComponent(); } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration component detach exception: %@", exception.reason]);
+ }
+ unsigned int generation = atomic_fetch_add_explicit(&vpUIConfigGeneration, 1, memory_order_acq_rel) + 1;
+ vpFinishUIConfigurationRestore(generation, 0);
+}
+
+static void vpActivateUIConfiguration(void) {
+ @try {
+ id scene = vpUIConfigWindowScene;
+ id current = vpReadObject(vpReadObject(vpUIConfigServerScene, "uiSettings"), "sb_hostedDisplayConfiguration");
+ if (!scene || vpReadObject(scene, "_FBSScene") != vpUIConfigClientScene ||
+ !vpUIConfigPublished || !vpUIObjectsEqual(current, vpUIConfigPublished)) {
+ vpFoldDisplayLog(@"UI configuration: activation refused without current hosted lease"); return;
+ }
+ BOOL submitted = vpNotifyUIConfiguration(scene, vpUIConfigPublished);
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration: native client activation submitted=%d", submitted]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration activation exception: %@", exception.reason]);
+ }
+}
+
+static void vpPulseUIConfiguration(BOOL nonEmbedded) {
+ @try {
+ if (vpUIConfigPublished) { vpFoldDisplayLog(@"UI configuration: prior lease must restore first"); return; }
+ id scene = vpMainInnerWindowScene();
+ id root = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ id monitor = vpReadObject(objc_getClass("FBDisplayManager"), "sharedInstance");
+ if (!scene || ![vpReadObject(vpReadObject(scene, "_FBSScene"), "identifier") isEqual:@"SB-main"] ||
+ !vpIsDuoInnerBounds(root) ||
+ [vpReadObject(monitor, "alwaysConnectedIdentities") count] != 1) return;
+ id candidate = nonEmbedded ? vpCreateNonEmbeddedUIConfiguration(root) : vpCreateUIConfiguration(root);
+ id render = vpReadObject(root, "CADisplay");
+ id identity = vpReadObject(candidate, "identity");
+ if (!candidate || !render || vpReadObject(candidate, "CADisplay") != render ||
+ ![vpReadObject(identity, "rootIdentity") isEqual:vpReadObject(root, "identity")] ||
+ [[identity valueForKey:@"isUIKitMainLike"] boolValue] == nonEmbedded || [[identity valueForKey:@"isExternal"] boolValue]) return;
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ id server = nil;
+ for (id candidateServer in vpRootServerScenes(app))
+ if ([vpReadObject(candidateServer, "identifier") isEqual:@"SB-main"]) { server = candidateServer; break; }
+ Method update = class_getInstanceMethod(object_getClass(server), sel_registerName("updateUISettingsWithBlock:"));
+ id client = vpReadObject(scene, "_FBSScene");
+ if (!client || !update || strcmp(method_getTypeEncoding(update), "v24@0:8@?16") != 0) {
+ vpFoldDisplayLog(@"UI configuration: writable SB-main server unavailable"); return;
+ }
+ id settingsCopy = [vpReadObject(server, "uiSettings") mutableCopy];
+ for (NSString *name in @[@"setDisplayConfiguration:", @"_setDisplayConfiguration:", @"setDisplayIdentity:"]) {
+ SEL selector = NSSelectorFromString(name);
+ BOOL available = [settingsCopy respondsToSelector:selector];
+ Method method = available ? class_getInstanceMethod(object_getClass(settingsCopy), selector) : NULL;
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration: mutable %@ %s ABI=%s",
+ NSStringFromClass(object_getClass(settingsCopy)), name.UTF8String, method ? method_getTypeEncoding(method) : "unavailable"]);
+ }
+ vpUIConfigWindowScene = scene;
+ vpUIConfigServerScene = server;
+ vpUIConfigClientScene = client;
+ vpUIConfigOriginalHosted = vpReadObject(vpReadObject(vpUIConfigServerScene, "uiSettings"), "sb_hostedDisplayConfiguration");
+ vpUIConfigOriginalServerDisplay = vpReadObject(vpReadObject(vpUIConfigServerScene, "uiSettings"), "displayConfiguration");
+ vpUIConfigOriginalUI = vpReadObject(scene, "_sbDisplayConfiguration") ?: root;
+ vpUIConfigPublished = candidate;
+ unsigned int generation = atomic_fetch_add_explicit(&vpUIConfigGeneration, 1, memory_order_acq_rel) + 1;
+ vpSetUISceneConfigurations(candidate, candidate, vpUIConfigOriginalHosted, vpUIConfigOriginalServerDisplay, generation);
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration: ten-second hosted lease generation=%u", generation]);
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ if (generation == atomic_load_explicit(&vpUIConfigGeneration, memory_order_acquire)) vpRestoreUIConfiguration();
+ });
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI configuration pulse exception: %@", exception.reason]);
+ }
+}
+
+static void vpPreviewUISceneConfiguration(void) {
+ @try {
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ id rootIdentity = vpReadObject(configuration, "identity");
+ if (![[rootIdentity valueForKey:@"isMainRootDisplay"] boolValue]) return;
+ NSArray *physicalBefore = vpReadObject(objc_getClass("CADisplay"), "displays");
+ NSUInteger physicalCountBefore = physicalBefore.count;
+ id monitor = vpReadObject(objc_getClass("FBDisplayManager"), "sharedInstance");
+ id identitiesBefore = vpReadObject(monitor, "alwaysConnectedIdentities");
+ NSUInteger connectedCountBefore = [identitiesBefore count];
+ Class builderClass = objc_getClass("FBSDisplayConfigurationBuilder");
+ Method setType = class_getInstanceMethod(builderClass, sel_registerName("setDisplayType:"));
+ Method mainLike = class_getInstanceMethod(builderClass, sel_registerName("setUIKitMainLike"));
+ if (!setType || strcmp(method_getTypeEncoding(setType), "v24@0:8q16") != 0 ||
+ !mainLike || strcmp(method_getTypeEncoding(mainLike), "v16@0:8") != 0) return;
+ id<VPhoneDisplayProjectionBuilding> builder = [(id<VPhoneDisplayProjectionBuilding>)[builderClass alloc] initWithConfiguration:configuration];
+ [builder setUniqueIdentifier:@"vphone-duo-ui-preview"];
+ // Unknown (7) is native-valid (type 2 is reserved/invalid). Retain
+ // the integrated, nonexternal Main backing and mark the UI view main-like.
+ [builder setDisplayType:7];
+ [builder setUIKitMainLike];
+ NSError *error = nil;
+ id preview = [builder buildConfigurationWithError:&error];
+ if (!preview) { vpFoldDisplayLog([NSString stringWithFormat:@"UI context preview build failed: %@", error]); return; }
+ id identity = vpReadObject(preview, "identity");
+ NSMutableDictionary *result = [NSMutableDictionary dictionary];
+ for (NSString *key in @[@"isMainDisplay", @"isMainRootDisplay", @"isRootIdentity", @"isUIKitMainLike",
+ @"isAlwaysConnected", @"isExternal", @"connectionType", @"type", @"displayID", @"uniqueIdentifier"])
+ result[key] = [identity valueForKey:key] ?: NSNull.null;
+ result[@"rootIdentity"] = vpReadObject(vpReadObject(identity, "rootIdentity"), "uniqueIdentifier") ?: NSNull.null;
+ result[@"rootMatchesOriginal"] = @([vpReadObject(identity, "rootIdentity") isEqual:rootIdentity]);
+ result[@"bounds"] = vpSnapshotRect(preview, "bounds");
+ id originalRender = vpReadObject(configuration, "CADisplay");
+ id previewRender = vpReadObject(preview, "CADisplay");
+ result[@"renderAccessorAvailable"] = @(originalRender != nil && previewRender != nil);
+ result[@"sameRenderDisplay"] = originalRender && previewRender ? @(originalRender == previewRender) : NSNull.null;
+ result[@"caDisplayObjectCountBefore"] = @(physicalCountBefore);
+ result[@"caDisplayObjectCountAfter"] = @([vpReadObject(objc_getClass("CADisplay"), "displays") count]);
+ result[@"connectedCountBefore"] = @(connectedCountBefore);
+ result[@"connectedCountAfter"] = @([vpReadObject(monitor, "alwaysConnectedIdentities") count]);
+ id app = vpReadObject(objc_getClass("UIApplication"), "sharedApplication");
+ for (id serverScene in vpRootServerScenes(app)) {
+ if (![vpReadObject(serverScene, "identifier") isEqual:@"SB-main"]) continue;
+ id original = vpReadObject(serverScene, "uiSettings");
+ id copy = [original mutableCopy];
+ Method setter = class_getInstanceMethod(object_getClass(copy), sel_registerName("sb_setHostedDisplayConfiguration:"));
+ if (!copy || copy == original || !setter || strcmp(method_getTypeEncoding(setter), "v24@0:8@16") != 0) continue;
+ ((void (*)(id, SEL, id))objc_msgSend)(copy, sel_registerName("sb_setHostedDisplayConfiguration:"), preview);
+ result[@"originalHostedIdentity"] = vpReadObject(vpReadObject(vpReadObject(original, "sb_hostedDisplayConfiguration"), "identity"), "uniqueIdentifier") ?: NSNull.null;
+ result[@"copiedHostedIdentity"] = vpReadObject(vpReadObject(vpReadObject(copy, "sb_hostedDisplayConfiguration"), "identity"), "uniqueIdentifier") ?: NSNull.null;
+ result[@"originalFrame"] = vpSnapshotRect(original, "frame");
+ result[@"copiedFrame"] = vpSnapshotRect(copy, "frame");
+ }
+ result[@"published"] = @NO;
+ NSData *data = [NSJSONSerialization dataWithJSONObject:result options:0 error:NULL];
+ if (data) vpFoldDisplayLog([@"UI context preview " stringByAppendingString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]]);
+ } @catch (NSException *exception) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"UI context preview exception: %@", exception.reason]);
+ }
+}
+
+#include "StatusProfile.inc"
+ vpFoldDisplayLog([NSString stringWithFormat:@"single viewport: requested %@ generation=%u",
+ enabled ? @"cover" : @"native inner", generation]);
+ vpRefreshMainTransform();
+ // The inner revert runs no transform branch of its own; a short delay
+ // lets the native pipeline re-publish first, and the generation dedupe
+ // keeps a transform-side schedule from double-running.
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(),
+ ^{ vpScheduleViewportAdoption(); });
+ // The posture path polls the map for the applied bounds; publish after
+ // the viewport settles so its confirmation loop sees the new size.
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(),
+ ^{ vpExportNativeOrientationMapping(); });
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(),
+ ^{
+ vpExportNativeOrientationMapping();
+ vpApplyQuickActionGlyphScale();
+ });
+ if (enabled && !vpPersistentViewport) {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 45 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ if (atomic_load_explicit(&vpViewportRequestGeneration, memory_order_relaxed) == generation &&
+ atomic_load_explicit(&vpCoverViewportEnabled, memory_order_acquire)) {
+ vpFoldDisplayLog(@"single viewport: timed native-configuration restore");
+ vpSetCoverViewport(NO);
+ }
+ });
+ }
+}
+
+// A single physical Main remains a single hardware source. Its active
+// logical SB-main surface follows the native canonical viewport dimensions.
+// Scoped experiment: do not change CADisplay type or resolver source count.
+static NSInteger vpLogicalSurfaceType(id self, SEL selector) {
+ NSInteger native = ((NSInteger (*)(id, SEL))vpOriginalLogicalSurfaceType)(self, selector);
+ if (vpReadingLogicalSurface || !vpAutomaticMainStatus) return native;
+ vpReadingLogicalSurface = YES;
+ @try {
+ if (![vpReadObject(vpReadObject(self, "_FBSScene"), "identifier") isEqual:@"SB-main"]) return native;
+ id configuration = vpReadObject(objc_getClass("FBDisplayManager"), "mainConfiguration");
+ if (![vpReadObject(self, "displayIdentity") isEqual:vpReadObject(configuration, "identity")]) return native;
+ NSArray *bounds = vpSnapshotRect(configuration, "bounds");
+ if ([bounds isEqual:@[@0, @0, @669, @951]]) return 2;
+ if ([bounds isEqual:@[@0, @0, @466, @678]]) return 1;
+ return native;
+ } @catch (NSException *exception) { return native; }
+ @finally { vpReadingLogicalSurface = NO; }
+}
+
+#include "WallpaperTraitsExperiment.inc"
+
+static void vpSetPersistentViewport(BOOL cover) {
+ if (!vpAutomaticMainStatus || !vpOriginalSceneGeometryCallback || !vpOriginalSBWindowResizePolicy) return;
+ if (vpPersistentViewport && atomic_load_explicit(&vpCoverViewportEnabled, memory_order_acquire) == cover) return;
+ vpPersistentViewport = YES;
+ atomic_store_explicit(&vpNativeGeometryRefreshEnabled, false, memory_order_release);
+ atomic_store_explicit(&vpSceneResizePropagationEnabled, true, memory_order_release);
+ atomic_store_explicit(&vpCoordinateRootSceneFrame, true, memory_order_release);
+ vpSetCoverViewport(cover);
+}
+
+__attribute__((constructor)) static void vpInstallFoldDisplay(void) {
+ if (strcmp(getprogname(), "backboardd") == 0) {
+ Method extended = class_getInstanceMethod(objc_getClass("CAWindowServerDisplay"), sel_registerName("extendedProperties"));
+ if (extended && strcmp(method_getTypeEncoding(extended), "@16@0:8") == 0) {
+ vpOriginalExtendedProperties = method_setImplementation(extended, (IMP)vpSurfaceExtendedProperties);
+ vpFoldDisplayLog(@"surface probe: extendedProperties observer installed, inactive");
+ }
+ static int surfaceToken, surfacePairToken, surfaceCoverToken;
+ notify_register_dispatch("com.vphone.display.surface.inner", &surfaceToken, dispatch_get_main_queue(),
+ ^(int token) { vpBeginSurfaceProbe(2, NO); });
+ notify_register_dispatch("com.vphone.display.surface.pair", &surfacePairToken, dispatch_get_main_queue(),
+ ^(int token) { vpBeginSurfaceProbe(2, YES); });
+ notify_register_dispatch("com.vphone.display.surface.cover", &surfaceCoverToken, dispatch_get_main_queue(),
+ ^(int token) { vpBeginSurfaceProbe(1, NO); });
+ static int createToken, removeToken, serverInspectToken, enableToken, tagToken;
+ notify_register_dispatch("com.vphone.display.virtual.create", &createToken, dispatch_get_main_queue(),
+ ^(int token) { vpVirtualDisplayExperiment(YES); });
+ notify_register_dispatch("com.vphone.display.virtual.remove", &removeToken, dispatch_get_main_queue(),
+ ^(int token) { vpVirtualDisplayExperiment(NO); });
+ notify_register_dispatch("com.vphone.display.server.inspect", &serverInspectToken, dispatch_get_main_queue(),
+ ^(int token) { vpInspectServerClass(); vpInspectRenderDisplays(); });
+ static int orientationInspectToken, orientationEnableToken, orientationRestoreToken;
+ notify_register_dispatch("com.vphone.display.server.orientation.inspect", &orientationInspectToken, dispatch_get_main_queue(),
+ ^(int token) { vpSnapshotBackboardOrientation(); });
+ notify_register_dispatch("com.vphone.display.server.orientation.enable", &orientationEnableToken, dispatch_get_main_queue(),
+ ^(int token) { vpProbeBackboardOrientationEvents(); });
+ notify_register_dispatch("com.vphone.display.server.orientation.restore", &orientationRestoreToken, dispatch_get_main_queue(),
+ ^(int token) { vpRestoreBackboardOrientationEvents(); });
+ notify_register_dispatch("com.vphone.display.virtual.enable", &enableToken, dispatch_get_main_queue(),
+ ^(int token) { vpEnableVirtualDisplayProbe(); });
+ notify_register_dispatch("com.vphone.display.virtual.tag-unknown", &tagToken, dispatch_get_main_queue(),
+ ^(int token) { vpTagVirtualDisplayProbe(); });
+ return;
+ }
+ if (strcmp(getprogname(), "SpringBoard") != 0)
+ return;
+ char product[128] = {0};
+ size_t productLength = sizeof(product);
+ vpAutomaticMainStatus = sysctlbyname("hw.machine", product, &productLength, NULL, 0) == 0 &&
+ strcmp(product, "iPhone19,4") == 0;
+ // The round-16 landscape wallpaper gate is now part of the Duo startup
+ // path. The one-shot marker remains accepted for older guests, but a
+ // fresh boot must not silently fall back to the portrait wallpaper
+ // admission path (which recreates the black bands).
+ if (vpAutomaticMainStatus || vpConsumeDisplayExperimentFlag("/var/mobile/Library/Caches/vphone-duo-wallpaper-traits.once")) {
+ vpInstallWallpaperTraitsExperiment();
+ vpInstallLandscapeWallpaperGateDetour();
+ }
+ BOOL requestedFamily = vpConsumeDisplayExperimentFlag("/var/mobile/Library/Caches/vphone-duo-viewport-family.once");
+ if (vpAutomaticMainStatus || requestedFamily)
+ vpInstallViewportFamilyLookup();
+ // Duo has one physical Main, but SpringBoard's native scene policy still
+ // needs the inner role to participate in orientation and status-bar
+ // arbitration. The role adapter preserves the physical identity and is
+ // now part of the normal Duo path; the old once marker remains accepted
+ // for older guests but is no longer required.
+ if (vpAutomaticMainStatus || vpConsumeDisplayExperimentFlag("/var/mobile/Library/Caches/vphone-duo-logical-role.once")) {
+ Method surface = class_getInstanceMethod(objc_getClass("SBWindowScene"), sel_registerName("surfaceType"));
+ if (surface && strcmp(method_getTypeEncoding(surface), "q16@0:8") == 0) {
+ vpLogicalRoleExperiment = YES;
+ Class clock = objc_getClass("SBFMachNextMinuteDateProvider");
+ Method tick = class_getInstanceMethod(clock, sel_registerName("_onMachTimer"));
+ Method observe = class_getInstanceMethod(clock, sel_registerName("observeMinuteUpdatesWithHandler:"));
+ if (tick && observe && strcmp(method_getTypeEncoding(tick), "v16@0:8") == 0 &&
+ strcmp(method_getTypeEncoding(observe), "@24@0:8@?16") == 0) {
+ vpOriginalMachClockTick = method_setImplementation(tick, (IMP)vpMachClockTick);
+ vpOriginalMachClockObserve = method_setImplementation(observe, (IMP)vpMachClockObserve);
+ vpFoldDisplayLog(@"native clock reference: detached-view scheduling adapter installed");
+ }
+ Method timeUpdate = class_getInstanceMethod(objc_getClass("SBStatusBarStateAggregator"), sel_registerName("_updateTimeItemsWithDate:"));
+ if (timeUpdate && strcmp(method_getTypeEncoding(timeUpdate), "v24@0:8@16") == 0)
+ vpOriginalTimeItemUpdate = method_setImplementation(timeUpdate, (IMP)vpObserveNativeTimeUpdate);
+ vpOriginalLogicalSurfaceType = method_setImplementation(surface, (IMP)vpLogicalSurfaceType);
+ vpFoldDisplayLog(@"logical surface: native-size scoped SB-main role adapter installed");
+ }
+ }
+ vpObservedDisplayMonitors = [NSHashTable weakObjectsHashTable];
+ vpResizedSceneGenerations = [NSMutableDictionary dictionary];
+ Method resizePolicy = class_getInstanceMethod(objc_getClass("SBWindow"), sel_registerName("_shouldResizeWithScene"));
+ if (resizePolicy && strcmp(method_getTypeEncoding(resizePolicy), "B16@0:8") == 0)
+ vpOriginalSBWindowResizePolicy = method_setImplementation(resizePolicy, (IMP)vpAllowScopedMainWindowResize);
+ Method sceneGeometry = class_getInstanceMethod(objc_getClass("SBAbstractWindowSceneDelegate"),
+ sel_registerName("windowScene:didUpdateCoordinateSpace:interfaceOrientation:traitCollection:"));
+ if (sceneGeometry && strcmp(method_getTypeEncoding(sceneGeometry), "v48@0:8@16@24q32@40") == 0)
+ vpOriginalSceneGeometryCallback = method_setImplementation(sceneGeometry, (IMP)vpObserveSceneGeometry);
+ // Retired: promoting a software CADisplay to builtin asserted in cloning.
+ // Consume stale markers without ever installing that type/scale override.
+ if (vpConsumeDisplayExperimentFlag("/var/mobile/Library/Caches/vphone-duo-internal-panel.once"))
+ vpFoldDisplayLog(@"panel adapter: retired builtin promotion marker discarded");
+ if (vpConsumeDisplayExperimentFlag("/var/mobile/Library/Caches/vphone-duo-shared-family.once"))
+ vpInstallSharedInnerFamily();
+ BOOL requestedMainStatus = vpConsumeDisplayExperimentFlag("/var/mobile/Library/Caches/vphone-duo-main-status.once");
+ if (vpAutomaticMainStatus || requestedMainStatus) vpInstallMainStatusLookup();
+ if (vpAutomaticMainStatus) {
+ static int mainStatusStartupToken;
+ notify_register_dispatch("com.apple.springboard.finishedstartup", &mainStatusStartupToken, dispatch_get_main_queue(),
+ ^(int token) { vpPulseMainStatusProfile(); });
+ // The library may load before scene construction or after the startup
+ // notification. Bounded retries establish the existing Main renderer.
+ for (unsigned int retry = 1; retry <= 12; ++retry)
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, retry * NSEC_PER_SEC), dispatch_get_main_queue(),
+ ^{ vpPulseMainStatusProfile(); });
+ // The same ladder establishes the default quick-action glyph scale
+ // on every lock-screen construction timing without any opt-in file.
+ for (unsigned int retry = 1; retry <= 12; ++retry)
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, retry * NSEC_PER_SEC), dispatch_get_main_queue(),
+ ^{ vpApplyQuickActionGlyphScale(); });
+ }
+ if (vpAutomaticMainStatus || vpConsumeDisplayExperimentFlag("/var/mobile/Library/Caches/vphone-duo-scene-status.once"))
+ vpInstallSceneStatusPolicy();
+ if (vpConsumeDisplayExperimentFlag("/var/mobile/Library/Caches/vphone-duo-root-scene-policy.once"))
+ vpFoldDisplayLog(@"root scene policy: retired global Main conversion marker discarded");
+ if (vpConsumeDisplayExperimentFlag("/var/mobile/Library/Caches/vphone-duo-inner-family.once")) {
+ Method family = class_getInstanceMethod(objc_getClass("SBWindowScene"), sel_registerName("sbhScreenType"));
+ if (family && strcmp(method_getTypeEncoding(family), "Q16@0:8") == 0) {
+ vpOriginalSceneScreenType = method_setImplementation(family, (IMP)vpNativeInnerSceneFamily);
+ vpFoldDisplayLog(@"shared scene family: one-instance classifier adapter installed");
+ }
+ }
+ BOOL requestedSingleInner = vpConsumeDisplayExperimentFlag("/var/mobile/Library/Caches/vphone-duo-single-inner.once");
+ if (vpLogicalRoleExperiment || requestedSingleInner) {
+ Method resolve = class_getInstanceMethod(objc_getClass("SBFDisplayContentModeResolver"),
+ sel_registerName("_startResolvingContentModeOfDisplay:"));
+ if (resolve && strcmp(method_getTypeEncoding(resolve), "v24@0:8@16") == 0) {
+ vpOriginalStartResolvingDisplay = method_setImplementation(resolve, (IMP)vpResolveSingleInnerDisplay);
+ vpFoldDisplayLog(@"single inner readiness: one-instance adapter installed");
+ } else vpFoldDisplayLog(@"single inner readiness: native callback ABI unavailable");
+ }
+ // SBFBSDisplayTransformer requires one result per source. The startup
+ // two-result experiment asserted before monitor initialization; retain
+ // native builder preview only, never arm that publication again.
+ if (vpConsumeDisplayExperimentFlag("/var/mobile/Library/Caches/vphone-duo-logical-panel.once"))
+ vpFoldDisplayLog(@"logical projection: unsupported startup marker discarded");
+static int persistentCoverToken, persistentInnerToken;
+ notify_register_dispatch("com.vphone.display.viewport.apply.cover", &persistentCoverToken, dispatch_get_main_queue(),
+ ^(int token) { vpSetPersistentViewport(YES); });
+ notify_register_dispatch("com.vphone.display.viewport.apply.inner", &persistentInnerToken, dispatch_get_main_queue(),
+ ^(int token) { vpSetPersistentViewport(NO); });
+ static int workspaceRefreshToken;
+ notify_register_dispatch("com.vphone.display.workspace.refresh", &workspaceRefreshToken, dispatch_get_main_queue(),
+ ^(int token) { vpProcessViewportWorkspaceRequest(YES); });
+ static int workspacePreviewToken;
+ notify_register_dispatch("com.vphone.display.workspace.preview", &workspacePreviewToken, dispatch_get_main_queue(),
+ ^(int token) { vpProcessViewportWorkspaceRequest(NO); });
+ static int presentationWallpaperToken;
+ notify_register_dispatch("com.vphone.display.presentation.wallpaper.pulse", &presentationWallpaperToken, dispatch_get_main_queue(),
+ ^(int token) { vpPulseNativeWallpaperOrientation(); });
+ static int presentationClockToken;
+ notify_register_dispatch("com.vphone.display.presentation.clock.refresh", &presentationClockToken, dispatch_get_main_queue(),
+ ^(int token) { vpRefreshNativeClockSource(); });
+ static int presentationRegistrationToken;
+ notify_register_dispatch("com.vphone.display.presentation.registration.refresh", &presentationRegistrationToken, dispatch_get_main_queue(),
+ ^(int token) { vpRefreshNativeStatusRegistration(); });
+ static int presentationInspectToken;
+ notify_register_dispatch("com.vphone.display.presentation.inspect", &presentationInspectToken, dispatch_get_main_queue(),
+ ^(int token) { vpInspectNativePresentation(); });
+ static int quickActionInspectToken;
+ notify_register_dispatch("com.vphone.display.quickaction.inspect", &quickActionInspectToken, dispatch_get_main_queue(),
+ ^(int token) { vpInspectQuickActions(); });
+ // Installed before SpringBoard builds its cover sheet, so the first
+ // SBSDeviceDeterminedConfiguration construction is captured.
+ vpInstallConfigInitSwizzle();
+ vpInstallLayoutClassSwizzle();
+ static int windowsInspectToken;
+ notify_register_dispatch("com.vphone.display.windows.inspect", &windowsInspectToken, dispatch_get_main_queue(),
+ ^(int token) { vpInspectAllWindows(); });
+ static int wallpaperSceneHostSyncToken;
+ notify_register_dispatch("com.vphone.display.wallpaper.scenehost.sync", &wallpaperSceneHostSyncToken, dispatch_get_main_queue(),
+ ^(int token) { vpSyncWallpaperSceneHosts(); });
+ // Keep a fresh SB-main orientation map from the first minute of boot:
+ // vphoned's rotation and posture paths refuse to settle without it.
+ for (unsigned int retry = 2; retry <= 12; retry += 2)
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(retry * NSEC_PER_SEC)), dispatch_get_main_queue(),
+ ^{ vpExportNativeOrientationMapping(); });
+ static int screenUndimToken;
+ notify_register_dispatch("com.vphone.display.screen.undim", &screenUndimToken, dispatch_get_main_queue(),
+ ^(int token) { vpUndimScreenOnly(); });
+ static int displayStateToken;
+ notify_register_dispatch("com.vphone.display.inspect", &displayStateToken, dispatch_get_main_queue(),
+ ^(int token) { vpSnapshotMainScene(); });
+ static int displayDetailsToken, homeFamilyToken;
+ notify_register_dispatch("com.vphone.display.inspect.detail", &displayDetailsToken, dispatch_get_main_queue(),
+ ^(int token) { vpInspectDisplayState(); });
+ notify_register_dispatch("com.vphone.display.families.inspect", &homeFamilyToken, dispatch_get_main_queue(),
+ ^(int token) { vpInspectHomeScreenType(); });
+ static int uiContextPreviewToken;
+ notify_register_dispatch("com.vphone.display.ui_context.preview", &uiContextPreviewToken, dispatch_get_main_queue(),
+ ^(int token) { vpPreviewUISceneConfiguration(); });
+ static int duoSystemUIInspectToken;
+ notify_register_dispatch("com.vphone.display.duo_system_ui.inspect", &duoSystemUIInspectToken, dispatch_get_main_queue(),
+ ^(int token) { vpInspectDuoSystemUI(); });
+ static int statusProviderInspectToken;
+ notify_register_dispatch("com.vphone.display.status_provider.inspect", &statusProviderInspectToken, dispatch_get_main_queue(),
+ ^(int token) { vpInspectStatusProvider(); });
+ static int statusProfilePulseToken, statusProfileRestoreToken;
+ notify_register_dispatch("com.vphone.display.status_profile.pulse", &statusProfilePulseToken, dispatch_get_main_queue(),
+ ^(int token) { vpPulseStatusProfileLookup(); });
+ notify_register_dispatch("com.vphone.display.status_profile.restore", &statusProfileRestoreToken, dispatch_get_main_queue(),
+ ^(int token) { vpRestoreStatusProfileLookup(); });
+ static int inputTracePulseToken, inputTraceRestoreToken;
+ notify_register_dispatch("com.vphone.display.input_trace.pulse", &inputTracePulseToken, dispatch_get_main_queue(),
+ ^(int token) { vpPulseInputTrace(); });
+ notify_register_dispatch("com.vphone.display.input_trace.restore", &inputTraceRestoreToken, dispatch_get_main_queue(),
+ ^(int token) { vpRestoreInputTrace(); });
+ static int mainStatusPulseToken, mainStatusRestoreToken;
+ notify_register_dispatch("com.vphone.display.main_status.pulse", &mainStatusPulseToken, dispatch_get_main_queue(),
+ ^(int token) { vpPulseMainStatusProfile(); });
+ notify_register_dispatch("com.vphone.display.main_status.restore", &mainStatusRestoreToken, dispatch_get_main_queue(),
+ ^(int token) { vpRestoreMainStatusProfile(); });
+ static int orientationMappingToken;
+ notify_register_dispatch("com.vphone.display.orientation.mapping.request", &orientationMappingToken, dispatch_get_main_queue(),
+ ^(int token) { vpExportNativeOrientationMapping(); });
+ static int uiContextPulseToken, uiContextActivateToken, uiContextRestoreToken;
+ notify_register_dispatch("com.vphone.display.ui_context.pulse", &uiContextPulseToken, dispatch_get_main_queue(),
+ ^(int token) { vpPulseUIConfiguration(NO); });
+ static int uiNonEmbeddedPreviewToken, uiNonEmbeddedPulseToken;
+ notify_register_dispatch("com.vphone.display.ui_context.unembedded.preview", &uiNonEmbeddedPreviewToken, dispatch_get_main_queue(),
+ ^(int token) { vpPreviewNonEmbeddedUIConfiguration(); });
+ notify_register_dispatch("com.vphone.display.ui_context.unembedded.pulse", &uiNonEmbeddedPulseToken, dispatch_get_main_queue(),
+ ^(int token) { vpPulseUIConfiguration(YES); });
+ static int uiScreenTraitsToken;
+ notify_register_dispatch("com.vphone.display.ui_context.traits.sync", &uiScreenTraitsToken, dispatch_get_main_queue(),
+ ^(int token) { vpSyncUIScreenTraits(); });
+ notify_register_dispatch("com.vphone.display.ui_context.activate", &uiContextActivateToken, dispatch_get_main_queue(),
+ ^(int token) { vpActivateUIConfiguration(); });
+ notify_register_dispatch("com.vphone.display.ui_context.restore", &uiContextRestoreToken, dispatch_get_main_queue(),
+ ^(int token) { vpRestoreUIConfiguration(); });
+ static int uiContextComponentToken;
+ notify_register_dispatch("com.vphone.display.ui_context.components.refresh", &uiContextComponentToken, dispatch_get_main_queue(),
+ ^(int token) { vpRefreshUIStatusComponent(); });
+ static int invalidationPulseToken;
+ notify_register_dispatch("com.vphone.display.invalidation.pulse", &invalidationPulseToken, dispatch_get_main_queue(),
+ ^(int token) {
+ if (!atomic_load_explicit(&vpCoverViewportEnabled, memory_order_acquire)) vpRefreshMainTransform();
+ });
+ static int coverViewportToken, innerViewportToken;
+ notify_register_dispatch("com.vphone.display.viewport.cover", &coverViewportToken, dispatch_get_main_queue(),
+ ^(int token) { vpSetCoverViewport(YES); });
+ notify_register_dispatch("com.vphone.display.viewport.inner", &innerViewportToken, dispatch_get_main_queue(),
+ ^(int token) { vpSetCoverViewport(NO); });
+ static int orientationSyncToken, orientationRestoreToken;
+ notify_register_dispatch("com.vphone.display.orientation.sync", &orientationSyncToken, dispatch_get_main_queue(),
+ ^(int token) { vpSyncRootSceneOrientation(); });
+ notify_register_dispatch("com.vphone.display.orientation.restore", &orientationRestoreToken, dispatch_get_main_queue(),
+ ^(int token) { vpRestoreRootSceneOrientations(); });
+ static int geometryRequestToken, geometryRestoreToken, poseRefreshToken, inputsRefreshToken;
+ notify_register_dispatch("com.vphone.display.orientation.geometry", &geometryRequestToken, dispatch_get_main_queue(),
+ ^(int token) { vpProbeSceneGeometryRequest(); });
+ notify_register_dispatch("com.vphone.display.orientation.geometry.restore", &geometryRestoreToken, dispatch_get_main_queue(),
+ ^(int token) { vpRestoreSceneGeometryRequest(); });
+ notify_register_dispatch("com.vphone.display.orientation.pose.refresh", &poseRefreshToken, dispatch_get_main_queue(),
+ ^(int token) { vpRefreshNativeOrientationInputs(YES); });
+ notify_register_dispatch("com.vphone.display.orientation.inputs.refresh", &inputsRefreshToken, dispatch_get_main_queue(),
+ ^(int token) { vpRefreshNativeOrientationInputs(NO); });
+ static int arbitrationRefreshToken;
+ notify_register_dispatch("com.vphone.display.orientation.arbitration.refresh", &arbitrationRefreshToken, dispatch_get_main_queue(),
+ ^(int token) { vpForceNativeOrientationResolution(); });
+ static int actuationRefreshToken;
+ notify_register_dispatch("com.vphone.display.orientation.actuation.refresh", &actuationRefreshToken, dispatch_get_main_queue(),
+ ^(int token) {
+ vpRefreshNativeOrientationActuation();
+ // Rotation pulses rebuild lock-screen presentation; fresh glyph
+ // instances render at the native factor until re-scaled.
+ if (vpAutomaticMainStatus) vpApplyQuickActionGlyphScale();
+ });
+ static int embeddedOrientationToken, embeddedOrientationRestoreToken;
+ notify_register_dispatch("com.vphone.display.orientation.embedded.sync", &embeddedOrientationToken, dispatch_get_main_queue(),
+ ^(int token) { vpProbeEmbeddedOrientation(); });
+ notify_register_dispatch("com.vphone.display.orientation.embedded.restore", &embeddedOrientationRestoreToken, dispatch_get_main_queue(),
+ ^(int token) { vpRestoreEmbeddedOrientation(); });
+ static int canonicalOrientationToken, canonicalOrientationRestoreToken;
+ notify_register_dispatch("com.vphone.display.orientation.canonical", &canonicalOrientationToken, dispatch_get_main_queue(),
+ ^(int token) { vpSetCanonicalOrientationProbe(YES); });
+ notify_register_dispatch("com.vphone.display.orientation.canonical.restore", &canonicalOrientationRestoreToken, dispatch_get_main_queue(),
+ ^(int token) { vpSetCanonicalOrientationProbe(NO); });
+ static int sceneViewportToken;
+ notify_register_dispatch("com.vphone.display.viewport.scene.cover", &sceneViewportToken, dispatch_get_main_queue(),
+ ^(int token) {
+ atomic_store_explicit(&vpCoordinateRootSceneFrame, true, memory_order_release);
+ vpSetCoverViewport(YES);
+ });
+ static int pipelineViewportToken;
+ notify_register_dispatch("com.vphone.display.viewport.pipeline.cover", &pipelineViewportToken, dispatch_get_main_queue(),
+ ^(int token) {
+ if (!vpOriginalSceneGeometryCallback) return;
+ atomic_store_explicit(&vpNativeGeometryRefreshEnabled, true, memory_order_release);
+ atomic_store_explicit(&vpCoordinateRootSceneFrame, true, memory_order_release);
+ vpSetCoverViewport(YES);
+ });
+ static int resizeViewportToken;
+ notify_register_dispatch("com.vphone.display.viewport.resize.cover", &resizeViewportToken, dispatch_get_main_queue(),
+ ^(int token) {
+ if (!vpOriginalSceneGeometryCallback || !vpOriginalSBWindowResizePolicy) return;
+ atomic_store_explicit(&vpNativeGeometryRefreshEnabled, false, memory_order_release);
+ atomic_store_explicit(&vpSceneResizePropagationEnabled, true, memory_order_release);
+ atomic_store_explicit(&vpCoordinateRootSceneFrame, true, memory_order_release);
+ vpSetCoverViewport(YES);
+ });
+ static int allowUnknownToken, restoreUnknownToken;
+ notify_register_dispatch("com.vphone.display.unknown.allow", &allowUnknownToken, dispatch_get_main_queue(),
+ ^(int token) { vpProbeUnknownDisplayPolicy(NO); });
+ notify_register_dispatch("com.vphone.display.unknown.restore", &restoreUnknownToken, dispatch_get_main_queue(),
+ ^(int token) { vpProbeUnknownDisplayPolicy(YES); });
+ static int projectionPreviewToken, projectionEnableToken, projectionDisableToken;
+ notify_register_dispatch("com.vphone.display.logical.preview", &projectionPreviewToken, dispatch_get_main_queue(),
+ ^(int token) { vpLogicalProjectionControl(0); });
+ notify_register_dispatch("com.vphone.display.logical.enable", &projectionEnableToken, dispatch_get_main_queue(),
+ ^(int token) { vpFoldDisplayLog(@"logical projection publication rejected: native transformer requires one result"); });
+ notify_register_dispatch("com.vphone.display.logical.disable", &projectionDisableToken, dispatch_get_main_queue(),
+ ^(int token) { vpLogicalProjectionControl(2); });
+ Class transformer = objc_getClass("SBMainDisplayConfigurationTransformer");
+ Method transform = class_getInstanceMethod(transformer, sel_registerName("transformDisplayConfiguration:"));
+ if (transform && strcmp(method_getTypeEncoding(transform), "@24@0:8@16") == 0) {
+ vpOriginalTransform = method_setImplementation(transform, (IMP)vpLoggedTransform);
+ vpFoldDisplayLog(@"transform probe installed");
+ } else {
+ vpFoldDisplayLog([NSString stringWithFormat:@"transform probe unavailable: %s",
+ transform ? method_getTypeEncoding(transform) : "missing"]);
+ }
+ dlopen("/System/Library/PrivateFrameworks/FrontBoard.framework/FrontBoard",
+ RTLD_LAZY | RTLD_LOCAL);
+ Class manager = objc_getClass("FBDisplayManager");
+ Method alwaysConnected = manager
+ ? class_getClassMethod(manager, sel_registerName("alwaysConnectedIdentities"))
+ : NULL;
+ if (!alwaysConnected) {
+ vpFoldDisplayLog(@"FBDisplayManager alwaysConnectedIdentities missing — idle");
+ return;
+ }
+ vpOriginalAlwaysConnected = method_getImplementation(alwaysConnected);
+ method_setImplementation(alwaysConnected, (IMP)vpObservedAlwaysConnected);
+ vpFoldDisplayLog(@"observation installed over +alwaysConnectedIdentities");
+
+ dlopen("/System/Library/PrivateFrameworks/FrontBoardServices.framework/FrontBoardServices",
+ RTLD_LAZY | RTLD_LOCAL);
+ Class monitor = objc_getClass("FBSDisplayMonitor");
+ Method publicInit = class_getInstanceMethod(monitor, sel_registerName("initWithTransformer:"));
+ if (publicInit && strcmp(method_getTypeEncoding(publicInit), "@24@0:8@16") == 0)
+ vpOriginalPublicMonitorInit = method_setImplementation(publicInit, (IMP)vpObservePublicMonitorInit);
+ Method completionInit = class_getInstanceMethod(monitor, sel_registerName("initWithInitializationCompletion:"));
+ if (completionInit && strcmp(method_getTypeEncoding(completionInit), "@24@0:8@?16") == 0)
+ vpOriginalCompletionMonitorInit = method_setImplementation(completionInit, (IMP)vpObserveCompletionMonitorInit);
+ Method monitorInit = monitor
+ ? class_getInstanceMethod(monitor,
+ sel_registerName("_initWithDisplays:mainDisplay:bookendObserver:transformer:"))
+ : NULL;
+ if (!monitorInit) {
+ vpFoldDisplayLog(@"FBSDisplayMonitor init missing — monitor half idle");
+ return;
+ }
+ vpOriginalMonitorInit = method_getImplementation(monitorInit);
+ method_setImplementation(monitorInit, (IMP)vpObservedMonitorInit);
+ vpFoldDisplayLog(@"observation installed over _initWithDisplays:mainDisplay:bookendObserver:transformer:");
+
+ Method identities = class_getInstanceMethod(monitor, sel_registerName("alwaysConnectedIdentities"));
+ if (identities) {
+ vpOriginalMonitorIdentities = method_getImplementation(identities);
+ method_setImplementation(identities, (IMP)vpObservedMonitorIdentities);
+ vpFoldDisplayLog(@"observation installed over -[FBSDisplayMonitor alwaysConnectedIdentities]");
+ } else {
+ vpFoldDisplayLog(@"FBSDisplayMonitor alwaysConnectedIdentities missing");
+ }
+ for (NSString *name in @[@"mainConfiguration", @"mainIdentity"]) {
+ SEL selector = sel_registerName(name.UTF8String);
+ Method method = class_getClassMethod(manager, selector);
+ if (!method) {
+ vpFoldDisplayLog([NSString stringWithFormat:@"FBDisplayManager %@ missing", name]);
+ continue;
+ }
+ if (selector == sel_registerName("mainConfiguration")) {
+ vpOriginalMainConfiguration = method_getImplementation(method);
+ method_setImplementation(method, (IMP)vpLoggedMainConfiguration);
+ } else {
+ vpOriginalMainIdentity = method_getImplementation(method);
+ method_setImplementation(method, (IMP)vpLoggedMainIdentity);
+ }
+ vpFoldDisplayLog([NSString stringWithFormat:@"log installed over +[%@ %@]",
+ NSStringFromClass(manager), name]);
+ }
+ Method configurations = class_getInstanceMethod(monitor, sel_registerName("_lock_alwaysConnectedConfigurations"));
+ if (configurations) {
+ vpOriginalLockConfigurations = method_getImplementation(configurations);
+ method_setImplementation(configurations, (IMP)vpObservedLockConfigurations);
+ vpFoldDisplayLog(@"observation installed over _lock_alwaysConnectedConfigurations");
+ }
+}
diff --git a/VPhoneGuestComponents/FoldGuard/libvphonefoldguard.m b/VPhoneGuestComponents/FoldGuard/libvphonefoldguard.m
new file mode 100644
index 00000000..44a31205
--- /dev/null
+++ b/VPhoneGuestComponents/FoldGuard/libvphonefoldguard.m
@@ -0,0 +1,115 @@
+// libvphonefoldguard.m — keep SpringBoard alive under the foldable identity.
+//
+// The Duo product-id token (preboot-exp-devicetree_foldable_product_id) opens
+// SpringBoard's fold layouts — and kills it on the single-display guest: the
+// first CA transaction reaches
+// -[CASecureIndicatorLayer _copyRenderLayer:layerFlags:commitFlags:], which
+// raises CASecureIndicatorLayerInvalidName ("Invalid indicator name Camera";
+// SpringBoard SIGABRT, com.apple.osanalytics
+// SpringBoard-2026-10-25-103807/08, measured twice on iOS 27.1 24A94425).
+//
+// The validation was reversed end to end (2026-10-25, guest's own lowered
+// cache + a live alias experiment; see Research/Guest/iphone_duo_bringup.md):
+// _copyRenderLayer reads the layer's privacyIndicatorType and asks a
+// validator that first consults a runtime registry — populated from the
+// window server per display — and only falls back to a static name list
+// (which contains "Camera", "Microphone", "MicrophoneAccessibility") when
+// that registry pointer is nil. The virtual panel registers no secure
+// indicator slots at all, so the registry is empty and every name is
+// "invalid" — aliasing Camera to Microphone still raised, as Microphone.
+// Filling the registry belongs to backboardd's CAWindowServerDisplay (the
+// same missing display-topology family as the fold layout), so the client
+// cannot fix it; the guard therefore catches the raise at the QuartzCore
+// boundary and answers no layer copy. The commit proceeds without the
+// secure indicator instead of taking the system app down, and the guard is
+// inert on a guest without the foldable identity. Loaded by SystemHook into
+// SpringBoard only.
+
+#import <Foundation/Foundation.h>
+#import <objc/runtime.h>
+#include <dlfcn.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+static void vpFoldLog(NSString *format, ...) {
+ va_list arguments;
+ va_start(arguments, format);
+ NSString *line = [[NSString alloc] initWithFormat:format arguments:arguments];
+ va_end(arguments);
+ if (!line)
+ return;
+ int fd = open("/var/mobile/Library/Caches/vphone-foldguard.log",
+ O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0666);
+ if (fd < 0)
+ return;
+ fchmod(fd, 0666);
+ dprintf(fd, "pid=%d %s\n", getpid(), line.UTF8String);
+ close(fd);
+}
+
+// QuartzCore returns an unmanaged CA::Render::Layer*, not an Objective-C
+// object. An id return lets ARC retain that C++ pointer and PAC-fault in
+// objc_msgSend on successful copies. Only forward pointer/integer GPR args.
+static IMP vpOriginalCopyRender;
+
+static const char *vpUnqualifiedType(const char *type) {
+ while (*type && strchr("rnNoORV", *type)) type++;
+ return type;
+}
+
+static BOOL vpCopyRenderABIIsSupported(Method method) {
+ if (!method) return NO;
+ NSMethodSignature *signature = [NSMethodSignature signatureWithObjCTypes:method_getTypeEncoding(method)];
+ if (signature.numberOfArguments != 5 || signature.methodReturnLength != sizeof(void *) ||
+ vpUnqualifiedType(signature.methodReturnType)[0] != '^') return NO;
+ for (NSUInteger index = 2; index < 5; index++) {
+ const char *type = vpUnqualifiedType([signature getArgumentTypeAtIndex:index]);
+ if (!strchr("^QqIiLlSsCcB", type[0])) return NO;
+ NSUInteger size = 0;
+ NSGetSizeAndAlignment(type, &size, NULL);
+ if (!size || size > sizeof(uintptr_t)) return NO;
+ }
+ return YES;
+}
+
+static void *vpGuardedCopyRender(id self, SEL selector, uintptr_t argument1, uintptr_t argument2, uintptr_t argument3) {
+ @try {
+ void *result = ((void *(*)(id, SEL, uintptr_t, uintptr_t, uintptr_t))vpOriginalCopyRender)(
+ self, selector, argument1, argument2, argument3);
+ static BOOL loggedNonNull = NO;
+ if (result && !loggedNonNull) {
+ loggedNonNull = YES;
+ vpFoldLog(@"forwarded non-null unmanaged render layer without ARC ownership");
+ }
+ return result;
+ } @catch (id exception) {
+ static int swallowed = 0;
+ int seen = swallowed++;
+ if (seen < 5)
+ vpFoldLog(@"swallowed secure-indicator exception #%d: %@ — %@", seen,
+ [(NSException *)exception name], [(NSException *)exception reason]);
+ else if (seen == 5)
+ vpFoldLog(@"further secure-indicator exceptions are not logged");
+ return NULL;
+ }
+}
+
+__attribute__((constructor)) static void vpInstallFoldGuard(void) {
+ if (strcmp(getprogname(), "SpringBoard") != 0)
+ return;
+ dlopen("/System/Library/Frameworks/QuartzCore.framework/QuartzCore", RTLD_LAZY | RTLD_LOCAL);
+ Class layer = objc_getClass("CASecureIndicatorLayer");
+ Method copyRender = layer ? class_getInstanceMethod(
+ layer, sel_registerName("_copyRenderLayer:layerFlags:commitFlags:"))
+ : NULL;
+ if (!vpCopyRenderABIIsSupported(copyRender)) {
+ vpFoldLog(@"CASecureIndicatorLayer pointer-copy ABI %@ — guard idle",
+ copyRender ? @(method_getTypeEncoding(copyRender)) : (layer ? @"missing" : @"class not found"));
+ return;
+ }
+ vpOriginalCopyRender = method_getImplementation(copyRender);
+ method_setImplementation(copyRender, (IMP)vpGuardedCopyRender);
+ vpFoldLog(@"guard installed over _copyRenderLayer:layerFlags:commitFlags: ABI=%s (unmanaged pointer)", method_getTypeEncoding(copyRender));
+}
diff --git a/VPhoneGuestComponents/Hinge/VPhoneHingeHID.h b/VPhoneGuestComponents/Hinge/VPhoneHingeHID.h
new file mode 100644
index 00000000..d8a85ba6
--- /dev/null
+++ b/VPhoneGuestComponents/Hinge/VPhoneHingeHID.h
@@ -0,0 +1,34 @@
+#pragma once
+#import <Foundation/Foundation.h>
+
+// Small ABI surface from Apple's IOHIDfamily HIDVirtualEventService.h, plus
+// the C hinge-angle event factory IOHIDEventCreateHingeAngleEvent. Everything
+// is resolved at runtime, so the guest library needs no private SDK stub:
+// the factory is a dlsym, the service class an NSClassFromString.
+@protocol VPhoneHingeHIDService <NSObject>
+@property (weak) id delegate;
+@property (readonly) uint64_t serviceID;
+- (void)setDispatchQueue:(dispatch_queue_t)queue;
+- (void)setCancelHandler:(dispatch_block_t)handler;
+- (void)activate;
+- (void)cancel;
+- (BOOL)dispatchEvent:(id)event;
+@end
+
+// HID.framework, verified against macOS 27.0.1's copy by calling it and
+// reading the event's own field description back:
+// IOHIDEventCreateHingeAngleEvent(allocator, timeStamp,
+// angleDegrees, mechanicalAngleDegrees,
+// velocityDegreesPerSecond, options)
+// CoreMotion's CLAngleNotifier consumes events of this type (0x2C) from the
+// virtual service below. The created event carries the hinge state through
+// HIDEvent's own -setHingeAngleState: accessor, the same field Apple's
+// recorded Duo samples (hinge-samples.csv in SpringBoardFoundation) carry
+// per sample.
+typedef void *(*VPhoneHingeEventFactory)(void *, uint64_t, double, double, double, uint32_t);
+
+// HIDEvent's hinge accessors, resolved at runtime beside the factory.
+@protocol VPhoneHingeHIDEvent <NSObject>
+- (void)setHingeAngleState:(int32_t)state;
+@property (readonly) double hingeAngleAngleDegrees;
+@end
diff --git a/VPhoneGuestComponents/Hinge/VPhoneHingeState.h b/VPhoneGuestComponents/Hinge/VPhoneHingeState.h
new file mode 100644
index 00000000..f6aaddf6
--- /dev/null
+++ b/VPhoneGuestComponents/Hinge/VPhoneHingeState.h
@@ -0,0 +1,110 @@
+#pragma once
+#import <Foundation/Foundation.h>
+#include <math.h>
+
+// One dictionary per update, as with the gyroscope: readers never combine an
+// angle with a pose from a different request.
+#define VP_HINGE_DOMAIN "com.apple.backboardd"
+#define VP_HINGE_CONFIGURATION "VPhoneHingeAngle"
+#define VP_HINGE_STATUS "VPhoneHingeStatus"
+// The newest sample, written beside every HID dispatch (angle,
+// mechanical_angle, velocity, state, event_phase, timestamp) so readers that
+// cannot subscribe to the HID service still see the hinge move. Written
+// without a disk sync: one entry per 10 ms sweep tick must not become one
+// plist flush per tick; cfprefsd carries it and readers sync their own view.
+#define VP_HINGE_LATEST "VPhoneHingeLatest"
+#define VP_HINGE_NOTIFICATION "com.vphone.motion.hinge.changed"
+
+// The foldable's hinge, degrees: 0 closed, 180 open flat. Apple's own
+// positions (suiatool, shipped in SpringBoardFoundation's help text and the
+// Duo simulator) are closed = 0, book = ~100, open = 180, and a change of
+// state is a sweep from the current angle to the target, not a jump.
+#define VP_HINGE_BOOK_ANGLE 100.0
+#define VP_HINGE_SWEEP_MS 10.03
+#define VP_HINGE_OPEN_DEFAULT_MS 600.0
+#define VP_HINGE_CLOSE_DEFAULT_MS 800.0
+
+typedef struct {
+ BOOL enabled;
+ BOOL sweep;
+ double angle;
+ double durationMs; // < 0: the per-direction default; 0: instant
+ int32_t profile; // 0 continuous, 1 fade
+} VPhoneHingeState;
+
+typedef enum {
+ VPhoneHingeProfileContinuous = 0,
+ VPhoneHingeProfileFade = 1,
+} VPhoneHingeProfile;
+
+// Reject malformed persisted state, booleans masquerading as angles, and
+// angles outside the hinge's range.
+static inline BOOL VPhoneHingeNumber(id value) {
+ return [value isKindOfClass:NSNumber.class] &&
+ CFGetTypeID((__bridge CFTypeRef)value) != CFBooleanGetTypeID();
+}
+
+static inline BOOL VPhoneHingeDecode(id value, VPhoneHingeState *state) {
+ *state = (VPhoneHingeState){0};
+ if (![value isKindOfClass:NSDictionary.class])
+ return NO;
+ id enabled = value[@"enabled"];
+ if (![enabled isKindOfClass:NSNumber.class] ||
+ CFGetTypeID((__bridge CFTypeRef)enabled) != CFBooleanGetTypeID())
+ return NO;
+ id angle = value[@"angle"];
+ if (!VPhoneHingeNumber(angle))
+ return NO;
+ double degrees = [angle doubleValue];
+ if (!isfinite(degrees) || degrees < 0 || degrees > 180)
+ return NO;
+ double duration = -1;
+ if (value[@"duration_ms"] != nil) {
+ if (!VPhoneHingeNumber(value[@"duration_ms"]))
+ return NO;
+ duration = [value[@"duration_ms"] doubleValue];
+ // -1 names the per-direction default; 0 is the instant swap.
+ if (!isfinite(duration) || duration < -1 || duration > 10000)
+ return NO;
+ }
+ int32_t profile = VPhoneHingeProfileContinuous;
+ if (value[@"profile"] != nil) {
+ if (!VPhoneHingeNumber(value[@"profile"]))
+ return NO;
+ profile = [value[@"profile"] intValue];
+ if (profile != VPhoneHingeProfileContinuous && profile != VPhoneHingeProfileFade)
+ return NO;
+ }
+ BOOL sweep = NO;
+ if (value[@"sweep"] != nil) {
+ id sweepValue = value[@"sweep"];
+ if (![sweepValue isKindOfClass:NSNumber.class] ||
+ CFGetTypeID((__bridge CFTypeRef)sweepValue) != CFBooleanGetTypeID())
+ return NO;
+ sweep = [sweepValue boolValue];
+ }
+ *state = (VPhoneHingeState){
+ [enabled boolValue], sweep, degrees, duration, profile,
+ };
+ return YES;
+}
+
+static inline NSDictionary *VPhoneHingeEncode(VPhoneHingeState state) {
+ return @{
+ @"enabled": @(state.enabled),
+ @"sweep": @(state.sweep),
+ @"angle": @(state.angle),
+ @"duration_ms": @(state.durationMs),
+ @"profile": @(state.profile),
+ };
+}
+
+// HID report interval, microseconds. Zero means there are no subscribers.
+static inline uint64_t VPhoneHingeInterval(id value) {
+ if (!VPhoneHingeNumber(value))
+ return 0;
+ double interval = [value doubleValue];
+ if (!isfinite(interval) || interval <= 0)
+ return 0;
+ return (uint64_t)fmin(1000000, fmax(5000, interval));
+}
diff --git a/VPhoneGuestComponents/Hinge/libvphonehinge.m b/VPhoneGuestComponents/Hinge/libvphonehinge.m
new file mode 100644
index 00000000..30204a5d
--- /dev/null
+++ b/VPhoneGuestComponents/Hinge/libvphonehinge.m
@@ -0,0 +1,384 @@
+#import "VPhoneHingeHID.h"
+#import "VPhoneHingeState.h"
+#include <dlfcn.h>
+#include <mach/mach_time.h>
+#include <notify.h>
+#include <objc/message.h>
+#include <unistd.h>
+
+// MARK: - HID provider in backboardd
+
+@interface VPhoneHingeProvider : NSObject
+@property (nonatomic, strong) dispatch_queue_t queue;
+@property (nonatomic, strong) dispatch_source_t timer;
+@property (nonatomic, strong) dispatch_source_t sweepTimer;
+@property (nonatomic, strong) dispatch_source_t heartbeat;
+@property (nonatomic, strong) id<VPhoneHingeHIDService> service;
+@property (nonatomic) VPhoneHingeEventFactory factory;
+@property (nonatomic, strong) NSMutableDictionary *properties;
+@property (nonatomic) VPhoneHingeState state;
+@property (nonatomic) double currentAngle;
+// The sweep in flight: from currentAngle to state.angle over its duration.
+@property (nonatomic) double sweepElapsed;
+@property (nonatomic) double sweepDuration;
+@property (nonatomic) double sweepStart;
+@property (nonatomic) BOOL enumerated;
+@property (nonatomic) BOOL cancelling;
+@property (nonatomic) uint64_t interval;
+@property (nonatomic) uint64_t dispatched;
+@property (nonatomic) uint64_t failures;
+@property (nonatomic) uint64_t sweeps;
+@property (nonatomic) int notificationToken;
+@property (nonatomic, copy) NSString *lastError;
+- (void)start;
+- (void)dispatchSample;
+- (void)dispatchAngle:(double)angle velocity:(double)velocity state:(int32_t)state phase:(int32_t)phase;
+@end
+
+@implementation VPhoneHingeProvider
+
+- (void)publishStatus {
+ NSDictionary *status = @{
+ @"enumerated": @(self.enumerated), @"service_id": @(self.service.serviceID),
+ @"pid": @(getpid()), @"updated_at": @([NSDate date].timeIntervalSince1970),
+ @"report_interval_us": @(self.interval), @"dispatched": @(self.dispatched),
+ @"dispatch_failures": @(self.failures), @"sweeps": @(self.sweeps),
+ @"sweeping": @(self.sweepTimer != nil), @"current_angle": @(self.currentAngle),
+ @"error": self.lastError ?: @"",
+ @"configuration": VPhoneHingeEncode(self.state),
+ };
+ CFPreferencesSetValue(CFSTR(VP_HINGE_STATUS), (__bridge CFDictionaryRef)status,
+ CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+ CFPreferencesSynchronize(CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+}
+
+- (void)readConfiguration {
+ CFPreferencesSynchronize(CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+ id value = CFBridgingRelease(CFPreferencesCopyValue(CFSTR(VP_HINGE_CONFIGURATION),
+ CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost));
+ VPhoneHingeState state;
+ if (VPhoneHingeDecode(value, &state)) {
+ self.state = state;
+ self.lastError = nil;
+ if (state.enabled && state.sweep) {
+ [self beginSweep];
+ } else {
+ [self endSweepTimer];
+ if (state.enabled)
+ self.currentAngle = state.angle;
+ // The stand-in's sample exists from the first request, before the
+ // HID service enumerates and on the rare tick it is down.
+ [self publishLatestAngle:self.currentAngle velocity:0
+ state:VPhoneHingeStateForAngle(self.currentAngle) phase:0];
+ if (self.enumerated)
+ [self dispatchSample];
+ }
+ } else {
+ self.lastError = @"Stored hinge angle is malformed; keeping the last one";
+ }
+ [self publishStatus];
+}
+
+- (void)updateTimer {
+ uint64_t period = self.enumerated && self.interval ? self.interval * NSEC_PER_USEC : DISPATCH_TIME_FOREVER;
+ dispatch_source_set_timer(self.timer, period == DISPATCH_TIME_FOREVER ? DISPATCH_TIME_FOREVER : DISPATCH_TIME_NOW,
+ period, NSEC_PER_MSEC);
+ // The status is republished every two seconds only while samples flow, as
+ // with the accelerometer: cfprefsd need not carry a rewrite for the
+ // guest's whole life, and vphoned judges the provider by its pid.
+ if (self.heartbeat) {
+ BOOL flowing = period != DISPATCH_TIME_FOREVER;
+ dispatch_source_set_timer(self.heartbeat,
+ flowing ? dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC) : DISPATCH_TIME_FOREVER,
+ 2 * NSEC_PER_SEC, 100 * NSEC_PER_MSEC);
+ }
+}
+
+// MARK: - Apple's sweep model
+//
+// A foldable's screen state is not a jump: suiatool (whose help text ships in
+// SpringBoardFoundation) and the Duo simulator's SBFHingeSamplePlayback both
+// move the hinge from its current angle to a target over a profiled sweep on
+// CoreMotion's 10.03 ms grid, reporting angle, velocity and hinge state on
+// every sample. Opening is faster than closing; duration 0 is an instant
+// swap. These methods reproduce that model with a synthetic ease, so no
+// Apple-recorded sample data is shipped.
+
+/// The hinge state (CoreMotion's 0–4 magic-pose hinge values) an angle in
+/// motion or at rest reports.
+static int32_t VPhoneHingeStateForAngle(double angle) {
+ if (angle < 5.0)
+ return 1; // closed
+ if (angle >= 170.0)
+ return 3; // open flat
+ return 2; // partially open, the state a sweep holds throughout
+}
+
+/// Continuous fold: a smoothstep, close to a hand fold's constant feel.
+/// Fade: a cosine ease with a dwell at each end, the crossfade feel the
+/// fade-in-out profile names.
+static double VPhoneHingeProgress(double t, int32_t profile) {
+ if (profile == VPhoneHingeProfileFade) {
+ if (t < 0.1)
+ return 0;
+ if (t > 0.9)
+ return 1;
+ return (1 - cos(M_PI * (t - 0.1) / 0.8)) / 2;
+ }
+ return t * t * (3 - 2 * t);
+}
+
+- (void)endSweepTimer {
+ if (self.sweepTimer) {
+ dispatch_source_cancel(self.sweepTimer);
+ self.sweepTimer = nil;
+ }
+}
+
+- (void)beginSweep {
+ [self endSweepTimer];
+ double target = self.state.angle;
+ double duration = self.state.durationMs;
+ if (duration < 0)
+ duration = target > self.currentAngle ? VP_HINGE_OPEN_DEFAULT_MS : VP_HINGE_CLOSE_DEFAULT_MS;
+ // An instant swap (the "yoinking path") and a no-op target are one sample.
+ if (duration < VP_HINGE_SWEEP_MS || fabs(target - self.currentAngle) < 0.5) {
+ double previous = self.currentAngle;
+ self.currentAngle = target;
+ self.sweeps++;
+ [self dispatchAngle:target
+ velocity:duration > 0 ? (target - previous) / (duration / 1000.0) : 0
+ state:VPhoneHingeStateForAngle(target)
+ phase:3];
+ [self publishStatus];
+ return;
+ }
+ self.sweepStart = self.currentAngle;
+ self.sweepElapsed = 0;
+ self.sweepDuration = duration;
+ self.sweeps++;
+ self.sweepTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue);
+ dispatch_source_set_timer(self.sweepTimer, DISPATCH_TIME_NOW,
+ (uint64_t)(VP_HINGE_SWEEP_MS * NSEC_PER_MSEC), (uint64_t)(1 * NSEC_PER_MSEC));
+ __weak VPhoneHingeProvider *weakSelf = self;
+ dispatch_source_set_event_handler(self.sweepTimer, ^{
+ @autoreleasepool {
+ VPhoneHingeProvider *provider = weakSelf;
+ if (!provider)
+ return;
+ provider.sweepElapsed += VP_HINGE_SWEEP_MS;
+ double t = provider.sweepElapsed / provider.sweepDuration;
+ if (t >= 1.0) {
+ double previous = provider.currentAngle;
+ provider.currentAngle = provider.state.angle;
+ [provider endSweepTimer];
+ [provider dispatchAngle:provider.currentAngle
+ velocity:(provider.currentAngle - previous) / (VP_HINGE_SWEEP_MS / 1000.0)
+ state:VPhoneHingeStateForAngle(provider.currentAngle)
+ phase:3];
+ [provider publishStatus];
+ return;
+ }
+ double progress = VPhoneHingeProgress(t, provider.state.profile);
+ double angle = provider.sweepStart + (provider.state.angle - provider.sweepStart) * progress;
+ double previousAngle = provider.currentAngle;
+ provider.currentAngle = angle;
+ [provider dispatchAngle:angle
+ velocity:(angle - previousAngle) / (VP_HINGE_SWEEP_MS / 1000.0)
+ state:VPhoneHingeStateForAngle(angle)
+ phase:provider.sweepElapsed == VP_HINGE_SWEEP_MS ? 1 : 2];
+ }
+ });
+ dispatch_resume(self.sweepTimer);
+}
+
+- (void)publishLatestAngle:(double)angle velocity:(double)velocity state:(int32_t)state phase:(int32_t)phase {
+ // The same sample for the CoreMotion stand-in in dtdeviceinfod, which
+ // reads this instead of driving CoreMotion's own machinery. Phase 0 is a
+ // stationary report, 1 the first tick of a sweep, 2 the ticks between,
+ // 3 the last.
+ NSDictionary *latest = @{
+ @"angle": @(angle),
+ @"mechanical_angle": @(angle),
+ @"velocity": @(velocity),
+ @"state": @(state),
+ @"event_phase": @(phase),
+ @"timestamp": @([NSDate date].timeIntervalSince1970),
+ };
+ CFPreferencesSetValue(CFSTR(VP_HINGE_LATEST), (__bridge CFDictionaryRef)latest,
+ CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+}
+
+- (void)dispatchAngle:(double)angle velocity:(double)velocity state:(int32_t)state phase:(int32_t)phase {
+ // The factory's angle and mechanical angle both take the fold angle: no
+ // mechanical detent distinguishes them on a virtual hinge. The state
+ // field carries the hinge state, as Apple's recorded samples do.
+ id event = (__bridge id)self.factory(NULL, mach_absolute_time(), angle, angle, velocity, 0);
+ if (event && [event respondsToSelector:NSSelectorFromString(@"setHingeAngleState:")])
+ ((void (*)(id, SEL, int32_t))objc_msgSend)(event, sel_registerName("setHingeAngleState:"), state);
+ if (event && [self.service dispatchEvent:event]) {
+ self.dispatched++;
+ self.lastError = nil;
+ } else {
+ self.failures++;
+ self.lastError = @"HID event dispatch failed";
+ }
+ [self publishLatestAngle:angle velocity:velocity state:state phase:phase];
+}
+
+- (id)sample {
+ id event = (__bridge id)self.factory(NULL, mach_absolute_time(), self.currentAngle,
+ self.currentAngle, 0, 0);
+ if (event && [event respondsToSelector:NSSelectorFromString(@"setHingeAngleState:")])
+ ((void (*)(id, SEL, int32_t))objc_msgSend)(
+ event, sel_registerName("setHingeAngleState:"),
+ VPhoneHingeStateForAngle(self.currentAngle));
+ return event;
+}
+
+- (void)createService {
+ self.enumerated = NO;
+ self.cancelling = NO;
+ self.interval = 0;
+ self.properties[@"ReportInterval"] = @0;
+ self.service = (id<VPhoneHingeHIDService>)[NSClassFromString(@"HIDVirtualEventService") new];
+ if (!self.service) {
+ self.lastError = @"HIDVirtualEventService creation failed";
+ [self publishStatus];
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), self.queue, ^{ [self createService]; });
+ return;
+ }
+ self.service.delegate = self;
+ [self.service setDispatchQueue:self.queue];
+ __weak VPhoneHingeProvider *weakSelf = self;
+ [self.service setCancelHandler:^{
+ VPhoneHingeProvider *provider = weakSelf;
+ if (!provider)
+ return;
+ provider.service = nil;
+ // A reset invalidates the old service. Cancel completely before
+ // releasing it, then register a new one with the restarted HID server.
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), provider.queue,
+ ^{ [provider createService]; });
+ }];
+ [self.service activate];
+}
+
+- (void)dispatchSample {
+ // A stationary report: the angle the last sweep or request left, no
+ // motion, phase 0. Same path as a sweep tick so the latest sample the
+ // CoreMotion stand-in reads is written here too.
+ [self dispatchAngle:self.currentAngle
+ velocity:0
+ state:VPhoneHingeStateForAngle(self.currentAngle)
+ phase:0];
+}
+
+- (void)start {
+ void *hid = dlopen("/System/Library/PrivateFrameworks/HID.framework/HID", RTLD_NOW | RTLD_LOCAL);
+ self.factory = (VPhoneHingeEventFactory)dlsym(hid, "IOHIDEventCreateHingeAngleEvent");
+ Class serviceClass = NSClassFromString(@"HIDVirtualEventService");
+ if (!hid || !self.factory || !serviceClass ||
+ ![serviceClass instancesRespondToSelector:@selector(dispatchEvent:)]) {
+ self.lastError = @"Required HID virtual-service API unavailable";
+ NSLog(@"[vphone-hinge] %@", self.lastError);
+ [self publishStatus];
+ return;
+ }
+ // CoreMotion's CLAngleNotifier subscribes to this virtual service: usage
+ // page 0xFF0C (Apple vendor), usage 0x21 (hinge angle). The capability is
+ // only selected on a product-id CoreMotion knows — the foldable product
+ // identity patch — so on any other guest the service sits unread.
+ self.properties = [@{
+ @"PrimaryUsagePage": @0xff0c, @"PrimaryUsage": @0x21,
+ @"DeviceUsagePairs": @[@{@"DeviceUsagePage": @0xff0c, @"DeviceUsage": @0x21}],
+ @"Product": @"VPhone Hinge Angle Sensor", @"Manufacturer": @"vphone",
+ @"Transport": @"Virtual", @"Built-In": @YES,
+ @"ReportInterval": @0, @"BatchInterval": @0,
+ // Aggregate subscriptions before forwarding the requested interval to
+ // this delegate, so one client's stop cannot stop other subscribers.
+ @"HIDDefaultSensorControlOptions": @7, @"SensorPropertySupported": @3,
+ } mutableCopy];
+ [self readConfiguration];
+ int status = notify_register_dispatch(VP_HINGE_NOTIFICATION, &_notificationToken, self.queue,
+ ^(int token) { [self readConfiguration]; });
+ if (status != NOTIFY_STATUS_OK) {
+ self.lastError = @"Hinge configuration notification registration failed";
+ [self publishStatus];
+ return;
+ }
+ self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue);
+ dispatch_source_set_event_handler(self.timer, ^{
+ @autoreleasepool {
+ [self dispatchSample];
+ }
+ });
+ self.heartbeat = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue);
+ dispatch_source_set_event_handler(self.heartbeat, ^{ [self publishStatus]; });
+ [self updateTimer];
+ dispatch_resume(self.timer);
+ dispatch_resume(self.heartbeat);
+ [self createService];
+}
+
+// MARK: - HIDVirtualEventServiceDelegate selectors
+
+- (id)propertyForKey:(NSString *)key forService:(id)service {
+ return self.properties[key];
+}
+
+- (BOOL)setProperty:(id)value forKey:(NSString *)key forService:(id)service {
+ if (service != self.service)
+ return NO;
+ if ([key isEqualToString:@"ReportInterval"]) {
+ self.interval = VPhoneHingeInterval(value);
+ self.properties[key] = @(self.interval);
+ [self updateTimer];
+ [self publishStatus];
+ return YES;
+ }
+ if ([key isEqualToString:@"BatchInterval"])
+ return YES; // No FIFO: samples are delivered as they are made.
+ return NO;
+}
+
+- (id)copyEventMatching:(NSDictionary *)matching forService:(id)service {
+ NSNumber *type = matching[@"EventType"];
+ // 0x2c is the hinge-angle event type CLAngleNotifier asks for.
+ return service == self.service && self.enumerated && (!type || type.unsignedIntValue == 0x2c) ? [self sample] : nil;
+}
+
+- (BOOL)setOutputEvent:(id)event forService:(id)service {
+ return NO;
+}
+
+- (void)notification:(NSInteger)type withProperty:(NSDictionary *)property forService:(id)service {
+ if (service != self.service)
+ return;
+ if (type == 10) { // HIDVirtualServiceNotificationTypeEnumerated
+ self.enumerated = YES;
+ self.lastError = nil;
+ NSLog(@"[vphone-hinge] HID service enumerated: %llu", self.service.serviceID);
+ [self dispatchSample];
+ } else if (type == 11 && !self.cancelling) { // Terminated or reset
+ self.enumerated = NO;
+ self.cancelling = YES;
+ self.lastError = @"HID service terminated; waiting to register again";
+ [self.service cancel];
+ }
+ [self updateTimer];
+ [self publishStatus];
+}
+@end
+
+__attribute__((constructor)) static void VPhoneHingeStart(void) {
+ // Only backboardd creates the HID service. Starting asynchronously avoids
+ // calling the HID server while its daemon is still running image
+ // constructors.
+ if (strcmp(getprogname(), "backboardd") != 0)
+ return;
+ static VPhoneHingeProvider *provider;
+ provider = [VPhoneHingeProvider new];
+ provider.queue = dispatch_queue_create("com.vphone.motion.hinge", DISPATCH_QUEUE_SERIAL);
+ dispatch_async(provider.queue, ^{ [provider start]; });
+}
diff --git a/VPhoneGuestComponents/MISFix/MISFixConditionalBranch.h b/VPhoneGuestComponents/MISFix/MISFixConditionalBranch.h
new file mode 100644
index 00000000..58f380c8
--- /dev/null
+++ b/VPhoneGuestComponents/MISFix/MISFixConditionalBranch.h
@@ -0,0 +1,23 @@
+#ifndef MISFIX_CONDITIONAL_BRANCH_H
+#define MISFIX_CONDITIONAL_BRANCH_H
+#include <stdint.h>
+#include <string.h>
+
+// B.cond -> inverted condition over an absolute branch. Only ordinary
+// conditions0...13 and destinations outside the overwritten region qualify.
+// NZCV is preserved. Like the existing absolute branch, the taken path uses
+// ABI scratch register x16. BC.cond and AL/NV remain unsupported.
+static unsigned vpRelocateConditionalBranch(uint32_t insn, uint64_t pc,
+ uint64_t overwrittenStart, uint64_t overwrittenEnd, uint32_t *out) {
+ if ((insn & 0xFF000010u) != 0x54000000u || (insn & 15u) >= 14u) return 0;
+ int64_t immediate = (insn >> 5) & 0x7FFFFu;
+ if (immediate & 0x40000) immediate -= 0x80000;
+ uint64_t destination = pc + immediate * 4;
+ if (destination >= overwrittenStart && destination < overwrittenEnd) return 0;
+ out[0] = 0x54000000u | (5u << 5) | ((insn & 15u) ^ 1u);
+ out[1] = 0x58000050u; // ldr x16, #8
+ out[2] = 0xD61F0200u; // br x16
+ memcpy(out + 3, &destination, sizeof(destination));
+ return 5;
+}
+#endif
diff --git a/VPhoneGuestComponents/MISFix/MISFixDetour.c b/VPhoneGuestComponents/MISFix/MISFixDetour.c
index 1c1c88cf..a1adc7e6 100644
--- a/VPhoneGuestComponents/MISFix/MISFixDetour.c
+++ b/VPhoneGuestComponents/MISFix/MISFixDetour.c
@@ -20,6 +20,7 @@
// ±4GB of each other.
#include "MISFixDetour.h"
+#include "MISFixConditionalBranch.h"
#include "MISFixConfig.h"
@@ -36,7 +37,7 @@
#define kDetourBytes (kDetourWords * 4u)
/// Room for one trampoline: four displaced instructions, each of which may
-/// expand to four words when it has to be rewritten, plus the four-word jump
+/// expand to five words when it has to be rewritten, plus the four-word jump
/// back.
#define kTrampolineBytes 128u
@@ -121,7 +122,7 @@ static unsigned vpRelocate(uint32_t insn, uint64_t pc, uint32_t *out) {
// (0x18000000). A prologue normally contains none of them; when one turns
// up, the log says so and nothing is written.
if ((insn & 0xFC000000u) == 0x94000000u // BL
- || (insn & 0xFF000010u) == 0x54000000u // B.cond
+ || (insn & 0xFF000000u) == 0x54000000u // B.cond/BC.cond (ordinary B.cond handled by caller)
|| (insn & 0x7E000000u) == 0x34000000u // CBZ/CBNZ/TBZ/TBNZ
|| (insn & 0x3B000000u) == 0x18000000u) // LDR/LDRSW literal, PRFM literal
{
@@ -196,11 +197,11 @@ MISFixDetourResult MISFixDetour(
for (unsigned index = 0; index < kDetourWords; index += 1) {
if (index + 1 < kDetourWords && vpIsTerminator(displaced[index]))
return MISFixDetourTooShort;
- unsigned written = vpRelocate(
- displaced[index],
- (uint64_t)(uintptr_t)target + index * 4u,
- body + words
- );
+ uint64_t start = (uint64_t)(uintptr_t)target;
+ uint64_t pc = start + index * 4u;
+ unsigned written = (displaced[index] & 0xFF000010u) == 0x54000000u
+ ? vpRelocateConditionalBranch(displaced[index], pc, start, start + kDetourBytes, body + words)
+ : vpRelocate(displaced[index], pc, body + words);
if (written == 0)
return MISFixDetourUnrelocatable;
words += written;
diff --git a/VPhoneGuestComponents/MISFix/MISFixDetour.h b/VPhoneGuestComponents/MISFix/MISFixDetour.h
index 5e557f61..f9d34b69 100644
--- a/VPhoneGuestComponents/MISFix/MISFixDetour.h
+++ b/VPhoneGuestComponents/MISFix/MISFixDetour.h
@@ -22,8 +22,10 @@
// - The displaced instructions must survive being moved. `adr` and `adrp`
// are rewritten to materialise the same absolute address, and an
// unconditional `b` becomes an absolute jump. Anything else PC-relative —
-// `bl`, `b.cond`, `cbz`, `tbz`, a literal load — is **refused**, because a
+// `bl`, `cbz`, `tbz`, a literal load — is **refused**, because a
// wrong relocation is a corrupted daemon and a refusal is a log line.
+// Ordinary B.cond is supported only to destinations outside the four
+// overwritten words, by inverting the condition around an absolute jump.
// - The target must be at least four instructions long. A function that
// returns or jumps away sooner is *shorter* than the patch, so writing it
// would scribble on whoever follows. A terminator in the first three words
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index 3024c545..4a9745aa 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -62,9 +62,11 @@ BATTERYHEALTHFIX_INCLUDES := $(wildcard BatteryHealthFix/*.h)
# CoreDeviceUtilities lives on the developer disk image, not in the SDK, and
# the image is mounted only after the host enables developer services. The two
# interposed Swift getters are weak flat-namespace imports. CoreVideo, IOSurface
-# and libobjc are for the avconferenced band reads it waits on the scaler for.
+# and libobjc are for the avconferenced band reads it waits on the scaler for;
+# Foundation and the ObjC runtime are for the CMAngleManager stand-in
+# (VPCMAngleManager.m) dtdeviceinfod answers the hinge stream from.
DEVICEHUBFIX := $(STAGE)/devicehubfix/libdevicehubfix.dylib
-DEVICEHUBFIX_SOURCES := $(wildcard DeviceHubFix/*.c)
+DEVICEHUBFIX_SOURCES := $(sort $(wildcard DeviceHubFix/*.c) $(wildcard DeviceHubFix/*.m))
DEVICEHUBFIX_INCLUDES := $(wildcard DeviceHubFix/*.h)
DEVICEHUBFIX_DYNAMIC_LOOKUP_SYMS := \
'-Wl,-U,_$$s19CoreDeviceUtilities28MediaStreamSupportedFeaturesV7currentACvgZ' \
@@ -92,6 +94,20 @@ GYROSCOPE_INPUTS := $(call find_headers,Gyroscope) $(call find_folders,Gyroscope
ACCELEROMETER := $(STAGE)/accelerometer/libvphoneaccelerometer.dylib
ACCELEROMETER_SOURCES := $(call find_sources,Accelerometer)
ACCELEROMETER_INPUTS := $(call find_headers,Accelerometer) $(call find_folders,Accelerometer)
+HINGE := $(STAGE)/hinge/libvphonehinge.dylib
+HINGE_SOURCES := $(call find_sources,Hinge)
+HINGE_INPUTS := $(call find_headers,Hinge) $(call find_folders,Hinge)
+# The SpringBoard guard that lets the foldable product identity survive on a
+# single-display guest. See FoldGuard/libvphonefoldguard.m.
+FOLDGUARD := $(STAGE)/foldguard/libvphonefoldguard.dylib
+FOLDGUARD_SOURCES := $(call find_sources,FoldGuard)
+FOLDGUARD_INPUTS := $(call find_headers,FoldGuard) $(call find_folders,FoldGuard)
+FOLDDISPLAY := $(STAGE)/folddisplay/libvphonefolddisplay.dylib
+FOLDDISPLAY_SOURCES := $(call find_sources,FoldDisplay)
+FOLDDISPLAY_INPUTS := $(call find_headers,FoldDisplay) $(call find_folders,FoldDisplay) MISFix/MISFixDetour.h
+POSTERPROBE := $(STAGE)/posterprobe/libvphoneposterprobe.dylib
+POSTERPROBE_SOURCES := $(call find_sources,PosterProbe)
+POSTERPROBE_INPUTS := $(call find_headers,PosterProbe) $(call find_folders,PosterProbe)
ATTITUDE := $(STAGE)/attitude/libvphoneattitude.dylib
ATTITUDE_SOURCES := $(call find_sources,Attitude)
ATTITUDE_INPUTS := $(call find_headers,Attitude) $(call find_folders,Attitude) Shared/AttitudeProcess.h
@@ -104,7 +120,7 @@ HOMEPODPERSONA := $(STAGE)/homepodpersona/libvphoneinstallpersona.dylib
HOMEPODPERSONA_INPUTS := HomePodInstallPersona/libvphoneinstallpersona.c LaunchHook/InstallCoordinationPersona.h
HOMEPODMISFIX := $(STAGE)/homepodmisfix/libvphonehomepodmisfix.dylib
HOMEPODMISFIX_SOURCES := MISFix/MISFixSignature.c MISFix/MISFixDetour.c MISFix/MISFixConfig.c MISFix/MISFixInstallPolicy.c
-HOMEPODMISFIX_INPUTS := $(HOMEPODMISFIX_SOURCES) MISFix/MISFixDetour.h MISFix/MISFixConfig.h
+HOMEPODMISFIX_INPUTS := $(HOMEPODMISFIX_SOURCES) MISFix/MISFixDetour.h MISFix/MISFixConditionalBranch.h MISFix/MISFixConfig.h
HOMEPODSETUP := $(STAGE)/homepodsetup/vphone-homepod-setup
HOMEPODSETUP_SOURCES := $(call find_sources,HomePodSetup)
HOMEPODSETUP_INPUTS := $(call find_headers,HomePodSetup) HomePodSetup/com.vphone.homepod-setup.plist
@@ -141,7 +157,7 @@ GPU_DYNAMIC_LOOKUP_SYMS := \
VIRTIOSOUND := $(STAGE)/virtiosound/VPhoneVirtIOSound.driver
VIRTIOSOUND_SOURCES := $(wildcard VirtIOSound/*.m VirtIOSound/*.c)
VIRTIOSOUND_INCLUDES := $(wildcard VirtIOSound/*.h) VirtIOSound/Info.plist VirtIOSound/AudioServerDriver.tbd
-ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(DEVICENAME) $(PREFSFIX) $(SIGNINFIX) $(GYROSCOPE) $(ACCELEROMETER) $(ATTITUDE) $(HOMEPODDISPLAY) $(CRYPTEXSTAGING) $(HOMEPODPERSONA) $(HOMEPODMISFIX) $(HOMEPODSETUP) $(GPU_PLUGIN) $(VIRTIOSOUND)
+ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(DEVICENAME) $(PREFSFIX) $(SIGNINFIX) $(GYROSCOPE) $(ACCELEROMETER) $(HINGE) $(FOLDGUARD) $(FOLDDISPLAY) $(POSTERPROBE) $(ATTITUDE) $(HOMEPODDISPLAY) $(CRYPTEXSTAGING) $(HOMEPODPERSONA) $(HOMEPODMISFIX) $(HOMEPODSETUP) $(GPU_PLUGIN) $(VIRTIOSOUND)
PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist \
$(STAGE)/misfix/libmisfix.plist
GPU_PROVENANCE := $(STAGE)/gpu/README.md
@@ -187,7 +203,7 @@ gpu: $(GPU_PLUGIN)
package: all
@rm -f $(ARCHIVE)
- @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix devicename prefsfix signinfix gyroscope accelerometer attitude homepoddisplay cryptexstaging homepodpersona homepodmisfix homepodsetup gpu virtiosound
+ @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix devicename prefsfix signinfix gyroscope accelerometer hinge foldguard attitude homepoddisplay cryptexstaging homepodpersona homepodmisfix homepodsetup gpu virtiosound folddisplay
@echo "Packaged $(ARCHIVE)"
test-loader-links:
@@ -253,7 +269,7 @@ test-vcam-dataplane:
-framework CoreGraphics
@$(OUT)/VCamDataPlaneTests
-$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/misfix $(STAGE)/hapticsfix $(STAGE)/batteryhealthfix $(STAGE)/devicehubfix $(STAGE)/devicename $(STAGE)/prefsfix $(STAGE)/signinfix $(STAGE)/gyroscope $(STAGE)/accelerometer $(STAGE)/attitude $(STAGE)/gpu $(STAGE)/virtiosound:
+$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/misfix $(STAGE)/hapticsfix $(STAGE)/batteryhealthfix $(STAGE)/devicehubfix $(STAGE)/devicename $(STAGE)/prefsfix $(STAGE)/signinfix $(STAGE)/gyroscope $(STAGE)/accelerometer $(STAGE)/hinge $(STAGE)/foldguard $(STAGE)/folddisplay $(STAGE)/posterprobe $(STAGE)/attitude $(STAGE)/gpu $(STAGE)/virtiosound:
@mkdir -p $@
$(CAMFIX): $(CAMFIX_SOURCES) $(CAMFIX_INPUTS) | $(STAGE)/camfix
@@ -321,10 +337,10 @@ $(BATTERYHEALTHFIX): $(BATTERYHEALTHFIX_SOURCES) $(BATTERYHEALTHFIX_INCLUDES) Ba
@codesign --force --sign - $@
$(DEVICEHUBFIX): $(DEVICEHUBFIX_SOURCES) $(DEVICEHUBFIX_INCLUDES) DeviceHubFix | $(STAGE)/devicehubfix
- $(CLANG) $(GUEST_C_FLAGS) -dynamiclib \
+ $(CLANG) $(COMMON_FLAGS) -dynamiclib \
-install_name /usr/lib/libdevicehubfix.dylib \
-o $@ $(DEVICEHUBFIX_SOURCES) $(DEVICEHUBFIX_DYNAMIC_LOOKUP_SYMS) \
- -framework CoreFoundation -framework CoreVideo -framework IOSurface -lMobileGestalt -lobjc \
+ -framework Foundation -framework CoreVideo -framework IOSurface -lMobileGestalt \
-Wl,-not_for_dyld_shared_cache
@codesign --force --sign - $@
@@ -366,13 +382,47 @@ $(ACCELEROMETER): $(ACCELEROMETER_SOURCES) $(ACCELEROMETER_INPUTS) | $(STAGE)/ac
-framework Foundation -Wl,-not_for_dyld_shared_cache
@codesign --force --sign - $@
-.PHONY: test-gyroscope test-accelerometer
+$(HINGE): $(HINGE_SOURCES) $(HINGE_INPUTS) | $(STAGE)/hinge
+ $(CLANG) -arch arm64e -miphoneos-version-min=18.0 -Os -fobjc-arc \
+ -Wall -Wextra -Werror -Wno-unused-parameter -dynamiclib \
+ -install_name /usr/lib/libvphonehinge.dylib -o $@ $(HINGE_SOURCES) \
+ -framework Foundation -Wl,-not_for_dyld_shared_cache
+ @codesign --force --sign - $@
+
+$(FOLDGUARD): $(FOLDGUARD_SOURCES) $(FOLDGUARD_INPUTS) | $(STAGE)/foldguard
+ $(CLANG) $(COMMON_FLAGS) -Wall -Wextra -Werror -Wno-unused-parameter -dynamiclib \
+ -install_name /usr/lib/libvphonefoldguard.dylib -o $@ $(FOLDGUARD_SOURCES) \
+ -framework Foundation -Wl,-not_for_dyld_shared_cache
+ @codesign --force --sign - $@
+
+$(FOLDDISPLAY): $(FOLDDISPLAY_SOURCES) $(FOLDDISPLAY_INPUTS) | $(STAGE)/folddisplay
+ $(CLANG) $(COMMON_FLAGS) -Wall -Wextra -Werror -Wno-unused-parameter -dynamiclib \
+ -install_name /usr/lib/libvphonefolddisplay.dylib -o $@ $(FOLDDISPLAY_SOURCES) \
+ -framework Foundation -framework CoreGraphics -Wl,-not_for_dyld_shared_cache
+ @codesign --force --sign - $@
+
+$(POSTERPROBE): $(POSTERPROBE_SOURCES) $(POSTERPROBE_INPUTS) | $(STAGE)/posterprobe
+ $(CLANG) $(COMMON_FLAGS) -fobjc-arc -dynamiclib \
+ -install_name /usr/lib/libvphoneposterprobe.dylib -o $@ $(POSTERPROBE_SOURCES) \
+ -framework Foundation -framework UIKit -Wl,-not_for_dyld_shared_cache
+ @codesign --force --sign - $@
+
+.PHONY: test-gyroscope test-accelerometer test-hinge
test-accelerometer:
@mkdir -p $(OUT)
xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -Wno-unused-parameter -IAccelerometer \
-o $(OUT)/AccelerometerTests Tests/AccelerometerTests.m Accelerometer/VPhoneOrientationSink.m -framework Foundation
@$(OUT)/AccelerometerTests
+# The hinge's transport and, on a Mac with Apple's HID.framework, a real
+# IOHIDEventCreateHingeAngleEvent call whose fields read back from the event's
+# own description.
+test-hinge:
+ @mkdir -p $(OUT)
+ xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -IHinge \
+ -o $(OUT)/HingeTests Tests/HingeTests.m -framework Foundation
+ @$(OUT)/HingeTests
+
$(ATTITUDE): $(ATTITUDE_SOURCES) $(ATTITUDE_INPUTS) | $(STAGE)/attitude
$(CLANG) -arch arm64e -miphoneos-version-min=18.0 -Os -fobjc-arc \
-Wall -Wextra -Werror -Wno-unused-parameter -dynamiclib \
diff --git a/VPhoneGuestComponents/PosterProbe/libvphoneposterprobe.m b/VPhoneGuestComponents/PosterProbe/libvphoneposterprobe.m
new file mode 100644
index 00000000..b3414a91
--- /dev/null
+++ b/VPhoneGuestComponents/PosterProbe/libvphoneposterprobe.m
@@ -0,0 +1,34 @@
+#import <Foundation/Foundation.h>
+#import <UIKit/UIKit.h>
+
+static void vpPosterProbe(void) {
+ @autoreleasepool {
+ @try {
+ UIApplication *app = [UIApplication sharedApplication];
+ NSMutableArray *rows = [NSMutableArray array];
+ for (UIScene *scene in app.connectedScenes.allObjects ?: @[]) {
+ UIScreen *screen = nil;
+ @try { screen = [scene valueForKey:@"screen"]; } @catch (__unused NSException *e) {}
+ if (!screen) screen = UIScreen.mainScreen;
+ NSMutableDictionary *row = [@{
+ @"class": NSStringFromClass(scene.class) ?: @"",
+ @"activation": @(scene.activationState),
+ @"bounds": NSStringFromCGRect(screen.bounds),
+ @"scale": @(screen.scale),
+ } mutableCopy];
+ @try { id settings = [scene valueForKey:@"settings"]; if (settings) row[@"settings"] = [settings description] ?: @""; } @catch (__unused NSException *e) {}
+ @try { id mode = [screen valueForKey:@"_displayMode"]; if (mode) row[@"display_mode"] = [mode description] ?: @""; } @catch (__unused NSException *e) {}
+ [rows addObject:row];
+ }
+ NSDictionary *payload = @{@"pid": @(getpid()), @"process": NSProcessInfo.processInfo.processName ?: @"", @"scenes": rows, @"uptime": @(NSProcessInfo.processInfo.systemUptime)};
+ NSData *data = [NSJSONSerialization dataWithJSONObject:payload options:0 error:NULL];
+ if (data.length > 65536) return;
+ NSString *path = @"/var/mobile/Library/Logs/vphone-poster-inspect.log";
+ if (![[NSFileManager defaultManager] fileExistsAtPath:path]) [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
+ NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];
+ [handle seekToEndOfFile]; [handle writeData:[[NSString stringWithFormat:@"%@\n", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]] dataUsingEncoding:NSUTF8StringEncoding]]; [handle closeFile];
+ } @catch (__unused NSException *exception) {}
+ }
+}
+
+__attribute__((constructor)) static void vpPosterProbeInit(void) { dispatch_async(dispatch_get_main_queue(), ^{ vpPosterProbe(); }); }
diff --git a/VPhoneGuestComponents/README.md b/VPhoneGuestComponents/README.md
index ee9c7744..2acf3ead 100644
--- a/VPhoneGuestComponents/README.md
+++ b/VPhoneGuestComponents/README.md
@@ -14,6 +14,7 @@ tweak filter plists, and the GPU provenance note:
| Device name pin | `devicename/libdevicename.dylib` |
| Virtual gyroscope | `gyroscope/libvphonegyro.dylib` |
| Gravity accelerometer | `accelerometer/libvphoneaccelerometer.dylib` |
+| Virtual hinge angle | `hinge/libvphonehinge.dylib` |
| Device attitude | `attitude/libvphoneattitude.dylib` |
| HomePod display identity | `homepoddisplay/libvphonehomepoddisplay.dylib` |
| HomePod setup maintenance | `homepodsetup/vphone-homepod-setup`, `homepodsetup/com.vphone.homepod-setup.plist` |
@@ -84,6 +85,19 @@ subscription changes and stale service callbacks without registering a host
sensor. See `Research/Guest/springboard_orientation_stuck.md` for evidence and
the language-change regression boundary.
+`system-backboardd-cfw-hinge` installs `libvphonehinge.dylib`, also selected
+independently and loaded only in backboardd. It publishes the foldable's
+virtual hinge HID service (usage page 0xFF0C, usage 0x21) and reports the
+angle configured by `display.posture`, using HID.framework's C factory
+`IOHIDEventCreateHingeAngleEvent` — the only hinge entry point; HIDEvent
+exposes just `-hingeAngle*` accessors. CoreMotion's angle manager, and through
+it CoreDevice's hingeAngle stream, reads it; CoreMotion only looks when the
+device tree carries the foldable board's own product-id
+(`preboot-cfw-devicetree_foldable_product_id`), so on any other guest the
+service sits unread. Foldable guests only; `make test-hinge` checks the
+configuration transport and, on a Mac with Apple's HID.framework, a real
+factory call whose fields read back from the event's own description.
+
`system-apps-cfw-attitude` installs `libvphoneattitude.dylib`, loaded by
SystemHook into apps. It supplies a stationary Core Motion pose through
`motion.attitude.set/get/clear`, independently of gyro angular velocity.
diff --git a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
index c32e5812..90641e2c 100644
--- a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
+++ b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
@@ -163,6 +163,14 @@ static int vpExecve(const char *path, char *const argv[], char *const envp[]) {
#define VP_CAMERA_APP_HOOK "/usr/lib/libcamfix.dylib"
#define VP_GYROSCOPE_HOOK "/usr/lib/libvphonegyro.dylib"
#define VP_ACCELEROMETER_HOOK "/usr/lib/libvphoneaccelerometer.dylib"
+#define VP_HINGE_HOOK "/usr/lib/libvphonehinge.dylib"
+#define VP_FOLD_GUARD "/usr/lib/libvphonefoldguard.dylib"
+// Pads SpringBoard's answer to +[FBDisplayManager alwaysConnectedIdentities]
+// with a copy of the one real identity, so the fold layouts' two-display
+// count gates pass on the single-panel guest. See
+// FoldDisplay/libvphonefolddisplay.m.
+#define VP_FOLD_DISPLAY "/usr/lib/libvphonefolddisplay.dylib"
+#define VP_POSTER_PROBE "/usr/lib/libvphoneposterprobe.dylib"
#define VP_ATTITUDE_HOOK "/usr/lib/libvphoneattitude.dylib"
#define VP_AVFOUNDATION "/System/Library/Frameworks/AVFoundation.framework/AVFoundation"
// The haptics fix rides the same route and needs no loader of its own. See
@@ -187,6 +195,10 @@ static int vpIsSpringBoard(const char *path) {
return vpPathHasSuffix(path, "/SpringBoard.app/SpringBoard");
}
+static int vpIsPosterExtension(const char *path) {
+ return path && (strcasestr(path, "PosterBoard") != NULL || strcasestr(path, "poster") != NULL);
+}
+
// Settings. Suffix-matched like the other targets.
static int vpIsPreferences(const char *path) {
return vpPathHasSuffix(path, "/Preferences.app/Preferences");
@@ -257,6 +269,9 @@ __attribute__((constructor)) static void vpLogProcess(void) {
if (vpIsMotionDaemon(path)) {
vpLoadLibrary("gyroscope-hook", VP_GYROSCOPE_HOOK);
vpLoadLibrary("accelerometer-hook", VP_ACCELEROMETER_HOOK);
+ vpLoadLibrary("hinge-hook", VP_HINGE_HOOK);
+ // Experimental: see the patch declaration before turning it on.
+ vpLoadLibrary("fold-display", VP_FOLD_DISPLAY);
return;
}
// SpringBoard needs the haptics swizzle before UIKit first asks for an
@@ -264,7 +279,14 @@ __attribute__((constructor)) static void vpLogProcess(void) {
if (vpIsSpringBoard(path)) {
vpLoadLibrary("haptics-fix", VP_HAPTICS_FIX);
vpLoadLibrary("accelerometer-hook", VP_ACCELEROMETER_HOOK);
+ // Inert without the foldable product identity; with it, the guard
+ // keeps the secure-indicator raise from crash-looping SpringBoard.
+ vpLoadLibrary("fold-guard", VP_FOLD_GUARD);
+ // Experimental: see the patch declaration before turning it on.
+ vpLoadLibrary("fold-display", VP_FOLD_DISPLAY);
}
+ if (vpIsPosterExtension(path))
+ vpLoadLibrary("poster-probe", VP_POSTER_PROBE);
// Loaded before the app gate too: the swizzle must be in place before
// Settings builds its follow-up section.
if (vpIsPreferences(path))
diff --git a/VPhoneGuestComponents/Tests/ConditionalBranchRelocationTests.c b/VPhoneGuestComponents/Tests/ConditionalBranchRelocationTests.c
new file mode 100644
index 00000000..122a6006
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/ConditionalBranchRelocationTests.c
@@ -0,0 +1,41 @@
+#include "../MISFix/MISFixConditionalBranch.h"
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/mman.h>
+#include <libkern/OSCacheControl.h>
+#include <unistd.h>
+
+int main(void) {
+ uint32_t out[5];
+ for (unsigned condition = 0; condition < 14; ++condition) {
+ assert(vpRelocateConditionalBranch(0x54000080u | condition, 0x100c, 0x1000, 0x1010, out) == 5);
+ assert((out[0] & 15) == (condition ^ 1));
+ uint64_t target; memcpy(&target, out + 3, 8); assert(target == 0x101c);
+ assert(vpRelocateConditionalBranch(0x54ffff80u | condition, 0x100c, 0x1000, 0x1010, out) == 5);
+ memcpy(&target, out + 3, 8); assert(target == 0xffc);
+ }
+ assert(!vpRelocateConditionalBranch(0x54ffffe1, 0x100c, 0x1000, 0x1010, out));
+ assert(!vpRelocateConditionalBranch(0x5400008e, 0x100c, 0x1000, 0x1010, out));
+ assert(!vpRelocateConditionalBranch(0x54000091, 0x100c, 0x1000, 0x1010, out));
+#ifdef __aarch64__
+ size_t size = (size_t)getpagesize();
+ uint32_t *code = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
+ assert(code != MAP_FAILED);
+ code[0] = 0xf100001f; // cmp x0, #0
+ uint64_t destination = (uint64_t)(uintptr_t)(code + 8);
+ // Relocate a NE branch whose original target is the taken result block.
+ assert(vpRelocateConditionalBranch(0x54000081, destination - 16,
+ destination - 28, destination - 12, code + 1) == 5);
+ code[6] = 0xd2800160; // mov x0, #11 (not taken)
+ code[7] = 0xd65f03c0; // ret
+ code[8] = 0xd28002c0; // mov x0, #22 (taken)
+ code[9] = 0xd65f03c0;
+ assert(mprotect(code, size, PROT_READ | PROT_EXEC) == 0);
+ sys_icache_invalidate(code, 40);
+ unsigned long (*run)(unsigned long) = (void *)code;
+ assert(run(0) == 11); assert(run(1) == 22);
+ munmap(code, size);
+#endif
+ puts("Conditional branch relocation: forward/backward conditions, rejection boundaries and native taken/fallthrough passed");
+}
diff --git a/VPhoneGuestComponents/Tests/FoldGuardTests.m b/VPhoneGuestComponents/Tests/FoldGuardTests.m
new file mode 100644
index 00000000..527b0534
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/FoldGuardTests.m
@@ -0,0 +1,46 @@
+#import <Foundation/Foundation.h>
+#include "../FoldGuard/libvphonefoldguard.m"
+
+// This is intentionally not a valid ObjC object. The old id-return wrapper
+// sends retain to it; the correct wrapper must pass its address untouched.
+static struct { uintptr_t invalidISA; uint64_t payload; } opaqueLayer = {0x123456789abcdef0, 42};
+static uintptr_t argumentsSeen[3];
+static BOOL throwCopy, returnNull;
+
+@interface VPFoldGuardFixture : NSObject
+- (void *)copyLayer:(void *)pointer layerFlags:(uint32_t)flags commitFlags:(uint32_t *)commit;
+- (id)objectResult:(void *)pointer layerFlags:(uint32_t)flags commitFlags:(uint32_t *)commit;
+- (void *)floatArgument:(double)value layerFlags:(uint32_t)flags commitFlags:(uint32_t *)commit;
+@end
+@implementation VPFoldGuardFixture
+- (void *)copyLayer:(void *)pointer layerFlags:(uint32_t)flags commitFlags:(uint32_t *)commit {
+ argumentsSeen[0] = (uintptr_t)pointer; argumentsSeen[1] = flags; argumentsSeen[2] = (uintptr_t)commit;
+ if (throwCopy) @throw [NSException exceptionWithName:@"CASecureIndicatorLayerInvalidName" reason:@"fixture" userInfo:nil];
+ return returnNull ? NULL : &opaqueLayer;
+}
+- (id)objectResult:(void *)pointer layerFlags:(uint32_t)flags commitFlags:(uint32_t *)commit { return self; }
+- (void *)floatArgument:(double)value layerFlags:(uint32_t)flags commitFlags:(uint32_t *)commit { return NULL; }
+@end
+
+int main(void) {
+ @autoreleasepool {
+ VPFoldGuardFixture *fixture = [VPFoldGuardFixture new];
+ SEL selector = @selector(copyLayer:layerFlags:commitFlags:);
+ Method method = class_getInstanceMethod(VPFoldGuardFixture.class, selector);
+ NSCAssert(vpCopyRenderABIIsSupported(method), @"native pointer/integer ABI should be accepted");
+ NSCAssert(!vpCopyRenderABIIsSupported(class_getInstanceMethod(VPFoldGuardFixture.class, @selector(objectResult:layerFlags:commitFlags:))), @"ObjC object result must not be treated as C++ pointer");
+ NSCAssert(!vpCopyRenderABIIsSupported(class_getInstanceMethod(VPFoldGuardFixture.class, @selector(floatArgument:layerFlags:commitFlags:))), @"FP-register argument must be refused");
+ vpOriginalCopyRender = method_getImplementation(method);
+ void *(*guard)(id, SEL, uintptr_t, uintptr_t, uintptr_t) = (void *)vpGuardedCopyRender;
+ uint32_t commit = 9;
+ void *returned = guard(fixture, selector, (uintptr_t)&opaqueLayer, 0xfedcba98, (uintptr_t)&commit);
+ NSCAssert(returned == &opaqueLayer, @"non-ObjC layer must pass through without ARC ownership");
+ NSCAssert(argumentsSeen[0] == (uintptr_t)&opaqueLayer && argumentsSeen[1] == 0xfedcba98 && argumentsSeen[2] == (uintptr_t)&commit, @"all argument registers must be forwarded");
+ returnNull = YES;
+ NSCAssert(guard(fixture, selector, 0, 0, 0) == NULL, @"normal null result must pass through");
+ throwCopy = YES;
+ NSCAssert(guard(fixture, selector, 0, 0, 0) == NULL, @"exception fallback must return a null opaque pointer");
+ puts("FoldGuard: 7 checks passed");
+ }
+ return 0;
+}
diff --git a/VPhoneGuestComponents/Tests/HingeTests.m b/VPhoneGuestComponents/Tests/HingeTests.m
new file mode 100644
index 00000000..6aa66adc
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/HingeTests.m
@@ -0,0 +1,108 @@
+// HingeTests.m — the hinge angle transport, and the real HID factory.
+//
+// On a Mac, Apple's own HID.framework answers IOHIDEventCreateHingeAngleEvent,
+// so the argument order the guest library calls with is checked against the
+// event's own field description: the third argument must read back as
+// AngleDegrees, the fourth as MechanicalAngleDegrees, the fifth as the
+// velocity. Where the framework is absent (a CI runner without the private
+// framework) the factory check is skipped; the transport checks always run.
+#import "../Hinge/VPhoneHingeHID.h"
+#import "../Hinge/VPhoneHingeState.h"
+#include <assert.h>
+#include <dlfcn.h>
+#include <mach/mach_time.h>
+#include <stdio.h>
+
+int main(void) {
+ @autoreleasepool {
+ VPhoneHingeState state;
+ NSDictionary *sample = @{
+ @"enabled": @YES, @"angle": @90.0,
+ @"sweep": @YES, @"duration_ms": @-1.0, @"profile": @0,
+ };
+ // The transport is a property list, including a real Boolean. Test
+ // after serialization, as cfprefsd crosses a process boundary.
+ NSData *wire = [NSPropertyListSerialization dataWithPropertyList:sample
+ format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];
+ id decoded = [NSPropertyListSerialization propertyListWithData:wire options:0 format:nil error:nil];
+ assert(VPhoneHingeDecode(decoded, &state));
+ assert(state.enabled && state.sweep && state.angle == 90.0);
+ assert(state.durationMs == -1.0 && state.profile == 0);
+ assert([VPhoneHingeEncode(state) isEqual:sample]);
+
+ // An instant set carries no sweep.
+ NSDictionary *instant = @{@"enabled": @YES, @"angle": @180.0};
+ NSData *instantWire = [NSPropertyListSerialization dataWithPropertyList:instant
+ format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];
+ id instantRead = [NSPropertyListSerialization propertyListWithData:instantWire options:0 format:nil error:nil];
+ assert(VPhoneHingeDecode(instantRead, &state));
+ assert(state.enabled && !state.sweep && state.angle == 180.0 && state.profile == 0);
+
+ NSMutableDictionary *closed = [sample mutableCopy];
+ closed[@"angle"] = @0.0;
+ assert(VPhoneHingeDecode(closed, &state) && state.angle == 0.0);
+ closed[@"angle"] = @180.0;
+ assert(VPhoneHingeDecode(closed, &state) && state.angle == 180.0);
+ closed[@"duration_ms"] = @0.0;
+ assert(VPhoneHingeDecode(closed, &state) && state.durationMs == 0.0);
+ closed[@"profile"] = @1;
+ assert(VPhoneHingeDecode(closed, &state) && state.profile == 1);
+ NSMutableDictionary *disabled = [sample mutableCopy];
+ disabled[@"enabled"] = @NO;
+ assert(VPhoneHingeDecode(disabled, &state) && !state.enabled && state.angle == 90.0);
+
+ for (id invalid in @[@YES, @"90", NSNull.null, @(NAN), @(INFINITY), @-0.5, @180.5]) {
+ NSMutableDictionary *bad = [sample mutableCopy];
+ bad[@"angle"] = invalid;
+ assert(!VPhoneHingeDecode(bad, &state));
+ assert(!state.enabled && state.angle == 0);
+ }
+ for (NSString *key in @[@"enabled", @"angle"]) {
+ NSMutableDictionary *bad = [sample mutableCopy];
+ [bad removeObjectForKey:key];
+ assert(!VPhoneHingeDecode(bad, &state));
+ }
+ // The optional sweep fields reject malformed values: a profile that
+ // is not one of the two, a boolean duration, an out-of-range
+ // duration.
+ for (id invalid in @[@2, @YES]) {
+ NSMutableDictionary *bad = [sample mutableCopy];
+ bad[@"profile"] = invalid;
+ assert(!VPhoneHingeDecode(bad, &state));
+ }
+ for (id invalid in @[@YES, @-2, @10001]) {
+ NSMutableDictionary *bad = [sample mutableCopy];
+ bad[@"duration_ms"] = invalid;
+ assert(!VPhoneHingeDecode(bad, &state));
+ }
+ assert(!VPhoneHingeDecode(@"flat", &state));
+ assert(VPhoneHingeInterval(nil) == 0);
+ assert(VPhoneHingeInterval(@YES) == 0);
+ assert(VPhoneHingeInterval(@0) == 0);
+ assert(VPhoneHingeInterval(@(-5)) == 0);
+ assert(VPhoneHingeInterval(@(4000.5)) == 5000);
+ assert(VPhoneHingeInterval(@(16000)) == 16000);
+ assert(VPhoneHingeInterval(@(2e9)) == 1000000);
+
+ void *hid = dlopen("/System/Library/PrivateFrameworks/HID.framework/HID", RTLD_NOW | RTLD_LOCAL);
+ VPhoneHingeEventFactory factory = (VPhoneHingeEventFactory)dlsym(hid, "IOHIDEventCreateHingeAngleEvent");
+ if (!factory) {
+ printf("HID.framework hinge factory unavailable here; transport checks only\n");
+ printf("hinge tests passed\n");
+ return 0;
+ }
+ id event = (__bridge id)factory(NULL, mach_absolute_time(), 42.0, 43.0, 1.0, 0);
+ assert(event);
+ // The description is column-formatted; collapse the runs of spaces
+ // before matching, so a wider label column still passes.
+ NSArray *fields = [[event description] componentsSeparatedByCharactersInSet:
+ [NSCharacterSet whitespaceCharacterSet]];
+ NSString *flat = [[fields filteredArrayUsingPredicate:
+ [NSPredicate predicateWithFormat:@"length > 0"]] componentsJoinedByString:@" "];
+ assert([flat containsString:@"AngleDegrees: 42.000000"]);
+ assert([flat containsString:@"MechanicalAngleDegre 43.000000"]);
+ assert([flat containsString:@"velocityDegreesPerSe 1.000000"]);
+ printf("hinge tests passed\n");
+ return 0;
+ }
+}
diff --git a/VPhoneGuestComponents/Tests/run-foldguard-tests.sh b/VPhoneGuestComponents/Tests/run-foldguard-tests.sh
new file mode 100644
index 00000000..eaf43c58
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/run-foldguard-tests.sh
@@ -0,0 +1,8 @@
+#!/bin/zsh
+set -euo pipefail
+test_root="${0:a:h}"
+test_work="$(mktemp -d "${TMPDIR:-/tmp}/vphone-foldguard-tests.XXXXXX")"
+trap 'rm -rf "$test_work"' EXIT
+xcrun --sdk macosx clang -fobjc-arc -fblocks -framework Foundation \
+ "$test_root/FoldGuardTests.m" -o "$test_work/FoldGuardTests"
+"$test_work/FoldGuardTests"
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
index 2889bcf2..2028e7d4 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
@@ -886,6 +886,23 @@ struct VPhoneLaunchpadControlCommands {
}
}
+ /// A maintenance command for a client: it shows in the app as a run of
+ /// Launchpad's own would, without opening its sheet, and its output
+ /// streams to the client too.
+ private func maintenance(
+ _ kind: VPhoneLaunchpadMaintenanceRun.Kind,
+ on machine: VPhoneLaunchpadMachinePath,
+ emit: @escaping Emit,
+ _ command: (@escaping @Sendable (String) -> Void) async throws -> Int32,
+ ) async throws -> Int32 {
+ try await library.runMaintenance(
+ VPhoneLaunchpadMaintenanceRun(kind: kind, machine: machine),
+ presents: false,
+ forward: emit,
+ command,
+ )
+ }
+
private func installCustomFirmware(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
let machine = try await machine(request)
let version = try bundleVersion(of: machine)
@@ -893,13 +910,16 @@ struct VPhoneLaunchpadControlCommands {
throw VPhoneLaunchpadError("Stop \(machine.name) before installing CFW.")
}
try await requireDiskUnheld(machine)
- let status = try await model.helper.installCustomFirmware(
- bundleVersion: version,
- machineName: machine.name,
- libraryRoot: machine.libraryRoot,
- keepArtifacts: request.flag("keep-artifacts"),
- onLine: emit,
- )
+ let keepArtifacts = request.flag("keep-artifacts")
+ let status = try await maintenance(.installCustomFirmware, on: machine, emit: emit) { [helper = model.helper] onLine in
+ try await helper.installCustomFirmware(
+ bundleVersion: version,
+ machineName: machine.name,
+ libraryRoot: machine.libraryRoot,
+ keepArtifacts: keepArtifacts,
+ onLine: onLine,
+ )
+ }
guard status == 0 else {
throw VPhoneLaunchpadError("Unable to install custom firmware. Check the log for details.")
}
@@ -914,12 +934,14 @@ struct VPhoneLaunchpadControlCommands {
throw VPhoneLaunchpadError("Stop \(machine.name) before updating its guest environment.")
}
try await requireDiskUnheld(machine)
- let status = try await model.helper.updateGuestEnvironment(
- bundleVersion: version,
- machineName: machine.name,
- libraryRoot: machine.libraryRoot,
- onLine: emit,
- )
+ let status = try await maintenance(.updateGuestEnvironment, on: machine, emit: emit) { [helper = model.helper] onLine in
+ try await helper.updateGuestEnvironment(
+ bundleVersion: version,
+ machineName: machine.name,
+ libraryRoot: machine.libraryRoot,
+ onLine: onLine,
+ )
+ }
guard status == 0 else {
throw VPhoneLaunchpadError("Unable to update the guest environment. Check the log for details.")
}
@@ -934,12 +956,14 @@ struct VPhoneLaunchpadControlCommands {
throw VPhoneLaunchpadError("Stop \(machine.name) before updating its kernel.")
}
try await requireDiskUnheld(machine)
- let status = try await model.helper.updateKernel(
- bundleVersion: version,
- machineName: machine.name,
- libraryRoot: machine.libraryRoot,
- onLine: emit,
- )
+ let status = try await maintenance(.updateKernel, on: machine, emit: emit) { [helper = model.helper] onLine in
+ try await helper.updateKernel(
+ bundleVersion: version,
+ machineName: machine.name,
+ libraryRoot: machine.libraryRoot,
+ onLine: onLine,
+ )
+ }
guard status == 0 else {
throw VPhoneLaunchpadError("Unable to update the kernel. Check the log for details.")
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
index d2fd0542..0c655637 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
@@ -6337,40 +6337,6 @@
}
}
},
- "Choose Show Console Log for the full output." : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Choose Show Console Log for the full output."
- }
- },
- "ja" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "完全な出力は「コンソールログを表示」で確認できます。"
- }
- },
- "ko" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "전체 출력은 '콘솔 로그 보기'에서 확인하십시오."
- }
- },
- "vi" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Chọn Hiển thị nhật ký bảng điều khiển để xem toàn bộ đầu ra."
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "选择“显示控制台日志”查看完整输出。"
- }
- }
- }
- },
"Choose…" : {
"localizations" : {
"en" : {
@@ -9124,6 +9090,96 @@
"zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "无法更新 %@ 的客户机环境" } }
}
},
+ "Update Guest Environment of %@" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Update Guest Environment of %@" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ のゲスト環境を更新" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@의 게스트 환경 업데이트" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cập nhật môi trường máy khách của %@" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "更新 %@ 的客户机环境" } }
+ }
+ },
+ "Install Custom Firmware on %@" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Install Custom Firmware on %@" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ にカスタムファームウェアをインストール" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@에 커스텀 펌웨어 설치" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cài firmware tùy chỉnh cho %@" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "为 %@ 安装自定义固件" } }
+ }
+ },
+ "Update Kernel of %@" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Update Kernel of %@" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ のカーネルを更新" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@의 커널 업데이트" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cập nhật kernel của %@" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "更新 %@ 的内核" } }
+ }
+ },
+ "Guest environment updated." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Guest environment updated." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ゲスト環境を更新しました。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "게스트 환경을 업데이트했습니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Đã cập nhật môi trường máy khách." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "客户机环境已更新。" } }
+ }
+ },
+ "Custom firmware installed." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Custom firmware installed." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "カスタムファームウェアをインストールしました。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "커스텀 펌웨어를 설치했습니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Đã cài firmware tùy chỉnh." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "自定义固件已安装。" } }
+ }
+ },
+ "Kernel updated." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Kernel updated." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "カーネルを更新しました。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "커널을 업데이트했습니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Đã cập nhật kernel." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "内核已更新。" } }
+ }
+ },
+ "It continues if you close this window." : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "It continues if you close this window." } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "このウインドウを閉じても処理は続行されます。" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "이 윈도우를 닫아도 작업은 계속됩니다." } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Tác vụ vẫn tiếp tục nếu bạn đóng cửa sổ này." } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "关闭此窗口后,操作仍会继续。" } }
+ }
+ },
+ "Open Log File" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Open Log File" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ログファイルを開く" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "로그 파일 열기" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Mở tệp nhật ký" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "打开日志文件" } }
+ }
+ },
+ "^[%lld warning](inflect: true)" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "^[%lld warning](inflect: true)" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%lld 件の警告" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "경고 %lld개" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "%lld cảnh báo" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "%lld 个警告" } }
+ }
+ },
+ "Show…" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Show…" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "表示…" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "보기…" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Hiển thị…" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "显示…" } }
+ }
+ },
"Install Custom Firmware" : {
"localizations" : {
"en" : {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
index bbdeb152..52019dd4 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
@@ -126,6 +126,9 @@ struct VPhoneLaunchpadMachineInspector: View {
)
}
}
+ if let run = library.maintenance[machine.path] {
+ maintenanceRow(run)
+ }
if let started = library.startedAt[machine.path] {
LabeledContent("Started", value: started.formatted(date: .omitted, time: .shortened))
}
@@ -279,6 +282,41 @@ struct VPhoneLaunchpadMachineInspector: View {
}
}
+ // MARK: - Maintenance
+
+ /// The machine's latest CFW install or update this session: the step it
+ /// is on, or how it ended, and a way back to its progress and output.
+ private func maintenanceRow(_ run: VPhoneLaunchpadMaintenanceRun) -> some View {
+ LabeledContent {
+ HStack(spacing: 6) {
+ VPhoneLaunchpadMaintenanceElapsed(run: run)
+ Button("Show…") { model.machineSheetRequest = .maintenance(machine.path) }
+ .controlSize(.small)
+ }
+ } label: {
+ Label {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: run.kind.title)
+ .lineLimit(1)
+ if let line = run.isRunning ? run.progress.stage : run.failure?.message {
+ Text(verbatim: line)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .help(line)
+ } else if run.progress.warningCount > 0 {
+ Text("^[\(run.progress.warningCount) warning](inflect: true)")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ } icon: {
+ VPhoneLaunchpadStatusIcon(status: run.status)
+ }
+ }
+ }
+
// MARK: - Patches
/// What a patch read depends on: the machine, the bundle that reads it,
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
index b237c3c9..65ac49a9 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
@@ -46,6 +46,15 @@ final class VPhoneLaunchpadMachineLibrary {
/// machine's disk image, the machine's own VM included.
private var diskHolders: [Path: [VPhoneLaunchpadDiskHolder]] = [:]
private var activities: [Path: String] = [:]
+ /// The last `cfw install` or update run on each machine this session,
+ /// kept once it ends so its sheet and the inspector can say how it went.
+ private(set) var maintenance: [Path: VPhoneLaunchpadMaintenanceRun] = [:]
+ /// Machines whose maintenance sheet is open: their failures show there,
+ /// not as an alert.
+ var showsMaintenance: Set<Path> = []
+ /// A run that has just started from Launchpad itself, for the machines
+ /// view to open its sheet. It clears this once it has.
+ var maintenanceSheetRequest: Path?
private var isRefreshing = false
private var timer: Timer?
@@ -551,7 +560,7 @@ final class VPhoneLaunchpadMachineLibrary {
}
/// Runs `cfw install` again through the helper, for a machine whose last
- /// install did not finish. Output goes to the machine's console log.
+ /// install did not finish.
func installCustomFirmware(_ machine: Path) async {
guard let version = bundleVersion(for: machine) else {
actionError = VPhoneLaunchpadError(String(localized: "No Core Bundle version is installed. Install one in Core Bundle."))
@@ -560,31 +569,17 @@ final class VPhoneLaunchpadMachineLibrary {
guard await requireDiskUnheld(machine) else {
return
}
- activities[machine] = String(localized: "Installing custom firmware…")
- defer { activities[machine] = nil }
- appendConsoleLog(machine, "$ vphone-cli cfw install \(machine.name)")
- let log = Self.consoleLog(machine)
- do {
- let status = try await helper.installCustomFirmware(
+ let installed = await performMaintenance(.installCustomFirmware, on: machine) { onLine in
+ try await helper.installCustomFirmware(
bundleVersion: version,
machineName: machine.name,
libraryRoot: machine.libraryRoot,
keepArtifacts: true,
- onLine: { line in Self.append(line, to: log) },
+ onLine: onLine,
)
- if status != 0 {
- actionError = VPhoneLaunchpadError(
- String(localized: "Unable to install custom firmware. Check the log for details."),
- detail: String(localized: "Choose Show Console Log for the full output."),
- )
- } else {
- recordGuestEnvironment(machine, version)
- }
- } catch {
- if !(error is CancellationError) {
- actionError = error as? VPhoneLaunchpadError
- ?? VPhoneLaunchpadError(String(localized: "Unable to install custom firmware. Check the log for details."), detail: error.localizedDescription)
- }
+ }
+ if installed {
+ recordGuestEnvironment(machine, version)
}
await refresh()
}
@@ -607,32 +602,16 @@ final class VPhoneLaunchpadMachineLibrary {
guard await requireDiskUnheld(machine, explain: explain) else {
return false
}
- var updated = false
- activities[machine] = String(localized: "Updating guest environment…")
- defer { activities[machine] = nil }
- appendConsoleLog(machine, "$ vphone-cli cfw update-environment \(machine.name)")
- let log = Self.consoleLog(machine)
- do {
- let status = try await helper.updateGuestEnvironment(
+ let updated = await performMaintenance(.updateGuestEnvironment, on: machine, explain: explain) { onLine in
+ try await helper.updateGuestEnvironment(
bundleVersion: version,
machineName: machine.name,
libraryRoot: machine.libraryRoot,
- onLine: { line in Self.append(line, to: log) },
+ onLine: onLine,
)
- if status != 0 {
- actionError = explain(VPhoneLaunchpadError(
- String(localized: "Unable to update the guest environment."),
- detail: String(localized: "Choose Show Console Log for the full output."),
- ))
- } else {
- recordGuestEnvironment(machine, version)
- updated = true
- }
- } catch {
- if !(error is CancellationError) {
- actionError = explain(error as? VPhoneLaunchpadError
- ?? VPhoneLaunchpadError(String(localized: "Unable to update the guest environment."), detail: error.localizedDescription))
- }
+ }
+ if updated {
+ recordGuestEnvironment(machine, version)
}
await refresh()
return updated
@@ -649,30 +628,90 @@ final class VPhoneLaunchpadMachineLibrary {
guard await requireDiskUnheld(machine) else {
return
}
- activities[machine] = String(localized: "Updating kernel…")
- defer { activities[machine] = nil }
- appendConsoleLog(machine, "$ vphone-cli cfw update-kernel \(machine.name)")
- let log = Self.consoleLog(machine)
- do {
- let status = try await helper.updateKernel(
+ await performMaintenance(.updateKernel, on: machine) { onLine in
+ try await helper.updateKernel(
bundleVersion: version,
machineName: machine.name,
libraryRoot: machine.libraryRoot,
- onLine: { line in Self.append(line, to: log) },
+ onLine: onLine,
)
+ }
+ await refresh()
+ }
+
+ // MARK: - Maintenance runs
+
+ /// Runs one of the helper's maintenance commands with the machine shown
+ /// busy. Each line goes to the machine's console log, as it always has,
+ /// to the run's own log, which its sheet follows, and to `forward`; the
+ /// few that mark a step or a warning reach the run itself. `presents`
+ /// asks the machines view to open the sheet. A failure is recorded on the
+ /// run in the words its sheet and an alert use; what the helper throws is
+ /// thrown on.
+ func runMaintenance(
+ _ run: VPhoneLaunchpadMaintenanceRun,
+ presents: Bool,
+ forward: (@Sendable (String) -> Void)? = nil,
+ _ command: (@escaping @Sendable (String) -> Void) async throws -> Int32,
+ ) async throws -> Int32 {
+ let machine = run.machine
+ maintenance[machine] = run
+ activities[machine] = run.kind.activity
+ defer { activities[machine] = nil }
+ if presents {
+ maintenanceSheetRequest = machine
+ }
+ let banner = "$ vphone-cli \(run.kind.command) \(machine.name)"
+ appendConsoleLog(machine, banner)
+ run.log.write(banner)
+ let console = Self.consoleLog(machine)
+ let log = run.log
+ let output: @Sendable (String) -> Void = { [weak run] line in
+ Self.append(line, to: console)
+ log.write(line)
+ forward?(line)
+ if VPhoneLaunchpadMaintenanceProgress.isNotable(line) {
+ Task { @MainActor in run?.read(line) }
+ }
+ }
+ do {
+ let status = try await command(output)
if status != 0 {
- actionError = VPhoneLaunchpadError(
- String(localized: "Unable to update the kernel."),
- detail: String(localized: "Choose Show Console Log for the full output."),
- )
+ run.failure = VPhoneLaunchpadError(run.kind.failure, detail: log.tail)
}
+ run.finish(succeeded: status == 0)
+ return status
} catch {
if !(error is CancellationError) {
- actionError = error as? VPhoneLaunchpadError
- ?? VPhoneLaunchpadError(String(localized: "Unable to update the kernel."), detail: error.localizedDescription)
+ run.failure = error as? VPhoneLaunchpadError
+ ?? VPhoneLaunchpadError(run.kind.failure, detail: error.localizedDescription)
}
+ run.finish(succeeded: false)
+ throw error
}
- await refresh()
+ }
+
+ /// `runMaintenance` for a button or a menu item: its sheet opens, and a
+ /// failure, reworded by `explain`, becomes `actionError` unless that
+ /// sheet is open to show it. True once the command has succeeded.
+ @discardableResult
+ private func performMaintenance(
+ _ kind: VPhoneLaunchpadMaintenanceRun.Kind,
+ on machine: Path,
+ explain: (VPhoneLaunchpadError) -> VPhoneLaunchpadError = { $0 },
+ _ command: (@escaping @Sendable (String) -> Void) async throws -> Int32,
+ ) async -> Bool {
+ let run = VPhoneLaunchpadMaintenanceRun(kind: kind, machine: machine)
+ if (try? await runMaintenance(run, presents: true, command)) == 0 {
+ return true
+ }
+ if let failure = run.failure {
+ run.failure = explain(failure)
+ if !showsMaintenance.contains(machine) {
+ actionError = run.failure
+ }
+ }
+ return false
}
/// Stops a machine. The guest is asked to shut down first, so it quits its
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift
index fabf97a1..ce64527a 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift
@@ -13,6 +13,7 @@ struct VPhoneLaunchpadMachinesView: View {
case clone(MachinePath)
case snapshots(MachinePath)
case console(MachinePath)
+ case maintenance(MachinePath)
case guestSystem(MachinePath)
case commands
@@ -26,6 +27,7 @@ struct VPhoneLaunchpadMachinesView: View {
case let .clone(machine): "clone-\(machine.url.path)"
case let .snapshots(machine): "snapshots-\(machine.url.path)"
case let .console(machine): "console-\(machine.url.path)"
+ case let .maintenance(machine): "maintenance-\(machine.url.path)"
case let .guestSystem(machine): "guest-system-\(machine.url.path)"
case .commands: "commands"
}
@@ -121,6 +123,19 @@ struct VPhoneLaunchpadMachinesView: View {
}
// So New Machine opens on the catalog rather than loading it.
.task(id: model.bundles.defaultVersion) { await VPhoneLaunchpadNewMachineView.prefetchCatalog(model) }
+ // A CFW install or update started here shows its progress at once.
+ // Another sheet open keeps its place; the inspector offers the
+ // progress then. A run already over by the time the list is back
+ // on screen does not open.
+ .onChange(of: library.maintenanceSheetRequest, initial: true) {
+ guard let machine = library.maintenanceSheetRequest else {
+ return
+ }
+ library.maintenanceSheetRequest = nil
+ if sheet == nil, library.maintenance[machine]?.isRunning == true {
+ sheet = .maintenance(machine)
+ }
+ }
.onChange(of: model.deletionRequest, initial: true) {
if !model.deletionRequest.isEmpty {
deletion = model.deletionRequest
@@ -440,6 +455,8 @@ struct VPhoneLaunchpadMachinesView: View {
VPhoneLaunchpadSnapshotsView(machine: path)
case let .console(path):
VPhoneLaunchpadConsoleView(title: "\(path.name) Console", url: VPhoneLaunchpadMachineLibrary.consoleLog(path))
+ case let .maintenance(path):
+ VPhoneLaunchpadMaintenanceView(machine: path)
case let .guestSystem(path):
VPhoneLaunchpadGuestSystemView(machine: path)
case .commands: