objc_msgSend慢速查找流程

消息查找流程

消息查找流程分为快速慢速快速查找是通过objc_msgSend缓存中进行查找,如果存在直接返回,如果不存在则会进入objc_msgSend_uncached开始慢速查找

慢速查找流程

1.首先声明实例方法,但不进行实现,通过调用查看查找流程

@interface LGPerson : NSObject
- (void)say666;
@end
@implementation LGPerson
@end
截屏2020-09-22 上午10.57.17.png
  • 通过Debug->Debug Workflow -> Always Show Disassembly 改为汇编调试
    截屏2020-09-22 上午10.58.09.png
  • 可以看出在main函数中调用了声明的实例方法,然后通过objc_msgSend进行查找

2.通过control + step into 查看下一步流程

截屏2020-09-22 上午10.58.23.png

截屏2020-09-22 上午10.58.45.png
  • 通过流程调用,我们发现没有对应的cache,因此进入objc_msgSend_uncached中进行查看
    截屏2020-09-22 上午10.59.09.png

    截屏2020-09-22 上午10.59.21.png
  • 通过上面流程,我们发现汇编底层在发现没有对应的cache后,就会去调用lookUpImpOrForword函数,而此时在objc-runtime-new.mm中存在,此时我们就可以关闭汇编调试进去对应的文件中查看
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();

    // Optimistic cache lookup
    if (fastpath(behavior & LOOKUP_CACHE)) {
        imp = cache_getImp(cls, sel);
        if (imp) goto done_nolock;
    }

    // runtimeLock is held during isRealized and isInitialized checking 在isRealized和isInitialized检查期间保持runtimeLock
    // 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.
    
    // 防止多线程访问两个方法出现返回imp错误

    runtimeLock.lock();
    // 非法类的检查
    checkIsKnownClass(cls);

    if (slowpath(!cls->isRealized())) {
        // 准备条件,如果当前这个类没有被加载,需要对当前类进行初始化以及属性和方法的加载
        cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
        // runtimeLock may have been dropped but is now locked again
    }

    if (slowpath((behavior & LOOKUP_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
    }

    runtimeLock.assertLocked();
    curClass = cls;
    // The code used to lookpu the class's cache again right after 类初始化后再对缓存进行一次查找
    // we take the lock but for the vast majority of the cases
    // evidence shows this is a miss most of the time, hence a time loss.
    //
    // The only codepath calling into this without having performed some
    // kind of cache lookup is class_getInstanceMethod().

    for (unsigned attempts = unreasonableClassCount();;) {
        // curClass method list.
        // 在当前类中找方法,通过二分查找节省时间
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp;
            goto done;
        }
        if (slowpath((curClass = curClass->superclass) == nil)) {
            // No implementation found, and method resolver didn't help.
            // Use forwarding.
            //如果根类中也没有方法,则返回指定的forward_imp
            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:
    // 找到了进行缓存一份
    log_and_fill_cache(cls, imp, sel, inst, curClass);
    runtimeLock.unlock();
 done_nolock:
    if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
        return nil;
    }
    return imp;
}

通过上面的代码我们发现:

1.  方法查找首先会在`当前类`中进行查找
2.  如果没有就会向`父类`及`根类`中查找(`二分法查找`)
3.  如果都没有则会进行`动态方法决议` `resolveMethod_locked`
4.  如果都没有,则会返回`forward_imp`->`_objc_msgForward_impcache`
  • 注: 由于在lookUpImpOrForward中的for循环只会是一个死循环,通过slowpath(--attempts == 0)给定一个出口,防止一直循环下去,通过slowpath((curClass = curClass->superclass)去查找父类以及根类,如果没有才会走resolveMethod_locked.

3.二分法查找分析

static method_t *
getMethodNoSuper_nolock(Class cls, SEL sel)
{
    runtimeLock.assertLocked();

    ASSERT(cls->isRealized());

    auto const methods = cls->data()->methods();
    for (auto mlists = methods.beginLists(),
              end = methods.endLists();
         mlists != end;
         ++mlists)
    {
            method_t *m = search_method_list_inline(*mlists, sel);
        if (m) return m;
    }

    return nil;
}
  • 通过上面代码我们可以找出重点是通过search_method_list_inline进行方法查找,如果有则返回方法,没有则返回nil
ALWAYS_INLINE static method_t *
search_method_list_inline(const method_list_t *mlist, SEL sel)
{
    int methodListIsFixedUp = mlist->isFixedUp();
    int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t);
    // 如果方法列表是有序的,则使用二分法查找方法,节省时间
    if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
        return findMethodInSortedMethodList(sel, mlist);
    } else {
        // 否则则遍历列表查找
        // Linear search of unsorted method list
        for (auto& meth : *mlist) {
            if (meth.name == sel) return &meth;
        }
    }
  • 通过上面代码我们可以得出:
    • 如果对应的方法列表是有序列表,则会通过二分法去查找,
    • 如果对应的方法是无序的,则只能通过遍历去进行对比查找
ALWAYS_INLINE 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;
    // count >>= 1 如果count为偶数则值变为(count / 2)。如果count为奇数则值变为(count-1) / 2
    for (count = list->count; count != 0; count >>= 1) {
        // >>1 表示将变量n的各个二进制位顺序右移1位,最高位补二进制0。 1000->0100 即 8->4->2->1
        // probe 指向数组中间的值
        probe = base + (count >> 1);
        // 取出中间method_t的name,也就是SEL
        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;
        }
        // 如果keyValue > probeValue 则折半向后查询
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}
  • 注:上述方法中查找到对应的方法后,又进行了一次probe--,这是因为存在方法重名的问题,我们会在后面的文章中进行陈述

