9、方法的調(diào)用原理(2)

好消息,先前電腦升級成Big Sur,導(dǎo)致新系統(tǒng)下源碼調(diào)試有問題,現(xiàn)在Big Sur又更新版本了,已經(jīng)可以配置源碼調(diào)試了,這篇文章后將用新的環(huán)境來研究。

2.方法調(diào)用的流程
2.2——methods查找(慢速查找)

鑒于研究慢速查找,因此對源碼修改一下:

@interface Person : NSObject
@property (nonatomic,assign)   int age;
@property (nonatomic,strong)   NSString *nickname;
@property (nonatomic,assign)   float height;
@property (nonatomic,strong)   NSString *name;

-(void)laugh;
-(void)cry;
-(void)run;
-(void)jump;
-(void)doNothing;
@end

@implementation Person
-(void)laugh
{
    NSLog(@"LMAO");
}

-(void)cry
{
    NSLog(@"cry me a river");
}

-(void)run
{
    NSLog(@"run! Forrest run!");
}

-(void)jump
{
    NSLog(@"you jump,I jump!");
}

-(void)doNothing
{
    NSLog(@"Today,I dont wanna do anything~");
}


//-(void)talkShow
//{
//    NSLog(@"roast king!");
//}


@end

@interface Saler : Person

@property (nonatomic,strong)   NSString *brand;


-(void)talkShow;

+(void)sayGiao;

@end

@implementation Saler

//-(void)talkShow
//{
//    NSLog(@"roast king!");
//}


//+(void)sayGiao
//{
//    NSLog(@"one geli my giao!");
//}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //main方法中
        Saler *person =  [Saler alloc];
        
        person.age = 10;
        person.nickname = @"pp";
        person.height = 180.0;
        person.name = @"ppext";
        person.brand = @"apple";

        Saler *saler = [Saler alloc];
        saler.age = 28;
        saler.nickname = @"xx";
        saler.height = 175.0;
        saler.name = @"xxext";
        saler.brand = @"apple";
//實例方法
//        [saler talkShow];
//類方法
        [Saler sayGiao];   
    }
    return 0;
}

書接上文,8、方法調(diào)用原理(1)中在cache的查找流程完成后,會調(diào)用lookUpImpOrForward(obj, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER),下面就對這個方法進行全局搜索,研究一下流程:

IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
    const IMP forward_imp = (IMP)_objc_msgForward_impcache;
    IMP imp = nil;
    Class curClass;

    runtimeLock.assertUnlocked();

    // Optimistic cache lookup
    if (fastpath(behavior & LOOKUP_CACHE)) {
        imp = cache_getImp(cls, sel);
        if (imp) goto done_nolock;
    }

    // runtimeLock is held during isRealized and isInitialized checking
    // to prevent races against concurrent realization.

    // runtimeLock is held during method search to make
    // method-lookup + cache-fill atomic with respect to method addition.
    // Otherwise, a category could be added but ignored indefinitely because
    // the cache was re-filled with the old value after the cache flush on
    // behalf of the category.

    runtimeLock.lock();

    // We don't want people to be able to craft a binary blob that looks like
    // a class but really isn't one and do a CFI attack.
    //
    // To make these harder we want to make sure this is a class that was
    // either built into the binary or legitimately registered through
    // objc_duplicateClass, objc_initializeClassPair or objc_allocateClassPair.
    checkIsKnownClass(cls);

    if (slowpath(!cls->isRealized())) {
        cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
        // runtimeLock may have been dropped but is now locked again
    }

    if (slowpath((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized())) {
        cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
        // runtimeLock may have been dropped but is now locked again

        // If sel == initialize, class_initialize will send +initialize and 
        // then the messenger will send +initialize again after this 
        // procedure finishes. Of course, if this is not being called 
        // from the messenger then it won't happen. 2778172
    }

    runtimeLock.assertLocked();
    curClass = cls;

    // The code used to lookpu the class's cache again right after
    // we take the lock but for the vast majority of the cases
    // evidence shows this is a miss most of the time, hence a time loss.
    //
    // The only codepath calling into this without having performed some
    // kind of cache lookup is class_getInstanceMethod().

    for (unsigned attempts = unreasonableClassCount();;) {
        // curClass method list.
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp(false);
            goto done;
        }

        if (slowpath((curClass = curClass->superclass) == nil)) {
            // No implementation found, and method resolver didn't help.
            // Use forwarding.
            imp = forward_imp;
            break;
        }

        // Halt if there is a cycle in the superclass chain.
        if (slowpath(--attempts == 0)) {
            _objc_fatal("Memory corruption in class list.");
        }

        // Superclass cache.
        imp = cache_getImp(curClass, sel);
        if (slowpath(imp == forward_imp)) {
            // Found a forward:: entry in a superclass.
            // Stop searching, but don't cache yet; call method
            // resolver for this class first.
            break;
        }
        if (fastpath(imp)) {
            // Found the method in a superclass. Cache it in this class.
            goto done;
        }
    }

    // No implementation found. Try method resolver once.

    if (slowpath(behavior & LOOKUP_RESOLVER)) {
        behavior ^= LOOKUP_RESOLVER;
        return resolveMethod_locked(inst, sel, cls, behavior);
    }

 done:
    log_and_fill_cache(cls, imp, sel, inst, curClass);
    runtimeLock.unlock();
 done_nolock:
    if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
        return nil;
    }
    return imp;
}

