Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Run Apple TV guests on tvOS 26.6, with vphoned and a 4K OTA build

Jacky8137c121e5ff
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/MachOBuildPlatform.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/MachOBuildPlatform.swift
new file mode 100644
index 00000000..97ab9847
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/MachOBuildPlatform.swift
@@ -0,0 +1,59 @@
+// MachOBuildPlatform.swift — read and rewrite the platform a Mach-O names.
+//
+// dyld refuses to load a library into a process of another platform. An
+// Apple TV guest's processes are tvOS, so an iOS-built library a TV guest
+// loads, the paravirtual GPU driver, is marked tvOS before it is installed.
+// The code signature no longer matches afterwards: the caller signs.
+
+import Foundation
+
+public enum MachOBuildPlatform {
+ public static let iOS: UInt32 = 2
+ public static let tvOS: UInt32 = 3
+
+ public enum Error: Swift.Error, Equatable {
+ case notThin64BitMachO
+ case noBuildVersion
+ }
+
+ private static let magic64: UInt32 = 0xFEED_FACF
+ private static let buildVersionCommand: UInt32 = 0x32 // LC_BUILD_VERSION
+
+ /// The platform of the first `LC_BUILD_VERSION`, or nil when there is none.
+ public static func read(_ data: Data) throws -> UInt32? {
+ try buildVersionOffsets(data).first.map { u32(data, $0 + 8) }
+ }
+
+ /// Rewrite the platform of every `LC_BUILD_VERSION` in a thin 64-bit Mach-O.
+ public static func set(_ platform: UInt32, in data: inout Data) throws {
+ let offsets = try buildVersionOffsets(data)
+ guard !offsets.isEmpty else { throw Error.noBuildVersion }
+ for offset in offsets {
+ let start = data.startIndex + offset + 8
+ withUnsafeBytes(of: platform.littleEndian) { data.replaceSubrange(start..<start + 4, with: $0) }
+ }
+ }
+
+ private static func buildVersionOffsets(_ data: Data) throws -> [Int] {
+ guard data.count >= 32, u32(data, 0) == magic64 else { throw Error.notThin64BitMachO }
+ let commands = Int(u32(data, 16))
+ let end = min(data.count, 32 + Int(u32(data, 20)))
+ var offsets: [Int] = []
+ var offset = 32
+ for _ in 0..<commands {
+ guard offset + 8 <= end else { break }
+ let size = Int(u32(data, offset + 4))
+ guard size >= 8, offset + size <= end else { break }
+ if u32(data, offset) == buildVersionCommand, size >= 12 {
+ offsets.append(offset)
+ }
+ offset += size
+ }
+ return offsets
+ }
+
+ private static func u32(_ data: Data, _ offset: Int) -> UInt32 {
+ let start = data.startIndex + offset
+ return data[start..<start + 4].enumerated().reduce(0) { $0 | UInt32($1.element) << (8 * $1.offset) }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift
index ba45abd8..6ea05b6c 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift
@@ -22,17 +22,28 @@ import Foundation
import VPhonePatchKit
public enum FirmwareGuestPatchResolution {
- /// TV admits the gigalocker repair and opt-in dyld TPRO compatibility.
- /// Payloads, other cache patches and shell integration need a TV port and
+ /// TV admits the gigalocker repair, opt-in dyld TPRO compatibility, and
+ /// vphoned with the launchd cache gate its launchd.plist entry needs.
+ /// Other payloads, cache patches and shell integration need a TV port and
/// validation before the installer can select them.
public static let tvSupportedGuestPatches: Set<String> = [
"system-seputil-boot-gigalocker_uuid",
"system-gigalocker-boot-rename",
FirmwareGuestSystemPatchSet.tvTPRO,
+ "system-vphoned-boot-install",
+ "system-launchd_cache_loader-boot-unsecure_cache_gate",
]
- public static func unvalidatedTVGuestPatches(enabled: Set<String>) -> [String] {
- let admitted = tvSupportedGuestPatches
+ /// An arm64e Apple TV (the 4K, from its OTA) also admits the paravirtual
+ /// GPU driver, which a plain-arm64 userland cannot load, and the OTA
+ /// userland swap itself.
+ public static let tvArm64eGuestPatches: Set<String> = [
+ "system-extensions-boot-gpu_bundle",
+ FirmwareGuestSystemPatchSet.tvOTAUserland,
+ ]
+
+ public static func unvalidatedTVGuestPatches(enabled: Set<String>, arm64eUserland: Bool = false) -> [String] {
+ let admitted = arm64eUserland ? tvSupportedGuestPatches.union(tvArm64eGuestPatches) : tvSupportedGuestPatches
return enabled.intersection(guestTargetIdentifiers).subtracting(admitted).sorted()
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index f58728e5..a77e1d36 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -31,6 +31,9 @@ public enum FirmwareGuestSystemPatchSet {
public static let locationdCohorting = "system-locationd-cfw-disable_auto_cohort"
public static let jetsamDisableAllowed = "system-jetsamproperties-cfw-disable_allowed"
public static let tvTPRO = "system-dyld-exp-tv_tpro"
+ /// Replaces the restored System volume with an Apple TV 4K userland
+ /// staged from its OTA. Research only: no IPSW exists for that device.
+ public static let tvOTAUserland = "system-tv-exp-ota_userland"
private static let ios27 = VPhonePatchApplicability(iOSBase: .major(27))
@@ -60,7 +63,14 @@ public enum FirmwareGuestSystemPatchSet {
title: "TV TPRO feature detection",
summary: "Plain-arm64 TVOS compatibility: stops standalone and cached dyld enabling cloudOS-advertised hardware TPRO and pager modes, preserving page-in linking and all fixups.",
target: .guestExecutable(path: "/usr/lib/dyld"),
- applicability: VPhonePatchApplicability(iOSBase: .release(major: 26, minor: 4)),
+ applicability: VPhonePatchApplicability(iOSBase: .major(26)),
+ ),
+ VPhonePatchDeclaration(
+ identifier: tvOTAUserland,
+ title: "Apple TV 4K userland from OTA",
+ summary: "Research: replaces the System volume with the arm64e tvOS userland staged in the VM's OTAUserland folder, extracted with aa so ownership, modes, flags and compression survive.",
+ target: .guestFile(path: "/"),
+ applicability: VPhonePatchApplicability(iOSBase: .major(26)),
),
VPhonePatchDeclaration(
identifier: locationdCohorting,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
index e1793342..364290ba 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
@@ -30,7 +30,7 @@ public enum FirmwareKernelCustomFirmwarePatchSet {
title: "TV TPRO pager compatibility",
summary: "Defaults sprr_tpro_pagers to zero so plain-arm64 tvOS dyld can make DATA_CONST writable. Pair with the TV dyld TPRO patch.",
target: .firmware(.kernelcache),
- applicability: VPhonePatchApplicability(iOSBase: .release(major: 26, minor: 4), cloudOS: .release(major: 26, minor: 4)),
+ applicability: VPhonePatchApplicability(iOSBase: .major(26), cloudOS: .release(major: 26, minor: 4)),
),
// MARK: Trust Cache and Code Signing
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index e65f7be6..1edf12f5 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -62,7 +62,7 @@ public enum FirmwarePatchSetCatalog {
Set(FirmwareKernelFridaPatchSet.manifest.patches.map(\.identifier))
.union(hypervisorConcealmentPatches)
.union(experimentalIdentityPatches)
- .union([FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, FirmwareGuestSystemPatchSet.tvTPRO])
+ .union([FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, FirmwareGuestSystemPatchSet.tvTPRO, FirmwareGuestSystemPatchSet.tvOTAUserland])
/// ProMotion: the 120 Hz timing for the paravirtual display.
///
@@ -213,6 +213,75 @@ public enum FirmwarePatchSetCatalog {
selection: .all,
)
+ /// The iOS payloads, hooks and shared-cache patches an Apple TV guest has no
+ /// validated port of: display, camera, audio, sensors, the GPU driver (a
+ /// plain-arm64 HD cannot load it), debugserver and the environment hooks.
+ public static let tvOSBlockedPatches: Set<String> = [
+ "dyld-boot-iomfb_force_kern",
+ "dyld-boot-iomfb_swapend",
+ "dyld-boot-lockdown_mode",
+ "dyld-boot-lsd_embedded_reg",
+ "dyld-boot-maxslide",
+ "dyld-boot-xpc_lwcr",
+ "dyld-cfw-camera",
+ "preboot-cfw-devicetree_board_audio",
+ "preboot-cfw-devicetree_haptics",
+ "preboot-cfw-devicetree_iphone_product",
+ "preboot-cfw-devicetree_microphone_array",
+ "system-apps-cfw-attitude",
+ "system-backboardd-cfw-gyroscope",
+ "system-campo-cfw-entitlements",
+ "system-debugserver-cfw-install",
+ "system-diskimagesiod-cfw-is_mount_complete",
+ "system-extensions-boot-gpu_bundle",
+ "system-installcoordination_proxy-cfw-persona_lookup",
+ "system-jetsamproperties-cfw-disable_allowed",
+ "system-launchd-boot-jetsam_panic_guard_bypass",
+ "system-launchdaemons-boot-environment",
+ "system-locationd-cfw-disable_auto_cohort",
+ "system-mobileactivationd-boot-should_hactivate",
+ "system-paravirt_gpu-cfw-heap_index_offset",
+ "system-systemversion-cfw-build_version",
+ "system-virtiosound-cfw-hal_plugin",
+ "system-virtualaudio-cfw-microphone_graph_chains",
+ "system-virtualaudio-cfw-mute_set_throw",
+ "system-virtualaudio-cfw-speaker_graph_chains",
+ "system-virtualaudio-cfw-speaker_protection_gate",
+ "system-virtualaudio-cfw-speaker_raw_chains",
+ "system-virtualaudio-cfw-speaker_route_throws",
+ "system-virtualaudio-cfw-volume_mode_precondition",
+ ]
+
+ /// Standard for an Apple TV guest: the TV TPRO compatibility on, and
+ /// ``tvOSBlockedPatches`` off. The shipped `tvos.plist` must match this.
+ public static let tvOSPreset = VPhonePatchPreset(
+ identifier: VPhonePatchPreset.tvOSIdentifier,
+ title: "Apple TV",
+ summary: "Standard for an Apple TV HD guest: plain-arm64 TPRO compatibility and vphoned, without the iOS display, camera, audio, sensor and shared-cache patches tvOS has no validated port of.",
+ patchSets: bundledReferences,
+ selection: .block(
+ manualOnlyPatches
+ .subtracting([FirmwareGuestSystemPatchSet.tvTPRO, FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers])
+ .union(tvOSBlockedPatches),
+ ),
+ )
+
+ /// The Apple TV preset for an arm64e Apple TV 4K whose userland comes from
+ /// its OTA: the paravirtual GPU driver, which the HD cannot load, and the
+ /// userland swap on; the TV TPRO patches, which only plain-arm64 dyld
+ /// needs, off. The shipped `tvos-4k.plist` must match this.
+ public static let tvOS4KPreset = VPhonePatchPreset(
+ identifier: VPhonePatchPreset.tvOS4KIdentifier,
+ title: "Apple TV 4K",
+ summary: "Research: the Apple TV preset for an Apple TV 4K restored over the Apple TV HD, with its arm64e userland from the OTA and the paravirtual GPU driver, without the plain-arm64 TPRO patches.",
+ patchSets: bundledReferences,
+ selection: .block(
+ manualOnlyPatches
+ .subtracting([FirmwareGuestSystemPatchSet.tvOTAUserland])
+ .union(tvOSBlockedPatches.subtracting(["system-extensions-boot-gpu_bundle"])),
+ ),
+ )
+
/// The presets the bundle ships.
- public static let builtInPresets: [VPhonePatchPreset] = [standardPreset, experimentalPreset]
+ public static let builtInPresets: [VPhonePatchPreset] = [standardPreset, experimentalPreset, tvOSPreset, tvOS4KPreset]
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
index a73ca5ee..7ed27fa8 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
@@ -57,6 +57,12 @@ extension FirmwarePipeline {
/// names none.
func readGuestDevice(_ restoreDir: URL) -> VPhoneGuestDevice {
let recorded = try? VPhoneVirtualMachineManifest.load(from: vmDirectory.appendingPathComponent("config.plist"))
+ // An Apple TV 4K has no IPSW: it is built over an Apple TV HD restore
+ // and takes its userland from an OTA, so the HD's manifest never lists
+ // it. Its own device tree, placed in the restore tree, presents it.
+ if recorded?.guestDevice == .appleTV14_1 {
+ return .appleTV14_1
+ }
return VPhoneGuestDevice.detect(
buildManifestAt: restoreDir.appendingPathComponent("iPhone-BuildManifest.plist"),
preferring: recorded?.guestProductType,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/MachOBuildPlatformTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/MachOBuildPlatformTests.swift
new file mode 100644
index 00000000..a8ebd6cd
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/MachOBuildPlatformTests.swift
@@ -0,0 +1,66 @@
+// MachOBuildPlatformTests.swift — the platform rewrite an Apple TV guest's
+// GPU driver gets before it is installed.
+
+import FirmwarePatcher
+import Foundation
+import Testing
+
+@Suite("Mach-O build platform")
+struct MachOBuildPlatformTests {
+ /// A thin 64-bit header with the given load commands, each `(cmd, body)`.
+ static func machO(_ commands: [(UInt32, [UInt32])]) -> Data {
+ var body = Data()
+ for (command, words) in commands {
+ let size = UInt32(8 + 4 * words.count)
+ for word in [command, size] + words {
+ withUnsafeBytes(of: word.littleEndian) { body.append(contentsOf: $0) }
+ }
+ }
+ var header = Data()
+ // magic, cputype arm64, cpusubtype, MH_EXECUTE, ncmds, sizeofcmds, flags, reserved
+ for word: UInt32 in [0xFEED_FACF, 0x0100_000C, 0, 2, UInt32(commands.count), UInt32(body.count), 0, 0] {
+ withUnsafeBytes(of: word.littleEndian) { header.append(contentsOf: $0) }
+ }
+ return header + body
+ }
+
+ @Test
+ func `the platform of every build version becomes tvOS and nothing else changes`() throws {
+ // LC_UUID-shaped filler, then two LC_BUILD_VERSIONs (platform, minos, sdk, ntools).
+ let original = Self.machO([
+ (0x1B, [1, 2, 3, 4]),
+ (0x32, [MachOBuildPlatform.iOS, 0x000F_0000, 0x001B_0000, 0]),
+ (0x32, [MachOBuildPlatform.iOS, 0x000F_0000, 0x001B_0000, 0]),
+ ])
+ #expect(try MachOBuildPlatform.read(original) == MachOBuildPlatform.iOS)
+ var data = original
+ try MachOBuildPlatform.set(MachOBuildPlatform.tvOS, in: &data)
+ #expect(try MachOBuildPlatform.read(data) == MachOBuildPlatform.tvOS)
+ let changed = zip(original, data).enumerated().filter { $0.element.0 != $0.element.1 }.map(\.offset)
+ // The low byte of each platform word: 2 -> 3.
+ #expect(changed == [32 + 24 + 8, 32 + 24 + 24 + 8])
+ }
+
+ @Test
+ func `a file that is not a thin 64-bit Mach-O or has no build version is refused`() throws {
+ var fat = Data([0xCA, 0xFE, 0xBA, 0xBE] + [UInt8](repeating: 0, count: 60))
+ #expect(throws: MachOBuildPlatform.Error.notThin64BitMachO) {
+ try MachOBuildPlatform.set(MachOBuildPlatform.tvOS, in: &fat)
+ }
+ var bare = Self.machO([(0x1B, [1, 2, 3, 4])])
+ #expect(try MachOBuildPlatform.read(bare) == nil)
+ #expect(throws: MachOBuildPlatform.Error.noBuildVersion) {
+ try MachOBuildPlatform.set(MachOBuildPlatform.tvOS, in: &bare)
+ }
+ }
+
+ @Test
+ func `a load command running past the declared commands is not followed`() throws {
+ var data = Self.machO([(0x32, [MachOBuildPlatform.iOS, 0, 0, 0])])
+ // Claim a second command the header's sizeofcmds does not cover.
+ data.replaceSubrange(16..<20, with: [2, 0, 0, 0])
+ #expect(try MachOBuildPlatform.read(data) == MachOBuildPlatform.iOS)
+ try MachOBuildPlatform.set(MachOBuildPlatform.tvOS, in: &data)
+ #expect(try MachOBuildPlatform.read(data) == MachOBuildPlatform.tvOS)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift
index 07f71d53..276702de 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift
@@ -255,7 +255,7 @@ struct CustomFirmwareDaemonsTests {
// Broken iPhone firmware and an uninspected TV board must not gain a
// fallback merely because the expected cryptex entries are missing.
- for products in [["iPhone17,3"], ["AppleTV14,1"], []] {
+ for products in [["iPhone17,3"], ["AppleTV11,1"], []] {
try CustomFirmwareDaemons.savePlist(manifest(products: products, entries: entries), to: url)
#expect(throws: CustomFirmwareDaemons.DaemonError.self) {
try CustomFirmwareDaemons.filesystemLayout(buildManifest: url)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
index 49b129b1..77e838f1 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
@@ -13,7 +13,7 @@ import VPhonePatchKit
@Suite("Guest patch resolution")
struct FirmwareGuestPatchResolutionTests {
@Test
- func `TV serial selection excludes iOS payloads and cache patches`() throws {
+ func `TV selection keeps vphoned and excludes iOS payloads and cache patches`() throws {
let standard = try VPhonePatchPlan.resolve(
preset: FirmwarePatchSetCatalog.standardPreset,
patchSets: FirmwarePatchSetCatalog.bundled,
@@ -21,7 +21,8 @@ struct FirmwareGuestPatchResolutionTests {
cloudOS: VPhoneVersion("26.4"),
)
let unvalidated = FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: standard.enabled)
- #expect(unvalidated.contains("system-vphoned-boot-install"))
+ #expect(!unvalidated.contains("system-vphoned-boot-install"))
+ #expect(!unvalidated.contains("system-launchd_cache_loader-boot-unsecure_cache_gate"))
#expect(unvalidated.contains("system-launchdaemons-boot-environment"))
#expect(unvalidated.contains("system-extensions-boot-gpu_bundle"))
#expect(unvalidated.contains(FirmwareGuestSystemPatchSet.paravirtGPUIndexOffset))
@@ -49,10 +50,67 @@ struct FirmwareGuestPatchResolutionTests {
FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: standard.enabled),
).union([identifier])
#expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: serial).isEmpty)
- #expect(!serial.contains("system-vphoned-boot-install"))
+ #expect(serial.contains("system-vphoned-boot-install"))
#expect(!serial.contains("system-extensions-boot-gpu_bundle"))
}
+ @Test
+ func `only an arm64e TV admits the GPU driver and the OTA userland`() {
+ let gpu = "system-extensions-boot-gpu_bundle"
+ let ota = FirmwareGuestSystemPatchSet.tvOTAUserland
+ let selection: Set<String> = [gpu, ota, "system-vphoned-boot-install"]
+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: selection) == [gpu, ota].sorted())
+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: selection, arm64eUserland: true).isEmpty)
+ // The iOS payloads stay out for both.
+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: ["dyld-cfw-camera"], arm64eUserland: true) == ["dyld-cfw-camera"])
+ }
+
+ @Test
+ func `the Apple TV 4K preset swaps in the OTA userland with the GPU driver and no TPRO patches`() throws {
+ let gpu = "system-extensions-boot-gpu_bundle"
+ let ota = FirmwareGuestSystemPatchSet.tvOTAUserland
+ let tpro: Set = [FirmwareGuestSystemPatchSet.tvTPRO, FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers]
+ func plan(_ preset: VPhonePatchPreset) throws -> VPhonePatchPlan {
+ try VPhonePatchPlan.resolve(
+ preset: preset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion("26.6"),
+ cloudOS: VPhoneVersion("26.4"),
+ )
+ }
+ let tv4K = try plan(FirmwarePatchSetCatalog.tvOS4KPreset)
+ #expect(tv4K.isEnabled(gpu) && tv4K.isEnabled(ota))
+ #expect(tv4K.enabled.isDisjoint(with: tpro))
+ #expect(tv4K.isEnabled("system-vphoned-boot-install"))
+ // The upstream GPU heap index patch stays out, as for every TV guest.
+ #expect(!tv4K.isEnabled(FirmwareGuestSystemPatchSet.paravirtGPUIndexOffset))
+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: tv4K.enabled, arm64eUserland: true).isEmpty)
+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: tv4K.enabled) == [gpu, ota].sorted())
+
+ // The HD's preset is the mirror image.
+ let tvHD = try plan(FirmwarePatchSetCatalog.tvOSPreset)
+ #expect(!tvHD.isEnabled(gpu) && !tvHD.isEnabled(ota))
+ #expect(tvHD.enabled.isSuperset(of: tpro))
+ // Otherwise the two agree.
+ #expect(tv4K.enabled.symmetricDifference(tvHD.enabled) == tpro.union([gpu, ota]))
+ }
+
+ @Test
+ func `TV TPRO patches apply to every tvOS 26 userland on the 26.4 kernel`() throws {
+ let tv: Set = [FirmwareGuestSystemPatchSet.tvTPRO, FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers]
+ for build in ["26.4", "26.6"] {
+ let plan = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.standardPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion(build),
+ cloudOS: VPhoneVersion("26.4"),
+ allowed: tv,
+ )
+ #expect(plan.enabled.isSuperset(of: tv), "\(build)")
+ #expect(plan.skippedByVersion.isDisjoint(with: tv), "\(build)")
+ }
+ }
+
@Test
func `Guest target identifiers include the guest patches and exclude the boot chain`() {
let guest = FirmwareGuestPatchResolution.guestTargetIdentifiers
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
index 88c9bda9..fd9b7168 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
@@ -132,10 +132,15 @@ struct FirmwarePatchSetCatalogTests {
cloudOS: VPhoneVersion(cloud),
)
#expect(!plan.enabled.isEmpty)
- // Nothing a shipped preset does should drop a boot-essential
- // patch: these are the combinations we claim boot.
+ // Nothing a shipped iOS preset does should drop a boot-essential
+ // patch: these are the combinations we claim boot. The tvOS
+ // presets drop exactly the iOS ones an Apple TV has no port of.
+ let tvPresets = [VPhonePatchPreset.tvOSIdentifier, VPhonePatchPreset.tvOS4KIdentifier]
+ let expected = tvPresets.contains(preset.identifier)
+ ? Set(plan.droppedBootEssentials).isSubset(of: FirmwarePatchSetCatalog.tvOSBlockedPatches)
+ : plan.droppedBootEssentials.isEmpty
#expect(
- plan.droppedBootEssentials.isEmpty,
+ expected,
"\(preset.identifier) on \(base)/\(cloud) drops \(plan.droppedBootEssentials)",
)
}
@@ -342,7 +347,7 @@ struct FirmwarePatchSetCatalogTests {
on.isEmpty || on == pair,
"\(preset.identifier) on \(base)/\(cloud) enabled only \(on)",
)
- #expect(on.isEmpty == preset.isStandard)
+ #expect(on.isEmpty == (preset.identifier != "experimental"))
}
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index 85d8c42d..54c8da4b 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -200,11 +200,19 @@ struct VPhoneCustomFirmwareInstaller {
? try restoreTree(in: bundleDirectory, path: bundlePath, owner: callerUID)
: nil
let device = configuredGuestDevice(in: bundleDirectory) ?? guestDevice(of: restore)
+ // Research: an Apple TV 4K userland staged from its OTA, which
+ // `system-tv-exp-ota_userland` puts in place of the restored one.
+ let otaUserland = device.family == .appleTV && (try? bundleDirectory.isDirectory(VPhoneOTAArchive.userlandDirectoryName)) == true
+ ? try bundleDirectory.directory(VPhoneOTAArchive.userlandDirectoryName)
+ : nil
if device.family == .appleTV {
guard let plan else {
throw ValidationError("tvOS installation needs an explicit patch plan. Resolve a TV selection with `fw set-patches` and `fw patch` first.")
}
- let unvalidated = FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: Set(plan.enabledPatches))
+ let unvalidated = FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(
+ enabled: Set(plan.enabledPatches),
+ arm64eUserland: !device.hasPlainArm64Userland,
+ )
guard unvalidated.isEmpty else {
throw ValidationError("These guest patches have not been validated for tvOS. Block them with `fw set-patches` before installation: \(unvalidated.joined(separator: ", "))")
}
@@ -367,6 +375,7 @@ struct VPhoneCustomFirmwareInstaller {
restore: restore,
work: work,
owner: callerUID,
+ otaUserland: otaUserland,
plan: plan,
priorGuest: priorGuest,
kernelPatches: receiptKernel,
@@ -386,6 +395,7 @@ struct VPhoneCustomFirmwareInstaller {
restore: nil,
work: work,
owner: nil,
+ otaUserland: otaUserland,
plan: plan,
priorGuest: priorGuest,
kernelPatches: receiptKernel,
@@ -402,7 +412,7 @@ struct VPhoneCustomFirmwareInstaller {
// drops that cache at startup when it is older than the tree; see
// VPhoneDaemon/Daemon/GuestMobileGestaltCache.swift.
let buildVersion = plan?.parameters[FirmwareGuestSystemPatchSet.buildVersionParameter] ?? spoofBuild
- let boardDeviceTree = try stageBoardDeviceTree(in: bundleDirectory, work: work)
+ let boardDeviceTree = try stageBoardDeviceTree(in: bundleDirectory, work: work, device: device)
// An environment update has no restore tree to read the device from;
// the VM's configuration says which board repair its tree takes.
try liveGuest.formUnion(patchPreboot(
@@ -1045,6 +1055,7 @@ struct VPhoneCustomFirmwareInstaller {
restore: VPhoneConfinedDirectory?,
work: WorkDirectory,
owner: uid_t?,
+ otaUserland: VPhoneConfinedDirectory?,
plan: VPhoneVirtualMachinePatchPlan?,
priorGuest: Set<String>,
kernelPatches: Set<String>?,
@@ -1126,6 +1137,21 @@ struct VPhoneCustomFirmwareInstaller {
}
}
+ // First, so every later step patches the userland that will boot.
+ if guestDevice.family == .appleTV {
+ let identifier = FirmwareGuestSystemPatchSet.tvOTAUserland
+ if on(identifier) {
+ guard let otaUserland else {
+ throw ValidationError("\(identifier) is on, but the VM has no OTAUserland folder with the staged payload chunks.")
+ }
+ try replaceTVUserland(system: system, ota: otaUserland, work: work)
+ live.insert(identifier)
+ } else if priorGuest.contains(identifier) {
+ print(" [!] \(identifier): off now, but the swapped userland cannot be reverted without a restore")
+ live.insert(identifier)
+ }
+ }
+
if let restore {
try installCryptexes(restore: restore, system: system, work: work, owner: owner)
}
@@ -1147,7 +1173,7 @@ struct VPhoneCustomFirmwareInstaller {
let cacheRelative = guestDevice.family == .appleTV
? "System/Library/Caches/com.apple.dyld"
: "System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"
- let cacheArchitecture = guestDevice.family == .appleTV ? "arm64" : "arm64e"
+ let cacheArchitecture = guestDevice.hasPlainArm64Userland ? "arm64" : "arm64e"
let dsc = try verifiedDyldCacheDirectory(system: system, relative: cacheRelative)
let widenedRegion = kernelPatches.map { $0.contains("kernel-boot-shared_region_size") }
?? version.hasPrefix("27.")
@@ -1166,7 +1192,7 @@ struct VPhoneCustomFirmwareInstaller {
print(" [!] shared region check skipped: \(error)")
}
- if guestDevice.family == .appleTV {
+ if guestDevice.hasPlainArm64Userland {
let identifier = FirmwareGuestSystemPatchSet.tvTPRO
let enabled = on(identifier)
// Unlike independent optional patches, dyld's two copies form a
@@ -1185,7 +1211,7 @@ struct VPhoneCustomFirmwareInstaller {
// keeps its old narrow rule under `environmentOnly`.
isolate(["system-vphoned-boot-install"]) {
if on("system-vphoned-boot-install") {
- try installVphoned(system: system, work: work)
+ try installVphoned(guestDevice: guestDevice, system: system, work: work)
live.insert("system-vphoned-boot-install")
}
}
@@ -1357,6 +1383,9 @@ struct VPhoneCustomFirmwareInstaller {
isolate(["system-extensions-boot-gpu_bundle"]) {
if let restore {
try installGPUBundle(restore: restore, system: system, owner: owner)
+ if guestDevice.family == .appleTV {
+ try retargetGPUBundleToTVOS(system: system, work: work)
+ }
gpuBundleReinstalled = true
} else {
print(" [·] system-extensions-boot-gpu_bundle: no restore tree; GPU bundle left as installed")
@@ -1915,11 +1944,78 @@ struct VPhoneCustomFirmwareInstaller {
}
}
- private func installVphoned(system: VPhoneConfinedDirectory, work: WorkDirectory) throws {
+ /// Research: put an Apple TV 4K userland in place of the restored Apple TV
+ /// HD one. `ota` holds the OTA's raw `payloadv2/payload.NNN` chunks and
+ /// `payload_chunks.txt`; each chunk is an Apple Archive, which `aa` extracts
+ /// as root with the owners, modes, BSD flags and APFS compression the OTA
+ /// records. The chunk list is kept on the volume so an environment update
+ /// does not extract the same userland again.
+ private func replaceTVUserland(
+ system: VPhoneConfinedDirectory,
+ ota: VPhoneConfinedDirectory,
+ work: WorkDirectory,
+ ) throws {
+ let identifier = FirmwareGuestSystemPatchSet.tvOTAUserland
+ let marker = ".vphone-ota-userland"
+ let chunkList = try ota.readData(VPhoneOTAArchive.chunkListName)
+ if try system.isRegularFile(marker), try system.readData(marker) == chunkList {
+ print(" [·] \(identifier): userland already in place")
+ return
+ }
+ let chunks = try ota.entries()
+ .filter { $0.hasPrefix("payload.") && Int($0.dropFirst("payload.".count)) != nil }
+ .sorted()
+ guard !chunks.isEmpty else {
+ throw ValidationError("\(identifier): OTAUserland has no payload.NNN chunks.")
+ }
+ // Private copies, so the archives root reads are the caller's files as
+ // they were when copied, not whatever the folder holds later.
+ for chunk in chunks {
+ try work.directory.removeItem(chunk)
+ try ota.copyFile(from: chunk, to: chunk, in: work.directory)
+ }
+ print(" [*] \(identifier): replacing the System volume with \(chunks.count) OTA payload chunks")
+ for entry in try system.entries() {
+ _ = try system.removeItem(entry)
+ }
+ let root = try system.path
+ for chunk in chunks {
+ _ = try tool("/usr/bin/aa", ["extract", "-d", root, "-i", work.file(chunk).path])
+ try work.directory.removeItem(chunk)
+ }
+ try system.writeFile(marker, contents: chunkList, mode: 0o644, owner: Self.guestOwner)
+ print(" [+] \(identifier): userland extracted")
+ }
+
+ /// The paravirtual GPU driver and its compiler plugin are built for iOS.
+ /// An arm64e tvOS process loads them once they say tvOS: dyld refuses a
+ /// library whose platform is not the process's. Each is re-signed after
+ /// the edit, then the bundle is sealed again.
+ private func retargetGPUBundleToTVOS(system: VPhoneConfinedDirectory, work: WorkDirectory) throws {
+ let gpu = "System/Library/Extensions/\(VPhonePCCGPUDriver.name)"
+ for name in ["AppleParavirtGPUMetalIOGPUFamily", "libAppleParavirtCompilerPluginIOGPUFamily.dylib"] {
+ let path = "\(gpu)/\(name)"
+ let staged = work.file(name)
+ try work.directory.removeItem(name)
+ try system.copyFile(from: path, to: name, in: work.directory)
+ var data = try Data(contentsOf: staged)
+ try MachOBuildPlatform.set(MachOBuildPlatform.tvOS, in: &data)
+ try data.write(to: staged)
+ try VPhoneSigner.sign(
+ fileAt: staged,
+ options: .init(identifier: nil, entitlements: nil, mergesExisting: true, style: .appleAdHoc),
+ )
+ try system.replaceFile(path, fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)
+ }
+ try sealGuestBundle(system: system, bundle: gpu)
+ print(" [+] GPU driver retargeted to tvOS")
+ }
+
+ private func installVphoned(guestDevice: VPhoneGuestDevice, system: VPhoneConfinedDirectory, work: WorkDirectory) throws {
// Install the same signed bytes that vm launch uses for auto-update.
// Re-signing here changes the binary hash and forces an upload and
// daemon restart on the VM's first boot.
- let vphoned = try VPhoneGuestBinaries.resolve("vphoned")
+ let vphoned = try VPhoneGuestBinaries.resolve(VPhoneResources.vphonedName(for: guestDevice.family))
let staged = work.file("vphoned")
try fm.copyItem(at: vphoned, to: staged)
try system.replaceFile("usr/bin/vphoned", fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)
@@ -2299,14 +2395,22 @@ struct VPhoneCustomFirmwareInstaller {
/// whose IPSW `recoverBoardDeviceTree` could not find.
///
/// The folder is the caller's, so the copy goes through the pinned bundle
- /// descriptor like every other read here, and more than one candidate is
- /// refused rather than guessed between.
+ /// descriptor like every other read here. Of several candidates, the
+ /// guest device's own is taken (an Apple TV 4K keeps J255's beside the
+ /// Apple TV HD base it is restored from); any other ambiguity is refused
+ /// rather than guessed between.
private func stageBoardDeviceTree(
in bundleDirectory: VPhoneConfinedDirectory,
work: WorkDirectory,
+ device: VPhoneGuestDevice,
) throws -> URL? {
- let found = try VPhoneBoardDeviceTree.kept(in: bundleDirectory)
+ var found = try VPhoneBoardDeviceTree.kept(in: bundleDirectory)
guard !found.isEmpty else { return nil }
+ if found.count > 1 {
+ let own = (device.boardDeviceTreePath as NSString).lastPathComponent
+ let matching = found.filter { $0.name == own }
+ if matching.count == 1 { found = matching }
+ }
guard found.count == 1, let board = found.first else {
throw ValidationError(
"Found \(found.count) board device trees in \(VPhoneBundleOperations.firmwareOriginalsDirectoryName): \(found.map(\.path).joined(separator: ", ")). Keep one.",
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
index 9b1a444c..c304a411 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
@@ -170,7 +170,7 @@ struct VPhoneFirmwareManifestCommand: ParsableCommand {
struct VPhoneFirmwareCatalogCommand: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "catalog",
- abstract: "Show the known iOS/iPadOS ↔ cloudOS firmware pairings (recommended per build)",
+ abstract: "Show the known iOS/iPadOS/tvOS ↔ cloudOS firmware pairings (recommended per build)",
)
@Flag(name: .shortAndLong, help: "Emit JSON") var json = false
@@ -195,7 +195,7 @@ struct VPhoneFirmwareCatalogCommand: ParsableCommand {
print("")
}
print("Firmware catalog (\(entry.productType), \(entry.name))")
- let os = entry.family == "iPad" ? "iPadOS" : "iOS"
+ let os = VPhoneGuestDevice.Family(rawValue: entry.family)?.osName ?? "iOS"
let width = max(os.count, entry.pairings.map(\.ios.name.count).max() ?? 0)
print("\(os.padding(toLength: width, withPad: " ", startingAt: 0)) recommended cloudOS")
for e in entry.pairings {
@@ -231,6 +231,16 @@ struct VPhoneFirmwarePrepareCommand: ParsableCommand {
valueName: "product-type",
))
var device: String?
+ @Option(help: ArgumentHelp(
+ "Full OTA (.aea) URL or local path for a device Apple ships no IPSW for (AppleTV14,1), restored over its base's IPSW of the same build (default: the catalog's OTA of that build)",
+ valueName: "ota",
+ ))
+ var otaSource: String?
+ @Option(help: ArgumentHelp(
+ "The OTA's AEA key in base64, as AppleDB lists it (default: the catalog's key for that build)",
+ valueName: "base64",
+ ))
+ var otaKey: String?
@Flag(help: "List downloadable IPSWs and exit") var list = false
@Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")
var projectRoot: String?
@@ -246,11 +256,15 @@ struct VPhoneFirmwarePrepareCommand: ParsableCommand {
if let device, VPhoneGuestDevice.named(device) == nil {
throw ValidationError("vphone runs \(VPhoneGuestDevice.known.map(\.productType).joined(separator: ", ")) guests, not \(device).")
}
+ if otaSource != nil || otaKey != nil, VPhoneGuestDevice.named(device)?.restoreBase == nil {
+ throw ValidationError("--ota-source and --ota-key are for a device Apple ships no IPSW for, such as --device AppleTV14,1.")
+ }
guard (1 ... 16).contains(downloadConnections) else {
throw ValidationError("--download-connections takes 1 to 16, not \(downloadConnections).")
}
let chosenDevice = device
- let device = device ?? VPhoneFirmwareCatalog.device
+ // A device without an IPSW lists and resolves its restore base's.
+ let device = VPhoneGuestDevice.named(device)?.restoreBase?.productType ?? device ?? VPhoneFirmwareCatalog.device
let urls = if needsCatalog {
try vphoneRunBlocking {
try await VPhoneFirmwareIndex.restoreURLs(forDevice: device)
@@ -309,6 +323,8 @@ struct VPhoneFirmwarePrepareCommand: ParsableCommand {
} ?? VPhoneResources.ipswCacheDirectory(),
downloadConnections: downloadConnections,
device: chosenDevice,
+ otaSource: otaSource,
+ otaKey: otaKey,
bundle: bundle,
resources: resources,
)
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift
index ae4212a1..c8c84844 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift
@@ -38,6 +38,8 @@ enum VPhoneFirmwarePreparer {
ipswCacheDirectory: URL = VPhoneResources.ipswCacheDirectory(),
downloadConnections: Int = VPhoneIPSWCache.defaultDownloadConnections,
device productType: String? = nil,
+ otaSource: String? = nil,
+ otaKey: String? = nil,
bundle: VPhoneBundle,
resources: VPhoneResources,
) throws {
@@ -64,6 +66,13 @@ enum VPhoneFirmwarePreparer {
print("[*] Removing boot-chain originals kept for the previous firmware...")
try fm.removeItem(at: staleOriginals)
}
+ // The same for a userland staged from an OTA: `cfw install` extracts it
+ // whenever it is there and its patch is on.
+ let bundleUserland = bundle.url.appendingPathComponent(VPhoneOTAArchive.userlandDirectoryName, isDirectory: true)
+ if fm.fileExists(atPath: bundleUserland.path) {
+ print("[*] Removing the OTA userland staged for the previous firmware...")
+ try fm.removeItem(at: bundleUserland)
+ }
let (phone, cloud, device) = try resolveSources(
iPhoneSource: iPhoneSource,
@@ -72,6 +81,22 @@ enum VPhoneFirmwarePreparer {
device: productType,
downloadConnections: downloadConnections,
)
+ let ota = try device.restoreBase.map { _ in
+ try resolveOTA(
+ otaSource,
+ key: otaKey,
+ device: device,
+ build: phone.build,
+ ipswCacheDirectory: ipswCacheDirectory,
+ downloadConnections: downloadConnections,
+ )
+ }
+ if ota == nil, otaSource != nil || otaKey != nil {
+ throw ValidationError("--ota-source and --ota-key are for a device Apple ships no IPSW for, such as AppleTV14,1, not \(device.productType).")
+ }
+ // Such a device is restored from its base's IPSW, so the tree and its
+ // manifest are the base's; the VM records the device itself.
+ let restored = device.restoreBase ?? device
// Preparation must use the same selection as patch/install: a serial
// configuration with the GPU disabled must not restore another PCC VM
@@ -93,7 +118,7 @@ enum VPhoneFirmwarePreparer {
throw ValidationError("Patch preset '\(selection.presetIdentifier)' did not resolve.")
}
- let name = device.restoreTreeName(version: phone.version, build: phone.build)
+ let name = restored.restoreTreeName(version: phone.version, build: phone.build)
let destination = bundle.url.appendingPathComponent(name)
let staging = bundle.url.appendingPathComponent(".firmware-prepare-\(UUID().uuidString)")
let phoneTree = staging.appendingPathComponent(name)
@@ -110,7 +135,7 @@ enum VPhoneFirmwarePreparer {
try fm.createDirectory(at: phoneTree, withIntermediateDirectories: false)
try fm.createDirectory(at: cloudTree, withIntermediateDirectories: false)
- print("[*] Extracting \(device.productType) IPSW...")
+ print("[*] Extracting \(restored.productType) IPSW...")
try VPhoneArchiveExtractor.extract(phone.file, into: phoneTree, options: .intoHostDirectory)
print("[*] Extracting cloudOS IPSW...")
try VPhoneArchiveExtractor.extract(cloud.file, into: cloudTree, options: .intoHostDirectory)
@@ -119,8 +144,14 @@ enum VPhoneFirmwarePreparer {
try mergeCloudOS(from: cloudTree, into: phoneTree)
let originalManifest = phoneTree.appendingPathComponent("BuildManifest.plist")
try clone(originalManifest, to: phoneTree.appendingPathComponent("iPhone-BuildManifest.plist"))
- try FirmwareManifest.generate(iPhoneDir: phoneTree, cloudOSDir: cloudTree, device: device, verbose: true)
- if plan.isEnabled("system-extensions-boot-gpu_bundle") {
+ try FirmwareManifest.generate(iPhoneDir: phoneTree, cloudOSDir: cloudTree, device: restored, verbose: true)
+ let userland = staging.appendingPathComponent(VPhoneOTAArchive.userlandDirectoryName, isDirectory: true)
+ if let ota {
+ try stageOTA(ota, device: device, build: phone.build, restoreTree: phoneTree, userland: userland)
+ }
+ // A plain-arm64 Apple TV cannot load the arm64e paravirtual GPU driver,
+ // and a creation may record its patch selection only after preparing.
+ if !device.hasPlainArm64Userland, plan.isEnabled("system-extensions-boot-gpu_bundle") {
let cachedDriver = cachedGPUDriver(for: cloud)
if let gpuDriverBundle {
print("[*] Staging GPU driver from local bundle...")
@@ -161,7 +192,7 @@ enum VPhoneFirmwarePreparer {
try fm.copyItem(at: source, to: destinationPlugin)
try fm.setAttributes([.posixPermissions: NSNumber(value: 0o755)], ofItemAtPath: destinationPlugin.path)
} else {
- print("[*] GPU bundle is off in the patch selection; skipping driver recovery and compiler plugin staging")
+ print("[*] GPU bundle is off for this guest; skipping driver recovery and compiler plugin staging")
}
// The destination did not exist at entry and the staging directory is
@@ -169,6 +200,10 @@ enum VPhoneFirmwarePreparer {
guard !fm.fileExists(atPath: destination.path) else { throw Error.existingRestore(destination) }
try fm.moveItem(at: phoneTree, to: destination)
print("[+] Restore tree ready: \(destination.path)")
+ if ota != nil {
+ try fm.moveItem(at: userland, to: bundleUserland)
+ print("[+] OTA userland ready: \(bundleUserland.path)")
+ }
try recordGuestDevice(device, in: bundle)
}
@@ -195,15 +230,90 @@ enum VPhoneFirmwarePreparer {
cloudOSSource, in: ipswCacheDirectory, connections: downloadConnections, label: "downloading cloudOS IPSW",
)
try VPhoneIPSWCache.checkPair(iPhone: phone, cloudOS: cloud)
- let device = VPhoneIPSWCache.guestDevice(for: phone, preferring: productType) ?? .default
- if let productType, VPhoneGuestDevice.named(productType) != device {
- throw Error.deviceNotInSource(productType, available: phone.productTypes)
+ // A device without an IPSW of its own is restored from its base's,
+ // so the IPSW must cover the base.
+ let wanted = VPhoneGuestDevice.named(productType)
+ let base = wanted?.restoreBase
+ let restored = VPhoneIPSWCache.guestDevice(for: phone, preferring: base?.productType ?? productType) ?? .default
+ if let productType, (base ?? wanted) != restored {
+ throw Error.deviceNotInSource(base?.productType ?? productType, available: phone.productTypes)
}
- try checkIPhoneName(iPhoneSource, archive: phone, device: device)
- print("[+] \(device.productType) \(phone.version) (\(phone.build)); cloudOS \(cloud.version) (\(cloud.build))")
+ try checkIPhoneName(iPhoneSource, archive: phone, device: restored)
+ let device = base == nil ? restored : wanted ?? restored
+ let over = base.map { " over the \($0.productName) IPSW" } ?? ""
+ print("[+] \(device.productType) \(phone.version) (\(phone.build))\(over); cloudOS \(cloud.version) (\(cloud.build))")
return (phone, cloud, device)
}
+ // MARK: - OTA userland
+
+ /// The OTA a device without an IPSW takes its device tree and userland
+ /// from, with its key: `source` and `key` when given, else the catalog's
+ /// OTA of the IPSW's build, downloaded into the IPSW cache's `ota` folder
+ /// unless it is already there. Its manifest is checked now, before any
+ /// IPSW is unpacked for it.
+ static func resolveOTA(
+ _ source: String?,
+ key: String?,
+ device: VPhoneGuestDevice,
+ build: String,
+ ipswCacheDirectory: URL,
+ downloadConnections: Int,
+ ) throws -> (file: URL, key: String?) {
+ let release = VPhoneFirmwareCatalog.otaRelease(for: device.productType, build: build)
+ guard source != nil || release != nil else {
+ throw ValidationError("The firmware catalog has no \(device.productType) OTA for build \(build). Pass the device's full OTA of that build with --ota-source, and its key with --ota-key.")
+ }
+ print("[*] Resolving \(device.productType) OTA...")
+ let bar = VPhoneProgressBar(label: "downloading OTA")
+ let file = try vphoneRunBlocking {
+ try await VPhoneOTAArchive.resolve(
+ source,
+ release: release,
+ in: ipswCacheDirectory,
+ connections: downloadConnections,
+ ) { done, total in
+ bar.update(done: done, total: total)
+ }
+ }
+ bar.finish()
+ // A local file of the catalog's build takes the catalog's key too.
+ let key = key ?? release?.key
+ let identity = try VPhoneOTAArchive.checkIdentity(of: file, key: key, device: device, build: build)
+ print("[+] \(device.productType) OTA \(identity.version) (\(identity.build)): \(file.path)")
+ return (file, key)
+ }
+
+ /// The device's own device tree into the restore tree, beside its base's,
+ /// and the OTA's payload chunks into `userland`.
+ private static func stageOTA(
+ _ ota: (file: URL, key: String?),
+ device: VPhoneGuestDevice,
+ build: String,
+ restoreTree: URL,
+ userland: URL,
+ ) throws {
+ print("[*] Staging \(device.productType) device tree and userland from the OTA...")
+ let flash = restoreTree.appendingPathComponent(
+ (device.boardDeviceTreePath as NSString).deletingLastPathComponent,
+ isDirectory: true,
+ )
+ try FileManager.default.createDirectory(at: flash, withIntermediateDirectories: true)
+ let staged = try VPhoneOTAArchive.stageUserland(
+ from: ota.file,
+ key: ota.key,
+ device: device,
+ build: build,
+ deviceTreeDirectory: flash,
+ userlandDirectory: userland,
+ ) { name in
+ if VPhoneOTAArchive.isChunkName(name) {
+ print(" \(name)")
+ }
+ }
+ print("[+] \(staged.deviceTree.lastPathComponent) and \(staged.chunks.count) payload chunks staged")
+ }
+
/// Resolves one source, with a progress bar while it downloads. Launchpad
/// reads the bar as `progress` lines and shows the percentage on its
/// firmware step (#590).
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift
index a7f98c0c..e38749d8 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift
@@ -52,6 +52,13 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {
valueName: "product-type",
))
var device: String?
+ @Option(help: ArgumentHelp(
+ "Full OTA (.aea) URL or local path for a device Apple ships no IPSW for (AppleTV14,1) (default: the catalog's OTA of the IPSW's build)",
+ valueName: "ota",
+ ))
+ var otaSource: String?
+ @Option(help: ArgumentHelp("The OTA's AEA key in base64, as AppleDB lists it (default: the catalog's)", valueName: "base64"))
+ var otaKey: String?
@Option(name: .shortAndLong, help: "Disk size (GB, default 64)") var diskSize: UInt64?
@Option(
name: .customLong("preset"),
@@ -79,6 +86,19 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {
@Flag(name: .customShort("v"), help: "Increase verbosity: -v tool detail, -vv guest serial, -vvv internal trace")
var verboseCount: Int
+ private var isAppleTV: Bool {
+ VPhoneGuestDevice.named(device)?.family == .appleTV
+ }
+
+ /// An Apple TV takes the TV preset; one whose userland comes from an OTA
+ /// takes the arm64e one, with the GPU driver and the userland swap.
+ private var defaultPreset: String {
+ guard let guest = VPhoneGuestDevice.named(device), guest.family == .appleTV else {
+ return VPhonePatchPreset.standardIdentifier
+ }
+ return guest.restoreBase == nil ? VPhonePatchPreset.tvOSIdentifier : VPhonePatchPreset.tvOS4KIdentifier
+ }
+
func validate() throws {
if template != nil, noTemplate {
throw ValidationError("--template and --no-template exclude each other.")
@@ -86,6 +106,18 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {
if noTemplate, try !slimming.request.isEmpty {
throw ValidationError("The slimming switches shape a template; --no-template builds the VM without one.")
}
+ if otaSource != nil || otaKey != nil, VPhoneGuestDevice.named(device)?.restoreBase == nil {
+ throw ValidationError("--ota-source and --ota-key are for a device Apple ships no IPSW for, such as --device AppleTV14,1.")
+ }
+ if isAppleTV {
+ // Templates and their setup boot drive iOS Setup Assistant and its apps.
+ if template != nil {
+ throw ValidationError("An Apple TV guest is built without a template; --template cannot be used.")
+ }
+ if try !slimming.request.isEmpty {
+ throw ValidationError("An Apple TV guest is built without a template; the slimming switches do not apply.")
+ }
+ }
_ = try slimming.resolve()
if template != nil {
let firmware = [
@@ -110,7 +142,7 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {
let unlocks = try unlockAtStartup.map { try VPhoneVirtualMachineConfigCommand.parseSwitch($0, option: "--unlock-at-startup") }
let templateUse: VPhoneVirtualMachineCreator.TemplateUse = if let template {
.identifier(template)
- } else if noTemplate {
+ } else if noTemplate || isAppleTV {
.none
} else {
.automatic
@@ -149,7 +181,9 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {
URL(fileURLWithPath: ($0 as NSString).expandingTildeInPath, isDirectory: true)
} ?? VPhoneResources.ipswCacheDirectory(),
device: device,
- patchPreset: preset ?? VPhonePatchPreset.standardIdentifier,
+ otaSource: otaSource,
+ otaKey: otaKey,
+ patchPreset: preset ?? defaultPreset,
cpuCount: cpu ?? 8,
memoryMB: memory ?? 8192,
diskSizeGB: diskSize ?? 64,
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift
index 37c5718f..3578e26c 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift
@@ -24,6 +24,10 @@ public extension VPhoneVirtualMachineCreator {
public var ipswCacheDirectory: URL
/// The guest device to take from an IPSW that covers several models.
public var device: String?
+ /// For a device without an IPSW: its full OTA and the OTA's key. Nil
+ /// takes the catalog's for the IPSW's build.
+ public var otaSource: String?
+ public var otaKey: String?
/// Which patch preset the new VM is built with. Individual patches are
/// turned on or off per VM afterwards, through its patch selection.
public var patchPreset: String
@@ -54,6 +58,8 @@ public extension VPhoneVirtualMachineCreator {
gpuDriverBundle: URL? = nil,
ipswCacheDirectory: URL = VPhoneResources.ipswCacheDirectory(),
device: String? = nil,
+ otaSource: String? = nil,
+ otaKey: String? = nil,
patchPreset: String = VPhonePatchPreset.standardIdentifier,
cpuCount: UInt = 8,
memoryMB: UInt64 = 8192,
@@ -73,6 +79,8 @@ public extension VPhoneVirtualMachineCreator {
self.gpuDriverBundle = gpuDriverBundle
self.ipswCacheDirectory = ipswCacheDirectory
self.device = device
+ self.otaSource = otaSource
+ self.otaKey = otaKey
self.patchPreset = patchPreset
self.cpuCount = cpuCount
self.memoryMB = memoryMB
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift
index 8048a330..8769100e 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift
@@ -499,6 +499,8 @@ public struct VPhoneVirtualMachineCreator {
gpuDriverBundle: options.gpuDriverBundle,
ipswCacheDirectory: options.ipswCacheDirectory,
device: options.device,
+ otaSource: options.otaSource,
+ otaKey: options.otaKey,
bundle: bundle, resources: resources,
)
print("[+] Firmware prepared (iPhone + cloudOS merged into bundle).")
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchPreset.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchPreset.swift
index cdb4dc46..2b1a627d 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchPreset.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchPreset.swift
@@ -74,6 +74,14 @@ public struct VPhonePatchPreset: Sendable, Hashable, Codable, Identifiable {
/// The identifier a VM gets when nothing asked for another preset.
public static let standardIdentifier = "standard"
+ /// The identifier an Apple TV guest gets when nothing asked for another
+ /// preset: standard without the iOS payloads tvOS has no port of.
+ public static let tvOSIdentifier = "tvos"
+
+ /// The preset an Apple TV 4K guest gets: the TV preset for an arm64e
+ /// userland taken from the device's OTA.
+ public static let tvOS4KIdentifier = "tvos-4k"
+
/// Whether this is the preset a VM gets by default.
public var isStandard: Bool {
identifier == Self.standardIdentifier
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
index bca72547..963f4739 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
@@ -64,6 +64,10 @@ fi
/bin/cp "$command_products/vphone-cli" "$macos/vphone-cli"
/bin/cp "$amfi_products/vphone-escalator" "$macos/vphone-escalator"
/bin/cp "$daemon_products/vphoned" "$guest/vphoned"
+# Apple TV guests run the same arm64 daemon. tvOS dyld loads its system
+# libraries only into a tvOS-platform process, so this copy says tvOS.
+daemon_sdk="$(/usr/bin/otool -l "$guest/vphoned" | /usr/bin/awk '/LC_BUILD_VERSION/ { found = 1 } found && $1 == "sdk" { print $2; exit }')"
+/usr/bin/xcrun vtool -set-build-version tvos 15.0 "$daemon_sdk" -replace -output "$guest/vphoned-tvos" "$guest/vphoned"
/bin/cp "$root/VPhoneDaemon/Configuration/vphoned.plist" "$guest/vphoned.plist"
/bin/cp "$guest_products/launchhook/launchdhook-vphone.dylib" "$guest/launchdhook-vphone.dylib"
/bin/cp "$guest_products/systemhook/SystemHook-vphone.dylib" "$guest/SystemHook-vphone.dylib"
@@ -141,6 +145,7 @@ compatibility_library="$(/usr/bin/xcrun swift-stdlib-tool --print \
/usr/bin/codesign --force --sign - "$frameworks/VPhonePatchKit.framework"
/usr/bin/codesign --force --sign - "$macos/vphone-cli"
/usr/bin/codesign --force --sign - --entitlements "$root/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements" "$guest/vphoned"
+/usr/bin/codesign --force --sign - --entitlements "$root/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements" "$guest/vphoned-tvos"
/usr/bin/codesign --force --sign - "$macos/vphone-escalator"
/usr/bin/codesign --force --sign - "$macos/libswiftCompatibilitySpan.vphone.dylib"
/usr/bin/codesign --force --sign - --entitlements "$root/VPhoneExecutable/VPhoneVirtualization/Resources/VPhoneVirtualization.entitlements" "$macos/vphone-vm"
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
index 04242e02..4a2f6d1f 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
@@ -93,7 +93,7 @@ for preset in "$resources/patches_presets/"*.plist; do
/usr/bin/plutil -lint -s "$preset" || { print -u2 "Malformed patch preset: ${preset:t}"; exit 1; }
done
-for name in vphoned launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \
+for name in vphoned vphoned-tvos launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \
libvcamcaptured.dylib libmisfix.dylib libhapticsfix.dylib libbatteryhealthfix.dylib libdevicehubfix.dylib libdevicename.dylib \
libprefsfix.dylib libsigninfix.dylib libvphonegyro.dylib libvphoneattitude.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
require_signed_macho "$guest/$name"
@@ -149,6 +149,10 @@ while IFS= read -r file; do
"$frameworks/"*)
[[ "$platform" != IOS ]] || { print -u2 "iOS binary in Contents/Frameworks: ${file#$bundle/}"; exit 1; }
;;
+ "$guest/vphoned-tvos")
+ # tvOS dyld refuses an iOS-platform daemon on an Apple TV guest.
+ [[ "$platform" == TVOS ]] || { print -u2 "Non-tvOS binary: ${file#$bundle/}"; exit 1; }
+ ;;
"$guest/"*)
[[ "$platform" == IOS ]] || { print -u2 "Non-iOS binary in guest-resources: ${file#$bundle/}"; exit 1; }
;;
@@ -172,12 +176,14 @@ vm_entitlements="$(/usr/bin/codesign -d --entitlements - --xml "$macos/vphone-vm
print -u2 "Guest daemon entitlements leaked into vphone-vm"
exit 1
}
-daemon_entitlements="$(/usr/bin/codesign -d --entitlements - --xml "$guest/vphoned" 2>/dev/null)"
-[[ "$daemon_entitlements" == *'com.apple.CommCenter.fine-grained'* &&
- "$daemon_entitlements" != *'com.apple.private.virtualization'* ]] || {
- print -u2 "vphoned has the wrong entitlements"
- exit 1
-}
+for daemon in vphoned vphoned-tvos; do
+ daemon_entitlements="$(/usr/bin/codesign -d --entitlements - --xml "$guest/$daemon" 2>/dev/null)"
+ [[ "$daemon_entitlements" == *'com.apple.CommCenter.fine-grained'* &&
+ "$daemon_entitlements" != *'com.apple.private.virtualization'* ]] || {
+ print -u2 "$daemon has the wrong entitlements"
+ exit 1
+ }
+done
for name in vphone-cli vphone-escalator ../Helpers/VPhoneLocation.app/Contents/MacOS/vphone-location; do
process_entitlements="$(/usr/bin/codesign -d --entitlements - --xml "$macos/$name" 2>/dev/null || true)"
[[ "$process_entitlements" != *'com.apple.private.virtualization'* &&
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
index 9d6843c6..d8fcdb49 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
@@ -1,6 +1,15 @@
{
"sourceLanguage" : "en",
"strings" : {
+ "Control Center" : {
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Control Center" } },
+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "コントロールセンター" } },
+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "제어 센터" } },
+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Trung tâm điều khiển" } },
+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "控制中心" } }
+ }
+ },
"Show Attitude Dials" : {
"extractionState" : "manual",
"localizations" : {
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
index 4e7429df..52f8f095 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
@@ -1,106 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<!--
- The preset every VM gets unless another is named.
-
- It is the CFW baseline plus the virtual camera. It draws on every patch set the
- bundle ships and turns on all of their patches bar five groups. The Frida
- Stalker pair widens what any process in the guest may do and nothing needs it in
- order to boot. The hv_vmm_present concealment — the kernel OID rename, the
- shared-cache mangle and the watchdogd patch — leaves a freshly restored 26.4
- guest on a black screen: bluetoothd caches the failed sysctl lookup,
- crash-loops, and the data migrator SpringBoard waits on never finishes. Each of
- those groups is all-or-nothing; see FirmwareKernelHypervisorPatchSet for the
- whole chain. The iPhone17,3 identity rewrites — eight device tree properties and
- the Preboot root model / target-type / compatible — are the rest of the former
- EXP variant; the camera does not need them, and with the concealment they left
- guests without location (issue #438). The fourth is the MIS
- online-authorization short-circuit: libmisfix.dylib declines the same check from
- userspace in installd, misagent and SpringBoard, so editing the shared cache for
- it buys nothing there, costs an iOS 27 guest its boot (issue #532), and on 24A435 cannot
- even be applied. See FirmwarePatchSetCatalog.misTrustAuthPatch.
- The fifth is the Settings row hiding (system-preferences-exp-root_rows and
- dyld-exp-settings_software_update_row), a preference.
- ProMotion, the 120 Hz display timing (kernel-cfw-display_promotion), is on: the
- guest renders at the rate its display advertises, and the host shows every frame.
- See FirmwarePatchSetCatalog.proMotionPatch.
- The narrow paravirtual user-client allowlist (kernel-cfw-paravirt_user_clients) is
- on: without it a daemon on a 26.x or 18.x base cannot open the paravirtual GPU,
- and cameracaptured crash-loops on it. See
- FirmwarePatchSetCatalog.paravirtUserClientsPatch.
-
- Each patch's own version gate still decides whether it lands on this pairing of
- iPhone base and cloudOS.
-
- Prewritten and reviewed. Nothing in the tool edits a preset: a VM records which
- boxes its owner changed, and those compose on top of this.
-
- FirmwarePatchSetCatalog.standardPreset is the in-code copy a dev build without a
- staged bundle falls back to. FirmwarePatchSetTests checks the two agree.
--->
<plist version="1.0">
<dict>
<key>Identifier</key>
<string>standard</string>
- <key>Title</key>
- <string>Standard</string>
- <key>Summary</key>
- <string>The patches every vphone VM needs to boot custom firmware, with a working display and camera.</string>
<key>PatchSets</key>
<array>
<dict>
- <key>Kind</key>
- <string>Bundled</string>
<key>Identifier</key>
<string>com.vphone.patchset.bootchain</string>
- </dict>
- <dict>
<key>Kind</key>
<string>Bundled</string>
- <key>Identifier</key>
- <string>com.vphone.patchset.kernel.base</string>
</dict>
<dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.base</string>
<key>Kind</key>
<string>Bundled</string>
- <key>Identifier</key>
- <string>com.vphone.patchset.kernel.cfw</string>
</dict>
<dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.cfw</string>
<key>Kind</key>
<string>Bundled</string>
- <key>Identifier</key>
- <string>com.vphone.patchset.kernel.hypervisor</string>
</dict>
<dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.hypervisor</string>
<key>Kind</key>
<string>Bundled</string>
- <key>Identifier</key>
- <string>com.vphone.patchset.kernel.frida</string>
</dict>
<dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.frida</string>
<key>Kind</key>
<string>Bundled</string>
- <key>Identifier</key>
- <string>com.vphone.patchset.devicetree</string>
</dict>
<dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.devicetree</string>
<key>Kind</key>
<string>Bundled</string>
- <key>Identifier</key>
- <string>com.vphone.patchset.guest.system</string>
</dict>
<dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.system</string>
<key>Kind</key>
<string>Bundled</string>
- <key>Identifier</key>
- <string>com.vphone.patchset.guest.display</string>
</dict>
<dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.display</string>
<key>Kind</key>
<string>Bundled</string>
+ </dict>
+ <dict>
<key>Identifier</key>
<string>com.vphone.patchset.guest.identity</string>
+ <key>Kind</key>
+ <string>Bundled</string>
</dict>
</array>
<key>Selection</key>
@@ -128,7 +86,12 @@
<string>dyld-exp-settings_software_update_row</string>
<string>system-dyld-exp-tv_tpro</string>
<string>kernel-exp-tv_tpro_pagers</string>
+ <string>system-tv-exp-ota_userland</string>
</array>
</dict>
+ <key>Summary</key>
+ <string>The patches every vphone VM needs to boot custom firmware, with a working display and camera.</string>
+ <key>Title</key>
+ <string>Standard</string>
</dict>
</plist>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
new file mode 100644
index 00000000..fe068d1b
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
@@ -0,0 +1,128 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Identifier</key>
+ <string>tvos-4k</string>
+ <key>PatchSets</key>
+ <array>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.bootchain</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.base</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.cfw</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.hypervisor</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.frida</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.devicetree</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.system</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.display</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.identity</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ </array>
+ <key>Selection</key>
+ <dict>
+ <key>Kind</key>
+ <string>Block</string>
+ <key>Patches</key>
+ <array>
+ <string>kernel-exp-frida_thread_set_state_entitlement_flag</string>
+ <string>kernel-exp-frida_vm_map_delete_immutable_code</string>
+ <string>kernel-exp-hv_vmm</string>
+ <string>dyld-exp-hv_vmm</string>
+ <string>system-watchdogd-exp-hv_vmm_cache</string>
+ <string>devicetree-exp-target_sub_type</string>
+ <string>devicetree-exp-compatible_secondary</string>
+ <string>devicetree-exp-product_fdr_product_type</string>
+ <string>devicetree-exp-product_sub_product_type</string>
+ <string>devicetree-exp-product_unique_model</string>
+ <string>devicetree-exp-product_gestalt_variants_rename</string>
+ <string>devicetree-exp-arm_io_device_type</string>
+ <string>devicetree-exp-arm_io_soc_generation</string>
+ <string>preboot-exp-devicetree_identity</string>
+ <string>dyld-exp-mis_trust_auth</string>
+ <string>system-preferences-exp-root_rows</string>
+ <string>dyld-exp-settings_software_update_row</string>
+ <string>dyld-boot-iomfb_force_kern</string>
+ <string>dyld-boot-iomfb_swapend</string>
+ <string>dyld-boot-lockdown_mode</string>
+ <string>dyld-boot-lsd_embedded_reg</string>
+ <string>dyld-boot-maxslide</string>
+ <string>dyld-boot-xpc_lwcr</string>
+ <string>dyld-cfw-camera</string>
+ <string>preboot-cfw-devicetree_board_audio</string>
+ <string>preboot-cfw-devicetree_haptics</string>
+ <string>preboot-cfw-devicetree_iphone_product</string>
+ <string>preboot-cfw-devicetree_microphone_array</string>
+ <string>system-apps-cfw-attitude</string>
+ <string>system-backboardd-cfw-gyroscope</string>
+ <string>system-campo-cfw-entitlements</string>
+ <string>system-debugserver-cfw-install</string>
+ <string>system-diskimagesiod-cfw-is_mount_complete</string>
+ <string>system-installcoordination_proxy-cfw-persona_lookup</string>
+ <string>system-jetsamproperties-cfw-disable_allowed</string>
+ <string>system-launchd-boot-jetsam_panic_guard_bypass</string>
+ <string>system-launchdaemons-boot-environment</string>
+ <string>system-locationd-cfw-disable_auto_cohort</string>
+ <string>system-mobileactivationd-boot-should_hactivate</string>
+ <string>system-paravirt_gpu-cfw-heap_index_offset</string>
+ <string>system-systemversion-cfw-build_version</string>
+ <string>system-virtiosound-cfw-hal_plugin</string>
+ <string>system-virtualaudio-cfw-microphone_graph_chains</string>
+ <string>system-virtualaudio-cfw-mute_set_throw</string>
+ <string>system-virtualaudio-cfw-speaker_graph_chains</string>
+ <string>system-virtualaudio-cfw-speaker_protection_gate</string>
+ <string>system-virtualaudio-cfw-speaker_raw_chains</string>
+ <string>system-virtualaudio-cfw-speaker_route_throws</string>
+ <string>system-virtualaudio-cfw-volume_mode_precondition</string>
+ <string>system-dyld-exp-tv_tpro</string>
+ <string>kernel-exp-tv_tpro_pagers</string>
+ </array>
+ </dict>
+ <key>Summary</key>
+ <string>Research: the Apple TV preset for an Apple TV 4K restored over the Apple TV HD, with its arm64e userland from the OTA and the paravirtual GPU driver, without the plain-arm64 TPRO patches.</string>
+ <key>Title</key>
+ <string>Apple TV 4K</string>
+</dict>
+</plist>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
new file mode 100644
index 00000000..937e4669
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
@@ -0,0 +1,128 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Identifier</key>
+ <string>tvos</string>
+ <key>PatchSets</key>
+ <array>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.bootchain</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.base</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.cfw</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.hypervisor</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.kernel.frida</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.devicetree</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.system</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.display</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>com.vphone.patchset.guest.identity</string>
+ <key>Kind</key>
+ <string>Bundled</string>
+ </dict>
+ </array>
+ <key>Selection</key>
+ <dict>
+ <key>Kind</key>
+ <string>Block</string>
+ <key>Patches</key>
+ <array>
+ <string>kernel-exp-frida_thread_set_state_entitlement_flag</string>
+ <string>kernel-exp-frida_vm_map_delete_immutable_code</string>
+ <string>kernel-exp-hv_vmm</string>
+ <string>dyld-exp-hv_vmm</string>
+ <string>system-watchdogd-exp-hv_vmm_cache</string>
+ <string>devicetree-exp-target_sub_type</string>
+ <string>devicetree-exp-compatible_secondary</string>
+ <string>devicetree-exp-product_fdr_product_type</string>
+ <string>devicetree-exp-product_sub_product_type</string>
+ <string>devicetree-exp-product_unique_model</string>
+ <string>devicetree-exp-product_gestalt_variants_rename</string>
+ <string>devicetree-exp-arm_io_device_type</string>
+ <string>devicetree-exp-arm_io_soc_generation</string>
+ <string>preboot-exp-devicetree_identity</string>
+ <string>dyld-exp-mis_trust_auth</string>
+ <string>system-preferences-exp-root_rows</string>
+ <string>dyld-exp-settings_software_update_row</string>
+ <string>dyld-boot-iomfb_force_kern</string>
+ <string>dyld-boot-iomfb_swapend</string>
+ <string>dyld-boot-lockdown_mode</string>
+ <string>dyld-boot-lsd_embedded_reg</string>
+ <string>dyld-boot-maxslide</string>
+ <string>dyld-boot-xpc_lwcr</string>
+ <string>dyld-cfw-camera</string>
+ <string>preboot-cfw-devicetree_board_audio</string>
+ <string>preboot-cfw-devicetree_haptics</string>
+ <string>preboot-cfw-devicetree_iphone_product</string>
+ <string>preboot-cfw-devicetree_microphone_array</string>
+ <string>system-apps-cfw-attitude</string>
+ <string>system-backboardd-cfw-gyroscope</string>
+ <string>system-campo-cfw-entitlements</string>
+ <string>system-debugserver-cfw-install</string>
+ <string>system-diskimagesiod-cfw-is_mount_complete</string>
+ <string>system-extensions-boot-gpu_bundle</string>
+ <string>system-installcoordination_proxy-cfw-persona_lookup</string>
+ <string>system-jetsamproperties-cfw-disable_allowed</string>
+ <string>system-launchd-boot-jetsam_panic_guard_bypass</string>
+ <string>system-launchdaemons-boot-environment</string>
+ <string>system-locationd-cfw-disable_auto_cohort</string>
+ <string>system-mobileactivationd-boot-should_hactivate</string>
+ <string>system-paravirt_gpu-cfw-heap_index_offset</string>
+ <string>system-systemversion-cfw-build_version</string>
+ <string>system-virtiosound-cfw-hal_plugin</string>
+ <string>system-virtualaudio-cfw-microphone_graph_chains</string>
+ <string>system-virtualaudio-cfw-mute_set_throw</string>
+ <string>system-virtualaudio-cfw-speaker_graph_chains</string>
+ <string>system-virtualaudio-cfw-speaker_protection_gate</string>
+ <string>system-virtualaudio-cfw-speaker_raw_chains</string>
+ <string>system-virtualaudio-cfw-speaker_route_throws</string>
+ <string>system-virtualaudio-cfw-volume_mode_precondition</string>
+ <string>system-tv-exp-ota_userland</string>
+ </array>
+ </dict>
+ <key>Summary</key>
+ <string>Standard for an Apple TV HD guest: plain-arm64 TPRO compatibility and vphoned, without the iOS display, camera, audio, sensor and shared-cache patches tvOS has no validated port of.</string>
+ <key>Title</key>
+ <string>Apple TV</string>
+</dict>
+</plist>
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
index 8c02add7..39ec6ec9 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
@@ -84,6 +84,10 @@ final class VPhoneGuestControl {
/// that has just started connects, from the manifest. Read at each connect,
/// so a change from the menu holds from the next guest start.
@ObservationIgnored var unlocksAtStartup = false
+ /// Whether the bundle's /usr/lib hooks are kept in step with the guest.
+ /// Off for an Apple TV: its preset leaves the environment out, and the
+ /// iOS hooks have no tvOS port.
+ @ObservationIgnored var syncsGuestEnvironment = true
/// Whether the Mac's location is forwarded to the guest, from the manifest.
/// The VM window's Location menu starts from it and writes it back.
@ObservationIgnored var syncsHostLocation = false
@@ -245,7 +249,7 @@ final class VPhoneGuestControl {
Task { await unlockAtStartup() }
}
}
- if capabilities.contains("environment_update") {
+ if syncsGuestEnvironment, capabilities.contains("environment_update") {
Task { await syncEnvironment() }
}
if capabilities.contains("network_ipv4"), let setting = guestIPv4Setting {
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
index 0f26855c..90f32efc 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
@@ -22,6 +22,12 @@ class VPhoneMenuController {
}
var hardwareKeyboardItem: NSMenuItem?
+ var tvControlCenterItem: NSMenuItem?
+
+ /// An Apple TV guest has a TV button that opens Control Center when held.
+ var showsTVControls = false {
+ didSet { tvControlCenterItem?.isHidden = !showsTVControls }
+ }
var onHardwareKeyboardChange: ((Bool) async throws -> Void)?
var onFrameRateDisplayChange: ((Bool) -> Void)?
/// Saves the unlock-at-startup setting to this machine's config.plist.
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
index f869aeba..7360dbef 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
@@ -21,6 +21,17 @@ extension VPhoneMenuController {
modifiers: [.command, .shift],
symbol: "house",
))
+ // Shown only for an Apple TV guest; see `showsTVControls`.
+ let controlCenter = makeItem(
+ "Control Center",
+ action: #selector(sendTVControlCenter),
+ keyEquivalent: "t",
+ modifiers: [.command, .shift],
+ symbol: "switch.2",
+ )
+ controlCenter.isHidden = true
+ tvControlCenterItem = controlCenter
+ menu.addItem(controlCenter)
// iOS has no back key, so this item and the Esc key both replay the
// system back gesture. The key equivalent is here so the menu can show
// it; VPhoneApplication intercepts Esc before the menu is consulted,
@@ -128,6 +139,10 @@ extension VPhoneMenuController {
keySender.sendHome()
}
+ @objc func sendTVControlCenter() {
+ keySender.sendTVControlCenter()
+ }
+
/// iOS has no back key. Esc and this item both replay the system back
/// gesture instead of forwarding a keystroke the guest would only read as
/// "cancel" (or, in Safari, "stop loading").
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift
index af567990..01e37035 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift
@@ -33,6 +33,8 @@ final class VPhoneApplication: NSApplication {
/// match forwards the key to the guest as a plain Escape — which is what
/// made the back gesture take a second press.
private static let escapeKeyCode: UInt16 = 53
+ /// `kVK_Home`: fn-← on a Mac laptop keyboard.
+ private static let homeKeyCode: UInt16 = 0x73
override func sendEvent(_ event: NSEvent) {
// While a sheet is up, its keys are its own: Esc must reach its
@@ -68,6 +70,17 @@ final class VPhoneApplication: NSApplication {
forwardGlobe(event, view: view)
return false
}
+ // No keyboard key reaches tvOS as the TV button, which goes Home on a
+ // press and opens Control Center when held. The Mac's Home key stands
+ // in for it through vphoned, held for as long as the key is.
+ if event.keyCode == Self.homeKeyCode, view.isTVGuest {
+ if event.type == .keyDown, !event.isARepeat {
+ view.control?.sendHIDDown(page: 0x0C, usage: 0x40)
+ } else if event.type == .keyUp {
+ view.control?.sendHIDUp(page: 0x0C, usage: 0x40)
+ }
+ return true
+ }
// tvOS consumes Escape as Back/Menu through its native keyboard.
// Bypass both the phone swipe and the menu equivalent, forwarding the
// matching press/release. Backspace remains available for text editing.
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift
index 032f6a17..f35bdcf8 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift
@@ -56,6 +56,18 @@ class VPhoneVirtualMachineKeySender {
control.sendHIDPress(page: 0x0C, usage: 0x40)
}
+ /// tvOS reads consumer Menu (0x0C/0x40) as the TV button and opens
+ /// Control Center when it is held. A USB keyboard has no such key, so
+ /// this goes through vphoned like Home.
+ func sendTVControlCenter() {
+ guard requireConnection() else { return }
+ control.sendHIDDown(page: 0x0C, usage: 0x40)
+ Task { [control] in
+ try? await Task.sleep(for: .milliseconds(1200))
+ control.sendHIDUp(page: 0x0C, usage: 0x40)
+ }
+ }
+
func sendPower() {
guard requireConnection() else { return }
control.sendHIDPress(page: 0x0C, usage: 0x30)
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift
index 1b164503..cbec7490 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift
@@ -10,6 +10,11 @@ class VPhoneVirtualMachineWindowController: NSObject, NSWindowDelegate {
private weak var virtualMachineView: VPhoneVirtualMachineView?
private(set) var touchIDMonitor: VPhoneTouchIDMonitor?
private var homeButton: NSButton?
+ /// An Apple TV's TV button: holding the titlebar button holds it in the
+ /// guest, so a click goes Home and a hold opens Control Center.
+ var homeButtonHoldsInGuest = false {
+ didSet { applyHomeButtonHold() }
+ }
private var subtitleLabel: NSTextField?
private var timers: [Timer] = []
private var keyStateObservers: [NSObjectProtocol] = []
@@ -417,7 +422,7 @@ class VPhoneVirtualMachineWindowController: NSObject, NSWindowDelegate {
}()
private func makeHomeAccessory() -> NSTitlebarAccessoryViewController {
- let button = NSButton(image: Self.homeImage, target: self, action: #selector(homePressed))
+ let button = VPhoneHomeButton(image: Self.homeImage, target: self, action: #selector(homePressed))
if #available(macOS 26.0, *) {
button.bezelStyle = .glass
button.borderShape = .circle
@@ -428,6 +433,7 @@ class VPhoneVirtualMachineWindowController: NSObject, NSWindowDelegate {
button.toolTip = VPhoneLocalization.text("Home Button")
button.translatesAutoresizingMaskIntoConstraints = false
homeButton = button
+ applyHomeButtonHold()
// A titlebar accessory takes its width from the view's frame, so the
// container is sized explicitly; otherwise the button collapses to 0.
@@ -464,6 +470,38 @@ class VPhoneVirtualMachineWindowController: NSObject, NSWindowDelegate {
// MARK: - Actions
@objc private func homePressed() {
+ // A held button already sent its press and release.
+ guard !homeButtonHoldsInGuest else { return }
control?.sendHIDPress(page: 0x0C, usage: 0x40)
}
+
+ private func applyHomeButtonHold() {
+ (homeButton as? VPhoneHomeButton)?.onHold = homeButtonHoldsInGuest
+ ? { [weak self] down in
+ if down {
+ self?.control?.sendHIDDown(page: 0x0C, usage: 0x40)
+ } else {
+ self?.control?.sendHIDUp(page: 0x0C, usage: 0x40)
+ }
+ }
+ : nil
+ }
+}
+
+// MARK: - Home Button
+
+/// Reports the press and the release around AppKit's tracking loop, which
+/// returns only when the mouse is released, inside the button or not.
+private final class VPhoneHomeButton: NSButton {
+ var onHold: ((Bool) -> Void)?
+
+ override func mouseDown(with event: NSEvent) {
+ guard isEnabled, let onHold else {
+ super.mouseDown(with: event)
+ return
+ }
+ onHold(true)
+ super.mouseDown(with: event)
+ onHold(false)
+ }
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
index ad3a1164..eb54b53d 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
@@ -114,6 +114,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
self.control = control
if !command.dfu {
control.unlocksAtStartup = vm.unlocksAtStartup
+ control.syncsGuestEnvironment = !options.isTVGuest
control.syncsHostLocation = vm.syncsHostLocation
control.guestDeviceName = Self.guestDeviceName(forConfig: options.configURL)
startNetworkServices(vm: vm, control: control)
@@ -168,6 +169,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
)
wc.captureView?.escapeIsBackGesture = !options.isPadGuest && !options.isTVGuest
wc.captureView?.isTVGuest = options.isTVGuest
+ wc.homeButtonHoldsInGuest = options.isTVGuest
windowController = wc
let fileWC = VPhoneFileWindowController()
@@ -204,6 +206,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
try VPhoneHostFilePermissions.makeAccessible(at: config)
}
mc.captureView = wc.captureView
+ mc.showsTVControls = options.isTVGuest
mc.touchIDMonitor = wc.touchIDMonitor
mc.onFilesPressed = { [weak fileWC, weak control] in
guard let fileWC, let control else { return }
diff --git a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift
index 5645eda5..d798658b 100644
--- a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift
+++ b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift
@@ -621,16 +621,18 @@ public enum VPhoneIPSWCache {
public static let guestDeviceClass = "vphone600ap"
/// Every product whose IPSW can supply the guest OS: the iPhone17,3 the
- /// catalog targets, and the iPads `VPhoneGuestDevice` knows.
+ /// catalog targets, and the iPads and Apple TV `VPhoneGuestDevice` knows.
+ /// A device restored over another's IPSW (`restoreBase`) is not one.
public static var guestProductTypes: [String] {
- VPhoneGuestDevice.known.map(\.productType)
+ VPhoneGuestDevice.known.filter { $0.restoreBase == nil }.map(\.productType)
}
/// The guest device an IPSW supplies, or nil for any other product. An IPSW
/// that covers several models gives `preferring` when it is one of them, and
/// its first known model otherwise.
public static func guestDevice(for archive: Archive, preferring productType: String? = nil) -> VPhoneGuestDevice? {
- VPhoneGuestDevice.detect(buildManifest: ["SupportedProductTypes": archive.productTypes], preferring: productType)
+ let types = archive.productTypes.filter { VPhoneGuestDevice.named($0)?.restoreBase == nil }
+ return VPhoneGuestDevice.detect(buildManifest: ["SupportedProductTypes": types], preferring: productType)
}
/// Checks each BuildManifest before anything is extracted, so a swapped
diff --git a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneOTAArchive.swift b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneOTAArchive.swift
new file mode 100644
index 00000000..695890ca
--- /dev/null
+++ b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneOTAArchive.swift
@@ -0,0 +1,575 @@
+import AppleArchive
+import CryptoKit
+import Foundation
+import System
+import VPhoneCoreKit
+
+/// A full OTA update, read with the system AppleArchive framework: no `ipsw`,
+/// no `aea` or `aa` process, nothing from Homebrew.
+///
+/// An OTA is an AEA file (`AEA1`): an Apple Archive encrypted and
+/// authenticated with a symmetric key that Apple does not publish and AppleDB
+/// records. The archive inside is segmented: its top-level entries are
+/// metadata (`TYP=M`), and each one whose `YOP` is `E` (extract) carries in its
+/// `DAT` blob another, uncompressed Apple Archive holding the next run of
+/// files. `YOP=M` is the segment manifest and `YOP=O` the owner and mode
+/// fix-ups applied after extraction, neither of which staging needs. An
+/// archive that `aea decrypt` already wrote out (`AA01`, or a `pbz*`
+/// compressed one) is read the same way, without a key.
+///
+/// Members stream from the file to their destination in fixed-size blocks,
+/// so a multi-gigabyte OTA is read once and never held in memory.
+public enum VPhoneOTAArchive {
+ public enum Error: Swift.Error, LocalizedError {
+ case missingFile(URL)
+ case notAnOTA(URL)
+ case invalidKey
+ case keyRequired(URL)
+ case wrongKey(URL)
+ case unreadable(URL, String)
+ case missingMember(String, URL)
+ case wrongDevice(URL, productTypes: [String], expected: String)
+ case wrongBuild(URL, build: String, expected: String)
+ case inconsistentChunks(URL, String)
+ case unexpectedSize(URL, expected: Int64, actual: Int64)
+ case existingUserland(URL)
+ case noSource(String)
+
+ public var errorDescription: String? {
+ switch self {
+ case let .missingFile(file):
+ "OTA not found at \(file.path). Check the path and try again."
+ case let .notAnOTA(file):
+ "\(file.lastPathComponent) is not an OTA: it is neither an AEA file nor an Apple Archive. Choose the device's full OTA (.aea)."
+ case .invalidKey:
+ "The OTA key must be 32 bytes in base64, as AppleDB lists it under the OTA's decryptionKey."
+ case let .keyRequired(file):
+ "\(file.lastPathComponent) is encrypted, and the firmware catalog has no key for it. Pass its key with --ota-key."
+ case let .wrongKey(file):
+ "\(file.lastPathComponent) did not decrypt with the given key. Check the key against AppleDB's entry for this OTA."
+ case let .unreadable(file, reason):
+ "\(file.lastPathComponent) could not be read: \(reason). Download the OTA again."
+ case let .missingMember(member, file):
+ "\(file.lastPathComponent) has no \(member). Choose the device's full OTA, not a delta update."
+ case let .wrongDevice(file, productTypes, expected):
+ "\(file.lastPathComponent) is for \(productTypes.isEmpty ? "no listed device" : productTypes.joined(separator: ", ")), not \(expected). Choose the \(expected) OTA."
+ case let .wrongBuild(file, build, expected):
+ "\(file.lastPathComponent) is build \(build), but the IPSW is \(expected). The OTA and the IPSW must be the same build."
+ case let .inconsistentChunks(file, reason):
+ "\(file.lastPathComponent) has an inconsistent payload: \(reason). Download the OTA again."
+ case let .unexpectedSize(file, expected, actual):
+ "\(file.lastPathComponent) is \(actual) bytes, not the \(expected) the catalog lists. Download the OTA again."
+ case let .existingUserland(folder):
+ "\(folder.path) already exists. Remove it, then prepare the firmware again."
+ case let .noSource(productType):
+ "The firmware catalog has no OTA for \(productType) at this build. Pass the device's full OTA with --ota-source."
+ }
+ }
+ }
+
+ /// What to do with one member, by its archive path.
+ public enum Disposition: Sendable {
+ case skip
+ /// Write it to this file, replacing whatever is there.
+ case file(URL)
+ /// Read it into memory and hand it to `received`. For small plists only.
+ case memory
+ }
+
+ /// The largest member `Disposition.memory` takes.
+ static let memoryLimit: UInt64 = 64 << 20
+ /// Bytes per blob read.
+ static let blockSize = 8 << 20
+
+ private static var typKey: ArchiveHeader.FieldKey { ArchiveHeader.FieldKey("TYP") }
+ private static var yopKey: ArchiveHeader.FieldKey { ArchiveHeader.FieldKey("YOP") }
+ private static var patKey: ArchiveHeader.FieldKey { ArchiveHeader.FieldKey("PAT") }
+ private static var datKey: ArchiveHeader.FieldKey { ArchiveHeader.FieldKey("DAT") }
+ /// `TYP` and `YOP` values are one ASCII letter.
+ private static let regularFile = UInt64(UInt8(ascii: "F"))
+ private static let extractSegment = UInt64(UInt8(ascii: "E"))
+
+ // MARK: - Key
+
+ /// The symmetric key from base64, with or without `aea`'s `base64:` prefix.
+ public static func symmetricKey(_ text: String) throws -> SymmetricKey {
+ var text = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ if text.hasPrefix("base64:") {
+ text.removeFirst("base64:".count)
+ }
+ guard let data = Data(base64Encoded: text), data.count == 32 else {
+ throw Error.invalidKey
+ }
+ return SymmetricKey(data: data)
+ }
+
+ // MARK: - Reading
+
+ /// Streams every regular file of the OTA's archive, in archive order, to
+ /// where `select` sends it. `received` is called after each member that
+ /// was not skipped, with its bytes for `.memory`; throwing from it stops
+ /// the read before any later member is written.
+ public static func readMembers(
+ _ ota: URL,
+ key: String?,
+ select: (String) throws -> Disposition,
+ received: (String, Data?) throws -> Void,
+ ) throws {
+ let opened = try openArchive(ota, key: key)
+ let outer = opened.archive
+ var buffer = [UInt8](repeating: 0, count: blockSize)
+ // AppleArchive's wrappers close their stream when released, and a
+ // decoder does not keep the stream it reads: every layer stays
+ // referenced until the read ends.
+ try withExtendedLifetime(opened) {
+ while let header = try readHeader(outer, of: ota) {
+ if case .uint(_, extractSegment)? = header.field(forKey: yopKey),
+ case let .blob(_, size, _)? = header.field(forKey: datKey)
+ {
+ let segment = SegmentByteStream(outer: outer, size: size)
+ guard let bytes = ArchiveByteStream.customStream(instance: segment),
+ let inner = ArchiveStream.decodeStream(readingFrom: bytes)
+ else {
+ throw Error.unreadable(ota, "an extract segment is not an Apple Archive")
+ }
+ try withExtendedLifetime((segment, bytes)) {
+ while let entry = try readHeader(inner, of: ota) {
+ try member(entry, of: inner, in: ota, buffer: &buffer, select: select, received: received)
+ }
+ try inner.close()
+ try bytes.close()
+ }
+ } else {
+ // A plain archive keeps its files at the top level.
+ try member(header, of: outer, in: ota, buffer: &buffer, select: select, received: received)
+ }
+ }
+ try outer.close()
+ for stream in opened.streams.reversed() {
+ try stream.close()
+ }
+ }
+ }
+
+ private struct OpenedArchive {
+ let archive: ArchiveStream
+ /// The file, then any decryption or decompression over it.
+ let streams: [ArchiveByteStream]
+ }
+
+ /// The decoded top-level archive: decrypted when the file is AEA,
+ /// decompressed when it is a compressed archive.
+ private static func openArchive(_ ota: URL, key: String?) throws -> OpenedArchive {
+ let magic = try readMagic(ota)
+ guard let file = ArchiveByteStream.fileStream(
+ path: FilePath(ota.path),
+ mode: .readOnly,
+ options: [],
+ permissions: FilePermissions(rawValue: 0o644),
+ ) else {
+ throw Error.unreadable(ota, "it could not be opened")
+ }
+ let plain: ArchiveByteStream
+ switch magic.prefix(3) {
+ case Data("AEA".utf8):
+ guard let key else { throw Error.keyRequired(ota) }
+ let symmetric = try symmetricKey(key)
+ guard let context = ArchiveEncryptionContext(from: file) else {
+ throw Error.unreadable(ota, "its AEA header is damaged")
+ }
+ try context.setSymmetricKey(symmetric)
+ guard let decrypted = ArchiveByteStream.decryptionStream(readingFrom: file, encryptionContext: context) else {
+ throw Error.wrongKey(ota)
+ }
+ plain = decrypted
+ case Data("pbz".utf8):
+ guard let decompressed = ArchiveByteStream.decompressionStream(readingFrom: file) else {
+ throw Error.unreadable(ota, "it could not be decompressed")
+ }
+ plain = decompressed
+ case Data("AA0".utf8), Data("YAA".utf8):
+ plain = file
+ default:
+ throw Error.notAnOTA(ota)
+ }
+ guard let archive = ArchiveStream.decodeStream(readingFrom: plain) else {
+ throw Error.notAnOTA(ota)
+ }
+ return OpenedArchive(archive: archive, streams: plain === file ? [file] : [file, plain])
+ }
+
+ private static func readMagic(_ file: URL) throws -> Data {
+ guard FileManager.default.fileExists(atPath: file.path) else { throw Error.missingFile(file) }
+ let handle = try FileHandle(forReadingFrom: file)
+ defer { try? handle.close() }
+ return try handle.read(upToCount: 4) ?? Data()
+ }
+
+ /// AppleArchive reports a failed AEA authentication or a truncated file
+ /// as an error from the read; name the file it came from.
+ private static func readHeader(_ stream: ArchiveStream, of ota: URL) throws -> ArchiveHeader? {
+ do {
+ return try stream.readHeader()
+ } catch {
+ throw Error.unreadable(ota, "\(error)")
+ }
+ }
+
+ private static func member(
+ _ header: ArchiveHeader,
+ of stream: ArchiveStream,
+ in ota: URL,
+ buffer: inout [UInt8],
+ select: (String) throws -> Disposition,
+ received: (String, Data?) throws -> Void,
+ ) throws {
+ guard case .uint(_, regularFile)? = header.field(forKey: typKey),
+ case let .string(_, path)? = header.field(forKey: patKey)
+ else { return }
+ let size: UInt64 = if case let .blob(_, size, _)? = header.field(forKey: datKey) { size } else { 0 }
+ switch try select(path) {
+ case .skip:
+ return
+ case let .file(destination):
+ let fm = FileManager.default
+ if fm.fileExists(atPath: destination.path) {
+ try fm.removeItem(at: destination)
+ }
+ guard fm.createFile(atPath: destination.path, contents: nil) else {
+ throw CocoaError(.fileWriteUnknown, userInfo: [NSFilePathErrorKey: destination.path])
+ }
+ let handle = try FileHandle(forWritingTo: destination)
+ defer { try? handle.close() }
+ try readBlob(size, from: stream, in: ota, buffer: &buffer) { try handle.write(contentsOf: $0) }
+ try handle.close()
+ try received(path, nil)
+ case .memory:
+ guard size <= memoryLimit else {
+ throw Error.unreadable(ota, "\(path) is \(size) bytes, larger than expected")
+ }
+ var data = Data(capacity: Int(size))
+ try readBlob(size, from: stream, in: ota, buffer: &buffer) { data.append($0) }
+ try received(path, data)
+ }
+ }
+
+ private static func readBlob(
+ _ size: UInt64,
+ from stream: ArchiveStream,
+ in ota: URL,
+ buffer: inout [UInt8],
+ consume: (Data) throws -> Void,
+ ) throws {
+ var left = size
+ while left > 0 {
+ let count = Int(min(UInt64(buffer.count), left))
+ let block = try buffer.withUnsafeMutableBytes { raw in
+ let slice = UnsafeMutableRawBufferPointer(rebasing: raw[0 ..< count])
+ do {
+ try stream.readBlob(key: datKey, into: slice)
+ } catch {
+ throw Error.unreadable(ota, "\(error)")
+ }
+ return Data(slice)
+ }
+ try consume(block)
+ left -= UInt64(count)
+ }
+ }
+
+ /// One extract segment's `DAT` blob, read in order from the enclosing
+ /// archive as the segment's own decoder asks for it.
+ private final class SegmentByteStream: ArchiveByteStreamProtocol {
+ let outer: ArchiveStream
+ var remaining: UInt64
+
+ init(outer: ArchiveStream, size: UInt64) {
+ self.outer = outer
+ remaining = size
+ }
+
+ func read(into buffer: UnsafeMutableRawBufferPointer) throws -> Int {
+ let count = Int(min(UInt64(buffer.count), remaining))
+ guard count > 0 else { return 0 }
+ try outer.readBlob(key: VPhoneOTAArchive.datKey, into: UnsafeMutableRawBufferPointer(rebasing: buffer[0 ..< count]))
+ remaining -= UInt64(count)
+ return count
+ }
+
+ func read(into _: UnsafeMutableRawBufferPointer, atOffset _: Int64) throws -> Int {
+ throw Errno.notSupported
+ }
+
+ func write(from _: UnsafeRawBufferPointer) throws -> Int {
+ throw Errno.notSupported
+ }
+
+ func write(from _: UnsafeRawBufferPointer, atOffset _: Int64) throws -> Int {
+ throw Errno.notSupported
+ }
+
+ func seek(toOffset _: Int64, relativeTo _: FileDescriptor.SeekOrigin) throws -> Int64 {
+ throw Errno.notSupported
+ }
+
+ func cancel() {}
+
+ func close() throws {}
+ }
+
+ // MARK: - Userland
+
+ /// The OTA's restore manifest, its device tree, and the root filesystem
+ /// payload: `payloadv2/payload.NNN`, each an Apple Archive of part of
+ /// the System volume with its owners, modes, flags and compression, and
+ /// `payload_chunks.txt`, which numbers them.
+ static let manifestPath = "AssetData/boot/BuildManifest.plist"
+ static let firmwarePrefix = "AssetData/boot/"
+ static let payloadPrefix = "AssetData/payloadv2/"
+ public static let chunkListName = "payload_chunks.txt"
+ /// The VM folder's copy of the payload, which `cfw install` extracts
+ /// over the restored System volume (`system-tv-exp-ota_userland`).
+ public static let userlandDirectoryName = "OTAUserland"
+
+ public struct StagedUserland: Sendable, Equatable {
+ public let version: String
+ public let build: String
+ /// The device's own `DeviceTree.<board>.im4p`.
+ public let deviceTree: URL
+ /// `payload.NNN`, in order.
+ public let chunks: [String]
+ }
+
+ /// Takes from `ota` what an OTA-userland guest needs: `device`'s device
+ /// tree into `deviceTreeDirectory`, beside the base IPSW's, and the payload
+ /// chunks with their list into `userlandDirectory`, which must not exist.
+ /// The OTA must be for `device` and of `build`, the base IPSW's; that is
+ /// checked from its manifest, which comes before the payload, so a wrong
+ /// OTA stops before the gigabytes of chunks are written. The folder is
+ /// created next to `userlandDirectory` and renamed into place complete.
+ public static func stageUserland(
+ from ota: URL,
+ key: String?,
+ device: VPhoneGuestDevice,
+ build: String,
+ deviceTreeDirectory: URL,
+ userlandDirectory: URL,
+ progress: ((String) -> Void)? = nil,
+ ) throws -> StagedUserland {
+ let fm = FileManager.default
+ guard !fm.fileExists(atPath: userlandDirectory.path) else { throw Error.existingUserland(userlandDirectory) }
+ let pending = userlandDirectory.deletingLastPathComponent()
+ .appendingPathComponent(".\(userlandDirectory.lastPathComponent).\(UUID().uuidString).partial", isDirectory: true)
+ try fm.createDirectory(at: pending, withIntermediateDirectories: false)
+ defer { try? fm.removeItem(at: pending) }
+
+ let deviceTreeName = (device.boardDeviceTreePath as NSString).lastPathComponent
+ let deviceTreeMember = firmwarePrefix + device.boardDeviceTreePath
+ let deviceTree = deviceTreeDirectory.appendingPathComponent(deviceTreeName)
+ var identity: (version: String, build: String)?
+ var wroteDeviceTree = false
+ var chunks: [String] = []
+ var chunkList: Data?
+
+ try readMembers(ota, key: key, select: { path in
+ if path == manifestPath { return .memory }
+ if path == deviceTreeMember {
+ guard identity != nil else { throw Error.missingMember(manifestPath, ota) }
+ return .file(deviceTree)
+ }
+ guard path.hasPrefix(payloadPrefix) else { return .skip }
+ let name = String(path.dropFirst(payloadPrefix.count))
+ if name == chunkListName { return .memory }
+ guard isChunkName(name) else { return .skip }
+ guard identity != nil else { throw Error.missingMember(manifestPath, ota) }
+ return .file(pending.appendingPathComponent(name))
+ }, received: { path, data in
+ if path == manifestPath {
+ identity = try checkManifest(data ?? Data(), of: ota, device: device, build: build)
+ progress?("OTA \(identity!.version) (\(identity!.build)) for \(device.productType)")
+ } else if path == deviceTreeMember {
+ wroteDeviceTree = true
+ } else if path == payloadPrefix + chunkListName {
+ chunkList = data
+ } else {
+ let name = String(path.dropFirst(payloadPrefix.count))
+ chunks.append(name)
+ progress?(name)
+ }
+ })
+
+ guard let identity else { throw Error.missingMember(manifestPath, ota) }
+ guard wroteDeviceTree else { throw Error.missingMember(deviceTreeMember, ota) }
+ guard let chunkList else { throw Error.missingMember(payloadPrefix + chunkListName, ota) }
+ chunks.sort()
+ try checkChunks(chunks, list: chunkList, of: ota)
+ try chunkList.write(to: pending.appendingPathComponent(chunkListName))
+ try fm.moveItem(at: pending, to: userlandDirectory)
+ try VPhoneHostFilePermissions.makeAccessible(at: userlandDirectory)
+ return StagedUserland(version: identity.version, build: identity.build, deviceTree: deviceTree, chunks: chunks)
+ }
+
+ /// The OTA's version and build, after checking that it is for `device`
+ /// and of `build`, read from its manifest without going further: a wrong
+ /// OTA or key is found before an IPSW is unpacked for it.
+ public static func checkIdentity(
+ of ota: URL,
+ key: String?,
+ device: VPhoneGuestDevice,
+ build: String,
+ ) throws -> (version: String, build: String) {
+ struct Found: Swift.Error {}
+ var identity: (version: String, build: String)?
+ do {
+ try readMembers(ota, key: key, select: { $0 == manifestPath ? .memory : .skip }, received: { _, data in
+ identity = try checkManifest(data ?? Data(), of: ota, device: device, build: build)
+ throw Found()
+ })
+ } catch is Found {}
+ guard let identity else { throw Error.missingMember(manifestPath, ota) }
+ return identity
+ }
+
+ /// `payload.NNN`: digits only, so no name the archive supplies can leave
+ /// the folder.
+ public static func isChunkName(_ name: String) -> Bool {
+ guard name.hasPrefix("payload.") else { return false }
+ let number = name.dropFirst("payload.".count)
+ return !number.isEmpty && number.allSatisfy(\.isASCIIDigit)
+ }
+
+ static func checkManifest(
+ _ data: Data,
+ of ota: URL,
+ device: VPhoneGuestDevice,
+ build expected: String,
+ ) throws -> (version: String, build: String) {
+ guard let manifest = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],
+ let version = manifest["ProductVersion"] as? String,
+ let build = manifest["ProductBuildVersion"] as? String
+ else {
+ throw Error.unreadable(ota, "its BuildManifest.plist is not a restore manifest")
+ }
+ let types = manifest["SupportedProductTypes"] as? [String] ?? []
+ guard types.contains(device.productType) else {
+ throw Error.wrongDevice(ota, productTypes: types, expected: device.productType)
+ }
+ guard build == expected else { throw Error.wrongBuild(ota, build: build, expected: expected) }
+ return (version, build)
+ }
+
+ /// `payload_chunks.txt` has one `index: size` line per chunk, numbered
+ /// from 0; every listed chunk must be there and nothing else.
+ static func checkChunks(_ chunks: [String], list: Data, of ota: URL) throws {
+ let lines = String(decoding: list, as: UTF8.self)
+ .split(whereSeparator: \.isNewline)
+ .map { $0.trimmingCharacters(in: .whitespaces) }
+ .filter { !$0.isEmpty }
+ let indices = lines.compactMap { Int($0.split(separator: ":").first ?? "") }
+ guard !chunks.isEmpty, indices.count == lines.count else {
+ throw Error.inconsistentChunks(ota, "\(chunkListName) does not list the chunks")
+ }
+ guard indices == Array(0 ..< indices.count) else {
+ throw Error.inconsistentChunks(ota, "\(chunkListName) is not numbered from 0")
+ }
+ let numbers = chunks.compactMap { Int($0.dropFirst("payload.".count)) }
+ guard numbers == indices else {
+ throw Error.inconsistentChunks(ota, "\(chunks.count) chunks for \(indices.count) listed")
+ }
+ }
+
+ // MARK: - Source
+
+ /// The OTA file to read: `source` when given, a local path read in place
+ /// or an HTTP(S) URL downloaded into the cache's `ota` folder; else the
+ /// catalog's `release`, downloaded there under its own name unless a copy
+ /// of its listed length is already there.
+ public static func resolve(
+ _ source: String?,
+ release: VPhoneOTARelease?,
+ in cacheDirectory: URL,
+ session: URLSession = URLSession(configuration: .ephemeral),
+ connections: Int = VPhoneIPSWCache.defaultDownloadConnections,
+ progress: (@Sendable (Int64, Int64) -> Void)? = nil,
+ ) async throws -> URL {
+ let remote: URL
+ let name: String
+ var expectedSize: Int64?
+ if let source {
+ guard let url = URL(string: source), let scheme = url.scheme?.lowercased(), scheme != "file" else {
+ let file = URL(string: source).flatMap { $0.isFileURL ? $0 : nil } ?? URL(fileURLWithPath: (source as NSString).expandingTildeInPath)
+ guard FileManager.default.fileExists(atPath: file.path) else { throw Error.missingFile(file) }
+ return file
+ }
+ guard scheme == "http" || scheme == "https" else { throw VPhoneIPSWCache.Error.unsupportedSource(source) }
+ remote = url
+ if let release, release.url == source {
+ name = release.fileName
+ expectedSize = release.size
+ } else {
+ name = cacheName(for: url)
+ }
+ } else if let release, let url = URL(string: release.url) {
+ remote = url
+ name = release.fileName
+ expectedSize = release.size
+ } else {
+ throw Error.noSource(release?.productType ?? "this device")
+ }
+
+ let fm = FileManager.default
+ let directory = cacheDirectory.appendingPathComponent("ota", isDirectory: true)
+ try fm.createDirectory(at: directory, withIntermediateDirectories: true)
+ try VPhoneHostFilePermissions.makeDirectoryAccessible(at: directory)
+ let cache = directory.appendingPathComponent(name)
+ if try reusable(cache, size: expectedSize) {
+ return cache
+ }
+ let pending = directory.appendingPathComponent(".\(name).\(UUID().uuidString).partial")
+ defer { try? fm.removeItem(at: pending) }
+ guard fm.createFile(atPath: pending.path, contents: nil) else { throw CocoaError(.fileWriteUnknown) }
+ try await VPhoneIPSWCache.download(remote, into: pending, session: session, connections: connections, progress: progress)
+ let actual = try (fm.attributesOfItem(atPath: pending.path)[.size] as? NSNumber)?.int64Value ?? 0
+ if let expectedSize, actual != expectedSize {
+ throw Error.unexpectedSize(remote, expected: expectedSize, actual: actual)
+ }
+ guard try readMagic(pending).starts(with: Data("AEA1".utf8)) else { throw Error.notAnOTA(remote) }
+ if fm.fileExists(atPath: cache.path) {
+ try fm.removeItem(at: cache)
+ }
+ try fm.moveItem(at: pending, to: cache)
+ try VPhoneHostFilePermissions.makeAccessible(at: cache)
+ return cache
+ }
+
+ /// A cached copy of the right length that starts as an AEA file. One of
+ /// another length is a damaged download and is removed.
+ static func reusable(_ cache: URL, size: Int64?) throws -> Bool {
+ let fm = FileManager.default
+ guard fm.fileExists(atPath: cache.path) else { return false }
+ let actual = (try? fm.attributesOfItem(atPath: cache.path)[.size] as? NSNumber)?.int64Value
+ let magic = (try? readMagic(cache)) ?? Data()
+ if let size, actual != size {
+ try fm.removeItem(at: cache)
+ return false
+ }
+ return magic.starts(with: Data("AEA1".utf8))
+ }
+
+ static func cacheName(for url: URL) -> String {
+ let stem = (url.lastPathComponent as NSString).deletingPathExtension
+ let safe = String(stem.prefix(48).unicodeScalars.map { scalar in
+ CharacterSet.alphanumerics.contains(scalar) && scalar.isASCII || "-._".unicodeScalars.contains(scalar)
+ ? Character(scalar) : "_"
+ })
+ let digest = SHA256.hash(data: Data(url.absoluteString.utf8))
+ let suffix = digest.prefix(6).map { String(format: "%02x", $0) }.joined()
+ return "\(safe.isEmpty ? "ota" : safe)-\(suffix).aea"
+ }
+}
+
+private extension Character {
+ var isASCIIDigit: Bool {
+ isASCII && isNumber
+ }
+}
diff --git a/VPhoneKit/VPhoneArchiveKitTests/OTAArchiveTests.swift b/VPhoneKit/VPhoneArchiveKitTests/OTAArchiveTests.swift
new file mode 100644
index 00000000..4d3828a1
--- /dev/null
+++ b/VPhoneKit/VPhoneArchiveKitTests/OTAArchiveTests.swift
@@ -0,0 +1,385 @@
+import AppleArchive
+import CryptoKit
+import Foundation
+import System
+import Testing
+@testable import VPhoneArchiveKit
+import VPhoneCoreKit
+
+/// Staging an Apple TV 4K's device tree and userland from its OTA with the
+/// system AppleArchive framework. The OTAs here are synthetic but shaped like
+/// Apple's: AEA around a segmented archive whose extract segments carry the
+/// files, plus the manifest and fix-up segments staging ignores.
+@Suite("OTA userland staging", .serialized)
+struct OTAArchiveTests {
+ // MARK: - Fixtures
+
+ private let key = SymmetricKey(size: .bits256)
+ private var keyText: String {
+ key.withUnsafeBytes { Data($0) }.base64EncodedString()
+ }
+
+ private func makeRoot() throws -> URL {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ return root
+ }
+
+ private enum Entry {
+ case file(String, Data)
+ case directory(String)
+ /// A top-level metadata entry: `yop` and an archive of `entries` in its blob.
+ case segment(Character, [Entry])
+ }
+
+ private func field(_ key: String, _ value: UInt64) -> ArchiveHeader.Field {
+ .uint(key: ArchiveHeader.FieldKey(key), value: value)
+ }
+
+ private func ascii(_ character: Character) -> UInt64 {
+ UInt64(character.asciiValue!)
+ }
+
+ /// The Apple Archive encoding of `entries`.
+ private func encode(_ entries: [Entry], in root: URL) throws -> Data {
+ let file = root.appendingPathComponent("\(UUID().uuidString).aar")
+ let stream = try #require(ArchiveByteStream.fileStream(
+ path: FilePath(file.path),
+ mode: .writeOnly,
+ options: [.create, .truncate],
+ permissions: FilePermissions(rawValue: 0o644),
+ ))
+ let encoder = try #require(ArchiveStream.encodeStream(writingTo: stream))
+ for entry in entries {
+ let header = ArchiveHeader()
+ let blob: Data?
+ switch entry {
+ case let .file(path, data):
+ header.append(field("TYP", ascii("F")))
+ header.append(.string(key: ArchiveHeader.FieldKey("PAT"), value: path))
+ blob = data
+ case let .directory(path):
+ header.append(field("TYP", ascii("D")))
+ header.append(.string(key: ArchiveHeader.FieldKey("PAT"), value: path))
+ blob = nil
+ case let .segment(yop, inner):
+ header.append(field("TYP", ascii("M")))
+ header.append(field("YOP", ascii(yop)))
+ header.append(.string(key: ArchiveHeader.FieldKey("LBL"), value: "main"))
+ blob = try encode(inner, in: root)
+ }
+ if let blob {
+ header.append(.blob(key: ArchiveHeader.FieldKey("DAT"), size: UInt64(blob.count)))
+ }
+ try encoder.writeHeader(header)
+ if let blob, !blob.isEmpty {
+ try blob.withUnsafeBytes { try encoder.writeBlob(key: ArchiveHeader.FieldKey("DAT"), from: $0) }
+ }
+ }
+ try encoder.close()
+ try stream.close()
+ defer { try? FileManager.default.removeItem(at: file) }
+ return try Data(contentsOf: file)
+ }
+
+ /// `archive` encrypted as Apple encrypts an OTA.
+ private func encrypt(_ archive: Data, to file: URL, with key: SymmetricKey) throws {
+ let stream = try #require(ArchiveByteStream.fileStream(
+ path: FilePath(file.path),
+ mode: .writeOnly,
+ options: [.create, .truncate],
+ permissions: FilePermissions(rawValue: 0o644),
+ ))
+ let context = ArchiveEncryptionContext(profile: .hkdf_sha256_aesctr_hmac__symmetric__none, compressionAlgorithm: .lzfse)
+ try context.setSymmetricKey(key)
+ let encrypted = try #require(ArchiveByteStream.encryptionStream(writingTo: stream, encryptionContext: context))
+ _ = try archive.withUnsafeBytes { try encrypted.write(from: $0) }
+ try encrypted.close()
+ try stream.close()
+ }
+
+ private func manifest(productTypes: [String] = ["AppleTV14,1"], build: String = "23L773") throws -> Data {
+ try PropertyListSerialization.data(fromPropertyList: [
+ "ProductVersion": "26.6",
+ "ProductBuildVersion": build,
+ "SupportedProductTypes": productTypes,
+ ], format: .xml, options: 0)
+ }
+
+ private func chunk(_ index: Int) -> Data {
+ Data("chunk \(index) ".utf8) + Data(repeating: UInt8(index), count: 1000 + index)
+ }
+
+ /// The members Apple's AppleTV14,1 26.6 OTA has, in its order: the
+ /// manifest and device trees in one extract segment, the payload chunks
+ /// split across two more, `.ecc` files staging skips, and fix-ups.
+ private func otaEntries(
+ manifest: Data,
+ chunks: Int = 3,
+ list: String? = nil,
+ deviceTree: Bool = true,
+ ) -> [Entry] {
+ let listed = list ?? (0 ..< chunks).map { "\($0): \(1000 + $0)" }.joined(separator: "\n") + "\n"
+ let payload = (0 ..< chunks).flatMap { index -> [Entry] in
+ let name = String(format: "AssetData/payloadv2/payload.%03d", index)
+ return [.file(name, chunk(index)), .file(name + ".ecc", Data("ecc".utf8))]
+ }
+ let split = payload.count / 2
+ var firmware: [Entry] = [
+ .file("AssetData/Info.plist", Data("info".utf8)),
+ .file("AssetData/boot/BuildManifest.plist", manifest),
+ .file("AssetData/boot/Firmware/all_flash/LLB.j255.RELEASE.im4p", Data("llb".utf8)),
+ ]
+ if deviceTree {
+ firmware.append(.file("AssetData/boot/Firmware/all_flash/DeviceTree.j255ap.im4p", Data("tree j255ap".utf8)))
+ }
+ return [
+ .segment("M", [.directory("")]),
+ .segment("E", [.directory("AssetData"), .directory("AssetData/payloadv2")]),
+ .segment("E", firmware),
+ .segment("E", Array(payload[..<split]) + [.file("AssetData/payloadv2/fixup.manifest", Data("fixup".utf8))]),
+ .segment("E", Array(payload[split...]) + [
+ .file("AssetData/payloadv2/payload_chunks.txt", Data(listed.utf8)),
+ .file("AssetData/payloadv2/prepare_payload", Data("pbzx".utf8)),
+ ]),
+ .segment("O", [.file("AssetData/payloadv2/payload.000", Data())]),
+ ]
+ }
+
+ private func makeOTA(in root: URL, _ entries: [Entry], key: SymmetricKey? = nil) throws -> URL {
+ let file = root.appendingPathComponent("AppleTV14,1_26.6_23L773_OTA.aea")
+ try encrypt(encode(entries, in: root), to: file, with: key ?? self.key)
+ return file
+ }
+
+ private func stage(_ ota: URL, in root: URL, key: String?, build: String = "23L773") throws -> VPhoneOTAArchive.StagedUserland {
+ let flash = root.appendingPathComponent("restore/Firmware/all_flash", isDirectory: true)
+ try FileManager.default.createDirectory(at: flash, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: root.appendingPathComponent("vm"), withIntermediateDirectories: true)
+ return try VPhoneOTAArchive.stageUserland(
+ from: ota,
+ key: key,
+ device: .appleTV14_1,
+ build: build,
+ deviceTreeDirectory: flash,
+ userlandDirectory: root.appendingPathComponent("vm/OTAUserland", isDirectory: true),
+ )
+ }
+
+ private func vmFolder(_ root: URL) throws -> [String] {
+ let vm = root.appendingPathComponent("vm")
+ try FileManager.default.createDirectory(at: vm, withIntermediateDirectories: true)
+ return try FileManager.default.contentsOfDirectory(atPath: vm.path)
+ }
+
+ // MARK: - Staging
+
+ @Test func `an encrypted OTA stages its device tree, payload chunks and chunk list`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ _ = try vmFolder(root)
+ let ota = try makeOTA(in: root, otaEntries(manifest: manifest()))
+
+ let staged = try stage(ota, in: root, key: keyText)
+
+ #expect(staged.version == "26.6" && staged.build == "23L773")
+ #expect(staged.chunks == ["payload.000", "payload.001", "payload.002"])
+ #expect(try Data(contentsOf: staged.deviceTree) == Data("tree j255ap".utf8))
+ #expect(staged.deviceTree.path.hasSuffix("restore/Firmware/all_flash/DeviceTree.j255ap.im4p"))
+ let userland = root.appendingPathComponent("vm/OTAUserland")
+ let names = try FileManager.default.contentsOfDirectory(atPath: userland.path).sorted()
+ #expect(names == ["payload.000", "payload.001", "payload.002", "payload_chunks.txt"])
+ for index in 0 ..< 3 {
+ #expect(try Data(contentsOf: userland.appendingPathComponent(String(format: "payload.%03d", index))) == chunk(index))
+ }
+ #expect(try String(contentsOf: userland.appendingPathComponent("payload_chunks.txt"), encoding: .utf8) == "0: 1000\n1: 1001\n2: 1002\n")
+ // Nothing else from the OTA lands beside the device tree.
+ let flash = try FileManager.default.contentsOfDirectory(atPath: staged.deviceTree.deletingLastPathComponent().path)
+ #expect(flash == ["DeviceTree.j255ap.im4p"])
+ #expect(try vmFolder(root) == ["OTAUserland"])
+ }
+
+ @Test func `a decrypted archive stages without a key`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ _ = try vmFolder(root)
+ let ota = root.appendingPathComponent("decrypted.aar")
+ try encode(otaEntries(manifest: manifest()), in: root).write(to: ota)
+
+ let staged = try stage(ota, in: root, key: nil)
+ #expect(staged.chunks.count == 3)
+ }
+
+ @Test func `an encrypted OTA needs its own key`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let ota = try makeOTA(in: root, otaEntries(manifest: manifest()))
+
+ #expect {
+ try stage(ota, in: root, key: nil)
+ } throws: { error in
+ if case .keyRequired(ota)? = error as? VPhoneOTAArchive.Error { true } else { false }
+ }
+ let other = SymmetricKey(size: .bits256).withUnsafeBytes { Data($0) }.base64EncodedString()
+ #expect {
+ try stage(ota, in: root, key: other)
+ } throws: { error in
+ if case .wrongKey? = error as? VPhoneOTAArchive.Error { true } else { false }
+ }
+ #expect(try vmFolder(root).isEmpty)
+ }
+
+ @Test func `another device's OTA stops before any chunk is written`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let ota = try makeOTA(in: root, otaEntries(manifest: manifest(productTypes: ["AppleTV11,1"])))
+
+ #expect {
+ try stage(ota, in: root, key: keyText)
+ } throws: { error in
+ guard case let .wrongDevice(_, types, expected)? = error as? VPhoneOTAArchive.Error else { return false }
+ return types == ["AppleTV11,1"] && expected == "AppleTV14,1"
+ }
+ #expect(try vmFolder(root).isEmpty)
+ let flash = root.appendingPathComponent("restore/Firmware/all_flash")
+ #expect(try FileManager.default.contentsOfDirectory(atPath: flash.path).isEmpty)
+ }
+
+ @Test func `the OTA must be the IPSW's build`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let ota = try makeOTA(in: root, otaEntries(manifest: manifest(build: "23L760")))
+
+ #expect {
+ try stage(ota, in: root, key: keyText)
+ } throws: { error in
+ guard case let .wrongBuild(_, build, expected)? = error as? VPhoneOTAArchive.Error else { return false }
+ return build == "23L760" && expected == "23L773"
+ }
+ #expect(try vmFolder(root).isEmpty)
+ }
+
+ @Test func `a chunk list that does not match the chunks leaves no userland`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let ota = try makeOTA(in: root, otaEntries(manifest: manifest(), list: "0: 1000\n1: 1001\n2: 1002\n3: 1003\n"))
+
+ #expect {
+ try stage(ota, in: root, key: keyText)
+ } throws: { error in
+ if case .inconsistentChunks? = error as? VPhoneOTAArchive.Error { true } else { false }
+ }
+ #expect(try vmFolder(root).isEmpty)
+ }
+
+ @Test func `an OTA without the device's tree is refused`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let ota = try makeOTA(in: root, otaEntries(manifest: manifest(), deviceTree: false))
+
+ #expect {
+ try stage(ota, in: root, key: keyText)
+ } throws: { error in
+ guard case let .missingMember(member, _)? = error as? VPhoneOTAArchive.Error else { return false }
+ return member.hasSuffix("DeviceTree.j255ap.im4p")
+ }
+ #expect(try vmFolder(root).isEmpty)
+ }
+
+ @Test func `an existing userland folder is not replaced`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let userland = root.appendingPathComponent("vm/OTAUserland")
+ try FileManager.default.createDirectory(at: userland, withIntermediateDirectories: true)
+ let ota = try makeOTA(in: root, otaEntries(manifest: manifest()))
+
+ #expect {
+ try stage(ota, in: root, key: keyText)
+ } throws: { error in
+ if case .existingUserland? = error as? VPhoneOTAArchive.Error { true } else { false }
+ }
+ }
+
+ @Test func `a file that is neither AEA nor Apple Archive is not an OTA`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let zip = root.appendingPathComponent("AppleTV5,3_26.6_23L773_Restore.ipsw")
+ try Data("PK\u{3}\u{4}not an ota".utf8).write(to: zip)
+
+ #expect {
+ try stage(zip, in: root, key: keyText)
+ } throws: { error in
+ if case .notAnOTA? = error as? VPhoneOTAArchive.Error { true } else { false }
+ }
+ }
+
+ // MARK: - Names and keys
+
+ @Test func `only numbered payload chunks are staged`() {
+ #expect(VPhoneOTAArchive.isChunkName("payload.000"))
+ #expect(VPhoneOTAArchive.isChunkName("payload.036"))
+ #expect(!VPhoneOTAArchive.isChunkName("payload.000.ecc"))
+ #expect(!VPhoneOTAArchive.isChunkName("payload."))
+ #expect(!VPhoneOTAArchive.isChunkName("payload_chunks.txt"))
+ #expect(!VPhoneOTAArchive.isChunkName("payload.0/../x"))
+ #expect(!VPhoneOTAArchive.isChunkName("../payload.000"))
+ }
+
+ @Test func `keys are 32 bytes of base64, with or without aea's prefix`() throws {
+ let raw = keyText
+ let plain = try VPhoneOTAArchive.symmetricKey(raw)
+ let prefixed = try VPhoneOTAArchive.symmetricKey("base64:\(raw)\n")
+ #expect(plain == key && prefixed == key)
+ #expect(throws: VPhoneOTAArchive.Error.self) { try VPhoneOTAArchive.symmetricKey("not base64") }
+ #expect(throws: VPhoneOTAArchive.Error.self) {
+ try VPhoneOTAArchive.symmetricKey(Data(repeating: 1, count: 16).base64EncodedString())
+ }
+ }
+
+ // MARK: - Source
+
+ @Test func `a local OTA is read in place and a cached catalog OTA is reused`() async throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let local = root.appendingPathComponent("local.aea")
+ try Data("AEA1local".utf8).write(to: local)
+ #expect(try await VPhoneOTAArchive.resolve(local.path, release: nil, in: root) == local)
+
+ let cached = Data("AEA1".utf8) + Data(repeating: 0, count: 60)
+ let release = VPhoneOTARelease(
+ productType: "AppleTV14,1",
+ version: "26.6",
+ build: "23L773",
+ url: "https://example.invalid/ota.aea",
+ size: Int64(cached.count),
+ key: keyText,
+ )
+ let ota = root.appendingPathComponent("ota", isDirectory: true)
+ try FileManager.default.createDirectory(at: ota, withIntermediateDirectories: true)
+ let file = ota.appendingPathComponent(release.fileName)
+ try cached.write(to: file)
+ #expect(try await VPhoneOTAArchive.resolve(nil, release: release, in: root) == file)
+ #expect(try await VPhoneOTAArchive.resolve(release.url, release: release, in: root) == file)
+ }
+
+ @Test func `a cached OTA of the wrong length is removed`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let file = root.appendingPathComponent("AppleTV14,1_26.6_23L773_OTA.aea")
+ try Data("AEA1short".utf8).write(to: file)
+
+ #expect(try !VPhoneOTAArchive.reusable(file, size: 4_764_729_344))
+ #expect(!FileManager.default.fileExists(atPath: file.path))
+ try Data("AEA1".utf8).write(to: file)
+ #expect(try VPhoneOTAArchive.reusable(file, size: 4))
+ try Data("PK..".utf8).write(to: file)
+ #expect(try !VPhoneOTAArchive.reusable(file, size: 4))
+ }
+
+ @Test func `a remote OTA outside the catalog gets a cache name of its own`() throws {
+ let url = try #require(URL(string: "https://updates.cdn-apple.com/x/com_apple_MobileAsset_SoftwareUpdate/9daea812.aea"))
+ let name = VPhoneOTAArchive.cacheName(for: url)
+ #expect(name.hasPrefix("9daea812-") && name.hasSuffix(".aea"))
+ #expect(name != VPhoneOTAArchive.cacheName(for: try #require(URL(string: "https://other.example/9daea812.aea"))))
+ }
+}
diff --git a/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneFirmwareCatalog.swift b/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneFirmwareCatalog.swift
index 70598937..bce58885 100644
--- a/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneFirmwareCatalog.swift
+++ b/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneFirmwareCatalog.swift
@@ -38,6 +38,36 @@ public struct VPhoneCloudOSOption: Sendable, Equatable {
}
}
+// MARK: - VPhoneOTARelease
+
+/// A full OTA update for a device Apple ships no IPSW for. `fw prepare`
+/// restores the base device's IPSW of the same build and takes this device's
+/// device tree and userland from the OTA (`VPhoneGuestDevice.restoreBase`).
+public struct VPhoneOTARelease: Sendable, Equatable {
+ public let productType: String
+ public let version: String
+ public let build: String
+ public let url: String
+ /// The `.aea` file's length, which a cached copy must have.
+ public let size: Int64
+ /// The AEA archive's symmetric key, base64, as AppleDB records it.
+ public let key: String
+
+ public init(productType: String, version: String, build: String, url: String, size: Int64, key: String) {
+ self.productType = productType
+ self.version = version
+ self.build = build
+ self.url = url
+ self.size = size
+ self.key = key
+ }
+
+ /// The name the IPSW cache keeps it under, in its `ota` folder.
+ public var fileName: String {
+ "\(productType)_\(version)_\(build)_OTA.aea"
+ }
+}
+
// MARK: - VPhoneFirmwareCatalog
/// The known downloadable restore/cloudOS pairings, per guest device. Prompts
@@ -380,19 +410,56 @@ public enum VPhoneFirmwareCatalog {
]),
]
+ /// tvOS releases of the Apple TV HD, one entry per IPSW, oldest first. Only
+ /// builds that have booted on the 26.4 kernel are listed; tvOS 27 dropped
+ /// the device, and no later Apple TV ships an IPSW.
+ static let tvReleases: [(devices: [String], releases: [(version: String, url: String)])] = [
+ (devices: ["AppleTV5,3"], releases: [
+ ("26.6", "https://updates.cdn-apple.com/2026SummerFCS/fullrestores/140-67287/F525C1FF-B49B-40AB-A5F4-A6F4A4847407/AppleTV5,3_26.6_23L773_Restore.ipsw"),
+ ]),
+ ]
+
+ /// Full OTAs of devices without an IPSW, oldest first. Each has a
+ /// `tvReleases` entry of the same version for its `restoreBase`. The keys
+ /// are AppleDB's.
+ public static let otaReleases: [VPhoneOTARelease] = [
+ .init(
+ productType: "AppleTV14,1",
+ version: "26.6",
+ build: "23L773",
+ url: "https://updates.cdn-apple.com/2026SummerFCS/mobileassets/140-66625/46AFA27F-8E4E-4D21-AF03-8029192EF95D/com_apple_MobileAsset_SoftwareUpdate/9daea812eb5bdb959d1ea256bc95ad7258951fd5218eb3944d162ba868d463f7.aea",
+ size: 4_764_729_344,
+ key: "zm99NLG9ucGRIqHjpHC5BVHS3v55gz7bBmVfeizDMv0=",
+ ),
+ ]
+
+ /// The full OTA of `productType` at `build`, or nil when the catalog has none.
+ public static func otaRelease(for productType: String, build: String) -> VPhoneOTARelease? {
+ otaReleases.first { $0.productType == productType && $0.build == build }
+ }
+
/// The pairings for one guest device, oldest first: the iPhone17,3 list,
/// or another model's releases with the cloudOS an iPhone17,3 of that
- /// release uses. A cellular iPad gets its Wi-Fi model's; an unknown device
- /// gets none.
+ /// release uses. A cellular iPad gets its Wi-Fi model's; an Apple TV gets
+ /// cloudOS 26.4, the only kernel its TPRO compatibility patch covers; a
+ /// device without an IPSW gets its restore base's releases that have an
+ /// OTA for it; an unknown device gets none.
public static func pairings(for device: String) -> [VPhoneFirmwarePairing] {
guard let guest = VPhoneGuestDevice.named(device) else { return [] }
guard guest.presentsBoard else { return pairings }
- let releases = (iPhoneReleases + iPadReleases).first { $0.devices.contains(guest.productType) }?.releases ?? []
+ let restored = guest.restoreBase ?? guest
+ var releases = (iPhoneReleases + iPadReleases + tvReleases).first { $0.devices.contains(restored.productType) }?.releases ?? []
+ if restored != guest {
+ let versions = Set(otaReleases.filter { $0.productType == guest.productType }.map(\.version))
+ releases = releases.filter { versions.contains($0.version) }
+ }
return releases.map { release in
- let cloudOS = recommendedCloudOS(forVersion: release.version)
+ let cloudOS = guest.family == .appleTV
+ ? VPhoneCloudOSOption(name: "cloudOS 26.4", url: cloud264)
+ : recommendedCloudOS(forVersion: release.version)
return VPhoneFirmwarePairing(
device: guest.productType,
- iosName: "\(guest.isPad ? "iPadOS" : "iOS") \(release.version)",
+ iosName: "\(guest.family.osName) \(release.version)",
iosURL: release.url,
cloudosName: cloudOS.name,
cloudosURL: cloudOS.url,
@@ -478,7 +545,7 @@ public struct VPhoneFirmwareCatalogReport: Codable, Equatable, Sendable {
public let productType: String
/// The marketing name, such as `iPad mini (A17 Pro)`.
public let name: String
- /// `iPhone` or `iPad`.
+ /// `iPhone`, `iPad` or `appleTV`.
public let family: String
public let pairings: [Entry]
public init(productType: String, name: String, family: String, pairings: [Entry]) {
diff --git a/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneFirmwarePicker.swift b/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneFirmwarePicker.swift
index f7219ae0..978bd7ff 100644
--- a/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneFirmwarePicker.swift
+++ b/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneFirmwarePicker.swift
@@ -98,9 +98,13 @@ public enum VPhoneFirmwarePicker {
read: () -> String?,
write: (String) -> Void,
) throws -> VPhoneFirmwarePairing {
- let os = VPhoneGuestDevice.named(pairings.first?.device)?.isPad == true ? "iPadOS" : "iPhone"
+ let os = switch VPhoneGuestDevice.named(pairings.first?.device)?.family {
+ case .iPad: "an iPadOS"
+ case .appleTV: "a tvOS"
+ case .iPhone, nil: "an iPhone"
+ }
let idx = try choose(
- "Select an \(os) firmware to download:",
+ "Select \(os) firmware to download:",
pairings.map(\.iosName),
maxRetries: maxRetries,
read: read,
diff --git a/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneResources.swift b/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneResources.swift
index 2f84118d..5c51beff 100644
--- a/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneResources.swift
+++ b/VPhoneKit/VPhoneCoreKit/Firmware/VPhoneResources.swift
@@ -104,12 +104,24 @@ public struct VPhoneResources: Sendable {
}
public var vphoned: URL {
- let bundled = guestResources.appendingPathComponent("vphoned")
+ vphoned(for: .iPhone)
+ }
+
+ /// The vphoned a guest of this family runs. Apple TV takes the same arm64
+ /// daemon marked as a tvOS executable: tvOS dyld refuses to load its
+ /// system libraries into an iOS-platform process.
+ public func vphoned(for family: VPhoneGuestDevice.Family) -> URL {
+ let name = Self.vphonedName(for: family)
+ let bundled = guestResources.appendingPathComponent(name)
if FileManager.default.fileExists(atPath: bundled.path) {
return bundled
}
// Dev fallback for a source build outside the bundle.
- return base.appendingPathComponent(".build/vphoned.signed")
+ return base.appendingPathComponent(".build/\(name).signed")
+ }
+
+ public static func vphonedName(for family: VPhoneGuestDevice.Family) -> String {
+ family == .appleTV ? "vphoned-tvos" : "vphoned"
}
public var gpuCompilerPlugin: URL {
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift
index bdce5bea..f0f3b2ed 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift
@@ -157,6 +157,33 @@ public struct VPhoneGuestDevice: Sendable, Equatable {
screen: .init(width: 1920, height: 1080, pixelsPerInch: 72, scale: 1.0),
)
+ /// Apple TV 4K (3rd generation), research only: Apple ships it no IPSW,
+ /// so its arm64e userland comes from an OTA over a restored Apple TV HD
+ /// (`system-tv-exp-ota_userland`). J255's device tree supplies the 2x
+ /// identity; 3840x2160 is the panel it drives at 4K.
+ public static let appleTV14_1 = VPhoneGuestDevice(
+ family: .appleTV,
+ productType: "AppleTV14,1",
+ deviceClass: "j255ap",
+ productName: "Apple TV 4K (3rd generation)",
+ screen: .init(width: 3840, height: 2160, pixelsPerInch: 144, scale: 2.0),
+ )
+
+ /// Whether the guest's userland is plain arm64 rather than arm64e: only
+ /// the Apple TV HD's. It has no paravirtual GPU driver to load, and its
+ /// dyld needs the TV TPRO patches.
+ public var hasPlainArm64Userland: Bool {
+ self == .appleTV5_3
+ }
+
+ /// The device whose IPSW is restored under this one, for a device Apple
+ /// ships no IPSW for: the Apple TV HD under the Apple TV 4K, whose own
+ /// device tree and userland `fw prepare` takes from its OTA. Nil for every
+ /// device restored from its own IPSW.
+ public var restoreBase: VPhoneGuestDevice? {
+ self == .appleTV14_1 ? .appleTV5_3 : nil
+ }
+
public static let known: [VPhoneGuestDevice] = [
iPhone17_3,
iPhone17_4, iPhone17_1, iPhone17_2, iPhone17_5,
@@ -166,7 +193,7 @@ public struct VPhoneGuestDevice: Sendable, Equatable {
iPad15_3, iPad15_5,
iPad16_3, iPad16_5,
iPad17_1, iPad17_3,
- appleTV5_3,
+ appleTV5_3, appleTV14_1,
]
/// Cellular models that ship in the same IPSW as a known Wi-Fi model and map
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
index 5c57b981..b9c1c74c 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneLaunchLayout.swift
@@ -17,10 +17,12 @@ public struct VPhoneLaunchLayout: Sendable {
resources.vphoned
}
- /// Copy the built vphoned into the bundle if present and different.
+ /// Copy the built vphoned for the machine's guest family into the bundle
+ /// if present and different.
@discardableResult
public func stageVphoned(into bundle: VPhoneBundle) throws -> Bool {
let fm = FileManager.default
+ let vphoned = resources.vphoned(for: bundle.manifest.guestDevice.family)
guard fm.fileExists(atPath: vphoned.path) else {
throw VPhoneGuestBinaries.Error.missing("vphoned.signed", [vphoned])
}
diff --git a/VPhoneKit/VPhoneCoreKitTests/Firmware/FirmwareCatalogReportTests.swift b/VPhoneKit/VPhoneCoreKitTests/Firmware/FirmwareCatalogReportTests.swift
index 8fc507c5..37d84a14 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Firmware/FirmwareCatalogReportTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Firmware/FirmwareCatalogReportTests.swift
@@ -16,10 +16,9 @@ struct FirmwareCatalogReportTests {
}
}
- @Test func `lists curated guests without advertising unlisted TV pairings`() {
+ @Test func `lists every curated guest`() {
let report = VPhoneFirmwareCatalog.report
- #expect(report.devices.map(\.productType) == VPhoneGuestDevice.known.filter { $0.family != .appleTV }.map(\.productType))
- #expect(VPhoneFirmwareCatalog.pairings(for: "AppleTV5,3").isEmpty)
+ #expect(report.devices.map(\.productType) == VPhoneGuestDevice.known.map(\.productType))
#expect(report.devices.first?.pairings == report.pairings)
for device in report.devices.dropFirst() {
#expect(device.family == VPhoneGuestDevice.named(device.productType)?.family.rawValue)
@@ -28,6 +27,47 @@ struct FirmwareCatalogReportTests {
}
}
+ @Test func `the Apple TV 4K pairs the Apple TV HD IPSW of each build with an OTA`() throws {
+ let pairings = VPhoneFirmwareCatalog.pairings(for: "AppleTV14,1")
+ #expect(pairings.map(\.iosName) == ["tvOS 26.6"])
+ let hd = VPhoneFirmwareCatalog.pairings(for: "AppleTV5,3")
+ for p in pairings {
+ #expect(p.device == "AppleTV14,1")
+ // Restored from the HD's IPSW, on the same cloudOS.
+ let base = try #require(hd.first { $0.iosName == p.iosName })
+ #expect(p.iosURL == base.iosURL && p.cloudosURL == base.cloudosURL)
+ }
+ let ota = try #require(VPhoneFirmwareCatalog.otaRelease(for: "AppleTV14,1", build: "23L773"))
+ #expect(ota.version == "26.6")
+ #expect(ota.url.hasPrefix("https://updates.cdn-apple.com/") && ota.url.hasSuffix(".aea"))
+ #expect(ota.size == 4_764_729_344)
+ #expect(Data(base64Encoded: ota.key)?.count == 32)
+ #expect(ota.fileName == "AppleTV14,1_26.6_23L773_OTA.aea")
+ #expect(VPhoneFirmwareCatalog.otaRelease(for: "AppleTV14,1", build: "23L760") == nil)
+ #expect(VPhoneFirmwareCatalog.otaRelease(for: "AppleTV5,3", build: "23L773") == nil)
+ // Every OTA has a base release of its version to be restored over.
+ for release in VPhoneFirmwareCatalog.otaReleases {
+ let base = try #require(VPhoneGuestDevice.named(release.productType)?.restoreBase)
+ #expect(VPhoneFirmwareCatalog.pairings(for: base.productType).contains { $0.iosName.hasSuffix(" \(release.version)") })
+ }
+ }
+
+ @Test func `Apple TV pairings are tvOS releases on cloudOS 26.4`() throws {
+ let pairings = VPhoneFirmwareCatalog.pairings(for: "AppleTV5,3")
+ #expect(pairings.map(\.iosName) == ["tvOS 26.6"])
+ for p in pairings {
+ #expect(p.device == "AppleTV5,3")
+ #expect(p.iosURL.hasPrefix("https://updates.cdn-apple.com/"))
+ #expect(p.iosURL.contains("/AppleTV5,3_"))
+ #expect(p.iosURL.hasSuffix("_Restore.ipsw"))
+ #expect(p.cloudosName == "cloudOS 26.4")
+ #expect(p.cloudosURL == VPhoneFirmwareCatalog.cloud264)
+ }
+ let tv = try #require(VPhoneFirmwareCatalog.report.devices.first { $0.productType == "AppleTV5,3" })
+ #expect(tv.family == "appleTV")
+ #expect(tv.name == "Apple TV HD")
+ }
+
@Test func `i pad pairings come from an IPSW that covers the device`() {
for guest in VPhoneGuestDevice.known where guest.isPad {
let pairings = VPhoneFirmwareCatalog.pairings(for: guest.productType)
diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift
index 23e25029..edf08b00 100644
--- a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift
@@ -21,7 +21,7 @@ struct GuestDeviceTests {
let tv = ["SupportedProductTypes": ["AppleTV5,3"]]
#expect(VPhoneGuestDevice.detect(buildManifest: tv) == .appleTV5_3)
#expect(VPhoneGuestDevice.covered(by: tv) == [.appleTV5_3])
- #expect(VPhoneGuestDevice.detect(buildManifest: ["SupportedProductTypes": ["AppleTV14,1"]]) == nil)
+ #expect(VPhoneGuestDevice.detect(buildManifest: ["SupportedProductTypes": ["AppleTV11,1"]]) == nil)
#expect(!VPhoneGuestDevice.appleTV5_3.isPad)
#expect(VPhoneGuestDevice.appleTV5_3.presentsBoard)
#expect(VPhoneGuestDevice.appleTV5_3.family.osName == "tvOS")
@@ -30,6 +30,18 @@ struct GuestDeviceTests {
== "iPhoneOS_AppleTV5,3_26.4_23L243_Restore")
}
+ @Test
+ func `the Apple TV 4K is an arm64e TV guest at 2x restored over the Apple TV HD`() throws {
+ let tv4k = try #require(VPhoneGuestDevice.named("AppleTV14,1"))
+ #expect(tv4k == .appleTV14_1 && tv4k.family == .appleTV)
+ #expect(tv4k.boardDeviceTreePath == "Firmware/all_flash/DeviceTree.j255ap.im4p")
+ #expect(tv4k.screen == .init(width: 3840, height: 2160, pixelsPerInch: 144, scale: 2.0))
+ #expect(!tv4k.hasPlainArm64Userland && VPhoneGuestDevice.appleTV5_3.hasPlainArm64Userland)
+ #expect(!VPhoneGuestDevice.iPhone17_3.hasPlainArm64Userland)
+ #expect(tv4k.restoreBase == .appleTV5_3)
+ #expect(VPhoneGuestDevice.appleTV5_3.restoreBase == nil && VPhoneGuestDevice.iPhone17_3.restoreBase == nil)
+ }
+
@Test
func `a TV guest persists its identity and provisional landscape canvas`() throws {
let manifest = VPhoneVirtualMachineManifest.newVM().updating(guestDevice: .appleTV5_3)
diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift
index 9adfe377..f332aa1f 100644
--- a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/LaunchLayoutTests.swift
@@ -187,6 +187,32 @@ struct LaunchLayoutTests {
#expect(try layout.stageVphoned(into: bundle) == false)
}
+ @Test func `stage vphoned picks the tvOS daemon for an Apple TV guest`() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ let guest = root.appendingPathComponent("guest-resources")
+ try FileManager.default.createDirectory(at: guest, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ try Data([1]).write(to: guest.appendingPathComponent("vphoned"))
+ try Data([2]).write(to: guest.appendingPathComponent("vphoned-tvos"))
+ let resources = VPhoneResources(base: root)
+ #expect(resources.vphoned.lastPathComponent == "vphoned")
+ #expect(resources.vphoned(for: .iPad).lastPathComponent == "vphoned")
+ #expect(resources.vphoned(for: .appleTV).lastPathComponent == "vphoned-tvos")
+
+ let base = VPhoneVirtualMachineManifest(
+ cpuCount: 2,
+ memorySize: 1024 * 1024,
+ romImages: .init(avpBooter: "a", avpSEPBooter: "b"),
+ )
+ for (device, expected) in [(VPhoneGuestDevice.appleTV5_3, Data([2])), (.iPhone17_3, Data([1]))] {
+ let bundleDir = root.appendingPathComponent(device.productType)
+ try FileManager.default.createDirectory(at: bundleDir, withIntermediateDirectories: true)
+ let bundle = VPhoneBundle(url: bundleDir, manifest: base.updating(guestDevice: device))
+ #expect(try VPhoneLaunchLayout(resources: resources).stageVphoned(into: bundle))
+ #expect(try Data(contentsOf: bundleDir.appendingPathComponent(".vphoned.signed")) == expected)
+ }
+ }
+
@Test func `stage vphoned fails when source absent`() throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)