Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Add virtual HID gyroscope and guest motion RPCs

Phineas Guo0be952826779
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 6c75747c..373ecf5f 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -232,6 +232,22 @@
> `cameracaptured`, `vphone-systemhook.log` records `camera-hook=... result=loaded`
> for its PID, and `vcamcaptured.log` shows the hook installing its source.
+> **3D gyroscope core (2026-10-08; guest acceptance pending):**
+> `system-backboardd-cfw-gyroscope`, declared in the Guest System set and
+> selected by both presets on iOS 18+, installs `/usr/lib/libvphonegyro.dylib`.
+> SystemHook loads it into backboardd through the same no-bootstrap daemon
+> route as the camera hook. It publishes a virtual HID gyro (page `0xff00`,
+> usage `9`); vphoned's `motion.gyroscope.set/get/clear` sends an atomic
+> three-axis rad/s configuration through mobile's backboardd preferences and
+> a Darwin notification. There is no system executable, kernel or DSC byte
+> change. Disabling the patch removes the added library; live environment
+> sync cannot reinstall an absent selected library. A provider/library update
+> needs a reboot, without silently restarting backboardd. The host menu and
+> panel are deferred until the user approves the next task. HID enumeration
+> and dispatch are observable separately from CoreMotion app acceptance; the
+> platform capability gate and optional IMU match still require guest proof.
+> Reveal evidence and manual acceptance: `Research/Guest/virtual_gyroscope.md`.
+
> **Current launchd hook (2026-09-25; isolated VM verification):**
> `cfw install` now places `launchdhook-vphone.dylib` and a diagnostic
> `SystemHook-vphone.dylib` in `/usr/lib`, links `/vh` to the launchd hook,
diff --git a/Research/Guest/virtual_gyroscope.md b/Research/Guest/virtual_gyroscope.md
new file mode 100644
index 00000000..bb486826
--- /dev/null
+++ b/Research/Guest/virtual_gyroscope.md
@@ -0,0 +1,145 @@
+# Virtual 3D gyroscope
+
+## Core boundary (2026-10-08)
+
+The core adds raw three-axis angular velocity, in **radians per second**. It
+does not represent Euler angles or synthesize accelerometer, compass, attitude,
+or fused `CMDeviceMotion`. The host menu and axis panel are a separate task.
+
+`vphoned` exposes `motion.gyroscope.set {x,y,z}`, `motion.gyroscope.get`, and
+`motion.gyroscope.clear` over the existing VSOCK 1339 RPC transport. Set requires
+all three finite JSON numbers in [-1000,1000]; strings, Booleans, missing axes,
+and out-of-range values are refused before any state is changed. Clear disables
+the configured rotation and writes zero on every axis.
+
+One dictionary, `VPhoneGyroscopeConfiguration`, is written through cfprefsd to
+the mobile user's `com.apple.backboardd` domain and then
+`com.vphone.motion.gyroscope.changed` is posted. This avoids a separate port or
+new daemon sandbox file permissions. A running provider reads the whole
+dictionary on its serial queue; malformed stored state becomes stationary.
+Configuration persists across guest restarts until changed or cleared.
+
+As with the camera daemon hook, SystemHook loads a guest dylib without ElleKit
+or a bootstrap. `/usr/lib/libvphonegyro.dylib` is loaded only into
+`/usr/libexec/backboardd`, the HID server, after its constructors return. The
+library publishes a `HIDVirtualEventService` with Apple vendor usage page
+`0xff00`, usage `9`, and `IMULocationID = 0`. It creates each event through
+`+[HIDEvent gyroEvent:x:y:z:options:]`, with `mach_absolute_time()` and an
+incrementing gyro sequence. No system instruction is overwritten, no app's
+`CMMotionManager` methods are swizzled, and there are no kernel/DSC edits.
+
+HID report/batch interval requests are handled on that same queue. The provider
+advertises aggregate sensor control so one client stopping does not cancel
+other clients. A zero report interval stops the timer; nonzero requests are
+bounded to 5,000–1,000,000 microseconds (1–200 Hz). There is no FIFO batching.
+Clear leaves the service and subscriptions alive and emits stationary samples.
+After a HID reset, the old service is cancelled and released only from its
+cancel handler, then a new service is registered after five seconds.
+
+`VPhoneGyroscopeStatus` is updated at configuration and service transitions and
+every two seconds. The RPC result includes `provider` and `provider_running`;
+the latter requires an enumerated service and a heartbeat younger than ten
+seconds. The status includes service ID, PID, report interval, dispatched event
+count, dispatch failures, last error, and the configuration consumed by the
+provider. **Enumeration and dispatch do not prove CoreMotion acceptance.**
+
+## Patch selection and installation
+
+`system-backboardd-cfw-gyroscope` is declared in the Guest System patch set and
+selected by both shipped presets on iOS 18 and newer. The dylib is built for
+arm64e with an iOS 18 deployment target. Missing runtime APIs produce a provider
+error and leave backboardd running. A legacy install with no patch plan does
+not enable this new provider; resolve an explicit selection first.
+
+The mounted `cfw install` and `cfw update-environment` steps install this library
+when selected and remove it when blocked. The general environment redeploy
+does not own this file. A live hash sync may replace an already installed copy
+but cannot add an absent copy, so it cannot undo a user's patch selection.
+Updating the gyro library or its loading SystemHook asks for a reboot; it does
+not restart backboardd, which would interrupt the guest UI.
+
+To test a local build, install it with `vphone-launchpad-cli bundle install-local`
+and bind the stopped test machine using `vm set-bundle <name> <version>
+--update-environment`, as described in `Documents/Guides/launchpad-cli.md`.
+The mounted update adds this newly selected patch to an older machine too.
+Reboot before testing. To turn it off, use the patch editor to block
+`system-backboardd-cfw-gyroscope`, update the stopped machine's environment,
+and boot again.
+
+## Reveal evidence
+
+Apple's primary interface sources:
+
+- [HIDVirtualEventService](https://github.com/apple-oss-distributions/IOHIDFamily/blob/main/HID/PrivateHeaders/HIDVirtualEventService.h): requires the HID event-dispatch entitlement; enumerated/terminated notifications and explicit cancel lifecycle.
+- [HIDEventAccessors](https://github.com/apple-oss-distributions/IOHIDFamily/blob/main/HID/Headers/HIDEventAccessors.h) and [implementation](https://github.com/apple-oss-distributions/IOHIDFamily/blob/main/HID/HIDEventAccessors.m): typed gyro factory and sequence accessor, signed 16.16 axis representation.
+- [IOHIDEventServiceTypes](https://github.com/apple-oss-distributions/IOHIDFamily/blob/main/IOHIDFamily/IOHIDEventServiceTypes.h): sensor control aggregation, decimation, and dispatch gating.
+
+The user-opened CoreMotion cache image in Hopper was inspected read-only. Its
+cache/build identity was not supplied, so the addresses below are **reveal
+evidence only**, not a claim that every iOS base has been verified and never
+runtime offsets:
+
+1. `-[CMMotionManager isGyroAvailable]` at `0x1af9a662c` checks the CoreMotion
+ initialization gate and its shared object before calling a query outside
+ the imported image. That external query was not resolved.
+2. The string `Setting Gyro matching properties with IMULocationID %d` reveals
+ `CLGyro::openHidDevice` at `0x1af9ff8b0`. Its lookup key at `0x1afc68e38`
+ contains `00 ff 00 00 09 00 00 00`: page `0xff00`, usage `9`. The adjacent
+ accelerometer key uses page `0xff00`, usage `3`.
+3. The gyro event callback beginning at `0x1af9ffb58` checks type `0x14`, reads
+ X/Y/Z fields `0x140000`, `0x140001`, `0x140002`, timestamp and subtype.
+4. `CLIoHidInterface` construction was traced through `0x1af9a9fec`,
+ `0x1af9b5218`, `0x1af9b52b4`, and `0x1afad5780`; its callback registration
+ goes through `0x1afad5ac0` on the motion thread.
+5. `openHidDevice` also checks bit 1 of the platform capability mask returned
+ by `0x1af977bb4`. That mask comes from a platform-indexed table. The virtual
+ board's result has **not** been measured, nor has its optional IMU matching
+ constraint. Publishing a HID service does not bypass this gate. If a guest
+ still reports unavailable, capture that guest's CoreMotion image/platform
+ result before adding any capability repair.
+
+The demo edition allowed inspection but refused assembly export. No Hopper
+scripting, interpreter, or generated instruction bytes were added to the repo.
+
+## Verification and manual acceptance
+
+Host transport test: `make -C VPhoneGuestComponents test-gyroscope`. It checks a
+binary property-list round trip, invalid types/non-finite values, incomplete
+axis dictionaries, clear state, and subscriber interval bounds. The full
+`VPhone` scheme validates the packaged signed dylib and vphoned.
+The host test also calls the real HID event factory without publishing a host
+service, verifying its selector ABI, timestamp, sequence, signed axes and
+16.16 quantization. The seven patch model/catalogue suites passed (55 tests),
+including default selection, explicit blocking, iOS 18+ and unknown/older-base
+gates. These checks do not substitute for the guest acceptance below.
+
+Guest runtime acceptance is delegated to the user; it has **not yet run**:
+
+```sh
+vphone-launchpad-cli guest rpc <name> motion.gyroscope.get
+vphone-launchpad-cli guest rpc <name> motion.gyroscope.set '{"x":1.25,"y":-2.5,"z":0.125}'
+vphone-launchpad-cli guest rpc <name> motion.gyroscope.get
+vphone-launchpad-cli guest rpc <name> motion.gyroscope.clear
+```
+
+1. Verify `vphone-systemhook.log` records `gyroscope-hook=... result=loaded` for
+ backboardd, then `provider_running = true` and a nonzero service ID.
+2. Open a foreground app that uses `CMMotionManager`. Confirm `isGyroAvailable`
+ and test **both** `startGyroUpdatesToQueue:withHandler:` and polling
+ `gyroData` after `startGyroUpdates`. Record rotationRate and timestamps.
+3. Set one axis at a time (including negatives), then all three. Compare the
+ readings with configured rad/s within 1/65536 quantization; timestamps must
+ advance. `provider.configuration` must match the latest RPC and the event
+ counter must increase while a client subscribes.
+4. Keep two clients subscribed; stop one and verify the other keeps receiving
+ samples. Stop both and verify no report timer remains active. Clear while
+ subscribed and verify zero rates, then set again without restarting the app.
+5. Test app restart, guest restart, and provider recovery after a HID reset.
+ Check backboardd crash reports and dispatch failures. Block the patch,
+ update the stopped machine, boot, and confirm the dylib stays absent after
+ the host's automatic environment sync.
+
+If step 1 passes but step 2 does not, core acceptance remains incomplete. The
+HID provider status must not be presented as proof that an app receives gyro
+data. Possible next reveal points are the platform mask, IMU match, and service
+interval requests in that guest's CoreMotion build.
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index 2b125c43..2b6ec817 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -295,6 +295,7 @@ request carries `"force": true`.
| System | `system.uicache`, `system.system_apps {visible?}`, `system.respring` **force**, `system.reboot {userspace?}` **force**, `system.shutdown` **force**, `developer_mode.status`, `developer_mode.enable`, `power.low_power_mode`, `time.timezone {identifier?, automatic?}` (see below), `diagnostics.self_test` |
| Files | `files.list`, `mkdir`, `remove`, `rename`, `read {binary?, limit?}`, `write`, `find`, `copy`, `symlink`, `chmod`, `chown`, `plist`, `plist_set {value \| remove}` |
| Preferences, clipboard, location | `settings.get/set/delete`, `clipboard.get/set/clear`, `location.set/clear/current` |
+| Motion | `motion.gyroscope.get`, `motion.gyroscope.set {x,y,z}`, `motion.gyroscope.clear` (capability `motion_gyroscope`; finite JSON numbers in [-1000,1000] rad/s, all axes required; returns configuration, `units`, `provider`, and `provider_running`; HID provider status is not proof of CoreMotion app delivery) |
| Keychain | `keychain.list {class?}`, `add`, `delete`, `get`, `update`, `database` |
| Packages (read-only) | `packages.list`, `status`, `info {path}`, `compare`, `tweaks`, `repos` |
| Bootstrap | `bootstrap.install {layout}`, `bootstrap.status`, `bootstrap.inspect`, `bootstrap.uninstall {jbroot, force}`, `bootstrap.firmware` (see above) |
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
index cf660668..fdcad8b6 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
@@ -21,6 +21,7 @@ extension GuestAPI {
"libdevicename.dylib",
"libprefsfix.dylib",
"libsigninfix.dylib",
+ "libvphonegyro.dylib",
]
static let environmentStaging = "/var/root/Library/Caches/vphone-environment"
@@ -57,6 +58,9 @@ extension GuestAPI {
guard environmentLibraries.contains(name) else {
throw GuestAPIError.invalidRequest("\(name) is not part of the vphone environment")
}
+ if name == "libvphonegyro.dylib", !FileManager.default.fileExists(atPath: "/usr/lib/" + name) {
+ throw GuestAPIError.invalidRequest("Enable the gyroscope patch with cfw install or cfw update-environment first")
+ }
let staged = URL(fileURLWithPath: environmentStaging + "/" + name)
guard let data = try? Data(contentsOf: staged, options: .mappedIfSafe) else {
throw GuestAPIError.invalidRequest("Upload \(name) to \(environmentStaging) first")
@@ -96,7 +100,10 @@ extension GuestAPI {
"installed": names,
"restarted_pids": restarted,
// launchd loaded its hook at boot and keeps the old copy mapped.
- "reboot_required": !rootReadOnly || names.contains("launchdhook-vphone.dylib"),
+ // 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"),
"root_read_only": rootReadOnly,
]
}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
index dd61a077..efbb088a 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
@@ -18,6 +18,7 @@ extension GuestAPI {
executeSetupAssistant,
executeTimeZone,
executeAudioLatency,
+ executeGyroscope,
]
for area in areas {
if let result = try area(method, params) {
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Gyroscope.swift b/VPhoneDaemon/Daemon/GuestAPI+Gyroscope.swift
new file mode 100644
index 00000000..d8972669
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+Gyroscope.swift
@@ -0,0 +1,37 @@
+import CoreFoundation
+import Foundation
+import VphonedNative
+
+// MARK: - Virtual Gyroscope
+
+extension GuestAPI {
+ private static let gyroscopeLock = NSLock()
+
+ static func executeGyroscope(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ guard ["motion.gyroscope.get", "motion.gyroscope.set", "motion.gyroscope.clear"].contains(method) else {
+ return nil
+ }
+ // The API queue is concurrent. Serialize publication and readback so
+ // the response contains the dictionary this request actually wrote.
+ gyroscopeLock.lock()
+ defer { gyroscopeLock.unlock() }
+ if method != "motion.gyroscope.get" {
+ var axes = [Double](repeating: 0, count: 3)
+ if method == "motion.gyroscope.set" {
+ for (index, key) in ["x", "y", "z"].enumerated() {
+ guard let value = params[key] as? NSNumber,
+ CFGetTypeID(value) != CFBooleanGetTypeID(),
+ value.doubleValue.isFinite, abs(value.doubleValue) <= 1000
+ else {
+ throw GuestAPIError.invalidRequest("\(key) must be a number between -1000 and 1000 rad/s")
+ }
+ axes[index] = value.doubleValue
+ }
+ }
+ guard vp_gyro_set(axes[0], axes[1], axes[2], method == "motion.gyroscope.set") else {
+ throw GuestAPIError.operationFailed("Could not publish the gyroscope configuration")
+ }
+ }
+ return vp_gyro_get() as? [String: Any] ?? [:]
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index 1b9d8b7b..d257a1a9 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -140,6 +140,7 @@ enum GuestAPI {
"network_resolve",
"timezone",
"audio_host_latency",
+ "motion_gyroscope",
],
]
}
diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.h
index b273c184..fd160d12 100644
--- a/VPhoneDaemon/Native/Include/VphonedNative.h
+++ b/VPhoneDaemon/Native/Include/VphonedNative.h
@@ -57,6 +57,10 @@ char *vp_usb_set_serial(const char *serial, bool force, bool *changed);
char *vp_usb_own_serial(void);
#ifdef __OBJC__
+/// 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);
+
/// Snapshot-local nested accessibility tree, using actual private iOS child links.
NSDictionary *vp_ax_hierarchy(int pid, int maxElements, int maxDepth, int timeoutMS);
diff --git a/VPhoneDaemon/Native/vphoned_gyro.m b/VPhoneDaemon/Native/vphoned_gyro.m
new file mode 100644
index 00000000..e49b5608
--- /dev/null
+++ b/VPhoneDaemon/Native/vphoned_gyro.m
@@ -0,0 +1,40 @@
+#import "Include/VphonedNative.h"
+#import "../../VPhoneGuestComponents/Gyroscope/VPhoneGyroscopeState.h"
+#include <notify.h>
+
+static id VPhoneGyroscopeRead(CFStringRef key) {
+ return CFBridgingRelease(CFPreferencesCopyValue(key, CFSTR(VP_GYRO_DOMAIN), CFSTR("mobile"),
+ kCFPreferencesAnyHost));
+}
+
+NSDictionary *vp_gyro_get(void) {
+ CFPreferencesSynchronize(CFSTR(VP_GYRO_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+ VPhoneGyroscopeState state;
+ VPhoneGyroscopeDecode(VPhoneGyroscopeRead(CFSTR(VP_GYRO_CONFIGURATION)), &state);
+ NSMutableDictionary *result = [VPhoneGyroscopeEncode(state) mutableCopy];
+ result[@"units"] = @"rad/s";
+ id status = VPhoneGyroscopeRead(CFSTR(VP_GYRO_STATUS));
+ if ([status isKindOfClass:NSDictionary.class] &&
+ [status[@"updated_at"] isKindOfClass:NSNumber.class] &&
+ [status[@"enumerated"] isKindOfClass:NSNumber.class]) {
+ result[@"provider"] = status;
+ double age = [NSDate date].timeIntervalSince1970 - [status[@"updated_at"] doubleValue];
+ result[@"provider_running"] = @([status[@"enumerated"] boolValue] && age >= 0 && age < 10);
+ } else {
+ result[@"provider"] = NSNull.null;
+ result[@"provider_running"] = @NO;
+ }
+ return result;
+}
+
+BOOL vp_gyro_set(double x, double y, double z, bool enabled) {
+ VPhoneGyroscopeState state = {enabled, x, y, z}, checked;
+ NSDictionary *value = VPhoneGyroscopeEncode(state);
+ if (!VPhoneGyroscopeDecode(value, &checked))
+ return NO;
+ CFPreferencesSetValue(CFSTR(VP_GYRO_CONFIGURATION), (__bridge CFDictionaryRef)value,
+ CFSTR(VP_GYRO_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+ if (!CFPreferencesSynchronize(CFSTR(VP_GYRO_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost))
+ return NO;
+ return notify_post(VP_GYRO_NOTIFICATION) == NOTIFY_STATUS_OK;
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index 017c0a78..b8944b81 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -21,6 +21,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"
private static let ios27 = VPhonePatchApplicability(iOSBase: .major(27))
@@ -219,6 +220,16 @@ public enum FirmwareGuestSystemPatchSet {
bootEssential: true,
),
+ // MARK: Motion
+
+ VPhonePatchDeclaration(
+ identifier: gyroscope,
+ title: "Virtual 3D gyroscope",
+ summary: "Installs libvphonegyro.dylib, loaded by SystemHook into backboardd. Publishes a virtual HID gyro service using the three-axis rotation rate configured through vphoned. Removing the library disables the provider after a reboot.",
+ target: .guestFile(path: "/usr/lib/libvphonegyro.dylib"),
+ applicability: VPhonePatchApplicability(iOSBase: .atLeast(major: 18, minor: 0)),
+ ),
+
// MARK: Audio
VPhonePatchDeclaration(
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
index c19ebeb3..cad828cb 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
@@ -17,6 +17,34 @@ import VPhonePatchKit
@Suite("Bundled patch set catalogue")
struct FirmwarePatchSetCatalogTests {
+ @Test func `Gyroscope follows selection and its deployment target`() throws {
+ let identifier = FirmwareGuestSystemPatchSet.gyroscope
+ for base in ["18.6.2", "26.4", "27.0.1"] {
+ let plan = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.standardPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion("26.4"),
+ )
+ #expect(plan.isEnabled(identifier))
+ var blocked = FirmwarePatchSetCatalog.standardPreset
+ blocked.selection = blocked.selection.blocking([identifier])
+ let disabled = try VPhonePatchPlan.resolve(
+ preset: blocked, patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion("26.4"),
+ )
+ #expect(!disabled.isEnabled(identifier))
+ }
+ let unsupportedBases: [VPhoneVersion?] = [nil, VPhoneVersion("17.0")]
+ for base in unsupportedBases {
+ let plan = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.standardPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: base, cloudOS: VPhoneVersion("26.4"),
+ )
+ #expect(!plan.isEnabled(identifier))
+ }
+ }
+
@Test func `CoreDevice persona lookup is selected only for iOS 27`() throws {
for base in ["26.4", "27.0.1", "28.0"] {
let plan = try VPhonePatchPlan.resolve(
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index 43285d91..6e7f956b 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -1004,9 +1004,12 @@ struct VPhoneCustomFirmwareInstaller {
/// Whether the VM's plan (its guest half re-resolved from the current
/// selection) turned this guest patch on. A VM with no plan gets every
/// legacy patch, which is what it was restored with. New Settings-row
- /// preferences still require an explicit plan.
+ /// preferences and the gyroscope still require an explicit plan.
func on(_ identifier: String) -> Bool {
- guard let plan else { return !FirmwareGuestSystemPatchSet.settingsRowPatches.contains(identifier) }
+ guard let plan else {
+ return !FirmwareGuestSystemPatchSet.settingsRowPatches.contains(identifier)
+ && identifier != FirmwareGuestSystemPatchSet.gyroscope
+ }
guard plan.isEnabled(identifier) else {
print(" [·] \(identifier): off in preset \(plan.presetIdentifier)")
return false
@@ -1114,6 +1117,18 @@ struct VPhoneCustomFirmwareInstaller {
live.insert("system-launchdaemons-boot-environment")
}
}
+ isolate([FirmwareGuestSystemPatchSet.gyroscope]) {
+ let path = "usr/lib/libvphonegyro.dylib"
+ if on(FirmwareGuestSystemPatchSet.gyroscope) {
+ try system.replaceFile(path, fromFileAt: VPhoneGuestBinaries.resolve("libvphonegyro.dylib"),
+ mode: 0o755, owner: Self.guestOwner)
+ live.insert(FirmwareGuestSystemPatchSet.gyroscope)
+ } else {
+ // vphone owns this added file; removing it fully reverts the
+ // patch without modifying the original backboardd executable.
+ try system.removeItem(path)
+ }
+ }
// 2. The dyld shared cache. The version branches and the declarations'
// applicability say the same thing; this is what a VM with no plan
@@ -1756,6 +1771,7 @@ struct VPhoneCustomFirmwareInstaller {
/// infrastructure. A full install writes every library and creates `/vh`.
private func installEnvironment(system: VPhoneConfinedDirectory, environmentOnly: Bool = false) throws {
for name in VPhoneGuestEnvironment.libraries {
+ if VPhoneGuestEnvironment.selectedLibraries.contains(name) { continue }
let path = "usr/lib/\(name)"
if environmentOnly, try !system.exists(path) {
print(" [·] \(path): not on this VM, left out")
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
index f9ce21c7..61a1c856 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
@@ -79,6 +79,7 @@ fi
/bin/cp "$guest_products/devicename/libdevicename.dylib" "$guest/libdevicename.dylib"
/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/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib" \
"$guest/libAppleParavirtCompilerPluginIOGPUFamily.dylib"
# The HAL plugin is a bundle, signed whole by the Makefile; copied as a tree so
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
index 4bc548f5..824791aa 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
@@ -95,7 +95,7 @@ done
for name in vphoned launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \
libvcamcaptured.dylib libmisfix.dylib libhapticsfix.dylib libbatteryhealthfix.dylib libdevicehubfix.dylib libdevicename.dylib \
- libprefsfix.dylib libsigninfix.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
+ libprefsfix.dylib libsigninfix.dylib libvphonegyro.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/UI/GuestCommunication/VPhoneGuestControlEnvironment.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlEnvironment.swift
index 2e53b4de..863ee911 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlEnvironment.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlEnvironment.swift
@@ -33,6 +33,9 @@ extension VPhoneGuestControl {
)
typealias Library = (name: String, data: Data, hash: String)
let changed = try VPhoneGuestEnvironment.libraries.compactMap { name -> Library? in
+ if VPhoneGuestEnvironment.selectedLibraries.contains(name), guestHashes[name] == nil {
+ return nil
+ }
let data = try Data(contentsOf: VPhoneGuestBinaries.resolve(name), options: .mappedIfSafe)
let hash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
return guestHashes[name] == hash ? nil : (name, data, hash)
diff --git a/VPhoneGuestComponents/Gyroscope/VPhoneGyroscopeHID.h b/VPhoneGuestComponents/Gyroscope/VPhoneGyroscopeHID.h
new file mode 100644
index 00000000..db5d54eb
--- /dev/null
+++ b/VPhoneGuestComponents/Gyroscope/VPhoneGyroscopeHID.h
@@ -0,0 +1,25 @@
+#pragma once
+#import <Foundation/Foundation.h>
+
+// Small ABI surface from Apple's IOHIDFamily HIDVirtualEventService.h and
+// HIDEventAccessors.h. Classes are resolved at runtime, as with the camera
+// hook; no private framework stub or third-party loader is needed.
+@protocol VPhoneGyroscopeHIDEvent <NSObject>
++ (id)gyroEvent:(uint64_t)timestamp x:(double)x y:(double)y z:(double)z options:(uint32_t)options;
+- (void)setGyroSequence:(uint32_t)sequence;
+@property (readonly) uint32_t gyroSequence;
+@property (readonly) double gyroX;
+@property (readonly) double gyroY;
+@property (readonly) double gyroZ;
+@property (readonly) uint64_t timestamp;
+@end
+
+@protocol VPhoneGyroscopeHIDService <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/Gyroscope/VPhoneGyroscopeState.h b/VPhoneGuestComponents/Gyroscope/VPhoneGyroscopeState.h
new file mode 100644
index 00000000..61a64a6d
--- /dev/null
+++ b/VPhoneGuestComponents/Gyroscope/VPhoneGyroscopeState.h
@@ -0,0 +1,57 @@
+#pragma once
+#import <Foundation/Foundation.h>
+#include <math.h>
+
+// One dictionary per update: readers never combine axes from different RPCs.
+#define VP_GYRO_DOMAIN "com.apple.backboardd"
+#define VP_GYRO_CONFIGURATION "VPhoneGyroscopeConfiguration"
+#define VP_GYRO_STATUS "VPhoneGyroscopeStatus"
+#define VP_GYRO_NOTIFICATION "com.vphone.motion.gyroscope.changed"
+
+typedef struct {
+ BOOL enabled;
+ double x, y, z; // CoreMotion rotation rate, radians per second.
+} VPhoneGyroscopeState;
+
+// Reject malformed persisted state, booleans masquerading as axes, and rates
+// outside the HID event's signed 16.16 range. No partial-axis updates.
+static inline BOOL VPhoneGyroscopeNumber(id value) {
+ return [value isKindOfClass:NSNumber.class] &&
+ CFGetTypeID((__bridge CFTypeRef)value) != CFBooleanGetTypeID();
+}
+
+static inline BOOL VPhoneGyroscopeDecode(id value, VPhoneGyroscopeState *state) {
+ *state = (VPhoneGyroscopeState){0};
+ if (![value isKindOfClass:NSDictionary.class])
+ return NO;
+ id enabled = value[@"enabled"];
+ if (![enabled isKindOfClass:NSNumber.class] ||
+ CFGetTypeID((__bridge CFTypeRef)enabled) != CFBooleanGetTypeID())
+ return NO;
+ double axes[3];
+ NSArray *keys = @[@"x", @"y", @"z"];
+ for (NSUInteger index = 0; index < 3; index++) {
+ id axis = value[keys[index]];
+ if (!VPhoneGyroscopeNumber(axis))
+ return NO;
+ axes[index] = [axis doubleValue];
+ if (!isfinite(axes[index]) || fabs(axes[index]) > 1000)
+ return NO;
+ }
+ *state = (VPhoneGyroscopeState){[enabled boolValue], axes[0], axes[1], axes[2]};
+ return YES;
+}
+
+static inline NSDictionary *VPhoneGyroscopeEncode(VPhoneGyroscopeState state) {
+ return @{@"enabled": @(state.enabled), @"x": @(state.x), @"y": @(state.y), @"z": @(state.z)};
+}
+
+// HID report interval, microseconds. Zero means there are no subscribers.
+static inline uint64_t VPhoneGyroscopeInterval(id value) {
+ if (!VPhoneGyroscopeNumber(value))
+ return 0;
+ double interval = [value doubleValue];
+ if (!isfinite(interval) || interval <= 0)
+ return 0;
+ return (uint64_t)fmin(1000000, fmax(5000, interval));
+}
diff --git a/VPhoneGuestComponents/Gyroscope/libvphonegyro.m b/VPhoneGuestComponents/Gyroscope/libvphonegyro.m
new file mode 100644
index 00000000..c96df1a9
--- /dev/null
+++ b/VPhoneGuestComponents/Gyroscope/libvphonegyro.m
@@ -0,0 +1,211 @@
+#import "VPhoneGyroscopeHID.h"
+#import "VPhoneGyroscopeState.h"
+#include <dlfcn.h>
+#include <mach/mach_time.h>
+#include <notify.h>
+#include <unistd.h>
+
+// MARK: - HID provider in backboardd
+
+@interface VPhoneGyroscopeProvider : NSObject
+@property (nonatomic, strong) dispatch_queue_t queue;
+@property (nonatomic, strong) dispatch_source_t timer;
+@property (nonatomic, strong) id<VPhoneGyroscopeHIDService> service;
+@property (nonatomic) Class<VPhoneGyroscopeHIDEvent> eventClass;
+@property (nonatomic, strong) NSMutableDictionary *properties;
+@property (nonatomic) VPhoneGyroscopeState state;
+@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;
+@end
+
+@implementation VPhoneGyroscopeProvider
+
+- (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": VPhoneGyroscopeEncode(self.state),
+ };
+ CFPreferencesSetValue(CFSTR(VP_GYRO_STATUS), (__bridge CFDictionaryRef)status,
+ CFSTR(VP_GYRO_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+ CFPreferencesSynchronize(CFSTR(VP_GYRO_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+}
+
+- (void)readConfiguration {
+ CFPreferencesSynchronize(CFSTR(VP_GYRO_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);
+ id value = CFBridgingRelease(CFPreferencesCopyValue(CFSTR(VP_GYRO_CONFIGURATION),
+ CFSTR(VP_GYRO_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost));
+ VPhoneGyroscopeState state;
+ VPhoneGyroscopeDecode(value, &state);
+ self.state = state;
+ [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);
+}
+
+- (id)sample {
+ VPhoneGyroscopeState state = self.state;
+ // Clearing simulation gives the stationary sensor's zero rate. The HID
+ // service stays present, so an already running client's subscription is
+ // preserved and the next set does not require reopening CMMotionManager.
+ id event = [self.eventClass gyroEvent:mach_absolute_time()
+ x:state.enabled ? state.x : 0
+ y:state.enabled ? state.y : 0
+ z:state.enabled ? state.z : 0 options:0];
+ if (event)
+ [(id<VPhoneGyroscopeHIDEvent>)event setGyroSequence:self.sequence++];
+ return event;
+}
+
+- (void)createService {
+ self.enumerated = NO;
+ self.cancelling = NO;
+ self.interval = 0;
+ self.properties[@"ReportInterval"] = @0;
+ self.service = (id<VPhoneGyroscopeHIDService>)[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 VPhoneGyroscopeProvider *weakSelf = self;
+ [self.service setCancelHandler:^{
+ VPhoneGyroscopeProvider *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)start {
+ void *hid = dlopen("/System/Library/PrivateFrameworks/HID.framework/HID", RTLD_NOW | RTLD_LOCAL);
+ self.eventClass = (Class<VPhoneGyroscopeHIDEvent>)NSClassFromString(@"HIDEvent");
+ Class serviceClass = NSClassFromString(@"HIDVirtualEventService");
+ if (!hid || !serviceClass ||
+ ![self.eventClass respondsToSelector:@selector(gyroEvent:x:y:z:options:)] ||
+ ![(Class)self.eventClass instancesRespondToSelector:@selector(setGyroSequence:)] ||
+ ![serviceClass instancesRespondToSelector:@selector(dispatchEvent:)]) {
+ self.lastError = @"Required HID virtual-service API unavailable";
+ NSLog(@"[vphone-gyro] %@", self.lastError);
+ [self publishStatus];
+ return;
+ }
+ self.properties = [@{
+ @"PrimaryUsagePage": @0xff00, @"PrimaryUsage": @9,
+ @"DeviceUsagePairs": @[@{@"DeviceUsagePage": @0xff00, @"DeviceUsage": @9}],
+ @"Product": @"VPhone 3D Gyroscope", @"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_GYRO_NOTIFICATION, &_notificationToken, self.queue,
+ ^(int token) { [self readConfiguration]; });
+ if (status != NOTIFY_STATUS_OK) {
+ self.lastError = @"Gyroscope 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 {
+ id event = [self sample];
+ if (event && [self.service dispatchEvent:event]) {
+ self.dispatched++;
+ } else {
+ self.failures++;
+ self.lastError = @"HID event dispatch failed";
+ }
+ }
+ });
+ [self updateTimer];
+ dispatch_resume(self.timer);
+ [self createService];
+ [self heartbeat];
+}
+
+- (void)heartbeat {
+ [self publishStatus];
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), self.queue, ^{ [self heartbeat]; });
+}
+
+// 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 ([key isEqualToString:@"ReportInterval"]) {
+ self.interval = VPhoneGyroscopeInterval(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 self.enumerated && (!type || type.unsignedIntValue == 0x14) ? [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-gyro] HID service enumerated: %llu", self.service.serviceID);
+ } 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 VPhoneGyroscopeStart(void) {
+ // SystemHook loads this only into backboardd, the mobile user's HID host.
+ // Starting asynchronously avoids synchronously calling the HID server
+ // while its daemon is still running image constructors.
+ if (strcmp(getprogname(), "backboardd") != 0)
+ return;
+ static VPhoneGyroscopeProvider *provider;
+ provider = [VPhoneGyroscopeProvider new];
+ provider.queue = dispatch_queue_create("com.vphone.motion.gyroscope", DISPATCH_QUEUE_SERIAL);
+ dispatch_async(provider.queue, ^{ [provider start]; });
+}
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index 53188f7b..3340703d 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -83,6 +83,9 @@ PREFSFIX_INCLUDES := $(wildcard PrefsFix/*.h)
SIGNINFIX := $(STAGE)/signinfix/libsigninfix.dylib
SIGNINFIX_SOURCES := $(wildcard SignInFix/*.m SignInFix/*.c)
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)
GPU_PLUGIN := $(STAGE)/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib
GPU_PLUGIN_SOURCES := $(wildcard GraphicLoader/*.mm)
GPU_PLUGIN_INCLUDES := $(wildcard GraphicLoader/*.h GraphicLoader/*.hpp GraphicLoader/*.inc)
@@ -116,7 +119,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) $(GPU_PLUGIN) $(VIRTIOSOUND)
+ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(DEVICENAME) $(PREFSFIX) $(SIGNINFIX) $(GYROSCOPE) $(GPU_PLUGIN) $(VIRTIOSOUND)
PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist \
$(STAGE)/misfix/libmisfix.plist
GPU_PROVENANCE := $(STAGE)/gpu/README.md
@@ -131,7 +134,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 gpu virtiosound
+ @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix devicename prefsfix signinfix gyroscope gpu virtiosound
@echo "Packaged $(ARCHIVE)"
test-loader-links:
@@ -191,7 +194,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)/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)/gpu $(STAGE)/virtiosound:
@mkdir -p $@
$(CAMFIX): $(CAMFIX_SOURCES) $(CAMFIX_INPUTS) | $(STAGE)/camfix
@@ -278,6 +281,20 @@ $(SIGNINFIX): $(SIGNINFIX_SOURCES) $(SIGNINFIX_INCLUDES) SignInFix | $(STAGE)/si
-Wl,-not_for_dyld_shared_cache
@codesign --force --sign - $@
+$(GYROSCOPE): $(GYROSCOPE_SOURCES) $(GYROSCOPE_INPUTS) | $(STAGE)/gyroscope
+ $(CLANG) -arch arm64e -miphoneos-version-min=18.0 -Os -fobjc-arc \
+ -Wall -Wextra -Werror -Wno-unused-parameter -dynamiclib \
+ -install_name /usr/lib/libvphonegyro.dylib -o $@ $(GYROSCOPE_SOURCES) \
+ -framework Foundation -Wl,-not_for_dyld_shared_cache
+ @codesign --force --sign - $@
+
+.PHONY: test-gyroscope
+test-gyroscope:
+ @mkdir -p $(OUT)
+ xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -IGyroscope \
+ -o $(OUT)/GyroscopeTests Tests/GyroscopeTests.m -framework Foundation
+ @$(OUT)/GyroscopeTests
+
$(STAGE)/misfix/libmisfix.plist: MISFix/libmisfix.plist | $(STAGE)/misfix
@cp $< $@
diff --git a/VPhoneGuestComponents/README.md b/VPhoneGuestComponents/README.md
index 0c47428e..3e35d122 100644
--- a/VPhoneGuestComponents/README.md
+++ b/VPhoneGuestComponents/README.md
@@ -12,6 +12,7 @@ tweak filter plists, and the GPU provenance note:
| Battery health fix | `batteryhealthfix/libbatteryhealthfix.dylib` |
| DeviceHub fix | `devicehubfix/libdevicehubfix.dylib` |
| Device name pin | `devicename/libdevicename.dylib` |
+| Virtual gyroscope | `gyroscope/libvphonegyro.dylib` |
| Launchd hook | `launchhook/launchdhook-vphone.dylib` |
| Process injection bridge | `systemhook/SystemHook-vphone.dylib` |
| iOS 27 app registrar | `vpregister/vpregister` |
@@ -58,6 +59,13 @@ Apple GPU binary is stored in this directory, the archive, or the shipped app.
See `Research/Guest/virtual_camera_transport.md` for the camera transport
validation and the hook installation prerequisites.
+`system-backboardd-cfw-gyroscope` installs the optional gyro provider into
+`/usr/lib`. SystemHook loads it only in backboardd; it publishes a HID service
+using vphoned's `motion.gyroscope.set/get/clear` configuration. A live update
+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`.
+
The virtio sound plugin is the CoreAudio half of the VM's virtio-snd device,
which iOS ships no driver for. audiomxd loads it when the kernel publishes
`AppleVirtIOSound`, and it publishes a speaker and a microphone device.
diff --git a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
index f0f4811e..04486e68 100644
--- a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
+++ b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
@@ -39,11 +39,15 @@ 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) {
+ return vpPathHasSuffix(path, "/usr/libexec/backboardd");
+}
+
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) ||
+ return vpIsBootstrapPath(path, root) || vpIsAppPath(path) || vpIsCameraDaemon(path) || vpIsGyroscopeDaemon(path) ||
(vpInBootstrap && path[0] != '/');
}
@@ -149,6 +153,7 @@ static int vpExecve(const char *path, char *const argv[], char *const envp[]) {
// They need no tweak loader: each installs its own Objective-C hooks.
#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_AVFOUNDATION "/System/Library/Frameworks/AVFoundation.framework/AVFoundation"
// The haptics fix rides the same route and needs no loader of its own. See
// HapticsFix/libhapticsfix.c for what it answers and why SpringBoard is the
@@ -210,7 +215,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)
+ int fd = vpInXPCProxy || vpInBootstrap || vpIsAppPath(path) || vpIsCameraDaemon(path) || vpIsGyroscopeDaemon(path)
? vpOpenLog("vphone-systemhook.log")
: -1;
if (fd >= 0) {
@@ -232,6 +237,10 @@ __attribute__((constructor)) static void vpLogProcess(void) {
vpLoadLibrary("camera-hook", VP_CAMERA_DAEMON_HOOK);
return;
}
+ if (vpIsGyroscopeDaemon(path)) {
+ vpLoadLibrary("gyroscope-hook", VP_GYROSCOPE_HOOK);
+ return;
+ }
// Loaded before the app gate: SpringBoard is neither an app path nor a
// bootstrap executable, and the swizzle has to be in place before UIKit
// first asks CoreHaptics for an engine.
diff --git a/VPhoneGuestComponents/Tests/GyroscopeTests.m b/VPhoneGuestComponents/Tests/GyroscopeTests.m
new file mode 100644
index 00000000..b7fd248e
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/GyroscopeTests.m
@@ -0,0 +1,66 @@
+#import "VPhoneGyroscopeState.h"
+#import "VPhoneGyroscopeHID.h"
+#include <assert.h>
+#include <dlfcn.h>
+#include <float.h>
+#include <stdio.h>
+
+int main(void) {
+ @autoreleasepool {
+ VPhoneGyroscopeState state;
+ NSDictionary *sample = @{@"enabled": @YES, @"x": @1.25, @"y": @-2.5, @"z": @0.125};
+ // The transport is a property list, including a real Boolean. Test
+ // after serialization, as cfprefsd crosses a process boundary.
+ NSData *wire = [NSPropertyListSerialization dataWithPropertyList:sample
+ format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];
+ id decoded = [NSPropertyListSerialization propertyListWithData:wire options:0 format:nil error:nil];
+ assert(VPhoneGyroscopeDecode(decoded, &state));
+ assert(state.enabled && state.x == 1.25 && state.y == -2.5 && state.z == 0.125);
+ assert([VPhoneGyroscopeEncode(state) isEqual:sample]);
+
+ for (id invalid in @[@YES, @"1", NSNull.null, @(NAN), @(INFINITY), @1001, @-1001]) {
+ NSMutableDictionary *bad = [sample mutableCopy];
+ bad[@"y"] = invalid;
+ assert(!VPhoneGyroscopeDecode(bad, &state));
+ assert(!state.enabled && state.x == 0 && state.y == 0 && state.z == 0);
+ }
+ for (NSString *key in @[@"enabled", @"x", @"y", @"z"]) {
+ NSMutableDictionary *bad = [sample mutableCopy];
+ [bad removeObjectForKey:key];
+ assert(!VPhoneGyroscopeDecode(bad, &state));
+ }
+ NSMutableDictionary *badFlag = [sample mutableCopy];
+ badFlag[@"enabled"] = @1;
+ assert(!VPhoneGyroscopeDecode(badFlag, &state));
+ assert(!VPhoneGyroscopeDecode(nil, &state));
+ assert(!VPhoneGyroscopeDecode(@[], &state));
+ assert(VPhoneGyroscopeDecode(@{@"enabled": @NO, @"x": @0, @"y": @0, @"z": @0}, &state));
+ assert(!state.enabled);
+ // A hostile or broken client interval must not produce an unbounded
+ // timer, overflow nanoseconds, or keep streaming after unsubscribe.
+ assert(VPhoneGyroscopeInterval(@500) == 5000);
+ assert(VPhoneGyroscopeInterval(@20000) == 20000);
+ assert(VPhoneGyroscopeInterval(@(DBL_MAX)) == 1000000);
+ for (id interval in @[@0, @-1, @YES, @"5000", @(NAN), @(INFINITY), NSNull.null])
+ assert(VPhoneGyroscopeInterval(interval) == 0);
+ puts("Gyroscope transport tests passed");
+
+ // Exercise the real HID factory without creating/publishing a host
+ // service. This verifies our ObjC ABI and signed axis representation.
+ void *hid = dlopen("/System/Library/PrivateFrameworks/HID.framework/HID", RTLD_NOW | RTLD_LOCAL);
+ assert(hid);
+ Class<VPhoneGyroscopeHIDEvent> eventClass = (Class<VPhoneGyroscopeHIDEvent>)NSClassFromString(@"HIDEvent");
+ assert([eventClass respondsToSelector:@selector(gyroEvent:x:y:z:options:)]);
+ id<VPhoneGyroscopeHIDEvent> event = [eventClass gyroEvent:123456789 x:1.25 y:-2.5 z:0.125 options:0];
+ assert(event && event.timestamp == 123456789);
+ assert(event.gyroX == 1.25 && event.gyroY == -2.5 && event.gyroZ == 0.125);
+ [event setGyroSequence:42];
+ assert(event.gyroSequence == 42);
+ event = [eventClass gyroEvent:123456790 x:0.1234567 y:-0.1234567 z:1000 options:0];
+ assert(fabs(event.gyroX - 0.1234567) < 1.0 / 65536);
+ assert(fabs(event.gyroY + 0.1234567) < 1.0 / 65536);
+ assert(event.gyroZ == 1000 && event.timestamp == 123456790);
+ puts("Gyroscope HID event factory tests passed");
+ }
+ return 0;
+}
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
index 91437557..7b55ba01 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
@@ -18,5 +18,10 @@ public enum VPhoneGuestEnvironment {
"libdevicename.dylib",
"libprefsfix.dylib",
"libsigninfix.dylib",
+ "libvphonegyro.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"]
}