动态方法决议

static NEVER_INLINE IMP
resolveMethod_locked(id inst, SEL sel, Class cls, int behavior)
{
    runtimeLock.assertLocked();
    ASSERT(cls->isRealized());
    runtimeLock.unlock();

    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]
        resolveInstanceMethod(inst, sel, cls);
    } 
    else {
        // try [nonMetaClass resolveClassMethod:sel]
        // and [cls resolveInstanceMethod:sel]
        resolveClassMethod(inst, sel, cls);
        if (!lookUpImpOrNil(inst, sel, cls)) {
            resolveInstanceMethod(inst, sel, cls);
        }
    }

    // chances are that calling the resolver have populated the cache
    // so attempt using it
    return lookUpImpOrForward(inst, sel, cls, behavior | LOOKUP_CACHE);
}
  • 通过上述代码我们发现主要会调用resolveInstanceMethodresolveClassMethod方法,因此可以通过重写此方法进行拦截处理
void sayHello(){
    NSLog(@"hello");
}

@implementation NSObject (DDResove)

+ (BOOL)resolveInstanceMethod:(SEL)sel{
    if (sel == @selector(say666)) {
        NSLog(@"------ coming");
        class_addMethod([self class],sel, (IMP)sayHello,"v@:@");

    }
    return YES;
}
2020-09-22 14:25:04.532576+0800 KCObjc[90797:16208600] ------ coming
2020-09-22 14:25:04.533134+0800 KCObjc[90797:16208600] hello
@end
  • 通过为NSObject增加分类,在分类中重写resolveInstanceMethod方法,我们发现就会进入此方法,并且调用其他的方法来避免崩溃

__objc_msgForward_impcache实现

我们在objc-msg-arm64.s汇编文件中发现在调用__objc_msgForward_impcache时会通过objc_msgForword转换成__objc_forward_handler,因此通过文件中查找objc_forward_handler方法

__attribute__((noreturn, cold)) void
objc_defaultForwardHandler(id self, SEL sel)
{
    _objc_fatal("%c[%s %s]: unrecognized selector sent to instance %p "
                "(no message forward handler is installed)", 
                class_isMetaClass(object_getClass(self)) ? '+' : '-', 
                object_getClassName(self), sel_getName(sel), self);
}
  • 通过打印的信息+-是打印信息中添加的,因此可以验证底层方法中并不存在类方法实例方法的区分。

你可能感兴趣的:(objc_msgSend慢速查找流程)