iOS 底層探索 - 消息查找

iOS 底層探索系列算法

iOS 查漏補缺系列緩存

1、objc_msgSend 彙編補充

咱們知道,之因此使用匯編來實現 objc_msgSend 有兩個緣由:sass

  • 由於 C 沒法經過寫一個函數來保留未知的參數而且跳轉到一個任意的函數指針。
  • objc_msgSend 必須足夠快。

1.1 objc_msgSend 流程

  • ENTRY _objc_msgSend
  • 對消息接收者進行判斷、處理 (id self, sel _cmd)
  • taggedPointer 判斷處理
  • GetClassFromIsa_p16 isa 指針處理拿到 class
  • CacheLookup 查找緩存
  • cache_t 處理 bucket 以及內存哈希處理
    • 找不到遞歸下一個 bucket
    • 找到了就返回 {imp, sel} = *bucket->imp\
    • 遇到意外就重試
    • 找不到就跳到 junpMiss
  • __objc_msgSend_uncached 找不到緩存 imp
  • STATIC ENTRY __objc_msgSend_uncached
  • MethodTableLookup 方法表查找
    • save parameters registers
    • self 以及 _cmd 準備
    • _class_lookupMethodAndLoadCache3 調用

2、經過彙編找到下一流程

咱們在探索 objc_msgSend 的時候,當找不到緩存的時候,會來到一個地方叫作 objc_msgSend_uncached,而後會來到 MethodTableLookup,而後會有一個核心的查找方法 __class_lookupMethodAndLoadCache3。可是咱們知道其實已經要進入 C/C++ 的流程了,因此咱們還能夠彙編來定位。
咱們打開 Always Show Disassembly選項markdown

image.png

而後咱們進入 objc_msgSend 內部ide

image.png

而後咱們進入 _objc_msgSend_uncached 的內部函數

image.png

咱們會來到 _class_lookupMethodAndLoadCache3,這就是真正的方法查找實現。oop

3、代碼分析方法查找流程

3.1 對象方法測試

  • 對象的實例方法 - 本身有
  • 對象的實例方法 - 本身沒有 - 找父類的
  • 對象的實例方法 - 本身沒有 - 父類也沒有 - 找父類的父類 - NSObject
  • 對象的實例方法 - 本身沒有 - 父類也沒有 - 找父類的父類 - NSObject也沒有 - 崩潰

3.2 類方法測試

  • 類方法 - 本身有
  • 類方法 - 本身沒有 - 找父類的
  • 類方法 - 本身沒有 - 父類也沒有 - 找父類的父類 - NSObject
  • 類方法 - 本身沒有 - 父類也沒有 - 找父類的父類 - NSObject也沒有 - 崩潰
  • 類方法 - 本身沒有 - 父類也沒有 - 找父類的父類 - NSObject也沒有 - 可是有對象方法

4、源碼分析方法查找流程

咱們直接定位到 _class_lookupMethodAndLoadCache3 源碼處:源碼分析

IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
    return lookUpImpOrForward(cls, sel, obj, 
                              YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}
複製代碼

接着咱們進入 lookUpImpOrForward,這裏注意一下, cache 是傳的 NO,由於來到這裏已經說明緩存不存在,因此須要進行方法查找。post

image.png

4.1 lookUpImpOrForward

咱們接着定位到 lookUpImpOrForward 的源碼處:測試

IMP lookUpImpOrForward(Class cls, SEL sel, id inst, bool initialize, bool cache, bool resolver) 複製代碼

由該方法的參數咱們能夠知道,lookUpImpOrForward 應該是個公共方法,initializecache 分別表明是否避免 +initialize 和是否從緩存中查找。

// Optimistic cache lookup
    if (cache) {
        imp = cache_getImp(cls, sel);
        if (imp) return imp;
    }
複製代碼
  • 若是 cacheYES,那麼就直接調用 cache_getImp 來從 cls 的緩存中獲取 sel 對應的 IMP,若是找到了就返回。
if (!cls->isRealized()) {
        realizeClass(cls);
    }
複製代碼
  • 判斷當前要查找的 cls 是否已經完成了準備工做,若是沒有,則須要進行一下類的 realize

