方法调用(二)-- 慢速查找流程

方法调用(一)-- objc_msgSend快速查找流程
方法调用(二)-- 慢速查找流程
方法调用(三)-- 动态方法决议&消息转发


上篇文章在objc_msgSend快速查找流程中,缓存中如果找不到方法,最终会调用_lookUpImpOrForward函数,开始进入慢速查找流程。本文从_lookUpImpOrForward为入口开始说明。

本文简要目录:

  1. 快速查找和慢速查找
  2. lookUpImpOrForward源码分析
  3. lookUpImpOrForward流程图
  4. 方法查找相关的一道有意思的面试题
  5. 动态方法决议小案例
  6. 扩展 - 二分查找方法分析

快速查找和慢速查找

  • 快速查找:使用汇编代码实现相关流程,汇编更加接近底层,所以执行起来快。而且这过程中实现的流程就是在缓存cache中查找,因此定义为快速查找
  • 慢速查找:这部分是C/C++实现的,是在类中去查找方法的imp。找到后缓存(调用cache_fill函数),为下次objc_msgSend快速查找阶段使用。

注意:汇编调用的函数会增加下划线_,所以找到对应C/C++的函数,需要去掉下划线。_lookUpImpOrForward函数在全局搜索结果都是在汇编中的调用,所以此处需要去掉下划线搜索lookUpImpOrForward函数,在objc-runtime-new.mm中,接下来我们来分析lookUpImpOrForward源码。

lookUpImpOrForward源码分析

通过函数名的大致的意思是‘查找imp或者进行转发’,我们来看看内部是怎么实现的。

IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
    //1.定义变量接受转发函数的imp,并定义了下面需要用到的变量imp和curClass
    const IMP forward_imp = (IMP)_objc_msgForward_impcache;
    IMP imp = nil;
    Class curClass;

    runtimeLock.assertUnlocked();

    // 2.再进行一次快速查找流程,防止多线程的情况下,动态添加方法的imp
    // 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
    // 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.

    runtimeLock.lock();

    // We don't want people to be able to craft a binary blob that looks like
    // a class but really isn't one and do a CFI attack.
    //
    // To make these harder we want to make sure this is a class that was
    // either built into the binary or legitimately registered through
    // objc_duplicateClass, objc_initializeClassPair or objc_allocateClassPair.
    //
    // TODO: this check is quite costly during process startup.
    
    // 3.确认类是有效的,并且类是已经在内存中存在
    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();
    
    // 4.对curClass进行初始化为传入的参数cls
    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().

    //5. 开始查找
    for (unsigned attempts = unreasonableClassCount();;) {
        // curClass method list.
        // 5.1 从当前的类中查找,找到了直接跳转到done
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp;
            goto done;
        }

        // 5.2 当前类中找不到就去父类中查找,将curClass指向父类。所有的父类中都找不到imp,superclass最终为nil时,给imp赋值成转发函数的imp
        if (slowpath((curClass = curClass->superclass) == 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.");
        }

        // 5.3 父类中进行查找,仅在父类中缓存查找
        // Superclass cache.
        imp = cache_getImp(curClass, sel);
        
        // 5.4 imp等于转发函数的imp时跳出循环
        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;
        }
        // 5.5 找到了imp,跳转到done
        if (fastpath(imp)) {
            // Found the method in a superclass. Cache it in this class.
            goto done;
        }
    }

    // No implementation found. Try method resolver once.

    // 6.系统提供的一次转发机会
    if (slowpath(behavior & LOOKUP_RESOLVER)) {
        behavior ^= LOOKUP_RESOLVER;
        return resolveMethod_locked(inst, sel, cls, behavior);
    }

 done:
    // 7.找到imp后进行缓存,为下次再次调用时,可在快速流程中找到
    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. 定义转发函数

//1.定义变量接受转发函数的imp,并定义了下面需要用到的变量imp和curClass
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
IMP imp = nil;
Class curClass;

_objc_msgForward_impcache函数前有下划线_,说明是在汇编中实现。全局搜索,查看在arm64中实现方式。

STATIC_ENTRY __objc_msgForward_impcache
// No stret specialization.
b   __objc_msgForward
END_ENTRY __objc_msgForward_impcache

⏬⏬⏬

ENTRY __objc_msgForward
adrp    x17, __objc_forward_handler@PAGE
ldr p17, [x17, __objc_forward_handler@PAGEOFF]
TailCallFunctionPointer x17
END_ENTRY __objc_msgForward

⏬⏬⏬

__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);
}
void *_objc_forward_handler = (void*)objc_defaultForwardHandler;
  • __objc_msgForward_impcache中调用__objc_msgForward
  • __objc_msgForward中调用的是__objc_forward_handler
  • __objc_forward_handler的实现在C/C++层,所以搜索时去掉一个下划线为_objc_forward_handler
  • _objc_forward_handler就是进行了一个log打印