根據(jù)上文對MethodTableLookup源碼注釋分析知道是這種參數(shù)傳遞調(diào)用lookUpImpOrForward(obj, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER),與大多數(shù)objc-4 781.1源碼類似,這里也分slowpathfastpath分支:
個分支fastpath(behavior & LOOKUP_CACHE)是判斷是否是在查找cache中的buckets進入的的lookUpImpOrForward方法,而且大概率是的,就直接調(diào)用cache_getImp方法,可以參考8、方法的調(diào)用原理(1)objc_MsgSend()的流程,正常的快速查找流程。
個分支slowpath(!cls->isRealized()),顯而易見確認類是否是實現(xiàn)的,而且大概率是實現(xiàn)了的,沒實現(xiàn)的話,會先進行類的實現(xiàn)再走下一步驟,且類的實現(xiàn)分兩種,一種是非Swift類型的,另一種是Swift類型。
個分支slowpath((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized()),確認behavior是否是查詢類的初始化且類是否已經(jīng)初始化了,大概率是已經(jīng)初始化了的,沒有的話就對類進行初始化。
個分支for (unsigned attempts = unreasonableClassCount();;)固定數(shù)目循環(huán),unreasonableClassCount循環(huán)次數(shù)多少是根據(jù)繼承鏈而定,結(jié)合4、isa與對象、類的關(guān)系isa走位圖分析如果是實例方法: 實例——類——父類——NSObject,如果是類方法:類——元類——根元類——NSObject,斷點調(diào)試發(fā)現(xiàn)會循環(huán)制NSObject的父類,也就是nil然后就跳出循環(huán)了。
四——一個分支Method meth = getMethodNoSuper_nolock(curClass, sel)方法列表中二分法搜尋方法,不搜尋父類的,搜到則跳轉(zhuǎn)至done代碼塊。
四——二個分支slowpath((curClass = curClass->superclass) == nil)判斷父類是否存在,存在概率很大,并將curClass變成父類,沒有父類就將進入imp = forward_imp,也就是消息轉(zhuǎn)發(fā)流程。
四——三個分支slowpath(--attempts == 0)判斷循環(huán)次數(shù)是否是0,大概率不為0,如果為0就是內(nèi)存中類列表被污染,報錯。
四——四個分支slowpath(imp == forward_imp),在這個之前imp = cache_getImp(curClass, sel)先搜索當前類的緩存是否有這個方法,這里的當前類可能是已經(jīng)轉(zhuǎn)化為父類了curClass = curClass->superclass;然后就是判斷是否走消息轉(zhuǎn)發(fā)流程,是的話直接跳出循環(huán),大概率不是轉(zhuǎn)發(fā)流程。
四——五個分支fastpath(imp)判斷imp是否找到,大概率找到,找到就會走done代碼塊。
個分支slowpath(behavior & LOOKUP_RESOLVER),判斷當前代碼流程行為是否是LOOKUP_RESOLVER,大概率不是,就會走if的代碼塊,進入resolveMethod_locked對方法進行決議,意味著類以及父類中都沒發(fā)現(xiàn)該方法,resolveMethod_locked主要是:

static NEVER_INLINE IMP
resolveMethod_locked(id inst, SEL sel, Class cls, int behavior)
{
    runtimeLock.assertLocked();
    ASSERT(cls->isRealized());

    runtimeLock.unlock();

    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]
        resolveInstanceMethod(inst, sel, cls);
    } 
    else {
        // try [nonMetaClass resolveClassMethod:sel]
        // and [cls resolveInstanceMethod:sel]
        resolveClassMethod(inst, sel, cls);
        if (!lookUpImpOrNil(inst, sel, cls)) {
            resolveInstanceMethod(inst, sel, cls);
        }
    }

    // chances are that calling the resolver have populated the cache
    // so attempt using it
    return lookUpImpOrForward(inst, sel, cls, behavior | LOOKUP_CACHE);
}

