iOS AOP框架Aspects實現(xiàn)原理

前言

眾所周知,Aspects框架運用了AOP(面向切面編程)的思想,這里解釋下AOP的思想:AOP是針對業(yè)務(wù)處理過程中的切面進行提取,它所面對的是處理過程中的某個步驟或階段,以獲得邏輯過程中各部分之間低耦合性的隔離效果。也許大家用Aspects提供的兩個方法用著很爽,有沒有想揭開它的神秘面紗,看一下它的廬山真面目?接下來主要講下Aspects的主要實現(xiàn)原理。


ruhua.gif

實現(xiàn)原理

其實主要涉及到兩點,用過runtime的同學(xué)都知道swizzling和消息轉(zhuǎn)發(fā),如果還不是很清楚的同學(xué)可以看下我之前寫的一篇文章OC中swizzling的“移魂大法”,“移魂大法”我這邊就不累贅了,提下消息轉(zhuǎn)發(fā)。

消息轉(zhuǎn)發(fā)

MessageForward.jpg

當向一個對象發(fā)送消息的時候,在這個對象的類繼承體系中沒有找到該方法的時候,就會Crash掉,拋出* unrecognized selector sent to …異常信息,但是在拋出這個異常前其實還是可以拯救的,Crash之前會依次執(zhí)行下面的方法:

  1. resolveInstanceMethod (或resolveClassMethod):實現(xiàn)該方法,可以通過class_addMethod添加方法,返回YES的話系統(tǒng)在運行時就會重新啟動一次消息發(fā)送的過程,NO的話會繼續(xù)執(zhí)行下一個方法。

2.forwardingTargetForSelector:實現(xiàn)該方法可以將消息轉(zhuǎn)發(fā)給其他對象,只要這個方法返回的不是nil或self,也會重啟消息發(fā)送的過程,把這消息轉(zhuǎn)發(fā)給其他對象來處理。

  1. methodSignatureForSelector:會去獲取一個方法簽名,如果沒有獲取到的話就回直接挑用doesNotRecognizeSelector,如果能獲取的話系統(tǒng)就會創(chuàng)建一個NSlnvocation傳給forwardInvocation方法。

  2. forwardInvocation:該方法是上一個步傳進來的NSlnvocation,然后調(diào)用NSlnvocationinvokeWithTarget方法,轉(zhuǎn)發(fā)到對應(yīng)的Target。

  3. doesNotRecognizeSelector:拋出unrecognized selector sent to …異常。

整體原理

上面講了幾種消息轉(zhuǎn)發(fā)的方法,Aspects主要是利用了forwardInvocation進行轉(zhuǎn)發(fā),Aspects其實利用和kvo類似的原理,通過動態(tài)創(chuàng)建子類的方式,把對應(yīng)的對象isa指針指向創(chuàng)建的子類,然后把子類的forwardInvocationIMP替成__ASPECTS_ARE_BEING_CALLED__,假設(shè)要hook的方法名XX,在子類中添加一個Aspects_XX的方法,然后將Aspects_XXIMP指向原來的XX方法的IMP,這樣方便后面調(diào)用原始的方法,再把要hook的方法XXIMP指向_objc_msgForward,這樣就進入了消息轉(zhuǎn)發(fā)流程,而forwardInvocationIMP被替換成了__ASPECTS_ARE_BEING_CALLED__,這樣就會進入__ASPECTS_ARE_BEING_CALLED__進行攔截處理,這樣整個流程大概結(jié)束。

代碼解析

代碼解析這塊的話主要講下核心的模塊,一些邊邊角角的東西去看了自然就明白了。

typedef NS_OPTIONS(NSUInteger, AspectOptions) {
    AspectPositionAfter   = 0,            /// Called after the original implementation (default)
    AspectPositionInstead = 1,            /// Will replace the original implementation.
    AspectPositionBefore  = 2,            /// Called before the original implementation.

    AspectOptionAutomaticRemoval = 1 << 3 /// Will remove the hook after the first execution.
};

AspectOptions提供各種姿勢,前插、后插、整個方法替換都行,簡直就是爽。

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

aspect_add、aspect_remove方法里面用了aspect_performLocked, 而aspect_performLocked方法用了OSSpinLockLock加鎖機制,保證線程安全并且性能高。不過這種鎖已經(jīng)不在安全,主要原因發(fā)生在低優(yōu)先級線程拿到鎖時,高優(yōu)先級線程進入忙等(busy-wait)狀態(tài),消耗大量 CPU 時間,從而導(dǎo)致低優(yōu)先級線程拿不到 CPU 時間,也就無法完成任務(wù)并釋放鎖。這種問題被稱為優(yōu)先級反轉(zhuǎn),有興趣的可以點擊任意門不再安全的 OSSpinLock

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

aspect_hookClass這個方法顧名思義就是要hook對應(yīng)的Class,這在里創(chuàng)建子類,通過aspect_swizzleForwardInvocation方法把forwardInvocation的實現(xiàn)替換成__ASPECTS_ARE_BEING_CALLED__, aspect_hookedGetClass修改了 subclass 以及其 subclass metaclass 的 class 方法,使他返回當前對象的 class,最后通過object_setClass把isa指針指向subclass

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_isMsgForwardIMP方法判斷要hook的方法時候被hook了,這里如果有使用JSPatch的話會沖突掉,不過JSPatch已經(jīng)被蘋果禁止使用了,蘋果爸爸說的算。如果沒有被hook走的話會先創(chuàng)建一個有自己別名的方法,然后把這個帶有別名方法的IMP指向原始要hook方法的實現(xiàn),最后要hook的方法的IMP指向_objc_msgForward或者_objc_msgForward_stret,為什么還會有一個_objc_msgForward_stret,詳細原因可以參考JSPatch實現(xiàn)原理詳解<二>里面的Special Struct

// This is the swizzled forwardInvocation: method.
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)];
}

該函數(shù)為swizzle后, 實現(xiàn)新IMP統(tǒng)一處理的核心方法 , 完成一下幾件事:

  • 處理調(diào)用邏輯, 有before, instead, after, remove四種option
  • 將block轉(zhuǎn)換成一個NSInvocation對象以供調(diào)用。
  • AspectsContainer根據(jù)aliasSelector取出對象, 并組裝一個AspectInfo, 帶有原函數(shù)的調(diào)用參數(shù)和各項屬性, 傳給外部的調(diào)用者 (在這是block) .
  • 調(diào)用完成后銷毀帶有removeOptionhook邏輯, 將原selector掛鉤到原IMP上, 刪除別名selector

總結(jié)

-forwardInvocation:的消息轉(zhuǎn)發(fā)雖然看起來很神奇,但是平時沒什么需求的話盡量不要去碰這個東西,一般的話swizzling基本可以滿足我們項目的大部分需求了,還有就是JSPatch既然不能用了,但是Aspects這個框架還是正常上AppStore的,利用這個庫的話還是可以弄出輕量級Hotfix,感興趣的同學(xué)可以點擊輕量級低風險 iOS 熱更新方案

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容