Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Every current iPad size: read the guest's identity from its own device tree

Jacky9600f529d8dc
diff --git a/Documents/Guides/ipados.md b/Documents/Guides/ipados.md
index 538a5f41..e62107ff 100644
--- a/Documents/Guides/ipados.md
+++ b/Documents/Guides/ipados.md
@@ -12,12 +12,30 @@ tree is rewritten so that userland sees an iPad.
## Supported devices
-| Product | Model | Board | Display |
-| --- | --- | --- | --- |
-| `iPad16,1` (and `iPad16,2`, same IPSW) | iPad mini (A17 Pro) | J410AP | 1488x2266 @ 326 ppi, 2x |
+| Product | Model | Board | Panel | Points @2x |
+| --- | --- | --- | --- | --- |
+| `iPad16,1` | iPad mini (A17 Pro) | J410AP | 1488x2266 @ 326 ppi | 744x1133 |
+| `iPad15,7` | iPad (A16) | J481AP | 1640x2360 @ 264 ppi | 820x1180 |
+| `iPad15,3` | iPad Air 11-inch (M3) | J607AP | 1640x2360 @ 264 ppi | 820x1180 |
+| `iPad15,5` | iPad Air 13-inch (M3) | J637AP | 2048x2732 @ 264 ppi | 1024x1366 |
+| `iPad16,3` | iPad Pro 11-inch (M4) | J717AP | 1668x2420 @ 264 ppi | 834x1210 |
+| `iPad16,5` | iPad Pro 13-inch (M4) | J720AP | 2064x2752 @ 264 ppi | 1032x1376 |
+| `iPad17,1` | iPad Pro 11-inch (M5) | J817AP | 1668x2420 @ 264 ppi | 834x1210 |
+| `iPad17,3` | iPad Pro 13-inch (M5) | J820AP | 2064x2752 @ 264 ppi | 1032x1376 |
-Other iPads are refused by `fw prepare` until their device tree values are
-added to `VPhoneGuestDevice` and `DeviceTreeGuestDevicePatches.swift`.
+The cellular models (`iPad16,2`, `iPad15,4`, `iPad15,6`, `iPad16,4`, `iPad16,6`,
+`iPad17,2`, `iPad17,4`) share their Wi-Fi twin's IPSW and run as it: the VM has
+no baseband. `iPad15,8` ships in an IPSW of its own without the Wi-Fi board and
+is not supported.
+
+Most iPad IPSWs cover several models — the iPad Air and iPad Pro IPSWs carry
+both sizes. Without `--device`, `fw prepare` takes the first model the IPSW
+lists (the 11-inch); pass `--device iPad17,3` to `fw prepare` or `vm create` for
+the 13-inch. Launchpad's New Machine takes the first model.
+
+Adding another iPad takes one line in `VPhoneGuestDevice`: its product type,
+board and panel. Everything the device tree needs is read from the board's own
+`DeviceTree.<board>.im4p` in the IPSW.
## Create one
@@ -28,6 +46,11 @@ same one an iPhone guest of that release would use; `fw catalog` lists it.
vphone-cli vm create ipad-mini \
--iphone-source 'https://updates.cdn-apple.com/2026SummerFCS/cf7db64d-5866-4bf2-bfff-50a32f58bec3/iPad16,1,iPad16,2_26.6.2_23G90_Restore.ipsw' \
--cloudos-source 'https://updates.cdn-apple.com/private-cloud-compute/c0ecdb4b310cf5239ab2b248dd3098eec297dc5aa3bbe6ada27273262b0b8b64'
+
+# The 13-inch iPad Pro (M5), from the IPSW that also carries the 11-inch
+vphone-cli vm create ipad-pro-13 --device iPad17,3 \
+ --iphone-source 'https://updates.cdn-apple.com/2026SummerFCS/<…>/iPad17,1,iPad17,2,iPad17,3,iPad17,4_26.6.2_23G90_Restore.ipsw' \
+ --cloudos-source 'https://updates.cdn-apple.com/private-cloud-compute/c0ecdb4b310cf5239ab2b248dd3098eec297dc5aa3bbe6ada27273262b0b8b64'
```
`fw prepare --device iPad16,1 --list` lists the iPad's downloadable IPSWs,
@@ -57,12 +80,15 @@ Only `fw prepare` and `fw patch` differ for an iPad; DFU, `restore` and
the manifest (`iPhone99,11`); the guest boots the copy.
- **`fw patch`** gives that copy the iPad's identity and presentation (patch
set `devicetree`, entries `devicetree-cfw-ipad_*`):
- - root `model` `iPad16,1`, `target-type` `J410`, `target-sub-type` `J410AP`,
- `compatible` `J410AP, VPHONE600AP, AppleVirtualPlatformARM`;
- - `/product`: `artwork-device-idiom` `pad`, subtype 2266, scale 2, the
- iPad's product name, chrome, camera and button geometry, the multitasking
- capabilities (`medusa-overlay-app-capability`, `ui-floating-live-app`,
- `ui-overlay-app`, `ui-pinned-app`), and its product type and unique model;
+ - root `model`, `target-type` and `target-sub-type` as on the board (for the
+ iPad mini `iPad16,1`, `J410`, `J410AP`), and `compatible` with the board
+ first and `VPHONE600AP` kept second;
+ - `/product`: the board's artwork idiom, subtype and scale, product name,
+ chrome, camera and button geometry, multitasking capabilities
+ (`medusa-overlay-app-capability`, `ui-floating-live-app`, `ui-overlay-app`,
+ `ui-pinned-app`, and `disable-chamois` where the board has no Stage
+ Manager), and its product type and unique model — all read from the
+ board's `DeviceTree.<board>.im4p`, which the restore tree keeps;
- phone-only `syscfg` placeholders (Dynamic Island, reachability, ringer
switch, volume-button geometry, CarPlay, Watch pairing) are removed.
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 413a1037..63bf62d4 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -19,9 +19,14 @@
> three `hv_vmm_present` concealment patches, and the iPhone17,3 identity rewrites;
> `extended` blocks nothing.
>
-> **iPad guests (2026-10-01):** four DeviceTree patches, on in `standard`,
-> exist only for a VM whose userland comes from an iPad restore IPSW
-> (`iPad16,1`, iPad mini A17 Pro, J410AP): `devicetree-cfw-ipad_artwork`,
+> **iPad guests (2026-10-01; every current iPad 2026-10-02):** four DeviceTree
+> patches, on in `standard`, exist only for a VM whose userland comes from an
+> iPad restore IPSW (iPad mini A17 Pro, iPad A16, iPad Air M3 11/13, iPad Pro
+> M4 and M5 11/13 — see `VPhoneGuestDevice.known`). Since 2026-10-02 their
+> values are read at `fw patch` time from the board's own
+> `DeviceTree.<board>.im4p` in the restore tree rather than a table, so an
+> M-series board keeps Stage Manager (no `disable-chamois`) and the iPad (A16)
+> has no `medusa-overlay-app-capability`: `devicetree-cfw-ipad_artwork`,
> `devicetree-cfw-ipad_product`, `devicetree-cfw-ipad_buttons` and
> `devicetree-cfw-ipad_identity`. They are written to a second device tree,
> `Firmware/all_flash/DeviceTree.vphone600ap.guest.im4p`, which `fw prepare`
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift
index 3e07dd58..a784d33b 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift
@@ -6,21 +6,22 @@
// 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:
+// The answers come from the iPad's own device tree, `DeviceTree.<board>.im4p`,
+// which the IPSW carries and the restore tree keeps:
//
-// - `/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.
+// - the `/product` properties in `copiedProductProperties` take the board's
+// values, and are removed where the board has none — so an iPad mini keeps
+// `disable-chamois` and an M-series iPad, which has Stage Manager, does not;
+// - the phone-only placeholders no iPad carries (Dynamic Island,
+// reachability, ringer switch, volume-button geometry, CarPlay, Watch
+// pairing) are removed, which is what "absent" means to MobileGestalt;
+// - the root and `/product` identity becomes the board'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.
+// `graphics-featureset-class` (the paravirtual GPU is APPLE7, not the iPad's),
+// `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
@@ -51,15 +52,77 @@ extension DeviceTreePatcher {
static let iPadButtonsPatch = "devicetree-cfw-ipad_buttons"
static let iPadIdentityPatch = "devicetree-cfw-ipad_identity"
+ // MARK: - What Is Copied
+
+ /// `/product` properties taken from the board's tree, by patch.
+ static let copiedProductProperties: [(name: String, patchID: String)] = [
+ // What UIKit and SpringBoard lay out against.
+ ("artwork-device-idiom", iPadArtworkPatch),
+ ("artwork-device-subtype", iPadArtworkPatch),
+ ("artwork-scale-factor", iPadArtworkPatch),
+ // The device MobileGestalt reports.
+ ("fdr-product-type", iPadIdentityPatch),
+ ("sub-product-type", iPadIdentityPatch),
+ ("unique-model", iPadIdentityPatch),
+ // Name, chrome, and the panel and camera geometry.
+ ("product-name", iPadProductPatch),
+ ("product-description", iPadProductPatch),
+ ("chrome-identifier", iPadProductPatch),
+ ("compatible-device-fallback", iPadProductPatch),
+ ("display-corner-radius", iPadProductPatch),
+ ("display-mirroring", iPadProductPatch),
+ ("side-button-location", iPadProductPatch),
+ ("front-cam-offset-from-center", iPadProductPatch),
+ ("rear-cam-offset-from-center", iPadProductPatch),
+ ("thin-bezel", iPadProductPatch),
+ ("ui-pip", iPadProductPatch),
+ ("ui-background-quality", iPadProductPatch),
+ ("ui-weather-quality", iPadProductPatch),
+ ("assistant", iPadProductPatch),
+ ("dictation", iPadProductPatch),
+ ("offline-dictation", iPadProductPatch),
+ ("builtin-mics", iPadProductPatch),
+ // Multitasking: Slide Over, the overlay and pinned app slots, and
+ // `disable-chamois`, which turns Stage Manager off where the board has it.
+ ("medusa-overlay-app-capability", iPadProductPatch),
+ ("ui-floating-live-app", iPadProductPatch),
+ ("ui-overlay-app", iPadProductPatch),
+ ("ui-pinned-app", iPadProductPatch),
+ ("disable-chamois", iPadProductPatch),
+ ("natural-volume-arrangement", iPadProductPatch),
+ ]
+
+ /// vphone600 `/product` properties that describe a phone. Removed unless the
+ /// board's tree has them too.
+ 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",
+ ]
+
+ /// Root properties taken from the board's tree. `compatible` is rebuilt.
+ static let copiedRootProperties = ["model", "target-type", "target-sub-type"]
+
+ /// The placeholder bit in a property's flags: the value is a `syscfg/` key,
+ /// not data.
+ static let placeholderFlag: UInt16 = 0x8000
+
// 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 set(Data)
case remove
}
@@ -69,130 +132,83 @@ extension DeviceTreePatcher {
let patchID: String
}
- /// The edits that make the vphone600 tree present `device`.
- static func guestEdits(for device: VPhoneGuestDevice) -> [GuestEdit] {
- guard device.isPad else { return [] }
+ /// The edits that make the vphone600 tree present the board whose tree is
+ /// `source`.
+ static func guestEdits(from source: DTNode) throws -> [GuestEdit] {
let product = ["device-tree", "product"]
+ let sourceProduct = try child(of: source, named: "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))
+ func value(_ node: DTNode, _ name: String) -> Data? {
+ guard let property = node.properties.first(where: { $0.name == name }),
+ property.flags & placeholderFlag == 0
+ else { return nil }
+ return property.value
+ }
- // 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, patchID) in copiedProductProperties {
+ let action: GuestEdit.Action = value(sourceProduct, name).map { .set($0) } ?? .remove
+ edits.append(GuestEdit(nodePath: product, property: name, action: action, patchID: patchID))
}
for name in iPhoneOnlyProductProperties {
- edits.append(GuestEdit(nodePath: product, property: name, action: .remove, patchID: iPadProductPatch))
+ if let board = value(sourceProduct, name) {
+ edits.append(GuestEdit(nodePath: product, property: name, action: .set(board), patchID: iPadProductPatch))
+ } else {
+ 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))
+ let sourceButtons = try? child(of: source, named: "buttons")
+ if sourceButtons.flatMap({ value($0, "function-button_ringeren") }) == nil {
+ 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))
+ for name in copiedRootProperties {
+ guard let board = value(source, name) else {
+ throw PatcherError.patchSiteNotFound("DeviceTree: the board's tree has no root \(name)")
+ }
+ edits.append(GuestEdit(nodePath: ["device-tree"], property: name, action: .set(board), patchID: iPadIdentityPatch))
+ }
+ guard let compatible = value(source, "compatible"),
+ let first = compatible.split(separator: 0, omittingEmptySubsequences: true).first
+ else {
+ throw PatcherError.patchSiteNotFound("DeviceTree: the board's tree has no root compatible")
+ }
+ edits.append(GuestEdit(nodePath: ["device-tree"], property: "compatible",
+ action: .set(Self.compatible(board: Data(first))), patchID: iPadIdentityPatch))
return edits
}
- /// `compatible` with the device's board first, so `hw.model` reads it, and
+ /// `compatible` with the 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)
+ static func compatible(board: Data) -> Data {
+ board + Data("\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: []
+ private static func child(of node: DTNode, named name: String) throws -> DTNode {
+ for child in node.children {
+ for property in child.properties where property.name == "name" {
+ if property.value.prefix(while: { $0 != 0 }) == Data(name.utf8) {
+ return child
+ }
+ }
}
+ throw PatcherError.patchSiteNotFound("DeviceTree: the board's tree has no \(name) node")
}
- /// 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.
+ /// Applies `guestEdits(from:)` to the parsed tree and records each change.
func applyGuestEdits(root: DTNode) throws {
- for edit in Self.guestEdits(for: device) {
+ guard let sourceTree else {
+ throw PatcherError.fileNotFound(
+ "DeviceTree: \(device.productType)'s own device tree (\(device.boardDeviceTreePath)) is needed to present it",
+ )
+ }
+ let source = try parsePayload(sourceTree)
+ for edit in try Self.guestEdits(from: source) {
guard gateAllows(edit.patchID) else { continue }
let node = try resolveNode(root, path: edit.nodePath)
let index = node.properties.firstIndex { $0.name == edit.property }
@@ -204,27 +220,22 @@ extension DeviceTreePatcher {
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
+ guard property.value != value || property.flags != 0 else { continue }
+ property.value = value
property.flags = 0
} else {
- node.properties.append(DTProperty(name: edit.property, flags: 0, value: after, valueOffset: 0))
+ node.properties.append(DTProperty(name: edit.property, flags: 0, value: value, valueOffset: 0))
}
+ after = value
}
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)"
+ case .set: "Set \(path) as on \(device.productType)"
}
patches.append(PatchRecord(
patchID: edit.patchID,
@@ -240,19 +251,4 @@ extension DeviceTreePatcher {
}
}
}
-
- /// 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.swift
index 4e23b739..68ce00b5 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
@@ -31,6 +31,9 @@ public final class DeviceTreePatcher: BufferedPatcher {
/// DeviceTreeGuestDevicePatches.swift.
let device: VPhoneGuestDevice
let role: TreeRole
+ /// The guest device's own flat device tree payload, which an iPad's
+ /// installed tree takes its identity and `/product` answers from.
+ let sourceTree: Data?
let buffer: BinaryBuffer
var patches: [PatchRecord] = []
@@ -72,12 +75,14 @@ public final class DeviceTreePatcher: BufferedPatcher {
includeIdentityPatches: Bool = false,
device: VPhoneGuestDevice = .default,
role: TreeRole = .shared,
+ sourceTree: Data? = nil,
) {
buffer = BinaryBuffer(data)
self.verbose = verbose
self.includeIdentityPatches = includeIdentityPatches
self.device = device
self.role = role
+ self.sourceTree = sourceTree
}
// MARK: - Patcher
@@ -178,7 +183,7 @@ public final class DeviceTreePatcher: BufferedPatcher {
}
/// Parse the entire device tree payload.
- private func parsePayload(_ blob: Data) throws -> DTNode {
+ func parsePayload(_ blob: Data) throws -> DTNode {
let (root, end) = try parseNode(blob, offset: 0)
guard end == blob.count else {
throw PatcherError.invalidFormat(
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift
index 53c3e0e2..9fbe6eb9 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift
@@ -55,6 +55,7 @@ public enum FirmwareManifest {
public static func generate(
iPhoneDir: URL,
cloudOSDir: URL,
+ device chosen: VPhoneGuestDevice? = nil,
verbose: Bool = true,
) throws {
// Load source plists.
@@ -72,7 +73,7 @@ public enum FirmwareManifest {
// 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) ?? .default
+ let device = chosen ?? VPhoneGuestDevice.detect(buildManifest: iPhoneBM) ?? .default
let (prod, res) = try findCloudOS(cloudIdentities, deviceClass: "vresearch101ap")
let (vp, vpr) = try findCloudOS(cloudIdentities, deviceClass: "vphone600ap")
let iErase = try findIPhoneErase(iPhoneIdentities, deviceClass: device.deviceClass)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
index e0a6c29d..10888fd4 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
@@ -50,9 +50,10 @@ extension FirmwarePipeline {
// An iPad guest boots a device tree of its own (7b) and needs LLB to give
// it the iPad's display scale (4).
- let guestDevice = Self.readGuestDevice(restoreDir)
+ let guestDevice = readGuestDevice(restoreDir)
let guestTreeURL = restoreDir.appending(path: FirmwareManifest.guestDeviceTreePath)
let hasGuestTree = guestDevice.isPad && FileManager.default.fileExists(atPath: guestTreeURL.path)
+ let boardTreeURL = restoreDir.appending(path: guestDevice.boardDeviceTreePath)
/// Whether the plan turned a patch on. Without a plan, fall back to the
/// release the patch is pinned to, which is the same answer the standard
@@ -168,7 +169,7 @@ extension FirmwarePipeline {
patcherFactories: includeBootChain ? [{ data, verbose in
let p = IBootPatcher(data: data, mode: .llb, verbose: verbose)
p.extraBootArgs = extraBootArgs
- p.displayScale = hasGuestTree ? UInt16(guestDevice.artworkScale) : nil
+ p.displayScale = hasGuestTree ? UInt16(guestDevice.screen.scale) : nil
p.gate = gate
return p
}] : [],
@@ -275,6 +276,7 @@ extension FirmwarePipeline {
includeIdentityPatches: dtIncludeIdentity,
device: guestDevice,
role: .installed,
+ sourceTree: try self.loader.load(from: boardTreeURL),
)
p.gate = gate
return p
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
index 9162b6d3..a73ca5ee 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift
@@ -51,11 +51,16 @@ 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
+ /// The device whose IPSW supplied the guest OS: the one `fw prepare`
+ /// recorded in the VM's configuration when that IPSW covers it, otherwise
+ /// the first known model the preserved manifest names. iPhone17,3 when it
+ /// names none.
+ func readGuestDevice(_ restoreDir: URL) -> VPhoneGuestDevice {
+ let recorded = try? VPhoneVirtualMachineManifest.load(from: vmDirectory.appendingPathComponent("config.plist"))
+ return VPhoneGuestDevice.detect(
+ buildManifestAt: restoreDir.appendingPathComponent("iPhone-BuildManifest.plist"),
+ preferring: recorded?.guestProductType,
+ ) ?? .default
}
/// cloudOS/kernel version (the live `BuildManifest.plist`).
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift
index 42cb43fc..a2f103f7 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift
@@ -92,6 +92,48 @@ struct DeviceTreeGuestDeviceTests {
],
)
+ /// A board tree shaped like `DeviceTree.j410ap.im4p`: iPad mini (A17 Pro).
+ static func board(
+ model: String = "iPad16,1",
+ unique: String = "J410AP",
+ subtype: UInt32 = 2266,
+ disablesStageManager: Bool = true,
+ ) -> Node {
+ var product: [Property] = [
+ .string("name", "product"),
+ .string("artwork-device-idiom", "pad"),
+ .integer("artwork-device-subtype", subtype),
+ .integer("artwork-scale-factor", 2),
+ .string("product-name", "iPad"),
+ .string("fdr-product-type", model),
+ .string("sub-product-type", model),
+ .string("unique-model", unique),
+ Property(name: "ui-pip", flags: 0, value: Data()),
+ .integer("medusa-overlay-app-capability", 1),
+ Property(name: "ui-pinned-app", flags: 0, value: Data()),
+ // A board placeholder is a syscfg key, not data: not copied, so the
+ // vphone600 placeholder it would replace is removed instead.
+ .placeholder("product-description", "prde"),
+ ]
+ if disablesStageManager {
+ product.append(.integer("disable-chamois", 1))
+ }
+ let target = String(unique.dropLast(2))
+ return Node(
+ properties: [
+ .string("name", "device-tree"),
+ .string("model", model),
+ .string("target-type", target),
+ .string("target-sub-type", unique),
+ Property(name: "compatible", flags: 0, value: Data("\(unique)\0\(model)\0AppleARM\0".utf8)),
+ ],
+ children: [
+ Node(properties: product, children: []),
+ Node(properties: [.string("name", "buttons"), .string("button-names", "volup")], children: []),
+ ],
+ )
+ }
+
// MARK: - Reading the result
/// `node -> property -> (flags, value)` for the two levels the fixture has.
@@ -132,13 +174,18 @@ struct DeviceTreeGuestDeviceTests {
return value.1.loadLE(UInt32.self, at: 0)
}
- static func patch(device: VPhoneGuestDevice, role: DeviceTreePatcher.TreeRole) throws -> [String: [String: (UInt16, Data)]] {
+ static func patch(
+ device: VPhoneGuestDevice,
+ role: DeviceTreePatcher.TreeRole,
+ board: Node = board(),
+ ) throws -> [String: [String: (UInt16, Data)]] {
let patcher = DeviceTreePatcher(
data: tree.serialized(),
verbose: false,
includeIdentityPatches: false,
device: device,
role: role,
+ sourceTree: board.serialized(),
)
_ = try patcher.findAll()
return read(patcher.patchedData)
@@ -161,12 +208,14 @@ struct DeviceTreeGuestDeviceTests {
#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["product-name"]) == "iPad")
+ #expect(product["product-description"] == nil)
#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(Self.integer(product["disable-chamois"]) == 1)
#expect(product["island-notch-location"] == nil)
#expect(product["car-integration"] == nil)
@@ -197,9 +246,30 @@ struct DeviceTreeGuestDeviceTests {
#expect(Self.integer(installed["device-tree/product"]?["island-notch-location"]) == 144)
}
- @Test func `the iPad edits are declared by the device tree patch set`() {
+ @Test func `a 13-inch M-series board keeps Stage Manager and its own identity`() throws {
+ let board = Self.board(model: "iPad17,3", unique: "J820AP", subtype: 2752, disablesStageManager: false)
+ let tree = try Self.patch(device: .iPad17_3, role: .installed, board: board)
+ let root = try #require(tree["device-tree"])
+ let product = try #require(tree["device-tree/product"])
+ #expect(Self.string(root["model"]) == "iPad17,3")
+ #expect(Self.string(root["target-type"]) == "J820")
+ #expect(root["compatible"]?.1 == Data("J820AP\0VPHONE600AP\0AppleVirtualPlatformARM\0".utf8))
+ #expect(Self.integer(product["artwork-device-subtype"]) == 2752)
+ #expect(product["disable-chamois"] == nil)
+ }
+
+ @Test func `an iPad's installed tree needs the board's tree`() {
+ let patcher = DeviceTreePatcher(
+ data: Self.tree.serialized(), verbose: false, device: .iPad16_1, role: .installed,
+ )
+ #expect(throws: (any Error).self) { try patcher.findAll() }
+ }
+
+ @Test func `the iPad edits are declared by the device tree patch set`() throws {
let declared = Set(FirmwareDeviceTreePatchSet.manifest.patches.map(\.identifier))
- let used = Set(DeviceTreePatcher.guestEdits(for: .iPad16_1).map(\.patchID))
+ let parser = DeviceTreePatcher(data: Data(), verbose: false)
+ let board = try parser.parsePayload(Self.board().serialized())
+ let used = try Set(DeviceTreePatcher.guestEdits(from: board).map(\.patchID))
#expect(!used.isEmpty)
#expect(used.isSubset(of: declared))
}
@@ -207,10 +277,12 @@ struct DeviceTreeGuestDeviceTests {
@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,
+ sourceTree: Self.board().serialized(),
)
_ = try once.findAll()
let twice = DeviceTreePatcher(
data: once.patchedData, verbose: false, device: .iPad16_1, role: .installed,
+ sourceTree: Self.board().serialized(),
)
_ = try twice.findAll()
#expect(twice.patchedData == once.patchedData)
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
index 993f3783..52d53c67 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift
@@ -208,8 +208,11 @@ struct VPhoneFirmwarePrepareCommand: ParsableCommand {
var ipswCache: String?
@Option(help: "iPhone version to resolve to an IPSW") var iphoneVersion: String?
@Option(help: "iPhone build to resolve to an IPSW") var iphoneBuild: String?
- @Option(help: "Device whose IPSWs --list, --iphone-version and --iphone-build look up: iPhone17,3 or iPad16,1")
- var device: String = VPhoneFirmwareCatalog.device
+ @Option(help: ArgumentHelp(
+ "Guest device: picks the model from an IPSW that covers several (iPad15,5 from the iPad Air IPSW), and the device --list, --iphone-version and --iphone-build look up (default: iPhone17,3)",
+ valueName: "product-type",
+ ))
+ var device: String?
@Flag(help: "List downloadable IPSWs and exit") var list = false
@Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")
var projectRoot: String?
@@ -222,10 +225,11 @@ struct VPhoneFirmwarePrepareCommand: ParsableCommand {
let bundleGuide = resources.base.appendingPathComponent("docs/guides/compatibility.md")
let readme = FileManager.default.fileExists(atPath: sourceGuide.path) ? sourceGuide.path : bundleGuide.path
let needsCatalog = list || iphoneVersion != nil || iphoneBuild != nil
- guard VPhoneGuestDevice.named(device) != nil else {
- throw ValidationError("vphone runs \(VPhoneGuestDevice.known.map(\.productType).joined(separator: " and ")) guests, not \(device).")
+ if let device, VPhoneGuestDevice.named(device) == nil {
+ throw ValidationError("vphone runs \(VPhoneGuestDevice.known.map(\.productType).joined(separator: ", ")) guests, not \(device).")
}
- let device = device
+ let chosenDevice = device
+ let device = device ?? VPhoneFirmwareCatalog.device
let urls = if needsCatalog {
try vphoneRunBlocking {
try await VPhoneFirmwareIndex.restoreURLs(forDevice: device)
@@ -282,6 +286,7 @@ struct VPhoneFirmwarePrepareCommand: ParsableCommand {
ipswCacheDirectory: ipswCache.map {
URL(fileURLWithPath: ($0 as NSString).expandingTildeInPath, isDirectory: true)
} ?? VPhoneResources.ipswCacheDirectory(),
+ device: chosenDevice,
bundle: bundle,
resources: resources,
)
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift
index 9c370048..ac647d11 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwarePreparer.swift
@@ -13,6 +13,7 @@ enum VPhoneFirmwarePreparer {
case existingRestore(URL)
case missingComponent(URL)
case sourceNameMismatch(URL, version: String, build: String)
+ case deviceNotInSource(String, available: [String])
var errorDescription: String? {
switch self {
@@ -22,6 +23,8 @@ enum VPhoneFirmwarePreparer {
"A firmware component is missing: \(path.path). Check that the IPSW is complete, then prepare the firmware again."
case let .sourceNameMismatch(path, version, build):
"The IPSW file name does not match its contents (\(version)/\(build)): \(path.path). Use the original file name or download the IPSW again."
+ case let .deviceNotInSource(productType, available):
+ "The IPSW does not contain \(productType); it covers \(available.joined(separator: ", ")). Choose one of those with --device, or use that model's IPSW."
}
}
}
@@ -31,6 +34,7 @@ enum VPhoneFirmwarePreparer {
cloudOSSource: String,
gpuDriverBundle: URL? = nil,
ipswCacheDirectory: URL = VPhoneResources.ipswCacheDirectory(),
+ device productType: String? = nil,
bundle: VPhoneBundle,
resources: VPhoneResources,
) throws {
@@ -70,7 +74,10 @@ enum VPhoneFirmwarePreparer {
try await VPhoneIPSWCache.resolve(cloudOSSource, in: ipswCacheDirectory)
}
try VPhoneIPSWCache.checkPair(iPhone: phone, cloudOS: cloud)
- let device = VPhoneIPSWCache.guestDevice(for: phone) ?? .default
+ let device = VPhoneIPSWCache.guestDevice(for: phone, preferring: productType) ?? .default
+ if let productType, VPhoneGuestDevice.named(productType) != device {
+ throw Error.deviceNotInSource(productType, available: phone.productTypes)
+ }
try checkIPhoneName(iPhoneSource, archive: phone, device: device)
print("[+] \(device.productType) \(phone.version) (\(phone.build)); cloudOS \(cloud.version) (\(cloud.build))")
@@ -100,7 +107,7 @@ enum VPhoneFirmwarePreparer {
try mergeCloudOS(from: cloudTree, into: phoneTree)
let originalManifest = phoneTree.appendingPathComponent("BuildManifest.plist")
try clone(originalManifest, to: phoneTree.appendingPathComponent("iPhone-BuildManifest.plist"))
- try FirmwareManifest.generate(iPhoneDir: phoneTree, cloudOSDir: cloudTree, verbose: true)
+ 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...")
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift
index 1d696b0b..0321aa2c 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift
@@ -18,6 +18,11 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {
var gpuDriverBundle: String?
@Option(help: "Directory for downloaded IPSWs, shared by every VM (default: ~/.vphone/ipsws or $VPHONE_ROOT/ipsws)")
var ipswCache: String?
+ @Option(help: ArgumentHelp(
+ "Guest device, when the IPSW covers several models (iPad15,5 from the iPad Air IPSW)",
+ valueName: "product-type",
+ ))
+ var device: String?
@Option(name: .shortAndLong, help: "Disk size (GB)") var diskSize: UInt64 = 64
@Option(
name: .customLong("preset"),
@@ -56,6 +61,7 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {
ipswCacheDirectory: ipswCache.map {
URL(fileURLWithPath: ($0 as NSString).expandingTildeInPath, isDirectory: true)
} ?? VPhoneResources.ipswCacheDirectory(),
+ device: device,
patchPreset: preset,
diskSizeGB: diskSize,
verbosity: VPhoneVerbosity(count: verboseCount),
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift
index cbe23fe9..a482c7a3 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift
@@ -11,6 +11,8 @@ public extension VPhoneVirtualMachineCreator {
public var cloudosSource: String?
public var gpuDriverBundle: URL?
public var ipswCacheDirectory: URL
+ /// The guest device to take from an IPSW that covers several models.
+ public var device: String?
/// Which patch preset the new VM is built with. Individual patches are
/// turned on or off per VM afterwards, through its patch selection.
public var patchPreset: String
@@ -26,6 +28,7 @@ public extension VPhoneVirtualMachineCreator {
cloudosSource: String? = nil,
gpuDriverBundle: URL? = nil,
ipswCacheDirectory: URL = VPhoneResources.ipswCacheDirectory(),
+ device: String? = nil,
patchPreset: String = VPhonePatchPreset.standardIdentifier,
cpuCount: UInt = 8,
memoryMB: UInt64 = 8192,
@@ -38,6 +41,7 @@ public extension VPhoneVirtualMachineCreator {
self.cloudosSource = cloudosSource
self.gpuDriverBundle = gpuDriverBundle
self.ipswCacheDirectory = ipswCacheDirectory
+ self.device = device
self.patchPreset = patchPreset
self.cpuCount = cpuCount
self.memoryMB = memoryMB
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift
index 9588fe08..4ee57a74 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift
@@ -232,6 +232,7 @@ public struct VPhoneVirtualMachineCreator {
iPhoneSource: phone, cloudOSSource: cloud,
gpuDriverBundle: options.gpuDriverBundle,
ipswCacheDirectory: options.ipswCacheDirectory,
+ device: options.device,
bundle: bundle, resources: resources,
)
print("[+] Firmware prepared (iPhone + cloudOS merged into bundle).")
diff --git a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift
index 6649585e..2bf84f66 100644
--- a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift
+++ b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift
@@ -254,9 +254,11 @@ public enum VPhoneIPSWCache {
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
+ /// The guest device an IPSW supplies, or nil for any other product. An IPSW
+ /// that covers several models gives `preferring` when it is one of them, and
+ /// its first known model otherwise.
+ public static func guestDevice(for archive: Archive, preferring productType: String? = nil) -> VPhoneGuestDevice? {
+ VPhoneGuestDevice.detect(buildManifest: ["SupportedProductTypes": archive.productTypes], preferring: productType)
}
/// Checks each BuildManifest before anything is extracted, so a swapped
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift
index 8f755bea..561d801e 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDevice.swift
@@ -10,7 +10,10 @@ import Foundation
/// 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`.
+/// The identity and `/product` values come from the device's own
+/// `DeviceTree.<deviceClass>.im4p`, which the IPSW carries and `fw prepare`
+/// keeps in the restore tree. What a device tree does not say — the panel's
+/// size and density — is recorded here.
public struct VPhoneGuestDevice: Sendable, Equatable {
public enum Family: String, Codable, Sendable {
case iPhone
@@ -20,44 +23,24 @@ public struct VPhoneGuestDevice: Sendable, Equatable {
public let family: Family
/// `Ap,ProductType`, e.g. `iPad16,1`.
public let productType: String
- /// BuildManifest `DeviceClass`, e.g. `j410ap`.
+ /// BuildManifest `DeviceClass`, and the board in `DeviceTree.<board>.im4p`.
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`.
+ /// The marketing name, for logs and prompts.
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.
+ /// The guest display, as the device's panel has it.
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
}
@@ -72,36 +55,64 @@ public struct VPhoneGuestDevice: Sendable, Equatable {
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]
+ private static func iPad(
+ _ productType: String,
+ _ deviceClass: String,
+ _ productName: String,
+ width: Int,
+ height: Int,
+ pixelsPerInch: Int = 264,
+ ) -> VPhoneGuestDevice {
+ VPhoneGuestDevice(
+ family: .iPad,
+ productType: productType,
+ deviceClass: deviceClass,
+ productName: productName,
+ screen: .init(width: width, height: height, pixelsPerInch: pixelsPerInch, scale: 2.0),
+ )
+ }
- /// 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"]
+ /// iPad mini (A17 Pro): 8.3-inch, 1488x2266 at 326 ppi, 744x1133 points.
+ public static let iPad16_1 = iPad("iPad16,1", "j410ap", "iPad mini (A17 Pro)", width: 1488, height: 2266, pixelsPerInch: 326)
+ /// iPad (A16): 11-inch, 1640x2360, 820x1180 points.
+ public static let iPad15_7 = iPad("iPad15,7", "j481ap", "iPad (A16)", width: 1640, height: 2360)
+ /// iPad Air 11-inch (M3): 1640x2360, 820x1180 points.
+ public static let iPad15_3 = iPad("iPad15,3", "j607ap", "iPad Air 11-inch (M3)", width: 1640, height: 2360)
+ /// iPad Air 13-inch (M3): 2048x2732, 1024x1366 points.
+ public static let iPad15_5 = iPad("iPad15,5", "j637ap", "iPad Air 13-inch (M3)", width: 2048, height: 2732)
+ /// iPad Pro 11-inch (M4): 1668x2420, 834x1210 points.
+ public static let iPad16_3 = iPad("iPad16,3", "j717ap", "iPad Pro 11-inch (M4)", width: 1668, height: 2420)
+ /// iPad Pro 13-inch (M4): 2064x2752, 1032x1376 points.
+ public static let iPad16_5 = iPad("iPad16,5", "j720ap", "iPad Pro 13-inch (M4)", width: 2064, height: 2752)
+ /// iPad Pro 11-inch (M5): 1668x2420, 834x1210 points.
+ public static let iPad17_1 = iPad("iPad17,1", "j817ap", "iPad Pro 11-inch (M5)", width: 1668, height: 2420)
+ /// 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)
+
+ public static let known: [VPhoneGuestDevice] = [
+ iPhone17_3,
+ iPad16_1,
+ iPad15_7,
+ iPad15_3, iPad15_5,
+ iPad16_3, iPad16_5,
+ iPad17_1, iPad17_3,
+ ]
+
+ /// Cellular models that ship in the same IPSW as a known Wi-Fi model and map
+ /// onto it: the VM has no baseband, so it gets the Wi-Fi identity.
+ static let aliases: [String: String] = [
+ "iPad16,2": "iPad16,1",
+ "iPad15,4": "iPad15,3",
+ "iPad15,6": "iPad15,5",
+ "iPad16,4": "iPad16,3",
+ "iPad16,6": "iPad16,5",
+ "iPad17,2": "iPad17,1",
+ "iPad17,4": "iPad17,3",
+ ]
/// The device a VM has when its configuration names none: every VM made
/// before iPad guests existed is an iPhone17,3.
@@ -127,12 +138,23 @@ public struct VPhoneGuestDevice: Sendable, Equatable {
}
}
+ /// Where the restore tree keeps this device's own device tree.
+ public var boardDeviceTreePath: String {
+ "Firmware/all_flash/DeviceTree.\(deviceClass).im4p"
+ }
+
// 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? {
+ /// `SupportedProductTypes`. One IPSW often covers several models — an 11-
+ /// and a 13-inch iPad and their cellular twins — so `preferring` names the
+ /// one wanted; without it, or when the IPSW does not cover it, the first
+ /// known model wins. Nil when the manifest names no known device.
+ public static func detect(buildManifest: [String: Any], preferring productType: String? = nil) -> VPhoneGuestDevice? {
let types = buildManifest["SupportedProductTypes"] as? [String] ?? []
+ if let productType, types.contains(productType), let device = named(productType) {
+ return device
+ }
for type in types {
if let device = named(type) {
return device
@@ -141,11 +163,23 @@ public struct VPhoneGuestDevice: Sendable, Equatable {
return nil
}
- public static func detect(buildManifestAt url: URL) -> VPhoneGuestDevice? {
+ public static func detect(buildManifestAt url: URL, preferring productType: String? = nil) -> 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)
+ return detect(buildManifest: plist, preferring: productType)
+ }
+
+ /// Every known device a restore BuildManifest can supply.
+ public static func covered(by buildManifest: [String: Any]) -> [VPhoneGuestDevice] {
+ let types = buildManifest["SupportedProductTypes"] as? [String] ?? []
+ var devices: [VPhoneGuestDevice] = []
+ for type in types {
+ if let device = named(type), !devices.contains(device) {
+ devices.append(device)
+ }
+ }
+ return devices
}
/// Whether a restore BuildManifest is for an iPad at all, known or not.
diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift
index 489f0cf2..53e40d1a 100644
--- a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceTests.swift
@@ -56,4 +56,26 @@ struct GuestDeviceTests {
#expect(manifest.guestProductType == nil)
#expect(manifest.screenConfig == .default)
}
+
+ @Test
+ func `an IPSW covering several iPads gives the one asked for`() {
+ let air = ["SupportedProductTypes": ["iPad15,3", "iPad15,4", "iPad15,5", "iPad15,6"]]
+ #expect(VPhoneGuestDevice.detect(buildManifest: air) == .iPad15_3)
+ #expect(VPhoneGuestDevice.detect(buildManifest: air, preferring: "iPad15,5") == .iPad15_5)
+ // A cellular model maps onto its Wi-Fi twin.
+ #expect(VPhoneGuestDevice.detect(buildManifest: air, preferring: "iPad15,6") == .iPad15_5)
+ // A model the IPSW does not cover is not invented.
+ #expect(VPhoneGuestDevice.detect(buildManifest: air, preferring: "iPad17,3") == .iPad15_3)
+ #expect(VPhoneGuestDevice.covered(by: air) == [.iPad15_3, .iPad15_5])
+ }
+
+ @Test
+ func `every known iPad has a 2x panel and a board tree to read`() {
+ for device in VPhoneGuestDevice.known where device.isPad {
+ #expect(device.screen.scale == 2.0)
+ #expect(device.screen.width < device.screen.height)
+ #expect(device.boardDeviceTreePath == "Firmware/all_flash/DeviceTree.\(device.deviceClass).im4p")
+ }
+ #expect(VPhoneGuestDevice.iPad17_3.screen == .init(width: 2064, height: 2752, pixelsPerInch: 264, scale: 2.0))
+ }
}