判斷是實例方法還是類方法,來發(fā)送決議方法消息,并進入lookUpImpOrForward查找決議方法的IMP,流程和之前分析lookUpImpOrForward類似,只不過換做是尋找resolveInstanceMethod或者resolveClassMethod,resolveClassMethod也就是類的InsatanceMethod,在NSObject中必然找到這個方法所以必然是找的到的。

最后:
done: log_and_fill_cache記錄并插入cache
done_nolockslowpath((behavior & LOOKUP_NIL) && imp == forward_imp)
判斷是否當前流程行為是否是LOOKUP_NILimp == forward_imp,大概率不是,如果不是將返回nil
return:返回imp。
到看到forwardresolve的方法就可以基本知道,慢速查找基本完成。因為這兩個方法將消息發(fā)送重新定向了這里兩個消息的發(fā)送。

如果對這里的分析中的大概率小概率有所疑問,請參考查漏補缺

2.3——慢速查找補充分析
2.3.1 getMethodNoSuper_nolock方法

在類信息查找Method對應(yīng)的就是在getMethodNoSuper_nolock方法中:

static method_t *
getMethodNoSuper_nolock(Class cls, SEL sel)
{
    runtimeLock.assertLocked();

    ASSERT(cls->isRealized());
    // fixme nil cls? 
    // fixme nil sel?

    auto const methods = cls->data()->methods();
    for (auto mlists = methods.beginLists(),
              end = methods.endLists();
         mlists != end;
         ++mlists)
    {
        // <rdar://problem/46904873> getMethodNoSuper_nolock is the hottest
        // caller of search_method_list, inlining it turns
        // getMethodNoSuper_nolock into a frame-less function and eliminates
        // any store from this codepath.
        method_t *m = search_method_list_inline(*mlists, sel);
        if (m) return m;
    }

    return nil;
}

與之前文章6、類結(jié)構(gòu)分析分析lldb打印對應(yīng),通過data來獲得methods,通過search_method_list_inline方法類定位對應(yīng)要找的method_t,再就是對search_method_list_inline分析:

ALWAYS_INLINE static method_t *
search_method_list_inline(const method_list_t *mlist, SEL sel)
{
    //確定方法列表是否是修正過的
    int methodListIsFixedUp = mlist->isFixedUp();
    //確定方法列表大小是否正確
    int methodListHasExpectedSize = mlist->isExpectedSize();
    
    if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
        return findMethodInSortedMethodList(sel, mlist);
    } else {
        // Linear search of unsorted method list
        for (auto& meth : *mlist) {
            if (meth.name() == sel) return &meth;
        }
    }

