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找到方法,若是分类里有同名方法,返回分类的方法
相关文章
相关标签/搜索