方法查找流程-慢速查找

在消息查找流程-快速查找流程,中分析到,如果在cache中没有找到,则会进入__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方法表查找

MethodTableLookup汇编实现

.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

从注释我们可以看出,前半段的汇编是在准备x0,x1。即消息接收者(receiver),与方法标识(selector)。然后调用了lookUpImpOrForward方法。在汇编下搜索,并没有找到_lookUpImpOrForward的汇编实现。所以去掉一个下划线,全局搜索lookUpImpOrForward就是方法慢速查找流程。

代码验证

  • step1
    在方法调用行加上断点,然后运行,来到断点


    方法查找流程验证step1.png
  • step2
    进到断点后,打开Debug→Debug WorkFlow→Always Show Disassembly
    打开Always Show Disassembly.png
  • step3
    objc_msgSend打上断点,然后执行到这个断点,然后使用control+step into,进入objc_msgSend的之后的流程
    方法调用之前的流程.png
  • step4
    _objc_msgSend_uncached打上断点后继续执行,然后control+step into,进入_objc_msgSend_uncached的流程
    objc_msgSend流程.png
  • step5
    lookUpImpOrForward打上断点,继续执行,得以验证慢速查找_objc_msgSend_uncached流程会执行到lookUpImpOrForward
    _objc_msgSend_uncached流程.png

lookUpImpOrForward

lookUpImpOrForward 底层源码

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

图解慢速查找流程


objc4-818慢速查找流程图.png
  1. 创建forward_impimp
    • forward_imp: const IMP forward_imp = (IMP)_objc_msgForward_impcache
    • impIMP imp = nil;
  2. 当前类是否已初始化
    • 如果没有:behavior |= LOOKUP_NOCACHE
  3. 读取加锁runtimeLock.lock()
  4. 判断当前类是否为已知类
    • 如果不是,则报错Attempt to use unknown class xxx
  5. 检查并完善类的初始化以及实现。
  6. 进入循环继承链循环查找流程
    • 如果当前类的缓存是不断优化的缓存,则从缓存中快速查找一次
      • 如果找到了,goto done_unlock: 解锁,并判断imp是否为forward_imp,如果是forward_imp,则返回nil,如果不是则返回imp
      • 如果没有找到,则curClass = curClass->cache.preoptFallbackClass(),继续执行6
    • 如果当前类的缓存不是不断优化的缓存
      • 开始在当前类的方法列表中采用二分查找
        • 如果找到了,则goto done,将方法存入缓存当前类的缓存
        • 如果没有找到
          • 则把当前类换成其父类
            • 如果其父类为nil,则imp = forward_imp,退出循环
            • 如果不是,则从父类的缓存中查找
              • 如果找到的imp = forward_imp,退出循环
              • 如果找到了,则goto done,将方法存入缓存到原本查找的类的缓存中
              • 如果没有找到,则开始慢速查找,回到第6步,直到找到父类为nil,或者imp = forward_imp,退出循环
  7. 对于 behavior & LOOKUP_RESOLVER = 0,则给其一次机会,进入动态方法决议
  8. 返回imp

总结

  • 对于对象方法(即实例方法),即在类中查找,其慢速查找的父类链是:类--父类--根类--nil
  • 对于类方法,即在元类中查找,其慢速查找的父类链是:元类--根元类--根类--nil
  • 如果快速查找、慢速查找也没有找到方法实现,则尝试动态方法决议
  • 如果动态方法决议仍然没有找到,则进行消息转发

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