Run a virtual iPhone on an Apple Silicon Mac.
Swift
Duo: match Apple's simulator for CoreMotion, displays and the book angle
Jackyec014d7c1afc
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 7399847c..e88dec34 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -559,6 +559,60 @@> each crashed or closed the chain on. See> [Duo bring-up](Guest/iphone_duo_bringup.md#virtual-hinge-2026-10-24).+> **Duo panel nodes, product identity on, and CoreMotion's VM relay+> (2026-10-30):** measured against Apple's iPhone Duo simulator+> (`Research/Guest/Evidence/duo-sim-baseline/BASELINE.md`), the dual-display+> guest still reported one display to MobileGestalt, no CoreMotion pose+> managers, and a 90° book angle from the test-automation override.+> - `preboot-cfw-devicetree_foldable_displays` (new; guest system set,+> Preboot device-tree repair, on in `standard`, blocked in `tvos`, `tvos-4k`+> and `homepod-mini`, foldable guests only; verb+> `cfw patch-dt-foldable-displays`) copies the board tree's `/product`+> children that carry `surface-type` — `display0` (cover) and `display1`+> (inner) on V68AP — into the guest's `/product`, first and in board order,+> with `AAPL,phandle` renumbered above the tree's highest. libMobileGestalt+> reads them live from `IODeviceTree:/product`: `MGGetLogicalDeviceDisplayCount`+> counts the children with `surface-type` (1 → 2) and+> `DisplayExtendedProperties` takes each one's `surface-type`,+> `display-scale`, `display-rotation`, `display-corner-radius`,+> `chrome-identifier` and `framebuffer-identifier` (nil → two entries).+> QuartzCore gives the cover's hardware display its entry at construction;+> `libvphonefolddisplay` now gives the inner virtual display the entry with+> surface type 2 and a 460 ppi physical size (`kCAVirtualDisplayPhysical*`).+> The cover's radii stay Apple's tree value [5, 5, 59, 59]; the simulator's+> device type says [8, 8, 59, 59].+> - `preboot-exp-devicetree_foldable_product_id` is renamed+> `preboot-cfw-devicetree_foldable_product_id` and is on in `standard`+> (`renamedPatches` migrates VM records). CoreMotion's+> `CLPlatformInfo::queryEmbeddedSystemHardware` matches the V68 token through+> `MGIsDeviceOfType`; without it the guest is a generic virtual device with+> zero motion capability bits, so `+[CMAngleManager isAvailable]`,+> `CMDeviceStateManager` and `CMMagicPoseManager` were NO and locationd+> started no `CLDeviceStateRelay`. The single-display crash loop that kept it+> off does not apply to the dual-display guest (measured on duobase-01:+> SpringBoard stable across boots, posture cycles and rotations).+> - `system-backboardd-cfw-hinge`'s `libvphonehinge.dylib` no longer+> publishes its own `0xFF0C/0x21` angle service (CoreMotion drops its+> phase-0 events). It publishes the VM host controls locationd's relay+> subscribes to — primary usage `0xFF61/0x5B` — and dispatches+> vendor-defined events whose data is an `IOCFSerialize`d dictionary of at+> most 256 bytes: `{source: hinge-slider-control, type: range, value:+> <integer degrees>}` and `{source: orientation-picker-control, type: enum,+> value: portrait|landscape-left|landscape-right|faceup|facedown}`. The+> relay publishes `CoreMotion_DeviceStateRelay_Crane` (`0xFF0C/0x21`) and+> `_DeviceState` (`0xFF0C/0x22`), the services the simulator shows, and+> SpringBoard's `SBFDevicePoseProvider` reads the angle and magic pose+> through CoreMotion: book is 99.4° (simulator 100°), not the override's+> 90°. Stationary values are re-sent every 5 s because the relay reseeds+> 0°/portrait when locationd restarts. Checked in `make test-hinge`+> (serialization round trip, size, vendor event).+> - vphoned's `display.posture` and `display.rotation` drive the host controls+> and skip the test-automation override when CoreMotion has the capability+> (`vp_core_motion_hinge`); opening from closed wakes the screen first,+> because the pose provider publishes a moving pose only on display frames.+> `libdevicehubfix`'s CMAngleManager stand-in steps aside when CoreMotion's+> own manager is available.+> **SpringBoard fold-guard (2026-10-25):** `system-springboard-cfw-fold_guard`> (guest system set, on in `standard`, blocked in `tvos`, `tvos-4k` and> `homepod-mini`, foldable guests only, iOS 27+; installsdiff --git a/Research/Guest/iphone_duo_bringup.md b/Research/Guest/iphone_duo_bringup.mdindex 1a035d88..18876e33 100644--- a/Research/Guest/iphone_duo_bringup.md+++ b/Research/Guest/iphone_duo_bringup.md@@ -4836,3 +4836,67 @@ Window captures (ScreenCaptureKit) cannot judge 120 Hz here: the cover, whichis natively 120, measures the same 40-55 changes per second as the innerdisplay, because the host composites the window at its own rate. Use guestdisplay links, or the host's `lastSubmittedTime` poller from the vGPU notes.++## 2026-10-30: CoreMotion, MobileGestalt displays and the book angle, against Apple's simulator++Apple's iPhone Duo simulator (Xcode 27.1, iOS 27.1 24A94425, device type+`iPhone-Duo`, two integrated displays: `LCD` 1398×2034 surface type 1 and+`LCD-1` 2007×2853 rotation 270 surface type 2) was probed over lldb in every+posture, through SpringBoard's own display-swap coordinator (the internal+suiatool path), and the same calls were run on a two-display guest+(`duobase-01`) through the guest's debugserver. The harness, the per-domain+records and the table are in `Research/Guest/Evidence/duo-sim-baseline/`+(`BASELINE.md`). Three of the differences had one cause each:++- **MobileGestalt saw one display.** libMobileGestalt computes+ `MGGetLogicalDeviceDisplayCount` and `DisplayExtendedProperties` live from+ the children of `IODeviceTree:/product` that carry `surface-type`+ (`display0`, `display1` in DeviceTree.v68ap); vphone600's tree has none, so+ the count fell back to 1 and the answer to nil (its fallback needs+ `MainScreenScale`, also nil). `preboot-cfw-devicetree_foldable_displays`+ copies the board's two nodes. QuartzCore gives a hardware display its entry+ when it builds it; the inner virtual display gets its own from FoldDisplay,+ with a physical size (`kCAVirtualDisplayPhysicalWidth/Height`, 460 ppi) so+ `pixelsPerInch` is no longer 0.+- **CoreMotion had no pose managers.** CoreMotion picks its motion+ capabilities from the product-id token (`MGIsDeviceOfType` in+ `CLPlatformInfo::queryEmbeddedSystemHardware`; V68 → hardware 0xC6, angle+ bit 38 and device-state bit 13). vphone600's token is no known product, and+ with `IsVirtualDevice` the guest became hardware 1 with no capabilities.+ SpringBoard's `SBFDevicePoseProvider` creates `_cmAngleManager` and+ `_cmMagicPoseManager` only when both report available and FrontBoard has+ two always-connected displays — the second condition the two-display path+ already met. The product-id patch, kept off since the single-display crash+ loop, is now on.+- **Book read 90°.** The test-automation override derives the angle from the+ hinge state. With the token, locationd starts `CLDeviceStateRelay`, Apple's+ VM path: it subscribes to host controls (primary usage `0xFF61/0x5B`) and+ turns `hinge-slider-control` / `orientation-picker-control` dictionaries+ (vendor-defined events, `IOCFUnserializeWithSize`, at most 256 bytes) into+ `CoreMotion_DeviceStateRelay_Crane` angle events (phase 2, private-data+ progress) and `_DeviceState` reports. libvphonehinge now publishes those+ host controls instead of its own `0xFF0C/0x21` service (whose phase-0 events+ CoreMotion drops), and vphoned stops setting the override when CoreMotion+ has the capability. SpringBoard then reads book at 99.444° (position+ 0.552; the simulator's synthetic 100° is 0.556).++One trap on the way: after the cover had gone dark in closed, a closed→book+sweep left the pose provider at 0° although CoreMotion delivered every angle+(breakpoints: `CLAngleNotifier::onIoHidEvent` 21 hits, `_handleAngle:` 19).+The provider commits a pose in motion only on ticks of its `UIUpdateLink`,+bound to `SB-main`, and a dark display produces none. On hardware the hinge+sensor's wake flag lights the screen on an unfold; the relay always sends 0+there. vphoned lights the screen before a sweep out of closed+(`SBSUndimScreen`, the side button when SpringBoard refuses it), 3/3 after.++Limits: the host controls' orientation picker has no upside-down, so the+cover's 180 and the inner panel's 270 are refused through CoreMotion. The+cover's corner radii are Apple's tree value [5, 5, 59, 59]; the simulator's+device type says [8, 8, 59, 59].++Reveal and validation on a new guest: `device.input_devices` lists+`VPhone Host Controls` and both `CoreMotion_DeviceStateRelay_*` services;+`display.posture` replies `source: coremotion`; in SpringBoard,+`MGGetLogicalDeviceDisplayCount()` is 2, `+[CMAngleManager isAvailable]` is+YES and `SBFDevicePoseProvider`'s description reads `.partiallyOpen` at+~99.4° six seconds after `{"hinge":"partially-open","position":"book"}`.diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex 5dbaa31a..00a519f3 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -1212,57 +1212,71 @@ plain HTTP, so use it only on a trusted network.## Device pose-`display.posture` sets a foldable guest's pose (iPhone Duo), driving both-halves of the fold state from one request. SpringBoard's half is the-test-automation override: vphoned calls-`-[SBSTestAutomationService setDevicePoseOverride:]`, which SpringBoard-accepts from a client entitled `com.apple.springboard.testautomation`; the-server builds a synthetic magic pose and derives a hinge angle from the-hinge state (0, 0, 90, 180 and 180 degrees for states 0–4). CoreMotion's-half is the virtual hinge HID service (`system-backboardd-cfw-hinge`,-`libvphonehinge.dylib` in backboardd, usage page `0xFF0C` / usage `0x21`),-which needs the foldable's own `product-id` in the device tree-(`preboot-exp-devicetree_foldable_product_id`) before CoreMotion looks for-it; that is the half CoreDevice's `hingeAngle` stream reads, because-CoreDevice does not go through SpringBoard.+`display.posture` sets a foldable guest's pose (iPhone Duo). The virtual+hinge (`system-backboardd-cfw-hinge`, `libvphonehinge.dylib` in backboardd)+publishes Apple's VM host controls, primary usage `0xFF61` / `0x5B`, and sends+the angle and device orientation as `hinge-slider-control` and+`orientation-picker-control` dictionaries. With the foldable's own+`product-id` in the device tree (`preboot-cfw-devicetree_foldable_product_id`)+CoreMotion has the foldable's capabilities, locationd's device-state relay+turns those dictionaries into the hinge-angle and device-state services+(`CoreMotion_DeviceStateRelay_Crane` `0xFF0C/0x21`, `_DeviceState`+`0xFF0C/0x22`), and SpringBoard reads its pose — angle, hinge state, each+panel's orientation — from CoreMotion as on a device; CoreDevice's+`hingeAngle` stream reads the same manager. Opening a closed guest lights the+screen first (`SBSUndimScreen`, the side button when SpringBoard refuses it):+SpringBoard's pose provider publishes a moving pose only on display frames.++On a guest whose CoreMotion lacks the capability, vphoned instead sets+SpringBoard's test-automation override+(`-[SBSTestAutomationService setDevicePoseOverride:]`, entitlement+`com.apple.springboard.testautomation`), whose server builds a synthetic+magic pose and derives the angle from the hinge state (0, 0, 90, 180 and 180+degrees for states 0–4). The reply's `source` says which: `coremotion` or+`test-automation`. `display.pose` reads the test-automation snapshot and is+only current in the second case.On the iPhone Duo (iPhone19,4) the fold display patch(`system-springboard-cfw-fold_display`) publishes the inner panel as a seconddisplay, and SpringBoard picks the posture policy from the pose itself:-`FoldingDual` open, `FullyClosed` closed. vphoned publishes the pose and the-hinge and does nothing further. `display.rotation` turns a foldable guest-(one with the virtual hinge enabled) through the same pose: it sets the pose-orientation that gives the lit panel the requested interface orientation-(cover: 0 portrait, 90 landscape-right, 180 upside-down, 270 landscape-left;-inner panel, mounted a quarter turn from the cover: 0 landscape-left, 90-portrait, 180 landscape-right, 270 upside-down) and reads the interface back.-The accelerometer and the AssistiveTouch rotation other iPhones use do not-turn a foldable's panels.+`FoldingDual` open, `FullyClosed` closed. `display.rotation` turns a+foldable guest (one with the virtual hinge enabled) through the same channel:+it sends the device orientation that gives the lit panel the requested+interface orientation (cover: 0 portrait, 90 landscape-right, 180+upside-down, 270 landscape-left; inner panel, mounted a quarter turn from the+cover: 0 landscape-left, 90 portrait, 180 landscape-right, 270 upside-down)+and reads the interface back. The host controls' orientation picker has no+upside-down, so with CoreMotion the cover's 180 and the inner panel's 270 are+refused. The accelerometer and the AssistiveTouch rotation other iPhones use+do not turn a foldable's panels.| Param | Values || --- | --- || `hinge` (required) | `ambiguous` 0, `closed` 1, `partially-open` 2, `open-flat` 3, `open` 4 || `orientation` | `ambiguous` 0, `portrait` 1 (default), `upside-down` 2, `landscape-left` 3, `landscape-right` 4, `face-up` 5, `face-down` 6 || `tabletop` | 0–10 (default 0, ambiguous) |-| `angle` | 0–180 (default: the hinge state's angle from SpringBoard's table) |+| `angle` | 0–180 (default: the hinge state's angle; partially open is book, 100°) || `position` | `closed` 0°, `book` ~100°, `open` 180°, or a fraction 0–1 — Apple's three screen states; requests a sweep || `duration` | sweep seconds; default the per-direction hand-fold time (opening faster), 0 instant || `profile` | `continuous` (default) or `fade`, the two profiles suiatool names |-The reply echoes the numeric values, the published `angle`, and `hinge_hid`-(`applied`, `provider_running`, `provider`) describing the virtual hinge-service, so a host can tell a live sensor from an absent one. A refused pose-override fails the request; a missing hinge provider does not — the pose is-the primary, the service may be off, and the angle then reaches CoreMotion-after the guest reboots with the provider installed. The override is state-of the running SpringBoard, gone with it at shutdown. The VM sub-type's own+The reply echoes the numeric values, the published `angle`, `source`, and+`hinge_hid` (`applied`, `provider_running`, `provider`) describing the+virtual hinge service, so a host can tell a live sensor from an absent one.+With CoreMotion the hinge is the pose, so a hinge that did not take the+request fails it; `tabletop` is CoreMotion's to compute and comes back null.+With the override, a refused override fails the request and a missing hinge+provider does not. The hinge's stored angle and orientation survive a reboot+and the provider hands them to the relay when it enumerates; the override is+state of the running SpringBoard, gone with it at shutdown. The VM sub-type's ownrestore path (`preboot-cfw-devicetree_foldable_vm_subtype`) does not standin on a single display: its `SBFDevicePoseLastKnown*` defaults are writtenon display-mode transitions, which one display never makes (measured-2026-10-25: they stay zero), so vphoned re-applies the saved posture over-the boot itself (`GuestFoldPose` in the daemon: a bounded ladder of pose-and hinge applications across SpringBoard's first 90 s; only a guest whose-hinge was configured is touched).+2026-10-25: they stay zero), so on a guest without CoreMotion's capability+vphoned re-applies the saved posture over the boot itself (`GuestFoldPose`+in the daemon: a bounded ladder of pose and hinge applications across+SpringBoard's first 90 s; only a guest whose hinge was configured is+touched).The VM window's Motion Sensors › Fold Posture panel (capability`device_pose`) is the host-side driver: a Closed / Book / Open picker with adiff --git a/VPhoneDaemon/Daemon/GuestAPI+Device.swift b/VPhoneDaemon/Daemon/GuestAPI+Device.swiftindex 5cb2a3a1..86bad1b8 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Device.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Device.swift@@ -186,18 +186,22 @@ extension GuestAPI {"landscape-right": 4, "face-up": 5, "face-down": 6,]- /// 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]+ /// The angle a hinge state names, as Apple's screen states have it:+ /// partially open is book (~100°). SpringBoard's own table for the pose+ /// override says 90°, but with CoreMotion's relay it reads the hinge.+ static let poseHingeAngles: [Double] = [0, 0, 100, 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 —+ /// Set a foldable guest's pose the way Apple's Duo tooling does. On a+ /// guest whose CoreMotion has the foldable's capabilities the virtual+ /// hinge's host controls carry the angle and orientation, locationd+ /// relays them into CoreMotion, and SpringBoard reads its pose from there+ /// as on a device; elsewhere SpringBoard's test-automation override sets+ /// the pose beside the hinge. 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@@ -273,22 +277,39 @@ extension GuestAPI {angle = requested.doubleValue}}+ let relayed = vp_core_motion_hinge()+ if relayed, orientation == 2 {+ throw GuestAPIError.invalidRequest("the host controls have no upside-down orientation")+ }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")+ if !relayed {+ guard vp_device_pose_set(Int32(orientation), Int32(hinge), Int32(tabletop)) else {+ throw GuestAPIError.operationFailed("SpringBoardServices has no device pose override on this guest")+ }+ } else if let current = vp_hinge_get()["angle"] as? Double, hingeState(for: current) == 1, hingeState(for: angle!) != 1 {+ // Opening a closed device wakes it; the hinge sensor's own wake+ // flag does that on hardware, and the host controls cannot set+ // it. SpringBoard's pose provider publishes a pose in motion only+ // on display frames, so with the cover asleep the new angle would+ // sit unpublished until the next wake. The screen is lit before+ // the sweep starts.+ GuestScreenUnlock.wakeDisplay()}- // 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.+ // With the override, the pose has landed and the hinge half is+ // published beside it; its absence (no virtual hinge service on this+ // guest) does not undo the pose. With the relay, the hinge is the pose.let published = sweep- ? vp_hinge_sweep(angle!, durationMs, Int32(profile))- : vp_hinge_set(angle!)+ ? vp_hinge_sweep(angle!, durationMs, Int32(profile), Int32(orientation))+ : vp_hinge_set(angle!, Int32(orientation))+ if relayed, !published {+ throw GuestAPIError.operationFailed("The virtual hinge did not take the pose")+ }var hingeHID = vp_hinge_get()hingeHID["applied"] = publishedvar reply: [String: Any] = [- "hinge": hinge, "orientation": orientation, "tabletop": tabletop,- "angle": angle!, "hinge_hid": hingeHID,+ "hinge": hinge, "orientation": orientation, "tabletop": relayed ? NSNull() : tabletop,+ "angle": angle!, "hinge_hid": hingeHID, "source": relayed ? "coremotion" : "test-automation",]if sweep {reply["sweep"] = [@@ -321,12 +342,24 @@ extension GuestAPI {// on the cover (hinge closed) and on the inner panel (open).let cover: [Int: Int32] = [0: 1, 90: 4, 180: 2, 270: 3]let inner: [Int: Int32] = [0: 3, 90: 1, 180: 4, 270: 2]+ let orientation = (hinge == 1 ? cover : inner)[degrees]!GuestFoldPose.cancelStartupRestore()defer { GuestFoldPose.finishExplicitRequest() }- guard vp_device_pose_set((hinge == 1 ? cover : inner)[degrees]!, hinge, tabletop) else {- throw GuestAPIError.operationFailed("SpringBoard refused the device pose")+ if vp_core_motion_hinge() {+ // The device orientation goes through the host controls with the+ // angle the hinge holds; CoreMotion turns it into each panel's.+ guard orientation != 2 else {+ throw GuestAPIError.invalidRequest("the host controls have no upside-down orientation")+ }+ guard let angle = vp_hinge_get()["angle"] as? Double, vp_hinge_set(angle, orientation) else {+ throw GuestAPIError.operationFailed("The virtual hinge did not take the orientation")+ }+ } else {+ guard vp_device_pose_set(orientation, hinge, tabletop) else {+ throw GuestAPIError.operationFailed("SpringBoard refused the device pose")+ }}- for _ in 0 ..< 20 where interfaceRotationDegrees() != degrees {+ for _ in 0 ..< 30 where interfaceRotationDegrees() != degrees {usleep(100_000)}guard interfaceRotationDegrees() == degrees else {diff --git a/VPhoneDaemon/Daemon/GuestFoldPose.swift b/VPhoneDaemon/Daemon/GuestFoldPose.swiftindex 436c5025..dce2af63 100644--- a/VPhoneDaemon/Daemon/GuestFoldPose.swift+++ b/VPhoneDaemon/Daemon/GuestFoldPose.swift@@ -99,6 +99,13 @@ enum GuestFoldPose {static func startOnStartup() {let hinge = vp_hinge_get()guard hinge["enabled"] as? Bool == true, let angle = hinge["angle"] as? Double else { return }+ // With CoreMotion's relay the hinge provider hands locationd the+ // stored angle and orientation itself, and SpringBoard reads the pose+ // from CoreMotion: there is no override to restore.+ if vp_core_motion_hinge() {+ NSLog("vphoned: fold pose at %.0f° comes through CoreMotion's relay", angle)+ return+ }observeSpringBoardStartup()NSLog("vphoned: fold pose restore: %.0f° over the boot ladder", angle)let expectedHinge = GuestAPI.hingeState(for: angle)@@ -110,7 +117,7 @@ enum GuestFoldPose {let published = restoration.lock.withLock {guard !restoration.cancelled else { return false }_ = vp_device_pose_set(1, Int32(expectedHinge), 0)- _ = vp_hinge_set(angle)+ _ = vp_hinge_set(angle, 0)restoration.latestPose = poseValues(vp_device_pose_get())return true}diff --git a/VPhoneDaemon/Daemon/GuestScreenUnlock.swift b/VPhoneDaemon/Daemon/GuestScreenUnlock.swiftindex 3354e3c5..c7acaab3 100644--- a/VPhoneDaemon/Daemon/GuestScreenUnlock.swift+++ b/VPhoneDaemon/Daemon/GuestScreenUnlock.swift@@ -85,6 +85,19 @@ enum GuestScreenUnlock {}}+ /// Lights a dark screen and waits for it, leaving it locked, as opening a+ /// closed foldable does: `SBSUndimScreen` first, one side-button press+ /// when SpringBoard refuses that. Returns whether the screen is lit.+ @discardableResult+ static func wakeDisplay(timeout: Double = 2) -> Bool {+ guard state().screenOff else { return true }+ let deadline = Date().addingTimeInterval(timeout)+ _ = vp_screen_undim()+ if wait(until: Date().addingTimeInterval(undimWait), for: { !$0.screenOff }) { return true }+ _ = try? pressButton("power")+ return wait(until: deadline, for: { !$0.screenOff })+ }+/// The log messages are literals: arguments come back `<private>` in the/// guest log.private static func wakeForTap() {diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.hindex ddb19570..dafa5082 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -120,6 +120,11 @@ bool vp_screen_undim(void);/// touch controller reports as a wake gesture.void vp_tap_to_wake_start(void (* _Nonnull touched)(void));bool vp_device_pose_set(int deviceOrientation, int hingeState, int tabletopPose);+/// Whether this guest's CoreMotion has a foldable's angle and device-state+/// capabilities (the foldable product-id). Then locationd relays the virtual+/// hinge's host controls into CoreMotion and SpringBoard reads its pose from+/// there; otherwise only the test-automation pose override reaches it.+bool vp_core_motion_hinge(void);/// Ask launchd to shut the guest down and halt. Returns 0 once the request is/// accepted, otherwise an errno value. Needs root.@@ -206,12 +211,16 @@ 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);-BOOL vp_hinge_set(double angleDegrees);+/// Set the hinge to `angleDegrees` at once. `orientation` is CoreMotion's+/// device orientation for the host controls (1 portrait … 6 face down), or 0+/// to keep the stored one.+BOOL vp_hinge_set(double angleDegrees, int orientation);/// 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);+/// swap. `orientation` as for `vp_hinge_set`. Returns false on an+/// out-of-range request.+BOOL vp_hinge_sweep(double targetDegrees, double durationMs, int profile, int orientation);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_pose.m b/VPhoneDaemon/Native/vphoned_pose.mindex af2007e7..f50d9801 100644--- a/VPhoneDaemon/Native/vphoned_pose.m+++ b/VPhoneDaemon/Native/vphoned_pose.m@@ -116,16 +116,44 @@ static bool vp_hinge_publish(NSDictionary *configuration, double expectedAngle)return true;}-bool vp_hinge_set(double angleDegrees) {- if (!isfinite(angleDegrees) || angleDegrees < 0 || angleDegrees > 180)+/// The orientation to store: the requested one, or the stored one for 0, so+/// a later angle-only request does not drop it.+static int vp_hinge_orientation(int requested) {+ if (requested)+ return requested;+ CFPreferencesSynchronize(CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);+ id stored = CFBridgingRelease(CFPreferencesCopyValue(CFSTR(VP_HINGE_CONFIGURATION),+ CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost));+ VPhoneHingeState state;+ return VPhoneHingeDecode(stored, &state) ? state.orientation : 0;+}++bool vp_hinge_set(double angleDegrees, int orientation) {+ if (!isfinite(angleDegrees) || angleDegrees < 0 || angleDegrees > 180 || orientation < 0 || orientation > 6)return false;- return vp_hinge_publish(VPhoneHingeEncode((VPhoneHingeState){true, false, angleDegrees, 0, 0}), angleDegrees);+ VPhoneHingeState state = {true, false, angleDegrees, 0, 0, vp_hinge_orientation(orientation)};+ return vp_hinge_publish(VPhoneHingeEncode(state), angleDegrees);}-bool vp_hinge_sweep(double targetDegrees, double durationMs, int profile) {+bool vp_hinge_sweep(double targetDegrees, double durationMs, int profile, int orientation) {if (!isfinite(targetDegrees) || targetDegrees < 0 || targetDegrees > 180 ||!isfinite(durationMs) || durationMs < -1 || durationMs > 10000 ||- (profile != VPhoneHingeProfileContinuous && profile != VPhoneHingeProfileFade))+ (profile != VPhoneHingeProfileContinuous && profile != VPhoneHingeProfileFade) ||+ orientation < 0 || orientation > 6)return false;- return vp_hinge_publish(VPhoneHingeEncode((VPhoneHingeState){true, true, targetDegrees, durationMs, profile}), targetDegrees);+ VPhoneHingeState state = {true, true, targetDegrees, durationMs, profile, vp_hinge_orientation(orientation)};+ return vp_hinge_publish(VPhoneHingeEncode(state), targetDegrees);+}++bool vp_core_motion_hinge(void) {+ static bool available;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ dlopen("/System/Library/Frameworks/CoreMotion.framework/CoreMotion", RTLD_NOW);+ SEL selector = sel_registerName("isAvailable");+ Class angle = NSClassFromString(@"CMAngleManager"), deviceState = NSClassFromString(@"CMDeviceStateManager");+ available = angle && deviceState && [angle respondsToSelector:selector] && [deviceState respondsToSelector:selector] &&+ ((BOOL (*)(id, SEL))objc_msgSend)(angle, selector) && ((BOOL (*)(id, SEL))objc_msgSend)(deviceState, selector);+ });+ return available;}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swiftindex e551763f..f68f929b 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift@@ -569,6 +569,50 @@ public enum CustomFirmwarePostRestoreDeviceTree {}}+ /// `blob` with the foldable board's panel nodes under `/product`, taken+ /// from its flat tree `board` through+ /// `DeviceTreePatcher.presentFoldableDisplays`. Returns the size change+ /// with the changes: each added node's serialized bytes. A tree that is+ /// not a foldable guest, or already has panel nodes, comes back unchanged.+ public static func withFoldableDisplays(_ blob: Data, board: Data) throws -> (Data, [Change], Int) {+ let root = try parseTree(blob, label: "DT")+ let source = try parseTree(board, label: "foldable board DT")+ let nodes = try DeviceTreePatcher.presentFoldableDisplays(in: root, from: source)+ guard !nodes.isEmpty else { return (blob, [], 0) }+ let records = nodes.map { node in+ var name = "?"+ if let (parsed, _) = try? parseNode(node, at: 0),+ let property = parsed.properties.first(where: { $0.name == "name" })+ {+ name = String(decoding: property.value.prefix { $0 != 0 }, as: UTF8.self)+ }+ return Change(property: "product/\(name)", before: "absent", after: "\(node.count)B")+ }+ return (serializeNode(root), records, nodes.reduce(0) { $0 + $1.count })+ }++ /// Give a foldable guest's `devicetree.img4` (or bare `.im4p`) the board's+ /// panel nodes, in place. See `withFoldableDisplays`.+ @discardableResult+ public static func presentFoldableDisplays(+ at url: URL,+ board boardURL: URL,+ dryRun: Bool = false,+ verbose: Bool = true,+ ) throws -> Outcome {+ let boardData: Data+ do {+ boardData = try Data(contentsOf: boardURL)+ } catch {+ throw PatcherError.fileNotFound(boardURL.path)+ }+ let board = try openDeviceTree(boardData, path: boardURL.path).blob+ return try rewrite(at: url, dryRun: dryRun, verbose: verbose) { blob in+ let (newBlob, changes, delta) = try withFoldableDisplays(blob, board: board)+ return (newBlob, changes, blob.count + delta)+ }+ }+/// The root of a flat tree that must fill `blob` exactly.private static func parseTree(_ blob: Data, label: String) throws -> DeviceTreePatcher.DTNode {let (root, end) = try parseNode(blob, at: 0)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swiftindex 789f45cd..67307299 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift@@ -459,6 +459,51 @@ extension DeviceTreePatcher {return (nil, value)}+ /// Give a foldable guest's `/product` the board's panel nodes.+ ///+ /// A foldable board describes each panel in a `/product` child carrying+ /// `surface-type` (V68AP: `display0` the cover, `display1` the inner+ /// panel): rotation, scale, corner radii, chrome and framebuffer+ /// identifiers, camera and button geometry. MobileGestalt counts those+ /// children for `MGGetLogicalDeviceDisplayCount` and reads them into+ /// `DisplayExtendedProperties`, which QuartzCore hands each hardware+ /// display as its `extendedProperties`. vphone600 has no such child, so+ /// the guest reports one display and no properties. Each node is copied+ /// with every property, `AAPL,phandle` renumbered above the tree's+ /// highest, and they go first under `/product` in the board's order. Like+ /// the product token, they reach only a foldable guest. Returns the added+ /// nodes serialized, empty when the tree already has panel nodes or is+ /// not a foldable guest.+ static func presentFoldableDisplays(in root: DTNode, from source: DTNode) throws -> [Data] {+ let subtypes = rootSubtypes(of: root)+ guard subtypes.count == 1,+ CustomFirmwarePostRestoreDeviceTree.foldableSubtypes.contains(subtypes[0])+ else { return [] }+ func isPanel(_ node: DTNode) -> Bool {+ node.properties.contains { $0.name == "surface-type" }+ }+ let panels = try child(of: source, named: "product").children.filter(isPanel)+ guard panels.count >= 2 else {+ throw PatcherError.invalidFormat("Foldable displays: the board's /product has \(panels.count) panel nodes, not two")+ }+ let product = try child(of: root, named: "product")+ guard !product.children.contains(where: isPanel) else { return [] }+ var phandle = maximumPhandle(in: root)+ let nodes = panels.map { panel in+ phandle += 1+ let number = phandle+ let node = DTNode()+ node.properties = panel.properties.map { property in+ let value = property.name == "AAPL,phandle"+ ? withUnsafeBytes(of: number.littleEndian) { Data($0) } : property.value+ return DTProperty(name: property.name, flags: property.flags, value: value, valueOffset: 0)+ }+ return node+ }+ product.children.insert(contentsOf: nodes, at: 0)+ return nodes.map(serialize)+ }+private static func rootSubtypes(of node: DTNode) -> [String] {node.properties.filter { $0.name == "target-sub-type" }diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeResearchBoardConversion.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeResearchBoardConversion.swiftindex 4cf47786..21fab993 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeResearchBoardConversion.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeResearchBoardConversion.swift@@ -300,7 +300,7 @@ extension DeviceTreePatcher {return String(decoding: property.value.prefix { $0 != 0 }, as: UTF8.self)}- private static func maximumPhandle(in node: DTNode) -> UInt32 {+ static func maximumPhandle(in node: DTNode) -> UInt32 {let own = node.properties.first { $0.name == "AAPL,phandle" && $0.value.count == 4 }.map { $0.value.withUnsafeBytes { UInt32(littleEndian: $0.loadUnaligned(as: UInt32.self)) } } ?? 0return node.children.map(maximumPhandle(in:)).reduce(own, max)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex 56b19b26..2136288c 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -747,14 +747,27 @@ public enum FirmwareGuestSystemPatchSet {identifier: prebootFoldableProductId,title: "Foldable product identity",summary: """- Research only, off in every preset. Replaces /product/product-id in a foldable \- guest's restored Preboot device tree with the board's own token, taken from the \- Duo's DeviceTree.v68ap. Measured on duotest-m5 (27.1, 24A94425): with the Duo \- token and one display, SpringBoard crash-loops and launchd reboots the guest into \- device-recovery — the Duo branches the token opens expect the second panel. \- CoreMotion's hinge capability therefore needs a narrower route than the device-tree \- token; Apple's Duo simulator satisfies it by registering two displays in its device \- type, not by the token alone.+ Replaces /product/product-id in a foldable guest's restored Preboot device tree \+ with the board's own token, taken from the Duo's DeviceTree.v68ap. CoreMotion \+ picks its motion capabilities from that token: without it the guest is a generic \+ virtual device with none, so the angle, device-state and magic-pose managers are \+ unavailable and locationd starts no device-state relay for the virtual hinge. The \+ Duo branches the token opens expect the second panel the fold display patch \+ publishes; with one display SpringBoard crash-loops. Introduced, off, as \+ preboot-exp-devicetree_foldable_product_id.+ """,+ target: .prebootDeviceTree,+ ),+ VPhonePatchDeclaration(+ identifier: prebootFoldableDisplays,+ title: "Foldable panel nodes",+ summary: """+ Copies a foldable board's panel nodes (/product/display0 and display1 on the \+ Duo's V68AP) into the guest's restored Preboot device tree. MobileGestalt counts \+ them for the logical display count and reads their rotation, scale, corner radii \+ and chrome identifiers into DisplayExtendedProperties, which QuartzCore gives each \+ display; without them the guest reports one display and no properties, where \+ Apple's Duo simulator reports two.""",target: .prebootDeviceTree,),@@ -862,7 +875,9 @@ public enum FirmwareGuestSystemPatchSet {/// Apple's VM sub-type for a foldable board in the restored Preboot/// device tree.public static let prebootFoldableVMSubtype = "preboot-cfw-devicetree_foldable_vm_subtype"- public static let prebootFoldableProductId = "preboot-exp-devicetree_foldable_product_id"+ public static let prebootFoldableProductId = "preboot-cfw-devicetree_foldable_product_id"+ /// The foldable board's panel nodes under `/product`.+ public static let prebootFoldableDisplays = "preboot-cfw-devicetree_foldable_displays"/// The haptics node removal in the restored Preboot device tree, for any/// VM patched before `fw patch` removed it from every guest's tree.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swiftindex 8ee04116..6349641e 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift@@ -70,7 +70,6 @@ public enum FirmwarePatchSetCatalog {.union(experimentalIdentityPatches).union([FirmwareGuestSystemPatchSet.otaUserland, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAirPlayVM, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall]).union([FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, FirmwareGuestSystemPatchSet.tvTPRO, FirmwareGuestSystemPatchSet.tvOTAUserland, FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.tvSetupFocus, FirmwareGuestSystemPatchSet.tvLocalActivation, FirmwareGuestSystemPatchSet.tvLegacySetup])- .union([FirmwareGuestSystemPatchSet.prebootFoldableProductId])/// ProMotion: the 120 Hz timing for the paravirtual display.///@@ -104,6 +103,7 @@ public enum FirmwarePatchSetCatalog {public static let renamedPatches: [String: String] = ["kernel-exp-display_refresh_120hz": proMotionPatch,"kernel-exp-paravirt_gpu_task3": paravirtTask3Patch,+ "preboot-exp-devicetree_foldable_product_id": FirmwareGuestSystemPatchSet.prebootFoldableProductId,]/// The identifiers this bundle declares for ones a VM recorded, in order, each@@ -252,7 +252,8 @@ public enum FirmwarePatchSetCatalog {"preboot-cfw-devicetree_haptics","preboot-cfw-devicetree_iphone_product","preboot-cfw-devicetree_foldable_vm_subtype",- "preboot-exp-devicetree_foldable_product_id",+ "preboot-cfw-devicetree_foldable_product_id",+ "preboot-cfw-devicetree_foldable_displays","preboot-cfw-devicetree_microphone_array",RestoreRamDiskSealPatcher.patchIdentifier,"system-apps-cfw-attitude",diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareIPhoneProductTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareIPhoneProductTests.swiftindex 000dd321..af7f04ae 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareIPhoneProductTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareIPhoneProductTests.swift@@ -210,3 +210,70 @@ struct CustomFirmwareFoldableProductIdTests {}}}++@Suite("Foldable panel nodes")+struct CustomFirmwareFoldableDisplaysTests {+ private typealias Node = FlatDeviceTreeNode++ private static func panel(_ name: String, surface: UInt32, rotation: UInt32, phandle: UInt32) -> Node {+ Node(name, [+ ("display-index", Node.uint32(surface - 1)),+ ("surface-type", Node.uint32(surface)),+ ("display-rotation", Node.uint32(rotation)),+ ("chrome-identifier", Data("com.apple.dt.devicekit.chrome.phone1\(surface)\0".utf8)),+ ("AAPL,phandle", Node.uint32(phandle)),+ ])+ }++ /// The board's `/product`: the two panels first, then a sibling without+ /// `surface-type`.+ private static let board = Node("device-tree", [("target-sub-type", Data("V68AP\0".utf8))], children: [+ Node("product", children: [+ panel("display0", surface: 1, rotation: 0, phandle: 470),+ panel("display1", surface: 2, rotation: 270, phandle: 471),+ Node("camera", [("AAPL,phandle", Node.uint32(472))]),+ ]),+ ]).serialized++ private static func guest(subtype: String, panels: [Node] = []) -> Data {+ Node("device-tree", [("target-sub-type", Data("\(subtype)\0".utf8)), ("AAPL,phandle", Node.uint32(1))], children: [+ Node("product", [("AAPL,phandle", Node.uint32(42))], children: panels + [+ Node("camera", [("AAPL,phandle", Node.uint32(143))]),+ ]),+ ]).serialized+ }++ @Test func `a foldable guest gains the board's panels first, renumbered`() throws {+ for subtype in ["V68AP", "V68VM2025"] {+ let original = Self.guest(subtype: subtype)+ let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withFoldableDisplays(original, board: Self.board)+ #expect(changes.map(\.property) == ["product/display0", "product/display1"])+ let expected = Self.guest(subtype: subtype, panels: [+ Self.panel("display0", surface: 1, rotation: 0, phandle: 144),+ Self.panel("display1", surface: 2, rotation: 270, phandle: 145),+ ])+ #expect(patched == expected)+ #expect(delta == expected.count - original.count)+ }+ }++ @Test func `other guests and a second run are left alone`() throws {+ let original = Self.guest(subtype: "D47AP")+ let (patched, changes, _) = try CustomFirmwarePostRestoreDeviceTree.withFoldableDisplays(original, board: Self.board)+ #expect(changes.isEmpty)+ #expect(patched == original)++ let (once, _, _) = try CustomFirmwarePostRestoreDeviceTree.withFoldableDisplays(Self.guest(subtype: "V68VM2025"), board: Self.board)+ let (twice, again, delta) = try CustomFirmwarePostRestoreDeviceTree.withFoldableDisplays(once, board: Self.board)+ #expect(again.isEmpty)+ #expect(delta == 0)+ #expect(twice == once)+ }++ @Test func `a board without two panels is refused`() throws {+ let donor = Node("device-tree", children: [Node("product", children: [Node("camera")])]).serialized+ #expect(throws: (any Error).self) {+ _ = try CustomFirmwarePostRestoreDeviceTree.withFoldableDisplays(Self.guest(subtype: "V68VM2025"), board: donor)+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 778e79c9..13197b30 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -586,6 +586,7 @@ struct VPhoneCustomFirmwareInstaller {if !Self.isFoldable(device) {notApplicableGuest.insert(FirmwareGuestSystemPatchSet.prebootFoldableVMSubtype)notApplicableGuest.insert(FirmwareGuestSystemPatchSet.prebootFoldableProductId)+ notApplicableGuest.insert(FirmwareGuestSystemPatchSet.prebootFoldableDisplays)notApplicableGuest.insert(FirmwareGuestSystemPatchSet.hinge)notApplicableGuest.insert(FirmwareGuestSystemPatchSet.foldGuard)}@@ -3307,9 +3308,14 @@ struct VPhoneCustomFirmwareInstaller {if enabled(FirmwareGuestSystemPatchSet.prebootFoldableProductId), boardDeviceTree == nil {throw ValidationError("Foldable product identity needs the board's own device tree.")}+ if enabled(FirmwareGuestSystemPatchSet.prebootFoldableDisplays), boardDeviceTree == nil {+ throw ValidationError("Foldable panel nodes need the board's own device tree.")+ }repairGroup.append((FirmwareGuestSystemPatchSet.prebootFoldableVMSubtype, "patch-dt-foldable-vm-subtype", []))repairGroup.append((FirmwareGuestSystemPatchSet.prebootFoldableProductId, "patch-dt-foldable-product-id",boardDeviceTree.map { [$0.path] } ?? []))+ repairGroup.append((FirmwareGuestSystemPatchSet.prebootFoldableDisplays, "patch-dt-foldable-displays",+ boardDeviceTree.map { [$0.path] } ?? []))}repairGroup.append((FirmwareGuestSystemPatchSet.prebootHaptics, "patch-dt-haptics", []))repairGroup.append((FirmwareGuestSystemPatchSet.prebootMicrophoneArray, "patch-dt-microphone-array", []))diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swiftindex 24c8537f..cddceb09 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift@@ -674,6 +674,42 @@ struct VPhoneCustomFirmwarePatchFoldableProductIdCommand: ParsableCommand {}}+// MARK: - patch-dt-foldable-displays++struct VPhoneCustomFirmwarePatchFoldableDisplaysCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-dt-foldable-displays",+ abstract: "Give a foldable guest's device tree the board's panel nodes",+ discussion: """+ Copies the /product children that carry surface-type (display0, the+ cover, and display1, the inner panel, on V68AP) from the foldable+ board's tree into a foldable guest's, in place, preserving the+ container's compression, manifest and restore info. MobileGestalt+ counts them for MGGetLogicalDeviceDisplayCount and reads their+ rotation, scale, corner radii and chrome identifiers into+ DisplayExtendedProperties. Any other tree, or one that already has+ panel nodes, is left as it is.++ Takes a devicetree.img4 (preferred) or bare .im4p, and the foldable+ board's DeviceTree.<board>.im4p.+ """,+ )++ @Argument(help: "Path to devicetree.img4 or devicetree.im4p", transform: URL.init(fileURLWithPath:))+ var deviceTree: URL++ @Argument(help: "Path to the foldable board's DeviceTree.<board>.im4p", transform: URL.init(fileURLWithPath:))+ var board: URL++ @Flag(name: .customLong("dry-run"), help: "Report what would change and exit")+ var dryRun = false++ func run() throws {+ try CustomFirmwarePostRestoreDeviceTree.presentFoldableDisplays(+ at: deviceTree, board: board, dryRun: dryRun, verbose: true)+ }+}+// MARK: - patch-dt-hapticsstruct VPhoneCustomFirmwarePatchHapticsCommand: ParsableCommand {diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swiftindex 71d0cd46..34ebacd3 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift@@ -260,6 +260,7 @@ struct VPhoneCustomFirmwareCommand: ParsableCommand {VPhoneCustomFirmwarePatchIPhoneProductCommand.self,VPhoneCustomFirmwarePatchFoldableVMSubtypeCommand.self,VPhoneCustomFirmwarePatchFoldableProductIdCommand.self,+ VPhoneCustomFirmwarePatchFoldableDisplaysCommand.self,VPhoneCustomFirmwarePatchHapticsCommand.self,VPhoneCustomFirmwarePatchMicrophoneArrayCommand.self,] + VPhoneCustomFirmwareMachOVerbs.all + VPhoneCustomFirmwareDyldSharedCacheVerbs.all,diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plistindex 58c0b714..e8d5f8ba 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist@@ -107,7 +107,8 @@<string>preboot-cfw-devicetree_foldable_vm_subtype</string><string>preboot-cfw-devicetree_microphone_array</string><string>preboot-homepod-exp-audio_product</string>- <string>preboot-exp-devicetree_foldable_product_id</string>+ <string>preboot-cfw-devicetree_foldable_product_id</string>+ <string>preboot-cfw-devicetree_foldable_displays</string><string>restoreramdisk-boot-apfs_sha3_hash</string><string>system-apps-cfw-attitude</string><string>system-apps-cfw-signin_sheets</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plistindex 06304eae..0ffe9fbf 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist@@ -101,7 +101,6 @@<string>devicetree-exp-arm_io_soc_generation</string><string>preboot-exp-devicetree_identity</string><string>dyld-exp-mis_trust_auth</string>- <string>preboot-exp-devicetree_foldable_product_id</string><string>system-preferences-exp-root_rows</string><string>dyld-exp-settings_software_update_row</string><string>system-dyld-exp-tv_tpro</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plistindex cda85baa..2015d16b 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist@@ -118,7 +118,8 @@<string>preboot-cfw-devicetree_iphone_product</string><string>preboot-cfw-devicetree_foldable_vm_subtype</string><string>preboot-cfw-devicetree_microphone_array</string>- <string>preboot-exp-devicetree_foldable_product_id</string>+ <string>preboot-cfw-devicetree_foldable_product_id</string>+ <string>preboot-cfw-devicetree_foldable_displays</string><string>restoreramdisk-boot-apfs_sha3_hash</string><string>system-apps-cfw-attitude</string><string>system-apps-cfw-signin_sheets</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plistindex 31addaf0..6f1a3f27 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist@@ -121,7 +121,8 @@<string>preboot-cfw-devicetree_iphone_product</string><string>preboot-cfw-devicetree_foldable_vm_subtype</string><string>preboot-cfw-devicetree_microphone_array</string>- <string>preboot-exp-devicetree_foldable_product_id</string>+ <string>preboot-cfw-devicetree_foldable_product_id</string>+ <string>preboot-cfw-devicetree_foldable_displays</string><string>restoreramdisk-boot-apfs_sha3_hash</string><string>system-apps-cfw-attitude</string><string>system-apps-cfw-signin_sheets</string>diff --git a/VPhoneGuestComponents/DeviceHubFix/VPCMAngleManager.m b/VPhoneGuestComponents/DeviceHubFix/VPCMAngleManager.mindex 3acdf243..b2890495 100644--- a/VPhoneGuestComponents/DeviceHubFix/VPCMAngleManager.m+++ b/VPhoneGuestComponents/DeviceHubFix/VPCMAngleManager.m@@ -28,6 +28,7 @@// addOperationWithBlock:.#import <Foundation/Foundation.h>+#import <objc/message.h>#import <objc/runtime.h>#include <dlfcn.h>#include <string.h>@@ -327,6 +328,13 @@ __attribute__((constructor)) static void vpInstallAngleManagerStandIn(void) {vpMotionLog(@"hinge manager: CMAngleManager not found, CoreDevice hingeAngle stays off");return;}+ // A guest with the foldable's product-id has CoreMotion's own capability+ // bits, and locationd relays the virtual hinge into the real manager.+ // The stand-in is only for a guest without them.+ if (((BOOL (*)(id, SEL))objc_msgSend)(manager, sel_registerName("isAvailable"))) {+ vpMotionLog(@"hinge manager: CoreMotion's own CMAngleManager is available, no stand-in");+ return;+ }vpRegisterAngleDataClass();Method available = class_getClassMethod(manager, sel_registerName("isAvailable"));diff --git a/VPhoneGuestComponents/FoldDisplay/FoldDisplayBackboard.m b/VPhoneGuestComponents/FoldDisplay/FoldDisplayBackboard.mindex 2ee2aff9..a50a4128 100644--- a/VPhoneGuestComponents/FoldDisplay/FoldDisplayBackboard.m+++ b/VPhoneGuestComponents/FoldDisplay/FoldDisplayBackboard.m@@ -69,9 +69,13 @@ static BOOL vpAddInnerRenderDisplayToServer(id server) {vpFoldDisplayLog(@"inner display: virtual display initializer ABI unavailable");return NO;}- // The panel's native pixels, landscape: 951x669 points at 3x.+ // The panel's native pixels, landscape: 951x669 points at 3x. Its+ // physical size, in inches, is what pixelsPerInch divides by; a+ // virtual display has none unless given one, and both panels share+ // the cover's 460 ppi pitch (MobileGestalt main-screen-pitch).id display = [(id<VPhoneInnerDisplayInitialization>)[cls alloc] initWithOptions:@{@"kCAVirtualDisplayWidth": @2853, @"kCAVirtualDisplayHeight": @2007,+ @"kCAVirtualDisplayPhysicalWidth": @(2853 / 460.0), @"kCAVirtualDisplayPhysicalHeight": @(2007 / 460.0),@"kCAVirtualDisplayUpdateRate": @60, @"kCAVirtualDisplayName": vpInnerDisplayName,}];if (!display) { vpFoldDisplayLog(@"inner display: initializer returned nil"); return NO; }@@ -129,14 +133,43 @@ static void vpAddInnerRenderDisplay(unsigned int attempt) {// a render display's extendedProperties. The iPhone19,4 device tree gives// display0 (the primary, the cover) surface type 1 and display1 (the inner// panel) 2; SpringBoard's fold policies pick their panels by these.+//+// A hardware display takes its whole entry of MobileGestalt's+// DisplayExtendedProperties (rotation, scale, corner radii, chrome and+// framebuffer identifiers, read from the panel nodes the device tree repair+// adds) when QuartzCore builds it. A virtual display takes nothing, so the+// inner display is given the entry with its surface type here.static IMP vpOriginalExtendedProperties;+static NSDictionary *vpGestaltDisplayProperties(NSNumber *surfaceType) {+ // Kept once MobileGestalt has an answer; asked again until then.+ static NSArray *entries;+ NSArray *known;+ @synchronized(NSNull.class) {+ if (!entries) {+ CFTypeRef (*copyAnswer)(CFStringRef, CFDictionaryRef) = dlsym(RTLD_DEFAULT, "MGCopyAnswer");+ id answer = copyAnswer ? CFBridgingRelease(copyAnswer(CFSTR("DisplayExtendedProperties"), NULL)) : nil;+ if ([answer isKindOfClass:NSArray.class] && [answer count]) {+ entries = answer;+ vpFoldDisplayLog([NSString stringWithFormat:@"inner display: %lu MobileGestalt display entries",+ (unsigned long)entries.count]);+ }+ }+ known = entries;+ }+ for (NSDictionary *entry in known)+ if ([entry isKindOfClass:NSDictionary.class] && [entry[@"DeviceSurfaceType"] isEqual:surfaceType]) return entry;+ return nil;+}+static id vpSurfaceExtendedProperties(id self, SEL cmd) {id properties = ((id (*)(id, SEL))vpOriginalExtendedProperties)(self, cmd);id name = ((id (*)(id, SEL))objc_msgSend)(self, sel_registerName("deviceName"));NSNumber *surfaceType = [name isEqual:@"primary"] ? @1 : [name isEqual:vpInnerDisplayName] ? @2 : nil;if (!surfaceType || (properties && ![properties isKindOfClass:NSDictionary.class])) return properties;NSMutableDictionary *derived = properties ? [properties mutableCopy] : [NSMutableDictionary dictionary];+ if ([surfaceType isEqual:@2])+ [derived addEntriesFromDictionary:vpGestaltDisplayProperties(surfaceType) ?: @{}];derived[@"DeviceSurfaceType"] = surfaceType;return [derived copy];}diff --git a/VPhoneGuestComponents/Hinge/VPhoneHingeHID.h b/VPhoneGuestComponents/Hinge/VPhoneHingeHID.hindex d8a85ba6..fbac433f 100644--- a/VPhoneGuestComponents/Hinge/VPhoneHingeHID.h+++ b/VPhoneGuestComponents/Hinge/VPhoneHingeHID.h@@ -2,9 +2,9 @@#import <Foundation/Foundation.h>// Small ABI surface from Apple's IOHIDfamily HIDVirtualEventService.h, plus-// the C hinge-angle event factory IOHIDEventCreateHingeAngleEvent. Everything-// is resolved at runtime, so the guest library needs no private SDK stub:-// the factory is a dlsym, the service class an NSClassFromString.+// the C event and serialization functions IOKit exports. Everything is+// resolved at runtime, so the guest library needs no private SDK stub: the+// functions are dlsyms, the service class an NSClassFromString.@protocol VPhoneHingeHIDService <NSObject>@property (weak) id delegate;@property (readonly) uint64_t serviceID;@@ -15,20 +15,24 @@- (BOOL)dispatchEvent:(id)event;@end-// HID.framework, verified against macOS 27.0.1's copy by calling it and-// reading the event's own field description back:-// IOHIDEventCreateHingeAngleEvent(allocator, timeStamp,-// angleDegrees, mechanicalAngleDegrees,-// velocityDegreesPerSecond, options)-// CoreMotion's CLAngleNotifier consumes events of this type (0x2C) from the-// virtual service below. The created event carries the hinge state through-// HIDEvent's own -setHingeAngleState: accessor, the same field Apple's-// recorded Duo samples (hinge-samples.csv in SpringBoardFoundation) carry-// per sample.-typedef void *(*VPhoneHingeEventFactory)(void *, uint64_t, double, double, double, uint32_t);+// Apple's virtual-machine host controls ("AVP" in locationd): a service with+// primary usage page 0xFF61, usage 0x5B, whose vendor-defined events carry a+// dictionary in IOKit's XML serialization (at most 256 bytes). locationd's+// CLDeviceStateRelay subscribes to it on a VM with a foldable's motion+// capabilities and turns each dictionary into the hinge-angle and+// device-state services CoreMotion reads (CoreMotion_DeviceStateRelay_Crane+// 0xFF0C/0x21 and _DeviceState 0xFF0C/0x22), the services Apple's Duo+// simulator shows:+// {source: hinge-slider-control, type: range, value: <degrees>}+// {source: orientation-picker-control, type: enum,+// value: ambiguous|portrait|landscape-left|landscape-right|faceup|facedown}+#define VP_HOST_CONTROLS_USAGE_PAGE 0xff61+#define VP_HOST_CONTROLS_USAGE 0x5b+#define VP_HOST_CONTROLS_MAX_DATA 256-// HIDEvent's hinge accessors, resolved at runtime beside the factory.-@protocol VPhoneHingeHIDEvent <NSObject>-- (void)setHingeAngleState:(int32_t)state;-@property (readonly) double hingeAngleAngleDegrees;-@end+// IOHIDEventCreateVendorDefinedEvent(allocator, timeStamp, usagePage,+// usage, version, data, length, options)+typedef void *(*VPhoneHingeVendorEventFactory)(void *, uint64_t, uint32_t, uint32_t, uint32_t,+ const uint8_t *, long, uint32_t);+// IOCFSerialize(object, options)+typedef CFDataRef (*VPhoneHingeSerializer)(CFTypeRef, uint32_t);diff --git a/VPhoneGuestComponents/Hinge/VPhoneHingeState.h b/VPhoneGuestComponents/Hinge/VPhoneHingeState.hindex f6aaddf6..ac5f8703 100644--- a/VPhoneGuestComponents/Hinge/VPhoneHingeState.h+++ b/VPhoneGuestComponents/Hinge/VPhoneHingeState.h@@ -23,6 +23,7 @@#define VP_HINGE_SWEEP_MS 10.03#define VP_HINGE_OPEN_DEFAULT_MS 600.0#define VP_HINGE_CLOSE_DEFAULT_MS 800.0+#define VP_HINGE_REPUSH_SECONDS 5typedef struct {BOOL enabled;@@ -30,6 +31,9 @@ typedef struct {double angle;double durationMs; // < 0: the per-direction default; 0: instantint32_t profile; // 0 continuous, 1 fade+ // CoreMotion's device orientation, 1 portrait … 6 face down; 0 leaves+ // the orientation the relay holds.+ int32_t orientation;} VPhoneHingeState;typedef enum {@@ -83,20 +87,31 @@ static inline BOOL VPhoneHingeDecode(id value, VPhoneHingeState *state) {return NO;sweep = [sweepValue boolValue];}+ int32_t orientation = 0;+ if (value[@"orientation"] != nil) {+ if (!VPhoneHingeNumber(value[@"orientation"]))+ return NO;+ orientation = [value[@"orientation"] intValue];+ if (orientation < 0 || orientation > 6 || orientation != [value[@"orientation"] doubleValue])+ return NO;+ }*state = (VPhoneHingeState){- [enabled boolValue], sweep, degrees, duration, profile,+ [enabled boolValue], sweep, degrees, duration, profile, orientation,};return YES;}static inline NSDictionary *VPhoneHingeEncode(VPhoneHingeState state) {- return @{+ NSMutableDictionary *encoded = [@{@"enabled": @(state.enabled),@"sweep": @(state.sweep),@"angle": @(state.angle),@"duration_ms": @(state.durationMs),@"profile": @(state.profile),- };+ } mutableCopy];+ if (state.orientation)+ encoded[@"orientation"] = @(state.orientation);+ return encoded;}// HID report interval, microseconds. Zero means there are no subscribers.diff --git a/VPhoneGuestComponents/Hinge/libvphonehinge.m b/VPhoneGuestComponents/Hinge/libvphonehinge.mindex 30204a5d..b6745fa2 100644--- a/VPhoneGuestComponents/Hinge/libvphonehinge.m+++ b/VPhoneGuestComponents/Hinge/libvphonehinge.m@@ -14,10 +14,13 @@@property (nonatomic, strong) dispatch_source_t sweepTimer;@property (nonatomic, strong) dispatch_source_t heartbeat;@property (nonatomic, strong) id<VPhoneHingeHIDService> service;-@property (nonatomic) VPhoneHingeEventFactory factory;+@property (nonatomic) VPhoneHingeVendorEventFactory factory;+@property (nonatomic) VPhoneHingeSerializer serialize;@property (nonatomic, strong) NSMutableDictionary *properties;@property (nonatomic) VPhoneHingeState state;@property (nonatomic) double currentAngle;+// The orientation the relay was last given; 0 before any.+@property (nonatomic) int32_t orientation;// The sweep in flight: from currentAngle to state.angle over its duration.@property (nonatomic) double sweepElapsed;@property (nonatomic) double sweepDuration;@@ -73,6 +76,11 @@if (self.enumerated)[self dispatchSample];}+ if (state.orientation && state.orientation != self.orientation) {+ self.orientation = state.orientation;+ if (self.enumerated)+ [self dispatchOrientation];+ }} else {self.lastError = @"Stored hinge angle is malformed; keeping the last one";}@@ -80,7 +88,10 @@}- (void)updateTimer {- uint64_t period = self.enumerated && self.interval ? self.interval * NSEC_PER_USEC : DISPATCH_TIME_FOREVER;+ // locationd's relay keeps the last value it was sent and never asks for+ // one; when locationd restarts it reseeds 0° and portrait. Stationary+ // values are therefore sent again every few seconds.+ uint64_t period = self.enumerated ? VP_HINGE_REPUSH_SECONDS * NSEC_PER_SEC : DISPATCH_TIME_FOREVER;dispatch_source_set_timer(self.timer, period == DISPATCH_TIME_FOREVER ? DISPATCH_TIME_FOREVER : DISPATCH_TIME_NOW,period, NSEC_PER_MSEC);// The status is republished every two seconds only while samples flow, as@@ -209,31 +220,41 @@ static double VPhoneHingeProgress(double t, int32_t profile) {CFSTR(VP_HINGE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);}-- (void)dispatchAngle:(double)angle velocity:(double)velocity state:(int32_t)state phase:(int32_t)phase {- // The factory's angle and mechanical angle both take the fold angle: no- // mechanical detent distinguishes them on a virtual hinge. The state- // field carries the hinge state, as Apple's recorded samples do.- id event = (__bridge id)self.factory(NULL, mach_absolute_time(), angle, angle, velocity, 0);- if (event && [event respondsToSelector:NSSelectorFromString(@"setHingeAngleState:")])- ((void (*)(id, SEL, int32_t))objc_msgSend)(event, sel_registerName("setHingeAngleState:"), state);+/// One host-control dictionary as a vendor-defined event on the service.+- (BOOL)dispatchControl:(NSDictionary *)control {+ NSData *data = CFBridgingRelease(self.serialize((__bridge CFTypeRef)control, 0));+ if (!data.length || data.length > VP_HOST_CONTROLS_MAX_DATA) {+ self.failures++;+ self.lastError = @"Host-control dictionary did not serialize within 256 bytes";+ return NO;+ }+ id event = CFBridgingRelease(self.factory(NULL, mach_absolute_time(), VP_HOST_CONTROLS_USAGE_PAGE,+ VP_HOST_CONTROLS_USAGE, 0, data.bytes, (long)data.length, 0));if (event && [self.service dispatchEvent:event]) {self.dispatched++;self.lastError = nil;- } else {- self.failures++;- self.lastError = @"HID event dispatch failed";+ return YES;}+ self.failures++;+ self.lastError = @"HID event dispatch failed";+ return NO;+}++- (void)dispatchAngle:(double)angle velocity:(double)velocity state:(int32_t)state phase:(int32_t)phase {+ // The relay reads the slider's value as whole degrees and derives the+ // velocity, hinge state and event phase CoreMotion reports itself.+ [self dispatchControl:@{@"source": @"hinge-slider-control", @"type": @"range", @"value": @((long)lround(angle))}];[self publishLatestAngle:angle velocity:velocity state:state phase:phase];}-- (id)sample {- id event = (__bridge id)self.factory(NULL, mach_absolute_time(), self.currentAngle,- self.currentAngle, 0, 0);- if (event && [event respondsToSelector:NSSelectorFromString(@"setHingeAngleState:")])- ((void (*)(id, SEL, int32_t))objc_msgSend)(- event, sel_registerName("setHingeAngleState:"),- VPhoneHingeStateForAngle(self.currentAngle));- return event;+- (void)dispatchOrientation {+ // The picker has no upside-down entry; that orientation stays with the+ // test-automation pose.+ NSDictionary *names = @{@1: @"portrait", @3: @"landscape-left", @4: @"landscape-right",+ @5: @"faceup", @6: @"facedown"};+ NSString *name = names[@(self.orientation)];+ if (name)+ [self dispatchControl:@{@"source": @"orientation-picker-control", @"type": @"enum", @"value": name}];}- (void)createService {@@ -275,29 +296,29 @@ static double VPhoneHingeProgress(double t, int32_t profile) {}- (void)start {- void *hid = dlopen("/System/Library/PrivateFrameworks/HID.framework/HID", RTLD_NOW | RTLD_LOCAL);- self.factory = (VPhoneHingeEventFactory)dlsym(hid, "IOHIDEventCreateHingeAngleEvent");+ void *iokit = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_NOW | RTLD_LOCAL);+ self.factory = (VPhoneHingeVendorEventFactory)dlsym(iokit, "IOHIDEventCreateVendorDefinedEvent");+ self.serialize = (VPhoneHingeSerializer)dlsym(iokit, "IOCFSerialize");+ dlopen("/System/Library/PrivateFrameworks/HID.framework/HID", RTLD_NOW | RTLD_LOCAL);Class serviceClass = NSClassFromString(@"HIDVirtualEventService");- if (!hid || !self.factory || !serviceClass ||+ if (!iokit || !self.factory || !self.serialize || !serviceClass ||![serviceClass instancesRespondToSelector:@selector(dispatchEvent:)]) {self.lastError = @"Required HID virtual-service API unavailable";NSLog(@"[vphone-hinge] %@", self.lastError);[self publishStatus];return;}- // CoreMotion's CLAngleNotifier subscribes to this virtual service: usage- // page 0xFF0C (Apple vendor), usage 0x21 (hinge angle). The capability is- // only selected on a product-id CoreMotion knows — the foldable product- // identity patch — so on any other guest the service sits unread.+ // locationd's device-state relay subscribes to the host controls by+ // primary usage alone. It runs only when CoreMotion selects a foldable's+ // capabilities from the product-id — the foldable product identity+ // patch — so on any other guest the service sits unread.self.properties = [@{- @"PrimaryUsagePage": @0xff0c, @"PrimaryUsage": @0x21,- @"DeviceUsagePairs": @[@{@"DeviceUsagePage": @0xff0c, @"DeviceUsage": @0x21}],- @"Product": @"VPhone Hinge Angle Sensor", @"Manufacturer": @"vphone",+ @"PrimaryUsagePage": @VP_HOST_CONTROLS_USAGE_PAGE, @"PrimaryUsage": @VP_HOST_CONTROLS_USAGE,+ @"DeviceUsagePairs": @[@{@"DeviceUsagePage": @VP_HOST_CONTROLS_USAGE_PAGE,+ @"DeviceUsage": @VP_HOST_CONTROLS_USAGE}],+ @"Product": @"VPhone Host Controls", @"Manufacturer": @"vphone",@"Transport": @"Virtual", @"Built-In": @YES,@"ReportInterval": @0, @"BatchInterval": @0,- // Aggregate subscriptions before forwarding the requested interval to- // this delegate, so one client's stop cannot stop other subscribers.- @"HIDDefaultSensorControlOptions": @7, @"SensorPropertySupported": @3,} mutableCopy];[self readConfiguration];int status = notify_register_dispatch(VP_HINGE_NOTIFICATION, &_notificationToken, self.queue,@@ -333,7 +354,6 @@ static double VPhoneHingeProgress(double t, int32_t profile) {if ([key isEqualToString:@"ReportInterval"]) {self.interval = VPhoneHingeInterval(value);self.properties[key] = @(self.interval);- [self updateTimer];[self publishStatus];return YES;}@@ -343,9 +363,7 @@ static double VPhoneHingeProgress(double t, int32_t profile) {}- (id)copyEventMatching:(NSDictionary *)matching forService:(id)service {- NSNumber *type = matching[@"EventType"];- // 0x2c is the hinge-angle event type CLAngleNotifier asks for.- return service == self.service && self.enumerated && (!type || type.unsignedIntValue == 0x2c) ? [self sample] : nil;+ return nil; // The relay only consumes events as they are dispatched.}- (BOOL)setOutputEvent:(id)event forService:(id)service {@@ -360,6 +378,7 @@ static double VPhoneHingeProgress(double t, int32_t profile) {self.lastError = nil;NSLog(@"[vphone-hinge] HID service enumerated: %llu", self.service.serviceID);[self dispatchSample];+ [self dispatchOrientation];} else if (type == 11 && !self.cancelling) { // Terminated or resetself.enumerated = NO;self.cancelling = YES;diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefileindex ccb51597..5a5b184e 100644--- a/VPhoneGuestComponents/Makefile+++ b/VPhoneGuestComponents/Makefile@@ -408,9 +408,9 @@ test-accelerometer:-o $(OUT)/AccelerometerTests Tests/AccelerometerTests.m Accelerometer/VPhoneOrientationSink.m -framework Foundation@$(OUT)/AccelerometerTests-# The hinge's transport and, on a Mac with Apple's HID.framework, a real-# IOHIDEventCreateHingeAngleEvent call whose fields read back from the event's-# own description.+# The hinge's transport and, on a Mac whose IOKit has them, the host-control+# dictionaries serialized, read back and wrapped in a vendor-defined event as+# the guest library does.test-hinge:@mkdir -p $(OUT)xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -IHinge \diff --git a/VPhoneGuestComponents/README.md b/VPhoneGuestComponents/README.mdindex 2acf3ead..458935e1 100644--- a/VPhoneGuestComponents/README.md+++ b/VPhoneGuestComponents/README.md@@ -86,17 +86,19 @@ sensor. See `Research/Guest/springboard_orientation_stuck.md` for evidence andthe language-change regression boundary.`system-backboardd-cfw-hinge` installs `libvphonehinge.dylib`, also selected-independently and loaded only in backboardd. It publishes the foldable's-virtual hinge HID service (usage page 0xFF0C, usage 0x21) and reports the-angle configured by `display.posture`, using HID.framework's C factory-`IOHIDEventCreateHingeAngleEvent` — the only hinge entry point; HIDEvent-exposes just `-hingeAngle*` accessors. CoreMotion's angle manager, and through-it CoreDevice's hingeAngle stream, reads it; CoreMotion only looks when the-device tree carries the foldable board's own product-id-(`preboot-cfw-devicetree_foldable_product_id`), so on any other guest the-service sits unread. Foldable guests only; `make test-hinge` checks the-configuration transport and, on a Mac with Apple's HID.framework, a real-factory call whose fields read back from the event's own description.+independently and loaded only in backboardd. It publishes Apple's VM host+controls (primary usage page 0xFF61, usage 0x5B) and sends the angle and+device orientation configured by `display.posture` and `display.rotation` as+vendor-defined events carrying `IOCFSerialize`d `hinge-slider-control` and+`orientation-picker-control` dictionaries. locationd's device-state relay+turns them into the hinge-angle and device-state services CoreMotion reads+(`CoreMotion_DeviceStateRelay_Crane` 0xFF0C/0x21 and `_DeviceState`+0xFF0C/0x22), and SpringBoard and CoreDevice's hingeAngle stream read+CoreMotion. The relay only runs when the device tree carries the foldable+board's own product-id (`preboot-cfw-devicetree_foldable_product_id`), so on+any other guest the service sits unread. Foldable guests only; `make+test-hinge` checks the configuration transport and, on a Mac, the+dictionaries' serialization round trip, size and vendor-defined event.`system-apps-cfw-attitude` installs `libvphoneattitude.dylib`, loaded bySystemHook into apps. It supplies a stationary Core Motion pose throughdiff --git a/VPhoneGuestComponents/Tests/HingeTests.m b/VPhoneGuestComponents/Tests/HingeTests.mindex 6aa66adc..bd06a960 100644--- a/VPhoneGuestComponents/Tests/HingeTests.m+++ b/VPhoneGuestComponents/Tests/HingeTests.m@@ -1,11 +1,11 @@-// HingeTests.m — the hinge angle transport, and the real HID factory.+// HingeTests.m — the hinge angle transport, and the host-control events.//-// On a Mac, Apple's own HID.framework answers IOHIDEventCreateHingeAngleEvent,-// so the argument order the guest library calls with is checked against the-// event's own field description: the third argument must read back as-// AngleDegrees, the fourth as MechanicalAngleDegrees, the fifth as the-// velocity. Where the framework is absent (a CI runner without the private-// framework) the factory check is skipped; the transport checks always run.+// On a Mac, IOKit answers IOCFSerialize, IOCFUnserializeWithSize and+// IOHIDEventCreateVendorDefinedEvent as the guest's does, so a host-control+// dictionary is checked to fit locationd's 256-byte limit, to read back the+// way locationd parses it, and to land in a vendor-defined event on the+// host-control usage. Where a function is absent the event checks are+// skipped; the transport checks always run.#import "../Hinge/VPhoneHingeHID.h"#import "../Hinge/VPhoneHingeState.h"#include <assert.h>@@ -75,6 +75,18 @@ int main(void) {bad[@"duration_ms"] = invalid;assert(!VPhoneHingeDecode(bad, &state));}+ // The host controls' orientation: 1–6, 0 leaving it, absent as 0;+ // encoded only when given, so an angle-only request round-trips.+ NSMutableDictionary *oriented = [sample mutableCopy];+ oriented[@"orientation"] = @3;+ assert(VPhoneHingeDecode(oriented, &state) && state.orientation == 3);+ assert([VPhoneHingeEncode(state) isEqual:oriented]);+ assert(VPhoneHingeDecode(sample, &state) && state.orientation == 0);+ for (id invalid in @[@7, @-1, @1.5, @YES, @"portrait"]) {+ NSMutableDictionary *bad = [sample mutableCopy];+ bad[@"orientation"] = invalid;+ assert(!VPhoneHingeDecode(bad, &state));+ }assert(!VPhoneHingeDecode(@"flat", &state));assert(VPhoneHingeInterval(nil) == 0);assert(VPhoneHingeInterval(@YES) == 0);@@ -84,24 +96,38 @@ int main(void) {assert(VPhoneHingeInterval(@(16000)) == 16000);assert(VPhoneHingeInterval(@(2e9)) == 1000000);- void *hid = dlopen("/System/Library/PrivateFrameworks/HID.framework/HID", RTLD_NOW | RTLD_LOCAL);- VPhoneHingeEventFactory factory = (VPhoneHingeEventFactory)dlsym(hid, "IOHIDEventCreateHingeAngleEvent");- if (!factory) {- printf("HID.framework hinge factory unavailable here; transport checks only\n");+ void *iokit = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_NOW | RTLD_LOCAL);+ VPhoneHingeSerializer serialize = (VPhoneHingeSerializer)dlsym(iokit, "IOCFSerialize");+ CFTypeRef (*unserialize)(const char *, size_t, CFAllocatorRef, uint32_t, CFStringRef *) =+ dlsym(iokit, "IOCFUnserializeWithSize");+ VPhoneHingeVendorEventFactory factory =+ (VPhoneHingeVendorEventFactory)dlsym(iokit, "IOHIDEventCreateVendorDefinedEvent");+ if (!serialize || !unserialize || !factory) {+ printf("IOKit host-control functions unavailable here; transport checks only\n");printf("hinge tests passed\n");return 0;}- id event = (__bridge id)factory(NULL, mach_absolute_time(), 42.0, 43.0, 1.0, 0);- assert(event);- // The description is column-formatted; collapse the runs of spaces- // before matching, so a wider label column still passes.- NSArray *fields = [[event description] componentsSeparatedByCharactersInSet:- [NSCharacterSet whitespaceCharacterSet]];- NSString *flat = [[fields filteredArrayUsingPredicate:- [NSPredicate predicateWithFormat:@"length > 0"]] componentsJoinedByString:@" "];- assert([flat containsString:@"AngleDegrees: 42.000000"]);- assert([flat containsString:@"MechanicalAngleDegre 43.000000"]);- assert([flat containsString:@"velocityDegreesPerSe 1.000000"]);+ // The longest dictionaries the provider sends.+ NSArray *controls = @[+ @{@"source": @"hinge-slider-control", @"type": @"range", @"value": @180L},+ @{@"source": @"orientation-picker-control", @"type": @"enum", @"value": @"landscape-right"},+ ];+ for (NSDictionary *control in controls) {+ NSData *data = CFBridgingRelease(serialize((__bridge CFTypeRef)control, 0));+ assert(data.length > 0 && data.length <= VP_HOST_CONTROLS_MAX_DATA);+ id read = CFBridgingRelease(unserialize(data.bytes, data.length, NULL, 0, NULL));+ assert([read isEqual:control]);+ id event = CFBridgingRelease(factory(NULL, mach_absolute_time(), VP_HOST_CONTROLS_USAGE_PAGE,+ VP_HOST_CONTROLS_USAGE, 0, data.bytes, (long)data.length, 0));+ assert(event);+ // The description is column-formatted; collapse the runs of+ // spaces before matching, so a wider label column still passes.+ NSArray *fields = [[event description] componentsSeparatedByCharactersInSet:+ [NSCharacterSet whitespaceCharacterSet]];+ NSString *flat = [[fields filteredArrayUsingPredicate:+ [NSPredicate predicateWithFormat:@"length > 0"]] componentsJoinedByString:@" "];+ assert([flat localizedCaseInsensitiveContainsString:@"VendorDefined"]);+ }printf("hinge tests passed\n");return 0;}