Run a virtual iPhone on an Apple Silicon Mac.
Swift
Hash the bundled vphoned once per file, not once per health probe
Jackyc35e99beac38
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swiftindex 582518c1..8c02add7 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift@@ -1,4 +1,3 @@-import CryptoKitimport Darwinimport Foundationimport Virtualization@@ -64,6 +63,8 @@ final class VPhoneGuestControl {private(set) var guestIPAddress: String?private(set) var guestIOSVersion: String?@ObservationIgnored var guestBinaryURL: URL?+ /// The bundled vphoned's hash, kept between probes (VPhoneFileDigestCache).+ @ObservationIgnored private var guestBinaryDigest = VPhoneFileDigestCache()@ObservationIgnored var onConnect: (([String]) -> Void)?@ObservationIgnored var onDisconnect: (() -> Void)?/// What en0 should be configured as, from the manifest. Applied on every@@ -200,17 +201,16 @@ final class VPhoneGuestControl {throw ControlError.protocolError("incompatible guest API")}if let binary = guestBinaryURL,+ let hash = guestBinaryDigest.sha256(of: binary),+ hash != info["binary_hash"] as? String,let data = try? Data(contentsOf: binary, options: .mappedIfSafe){- let hash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()- if hash != info["binary_hash"] as? String {- print("[control] updating vphoned over HTTP...")- try await createDirectory(path: "/var/root/Library/Caches")- try await uploadFile(path: "/var/root/Library/Caches/vphoned.next", data: data)- _ = try await call("agent.apply_update", params: ["sha256": hash])- setDisconnected()- return- }+ print("[control] updating vphoned over HTTP...")+ try await createDirectory(path: "/var/root/Library/Caches")+ try await uploadFile(path: "/var/root/Library/Caches/vphoned.next", data: data)+ _ = try await call("agent.apply_update", params: ["sha256": hash])+ setDisconnected()+ return}// The probe repeats every few seconds; assign only changes so// observing windows do not redraw on every probe.diff --git a/VPhoneKit/VPhoneCoreKit/Support/VPhoneFileDigestCache.swift b/VPhoneKit/VPhoneCoreKit/Support/VPhoneFileDigestCache.swiftnew file mode 100644index 00000000..78d32e30--- /dev/null+++ b/VPhoneKit/VPhoneCoreKit/Support/VPhoneFileDigestCache.swift@@ -0,0 +1,63 @@+import CryptoKit+import Foundation++/// The SHA-256 of one file, hashed again only when the file's identity, size+/// or modification time changes.+///+/// `vphone-vm` compares the bundled vphoned with the guest's on every health+/// probe, every three seconds while connected. Reading and hashing the 9 MB+/// binary each time was most of an idle VM window's CPU in `vphone-vm`,+/// although the file in an installed bundle never changes while it runs.+public struct VPhoneFileDigestCache: Sendable {+ struct Stamp: Equatable {+ var path: String+ var device: UInt64+ var inode: UInt64+ var size: Int64+ var modifiedSeconds: Int+ var modifiedNanoseconds: Int+ }++ private var stamp: Stamp?+ private var digest: String?+ /// How often the file was read and hashed, for tests.+ public private(set) var hashCount = 0++ public init() {}++ /// The lowercase hex SHA-256 of the file at `url`, or nil when it cannot+ /// be read.+ public mutating func sha256(of url: URL) -> String? {+ guard let current = Self.stamp(of: url) else {+ stamp = nil+ digest = nil+ return nil+ }+ if current == stamp, let digest {+ return digest+ }+ guard let data = try? Data(contentsOf: url, options: .mappedIfSafe) else {+ stamp = nil+ digest = nil+ return nil+ }+ hashCount += 1+ let hex = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ stamp = current+ digest = hex+ return hex+ }++ static func stamp(of url: URL) -> Stamp? {+ var info = stat()+ guard stat(url.path, &info) == 0 else { return nil }+ return Stamp(+ path: url.path,+ device: UInt64(bitPattern: Int64(info.st_dev)),+ inode: UInt64(info.st_ino),+ size: Int64(info.st_size),+ modifiedSeconds: Int(info.st_mtimespec.tv_sec),+ modifiedNanoseconds: Int(info.st_mtimespec.tv_nsec),+ )+ }+}diff --git a/VPhoneKit/VPhoneCoreKitTests/Support/FileDigestCacheTests.swift b/VPhoneKit/VPhoneCoreKitTests/Support/FileDigestCacheTests.swiftnew file mode 100644index 00000000..428a38ad--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Support/FileDigestCacheTests.swift@@ -0,0 +1,77 @@+import CryptoKit+import Foundation+import Testing+@testable import VPhoneCoreKit++struct FileDigestCacheTests {+ @Test func `an unchanged file is hashed once`() throws {+ let url = try Self.makeFile(Data("vphoned".utf8))+ defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }+ var cache = VPhoneFileDigestCache()+ let first = cache.sha256(of: url)+ for _ in 0 ..< 100 {+ #expect(cache.sha256(of: url) == first)+ }+ #expect(first == Self.hex(Data("vphoned".utf8)))+ #expect(cache.hashCount == 1)+ }++ @Test func `a rewritten file is hashed again`() throws {+ let url = try Self.makeFile(Data("old build".utf8))+ defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }+ var cache = VPhoneFileDigestCache()+ _ = cache.sha256(of: url)+ // Same size, later modification time.+ try Data("new build".utf8).write(to: url)+ try FileManager.default.setAttributes([.modificationDate: Date().addingTimeInterval(5)], ofItemAtPath: url.path)+ #expect(cache.sha256(of: url) == Self.hex(Data("new build".utf8)))+ #expect(cache.hashCount == 2)+ }++ @Test func `a file replaced by a rename is hashed again`() throws {+ let url = try Self.makeFile(Data("A".utf8))+ defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }+ var cache = VPhoneFileDigestCache()+ _ = cache.sha256(of: url)+ let replacement = url.deletingLastPathComponent().appendingPathComponent("next")+ try Data("B".utf8).write(to: replacement)+ let attributes = try FileManager.default.attributesOfItem(atPath: url.path)+ try FileManager.default.setAttributes([.modificationDate: attributes[.modificationDate] as Any],+ ofItemAtPath: replacement.path)+ _ = try FileManager.default.replaceItemAt(url, withItemAt: replacement)+ #expect(cache.sha256(of: url) == Self.hex(Data("B".utf8)))+ }++ @Test func `another path is hashed on its own`() throws {+ let a = try Self.makeFile(Data("A".utf8))+ let b = try Self.makeFile(Data("B".utf8))+ defer {+ try? FileManager.default.removeItem(at: a.deletingLastPathComponent())+ try? FileManager.default.removeItem(at: b.deletingLastPathComponent())+ }+ var cache = VPhoneFileDigestCache()+ #expect(cache.sha256(of: a) == Self.hex(Data("A".utf8)))+ #expect(cache.sha256(of: b) == Self.hex(Data("B".utf8)))+ }++ @Test func `a missing file has no digest and forgets the old one`() throws {+ let url = try Self.makeFile(Data("A".utf8))+ var cache = VPhoneFileDigestCache()+ _ = cache.sha256(of: url)+ try FileManager.default.removeItem(at: url.deletingLastPathComponent())+ #expect(cache.sha256(of: url) == nil)+ }++ private static func makeFile(_ data: Data) throws -> URL {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("FileDigestCacheTests-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ let url = root.appendingPathComponent("vphoned")+ try data.write(to: url)+ return url+ }++ private static func hex(_ data: Data) -> String {+ SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ }+}