Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Keep the attitude hook from deadlocking SpringBoard on Core Motion

Jacky12c72fa4f3dd
diff --git a/VPhoneGuestComponents/Attitude/libvphoneattitude.m b/VPhoneGuestComponents/Attitude/libvphoneattitude.m
index 9f1d23fc..427f394d 100644
--- a/VPhoneGuestComponents/Attitude/libvphoneattitude.m
+++ b/VPhoneGuestComponents/Attitude/libvphoneattitude.m
@@ -2,6 +2,7 @@
#import "VPhoneAttitudeMotionManager.h"
#import <objc/runtime.h>
#include <notify.h>
+#include <os/lock.h>
// MARK: - Shared configuration
@@ -36,9 +37,10 @@ static CMAttitudeReferenceFrame (*availableFrames)(id, SEL);
@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;
+// Read without the session lock by the getters below; see "Lock order".
+@property (atomic, strong) CMDeviceMotion *latest;
+@property (atomic) CMAttitudeReferenceFrame frame;
+@property (atomic) BOOL active;
@property (nonatomic) BOOL nativeActive;
@property (nonatomic) BOOL invokingNative;
@property (nonatomic) NSUInteger generation;
@@ -156,19 +158,42 @@ static CMAttitudeReferenceFrame (*availableFrames)(id, SEL);
- (void)dealloc { if (_timer) dispatch_source_cancel(_timer); }
@end
+// MARK: - Lock order
+//
+// Core Motion's own methods can wait for its MotionThread, and that thread
+// calls the public getters (`isDeviceMotionActive`, `deviceMotion`, …) on the
+// same manager. So no thread may wait for the session lock, or for the
+// manager's own `@synchronized` lock, inside a hooked getter: a caller holding
+// it while it runs a native method would wait for the MotionThread forever.
+// On iOS 26.6.2 that froze SpringBoard's main thread when it built the Home
+// Screen's parallax (`_UIMotionEffectCoreMotionEventProvider` sets the update
+// interval). The getters read the atomic `active`, `frame` and `latest`
+// without the session lock, the setter calls the native method before taking
+// it, and the session is looked up under a private lock that is never held
+// across a call out.
+
+static os_unfair_lock sessionCreationLock = OS_UNFAIR_LOCK_INIT;
+
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;
+ VPhoneAttitudeSession *session = objc_getAssociatedObject(manager, &sessionKey);
+ if (session) return session;
+ VPhoneAttitudeSession *created = [VPhoneAttitudeSession new];
+ created.manager = manager;
+ BOOL inserted = NO;
+ os_unfair_lock_lock(&sessionCreationLock);
+ session = objc_getAssociatedObject(manager, &sessionKey);
+ if (!session) {
+ objc_setAssociatedObject(manager, &sessionKey, created, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ session = created;
+ inserted = YES;
}
+ os_unfair_lock_unlock(&sessionCreationLock);
+ if (inserted) {
+ [configurationLock lock];
+ [sessions addObject:session];
+ [configurationLock unlock];
+ }
+ return session;
}
// MARK: - CMMotionManager public entry points
@@ -210,23 +235,23 @@ static void VPhoneStop(id manager, SEL selector) {
}
}
static void VPhoneInterval(id manager, SEL selector, NSTimeInterval value) {
- VPhoneAttitudeSession *session = VPhoneSession(manager);
- @synchronized (session) { setInterval(manager, selector, value); [session reschedule]; }
+ setInterval(manager, selector, value);
+ [VPhoneSession(manager) reschedule];
}
static BOOL VPhoneAvailable(id manager, SEL selector) {
return VPhoneCurrentAttitude().enabled || isAvailable(manager, selector);
}
+// The getters take no lock that a caller of a native method may hold.
static BOOL VPhoneActive(id manager, SEL selector) {
- VPhoneAttitudeSession *session = VPhoneSession(manager);
- @synchronized (session) { return [session simulating] || isActive(manager, selector); }
+ return [VPhoneSession(manager) 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); }
+ 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); }
+ return [session simulating] ? session.frame : getFrame(manager, selector);
}
static CMAttitudeReferenceFrame VPhoneFrames(id manager, SEL selector) {
CMAttitudeReferenceFrame frames = availableFrames(manager, selector);
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index dfea3377..8bf859f5 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -311,6 +311,11 @@ test-attitude:
-o $(OUT)/AttitudeHookTests Tests/AttitudeHookTests.m $(ATTITUDE_SOURCES) \
-framework Foundation -framework CoreMotion
@$(OUT)/AttitudeHookTests
+ xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -Wno-unused-parameter -IAttitude \
+ -DVP_ATTITUDE_NOTIFICATION='"com.vphone.motion.attitude.lock-order-test"' \
+ -o $(OUT)/AttitudeLockOrderTests Tests/AttitudeLockOrderTests.m $(ATTITUDE_SOURCES) \
+ -framework Foundation -framework CoreMotion
+ @$(OUT)/AttitudeLockOrderTests
test-gyroscope:
@mkdir -p $(OUT)
diff --git a/VPhoneGuestComponents/Tests/AttitudeLockOrderTests.m b/VPhoneGuestComponents/Tests/AttitudeLockOrderTests.m
new file mode 100644
index 00000000..bf8dd996
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/AttitudeLockOrderTests.m
@@ -0,0 +1,111 @@
+// Core Motion's own methods wait for its MotionThread, and the MotionThread
+// calls back into public CMMotionManager getters. SpringBoard on iOS 26.6.2
+// deadlocked this way on its first Home Screen: `_UIMotionEffectCoreMotionEventProvider`
+// set the update interval, the hook held the session lock around the native
+// setter, and the MotionThread's `isDeviceMotionActive` waited for that lock.
+//
+// This file must be linked before the hook's sources: its constructor puts
+// stand-ins for the native methods in place first, so the hook keeps them as
+// the "actual implementations" and calls them as it would call Core Motion.
+#import "VPhoneAttitudeSample.h"
+#import "VPhoneAttitudeMotionManager.h"
+#import <objc/runtime.h>
+#include <assert.h>
+#include <notify.h>
+#include <unistd.h>
+
+static dispatch_queue_t motionThread;
+static int nativeCalls;
+static void (*realInterval)(id, SEL, NSTimeInterval);
+static void (*realStart)(id, SEL, CMAttitudeReferenceFrame);
+static void (*realStop)(id, SEL);
+
+// What the MotionThread does while a caller waits for it: read the public
+// getters, which the hook replaces. dispatch_sync would run the block on the
+// caller's thread, so the wait goes through a semaphore as the real one does.
+static void waitForMotionThread(id<VPhoneAttitudeMotionManager> manager) {
+ nativeCalls++;
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
+ dispatch_async(motionThread, ^{
+ (void)manager.deviceMotionActive;
+ (void)manager.deviceMotion;
+ (void)manager.attitudeReferenceFrame;
+ (void)manager.deviceMotionAvailable;
+ dispatch_semaphore_signal(done);
+ });
+ dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER);
+}
+static void nativeInterval(id manager, SEL selector, NSTimeInterval value) {
+ waitForMotionThread(manager);
+ realInterval(manager, selector, value);
+}
+static void nativeStart(id manager, SEL selector, CMAttitudeReferenceFrame frame) {
+ waitForMotionThread(manager);
+ realStart(manager, selector, frame);
+}
+static void nativeStop(id manager, SEL selector) {
+ waitForMotionThread(manager);
+ realStop(manager, selector);
+}
+
+__attribute__((constructor)) static void installNativeStandIns(void) {
+ motionThread = dispatch_queue_create("test.CoreMotion.MotionThread", DISPATCH_QUEUE_SERIAL);
+ Class cls = NSClassFromString(@"CMMotionManager");
+ assert(cls);
+ realInterval = (__typeof__(realInterval))method_setImplementation(
+ class_getInstanceMethod(cls, @selector(setDeviceMotionUpdateInterval:)), (IMP)nativeInterval);
+ realStart = (__typeof__(realStart))method_setImplementation(
+ class_getInstanceMethod(cls, @selector(startDeviceMotionUpdatesUsingReferenceFrame:)), (IMP)nativeStart);
+ realStop = (__typeof__(realStop))method_setImplementation(
+ class_getInstanceMethod(cls, @selector(stopDeviceMotionUpdates)), (IMP)nativeStop);
+}
+
+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);
+}
+
+// Runs `body` off the main thread and fails instead of hanging.
+static void finishes(const char *what, void (^body)(void)) {
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
+ body();
+ dispatch_semaphore_signal(done);
+ });
+ if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC)) != 0) {
+ fprintf(stderr, "deadlock: %s did not return while Core Motion waited for its MotionThread\n", what);
+ _exit(1);
+ }
+}
+
+int main(void) {
+ @autoreleasepool {
+ assert(notify_register_check(VP_ATTITUDE_NOTIFICATION, &token) == NOTIFY_STATUS_OK);
+ Class managerClass = NSClassFromString(@"CMMotionManager");
+ id<VPhoneAttitudeMotionManager> manager = [managerClass new];
+
+ // Native path: the simulation is off, so every call reaches Core Motion.
+ publish((VPhoneAttitudeState){0});
+ finishes("setDeviceMotionUpdateInterval:", ^{ manager.deviceMotionUpdateInterval = 0.02; });
+ finishes("startDeviceMotionUpdatesUsingReferenceFrame:", ^{
+ [manager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXArbitraryZVertical];
+ });
+ finishes("setDeviceMotionUpdateInterval: while running", ^{ manager.deviceMotionUpdateInterval = 0.05; });
+
+ // Simulated path: turning the simulation on stops the native updates
+ // from the notification queue while the session is locked.
+ publish((VPhoneAttitudeState){YES, 10, 20, 30});
+ for (int i = 0; i < 200 && ![manager.deviceMotion isKindOfClass:VPhoneAttitudeSample.class]; i++) usleep(5000);
+ assert([manager.deviceMotion isKindOfClass:VPhoneAttitudeSample.class]);
+ finishes("setDeviceMotionUpdateInterval: while simulating", ^{ manager.deviceMotionUpdateInterval = 0.01; });
+ publish((VPhoneAttitudeState){0});
+ for (int i = 0; i < 200 && [manager.deviceMotion isKindOfClass:VPhoneAttitudeSample.class]; i++) usleep(5000);
+ finishes("stopDeviceMotionUpdates", ^{ [manager stopDeviceMotionUpdates]; });
+
+ assert(nativeCalls >= 4); // The hook called the stand-ins, not Core Motion directly.
+ notify_cancel(token);
+ puts("Core Motion calls that wait for the MotionThread do not deadlock with the attitude hook");
+ }
+ return 0;
+}