此处举个例子:

@interface DZPerson : NSObject
- (void)sayBaibai;
@end

@implementation DZPerson
@end

//调用
DZPerson *person = [DZPerson alloc];
[person sayBaibai];
  • 定义一个DZPerson类,声明sayBaibai方法,但是没有实现。
  • 调用sayBaibai方法,运行时报错,因为找不到对应的imp。这个报错信息输出,就是_objc_forward_handler函数中实现的。

2. 再一次快速查找

// 2.再进行一次快速查找流程,防止多线程的情况下,动态添加方法的imp
// Optimistic cache lookup
if (fastpath(behavior & LOOKUP_CACHE)) {
    imp = cache_getImp(cls, sel);
    if (imp) goto done_nolock;
}

⏬⏬⏬

    STATIC_ENTRY _cache_getImp

    GetClassFromIsa_p16 p0
    CacheLookup GETIMP, _cache_getImp

LGetImpMiss:
    mov p0, #0
    ret

    END_ENTRY _cache_getImp
  • 再一次进行快速查找流程,目的是防止多线程情况下进行动态添加imp,第一次快速查找时还没有添加,而此时进入慢速查找流程时已经进行了添加。所以再进行一次快速查找
  • cache_getImp对应的汇编代码添加添加一个下划线即可以在汇编中找到实现
  • 最终调用CacheLookup,具体可以参考上篇文章中:方法(一)-- objc_msgSend快速查找流程,但是传入的参数是GETIMP,参数的意思是只进行缓存查找,不进行类中方法查找。

3. & 4. 确认类信息

// 3.确认类是有效的,并且类是已经在内存中存在
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();
    
// 4.对curClass进行初始化为传入的参数cls
curClass = cls;
  • 类有效性的相关判断,主要是确认类是否有效以及继承关系和元类相关信息。
  • 后面的方法查找,会先从当前类开始查找,找不到的情况会去父类中查找,所以需要确认类的继承关系链
  • 此处不是本文的重点,先略过具体实现,以后会在其他文章中进行学习。

5.开始查找

//5. 开始查找
for (unsigned attempts = unreasonableClassCount();;) {
    // curClass method list.
    // 5.1 从当前的类中查找,找到了直接跳转到done
    Method meth = getMethodNoSuper_nolock(curClass, sel);
    if (meth) {
        imp = meth->imp;
        goto done;
    }

    // 5.2 当前类中找不到就去父类中查找,将curClass指向父类。所有的父类中都找不到imp,superclass最终为nil时,给imp赋值成转发函数的imp
    if (slowpath((curClass = curClass->superclass) == 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.");
    }

    // 5.3 父类中进行查找,仅在父类中缓存查找
    // Superclass cache.
    imp = cache_getImp(curClass, sel);
    
    // 5.4 imp等于转发函数的imp时跳出循环
    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;
    }
    // 5.5 找到了imp,跳转到done
    if (fastpath(imp)) {
        // Found the method in a superclass. Cache it in this class.
        goto done;
    }
}
  • 进入for循环开始查找,但是需要注意for循环的代码for (unsigned attempts = unreasonableClassCount();;),只有初始条件,没有判断条件,也就是说条件总是满足,这个for循环是个无限循环。
5.1 从当前类中查找

调用函数getMethodNoSuper_nolock,从当前类中查找imp

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)
    {
        //  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->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;
        }
    }

#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;
}

⏬⏬⏬

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;
    
    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;
}
  • getMethodNoSuper_nolock中调用search_method_list_inline,然后调用到findMethodInSortedMethodList
  • 通过函数名了解到,对方法列表中的方法进行了排序,排序的目的是用‘二分查找法’,进行查找。
  • findMethodInSortedMethodList中的二分查找用的是右移操作>>进行的
5.2 & 5.3 & 5.4 父类中进行快速查找

当前类中没有找到,进行父类查找,所以需要先将curClass变量转换为父类

// 5.2 当前类中找不到就去父类的缓存中查找,将curClass指向父类。所有的父类中都找不到imp,superclass最终为nil时,给imp赋值成转发函数的imp
if (slowpath((curClass = curClass->superclass) == 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.");
}

// 5.3 父类中进行查找,仅在父类中缓存查找
// Superclass cache.
imp = cache_getImp(curClass, sel);

// 5.4 imp等于转发函数的imp时跳出循环
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;
}
// 5.5 找到了imp,跳转到done
if (fastpath(imp)) {
    // Found the method in a superclass. Cache it in this class.
    goto done;
}
  • 此处将curClass赋值成父类
  • curClass == nil,也就是所有的父类中都没有时,将imp变量赋值为forward_imp,也就是方法转发的imp
  • cache_getImp,前面介绍过,就是进入父类的快速查找流程。但是仅仅是查找父类缓存。
  • 如果父类的缓存中找不到,继续进行for循环,curClass指向父类,所以当前的循环是父类中方法列表查找,还找不到就在“父类的父类”方法列表中查找。
  • 每次for循环可以理解为:当前类中方法列表查找->curClass指向父类->父类缓存列表查找,流程图如下:

6.系统提供的一次转发机会

// 6.系统提供的一次转发机会
if (slowpath(behavior & LOOKUP_RESOLVER)) {
    behavior ^= LOOKUP_RESOLVER;
    return resolveMethod_locked(inst, sel, cls, behavior);
}
  • LOOKUP_RESOLVER是一个枚举,值为2
  • behavior & LOOKUP_RESOLVER判断,进入判断后,将behavior中的LOOKUP_RESOLVER位取反,目的是这段代码只执行一遍。

7.找到了imp,进行一次缓存

done:
    // 7.找到imp后进行缓存,为下次再次调用时,可在快速流程中找到
    log_and_fill_cache(cls, imp, sel, inst, curClass);
    runtimeLock.unlock();
    
⏬⏬⏬    

static void
log_and_fill_cache(Class cls, IMP imp, SEL sel, id receiver, Class implementer)
{
#if SUPPORT_MESSAGE_LOGGING
    if (slowpath(objcMsgLogEnabled && implementer)) {
        bool cacheIt = logMessageSend(implementer->isMetaClass(), 
                                      cls->nameForLogging(),
                                      implementer->nameForLogging(), 
                                      sel);
        if (!cacheIt) return;
    }
#endif
    //
    cache_fill(cls, sel, imp, receiver);
}
  • log_and_fill_cache中调用的cache_fill,找到imp后进行缓存,目的是再次调用方法时,可以在快速查找流程中可以直接找到

lookUpImpOrForward流程图

方法查找相关的一道有意思的面试题

@interface DZPerson : NSObject
@end

@implementation DZPerson
@end

//调用
[DZPerson performSelector:@selector(hello)];
  • 定义一个DZPerson类,继承自NSObject,类中没有定义任何方法。
  • 调用DZPerson的类方法hello,正常运行会闪退,因为找不到imp。

添加NSObject分类DZ,并在里面定义了一个对象方法hello

@interface NSObject (DZ)
- (void)hello;
@end

@implementation NSObject (DZ)
- (void)hello {
    NSLog(@"%s", __func__);
}
@end

问:运行时是否报错?(注意调用的地方是类方法(+方法),分类中写的是对象方法(-方法))

解答:

  • 不报错,可以正常运行。
  • 调用的地方是类方法,查找方法的路径就是从DZPerson元类中查找,找不到就会在元类的继承链中查找。根元类中也找不到,就去根元类的父类,也就是NSObject中查找,而NSObjectDZ分类中有,因此可以直接调用分类中的对象方法。

参考isa走位图


动态方法决议小案例

@interface DZPerson : NSObject
- (void)say666;
@end

@implementation DZPerson

void test() {
    NSLog(@"调用%s函数", __func__);
}

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(say666)) {
        return class_addMethod(self, sel, (IMP)test, "v:");
    }
    
    return [super resolveClassMethod:sel];
}

@end

//调用
DZPerson *per = [DZPerson alloc];
[per say666];
  • 定义DZPerson类,声明say666方法,但是没有实现。
  • 实现动态方法决议resolveInstanceMethod,在类中添加方法。
  • 当调用say666方法时,最终会找到test函数的实现

运行结果:


扩展 - 二分查找方法分析

先上源码

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;
    
    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;
}

举个例子:

  • 一共有8个方法,所以count=8
  • 我们要找到方法4

开始进入for循环:

  • count初始值是8
  • count >> 1,8右移1位,8二进制是1000,右移后是0100,等于4。probe = base + (count >> 1),也就是probe指向“方法5”的位置。
  • 不是目标方法,目标方法的位置小于probe指定的位置,循环继续。
  • for循环中的第三部分,count >> 1,count=4
  • probe = base + (count >> 1)probe等于首位置+2,也就是指向“方法3”
  • 与目标方法不相等
  • probe的位置小于目标位置,调整base= probe+1,count--变成7
  • for循环第三部分count >>= 1,7二进制0111,右移1位,变成0011,等于3
  • probe = base + (count >> 1) = base + 1,probe指向“方法5”
  • 继续for循环,第三条件count >>= 1 = 3>>=1 等于1
  • probe = base + (count >> 1) = base + 0,probe指向“方法4”
  • 这一步就找到了目标方法
  • 找到后的代码还有一个while循环,此步是找category的同名方法。因为同名方法会在原方法之前,所以向前查找。

你可能感兴趣的:(方法调用(二)-- 慢速查找流程)