#if DEBUG
    // sanity-check negative results
    if (mlist->isFixedUp()) {
        for (auto& meth : *mlist) {
            if (meth.name() == sel) {
                _objc_fatal("linear search worked when binary search did not");
            }
        }
    }
#endif

    return nil;
}

到這步,在類信息中搜索方法的流程就基本上清楚,這個方法內(nèi)還有一個findMethodInSortedMethodList方法是具體的查找算法,也分析一下:

ALWAYS_INLINE static method_t *
findMethodInSortedMethodList(SEL key, const method_list_t *list)
{
    ASSERT(list);

    auto first = list->begin();
    auto base = first;
    decltype(first) probe;

    uintptr_t keyValue = (uintptr_t)key;
    uint32_t count;
    
    for (count = list->count; count != 0; count >>= 1) {
        probe = base + (count >> 1);
        
        uintptr_t probeValue = (uintptr_t)probe->name();
        
        if (keyValue == probeValue) {
            // `probe` is a match.
            // Rewind looking for the *first* occurrence of this value.
            // This is required for correct category overrides.
            while (probe > first && keyValue == (uintptr_t)(probe - 1)->name()) {
                probe--;
            }
            return &*probe;
        }
        
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}

主要在for循環(huán)內(nèi),是逆序的循環(huán),而且每次count >>= 1,右移一位,這個跨度是多大,在二進制中相當于1/2,特點很明顯二分法查找。
當查找到keyValue == probeValue時,下面while循環(huán)是為了找到比當前的probe更靠前的位置是否還存在這個方法名,注釋的解釋是需要正確的分類重載,那大概可以猜測的時分類方法重載時,是會將分類方法插在原有方法之前的位置。
找到后就會返回probe這個method_t。

2.3.2 imp = cache_getImp(curClass, sel)方法

lookUpImpOrForward方法中的流程還沒有完全分析完成,比較重要的漏掉的,在getMethodNoSuper_nolock之后有imp = cache_getImp(curClass, sel);方法,注釋就是父類的Cache,也就是自身的方法列表沒找到,先在父類的cache中查找,這里其實流程和之前文章8、方法的調(diào)用原理(1)中的_objc_msgSend方法中的:CacheLookup NORMAL, _objc_msgSend方法的調(diào)用類似,這里調(diào)用的是CacheLookup GETIMP, _cache_getImp,對照_objc_msgSend的參數(shù)調(diào)用的是person這個對象,獲取的是這個對象的isa。_cache_getImp傳入的參數(shù)是curClass,獲取的是這個類的isa,以為處在for的死循環(huán)中,curClass是按照實例——類——父類——NSObject或者類——元類——根元類——NSObject的變化來的,會循環(huán)按這個繼承鏈查找,所以這里會查詢父類或者元類的cache混存中是否存在對應(yīng)的方法。

2.4——methods查找(慢速查找)總結(jié)

慢速查找流程圖
這個就是慢速查找基本流程(也是借鑒了大神的圖-。-)。
這里分析要注意:
1、for循環(huán)那一段代碼塊和消息決議resolveMethod_locked已經(jīng)涉及了嵌套的調(diào)用lookUpImpOrForward方法,需要開啟Debug——>Debug Workflow——>Always Show Disassembly來斷點調(diào)試。(lookUpImpOrForward為什么寫的這么凌亂,因為它是一個無限月瀆的方法-。-)
2、測試的類和方法,要適當不實現(xiàn),讓流程走向方法無法查找到的情況,就如源碼注銷的部分代碼。
3、整個流程是分代碼塊分析拼湊形成,最早的分析流程可能很凌亂,但是主要線路是兩條:一條是找到imp,一條是找不到imp
4、慢速查找流程沒查找到會走向resolveMethod_locked或者forward
5、消息決議方法也會走消息發(fā)送流程,即resolveInstanceMethod也會走objc_msgSend的流程。

最后編輯于
?著作權(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)容