Run a virtual iPhone on an Apple Silicon Mac.
Swift
Drop a stale MobileGestalt cache from vphoned, not from the host
Jacky5d7232a0c396
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex d0587379..bdc6ee08 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -2228,7 +2228,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-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. When it changes the tree, the installer also removes the guest's cached MobileGestalt answers, see below. |+| `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. |`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.@@ -2255,15 +2255,21 @@ with no Taptic Engine 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 onesuntil 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 device tree repair (the-haptics removal, or the board audio node) changed the tree, and log-`[+] MobileGestalt cache removed`; a repair that found the tree already right-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+patch never has them. The host cannot remove it: the file is on the guest's+Data volume, a FileVault volume whose keys are in the guest's SEP, which the+host sees locked and cannot mount (the volume the installer mounts beside+System, s3, is xART). vphoned removes it at startup instead, when it is older+than the Preboot `devicetree.img4` the guest booted+(`VPhoneDaemon/Daemon/GuestMobileGestaltCache.swift`): the host rewrites that+tree only with the VM stopped and only when a repair changed it, so an older+cache was worked out from an older tree. It logs `vphoned: MobileGestalt+cache predates the device tree, removed it; …`, and `/v1/health` reports+`mobilegestalt_restart_pending` until the guest restarts, since running+processes keep the answers they read. An existing guest therefore needs `cfw+update-environment`, one boot, and one restart. This is no patch declaration+of its own: it writes nothing to the tree, and with the repairs off the tree+is not rewritten and the cache stays. Removing the file by hand (`files.remove`, then+`system.reboot`) is what vphoned does, less the reboot. Detail and themeasurements: `Research/Guest/virtio_sound.md` §7.**Why a plugin.** The cloudOS kernel has `AppleVirtIOSound` and its user client,diff --git a/Research/Guest/virtio_sound.md b/Research/Guest/virtio_sound.mdindex 544f543e..8b169af1 100644--- a/Research/Guest/virtio_sound.md+++ b/Research/Guest/virtio_sound.md@@ -539,22 +539,40 @@ 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. For an existing-one the installer now does the removal: when a Preboot device tree repair-(`preboot-cfw-devicetree_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+A guest created with the patch never caches the wrong answers: its tree is+written before its first boot. An existing one needs the file removed, and+the host cannot do it. The guest's container holds s1 System, s2 Data, s3+xART, s4 Hardware, s5 Preboot and s7 User; Data and User are FileVault+volumes whose keys are in the guest's SEP, and `diskutil mount` on the host+answers "This is an encrypted and locked APFS Volume". The volume the+installer mounts beside System is xART, where the gigalocker lives. An+earlier installer change that removed the cache from that volume could never+find it: after a live `cfw update-environment` the cache still had its+first-boot modification time.++So vphoned does what the two commands above do, less the reboot, at startup+(`VPhoneDaemon/Daemon/GuestMobileGestaltCache.swift`). The rule is the age of+the cache against the tree the guest booted,+`/private/preboot/<hash>/usr/standalone/firmware/devicetree.img4`, the file+the installer patches. The host changes that tree only with the VM stopped,+and the installer writes a guest file only when its verb changed it, so a+cache older than the tree was worked out from an older tree and is removed:```- [+] MobileGestalt cache removed; the guest rebuilds it from the new device tree at next boot+vphoned: MobileGestalt cache predates the device tree, removed it; a restart makes the new answers take effect```-The guest's next boot is then enough. A repair that finds the tree already-right 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.+A cache written after the tree was written by a boot of that tree, and is+left alone without a line. That covers every Preboot tree repair (the haptics+removal, the board audio node) and needs no state, so it works the first+time a new vphoned runs on an old guest. Processes that read the cache keep+their answers until they exit, so the removal takes full effect at the next+boot; vphoned does not restart the guest itself. Until then `/v1/health`+reports `mobilegestalt_restart_pending: true`.++For an existing guest that is `cfw update-environment`, one boot (vphoned+drops the cache), and one restart. A new guest, and every later boot of an+updated one, does nothing: its cache is newer than its tree.**Verified** (`audiotest-ipad`): after the cache was rebuilt the Ringtone pagehas no Haptics row, mediaplaybackd makes no hapticd connection, and a tone@@ -565,6 +583,10 @@ Not yet verified on an iPhone guest: that, with the node removed and thecache rebuilt, a tone there plays as it does on `audiotest-ipad`. The failureit removes is the same one, measured above.+Not yet verified live: vphoned's removal on an existing guest after `cfw+update-environment` — the log line above on the first boot, then+`mobilegestalt_restart_pending: false` and no Haptics row after the restart.+## Reveal and validation1. Kernel side present: `strings` on the decompressed kernelcache shows thediff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex 92566d45..0230aad9 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -299,6 +299,16 @@ and whenever the settings change. SpringBoard reads the key when it starts, soa newly written one holds from the next boot or respring. Measurements:`Research/Guest/lock_screen_idle_timer.md`.+`/v1/health` also carries `mobilegestalt_restart_pending`. At startup vphoned+removes libMobileGestalt's cache,+`/private/var/containers/Shared/SystemGroup/systemgroup.com.apple.mobilegestaltcache/Library/Caches/com.apple.MobileGestalt.plist`,+when it is older than the Preboot `devicetree.img4` the guest booted: its+answers were worked out from an older tree+(`VPhoneDaemon/Daemon/GuestMobileGestaltCache.swift`). Running processes keep+the answers they read, so the field is true from that removal until the guest+restarts, also across a vphoned restart in the same boot; vphoned does not+restart the guest itself. See `Research/Guest/virtio_sound.md` §7.+`network.ipv4.get` and `network.ipv4.set` read and write the IPv4 settings ofone interface (default `en0`) in configd's network preferences,`/var/preferences/SystemConfiguration/preferences.plist`, through SCPreferencesdiff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex 57a37164..5ed547dc 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -79,6 +79,7 @@ enum GuestAPI {"ios": "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)","ip": ip ?? "","setup_pending": setupAssistantPending(),+ "mobilegestalt_restart_pending": GuestMobileGestaltCache.restartPending(),"capabilities": ["touch","touch2",diff --git a/VPhoneDaemon/Daemon/GuestMobileGestaltCache.swift b/VPhoneDaemon/Daemon/GuestMobileGestaltCache.swiftnew file mode 100644index 00000000..054b0e87--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestMobileGestaltCache.swift@@ -0,0 +1,94 @@+import Darwin+import Foundation++/// Drops libMobileGestalt's cache when it is older than the device tree the+/// guest booted.+///+/// libMobileGestalt works most of its answers out from the device tree, and at+/// first boot it writes them to a cache on the Data volume. Every process+/// answers from that file from then on, so a guest whose Preboot device tree+/// was changed later keeps answering as the old tree did: after `cfw+/// update-environment` removed `/product/haptics`, Settings still showed the+/// Haptics row and tones stayed silent. With the file gone, the answers are+/// worked out again from the tree the guest booted.+///+/// The host cannot do this. The Data volume is a FileVault volume whose keys+/// are in the guest's SEP; a host that attaches the disk sees it locked and+/// cannot mount it. So vphoned does it here, at startup.+///+/// The rule is about age, not about any one answer. The host changes the tree+/// only with the VM stopped, and writes it only when a repair changed it, so a+/// cache older than the tree's modification time was worked out from an older+/// tree. One written after it was written by a boot of this tree. That covers+/// every tree repair — the haptics removal, the board audio node — and needs+/// no state: an existing guest's first-boot cache is older than the tree+/// `update-environment` just rewrote, a new guest's tree is written before its+/// first boot, and the cache rebuilt after a drop is newer than the tree.+///+/// Processes that have read the cache keep its answers until they exit, so a+/// drop takes full effect at the next boot. vphoned never restarts the guest+/// for it; `/v1/health` reports `mobilegestalt_restart_pending` until then.+///+/// See Research/Guest/virtio_sound.md §7.+enum GuestMobileGestaltCache {+ static let cachePath =+ "/private/var/containers/Shared/SystemGroup/systemgroup.com.apple.mobilegestaltcache/Library/Caches/com.apple.MobileGestalt.plist"+ /// The Preboot volume. The tree the guest boots is+ /// `<boot manifest hash>/usr/standalone/firmware/devicetree.img4` in it,+ /// the same file `cfw install` and `cfw update-environment` patch.+ private static let preboot = "/private/preboot"+ /// The boot session in which vphoned dropped the cache, so that a vphoned+ /// restarted in the same boot (`agent.apply_update`) still reports it.+ private static let dropMarker = "/var/root/Library/Caches/com.vphone.vphoned.mobilegestalt-dropped"++ // MARK: - Startup++ static func dropIfStaleOnStartup() {+ guard let cache = modificationTime(cachePath) else { return }+ let trees = (try? FileManager.default.contentsOfDirectory(atPath: preboot))?+ .map { "\(preboot)/\($0)/usr/standalone/firmware/devicetree.img4" }+ .filter { modificationTime($0) != nil } ?? []+ guard trees.count == 1, let tree = modificationTime(trees[0]) else {+ NSLog("vphoned: MobileGestalt cache: found %ld device trees in %@, left the cache alone", trees.count, preboot)+ return+ }+ guard isEarlier(cache, than: tree) else { return }+ guard unlink(cachePath) == 0 || errno == ENOENT else {+ NSLog("vphoned: MobileGestalt cache: cannot remove %@: %@", cachePath, String(cString: strerror(errno)))+ return+ }+ if let session = bootSession() {+ try? Data(session.utf8).write(to: URL(fileURLWithPath: dropMarker), options: .atomic)+ }+ NSLog("vphoned: MobileGestalt cache predates the device tree, removed it; a restart makes the new answers take effect")+ }++ /// True when vphoned dropped the cache during this boot: the guest has+ /// not restarted since, and still answers some questions from the old tree.+ static func restartPending() -> Bool {+ guard let session = bootSession(),+ let marker = FileManager.default.contents(atPath: dropMarker)+ else { return false }+ return String(decoding: marker, as: UTF8.self) == session+ }++ // MARK: - Helpers++ /// A regular file's modification time; nil for anything else or nothing.+ private static func modificationTime(_ path: String) -> timespec? {+ var status = stat()+ guard lstat(path, &status) == 0, status.st_mode & S_IFMT == S_IFREG else { return nil }+ return status.st_mtimespec+ }++ private static func isEarlier(_ a: timespec, than b: timespec) -> Bool {+ a.tv_sec != b.tv_sec ? a.tv_sec < b.tv_sec : a.tv_nsec < b.tv_nsec+ }++ private static func bootSession() -> String? {+ var buffer = [UInt8](repeating: 0, count: 64)+ var size = buffer.count+ guard sysctlbyname("kern.bootsessionuuid", &buffer, &size, nil, 0) == 0 else { return nil }+ return String(decoding: buffer.prefix { $0 != 0 }, as: UTF8.self)+ }+}diff --git a/VPhoneDaemon/Daemon/main.swift b/VPhoneDaemon/Daemon/main.swiftindex c5002df5..0c948e15 100644--- a/VPhoneDaemon/Daemon/main.swift+++ b/VPhoneDaemon/Daemon/main.swift@@ -15,6 +15,8 @@ if mode != 1 {guard vp_native_watch_proxy() == 0 else { exit(1) }// First, so the Lock Screen timeout is in place before SpringBoard reads it.GuestLockScreenIdle.startOnStartup()+// Before the server, so `/v1/health` reports a drop from its first answer.+GuestMobileGestaltCache.dropIfStaleOnStartup()vp_vcam_start()// Multi-finger injection is resolved here so the first pinch is not the call// that pays for `dlopen`; a base without the symbols logs and stays a no-op.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMobileGestaltCache.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMobileGestaltCache.swiftdeleted file mode 100644index b7beb3a2..00000000--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareMobileGestaltCache.swift+++ /dev/null@@ -1,36 +0,0 @@-// 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 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 Preboot device-// tree repair (the haptics removal or the board audio node) 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/CustomFirmware/CustomFirmwareMobileGestaltCacheTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMobileGestaltCacheTests.swiftdeleted file mode 100644index 9ecda4e8..00000000--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMobileGestaltCacheTests.swift+++ /dev/null@@ -1,113 +0,0 @@-// 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 Preboot 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 c07b43f3..ae821672 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -227,17 +227,20 @@ struct VPhoneCustomFirmwareInstaller {physicalStore: "\(baseDisk.dropFirst("/dev/".count))s1",)+ // s3 is the xART volume, which holds the gigalocker. The guest's Data+ // and User volumes are FileVault volumes locked to its SEP; the host+ // cannot mount them, so nothing here writes to them.let system = work.file("system")- let data = work.file("data")+ let xart = work.file("xart")_ = try work.directory.directory("system", create: true, mode: 0o700)- _ = try work.directory.directory("data", create: true, mode: 0o700)+ _ = try work.directory.directory("xart", create: true, mode: 0o700)var systemMounted = false- var dataMounted = false+ var xartMounted = falsedefer {- if dataMounted,- (try? tool("/sbin/umount", [data.path], quiet: true)) == nil+ if xartMounted,+ (try? tool("/sbin/umount", [xart.path], quiet: true)) == nil{- _ = try? tool("/sbin/umount", ["-f", data.path], quiet: true)+ _ = try? tool("/sbin/umount", ["-f", xart.path], quiet: true)}if systemMounted,(try? tool("/sbin/umount", [system.path], quiet: true)) == nil@@ -247,14 +250,14 @@ struct VPhoneCustomFirmwareInstaller {}systemMounted = truetry mountGuestVolume("\(container)s1", at: system)- dataMounted = true- try mountGuestVolume("\(container)s3", at: data)+ xartMounted = true+ try mountGuestVolume("\(container)s3", at: xart)print("[*] \(mode.summary.capitalized): \(bundle.lastPathComponent)")do {// Every descriptor on a guest volume lives in this scope, so none// is left open to hold the volume busy when it is unmounted.let systemRoot = try openGuestVolume("system", device: "\(container)s1", in: work)- let dataRoot = try openGuestVolume("data", device: "\(container)s3", in: work)+ let xartRoot = try openGuestVolume("xart", device: "\(container)s3", in: work)switch mode {case .full:guard let restore else {@@ -262,7 +265,7 @@ struct VPhoneCustomFirmwareInstaller {}try installMounted(system: systemRoot,- data: dataRoot,+ xart: xartRoot,restore: restore,work: work,owner: callerUID,@@ -276,7 +279,11 @@ struct VPhoneCustomFirmwareInstaller {// full install only. The device tree repairs are the exception: a VM// restored before the board audio repair or the haptics removal has no// other way to get them, since `fw patch` does not run again.- let treeRepaired = try patchPreboot(+ // A guest that has booted keeps the MobileGestalt answers it cached from+ // the old tree on its Data volume, which the host cannot reach. vphoned+ // drops that cache at startup when it is older than the tree; see+ // VPhoneDaemon/Daemon/GuestMobileGestaltCache.swift.+ try patchPreboot(volumes: volumes,work: work,plan: plan,@@ -284,20 +291,11 @@ 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 treeRepaired {- 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.- _ = try tool("/sbin/umount", [data.path])- dataMounted = false+ _ = try tool("/sbin/umount", [xart.path])+ xartMounted = false_ = try tool("/sbin/umount", [system.path])systemMounted = false_ = try tool("/usr/bin/hdiutil", ["detach", baseDisk], quiet: true)@@ -600,7 +598,7 @@ struct VPhoneCustomFirmwareInstaller {private func installMounted(system: VPhoneConfinedDirectory,- data: VPhoneConfinedDirectory,+ xart: VPhoneConfinedDirectory,restore: VPhoneConfinedDirectory,work: WorkDirectory,owner: uid_t?,@@ -692,7 +690,7 @@ struct VPhoneCustomFirmwareInstaller {)}if on("system-gigalocker-boot-rename") {- try renameGigalocker(data: data)+ try renameGigalocker(xart: xart)}if on("system-extensions-boot-gpu_bundle") {try installGPUBundle(restore: restore, system: system, owner: owner)@@ -1165,9 +1163,6 @@ struct VPhoneCustomFirmwareInstaller {/// `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 repair changed the device tree, which leaves the- /// guest's cached MobileGestalt answers stale.private func patchPreboot(volumes: [[String: Any]],work: WorkDirectory,@@ -1175,7 +1170,7 @@ struct VPhoneCustomFirmwareInstaller {guestDevice: VPhoneGuestDevice,includeIdentity: Bool,boardDeviceTree: URL?,- ) throws -> Bool {+ ) throws {// 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@@ -1204,7 +1199,7 @@ struct VPhoneCustomFirmwareInstaller {if on(FirmwareGuestSystemPatchSet.prebootHaptics) {repairs.append(("patch-dt-haptics", []))}- guard rewriteIdentity || !repairs.isEmpty || !(spoofBuild ?? "").isEmpty else { return false }+ guard rewriteIdentity || !repairs.isEmpty || !(spoofBuild ?? "").isEmpty else { return }guardlet preboot = volumes.first(where: { ($0["Roles"] as? [String])?.contains("Preboot") == true }),let device = preboot["DeviceIdentifier"] as? String@@ -1232,11 +1227,8 @@ struct VPhoneCustomFirmwareInstaller {if rewriteIdentity {try patchCopy(of: deviceTree, in: root, work: work, verb: "patch-post-restore-dt")}- var treeRepaired = falsefor repair in repairs {- if try patchCopy(of: deviceTree, in: root, work: work, verb: repair.verb, arguments: repair.arguments) {- treeRepaired = true- }+ try patchCopy(of: deviceTree, in: root, work: work, verb: repair.verb, arguments: repair.arguments)}if let build = spoofBuild {let version = "Cryptexes/OS/System/Library/CoreServices/SystemVersion.plist"@@ -1244,7 +1236,6 @@ struct VPhoneCustomFirmwareInstaller {try patchCopy(of: version, in: root, work: work, verb: "patch-build-version", arguments: [build])}}- return treeRepaired}}@@ -1293,16 +1284,17 @@ struct VPhoneCustomFirmwareInstaller {/// 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.- @discardableResult+ /// A verb that found the file already as it should be leaves the guest's+ /// copy untouched, modification time included: vphoned drops the guest's+ /// MobileGestalt cache when the Preboot device tree is newer than it, so a+ /// repeated environment update must not make an unchanged tree look new.private func patchCopy(of relative: String,in root: VPhoneConfinedDirectory,work: WorkDirectory,verb: String,arguments: [String] = [],- ) throws -> Bool {+ ) throws {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.")}@@ -1315,14 +1307,13 @@ struct VPhoneCustomFirmwareInstaller {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 }+ guard try Data(contentsOf: staged) != before else { return }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@@ -1479,16 +1470,18 @@ struct VPhoneCustomFirmwareInstaller {try system.replaceFile(target, fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)}- // MARK: - Data volume+ // MARK: - xART volume- private func renameGigalocker(data: VPhoneConfinedDirectory) throws {+ /// The patched seputil looks for the gigalocker as `AA.gl` rather than+ /// under a UUID, so the one the restore wrote takes that name.+ private func renameGigalocker(xart: VPhoneConfinedDirectory) throws {let destination = "AA.gl"- for source in try data.entries() where (source as NSString).pathExtension == "gl" {+ for source in try xart.entries() where (source as NSString).pathExtension == "gl" {if source == destination {continue}- try data.removeItem(destination)- try data.rename(source, to: destination)+ try xart.removeItem(destination)+ try xart.rename(source, to: destination)}}