4.2 從當前類上查找

// 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;
        }
    }
複製代碼
  • 上面的方法很顯然,是從類的方法列表中查找 IMP。這裏加兩個大括號的目的是造成局部做用域,讓命名不會不想衝突。經過 getMethodNoSuper_nolock 查找 Method,找到了以後就調用 log_and_fill_cache 進行緩存的填充,而後返回 imp

4.2.1 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);
        if (m) return m;
    }

    return nil;
}

static method_t *search_method_list(const method_list_t *mlist, SEL sel) {
    int methodListIsFixedUp = mlist->isFixedUp();
    int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t);
    
    if (__builtin_expect(methodListIsFixedUp && methodListHasExpectedSize, 1)) {
        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;
}
複製代碼

getMethodNoSuper_nolock 實現很簡單,就是從 clsdata() 中進行遍歷,而後對遍歷到的 method_list_t 結構體指針再次調用 search_method_listsel 進行匹配。這裏的 findMethodInSortedMethodList 咱們再接着往下探索。

4.2.2 findMethodInSortedMethodList

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) {
            // `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 (method_t *)probe;
        }
        
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}
複製代碼

findMethodInSortedMethodList 的核心邏輯是二分查找,這種算法的前提是有序的集合。

4.3 從父類中查找

源碼以下:

// 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;
            }
        }
    }
複製代碼
// Superclass cache.
            imp = cache_getImp(curClass, sel);
複製代碼
  • 在父類中查找的時候,和在當前類查找有一點不一樣的是須要檢查緩存。
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;
                }
複製代碼
  • 若是在父類中找到了 IMP,同時判斷是不是消息轉發的入口,若是不是消息轉發,那麼就把找到的 IMP 經過 log_and_fill_cache 緩存到當前類的緩存中;若是是消息轉發,就退出循環。
// 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;
            }
複製代碼
  • 若是父類緩存中沒有找到,那麼就查找父類的方法列表,這裏和上面在當前類中的方法列表中查找是殊途同歸之妙,就再也不贅述了。

4.4 方法解析

// No implementation found. Try method resolver once.

    if (resolver  &&  !triedResolver) {
        runtimeLock.unlock();
        _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;
        goto retry;
    }
複製代碼

若是在類和父類中都沒有找到,Runtime 給了咱們一個機會來進行動態方法解析

/*********************************************************************** * _class_resolveMethod * Call +resolveClassMethod or +resolveInstanceMethod. * Returns nothing; any result would be potentially out-of-date already. * Does not check if the method already exists. **********************************************************************/
void _class_resolveMethod(Class cls, SEL sel, id inst)
{
    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]

        _class_resolveInstanceMethod(cls, sel, inst);
    } 
    else {
        // 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);
        }
    }
}
複製代碼

咱們來分析一下 _class_resolveMethod:

if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]

        _class_resolveInstanceMethod(cls, sel, inst);
    } 
    else {
        // 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);
        }
    }
複製代碼
  • 判斷當前類是不是元類,若是不是的話,調用 _class_resolveInstanceMethod
  • 若是是元類的話,說明要查找的是類方法,調用 _class_resolveClassMethod

4.4.1 _class_resolveInstanceMethod

首先咱們分析動態解析對象方法:

static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
{
    if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls, 
                         NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
    {
        // Resolver not implemented.
        return;
    }

    BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
    bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);

    // Cache the result (good or bad) so the resolver doesn't fire next time.
    // +resolveInstanceMethod adds to self a.k.a. cls
    IMP imp = lookUpImpOrNil(cls, sel, inst, 
                             NO/*initialize*/, YES/*cache*/, NO/*resolver*/);

    if (resolved  &&  PrintResolving) {
        if (imp) {
            _objc_inform("RESOLVE: method %c[%s %s] "
                         "dynamically resolved to %p", 
                         cls->isMetaClass() ? '+' : '-', 
                         cls->nameForLogging(), sel_getName(sel), imp);
        }
        else {
            // Method resolver didn't add anything?
            _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
                         ", but no new implementation of %c[%s %s] was found",
                         cls->nameForLogging(), sel_getName(sel), 
                         cls->isMetaClass() ? '+' : '-', 
                         cls->nameForLogging(), sel_getName(sel));
        }
    }
}

