Runtime底層原理探究(二) --- 消息發送機制(慢速查找)

源碼

/***********************************************************************
* lookUpImpOrForward.
* The standard IMP lookup. 
* initialize==NO tries to avoid +initialize (but sometimes fails)
* cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)
* Most callers should use initialize==YES and cache==YES.
* inst is an instance of cls or a subclass thereof, or nil if none is known. 
*   If cls is an un-initialized metaclass then a non-nil inst is faster.
* May return _objc_msgForward_impcache. IMPs destined for external use 
*   must be converted to _objc_msgForward or _objc_msgForward_stret.
*   If you don't want forwarding at all, use lookUpImpOrNil() instead. **********************************************************************/ IMP lookUpImpOrForward(Class cls, SEL sel, id inst, bool initialize, bool cache, bool resolver) { IMP imp = nil; bool triedResolver = NO; runtimeLock.assertUnlocked(); // Optimistic cache lookup if (cache) { /// 若是有緩存則從緩存裏取 imp = cache_getImp(cls, sel); if (imp) return imp; } // 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.read(); if (!cls->isRealized()) { // Drop the read-lock and acquire the write-lock. // realizeClass() checks isRealized() again to prevent // a race while the lock is down. runtimeLock.unlockRead(); runtimeLock.write(); realizeClass(cls); runtimeLock.unlockWrite(); runtimeLock.read(); } if (initialize && !cls->isInitialized()) { runtimeLock.unlockRead(); _class_initialize (_class_getNonMetaClass(cls, inst)); runtimeLock.read(); // 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.assertReading();

    // Try this class's cache. /// 這裏爲啥又取了一次imp /// /// 1. 保證併發 /// 2.remap(cls) -- 重映射 imp = cache_getImp(cls, sel); if (imp) goto done; // Try this class's method lists.
    {
        Method meth = getMethodNoSuper_nolock(cls, sel);
        if (meth) {
            log_and_fill_cache(cls, meth->imp, sel, inst, cls);
            imp = meth->imp;
            goto done;
        }
    }

    // Try superclass caches and method lists.
    {
        unsigned attempts = unreasonableClassCount();
        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);
            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. 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. if (resolver && !triedResolver) { runtimeLock.unlockRead(); _class_resolveMethod(cls, sel, inst); runtimeLock.read(); // 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; goto retry; } // No implementation found, and method resolver didn't help. 
    // Use forwarding.

    imp = (IMP)_objc_msgForward_impcache;
    cache_fill(cls, sel, imp, inst);

 done:
    runtimeLock.unlockRead();

    return imp;
}
複製代碼

lookUpImpOrForward

cache

首先聲明瞭一個nil imp,而後判斷cache 若是有則調用cache_ getImp,這個cache_ getimp是 是從緩存裏去取並不是遞歸,不會執行以前快速查找的代碼(慢速查找絕對沒有緩存,由於剛剛快速查找調用這個方法傳進來的第二個參數是NO,第一個參數的意思是)緩存

checkIsKnowClass

檢查類是不是已知類,若是是未知的則拋異常。若是是已知類則判斷是否已經實現,若是未實現則進行賦值,而後在判斷是否已經初始化。若是類未初始化,對其進行初始化。若是這個消息是initialize,那麼直接進行類的初始化bash

方法查找流程

此時他又執行cache_ getimp(之因此在此這麼作1是由於防止併發進行資源搶奪,2是由於remap可能會已經持有就不必浪費資源再去查找了),若是沒有則會執行一個的過程併發

// Try this class's method lists. { Method meth = getMethodNoSuper_nolock(cls, sel); if (meth) { log_and_fill_cache(cls, meth->imp, sel, inst, cls); imp = meth->imp; goto done; } } 複製代碼

而後傳入一個cls和sel,找到對應的imp若是存在則緩存後直接去done,若是沒有找到的話則去父類查找app

// Try superclass caches and method lists.
    {
        unsigned attempts = unreasonableClassCount();
        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);
            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. ///娶不到的話查找父類方法列表 Method meth = getMethodNoSuper_nolock(curClass, sel); if (meth) { log_and_fill_cache(cls, meth->imp, sel, inst, curClass); imp = meth->imp; goto done; } } } 複製代碼

查找父類循環條件是 父類不爲nil,則一直進行循環,若是父類方法有緩存則取緩存,而後緩存到子類的方法中,若是父類方法沒有緩存,則去方法列表裏查找而後進行緩存賦值。post

// No implementation found. Try method resolver once.

    if (resolver  &&  !triedResolver) {
        runtimeLock.unlockRead();
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.read();
        // 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;
        goto retry;
    }

    // No implementation found, and method resolver didn't help. // Use forwarding. imp = (IMP)_objc_msgForward_impcache; cache_fill(cls, sel, imp, inst); 複製代碼

若是沒有發現實現則會進入動態方法解析流程ui

ps: 2019年04月04日10:33:21 補充:

cache_getImp不會從緩存查找IMP,這個方法不會遞歸調用由於cache_getImp是一個 this

他掉用的GETIMP方法當調用CacheHit Checkmiss的時候並無發送objc_msgSend_uncached

慢速查找總結

當消息發送沒有經過查找時則會進入慢速查找,若是未初始化則進行類的初始化,首先查找當前類的方法列表經過Selector找到對應IMP,若是有則返回並緩存,沒有的話進行下一步遍歷父類直到nil若是父類裏存在則返回父類方法。並緩存到當前類,若是都沒有則判斷reslover參數是否支持消息轉發機制,若是支持則進入消息轉發流程,若是不支持則拋出異常。atom

相關文章
相關標籤/搜索