IOS底層探索慢速查找

緩存找不到彙編分析

彙編查找流程中,MissLabelDynamicCacheLookup的第三個參數:c++

// NORMAL, _objc_msgSend, __objc_msgSend_uncached , MissLabelConstant
.macro CacheLookup Mode, Function, MissLabelDynamic, MissLabelConstant
複製代碼

也就對應着__objc_msgSend_uncached,全局搜索__objc_msgSend_uncached,在objc-msg-arm64.s數組

.endmacro

	STATIC_ENTRY __objc_msgSend_uncached
	UNWIND __objc_msgSend_uncached, FrameWithNoSaves

	// THIS IS NOT A CALLABLE C FUNCTION
	// Out-of-band p15 is the class to search
	//重要信息在MethodTableLookup
	MethodTableLookup
        //這裏這是調用返回
	TailCallFunctionPointer x17

	END_ENTRY __objc_msgSend_uncached
複製代碼
.macro MethodTableLookup
	
	SAVE_REGS MSGSEND

	// lookUpImpOrForward(obj, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER)
	// receiver and selector already in x0 and x1
	mov	x2, x16
	mov	x3, #3
	bl	_lookUpImpOrForward

	// IMP in x0
        //IMP在x0裏面,也就是_lookUpImpOrForward的返回值
	mov	x17, x0

	RESTORE_REGS MSGSEND

.endmacro
複製代碼

全局搜索lookUpImpOrForwardobjc-runtime-new.mm找到:緩存

//慢速查找流程
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior) 複製代碼

來到了c++。爲何查找緩存用匯編寫,而不用c++寫?markdown

  • 彙編更接近機器語言,執行流程很是快
  • 彙編更加動態化(參數未知),C語言參數必須固定

慢速查找lookUpImpOrForward分析

NEVER_INLINE 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();
     
     // //判斷類是否初始化
     if (slowpath(!cls->isInitialized())) {
        behavior |= LOOKUP_NOCACHE;
    }
    
    //加鎖,防止多線程操做
     runtimeLock.lock();
     //檢測是不是已知類,是否註冊到當前的緩存表裏面
     checkIsKnownClass(cls); 
      //初始化類、父類、元類 (isa走位實現)
     cls = realizeAndInitializeIfNeeded_locked(inst, cls, behavior & LOOKUP_INITIALIZE);
    // runtimeLock may have been dropped but is now locked again
    runtimeLock.assertLocked();
    curClass = cls;
    //死循環
     for (unsigned attempts = unreasonableClassCount();;) {
        if (curClass->cache.isConstantOptimizedCache(/* strict */true)) {
            //查找共享緩存
#if CONFIG_USE_PREOPT_CACHES
            imp = cache_getImp(curClass, sel);
            if (imp) goto done_unlock;
            curClass = curClass->cache.preoptFallbackClass();
#endif
        } else {
            // curClass method list.
            //查找方法列表(二分查找)
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
                imp = meth->imp(false);
                goto done;
            }
             //當前的class = curClass->getSuperclass()當前class的父類
 if (slowpath((curClass = curClass->getSuperclass()) == 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)) {
        //父類中返回的是forward,就中止查找,調用用方法
            // Found a forward:: entry in a superclass.
            // Stop searching, but don't cache yet; call method
            // resolver for this class first.
            break;
        }
        if (fastpath(imp)) {
            // Found the method in a superclass. Cache it in this class.
            goto done;
        }
    }

    // No implementation found. Try method resolver once.
   //方法沒有實現。嘗試一次方法解析器。
   // 3 & 2 = 2
    if (slowpath(behavior & LOOKUP_RESOLVER)) {
    // behavior = 0
        behavior ^= LOOKUP_RESOLVER;
        //動態方法決議
        return resolveMethod_locked(inst, sel, cls, behavior);
    }

 done:
    if (fastpath((behavior & LOOKUP_NOCACHE) == 0)) {
#if CONFIG_USE_PREOPT_CACHES
        while (cls->cache.isConstantOptimizedCache(/* strict */true)) {
            cls = cls->cache.preoptFallbackClass();
        }
#endif
       //緩存填充
        log_and_fill_cache(cls, imp, sel, inst, curClass);
    }
 done_unlock:
    runtimeLock.unlock();
    if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
        return nil;
    }
    return imp;
}

複製代碼

lookUpImpOrForward慢速查找流程:多線程

  1. checkIsKnownClass判斷當前類是不是註冊過的類,不是就直接報錯Attempt to use unknown class
  2. realizeAndInitializeIfNeeded_locked初始化類,父類,元類,父類的父類等等一系列類的實現(isa走位實現)

