Runtime底層原理探究(二) --- 訊息傳送機制(慢速查詢)

派二星發表於2019-04-02

原始碼

/***********************************************************************
* 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,那麼直接進行類的初始化

方法查詢流程

此時他又執行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,如果沒有找到的話則去父類查詢

 // 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,則一直進行迴圈,如果父類方法有快取則取快取,然後快取到子類的方法中,如果父類方法沒有快取,則去方法列表裡查詢然後進行快取賦值。

  // 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);
複製程式碼

如果沒有發現實現則會進入動態方法解析流程

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

cache_getImp不會從快取查詢IMP,這個方法不會遞迴呼叫因為cache_getImp是一個

Runtime底層原理探究(二) --- 訊息傳送機制(慢速查詢)
他掉用的GETIMP方法當呼叫CacheHit Checkmiss的時候並沒有傳送objc_msgSend_uncached

Runtime底層原理探究(二) --- 訊息傳送機制(慢速查詢)

慢速查詢總結

當訊息傳送沒有通過查詢時則會進入慢速查詢,如果未初始化則進行類的初始化,首先查詢當前類的方法列表通過Selector找到對應IMP,如果有則返回並快取,沒有的話進行下一步遍歷父類直到nil如果父類裡存在則返回父類方法。並快取到當前類,如果都沒有則判斷reslover引數是否支援訊息轉發機制,如果支援則進入訊息轉發流程,如果不支援則丟擲異常。

相關文章