objc_msgSend源碼解析(二)

objc_msgSend源碼解析(一)中最后進(jìn)入_lookUpImpOrForward函數(shù)調(diào)用

1. _lookUpImpOrForward源碼分析

_objc_msgForward_impcache->_objc_msgForward->_objc_forward_handler  

__attribute__((noreturn, cold)) void
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;

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.lock();
 
    // TODO: this check is quite costly during process startup.
    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.assertLocked();
    curClass = cls; 

    for (unsigned attempts = unreasonableClassCount();;) {
        // curClass method list.
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp;
            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)) {
            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;
}

分析:

  1. 首先還是會(huì)在當(dāng)前類curClass的緩存中查找一遍,避免由于多線程問題,此時(shí)已經(jīng)將該方法放進(jìn)緩存
  2. 然后進(jìn)行類的一系列準(zhǔn)備及確認(rèn)工作
  3. 此時(shí)的for循環(huán)只要沒有跳出循環(huán),則相當(dāng)于死循環(huán),在for循環(huán)中先調(diào)用getMethodNoSuper_nolock方法,從當(dāng)前類curClassmethodlist中進(jìn)行查找,如果找到則放到緩存中
  4. 如果沒有找到,則將當(dāng)前類修改為當(dāng)前類的父類,即curClass=curClass->superclass,如果父類為nil,則給imp賦值為unrecognized selector
  5. 然后調(diào)用cache_getImp去父類的緩存中進(jìn)行查找,cache_getImp在父類緩存中如果找到,則返回imp,并放入自己類的緩存中
  6. 如果父類緩存中也沒有找到,即在cache_getImp函數(shù)中沒有找到imp,則繼續(xù)循環(huán),通過getMethodNoSuper_nolock函數(shù)查找父類的methodlist,如果沒有找到則遞歸查找父類緩存,父類方法列表,直到找到對(duì)應(yīng)的imp或者走到第4步
  7. 在返回unrecognized selector之前,會(huì)走一次resolveMethod_locked動(dòng)態(tài)方法解析的流程

2. getMethodNoSuper_nolock源碼分析

getMethodNoSuper_nolock -> search_method_list_inline -> findMethodInSortedMethodList

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


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

    const method_t * const first = &list->first;
    const method_t *base = first;
    const method_t *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) { 
            while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
                probe--;
            }
            return (method_t *)probe;
        }
        
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}

分析:在getMethodNoSuper_nolock函數(shù)中,遍歷methods中的方法數(shù)組,此時(shí)若存在分類,則分類最先被遍歷到。在findMethodInSortedMethodList函數(shù)中采用二分查找方式,由于methodmethodlist中存放的特點(diǎn),如果找到sel對(duì)應(yīng)的method,則會(huì)檢查該method的前一個(gè)methodname是否相同,直到找到第一個(gè)為止并返回,如果沒有找到則返回nil

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

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

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