Run a virtual iPhone on an Apple Silicon Mac.
Swift
Convert the research board's device tree into vphone600
Maximilian Paß754630ea2c53
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 0e7fe560..1efb9e36 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -3351,3 +3351,47 @@ ldid's signature (no ad-hoc flag, empty CMS blob), and launchd panicked at itsfirst boot task ("launchd_cache_loader - posix_spawn: 85: Bad executable").vphoned, its launch daemon plist and the rewritten `launchd.plist` belong toroot:wheel, as the system's own; they kept the host user's owner and group.++## The research board stands in for vphone600 (2026-10-19)++Only the 26.1–26.4 beta cloudOS releases (up to 23E5207q) carry a vphone600ap+build identity. The 26.4 release and every one up to 26.7, and the 18.x+releases, have the research board alone (vresearch101ap). `FirmwareManifest`+now takes the research identities for the vphone600 components when there is+no vphone600ap, and leaves `RecoveryMode` out when the identity has none.+The new set `com.vphone.patchset.research.board` turns those components into+vphone600's. Every shipped preset names it. Its patches write only where they+find the research board, so a cloudOS with vphone600 components records+nothing and stays byte-identical.++**`devicetree-boot-vresearch101_conversion`**+(`DeviceTreeResearchBoardConversion.swift`) rewrites the research tree before+any other device tree patch runs, whatever the selection, because those are+written against vphone600 paths and values. It finds the research tree by its+root `target-type` (`VRESEARCH101`) and then:++- sets the root identity (`VPHONE600AP`, `iPhone99,11`);+- adds the seven nodes the research board lacks: `/buttons`,+ `/arm-io/multi-touch`, `/arm-io/bluetooth`,+ `/product/vphone600-gestalt-variants` with its `d47vm2025vre-variant`,+ `/product/maps` and `/product/haptics`. Each goes where vphone600 has it and+ gets an unused `AAPL,phandle`;+- sets the phone's `/product`, `/defaults`, `/filesystems` and gestalt+ variant properties, most of them `syscfg/` placeholders (flag 0x8000);+- removes `/defaults/pmap-max-asids` and `/product/kernel-core-dump-location`.++Existing phandles are kept, so `interrupt-parent`, `device-interrupt-parent`+and `serial-device` keep naming the nodes they named. The earlier port+renumbered every node and repaired those three references by hand, which+would have broken any other reference.++Checked against Apple: converting the vresearch101 tree of cloudOS 26.1+(`399b664d`) and of the 26.4 beta (`c0ecdb4b`) gives their vphone600 tree+property for property. The only differences are the build `time-stamp`, the+order properties are stored in, and the phandle numbers, which are compared+through the node each reference names. `DeviceTreeResearchBoardTests` runs+that comparison whenever an IPSW in `ipsws/` carries both trees.++`fw prepare` still refuses a cloudOS without vphone600ap+(`VPhoneIPSWCache.checkPair`): the guest also needs a kernel with the+iPhone's kexts, which the research board's kernelcache does not have.diff --git a/Skills/authoring-patch-sets/SKILL.md b/Skills/authoring-patch-sets/SKILL.mdindex 8015957c..4c1c6fb0 100644--- a/Skills/authoring-patch-sets/SKILL.md+++ b/Skills/authoring-patch-sets/SKILL.md@@ -19,7 +19,7 @@ warning on every run. Declaring it is what makes it real.| A preset | `VPhonePatchPreset` | `VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/*.plist` |The types live in `VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/`. The-nine in-tree sets and the two shipped presets live in+in-tree sets and the shipped presets live in`VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/`, listed by`FirmwarePatchSetCatalog`.@@ -169,8 +169,9 @@ Then:has to mean leaving the patcher out.3. Add the set to both shipped preset plists (both name every set; presets differby their selection, not by which sets they draw on). The one exception is- `minimal`, which names only the device tree and the restore image set: it- customises the system before the restore, the other sets after it.+ `minimal`, which names only the boot chain, research board, device tree and+ restore image sets: it customises the system before the restore, the other+ sets after it.4. Run the catalogue tests.### Capabilities, Requires, Conflicts, After@@ -192,7 +193,7 @@ Presets are prewritten and reviewed. Nothing in the tool writes one; a VM recordonly which boxes its owner changed, and those compose on top.`standard` is what every VM gets. Any other preset must be asked for with-`--preset`. Both shipped presets name all nine sets and differ only in their+`--preset`. The shipped presets name every set but the restore image and differ only in theirselection:```xmldiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swiftindex b95b55fd..3c16d649 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift@@ -3,7 +3,8 @@// Historical note: derived from the legacy Python firmware patcher during the Swift migration.//// Strategy:-// 1. Parse the flat device tree binary into a node/property tree.+// 1. Parse the flat device tree binary into a node/property tree, and+// convert a research board tree into vphone600 (DeviceTreeResearchBoardConversion.swift).// 2. Apply a fixed set of property patches (serial-number, home-button-type,// artwork-device-subtype, island-notch-location).// 3. Serialize the modified tree back to flat binary.@@ -20,6 +21,11 @@ public final class DeviceTreePatcher: BufferedPatcher {/// Which patches the resolved preset turned on. Unrestricted by default.public var gate: VPhonePatchGate = .unrestricted+ /// Whether a research board tree is converted into vphone600 first. Off when+ /// the preset leaves out `FirmwareResearchBoardPatchSet`, whose patch would+ /// otherwise be declared by nothing and apply regardless.+ public var convertsResearchBoard = true+/// Whether to apply the 8 identity-rewrite property patches (Tier 1b + 1c)/// that flip device identity towards iPhone17,3 / D47AP. Enabled for/// public JB and the historical internal EXP variant.@@ -321,6 +327,10 @@ public final class DeviceTreePatcher: BufferedPatcher {/// other variants leave the device's identity properties untouched./// `/product/haptics` is removed from every tree, whatever the variant.private func applyPatches(root: DTNode) throws {+ // Before everything else, whatever the selection: every patch below is+ // written against vphone600 paths and values.+ try applyResearchBoardConversion(root: root)+var patchesToApply = Self.basePropertyPatchesif includeIdentityPatches {patchesToApply.append(contentsOf: Self.identityPropertyPatches)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeResearchBoardConversion.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeResearchBoardConversion.swiftnew file mode 100644index 00000000..4cf47786--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeResearchBoardConversion.swift@@ -0,0 +1,308 @@+// DeviceTreeResearchBoardConversion.swift — vresearch101 → vphone600.+//+// Only the 26.1–26.4 beta cloudOS releases carry a vphone600ap device tree.+// Every other one has the research board's alone, which describes a compute+// module: no buttons, touch screen or Bluetooth, no phone product properties,+// and `ComputeModule14,2` where the userland looks for `iPhone99,11`. This+// rewrites it as the vphone600 tree of the same release, before any other+// device tree patch runs, so those see the tree they were written for.+//+// Checked against Apple's own trees: converting the vresearch101 tree of the+// 26.1 and 26.4 beta cloudOS gives their vphone600 tree, property for property,+// apart from the build time-stamp and the order properties are stored in.+//+// Nodes the research board lacks go where vphone600 has them, each with a+// fresh `AAPL,phandle`. The existing phandles are left alone, so every+// `interrupt-parent` and `serial-device` reference keeps pointing where it did.++import Foundation+import VPhonePatchKit++extension DeviceTreePatcher {+ // MARK: - What Is Converted++ /// A property value, encoded as the vphone600 tree stores it.+ enum ResearchBoardValue {+ case string(String)+ case strings([String])+ case integer(UInt32)+ case bytes(Data)+ /// A `syscfg/<key>` placeholder: iBoot fills it from the VM's syscfg,+ /// or drops the property when the syscfg has no such key.+ case syscfg(String)+ case empty+ }++ /// A node the research board lacks, inserted after `after` (first when nil).+ struct ResearchBoardNode {+ let parent: [String]+ let name: String+ let after: String?+ }++ struct ResearchBoardProperty {+ let path: [String]+ let name: String+ let value: ResearchBoardValue+ }++ /// In vphone600's order, so a node is added before its children.+ static let researchBoardNodes: [ResearchBoardNode] = [+ ResearchBoardNode(parent: [], name: "buttons", after: nil),+ ResearchBoardNode(parent: ["arm-io"], name: "multi-touch", after: "gfx"),+ ResearchBoardNode(parent: ["arm-io"], name: "bluetooth", after: "cpu-debug-interface"),+ ResearchBoardNode(parent: ["product"], name: "vphone600-gestalt-variants", after: nil),+ ResearchBoardNode(parent: ["product", "vphone600-gestalt-variants"], name: "d47vm2025vre-variant", after: nil),+ ResearchBoardNode(parent: ["product"], name: "maps", after: "vphone600-gestalt-variants"),+ ResearchBoardNode(parent: ["product"], name: "haptics", after: "maps"),+ ]++ /// Research board properties vphone600 does not have.+ static let researchBoardRemovals: [(path: [String], name: String)] = [+ (["defaults"], "pmap-max-asids"),+ (["product"], "kernel-core-dump-location"),+ ]++ static let researchBoardProperties: [ResearchBoardProperty] = {+ func set(_ path: [String], _ name: String, _ value: ResearchBoardValue) -> ResearchBoardProperty {+ ResearchBoardProperty(path: path, name: name, value: value)+ }+ let variant = ["product", "vphone600-gestalt-variants", "d47vm2025vre-variant"]+ return [+ // MARK: Identity++ set([], "compatible", .strings(["VPHONE600AP", "iPhone99,11", "AppleVirtualPlatformARM"])),+ set([], "model", .string("iPhone99,11")),+ set([], "target-sub-type", .string("VPHONE600AP")),+ set([], "target-type", .string("VPHONE600")),++ // MARK: Buttons, Touch, Bluetooth++ set(["buttons"], "function-button_ringeren", .syscfg("rgen")),+ set(["buttons"], "home-button-type", .syscfg("home")),+ set(["arm-io", "multi-touch"], "device_type", .string("multi-touch")),+ set(["arm-io", "multi-touch"], "ttw-supported", .empty),+ set(["arm-io", "bluetooth"], "device_type", .string("bluetooth")),+ set(["arm-io", "bluetooth"], "local-mac-address", .syscfg("BMac/6,zeroes/6")),+ set(["arm-io", "bluetooth"], "transport-encoding", .integer(10)),++ // MARK: Filesystems and Defaults++ set(["filesystems"], "e-apfs", .integer(1)),+ set(["defaults"], "kern.entitled_max_task_pmem", .syscfg("ketp")),+ set(["defaults"], "kern.max_task_pmem", .syscfg("kmtp")),+ set(["defaults"], "kern.maxkfsevents", .integer(1024)),+ set(["defaults"], "kern.maxvnodes", .integer(14000)),+ set(["defaults"], "kern.vm_compressor", .integer(32)),++ // MARK: Product++ set(["product"], "artwork-device-idiom", .string("phone")),+ set(["product"], "artwork-device-subtype", .syscfg("ards")),+ set(["product"], "artwork-display-gamut", .string("P3")),+ set(["product"], "artwork-scale-factor", .syscfg("arsf")),+ set(["product"], "assistant", .syscfg("assi")),+ set(["product"], "builtin-mics", .syscfg("mics")),+ set(["product"], "car-integration", .integer(1)),+ set(["product"], "carplay-2", .syscfg("car2")),+ set(["product"], "chrome-identifier", .syscfg("crid")),+ set(["product"], "compatible-device-fallback", .syscfg("codf")),+ set(["product"], "device-perf-memory-class", .integer(8)),+ set(["product"], "dictation", .syscfg("dict")),+ set(["product"], "display-corner-radius", .syscfg("dcrd")),+ set(["product"], "display-mirroring", .syscfg("dimi")),+ set(["product"], "ephemeral-data-mode", .integer(0)),+ set(["product"], "fdr-product-type", .string("iPhone99,11")),+ set(["product"], "framebuffer-identifier", .syscfg("fbid")),+ set(["product"], "front-cam-offset-from-center", .syscfg("fcof")),+ set(["product"], "gestalt-variant-id", .syscfg("gvid")),+ set(["product"], "hme-in-arkit", .syscfg("hmei")),+ set(["product"], "island-notch-location", .syscfg("isnl")),+ set(["product"], "jetsam-properties-product-type", .syscfg("jppt")),+ set(["product"], "large-format-phone", .syscfg("larg")),+ set(["product"], "location-reminders", .syscfg("lore")),+ set(["product"], "offline-dictation", .syscfg("odct")),+ set(["product"], "oled-display", .syscfg("oled")),+ set(["product"], "product-description", .syscfg("prde")),+ set(["product"], "product-id", .bytes(Data(base64Encoded: "UT13EFwE1E/xcpFIvIZC6UYOjpc=")!)),+ set(["product"], "product-name", .syscfg("prde")),+ set(["product"], "rear-cam-offset-from-center", .syscfg("rcof")),+ set(["product"], "side-button-location", .syscfg("sblo")),+ set(["product"], "siri-gesture", .syscfg("sige")),+ set(["product"], "sub-product-type", .string("iPhone99,11")),+ set(["product"], "supports-recoveryos", .integer(1)),+ set(["product"], "sw-pro-res", .integer(1)),+ set(["product"], "thin-bezel", .syscfg("thin")),+ set(["product"], "thinning-product-type", .syscfg("tprt")),+ set(["product"], "ui-background-quality", .syscfg("uiba")),+ set(["product"], "ui-pip", .syscfg("uipi")),+ set(["product"], "ui-reachability", .syscfg("uire")),+ set(["product"], "ui-weather-quality", .syscfg("uiwe")),+ set(["product"], "unique-model", .string("VPHONE600AP")),+ set(["product"], "variant-name", .syscfg("vana")),+ set(["product"], "vm-supports-generative-models", .syscfg("vsgm")),+ set(["product"], "volume-down-button-location", .syscfg("vdbl")),+ set(["product"], "volume-up-button-location", .syscfg("vubl")),+ set(["product"], "watch-companion", .syscfg("waco")),+ set(["product", "maps"], "3d-imagery", .syscfg("3dim")),+ set(["product", "maps"], "3d-maps", .syscfg("3dma")),+ set(["product", "maps"], "navigation", .syscfg("navi")),+ set(["product", "haptics"], "closed-loop", .integer(1)),+ set(["product", "haptics"], "supports-3rd-party-haptics", .integer(1)),+ set(["product", "usb-device"], "product-string", .string("iPhone Research Environment Virtual Machine")),++ // MARK: Gestalt Variant+ //+ // The values the placeholders above resolve to on this variant.++ set(["product", "vphone600-gestalt-variants"], "compatible", .string("gestalt-variant-list")),+ set(variant, "tag-3dim", .integer(0)),+ set(variant, "tag-3dma", .integer(0)),+ set(variant, "tag-WMac", .integer(0)),+ set(variant, "tag-ards", .integer(2556)),+ set(variant, "tag-arsf", .integer(3)),+ set(variant, "tag-assi", .integer(1)),+ set(variant, "tag-bumi", .integer(1)),+ set(variant, "tag-car2", .integer(1)),+ set(variant, "tag-codf", .string("iPhone17,3")),+ set(variant, "tag-crid", .string("com.apple.dt.devicekit.chrome.phone11")),+ set(variant, "tag-dcrd", .bytes(Data(base64Encoded: "NwAAAAEAAAA=")!)),+ set(variant, "tag-dict", .integer(1)),+ set(variant, "tag-dimi", .integer(1)),+ set(variant, "tag-fbid", .string("A6AC96E7-C5D3-47A6-8967-A8B2D02F1C66")),+ set(variant, "tag-fcof", .bytes(Data(base64Encoded: "YQABAJIcAADYEwAA6AMAAAAAAAA=")!)),+ set(variant, "tag-gvid", .integer(134_369_303)),+ set(variant, "tag-hmei", .integer(1)),+ set(variant, "tag-home", .integer(2)),+ set(variant, "tag-isnl", .integer(144)),+ set(variant, "tag-jppt", .string("D47")),+ set(variant, "tag-ketp", .integer(6144)),+ set(variant, "tag-kmtp", .integer(0x0D30)),+ set(variant, "tag-larg", .integer(0)),+ set(variant, "tag-lore", .integer(1)),+ set(variant, "tag-mics", .integer(1)),+ set(variant, "tag-navi", .integer(0)),+ set(variant, "tag-odct", .integer(1)),+ set(variant, "tag-oled", .integer(1)),+ set(variant, "tag-prde", .string("iPhone 16 Research Device")),+ set(variant, "tag-rcof", .bytes(Data(base64Encoded: "7aUAALJWAABZCAAA6AMAAAAAAAA=")!)),+ set(variant, "tag-rgen", .empty),+ set(variant, "tag-sblo", .bytes(Data(base64Encoded: "Ou4JAF6HFQDulwYANrMCABAnAAA=")!)),+ set(variant, "tag-sige", .integer(1)),+ set(variant, "tag-thin", .integer(1)),+ set(variant, "tag-tprt", .string("iPhone17,3")),+ set(variant, "tag-uiba", .integer(0x64)),+ set(variant, "tag-uipi", .integer(1)),+ set(variant, "tag-uire", .integer(1)),+ set(variant, "tag-uiwe", .integer(0x64)),+ set(variant, "tag-vana", .string("D47VM2025VRE")),+ set(variant, "tag-vdbl", .bytes(Data(base64Encoded: "Ou4JAF6HFQAXLAgAgLUBABAnAAA=")!)),+ set(variant, "tag-vsgm", .integer(1)),+ set(variant, "tag-vubl", .bytes(Data(base64Encoded: "Ou4JAF6HFQBxAQYAgLUBABAnAAA=")!)),+ set(variant, "tag-waco", .integer(1)),+ set(variant, "valid-tags", .bytes(Data(base64Encoded: "ZGl2Z29sYnNmb2NmZm9jcmRyY2RncmFsYWJpdWVyaXVpcGl1dm9pdWVnaXNpZW1oZXJvbGV3aXVpbXVidGNpZHRjZG9pc3NhbmlodGRlbG9lZHJwZnNyYXNkcmFmZG9jYW5hdmVtb2hvY29yc2NpbWltaWRsYnV2bGJkdmNhTVdhbWQzbWlkMzJyYWNvY2F3cHRta3B0ZWt0cnB0ZGlyY2RpYmZuZWdydHBwaml2YW5sbnNpbWdzdg==")!)),+ ]+ }()++ // MARK: - Detection++ /// Whether `root` is the research board's tree, by its root `target-type`.+ static func isResearchBoardTree(_ root: DTNode) -> Bool {+ guard let targetType = root.properties.first(where: { $0.name == "target-type" }) else { return false }+ return String(decoding: targetType.value.prefix { $0 != 0 }, as: UTF8.self) == "VRESEARCH101"+ }++ // MARK: - Conversion++ /// Rewrites a research board tree as vphone600 and records one change.+ /// Leaves any other tree alone, so a cloudOS that has vphone600 components+ /// records nothing.+ func applyResearchBoardConversion(root: DTNode) throws {+ let patchID = FirmwareResearchBoardPatchSet.deviceTreeConversion+ guard convertsResearchBoard, Self.isResearchBoardTree(root), gateAllows(patchID) else { return }++ func node(_ path: [String]) throws -> DTNode {+ try resolveNode(root, path: ["device-tree"] + path)+ }++ var removed = 0+ for (path, name) in Self.researchBoardRemovals {+ let target = try node(path)+ let before = target.properties.count+ target.properties.removeAll { $0.name == name }+ removed += before - target.properties.count+ }++ var phandle = Self.maximumPhandle(in: root)+ var added = 0+ for spec in Self.researchBoardNodes {+ let parent = try node(spec.parent)+ guard !parent.children.contains(where: { Self.name(of: $0) == spec.name }) else { continue }+ phandle += 1+ let child = DTNode()+ child.properties = [+ DTProperty(name: "name", flags: 0, value: Self.researchBoardEncoding(.string(spec.name)), valueOffset: 0),+ DTProperty(name: "AAPL,phandle", flags: 0, value: Self.researchBoardEncoding(.integer(phandle)), valueOffset: 0),+ ]+ // After its vphone600 sibling, or last when a release has none.+ var index = 0+ if let after = spec.after {+ index = parent.children.firstIndex { Self.name(of: $0) == after }.map { $0 + 1 } ?? parent.children.count+ }+ parent.children.insert(child, at: index)+ added += 1+ }++ for spec in Self.researchBoardProperties {+ let target = try node(spec.path)+ let value = Self.researchBoardEncoding(spec.value)+ let flags: UInt16 = if case .syscfg = spec.value { Self.placeholderFlag } else { 0 }+ if let existing = target.properties.first(where: { $0.name == spec.name }) {+ existing.value = value+ existing.flags = flags+ } else {+ target.properties.append(DTProperty(name: spec.name, flags: flags, value: value, valueOffset: 0))+ }+ }++ patches.append(PatchRecord(+ patchID: patchID,+ component: component,+ fileOffset: 0,+ virtualAddress: nil,+ originalBytes: Data(),+ patchedBytes: Data(),+ description: "Convert the vresearch101 device tree into vphone600",+ ))+ if verbose {+ print(" vresearch101 → vphone600: \(added) nodes added, \(Self.researchBoardProperties.count) properties set, \(removed) removed [\(patchID)]")+ }+ }++ // MARK: - Helpers++ static func researchBoardEncoding(_ value: ResearchBoardValue) -> Data {+ func cString(_ text: String) -> Data {+ Data(text.utf8) + [0]+ }+ return switch value {+ case let .string(text): cString(text)+ case let .strings(texts): texts.map(cString).reduce(Data(), +)+ case let .integer(number): withUnsafeBytes(of: number.littleEndian) { Data($0) }+ case let .bytes(data): data+ case let .syscfg(key): cString("syscfg/" + key)+ case .empty: Data()+ }+ }++ private static func name(of node: DTNode) -> String {+ guard let property = node.properties.first(where: { $0.name == "name" }) else { return "" }+ return String(decoding: property.value.prefix { $0 != 0 }, as: UTF8.self)+ }++ private static func maximumPhandle(in node: DTNode) -> UInt32 {+ let own = node.properties.first { $0.name == "AAPL,phandle" && $0.value.count == 4 }+ .map { $0.value.withUnsafeBytes { UInt32(littleEndian: $0.loadUnaligned(as: UInt32.self)) } } ?? 0+ return node.children.map(maximumPhandle(in:)).reduce(own, max)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swiftindex 756f06c5..9ce1adf3 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Manifest/FirmwareManifest.swift@@ -76,12 +76,20 @@ public enum FirmwareManifest {// per board it covers, so the userland one is picked by board.let device = chosen ?? VPhoneGuestDevice.detect(buildManifest: iPhoneBM) ?? .defaultlet (prod, res) = try findCloudOS(cloudIdentities, deviceClass: "vresearch101ap")- let (vp, vpr) = try findCloudOS(cloudIdentities, deviceClass: "vphone600ap")+ // Only the 26.1–26.4 beta cloudOS releases carry vphone600ap. Every other+ // one boots the research board's own device tree and SEP, which+ // `fw patch` converts (FirmwareResearchBoardPatchSet).+ let vphone = try? findCloudOS(cloudIdentities, deviceClass: "vphone600ap")+ let (vp, vpr) = vphone ?? (prod, res)let iErase = try findIPhoneErase(iPhoneIdentities, deviceClass: device.deviceClass)if verbose {print(" cloudOS vresearch101ap: release=#\(prod), research=#\(res)")- print(" cloudOS vphone600ap: release=#\(vp), research=#\(vpr)")+ if vphone == nil {+ print(" cloudOS vphone600ap: none, the research board stands in")+ } else {+ print(" cloudOS vphone600ap: release=#\(vp), research=#\(vpr)")+ }print(" \(device.productType) erase: #\(iErase)")}@@ -381,8 +389,10 @@ public enum FirmwareManifest {m["KernelCache"] = try entry(C, vpr, "KernelCache") // researchm["RestoreKernelCache"] = try entry(C, vp, "RestoreKernelCache") // release- // Recovery mode (vphone600ap carries this entry).- m["RecoveryMode"] = try entry(C, vp, "RecoveryMode")+ // Recovery mode, which vphone600ap carries and the research board may not.+ if let recoveryMode = try? entry(C, vp, "RecoveryMode") {+ m["RecoveryMode"] = recoveryMode+ }// CloudOS erase ramdisk.m["RestoreRamDisk"] = try entry(C, prod, "RestoreRamDisk")diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swiftindex 451b8ba2..d0d8c17a 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift@@ -16,6 +16,7 @@ public enum FirmwarePatchSetCatalog {FirmwareKernelCustomFirmwarePatchSet.manifest,FirmwareKernelHypervisorPatchSet.manifest,FirmwareKernelFridaPatchSet.manifest,+ FirmwareResearchBoardPatchSet.manifest,FirmwareDeviceTreePatchSet.manifest,FirmwareGuestSystemPatchSet.manifest,FirmwareGuestDisplayPatchSet.manifest,@@ -350,12 +351,14 @@ public enum FirmwarePatchSetCatalog {summary: "No kernel or TXM patches and only iBEC and LLB in the boot chain: the restore installs a resealed system with vphoned, the GPU driver and activation, and nothing writes it afterwards.",patchSets: [.bundled(FirmwareBootChainPatchSet.identifier),+ .bundled(FirmwareResearchBoardPatchSet.identifier),.bundled(FirmwareDeviceTreePatchSet.identifier),.bundled(FirmwareRestoreImagePatchSet.identifier),],selection: .allow(minimalBootChainPatches.union(minimalDeviceTreePatches)+ .union(FirmwareResearchBoardPatchSet.manifest.patches.map(\.identifier)).union(FirmwareRestoreImagePatchSet.manifest.patches.map(\.identifier)),),)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareResearchBoardPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareResearchBoardPatchSet.swiftnew file mode 100644index 00000000..fd3a8e91--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareResearchBoardPatchSet.swift@@ -0,0 +1,38 @@+// FirmwareResearchBoardPatchSet.swift — Manifest for the research board fallback.+//+// The guest boots the vphone600 device tree and SEP firmware, but only the+// 26.1–26.4 beta cloudOS releases carry a vphone600ap identity. Every other+// cloudOS ships the research board alone, vresearch101ap, and `fw prepare` then+// takes its components instead (`FirmwareManifest.generate`). The patches here+// turn those into what vphone600 would have been.+//+// Every shipped preset names this set. Its patches only write where they find+// the research board, so on a cloudOS with vphone600 components they record+// nothing: the fallback costs the other presets nothing and needs no version+// gate. They are boot-essential where they apply.++import Foundation+import VPhonePatchKit++public enum FirmwareResearchBoardPatchSet {+ public static let identifier = "com.vphone.patchset.research.board"++ /// The research board's device tree, rewritten as the vphone600 one.+ public static let deviceTreeConversion = "devicetree-boot-vresearch101_conversion"++ public static let manifest = VPhonePatchSetManifest(+ identifier: identifier,+ name: "Research Board",+ summary: "Converts a cloudOS without vphone600 components from the research board",+ patches: [+ VPhonePatchDeclaration(+ identifier: deviceTreeConversion,+ title: "vphone600 device tree",+ summary: "Gives the research board's device tree the vphone600 identity, product properties and nodes, so a cloudOS without vphone600ap boots an iPhone userland. Runs before every other device tree patch.",+ target: .firmware(.deviceTree),+ bootEssential: true,+ ),+ ],+ provides: ["vphone.research.board"],+ )+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swiftindex a1cbe9c1..0a60ccd9 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift@@ -314,11 +314,19 @@ extension FirmwarePipeline {// properties so the guest presents a consistent iPhone17,3 identity.// A guest that presents its board restores with this tree and boots// its own copy (7b).+ // The tree is vphone600's, or the research board's on a cloudOS+ // without vphone600 components, which the patcher converts first+ // (FirmwareResearchBoardPatchSet). `RestoreDeviceTree` names it either+ // way; `DeviceTree` names the board's copy (7b). A tree whose manifest+ // names none (catalogue tests) keeps vphone600's.let dtIncludeIdentity = variant == .jb || variant == .exp+ let convertsResearchBoard = includesSet(FirmwareResearchBoardPatchSet.identifier)+ let deviceTreePath = (try? Self.manifestComponentPath("RestoreDeviceTree", in: restoreDir))+ ?? "Firmware/all_flash/DeviceTree.vphone600ap.im4p"components.append(ComponentDescriptor(name: "DeviceTree",inRestoreDir: true,- searchPatterns: ["Firmware/all_flash/DeviceTree.vphone600ap.im4p"],+ searchPatterns: [deviceTreePath],patcherFactories: includeDeviceTree ? [{ data, verbose inlet p = DeviceTreePatcher(data: data,@@ -328,6 +336,7 @@ extension FirmwarePipeline {role: hasGuestTree ? .restore : .shared,)p.gate = gate+ p.convertsResearchBoard = convertsResearchBoardreturn p}] : [],))@@ -352,6 +361,7 @@ extension FirmwarePipeline {sourceTree: self.loader.load(from: self.pristineInput(for: boardTreeURL).url),)p.gate = gate+ p.convertsResearchBoard = convertsResearchBoardreturn p}] : [],))diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeResearchBoardTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeResearchBoardTests.swiftnew file mode 100644index 00000000..21c29a70--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeResearchBoardTests.swift@@ -0,0 +1,199 @@+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++/// The vresearch101 → vphone600 conversion: against a small research board+/// tree, and against Apple's own pair of trees when an IPSW in `ipsws/`+/// carries both.+@Suite("Device tree research board conversion")+struct DeviceTreeResearchBoardTests {+ // MARK: - Fixture++ static func string(_ text: String) -> Data {+ Data((text + "\0").utf8)+ }++ static func phandle(_ number: UInt32) -> (String, Data) {+ ("AAPL,phandle", FlatDeviceTreeNode.uint32(number))+ }++ static func researchTree(targetType: String = "VRESEARCH101") -> Data {+ FlatDeviceTreeNode("device-tree", [+ ("target-type", string(targetType)),+ ("model", string("ComputeModule14,2")),+ phandle(1),+ ], children: [+ FlatDeviceTreeNode("filesystems", [phandle(2)]),+ FlatDeviceTreeNode("arm-io", [phandle(3)], children: [+ FlatDeviceTreeNode("uart0", [phandle(4)]),+ FlatDeviceTreeNode("gfx", [phandle(5), ("interrupt-parent", FlatDeviceTreeNode.uint32(4))]),+ FlatDeviceTreeNode("cpu-debug-interface", [phandle(6)]),+ FlatDeviceTreeNode("sep", [phandle(7)]),+ ]),+ FlatDeviceTreeNode("defaults", [+ phandle(8),+ ("pmap-max-asids", FlatDeviceTreeNode.uint32(4)),+ ("serial-device", FlatDeviceTreeNode.uint32(4)),+ ]),+ FlatDeviceTreeNode("product", [phandle(9), ("kernel-core-dump-location", string("x"))], children: [+ FlatDeviceTreeNode("usb-device", [phandle(10)]),+ ]),+ ]).serialized+ }++ /// Only the conversion on, so the vphone600 patches that follow it do not+ /// need their properties in this small tree.+ static let conversionOnly = VPhonePatchGate(+ declared: Set((FirmwareResearchBoardPatchSet.manifest.patches + FirmwareDeviceTreePatchSet.manifest.patches).map(\.identifier)),+ enabled: [FirmwareResearchBoardPatchSet.deviceTreeConversion],+ )++ static func convert(_ data: Data, converting: Bool = true) throws -> (DeviceTreePatcher, DeviceTreePatcher.DTNode, [PatchRecord]) {+ let patcher = DeviceTreePatcher(data: data, verbose: false)+ patcher.gate = conversionOnly+ patcher.convertsResearchBoard = converting+ let records = try patcher.findAll()+ return (patcher, try patcher.parsePayload(patcher.patchedData), records)+ }++ static func name(_ node: DeviceTreePatcher.DTNode) -> String {+ String(decoding: (node.properties.first { $0.name == "name" }?.value ?? Data()).prefix { $0 != 0 }, as: UTF8.self)+ }++ static func value(_ node: DeviceTreePatcher.DTNode, _ property: String) -> Data? {+ node.properties.first { $0.name == property }?.value+ }++ // MARK: - Small Tree++ @Test("A research board tree becomes vphone600, with new nodes in vphone600's places")+ func convertsResearchBoard() throws {+ let (patcher, root, records) = try Self.convert(Self.researchTree())+ #expect(records.map(\.patchID) == [FirmwareResearchBoardPatchSet.deviceTreeConversion])+ #expect(Self.value(root, "target-type") == Self.string("VPHONE600"))+ #expect(Self.value(root, "model") == Self.string("iPhone99,11"))++ #expect(root.children.map(Self.name) == ["buttons", "filesystems", "arm-io", "defaults", "product"])+ let armIO = try patcher.resolveNode(root, path: ["device-tree", "arm-io"])+ #expect(armIO.children.map(Self.name) == ["uart0", "gfx", "multi-touch", "cpu-debug-interface", "bluetooth", "sep"])+ let product = try patcher.resolveNode(root, path: ["device-tree", "product"])+ #expect(product.children.map(Self.name) == ["vphone600-gestalt-variants", "maps", "haptics", "usb-device"])++ let defaults = try patcher.resolveNode(root, path: ["device-tree", "defaults"])+ #expect(Self.value(defaults, "pmap-max-asids") == nil)+ #expect(Self.value(product, "kernel-core-dump-location") == nil)+ let placeholder = try #require(product.properties.first { $0.name == "artwork-device-subtype" })+ #expect(placeholder.flags == DeviceTreePatcher.placeholderFlag)+ #expect(placeholder.value == Self.string("syscfg/ards"))+ }++ @Test("Existing phandles and the references to them are kept; new nodes get unused ones")+ func keepsPhandles() throws {+ let (patcher, root, _) = try Self.convert(Self.researchTree())+ let gfx = try patcher.resolveNode(root, path: ["device-tree", "arm-io", "gfx"])+ #expect(Self.value(gfx, "AAPL,phandle") == FlatDeviceTreeNode.uint32(5))+ #expect(Self.value(gfx, "interrupt-parent") == FlatDeviceTreeNode.uint32(4))++ var phandles: [Data] = []+ func collect(_ node: DeviceTreePatcher.DTNode) {+ phandles += node.properties.filter { $0.name == "AAPL,phandle" }.map(\.value)+ node.children.forEach(collect)+ }+ collect(root)+ #expect(phandles.count == 17)+ #expect(Set(phandles).count == phandles.count)+ }++ @Test("A vphone600 tree, or a preset without the set, is left alone")+ func leavesOtherTreesAlone() throws {+ let vphone = Self.researchTree(targetType: "VPHONE600")+ let (_, _, records) = try Self.convert(vphone)+ #expect(records.isEmpty)++ let research = Self.researchTree()+ let (patcher, _, unconverted) = try Self.convert(research, converting: false)+ #expect(unconverted.isEmpty)+ #expect(patcher.patchedData == research)+ }++ // MARK: - Apple's Trees++ static let repoRoot = URL(fileURLWithPath: #filePath)+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ .deletingLastPathComponent()++ static let researchEntry = "Firmware/all_flash/DeviceTree.vresearch101ap.im4p"+ static let vphoneEntry = "Firmware/all_flash/DeviceTree.vphone600ap.im4p"++ /// The cloudOS IPSWs in `ipsws/` with both trees: 26.1 to the 26.4 beta.+ static var pairedIPSWs: [URL] {+ let candidates = (try? FileManager.default.contentsOfDirectory(+ at: repoRoot.appending(path: "ipsws"),+ includingPropertiesForKeys: nil,+ )) ?? []+ return candidates.filter { candidate in+ guard candidate.pathExtension == "ipsw" else { return false }+ let listing = (try? CustomFirmwarePatchFixtures.run("/usr/bin/unzip", ["-l", candidate.path, researchEntry, vphoneEntry]))?.output ?? ""+ return listing.contains(researchEntry) && listing.contains(vphoneEntry)+ }+ }++ /// Every property as `path name flags value`, with phandles left out and+ /// phandle references given as the path they name: the two trees number+ /// their nodes differently.+ static func describe(_ root: DeviceTreePatcher.DTNode) -> Set<String> {+ var paths: [Data: String] = [:]+ var nodes: [(String, DeviceTreePatcher.DTNode)] = []+ func walk(_ node: DeviceTreePatcher.DTNode, _ path: String) {+ nodes.append((path, node))+ if let phandle = value(node, "AAPL,phandle") { paths[phandle] = path }+ var seen: [String: Int] = [:]+ for child in node.children {+ let childName = name(child)+ let index = seen[childName, default: 0]+ seen[childName] = index + 1+ walk(child, path + "/" + childName + (index > 0 ? "#\(index)" : ""))+ }+ }+ walk(root, "")+ let references: Set<String> = ["interrupt-parent", "device-interrupt-parent", "serial-device"]+ var lines = Set<String>()+ for (path, node) in nodes {+ for property in node.properties where property.name != "AAPL,phandle" && property.name != "time-stamp" {+ let shown = references.contains(property.name)+ ? "-> " + (paths[property.value] ?? "dangling")+ : property.value.map { String(format: "%02x", $0) }.joined()+ lines.insert("\(path) \(property.name) \(property.flags) \(shown)")+ }+ }+ return lines+ }++ @Test(+ "Apple's research board tree converts into Apple's vphone600 tree of the same release",+ .enabled(if: !pairedIPSWs.isEmpty, "needs a cloudOS IPSW with both device trees in ipsws/"),+ )+ func matchesApplesTree() throws {+ for ipsw in Self.pairedIPSWs {+ let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ let result = try CustomFirmwarePatchFixtures.run("/usr/bin/unzip", ["-o", "-j", ipsw.path, Self.researchEntry, Self.vphoneEntry, "-d", directory.path])+ try #require(result.status == 0)++ let research = try IM4PHandler.load(contentsOf: directory.appending(path: "DeviceTree.vresearch101ap.im4p")).payload+ let vphone = try IM4PHandler.load(contentsOf: directory.appending(path: "DeviceTree.vphone600ap.im4p")).payload+ let (_, converted, _) = try Self.convert(research)+ let (_, expected, _) = try Self.convert(vphone)++ let produced = Self.describe(converted)+ let apple = Self.describe(expected)+ #expect(produced.subtracting(apple).sorted() == [], "\(ipsw.lastPathComponent): not in vphone600")+ #expect(apple.subtracting(produced).sorted() == [], "\(ipsw.lastPathComponent): missing from the conversion")+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swiftindex 6bccc0e4..be127344 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift@@ -172,7 +172,7 @@ struct FirmwarePatchSetCatalogTests {}@Test- func `Only minimal names the restore image, and patches only iBEC, LLB and the device tree besides`() throws {+ func `Only minimal names the restore image, and patches only iBEC, LLB, the device tree and the research board besides`() throws {for preset in FirmwarePatchSetCatalog.builtInPresets {let namesRestoreImage = preset.patchSets.map(\.identifier).contains(FirmwareRestoreImagePatchSet.identifier)#expect(namesRestoreImage == (preset.identifier == VPhonePatchPreset.minimalIdentifier), "\(preset.identifier)")@@ -185,7 +185,8 @@ struct FirmwarePatchSetCatalogTests {)let restoreImage = Set(FirmwareRestoreImagePatchSet.manifest.patches.map(\.identifier))let bootChain = FirmwarePatchSetCatalog.minimalBootChainPatches- #expect(plan.enabled == restoreImage.union(FirmwarePatchSetCatalog.minimalDeviceTreePatches).union(bootChain))+ let researchBoard = Set(FirmwareResearchBoardPatchSet.manifest.patches.map(\.identifier))+ #expect(plan.enabled == restoreImage.union(FirmwarePatchSetCatalog.minimalDeviceTreePatches).union(bootChain).union(researchBoard))#expect(plan.droppedBootEssentials.allSatisfy { !$0.hasPrefix("ibec-") && !$0.hasPrefix("llb-") })}diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plistindex 0f010786..58ec8c65 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist@@ -56,6 +56,12 @@<key>Identifier</key><string>com.vphone.patchset.kernel.frida</string></dict>+ <dict>+ <key>Kind</key>+ <string>Bundled</string>+ <key>Identifier</key>+ <string>com.vphone.patchset.research.board</string>+ </dict><dict><key>Kind</key><string>Bundled</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plistindex bb848486..e86143b6 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist@@ -12,6 +12,12 @@<key>Kind</key><string>Bundled</string></dict>+ <dict>+ <key>Identifier</key>+ <string>com.vphone.patchset.research.board</string>+ <key>Kind</key>+ <string>Bundled</string>+ </dict><dict><key>Identifier</key><string>com.vphone.patchset.devicetree</string>@@ -31,6 +37,7 @@<string>Allow</string><key>Patches</key><array>+ <string>devicetree-boot-vresearch101_conversion</string><string>devicetree-cfw-artwork_device_subtype</string><string>devicetree-cfw-home_button_type</string><string>devicetree-cfw-island_notch_location</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plistindex 52f8f095..dcd65f88 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist@@ -36,6 +36,12 @@<key>Kind</key><string>Bundled</string></dict>+ <dict>+ <key>Identifier</key>+ <string>com.vphone.patchset.research.board</string>+ <key>Kind</key>+ <string>Bundled</string>+ </dict><dict><key>Identifier</key><string>com.vphone.patchset.devicetree</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plistindex d5e25429..2c8f85e2 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist@@ -36,6 +36,12 @@<key>Kind</key><string>Bundled</string></dict>+ <dict>+ <key>Identifier</key>+ <string>com.vphone.patchset.research.board</string>+ <key>Kind</key>+ <string>Bundled</string>+ </dict><dict><key>Identifier</key><string>com.vphone.patchset.devicetree</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plistindex 00fbb819..4d8d5bc9 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist@@ -36,6 +36,12 @@<key>Kind</key><string>Bundled</string></dict>+ <dict>+ <key>Identifier</key>+ <string>com.vphone.patchset.research.board</string>+ <key>Kind</key>+ <string>Bundled</string>+ </dict><dict><key>Identifier</key><string>com.vphone.patchset.devicetree</string>