Run a virtual iPhone on an Apple Silicon Mac.
Swift
Add guest device attitude simulation
Phineas Guoe36f5379bd21
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex d169a293..6f931b8c 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -253,6 +253,19 @@> platform capability gate and optional IMU match still require guest proof.> Reveal evidence and manual acceptance: `Research/Guest/virtual_gyroscope.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+> into apps, with no system executable, kernel or DSC byte change. Public+> CMMotionManager methods supply a stationary XArbitraryZVertical pose through+> polling/callbacks. vphoned persists degrees and publishes one packed Darwin+> notify state; apps receive radians, quaternion, matrix and matching gravity.+> Disabling restores the native path; removing the library and relaunching apps+> reverts injection. Live sync cannot reinstall an absent selected library.+> Native host subscription tests and guest cross-compilation passed;+> manual guest acceptance remains.+> Contract and validation: `Research/Guest/virtual_attitude.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_attitude.md b/Research/Guest/virtual_attitude.mdnew file mode 100644index 00000000..63200cbf--- /dev/null+++ b/Research/Guest/virtual_attitude.md@@ -0,0 +1,86 @@+# Device attitude simulation++## Core contract++vphoned capability `motion_attitude` exposes `motion.attitude.get`,+`motion.attitude.set {roll,pitch,yaw,enabled?}` and `motion.attitude.clear`.+Set requires finite JSON numbers: roll/yaw in [-180,180] degrees, pitch in+[-90,90]. Booleans, strings, missing/non-finite/out-of-range angles are rejected.+`enabled` must be a Boolean and defaults to true. Clear disables and zeros;+set with enabled=false retains angles.++RPC uses degrees; Core Motion uses radians. Zero is face-up, gravity (0,0,-1)+g. Pitch is about X, roll about Y, yaw about Z: R = Rz(yaw) Rx(pitch) Ry(roll).+Pitch ±90° makes Euler roll/yaw singular; quaternion/matrix remain well-defined.++This is a stationary pose, independent of raw gyro simulation. Device motion+supplies attitude, corresponding gravity, zero rotation rate/user acceleration,+an uncalibrated zero magnetic field and invalid heading (-1). Changing angles+does not synthesize angular velocity or UIKit/display orientation changes.++## Injection and transport++Guest System declares `system-apps-cfw-attitude`, selected by both presets on+iOS 18+. It adds `/usr/lib/libvphoneattitude.dylib`. SystemHook loads it into+apps before the optional tweak loader; no bootstrap or new daemon is required.+Safe-mode/injection-disable flags still apply. No system executable, kernel or+DSC bytes change. This intercepts the app's public Core Motion boundary;+it does not claim that raw gyro HID events are fused attitude samples.++All four CMMotionManager device-motion start methods, stop, interval, polling,+availability, active state and reference-frame getters are covered. Only+XArbitraryZVertical is simulated/advertised. Corrected/magnetic/true-north+requests keep the native path. Enable simulation before launching an app whose+availability check would otherwise prevent subscription.++Per-manager timers honor intervals at 1–200 Hz (unset: 60 Hz). Callbacks run on+the app's NSOperationQueue, outside session locks. At most one simulated+delivery is queued; a suspended queue cannot accumulate samples. Generations+discard deliveries after stop/restart/mode changes. Samples support independent+copies, secure coding and relative quaternion multiplication. Weak timer+captures and cancellation prevent a timer retaining a released manager.+Enabling/disabling an existing subscription switches between simulation and+retained native implementations, including native availability when disabled.++vphoned serializes publication/readback and persists one dictionary,+`VPhoneAttitudeConfiguration`, in mobile's `com.apple.backboardd` preferences.+It packs angles and enabled in one 64-bit Darwin notification state,+`com.vphone.motion.attitude.changed`. Apps read this atomic state without+cross-sandbox preferences/file access. Transport quantizes to 0.001° (maximum+0.0005° error); persisted/RPC values retain input precision. vphoned seeds+notifyd at startup; new app readers immediately read the latest state.++`provider_installed` only reports the dylib's presence. It does not prove a+target app loaded the hook or received samples. Check SystemHook's app-PID+`attitude-hook=... result=loaded` log and the actual Core Motion consumer.++## Selection and verification++cfw install/update-environment follows selection and records the guest receipt.+No-plan legacy VMs do not opt in. Blocking removes the added file; live hash+sync replaces installed selected copies only. Relaunch apps after changing the+library. A changed SystemHook still requires reboot; no UI daemon is restarted+for attitude updates.++Host checks: `make -C VPhoneGuestComponents test-attitude` tests malformed+configuration, packed-state boundaries, quaternion/matrix/gravity, copy,+relative attitude and secure coding. Its real host Core Motion runtime test+covers all start overloads, polling, callback delivery, live toggle, snapshots,+interval setting, bounded backlog and suppression after stop, using a separate+Darwin notification name. Catalogue tests cover version gating, blocking,+preset reachability and manifest invariants.++2026-10-08: sample and live hook tests passed, and 55 catalogue/model tests+in seven suites passed. The complete bundle built successfully; bundle+admission and strict deep signature verification passed.++Guest acceptance is manual, as requested: update guest, relaunch a consumer,+enable simulation, compare polling/callback Euler radians, quaternion and+gravity at zero and single-axis 90° poses. Check reset/disable while subscribed,+stopped-manager silence, and relaunch after blocking the patch. Host runtime+checks do not establish guest injection/sandbox acceptance or every app's API.++ABI sources: Xcode iPhoneOS SDK CMMotionManager.h, CMAttitude.h, CMDeviceMotion.h,+system notify.h, Apple [CMAttitude](https://developer.apple.com/documentation/coremotion/cmattitude)+and [CMDeviceMotion](https://developer.apple.com/documentation/coremotion/cmdevicemotion).+No Hopper-derived offset or private initializer is used.diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex 8f48940c..5df61382 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -297,6 +297,7 @@ request carries `"force": true`.| 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,enabled?}`, `motion.gyroscope.clear` (capability `motion_gyroscope`; finite JSON numbers in [-1000,1000] rad/s, all axes required; `enabled` defaults to true and must be a JSON Boolean; capability `motion_gyroscope_toggle` supports disabling while retaining configured axes; 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` |+| Device attitude | `motion.attitude.get`, `motion.attitude.set {roll,pitch,yaw,enabled?}`, `motion.attitude.clear` (capability `motion_attitude`; degrees: roll/yaw [-180,180], pitch [-90,90], all finite JSON numbers required; `enabled` defaults to true, false retains angles; clear disables and zeros; returns configuration, `units`, `reference_frame`, `provider_installed`; stationary XArbitraryZVertical Core Motion pose; library presence does not prove app delivery; see `Guest/virtual_attitude.md`) || 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) || Environment | `environment.status` (SHA-256 of each vphone library in `/usr/lib`, or null when absent, plus the staging directory), `environment.install {libraries: [{name, sha256}]}` (see below) |diff --git a/VPhoneDaemon/Daemon/GuestAPI+Attitude.swift b/VPhoneDaemon/Daemon/GuestAPI+Attitude.swiftnew file mode 100644index 00000000..abd5db55--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestAPI+Attitude.swift@@ -0,0 +1,39 @@+import CoreFoundation+import Foundation+import VphonedNative++// MARK: - Device Attitude++extension GuestAPI {+ private static let attitudeLock = NSLock()++ static func executeAttitude(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {+ guard ["motion.attitude.get", "motion.attitude.set", "motion.attitude.clear"].contains(method) else { return nil }+ attitudeLock.lock()+ defer { attitudeLock.unlock() }+ if method != "motion.attitude.get" {+ var angles = [Double](repeating: 0, count: 3)+ var enabled = method == "motion.attitude.set"+ if method == "motion.attitude.set" {+ if let flag = params["enabled"] {+ guard let number = flag as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() else {+ throw GuestAPIError.invalidRequest("enabled must be a boolean")+ }+ enabled = number.boolValue+ }+ for (index, key) in ["roll", "pitch", "yaw"].enumerated() {+ let limit = index == 1 ? 90.0 : 180.0+ guard let number = params[key] as? NSNumber,+ CFGetTypeID(number) != CFBooleanGetTypeID(), number.doubleValue.isFinite,+ abs(number.doubleValue) <= limit+ else { throw GuestAPIError.invalidRequest("\(key) must be a number between -\(limit) and \(limit) degrees") }+ angles[index] = number.doubleValue+ }+ }+ guard vp_attitude_set(angles[0], angles[1], angles[2], enabled) else {+ throw GuestAPIError.operationFailed("Could not publish the attitude configuration")+ }+ }+ return vp_attitude_get() as? [String: Any] ?? [:]+ }+}diff --git a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift b/VPhoneDaemon/Daemon/GuestAPI+Environment.swiftindex fdcad8b6..4f180c76 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",+ "libvphoneattitude.dylib",]static let environmentStaging = "/var/root/Library/Caches/vphone-environment"@@ -58,8 +59,8 @@ 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")+ if ["libvphonegyro.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)guard let data = try? Data(contentsOf: staged, options: .mappedIfSafe) else {diff --git a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift b/VPhoneDaemon/Daemon/GuestAPI+Extended.swiftindex efbb088a..28f91e82 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift@@ -19,6 +19,7 @@ extension GuestAPI {executeTimeZone,executeAudioLatency,executeGyroscope,+ executeAttitude,]for area in areas {if let result = try area(method, params) {diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex d5dc7cb4..9178e084 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -142,6 +142,7 @@ enum GuestAPI {"audio_host_latency","motion_gyroscope","motion_gyroscope_toggle",+ "motion_attitude",],]}diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.hindex fd160d12..b45c5a7e 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -60,6 +60,8 @@ char *vp_usb_own_serial(void);/// 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);+NSDictionary *vp_attitude_get(void);+BOOL vp_attitude_set(double roll, double pitch, double yaw, 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_attitude.m b/VPhoneDaemon/Native/vphoned_attitude.mnew file mode 100644index 00000000..e69f58fb--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_attitude.m@@ -0,0 +1,47 @@+#import "Include/VphonedNative.h"+#import "../../VPhoneGuestComponents/Attitude/VPhoneAttitudeState.h"+#include <notify.h>+#include <unistd.h>++static VPhoneAttitudeState VPhoneAttitudeRead(void) {+ CFPreferencesSynchronize(CFSTR(VP_ATTITUDE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);+ id value = CFBridgingRelease(CFPreferencesCopyValue(CFSTR(VP_ATTITUDE_CONFIGURATION),+ CFSTR(VP_ATTITUDE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost));+ VPhoneAttitudeState state;+ VPhoneAttitudeDecode(value, &state);+ return state;+}++static BOOL VPhoneAttitudePublish(VPhoneAttitudeState state) {+ static int token, registration = NOTIFY_STATUS_FAILED;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ registration = notify_register_check(VP_ATTITUDE_NOTIFICATION, &token); });+ return registration == NOTIFY_STATUS_OK &&+ notify_set_state(token, VPhoneAttitudePack(state)) == NOTIFY_STATUS_OK &&+ notify_post(VP_ATTITUDE_NOTIFICATION) == NOTIFY_STATUS_OK;+}++NSDictionary *vp_attitude_get(void) {+ VPhoneAttitudeState state = VPhoneAttitudeRead();+ VPhoneAttitudePublish(state);+ NSMutableDictionary *result = [VPhoneAttitudeEncode(state) mutableCopy];+ result[@"units"] = @"degrees";+ result[@"reference_frame"] = @"xArbitraryZVertical";+ result[@"provider_installed"] = @(access("/usr/lib/libvphoneattitude.dylib", R_OK) == 0);+ return result;+}++BOOL vp_attitude_set(double roll, double pitch, double yaw, bool enabled) {+ VPhoneAttitudeState state = {enabled, roll, pitch, yaw}, checked;+ NSDictionary *value = VPhoneAttitudeEncode(state);+ if (!VPhoneAttitudeDecode(value, &checked)) return NO;+ CFPreferencesSetValue(CFSTR(VP_ATTITUDE_CONFIGURATION), (__bridge CFDictionaryRef)value,+ CFSTR(VP_ATTITUDE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost);+ return CFPreferencesSynchronize(CFSTR(VP_ATTITUDE_DOMAIN), CFSTR("mobile"), kCFPreferencesAnyHost) &&+ VPhoneAttitudePublish(state);+}++// Re-seed notifyd after boot/daemon restart before any host editor is opened.+__attribute__((constructor)) static void VPhoneAttitudeInitialize(void) {+ @autoreleasepool { VPhoneAttitudePublish(VPhoneAttitudeRead()); }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex b8944b81..a12c3f9c 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 attitude = "system-apps-cfw-attitude"private static let ios27 = VPhonePatchApplicability(iOSBase: .major(27))@@ -230,6 +231,14 @@ public enum FirmwareGuestSystemPatchSet {applicability: VPhonePatchApplicability(iOSBase: .atLeast(major: 18, minor: 0)),),+ VPhonePatchDeclaration(+ identifier: attitude,+ title: "Device attitude simulation",+ summary: "Installs libvphoneattitude.dylib, loaded by SystemHook into apps. Supplies a stationary Core Motion pose configured through vphoned, with polling and callback updates in the arbitrary vertical reference frame. Disabling simulation restores native motion; removing the library reverts the hook on app relaunch.",+ target: .guestFile(path: "/usr/lib/libvphoneattitude.dylib"),+ applicability: VPhonePatchApplicability(iOSBase: .atLeast(major: 18, minor: 0)),+ ),+// MARK: AudioVPhonePatchDeclaration(diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swiftindex cad828cb..d55829dc 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift@@ -17,8 +17,8 @@ import VPhonePatchKit@Suite("Bundled patch set catalogue")struct FirmwarePatchSetCatalogTests {- @Test func `Gyroscope follows selection and its deployment target`() throws {- let identifier = FirmwareGuestSystemPatchSet.gyroscope+ @Test(arguments: [FirmwareGuestSystemPatchSet.gyroscope, 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(preset: FirmwarePatchSetCatalog.standardPreset,diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 6e7f956b..b9b3d6c8 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -1004,11 +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 and the gyroscope still require an explicit plan.+ /// preferences and motion sensors still require an explicit plan.func on(_ identifier: String) -> Bool {guard let plan else {return !FirmwareGuestSystemPatchSet.settingsRowPatches.contains(identifier)&& identifier != FirmwareGuestSystemPatchSet.gyroscope+ && identifier != FirmwareGuestSystemPatchSet.attitude}guard plan.isEnabled(identifier) else {print(" [·] \(identifier): off in preset \(plan.presetIdentifier)")@@ -1117,16 +1118,20 @@ 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)+ for (identifier, library) in [+ (FirmwareGuestSystemPatchSet.gyroscope, "libvphonegyro.dylib"),+ (FirmwareGuestSystemPatchSet.attitude, "libvphoneattitude.dylib"),+ ] {+ isolate([identifier]) {+ let path = "usr/lib/" + library+ if on(identifier) {+ try system.replaceFile(path, fromFileAt: VPhoneGuestBinaries.resolve(library),+ mode: 0o755, owner: Self.guestOwner)+ live.insert(identifier)+ } else {+ // Removing vphone's added library reverts its injection.+ try system.removeItem(path)+ }}}diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.shindex 61a1c856..bca72547 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh@@ -80,6 +80,7 @@ fi/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/attitude/libvphoneattitude.dylib" "$guest/libvphoneattitude.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 sodiff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.shindex 824791aa..04242e02 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh@@ -95,7 +95,7 @@ donefor 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 libvphonegyro.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do+ libprefsfix.dylib libsigninfix.dylib libvphonegyro.dylib libvphoneattitude.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; dorequire_signed_macho "$guest/$name"donefor name in vphoned.plist libcamfix.plist libvcamcaptured.plist libmisfix.plist; dodiff --git a/VPhoneGuestComponents/Attitude/VPhoneAttitudeMotionManager.h b/VPhoneGuestComponents/Attitude/VPhoneAttitudeMotionManager.hnew file mode 100644index 00000000..540efc39--- /dev/null+++ b/VPhoneGuestComponents/Attitude/VPhoneAttitudeMotionManager.h@@ -0,0 +1,18 @@+#pragma once+#import <CoreMotion/CoreMotion.h>++// Public CMMotionManager selectors, sent through the runtime so the same+// injection can be exercised on a host whose SDK hides this iOS class.+@protocol VPhoneAttitudeMotionManager <NSObject>+@property (nonatomic) NSTimeInterval deviceMotionUpdateInterval;+@property (readonly, getter=isDeviceMotionAvailable) BOOL deviceMotionAvailable;+@property (readonly, getter=isDeviceMotionActive) BOOL deviceMotionActive;+@property (readonly) CMDeviceMotion *deviceMotion;+@property (readonly) CMAttitudeReferenceFrame attitudeReferenceFrame;++ (CMAttitudeReferenceFrame)availableAttitudeReferenceFrames;+- (void)startDeviceMotionUpdates;+- (void)startDeviceMotionUpdatesUsingReferenceFrame:(CMAttitudeReferenceFrame)frame;+- (void)startDeviceMotionUpdatesToQueue:(NSOperationQueue *)queue withHandler:(CMDeviceMotionHandler)handler;+- (void)startDeviceMotionUpdatesUsingReferenceFrame:(CMAttitudeReferenceFrame)frame toQueue:(NSOperationQueue *)queue withHandler:(CMDeviceMotionHandler)handler;+- (void)stopDeviceMotionUpdates;+@enddiff --git a/VPhoneGuestComponents/Attitude/VPhoneAttitudeSample.h b/VPhoneGuestComponents/Attitude/VPhoneAttitudeSample.hnew file mode 100644index 00000000..b8c814a6--- /dev/null+++ b/VPhoneGuestComponents/Attitude/VPhoneAttitudeSample.h@@ -0,0 +1,12 @@+#pragma once+#import <CoreMotion/CoreMotion.h>+#import "VPhoneAttitudeState.h"++// A stationary pose in XArbitraryZVertical. No magnetic/true-north claim.+@interface VPhoneAttitude : CMAttitude+- (instancetype)initWithState:(VPhoneAttitudeState)state;+@end++@interface VPhoneAttitudeSample : CMDeviceMotion+- (instancetype)initWithState:(VPhoneAttitudeState)state timestamp:(NSTimeInterval)timestamp;+@enddiff --git a/VPhoneGuestComponents/Attitude/VPhoneAttitudeSample.m b/VPhoneGuestComponents/Attitude/VPhoneAttitudeSample.mnew file mode 100644index 00000000..742ab3bc--- /dev/null+++ b/VPhoneGuestComponents/Attitude/VPhoneAttitudeSample.m@@ -0,0 +1,115 @@+#import "VPhoneAttitudeSample.h"++// MARK: - Attitude snapshots++@interface VPhoneAttitude ()+@property (nonatomic) CMQuaternion value;+@end++@implementation VPhoneAttitude+- (instancetype)initWithState:(VPhoneAttitudeState)state {+ if ((self = [super init])) {+ // Core Motion: pitch about X, roll about Y, yaw about Z.+ // R = Rz(yaw) Rx(pitch) Ry(roll), in radians.+ double r = state.roll * M_PI / 360, p = state.pitch * M_PI / 360, y = state.yaw * M_PI / 360;+ double cr = cos(r), sr = sin(r), cp = cos(p), sp = sin(p), cy = cos(y), sy = sin(y);+ _value = (CMQuaternion){cy * sp * cr - sy * cp * sr,+ cy * cp * sr + sy * sp * cr,+ cy * sp * sr + sy * cp * cr,+ cy * cp * cr - sy * sp * sr};+ }+ return self;+}+- (CMQuaternion)quaternion { return self.value; }+- (CMRotationMatrix)rotationMatrix {+ CMQuaternion q = self.value;+ return (CMRotationMatrix){1-2*(q.y*q.y+q.z*q.z), 2*(q.x*q.y-q.z*q.w), 2*(q.x*q.z+q.y*q.w),+ 2*(q.x*q.y+q.z*q.w), 1-2*(q.x*q.x+q.z*q.z), 2*(q.y*q.z-q.x*q.w),+ 2*(q.x*q.z-q.y*q.w), 2*(q.y*q.z+q.x*q.w), 1-2*(q.x*q.x+q.y*q.y)};+}+- (double)roll { CMRotationMatrix m = self.rotationMatrix; return atan2(-m.m31, m.m33); }+- (double)pitch { return asin(fmax(-1, fmin(1, self.rotationMatrix.m32))); }+- (double)yaw { CMRotationMatrix m = self.rotationMatrix; return atan2(-m.m12, m.m22); }+- (void)multiplyByInverseOfAttitude:(CMAttitude *)attitude {+ CMQuaternion a = self.value, b = attitude.quaternion;+ double norm = b.x*b.x + b.y*b.y + b.z*b.z + b.w*b.w;+ if (!isfinite(norm) || norm <= 0) return;+ b = (CMQuaternion){-b.x/norm, -b.y/norm, -b.z/norm, b.w/norm};+ CMQuaternion q = {a.w*b.x+a.x*b.w+a.y*b.z-a.z*b.y,+ a.w*b.y-a.x*b.z+a.y*b.w+a.z*b.x,+ a.w*b.z+a.x*b.y-a.y*b.x+a.z*b.w,+ a.w*b.w-a.x*b.x-a.y*b.y-a.z*b.z};+ double length = sqrt(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w);+ if (isfinite(length) && length > 0)+ self.value = (CMQuaternion){q.x/length, q.y/length, q.z/length, q.w/length};+}+- (id)copyWithZone:(NSZone *)zone {+ VPhoneAttitude *copy = [[VPhoneAttitude allocWithZone:zone] initWithState:(VPhoneAttitudeState){0}];+ copy.value = self.value;+ return copy;+}++ (BOOL)supportsSecureCoding { return YES; }+- (void)encodeWithCoder:(NSCoder *)coder {+ [coder encodeDouble:self.value.x forKey:@"x"]; [coder encodeDouble:self.value.y forKey:@"y"];+ [coder encodeDouble:self.value.z forKey:@"z"]; [coder encodeDouble:self.value.w forKey:@"w"];+}+- (instancetype)initWithCoder:(NSCoder *)coder {+ if ((self = [self initWithState:(VPhoneAttitudeState){0}])) {+ CMQuaternion q = {[coder decodeDoubleForKey:@"x"], [coder decodeDoubleForKey:@"y"],+ [coder decodeDoubleForKey:@"z"], [coder decodeDoubleForKey:@"w"]};+ double norm = sqrt(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w);+ if (!isfinite(norm) || norm <= 0) return nil;+ self.value = (CMQuaternion){q.x/norm, q.y/norm, q.z/norm, q.w/norm};+ }+ return self;+}+@end++// MARK: - Stationary device motion++@interface VPhoneAttitudeSample ()+@property (nonatomic, strong) VPhoneAttitude *pose;+@property (nonatomic) NSTimeInterval sampleTime;+@end++@implementation VPhoneAttitudeSample+- (instancetype)initWithState:(VPhoneAttitudeState)state timestamp:(NSTimeInterval)timestamp {+ if ((self = [super init])) {+ _pose = [[VPhoneAttitude alloc] initWithState:state];+ _sampleTime = timestamp;+ }+ return self;+}+- (CMAttitude *)attitude { return self.pose; }+- (NSTimeInterval)timestamp { return self.sampleTime; }+- (CMAcceleration)gravity {+ CMRotationMatrix m = self.pose.rotationMatrix;+ return (CMAcceleration){-m.m31, -m.m32, -m.m33};+}+- (CMAcceleration)userAcceleration { return (CMAcceleration){0}; }+- (CMRotationRate)rotationRate { return (CMRotationRate){0}; }+- (CMCalibratedMagneticField)magneticField {+ return (CMCalibratedMagneticField){{0}, CMMagneticFieldCalibrationAccuracyUncalibrated};+}+- (double)heading { return -1; }+- (double)headingAccuracy { return -1; }+- (CMDeviceMotionSensorLocation)sensorLocation { return CMDeviceMotionSensorLocationDefault; }+- (id)copyWithZone:(NSZone *)zone {+ VPhoneAttitudeSample *copy = [[VPhoneAttitudeSample allocWithZone:zone]+ initWithState:(VPhoneAttitudeState){0} timestamp:self.sampleTime];+ copy.pose = [self.pose copy];+ return copy;+}++ (BOOL)supportsSecureCoding { return YES; }+- (void)encodeWithCoder:(NSCoder *)coder {+ [coder encodeObject:self.pose forKey:@"pose"];+ [coder encodeDouble:self.sampleTime forKey:@"timestamp"];+}+- (instancetype)initWithCoder:(NSCoder *)coder {+ if ((self = [self initWithState:(VPhoneAttitudeState){0} timestamp:[coder decodeDoubleForKey:@"timestamp"]])) {+ self.pose = [coder decodeObjectOfClass:VPhoneAttitude.class forKey:@"pose"];+ if (!self.pose || !isfinite(self.sampleTime)) return nil;+ }+ return self;+}+@enddiff --git a/VPhoneGuestComponents/Attitude/VPhoneAttitudeState.h b/VPhoneGuestComponents/Attitude/VPhoneAttitudeState.hnew file mode 100644index 00000000..c1593e20--- /dev/null+++ b/VPhoneGuestComponents/Attitude/VPhoneAttitudeState.h@@ -0,0 +1,55 @@+#pragma once+#import <Foundation/Foundation.h>+#include <math.h>++#define VP_ATTITUDE_DOMAIN "com.apple.backboardd"+#define VP_ATTITUDE_CONFIGURATION "VPhoneAttitudeConfiguration"+#ifndef VP_ATTITUDE_NOTIFICATION+#define VP_ATTITUDE_NOTIFICATION "com.vphone.motion.attitude.changed"+#endif++typedef struct {+ BOOL enabled;+ double roll, pitch, yaw; // Degrees at the RPC boundary; Core Motion uses radians.+} VPhoneAttitudeState;++static inline BOOL VPhoneAttitudeDecode(id value, VPhoneAttitudeState *state) {+ *state = (VPhoneAttitudeState){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 angles[3], limits[] = {180, 90, 180};+ NSArray *keys = @[@"roll", @"pitch", @"yaw"];+ for (NSUInteger i = 0; i < 3; i++) {+ id angle = value[keys[i]];+ if (![angle isKindOfClass:NSNumber.class] ||+ CFGetTypeID((__bridge CFTypeRef)angle) == CFBooleanGetTypeID()) return NO;+ angles[i] = [angle doubleValue];+ if (!isfinite(angles[i]) || fabs(angles[i]) > limits[i]) return NO;+ }+ *state = (VPhoneAttitudeState){[enabled boolValue], angles[0], angles[1], angles[2]};+ return YES;+}++static inline NSDictionary *VPhoneAttitudeEncode(VPhoneAttitudeState state) {+ return @{@"enabled": @(state.enabled), @"roll": @(state.roll),+ @"pitch": @(state.pitch), @"yaw": @(state.yaw)};+}++// One notify state holds the complete pose, including enabled. Millidegree+// quantization avoids cross-domain preferences reads by sandboxed apps.+static inline uint64_t VPhoneAttitudePack(VPhoneAttitudeState state) {+ uint64_t roll = (uint64_t)llround((state.roll + 180) * 1000);+ uint64_t pitch = (uint64_t)llround((state.pitch + 90) * 1000);+ uint64_t yaw = (uint64_t)llround((state.yaw + 180) * 1000);+ return (UINT64_C(1) << 63) | ((uint64_t)state.enabled << 56) | (yaw << 37) | (pitch << 19) | roll;+}++static inline VPhoneAttitudeState VPhoneAttitudeUnpack(uint64_t value) {+ if (!(value & (UINT64_C(1) << 63))) return (VPhoneAttitudeState){0};+ uint64_t r = value & 0x7ffff, p = (value >> 19) & 0x3ffff, y = (value >> 37) & 0x7ffff;+ if (r > 360000 || p > 180000 || y > 360000) return (VPhoneAttitudeState){0};+ return (VPhoneAttitudeState){(value >> 56) & 1, r / 1000.0 - 180,+ p / 1000.0 - 90, y / 1000.0 - 180};+}diff --git a/VPhoneGuestComponents/Attitude/libvphoneattitude.m b/VPhoneGuestComponents/Attitude/libvphoneattitude.mnew file mode 100644index 00000000..9f1d23fc--- /dev/null+++ b/VPhoneGuestComponents/Attitude/libvphoneattitude.m@@ -0,0 +1,279 @@+#import "VPhoneAttitudeSample.h"+#import "VPhoneAttitudeMotionManager.h"+#import <objc/runtime.h>+#include <notify.h>++// MARK: - Shared configuration++static NSRecursiveLock *configurationLock;+static NSHashTable *sessions;+static VPhoneAttitudeState configuration;+static int notificationToken;+static char sessionKey;++static VPhoneAttitudeState VPhoneCurrentAttitude(void) {+ [configurationLock lock];+ VPhoneAttitudeState value = configuration;+ [configurationLock unlock];+ return value;+}++// Preserve the actual implementations, including calls they make to each other.+static void (*startPolling)(id, SEL);+static void (*startFramePolling)(id, SEL, CMAttitudeReferenceFrame);+static void (*startCallback)(id, SEL, NSOperationQueue *, CMDeviceMotionHandler);+static void (*startFrameCallback)(id, SEL, CMAttitudeReferenceFrame, NSOperationQueue *, CMDeviceMotionHandler);+static void (*stopUpdates)(id, SEL);+static void (*setInterval)(id, SEL, NSTimeInterval);+static BOOL (*isAvailable)(id, SEL);+static BOOL (*isActive)(id, SEL);+static CMDeviceMotion *(*getMotion)(id, SEL);+static CMAttitudeReferenceFrame (*getFrame)(id, SEL);+static CMAttitudeReferenceFrame (*availableFrames)(id, SEL);++@interface VPhoneAttitudeSession : NSObject+@property (nonatomic, weak) id<VPhoneAttitudeMotionManager> manager;+@property (nonatomic, strong) NSOperationQueue *deliveryQueue;+@property (nonatomic, copy) CMDeviceMotionHandler handler;+@property (nonatomic, strong) dispatch_source_t timer;+@property (nonatomic, strong) CMDeviceMotion *latest;+@property (nonatomic) CMAttitudeReferenceFrame frame;+@property (nonatomic) BOOL active;+@property (nonatomic) BOOL nativeActive;+@property (nonatomic) BOOL invokingNative;+@property (nonatomic) NSUInteger generation;+@property (nonatomic, strong) NSNumber *queuedGeneration;+- (void)refresh;+- (void)reschedule;+- (void)stop;+@end++@implementation VPhoneAttitudeSession+- (BOOL)simulating {+ return self.active && self.frame == CMAttitudeReferenceFrameXArbitraryZVertical && VPhoneCurrentAttitude().enabled;+}+- (void)reschedule {+ @synchronized (self) {+ double interval = self.manager.deviceMotionUpdateInterval;+ if (!isfinite(interval) || interval <= 0) interval = 1.0 / 60;+ uint64_t period = (uint64_t)(fmax(0.005, fmin(1, interval)) * NSEC_PER_SEC);+ if (self.timer) dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, period, NSEC_PER_MSEC);+ }+}+- (void)tick {+ @synchronized (self) {+ if (![self simulating]) return;+ self.latest = [[VPhoneAttitudeSample alloc] initWithState:VPhoneCurrentAttitude()+ timestamp:NSProcessInfo.processInfo.systemUptime];+ if (!self.handler || self.queuedGeneration) return;+ NSUInteger generation = self.generation;+ self.queuedGeneration = @(generation);+ __weak VPhoneAttitudeSession *weakSelf = self;+ [self.deliveryQueue addOperationWithBlock:^{+ VPhoneAttitudeSession *session = weakSelf;+ // Recheck on the app's queue: stop/restart/disable invalidates+ // callbacks waiting behind a suspended or slow operation queue.+ CMDeviceMotionHandler handler;+ CMDeviceMotion *sample;+ @synchronized (session) {+ if (session.queuedGeneration.unsignedIntegerValue == generation) session.queuedGeneration = nil;+ if (session.generation != generation || ![session simulating]) return;+ handler = session.handler;+ sample = session.latest;+ }+ if (handler) handler(sample, nil);+ }];+ }+}+- (void)refresh {+ @synchronized (self) {+ id<VPhoneAttitudeMotionManager> manager = self.manager;+ if (!self.active || !manager) return;+ BOOL needsNative = ![self simulating];+ if (needsNative == self.nativeActive) return;+ self.generation++;+ self.queuedGeneration = nil;+ self.latest = nil;+ self.invokingNative = YES;+ if (needsNative) {+ if (self.handler) {+ NSUInteger generation = self.generation;+ __weak VPhoneAttitudeSession *weakSelf = self;+ startFrameCallback(manager, @selector(startDeviceMotionUpdatesUsingReferenceFrame:toQueue:withHandler:),+ self.frame, self.deliveryQueue, ^(CMDeviceMotion *sample, NSError *error) {+ VPhoneAttitudeSession *session = weakSelf;+ CMDeviceMotionHandler handler;+ @synchronized (session) {+ if (!session.active || session.generation != generation || [session simulating]) return;+ handler = session.handler;+ }+ if (handler) handler(sample, error);+ });+ } else {+ startFramePolling(manager, @selector(startDeviceMotionUpdatesUsingReferenceFrame:), self.frame);+ }+ } else {+ stopUpdates(manager, @selector(stopDeviceMotionUpdates));+ }+ self.nativeActive = needsNative;+ self.invokingNative = NO;+ }+}+- (void)startWithFrame:(CMAttitudeReferenceFrame)frame queue:(NSOperationQueue *)queue handler:(CMDeviceMotionHandler)handler {+ @synchronized (self) {+ [self stop];+ self.frame = frame;+ self.deliveryQueue = queue;+ self.handler = handler;+ self.active = YES;+ // A timer also caches polling samples at the requested interval.+ self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,+ dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0));+ __weak VPhoneAttitudeSession *weakSelf = self;+ dispatch_source_set_event_handler(self.timer, ^{ @autoreleasepool { [weakSelf tick]; } });+ [self reschedule];+ dispatch_resume(self.timer);+ [self refresh];+ [self tick];+ }+}+- (void)stop {+ @synchronized (self) {+ self.active = NO;+ self.generation++;+ self.queuedGeneration = nil;+ if (self.timer) dispatch_source_cancel(self.timer);+ self.timer = nil;+ self.latest = nil;+ self.handler = nil;+ self.deliveryQueue = nil;+ self.invokingNative = YES;+ stopUpdates(self.manager, @selector(stopDeviceMotionUpdates));+ self.invokingNative = NO;+ self.nativeActive = NO;+ }+}+- (void)dealloc { if (_timer) dispatch_source_cancel(_timer); }+@end++static VPhoneAttitudeSession *VPhoneSession(id<VPhoneAttitudeMotionManager> manager) {+ @synchronized (manager) {+ VPhoneAttitudeSession *session = objc_getAssociatedObject(manager, &sessionKey);+ if (!session) {+ session = [VPhoneAttitudeSession new];+ session.manager = manager;+ objc_setAssociatedObject(manager, &sessionKey, session, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+ [configurationLock lock];+ [sessions addObject:session];+ [configurationLock unlock];+ }+ return session;+ }+}++// MARK: - CMMotionManager public entry points++static void VPhoneStart(id manager, SEL selector) {+ VPhoneAttitudeSession *session = VPhoneSession(manager);+ @synchronized (session) {+ if (session.invokingNative) { startPolling(manager, selector); return; }+ [session startWithFrame:CMAttitudeReferenceFrameXArbitraryZVertical queue:nil handler:nil];+ }+}+static void VPhoneStartFrame(id manager, SEL selector, CMAttitudeReferenceFrame frame) {+ VPhoneAttitudeSession *session = VPhoneSession(manager);+ @synchronized (session) {+ if (session.invokingNative) { startFramePolling(manager, selector, frame); return; }+ [session startWithFrame:frame queue:nil handler:nil];+ }+}+static void VPhoneStartCallback(id manager, SEL selector, NSOperationQueue *queue, CMDeviceMotionHandler handler) {+ VPhoneAttitudeSession *session = VPhoneSession(manager);+ @synchronized (session) {+ if (session.invokingNative) { startCallback(manager, selector, queue, handler); return; }+ [session startWithFrame:CMAttitudeReferenceFrameXArbitraryZVertical queue:queue handler:handler];+ }+}+static void VPhoneStartFrameCallback(id manager, SEL selector, CMAttitudeReferenceFrame frame,+ NSOperationQueue *queue, CMDeviceMotionHandler handler) {+ VPhoneAttitudeSession *session = VPhoneSession(manager);+ @synchronized (session) {+ if (session.invokingNative) { startFrameCallback(manager, selector, frame, queue, handler); return; }+ [session startWithFrame:frame queue:queue handler:handler];+ }+}+static void VPhoneStop(id manager, SEL selector) {+ VPhoneAttitudeSession *session = VPhoneSession(manager);+ @synchronized (session) {+ if (session.invokingNative) { stopUpdates(manager, selector); return; }+ [session stop];+ }+}+static void VPhoneInterval(id manager, SEL selector, NSTimeInterval value) {+ VPhoneAttitudeSession *session = VPhoneSession(manager);+ @synchronized (session) { setInterval(manager, selector, value); [session reschedule]; }+}+static BOOL VPhoneAvailable(id manager, SEL selector) {+ return VPhoneCurrentAttitude().enabled || isAvailable(manager, selector);+}+static BOOL VPhoneActive(id manager, SEL selector) {+ VPhoneAttitudeSession *session = VPhoneSession(manager);+ @synchronized (session) { return [session simulating] || isActive(manager, selector); }+}+static CMDeviceMotion *VPhoneMotion(id manager, SEL selector) {+ VPhoneAttitudeSession *session = VPhoneSession(manager);+ @synchronized (session) { return [session simulating] ? session.latest : getMotion(manager, selector); }+}+static CMAttitudeReferenceFrame VPhoneFrame(id manager, SEL selector) {+ VPhoneAttitudeSession *session = VPhoneSession(manager);+ @synchronized (session) { return [session simulating] ? session.frame : getFrame(manager, selector); }+}+static CMAttitudeReferenceFrame VPhoneFrames(id manager, SEL selector) {+ CMAttitudeReferenceFrame frames = availableFrames(manager, selector);+ return VPhoneCurrentAttitude().enabled ? frames | CMAttitudeReferenceFrameXArbitraryZVertical : frames;+}++static void VPhoneReadAttitude(void) {+ uint64_t state = 0;+ if (notify_get_state(notificationToken, &state) != NOTIFY_STATUS_OK) return;+ [configurationLock lock];+ configuration = VPhoneAttitudeUnpack(state);+ NSArray *live = sessions.allObjects;+ [configurationLock unlock];+ for (VPhoneAttitudeSession *session in live) { [session refresh]; [session tick]; }+}++__attribute__((constructor)) static void VPhoneAttitudeInstall(void) {+ @autoreleasepool {+ configurationLock = [NSRecursiveLock new];+ sessions = [NSHashTable weakObjectsHashTable];+ dispatch_queue_t queue = dispatch_queue_create("com.vphone.motion.attitude", DISPATCH_QUEUE_SERIAL);+ if (notify_register_dispatch(VP_ATTITUDE_NOTIFICATION, ¬ificationToken, queue,+ ^(int token) { VPhoneReadAttitude(); }) != NOTIFY_STATUS_OK) return;+ VPhoneReadAttitude();+ Class cls = NSClassFromString(@"CMMotionManager");+ // Validate the entire ABI before installing any part of the hook.+ SEL selectors[] = {@selector(startDeviceMotionUpdates), @selector(startDeviceMotionUpdatesUsingReferenceFrame:),+ @selector(startDeviceMotionUpdatesToQueue:withHandler:), @selector(startDeviceMotionUpdatesUsingReferenceFrame:toQueue:withHandler:),+ @selector(stopDeviceMotionUpdates), @selector(setDeviceMotionUpdateInterval:), @selector(isDeviceMotionAvailable),+ @selector(isDeviceMotionActive), @selector(deviceMotion), @selector(attitudeReferenceFrame)};+ for (NSUInteger i = 0; i < sizeof(selectors)/sizeof(*selectors); i++)+ if (!class_getInstanceMethod(cls, selectors[i])) return;+ Method frames = class_getClassMethod(cls, @selector(availableAttitudeReferenceFrames));+ if (!frames) return;+#define VP_HOOK(methodName, replacement, original) \+ original = (__typeof__(original))method_setImplementation(class_getInstanceMethod(cls, @selector(methodName)), (IMP)replacement)+ VP_HOOK(startDeviceMotionUpdates, VPhoneStart, startPolling);+ VP_HOOK(startDeviceMotionUpdatesUsingReferenceFrame:, VPhoneStartFrame, startFramePolling);+ VP_HOOK(startDeviceMotionUpdatesToQueue:withHandler:, VPhoneStartCallback, startCallback);+ VP_HOOK(startDeviceMotionUpdatesUsingReferenceFrame:toQueue:withHandler:, VPhoneStartFrameCallback, startFrameCallback);+ VP_HOOK(stopDeviceMotionUpdates, VPhoneStop, stopUpdates);+ VP_HOOK(setDeviceMotionUpdateInterval:, VPhoneInterval, setInterval);+ VP_HOOK(isDeviceMotionAvailable, VPhoneAvailable, isAvailable);+ VP_HOOK(isDeviceMotionActive, VPhoneActive, isActive);+ VP_HOOK(deviceMotion, VPhoneMotion, getMotion);+ VP_HOOK(attitudeReferenceFrame, VPhoneFrame, getFrame);+#undef VP_HOOK+ availableFrames = (__typeof__(availableFrames))method_setImplementation(frames, (IMP)VPhoneFrames);+ }+}diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefileindex 3340703d..699da39b 100644--- a/VPhoneGuestComponents/Makefile+++ b/VPhoneGuestComponents/Makefile@@ -86,6 +86,9 @@ SIGNINFIX_INCLUDES := $(wildcard SignInFix/*.h)GYROSCOPE := $(STAGE)/gyroscope/libvphonegyro.dylibGYROSCOPE_SOURCES := $(call find_sources,Gyroscope)GYROSCOPE_INPUTS := $(call find_headers,Gyroscope) $(call find_folders,Gyroscope)+ATTITUDE := $(STAGE)/attitude/libvphoneattitude.dylib+ATTITUDE_SOURCES := $(call find_sources,Attitude)+ATTITUDE_INPUTS := $(call find_headers,Attitude) $(call find_folders,Attitude)GPU_PLUGIN := $(STAGE)/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylibGPU_PLUGIN_SOURCES := $(wildcard GraphicLoader/*.mm)GPU_PLUGIN_INCLUDES := $(wildcard GraphicLoader/*.h GraphicLoader/*.hpp GraphicLoader/*.inc)@@ -119,7 +122,7 @@ GPU_DYNAMIC_LOOKUP_SYMS := \VIRTIOSOUND := $(STAGE)/virtiosound/VPhoneVirtIOSound.driverVIRTIOSOUND_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) $(GPU_PLUGIN) $(VIRTIOSOUND)+ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(DEVICENAME) $(PREFSFIX) $(SIGNINFIX) $(GYROSCOPE) $(ATTITUDE) $(GPU_PLUGIN) $(VIRTIOSOUND)PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist \$(STAGE)/misfix/libmisfix.plistGPU_PROVENANCE := $(STAGE)/gpu/README.md@@ -134,7 +137,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 gpu virtiosound+ @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix devicename prefsfix signinfix gyroscope attitude gpu virtiosound@echo "Packaged $(ARCHIVE)"test-loader-links:@@ -194,7 +197,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)/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)/attitude $(STAGE)/gpu $(STAGE)/virtiosound:@mkdir -p $@$(CAMFIX): $(CAMFIX_SOURCES) $(CAMFIX_INPUTS) | $(STAGE)/camfix@@ -289,6 +292,26 @@ $(GYROSCOPE): $(GYROSCOPE_SOURCES) $(GYROSCOPE_INPUTS) | $(STAGE)/gyroscope@codesign --force --sign - $@.PHONY: test-gyroscope+$(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 \+ -install_name /usr/lib/libvphoneattitude.dylib -o $@ $(ATTITUDE_SOURCES) \+ -framework Foundation -framework CoreMotion -Wl,-not_for_dyld_shared_cache+ @codesign --force --sign - $@++.PHONY: test-attitude+test-attitude:+ @mkdir -p $(OUT)+ xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -Wno-unused-parameter -IAttitude \+ -o $(OUT)/AttitudeTests Tests/AttitudeTests.m Attitude/VPhoneAttitudeSample.m \+ -framework Foundation -framework CoreMotion+ @$(OUT)/AttitudeTests+ xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -Wno-unused-parameter -IAttitude \+ -DVP_ATTITUDE_NOTIFICATION='"com.vphone.motion.attitude.host-test"' \+ -o $(OUT)/AttitudeHookTests Tests/AttitudeHookTests.m $(ATTITUDE_SOURCES) \+ -framework Foundation -framework CoreMotion+ @$(OUT)/AttitudeHookTests+test-gyroscope:@mkdir -p $(OUT)xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -IGyroscope \diff --git a/VPhoneGuestComponents/README.md b/VPhoneGuestComponents/README.mdindex 3e35d122..789a32a0 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` |+| Device attitude | `attitude/libvphoneattitude.dylib` || Launchd hook | `launchhook/launchdhook-vphone.dylib` || Process injection bridge | `systemhook/SystemHook-vphone.dylib` || iOS 27 app registrar | `vpregister/vpregister` |@@ -66,6 +67,13 @@ replaces installed copies only and requests a reboot without restarting theUI daemon. `make test-gyroscope` checks its configuration transport. GuestCoreMotion acceptance is still pending; see `Research/Guest/virtual_gyroscope.md`.+`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.+Removing the selected library and relaunching apps reverts the hook.+`make test-attitude` checks samples and the actual host Core Motion subscription+runtime. Guest validation is manual; see `Research/Guest/virtual_attitude.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.cindex 04486e68..b3971ca6 100644--- a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c+++ b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c@@ -154,6 +154,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_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// HapticsFix/libhapticsfix.c for what it answers and why SpringBoard is the@@ -257,6 +258,8 @@ __attribute__((constructor)) static void vpLogProcess(void) {// above, so background AuthKit auth is untouched).if (vpIsAppPath(path))vpLoadLibrary("signin-fix", VP_SIGNIN_FIX);+ if (vpIsAppPath(path))+ vpLoadLibrary("attitude-hook", VP_ATTITUDE_HOOK);if (vpIsAppPath(path) && dlopen(VP_AVFOUNDATION, RTLD_LAZY | RTLD_NOLOAD))vpLoadLibrary("camera-hook", VP_CAMERA_APP_HOOK);const char *root = getenv("VPHONE_JB_ROOT");diff --git a/VPhoneGuestComponents/Tests/AttitudeHookTests.m b/VPhoneGuestComponents/Tests/AttitudeHookTests.mnew file mode 100644index 00000000..c1148c3b--- /dev/null+++ b/VPhoneGuestComponents/Tests/AttitudeHookTests.m@@ -0,0 +1,83 @@+#import "VPhoneAttitudeSample.h"+#import "VPhoneAttitudeMotionManager.h"+#include <assert.h>+#include <notify.h>+#include <unistd.h>++static int token;+static void publish(VPhoneAttitudeState state) {+ assert(notify_set_state(token, VPhoneAttitudePack(state)) == NOTIFY_STATUS_OK);+ assert(notify_post(VP_ATTITUDE_NOTIFICATION) == NOTIFY_STATUS_OK);+}+static void waitFor(BOOL (^condition)(void)) {+ for (int i = 0; i < 200; i++) {+ if (condition()) return;+ usleep(5000);+ }+ assert(!"Timed out waiting for the attitude hook");+}+static void closeTo(double actual, double expected) { assert(fabs(actual - expected) < 1e-8); }++int main(void) {+ @autoreleasepool {+ assert(notify_register_check(VP_ATTITUDE_NOTIFICATION, &token) == NOTIFY_STATUS_OK);+ Class<VPhoneAttitudeMotionManager> managerClass = (Class<VPhoneAttitudeMotionManager>)NSClassFromString(@"CMMotionManager");+ assert(managerClass);+ id<VPhoneAttitudeMotionManager> polling = [(Class)managerClass new];+ BOOL nativeAvailable = polling.deviceMotionAvailable;+ publish((VPhoneAttitudeState){YES, 30, -20, 45});+ waitFor(^BOOL { return polling.deviceMotionAvailable; });+ assert([managerClass availableAttitudeReferenceFrames] & CMAttitudeReferenceFrameXArbitraryZVertical);+ [polling startDeviceMotionUpdates];+ assert(polling.deviceMotionActive);+ assert(polling.attitudeReferenceFrame == CMAttitudeReferenceFrameXArbitraryZVertical);+ waitFor(^BOOL { return polling.deviceMotion != nil; });+ CMDeviceMotion *old = polling.deviceMotion;+ closeTo(old.attitude.roll, M_PI/6);+ closeTo(old.attitude.pitch, -M_PI/9);++ id<VPhoneAttitudeMotionManager> callbacks = [(Class)managerClass new];+ callbacks.deviceMotionUpdateInterval = 0.01;+ NSOperationQueue *queue = [NSOperationQueue new];+ queue.maxConcurrentOperationCount = 1;+ dispatch_semaphore_t received = dispatch_semaphore_create(0);+ __block NSTimeInterval timestamp = 0;+ [callbacks startDeviceMotionUpdatesToQueue:queue withHandler:^(CMDeviceMotion *sample, NSError *error) {+ assert(!error && sample.timestamp >= timestamp);+ timestamp = sample.timestamp;+ dispatch_semaphore_signal(received);+ }];+ assert(dispatch_semaphore_wait(received, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC)) == 0);+ publish((VPhoneAttitudeState){YES, -60, 10, -90});+ waitFor(^BOOL { return fabs(polling.deviceMotion.attitude.roll + M_PI/3) < 1e-8; });+ closeTo(old.attitude.roll, M_PI/6); // Delivered samples are snapshots.+ [callbacks stopDeviceMotionUpdates];+ [queue waitUntilAllOperationsAreFinished];+ assert(!callbacks.deviceMotionActive && callbacks.deviceMotion == nil);++ // Bound delivery backlog and discard queued callbacks after a stop.+ queue.suspended = YES;+ __block int calls = 0;+ [callbacks startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXArbitraryZVertical+ toQueue:queue withHandler:^(CMDeviceMotion *sample, NSError *error) { calls++; }];+ usleep(80000);+ assert(queue.operationCount == 1);+ [callbacks stopDeviceMotionUpdates];+ queue.suspended = NO;+ [queue waitUntilAllOperationsAreFinished];+ assert(calls == 0);++ // Exercise explicit polling and toggling an existing subscription.+ [polling startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXArbitraryZVertical];+ publish((VPhoneAttitudeState){NO, -60, 10, -90});+ waitFor(^BOOL { return polling.deviceMotionAvailable == nativeAvailable && ![polling.deviceMotion isKindOfClass:VPhoneAttitudeSample.class]; });+ publish((VPhoneAttitudeState){YES, 0, 0, 0});+ waitFor(^BOOL { return [polling.deviceMotion isKindOfClass:VPhoneAttitudeSample.class]; });+ closeTo(polling.deviceMotion.gravity.z, -1);+ [polling stopDeviceMotionUpdates];+ publish((VPhoneAttitudeState){0});+ notify_cancel(token);+ puts("Core Motion polling, callback, live toggle, snapshot and bounded backlog tests passed");+ }+ return 0;+}diff --git a/VPhoneGuestComponents/Tests/AttitudeTests.m b/VPhoneGuestComponents/Tests/AttitudeTests.mnew file mode 100644index 00000000..5f9ed03b--- /dev/null+++ b/VPhoneGuestComponents/Tests/AttitudeTests.m@@ -0,0 +1,55 @@+#import "VPhoneAttitudeSample.h"+#include <assert.h>++static void closeTo(double actual, double expected) { assert(fabs(actual - expected) < 1e-9); }++int main(void) {+ @autoreleasepool {+ VPhoneAttitudeState state = {YES, 32.5, -24.25, 117.75}, decoded;+ assert(VPhoneAttitudeDecode(VPhoneAttitudeEncode(state), &decoded));+ closeTo(decoded.roll, state.roll);+ for (NSDictionary *invalid in @[+ @{@"enabled": @YES, @"roll": @YES, @"pitch": @0, @"yaw": @0},+ @{@"enabled": @1, @"roll": @0, @"pitch": @0, @"yaw": @0},+ @{@"enabled": @YES, @"roll": @181, @"pitch": @0, @"yaw": @0},+ @{@"enabled": @YES, @"roll": @0, @"pitch": @91, @"yaw": @0},+ @{@"enabled": @YES, @"roll": @0, @"pitch": @0, @"yaw": @(NAN)},+ ]) assert(!VPhoneAttitudeDecode(invalid, &decoded));+ VPhoneAttitudeState poses[] = {state, {NO, -180, -90, -180}, {YES, 180, 90, 180}, {YES, 0, 0, 0}};+ for (NSUInteger i = 0; i < sizeof(poses)/sizeof(*poses); i++) {+ decoded = VPhoneAttitudeUnpack(VPhoneAttitudePack(poses[i]));+ assert(decoded.enabled == poses[i].enabled);+ closeTo(decoded.roll, poses[i].roll); closeTo(decoded.pitch, poses[i].pitch); closeTo(decoded.yaw, poses[i].yaw);+ }+ assert(!VPhoneAttitudeUnpack(0).enabled);+ assert(!VPhoneAttitudeUnpack(UINT64_MAX).enabled);+ VPhoneAttitudeSample *sample = [[VPhoneAttitudeSample alloc] initWithState:state timestamp:123];+ CMAttitude *pose = sample.attitude;+ closeTo(pose.roll, state.roll*M_PI/180); closeTo(pose.pitch, state.pitch*M_PI/180); closeTo(pose.yaw, state.yaw*M_PI/180);+ CMQuaternion q = pose.quaternion;+ closeTo(q.x*q.x+q.y*q.y+q.z*q.z+q.w*q.w, 1);+ CMRotationMatrix m = pose.rotationMatrix;+ closeTo(m.m11*m.m11+m.m12*m.m12+m.m13*m.m13, 1);+ closeTo(m.m11*m.m21+m.m12*m.m22+m.m13*m.m23, 0);+ CMAcceleration g = sample.gravity;+ closeTo(g.x*g.x+g.y*g.y+g.z*g.z, 1);+ closeTo(sample.rotationRate.x, 0); closeTo(sample.userAcceleration.y, 0); closeTo(sample.timestamp, 123);+ assert(sample.heading < 0 && sample.magneticField.accuracy == CMMagneticFieldCalibrationAccuracyUncalibrated);+ CMAttitude *copy = [pose copy];+ [copy multiplyByInverseOfAttitude:pose];+ closeTo(copy.quaternion.w, 1); closeTo(copy.roll, 0); closeTo(copy.pitch, 0); closeTo(copy.yaw, 0);+ closeTo(pose.roll, state.roll*M_PI/180);+ NSError *error;+ NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:sample requiringSecureCoding:YES error:&error];+ assert(archive && !error);+ VPhoneAttitudeSample *restored = [NSKeyedUnarchiver unarchivedObjectOfClass:VPhoneAttitudeSample.class fromData:archive error:&error];+ assert(restored && !error);+ closeTo(restored.attitude.yaw, pose.yaw); closeTo(restored.timestamp, 123);+ VPhoneAttitudeSample *pitch = [[VPhoneAttitudeSample alloc] initWithState:(VPhoneAttitudeState){YES, 0, 90, 0} timestamp:0];+ closeTo(pitch.gravity.y, -1);+ VPhoneAttitudeSample *roll = [[VPhoneAttitudeSample alloc] initWithState:(VPhoneAttitudeState){YES, 90, 0, 0} timestamp:0];+ closeTo(roll.gravity.x, 1);+ puts("Attitude configuration, quaternion, gravity, copy and coding tests passed");+ }+ return 0;+}diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swiftindex 7b55ba01..b6ef1b81 100644--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift@@ -19,9 +19,10 @@ public enum VPhoneGuestEnvironment {"libprefsfix.dylib","libsigninfix.dylib","libvphonegyro.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"]+ public static let selectedLibraries: Set<String> = ["libvphonegyro.dylib", "libvphoneattitude.dylib"]}