Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

watchOS: support for system alert sounds

Luke05c2b41c2751
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 0dd39ec9..33e32fc9 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -1,5 +1,23 @@
# Patch Comparison: Regular / Development / Jailbreak / Experimental
+> **Watch audio validated on a fresh restore (2026-10-31).** A new VM restored
+> from the latest bundle with the shipped `watchos` payload produces audible
+> system sounds (the charging chime and ringtones). A paired control restore
+> with `filesystem-exp-watch_audio` blocked produced no audio: the live HAL
+> directory had no virtio sound plugin, AVAudioSession reported no output routes
+> and zero rate/channels, and AVAudioPlayer of the built-in NanoRingtone3.caf
+> failed to prepare or play. Together these attribute the speaker route to the
+> payload. Playback-category media (music, text and notification tones) still
+> depends on the unimplemented MediaExperience power-budget fix. No code change.
+> See [watch audio](Guest/watch_audio.md).
+
+> **Watch preset audio (2026-10-30).** The standard `watchos` preset now includes
+> the validated watch audio payload, owned by the single `filesystem-exp-watch_audio`
+> declaration. The separate experimental speaker preset has been removed. Local-speaker
+> Playback sessions still fail MediaExperience's power budget, which this does not
+> address. Existing guests need a restore; other presets and the remaining broad
+> audio patches are unchanged. See [watch audio](Guest/watch_audio.md).
+
> **HomeView distance simulation (2026-10-30, runtime validation pending).**
> `dyld-exp-homeview_environment_service` opens only BreadBoardServices'
> environment-service internal-install branch on the reviewed 27.2 userland.
@@ -73,6 +91,31 @@
> original abort on iOS 27.0.1 (24A446). See
> [reproduction and crash stack](Guest/virtual_camera_transport.md#session-registration-during-teardown-2026-10-29).
+> **Watch speaker audio (2026-10-28).** `filesystem-exp-watch_audio`, selected
+> only by `watchos`, installs the watchOS-retargeted virtio sound HAL plugin
+> before the system image is sealed; native product 4017 for Watch7,18 selects
+> the existing HALSPP tunings and PuffinOutput publishes the speaker port. The
+> installer also rewrites the eight `speaker_*` chainTypes from `clhs` to `dflt`
+> in `Library/Audio/Tunings/AID*/VAD/graph_configurations_halspp.plist` through
+> the confined file-edit path, retaining all graphs, AU tunings, volume commands
+> and microphone entries. Native product selection and the graph rewrite alone
+> were not enough (the generic playback handler still declined the route), so
+> the payload also applies three playback-only VirtualAudio bypasses:
+> `patchSpeakerProtectionGate(handler: .playback)`, `patchVolumeModePrecondition`,
+> and the fault-logged inactive-protection terminating call, each matched by
+> source/log/mask or walker/epilogue control-flow anchors and each one four
+> bytes. Mute, play-and-record, the other walker exceptions, raw tunings and
+> microphone patches stay disabled. Verified on WatchAudioGraphTest: live
+> executable text differs from stock only in the three intended instructions
+> (twelve bytes total) and graph data only in the eight speaker chainTypes.
+> Ringtone playback selects Speaker / PuffinOutput, starts HAL I/O, survives
+> repeated stop/start, and keeps audiomxd at PID 110; the owner confirmed
+> audible output after unmuting the Mac. Local-speaker Playback sessions still
+> fail MediaExperience's power budget, which this does not address, and other
+> session categories and long-duration playback are not covered. All 103 focused
+> tests and full bundle build/admission passed. See
+> [watch audio](Guest/watch_audio.md).
+
> **Apple TV RootHide bootstrap and environment hooks (2026-10-26).** No new
> declaration or instruction patch. An arm64e Apple TV now admits
> `system-launchdaemons-boot-environment` and
@@ -4236,6 +4279,7 @@ gone. The preset names three sets:
| `filesystem-boot-mobileactivationd_should_hactivate` | The `should_hactivate` patch, in the image |
| `filesystem-boot-vphoned` | vphoned and its launch daemon, in the image |
| `filesystem-boot-launchd_cache_loader_unsecure_cache_gate` | Lets launchd read the launch daemons from the volume |
+| `filesystem-exp-watch_audio` | Watch images only, and selected by `watchos` alone: installs the virtio sound HAL plugin retargeted to watchOS, rewrites the speaker chain to the generic DSP type, and bypasses VirtualAudio's playback missing-speaker-protection and volume-mode declines and the fault-logged inactive-protection termination. Local-speaker Playback sessions still fail MediaExperience's power budget, which this does not address. Cannot be turned on or off without another restore |
| `manifest-boot-digest_rehash` | Rewrites every BuildManifest digest to the files the restore now sends; for an AEA archive, the digest of its decrypted image, which is what Apple's manifests hold and what an 18.x restore checks the written image against |
The kernel and TXM stay stock, and the restore installs a system whose seal
diff --git a/Research/Guest/watch_audio.md b/Research/Guest/watch_audio.md
new file mode 100644
index 00000000..592801fd
--- /dev/null
+++ b/Research/Guest/watch_audio.md
@@ -0,0 +1,310 @@
+# Apple Watch audio through virtio-snd
+
+## Scope
+
+This puts the existing virtio-snd output transport on an Apple Watch guest
+(`Watch7,18`, N227b, watchOS 26.4 / 23T240). The host already attaches
+`VZVirtioSoundDeviceConfiguration` to every VM, so nothing changes there. What a
+watch lacked is a HAL plugin for the device and a VirtualAudio product that
+initializes on a VM.
+
+The standard `watchos` preset selects the single `filesystem-exp-watch_audio`
+declaration. The separate experimental speaker preset has been removed.
+Ringtones, text-tone previews and user-provided media audio were audible on
+WatchAudioGraphTest. Existing watches require a restore to acquire these patches.
+
+## Why this is a restore-image patch
+
+Every other guest gets the plugin after its restore, from
+`system-virtiosound-cfw-hal_plugin`. A watch cannot. Its System volume is
+sealed and nothing writes it after the restore (that is the whole point of the
+Restore Image set), so the plugin has to be inside the image before its trust
+cache and seal are made. `cfw update-environment` therefore cannot add or
+remove watch audio, and turning the patch on or off needs another restore.
+
+## The three routing-gate bypasses
+
+Native watch product selection enters VirtualAudio's generic playback handler,
+and three separate refusals sit between that handler and a running speaker
+route. They were brought up one at a time on 2026-10-28, and each one revealed
+the next, which is why all three ship together and none is sufficient alone:
+
+1. **Missing speaker protection.** `RoutingHandler_Playback_GenericConfig1`
+ declines a route whose VAD has no speaker protection. Bypassing only this
+ one, playback constructs the generic speaker graph, then fails
+ `RoutingHandler_Playback_GenericConfig1.cpp:252 PRECONDITION FAILURE
+ (std::logic_error)` immediately after the per-VAD volume description reports
+ `SWVolumeMode:SoftwareHardwareMix`, and falls back to Null_Device.
+2. **Volume-mode precondition.** That is the next decline, documented as Layer 4
+ in `virtualaudio_speaker_route_throws.md`. With both declines gone, the later
+ speaker-route serialization path logs `VA/HAL Speaker protection for VAD
+ '[vdef]' is none` and then `Speaker Protection is not active on speaker
+ route`; audiomxd aborts with EXC_CRASH/SIGABRT through libc++abi and
+ crash-loops (three PIDs in a 12-second capture), and an AVAudioPlayer probe
+ cannot complete within 30 seconds while the service restarts.
+3. **Fault-logged inactive-protection termination.** Retargeting that one
+ terminating call in the speaker-route walker is what makes the route survive.
+
+Each is matched semantically, not by offset. The speaker-protection gate and the
+volume-mode precondition use the existing source-file and log-string anchors,
+the latter also keying on the 33-bit volume-mode packing-mask comparison. The
+inactive-protection bypass uses the walker locator and the exact fault-string
+call-flow matcher to recover the terminating call and its own function's
+epilogue. Each recognises its own output on a second run for idempotence, and
+each refuses the patch when its anchor is absent.
+
+### Validated state
+
+On WatchAudioGraphTest, freshly restored, the live arm64e executable text
+differs from stock 23T240 at exactly twelve bytes, three instructions:
+
+- playback speaker-protection decline: 0x2199d4–0x2199d7, branching to 0x219750;
+- playback volume-mode decline: 0x21aa44–0x21aa47, branching to 0x219b20;
+- inactive-protection terminating call: 0x2a7794–0x2a7797, now branching to the
+ walker's epilogue at 0x2a746c. The original callee stub 0x405a10 resolves
+ through the indirect symbol table to `__ZSt9terminatev`.
+
+No other VirtualAudio executable-code byte changed. Full graph-plist comparison confirms only
+the eight speaker chainTypes differ from stock; tuning references and volume
+commands remain unchanged.
+
+What stays disabled: the five other walker exception sites, the mute exception
+bypass, the play-and-record gate, the raw-speaker tuning rewrite and the
+microphone fixes.
+
+### Runtime evidence
+
+AVAudioPlayer preparation and playback both succeeded for the built-in
+NanoRingtone3.caf. AVAudioSession selected Speaker / PuffinOutput and the HAL
+entered Running; repeated stop/start playback also succeeded, and audiomxd
+stayed at PID 110 before, after and across it. After unmuting the Mac, the owner
+explicitly confirmed the replay was audible. This validates ringtone playback
+through the virtual output, but not every audio session category, and not
+long-duration timing. S11 and its pairing were not changed.
+
+Stock-binary regression tests cover dry run, single-instruction scope,
+preservation of the other throw sites, idempotence and refusal when the fatal
+anchor is absent. 103 focused tests passed, with full bundle build and admission.
+
+On 2026-10-31 a new VM restored from the latest bundle (the shipped `watchos`
+payload, not the bring-up test image) produced audible system sounds: the
+charging chime and ringtones. A paired control restore with
+`filesystem-exp-watch_audio` blocked was silent (recorded under Testing below),
+which attributes the speaker route to the payload. Playback-category media
+(music, text tones and notification tones) still depends on the unimplemented
+MediaExperience power-budget fix described below.
+
+## Speaker graph construction
+
+The payload installs the plugin and rewrites the eight `speaker_*` entries in
+`AID4017/VAD/graph_configurations_halspp.plist` from `clhs` to `dflt`.
+The existing graphs, AudioUnit settings and microphone entries stay unchanged.
+The current payload also applies the three VirtualAudio routing-gate bypasses
+described above.
+
+On 2026-10-28, the minimal-payload S11 reproduced the missing dependency:
+VirtualAudio creates `speaker_general` as `DSPGraphChain_HAL_SpeakerProtection`,
+throws `Could not lock weak ptr (:60)`, rejects the connected `PuffinOutput`
+route and falls back to `Null_Device`. The live graph file matched stock bytes.
+The earlier working image also carried the generic speaker-chain rewrite;
+native product 4017 alone does not make physical speaker protection usable.
+
+The restore-image installer now reuses the existing graph patch helper on
+HALSPP configuration files through confined file operations before sealing.
+A missing HALSPP configuration fails the selected install. All broader
+VirtualAudio instruction patches and the raw-speaker tuning rewrite remain off.
+Graph-only runtime validation on 2026-10-28: WatchAudioGraphTest was restored.
+All eight live speaker entries are `dflt` and ProductIDOverride is 4017. A
+synchronized audiomxd capture around an
+AVAudioPlayer playing NanoRingtone3.caf shows successful generic
+`speaker_general` graph construction, with no weak-pointer exception. The
+next blocker is `RoutingHandler_Playback_GenericConfig1.cpp:223 HAL Speaker
+Protection is missing. Failing route`, followed by Null_Device fallback.
+Thus the graph rewrite is necessary but not sufficient: native watch product
+selection still enters the generic playback handler, which is what the three
+routing-gate bypasses above address. No executable patch was enabled in this
+test.
+
+Trimming in this test run removed update assets, watch faces and some linguistic
+data, not the audio tunings. That is a limitation of the test setup, not of the
+payload; S11 and its pairing were not changed.
+
+## Product selection
+
+Read from the 23T240 arm64e `VirtualAudio` slice; addresses are image-relative.
+The watch executable is universal arm64_32 + arm64e and the research VM runs the
+arm64e slice.
+
+- `0x1cab94` caches what the product resolver at `0x1cac08` answers. The
+ resolver reads integer `ProductIDOverride` in `com.apple.audio.virtualaudio`
+ first (`0x1cac3c`–`0x1cac54`) and takes it directly.
+- With no override it calls the hardware product lookup, which asks
+ `MGGetProductType`. That answers nothing a watch VM knows, so at
+ `0x1cad28`–`0x1cad50` it falls back to `DeviceClassNumber` and indexes the
+ table at `0x409050`: `[195, 0, 196, 199, 0, 198]`. This watch takes the last
+ entry, **198**.
+- `0x1cd398` caches the HALSPP-all-routes predicate, which classifies the
+ resolved product through `0x1cd41c` and answers true for classification 2 or
+ 3. Acoustic products 4013–4017 classify as 3 unconditionally; anything else
+ consults NanoMediaUI/SpeakerPlayback and DeviceSupportsWatchSpeakerPlayback.
+- The routing constructor calls that predicate at `0x158078`. True selects
+ `graph_configurations_halspp.plist`; false selects
+ `graph_configurations.plist`.
+
+198 therefore asks for `graph_configurations.plist`, which no watch ships: the
+guest has only `Library/Audio/Tunings/AID4017/VAD/graph_configurations_halspp.plist`.
+`DSPGraphConfig_Utilities` throws `Could not construct`, initialization ends
+with `VA Init Status: 1`, `HALDeviceManager` admits only `Null_Device` under its
+`AllowOnlyNull` filter, and `AVAudioSession` reports no output routes, zero
+channels and a zero sample rate.
+
+**4017** is one of the acoustic products that classify without consulting
+hardware, so the route reads the HALSPP graph the watch already has. Renaming
+the graph would not do: it would bypass the matching HALSPP settings and still
+leave the product wrong.
+
+With 4017 stored and nothing else changed (no sealed file and no binary
+modified), initialization reports `PlugIn initialized ? 2` and `VA Init Status:
+0`, no missing-graph exception, and `HALDeviceManager` admits `PuffinOutput`,
+creates its `PhysicalDevice` and publishes the routable `pspk` speaker port.
+`AVAudioSession` then exposes Speaker/`PuffinOutput` at 44100 Hz, one channel.
+The early `AllowOnlyNull` messages still appear: that filter is a transient
+restriction during initialization, not a permanent VM-product blacklist, so no
+filter bypass is needed.
+
+Both `VPGuestProductID` in the plugin and `GuestVirtualAudioProduct` in vphoned
+answer 4017 for `Watch7,18`, the way they answer 4 for `AudioAccessory5,1`.
+Whichever starts first, audiomxd finds the value: the plugin sets it in process
+on every launch, and vphoned stores it at startup so no launch ordering is
+relied on. An explicit `VPhoneVirtIOSoundProductID` still wins, and 0 there
+leaves VirtualAudio to itself.
+
+Only `Watch7,18` is tested. Another watch model keeps native selection rather
+than borrowing an acoustic product whose tunings it may not carry.
+
+## Routing identity
+
+The output's UID is `PuffinOutput`, which is the only name VirtualAudio's device
+factory builds a speaker port for. A watch claims it the way a HomePod does, and
+in fact uses it natively even with no override stored.
+
+Input keeps a UID of ours. Record routes ask the port for the product's
+microphone sub-ports, which the virtual device does not present, so claiming
+`Digital Mic` on a watch would offer a microphone array that is not there.
+Watch microphone routing is outside this output port's scope.
+
+Neither of HomePod's two driver-side quirks applies. The `mode/glob/0` raw
+custom property and the withheld 44.1 kHz physical format are both gated on
+`AudioAccessory5,1` exactly. A watch's HALSPP route reports 44100 Hz and does
+not read `mode/glob/0`; the `who?` throw at `RoutingHandlerUtilities_Aspen.cpp:385`
+that forced the HomePod property does not appear in watch logs.
+
+## What is established, and what is not
+
+Established on a fresh restore of the current payload: the watch guest
+initializes VirtualAudio with the native product, publishes the speaker port,
+and the owner hears the charging chime and ringtones at the host; a control
+restore with the payload blocked is silent. Earlier, broader-patched images
+also published an AirPlay port and reached the host with ordinary playback; an
+earlier paired test confirmed an AirPlay output, which is historical evidence,
+not fresh AirPlay validation of this payload.
+
+Not established here:
+
+- The earlier audible image carried five VirtualAudio executable fixes and the
+ graph-chain rewrite. The graph-only revision was tested separately as
+ described above and still fails the speaker-protection gate; initialization
+ and a published port do not prove route activation.
+- `MediaExperience` has a separate problem on the local-speaker media path.
+ `CMSUtility_DoesSessionNeedAudioBudget` has Apple's own virtual-device exit,
+ but `CMSMDeviceState_UpdateDeviceClass` sets that flag from `MGGetProductType`
+ comparisons against two legacy tokens and never asks MobileGestalt
+ `IsVirtualDevice`, so a watch VM takes the physical path:
+ `PowerManager_InitializePPM` finds no `ApplePPM` service (`ioreg -r -c
+ ApplePPM -l` is empty, logs say `PPM Error:No matching driver found`), and
+ `PowerManager_RequestBudgetForMediaPPM` returns -16982, which surfaces as
+ `cmsSetIsPlaying: ... unable to take power budget` and AudioQueue 2003329396.
+ This affects Playback-category media on the local speaker: music, text tones
+ and notification tones. The 2026-10-30 Settings text-tone capture establishes
+ that budget failure; direct AVAudioPlayer ringtone playback does not exercise
+ it, and the system sounds that do work (the charging chime and ringtones)
+ take a path that needs no media budget. No MediaExperience patch is currently
+ included.
+- Long-duration clock accuracy, every session category, watch microphone
+ routing and AirPlay lifetime are untested.
+
+## Comparison with audioOS
+
+Here audioOS means the existing HomePod mini (`AudioAccessory5,1`) support,
+validated on HomePod Software 27.0. The watch evidence is from `Watch7,18`
+on watchOS 26.4; this is not a claim about every model or release.
+
+| Area | audioOS / HomePod mini | watchOS addition |
+| --- | --- | --- |
+| Transport | Existing virtio-snd, guest PCM to the host output sink | Same driver, converter, ring, clock and host sink; no new transport |
+| Installation | `system-virtiosound-cfw-hal_plugin`, applied after restore by `cfw install` / environment update | `filesystem-exp-watch_audio`, selected by `watchos`, installed before the system image is sealed |
+| Changing selection | Added driver can be removed by the guest environment update | Requires another restore to add or remove |
+| Platform | Shared iOS driver retargeted to tvOS; bundle metadata `AppleTVOS` | Same retargeting procedure to watchOS; bundle metadata `WatchOS` |
+| Audio product | Override 4 selects native B520/B238 routing | Override 4017 selects the native watch HALSPP graph; the VM-derived 198 asks for a missing graph |
+| Preference ordering | Plugin sets the override in process; vphoned persists it before subsequent audio-service launches | Same mechanism, including the explicit override and zero opt-out |
+| Device identity | `PuffinOutput`; input retains a virtual UID | Same, restricted to the supported watch model |
+| Processing mode | Driver implements the native `mode/glob/0` property required by B238 routing | No additional mode property; the watch route has not required it |
+| Physical rate | Output restricted to 48 kHz to avoid native DSP buffer overruns; 44.1 kHz sources are converted | Keeps the existing alternate-rate support; the observed watch speaker route is 44.1 kHz, mono |
+| Apple audio code | Native product route; iPhone VirtualAudio instruction/tuning fixes disabled | Native product route; generic DSP speaker chain and three VirtualAudio routing-gate bypasses; no MediaExperience patch |
+| Global identity | Original VM MobileGestalt token retained | Same; only VirtualAudio's product preference changes |
+| Playback evidence | Ordinary AVAudioPlayer playback of 48/44.1 kHz sources, repeated cold boots, nonzero host PCM and listening confirmation | Native-product initialization and audible system sounds/ringtones reported; local-speaker Playback sessions still fail the MediaExperience power-budget path |
+| Coverage limits | Microphone, Siri, AirPlay and long-duration timing not validated | Microphone and long-duration timing not validated; an earlier AirPlay output was observed, but lifetime is untested; a 2026-10-31 fresh restore of the shipped payload produced audible system sounds (charging, ringtone) |
+
+The watch addition reuses the HomePod approach to native routing and driver
+compatibility. It needs a different installation stage and product ID, and does
+not inherit HomePod's mode-property or physical-rate workarounds. Its current
+playback coverage is narrower. The missing ApplePPM budget path is documented
+above and remains outside this patch.
+
+## Testing
+
+Build validation (2026-10-27): the `VPhone` Debug bundle builds and passes
+bundle admission. The catalogue, Mach-O platform and cryptex file-operation
+suites pass 46 tests; the version, selection, declaration, plan and gate suites
+pass another 32. The file-operation coverage verifies that even an unrestricted
+gate does not record watch audio for an iPhone, Apple TV, unknown or missing
+manifest. These checks do not replace the fresh, minimal-payload restore
+validation described above.
+
+```zsh
+vphone-cli vm create WatchAudioTest --device Watch7,18 --preset watchos
+```
+
+Supply the same firmware inputs the watch normally takes. On an existing record
+the preset can also be reached with
+`fw set-patches <vm> --preset watchos --allow filesystem-exp-watch_audio`,
+which still needs a restore to take effect.
+
+Prepare a separate VM rather than changing a paired watch in place: the payload
+cannot be added or removed without another restore, and restoring replaces the
+pairing.
+
+Then check, in order:
+
+1. The kernel exposes `AppleVirtIOSound` and its user client opens.
+2. audiomxd loads the watchOS-marked plugin with no symbol or selector failure.
+3. VirtualAudio reports `VA Init Status: 0` and publishes `PuffinOutput` with a
+ `pspk` port. Log the ProductID rather than guessing at an override.
+4. Charging sounds and ringtones are audible at the host; test media and text
+ tones separately and record any MediaExperience budget failure.
+5. For a negative control, create a separate VM with
+ `--preset watchos --block filesystem-exp-watch_audio` and confirm that its
+ restored system omits the plugin. The standard `watchos` preset includes it.
+
+### Negative control (2026-10-31)
+
+A separate VM restored with `--preset watchos --block
+filesystem-exp-watch_audio`, same Watch7,18 / watchOS 26.4 (23T240), produced
+no audio. The live `/System/Library/Audio/Plug-Ins/HAL` directory held no
+`VPhoneVirtIOSound.driver`, and `AVAudioSession.sharedInstance()` reported an
+empty output-route list with zero sample rate and zero channels. AVAudioPlayer
+of the built-in `NanoRingtone3.caf` returned false from both `prepareToPlay()`
+and `play()`, and after 1.5 seconds `isPlaying()` was still false with
+`currentTime()` 0. This tests removal of the whole payload, not the necessity
+of each graph or instruction change, and pairs with the fresh-restore
+confirmation above to attribute the speaker route to the payload.
diff --git a/VPhoneDaemon/Daemon/GuestVirtualAudioProduct.swift b/VPhoneDaemon/Daemon/GuestVirtualAudioProduct.swift
index ede57bbb..4216d62c 100644
--- a/VPhoneDaemon/Daemon/GuestVirtualAudioProduct.swift
+++ b/VPhoneDaemon/Daemon/GuestVirtualAudioProduct.swift
@@ -47,14 +47,16 @@ enum GuestVirtualAudioProduct {
}
/// The same answer as the plugin's `VPGuestProductID`: 8010 on an iPad or
- /// iPhone guest, native B520 route 4 on HomePod mini, 0 elsewhere unless
- /// one was chosen. This preference affects only VirtualAudio; the VM keeps
- /// its original MobileGestalt product token for every other subsystem.
+ /// iPhone guest, native B520 route 4 on HomePod mini, native acoustic
+ /// product 4017 on a Watch7,18, 0 elsewhere unless one was chosen. This
+ /// preference affects only VirtualAudio; the VM keeps its original
+ /// MobileGestalt product token for every other subsystem.
static func product(machine: String, chosen: Int?) -> Int {
if let chosen, chosen >= 0 {
return chosen
}
if machine == "AudioAccessory5,1" { return 4 }
+ if machine == "Watch7,18" { return 4017 }
return machine.hasPrefix("iPad") || machine.hasPrefix("iPhone") ? 8010 : 0
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift
index ac05523c..c7e6909f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift
@@ -69,10 +69,21 @@ public final class CryptexFilesystemPatcher: BufferedPatcher {
// MARK: - Patcher
+ /// Whether this step has anything to do on the system being merged. A step
+ /// the gate allows but this image has no use for is left out of the records
+ /// rather than reported as applied.
+ func applies(_ identifier: String) -> Bool {
+ switch identifier {
+ case FirmwareRestoreImagePatchSet.surfaceCompression: isIOS18
+ case FirmwareRestoreImagePatchSet.watchAudio: guestFamily == .watch
+ default: true
+ }
+ }
+
/// One record per step the gate lets through. The merge itself is the
/// patcher: the pipeline builds it only when the merge is on.
public func findAll() throws -> [PatchRecord] {
- Self.steps.filter { gate.isEnabled($0.identifier) && ($0.identifier != FirmwareRestoreImagePatchSet.surfaceCompression || isIOS18) }.map { step in
+ Self.steps.filter { gate.isEnabled($0.identifier) && applies($0.identifier) }.map { step in
PatchRecord(
patchID: step.identifier,
component: "",
@@ -92,6 +103,7 @@ public final class CryptexFilesystemPatcher: BufferedPatcher {
(FirmwareRestoreImagePatchSet.vphoned, "Install vphoned and its launch daemon"),
(FirmwareRestoreImagePatchSet.launchdCacheLoader, "Patch launchd_cache_loader"),
(FirmwareRestoreImagePatchSet.virtualBluetooth, "Enable LE connections over the virtual Bluetooth controller"),
+ (FirmwareRestoreImagePatchSet.watchAudio, "Install the virtio sound HAL plugin for a watch"),
]
@discardableResult
@@ -203,6 +215,10 @@ public final class CryptexFilesystemPatcher: BufferedPatcher {
}
print(" [+] \(CustomFirmwareBluetoothVirtualController.feature) on")
}
+ if gate.isEnabled(FirmwareRestoreImagePatchSet.watchAudio), applies(FirmwareRestoreImagePatchSet.watchAudio) {
+ print("- Adding the watch speaker…")
+ try addWatchAudio(targetMount: targetMount)
+ }
try removeHostEventLog(mount: targetMount)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherWatchAudio.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherWatchAudio.swift
new file mode 100644
index 00000000..61c8d066
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherWatchAudio.swift
@@ -0,0 +1,123 @@
+// CryptexFilesystemPatcherWatchAudio.swift — The watch speaker payload, written before the seal.
+//
+// The virtio sound HAL plugin is retargeted to watchOS, the speaker tuning graphs are
+// rebuilt through the generic DSP chain, and three VirtualAudio routing gates are
+// addressed.
+//
+// Selected by `filesystem-exp-watch_audio`, which `applies(_:)` in CryptexFilesystemPatcher.swift
+// gates to a watch guest. See Research/Guest/watch_audio.md.
+
+import Foundation
+import VPhoneCoreKit
+import VPhonePatchKit
+import VPhoneSign
+
+extension CryptexFilesystemPatcher {
+
+ func addWatchAudio(targetMount: String) throws {
+ // Routing uses the native watch product. See Research/Guest/watch_audio.md
+
+ let name = "VPhoneVirtIOSound.driver"
+ let relative = "System/Library/Audio/Plug-Ins/HAL/\(name)"
+
+ let confined = try VPhoneConfinedDirectory.pin(absolutePath: targetMount)
+ let source = try VPhoneConfinedDirectory.pin(absolutePath: VPhoneGuestBinaries.resolve(name).path)
+
+ try confined.removeItem(relative)
+ try confined.copyTree(from: source, to: relative, owner: (0, 0))
+
+ let bundle = URL(filePath: targetMount).appending(path: relative)
+ try deleteAppleDoubleFiles(under: bundle)
+
+ let executable = bundle.appending(path: "VPhoneVirtIOSound")
+ var data = try Data(contentsOf: executable)
+
+ try MachOBuildPlatform.set(MachOBuildPlatform.watchOS, in: &data)
+ try data.write(to: executable)
+ try VPhoneSigner.sign(
+ fileAt: executable,
+ options: .init(identifier: nil, entitlements: nil, mergesExisting: true, style: .appleAdHoc),
+ )
+
+ let infoURL = bundle.appending(path: "Info.plist")
+ guard var info = try PropertyListSerialization.propertyList(
+ from: Data(contentsOf: infoURL), format: nil,
+ ) as? [String: Any] else {
+ throw VPhonePatchKit.PatcherError.patchVerificationFailed(
+ "The virtio sound driver has no valid bundle metadata.",
+ )
+ }
+
+ info["CFBundleSupportedPlatforms"] = ["WatchOS"]
+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: infoURL)
+
+ _ = try runProcess("/usr/bin/codesign", ["-f", "-s", "-", "--timestamp=none", bundle.path])
+ try chownRecursively(uid: 0, gid: 0, at: bundle)
+
+ for path in [bundle, bundle.appending(path: "/VPhoneVirtIOSound"), bundle.appending(path: "/_CodeSignature")] {
+ try setMode(0o755, at: path)
+ }
+
+ for path in [bundle.appending(path: "/Info.plist"), bundle.appending(path: "/_CodeSignature/CodeResources")] {
+ try setMode(0o644, at: path)
+ }
+
+ print(" [+] /\(relative)")
+
+ try patchWatchAudioGraphs(targetMount: targetMount)
+ try patchWatchAudioRoutingGates(targetMount: targetMount)
+ }
+
+ func patchWatchAudioRoutingGates(targetMount: String) throws {
+ let relative = "Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin"
+ try editGuestFile("\(relative)/VirtualAudio", targetMount: targetMount, mode: 0o755) { file in
+ try thinToArm64e(file)
+ try CustomFirmwareVirtualAudio.patchSpeakerProtectionGate(
+ fileAt: file, handler: .playback, reattest: false,
+ )
+
+ try CustomFirmwareVirtualAudio.patchVolumeModePrecondition(
+ fileAt: file, reattest: false,
+ )
+
+ try CustomFirmwareVirtualAudio.patchInactiveSpeakerProtection(
+ fileAt: file, reattest: false,
+ )
+
+ try VPhoneSigner.sign(fileAt: file, options: guestSigningOptions())
+ }
+
+ let target = try VPhoneConfinedDirectory.pin(absolutePath: targetMount)
+ let bundle = try target.directory(relative)
+ _ = try runProcess("/usr/bin/codesign", [
+ "-f", "-s", "-", "--timestamp=none", "--preserve-metadata=entitlements", bundle.path,
+ ])
+ }
+
+ func patchWatchAudioGraphs(targetMount: String) throws {
+ // The HAL speaker-protection chain requires a physical Speaker device
+ // Keep the watch's DSP tunings, but construct them through the generic chain
+ let target = try VPhoneConfinedDirectory.pin(absolutePath: targetMount)
+ let tunings = try target.directory("Library/Audio/Tunings")
+
+ var patched = 0
+ for name in try tunings.entries().sorted() where name.hasPrefix("AID") {
+ let relative = "Library/Audio/Tunings/\(name)/VAD/graph_configurations_halspp.plist"
+ guard try target.exists(relative) else {
+ continue
+ }
+
+ try editGuestFile(relative, targetMount: targetMount, mode: 0o644) { file in
+ try CustomFirmwareVirtualAudioGraphConfigurations.patch(at: file)
+ }
+
+ patched += 1
+ }
+
+ guard patched > 0 else {
+ throw VPhonePatchKit.PatcherError.patchVerificationFailed(
+ "Watch audio requires a HALSPP graph configuration in the image",
+ )
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift
index 24da6626..fb2c055d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/VirtualAudio/CustomFirmwareVirtualAudio.swift
@@ -510,6 +510,121 @@ public enum CustomFirmwareVirtualAudio {
)
}
+ // MARK: - Speaker Protection
+
+ /// Patch the VirtualAudio Mach-O at `url` in place, turning the speaker-route
+ /// walker's fault-logged terminating call into an unconditional branch to the
+ /// wrapper's epilogue, so a speaker whose protection is inactive returns
+ /// quietly instead of terminating.
+ ///
+ /// Idempotent: a second run finds the site already holding an unconditional
+ /// branch to the epilogue, 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 patchInactiveSpeakerProtection(
+ 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 patchInactiveSpeakerProtection(
+ &data, reattest: reattest, dryRun: dryRun, log: log,
+ )
+
+ if data != before {
+ try data.write(to: url)
+ }
+
+ return report
+ }
+
+ /// In-memory form of ``patchInactiveSpeakerProtection(fileAt:reattest:dryRun:log:)``.
+ @discardableResult
+ public static func patchInactiveSpeakerProtection(
+ _ 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)
+ guard let site = terminateSite(
+ in: data, disasm: located.disasm,
+ sections: MachOParser.parseSections(from: data),
+ textStart: located.textStart, textEnd: located.walkerEndOffset,
+ walkerStart: located.walkerStartOffset, walkerEnd: located.walkerEndOffset,
+ epilogueVMA: located.epilogueVMA, includePatched: true, requireUniqueReference: true,
+ ) else {
+ throw PatcherError.patchSiteNotFound(
+ "\(component): no fault-logged inactive speaker-protection termination in the walker",
+ )
+ }
+
+ let siteVMA = located.vma(site)
+ let anchor = Anchor(
+ throwBlockFileOffset: site, throwBlockVMA: siteVMA,
+ epilogueFileOffset: located.epilogueOffset, epilogueVMA: located.epilogueVMA,
+ )
+
+ let instruction = located.disasm.disassembleOne(in: data, at: site, address: siteVMA)
+ if let instruction, instruction.isJump,
+ !instruction.isCall,
+ let word = wordAt(data, site),
+ ARM64Encoder.decodeBranchTarget(insn: word, pc: siteVMA) == located.epilogueVMA
+ {
+ log?(" [=] inactive speaker-protection termination already bypassed")
+ return Report(outcome: .alreadyPatched, anchor: anchor, records: [], slotRehashes: [])
+ }
+
+ guard instruction?.isCall == true,
+ let branch = ARM64Encoder.encodeB(from: Int(siteVMA), to: Int(located.epilogueVMA)) else {
+ throw PatcherError.patchSiteNotFound(
+ "\(component): inactive speaker-protection termination is not a call with a reachable epilogue",
+ )
+ }
+
+ log?(" [.] inactive speaker-protection termination 0x\(hex(siteVMA)) -> epilogue 0x\(hex(located.epilogueVMA))")
+ if dryRun {
+ return Report(outcome: .wouldPatch, anchor: anchor, records: [], slotRehashes: [])
+ }
+
+ let original = Data(data[site..<site + 4])
+ data.replaceSubrange(site..<site + 4, with: branch)
+
+ let rehashes = reattest
+ ? try CustomFirmwareMachOCodeSignature.reattest(&data, modifiedOffsets: [site]) : []
+ log?(" [+] bypassed only the inactive speaker-protection termination")
+
+ return Report(
+ outcome: .patched, anchor: anchor,
+ records: [PatchRecord(
+ patchID: patchID + ".inactive_protection", component: component,
+ fileOffset: site, virtualAddress: siteVMA,
+ originalBytes: original, patchedBytes: branch,
+ beforeDisasm: instruction?.description ?? "",
+ afterDisasm: branch.map { String(format: "%02x", $0) }.joined(separator: " "),
+ description: "inactive speaker-protection termination -> epilogue",
+ )], slotRehashes: rehashes,
+ )
+ }
+
// MARK: - Mute-set patching
/// Patch the VirtualAudio Mach-O at `url` in place, turning the mute-set
@@ -2066,6 +2181,8 @@ public enum CustomFirmwareVirtualAudio {
walkerStart: Int,
walkerEnd: Int,
epilogueVMA: UInt64,
+ includePatched: Bool = false,
+ requireUniqueReference: Bool = false,
) -> Int? {
let needle = Array((terminateFault + "\0").utf8)
var faultVMA: UInt64?
@@ -2087,7 +2204,8 @@ public enum CustomFirmwareVirtualAudio {
textStart: walkerStart,
textEnd: walkerEnd,
)
- guard let reference = references.first else { return nil }
+ guard !requireUniqueReference || references.count == 1,
+ 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.
@@ -2137,7 +2255,7 @@ public enum CustomFirmwareVirtualAudio {
let target = ARM64Encoder.decodeBranchTarget(insn: word, pc: UInt64(site + 4)),
target == epilogueVMA
{
- return nil
+ return includePatched ? site + 4 : nil
}
return site
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index 73773ef7..637355a2 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -440,7 +440,7 @@ public enum FirmwarePatchSetCatalog {
public static let watchOSPreset = VPhonePatchPreset(
identifier: VPhonePatchPreset.watchOSIdentifier,
title: "Apple Watch",
- summary: "Minimal for an Apple Watch guest: the watch board's device tree, and a resealed system with vphoned, the GPU driver and activation restored onto a stock kernel and TXM.",
+ summary: "Minimal for an Apple Watch guest: the watch board's device tree, and a resealed system with vphoned, the GPU driver, speaker audio and activation restored onto a stock kernel and TXM.",
patchSets: minimalPreset.patchSets,
selection: .allow(
minimalBootChainPatches
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareRestoreImagePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareRestoreImagePatchSet.swift
index 2c1781c3..f131384e 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareRestoreImagePatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareRestoreImagePatchSet.swift
@@ -8,10 +8,11 @@
// chain, kernel and TXM stay stock, and nothing writes the System volume after the
// restore, because that would break the seal.
//
-// Only the `minimal` preset and its watch form, `watchos`, name this set. Every
-// patch in it is boot-essential for them, and naming it nowhere else keeps
-// `standard` from counting them as dropped. A watchOS image has no cryptexes:
-// for a watch the merge only reseals the image with the guest payload.
+// Only the `minimal` preset and its watch form, `watchos`, name this set, and both
+// allow all of it. Every patch in it but the two experiments is boot-essential for
+// them, and naming it nowhere else keeps `standard` from counting them as dropped.
+// A watchOS image has no cryptexes: for a watch the merge only reseals the image
+// with the guest payload.
import Foundation
import VPhonePatchKit
@@ -29,6 +30,7 @@ public enum FirmwareRestoreImagePatchSet {
public static let vphoned = "filesystem-boot-vphoned"
public static let launchdCacheLoader = "filesystem-boot-launchd_cache_loader_unsecure_cache_gate"
public static let virtualBluetooth = "filesystem-exp-btvc_le_connection"
+ public static let watchAudio = "filesystem-exp-watch_audio"
public static let digestRehash = "manifest-boot-digest_rehash"
private static func filesystem(_ identifier: String, _ title: String, _ summary: String) -> VPhonePatchDeclaration {
@@ -82,6 +84,12 @@ public enum FirmwareRestoreImagePatchSet {
summary: "Turns on the feature flag that lets bluetoothd connect over its virtual controller, which a watch and its phone talk over once paired.",
target: .firmware(.filesystem),
),
+ VPhonePatchDeclaration(
+ identifier: watchAudio,
+ title: "Watch speaker",
+ summary: "Installs the virtio sound HAL plugin on watchOS.",
+ target: .firmware(.filesystem),
+ ),
VPhonePatchDeclaration(
identifier: digestRehash,
title: "Manifest digests",
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift
index 2fa064f1..4e314ff4 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift
@@ -56,19 +56,6 @@ struct CryptexFileOpsTests {
}
/// A patcher is only needed for the methods; nothing here reads a manifest.
- private func makePatcher(_ scratch: URL) -> CryptexFilesystemPatcher {
- CryptexFilesystemPatcher(buildManiest: Data(), restoreDir: scratch, verbose: false)
- }
-
- private func makeScratch() throws -> URL {
- let url = FileManager.default.temporaryDirectory
- .appendingPathComponent("vphone-fileops-\(UUID().uuidString)")
- try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
- guard let path = realpath(url.path, nil) else { throw POSIXError(.ENOENT) }
- defer { free(path) }
- return URL(fileURLWithPath: String(cString: path))
- }
-
private func mode(of url: URL) throws -> Int {
let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
return (attributes[.posixPermissions] as? NSNumber)?.intValue ?? -1
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFilesystemPatcherWatchAudioTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFilesystemPatcherWatchAudioTests.swift
new file mode 100644
index 00000000..7164d379
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFilesystemPatcherWatchAudioTests.swift
@@ -0,0 +1,36 @@
+// CryptexFilesystemPatcherWatchAudioTests.swift — selection coverage for
+// `filesystem-exp-watch_audio`.
+//
+// The watch speaker payload is gated by CryptexFilesystemPatcher.applies(_:),
+// which answers `guestFamily == .watch` for this step. This asserts that the
+// product gate records the payload only for a watch restore image and never for
+// an iPhone, an Apple TV, an unknown product, or a missing manifest. The
+// preset-to-plan side of selection lives in FirmwarePatchSetCatalogTests; the
+// VirtualAudio executable bypasses live in CustomFirmwareVirtualAudioTests.
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+
+@Suite("Watch speaker payload selection")
+struct CryptexFilesystemPatcherWatchAudioTests {
+
+ @Test("The watch speaker payload is recorded only for a watch restore image")
+ func watchAudioRequiresWatchImage() throws {
+ let identifier = FirmwareRestoreImagePatchSet.watchAudio
+ let root = try makeScratch()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let manifest = root.appending(path: "iPhone-BuildManifest.plist")
+ for product in ["Watch7,18", "iPhone17,3", "AppleTV5,3", "unknown"] {
+ try PropertyListSerialization.data(
+ fromPropertyList: ["SupportedProductTypes": [product]], format: .xml, options: 0,
+ ).write(to: manifest)
+ let records = try makePatcher(root).findAll()
+ #expect(records.contains { $0.patchID == identifier } == (product == "Watch7,18"))
+ }
+
+ try FileManager.default.removeItem(at: manifest)
+ #expect(try !makePatcher(root).findAll().contains { $0.patchID == identifier })
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexPatcherTestSupport.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexPatcherTestSupport.swift
new file mode 100644
index 00000000..7474ccc5
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexPatcherTestSupport.swift
@@ -0,0 +1,21 @@
+// CryptexPatcherTestSupport.swift — shared fixtures for the CryptexFilesystemPatcher suites.
+//
+// `makeScratch` and `makePatcher` stand a patcher up over a throwaway restore
+// directory. They are shared by the file-operation suite (CryptexFileOpsTests)
+// and the watch speaker payload selection suite
+
+@testable import FirmwarePatcher
+import Foundation
+
+func makePatcher(_ scratch: URL) -> CryptexFilesystemPatcher {
+ CryptexFilesystemPatcher(buildManiest: Data(), restoreDir: scratch, verbose: false)
+}
+
+func makeScratch() throws -> URL {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-cryptex-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ guard let path = realpath(url.path, nil) else { throw POSIXError(.ENOENT) }
+ defer { free(path) }
+ return URL(fileURLWithPath: String(cString: path))
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift
index 9af2bac2..4fddc32c 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareVirtualAudioTests.swift
@@ -18,6 +18,27 @@ import VPhonePatchKit
@Suite("CustomFirmwareVirtualAudio")
struct CustomFirmwareVirtualAudioTests {
+ @Test(arguments: [Self.junk, Data()])
+ func `inactive protection bypass refuses an invalid binary`(_ input: Data) {
+ var data = input
+ #expect(throws: PatcherError.self) {
+ try CustomFirmwareVirtualAudio.patchInactiveSpeakerProtection(
+ &data, reattest: false, log: nil,
+ )
+ }
+ #expect(data == input)
+ }
+
+ @Test
+ func `the inactive-protection anchor strings and record identity are stable`() {
+ #expect(CustomFirmwareVirtualAudio.terminateFault == "Speaker Protection is not active on speaker route")
+ #expect(
+ CustomFirmwareVirtualAudio.patchID + ".inactive_protection"
+ == "system-virtualaudio-cfw-speaker_route_throws.inactive_protection",
+ )
+ #expect(CustomFirmwareVirtualAudio.component == "virtualaudio")
+ }
+
/// Not a Mach-O at all.
static let junk = Data(repeating: 0x41, count: 4096)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
index 81806ae2..83454849 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
@@ -221,6 +221,44 @@ struct FirmwarePatchSetCatalogTests {
.union(FirmwarePatchSetCatalog.watchOSDeviceTreePatches).union(bootChain).union(researchBoard))
}
+ @Test
+ func `The presets naming the restore image set include the audio payload`() throws {
+ func enabled(_ preset: VPhonePatchPreset) throws -> Set<String> {
+ try VPhonePatchPlan.resolve(
+ preset: preset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion("26.4"),
+ cloudOS: VPhoneVersion("26.4"),
+ ).enabled
+ }
+
+ let namesRestoreImage: Set<String> = [
+ VPhonePatchPreset.minimalIdentifier,
+ VPhonePatchPreset.watchOSIdentifier,
+ ]
+
+ for preset in FirmwarePatchSetCatalog.builtInPresets {
+ let resolved = try enabled(preset)
+ #expect(
+ resolved.contains(FirmwareRestoreImagePatchSet.watchAudio)
+ == namesRestoreImage.contains(preset.identifier),
+ "\(preset.identifier)",
+ )
+ }
+ }
+
+ @Test
+ func `The watch audio payload stays selected across supported bases`() throws {
+ for base in ["26.4", "26.5", "27.0"] {
+ let plan = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.watchOSPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion("26.4"),
+ )
+ #expect(plan.enabled.contains(FirmwareRestoreImagePatchSet.watchAudio))
+ }
+ }
+
@Test
func `Standard leaves every manual-only patch off, on every base`() throws {
for base in ["18.6.2", "26.4", "27.0"] {
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist
index cba086dc..e4a383e4 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist
@@ -52,6 +52,7 @@
<string>filesystem-boot-mobileactivationd_should_hactivate</string>
<string>filesystem-boot-vphoned</string>
<string>filesystem-exp-btvc_le_connection</string>
+ <string>filesystem-exp-watch_audio</string>
<string>ibec-boot-boot_args</string>
<string>ibec-boot-bootx_precondition</string>
<string>ibec-boot-image4_callback</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/watchos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/watchos.plist
index 9765cd42..f4e9bc8b 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/watchos.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/watchos.plist
@@ -55,6 +55,7 @@
<string>filesystem-boot-mobileactivationd_should_hactivate</string>
<string>filesystem-boot-vphoned</string>
<string>filesystem-exp-btvc_le_connection</string>
+ <string>filesystem-exp-watch_audio</string>
<string>ibec-boot-boot_args</string>
<string>ibec-boot-bootx_precondition</string>
<string>ibec-boot-image4_callback</string>
@@ -71,7 +72,7 @@
</array>
</dict>
<key>Summary</key>
- <string>Minimal for an Apple Watch guest: the watch board's device tree, and a resealed system with vphoned, the GPU driver and activation restored onto a stock kernel and TXM.</string>
+ <string>Minimal for an Apple Watch guest: the watch board's device tree, and a resealed system with vphoned, the GPU driver, speaker audio and activation restored onto a stock kernel and TXM.</string>
<key>Title</key>
<string>Apple Watch</string>
</dict>
diff --git a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.m b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.m
index 6f234387..b346a60a 100644
--- a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.m
+++ b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.m
@@ -268,6 +268,10 @@ static const char *VPMachine(void) {
/// Keep the original VM product token: its donor replacement also changes
/// unrelated services, including HomePodDisplayService's physical gamma path.
///
+/// Watch7,18 uses native acoustic product 4017 to select its HALSPP graph.
+/// The VM-derived 198 asks for a graph the watch does not ship.
+/// See Research/Guest/watch_audio.md.
+///
/// VirtualAudio derives its ProductID from a MobileGestalt class answer, and
/// vphone600 lands on a simulator class — 196 presenting an iPad, 195 an
/// iPhone — whose routing constructor skips the sub-port configurations the
@@ -290,6 +294,7 @@ static int VPGuestProductID(void) {
const char *machine = VPMachine();
product = strncmp(machine, "iPad", 4) == 0 || strncmp(machine, "iPhone", 6) == 0 ? 8010 : 0;
if (strcmp(machine, "AudioAccessory5,1") == 0) product = 4;
+ if (strcmp(machine, "Watch7,18") == 0) product = 4017;
id chosen = CFBridgingRelease(CFPreferencesCopyAppValue(CFSTR("VPhoneVirtIOSoundProductID"), kSettingsDomain));
if ([chosen isKindOfClass:NSNumber.class] && [chosen intValue] >= 0) {
product = [chosen intValue];
@@ -316,14 +321,16 @@ static NSString *VPDeviceUID(ASDStreamDirection direction, unsigned index) {
// sub-ports for. Under any name of our own a device is claimed by nothing.
// Only where the route is set up: a speaker route on a VirtualAudio that
// was not deadlocked audiomxd and crash-looped it across launches.
- // HomePod mini's native B238 routing also claims PuffinOutput. Its
- // ProductID uses the audio-only B520 override. Leave its input unclaimed: microphone
- // routing needs the physical array and is not part of this output port.
- if (!input && index == 0 && strcmp(VPMachine(), "AudioAccessory5,1") == 0) {
- return @"PuffinOutput";
- }
- if (index == 0 && VPGuestProductID() != 0 && strcmp(VPMachine(), "AudioAccessory5,1") != 0) {
- return input ? @"Digital Mic" : @"PuffinOutput";
+ // Native HomePod and watch routes claim PuffinOutput; their microphone
+ // arrays are not supplied by the virtual device, so their input keeps a
+ // name of our own. A product of 0 claims nothing on any machine: it leaves
+ // VirtualAudio to itself, and the route this device would need is then the
+ // one VirtualAudio never set up.
+ const char *machine = VPMachine();
+ BOOL outputOnly = strcmp(machine, "AudioAccessory5,1") == 0 || strcmp(machine, "Watch7,18") == 0;
+ if (index == 0 && VPGuestProductID() != 0) {
+ if (!input) return @"PuffinOutput";
+ if (!outputOnly) return @"Digital Mic";
}
return [NSString stringWithFormat:@"VPhoneVirtIOSound%s:%u", input ? "Input" : "", index];
}