Run a virtual iPhone on an Apple Silicon Mac.
Swift
vphoned: Duo pose validation, native orientation map, boot pose restore
Jacky315b44c5e69e
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Device.swift b/VPhoneDaemon/Daemon/GuestAPI+Device.swiftindex 41abc2e8..59d5e064 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Device.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Device.swift@@ -61,6 +61,12 @@ extension GuestAPI {return try setDeviceName(name as? String)case "device.ioreg":return try ioregistry(plane: optionalString(params, "plane") ?? "IOService")+ case "device.input_devices":+ return vp_hid_input_devices()+ case "device.displays":+ return ["displays": vp_display_probe()]+ case "display.modes":+ return vp_display_modes()case "device.environment":return try environmentReport()case "device.basebin":@@ -80,13 +86,85 @@ extension GuestAPI {let previousPose = (accelerometer["degrees"] as? NSNumber).map { String($0.intValue) }let publishesPose = accelerometer["provider_running"] as? Bool == truelet previousInterface = interfaceRotationDegrees()- if publishesPose {- guard vp_accelerometer_set_orientation(orientation) else {- throw GuestAPIError.operationFailed("Could not publish the accelerometer orientation")+ var mappedRotation: GuestDisplayRotation?+ var originalDevicePose: [String: Any]?+ if ((try? deviceSnapshot())?["model"] as? String) == "iPhone19,4" {+ let mapping = vp_display_orientation_mapping()+ let pose = vp_device_pose_get()+ guard mapping["available"] as? Bool == true,+ let values = mapping["deviceOrientations"] as? [Int],+ let resolved = GuestDisplayRotation.resolve(orientation, deviceOrientations: values),+ pose["available"] as? Bool == true,+ pose["device_orientation"] is NSNumber, pose["hinge"] is NSNumber, pose["tabletop"] is NSNumber+ else {+ throw GuestAPIError.operationFailed("The active Duo scene orientation map or pose is unavailable")}+ mappedRotation = resolved+ originalDevicePose = pose}+ defer {+ if mappedRotation != nil { GuestFoldPose.finishExplicitRequest() }+ }+ var devicePosePublished = falsedo {- return try setRotation(orientation)+ if let mappedRotation, let originalDevicePose {+ GuestFoldPose.cancelStartupRestore()+ guard vp_device_pose_set(+ Int32(mappedRotation.deviceOrientation),+ (originalDevicePose["hinge"] as! NSNumber).int32Value,+ (originalDevicePose["tabletop"] as! NSNumber).int32Value+ ) else { throw GuestAPIError.operationFailed("Could not publish the mapped Duo device pose") }+ devicePosePublished = true+ }+ if publishesPose {+ let physicalSpec = mappedRotation.map { String($0.accelerometerDegrees) } ?? orientation+ guard vp_accelerometer_set_orientation(physicalSpec) else {+ throw GuestAPIError.operationFailed("Could not publish the accelerometer orientation")+ }+ }+ if mappedRotation != nil {+ // The Duo scene's inverse mounting map is native and+ // does not itself enqueue UIKit's orientation+ // arbitration. Publish the same bounded refresh+ // sequence used by the native pose pipeline before+ // waiting for SpringBoard's scene receipt.+ _ = try? postDarwinNotification("com.vphone.display.orientation.mapping.request", state: nil)+ _ = try? postDarwinNotification("com.vphone.display.orientation.inputs.refresh", state: nil)+ _ = try? postDarwinNotification("com.vphone.display.orientation.arbitration.refresh", state: nil)+ _ = try? postDarwinNotification("com.vphone.display.orientation.actuation.refresh", state: nil)+ _ = try? postDarwinNotification("com.vphone.display.presentation.wallpaper.pulse", state: nil)+ _ = try? postDarwinNotification("com.vphone.display.presentation.clock.refresh", state: nil)+ }+ var result: [String: Any]+ if let mappedRotation {+ // The foldable pose transition is asynchronous. An AX+ // forced rotation during that transition can race it;+ // accept the native scene's receipt instead.+ let deadline = ProcessInfo.processInfo.systemUptime + 2+ while interfaceRotationDegrees() != mappedRotation.interfaceDegrees,+ ProcessInfo.processInfo.systemUptime < deadline {+ Thread.sleep(forTimeInterval: 0.05)+ }+ guard interfaceRotationDegrees() == mappedRotation.interfaceDegrees else {+ throw GuestAPIError.operationFailed("The Duo scene did not settle at the requested orientation")+ }+ // Reassert only the already-settled angle: this also+ // refreshes Icli's upright screenshot geometry and+ // synchronizes the pointer without driving the fold.+ result = try setRotation(orientation)+ } else {+ result = try setRotation(orientation)+ }+ if let mappedRotation, let originalDevicePose {+ let actual = vp_device_pose_get()+ guard actual["device_orientation"] as? Int == mappedRotation.deviceOrientation,+ actual["hinge"] as? Int == originalDevicePose["hinge"] as? Int,+ actual["tabletop"] as? Int == originalDevicePose["tabletop"] as? Int+ else { throw GuestAPIError.operationFailed("The mapped Duo pose did not apply") }+ result["physical_pose"] = actual+ result["accelerometer_degrees"] = mappedRotation.accelerometerDegrees+ }+ return result} catch {// A refused rotation leaves the guest as it was. The pose// is persisted, and a refused request still turns iPadOS's@@ -94,11 +172,35 @@ extension GuestAPI {// left the interface portrait and the pointer upside down,// so the mouse ran backwards. Asking again for the// interface's own orientation turns the pointer back.- if publishesPose, let previousPose {+ let ownsGravity = mappedRotation.map { vp_accelerometer_get()["degrees"] as? Int == $0.accelerometerDegrees } ?? true+ if publishesPose, ownsGravity, let previousPose {_ = vp_accelerometer_set_orientation(previousPose)}+ if devicePosePublished, let mappedRotation, let originalDevicePose {+ let current = vp_device_pose_get()+ if current["device_orientation"] as? Int == mappedRotation.deviceOrientation,+ current["hinge"] as? Int == originalDevicePose["hinge"] as? Int,+ current["tabletop"] as? Int == originalDevicePose["tabletop"] as? Int {+ _ = vp_device_pose_set(+ (originalDevicePose["device_orientation"] as! NSNumber).int32Value,+ (originalDevicePose["hinge"] as! NSNumber).int32Value,+ (originalDevicePose["tabletop"] as! NSNumber).int32Value+ )+ }+ }if let previousInterface {- _ = try? setRotation(String(previousInterface))+ if mappedRotation == nil {+ _ = try? setRotation(String(previousInterface))+ } else {+ let deadline = ProcessInfo.processInfo.systemUptime + 2+ while interfaceRotationDegrees() != previousInterface,+ ProcessInfo.processInfo.systemUptime < deadline {+ Thread.sleep(forTimeInterval: 0.05)+ }+ if interfaceRotationDegrees() == previousInterface {+ _ = try? setRotation(String(previousInterface))+ }+ }}throw error}@@ -108,8 +210,12 @@ extension GuestAPI {return rotationcase "display.orientation":return interfaceOrientation()+ case "display.orientation_mapping", "display.geometry":+ return vp_display_orientation_mapping()case "display.posture":return try setDevicePose(params)+ case "display.pose":+ return vp_device_pose_get()case "display.rotation_lock":guard let locked = params["locked"] as? Bool else {throw GuestAPIError.invalidRequest("locked must be true or false")@@ -175,9 +281,23 @@ extension GuestAPI {"landscape-right": 4, "face-up": 5, "face-down": 6,]- /// Set a foldable guest's pose through SpringBoard's test-automation- /// override: `hinge` (a name or 0–4), `orientation` (a name or 0–6,- /// default portrait) and `tabletop` (0–10, default 0, ambiguous).+ /// SpringBoard's own hinge-angle table, one angle per hinge state, so the+ /// virtual hinge reports what the pose override implies.+ static let poseHingeAngles: [Double] = [0, 0, 90, 180, 180]++ /// Apple's screen-state positions, from suiatool's help text shipped in+ /// SpringBoardFoundation: closed, book (~100°) and open (a fraction of+ /// the 180° range, or a name).+ static let posePositions: [String: Double] = ["closed": 0, "book": 100, "open": 180]++ /// Set a foldable guest's pose the way Apple's Duo tooling does, driving+ /// SpringBoard's test-automation override and the virtual hinge HID+ /// service from one request. The official model is three screen states —+ /// `position` `closed`, `book` (~100°) or `open`, or a fraction 0–1 of+ /// the hinge's 180° — changed by a sweep from the current angle+ /// (`duration` seconds; default the per-direction hand-fold time, opening+ /// faster than closing; 0 an instant swap; `profile` `continuous` or+ /// `fade`). The older `hinge` names still work and set the pose at once.private static func setDevicePose(_ params: [String: Any]) throws -> [String: Any] {func value(_ key: String, names: [String: Int], range: ClosedRange<Int>, default fallback: Int?) throws -> Int {if let name = params[key] as? String {@@ -195,13 +315,153 @@ extension GuestAPI {guard params[key] == nil, let fallback else { throw GuestAPIError.invalidRequest("\(key) is required") }return fallback}- let hinge = try value("hinge", names: poseHingeStates, range: 0 ... 4, default: nil)++ var angle: Double?+ var sweep = false+ var durationMs = -1.0+ var profile = 0+ if let position = params["position"] {+ let target: Double+ switch position {+ case let name as String:+ guard let named = Self.posePositions[name.lowercased()] else {+ throw GuestAPIError.invalidRequest("position must be closed, book, open, or a fraction in 0...1")+ }+ target = named+ case let number as NSNumber where CFGetTypeID(number) != CFBooleanGetTypeID():+ let fraction = number.doubleValue+ guard fraction.isFinite, 0 ... 1 ~= fraction else {+ throw GuestAPIError.invalidRequest("position must be closed, book, open, or a fraction in 0...1")+ }+ target = fraction * 180+ default:+ throw GuestAPIError.invalidRequest("position must be closed, book, open, or a fraction in 0...1")+ }+ angle = target+ sweep = true+ if let requested = params["duration"] as? NSNumber, CFGetTypeID(requested) != CFBooleanGetTypeID() {+ let seconds = requested.doubleValue+ guard seconds.isFinite, 0 ... 10 ~= seconds else {+ throw GuestAPIError.invalidRequest("duration must be a number of seconds in 0...10")+ }+ durationMs = seconds * 1000+ }+ if let name = params["profile"] as? String {+ switch name.lowercased() {+ case "continuous": profile = 0+ case "fade": profile = 1+ default:+ throw GuestAPIError.invalidRequest("profile must be continuous or fade")+ }+ }+ }++ let hinge = try value("hinge", names: poseHingeStates, range: 0 ... 4, default: angle.map(angleToHingeState))let orientation = try value("orientation", names: poseOrientations, range: 0 ... 6, default: 1)let tabletop = try value("tabletop", names: [:], range: 0 ... 10, default: 0)+ if angle == nil {+ angle = Self.poseHingeAngles[hinge]+ if let requested = params["angle"] as? NSNumber, CFGetTypeID(requested) != CFBooleanGetTypeID() {+ guard requested.doubleValue.isFinite, 0 ... 180 ~= requested.doubleValue else {+ throw GuestAPIError.invalidRequest("angle must be a number in 0...180")+ }+ angle = requested.doubleValue+ }+ }+ GuestFoldPose.cancelStartupRestore()+ defer { GuestFoldPose.finishExplicitRequest() }guard vp_device_pose_set(Int32(orientation), Int32(hinge), Int32(tabletop)) else {throw GuestAPIError.operationFailed("SpringBoardServices has no device pose override on this guest")}- return ["hinge": hinge, "orientation": orientation, "tabletop": tabletop]+ // The pose override has landed; the hinge half is published beside it,+ // and its absence (no virtual hinge service on this guest) does not+ // undo the pose.+ let published = sweep+ ? vp_hinge_sweep(angle!, durationMs, Int32(profile))+ : vp_hinge_set(angle!)+ if ((try? deviceSnapshot())?["model"] as? String) == "iPhone19,4" {+ GuestFoldPose.requestViewport(for: angle!)+ let expected = angle! < 5 ? [0.0, 0.0, 466.0, 678.0] : [0.0, 0.0, 669.0, 951.0]+ let deadline = ProcessInfo.processInfo.systemUptime + 3+ var applied = false+ repeat {+ let geometry = vp_display_orientation_mapping()+ if geometry["available"] as? Bool == true,+ geometry["persistentViewport"] as? Bool == true,+ let bounds = geometry["configurationBounds"] as? [NSNumber],+ bounds.map(\.doubleValue) == expected {+ applied = true+ break+ }+ Thread.sleep(forTimeInterval: 0.05)+ } while ProcessInfo.processInfo.systemUptime < deadline+ guard applied else { throw GuestAPIError.operationFailed("Duo logical viewport did not reach the requested size") }++ // A fold transition changes the active panel's native mounting+ // map. Preserve the requested portrait pose across a landscape+ // -> cover -> inner sequence by resolving interface portrait+ // against the newly active map, rather than reusing the old+ // physical device orientation.+ // Both panels present portrait at rest: the cover starts+ // portrait, and the unfolded inner panel presents portrait+ // through its rotated mounting (device 3 in the measured+ // [3,4,2,1] table). Resolve interface portrait after the+ // viewport transition; landscape stays an explicit rotation.+ let desiredInterface = "0"+ if orientation == Self.poseOrientations["portrait"],+ let values = vp_display_orientation_mapping()["deviceOrientations"] as? [Int],+ let portrait = GuestDisplayRotation.resolve(desiredInterface, deviceOrientations: values) {+ let current = vp_device_pose_get()+ _ = vp_device_pose_set(+ Int32(portrait.deviceOrientation),+ (current["hinge"] as? NSNumber)?.int32Value ?? Int32(hinge),+ (current["tabletop"] as? NSNumber)?.int32Value ?? Int32(tabletop)+ )+ _ = vp_accelerometer_set_orientation(String(portrait.accelerometerDegrees))+ _ = try? postDarwinNotification("com.vphone.display.orientation.mapping.request", state: nil)+ _ = try? postDarwinNotification("com.vphone.display.orientation.inputs.refresh", state: nil)+ _ = try? postDarwinNotification("com.vphone.display.orientation.arbitration.refresh", state: nil)+ _ = try? postDarwinNotification("com.vphone.display.orientation.actuation.refresh", state: nil)+ _ = try? postDarwinNotification("com.vphone.display.presentation.wallpaper.pulse", state: nil)+ _ = try? postDarwinNotification("com.vphone.display.presentation.clock.refresh", state: nil)+ // The scene may finish the fold transition after the first+ // notification batch. Give native arbitration a bounded+ // settle window and re-read the map once before returning.+ let orientationDeadline = ProcessInfo.processInfo.systemUptime + 2+ while interfaceRotationDegrees() != portrait.interfaceDegrees,+ ProcessInfo.processInfo.systemUptime < orientationDeadline {+ Thread.sleep(forTimeInterval: 0.05)+ }+ if interfaceRotationDegrees() != portrait.interfaceDegrees {+ // Reuse the same public rotation path once the new panel+ // is fully selected; it resolves the post-fold map again+ // instead of relying on a stale pre-transition snapshot.+ _ = try? setRotation("0")+ }+ }+ }+ var hingeState = vp_hinge_get()+ hingeState["applied"] = published+ var reply: [String: Any] = [+ "hinge": hinge, "orientation": orientation, "tabletop": tabletop,+ "angle": angle!, "hinge_hid": hingeState,+ ]+ if sweep {+ reply["sweep"] = [+ "duration_ms": durationMs,+ "profile": profile == 1 ? "fade" : "continuous",+ ]+ }+ return reply+ }++ /// The hinge state a settled angle reports: closed under 5°, open flat+ /// from 170°, partially open between — the bands Apple's recorded Duo+ /// samples hold.+ private static func angleToHingeState(_ angle: Double) -> Int {+ if angle < 5 { return 1 }+ if angle >= 170 { return 3 }+ return 2}private static func brightnessState() -> [String: Any] {diff --git a/VPhoneDaemon/Daemon/GuestAPI+Process.swift b/VPhoneDaemon/Daemon/GuestAPI+Process.swiftindex 84e32181..d1b028fa 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Process.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Process.swift@@ -9,6 +9,10 @@ import VphonedNativeextension GuestAPI {static func executeProcess(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {switch method {+ case "process.spawn":+ return try spawnProcess(params)+ case "poster.inspect":+ return try inspectPoster(params)case "processes.list":return try processList(filter: optionalString(params, "filter"))case "processes.kill":@@ -34,6 +38,89 @@ extension GuestAPI {}}+ /// Read-only poster probe plumbing. The signed helper is intentionally+ /// optional until the guest payload is installed; callers get an explicit+ /// unavailable result rather than a synthetic scene snapshot.+ private static func inspectPoster(_ params: [String: Any]) throws -> [String: Any] {+ let pid = try integer(params, "pid")+ guard pid > 1 else { throw GuestAPIError.invalidRequest("pid must be a positive process id") }+ let helper = "/usr/libexec/vphone-poster-inspect"+ guard access(helper, X_OK) == 0 else {+ return ["available": false, "pid": pid, "reason": "poster instrumented helper is not installed"]+ }+ // Helper execution is deliberately not enabled until its payload hash+ // and target identity checks are wired into the guest manifest.+ return ["available": false, "pid": pid, "reason": "poster helper is present but not admitted"]+ }++ // This is deliberately a small diagnostic surface. It is not a general+ // shell: every executable has a fixed path and arguments are passed+ // directly to posix_spawn (there is no shell expansion).+ private static func spawnProcess(_ params: [String: Any]) throws -> [String: Any] {+ guard let name = params["executable"] as? String,+ let executable = GuestProcessSpawnPolicy.executables[name] else { throw GuestAPIError.invalidRequest("executable must be one of " + GuestProcessSpawnPolicy.executables.keys.sorted().joined(separator: ", ")) }+ let arguments = params["arguments"] as? [String] ?? []+ let timeout = (params["timeout_seconds"] as? NSNumber).map { $0.doubleValue } ?? 3.0+ if let error = GuestProcessSpawnPolicy.validate(executable: name, arguments: arguments, timeout: timeout) { throw GuestAPIError.invalidRequest(error) }++ var stdoutPipe: [Int32] = [0, 0]+ var stderrPipe: [Int32] = [0, 0]+ guard pipe(&stdoutPipe) == 0, pipe(&stderrPipe) == 0 else {+ throw GuestAPIError.operationFailed("pipe: " + String(cString: strerror(errno)))+ }+ defer {+ close(stdoutPipe[0]); close(stdoutPipe[1]); close(stderrPipe[0]); close(stderrPipe[1])+ }++ var argv = [UnsafeMutablePointer<CChar>?](repeating: nil, count: arguments.count + 2)+ argv[0] = strdup(executable)+ for (index, argument) in arguments.enumerated() { argv[index + 1] = strdup(argument) }+ defer { for value in argv where value != nil { free(value) } }+ var actions: posix_spawn_file_actions_t?+ posix_spawn_file_actions_init(&actions)+ defer { posix_spawn_file_actions_destroy(&actions) }+ posix_spawn_file_actions_adddup2(&actions, stdoutPipe[1], STDOUT_FILENO)+ posix_spawn_file_actions_adddup2(&actions, stderrPipe[1], STDERR_FILENO)+ posix_spawn_file_actions_addclose(&actions, stdoutPipe[0])+ posix_spawn_file_actions_addclose(&actions, stderrPipe[0])+ var pid: pid_t = 0+ let spawnError = posix_spawn(&pid, executable, &actions, nil, &argv, environ)+ guard spawnError == 0 else { throw GuestAPIError.operationFailed("posix_spawn: " + String(cString: strerror(spawnError))) }+ close(stdoutPipe[1]); close(stderrPipe[1])++ fcntl(stdoutPipe[0], F_SETFL, O_NONBLOCK)+ fcntl(stderrPipe[0], F_SETFL, O_NONBLOCK)+ var output = Data(); var errorOutput = Data(); var status: Int32 = 0+ let deadline = Date().addingTimeInterval(timeout)+ var exited = false+ while Date() < deadline {+ drainSpawnPipe(stdoutPipe[0], into: &output)+ drainSpawnPipe(stderrPipe[0], into: &errorOutput)+ if waitpid(pid, &status, WNOHANG) == pid { exited = true; break }+ usleep(10_000)+ }+ if !exited {+ kill(pid, SIGKILL)+ _ = waitpid(pid, &status, 0)+ }+ drainSpawnPipe(stdoutPipe[0], into: &output); drainSpawnPipe(stderrPipe[0], into: &errorOutput)+ return [+ "executable": executable, "arguments": arguments, "pid": Int(pid),+ "timed_out": !exited, "exit_code": exited && (status & 0x7f) == 0 ? Int((status >> 8) & 0xff) : NSNull(),+ "signal": exited && (status & 0x7f) != 0 ? Int(status & 0x7f) : NSNull(),+ "stdout": String(decoding: output, as: UTF8.self), "stderr": String(decoding: errorOutput, as: UTF8.self),+ ]+ }++ private static func drainSpawnPipe(_ fd: Int32, into data: inout Data) {+ guard data.count < GuestProcessSpawnPolicy.outputLimit else { return }+ var buffer = [UInt8](repeating: 0, count: min(4096, GuestProcessSpawnPolicy.outputLimit - data.count))+ while true {+ let count = read(fd, &buffer, buffer.count)+ if count > 0 { data.append(contentsOf: buffer[0..<count]) } else { break }+ }+ }+/// The three kernel memory sysctls of `memory.jetsam`, without its priority/// list and property plists, for panels that poll.private static func memoryPressure() -> [String: Any] {diff --git a/VPhoneDaemon/Daemon/GuestDisplayRotation.swift b/VPhoneDaemon/Daemon/GuestDisplayRotation.swiftnew file mode 100644index 00000000..c2819ee7--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestDisplayRotation.swift@@ -0,0 +1,25 @@+import Foundation++/// Interface requests use UIKit orientation codes; the native scene supplies+/// the inverse device map, including a foldable panel's mounting transform.+struct GuestDisplayRotation: Equatable, Sendable {+ let interfaceDegrees: Int+ let deviceOrientation: Int+ let accelerometerDegrees: Int++ static func resolve(_ spec: String, deviceOrientations: [Int]) -> Self? {+ guard deviceOrientations.count == 4, Set(deviceOrientations) == Set(1 ... 4) else { return nil }+ let interfaceOrientation: Int+ switch spec.lowercased() {+ case "0", "portrait": interfaceOrientation = 1+ case "90", "landscape-left", "left": interfaceOrientation = 4+ case "180", "upside-down", "portrait-upside-down": interfaceOrientation = 2+ case "270", "landscape-right", "right": interfaceOrientation = 3+ default: return nil+ }+ let device = deviceOrientations[interfaceOrientation - 1]+ let degrees = [1: 0, 2: 180, 3: 270, 4: 90][device]!+ let interfaceDegrees = [1: 0, 2: 180, 3: 270, 4: 90][interfaceOrientation]!+ return Self(interfaceDegrees: interfaceDegrees, deviceOrientation: device, accelerometerDegrees: degrees)+ }+}diff --git a/VPhoneDaemon/Daemon/GuestFoldPose.swift b/VPhoneDaemon/Daemon/GuestFoldPose.swiftnew file mode 100644index 00000000..547ac51e--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestFoldPose.swift@@ -0,0 +1,143 @@+import Foundation+import notify+import VphonedNative++/// Re-applies a foldable guest's saved posture after each boot.+///+/// The posture `display.posture` sets rides two channels: SpringBoard's+/// test-automation pose override — state of the running SpringBoard, gone+/// with it at shutdown — and the virtual hinge preference, which survives+/// but is only read when the provider enumerates. A rebooted guest that had+/// the pose open therefore starts with the hinge reporting open while+/// SpringBoard still holds its default pose, until the pose is set again;+/// SpringBoard's own VM-sub-type restore path cannot stand in, because its+/// `SBFDevicePoseLastKnown*` defaults are written on display-mode+/// transitions, which a single display never makes (measured 2026-10-25:+/// they stay zero). Retry until SpringBoard reports the restored pose, but+/// cancel immediately when an explicit request supersedes the boot snapshot.+///+/// Only a guest whose hinge was configured is touched. The home grid itself+/// still needs a working display-content transition; this restore does not+/// establish one. See Research/Guest/iphone_duo_bringup.md.+enum GuestFoldPose {+ private final class RestoreState: @unchecked Sendable {+ let lock = NSLock()+ var cancelled = false+ var generation: UInt64 = 0+ var explicitRequest = false+ var latestPose: [Int32]?+ var observerInstalled = false+ }++private static let restoration = RestoreState()++ static func requestViewport(for angle: Double) {+ notify_post(angle < 5 ? "com.vphone.display.viewport.apply.cover" : "com.vphone.display.viewport.apply.inner")+ }++ /// A new explicit request supersedes the boot snapshot. Serialize this+ /// with publication so an in-flight retry cannot overwrite the request.+ static func cancelStartupRestore() {+ restoration.lock.withLock {+ restoration.cancelled = true+ restoration.generation &+= 1+ restoration.explicitRequest = true+ }+ }++ /// Capture the actual final state, including a failed request's rollback.+ /// Never retain the requested value as proof that SpringBoard applied it.+ static func finishExplicitRequest() {+ restoration.lock.withLock {+ let actual = vp_device_pose_get()+ restoration.latestPose = poseValues(actual)+ restoration.explicitRequest = false+ restoration.generation &+= 1+ }+ }++ private static func poseValues(_ actual: [String: Any]) -> [Int32]? {+ guard actual["available"] as? Bool == true,+ let orientation = actual["device_orientation"] as? Int32,+ let hinge = actual["hinge"] as? Int32,+ let tabletop = actual["tabletop"] as? Int32,+ (1...4).contains(orientation), (1...4).contains(hinge)+ else { return nil }+ return [orientation, hinge, tabletop]+ }++ private static let restoreQueue = DispatchQueue(label: "vphoned.fold-pose-replay", qos: .utility)++ private static func observeSpringBoardStartup() {+ let install = restoration.lock.withLock {+ if restoration.observerInstalled { return false }+ restoration.observerInstalled = true+ return true+ }+ guard install else { return }+ var token: Int32 = 0+ let status = notify_register_dispatch("com.apple.springboard.finishedstartup", &token, restoreQueue) { _ in+ let generation = restoration.lock.withLock { restoration.generation }+ for delay in [0.5, 1.5, 3.0] {+ restoreQueue.asyncAfter(deadline: .now() + delay) {+ restoration.lock.withLock {+ guard restoration.generation == generation, !restoration.explicitRequest,+ let pose = restoration.latestPose,+ vp_hinge_get()["enabled"] as? Bool == true else { return }+ if let angle = vp_hinge_get()["angle"] as? Double { requestViewport(for: angle) }+ if poseValues(vp_device_pose_get()) == pose { return }+ _ = vp_device_pose_set(pose[0], pose[1], pose[2])+ NSLog("vphoned: replay latest fold pose after SpringBoard startup")+ }+ }+ }+ }+ if status != 0 {+ NSLog("vphoned: cannot observe SpringBoard pose lifecycle: %u", status)+ }+ }++ /// SpringBoard is up well inside this on a normal boot; a first boot+ /// after a restore takes longer, and the later attempts cover it. The+ /// setter reports only submission, so read the actual pose before+ /// deciding whether another retry is needed.+ private static let attemptDelays: [TimeInterval] = [8, 12, 15, 20, 30, 45, 60, 90]++ static func startOnStartup() {+ let hinge = vp_hinge_get()+ guard hinge["enabled"] as? Bool == true, let angle = hinge["angle"] as? Double else { return }+ observeSpringBoardStartup()+ NSLog("vphoned: fold pose restore: %.0f° over the boot ladder", angle)+ DispatchQueue.global(qos: .utility).async {+ var waited: TimeInterval = 0+ for delay in attemptDelays {+ Thread.sleep(forTimeInterval: delay - waited)+ waited = delay+ let expectedHinge = hingeState(for: angle)+ let published = restoration.lock.withLock {+ guard !restoration.cancelled else { return false }+ _ = vp_device_pose_set(1, Int32(expectedHinge), 0)+ _ = vp_hinge_set(angle)+ requestViewport(for: angle)+ restoration.latestPose = poseValues(vp_device_pose_get())+ return true+ }+ guard published else { return }+ let actual = vp_device_pose_get()+ if actual["available"] as? Bool == true,+ actual["device_orientation"] as? Int == 1,+ actual["hinge"] as? Int == expectedHinge {+ return+ }+ }+ }+ }++ /// SpringBoard's hinge-state bands: closed below 5°, open-flat from 170°,+ /// partially open between.+ private static func hingeState(for angle: Double) -> Int {+ if angle < 5 { return 1 }+ if angle >= 170 { return 3 }+ return 2+ }+}diff --git a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swiftindex 6706ad66..d285a2e7 100644--- a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift+++ b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift@@ -224,6 +224,7 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandlecase (.GET, "/v1/device"): "device.snapshot"case (.GET, "/v1/device/screen"): "device.screen"case (.GET, "/v1/apps"): "apps.list"+ case (.POST, "/v1/process/spawn"): "process.spawn"case (.POST, "/v1/apps/refresh"): "apps.refresh"case (.POST, "/v1/apps/launch"): "apps.launch"case (.POST, "/v1/apps/terminate"): "apps.terminate"diff --git a/VPhoneDaemon/Daemon/GuestProcessSpawnPolicy.swift b/VPhoneDaemon/Daemon/GuestProcessSpawnPolicy.swiftnew file mode 100644index 00000000..922cb20b--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestProcessSpawnPolicy.swift@@ -0,0 +1,18 @@+import Foundation++/// Guest-free validation shared by vphoned and its regression harness.+enum GuestProcessSpawnPolicy {+ static let executables: [String: String] = [+ "ps": "/bin/ps", "launchctl": "/bin/launchctl", "log": "/usr/bin/log",+ ]+ static let outputLimit = 64 * 1024++ static func validate(executable name: String?, arguments: [String], timeout: Double) -> String? {+ guard let name, executables[name] != nil else { return "unknown executable" }+ guard arguments.count <= 16 else { return "too many arguments" }+ guard arguments.allSatisfy({ !$0.isEmpty && $0.utf8.count <= 256 && !$0.contains(where: { $0 == "\0" || $0 == "\n" || $0 == "\r" }) }) else { return "invalid argument" }+ guard arguments.joined().utf8.count <= 2048 else { return "arguments too long" }+ guard timeout.isFinite, timeout >= 0.1, timeout <= 10 else { return "invalid timeout" }+ return nil+ }+}diff --git a/VPhoneDaemon/Daemon/GuestServiceProfile.swift b/VPhoneDaemon/Daemon/GuestServiceProfile.swiftindex 638a3d28..c37152f5 100644--- a/VPhoneDaemon/Daemon/GuestServiceProfile.swift+++ b/VPhoneDaemon/Daemon/GuestServiceProfile.swift@@ -21,7 +21,7 @@ import Foundationenum GuestServiceProfile {/// Raised whenever a label list changes, and kept in the record, so a/// guest shows which list its overrides came from.- static let listVersion = 2+ static let listVersion = 3static let recordPath = "/var/db/vphoned/service-profile.plist"static let trimmed = "trimmed"static let none = "none"@@ -82,7 +82,8 @@ enum GuestServiceProfile {/// Appendix A of the 2026-10-07 measurement on `svctest-a` (iPhone, 27.0/// 24A435): the LaunchDaemons that were loaded at boot and stayed unloaded/// after the override, with the four traps below already taken out: 137,- /// less siriactionsd since list version 2 (see `neverDisable`).+ /// less siriactionsd since list version 2 and passd and financed since+ /// list version 3 (see `neverDisable`).static let base27: [String] = ["com.apple.CallHistorySyncHelper","com.apple.Maps.mapspushd",@@ -129,7 +130,6 @@ enum GuestServiceProfile {"com.apple.email.maild","com.apple.eyereliefd","com.apple.familycircled",- "com.apple.financed","com.apple.findmy.findmybeaconingd","com.apple.findmy.findmylocated","com.apple.finhealthd",@@ -174,7 +174,6 @@ enum GuestServiceProfile {"com.apple.nfcd","com.apple.ospredictiond","com.apple.parsec-fbf",- "com.apple.passd","com.apple.peopled","com.apple.perfpowermetricd","com.apple.photoanalysisd",@@ -285,6 +284,10 @@ enum GuestServiceProfile {// without it WidgetKit traps in each extension and the controls draw// blank."com.apple.siriactionsd",+ // Wallet: its first screen asks passd synchronously for the pass groups,+ // and passd waits on financed's Core Data store; with either disabled+ // FrontBoard kills Wallet at the scene-create watchdog.+ "com.apple.passd", "com.apple.financed",]// MARK: - Selectiondiff --git a/VPhoneDaemon/Daemon/main.swift b/VPhoneDaemon/Daemon/main.swiftindex 6ea3ac97..e898cb71 100644--- a/VPhoneDaemon/Daemon/main.swift+++ b/VPhoneDaemon/Daemon/main.swift@@ -19,6 +19,9 @@ GuestLockScreenIdle.startOnStartup()GuestMobileGestaltCache.dropIfStaleOnStartup()// 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 layout+// matches the posture it was booted with.+GuestFoldPose.startOnStartup()vp_vcam_start()GuestHomePodDisplay.startOnStartup()// Multi-finger injection is resolved here so the first pinch is not the calldiff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.hindex 858bf46f..e5cdd9c9 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -121,12 +121,32 @@ char * _Null_unspecified vp_ls_system_app_state(const char * _Null_unspecified bchar * _Null_unspecified vp_ls_unregister_system_app(const char * _Null_unspecified bundle_id, const char * _Null_unspecified app_path);#ifdef __OBJC__+/// Read-only HID service geometry and report descriptors; no event is sent.+NSDictionary<NSString *, id> * _Nonnull vp_hid_input_devices(void);/// The configured radians/second and the injected HID provider's heartbeat.NSDictionary * _Null_unspecified vp_gyro_get(void);BOOL vp_gyro_set(double x, double y, double z, bool enabled);/// The backboardd HID gravity provider used by display.rotation.NSDictionary * _Nonnull vp_accelerometer_get(void);BOOL vp_accelerometer_set_orientation(NSString * _Nonnull spec);+/// The virtual hinge HID provider behind display.posture: the fold angle+/// (degrees, closed 0) and whether the provider in backboardd is enumerated+/// and current.+NSDictionary * _Nonnull vp_hinge_get(void);+/// Every display-ish IOService object the guest published, with its small+/// properties: what the display stack bound, for the foldable display work.+NSArray * _Nonnull vp_display_probe(void);+/// Read-only CoreAnimation display modes and capability surface.+NSDictionary<NSString *, id> * _Nonnull vp_display_modes(void);+NSDictionary<NSString *, id> * _Nonnull vp_device_pose_get(void);+/// Fresh read-only inverse orientation map exported by the active SB scene.+NSDictionary<NSString *, id> * _Nonnull vp_display_orientation_mapping(void);+BOOL vp_hinge_set(double angleDegrees);+/// Sweep the hinge to `targetDegrees` the way Apple's Duo tooling does: over+/// a profiled transition (0 continuous fold, 1 fade-in-out), `durationMs` < 0+/// the per-direction default (opening faster than closing), 0 an instant+/// swap. Returns false on an out-of-range request.+BOOL vp_hinge_sweep(double targetDegrees, double durationMs, int profile);NSDictionary * _Null_unspecified vp_attitude_get(void);BOOL vp_attitude_set(double roll, double pitch, double yaw, bool enabled);diff --git a/VPhoneDaemon/Native/vphoned_display.m b/VPhoneDaemon/Native/vphoned_display.mnew file mode 100644index 00000000..787522fa--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_display.m@@ -0,0 +1,174 @@+/*+ * vphoned_display — enumerate the display pipeline as the guest sees it.+ *+ * The depth-capped registry walk `device.ioreg` offers stops above `gfx`,+ * where a paravirt display stack publishes its controllers, so whether the+ * guest bound one display or two has been unobservable right where the Duo+ * work needs it (SpringBoard's two-always-connected-displays gate). A flat+ * IOService match over the whole plane has no depth to stop at; this file+ * filters it to display-ish classes and reports each object's small+ * properties — the identity and geometry answers backboardd builds its+ * display set from.+ */++#import "Include/VphonedNative.h"++#include <IOKit/IOKitLib.h>+#include <dlfcn.h>+#include <objc/message.h>+#include <objc/runtime.h>++static NSDictionary *vpModeDescription(id mode) {+ NSMutableDictionary *result = [NSMutableDictionary dictionary];+ for (NSString *key in @[@"width", @"height", @"refreshRate", @"isVirtual", @"preferredUIScale", @"pointScale"]) {+ if (![mode respondsToSelector:NSSelectorFromString(key)]) continue;+ id value = [mode valueForKey:key];+ if ([value isKindOfClass:NSNumber.class] || [value isKindOfClass:NSString.class]) result[key] = value;+ }+ return result;+}++NSDictionary<NSString *, id> *vp_display_modes(void) {+ @try {+ dlopen("/System/Library/Frameworks/QuartzCore.framework/QuartzCore", RTLD_LAZY | RTLD_LOCAL);+ Class cls = objc_getClass("CADisplay");+ SEL enumerate = sel_registerName("displays");+ if (![cls respondsToSelector:enumerate]) return @{@"available": @NO, @"reason": @"CADisplay.displays unavailable"};+ SEL refresh = sel_registerName("updateDisplays");+ if ([cls respondsToSelector:refresh]) ((void (*)(id, SEL))objc_msgSend)(cls, refresh);+ id displays = ((id (*)(id, SEL))objc_msgSend)(cls, enumerate);+ if (![displays isKindOfClass:NSArray.class]) return @{@"available": @NO, @"reason": @"unexpected display collection"};+ NSMutableArray *rows = [NSMutableArray array];+ for (id display in displays) {+ NSMutableDictionary *row = [NSMutableDictionary dictionary];+ for (NSString *key in @[@"name", @"deviceName", @"displayId", @"displayType", @"allowsVirtualModes",+ @"isSupported", @"isExternal", @"isReference", @"isCloningSupported",+ @"isCloning", @"isCloned", @"pointScale", @"minimumLogicalScale",+ @"maximumLogicalScale", @"tag", @"seed", @"connectionSeed"]) {+ if (![display respondsToSelector:NSSelectorFromString(key)]) continue;+ id value = [display valueForKey:key];+ if ([value isKindOfClass:NSNumber.class] || [value isKindOfClass:NSString.class]) row[key] = value;+ }+ for (NSString *key in @[@"bounds", @"nativeSize", @"currentOrientation", @"nativeOrientation", @"logicalScale", @"uniqueId"]) {+ if ([display respondsToSelector:NSSelectorFromString(key)]) row[key] = [[display valueForKey:key] description] ?: @"";+ }+ if ([display respondsToSelector:sel_registerName("currentMode")]) row[@"current_mode"] = vpModeDescription([display valueForKey:@"currentMode"]);+ if ([display respondsToSelector:sel_registerName("availableModes")]) {+ NSMutableArray *modes = [NSMutableArray array];+ for (id mode in [display valueForKey:@"availableModes"]) {+ [modes addObject:vpModeDescription(mode)];+ if (modes.count == 64) break;+ }+ row[@"available_modes"] = modes;+ }+ row[@"can_set_mode"] = @([display respondsToSelector:sel_registerName("setCurrentMode:")]);+ row[@"can_allow_virtual_modes"] = @([display respondsToSelector:sel_registerName("setAllowsVirtualModes:")]);+ if ([display respondsToSelector:sel_registerName("stateControl")]) {+ id state = [display valueForKey:@"stateControl"];+ NSMutableDictionary *values = [NSMutableDictionary dictionary];+ for (NSString *key in @[@"displayState", @"powerState", @"cloningState", @"targetDisplayState", @"targetPowerState"])+ if ([state respondsToSelector:NSSelectorFromString(key)]) values[key] = [state valueForKey:key] ?: NSNull.null;+ row[@"state"] = values;+ }+ [rows addObject:row];+ if (rows.count == 16) break;+ }+ return @{@"available": @YES, @"displays": rows};+ } @catch (NSException *exception) {+ return @{@"available": @NO, @"reason": exception.reason ?: exception.name};+ }+}++/// Property keys worth reporting whole; everything else of a printable+/// scalar kind is reported by kind, and blobs are skipped.+static id valueForReport(id value) {+ if ([value isKindOfClass:NSNumber.class] || [value isKindOfClass:NSString.class]) {+ if ([value isKindOfClass:NSString.class] && [(NSString *)value length] > 96) {+ return nil;+ }+ return value;+ }+ if ([value isKindOfClass:NSData.class] && [(NSData *)value length] <= 16) {+ return [value description];+ }+ return nil;+}++NSArray *vp_display_probe(void) {+ NSMutableArray *found = [NSMutableArray array];+ // First the boot display handoff iBoot left in the device tree's+ // /chosen: the geometry early userspace inherits before any driver+ // re-reports it, and the outer size a stale one would pin UI to.+ io_registry_entry_t chosen = IORegistryEntryFromPath(kIOMainPortDefault, "IODeviceTree:/chosen");+ if (chosen != MACH_PORT_NULL) {+ io_name_t chosenName = {0};+ IORegistryEntryGetName(chosen, chosenName);+ NSMutableDictionary *chosenRow = [NSMutableDictionary dictionary];+ chosenRow[@"class"] = @"IODeviceTree:/chosen";+ chosenRow[@"name"] = [NSString stringWithUTF8String:chosenName] ?: @"chosen";+ CFMutableDictionaryRef chosenProps = NULL;+ if (IORegistryEntryCreateCFProperties(chosen, &chosenProps, kCFAllocatorDefault, kNilOptions)+ == KERN_SUCCESS && chosenProps) {+ NSMutableDictionary *reported = [NSMutableDictionary dictionary];+ NSDictionary *all = (__bridge NSDictionary *)chosenProps;+ for (NSString *key in all) {+ id value = valueForReport(all[key]);+ if (value) {+ reported[key] = value;+ }+ }+ CFRelease(chosenProps);+ chosenRow[@"properties"] = reported;+ }+ IOObjectRelease(chosen);+ [found addObject:chosenRow];+ }+ io_iterator_t iterator = IO_OBJECT_NULL;+ if (IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOService"), &iterator)+ != KERN_SUCCESS) {+ return @[@{@"error": @"IOService enumeration failed"}];+ }+ io_object_t entry;+ while ((entry = IOIteratorNext(iterator))) {+ io_name_t cls = {0};+ if (IOObjectGetClass(entry, cls) != KERN_SUCCESS) {+ IOObjectRelease(entry);+ continue;+ }+ NSString *className = [NSString stringWithUTF8String:cls] ?: @"";+ NSString *lower = className.lowercaseString;+ bool displayish = [lower containsString:@"display"] || [lower containsString:@"framebuffer"]+ || [lower containsString:@"appleclcd"] || [lower containsString:@"gpu"];+ if (!displayish) {+ IOObjectRelease(entry);+ continue;+ }+ io_name_t name = {0};+ IORegistryEntryGetName(entry, name);+ NSMutableDictionary *row = [NSMutableDictionary dictionary];+ row[@"class"] = className;+ row[@"name"] = [NSString stringWithUTF8String:name] ?: @"";+ CFMutableDictionaryRef properties = NULL;+ if (IORegistryEntryCreateCFProperties(entry, &properties, kCFAllocatorDefault, kNilOptions)+ == KERN_SUCCESS && properties) {+ NSMutableDictionary *reported = [NSMutableDictionary dictionary];+ NSDictionary *all = (__bridge NSDictionary *)properties;+ for (NSString *key in all) {+ id value = valueForReport(all[key]);+ if (value) {+ reported[key] = value;+ }+ }+ CFRelease(properties);+ row[@"properties"] = reported;+ }+ [found addObject:row];+ IOObjectRelease(entry);+ if (found.count >= 64) {+ IOObjectRelease(iterator);+ return found;+ }+ }+ IOObjectRelease(iterator);+ return found;+}diff --git a/VPhoneDaemon/Native/vphoned_pose.m b/VPhoneDaemon/Native/vphoned_pose.mnew file mode 100644index 00000000..33568713--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_pose.m@@ -0,0 +1,147 @@+/*+ * vphoned_pose — set a foldable guest's device pose, and the virtual hinge+ * angle behind it.+ *+ * A VM has no hinge, and SpringBoard only consumes CoreMotion's hinge angle+ * and magic pose on a board CoreMotion recognizes with two always-connected+ * displays. SpringBoardServices' test-automation client sets the pose+ * directly: SpringBoard builds a synthetic magic pose from the device+ * orientation, hinge state and tabletop pose, and derives the hinge angle+ * from the hinge state. The server checks the client for+ * com.apple.springboard.testautomation, which vphoned carries.+ *+ * The class is resolved at run time, so a base without it reports false.+ */++#import "Include/VphonedNative.h"+#import "../../VPhoneGuestComponents/Hinge/VPhoneHingeState.h"++#include <dlfcn.h>+#include <errno.h>+#include <math.h>+#include <notify.h>+#include <objc/message.h>+#include <objc/runtime.h>+#include <signal.h>+#include <unistd.h>++/// The override `-[SBSTestAutomationService setDevicePoseOverride:]` takes, as+/// SpringBoard's handler reads it: a 64-bit orientation, then the device+/// orientation, hinge state and tabletop pose as 32-bit values.+typedef struct {+ int64_t orientation;+ int32_t deviceOrientation;+ int32_t hingeState;+ int32_t tabletopPose;+} VPDevicePoseOverride;++bool vp_device_pose_set(int deviceOrientation, int hingeState, int tabletopPose) {+ static Class service;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ dlopen("/System/Library/PrivateFrameworks/SpringBoardServices.framework/SpringBoardServices", RTLD_NOW);+ service = NSClassFromString(@"SBSTestAutomationService");+ });+ SEL selector = NSSelectorFromString(@"setDevicePoseOverride:");+ if (!service || ![service instancesRespondToSelector:selector]) return false;+ id client = [service new];+ VPDevicePoseOverride pose = {deviceOrientation, deviceOrientation, hingeState, tabletopPose};+ ((void (*)(id, SEL, VPDevicePoseOverride))objc_msgSend)(client, selector, pose);+ return true;+}++NSDictionary<NSString *, id> *vp_device_pose_get(void) {+ dlopen("/System/Library/PrivateFrameworks/SpringBoardServices.framework/SpringBoardServices", RTLD_NOW);+ Class service = NSClassFromString(@"SBSTestAutomationService");+ SEL selector = NSSelectorFromString(@"getDevicePose");+ Method method = class_getInstanceMethod(service, selector);+ if (!method || strcmp(method_getTypeEncoding(method), "{?=qiii}16@0:8") != 0)+ return @{@"available": @NO, @"reason": @"device pose readback ABI unavailable"};+ // The client synchronously returns the 24-byte structure reconstructed+ // from SpringBoard's current pose snapshot. The completion selector is+ // on the server protocol, not this client class.+ id client = [service new];+ VPDevicePoseOverride pose = ((VPDevicePoseOverride (*)(id, SEL))objc_msgSend)(client, selector);+ return @{@"available": @YES, @"orientation": @(pose.orientation),+ @"device_orientation": @(pose.deviceOrientation), @"hinge": @(pose.hingeState),+ @"tabletop": @(pose.tabletopPose)};+}++NSDictionary<NSString *, id> *vp_display_orientation_mapping(void) {+ NSTimeInterval requested = NSProcessInfo.processInfo.systemUptime;+ notify_post("com.vphone.display.orientation.mapping.request");+ NSString *path = @"/var/mobile/Library/Caches/vphone-display-orientation-map.json";+ for (unsigned int attempt = 0; attempt < 15; attempt++) {+ NSData *data = [NSData dataWithContentsOfFile:path];+ id record = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL] : nil;+ if ([record isKindOfClass:NSDictionary.class] && [record[@"version"] isEqual:@1] &&+ [record[@"generatedUptime"] isKindOfClass:NSNumber.class] &&+ [record[@"generatedUptime"] doubleValue] >= requested && [record[@"scene"] isEqual:@"SB-main"])+ return record;+ usleep(10000);+ }+ return @{@"available": @NO, @"reason": @"active native scene orientation map unavailable"};+}++/* The virtual hinge publishes one coherent preference dictionary per update. */+NSDictionary *vp_hinge_get(void) {+ CFPreferencesSynchronize(CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);+ id configuration = CFBridgingRelease(CFPreferencesCopyValue(CFSTR(VP_HINGE_CONFIGURATION),+ CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost));+ VPhoneHingeState state;+ BOOL valid = VPhoneHingeDecode(configuration, &state);+ id status = CFBridgingRelease(CFPreferencesCopyValue(CFSTR(VP_HINGE_STATUS),+ CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost));+ BOOL running = NO;+ if ([status isKindOfClass:NSDictionary.class] &&+ [status[@"pid"] isKindOfClass:NSNumber.class] &&+ [status[@"updated_at"] isKindOfClass:NSNumber.class] &&+ [status[@"enumerated"] isKindOfClass:NSNumber.class] &&+ [status[@"report_interval_us"] isKindOfClass:NSNumber.class]) {+ pid_t pid = [status[@"pid"] intValue];+ BOOL alive = pid > 1 && (kill(pid, 0) == 0 || errno == EPERM);+ double age = NSDate.date.timeIntervalSince1970 - [status[@"updated_at"] doubleValue];+ BOOL flowing = [status[@"report_interval_us"] unsignedLongLongValue] > 0;+ running = [status[@"enumerated"] boolValue] && alive && age >= 0 && (age < 10 || !flowing);+ } else {+ status = NSNull.null;+ }+ return @{@"angle": @(valid && state.enabled ? state.angle : 0.0),+ @"enabled": @(valid && state.enabled),+ @"provider_running": @(running), @"provider": status};+}++static bool vp_hinge_publish(NSDictionary *configuration, double expectedAngle) {+ CFPreferencesSetValue(CFSTR(VP_HINGE_CONFIGURATION), (__bridge CFDictionaryRef)configuration,+ CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);+ if (!CFPreferencesSynchronize(CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost))+ return false;+ if (notify_post(VP_HINGE_NOTIFICATION) != NOTIFY_STATUS_OK)+ return false;+ for (int attempt = 0; attempt < 15; attempt++) {+ usleep(20000);+ CFPreferencesSynchronize(CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);+ id status = CFBridgingRelease(CFPreferencesCopyValue(CFSTR(VP_HINGE_STATUS),+ CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost));+ id reported = [status isKindOfClass:NSDictionary.class] ? status[@"configuration"] : nil;+ if ([reported isKindOfClass:NSDictionary.class] &&+ [reported[@"angle"] isKindOfClass:NSNumber.class] &&+ fabs([reported[@"angle"] doubleValue] - expectedAngle) < 0.5)+ break;+ }+ return true;+}++bool vp_hinge_set(double angleDegrees) {+ if (!isfinite(angleDegrees) || angleDegrees < 0 || angleDegrees > 180)+ return false;+ return vp_hinge_publish(VPhoneHingeEncode((VPhoneHingeState){true, false, angleDegrees, 0, 0}), angleDegrees);+}++bool vp_hinge_sweep(double targetDegrees, double durationMs, int profile) {+ if (!isfinite(targetDegrees) || targetDegrees < 0 || targetDegrees > 180 ||+ !isfinite(durationMs) || durationMs < -1 || durationMs > 10000 ||+ (profile != VPhoneHingeProfileContinuous && profile != VPhoneHingeProfileFade))+ return false;+ return vp_hinge_publish(VPhoneHingeEncode((VPhoneHingeState){true, true, targetDegrees, durationMs, profile}), targetDegrees);+}diff --git a/VPhoneDaemon/Native/vphoned_touch.m b/VPhoneDaemon/Native/vphoned_touch.mindex d8dbbe1b..89249e23 100644--- a/VPhoneDaemon/Native/vphoned_touch.m+++ b/VPhoneDaemon/Native/vphoned_touch.m@@ -41,6 +41,44 @@ static IOHIDEventSystemClientRef gTouchClient;static dispatch_queue_t gTouchQueue;static bool gTouchUnavailableLogged;+NSDictionary<NSString *, id> *vp_hid_input_devices(void) {+ void *ioKit = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_NOW);+ IOHIDEventSystemClientRef (*create)(CFAllocatorRef) = ioKit ? dlsym(ioKit, "IOHIDEventSystemClientCreate") : NULL;+ CFArrayRef (*copyServices)(IOHIDEventSystemClientRef) = ioKit ? dlsym(ioKit, "IOHIDEventSystemClientCopyServices") : NULL;+ CFTypeRef (*copyProperty)(const void *, CFStringRef) = ioKit ? dlsym(ioKit, "IOHIDServiceClientCopyProperty") : NULL;+ CFTypeRef (*registryID)(const void *) = ioKit ? dlsym(ioKit, "IOHIDServiceClientGetRegistryID") : NULL;+ if (!create || !copyServices || !copyProperty) return @{@"available": @NO, @"reason": @"HID service APIs unavailable"};+ IOHIDEventSystemClientRef client = create(kCFAllocatorDefault);+ if (!client) return @{@"available": @NO, @"reason": @"HID read client unavailable"};+ CFArrayRef services = copyServices(client);+ NSMutableArray *rows = [NSMutableArray array];+ NSArray *keys = @[@"Product", @"Transport", @"VendorID", @"ProductID", @"PrimaryUsagePage", @"PrimaryUsage",+ @"DeviceUsagePairs", @"DisplayIntegrated", @"DisplayID", @"DisplayIdentifier", @"DisplayUUID",+ @"PixelWidth", @"PixelHeight", @"DigitizerSurfaceDimensions", @"DisplaySurfaceDimensions",+ @"DigitizerSurfaceWidth", @"DigitizerSurfaceHeight", @"PhysicalMaxX", @"PhysicalMaxY",+ @"LogicalMaxX", @"LogicalMaxY", @"MinX", @"MinY", @"MaxX", @"MaxY", @"ReportDescriptor"];+ for (CFIndex index = 0; services && index < CFArrayGetCount(services) && index < 64; index++) {+ const void *service = CFArrayGetValueAtIndex(services, index);+ NSMutableDictionary *row = [NSMutableDictionary dictionaryWithObject:@(index) forKey:@"index"];+ CFTypeRef identifier = registryID ? registryID(service) : NULL;+ if (identifier && CFGetTypeID(identifier) == CFNumberGetTypeID()) row[@"registryID"] = (__bridge NSNumber *)identifier;+ for (NSString *key in keys) {+ CFTypeRef copied = copyProperty(service, (__bridge CFStringRef)key);+ if (!copied) continue;+ id value = CFBridgingRelease(copied);+ if ([value isKindOfClass:NSData.class]) {+ NSData *data = value;+ row[key] = @{@"byteCount": @(data.length), @"base64": [[data subdataWithRange:NSMakeRange(0, MIN(data.length, 4096))] base64EncodedStringWithOptions:0]};+ } else if ([NSJSONSerialization isValidJSONObject:@[value]]) row[key] = value;+ }+ [rows addObject:row];+ }+ NSUInteger count = services ? (NSUInteger)CFArrayGetCount(services) : 0;+ if (services) CFRelease(services);+ CFRelease(client);+ return @{@"available": @YES, @"serviceCount": @(count), @"services": rows};+}+// Digitizer event-mask bits and transducer types (IOHIDEventTypes.h).#define VP_DIG_RANGE 0x00000001u#define VP_DIG_TOUCH 0x00000002udiff --git a/VPhoneDaemon/Tests/LogicTests.swift b/VPhoneDaemon/Tests/LogicTests.swiftindex 5877f3cb..13127aba 100644--- a/VPhoneDaemon/Tests/LogicTests.swift+++ b/VPhoneDaemon/Tests/LogicTests.swift@@ -36,18 +36,31 @@ enum LogicTests {dataMigrationRecord()deviceNameRule()pointerScroll()+ displayRotationMapping()+ processSpawnPolicy()print("\(checks) checks, \(failures) failures")exit(failures == 0 ? 0 : 1)}+ static func processSpawnPolicy() {+ let valid = GuestProcessSpawnPolicy.validate(executable: "ps", arguments: ["-axo", "pid=,ppid=,args="], timeout: 3)+ expect(valid == nil, "standard ps discovery request is accepted")+ expect(GuestProcessSpawnPolicy.validate(executable: "sh", arguments: [], timeout: 3) != nil, "shell is refused")+ expect(GuestProcessSpawnPolicy.validate(executable: "ps", arguments: Array(repeating: "x", count: 17), timeout: 3) != nil, "argument count is bounded")+ expect(GuestProcessSpawnPolicy.validate(executable: "ps", arguments: [String(repeating: "x", count: 257)], timeout: 3) != nil, "argument length is bounded")+ expect(GuestProcessSpawnPolicy.validate(executable: "ps", arguments: ["x\n"], timeout: 3) != nil, "control characters are refused")+ expect(GuestProcessSpawnPolicy.validate(executable: "ps", arguments: [], timeout: 0.09) != nil, "short timeout is refused")+ expect(GuestProcessSpawnPolicy.validate(executable: "ps", arguments: [], timeout: 10.01) != nil, "long timeout is refused")+ }+// MARK: - Service Profilestatic let labelPattern = "^[A-Za-z0-9][A-Za-z0-9._:\\[\\]-]{0,200}$"static func profileCatalog() {let groups = GuestServiceProfile.groups27- expectEqual(GuestServiceProfile.base27.count, 136, "appendix A less siriactionsd")- expectEqual(Set(GuestServiceProfile.base27).count, 136, "appendix A has no duplicates")+ expectEqual(GuestServiceProfile.base27.count, 134, "appendix A less siriactionsd, passd and financed")+ expectEqual(Set(GuestServiceProfile.base27).count, 134, "appendix A has no duplicates")let all = groups.flatMap(\.labels)expectEqual(Set(all).count, all.count, "no label is in two groups")for label in all + GuestServiceProfile.neverDisable {@@ -65,7 +78,7 @@ enum LogicTests {static func profileCatalog26() {let base26 = GuestServiceProfile.base26- expectEqual(base26.count, 130, "136 minus six 26.6.2 does not load")+ expectEqual(base26.count, 128, "134 minus six 26.6.2 does not load")expectEqual(Set(base26).count, base26.count, "no duplicates")expect(Set(base26).isSubset(of: GuestServiceProfile.base27), "26 adds no label of its own")expect(GuestServiceProfile.notLoadedOn26.isSubset(of: GuestServiceProfile.base27), "only 27 labels are left out")@@ -87,32 +100,33 @@ enum LogicTests {static func profileSelection() {let trimmed = try? GuestServiceProfile.select(profile: "trimmed", iosMajor: 27)- expectEqual(trimmed?.labels.count, 140, "default trimmed = 136 + 2 store + 2 follow-up")+ expectEqual(trimmed?.labels.count, 138, "default trimmed = 134 + 2 store + 2 follow-up")expectEqual(trimmed?.groups, ["base", "app_store", "signin_followup"])expect(trimmed?.labels.contains("com.apple.followupd") == true, "followupd is in trimmed")expect(trimmed?.labels.contains("com.apple.akd") == false, "akd is not in trimmed by default")expect(trimmed?.labels.contains("com.apple.siriactionsd") == false, "siriactionsd serves App Intents controls")expect(GuestServiceProfile.neverDisable.contains("com.apple.siriactionsd"), "siriactionsd is never disabled")+ expect(trimmed?.labels.contains("com.apple.passd") == false && trimmed?.labels.contains("com.apple.financed") == false, "Wallet's daemons stay")expectEqual(trimmed?.labels, trimmed?.labels.sorted(), "labels sorted")let accounts = try? GuestServiceProfile.select(profile: "trimmed", iosMajor: 27, extraGroups: ["accounts"])- expectEqual(accounts?.labels.count, 143, "accounts adds three")+ expectEqual(accounts?.labels.count, 141, "accounts adds three")expect(accounts?.labels.contains("com.apple.amsaccountsd") == true, "amsaccountsd with accounts")let allowed = try? GuestServiceProfile.select(profile: "trimmed", iosMajor: 27, allow: ["com.apple.weatherd", "com.example.not-listed"],)- expectEqual(allowed?.labels.count, 139, "allow removes one")+ expectEqual(allowed?.labels.count, 137, "allow removes one")expectEqual(allowed?.allowed, ["com.apple.weatherd"], "only catalog labels are reported as allowed")expect(allowed?.labels.contains("com.apple.weatherd") == false, "weatherd kept")let trimmed26 = try? GuestServiceProfile.select(profile: "trimmed", iosMajor: 26)- expectEqual(trimmed26?.labels.count, 134, "26 trimmed = 130 + 2 store + 2 follow-up")+ expectEqual(trimmed26?.labels.count, 132, "26 trimmed = 128 + 2 store + 2 follow-up")expectEqual(trimmed26?.groups, ["base", "app_store", "signin_followup"])expect(trimmed26?.refused.isEmpty == true, "the 26 list names nothing never disabled")expectEqual((try? GuestServiceProfile.select(profile: "trimmed", iosMajor: 26, extraGroups: ["accounts"]))?.labels.count,- 137, "accounts adds three on 26",+ 135, "accounts adds three on 26",)expectEqual(try? GuestServiceProfile.select(profile: "none", iosMajor: 25), GuestServiceProfile.Selection())@@ -207,7 +221,7 @@ enum LogicTests {var overrides = Dictionary(uniqueKeysWithValues: ota.map { ($0, true) })overrides["com.apple.user-choice"] = truelet apply = GuestServiceProfile.reconcile(target: trimmed.labels, owned: [], overrides: overrides)- expectEqual(apply.disable.count, 137, "140 minus the three already disabled")+ expectEqual(apply.disable.count, 135, "138 minus the three already disabled")expectEqual(apply.skipped.map(\.label), ota.sorted())let owned = GuestServiceProfile.owned(after: apply, failedDisable: [], failedEnable: [])for label in apply.disable {@@ -398,3 +412,29 @@ enum LogicTests {}}}++extension LogicTests {+ static func displayRotationMapping() {+ let specs = ["0", "90", "180", "270"]+ let coverDevices = [1, 4, 2, 3]+ let innerDevices = [3, 1, 4, 2]+ let innerDegrees = [270, 0, 90, 180]+ for index in specs.indices {+ let cover = GuestDisplayRotation.resolve(specs[index], deviceOrientations: [1, 2, 3, 4])+ expectEqual(cover?.deviceOrientation, coverDevices[index], "cover uses native toll-free map")+ expectEqual(cover?.accelerometerDegrees, Int(specs[index]), "ordinary gravity direction is preserved")+ let inner = GuestDisplayRotation.resolve(specs[index], deviceOrientations: [3, 4, 2, 1])+ expectEqual(inner?.deviceOrientation, innerDevices[index], "inner uses measured native inverse map")+ expectEqual(inner?.accelerometerDegrees, innerDegrees[index], "inner gravity and device pose agree")+ expectEqual(inner?.interfaceDegrees, Int(specs[index]), "receipt stays in logical interface degrees")+ }+ for (alias, canonical) in [("portrait", "0"), ("LEFT", "90"), ("portrait-upside-down", "180"), ("right", "270")] {+ expectEqual(GuestDisplayRotation.resolve(alias, deviceOrientations: [3, 4, 2, 1]),+ GuestDisplayRotation.resolve(canonical, deviceOrientations: [3, 4, 2, 1]), "existing rotation aliases")+ }+ expect(GuestDisplayRotation.resolve("45", deviceOrientations: [1, 2, 3, 4]) == nil, "unknown rotation is refused")+ expect(GuestDisplayRotation.resolve("0", deviceOrientations: [1, 1, 3, 4]) == nil, "non-invertible native map is refused")+ expect(GuestDisplayRotation.resolve("0", deviceOrientations: [1, 2, 3, 5]) == nil, "invalid device orientation is refused")+ expect(GuestDisplayRotation.resolve("0", deviceOrientations: [1, 2]) == nil, "partial native map is refused")+ }+}diff --git a/VPhoneDaemon/Tests/run-logic-tests.sh b/VPhoneDaemon/Tests/run-logic-tests.shindex 597bba25..6816190f 100755--- a/VPhoneDaemon/Tests/run-logic-tests.sh+++ b/VPhoneDaemon/Tests/run-logic-tests.sh@@ -16,6 +16,8 @@ trap '/bin/rm -rf "$temporary"' EXIT"$daemon/Daemon/GuestFirstBootSettle.swift" \"$daemon/Daemon/GuestDeviceNameRule.swift" \"$daemon/Daemon/GuestPointerScroll.swift" \+ "$daemon/Daemon/GuestDisplayRotation.swift" \+ "$daemon/Daemon/GuestProcessSpawnPolicy.swift" \"$daemon/Tests/LogicTests.swift" \-o "$temporary/logic-tests"