Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Make the VirtualAudio device-state updates wait for their manager on the iPhone Duo

Jackyc094fb486d65
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 0adf0c6f..07d106be 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -207,23 +207,34 @@
> See [HomePod mini support](Firmware/homepod_mini_support.md) for evidence,
> validation status and limitations.
-> **VirtualAudio device-state guard (2026-10-23):**
-> `system-virtualaudio-cfw-device_state_guard` (guest system set, iOS 27, on
-> in `standard`, blocked in `tvos` and `tvos-4k`; verb `cfw
-> patch-virtualaudio-device-state-guard`, riding the shared staged copy with
-> the other four VirtualAudio verbs) stands down the two device-state updates
-> that read the DeviceStateManager singleton before deferred initialization
-> publishes it — the audiomxd crash loop on the iPhone Duo guest, ~0.6 s
-> after every launch, once the four speaker-route patches let the route
-> through. Each gate's `cbz w0, <skip>` becomes an unconditional `b` to the
-> same target. The plugin header gates the patch to arm64e.x1 (cpusubtype 12,
-> iOS 27.1's iPhone19,4): the 26.6.2 and 27.0 plugins are plain arm64e and
-> are left byte-identical. The five other TheInstance callers are
-> HapticAttenuationIODelegate's and are not touched — see the full section
-> below. Verified live on `duotest-m5` (2026-10-23 night): audiomxd survives
-> at a stable pid where it previously died ~0.6 s after every launch (28
-> crash reports before, zero new after), with the system-sound stream
-> routed on `PuffinOutput` and its DSP chain running.
+> **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
@@ -244,7 +255,7 @@
> `PACIBSPPC`/`RETABSPPC` prologues and returns; the audiomxd crash those
> four patches triggered on 27.1 is root-caused as the pre-init
> DeviceStateManager read and fixed by
-> `system-virtualaudio-cfw-device_state_guard` above.
+> `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`
@@ -4102,78 +4113,117 @@ consistency, plus full bundle/Launchpad builds. Firmware fixture tests still
require the separately held reference IPSWs; a build or synthetic test is not a
claim that every newly supported OS has been restored and booted on this host.
-## VirtualAudio's device-state guard — the null singleton before deferred init (2026-10-23)
+## VirtualAudio's device-state null gate — the singleton a guest never gets (2026-10-24)
-`system-virtualaudio-cfw-device_state_guard` (new), same
-`VirtualAudio.plugin` binary, verb `cfw patch-virtualaudio-device-state-guard`,
-riding the same `patchMachO` staged copy as the other four VirtualAudio
-verbs in both `cfw install` and `cfw update-environment`. Patcher:
+`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`
-(`patchDeviceStateGuard`, anchoring in `locateDeviceStateGuard` and
-`gatedDeviceStateSite`).
+(`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) ~0.6 s
-after every launch, on queue AudioControl, in the plugin at 0xa16b0
-reached `HALS_AHPPlugIn::ObjectSetPropertyData` ←
+(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, inside "Deferred Initialization", after a wait of up to
-8 s for a haptic actuator port a VM does not have; asked earlier,
-TheInstance logs "TheInstance() called before SetInstance()" and returns
-null. The saved VAD serialization state replays the same property write
-into every launch, so one fault is a crash loop. 27.0 carries the same
-gated code (update at 0xa1ee4, TheInstance at 0x2b64ec) but its graph
-never takes the path; none of the other four patches' sites is on it.
+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 (`pacibsppc`) is TheInstance's entry. Every direct
-`bl` to that entry — six on 27.1 — is filtered to the gated shape above:
-a call at −8 (the gate check), a `cbz w0` at −4 whose decoded target
-skips forward past the whole update (target beyond the `ldr` at +8), the
-return moved aside at +4 (`mov xN, x0`), and the unchecked dereference at
-+8 (`ldr xM, [x0]`). Exactly two callers carry the shape; a build with a
-different count is refused rather than half-patched. The plugin header
-gates everything first: cputype arm64 and cpusubtype (masked of the
-LIB64 bit) 12 — arm64e.x1. Any other subtype reports "nothing to do" and
+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's `cbz w0, <skip>` becomes an unconditional `b`
-to the same target (`ARM64Encoder.encodeB`): the gate-check call still
-runs, its answer is no longer read, and the device-state update is
-skipped exactly as when the gate's check answers false — the state the
-VM is always in before SetInstance. After deferred initialization
-completes, TheInstance answers a real singleton and every later update
-reaches the manager. Idempotent: a re-run finds the unconditional branch
-in the gate slot, requires it to skip past the dereference, and writes
-nothing. Verified on the real binaries: 27.1 resolves TheInstance at
-0x2b2988 and rewrites exactly the two gates (0xa16a4 `cbz w0, 0xa16d8`
-→ `b 0xa16d8`, 0x340001a0 → 0x1400000d; 0xa16e0 `cbz w0, 0xa1720` →
-`b 0xa1720`, 0x34000200 → 0x14000010) — six bytes move, a second run is
-byte-identical — and the 27.0 and 26.6.2 plugins report "not an
-arm64e.x1 plugin" with unchanged SHA-256s.
-
-**The callers left alone.** The other five TheInstance callers
-(0x4f7b94, 0x4f7dec, 0x4f9114, 0x5013ac, and the coordinator) all live
-in `HapticAttenuationIODelegate.mm`. The 0x4f7dec caller dereferences
-the singleton unguarded exactly like the crash site (`mov x20, x0; ldr
-x21, [x0]`, field 0x170), but its whole block sits behind a capability
-flag (`tbz w8, #0` at 0x4f7d0c skipping past it) that reads false
-without a Taptic Engine — the same absence that makes deferred
-initialization time out; the other three pass the singleton into
-0x2b30b4, which does dereference unchecked (0x2b30d8) but is reached
-only through the coordinator's activation ("Coordinator active
-(subscriptions set)"), which needs an actuator port. Across the observed
-crash loop neither path ever faulted — every crash is the device-state
-site — so they are unpatched; if a future build ever faults there, the
-guard's matcher refuses (it requires the gate shape) and the site gets
-its own patch. Research detail:
-`Research/Guest/virtualaudio_speaker_route_throws.md`.
+**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 4160ef25..f16f3009 100644
--- a/Research/Guest/iphone_duo_bringup.md
+++ b/Research/Guest/iphone_duo_bringup.md
@@ -197,15 +197,17 @@ With them live, audiomxd crash-looped on this guest (a null read in
`VirtualAudio.plugin` reached from `SetPropertyData`): the device update
reads the DeviceStateManager singleton before deferred initialization
publishes it. Root-caused and fixed by
-`system-virtualaudio-cfw-device_state_guard` (stand each gated
-device-state update down while the singleton is absent; arm64e.x1
-plugins only, earlier builds byte-identical) — see
+`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-23 night, bundle `2.12.0-local.34ce2075`): audiomxd survives at
-a stable pid where it previously died ~0.6 s after every launch (28
-crash reports before, zero new after), and the system-sound stream
-routes on `PuffinOutput` with its DSP chain running.
+(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)
diff --git a/Research/Guest/virtualaudio_speaker_route_throws.md b/Research/Guest/virtualaudio_speaker_route_throws.md
index db677195..e823ac63 100644
--- a/Research/Guest/virtualaudio_speaker_route_throws.md
+++ b/Research/Guest/virtualaudio_speaker_route_throws.md
@@ -686,16 +686,14 @@ its I/O context is `PuffinOutput (VAD [vdef] AggDev N)`. Volume adjusts
kept the tone silent after that was not routing: see `virtio_sound.md` §6 for
the plugin faults and §7 for the haptic track.
-## Layer 5 — the null DeviceStateManager singleton on arm64e.x1 (2026-10-23, decoded)
+## 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 ~0.6 s after every launch: EXC_BAD_ACCESS far=0, queue
-AudioControl, plugin offset 0xa16b0, reached
+then segfaults on queue AudioControl at plugin offset 0xa16b0, reached
`HALS_AHPPlugIn::ObjectSetPropertyData` ←
-`__vaemVADSerializationListener_block_invoke`. Both saved crash reports
-fault at exactly that offset.
+`__vaemVADSerializationListener_block_invoke`.
The faulting function is `VirtualAudio_Device`'s update (0xa08bc; its
`retabsppc` names it). After the route is published it pushes the
@@ -719,78 +717,92 @@ a16ec ldr x21, [x0] ; same unchecked read
a1720 add x0, sp, #0xf ; past both gates
```
-`TheInstance()` (0x2b2988) loads the global at 0x74ff28 and returns it
-on the fast path; when the global is null it logs
-"TheInstance() called before SetInstance()", reloads the global and
-returns that — null. The global is stored exactly once, at 0x3ad0a8
-inside "Deferred Initialization", *after* waiting up to 8 s for a
-haptic actuator port the VM does not have. So the ordering on a 27.1
-guest is: route published → serialization listener pushes saved state →
-device update runs → TheInstance is null → fault. The saved state
-replays on every launch: the crash loop. None of the four patches'
-sites is on this path, and 27.0 (update at 0xa1ee4, TheInstance at
-0x2b64ec, same gated shape) never takes it — its graph's gates answer
-false before the singleton is read.
+`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_guard` (verb
-`cfw patch-virtualaudio-device-state-guard`, declared in
+`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` for the entry): each
-gate's `cbz w0, <skip>` becomes an unconditional `b` to the same target
-— 0xa16a4: `cbz w0, 0xa16d8` → `b 0xa16d8` (0x340001a0 → 0x1400000d)
-and 0xa16e0: `cbz w0, 0x1720` → `b 0xa1720` (0x34000200 → 0x14000010).
-The gate-check calls still run; their answers are no longer read, and
-both device-state updates are skipped exactly as when a gate answers
-false. Once deferred initialization finishes, TheInstance answers a
-real singleton and every later update reaches the manager.
+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.
-The "TheInstance() called before SetInstance()" cstring is referenced
-exactly once in `__text`; the prologue above that reference is
-TheInstance. Every direct `bl` to it (six on 27.1) is filtered to the
-gated shape — call at −8, `cbz w0` at −4 skipping past the whole
-update, `mov xN, x0` at +4, `ldr xM, [x0]` at +8 — and exactly two
-callers match; any other count refuses. The plugin header gates the
-whole patch to arm64e.x1 (cputype arm64, cpusubtype masked of the
-LIB64 bit == 12): the 26.6.2 and 27.0 plugins (cpusubtype 2) report
-"not an arm64e.x1 plugin", exit 0 and keep their SHA-256s, so the
-installer's shared staged copy costs them nothing.
-
-**The other five callers, examined and left alone.** All are in
-`HapticAttenuationIODelegate.mm`:
-
-| Call | Shape | Why it cannot fault pre-init on this guest |
-| --- | --- | --- |
-| 0x4f7dec | `mov x20,x0; ldr x21,[x0]` — unguarded deref like ours, field 0x170 | The whole block sits behind a capability flag (`tbz w8,#0` @0x4f7d0c skips past it) that reads false without a Taptic Engine — the same absence that makes deferred init time out. |
-| 0x4f7b94, 0x4f9114, 0x5013ac | pass the singleton into 0x2b30b4, which derefs unchecked at 0x2b30d8 | Reached only through the coordinator's activation ("Coordinator active (subscriptions set)" @0x4f91a8), which needs an actuator port to subscribe to. |
-| 0x4f7b94's sibling reads | — | Same coordinator. |
-
-Across the whole observed crash loop neither path ever faulted — both
-crash reports are the device-state site — so they stay unpatched. The
-guard's matcher would refuse them anyway: it requires the `cbz w0` gate
-under the call, which is exactly what distinguishes the two device-state
-updates. If a future build ever faults in the delegate, that site needs
-its own patch.
-
-**Status.** Patcher, declaration, verb, installer wiring, tvOS block
-lists and unit tests are in; the verb patches a copy of the stock 27.1
-plugin (six bytes, the two gate words above) and a second run is
-byte-identical; the 27.0 and 26.6.2 copies are untouched.
-`FirmwarePatcherTests` shows no new failures against a HEAD baseline
-(the fixture suites fail identically on both trees).
-
-**Verified in the guest (2026-10-23, night).** Bundle `2.12.0-local.34ce2075`
-(built from this tree) installed through `bundle install-local`; after
-stopping the machine, `vm set-bundle duotest-m5 … --update-environment` and
-`cfw update-environment` put the patch in the receipt's live list. (The
-machine carried a stale owner block of the identifier, written 22:56 from a
-bundle built while the patcher was still being written; `fw set-patches
-duotest-m5` cleared it.) After boot: audiomxd survives past a minute at a
-stable pid — it previously died ~0.6 s after every launch, 28 crash reports
-all faulting 0xa16b0 on AudioControl — the crash count stays at 28 with zero
-new reports, and RTAID telemetry shows a SystemSounds stream routed on
-`PuffinOutput` (`rout: 1`, PreDSP/PostDSP running): the route on the virtio
-aggregate, not Null_Device. The widget-extension crashes on this machine
-(WorldClockWidget, WidgetRenderer) predate the update and are the known Duo
-bring-up issue, not audio.
+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/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift
index 68b04256..24da6626 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift
@@ -134,41 +134,50 @@
// it reads from memory and never re-reads the value the test examined, on
// either supported build.
//
-// The device-state guard
-// ----------------------
+// 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. The singleton is published only at
-// the end of "Deferred Initialization", which first waits up to 8 s for a
-// haptic actuator port a VM does not have; asked earlier, TheInstance()
-// logs "TheInstance() called before SetInstance()" and returns null, and
-// the update dereferences that null — the audiomxd crash loop on an
-// iPhone Duo guest, ~0.6 s after every launch.
+// the 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 stands the two device-state updates down: each gate's
-// `cbz w0, <skip>` — the branch that already skips the update when the
-// gate's check answers false — becomes an unconditional `b` to the same
-// target. Nothing else in either block changes; the gate-check call still
-// runs, its answer is simply no longer read, and the device-state update
-// the manager would have received before it exists never happens — the
-// same nothing the gates already do when their check fails. After
-// deferred initialization completes, TheInstance answers a real singleton
-// again and the manager takes every later update.
+// 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 then filtered to the gated shape
-// both device-state updates share: a gate-check call, its `cbz w0`
-// skipping forward past the whole update, the singleton's return moved
-// aside (`mov xN, x0`), and the unchecked dereference of that return
-// (`ldr xM, [x0]`) — the instruction that faults. Exactly two callers
-// carry the shape; both are rewritten. The plugin is touched only where
-// iOS 27.1's arm64e.x1 build carries it: a header check (cputype arm64,
-// cpusubtype 12 — 26.x and 27.0 are cpusubtype 2) reports "nothing to do"
-// on every other build, so their bytes never move.
+// 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
@@ -256,13 +265,13 @@ public enum CustomFirmwareVirtualAudio {
/// Record identity for the volume-gate patch.
public static let volumeGatePatchID = "system-virtualaudio-cfw-volume_mode_precondition"
- /// The singleton's own diagnostic, and the anchor for the device-state
- /// guard: the log DeviceStateManager's accessor prints when it is asked
- /// for an instance nobody published yet.
+ /// 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 device-state guard.
- public static let deviceStateGuardPatchID = "system-virtualaudio-cfw-device_state_guard"
+ /// 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) }
@@ -353,29 +362,36 @@ public enum CustomFirmwareVirtualAudio {
public let slotRehashes: [CustomFirmwareSlotRehash]
}
- /// One gated device-state update: the gate branch the patch rewrites
- /// and the singleton call it stands over.
- public struct DeviceStateGuardAnchor: Sendable, Equatable {
- /// The `cbz w0` gate — the instruction the patch rewrites.
- public let gateFileOffset: Int
- public let gateVMA: UInt64
- /// The `bl TheInstance` the gate stands over.
- public let callFileOffset: Int
- public let callVMA: UInt64
- /// Where the gate skips to — the rewrite's own target.
+ /// 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 DeviceStateGuardReport: Sendable {
+ public struct DeviceStateNullGateReport: Sendable {
public let outcome: Outcome
/// TheInstance's entry, resolved from its own diagnostic.
public let theInstanceVMA: UInt64
- public let sites: [DeviceStateGuardAnchor]
+ public let sites: [DeviceStateNullGateAnchor]
public let records: [PatchRecord]
public let slotRehashes: [CustomFirmwareSlotRehash]
}
- // MARK: - Patching
+ 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.
///
@@ -494,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
@@ -621,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
@@ -883,22 +891,24 @@ public enum CustomFirmwareVirtualAudio {
)
}
- // MARK: - Device-state guard patching
+ // MARK: - Device-state null-gate patching
- /// Patch the VirtualAudio Mach-O at `url` in place, standing down the
- /// two gated device-state updates that dereference the
- /// DeviceStateManager singleton before deferred initialization
- /// publishes it.
+ /// 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's `cbz w0, <skip>` — the branch that already skips its
- /// update when the gate's check answers false — becomes an
- /// unconditional `b` to the same target. The gate-check call keeps
- /// running; its answer is no longer read. Applies only to an arm64e.x1
- /// (cpusubtype 12) plugin: every other build reports
- /// ``Outcome/notArm64EX1`` and keeps its bytes.
+ /// 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 recognises its own branches, reports
- /// ``Outcome/alreadyPatched`` and leaves the file byte-identical.
+ /// 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.
@@ -907,32 +917,32 @@ public enum CustomFirmwareVirtualAudio {
/// after, which is what both install paths do.
/// - dryRun: locate and report, write nothing.
@discardableResult
- public static func patchDeviceStateGuard(
+ public static func patchDeviceStateNullGate(
fileAt url: URL,
reattest: Bool = true,
dryRun: Bool = false,
log: ((String) -> Void)? = stdoutLog,
- ) throws -> DeviceStateGuardReport {
+ ) 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 patchDeviceStateGuard(&data, reattest: reattest, dryRun: dryRun, log: log)
+ 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 ``patchDeviceStateGuard(fileAt:reattest:dryRun:log:)``.
+ /// In-memory form of ``patchDeviceStateNullGate(fileAt:reattest:dryRun:log:)``.
@discardableResult
- public static func patchDeviceStateGuard(
+ public static func patchDeviceStateNullGate(
_ data: inout Data,
reattest: Bool = true,
dryRun: Bool = false,
log: ((String) -> Void)? = stdoutLog,
- ) throws -> DeviceStateGuardReport {
+ ) throws -> DeviceStateNullGateReport {
if data.startIndex != 0 {
data = Data(data)
}
@@ -941,8 +951,8 @@ public enum CustomFirmwareVirtualAudio {
case .x1:
break
case .other:
- log?(" [·] VirtualAudio: not an arm64e.x1 plugin — the device-state guard has nothing to do")
- return DeviceStateGuardReport(
+ log?(" [·] VirtualAudio: not an arm64e.x1 plugin — the device-state null gate has nothing to do")
+ return DeviceStateNullGateReport(
outcome: .notArm64EX1,
theInstanceVMA: 0,
sites: [],
@@ -953,14 +963,13 @@ public enum CustomFirmwareVirtualAudio {
break // not a thin arm64 image; the anchor below refuses it
}
- let located = try locateDeviceStateGuard(in: data)
+ 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
- DeviceStateGuardAnchor(
- gateFileOffset: site.gate,
- gateVMA: located.vma(site.gate),
- callFileOffset: site.call,
- callVMA: located.vma(site.call),
+ DeviceStateNullGateAnchor(
+ gateCallFileOffset: site.gateCall,
+ gateCallVMA: located.vma(site.gateCall),
+ branchVMA: located.vma(site.branch),
skipTargetVMA: site.target,
)
}
@@ -969,43 +978,43 @@ public enum CustomFirmwareVirtualAudio {
var written: [Int] = []
var alreadyPatched = 0
for site in located.sites {
- let gate = site.gate
- let gateVMA = located.vma(gate)
- let gateInstruction = located.disasm.disassembleOne(in: data, at: gate, address: gateVMA)
- if site.alreadySkips {
+ 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(gateVMA)): the gate already skips the device-state update")
+ log?(" [=] 0x\(hex(callVMA)): the gate already asks TheInstance")
continue
}
- guard let branch = ARM64Encoder.encodeB(from: Int(gateVMA), to: Int(site.target)) else {
+ guard let redirect = ARM64Encoder.encodeBL(from: Int(callVMA), to: Int(located.theInstanceVMA)) else {
throw PatcherError.patchSiteNotFound(
- "\(component): the skip at 0x\(hex(site.target)) is out of branch range "
- + "of the gate at 0x\(hex(gateVMA))",
+ "\(component): TheInstance at 0x\(hex(located.theInstanceVMA)) is out of "
+ + "branch range of the gate call at 0x\(hex(callVMA))",
)
}
- let original = Data(data[gate ..< gate + 4])
+ let original = Data(data[call ..< call + 4])
if dryRun {
- log?(" [.] dry-run — would branch 0x\(hex(gateVMA)) -> 0x\(hex(site.target))")
+ log?(" [.] dry-run — would call TheInstance from 0x\(hex(callVMA))")
continue
}
- data.replaceSubrange(gate ..< gate + 4, with: branch)
- written.append(gate)
+ data.replaceSubrange(call ..< call + 4, with: redirect)
+ written.append(call)
records.append(PatchRecord(
- patchID: deviceStateGuardPatchID,
+ patchID: deviceStateNullGatePatchID,
component: component,
- fileOffset: gate,
- virtualAddress: gateVMA,
+ fileOffset: call,
+ virtualAddress: callVMA,
originalBytes: original,
- patchedBytes: branch,
- beforeDisasm: gateInstruction?.description ?? "",
- afterDisasm: branch.map { String(format: "%02x", $0) }.joined(separator: " "),
- description: "device-state gate -> unconditional skip",
+ patchedBytes: redirect,
+ beforeDisasm: callInstruction?.description ?? "",
+ afterDisasm: redirect.map { String(format: "%02x", $0) }.joined(separator: " "),
+ description: "device-state gate check -> TheInstance",
))
- log?(" [+] 0x\(hex(gateVMA)): \(gateInstruction?.description ?? "") -> b 0x\(hex(site.target))")
+ log?(" [+] 0x\(hex(callVMA)): \(callInstruction?.description ?? "") -> bl 0x\(hex(located.theInstanceVMA))")
}
if records.isEmpty, !dryRun {
- log?(" [=] all \(alreadyPatched) gate(s) already skip the device-state update")
+ log?(" [=] all \(alreadyPatched) gate(s) already ask TheInstance")
}
var rehashes: [CustomFirmwareSlotRehash] = []
@@ -1016,7 +1025,7 @@ public enum CustomFirmwareVirtualAudio {
}
}
let outcome: Outcome = dryRun ? .wouldPatch : (records.isEmpty ? .alreadyPatched : .patched)
- return DeviceStateGuardReport(
+ return DeviceStateNullGateReport(
outcome: outcome,
theInstanceVMA: located.theInstanceVMA,
sites: anchors,
@@ -1025,6 +1034,7 @@ public enum CustomFirmwareVirtualAudio {
)
}
+
// MARK: - Anchoring
/// Resolve the throw block and the epilogue, or say why not.
@@ -1704,29 +1714,29 @@ public enum CustomFirmwareVirtualAudio {
return false
}
- // MARK: - Device-state guard anchoring
+ // MARK: - Device-state null-gate anchoring
/// One gated device-state update, in file-offset terms.
- struct DeviceStateGuardSite: Sendable {
- /// The gate branch — the instruction the patch rewrites.
- let gate: Int
- /// The `bl TheInstance` the gate stands over.
- let call: Int
- /// Where the gate skips to — the rewrite's own target.
+ 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 already skips unconditionally: this patch's own earlier
- /// write, recognised rather than repeated.
- let alreadySkips: Bool
+ /// The gate slot already calls TheInstance: this patch's own
+ /// earlier write, recognised rather than repeated.
+ let alreadyGated: Bool
}
- /// Everything the device-state guard needs: TheInstance's own entry and
- /// the gated callers that dereference its answer.
- struct DeviceStateGuardPlan: Sendable {
+ /// 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: [DeviceStateGuardSite]
+ let sites: [DeviceStateNullGateSite]
var theInstanceVMA: UInt64 {
vma(theInstanceOffset)
@@ -1740,13 +1750,14 @@ public enum CustomFirmwareVirtualAudio {
/// How many direct callers of TheInstance must carry the gated shape —
/// one per device-state update VirtualAudio_Device pushes at the
/// manager. A build with a different count is refused, not half-patched.
- private static let deviceStateGuardSiteCount = 2
+ 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 locateDeviceStateGuard(in data: Data) throws -> DeviceStateGuardPlan {
+ /// 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")
@@ -1789,7 +1800,7 @@ public enum CustomFirmwareVirtualAudio {
// Every direct caller, kept where the gated device-state shape
// holds around the call.
- var sites: [DeviceStateGuardSite] = []
+ var sites: [DeviceStateNullGateSite] = []
var offset = textStart
while offset + 4 <= textEnd {
defer { offset += 4 }
@@ -1798,40 +1809,44 @@ public enum CustomFirmwareVirtualAudio {
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) {
+ if let site = gatedDeviceStateSite(
+ in: data, disasm: disasm, call: offset, vma: vma, theInstance: vma(theInstance),
+ ) {
sites.append(site)
}
}
- guard sites.count == deviceStateGuardSiteCount else {
+ guard sites.count == deviceStateNullGateSiteCount else {
throw PatcherError.patchSiteNotFound(
- "\(component): expected exactly \(deviceStateGuardSiteCount) gated device-state "
+ "\(component): expected exactly \(deviceStateNullGateSiteCount) gated device-state "
+ "updates around TheInstance at 0x\(hex(vma(theInstance))), found \(sites.count)",
)
}
- return DeviceStateGuardPlan(
+ return DeviceStateNullGatePlan(
disasm: disasm,
textStart: textStart,
textAddress: text.address,
theInstanceOffset: theInstance,
- sites: sites.sorted { $0.gate < $1.gate },
+ sites: sites.sorted { $0.gateCall < $1.gateCall },
)
}
/// Whether a direct `bl` to TheInstance sits in the gated device-state
- /// shape: a gate-check call, its `cbz w0` skipping forward past the
- /// whole update (or the unconditional branch this patch wrote over it),
- /// the singleton's return moved aside, and that return dereferenced
- /// unchecked — the read that faults before SetInstance runs. The
- /// singleton's other callers either test its answer or live behind the
- /// haptic attenuation delegate's own capability flag, and match nothing
- /// here.
+ /// 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,
- ) -> DeviceStateGuardSite? {
+ theInstance: UInt64,
+ ) -> DeviceStateNullGateSite? {
guard call >= 8 else { return nil }
// The singleton's answer, moved aside and then read unchecked:
@@ -1840,7 +1855,7 @@ public enum CustomFirmwareVirtualAudio {
saved.mnemonic == "mov",
let savedOps = saved.detail?.operands, savedOps.count == 2,
savedOps[0].type == .register, savedOps[1].type == .register,
- savedOps[1].reg == ARM64Register.x(0),
+ 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,
@@ -1848,33 +1863,28 @@ public enum CustomFirmwareVirtualAudio {
derefOps[1].type == .memory, derefOps[1].mem.base == ARM64Register.x(0)
else { return nil }
- // The gate: a call whose answer picks, then the branch that skips
- // the update when the answer is false.
- guard disasm.disassembleOne(in: data, at: call - 8)?.isCall == true else { return nil }
- let gate = call - 4
- guard let gateInsn = disasm.disassembleOne(in: data, at: gate),
- let gateWord = wordAt(data, gate)
+ // 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 }
- var alreadySkips = false
- let target: UInt64?
- if gateInsn.mnemonic == "cbz",
- let operands = gateInsn.detail?.operands, operands.count == 2,
- operands[0].type == .register, operands[0].reg == ARM64Register.w(0)
- {
- target = decodeConditionalBranchTarget(insn: gateWord, pc: vma(gate))
- } else if gateInsn.isJump, !gateInsn.isCall, gateInsn.detail?.conditionCode == nil {
- // An unconditional skip is this patch's own earlier write. Some
- // other branch of exactly that shape is indistinguishable from
- // it, and for either the safe answer is to leave the word alone.
- alreadySkips = true
- target = ARM64Encoder.decodeBranchTarget(insn: gateWord, pc: vma(gate))
- } else {
- return nil
- }
// The skip must clear the dereference: the branch and its target
- // bracket the whole device-state update the patch stands down.
- guard let target, target > vma(call + 8) else { return nil }
- return DeviceStateGuardSite(gate: gate, call: call, target: target, alreadySkips: alreadySkips)
+ // 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
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index 150d049a..6241c197 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -494,19 +494,20 @@ public enum FirmwareGuestSystemPatchSet {
target: .guestExecutable(path: "/Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio"),
),
VPhonePatchDeclaration(
- identifier: virtualAudioDeviceStateGuard,
- title: "VirtualAudio device-state guard",
+ identifier: virtualAudioDeviceStateNullGate,
+ title: "VirtualAudio device-state null gate",
summary: """
- Stands down the two device-state updates VirtualAudio_Device pushes at \
- DeviceStateManager while the manager's singleton does not exist yet. \
- The singleton is published only at the end of deferred initialization, \
- which first waits for a haptic actuator port a VM does not have; with \
- the speaker-route patches on, the published route reaches the update \
- first, and its unchecked read of the null singleton crash-loops \
- audiomxd about half a second after every launch. Each gate's \
- skip-when-false branch is made unconditional, so both updates wait for \
- the manager like every later one. Applies only to the arm64e.x1 \
- plugin (iOS 27.1's iPhone19,4); earlier builds are left byte-identical.
+ 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)),
@@ -651,11 +652,10 @@ public enum FirmwareGuestSystemPatchSet {
/// the virtio aggregate it already built.
public static let virtualAudioVolumeModePrecondition = "system-virtualaudio-cfw-volume_mode_precondition"
- /// The two gated device-state updates that read the DeviceStateManager
- /// singleton before deferred initialization publishes it, stood down so
- /// audiomxd cannot crash on the null singleton an arm64e.x1 guest is
- /// always asked about first.
- public static let virtualAudioDeviceStateGuard = "system-virtualaudio-cfw-device_state_guard"
+ /// The 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
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index 15bfdbd6..cd597237 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -273,7 +273,7 @@ public enum FirmwarePatchSetCatalog {
"system-systemhook-cfw-metal_cache_reuse",
"system-systemversion-cfw-build_version",
"system-virtiosound-cfw-hal_plugin",
- "system-virtualaudio-cfw-device_state_guard",
+ "system-virtualaudio-cfw-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/CustomFirmwareVirtualAudioTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift
index e5c5d603..9af2bac2 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift
@@ -300,7 +300,7 @@ struct CustomFirmwareVirtualAudioTests {
}
}
- // MARK: - Device-state guard
+ // MARK: - Device-state null gate
@Test(
arguments: [Self.junk, Data()],
@@ -308,7 +308,7 @@ struct CustomFirmwareVirtualAudioTests {
func `a binary without the singleton diagnostic is refused, not searched past`(_ input: Data) throws {
var data = input
#expect(throws: PatcherError.self) {
- try CustomFirmwareVirtualAudio.patchDeviceStateGuard(
+ try CustomFirmwareVirtualAudio.patchDeviceStateNullGate(
&data,
reattest: false,
dryRun: true,
@@ -318,9 +318,9 @@ struct CustomFirmwareVirtualAudioTests {
}
@Test
- func `the device-state anchor strings and record identity are stable`() {
+ func `the null-gate anchor strings and record identity are stable`() {
#expect(CustomFirmwareVirtualAudio.deviceStateInstanceMissing == "TheInstance() called before SetInstance()")
- #expect(CustomFirmwareVirtualAudio.deviceStateGuardPatchID == "system-virtualaudio-cfw-device_state_guard")
+ #expect(CustomFirmwareVirtualAudio.deviceStateNullGatePatchID == "system-virtualaudio-cfw-device_state_null_gate")
}
/// The arm64e.x1 header word iOS 27.1's plugin carries, and the plain
@@ -344,41 +344,35 @@ struct CustomFirmwareVirtualAudioTests {
#expect(CustomFirmwareVirtualAudio.arm64Subtype(of: Data()) == .notArm64)
}
- // A synthetic plugin carrying the guarded device-state shape: TheInstance
- // with its diagnostic reference, two gated updates, and the two callers
- // the shape must refuse — the haptic delegate's unguarded deref and a
- // caller that passes the singleton on. Every instruction comes from the
- // encoder or the frozen constants, and the layout is fixed so the gate,
- // call and skip addresses are the same in every test.
+ // 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 retab gate check, site 1
- // text+0x14 cbz w0, +0x20 the gate the patch rewrites
+ // 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+0x58 bl retab the haptic caller's release call
- // text+0x5c bl TheInstance unguarded: no gate above it
- // text+0x60 mov x20, x0
- // text+0x64 ldr x21, [x0]
- // text+0x68 nop
- // text+0x6c bl TheInstance pass-through caller: no deref after
- static let deviceStateTextStart = 0x108
- static let deviceStateGate1 = 0x11C
- static let deviceStateCall1 = 0x120
- static let deviceStateSkip1 = 0x13C
- static let deviceStateGate2 = 0x140
- static let deviceStateCall2 = 0x144
- static let deviceStateSkip2 = 0x160
- static let deviceStateHapticStart = 0x160
+ // 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 two mismatching
+ /// 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 {
@@ -391,15 +385,14 @@ struct CustomFirmwareVirtualAudioTests {
| UInt32(encoded[encoded.startIndex + 3]) << 24
}
- let theInstance = deviceStateTextStart
+ let theInstance = deviceStateText
let stub = theInstance + 0xC
func gatedSite(start: Int) throws -> [UInt32] {
- let gate = start + 4
let call = start + 8
let skip = call + 0x1C
return [
try word(ARM64Encoder.encodeBL(from: start, to: stub)),
- try word(ARM64Encoder.encodeCompareBranch(nonzero: false, register: 0, from: gate, to: skip)),
+ try word(ARM64Encoder.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)),
@@ -414,17 +407,12 @@ struct CustomFirmwareVirtualAudioTests {
ARM64.retabU32,
]
for index in 0 ..< gatedSites {
- code += try gatedSite(start: deviceStateTextStart + 0x10 + index * 0x24)
- // The gap word the 0x24 spacing runs through — a call, like the
- // release call the real haptic site carries above its own.
- let gap = deviceStateTextStart + 0x30 + index * 0x24
- code += [try word(ARM64Encoder.encodeBL(from: gap, to: stub))]
+ 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, not a gate; then a
- // caller that passes the singleton on instead of reading it, closed
- // by two nops so the scan reads deterministic words past it.
- let haptic = deviceStateHapticStart
+ // 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)),
@@ -434,17 +422,26 @@ struct CustomFirmwareVirtualAudioTests {
try word(ARM64Encoder.encodeBL(from: haptic + 0x14, to: theInstance)),
ARM64.nopU32, ARM64.nopU32,
]
- return pluginImage(cpuSubtype: cpuSubtype, text: code)
+ 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 the
- /// singleton's diagnostic as __cstring at 0x2000.
- static func pluginImage(cpuSubtype: UInt32, text: [UInt32]) -> Data {
+ /// __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
- let diagnostic = Array("TheInstance() called before SetInstance()\0".utf8)
- let total = cstringOffset + diagnostic.count
+ 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)
@@ -466,58 +463,50 @@ struct CustomFirmwareVirtualAudioTests {
command += word32([UInt32(textOffset), 2, 0, 0, 0x8000_0400, 0, 0, 0])
// __cstring
command += padded("__cstring") + padded("__TEXT")
- command += word64([0x2000, UInt64(diagnostic.count)])
+ command += 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 += diagnostic
+ image += cstringBytes
image += Array(repeating: 0, count: total - image.count)
return Data(image)
}
- private static func word(_ data: Data, _ offset: Int) -> UInt32? {
- guard offset + 4 <= data.count else { return nil }
- return UInt32(data[data.startIndex + offset])
- | UInt32(data[data.startIndex + offset + 1]) << 8
- | UInt32(data[data.startIndex + offset + 2]) << 16
- | UInt32(data[data.startIndex + offset + 3]) << 24
- }
-
@Test
- func `the guard rewrites exactly the two gates and is idempotent`() throws {
+ 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.patchDeviceStateGuard(
+ 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.deviceStateGuardPatchID,
- CustomFirmwareVirtualAudio.deviceStateGuardPatchID,
+ CustomFirmwareVirtualAudio.deviceStateNullGatePatchID,
+ CustomFirmwareVirtualAudio.deviceStateNullGatePatchID,
+ ])
+ #expect(report.theInstanceVMA == UInt64(Self.deviceStateText))
+ #expect(report.sites.map(\.gateCallVMA) == [
+ UInt64(Self.deviceStateGateCall1), UInt64(Self.deviceStateGateCall2),
])
- // Each gate's `cbz w0` became an unconditional `b` to its own skip;
- // every byte that moved lies inside a gate's word. (The two words can
- // share a byte — both hold 0x00 in their high half — so the count is
- // not the whole test.)
+ // 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)
- let gates = [(Self.deviceStateGate1, Self.deviceStateSkip1), (Self.deviceStateGate2, Self.deviceStateSkip2)]
- #expect(changed.allSatisfy { offset in gates.contains { gate, _ in gate <= offset && offset < gate + 4 } })
- for (gate, skip) in gates {
- let branch = try #require(ARM64Encoder.encodeB(from: gate, to: skip))
- #expect(Data(data[gate ..< gate + 4]) == branch)
- let patchedWord = try #require(Self.word(data, gate))
- #expect(ARM64Encoder.decodeBranchTarget(insn: patchedWord, pc: UInt64(gate)) == UInt64(skip))
+ #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 branches and writes nothing.
+ // A second run recognises its own redirects and writes nothing.
let once = data
- let again = try CustomFirmwareVirtualAudio.patchDeviceStateGuard(
+ let again = try CustomFirmwareVirtualAudio.patchDeviceStateNullGate(
&data, reattest: false, dryRun: false, log: nil,
)
#expect(again.outcome == .alreadyPatched)
@@ -529,22 +518,22 @@ struct CustomFirmwareVirtualAudioTests {
func `a dry run locates both sites and writes nothing`() throws {
var data = try Self.deviceStateImage(cpuSubtype: Self.x1Subtype)
let pristine = data
- let report = try CustomFirmwareVirtualAudio.patchDeviceStateGuard(
+ 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(\.gateVMA) == [UInt64(Self.deviceStateGate1), UInt64(Self.deviceStateGate2)])
- #expect(report.sites.map(\.skipTargetVMA) == [UInt64(Self.deviceStateSkip1), UInt64(Self.deviceStateSkip2)])
- #expect(report.theInstanceVMA == UInt64(Self.deviceStateTextStart))
+ #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.patchDeviceStateGuard(
+ let report = try CustomFirmwareVirtualAudio.patchDeviceStateNullGate(
&data, reattest: false, dryRun: false, log: nil,
)
#expect(report.outcome == .notArm64EX1)
@@ -558,7 +547,7 @@ struct CustomFirmwareVirtualAudioTests {
var data = try Self.deviceStateImage(cpuSubtype: Self.x1Subtype, gatedSites: 1)
let pristine = data
#expect(throws: PatcherError.self) {
- try CustomFirmwareVirtualAudio.patchDeviceStateGuard(
+ try CustomFirmwareVirtualAudio.patchDeviceStateNullGate(
&data, reattest: false, dryRun: false, log: nil,
)
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index 94a3f448..d3aff87d 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -1771,14 +1771,14 @@ struct VPhoneCustomFirmwareInstaller {
// The VirtualAudio HAL plugin: five sub-patches ride one staged copy
// (`patchMachO` stages from the pristine backup, so two calls would not
// compose). On when any is on; reverted from `.bak` when all are off.
- // The device-state guard reports "nothing to do" on the non-X1
+ // 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.virtualAudioDeviceStateGuard, "patch-virtualaudio-device-state-guard"),
+ (FirmwareGuestSystemPatchSet.virtualAudioDeviceStateNullGate, "patch-virtualaudio-device-state-null-gate"),
]
let virtualAudioBundle = "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin"
let virtualAudioBinary = "\(virtualAudioBundle)/VirtualAudio"
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
index 375bae84..8d252559 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
@@ -490,47 +490,52 @@ struct VPhoneCustomFirmwarePatchVirtualAudioVolumeGateCommand: ParsableCommand {
}
}
-// MARK: - patch-virtualaudio-device-state-guard
+// MARK: - patch-virtualaudio-device-state-null-gate
-struct VPhoneCustomFirmwarePatchVirtualAudioDeviceStateGuardCommand: ParsableCommand {
+struct VPhoneCustomFirmwarePatchVirtualAudioDeviceStateNullGateCommand: ParsableCommand {
static let configuration = CommandConfiguration(
- commandName: "patch-virtualaudio-device-state-guard",
- abstract: "Keep VirtualAudio's device-state updates off the null DeviceStateManager singleton",
+ 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 — but the
- manager's singleton is published only at the end of deferred
- initialization, which first waits for a haptic actuator port a VM
- does not have. Asked earlier, the singleton's accessor logs
- "TheInstance() called before SetInstance()", returns null, and the
- update dereferences it: audiomxd crash-loops seconds after every
- launch on an arm64e.x1 guest once the speaker-route patches let
- the route through.
-
- The patch stands the two device-state updates down. Each sits
- behind its own gate — a capability check whose `cbz w0` already
- skips the whole update when the check answers false — and that
- branch is made unconditional, to the same target. The gate-check
- call keeps running; its answer is no longer read. After deferred
- initialization completes, the singleton exists and every later
- update reaches the manager.
-
- The sites are anchored on the singleton's own diagnostic string,
- whose reference lives inside the accessor; every direct call to it
- is then filtered to the gated shape both updates share — the
- gate-check call, its `cbz w0` skipping forward past the update, the
- singleton's return moved aside, and that return dereferenced
- unchecked. Exactly two callers carry the shape; both are
- rewritten. No address is literal.
+ 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.
+ iPhone19,4). Every other build is reported and left
+ byte-identical, and the verb still exits 0: the install shares
+ one staged copy between all five VirtualAudio patches, and the
+ earlier builds are meant to keep their bytes.
- Idempotent: a gate already holding the unconditional skip is
- reported and left alone, byte for byte.
+ Idempotent: a gate slot already calling TheInstance is reported
+ and left alone, byte for byte.
""",
)
@@ -543,7 +548,7 @@ struct VPhoneCustomFirmwarePatchVirtualAudioDeviceStateGuardCommand: ParsableCom
func run() throws {
try requireUntruncatedMachO(at: binary)
// reattest: false — the caller re-signs.
- try CustomFirmwareVirtualAudio.patchDeviceStateGuard(
+ try CustomFirmwareVirtualAudio.patchDeviceStateNullGate(
fileAt: binary,
reattest: false,
dryRun: dryRun,
@@ -552,6 +557,7 @@ struct VPhoneCustomFirmwarePatchVirtualAudioDeviceStateGuardCommand: ParsableCom
}
}
+// MARK: - patch-virtualaudio
// MARK: - patch-virtualaudio
struct VPhoneCustomFirmwarePatchVirtualAudioCommand: ParsableCommand {
@@ -649,7 +655,7 @@ enum VPhoneCustomFirmwareMachOVerbs {
VPhoneCustomFirmwarePatchVirtualAudioMuteCommand.self,
VPhoneCustomFirmwarePatchVirtualAudioSPGateCommand.self,
VPhoneCustomFirmwarePatchVirtualAudioVolumeGateCommand.self,
- VPhoneCustomFirmwarePatchVirtualAudioDeviceStateGuardCommand.self,
+ VPhoneCustomFirmwarePatchVirtualAudioDeviceStateNullGateCommand.self,
VPhoneCustomFirmwarePatchParavirtGPUIndexOffsetCommand.self,
]
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
index 0335d759..b730589e 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
@@ -135,7 +135,7 @@
<string>system-virtualaudio-cfw-speaker_raw_chains</string>
<string>system-virtualaudio-cfw-speaker_route_throws</string>
<string>system-virtualaudio-cfw-volume_mode_precondition</string>
- <string>system-virtualaudio-cfw-device_state_guard</string>
+ <string>system-virtualaudio-cfw-device_state_null_gate</string>
<string>system-dyld-exp-tv_tpro</string>
<string>kernel-exp-tv_tpro_pagers</string>
</array>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
index bb790b23..5c6389af 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
@@ -133,7 +133,7 @@
<string>system-systemhook-cfw-metal_cache_reuse</string>
<string>system-systemversion-cfw-build_version</string>
<string>system-virtiosound-cfw-hal_plugin</string>
- <string>system-virtualaudio-cfw-device_state_guard</string>
+ <string>system-virtualaudio-cfw-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 74647695..1fbecf8a 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
@@ -138,7 +138,7 @@
<string>system-systemhook-cfw-metal_cache_reuse</string>
<string>system-systemversion-cfw-build_version</string>
<string>system-virtiosound-cfw-hal_plugin</string>
- <string>system-virtualaudio-cfw-device_state_guard</string>
+ <string>system-virtualaudio-cfw-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>