美文网首页ios runtime专题
从 Aspects 来看 Runtime

从 Aspects 来看 Runtime

作者: wind黑子 | 来源:发表于2018-01-23 17:18 被阅读25次

    用 OC 开发 iOS 应用的人都知道 OC 是一门动态语言。我们能够在运行时通过 Runtime API 获取并替换任意方法。所以,在 AOP 和 热更新的实现上都经常可以看到 Runtime 的身影。这虽然看似美好,但运用不当的话通常会造成重大 bug。Runtime 对于 OC 来说就像是魔力强大但又十分危险的黑魔法。

    黑魔法.jpg

    1 消息转发

    iOS 的方法执行是通过 SEL 找到 对应的 IMP,然后执行相应的函数。如果 SEL 找不到对应的 IMP 就会启动消息转发机制。消息转发会经过三个阶段。

    • 第一阶段:在类的内部进行处理

        //处理实例方法
        + (BOOL)resolveInstanceMethod:(SEL)sel 
        //处理类方法
        + (BOOL)resolveClassMethod:(SEL)sel
      

      重写该方法可以对相应的 SEL 进行处理,返回 YES 说明处理完成,不进行下一步转发。

    • 第二阶段:寻找备援接收者

        - (id)forwardingTargetForSelector:(SEL)aSelector
      

      该方法会返回一个能够处理改消息的备援接收者。如果返回 nil 则继续下一步。

    • 第三阶段:全局处理

        - (void)forwardInvocation:(NSInvocation *)invocation
      

      将消息包装成一个 NSInvocation 对象,让系统对其进行处理。如果这里还是没有进行,则会抛出相应的异常。

    整个流程如下图所示:

    消息转发.jpg

    2 Aspects

    Aspects 通过 swizzling method 和 swizzling isa 实现对原方法的 hook ,以此来帮助使用者完成 AOP 编程。

    2.1 Aspect 主要主要类介绍:

    @interface AspectInfo : NSObject <AspectInfo>
    - (id)initWithInstance:(__unsafe_unretained id)instance invocation:(NSInvocation *)invocation;
    @property (nonatomic, unsafe_unretained, readonly) id instance;
    @property (nonatomic, strong, readonly) NSArray *arguments;
    @property (nonatomic, strong, readonly) NSInvocation *originalInvocation;
    @end
    

    AspectInfo:aspect 的信息,被 hook 方法的 IMP 信息存放在 NSInvocation 中。

    @interface AspectIdentifier : NSObject
    + (instancetype)identifierWithSelector:(SEL)selector object:(id)object options:(AspectOptions)options block:(id)block error:(NSError **)error;
    - (BOOL)invokeWithInfo:(id<AspectInfo>)info;
    @property (nonatomic, assign) SEL selector;
    @property (nonatomic, strong) id block;
    @property (nonatomic, strong) NSMethodSignature *blockSignature;
    @property (nonatomic, weak) id object;
    @property (nonatomic, assign) AspectOptions options;
    @end
    

    AspectIdentifier:一个 aspect 的具体信息,相应的 sel,options,block

    @interface AspectsContainer : NSObject
    - (void)addAspect:(AspectIdentifier *)aspect withOptions:(AspectOptions)injectPosition;
    - (BOOL)removeAspect:(id)aspect;
    - (BOOL)hasAspects;
    @property (atomic, copy) NSArray *beforeAspects;
    @property (atomic, copy) NSArray *insteadAspects;
    @property (atomic, copy) NSArray *afterAspects;
    @end
    

    AspectsContainer:本类所有的 aspect 的容器

    @interface AspectTracker : NSObject
    - (id)initWithTrackedClass:(Class)trackedClass;
    @property (nonatomic, strong) Class trackedClass;
    @property (nonatomic, readonly) NSString *trackedClassName;
    @property (nonatomic, strong) NSMutableSet *selectorNames;
    @property (nonatomic, strong) NSMutableDictionary *selectorNamesToSubclassTrackers;
    - (void)addSubclassTracker:(AspectTracker *)subclassTracker hookingSelectorName:(NSString *)selectorName;
    - (void)removeSubclassTracker:(AspectTracker *)subclassTracker hookingSelectorName:(NSString *)selectorName;
    - (BOOL)subclassHasHookedSelectorName:(NSString *)selectorName;
    - (NSSet *)subclassTrackersHookingSelectorName:(NSString *)selectorName;
    @end
    

    AspectTracker:用来追踪 aspect 的相关信息

    2.2 Aspects API调用之后发生的事情

    下面是 aspect 相关方法调用之后,主要的执行逻辑

    static id aspect_add(id self, SEL selector, AspectOptions options, id block, NSError **error) {
        NSCParameterAssert(self);
        NSCParameterAssert(selector);
        NSCParameterAssert(block);
    
        __block AspectIdentifier *identifier = nil;
        aspect_performLocked(^{
            if (aspect_isSelectorAllowedAndTrack(self, selector, options, error)) {
                AspectsContainer *aspectContainer = aspect_getContainerForObject(self, selector);
                identifier = [AspectIdentifier identifierWithSelector:selector object:self options:options block:block error:error];
                if (identifier) {
                    [aspectContainer addAspect:identifier withOptions:options];
    
                    // Modify the class to allow message interception.
                    aspect_prepareClassAndHookSelector(self, selector, error);
                }
            }
        });
        return identifier;
    }
    

    aspect 方法入口,先是断言判断传入的参数。然后 aspect_performLocked 加锁同步操作,通过 aspect_isSelectorAllowedAndTrack 判断该方法是否允许 hook。判断逻辑如下:

    1. 实例方法的"retain", "release", "autorelease", "forwardInvocation:" 不允许 hook , "dealloc" 方法只能是 AspectPositionBefore 的方式操作
    2. 类方法要判断父类,子类中没有 hook 过该方法。

    如果可以 hook,则根据参数生成一个 AspectIdentifier 对象,之后放在相应的 AspectsContainer 容器中,然后调用 aspect_prepareClassAndHookSelector 进行 class swizzling 和 method swizzling。

    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));
        }
    }
    

    调用 aspect_hookClass 进行相应的 class swizzling 操作。

    static Class aspect_hookClass(NSObject *self, NSError **error) {
        NSCParameterAssert(self);
        Class statedClass = self.class;
        Class baseClass = object_getClass(self);
        NSString *className = NSStringFromClass(baseClass);
    
        // Already subclassed
        if ([className hasSuffix:AspectsSubclassSuffix]) {
            return baseClass;
    
            // We swizzle a class object, not a single object.
        }else if (class_isMetaClass(baseClass)) {
            return aspect_swizzleClassInPlace((Class)self);
            // Probably a KVO'ed class. Swizzle in place. Also swizzle meta classes in place.
        }else if (statedClass != baseClass) {
            return aspect_swizzleClassInPlace(baseClass);
        }
    
        // Default case. Create dynamic subclass.
        const char *subclassName = [className stringByAppendingString:AspectsSubclassSuffix].UTF8String;
        Class subclass = objc_getClass(subclassName);
    
        if (subclass == nil) {
            subclass = objc_allocateClassPair(baseClass, subclassName, 0);
            if (subclass == nil) {
                NSString *errrorDesc = [NSString stringWithFormat:@"objc_allocateClassPair failed to allocate class %s.", subclassName];
                AspectError(AspectErrorFailedToAllocateClassPair, errrorDesc);
                return nil;
            }
    
            aspect_swizzleForwardInvocation(subclass);
            aspect_hookedGetClass(subclass, statedClass);
            aspect_hookedGetClass(object_getClass(subclass), statedClass);
            objc_registerClassPair(subclass);
        }
    
        object_setClass(self, subclass);
        return subclass;
    }
    

    class swizzling 的主要逻辑如下:

    1. 若 class 是元类,swizzling 相应的 ForwardInvocation 方法
    2. 若 class 是普通的类, 先判断是否是 KVO 对象,是的话 swizzling 相应的 ForwardInvocation 方法
    3. 若不是 KVO 对象的话,先创建一个子类,并 swizzling 子类的 ForwardInvocation,同时将本类的 isa 指针,指向创建的子类。

    hook 过的 class 都保存在 swizzledClasses 对象中。接下去进行 method swizzling, 调用 aspect_isMsgForwardIMP 确认实现函数不是消息转发相关的。然后让 aliasSelector 指向 targetMethodIMP,本来的 OriginalSel 指向 msgForwardIMP。至此设置阶段就完成了。

    2.3 被 Hook 的方法被调用之后发生的事情

    在调用 aspect 的 api 进行相关设置之后,程序执行到刚被 hook 过的方法就会进入 aspect 的执行逻辑。

    由于上面的设置,我们知道调用实例方法的类的 isa 会指向了一个子类,然后子类的 OriginalSel 指向了 msgForwardIMP, 而子类相应的 ForwardInvocation 也被替换了,指向了 __ASPECTS_ARE_BEING_CALLED__,所以,一旦调用相应的方法就会进入 __ASPECTS_ARE_BEING_CALLED__ 里面。

    如果是类方法,则是 OriginalSel 指向了 msgForwardIMP ,本身的 ForwardInvocation 被替换指向了__ASPECTS_ARE_BEING_CALLED__ ,所以一样进入到 __ASPECTS_ARE_BEING_CALLED__ 方法里。

    static void __ASPECTS_ARE_BEING_CALLED__(__unsafe_unretained NSObject *self, SEL selector, NSInvocation *invocation) {
        NSCParameterAssert(self);
        NSCParameterAssert(invocation);
        SEL originalSelector = invocation.selector;
        SEL aliasSelector = aspect_aliasForSelector(invocation.selector);
        invocation.selector = aliasSelector;
        AspectsContainer *objectContainer = objc_getAssociatedObject(self, aliasSelector);
        AspectsContainer *classContainer = aspect_getContainerForClass(object_getClass(self), aliasSelector);
        AspectInfo *info = [[AspectInfo alloc] initWithInstance:self invocation:invocation];
        NSArray *aspectsToRemove = nil;
    
        // Before hooks.
        aspect_invoke(classContainer.beforeAspects, info);
        aspect_invoke(objectContainer.beforeAspects, info);
    
        // Instead hooks.
        BOOL respondsToAlias = YES;
        if (objectContainer.insteadAspects.count || classContainer.insteadAspects.count) {
            aspect_invoke(classContainer.insteadAspects, info);
            aspect_invoke(objectContainer.insteadAspects, info);
        }else {
            Class klass = object_getClass(invocation.target);
            do {
                if ((respondsToAlias = [klass instancesRespondToSelector:aliasSelector])) {
                    [invocation invoke];
                    break;
                }
            }while (!respondsToAlias && (klass = class_getSuperclass(klass)));
        }
    
        // After hooks.
        aspect_invoke(classContainer.afterAspects, info);
        aspect_invoke(objectContainer.afterAspects, info);
    
        // If no hooks are installed, call original implementation (usually to throw an exception)
        if (!respondsToAlias) {
            invocation.selector = originalSelector;
            SEL originalForwardInvocationSEL = NSSelectorFromString(AspectsForwardInvocationSelectorName);
            if ([self respondsToSelector:originalForwardInvocationSEL]) {
                ((void( *)(id, SEL, NSInvocation *))objc_msgSend)(self, originalForwardInvocationSEL, invocation);
            }else {
                [self doesNotRecognizeSelector:invocation.selector];
            }
        }
    
        // Remove any hooks that are queued for deregistration.
        [aspectsToRemove makeObjectsPerformSelector:@selector(remove)];
    }
    

    __ASPECTS_ARE_BEING_CALLED__ 内部的逻辑是:根据 aliasSelector 获取之前存储的类或者元类的 AspectsContainer 对象,之后根据 AspectOptions 在适当的时机获取 AspectsContainer 中对应的所有 AspectIdentifier 并执行相应的 block 。
    同时处理被 hook 方法原来的实现( IMP ) , 被封装在 originalInvocation 中(若有 AspectIdentifier 的 AspectOptions 是 insteadAspects ,则 originalInvocation 将不会被执行)。若 AspectIdentifier 的 AspectOptions 是 AspectOptionAutomaticRemoval ,则该 AspectIdentifier 会被存入 aspectsToRemove 中,执行结束之后会被移除。

    3 总结

    以上就是本人对于 Aspects 这个强大的 AOP 库的一个大致理解。同时这里面还有很多细节很值得学习。

    4 参考文章

    面向切面编程之 Aspects 源码解析及应用

    相关文章

      网友评论

        本文标题:从 Aspects 来看 Runtime

        本文链接:https://www.haomeiwen.com/subject/ijasaxtx.html