Run a virtual iPhone on an Apple Silicon Mac.
Swift
Add Apple TV HD guest support for tvOS 26.4
^^c1791809ed5e
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 9556cec3..7658ee82 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -1,5 +1,23 @@# Patch Comparison: Regular / Development / Jailbreak / Experimental+> **tvOS 26.4 support (2026-10-15).** AppleTV5,3 / J42d uses a+> monolithic arm64 TVOS userland with the cloudOS 26.4 vphone600ap kernel.+> `devicetree-cfw-tv_app_architecture` copies the donor's concrete app architecture.+> `system-dyld-exp-tv_tpro` reversibly disables the two hardware-TPRO parameter+> lookups in standalone and cached dyld, preserving native page-in linking.+> `kernel-exp-tv_tpro_pagers` changes the native tunable's four-byte default+> through validated name/descriptor/startup-registration discovery. Both TPRO+> operations are opt-in, off in Standard. The persistent kernel fix allowed a+> normal four-CPU boot into TVSetup and Settings, with arrow/Return/Escape input.+> Activation remains Failed; audio and third-party apps are unverified.+> Diagnostic helpers and unused approaches are excluded from this PR;+> a normal boot and Escape navigation were confirmed after their removal.+> TV dyld installation requires a private APFS disk clone and validates its original+> standalone backup and cache undo before modifying an existing patch. Paired+> errors abort the install before disk replacement; rollback retires the undo+> record only after cache re-attestation and standalone restoration succeed.+> Details and evidence: [tvOS support](Firmware/tvos_support.md).+> **iOS 27 disabled services (2026-10-13):**> `system-jetsamproperties-cfw-disable_allowed` removes every> `DisableAllowed = false` fromdiff --git a/Research/Firmware/tvos_support.md b/Research/Firmware/tvos_support.mdnew file mode 100644index 00000000..cee0d62b--- /dev/null+++ b/Research/Firmware/tvos_support.md@@ -0,0 +1,215 @@+# tvOS support++Validated on 2026-10-15: AppleTV5,3 tvOS 26.4 beta 1 (23L5208m) on the+cloudOS 26.4 beta (23E5207q) vphone600ap platform boots to TVSetup and Settings.+The same VM booted normally with four CPUs after installing the persistent+kernel fix, without a debugger. Arrow keys, Return and Escape navigation were+confirmed by the user. Device > Back sends the same native Escape key pair;+that menu action has not been separately confirmed.++Validation covers the specific donor/kernel pairing listed below. Settings >+About reports tvOS 26.4 (23L5208m), an IPv4 address, and 1080p HD / 120 Hz.+The display mode is reported metadata, not measured rendering performance.+Activation reports Failed and the model is Not Applicable. Apple services,+audio, video playback, third-party apps and long-term stability remain untested.+No tvOS pairing is advertised in the firmware catalog.++## Firmware and storage++- Donor: Apple TV HD, `AppleTV5,3`, board `j42dap`, plain arm64 / TVOS.+- Kernel, boot chain and SEP: cloudOS 26.4 beta, `vphone600ap`.+- [Apple-hosted donor IPSW](https://updates.cdn-apple.com/2026WinterSeed/fullrestores/089-95491/1679DEB6-820D-40A8-9F28-1735EFDFB01D/AppleTV5,3_26.4_23L5208m_Restore.ipsw).+- Verified SHA-256: `2128c348ffbb0f65096ac3e7be22e901e09773e02c17edbce4c0647769c24ae8`;+ length 5,269,316,627 bytes.+- The lab reuses one logical 32 GB disk, about 11 GiB allocated. No second+ VM, template, or automatic PCC GPU recovery disk was created.++The matching release numbers motivated the pairing investigation; they do not establish+compatibility with other builds. The beta archive, FirmwareOriginals and+restore tree are retained locally for reproducibility and rollback.++## Reproducing the validated configuration++Use the built bundle's `vphone-cli` on a host configured according to+[host setup](../../Documents/Guides/host-setup.md). Both IPSWs must be supplied+locally: the donor above and cloudOS 23E5207q. Other pairings are unvalidated.+The VM and the installer's temporary directory must share an APFS volume;+TV guest updates refuse an in-place fallback when cloning is unavailable.+Copy-on-write updates share unchanged blocks, but require space for changed data.++For a **new** VM only, run these commands in zsh, replacing the three paths.+Do not run `vm new` or restore against an existing VM you want to preserve.+This manual pipeline creates one 32 GB disk and no template. The historical+`--iphone-source` option accepts the TV donor.++```zsh+cli='/absolute/path/to/VPhone.bundle/Contents/MacOS/vphone-cli'+tv_ipsw='/absolute/path/to/AppleTV5,3_26.4_23L5208m_Restore.ipsw'+cloud_ipsw='/absolute/path/to/cloudOS_23E5207q_Restore.ipsw'+export VPHONE_LIBRARY_ROOT="$HOME/vphone-tvos"+vm='tvos-26_4-beta'+"$cli" vm new "$vm" --cpu 4 --memory 4096 --disk-size 32+"$cli" fw set-patches "$vm" --preset standard \+ --allow kernel-exp-tv_tpro_pagers \+ --allow system-dyld-exp-tv_tpro \+ --block dyld-boot-iomfb_force_kern \+ --block dyld-boot-iomfb_swapend \+ --block dyld-boot-lockdown_mode \+ --block dyld-boot-lsd_embedded_reg \+ --block dyld-boot-maxslide \+ --block dyld-boot-xpc_lwcr \+ --block dyld-cfw-camera \+ --block preboot-cfw-devicetree_board_audio \+ --block preboot-cfw-devicetree_haptics \+ --block preboot-cfw-devicetree_iphone_product \+ --block preboot-cfw-devicetree_microphone_array \+ --block system-apps-cfw-attitude \+ --block system-backboardd-cfw-gyroscope \+ --block system-campo-cfw-entitlements \+ --block system-debugserver-cfw-install \+ --block system-diskimagesiod-cfw-is_mount_complete \+ --block system-extensions-boot-gpu_bundle \+ --block system-installcoordination_proxy-cfw-persona_lookup \+ --block system-jetsamproperties-cfw-disable_allowed \+ --block system-launchd-boot-jetsam_panic_guard_bypass \+ --block system-launchd_cache_loader-boot-unsecure_cache_gate \+ --block system-launchdaemons-boot-environment \+ --block system-locationd-cfw-disable_auto_cohort \+ --block system-mobileactivationd-boot-should_hactivate \+ --block system-systemversion-cfw-build_version \+ --block system-virtiosound-cfw-hal_plugin \+ --block system-virtualaudio-cfw-microphone_graph_chains \+ --block system-virtualaudio-cfw-mute_set_throw \+ --block system-virtualaudio-cfw-speaker_graph_chains \+ --block system-virtualaudio-cfw-speaker_protection_gate \+ --block system-virtualaudio-cfw-speaker_raw_chains \+ --block system-virtualaudio-cfw-speaker_route_throws \+ --block system-virtualaudio-cfw-volume_mode_precondition \+ --block system-vphoned-boot-install+"$cli" fw prepare "$vm" --device AppleTV5,3 \+ --iphone-source "$tv_ipsw" --cloudos-source "$cloud_ipsw"+"$cli" fw patch "$vm"+"$cli" vm launch "$vm" --dfu+```++Leave DFU running. In a second terminal, set the same `cli`, `vm` and+`VPHONE_LIBRARY_ROOT` variables, then run:++```zsh+"$cli" restore "$vm"+"$cli" vm stop "$vm"+sudo "$cli" cfw install --library-root "$VPHONE_LIBRARY_ROOT" "$vm" --keep-artifacts+"$cli" vm launch "$vm"+```++If host preflight refuses the VM binary, run its printed allowlist command and+retry the launch. Navigate setup with arrows and Return; Escape goes back.+No vphoned first-boot probe is appropriate for this configuration.++`fw set-patches` replaces all overrides, so always retain the entire selection+above. On an installed, stopped VM, guest-side changes use `sudo "$cli" cfw+update-environment --library-root "$VPHONE_LIBRARY_ROOT" "$vm"`; kernel changes+use `sudo "$cli" cfw update-kernel --library-root "$VPHONE_LIBRARY_ROOT" "$vm"`.+Neither requires another restore. A prior research installation must first+remove its diagnostic jobs with the preserved research bundle; the PR bundle+does not contain those removed patch implementations.++## Required implementation++1. Admit AppleTV5,3 explicitly. Copy its TV idiom, identity, 1x artwork and+ `app-macho-architecture=arm64` from the donor device tree. The virtual display+ uses 1920x1080; 72 ppi is a provisional VM value, not television metadata.+ Preserve the virtual identity in the restore tree. Non-iPhone restore-tree+ names retain the existing `iPhoneOS_…_Restore` compatibility prefix.+2. Admit the monolithic TV filesystem only after validating its erase identity,+ TVOS platform and required component paths. It contains neither OS nor App+ cryptex; its cache remains at `System/Library/Caches/com.apple.dyld` and uses+ architecture `arm64`. Other guest families keep their cryptex layout.+3. Rehash the unchanged TV `OS`, `SystemVolume`, `StaticTrustCache` and+ `Ap,SystemVolumeCanonicalMetadata` with SHA-384 in the hybrid manifest.+ J42d's SHA-1 donor digests failed PCC metadata authentication and sealing;+ the corrected hybrid restore completed.+4. Apply the existing seputil/gigalocker repair. Block unvalidated iOS guest+ payloads, graphics/audio hooks and shared-cache patches. Preparation now+ respects the GPU patch selection, avoiding an unnecessary recovery VM.+5. Explicitly enable `system-dyld-exp-tv_tpro` and+ `kernel-exp-tv_tpro_pagers`. Both are off in Standard. Keep the donor's+ native shared cache and page-in linking intact.+6. Forward Escape to the TV's native virtual keyboard instead of consuming+ it as an iPhone edge swipe. Device > Back uses the same keyboard path,+ without vphoned. Backspace remains available for editing text.++The dyld operation rewrites only the exact `dyld_hw_tpro` and+`dyld_hw_tpro_pagers` parameter-name prefixes to `vphn`, in both standalone+and cached dyld. It validates TVOS/arm64, symbol bounds, getenv references and+presence checks, then re-attests the modified code-signature slots. A backup+and shared-cache undo record support paired rollback. An existing patch must+have both records before another write. Paired failures abort the install and+discard its private disk clone; rollback retires undo only after both images+are restored.++## Kernel cause and persistent fix++The embedded research kernel UUID was+`784F88D3-2AF5-3D4A-AB00-365607646E44`. Native runtime tracing caught+MobileGestaltHelper, UUID `7CF0ED37-E30C-38AA-AE6C-F10A7CA15BC8`, at a libobjc+store with ESR `0x9200004f` and unslid FAR `0x1ea57c808`. Its DATA_CONST+RW|COPY request (`0x13`, size `0xa23c000`) returned KERN_PROTECTION_FAILURE.+Following the remap/extract calls showed a TPRO-tagged map entry while dyld+used an ordinary writable request. The source entry allowed maximum RW.+The local symbol dataset was unavailable; function descriptions were derived+from native control flow and correlated with XNU, not claimed symbol lookups.++The native `sprr_tpro_pagers` tunable controls tagging these ranges. Setting+its live value from 1 to 0 made subsequent COPY requests succeed and allowed+TVSetup to appear. No other functional debugger write was made.++The persistent patch changes only the integer tunable's initial four bytes.+It locates the unique NUL-terminated name, validates the four-byte integer+startup descriptor and its data pointer, and requires one TUNABLES registration+with an executable initializer. It accepts only defaults 0 or 1. Both segment+bounds and actual file bounds are checked. The fileset's outer `__DATA` contains+the embedded `__KLDDATA`. No observed offsets or instruction words are baked+into the patch; unsupported or ambiguous layouts fail the selected operation.+Its applicability is limited to the 26.4 donor/kernel pairing.++`cfw update-kernel` rebuilt from FirmwareOriginals and replaced only the+installed Preboot kernel payload, retaining the manifest and volumes. A normal+four-CPU boot subsequently reached the Language screen, and the user navigated+to Settings > About. Disabling the kernel patch and running the same command+rebuilds from pristine bytes; the dyld operation is separately reversible.++## Validation and PR scope++The trimmed PR passed:++- 89 tests in seven firmware suites, including the real research kernel's+ exact four-byte change, blocked-gate byte identity and malformed/truncated+ tunable descriptor rejection.+- 36 final follow-up tests in four suites covering TV guest patch admission,+ TV dyld, patch declarations,+ missing-backup rejection and injected rollback failures. These overlap+ the preceding firmware suites and are not an additional unique-test count.+- 17 core identity/catalog tests, 15 archive admission tests, and the+ Launchpad IPSW classification tests.+- The final complete VPhone bundle build and bundle admission checks.+- A normal four-CPU, 4 GiB boot after removing the diagnostic patches. The+ user confirmed the UI works and Escape goes back. Device > Back uses the+ same key path but has not been separately confirmed.++The PR excludes diagnostic executables, launchd logging/cache modifications,+the abandoned page-in-linking fallback and the unused conclave change.+The lab's guest receipt after cleanup contains only TV dyld TPRO and the two+seputil/gigalocker repairs. TV environment updates recognize the guest receipt+when vphoned is omitted. Unreadable cache undo logs abort instead of being+silently replaced.++The titlebar Home button requires vphoned and remains disabled in this+configuration. Native arrow, Return and Escape input does not require it.+Activation, model metadata, audio and Apple services retain the limitations+listed above; this validation does not establish full Apple TV compatibility.++Research helpers and the prior bundle are retained locally under+`.build/tvos-research/pr-backup`, outside the PR. Boot evidence is in+`.build/tvos-research/pr-clean-boot.log`; the Settings screenshot and earlier+native runtime transcripts remain beside it. No second VM disk was created.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareDaemons.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareDaemons.swiftindex 4134a3a3..6bf4dba7 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareDaemons.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareDaemons.swift@@ -6,6 +6,7 @@// patchers.import Foundation+import VPhoneCoreKit// MARK: - CustomFirmwareDaemons@@ -47,6 +48,44 @@ public enum CustomFirmwareDaemons {}}+ /// tvOS on AppleTV5,3 carries its frameworks and cache in the OS image,+ /// rather than the two cryptexes iPhone/iPad firmware supplies. This is+ /// manifest admission only; it does not establish that the userland boots.+ public enum FilesystemLayout: Sendable, Equatable {+ case cryptex(CryptexPaths)+ case monolithic+ }++ public static func filesystemLayout(buildManifest url: URL) throws -> FilesystemLayout {+ let manifest = try loadPlist(url)+ guard let identities = manifest["BuildIdentities"] as? [PlistDict], !identities.isEmpty else {+ throw DaemonError.invalidPlist(url.path)+ }+ // A partial or malformed cryptex declaration is never evidence for a+ // monolithic image. Keep the original lookup and its path validation.+ let hasCryptex = identities.contains { identity in+ let entries = identity["Manifest"] as? PlistDict ?? [:]+ return entries["Cryptex1,SystemOS"] != nil || entries["Cryptex1,AppOS"] != nil+ }+ if hasCryptex {+ return .cryptex(try cryptexPaths(buildManifest: url))+ }+ guard let products = manifest["SupportedProductTypes"] as? [String], !products.isEmpty,+ products.allSatisfy({ VPhoneGuestDevice.named($0)?.family == .appleTV }),+ let erase = identities.first(where: {+ ($0["Info"] as? PlistDict)?["RestoreBehavior"] as? String == "Erase"+ }),+ erase["Ap,SDKPlatform"] as? String == "appletvos",+ let entries = erase["Manifest"] as? PlistDict+ else { throw DaemonError.cryptexPathsNotFound(url.path) }+ for component in ["OS", "SystemVolume", "StaticTrustCache", "Ap,SystemVolumeCanonicalMetadata"] {+ let path = componentPath(entries, component)+ guard !path.isEmpty else { throw DaemonError.invalidPlist(url.path) }+ guard isPlainRelativePath(path) else { throw DaemonError.unsafeCryptexPath(path) }+ }+ return .monolithic+ }+/// Extract the Cryptex DMG paths from a BuildManifest.////// Every BuildIdentity is searched, not just the first: vResearch IPSWs carrydiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Dyld/CustomFirmwareTVTPRO.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Dyld/CustomFirmwareTVTPRO.swiftnew file mode 100644index 00000000..1e775cb4--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Dyld/CustomFirmwareTVTPRO.swift@@ -0,0 +1,281 @@+import Foundation+import MachOKit+import VPhonePatchKit++/// Apple dyld enables TPRO mappings from kernel Apple parameters, while its+/// hardware writable scopes are compiled only for arm64e (common/Defines.h).+/// This opt-in plain-arm64 TV compatibility patch makes the two parameter lookups miss.+/// Page-in linking, chained/ObjC fixups and later DATA_CONST protection remain+/// intact. Both dyld images must be changed and reverted by the caller.+public enum CustomFirmwareTVTPRO {+ public static let patchID = "system-dyld-exp-tv_tpro"+ public static let stdoutLog: @Sendable (String) -> Void = { print($0) }+ public enum Outcome: String, Sendable { case patched, wouldPatch, alreadyPatched }+ public struct Site: Sendable {+ public let key: String+ public let virtualAddress: UInt64+ public let fileOffset: Int+ public let originalBytes: Data+ }+ public struct Report: Sendable {+ public let outcome: Outcome+ public let sites: [Site]+ public let records: [PatchRecord]+ }++ static let keys = ["dyld_hw_tpro", "dyld_hw_tpro_pagers"]+ static let process = "__ZN5dyld413ProcessConfig7ProcessC2EPKNS_10KernelArgsERNS_15SyscallDelegateERN3lsl9AllocatorE"+ static let stack = "__ZNK5dyld413ProcessConfig7Process16defaultTproStackEv"+ static let cacheConstructor = "__ZN5dyld413ProcessConfig9DyldCacheC2ERNS0_7ProcessERKNS0_8SecurityERKNS0_7LoggingERNS_15SyscallDelegateERN3lsl9AllocatorERKS0_"+ static let getenv = "__simple_getenv"+ static let replacement = Data("vphn".utf8)++ // MARK: - Standalone dyld++ @discardableResult+ public static func patchStandalone(+ fileAt url: URL, dryRun: Bool = false, log: ((String) -> Void)? = stdoutLog,+ ) throws -> Report {+ var data = try Data(contentsOf: url)+ let original = data+ let report = try patchStandalone(&data, dryRun: dryRun, log: log)+ if data != original { try data.write(to: url) }+ return report+ }++ @discardableResult+ public static func patchStandalone(+ _ data: inout Data, reattest: Bool = true, dryRun: Bool = false,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> Report {+ let input = Data(data)+ try validateImageHeader(input)+ let sections = MachOParser.parseSections(from: input)+ let segments = MachOParser.parseSegments(from: input)+ func offset(_ address: UInt64, _ count: Int) throws -> Int {+ for segment in segments where address >= segment.vmAddr {+ let delta = address - segment.vmAddr+ guard delta < segment.vmSize, delta <= segment.fileSize,+ UInt64(count) <= segment.fileSize - delta,+ segment.fileOffset <= UInt64(input.count),+ delta <= UInt64(input.count) - segment.fileOffset,+ UInt64(count) <= UInt64(input.count) - segment.fileOffset - delta else { continue }+ return Int(segment.fileOffset + delta)+ }+ throw PatcherError.invalidFormat("TV TPRO discovery extends outside file-backed segments")+ }+ let symbols = try definedSymbols(input)+ let discovered = try discover(sections: sections, symbols: symbols) { address, count in+ let start = try offset(address, count)+ return input.subdata(in: start ..< start + count)+ }+ let sites = try discovered.map { item in+ Site(key: item.key, virtualAddress: item.address, fileOffset: try offset(item.address, 4), originalBytes: item.bytes)+ }+ let pending = sites.filter { $0.originalBytes != replacement }+ logSites(sites, log: log)+ guard !pending.isEmpty else { return Report(outcome: .alreadyPatched, sites: sites, records: []) }+ if dryRun { return Report(outcome: .wouldPatch, sites: sites, records: []) }+ var output = input+ for site in pending { output.replaceSubrange(site.fileOffset ..< site.fileOffset + 4, with: replacement) }+ if reattest {+ _ = try CustomFirmwareMachOCodeSignature.reattest(+ &output, modifiedOffsets: pending.flatMap { [$0.fileOffset, $0.fileOffset + 3] },+ )+ }+ data = output+ return Report(outcome: .patched, sites: sites,+ records: pending.map { record($0, component: "dyld", suffix: "standalone") })+ }++ // MARK: - Native cache twin++ @discardableResult+ public static func patchCache(+ in chunks: DyldSharedCacheChunkSet, dryRun: Bool = false,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> Report {+ let handle = try FileHandle(forReadingFrom: chunks.mainCacheURL)+ defer { try? handle.close() }+ let head = try handle.read(upToCount: MemoryLayout<DyldCacheHeader.Layout>.size) ?? Data()+ guard head.count == MemoryLayout<DyldCacheHeader.Layout>.size,+ String(data: head.prefix(16).prefix { $0 != 0 }, encoding: .ascii) == "dyld_v1 arm64"+ else { throw PatcherError.invalidFormat("TV TPRO probe requires a complete native arm64 cache header") }+ let cache = try DyldCache(url: chunks.mainCacheURL)+ guard cache.header.platform == .tvOS, !cache.header.isSimulator,+ let constructor = try chunks.resolveLocalSymbol(process),+ chunks.mapping(forVMA: constructor)?.isExecutable == true,+ let imageAddress = try chunks.findMachOHeaderBefore(constructor),+ imageAddress >= cache.header.sharedRegionStart+ else { throw PatcherError.invalidFormat("TV TPRO probe requires native TVOS cache dyld") }+ let imageHead = try chunks.bytesAtVMA(imageAddress, length: 32)+ let commandSize = Int(imageHead.loadLE(UInt32.self, at: 20))+ guard commandSize <= 64 * 1024 else { throw PatcherError.invalidFormat("TV dyld load commands are too large") }+ let image = try chunks.bytesAtVMA(imageAddress, length: 32 + commandSize)+ try validateImageHeader(image)+ let table = try chunks.localSymbolTable()+ guard let entry = table.entry(forDylibOffset: imageAddress - cache.header.sharedRegionStart) else {+ throw PatcherError.patchSiteNotFound("TV dyld has no image-local symbol bounds")+ }+ let symbols = table.symbols(in: entry)+ let discovered = try discover(sections: MachOParser.parseSections(from: image), symbols: symbols) { address, count in+ try chunks.bytesAtVMA(address, length: count)+ }+ let sites = try discovered.map { item -> Site in+ let span = DyldSharedCacheWriteSpan(vma: item.address, length: 4)+ let translated = try chunks.fileRange(of: span)+ return Site(key: item.key, virtualAddress: item.address, fileOffset: translated.range.lowerBound, originalBytes: item.bytes)+ }+ let pending = sites.filter { $0.originalBytes != replacement }+ logSites(sites, log: log)+ guard !pending.isEmpty else { return Report(outcome: .alreadyPatched, sites: sites, records: []) }+ if dryRun { return Report(outcome: .wouldPatch, sites: sites, records: []) }+ let spans = pending.map { DyldSharedCacheWriteSpan(vma: $0.virtualAddress, length: 4) }+ // Admission precedes every write, including all pages' signature slots.+ let preview = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: spans, dryRun: true, log: nil)+ guard preview.isFullyAttested else { throw PatcherError.patchVerificationFailed("TV TPRO keys lack covering cache signatures") }+ var records: [PatchRecord] = []+ for site in pending {+ let location = try chunks.fileRange(of: DyldSharedCacheWriteSpan(vma: site.virtualAddress, length: 4))+ _ = try chunks.write(at: site.virtualAddress, replacement)+ records.append(record(site, component: location.chunkURL.lastPathComponent, suffix: "cache"))+ }+ let attestation = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: spans, log: log)+ guard attestation.isFullyAttested else { throw PatcherError.patchVerificationFailed("TV TPRO key writes were not fully re-attested") }+ return Report(outcome: .patched, sites: sites, records: records)+ }++ // MARK: - Source-backed keys and getenv call sites++ struct Discovered { let key: String; let address: UInt64; let bytes: Data }++ static func discover(+ sections: [String: MachOSectionInfo], symbols: [String: UInt64],+ read: (UInt64, Int) throws -> Data,+ ) throws -> [Discovered] {+ guard let strings = sections["__TEXT,__cstring"], strings.size > 0, strings.size <= 1_048_576,+ let text = sections["__TEXT,__text"], text.size > 0,+ text.address <= UInt64.max - text.size,+ strings.address <= UInt64.max - strings.size,+ let getenvAddress = symbols[getenv], getenvAddress >= text.address,+ getenvAddress - text.address < text.size+ else { throw PatcherError.invalidFormat("TV dyld discovery sections or getenv symbol are absent") }+ let bytes = try read(strings.address, Int(strings.size))+ var sites: [Discovered] = []+ for key in keys {+ let renamed = "vphn" + key.dropFirst(4)+ var matches: [Int] = []+ for value in [key, renamed] {+ let needle = Data((value + "\0").utf8)+ var cursor = 0+ while cursor < bytes.count, let range = bytes.range(of: needle, in: cursor ..< bytes.count) {+ if range.lowerBound == 0 || bytes[range.lowerBound - 1] == 0 { matches.append(range.lowerBound) }+ cursor = range.lowerBound + 1+ }+ }+ guard matches.count == 1, let offset = matches.first else {+ throw PatcherError.patchSiteNotFound("TV dyld requires one exact original or renamed \(key) C string")+ }+ sites.append(Discovered(key: key, address: strings.address + UInt64(offset), bytes: bytes.subdata(in: offset ..< offset + 4)))+ }+ let required = [(process, keys), (stack, [keys[0]]), (cacheConstructor, [keys[1]])]+ for (name, wanted) in required {+ guard let start = symbols[name], start >= text.address, start - text.address < text.size,+ let end = symbols.values.filter({ $0 > start && $0 <= text.address + text.size }).min(),+ end - start <= 64 * 1024+ else { throw PatcherError.patchSiteNotFound("TV dyld requires exact bounded \(name)") }+ let instructions = ARM64Disassembler().disassemble(try read(start, Int(end - start)), at: start)+ guard instructions.allSatisfy({ $0.isDecoded && $0.size == 4 }) else {+ throw PatcherError.patchSiteNotFound("TV dyld TPRO lookup function does not decode completely")+ }+ for key in wanted {+ let address = sites.first { $0.key == key }!.address+ var matches = 0+ for index in instructions.indices where index + 3 < instructions.count {+ let a = instructions[index], b = instructions[index + 1], call = instructions[index + 2], result = instructions[index + 3]+ let ao = a.detail?.operands ?? [], bo = b.detail?.operands ?? [], co = call.detail?.operands ?? []+ guard a.mnemonic == "adrp", ao.count == 2, ao[0].type == .register, ao[0].reg == .x(1),+ ao[1].type == .immediate, ao[1].imm >= 0,+ b.mnemonic == "add", bo.count == 3, bo[0].type == .register, bo[0].reg == .x(1),+ bo[1].type == .register, bo[1].reg == .x(1), bo[2].type == .immediate, bo[2].imm >= 0,+ UInt64(ao[1].imm) <= UInt64.max - UInt64(bo[2].imm),+ UInt64(ao[1].imm) + UInt64(bo[2].imm) == address,+ call.mnemonic == "bl", co.count == 1, co[0].type == .immediate,+ co[0].imm >= 0, UInt64(co[0].imm) == getenvAddress+ else { continue }+ let ro = result.detail?.operands ?? []+ if result.mnemonic == "cmp", ro.count == 2, ro[0].type == .register, ro[0].reg == .x(0),+ ro[1].type == .immediate, ro[1].imm == 0, index + 4 < instructions.count,+ instructions[index + 4].mnemonic == "cset", instructions[index + 4].detail?.conditionCode == .ne {+ matches += 1+ } else if result.mnemonic == "cbz", ro.count == 2, ro[0].type == .register, ro[0].reg == .x(0) {+ matches += 1+ }+ }+ guard matches == 1 else { throw PatcherError.patchSiteNotFound("TV dyld \(name) must read \(key) through getenv and test presence") }+ }+ }+ return sites+ }++ static func validateImageHeader(_ data: Data) throws {+ // mach_header_64: CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL, MH_DYLINKER.+ guard data.count >= 32, data.loadLE(UInt32.self, at: 0) == 0xFEED_FACF,+ data.loadLE(UInt32.self, at: 4) == 0x0100_000C,+ data.loadLE(UInt32.self, at: 8) & 0x00FF_FFFF == 0,+ data.loadLE(UInt32.self, at: 12) == 7+ else { throw PatcherError.invalidFormat("TV dyld probe requires a native arm64 MH_DYLINKER") }+ let size = Int(data.loadLE(UInt32.self, at: 20))+ guard size <= data.count - 32 else { throw PatcherError.invalidFormat("Truncated TV dyld load commands") }+ let end = 32 + size+ var offset = 32+ var platforms: [UInt32] = []+ for _ in 0 ..< data.loadLE(UInt32.self, at: 16) {+ guard offset <= end - 8 else { throw PatcherError.invalidFormat("Truncated TV dyld load command") }+ let command = data.loadLE(UInt32.self, at: offset)+ let length = Int(data.loadLE(UInt32.self, at: offset + 4))+ guard length >= 8, length <= end - offset else { throw PatcherError.invalidFormat("Invalid TV dyld load command size") }+ if command == 0x32 { // LC_BUILD_VERSION+ guard length >= 24 else { throw PatcherError.invalidFormat("Truncated TV dyld build version") }+ platforms.append(data.loadLE(UInt32.self, at: offset + 8))+ }+ offset += length+ }+ guard offset == end, platforms == [3] else { throw PatcherError.invalidFormat("TV dyld probe requires one TVOS build version") }+ }++ static func definedSymbols(_ data: Data) throws -> [String: UInt64] {+ guard let table = MachOParser.parseSymtab(from: data), table.symoff <= data.count,+ table.nsyms <= (data.count - table.symoff) / 16, table.stroff <= data.count,+ table.strsize <= data.count - table.stroff+ else { throw PatcherError.invalidFormat("TV dyld has no complete symbol table") }+ var symbols: [String: UInt64] = [:]+ for index in 0 ..< table.nsyms {+ let entry = table.symoff + index * 16+ guard data[entry + 4] & 0xE0 == 0, data[entry + 4] & 0x0E == 0x0E, data[entry + 5] != 0 else { continue }+ let stringIndex = Int(data.loadLE(UInt32.self, at: entry))+ guard stringIndex < table.strsize else { continue }+ let start = table.stroff + stringIndex+ guard let end = data[start ..< table.stroff + table.strsize].firstIndex(of: 0),+ let name = String(data: data[start ..< end], encoding: .utf8) else { continue }+ let value = data.loadLE(UInt64.self, at: entry + 8)+ if [process, stack, cacheConstructor, getenv].contains(name), symbols[name] != nil {+ throw PatcherError.invalidFormat("Ambiguous TV dyld TPRO symbol \(name)")+ }+ symbols[name] = value+ }+ return symbols+ }++ static func logSites(_ sites: [Site], log: ((String) -> Void)?) {+ for site in sites {+ log?(" [.] TV dyld \(site.key) key at 0x\(String(site.virtualAddress, radix: 16)): \(String(decoding: site.originalBytes, as: UTF8.self)) -> vphn")+ }+ }+ static func record(_ site: Site, component: String, suffix: String) -> PatchRecord {+ PatchRecord(patchID: "\(patchID).\(suffix).\(site.key)", component: component,+ fileOffset: site.fileOffset, virtualAddress: site.virtualAddress,+ originalBytes: site.originalBytes, patchedBytes: replacement,+ description: "Disable the plain-arm64 TV dyld hardware TPRO parameter lookup")+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Dyld/CustomFirmwareTVTPROInstallation.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Dyld/CustomFirmwareTVTPROInstallation.swiftnew file mode 100644index 00000000..5657ad32--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/Dyld/CustomFirmwareTVTPROInstallation.swift@@ -0,0 +1,50 @@+import Foundation++/// Preconditions for paired standalone/cache dyld updates. A caller must let+/// failures escape the install, discarding its private disk clone. Continuing+/// after a failed step could commit half of the pair with an incorrect receipt.+public enum CustomFirmwareTVTPROInstallation {+ public enum Failure: Error, CustomStringConvertible {+ case privateCloneRequired+ case missingUndo+ case invalidBackup+ case missingBackup++ public var description: String {+ switch self {+ case .privateCloneRequired:+ "tvOS guest updates require an APFS disk clone; place the VM and work directory on the same APFS volume. The original disk was not modified."+ case .missingUndo:+ "TV dyld cache undo record is missing; refusing a paired change."+ case .invalidBackup:+ "TV standalone dyld backup is not a regular file; refusing a paired change."+ case .missingBackup:+ "TV standalone dyld backup is missing for an existing patch; refusing to capture patched bytes as original."+ }+ }+ }++ public static func requirePrivateClone(_ cloned: Bool) throws {+ guard cloned else { throw Failure.privateCloneRequired }+ }++ public static func validateBackup(+ priorApplied: Bool, hasUndo: Bool, backupExists: Bool, backupIsRegular: Bool,+ ) throws {+ if priorApplied, !hasUndo { throw Failure.missingUndo }+ if backupExists, !backupIsRegular { throw Failure.invalidBackup }+ if priorApplied || hasUndo, !backupIsRegular { throw Failure.missingBackup }+ }++ /// Cache restoration and standalone restoration precede retirement of the+ /// undo record. Errors propagate to the caller's disk-clone transaction.+ public static func restorePair(+ restoreCache: () throws -> Void,+ restoreStandalone: () throws -> Void,+ retireUndo: () throws -> Void,+ ) throws {+ try restoreCache()+ try restoreStandalone()+ try retireUndo()+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swiftindex 146a7aaa..9c7db356 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift@@ -61,6 +61,7 @@ extension DeviceTreePatcher {static let iPadButtonsPatch = "devicetree-cfw-ipad_buttons"static let iPadIdentityPatch = "devicetree-cfw-ipad_identity"static let iPadAudioPatch = "devicetree-cfw-ipad_audio"+ static let tvAppArchitecturePatch = "devicetree-cfw-tv_app_architecture"static let hapticsPatch = "devicetree-cfw-product_haptics_node"static let microphoneArrayPatch = "devicetree-cfw-product_audio_microphone_array"@@ -158,6 +159,19 @@ extension DeviceTreePatcher {return property.value}+ // J42d's tvOS tree declares arm64 apps. Keep the source's concrete+ // value rather than the virtual phone's architecture; this edit is TV+ // presentation only and must not change existing phone or pad output.+ if let idiom = value(sourceProduct, "artwork-device-idiom"),+ String(decoding: idiom.prefix { $0 != 0 }, as: UTF8.self) == "tv"+ {+ guard let architecture = value(sourceProduct, "app-macho-architecture"), !architecture.isEmpty else {+ throw PatcherError.patchSiteNotFound("DeviceTree: the TV board's tree has no concrete app-macho-architecture")+ }+ edits.append(GuestEdit(nodePath: product, property: "app-macho-architecture",+ action: .set(architecture), patchID: tvAppArchitecturePatch))+ }+for (name, patchID) in copiedProductProperties {let action: GuestEdit.Action = value(sourceProduct, name).map { .set($0) } ?? .removeedits.append(GuestEdit(nodePath: product, property: name, action: action, patchID: patchID))diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchTVTPROPagers.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchTVTPROPagers.swiftnew file mode 100644index 00000000..b8efec08--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchTVTPROPagers.swift@@ -0,0 +1,72 @@+import Foundation+import VPhonePatchKit++extension KernelCustomFirmwarePatcher {+ /// Change the native tunable's initial data, not its callers or protection+ /// checks. The descriptor and startup registration follow kern/startup.h.+ /// Kernel-cache rebase targets are image-relative; next/PAC bits stay intact.+ @discardableResult+ func patchTVTPROPagers() -> Bool {+ guard let offset = Self.tvTPROPagersDefault(in: buffer.data, segments: segments) else {+ log(" [-] sprr_tpro_pagers tunable not uniquely validated")+ return false+ }+ let old = buffer.readU32(at: offset)+ log(" [.] sprr_tpro_pagers default at 0x\(String(offset, radix: 16)): \(old) -> 0")+ emit(offset, Data(repeating: 0, count: 4),+ patchID: FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers,+ virtualAddress: fileOffsetToVA(offset),+ description: "sprr_tpro_pagers integer tunable default \(old) -> 0 (data)")+ return true+ }++ static func tvTPROPagersDefault(in data: Data, segments: [MachOSegmentInfo]) -> Int? {+ guard data.count >= 24 else { return nil }+ let name = Data("sprr_tpro_pagers\0".utf8)+ guard let nameRange = data.range(of: name),+ data.range(of: name, in: nameRange.upperBound..<data.count) == nil,+ nameRange.lowerBound == 0 || data[nameRange.lowerBound - 1] == 0+ else { return nil }++ func word(_ offset: Int) -> UInt64 { data.loadLE(UInt64.self, at: offset) }+ func target(_ raw: UInt64) -> Int? {+ // DYLD_CHAINED_PTR_64_KERNEL_CACHE: target:30, cacheLevel:2,+ // diversity:16, addrDiv:1, key:2, next:12, isAuth:1.+ guard raw & 0xC000_0000 == 0 else { return nil }+ let value = Int(raw & 0x3FFF_FFFF)+ return value < data.count ? value : nil+ }+ func contains(_ offset: Int, count: Int, names: Set<String>) -> Bool {+ segments.contains { segment in+ names.contains(segment.name) && UInt64(offset) >= segment.fileOffset &&+ UInt64(offset) - segment.fileOffset <= segment.fileSize &&+ UInt64(count) <= segment.fileSize - (UInt64(offset) - segment.fileOffset)+ }+ }+ // Fileset outer __DATA contains the embedded kernel's __KLDDATA.+ guard contains(nameRange.lowerBound, count: name.count, names: ["__KLDDATA", "__DATA"]) else { return nil }+ var candidates: [Int] = []+ for descriptor in stride(from: 0, through: data.count - 24, by: 8) {+ guard target(word(descriptor)) == nameRange.lowerBound,+ // Integer, four bytes, neither bool nor string.+ word(descriptor + 16) == 4,+ contains(descriptor, count: 24, names: ["__KLDDATA", "__DATA"]),+ let variable = target(word(descriptor + 8)), variable % 4 == 0,+ variable <= data.count - MemoryLayout<UInt32>.size,+ contains(variable, count: 4, names: ["__DATA", "__DATA_CONST"]),+ data.loadLE(UInt32.self, at: variable) <= 1+ else { continue }+ // A real STARTUP_SUB_TUNABLES registration must point at the spec+ // and an executable initializer. Reject stray descriptor-shaped data.+ let registrations = stride(from: 0, through: data.count - 24, by: 8).filter { entry in+ guard word(entry) == 1, target(word(entry + 16)) == descriptor,+ let callback = target(word(entry + 8))+ else { return false }+ return contains(entry, count: 24, names: ["__KLDDATA", "__DATA"]) &&+ contains(callback, count: 4, names: ["__TEXT_EXEC", "__TEXT_BOOT_EXEC"])+ }+ if registrations.count == 1 { candidates.append(variable) }+ }+ return candidates.count == 1 ? candidates[0] : nil+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swiftindex 7e20335b..b8be20c1 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift@@ -36,6 +36,9 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,/// a patcher built directly writes what the reference records were taken from.public var applyProMotion = false+ /// Opt-in plain-arm64 tvOS shared-cache compatibility; off by default.+ public var applyTVTPROPagers = false+/// On a base older than 27: a narrow allowlist at the same sandbox gate, so a/// process outside an app sandbox can open the paravirtual GPU, video decoder,/// Neural Engine and IOSurface scaler user clients and nothing else. Set from@@ -50,6 +53,12 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,buildSymbolTable()findPanic()+ if applyTVTPROPagers {+ guard patchTVTPROPagers() else {+ throw NSError(domain: "FirmwarePatcher.TVTPROPagers", code: 1, userInfo: [NSLocalizedDescriptionKey: "Cannot validate sprr_tpro_pagers tunable; kernel unchanged by this operation"])+ }+ }+// Group ApatchAmfiCdhashInTrustcache()patchTaskConversionEvalInternal()diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swiftindex 0f67e0cb..756f06c5 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift@@ -6,6 +6,7 @@// (device tree, SEP, kernel) and iPhone OS images into a single DFU erase-install// Build Identity.+import CryptoKitimport Foundationimport VPhoneCoreKit@@ -85,7 +86,7 @@ public enum FirmwareManifest {}// Build the single DFU erase identity.- let buildIdentity = try buildEraseIdentity(+ let sourceIdentity = try buildEraseIdentity(cloudIdentities: cloudIdentities,iPhoneIdentities: iPhoneIdentities,prod: prod,@@ -94,6 +95,9 @@ public enum FirmwareManifest {vpr: vpr,iErase: iErase,)+ let buildIdentity = try normalizeGuestComponentDigests(+ sourceIdentity, device: device, restoreDir: iPhoneDir,+ )let guestIdentity = try separateGuestDeviceTree(for: device,identity: buildIdentity,@@ -256,6 +260,35 @@ public enum FirmwareManifest {// MARK: - Build Identity Construction+ /// J42d uses SHA-1 digests, but the PCC restore environment authenticates+ /// Image4 payloads with SHA-384. Keeping the donor digest makes canonical+ /// metadata execution fail with ENOEXEC before sealing. Hash the unchanged+ /// guest components for the hybrid ticket; other guest families retain+ /// their existing manifest entries and signature-bypass behavior.+ static func normalizeGuestComponentDigests(+ _ identity: PlistDict,+ device: VPhoneGuestDevice,+ restoreDir: URL,+ ) throws -> PlistDict {+ guard device.family == .appleTV else { return identity }+ guard var manifest = identity["Manifest"] as? PlistDict else {+ throw ManifestError.missingKey("Manifest in the hybrid build identity")+ }+ for name in ["Ap,SystemVolumeCanonicalMetadata", "OS", "StaticTrustCache", "SystemVolume"] {+ guard var component = manifest[name] as? PlistDict,+ let info = component["Info"] as? PlistDict,+ let path = info["Path"] as? String,+ CustomFirmwareDaemons.isPlainRelativePath(path)+ else { throw ManifestError.missingKey("Safe Path for \(name) in the hybrid build identity") }+ let data = try Data(contentsOf: restoreDir.appending(path: path), options: .mappedIfSafe)+ component["Digest"] = Data(SHA384.hash(data: data))+ manifest[name] = component+ }+ var normalized = identity+ normalized["Manifest"] = manifest+ return normalized+ }+/// Deep-copy a single Manifest entry from a build identity.static func entry(_ identities: [PlistDict],diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swiftindex 62cc226e..7196d5dd 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift@@ -214,6 +214,14 @@ public enum FirmwareDeviceTreePatchSet {"iPad audio configuration","Takes the audio node from the iPad's tree, so its acoustic ID names tunings the iPad image ships.",),++ // MARK: TV Guest++ property(+ "devicetree-cfw-tv_app_architecture",+ "TV app architecture",+ "Copies app-macho-architecture from a TV board's own device tree into the installed tree, so its userland sees the donor's architecture. Restore, iPhone and iPad trees are unchanged.",+ ),],provides: ["vphone.devicetree"],)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swiftindex e090fdbf..ba45abd8 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift@@ -22,6 +22,20 @@ import Foundationimport VPhonePatchKitpublic 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+ /// validation before the installer can select them.+ public static let tvSupportedGuestPatches: Set<String> = [+ "system-seputil-boot-gigalocker_uuid",+ "system-gigalocker-boot-rename",+ FirmwareGuestSystemPatchSet.tvTPRO,+ ]++ public static func unvalidatedTVGuestPatches(enabled: Set<String>) -> [String] {+ let admitted = tvSupportedGuestPatches+ return enabled.intersection(guestTargetIdentifiers).subtracting(admitted).sorted()+ }+/// Every bundled-set patch whose bytes the guest half of an install writes —/// the dyld shared cache, a guest Mach-O, its entitlements, a guest file, or/// the Preboot device tree. The complement is the boot chain, which `fwdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex 14befecd..b2a88fe4 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -26,6 +26,7 @@ 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"private static let ios27 = VPhonePatchApplicability(iOSBase: .major(27))@@ -50,6 +51,13 @@ public enum FirmwareGuestSystemPatchSet {name: "Guest System",summary: "Shared-cache policy gates, patched system daemons and the vphone guest payload",patches: [+ VPhonePatchDeclaration(+ identifier: tvTPRO,+ 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)),+ ),VPhonePatchDeclaration(identifier: locationdCohorting,title: "locationd startup stability",diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swiftindex 18ca8a7d..e1793342 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift@@ -15,6 +15,8 @@ import VPhonePatchKitpublic enum FirmwareKernelCustomFirmwarePatchSet {public static let identifier = "com.vphone.patchset.kernel.cfw"+ public static let tvTPROPagers = "kernel-exp-tv_tpro_pagers"+/// Only applies to an iOS 27 userland.private static let ios27 = VPhonePatchApplicability(iOSBase: .major(27))@@ -23,6 +25,13 @@ public enum FirmwareKernelCustomFirmwarePatchSet {name: "Kernel Custom Firmware",summary: "Trust cache admission, writable root, task ports and the guest's extra syscall surface",patches: [+ VPhonePatchDeclaration(+ identifier: tvTPROPagers,+ 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)),+ ),// MARK: Trust Cache and Code SigningVPhonePatchDeclaration(diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swiftindex 28d2902a..e65f7be6 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([misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate])+ .union([FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, FirmwareGuestSystemPatchSet.tvTPRO])/// ProMotion: the 120 Hz timing for the paravirtual display.///diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swiftindex c5d07351..2bf9bde5 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift@@ -244,6 +244,7 @@ extension FirmwarePipeline {applyIOS27: applyIOS27,applyFrida: applyFrida,applyProMotion: applyProMotion,+ applyTVTPROPagers: isEnabled(FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, fallback: false),applyParavirtUserClients: applyParavirtUserClients,includeBase: includeKernelBase,includeCustomFirmware: includeKernelCustomFirmware,@@ -392,6 +393,7 @@ extension FirmwarePipeline {applyIOS27: Bool,applyFrida: Bool,applyProMotion: Bool,+ applyTVTPROPagers: Bool,applyParavirtUserClients: Bool,includeBase: Bool,includeCustomFirmware: Bool,@@ -412,6 +414,7 @@ extension FirmwarePipeline {p.applyIOS27 = applyIOS27p.applyFrida = applyFridap.applyProMotion = applyProMotion+ p.applyTVTPROPagers = applyTVTPROPagersp.applyParavirtUserClients = applyParavirtUserClientsp.gate = gatereturn pdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swiftindex 76fe34b1..df03d09c 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift@@ -123,13 +123,16 @@ struct DeviceTreeGuestDeviceTests {unique: String = "J410AP",subtype: UInt32 = 2266,disablesStageManager: Bool = true,+ idiom: String = "pad",+ scale: UInt32 = 2,+ appArchitecture: Property? = nil,) -> Node {var product: [Property] = [.string("name", "product"),- .string("artwork-device-idiom", "pad"),+ .string("artwork-device-idiom", idiom),.integer("artwork-device-subtype", subtype),- .integer("artwork-scale-factor", 2),- .string("product-name", "iPad"),+ .integer("artwork-scale-factor", scale),+ .string("product-name", idiom == "tv" ? "Apple TV" : "iPad"),.string("fdr-product-type", model),.string("sub-product-type", model),.string("unique-model", unique),@@ -143,6 +146,9 @@ struct DeviceTreeGuestDeviceTests {if disablesStageManager {product.append(.integer("disable-chamois", 1))}+ if let appArchitecture {+ product.append(appArchitecture)+ }let target = String(unique.dropLast(2))return Node(properties: [@@ -159,6 +165,13 @@ struct DeviceTreeGuestDeviceTests {)}+ /// J42d's TV idiom, scale and app architecture from the 23L243/23L5208m trees.+ static func tvBoard() -> Node {+ board(model: "AppleTV5,3", unique: "J42dAP", subtype: 0,+ disablesStageManager: false, idiom: "tv", scale: 1,+ appArchitecture: .string("app-macho-architecture", "arm64"))+ }+// MARK: - Reading the result/// `node -> property -> (flags, value)` for the two levels the fixture has.@@ -222,16 +235,22 @@ struct DeviceTreeGuestDeviceTests {case iPhonecase iPadcase iPadRestore+ case appleTV+ case appleTVRestorevar device: VPhoneGuestDevice {- self == .iPhone ? .default : .iPad16_1+ switch self {+ case .iPhone: .default+ case .iPad, .iPadRestore: .iPad16_1+ case .appleTV, .appleTVRestore: .appleTV5_3+ }}var role: DeviceTreePatcher.TreeRole {switch self {case .iPhone: .shared- case .iPad: .installed- case .iPadRestore: .restore+ case .iPad, .appleTV: .installed+ case .iPadRestore, .appleTVRestore: .restore}}}@@ -245,7 +264,7 @@ struct DeviceTreeGuestDeviceTests {) throws -> (data: Data, records: [PatchRecord]) {let patcher = DeviceTreePatcher(data: tree, verbose: false, device: guest.device, role: guest.role,- sourceTree: board().serialized(),+ sourceTree: (guest.device.family == .appleTV ? tvBoard() : board()).serialized(),)patcher.gate = gatelet records = try patcher.findAll()@@ -267,6 +286,50 @@ struct DeviceTreeGuestDeviceTests {// MARK: - Tests+ @Test func `a TV installed tree takes its donor app architecture while restore keeps the virtual board`() throws {+ let (installedData, records) = try Self.patched(Self.tree.serialized(), as: .appleTV)+ let installed = Self.read(installedData)+ #expect(Self.string(installed["device-tree"]?["model"]) == "AppleTV5,3")+ #expect(Self.string(installed["device-tree/product"]?["artwork-device-idiom"]) == "tv")+ #expect(Self.integer(installed["device-tree/product"]?["artwork-scale-factor"]) == 1)+ #expect(Self.string(installed["device-tree/product"]?["app-macho-architecture"]) == "arm64")+ #expect(records.filter { $0.patchID == DeviceTreePatcher.tvAppArchitecturePatch }.count == 1)++ let (restoreData, restoreRecords) = try Self.patched(Self.tree.serialized(), as: .appleTVRestore)+ let restore = Self.read(restoreData)+ #expect(Self.string(restore["device-tree"]?["model"]) == "iPhone99,11")+ #expect(Self.string(restore["device-tree/product"]?["artwork-device-idiom"]) == "phone")+ #expect(restore["device-tree/product"]?["app-macho-architecture"] == nil)+ #expect(!restoreRecords.contains { $0.patchID == DeviceTreePatcher.tvAppArchitecturePatch })+ }++ @Test func `the TV architecture edit is declared and obeys its gate`() throws {+ let declared = Set(FirmwareDeviceTreePatchSet.manifest.patches.map(\.identifier))+ #expect(declared.contains(DeviceTreePatcher.tvAppArchitecturePatch))+ let gate = VPhonePatchGate(declared: declared, enabled: declared.subtracting([DeviceTreePatcher.tvAppArchitecturePatch]))+ let (data, records) = try Self.patched(Self.tree.serialized(), as: .appleTV, gate: gate)+ #expect(Self.read(data)["device-tree/product"]?["app-macho-architecture"] == nil)+ #expect(!records.contains { $0.patchID == DeviceTreePatcher.tvAppArchitecturePatch })+ #expect(Self.string(Self.read(data)["device-tree/product"]?["artwork-device-idiom"]) == "tv")+ }++ @Test func `non-TV board presentation never edits app architecture`() throws {+ let parser = DeviceTreePatcher(data: Data(), verbose: false)+ for idiom in ["phone", "pad"] {+ let source = Self.board(idiom: idiom, appArchitecture: .string("app-macho-architecture", "arm64"))+ let edits = try DeviceTreePatcher.guestEdits(from: parser.parsePayload(source.serialized()))+ #expect(!edits.contains { $0.patchID == DeviceTreePatcher.tvAppArchitecturePatch })+ #expect(!edits.contains { $0.property == "app-macho-architecture" })+ }+ }++ @Test func `a TV board architecture placeholder cannot be copied as data`() throws {+ let source = Self.board(idiom: "tv", appArchitecture: .placeholder("app-macho-architecture", "arch"))+ let parser = DeviceTreePatcher(data: Data(), verbose: false)+ let parsed = try parser.parsePayload(source.serialized())+ #expect(throws: (any Error).self) { try DeviceTreePatcher.guestEdits(from: parsed) }+ }+@Test func `an iPad's installed tree presents the iPad`() throws {let tree = try Self.patch(device: .iPad16_1, role: .installed)let root = try #require(tree["device-tree"])diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwareManifestSelectionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwareManifestSelectionTests.swiftindex f41a6743..4bf0dd87 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwareManifestSelectionTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwareManifestSelectionTests.swift@@ -1,5 +1,7 @@@testable import FirmwarePatcherimport Foundation+import CryptoKit+import VPhoneCoreKitimport Testing/// Identity selection for the hybrid manifest.@@ -17,6 +19,54 @@ import Testing/// pinned here without a firmware image, which is what these do.@Suite("Hybrid manifest identity selection")struct FirmwareManifestSelectionTests {+ @Test+ func `TV donor digests authenticate unchanged payloads using PCC SHA384`() throws {+ let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let payload = Data("unchanged donor payload".utf8)+ try payload.write(to: root.appending(path: "payload.im4p"))+ let names = ["Ap,SystemVolumeCanonicalMetadata", "OS", "StaticTrustCache", "SystemVolume"]+ let entry: PlistDict = ["Digest": Data(Insecure.SHA1.hash(data: payload)),+ "Trusted": true, "Info": ["Path": "payload.im4p"]]+ var components = PlistDict()+ for name in names { components[name] = entry }+ components["KernelCache"] = entry+ let identity: PlistDict = ["Manifest": components]+ let normalized = try FirmwareManifest.normalizeGuestComponentDigests(+ identity, device: .appleTV5_3, restoreDir: root,+ )+ let result = try #require(normalized["Manifest"] as? PlistDict)+ for name in names {+ let component = try #require(result[name] as? PlistDict)+ #expect(component["Digest"] as? Data == Data(SHA384.hash(data: payload)))+ #expect(component["Trusted"] as? Bool == true)+ }+ #expect((result["KernelCache"] as? PlistDict)?["Digest"] as? Data == entry["Digest"] as? Data)+ #expect(try Data(contentsOf: root.appending(path: "payload.im4p")) == payload)+ }++ @Test+ func `phone and pad manifest digests remain unchanged without reading files`() throws {+ let identity: PlistDict = ["Manifest": ["OS": ["Digest": Data([1, 2, 3])]]]+ for device in [VPhoneGuestDevice.iPhone17_3, .iPad16_1] {+ let result = try FirmwareManifest.normalizeGuestComponentDigests(+ identity, device: device, restoreDir: URL(fileURLWithPath: "/missing"),+ )+ #expect(NSDictionary(dictionary: result).isEqual(to: identity))+ }+ }++ @Test+ func `TV digest normalization rejects paths outside the restore tree`() {+ let identity: PlistDict = ["Manifest": ["Ap,SystemVolumeCanonicalMetadata": ["Info": ["Path": "../outside"]]]]+ #expect(throws: (any Error).self) {+ try FirmwareManifest.normalizeGuestComponentDigests(+ identity, device: .appleTV5_3, restoreDir: URL(fileURLWithPath: "/missing"),+ )+ }+ }+// MARK: - Fixturesstatic func identity(diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swiftindex 23c801f3..07f71d53 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift@@ -234,6 +234,66 @@ struct CustomFirmwareDaemonsTests {// MARK: - Cryptex paths+ @Test+ func `tvOS without cryptexes admits only a complete monolithic erase image`() throws {+ let directory = try CustomFirmwareDaemonsFixtures.temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ let url = directory.appending(path: "BuildManifest.plist")+ var entries: PlistDict = [:]+ for component in ["OS", "SystemVolume", "StaticTrustCache", "Ap,SystemVolumeCanonicalMetadata"] {+ entries[component] = ["Info": ["Path": "Firmware/\(component).img"]] as PlistDict+ }+ func manifest(products: [String] = ["AppleTV5,3"], entries: PlistDict) -> PlistDict {+ ["SupportedProductTypes": products, "BuildIdentities": [[+ "Ap,SDKPlatform": "appletvos",+ "Info": ["RestoreBehavior": "Erase"],+ "Manifest": entries,+ ] as PlistDict]]+ }+ try CustomFirmwareDaemons.savePlist(manifest(entries: entries), to: url)+ #expect(try CustomFirmwareDaemons.filesystemLayout(buildManifest: url) == .monolithic)++ // 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"], []] {+ try CustomFirmwareDaemons.savePlist(manifest(products: products, entries: entries), to: url)+ #expect(throws: CustomFirmwareDaemons.DaemonError.self) {+ try CustomFirmwareDaemons.filesystemLayout(buildManifest: url)+ }+ }+ var partial = entries+ partial["Cryptex1,SystemOS"] = ["Info": ["Path": "SystemOS.dmg"]] as PlistDict+ try CustomFirmwareDaemons.savePlist(manifest(entries: partial), to: url)+ #expect(throws: CustomFirmwareDaemons.DaemonError.self) {+ try CustomFirmwareDaemons.filesystemLayout(buildManifest: url)+ }+ entries.removeValue(forKey: "SystemVolume")+ try CustomFirmwareDaemons.savePlist(manifest(entries: entries), to: url)+ #expect(throws: CustomFirmwareDaemons.DaemonError.self) {+ try CustomFirmwareDaemons.filesystemLayout(buildManifest: url)+ }+ }++ @Test+ func `monolithic image paths and platform remain validated`() throws {+ let directory = try CustomFirmwareDaemonsFixtures.temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ let url = directory.appending(path: "BuildManifest.plist")+ for (platform, osPath) in [("iphoneos", "OS.dmg"), ("appletvos", "../OS.dmg"), ("appletvos", "/OS.dmg")] {+ var entries: PlistDict = [:]+ for component in ["OS", "SystemVolume", "StaticTrustCache", "Ap,SystemVolumeCanonicalMetadata"] {+ entries[component] = ["Info": ["Path": component == "OS" ? osPath : "Firmware/image"]] as PlistDict+ }+ try CustomFirmwareDaemons.savePlist([+ "SupportedProductTypes": ["AppleTV5,3"],+ "BuildIdentities": [["Ap,SDKPlatform": platform, "Info": ["RestoreBehavior": "Erase"], "Manifest": entries] as PlistDict],+ ], to: url)+ #expect(throws: CustomFirmwareDaemons.DaemonError.self) {+ try CustomFirmwareDaemons.filesystemLayout(buildManifest: url)+ }+ }+ }+@Testfunc `Cryptex paths are found in a later identity, not just the first`() throws {let directory = try CustomFirmwareDaemonsFixtures.temporaryDirectory()@@ -256,6 +316,7 @@ struct CustomFirmwareDaemonsTests {let paths = try CustomFirmwareDaemons.cryptexPaths(buildManifest: url)#expect(paths.systemOS == "043-70113-702.dmg.aea")#expect(paths.appOS == "043-69297-784.dmg")+ #expect(try CustomFirmwareDaemons.filesystemLayout(buildManifest: url) == .cryptex(paths))}@Testdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareTVTPROInstallationTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareTVTPROInstallationTests.swiftnew file mode 100644index 00000000..c5979c40--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareTVTPROInstallationTests.swift@@ -0,0 +1,68 @@+@testable import FirmwarePatcher+import Testing++@Suite("TV dyld paired installation safety")+struct CustomFirmwareTVTPROInstallationTests {+ @Test func `existing patches require both original backup and undo`() throws {+ for priorApplied in [false, true] {+ #expect(throws: (any Error).self) {+ try CustomFirmwareTVTPROInstallation.validateBackup(+ priorApplied: priorApplied, hasUndo: true,+ backupExists: false, backupIsRegular: false,+ )+ }+ }+ #expect(throws: (any Error).self) {+ try CustomFirmwareTVTPROInstallation.validateBackup(+ priorApplied: true, hasUndo: false, backupExists: true, backupIsRegular: true,+ )+ }+ #expect(throws: (any Error).self) {+ try CustomFirmwareTVTPROInstallation.validateBackup(+ priorApplied: false, hasUndo: false, backupExists: true, backupIsRegular: false,+ )+ }+ try CustomFirmwareTVTPROInstallation.validateBackup(+ priorApplied: false, hasUndo: false, backupExists: false, backupIsRegular: false,+ )+ try CustomFirmwareTVTPROInstallation.validateBackup(+ priorApplied: true, hasUndo: true, backupExists: true, backupIsRegular: true,+ )+ }++ @Test func `in place disk updates are refused`() throws {+ #expect(throws: (any Error).self) {+ try CustomFirmwareTVTPROInstallation.requirePrivateClone(false)+ }+ try CustomFirmwareTVTPROInstallation.requirePrivateClone(true)+ }++ enum InjectedFailure: Error { case write }++ @Test(arguments: 0 ... 3)+ func `failure stops rollback before retiring undo or committing`(failureAt: Int) {+ var visited: [Int] = []+ var undoRetired = false+ var committed = false+ func step(_ index: Int) throws {+ visited.append(index)+ if failureAt == index { throw InjectedFailure.write }+ }+ do {+ try CustomFirmwareTVTPROInstallation.restorePair {+ try step(0)+ } restoreStandalone: {+ try step(1)+ } retireUndo: {+ try step(2)+ undoRetired = true+ }+ committed = true+ } catch {+ #expect(error is InjectedFailure)+ }+ #expect(visited == Array(0 ... min(failureAt, 2)))+ #expect(undoRetired == (failureAt == 3))+ #expect(committed == (failureAt == 3))+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareTVTPROTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareTVTPROTests.swiftnew file mode 100644index 00000000..041090e9--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareTVTPROTests.swift@@ -0,0 +1,196 @@+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++@Suite("TV dyld TPRO parameter compatibility")+struct CustomFirmwareTVTPROTests {+ // Independent native instruction windows from 23L5208m TV dyld. Their+ // real ADRP/ADD, BL and presence tests survive relocation in this fixture.+ static let processAddress = 0x240DC+ static let stackAddress = 0x249FC+ static let cacheAddress = 0x25CD8+ static let hardwareKey = 0x71BA3+ static let pagersKey = 0x71B8F+ static let processCode = Data(fromHexString:+ "605a40f9610200b0218c2e9114baff971f0000f1e8079f1a683e0339" ++ "605a40f9610200b0213c2e910dbaff971f0000f1e8079f1a68420339")!+ static let stackCode = Data(fromHexString: "005840f9610200b0218c2e91ccb7ff97a00200b4")!+ static let cacheCode = Data(fromHexString: "c05a40f961020090213c2e9115b3ff971f0000f1e8079f1ae8470139")!+ static func store<T: FixedWidthInteger>(_ value: T, _ offset: Int, _ data: inout Data) {+ var little = value.littleEndian+ withUnsafeBytes(of: &little) { data.replaceSubrange(offset ..< offset + $0.count, with: $0) }+ }+ static func text(_ value: String, _ offset: Int, _ data: inout Data) {+ let bytes = Data((value + "\0").utf8)+ data.replaceSubrange(offset ..< offset + bytes.count, with: bytes)+ }+ static func image(platform: UInt32 = 3) -> Data {+ var data = Data(repeating: 0, count: 0x73000)+ store(UInt32(0xFEED_FACF), 0, &data)+ store(UInt32(0x0100_000C), 4, &data)+ store(UInt32(7), 12, &data)+ store(UInt32(3), 16, &data)+ store(UInt32(232 + 24 + 24), 20, &data)+ store(UInt32(0x19), 32, &data)+ store(UInt32(232), 36, &data)+ text("__TEXT", 40, &data)+ store(UInt64(0x72000), 64, &data)+ store(UInt64(0x72000), 80, &data)+ store(UInt32(5), 88, &data)+ store(UInt32(5), 92, &data)+ store(UInt32(2), 96, &data)+ text("__text", 104, &data)+ text("__TEXT", 120, &data)+ store(UInt64(0x1000), 136, &data)+ store(UInt64(0x26000), 144, &data)+ store(UInt32(0x1000), 152, &data)+ text("__cstring", 184, &data)+ text("__TEXT", 200, &data)+ store(UInt64(0x71000), 216, &data)+ store(UInt64(0x1000), 224, &data)+ store(UInt32(0x71000), 232, &data)+ store(UInt32(0x32), 264, &data)+ store(UInt32(24), 268, &data)+ store(platform, 272, &data)+ store(UInt32(2), 288, &data)+ store(UInt32(24), 292, &data)+ store(UInt32(0x72000), 296, &data)+ let symbols: [(String, Int)] = [+ (CustomFirmwareTVTPRO.process, processAddress),+ ("_process_end", processAddress + processCode.count),+ (CustomFirmwareTVTPRO.stack, stackAddress),+ ("_stack_end", stackAddress + stackCode.count),+ (CustomFirmwareTVTPRO.cacheConstructor, cacheAddress),+ ("_cache_end", cacheAddress + cacheCode.count),+ (CustomFirmwareTVTPRO.getenv, 0x12938),+ ]+ store(UInt32(symbols.count), 300, &data)+ store(UInt32(0x72200), 304, &data)+ var cursor = 1+ for (index, item) in symbols.enumerated() {+ let entry = 0x72000 + index * 16+ store(UInt32(cursor), entry, &data)+ data[entry + 4] = 0x0E+ data[entry + 5] = 1+ store(UInt64(item.1), entry + 8, &data)+ text(item.0, 0x72200 + cursor, &data)+ cursor += item.0.utf8.count + 1+ }+ store(UInt32(cursor), 308, &data)+ data.replaceSubrange(processAddress ..< processAddress + processCode.count, with: processCode)+ data.replaceSubrange(stackAddress ..< stackAddress + stackCode.count, with: stackCode)+ data.replaceSubrange(cacheAddress ..< cacheAddress + cacheCode.count, with: cacheCode)+ text("dyld_hw_tpro", hardwareKey, &data)+ text("dyld_hw_tpro_pagers", pagersKey, &data)+ return data+ }++ @Test func `only key prefixes change and repeated runs capture nothing`() throws {+ var data = Self.image()+ let original = data+ let dry = try CustomFirmwareTVTPRO.patchStandalone(&data, reattest: false, dryRun: true, log: nil)+ #expect(dry.outcome == .wouldPatch && dry.records.isEmpty && data == original)+ let patched = try CustomFirmwareTVTPRO.patchStandalone(&data, reattest: false, log: nil)+ #expect(patched.outcome == .patched && patched.records.count == 2)+ var expected = original+ for offset in [Self.hardwareKey, Self.pagersKey] {+ expected.replaceSubrange(offset ..< offset + 4, with: Data("vphn".utf8))+ }+ #expect(data == expected) // Includes all code, flags and load commands.+ #expect(patched.records.allSatisfy { $0.patchID.hasPrefix("system-dyld-exp-tv_tpro.standalone.") })+ let repeated = try CustomFirmwareTVTPRO.patchStandalone(&data, reattest: false, log: nil)+ #expect(repeated.outcome == .alreadyPatched && repeated.records.isEmpty && data == expected)+ }++ @Test func `a partial prior key edit only writes the remaining key`() throws {+ var data = Self.image()+ data.replaceSubrange(Self.hardwareKey ..< Self.hardwareKey + 4, with: Data("vphn".utf8))+ let report = try CustomFirmwareTVTPRO.patchStandalone(&data, reattest: false, log: nil)+ #expect(report.outcome == .patched && report.records.count == 1)+ #expect(report.records.first?.fileOffset == Self.pagersKey)+ }++ @Test func `platform malformed bounds and undefined symbols are refused atomically`() {+ var malformedCommands = Self.image()+ Self.store(UInt32.max, 20, &malformedCommands)+ var malformedSection = Self.image()+ Self.store(UInt64.max, 224, &malformedSection)+ var imported = Self.image()+ imported[0x72004] = 0+ for original in [Self.image(platform: 2), malformedCommands, malformedSection, imported, Data(Self.image().prefix(50))] {+ var data = original+ #expect(throws: (any Error).self) { try CustomFirmwareTVTPRO.patchStandalone(&data, reattest: false, log: nil) }+ #expect(data == original)+ }+ }++ @Test func `keys must be complete unique strings referenced by every relevant function`() throws {+ var missing = Self.image()+ missing[Self.hardwareKey] = Character("X").asciiValue!+ var duplicate = Self.image()+ Self.text("dyld_hw_tpro", 0x71100, &duplicate)+ var noReference = Self.image()+ noReference.replaceSubrange(Self.cacheAddress + 4 ..< Self.cacheAddress + 8, with: ARM64.nop)+ var wrongCall = Self.image()+ wrongCall.replaceSubrange(Self.stackAddress + 12 ..< Self.stackAddress + 16, with: ARM64.nop)+ var wrongPresence = Self.image()+ wrongPresence.replaceSubrange(Self.processAddress + 20 ..< Self.processAddress + 24,+ with: try #require(ARM64Encoder.encodeCsetW(rd: 8, condition: .eq)))+ for original in [missing, duplicate, noReference, wrongCall, wrongPresence] {+ var data = original+ #expect(throws: (any Error).self) { try CustomFirmwareTVTPRO.patchStandalone(&data, reattest: false, log: nil) }+ #expect(data == original)+ }+ }++ @Test func `unsigned input cannot leave either key modified`() {+ var data = Self.image()+ let original = data+ #expect(throws: (any Error).self) { try CustomFirmwareTVTPRO.patchStandalone(&data, log: nil) }+ #expect(data == original)+ }++ static var probeRoot: URL? {+ ProcessInfo.processInfo.environment["VPHONE_TV_TPRO_PROBE_ROOT"].map { URL(fileURLWithPath: $0) }+ }+ @Test(.enabled(if: probeRoot != nil))+ func `real dyld signature identity survives and both cache keys undo cleanly`() throws {+ let root = try #require(Self.probeRoot)+ var data = try Data(contentsOf: root.appendingPathComponent("dyld-tpro-probe"))+ let original = data+ let directories = try #require(CustomFirmwareMachOCodeSignature.codeDirectories(in: data))+ #expect(try CustomFirmwareTVTPRO.patchStandalone(&data, dryRun: true, log: nil).outcome == .wouldPatch)+ #expect(data == original)+ let changed = try CustomFirmwareTVTPRO.patchStandalone(&data, log: nil)+ #expect(changed.outcome == .patched && changed.records.count == 2)+ #expect(CustomFirmwareMachOCodeSignature.codeDirectories(in: data) == directories)+ for directory in directories {+ #expect(data[directory.offset ..< directory.offset + directory.hashOffset]+ == original[directory.offset ..< directory.offset + directory.hashOffset])+ }+ #expect(try CustomFirmwareMachOCodeSignature.reattest(&data, modifiedOffsets: changed.sites.map(\.fileOffset)).isEmpty)+ let attested = data+ #expect(try CustomFirmwareTVTPRO.patchStandalone(&data, log: nil).outcome == .alreadyPatched)+ #expect(data == attested)++ let directory = root.appendingPathComponent("tpro-cache-probe")+ let chunks = try DyldSharedCacheChunkSet(directory: directory, architecture: "arm64", captureUndo: true)+ #expect(try CustomFirmwareTVTPRO.patchCache(in: chunks, dryRun: true, log: nil).outcome == .wouldPatch)+ #expect(chunks.takeUndoLog()?.records.isEmpty == true)+ let changedCache = try CustomFirmwareTVTPRO.patchCache(in: chunks, log: nil)+ #expect(changedCache.outcome == .patched && changedCache.records.count == 2)+ var undo = try #require(chunks.takeUndoLog())+ undo.stamp(patchID: CustomFirmwareTVTPRO.patchID)+ #expect(!undo.records.isEmpty)+ let writes = chunks.recordedWrites.count+ #expect(try CustomFirmwareTVTPRO.patchCache(in: chunks, log: nil).outcome == .alreadyPatched)+ #expect(chunks.recordedWrites.count == writes && chunks.takeUndoLog()?.records.isEmpty == true)+ let spans = try undo.restore(patchIDs: [CustomFirmwareTVTPRO.patchID], in: directory)+ #expect(try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: spans, log: nil).isFullyAttested)+ for site in changedCache.sites {+ #expect(try chunks.bytesAtVMA(site.virtualAddress, length: 4) == site.originalBytes)+ }+ #expect(try CustomFirmwareTVTPRO.patchCache(in: chunks, dryRun: true, log: nil).outcome == .wouldPatch)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelTVTPROPagersTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelTVTPROPagersTests.swiftnew file mode 100644index 00000000..6873f3d8--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelTVTPROPagersTests.swift@@ -0,0 +1,90 @@+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++@Suite("TV TPRO pager tunable")+struct KernelTVTPROPagersTests {+ static let segments = [+ MachOSegmentInfo(name: "__KLDDATA", vmAddr: 0, vmSize: 256, fileOffset: 0, fileSize: 256),+ MachOSegmentInfo(name: "__DATA", vmAddr: 256, vmSize: 64, fileOffset: 256, fileSize: 64),+ MachOSegmentInfo(name: "__TEXT_EXEC", vmAddr: 320, vmSize: 64, fileOffset: 320, fileSize: 64),+ ]++ func fixture() -> Data {+ var data = Data(repeating: 0, count: 384)+ data.replaceSubrange(16..<33, with: Data("sprr_tpro_pagers\0".utf8))+ // Name occupies 17 bytes; preserve descriptor alignment independently.+ put(&data, 64, 0x0010_0000_0000_0010)+ put(&data, 72, 0x0040_0000_0000_0100)+ put(&data, 80, 4)+ put(&data, 128, 1)+ put(&data, 136, 0x8010_2ABE_0000_0140)+ put(&data, 144, 0x0020_0000_0000_0040)+ put(&data, 256, 1)+ return data+ }++ func put(_ data: inout Data, _ offset: Int, _ value: UInt64) {+ var value = value.littleEndian+ withUnsafeBytes(of: &value) { data.replaceSubrange(offset..<offset+8, with: $0) }+ }++ @Test func validatesDescriptorAndRegistration() {+ let data = fixture()+ #expect(KernelCustomFirmwarePatcher.tvTPROPagersDefault(in: data, segments: Self.segments) == 256)+ }++ @Test func acceptsAlreadyZeroDefault() {+ var data = fixture()+ put(&data, 256, 0)+ #expect(KernelCustomFirmwarePatcher.tvTPROPagersDefault(in: data, segments: Self.segments) == 256)+ }++ @Test func blockedPatchLeavesBytesUnchanged() {+ let data = fixture()+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)+ patcher.segments = Self.segments+ patcher.gate = VPhonePatchGate(declared: [FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers], enabled: [])+ #expect(patcher.patchTVTPROPagers())+ #expect(patcher.patches.isEmpty)+ #expect(patcher.buffer.data == data)+ }++ @Test func rejectsInvalidDescriptorsAndRegistrations() {+ for (offset, value) in [(80, UInt64(8)), (80, 0x100000004), (72, 0x40000100), (72, 320), (128, 2), (136, 256), (144, 65), (256, 2)] {+ var data = fixture()+ put(&data, offset, value)+ #expect(KernelCustomFirmwarePatcher.tvTPROPagersDefault(in: data, segments: Self.segments) == nil)+ }+ }++ @Test func rejectsAmbiguousRegistrationAndTruncation() {+ var data = fixture()+ data.replaceSubrange(160..<184, with: data[128..<152])+ #expect(KernelCustomFirmwarePatcher.tvTPROPagersDefault(in: data, segments: Self.segments) == nil)+ #expect(KernelCustomFirmwarePatcher.tvTPROPagersDefault(in: Data(), segments: []) == nil)+ // Segment metadata can claim bytes beyond EOF; do not trust it as a+ // substitute for bounding the integer read against the actual file.+ let truncated = fixture().prefix(258)+ #expect(KernelCustomFirmwarePatcher.tvTPROPagersDefault(in: Data(truncated), segments: Self.segments) == nil)+ }++ @Test func nativeResearchKernelWhenPresent() throws {+ let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent()+ .deletingLastPathComponent().deletingLastPathComponent()+ .deletingLastPathComponent().deletingLastPathComponent()+ let url = root.appendingPathComponent(".build/tvos-research/kernel-dec/kernelcache.research.vphone600.decompressed")+ guard FileManager.default.fileExists(atPath: url.path) else { return }+ let data = try Data(contentsOf: url)+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)+ patcher.parseMachO()+ #expect(patcher.patchTVTPROPagers())+ let record = try #require(patcher.patches.first)+ #expect(record.originalBytes == Data([1, 0, 0, 0]))+ #expect(record.patchedBytes == Data(repeating: 0, count: 4))+ var expected = data+ expected.replaceSubrange(record.fileOffset..<record.fileOffset+4, with: record.patchedBytes)+ #expect(patcher.buffer.data == expected)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swiftindex fa71a903..f71a49d0 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift@@ -12,6 +12,46 @@ import VPhonePatchKit@Suite("Guest patch resolution")struct FirmwareGuestPatchResolutionTests {+ @Test+ func `TV serial selection excludes iOS payloads and cache patches`() throws {+ let standard = try VPhonePatchPlan.resolve(+ preset: FirmwarePatchSetCatalog.standardPreset,+ patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion("26.4"),+ cloudOS: VPhoneVersion("26.4"),+ )+ let unvalidated = FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: standard.enabled)+ #expect(unvalidated.contains("system-vphoned-boot-install"))+ #expect(unvalidated.contains("system-launchdaemons-boot-environment"))+ #expect(unvalidated.contains("system-extensions-boot-gpu_bundle"))+ #expect(unvalidated.contains("dyld-cfw-camera"))+ #expect(!unvalidated.contains("system-seputil-boot-gigalocker_uuid"))+ #expect(!unvalidated.contains("system-gigalocker-boot-rename"))+ let serial = standard.enabled.subtracting(unvalidated)+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: serial).isEmpty)+ #expect(serial.intersection(FirmwareGuestPatchResolution.guestTargetIdentifiers)+ == FirmwareGuestPatchResolution.tvSupportedGuestPatches.subtracting([FirmwareGuestSystemPatchSet.tvTPRO]))+ #expect(serial.subtracting(FirmwareGuestPatchResolution.guestTargetIdentifiers)+ == standard.enabled.subtracting(FirmwareGuestPatchResolution.guestTargetIdentifiers))+ }++ @Test+ func `TV TPRO is opt in and retains the TV guest guard`() throws {+ let identifier = FirmwareGuestSystemPatchSet.tvTPRO+ let standard = try VPhonePatchPlan.resolve(+ preset: FirmwarePatchSetCatalog.standardPreset,+ patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion("26.4"), cloudOS: VPhoneVersion("26.4"),+ )+ #expect(!standard.enabled.contains(identifier))+ let serial = standard.enabled.subtracting(+ FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: standard.enabled),+ ).union([identifier])+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: serial).isEmpty)+ #expect(!serial.contains("system-vphoned-boot-install"))+ #expect(!serial.contains("system-extensions-boot-gpu_bundle"))+ }+@Testfunc `Guest target identifiers include the guest patches and exclude the boot chain`() {let guest = FirmwareGuestPatchResolution.guestTargetIdentifiersdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 4067c854..45617ee9 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -82,7 +82,6 @@ struct VPhoneCustomFirmwareInstaller {/// cache travels with it. `verifiedDyldCacheDirectory` admits it — it is a/// plain single-link file, and `enumerateChunks` never mistakes a dotfile/// for a `dyld_shared_cache_arm64e*` chunk.- private static let dscCacheRelative = "System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"private static let dscUndoLogLeaf = ".vphone-dsc-undo.json"/// Root-owned and sticky, outside every user's tree. The work folder is@@ -200,6 +199,16 @@ struct VPhoneCustomFirmwareInstaller {let restore = mode == .full? try restoreTree(in: bundleDirectory, path: bundlePath, owner: callerUID): nil+ let device = configuredGuestDevice(in: bundleDirectory) ?? guestDevice(of: restore)+ 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))+ 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: ", "))")+ }+ }// Before any disk work, so what it says is not buried under it.recoverBoardDeviceTree(in: bundleDirectory, restore: restore, plan: plan, invokingUser: invokingUser)@@ -218,6 +227,12 @@ struct VPhoneCustomFirmwareInstaller {// and a failed install leaves the original untouched.let image: URLlet cloned = try work.directory.clone(disk, to: "Disk.img")+ if device.family == .appleTV {+ // A paired dyld edit must never fall back to mutating the live disk.+ // Its errors propagate below, so this clone is committed only after+ // the whole install succeeds.+ try CustomFirmwareTVTPROInstallation.requirePrivateClone(cloned)+ }if cloned {image = work.file("Disk.img")} else {@@ -334,7 +349,9 @@ struct VPhoneCustomFirmwareInstaller {// `installVphoned`, so it is the signal that the guest is not// pristine. A VM that was never installed has nothing applied, so// its prior set is empty whatever a stale plan might say.- let wasInstalled = (try? systemRoot.exists("System/Library/xpc/launchd.plist.bak")) ?? false+ let hasLaunchdBackup = (try? systemRoot.exists("System/Library/xpc/launchd.plist.bak")) ?? false+ // TV installs deliberately omit vphoned and its launchd backup.+ let wasInstalled = hasLaunchdBackup || (device.family == .appleTV && receiptGuest != nil)priorGuest = receiptGuest ?? (wasInstalled ? priorFallback : [])switch mode {case .kernelUpdate:@@ -344,6 +361,7 @@ struct VPhoneCustomFirmwareInstaller {throw ValidationError("A full CFW install needs a prepared restore tree.")}liveGuest = try applyGuestPatches(+ guestDevice: device,system: systemRoot,xart: xartRoot,restore: restore,@@ -362,6 +380,7 @@ struct VPhoneCustomFirmwareInstaller {)}liveGuest = try applyGuestPatches(+ guestDevice: device,system: systemRoot,xart: nil,restore: nil,@@ -386,7 +405,6 @@ struct VPhoneCustomFirmwareInstaller {let boardDeviceTree = try stageBoardDeviceTree(in: bundleDirectory, work: work)// An environment update has no restore tree to read the device from;// the VM's configuration says which board repair its tree takes.- let device = configuredGuestDevice(in: bundleDirectory) ?? guestDevice(of: restore)try liveGuest.formUnion(patchPreboot(volumes: volumes,work: work,@@ -400,16 +418,19 @@ struct VPhoneCustomFirmwareInstaller {// Selected patches this guest has nothing for, so the receipt does not// report them as missing forever: the board audio repair on an// iPhone17,3, which has no board of its own to present, the iPhone- // product repair on an iPad, and the build spoof with no value set. A+ // product repair on a non-iPhone, and the build spoof with no value set. A// guest whose board tree could not be recovered is not among them: its// repair is missing, and drift should keep saying so.var notApplicableGuest = Set<String>()if !device.presentsBoard {notApplicableGuest.insert(FirmwareGuestSystemPatchSet.prebootBoardAudio)}- if device.isPad {+ if device.family != .iPhone {notApplicableGuest.insert(FirmwareGuestSystemPatchSet.prebootIPhoneProduct)}+ if device.family != .appleTV {+ notApplicableGuest.insert(FirmwareGuestSystemPatchSet.tvTPRO)+ }if buildVersion?.isEmpty ?? true {notApplicableGuest.insert("system-systemversion-cfw-build_version")}@@ -437,11 +458,15 @@ struct VPhoneCustomFirmwareInstaller {try work.directory.setMode("Disk.img", disk.mode & 0o777)try work.directory.rename("Disk.img", to: "Disk.img", in: bundleDirectory)}- try installSignedDaemonCopy(- in: bundleDirectory,- work: work,- owner: invokingUser.map { ($0.uid, $0.gid) },- )+ // A serial-only research selection can leave vphoned off. Its host+ // copy exists only after installVphoned staged it successfully.+ if try work.directory.isRegularFile("vphoned") {+ try installSignedDaemonCopy(+ in: bundleDirectory,+ work: work,+ owner: invokingUser.map { ($0.uid, $0.gid) },+ )+ }// Record what is live in the guest now. Written through the pinned// bundle descriptor as the caller, 0777 like every other host VM// artifact, replacing only the `Guest` part so a boot-chain part a@@ -455,7 +480,11 @@ struct VPhoneCustomFirmwareInstaller {)switch mode {case .full:- print("[+] CFW system install complete; vphoned is installed, no package bootstrap was staged")+ if liveGuest.contains("system-vphoned-boot-install") {+ print("[+] CFW system install complete; vphoned is installed, no package bootstrap was staged")+ } else {+ print("[+] CFW system install complete; vphoned is not installed")+ }case .environmentOnly:print("[+] Guest environment updated; start the VM to pick it up")case .kernelUpdate:@@ -1001,7 +1030,8 @@ struct VPhoneCustomFirmwareInstaller {/// (a library absent from the VM stays absent, no `/vh` alias is created) and/// no restore-tree step runs.///- /// Each patch runs in isolation: one patch failing — a verb rejecting an+ /// Paired TV dyld updates abort on failure and discard the private disk+ /// clone, preserving the original disk and receipt. Other patches run in isolation: one patch failing — a verb rejecting an/// unexpected prologue on an older VM, say — is reported and the patch is/// left in its prior state, but the run continues and the vphoned redeploy,/// done first, is never blocked. Non-patch failures (a volume that will not@@ -1009,6 +1039,7 @@ struct VPhoneCustomFirmwareInstaller {/// failures; they are printed as `[!]` lines and summarised at the end.@discardableResultprivate func applyGuestPatches(+ guestDevice: VPhoneGuestDevice,system: VPhoneConfinedDirectory,xart: VPhoneConfinedDirectory?,restore: VPhoneConfinedDirectory?,@@ -1111,7 +1142,13 @@ struct VPhoneCustomFirmwareInstaller {// still has the stock 6 GiB and must still be refused. A VM with no// kernelcache receipt falls back to the patch's applicability, the// 27.x base.- let dsc = try verifiedDyldCacheDirectory(system: system)+ // The selected TV donor has a native arm64 cache. Keep its directory+ // intact; cryptex symlinks would point into images it does not ship.+ 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 dsc = try verifiedDyldCacheDirectory(system: system, relative: cacheRelative)let widenedRegion = kernelPatches.map { $0.contains("kernel-boot-shared_region_size") }?? version.hasPrefix("27.")let kernelRegionSize = widenedRegion@@ -1120,6 +1157,7 @@ struct VPhoneCustomFirmwareInstaller {do {try DyldSharedCacheMaxSlidePatcher.requireFitsAtSlideZero(chunksDirectory: URL(fileURLWithPath: dsc),+ architecture: cacheArchitecture,kernelRegionSize: kernelRegionSize,)} catch let overflow as DyldSharedCacheMaxSlidePatcher.RegionOverflow {@@ -1128,6 +1166,20 @@ struct VPhoneCustomFirmwareInstaller {print(" [!] shared region check skipped: \(error)")}+ if guestDevice.family == .appleTV {+ let identifier = FirmwareGuestSystemPatchSet.tvTPRO+ let enabled = on(identifier)+ // Unlike independent optional patches, dyld's two copies form a+ // boot-critical pair. Abort on any error; never commit a partial+ // pair or describe it as unchanged via isolate's catch-and-continue.+ let applied = try updateTVDyld(+ identifier: identifier, enabled: enabled, system: system, work: work,+ cacheDirectory: URL(fileURLWithPath: dsc), cacheRelative: cacheRelative,+ priorApplied: priorGuest.contains(identifier),+ )+ if applied { live.insert(identifier) }+ }+// 1. The redeploy first, so no later patch failure can block it. vphoned// and the environment are boot-essential (always on). The environment// keeps its old narrow rule under `environmentOnly`.@@ -1182,7 +1234,7 @@ struct VPhoneCustomFirmwareInstaller {("dyld-cfw-camera", "patch-camera-dsc", [dsc, (dsc as NSString).appendingPathComponent("dyld_shared_cache_arm64e")]),]applyDyldPatches(- dyld, dsc: dsc, system: system, plan: plan, priorGuest: priorGuest,+ dyld, dsc: dsc, cacheRelative: cacheRelative, system: system, plan: plan, priorGuest: priorGuest,live: &live, failures: &failures,)@@ -1478,6 +1530,7 @@ struct VPhoneCustomFirmwareInstaller {private func applyDyldPatches(_ dyld: [(id: String, verb: String, args: [String])],dsc: String,+ cacheRelative: String,system: VPhoneConfinedDirectory,plan: VPhoneVirtualMachinePatchPlan?,priorGuest: Set<String>,@@ -1488,7 +1541,7 @@ struct VPhoneCustomFirmwareInstaller {plan?.isEnabled(id) ?? !FirmwareGuestSystemPatchSet.settingsRowPatches.contains(id)}let undoAbsolute = (dsc as NSString).appendingPathComponent(Self.dscUndoLogLeaf)- let undoRelative = "\(Self.dscCacheRelative)/\(Self.dscUndoLogLeaf)"+ let undoRelative = "\(cacheRelative)/\(Self.dscUndoLogLeaf)"let undoLog = (try? system.readData(undoRelative)).flatMap { try? DyldSharedCacheUndoLog.decode($0) }let recorded = undoLog?.patchIDs ?? []@@ -1668,8 +1721,7 @@ struct VPhoneCustomFirmwareInstaller {/// files in it, and hand the tools that verified path. The path is/// stable: the volume is mounted inside the root-only work folder and/// nothing else writes to it during the install.- private func verifiedDyldCacheDirectory(system: VPhoneConfinedDirectory) throws -> String {- let relative = "System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"+ private func verifiedDyldCacheDirectory(system: VPhoneConfinedDirectory, relative: String) throws -> String {let directory = try system.directory(relative)for name in try directory.entries() {guard let metadata = try directory.status(name) else { continue }@@ -1699,7 +1751,10 @@ struct VPhoneCustomFirmwareInstaller {if !(populated(os) && populated(app)) {let manifest = work.file("iPhone-BuildManifest.plist")try restore.readData("iPhone-BuildManifest.plist").write(to: manifest)- let paths = try CustomFirmwareDaemons.cryptexPaths(buildManifest: manifest)+ guard case let .cryptex(paths) = try CustomFirmwareDaemons.filesystemLayout(buildManifest: manifest) else {+ print("[*] Monolithic tvOS system image: no cryptex files to install")+ return+ }// Root attaches and decrypts only private copies of the images,// taken from descriptors verified to be the caller's own files.let systemImage = try stageCryptexImage(paths.systemOS, from: restore, as: "SystemOS-source.dmg", work: work, owner: owner)@@ -2067,7 +2122,7 @@ struct VPhoneCustomFirmwareInstaller {// A board-presenting iPhone's restored tree takes the board's// values only where vphone600 has a placeholder; Camera Control// and the Action Button are added here.- if !guestDevice.isPad {+ if guestDevice.family == .iPhone {repairGroup.append((FirmwareGuestSystemPatchSet.prebootIPhoneProduct, "patch-dt-iphone-product", [boardDeviceTree.path]))}}@@ -2510,6 +2565,74 @@ struct VPhoneCustomFirmwareInstaller {try system.replaceFile(path, fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)}+ private func updateTVDyld(+ identifier: String,+ enabled: Bool,+ system: VPhoneConfinedDirectory,+ work: WorkDirectory,+ cacheDirectory: URL,+ cacheRelative: String,+ priorApplied: Bool,+ ) throws -> Bool {+ let path = "usr/lib/dyld"+ let backup = "\(path).bak"+ let undoPath = "\(cacheRelative)/\(Self.dscUndoLogLeaf)"+ // A corrupt or unreadable undo record is not an absent record: never+ // overwrite it and lose the only original cache bytes.+ let undo = try system.exists(undoPath)+ ? DyldSharedCacheUndoLog.decode(system.readData(undoPath))+ : nil+ let hasUndo = undo?.patchIDs.contains(identifier) == true+ if !enabled, !priorApplied, !hasUndo { return false }+ try CustomFirmwareTVTPROInstallation.validateBackup(+ priorApplied: priorApplied, hasUndo: hasUndo,+ backupExists: system.exists(backup), backupIsRegular: system.isRegularFile(backup),+ )+ let chunks = try DyldSharedCacheChunkSet(directory: cacheDirectory, architecture: "arm64", captureUndo: enabled)+ func patchStandalone(_ staged: URL) throws {+ try CustomFirmwareTVTPRO.patchStandalone(fileAt: staged, log: { print($0) })+ }+ func patchCache(dryRun: Bool = false) throws -> Bool {+ return try CustomFirmwareTVTPRO.patchCache(in: chunks, dryRun: dryRun, log: { print($0) }).outcome == .alreadyPatched+ }+ if enabled {+ if try !system.exists(backup) { try system.copyFile(from: path, to: backup) }+ let staged = work.file("dyld-tv")+ try work.directory.removeItem("dyld-tv")+ try system.copyFile(from: backup, to: "dyld-tv", in: work.directory)+ if try patchCache(dryRun: true), !hasUndo {+ throw ValidationError("\(identifier): cached dyld is already modified but has no undo record.")+ }+ // Fully validate and re-attest the private standalone copy before+ // changing the cache; a bad signature must not leave half a pair.+ try patchStandalone(staged)+ _ = try patchCache()+ if let captured = chunks.takeUndoLog(),+ let merged = DyldSharedCacheUndoLog.updated(existing: undo, captured: captured, patchID: identifier)+ {+ try system.writeFile(undoPath, contents: merged.encoded(), mode: 0o644, owner: Self.guestOwner)+ }+ try system.replaceFile(path, fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)+ return true+ }+ try CustomFirmwareTVTPROInstallation.restorePair {+ guard let undo, hasUndo else { return }+ let spans = try undo.restore(patchIDs: [identifier], in: cacheDirectory, log: { print($0) })+ let attestation = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: spans, log: { print($0) })+ guard attestation.isFullyAttested else {+ throw ValidationError("\(identifier): restored cache pages could not be fully re-attested; keeping the undo record.")+ }+ } restoreStandalone: {+ try system.copyFile(from: backup, to: "dyld-tv-original", in: work.directory)+ try system.replaceFile(path, fromFileAt: work.file("dyld-tv-original"), mode: 0o755, owner: Self.guestOwner)+ } retireUndo: {+ guard let undo, hasUndo else { return }+ try system.writeFile(undoPath, contents: undo.removing(patchIDs: [identifier]).encoded(), mode: 0o644, owner: Self.guestOwner)+ }+ print(" [+] \(identifier): restored standalone and cached dyld")+ return false+ }+/// Re-seal a code-signed bundle on the mounted guest system volume.////// `patchMachO` re-signs the Mach-O it replaces, but a bundle's outerdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swiftindex c4c2340d..ae4212a1 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift@@ -1,8 +1,10 @@+import ArgumentParserimport Darwinimport FirmwarePatcherimport Foundationimport VPhoneArchiveKitimport VPhoneCoreKit+import VPhonePatchKit/// Builds one restore tree from two IPSWs without a shell or a second full/// copy of either source archive. All extraction and merging happens in one@@ -71,6 +73,26 @@ enum VPhoneFirmwarePreparer {downloadConnections: downloadConnections,)+ // Preparation must use the same selection as patch/install: a serial+ // configuration with the GPU disabled must not restore another PCC VM+ // merely to recover a driver that will never be installed.+ let selection = VPhonePatchPresetStore.selection(forVM: bundle.url)+ guard let preset = VPhonePatchPresetStore.preset(named: selection.presetIdentifier) else {+ let available = VPhonePatchPresetStore.availablePresets().map(\.identifier)+ throw ValidationError("Unknown patch preset '\(selection.presetIdentifier)'. Available: \(available.joined(separator: ", "))")+ }+ let pipeline = FirmwarePipeline(+ vmDirectory: bundle.url,+ variant: .jb,+ verbose: false,+ preset: preset,+ blockedPatches: Set(selection.blockedPatches),+ allowedPatches: Set(selection.allowedPatches),+ )+ guard let plan = try pipeline.resolvePlan(iOSBase: VPhoneVersion(phone.version), cloudOS: VPhoneVersion(cloud.version)) else {+ throw ValidationError("Patch preset '\(selection.presetIdentifier)' did not resolve.")+ }+let name = device.restoreTreeName(version: phone.version, build: phone.build)let destination = bundle.url.appendingPathComponent(name)let staging = bundle.url.appendingPathComponent(".firmware-prepare-\(UUID().uuidString)")@@ -98,45 +120,49 @@ enum VPhoneFirmwarePreparer {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)- let cachedDriver = cachedGPUDriver(for: cloud)- if let gpuDriverBundle {- print("[*] Staging GPU driver from local bundle...")- try VPhonePCCGPUDriver.stage(- from: gpuDriverBundle,- into: phoneTree,- expectedPlatformVersion: cloud.version,- )- } else if (try? VPhonePCCGPUDriver.stage(- from: cachedDriver,- into: phoneTree,- expectedPlatformVersion: cloud.version,- )) != nil {- print("[+] GPU driver reused from cloudOS \(cloud.version) (\(cloud.build)) cache")- } else {- print("[*] Restoring cloudOS in a temporary vphone VM to extract its GPU driver...")- try VPhonePCCGPURecovery.stage(- cloudOSDirectory: cloudTree,+ if plan.isEnabled("system-extensions-boot-gpu_bundle") {+ let cachedDriver = cachedGPUDriver(for: cloud)+ if let gpuDriverBundle {+ print("[*] Staging GPU driver from local bundle...")+ try VPhonePCCGPUDriver.stage(+ from: gpuDriverBundle,+ into: phoneTree,+ expectedPlatformVersion: cloud.version,+ )+ } else if (try? VPhonePCCGPUDriver.stage(+ from: cachedDriver,into: phoneTree,expectedPlatformVersion: cloud.version,- )- // Every later machine on this cloudOS build skips the restore.- do {- try storeGPUDriver(VPhonePCCGPUDriver.stagedBundle(in: phoneTree), at: cachedDriver)- } catch {- fputs("warning: could not cache the GPU driver at \(cachedDriver.path): \(error.localizedDescription)\n", stderr)+ )) != nil {+ print("[+] GPU driver reused from cloudOS \(cloud.version) (\(cloud.build)) cache")+ } else {+ print("[*] Restoring cloudOS in a temporary vphone VM to extract its GPU driver...")+ try VPhonePCCGPURecovery.stage(+ cloudOSDirectory: cloudTree,+ into: phoneTree,+ expectedPlatformVersion: cloud.version,+ )+ // Every later machine on this cloudOS build skips the restore.+ do {+ try storeGPUDriver(VPhonePCCGPUDriver.stagedBundle(in: phoneTree), at: cachedDriver)+ } catch {+ fputs("warning: could not cache the GPU driver at \(cachedDriver.path): \(error.localizedDescription)\n", stderr)+ }}- }- let source = resources.gpuCompilerPlugin- guard fm.fileExists(atPath: source.path) else { throw Error.missingComponent(source) }- print("[*] Merging bundled GPU compiler plugin...")- let pluginName = "libAppleParavirtCompilerPluginIOGPUFamily.dylib"- let destinationPlugin = VPhonePCCGPUDriver.stagedBundle(in: phoneTree).appendingPathComponent(pluginName)- if fm.fileExists(atPath: destinationPlugin.path) {- try fm.removeItem(at: destinationPlugin)+ let source = resources.gpuCompilerPlugin+ guard fm.fileExists(atPath: source.path) else { throw Error.missingComponent(source) }+ print("[*] Merging bundled GPU compiler plugin...")+ let pluginName = "libAppleParavirtCompilerPluginIOGPUFamily.dylib"+ let destinationPlugin = VPhonePCCGPUDriver.stagedBundle(in: phoneTree).appendingPathComponent(pluginName)+ if fm.fileExists(atPath: destinationPlugin.path) {+ try fm.removeItem(at: destinationPlugin)+ }+ 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")}- try fm.copyItem(at: source, to: destinationPlugin)- try fm.setAttributes([.posixPermissions: NSNumber(value: 0o755)], ofItemAtPath: destinationPlugin.path)// The destination did not exist at entry and the staging directory is// on the same volume. One rename exposes the complete restore tree.diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plistindex eb7dfafe..4e7429df 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist@@ -126,6 +126,8 @@<string>dyld-exp-mis_trust_auth</string><string>system-preferences-exp-root_rows</string><string>dyld-exp-settings_software_update_row</string>+ <string>system-dyld-exp-tv_tpro</string>+ <string>kernel-exp-tv_tpro_pagers</string></array></dict></dict>diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swiftindex 47e6a150..af567990 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift@@ -68,6 +68,12 @@ final class VPhoneApplication: NSApplication {forwardGlobe(event, view: view)return false}+ // 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.+ if event.keyCode == Self.escapeKeyCode, view.isTVGuest {+ return false+ }// Esc replays the guest's back gesture: iOS has no back key, and a// forwarded Escape only reads as cancel. The press and its release both// stop here, so the guest sees neither. An iPad has a real Esc key —diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swiftindex 41f3ae21..032f6a17 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineKeySender.swift@@ -40,6 +40,17 @@ class VPhoneVirtualMachineKeySender {// MARK: - Hardware Keys (Consumer Page 0x0C)+ /// The TV's Back/Menu key through the same native keyboard as arrows and+ /// Return. This works without the guest daemon, including during setup.+ func sendTVBack() {+ guard let keyboard = firstKeyboard else { return }+ for type in [0, 1] {+ if let event = Dynamic._VZKeyEvent(type: type, keyCode: UInt16(0x35)).asAnyObject {+ Dynamic(keyboard).sendKeyEvents([event] as NSArray)+ }+ }+ }+func sendHome() {guard requireConnection() else { return }control.sendHIDPress(page: 0x0C, usage: 0x40)diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneBootCommand+VirtualMachine.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneBootCommand+VirtualMachine.swiftindex 7d887e02..b05a8c0a 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneBootCommand+VirtualMachine.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneBootCommand+VirtualMachine.swift@@ -32,6 +32,7 @@ extension VPhoneBootCommand {screenScale: manifest.screenConfig.scale,kernelDebugPort: kernelDebugPort,isPadGuest: manifest.guestDevice.isPad,+ isTVGuest: manifest.guestDevice.family == .appleTV,)}}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swiftindex 09101615..ad3a1164 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift@@ -166,7 +166,8 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {.resolvingSymlinksInPath().path,)- wc.captureView?.escapeIsBackGesture = !options.isPadGuest+ wc.captureView?.escapeIsBackGesture = !options.isPadGuest && !options.isTVGuest+ wc.captureView?.isTVGuest = options.isTVGuestwindowController = wclet fileWC = VPhoneFileWindowController()diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swiftindex 19c92adc..6f13a16e 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift@@ -46,6 +46,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {var kernelDebugPort: Int?/// The guest runs iPadOS: Esc is a key there, not the back gesture.var isPadGuest = false+ var isTVGuest = false}private struct DeviceIdentity {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swiftindex e0a03c57..891a2bfe 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachineView.swift@@ -10,6 +10,7 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {/// Whether Esc replays the back gesture (an iPhone, which has no Esc key)/// or reaches the guest as Esc (an iPad). See `VPhoneApplication`.var escapeIsBackGesture = true+ var isTVGuest = falsevar hardwareKeyboardEnabled = true/// Whether trackpad scroll/pinch gestures are replayed as guest touches.@@ -760,6 +761,10 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {private var backGestureInFlight = falsefunc performBackGesture() {+ if isTVGuest {+ keySender?.sendTVBack()+ return+ }guard !backGestureInFlight, let display = recordingGraphicsDisplay else { return }let size = display.sizeInPixelsguard size.width > 0, size.height > 0 else { return }diff --git a/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift b/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swiftindex 26090f74..78d8d901 100644--- a/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift+++ b/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift@@ -533,6 +533,30 @@ struct IPSWCacheTests {}}+ @Test func `a known TV donor pairs with cloudOS without admitting unknown TVs`() throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let tv = try ipsw(in: root, "tv", productTypes: ["AppleTV5,3"], deviceClasses: ["J42DAP"])+ let cloud = try ipsw(in: root, "cloud", productTypes: ["iProd99,1"], deviceClasses: ["vresearch101ap", "vphone600ap"])+ let otherTV = try ipsw(in: root, "other-tv", productTypes: ["AppleTV14,1"], deviceClasses: ["j255ap"])++ try VPhoneIPSWCache.checkPair(iPhone: tv, cloudOS: cloud)+ #expect(VPhoneIPSWCache.guestDevice(for: tv) == .appleTV5_3)+ #expect(tv.deviceClasses == ["j42dap"])+ #expect(VPhoneIPSWCache.guestProductTypes.contains("AppleTV5,3"))+ #expect {+ try VPhoneIPSWCache.checkPair(iPhone: otherTV, cloudOS: cloud)+ } throws: { error in+ if case .notIPhoneSource? = error as? VPhoneIPSWCache.Error { true } else { false }+ }+ #expect {+ try VPhoneIPSWCache.checkPair(iPhone: cloud, cloudOS: tv)+ } throws: { error in+ if case .swappedSources? = error as? VPhoneIPSWCache.Error { true } else { false }+ }+ }+@Test func `an iPad IPSW the guest device list knows pairs with cloudOS`() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swiftindex f2cfbbae..bdce5bea 100644--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift@@ -18,6 +18,15 @@ public struct VPhoneGuestDevice: Sendable, Equatable {public enum Family: String, Codable, Sendable {case iPhonecase iPad+ case appleTV++ public var osName: String {+ switch self {+ case .iPhone: "iOS"+ case .iPad: "iPadOS"+ case .appleTV: "tvOS"+ }+ }}public let family: Family@@ -27,7 +36,7 @@ public struct VPhoneGuestDevice: Sendable, Equatable {public let deviceClass: String/// The marketing name, for logs and prompts.public let productName: String- /// The guest display, as the device's panel has it.+ /// The guest display: a device panel, or a provisional virtual TV canvas.public let screen: VPhoneVirtualMachineManifest.ScreenConfigpublic init(@@ -136,6 +145,18 @@ public struct VPhoneGuestDevice: Sendable, Equatable {/// iPad Pro 13-inch (M5): 2064x2752, 1032x1376 points.public static let iPad17_3 = iPad("iPad17,3", "j820ap", "iPad Pro 13-inch (M5)", width: 2064, height: 2752)+ /// Apple TV HD donor; the documented 26.4 beta pairing boots+ /// with explicit TV patches. No general catalog pairing is advertised.+ /// J42d's device tree supplies the TV idiom and 1x scale. The 1080p canvas+ /// and 72 ppi are provisional VM settings, not an attached television's density.+ public static let appleTV5_3 = VPhoneGuestDevice(+ family: .appleTV,+ productType: "AppleTV5,3",+ deviceClass: "j42dap",+ productName: "Apple TV HD",+ screen: .init(width: 1920, height: 1080, pixelsPerInch: 72, scale: 1.0),+ )+public static let known: [VPhoneGuestDevice] = [iPhone17_3,iPhone17_4, iPhone17_1, iPhone17_2, iPhone17_5,@@ -145,6 +166,7 @@ public struct VPhoneGuestDevice: Sendable, Equatable {iPad15_3, iPad15_5,iPad16_3, iPad16_5,iPad17_1, iPad17_3,+ appleTV5_3,]/// Cellular models that ship in the same IPSW as a known Wi-Fi model and map@@ -174,12 +196,12 @@ public struct VPhoneGuestDevice: Sendable, Equatable {/// The folder `fw prepare` builds the restore tree in.////// Every reader of the tree — restore, `cfw install`, Launchpad's cleanup —- /// matches `iPhone*_Restore`, so an iPad tree keeps that prefix: the- /// prefix names the iPhoneOS restore format, not the device.+ /// matches `iPhone*_Restore`, so non-iPhone trees keep that prefix as a+ /// restore-tree compatibility convention.public func restoreTreeName(version: String, build: String) -> String {switch family {case .iPhone: "\(productType)_\(version)_\(build)_Restore"- case .iPad: "iPhoneOS_\(productType)_\(version)_\(build)_Restore"+ case .iPad, .appleTV: "iPhoneOS_\(productType)_\(version)_\(build)_Restore"}}diff --git a/VPhoneKit/VPhoneCoreKitTests/Firmware/FirmwareCatalogReportTests.swift b/VPhoneKit/VPhoneCoreKitTests/Firmware/FirmwareCatalogReportTests.swiftindex 7a288bc1..8fc507c5 100644--- a/VPhoneKit/VPhoneCoreKitTests/Firmware/FirmwareCatalogReportTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Firmware/FirmwareCatalogReportTests.swift@@ -16,9 +16,10 @@ struct FirmwareCatalogReportTests {}}- @Test func `lists every known guest device`() {+ @Test func `lists curated guests without advertising unlisted TV pairings`() {let report = VPhoneFirmwareCatalog.report- #expect(report.devices.map(\.productType) == VPhoneGuestDevice.known.map(\.productType))+ #expect(report.devices.map(\.productType) == VPhoneGuestDevice.known.filter { $0.family != .appleTV }.map(\.productType))+ #expect(VPhoneFirmwareCatalog.pairings(for: "AppleTV5,3").isEmpty)#expect(report.devices.first?.pairings == report.pairings)for device in report.devices.dropFirst() {#expect(device.family == VPhoneGuestDevice.named(device.productType)?.family.rawValue)diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swiftindex 278c70a6..23e25029 100644--- a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift@@ -16,6 +16,34 @@ struct GuestDeviceTests {#expect(VPhoneGuestDevice.isPadManifest(["SupportedProductTypes": ["iPad13,1"]]))}+ @Test+ func `a supported TV donor is detected without admitting unknown TVs`() {+ 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.appleTV5_3.isPad)+ #expect(VPhoneGuestDevice.appleTV5_3.presentsBoard)+ #expect(VPhoneGuestDevice.appleTV5_3.family.osName == "tvOS")+ #expect(VPhoneGuestDevice.appleTV5_3.boardDeviceTreePath == "Firmware/all_flash/DeviceTree.j42dap.im4p")+ #expect(VPhoneGuestDevice.appleTV5_3.restoreTreeName(version: "26.4", build: "23L243")+ == "iPhoneOS_AppleTV5,3_26.4_23L243_Restore")+ }++ @Test+ func `a TV guest persists its identity and provisional landscape canvas`() throws {+ let manifest = VPhoneVirtualMachineManifest.newVM().updating(guestDevice: .appleTV5_3)+ #expect(manifest.guestProductType == "AppleTV5,3")+ #expect(manifest.screenConfig == .init(width: 1920, height: 1080, pixelsPerInch: 72, scale: 1.0))+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).plist")+ defer { try? FileManager.default.removeItem(at: url) }+ try manifest.write(to: url)+ let loaded = try VPhoneVirtualMachineManifest.load(from: url)+ #expect(loaded.guestDevice == .appleTV5_3)+ #expect(loaded.screenConfig == manifest.screenConfig)+ #expect(loaded.updating(cpuCount: 4).guestProductType == "AppleTV5,3")+ }+@Testfunc `an iPad restore tree keeps the prefix every reader matches`() {let name = VPhoneGuestDevice.iPad16_1.restoreTreeName(version: "26.6.2", build: "23G90")diff --git a/VPhoneLaunchpad/Tests/IPSWCacheTests.swift b/VPhoneLaunchpad/Tests/IPSWCacheTests.swiftindex a60f10e2..db5f8261 100644--- a/VPhoneLaunchpad/Tests/IPSWCacheTests.swift+++ b/VPhoneLaunchpad/Tests/IPSWCacheTests.swift@@ -39,6 +39,11 @@ struct IPSWCacheTests {expect(pad?.productTypes == ["iPad16,1", "iPad16,2"], "\(String(describing: pad?.productTypes))")expect(pad?.kind == .iPad && pad?.title == "iPadOS 26.6.2 (23G90)", "iPad title")+ let tv = VPhoneLaunchpadIPSW(fileName: "AppleTV5,3_26.4_23L243_Restore.ipsw")+ expect(tv?.productTypes == ["AppleTV5,3"], "TV product type")+ expect(tv?.kind == .appleTV && tv?.title == "tvOS 26.4 (23L243)", "TV title")+ expect(VPhoneLaunchpadIPSWRows.kindLabel(.appleTV) == "Apple TV", "TV family label")+let cachedPad = VPhoneLaunchpadIPSW(fileName: "iPad16_1_iPad16_2_26.6.2_23G90_Restore-0123456789ab.ipsw")expect(cachedPad?.productTypes == ["iPad16,1", "iPad16,2"], "\(String(describing: cachedPad?.productTypes))")diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSW.swift b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSW.swiftindex 8176262c..e0269c6f 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSW.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSW.swift@@ -9,13 +9,14 @@ import Foundation/// manifest cannot be read.nonisolated struct VPhoneLaunchpadIPSW: Hashable, Sendable {enum Kind: Hashable, Sendable {- case iPhone, iPad, cloudOS, unknown+ case iPhone, iPad, appleTV, cloudOS, unknown/// The system the IPSW installs: the first word of its title.var systemName: String? {switch self {case .iPhone: "iOS"case .iPad: "iPadOS"+ case .appleTV: "tvOS"case .cloudOS: "cloudOS"case .unknown: nil}@@ -46,6 +47,9 @@ nonisolated struct VPhoneLaunchpadIPSW: Hashable, Sendable {if productTypes.contains(where: { $0.hasPrefix("iPhone") }) {return .iPhone}+ if productTypes.contains(where: { $0.hasPrefix("AppleTV") }) {+ return .appleTV+ }return .unknown}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWRows.swift b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWRows.swiftindex 0310b051..e371d907 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWRows.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/IPSWCache/VPhoneLaunchpadIPSWRows.swift@@ -136,8 +136,9 @@ nonisolated enum VPhoneLaunchpadIPSWRows {switch kind {case .iPhone: 0case .iPad: 1- case .cloudOS: 2- case .unknown: 3+ case .appleTV: 2+ case .cloudOS: 3+ case .unknown: 4}}@@ -157,6 +158,7 @@ nonisolated enum VPhoneLaunchpadIPSWRows {switch kind {case .iPhone: String(localized: "iPhone")case .iPad: String(localized: "iPad")+ case .appleTV: String(localized: "Apple TV")case .cloudOS: String(localized: "cloudOS")case .unknown: String(localized: "Unknown")}