Run a virtual iPhone on an Apple Silicon Mac.
Swift
Drop the guest's MobileGestalt cache when a tree repair changed it
Jacky59601eb60c8f
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 1d5e58e6..60dfb872 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -2226,7 +2226,7 @@ virtio sound device with a host output sink. Two faults; the full reveal is| `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`. || `devicetree-cfw-ipad_haptics` (new, 2026-10-03) | An iPad guest's installed DeviceTree, `fw patch` | Makes `/product/haptics` what the board tree has (`DeviceTreePatcher.presentBoardHaptics`): removed for every iPad so far, none of which has the node. |-| `preboot-cfw-devicetree_board_haptics` (new, 2026-10-03) | Restored Preboot `devicetree.img4`, `cfw install` and `cfw update-environment` | The same change for an iPad VM patched before it (`vphone-cli cfw patch-dt-board-haptics`), from the board tree in `FirmwareOriginals`. An existing guest also needs its MobileGestalt cache dropped once, see below. |+| `preboot-cfw-devicetree_board_haptics` (new, 2026-10-03) | Restored Preboot `devicetree.img4`, `cfw install` and `cfw update-environment` | The same change for an iPad VM patched before it (`vphone-cli cfw patch-dt-board-haptics`), from the board tree in `FirmwareOriginals`. When it changes the tree, the installer also removes the guest's cached MobileGestalt answers, see below. |`fw patch` now reads an iPad's board tree through the `FirmwareOriginals` stash,so `DeviceTree.<board>.im4p` stays in the VM folder after the restore tree goes.@@ -2243,9 +2243,16 @@ starts although its route and audio queue are built. Without the node theguest answers as the iPad does and tones play. The answers are cached in`/private/var/containers/Shared/SystemGroup/systemgroup.com.apple.mobilegestaltcache/Library/Caches/com.apple.MobileGestalt.plist`,written at first boot, so a guest that has already booted keeps the old ones-until that file is removed and the guest restarted (`files.remove`, then-`system.reboot`); a guest created with the patch never has them. Detail and-the measurements: `Research/Guest/virtio_sound.md` §7.+until that file is removed and the guest restarted; a guest created with the+patch never has them. `cfw install` and `cfw update-environment` remove the+file from the mounted Data volume whenever a Preboot board repair (haptics or+audio) changed the tree, and log `[+] MobileGestalt cache removed`; a repair+that found the tree already matching removes nothing. This is part of those+two repairs rather than a declaration of its own: it writes no patch, runs+only when one of them changed the tree, and turning a repair off already+turns it off. Removing it by hand (`files.remove`, then `system.reboot`)+remains the fallback for a tree changed any other way. Detail and the+measurements: `Research/Guest/virtio_sound.md` §7.**Why a plugin.** The cloudOS kernel has `AppleVirtIOSound` and its user client,but only macOS ships the HAL plugin that drives it; neither cloudOS nor any iOSdiff --git a/Research/Guest/virtio_sound.md b/Research/Guest/virtio_sound.mdindex e9d4fe5e..ee53cf25 100644--- a/Research/Guest/virtio_sound.md+++ b/Research/Guest/virtio_sound.md@@ -272,6 +272,14 @@ never do.### The fix+> **Superseded (2026-10-03).** Do not store this value. The plugin now+> supplies `ProductIDOverride = 8010` in-process on an iPad guest when nothing+> is stored (§6, "Nothing left to set by hand"), and a stored value wins over+> it. 198 has no ringtone-preview category, so with it tones stay silent. A+> guest that still carries a stored 198 should have it deleted:+> `settings.delete` with domain `com.apple.audio.virtualaudio`, key+> `ProductIDOverride`. What follows is how the override was found.+```vphone-launchpad-cli guest rpc <machine> settings.set \'{"domain":"com.apple.audio.virtualaudio","key":"ProductIDOverride","value":198,"type":"int"}'@@ -517,9 +525,22 @@ vphone-launchpad-cli guest rpc <machine> files.remove \vphone-launchpad-cli guest rpc <machine> system.reboot '{"force":true}'```-A guest created with the patch never caches the wrong answers. An existing one-needs this once after the environment update; nothing does it automatically-yet.+A guest created with the patch never caches the wrong answers. For an existing+one the installer now does the removal: when a Preboot board repair+(`preboot-cfw-devicetree_board_haptics` or+`preboot-cfw-devicetree_board_audio`) changes the device+tree during `cfw install` or `cfw update-environment`, it deletes that file+from the mounted Data volume (`CustomFirmwareMobileGestaltCache`, through the+same descriptor-relative access as every other guest write) and prints++```+ [+] MobileGestalt cache removed; the guest rebuilds it from the new device tree at next boot+```++The guest's next boot is then enough. A repair that finds the tree already+matching the board removes nothing, and a guest that never booted has no file+and gets no line. The two commands above remain the way to do it by hand, for+a guest whose tree was changed some other way.**Verified** (`audiotest-ipad`): after the cache was rebuilt the Ringtone pagehas no Haptics row, mediaplaybackd makes no hapticd connection, and a tonediff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMobileGestaltCache.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMobileGestaltCache.swiftnew file mode 100644index 00000000..d305b0aa--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMobileGestaltCache.swift@@ -0,0 +1,35 @@+// CustomFirmwareMobileGestaltCache.swift — drop the guest's cached MobileGestalt answers.+//+// libMobileGestalt answers most device questions from the device tree, and at+// first boot it writes those answers to a cache on the Data volume. It reads+// the cache from then on, so a guest whose Preboot device tree is repaired+// later keeps answering as the old tree did: after the board haptics repair+// removed `/product/haptics`, Settings still showed the Haptics row and tones+// stayed silent until the file was removed and the guest rebooted. Without the+// file, libMobileGestalt computes the answers again from the tree it booted.+//+// `cfw install` and `cfw update-environment` remove it when a board repair+// changed the tree, and only then. See `Research/Guest/virtio_sound.md` §7.++import Foundation+import VPhoneCoreKit++public enum CustomFirmwareMobileGestaltCache {+ /// The cache, relative to the root of the guest's Data volume, which the+ /// guest mounts at `/private/var`.+ public static let path =+ "containers/Shared/SystemGroup/systemgroup.com.apple.mobilegestaltcache/Library/Caches/com.apple.MobileGestalt.plist"++ /// Remove the cache from a mounted Data volume. Returns whether there was+ /// one: a guest that never booted has none, and that is not an error.+ ///+ /// Only a regular file is removed — that is all libMobileGestalt writes.+ /// The walk is descriptor relative, so a link on the way is refused+ /// rather than followed.+ @discardableResult+ public static func remove(fromDataVolume data: VPhoneConfinedDirectory) throws -> Bool {+ guard try data.isRegularFile(path) else { return false }+ try data.removeItem(path)+ return true+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swiftindex a2f103f7..0d4030c3 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift@@ -2,6 +2,7 @@import Foundationimport Testingimport VPhoneCoreKit+import VPhonePatchKit/// The iPad presentation of the vphone600 device tree, against a small tree/// shaped like the shipped one: the root identity, a `/product` node with@@ -92,6 +93,30 @@ struct DeviceTreeGuestDeviceTests {],)+ /// vphone600's `/product/haptics`, which no iPad tree has.+ static let haptics = Node(+ properties: [+ .string("name", "haptics"),+ .integer("closed-loop", 1),+ .integer("supports-3rd-party-haptics", 1),+ .integer("AAPL,phandle", 100),+ ],+ children: [],+ )++ /// `tree` with `/product` children `maps`, then `haptics` when given, then+ /// `util`: the node sits between siblings, as it does on vphone600.+ static func guestTree(haptics: Node?) -> Node {+ let product = tree.children[0]+ let children = [Node(properties: [.string("name", "maps"), .integer("regulatory", 1)], children: [])]+ + (haptics.map { [$0] } ?? [])+ + [Node(properties: [.string("name", "util"), .integer("ramdisk", 0)], children: [])]+ return Node(+ properties: tree.properties,+ children: [Node(properties: product.properties, children: children)] + tree.children.dropFirst(),+ )+ }+/// A board tree shaped like `DeviceTree.j410ap.im4p`: iPad mini (A17 Pro).static func board(model: String = "iPad16,1",@@ -191,6 +216,34 @@ struct DeviceTreeGuestDeviceTests {return read(patcher.patchedData)}+ /// Run the patcher on an iPad's installed tree, returning the tree it+ /// writes and its records.+ static func installed(+ _ guest: Data,+ gate: VPhonePatchGate = .unrestricted,+ ) throws -> (data: Data, records: [PatchRecord]) {+ let patcher = DeviceTreePatcher(+ data: guest, verbose: false, device: .iPad16_1, role: .installed,+ sourceTree: board().serialized(),+ )+ patcher.gate = gate+ let records = try patcher.findAll()+ return (patcher.patchedData, records)+ }++ /// The `name` of each child of the node at `path` in a parsed tree.+ static func childNames(_ node: DeviceTreePatcher.DTNode, at path: [String] = []) -> [String] {+ func name(_ node: DeviceTreePatcher.DTNode) -> String {+ node.properties.first { $0.name == "name" }.map { String(decoding: $0.value.prefix { $0 != 0 }, as: UTF8.self) } ?? ""+ }+ var current = node+ for component in path {+ guard let child = current.children.first(where: { name($0) == component }) else { return [] }+ current = child+ }+ return current.children.map(name)+ }+// MARK: - Tests@Test func `an iPad's installed tree presents the iPad`() throws {@@ -287,6 +340,51 @@ struct DeviceTreeGuestDeviceTests {_ = try twice.findAll()#expect(twice.patchedData == once.patchedData)}++ // MARK: - Haptics++ @Test func `an iPad's installed tree loses the haptics node its board does not have`() throws {+ let guest = Self.guestTree(haptics: Self.haptics).serialized()+ let (patched, records) = try Self.installed(guest)++ #expect(Self.read(patched)["device-tree/product/haptics"] == nil)+ let parser = DeviceTreePatcher(data: Data(), verbose: false)+ let root = try parser.parsePayload(patched)+ #expect(Self.childNames(root) == ["product", "buttons"])+ #expect(Self.childNames(root, at: ["product"]) == ["maps", "util"])++ // The same tree without the node patches to the same bytes: nothing+ // around it moved, and the length is the node's shorter.+ let (without, _) = try Self.installed(Self.guestTree(haptics: nil).serialized())+ #expect(patched == without)+ #expect(guest.count - Self.guestTree(haptics: nil).serialized().count == Self.haptics.serialized().count)++ let haptics = records.filter { $0.patchID == "devicetree-cfw-ipad_haptics" }+ #expect(haptics.count == 1)+ #expect(haptics.first?.originalBytes == Self.haptics.serialized())+ #expect(haptics.first?.patchedBytes.isEmpty == true)+ }++ @Test func `the haptics node stays when its patch is off`() throws {+ let declared = Set(FirmwareDeviceTreePatchSet.manifest.patches.map(\.identifier))+ #expect(declared.contains("devicetree-cfw-ipad_haptics"))+ let gate = VPhonePatchGate(declared: declared, enabled: declared.subtracting(["devicetree-cfw-ipad_haptics"]))+ let (patched, records) = try Self.installed(Self.guestTree(haptics: Self.haptics).serialized(), gate: gate)++ #expect(!records.contains { $0.patchID == "devicetree-cfw-ipad_haptics" })+ let product = try #require(Self.read(patched)["device-tree/product"])+ #expect(Self.string(product["artwork-device-idiom"]) == "pad", "the other iPad edits still apply")+ let root = try DeviceTreePatcher(data: Data(), verbose: false).parsePayload(patched)+ #expect(Self.childNames(root, at: ["product"]) == ["maps", "haptics", "util"])+ #expect(Self.integer(Self.read(patched)["device-tree/product/haptics"]?["closed-loop"]) == 1)+ }++ @Test func `removing the haptics node a second time changes nothing`() throws {+ let (once, _) = try Self.installed(Self.guestTree(haptics: Self.haptics).serialized())+ let (twice, records) = try Self.installed(once)+ #expect(twice == once)+ #expect(!records.contains { $0.patchID == "devicetree-cfw-ipad_haptics" })+ }}private extension Data {diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMobileGestaltCacheTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMobileGestaltCacheTests.swiftnew file mode 100644index 00000000..0f0d049b--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMobileGestaltCacheTests.swift@@ -0,0 +1,113 @@+// CustomFirmwareMobileGestaltCacheTests.swift — the installer drops the guest's cached answers.+//+// `cfw install` and `cfw update-environment` remove the MobileGestalt cache+// from the mounted Data volume after a board repair changed the device tree.+// These run the removal against a scratch folder standing in for that volume.++import Darwin+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhoneCoreKit++@Suite("MobileGestalt cache removal")+struct CustomFirmwareMobileGestaltCacheTests {+ /// A canonical scratch folder: `data/` stands in for the Data volume,+ /// `outside/` for anything a link in it could point at.+ private struct Volume {+ let base: URL+ let data: URL+ let outside: URL++ init() throws {+ let temporary = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)+ guard let resolved = realpath(temporary.path, nil) else { throw POSIXError(.ENOENT) }+ base = URL(fileURLWithPath: String(cString: resolved))+ free(resolved)+ data = base.appendingPathComponent("data")+ outside = base.appendingPathComponent("outside")+ try FileManager.default.createDirectory(at: data, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ }++ var cache: URL {+ data.appendingPathComponent(CustomFirmwareMobileGestaltCache.path)+ }++ func root() throws -> VPhoneConfinedDirectory {+ try VPhoneConfinedDirectory.pin(absolutePath: data.path)+ }++ func remove() {+ try? FileManager.default.removeItem(at: base)+ }+ }++ private static func exists(_ url: URL) -> Bool {+ var metadata = stat()+ return lstat(url.path, &metadata) == 0+ }++ // MARK: - Tests++ @Test func `the cache is removed and its folder kept`() throws {+ let volume = try Volume()+ defer { volume.remove() }+ let caches = volume.cache.deletingLastPathComponent()+ try FileManager.default.createDirectory(at: caches, withIntermediateDirectories: true)+ try Data("cached".utf8).write(to: volume.cache)+ try Data("other".utf8).write(to: caches.appendingPathComponent("other.plist"))++ #expect(try CustomFirmwareMobileGestaltCache.remove(fromDataVolume: volume.root()))+ #expect(!Self.exists(volume.cache))+ #expect(Self.exists(caches.appendingPathComponent("other.plist")))+ }++ @Test func `a guest that never booted has nothing to remove`() throws {+ let volume = try Volume()+ defer { volume.remove() }+ #expect(try !CustomFirmwareMobileGestaltCache.remove(fromDataVolume: volume.root()))++ // The folder without the file, as after a removal in the guest.+ try FileManager.default.createDirectory(+ at: volume.cache.deletingLastPathComponent(),+ withIntermediateDirectories: true,+ )+ #expect(try !CustomFirmwareMobileGestaltCache.remove(fromDataVolume: volume.root()))+ }++ @Test func `a link on the way is refused, not followed`() throws {+ let volume = try Volume()+ defer { volume.remove() }+ // `containers/Shared` points outside the volume, where a file sits at+ // the rest of the cache's path.+ let shared = volume.data.appendingPathComponent("containers/Shared")+ try FileManager.default.createDirectory(+ at: shared.deletingLastPathComponent(),+ withIntermediateDirectories: true,+ )+ try FileManager.default.createSymbolicLink(at: shared, withDestinationURL: volume.outside)+ let rest = CustomFirmwareMobileGestaltCache.path.dropFirst("containers/Shared/".count)+ let target = volume.outside.appendingPathComponent(String(rest))+ try FileManager.default.createDirectory(+ at: target.deletingLastPathComponent(),+ withIntermediateDirectories: true,+ )+ try Data("outside".utf8).write(to: target)++ #expect(throws: VPhoneConfinedDirectoryError.self) {+ try CustomFirmwareMobileGestaltCache.remove(fromDataVolume: volume.root())+ }+ #expect(Self.exists(target))+ }++ @Test func `something other than a file at the path is left`() throws {+ let volume = try Volume()+ defer { volume.remove() }+ try FileManager.default.createDirectory(at: volume.cache, withIntermediateDirectories: true)++ #expect(try !CustomFirmwareMobileGestaltCache.remove(fromDataVolume: volume.root()))+ #expect(Self.exists(volume.cache))+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 900a4aac..a52e4cee 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -276,7 +276,7 @@ struct VPhoneCustomFirmwareInstaller {// full install only. The board audio repair is the exception: an iPad VM// restored before it has no other way to get its audio back, since its// restore tree is gone and `fw patch` does not run again.- try patchPreboot(+ let boardTreeChanged = try patchPreboot(volumes: volumes,work: work,plan: plan,@@ -284,6 +284,15 @@ struct VPhoneCustomFirmwareInstaller {includeIdentity: mode == .full,boardDeviceTree: stageBoardDeviceTree(in: bundleDirectory, work: work),)+ // A guest that has booted keeps the MobileGestalt answers it cached+ // from the old tree, so a repair that changed the tree drops them; one+ // that found the tree already right leaves them be.+ if boardTreeChanged {+ let dataRoot = try openGuestVolume("data", device: "\(container)s3", in: work)+ if try CustomFirmwareMobileGestaltCache.remove(fromDataVolume: dataRoot) {+ print(" [+] MobileGestalt cache removed; the guest rebuilds it from the new device tree at next boot")+ }+ }// The snapshot rename is a full install's alone: it has already been// done on any VM an environment update is allowed to run against, and// this run creates no new snapshot to flip.@@ -1154,6 +1163,9 @@ struct VPhoneCustomFirmwareInstaller {/// only the board audio and haptics repairs. `boardDeviceTree` is the/// iPad's own device tree, staged from the VM's `FirmwareOriginals`, or nil/// for an iPhone guest or a VM patched before `fw patch` kept it.+ ///+ /// Returns whether a board repair changed the device tree, which leaves+ /// the guest's cached MobileGestalt answers stale.private func patchPreboot(volumes: [[String: Any]],work: WorkDirectory,@@ -1161,7 +1173,7 @@ struct VPhoneCustomFirmwareInstaller {guestDevice: VPhoneGuestDevice,includeIdentity: Bool,boardDeviceTree: URL?,- ) throws {+ ) throws -> Bool {// Like every guest patch, a VM with no plan still gets it — except the// identity rewrite on an iPad guest, whose installed tree already// carries its own identity from `fw patch`; the rewrite would turn it@@ -1187,7 +1199,7 @@ struct VPhoneCustomFirmwareInstaller {(FirmwareGuestSystemPatchSet.prebootBoardAudio, "patch-dt-board-audio"),(FirmwareGuestSystemPatchSet.prebootBoardHaptics, "patch-dt-board-haptics"),].filter { on($0.0) }.map(\.1)- guard rewriteIdentity || !boardVerbs.isEmpty || !(spoofBuild ?? "").isEmpty else { return }+ guard rewriteIdentity || !boardVerbs.isEmpty || !(spoofBuild ?? "").isEmpty else { return false }guardlet preboot = volumes.first(where: { ($0["Roles"] as? [String])?.contains("Preboot") == true }),let device = preboot["DeviceIdentifier"] as? String@@ -1215,9 +1227,12 @@ struct VPhoneCustomFirmwareInstaller {if rewriteIdentity {try patchCopy(of: deviceTree, in: root, work: work, verb: "patch-post-restore-dt")}+ var boardTreeChanged = falseif let boardDeviceTree {for verb in boardVerbs {- try patchCopy(of: deviceTree, in: root, work: work, verb: verb, arguments: [boardDeviceTree.path])+ if try patchCopy(of: deviceTree, in: root, work: work, verb: verb, arguments: [boardDeviceTree.path]) {+ boardTreeChanged = true+ }}}if let build = spoofBuild {@@ -1226,6 +1241,7 @@ struct VPhoneCustomFirmwareInstaller {try patchCopy(of: version, in: root, work: work, verb: "patch-build-version", arguments: [build])}}+ return boardTreeChanged}}@@ -1273,13 +1289,17 @@ struct VPhoneCustomFirmwareInstaller {/// instead: copy it out by descriptor, patch the copy in the work folder,/// and install the result with its original owner and mode. The verb/// never sees a guest path, so it cannot be steered by a link in one.+ ///+ /// Returns whether the verb changed the file. One that found it already+ /// as it should be leaves the guest's copy untouched.+ @discardableResultprivate func patchCopy(of relative: String,in root: VPhoneConfinedDirectory,work: WorkDirectory,verb: String,arguments: [String] = [],- ) throws {+ ) throws -> Bool {guard let original = try root.status(relative), original.st_mode & S_IFMT == S_IFREG else {throw ValidationError("\(relative) on the VM is missing or is not a regular file. Restore the VM, then install CFW again.")}@@ -1290,13 +1310,16 @@ struct VPhoneCustomFirmwareInstaller {let leaf = (relative as NSString).lastPathComponenttry root.copyFile(from: relative, to: leaf, in: stage)let staged = work.file(folder).appendingPathComponent(leaf)+ let before = try Data(contentsOf: staged)try patch(verb, [staged.path] + arguments)+ guard try Data(contentsOf: staged) != before else { return false }try root.replaceFile(relative,fromFileAt: staged,mode: original.st_mode & 0o7777,owner: (original.st_uid, original.st_gid),)+ return true}/// Flip the speaker chains in every tuning set's graph_configurations.plist