Run a virtual iPhone on an Apple Silicon Mac.
Swift
Run an iPad's OS: iPadOS guests from an iPad restore IPSW
Jacky8a254987ff31
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swiftnew file mode 100644index 00000000..3e07dd58--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift@@ -0,0 +1,258 @@+// DeviceTreeGuestDevicePatches.swift — The iPad presentation of the vphone600 tree.+//+// vphone600ap is a virtual iPhone: `artwork-device-idiom` is "phone", the root+// `model` is iPhone99,11, and most `/product` properties are `syscfg/xxxx`+// placeholders (flag 0x8000) that no syscfg on a VM ever fills. An iPadOS+// userland reads the same nodes, so a guest restored from an iPad IPSW lays+// itself out as a phone unless the tree it boots says otherwise.+//+// The edits below give the installed tree the iPad's own answers, copied from+// that device's `DeviceTree.<board>.im4p` in the same IPSW:+//+// - `/product` placeholders the iPad carries get its values; the phone-only+// placeholders it does not carry (Dynamic Island, reachability, ringer,+// volume-button geometry, CarPlay, Watch pairing...) are removed, which is+// what "absent" means to MobileGestalt.+// - The iPad-only multitasking capabilities are added.+// - The root and `/product` identity becomes the iPad's, with VPHONE600AP kept+// second in `compatible` so the platform expert still binds.+//+// What stays vphone600: everything that describes the virtual hardware —+// `graphics-featureset-class` (the paravirtual GPU is APPLE7, not the A17's+// APPLE9), `framebuffer-identifier`, `has-virtualization`, the guest agent port,+// memory class and boot flags.+//+// Only the installed tree carries these. Restore boots `RestoreDeviceTree`,+// which keeps the iPhone99,11 identity `restored_external` checks against the+// manifest; see `FirmwareManifest.separateGuestDeviceTree`.++import Foundation+import VPhoneCoreKit+import VPhonePatchKit++extension DeviceTreePatcher {+ // MARK: - Role++ /// Which of the VM's device trees a patcher is rewriting.+ public enum TreeRole: Sendable {+ /// The one file an iPhone guest restores and boots with.+ case shared+ /// An iPad guest's `RestoreDeviceTree`: patched exactly as an iPhone+ /// guest's tree, so restore sees the board it always has.+ case restore+ /// An iPad guest's installed `DeviceTree`, which carries its identity.+ case installed+ }++ // MARK: - Patch IDs++ static let iPadArtworkPatch = "devicetree-cfw-ipad_artwork"+ static let iPadProductPatch = "devicetree-cfw-ipad_product"+ static let iPadButtonsPatch = "devicetree-cfw-ipad_buttons"+ static let iPadIdentityPatch = "devicetree-cfw-ipad_identity"++ // MARK: - Edits++ /// One change to an existing node: a property set (added when missing) or+ /// removed.+ struct GuestEdit {+ enum Action {+ case set(PropertyValue)+ /// A present-or-absent boolean, stored with no value.+ case setEmpty+ case remove+ }++ let nodePath: [String]+ let property: String+ let action: Action+ let patchID: String+ }++ /// The edits that make the vphone600 tree present `device`.+ static func guestEdits(for device: VPhoneGuestDevice) -> [GuestEdit] {+ guard device.isPad else { return [] }+ let product = ["device-tree", "product"]+ var edits: [GuestEdit] = []++ // Idiom and artwork: what UIKit and SpringBoard lay out against.+ edits.append(GuestEdit(nodePath: product, property: "artwork-device-idiom",+ action: .set(.string(device.artworkIdiom)), patchID: iPadArtworkPatch))+ edits.append(GuestEdit(nodePath: product, property: "artwork-device-subtype",+ action: .set(.integer(device.artworkSubtype)), patchID: iPadArtworkPatch))+ edits.append(GuestEdit(nodePath: product, property: "artwork-scale-factor",+ action: .set(.integer(device.artworkScale)), patchID: iPadArtworkPatch))++ // The rest of `/product`, as the device's own tree has it.+ for (name, value) in productProperties(for: device) {+ let action: GuestEdit.Action = switch value {+ case .none: .setEmpty+ case let .some(value): .set(value)+ }+ edits.append(GuestEdit(nodePath: product, property: name, action: action, patchID: iPadProductPatch))+ }+ for name in iPhoneOnlyProductProperties {+ edits.append(GuestEdit(nodePath: product, property: name, action: .remove, patchID: iPadProductPatch))+ }++ // An iPad has no ring/silent switch.+ edits.append(GuestEdit(nodePath: ["device-tree", "buttons"], property: "function-button_ringeren",+ action: .remove, patchID: iPadButtonsPatch))++ // Identity: the product type MobileGestalt derives the device class from.+ let root = ["device-tree"]+ edits.append(GuestEdit(nodePath: root, property: "model",+ action: .set(.string(device.productType)), patchID: iPadIdentityPatch))+ edits.append(GuestEdit(nodePath: root, property: "target-type",+ action: .set(.string(device.targetType)), patchID: iPadIdentityPatch))+ edits.append(GuestEdit(nodePath: root, property: "target-sub-type",+ action: .set(.string(device.uniqueModel)), patchID: iPadIdentityPatch))+ edits.append(GuestEdit(nodePath: root, property: "compatible",+ action: .set(.bytes(compatible(for: device))), patchID: iPadIdentityPatch))+ edits.append(GuestEdit(nodePath: product, property: "fdr-product-type",+ action: .set(.string(device.productType)), patchID: iPadIdentityPatch))+ edits.append(GuestEdit(nodePath: product, property: "sub-product-type",+ action: .set(.string(device.productType)), patchID: iPadIdentityPatch))+ edits.append(GuestEdit(nodePath: product, property: "unique-model",+ action: .set(.string(device.uniqueModel)), patchID: iPadIdentityPatch))+ return edits+ }++ /// `compatible` with the device's board first, so `hw.model` reads it, and+ /// VPHONE600AP kept for the platform expert's AppleVMApple1IO match.+ static func compatible(for device: VPhoneGuestDevice) -> Data {+ Data("\(device.uniqueModel)\0VPHONE600AP\0AppleVirtualPlatformARM\0".utf8)+ }++ /// vphone600 `/product` placeholders a real iPad does not carry. Left in,+ /// an unresolved placeholder would read as present.+ static let iPhoneOnlyProductProperties = [+ "island-notch-location",+ "large-format-phone",+ "ui-reachability",+ "oled-display",+ "siri-gesture",+ "hme-in-arkit",+ "location-reminders",+ "volume-up-button-location",+ "volume-down-button-location",+ "watch-companion",+ "carplay-2",+ "car-integration",+ ]++ /// `/product` values copied from the device's own tree. A nil value is a+ /// present-or-absent boolean.+ static func productProperties(for device: VPhoneGuestDevice) -> [(String, PropertyValue?)] {+ switch device.productType {+ case VPhoneGuestDevice.iPad16_1.productType: j410Product+ default: []+ }+ }++ /// iPad mini (A17 Pro), `DeviceTree.j410ap.im4p` from iPadOS 26.6.2 (23G90).+ static let j410Product: [(String, PropertyValue?)] = [+ ("product-name", .string("iPad mini (A17 Pro)")),+ ("product-description", .string("iPad mini (A17 Pro)")),+ ("chrome-identifier", .string("com.apple.dt.devicekit.chrome.tablet3")),+ ("compatible-device-fallback", .string("iPad14,1")),+ ("display-corner-radius", .bytes(Data([0x2B, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00]))),+ ("display-mirroring", .integer(1)),+ ("side-button-location", .bytes(Data([+ 0x60, 0xC5, 0x01, 0x00, 0x6C, 0xB2, 0x02, 0x00, 0x49, 0x0D,+ 0x00, 0x00, 0x78, 0x42, 0x00, 0x00, 0xE8, 0x03, 0x00, 0x00,+ ]))),+ ("front-cam-offset-from-center", .bytes(Data([+ 0x64, 0x6D, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x12,+ 0x00, 0x00, 0xE8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ ]))),+ ("rear-cam-offset-from-center", .bytes(Data([+ 0x1E, 0x4C, 0x01, 0x00, 0x99, 0xD5, 0x00, 0x00, 0x71, 0x0C,+ 0x00, 0x00, 0xE8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ ]))),+ ("thin-bezel", .integer(1)),+ ("ui-pip", nil),+ ("ui-background-quality", .integer(100)),+ ("ui-weather-quality", .integer(100)),+ ("assistant", .integer(1)),+ ("dictation", .integer(1)),+ ("offline-dictation", .integer(1)),+ ("builtin-mics", .integer(2)),+ // iPad multitasking: Slide Over, the overlay and pinned app slots.+ ("medusa-overlay-app-capability", .integer(1)),+ ("ui-floating-live-app", nil),+ ("ui-overlay-app", nil),+ ("ui-pinned-app", nil),+ // The iPad mini has no Stage Manager.+ ("disable-chamois", .integer(1)),+ ("natural-volume-arrangement", nil),+ ]++ // MARK: - Application++ /// Applies `guestEdits(for:)` to the parsed tree and records each change.+ func applyGuestEdits(root: DTNode) throws {+ for edit in Self.guestEdits(for: device) {+ guard gateAllows(edit.patchID) else { continue }+ let node = try resolveNode(root, path: edit.nodePath)+ let index = node.properties.firstIndex { $0.name == edit.property }+ let before = index.map { node.properties[$0].value } ?? Data()++ let after: Data?+ switch edit.action {+ case .remove:+ guard let index else { continue }+ node.properties.remove(at: index)+ after = nil+ case .setEmpty:+ after = Data()+ case let .set(value):+ after = try Self.encode(value)+ }++ if let after {+ if let index {+ let property = node.properties[index]+ guard property.value != after || property.flags != 0 else { continue }+ property.value = after+ property.flags = 0+ } else {+ node.properties.append(DTProperty(name: edit.property, flags: 0, value: after, valueOffset: 0))+ }+ }++ let path = (edit.nodePath + [edit.property]).joined(separator: "/")+ let description = switch edit.action {+ case .remove: "Remove \(path) (not on \(device.productType))"+ case .setEmpty, .set: "Set \(path) for \(device.productType)"+ }+ patches.append(PatchRecord(+ patchID: edit.patchID,+ component: component,+ fileOffset: 0,+ virtualAddress: nil,+ originalBytes: before,+ patchedBytes: after ?? Data(),+ description: description,+ ))+ if verbose {+ print(" \(after == nil ? "-prop " : "=prop "): /\(path) \(before.hex) → \((after ?? Data()).hex) [\(edit.patchID)]")+ }+ }+ }++ /// A value at its natural size: a NUL-terminated string, a 32-bit integer.+ private static func encode(_ value: PropertyValue) throws -> Data {+ switch value {+ case let .string(text):+ var data = Data(text.utf8)+ data.append(0)+ return data+ case let .integer(number):+ var little = UInt32(truncatingIfNeeded: number).littleEndian+ return Data(bytes: &little, count: 4)+ case let .bytes(data):+ return data+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swiftindex 2892b089..4e23b739 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift@@ -9,6 +9,7 @@// 3. Serialize the modified tree back to flat binary.import Foundation+import VPhoneCoreKitimport VPhonePatchKit/// Patcher for DeviceTree payloads.@@ -24,6 +25,13 @@ public final class DeviceTreePatcher: BufferedPatcher {/// public JB and the historical internal EXP variant.let includeIdentityPatches: Bool+ /// The device whose OS the guest runs, and which of its trees this is.+ /// An iPhone guest has one `.shared` tree; an iPad guest boots its+ /// `.installed` tree and restores with a `.restore` one. See+ /// DeviceTreeGuestDevicePatches.swift.+ let device: VPhoneGuestDevice+ let role: TreeRole+let buffer: BinaryBuffervar patches: [PatchRecord] = []var rebuiltData: Data?@@ -58,10 +66,18 @@ public final class DeviceTreePatcher: BufferedPatcher {// MARK: - Init- public init(data: Data, verbose: Bool = true, includeIdentityPatches: Bool = false) {+ public init(+ data: Data,+ verbose: Bool = true,+ includeIdentityPatches: Bool = false,+ device: VPhoneGuestDevice = .default,+ role: TreeRole = .shared,+ ) {buffer = BinaryBuffer(data)self.verbose = verboseself.includeIdentityPatches = includeIdentityPatches+ self.device = device+ self.role = role}// MARK: - Patcher@@ -224,7 +240,7 @@ public final class DeviceTreePatcher: BufferedPatcher {}/// Resolve a node path like ["device-tree", "buttons"] from the root.- private func resolveNode(_ root: DTNode, path: [String]) throws -> DTNode {+ func resolveNode(_ root: DTNode, path: [String]) throws -> DTNode {guard !path.isEmpty, path[0] == "device-tree" else {throw PatcherError.patchSiteNotFound("DeviceTree: invalid node path \(path)")}@@ -303,6 +319,12 @@ public final class DeviceTreePatcher: BufferedPatcher {if includeIdentityPatches {patchesToApply.append(contentsOf: Self.identityPropertyPatches)}+ // An iPad's installed tree takes its artwork, notch and camera geometry+ // from the iPad edits, and none of the iPhone17,3 identity.+ let presentsGuest = device.isPad && role == .installed+ if presentsGuest {+ patchesToApply.removeAll { !Self.deviceNeutralPatches.contains($0.patchID) }+ }for patch in patchesToApply {// Before the property is rewritten, not after: the tree is serialised// from these nodes, so a skipped record with a mutated node would@@ -353,8 +375,19 @@ public final class DeviceTreePatcher: BufferedPatcher {try applyNodeAddition(root: root, patch: nodeAdd)}}++ if presentsGuest {+ try applyGuestEdits(root: root)+ }}+ /// Property patches that describe the virtual board rather than a phone,+ /// and so apply to an iPad's installed tree as well.+ static let deviceNeutralPatches: Set<String> = [+ "devicetree-cfw-serial_number",+ "devicetree-cfw-home_button_type",+ ]+/// Apply a single `AddChildNodePatch`: construct the new `DTNode`,/// fill its `name` + caller-supplied properties, attach to the/// parent's `children`, and record a `PatchRecord` for the change.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swiftindex f9cb2b9a..53c3e0e2 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift@@ -7,6 +7,7 @@// Build Identity.import Foundation+import VPhoneCoreKit// MARK: - Plist type aliases@@ -69,15 +70,17 @@ public enum FirmwareManifest {throw ManifestError.missingKey("BuildIdentities in iPhone BuildManifest")}- // Discover source identities.+ // Discover source identities. An iPad IPSW carries one erase identity+ // per board it covers, so the userland one is picked by board.+ let device = VPhoneGuestDevice.detect(buildManifest: iPhoneBM) ?? .defaultlet (prod, res) = try findCloudOS(cloudIdentities, deviceClass: "vresearch101ap")let (vp, vpr) = try findCloudOS(cloudIdentities, deviceClass: "vphone600ap")- let iErase = try findIPhoneErase(iPhoneIdentities)+ let iErase = try findIPhoneErase(iPhoneIdentities, deviceClass: device.deviceClass)if verbose {print(" cloudOS vresearch101ap: release=#\(prod), research=#\(res)")print(" cloudOS vphone600ap: release=#\(vp), research=#\(vpr)")- print(" iPhone erase: #\(iErase)")+ print(" \(device.productType) erase: #\(iErase)")}// Build the single DFU erase identity.@@ -90,10 +93,16 @@ public enum FirmwareManifest {vpr: vpr,iErase: iErase,)+ let guestIdentity = try separateGuestDeviceTree(+ for: device,+ identity: buildIdentity,+ restoreDir: iPhoneDir,+ verbose: verbose,+ )// Assemble BuildManifest.let buildManifest: PlistDict = [- "BuildIdentities": [buildIdentity],+ "BuildIdentities": [guestIdentity],"ManifestVersion": cloudOSBM["ManifestVersion"] as Any,"ProductBuildVersion": cloudOSBM["ProductBuildVersion"] as Any,"ProductVersion": cloudOSBM["ProductVersion"] as Any,@@ -104,6 +113,7 @@ public enum FirmwareManifest {let restore = try buildRestorePlist(cloudOSRP: cloudOSRP,iPhoneRP: iPhoneRP,+ boardConfig: device.deviceClass,)// Write output.@@ -166,17 +176,80 @@ public enum FirmwareManifest {}/// Return the index of the first iPhone erase identity.- static func findIPhoneErase(_ identities: [PlistDict]) throws -> Int {+ ///+ /// With `deviceClass`, an erase identity for that board wins; the first+ /// erase identity of any board is the fallback, which is all a single-board+ /// iPhone manifest has.+ static func findIPhoneErase(_ identities: [PlistDict], deviceClass: String? = nil) throws -> Int {+ var first: Int?for (i, bi) in identities.enumerated() {- let variant = ((bi["Info"] as? PlistDict)?["Variant"] as? String ?? "").lowercased()- if !variant.contains("research"),- !variant.contains("upgrade"),- !variant.contains("recovery")- {+ let info = bi["Info"] as? PlistDict+ let variant = (info?["Variant"] as? String ?? "").lowercased()+ guard !variant.contains("research"),+ !variant.contains("upgrade"),+ !variant.contains("recovery")+ else { continue }+ let board = (info?["DeviceClass"] as? String ?? "").lowercased()+ if let deviceClass, board == deviceClass.lowercased() {return i}+ first = first ?? i+ }+ guard let first else {+ throw ManifestError.identityNotFound("erase identity in the iPhone BuildManifest")+ }+ return first+ }++ // MARK: - Guest Device Tree++ /// Where an iPad guest's installed device tree is kept, beside the+ /// vphone600 one that restore boots with.+ public static let guestDeviceTreePath = "Firmware/all_flash/DeviceTree.vphone600ap.guest.im4p"++ /// Points an iPad identity's installed `DeviceTree` at a copy of the+ /// vphone600 tree, so `fw patch` can give that copy the iPad identity.+ ///+ /// The DFU device restores with `RestoreDeviceTree`, and `restored_external`+ /// checks its root `model` and `target-type` against the manifest — the+ /// reason the iPhone identity is only rewritten after restore. The+ /// installed `DeviceTree` is a separate manifest entry that restore only+ /// personalizes and writes to Preboot, so giving it its own file lets the+ /// iPad identity ride through restore without a root-only rewrite on the+ /// host. An iPhone identity is returned unchanged.+ static func separateGuestDeviceTree(+ for device: VPhoneGuestDevice,+ identity: PlistDict,+ restoreDir: URL,+ verbose: Bool,+ ) throws -> PlistDict {+ guard device.isPad else { return identity }+ guard var manifest = identity["Manifest"] as? PlistDict,+ var deviceTree = manifest["DeviceTree"] as? PlistDict,+ var info = deviceTree["Info"] as? PlistDict,+ let path = info["Path"] as? String+ else {+ throw ManifestError.missingKey("DeviceTree in the hybrid build identity")+ }+ let fm = FileManager.default+ let source = restoreDir.appending(path: path)+ let destination = restoreDir.appending(path: guestDeviceTreePath)+ guard fm.fileExists(atPath: source.path) else {+ throw ManifestError.fileNotFound(source.path)+ }+ if fm.fileExists(atPath: destination.path) {+ try fm.removeItem(at: destination)+ }+ try fm.copyItem(at: source, to: destination)+ info["Path"] = guestDeviceTreePath+ deviceTree["Info"] = info+ manifest["DeviceTree"] = deviceTree+ var separated = identity+ separated["Manifest"] = manifest+ if verbose {+ print(" \(device.productType): installed DeviceTree -> \(guestDeviceTreePath)")}- throw ManifestError.identityNotFound("erase identity in the iPhone BuildManifest")+ return separated}// MARK: - Build Identity Construction@@ -296,6 +369,7 @@ public enum FirmwareManifest {static func buildRestorePlist(cloudOSRP: PlistDict,iPhoneRP: PlistDict,+ boardConfig: String? = nil,) throws -> PlistDict {// DeviceMap: iPhone first entry + cloudOS vphone600ap/vresearch101ap entries.guard let iPhoneDeviceMap = iPhoneRP["DeviceMap"] as? [PlistDict],@@ -307,7 +381,11 @@ public enum FirmwareManifest {throw ManifestError.missingKey("DeviceMap in cloudOS Restore.plist")}- var deviceMap: [PlistDict] = [iPhoneDeviceMap[0]]+ // A multi-board iPad IPSW lists one entry per board; keep the guest's.+ let guestEntry = iPhoneDeviceMap.first {+ ($0["BoardConfig"] as? String)?.lowercased() == boardConfig?.lowercased()+ } ?? iPhoneDeviceMap[0]+ var deviceMap: [PlistDict] = [guestEntry]for d in cloudDeviceMap {if let bc = d["BoardConfig"] as? String,bc == "vphone600ap" || bc == "vresearch101ap"diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swiftindex 12646737..057d85e2 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift@@ -1,5 +1,8 @@// FirmwareDeviceTreePatchSet.swift — Manifest for the device tree.//+// An iPad guest's installed tree takes the `ipad_*` entries in place of the+// board presentation, camera geometry and identity ones.+//// Two kinds of entry. The first four properties make the research board present// as a phone the guest's own UI can lay out. The rest give it the iPhone17,3// identity and the camera, audio and SMC nodes that identity implies, which is@@ -162,6 +165,32 @@ public enum FirmwareDeviceTreePatchSet {"ISP RTB camera flags","Sets the ISP round-trip buffer flags for the camera pipeline.",),++ // MARK: iPad Guest+ //+ // Written only to an iPad guest's installed tree (an iPhone guest+ // never produces these records). See DeviceTreeGuestDevicePatches.swift.++ property(+ "devicetree-cfw-ipad_artwork",+ "iPad artwork",+ "Gives an iPad guest the pad idiom, its panel subtype and 2x scale.",+ ),+ property(+ "devicetree-cfw-ipad_product",+ "iPad product properties",+ "Fills the product properties an iPad carries and removes the phone-only ones.",+ ),+ property(+ "devicetree-cfw-ipad_buttons",+ "iPad buttons",+ "Removes the ring/silent switch an iPad does not have.",+ ),+ property(+ "devicetree-cfw-ipad_identity",+ "iPad identity",+ "Reports the iPad's product type and board, so the guest runs as an iPad.",+ ),],provides: ["vphone.devicetree"],)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swiftindex 74e92386..0733c811 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift@@ -7,6 +7,7 @@// Split out of FirmwarePipeline.swift; the execution loop stays there.import Foundation+import VPhoneCoreKitimport VPhonePatchKitextension FirmwarePipeline {@@ -234,7 +235,11 @@ extension FirmwarePipeline {// 7. DeviceTree — JB includes the former EXP identity and camera// properties so the guest presents a consistent iPhone17,3 identity.+ // An iPad guest restores with this tree and boots its own copy (7b).let dtIncludeIdentity = variant == .jb || variant == .exp+ let guestDevice = Self.readGuestDevice(restoreDir)+ let guestTreeURL = restoreDir.appending(path: FirmwareManifest.guestDeviceTreePath)+ let hasGuestTree = guestDevice.isPad && FileManager.default.fileExists(atPath: guestTreeURL.path)components.append(ComponentDescriptor(name: "DeviceTree",inRestoreDir: true,@@ -244,12 +249,35 @@ extension FirmwarePipeline {data: data,verbose: verbose,includeIdentityPatches: dtIncludeIdentity,+ device: guestDevice,+ role: hasGuestTree ? .restore : .shared,)p.gate = gatereturn p}] : [],))+ // 7b. The iPad's installed DeviceTree, which `fw prepare` split off so it+ // can carry the iPad identity through restore.+ if hasGuestTree {+ components.append(ComponentDescriptor(+ name: "GuestDeviceTree",+ inRestoreDir: true,+ searchPatterns: [FirmwareManifest.guestDeviceTreePath],+ patcherFactories: includeDeviceTree ? [{ data, verbose in+ let p = DeviceTreePatcher(+ data: data,+ verbose: verbose,+ includeIdentityPatches: dtIncludeIdentity,+ device: guestDevice,+ role: .installed,+ )+ p.gate = gate+ return p+ }] : [],+ ))+ }+// 8. Filesystem// Not restorable: it reads BuildManifest.plist but writes cryptex images// all over the restore tree, so putting the manifest back on its owndiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swiftindex 533c0503..9162b6d3 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift@@ -11,6 +11,7 @@import Darwinimport Foundation+import VPhoneCoreKitimport VPhonePatchKitextension FirmwarePipeline {@@ -50,6 +51,13 @@ extension FirmwarePipeline {readProductVersion(restoreDir, manifest: "iPhone-BuildManifest.plist")}+ /// The device whose IPSW supplied the guest OS, from the same preserved+ /// manifest. iPhone17,3 when it names no known device.+ static func readGuestDevice(_ restoreDir: URL) -> VPhoneGuestDevice {+ VPhoneGuestDevice.detect(buildManifestAt: restoreDir.appendingPathComponent("iPhone-BuildManifest.plist"))+ ?? .default+ }+/// cloudOS/kernel version (the live `BuildManifest.plist`).static func readCloudOSProductVersion(_ restoreDir: URL) -> String? {readProductVersion(restoreDir, manifest: "BuildManifest.plist")diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swiftnew file mode 100644index 00000000..42cb43fc--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift@@ -0,0 +1,225 @@+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhoneCoreKit++/// The iPad presentation of the vphone600 device tree, against a small tree+/// shaped like the shipped one: the root identity, a `/product` node with+/// `syscfg/` placeholders (flag 0x8000) and a `/buttons` node.+@Suite("Device tree guest device")+struct DeviceTreeGuestDeviceTests {+ // MARK: - Fixture++ struct Property {+ let name: String+ let flags: UInt16+ let value: Data++ static func string(_ name: String, _ text: String, flags: UInt16 = 0) -> Property {+ Property(name: name, flags: flags, value: Data((text + "\0").utf8))+ }++ static func integer(_ name: String, _ number: UInt32) -> Property {+ var little = number.littleEndian+ return Property(name: name, flags: 0, value: Data(bytes: &little, count: 4))+ }++ static func placeholder(_ name: String, _ key: String) -> Property {+ .string(name, "syscfg/\(key)", flags: 0x8000)+ }+ }++ struct Node {+ let properties: [Property]+ let children: [Node]++ func serialized() -> Data {+ var out = Data()+ out.append(littleEndian: UInt32(properties.count))+ out.append(littleEndian: UInt32(children.count))+ for property in properties {+ var name = Data(property.name.utf8)+ name.append(contentsOf: [UInt8](repeating: 0, count: 32 - name.count))+ out.append(name)+ out.append(littleEndian: UInt16(property.value.count))+ out.append(littleEndian: property.flags)+ out.append(property.value)+ let pad = (4 - property.value.count % 4) % 4+ out.append(contentsOf: [UInt8](repeating: 0, count: pad))+ }+ for child in children {+ out.append(child.serialized())+ }+ return out+ }+ }++ static let tree = Node(+ properties: [+ .string("name", "device-tree"),+ .string("model", "iPhone99,11"),+ .string("target-type", "VPHONE600"),+ .string("target-sub-type", "VPHONE600AP"),+ Property(name: "compatible", flags: 0, value: Data("VPHONE600AP\0iPhone99,11\0AppleVirtualPlatformARM\0".utf8)),+ .string("serial-number", "syscfg/SrNm"),+ ],+ children: [+ Node(+ properties: [+ .string("name", "product"),+ .string("artwork-device-idiom", "phone"),+ .placeholder("artwork-device-subtype", "ards"),+ .placeholder("artwork-scale-factor", "arsf"),+ .placeholder("island-notch-location", "isnl"),+ .placeholder("ui-pip", "uipi"),+ .placeholder("product-name", "prde"),+ .integer("car-integration", 1),+ .string("fdr-product-type", "iPhone99,11"),+ .string("sub-product-type", "iPhone99,11"),+ .string("unique-model", "VPHONE600AP"),+ .string("graphics-featureset-class", "APPLE7"),+ ],+ children: [],+ ),+ Node(+ properties: [+ .string("name", "buttons"),+ .placeholder("home-button-type", "home"),+ .placeholder("function-button_ringeren", "rgen"),+ ],+ children: [],+ ),+ ],+ )++ // MARK: - Reading the result++ /// `node -> property -> (flags, value)` for the two levels the fixture has.+ static func read(_ data: Data) -> [String: [String: (UInt16, Data)]] {+ var result: [String: [String: (UInt16, Data)]] = [:]+ func node(at offset: Int, path: String) -> Int {+ let propertyCount = Int(data.loadLE(UInt32.self, at: offset))+ let childCount = Int(data.loadLE(UInt32.self, at: offset + 4))+ var pos = offset + 8+ var properties: [String: (UInt16, Data)] = [:]+ for _ in 0 ..< propertyCount {+ let nameBytes = data[data.startIndex + pos ..< data.startIndex + pos + 32].prefix { $0 != 0 }+ let name = String(decoding: nameBytes, as: UTF8.self)+ let length = Int(data.loadLE(UInt16.self, at: pos + 32))+ let flags = data.loadLE(UInt16.self, at: pos + 34)+ let start = data.startIndex + pos + 36+ properties[name] = (flags, Data(data[start ..< start + length]))+ pos += 36 + ((length + 3) & ~3)+ }+ let ownName = properties["name"].map { String(decoding: $0.1.prefix { $0 != 0 }, as: UTF8.self) } ?? ""+ let here = path.isEmpty ? ownName : "\(path)/\(ownName)"+ result[here] = properties+ for _ in 0 ..< childCount {+ pos = node(at: pos, path: here)+ }+ return pos+ }+ _ = node(at: 0, path: "")+ return result+ }++ static func string(_ value: (UInt16, Data)?) -> String? {+ value.map { String(decoding: $0.1.prefix { $0 != 0 }, as: UTF8.self) }+ }++ static func integer(_ value: (UInt16, Data)?) -> UInt32? {+ guard let value, value.1.count == 4 else { return nil }+ return value.1.loadLE(UInt32.self, at: 0)+ }++ static func patch(device: VPhoneGuestDevice, role: DeviceTreePatcher.TreeRole) throws -> [String: [String: (UInt16, Data)]] {+ let patcher = DeviceTreePatcher(+ data: tree.serialized(),+ verbose: false,+ includeIdentityPatches: false,+ device: device,+ role: role,+ )+ _ = try patcher.findAll()+ return read(patcher.patchedData)+ }++ // MARK: - Tests++ @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"])+ let product = try #require(tree["device-tree/product"])+ let buttons = try #require(tree["device-tree/buttons"])++ #expect(Self.string(root["model"]) == "iPad16,1")+ #expect(Self.string(root["target-type"]) == "J410")+ #expect(Self.string(root["target-sub-type"]) == "J410AP")+ #expect(root["compatible"]?.1 == Data("J410AP\0VPHONE600AP\0AppleVirtualPlatformARM\0".utf8))++ #expect(Self.string(product["artwork-device-idiom"]) == "pad")+ #expect(Self.integer(product["artwork-device-subtype"]) == 2266)+ #expect(Self.integer(product["artwork-scale-factor"]) == 2)+ #expect(product["artwork-scale-factor"]?.0 == 0, "a filled placeholder loses its flag")+ #expect(Self.string(product["product-name"]) == "iPad mini (A17 Pro)")+ #expect(Self.string(product["sub-product-type"]) == "iPad16,1")+ #expect(Self.string(product["unique-model"]) == "J410AP")+ #expect(product["ui-pip"].map { $0.1.isEmpty && $0.0 == 0 } == true)+ #expect(product["medusa-overlay-app-capability"] != nil)+ #expect(product["ui-pinned-app"]?.1.isEmpty == true)++ #expect(product["island-notch-location"] == nil)+ #expect(product["car-integration"] == nil)+ #expect(buttons["function-button_ringeren"] == nil)++ // The virtual hardware stays as vphone600 describes it.+ #expect(Self.string(product["graphics-featureset-class"]) == "APPLE7")+ }++ @Test func `an iPad's restore tree keeps the board restore expects`() throws {+ let tree = try Self.patch(device: .iPad16_1, role: .restore)+ let root = try #require(tree["device-tree"])+ let product = try #require(tree["device-tree/product"])+ #expect(Self.string(root["model"]) == "iPhone99,11")+ #expect(Self.string(product["artwork-device-idiom"]) == "phone")+ #expect(product["medusa-overlay-app-capability"] == nil)+ }++ @Test func `an iPhone tree is patched as it always was`() throws {+ let shared = try Self.patch(device: .iPhone17_3, role: .shared)+ let product = try #require(shared["device-tree/product"])+ #expect(Self.integer(product["artwork-device-subtype"]) == 2556)+ #expect(Self.integer(product["island-notch-location"]) == 144)+ #expect(Self.string(product["artwork-device-idiom"]) == "phone")++ // A `.installed` role means nothing without an iPad.+ let installed = try Self.patch(device: .iPhone17_3, role: .installed)+ #expect(Self.integer(installed["device-tree/product"]?["island-notch-location"]) == 144)+ }++ @Test func `the iPad edits are declared by the device tree patch set`() {+ let declared = Set(FirmwareDeviceTreePatchSet.manifest.patches.map(\.identifier))+ let used = Set(DeviceTreePatcher.guestEdits(for: .iPad16_1).map(\.patchID))+ #expect(!used.isEmpty)+ #expect(used.isSubset(of: declared))+ }++ @Test func `patching an iPad tree twice changes nothing more`() throws {+ let once = DeviceTreePatcher(+ data: Self.tree.serialized(), verbose: false, device: .iPad16_1, role: .installed,+ )+ _ = try once.findAll()+ let twice = DeviceTreePatcher(+ data: once.patchedData, verbose: false, device: .iPad16_1, role: .installed,+ )+ _ = try twice.findAll()+ #expect(twice.patchedData == once.patchedData)+ }+}++private extension Data {+ mutating func append<T: FixedWidthInteger>(littleEndian value: T) {+ var little = value.littleEndian+ Swift.withUnsafeBytes(of: &little) { append(contentsOf: $0) }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwareManifestSelectionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwareManifestSelectionTests.swiftindex 4766176f..f41a6743 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwareManifestSelectionTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/FirmwareManifestSelectionTests.swift@@ -154,4 +154,24 @@ struct FirmwareManifestSelectionTests {try FirmwareManifest.findIPhoneErase(identities)}}++ @Test+ func `a multi-board iPad manifest yields the guest board's erase identity`() throws {+ let identities = [+ Self.identity(deviceClass: "j411ap", variant: "Customer Erase Install (IPSW)"),+ Self.identity(deviceClass: "j411ap", variant: "Customer Upgrade Install (IPSW)"),+ Self.identity(deviceClass: "J410AP", variant: "Customer Erase Install (IPSW)"),+ Self.identity(deviceClass: "j410ap", variant: "Customer Upgrade Install (IPSW)"),+ ]+ #expect(try FirmwareManifest.findIPhoneErase(identities, deviceClass: "j410ap") == 2)+ }++ @Test+ func `an unknown board falls back to the first erase identity`() throws {+ let identities = [+ Self.identity(deviceClass: "d47ap", variant: "Customer Upgrade Install (IPSW)"),+ Self.identity(deviceClass: "d47ap", variant: "Customer Erase Install (IPSW)"),+ ]+ #expect(try FirmwareManifest.findIPhoneErase(identities, deviceClass: "j410ap") == 1)+ }}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 5ff5fc0e..4d61fb62 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -274,7 +274,7 @@ struct VPhoneCustomFirmwareInstaller {// VM an environment update is allowed to run against — this run creates// no new snapshot to flip.if mode == .full {- try patchPreboot(volumes: volumes, work: work, plan: plan)+ try patchPreboot(volumes: volumes, work: work, plan: plan, guestDevice: guestDevice(of: restore))}_ = try tool("/sbin/umount", [data.path])dataMounted = false@@ -973,15 +973,28 @@ struct VPhoneCustomFirmwareInstaller {// MARK: - Preboot+ /// The device whose IPSW the restore tree was prepared from.+ private func guestDevice(of restore: VPhoneConfinedDirectory?) -> VPhoneGuestDevice {+ guard let data = try? restore?.readData("iPhone-BuildManifest.plist"),+ let manifest = (try? PropertyListSerialization.propertyList(from: data, format: nil)) as? [String: Any]+ else { return .default }+ return VPhoneGuestDevice.detect(buildManifest: manifest) ?? .default+ }+private func patchPreboot(volumes: [[String: Any]],work: WorkDirectory,plan: VPhoneVirtualMachinePatchPlan?,+ guestDevice: VPhoneGuestDevice,) throws {- // Like every guest patch, a VM with no plan still gets it.+ // Like every guest patch, a VM with no plan still gets it — except on an+ // iPad guest, whose installed tree already carries its own identity+ // from `fw patch`; the rewrite would turn it back into an iPhone17,3.let identity = FirmwareGuestIdentityPatchSet.prebootDeviceTreeIdentity- let rewriteIdentity = plan?.isEnabled(identity) ?? true- if let plan, !rewriteIdentity {+ let rewriteIdentity = !guestDevice.isPad && (plan?.isEnabled(identity) ?? true)+ if guestDevice.isPad {+ print(" [·] \(identity): skipped, the device tree already presents \(guestDevice.productType)")+ } else if let plan, !rewriteIdentity {print(" [·] \(identity): off in preset \(plan.presetIdentifier)")}guard rewriteIdentity || !(spoofBuild ?? "").isEmpty else { return }diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swiftindex 8db399f5..9c370048 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift@@ -70,10 +70,11 @@ enum VPhoneFirmwarePreparer {try await VPhoneIPSWCache.resolve(cloudOSSource, in: ipswCacheDirectory)}try VPhoneIPSWCache.checkPair(iPhone: phone, cloudOS: cloud)- try checkIPhoneName(iPhoneSource, archive: phone)- print("[+] iPhone \(phone.version) (\(phone.build)); cloudOS \(cloud.version) (\(cloud.build))")+ let device = VPhoneIPSWCache.guestDevice(for: phone) ?? .default+ try checkIPhoneName(iPhoneSource, archive: phone, device: device)+ print("[+] \(device.productType) \(phone.version) (\(phone.build)); cloudOS \(cloud.version) (\(cloud.build))")- let name = "iPhone17,3_\(phone.version)_\(phone.build)_Restore"+ 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)")let phoneTree = staging.appendingPathComponent(name)@@ -90,7 +91,7 @@ enum VPhoneFirmwarePreparer {try fm.createDirectory(at: phoneTree, withIntermediateDirectories: false)try fm.createDirectory(at: cloudTree, withIntermediateDirectories: false)- print("[*] Extracting iPhone IPSW...")+ print("[*] Extracting \(device.productType) IPSW...")try VPhoneArchiveExtractor.extract(phone.file, into: phoneTree, options: .intoHostDirectory)print("[*] Extracting cloudOS IPSW...")try VPhoneArchiveExtractor.extract(cloud.file, into: cloudTree, options: .intoHostDirectory)@@ -145,6 +146,23 @@ enum VPhoneFirmwarePreparer {guard !fm.fileExists(atPath: destination.path) else { throw Error.existingRestore(destination) }try fm.moveItem(at: phoneTree, to: destination)print("[+] Restore tree ready: \(destination.path)")+ try recordGuestDevice(device, in: bundle)+ }++ /// Records which device's OS the VM runs, and gives it that device's+ /// display. `fw patch` reads the device back from the restore tree; the+ /// manifest is what the VM window and the guest's screen size follow.+ static func recordGuestDevice(_ device: VPhoneGuestDevice, in bundle: VPhoneBundle) throws {+ let configURL = bundle.url.appendingPathComponent("config.plist")+ guard FileManager.default.fileExists(atPath: configURL.path) else { return }+ let manifest = try VPhoneVirtualMachineManifest.load(from: configURL)+ let updated = manifest.updating(guestDevice: device)+ guard updated.guestProductType != manifest.guestProductType+ || updated.screenConfig != manifest.screenConfig+ else { return }+ try updated.write(to: configURL)+ let screen = updated.screenConfig+ print("[+] Guest device: \(device.productName) (\(device.productType)), display \(screen.width)x\(screen.height) @ \(screen.pixelsPerInch) ppi")}// MARK: - GPU driver cache@@ -189,10 +207,16 @@ enum VPhoneFirmwarePreparer {}}- private static func checkIPhoneName(_ source: String, archive: VPhoneIPSWCache.Archive) throws {+ private static func checkIPhoneName(+ _ source: String,+ archive: VPhoneIPSWCache.Archive,+ device: VPhoneGuestDevice,+ ) throws {let basename = URL(string: source)?.lastPathComponent?? URL(fileURLWithPath: source).lastPathComponent- let pattern = #"^iPhone17,3_([^_]+)_([^_]+)_Restore\.ipsw$"#+ // An iPad IPSW names every model it covers: `iPad16,1,iPad16,2_…`.+ let product = NSRegularExpression.escapedPattern(for: device.productType)+ let pattern = "^(?:[^_/]*,)?" + product + "(?:,[^_/]*)?_([^_]+)_([^_]+)_Restore\\.ipsw$"guard let range = basename.range(of: pattern, options: .regularExpression) else { return }let components = basename[range].split(separator: "_")guard components.count == 4 else { return }diff --git a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swiftindex 9c07d4cb..6649585e 100644--- a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift+++ b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift@@ -37,7 +37,7 @@ public enum VPhoneIPSWCache {case let .swappedSources(iPhone, cloudOS):"The iPhone and cloudOS IPSWs are swapped: \(iPhone.lastPathComponent) is a cloudOS IPSW and \(cloudOS.lastPathComponent) is an iPhone IPSW. Swap the two sources, then try again."case let .notIPhoneSource(file, productTypes):- "\(file.lastPathComponent) is not an \(VPhoneIPSWCache.iPhoneProductType) IPSW; it is for \(productTypes.isEmpty ? "no listed product" : productTypes.joined(separator: ", ")). Choose an \(VPhoneIPSWCache.iPhoneProductType) IPSW as the iPhone source."+ "\(file.lastPathComponent) is not an IPSW vphone can run; it is for \(productTypes.isEmpty ? "no listed product" : productTypes.joined(separator: ", ")). Choose an IPSW for \(VPhoneIPSWCache.guestProductTypes.joined(separator: " or ")) as the iPhone source."case let .notCloudOSSource(file):"\(file.lastPathComponent) is not a cloudOS IPSW: it has no \(VPhoneIPSWCache.cloudOSDeviceClass) build identity. Choose a cloudOS IPSW as the cloudOS source."}@@ -248,14 +248,25 @@ public enum VPhoneIPSWCache {public static let iPhoneProductType = VPhoneFirmwareCatalog.devicepublic static let cloudOSDeviceClass = "vresearch101ap"+ /// Every product whose IPSW can supply the guest OS: the iPhone17,3 the+ /// catalog targets, and the iPads `VPhoneGuestDevice` knows.+ public static var guestProductTypes: [String] {+ VPhoneGuestDevice.known.map(\.productType)+ }++ /// The guest device an IPSW supplies, or nil for any other product.+ public static func guestDevice(for archive: Archive) -> VPhoneGuestDevice? {+ archive.productTypes.lazy.compactMap(VPhoneGuestDevice.named).first+ }+/// Checks each BuildManifest before anything is extracted, so a swapped/// or wrong IPSW fails at once with the fix instead of deep in the merge.public static func checkPair(iPhone: Archive, cloudOS: Archive) throws {- let iPhoneIsPhone = iPhone.productTypes.contains(iPhoneProductType)+ let iPhoneIsPhone = guestDevice(for: iPhone) != nillet cloudOSIsCloudOS = cloudOS.deviceClasses.contains(cloudOSDeviceClass)if !iPhoneIsPhone, !cloudOSIsCloudOS,iPhone.deviceClasses.contains(cloudOSDeviceClass),- cloudOS.productTypes.contains(iPhoneProductType)+ guestDevice(for: cloudOS) != nil{throw Error.swappedSources(iPhone: iPhone.file, cloudOS: cloudOS.file)}diff --git a/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift b/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swiftindex b5cab31f..6d5fae1c 100644--- a/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift+++ b/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift@@ -212,4 +212,25 @@ struct IPSWCacheTests {}}}++ @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)+ defer { try? FileManager.default.removeItem(at: root) }+ let pad = try ipsw(in: root, "pad", productTypes: ["iPad16,1", "iPad16,2"], deviceClasses: ["j410ap", "j411ap"])+ let cloud = try ipsw(in: root, "cloud", productTypes: ["iProd99,1"], deviceClasses: ["vresearch101ap", "vphone600ap"])+ let otherPad = try ipsw(in: root, "other-pad", productTypes: ["iPad13,1"], deviceClasses: ["j307ap"])++ try VPhoneIPSWCache.checkPair(iPhone: pad, cloudOS: cloud)+ #expect(VPhoneIPSWCache.guestDevice(for: pad) == .iPad16_1)+ #expect {+ try VPhoneIPSWCache.checkPair(iPhone: otherPad, cloudOS: cloud)+ } throws: { error in+ if case .notIPhoneSource? = error as? VPhoneIPSWCache.Error {+ true+ } else {+ false+ }+ }+ }}diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swiftnew file mode 100644index 00000000..8f755bea--- /dev/null+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift@@ -0,0 +1,156 @@+import Foundation++// MARK: - Guest Device++/// The Apple device whose restore IPSW supplies the guest's OS image.+///+/// The boot chain, kernel, SEP and device tree always come from the PCC+/// `vresearch101ap` / `vphone600ap` identities. Only the userland changes with+/// the device: an iPhone17,3 IPSW gives the guest iOS, an iPad IPSW gives it+/// iPadOS. The device tree then has to present the matching idiom, artwork+/// and product type, or the iPadOS userland lays itself out as a phone.+///+/// Values are copied from each device's own `DeviceTree.<board>.im4p`.+public struct VPhoneGuestDevice: Sendable, Equatable {+ public enum Family: String, Codable, Sendable {+ case iPhone+ case iPad+ }++ public let family: Family+ /// `Ap,ProductType`, e.g. `iPad16,1`.+ public let productType: String+ /// BuildManifest `DeviceClass`, e.g. `j410ap`.+ public let deviceClass: String+ /// Root `target-type`, e.g. `J410`.+ public let targetType: String+ /// Root `target-sub-type` and `/product/unique-model`, e.g. `J410AP`.+ public let uniqueModel: String+ /// `/product/product-name` and `product-description`.+ public let productName: String+ /// `/product/artwork-device-idiom`: `phone` or `pad`.+ public let artworkIdiom: String+ /// `/product/artwork-device-subtype`: the panel height class.+ public let artworkSubtype: UInt64+ /// `/product/artwork-scale-factor`.+ public let artworkScale: UInt64+ /// The guest display.+ public let screen: VPhoneVirtualMachineManifest.ScreenConfig++ public init(+ family: Family,+ productType: String,+ deviceClass: String,+ targetType: String,+ uniqueModel: String,+ productName: String,+ artworkIdiom: String,+ artworkSubtype: UInt64,+ artworkScale: UInt64,+ screen: VPhoneVirtualMachineManifest.ScreenConfig,+ ) {+ self.family = family+ self.productType = productType+ self.deviceClass = deviceClass+ self.targetType = targetType+ self.uniqueModel = uniqueModel+ self.productName = productName+ self.artworkIdiom = artworkIdiom+ self.artworkSubtype = artworkSubtype+ self.artworkScale = artworkScale+ self.screen = screen+ }++ public var isPad: Bool {+ family == .iPad+ }++ // MARK: - Known Devices++ /// iPhone 16 (D47AP), the device every catalog IPSW targets.+ public static let iPhone17_3 = VPhoneGuestDevice(+ family: .iPhone,+ productType: "iPhone17,3",+ deviceClass: "d47ap",+ targetType: "D47",+ uniqueModel: "D47AP",+ productName: "iPhone 16",+ artworkIdiom: "phone",+ artworkSubtype: 2556,+ artworkScale: 3,+ screen: .default,+ )++ /// iPad mini (A17 Pro, Wi-Fi), J410AP. The 8.3-inch 1488x2266 panel at+ /// 326 ppi keeps the VM window a manageable size on a laptop.+ public static let iPad16_1 = VPhoneGuestDevice(+ family: .iPad,+ productType: "iPad16,1",+ deviceClass: "j410ap",+ targetType: "J410",+ uniqueModel: "J410AP",+ productName: "iPad mini (A17 Pro)",+ artworkIdiom: "pad",+ artworkSubtype: 2266,+ artworkScale: 2,+ screen: .init(width: 1488, height: 2266, pixelsPerInch: 326, scale: 2.0),+ )++ public static let known: [VPhoneGuestDevice] = [iPhone17_3, iPad16_1]++ /// Product types that share a known device's IPSW and map onto it. The+ /// cellular iPad mini ships in the same IPSW as the Wi-Fi one; the VM has+ /// no baseband, so it gets the Wi-Fi identity.+ static let aliases: [String: String] = ["iPad16,2": "iPad16,1"]++ /// The device a VM has when its configuration names none: every VM made+ /// before iPad guests existed is an iPhone17,3.+ public static let `default` = iPhone17_3++ public static func named(_ productType: String?) -> VPhoneGuestDevice? {+ guard let productType else { return nil }+ let canonical = aliases[productType] ?? productType+ return known.first { $0.productType == canonical }+ }++ // MARK: - Restore Tree++ /// 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.+ public func restoreTreeName(version: String, build: String) -> String {+ switch family {+ case .iPhone: "\(productType)_\(version)_\(build)_Restore"+ case .iPad: "iPhoneOS_\(productType)_\(version)_\(build)_Restore"+ }+ }++ // MARK: - Detection++ /// The device a restore BuildManifest is for, from its+ /// `SupportedProductTypes`. Nil when it names no known device.+ public static func detect(buildManifest: [String: Any]) -> VPhoneGuestDevice? {+ let types = buildManifest["SupportedProductTypes"] as? [String] ?? []+ for type in types {+ if let device = named(type) {+ return device+ }+ }+ return nil+ }++ public static func detect(buildManifestAt url: URL) -> VPhoneGuestDevice? {+ guard let data = try? Data(contentsOf: url),+ let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]+ else { return nil }+ return detect(buildManifest: plist)+ }++ /// Whether a restore BuildManifest is for an iPad at all, known or not.+ public static func isPadManifest(_ buildManifest: [String: Any]) -> Bool {+ let types = buildManifest["SupportedProductTypes"] as? [String] ?? []+ return types.contains { $0.hasPrefix("iPad") }+ }+}diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swiftindex dd555ee4..57134fdd 100644--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift@@ -120,6 +120,18 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {/// SEP storage filenamepublic let sepStorage: String+ // MARK: - Guest Device++ /// Product type of the device whose IPSW supplied the guest OS, as+ /// `fw prepare` found it. Absent for an iPhone17,3 guest and for every VM+ /// made before iPad guests existed.+ public let guestProductType: String?++ /// The guest device `fw patch` presents in the device tree.+ public var guestDevice: VPhoneGuestDevice {+ VPhoneGuestDevice.named(guestProductType) ?? .default+ }+// MARK: - Nested Typespublic enum PlatformType: String, Codable, Sendable {@@ -131,7 +143,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {case dev}- public struct ScreenConfig: Codable, Sendable {+ public struct ScreenConfig: Codable, Equatable, Sendable {public let width: Intpublic let height: Intpublic let pixelsPerInch: Int@@ -211,6 +223,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {nvramStorage: String = "nvram.bin",romImages: ROMImages?,sepStorage: String = "SEPStorage",+ guestProductType: String? = nil,) {schemaVersion = Self.currentSchemaVersionself.platformType = platformType@@ -224,6 +237,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {self.nvramStorage = nvramStorageself.romImages = romImagesself.sepStorage = sepStorage+ self.guestProductType = guestProductType}// MARK: - Creation@@ -404,6 +418,27 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {nvramStorage: nvramStorage,romImages: romImages,sepStorage: sepStorage,+ guestProductType: guestProductType,+ )+ }++ /// This manifest for a guest running `device`'s OS: its product type and+ /// its display. An iPhone17,3 guest records no product type, so its+ /// configuration stays readable by bundles that predate iPad guests.+ public func updating(guestDevice device: VPhoneGuestDevice) -> VPhoneVirtualMachineManifest {+ VPhoneVirtualMachineManifest(+ platformType: platformType,+ platformFusing: platformFusing,+ machineIdentifier: machineIdentifier,+ cpuCount: cpuCount,+ memorySize: memorySize,+ screenConfig: device.screen,+ networkConfig: networkConfig,+ diskImage: diskImage,+ nvramStorage: nvramStorage,+ romImages: romImages,+ sepStorage: sepStorage,+ guestProductType: device == .default ? nil : device.productType,)}}diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swiftnew file mode 100644index 00000000..489f0cf2--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift@@ -0,0 +1,59 @@+import Foundation+import Testing+@testable import VPhoneCoreKit++/// Which device's OS a VM runs, as `fw prepare` finds it in the IPSW and the+/// VM's `config.plist` keeps it.+@Suite("Guest device")+struct GuestDeviceTests {+ @Test+ func `a restore manifest names its device`() {+ #expect(VPhoneGuestDevice.detect(buildManifest: ["SupportedProductTypes": ["iPhone17,3"]]) == .iPhone17_3)+ #expect(VPhoneGuestDevice.detect(buildManifest: ["SupportedProductTypes": ["iPad16,1", "iPad16,2"]]) == .iPad16_1)+ // The cellular model shares the Wi-Fi one's IPSW and identity.+ #expect(VPhoneGuestDevice.detect(buildManifest: ["SupportedProductTypes": ["iPad16,2"]]) == .iPad16_1)+ #expect(VPhoneGuestDevice.detect(buildManifest: ["SupportedProductTypes": ["iPad13,1"]]) == nil)+ #expect(VPhoneGuestDevice.isPadManifest(["SupportedProductTypes": ["iPad13,1"]]))+ }++ @Test+ func `an iPad restore tree keeps the prefix every reader matches`() {+ let name = VPhoneGuestDevice.iPad16_1.restoreTreeName(version: "26.6.2", build: "23G90")+ #expect(name == "iPhoneOS_iPad16,1_26.6.2_23G90_Restore")+ #expect(name.hasPrefix("iPhone") && name.hasSuffix("_Restore"))+ #expect(VPhoneGuestDevice.iPhone17_3.restoreTreeName(version: "27.0", build: "24A435")+ == "iPhone17,3_27.0_24A435_Restore")+ }++ @Test+ func `a VM made before iPad guests is an iPhone17,3`() throws {+ let manifest = VPhoneVirtualMachineManifest.newVM()+ #expect(manifest.guestProductType == nil)+ #expect(manifest.guestDevice == .iPhone17_3)+ }++ @Test+ func `an iPad guest records its product and display`() throws {+ let manifest = VPhoneVirtualMachineManifest.newVM().updating(guestDevice: .iPad16_1)+ #expect(manifest.guestProductType == "iPad16,1")+ #expect(manifest.guestDevice == .iPad16_1)+ #expect(manifest.screenConfig == .init(width: 1488, height: 2266, pixelsPerInch: 326, scale: 2.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 == .iPad16_1)+ #expect(loaded.screenConfig == manifest.screenConfig)++ // Editing CPU or memory keeps the device.+ #expect(loaded.updating(cpuCount: 4).guestProductType == "iPad16,1")+ }++ @Test+ func `an iPhone17,3 guest writes no product, so older bundles read it unchanged`() {+ let manifest = VPhoneVirtualMachineManifest.newVM().updating(guestDevice: .iPhone17_3)+ #expect(manifest.guestProductType == nil)+ #expect(manifest.screenConfig == .default)+ }+}