iOS-OC底层08:objc_msgSend慢速查找

前沿

在objc_msgSend缓存中读取IMP中,
如果缓存没有找到会有下面方法

.macro CheckMiss
    // miss if bucket->sel == 0
.if $0 == GETIMP
    cbz p9, LGetImpMiss
.elseif $0 == NORMAL
    cbz p9, __objc_msgSend_uncached
.elseif $0 == LOOKUP
    cbz p9, __objc_msgLookup_uncached
.else
.abort oops
.endif
.endmacro

.macro JumpMiss
.if $0 == GETIMP
    b   LGetImpMiss
.elseif $0 == NORMAL
    b   __objc_msgSend_uncached
.elseif $0 == LOOKUP
    b   __objc_msgLookup_uncached
.else
.abort oops
.endif
.endmacro

流程图如下


iOS-OC底层08:objc_msgSend慢速查找_第1张图片
cachemiss.png

今天我们着重分析_lookUpImpOrForward

_lookUpImpOrForward

我们先用一个流程图来大致了解一下_lookUpImpOrForward的流程


iOS-OC底层08:objc_msgSend慢速查找_第2张图片
慢速查找.png

我们先了解一下源码

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();
//如果是从快速查找中进来的不会走cache_getImp方法
    // 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;
}

cache_getImp

从缓存中查找本类方法

STATIC_ENTRY _cache_getImp

    GetClassFromIsa_p16 p0
    CacheLookup GETIMP, _cache_getImp

LGetImpMiss:
    mov p0, #0
    ret

    END_ENTRY _cache_getImp

从汇编中看出,如果lookUpImpOrForward是从objc_msgsend流程的快速查找方法
进来的话第一个cache_getImp方法不会走,因为behavior的参数
CacheLookup后面参数为GETIMP,如果缓存中找不到接下来可能会走CheckMiss或者JumpMiss中的一个由于参数为GETIMP所以走LGetImpMiss,返回空,

是否已经实现realizeClassMaybeSwiftAndLeaveLocked如果没有实现下面步骤

iOS-OC底层08:objc_msgSend慢速查找_第3张图片
ClassIsRealized.png

realizeClassWithoutSwift中主要是给class赋值,把类中的元素添加进去。

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

这两个方法实现递归,把所有的父类和元类的父类都递归完

isInitialized方法

iOS-OC底层08:objc_msgSend慢速查找_第4张图片
IsInitialized.png

类的方法列表中查询对应的方法

getMethodNoSuper_nolock中for循环


iOS-OC底层08:objc_msgSend慢速查找_第5张图片
大循环.png

getMethodNoSuper_nolock中for循环又一个方法search_method_list_inline是采用二分法实现方法的寻找


iOS-OC底层08:objc_msgSend慢速查找_第6张图片
MethodSearch.png

** lookUpImpOrForward只是负责寻找IMP,那什么时候完成IMP函数的调用呢 **

什么时候完成函数IMP的调用

1.在快速查找中找到IMP

//objc_msgsend调用CacheLookup
CacheLookup NORMAL, _objc_msgSend
//CacheLookup命中CacheHit NORMAL
//在CacheHit中调用TailCallCachedImp x17, x12, x1, x16方法
.macro TailCallCachedImp
    // $0 = cached imp, $1 = address of cached imp, $2 = SEL, $3 = isa
    eor $1, $1, $2  // mix SEL into ptrauth modifier
    eor $1, $1, $3  // mix isa into ptrauth modifier
    brab    $0, $1
.endmacro

brab调到我们找到的IMP,并执行
2.在慢速查找中找到

//如果在CacheLookup中没有在缓存中找到则会调用__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会调用到c++完成IMP的查找
    MethodTableLookup
    TailCallFunctionPointer x17

    END_ENTRY __objc_msgSend_uncached

TailCallFunctionPointer的实现就是调到我们查找到的IMP去执行

面试题

我们创建一个类MYTeacher,另外在NSObject的Category中添加一个方法-(void)myNSObjectMethod;并实现

-(void)myNSObjectMethod {
    NSLog(@"--%s",__func__);
}
调用
        [MYTeacher performSelector:@selector(myNSObjectMethod)];

问会报错吗?
答案是能正常运行并打印[NSObject(MYCategory) myNSObjectMethod]
因为我们调用MYTeacher的类的方法系统会查询元类和沿着元类的继承树的实例方法,最后查询到NSObject, myNSObjectMethod是NSObject的实例。
再试想如果myNSObjectMethod是NSObject的类方法能不能正常呢?答案是能正常运行isa流程图送上


iOS-OC底层08:objc_msgSend慢速查找_第7张图片
isa流程图.png

你可能感兴趣的:(iOS-OC底层08:objc_msgSend慢速查找)