Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Recover an iPad VM's board device tree from its IPSW

Jackyaf753f115461
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index ac13e96b..365d0917 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -2230,7 +2230,7 @@ virtio sound device with a host output sink. Two faults; the full reveal is
| --- | --- | --- |
| `system-virtiosound-cfw-hal_plugin` (new) | `/System/Library/Audio/Plug-Ins/HAL/VPhoneVirtIOSound.driver`, `cfw install` and `cfw update-environment` | Installs the CoreAudio HAL plugin for `AppleVirtIOSound`, built from `VPhoneGuestComponents/VirtIOSound`. |
| `devicetree-cfw-ipad_audio` (new) | An iPad guest's installed DeviceTree, `fw patch` | Replaces `/product/audio` with the board tree's node (`DeviceTreePatcher.presentBoardAudio`), all properties as the board has them except its `AAPL,phandle`. |
-| `preboot-cfw-devicetree_board_audio` (new) | Restored Preboot `devicetree.img4`, `cfw install` and `cfw update-environment` | The same replacement for an iPad VM patched before it (`vphone-cli cfw patch-dt-board-audio`), from the board tree in `FirmwareOriginals`. |
+| `preboot-cfw-devicetree_board_audio` (new) | Restored Preboot `devicetree.img4`, `cfw install` and `cfw update-environment` | The same replacement for an iPad VM patched before it (`vphone-cli cfw patch-dt-board-audio`), from the board tree in `FirmwareOriginals`. When that has none (a VM patched before `fw patch` kept it), the tree is first recovered from the VM's IPSW in `~/.vphone/ipsws`, matched by BuildManifest version, build, product type and board, and kept in `FirmwareOriginals`; with no matching IPSW the repair is skipped with one `[!]` line naming the fix. |
| `devicetree-cfw-product_haptics_node` (new, 2026-10-03) | Every guest's DeviceTree, `fw patch`: an iPhone guest's one tree, an iPad guest's installed tree and its `RestoreDeviceTree` | Removes `/product/haptics` (`DeviceTreePatcher.removeHaptics(from:)`), whatever the variant and the board. |
| `preboot-cfw-devicetree_haptics` (new, 2026-10-03) | Restored Preboot `devicetree.img4`, `cfw install` and `cfw update-environment`, every guest | The same removal for a VM patched before it (`vphone-cli cfw patch-dt-haptics`); it needs no board tree. A guest that booted before it keeps cached MobileGestalt answers, which vphoned drops at its next startup, see below. |
diff --git a/Research/Guest/virtio_sound.md b/Research/Guest/virtio_sound.md
index 4d97c4d4..5ba9c76a 100644
--- a/Research/Guest/virtio_sound.md
+++ b/Research/Guest/virtio_sound.md
@@ -152,10 +152,43 @@ fault; the tuning directory was. That attempt is not in the tree.
- `preboot-cfw-devicetree_board_audio`: `cfw install` and `cfw update-environment`
apply the same replacement to the restored Preboot `devicetree.img4`
(`vphone-cli cfw patch-dt-board-audio <devicetree.img4> <board.im4p>`), taking
- the board tree from `FirmwareOriginals`. An iPad VM patched before this has no
- copy there; put the board's `DeviceTree.<board>.im4p` from its IPSW into
- `FirmwareOriginals/<restore tree>/Firmware/all_flash/` and run the environment
- update. An iPhone guest has no board tree there and is left alone.
+ the board tree from `FirmwareOriginals`. An iPhone guest has no board tree
+ there and is left alone.
+- An iPad VM patched before `fw patch` kept the board tree has no copy in
+ `FirmwareOriginals`, and the update used to skip the repair without a word
+ (ipad-mini-01: acousticID stayed 8018, `VA Init Status: 1`). Both commands now
+ recover it first (`VPhoneBoardDeviceTree` in VPhoneArchiveKit):
+ - the firmware is read from the `FirmwareOriginals/<restore tree>` folder name
+ (`iPhoneOS_iPad16,1_26.6.2_23G90_Restore`), or from `restore-info.json`
+ when no such folder is there; the board is the guest device's
+ `deviceClass` (`config.plist` `guestProductType`, iPad16,1 → j410ap);
+ - every `*.ipsw` in the shared cache (`~/.vphone/ipsws`, or
+ `$VPHONE_ROOT/ipsws`) and in the `ipsws` folder beside the VM's library is
+ matched by its BuildManifest, never its file name: same `ProductVersion`
+ and `ProductBuildVersion`, the device among `SupportedProductTypes`, and a
+ build identity for the board whose `DeviceTree` path is
+ `DeviceTree.<board>.im4p`. That one member is read out without unpacking
+ the IPSW;
+ - it is written to `FirmwareOriginals/<restore tree>/Firmware/all_flash/`,
+ mode 0777, so later runs find it there like a tree `fw patch` kept. The
+ search and the write run with the invoking user's credentials, through
+ the pinned VM folder; the file is the user's, not root's.
+
+ The output says which it did:
+
+ ```
+ [*] FirmwareOriginals has no DeviceTree.j410ap.im4p; looking for the iPad16,1 26.6.2 (23G90) IPSW in /Users/<user>/.vphone/ipsws
+ [+] Board device tree recovered: Firmware/all_flash/DeviceTree.j410ap.im4p from /Users/<user>/.vphone/ipsws/<file>.ipsw, kept as FirmwareOriginals/iPhoneOS_iPad16,1_26.6.2_23G90_Restore/Firmware/all_flash/DeviceTree.j410ap.im4p
+ [*] Board device tree: FirmwareOriginals/iPhoneOS_iPad16,1_26.6.2_23G90_Restore/Firmware/all_flash/DeviceTree.j410ap.im4p
+ ```
+
+ When no IPSW matches, the run goes on without the repair and says so in one
+ `[!] Board audio repair skipped, so this iPad16,1 guest will have no sound: …`
+ line naming the build it looked for. The manual fix is still the fallback:
+ put that IPSW in `~/.vphone/ipsws`, or copy its
+ `Firmware/all_flash/DeviceTree.<board>.im4p` into
+ `FirmwareOriginals/<restore tree>/Firmware/all_flash/` yourself, and run the
+ environment update again.
## 3. Inside the precondition failure (follow-up session, 2026-10-02)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index e8924318..451a76b8 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -282,8 +282,9 @@ public enum FirmwareGuestSystemPatchSet {
summary: """
Gives an iPad guest's restored Preboot device tree the iPad's own audio node, as \
fw patch now does. Earlier trees kept the iPhone's, whose acoustic ID names tunings \
- an iPad image does not ship, so iOS's audio routing failed to start. Needs the \
- iPad's device tree in the VM's FirmwareOriginals.
+ an iPad image does not ship, so iOS's audio routing failed to start. Takes the \
+ iPad's device tree from the VM's FirmwareOriginals, and recovers it there from the \
+ VM's IPSW in ~/.vphone/ipsws when it is missing.
""",
target: .prebootDeviceTree,
),
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index 241c869c..39a99571 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -2,6 +2,7 @@ import ArgumentParser
import Darwin
import FirmwarePatcher
import Foundation
+import VPhoneArchiveKit
import VPhoneCoreKit
import VPhonePatchKit
import VPhoneSign
@@ -114,6 +115,12 @@ struct VPhoneCustomFirmwareInstaller {
guard geteuid() == 0 else {
throw ValidationError("\(mode.summary.capitalized) needs root. Run this command with sudo.")
}
+ // Launchpad's helper reads this through a pipe, where stdout would
+ // otherwise be block buffered: a warning printed early in the run
+ // would reach the machine's log only with the burst at exit. One line
+ // at a time, as in a terminal.
+ fflush(stdout)
+ setvbuf(stdout, nil, _IOLBF, 0)
// Ownership checks apply when the caller is known (SUDO_UID, which
// the Launchpad helper also sets). Plain root trusts its own files.
let invokingUser = VPhoneInvokingUser.current
@@ -139,6 +146,8 @@ struct VPhoneCustomFirmwareInstaller {
let restore = mode == .full
? try restoreTree(in: bundleDirectory, path: bundlePath, owner: callerUID)
: nil
+ // Before any disk work, so what it says is not buried under it.
+ recoverBoardDeviceTree(in: bundleDirectory, restore: restore, plan: plan, invokingUser: invokingUser)
let work = try makeWorkDirectory()
defer {
@@ -1268,7 +1277,8 @@ struct VPhoneCustomFirmwareInstaller {
/// The iPad's own device tree, `DeviceTree.<board>.im4p`, which `fw patch`
/// keeps in the VM's `FirmwareOriginals` beside the vphone600 trees,
/// copied into the work folder by descriptor. Nil when there is none: an
- /// iPhone guest, or a VM patched by a build that did not keep it.
+ /// iPhone guest, or a VM patched by a build that did not keep it and
+ /// whose IPSW `recoverBoardDeviceTree` could not find.
///
/// The folder is the caller's, so the copy goes through the pinned bundle
/// descriptor like every other read here, and more than one candidate is
@@ -1277,25 +1287,11 @@ struct VPhoneCustomFirmwareInstaller {
in bundleDirectory: VPhoneConfinedDirectory,
work: WorkDirectory,
) throws -> URL? {
- let originals = VPhoneBundleOperations.firmwareOriginalsDirectoryName
- guard try bundleDirectory.isDirectory(originals) else { return nil }
- let stash = try bundleDirectory.directory(originals)
- var found: [(directory: VPhoneConfinedDirectory, name: String, path: String)] = []
- for tree in try stash.entries() where try stash.isDirectory(tree) {
- let flash = "\(tree)/Firmware/all_flash"
- guard try stash.isDirectory(flash) else { continue }
- let directory = try stash.directory(flash)
- for name in try directory.entries()
- where name.hasPrefix("DeviceTree.") && name.hasSuffix(".im4p")
- && !name.hasPrefix("DeviceTree.vphone600") && (try? directory.isRegularFile(name)) == true
- {
- found.append((directory, name, "\(originals)/\(flash)/\(name)"))
- }
- }
+ let found = try VPhoneBoardDeviceTree.kept(in: bundleDirectory)
guard !found.isEmpty else { return nil }
guard found.count == 1, let board = found.first else {
throw ValidationError(
- "Found \(found.count) board device trees in \(originals): \(found.map(\.path).joined(separator: ", ")). Keep one.",
+ "Found \(found.count) board device trees in \(VPhoneBundleOperations.firmwareOriginalsDirectoryName): \(found.map(\.path).joined(separator: ", ")). Keep one.",
)
}
try board.directory.copyFile(from: board.name, to: board.name, in: work.directory)
@@ -1303,6 +1299,85 @@ struct VPhoneCustomFirmwareInstaller {
return work.file(board.name)
}
+ /// Make sure an iPad VM's `FirmwareOriginals` holds the board tree that
+ /// `stageBoardDeviceTree` stages, recovering it from the IPSW the VM was
+ /// made from when a VM patched before `fw patch` kept it has none. Without
+ /// it the board audio repair cannot run, VirtualAudio looks for the
+ /// iPhone's tunings, and the guest has no sound.
+ ///
+ /// The IPSW cache and the VM folder are the caller's, so the search and
+ /// the write run with the caller's credentials, as `cfw install` records
+ /// its variant: the kernel applies the caller's permissions to every read
+ /// and to the write, and the file left in the VM folder is the caller's.
+ /// The write still goes through the pinned VM folder, and the tree is then
+ /// staged from there like one `fw patch` kept.
+ ///
+ /// Never fails the run: without the tree only the repair is left out, and
+ /// that is said in one `[!]` line naming what is missing and the fix.
+ private func recoverBoardDeviceTree(
+ in bundleDirectory: VPhoneConfinedDirectory,
+ restore: VPhoneConfinedDirectory?,
+ plan: VPhoneVirtualMachinePatchPlan?,
+ invokingUser: VPhoneInvokingUser?,
+ ) {
+ guard plan?.isEnabled(FirmwareGuestSystemPatchSet.prebootBoardAudio) ?? true else { return }
+ let device = configuredGuestDevice(in: bundleDirectory) ?? guestDevice(of: restore)
+ let tree = (device.boardDeviceTreePath as NSString).lastPathComponent
+ let originals = VPhoneBundleOperations.firmwareOriginalsDirectoryName
+ let skipped = "[!] Board audio repair skipped, so this \(device.productType) guest will have no sound:"
+ do {
+ let need = try VPhoneBoardDeviceTree.need(
+ device: device,
+ in: bundleDirectory,
+ recorded: recordedOSVersion(in: bundleDirectory),
+ )
+ let firmware: VPhoneBoardDeviceTree.Firmware
+ switch need {
+ case .none, .kept:
+ return
+ case .unidentified:
+ print("\(skipped) \(originals) has no \(tree), and the VM folder does not say which IPSW it was made from. Copy \(device.boardDeviceTreePath) from that IPSW into \(bundle.path)/\(originals)/<restore tree>/Firmware/all_flash/, then run this again.")
+ return
+ case let .recover(found):
+ firmware = found
+ }
+ let directories = VPhoneBoardDeviceTree.searchDirectories(forVirtualMachineAt: bundle)
+ let fix = "Put that IPSW in \(directories[0].path), or copy its \(device.boardDeviceTreePath) to \(bundle.path)/\(firmware.keptPath), then run this again."
+ print("[*] \(originals) has no \(tree); looking for the \(device.productType) \(firmware.version) (\(firmware.build)) IPSW in \(directories.map(\.path).joined(separator: ", "))")
+ let recover = { () throws -> (source: VPhoneBoardDeviceTree.Source, path: String)? in
+ guard let source = VPhoneBoardDeviceTree.find(firmware, in: directories) else { return nil }
+ return (source, try VPhoneBoardDeviceTree.store(source, for: firmware, in: bundleDirectory))
+ }
+ do {
+ guard let recovered = try invokingUser.map({ try $0.withUserCredentials(recover) }) ?? recover() else {
+ print("\(skipped) no IPSW for \(device.productType) \(firmware.version) (\(firmware.build)) was found, and \(originals) has no \(tree). \(fix)")
+ return
+ }
+ print("[+] Board device tree recovered: \(recovered.source.member) from \(recovered.source.archive.path), kept as \(recovered.path)")
+ } catch {
+ print("\(skipped) \(tree) could not be kept in \(originals): \(error). \(fix)")
+ }
+ } catch {
+ print("\(skipped) \(bundle.path)/\(originals) could not be read: \(error). Copy \(device.boardDeviceTreePath) from the VM's IPSW into \(originals)/<restore tree>/Firmware/all_flash/, then run this again.")
+ }
+ }
+
+ /// The guest device `fw prepare` recorded in `config.plist`, read through
+ /// the pinned folder. Nil when it names none, as on a VM older than iPad
+ /// guests.
+ private func configuredGuestDevice(in bundleDirectory: VPhoneConfinedDirectory) -> VPhoneGuestDevice? {
+ guard let data = try? bundleDirectory.readData("config.plist"),
+ let plist = (try? PropertyListSerialization.propertyList(from: data, format: nil)) as? [String: Any]
+ else { return nil }
+ return VPhoneGuestDevice.named(plist["guestProductType"] as? String)
+ }
+
+ /// The iOS version and build `restore-info.json` records.
+ private func recordedOSVersion(in bundleDirectory: VPhoneConfinedDirectory) -> VPhoneRestoreInfo.OSVersion? {
+ guard let data = try? bundleDirectory.readData("restore-info.json") else { return nil }
+ return (try? JSONDecoder().decode(VPhoneRestoreInfo.self, from: data))?.ios
+ }
+
// MARK: - Guest file patches
/// Run a patch verb that edits a guest file in place, on a private copy
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
index 1f70fd80..117d5ff7 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift
@@ -313,6 +313,12 @@ struct VPhoneCustomFirmwareUpdateEnvironmentCommand: ParsableCommand {
A library the VM does not already have is left out, because its absence
means the VM's patch plan never selected it.
+ An iPad VM's audio repair needs the iPad's own DeviceTree.<board>.im4p
+ in the VM's FirmwareOriginals. When a VM patched by an older build has
+ none, it is recovered from the VM's IPSW in ~/.vphone/ipsws (matched by
+ its BuildManifest) and kept there; without that IPSW the repair is
+ skipped with a [!] line naming the fix.
+
Needs root, and the VM must be powered off.
""",
)
diff --git a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBoardDeviceTree.swift b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBoardDeviceTree.swift
new file mode 100644
index 00000000..4ece5eaf
--- /dev/null
+++ b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBoardDeviceTree.swift
@@ -0,0 +1,230 @@
+import Darwin
+import Foundation
+import VPhoneCoreKit
+
+/// An iPad guest's own device tree, `DeviceTree.<board>.im4p`, as a VM folder
+/// keeps it and as the IPSW the VM was made from carries it.
+///
+/// `fw patch` keeps the tree in the VM's `FirmwareOriginals`, mirrored under
+/// the restore tree's name, and the board audio repair that `cfw install` and
+/// `cfw update-environment` apply to the Preboot device tree reads it from
+/// there. A VM patched by a build that did not keep it has none, and nothing
+/// else in the VM folder still holds it: the restore tree is deleted once the
+/// VM has booted. The IPSW usually still exists, in the cache `fw prepare`
+/// downloads into, so the tree is recovered from there — matched by what the
+/// IPSW's BuildManifest says, never by its file name, and read as one member
+/// without unpacking the rest.
+///
+/// Everything here takes the VM folder as a pinned `VPhoneConfinedDirectory`,
+/// because the installer that calls it runs as root against a folder the
+/// caller controls; see `VPhoneCustomFirmwareInstaller`.
+public enum VPhoneBoardDeviceTree {
+ // MARK: - Firmware
+
+ /// The firmware a VM was made from, as far as its board tree is concerned.
+ public struct Firmware: Equatable, Sendable {
+ public let device: VPhoneGuestDevice
+ public let version: String
+ public let build: String
+
+ public init(device: VPhoneGuestDevice, version: String, build: String) {
+ self.device = device
+ self.version = version
+ self.build = build
+ }
+
+ /// The restore tree's name, which `FirmwareOriginals` mirrors.
+ public var treeName: String {
+ device.restoreTreeName(version: version, build: build)
+ }
+
+ /// `DeviceTree.<board>.im4p`.
+ public var fileName: String {
+ (device.boardDeviceTreePath as NSString).lastPathComponent
+ }
+
+ /// Where `fw patch` keeps the tree, relative to the VM folder.
+ public var keptPath: String {
+ "\(originalsName)/\(treeName)/\(device.boardDeviceTreePath)"
+ }
+ }
+
+ /// Read `<treeName>` back into the version and build it was made from, for
+ /// `device`. Nil for a folder another device or naming scheme made.
+ public static func firmware(treeName: String, device: VPhoneGuestDevice) -> Firmware? {
+ let suffix = "_Restore"
+ guard treeName.hasSuffix(suffix) else { return nil }
+ let parts = treeName.dropLast(suffix.count).split(separator: "_", omittingEmptySubsequences: false)
+ guard parts.count >= 3 else { return nil }
+ let firmware = Firmware(device: device, version: String(parts[parts.count - 2]), build: String(parts[parts.count - 1]))
+ guard !firmware.version.isEmpty, !firmware.build.isEmpty, firmware.treeName == treeName else { return nil }
+ return firmware
+ }
+
+ // MARK: - Kept trees
+
+ public struct Kept {
+ /// The `all_flash` folder holding it.
+ public let directory: VPhoneConfinedDirectory
+ public let name: String
+ /// Relative to the VM folder, for messages.
+ public let path: String
+ }
+
+ static let originalsName = VPhoneBundleOperations.firmwareOriginalsDirectoryName
+
+ /// Every board tree in the VM's `FirmwareOriginals`: any
+ /// `DeviceTree.*.im4p` there that is not one of the vphone600 trees the
+ /// boot chain is built from. Reached without following a link.
+ public static func kept(in vm: VPhoneConfinedDirectory) throws -> [Kept] {
+ guard try vm.isDirectory(originalsName) else { return [] }
+ let stash = try vm.directory(originalsName)
+ var found: [Kept] = []
+ for tree in try stash.entries() where try stash.isDirectory(tree) {
+ let flash = "\(tree)/Firmware/all_flash"
+ guard try stash.isDirectory(flash) else { continue }
+ let directory = try stash.directory(flash)
+ for name in try directory.entries()
+ where name.hasPrefix("DeviceTree.") && name.hasSuffix(".im4p")
+ && !name.hasPrefix("DeviceTree.vphone600") && (try? directory.isRegularFile(name)) == true
+ {
+ found.append(Kept(directory: directory, name: name, path: "\(originalsName)/\(flash)/\(name)"))
+ }
+ }
+ return found
+ }
+
+ // MARK: - Need
+
+ /// What a run has to do about a VM's board tree.
+ public enum Need: Equatable {
+ /// An iPhone guest, which has no board tree.
+ case none
+ /// `FirmwareOriginals` already holds one, or several, which staging
+ /// refuses to choose between.
+ case kept
+ /// None is kept; this is the firmware to recover it from.
+ case recover(Firmware)
+ /// None is kept, and the VM folder does not say which firmware it runs.
+ case unidentified
+ }
+
+ /// The firmware comes from the restore tree name `fw patch` mirrored into
+ /// `FirmwareOriginals`, which names exactly the IPSW the boot chain was
+ /// built from; `restore-info.json` (`recorded`) answers only when no such
+ /// folder is there. Two folders for the device are not guessed between.
+ public static func need(
+ device: VPhoneGuestDevice,
+ in vm: VPhoneConfinedDirectory,
+ recorded: VPhoneRestoreInfo.OSVersion?,
+ ) throws -> Need {
+ guard device.isPad else { return .none }
+ guard try kept(in: vm).isEmpty else { return .kept }
+ var trees: [String] = []
+ if try vm.isDirectory(originalsName) {
+ let stash = try vm.directory(originalsName)
+ trees = try stash.entries().filter { try stash.isDirectory($0) }
+ }
+ let named = trees.compactMap { firmware(treeName: $0, device: device) }
+ if named.count == 1, let firmware = named.first {
+ return .recover(firmware)
+ }
+ if named.isEmpty, let recorded, !recorded.version.isEmpty, !recorded.build.isEmpty {
+ return .recover(Firmware(device: device, version: recorded.version, build: recorded.build))
+ }
+ return .unidentified
+ }
+
+ // MARK: - IPSW
+
+ /// Where a VM's IPSW can be: the shared cache (`~/.vphone/ipsws`, or
+ /// `$VPHONE_ROOT/ipsws`), and the `ipsws` folder beside the VM's library,
+ /// which is the same cache for a library under another data root.
+ public static func searchDirectories(forVirtualMachineAt vm: URL) -> [URL] {
+ let beside = vm.standardizedFileURL.deletingLastPathComponent().deletingLastPathComponent()
+ .appendingPathComponent("ipsws", isDirectory: true)
+ var directories: [URL] = []
+ for directory in [VPhoneResources.ipswCacheDirectory(), beside] {
+ let path = directory.standardizedFileURL.path
+ if !directories.contains(where: { $0.standardizedFileURL.path == path }) {
+ directories.append(directory)
+ }
+ }
+ return directories
+ }
+
+ public struct Source: Sendable {
+ public let archive: URL
+ /// The member the BuildManifest names for the board's device tree.
+ public let member: String
+ public let contents: Data
+ }
+
+ /// The first IPSW in `directories`, by name, whose BuildManifest is
+ /// `firmware`'s version and build, covers its product type and names a
+ /// device tree for its board; with that tree's bytes. Unreadable archives
+ /// and partial downloads are passed over.
+ public static func find(_ firmware: Firmware, in directories: [URL]) -> Source? {
+ let fm = FileManager.default
+ for directory in directories {
+ let names = ((try? fm.contentsOfDirectory(atPath: directory.path)) ?? [])
+ .filter { !$0.hasPrefix(".") && $0.lowercased().hasSuffix(".ipsw") }
+ .sorted()
+ for name in names {
+ let file = directory.appendingPathComponent(name)
+ guard let manifest = try? VPhoneIPSWCache.buildManifest(of: file),
+ let member = member(for: firmware, in: manifest),
+ let contents = try? VPhoneArchiveReader.readMember(member, from: file),
+ !contents.isEmpty
+ else { continue }
+ return Source(archive: file, member: member, contents: contents)
+ }
+ }
+ return nil
+ }
+
+ /// The archive path of `firmware`'s board tree, when `manifest` is that
+ /// firmware: same version and build, the device among its product types,
+ /// and a build identity for the board whose `DeviceTree` is the tree.
+ static func member(for firmware: Firmware, in manifest: [String: Any]) -> String? {
+ guard manifest["ProductVersion"] as? String == firmware.version,
+ manifest["ProductBuildVersion"] as? String == firmware.build,
+ VPhoneGuestDevice.covered(by: manifest).contains(firmware.device)
+ else { return nil }
+ for identity in manifest["BuildIdentities"] as? [[String: Any]] ?? [] {
+ let info = identity["Info"] as? [String: Any]
+ guard (info?["DeviceClass"] as? String)?.lowercased() == firmware.device.deviceClass else { continue }
+ let deviceTree = (identity["Manifest"] as? [String: Any])?["DeviceTree"] as? [String: Any]
+ if let path = (deviceTree?["Info"] as? [String: Any])?["Path"] as? String,
+ (path as NSString).lastPathComponent == firmware.fileName
+ {
+ return path
+ }
+ }
+ return nil
+ }
+
+ // MARK: - Store
+
+ /// Keep `source` where `fw patch` would have, so every later run finds it
+ /// there. Written through the pinned VM folder and renamed into place, so
+ /// a link in the folder is replaced rather than written through. Folders
+ /// it creates and the file get mode 0777, like every host VM artifact.
+ /// Returns the path relative to the VM folder.
+ @discardableResult
+ public static func store(_ source: Source, for firmware: Firmware, in vm: VPhoneConfinedDirectory) throws -> String {
+ let components = (firmware.keptPath as NSString).deletingLastPathComponent.split(separator: "/").map(String.init)
+ var directory = vm
+ for component in components {
+ let existed = try directory.exists(component)
+ directory = try directory.directory(component, create: true, mode: 0o777)
+ if !existed {
+ guard fchmod(directory.descriptor, 0o777) == 0 else {
+ throw VPhoneConfinedDirectoryError.system(component, errno)
+ }
+ }
+ }
+ try directory.writeFile(firmware.fileName, contents: source.contents, mode: 0o777)
+ return firmware.keptPath
+ }
+}
diff --git a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift
index 05402108..fd245b69 100644
--- a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift
+++ b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneIPSWCache.swift
@@ -142,14 +142,23 @@ public enum VPhoneIPSWCache {
}
}
- public static func inspect(_ file: URL) throws -> Archive {
+ /// The IPSW's BuildManifest, read without unpacking anything else.
+ public static func buildManifest(of file: URL) throws -> [String: Any] {
guard FileManager.default.fileExists(atPath: file.path) else {
throw Error.missingFile(file)
}
guard let data = try? VPhoneArchiveReader.readMember("BuildManifest.plist", from: file),
let plist = try? PropertyListSerialization.propertyList(from: data, format: nil)
- as? [String: Any],
- let version = plist["ProductVersion"] as? String, !version.isEmpty,
+ as? [String: Any]
+ else {
+ throw Error.invalidManifest(file)
+ }
+ return plist
+ }
+
+ public static func inspect(_ file: URL) throws -> Archive {
+ let plist = try buildManifest(of: file)
+ guard let version = plist["ProductVersion"] as? String, !version.isEmpty,
let build = plist["ProductBuildVersion"] as? String, !build.isEmpty
else {
throw Error.invalidManifest(file)
diff --git a/VPhoneKit/VPhoneArchiveKitTests/BoardDeviceTreeTests.swift b/VPhoneKit/VPhoneArchiveKitTests/BoardDeviceTreeTests.swift
new file mode 100644
index 00000000..c212c93e
--- /dev/null
+++ b/VPhoneKit/VPhoneArchiveKitTests/BoardDeviceTreeTests.swift
@@ -0,0 +1,223 @@
+import Foundation
+import Testing
+@testable import VPhoneArchiveKit
+import VPhoneCoreKit
+
+/// Recovering an iPad VM's board device tree from the IPSW it was made from,
+/// for the board audio repair `cfw update-environment` applies. Synthetic VM
+/// folders and IPSWs only: a manifest and the members it names, no firmware.
+@Suite("Board device tree recovery", .serialized)
+struct BoardDeviceTreeTests {
+ // MARK: - Fixtures
+
+ private let iPadTree = "iPhoneOS_iPad16,1_26.6.2_23G90_Restore"
+
+ private func makeRoot() throws -> URL {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ return root
+ }
+
+ /// A VM folder whose `FirmwareOriginals` holds `trees`, each with the
+ /// vphone600 trees `fw patch` keeps and the extra `files` given.
+ private func makeVM(in root: URL, trees: [String], files: [String] = []) throws -> URL {
+ let vm = root.appendingPathComponent("machines/ipad", isDirectory: true)
+ try FileManager.default.createDirectory(at: vm, withIntermediateDirectories: true)
+ for tree in trees {
+ let flash = vm.appendingPathComponent("FirmwareOriginals/\(tree)/Firmware/all_flash", isDirectory: true)
+ try FileManager.default.createDirectory(at: flash, withIntermediateDirectories: true)
+ for name in ["DeviceTree.vphone600ap.im4p", "DeviceTree.vphone600ap.guest.im4p"] + files {
+ try Data(name.utf8).write(to: flash.appendingPathComponent(name))
+ }
+ }
+ return vm
+ }
+
+ /// An IPSW with a BuildManifest for `productTypes` and one build identity
+ /// per board, each naming `Firmware/all_flash/DeviceTree.<board>.im4p`,
+ /// and that member holding `"tree <board>"`.
+ @discardableResult
+ private func makeIPSW(
+ _ name: String,
+ in directory: URL,
+ version: String = "26.6.2",
+ build: String = "23G90",
+ productTypes: [String] = ["iPad16,1", "iPad16,2"],
+ boards: [String] = ["j410ap", "j411ap"],
+ includeMembers: Bool = true,
+ ) throws -> URL {
+ let files = directory.appendingPathComponent(".\(UUID().uuidString)", isDirectory: true)
+ let flash = files.appendingPathComponent("Firmware/all_flash", isDirectory: true)
+ try FileManager.default.createDirectory(at: flash, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: files) }
+ let identities: [[String: Any]] = boards.map { board in
+ [
+ "Info": ["DeviceClass": board],
+ "Manifest": ["DeviceTree": ["Info": ["Path": "Firmware/all_flash/DeviceTree.\(board).im4p"]]],
+ ]
+ }
+ let manifest: [String: Any] = [
+ "ProductVersion": version,
+ "ProductBuildVersion": build,
+ "SupportedProductTypes": productTypes,
+ "BuildIdentities": identities,
+ ]
+ try PropertyListSerialization.data(fromPropertyList: manifest, format: .xml, options: 0)
+ .write(to: files.appendingPathComponent("BuildManifest.plist"))
+ if includeMembers {
+ for board in boards {
+ try Data("tree \(board)".utf8).write(to: flash.appendingPathComponent("DeviceTree.\(board).im4p"))
+ }
+ }
+ let archive = directory.appendingPathComponent(name)
+ try VPhoneArchiveWriter.create(archive: archive, from: files)
+ return archive
+ }
+
+ private var miniFirmware: VPhoneBoardDeviceTree.Firmware {
+ .init(device: .iPad16_1, version: "26.6.2", build: "23G90")
+ }
+
+ // MARK: - Firmware
+
+ @Test func `restore tree names read back into the firmware they name`() {
+ let iPad = VPhoneBoardDeviceTree.firmware(treeName: iPadTree, device: .iPad16_1)
+ #expect(iPad == miniFirmware)
+ #expect(iPad?.keptPath == "FirmwareOriginals/\(iPadTree)/Firmware/all_flash/DeviceTree.j410ap.im4p")
+ #expect(VPhoneBoardDeviceTree.firmware(treeName: "iPhone17,3_26.0_23A341_Restore", device: .iPhone17_3)?.build == "23A341")
+ // Another device's tree, or not a restore tree at all.
+ #expect(VPhoneBoardDeviceTree.firmware(treeName: iPadTree, device: .iPad15_7) == nil)
+ #expect(VPhoneBoardDeviceTree.firmware(treeName: "Restore", device: .iPad16_1) == nil)
+ #expect(VPhoneBoardDeviceTree.firmware(treeName: "iPhoneOS_iPad16,1__23G90_Restore", device: .iPad16_1) == nil)
+ }
+
+ // MARK: - Need
+
+ @Test func `an iPhone guest needs no board tree`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let vm = try VPhoneConfinedDirectory(root: makeVM(in: root, trees: ["iPhone17,3_26.6.2_23G90_Restore"]).path)
+ #expect(try VPhoneBoardDeviceTree.need(device: .iPhone17_3, in: vm, recorded: nil) == .none)
+ }
+
+ @Test func `an iPad VM that kept its board tree needs nothing more`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let vm = try VPhoneConfinedDirectory(root: makeVM(in: root, trees: [iPadTree], files: ["DeviceTree.j410ap.im4p"]).path)
+ #expect(try VPhoneBoardDeviceTree.need(device: .iPad16_1, in: vm, recorded: nil) == .kept)
+ #expect(try VPhoneBoardDeviceTree.kept(in: vm).map(\.path) == [
+ "FirmwareOriginals/\(iPadTree)/Firmware/all_flash/DeviceTree.j410ap.im4p",
+ ])
+ }
+
+ @Test func `an iPad VM without one recovers it for the firmware its originals name`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let vm = try VPhoneConfinedDirectory(root: makeVM(in: root, trees: [iPadTree]).path)
+ #expect(try VPhoneBoardDeviceTree.kept(in: vm).isEmpty)
+ // The originals win over a restore-info.json that disagrees.
+ let recorded = VPhoneRestoreInfo.OSVersion(version: "26.6.1", build: "23G80")
+ #expect(try VPhoneBoardDeviceTree.need(device: .iPad16_1, in: vm, recorded: recorded) == .recover(miniFirmware))
+ }
+
+ @Test func `restore-info answers only when the originals cannot`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let vm = try VPhoneConfinedDirectory(root: makeVM(in: root, trees: []).path)
+ let recorded = VPhoneRestoreInfo.OSVersion(version: "26.6.2", build: "23G90")
+ #expect(try VPhoneBoardDeviceTree.need(device: .iPad16_1, in: vm, recorded: recorded) == .recover(miniFirmware))
+ #expect(try VPhoneBoardDeviceTree.need(device: .iPad16_1, in: vm, recorded: nil) == .unidentified)
+
+ // Two trees for the device are not guessed between.
+ let twice = try VPhoneConfinedDirectory(root: makeVM(
+ in: root.appendingPathComponent("second"),
+ trees: [iPadTree, "iPhoneOS_iPad16,1_26.6.1_23G80_Restore"],
+ ).path)
+ #expect(try VPhoneBoardDeviceTree.need(device: .iPad16_1, in: twice, recorded: recorded) == .unidentified)
+ }
+
+ // MARK: - IPSW
+
+ @Test func `the IPSW is chosen by its manifest, not its name`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let cache = root.appendingPathComponent("ipsws", isDirectory: true)
+ try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: true)
+ // Named like the right one, but another build.
+ try makeIPSW("iPad16,1,iPad16,2_26.6.2_23G90_Restore.ipsw", in: cache, version: "26.6.1", build: "23G80")
+ // The right build for other iPads.
+ try makeIPSW("a.ipsw", in: cache, productTypes: ["iPad17,1", "iPad17,2"], boards: ["j817ap"])
+ // Not an archive at all, and a partial download.
+ try Data("not an ipsw".utf8).write(to: cache.appendingPathComponent("b.ipsw"))
+ try makeIPSW(".c.ipsw.partial", in: cache)
+ // The one, cellular model only in its product list.
+ let right = try makeIPSW("z.ipsw", in: cache, productTypes: ["iPad16,2"])
+
+ let source = try #require(VPhoneBoardDeviceTree.find(miniFirmware, in: [root.appendingPathComponent("missing"), cache]))
+ #expect(source.archive == right)
+ #expect(source.member == "Firmware/all_flash/DeviceTree.j410ap.im4p")
+ #expect(source.contents == Data("tree j410ap".utf8))
+ }
+
+ @Test func `no IPSW is found when none carries the board tree`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ try makeIPSW("x.ipsw", in: root, boards: ["j411ap"])
+ try makeIPSW("y.ipsw", in: root, includeMembers: false)
+ #expect(VPhoneBoardDeviceTree.find(miniFirmware, in: [root]) == nil)
+ }
+
+ @Test func `the library's own ipsws folder is searched after the shared cache`() {
+ let vm = URL(fileURLWithPath: "/Volumes/Lab/vphone/machines/ipad", isDirectory: true)
+ let directories = VPhoneBoardDeviceTree.searchDirectories(forVirtualMachineAt: vm)
+ #expect(directories.first == VPhoneResources.ipswCacheDirectory())
+ #expect(directories.last?.path == "/Volumes/Lab/vphone/ipsws")
+
+ let local = VPhoneResources.ipswCacheDirectory().deletingLastPathComponent()
+ .appendingPathComponent("machines/ipad", isDirectory: true)
+ #expect(VPhoneBoardDeviceTree.searchDirectories(forVirtualMachineAt: local).count == 1)
+ }
+
+ // MARK: - Store
+
+ @Test func `a recovered tree is kept where fw patch keeps it`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let url = try makeVM(in: root, trees: [iPadTree])
+ let vm = try VPhoneConfinedDirectory(root: url.path)
+ let source = try #require(VPhoneBoardDeviceTree.find(miniFirmware, in: [makeIPSWDirectory(in: root)]))
+
+ let path = try VPhoneBoardDeviceTree.store(source, for: miniFirmware, in: vm)
+ #expect(path == miniFirmware.keptPath)
+ let file = url.appendingPathComponent(path)
+ #expect(try Data(contentsOf: file) == Data("tree j410ap".utf8))
+ let mode = try #require(FileManager.default.attributesOfItem(atPath: file.path)[.posixPermissions] as? Int)
+ #expect(mode == 0o777)
+ // A later run finds it like one fw patch kept.
+ #expect(try VPhoneBoardDeviceTree.need(device: .iPad16_1, in: vm, recorded: nil) == .kept)
+ }
+
+ @Test func `storing creates the originals folders a VM never had`() throws {
+ let root = try makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let url = try makeVM(in: root, trees: [])
+ let vm = try VPhoneConfinedDirectory(root: url.path)
+ let source = try #require(VPhoneBoardDeviceTree.find(miniFirmware, in: [makeIPSWDirectory(in: root)]))
+
+ try VPhoneBoardDeviceTree.store(source, for: miniFirmware, in: vm)
+ for folder in ["FirmwareOriginals", "FirmwareOriginals/\(iPadTree)/Firmware/all_flash"] {
+ let mode = try #require(
+ FileManager.default.attributesOfItem(atPath: url.appendingPathComponent(folder).path)[.posixPermissions] as? Int,
+ )
+ #expect(mode == 0o777)
+ }
+ #expect(try VPhoneBoardDeviceTree.kept(in: vm).map(\.name) == ["DeviceTree.j410ap.im4p"])
+ }
+
+ private func makeIPSWDirectory(in root: URL) throws -> URL {
+ let directory = root.appendingPathComponent("ipsws", isDirectory: true)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ try makeIPSW("mini.ipsw", in: directory)
+ return directory
+ }
+}