Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Complete HomePod 26.5 setup, and play AirPlay to a HomePod VM

Maximilian Paß878c951a04a6
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 479a1936..32d26f5d 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -367,6 +367,36 @@
> presentation/reconnection. Opt-out restored absent keys and setup behavior.
> See [implementation, live evidence, and service boundaries](Firmware/homepod_soundboard_controls.md).
+> **HomePod setup completion on 26.5 (2026-10-26).** The gate of
+> `system-homepod-exp-setup_bypass` is now 26.5 or later (`.atLeast(26, 5)`
+> instead of `.major(27)`); the helper is unchanged. Under `homepod-mini` on the
+> 26.5 kernelcache mix (`homepod-std`, HomePod Software 26.5, 23L471), an
+> environment update reported the patch "on in the current selection, newer
+> than this VM's patch plan" and staged the marker. On the next boot the helper
+> journalled both keys as absent, found all four SetupAssistant exports, and
+> reported `NeedsSetup=false`, `CompletedInitialRun=true`, `Succeeded=true`
+> with a fresh `lastPrepareLaunchSentinel`; HPSetup ended. Setting the two keys
+> with vphoned's `setup.skip` alone, as before, skips that sentinel, so
+> SoundBoard never runs its setup-gated initialization. No new instruction patch.
+
+> **HomePod AirPlay on a VM (2026-10-27).** New `system-homepod-exp-airplay_vm`
+> is HomePod-only, restricted to 26.5, and selected only by `homepod-mini`. It
+> installs the System marker `/usr/share/vphone/HomePodAirPlay.plist`; the
+> existing setup helper then sets AirPlay's own VM override,
+> `useWiFiAndAWDLOnVirtualMachine = 1` in mobile's `com.apple.airplay`,
+> through CFPreferences. Without it `APSIsVirtualMachine()` is true and
+> airplayd forces discovery mode none ("customer VM build"), so the HomePod has
+> no local endpoint and a Mac's Music fails with -15016. The helper journals the
+> original value the same way as the setup keys (absent included) and, only when
+> the value changed, sends SIGTERM to mobile's exact `airplayd`, `tvairplayd`
+> and `mediaremoted` so they reread it. Opt-out restores the journal at the next
+> boot. Live on `homepod-std` with bundle `2.13.5-local.47579029` after removing
+> the manually written pref: the status reported `Changed=true`, `Restarted=3`,
+> the journal recorded the key as absent, and the Mac's Music played to the
+> HomePod (selected, active, playing). Playback also needs the gPTP recipe
+> change in the HomePod kernelcache section. No new instruction patch. See
+> [Guest/homepod_airplay.md](Guest/homepod_airplay.md).
+
> **HomePod top cap (2026-10-22).** `system-homepod-exp-top_cap` installs
> `/usr/share/vphone/HomePodDisplay.plist`, extracted from the selected board's
> `/arm-io/dockchannel-rtp/rtp-transport/display` node. It preserves the donor's
diff --git a/Research/Firmware/homepod_soundboard_controls.md b/Research/Firmware/homepod_soundboard_controls.md
index 62d10fe7..612d6a95 100644
--- a/Research/Firmware/homepod_soundboard_controls.md
+++ b/Research/Firmware/homepod_soundboard_controls.md
@@ -174,7 +174,9 @@ The full VPhone bundle build passed.
## Setup completion and inverse
`system-homepod-exp-setup_bypass` is a declared optional patch, gated to HomePod
-27.x and enabled only in the `homepod-mini` preset. Other presets explicitly
+26.5 and later and enabled only in the `homepod-mini` preset. HomePod Software
+26.5 (23L471) has the same four SetupAssistant exports; the helper succeeded on
+it on 2026-10-26 (see the binary patch comparison). Other presets explicitly
disable it, and explicit selection for another family is rejected. Its System
marker is `/usr/share/vphone/HomePodSetup.plist`, with `Enabled=true`.
diff --git a/Research/Guest/homepod_airplay.md b/Research/Guest/homepod_airplay.md
new file mode 100644
index 00000000..848965a1
--- /dev/null
+++ b/Research/Guest/homepod_airplay.md
@@ -0,0 +1,142 @@
+# HomePod AirPlay from the Mac
+
+Measured on 2026-10-26 with `homepod-std`: HomePod Software 26.5 (23L471),
+`homepod-mini` on the 26.5 kernelcache mix, `system-homepod-exp-setup_bypass`
+on, NAT network. The sender is the host Mac's Music app (AppleScript
+`current AirPlay devices`), which goes through AirPlayXPCHelper and the Mac's
+mediaremoted.
+
+## Before local setup completion
+
+The HomePod advertises `_airplay._tcp` and `_raop._tcp` (model
+`AudioAccessory5,1`, `srcvers=950.7.1`) only once setup is done. With the two
+`com.apple.purplebuddy` keys alone, port 7000 answers `/info`, pair-setup
+succeeds, and the Mac's control session activates.
+
+## The VM discovery gate
+
+The HomePod's airplayd logs `Discovery mode set to none - customer VM build`.
+In AirPlaySender, `browserController_updateDiscoveryMode` forces
+`kFigEndpointManagerDiscoveryMode_None` when `APSIsVirtualMachine()` is true and
+`IsAppleInternalBuild()` is false. Without discovery the HomePod never finds its
+own output device (`searchAVOutputDeviceForUID` for its own UID times out), so
+its mediaremoted has no local endpoint (`NoLocalEndpointConnection`), and the
+Mac's `loadDeviceInfo` over the remote-control channel times out (MediaRemote
+error 113; Music reports -15016).
+
+`APSIsVirtualMachine` (AirPlaySupport) caches `sysctlbyname("kern.hv_vmm_present")`
+once per process, then clears the flag when the AirPlay setting
+`useWiFiAndAWDLOnVirtualMachine` is non-zero (`APSSettingsGetInt64`, domain
+`com.apple.airplay`, read with `CFPreferencesCopyAppValue`). The AirPlay
+daemons run as mobile, so the value belongs in
+`/private/var/mobile/Library/Preferences/com.apple.airplay.plist` (0600,
+501:501). Written live through vphoned and followed by a reboot, it changes:
+
+- the discovery mode follows the endpoints again, and airplayd creates
+ `APEndpoint-RC` for the HomePod itself;
+- after a clean boot the HomePod's mediaremoted opens its local endpoint
+ (`Open comm channel completed (err=0)`, 0.11 s);
+- the Mac's control session activates and `loadDeviceInfo` returns in 13 ms.
+
+Side effect: airplayd now asks the absent WiFiManager and corewifi about AWDL
+Solo support about once a second (`kNotFoundErr`, `NSXPCConnectionInvalid`).
+
+A direct file write is not enough while the guest runs: cfprefsd keeps
+serving its cached copy until a reboot. The patch below writes through
+CFPreferences instead.
+
+## The audio session: gPTP
+
+With discovery back, the buffered-audio session stalled after pair-setup: the
+receiver (`tvairplayd`, AirPlayReceiver) accepted SETUP, created the session
+(`TP=PTP`), activated its AVAudioSession and NowPlaying, then never answered.
+A guest `spindump` showed the session thread in `CM8021ASClockCreate` →
+TimeSync, blocked on a reply from `com.apple.timesync.expositor`
+(`audioclocksyncd`). `audioclocksyncd` waits for the kernel's
+`IOTimeSyncgPTPManager`, and the IORegistry had none, although
+`IOTimeSyncClockManager` carried `WantsgPTPServices = Yes`.
+
+The cause was the kernelcache mix. It took `IOgPTPPlugin` from the B520
+kernel, whose `IOTimeSyncgPTPManager` personality adds
+`TemperatureSensor = {B520: "PMU tdev1"}`: its start looks up an
+`IOHIDEventService` with that `Product`, logs "could not get matching service"
+and fails on a VM. Apple's VM build in the vphone600 kernel has the same
+personality without the sensor (and without the tvOS Wi-Fi controller). The
+iPhone 26.5 mix already pairs that plugin with the research board's own
+`IOTimeSyncFamily` 1450.2, so the HomePod recipe now pins the same two:
+`IOTimeSyncFamily` from `base`, `IOgPTPPlugin` from `vphone600_26.4_23E5207q`
+(`kextOverrides`). The vphone600 family itself does not link against the 26.5
+kernel: it imports an `IOPlatformExpert` private function the base does not
+provide.
+
+After the relink, restore and CFW (2026-10-27), the guest has
+`IOTimeSyncgPTPManager`, an `IOTimeSyncDomain` and a local clock port. With
+`useWiFiAndAWDLOnVirtualMachine` set, the Mac's Music selected the HomePod and
+played a clip over AirPlay 2 (selected, active, playing); SoundBoard reported
+`mediaState 1`, and the audio came out of the host through the virtio sound
+device. The top cap stays dark while playing: the media glow is the 27.2+
+`system-homepod-exp-sound_glow`.
+
+## The patch: `system-homepod-exp-airplay_vm`
+
+The Data volume is encrypted on the host, so the setting is installed like the
+setup completion: the patch puts the marker `/usr/share/vphone/HomePodAirPlay.plist`
+on the System volume, and the HomePod setup helper (running as mobile at boot)
+does the rest:
+
+- it journals the current value in
+ `/var/mobile/Library/Application Support/vphone/HomePodAirPlayOriginal.plist`
+ (an absent key is recorded as absent);
+- it sets `useWiFiAndAWDLOnVirtualMachine = 1` with `CFPreferencesSetValue`
+ (current user, any host) and synchronizes;
+- only if the value changed, it sends SIGTERM once to mobile's exact
+ `/usr/libexec/airplayd`, `/usr/libexec/tvairplayd` and
+ `/System/Library/PrivateFrameworks/MediaRemote.framework/Support/mediaremoted`,
+ rechecking each identity first; launchd restarts them and they read the new
+ value (`APSIsVirtualMachine` caches it per process);
+- it writes `HomePodAirPlayStatus.plist` (`Enabled`, `Succeeded`, `Changed`,
+ `Restarted`, `Updated`, `Error`).
+
+With the marker gone, the helper restores the journalled value and then deletes
+the journal. Unit tests: `make -C VPhoneGuestComponents test-homepod-setup`
+(`HomePodAirPlayTests`).
+
+Validated on 2026-10-27, bundle `2.13.5-local.47579029`, after removing the
+manually written pref: the environment update staged the marker, and on the next
+boot the status showed `Changed=true`, `Restarted=3`, `Succeeded=true`. The
+journal recorded the key as absent, and the Mac's Music played to the HomePod
+with no manual step.
+
+## Related limits (2026-10-27)
+
+- **Top cap while playing.** 26.5's NowPlayingCap has no media glow. Its only
+ playback effect is a blue `audioTapping` pulse behind the internal default
+ `depictNonGroupLeaders` (suite `com.apple.NowPlayingCap`), drawn only while
+ the local `MRDeviceInfo.isGroupLeader` is false. With the default set for
+ mobile, the LEDs stayed dark playing to the HomePod alone and in a group with
+ the Mac's speakers: in both it leads its own group. Only a follower in a group
+ led by another HomePod or Apple TV would show it.
+- **Setup from a Mac.** With `system-homepod-exp-setup_bypass` off, the
+ HomePod in setup mode drops `_airplay._tcp`/`_raop._tcp` and advertises
+ `_companion-link._tcp` (and, with the guest BTVC patch, `_btvc._tcp`). The
+ macOS Home app cannot add accessories; the Mac's sharingd looks for HomePod
+ setup only over Bluetooth LE. Real setup would need an OS 26+ iPhone guest
+ reaching the HomePod over BTVC.
+- **Top cap input.** The cap's consumer HID events reach SoundBoard; it ignores
+ them in two states. With nothing playing there is no volume category
+ (`Volume State..OFF with current Volume Category..(null)`), so +/- do
+ nothing. While playing, the first press brings NowPlayingCap forward and
+ later presses change the volume (0.90 → 0.85 → 0.90, read with the
+ debug interface's `getVolume:`); the center tap pauses the sender. Siri can
+ also stay the foreground activity while idle (`getAllDebugInfo:`:
+ `Foreground Activity: Siri`); SoundBoard then ignores volume input, even its
+ own `sendButtonCommand:`. What keeps pushing Siri forward is corespeechd's
+ voice-trigger recorder: it asks for 14 channels at 16 kHz (the B520 mic
+ array) from a 2-channel 48 kHz virtio input, AudioQueue fails
+ (`kAudioQueueProperty_ChannelLayout` -50, `prepareRecordForStream` -11795)
+ and it retries about once a second. Turning `VoiceTrigger Enabled` off in
+ mobile's `com.apple.voicetrigger` stops the Siri activations, but on two of
+ two boots the Mac's Music then selected the HomePod without it becoming
+ active (later -15016), while tvairplayd saw no connection; with the value
+ restored, playback works. So it is not shipped as a patch. The root fix is a
+ virtual input that matches the route's 14-channel layout.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift
index 1ddbcfcc..b925ff6c 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift
@@ -61,7 +61,7 @@ public enum FirmwareGuestPatchResolution {
/// Apple TV OTA swap, GPU injection, or plain-arm64 dyld workarounds.
public static let homePodSupportedGuestPatches = tvSupportedGuestPatches
.subtracting([FirmwareGuestSystemPatchSet.tvTPRO])
- .union([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass,
+ .union([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAirPlayVM,
FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome,
FirmwareGuestSystemPatchSet.homePodSiriSpeech,
FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index f881295e..a712f480 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -416,7 +416,16 @@ public enum FirmwareGuestSystemPatchSet {
title: "HomePod setup completion",
summary: "Completes the donor's local AudioAccessory setup state as mobile, prepares SetupAssistant's native launch sentinel and lets SoundBoard initialize its post-setup services. Turning it off restores the prior completion flags at the next boot. Does not provision accounts, activation or a HomeKit home.",
target: .guestFile(path: homePodSetupPath),
- applicability: VPhonePatchApplicability(iOSBase: .major(27)),
+ // 26.5 has the same AudioAccessory gate and SetupAssistant
+ // exports; the helper refuses if one is missing.
+ applicability: VPhonePatchApplicability(iOSBase: .atLeast(major: 26, minor: 5)),
+ ),
+ VPhonePatchDeclaration(
+ identifier: homePodAirPlayVM,
+ title: "HomePod AirPlay on a VM",
+ summary: "Sets AirPlay's own virtual-machine override (useWiFiAndAWDLOnVirtualMachine in mobile's com.apple.airplay) through the HomePod helper, so AirPlay keeps discovery and its own endpoint and a Mac or iPhone can play to the guest. Turning it off restores the prior value at the next boot.",
+ target: .guestFile(path: homePodAirPlayVMPath),
+ applicability: VPhonePatchApplicability(iOSBase: .release(major: 26, minor: 5)),
),
VPhonePatchDeclaration(
identifier: homePodSiriSpeech,
@@ -712,6 +721,8 @@ public enum FirmwareGuestSystemPatchSet {
public static let homePodDisplayPath = "/usr/share/vphone/HomePodDisplay.plist"
public static let homePodSetupBypass = "system-homepod-exp-setup_bypass"
public static let homePodSetupPath = "/usr/share/vphone/HomePodSetup.plist"
+ public static let homePodAirPlayVM = "system-homepod-exp-airplay_vm"
+ public static let homePodAirPlayVMPath = "/usr/share/vphone/HomePodAirPlay.plist"
public static let homePodWelcome = "system-homepod-exp-welcome"
public static let homePodWelcomePath = "/usr/share/vphone/HomePodWelcome.plist"
public static let homePodSiriSpeech = "system-homepod-exp-siri_speech"
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index 182b40ce..7e83d6c5 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -68,7 +68,7 @@ public enum FirmwarePatchSetCatalog {
Set(FirmwareKernelFridaPatchSet.manifest.patches.map(\.identifier))
.union(hypervisorConcealmentPatches)
.union(experimentalIdentityPatches)
- .union([FirmwareGuestSystemPatchSet.otaUserland, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall])
+ .union([FirmwareGuestSystemPatchSet.otaUserland, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAirPlayVM, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall])
.union([FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, FirmwareGuestSystemPatchSet.tvTPRO, FirmwareGuestSystemPatchSet.tvOTAUserland, FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.tvSetupFocus, FirmwareGuestSystemPatchSet.tvLocalActivation, FirmwareGuestSystemPatchSet.tvLegacySetup])
/// ProMotion: the 120 Hz timing for the paravirtual display.
@@ -226,7 +226,7 @@ public enum FirmwarePatchSetCatalog {
freshly restored 26.4 guest does not survive. The HomePod-only top cap is off.
""",
patchSets: bundledReferences,
- selection: .block([FirmwareGuestSystemPatchSet.tvLegacySetup, FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.tvSetupFocus, FirmwareGuestSystemPatchSet.tvLocalActivation, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall]),
+ selection: .block([FirmwareGuestSystemPatchSet.tvLegacySetup, FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.tvSetupFocus, FirmwareGuestSystemPatchSet.tvLocalActivation, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAirPlayVM, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall]),
)
/// The iOS payloads, hooks and shared-cache patches an Apple TV guest has no
@@ -333,10 +333,10 @@ public enum FirmwarePatchSetCatalog {
public static let homePodMiniPreset = VPhonePatchPreset(
identifier: VPhonePatchPreset.homePodMiniIdentifier,
title: "HomePod mini",
- summary: "Research: HomePod mini's own arm64e TVOS IPSW with vphoned, its donor-driven top cap, local setup completion and virtio audio using an audio-only B520 route, without changing the VM product token or adding Apple TV OTA replacement or iPhone display, camera and routing hooks.",
+ summary: "Research: HomePod mini's own arm64e TVOS IPSW with vphoned, its donor-driven top cap, local setup completion, AirPlay's own VM override and virtio audio using an audio-only B520 route, without changing the VM product token or adding Apple TV OTA replacement or iPhone display, camera and routing hooks.",
patchSets: bundledReferences,
selection: .block(
- manualOnlyPatches.subtracting([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall])
+ manualOnlyPatches.subtracting([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAirPlayVM, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall])
.union(tvOSBlockedPatches.subtracting(tvOS27UserlandPatches).subtracting([FirmwareGuestSystemPatchSet.virtioSoundDriver, FirmwareGuestSystemPatchSet.installCoordinationPersona])),
),
)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
index bd29878d..a8e044f0 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
@@ -145,16 +145,20 @@ struct FirmwareGuestPatchResolutionTests {
#expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: [identifier], arm64eUserland: true) == [identifier])
}
- @Test(arguments: [FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct,
+ @Test(arguments: [FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAirPlayVM, FirmwareGuestSystemPatchSet.homePodAudioProduct,
FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech])
func `HomePod optional guest repairs are version gated and never selected for other devices`(identifier: String) throws {
- for base in ["26.4", "27.0", "27.1"] {
+ for base in ["26.4", "26.5", "27.0", "27.1"] {
+ // The setup completion also applies to 26.5, the AirPlay override
+ // only there; the others need 27.
+ let applies = identifier == FirmwareGuestSystemPatchSet.homePodAirPlayVM ? base == "26.5"
+ : base.hasPrefix("27.") || (base == "26.5" && identifier == FirmwareGuestSystemPatchSet.homePodSetupBypass)
for preset in FirmwarePatchSetCatalog.builtInPresets {
let plan = try VPhonePatchPlan.resolve(
preset: preset, patchSets: FirmwarePatchSetCatalog.bundled,
iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion("26.4"),
)
- #expect(plan.isEnabled(identifier) == (base.hasPrefix("27.")
+ #expect(plan.isEnabled(identifier) == (applies
&& identifier != FirmwareGuestSystemPatchSet.homePodAudioProduct
&& preset.identifier == VPhonePatchPreset.homePodMiniIdentifier))
}
@@ -165,6 +169,14 @@ struct FirmwareGuestPatchResolutionTests {
#expect(FirmwareGuestPatchResolution.guestPatchesOff(selectionEnabled: []).contains(identifier))
}
+ @Test func `HomePod AirPlay override is a guest marker for the setup helper`() throws {
+ let airPlay = FirmwareGuestSystemPatchSet.homePodAirPlayVM
+ let declaration = try #require(FirmwarePatchSetCatalog.allDeclarations.first { $0.identifier == airPlay })
+ #expect(declaration.target == .guestFile(path: "/usr/share/vphone/HomePodAirPlay.plist"))
+ #expect(!declaration.bootEssential)
+ #expect(FirmwarePatchSetCatalog.manualOnlyPatches.contains(airPlay))
+ }
+
@Test func `HomePod welcome requires every selected runtime prerequisite but opt out is independent`() throws {
let welcome = FirmwareGuestSystemPatchSet.homePodWelcome
let dependencies = FirmwareGuestPatchResolution.homePodWelcomeDependencies
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index ae7a6ff6..3c5b1e84 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -229,6 +229,9 @@ struct VPhoneCustomFirmwareInstaller {
if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodSetupBypass), device.family != .homePod {
throw ValidationError("The HomePod setup-completion patch is supported only for a HomePod guest.")
}
+ if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodAirPlayVM), device.family != .homePod {
+ throw ValidationError("The HomePod AirPlay patch is supported only for a HomePod guest.")
+ }
if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodAudioProduct), device.family != .homePod {
throw ValidationError("The HomePod audio-product patch is supported only for a HomePod guest.")
}
@@ -1556,6 +1559,21 @@ struct VPhoneCustomFirmwareInstaller {
} else {
try system.removeItem(setupPath)
}
+ // The same helper sets AirPlay's VM override as mobile and restarts the
+ // AirPlay daemons when the value changed; removing the marker restores it.
+ let airPlay = FirmwareGuestSystemPatchSet.homePodAirPlayVM
+ let airPlayPath = String(FirmwareGuestSystemPatchSet.homePodAirPlayVMPath.dropFirst())
+ if plan?.isEnabled(airPlay) == true {
+ guard guestDevice.family == .homePod else {
+ throw ValidationError("HomePod AirPlay on a VM requires a HomePod guest.")
+ }
+ _ = try system.directory("usr/share/vphone", create: true, mode: 0o755)
+ let policy = try PropertyListSerialization.data(fromPropertyList: ["Enabled": true], format: .binary, options: 0)
+ try system.writeFile(airPlayPath, contents: policy, mode: 0o644, owner: Self.guestOwner)
+ live.insert(airPlay)
+ } else {
+ try system.removeItem(airPlayPath)
+ }
let speech = FirmwareGuestSystemPatchSet.homePodSiriSpeech
let speechPath = String(FirmwareGuestSystemPatchSet.homePodSiriSpeechPath.dropFirst())
if plan?.isEnabled(speech) == true {
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist
index c782e473..de590441 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist
@@ -99,6 +99,7 @@
<string>system-mobileactivationd-exp-tv_activation</string>
<string>system-tv-exp-legacy_setup</string>
<string>system-homepod-exp-setup_bypass</string>
+ <string>system-homepod-exp-airplay_vm</string>
<string>system-homepod-exp-welcome</string>
<string>system-homepod-exp-siri_speech</string>
<string>system-homepod-exp-ota_userland</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
index 5f8f0398..e47a9e81 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
@@ -143,7 +143,7 @@
</array>
</dict>
<key>Summary</key>
- <string>Research: HomePod mini's own arm64e TVOS IPSW with vphoned, its donor-driven top cap, local setup completion and virtio audio using an audio-only B520 route, without changing the VM product token or adding Apple TV OTA replacement or iPhone display, camera and routing hooks.</string>
+ <string>Research: HomePod mini's own arm64e TVOS IPSW with vphoned, its donor-driven top cap, local setup completion, AirPlay's own VM override and virtio audio using an audio-only B520 route, without changing the VM product token or adding Apple TV OTA replacement or iPhone display, camera and routing hooks.</string>
<key>Title</key>
<string>HomePod mini</string>
</dict>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
index df8f06b2..0ffe9fbf 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
@@ -75,6 +75,7 @@
<array>
<string>system-homepod-exp-top_cap</string>
<string>system-homepod-exp-setup_bypass</string>
+ <string>system-homepod-exp-airplay_vm</string>
<string>system-homepod-exp-welcome</string>
<string>system-homepod-exp-siri_speech</string>
<string>system-homepod-exp-ota_userland</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
index 927ddb95..d6386bc3 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
@@ -76,6 +76,7 @@
<string>system-tv-exp-legacy_setup</string>
<string>system-homepod-exp-top_cap</string>
<string>system-homepod-exp-setup_bypass</string>
+ <string>system-homepod-exp-airplay_vm</string>
<string>system-homepod-exp-welcome</string>
<string>system-homepod-exp-siri_speech</string>
<string>system-homepod-exp-ota_userland</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
index bbedc0d9..fbcce414 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
@@ -75,6 +75,7 @@
<array>
<string>system-homepod-exp-top_cap</string>
<string>system-homepod-exp-setup_bypass</string>
+ <string>system-homepod-exp-airplay_vm</string>
<string>system-homepod-exp-welcome</string>
<string>system-homepod-exp-siri_speech</string>
<string>system-homepod-exp-ota_userland</string>
diff --git a/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.h b/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.h
index b0b770b7..8ecc5004 100644
--- a/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.h
+++ b/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.h
@@ -11,3 +11,10 @@ typedef struct {
// exact Apple setup executable may receive SIGTERM. No escalation to SIGKILL.
BOOL VPHomePodSetupStopProcesses(VPHomePodSetupProcessAPI api, uid_t user,
NSUInteger maximumPolls, void (^wait)(void), NSError **error);
+
+// AirPlay caches APSIsVirtualMachine once per process. After the VM setting
+// changed, mobile's exact AirPlay daemons get one SIGTERM each, and launchd
+// starts them again with the new value. Nothing else is signalled.
+NSArray<NSString *> *VPHomePodAirPlayExecutables(void);
+BOOL VPHomePodRestartProcesses(VPHomePodSetupProcessAPI api, uid_t user, NSArray<NSString *> *executables,
+ NSUInteger *signaled, NSError **error);
diff --git a/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.m b/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.m
index 16dd5f45..3de349de 100644
--- a/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.m
+++ b/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.m
@@ -15,7 +15,15 @@ static BOOL VPProcessError(NSError **error, NSString *description) {
return NO;
}
-static NSArray<NSNumber *> *VPSetupProcesses(VPHomePodSetupProcessAPI api, uid_t user, NSError **error) {
+static BOOL VPPathMatches(const char *path, NSArray<NSString *> *executables) {
+ for (NSString *executable in executables) {
+ if (strcmp(path, executable.fileSystemRepresentation) == 0) return YES;
+ }
+ return NO;
+}
+
+static NSArray<NSNumber *> *VPOwnedProcesses(VPHomePodSetupProcessAPI api, uid_t user, NSArray<NSString *> *executables,
+ NSError **error) {
int needed = api.listPIDs(VPProcUIDOnly, user, NULL, 0);
if (needed <= 0) { VPProcessError(error, @"Could not enumerate mobile's processes."); return nil; }
NSUInteger capacity = (NSUInteger)needed + 128 * sizeof(pid_t);
@@ -39,7 +47,7 @@ static NSArray<NSNumber *> *VPSetupProcesses(VPHomePodSetupProcessAPI api, uid_t
}
continue; // Exited during enumeration, or no executable remains.
}
- if ((size_t)length < sizeof(path) && strcmp(path, VPSetupExecutable) == 0) [found addObject:@(pids[index])];
+ if ((size_t)length < sizeof(path) && VPPathMatches(path, executables)) [found addObject:@(pids[index])];
}
return found;
}
@@ -55,7 +63,7 @@ BOOL VPHomePodSetupStopProcesses(VPHomePodSetupProcessAPI api, uid_t user,
NSMutableSet *signaled = [NSMutableSet set];
NSUInteger quietPolls = 0;
for (NSUInteger poll = 0; poll <= maximumPolls; poll++) {
- NSArray<NSNumber *> *pids = VPSetupProcesses(api, user, error);
+ NSArray<NSNumber *> *pids = VPOwnedProcesses(api, user, @[@(VPSetupExecutable)], error);
if (!pids) return NO;
// Observe a short quiet interval too: an app launch requested before
// completion may still have been in flight when the first scan ran.
@@ -76,3 +84,30 @@ BOOL VPHomePodSetupStopProcesses(VPHomePodSetupProcessAPI api, uid_t user,
}
return VPProcessError(error, @"HomePod setup is still running after its graceful completion deadline; journal retained.");
}
+
+NSArray<NSString *> *VPHomePodAirPlayExecutables(void) {
+ return @[@"/usr/libexec/airplayd", @"/usr/libexec/tvairplayd",
+ @"/System/Library/PrivateFrameworks/MediaRemote.framework/Support/mediaremoted"];
+}
+
+BOOL VPHomePodRestartProcesses(VPHomePodSetupProcessAPI api, uid_t user, NSArray<NSString *> *executables,
+ NSUInteger *signaled, NSError **error) {
+ if (signaled) *signaled = 0;
+ if (user != 501 || !api.listPIDs || !api.processPath || !api.signalProcess || !executables.count) {
+ return VPProcessError(error, @"Restarting AirPlay requires mobile and the native process APIs.");
+ }
+ NSArray<NSNumber *> *pids = VPOwnedProcesses(api, user, executables, error);
+ if (!pids) return NO;
+ for (NSNumber *pid in pids) {
+ // The identity is checked again right before the signal, as for setup.
+ char path[PATH_MAX] = {0};
+ int length = api.processPath(pid.intValue, path, sizeof(path));
+ if (length <= 0 || (size_t)length >= sizeof(path) || !VPPathMatches(path, executables)) continue;
+ if (api.signalProcess(pid.intValue, SIGTERM) != 0) {
+ if (errno == ESRCH) continue;
+ return VPProcessError(error, @"Could not restart an AirPlay daemon.");
+ }
+ if (signaled) *signaled += 1;
+ }
+ return YES;
+}
diff --git a/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.h b/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.h
index a6ce49f4..30c893ca 100644
--- a/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.h
+++ b/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.h
@@ -6,6 +6,18 @@ NSArray<NSString *> *VPHomePodSetupKeys(void);
BOOL VPHomePodSetupUpdate(BOOL enabled, NSURL *journalURL, NSDictionary<NSString *, id> *current,
void (^setValue)(NSString *, id), BOOL (^synchronize)(void), NSError **error);
+// AirPlay's own override for a virtual machine (AirPlaySupport reads it in
+// APSIsVirtualMachine, domain com.apple.airplay): with it set, AirPlay keeps
+// discovery and its own endpoint on a VM.
+NSArray<NSString *> *VPHomePodAirPlayKeys(void);
+
+// The journalled update both use: while enabled, each key gets its value from
+// enabledValues; turning it off restores exactly the recorded originals,
+// including which keys were absent. The journal is written before any value.
+BOOL VPHomePodPreferenceUpdate(NSArray<NSString *> *keys, NSDictionary<NSString *, id> *enabledValues,
+ BOOL enabled, NSURL *journalURL, NSDictionary<NSString *, id> *current,
+ void (^setValue)(NSString *, id), BOOL (^synchronize)(void), NSError **error);
+
// Call after preferences synchronize. Native prepare publishes a new sentinel's
// completion itself; only an already-completed state needs an explicit replay.
BOOL VPHomePodSetupPrepare(BOOL enabled, BOOL expectedNeedsSetup, BOOL expectedCompleted,
diff --git a/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.m b/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.m
index 6c1fa643..800e80d4 100644
--- a/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.m
+++ b/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.m
@@ -4,6 +4,10 @@ NSArray<NSString *> *VPHomePodSetupKeys(void) {
return @[@"SetupDone", @"SetupFinishedAllSteps"];
}
+NSArray<NSString *> *VPHomePodAirPlayKeys(void) {
+ return @[@"useWiFiAndAWDLOnVirtualMachine"];
+}
+
static BOOL VPSetupError(NSError **error, NSString *description) {
if (error) *error = [NSError errorWithDomain:@"com.vphone.homepod-setup" code:1
userInfo:@{NSLocalizedDescriptionKey: description}];
@@ -12,6 +16,14 @@ static BOOL VPSetupError(NSError **error, NSString *description) {
BOOL VPHomePodSetupUpdate(BOOL enabled, NSURL *journalURL, NSDictionary<NSString *, id> *current,
void (^setValue)(NSString *, id), BOOL (^synchronize)(void), NSError **error) {
+ NSMutableDictionary *values = [NSMutableDictionary dictionary];
+ for (NSString *key in VPHomePodSetupKeys()) values[key] = @YES;
+ return VPHomePodPreferenceUpdate(VPHomePodSetupKeys(), values, enabled, journalURL, current, setValue, synchronize, error);
+}
+
+BOOL VPHomePodPreferenceUpdate(NSArray<NSString *> *keys, NSDictionary<NSString *, id> *enabledValues,
+ BOOL enabled, NSURL *journalURL, NSDictionary<NSString *, id> *current,
+ void (^setValue)(NSString *, id), BOOL (^synchronize)(void), NSError **error) {
NSFileManager *files = NSFileManager.defaultManager;
NSDictionary *journal = nil;
if ([files fileExistsAtPath:journalURL.path]) {
@@ -21,20 +33,20 @@ BOOL VPHomePodSetupUpdate(BOOL enabled, NSURL *journalURL, NSDictionary<NSString
if (![journal isKindOfClass:NSDictionary.class] || ![journal[@"Version"] isEqual:@1]
|| ![journal[@"Original"] isKindOfClass:NSDictionary.class]
|| ![journal[@"Absent"] isKindOfClass:NSArray.class]) {
- return VPSetupError(error, @"Refusing an invalid HomePod setup journal.");
+ return VPSetupError(error, @"Refusing an invalid HomePod preference journal.");
}
NSMutableSet *recorded = [NSMutableSet setWithArray:[journal[@"Original"] allKeys]];
[recorded addObjectsFromArray:journal[@"Absent"]];
- if (![recorded isEqualToSet:[NSSet setWithArray:VPHomePodSetupKeys()]]
+ if (![recorded isEqualToSet:[NSSet setWithArray:keys]]
|| [[journal[@"Original"] allKeys] count] + [journal[@"Absent"] count] != recorded.count) {
- return VPSetupError(error, @"HomePod setup journal contains unexpected or duplicate keys.");
+ return VPSetupError(error, @"HomePod preference journal contains unexpected or duplicate keys.");
}
}
if (!enabled && !journal) return YES;
if (enabled && !journal) {
NSMutableDictionary *original = [NSMutableDictionary dictionary];
NSMutableArray *absent = [NSMutableArray array];
- for (NSString *key in VPHomePodSetupKeys()) {
+ for (NSString *key in keys) {
if (current[key]) original[key] = current[key];
else [absent addObject:key];
}
@@ -44,15 +56,15 @@ BOOL VPHomePodSetupUpdate(BOOL enabled, NSURL *journalURL, NSDictionary<NSString
NSData *data = [NSPropertyListSerialization dataWithPropertyList:journal
format:NSPropertyListBinaryFormat_v1_0 options:0 error:error];
// Persist the inverse before touching preferences. A failed write must
- // never leave completion flags whose original values cannot be restored.
+ // never leave values whose originals cannot be restored.
if (!data || ![data writeToURL:journalURL options:NSDataWritingAtomic error:error]) return NO;
if (![files setAttributes:@{NSFilePosixPermissions: @0600} ofItemAtPath:journalURL.path error:error]) return NO;
}
- for (NSString *key in VPHomePodSetupKeys()) {
- setValue(key, enabled ? @YES : journal[@"Original"][key]);
+ for (NSString *key in keys) {
+ setValue(key, enabled ? enabledValues[key] : journal[@"Original"][key]);
}
- if (!synchronize()) return VPSetupError(error, @"Could not synchronize HomePod setup preferences; journal retained.");
- // The caller must prepare and verify the native launch sentinel before
+ if (!synchronize()) return VPSetupError(error, @"Could not synchronize HomePod preferences; journal retained.");
+ // For setup, the caller must prepare and verify the native launch sentinel before
// deleting a restored journal. Preference synchronization alone is not
// proof that SoundBoard sees the new setup state.
return YES;
diff --git a/VPhoneGuestComponents/HomePodSetup/main.m b/VPhoneGuestComponents/HomePodSetup/main.m
index 7cf2f66f..07c77706 100644
--- a/VPhoneGuestComponents/HomePodSetup/main.m
+++ b/VPhoneGuestComponents/HomePodSetup/main.m
@@ -1,4 +1,4 @@
-// Run as mobile by launchd: the donor SoundBoard writes current-user values,
+// Run as mobile by launchd: the donor SoundBoard and AirPlay read current-user values,
// and SetupAssistant's launch sentinel is a per-user POSIX named semaphore.
#import "HomePodSetupState.h"
#import "HomePodSetupProcesses.h"
@@ -8,18 +8,18 @@
#import <signal.h>
#import <unistd.h>
-int main(void) {
+static NSString *const VPStateDirectory = @"/var/mobile/Library/Application Support/vphone";
+
+// The setup completion: SetupAssistant's two keys, its native sentinel, and the
+// end of a pending HPSetup session.
+static BOOL VPRunSetup(void) {
@autoreleasepool {
- if (getuid() != 501 || geteuid() != 501) {
- NSLog(@"HomePod setup maintenance must run as mobile (501).");
- return 1;
- }
- NSString *directory = @"/var/mobile/Library/Application Support/vphone";
+ NSString *directory = VPStateDirectory;
NSURL *journal = [NSURL fileURLWithPath:[directory stringByAppendingPathComponent:@"HomePodSetupOriginal.plist"]];
NSDictionary *policy = [NSDictionary dictionaryWithContentsOfFile:@"/usr/share/vphone/HomePodSetup.plist"];
BOOL enabled = [policy[@"Enabled"] isEqual:@YES];
BOOL hadJournal = [NSFileManager.defaultManager fileExistsAtPath:journal.path];
- if (!enabled && !hadJournal) return 0;
+ if (!enabled && !hadJournal) return YES;
void *framework = dlopen("/System/Library/PrivateFrameworks/SetupAssistant.framework/SetupAssistant", RTLD_NOW);
void (*prepare)(void) = framework ? dlsym(framework, "BYSetupAssistantPrepareLaunchSentinel") : NULL;
@@ -89,14 +89,89 @@ int main(void) {
}
}
}
- [NSFileManager.defaultManager createDirectoryAtPath:directory withIntermediateDirectories:YES
- attributes:@{NSFilePosixPermissions: @0700} error:NULL];
NSMutableDictionary *status = [@{@"Enabled": @(enabled), @"Succeeded": @(success), @"Updated": NSDate.date} mutableCopy];
if (needsSetup) status[@"NeedsSetup"] = @(needsSetup());
if (completed) status[@"CompletedInitialRun"] = @(completed());
if (error) status[@"Error"] = error.localizedDescription;
[status writeToFile:[directory stringByAppendingPathComponent:@"HomePodSetupStatus.plist"] atomically:YES];
NSLog(@"HomePod setup maintenance: %@", status);
- return success ? 0 : 1;
+ return success;
+ }
+}
+
+// AirPlay's own VM override, useWiFiAndAWDLOnVirtualMachine in mobile's
+// com.apple.airplay. AirPlaySupport reads it once per process, so the AirPlay
+// daemons restart only when this run changed the value.
+static BOOL VPRunAirPlay(void) {
+ @autoreleasepool {
+ NSString *directory = VPStateDirectory;
+ NSURL *journal = [NSURL fileURLWithPath:[directory stringByAppendingPathComponent:@"HomePodAirPlayOriginal.plist"]];
+ NSDictionary *policy = [NSDictionary dictionaryWithContentsOfFile:@"/usr/share/vphone/HomePodAirPlay.plist"];
+ BOOL enabled = [policy[@"Enabled"] isEqual:@YES];
+ BOOL hadJournal = [NSFileManager.defaultManager fileExistsAtPath:journal.path];
+ if (!enabled && !hadJournal) return YES;
+
+ CFStringRef domain = CFSTR("com.apple.airplay");
+ CFPreferencesSynchronize(domain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+ NSMutableDictionary *current = [NSMutableDictionary dictionary];
+ for (NSString *key in VPHomePodAirPlayKeys()) {
+ id value = CFBridgingRelease(CFPreferencesCopyValue((__bridge CFStringRef)key, domain,
+ kCFPreferencesCurrentUser, kCFPreferencesAnyHost));
+ if (value) current[key] = value;
+ }
+ NSMutableDictionary *values = [NSMutableDictionary dictionary];
+ for (NSString *key in VPHomePodAirPlayKeys()) values[key] = @1;
+ NSError *error = nil;
+ BOOL success = VPHomePodPreferenceUpdate(VPHomePodAirPlayKeys(), values, enabled, journal, current,
+ ^(NSString *key, id value) {
+ CFPreferencesSetValue((__bridge CFStringRef)key, (__bridge CFPropertyListRef)value, domain,
+ kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+ }, ^BOOL {
+ return CFPreferencesSynchronize(domain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+ }, &error);
+ BOOL changed = NO;
+ NSUInteger restarted = 0;
+ if (success) {
+ for (NSString *key in VPHomePodAirPlayKeys()) {
+ id now = CFBridgingRelease(CFPreferencesCopyValue((__bridge CFStringRef)key, domain,
+ kCFPreferencesCurrentUser, kCFPreferencesAnyHost));
+ if (!(now == current[key] || [now isEqual:current[key]])) changed = YES;
+ }
+ if (changed) {
+ void *processLibrary = dlopen("/usr/lib/libproc.dylib", RTLD_NOW);
+ VPHomePodSetupProcessAPI api = {
+ .listPIDs = processLibrary ? dlsym(processLibrary, "proc_listpids") : NULL,
+ .processPath = processLibrary ? dlsym(processLibrary, "proc_pidpath") : NULL,
+ .signalProcess = kill,
+ };
+ success = VPHomePodRestartProcesses(api, getuid(), VPHomePodAirPlayExecutables(), &restarted, &error);
+ }
+ // The journal goes only once the restored value is in place.
+ if (success && !enabled) success = [NSFileManager.defaultManager removeItemAtURL:journal error:&error];
+ }
+ NSMutableDictionary *status = [@{@"Enabled": @(enabled), @"Succeeded": @(success), @"Changed": @(changed),
+ @"Restarted": @(restarted), @"Updated": NSDate.date} mutableCopy];
+ if (error) status[@"Error"] = error.localizedDescription;
+ [status writeToFile:[directory stringByAppendingPathComponent:@"HomePodAirPlayStatus.plist"] atomically:YES];
+ NSLog(@"HomePod AirPlay maintenance: %@", status);
+ return success;
+ }
+}
+
+int main(void) {
+ @autoreleasepool {
+ if (getuid() != 501 || geteuid() != 501) {
+ NSLog(@"HomePod setup maintenance must run as mobile (501).");
+ return 1;
+ }
+ // Both journals live here and are written before any preference, so
+ // the directory must exist before either half runs.
+ [NSFileManager.defaultManager createDirectoryAtPath:VPStateDirectory withIntermediateDirectories:YES
+ attributes:@{NSFilePosixPermissions: @0700} error:NULL];
+ // Independent: a failure of one is retried by launchd without
+ // leaving the other undone.
+ BOOL setup = VPRunSetup();
+ BOOL airPlay = VPRunAirPlay();
+ return setup && airPlay ? 0 : 1;
}
}
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index cb1148df..1ad69a48 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -444,6 +444,9 @@ test-homepod-setup:
xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -IHomePodSetup \
-o $(OUT)/HomePodSetupProcessTests Tests/HomePodSetupProcessTests.m HomePodSetup/HomePodSetupProcesses.m -framework Foundation
@$(OUT)/HomePodSetupProcessTests
+ xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -IHomePodSetup \
+ -o $(OUT)/HomePodAirPlayTests Tests/HomePodAirPlayTests.m HomePodSetup/HomePodSetupState.m HomePodSetup/HomePodSetupProcesses.m -framework Foundation
+ @$(OUT)/HomePodAirPlayTests
.PHONY: test-attitude
test-attitude:
diff --git a/VPhoneGuestComponents/Tests/HomePodAirPlayTests.m b/VPhoneGuestComponents/Tests/HomePodAirPlayTests.m
new file mode 100644
index 00000000..21c1a64d
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/HomePodAirPlayTests.m
@@ -0,0 +1,73 @@
+#import "HomePodSetupState.h"
+#import "HomePodSetupProcesses.h"
+#include <assert.h>
+#include <errno.h>
+#include <signal.h>
+#include <string.h>
+
+#define CHECK(condition) do { if (!(condition)) { NSLog(@"Failed at line %d: %s", __LINE__, #condition); abort(); } } while (0)
+
+// mobile's processes: an unrelated one, airplayd, a look-alike outside
+// /usr/libexec, tvairplayd and mediaremoted.
+static const pid_t pids[] = {7, 120, 121, 122, 123};
+static NSMutableArray<NSNumber *> *signalled;
+
+static int listPIDs(uint32_t type, uint32_t user, void *buffer, int capacity) {
+ assert(type == 4 && user == 501);
+ if (!buffer) return sizeof(pids);
+ assert(capacity >= (int)sizeof(pids));
+ memcpy(buffer, pids, sizeof(pids));
+ return sizeof(pids);
+}
+static int processPath(int pid, void *buffer, uint32_t capacity) {
+ const char *path = "/usr/bin/unrelated";
+ if (pid == 120) path = "/usr/libexec/airplayd";
+ if (pid == 121) path = "/tmp/usr/libexec/airplayd";
+ if (pid == 122) path = "/usr/libexec/tvairplayd";
+ if (pid == 123) path = "/System/Library/PrivateFrameworks/MediaRemote.framework/Support/mediaremoted";
+ assert(strlen(path) + 1 < capacity);
+ strcpy(buffer, path);
+ return (int)strlen(path);
+}
+static int signalProcess(pid_t pid, int signal) {
+ assert(signal == SIGTERM);
+ [signalled addObject:@(pid)];
+ return 0;
+}
+
+int main(void) {
+ @autoreleasepool {
+ // The VM override round-trips through the journal like the setup keys.
+ NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:NSUUID.UUID.UUIDString];
+ NSURL *journal = [NSURL fileURLWithPath:[path stringByAppendingPathComponent:@"state/airplay.plist"]];
+ NSMutableDictionary *preferences = [@{@"Unrelated": @"unchanged"} mutableCopy];
+ void (^set)(NSString *, id) = ^(NSString *key, id value) {
+ if (value) preferences[key] = value;
+ else [preferences removeObjectForKey:key];
+ };
+ NSDictionary *values = @{@"useWiFiAndAWDLOnVirtualMachine": @1};
+ NSError *error = nil;
+ CHECK([VPHomePodAirPlayKeys() isEqual:@[@"useWiFiAndAWDLOnVirtualMachine"]]);
+ CHECK(VPHomePodPreferenceUpdate(VPHomePodAirPlayKeys(), values, YES, journal, preferences, set, ^BOOL { return YES; }, &error));
+ CHECK([preferences[@"useWiFiAndAWDLOnVirtualMachine"] isEqual:@1]);
+ CHECK([preferences[@"Unrelated"] isEqual:@"unchanged"]);
+ CHECK(VPHomePodPreferenceUpdate(VPHomePodAirPlayKeys(), values, NO, journal, preferences, set, ^BOOL { return YES; }, &error));
+ CHECK(preferences[@"useWiFiAndAWDLOnVirtualMachine"] == nil); // It was absent before.
+ // A setup journal cannot be replayed as an AirPlay one.
+ [NSFileManager.defaultManager removeItemAtURL:journal error:NULL];
+ CHECK(VPHomePodSetupUpdate(YES, journal, preferences, set, ^BOOL { return YES; }, &error));
+ CHECK(!VPHomePodPreferenceUpdate(VPHomePodAirPlayKeys(), values, NO, journal, preferences, set, ^BOOL { return YES; }, &error));
+
+ // Only mobile's exact AirPlay daemons get one SIGTERM.
+ signalled = [NSMutableArray array];
+ VPHomePodSetupProcessAPI api = {.listPIDs = listPIDs, .processPath = processPath, .signalProcess = signalProcess};
+ NSUInteger restarted = 0;
+ CHECK(VPHomePodRestartProcesses(api, 501, VPHomePodAirPlayExecutables(), &restarted, &error));
+ CHECK(restarted == 3);
+ CHECK([signalled isEqual:(@[@120, @122, @123])]);
+ CHECK(!VPHomePodRestartProcesses(api, 0, VPHomePodAirPlayExecutables(), &restarted, &error));
+ [NSFileManager.defaultManager removeItemAtPath:path error:NULL];
+ NSLog(@"HomePod AirPlay preference and restart tests passed");
+ }
+ return 0;
+}