iOS - 方法查找流程

iOS - objc_msgSend分析一文中我們提到了__class_lookupMethodAndLoadCache3方法可以通過,全局搜索找到,那么還有其他的方式能看到_class_lookupMethodAndLoadCache3方法在哪里面呢?下面就介紹另一種方法:

1、通過查看匯編,找到_class_lookupMethodAndLoadCache3
1.1打斷點,查看匯編
1.2運行程序,由iOS - objc_msgSend分析一文我們知道,方法的快速查找會進入objc_msgSend方法中,因此我們在此處打斷點,按住control點擊Step into 進入該方法中;
1.3在_objc_msgSend_uncached出打斷點,按住control點擊Step into 進入方法中


至此我們完美的看到:_class_lookupMethodAndLoadCache3(id, SEL, Class) at objc-runtime-new.mm:4845證明了_class_lookupMethodAndLoadCache3方法實現(xiàn)在objc-runtime-new.mm文件中.

IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
/**
查找當前的imp或者轉(zhuǎn)發(fā)
     cls:如果是實例方法那就是類,如果是類方法那就是元類
     sel:方法名
     obj:方法調(diào)用者
     NO/*cache*/ //因為是CheckMiss狀態(tài)下點用的該方法,所以此處為NO
*/
    return lookUpImpOrForward(cls, sel, obj, 
                              YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}

2、方法查找流程

1.1 lookUpImpOrForward源碼分析
/**此處省略部分代碼*/

//為查找方法做準備條件,判斷類有沒有加載好,如果沒有加載好,那就先加載一下類信息,準備好父類、元類
    if (!cls->isRealized()) {
        realizeClass(cls);
    }
//確定類已經(jīng)加載完畢
    if (initialize  &&  !cls->isInitialized()) {
        runtimeLock.unlock();
        _class_initialize (_class_getNonMetaClass(cls, inst));
        runtimeLock.lock();
        // 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
    }

    
 retry:    
    runtimeLock.assertLocked();//加鎖,防止多個方法調(diào)用時產(chǎn)生沖突

    // Try this class's cache.

    imp = cache_getImp(cls, sel);//從該類的方法緩存中找imp,明顯緩存為NO,此處勢必拿不到方法的,因此會繼續(xù)走接下來的流程
    if (imp) goto done;//拿到方法就返回

    // Try this class's method lists.
    {
        Method meth = getMethodNoSuper_nolock(cls, sel);//在該類中查找該方法
        if (meth) {
//如果找到了則進行方法的緩存, log_and_fill_cache->cache_fill->cache_fill_nolock
            log_and_fill_cache(cls, meth->imp, sel, inst, cls);//進行緩存
            imp = meth->imp;//拿到imp
            goto done;
        }
    }

    // Try superclass caches and method lists.
    {
        unsigned attempts = unreasonableClassCount();
//遍歷父類,父類的父類等等一系列父類,直到為nil
        for (Class curClass = cls->superclass;
             curClass != nil;
             curClass = curClass->superclass)
        {
            // Halt if there is a cycle in the superclass chain.
            if (--attempts == 0) {
                _objc_fatal("Memory corruption in class list.");
            }
            
            // Superclass cache.
            imp = cache_getImp(curClass, sel);//從父類的方法緩存中查找該方法,如果拿到該方法則直接goto done
            if (imp) {
                if (imp != (IMP)_objc_msgForward_impcache) {
                    // Found the method in a superclass. Cache it in this class.
                    log_and_fill_cache(cls, imp, sel, inst, curClass);
                    goto done;
                }
                else {
                    // Found a forward:: entry in a superclass.
                    // Stop searching, but don't cache yet; call method 
                    // resolver for this class first.
                    break;
                }
            }
            
            // Superclass method list.
//如果在父類的方法緩存中沒有找到該方法,則從發(fā)類的方法列表中查到
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
                log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
                imp = meth->imp;
                goto done;
            }
        }
    }

    // No implementation found. Try method resolver once.
//如果方法仍然沒找到,就開始做方法消息動態(tài)解析了
    if (resolver  &&  !triedResolver) {
        runtimeLock.unlock();
/*
         實例方法解析:_class_resolveInstanceMethod
         類方法解析:_class_resolveClassMethod
         */
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.lock();
        // Don't cache the result; we don't hold the lock so it may have 
        // changed already. Re-do the search from scratch instead.
//將triedResolver標記為YES,下次就不會再進入動態(tài)方法解析
        triedResolver = YES;
        goto retry;
    }

    // No implementation found, and method resolver didn't help. 
    // Use forwarding.
