SwiftHook
SwiftHook copied to clipboard
Crash when hooking dispatch_source_t
Crash demo code:
#import "ViewController.h"
#import <Foundation/Foundation.h>
@import EasySwiftHook;
@interface ViewController ()
@property (nonatomic, strong) dispatch_source_t timer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self startTimer];
}
#pragma mark - timer
- (void)startTimer
{
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(self.timer, dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), 1 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(self.timer, ^{
NSLog(@"aaa");
});
dispatch_resume(self.timer);
NSError *error = nil;
[self.timer sh_hookDeallocAfterAndReturnError:&error closure:^{
NSLog(@"dealloc");
}];
NSAssert(error == nil, @"!!!");
}
@end
Crash screenshot:
Actually, this is a bug from KVO. The code below also crashes.
#import "ViewController.h"
#import <Foundation/Foundation.h>
@interface ViewController ()
@property (nonatomic, strong) dispatch_source_t timer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self startTimer];
}
#pragma mark - timer
- (void)startTimer
{
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(self.timer, dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), 1 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(self.timer, ^{
NSLog(@"aaa");
});
dispatch_resume(self.timer);
[self.timer addObserver:self forKeyPath:@"hash" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"%@", keyPath);
}
@end