Run a virtual iPhone on an Apple Silicon Mac.
Swift
Offer Always On Display on iPhones whose board has it
Marvaebd5aabff0c4b
diff --git a/VPhoneDaemon/Daemon/GuestMobileGestaltAnswers.swift b/VPhoneDaemon/Daemon/GuestMobileGestaltAnswers.swiftnew file mode 100644index 00000000..92b0a8f3--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestMobileGestaltAnswers.swift@@ -0,0 +1,53 @@+import Foundation++/// Answers vphoned gives libMobileGestalt's cache because the device tree+/// cannot give them alone.+///+/// The Always On display is the one so far. MobileGestalt answers it from the+/// board's `/arm-io/disp0` `always-on-time`, and that property answers three+/// questions yes together: DeviceSupportsAlwaysOnDisplay,+/// DeviceSupportsAlwaysOnTime and DeviceSupportsAlwaysOnDisplayFlipbook.+/// Settings offers Always On Display only with the first two+/// (DisplayAndBrightnessSettings asks for AlwaysOnTime). The flipbook is the+/// panel controller (DCP) replaying prerendered frames, and CoreBrightness+/// asks the DCP for it in backboardd: this VM's paravirtual panel has none,+/// and an iPhone18,1 27.0.1 guest whose tree carried `always-on-time` lost+/// backboardd at every boot until launchd restarted it into the device+/// recovery environment. Without the flipbook, BacklightServices renders the+/// always-on Lock Screen itself (BLSHPseudoFlipbook), which works on a guest+/// (iPhone19,4 27.1, iPhone18,1 27.0.1). So the tree only marks a board that+/// has the display (`vphone-always-on-display` in `/product`), and these two+/// answers go into `CacheExtra`, where libMobileGestalt takes an answer before+/// working it out. The flipbook stays unanswered there and so no.+enum GuestMobileGestaltAnswers {+ /// DeviceSupportsAlwaysOnDisplay and DeviceSupportsAlwaysOnTime, as the+ /// cache keys them: the first 22 characters of the base64 MD5 of+ /// "MGCopyAnswer" followed by the name.+ static let alwaysOnDisplay = ["2OOJf1VhaM7NxfRok3HbWQ", "j8/Omm6s1lsmTDFsXjsBfA"]++ enum Update: Equatable {+ /// Not a cache vphoned can read, or one being written.+ case unreadable+ /// Every answer is already yes.+ case present+ /// The cache with the answers, to write back.+ case updated(Data)+ }++ /// `cache` with every key of `answers` answering yes in `CacheExtra`; the+ /// rest of the cache is kept as it is.+ static func answeringYes(_ answers: [String], in cache: Data) -> Update {+ guard var plist = try? PropertyListSerialization.propertyList(from: cache, format: nil) as? [String: Any],+ var extra = plist["CacheExtra"] as? [String: Any]+ else { return .unreadable }+ guard answers.contains(where: { extra[$0] as? Bool != true }) else { return .present }+ for key in answers {+ extra[key] = true+ }+ plist["CacheExtra"] = extra+ guard let data = try? PropertyListSerialization.data(fromPropertyList: plist, format: .binary, options: 0) else {+ return .unreadable+ }+ return .updated(data)+ }+}diff --git a/VPhoneDaemon/Daemon/GuestMobileGestaltCache.swift b/VPhoneDaemon/Daemon/GuestMobileGestaltCache.swiftindex 054b0e87..f6378465 100644--- a/VPhoneDaemon/Daemon/GuestMobileGestaltCache.swift+++ b/VPhoneDaemon/Daemon/GuestMobileGestaltCache.swift@@ -1,5 +1,6 @@import Darwinimport Foundation+import VphonedNative/// Drops libMobileGestalt's cache when it is older than the device tree the/// guest booted.@@ -57,14 +58,76 @@ enum GuestMobileGestaltCache {NSLog("vphoned: MobileGestalt cache: cannot remove %@: %@", cachePath, String(cString: strerror(errno)))return}+ markRestartPending()+ NSLog("vphoned: MobileGestalt cache predates the device tree, removed it; a restart makes the new answers take effect")+ }++ // MARK: - Always On display++ /// The `/product` property `cfw install` and `cfw update-environment` add+ /// for a board with an Always On display (`DeviceTreePatcher.alwaysOnDisplayMarker`).+ private static let alwaysOnDisplayMarker = "vphone-always-on-display"++ /// On a board with an Always On display, answer DeviceSupportsAlwaysOnDisplay+ /// and DeviceSupportsAlwaysOnTime yes in the cache; see+ /// `GuestMobileGestaltAnswers` for why the tree cannot.+ ///+ /// libMobileGestalt writes the cache when a process first asks after it is+ /// gone: on a guest's first boot, and after a drop above. So this waits+ /// for it, in the background, then adds the answers once. Processes that+ /// read the cache before keep their answers until they exit, so the+ /// answers reach Settings and SpringBoard at the next boot, as a drop's do,+ /// and `/v1/health` reports the restart pending. The cache keeps them+ /// across boots; only a rebuild loses them, and the next start adds them+ /// again. Run after `dropIfStaleOnStartup`.+ static func presentAlwaysOnDisplayOnStartup() {+ guard vp_device_tree_has_property("IODeviceTree:/product", alwaysOnDisplayMarker) else { return }+ DispatchQueue.global(qos: .utility).async {+ for _ in 0 ..< 120 {+ if presentAlwaysOnDisplay() { return }+ sleep(5)+ }+ NSLog("vphoned: MobileGestalt cache: none written in 10 minutes, Always On Display not offered")+ }+ }++ /// True when the cache answers yes, now or already; false to try again.+ private static func presentAlwaysOnDisplay() -> Bool {+ guard let cache = FileManager.default.contents(atPath: cachePath) else { return false }+ let data: Data+ switch GuestMobileGestaltAnswers.answeringYes(GuestMobileGestaltAnswers.alwaysOnDisplay, in: cache) {+ case .unreadable: return false+ case .present: return true+ case let .updated(updated): data = updated+ }+ // Replace it whole, as its owner with its mode, so a reader never+ // sees half a file.+ var status = stat()+ guard lstat(cachePath, &status) == 0 else { return false }+ let temporary = cachePath + ".vphoned"+ guard (try? data.write(to: URL(fileURLWithPath: temporary))) != nil,+ chown(temporary, status.st_uid, status.st_gid) == 0,+ chmod(temporary, status.st_mode & 0o7777) == 0,+ rename(temporary, cachePath) == 0+ else {+ NSLog("vphoned: MobileGestalt cache: cannot add the Always On display answers: %@", String(cString: strerror(errno)))+ unlink(temporary)+ return true+ }+ markRestartPending()+ NSLog("vphoned: MobileGestalt cache: answered the Always On display yes; a restart offers it in Settings")+ return true+ }++ private static func markRestartPending() {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.+ /// True when vphoned dropped the cache, or added answers to it, during+ /// this boot: the guest has not restarted since, and some processes still+ /// answer from the old cache.static func restartPending() -> Bool {guard let session = bootSession(),let marker = FileManager.default.contents(atPath: dropMarker)diff --git a/VPhoneDaemon/Daemon/main.swift b/VPhoneDaemon/Daemon/main.swiftindex 5a2e5e6d..36886883 100644--- a/VPhoneDaemon/Daemon/main.swift+++ b/VPhoneDaemon/Daemon/main.swift@@ -23,6 +23,7 @@ guard vp_native_watch_proxy() == 0 else { exit(1) }GuestLockScreenIdle.startOnStartup()// Before the server, so `/v1/health` reports a drop from its first answer.GuestMobileGestaltCache.dropIfStaleOnStartup()+GuestMobileGestaltCache.presentAlwaysOnDisplayOnStartup()// Before audiomxd is asked for sound again; see the type for what it cannot cover.GuestVirtualAudioProduct.storeOnStartup()// After SpringBoard has had time to come up, so the inner panel's layoutdiff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.hindex 72513dc0..0bee5cee 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -190,6 +190,10 @@ char * _Null_unspecified vp_usb_set_serial(const char * _Null_unspecified serial/// `unique-chip-id`. malloc-owned, or NULL when the device tree lacks either.char * _Null_unspecified vp_usb_own_serial(void);+/// Whether the device tree node at `path` (an `IODeviceTree:` path) has the+/// property `name`, whatever its value.+bool vp_device_tree_has_property(const char * _Nonnull path, const char * _Nonnull name);+/// The names of the APFS snapshots of the volume mounted at `mount`, in/// `*names` (free with `vp_apfs_snapshot_names_free`). Returns 0 or an errno value.int vp_apfs_snapshot_list(const char * _Null_unspecified mount, char * _Null_unspecified * _Null_unspecified * _Null_unspecified names, int * _Null_unspecified count);diff --git a/VPhoneDaemon/Native/vphoned_usb.m b/VPhoneDaemon/Native/vphoned_usb.mindex 595b6ed0..0c7aafcb 100644--- a/VPhoneDaemon/Native/vphoned_usb.m+++ b/VPhoneDaemon/Native/vphoned_usb.m@@ -113,3 +113,14 @@ char *vp_usb_own_serial(void) {asprintf(&serial, "%08X%016llX", chipID, ecid);return serial;}++bool vp_device_tree_has_property(const char *path, const char *name) {+ io_registry_entry_t entry = IORegistryEntryFromPath(kIOMainPortDefault, path);+ if (entry == MACH_PORT_NULL) return false;+ CFStringRef key = CFStringCreateWithCString(kCFAllocatorDefault, name, kCFStringEncodingUTF8);+ CFTypeRef value = key ? IORegistryEntryCreateCFProperty(entry, key, kCFAllocatorDefault, 0) : NULL;+ if (key) CFRelease(key);+ IOObjectRelease(entry);+ if (value) CFRelease(value);+ return value != NULL;+}diff --git a/VPhoneDaemon/Tests/LogicTests.swift b/VPhoneDaemon/Tests/LogicTests.swiftindex 30ddc1d8..ee0dbac0 100644--- a/VPhoneDaemon/Tests/LogicTests.swift+++ b/VPhoneDaemon/Tests/LogicTests.swift@@ -6,7 +6,8 @@ import MachO/// Checks the guest-independent parts of vphoned on the Mac: the service/// profile lists and bookkeeping, the first-boot settle verdict (data/// migration included), the device name rule, the pointer scroll-/// parameters and the Irisin package a guest takes. `run-logic-tests.sh`+/// parameters, the Irisin package a guest takes and the MobileGestalt+/// answers vphoned adds. `run-logic-tests.sh`/// builds this file with those sources.nonisolated(unsafe) var failures = 0nonisolated(unsafe) var checks = 0@@ -41,10 +42,37 @@ enum LogicTests {bootstrapPlatform()setupAssistantState()homeViewDistancePolicy()+ mobileGestaltAnswers()print("\(checks) checks, \(failures) failures")exit(failures == 0 ? 0 : 1)}+ static func mobileGestaltAnswers() {+ let answers = GuestMobileGestaltAnswers.alwaysOnDisplay+ func cache(_ extra: [String: Any]) -> Data {+ try! PropertyListSerialization.data(fromPropertyList: [+ "CacheData": Data([1, 2, 3]), "CacheExtra": extra, "CacheUUID": "u", "CacheVersion": "24A446",+ ], format: .binary, options: 0)+ }+ let original = cache(["ybGkijAwLTwevankfVzsDQ": Data(count: 16), "aoJSd/MXk7M40NgXTM6x+g": false])+ guard case let .updated(data) = GuestMobileGestaltAnswers.answeringYes(answers, in: original) else {+ expect(false, "a cache without the answers is updated")+ return+ }+ let plist = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [String: Any]+ let extra = plist["CacheExtra"] as! [String: Any]+ expectEqual(extra["2OOJf1VhaM7NxfRok3HbWQ"] as? Bool, true, "DeviceSupportsAlwaysOnDisplay")+ expectEqual(extra["j8/Omm6s1lsmTDFsXjsBfA"] as? Bool, true, "DeviceSupportsAlwaysOnTime")+ expectEqual(extra["aoJSd/MXk7M40NgXTM6x+g"] as? Bool, false, "the flipbook answer is left as it was")+ expectEqual(extra["ybGkijAwLTwevankfVzsDQ"] as? Data, Data(count: 16), "other answers are kept")+ expectEqual(plist["CacheData"] as? Data, Data([1, 2, 3]), "the computed answers are kept")+ expectEqual(plist["CacheVersion"] as? String, "24A446")+ expectEqual(GuestMobileGestaltAnswers.answeringYes(answers, in: data), .present, "a second pass changes nothing")+ expectEqual(GuestMobileGestaltAnswers.answeringYes(answers, in: Data("half a fi".utf8)), .unreadable)+ let noExtra = try! PropertyListSerialization.data(fromPropertyList: ["CacheVersion": "24A446"], format: .binary, options: 0)+ expectEqual(GuestMobileGestaltAnswers.answeringYes(answers, in: noExtra), .unreadable, "a cache needs CacheExtra")+ }+static func homeViewDistancePolicy() {expect(GuestHomeViewDistancePolicy.rejection(mode: "automatic", resetEnvironment: false) != nil,"environment-wide reset requires explicit acknowledgement before native transport")diff --git a/VPhoneDaemon/Tests/run-logic-tests.sh b/VPhoneDaemon/Tests/run-logic-tests.shindex 4a3f98db..dfd06185 100755--- a/VPhoneDaemon/Tests/run-logic-tests.sh+++ b/VPhoneDaemon/Tests/run-logic-tests.sh@@ -4,7 +4,8 @@ set -euo pipefail# Builds the guest-independent vphoned sources with LogicTests.swift for the# Mac and runs them: service profile lists and bookkeeping, the first-boot# settle verdict, the device name rule, the pointer scroll parameters, the-# Irisin package a guest takes. No guest is needed.+# Irisin package a guest takes, the MobileGestalt answers vphoned adds. No+# guest is needed.daemon="${0:a:h:h}"temporary="$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/vphone-logic-tests.XXXXXX")"@@ -20,6 +21,7 @@ trap '/bin/rm -rf "$temporary"' EXIT"$daemon/Daemon/Bootstrap/GuestBootstrapPlatform.swift" \"$daemon/Daemon/GuestSetupAssistantState.swift" \"$daemon/Daemon/GuestHomeViewDistancePolicy.swift" \+ "$daemon/Daemon/GuestMobileGestaltAnswers.swift" \"$daemon/Tests/LogicTests.swift" \-o "$temporary/logic-tests"diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swiftindex 3f383e29..3af1354d 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift@@ -676,6 +676,24 @@ extension DeviceTreePatcher {"ringer-button-location", "camera-button-location", "supports-camera-button",]+ /// The `/product` property that tells vphoned the board has an Always On+ /// display. MobileGestalt reads nothing by this name.+ ///+ /// MobileGestalt answers the Always On display from the board's+ /// `/arm-io/disp0` `always-on-time`, and that one property answers three+ /// questions yes: DeviceSupportsAlwaysOnDisplay, DeviceSupportsAlwaysOnTime+ /// and DeviceSupportsAlwaysOnDisplayFlipbook. The flipbook is the panel+ /// controller (DCP) replaying prerendered frames; CoreBrightness asks the+ /// DCP for it in backboardd, which this VM's paravirtual panel cannot+ /// answer, so a guest whose tree carries `always-on-time` loses backboardd+ /// at every boot and launchd restarts it into the device recovery+ /// environment (iPhone18,1 27.0.1). Without the flipbook, BacklightServices+ /// renders the always-on Lock Screen itself (BLSHPseudoFlipbook), which+ /// works here; so the tree only marks the board, and vphoned answers the+ /// first two questions yes in the MobileGestalt cache+ /// (`GuestMobileGestaltCache.presentAlwaysOnDisplay`).+ static let alwaysOnDisplayMarker = "vphone-always-on-display"+/// `/buttons` properties taken from the board when they are placeholders./// `function-button_ringeren` is what MobileGestalt reads for the Action/// Button. vphone600's `/buttons` has no `compatible`, so no button driver@@ -692,7 +710,8 @@ extension DeviceTreePatcher {/// Give an iPhone guest's `/product` and `/buttons` the board's values for/// `iPhoneProductProperties`, `iPhoneAddedProductProperties` and- /// `iPhoneButtonProperties`.+ /// `iPhoneButtonProperties`, and `alwaysOnDisplayMarker` when the board has+ /// an Always On display.////// A listed property is copied only when the guest's is a placeholder (or,/// for the added ones, missing) and the board's is a real value, so a tree@@ -723,6 +742,15 @@ extension DeviceTreePatcher {fill(iPhoneProductProperties, node: "product", add: false)fill(iPhoneAddedProductProperties, node: "product", add: true)fill(iPhoneButtonProperties, node: "buttons", add: false)+ if let display = optionalChild(of: source, named: "arm-io").flatMap({ optionalChild(of: $0, named: "disp0") }),+ display.properties.contains(where: { $0.name == "always-on-time" && $0.flags & placeholderFlag == 0 }),+ let product = optionalChild(of: root, named: "product"),+ !product.properties.contains(where: { $0.name == alwaysOnDisplayMarker })+ {+ let value = Data([1, 0, 0, 0])+ product.properties.append(DTProperty(name: alwaysOnDisplayMarker, flags: 0, value: value, valueOffset: 0))+ changes.append(PhoneProductChange(path: "product/\(alwaysOnDisplayMarker)", before: nil, after: value))+ }return changes}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex 42d7d0a7..2652182a 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -779,7 +779,8 @@ public enum FirmwareGuestSystemPatchSet {iPhone's own tree: model name, Siri and dictation, button and display geometry, \Camera Control and the Action Button. vphone600 leaves them as syscfg placeholders, \which MobileGestalt reads as absent, so Settings has no Siri, Camera Control or Action \- Button and About no Model Name. Hardware the VM does not have is left out. Takes the \+ Button and About no Model Name. Hardware the VM does not have is left out. An iPhone \+ with an Always On display is marked, so vphoned offers Always On Display. Takes the \iPhone's device tree from the VM's FirmwareOriginals, and recovers it there from the \VM's IPSW in ~/.vphone/ipsws when it is missing.""",diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareIPhoneProductTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareIPhoneProductTests.swiftindex af7f04ae..6ff4564b 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareIPhoneProductTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareIPhoneProductTests.swift@@ -107,6 +107,49 @@ struct CustomFirmwareIPhoneProductTests {#expect(delta == 0)#expect(patched == presented)}++ // MARK: - Always On display++ private static func tree(product: Node, armIO: [Node]) -> Data {+ Node("device-tree", [("model", Data("iPhone18,1\0\0".utf8))], children: [+ Node("arm-io", children: armIO),+ product,+ ]).serialized+ }++ private static let guestArmIO = [Node("gfx", [("compatible", Data("paravirtualizedgraphics,gpu\0".utf8))])]++ @Test func `an Always On board marks the guest's product, once`() throws {+ let original = Self.tree(product: Node("product", [("graphics-featureset-class", Data("APPLE7\0".utf8))]),+ armIO: Self.guestArmIO)+ let board = Self.tree(product: Node("product"), armIO: [+ Node("disp0", [("compatible", Data("disp0,t8150\0".utf8)), ("always-on-time", Node.uint32(1))]),+ ])+ let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withPhoneProduct(original, board: board)+ #expect(changes.map(\.property) == ["product/vphone-always-on-display"])+ #expect(delta == 36 + 4)+ #expect(patched == Self.tree(product: Node("product", [+ ("graphics-featureset-class", Data("APPLE7\0".utf8)),+ ("vphone-always-on-display", Node.uint32(1)),+ ]), armIO: Self.guestArmIO))+ // The marker is all: the guest's arm-io gets no disp0.+ #expect(!String(decoding: patched, as: UTF8.self).contains("always-on-time"))++ let (twice, again, _) = try CustomFirmwarePostRestoreDeviceTree.withPhoneProduct(patched, board: board)+ #expect(again.isEmpty)+ #expect(twice == patched)+ }++ @Test func `a board without an Always On display leaves the product unmarked`() throws {+ let original = Self.tree(product: Node("product", [("graphics-featureset-class", Data("APPLE7\0".utf8))]),+ armIO: Self.guestArmIO)+ let board = Self.tree(product: Node("product"), armIO: [+ Node("disp0", [("compatible", Data("disp0,t8140\0".utf8))]),+ ])+ let (patched, changes, _) = try CustomFirmwarePostRestoreDeviceTree.withPhoneProduct(original, board: board)+ #expect(changes.isEmpty)+ #expect(patched == original)+ }}@Suite("Foldable VM sub-type")