Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Investigation: timers synchronization #33

Draft
wants to merge 11 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions DetoxSync/DetoxSync.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -1224,7 +1224,6 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = NO;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = NO;
CODE_SIGN_STYLE = Automatic;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
Expand Down Expand Up @@ -1255,7 +1254,6 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = NO;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = NO;
CODE_SIGN_STYLE = Automatic;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
Expand Down
26 changes: 19 additions & 7 deletions DetoxSync/DetoxSync/Spies/NSTimer+DTXSpy.m
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ static void _DTXCFTimerTrampoline(CFRunLoopTimerRef timer, void *info)
// NSLog(@"❤️ %p", timer);

id<DTXTimerProxy> tp = [DTXTimerSyncResource existingTimerProxyWithTimer:NS(timer)];
[tp fire:(__bridge NSTimer*)timer];
[tp fire];
}

static CFRunLoopTimerRef (*__orig_CFRunLoopTimerCreate)(CFAllocatorRef allocator, CFAbsoluteTime fireDate, CFTimeInterval interval, CFOptionFlags flags, CFIndex order, CFRunLoopTimerCallBack callout, CFRunLoopTimerContext *context);
Expand All @@ -72,6 +72,9 @@ CFRunLoopTimerRef __detox_sync_CFRunLoopTimerCreate(CFAllocatorRef allocator, CF
static CFRunLoopTimerRef (*__orig_CFRunLoopTimerCreateWithHandler)(CFAllocatorRef allocator, CFAbsoluteTime fireDate, CFTimeInterval interval, CFOptionFlags flags, CFIndex order, void (^block) (CFRunLoopTimerRef timer));
CFRunLoopTimerRef __detox_sync_CFRunLoopTimerCreateWithHandler(CFAllocatorRef allocator, CFAbsoluteTime fireDate, CFTimeInterval interval, CFOptionFlags flags, CFIndex order, void (^block) (id timer))
{
NSLog(@"🤔 CFRunLoopTimerCreateWithHandler");

// What is this doing? We don't seem to be creating a trampoline here - I feel like we should be?
return (__bridge_retained CFRunLoopTimerRef)[[NSTimer alloc] initWithFireDate:CFBridgingRelease(CFDateCreate(allocator, fireDate)) interval:interval repeats:interval > 0 block:block];
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand why we're swizzling CFRunLoopTimerCreateWithHandler without adding any tracking for these timers (as far as I can tell).

Unless initWithFireDate somehow ends up calling CFRunLoopTimerCreate?

Copy link
Contributor Author

@ball-hayden ball-hayden Apr 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This happens a lot when running the Detox example app.
I don't understand what this is doing.

Copy link
Contributor

@asafkorem asafkorem Apr 20, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless initWithFireDate somehow ends up calling CFRunLoopTimerCreate

Probably yes. This can be easily checked by putting a breakpoint on __detox_sync_CFRunLoopTimerCreate.
https://github.com/wix/DetoxSync/tree/master/ExampleApp

}

Expand All @@ -94,9 +97,9 @@ void __detox_sync_CFRunLoopRemoveTimer(CFRunLoopRef rl, CFRunLoopTimerRef timer,
// NSLog(@"🤦‍♂️ removeTimer: %@", NS(timer));

id<DTXTimerProxy> trampoline = [DTXTimerSyncResource existingTimerProxyWithTimer:NS(timer)];
[trampoline untrack];

__orig_CFRunLoopRemoveTimer(rl, timer, mode);

[trampoline untrack];
Comment on lines 99 to +102
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've observed that [_DTXTimerTrampoline fire:] is called after the trampoline has been untracked (and therefore dealloced).

By switching these, I was hoping that the timer would be cancelled (ensuring that the fire method is not called after untracking).

This doesn't seem to be the case, and I'm still seeing fire called after the trampoline has been untracked, but it still feels safer to me to remove the timer before untracking?

Copy link
Contributor

@asafkorem asafkorem Apr 20, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Untracking the timer only after removing it from the runloop does make sense, but I'm not sure if it matters.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[_DTXTimerTrampoline fire:] is called after the trampoline has been untracked

That's very weird. 🤔

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe the thread where this timer was created and the thread where the timer was called to invalidate are different?

Apple docs (invalidate()):

You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.

}

static void (*__orig_CFRunLoopTimerInvalidate)(CFRunLoopTimerRef timer);
Expand All @@ -105,9 +108,9 @@ void __detox_sync_CFRunLoopTimerInvalidate(CFRunLoopTimerRef timer)
// NSLog(@"🤦‍♂️ invalidate: %@", NS(timer));

id<DTXTimerProxy> trampoline = [DTXTimerSyncResource existingTimerProxyWithTimer:NS(timer)];
[trampoline untrack];

__orig_CFRunLoopTimerInvalidate(timer);

[trampoline untrack];
}

