Run a virtual iPhone on an Apple Silicon Mac.
Swift
Play guest audio through virtio-snd (work in progress)
Jacky9ad39f1c2298
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex ec3ead6f..82fa22e5 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -19,7 +19,7 @@> three `hv_vmm_present` concealment patches, and the iPhone17,3 identity rewrites;> `extended` blocks nothing.>-> **iPad guests (2026-10-01; every current iPad 2026-10-02):** four DeviceTree+> **iPad guests (2026-10-01; every current iPad 2026-10-02):** five DeviceTree> patches, on in `standard`, exist only for a VM whose userland comes from an> iPad restore IPSW (iPad mini A17 Pro, iPad A16, iPad Air M3 11/13, iPad Pro> M4 and M5 11/13 — see `VPhoneGuestDevice.known`). Since 2026-10-02 their@@ -27,8 +27,9 @@> `DeviceTree.<board>.im4p` in the restore tree rather than a table, so an> M-series board keeps Stage Manager (no `disable-chamois`) and the iPad (A16)> has no `medusa-overlay-app-capability`: `devicetree-cfw-ipad_artwork`,-> `devicetree-cfw-ipad_product`, `devicetree-cfw-ipad_buttons` and-> `devicetree-cfw-ipad_identity`. They are written to a second device tree,+> `devicetree-cfw-ipad_product`, `devicetree-cfw-ipad_buttons`,+> `devicetree-cfw-ipad_identity` and (2026-10-02) `devicetree-cfw-ipad_audio`,+> which takes the board's `/product/audio` node. They are written to a second device tree,> `Firmware/all_flash/DeviceTree.vphone600ap.guest.im4p`, which `fw prepare`> copies from the vphone600 one and the hybrid manifest names as `DeviceTree`;> `RestoreDeviceTree` keeps pointing at the original, so restore still boots@@ -1095,7 +1096,7 @@ header.| # | Target | Framework | Effect ||---|---|---|---|| 1 | `+[_NUStyleTransfer{,Apply,Thumbnail,Learn,Interpolate}Processor processWithInputs:arguments:output:error:]` (5 entry points) | NeutrinoCore | Each replaced with `mov w0, #0; ret`. Camera's CIImageProcessorKernel chain that drives the style preview thumbnails short-circuits before reaching `+[_NUStyleEngine usingSharedStyleEngineForUsage:...]` → `_NUStyleEngineMemoryResource initWithDevice:descriptor:` which would otherwise assert on a nil descriptor (root cause is an upstream ANE-detection gate in `CMIStyleEngineCommonSettings`; we workaround at the consumer instead of unblocking it). |-| 2 | `+[AVCaptureDevice authorizationStatusForMediaType:]` | AVFCapture | Replaced with `mov w0, #3; ret` (AVAuthorizationStatusAuthorized = 3). Any process probing camera/audio/etc. media-type authorization gets "Authorized" without going through TCC. Stage 0 of the vcam stack — makes apps stop bailing on the auth check. Audio still doesn't work on the VM, so the broader scope is harmless (audio consumers would have failed downstream regardless). Downstream pipeline (cameracaptured rewrite, vcamd daemon) still owed for actual frame delivery. |+| 2 | `+[AVCaptureDevice authorizationStatusForMediaType:]` | AVFCapture | Replaced with `mov w0, #3; ret` (AVAuthorizationStatusAuthorized = 3). Any process probing camera/audio/etc. media-type authorization gets "Authorized" without going through TCC. Stage 0 of the vcam stack — makes apps stop bailing on the auth check. Audio capture still does not work on the VM (the virtio sound driver added 2026-10-02 is output only), so the broader scope is harmless (audio-capture consumers fail downstream regardless). Downstream pipeline (cameracaptured rewrite, vcamd daemon) still owed for actual frame delivery. |Wired into `cfw_install_exp.sh` immediately after the hv_vmm DSC step,inside the same `hdiutil attach` block (one mount/unmount per install).@@ -1162,7 +1163,7 @@ sibling nodes to `/product/camera`. vphone600 has none of them.| Node | Props | Camera relevance ||------|:-----:|------------------|| `/product/facetime` | 9 (excl. AAPL,phandle) | Front-camera video-call config — bitrates, codec encoding/decoding, tnr-mode-back/front. |-| `/product/audio` | 31 (excl. AAPL,phandle) | Carries `supports-spatial-audio-capture=1` + `supports-spatial-facetime=1` (camera-joint). Rest is audio config. |+| `/product/audio` | 31 (excl. AAPL,phandle; an iPad guest takes its board's node instead, see "Guest audio" 2026-10-02) | Carries `supports-spatial-audio-capture=1` + `supports-spatial-facetime=1` (camera-joint). Rest is audio config. || `/product/iopm` | 2 (excl. AAPL,phandle) | `aot-mode=13` + `aot-linger-time-ms=0`. Always-On Technology mode. |All property values copied byte-for-byte from@@ -2210,3 +2211,256 @@ early-exiting grep and awk closed their file/vtool producers under pipefail.Those probes now drain producer output while keeping matching, first-platformselection, failure propagation, and all signature checks. The full workspacebuild and strict signatures then passed.++## Guest audio: a HAL plugin, and an iPad's own audio node (2026-10-02)++The guest never produced sound, although `vphone-vm` has always attached a+virtio sound device with a host output sink. Two faults; the full reveal is+`Research/Guest/virtio_sound.md`.++| Patch | Component | Effect |+| --- | --- | --- |+| `system-virtiosound-cfw-hal_plugin` (new) | `/System/Library/Audio/Plug-Ins/HAL/VPhoneVirtIOSound.driver`, `cfw install` and `cfw update-environment` | Installs the CoreAudio HAL plugin for `AppleVirtIOSound`, built from `VPhoneGuestComponents/VirtIOSound`. |+| `devicetree-cfw-ipad_audio` (new) | An iPad guest's installed DeviceTree, `fw patch` | Replaces `/product/audio` with the board tree's node (`DeviceTreePatcher.presentBoardAudio`), all properties as the board has them except its `AAPL,phandle`. |+| `preboot-cfw-devicetree_board_audio` (new) | Restored Preboot `devicetree.img4`, `cfw install` and `cfw update-environment` | The same replacement for an iPad VM patched before it (`vphone-cli cfw patch-dt-board-audio`), from the board tree in `FirmwareOriginals`. |++`fw patch` now reads an iPad's board tree through the `FirmwareOriginals` stash,+so `DeviceTree.<board>.im4p` stays in the VM folder after the restore tree goes.++**Why a plugin.** The cloudOS kernel has `AppleVirtIOSound` and its user client,+but only macOS ships the HAL plugin that drives it; neither cloudOS nor any iOS+image has one. `VPhoneVirtIOSound.driver` speaks the same user-client selectors+as the macOS `AppleVirtIOSound.driver`, on AudioServerDriver as Apple's own+plugins are. It is output only. Its host checks are `make -C VPhoneGuestComponents+test-virtiosound`; `Build/ValidateBundle.sh` checks the staged bundle's signature+and factory.++**Why the audio node.** On an iPad guest VirtualAudio never initialized+(`RoutingSettings_J98.cpp:805`, then `:856`, `PRECONDITION FAILURE`), so audiomxd+had no device at all and Safari video would not start. J820's routing code builds+its stereo and webcam microphone sub-ports from the tuning directory the device+tree's `acoustic-id` names. `devicetree-cfw-product_audio_node` gives every guest+the D47 iPhone's node, `acoustic-id = 8018`; the iPhone image ships `AID8018`, the+iPad image ships `AID2028`/`AID2029` (J820's is 2029). Removing the+`stereo-sound-recording` flag was tried first and only moved the failure to the+webcam sub-port, whose flag comes from AVFCapture's per-board table; that attempt+is not in the tree. iPhone guests are unchanged.++**system-virtualaudio-cfw-speaker_route_throws.** The counterweight to the+virtio plugin's `PuffinOutput` masquerade. iOS's speaker-route walker treats+the synthetic speaker's missing protection metadata as fatal six different+ways — five C++ throws out of an AudioServerPlugIn callback (terminate) and+one direct `bl std::terminate` after a fault log — and MediaExperience's+serialization replay hits the first of them on every launch. The patcher+(`FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/`) branches+each site to the function's own epilogue: anchored on the exception strings,+shape-matched through Capstone (allocation call, x1 message load, constructor+call, `brk` or branch terminator; the terminate as the last call of the fault+logger's back-to-back `bl` run), never an offset. The installer stage re-seals+the `.plugin` bundle after `patchMachO` re-signs the binary — the outer+CodeResources still named the old bytes, and the code-signing monitor killed+audiomxd on load. Research detail: `Research/Guest/virtualaudio_speaker_route_throws.md`.++## VirtualAudio's mute-set throw — the chime's last blocker (2026-10-03)++`system-virtualaudio-cfw-mute_set_throw` (new), same+`VirtualAudio.plugin` binary, verb `cfw patch-virtualaudio-mute`, applied by+`cfw install` and `cfw update-environment` riding the same `patchMachO`+staged copy as `patch-virtualaudio` — staging restarts from the pristine+`.bak`, so the two verbs must share one call.++**Fault.** Establishing the speaker route asks the HAL device itself to+unmute: `Device_HAL_Common`'s set wrapper pushes `kAudioDevicePropertyMute`+('mute'/'outp'/0) and reads it back. The HAL *server* pre-validates the+device-level set at `HALS_UCPlugIn.cpp:1190` and rejects it 'what'+(2003329396) without ever forwarding the selector to the plugin — proven by a+guest probe whose `hasProperty:` override saw 60 selectors and never 'mute',+while the control-level 'bcvl' set on the same device succeeds (so no+plugin-side fix exists on iOS). The wrapper answers the failure by throwing+`CAException("Unable to set property data.")` out of the callback;+`RoutingManager.cpp:3515` catches it and abandons the route — the aggregate's+master stays `Null_Device`, no `PVMSetCurrentState`, and the boot charge chime+is silent. Every caller ignores the wrapper's return value, so the fix is the+same shape as the walker patch: branch the throw to the wrapper's own+epilogue. The FAIL/EXCEPTION diagnostics still log; the route proceeds.++**Reveal** (all Capstone-decoded, no literal address): anchor on the cstring+containing `Set mute value of %u on HAL device`, referenced exactly once in+`__text`; the wrapper is the enclosing pacibsp-to-pacibsp function. The site+is the wrapper's CAException block — allocation call, vtable/status stores+into `[x0]`/`[x0, #8]`, throw call, `brk` terminator; a CAException carries no+message string, so the walker patch's runtime_error shape does not match, and+the block runs 17 instructions where that scan budgeted 16 (the new scan+budgets 32). Discriminated from iOS 27's second, unrelated CAException (the+deactivated-device throw) by requiring an adrp+add forming a cstring+containing `Unable to set property data.` within 0x40 bytes above the site —+the EXCEPTION log that always precedes this throw. The epilogue is the+wrapper's single `retab` walked back through the shared guarded-canary chain;+it cannot be searched forwards from the throw because the throw sits below+the epilogue, so the retab is enumerated within the wrapper's bounds.+Verified on the real iPadOS 26.6.2 and iOS 27 binaries: exactly one site and+epilogue each (0xee224 → 0xedfcc; 0x111ac8 → 0x11179c), byte-identical+re-runs, and both verbs composing on one copy. Research detail:+`Research/Guest/virtualaudio_speaker_route_throws.md`.++## VirtualAudio's SpeakerProtection chain — the speaker route's last blocker (2026-10-03)++`system-virtualaudio-cfw-speaker_graph_chains` (new), *not* a binary patch:+it rewrites the tuning set's `graph_configurations.plist` on the guest system+volume (`/Library/Audio/Tunings/<acoustic ID>/VAD/`, e.g. `AID2029` for an+iPad Pro 13; the ID varies by board, so `cfw install` and+`cfw update-environment` walk the `Tunings` directory instead of naming one).+Verb `cfw patch-virtualaudio-graph-configurations` on a staged copy, format+preserved (binary in, binary out), idempotent. An image with no tuning sets —+iOS 27's VirtualAudio carries no `graph_configurations.plist` reference at+all — is skipped quietly. Patcher:+`FirmwarePatcher/CustomFirmware/CustomFirmwareVirtualAudioGraphConfigurations.swift`.++**Fault.** With the walker and mute-set throws quieted and+`ProductIDOverride=8010` (the only accepted ProductID whose VAD map covers+`'crnp'`, the RingtonePreview category), the ringtone route change runs its+full pipeline — route list built, aggregate master `PuffinOutput` — and then+dies building the route's DSP chain. `graph_configurations.plist` gives every+`speaker_*` configuration `chainType "clhs"`, and the DSP chain factory+(0x117628, iPadOS 26.6.2) switches on it: `clhs` builds the HAL+SpeakerProtection chain, whose config constructor (0x3dcccc) calls+`findDevice("Speaker")` (0x3dc460) → registry lookup →+`LockWeakPtrOrThrow` throws `Could not lock weak ptr (:60)` — a VM's device+registry has no physical Speaker. The chain is destroyed,+`RoutingManager.cpp:1774` logs `Failed to activate a route list`, the route+change fails `nort` (1852797556), and the guest stays silent with no+fallback. `dflt` — the chainType every `beam_mic_*`/`omni_mic_*`+configuration already ships — takes the generic graph chain instead: no+device lookup, the configuration's `graph` DSP file (which the tuning set+ships for every speaker configuration) is loaded directly. The patch flips+every `speaker_*` entry's `chainType` from `clhs` to `dflt` and touches+nothing else. Static analysis ruled out every null-tolerant patch of+`findDevice` itself: `buildParams` (0x3dc518) dereferences the returned+`Device*` immediately at two call sites (0x3dcda4, 0x1182a4), so a null+return would crash instead of degrade. Research detail:+`Research/Guest/virtualaudio_speaker_route_throws.md`.++## VirtualAudio's speaker-protection gate — the decline after the build (2026-10-03)++`system-virtualaudio-cfw-speaker_protection_gate` (new), same+`VirtualAudio.plugin` binary, verb `cfw patch-virtualaudio-sp-gate`, riding+the same `patchMachO` staged copy as the other two VirtualAudio verbs+(`patch-virtualaudio`, `patch-virtualaudio-mute`) in both `cfw install` and+`cfw update-environment`. Patcher:+`FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift`.++**Fault.** With layers 1–3a quieted (walker throws, mute-set throw, plist+chains), the ringtone route change still declines at its last step:+`RoutingHandler_Playback_GenericConfig1.cpp:223` — "HAL Speaker Protection is+missing. Failing route %s" — because the route's device list calls for HAL+Speaker Protection, a capability only a physical codec reports. The route is+*finished* when the decline lands: virtual stream on `pspk` at the matched+rate, the `dflt` DSP chain built, IOProc cache warm. The capability query+never leaves VirtualAudio — the ASD plugin's file logs show 0 'caps'+selectors reaching it — so no plugin-side fix exists. The handler's failure+path puts the vdef's output stream on `Null_Device`: a StartIO "Running"+signature still appears (on `Null_Device`, `VAD [vdef] AggDev 8`), which is+how an earlier validation was fooled; the audible era's signature is StartIO+on the `PuffinOutput` aggregate (`AggDev 2`). The guest is completely silent+and the volume is dead.++**Reveal** (all Capstone-decoded, no literal address): anchored on the+cstring containing `HAL Speaker Protection is missing. Failing route` — a+format three routing handlers share — and discriminated by requiring the+enclosing pacibsp-to-pacibsp function to also reference+`RoutingHandler_Playback_GenericConfig1.cpp`. Within that one handler, the+gate is the branch whose forward target heads the log block: a target at or+above which, within 0x100, the format's adrp+add sits, and the file name's+adrp+add too (both builds hold them 0x34 apart, 0x84 above the block's+entry), and whose target opens the os_log allocation itself (`mov w0,+#<size>` followed by the allocation call). That last shape check is what+kills the near miss: iOS 27 holds a `cbz x0, 0x146360` whose target lands+0xC4 below the format ref, inside the string window but on a `sub`, not a+block head. The scan decodes each word rather than trusting Capstone's jump+group — the gate is a `tbz` (`tbz w21, #0` on 26.6.2, `tbz w19, #0` on+iOS 27), which the group tagging misses — through+`decodeConditionalBranchTarget`, which reads the 19-bit immediates of+`b.cond`/`cbz`/`cbnz` and the 14-bit one of `tbz`/`tbnz`, sign-extended.++**The write.** The gate's branch is left untouched — that is what lets the+anchor resolve the site again on an already-patched binary. What changes is+the log block's own entry: the `mov w0, #0x14` opening the os_log becomes a+`b` back to the gate's fall-through, so a taken gate lands directly on the+success continuation the handler already built. Verified on both builds+that the fall-through never re-reads the register the gate tested (w21 /+w19), so no stale verdict flows on. The block is entered only by the gate's+jump — the instruction above the head is an unconditional branch on both+builds (`b 0x136d28` at 0x136874; `b 0x1467a0` at 0x14639c), checked before+anything is written, so rewriting the head orphans no fall-through.+Idempotency is exact, not marker-based: a re-run finds the head holding an+unconditional branch, decodes it, and requires its target to be the gate+site's own successor — a shape no compiler emits — before reporting+already-patched; a foreign branch at the head is an error, never+overwritten. Verified on the real iPadOS 26.6.2 and iOS 27 binaries: the+expected sites on both (gate 0x136620 → head 0x136878, fall-through+0x136624; gate 0x1460b4 → head 0x1463a0, fall-through 0x1460b8), writes+byte-identical on re-run, and all three VirtualAudio verbs composing on one+staged copy with a clean second pass. Research detail:+`Research/Guest/virtualaudio_speaker_route_throws.md`.++## VirtualAudio's volume-mode precondition — the decline after the gate (2026-10-03)++`system-virtualaudio-cfw-volume_mode_precondition` (new), same+`VirtualAudio.plugin` binary, verb `cfw patch-virtualaudio-volume-gate`,+riding the same `patchMachO` staged copy as the other three VirtualAudio+verbs in both `cfw install` and `cfw update-environment`. Patcher:+`FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift`+(the handler is resolved once for both gates, in `locatePlaybackHandler`).++**Fault.** With layers 1–3 quieted (walker throws, mute-set throw, plist+chains, speaker-protection gate), the same ringtone handler declines the+same finished route one step later, at+`RoutingHandler_Playback_GenericConfig1.cpp:252`: the route's+software-volume mode must be the packed pair+`(present, kHardwareOnlyReadOnly)` — present-flag in bit 32 over the+mode's low 32 bits, expected value `0x1_00000003`. The virtio plugin's+device reports `SoftwareHardwareMix`, so the precondition fails and the+handler *throws* a `std::logic_error` — unlike the SP gate's quiet+decline — which unwinds past the route's own teardown into+`RoutingManager.cpp:3520`: the route change fails `nort`, the session is+torn down onto `Null_Device`, and the guest is silent with the volume+dead. iPadOS 26.6.2 logs this as a bare "Precondition failure."; iOS 27+still carries the assert text+`softwareVolumeModeForPerDefaultScope.has_value() && softwareVolumeModeForPerDefaultScope.value() == VolumeControl::SoftwareVolumeMode::kHardwareOnlyReadOnly`,+which is what named the fault.++**Reveal** (all Capstone-decoded, no literal address). The handler is the+one `locatePlaybackHandler` already resolves for the SP gate — the+function holding both the `HAL Speaker Protection is missing. Failing+route` format and the `RoutingHandler_Playback_GenericConfig1.cpp` file+name. Within it, the guard chain reads: `bl` a wrapper (ActivationParams+check, else logs `Aspen.cpp:1428` and returns 0; on hit it calls a map+getter that logs `Aspen.cpp:1445/1451` and returns the packed 64-bit+map entry), then `and xN, xRet, #0x1ffffffff` — the 33-bit packing mask+— then `add x9, xBase, #1` building the expected pair, `cmp`, and a+`b.ne` to the decline. The decline's discriminator among the handler's+three `PRECONDITION FAILURE (std::logic_error)` blocks (`:142`, `:252`,+`:270`) plus the `Aspen.cpp:729` one is `isVolumeModeComparison`: within+six instructions below a non-call branch, a `cmp` seen, then an `and`+whose immediate operand is exactly `0x1ffffffff` and whose preceding+word is a call. The inner exception-allocation labels (`cbz x19` to a+`mov w0, #0x10` sizing) pass every block-shape check; it is the mask+window that rejects them. Block layout matches the SP gate's: the+format's adrp+add 0x58 above the head, the file name's 0x2c above, the+sole entry the guard's branch, and an unconditional branch at the+pre-head — checked before anything is written.++**The write.** The comparison and its `b.ne` are left untouched; the+decline's log-block head — the `mov w0, #0xe` sizing the os_log —+becomes a `b` back to the comparison's own fall-through, so a failed+precondition lands on the continuation the handler already built. The+fall-through reloads its inputs from memory and never re-reads the+tested value, on either build. Idempotency is the SP gate's exact scheme:+a re-run finds an unconditional branch at the head and requires it to+decode to the comparison site's own successor. Verified on the real+iPadOS 26.6.2 and iOS 27 binaries: the expected sites on both+(comparison `b.ne` 0x1369c4 → head 0x138124, fall-through 0x1369c8;+comparison 0x1464e0 → head 0x1475d0, fall-through 0x1464e4), byte-+identical re-runs, and all four VirtualAudio verbs composing on one+staged copy with a clean second pass. Research detail:+`Research/Guest/virtualaudio_speaker_route_throws.md`.diff --git a/Research/Guest/virtio_sound.md b/Research/Guest/virtio_sound.mdnew file mode 100644index 00000000..57ca8ed4--- /dev/null+++ b/Research/Guest/virtio_sound.md@@ -0,0 +1,402 @@+# Guest audio through virtio-snd++`vphone-vm` has always configured a `VZVirtioSoundDeviceConfiguration` with a+host output sink and a host input source+(`VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift`),+and the guest never played a sound through it. Two separate faults stood in the+way. Either one alone is enough to keep the guest silent.++## 1. Nothing in iOS drives the virtio sound device++The cloudOS kernelcache (`kernelcache.research.vphone600`) carries the kernel+half. `com.apple.driver.AppleVirtIO` has a personality matching virtio device+`0x19` (virtio-snd):++| Key | Value |+| --- | --- |+| `IOClass` | `AppleVirtIOSound` |+| `IOProviderClass` | `AppleVirtIOTransport` |+| `IOVirtIOPrimaryMatch` | `0x00191af4` |+| `IOUserClientClass` | `AppleVirtIOSoundUserClient` |++The userspace half is a CoreAudio HAL plugin, and only macOS has one:+`/System/Library/Audio/Plug-Ins/HAL/AppleVirtIOSound.driver` (factory+`AVIOPluginFactory`, classes `AVIOPlugin : ASDPlugin`, `AVIODevice :+ASDAudioDevice`, `AVIOStream : ASDStream`). The guest's+`/System/Library/Audio/Plug-Ins/HAL` holds `BuiltinAudioPlugin`, `AppleAOPAudioPlugin`,+Bluetooth, AirPlay and USB plugins and nothing for virtio. The cloudOS 26.4 system+image has no HAL plugins at all, and the iPhone 27.0 image has none for virtio+either (checked in each IPSW's `.dmg.aea.mtree`, which is plaintext once the+`pbze` chunks are decompressed).++### The user-client protocol++Read out of the macOS plugin's arm64e slice. Every selector forwards one+virtio-snd request, so the structures are the virtio specification's:++| Selector | Call | virtio-snd request |+| --- | --- | --- |+| 1 | `IOConnectCallMethod`: 1 scalar (stream ID) in, 32-byte struct out | `PCM_INFO` → `virtio_snd_pcm_info` |+| 3 | `IOConnectCallMethod`: 1 scalar in, 24-byte struct in | `PCM_SET_PARAMS` (`virtio_snd_pcm_set_params`; header left zero, the kernel fills it) |+| 4 | scalar | `PCM_PREPARE` |+| 5 | scalar | `PCM_START` |+| 6 | scalar | `PCM_STOP` |+| 7 | scalar | `PCM_RELEASE` |+| 8 | `IOConnectCallAsyncMethod`: 1 scalar in, the PCM bytes as the input struct | TX transfer |+| 9 | `IOConnectCallAsyncMethod`: 1 scalar in, the period buffer as the output struct | RX transfer |++The stream count is the `AVIOSoundStreamCountKey` property on the+`AppleVirtIOSound` service. Async references use three slots, with the callout+signed with the zero discriminator (`paciza`) as any C function pointer is on+arm64e. The macOS plugin sizes a period as a twelfth of a second rounded up to a+page, keeps twelve periods, flushes whole periods every 1/24 s on a dispatch+timer, and only lets the I/O thread reuse a region once its transfer has+completed. Its device clock is free running from `mach_absolute_time`, with a+timestamp period of `rate × 260 / 1000` frames and safety offsets of 100 frames.++### `VPhoneVirtIOSound.driver`++`VPhoneGuestComponents/VirtIOSound` is the iOS plugin built from that protocol.+It is written on AudioServerDriver, the private framework `BuiltinAudioPlugin`+itself uses on iOS (its log shows `ASD_Initialize`); the classes are declared in+`VPVirtIOSoundAudioServerDriver.h` and bound through `AudioServerDriver.tbd`.+It publishes one HAL device per `AppleVirtIOSound` service and one output stream+per virtio output stream, at the format the device offers (32-bit float, 48 kHz,+2 channels from `VZHostAudioOutputStreamSink`). Input streams are left out, so the+host microphone is never opened. The virtio stream is released when CoreAudio+stops and the last transfer has come back, so an idle guest does not keep the+host audio device running.++`cfw install` and `cfw update-environment` install it at+`/System/Library/Audio/Plug-Ins/HAL/VPhoneVirtIOSound.driver`+(`system-virtiosound-cfw-hal_plugin`).++Two optional values in the `com.apple.coreaudio` domain exist for routing work+and are read when audiomxd loads the plugin: `VPhoneVirtIOSoundTransportType`+(four characters, default `usb `) and `VPhoneVirtIOSoundDeviceUID`.++## 2. VirtualAudio never finished initializing (iPad guests)++Restarting `audiomxd` in an iPad guest (ipad-pro-13, iPad17,3 / J820, iPadOS+26.6.2) and reading its log shows the HAL loading `BuiltinAudioPlugin` fine and+then VirtualAudio, the routing layer in+`/Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin`, abort:++```+audio_dsp_manager Found device acousticID = 8018+audio_dsp_manager Device tuning directory not found: /Library/Audio/Tunings/AID8018+RoutingSettings_J98.cpp:804 Creating subport config for spatial recording+RoutingSettings_J98.cpp:805 PRECONDITION FAILURE (std::logic_error).+VirtualAudio_PlugIn.mm:2135 VA Init Status: 1+-CMVAEndptMgr- vaemGetVirtualAudioDeviceIDs: No Audio Device Available. This is a serious error.+```++and every later session request logs `VirtualAudio PlugIn is not initialized yet`.+With no VirtualAudio device there is no audio route at all, which is also why+YouTube and bilibili in Safari would not start playing.++### What the routing code expects++The J98 routing settings (`sub_47420c` in the 26.6.2 `VirtualAudio`) build one+microphone sub-port configuration per recording mode the device advertises, and+each builder (`0x4988c0` spatial, `0x498ae0` multicam, `0x498d00` webcam) throws+when its mode is advertised but the configuration was not built:++| Mode | Advertised by |+| --- | --- |+| Spatial (stereo) recording | `MGGetBoolAnswer("DeviceSupportsStereoAudioRecording")` (`0x477698`), which libMobileGestalt answers from the *presence* of `IODeviceTree:/product/audio/stereo-sound-recording` (a copy-property call tested for non-NULL; `0x186ff4ee8` → `0x186fcfb20` in the host's copy) |+| Webcam recording | `AVGestaltGetBoolAnswer(AVGQ3J3FEVOOCNOKKTK3XQPUQ47DYY)` (`0x4776bc`), byte `0x11` of AVFCapture's per-board capability table, set for `J817-J818-J820-J821` |++For these boards (product IDs 195 and 196) the routing code skips its own+input-processing path ("Input processing disabled", `RoutingSettings_J98.cpp:400`)+and builds the configurations from the tuning directory named by the device+tree's acoustic ID (`0x491738` onwards: `AU`, `VAD`, `…_mic_peripheral_sender_all_mics`).+A real J820 has `acoustic-id = 2029`, and the iPad image ships+`/Library/Audio/Tunings/AID2029` (and `AID2028`).++For these boards (product IDs 195 and 196) the routing code skips its own+input-processing path ("Input processing disabled", `RoutingSettings_J98.cpp:400`)+and builds the configurations from the tuning directory named by the device+tree's acoustic ID (`0x491738` onwards: `AU`, `VAD`, `…_mic_peripheral_sender_all_mics`).+A real J820 has `acoustic-id = 2029`, and the iPad image ships+`/Library/Audio/Tunings/AID2029` (and `AID2028`).++### Why the guest had the wrong acoustic ID++`devicetree-cfw-product_audio_node` adds the D47 iPhone's `/product/audio`,+whose `acoustic-id` is 8018. That is right for an iPhone guest — the iPhone image+ships `AID8018` and `D47` tunings — but the iPad identity patches copy `/product`+properties from the iPad's own tree and never touched this child node, so an iPad+guest advertised J820's recording modes over tunings it does not have.++The first attempt here removed `stereo-sound-recording`. That cleared the first+failure, and the webcam builder failed next (`RoutingSettings_J98.cpp:855/856`).+The webcam answer comes from the board name itself, so the flags were never the+fault; the tuning directory was. That attempt is not in the tree.++### The fix++- `devicetree-cfw-ipad_audio`: for an iPad guest's installed tree, `fw patch`+ replaces `/product/audio` with the board tree's node+ (`DeviceTreePatcher.presentBoardAudio`): every property as the board has it,+ placeholders included, except the board's `AAPL,phandle`.+- `fw patch` now reads the board tree through the `FirmwareOriginals` stash, so a+ copy of `DeviceTree.<board>.im4p` stays in the VM folder after the restore tree+ is deleted.+- `preboot-cfw-devicetree_board_audio`: `cfw install` and `cfw update-environment`+ apply the same replacement to the restored Preboot `devicetree.img4`+ (`vphone-cli cfw patch-dt-board-audio <devicetree.img4> <board.im4p>`), taking+ the board tree from `FirmwareOriginals`. An iPad VM patched before this has no+ copy there; put the board's `DeviceTree.<board>.im4p` from its IPSW into+ `FirmwareOriginals/<restore tree>/Firmware/all_flash/` and run the environment+ update. An iPhone guest has no board tree there and is left alone.++## 3. Inside the precondition failure (follow-up session, 2026-10-02)++The acoustic-ID fix (§2) holds — a fresh `audiomxd` restart on ipad-pro-13 logs+`Found device acousticID = 2029` and loads the AID2029 configuration — but+`RoutingSettings_J98.cpp:805` still throws. ipad-mini-01 (J410, also iOS 26.6.2,+its own AID8018 present) fails at the same line, and pcc-research-01 (iPhone17,3,+iOS 27) fails at the analogous `RoutingSettings_N71.cpp:1167`. In all three:++```+PlatformUtilities_Aspen.mm:154 ProductID to int is: 195|196+RoutingSettings_{N71:1073|J98:400} Input processing disabled+RoutingSettings_{N71:1166|J98:804} Creating subport config for spatial recording+RoutingSettings_{N71:1167|J98:805} PRECONDITION FAILURE (std::logic_error).+VirtualAudio_PlugIn.mm PlugIn initialized ? 1 / VA Init Status: 1+```++`PlatformUtilities` ProductID 195 selects the N71 (iPhone) routing settings,+196 the J98 (iPad) ones — every current iPhone and iPad guest walks the+"input processing disabled" path, and on that path the spatial sub-port+configuration is never built while the mode is advertised, so the builder+throws and VirtualAudio never initializes. Since real hardware takes the same+ProductID branch, something the VM lacks — not the branch itself — keeps the+configuration from being built there.++### Disassembled mechanics (iPadOS 26.6.2 plugin, offsets in the file)++`/Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio` is a standalone+arm64e Mach-O with its local symbol table intact — pulled from the running+guest with `files.read` (7,356,608 B; saved with the iOS 27 copy in+`~/.vphone/va-analysis/`). `otool -tV` on it gives:++* The three builders (`0x4988c0` spatial, `0x498ae0` multicam, `0x498d00`+ webcam) all follow one shape: if the mode is not advertised (`tbz w0,#0`)+ return NULL quietly; if it is advertised but `*(this->subportConfig)` is+ NULL (`ldr x8,[x19]; cbz x8`), log at J98.cpp:805 and throw+ `std::logic_error("Precondition failure.")`.+* The subport-config slots are constructor locals at `sp+0x1a70/0x1a78/0x1a80`+ (webcam/multicam/spatial), zeroed at `0x47452c-0x474548`.+* Advertisement inputs: `x24 = MGGetBoolAnswer(DeviceSupportsStereoAudioRecording)`+ captured at `0x47769c`, webcam answer stored `[sp+0xf8]` at `0x4776c0`;+ both feed the guard-dispatcher at `0x477c80…` (one-shot flags+ `0x6fc468…0x6fc4b8`) which calls the three builders at `0x4938c8`,+ `0x493914`, `0x493960`.+* Config-building blocks for the three modes do exist in the constructor+ (`0x48ee24` spatial → stores the slot at `0x48ef94`, `0x48f04c` multicam,+ web-cam variant near `0x48f378`, second multicam/webcam variants at+ `0x4916b0`/`0x491a78`). They look the configuration names up in the+ `graph_configurations.plist` database through `0x4d8be0` (misses log+ `DSPGraphConfig_Utilities.cpp:437 Graph collection missing expected key`+ and zero the output — that message never appears in any guest log).+* What was **not** found statically: the branch chain on the+ "input processing disabled" path that is supposed to fill the three slots+ before the guard-dispatcher runs. The obvious build blocks are reached from+ `0x4776f8 b.ne 0x48e8c4` — the branch for devices whose webcam is *not*+ advertised and whose ProductID is *not* 195/196. Manual tracing of the+ 180 KB constructor did not close the gap; instrumenting a patched copy of+ the plugin (below) is the fast way to see which path runs.++### What VirtualAudio does with our HAL device++Nothing, so far. Its `HALDeviceManager` processed only `Null_Device`+(`DeviceFactory.cpp:144 Unhandled UID "Null_Device"`); device 37+(`VPhoneVirtIOSound:0`) is activated by the HAL but never "[Added]" to+VirtualAudio. Setting `VPhoneVirtIOSoundTransportType` to `vrtc`+(kAudioDeviceTransportTypeVirtual) changed nothing. Physical devices reach+the factory through a creator registry (`unordered_map` at `0x6da2f8`,+lookup `0x1cf0f0`, dispatch `0xe0c8c-0xe0dcc`) that the routing settings+populate (the N71 mic builder at `0x2be594` registers per-mic creators, e.g.+`bottom_mic2`), so until init completes there is no built-in device for a+speaker route either — fixing playback needs both the throw fixed *and* the+virtio device registered in that registry.++### Ruled out++* **Tuning-directory naming.** The AID2029 directory is used where it should+ be; `graph_configurations.plist` (`CommonData`: `tuningPath =+ /Library/Audio/Tunings/AID2029/VAD`, `tuningFilePrefix = ""`) maps every+ mic mode to graphs that exist (`stereo_recording` → `stereo_recording_no_tap`,+ `spatial_video_recording`, `multicam` → `multicam`). The+ `/Library/Audio/Tunings/J820/VAD/v201_speaker_*.dspg` lookups that fail+ (`RoutingSettings_Aspen.cpp:3287/1870/1889`, loader `0x4283d4`, called from+ `0x4310dc` with chainType `'clhs'`) are non-fatal, and no image ships a+ `J820` directory, so real hardware fails them too — they are not the blocker.+* **Stale MobileGestalt cache.** The cache directory is empty (the previous+ session's deletion stuck); answers are computed live. Writing+ `com.apple.MobileGestalt.plist` (the file libMobileGestalt actually opens —+ it logs `Could not open …/com.apple.MobileGestalt.plist` when absent) with+ `CacheExtra {DeviceSupportsStereoAudioRecording: 0,+ AVGQ3J3FEVOOCNOKKTK3XQPUQ47DYY: 0}` did not change the outcome: the+ device-tree-backed answer bypasses `CacheExtra` (or the full+ `CacheData`/`CacheUUID`/`CacheVersion` schema is required — those key+ strings are in libMobileGestalt).+* **Our device's transport type.** `usb ` → `vrtc` made no difference (above).++## 4. Root cause found and fixed: `ProductIDOverride` (same session, evening)++The missing input was the **ProductID**. `PlatformUtilities_Aspen.mm` derives+it in this order (`0x2fa638` in the 26.6.2 plugin):++1. A defaults key, read by `RunTimeDefaults.mm`: **`ProductIDOverride` in the+ `com.apple.audio.virtualaudio` domain** (its own debug knob —+ `Defaults key ProductIDOverride was defined to %u`, `0x2fa638`).+2. A table lookup over a MobileGestalt class answer — table at `0x50cfd0` =+ `[195, 0, 196, 199, 0, 198]`. These five values are **simulator/research+ classes**: every one of them makes the routing constructor take its+ "input processing disabled" path (§3: `pid ∈ {195,196}` or the+ `DisableInputProcessing` default — *another* `RunTimeDefaults` key,+ `0x2735d8` — forces it), which never builds the spatial/multicam/webcam+ sub-port configurations, so the builders throw.+3. Real hardware never reaches that table: `MGGetProductType` (`0x9135c`)+ maps the actual model to a real ProductID, and for acoustic-id devices+ the id *is* the acoustic id (`Product with AcousticID '%d' is handled`,+ chip range 2025–2035 → the J-boards).++The vphone600 research platform lands on **196** ("iPad simulator"), which is+in the skip-set — hence every iPad guest threw at `RoutingSettings_J98.cpp:805`+and every iPhone guest at `RoutingSettings_N71.cpp:1167`, while real devices+never do.++### The fix++```+vphone-launchpad-cli guest rpc <machine> settings.set \+ '{"domain":"com.apple.audio.virtualaudio","key":"ProductIDOverride","value":198,"type":"int"}'+```++198 (`0xc6`) is one of Apple's own class values (the table's sixth entry) and+the only one that satisfies both gates found:++* not 195/196 → the J98 constructor builds the mode configurations+ (`Creating subport config for …` at :804/:816/:855 all run, no throw);+* accepted by `ActuatorSettingsFactory_Aspen.cpp:172`'s ProductID switch+ (`0x36d4f0`) — overriding to the acoustic id 2029 fixes routing but throws+ `Invalid Product Type` there, killing init a few lines later.++Verified live on both iPad guests (audiomxd restart): `PlugIn initialized ? 2`,+**`VA Init Status: 0`**, no exceptions, and the route comes up — `VirtualAudio_Device: type vdef; id 65 … agg dev "VAD [vdef] AggDev 1"`, the+`ap:ha:nd:of:fd:ev-screen`/AP ports publish, and a ringtone preview in+Settings ▸ 声效与触感反馈 ▸ 电话铃声 produces real `AQMEIO_HAL` output+activity. One benign exception remains (`noct`/`crng` category lookup in the+routing database — 198's route set is a simulator's).++## 5. The route to the virtio device exists — it is called `PuffinOutput`++With init fixed (§4), `VirtualAudio_PlugIn.mm` processes every HAL device and+its `DeviceFactory` creates a `PhysicalDevice` only for UIDs it knows. Two+tables in the 26.6.2 binary decide:++* a device filter allow-list at `0x6b4668` — `Null_Device`, `Actuator`,+ `Halogen`, `Hawking`, `Flicker`, `Penrose` (the "AllowOnlyNull" filter mode+ in `HALDeviceManager`);+* a per-UID handler table built in the `0xe002c` device-state handler —+ `PuffinOutput`, `Actuator`, `AOP Audio-1`, `HP16Mic`, `Digital Mic`,+ `DigitalMic`, `Mic`, `Hawking`, `Flicker`, `Penrose`, `Halogen`, …++`VPhoneVirtIOSoundDeviceUID` (the plugin's existing knob) renames our device,+so each family was tried live by restarting `audiomxd`:++| UID | Result |+| --- | --- |+| `VPhoneVirtIOSound:0` (default) | `Unhandled UID` — claimed by nothing |+| `Halogen` | PhysicalDevice created, publishes `plqi`/`plqo` (LDCM) ports |+| `Hawking` | publishes `phki` input port only (mic family) |+| `AOP Audio-1` | ASD binds dependencies (`IOPAudioLPMicDevice`, `IOPAudioIOBufferDevice`), rtaid Detector node, no output port |+| **`PuffinOutput`** | **`pspk` speaker port published, routable, and the VAD aggregate is built with `master = PuffinOutput`; the vdef's stream then binds `actual strm: id 38` — our virtio stream — with `associated ports: { pspk; PuffinOutput }`** |++"Puffin" is the Apple-silicon host-audio codec family, and the research+platform is exactly a virtual Apple-silicon Mac — which is why its built-in+output device name slots straight into the iOS routing tables.++### The remaining crash++Playing a ringtone with the `pspk` route deadlocks `audiomxd` within seconds:+CoreMedia's `MXInitialize → FigVAEndpointManagerCreate →+vaemCurrentRouteHasVolumeControlListenerGuts →+CMSMUtility_GetCurrentOutputPortAtIndex` blocks on a mutex held across the+`ASDTDeviceManager` background thread (`AudioServerDriver`'s device manager,+the same layer whose `ASDTDeviceManager: Started background thread.` line+appears in every boot), then abort()s — and the poisoned state makes every+subsequent `audiomxd` launch die the same way (17 crash reports,+`~/.vphone/va-analysis/crash2.json`). Deleting the UID preference alone does+not stop the loop; a **guest reboot clears it** (verified: `audiomxd` back,+`VA Init Status: 0`, no new crashes).++Likely cause, to confirm next session: a `pspk` speaker promises CoreMedia a+volume-capable output port (`VolumeControl.cpp: Device PuffinOutput does not+support hardware volume range property` is logged and tolerated, but the+listener then blocks). Our ASD device must answer the volume/port property+queries a Puffin output answers — implementable in the plugin with the same+`AudioServerDriver` API. One instrumented build of `VPhoneVirtIOSound.driver`+logging entry/exit of its property callbacks while the `pspk` route is up+will pinpoint the call that never returns.++The direction suggested earlier in §4 — publishing through the+AudioServerDriver layer like `BuiltinAudioPlugin` — is already what+`VPhoneVirtIOSound.driver` does; the masquerade-by-UID experiments above are+the cheap form of it, and implementing the missing volume/port property+callbacks is the completion of that path. The iOS 27 binary+(`VirtualAudio-ios27`) is saved for the N71-side port of the same fix.+++## Reveal and validation++1. Kernel side present: `strings` on the decompressed kernelcache shows the+ `AppleVirtIOSound` personality above.+2. Plugin loaded: `logs.syslog` for `audiomxd` shows+ `com.vphone.audio/virtiosound` lines `stream 0: 48000 Hz, 2 channels…` and+ `published 1 virtio sound device(s)`.+3. VirtualAudio initialized: with `ProductIDOverride = 198` set (§4), a+ restarted `audiomxd` logs `PlugIn initialized ? 2` / `VA Init Status: 0`,+ no `PRECONDITION FAILURE`, and no+ `VirtualAudio PlugIn is not initialized yet` when an app opens a session.+4. Sound on the host: audible. The speaker route needs three things beyond+ the plugin — `ProductIDOverride` (§4), the `PuffinOutput` UID (§5),+ `system-virtualaudio-cfw-speaker_route_throws` (§ above and+ `virtualaudio_speaker_route_throws.md`), and the zero-timestamp seed+ advancing with the timestamp (`VPClockZeroTimestamp`), without which the+ vdef's aggregate never establishes the device timeline and aborts the+ start with `nope`.+5. Hardware volume: the plugin answers the pspk route's volume queries with a+ real control set — dsrc selector ('ispk' "Speakers"), mute, volume — added+ from `halInitializeWithPluginHost:` after device init, before+ `addAudioDevice:`. Init-time `addControl:` fails the whole device+ activation (`HALS_PlugIn.cpp:162`); this lifecycle moment does not.+ Validated by staged isolation on ipad-pro-13 (2026-10-03): with+ `endpointTypeInfo` deleted, audiomxd restart, RingtonePreview playback,+ and a tone tap preview all left it absent — no more `Unspecified` rewrite+ — and `[volm/outp/0]` writes on the VAD succeed. Two constraints the+ controls themselves carry on iOS: construct them through the+ explicit-class initializers (`initWithValue:…andObjectClassID:` and the+ decibel twin), never the factories — the factories are state-dependent and+ returned the raw FourCharCode 'togl' as an `id`, crash-looping audiomxd —+ and never call `booleanValue` on the result (the getter is `value`;+ the selector does not exist and faults inside audiomxd). And the controls+ alone still do not give the device a mute property: iOS ASDAudioDevice's+ device-level dispatch has no 'mute' case at all, so+ `VPVirtIOSoundDevice` overrides the five ASD property methods and answers+ `kAudioDevicePropertyMute` from a shadow ivar, forwarding sets to the+ registered mute control (see the handoff in+ `virtualaudio_speaker_route_throws.md` for the disassembly).+6. Dual-rate (44100 ringtone previews): the device advertises+ `@[@44100, @48000]` and the 48 kHz stream carries a 44100 physical format;+ `setSamplingRate:`/`deviceChangedToSamplingRate:` move an atomic HAL rate+ under the mix block, which linearly resamples 44100→48000 onto the wire+ while the clock re-derives its period math. Verified booting and answering+ at both nominal rates — and disproven as the ringtone gate: a 44100-nominal+ boot fails the tone tap exactly like a 48000 one. The gate is the+ RingtonePreview category itself; see the session-5 section of+ `virtualaudio_speaker_route_throws.md`.diff --git a/Research/Guest/virtualaudio_speaker_route_throws.md b/Research/Guest/virtualaudio_speaker_route_throws.mdnew file mode 100644index 00000000..0d8c5fb3--- /dev/null+++ b/Research/Guest/virtualaudio_speaker_route_throws.md@@ -0,0 +1,672 @@+# VirtualAudio speaker-route throws — the patch that made audiomxd survive++`system-virtualaudio-cfw-speaker_route_throws` (declared in+`FirmwareGuestSystemPatchSet`, applied by `cfw install` and+`cfw update-environment` through `patchMachO`, verb `cfw patch-virtualaudio`).++## What the walker is++`VPhoneVirtIOSoundDriver`'s masquerade as `PuffinOutput` (§5 of+`virtio_sound.md`) publishes the guest's only `pspk` speaker port, which is+what makes the default route reach the virtio device at all. The price is+that VirtualAudio's speaker-route walker — the function that applies speaker+protection and the DSP chain when a property write touches the route, entered+from MediaExperience's VAD serialization listener on every launch and every+route change — meets a speaker whose protection metadata is not what a real+codec reports, and answers each surprise by killing the process:++| Site (iPadOS 26.6.2 / iOS 27) | Exception |+| --- | --- |+| 0x16ca74 / 0x172ffc | `runtime_error("No default VAD present")` |+| 0x16cf6c / 0x173580 | `runtime_error("Could not construct")` — behind the routing-mutex assertion |+| 0x16cfa8 / 0x1735bc | `runtime_error("Could not construct")` — the second one |+| 0x16d0b4 / 0x1736c4 | `runtime_error("Unexpected HAL speaker protection … *VP* speaker protection")` |+| 0x16d1d0 / — | `logic_error("Precondition failure.")` |+| 0x16d148 / 0x173828 | no exception — a direct `bl std::terminate` after the `Speaker Protection is not active on speaker route` fault log |++The five throws cross the AudioServerPlugIn C boundary, reach+`std::terminate`, and abort audiomxd; the saved serialization state replays+the same write into every launch, so one abort is a crash loop. The terminate+needs no exception at all. None of the six sites is reachable on real+hardware, where the built-in speaker is a codec this code grew up with.++## What the patch does++Every site's first instruction is replaced with a branch to the function's+own epilogue, so each fatal condition degrades to "apply nothing and+return". The diagnostic logs stay. Sites are found by shape, never by+offset:++* the walker is anchored on the `No default VAD present` string — exactly one+ adrp+add materialises the bare message (the exception constructor's x1);+ a second reference to a longer format string containing the message must+ corroborate it above the throw;+* the throw blocks are `mov w0, #<size>` + `bl ___cxa_allocate_exception` ++ a message load into x1 + a constructor call, closed by an unconditional+ branch or a `brk` (iOS 26 builds end with `bl ___cxa_throw` + branch, iOS+ 27 tail-calls the throw and one block ends in `brk #1` — the scan takes+ both);+* the terminate is anchored on `Speaker Protection is not active on speaker+ route`: the fault logger's back-to-back `bl` run (the log, its releases)+ ends in the terminate, whose successor is never a call;+* the epilogue is the stack-guarded pop run after the anchor's throw (iOS+ 26) or the plain frame restore (iOS 27 builds the walker without the+ protector) — shape-checked either way.++Idempotent: a re-run recognises its own branches (including the terminate+site, whose patched shape ends the `bl` run one call early) and writes+nothing. Verified against the real iPadOS 26.6.2 and iOS 27.0 binaries in+`~/.vphone/va-analysis/`: 6 sites and 5 sites respectively, byte-exact+re-runs.++## The bundle seal++`patchMachO` re-signs the Mach-O it replaces, but `VirtualAudio.plugin` is a+bundle: the outer `_CodeSignature/CodeResources` seals the directory, and a+guest with `codeSigningMonitor == 2` kills audiomxd on load when the seal+still names the old binary. The stage re-seals the bundle with+`codesign -f -s -` after the patch (`sealGuestBundle`); the same call covers+the restore-from-backup path.++## Verified in the guest++With the patch installed (`cfw update-environment`), ipad-pro-13 boots+through the serialization replay that used to be a crash loop, audiomxd+stays up, VirtualAudio initializes (`we have found the default VAD ID: 65`),+the pspk port publishes, and — reported by the user — **the boot charge+chime is audible on the Mac**. First boot may still see one audiomxd abort+before the state settles; the relaunch survives.++## The gap that followed, and the clock seed that closed it++With the walker silenced, playback still failed once the vdef's aggregate+owned the device: `HALS_IOContext_Legacy_Impl::IOWorkLoop: could not+establish a timeline after waiting 5000000 microseconds`, then+`AudioDeviceStart (err 'nope')` — the aggregate ran our device for three+seconds, never accepted its clock, and aborted the start. (The boot charge+chime had worked because it plays before the vdef takes the default device,+on a direct start.)++The cause was the plugin's zero-timestamp seed. `getZeroTimestampBlock`+advanced `(sampleTime, hostTime)` a whole period at a time but bumped the+seed only at re-anchor, so the HAL read every advancing pair as the same+frozen timestamp and never established the timeline. The seed now changes+whenever the reported pair does (`VPClockZeroTimestamp`). With that one+change, ringtone sessions play through the aggregate with no `nope`, no+timeline failure and no crash (`~/.vphone/va-analysis/clockfix.json`), and+the system route reads `PVMSetCurrentState [Audio/Video, Default, Speaker,+PuffinOutput]`.++## Where the audio path stands after the seed fix (open work)++With the walker silenced and the clock seed advancing, ringtone sessions play+end to end **when their rate is 48000** — the vdef's aggregate then carries our+device (`AggDev 2: phys devs {PuffinOutput}`) and the Mac plays it; the boot+charge chime, a direct 48k start, was audible to the user. Two further facts,+both from `~/.vphone/va-analysis/vol4.json`:++1. **44100 sessions exclude the device.** A RingtonePreview session runs its+ AudioQueue at 44100; the vdef then builds its aggregate around the+ **Null_Device** (`AggDev 8, sr: 44100`) because our device advertises+ `samplingRates = @[@(48000)]` only, and the preview is silent. A dual-rate+ build (advertise 44100, resample in `writeMixBlock`, rate-aware clock) was+ written and built but not yet validated: the volume-control experiment it+ shipped with (below) removed the boot chime, so the plugin was rolled back+ to the last confirmed-audible state (the seed fix alone) pending a clean+ test. The dual-rate and resampler code exists in the session notes, not in+ the tree.+2. **The pspk route runs in HardwareOnly volume mode.** VirtualAudio fails+ `OutputVolumeControl_HAL_Common.cpp:1390 "Volume Mode is HardwareOnly but+ physical device does not support HW volume"` and every volume set on the+ vdef errors. Adding `ASDLevelControl`/`ASDBooleanControl` (the macOS+ AppleVirtIOSound plugin's own volume API, confirmed present in the iOS+ AudioServerDriver framework) is the right shape — but the first attempt+ also broke the boot chime, so it needs re-introducing on its own, with the+ element/scope choices checked against what the pspk volume queries expect.++## Handoff state (2026-10-03, session 3 — the mute dispatch)++**Machine**: ipad-pro-13 on the v5 build (controls via explicit-class+initializers, everything else as before); VirtualAudio carries the 6-site+`speaker_route_throws` patch; `ProductIDOverride=198` and+`VPhoneVirtIOSoundDeviceUID=PuffinOutput` prefs set. audiomxd stable, no+crashes. **The boot charge chime is still silent** — the regression this+session chased to ground.++**Regression history (fix 1 of the previous handoff, in three acts):**++1. *Factory initializers are poison on the guest ASD.* The+ `muteControlWithValue:…` / `volumeControlWithDecibelValue:…` factories are+ state-dependent: runs where they returned real controls still failed the+ route unmute with 'what', and later runs returned the raw FourCharCode+ `'togl'` (0x746f676c) as an `id`, which release-faulted in the caller's+ epilogue and crash-looped audiomxd (`audiomxd-*.ips`). The explicit-class+ initializers — `initWithValue:isSettable:forElement:inScope:withPlugin:+ andObjectClassID:` and the decibel twin — construct deterministically;+ a guest-side reflection probe confirmed both return real ASD controls+ that register under exactly the class ID passed ('mute' 0x6d757465,+ 'vlme', 'dsrc' — read back through `objectClass` and+ `isKindOfAudioClass:` in v5's init log). v4 (this construction) is the+ first controls build audiomxd survives cleanly: runs=1, pspk port+ published, endpoint typed Speaker, volume range answers.+2. *Controls registering correctly is still not enough.* v5 proved the+ registration and still: `selector "mute"` fails 'what' at (outp, 0),+ ProcessRoute throws its CAException, the aggregate lands on Null_Device,+ no `PVMSetCurrentState`, no chime.+3. *Root cause, by disassembly.* AudioServerDriver's resident `__TEXT`+ (535968 bytes) was paged out of a guest process that dlopens it+ (`asdtext-guest.m`), turned into a self-contained MH_OBJECT host-side+ (`patch-macho.c`: `__TEXT` fileoff→0, vmaddrs rebased by the same delta,+ header trimmed to the one segment), and disassembled with+ `llvm-objdump` (`asd.dis`, 104362 lines) after a guest reflection probe+ (`asdimp-guest.m`) reported the PAC-masked IMP offsets of every method of+ interest relative to `dli_fbase`. Finding: the FourCharCode `'mute'`+ occurs in exactly two comparisons in the whole image (0x3b8f0, 0x3bc10),+ both inside ASDBooleanControl's control-level code; ASDAudioDevice's+ device-level dispatch — the binary-search selector trees behind its+ `hasProperty:` (0x3528) / `getProperty:` (0x1cf4) — has no 'mute' case+ at all. (Eight other `#0x6d75` materializations are `'muid'`, ModelUID —+ low half 0x6964.) macOS's ASD dispatches device-level mute; iOS's+ doesn't, so no plugin device can inherit it, and VirtualAudio's+ Device_HAL_Common unmute-then-read-back on the device object gets 'what'.++**v6 fix (built this session, install pending): `VPVirtIOSoundDevice` answers+device-level mute itself.** The ASD property plumbing the driver's C ops call+into is declared on ASDObject in our header and overridden on the device:+`hasProperty:`, `isPropertySettable:`,+`dataSizeForProperty:withQualifierSize:andQualifierData:`,+`getProperty:withQualifierSize:qualifierData:dataSize:andData:forClient:`,+`setProperty:…` (signatures from the arm64e argument layout of+ASDAudioDevice's own implementations: x2 = address, x3/x4 = qualifier,+x5 = in/out `UInt32 *dataSize`, x6 = data, x7 = client). A+`VPIsDeviceMuteAddress` predicate (selector 'mute' — the iPhoneOS SDK headers+omit `kAudioDevicePropertyMute`, so it is `0x6d757465` beside the 'ispk'+constant — scope glob or outp, element 0/main) routes to a shadow+`UInt32 _muteState`; sets forward to the registered `ASDBooleanControl`+through `setValue:` only — `booleanValue` does not exist on the class (the+getter is `value`), and calling it would be an unrecognized selector inside+audiomxd. Everything else passes to `super`.++**Verification for v6 — run, and the override did not change the outcome.**+v6 deployed (guest plugin sha byte-identical to the build), audiomxd stable,+device 37 `PuffinOutput` activates — but `Device_HAL_Common.mm:290 Set mute+value of 0 … (selector kAudioDevicePropertyMute; 'outp'; 0)` still fails+`'what'` (:307), `RoutingManager.cpp:3515 CAException … ProcessRoute: 'what'`+still throws, and the aggregate is still built `master = "Null_Device"`. Two+new facts from the same capture (`v6-restart3.json`, pid-filtered — note+vphoned's `logs.syslog` `process` filter silently drops the plugin's+`com.vphone.audio` lines; only the unfiltered query returns them, and its+4000-line default truncates mid-restart, so use unfiltered + `max_lines`+5000):++1. The rejection is server-side and logged:+ `HALS_UCPlugIn.cpp:1190 HALS_UCPlugIn::ObjectSetPropertyData: failed:+ [<private>/<private>/0], Error: 2003329396` — the HAL *server's*+ plugin-bridge rejects the device-level mute before (or while) consulting+ the driver ops.+2. Immediately after, the **control** path succeeds:+ `HALS_PlugInControl::SetPropertyData: control id 40, property address+ ['bcvl', 'glob', 0], owning device UID PuffinOutput, control type external+ driver, control scope 'outp', control element 0, mute: 0.000000`. The+ server knows our ASDBooleanControl is a mute control (it labels the value+ "mute:"), sets its 'bcvl' fine — only the device-level selector dies.++So the open question is whether the driver ops ever reach the overridden ObjC+methods for a device-level selector. The follow-up build (in flight) adds+`prop-probe` logging: the first 40 `hasProperty:` selectors seen, a log on+every mute-address hit in each of the five overrides, and an init-time+`class_getInstanceMethod` presence check. Outcomes and what they mean:++* probes fire with 'mute' → the 'what' is generated above the driver (HALS+ pre-validation); the plugin cannot fix it from ObjC, and the fix moves to+ patching VirtualAudio's mute handling (a new site in the existing+ `speaker_route_throws` patch family).+* probes fire but 'mute' never arrives → same conclusion: the server never+ forwards the selector.+* no probes at all → the ASD C-op layer answers device-level properties+ without calling these ObjC methods; the subclass-override approach is+ wrong on iOS and the candidate becomes swizzling ASDAudioDevice's methods+ at plugin init (before any device registers) or the VirtualAudio patch.++Guest probe leftovers to sweep: `/var/mobile/asdimp*`, `asdtext*`,+`asd-text.bin`.++Probe-infrastructure notes for whoever extends this: vphoned's+`files.read` with `binary:true` truncates at 524288 bytes (the needed+functions all sit below 0x80000); `processes.kill` refuses without+`{"pid":N,"force":true}`; an unentitled launchd daemon sees zero HAL+devices, so client-side probing is a dead end — the reflection/memory-dump+probe running *inside* a process that has the framework loaded is the+working shape. Artifacts in `/tmp/va-analysis/` (asd-patched.bin, asd.dis,+the three probe sources, patch-macho.c) and captures `v4-restart2.json`,+`v5-restart.json`.++## The probe settled it: the server never forwards 'mute' (2026-10-03, session 4)++The probe build (v6+probe) appended a `VPProbeLog` sink to+`/var/mobile/vpprobe.log` — vphoned's syslog capture is a live tail that+swallows early-restart lines and its `process` filter drops the plugin's+subsystem outright, so a file was the only reliable channel. The result+(`probe.b64`, pulled before the sweep): **60 `hasProperty:` calls reached the+override, not one of them 'mute'** — the overrides dispatch for every other+selector, so the third outcome above is ruled out and the first is the+answer: `HALS_UCPlugIn.cpp:1190` pre-validates the device-level set against+the plugin's driver-op table, finds no 'mute' entry, and answers 'what'+(2003329396) without ever consulting the driver. No plugin-side fix exists on+iOS; the fix is the VirtualAudio binary below. The overrides stay in the+plugin as macOS-parity dispatch (the doc comment in+`VPVirtIOSoundPlugin.m` says so); the probe sink itself is gone.++## `system-virtualaudio-cfw-mute_set_throw` — the mute-set throw++With the 'what' unavoidable, the remaining lever is what VirtualAudio does+with it. `Device_HAL_Common`'s set wrapper logs FAIL (`:307`) and EXCEPTION+(`:308`) then **throws `CAException("Unable to set property data.")`** out of+the property callback; `RoutingManager.cpp:3515` catches it and abandons the+route — the aggregate's master stays `Null_Device`, no+`PVMSetCurrentState`, no chime. Every caller of the wrapper ignores its+return value, so turning the throw into a quiet return through the wrapper's+epilogue is safe: the diagnostics still log, the route proceeds as if the+mute had held (and the control-level 'bcvl' set the server already performed+stands).++The patch (`patchMuteSet` in the same `CustomFirmwareVirtualAudio.swift`,+verb `cfw patch-virtualaudio-mute`, both install paths riding one+`patchMachO` call with `patch-virtualaudio` — staging restarts from the+pristine `.bak`, so two calls would not compose):++* **Anchor**: the log format `Set mute value of %u on HAL device`+ (stable prefix across both builds), found as a cstring in a real string+ section and referenced by exactly one adrp+add in `__text` — inside the+ wrapper's selector dispatch. The wrapper is the enclosing+ pacibsp-to-pacibsp function.+* **Site**: within the wrapper, the CAException throw block. A CAException+ carries no message string, so the walker patch's `isThrowBlock` shape+ (x1 message load + constructor call) does not match it; the CAException+ shape is: the `___cxa_allocate_exception` call, then `str xN, [x0]`+ (vtable) and `str wN, [x0, #imm]` (status) stored into the allocated+ object, then a call after the store (`___cxa_throw`), closed by the `brk`+ the compiler plants after a call it knows never returns. On both builds+ that block is **17 instructions from the allocation call to the `brk`** —+ the scan budget (`isCAExceptionThrowBlock`) is 32 for exactly this reason;+ 16 (the runtime_error budget) exits one instruction before the terminator+ and reports the block absent.+* **Discriminator**: iOS 27's wrapper holds a *second* CAException — the+ deactivated-device throw (`'!obj'`, log "Device has been deactivated.").+ What tells them apart is the EXCEPTION log window: the target throw has an+ adrp+add forming a cstring **containing** `Unable to set property data.`+ within 0x40 bytes above the site (the actual gap is 7 instructions on both+ builds); the deactivated throw's window references its own string. On+ 26.6.2 the deactivated throw does not exist, and exactly one candidate+ survives on each build.+* **Epilogue**: the wrapper's single `retab`, walked back to its entry by the+ same guarded-canary chain logic as the walker patch (`epilogueEntry` is+ shared) — except the retab cannot be searched forwards from the throw,+ because the mute-set throw sits *below* the epilogue (the wrapper's+ success path returns before the failure paths); it is enumerated within the+ function's own bounds instead.+* **Write**: `ARM64Encoder.encodeB` from the throw site (the `mov w0, #0x10`+ sizing the exception) to the epilogue entry. Backwards branches, −0x558+ (26.6.2) and −0x32c (iOS 27).++Verified against the real binaries (`/tmp/va-analysis/mute-verify/`):+exactly one site and one epilogue each (26.6.2: throw 0xee224 → epilogue+0xedfcc, wrapper 0xeda04–0xee2e4; iOS 27: throw 0x111ac8 → 0x11179c,+wrapper 0x111168–0x111b8c), dry-run writes nothing, second apply is+byte-identical (`cmp`), and both verbs compose on one copy (`patch-virtualaudio`+then `patch-virtualaudio-mute`, re-run idempotent).++The mute-set wrapper is a different function from the walker: the two+patches are siblings over the same binary, not one site list — the walker's+six sites (table above) all live in the speaker-protection walk, the+mute-set throw in Device_HAL_Common's set wrapper, reached after them on the+same route establishment.++## The gate is the category: RingtonePreview drops the device from discovery (2026-10-03, session 5)++The v7 build (dual-rate stream, speaker controls, device-level mute/nsrt+dispatch) is audible for one flow and silent for another, and the difference+is not the device, the rate, or the mute/nsrt noise — it is the **audio+category** the session runs under.++**The failing flow** (tone tap in Settings ▸ Ringtone; captures+`nr1-tone2.json`, `nr2-tone.json` in `/tmp/va-analysis/`):++1. mediaserverd logs the session going active, `[NonMixable]`, with+ category **'crnp'** (RingtonePreview) in the Parsed RouteConfiguration.+2. Within a second every discovery client *removes* the device:+ `Output devices changed - PuffinOutput` from chronod, duetexpertd,+ SpringBoard and mediaremoted (each tagged `(Audio - Disabled)`).+3. The Audio discoverer answers `no available routes for clientName=…,+ discovererType=Audio`.+4. mediaplaybackd fails `Get SelectableOutputs` three times, then+ `itemfig_createRenderTriplesForAudio: No audio device is available` —+ no render pipeline, silence.+5. On session end (`going inactive` / `stopping playing`),+ `Output devices changed + PuffinOutput` — the device returns.++**The working flow** (`stut1.json`, WebKit mp3 in Safari): the session is+`[MediaPlayback/Default] [NonMixable] [System Music]` — category **'csav'**+— and the same discoverer line reads `Available routes for+clientName=mediaremoted, discovererType=Audio: [0].扬声器`; no+SelectableOutputs failures; StartIO runs and the Mac plays it. (stut1's+StartIO was this WebKit session — that capture never proved a ringtone+worked.) A real iPhone (`iphone-live.json`) also logs transient no-routes+discoverer lines but never removes a device and never fails+SelectableOutputs.++The route pick itself succeeds even in the failing flow+(`FigRoutingManagerCopySelectedBufferedEndpoint: pickedEndpointName=扬声器 …+routingContextType= System Audio`). What fails is the route-configuration+computation for the RingtonePreview category, and its failure mode is to+retract the pspk port from discovery wholesale.++**Hypotheses killed this session:**++* *'noct' GET errors* (`HALS_AHPPlugIn.cpp:119`, error 1852793716 =+ `kVirtualAudioObjectRoutingNotSupportedError`). The literal source string+ is VirtualAudio's `"Routing is not supported: attempt to activate the+ routes failed."` — and the same errors appear in the **working** stut1+ capture. Tolerated noise, as are the nsrt/mute 'what' failures (which did+ not even recur in these captures).+* *Boot-time nominal rate.* A verified 44100-nominal boot (see below) fails+ the tone tap identically to the 48000 boot. The `Device Hints vdef nsrt+ 44100` lines during sessions come from VirtualAudio's negotiation cache,+ not the boot preference. The dual-rate device code stays — a 44100+ aggregate needs it — but it is not the gate.++**Where the ringtone route diverges in the binary** (26.6.2): the+route-subtype family `_speaker_ringtone` (beside `_speaker_general`,+`_speaker_movie`, `_speaker_alarm`, `_speaker_latenight_*`), a subtype+named "Local System Sound For Ringtone Category", a routing database whose+misses log `Category %s does not exist in the database`, and the+`kVirtualAudioPlugInPropertyActiveNonQuiesceablePortsForCategory` /+`…ForRouteConfiguration` property sites — the plugin-side exception sources+for 'noct' / `kVirtualAudioObjectCategoryNotSupportedError` / 'unspec'.+None of the route-activation failure strings appear in any capture, so the+failing branch logs nothing we currently match.++**cfprefsd clobbers direct plist writes.** Writing+`/var/mobile/Library/Preferences/com.apple.coreaudio.plist` through+`files.write` gets rewritten by cfprefsd as a bplist that drops both+`VPhoneVirtIOSound*` keys (the device then boots as `VPhoneVirtIOSound:0`,+the default UID, and nothing routes). The durable write is the+`settings.set` RPC+(`{"domain":"com.apple.coreaudio","key":…,"value":…,"type":"float"|"string"}`),+which goes through CFPreferences.++**The abort signature (found across every failing capture):** the 'crnp'+route-change handler does not complete. It logs++```+VirtualAudio_PlugIn.mm:4270 Parsed RouteConfiguration: [ [ Category: 'crnp'; Mode: 'imdf' ]; … ]+VirtualAudio_PlugIn.mm:2766 The routing mutex was left held after handling a route change. Unlocked it.+HALS_AHPPlugIn.cpp:126 ObjectSetPropertyData: got an error from the plug-in routine, Error: 1852793716 ('noct')+```++in immediate succession — the handler bails between parsing the+configuration and finishing (an exception unwinds past the unlock; the+watchdog at :2766 catches it), and the property **SET** that drove the+route change fails `'noct'` ("attempt to activate the routes failed",+`kVirtualAudioObjectRoutingNotSupportedError`) on the now-inconsistent+state. Line **126** is the SET path; the `:119` GET errors seen in+*working* captures are a different, tolerated site. Cross-capture+provenance (all captures in `/tmp/va-analysis/`):++| Capture | Flow | :2766 mutex-left-held | :126 SET error | Session outcome |+| --- | --- | --- | --- | --- |+| nr1-tone2 | RingtonePreview 'crnp' | **4×** (idx 302/684/774/901) | **4× 'noct'** right after each | silent (session retried 4×) |+| nr2-tone | RingtonePreview 'crnp' | 1× | 'noct' | silent |+| v8-ring | RingtonePreview 'crnp' (2026-10-03, current guest) | 1× (idx 3501) | 'noct' (idx 3502) | silent |+| stut1 | WebKit 'csav' (working) | **0** | 1× — but error **2003329396 ('what')**, plus 10× :119 GET 'noct' | audible |+| iphone-live | real iPhone, ringtone + playback | 0 | 0 | audible |++So the divergence is exactly two lines: the 'crnp' computation dies inside+the handler, leaves the mutex behind, and the SET fails 'noct'; the 'csav'+computation never aborts. CoreMedia reads that failure as "no available+routes" and discovery drops the device (the `- PuffinOutput` cascade+above). The 'what' SET failure in the working capture is the familiar+mute/nsrt rejection — tolerated.++**Deploy note (same session):** the v8 build installed as `2.3.2-local`+(the bundle version bumped), but the deploy chain ran `bundle accept+2.3.1-local` — accept marks trust, **`bundle use <version>` is what+activates** — so the guest kept booting the old plugin (zero+`com.vphone` lines in the captures; the signature above reproduced on v7).+Activation fix: `bundle use 2.3.2-local` → `cfw update-environment` →+`vm start`. Symptom to check first in any future capture: the plugin's+boot line (`device PuffinOutput: … Hz nominal`) must appear before+trusting the rest.++**The v9 selector inventory (file sink) — and what it rules out (2026-10-03,+afternoon).** Two infrastructure facts first:++* The 2.3.x guest bundles' `vphoned` syslog tail **no longer delivers+ `com.vphone.audio` lines at all** — under the 2.2.5-era bundle they flowed+ (seven boot lines per audiomxd restart, plus session-time rate-probes);+ with 2.3.x they are absent from every capture, unfiltered query included,+ while the plugin binary in the guest is byte-identical to the build. The+ inventory therefore also lands in `/var/mobile/vpquery.log` (v9:+ `VPLogToFile` in `VPVirtIOSoundPlugin.m`, UTC-stamped, 4 MB cap,+ `=== plugin load ===` segment marker — the channel the session-4+ reflection probe already proved writable). Pull it with `files.read+ binary:true`.+* `logs.syslog` returns the last `max_lines` **buffered** lines and returns+ early once it has them — on a guest flooded by mDNSResponder noise+ (≈5000 lines/s) a capture started before the event it wants closes within+ a second or two and misses it entirely. Drain first (`seconds:1,+ max_lines:5000`), then start the real window.++The inventory's verdict: **during the failing 'crnp' attempts the plugin's+objects are asked nothing new at all.** The full init vocabulary (~40+tuples: `clas uid stm# pfta ctrl siso nsrt ring saft ltnc clok cstb tran+schn pft term clkd accs hidn exsm box# clk# drte dflt sflt auto muid lnam+aerE cfsz sact evAd evAS dsHS dsOr srnd …`) is asked in the first second+after respawn; the only flow-time additions in both the ring and Safari+legs are `size nsrt` → `set nsrt 44100` (the device-level rate set works —+it reaches the override, answers YES, `setSamplingRate` runs) — and then+the ring leg goes silent while the handler aborts. The divergence is+entirely inside VirtualAudio; no missing plugin property is involved.++**The abort site, found statically.** The route-change handler is+`0xa203c–0xa46dc` in the 26.6.2 plugin (anchored by the+`Parsed RouteConfiguration` string at `0xa2bc8`; the mutex watchdog that+logs "was left held … Unlocked it." is at `0x3a2720`). The handler builds a+`std::map<UInt32, …>` from its argument's VAD list (entries with flag+`+0x131 == 1`, key = the FourCC at `+0x20`), then walks the parsed+configuration's session list and does `map::at(sessionCategory)` with the+category FourCC from `+0x60` — the descent loops at `0xa238c`/`0xa23a8`+fall through to the throw at `0xa3e7c`, which loads+`"map::at: key not found"` into a noreturn throw helper. A libc+++`logic_error` has no VirtualAudio EXCEPTION template, which is exactly why+the captures show no exception line: **the RingtonePreview category has no+entry in the category→VAD map, `map::at` throws, the handler unwinds past+the routing-mutex unlock, the watchdog at :2766 catches it, and the driving+property SET fails 'noct'.** The handler holds nine throw blocks in all+(`map::at` at `0xa3e7c`, `runtime_error("Could not convert")` at+`0xa3e8c`, five `logic_error("Precondition failure.")`/`"Could not+construct"` pairs at `0xa3f6c`–`0xa419c`, and a merged+construct/find/convert block at `0xa4230`–`0xa42cc`).++The map's population comes from the routing settings for the effective+ProductID — `ProductIDOverride=198` is a simulator class whose route set+evidently lacks the RingtonePreview entry, while 'csav' is present. The+ActuatorSettingsFactory gate (`0x36d4f0`) accepts ProductIDs+{146–169, a bitmask set ≤ 46, 197, 198, 4013–4018, 8010–8025}; only+195/196 force the "input processing disabled" path, so 197 / 4013–4018 /+8010–8025 are untried real-path candidates (a live matrix is in flight).++**Disassembly convenience for whoever continues here:** `otool -tV`+annotates string references inline — `add x3, x3, #0x5d5 ; literal pool+for: "…"` — so anchor hunts in this binary are greps over the annotation+text (`/tmp/va-analysis/va.dis`), not adrp+add address math.+**Layer 2 — the SpeakerProtection chain throw (2026-10-03, decoded).** With+`ProductIDOverride=8010` — the only accepted ProductID whose category→VAD map+covers `'crnp'` — the ringtone route change runs its full pipeline (route+list built, aggregate master `PuffinOutput`) and dies building the route's+DSP chain. `graph_configurations.plist`, loaded from+`/Library/Audio/Tunings/<acoustic ID>/VAD/` (`AID2029` on the iPad Pro 13;+the loader at 0x2fb36c joins the CommonData tuning path with `VAD` and the+filename — a filename literal referenced at 13 code sites), gives every+`speaker_*` configuration `chainType "clhs"`. The DSP chain factory (F2,+0x117628) switches on that fourCC: `clhs` (b.eq at 0x117ac8) takes the HAL+SpeakerProtection branch 0x117c30, whose config constructor (0x3dcccc, a+0xd0-byte object, exactly two callers) first calls `findDevice("Speaker")`+(0x3dc460: registry singleton → find → `LockWeakPtrOrThrow` at 0x3dc4a8,+line 60) — and a VM's device registry has no physical Speaker, so it throws+`Could not lock weak ptr (:60)`. The chain is destroyed, RoutingManager.cpp:1774+logs `Failed to activate a route list`, the route change fails `nort`+(1852797556), and the guest stays silent with no fallback. PID matrix+rounds 1–2: 197/4013–4018/8011–8020 all abort at layer 1 (`map::at` on+`'crnp'`); 195/196 die at VirtualAudio init (timeout, degenerate); only 8010+reaches layer 2. The mute `'what'` failure is benign (server-side+pre-validation).++**Why the fix is a plist, not a binary patch.** `dflt` — the chainType every+`beam_mic_*`/`omni_mic_*` configuration already ships — takes the generic+graph chain instead (0x117a38: 0x4c0 object, F1 ctor 0x117088, no+`findDevice`, wraps a shared control block). Every speaker configuration's+`graph`/`austrip` tuning files exist in the same VAD directory, so flipping+`chainType` alone moves the speaker routes onto the proven mic path. The+plist sits on the sealed system volume, so runtime `files.write` fails+EROFS; the change ships as `system-virtualaudio-cfw-speaker_graph_chains`+(see `Research/0_binary_patch_comparison.md`), which stages the plist+offline like `patch-build-version` does. Null-tolerant `findDevice` patches+are structurally dead: `buildParams` (0x3dc518) dereferences the returned+`Device*` at its first virtual call (0x3dc550), reached from both+0x3dcda4 (config ctor) and 0x1182a4 (F2's reconfigure) — a null return+crashes instead of degrading; the `LockWeakPtrOrThrow` helper 0x53a08 has+40+ callers; skipping `buildParams` leaves an uninitialized output map the+destructor crashes on. Candidate D (NOP the `clhs` b.eq at 0x117ac8 so the+factory returns a null chain via the Unsupported path) stays as the+fallback if the plist route fails empirically — downstream null-chain+tolerance is unverified.++**Empirical validation (2026-10-03, iPad Pro 13 / 26.6.2).** The plist+route works; Candidate D stays retired. With the patch applied through+`cfw update-environment` (all 8 `speaker_*` chains `clhs` → `dflt` in+`AID2029/VAD/graph_configurations.plist`) and `ProductIDOverride=8010`+persisted in `com.apple.audio.virtualaudio`, a Ringtone-preview tap on a+pristine boot — no manual audiomxd restart — shows the complete chain in+syslog: `AggregateDeviceUtilities` builds the VAD with `master =+PuffinOutput`, the generic `dflt` graph chains are created, and+`HALS_IOEngine2::_StartIO … State: Running` follows+`cmsSetIsPlaying … [RingtonePreview/Default] [System Audio] starting+playing to output VAD`. All four abort signatures are absent:+`map::at` 0, `Could not lock weak ptr` 0, `mutex was left held` 0,+`DSPGraphChain_HAL_SpeakerProtection` 0. Re-running the environment+update is idempotent (`8 speaker chains already 'dflt'`, no write).+One reading in that capture was later corrected — see the next+paragraph: the StartIO evidence was checked against the wrong device+identity.++The `:223` residue is **fatal**, not benign — the "non-fatal" reading+above was a false positive, corrected 2026-10-03 when the user reported+complete silence with the volume dead. The StartIO "Running" lines sat+on `Null_Device (VAD [vdef] AggDev 8)`, not the PuffinOutput aggregate+the audible era starts (`stut1.json`: `StartIOProcID: 78 PuffinOutput+(VAD [vdef] AggDev 2)`). Device identity, not the Running state, is the+evidence that matters: the decline at+`RoutingHandler_Playback_GenericConfig1.cpp:223` — "HAL Speaker+Protection is missing. Failing route", on the `Category: 'crnp'`+reconfiguration — drops the vdef's output stream onto Null_Device, every+"playing" signature is genuine, and nothing is audible. The capability+query the handler gates on never leaves VirtualAudio (0 hits in the ASD+plugin's file logs), so no plugin can supply it; the fix is the third+binary patch, `system-virtualaudio-cfw-speaker_protection_gate` (see+`Research/0_binary_patch_comparison.md`), which rewrites the decline's+own log block into a branch back to the gate's fall-through. The `nort`+failures from `VirtualAudio_PlugIn.mm:2815` remain, four per tap, and+are expected to be benign once the route survives.++A deployment hazard worth knowing: the first environment update after a+`bundle install-local` ran while the store swap was still settling, so+the helper exec'd the pre-swap binary against post-swap resources and+the plist step silently never ran (that build had no plist call site).+Symptom: every other guest change landed, Tunings untouched. Rule:+never run `install-local` concurrently with a helper-driven CFW+operation; re-run the environment update after the store settles.++## Layer 4 — the volume-mode precondition at :252 (2026-10-03, decoded)++The SP-gate patch landed and the capture after it+(`/tmp/va-analysis/spgate-ring.json`) proved `:223` gone — and exposed+the next decline one step down the same handler:+`RoutingHandler_Playback_GenericConfig1.cpp:252`, logging as a bare+`Precondition failure.` on 26.6.2, with StartIO still landing on+`Null_Device`. Same finished route, same teardown; one gate deeper.++**What the precondition is.** iOS 27's build kept the assert text that+26.6.2 strips to the bare string:++```+softwareVolumeModeForPerDefaultScope.has_value() &&+softwareVolumeModeForPerDefaultScope.value() ==+ VolumeControl::SoftwareVolumeMode::kHardwareOnlyReadOnly+```++The route's per-default-scope software-volume mode must be present and+be `kHardwareOnlyReadOnly` (enum 3). The virtio plugin's device reports+`SoftwareHardwareMix`, so the test fails on every VM device — same shape+as the SP gate: a hardware assumption no virtual device can satisfy.+Unlike the SP gate's quiet decline, this one *throws* a+`std::logic_error` (libc++: no VirtualAudio EXCEPTION template, so the+capture shows only the OS log's `Precondition failure.` line), which+unwinds past the route's own teardown into `RoutingManager.cpp:3520`'s+catch: route change failed `nort`, session torn down onto `Null_Device`,+silent with the volume dead. This — not the SP gate alone — is the layer+the "no sound and the volume won't move" report names.++**The guard chain** (identical instruction-for-instruction on both+builds; addresses are 26.6.2, iOS 27 in parens):++1. `bl` a wrapper (0x1450e0 / 0x14ed4c-equivalent): checks+ ActivationParams — a miss logs `Aspen.cpp:1428` "Missing+ ActivationParams for connection %u" and returns 0 — else calls the+ map getter and returns its low 40 bits.+2. The getter (0x143f34): map lookup; a miss logs `Aspen.cpp:1451`+ "Extended Volume description … absent", returns 0; a hit logs+ `Aspen.cpp:1445` "PerVAD Volume description … present" and returns+ the packed 64-bit map entry verbatim.+3. `and xN, xRet, #0x1ffffffff` — the 33-bit packing mask: present-flag+ bit 32 over the mode's low 32 bits.+4. `add x9, xBase, #1` — the expected pair `0x1_00000003`+ (`(1<<32)|kHardwareOnlyReadOnly`), built as base+1 because the+ compiler materialized `0x1_00000002` for a sibling compare.+5. `cmp` / `b.ne` to the decline (guard at 0x1369c4 / 0x1464e0; decline+ block head 0x138124 / 0x1475d0; comparison fall-through 0x1369c8 /+ 0x1464e4).++The fall-through reloads its inputs from memory (`ldr x8,[sp,#…]`;+`ldr xN,[x8,#0x48]`) and never re-reads the tested value, so landing on+it after a failed compare is safe. The decline block's layout matches+the SP gate's: PRECONDITION format adrp+add 0x58 above the head, file+name 0x2c above, sole entry the guard's branch, pre-head an+unconditional branch — checked before any write.++**The fix** is the fourth binary patch,+`system-virtualaudio-cfw-volume_mode_precondition` (verb+`cfw patch-virtualaudio-volume-gate`, see+`Research/0_binary_patch_comparison.md`): the comparison and its `b.ne`+are left intact; the decline's log-block head — the `mov w0, #0xe`+sizing the os_log — becomes a `b` back to the comparison's own+fall-through, so the failed precondition lands on the continuation the+handler already built. The handler is the same one+`locatePlaybackHandler` resolves for the SP gate (SP format + file name;+exactly one function holds both), and among that handler's three+PRECONDITION declines (`:142` guard `tbz`@0x135fe0, `:252` ours, `:270`+guard `cbnz`@0x1367dc) plus `Aspen.cpp:729`, ours is the only one whose+guard sits within six instructions of a `cmp` and an `and` with+immediate `0x1ffffffff` whose preceding word is a call — the mask+window is the discriminator. Verified offline on both pristine builds:+exact sites, real writes (`29 fa ff 17` @0x138124; `c5 fb ff 17`+@0x1475d0), byte-identical idempotent re-runs, and all four VirtualAudio+verbs composing on one staged copy with a clean second pass.++**Open risk, accepted per playbook:** downstream, the route now proceeds+in `SoftwareHardwareMix` with whatever volume description the map holds+(a degenerate 0..0 dB range is plausible). Sound returning is the+expectation; volume-adjust behavior after it is the next thing to+re-check, and the earlier HardwareOnly volume-mode suspicion is related+but separate. In-guest proof standard unchanged: `:252` = 0 and StartIO+on the `PuffinOutput` aggregate (`VAD [vdef] AggDev 2`), not Null_Device.\ No newline at end of filediff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swiftindex 891fa779..383912b6 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift@@ -73,13 +73,43 @@ public enum CustomFirmwarePostRestoreDeviceTree {dryRun: Bool = false,verbose: Bool = true,) throws -> Outcome {- let data: Data+ // Every identity rewrite lands in the property's existing slot.+ try rewrite(at: url, dryRun: dryRun, verbose: verbose) { blob in+ let (newBlob, changes) = try patchedDeviceTree(blob)+ return (newBlob, changes, blob.count)+ }+ }++ /// Give an iPad guest's `devicetree.img4` (or bare `.im4p`) the audio node+ /// of the iPad's own tree at `boardURL`, in place. See+ /// `DeviceTreePatcher.presentBoardAudio`.+ @discardableResult+ public static func presentBoardAudio(+ at url: URL,+ board boardURL: URL,+ dryRun: Bool = false,+ verbose: Bool = true,+ ) throws -> Outcome {+ let boardData: Datado {- data = try Data(contentsOfFileToRewrite: url)+ boardData = try Data(contentsOf: boardURL)} catch {- throw PatcherError.fileNotFound(url.path)+ throw PatcherError.fileNotFound(boardURL.path)}+ let board = try openDeviceTree(boardData, path: boardURL.path).blob+ return try rewrite(at: url, dryRun: dryRun, verbose: verbose) { blob in+ let (newBlob, changes, delta) = try withBoardAudio(blob, board: board)+ return (newBlob, changes, blob.count + delta)+ }+ }+ /// The container, payload and flat tree of a device tree file. Refuses a+ /// payload that is not a device tree, is encrypted, or came back still+ /// compressed.+ private static func openDeviceTree(+ _ data: Data,+ path: String,+ ) throws -> (container: Container, im4p: IM4P, compression: PayloadCompression, blob: Data) {let container = try Container(data)let im4p = try IM4P(container.im4pBytes)guard im4p.fourcc == "dtre" else {@@ -88,16 +118,9 @@ public enum CustomFirmwarePostRestoreDeviceTree {)}guard !im4p.isEncrypted else {- throw PatcherError.invalidFormat("DT payload is encrypted (KBAG present): \(url.path)")+ throw PatcherError.invalidFormat("DT payload is encrypted (KBAG present): \(path)")}-let compression = try container.payloadCompression()- let kind = container.isIMG4 ? "IMG4" : "IM4P"- if verbose {- print(" [.] \(url.path): \(kind) desc='\(im4p.description)' "- + "payload_compression=\(compression.rawValue)")- }-let blob = try im4p.payload()// Img4tool finds the uncompressed size in the IM4P's compression-info// element rather than in the bvx2 stream, so a container that carries@@ -108,11 +131,35 @@ public enum CustomFirmwarePostRestoreDeviceTree {"IM4P payload is \(compression) but did not decompress — no compression-info element?",)}+ return (container, im4p, compression, blob)+ }++ /// Open the container, apply `transform` to the flat device tree, and+ /// write the container back with its compression, manifest and restore+ /// info when anything changed. `transform` also returns the size its+ /// output must have, which is checked: a mismatch means the parser and the+ /// serializer have drifted apart.+ private static func rewrite(+ at url: URL,+ dryRun: Bool,+ verbose: Bool,+ transform: (Data) throws -> (Data, [Change], Int),+ ) throws -> Outcome {+ let data: Data+ do {+ data = try Data(contentsOfFileToRewrite: url)+ } catch {+ throw PatcherError.fileNotFound(url.path)+ }++ let (container, im4p, compression, blob) = try openDeviceTree(data, path: url.path)if verbose {+ print(" [.] \(url.path): \(container.isIMG4 ? "IMG4" : "IM4P") desc='\(im4p.description)' "+ + "payload_compression=\(compression.rawValue)")print(" [.] DT blob: \(blob.count) bytes")}- let (newBlob, changes) = try patchedDeviceTree(blob)+ let (newBlob, changes, expectedSize) = try transform(blob)guard !changes.isEmpty else {if verbose {print(" [.] \(url.path): DT already in target state — no change")@@ -124,13 +171,9 @@ public enum CustomFirmwarePostRestoreDeviceTree {print(" [+] \(change.property): '\(change.before)' -> '\(change.after)'")}}- // Every patch writes into the property's existing slot, so a size- // change means the parser and the serializer have drifted apart —- // and an IM4P whose payload no longer matches its recorded- // uncompressed size will not load.- guard newBlob.count == blob.count else {+ guard newBlob.count == expectedSize else {throw PatcherError.patchVerificationFailed(- "DT size changed: \(blob.count) -> \(newBlob.count) bytes (would break IM4P offsets)",+ "DT is \(newBlob.count) bytes, expected \(expectedSize) (was \(blob.count)): parser and serializer disagree",)}@@ -224,6 +267,43 @@ public enum CustomFirmwarePostRestoreDeviceTree {return (serializeNode(root), changes)}+ /// `blob` with `/product/audio` taken from the board's flat tree `board`,+ /// through `DeviceTreePatcher.presentBoardAudio`, which fw patch uses for+ /// a new iPad guest. Returns the size change with the changes, so the caller+ /// can check the serialized size: the node's old bytes out, its new bytes in.+ /// A tree that already matches, or a board with no audio node, comes back+ /// unchanged.+ public static func withBoardAudio(_ blob: Data, board: Data) throws -> (Data, [Change], Int) {+ let (root, end) = try parseNode(blob, at: 0)+ guard end == blob.count else {+ throw PatcherError.invalidFormat(+ "DT parse length mismatch: ended at \(end), blob is \(blob.count)",+ )+ }+ let (source, sourceEnd) = try parseNode(board, at: 0)+ guard sourceEnd == board.count else {+ throw PatcherError.invalidFormat(+ "board DT parse length mismatch: ended at \(sourceEnd), blob is \(board.count)",+ )+ }+ func acousticID(_ node: Data) -> String {+ guard let (audio, _) = try? parseNode(node, at: 0),+ let id = audio.properties.first(where: { $0.name == "acoustic-id" }),+ id.length == 4+ else { return "none" }+ return String(id.value.loadLE(UInt32.self, at: 0))+ }+ guard let change = DeviceTreePatcher.presentBoardAudio(in: root, from: source) else {+ return (blob, [], 0)+ }+ let record = Change(+ property: "product/audio",+ before: "acoustic-id \(acousticID(change.before))",+ after: "acoustic-id \(acousticID(change.after)), \(change.after.count)B",+ )+ return (serializeNode(root), [record], change.after.count - change.before.count)+ }+// MARK: - Flat device tree format//diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareVirtualAudioGraphConfigurations.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareVirtualAudioGraphConfigurations.swiftnew file mode 100644index 00000000..9d4f8f94--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareVirtualAudioGraphConfigurations.swift@@ -0,0 +1,187 @@+// CustomFirmwareVirtualAudioGraphConfigurations.swift — speaker chains to the+// generic graph path in graph_configurations.plist.+//+// VirtualAudio builds each route's DSP chain through a factory that switches+// on the chain's `chainType`. Every `speaker_*` configuration ships with+// `clhs` — the HAL SpeakerProtection chain, whose construction looks a+// physical "Speaker" device up in the device registry and throws+// `Could not lock weak ptr` when the registry has none. A VM has no speaker+// hardware, so with the route walk otherwise fixed, the chain factory is what+// still kills every speaker route: RoutingManager catches the throw, logs+// "Failed to activate a route list", and the guest stays silent.+//+// The `dflt` chainType takes the generic graph chain instead — the same path+// every `beam_mic_*` and `omni_mic_*` configuration already uses. It needs no+// device: it loads the configuration's `graph` DSP file, which the tuning set+// ships for every speaker configuration. Flipping the speaker entries to+// `dflt` moves speaker routes onto that path; the tuning files themselves are+// not touched.+//+// The plist lives at `/Library/Audio/Tunings/<acoustic ID>/VAD/` on the+// sealed system volume, so the change rides the offline install; the patcher+// itself only ever sees a staged copy.++import Foundation+import VPhonePatchKit++/// Rewrites every `speaker_*` entry in a `graph_configurations.plist` from+/// the `clhs` HAL chain to the `dflt` generic graph chain.+public enum CustomFirmwareVirtualAudioGraphConfigurations {+ /// The key holding the per-configuration chain table.+ static let configurationsKey = "Configurations"++ /// The key inside each configuration naming its DSP chain type.+ static let chainTypeKey = "chainType"++ /// The HAL SpeakerProtection chain a physical speaker would use.+ static let speakerChainType = "clhs"++ /// The generic graph chain every mic configuration already uses.+ static let graphChainType = "dflt"++ /// What a patch attempt did.+ public enum Outcome: Sendable, Equatable {+ /// Entries already on the generic chain; nothing to write.+ case alreadyGraphChains([String])+ /// Entries would flip but `dryRun` suppressed the write.+ case dryRun(changed: [String])+ /// The file was rewritten with the flipped entries.+ case rewritten(changed: [String])++ /// True only when bytes landed on disk.+ public var didWrite: Bool {+ if case .rewritten = self {+ return true+ }+ return false+ }+ }++ // MARK: - Patching++ /// Flip every `speaker_*` configuration's `chainType` to `dflt` at `url`.+ ///+ /// - Throws: ``PatcherError/invalidFormat(_:)`` when the file is not a+ /// plist, its root is not a dictionary, `Configurations` is missing or+ /// not a dictionary, a speaker configuration is not a dictionary, its+ /// `chainType` is missing or not one of the two strings this patch+ /// knows, or no speaker configuration is present at all. Each is a+ /// reason to stop the install rather than write a half-understood file+ /// back to a mounted guest volume.+ @discardableResult+ public static func patch(+ at url: URL,+ dryRun: Bool = false,+ verbose: Bool = true,+ ) throws -> Outcome {+ let data = try readFile(at: url)+ let format = detectFormat(data)++ guard let parsed = try? PropertyListSerialization.propertyList(+ from: data,+ options: [],+ format: nil,+ ) else {+ throw PatcherError.invalidFormat("cannot parse as plist: \(url.path)")+ }++ guard let plist = parsed as? [String: Any] else {+ throw PatcherError.invalidFormat(+ "top-level plist is \(type(of: parsed)), expected dict: \(url.path)"+ )+ }++ guard let configurations = plist[configurationsKey] as? [String: Any] else {+ throw PatcherError.invalidFormat(+ "no '\(configurationsKey)' dict present: \(url.path)"+ )+ }++ let speakerNames = configurations.keys.filter { $0.hasPrefix("speaker_") }.sorted()+ guard !speakerNames.isEmpty else {+ throw PatcherError.invalidFormat(+ "no 'speaker_' configurations in '\(configurationsKey)': \(url.path)"+ )+ }++ var changed: [String] = []+ for name in speakerNames {+ let configuration = configurations[name]+ guard let entry = configuration as? [String: Any] else {+ throw PatcherError.invalidFormat(+ "configuration '\(name)' is \(type(of: configuration)), expected dict: \(url.path)"+ )+ }+ guard let chainType = entry[chainTypeKey] as? String else {+ throw PatcherError.invalidFormat(+ "configuration '\(name)' has no '\(chainTypeKey)' string: \(url.path)"+ )+ }+ switch chainType {+ case graphChainType:+ continue+ case speakerChainType:+ changed.append(name)+ default:+ throw PatcherError.invalidFormat(+ "configuration '\(name)' has chainType '\(chainType)', expected "+ + "'\(speakerChainType)' or '\(graphChainType)': \(url.path)"+ )+ }+ }++ if changed.isEmpty {+ if verbose {+ print(" [.] \(url.lastPathComponent): \(speakerNames.count) speaker chains already '\(graphChainType)'")+ }+ return .alreadyGraphChains(speakerNames)+ }++ if verbose {+ for name in changed {+ print(" [+] \(url.lastPathComponent): \(name) chainType '\(speakerChainType)' -> '\(graphChainType)'")+ }+ }++ if dryRun {+ if verbose {+ print(" [.] dry-run — not writing back")+ }+ return .dryRun(changed: changed)+ }++ var patched = plist+ var patchedConfigurations = configurations+ for name in changed {+ var entry = patchedConfigurations[name] as! [String: Any]+ entry[chainTypeKey] = graphChainType+ patchedConfigurations[name] = entry+ }+ patched[configurationsKey] = patchedConfigurations++ let output = try PropertyListSerialization.data(+ fromPropertyList: patched,+ format: format,+ options: 0,+ )+ try output.write(to: url)+ return .rewritten(changed: changed)+ }++ // MARK: - Format detection++ /// XML plists start with `<?xml` or `<plist`; binary plists start with+ /// `bplist00`. Same sniff as `CustomFirmwareBuildVersion`, so the two+ /// plist patchers keep provably identical format behaviour.+ static func detectFormat(_ data: Data) -> PropertyListSerialization.PropertyListFormat {+ CustomFirmwareBuildVersion.detectFormat(data)+ }++ private static func readFile(at url: URL) throws -> Data {+ do {+ return try Data(contentsOfFileToRewrite: url)+ } catch {+ throw PatcherError.fileNotFound(url.path)+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swiftnew file mode 100644index 00000000..69470654--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift@@ -0,0 +1,1955 @@+// CustomFirmwareVirtualAudio.swift — keep `No default VAD present` from+// terminating audiomxd.+//+// VirtualAudio walks the current port list applying speaker protection and the+// DSP chain whenever a property write arrives that touches the route (most+// visibly MediaExperience's VAD serialization listener, which pushes saved+// route and volume state on every launch and on every route change). The+// walker needs a `vdef` virtual audio device to apply anything to; when the+// speaker port is published by a device that is not one of VirtualAudio's own+// — the virtio sound device publishing as `PuffinOutput`, whose `pspk` speaker+// port is what makes playback routable in a vphone guest at all — the list it+// is handed can hold no `vdef`, and the walker answers that with+// `throw std::runtime_error("No default VAD present")`.+//+// The throw sits inside an AudioServerPlugIn property callback, which is a C+// boundary that cannot propagate C++ exceptions: the exception reaches+// `std::terminate` and audiomxd aborts. The saved serialization state then+// replays the same write into every later launch, so one abort becomes a+// crash loop until the guest is rebooted.+//+// The walker holds five exception sites — "No default VAD present", two+// "Could not construct" (each behind a routing-mutex assertion), "Unexpected+// HAL speaker protection ... *VP* speaker protection", and a generic+// "Precondition failure." — every one unreachable on real hardware, where the+// built-in speaker is a codec the routing layer grew up with. A guest whose+// speaker arrives any other way reaches them all.+//+// The patch rewrites the first instruction of each throw block — the `mov w0,+// #<size>` that sizes the exception allocation — into a branch to the+// function's own epilogue, so each condition degrades to "apply nothing and+// return". The diagnostic logs that precede the throws are left intact.+//+// Anchoring+// ---------+// Nothing is a literal address. The site is found from the C string+// `No default VAD present`, which the code references exactly twice: once as+// the os_log format's argument (x3) and once as the `runtime_error`+// constructor's message argument (x1), the second reference being the throw+// site. Both references must resolve, and the ctor reference must be the one+// whose `add` is followed by a call. The throw block is then read backwards+// from there: `bl` (the exception allocation) preceded by `movz w0, #imm`.+// The epilogue is found forwards from the `___cxa_throw` call as the stack-+// guard-checked pop sequence ending in `retab`, and its shape is verified+// instruction by instruction before the branch is encoded.+//+// The mute-set throw+// ------------------+// Establishing the route also asks the HAL device itself to unmute:+// Device_HAL_Common's set wrapper pushes `kAudioDevicePropertyMute` through+// `AudioObjectSetPropertyData` and reads it back. iOS's HAL server rejects a+// device-level mute on a plugin device with 'what' without ever forwarding+// the selector to the driver — ASDAudioDevice's dispatch has no case for it+// — and the wrapper answers any failed set by throwing a CAException out of+// the callback. RoutingManager catches it and abandons the route, which+// leaves the vdef's aggregate on Null_Device and the guest silent. Every+// caller of the wrapper ignores its return value, so skipping the throw is+// safe: the FAIL and EXCEPTION diagnostics still log, and the route proceeds+// as if the mute had held.+//+// Anchored on the mute-set log ("Set mute value of %u on HAL device"), whose+// single `__text` reference sits in the wrapper's selector dispatch. Within+// the wrapper, the site is the CAException throw block — the exception+// allocation, the status stored into the object, the throw call — that has+// 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 speaker-protection gate+// ---------------------------+// With the walker and the mute-set throw quieted, a route change still+// declines at the last step: RoutingHandler_Playback_GenericConfig1 builds+// the whole route — virtual stream, DSP chain, format match — and then+// rejects it because the route's device list calls for HAL Speaker+// Protection, a capability only a physical codec reports. The capability+// query never leaves VirtualAudio, so no plugin can provide it. The decline+// is a log line and a branch to the handler's failure path, which leaves the+// vdef's output stream on Null_Device: every "playing" signature is genuine+// and nothing is audible, volume included.+//+// Anchored on the decline's log format, a message three routing handlers+// share — ours is the handler whose log block also names+// RoutingHandler_Playback_GenericConfig1.cpp. The gate's branch is left as+// it is; what changes is the log block it jumps to, whose opening+// instruction — the `mov w0, #<size>` sizing the os_log — becomes a branch+// back to the gate's own fall-through. A taken gate now lands on the+// success path the handler already built, which never reads the verdict+// the gate tested, on either supported build. The block is entered only by+// the gate's jump — the instruction above its head is an unconditional+// branch, checked before anything is written — so no fall-through is+// orphaned, and leaving the gate's branch intact is what lets the anchor+// find the site again on an already-patched binary.+//+// The volume-mode precondition+// ----------------------------+// The gate opened; the route survives its own construction and dies one+// step later on a precondition. The handler asks the volume-mode lookup for+// the route's default scope and requires a packed (present,+// kHardwareOnlyReadOnly) pair back; a device whose software volume runs any+// other mode — the virtio plugin's reports SoftwareHardwareMix — fails the+// test, and the handler answers a `std::logic_error` that unwinds into+// RoutingManager, which fails the route and tears the session down onto+// Null_Device. Same silence as the gate produced, one layer later: by then+// the route had already built its DSP chain, its virtual stream and an+// IOProc on the virtio aggregate.+//+// The precondition's own text survives only in the iOS 27 build+// ("softwareVolumeModeForPerDefaultScope.has_value() && … ==+// kHardwareOnlyReadOnly"); iPadOS 26 stripped it to a bare "Precondition+// failure.". What identifies the site on both builds is the test itself:+// the handler masks the lookup's return with the 33-bit packing mask+// (`and xN, xM, #0x1ffffffff` — a present flag in bit 32 above the mode's+// low 32 bits), compares it against the expected pair, and branches to the+// decline on inequality. Two sibling preconditions in the same handler+// branch off plain flag tests, so the mask is what tells the declines+// apart. The write is the one the speaker-protection gate performs: the+// comparison stays intact, and the decline's log block head becomes a+// 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.++import Foundation+import VPhonePatchKit++/// Turns VirtualAudio's `No default VAD present` exception into a no-op+/// return, so a speaker route published by the virtio device cannot abort+/// audiomxd.+public enum CustomFirmwareVirtualAudio {+ // MARK: - Identity++ /// The exception message, and the anchor string.+ public static let message = "No default VAD present"++ /// The fault log that precedes the walker's direct `std::terminate` call.+ public static let terminateFault = "Speaker Protection is not active on speaker route"++ /// Component name for the patch records.+ public static let component = "virtualaudio"++ /// Record identity, tying the emitted record to its patch-set declaration.+ public static let patchID = "system-virtualaudio-cfw-speaker_route_throws"++ /// The mute-set log format, and the anchor for the set wrapper's patch.+ /// Its full text carries the selector and scope; the needle stops where+ /// the format stays stable across builds.+ public static let muteSetMessage = "Set mute value of %u on HAL device"++ /// The EXCEPTION diagnostic whose log must sit just above the mute-set+ /// throw, telling it apart from the wrapper's other CAException (the+ /// deactivated-device throw iOS 27 builds in).+ public static let muteSetException = "Unable to set property data."++ /// Record identity for the mute-set patch.+ public static let muteSetPatchID = "system-virtualaudio-cfw-mute_set_throw"++ /// The route-decline log format, and the anchor for the SP-gate patch.+ /// Its full text carries the route it declines; the needle stops where+ /// the format stays stable across builds.+ public static let spGateMessage = "HAL Speaker Protection is missing. Failing route"++ /// The routing handler the SP-gate patch targets, named by its own log:+ /// three handlers share the decline's format, and this file's string is+ /// the one the ringtone ('crnp') reconfiguration route runs through.+ public static let spGateFile = "RoutingHandler_Playback_GenericConfig1.cpp"++ /// Record identity for the SP-gate patch.+ public static let spGatePatchID = "system-virtualaudio-cfw-speaker_protection_gate"++ /// The precondition log format the volume-mode decline opens with, and+ /// one anchor of the volume-gate patch. Three declines in this handler+ /// share it; the packing-mask comparison picks ours out.+ public static let volumePreconditionFormat = "PRECONDITION FAILURE (std::logic_error)"++ /// The 33-bit packing mask the handler compares the volume-mode lookup+ /// under — a present flag in bit 32 above the mode's low 32 bits. The+ /// semantic constant the site is recognised by, beside the strings.+ public static let volumeModePackingMask = 0x1ffffffff++ /// Record identity for the volume-gate patch.+ public static let volumeGatePatchID = "system-virtualaudio-cfw-volume_mode_precondition"++ /// Where progress goes when the caller does not say.+ public static let stdoutLog: @Sendable (String) -> Void = { print($0) }++ // MARK: - Results++ public enum Outcome: String, Sendable, Equatable {+ /// The throw block already branched to the epilogue. Nothing was written.+ case alreadyPatched+ /// `dryRun` was set, so the site was located and reported only.+ case wouldPatch+ /// The branch was written and its page re-attested.+ case patched+ }++ /// The resolved pair the patch writes between.+ public struct Anchor: Sendable, Equatable {+ /// `movz w0, #imm` — the first instruction of the throw block.+ public let throwBlockFileOffset: Int+ public let throwBlockVMA: UInt64+ /// The `ldur` that begins the function's epilogue.+ public let epilogueFileOffset: Int+ public let epilogueVMA: UInt64+ }++ public struct Report: Sendable {+ public let outcome: Outcome+ public let anchor: Anchor+ public let records: [PatchRecord]+ public let slotRehashes: [CustomFirmwareSlotRehash]+ }++ /// The resolved pair the mute-set patch writes between.+ public struct MuteSetAnchor: Sendable, Equatable {+ /// `mov w0, #<size>` — the first instruction of the throw block.+ public let throwBlockFileOffset: Int+ public let throwBlockVMA: UInt64+ /// The guarded canary load (or first pop) that begins the wrapper's+ /// epilogue.+ public let epilogueFileOffset: Int+ public let epilogueVMA: UInt64+ }++ public struct MuteSetReport: Sendable {+ public let outcome: Outcome+ public let anchor: MuteSetAnchor+ public let records: [PatchRecord]+ public let slotRehashes: [CustomFirmwareSlotRehash]+ }++ /// The resolved pair the SP-gate patch writes between.+ public struct SPGateAnchor: Sendable, Equatable {+ /// The branch that jumps into the decline's log block — left as it is.+ public let branchFileOffset: Int+ public let branchVMA: UInt64+ /// The log block's entry — the instruction the patch rewrites into a+ /// branch back to the gate's own fall-through.+ public let blockHeadFileOffset: Int+ public let blockHeadVMA: UInt64+ }++ public struct SPGateReport: Sendable {+ public let outcome: Outcome+ public let anchor: SPGateAnchor+ public let records: [PatchRecord]+ public let slotRehashes: [CustomFirmwareSlotRehash]+ }++ /// The resolved pair the volume-gate patch writes between.+ public struct VolumeGateAnchor: Sendable, Equatable {+ /// The conditional branch that jumps into the decline's log block —+ /// left as it is.+ public let branchFileOffset: Int+ public let branchVMA: UInt64+ /// The log block's entry — the instruction the patch rewrites into a+ /// branch back to the comparison's own fall-through.+ public let blockHeadFileOffset: Int+ public let blockHeadVMA: UInt64+ }++ public struct VolumeGateReport: Sendable {+ public let outcome: Outcome+ public let anchor: VolumeGateAnchor+ public let records: [PatchRecord]+ public let slotRehashes: [CustomFirmwareSlotRehash]+ }++ // MARK: - Patching++ /// Patch the VirtualAudio Mach-O at `url` in place.+ ///+ /// Idempotent: a second run recognises its own branch, 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 patch(+ fileAt url: URL,+ reattest: Bool = true,+ dryRun: Bool = false,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> Report {+ 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 patch(&data, reattest: reattest, dryRun: dryRun, log: log)+ if data != before {+ try data.write(to: url)+ }+ return report+ }++ /// In-memory form of ``patch(fileAt:reattest:dryRun:log:)``.+ @discardableResult+ public static func patch(+ _ data: inout Data,+ reattest: Bool = true,+ dryRun: Bool = false,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> Report {+ if data.startIndex != 0 {+ data = Data(data)+ }++ let located = try locate(in: data)+ log?(" [.] speaker-route walker 0x\(hex(located.walkerStartVMA)) … 0x\(hex(located.walkerEndVMA))"+ + "; epilogue 0x\(hex(located.epilogueVMA)); \(located.sites.count) throw site(s)")++ var records: [PatchRecord] = []+ var written: [Int] = []+ var alreadyPatched = 0+ for site in located.sites {+ let siteVMA = located.vma(site)+ let siteInstruction = located.disasm.disassembleOne(in: data, at: site, address: siteVMA)+ if let insn = siteInstruction, insn.isJump, !insn.isCall,+ let word = wordAt(data, site),+ let target = ARM64Encoder.decodeBranchTarget(insn: word, pc: siteVMA),+ target == located.epilogueVMA {+ alreadyPatched += 1+ continue+ }+ guard isExceptionSizeMove(siteInstruction) || siteInstruction?.isCall == true else {+ throw PatcherError.invalidFormat(+ "\(component): site 0x\(hex(siteVMA)) is neither `mov w0, #<size>` nor a call",+ )+ }+ guard let branch = ARM64Encoder.encodeB(from: Int(siteVMA), to: Int(located.epilogueVMA)) else {+ throw PatcherError.patchSiteNotFound(+ "\(component): the epilogue at 0x\(hex(located.epilogueVMA)) is out of "+ + "branch range of the throw block at 0x\(hex(siteVMA))",+ )+ }+ let original = Data(data[site ..< site + 4])+ if dryRun {+ log?(" [.] dry-run — would branch 0x\(hex(siteVMA)) -> 0x\(hex(located.epilogueVMA))")+ continue+ }+ data.replaceSubrange(site ..< site + 4, with: branch)+ written.append(site)+ records.append(PatchRecord(+ patchID: patchID,+ component: component,+ fileOffset: site,+ virtualAddress: siteVMA,+ originalBytes: original,+ patchedBytes: branch,+ beforeDisasm: siteInstruction?.description ?? "",+ afterDisasm: branch.map { String(format: "%02x", $0) }.joined(separator: " "),+ description: "speaker-route walker throw -> epilogue",+ ))+ log?(" [+] 0x\(hex(siteVMA)): \(siteInstruction?.description ?? "") -> b 0x\(hex(located.epilogueVMA))")+ }++ if records.isEmpty, !dryRun {+ log?(" [=] all \(alreadyPatched) throw site(s) already branch to the epilogue")+ }++ 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 Report(+ outcome: outcome,+ anchor: Anchor(+ throwBlockFileOffset: located.sites.first ?? 0,+ throwBlockVMA: located.sites.isEmpty ? 0 : located.vma(located.sites[0]),+ epilogueFileOffset: located.epilogueOffset,+ epilogueVMA: located.epilogueVMA,+ ),+ records: records,+ slotRehashes: rehashes,+ )+ }++ 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+ /// CAException into a quiet return through the wrapper's epilogue.+ ///+ /// Idempotent: a second run recognises its own branch, 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 patchMuteSet(+ fileAt url: URL,+ reattest: Bool = true,+ dryRun: Bool = false,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> MuteSetReport {+ 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 patchMuteSet(&data, reattest: reattest, dryRun: dryRun, log: log)+ if data != before {+ try data.write(to: url)+ }+ return report+ }++ /// In-memory form of ``patchMuteSet(fileAt:reattest:dryRun:log:)``.+ @discardableResult+ public static func patchMuteSet(+ _ data: inout Data,+ reattest: Bool = true,+ dryRun: Bool = false,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> MuteSetReport {+ if data.startIndex != 0 {+ data = Data(data)+ }++ let located = try locateMuteSet(in: data)+ let site = located.site+ let siteVMA = located.vma(site)+ log?(" [.] mute-set wrapper 0x\(hex(located.functionStartVMA)) … 0x\(hex(located.functionEndVMA))"+ + "; epilogue 0x\(hex(located.epilogueVMA)); throw 0x\(hex(siteVMA))")++ let anchor = MuteSetAnchor(+ throwBlockFileOffset: site,+ throwBlockVMA: siteVMA,+ epilogueFileOffset: located.epilogueOffset,+ epilogueVMA: located.epilogueVMA,+ )+ let siteInstruction = located.disasm.disassembleOne(in: data, at: site, address: siteVMA)+ if let insn = siteInstruction, insn.isJump, !insn.isCall,+ let word = wordAt(data, site),+ let target = ARM64Encoder.decodeBranchTarget(insn: word, pc: siteVMA),+ target == located.epilogueVMA {+ log?(" [=] the mute-set throw already branches to the epilogue")+ return MuteSetReport(outcome: .alreadyPatched, anchor: anchor, records: [], slotRehashes: [])+ }+ guard isExceptionSizeMove(siteInstruction) else {+ throw PatcherError.invalidFormat(+ "\(component): the mute-set throw at 0x\(hex(siteVMA)) is not `mov w0, #<size>`",+ )+ }+ guard let branch = ARM64Encoder.encodeB(from: Int(siteVMA), to: Int(located.epilogueVMA)) else {+ throw PatcherError.patchSiteNotFound(+ "\(component): the epilogue at 0x\(hex(located.epilogueVMA)) is out of "+ + "branch range of the mute-set throw at 0x\(hex(siteVMA))",+ )+ }+ let original = Data(data[site ..< site + 4])+ if dryRun {+ log?(" [.] dry-run — would branch 0x\(hex(siteVMA)) -> 0x\(hex(located.epilogueVMA))")+ return MuteSetReport(outcome: .wouldPatch, anchor: anchor, records: [], slotRehashes: [])+ }+ data.replaceSubrange(site ..< site + 4, with: branch)+ log?(" [+] 0x\(hex(siteVMA)): \(siteInstruction?.description ?? "") -> b 0x\(hex(located.epilogueVMA))")+ var rehashes: [CustomFirmwareSlotRehash] = []+ if reattest {+ rehashes = try CustomFirmwareMachOCodeSignature.reattest(&data, modifiedOffsets: [site])+ if !rehashes.isEmpty {+ log?(" [+] re-attested \(rehashes.count) stale slot(s)")+ }+ }+ return MuteSetReport(+ outcome: .patched,+ anchor: anchor,+ records: [PatchRecord(+ patchID: muteSetPatchID,+ component: component,+ fileOffset: site,+ virtualAddress: siteVMA,+ originalBytes: original,+ patchedBytes: branch,+ beforeDisasm: siteInstruction?.description ?? "",+ afterDisasm: branch.map { String(format: "%02x", $0) }.joined(separator: " "),+ description: "mute-set throw -> epilogue",+ )],+ slotRehashes: rehashes,+ )+ }++ // MARK: - SP-gate patching++ /// Patch the VirtualAudio Mach-O at `url` in place, opening the branch+ /// that declines a finished speaker route for lack of HAL Speaker+ /// Protection.+ ///+ /// The gate branch is left untouched; what changes is the decline's own+ /// 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.+ ///+ /// Idempotent: a second run finds the log block's entry holding its own+ /// unconditional branch, 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 patchSpeakerProtectionGate(+ fileAt url: URL,+ reattest: Bool = true,+ dryRun: Bool = false,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> SPGateReport {+ 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 patchSpeakerProtectionGate(&data, reattest: reattest, dryRun: dryRun, log: log)+ if data != before {+ try data.write(to: url)+ }+ return report+ }++ /// In-memory form of ``patchSpeakerProtectionGate(fileAt:reattest:dryRun:log:)``.+ @discardableResult+ public static func patchSpeakerProtectionGate(+ _ data: inout Data,+ reattest: Bool = true,+ dryRun: Bool = false,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> SPGateReport {+ if data.startIndex != 0 {+ data = Data(data)+ }++ let located = try locateSPGate(in: data)+ let head = located.blockHead+ let headVMA = located.vma(head)+ let site = located.site+ let siteVMA = located.vma(site)+ log?(" [.] SP-gate handler 0x\(hex(located.functionStartVMA)) … 0x\(hex(located.functionEndVMA))"+ + "; log block 0x\(hex(headVMA)); gate 0x\(hex(siteVMA))")+ let anchor = SPGateAnchor(+ branchFileOffset: site,+ branchVMA: siteVMA,+ blockHeadFileOffset: head,+ blockHeadVMA: headVMA,+ )++ let headInstruction = located.disasm.disassembleOne(in: data, at: head, address: headVMA)+ if let insn = headInstruction, insn.isJump, !insn.isCall, insn.detail?.conditionCode == nil {+ // An unconditional branch at the head is either this patch's own+ // work or someone else's; the target tells them apart, and+ // someone else's is never overwritten.+ guard let word = wordAt(data, head),+ let target = ARM64Encoder.decodeBranchTarget(insn: word, pc: headVMA),+ target == siteVMA + 4+ else {+ throw PatcherError.invalidFormat(+ "\(component): the log block at 0x\(hex(headVMA)) holds a branch this "+ + "patch did not write",+ )+ }+ log?(" [=] the decline's log block already branches back to the gate's fall-through")+ return SPGateReport(outcome: .alreadyPatched, anchor: anchor, records: [], slotRehashes: [])+ }+ // A pristine block opens the os_log allocation: the size move, then+ // the call that allocates it.+ guard isExceptionSizeMove(headInstruction),+ let next = located.disasm.disassembleOne(in: data, at: head + 4), next.isCall+ else {+ throw PatcherError.invalidFormat(+ "\(component): the log block at 0x\(hex(headVMA)) does not open an os_log allocation",+ )+ }+ guard let branch = ARM64Encoder.encodeB(from: Int(headVMA), to: Int(siteVMA) + 4) else {+ throw PatcherError.patchSiteNotFound(+ "\(component): the fall-through at 0x\(hex(siteVMA + 4)) is out of "+ + "branch range of the log block at 0x\(hex(headVMA))",+ )+ }+ let original = Data(data[head ..< head + 4])+ if dryRun {+ log?(" [.] dry-run — would branch 0x\(hex(headVMA)) -> 0x\(hex(siteVMA + 4))")+ return SPGateReport(outcome: .wouldPatch, anchor: anchor, records: [], slotRehashes: [])+ }+ data.replaceSubrange(head ..< head + 4, with: branch)+ log?(" [+] 0x\(hex(headVMA)): \(headInstruction?.description ?? "") -> b 0x\(hex(siteVMA + 4))")+ var rehashes: [CustomFirmwareSlotRehash] = []+ if reattest {+ rehashes = try CustomFirmwareMachOCodeSignature.reattest(&data, modifiedOffsets: [head])+ if !rehashes.isEmpty {+ log?(" [+] re-attested \(rehashes.count) stale slot(s)")+ }+ }+ return SPGateReport(+ outcome: .patched,+ anchor: anchor,+ records: [PatchRecord(+ patchID: spGatePatchID,+ component: component,+ fileOffset: head,+ virtualAddress: headVMA,+ originalBytes: original,+ patchedBytes: branch,+ beforeDisasm: headInstruction?.description ?? "",+ afterDisasm: branch.map { String(format: "%02x", $0) }.joined(separator: " "),+ description: "speaker-protection decline -> gate fall-through",+ )],+ slotRehashes: rehashes,+ )+ }++ // MARK: - Volume-gate patching++ /// Patch the VirtualAudio Mach-O at `url` in place, opening the branch+ /// that declines a finished route when its software-volume mode is not+ /// the kHardwareOnlyReadOnly the routing database demands.+ ///+ /// The comparison is left untouched; what changes is the decline's own+ /// log block: its entry — the `mov w0, #<size>` that opens the os_log —+ /// is rewritten into a branch back to the comparison's fall-through, so+ /// a failed precondition lands on the success path the handler already+ /// built. The block is reachable only by the comparison's jump (its+ /// predecessor is an unconditional branch, verified before writing) and+ /// that success path never reads the value the comparison tested, on+ /// either supported build.+ ///+ /// Idempotent: a second run finds the log block's entry holding its own+ /// unconditional branch, 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 patchVolumeModePrecondition(+ fileAt url: URL,+ reattest: Bool = true,+ dryRun: Bool = false,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> VolumeGateReport {+ 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 patchVolumeModePrecondition(&data, reattest: reattest, dryRun: dryRun, log: log)+ if data != before {+ try data.write(to: url)+ }+ return report+ }++ /// In-memory form of ``patchVolumeModePrecondition(fileAt:reattest:dryRun:log:)``.+ @discardableResult+ public static func patchVolumeModePrecondition(+ _ data: inout Data,+ reattest: Bool = true,+ dryRun: Bool = false,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> VolumeGateReport {+ if data.startIndex != 0 {+ data = Data(data)+ }++ let located = try locateVolumeGate(in: data)+ let head = located.blockHead+ let headVMA = located.vma(head)+ let site = located.site+ let siteVMA = located.vma(site)+ log?(" [.] volume-gate handler 0x\(hex(located.functionStartVMA)) … 0x\(hex(located.functionEndVMA))"+ + "; log block 0x\(hex(headVMA)); comparison 0x\(hex(siteVMA))")+ let anchor = VolumeGateAnchor(+ branchFileOffset: site,+ branchVMA: siteVMA,+ blockHeadFileOffset: head,+ blockHeadVMA: headVMA,+ )++ let headInstruction = located.disasm.disassembleOne(in: data, at: head, address: headVMA)+ if let insn = headInstruction, insn.isJump, !insn.isCall, insn.detail?.conditionCode == nil {+ // An unconditional branch at the head is either this patch's own+ // work or someone else's; the target tells them apart, and+ // someone else's is never overwritten.+ guard let word = wordAt(data, head),+ let target = ARM64Encoder.decodeBranchTarget(insn: word, pc: headVMA),+ target == siteVMA + 4+ else {+ throw PatcherError.invalidFormat(+ "\(component): the log block at 0x\(hex(headVMA)) holds a branch this "+ + "patch did not write",+ )+ }+ log?(" [=] the decline's log block already branches back to the comparison's fall-through")+ return VolumeGateReport(outcome: .alreadyPatched, anchor: anchor, records: [], slotRehashes: [])+ }+ // A pristine block opens the os_log allocation: the size move, then+ // the call that allocates it.+ guard isExceptionSizeMove(headInstruction),+ let next = located.disasm.disassembleOne(in: data, at: head + 4), next.isCall+ else {+ throw PatcherError.invalidFormat(+ "\(component): the log block at 0x\(hex(headVMA)) does not open an os_log allocation",+ )+ }+ guard let branch = ARM64Encoder.encodeB(from: Int(headVMA), to: Int(siteVMA) + 4) else {+ throw PatcherError.patchSiteNotFound(+ "\(component): the fall-through at 0x\(hex(siteVMA + 4)) is out of "+ + "branch range of the log block at 0x\(hex(headVMA))",+ )+ }+ let original = Data(data[head ..< head + 4])+ if dryRun {+ log?(" [.] dry-run — would branch 0x\(hex(headVMA)) -> 0x\(hex(siteVMA + 4))")+ return VolumeGateReport(outcome: .wouldPatch, anchor: anchor, records: [], slotRehashes: [])+ }+ data.replaceSubrange(head ..< head + 4, with: branch)+ log?(" [+] 0x\(hex(headVMA)): \(headInstruction?.description ?? "") -> b 0x\(hex(siteVMA + 4))")+ var rehashes: [CustomFirmwareSlotRehash] = []+ if reattest {+ rehashes = try CustomFirmwareMachOCodeSignature.reattest(&data, modifiedOffsets: [head])+ if !rehashes.isEmpty {+ log?(" [+] re-attested \(rehashes.count) stale slot(s)")+ }+ }+ return VolumeGateReport(+ outcome: .patched,+ anchor: anchor,+ records: [PatchRecord(+ patchID: volumeGatePatchID,+ component: component,+ fileOffset: head,+ virtualAddress: headVMA,+ originalBytes: original,+ patchedBytes: branch,+ beforeDisasm: headInstruction?.description ?? "",+ afterDisasm: branch.map { String(format: "%02x", $0) }.joined(separator: " "),+ description: "volume-mode precondition -> comparison fall-through",+ )],+ slotRehashes: rehashes,+ )+ }++ // MARK: - Anchoring++ /// Resolve the throw block and the epilogue, or say why not.+ /// Everything the patch needs: the walker's bounds, its epilogue, and+ /// every throw site inside it.+ struct Plan: Sendable {+ let disasm: ARM64Disassembler+ let textStart: Int+ let textAddress: UInt64+ let walkerStartOffset: Int+ let walkerEndOffset: Int+ let epilogueOffset: Int+ let epilogueVMA: UInt64+ let sites: [Int]++ var walkerStartVMA: UInt64 { vma(walkerStartOffset) }+ var walkerEndVMA: UInt64 { vma(walkerEndOffset) }+ func vma(_ offset: Int) -> UInt64 { textAddress + UInt64(offset - textStart) }+ }++ static func locate(in data: Data) throws -> Plan {+ 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()++ let stringVMA = try locateMessage(in: data, sections: sections)+ let references = adrpAddReferences(to: 0, formingAnyOf: [stringVMA], in: data, textStart: textStart, textEnd: textEnd)+ guard references.count == 1 else {+ throw PatcherError.patchSiteNotFound(+ "\(component): expected exactly 1 reference to \"\(message)\" (the exception "+ + "constructor's), found \(references.count)",+ )+ }+ let ctor = references[0]+ guard disasm.disassembleOne(in: data, at: ctor.add + 4)?.isCall == true else {+ throw PatcherError.patchSiteNotFound(+ "\(component): the reference to \"\(message)\" is not the exception constructor's",+ )+ }+ guard nearbyLogReference(in: data, sections: sections, textStart: textStart, textEnd: textEnd, before: ctor.adrp) != nil else {+ throw PatcherError.patchSiteNotFound(+ "\(component): no diagnostic-log reference above the throw to corroborate it",+ )+ }++ // The walker: the function whose prologue stands above the anchor and+ // whose next prologue closes it.+ let walkerStart = nearestPrologue(in: data, disasm: disasm, below: ctor.adrp, floor: textStart)+ ?? textStart+ let walkerEnd = nearestPrologue(in: data, disasm: disasm, atOrAfter: walkerStart + 4, ceiling: textEnd)+ ?? textEnd++ // The epilogue: the guarded pop run after the anchor's throw.+ guard let terminator = firstUnconditionalBranch(in: data, disasm: disasm, after: ctor.add + 4, textEnd: walkerEnd) else {+ throw PatcherError.patchSiteNotFound(+ "\(component): no terminator branch after the exception constructor",+ )+ }+ let epilogueOffset = try locateEpilogue(in: data, disasm: disasm, after: terminator, textEnd: walkerEnd)++ // Every throw block in the walker: a `mov w0, #<size>` whose next+ // instruction calls the exception allocator, followed within a short+ // window by a message load into x1 and a constructor call, and closed+ // by the terminator branch.+ var sites: [Int] = []+ var offset = walkerStart+ while offset + 4 <= walkerEnd {+ defer { offset += 4 }+ guard let insn = disasm.disassembleOne(in: data, at: offset),+ isExceptionSizeMove(insn) || (insn.isJump && !insn.isCall),+ let next = disasm.disassembleOne(in: data, at: offset + 4), next.isCall+ else { continue }+ // An already-patched site still carries its allocation call and+ // the whole machinery below, so the shape check holds for it too+ // and `patch` recognises its own branch when it writes.+ if isThrowBlock(in: data, disasm: disasm, from: offset + 4, to: walkerEnd) {+ sites.append(offset)+ }+ }+ var allSites = sites+ if let terminate = terminateSite(+ in: data,+ disasm: disasm,+ sections: sections,+ textStart: textStart,+ textEnd: textEnd,+ walkerStart: walkerStart,+ walkerEnd: walkerEnd,+ epilogueVMA: text.address + UInt64(epilogueOffset - textStart),+ ) {+ allSites.append(terminate)+ }++ guard !allSites.isEmpty else {+ throw PatcherError.patchSiteNotFound(+ "\(component): no exception throw blocks in the walker at 0x\(hex(UInt64(textStart)))",+ )+ }++ return Plan(+ disasm: disasm,+ textStart: textStart,+ textAddress: text.address,+ walkerStartOffset: walkerStart,+ walkerEndOffset: walkerEnd,+ epilogueOffset: epilogueOffset,+ epilogueVMA: text.address + UInt64(epilogueOffset - textStart),+ sites: allSites.sorted(),+ )+ }++ // MARK: - Mute-set anchoring++ /// Everything the mute-set patch needs: the set wrapper's bounds, its+ /// epilogue, and its throw site.+ struct MuteSetPlan: Sendable {+ let disasm: ARM64Disassembler+ let textStart: Int+ let textAddress: UInt64+ let functionStartOffset: Int+ let functionEndOffset: Int+ let epilogueOffset: Int+ let epilogueVMA: UInt64+ let site: Int++ var functionStartVMA: UInt64 { vma(functionStartOffset) }+ var functionEndVMA: UInt64 { vma(functionEndOffset) }+ func vma(_ offset: Int) -> UInt64 { textAddress + UInt64(offset - textStart) }+ }++ /// Resolve the mute-set throw and the wrapper's epilogue, or say why not.+ static func locateMuteSet(in data: Data) throws -> MuteSetPlan {+ 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()++ // The anchor: the mute-set log format, referenced exactly once in+ // __text — by the wrapper's selector dispatch.+ guard let logVMA = cStringVMA(containing: muteSetMessage, in: data, sections: sections) else {+ throw PatcherError.patchSiteNotFound(+ "\(component): the string \"\(muteSetMessage)\" is nowhere in the binary's sections",+ )+ }+ let references = adrpAddReferences(+ to: 0,+ formingAnyOf: [logVMA],+ in: data,+ textStart: textStart,+ textEnd: textEnd,+ )+ guard references.count == 1 else {+ throw PatcherError.patchSiteNotFound(+ "\(component): expected exactly 1 reference to \"\(muteSetMessage)\", found \(references.count)",+ )+ }++ // The wrapper: the function whose prologue stands above the log+ // reference and whose next prologue closes it.+ let functionStart = nearestPrologue(in: data, disasm: disasm, below: references[0].adrp, floor: textStart)+ ?? textStart+ let functionEnd = nearestPrologue(in: data, disasm: disasm, atOrAfter: functionStart + 4, ceiling: textEnd)+ ?? textEnd++ // The throw: the wrapper's CAException block whose EXCEPTION log sits+ // just above it. iOS 27's wrapper holds a second CAException — the+ // deactivated-device throw — and the log window is what tells them+ // apart.+ let exceptionStrings = cStringVMAs(containing: muteSetException, in: data, sections: sections)+ guard !exceptionStrings.isEmpty else {+ throw PatcherError.patchSiteNotFound(+ "\(component): the string \"\(muteSetException)\" is nowhere in the binary's sections",+ )+ }+ var sites: [Int] = []+ var offset = functionStart+ while offset + 4 <= functionEnd {+ defer { offset += 4 }+ guard let insn = disasm.disassembleOne(in: data, at: offset),+ isExceptionSizeMove(insn) || (insn.isJump && !insn.isCall),+ let next = disasm.disassembleOne(in: data, at: offset + 4), next.isCall+ else { continue }+ // An already-patched site still carries the allocation call and+ // the stores below it, so the shape holds for it too and+ // `patchMuteSet` recognises its own branch when it writes.+ guard isCAExceptionThrowBlock(in: data, disasm: disasm, from: offset + 4, to: functionEnd),+ hasExceptionLogWindow(+ in: data,+ textStart: textStart,+ before: offset,+ targets: exceptionStrings,+ )+ else { continue }+ sites.append(offset)+ }+ guard sites.count == 1, let site = sites.first else {+ throw PatcherError.patchSiteNotFound(+ "\(component): expected exactly 1 mute-set throw in the wrapper at 0x\(hex(text.address + UInt64(functionStart - textStart))), found \(sites.count)",+ )+ }++ // 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] = []+ offset = functionStart+ while offset + 4 <= functionEnd {+ if let insn = disasm.disassembleOne(in: data, at: offset), insn.mnemonic == "retab" {+ retabs.append(offset)+ }+ offset += 4+ }+ guard retabs.count == 1, let retab = retabs.first else {+ throw PatcherError.patchSiteNotFound(+ "\(component): expected exactly 1 `retab` in the mute-set wrapper, found \(retabs.count)",+ )+ }+ let epilogueOffset = try epilogueEntry(in: data, disasm: disasm, retab: retab)++ return MuteSetPlan(+ disasm: disasm,+ textStart: textStart,+ textAddress: text.address,+ functionStartOffset: functionStart,+ functionEndOffset: functionEnd,+ epilogueOffset: epilogueOffset,+ epilogueVMA: text.address + UInt64(epilogueOffset - textStart),+ site: site,+ )+ }++ // MARK: - SP-gate anchoring++ /// Everything the SP-gate patch needs: the routing handler's bounds, the+ /// decline's log block, and the branch that jumps into it. The branch is+ /// found the same way on a pristine and on an already-patched binary —+ /// the patch leaves it intact and rewrites the block's head instead.+ struct SPGatePlan: Sendable {+ let disasm: ARM64Disassembler+ let textStart: Int+ let textAddress: UInt64+ let functionStartOffset: Int+ let functionEndOffset: Int+ let blockHead: Int+ let site: Int++ var functionStartVMA: UInt64 { vma(functionStartOffset) }+ var functionEndVMA: UInt64 { vma(functionEndOffset) }+ func vma(_ offset: Int) -> UInt64 { textAddress + UInt64(offset - textStart) }+ }++ /// How far above a branch target the format-string reference may sit and+ /// still be inside the log block that target heads. Both supported+ /// builds hold the os_log's file-name and format references 0x34 apart,+ /// 0x84 above the block's entry; the budget covers the shape, not those+ /// exact figures.+ private static let spGateBlockWindow = 0x100++ /// The ringtone ('crnp') routing handler both gate patches live in,+ /// resolved once and shared: the SP-missing decline and the volume-mode+ /// precondition sit in the same function, qualified by the same pair of+ /// strings.+ struct PlaybackHandler: Sendable {+ let disasm: ARM64Disassembler+ let textStart: Int+ let textAddress: UInt64+ let functionStartOffset: Int+ let functionEndOffset: Int+ /// The SP-missing format reference that qualified the handler.+ let reference: (adrp: Int, add: Int)+ /// The handler's own source-file string addresses — the corroboration+ /// both gate scans read.+ let fileNameVMAs: Set<UInt64>++ var functionStartVMA: UInt64 { vma(functionStartOffset) }+ var functionEndVMA: UInt64 { vma(functionEndOffset) }+ func vma(_ offset: Int) -> UInt64 { textAddress + UInt64(offset - textStart) }+ }++ /// Resolve the routing handler, or say why not. The anchors are the+ /// SP-missing decline's log format and the handler's own source file:+ /// the format alone names three routing handlers, and of the functions+ /// holding a reference to it, exactly one — ours — also references the+ /// GenericConfig1 file name.+ static func locatePlaybackHandler(in data: Data) throws -> PlaybackHandler {+ 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()++ let formats = cStringVMAs(containing: spGateMessage, in: data, sections: sections)+ guard !formats.isEmpty else {+ throw PatcherError.patchSiteNotFound(+ "\(component): the string \"\(spGateMessage)\" is nowhere in the binary's sections",+ )+ }+ let fileNames = cStringVMAs(containing: spGateFile, in: data, sections: sections)+ guard !fileNames.isEmpty else {+ throw PatcherError.patchSiteNotFound(+ "\(component): the string \"\(spGateFile)\" is nowhere in the binary's sections",+ )+ }++ let references = adrpAddReferences(+ to: 0,+ formingAnyOf: formats,+ in: data,+ textStart: textStart,+ textEnd: textEnd,+ )+ guard !references.isEmpty else {+ throw PatcherError.patchSiteNotFound(+ "\(component): no reference to \"\(spGateMessage)\" in __text",+ )+ }++ var qualified: [(reference: (adrp: Int, add: Int), start: Int, end: Int)] = []+ for reference in references {+ let start = nearestPrologue(in: data, disasm: disasm, below: reference.adrp, floor: textStart)+ ?? textStart+ let end = nearestPrologue(in: data, disasm: disasm, atOrAfter: start + 4, ceiling: textEnd)+ ?? textEnd+ let corroborated = adrpAddReferences(+ to: 0,+ formingAnyOf: fileNames,+ in: data,+ textStart: start,+ textEnd: end,+ )+ if !corroborated.isEmpty {+ qualified.append((reference, start, end))+ }+ }+ guard qualified.count == 1, let handler = qualified.first else {+ throw PatcherError.patchSiteNotFound(+ "\(component): expected exactly 1 \"\(spGateFile)\" handler referencing "+ + "\"\(spGateMessage)\", found \(qualified.count)",+ )+ }+ return PlaybackHandler(+ disasm: disasm,+ textStart: textStart,+ textAddress: text.address,+ functionStartOffset: handler.start,+ functionEndOffset: handler.end,+ reference: handler.reference,+ fileNameVMAs: fileNames,+ )+ }++ /// Resolve the SP-gate branch, or say why not.+ static func locateSPGate(in data: Data) throws -> SPGatePlan {+ let handler = try locatePlaybackHandler(in: data)+ func vma(_ offset: Int) -> UInt64 { handler.vma(offset) }+ func offset(of address: UInt64) -> Int { handler.textStart + Int(address - handler.textAddress) }++ // The gate: the one branch in the handler whose target heads the log+ // block — a target at or above which, within the window, the format+ // reference sits and the handler's own file name is referenced too.+ // The os_log block carries both strings; a branch into any other+ // label in the window does not qualify.+ //+ // Each word is decoded rather than trusted to Capstone's jump group:+ // the gate is a `tbz`, which the group tagging misses, and the op+ // fields the decoded families live in hold nothing but branches.+ // The gate's branch is never rewritten, so the scan resolves the+ // same candidate on a pristine and on an already-patched binary+ // alike.+ var candidates: [(site: Int, head: Int)] = []+ var cursor = handler.functionStartOffset+ while cursor + 4 <= handler.functionEndOffset {+ defer { cursor += 4 }+ guard let insn = handler.disasm.disassembleOne(in: data, at: cursor),+ !insn.isCall,+ let word = wordAt(data, cursor),+ let target = branchTargetValue(insn: word, pc: vma(cursor))+ else { continue }+ let head = offset(of: target)+ guard cursor < head, head >= handler.functionStartOffset,+ head <= handler.reference.add, handler.reference.add - head <= spGateBlockWindow+ else { continue }+ let names = adrpAddReferences(+ to: 0,+ formingAnyOf: handler.fileNameVMAs,+ in: data,+ textStart: head,+ textEnd: handler.reference.add + 4,+ )+ guard !names.isEmpty else { continue }+ // The head must be the block's own opening — the os_log size+ // move and the allocation call, which is exactly what the patch+ // rewrites — or, once it has run, the branch back to the gate's+ // fall-through that replaced them. Any other label inside the+ // window is not the block's head, whichever branch lands on it.+ let headInsn = handler.disasm.disassembleOne(in: data, at: head)+ let opensLog = isExceptionSizeMove(headInsn)+ && handler.disasm.disassembleOne(in: data, at: head + 4)?.isCall == true+ let holdsOurBranch: Bool = {+ guard let insn = headInsn, insn.isJump, !insn.isCall,+ insn.detail?.conditionCode == nil,+ let word = wordAt(data, head)+ else { return false }+ return ARM64Encoder.decodeBranchTarget(insn: word, pc: vma(head)) == vma(cursor) + 4+ }()+ guard opensLog || holdsOurBranch else { continue }+ candidates.append((cursor, head))+ }+ guard candidates.count == 1, let gate = candidates.first else {+ throw PatcherError.patchSiteNotFound(+ "\(component): expected exactly 1 branch into the SP-missing log block in "+ + "the handler at 0x\(hex(vma(handler.functionStartOffset))), found \(candidates.count)",+ )+ }++ // The block is entered only by the gate's jump: the instruction+ // above its head must not fall through. That is what 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.isJump && !above.isCall && above.detail?.conditionCode == nil)+ else {+ throw PatcherError.invalidFormat(+ "\(component): the log block at 0x\(hex(vma(gate.head))) is reached by "+ + "fall-through, not only by the gate's jump",+ )+ }++ return SPGatePlan(+ disasm: handler.disasm,+ textStart: handler.textStart,+ textAddress: handler.textAddress,+ functionStartOffset: handler.functionStartOffset,+ functionEndOffset: handler.functionEndOffset,+ blockHead: gate.head,+ site: gate.site,+ )+ }++ // MARK: - Volume-gate anchoring++ /// Everything the volume-gate patch needs: the routing handler's bounds,+ /// the decline's log block, and the comparison that jumps into it. The+ /// comparison is found the same way on a pristine and on an+ /// already-patched binary — the patch leaves it intact and rewrites the+ /// block's head instead.+ struct VolumeGatePlan: Sendable {+ let disasm: ARM64Disassembler+ let textStart: Int+ let textAddress: UInt64+ let functionStartOffset: Int+ let functionEndOffset: Int+ let blockHead: Int+ let site: Int++ var functionStartVMA: UInt64 { vma(functionStartOffset) }+ var functionEndVMA: UInt64 { vma(functionEndOffset) }+ func vma(_ offset: Int) -> UInt64 { textAddress + UInt64(offset - textStart) }+ }++ /// How far above a branch target the precondition block's format and+ /// file-name references may sit. Both supported builds hold them 0x2c+ /// and 0x58 above the block's entry — the same layout every decline log+ /// in this handler carries; the budget covers the shape, not those+ /// exact figures.+ private static let volumeGateBlockWindow = 0x100++ /// Resolve the volume-mode comparison and its decline, or say why not.+ /// The decline is one of three in this handler that open with the same+ /// PRECONDITION FAILURE format; what picks ours out is the comparison+ /// that reaches it — the only one that masks a lookup's return with the+ /// 33-bit volume-mode packing mask and compares it against the expected+ /// packed pair. The sibling preconditions branch off plain flag tests.+ static func locateVolumeGate(in data: Data) throws -> VolumeGatePlan {+ let sections = MachOParser.parseSections(from: data)+ let handler = try locatePlaybackHandler(in: data)+ let formats = cStringVMAs(containing: volumePreconditionFormat, in: data, sections: sections)+ guard !formats.isEmpty else {+ throw PatcherError.patchSiteNotFound(+ "\(component): the string \"\(volumePreconditionFormat)\" is nowhere in the binary's sections",+ )+ }+ func vma(_ offset: Int) -> UInt64 { handler.vma(offset) }+ func offset(of address: UInt64) -> Int { handler.textStart + Int(address - handler.textAddress) }++ // The comparison: the one branch in the handler whose target heads a+ // precondition log block — both the format and the handler's own+ // file name referenced within the window, and the target opening the+ // os_log allocation — and whose own backward window holds the+ // packing-mask `and` over a call's return, closed by the branch.+ // Each word is decoded rather than trusted to Capstone's jump group:+ // the comparison's branch is a `b.ne`, and the op fields the decoded+ // families live in hold nothing but branches. The branch is never+ // rewritten, so the scan resolves the same candidate on a pristine+ // and on an already-patched binary alike.+ var candidates: [(site: Int, head: Int)] = []+ var cursor = handler.functionStartOffset+ while cursor + 4 <= handler.functionEndOffset {+ defer { cursor += 4 }+ guard let insn = handler.disasm.disassembleOne(in: data, at: cursor),+ !insn.isCall,+ let word = wordAt(data, cursor),+ let target = branchTargetValue(insn: word, pc: vma(cursor))+ else { continue }+ let head = offset(of: target)+ guard cursor < head, head >= handler.functionStartOffset,+ !adrpAddReferences(+ to: 0,+ formingAnyOf: formats,+ in: data,+ textStart: head,+ textEnd: head + volumeGateBlockWindow,+ ).isEmpty,+ !adrpAddReferences(+ to: 0,+ formingAnyOf: handler.fileNameVMAs,+ in: data,+ textStart: head,+ textEnd: head + volumeGateBlockWindow,+ ).isEmpty+ else { continue }+ // The head must be the block's own opening — the os_log size+ // move and the allocation call, which is exactly what the patch+ // rewrites — or, once it has run, the branch back to the+ // comparison's fall-through that replaced them. The block's own+ // exception-allocation label and its log-enable skips hold size+ // moves too; the comparison window below the branch is what+ // rejects them.+ let headInsn = handler.disasm.disassembleOne(in: data, at: head)+ let opensLog = isExceptionSizeMove(headInsn)+ && handler.disasm.disassembleOne(in: data, at: head + 4)?.isCall == true+ let holdsOurBranch: Bool = {+ guard let insn = headInsn, insn.isJump, !insn.isCall,+ insn.detail?.conditionCode == nil,+ let word = wordAt(data, head)+ else { return false }+ return ARM64Encoder.decodeBranchTarget(insn: word, pc: vma(head)) == vma(cursor) + 4+ }()+ guard opensLog || holdsOurBranch,+ isVolumeModeComparison(in: data, disasm: handler.disasm, below: cursor)+ else { continue }+ candidates.append((cursor, head))+ }+ guard candidates.count == 1, let gate = candidates.first else {+ throw PatcherError.patchSiteNotFound(+ "\(component): expected exactly 1 volume-mode comparison guarding a "+ + "precondition decline in the handler at 0x\(hex(vma(handler.functionStartOffset))), "+ + "found \(candidates.count)",+ )+ }++ // The block is entered only by the comparison's jump: the+ // instruction above its head must not fall through. That is what+ // 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.isJump && !above.isCall && above.detail?.conditionCode == nil)+ else {+ throw PatcherError.invalidFormat(+ "\(component): the precondition block at 0x\(hex(vma(gate.head))) is reached by "+ + "fall-through, not only by the comparison's jump",+ )+ }++ return VolumeGatePlan(+ disasm: handler.disasm,+ textStart: handler.textStart,+ textAddress: handler.textAddress,+ functionStartOffset: handler.functionStartOffset,+ functionEndOffset: handler.functionEndOffset,+ blockHead: gate.head,+ site: gate.site,+ )+ }++ /// Whether the branch at `branch` closes a volume-mode comparison: the+ /// packing-mask `and` over a lookup's return within a few instructions+ /// below it, a `cmp` between the two, and the call that produced the+ /// masked value directly below the `and`. The sibling preconditions in+ /// this handler branch off plain flag tests, so this is what tells the+ /// declines apart.+ private static func isVolumeModeComparison(+ in data: Data,+ disasm: ARM64Disassembler,+ below branch: Int,+ ) -> Bool {+ var sawCompare = false+ var cursor = branch - 4+ // Six instructions reach from the branch past the whole masked+ // compare on both supported builds (`cmp; add; and; bl`).+ while cursor >= branch - 24 {+ defer { cursor -= 4 }+ guard let insn = disasm.disassembleOne(in: data, at: cursor) else { return false }+ if insn.mnemonic == "cmp" { sawCompare = true }+ guard insn.mnemonic == "and",+ let operands = insn.detail?.operands, operands.count >= 3,+ operands[2].type == .immediate,+ operands[2].imm == volumeModePackingMask+ else { continue }+ // The masked value is a lookup's return: the call that produced+ // it sits directly below the `and`.+ guard disasm.disassembleOne(in: data, at: cursor - 4)?.isCall == true else { return false }+ return sawCompare+ }+ return false+ }++ /// 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+ /// rest.+ private static func branchTargetValue(insn word: UInt32, pc: UInt64) -> UInt64? {+ ARM64Encoder.decodeBranchTarget(insn: word, pc: pc)+ ?? decodeConditionalBranchTarget(insn: word, pc: pc)+ }++ /// The target of the conditional-branch families, which+ /// ``ARM64Encoder.decodeBranchTarget(insn:pc:)`` (the `b`/`bl` pair)+ /// does not decode: `b.cond` and `cbz`/`cbnz` carry a 19-bit immediate+ /// at bits 23-5, `tbz`/`tbnz` a 14-bit one at bits 18-5. The SP-gate+ /// branch is a `tbz`. Analysis only: this reads where a branch goes, it+ /// assembles nothing.+ static func decodeConditionalBranchTarget(insn: UInt32, pc: UInt64) -> UInt64? {+ // b.cond: bits 31-24 = 01010100. The PAUTH BC.cond shares the top+ // seven bits but sets bit 24, and names a register, not an offset.+ if insn >> 24 == 0b0101_0100 {+ let imm19 = (insn >> 5) & 0x7FFFF+ let signed = Int32(bitPattern: imm19 << 13) >> 13+ return UInt64(Int64(pc) + Int64(signed) * 4)+ }+ // cbz/cbnz (bits 30-25 = 011010) and tbz/tbnz (011011): the leading+ // bit is sf/b5, which does not change how far the branch reaches.+ switch (insn >> 25) & 0x3F {+ case 0b011010:+ let imm19 = (insn >> 5) & 0x7FFFF+ let signed = Int32(bitPattern: imm19 << 13) >> 13+ return UInt64(Int64(pc) + Int64(signed) * 4)+ case 0b011011:+ let imm14 = (insn >> 5) & 0x3FFF+ let signed = Int32(bitPattern: imm14 << 18) >> 18+ return UInt64(Int64(pc) + Int64(signed) * 4)+ default:+ return nil+ }+ }++ /// Whether the window after an allocation call holds the CAException+ /// throw machinery: the vtable or status stored into the allocated object+ /// (`str xN, [x0, #imm]`), the throw call after it, and the block's+ /// terminator. A CAException carries no message string, so the+ /// `runtime_error` shape (`isThrowBlock`) does not fit it.+ private static func isCAExceptionThrowBlock(+ in data: Data,+ disasm: ARM64Disassembler,+ from offset: Int,+ to end: Int,+ ) -> Bool {+ var cursor = offset+ var sawObjectStore = false+ var sawThrowCall = false+ var scanned = 0+ // A CAException block runs longer than a runtime_error one — the+ // vtable and its PAC discriminators, the status store, the typeinfo+ // pointer — 17 instructions on both supported builds before the+ // terminator, so the budget reaches past it.+ while cursor + 4 <= end, scanned < 32 {+ defer {+ cursor += 4+ scanned += 1+ }+ guard let insn = disasm.disassembleOne(in: data, at: cursor) else { return false }+ if insn.mnemonic == "str",+ let operands = insn.detail?.operands, operands.count >= 2,+ operands[0].type == .register,+ operands[1].type == .memory, operands[1].mem.base == ARM64Register.x(0) {+ sawObjectStore = true+ }+ if insn.isCall, sawObjectStore {+ sawThrowCall = true+ continue+ }+ // The block ends at an unconditional branch (the iOS 27 twin jumps+ // to its `brk`) or at the `brk` the compiler plants after a call+ // it knows never returns.+ if insn.mnemonic == "brk"+ || (insn.isJump && !insn.isCall && insn.detail?.conditionCode == nil) {+ return sawObjectStore && sawThrowCall+ }+ }+ return false+ }++ /// Whether an adrp+add pair within `window` bytes above the site forms+ /// one of `targets` — the EXCEPTION log that always precedes this throw.+ private static func hasExceptionLogWindow(+ in data: Data,+ textStart: Int,+ before site: Int,+ targets: Set<UInt64>,+ window: Int = 0x40,+ ) -> Bool {+ !adrpAddReferences(+ to: 0,+ formingAnyOf: targets,+ in: data,+ textStart: max(textStart, site - window),+ textEnd: site,+ ).isEmpty+ }++ /// The address of the cstring containing `needle`, in a real string+ /// section. The os_log formats begin with a `%25s:%-5d` prefix, so the+ /// reference the code materialises points at the whole string's start,+ /// not at the needle itself.+ private static func cStringVMA(containing needle: String, in data: Data, sections: [String: MachOSectionInfo]) -> UInt64? {+ cStringVMAs(containing: needle, in: data, sections: sections).first+ }++ /// Every such address, one per section occurrence — a message can live in+ /// more than one string, and the callers only need the set for+ /// corroboration.+ private static func cStringVMAs(containing needle: String, in data: Data, sections: [String: MachOSectionInfo]) -> Set<UInt64> {+ let bytes = Array(needle.utf8)+ // cstring sections first, then any other section that still holds+ // file bytes; the signature and symbol tables are not sections.+ let searchable = sections.values+ .filter { $0.fileOffset > 0 && Int($0.fileOffset) + Int($0.size) <= data.count }+ .sorted { lhs, rhs in+ let l = lhs.sectionName == "__cstring"+ let r = rhs.sectionName == "__cstring"+ if l != r { return l }+ return lhs.fileOffset < rhs.fileOffset+ }+ var addresses: Set<UInt64> = []+ for section in searchable {+ let start = Int(section.fileOffset)+ let end = start + Int(section.size)+ var searchFrom = start+ while searchFrom + bytes.count <= end,+ let match = range(of: bytes, in: data, start: searchFrom, end: end) {+ let stringStart = cStringStart(in: data, containing: match, notBefore: start)+ addresses.insert(section.address + UInt64(stringStart - start))+ searchFrom = match + 1+ }+ }+ return addresses+ }++ /// The walker's direct `std::terminate` call. The compiler ends a+ /// fault-logged fatal path with a run of back-to-back `bl`s — the log, its+ /// releases — closed by the terminate call, whose successor is never a+ /// call. Anchored on the fault's own string, not on the stub address.+ private static func terminateSite(+ in data: Data,+ disasm: ARM64Disassembler,+ sections: [String: MachOSectionInfo],+ textStart: Int,+ textEnd: Int,+ walkerStart: Int,+ walkerEnd: Int,+ epilogueVMA: UInt64,+ ) -> Int? {+ let needle = Array((terminateFault + "\0").utf8)+ var faultVMA: UInt64?+ for section in sections.values+ where section.fileOffset > 0 && Int(section.fileOffset) + Int(section.size) <= data.count {+ let start = Int(section.fileOffset)+ let end = start + Int(section.size)+ if let match = range(of: needle, in: data, start: start, end: end) {+ faultVMA = section.address + UInt64(match - start)+ break+ }+ }+ guard let faultVMA else { return nil }+ let references = adrpAddReferences(+ to: 0,+ formingAnyOf: [faultVMA],+ in: data,+ textStart: walkerStart,+ textEnd: walkerEnd,+ )+ guard let reference = references.first else { return nil }++ // The fault logger: the first call after the string reference,+ // following any unconditional branch its argument setup ends with.+ var cursor = reference.add + 4+ var steps = 0+ var faultLogger: Int?+ while cursor + 4 <= walkerEnd, steps < 32 {+ defer {+ cursor += 4+ steps += 1+ }+ guard let insn = disasm.disassembleOne(in: data, at: cursor) else { return nil }+ if insn.isCall {+ faultLogger = cursor+ break+ }+ if insn.isJump, !insn.isCall, insn.detail?.conditionCode == nil,+ let target = branchTarget(insn, at: cursor), target >= walkerStart, target < walkerEnd {+ cursor = Int(target) - 4 // the defer moves past it+ continue+ }+ }+ guard let logger = faultLogger else { return nil }++ // The back-to-back call run the logger opens; its last call, followed+ // by anything but a call, is the terminate.+ var call = logger+ var site: Int?+ while call + 8 <= walkerEnd {+ let nextOffset = call + 4+ guard let next = disasm.disassembleOne(in: data, at: nextOffset) else { break }+ if next.isCall {+ site = nextOffset+ call = nextOffset+ continue+ }+ break+ }+ // Already patched: the run now ends one call early, and what follows+ // its last call is our branch to the epilogue. Recognise it rather+ // than eating the release on every re-run.+ if let site,+ let after = disasm.disassembleOne(in: data, at: site + 4),+ after.isJump, !after.isCall,+ let word = wordAtCache(data: after.bytes, offset: 0),+ let target = ARM64Encoder.decodeBranchTarget(insn: word, pc: UInt64(site + 4)),+ target == epilogueVMA {+ return nil+ }+ return site+ }++ private static func branchTarget(_ insn: ARM64Instruction, at offset: Int) -> UInt64? {+ guard let word = wordAtCache(data: insn.bytes, offset: 0) else { return nil }+ return ARM64Encoder.decodeBranchTarget(insn: word, pc: UInt64(offset))+ }++ private static func wordAtCache(data bytes: [UInt8], offset: Int) -> UInt32? {+ guard bytes.count >= 4 else { return nil }+ 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? {+ var offset = min(below, floor + ((below - floor) & ~3))+ while offset >= floor {+ if let insn = disasm.disassembleOne(in: data, at: offset), insn.mnemonic == "pacibsp" {+ return offset+ }+ offset -= 4+ }+ return nil+ }++ /// The nearest function prologue at or after `atOrAfter`.+ private 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" {+ return offset+ }+ offset += 4+ }+ return nil+ }++ /// Whether the window after an allocation call holds the whole throw+ /// machinery: a message load into x1, a constructor call, and the block's+ /// terminating branch.+ private static func isThrowBlock(+ in data: Data,+ disasm: ARM64Disassembler,+ from offset: Int,+ to end: Int,+ ) -> Bool {+ var cursor = offset+ var sawMessageLoad = false+ var sawConstructorCall = false+ var scanned = 0+ while cursor + 4 <= end, scanned < 16 {+ defer {+ cursor += 4+ scanned += 1+ }+ guard let insn = disasm.disassembleOne(in: data, at: cursor) else { return false }+ if insn.mnemonic == "adrp",+ let operands = insn.detail?.operands, operands.count >= 2,+ operands[0].reg == ARM64Register.x(1) {+ if let low = disasm.disassembleOne(in: data, at: cursor + 4), low.mnemonic == "add",+ let lowOps = low.detail?.operands, lowOps.count >= 3,+ lowOps[0].reg == ARM64Register.x(1), lowOps[1].reg == ARM64Register.x(1) {+ sawMessageLoad = true+ }+ }+ if insn.isCall, sawMessageLoad {+ sawConstructorCall = true+ continue+ }+ // The block ends at an unconditional branch (to a resume path or+ // a tail-called throw) or at the `brk` the compiler plants after+ // a call it knows never returns.+ if insn.mnemonic == "brk"+ || (insn.isJump, !insn.isCall, insn.detail?.conditionCode == nil) == (true, true, true) {+ return sawMessageLoad && sawConstructorCall+ }+ }+ return false+ }++ /// A cstring that *contains* the message — the diagnostic log's format+ /// string — with an adrp+add reference within `window` bytes above the+ /// throw. The exception and its log always come as this pair, so a+ /// message string whose only reference is not corroborated by a log+ /// reference nearby is not this site.+ private static func nearbyLogReference(+ in data: Data,+ sections: [String: MachOSectionInfo],+ textStart: Int,+ textEnd: Int,+ before offset: Int,+ window: Int = 0x100,+ ) -> (adrp: Int, add: Int)? {+ let messageBytes = Array(message.utf8)+ let formats: [UInt64] = sections.values+ .filter { $0.fileOffset > 0 && Int($0.fileOffset) + Int($0.size) <= data.count }+ .compactMap { section in+ let start = Int(section.fileOffset)+ let end = start + Int(section.size)+ guard let match = range(of: messageBytes, in: data, start: start, end: end) else { return nil }+ let stringStart = cStringStart(in: data, containing: match, notBefore: start)+ let stringEnd = cStringEnd(in: data, from: stringStart, notAfter: end)+ guard stringEnd - stringStart > messageBytes.count + 8 else { return nil }+ return section.address + UInt64(stringStart - start)+ }+ guard !formats.isEmpty else { return nil }+ return adrpAddReferences(+ to: 0,+ formingAnyOf: Set(formats),+ in: data,+ textStart: max(textStart, offset - window),+ textEnd: offset,+ ).first+ }++ /// The `No default VAD present` C string, in a real string section.+ private static func locateMessage(in data: Data, sections: [String: MachOSectionInfo]) throws -> UInt64 {+ let needle = Array((message + "\0").utf8)+ // cstring sections first, then any other section that still holds+ // file bytes; the signature and symbol tables are not sections.+ let searchable = sections.values+ .filter { $0.fileOffset > 0 && Int($0.fileOffset) + Int($0.size) <= data.count }+ .sorted { lhs, rhs in+ let l = lhs.sectionName == "__cstring"+ let r = rhs.sectionName == "__cstring"+ if l != r { return l }+ return lhs.fileOffset < rhs.fileOffset+ }+ for section in searchable {+ let start = Int(section.fileOffset)+ let end = start + Int(section.size)+ guard end - start >= needle.count else { continue }+ guard let match = range(of: needle, in: data, start: start, end: end) else { continue }+ return section.address + UInt64(match - start)+ }+ throw PatcherError.patchSiteNotFound(+ "\(component): the string \"\(message)\" is nowhere in the binary's sections",+ )+ }++ /// Every `adrp Xn, page ; add Xn, Xn, #low` pair in `__text` whose sum is+ /// `target`, in file-offset terms.+ private static func adrpAddReferences(+ to target: UInt64,+ in data: Data,+ textStart: Int,+ textEnd: Int,+ ) -> [(adrp: Int, add: Int)] {+ adrpAddReferences(to: 0, formingAnyOf: [target], in: data, textStart: textStart, textEnd: textEnd)+ }++ /// The same pairs, matching any target in a set.+ private static func adrpAddReferences(+ to placeholder: UInt64,+ formingAnyOf targets: Set<UInt64>,+ in data: Data,+ textStart: Int,+ textEnd: Int,+ ) -> [(adrp: Int, add: Int)] {+ let disasm = ARM64Disassembler()+ var references: [(Int, Int)] = []+ var offset = textStart+ while offset + 8 <= textEnd {+ defer { offset += 4 }+ guard let adrp = disasm.disassembleOne(in: data, at: offset), adrp.mnemonic == "adrp",+ let add = disasm.disassembleOne(in: data, at: offset + 4), add.mnemonic == "add",+ let page = adrp.detail?.operands, page.count >= 2,+ let low = add.detail?.operands, low.count >= 3,+ page[0].reg == low[1].reg,+ page[1].type == .immediate, low[2].type == .immediate,+ targets.contains(UInt64(page[1].imm + low[2].imm))+ else { continue }+ references.append((offset, offset + 4))+ }+ return references+ }++ /// The first unconditional, non-call branch after `offset` — the throw+ /// block's terminator, whether it jumps to a resume path or tail-calls+ /// the throw itself.+ private static func firstUnconditionalBranch(+ in data: Data,+ disasm: ARM64Disassembler,+ after offset: Int,+ textEnd: Int,+ ) -> Int? {+ var cursor = offset+ var scanned = 0+ while cursor + 4 <= textEnd, scanned < 16 {+ defer {+ cursor += 4+ scanned += 1+ }+ guard let insn = disasm.disassembleOne(in: data, at: cursor) else { return nil }+ if insn.isCall { continue }+ if insn.mnemonic == "brk" || (insn.isJump && insn.detail?.conditionCode == nil) {+ return cursor+ }+ }+ return nil+ }++ /// `mov w0, #<size>` — the instruction that sizes a std::exception.+ static func isExceptionSizeMove(_ insn: ARM64Instruction?) -> Bool {+ guard let insn else { return false }+ guard ["mov", "movz"].contains(insn.mnemonic),+ let operands = insn.detail?.operands, operands.count == 2+ else { return false }+ return operands[0].type == .register+ && operands[0].reg == ARM64Register.w(0)+ && operands[1].type == .immediate+ && (0 ... 0x100).contains(operands[1].imm)+ }++ /// 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(+ in data: Data,+ disasm: ARM64Disassembler,+ after offset: Int,+ textEnd: Int,+ ) throws -> Int {+ // The first `retab` after the throw ends the epilogue.+ var retabOffset: 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+ break+ }+ }+ guard let retab = retabOffset else {+ throw PatcherError.patchSiteNotFound(+ "\(component): no `retab` after the throw at 0x\(hex(UInt64(offset)))",+ )+ }+ return try epilogueEntry(in: data, disasm: disasm, retab: retab)+ }++ /// 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(+ in data: Data,+ disasm: ARM64Disassembler,+ retab: Int,+ ) throws -> Int {+ func instruction(_ at: Int) -> ARM64Instruction? {+ guard at >= 0 else { return nil }+ return disasm.disassembleOne(in: data, at: at)+ }++ // `add sp, sp, #imm` directly before the return, then the pops.+ guard let addSP = instruction(retab - 4), addSP.mnemonic == "add",+ let addOps = addSP.detail?.operands, addOps.count >= 2,+ addOps[0].type == .register, addOps[1].type == .register,+ addOps[0].reg == addOps[1].reg+ else {+ throw PatcherError.invalidFormat(+ "\(component): no `add sp` directly before the epilogue's `retab`",+ )+ }++ // The pops, innermost first, until the frame pair. `index` lands one+ // instruction below the first pop.+ var index = retab - 8+ var sawFramePair = false+ while let insn = instruction(index), insn.mnemonic == "ldp",+ let operands = insn.detail?.operands, operands.count >= 2 {+ if operands[0].reg == ARM64Register.x(29), operands[1].reg == ARM64Register.x(30) {+ sawFramePair = true+ }+ index -= 4+ }+ guard sawFramePair else {+ throw PatcherError.invalidFormat(+ "\(component): the epilogue's pops do not restore the frame pair",+ )+ }+ let firstPop = index + 4++ // A stack-guarded function loads the canary below the first pop:+ // `ldur` off the frame pointer, its page, two loads, a compare and+ // the fail branch. When that chain is there the entry is the load,+ // so the restored canary is still checked; when it is not (a build+ // without the protector) the entry is the first pop itself.+ if let branch = instruction(index), branch.mnemonic == "b.ne",+ let cmp = instruction(index - 4), cmp.mnemonic == "cmp",+ let load2 = instruction(index - 8), load2.mnemonic == "ldr",+ let load1 = instruction(index - 12), load1.mnemonic == "ldr",+ let page = instruction(index - 16), page.mnemonic == "adrp",+ let canary = instruction(index - 20), canary.mnemonic == "ldur",+ let canaryOps = canary.detail?.operands, canaryOps.count >= 2,+ canaryOps[1].type == .memory,+ canaryOps[1].mem.base == ARM64Register.x(29) {+ return index - 20+ }+ return firstPop+ }++ // MARK: - Bytes++ /// The first byte of the null-terminated string containing `offset`.+ private static func cStringStart(in data: Data, containing offset: Int, notBefore start: Int) -> Int {+ var begin = offset+ while begin > start, data[begin - 1] != 0 {+ begin -= 1+ }+ return begin+ }++ /// One past the NUL ending the string at `offset`.+ private static func cStringEnd(in data: Data, from offset: Int, notAfter end: Int) -> Int {+ var terminator = offset+ while terminator < end, data[terminator] != 0 {+ terminator += 1+ }+ return min(terminator + 1, end)+ }++ private static func range(of needle: [UInt8], in data: Data, start: Int, end: Int) -> Int? {+ guard end - start >= needle.count else { return nil }+ for offset in start ... (end - needle.count) {+ var matched = true+ for (index, byte) in needle.enumerated() where data[offset + index] != byte {+ matched = false+ break+ }+ if matched { return offset }+ }+ return nil+ }+}++private func hex(_ value: UInt64) -> String {+ String(format: "%llx", value)+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swiftindex a784d33b..e6fe6722 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift@@ -51,6 +51,7 @@ extension DeviceTreePatcher {static let iPadProductPatch = "devicetree-cfw-ipad_product"static let iPadButtonsPatch = "devicetree-cfw-ipad_buttons"static let iPadIdentityPatch = "devicetree-cfw-ipad_identity"+ static let iPadAudioPatch = "devicetree-cfw-ipad_audio"// MARK: - What Is Copied@@ -198,6 +199,95 @@ extension DeviceTreePatcher {throw PatcherError.patchSiteNotFound("DeviceTree: the board's tree has no \(name) node")}+ // MARK: - Audio++ /// What `presentBoardAudio` changed: the audio node's serialized bytes+ /// before and after, empty when there was no node.+ struct BoardAudioChange {+ let before: Data+ let after: Data+ }++ /// Give `root`'s `/product/audio` the properties of the board's.+ ///+ /// The tree's audio node, when there is one, came from+ /// `devicetree-cfw-product_audio_node`, which copies the D47 iPhone's. Its+ /// `acoustic-id` (8018) names `/Library/Audio/Tunings/AID8018`, which an iPad+ /// image does not ship; VirtualAudio then builds no microphone sub-ports, and+ /// on an iPad, whose board answers yes to stereo and webcam recording, it+ /// throws `PRECONDITION FAILURE` in `RoutingSettings_J98` and never+ /// initializes, so the guest has no audio route at all. The board's own node+ /// names the tunings its image carries (AID2029 on J820).+ ///+ /// Every property is copied as the board has it, placeholders included, except+ /// `AAPL,phandle`, which is the board tree's and could collide in this one; a+ /// property the board's node lacks is removed. The node is added under+ /// `/product` when the tree has none. Returns nil when the board has no audio+ /// node or the tree already matches it.+ static func presentBoardAudio(in root: DTNode, from source: DTNode) -> BoardAudioChange? {+ func named(_ node: DTNode, _ name: String) -> DTNode? {+ node.children.first { child in+ child.properties.contains { $0.name == "name" && $0.value.prefix(while: { $0 != 0 }) == Data(name.utf8) }+ }+ }+ guard+ let sourceProduct = named(source, "product"),+ let sourceAudio = named(sourceProduct, "audio"),+ let product = named(root, "product")+ else { return nil }++ let copied = sourceAudio.properties.filter { $0.name != "AAPL,phandle" }+ func describe(_ properties: [DTProperty]) -> [String: (UInt16, Data)] {+ Dictionary(properties.map { ($0.name, ($0.flags, $0.value)) }, uniquingKeysWith: { first, _ in first })+ }++ let existing = named(product, "audio")+ if let existing {+ let current = existing.properties.filter { $0.name != "AAPL,phandle" }+ let lhs = describe(current)+ let rhs = describe(copied)+ if lhs.count == rhs.count, lhs.allSatisfy({ name, entry in+ rhs[name].map { $0.0 == entry.0 && $0.1 == entry.1 } ?? false+ }) {+ return nil+ }+ }++ let before = existing.map(serialize) ?? Data()+ let node = existing ?? DTNode()+ let phandle = node.properties.filter { $0.name == "AAPL,phandle" }+ node.properties = copied.map {+ DTProperty(name: $0.name, flags: $0.flags, value: $0.value, valueOffset: 0)+ } + phandle+ if existing == nil {+ product.children.append(node)+ }+ return BoardAudioChange(before: before, after: serialize(node))+ }++ /// The flat encoding of one node and its children, for the patch record.+ private static func serialize(_ node: DTNode) -> Data {+ var out = Data()+ func append(_ value: UInt32) {+ withUnsafeBytes(of: value.littleEndian) { out.append(contentsOf: $0) }+ }+ append(UInt32(node.properties.count))+ append(UInt32(node.children.count))+ for property in node.properties {+ var name = Data(property.name.utf8.prefix(31))+ name.append(contentsOf: [UInt8](repeating: 0, count: 32 - name.count))+ out.append(name)+ withUnsafeBytes(of: UInt16(property.length).littleEndian) { out.append(contentsOf: $0) }+ withUnsafeBytes(of: property.flags.littleEndian) { out.append(contentsOf: $0) }+ out.append(property.value)+ out.append(contentsOf: [UInt8](repeating: 0, count: (4 - property.length % 4) % 4))+ }+ for child in node.children {+ out.append(serialize(child))+ }+ return out+ }+// MARK: - Application/// Applies `guestEdits(from:)` to the parsed tree and records each change.@@ -208,6 +298,20 @@ extension DeviceTreePatcher {)}let source = try parsePayload(sourceTree)+ if gateAllows(Self.iPadAudioPatch), let change = Self.presentBoardAudio(in: root, from: source) {+ patches.append(PatchRecord(+ patchID: Self.iPadAudioPatch,+ component: component,+ fileOffset: 0,+ virtualAddress: nil,+ originalBytes: change.before,+ patchedBytes: change.after,+ description: "Set /device-tree/product/audio as on \(device.productType)",+ ))+ if verbose {+ print(" =node : /product/audio as on \(device.productType) (\(change.after.count)B) [\(Self.iPadAudioPatch)]")+ }+ }for edit in try Self.guestEdits(from: source) {guard gateAllows(edit.patchID) else { continue }let node = try resolveNode(root, path: edit.nodePath)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swiftindex 057d85e2..91b4aef8 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift@@ -191,6 +191,11 @@ public enum FirmwareDeviceTreePatchSet {"iPad identity","Reports the iPad's product type and board, so the guest runs as an iPad.",),+ property(+ "devicetree-cfw-ipad_audio",+ "iPad audio configuration",+ "Takes the audio node from the iPad's tree, so its acoustic ID names tunings the iPad image ships.",+ ),],provides: ["vphone.devicetree"],)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex a036fd8c..79149af6 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -178,6 +178,92 @@ public enum FirmwareGuestSystemPatchSet {target: .guestFile(path: "/Library/LaunchDaemons"),bootEssential: true,),+ // MARK: Audio++ VPhonePatchDeclaration(+ identifier: virtioSoundDriver,+ title: "Virtual sound driver",+ summary: """+ Installs the CoreAudio HAL plugin that plays the guest's audio through the VM's \+ virtio sound device. iOS ships the kernel driver but not this half, so without \+ it nothing reaches the Mac's speakers.+ """,+ target: .guestFile(path: "/System/Library/Audio/Plug-Ins/HAL/VPhoneVirtIOSound.driver"),+ ),+ VPhonePatchDeclaration(+ identifier: virtualAudioSpeakerRouteThrows,+ title: "VirtualAudio speaker-route throws",+ summary: """+ Turns VirtualAudio's \"No default VAD present\" exception into a quiet return. \+ Applying a speaker route with no default VAD throws through an AudioServerPlugIn \+ callback, which cannot propagate it: audiomxd aborts, and the saved route state \+ replays the same throw into every launch. The speaker route the virtio plugin \+ publishes is what makes the walk reach that throw, so the two patches go together.+ """,+ target: .guestExecutable(path: "/Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio"),+ ),+ VPhonePatchDeclaration(+ identifier: virtualAudioMuteSetThrow,+ title: "VirtualAudio mute-set throw",+ summary: """+ Turns the CAException VirtualAudio throws when the HAL server refuses its \+ device-level mute set into a quiet return. iOS's HAL never forwards that \+ selector to a plugin device, and RoutingManager catches the throw by \+ abandoning the route — the aggregate is left on Null_Device and the guest \+ is silent. With the throw quieted, the route survives on the virtio device.+ """,+ target: .guestExecutable(path: "/Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio"),+ ),+ VPhonePatchDeclaration(+ identifier: virtualAudioSpeakerProtectionGate,+ title: "VirtualAudio speaker-protection gate",+ summary: """+ Stops the ringtone route handler from declining its own finished route for lack \+ of HAL Speaker Protection — a capability only a physical codec reports, whose \+ query never leaves VirtualAudio. The decline leaves the vdef playing into \+ Null_Device, silent with the volume dead; with the gate opened, the route keeps \+ the virtio device it already built.+ """,+ target: .guestExecutable(path: "/Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio"),+ ),+ VPhonePatchDeclaration(+ identifier: virtualAudioVolumeModePrecondition,+ title: "VirtualAudio volume-mode precondition",+ summary: """+ One step after the speaker-protection gate, the same handler declines the \+ finished route because its software-volume mode is not the kHardwareOnlyReadOnly \+ the routing database demands — a mismatch every virtio-plugin device carries, \+ since the mode a VM's device reports is SoftwareHardwareMix. The decline throws \+ past the route's own teardown, leaving the session on Null_Device: silent, \+ volume dead. With the precondition opened, the route keeps the virtio aggregate \+ it already built.+ """,+ target: .guestExecutable(path: "/Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio"),+ ),+ VPhonePatchDeclaration(+ identifier: virtualAudioGraphConfigurations,+ title: "VirtualAudio speaker graph chains",+ summary: """+ Moves every speaker_* entry in the tuning set's graph_configurations.plist from the \+ `clhs` HAL SpeakerProtection chain to the `dflt` generic graph chain the mic \+ configurations use. The HAL chain's construction looks a physical "Speaker" device \+ up in the device registry and throws when a VM has none, which is what still kills \+ every speaker route once the route walk itself survives.+ """,+ target: .guestFile(path: "/Library/Audio/Tunings"),+ ),+ VPhonePatchDeclaration(+ identifier: prebootBoardAudio,+ title: "iPad audio configuration",+ summary: """+ Gives an iPad guest's restored Preboot device tree the iPad's own audio node, as \+ fw patch now does. Earlier trees kept the iPhone's, whose acoustic ID names tunings \+ an iPad image does not ship, so iOS's audio routing failed to start. Needs the \+ iPad's device tree in the VM's FirmwareOriginals.+ """,+ target: .prebootDeviceTree,+ ),+VPhonePatchDeclaration(identifier: "system-systemversion-cfw-build_version",title: "Reported build version",@@ -193,6 +279,38 @@ public enum FirmwareGuestSystemPatchSet {provides: ["vphone.guest.system"],)+ /// The virtio sound HAL plugin, installed by `cfw install` and by the+ /// environment update.+ public static let virtioSoundDriver = "system-virtiosound-cfw-hal_plugin"++ /// The no-default-VAD throw VirtualAudio must survive when the virtio+ /// plugin publishes the guest's speaker route.+ public static let virtualAudioSpeakerRouteThrows = "system-virtualaudio-cfw-speaker_route_throws"++ /// The mute-set CAException that makes VirtualAudio abandon the speaker+ /// route when the HAL server refuses the device-level unmute.+ public static let virtualAudioMuteSetThrow = "system-virtualaudio-cfw-mute_set_throw"++ /// The branch that declines a finished route for lack of HAL Speaker+ /// Protection, opened so the ringtone route keeps the virtio device it+ /// already built instead of falling back to Null_Device.+ public static let virtualAudioSpeakerProtectionGate = "system-virtualaudio-cfw-speaker_protection_gate"++ /// The precondition that declines a finished route whose software-volume+ /// mode is not the kHardwareOnlyReadOnly the routing database demands,+ /// opened one step after the speaker-protection gate so the route keeps+ /// the virtio aggregate it already built.+ public static let virtualAudioVolumeModePrecondition = "system-virtualaudio-cfw-volume_mode_precondition"++ /// 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.+ public static let virtualAudioGraphConfigurations = "system-virtualaudio-cfw-speaker_graph_chains"++ /// The iPad audio node repair in the restored Preboot device tree, for an+ /// iPad VM patched before `fw patch` copied the board's node.+ public static let prebootBoardAudio = "preboot-cfw-devicetree_board_audio"+/// The preset parameter `system-systemversion-cfw-build_version` reads.public static let buildVersionParameter = "BuildVersion"}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swiftindex 10888fd4..32c2e738 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift@@ -276,7 +276,10 @@ extension FirmwarePipeline {includeIdentityPatches: dtIncludeIdentity,device: guestDevice,role: .installed,- sourceTree: try self.loader.load(from: boardTreeURL),+ // Read through the originals stash, which keeps a copy: the+ // restore tree goes once the VM boots, and `cfw install` and+ // the environment update take the board's audio node from it.+ sourceTree: try self.loader.load(from: self.pristineInput(for: boardTreeURL).url),)p.gate = gatereturn pdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swiftnew file mode 100644index 00000000..22ecd346--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swift@@ -0,0 +1,153 @@+// CustomFirmwareBoardAudioTests.swift — an iPad guest takes the board's audio node.+//+// `withBoardAudio` (the Preboot repair) and `DeviceTreePatcher.presentBoardAudio`+// (what `fw patch` runs for an iPad's installed tree) replace `/product/audio`+// with the board tree's. The trees here are built in the flat format the+// restored tree uses, so the parse, the edit and the serialization all run.++@testable import FirmwarePatcher+import Foundation+import Testing++@Suite("iPad audio node from the board tree")+struct CustomFirmwareBoardAudioTests {+ // MARK: - A flat device tree++ private struct Node {+ var properties: [(name: String, flags: UInt16, value: Data)]+ var children: [Node] = []+ }++ private static func node(+ _ name: String,+ _ properties: [(String, Data)] = [],+ flags: [String: UInt16] = [:],+ children: [Node] = [],+ ) -> Node {+ Node(+ properties: [("name", 0, Data((name + "\0").utf8))]+ + properties.map { ($0.0, flags[$0.0] ?? 0, $0.1) },+ children: children,+ )+ }++ private static func uint32(_ value: UInt32) -> Data {+ withUnsafeBytes(of: value.littleEndian) { Data($0) }+ }++ private static func serialize(_ node: Node) -> Data {+ var out = uint32(UInt32(node.properties.count)) + uint32(UInt32(node.children.count))+ for (name, flags, value) in node.properties {+ var field = Data(name.utf8)+ field.append(contentsOf: [UInt8](repeating: 0, count: 32 - field.count))+ out.append(field)+ out.append(contentsOf: withUnsafeBytes(of: UInt16(value.count).littleEndian) { Array($0) })+ out.append(contentsOf: withUnsafeBytes(of: flags.littleEndian) { Array($0) })+ out.append(value)+ out.append(contentsOf: [UInt8](repeating: 0, count: (4 - value.count % 4) % 4))+ }+ for child in node.children {+ out.append(serialize(child))+ }+ return out+ }++ private static func tree(audio: Node?) -> Data {+ let product = node(+ "product",+ [("product-name", Data("iPad\0".utf8))],+ children: audio.map { [$0] } ?? [],+ )+ return serialize(node("device-tree", [("model", Data("iPad17,3\0\0".utf8))], children: [+ node("chosen"),+ product,+ ]))+ }++ /// The D47 node `devicetree-cfw-product_audio_node` adds.+ private static let iPhoneAudio = node("audio", [+ ("acoustic-id", uint32(8018)),+ ("stereo-sound-recording", uint32(1)),+ ("supports-spatial-audio-capture", uint32(1)),+ ])++ /// J820's, trimmed: its own acoustic ID, a placeholder, and the board's phandle.+ private static let boardAudio = node("audio", [+ ("AAPL,phandle", uint32(395)),+ ("acoustic-id", uint32(2029)),+ ("speaker-thiele-small", Data("syscfg/SpTS\0".utf8)),+ ("stereo-sound-recording", uint32(1)),+ ], flags: ["speaker-thiele-small": 0x8000])++ /// What the guest's node should become: the board's, without its phandle.+ private static let presentedAudio = node("audio", [+ ("acoustic-id", uint32(2029)),+ ("speaker-thiele-small", Data("syscfg/SpTS\0".utf8)),+ ("stereo-sound-recording", uint32(1)),+ ], flags: ["speaker-thiele-small": 0x8000])++ // MARK: - Tests++ @Test func `replaces the iPhone node with the board's`() throws {+ let original = Self.tree(audio: Self.iPhoneAudio)+ let board = Self.tree(audio: Self.boardAudio)+ let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withBoardAudio(original, board: board)+ #expect(changes.map(\.property) == ["product/audio"])+ #expect(changes.first?.before == "acoustic-id 8018")+ #expect(changes.first?.after.hasPrefix("acoustic-id 2029") == true)+ #expect(patched.count == original.count + delta)+ #expect(patched == Self.tree(audio: Self.presentedAudio))+ }++ @Test func `keeps the guest's own phandle`() throws {+ var iPhone = Self.iPhoneAudio+ iPhone.properties.append(("AAPL,phandle", 0, Self.uint32(77)))+ let (patched, _, _) = try CustomFirmwarePostRestoreDeviceTree.withBoardAudio(+ Self.tree(audio: iPhone),+ board: Self.tree(audio: Self.boardAudio),+ )+ var expected = Self.presentedAudio+ expected.properties.append(("AAPL,phandle", 0, Self.uint32(77)))+ #expect(patched == Self.tree(audio: expected))+ }++ @Test func `adds the node when the guest has none`() throws {+ let original = Self.tree(audio: nil)+ let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withBoardAudio(+ original,+ board: Self.tree(audio: Self.boardAudio),+ )+ #expect(changes.first?.before == "acoustic-id none")+ #expect(patched.count == original.count + delta)+ #expect(patched == Self.tree(audio: Self.presentedAudio))+ }++ @Test func `a presented tree is left alone`() throws {+ let board = Self.tree(audio: Self.boardAudio)+ let (once, _, _) = try CustomFirmwarePostRestoreDeviceTree.withBoardAudio(Self.tree(audio: Self.iPhoneAudio), board: board)+ let (twice, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withBoardAudio(once, board: board)+ #expect(changes.isEmpty)+ #expect(delta == 0)+ #expect(twice == once)+ }++ @Test func `a board without an audio node changes nothing`() throws {+ let original = Self.tree(audio: Self.iPhoneAudio)+ let (patched, changes, _) = try CustomFirmwarePostRestoreDeviceTree.withBoardAudio(+ original,+ board: Self.tree(audio: nil),+ )+ #expect(changes.isEmpty)+ #expect(patched == original)+ }++ @Test func `a truncated tree is refused`() {+ let original = Self.tree(audio: Self.iPhoneAudio)+ #expect(throws: (any Error).self) {+ try CustomFirmwarePostRestoreDeviceTree.withBoardAudio(+ original.prefix(original.count - 4),+ board: Self.tree(audio: Self.boardAudio),+ )+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioGraphConfigurationsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioGraphConfigurationsTests.swiftnew file mode 100644index 00000000..ee445edb--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioGraphConfigurationsTests.swift@@ -0,0 +1,157 @@+// CustomFirmwareVirtualAudioGraphConfigurationsTests.swift — the speaker-chain+// flip in graph_configurations.plist.+//+// The plist's real shape is fixed by the iPadOS image (Configurations →+// speaker_* → chainType "clhs", mic configurations on "dflt"), so the+// synthetic fixtures below mirror it name for name. The patcher's contract+// is what needs holding: every speaker_* flips, nothing else moves, the+// file's format survives, a re-run writes nothing, and anything unexpected+// refuses rather than half-patches.++import Foundation+import Testing+@testable import FirmwarePatcher+import VPhonePatchKit++@Suite("CustomFirmwareVirtualAudioGraphConfigurations")+struct CustomFirmwareVirtualAudioGraphConfigurationsTests {+ /// The shape the tuning set ships: CommonData, the speaker configurations+ /// on `clhs`, mic configurations on `dflt` — names as the real plist+ /// carries them, so the prefix match is exercised against the exact keys+ /// it will meet on a guest.+ static func tuningSet() -> [String: Any] {+ func configuration(_ chainType: String, graph: String) -> [String: Any] {+ ["chainType": chainType, "graph": graph, "austrip": graph,+ "busChannelCounts": [[2, 8]], "properties": [["ID": "iods"]]]+ }+ return [+ "CommonData": [+ "presetPath": "/Library/Audio/Tunings/AID2029/AU",+ "tuningPath": "/Library/Audio/Tunings/AID2029/VAD",+ "tuningFilePrefix": "",+ ],+ "Configurations": [+ "speaker_ringtone": configuration("clhs", graph: "speaker_general"),+ "speaker_general": configuration("clhs", graph: "speaker_general"),+ "speaker_raw": configuration("clhs", graph: "speaker_raw"),+ "beamformed_mic_general": configuration("dflt", graph: "beam_mic_general"),+ "stereo_recording": configuration("dflt", graph: "stereo_recording_no_tap"),+ ],+ ]+ }++ private func writeTemporary(_ plist: [String: Any], format: PropertyListSerialization.PropertyListFormat = .binary) throws -> URL {+ let directory = try CustomFirmwarePatchFixtures.makeTemporaryDirectory()+ let url = directory.appending(path: "graph_configurations.plist")+ try PropertyListSerialization.data(fromPropertyList: plist, format: format, options: 0).write(to: url)+ return url+ }++ @Test("flips every speaker chain and leaves the rest of the file alone")+ func flipsSpeakerChains() throws {+ let url = try writeTemporary(Self.tuningSet())+ let outcome = try CustomFirmwareVirtualAudioGraphConfigurations.patch(at: url, verbose: false)+ #expect(outcome == .rewritten(changed: ["speaker_general", "speaker_raw", "speaker_ringtone"]))++ let patched = try PlistComparison.load(url) as? [String: Any]+ let configurations = patched?["Configurations"] as? [String: Any]+ #expect((configurations?["speaker_ringtone"] as? [String: Any])?["chainType"] as? String == "dflt")+ #expect((configurations?["speaker_raw"] as? [String: Any])?["chainType"] as? String == "dflt")+ // A mic configuration already on dflt, and a speaker graph, are untouched.+ #expect((configurations?["beamformed_mic_general"] as? [String: Any])?["chainType"] as? String == "dflt")+ #expect((configurations?["speaker_ringtone"] as? [String: Any])?["graph"] as? String == "speaker_general")+ // CommonData is carried as it went in.+ #expect((patched?["CommonData"] as? [String: Any])?.count == 3)++ // The only difference from the input is the flipped chainTypes.+ var expected = Self.tuningSet()+ var expectedConfigurations = expected["Configurations"] as! [String: Any]+ for name in ["speaker_ringtone", "speaker_general", "speaker_raw"] {+ var entry = expectedConfigurations[name] as! [String: Any]+ entry["chainType"] = "dflt"+ expectedConfigurations[name] = entry+ }+ expected["Configurations"] = expectedConfigurations+ let difference = PlistComparison.difference(patched ?? [:], expected)+ #expect(difference == nil, "unexpected differences beyond the flipped chainTypes: \(difference ?? "")")+ }++ @Test("keeps the plist's format — binary in, binary out")+ func preservesFormat() throws {+ for format in [PropertyListSerialization.PropertyListFormat.binary, .xml] {+ let url = try writeTemporary(Self.tuningSet(), format: format)+ try CustomFirmwareVirtualAudioGraphConfigurations.patch(at: url, verbose: false)+ let bytes = try Data(contentsOf: url)+ #expect(CustomFirmwareVirtualAudioGraphConfigurations.detectFormat(bytes) == format)+ }+ }++ @Test("is idempotent and honours dry run")+ func idempotentAndDryRun() throws {+ let url = try writeTemporary(Self.tuningSet())+ let dry = try CustomFirmwareVirtualAudioGraphConfigurations.patch(at: url, dryRun: true, verbose: false)+ #expect(dry == .dryRun(changed: ["speaker_general", "speaker_raw", "speaker_ringtone"]))+ let untouched = try Data(contentsOf: url)++ try CustomFirmwareVirtualAudioGraphConfigurations.patch(at: url, verbose: false)+ let written = try Data(contentsOf: url)+ #expect(written != untouched)++ let again = try CustomFirmwareVirtualAudioGraphConfigurations.patch(at: url, verbose: false)+ #expect(again == .alreadyGraphChains(["speaker_general", "speaker_raw", "speaker_ringtone"]))+ #expect(try Data(contentsOf: url) == written)+ }++ @Test("refuses plists it does not understand, not searched past",+ arguments: [+ "not a plist at all",+ "{\"Configurations\": {\"speaker_ringtone\": {\"chainType\": \"sprt\"}}}",+ ])+ func refusesUnexpectedInput(_ text: String) throws {+ let url = try writeTemporary(["placeholder": true])+ try Data(text.utf8).write(to: url)+ #expect(throws: PatcherError.self) {+ try CustomFirmwareVirtualAudioGraphConfigurations.patch(at: url, verbose: false)+ }+ }++ @Test("refuses a speaker chain on an unknown chainType")+ func refusesUnknownChainType() throws {+ var plist = Self.tuningSet()+ var configurations = plist["Configurations"] as! [String: Any]+ configurations["speaker_siri"] = ["chainType": "sprt", "graph": "speaker_general"]+ plist["Configurations"] = configurations+ let url = try writeTemporary(plist)+ #expect(throws: PatcherError.self) {+ try CustomFirmwareVirtualAudioGraphConfigurations.patch(at: url, verbose: false)+ }+ }++ @Test("refuses a plist with no speaker configurations")+ func refusesNoSpeakerConfigurations() throws {+ let micOnly: [String: Any] = [+ "CommonData": ["tuningPath": "/Library/Audio/Tunings/AID2029/VAD"],+ "Configurations": ["beamformed_mic_general": ["chainType": "dflt", "graph": "beam_mic_general"]],+ ]+ let url = try writeTemporary(micOnly)+ #expect(throws: PatcherError.self) {+ try CustomFirmwareVirtualAudioGraphConfigurations.patch(at: url, verbose: false)+ }+ }++ @Test("refuses a plist without the Configurations dict")+ func refusesMissingConfigurations() throws {+ let url = try writeTemporary(["CommonData": ["tuningPath": "/x"]])+ #expect(throws: PatcherError.self) {+ try CustomFirmwareVirtualAudioGraphConfigurations.patch(at: url, verbose: false)+ }+ }++ @Test("the anchor keys are the ones the tuning set ships")+ func keysAreStable() {+ #expect(CustomFirmwareVirtualAudioGraphConfigurations.speakerChainType == "clhs")+ #expect(CustomFirmwareVirtualAudioGraphConfigurations.graphChainType == "dflt")+ #expect(CustomFirmwareVirtualAudioGraphConfigurations.configurationsKey == "Configurations")+ #expect(CustomFirmwareVirtualAudioGraphConfigurations.chainTypeKey == "chainType")+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swiftnew file mode 100644index 00000000..e84b7d85--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift@@ -0,0 +1,155 @@+// CustomFirmwareVirtualAudioTests.swift — the no-default-VAD throw's anchor.++// The parity bar the other patcher suites hold — same bytes as a frozen+// reference on a pristine binary — needs `ipsws/ref_extract` fixtures this+// machine does not carry, so what is tested here is everything around that:+// the anchor refuses binaries that are not the shape it was told about, and+// the exception-size check is exactly the guard the patcher applies. The+// 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.++import Foundation+import Testing+@testable import FirmwarePatcher+import VPhonePatchKit++@Suite("CustomFirmwareVirtualAudio")+struct CustomFirmwareVirtualAudioTests {+ /// Not a Mach-O at all.+ static let junk = Data(repeating: 0x41, count: 4096)++ @Test("a binary without the message is refused, not searched past",+ arguments: [Self.junk, Data()])+ func refusesBinariesWithoutTheSite(_ input: Data) throws {+ var data = input+ #expect(throws: PatcherError.self) {+ try CustomFirmwareVirtualAudio.patch(+ &data,+ reattest: false,+ dryRun: true,+ log: nil,+ )+ }+ }++ @Test("the message string is the anchor the records name")+ func messageIsStable() {+ #expect(CustomFirmwareVirtualAudio.message == "No default VAD present")+ #expect(CustomFirmwareVirtualAudio.patchID == "system-virtualaudio-cfw-speaker_route_throws")+ }++ @Test("a binary without the mute-set log is refused, not searched past",+ arguments: [Self.junk, Data()])+ func refusesBinariesWithoutTheMuteSetSite(_ input: Data) throws {+ var data = input+ #expect(throws: PatcherError.self) {+ try CustomFirmwareVirtualAudio.patchMuteSet(+ &data,+ reattest: false,+ dryRun: true,+ log: nil,+ )+ }+ }++ @Test("the mute-set anchor strings and record identity are stable")+ func muteSetIdentityIsStable() {+ #expect(CustomFirmwareVirtualAudio.muteSetMessage == "Set mute value of %u on HAL device")+ #expect(CustomFirmwareVirtualAudio.muteSetException == "Unable to set property data.")+ #expect(CustomFirmwareVirtualAudio.muteSetPatchID == "system-virtualaudio-cfw-mute_set_throw")+ }++ @Test("a binary without the decline log is refused, not searched past",+ arguments: [Self.junk, Data()])+ func refusesBinariesWithoutTheSPGateSite(_ input: Data) throws {+ var data = input+ #expect(throws: PatcherError.self) {+ try CustomFirmwareVirtualAudio.patchSpeakerProtectionGate(+ &data,+ reattest: false,+ dryRun: true,+ log: nil,+ )+ }+ }++ @Test("the SP-gate anchor strings and record identity are stable")+ func spGateIdentityIsStable() {+ #expect(CustomFirmwareVirtualAudio.spGateMessage == "HAL Speaker Protection is missing. Failing route")+ #expect(CustomFirmwareVirtualAudio.spGateFile == "RoutingHandler_Playback_GenericConfig1.cpp")+ #expect(CustomFirmwareVirtualAudio.spGatePatchID == "system-virtualaudio-cfw-speaker_protection_gate")+ }++ @Test("a binary without the precondition decline is refused, not searched past",+ arguments: [Self.junk, Data()])+ func refusesBinariesWithoutTheVolumeGateSite(_ input: Data) throws {+ var data = input+ #expect(throws: PatcherError.self) {+ try CustomFirmwareVirtualAudio.patchVolumeModePrecondition(+ &data,+ reattest: false,+ dryRun: true,+ log: nil,+ )+ }+ }++ @Test("the volume-gate anchor strings and record identity are stable")+ func volumeGateIdentityIsStable() {+ #expect(CustomFirmwareVirtualAudio.volumePreconditionFormat == "PRECONDITION FAILURE (std::logic_error)")+ #expect(CustomFirmwareVirtualAudio.volumeModePackingMask == 0x1ffffffff)+ #expect(CustomFirmwareVirtualAudio.volumeGatePatchID == "system-virtualaudio-cfw-volume_mode_precondition")+ }++ /// `tbz w21, #0, 0x136878` at 0x136620 — the real gate branch, read off+ /// the iPadOS 26.6.2 plugin binary this patch was written against (bytes+ /// d5 12 00 36 at that offset).+ @Test("the conditional-branch decoder reads the real gate's target")+ func decodesTheGatesTBZ() {+ #expect(+ CustomFirmwareVirtualAudio.decodeConditionalBranchTarget(+ insn: 0x3600_12D5,+ pc: 0x136620,+ ) == 0x136878,+ )+ }++ /// The 19-bit immediate must sign-extend, or a backward branch decodes+ /// up to 512 KB ahead instead of up to 256 KB back. The word is built+ /// from its fields — `b.eq` with every immediate bit set, i.e. −1 — not+ /// taken as a literal.+ @Test("the 19-bit immediate sign-extends")+ func signExtendsTheImmediate19() {+ let word: UInt32 = 0x5400_0000 | (0x7FFFF << 5) // b.eq, imm19 = −1+ #expect(+ CustomFirmwareVirtualAudio.decodeConditionalBranchTarget(+ insn: word,+ pc: 0x1000,+ ) == 0x0FFC,+ )+ }++ /// `tbz` reaches ±32 KB through a 14-bit immediate at bits 18-5, and a+ /// 64-bit `cbnz` proves the leading sf/b5 bit is not mistaken for part+ /// of the family. Both words are built from their fields.+ @Test("the 14-bit and 64-bit families decode")+ func decodesTheImmediate14And64BitFamilies() {+ // tbz w21, #0, imm14 = −1 (bits 30-25 = 011011, bit 24 = 0)+ let tbz: UInt32 = 0x3600_0000 | (0x3FFF << 5) | 21+ #expect(CustomFirmwareVirtualAudio.decodeConditionalBranchTarget(insn: tbz, pc: 0x1000) == 0x0FFC)+ // cbnz xzr, +0x40 (sf = 1, bit 24 = 1): top byte 1_011010_1+ let cbnz: UInt32 = 0xB500_0000 | (0x10 << 5) | 31+ #expect(CustomFirmwareVirtualAudio.decodeConditionalBranchTarget(insn: cbnz, pc: 0x2000) == 0x2040)+ }++ @Test("the conditional-branch decoder refuses words outside its families")+ func refusesNonBranchWords() {+ #expect(CustomFirmwareVirtualAudio.decodeConditionalBranchTarget(insn: 0xD503_201F, pc: 0) == nil)+ // A `b` — the family `ARM64Encoder.decodeBranchTarget` owns.+ #expect(CustomFirmwareVirtualAudio.decodeConditionalBranchTarget(insn: 0x1400_0002, pc: 0) == nil)+ // A PAUTH BC.cond — bit 24 set, a register operand, not an offset.+ #expect(CustomFirmwareVirtualAudio.decodeConditionalBranchTarget(insn: 0x5500_0FE0, pc: 0) == nil)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 4d61fb62..b0811eda 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -3,6 +3,7 @@ import Darwinimport FirmwarePatcherimport Foundationimport VPhoneCoreKit+import VPhonePatchKitimport VPhoneSign/// Host-side JB system installation. The VM must be off: all writes go to its@@ -28,8 +29,10 @@ struct VPhoneCustomFirmwareInstaller {/// prepared restore tree.case full/// Only the files this bundle ships into the guest — vphoned, its- /// launch daemon, the guest dylibs and the libmisfix defaults — put- /// back where a full install already placed them.+ /// launch daemon, the guest dylibs, the libmisfix defaults and the+ /// virtio sound driver — put back where a full install already placed+ /// them, plus the audio repair that driver needs on an older VM (see+ /// `updateEnvironmentMounted`).////// No patch runs, nothing is injected, no cryptex or GPU work happens/// and no restore tree is needed. That last part is the point: the@@ -120,7 +123,7 @@ struct VPhoneCustomFirmwareInstaller {let bundlePath = try bundleDirectory.path// Which guest patches to apply, as `fw patch` resolved them. Read through// the pinned descriptor so root never follows a link out of the bundle.- let plan = readPatchPlan(in: bundleDirectory)+ let plan = withLateGuestPatches(readPatchPlan(in: bundleDirectory), in: bundleDirectory)let disk = try openDiskImage(in: bundleDirectory, path: bundlePath, owner: callerUID)let diskPath = (bundlePath as NSString).appendingPathComponent("Disk.img")let busy = try VPhoneProcessRunner.runCapturing(@@ -266,16 +269,24 @@ struct VPhoneCustomFirmwareInstaller {plan: plan,)case .environmentOnly:- try updateEnvironmentMounted(system: systemRoot, work: work)+ try updateEnvironmentMounted(system: systemRoot, work: work, plan: plan)}}- // Both of these belong to a full install only. The Preboot patches go- // with the boot chain, and the snapshot has already been renamed on any- // VM an environment update is allowed to run against — this run creates- // no new snapshot to flip.- if mode == .full {- try patchPreboot(volumes: volumes, work: work, plan: plan, guestDevice: guestDevice(of: restore))- }+ // The Preboot identity patches go with the boot chain and belong to a+ // full install only. The board audio repair is the exception: an iPad VM+ // restored before it has no other way to get its audio back, since its+ // restore tree is gone and `fw patch` does not run again.+ try patchPreboot(+ volumes: volumes,+ work: work,+ plan: plan,+ guestDevice: guestDevice(of: restore),+ includeIdentity: mode == .full,+ boardDeviceTree: stageBoardDeviceTree(in: bundleDirectory, work: work),+ )+ // The snapshot rename is a full install's alone: it has already been+ // done on any VM an environment update is allowed to run against, and+ // this run creates no new snapshot to flip._ = try tool("/sbin/umount", [data.path])dataMounted = false_ = try tool("/sbin/umount", [system.path])@@ -324,7 +335,16 @@ struct VPhoneCustomFirmwareInstaller {/// A missing target is left missing. The libraries are not all/// unconditional — a VM whose plan left a patch out never received the/// library that goes with it — and an update is not the place to add one.- private func updateEnvironmentMounted(system: VPhoneConfinedDirectory, work: WorkDirectory) throws {+ ///+ /// The virtio sound driver is the exception, and follows the plan instead:+ /// it came after most VMs were installed, and this is the only route by+ /// which a VM in use can receive it. The board audio repair that goes+ /// with it touches the Preboot device tree, outside this function.+ private func updateEnvironmentMounted(+ system: VPhoneConfinedDirectory,+ work: WorkDirectory,+ plan: VPhoneVirtualMachinePatchPlan?,+ ) throws {// Evidence that a full install ran. `launchd.plist.bak` is written by// the first `installVphoned` and by nothing else, so its absence means// this guest has never been installed and there is nothing to update.@@ -352,6 +372,55 @@ struct VPhoneCustomFirmwareInstaller {// file carries a per-machine UDID choice and is not the bundle's to// overwrite.try installMISFixDefaults(system: system)++ if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtioSoundDriver) ?? true {+ try installVirtioSoundDriver(system: system)+ }+ // Both patches ride one staged copy — `patchMachO` stages from the+ // pristine backup, so two calls would not compose. The restore below+ // fires only when every VirtualAudio patch is off.+ var virtualAudioVerbs: [String] = []+ if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtualAudioSpeakerRouteThrows) ?? true {+ virtualAudioVerbs.append("patch-virtualaudio")+ }+ if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtualAudioMuteSetThrow) ?? true {+ virtualAudioVerbs.append("patch-virtualaudio-mute")+ }+ if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtualAudioSpeakerProtectionGate) ?? true {+ virtualAudioVerbs.append("patch-virtualaudio-sp-gate")+ }+ if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtualAudioVolumeModePrecondition) ?? true {+ virtualAudioVerbs.append("patch-virtualaudio-volume-gate")+ }+ if !virtualAudioVerbs.isEmpty {+ try patchMachO(+ system: system,+ work: work,+ path: "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio",+ verbs: virtualAudioVerbs,+ preserveEntitlements: true,+ )+ try sealGuestBundle(system: system, bundle: "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin")+ print(" [+] VirtualAudio: \(virtualAudioVerbs.joined(separator: ", "))")+ } else if try system.exists("Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio.bak") {+ // The patch is off but a previous install left it applied; stage+ // the backup the same way `patchMachO` does and put the original+ // back, so the gate means what it says.+ let name = "VirtualAudio"+ try work.directory.removeItem(name)+ try system.copyFile(from: "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio.bak", to: name, in: work.directory)+ try system.replaceFile(+ "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio",+ fromFileAt: work.file(name),+ mode: 0o755,+ owner: Self.guestOwner,+ )+ try sealGuestBundle(system: system, bundle: "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin")+ print(" [+] VirtualAudio restored from backup (patch off)")+ }+ if plan?.isEnabled(FirmwareGuestSystemPatchSet.virtualAudioGraphConfigurations) ?? true {+ try patchVirtualAudioGraphConfigurations(system: system, work: work)+ }}/// Host bookkeeping in the caller's folder, written with the caller's@@ -600,7 +669,7 @@ struct VPhoneCustomFirmwareInstaller {system: system,work: work,path: "usr/libexec/seputil",- verb: "patch-seputil",+ verbs: ["patch-seputil"],identifier: "com.apple.seputil",)}@@ -609,7 +678,7 @@ struct VPhoneCustomFirmwareInstaller {system: system,work: work,path: "usr/libexec/diskimagesiod",- verb: "patch-diskimagesiod",+ verbs: ["patch-diskimagesiod"],preserveEntitlements: true,)}@@ -624,7 +693,7 @@ struct VPhoneCustomFirmwareInstaller {system: system,work: work,path: "usr/libexec/launchd_cache_loader",- verb: "patch-launchd-cache-loader",+ verbs: ["patch-launchd-cache-loader"],identifier: "com.apple.launchd_cache_loader",)}@@ -633,7 +702,7 @@ struct VPhoneCustomFirmwareInstaller {system: system,work: work,path: "usr/libexec/mobileactivationd",- verb: "patch-mobileactivationd",+ verbs: ["patch-mobileactivationd"],)}if on("system-watchdogd-exp-hv_vmm_cache") {@@ -645,12 +714,43 @@ struct VPhoneCustomFirmwareInstaller {if on("system-launchdaemons-boot-environment") {try installEnvironment(system: system)}+ if on(FirmwareGuestSystemPatchSet.virtioSoundDriver) {+ try installVirtioSoundDriver(system: system)+ }+ // Both patches ride one staged copy — `patchMachO` stages from the+ // pristine backup, so two calls would not compose.+ var virtualAudioVerbs: [String] = []+ if on(FirmwareGuestSystemPatchSet.virtualAudioSpeakerRouteThrows) {+ virtualAudioVerbs.append("patch-virtualaudio")+ }+ if on(FirmwareGuestSystemPatchSet.virtualAudioMuteSetThrow) {+ virtualAudioVerbs.append("patch-virtualaudio-mute")+ }+ if on(FirmwareGuestSystemPatchSet.virtualAudioSpeakerProtectionGate) {+ virtualAudioVerbs.append("patch-virtualaudio-sp-gate")+ }+ if on(FirmwareGuestSystemPatchSet.virtualAudioVolumeModePrecondition) {+ virtualAudioVerbs.append("patch-virtualaudio-volume-gate")+ }+ if !virtualAudioVerbs.isEmpty {+ try patchMachO(+ system: system,+ work: work,+ path: "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin/VirtualAudio",+ verbs: virtualAudioVerbs,+ preserveEntitlements: true,+ )+ try sealGuestBundle(system: system, bundle: "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin")+ }+ if on(FirmwareGuestSystemPatchSet.virtualAudioGraphConfigurations) {+ try patchVirtualAudioGraphConfigurations(system: system, work: work)+ }if on("system-launchd-boot-jetsam_panic_guard_bypass") {try patchMachO(system: system,work: work,path: "sbin/launchd",- verb: "patch-launchd-jetsam",+ verbs: ["patch-launchd-jetsam"],preserveEntitlements: true,injectedDylibPath: "/vh",)@@ -664,6 +764,54 @@ struct VPhoneCustomFirmwareInstaller {}}+ /// Guest patches declared after most VMs' plans were written. A plan is the+ /// list of what was on when `fw patch` ran, so it reads these as off on any+ /// VM patched before them. They need no firmware change, so they follow the+ /// VM's selection as it resolves now instead.+ private static let lateGuestPatches = [+ FirmwareGuestSystemPatchSet.virtioSoundDriver,+ FirmwareGuestSystemPatchSet.prebootBoardAudio,+ FirmwareGuestSystemPatchSet.virtualAudioSpeakerRouteThrows,+ FirmwareGuestSystemPatchSet.virtualAudioMuteSetThrow,+ FirmwareGuestSystemPatchSet.virtualAudioSpeakerProtectionGate,+ FirmwareGuestSystemPatchSet.virtualAudioVolumeModePrecondition,+ FirmwareGuestSystemPatchSet.virtualAudioGraphConfigurations,+ ]++ /// `plan`, with each late guest patch it leaves out turned on when the+ /// VM's preset and its own block and allow choices select it today. A+ /// preset that cannot be resolved from the bundled sets (one naming an+ /// external set) leaves the plan as it is: root loads no external set.+ private func withLateGuestPatches(+ _ plan: VPhoneVirtualMachinePatchPlan?,+ in bundleDirectory: VPhoneConfinedDirectory,+ ) -> VPhoneVirtualMachinePatchPlan? {+ guard var plan else { return nil }+ let missing = Self.lateGuestPatches.filter { !plan.isEnabled($0) }+ guard !missing.isEmpty else { return plan }+ let selection = (try? bundleDirectory.readData(VPhonePatchPresetStore.selectionFileName))+ .flatMap { try? PropertyListDecoder().decode(VPhoneVirtualMachinePatchSelection.self, from: $0) }+ ?? VPhoneVirtualMachinePatchSelection()+ guard+ let preset = VPhonePatchPresetStore.preset(named: plan.presetIdentifier),+ let resolved = try? VPhonePatchPlan.resolve(+ preset: preset,+ patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion(plan.iOSBaseVersion),+ cloudOS: VPhoneVersion(plan.cloudOSVersion),+ blocked: Set(selection.blockedPatches),+ allowed: Set(selection.allowedPatches),+ )+ else {+ return plan+ }+ for identifier in missing where resolved.enabled.contains(identifier) {+ plan.enabledPatches.append(identifier)+ print("[*] \(identifier): newer than this VM's patch plan, on in preset \(plan.presetIdentifier)")+ }+ return plan+ }+/// The plan `fw patch` wrote into the VM, or nil when it never ran with one.private func readPatchPlan(in bundleDirectory: VPhoneConfinedDirectory) -> VPhoneVirtualMachinePatchPlan? {guard let data = try? bundleDirectory.readData(VPhonePatchPresetStore.planFileName) else {@@ -904,6 +1052,26 @@ struct VPhoneCustomFirmwareInstaller {try installMISFixDefaults(system: system)}+ /// The CoreAudio HAL plugin for the VM's virtio sound device. iOS ships+ /// the kernel driver, AppleVirtIOSound, but no plugin for it, so audiomxd+ /// has nothing to play through. The bundle is replaced whole; its+ /// signature seals the binary and Info.plist together.+ private func installVirtioSoundDriver(system: VPhoneConfinedDirectory) throws {+ let name = "VPhoneVirtIOSound.driver"+ let source = try VPhoneConfinedDirectory(root: VPhoneGuestBinaries.resolve(name).path)+ let target = "System/Library/Audio/Plug-Ins/HAL/\(name)"+ try system.removeItem(target)+ try system.copyTree(from: source, to: target, owner: Self.guestOwner)+ for directory in [target, "\(target)/_CodeSignature"] {+ try system.setMode(directory, 0o755)+ }+ try system.setMode("\(target)/VPhoneVirtIOSound", 0o755)+ for file in ["\(target)/Info.plist", "\(target)/_CodeSignature/CodeResources"] {+ try system.setMode(file, 0o644)+ }+ print(" [+] /\(target)")+ }+/// A symlink at the volume root, so a load command in a binary with little/// header space can name a library in seven bytes or fewer.private func installLibraryAlias(system: VPhoneConfinedDirectory, alias: String, target: String) throws {@@ -981,23 +1149,41 @@ struct VPhoneCustomFirmwareInstaller {return VPhoneGuestDevice.detect(buildManifest: manifest) ?? .default}+ /// `includeIdentity` is false for an environment update, which carries+ /// only the board audio repair. `boardDeviceTree` is the iPad's own device+ /// tree, staged from the VM's `FirmwareOriginals`, or nil for an iPhone+ /// guest or a VM patched before `fw patch` kept it.private func patchPreboot(volumes: [[String: Any]],work: WorkDirectory,plan: VPhoneVirtualMachinePatchPlan?,guestDevice: VPhoneGuestDevice,+ includeIdentity: Bool,+ boardDeviceTree: URL?,) throws {- // Like every guest patch, a VM with no plan still gets it — except on an- // iPad guest, whose installed tree already carries its own identity- // from `fw patch`; the rewrite would turn it back into an iPhone17,3.+ // Like every guest patch, a VM with no plan still gets it — except the+ // identity rewrite on an iPad guest, whose installed tree already+ // carries its own identity from `fw patch`; the rewrite would turn it+ // back into an iPhone17,3.+ func on(_ identifier: String) -> Bool {+ let enabled = plan?.isEnabled(identifier) ?? true+ if let plan, !enabled {+ print(" [·] \(identifier): off in preset \(plan.presetIdentifier)")+ }+ return enabled+ }let identity = FirmwareGuestIdentityPatchSet.prebootDeviceTreeIdentity- let rewriteIdentity = !guestDevice.isPad && (plan?.isEnabled(identity) ?? true)- if guestDevice.isPad {- print(" [·] \(identity): skipped, the device tree already presents \(guestDevice.productType)")- } else if let plan, !rewriteIdentity {- print(" [·] \(identity): off in preset \(plan.presetIdentifier)")+ var rewriteIdentity = false+ if includeIdentity {+ if guestDevice.isPad {+ print(" [·] \(identity): skipped, the device tree already presents \(guestDevice.productType)")+ } else {+ rewriteIdentity = on(identity)+ }}- guard rewriteIdentity || !(spoofBuild ?? "").isEmpty else { return }+ let spoofBuild = includeIdentity ? self.spoofBuild : nil+ let boardAudio = boardDeviceTree != nil && on(FirmwareGuestSystemPatchSet.prebootBoardAudio)+ guard rewriteIdentity || boardAudio || !(spoofBuild ?? "").isEmpty else { return }guardlet preboot = volumes.first(where: { ($0["Roles"] as? [String])?.contains("Preboot") == true }),let device = preboot["DeviceIdentifier"] as? String@@ -1025,6 +1211,15 @@ struct VPhoneCustomFirmwareInstaller {if rewriteIdentity {try patchCopy(of: deviceTree, in: root, work: work, verb: "patch-post-restore-dt")}+ if boardAudio, let boardDeviceTree {+ try patchCopy(+ of: deviceTree,+ in: root,+ work: work,+ verb: "patch-dt-board-audio",+ arguments: [boardDeviceTree.path],+ )+ }if let build = spoofBuild {let version = "Cryptexes/OS/System/Library/CoreServices/SystemVersion.plist"if try root.isRegularFile(version) {@@ -1034,6 +1229,44 @@ struct VPhoneCustomFirmwareInstaller {}}+ /// The iPad's own device tree, `DeviceTree.<board>.im4p`, which `fw patch`+ /// keeps in the VM's `FirmwareOriginals` beside the vphone600 trees,+ /// copied into the work folder by descriptor. Nil when there is none: an+ /// iPhone guest, or a VM patched by a build that did not keep it.+ ///+ /// The folder is the caller's, so the copy goes through the pinned bundle+ /// descriptor like every other read here, and more than one candidate is+ /// refused rather than guessed between.+ private func stageBoardDeviceTree(+ in bundleDirectory: VPhoneConfinedDirectory,+ work: WorkDirectory,+ ) throws -> URL? {+ let originals = VPhoneBundleOperations.firmwareOriginalsDirectoryName+ guard try bundleDirectory.isDirectory(originals) else { return nil }+ let stash = try bundleDirectory.directory(originals)+ var found: [(directory: VPhoneConfinedDirectory, name: String, path: String)] = []+ for tree in try stash.entries() where try stash.isDirectory(tree) {+ let flash = "\(tree)/Firmware/all_flash"+ guard try stash.isDirectory(flash) else { continue }+ let directory = try stash.directory(flash)+ for name in try directory.entries()+ where name.hasPrefix("DeviceTree.") && name.hasSuffix(".im4p")+ && !name.hasPrefix("DeviceTree.vphone600") && (try? directory.isRegularFile(name)) == true+ {+ found.append((directory, name, "\(originals)/\(flash)/\(name)"))+ }+ }+ guard !found.isEmpty else { return nil }+ guard found.count == 1, let board = found.first else {+ throw ValidationError(+ "Found \(found.count) board device trees in \(originals): \(found.map(\.path).joined(separator: ", ")). Keep one.",+ )+ }+ try board.directory.copyFile(from: board.name, to: board.name, in: work.directory)+ print("[*] Board device tree: \(board.path)")+ return work.file(board.name)+ }+// MARK: - Guest file patches/// Run a patch verb that edits a guest file in place, on a private copy@@ -1066,15 +1299,44 @@ struct VPhoneCustomFirmwareInstaller {)}+ /// Flip the speaker chains in every tuning set's graph_configurations.plist+ /// onto the generic graph path. The plist lives under the acoustic ID the+ /// image ships for (`Library/Audio/Tunings/<AID>/VAD/`), which varies by+ /// board, so the directory is walked rather than named. An image with no+ /// tuning sets — iOS 27's VirtualAudio reads no such plist — is left+ /// alone, quietly: there is nothing this patch could act on.+ private func patchVirtualAudioGraphConfigurations(+ system: VPhoneConfinedDirectory,+ work: WorkDirectory,+ ) throws {+ let tunings = "Library/Audio/Tunings"+ guard try system.exists(tunings), try system.isDirectory(tunings) else {+ print(" [·] \(tunings): not on this VM, left out")+ return+ }+ var patched = 0+ for acousticID in try system.directory(tunings).entries().sorted() {+ let plist = "\(tunings)/\(acousticID)/VAD/graph_configurations.plist"+ guard try system.isRegularFile(plist) else { continue }+ try patchCopy(of: plist, in: system, work: work, verb: "patch-virtualaudio-graph-configurations")+ patched += 1+ }+ if patched == 0 {+ print(" [·] \(tunings): no graph_configurations.plist under any tuning set, left out")+ }+ }+/// Stage a guest Mach-O, patch it, re-sign it and put it back.///- /// `verb` is optional: a binary that only needs a library injected — as- /// installd does for libmisfix — has no bytes of its own to change.+ /// `verbs` runs in order against the one staged copy — the staging starts+ /// from the pristine backup, so two calls would not compose. Empty: a+ /// binary that only needs a library injected — as installd does for+ /// libmisfix — has no bytes of its own to change.private func patchMachO(system: VPhoneConfinedDirectory,work: WorkDirectory,path: String,- verb: String? = nil,+ verbs: [String] = [],identifier: String? = nil,preserveEntitlements: Bool = false,injectedDylibPath: String? = nil,@@ -1091,7 +1353,7 @@ struct VPhoneCustomFirmwareInstaller {preserveEntitlements? try VPhoneSigner.entitlements(ofFileAt: staged).first(where: { !$0.isEmpty }): nil- if let verb {+ for verb in verbs {try patch(verb, [staged.path])}if let injectedDylibPath {@@ -1104,6 +1366,22 @@ struct VPhoneCustomFirmwareInstaller {try system.replaceFile(path, fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)}+ /// Re-seal a code-signed bundle on the mounted guest system volume.+ ///+ /// `patchMachO` re-signs the Mach-O it replaces, but a bundle's outer+ /// `_CodeSignature/CodeResources` seals the whole directory, and a guest+ /// built with the code-signing monitor kills the process that loads a+ /// bundle whose seal no longer matches its contents. Ad hoc, like every+ /// other guest binary this pipeline writes; the identifier is kept so the+ /// plugin still answers to the name it always had.+ private func sealGuestBundle(system: VPhoneConfinedDirectory, bundle: String) throws {+ // No --identifier: codesign keeps the one the bundle already carries.+ _ = try tool("/usr/bin/codesign", [+ "-f", "-s", "-", "--timestamp=none",+ try system.directory(bundle).path,+ ])+ }+/// Copy an optional guest binary into the work folder, or nil (with a/// note) when it is absent or not a regular file.private func stageOptional(diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swiftindex 2f56b97a..b21a1429 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift@@ -302,7 +302,203 @@ struct VPhoneCustomFirmwarePatchDiskimagesiodCommand: ParsableCommand {}}-// MARK: - Registration+// MARK: - patch-virtualaudio-mute++struct VPhoneCustomFirmwarePatchVirtualAudioMuteCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-virtualaudio-mute",+ abstract: "Keep VirtualAudio's mute-set CAException from abandoning the speaker route",+ discussion: """+ Establishing a speaker route asks the HAL device itself to unmute;+ iOS's HAL server rejects a device-level mute on a plugin device with+ 'what' without ever forwarding the selector to the driver, and+ VirtualAudio's set wrapper answers the failure by throwing a+ CAException out of the callback. RoutingManager catches it and+ abandons the route — the aggregate is left on Null_Device and the+ guest is silent, the missing boot charge chime included.++ The throw block's first instruction — the `mov w0, #<size>` sizing+ the exception — is replaced with a branch to the wrapper's own+ epilogue, so the failed set logs its diagnostics and returns; the+ callers ignore the return value and the route proceeds. Anchored on+ the mute-set log string, with the site discriminated by the+ "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.++ Idempotent: a site already holding the branch 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 site and write nothing")+ var dryRun = false++ func run() throws {+ try requireUntruncatedMachO(at: binary)+ // reattest: false — the caller re-signs.+ try CustomFirmwareVirtualAudio.patchMuteSet(+ fileAt: binary,+ reattest: false,+ dryRun: dryRun,+ log: machOVerbLog,+ )+ }+}++// MARK: - patch-virtualaudio-sp-gate++struct VPhoneCustomFirmwarePatchVirtualAudioSPGateCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-virtualaudio-sp-gate",+ abstract: "Keep VirtualAudio's speaker-protection gate from declining a finished route",+ discussion: """+ With the speaker-route throws quieted, the ringtone ('crnp') route+ change still builds its whole route — virtual stream, DSP chain,+ format match — and then declines it at the last step, because the+ route's device list calls for HAL Speaker Protection, a capability+ only a physical codec reports and whose query never leaves+ VirtualAudio. The decline drops the vdef's output stream onto+ Null_Device: every "playing" signature is genuine and nothing is+ audible, volume included.++ The gate's branch is left alone; what changes is the log block it+ jumps to, whose opening instruction — the `mov w0, #<size>` sizing+ the os_log — becomes a branch back to the gate's own fall-through,+ so a taken gate lands on the success path the handler already 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. The site is anchored on the decline's log+ format and named by the handler's own source file: the same message+ serves three routing handlers, ours among them by that file string+ alone. No address is literal.++ Idempotent: a site already holding the branch 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 site and write nothing")+ var dryRun = false++ func run() throws {+ try requireUntruncatedMachO(at: binary)+ // reattest: false — the caller re-signs.+ try CustomFirmwareVirtualAudio.patchSpeakerProtectionGate(+ fileAt: binary,+ reattest: false,+ dryRun: dryRun,+ log: machOVerbLog,+ )+ }+}++// MARK: - patch-virtualaudio-volume-gate++struct VPhoneCustomFirmwarePatchVirtualAudioVolumeGateCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-virtualaudio-volume-gate",+ abstract: "Keep VirtualAudio's volume-mode precondition from declining a finished route",+ discussion: """+ One step after the speaker-protection gate, the same route handler+ demands the route's software-volume mode be the packed (present,+ kHardwareOnlyReadOnly) pair its routing database calls for. A device+ whose software volume runs any other mode — the virtio plugin's+ reports SoftwareHardwareMix — fails the test, and the handler throws+ a std::logic_error that unwinds into RoutingManager: the route is+ failed and the session torn down onto Null_Device, silent with the+ volume dead, after its DSP chain, virtual stream and IOProc were+ already built on the virtio aggregate.++ The comparison is left alone; what changes is the decline's log+ block, whose opening instruction — the `mov w0, #<size>` sizing the+ os_log — becomes a branch back to the comparison's own fall-through,+ so a failed precondition lands on the success path the handler+ already built. That path never reads the value the comparison+ tested, on either supported build, and the block is reached only by+ the comparison's jump — the instruction above it is an+ unconditional branch, checked before anything is written. The site+ is anchored on the handler its speaker-protection sibling targets,+ and picked out among the handler's three PRECONDITION FAILURE+ declines by the comparison itself: the only one that masks a+ lookup's return with the 33-bit volume-mode packing mask and+ compares it against the expected pair. No address is literal.++ Idempotent: a site already holding the branch 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 site and write nothing")+ var dryRun = false++ func run() throws {+ try requireUntruncatedMachO(at: binary)+ // reattest: false — the caller re-signs.+ try CustomFirmwareVirtualAudio.patchVolumeModePrecondition(+ fileAt: binary,+ reattest: false,+ dryRun: dryRun,+ log: machOVerbLog,+ )+ }+}++// MARK: - patch-virtualaudio++struct VPhoneCustomFirmwarePatchVirtualAudioCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-virtualaudio",+ abstract: "Keep VirtualAudio's \"No default VAD present\" exception from aborting audiomxd",+ discussion: """+ VirtualAudio answers a missing default VAD while applying a speaker+ route with a C++ exception, from inside an AudioServerPlugIn property+ callback — a C boundary the exception cannot cross, so audiomxd+ terminates. With the virtio sound device publishing the guest's only+ speaker port, every serialized route push lands on that throw, and the+ saved state replays it into every launch: a crash loop.++ The throw block's first instruction — the `mov w0, #<size>` sizing the+ exception — is replaced with a branch to the function's own epilogue,+ so a missing default VAD applies nothing and returns. The site is+ anchored on the exception's message string, referenced by both the+ diagnostic log and the runtime_error constructor; the epilogue is+ located and shape-checked as the stack-guarded pop run after the+ throw. No address is literal.++ Idempotent: a site already holding the branch 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 site and write nothing")+ var dryRun = false++ func run() throws {+ try requireUntruncatedMachO(at: binary)+ // reattest: false — the caller re-signs.+ try CustomFirmwareVirtualAudio.patch(+ fileAt: binary,+ reattest: false,+ dryRun: dryRun,+ log: machOVerbLog,+ )+ }+}enum VPhoneCustomFirmwareMachOVerbs {/// Registered into `vphone-cli cfw` by `VPhoneCustomFirmwareCommand`.@@ -317,6 +513,10 @@ enum VPhoneCustomFirmwareMachOVerbs {VPhoneCustomFirmwarePatchLaunchdJetsamCommand.self,VPhoneCustomFirmwarePatchWatchdogdCommand.self,VPhoneCustomFirmwarePatchDiskimagesiodCommand.self,+ VPhoneCustomFirmwarePatchVirtualAudioCommand.self,+ VPhoneCustomFirmwarePatchVirtualAudioMuteCommand.self,+ VPhoneCustomFirmwarePatchVirtualAudioSPGateCommand.self,+ VPhoneCustomFirmwarePatchVirtualAudioVolumeGateCommand.self,]}}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swiftindex 71d9fd1e..50c92049 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift@@ -216,6 +216,42 @@ struct VPhoneCustomFirmwarePatchBuildVersionCommand: ParsableCommand {}}+// MARK: - patch-virtualaudio-graph-configurations++struct VPhoneCustomFirmwarePatchVirtualAudioGraphConfigurationsCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-virtualaudio-graph-configurations",+ abstract: "Move VirtualAudio's speaker chains onto the generic graph path",+ discussion: """+ graph_configurations.plist gives every route configuration a+ chainType, and the DSP chain factory switches on it: `clhs` builds the+ HAL SpeakerProtection chain, which looks the physical "Speaker" device+ up in the device registry and throws when a VM has none — the throw+ RoutingManager answers by abandoning every speaker route. `dflt`+ builds the generic graph chain the mic configurations already use,+ which needs no device.++ Every speaker_* entry's chainType is flipped `clhs` -> `dflt`; the+ entries' graph and austrip tunings are left alone. The plist sits on+ the sealed system volume, so the install stages a copy and this+ patches the copy.++ Idempotent — a re-run on an already-patched plist reports and exits+ without rewriting.+ """,+ )++ @Argument(help: "Path to graph_configurations.plist", transform: URL.init(fileURLWithPath:))+ var plist: URL++ @Flag(name: .customLong("dry-run"), help: "Report what would change and exit")+ var dryRun = false++ func run() throws {+ try CustomFirmwareVirtualAudioGraphConfigurations.patch(at: plist, dryRun: dryRun, verbose: true)+ }+}+// MARK: - patch-campo-entitlementsstruct VPhoneCustomFirmwarePatchCampoEntitlementsCommand: ParsableCommand {@@ -278,3 +314,42 @@ struct VPhoneCustomFirmwarePatchPostRestoreDeviceTreeCommand: ParsableCommand {try CustomFirmwarePostRestoreDeviceTree.patch(at: deviceTree, dryRun: dryRun, verbose: true)}}++// MARK: - patch-dt-board-audio++struct VPhoneCustomFirmwarePatchBoardAudioCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-dt-board-audio",+ abstract: "Give an iPad guest's device tree the iPad's own audio node",+ discussion: """+ Replaces /product/audio in a restored device tree with the audio node of+ the iPad's own tree (DeviceTree.<board>.im4p from its IPSW), in place,+ preserving the container's compression, manifest and restore info. The+ node earlier device tree patches added is the D47 iPhone's, whose+ acoustic ID names tunings an iPad image does not ship; iOS's VirtualAudio+ then fails to initialize and the guest has no audio device. A tree that+ already matches is left as it is.++ Takes a devicetree.img4 (preferred) or a bare .im4p, and the board's+ DeviceTree .im4p.+ """,+ )++ @Argument(help: "Path to devicetree.img4 or devicetree.im4p", transform: URL.init(fileURLWithPath:))+ var deviceTree: URL++ @Argument(help: "Path to the iPad's DeviceTree.<board>.im4p", transform: URL.init(fileURLWithPath:))+ var board: URL++ @Flag(name: .customLong("dry-run"), help: "Report what would change and exit")+ var dryRun = false++ func run() throws {+ try CustomFirmwarePostRestoreDeviceTree.presentBoardAudio(+ at: deviceTree,+ board: board,+ dryRun: dryRun,+ verbose: true,+ )+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swiftindex 32abf654..5485b2c4 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift@@ -181,8 +181,10 @@ struct VPhoneCustomFirmwareCommand: ParsableCommand {VPhoneCustomFirmwarePatchDropbearPlistCommand.self,VPhoneCustomFirmwareInjectDylibCommand.self,VPhoneCustomFirmwarePatchBuildVersionCommand.self,+ VPhoneCustomFirmwarePatchVirtualAudioGraphConfigurationsCommand.self,VPhoneCustomFirmwarePatchCampoEntitlementsCommand.self,VPhoneCustomFirmwarePatchPostRestoreDeviceTreeCommand.self,+ VPhoneCustomFirmwarePatchBoardAudioCommand.self,] + VPhoneCustomFirmwareMachOVerbs.all + VPhoneCustomFirmwareDyldSharedCacheVerbs.all,)}diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.shindex c6818c0b..3163f377 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh@@ -76,6 +76,9 @@ fi/bin/cp "$guest_products/hapticsfix/libhapticsfix.dylib" "$guest/libhapticsfix.dylib"/bin/cp "$guest_products/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib" \"$guest/libAppleParavirtCompilerPluginIOGPUFamily.dylib"+# The HAL plugin is a bundle, signed whole by the Makefile; copied as a tree so+# its _CodeSignature still matches.+/bin/cp -R "$guest_products/virtiosound/VPhoneVirtIOSound.driver" "$guest/VPhoneVirtIOSound.driver"# The commit this bundle was built from, shown in vphone-vm's app menu next to# CFBundleShortVersionString and CFBundleVersion. A tree with uncommitteddiff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.shindex c3f9ef4b..cd1eb286 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh@@ -81,6 +81,18 @@ donefor name in vphoned.plist libcamfix.plist libvcamcaptured.plist libmisfix.plist; do[[ -f "$guest/$name" ]] || { print -u2 "Missing guest configuration: $name"; exit 1; }done+# The virtio sound HAL plugin is a whole bundle: audiomxd finds its factory+# through Info.plist, and the bundle signature seals both.+require_signed_macho "$guest/VPhoneVirtIOSound.driver/VPhoneVirtIOSound"+/usr/bin/codesign --verify --strict "$guest/VPhoneVirtIOSound.driver" || {+ print -u2 "Invalid signature: VPhoneVirtIOSound.driver"+ exit 1+}+/usr/libexec/PlistBuddy -c 'Print :CFPlugInFactories' "$guest/VPhoneVirtIOSound.driver/Info.plist" |+ /usr/bin/grep -q VPVirtIOSoundFactory || {+ print -u2 "VPhoneVirtIOSound.driver does not name its factory"+ exit 1+}[[ ! -e "$guest/libvlocation.dylib" ]] || { print -u2 "Obsolete guest library: libvlocation.dylib"; exit 1; }for name in vphoned vphoned.signed vphone-app VPhoneAMFIAllow VPhoneEscalator vphone-archive icli vpregister \diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefileindex aeffb349..5563803b 100644--- a/VPhoneGuestComponents/Makefile+++ b/VPhoneGuestComponents/Makefile@@ -78,14 +78,20 @@ GPU_DYNAMIC_LOOKUP_SYMS := \-Wl,-U,_MTLMetalFunctionCreate \-Wl,-U,_MTLMetalLibInsertFunction \-Wl,-U,_MTLWriteMetalLibToMemoryBuffer-ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(GPU_PLUGIN)+# The HAL plugin audiomxd loads for the virtio-snd device. AudioServerDriver+# is private and not in the SDK, so its classes link against the stub beside+# the sources. The bundle is flat, as iOS HAL plugins are, and signed whole.+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) $(GPU_PLUGIN) $(VIRTIOSOUND)PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist \$(STAGE)/misfix/libmisfix.plistGPU_PROVENANCE := $(STAGE)/gpu/README.md# Directory timestamps also catch files removed from the wildcard inputs.-.PHONY: all gpu package test-loader-links test-injection-environment test-vcam-dataplane clean+.PHONY: all gpu package test-loader-links test-injection-environment test-vcam-dataplane test-virtiosound cleanall: $(ARTIFACTS) $(PLISTS) $(GPU_PROVENANCE)@@ -93,7 +99,7 @@ gpu: $(GPU_PLUGIN)package: all@rm -f $(ARCHIVE)- @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix gpu+ @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix gpu virtiosound@echo "Packaged $(ARCHIVE)"test-loader-links:@@ -108,6 +114,14 @@ test-injection-environment:-o $(OUT)/InjectionEnvironmentTests Tests/InjectionEnvironmentTests.c@$(OUT)/InjectionEnvironmentTests+# Host proof harness for the virtio-snd format choice and output ring.+test-virtiosound:+ @mkdir -p $(OUT)+ xcrun --sdk macosx clang -O1 -Wall -Wextra -Werror -IVirtIOSound \+ -o $(OUT)/VirtIOSoundTests \+ Tests/VirtIOSoundTests.c VirtIOSound/VPVirtIOSoundProtocol.c VirtIOSound/VPVirtIOSoundRing.c+ @$(OUT)/VirtIOSoundTests+# Host proof harness for the camera data plane the guest hooks share.test-vcam-dataplane:@mkdir -p $(OUT)@@ -119,7 +133,7 @@ test-vcam-dataplane:-framework CoreGraphics@$(OUT)/VCamDataPlaneTests-$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/misfix $(STAGE)/hapticsfix $(STAGE)/gpu:+$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/misfix $(STAGE)/hapticsfix $(STAGE)/gpu $(STAGE)/virtiosound:@mkdir -p $@$(CAMFIX): $(CAMFIX_SOURCES) $(CAMFIX_INPUTS) | $(STAGE)/camfix@@ -177,6 +191,16 @@ $(GPU_PLUGIN): $(GPU_PLUGIN_SOURCES) $(GPU_PLUGIN_INCLUDES) GraphicLoader | $(ST-o $@ $(GPU_PLUGIN_SOURCES)@codesign --force --sign - $@+$(VIRTIOSOUND): $(VIRTIOSOUND_SOURCES) $(VIRTIOSOUND_INCLUDES) VirtIOSound | $(STAGE)/virtiosound+ @rm -rf $@+ @mkdir -p $@+ $(CLANG) $(COMMON_FLAGS) -Wall -Wextra -Werror -fvisibility=hidden -bundle \+ -o $@/VPhoneVirtIOSound $(VIRTIOSOUND_SOURCES) \+ -framework Foundation -framework CoreAudio -framework IOKit \+ VirtIOSound/AudioServerDriver.tbd -Wl,-not_for_dyld_shared_cache+ @cp VirtIOSound/Info.plist $@/Info.plist+ @codesign --force --sign - $@+$(STAGE)/camfix/libcamfix.plist: CamFix/libcamfix.plist | $(STAGE)/camfix@cp $< $@diff --git a/VPhoneGuestComponents/README.md b/VPhoneGuestComponents/README.mdindex 10f64959..1f805d6b 100644--- a/VPhoneGuestComponents/README.md+++ b/VPhoneGuestComponents/README.md@@ -13,6 +13,7 @@ tweak filter plists, and the GPU provenance note:| Process injection bridge | `systemhook/SystemHook-vphone.dylib` || iOS 27 app registrar | `vpregister/vpregister` || PCC GPU driver | `gpu/README.md` (source and extraction flow; no Apple binary) |+| Virtio sound HAL plugin | `virtiosound/VPhoneVirtIOSound.driver` |The archive is a local build artifact, not a VM bootstrap. `cfw install` placesthe launchd hook, SystemHook, and camera hooks in `/usr/lib`, and the@@ -39,3 +40,8 @@ Apple GPU binary is stored in this directory, the archive, or the shipped app.See `Research/Guest/virtual_camera_transport.md` for the camera transportvalidation and the hook installation prerequisites.++The virtio sound plugin is the CoreAudio half of the VM's virtio-snd device,+which iOS ships no driver for. audiomxd loads it when the kernel publishes+`AppleVirtIOSound`. `make test-virtiosound` checks its format choice and output+ring on the host. See `Research/Guest/virtio_sound.md`.diff --git a/VPhoneGuestComponents/Tests/VirtIOSoundTests.c b/VPhoneGuestComponents/Tests/VirtIOSoundTests.cnew file mode 100644index 00000000..e419139a--- /dev/null+++ b/VPhoneGuestComponents/Tests/VirtIOSoundTests.c@@ -0,0 +1,213 @@+// VirtIOSoundTests.c — host checks for the virtio-snd HAL plugin's pure parts:+// the format the plugin asks the device for, and the output ring's counters.++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "VPVirtIOSoundProtocol.h"+#include "VPVirtIOSoundRing.h"++static int failures;++#define CHECK(condition) \+ do { \+ if (!(condition)) { \+ fprintf(stderr, "%s:%d: CHECK(%s) failed\n", __FILE__, __LINE__, \+ #condition); \+ failures++; \+ } \+ } while (0)++// MARK: - Format choice++static VPVirtIOSoundPCMInfo info(uint64_t formats, uint64_t rates, uint8_t channels) {+ VPVirtIOSoundPCMInfo value;+ memset(&value, 0, sizeof(value));+ value.formats = formats;+ value.rates = rates;+ value.channelsMinimum = 1;+ value.channelsMaximum = channels;+ return value;+}++static void testPrefersFloat48k(void) {+ // What Virtualization.framework's VZHostAudioOutputStreamSink offers.+ VPVirtIOSoundPCMInfo device = info(1ULL << 19 | 1ULL << 5, 1ULL << 7 | 1ULL << 6, 2);+ VPVirtIOSoundStreamFormat format;+ CHECK(VPVirtIOSoundChooseFormat(&device, &format));+ CHECK(format.virtioFormat == kVPVirtIOSoundFormatFloat);+ CHECK(format.isFloat);+ CHECK(format.bitsPerChannel == 32);+ CHECK(format.virtioRate == 7);+ CHECK(format.sampleRate == 48000);+ CHECK(format.channels == 2);+ CHECK(format.bytesPerFrame == 8);+}++static void testFallsBackToInteger(void) {+ VPVirtIOSoundPCMInfo device = info(1ULL << 5, 1ULL << 6, 1);+ VPVirtIOSoundStreamFormat format;+ CHECK(VPVirtIOSoundChooseFormat(&device, &format));+ CHECK(format.virtioFormat == kVPVirtIOSoundFormatS16);+ CHECK(!format.isFloat);+ CHECK(format.sampleRate == 44100);+ CHECK(format.bytesPerFrame == 2);+}++static void testTakesHighestOtherRate(void) {+ VPVirtIOSoundPCMInfo device = info(1ULL << 17, 1ULL << 3 | 1ULL << 10, 2);+ VPVirtIOSoundStreamFormat format;+ CHECK(VPVirtIOSoundChooseFormat(&device, &format));+ CHECK(format.sampleRate == 96000);+ CHECK(format.virtioRate == 10);+}++static void testRefusesUnusableDevice(void) {+ VPVirtIOSoundStreamFormat format;+ VPVirtIOSoundPCMInfo noFormat = info(1ULL << 3, 1ULL << 7, 2);+ CHECK(!VPVirtIOSoundChooseFormat(&noFormat, &format));+ VPVirtIOSoundPCMInfo noRate = info(1ULL << 19, 0, 2);+ CHECK(!VPVirtIOSoundChooseFormat(&noRate, &format));+ VPVirtIOSoundPCMInfo noChannels = info(1ULL << 19, 1ULL << 7, 0);+ CHECK(!VPVirtIOSoundChooseFormat(&noChannels, &format));+}++static void testSizesAndParameters(void) {+ VPVirtIOSoundPCMInfo device = info(1ULL << 19, 1ULL << 7, 2);+ VPVirtIOSoundStreamFormat format;+ CHECK(VPVirtIOSoundChooseFormat(&device, &format));+ uint32_t period = 0;+ uint32_t buffer = 0;+ // 48000 * 8 / 12 = 32000 bytes, rounded up to 16 KiB pages.+ VPVirtIOSoundBufferSizes(&format, 16384, &period, &buffer);+ CHECK(period == 32768);+ CHECK(buffer == 12 * 32768);+ VPVirtIOSoundPCMParameters parameters = VPVirtIOSoundParameters(&format, period, buffer);+ CHECK(parameters.code == 0);+ CHECK(parameters.streamID == 0);+ CHECK(parameters.bufferBytes == buffer);+ CHECK(parameters.periodBytes == period);+ CHECK(parameters.channels == 2);+ CHECK(parameters.format == kVPVirtIOSoundFormatFloat);+ CHECK(parameters.rate == 7);+}++// MARK: - Ring++static void fill(uint8_t *bytes, uint32_t length, uint8_t value) {+ memset(bytes, value, length);+}++static void testRingSubmitsWholePeriods(void) {+ VPVirtIOSoundRing ring;+ CHECK(VPVirtIOSoundRingInit(&ring, 4 * 64, 64));+ uint8_t frames[96];+ fill(frames, sizeof(frames), 1);+ CHECK(VPVirtIOSoundRingWrite(&ring, frames, sizeof(frames)));++ uint32_t offset = 0;+ uint32_t length = 0;+ CHECK(VPVirtIOSoundRingNextSubmission(&ring, false, &offset, &length));+ CHECK(offset == 0 && length == 64);+ VPVirtIOSoundRingDidSubmit(&ring, length);+ // 32 bytes pending: not a period yet.+ CHECK(!VPVirtIOSoundRingNextSubmission(&ring, false, &offset, &length));+ // When the stream stops, the tail goes too.+ CHECK(VPVirtIOSoundRingNextSubmission(&ring, true, &offset, &length));+ CHECK(offset == 64 && length == 32);+ VPVirtIOSoundRingDidSubmit(&ring, length);+ CHECK(VPVirtIOSoundRingInFlight(&ring) == 96);+ VPVirtIOSoundRingDidComplete(&ring, 64);+ VPVirtIOSoundRingDidComplete(&ring, 32);+ CHECK(VPVirtIOSoundRingInFlight(&ring) == 0);+ VPVirtIOSoundRingDestroy(&ring);+}++static void testRingKeepsInFlightBytes(void) {+ VPVirtIOSoundRing ring;+ CHECK(VPVirtIOSoundRingInit(&ring, 4 * 64, 64));+ uint8_t frames[256];+ fill(frames, sizeof(frames), 2);+ CHECK(VPVirtIOSoundRingWrite(&ring, frames, 256));+ // Full: submitting frees nothing, only completion does.+ CHECK(!VPVirtIOSoundRingWrite(&ring, frames, 64));+ uint32_t offset = 0;+ uint32_t length = 0;+ CHECK(VPVirtIOSoundRingNextSubmission(&ring, false, &offset, &length));+ VPVirtIOSoundRingDidSubmit(&ring, length);+ CHECK(!VPVirtIOSoundRingWrite(&ring, frames, 64));+ VPVirtIOSoundRingDidComplete(&ring, length);+ CHECK(VPVirtIOSoundRingWrite(&ring, frames, 64));+ // All or nothing: 65 bytes do not fit in what is left.+ CHECK(!VPVirtIOSoundRingWrite(&ring, frames, 65));+ VPVirtIOSoundRingDestroy(&ring);+}++static void testRingWrapsWritesAndSplitsSubmissions(void) {+ VPVirtIOSoundRing ring;+ CHECK(VPVirtIOSoundRingInit(&ring, 4 * 64, 64));+ uint8_t first[224];+ fill(first, sizeof(first), 3);+ CHECK(VPVirtIOSoundRingWrite(&ring, first, sizeof(first)));+ uint32_t offset = 0;+ uint32_t length = 0;+ // Three whole periods, then the 32-byte tail at 192.+ for (int i = 0; i < 3; i++) {+ CHECK(VPVirtIOSoundRingNextSubmission(&ring, false, &offset, &length));+ VPVirtIOSoundRingDidSubmit(&ring, length);+ VPVirtIOSoundRingDidComplete(&ring, length);+ }+ CHECK(VPVirtIOSoundRingNextSubmission(&ring, true, &offset, &length));+ CHECK(offset == 192 && length == 32);+ VPVirtIOSoundRingDidSubmit(&ring, length);+ VPVirtIOSoundRingDidComplete(&ring, length);++ // 64 bytes now start at 224 and wrap: 32 at the end, 32 at the front.+ uint8_t second[64];+ for (unsigned i = 0; i < sizeof(second); i++) {+ second[i] = (uint8_t)i;+ }+ CHECK(VPVirtIOSoundRingWrite(&ring, second, sizeof(second)));+ CHECK(memcmp(ring.bytes + 224, second, 32) == 0);+ CHECK(memcmp(ring.bytes, second + 32, 32) == 0);+ CHECK(VPVirtIOSoundRingNextSubmission(&ring, false, &offset, &length));+ CHECK(offset == 224 && length == 32);+ VPVirtIOSoundRingDidSubmit(&ring, length);+ CHECK(VPVirtIOSoundRingNextSubmission(&ring, true, &offset, &length));+ CHECK(offset == 0 && length == 32);+ VPVirtIOSoundRingDestroy(&ring);+}++static void testRingResetAndValidation(void) {+ VPVirtIOSoundRing ring;+ CHECK(!VPVirtIOSoundRingInit(&ring, 100, 64));+ CHECK(!VPVirtIOSoundRingInit(&ring, 128, 0));+ CHECK(VPVirtIOSoundRingInit(&ring, 128, 64));+ uint8_t frames[64] = {0};+ CHECK(VPVirtIOSoundRingWrite(&ring, frames, 64));+ VPVirtIOSoundRingReset(&ring);+ uint32_t offset = 0;+ uint32_t length = 0;+ CHECK(!VPVirtIOSoundRingNextSubmission(&ring, true, &offset, &length));+ CHECK(VPVirtIOSoundRingInFlight(&ring) == 0);+ VPVirtIOSoundRingDestroy(&ring);+}++int main(void) {+ testPrefersFloat48k();+ testFallsBackToInteger();+ testTakesHighestOtherRate();+ testRefusesUnusableDevice();+ testSizesAndParameters();+ testRingSubmitsWholePeriods();+ testRingKeepsInFlightBytes();+ testRingWrapsWritesAndSplitsSubmissions();+ testRingResetAndValidation();+ if (failures) {+ fprintf(stderr, "VirtIOSoundTests: %d failure(s)\n", failures);+ return 1;+ }+ printf("VirtIOSoundTests: all passed\n");+ return 0;+}diff --git a/VPhoneGuestComponents/VirtIOSound/AudioServerDriver.tbd b/VPhoneGuestComponents/VirtIOSound/AudioServerDriver.tbdnew file mode 100644index 00000000..7cfbf0d0--- /dev/null+++ b/VPhoneGuestComponents/VirtIOSound/AudioServerDriver.tbd@@ -0,0 +1,13 @@+--- !tapi-tbd+# The AudioServerDriver classes VPhoneVirtIOSound subclasses or instantiates.+# The framework is private and the iPhoneOS SDK ships no stub for it; this one+# lets the linker bind these symbols two-level to the guest's copy, which+# lives in the dyld shared cache.+tbd-version: 4+targets: [ arm64e-ios ]+install-name: '/System/Library/PrivateFrameworks/AudioServerDriver.framework/AudioServerDriver'+current-version: 1+exports:+ - targets: [ arm64e-ios ]+ objc-classes: [ ASDAudioDevice, ASDBooleanControl, ASDLevelControl, ASDObject, ASDPlugin, ASDSelectorControl, ASDSelectorValue, ASDStream, ASDStreamFormat ]+...diff --git a/VPhoneGuestComponents/VirtIOSound/Info.plist b/VPhoneGuestComponents/VirtIOSound/Info.plistnew file mode 100644index 00000000..e90bc12d--- /dev/null+++ b/VPhoneGuestComponents/VirtIOSound/Info.plist@@ -0,0 +1,54 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>AudioServerPlugIn_IOKitUserClients</key>+ <array>+ <string>AppleVirtIOSoundUserClient</string>+ </array>+ <key>AudioServerPlugIn_LoadingConditions</key>+ <dict>+ <key>IOService Matching</key>+ <array>+ <dict>+ <key>IOProviderClass</key>+ <string>AppleVirtIOSound</string>+ </dict>+ </array>+ </dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleExecutable</key>+ <string>VPhoneVirtIOSound</string>+ <key>CFBundleIdentifier</key>+ <string>com.vphone.audio.VirtIOSound</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>VPhoneVirtIOSound</string>+ <key>CFBundlePackageType</key>+ <string>BNDL</string>+ <key>CFBundleShortVersionString</key>+ <string>1.0</string>+ <key>CFBundleSupportedPlatforms</key>+ <array>+ <string>iPhoneOS</string>+ </array>+ <key>CFBundleVersion</key>+ <string>1</string>+ <key>CFPlugInFactories</key>+ <dict>+ <key>A5F451C6-A051-4EEE-A0E7-FF65407CDB43</key>+ <string>VPVirtIOSoundFactory</string>+ </dict>+ <key>CFPlugInTypes</key>+ <dict>+ <key>443ABAB8-E7B3-491A-B985-BEB9187030DB</key>+ <array>+ <string>A5F451C6-A051-4EEE-A0E7-FF65407CDB43</string>+ </array>+ </dict>+ <key>MinimumOSVersion</key>+ <string>26.0</string>+</dict>+</plist>diff --git a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundAudioServerDriver.h b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundAudioServerDriver.hnew file mode 100644index 00000000..eab1057e--- /dev/null+++ b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundAudioServerDriver.h@@ -0,0 +1,198 @@+// VPVirtIOSoundAudioServerDriver.h — the part of AudioServerDriver we use.+//+// AudioServerDriver.framework is the private Objective-C layer Apple's HAL+// plugins are written in; BuiltinAudioPlugin uses it on iOS and+// AppleVirtIOSound.driver on macOS. It ships no headers, so these are the+// classes and selectors the macOS AppleVirtIOSound plugin calls, declared+// with the signatures its class-dump shows. AudioServerDriver.tbd beside+// this file lets the linker bind them two-level.++#ifndef VPVirtIOSoundAudioServerDriver_h+#define VPVirtIOSoundAudioServerDriver_h++#import <CoreAudio/AudioServerPlugIn.h>+#import <Foundation/Foundation.h>++/// `ASDStreamDirection`: the HAL scope four-character codes.+typedef UInt32 ASDStreamDirection;+static const ASDStreamDirection ASDStreamDirectionOutput = kAudioObjectPropertyScopeOutput;++@class ASDPlugin;++@interface ASDObject : NSObject+@property (weak, nonatomic) ASDObject *owner;+@property (weak, nonatomic) ASDPlugin *plugin;+/// The object's registered CoreAudio class FourCharCode (what+/// `kAudioObjectPropertyClass` answers). Server-side ASD getter.+- (UInt32)objectClass;+/// Whether the object's class chain carries a CoreAudio class — the predicate+/// ASDAudioDevice's property dispatch consults when routing device-level+/// selectors like `kAudioDevicePropertyMute` to controls.+- (BOOL)isKindOfAudioClass:(UInt32)classID;+/// The property plumbing the plugin driver's C ops call into. The iOS+/// ASDAudioDevice implements these for its selector set — which, disassembled,+/// contains no `kAudioDevicePropertyMute`, so a plugin device answers that+/// selector by overriding them. Signatures follow the arm64e argument layout+/// of ASDAudioDevice's own implementations; both accessors return a handled+/// flag (YES = the C-op layer reports success, NO = it answers 'what').+- (BOOL)hasProperty:(AudioObjectPropertyAddress *)address;+- (BOOL)isPropertySettable:(AudioObjectPropertyAddress *)address;+- (UInt32)dataSizeForProperty:(AudioObjectPropertyAddress *)address+ withQualifierSize:(UInt32)qualifierSize+ andQualifierData:(const void *)qualifierData;+- (BOOL)getProperty:(AudioObjectPropertyAddress *)address+ withQualifierSize:(UInt32)qualifierSize+ qualifierData:(const void *)qualifierData+ dataSize:(UInt32 *)dataSize+ andData:(void *)data+ forClient:(UInt32)clientID;+- (BOOL)setProperty:(AudioObjectPropertyAddress *)address+ withQualifierSize:(UInt32)qualifierSize+ qualifierData:(const void *)qualifierData+ dataSize:(UInt32)dataSize+ andData:(const void *)data+ forClient:(UInt32)clientID;+@end++@interface ASDPlugin : ASDObject+@property (readonly, nonatomic) AudioServerPlugInDriverRef driverRef;+@property (readonly, nonatomic) NSString *bundleID;+- (void)halInitializeWithPluginHost:(AudioServerPlugInHostRef)host;+- (void)addAudioDevice:(id)device;+- (NSArray *)audioDevices;+@end++/// Signatures from the macOS plugin's block type encodings.+typedef int (^ASDGetZeroTimestampBlock)(Float64 *sampleTime, UInt64 *hostTime, UInt64 *seed, UInt32 clientID);+typedef int (^ASDWillDoBlock)(UInt32 operationID, Boolean *willDo, Boolean *willDoInPlace);+typedef int (^ASDIOBlock)(+ UInt32 frameCount,+ const AudioServerPlugInIOCycleInfo *cycleInfo,+ void *mainBuffer,+ void *secondaryBuffer,+ UInt32 clientID);++@interface ASDAudioDevice : ASDObject+- (instancetype)initWithDeviceUID:(NSString *)uid withPlugin:(ASDPlugin *)plugin;+@property (copy, nonatomic) NSString *deviceName;+@property (copy, nonatomic) NSString *modelName;+@property (copy, nonatomic) NSString *manufacturerName;+@property (nonatomic) BOOL canBeDefaultInputDevice;+@property (nonatomic) BOOL canBeDefaultOutputDevice;+@property (nonatomic) BOOL canBeDefaultSystemDevice;+@property (nonatomic) BOOL canChangeDeviceName;+@property (nonatomic) double samplingRate;+@property (copy, nonatomic) NSArray<NSNumber *> *samplingRates;+@property (nonatomic) UInt32 timestampPeriod;+@property (nonatomic) UInt32 inputSafetyOffset;+@property (nonatomic) UInt32 outputSafetyOffset;+@property (nonatomic) UInt32 transportType;+@property (readonly, nonatomic) BOOL hasOutput;+/// The rates the device answers `kAudioDevicePropertyAvailableSampleRates`+/// with; the framework validates a nominal-rate change against+/// `supportsSamplingRate:` before switching.+- (BOOL)supportsSamplingRate:(double)rate;+@property (copy, nonatomic) ASDGetZeroTimestampBlock getZeroTimestampBlock;+@property (copy, nonatomic) ASDWillDoBlock willDoReadInputBlock;+@property (copy, nonatomic) ASDWillDoBlock willDoWriteMixBlock;+- (void)addOutputStream:(id)stream;+- (NSArray *)outputStreams;+- (int)performStartIO;+- (int)performStopIO;+@end++/// A hardware volume control, as the macOS `AppleVirtIOSound.driver` creates+/// one for its device. Signatures follow the selectors its binary references;+/// the factory returns an autoreleased control bound to the plugin.+@interface ASDLevelControl : ASDObject++ (instancetype)volumeControlWithDecibelValue:(float)decibelValue+ minimumValue:(float)minimumValue+ maximumValue:(float)maximumValue+ isSettable:(BOOL)settable+ forElement:(UInt32)element+ inScope:(UInt32)scope+ withPlugin:(ASDPlugin *)plugin;+/// Mirrors the boolean control's explicit-class initializer: pins the+/// control class ID instead of trusting the factory to pick one.+- (instancetype)initWithDecibelValue:(float)decibelValue+ minimumValue:(float)minimumValue+ maximumValue:(float)maximumValue+ isSettable:(BOOL)settable+ forElement:(UInt32)element+ inScope:(UInt32)scope+ withPlugin:(ASDPlugin *)plugin+ andObjectClassID:(UInt32)classID;+@property (nonatomic, readonly) float scalarValue;+@property (nonatomic, readonly) float decibelValue;+@property (nonatomic, readonly) float minimumDecibelValue;+@property (nonatomic, readonly) float maximumDecibelValue;+- (void)setDecibelValue:(float)value;+@end++/// The matching mute control.+@interface ASDBooleanControl : ASDObject++ (instancetype)muteControlWithValue:(BOOL)value+ isSettable:(BOOL)settable+ forElement:(UInt32)element+ inScope:(UInt32)scope+ withPlugin:(ASDPlugin *)plugin;+/// The guest ASD also answers this explicit-class initializer. Its+/// `muteControlWithValue:...` factory yields a control that does not answer+/// `kAudioDevicePropertyMute` (VirtualAudio's route unmute fails 'what'),+/// so the mute control pins `kAudioMuteControlClassID` through this one the+/// way the data-source control pins `kAudioDataSourceControlClassID`.+- (instancetype)initWithValue:(BOOL)value+ isSettable:(BOOL)settable+ forElement:(UInt32)element+ inScope:(UInt32)scope+ withPlugin:(ASDPlugin *)plugin+ andObjectClassID:(UInt32)classID;+@property (nonatomic, readonly, getter=booleanValue) BOOL booleanValue;+- (void)setValue:(UInt32)value;+@end++/// One selectable value of an `ASDSelectorControl`, as the macOS+/// `AppleVirtIOSound.driver` configures its speaker data source.+@interface ASDSelectorValue : ASDObject+- (void)setValue:(UInt32)value;+- (void)setName:(NSString *)name;+@end++/// A data-source selector control; the class ID is a CoreAudio control class+/// (`kAudioDataSourceControlClassID`).+@interface ASDSelectorControl : ASDObject+- (instancetype)initWithIsSettable:(BOOL)settable+ forElement:(UInt32)element+ inScope:(UInt32)scope+ withPlugin:(ASDPlugin *)plugin+ andObjectClassID:(UInt32)classID;+- (void)addValue:(ASDSelectorValue *)value;+- (void)setSelectedValues:(NSArray<ASDSelectorValue *> *)values;+@end++@interface ASDAudioDevice (Controls)+- (void)addControl:(ASDObject *)control;+@end++@interface ASDStreamFormat : NSObject <NSCopying>+- (instancetype)initWithAudioStreamBasicDescription:(AudioStreamBasicDescription)description;+@property (nonatomic) double sampleRate;+@property (nonatomic) double minimumSampleRate;+@property (nonatomic) double maximumSampleRate;+@end++@interface ASDStream : ASDObject+- (instancetype)initWithDirection:(ASDStreamDirection)direction withPlugin:(ASDPlugin *)plugin;+@property (copy, nonatomic) NSString *streamName;+@property (copy, nonatomic) ASDStreamFormat *physicalFormat;+@property (copy, nonatomic) NSArray<ASDStreamFormat *> *physicalFormats;+@property (nonatomic) BOOL physicalFormatSettable;+@property (copy, nonatomic) ASDIOBlock writeMixBlock;+/// Sent to every stream when the device's nominal sample rate changed; the+/// default implementation reconciles the physical format with the new rate.+- (void)deviceChangedToSamplingRate:(double)rate;+- (void)startStream;+- (void)stopStream;+@end++#endif /* VPVirtIOSoundAudioServerDriver_h */diff --git a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.m b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.mnew file mode 100644index 00000000..b021eed2--- /dev/null+++ b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.m@@ -0,0 +1,1191 @@+// VPVirtIOSoundPlugin.m — CoreAudio HAL plugin for the VM's virtio-snd device.+//+// audiomxd loads this bundle from /System/Library/Audio/Plug-Ins/HAL when the+// kernel has published `AppleVirtIOSound` (Info.plist's loading condition).+// One HAL device is created per `AppleVirtIOSound` service, with one output+// stream per virtio-snd output stream. Input streams are left out: nothing+// in the guest needs the host microphone yet, and leaving them out keeps+// the host from opening it.+//+// The device clock is free running, anchored to mach_absolute_time when I/O+// starts, as the macOS plugin's is. The mixed output goes into a ring (see+// VPVirtIOSoundRing.h) and a timer hands it to the kernel a period at a time+// with the async write selector; the virtio device paces playback on the host.+//+// Two optional settings in the `com.apple.coreaudio` preference domain, read+// once when audiomxd loads the plugin, exist for diagnosing routing:+// VPhoneVirtIOSoundTransportType four-character transport ("usb ", "bltn")+// VPhoneVirtIOSoundDeviceUID HAL device UID++#import "VPVirtIOSoundAudioServerDriver.h"++#include <IOKit/IOKitLib.h>+#include <mach/mach_time.h>+#include <os/log.h>+#include <stdatomic.h>+#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <sys/time.h>+#include <time.h>+#include <unistd.h>++#include "VPVirtIOSoundProtocol.h"+#include "VPVirtIOSoundRing.h"++// Newer CoreAudio spelling of element 0; both arms of the mute check accept+// the raw 0 regardless.+#ifndef kAudioObjectPropertyElementMain+#define kAudioObjectPropertyElementMain 0+#endif++// MARK: - Constants++/// The macOS plugin's timestamp period: 260 ms of frames.+static const double kTimestampPeriodSeconds = 0.26;+static const UInt32 kSafetyOffsetFrames = 100;+/// How often queued periods are handed to the device: 1/24 s, as the macOS+/// plugin flushes, a little under half a period.+static const uint64_t kFlushIntervalNanoseconds = NSEC_PER_SEC / 24;+static const uint32_t kAsyncReferenceCount = 3;++static CFStringRef const kSettingsDomain = CFSTR("com.apple.coreaudio");++/// The internal-speaker data source the macOS plugin selects for its output+/// ('ispk'; no SDK constant carries it).+static const UInt32 kVPDataSourceInternalSpeaker = 0x6973706b;++/// `kAudioDevicePropertyMute` ('mute'), which the trimmed iPhoneOS CoreAudio+/// headers leave out (AudioHardwareBase.h stops at the server-side set).+static const UInt32 kVPDevicePropertyMute = 0x6d757465;++/// `kAudioDevicePropertyNominalSampleRate` ('nsrt'), absent from the same+/// trimmed headers.+static const UInt32 kVPDevicePropertyNominalSampleRate = 0x6e737274;++/// The rate a ringtone-preview aggregate runs the vdef at. The virtio wire+/// itself only offers 48000, so the device advertises this rate beside it+/// and the mix converts into the wire rate.+static const double kVPAlternateRate = 44100;++static os_log_t VPLog(void) {+ static os_log_t log;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ log = os_log_create("com.vphone.audio", "virtiosound");+ });+ return log;+}++// MARK: - Selector inventory++/// The guest's property vocabulary for this plugin, one line per distinct+/// (operation, selector, scope, element). A syslog capture during a session+/// activation then shows every selector VirtualAudio and the HAL server ask+/// the plugin's objects, which selectors they never ask, and in what order —+/// the inventory a missing-property hunt needs. Repeats are suppressed: the+/// first ask of a tuple logs, later ones only counted by the guest's own+/// noise.+///+/// Everything also lands in `/var/mobile/vpquery.log`: the 2.3.x guest+/// vphoned's syslog tail stopped delivering `com.vphone.audio` lines (the+/// 2.2.5-era tail carried them), and the inventory died with the channel.+/// The file is the reliable transport; each line carries a UTC wall-clock+/// stamp so its entries align with the first-party syslog captures that+/// still work, and a size cap keeps a runaway query loop from filling the+/// disk. audiomxd can write there (the session-4 reflection probe proved+/// the path with `/var/mobile/vpprobe.log`).+static void VPLogToFile(const char *format, ...) __attribute__((format(printf, 1, 2)));++static void VPLogToFile(const char *format, ...) {+ static const char *kPath = "/var/mobile/vpquery.log";+ static const off_t kCap = 4 * 1024 * 1024;+ struct stat st;+ if (stat(kPath, &st) == 0 && st.st_size > kCap) {+ return;+ }+ FILE *file = fopen(kPath, "a");+ if (!file) {+ return;+ }+ struct timeval now;+ gettimeofday(&now, NULL);+ struct tm utc;+ gmtime_r(&now.tv_sec, &utc);+ va_list args;+ va_start(args, format);+ fprintf(file, "%02d:%02d:%02d.%03d ", utc.tm_hour, utc.tm_min, utc.tm_sec, now.tv_usec / 1000);+ vfprintf(file, format, args);+ fputc('\n', file);+ va_end(args);+ fclose(file);+}++static NSString *VPFourCC(UInt32 code) {+ char text[5] = {+ (char)(code >> 24), (char)(code >> 16), (char)(code >> 8), (char)code, 0,+ };+ return [NSString stringWithFormat:@"%s", text];+}++static void VPLogSelectorQuery(const char *operation, const AudioObjectPropertyAddress *address) {+ static NSMutableSet *seen;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ seen = [NSMutableSet set];+ });+ NSString *key = [NSString stringWithFormat:@"%s:%u:%u:%u",+ operation, address->mSelector, address->mScope, address->mElement];+ @synchronized(seen) {+ if ([seen containsObject:key]) {+ return;+ }+ [seen addObject:key];+ }+ os_log(VPLog(), "query %{public}s: '%{public}@' / '%{public}@' / %u",+ operation, VPFourCC(address->mSelector), VPFourCC(address->mScope), address->mElement);+ VPLogToFile("query %s: '%s' / '%s' / %u",+ operation, VPFourCC(address->mSelector).UTF8String,+ VPFourCC(address->mScope).UTF8String, address->mElement);+}++// MARK: - Settings++static UInt32 VPTransportType(void) {+ CFPropertyListRef value = CFPreferencesCopyAppValue(CFSTR("VPhoneVirtIOSoundTransportType"), kSettingsDomain);+ UInt32 transport = kAudioDeviceTransportTypeUSB;+ if (value && CFGetTypeID(value) == CFStringGetTypeID()) {+ char code[8] = {0};+ if (CFStringGetCString(value, code, sizeof(code), kCFStringEncodingASCII) && strlen(code) == 4) {+ transport = (UInt32)code[0] << 24 | (UInt32)code[1] << 16 | (UInt32)code[2] << 8 | (UInt32)code[3];+ }+ }+ if (value) {+ CFRelease(value);+ }+ return transport;+}++static NSString *VPDeviceUID(unsigned index) {+ NSString *uid = CFBridgingRelease(+ CFPreferencesCopyAppValue(CFSTR("VPhoneVirtIOSoundDeviceUID"), kSettingsDomain));+ if ([uid isKindOfClass:NSString.class] && uid.length > 0) {+ return index == 0 ? uid : [NSString stringWithFormat:@"%@:%u", uid, index];+ }+ return [NSString stringWithFormat:@"VPhoneVirtIOSound:%u", index];+}++/// The nominal rate the device boots with, for testing how VirtualAudio picks+/// aggregate members: a ringtone-preview vdef runs at 44100 and may require a+/// candidate's *current* nominal rate to match, not just advertised support.+/// 0 (or any unsupported value) leaves the wire rate as the nominal rate.+static double VPNominalRateOverride(void) {+ CFPropertyListRef value = CFPreferencesCopyAppValue(CFSTR("VPhoneVirtIOSoundNominalRate"), kSettingsDomain);+ double rate = 0;+ if (value && CFGetTypeID(value) == CFNumberGetTypeID()) {+ double number = 0;+ if (CFNumberGetValue(value, kCFNumberDoubleType, &number) && number > 0) {+ rate = number;+ }+ }+ if (value) {+ CFRelease(value);+ }+ return rate;+}++// MARK: - Clock++/// The free-running device clock. `performStartIO` anchors it; the I/O+/// thread reads it through `getZeroTimestampBlock`. The period math is+/// atomic because the nominal rate can move under it: the HAL runs the+/// device at 44100 for ringtone-preview aggregates and back at 48000 for+/// everything else, and the timeline must answer in the current rate's+/// frames (`VPClockSetRate`).+typedef struct {+ _Atomic uint64_t anchorHostTime;+ _Atomic uint64_t periodCount;+ _Atomic uint64_t seed;+ _Atomic uint64_t hostTicksPerPeriod;+ _Atomic uint32_t periodFrames;+} VPClock;++static void VPClockConfigure(VPClock *clock, double sampleRate) {+ uint32_t periodFrames = (UInt32)(sampleRate * kTimestampPeriodSeconds);+ mach_timebase_info_data_t timebase;+ mach_timebase_info(&timebase);+ double hostTicksPerSecond = 1e9 * timebase.denom / timebase.numer;+ double hostTicksPerPeriod = hostTicksPerSecond * periodFrames / sampleRate;+ uint64_t bits;+ memcpy(&bits, &hostTicksPerPeriod, sizeof(bits));+ atomic_init(&clock->anchorHostTime, mach_absolute_time());+ atomic_init(&clock->periodCount, 0);+ atomic_init(&clock->seed, 1);+ atomic_init(&clock->hostTicksPerPeriod, bits);+ atomic_init(&clock->periodFrames, periodFrames);+}++/// Re-derives the period math for a new nominal rate and re-anchors, so the+/// timeline restarts in the new rate's frames. Rate changes arrive while+/// I/O is stopped.+static void VPClockSetRate(VPClock *clock, double sampleRate) {+ uint32_t periodFrames = (UInt32)(sampleRate * kTimestampPeriodSeconds);+ mach_timebase_info_data_t timebase;+ mach_timebase_info(&timebase);+ double hostTicksPerSecond = 1e9 * timebase.denom / timebase.numer;+ double hostTicksPerPeriod = hostTicksPerSecond * periodFrames / sampleRate;+ uint64_t bits;+ memcpy(&bits, &hostTicksPerPeriod, sizeof(bits));+ atomic_store(&clock->periodFrames, periodFrames);+ atomic_store(&clock->hostTicksPerPeriod, bits);+ atomic_store(&clock->periodCount, 0);+ atomic_store(&clock->anchorHostTime, mach_absolute_time());+ atomic_fetch_add(&clock->seed, 1);+}++static void VPClockAnchor(VPClock *clock) {+ atomic_store(&clock->periodCount, 0);+ atomic_store(&clock->anchorHostTime, mach_absolute_time());+ atomic_fetch_add(&clock->seed, 1);+}++static void VPClockZeroTimestamp(VPClock *clock, Float64 *sampleTime, UInt64 *hostTime, UInt64 *seed) {+ uint64_t anchor = atomic_load(&clock->anchorHostTime);+ uint64_t count = atomic_load(&clock->periodCount);+ uint64_t ticksBits = atomic_load(&clock->hostTicksPerPeriod);+ uint32_t periodFrames = atomic_load(&clock->periodFrames);+ double hostTicksPerPeriod;+ memcpy(&hostTicksPerPeriod, &ticksBits, sizeof(hostTicksPerPeriod));+ uint64_t now = mach_absolute_time();+ if (now > anchor && (double)(now - anchor) >= (count + 1) * hostTicksPerPeriod) {+ count = (uint64_t)((now - anchor) / hostTicksPerPeriod);+ atomic_store(&clock->periodCount, count);+ // The HAL drops an advancing timestamp whose seed did not move: a+ // constant seed reads as a frozen clock, and the IO context waits the+ // full five seconds and then fails the start with 'nope'. The seed+ // changes whenever the reported pair does.+ atomic_fetch_add(&clock->seed, 1);+ }+ *sampleTime = (Float64)count * periodFrames;+ *hostTime = anchor + (UInt64)(count * hostTicksPerPeriod);+ *seed = atomic_load(&clock->seed);+}++// MARK: - Resampler++/// Linear-rate conversion of the HAL mix into the virtio wire rate. The+/// virtio stream always runs SET_PARAMS at 48000, but a ringtone-preview+/// aggregate runs the device at 44100; `writeMixBlock` then hands over+/// 44100-frame blocks that must become 48000 frames in the ring. Plain+/// linear interpolation is enough — a preview tone has no content near+/// Nyquist worth protecting.+typedef struct {+ /// The last input frame, the interpolation partner of the next block's+ /// first frame.+ float lastFrame[2];+ /// Where the next output frame falls between the previous and the+ /// current input frame, in input frames.+ double phase;+} VPResampler;++static void VPResamplerReset(VPResampler *resampler) {+ resampler->lastFrame[0] = 0;+ resampler->lastFrame[1] = 0;+ resampler->phase = 0;+}++/// Converts one interleaved stereo float block into `scratch`, returning the+/// output frame count. Outputs land `rateIn / rateOut` input frames apart,+/// so each input frame emits one or two.+static uint32_t VPResamplerProcess(VPResampler *resampler, const float *input, uint32_t inputFrames,+ double rateIn, double rateOut, float *scratch, uint32_t scratchFrames) {+ const double step = rateIn / rateOut;+ uint32_t outputFrames = 0;+ for (uint32_t i = 0; i < inputFrames; i++) {+ const float *current = input + i * 2;+ while (resampler->phase < 1.0 && outputFrames < scratchFrames) {+ float *output = scratch + outputFrames * 2;+ output[0] = resampler->lastFrame[0] + (current[0] - resampler->lastFrame[0]) * (float)resampler->phase;+ output[1] = resampler->lastFrame[1] + (current[1] - resampler->lastFrame[1]) * (float)resampler->phase;+ outputFrames++;+ resampler->phase += step;+ }+ resampler->phase -= 1.0;+ resampler->lastFrame[0] = current[0];+ resampler->lastFrame[1] = current[1];+ }+ return outputFrames;+}++/// Input frames per resampler pass; 512 in at 44100→48000 produces at most+/// 559 out, so a 1024-frame scratch bounds the allocation.+static const uint32_t kResampleChunkFrames = 512;+static const uint32_t kResampleScratchFrames = 1024;++/// What `writeMixBlock` captures instead of the stream object: the I/O+/// thread must not touch Objective-C, so it gets plain pointers that live as+/// long as the device.+typedef struct {+ VPVirtIOSoundRing *ring;+ _Atomic uint32_t *halRate;+ VPResampler *resampler;+ float *scratch;+ uint32_t bytesPerFrame;+ uint32_t wireRate;+} VPMixState;++static int VPMixWrite(VPMixState *mix, void *buffer, UInt32 frameCount) {+ uint32_t halRate = atomic_load(mix->halRate);+ if (halRate == mix->wireRate) {+ VPVirtIOSoundRingWrite(mix->ring, buffer, frameCount * mix->bytesPerFrame);+ return kAudioHardwareNoError;+ }+ uint32_t done = 0;+ while (done < frameCount) {+ uint32_t chunk = frameCount - done;+ if (chunk > kResampleChunkFrames) {+ chunk = kResampleChunkFrames;+ }+ uint32_t converted = VPResamplerProcess(mix->resampler,+ (const float *)((uint8_t *)buffer + done * mix->bytesPerFrame), chunk,+ halRate, mix->wireRate, mix->scratch, kResampleScratchFrames);+ VPVirtIOSoundRingWrite(mix->ring, mix->scratch, converted * mix->bytesPerFrame);+ done += chunk;+ }+ return kAudioHardwareNoError;+}++// MARK: - Stream++typedef NS_ENUM(NSInteger, VPStreamState) {+ /// The virtio stream is released; SET_PARAMS comes first.+ VPStreamStateIdle,+ /// Started on the device, and CoreAudio is writing.+ VPStreamStateRunning,+ /// CoreAudio stopped; the device stops once what it holds comes back.+ VPStreamStateDraining,+};++@interface VPVirtIOSoundStream : ASDStream+- (instancetype)initWithConnection:(io_connect_t)connection+ streamID:(uint32_t)streamID+ format:(VPVirtIOSoundStreamFormat)format+ plugin:(ASDPlugin *)plugin;+- (void)transferCompletedWithLength:(uint32_t)length result:(IOReturn)result;+@end++/// The refcon of one async write.+typedef struct {+ void *stream;+ uint32_t length;+} VPTransfer;++static void VPWriteCompleted(void *refcon, IOReturn result, void **arguments, UInt32 argumentCount) {+ (void)arguments;+ (void)argumentCount;+ VPTransfer *transfer = refcon;+ VPVirtIOSoundStream *stream = (__bridge VPVirtIOSoundStream *)transfer->stream;+ uint32_t length = transfer->length;+ free(transfer);+ [stream transferCompletedWithLength:length result:result];+}++@implementation VPVirtIOSoundStream {+ io_connect_t _connection;+ uint32_t _streamID;+ VPVirtIOSoundStreamFormat _format;+ uint32_t _periodBytes;+ uint32_t _bufferBytes;+ VPVirtIOSoundRing _ring;+ dispatch_queue_t _queue;+ IONotificationPortRef _port;+ dispatch_source_t _timer;+ VPStreamState _state;+ BOOL _reportedTransferError;+ /// The rate CoreAudio runs the stream at, which is the wire rate until a+ /// 44100 aggregate switches the device. The mix block reads it, the rate+ /// change writes it, both lock-free.+ _Atomic uint32_t _halRate;+ VPResampler _resampler;+ float *_resampleScratch;+}++- (instancetype)initWithConnection:(io_connect_t)connection+ streamID:(uint32_t)streamID+ format:(VPVirtIOSoundStreamFormat)format+ plugin:(ASDPlugin *)plugin {+ self = [super initWithDirection:ASDStreamDirectionOutput withPlugin:plugin];+ if (!self) {+ return nil;+ }+ _connection = connection;+ _streamID = streamID;+ _format = format;+ VPVirtIOSoundBufferSizes(&format, (uint32_t)getpagesize(), &_periodBytes, &_bufferBytes);+ if (!VPVirtIOSoundRingInit(&_ring, _bufferBytes, _periodBytes)) {+ os_log_error(VPLog(), "stream %u: cannot allocate a %u-byte ring", streamID, _bufferBytes);+ return nil;+ }+ _queue = dispatch_queue_create("com.vphone.audio.virtiosound.stream", DISPATCH_QUEUE_SERIAL);+ _port = IONotificationPortCreate(kIOMainPortDefault);+ if (!_port) {+ VPVirtIOSoundRingDestroy(&_ring);+ return nil;+ }+ IONotificationPortSetDispatchQueue(_port, _queue);+ _resampleScratch = malloc(kResampleScratchFrames * format.bytesPerFrame);+ if (!_resampleScratch) {+ IONotificationPortDestroy(_port);+ VPVirtIOSoundRingDestroy(&_ring);+ return nil;+ }++ AudioStreamBasicDescription description = {+ .mSampleRate = format.sampleRate,+ .mFormatID = kAudioFormatLinearPCM,+ .mFormatFlags = (format.isFloat ? kAudioFormatFlagIsFloat : kAudioFormatFlagIsSignedInteger)+ | kAudioFormatFlagIsPacked,+ .mBytesPerPacket = format.bytesPerFrame,+ .mFramesPerPacket = 1,+ .mBytesPerFrame = format.bytesPerFrame,+ .mChannelsPerFrame = format.channels,+ .mBitsPerChannel = format.bitsPerChannel,+ };+ ASDStreamFormat *physical = [[ASDStreamFormat alloc] initWithAudioStreamBasicDescription:description];+ physical.minimumSampleRate = format.sampleRate;+ physical.maximumSampleRate = format.sampleRate;+ self.streamName = @"Output Stream";+ self.physicalFormat = physical;+ self.physicalFormats = @[physical];+ double nominalRate = 0;+ // The 44100 twin: a ringtone-preview aggregate runs the vdef at 44100,+ // and the aggregate only carries devices that answer that rate. The+ // virtio stream itself stays at the wire rate; the mix resamples. The+ // current format follows the nominal-rate override so the device boots+ // already answering 44100, matching how the vdef composes.+ if (format.sampleRate == 48000.0) {+ AudioStreamBasicDescription alternate = description;+ alternate.mSampleRate = kVPAlternateRate;+ ASDStreamFormat *reduced = [[ASDStreamFormat alloc] initWithAudioStreamBasicDescription:alternate];+ reduced.minimumSampleRate = kVPAlternateRate;+ reduced.maximumSampleRate = kVPAlternateRate;+ self.physicalFormats = @[physical, reduced];+ self.physicalFormatSettable = YES;+ double override = VPNominalRateOverride();+ if (override == kVPAlternateRate) {+ nominalRate = override;+ self.physicalFormat = reduced;+ }+ }++ atomic_init(&_halRate, nominalRate > 0 ? (uint32_t)nominalRate : (uint32_t)format.sampleRate);+ VPResamplerReset(&_resampler);+ // The I/O thread must not touch Objective-C or take locks, so the block+ // captures plain state. The stream lives as long as its device.+ VPMixState mix = {+ .ring = &_ring,+ .halRate = &_halRate,+ .resampler = &_resampler,+ .scratch = _resampleScratch,+ .bytesPerFrame = format.bytesPerFrame,+ .wireRate = (uint32_t)format.sampleRate,+ };+ self.writeMixBlock = ^int(UInt32 frameCount, const AudioServerPlugInIOCycleInfo *cycleInfo,+ void *mainBuffer, void *secondaryBuffer, UInt32 clientID) {+ (void)cycleInfo;+ (void)secondaryBuffer;+ (void)clientID;+ return VPMixWrite((VPMixState *)&mix, mainBuffer, frameCount);+ };+ os_log(VPLog(), "stream %u: %.0f Hz, %u channels, %u-bit %{public}s, period %u bytes",+ streamID, format.sampleRate, format.channels, format.bitsPerChannel,+ format.isFloat ? "float" : "integer", _periodBytes);+ VPLogToFile("stream %u: %.0f Hz, %u channels, %u-bit %s, period %u bytes",+ streamID, format.sampleRate, format.channels, format.bitsPerChannel,+ format.isFloat ? "float" : "integer", _periodBytes);+ return self;+}++- (void)dealloc {+ if (_timer) {+ dispatch_source_cancel(_timer);+ }+ if (_port) {+ IONotificationPortDestroy(_port);+ }+ free(_resampleScratch);+ VPVirtIOSoundRingDestroy(&_ring);+}++// MARK: Rate changes++- (void)deviceChangedToSamplingRate:(double)rate {+ os_log(VPLog(), "rate-probe: stream %u deviceChangedToSamplingRate %.0f (hal %.0f, format %.0f)",+ _streamID, rate, (double)atomic_load(&_halRate), self.physicalFormat.sampleRate);+ VPLogToFile("rate-probe: stream %u deviceChangedToSamplingRate %.0f (hal %.0f, format %.0f)",+ _streamID, rate, (double)atomic_load(&_halRate), self.physicalFormat.sampleRate);+ [super deviceChangedToSamplingRate:rate];+ uint32_t previous = atomic_load(&_halRate);+ if (rate > 0 && (uint32_t)rate != previous) {+ atomic_store(&_halRate, (uint32_t)rate);+ VPResamplerReset(&_resampler);+ os_log(VPLog(), "stream %u: device rate %.0f -> %.0f, physical format %.0f Hz",+ _streamID, (double)previous, rate, self.physicalFormat.sampleRate);+ }+}++// MARK: Property inventory++// The same five entry points as the device's below, logging what the stream+// object itself is asked (its physical formats and layouts mostly) before+// ASDStream answers.++- (BOOL)hasProperty:(AudioObjectPropertyAddress *)address {+ VPLogSelectorQuery("stream-has", address);+ return [super hasProperty:address];+}++- (BOOL)isPropertySettable:(AudioObjectPropertyAddress *)address {+ VPLogSelectorQuery("stream-settable", address);+ return [super isPropertySettable:address];+}++- (UInt32)dataSizeForProperty:(AudioObjectPropertyAddress *)address+ withQualifierSize:(UInt32)qualifierSize+ andQualifierData:(const void *)qualifierData {+ VPLogSelectorQuery("stream-size", address);+ return [super dataSizeForProperty:address withQualifierSize:qualifierSize+ andQualifierData:qualifierData];+}++- (BOOL)getProperty:(AudioObjectPropertyAddress *)address+ withQualifierSize:(UInt32)qualifierSize+ qualifierData:(const void *)qualifierData+ dataSize:(UInt32 *)dataSize+ andData:(void *)data+ forClient:(UInt32)clientID {+ VPLogSelectorQuery("stream-get", address);+ return [super getProperty:address withQualifierSize:qualifierSize+ qualifierData:qualifierData dataSize:dataSize+ andData:data forClient:clientID];+}++- (BOOL)setProperty:(AudioObjectPropertyAddress *)address+ withQualifierSize:(UInt32)qualifierSize+ qualifierData:(const void *)qualifierData+ dataSize:(UInt32)dataSize+ andData:(const void *)data+ forClient:(UInt32)clientID {+ VPLogSelectorQuery("stream-set", address);+ return [super setProperty:address withQualifierSize:qualifierSize+ qualifierData:qualifierData dataSize:dataSize+ andData:data forClient:clientID];+}++// MARK: Device commands++- (kern_return_t)callSelector:(uint32_t)selector {+ uint64_t scalar = _streamID;+ kern_return_t result = IOConnectCallScalarMethod(_connection, selector, &scalar, 1, NULL, NULL);+ if (result != KERN_SUCCESS) {+ os_log_error(VPLog(), "stream %u: selector %u failed: 0x%x", _streamID, selector, result);+ }+ return result;+}++- (BOOL)startDevice {+ dispatch_assert_queue(_queue);+ VPVirtIOSoundRingReset(&_ring);+ VPVirtIOSoundPCMParameters parameters = VPVirtIOSoundParameters(&_format, _periodBytes, _bufferBytes);+ uint64_t scalar = _streamID;+ kern_return_t result = IOConnectCallMethod(_connection, kVPVirtIOSoundSelectorSetParameters,+ &scalar, 1, ¶meters, sizeof(parameters), NULL, NULL, NULL, NULL);+ if (result != KERN_SUCCESS) {+ os_log_error(VPLog(), "stream %u: SET_PARAMS failed: 0x%x", _streamID, result);+ return NO;+ }+ if ([self callSelector:kVPVirtIOSoundSelectorPrepare] != KERN_SUCCESS) {+ [self callSelector:kVPVirtIOSoundSelectorRelease];+ return NO;+ }+ if ([self callSelector:kVPVirtIOSoundSelectorStart] != KERN_SUCCESS) {+ [self callSelector:kVPVirtIOSoundSelectorRelease];+ return NO;+ }+ _reportedTransferError = NO;+ return YES;+}++- (void)stopDevice {+ dispatch_assert_queue(_queue);+ [self callSelector:kVPVirtIOSoundSelectorStop];+ [self callSelector:kVPVirtIOSoundSelectorRelease];+ _state = VPStreamStateIdle;+}++// MARK: Transfers++- (void)submitPending:(BOOL)partial {+ dispatch_assert_queue(_queue);+ mach_port_t wakePort = IONotificationPortGetMachPort(_port);+ uint32_t offset = 0;+ uint32_t length = 0;+ while (VPVirtIOSoundRingNextSubmission(&_ring, partial, &offset, &length)) {+ VPTransfer *transfer = malloc(sizeof(*transfer));+ if (!transfer) {+ return;+ }+ transfer->stream = (__bridge void *)self;+ transfer->length = length;+ uint64_t reference[kOSAsyncRef64Count] = {0};+ reference[kIOAsyncCalloutFuncIndex] = (uint64_t)(uintptr_t)VPWriteCompleted;+ reference[kIOAsyncCalloutRefconIndex] = (uint64_t)(uintptr_t)transfer;+ uint64_t scalar = _streamID;+ VPVirtIOSoundRingDidSubmit(&_ring, length);+ kern_return_t result = IOConnectCallAsyncMethod(_connection, kVPVirtIOSoundSelectorWrite, wakePort,+ reference, kAsyncReferenceCount, &scalar, 1, _ring.bytes + offset, length, NULL, NULL, NULL, NULL);+ if (result != KERN_SUCCESS) {+ // Nothing will complete this one, so return its space now.+ free(transfer);+ [self transferCompletedWithLength:length result:result];+ }+ }+}++- (void)transferCompletedWithLength:(uint32_t)length result:(IOReturn)result {+ dispatch_assert_queue(_queue);+ VPVirtIOSoundRingDidComplete(&_ring, length);+ if (result != kIOReturnSuccess && !_reportedTransferError) {+ _reportedTransferError = YES;+ os_log_error(VPLog(), "stream %u: write of %u bytes failed: 0x%x", _streamID, length, result);+ }+ if (_state == VPStreamStateDraining && VPVirtIOSoundRingInFlight(&_ring) == 0) {+ [self stopDevice];+ }+}++// MARK: ASDStream++- (void)startStream {+ dispatch_sync(_queue, ^{+ if (self->_state == VPStreamStateIdle && ![self startDevice]) {+ return;+ }+ self->_state = VPStreamStateRunning;+ });+ if (!_timer) {+ _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _queue);+ dispatch_source_set_timer(_timer, dispatch_time(DISPATCH_TIME_NOW, kFlushIntervalNanoseconds),+ kFlushIntervalNanoseconds, kFlushIntervalNanoseconds / 10);+ __unsafe_unretained VPVirtIOSoundStream *unretained = self;+ dispatch_source_set_event_handler(_timer, ^{+ if (unretained->_state == VPStreamStateRunning) {+ [unretained submitPending:NO];+ }+ });+ dispatch_resume(_timer);+ }+ [super startStream];+}++- (void)stopStream {+ dispatch_sync(_queue, ^{+ if (self->_state != VPStreamStateRunning) {+ return;+ }+ [self submitPending:YES];+ self->_state = VPStreamStateDraining;+ if (VPVirtIOSoundRingInFlight(&self->_ring) == 0) {+ [self stopDevice];+ }+ });+ [super stopStream];+}++@end++// MARK: - Device++@interface VPVirtIOSoundDevice : ASDAudioDevice+- (instancetype)initWithService:(io_service_t)service index:(unsigned)index plugin:(ASDPlugin *)plugin;+- (void)addSpeakerControls;+@end++@implementation VPVirtIOSoundDevice {+ io_service_t _service;+ io_connect_t _connection;+ VPClock _clock;+ /// The virtio wire rate, the only rate the device actually runs at.+ double _wireRate;+ /// The second advertised rate, or 0 when the wire rate leaves nothing to+ /// convert (44100 beside 48000).+ double _alternateRate;+ /// The nominal rate the clock last ran, so a re-set of the current rate+ /// does not re-anchor it.+ double _clockRate;+ /// The mute control `addSpeakerControls` registered, for the device-level+ /// mute selector's forwarding below.+ ASDBooleanControl *_muteControl;+ /// The mute state the device-level selector answers; shadowed beside the+ /// control because the control's own value is only reachable through its+ /// 'bcvl' property, whose getter shape the guest ASD does not publish.+ UInt32 _muteState;+}++static uint32_t VPStreamCount(io_service_t service) {+ CFTypeRef value = IORegistryEntryCreateCFProperty(+ service, CFSTR(kVPVirtIOSoundStreamCountKey), kCFAllocatorDefault, 0);+ uint32_t count = 0;+ if (value && CFGetTypeID(value) == CFNumberGetTypeID()) {+ CFNumberGetValue(value, kCFNumberSInt32Type, &count);+ }+ if (value) {+ CFRelease(value);+ }+ return count;+}++- (instancetype)initWithService:(io_service_t)service index:(unsigned)index plugin:(ASDPlugin *)plugin {+ io_connect_t connection = IO_OBJECT_NULL;+ kern_return_t result = IOServiceOpen(service, mach_task_self(), 0, &connection);+ if (result != KERN_SUCCESS) {+ os_log_error(VPLog(), "cannot open AppleVirtIOSound: 0x%x", result);+ return nil;+ }+ self = [super initWithDeviceUID:VPDeviceUID(index) withPlugin:plugin];+ if (!self) {+ IOServiceClose(connection);+ return nil;+ }+ IOObjectRetain(service);+ _service = service;+ _connection = connection;++ double sampleRate = 0;+ uint32_t count = VPStreamCount(service);+ for (uint32_t streamID = 0; streamID < count; streamID++) {+ VPVirtIOSoundPCMInfo info = {0};+ uint64_t scalar = streamID;+ size_t size = sizeof(info);+ result = IOConnectCallMethod(connection, kVPVirtIOSoundSelectorPCMInfo,+ &scalar, 1, NULL, 0, NULL, NULL, &info, &size);+ if (result != KERN_SUCCESS || size != sizeof(info)) {+ os_log_error(VPLog(), "stream %u: PCM_INFO failed: 0x%x", streamID, result);+ continue;+ }+ if (info.direction != kVPVirtIOSoundDirectionOutput) {+ continue;+ }+ VPVirtIOSoundStreamFormat format;+ if (!VPVirtIOSoundChooseFormat(&info, &format)) {+ os_log_error(VPLog(), "stream %u: no usable format (formats 0x%llx, rates 0x%llx)",+ streamID, info.formats, info.rates);+ continue;+ }+ // One device has one clock, so every stream must share its rate.+ if (sampleRate != 0 && format.sampleRate != sampleRate) {+ continue;+ }+ VPVirtIOSoundStream *stream = [[VPVirtIOSoundStream alloc] initWithConnection:connection+ streamID:streamID+ format:format+ plugin:plugin];+ if (!stream) {+ continue;+ }+ sampleRate = format.sampleRate;+ [self addOutputStream:stream];+ }+ if (sampleRate == 0) {+ os_log_error(VPLog(), "AppleVirtIOSound has no usable output stream among %u", count);+ return nil;+ }++ _wireRate = sampleRate;+ _alternateRate = sampleRate == 48000.0 ? kVPAlternateRate : 0;+ // The nominal rate the device answers at boot: the wire rate unless the+ // override names the alternate (testing VirtualAudio's aggregate-member+ // selection, which may compare the current nominal rate, not the list).+ double nominalRate = sampleRate;+ double override = VPNominalRateOverride();+ if (_alternateRate > 0 && override == _alternateRate) {+ nominalRate = _alternateRate;+ }+ UInt32 periodFrames = (UInt32)(nominalRate * kTimestampPeriodSeconds);+ VPClockConfigure(&_clock, nominalRate);+ _clockRate = nominalRate;+ self.deviceName = @"vphone Speaker";+ self.modelName = @"Virtual Sound Device";+ self.manufacturerName = @"vphone";+ self.canBeDefaultOutputDevice = YES;+ self.canBeDefaultSystemDevice = YES;+ self.canBeDefaultInputDevice = NO;+ self.canChangeDeviceName = NO;+ self.samplingRates = _alternateRate ? @[@(_alternateRate), @(sampleRate)] : @[@(sampleRate)];+ self.samplingRate = nominalRate;+ self.outputSafetyOffset = kSafetyOffsetFrames;+ self.transportType = VPTransportType();+ self.timestampPeriod = periodFrames;++ VPClock *clock = &_clock;+ self.getZeroTimestampBlock = ^int(Float64 *sampleTime, UInt64 *hostTime, UInt64 *seed, UInt32 clientID) {+ (void)clientID;+ VPClockZeroTimestamp(clock, sampleTime, hostTime, seed);+ return kAudioHardwareNoError;+ };+ self.willDoReadInputBlock = ^int(UInt32 operationID, Boolean *willDo, Boolean *willDoInPlace) {+ (void)operationID;+ *willDo = false;+ *willDoInPlace = true;+ return kAudioHardwareNoError;+ };+ self.willDoWriteMixBlock = ^int(UInt32 operationID, Boolean *willDo, Boolean *willDoInPlace) {+ (void)operationID;+ *willDo = true;+ *willDoInPlace = true;+ return kAudioHardwareNoError;+ };+ UInt32 transport = self.transportType;+ os_log(VPLog(), "device %{public}@: %.0f Hz nominal (%.0f wire, %.0f advertised too), transport '%c%c%c%c'",+ VPDeviceUID(index), nominalRate, sampleRate, _alternateRate,+ (char)(transport >> 24), (char)(transport >> 16), (char)(transport >> 8), (char)transport);+ VPLogToFile("device %s: %.0f Hz nominal (%.0f wire, %.0f advertised too), transport '%c%c%c%c'",+ VPDeviceUID(index).UTF8String, nominalRate, sampleRate, _alternateRate,+ (char)(transport >> 24), (char)(transport >> 16), (char)(transport >> 8), (char)transport);+ return self;+}++- (void)dealloc {+ if (_connection) {+ IOServiceClose(_connection);+ }+ if (_service) {+ IOObjectRelease(_service);+ }+}++- (int)performStartIO {+ int result = [super performStartIO];+ if (result == kAudioHardwareNoError) {+ VPClockAnchor(&_clock);+ }+ return result;+}++// MARK: Rate changes++- (BOOL)supportsSamplingRate:(double)rate {+ BOOL supported = rate == _wireRate || (_alternateRate > 0 && rate == _alternateRate);+ os_log(VPLog(), "rate-probe: supportsSamplingRate %.0f -> %{public}s",+ rate, supported ? "yes" : "no");+ VPLogToFile("rate-probe: supportsSamplingRate %.0f -> %s", rate, supported ? "yes" : "no");+ return supported;+}++/// The virtio stream keeps SET_PARAMS at the wire rate whatever the HAL+/// runs; only the clock's period math and the mix's input rate follow the+/// nominal rate, and the streams hear about it from `super` before the+/// clock moves.+- (void)setSamplingRate:(double)rate {+ os_log(VPLog(), "rate-probe: setSamplingRate %.0f (clock %.0f)", rate, _clockRate);+ VPLogToFile("rate-probe: setSamplingRate %.0f (clock %.0f)", rate, _clockRate);+ [super setSamplingRate:rate];+ if (rate > 0 && [self supportsSamplingRate:rate] && rate != _clockRate) {+ _clockRate = rate;+ VPClockSetRate(&_clock, rate);+ self.timestampPeriod = (UInt32)(rate * kTimestampPeriodSeconds);+ os_log(VPLog(), "nominal rate -> %.0f Hz", rate);+ }+}++// MARK: Device-level properties++/// VirtualAudio's route code asks the device itself for+/// `kAudioDevicePropertyMute` (scope 'outp', element 0) while establishing+/// the pspk route — Device_HAL_Common's unmute, then a read-back. The iOS+/// ASDAudioDevice's property dispatch has no 'mute' case at all (the+/// disassembly of the guest's AudioServerDriver contains the FourCharCode in+/// exactly two places, both inside ASDBooleanControl's control-level code,+/// none in ASDAudioDevice's selector trees), and the HAL server answers the+/// set 'what' at HALS_UCPlugIn.cpp:1190 without ever forwarding the selector+/// here — a guest probe saw these overrides dispatch for every selector but+/// 'mute'. The route's throw that follows is quieted host-side, in the+/// VirtualAudio binary patch; this dispatch stays as macOS's ASD carries it,+/// with the mute control this device registered as the backing store, for+/// the build that does forward.+static BOOL VPIsDeviceMuteAddress(const AudioObjectPropertyAddress *address) {+ return address->mSelector == kVPDevicePropertyMute+ && (address->mScope == kAudioObjectPropertyScopeOutput+ || address->mScope == kAudioObjectPropertyScopeGlobal)+ && (address->mElement == kAudioObjectPropertyElementMain+ || address->mElement == 0);+}++/// `kAudioDevicePropertyNominalSampleRate` is a global-scope, main-element+/// property ('nsrt'/glob/0). A device-level mute address check accepts the+/// output scope as well; the rate has no per-scope form, so global only.+static BOOL VPIsDeviceRateAddress(const AudioObjectPropertyAddress *address) {+ return address->mSelector == kVPDevicePropertyNominalSampleRate+ && address->mScope == kAudioObjectPropertyScopeGlobal+ && (address->mElement == kAudioObjectPropertyElementMain+ || address->mElement == 0);+}++- (BOOL)hasProperty:(AudioObjectPropertyAddress *)address {+ VPLogSelectorQuery("has", address);+ if (VPIsDeviceMuteAddress(address)) {+ return YES;+ }+ return [super hasProperty:address];+}++- (BOOL)isPropertySettable:(AudioObjectPropertyAddress *)address {+ VPLogSelectorQuery("settable", address);+ if (VPIsDeviceMuteAddress(address) || VPIsDeviceRateAddress(address)) {+ return YES;+ }+ return [super isPropertySettable:address];+}++- (UInt32)dataSizeForProperty:(AudioObjectPropertyAddress *)address+ withQualifierSize:(UInt32)qualifierSize+ andQualifierData:(const void *)qualifierData {+ VPLogSelectorQuery("size", address);+ if (VPIsDeviceMuteAddress(address)) {+ return sizeof(UInt32);+ }+ return [super dataSizeForProperty:address withQualifierSize:qualifierSize+ andQualifierData:qualifierData];+}++- (BOOL)getProperty:(AudioObjectPropertyAddress *)address+ withQualifierSize:(UInt32)qualifierSize+ qualifierData:(const void *)qualifierData+ dataSize:(UInt32 *)dataSize+ andData:(void *)data+ forClient:(UInt32)clientID {+ VPLogSelectorQuery("get", address);+ if (VPIsDeviceMuteAddress(address)) {+ if (dataSize == NULL || *dataSize < sizeof(UInt32)) {+ return NO;+ }+ *(UInt32 *)data = _muteState;+ *dataSize = sizeof(UInt32);+ return YES;+ }+ if (VPIsDeviceRateAddress(address)) {+ if (dataSize == NULL || *dataSize < sizeof(double) || data == NULL) {+ return NO;+ }+ *(double *)data = _clockRate;+ *dataSize = sizeof(double);+ return YES;+ }+ return [super getProperty:address withQualifierSize:qualifierSize+ qualifierData:qualifierData dataSize:dataSize+ andData:data forClient:clientID];+}++/// The rate set the route code's "Synchronously setting sample rate" runs+/// into. ASDAudioDevice's own `setProperty:` 'nsrt' case checks+/// `supportsSamplingRate:` (that call reaches the plugin — the rate-probe+/// log shows it answering) and then hands the change to a second internal+/// gate whose tail call returns NO for a plugin device; the C-op layer maps+/// that NO to 'what' at HALS_UCPlugIn.cpp:1190, the set "Gives up", and a+/// 44100 session finds no device at its rate ("No audio device is+/// available"). The commit the gate would perform lives in+/// `setSamplingRate:` — disassembled, that method logs, then dispatches a+/// block that stores the rate and fans it out to every stream — so the+/// device performs the change itself here, through its own override, and+/// answers YES.+- (BOOL)setProperty:(AudioObjectPropertyAddress *)address+ withQualifierSize:(UInt32)qualifierSize+ qualifierData:(const void *)qualifierData+ dataSize:(UInt32)dataSize+ andData:(const void *)data+ forClient:(UInt32)clientID {+ VPLogSelectorQuery("set", address);+ if (VPIsDeviceMuteAddress(address)) {+ if (dataSize < sizeof(UInt32) || data == NULL) {+ return NO;+ }+ _muteState = (*(const UInt32 *)data != 0);+ [_muteControl setValue:_muteState];+ return YES;+ }+ if (VPIsDeviceRateAddress(address)) {+ if (dataSize < sizeof(double) || data == NULL) {+ return NO;+ }+ double rate = *(const double *)data;+ if (rate <= 0 || ![self supportsSamplingRate:rate]) {+ return NO;+ }+ [self setSamplingRate:rate];+ return YES;+ }+ return [super setProperty:address withQualifierSize:qualifierSize+ qualifierData:qualifierData dataSize:dataSize+ andData:data forClient:clientID];+}++// MARK: Controls++- (void)addSpeakerControls {+ // The control set a real speaker answers with: one selected data-source+ // value ('ispk', "Speakers"), then mute and volume, all on the master+ // element of the output scope. Mirrored argument for argument from the+ // macOS plugin, which adds these from its own+ // `halInitializeWithPluginHost:` — after the device is built, before it+ // is registered — and never from inside the device's init: calling+ // `addControl:` during `initWithService:` fails the whole device+ // activation (HALS_PlugIn.cpp:162). The pspk route runs in HardwareOnly+ // volume mode and reads this control set; without it every volume query+ // on the route fails and the endpoint is retyped "Unspecified" after+ // the first playback, silencing every later one.+ ASDSelectorValue *speakers = [[ASDSelectorValue alloc] init];+ [speakers setValue:kVPDataSourceInternalSpeaker];+ [speakers setName:@"Speakers"];+ ASDSelectorControl *dataSource = [[ASDSelectorControl alloc]+ initWithIsSettable:YES+ forElement:0+ inScope:ASDStreamDirectionOutput+ withPlugin:self.plugin+ andObjectClassID:kAudioDataSourceControlClassID];+ [dataSource addValue:speakers];+ [dataSource setSelectedValues:@[speakers]];+ [self addControl:dataSource];++ // The macOS plugin's `-[AVIODevice _addMuteAndVolumeControlsInScope:]`+ // argument-for-argument: mute off, volume at -30 dB in a [-60, 0] dB+ // range pushed to its maximum, both settable. But not through its+ // factories: on the guest ASD those are state-dependent — runs where+ // they returned real controls still failed VirtualAudio's route unmute+ // with 'what' (a factory mute control does not answer+ // kAudioDevicePropertyMute), and later runs crashed audiomxd outright+ // when the volume factory's return value was the raw FourCharCode+ // 'togl', release-faulted in this function's epilogue (audiomxd-*.ips;+ // successive-crash loops in launchd). The explicit-class initializers+ // construct controls deterministically — a guest-side reflection probe+ // confirmed both initializers return real ASD controls — so pin the+ // class IDs the way the data-source control above pins 'dsrc'.+ ASDPlugin *plugin = self.plugin;+ ASDBooleanControl *mute = [[ASDBooleanControl alloc] initWithValue:NO+ isSettable:YES forElement:0 inScope:ASDStreamDirectionOutput+ withPlugin:plugin andObjectClassID:kAudioMuteControlClassID];+ ASDLevelControl *volume = [[ASDLevelControl alloc] initWithDecibelValue:-30.0+ minimumValue:-60.0 maximumValue:0.0 isSettable:YES+ forElement:0 inScope:ASDStreamDirectionOutput+ withPlugin:plugin andObjectClassID:kAudioVolumeControlClassID];+ [self addControl:mute];+ [self addControl:volume];+ [mute setValue:0];+ [volume setDecibelValue:volume.maximumDecibelValue];+ _muteControl = mute;+ _muteState = 0;+ os_log(VPLog(), "speaker controls added: dsrc 'ispk', mute, volume");+ VPLogToFile("speaker controls added: dsrc 'ispk', mute, volume");+}++@end++// MARK: - Plugin++@interface VPVirtIOSoundPlugin : ASDPlugin+@end++@implementation VPVirtIOSoundPlugin++// The plugin object (not a device) answers its own selectors — the box-level+// queries the HAL server makes while enumerating plugins. Logged the same way+// so the inventory covers every object this bundle publishes.++- (BOOL)hasProperty:(AudioObjectPropertyAddress *)address {+ VPLogSelectorQuery("plugin-has", address);+ return [super hasProperty:address];+}++- (BOOL)isPropertySettable:(AudioObjectPropertyAddress *)address {+ VPLogSelectorQuery("plugin-settable", address);+ return [super isPropertySettable:address];+}++- (UInt32)dataSizeForProperty:(AudioObjectPropertyAddress *)address+ withQualifierSize:(UInt32)qualifierSize+ andQualifierData:(const void *)qualifierData {+ VPLogSelectorQuery("plugin-size", address);+ return [super dataSizeForProperty:address withQualifierSize:qualifierSize+ andQualifierData:qualifierData];+}++- (BOOL)getProperty:(AudioObjectPropertyAddress *)address+ withQualifierSize:(UInt32)qualifierSize+ qualifierData:(const void *)qualifierData+ dataSize:(UInt32 *)dataSize+ andData:(void *)data+ forClient:(UInt32)clientID {+ VPLogSelectorQuery("plugin-get", address);+ return [super getProperty:address withQualifierSize:qualifierSize+ qualifierData:qualifierData dataSize:dataSize+ andData:data forClient:clientID];+}++- (BOOL)setProperty:(AudioObjectPropertyAddress *)address+ withQualifierSize:(UInt32)qualifierSize+ qualifierData:(const void *)qualifierData+ dataSize:(UInt32)dataSize+ andData:(const void *)data+ forClient:(UInt32)clientID {+ VPLogSelectorQuery("plugin-set", address);+ return [super setProperty:address withQualifierSize:qualifierSize+ qualifierData:qualifierData dataSize:dataSize+ andData:data forClient:clientID];+}++- (void)halInitializeWithPluginHost:(AudioServerPlugInHostRef)host {+ [super halInitializeWithPluginHost:host];+ io_iterator_t services = IO_OBJECT_NULL;+ kern_return_t result = IOServiceGetMatchingServices(+ kIOMainPortDefault, IOServiceMatching("AppleVirtIOSound"), &services);+ if (result != KERN_SUCCESS) {+ os_log_error(VPLog(), "no AppleVirtIOSound service: 0x%x", result);+ return;+ }+ unsigned index = 0;+ io_service_t service;+ while ((service = IOIteratorNext(services))) {+ VPVirtIOSoundDevice *device = [[VPVirtIOSoundDevice alloc] initWithService:service index:index plugin:self];+ IOObjectRelease(service);+ if (device) {+ [device addSpeakerControls];+ [self addAudioDevice:device];+ index++;+ }+ }+ IOObjectRelease(services);+ VPLogToFile("=== plugin load ===");+ os_log(VPLog(), "published %u virtio sound device(s)", index);+ VPLogToFile("published %u virtio sound device(s)", index);+}++@end++// MARK: - Factory++__attribute__((visibility("default")))+void *VPVirtIOSoundFactory(CFAllocatorRef allocator, CFUUIDRef requestedType);++void *VPVirtIOSoundFactory(CFAllocatorRef allocator, CFUUIDRef requestedType) {+ (void)allocator;+ if (!CFEqual(requestedType, kAudioServerPlugInTypeUUID)) {+ return NULL;+ }+ static VPVirtIOSoundPlugin *plugin;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ plugin = [[VPVirtIOSoundPlugin alloc] init];+ });+ return plugin.driverRef;+}diff --git a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundProtocol.c b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundProtocol.cnew file mode 100644index 00000000..5fde7659--- /dev/null+++ b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundProtocol.c@@ -0,0 +1,96 @@+// VPVirtIOSoundProtocol.c — format choice and SET_PARAMS sizing.++#include "VPVirtIOSoundProtocol.h"++#include <string.h>++// MARK: - Rates++// `VIRTIO_SND_PCM_RATE_*`, indexed by the bit the device sets in `rates`.+static const double kRates[] = {+ 5512, 8000, 11025, 16000, 22050, 32000, 44100,+ 48000, 64000, 88200, 96000, 176400, 192000, 384000,+};+static const uint8_t kRateCount = sizeof(kRates) / sizeof(kRates[0]);++double VPVirtIOSoundRateForIndex(uint8_t index) {+ return index < kRateCount ? kRates[index] : 0;+}++static bool chooseRate(uint64_t rates, uint8_t *index) {+ static const uint8_t preferred[] = {7, 6}; // 48 kHz, 44.1 kHz+ for (unsigned i = 0; i < sizeof(preferred); i++) {+ if (rates & (1ULL << preferred[i])) {+ *index = preferred[i];+ return true;+ }+ }+ for (int bit = kRateCount - 1; bit >= 0; bit--) {+ if (rates & (1ULL << bit)) {+ *index = (uint8_t)bit;+ return true;+ }+ }+ return false;+}++// MARK: - Format++bool VPVirtIOSoundChooseFormat(const VPVirtIOSoundPCMInfo *info, VPVirtIOSoundStreamFormat *format) {+ memset(format, 0, sizeof(*format));+ if (info->channelsMaximum == 0) {+ return false;+ }+ uint8_t rate = 0;+ if (!chooseRate(info->rates, &rate)) {+ return false;+ }+ if (info->formats & (1ULL << kVPVirtIOSoundFormatFloat)) {+ format->virtioFormat = kVPVirtIOSoundFormatFloat;+ format->bitsPerChannel = 32;+ format->isFloat = true;+ } else if (info->formats & (1ULL << kVPVirtIOSoundFormatS32)) {+ format->virtioFormat = kVPVirtIOSoundFormatS32;+ format->bitsPerChannel = 32;+ } else if (info->formats & (1ULL << kVPVirtIOSoundFormatS16)) {+ format->virtioFormat = kVPVirtIOSoundFormatS16;+ format->bitsPerChannel = 16;+ } else {+ return false;+ }+ format->virtioRate = rate;+ format->sampleRate = VPVirtIOSoundRateForIndex(rate);+ format->channels = info->channelsMaximum;+ format->bytesPerFrame = format->bitsPerChannel / 8 * format->channels;+ return true;+}++// MARK: - Sizes++enum { kPeriodsPerBuffer = 12 };++void VPVirtIOSoundBufferSizes(+ const VPVirtIOSoundStreamFormat *format,+ uint32_t pageSize,+ uint32_t *periodBytes,+ uint32_t *bufferBytes) {+ uint32_t perSecond = (uint32_t)format->sampleRate * format->bytesPerFrame;+ uint32_t period = perSecond / kPeriodsPerBuffer;+ period = (period + pageSize - 1) / pageSize * pageSize;+ *periodBytes = period;+ *bufferBytes = period * kPeriodsPerBuffer;+}++VPVirtIOSoundPCMParameters VPVirtIOSoundParameters(+ const VPVirtIOSoundStreamFormat *format,+ uint32_t periodBytes,+ uint32_t bufferBytes) {+ VPVirtIOSoundPCMParameters parameters;+ memset(¶meters, 0, sizeof(parameters));+ parameters.bufferBytes = bufferBytes;+ parameters.periodBytes = periodBytes;+ parameters.channels = (uint8_t)format->channels;+ parameters.format = format->virtioFormat;+ parameters.rate = format->virtioRate;+ return parameters;+}diff --git a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundProtocol.h b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundProtocol.hnew file mode 100644index 00000000..6ebe940d--- /dev/null+++ b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundProtocol.h@@ -0,0 +1,118 @@+// VPVirtIOSoundProtocol.h — the guest kernel's AppleVirtIOSoundUserClient.+//+// The cloudOS kernelcache matches `AppleVirtIOSound` to virtio device 0x19+// (virtio-snd) and publishes `AppleVirtIOSoundUserClient` for it, but no iOS+// userland ships the CoreAudio half that drives it: macOS has+// /System/Library/Audio/Plug-Ins/HAL/AppleVirtIOSound.driver, cloudOS and+// iOS have nothing. The selectors below were read out of that macOS plugin+// (Research/Guest/virtio_sound.md); each one forwards one virtio-snd request,+// so the structures are the virtio specification's own.+//+// Nothing here depends on CoreAudio, so the host test harness compiles it.++#ifndef VPVirtIOSoundProtocol_h+#define VPVirtIOSoundProtocol_h++#include <stdbool.h>+#include <stdint.h>++// MARK: - User-client selectors++enum {+ /// 1 scalar in (stream ID), `VPVirtIOSoundPCMInfo` out.+ kVPVirtIOSoundSelectorPCMInfo = 1,+ /// 1 scalar in (stream ID), `VPVirtIOSoundPCMParameters` in.+ kVPVirtIOSoundSelectorSetParameters = 3,+ /// 1 scalar in (stream ID) each.+ kVPVirtIOSoundSelectorPrepare = 4,+ kVPVirtIOSoundSelectorStart = 5,+ kVPVirtIOSoundSelectorStop = 6,+ kVPVirtIOSoundSelectorRelease = 7,+ /// Async. 1 scalar in (stream ID), the PCM bytes as the input structure.+ /// The kernel keeps the caller's pages until the completion arrives.+ kVPVirtIOSoundSelectorWrite = 8,+};++/// The IORegistry key on the `AppleVirtIOSound` service with the stream count.+#define kVPVirtIOSoundStreamCountKey "AVIOSoundStreamCountKey"++// MARK: - virtio-snd structures++/// `struct virtio_snd_pcm_info`.+typedef struct {+ uint32_t hdaFunctionNodeID;+ uint32_t features;+ uint64_t formats;+ uint64_t rates;+ uint8_t direction;+ uint8_t channelsMinimum;+ uint8_t channelsMaximum;+ uint8_t padding[5];+} VPVirtIOSoundPCMInfo;+_Static_assert(sizeof(VPVirtIOSoundPCMInfo) == 32, "virtio_snd_pcm_info is 32 bytes");++/// `struct virtio_snd_pcm_set_params`. The kernel fills the header (request+/// code and stream ID) from the scalar; the plugin leaves it zero.+typedef struct {+ uint32_t code;+ uint32_t streamID;+ uint32_t bufferBytes;+ uint32_t periodBytes;+ uint32_t features;+ uint8_t channels;+ uint8_t format;+ uint8_t rate;+ uint8_t padding;+} VPVirtIOSoundPCMParameters;+_Static_assert(sizeof(VPVirtIOSoundPCMParameters) == 24, "virtio_snd_pcm_set_params is 24 bytes");++enum {+ kVPVirtIOSoundDirectionOutput = 0,+ kVPVirtIOSoundDirectionInput = 1,+};++/// `VIRTIO_SND_PCM_FMT_*` values the plugin can feed CoreAudio from.+enum {+ kVPVirtIOSoundFormatS16 = 5,+ kVPVirtIOSoundFormatS32 = 17,+ kVPVirtIOSoundFormatFloat = 19,+};++// MARK: - Stream format++/// The one format a stream runs at: what CoreAudio is told and what+/// SET_PARAMS asks the device for.+typedef struct {+ double sampleRate;+ uint32_t channels;+ uint32_t bitsPerChannel;+ uint32_t bytesPerFrame;+ bool isFloat;+ uint8_t virtioFormat;+ uint8_t virtioRate;+} VPVirtIOSoundStreamFormat;++/// The sample rate behind a `VIRTIO_SND_PCM_RATE_*` index, or 0.+double VPVirtIOSoundRateForIndex(uint8_t index);++/// Pick a format from what the device offers: 32-bit float, then 32-bit and+/// 16-bit signed integer; 48 kHz, then 44.1 kHz, then the highest rate; the+/// widest channel count. False when the device offers nothing usable.+bool VPVirtIOSoundChooseFormat(const VPVirtIOSoundPCMInfo *info, VPVirtIOSoundStreamFormat *format);++/// Period and buffer sizes for a format: a period is a twelfth of a second+/// rounded up to whole pages, and the buffer holds twelve periods, as Apple's+/// macOS plugin sizes them.+void VPVirtIOSoundBufferSizes(+ const VPVirtIOSoundStreamFormat *format,+ uint32_t pageSize,+ uint32_t *periodBytes,+ uint32_t *bufferBytes);++/// The SET_PARAMS body for a format and its sizes.+VPVirtIOSoundPCMParameters VPVirtIOSoundParameters(+ const VPVirtIOSoundStreamFormat *format,+ uint32_t periodBytes,+ uint32_t bufferBytes);++#endif /* VPVirtIOSoundProtocol_h */diff --git a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundRing.c b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundRing.cnew file mode 100644index 00000000..c656514d--- /dev/null+++ b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundRing.c@@ -0,0 +1,89 @@+// VPVirtIOSoundRing.c — see VPVirtIOSoundRing.h for the counter contract.++#include "VPVirtIOSoundRing.h"++#include <stdlib.h>+#include <string.h>+#include <unistd.h>++bool VPVirtIOSoundRingInit(VPVirtIOSoundRing *ring, uint32_t capacity, uint32_t period) {+ memset(ring, 0, sizeof(*ring));+ if (period == 0 || capacity == 0 || capacity % period != 0) {+ return false;+ }+ void *bytes = NULL;+ if (posix_memalign(&bytes, (size_t)getpagesize(), capacity) != 0) {+ return false;+ }+ memset(bytes, 0, capacity);+ ring->bytes = bytes;+ ring->capacity = capacity;+ ring->period = period;+ atomic_init(&ring->written, 0);+ atomic_init(&ring->completed, 0);+ return true;+}++void VPVirtIOSoundRingDestroy(VPVirtIOSoundRing *ring) {+ free(ring->bytes);+ memset(ring, 0, sizeof(*ring));+}++void VPVirtIOSoundRingReset(VPVirtIOSoundRing *ring) {+ atomic_store_explicit(&ring->written, 0, memory_order_relaxed);+ atomic_store_explicit(&ring->completed, 0, memory_order_relaxed);+ ring->submitted = 0;+}++bool VPVirtIOSoundRingWrite(VPVirtIOSoundRing *ring, const void *source, uint32_t length) {+ if (length == 0) {+ return true;+ }+ uint64_t written = atomic_load_explicit(&ring->written, memory_order_relaxed);+ uint64_t completed = atomic_load_explicit(&ring->completed, memory_order_acquire);+ if (length > ring->capacity - (written - completed)) {+ return false;+ }+ uint32_t offset = (uint32_t)(written % ring->capacity);+ uint32_t first = ring->capacity - offset;+ if (first >= length) {+ memcpy(ring->bytes + offset, source, length);+ } else {+ memcpy(ring->bytes + offset, source, first);+ memcpy(ring->bytes, (const uint8_t *)source + first, length - first);+ }+ atomic_store_explicit(&ring->written, written + length, memory_order_release);+ return true;+}++bool VPVirtIOSoundRingNextSubmission(+ const VPVirtIOSoundRing *ring,+ bool partial,+ uint32_t *offset,+ uint32_t *length) {+ uint64_t written = atomic_load_explicit(&ring->written, memory_order_acquire);+ uint64_t pending = written - ring->submitted;+ if (pending == 0 || (!partial && pending < ring->period)) {+ return false;+ }+ uint32_t start = (uint32_t)(ring->submitted % ring->capacity);+ uint64_t size = partial && pending < ring->period ? pending : ring->period;+ if (size > ring->capacity - start) {+ size = ring->capacity - start;+ }+ *offset = start;+ *length = (uint32_t)size;+ return true;+}++void VPVirtIOSoundRingDidSubmit(VPVirtIOSoundRing *ring, uint32_t length) {+ ring->submitted += length;+}++void VPVirtIOSoundRingDidComplete(VPVirtIOSoundRing *ring, uint32_t length) {+ atomic_fetch_add_explicit(&ring->completed, length, memory_order_release);+}++uint64_t VPVirtIOSoundRingInFlight(const VPVirtIOSoundRing *ring) {+ return ring->submitted - atomic_load_explicit(&ring->completed, memory_order_acquire);+}diff --git a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundRing.h b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundRing.hnew file mode 100644index 00000000..01f45022--- /dev/null+++ b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundRing.h@@ -0,0 +1,60 @@+// VPVirtIOSoundRing.h — output ring between the HAL I/O thread and virtio.+//+// Three byte counters, each with one writer:+//+// completed <= submitted <= written+//+// The real-time I/O thread appends mixed frames and advances `written`. The+// stream's serial queue hands `[submitted, written)` to the device and+// advances `submitted`, and advances `completed` when the device returns the+// bytes. Only `[written, completed + capacity)` may be overwritten: the+// kernel reads a submitted region from the caller's pages until it+// completes, so the space is not free before then.++#ifndef VPVirtIOSoundRing_h+#define VPVirtIOSoundRing_h++#include <stdatomic.h>+#include <stdbool.h>+#include <stdint.h>++typedef struct {+ uint8_t *bytes;+ uint32_t capacity;+ uint32_t period;+ _Atomic uint64_t written;+ _Atomic uint64_t completed;+ uint64_t submitted;+} VPVirtIOSoundRing;++/// Allocate a page-aligned, zeroed ring. False when allocation fails or the+/// capacity is not a whole number of periods.+bool VPVirtIOSoundRingInit(VPVirtIOSoundRing *ring, uint32_t capacity, uint32_t period);+void VPVirtIOSoundRingDestroy(VPVirtIOSoundRing *ring);++/// Rewind every counter to zero. Only while nothing is in flight and the I/O+/// thread is not writing: when the device stream is about to be set up again.+void VPVirtIOSoundRingReset(VPVirtIOSoundRing *ring);++/// Append `length` bytes, all or none. Real-time safe. False, and nothing+/// written, when the free space is short: the device fell behind and these+/// frames are dropped rather than overwriting bytes still in flight.+bool VPVirtIOSoundRingWrite(VPVirtIOSoundRing *ring, const void *source, uint32_t length);++/// The next region to submit, contiguous in memory. Normally a whole period+/// or nothing; with `partial`, whatever is pending (used when the stream+/// stops, so its tail is not left behind). A region never crosses the end+/// of the buffer, so a pending range that wraps takes two calls.+bool VPVirtIOSoundRingNextSubmission(+ const VPVirtIOSoundRing *ring,+ bool partial,+ uint32_t *offset,+ uint32_t *length);++void VPVirtIOSoundRingDidSubmit(VPVirtIOSoundRing *ring, uint32_t length);+void VPVirtIOSoundRingDidComplete(VPVirtIOSoundRing *ring, uint32_t length);++/// Bytes handed to the device and not yet returned.+uint64_t VPVirtIOSoundRingInFlight(const VPVirtIOSoundRing *ring);++#endif /* VPVirtIOSoundRing_h */