Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

watchOS: MediaExperience power budget fix

Luke69393775aee4
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 33e32fc9..81c6c751 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 budget runtime check (2026-10-31).** A fresh Watch7,18 VM on
+> 26.4 (23T240): native Resonate text-message
+> alert completed with `BudgetNotAvailable = 0`; explicit Playback-category
+> AVAudioPlayer prepared, started and advanced on Speaker/PuffinOutput. HAL I/O
+> ran on both paths. Untruncated live audiomxd captures show PID 110 throughout
+> and none of the previous budget failures. The owner confirmed audible
+> output. See [budget runtime check](Guest/watch_audio.md#mediaexperience-budget-fresh-restore-runtime-check-2026-10-31).
+
+> **Watch audio budget patch (2026-10-31).** The `filesystem-exp-watch_audio`
+> payload includes a MediaExperience budget patch: `patchWatchAudioBudget`
+> NOPs the `CMSMDeviceState_UpdateDeviceClass` token-mismatch branch in the arm64e
+> cache so a watch VM takes MediaExperience's virtual-device budget exit,
+> version-gated to watchOS 26.4 and reported as the
+> `filesystem-exp-watch_audio.budget_device_class` sub-record. Covered by an
+> always-on synthetic discovery test plus fixture-gated real-image tests; its
+> runtime effect on Playback media is confirmed on a 26.4 restore (host
+> audibility confirmed; see the budget runtime check above). See [watch audio](Guest/watch_audio.md).
+
> **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
@@ -8,7 +26,7 @@
> 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.
+> depends on the 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
@@ -4279,7 +4297,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 |
+| `filesystem-exp-watch_audio` | Watch images only, via `watchos`: the watchOS-marked virtio sound HAL plugin, a generic-DSP speaker chain, the three VirtualAudio playback routing-gate bypasses, and on watchOS 26.4 the MediaExperience device-class NOP for the virtual-device audio budget. Cannot be toggled 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
index 592801fd..17fa3034 100644
--- a/Research/Guest/watch_audio.md
+++ b/Research/Guest/watch_audio.md
@@ -1,5 +1,38 @@
# Apple Watch audio through virtio-snd
+## MediaExperience budget fresh-restore runtime check (2026-10-31)
+
+A fresh Watch7,18 VM was restored without a template on watchOS 26.4 / 23T240.
+The full Debug bundle passed build/admission and Launchpad host preflight.
+Restore-image preparation applied the three routing gates and the MediaExperience
+classifier patch at unslid `0x189a34710`; `.03` page slot 3053 was rehashed
+successfully, with no skipped pages.
+
+Two isolated vphoned script sessions exercised distinct paths:
+
+- **Native system sound:** ToneLibrary `TLAlertConfiguration` type 2 (text
+ message), tone `texttone:Resonate`, played through `TLAlert.play()`. The
+ audiomxd capture shows `Alert_Messages_1_Haptic`, `suppressesAudio = NO`,
+ `Audio = 1` and `BudgetNotAvailable = 0`. PuffinOutput HAL I/O entered Running,
+ and SystemSoundServer reported sound completion after 4929 ms. This tests
+ the native alert path, beyond direct AVAudioPlayer ringtone playback.
+- **Playback category:** AVAudioSession accepted
+ `AVAudioSessionCategoryPlayback` and activation; AVAudioPlayer of
+ `/System/Library/Audio/UISounds/nano/NanoRingtone3.caf` returned true from
+ preparation and play. Playback remained active after five seconds, with
+ `currentTime = 4.809520833333333`, on Speaker / PuffinOutput. MediaExperience
+ logged a `[MediaPlayback/Default]` session starting and stopping output on
+ `VirtualAudioDevice_Default`, and HAL I/O entered Running.
+
+The 15-second system-sound capture contained 690 entries and the 18-second
+Playback capture 1138; neither was truncated. Both show only audiomxd PID 110.
+Neither contains `unable to take power budget`, `budget request failed`,
+`suppressing audio and haptics`, -16982 or AudioQueue 2003329396. Thus the
+previous budget failure did not recur in either tested path. These are runtime
+route/playback and log checks, and the owner confirmed audible output on the
+host. Long-duration playback, other categories and other releases remain
+separate validation.
+
## Scope
This puts the existing virtio-snd output transport on an Apple Watch guest
@@ -91,8 +124,8 @@ 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.
+(music, text tones and notification tones) still depends on the MediaExperience
+power-budget fix described below.
## Speaker graph construction
@@ -228,8 +261,12 @@ Not established here:
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.
+ take a path that needs no media budget. The payload now applies the budget
+ patch on watchOS 26.4 (`patchWatchAudioBudget`, which NOPs the
+ `CMSMDeviceState_UpdateDeviceClass` token-mismatch branch so MediaExperience
+ takes its virtual-device budget exit) and skips it on every other version;
+ its runtime effect on Playback media is confirmed on a 26.4 restore (see the
+ budget runtime check, audible to the owner).
- Long-duration clock accuracy, every session category, watch microphone
routing and AirPlay lifetime are untested.
@@ -250,9 +287,9 @@ on watchOS 26.4; this is not a claim about every model or release.
| 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 |
+| Apple audio code | Native product route; iPhone VirtualAudio instruction/tuning fixes disabled | Native product route; generic DSP speaker chain, three VirtualAudio routing-gate bypasses, and the MediaExperience device-class budget patch on watchOS 26.4 |
| 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 |
+| 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 need the MediaExperience budget patch, which the payload now applies on watchOS 26.4, its runtime effect confirmed on a 26.4 restore (audible to the owner) |
| 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
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift
index c7e6909f..687a6be9 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift
@@ -218,6 +218,7 @@ public final class CryptexFilesystemPatcher: BufferedPatcher {
if gate.isEnabled(FirmwareRestoreImagePatchSet.watchAudio), applies(FirmwareRestoreImagePatchSet.watchAudio) {
print("- Adding the watch speaker…")
try addWatchAudio(targetMount: targetMount)
+ try patchWatchAudioBudget(targetMount: targetMount)
}
try removeHostEventLog(mount: targetMount)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherWatchAudio.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherWatchAudio.swift
index 61c8d066..54cce983 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherWatchAudio.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherWatchAudio.swift
@@ -120,4 +120,19 @@ extension CryptexFilesystemPatcher {
)
}
}
+
+ func patchWatchAudioBudget(targetMount: String) throws {
+ let version = try getProductVersion()
+ guard CustomFirmwareWatchAudioBudget.supports(VPhoneVersion(version)) else {
+ print(" [!] Watch audio budget: Playback audio class fix not verified on \(version), so not applied")
+ print(" Local-speaker Playback sessions will fail the MediaExperience power budget")
+ return
+ }
+
+ let cache = try DyldSharedCacheChunkSet(
+ directory: URL(filePath: targetMount).appending(path: "System/Library/Caches/com.apple.dyld"),
+ architecture: "arm64e",
+ )
+ try CustomFirmwareWatchAudioBudget.patchCache(in: cache)
+ }
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Dyld/CustomFirmwareWatchAudioBudget.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Dyld/CustomFirmwareWatchAudioBudget.swift
new file mode 100644
index 00000000..0faa268a
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Dyld/CustomFirmwareWatchAudioBudget.swift
@@ -0,0 +1,240 @@
+// CustomFirmwareWatchAudioBudget.swift — let MediaExperience treat a watch VM as virtual.
+//
+// A watch VM has no ApplePPM, so Playback-category audio fails the MediaExperience
+// power budget. MediaExperience already skips the budget for a virtual device, but
+// `_CMSMDeviceState_UpdateDeviceClass` sets that flag only for two legacy
+// `MGGetProductType` tokens and never asks MobileGestalt `IsVirtualDevice`, so a VM
+// misses it. This NOPs the first token-mismatch branch so the classifier falls into
+// its existing set-virtual block: one instruction, with the second comparison and
+// the flag stores kept as anchors. watchOS 26.4 / 23T240 only; disassembly in
+// `Research/Guest/watch_audio.md`.
+
+import Foundation
+import MachOKit
+import VPhonePatchKit
+
+/// Selects MediaExperience's existing virtual-device budget policy on a watch VM.
+public enum CustomFirmwareWatchAudioBudget {
+ public static let patchID = "filesystem-exp-watch_audio"
+ public static let imagePath = "/System/Library/PrivateFrameworks/MediaExperience.framework/MediaExperience"
+ public static let stdoutLog: @Sendable (String) -> Void = { print($0) }
+
+ static func supports(_ version: VPhoneVersion?) -> Bool {
+ version?.major == 26 && version?.minor == 4
+ }
+
+ static let classifier = "_CMSMDeviceState_UpdateDeviceClass"
+ static let getter = "_CMSMDeviceState_IsAVirtualDevice"
+ static let consumers = ["_cmsmSystemSoundNeedsMediaBudget", "_CMSUtility_DoesSessionNeedAudioBudget"]
+
+ /// The two legacy VM product tokens `_CMSMDeviceState_UpdateDeviceClass`
+ /// compares `MGGetProductType` against, in the `mov w8, #lo` / `movk w8,
+ /// #hi, lsl #16` halves the comparison is built from. 23T240: `0xfc319ad9`
+ /// at the first comparison, `0x71c6787b` at the second. Read from
+ /// `_CMSMDeviceState_UpdateDeviceClass` at `0x189a34620`; both must still
+ /// be present or the classifier is not the one that was reviewed.
+ static let legacyProductTokenHalves: [[Int64]] = [[0x9AD9, 0xFC31], [0x787B, 0x71C6]]
+
+ public enum Outcome: String, Sendable { case patched, wouldPatch, alreadyPatched }
+
+ public struct Site: Sendable {
+ public let address: UInt64
+ public let original: Data
+ public var alreadyPatched: Bool { original == ARM64.nop }
+ }
+
+ public struct Report: Sendable {
+ public let outcome: Outcome
+ public let site: Site
+ public let records: [PatchRecord]
+ }
+
+ // MARK: - Cache patch
+
+ @discardableResult
+ public static func patchCache(
+ in chunks: DyldSharedCacheChunkSet, dryRun: Bool = false,
+ log: ((String) -> Void)? = stdoutLog,
+ ) throws -> Report {
+ let symbols = try imageSymbols(in: chunks)
+ let site = try discover(symbols: symbols) { try chunks.bytesAtVMA($0, length: $1) }
+
+ log?(" [.] MediaExperience VM classification at 0x\(String(site.address, radix: 16))\(site.alreadyPatched ? " (already patched)" : "")")
+
+ if site.alreadyPatched { return Report(outcome: .alreadyPatched, site: site, records: []) }
+ let span = DyldSharedCacheWriteSpan(vma: site.address, length: 4)
+
+ let preview = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: [span], dryRun: true, log: nil)
+ guard preview.isFullyAttested else {
+ throw PatcherError.patchVerificationFailed("Watch audio budget: cache signature does not cover the patch")
+ }
+
+ if dryRun { return Report(outcome: .wouldPatch, site: site, records: []) }
+ let location = try chunks.fileRange(of: span)
+ _ = try chunks.write(at: site.address, ARM64.nop)
+
+ let signed = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: [span], log: log)
+ guard signed.isFullyAttested else {
+ throw PatcherError.patchVerificationFailed("Watch audio budget: cache re-attestation failed")
+ }
+
+ let record = PatchRecord(
+ patchID: "\(patchID).budget_device_class", component: location.chunkURL.lastPathComponent,
+ fileOffset: location.range.lowerBound, virtualAddress: site.address,
+ originalBytes: site.original, patchedBytes: ARM64.nop,
+ description: "Select MediaExperience's virtual-device audio budget policy",
+ )
+
+ return Report(outcome: .patched, site: site, records: [record])
+ }
+
+ /// All required names are private local symbols; restrict lookup to this image's table entry
+ static func imageSymbols(in chunks: DyldSharedCacheChunkSet) throws -> [String: UInt64] {
+ let cache = try DyldCache(url: chunks.mainCacheURL)
+ guard cache.header.platform == .watchOS, !cache.header.isSimulator,
+ let images = cache.imageInfos else {
+ throw PatcherError.invalidFormat("Watch audio budget requires a native watchOS cache")
+ }
+
+ let matches = images.filter { $0.path(in: cache) == imagePath }
+ guard matches.count == 1, let image = matches.first,
+ image.address >= cache.header.sharedRegionStart else {
+ throw PatcherError.patchSiteNotFound("Watch audio budget: missing unique MediaExperience image")
+ }
+
+ let table = try chunks.localSymbolTable()
+ guard let entry = table.entry(forDylibOffset: image.address - cache.header.sharedRegionStart) else {
+ throw PatcherError.patchSiteNotFound("Watch audio budget: MediaExperience local symbols are missing")
+ }
+
+ let symbols = table.symbols(in: entry)
+ for name in [classifier, getter] + consumers {
+ guard let address = symbols[name], chunks.mapping(forVMA: address)?.isExecutable == true else {
+ throw PatcherError.patchSiteNotFound("Watch audio budget: missing executable \(name) in MediaExperience")
+ }
+ }
+
+ return symbols
+ }
+
+ // MARK: - Discovery
+
+ static func discover(symbols: [String: UInt64], read: (UInt64, Int) throws -> Data) throws -> Site {
+ func fail() -> PatcherError { .patchSiteNotFound("Watch audio budget: unexpected VM-classification control flow") }
+
+ guard let start = symbols[classifier], let get = symbols[getter], get > start, get - start < 4096 else { throw fail() }
+
+ let decoder = ARM64Disassembler()
+ let body = try read(start, Int(get - start))
+ let code = decoder.disassemble(body, at: start)
+ let flag = try virtualFlagAddress(getter: get, read: read)
+ try validateBudgetConsumers(symbols: symbols, getter: get, read: read)
+ var sites: [Site] = []
+
+ for i in code.indices where i >= 3 && i + 1 < code.count {
+ let compare = code[i], gate = code[i + 1]
+ guard compare.mnemonic == "cmp", let args = compare.detail?.operands, args.count == 2,
+ args[0].reg == .x(0), args[1].reg == .x(8),
+ gate.mnemonic == "b.ne" || gate.mnemonic == "nop" else { continue }
+
+ // Both legacy product-token comparisons must remain present, in order.
+ let prefix = code[max(0, i - 5)..<i]
+ let halves = productTokenHalves(in: prefix)
+
+ guard sites.count < legacyProductTokenHalves.count else { throw fail() }
+ guard halves == legacyProductTokenHalves[sites.count],
+ prefix.contains(where: { $0.mnemonic == "bl" }) else { throw fail() }
+ guard let store = flagStore(in: code, after: i, flag: flag) else { throw fail() }
+
+ if gate.mnemonic != "nop" {
+ guard gate.detail?.conditionCode == .ne, let destination = gate.detail?.operands.first,
+ destination.type == .immediate, destination.imm == Int64(store.address + 4) else { throw fail() }
+ }
+
+ let offset = Int(gate.address - start)
+ sites.append(Site(address: gate.address, original: body.subdata(in: offset..<offset + 4)))
+ }
+
+ guard sites.count == 2, !sites[1].alreadyPatched else { throw fail() }
+ return sites[0]
+ }
+
+ // MARK: - Classifier anchors
+
+ static func virtualFlagAddress(getter: UInt64, read: (UInt64, Int) throws -> Data) throws -> UInt64 {
+ let accessor = ARM64Disassembler().disassemble(try read(getter, 12), at: getter)
+
+ guard accessor.count == 3, accessor[0].mnemonic == "adrp", accessor[1].mnemonic == "ldrb",
+ accessor[2].mnemonic == "ret",
+ let page = accessor[0].detail?.operands, page.count == 2, page[1].imm >= 0,
+ let load = accessor[1].detail?.operands, load.count == 2,
+ load[0].reg == .w(0), load[1].type == .memory, load[1].mem.base == page[0].reg,
+ load[1].mem.disp >= 0 else {
+ throw PatcherError.patchSiteNotFound("Watch audio budget: unexpected virtual-device getter")
+ }
+
+ return UInt64(page[1].imm) + UInt64(load[1].mem.disp)
+ }
+
+ static func validateBudgetConsumers(
+ symbols: [String: UInt64], getter: UInt64, read: (UInt64, Int) throws -> Data
+ ) throws {
+ for name in consumers {
+ guard let address = symbols[name] else {
+ throw PatcherError.patchSiteNotFound("Watch audio budget: missing budget consumer check")
+ }
+
+ let calls = ARM64Disassembler().disassemble(try read(address, 64), at: address).filter {
+ $0.mnemonic == "bl" && $0.detail?.operands.first?.imm == Int64(getter)
+ }
+
+ guard calls.count == 1 else {
+ throw PatcherError.patchSiteNotFound("Watch audio budget: missing budget consumer check")
+ }
+ }
+ }
+
+ static func productTokenHalves(in code: ArraySlice<ARM64Instruction>) -> [Int64] {
+ let halves = code.compactMap { instruction -> Int64? in
+ guard ["mov", "movk"].contains(instruction.mnemonic),
+ let operands = instruction.detail?.operands, operands.count == 2,
+ operands[0].type == .register, operands[0].reg == .w(8),
+ operands[1].type == .immediate else { return nil }
+
+ if instruction.mnemonic == "movk" {
+ guard operands[1].shift.type == .lsl, operands[1].shift.amount == 16 else { return nil }
+ } else {
+ guard operands[1].shift.amount == 0 else { return nil }
+ }
+
+ return operands[1].imm
+ }
+
+ return Array(halves.suffix(2))
+ }
+
+ static func flagStore(in code: [ARM64Instruction], after compare: Int, flag: UInt64) -> ARM64Instruction? {
+ let tail = (compare + 2)..<min(code.count, compare + 19)
+ for index in tail {
+ let store = code[index]
+
+ guard store.mnemonic == "strb",
+ let operands = store.detail?.operands, operands.count == 2,
+ operands[0].type == .register, operands[0].reg == .w(8),
+ operands[1].type == .memory, operands[1].mem.disp >= 0,
+ code[index - 1].mnemonic == "mov",
+ let value = code[index - 1].detail?.operands, value.count == 2,
+ value[0].reg == .w(8), value[1].type == .immediate, value[1].imm == 1,
+ let page = code[..<compare].last(where: {
+ $0.mnemonic == "adrp" && $0.detail?.operands.first?.reg == operands[1].mem.base
+ }), let pageOperands = page.detail?.operands, pageOperands.count == 2,
+ pageOperands[1].type == .immediate, pageOperands[1].imm >= 0
+ else { continue }
+
+ if UInt64(pageOperands[1].imm) + UInt64(operands[1].mem.disp) == flag { return store }
+ }
+
+ return nil
+ }
+
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
index 76545bac..5f66962f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
@@ -547,7 +547,20 @@ struct ARM64EncoderKeystoneParityTests {
.init(source: "b.hi #0x0 @0x100000", keystone: 0x5480_0008, encoded: ARM64Encoder.encodeBCond(from: 0x10_0000, to: 0, condition: .hi), origin: "B.cond max backward"),
]
- static let allCases: [ARM64EncodingCase] = asmCallSiteCases + operandCoverageCases + x1ComparisonCases + x1LoweringCases + task3Cases + aksUnlockBagCases
+ // Frozen from Keystone 0.9.2 (Homebrew `kstool -b arm64 "<insn>" <address>`) outside the repository.
+ static let watchBudgetFixtureCases: [ARM64EncodingCase] = [
+ .init(source: "cmp x0, x8", keystone: 0xEB08_001F, encoded: ARM64Encoder.encodeCmpX(rn: 0, rm: 8), origin: "watch budget fixture"),
+ .init(source: "cmp x31, x30", keystone: 0xEB1E_03FF, encoded: ARM64Encoder.encodeCmpX(rn: 31, rm: 30), origin: "register boundary"),
+ .init(source: "movk w8, #0xfc31, lsl #16", keystone: 0x72BF_8628, encoded: ARM64Encoder.encodeMovkW(rd: 8, imm16: 0xFC31, shift: 16), origin: "first VM token"),
+ .init(source: "movk w8, #0x71c6, lsl #16", keystone: 0x72AE_38C8, encoded: ARM64Encoder.encodeMovkW(rd: 8, imm16: 0x71C6, shift: 16), origin: "second VM token"),
+ .init(source: "movk w0, #0xffff", keystone: 0x729F_FFE0, encoded: ARM64Encoder.encodeMovkW(rd: 0, imm16: 0xFFFF), origin: "unshifted lane"),
+ .init(source: "strb w8, [x9]", keystone: 0x3900_0128, encoded: ARM64Encoder.encodeStrBUnsignedOffset(rt: 8, rn: 9, offset: 0), origin: "flag store"),
+ .init(source: "ldrb w0, [x0]", keystone: 0x3940_0000, encoded: ARM64Encoder.encodeLdrBUnsignedOffset(rt: 0, rn: 0, offset: 0), origin: "flag getter"),
+ .init(source: "strb w31, [sp, #4095]", keystone: 0x393F_FFFF, encoded: ARM64Encoder.encodeStrBUnsignedOffset(rt: 31, rn: 31, offset: 4095), origin: "byte offset boundary"),
+ .init(source: "ldrb w30, [x29, #4095]", keystone: 0x397F_FFBE, encoded: ARM64Encoder.encodeLdrBUnsignedOffset(rt: 30, rn: 29, offset: 4095), origin: "byte offset boundary"),
+ ]
+
+ static let allCases: [ARM64EncodingCase] = asmCallSiteCases + operandCoverageCases + x1ComparisonCases + x1LoweringCases + task3Cases + aksUnlockBagCases + watchBudgetFixtureCases
@Test func `Task3 encoders reject invalid registers and offsets`() {
for invalid in [UInt32(32), 100] {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareWatchAudioBudgetTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareWatchAudioBudgetTests.swift
new file mode 100644
index 00000000..82d7d520
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareWatchAudioBudgetTests.swift
@@ -0,0 +1,330 @@
+// CustomFirmwareWatchAudioBudgetTests.swift — the watch MediaExperience budget classifier.
+//
+// A wrong instruction here panics boot rather than failing an assertion, so the
+// addresses the patcher must find are frozen in `FrozenReference`, named against the
+// disassembly in `Research/Guest/watch_audio.md`. The fixture-backed tests resolve
+// their image/cache like the other patcher suites (an in-repo `ipsws/ref_extract/`
+// path, or a `VPHONE_WATCH_*` override) and fail when it is absent unless
+// `VPHONE_WATCH_AUDIO_FIXTURE_OPTIONAL=1`, so a green run cannot mean the fixture was
+// missing. The cache test patches a throwaway copy.
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+// MARK: - The frozen reference
+
+/// Unslid 23T240 cache addresses, read from the running guest's arm64e cache.
+private enum FrozenReference {
+ /// `_CMSMDeviceState_UpdateDeviceClass` — the classifier that sets the byte.
+ static let classifierVMA: UInt64 = 0x1_89A3_4620
+
+ /// `b.ne 0x189a34754` at `0x189a34710`: the first token mismatch, which
+ /// skips the existing virtual-device log-and-set block. This is the patch.
+ static let gateVMA: UInt64 = 0x1_89A3_4710
+
+ /// The equivalent branch for the second token comparison. Forcing this one
+ /// too is not an input the patch produces, so discovery must refuse it.
+ static let secondGateVMA: UInt64 = 0x1_89A3_4764
+
+ /// `strb w8, [x20, #0x258]` at `0x189a34750`, after `mov w8, #1` at
+ /// `0x189a3474c`: the flag store the gate must be shown to reach.
+ static let flagStoreVMA: UInt64 = 0x1_89A3_4750
+
+ /// `dyld_cache_header.codeSignatureOffset`, which bounds the code the patch
+ /// may touch. Documented at `@0x28` in `DyldSharedCacheCodeSignature.swift`.
+ static let codeSignatureOffset = 0x28
+
+ /// The chunks the cache test needs: index, the `.03` code subcache the site
+ /// lives in, and the local-symbol file the patcher resolves names through.
+ static let cacheChunks = [
+ "dyld_shared_cache_arm64e",
+ "dyld_shared_cache_arm64e.03",
+ "dyld_shared_cache_arm64e.symbols",
+ ]
+}
+
+// MARK: - Fixtures
+
+private enum Fixture {
+ static let repoRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+
+ /// The reviewed 23T240 MediaExperience Mach-O. The env var overrides the
+ /// in-repo extract path, as with the other patcher fixtures.
+ static var image: URL? {
+ let url = ProcessInfo.processInfo.environment["VPHONE_WATCH_MEDIAEXPERIENCE_FIXTURE"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/ref_extract/watch_macho_pristine/MediaExperience")
+ return FileManager.default.fileExists(atPath: url.path) ? url : nil
+ }
+
+ /// The 23T240 arm64e watch cache chunk directory. The env var overrides the
+ /// in-repo extract path.
+ static var cache: URL? {
+ let directory = ProcessInfo.processInfo.environment["VPHONE_WATCH_AUDIO_CACHE_FIXTURE"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/ref_extract/watch_dsc_pristine")
+ let main = directory.appendingPathComponent("dyld_shared_cache_arm64e")
+ return FileManager.default.fileExists(atPath: main.path) ? directory : nil
+ }
+
+ /// Opt-out for a machine that does not carry the extracted watch IPSW.
+ static var isOptional: Bool {
+ ProcessInfo.processInfo.environment["VPHONE_WATCH_AUDIO_FIXTURE_OPTIONAL"] == "1"
+ }
+
+ /// A test runs unless its fixture is absent *and* the caller opted out.
+ static var imageRuns: Bool { image != nil || !isOptional }
+ static var cacheRuns: Bool { cache != nil || !isOptional }
+
+ static let missingImage: Comment = """
+ the 23T240 MediaExperience Mach-O is required — put it at \
+ ipsws/ref_extract/watch_macho_pristine/MediaExperience, point \
+ VPHONE_WATCH_MEDIAEXPERIENCE_FIXTURE at one, or set \
+ VPHONE_WATCH_AUDIO_FIXTURE_OPTIONAL=1 to skip this test instead of failing
+ """
+
+ static let missingCache: Comment = """
+ the 23T240 arm64e watch shared cache is required — put its chunks at \
+ ipsws/ref_extract/watch_dsc_pristine, point VPHONE_WATCH_AUDIO_CACHE_FIXTURE \
+ at their directory, or set VPHONE_WATCH_AUDIO_FIXTURE_OPTIONAL=1 to skip this \
+ test instead of failing
+ """
+}
+
+// MARK: - Tests
+
+@Suite("Watch audio power budget")
+struct CustomFirmwareWatchAudioBudgetTests {
+ @Test
+ func budgetVersionGate() {
+ for version in ["26.4", "26.4.1"] {
+ #expect(CustomFirmwareWatchAudioBudget.supports(VPhoneVersion(version)))
+ }
+ for version in ["26.3", "26.5", "26.40", "27.0", "unknown"] {
+ #expect(!CustomFirmwareWatchAudioBudget.supports(VPhoneVersion(version)))
+ }
+ #expect(!CustomFirmwareWatchAudioBudget.supports(nil))
+ }
+
+ @Test func missingSymbolsRefuse() {
+ #expect(throws: PatcherError.self) {
+ try CustomFirmwareWatchAudioBudget.discover(symbols: [:]) { _, _ in Data() }
+ }
+ }
+
+ /// Discovery against a synthetic stand-in, so the control-flow matching runs
+ /// everywhere and not only where the real cache is present. The stand-in is a
+ /// flat MediaExperience laid out at base 0x10000 with the reviewed shape: two
+ /// token comparisons (halves 0xfc319ad9 / 0x71c6787b), each a `bl`-prefixed
+ /// `cmp x0,x8` + `b.ne` that skips a `mov w8,#1; strb w8,[x9]` flag store; an
+ /// `adrp`/`ldrb`/`ret` getter; and two consumers that each `bl` the getter.
+ @Test func discoversAgainstSyntheticImage() throws {
+ let base: UInt64 = 0x10000
+ let getter: UInt64 = 0x10040
+ let gate: UInt64 = 0x10014, secondGate: UInt64 = 0x10030, flagStore: UInt64 = 0x1001c
+ let image = try Self.makeStandIn()
+ let symbols: [String: UInt64] = [
+ "_CMSMDeviceState_UpdateDeviceClass": base,
+ "_CMSMDeviceState_IsAVirtualDevice": getter,
+ "_cmsmSystemSoundNeedsMediaBudget": 0x10080,
+ "_CMSUtility_DoesSessionNeedAudioBudget": 0x10100,
+ ]
+ func discover(_ data: Data) throws -> CustomFirmwareWatchAudioBudget.Site {
+ try CustomFirmwareWatchAudioBudget.discover(symbols: symbols) { address, count in
+ let start = Int(address - base)
+ return data.subdata(in: start..<start + count)
+ }
+ }
+ func nop(_ data: inout Data, at vma: UInt64) {
+ let start = Int(vma - base)
+ data.replaceSubrange(start..<start + 4, with: ARM64.nop)
+ }
+
+ let site = try discover(image)
+ #expect(site.address == gate)
+ #expect(!site.alreadyPatched)
+
+ // Exactly one word changes, and it is the gate.
+ var patched = image
+ nop(&patched, at: gate)
+ #expect(zip(image, patched).enumerated().filter { $0.element.0 != $0.element.1 }.allSatisfy {
+ (Int(gate - base)..<Int(gate - base) + 4).contains($0.offset)
+ })
+
+ // Idempotence: the same gate is found again and reported patched.
+ let repeated = try discover(patched)
+ #expect(repeated.address == gate && repeated.alreadyPatched)
+
+ // A second forced classification is not an input this patch produces.
+ var both = patched
+ nop(&both, at: secondGate)
+ #expect(throws: PatcherError.self) { try discover(both) }
+
+ // Without the flag store the gate reaches, the anchor set is incomplete.
+ var broken = image
+ nop(&broken, at: flagStore)
+ #expect(throws: PatcherError.self) { try discover(broken) }
+ }
+
+ /// Keep the original addresses so each mutation below still tests the same site.
+ static func makeStandIn() throws -> Data {
+ let base = 0x10000
+ let getter = 0x10040
+ let flag: UInt64 = 0x14000
+ var code = Data()
+
+ func append(_ instruction: Data?) throws {
+ code.append(try #require(instruction))
+ }
+ func pad(to address: Int) throws {
+ try #require(base + code.count <= address && (address - base - code.count) % 4 == 0)
+ while base + code.count < address { code.append(ARM64.nop) }
+ }
+
+ // Classifier: each token mismatch skips its flag store.
+ try append(ARM64Encoder.encodeADRP(rd: 9, pc: UInt64(base), target: flag))
+ let tokens: [(UInt16, UInt16, Int)] = [
+ (0x9AD9, 0xFC31, 0x10020),
+ (0x787B, 0x71C6, 0x1003c),
+ ]
+ for (low, high, next) in tokens {
+ try append(ARM64Encoder.encodeBL(from: base + code.count, to: getter))
+ try append(ARM64Encoder.encodeMovzW(rd: 8, imm16: low))
+ try append(ARM64Encoder.encodeMovkW(rd: 8, imm16: high, shift: 16))
+ try append(ARM64Encoder.encodeCmpX(rn: 0, rm: 8))
+ try append(ARM64Encoder.encodeBCond(from: base + code.count, to: next, condition: .ne))
+ try append(ARM64Encoder.encodeMovzW(rd: 8, imm16: 1))
+ try append(ARM64Encoder.encodeStrBUnsignedOffset(rt: 8, rn: 9, offset: 0))
+ }
+ code.append(ARM64.ret)
+
+ // Getter: read the byte both classifier stores target.
+ try pad(to: getter)
+ try append(ARM64Encoder.encodeADRP(rd: 0, pc: UInt64(getter), target: flag))
+ try append(ARM64Encoder.encodeLdrBUnsignedOffset(rt: 0, rn: 0, offset: 0))
+ code.append(ARM64.ret)
+
+ // Both budget consumers call the getter; discovery reads 64 bytes each.
+ for consumer in [0x10080, 0x10100] {
+ try pad(to: consumer)
+ try append(ARM64Encoder.encodeBL(from: consumer, to: getter))
+ code.append(ARM64.ret)
+ }
+ try pad(to: 0x10140)
+ return code
+ }
+
+ @Test(.enabled(if: Fixture.imageRuns))
+ func reviewedClassifier() throws {
+ let data = try Data(contentsOf: #require(Fixture.image, Fixture.missingImage))
+ let symbols = try Self.fixtureSymbols(data)
+ let segments = MachOParser.parseSegments(from: data)
+ func offset(_ address: UInt64, _ count: Int) throws -> Int {
+ guard let segment = segments.first(where: {
+ address >= $0.vmAddr && address - $0.vmAddr + UInt64(count) <= $0.fileSize
+ }) else { throw PatcherError.invalidFormat("Fixture address is not file backed") }
+ return Int(segment.fileOffset + address - segment.vmAddr)
+ }
+ func discover(_ input: Data) throws -> CustomFirmwareWatchAudioBudget.Site {
+ try CustomFirmwareWatchAudioBudget.discover(symbols: symbols) { address, count in
+ let start = try offset(address, count)
+ return input.subdata(in: start..<start + count)
+ }
+ }
+ let site = try discover(data)
+ #expect(site.address == FrozenReference.gateVMA)
+ #expect(!site.alreadyPatched)
+
+ // Exactly one word changes, and it is the gate.
+ var patched = data
+ let start = try offset(site.address, 4)
+ patched.replaceSubrange(start..<start + 4, with: ARM64.nop)
+ #expect(zip(data, patched).enumerated().filter { $0.element.0 != $0.element.1 }.allSatisfy {
+ (start..<start + 4).contains($0.offset)
+ })
+
+ // Idempotence: the same site is found again and reported patched.
+ let repeated = try discover(patched)
+ #expect(repeated.address == site.address && repeated.alreadyPatched)
+
+ // A second forced classification is not an input this patch produced.
+ let other = try offset(FrozenReference.secondGateVMA, 4)
+ patched.replaceSubrange(other..<other + 4, with: ARM64.nop)
+ #expect(throws: PatcherError.self) { try discover(patched) }
+
+ // Without the flag store the gate reaches, the anchor set is incomplete.
+ var broken = data
+ let setter = try offset(FrozenReference.flagStoreVMA, 4)
+ broken.replaceSubrange(setter..<setter + 4, with: ARM64.nop)
+ #expect(throws: PatcherError.self) { try discover(broken) }
+
+ #expect(try discover(data).original == site.original)
+ }
+
+ @Test(.enabled(if: Fixture.cacheRuns))
+ func cachePatchAndSignature() throws {
+ let fixture = try #require(Fixture.cache, Fixture.missingCache)
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ for name in FrozenReference.cacheChunks {
+ let source = fixture.appendingPathComponent(name).resolvingSymlinksInPath()
+ try FileManager.default.copyItem(at: source, to: directory.appendingPathComponent(name))
+ }
+ let codeURL = directory.appendingPathComponent("dyld_shared_cache_arm64e.03")
+ let before = try Data(contentsOf: codeURL)
+ let chunks = try DyldSharedCacheChunkSet(directory: directory, architecture: "arm64e")
+
+ // A dry run reports the site and writes nothing.
+ let preview = try CustomFirmwareWatchAudioBudget.patchCache(in: chunks, dryRun: true, log: nil)
+ #expect(preview.outcome == .wouldPatch && preview.records.isEmpty)
+ #expect(try Data(contentsOf: codeURL) == before)
+
+ let report = try CustomFirmwareWatchAudioBudget.patchCache(in: chunks, log: nil)
+ #expect(report.outcome == .patched)
+ let record = try #require(report.records.first)
+ #expect(report.records.count == 1)
+ #expect(record.patchID == "\(CustomFirmwareWatchAudioBudget.patchID).budget_device_class")
+ #expect(record.virtualAddress == report.site.address)
+ #expect(record.originalBytes == report.site.original && record.patchedBytes == ARM64.nop)
+
+ // Exactly the four bytes of the gate change inside the signed code.
+ let after = try Data(contentsOf: codeURL)
+ #expect(after != before)
+ let codeEnd = Int(before.loadLE(UInt64.self, at: FrozenReference.codeSignatureOffset))
+ let site = try chunks.fileRange(
+ of: DyldSharedCacheWriteSpan(vma: FrozenReference.gateVMA, length: 4),
+ )
+ let changed = zip(before.prefix(codeEnd), after.prefix(codeEnd)).enumerated().filter {
+ $0.element.0 != $0.element.1
+ }
+ #expect(changed.count == 4)
+ #expect(changed.allSatisfy { site.range.contains($0.offset) })
+ #expect(try chunks.bytesAtVMA(FrozenReference.gateVMA, length: 4) == ARM64.nop)
+
+ // Idempotence on the cache: a second run writes nothing more.
+ let repeated = try CustomFirmwareWatchAudioBudget.patchCache(in: chunks, log: nil)
+ #expect(repeated.outcome == .alreadyPatched && repeated.records.isEmpty)
+ #expect(try Data(contentsOf: codeURL) == after)
+ }
+
+ private static func fixtureSymbols(_ data: Data) throws -> [String: UInt64] {
+ let table = try #require(MachOParser.parseSymtab(from: data))
+ var symbols: [String: UInt64] = [:]
+ for index in 0..<table.nsyms {
+ let entry = table.symoff + index * 16
+ let offset = table.stroff + Int(data.loadLE(UInt32.self, at: entry))
+ let end = try #require(data[offset..<table.stroff + table.strsize].firstIndex(of: 0))
+ let name = try #require(String(data: data[offset..<end], encoding: .utf8))
+ symbols[name] = data.loadLE(UInt64.self, at: entry + 8)
+ }
+ return symbols
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
index a0ab25f7..b3bdfad1 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
@@ -69,6 +69,13 @@ public enum ARM64Encoder {
// MARK: - Comparisons
+ /// CMP Xn, Xm (SUBS XZR, Xn, Xm); register 31 is XZR.
+ public static func encodeCmpX(rn: UInt32, rm: UInt32) -> Data? {
+ guard rn < 32, rm < 32 else { return nil }
+ let insn: UInt32 = 0xEB00_001F | (rm << 16) | (rn << 5)
+ return ARM64.encodeU32(insn)
+ }
+
/// CMP Wn,#imm12; register 31 is WSP.
public static func encodeCmpWImmediate(rn: UInt32, imm12: UInt32) -> Data? {
guard rn < 32, imm12 < 4096 else { return nil }
@@ -225,6 +232,13 @@ public enum ARM64Encoder {
return ARM64.encodeU32(insn)
}
+ /// MOVK Wd, #imm16, LSL #shift; replace one 16-bit lane.
+ public static func encodeMovkW(rd: UInt32, imm16: UInt16, shift: UInt32 = 0) -> Data? {
+ guard rd < 32, shift == 0 || shift == 16 else { return nil }
+ let insn: UInt32 = 0x7280_0000 | ((shift / 16) << 21) | (UInt32(imm16) << 5) | rd
+ return ARM64.encodeU32(insn)
+ }
+
/// Encode MOVZ Xd, #imm16 (64-bit).
public static func encodeMovzX(rd: UInt32, imm16: UInt16, shift: UInt32 = 0) -> Data? {
let hw = shift / 16
@@ -304,6 +318,20 @@ public enum ARM64Encoder {
return ARM64.encodeU32(insn)
}
+ /// LDRB Wt, [Xn|SP, #offset], with an unsigned byte offset.
+ public static func encodeLdrBUnsignedOffset(rt: UInt32, rn: UInt32, offset: UInt32) -> Data? {
+ guard rt < 32, rn < 32, offset < 4096 else { return nil }
+ let insn: UInt32 = 0x3940_0000 | (offset << 10) | (rn << 5) | rt
+ return ARM64.encodeU32(insn)
+ }
+
+ /// STRB Wt, [Xn|SP, #offset], with an unsigned byte offset.
+ public static func encodeStrBUnsignedOffset(rt: UInt32, rn: UInt32, offset: UInt32) -> Data? {
+ guard rt < 32, rn < 32, offset < 4096 else { return nil }
+ let insn: UInt32 = 0x3900_0000 | (offset << 10) | (rn << 5) | rt
+ return ARM64.encodeU32(insn)
+ }
+
/// LDR Xt, [Xn, #offset]; rn 31 is SP, scaled by eight.
public static func encodeLdrXUnsignedOffset(rt: UInt32, rn: UInt32, offset: UInt32) -> Data? {
guard rt < 32, rn < 32, offset % 8 == 0, offset / 8 < 4096 else { return nil }