static void (*__orig___NSCFTimer_invalidate)(NSTimer* timer);
Expand All @@ -116,11 +119,20 @@ void __detox_sync___NSCFTimer_invalidate(NSTimer* timer)
// NSLog(@"🤦‍♂️ invalidate: %@", timer);

id<DTXTimerProxy> trampoline = [DTXTimerSyncResource existingTimerProxyWithTimer:timer];
[trampoline untrack];

__orig___NSCFTimer_invalidate(timer);

[trampoline untrack];
}

- (void)dealloc
{
id<DTXTimerProxy> trampoline = [DTXTimerSyncResource existingTimerProxyWithTimer:self];

if(trampoline) {
NSLog(@"🤦‍♂️ dealloc, but trampoline was still active: %@", self);
[trampoline untrack];
}
}
Comment on lines +127 to +135
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think adding this makes it safe to remove _DTXCleanTimersAndReturnCount (since we've then got a nicer way of calling untrack if the timer is dealloced)?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make sense.


+ (void)load
{
Expand Down
2 changes: 1 addition & 1 deletion DetoxSync/DetoxSync/SyncResources/DTXTimerSyncResource.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ NS_ASSUME_NONNULL_BEGIN

//NSTimer
@property (nonatomic, weak) NSTimer* timer;
- (void)fire:(NSTimer*)timer;
- (void)fire;
@property (nonatomic) CFRunLoopRef runLoop;

//CADisplayLink
Expand Down
26 changes: 6 additions & 20 deletions DetoxSync/DetoxSync/SyncResources/DTXTimerSyncResource.m
Original file line number Diff line number Diff line change
Expand Up @@ -86,30 +86,16 @@ + (instancetype)sharedInstance
shared = [DTXTimerSyncResource new];
[DTXSyncManager registerSyncResource:shared];
});

return shared;
}

/// Ugly hack for rare occasions where NSTimer gets released, but its associated objects are not released.
static NSUInteger _DTXCleanTimersAndReturnCount(NSMutableSet* _timers, NSMutableArray<NSString*(^)(void)>* eventIdentifiers)
{
for (_DTXTimerTrampoline* trampoline in _timers.copy) {
if(trampoline.isDead)
{
[eventIdentifiers addObject:_DTXStringReturningBlock([NSString stringWithFormat:@"%p", trampoline])];
[_timers removeObject:trampoline];
}
}

return _timers.count;
return shared;
}

- (void)clearTimerTrampolinesForCFRunLoop:(CFRunLoopRef)cfRunLoop
{
__block NSMutableArray<NSString*(^)(void)>* eventIdentifiers = [NSMutableArray new];

[self performMultipleUpdateBlock:^{
return _DTXCleanTimersAndReturnCount(_timers, eventIdentifiers);
return _timers.count;
} eventIdentifiers:_DTXObjectReturningBlock(eventIdentifiers)
eventDescriptions:nil
objectDescriptions:nil
Expand All @@ -131,7 +117,7 @@ - (void)trackTimerTrampoline:(_DTXTimerTrampoline *)trampoline
trampoline.jsonDescription])];
[_timers addObject:trampoline];