for循環遍歷:less

  1. 查找共享緩存,若是有找到就直接返回ide

  2. 共享緩存沒找到,查找當前類(二分查找),若是找到就退出循環,執行緩存填充log_and_fill_cachepost

  3. 當前類未找到,就查找當前類的父類,若是父類也有循環,就報錯Memory corruption in class listui

  4. 先查找父類的緩存若是找到就退出循環,執行緩存填充log_and_fill_cache,若是沒找到就查找父類的父類(遞歸),直到curClass=nil,還沒找到就將forward_imp賦值給impthis

  5. 若是沒有執行過動態方法決議,能夠執行一次,沒有實現,就消息轉發。

慢速查找流程圖

慢速.png

cache_getImp分析

cache_getImp(curClass, sel)

全局搜索cache_getImp, 在objc-msg-arm64.s找到:

STATIC_ENTRY _cache_getImp

	GetClassFromIsa_p16 p0, 0
	CacheLookup GETIMP, _cache_getImp, LGetImpMissDynamic, LGetImpMissConstant
複製代碼

image.png 由於GetClassFromIsa_p16 p0, 0,因此p0就是curClassneeds_auth= 0Mov p16curClassp16.接着調用

CacheLookup GETIMP, _cache_getImp, LGetImpMissDynamic, LGetImpMissConstant

複製代碼

查找流程可查看CacheLookup彙編分析。 緩存找不到的狀況下,直接將0放到p0中,返回

LGetImpMissDynamic:
	mov	p0, #0
	ret
複製代碼

二分查找流程

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 * search_method_list_inline(const method_list_t *mlist, SEL sel) {
    int methodListIsFixedUp = mlist->isFixedUp();
    int methodListHasExpectedSize = mlist->isExpectedSize();
     省略部分代碼
    if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
    //排好的方法列表 
        return findMethodInSortedMethodList(sel, mlist);
    } else {
        // Linear search of unsorted method list
        if (auto *m = findMethodInUnsortedMethodList(sel, mlist))
            return m;
    }
    省略部分代碼
    return nil;
}
複製代碼
ALWAYS_INLINE static method_t * findMethodInSortedMethodList(SEL key, const method_list_t *list) {
    //M1電腦走這裏
    if (list->isSmallList()) {
        if (CONFIG_SHARED_CACHE_RELATIVE_DIRECT_SELECTORS && objc::inSharedCache((uintptr_t)list)) {
            return findMethodInSortedMethodList(key, list, [](method_t &m) { return m.getSmallNameAsSEL(); });
        } else {
            return findMethodInSortedMethodList(key, list, [](method_t &m) { return m.getSmallNameAsSELRef(); });
        }
    } else {
        //二分查找
        return findMethodInSortedMethodList(key, list, [](method_t &m) { return m.big().name; });
    }
}

複製代碼

調用流程: lookUpImpOrForward->getMethodNoSuper_nolock->search_method_list_inline->findMethodInSortedMethodList

template<class getNameFunc> ALWAYS_INLINE static method_t * findMethodInSortedMethodList(SEL key, const method_list_t *list, const getNameFunc &getName) {
    ASSERT(list);

    auto first = list->begin();
    auto base = first;
    decltype(first) probe;

    uintptr_t keyValue = (uintptr_t)key;
    uint32_t count;
    //假如count是8 二進制: 1000 右移一位 0100 是 4 減半了
    for (count = list->count; count != 0; count >>= 1) {
        // probe初始化是0
        // probe = 0 + 4 = 4
        probe = base + (count >> 1);
        
        //經過probe獲取name
        uintptr_t probeValue = (uintptr_t)getName(probe);
        
        //若是找到方法
        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)getName((probe - 1))) {
                probe--;
            }
            //返回method_t
            return &*probe;
        }
        //若是沒有找到
        if (keyValue > probeValue) {
            //base = 4+1 = 5
            base = probe + 1;
            //count = 7,繼續循環
            count--;
        }
    }
    return nil;
}
複製代碼

假如count=8,要查找的方法在7號位置 二分查找邏輯以下:

  1. probe = base + (count >> 1),即probe = 0 + 4(8 >> 1) = 4
  2. 沒有找到,由於keyValue > probeValue,因此取值應該在58之間,base = probe + 1,即base = 4 +1 = 5
  3. count --,即8 --count = 7
  4. count >>= 1,即 7 >> 1 = 3 = count
  5. probe = base + (count >> 1),即probe = 5 + 1(3 >> 1) = 6
  6. 當前keyValue > probeValue任然成立,因此取值應該在68之間,base = probe + 1,即base = 5 +1 = 6
  7. count --,即3 --count = 2
  8. probe = base + (count >> 1),即probe = 6 + 1(2 >> 1) = 7
  9. keyValue = probeValue找到方法,若是分類裏有同名方法,返回分類的方法
相關文章
相關標籤/搜索