Aspects源码解析

Aspects 源码:https://github.com/steipete/Aspects

基本概述,此框架提供了可以替换原方法的实现,或者在方法执行之前或者之后干点额外的工作的功能。看了功能,很容易简单粗暴地觉得原理就是方法hook、methods swizzle。
典型用法:
[UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id aspectInfo, BOOL animated) {
    NSLog(@"View Controller %@ will appear animated: %tu", aspectInfo.instance, animated);
} error:NULL];

先猜测:

Q1. 类名和实例对象hook 有啥区别?
  1. 类名直接调用aspect_hookSelector
  • hook的是类方法还是实例方法,必须要正确的区别这一点,才能正确的swizzle.
  1. 实例对象调用aspect_hookSelector
  • hook的一定是实例方法
Q2. 调用原方法,如果执行block?
  • 以block的形式注册,那么block注册完存在哪里?如何存储?
    这里的存储应该不是搞个容器啥的存相应的block,而是注册的时候,直接创建一个block相应的方法,然后让原有selector指向刚创建的方法。
  • 如何动态的创建方法应对各种类型的block呢?动态的创建方法OC里面应该做不到吧?可以动态的添加方法,所以上述猜想应该不对。
  • 进一步猜想,直接走消息转发,那么这样肯定是需要把block先存储下来的。

跟踪原因学习细节

- (id)aspect_hookSelector:(SEL)selector
                      withOptions:(AspectOptions)options
                       usingBlock:(id)block
                            error:(NSError **)error {
    return aspect_add(self, selector, options, block, error);
}

这个方法是一个入口方法,在方法中会调用aspect_add,参数全部透传过去,返回值是一个token,主要用于后续的deregister

static id aspect_add(id self, SEL selector, AspectOptions options, id block, NSError **error) {
    #1. 验证参数, self、selector、block不能为nil

    __block AspectIdentifier *identifier = nil;
    aspect_performLocked(^{ #2, 自旋锁的方式保证线程安全
        if (aspect_isSelectorAllowedAndTrack(self, selector, options, error)) {
#3. 验证selectore是否是全局禁止hook的几个selector之一。Selectors like release, retain, autorelease are blacklisted.
            AspectsContainer *aspectContainer = aspect_getContainerForObject(self, selector);  #4. 根据selector取当前对象上存hook信息的容器,也就是支持对同一selector执行多次hook
            identifier = [AspectIdentifier identifierWithSelector:selector object:self options:options block:block error:error]; #5. 根据参数生成本次hook的一个identifier
            if (identifier) {
                [aspectContainer addAspect:identifier withOptions:options]; #6. 将identifier添加到容器中,这里面不理解为啥需要传options,可以从identifier中拿到options信息

                // #7. 真正的hook Modify the class to allow message interception.
                aspect_prepareClassAndHookSelector(self, selector, error);
            }
        }
    });
    return identifier;
}

采用自旋锁的方式保证线程安全

static void aspect_performLocked(dispatch_block_t block) {
    static OSSpinLock aspect_lock = OS_SPINLOCK_INIT;
    OSSpinLockLock(&aspect_lock);
    block();
    OSSpinLockUnlock(&aspect_lock);
}

这个方法中主要就是以线程安全的方式执行hook的注册,涉及到全局selector黑名单的检测、生成一个AspectsContainer、生成一个AspectIdentifier对象,这些对象的作用见上面代码注释,后续会详细分析这两个类。方法最后调用了真正的hook操作aspect_prepareClassAndHookSelector

static void aspect_prepareClassAndHookSelector(NSObject *self, SEL selector, NSError **error) {
    NSCParameterAssert(selector);
    Class klass = aspect_hookClass(self, error);
    Method targetMethod = class_getInstanceMethod(klass, selector);
    IMP targetMethodIMP = method_getImplementation(targetMethod);
    if (!aspect_isMsgForwardIMP(targetMethodIMP)) {
        // Make a method alias for the existing method implementation, it not already copied.
        const char *typeEncoding = method_getTypeEncoding(targetMethod);
        SEL aliasSelector = aspect_aliasForSelector(selector);
        if (![klass instancesRespondToSelector:aliasSelector]) {
            __unused BOOL addedAlias = class_addMethod(klass, aliasSelector, method_getImplementation(targetMethod), typeEncoding);
            NSCAssert(addedAlias, @"Original implementation for %@ is already copied to %@ on %@", NSStringFromSelector(selector), NSStringFromSelector(aliasSelector), klass);
        }

        // We use forwardInvocation to hook in.
        class_replaceMethod(klass, selector, aspect_getMsgForwardIMP(self, selector), typeEncoding);
        AspectLog(@"Aspects: Installed hook for -[%@ %@].", klass, NSStringFromSelector(selector));
    }
}

你可能感兴趣的:(Aspects源码解析)