IMP lookUpImpOrNil(Class cls, SEL sel, id inst, bool initialize, bool cache, bool resolver) {
    IMP imp = lookUpImpOrForward(cls, sel, inst, initialize, cache, resolver);
    if (imp == _objc_msgForward_impcache) return nil;
    else return imp;
}
複製代碼

這裏還有一個注意點:

bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
複製代碼

對當前 cls 發送 SEL_resolveInstanceMethod 消息,若是返回的是 YES,那說明當前類是實現了動態方法解析。

由上面的代碼可知動態方法解析到最後會回到 lookUpImpOrForward。注意這裏的傳參:
cacheYESresolverNO,什麼意思呢?

Cache the result (good or bad) so the resolver doesn't fire next time. 緩存查找的結果,因此解析器下一次就不會被觸發,其實本質上就是打破遞歸

4.4.2 _class_resolveClassMethod

咱們接着分析動態解析類方法:

static void _class_resolveClassMethod(Class cls, SEL sel, id inst)
{
    assert(cls->isMetaClass());

    if (! lookUpImpOrNil(cls, SEL_resolveClassMethod, inst, 
                         NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
    {
        // Resolver not implemented.
        return;
    }

    BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
    bool resolved = msg(_class_getNonMetaClass(cls, inst), 
                        SEL_resolveClassMethod, sel);

    // Cache the result (good or bad) so the resolver doesn't fire next time.
    // +resolveClassMethod adds to self->ISA() a.k.a. cls
    IMP imp = lookUpImpOrNil(cls, sel, inst, 
                             NO/*initialize*/, YES/*cache*/, NO/*resolver*/);

    if (resolved  &&  PrintResolving) {
        if (imp) {
            _objc_inform("RESOLVE: method %c[%s %s] "
                         "dynamically resolved to %p", 
                         cls->isMetaClass() ? '+' : '-', 
                         cls->nameForLogging(), sel_getName(sel), imp);
        }
        else {
            // Method resolver didn't add anything?
            _objc_inform("RESOLVE: +[%s resolveClassMethod:%s] returned YES"
                         ", but no new implementation of %c[%s %s] was found",
                         cls->nameForLogging(), sel_getName(sel), 
                         cls->isMetaClass() ? '+' : '-', 
                         cls->nameForLogging(), sel_getName(sel));
        }
    }
}
複製代碼

這裏有一個注意點:傳進來的 cls 必須是元類,由於類方法存在元類的緩存或方法列表中。

// 對象方法動態解析
bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);

// 類方法動態解析
bool resolved = msg(_class_getNonMetaClass(cls, inst), 
                        SEL_resolveClassMethod, sel);
複製代碼

這裏 msg 方法的第一個參數就明顯不一樣,解析對象方法的時候傳的是當前類,而解析類方法的時候傳的是 _class_getNonMetaClass(cls, inst) 的結果。咱們進入 _class_getNonMetaClass 內部:

Class _class_getNonMetaClass(Class cls, id obj)
{
    mutex_locker_t lock(runtimeLock);
    cls = getNonMetaClass(cls, obj);
    assert(cls->isRealized());
    return cls;
}
複製代碼

接着進入 getNonMetaClass,這個方法的目的就是經過元類獲取類,咱們去除一些干擾信息:

static Class getNonMetaClass(Class metacls, id inst) {
    static int total, named, secondary, sharedcache;
    realizeClass(metacls);

    total++;

    // 若是已經不是元類的,那就直接返回
    if (!metacls->isMetaClass()) return metacls;

    // metacls really is a metaclass

    // 根元類的特殊狀況,這裏回憶一下,根元類的isa指向的是本身
    // where inst == inst->ISA() == metacls is possible
    if (metacls->ISA() == metacls) {
        Class cls = metacls->superclass;
        assert(cls->isRealized());
        assert(!cls->isMetaClass());
        assert(cls->ISA() == metacls);
        if (cls->ISA() == metacls) return cls;
    }

    // 若是實例不爲空
    if (inst) {
        Class cls = (Class)inst;
        realizeClass(cls);
        // cls 多是一個子類,這裏經過實例獲取到類對象,
        // 而後經過一個 while 循環來遍歷判斷類對象的 isa 是不是元類
        // 若是是元類的話,就跳出循環;若是不是接着獲取類對象的父類
        // cls may be a subclass - find the real class for metacls
        while (cls  &&  cls->ISA() != metacls) {
            cls = cls->superclass;
            realizeClass(cls);
        }
        // 說明已經找到了當前元類所匹配的類
        if (cls) {
            assert(!cls->isMetaClass());
            assert(cls->ISA() == metacls);
            return cls;
        }
#if DEBUG
        _objc_fatal("cls is not an instance of metacls");
#else
        // release build: be forgiving and fall through to slow lookups
#endif
    }

    // 嘗試命名查詢
    {
        Class cls = getClass(metacls->mangledName());
        if (cls->ISA() == metacls) {
            named++;
            if (PrintInitializing) {
                _objc_inform("INITIALIZE: %d/%d (%g%%) "
                             "successful by-name metaclass lookups",
                             named, total, named*100.0/total);
            }

            realizeClass(cls);
            return cls;
        }
    }

    // 嘗試 NXMapGet
    {
        Class cls = (Class)NXMapGet(nonMetaClasses(), metacls);
        if (cls) {
            secondary++;
            if (PrintInitializing) {
                _objc_inform("INITIALIZE: %d/%d (%g%%) "
                             "successful secondary metaclass lookups",
                             secondary, total, secondary*100.0/total);
            }

            assert(cls->ISA() == metacls);            
            realizeClass(cls);
            return cls;
        }
    }

    // try any duplicates in the dyld shared cache
    // 嘗試從 dyld 動態共享緩存庫中查詢
    {
        Class cls = nil;

        int count;
        Class *classes = copyPreoptimizedClasses(metacls->mangledName(),&count);
        if (classes) {
            for (int i = 0; i < count; i++) {
                if (classes[i]->ISA() == metacls) {
                    cls = classes[i];
                    break;
                }
            }
            free(classes);
        }

        if (cls) {
            sharedcache++;
            if (PrintInitializing) {
                _objc_inform("INITIALIZE: %d/%d (%g%%) "
                             "successful shared cache metaclass lookups",
                             sharedcache, total, sharedcache*100.0/total);
            }

            realizeClass(cls);
            return cls;
        }
    }

    _objc_fatal("no class for metaclass %p", (void*)metacls);
}
複製代碼

4.5 消息轉發

// No implementation found, and method resolver didn't help. 
    // Use forwarding.

    imp = (IMP)_objc_msgForward_impcache;
    cache_fill(cls, sel, imp, inst);
複製代碼

若是動態消息解析仍然失敗,那麼就會來到消息查找的最後一步了,消息轉發

此時會返回一個類型爲 _objc_msgForward_impcacheIMP,而後填充到 cls 中的 cache_t 裏面。至此,咱們的消息查找流程就此結束了。

5、總結

  • 方法查找或者說消息查找,起始於 _class_lookupMethodAndLoadCache3
  • _class_lookupMethodAndLoadCache3 的核心實現是 lookUpImpOrForward
  • _class_lookupMethodAndLoadCache3 進入的話,是忽略緩存直接從方法列表中查找。
  • 查找以前會確保類已經完成諸如 屬性、方法、協議等內容的 attach
  • 先從當前類的方法列表中查找,找到了返回,找不到交給父類。
  • 先從父類的緩存中查找,若是找到返回,若是沒有查找方法列表,找到了返回,找不到進行動態方法解析
  • 根據當前是類仍是元類來進行對象方法動態解析類方法動態解析
  • 若是解析成功,則返回,若是失敗,進入消息轉發流程。

咱們今天一塊兒探索了消息查找的底層,下一章咱們將會沿着今天的方向再往下探索方法轉發的流程。敬請期待~

相關文章
相關標籤/搜索