方法查找下(快速查找)

引言

前面从汇编的角度分析了objc_msgSend来查找方法的过程,当找不到的时候调用lookUpImpOrForward方法,objc_msgSend是用汇编写的,为什么第一步的缓存查找要用汇编来写呢?后面来查找methodlist的方法又回到了c++代码呢,汇编速度比较快,传入参数的时候,可以动态传入参数,增加了动态性。如果说cache中的查找是快速查找,那么lookUpImpOrForward就是慢速查找。哪里存在methodlist呢,从之前的结构上看cls->data()->methods()中有methods,类存在着继承关系,如果查找的话,会先查找自己的方法列表,然后查找父类的,依次父类查找,对于父类也是先快速查找,然后慢速查找,是一个递归的过程。

源码解析

我们来看lookUpImpOrForward

IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
    const IMP forward_imp = (IMP)_objc_msgForward_impcache;
    IMP imp = nil;
    Class curClass;
    if (slowpath(!cls->isInitialized())) {
        behavior |= LOOKUP_NOCACHE;
     }
     runtimeLock.lock();
     //关于类一些是注册的操作
     checkIsKnownClass(cls);
     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;
            }

            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_imp)) {
            // 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.

    if (slowpath(behavior & LOOKUP_RESOLVER)) {
        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;
    
  }
复制代码

我们分析一下 cls = realizeAndInitializeIfNeeded_locked(inst, cls, behavior & LOOKUP_INITIALIZE);这个方法

realizeAndInitializeIfNeeded_locked(id inst, Class cls, bool initialize)
{
    runtimeLock.assertLocked();
    if (slowpath(!cls->isRealized())) {
        cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
        // runtimeLock may have been dropped but is now locked again
    }

    if (slowpath(initialize && !cls->isInitialized())) {
        cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
        // runtimeLock may have been dropped but is now locked again

        // 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
    }
    return cls;
}
复制代码

如果没有实现,则走 cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
realizeClassMaybeSwiftAndLeaveLocked方法中

realizeClassMaybeSwiftMaybeRelock(Class cls, mutex_t& lock, bool leaveLocked)
{
    lock.assertLocked();

    if (!cls->isSwiftStable_ButAllowLegacyForNow()) {
        // Non-Swift class. Realize it now with the lock still held.
        // fixme wrong in the future for objc subclasses of swift classes
        realizeClassWithoutSwift(cls, nil);
        if (!leaveLocked) lock.unlock();
    } else {
        // Swift class. We need to drop locks and call the Swift
        // runtime to initialize it.
        lock.unlock();
        cls = realizeSwiftClass(cls);
        ASSERT(cls->isRealized());    // callback must have provoked realization
        if (leaveLocked) lock.lock();
    }

    return cls;
}
复制代码

我们看Non-Swift classrealizeClassWithoutSwift方法

static Class realizeClassWithoutSwift(Class cls, Class previously)
{
    runtimeLock.assertLocked();

    class_rw_t *rw;
    Class supercls;
    Class metacls;

    if (!cls) return nil;
    if (cls->isRealized()) {
        validateAlreadyRealizedClass(cls);
        return cls;
    }
    ASSERT(cls == remapClass(cls));

    // fixme verify class is not in an un-dlopened part of the shared cache?

    auto ro = (const class_ro_t *)cls->data();
    auto isMeta = ro->flags & RO_META;
    if (ro->flags & RO_FUTURE) {
        // This was a future class. rw data is already allocated.
        rw = cls->data();
        ro = cls->data()->ro();
        ASSERT(!isMeta);
        cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
    } else {
        // Normal class. Allocate writeable class data.
        rw = objc::zalloc<class_rw_t>();
        rw->set_ro(ro);
        rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
        cls->setData(rw);
    }

    cls->cache.initializeToEmptyOrPreoptimizedInDisguise();

#if FAST_CACHE_META
    if (isMeta) cls->cache.setBit(FAST_CACHE_META);
#endif

    // Choose an index for this class.
    // Sets cls->instancesRequireRawIsa if indexes no more indexes are available
    cls->chooseClassArrayIndex();

    if (PrintConnecting) {
        _objc_inform("CLASS: realizing class '%s'%s %p %p #%u %s%s",
                     cls->nameForLogging(), isMeta ? " (meta)" : "", 
                     (void*)cls, ro, cls->classArrayIndex(),
                     cls->isSwiftStable() ? "(swift)" : "",
                     cls->isSwiftLegacy() ? "(pre-stable swift)" : "");
    }

  
    supercls = realizeClassWithoutSwift(remapClass(cls->getSuperclass()), nil);
    metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);

    .....

    return cls;
}
复制代码

可以看到这个方法中做了协议rw,的赋值操作,而且在里面调用了 supercls = realizeClassWithoutSwift(remapClass(cls->getSuperclass()), nil); metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);就把之前介绍的那个isa以及superClass的图整个给初始化掉了。
我们回到lookUpImpOrForward方法中,看到for (unsigned attempts = unreasonableClassCount();;)这是一个死循环,退出条件和改变条件为空,那么怎么才能跳出这个循环呢,只有在里面有return或者break或者goto这些字段。我们来详细看下里面的内容。
由前面分析知道,如果类没有实现,则会进行一步初始化操作,所以为了正确性,先进行了一步共享缓存的查找。

  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部分
这个是获取方法的具体方法。
Method meth = getMethodNoSuper_nolock(curClass, sel);
点进去看一下,最后定位到查找方法的具体函数实现

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;
    //5 probe=2
    for (count = list->count; count != 0; count >>= 1) {
        probe = base + (count >> 1);
        
        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--;
            }
            return &*probe;
        }
        
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}
复制代码

这是一个二分查找。
比如刚开始
count=8,1000,
第一轮:probe = base + (count >> 1);//count >> 1 = 4, 即probe 4
如果值大于4时候的值
则 base = 5, count = 7, count >>=1 则count = 3(0111 => 0011)
第二轮:probe = base + (count >> 1); //count>>1 = 1, 即probe = 6
则比较6时候的值,直到找到或者找不到结束
如果值小于4时候的值
count>>=1 = 4
第二轮:probe = base + (count >> 1);//4>>1, 则probe = 2

如果找到则走 goto done; 把方法插入到cache中, log_and_fill_cache(cls, imp, sel, inst, curClass);则会进入到我们前面讲到的缓存插入流程 cls->cache.insert(sel, imp, receiver);

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);
    }
复制代码

如果没有找到并且父类不为nil,则走 imp = cache_getImp(curClass, sel);

extern "C" IMP cache_getImp(Class cls, SEL sel, IMP value_on_constant_cache_miss = nil);
复制代码

进行父类的快速查找,

STATIC_ENTRY _cache_getImp
GetClassFromIsa_p16 p0, 0
CacheLookup GETIMP, _cache_getImp, LGetImpMissDynamic, LGetImpMissConstant
复制代码

然后父类的慢速查找,依次递归查找父类直到nil。
如果都没有找到则 imp = forward_imp; 将forward_imp赋值为imp

 if (slowpath((curClass = curClass->getSuperclass()) == nil)) {
                // No implementation found, and method resolver didn't help.
                // Use forwarding.
                imp = forward_imp;
                break;
            }
复制代码

总结

先在缓存中进行快速查找,没有找到,则在本类的方法列表中进行查找,
如果没有找到,则逐级父类中进行查找,父类也是先进行快速查找,后进行慢速查找,是一个递归的过程。
如果在方法列表中找到,写入缓存。
如果都没有找到,则将imp=forward_imp,进行消息转发。
对于已排序的方法列表采用二分查找

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享