Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

fix: feed virtual gravity into SpringBoard orientation

Jacky96ecc23e924f
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index c5504a2b..e5642060 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -423,6 +423,32 @@
> platform capability gate and optional IMU match still require guest proof.
> Reveal evidence and manual acceptance: `Research/Guest/virtual_gyroscope.md`.
+> **Gravity accelerometer (2026-10-20; iPadOS 26.6.2 guest verified):**
+> `system-backboardd-cfw-accelerometer` in Guest System, selected by both
+> presets on iOS 18+, installs `/usr/lib/libvphoneaccelerometer.dylib`.
+> SystemHook loads it into backboardd and SpringBoard. A built-in HID accelerometer
+> (page `0xff00`, usage `3`) supplies stationary gravity in g, with a monotonic
+> timestamp and sequence. `display.rotation` publishes the matching physical
+> pose through mobile preferences and a Darwin notification before its existing
+> orientation request. The provider keeps that pose across SpringBoard
+> relaunches; it streams while HID clients request a report interval and emits
+> one sample on enumeration/configuration changes. Raw HID alone was verified
+> insufficient on iPadOS 26.6.2: it enumerated but never gained a subscription,
+> and the language-change wedge remained. The provider also classifies its
+> stationary HID sample and posts it on BKOrientationManager's native queue,
+> replacing the missing hardware classification stage. SpringBoard recomputes
+> delivery and deferral after setup seeds the actual backlight state.
+> No kernel, DSC or system executable bytes change. Disabling the patch removes
+> its library; live environment synchronization never reinstalls an absent copy.
+> Replacing the library requires a reboot, without restarting backboardd during
+> environment installation. HID enumeration/dispatch alone do not establish
+> SpringBoard recovery; native sink delivery and interface readback are
+> separately observable. The isolated `gyro-regress` clone passed gravity-only
+> four-direction rotation, rotation lock/unlock and same-pose language-change
+> relaunch on `2.10.1-local.a8c22dce`, without a recovery respring/lock cycle.
+> Evidence and regression procedure:
+> `Research/Guest/springboard_orientation_stuck.md`.
+
> **Device attitude (2026-10-08; guest acceptance pending):**
> `system-apps-cfw-attitude` in Guest System is selected by both presets on
> iOS 18+. It adds `/usr/lib/libvphoneattitude.dylib`, loaded by SystemHook
diff --git a/Research/Guest/springboard_orientation_stuck.md b/Research/Guest/springboard_orientation_stuck.md
new file mode 100644
index 00000000..f0cc256d
--- /dev/null
+++ b/Research/Guest/springboard_orientation_stuck.md
@@ -0,0 +1,333 @@
+# SpringBoard orientation arbitration stuck after language-change relaunch
+
+Investigated 2026-10-20 on iPad16,1 / iPadOS 26.6.2 (23G90). Static evidence is
+the `23G90__iPad16,1_2` dyld shared cache extraction plus live `log collect`
+captures from clean local VMs (`repro26`, `kbdtest-ipad`); every function
+cited below was decompiled from the cache's SpringBoard image with REA/Ghidra
+12.1.4 (addresses are cache VM addresses, preserved by `ipsw dyld extract`).
+
+## Symptom
+
+After Settings → General → Language & Region applies a new preferred language,
+the system relaunches SpringBoard behind a full-screen transition overlay.
+From that point every landscape `display.rotation` on the home screen returns
+`unavailable: The device did not apply the requested rotation`. Rotation lock
+is off. Reproduced deterministically on a clean VM with no third-party apps;
+plain respring and respring-with-rotation-lock never trigger it. A respring
+clears it; on one machine lock/unlock cleared it, on another it did not.
+
+## The arbitration gate, from the image
+
+`SBTraitsEmbeddedDisplayPipelineManager` (SpringBoard,
+`/System/Library/PrivateFrameworks/SpringBoard.framework/SpringBoard`) owns
+device-orientation delivery to the TRA arbiter.
+
+- `_updateOrientationEventsEnabledState` @ `0x22410802c`
+
+ ```
+ enabled = [self _isBacklightOn] || [[SBPlatformController sharedInstance] prefersAlwaysOnOrientation]
+ if (accelerometer.orientationEventsEnabled != enabled)
+ [accelerometer setOrientationEventsEnabled:enabled]
+ ```
+
+ iPads carry no always-on display, so the gate is effectively
+ `_backlightIsOn` alone. `BKSAccelerometer` (BackBoardServices) stops
+ delivering device-orientation notifications to SpringBoard while this is
+ false.
+
+- `setupDefaultPipelineForArbiter:` @ `0x224448664` — the seed and its order:
+
+ ```
+ [self->_accelerometer setDelegate:self]
+ ...
+ [self _updateOrientationEventsEnabledState] // _backlightIsOn is still its default NO here
+ ...
+ self->_backlightIsOn = [[SBBacklightController sharedInstanceIfExists] screenIsOn] // seeded, NOT followed by a recompute
+ [backlightController addObserver:self]
+ ```
+
+ The enable state is computed **before** the seed is written and is never
+ recomputed after it. The only later path that recomputes it is the backlight
+ observer callback.
+
+- `backlightController:willAnimateBacklightToFactor:source:` @ `0x224108904`
+
+ ```
+ log "[EmbeddedPipeline] Backlight is animating with source: %@ to factor: %.1f"
+ newOn = (factor != 0)
+ oldOn = [self _isBacklightOn]
+ self->_backlightIsOn = newOn
+ [self _updateOrientationEventsEnabledState] // every animation
+ if (newOn != oldOn) [self _updateOrientationInputsDeferralAnimated:NO]
+ ```
+
+- `_updateOrientationInputsDeferralAnimated:` @ `0x2240cc40c`
+
+ ```
+ shouldDefer = [self->_systemOrientationLockManager isCurrentlyDeferringOrientationUpdates]
+ || ![self _isBacklightOn]
+ [self->_orientationLockInputsValidator setPrefersDeferringOrientationUpdates:shouldDefer]
+ if (!shouldDefer) [self _noteInputsNeedUpdateAnimated:animated reason:...]
+ ```
+
+ While the backlight is considered off, the arbiter itself is told to prefer
+ deferring orientation updates — an arbiter-level veto, independent of the
+ accelerometer.
+
+- `accelerometer:didChangeDeviceOrientation:` @ `0x22444942c` is the only
+ post-boot path that refreshes device-orientation inputs:
+
+ ```
+ log "[EmbeddedPipeline][Accelerometer] did change device orientation to: %@"
+ [self _evaluateNonFlatOverrideNecessityForCurrentDeviceOrientation:orientation]
+ self->_orientationInputs = [self _orientationInputsForDeviceOrientation:orientation]
+ [self _updateInputs]
+ [self _noteInputsNeedUpdateAnimated:[self _isBacklightOn] reason:"Device orientation change"]
+ ```
+
+- `SBDeviceOrientationUpdateManager.deviceOrientationUpdateDeferralAssertionWithReason:`
+ @ `0x2240e2f1c` creates an assertion into `_deferralAssertions` and posts a
+ notification that reaches `_systemOrientationLockChanged:` →
+ `_updateOrientationInputsDeferralAnimated:YES`. Live logs show these
+ assertions are only created for `SBLockForScreenFadeOut` and
+ `Coversheet dismissal` (lock/unlock) and are released on completion.
+
+## Behavior evidence
+
+| SpringBoard pid | How it started | State | `Backlight is animating` lines | `[Accelerometer] did change` lines |
+|---|---|---|---|---|
+| 454 | language relaunch | stuck | 2 — only when we locked (0.0) and unlocked (1.0) at 09:38:42–45 | 0, ever |
+| 600 | plain respring | working | 0 in capture (capture began after boot) | 1 — rotation applied normally |
+
+Decisive points:
+
+1. The stuck SpringBoard **never receives a backlight animation during or
+ after its relaunch**. The language transition overlay holds the display on
+ across the entire relaunch, so the new SpringBoard sees no backlight
+ off→on edge in its lifetime. `_backlightIsOn` therefore never turns true by
+ itself: orientation events stay disabled and the arbiter keeps a
+ deferral preference.
+2. pid 454 proves the callbacks themselves work in a stuck instance: lock and
+ unlock delivered `willAnimateBacklightToFactor:` 0.0 and 1.0, which ran
+ `_updateOrientationEventsEnabledState` (re-enable) and
+ `_updateOrientationInputsDeferralAnimated:NO` (deferral preference off).
+ The accelerometer callback still never fired and rotation stayed stuck.
+ Re-enabling is not sufficient — recovery also needs a **device-orientation
+ change** delivered after the re-enable, and nothing in the VM produces one:
+ - no accelerometer exists, so no gravity stream ever changes orientation;
+ - the synthetic-motion providers (`motion.attitude.set`,
+ `motion.gyroscope.set`, see `virtual_attitude.md` / `virtual_gyroscope.md`)
+ feed CoreMotion, a different sink;
+ - AX forced-orientation injection reaches the SpringBoard process but a
+ portrait event while the device orientation is already portrait is a
+ no-change and fires nothing; the heartbeat campaign also ended before
+ the unlock edge in the captured run.
+3. No deferral assertion is leaked: `Deferring device orientation updates for
+ reason:` appears zero times in either stuck boot's log. The arbiter veto
+ comes solely from `_backlightIsOn == NO`. The original leaked-assertion
+ hypothesis is disproven for this state.
+
+## Why real hardware never sticks
+
+A real device relaunch blanks the panel, so the new SpringBoard receives a
+genuine backlight off→on animation that flips `_backlightIsOn` and re-enables
+orientation events; and gravity continuously produces device-orientation
+changes that immediately re-drive the arbiter even if a window is missed. The
+VM has no real blank across the language overlay and no gravity stream, so a
+one-shot Apple edge condition becomes a permanent wedge.
+
+## Recovery and fix surface
+
+- Workaround (proven): respring. Lock/unlock is *not* reliable: it repairs the
+ gates but cannot synthesize the missing orientation change.
+- Reliable non-respring recovery, if ever wanted: after a lock/unlock edge,
+ inject a device-orientation value **different from the current one** and
+ then the target value through the backboardd device-orientation sink. A
+ same-value injection is a no-change no-op; this is why the portrait-only
+ heartbeat campaign failed.
+- Systemic fix: give the guest a virtual accelerometer/gravity HID service in
+ `backboardd` alongside the existing gyro provider (the
+ `libvphonegyro.m`/SystemHook pattern), so device orientation self-drives the
+ way real hardware does. It must feed the backboardd device-orientation
+ sink — CoreMotion providers do not touch this path.
+- The web console can also auto-respring on `unavailable: The device did not
+ apply the requested rotation`, but with the HID fix the state should not
+ occur in the first place.
+
+## Virtual gravity provider implementation (2026-10-20)
+
+The independent Guest System patch `system-backboardd-cfw-accelerometer`
+installs `/usr/lib/libvphoneaccelerometer.dylib`, selected by standard and
+experimental on iOS 18+, blocked by both TV presets. Disabling it removes the
+library. SystemHook loads it into backboardd and SpringBoard, without a
+bootstrap or tweak loader; environment updates replace an installed copy and
+request a reboot without restarting backboardd.
+
+The service advertises built-in accelerometer usage page `0xff00`, usage `3`.
+This match is observed in the standalone backboardd artifact's
+`-[BKOrientationManager _initWithDeviceOrientationManager:]` at `0x10009aaf8`:
+`initWithUsagePage:usage:builtIn:dataProvider:(0xff00, 3, YES, ...)`.
+Artifact SHA-256:
+`050bc2ea69fd76a89ce3c5fa8f3477726a1177c50152d3ba8fd570f0f03f45af`.
+This older standalone artifact establishes the match, not full version parity
+with the 23G90 shared cache; guest acceptance must establish that separately.
+REA/Ghidra output is `/private/tmp/vphone-orientation-bb-init.json`.
+
+The implementation uses Apple's `HIDEvent` accelerometer factory, sequence
+accessor, and `HIDVirtualEventService` lifecycle. Its samples are accelerometer
+events (type `13`), not quaternion/tilt events or app CoreMotion callbacks.
+Gravity in g for interface rotations 0/90/180/270 is respectively
+`(0,-1,0)`, `(-1,0,0)`, `(0,1,0)`, `(1,0,0)`. The HID report interval controls
+streaming; zero unsubscribes. Enumeration and configuration changes also emit
+one sample. Status is refreshed every two seconds only while streaming, and
+at state transitions or native orientation delivery.
+Service resets cancel before re-registration, and stale delegate callbacks
+cannot change the replacement service's state.
+
+### Raw HID alone was insufficient
+
+The first clone run (`2.10.1-local.1215039e`) registered the accelerometer
+successfully but never acquired a report interval: `report_interval_us=0`,
+`dispatched=0`, no dispatch failures. English → Simplified Chinese relaunched
+SpringBoard to pid 490, after which `display.rotation {orientation:90}` still
+returned `unavailable`. This is a direct counterexample to the original
+proposal that the raw service alone would fix the wedge on this board.
+
+The final implementation includes the missing classification-to-sink stage.
+After the built-in service matches, it captures the native
+`BKOrientationManager` and its runtime-resolved `_queue`. It classifies the
+actual HID sample's stationary gravity with a flat/ambiguous dead band and
+posts `_queue_postUpdatedRawAccelerometerDeviceOrientation:` on that queue.
+Only changed classifications are posted. All selectors and ivars are resolved
+from runtime metadata; no instruction or per-version address is patched.
+
+This sink's BKS orientation values are **1/4/2/3** for 0/90/180/270 degrees;
+they are not UIDevice's device-landscape numbering. The first bridge build
+used the latter, and gravity-only readback exposed swapped landscapes even
+though AX requests temporarily masked the error. The final bridge and tests
+use the measured BKS ordering.
+
+SpringBoard loads only the other half of this library: after the original
+`setupDefaultPipelineForArbiter:` returns, the hook samples the real
+`SBBacklightController.screenIsOn`, seeds `_backlightIsOn` and recomputes both
+orientation-event delivery and input deferral. A genuinely off screen remains
+off/deferred; rotation-lock policy remains in the native pipeline. This repairs
+the ordering defect without permanently forcing orientation events on.
+
+`display.rotation` publishes the matching physical pose before its existing
+AX orientation request whenever the HID provider is alive and enumerated.
+Mobile preferences retain the pose across a SpringBoard or backboardd restart;
+invalid or absent preferences default to stationary portrait. The read form
+adds `accelerometer` with the configuration and provider status. Its original
+SpringBoard interface-orientation readback still decides request success.
+Nested `orientation_sink` reports native readiness, the last BKS orientation
+and delivery count separately from HID enumeration/dispatch. The outer
+`device_orientation` remains UIDevice's value in vphoned, which does not
+subscribe to device notifications; it is not the bridge's readback.
+
+### Verification boundary
+
+`make -C VPhoneGuestComponents test-accelerometer` passed: malformed persisted
+values, aliases and gravity axes, real host HID event construction, monotonic
+timestamps/sequence, report interval bounds/unsubscribe, stale callbacks and
+idempotent termination. Additional native-shaped peer tests cover queue
+confinement, classification, deduplication, flat/ambiguous rejection, and the
+SpringBoard setup ordering bug with both on/off backlights. Guest arm64e
+cross-compilation, injection-environment tests, all 21 patch catalogue tests
+and the full `VPhone` bundle build passed.
+
+The clone is `gyro-regress`, made from stopped `ota-canary26` with
+`--new-identity`; existing running guests were not stopped.
+
+On `2.10.1-local.e26e2935`, Simplified Chinese → English rebuilt SpringBoard
+to pid 441. All four `display.rotation` directions succeeded without a
+lock/unlock or respring recovery. More decisively, changing only the mobile
+preference `VPhoneAccelerometerOrientation` and posting
+`com.vphone.motion.accelerometer.changed` rotated the interface without any
+AX request. SpringBoard logged at `2026-10-20T15:24:08Z`:
+`[EmbeddedPipeline][Accelerometer] did change device orientation to: Lr`.
+This run established the live sink and revealed the landscape enumeration
+correction described above. Final calibrated-build acceptance follows below.
+
+### Final calibrated-build acceptance
+
+Verified on `gyro-regress`, iPad16,1 / iPadOS 26.6.2 (23G90), cloudOS 26.4
+(23E5207q), bound to `2.10.1-local.a8c22dce`. The user's default bundle and
+existing guests were preserved. The clone remains available for inspection.
+
+| Check | Observed result |
+| --- | --- |
+| Gravity only; no `display.rotation` / AX request | 90 → 90, 270 → 270, 180 → 180, 0 → 0 |
+| Rotation lock at portrait, then gravity 90 | Interface stayed 0 while locked; followed 90 after unlock |
+| English → Simplified Chinese; physical pose remains 90 | New SpringBoard pid 494 returned 90 before a new AX request; same-value `display.rotation {orientation:90}` then succeeded |
+| Remaining gravity-only directions after language relaunch | 270, 180 and 0 each read back correctly |
+| Final provider state | backboardd pid 56, enumerated, 13 HID dispatches, 11 native sink deliveries, zero failures, no errors |
+
+No lock/unlock or respring recovery was performed after the final language
+transition. The first read four seconds into that transition was null because
+SpringBoard was not ready yet, and an immediate rotation request failed;
+once pid 494 finished starting, interface readback was already 90. This fix
+does not make orientation RPCs usable while SpringBoard is still restarting.
+
+At `2026-10-20T15:44:11Z`, the new SpringBoard logged
+`[EmbeddedPipeline][Accelerometer] did change device orientation to: Ll`
+during the final gravity-only run. Capture:
+`/private/tmp/vphone-orientation-final-gravity-springboard.json`.
+The earlier gravity-only callback capture is
+`/private/tmp/vphone-orientation-hid-only-springboard.json`.
+
+Final guest resource SHA-256:
+
+| Resource | SHA-256 |
+| --- | --- |
+| `libvphoneaccelerometer.dylib` | `8ee426c72b294a97f0021da39a2b08c770c90c5814e09a9ca756453af0fa16c9` |
+| `SystemHook-vphone.dylib` | `86f48ae50e6a258f1b05444929f2c44cb33452fe9bfe7f8a27e039a61b1cce8b` |
+
+The two hashes were also read back through the guest's `environment.status`.
+Other iOS versions have not been guest-tested in this change; missing native
+classes/selectors leave the affected bridge inactive and report that state.
+
+Gravity-only reproduction (substitute the clone's name when different):
+
+```sh
+vphone-launchpad-cli guest rpc gyro-regress settings.set \
+ '{"domain":"com.apple.backboardd","key":"VPhoneAccelerometerOrientation","type":"int","value":90}'
+vphone-launchpad-cli guest rpc gyro-regress notify.post \
+ '{"name":"com.vphone.motion.accelerometer.changed"}'
+# Read after the native orientation animation settles.
+vphone-launchpad-cli guest rpc gyro-regress display.orientation
+vphone-launchpad-cli guest rpc gyro-regress display.rotation
+```
+
+Continuous samples with an unchanged pose are not themselves orientation
+changes. Nor can an accelerometer alone release an independently disabled
+SpringBoard backlight/deferral gate. Do not describe HID enumeration or
+dispatch as proof that the language-change wedge is fixed: acceptance needs
+the actual language transition, orientation callback and successful interface
+readback, including a request following the transition without lock/unlock.
+
+## Residual unknowns
+
+- `BKSAccelerometer` internals (`setOrientationEventsEnabled:`,
+ `_orientationDidChange`, re-registration semantics after re-enable): the
+ standalone BackBoardServices image OOMs Ghidra 12.1.4 (the Mach-O loader
+ resolves its dependency libraries into the host macOS dyld cache and the
+ slide-fixup map exceeds the heap even at 16 GB). The SpringBoard-side
+ behavior is fully covered without it.
+- Whether `screenIsOn` returned false at the stuck boot's seed (both orders —
+ seed false, or seed true without a recompute — terminate in the same state;
+ distinguishing them needs a runtime ivar read).
+- The exact code site that emits `The device did not apply the requested
+ rotation` (consistent with arbiter refusal; not chased).
+
+## Artifacts
+
+- Cache extraction and decompilations:
+ `/private/tmp/claude-501/.../scratchpad/rea/` (`SpringBoard`,
+ `BackBoardServices`, `sb_*.json`, address table in `pm_re.txt`/`mgr_re.txt`).
+- Log captures: same scratchpad `lang_sb.json`, `lang2_sb.json`, `ok_sb.json`,
+ `reset_sb.json` (SpringBoard) and `*_bb.json` (backboardd).
+- REA CLI recipe used here: `JAVA_HOME=<openjdk@21>
+ GHIDRA_INSTALL_DIR=/opt/homebrew/opt/ghidra/libexec npx [email protected]
+ function <image> <cache-vm-address> --provider ghidra --format json`.
+ Procedure names from `ipsw class-dump <DSC> <image> --class <Cls> --re -V`.
diff --git a/Research/README.md b/Research/README.md
index c26c8075..8aa9c28f 100644
--- a/Research/README.md
+++ b/Research/README.md
@@ -15,6 +15,7 @@ This directory keeps the evidence behind firmware patches, restore and the self-
| Subject | Notes |
| --- | --- |
+| Guest orientation | [SpringBoard language-change wedge and virtual gravity](Guest/springboard_orientation_stuck.md) |
| Firmware and boot chain | [Manifest and origins](Firmware/firmware_manifest_and_origins.md), [iBoot patches](Firmware/iboot_patches.md), [TXM full chain](Firmware/txm_fullchain_analysis.md), [TXM JB patches](Firmware/txm_jb_patches.md), [selector 24](Firmware/txm_selector24_analysis.md), [variant differences](Firmware/txm_variant_diff.md) |
| Kernel | [CFW overview](Kernel/kernel_jb_patch_notes.md), [patcher verification](Kernel/kernel_patcher_verification.md), [FairPlay kexts](Kernel/kernel_fairplay_kexts.md), [base validation 1–5](Kernel/kernel_patch_base_first5_validation.md), [11–15](Kernel/kernel_patch_base_11_15_validation.md), [16–20](Kernel/kernel_patch_base_16_20_validation.md), [sandbox hooks](Kernel/kernel_patch_sandbox_hooks_17_26_validation.md), [individual patch notes](KernelCustomFirmwarePatches/README.md) |
| Other patches and captures | [Launchd jetsam](Patches/cfw_patch_launchd_jetsam.md), [user-mode hypervisor references](Patches/hv_vmm_present_usermode_xrefs.md), [reference capture](Patches/patch_reference_capture.md) |
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index 9a6791da..2ae74e54 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -393,6 +393,19 @@ request carries `"force": true`.
| Profile UDID | `udid.get`, `udid.set {udid}`, `udid.clear` — each returns `{udid, path}`, the UDID the guest gives its profile checks and the host (null: the guest's own) and the settings file it came from; `set` and `clear` also return `restarted_pids`, `usb_serial` and `usb_reenumerated` (see below) |
| Setup Assistant | `setup.status` (`{pending, running, pid, setup_done, setup_version, current_version, data_migration_done}`), `setup.skip` **force** (sets `SetupDone`, `SetupFinishedAllSteps` and `SetupVersion` in `com.apple.purplebuddy`, restarts SpringBoard, returns the status plus `respring`; while the first boot's data migration is still running it does not restart SpringBoard, which reads the keys when migration ends, and `respring` is `{restarted: false, reason: "data_migration_pending"}`; a restart FrontBoard ignored is refused with `reason: busy`, `retryable: true`, the keys already written); `setup.settle {timeout_s?, poll_s?, stable_polls?}` (read-only wait for first-boot work, see below); `/v1/health` carries `setup_pending` — see `Research/Guest/setup_assistant_skip.md` |
+`display.rotation` also reads `accelerometer`: its persisted `degrees`,
+`provider_running`, and the backboardd HID provider's status (enumeration,
+service ID, pid, report interval, dispatch/failure counts and last error).
+`orientation_sink` separately reports the native backboardd bridge's readiness,
+last device orientation and delivery count. This is distinct from raw HID
+dispatch, which by itself did not drive orientation on the research board.
+When the provider is running, setting rotation first publishes a stationary
+gravity pose matching the requested orientation. The existing SpringBoard
+request and interface-orientation readback still decide success; a running HID
+provider is not an acknowledgement that SpringBoard rotated. The selected
+`system-backboardd-cfw-accelerometer` patch installs this provider; older or
+disabled guests retain their existing rotation path.
+
`display.auto_lock` reads Settings' Auto-Lock (`maxInactivity` in profiled's
`EffectiveUserSettings.plist`) and SpringBoard's `SBMinimumLockscreenIdleTime`.
SpringBoard honors Auto-Lock only while unlocked; on the Lock Screen it turns
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Device.swift b/VPhoneDaemon/Daemon/GuestAPI+Device.swift
index e12b9814..77d82bed 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Device.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Device.swift
@@ -6,6 +6,8 @@ import VphonedNative
// MARK: - Device, Display, Audio, Network
extension GuestAPI {
+ private static let rotationLock = NSLock()
+
static func executeDevice(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
switch method {
case "device.info":
@@ -69,10 +71,22 @@ extension GuestAPI {
}
return brightnessState()
case "display.rotation":
+ rotationLock.lock()
+ defer { rotationLock.unlock() }
if let orientation = optionalString(params, "orientation") {
+ // Preserve the physical pose across SpringBoard relaunches.
+ // CoreMotion's app pose provider cannot feed this HID sink.
+ let accelerometer = vp_accelerometer_get()
+ if accelerometer["provider_running"] as? Bool == true {
+ guard vp_accelerometer_set_orientation(orientation) else {
+ throw GuestAPIError.operationFailed("Could not publish the accelerometer orientation")
+ }
+ }
return try setRotation(orientation)
}
- return rotationInfo()
+ var rotation = rotationInfo()
+ rotation["accelerometer"] = vp_accelerometer_get()
+ return rotation
case "display.orientation":
return interfaceOrientation()
case "display.rotation_lock":
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
index 4f180c76..0a2352cc 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
@@ -22,6 +22,7 @@ extension GuestAPI {
"libprefsfix.dylib",
"libsigninfix.dylib",
"libvphonegyro.dylib",
+ "libvphoneaccelerometer.dylib",
"libvphoneattitude.dylib",
]
static let environmentStaging = "/var/root/Library/Caches/vphone-environment"
@@ -59,7 +60,7 @@ extension GuestAPI {
guard environmentLibraries.contains(name) else {
throw GuestAPIError.invalidRequest("\(name) is not part of the vphone environment")
}
- if ["libvphonegyro.dylib", "libvphoneattitude.dylib"].contains(name), !FileManager.default.fileExists(atPath: "/usr/lib/" + name) {
+ if ["libvphonegyro.dylib", "libvphoneaccelerometer.dylib", "libvphoneattitude.dylib"].contains(name), !FileManager.default.fileExists(atPath: "/usr/lib/" + name) {
throw GuestAPIError.invalidRequest("Enable the motion sensor patch with cfw install or cfw update-environment first")
}
let staged = URL(fileURLWithPath: environmentStaging + "/" + name)
@@ -104,7 +105,8 @@ extension GuestAPI {
// backboardd owns the UI's HID connection. Do not restart it here:
// a new gyro hook (or SystemHook which loads it) needs a reboot.
"reboot_required": !rootReadOnly || names.contains("launchdhook-vphone.dylib")
- || names.contains("libvphonegyro.dylib") || names.contains("SystemHook-vphone.dylib"),
+ || names.contains("libvphonegyro.dylib") || names.contains("libvphoneaccelerometer.dylib")
+ || names.contains("SystemHook-vphone.dylib"),
"root_read_only": rootReadOnly,
]
}
diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.h
index 07a07561..937605a8 100644
--- a/VPhoneDaemon/Native/Include/VphonedNative.h
+++ b/VPhoneDaemon/Native/Include/VphonedNative.h
@@ -99,6 +99,9 @@ char *vp_ls_register_system_app(const char *app_path, const char *container_path
/// The configured radians/second and the injected HID provider's heartbeat.
NSDictionary *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);
NSDictionary *vp_attitude_get(void);
BOOL vp_attitude_set(double roll, double pitch, double yaw, bool enabled);
diff --git a/VPhoneDaemon/Native/vphoned_accelerometer.m b/VPhoneDaemon/Native/vphoned_accelerometer.m
new file mode 100644
index 00000000..e48c0476
--- /dev/null
+++ b/VPhoneDaemon/Native/vphoned_accelerometer.m
@@ -0,0 +1,41 @@
+#import "Include/VphonedNative.h"
+#import "../../VPhoneGuestComponents/Accelerometer/VPhoneAccelerometerState.h"
+#include <errno.h>
+#include <notify.h>
+#include <signal.h>
+
+NSDictionary *vp_accelerometer_get(void) {
+ CFPreferencesSynchronize(CFSTR(VP_ACCEL_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+ id value = CFBridgingRelease(CFPreferencesCopyValue(CFSTR(VP_ACCEL_CONFIGURATION),
+ CFSTR(VP_ACCEL_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost));
+ int degrees;
+ VPhoneAccelerometerDecode(value, &degrees);
+ id status = CFBridgingRelease(CFPreferencesCopyValue(CFSTR(VP_ACCEL_STATUS),
+ CFSTR(VP_ACCEL_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 @{@"degrees": @(degrees), @"provider_running": @(running), @"provider": status};
+}
+
+BOOL vp_accelerometer_set_orientation(NSString *spec) {
+ int degrees = VPhoneAccelerometerDegrees(spec);
+ if (degrees < 0)
+ return NO;
+ CFPreferencesSetValue(CFSTR(VP_ACCEL_CONFIGURATION), (__bridge CFNumberRef)@(degrees),
+ CFSTR(VP_ACCEL_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+ if (!CFPreferencesSynchronize(CFSTR(VP_ACCEL_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost))
+ return NO;
+ return notify_post(VP_ACCEL_NOTIFICATION) == NOTIFY_STATUS_OK;
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index accf2f3f..42c9aaee 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -22,6 +22,7 @@ public enum FirmwareGuestSystemPatchSet {
public static let installCoordinationPersona = "system-installcoordination_proxy-cfw-persona_lookup"
public static let installCoordinationPersonaMarker = "/usr/lib/vphone-installcoordination-persona-lookup"
public static let gyroscope = "system-backboardd-cfw-gyroscope"
+ public static let accelerometer = "system-backboardd-cfw-accelerometer"
public static let attitude = "system-apps-cfw-attitude"
public static let arm64eX1DyldBootstrap = "system-dyld-boot-arm64e_x1_bootstrap"
public static let arm64eX1CacheBootstrap = "dyld-boot-arm64e_x1_bootstrap"
@@ -325,6 +326,14 @@ public enum FirmwareGuestSystemPatchSet {
// MARK: Motion
+ VPhonePatchDeclaration(
+ identifier: accelerometer,
+ title: "Virtual gravity accelerometer",
+ summary: "Installs libvphoneaccelerometer.dylib. Publishes a built-in HID gravity sensor and bridges its classified pose into backboardd's native device-orientation sink. In SpringBoard, recomputes orientation delivery and deferral after the real backlight seed. Follows display.rotation across relaunches; removing the library disables both after a reboot.",
+ target: .guestFile(path: "/usr/lib/libvphoneaccelerometer.dylib"),
+ applicability: VPhonePatchApplicability(iOSBase: .atLeast(major: 18, minor: 0)),
+ ),
+
VPhonePatchDeclaration(
identifier: gyroscope,
title: "Virtual 3D gyroscope",
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index c30622c8..fbf6d95e 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -233,6 +233,7 @@ public enum FirmwarePatchSetCatalog {
RestoreRamDiskSealPatcher.patchIdentifier,
"system-apps-cfw-attitude",
"system-backboardd-cfw-gyroscope",
+ "system-backboardd-cfw-accelerometer",
"system-campo-cfw-entitlements",
"system-debugserver-cfw-install",
FirmwareGuestSystemPatchSet.arm64eX1DyldBootstrap,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
index fd9b7168..33d94a98 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
@@ -17,7 +17,7 @@ import VPhonePatchKit
@Suite("Bundled patch set catalogue")
struct FirmwarePatchSetCatalogTests {
- @Test(arguments: [FirmwareGuestSystemPatchSet.gyroscope, FirmwareGuestSystemPatchSet.attitude])
+ @Test(arguments: [FirmwareGuestSystemPatchSet.gyroscope, FirmwareGuestSystemPatchSet.accelerometer, FirmwareGuestSystemPatchSet.attitude])
func `Motion sensors follow selection and their deployment target`(identifier: String) throws {
for base in ["18.6.2", "26.4", "27.0.1"] {
let plan = try VPhonePatchPlan.resolve(
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index 0ba13a5c..ba10510a 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -1089,6 +1089,7 @@ struct VPhoneCustomFirmwareInstaller {
guard let plan else {
return !FirmwareGuestSystemPatchSet.settingsRowPatches.contains(identifier)
&& identifier != FirmwareGuestSystemPatchSet.gyroscope
+ && identifier != FirmwareGuestSystemPatchSet.accelerometer
&& identifier != FirmwareGuestSystemPatchSet.attitude
}
guard plan.isEnabled(identifier) else {
@@ -1253,6 +1254,7 @@ struct VPhoneCustomFirmwareInstaller {
}
for (identifier, library) in [
(FirmwareGuestSystemPatchSet.gyroscope, "libvphonegyro.dylib"),
+ (FirmwareGuestSystemPatchSet.accelerometer, "libvphoneaccelerometer.dylib"),
(FirmwareGuestSystemPatchSet.attitude, "libvphoneattitude.dylib"),
] {
isolate([identifier]) {
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
index 83071d9e..6b110205 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
@@ -87,6 +87,7 @@ daemon_sdk="$(/usr/bin/otool -l "$guest/vphoned" | /usr/bin/awk '/LC_BUILD_VERSI
/bin/cp "$guest_products/prefsfix/libprefsfix.dylib" "$guest/libprefsfix.dylib"
/bin/cp "$guest_products/signinfix/libsigninfix.dylib" "$guest/libsigninfix.dylib"
/bin/cp "$guest_products/gyroscope/libvphonegyro.dylib" "$guest/libvphonegyro.dylib"
+/bin/cp "$guest_products/accelerometer/libvphoneaccelerometer.dylib" "$guest/libvphoneaccelerometer.dylib"
/bin/cp "$guest_products/attitude/libvphoneattitude.dylib" "$guest/libvphoneattitude.dylib"
/bin/cp "$guest_products/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib" \
"$guest/libAppleParavirtCompilerPluginIOGPUFamily.dylib"
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
index 4fd9a509..7bef958e 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
@@ -122,7 +122,7 @@ fi
for name in vphoned vphoned-tvos launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \
libvcamcaptured.dylib libmisfix.dylib libhapticsfix.dylib libbatteryhealthfix.dylib libdevicehubfix.dylib libdevicename.dylib \
- libprefsfix.dylib libsigninfix.dylib libvphonegyro.dylib libvphoneattitude.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
+ libprefsfix.dylib libsigninfix.dylib libvphonegyro.dylib libvphoneaccelerometer.dylib libvphoneattitude.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
require_signed_macho "$guest/$name"
done
for name in vphoned.plist libcamfix.plist libvcamcaptured.plist libmisfix.plist; do
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
index ff580466..d5e25429 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
@@ -95,6 +95,7 @@
<string>restoreramdisk-boot-apfs_sha3_hash</string>
<string>system-apps-cfw-attitude</string>
<string>system-backboardd-cfw-gyroscope</string>
+ <string>system-backboardd-cfw-accelerometer</string>
<string>system-campo-cfw-entitlements</string>
<string>system-debugserver-cfw-install</string>
<string>system-dyld-boot-arm64e_x1_bootstrap</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
index 1c09901d..00fbb819 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
@@ -100,6 +100,7 @@
<string>restoreramdisk-boot-apfs_sha3_hash</string>
<string>system-apps-cfw-attitude</string>
<string>system-backboardd-cfw-gyroscope</string>
+ <string>system-backboardd-cfw-accelerometer</string>
<string>system-campo-cfw-entitlements</string>
<string>system-debugserver-cfw-install</string>
<string>system-dyld-boot-arm64e_x1_bootstrap</string>
diff --git a/VPhoneGuestComponents/Accelerometer/VPhoneAccelerometerHID.h b/VPhoneGuestComponents/Accelerometer/VPhoneAccelerometerHID.h
new file mode 100644
index 00000000..f61e2744
--- /dev/null
+++ b/VPhoneGuestComponents/Accelerometer/VPhoneAccelerometerHID.h
@@ -0,0 +1,24 @@
+#pragma once
+#import <Foundation/Foundation.h>
+
+// Apple's HIDEventAccessors.h and HIDEventAccessors_Internal.h. Runtime lookup
+// keeps the guest library independent of private SDK stubs.
+@protocol VPhoneAccelerometerHIDEvent <NSObject>
++ (id)accelerometerEvent:(uint64_t)timestamp x:(double)x y:(double)y z:(double)z options:(uint32_t)options;
+- (void)setAccelerometerSequence:(uint32_t)sequence;
+@property (readonly) uint32_t accelerometerSequence;
+@property (readonly) double accelerometerX;
+@property (readonly) double accelerometerY;
+@property (readonly) double accelerometerZ;
+@property (readonly) uint64_t timestamp;
+@end
+
+@protocol VPhoneAccelerometerHIDService <NSObject>
+@property (weak) id delegate;
+@property (readonly) uint64_t serviceID;
+- (void)setDispatchQueue:(dispatch_queue_t)queue;
+- (void)setCancelHandler:(dispatch_block_t)handler;
+- (void)activate;
+- (void)cancel;
+- (BOOL)dispatchEvent:(id)event;
+@end
diff --git a/VPhoneGuestComponents/Accelerometer/VPhoneAccelerometerState.h b/VPhoneGuestComponents/Accelerometer/VPhoneAccelerometerState.h
new file mode 100644
index 00000000..98f42a19
--- /dev/null
+++ b/VPhoneGuestComponents/Accelerometer/VPhoneAccelerometerState.h
@@ -0,0 +1,53 @@
+#pragma once
+#import <Foundation/Foundation.h>
+#include <math.h>
+
+#define VP_ACCEL_DOMAIN "com.apple.backboardd"
+#define VP_ACCEL_CONFIGURATION "VPhoneAccelerometerOrientation"
+#define VP_ACCEL_STATUS "VPhoneAccelerometerStatus"
+#define VP_ACCEL_NOTIFICATION "com.vphone.motion.accelerometer.changed"
+
+typedef struct { double x, y, z; } VPhoneGravity;
+
+// A stationary device in portrait by default. Units are g, as in IOHID's
+// accelerometer events. These are device axes, not interface orientation:
+// interface landscape-right (90 degrees) means device landscape-left.
+static inline BOOL VPhoneAccelerometerDecode(id value, int *degrees) {
+ *degrees = 0;
+ if (![value isKindOfClass:NSNumber.class] ||
+ CFGetTypeID((__bridge CFTypeRef)value) == CFBooleanGetTypeID())
+ return NO;
+ double number = [value doubleValue];
+ if (!isfinite(number) || (number != 0 && number != 90 && number != 180 && number != 270))
+ return NO;
+ *degrees = (int)number;
+ return YES;
+}
+
+static inline VPhoneGravity VPhoneAccelerometerGravity(int degrees) {
+ switch (degrees) {
+ case 90: return (VPhoneGravity){-1, 0, 0};
+ case 180: return (VPhoneGravity){0, 1, 0};
+ case 270: return (VPhoneGravity){1, 0, 0};
+ default: return (VPhoneGravity){0, -1, 0};
+ }
+}
+
+static inline int VPhoneAccelerometerDegrees(NSString *spec) {
+ NSDictionary *values = @{
+ @"0": @0, @"portrait": @0,
+ @"90": @90, @"landscape-left": @90, @"left": @90,
+ @"180": @180, @"upside-down": @180, @"portrait-upside-down": @180,
+ @"270": @270, @"landscape-right": @270, @"right": @270,
+ };
+ NSNumber *value = values[spec.lowercaseString];
+ return value ? value.intValue : -1;
+}
+
+static inline uint64_t VPhoneAccelerometerInterval(id value) {
+ if (![value isKindOfClass:NSNumber.class] ||
+ CFGetTypeID((__bridge CFTypeRef)value) == CFBooleanGetTypeID())
+ return 0;
+ double interval = [value doubleValue];
+ return isfinite(interval) && interval > 0 ? (uint64_t)fmin(1000000, fmax(5000, interval)) : 0;
+}
diff --git a/VPhoneGuestComponents/Accelerometer/VPhoneOrientationSink.h b/VPhoneGuestComponents/Accelerometer/VPhoneOrientationSink.h
new file mode 100644
index 00000000..8c41e9e7
--- /dev/null
+++ b/VPhoneGuestComponents/Accelerometer/VPhoneOrientationSink.h
@@ -0,0 +1,10 @@
+#pragma once
+#import <Foundation/Foundation.h>
+#import "VPhoneAccelerometerHID.h"
+
+// The virtual board has no motion coprocessor to classify gravity for
+// CMDeviceOrientationManager. Deliver the HID sample to backboardd's own sink.
+void VPhoneOrientationSinkInstall(dispatch_queue_t statusQueue, dispatch_block_t statusChanged);
+void VPhoneOrientationSinkPublish(id<VPhoneAccelerometerHIDEvent> event);
+NSDictionary *VPhoneOrientationSinkStatus(void);
+void VPhoneOrientationGateInstall(void);
diff --git a/VPhoneGuestComponents/Accelerometer/VPhoneOrientationSink.m b/VPhoneGuestComponents/Accelerometer/VPhoneOrientationSink.m
new file mode 100644
index 00000000..8a15108b
--- /dev/null
+++ b/VPhoneGuestComponents/Accelerometer/VPhoneOrientationSink.m
@@ -0,0 +1,150 @@
+#import "VPhoneOrientationSink.h"
+#include <math.h>
+#include <objc/message.h>
+#include <objc/runtime.h>
+
+@interface VPhoneDeviceOrientationSink : NSObject
+@property (nonatomic, weak) id manager;
+@property (nonatomic, strong) dispatch_queue_t queue;
+@property (nonatomic, strong) dispatch_queue_t statusQueue;
+@property (nonatomic, copy) dispatch_block_t statusChanged;
+@property (nonatomic) NSInteger orientation;
+@property (nonatomic) NSInteger deliveredOrientation;
+@property (nonatomic) uint64_t deliveries;
+@property (nonatomic, copy) NSString *error;
+@end
+@implementation VPhoneDeviceOrientationSink
+@end
+
+static VPhoneDeviceOrientationSink *vpOrientationSink;
+static void (*vpOriginalServicesMatched)(id, SEL, id, id);
+static void (*vpOriginalSetupPipeline)(id, SEL, id);
+
+static void vpOrientationDeliver(void) {
+ VPhoneDeviceOrientationSink *sink = vpOrientationSink;
+ id manager;
+ dispatch_queue_t queue;
+ @synchronized (sink) { manager = sink.manager; queue = sink.queue; }
+ if (!manager || !queue)
+ return;
+ dispatch_async(queue, ^{
+ NSInteger orientation;
+ @synchronized (sink) {
+ orientation = sink.orientation;
+ if (manager != sink.manager || orientation == sink.deliveredOrientation)
+ return;
+ }
+ ((void (*)(id, SEL, NSInteger))objc_msgSend)(manager,
+ sel_registerName("_queue_postUpdatedRawAccelerometerDeviceOrientation:"), orientation);
+ dispatch_queue_t statusQueue;
+ dispatch_block_t changedHandler;
+ @synchronized (sink) {
+ sink.deliveredOrientation = orientation;
+ sink.deliveries++;
+ statusQueue = sink.statusQueue;
+ changedHandler = sink.statusChanged;
+ }
+ if (statusQueue && changedHandler)
+ dispatch_async(statusQueue, changedHandler);
+ });
+}
+
+static void vpOrientationServicesMatched(id manager, SEL selector, id matcher, id services) {
+ vpOriginalServicesMatched(manager, selector, matcher, services);
+ Ivar queueIvar = class_getInstanceVariable(object_getClass(manager), "_queue");
+ dispatch_queue_t queue = queueIvar ? object_getIvar(manager, queueIvar) : nil;
+ if (!queue)
+ return;
+ @synchronized (vpOrientationSink) {
+ if (manager != vpOrientationSink.manager)
+ vpOrientationSink.deliveredOrientation = 0;
+ vpOrientationSink.manager = manager;
+ vpOrientationSink.queue = queue;
+ vpOrientationSink.error = nil;
+ }
+ vpOrientationDeliver();
+}
+
+void VPhoneOrientationSinkInstall(dispatch_queue_t statusQueue, dispatch_block_t statusChanged) {
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ vpOrientationSink = [VPhoneDeviceOrientationSink new];
+ vpOrientationSink.orientation = 1;
+ vpOrientationSink.statusQueue = statusQueue;
+ vpOrientationSink.statusChanged = statusChanged;
+ vpOrientationSink.error = @"Waiting for the built-in accelerometer match";
+ Class cls = NSClassFromString(@"BKOrientationManager");
+ Method match = class_getInstanceMethod(cls, sel_registerName("matcher:servicesDidMatch:"));
+ Method post = class_getInstanceMethod(cls,
+ sel_registerName("_queue_postUpdatedRawAccelerometerDeviceOrientation:"));
+ if (!match || !post || !class_getInstanceVariable(cls, "_queue") ||
+ method_getNumberOfArguments(match) != 4 || method_getNumberOfArguments(post) != 3) {
+ vpOrientationSink.error = @"Native backboardd device-orientation sink unavailable";
+ return;
+ }
+ vpOriginalServicesMatched = (void (*)(id, SEL, id, id))method_setImplementation(
+ match, (IMP)vpOrientationServicesMatched);
+ });
+}
+
+void VPhoneOrientationSinkPublish(id<VPhoneAccelerometerHIDEvent> event) {
+ // A dead band excludes flat/ambiguous samples. This BKS sink uses 4 for
+ // the 90-degree interface and 3 for 270, unlike UIDevice's landscape
+ // numbering. Confirmed with gravity-only guest readback (without AX).
+ double x = event.accelerometerX, y = event.accelerometerY, z = event.accelerometerZ;
+ NSInteger orientation = 0;
+ if (fabs(z) < 0.5) {
+ if (fabs(x) > 0.75 && fabs(y) < 0.5)
+ orientation = x < 0 ? 4 : 3;
+ else if (fabs(y) > 0.75 && fabs(x) < 0.5)
+ orientation = y < 0 ? 1 : 2;
+ }
+ if (!orientation || !vpOrientationSink)
+ return;
+ @synchronized (vpOrientationSink) { vpOrientationSink.orientation = orientation; }
+ vpOrientationDeliver();
+}
+
+NSDictionary *VPhoneOrientationSinkStatus(void) {
+ VPhoneDeviceOrientationSink *sink = vpOrientationSink;
+ if (!sink)
+ return @{@"ready": @NO, @"error": @"Orientation bridge not installed"};
+ @synchronized (sink) {
+ return @{@"ready": @(sink.manager != nil && sink.queue != nil),
+ @"device_orientation": @(sink.deliveredOrientation), @"deliveries": @(sink.deliveries),
+ @"error": sink.error ?: @""};
+ }
+}
+
+// MARK: - SpringBoard's backlight seed
+
+static void vpOrientationSetupPipeline(id manager, SEL selector, id arbiter) {
+ vpOriginalSetupPipeline(manager, selector, arbiter);
+ Class cls = NSClassFromString(@"SBBacklightController");
+ SEL shared = sel_registerName("sharedInstanceIfExists");
+ if (![cls respondsToSelector:shared])
+ return;
+ id controller = ((id (*)(id, SEL))objc_msgSend)(cls, shared);
+ SEL screenIsOn = sel_registerName("screenIsOn");
+ if (![controller respondsToSelector:screenIsOn])
+ return;
+ BOOL on = ((BOOL (*)(id, SEL))objc_msgSend)(controller, screenIsOn);
+ [manager setValue:@(on) forKey:@"_backlightIsOn"];
+ ((void (*)(id, SEL))objc_msgSend)(manager, sel_registerName("_updateOrientationEventsEnabledState"));
+ ((void (*)(id, SEL, BOOL))objc_msgSend)(manager,
+ sel_registerName("_updateOrientationInputsDeferralAnimated:"), NO);
+ NSLog(@"[vphone-accelerometer] Recomputed orientation gates after backlight seed: %d", on);
+}
+
+void VPhoneOrientationGateInstall(void) {
+ Class cls = NSClassFromString(@"SBTraitsEmbeddedDisplayPipelineManager");
+ Method method = class_getInstanceMethod(cls, sel_registerName("setupDefaultPipelineForArbiter:"));
+ if (!method || method_getNumberOfArguments(method) != 3 ||
+ !class_getInstanceVariable(cls, "_backlightIsOn") ||
+ ![cls instancesRespondToSelector:sel_registerName("_updateOrientationEventsEnabledState")] ||
+ ![cls instancesRespondToSelector:sel_registerName("_updateOrientationInputsDeferralAnimated:")]) {
+ NSLog(@"[vphone-accelerometer] SpringBoard orientation gate API unavailable");
+ return;
+ }
+ vpOriginalSetupPipeline = (void (*)(id, SEL, id))method_setImplementation(method, (IMP)vpOrientationSetupPipeline);
+}
diff --git a/VPhoneGuestComponents/Accelerometer/libvphoneaccelerometer.m b/VPhoneGuestComponents/Accelerometer/libvphoneaccelerometer.m
new file mode 100644
index 00000000..d6e4ef90
--- /dev/null
+++ b/VPhoneGuestComponents/Accelerometer/libvphoneaccelerometer.m
@@ -0,0 +1,236 @@
+#import "VPhoneAccelerometerHID.h"
+#import "VPhoneAccelerometerState.h"
+#import "VPhoneOrientationSink.h"
+#include <dlfcn.h>
+#include <mach/mach_time.h>
+#include <notify.h>
+#include <unistd.h>
+
+// MARK: - HID provider in backboardd
+
+@interface VPhoneAccelerometerProvider : NSObject
+@property (nonatomic, strong) dispatch_queue_t queue;
+@property (nonatomic, strong) dispatch_source_t timer;
+@property (nonatomic, strong) dispatch_source_t heartbeat;
+@property (nonatomic, strong) id<VPhoneAccelerometerHIDService> service;
+@property (nonatomic) Class<VPhoneAccelerometerHIDEvent> eventClass;
+@property (nonatomic, strong) NSMutableDictionary *properties;
+@property (nonatomic) int degrees;
+@property (nonatomic) BOOL enumerated;
+@property (nonatomic) BOOL cancelling;
+@property (nonatomic) uint32_t sequence;
+@property (nonatomic) uint64_t interval;
+@property (nonatomic) uint64_t dispatched;
+@property (nonatomic) uint64_t failures;
+@property (nonatomic) int notificationToken;
+@property (nonatomic, copy) NSString *lastError;
+- (void)start;
+- (void)dispatchSample;
+@end
+
+@implementation VPhoneAccelerometerProvider
+
+- (void)publishStatus {
+ NSDictionary *status = @{
+ @"enumerated": @(self.enumerated), @"service_id": @(self.service.serviceID),
+ @"pid": @(getpid()), @"updated_at": @([NSDate date].timeIntervalSince1970),
+ @"report_interval_us": @(self.interval), @"dispatched": @(self.dispatched),
+ @"dispatch_failures": @(self.failures), @"error": self.lastError ?: @"",
+ @"configuration": @{@"degrees": @(self.degrees)},
+ @"orientation_sink": VPhoneOrientationSinkStatus(),
+ };
+ CFPreferencesSetValue(CFSTR(VP_ACCEL_STATUS), (__bridge CFDictionaryRef)status,
+ CFSTR(VP_ACCEL_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+ CFPreferencesSynchronize(CFSTR(VP_ACCEL_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+}
+
+- (void)readConfiguration {
+ CFPreferencesSynchronize(CFSTR(VP_ACCEL_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+ id value = CFBridgingRelease(CFPreferencesCopyValue(CFSTR(VP_ACCEL_CONFIGURATION),
+ CFSTR(VP_ACCEL_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost));
+ int degrees;
+ VPhoneAccelerometerDecode(value, &degrees);
+ self.degrees = degrees;
+ if (self.enumerated)
+ [self dispatchSample];
+ [self publishStatus];
+}
+
+- (void)updateTimer {
+ uint64_t period = self.enumerated && self.interval ? self.interval * NSEC_PER_USEC : 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,
+ // to keep its dispatch counts current. Otherwise it changes only at the
+ // transitions, which publish it themselves, and vphoned judges the
+ // provider by its pid. An unconditional heartbeat had backboardd rewrite
+ // the preferences domain through cfprefsd every two seconds for the
+ // guest's whole life.
+ if (self.heartbeat) {
+ BOOL flowing = period != DISPATCH_TIME_FOREVER;
+ dispatch_source_set_timer(self.heartbeat,
+ flowing ? dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC) : DISPATCH_TIME_FOREVER,
+ 2 * NSEC_PER_SEC, 100 * NSEC_PER_MSEC);
+ }
+}
+
+- (id)sample {
+ VPhoneGravity gravity = VPhoneAccelerometerGravity(self.degrees);
+ id event = [self.eventClass accelerometerEvent:mach_absolute_time()
+ x:gravity.x y:gravity.y z:gravity.z options:0];
+ if (event)
+ [(id<VPhoneAccelerometerHIDEvent>)event setAccelerometerSequence:self.sequence++];
+ return event;
+}
+
+- (void)createService {
+ self.enumerated = NO;
+ self.cancelling = NO;
+ self.interval = 0;
+ self.properties[@"ReportInterval"] = @0;
+ self.service = (id<VPhoneAccelerometerHIDService>)[NSClassFromString(@"HIDVirtualEventService") new];
+ if (!self.service) {
+ self.lastError = @"HIDVirtualEventService creation failed";
+ [self publishStatus];
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), self.queue, ^{ [self createService]; });
+ return;
+ }
+ self.service.delegate = self;
+ [self.service setDispatchQueue:self.queue];
+ __weak VPhoneAccelerometerProvider *weakSelf = self;
+ [self.service setCancelHandler:^{
+ VPhoneAccelerometerProvider *provider = weakSelf;
+ if (!provider)
+ return;
+ provider.service = nil;
+ // A reset invalidates the old service. Cancel completely before
+ // releasing it, then register a new one with the restarted HID server.
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), provider.queue,
+ ^{ [provider createService]; });
+ }];
+ [self.service activate];
+}
+
+- (void)dispatchSample {
+ id event = [self sample];
+ if (event && [self.service dispatchEvent:event]) {
+ self.dispatched++;
+ self.lastError = nil;
+ } else {
+ self.failures++;
+ self.lastError = @"HID event dispatch failed";
+ }
+ if (event)
+ VPhoneOrientationSinkPublish(event);
+}
+
+- (void)start {
+ void *hid = dlopen("/System/Library/PrivateFrameworks/HID.framework/HID", RTLD_NOW | RTLD_LOCAL);
+ self.eventClass = (Class<VPhoneAccelerometerHIDEvent>)NSClassFromString(@"HIDEvent");
+ Class serviceClass = NSClassFromString(@"HIDVirtualEventService");
+ if (!hid || !serviceClass ||
+ ![self.eventClass respondsToSelector:@selector(accelerometerEvent:x:y:z:options:)] ||
+ ![(Class)self.eventClass instancesRespondToSelector:@selector(setAccelerometerSequence:)] ||
+ ![serviceClass instancesRespondToSelector:@selector(dispatchEvent:)]) {
+ self.lastError = @"Required HID virtual-service API unavailable";
+ NSLog(@"[vphone-accelerometer] %@", self.lastError);
+ [self publishStatus];
+ return;
+ }
+ self.properties = [@{
+ @"PrimaryUsagePage": @0xff00, @"PrimaryUsage": @3,
+ @"DeviceUsagePairs": @[@{@"DeviceUsagePage": @0xff00, @"DeviceUsage": @3}],
+ @"Product": @"VPhone Gravity Accelerometer", @"Manufacturer": @"vphone",
+ @"Transport": @"Virtual", @"Built-In": @YES, @"IMULocationID": @0,
+ @"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_ACCEL_NOTIFICATION, &_notificationToken, self.queue,
+ ^(int token) { [self readConfiguration]; });
+ if (status != NOTIFY_STATUS_OK) {
+ self.lastError = @"Accelerometer configuration notification registration failed";
+ [self publishStatus];
+ return;
+ }
+ self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue);
+ dispatch_source_set_event_handler(self.timer, ^{
+ @autoreleasepool {
+ [self dispatchSample];
+ }
+ });
+ self.heartbeat = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue);
+ dispatch_source_set_event_handler(self.heartbeat, ^{ [self publishStatus]; });
+ [self updateTimer];
+ dispatch_resume(self.timer);
+ dispatch_resume(self.heartbeat);
+ [self createService];
+}
+
+// MARK: - HIDVirtualEventServiceDelegate selectors
+
+- (id)propertyForKey:(NSString *)key forService:(id)service {
+ return self.properties[key];
+}
+
+- (BOOL)setProperty:(id)value forKey:(NSString *)key forService:(id)service {
+ if (service != self.service)
+ return NO;
+ if ([key isEqualToString:@"ReportInterval"]) {
+ self.interval = VPhoneAccelerometerInterval(value);
+ self.properties[key] = @(self.interval);
+ [self updateTimer];
+ [self publishStatus];
+ return YES;
+ }
+ if ([key isEqualToString:@"BatchInterval"])
+ return YES; // No FIFO: samples are delivered as they are made.
+ return NO;
+}
+
+- (id)copyEventMatching:(NSDictionary *)matching forService:(id)service {
+ NSNumber *type = matching[@"EventType"];
+ return service == self.service && self.enumerated && (!type || type.unsignedIntValue == 0x0d) ? [self sample] : nil;
+}
+
+- (BOOL)setOutputEvent:(id)event forService:(id)service {
+ return NO;
+}
+
+- (void)notification:(NSInteger)type withProperty:(NSDictionary *)property forService:(id)service {
+ if (service != self.service)
+ return;
+ if (type == 10) { // HIDVirtualServiceNotificationTypeEnumerated
+ self.enumerated = YES;
+ self.lastError = nil;
+ NSLog(@"[vphone-accelerometer] HID service enumerated: %llu", self.service.serviceID);
+ [self dispatchSample];
+ } else if (type == 11 && !self.cancelling) { // Terminated or reset
+ self.enumerated = NO;
+ self.cancelling = YES;
+ self.lastError = @"HID service terminated; waiting to register again";
+ [self.service cancel];
+ }
+ [self updateTimer];
+ [self publishStatus];
+}
+@end
+
+__attribute__((constructor)) static void VPhoneAccelerometerStart(void) {
+ if (strcmp(getprogname(), "SpringBoard") == 0) {
+ VPhoneOrientationGateInstall();
+ return;
+ }
+ // Only backboardd creates the HID service; SpringBoard installs the seed
+ // repair above. Starting asynchronously avoids calling the HID server
+ // while its daemon is still running image constructors.
+ if (strcmp(getprogname(), "backboardd") != 0)
+ return;
+ static VPhoneAccelerometerProvider *provider;
+ provider = [VPhoneAccelerometerProvider new];
+ provider.queue = dispatch_queue_create("com.vphone.motion.accelerometer", DISPATCH_QUEUE_SERIAL);
+ VPhoneOrientationSinkInstall(provider.queue, ^{ [provider publishStatus]; });
+ dispatch_async(provider.queue, ^{ [provider start]; });
+}
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index 6e9a0029..817542a9 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -89,6 +89,9 @@ SIGNINFIX_INCLUDES := $(wildcard SignInFix/*.h)
GYROSCOPE := $(STAGE)/gyroscope/libvphonegyro.dylib
GYROSCOPE_SOURCES := $(call find_sources,Gyroscope)
GYROSCOPE_INPUTS := $(call find_headers,Gyroscope) $(call find_folders,Gyroscope)
+ACCELEROMETER := $(STAGE)/accelerometer/libvphoneaccelerometer.dylib
+ACCELEROMETER_SOURCES := $(call find_sources,Accelerometer)
+ACCELEROMETER_INPUTS := $(call find_headers,Accelerometer) $(call find_folders,Accelerometer)
ATTITUDE := $(STAGE)/attitude/libvphoneattitude.dylib
ATTITUDE_SOURCES := $(call find_sources,Attitude)
ATTITUDE_INPUTS := $(call find_headers,Attitude) $(call find_folders,Attitude) Shared/AttitudeProcess.h
@@ -125,7 +128,7 @@ GPU_DYNAMIC_LOOKUP_SYMS := \
VIRTIOSOUND := $(STAGE)/virtiosound/VPhoneVirtIOSound.driver
VIRTIOSOUND_SOURCES := $(wildcard VirtIOSound/*.m VirtIOSound/*.c)
VIRTIOSOUND_INCLUDES := $(wildcard VirtIOSound/*.h) VirtIOSound/Info.plist VirtIOSound/AudioServerDriver.tbd
-ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(DEVICENAME) $(PREFSFIX) $(SIGNINFIX) $(GYROSCOPE) $(ATTITUDE) $(GPU_PLUGIN) $(VIRTIOSOUND)
+ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(DEVICENAME) $(PREFSFIX) $(SIGNINFIX) $(GYROSCOPE) $(ACCELEROMETER) $(ATTITUDE) $(GPU_PLUGIN) $(VIRTIOSOUND)
PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist \
$(STAGE)/misfix/libmisfix.plist
GPU_PROVENANCE := $(STAGE)/gpu/README.md
@@ -140,7 +143,7 @@ gpu: $(GPU_PLUGIN)
package: all
@rm -f $(ARCHIVE)
- @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix devicename prefsfix signinfix gyroscope attitude gpu virtiosound
+ @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix devicename prefsfix signinfix gyroscope accelerometer attitude gpu virtiosound
@echo "Packaged $(ARCHIVE)"
test-loader-links:
@@ -206,7 +209,7 @@ test-vcam-dataplane:
-framework CoreGraphics
@$(OUT)/VCamDataPlaneTests
-$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/misfix $(STAGE)/hapticsfix $(STAGE)/batteryhealthfix $(STAGE)/devicehubfix $(STAGE)/devicename $(STAGE)/prefsfix $(STAGE)/signinfix $(STAGE)/gyroscope $(STAGE)/attitude $(STAGE)/gpu $(STAGE)/virtiosound:
+$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/misfix $(STAGE)/hapticsfix $(STAGE)/batteryhealthfix $(STAGE)/devicehubfix $(STAGE)/devicename $(STAGE)/prefsfix $(STAGE)/signinfix $(STAGE)/gyroscope $(STAGE)/accelerometer $(STAGE)/attitude $(STAGE)/gpu $(STAGE)/virtiosound:
@mkdir -p $@
$(CAMFIX): $(CAMFIX_SOURCES) $(CAMFIX_INPUTS) | $(STAGE)/camfix
@@ -312,7 +315,20 @@ $(GYROSCOPE): $(GYROSCOPE_SOURCES) $(GYROSCOPE_INPUTS) | $(STAGE)/gyroscope
-framework Foundation -Wl,-not_for_dyld_shared_cache
@codesign --force --sign - $@
-.PHONY: test-gyroscope
+$(ACCELEROMETER): $(ACCELEROMETER_SOURCES) $(ACCELEROMETER_INPUTS) | $(STAGE)/accelerometer
+ $(CLANG) -arch arm64e -miphoneos-version-min=18.0 -Os -fobjc-arc \
+ -Wall -Wextra -Werror -Wno-unused-parameter -dynamiclib \
+ -install_name /usr/lib/libvphoneaccelerometer.dylib -o $@ $(ACCELEROMETER_SOURCES) \
+ -framework Foundation -Wl,-not_for_dyld_shared_cache
+ @codesign --force --sign - $@
+
+.PHONY: test-gyroscope test-accelerometer
+test-accelerometer:
+ @mkdir -p $(OUT)
+ xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -Wno-unused-parameter -IAccelerometer \
+ -o $(OUT)/AccelerometerTests Tests/AccelerometerTests.m Accelerometer/VPhoneOrientationSink.m -framework Foundation
+ @$(OUT)/AccelerometerTests
+
$(ATTITUDE): $(ATTITUDE_SOURCES) $(ATTITUDE_INPUTS) | $(STAGE)/attitude
$(CLANG) -arch arm64e -miphoneos-version-min=18.0 -Os -fobjc-arc \
-Wall -Wextra -Werror -Wno-unused-parameter -dynamiclib \
diff --git a/VPhoneGuestComponents/README.md b/VPhoneGuestComponents/README.md
index 10629790..0fca21e8 100644
--- a/VPhoneGuestComponents/README.md
+++ b/VPhoneGuestComponents/README.md
@@ -13,6 +13,7 @@ tweak filter plists, and the GPU provenance note:
| DeviceHub fix | `devicehubfix/libdevicehubfix.dylib` |
| Device name pin | `devicename/libdevicename.dylib` |
| Virtual gyroscope | `gyroscope/libvphonegyro.dylib` |
+| Gravity accelerometer | `accelerometer/libvphoneaccelerometer.dylib` |
| Device attitude | `attitude/libvphoneattitude.dylib` |
| Launchd hook | `launchhook/launchdhook-vphone.dylib` |
| Process injection bridge | `systemhook/SystemHook-vphone.dylib` |
@@ -67,6 +68,20 @@ replaces installed copies only and requests a reboot without restarting the
UI daemon. `make test-gyroscope` checks its configuration transport. Guest
CoreMotion acceptance is still pending; see `Research/Guest/virtual_gyroscope.md`.
+`system-backboardd-cfw-accelerometer` installs a stationary gravity HID service
+in backboardd, selected independently of the gyro and app attitude providers.
+It matches the built-in accelerometer usage (`0xff00`, `3`), emits real
+accelerometer events on the requested report interval, and retains the device
+pose selected by `display.rotation` across SpringBoard relaunches. A native
+queue bridge supplies classified device orientation where the virtual board's
+motion stack never subscribes to raw HID samples. The same library recomputes
+SpringBoard's orientation gates after seeding the real backlight state. The read
+form of `display.rotation` includes its configuration and provider status.
+`make test-accelerometer` exercises gravity axes, the real HID event factory,
+subscription changes and stale service callbacks without registering a host
+sensor. See `Research/Guest/springboard_orientation_stuck.md` for evidence and
+the language-change regression boundary.
+
`system-apps-cfw-attitude` installs `libvphoneattitude.dylib`, loaded by
SystemHook into apps. It supplies a stationary Core Motion pose through
`motion.attitude.set/get/clear`, independently of gyro angular velocity.
diff --git a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
index 71fdc213..50dc67a5 100644
--- a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
+++ b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
@@ -41,7 +41,7 @@ static int vpIsCameraDaemon(const char *path) {
return length >= sizeof(suffix) - 1 && strcmp(path + length - (sizeof(suffix) - 1), suffix) == 0;
}
-static int vpIsGyroscopeDaemon(const char *path) {
+static int vpIsMotionDaemon(const char *path) {
return vpPathHasSuffix(path, "/usr/libexec/backboardd");
}
@@ -49,7 +49,7 @@ static int vpIsInjectionTarget(const char *path) {
if (!path)
return 0;
const char *root = getenv("VPHONE_JB_ROOT");
- return vpIsBootstrapPath(path, root) || vpIsAppPath(path) || vpIsCameraDaemon(path) || vpIsGyroscopeDaemon(path) ||
+ return vpIsBootstrapPath(path, root) || vpIsAppPath(path) || vpIsCameraDaemon(path) || vpIsMotionDaemon(path) ||
(vpInBootstrap && path[0] != '/');
}
@@ -162,6 +162,7 @@ static int vpExecve(const char *path, char *const argv[], char *const envp[]) {
#define VP_CAMERA_DAEMON_HOOK "/usr/lib/libvcamcaptured.dylib"
#define VP_CAMERA_APP_HOOK "/usr/lib/libcamfix.dylib"
#define VP_GYROSCOPE_HOOK "/usr/lib/libvphonegyro.dylib"
+#define VP_ACCELEROMETER_HOOK "/usr/lib/libvphoneaccelerometer.dylib"
#define VP_ATTITUDE_HOOK "/usr/lib/libvphoneattitude.dylib"
#define VP_AVFOUNDATION "/System/Library/Frameworks/AVFoundation.framework/AVFoundation"
// The haptics fix rides the same route and needs no loader of its own. See
@@ -224,7 +225,7 @@ __attribute__((constructor)) static void vpLogProcess(void) {
vpInBootstrap = vpIsBootstrapPath(path, getenv("VPHONE_JB_ROOT"));
// Every process loads this hook; only the ones it acts on are logged.
- int fd = vpInXPCProxy || vpInBootstrap || vpIsAppPath(path) || vpIsCameraDaemon(path) || vpIsGyroscopeDaemon(path)
+ int fd = vpInXPCProxy || vpInBootstrap || vpIsAppPath(path) || vpIsCameraDaemon(path) || vpIsMotionDaemon(path)
? vpOpenLog("vphone-systemhook.log")
: -1;
if (fd >= 0) {
@@ -246,14 +247,17 @@ __attribute__((constructor)) static void vpLogProcess(void) {
vpLoadLibrary("camera-hook", VP_CAMERA_DAEMON_HOOK);
return;
}
- if (vpIsGyroscopeDaemon(path)) {
+ if (vpIsMotionDaemon(path)) {
vpLoadLibrary("gyroscope-hook", VP_GYROSCOPE_HOOK);
+ vpLoadLibrary("accelerometer-hook", VP_ACCELEROMETER_HOOK);
return;
}
// SpringBoard needs the haptics swizzle before UIKit first asks for an
// engine, even though attitude simulation excludes this system UI app.
- if (vpIsSpringBoard(path))
+ if (vpIsSpringBoard(path)) {
vpLoadLibrary("haptics-fix", VP_HAPTICS_FIX);
+ vpLoadLibrary("accelerometer-hook", VP_ACCELEROMETER_HOOK);
+ }
// Loaded before the app gate too: the swizzle must be in place before
// Settings builds its follow-up section.
if (vpIsPreferences(path))
diff --git a/VPhoneGuestComponents/Tests/AccelerometerTests.m b/VPhoneGuestComponents/Tests/AccelerometerTests.m
new file mode 100644
index 00000000..9cfcbc89
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/AccelerometerTests.m
@@ -0,0 +1,168 @@
+#import "../Accelerometer/libvphoneaccelerometer.m"
+#include <assert.h>
+#include <stdio.h>
+
+// Exercise subscriptions and reset without publishing a HID device or writing
+// mobile's preferences on the host. The sample factory is Apple's real HID ABI.
+@interface VPhoneAccelerometerTestProvider : VPhoneAccelerometerProvider
+@property (nonatomic) NSUInteger timerUpdates;
+@property (nonatomic) NSUInteger statusUpdates;
+@end
+@implementation VPhoneAccelerometerTestProvider
+- (void)publishStatus { self.statusUpdates++; }
+- (void)updateTimer { self.timerUpdates++; }
+@end
+
+@interface VPhoneAccelerometerTestService : NSObject
+@property (nonatomic) NSUInteger cancellations;
+@end
+@implementation VPhoneAccelerometerTestService
+- (uint64_t)serviceID { return 42; }
+- (void)cancel { self.cancellations++; }
+- (BOOL)dispatchEvent:(id)event { return YES; }
+@end
+
+// Runtime-shaped native peers, to check queue confinement and the actual
+// setup ordering bug without loading or modifying any host system UI.
+@interface BKOrientationManager : NSObject
+@property (nonatomic, strong) dispatch_queue_t queue;
+@property (nonatomic) NSInteger orientation;
+@property (nonatomic) NSUInteger deliveries;
+@property (nonatomic) NSUInteger matches;
+- (void)matcher:(id)matcher servicesDidMatch:(id)services;
+- (void)_queue_postUpdatedRawAccelerometerDeviceOrientation:(NSInteger)orientation;
+@end
+@implementation BKOrientationManager
+- (void)matcher:(id)matcher servicesDidMatch:(id)services { self.matches++; }
+- (void)_queue_postUpdatedRawAccelerometerDeviceOrientation:(NSInteger)orientation {
+ dispatch_assert_queue(self.queue);
+ self.orientation = orientation;
+ self.deliveries++;
+}
+@end
+
+@interface SBBacklightController : NSObject
+@property (nonatomic) BOOL screenIsOn;
++ (instancetype)sharedInstanceIfExists;
+@end
+@implementation SBBacklightController
++ (instancetype)sharedInstanceIfExists {
+ static SBBacklightController *controller;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{ controller = [SBBacklightController new]; });
+ return controller;
+}
+@end
+
+@interface SBTraitsEmbeddedDisplayPipelineManager : NSObject
+@property (nonatomic) BOOL backlightIsOn;
+@property (nonatomic) BOOL eventsEnabled;
+@property (nonatomic) BOOL deferring;
+@property (nonatomic) NSUInteger setups;
+- (void)setupDefaultPipelineForArbiter:(id)arbiter;
+- (void)_updateOrientationEventsEnabledState;
+- (void)_updateOrientationInputsDeferralAnimated:(BOOL)animated;
+@end
+@implementation SBTraitsEmbeddedDisplayPipelineManager
+- (void)setupDefaultPipelineForArbiter:(id)arbiter {
+ self.setups++;
+ self.backlightIsOn = NO;
+ [self _updateOrientationEventsEnabledState];
+ self.backlightIsOn = [SBBacklightController sharedInstanceIfExists].screenIsOn;
+}
+- (void)_updateOrientationEventsEnabledState { self.eventsEnabled = self.backlightIsOn; }
+- (void)_updateOrientationInputsDeferralAnimated:(BOOL)animated { self.deferring = !self.backlightIsOn; }
+@end
+
+int main(void) {
+ @autoreleasepool {
+ int degrees = -1;
+ for (id invalid in @[@YES, @"90", @-90, @360, @90.5, @(NAN), @(INFINITY), NSNull.null]) {
+ assert(!VPhoneAccelerometerDecode(invalid, &degrees));
+ assert(degrees == 0);
+ }
+ assert(!VPhoneAccelerometerDecode(nil, &degrees) && degrees == 0);
+ NSArray *specs = @[@"portrait", @"LEFT", @"portrait-upside-down", @"right"];
+ double expectedX[] = {0, -1, 0, 1}, expectedY[] = {-1, 0, 1, 0};
+ assert(VPhoneAccelerometerDegrees(@"face-up") == -1);
+ assert(VPhoneAccelerometerInterval(@500) == 5000);
+ assert(VPhoneAccelerometerInterval(@20000) == 20000);
+ assert(VPhoneAccelerometerInterval(@1e30) == 1000000);
+ for (id invalid in @[@YES, @"20000", @-1, @0, @(NAN), @(INFINITY)])
+ assert(VPhoneAccelerometerInterval(invalid) == 0);
+
+ assert(dlopen("/System/Library/PrivateFrameworks/HID.framework/HID", RTLD_NOW | RTLD_LOCAL));
+ VPhoneAccelerometerTestProvider *provider = [VPhoneAccelerometerTestProvider new];
+ provider.eventClass = (Class<VPhoneAccelerometerHIDEvent>)NSClassFromString(@"HIDEvent");
+ provider.properties = [NSMutableDictionary new];
+ VPhoneAccelerometerTestService *service = [VPhoneAccelerometerTestService new];
+ NSObject *staleService = [NSObject new];
+ provider.service = (id)service;
+ for (int index = 0; index < 4; index++) {
+ assert(VPhoneAccelerometerDecode(@(index * 90), &degrees));
+ assert(VPhoneAccelerometerDegrees(specs[index]) == degrees);
+ provider.degrees = degrees;
+ id<VPhoneAccelerometerHIDEvent> event = [provider sample];
+ assert(event && event.timestamp > 0);
+ assert(event.accelerometerX == expectedX[index]);
+ assert(event.accelerometerY == expectedY[index]);
+ assert(event.accelerometerZ == 0 && event.accelerometerSequence == (uint32_t)index);
+ }
+ assert(![provider copyEventMatching:nil forService:service]);
+ [provider notification:10 withProperty:nil forService:staleService];
+ assert(!provider.enumerated && provider.statusUpdates == 0);
+ [provider notification:10 withProperty:nil forService:service];
+ assert(provider.enumerated && provider.statusUpdates == 1);
+ assert([provider copyEventMatching:@{@"EventType": @13} forService:service]);
+ assert(![provider copyEventMatching:@{@"EventType": @20} forService:service]);
+ assert(![provider copyEventMatching:nil forService:staleService]);
+ assert([provider setProperty:@20000 forKey:@"ReportInterval" forService:service]);
+ assert(provider.interval == 20000);
+ assert(![provider setProperty:@0 forKey:@"ReportInterval" forService:staleService]);
+ assert(provider.interval == 20000);
+ assert([provider setProperty:@0 forKey:@"ReportInterval" forService:service]);
+ assert(provider.interval == 0);
+ assert([provider setProperty:@100 forKey:@"BatchInterval" forService:service]);
+ assert(![provider setProperty:@YES forKey:@"Unsupported" forService:service]);
+ [provider notification:11 withProperty:nil forService:service];
+ [provider notification:11 withProperty:nil forService:service];
+ assert(!provider.enumerated && provider.cancelling && service.cancellations == 1);
+ assert(![provider copyEventMatching:nil forService:service]);
+ puts("Accelerometer gravity, real HID samples and subscription tests passed");
+
+ VPhoneOrientationSinkInstall(nil, nil);
+ BKOrientationManager *manager = [BKOrientationManager new];
+ manager.queue = dispatch_queue_create("com.vphone.orientation.sink-test", DISPATCH_QUEUE_SERIAL);
+ dispatch_sync(manager.queue, ^{ [manager matcher:nil servicesDidMatch:@[]]; });
+ dispatch_sync(manager.queue, ^{ assert(manager.orientation == 1 && manager.deliveries == 1 && manager.matches == 1); });
+ NSInteger nativeOrientations[] = {1, 4, 2, 3};
+ for (int index = 0; index < 4; index++) {
+ provider.degrees = index * 90;
+ VPhoneOrientationSinkPublish([provider sample]);
+ NSInteger expectedOrientation = nativeOrientations[index];
+ dispatch_sync(manager.queue, ^{ assert(manager.orientation == expectedOrientation); });
+ }
+ NSUInteger deliveries = manager.deliveries;
+ VPhoneOrientationSinkPublish([provider sample]);
+ // Flat and ambiguous samples must not create a made-up direction.
+ VPhoneOrientationSinkPublish([provider.eventClass accelerometerEvent:1 x:0 y:0 z:1 options:0]);
+ VPhoneOrientationSinkPublish([provider.eventClass accelerometerEvent:2 x:0.6 y:0.6 z:0 options:0]);
+ dispatch_sync(manager.queue, ^{ assert(manager.deliveries == deliveries); });
+ assert([VPhoneOrientationSinkStatus()[@"ready"] boolValue]);
+ assert([VPhoneOrientationSinkStatus()[@"device_orientation"] integerValue] == 3);
+
+ SBBacklightController *backlight = [SBBacklightController sharedInstanceIfExists];
+ backlight.screenIsOn = YES;
+ SBTraitsEmbeddedDisplayPipelineManager *pipeline = [SBTraitsEmbeddedDisplayPipelineManager new];
+ [pipeline setupDefaultPipelineForArbiter:nil];
+ assert(!pipeline.eventsEnabled); // Native ordering reproduces the bug.
+ VPhoneOrientationGateInstall();
+ [pipeline setupDefaultPipelineForArbiter:nil];
+ assert(pipeline.eventsEnabled && !pipeline.deferring && pipeline.setups == 2);
+ backlight.screenIsOn = NO;
+ [pipeline setupDefaultPipelineForArbiter:nil];
+ assert(!pipeline.eventsEnabled && pipeline.deferring && pipeline.setups == 3);
+ puts("Device orientation sink queue, deduplication and backlight seed regression tests passed");
+ }
+ return 0;
+}
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
index b6ef1b81..08c76339 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
@@ -19,10 +19,11 @@ public enum VPhoneGuestEnvironment {
"libprefsfix.dylib",
"libsigninfix.dylib",
"libvphonegyro.dylib",
+ "libvphoneaccelerometer.dylib",
"libvphoneattitude.dylib",
]
/// Selection installs/removes these. A live hash sync may replace an
/// installed copy, but must never reinstall a patch the user turned off.
- public static let selectedLibraries: Set<String> = ["libvphonegyro.dylib", "libvphoneattitude.dylib"]
+ public static let selectedLibraries: Set<String> = ["libvphonegyro.dylib", "libvphoneaccelerometer.dylib", "libvphoneattitude.dylib"]
}