objc_msgSend 流程分析(慢速查找)

在上一篇 objc_msgSend 流程分析(快速查找) 中解析了消息的快速查找流程,那有快速肯定就有慢速查找,今天我们就来分析下消息的慢速查找流程

objc_msgSend 慢速查找流程

在快速查找流程中,如果没有找到方法实现,会走到 CheckMiss 还是 JumpMiss,因为带的参数为 NORMAL, 最终会走到 __objc_msgSend_uncached 汇编里面

__objc_msgSend_uncached 汇编源码如下

STATIC_ENTRY __objc_msgSend_uncached
UNWIND __objc_msgSend_uncached, FrameWithNoSaves

// THIS IS NOT A CALLABLE C FUNCTION
// Out-of-band p16 is the class to search
    
MethodTableLookup //查询方法列表
TailCallFunctionPointer x17

END_ENTRY __objc_msgSend_uncached

搜索 MethodTableLookup 的汇编实现,在 objc-msg-arm64.s 下,其源码的核心是 _lookUpImpOrForward

.macro MethodTableLookup
    
    // push frame
    SignLR
    stp fp, lr, [sp, #-16]!
    mov fp, sp

    // save parameter registers: x0..x8, q0..q7
    sub sp, sp, #(10*8 + 8*16)
    stp q0, q1, [sp, #(0*16)]
    stp q2, q3, [sp, #(2*16)]
    stp q4, q5, [sp, #(4*16)]
    stp q6, q7, [sp, #(6*16)]
    stp x0, x1, [sp, #(8*16+0*8)]
    stp x2, x3, [sp, #(8*16+2*8)]
    stp x4, x5, [sp, #(8*16+4*8)]
    stp x6, x7, [sp, #(8*16+6*8)]
    str x8,     [sp, #(8*16+8*8)]

    // 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
    mov x17, x0
    
    // restore registers and return
    ldp q0, q1, [sp, #(0*16)]
    ldp q2, q3, [sp, #(2*16)]
    ldp q4, q5, [sp, #(4*16)]
    ldp q6, q7, [sp, #(6*16)]
    ldp x0, x1, [sp, #(8*16+0*8)]
    ldp x2, x3, [sp, #(8*16+2*8)]
    ldp x4, x5, [sp, #(8*16+4*8)]
    ldp x6, x7, [sp, #(8*16+6*8)]
    ldr x8,     [sp, #(8*16+8*8)]

    mov sp, fp
    ldp fp, lr, [sp], #16
    AuthenticateLR

.endmacro

验证

创建一个新工程,创建 LCPerson 类,声明一个实例方法,在main 函数中添加断点

运行项目,会走到断点处,此时打开汇编调试:Debug -> Debug worlflow -> Always show Disassembly,会出现如下界面

objc_msgSend 加一个断点,执行下一步,会断在 objc_msgSend 处,按住 control 点击 stepinto 键,进入 objc_msgSend 的汇编

_objc_msgSend_uncached 汇编处加一个断点,执行下一步,会断在 _objc_msgSend_uncached 处,按住 control,点击 stepinto 键,进入 _objc_msgSend_uncached 汇编

此时,可以看到,汇编最后走的就是 lookUpImpOrForward

慢速查找

  • 根据上面汇编调试,在 objc-781 源码中查找 lookUpImpOrForward 的实现,方法是在 objc-runtime-new.mm 文件中,是一个 C 函数的实现
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();

    // 快速查找,如果找到则直接返回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.
    //
    //判断是否是一个已知的类:判断当前类是否是已经被认可的类,即已经加载的类
    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.
        //当前类方法列表(采用二分查找算法),如果找到,则返回,将方法缓存到cache中
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp;
            goto done;
        }

        //当前类 = 当前类的父类,并判断父类是否为nil
        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.");
        }

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

lookupImpOrForward 主要就是查找方法并返回 imp

  • 从缓存中查找方法
  • checkIsKnownClass 判断当前类是否是系统的类或者是自定创建的类,只有是系统已知的才能执行查找
  • realizeClassMaybeSwiftAndLeaveLocked 类是否实现,获得当前对象继承关系,方便从父类查找
  • initializeAndLeaveLocked 是否初始化,主要是系统方法的自动调用,比如initalize
  • for 循环,按照类继承链或者元类继承链的顺序查找
    • 从当前类查找方法
    • 从父类查找方法,并将父类赋值给curClass
    • 如果父类链中存在循环,则报错,终止循环
    • 从父类缓存中查找方法:找不到继续循环查找;找到,直接走 done
  • 判断是否执行过动态方法解析
    • 没有,执行动态方法解析
    • 执行过一次动态方法解析,则走到消息转发流程
getMethodNoSuper_nolock 方法解析
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 的源码实现

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

findMethodInSortedMethodList 的源码实现

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

方法列表是有序的,所以使用二分查找,更快速。在源码中两点需要注意

  • count >> 1,就是右移一位,变成原来的一半。例如 00010001(17) 右移一位就变成了 00001000(8)
  • while (probe > first && keyValue == (uintptr_t)probe[-1].name) { probe--; } 是因为分类方法中可能出现同名方法

总结

    1. 从缓存中查找,如果有返回 imp
    1. 从方法列表中查找(使用二分查找),如果有,存储到缓存,返回 imp,如果没有,若父类中存在,从父类中查找,否则走动态决议
      1. 将父类赋值给当前类,重复上述动作,直到父类不存在
      1. 找到 imp 则存入缓存中

流程图

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