Aspects源碼解析

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

基本概述,此框架提供了可以替換原方法的實現(xiàn),或者在方法執(zhí)行之前或者之后干點額外的工作的功能??戳斯δ埽苋菀缀唵未直┑赜X得原理就是方法hook、methods swizzle。
典型用法:
[UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) {
    NSLog(@"View Controller %@ will appear animated: %tu", aspectInfo.instance, animated);
} error:NULL];

先猜測:

Q1. 類名和實例對象hook 有啥區(qū)別?
  1. 類名直接調(diào)用aspect_hookSelector
  • hook的是類方法還是實例方法,必須要正確的區(qū)別這一點,才能正確的swizzle.
  1. 實例對象調(diào)用aspect_hookSelector
  • hook的一定是實例方法
Q2. 調(diào)用原方法,如果執(zhí)行block?
  • 以block的形式注冊,那么block注冊完存在哪里?如何存儲?
    這里的存儲應(yīng)該不是搞個容器啥的存相應(yīng)的block,而是注冊的時候,直接創(chuàng)建一個block相應(yīng)的方法,然后讓原有selector指向剛創(chuàng)建的方法。
  • 如何動態(tài)的創(chuàng)建方法應(yīng)對各種類型的block呢?動態(tài)的創(chuàng)建方法OC里面應(yīng)該做不到吧?可以動態(tài)的添加方法,所以上述猜想應(yīng)該不對。
  • 進一步猜想,直接走消息轉(zhuǎn)發(fā),那么這樣肯定是需要把block先存儲下來的。

跟蹤原因?qū)W習細節(jié)

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

這個方法是一個入口方法,在方法中會調(diào)用aspect_add,參數(shù)全部透傳過去,返回值是一個token,主要用于后續(xù)的deregister

static id aspect_add(id self, SEL selector, AspectOptions options, id block, NSError **error) {
    #1. 驗證參數(shù), 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. 根據(jù)selector取當前對象上存hook信息的容器,也就是支持對同一selector執(zhí)行多次hook
            identifier = [AspectIdentifier identifierWithSelector:selector object:self options:options block:block error:error]; #5. 根據(jù)參數(shù)生成本次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);
}

這個方法中主要就是以線程安全的方式執(zhí)行hook的注冊,涉及到全局selector黑名單的檢測、生成一個AspectsContainer、生成一個AspectIdentifier對象,這些對象的作用見上面代碼注釋,后續(xù)會詳細分析這兩個類。方法最后調(diào)用了真正的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));
    }
}
最后編輯于
?著作權(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)容