//動態(tài)解析階段完成,進入消息轉(zhuǎn)發(fā)階段
    imp = (IMP)_objc_msgForward_impcache;
    cache_fill(cls, sel, imp, inst);

 done:
    runtimeLock.unlock();

    return imp;
}

getMethodNoSuper_nolock獲取方法列表
static method_t *
getMethodNoSuper_nolock(Class cls, SEL sel)
{
    runtimeLock.assertLocked();

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

    for (auto mlists = cls->data()->methods.beginLists(), 
              end = cls->data()->methods.endLists(); 
         mlists != end;
         ++mlists)
    {
        method_t *m = search_method_list(*mlists, sel);//通過二分查找獲取m,此處不做詳解,有興趣的可以自己看下源碼
        if (m) return m;
    }

    return nil;
}
_class_resolveMethod
void _class_resolveMethod(Class cls, SEL sel, id inst)
{
//首先會判斷cls是不是元類,如果cls不是元類的話,說明調(diào)用的是實例方法,那就就會調(diào)用_class_resolveInstanceMethod函數(shù),
    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]

        _class_resolveInstanceMethod(cls, sel, inst);
    } 
    else {
//如果是元類的話,說明調(diào)用的是類方法,那么就會調(diào)用_class_resolveClassMethod函數(shù),
        // try [nonMetaClass resolveClassMethod:sel]
        // and [cls resolveInstanceMethod:sel]
        _class_resolveClassMethod(cls, sel, inst);
        if (!lookUpImpOrNil(cls, sel, inst, 
                            NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
        {
            _class_resolveInstanceMethod(cls, sel, inst);
        }
    }
}
_objc_msgForward_impcache
STATIC_ENTRY __objc_msgForward_impcache

    // No stret specialization.
    b   __objc_msgForward //調(diào)用__objc_msgForward

    END_ENTRY __objc_msgForward_impcache

    
    ENTRY __objc_msgForward

    adrp    x17, __objc_forward_handler@PAGE
    ldr p17, [x17, __objc_forward_handler@PAGEOFF]//調(diào)用該方法
    TailCallFunctionPointer x17
    
    END_ENTRY __objc_msgForward 
通過全局搜索_objc_forward_handler我們可以找到
objc_defaultForwardHandler(id self, SEL sel)
{
    _objc_fatal("%c[%s %s]: unrecognized selector sent to instance %p "
                "(no message forward handler is installed)", 
                class_isMetaClass(object_getClass(self)) ? '+' : '-', 
                object_getClassName(self), sel_getName(sel), self);
}
void *_objc_forward_handler = (void*)objc_defaultForwardHandler;

這便是我們經(jīng)??吹降?方法查找不到時所報的錯誤.

流程總結(jié):

1.對需要的變量進行初始化操作和加鎖操作
2.在該類的方法緩存中進行查找,如果找到就就直接goto done;
3.緩存中查找不到時,則從該類的方法列表中進行查找,如果找到,則在緩存中備份一份,方便下次查找,然后goto done;
4.如果該類的方法列表用依舊找不到,則從該類的父類,父類的父類,一直找到NSObject類,依舊是先從父類的緩存中查找,緩存中有則直接goto done,否則就遍歷父類的方法列表,如果找到就直接goto done,找不到則break,進行方法決議;
5.實例方法會轉(zhuǎn)發(fā)+(BOOL) resolveInstanceMethod:(SEL)sel;類方法會轉(zhuǎn)發(fā)+(BOOL) resolveClassMethod:(SEL)sel,并且類方法轉(zhuǎn)發(fā)完后會再次走查找流程,如果還沒找到的話會走一下實例方法轉(zhuǎn)發(fā)流程;轉(zhuǎn)發(fā)邏輯完成后,會再次走一下方法查找邏輯
6.如果第一次轉(zhuǎn)發(fā)依然后還沒找到IMP,那么就會返回_objc_msgForward_impcache方法指針,調(diào)用_objc_forward_handler->objc_defaultForwardHandler,報出方法錯誤

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

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