SwiftHook icon indicating copy to clipboard operation
SwiftHook copied to clipboard

Crash when hooking dispatch_source_t

Open 623637646 opened this issue 4 years ago • 1 comments

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:

Screenshot 2022-01-08 at 3 25 39 PM

623637646 avatar Jan 08 '22 07:01 623637646

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

623637646 avatar Jan 08 '22 07:01 623637646