return _DTXCleanTimersAndReturnCount(_timers, eventIdentifiers);
return _timers.count;
}
eventIdentifiers:_DTXObjectReturningBlock(eventIdentifiers)
eventDescriptions:_DTXObjectReturningBlock(eventDescriptions)
Expand All @@ -142,11 +128,11 @@ - (void)trackTimerTrampoline:(_DTXTimerTrampoline *)trampoline
- (void)untrackTimerTrampoline:(_DTXTimerTrampoline *)trampoline
{
__block NSMutableArray<NSString*(^)(void)>* eventIdentifiers = [NSMutableArray new];

[self performMultipleUpdateBlock:^{
[eventIdentifiers addObject:_DTXStringReturningBlock([NSString stringWithFormat:@"%p", trampoline])];
[_timers removeObject:trampoline];
return _DTXCleanTimersAndReturnCount(_timers, eventIdentifiers);
return _timers.count;
} eventIdentifiers:_DTXObjectReturningBlock(eventIdentifiers)
eventDescriptions:nil
objectDescriptions:nil
Expand Down
28 changes: 14 additions & 14 deletions DetoxSync/DetoxSync/SyncResources/DTXUISyncResource.m
Original file line number Diff line number Diff line change
Expand Up @@ -113,45 +113,45 @@ - (void)_untrackForParam:(NSUInteger*)param eventIdentifier:(NSString*(NS_NOESCA
- (void)trackViewNeedsLayout:(UIView *)view
{
NSString* identifier = [self _trackForParam:&_viewNeedsLayoutCount eventDescription:_DTXStringReturningBlock(@"View Layout") objectDescription:_DTXStringReturningBlock(view.__detox_sync_safeDescription)];

__detox_sync_orig_dispatch_async(dispatch_get_main_queue(), ^ {
[self _untrackForParam:&_viewNeedsLayoutCount eventIdentifier:_DTXStringReturningBlock(identifier)];
[self _untrackForParam:&self->_viewNeedsLayoutCount eventIdentifier:_DTXStringReturningBlock(identifier)];
Copy link
Contributor

@asafkorem asafkorem May 11, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

being explicit in such cases is indeed better

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but except for being more explicit, is there any other goal in this change? What exactly is the fix here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

});
}

- (void)trackViewNeedsDisplay:(UIView *)view
{
NSString* identifier = [self _trackForParam:&_viewNeedsDisplayCount eventDescription:_DTXStringReturningBlock(@"View Display") objectDescription:_DTXStringReturningBlock(view.__detox_sync_safeDescription)];

__detox_sync_orig_dispatch_async(dispatch_get_main_queue(), ^ {
[self _untrackForParam:&_viewNeedsDisplayCount eventIdentifier:_DTXStringReturningBlock(identifier)];
[self _untrackForParam:&self->_viewNeedsDisplayCount eventIdentifier:_DTXStringReturningBlock(identifier)];
});
}

- (void)trackLayerNeedsLayout:(CALayer *)layer
{
NSString* identifier = [self _trackForParam:&_layerNeedsLayoutCount eventDescription:_DTXStringReturningBlock(@"Layer Layout") objectDescription:_DTXStringReturningBlock(layer.description)];

__detox_sync_orig_dispatch_async(dispatch_get_main_queue(), ^ {
[self _untrackForParam:&_layerNeedsLayoutCount eventIdentifier:_DTXStringReturningBlock(identifier)];
[self _untrackForParam:&self->_layerNeedsLayoutCount eventIdentifier:_DTXStringReturningBlock(identifier)];
});
}

- (void)trackLayerNeedsDisplay:(CALayer *)layer
{
NSString* identifier = [self _trackForParam:&_layerNeedsDisplayCount eventDescription:_DTXStringReturningBlock(@"Layer Display") objectDescription:_DTXStringReturningBlock(layer.description)];

__detox_sync_orig_dispatch_async(dispatch_get_main_queue(), ^ {
[self _untrackForParam:&_layerNeedsDisplayCount eventIdentifier:_DTXStringReturningBlock(identifier)];
[self _untrackForParam:&self->_layerNeedsDisplayCount eventIdentifier:_DTXStringReturningBlock(identifier)];
});
}

- (void)trackLayerPendingAnimation:(CALayer*)layer
{
NSString* identifier = [self _trackForParam:&_layerPendingAnimationCount eventDescription:_DTXStringReturningBlock(@"Layer Pending Animation") objectDescription:_DTXStringReturningBlock(layer.description)];

__detox_sync_orig_dispatch_async(dispatch_get_main_queue(), ^ {
[self _untrackForParam:&_layerPendingAnimationCount eventIdentifier:_DTXStringReturningBlock(identifier)];
[self _untrackForParam:&self->_layerPendingAnimationCount eventIdentifier:_DTXStringReturningBlock(identifier)];
});
}

Expand All @@ -160,9 +160,9 @@ - (void)trackViewControllerWillAppear:(UIViewController *)vc
if(vc.transitionCoordinator)
{
NSString* identifier = [self _trackForParam:&_viewControllerWillAppearCount eventDescription:_DTXStringReturningBlock(@"View Layout") objectDescription:_DTXStringReturningBlock(vc.description)];

[vc.transitionCoordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
[self _untrackForParam:&_viewControllerWillAppearCount eventIdentifier:_DTXStringReturningBlock(identifier)];
[self _untrackForParam:&self->_viewControllerWillAppearCount eventIdentifier:_DTXStringReturningBlock(identifier)];
}];
}
}
Expand All @@ -172,9 +172,9 @@ - (void)trackViewControllerWillDisappear:(UIViewController *)vc
if(vc.transitionCoordinator)
{
NSString* identifier = [self _trackForParam:&_viewControllerWillDisappearCount eventDescription:_DTXStringReturningBlock(@"View Layout") objectDescription:_DTXStringReturningBlock(vc.description)];

[vc.transitionCoordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
[self _untrackForParam:&_viewControllerWillDisappearCount eventIdentifier:_DTXStringReturningBlock(identifier)];
[self _untrackForParam:&self->_viewControllerWillDisappearCount eventIdentifier:_DTXStringReturningBlock(identifier)];
}];
}
}
Expand Down
Loading