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

流程圖如下


cachemiss.png

今天我們著重分析_lookUpImpOrForward

_lookUpImpOrForward

我們先用一個流程圖來大致了解一下_lookUpImpOrForward的流程


慢速查找.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的參數(shù)
CacheLookup后面參數(shù)為GETIMP,如果緩存中找不到接下來可能會走CheckMiss或者JumpMiss中的一個由于參數(shù)為GETIMP所以走LGetImpMiss,返回空,

是否已經(jīng)實現(xiàn)realizeClassMaybeSwiftAndLeaveLocked如果沒有實現(xiàn)下面步驟

ClassIsRealized.png

realizeClassWithoutSwift中主要是給class賦值,把類中的元素添加進去。

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

這兩個方法實現(xiàn)遞歸,把所有的父類和元類的父類都遞歸完

isInitialized方法

IsInitialized.png

類的方法列表中查詢對應的方法

getMethodNoSuper_nolock中for循環(huán)


大循環(huán).png

getMethodNoSuper_nolock中for循環(huán)又一個方法search_method_list_inline是采用二分法實現(xiàn)方法的尋找


MethodSearch.png

** lookUpImpOrForward只是負責尋找IMP,那什么時候完成IMP函數(shù)的調(diào)用呢 **

什么時候完成函數(shù)IMP的調(diào)用

1.在快速查找中找到IMP

//objc_msgsend調(diào)用CacheLookup
CacheLookup NORMAL, _objc_msgSend
//CacheLookup命中CacheHit NORMAL
//在CacheHit中調(diào)用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調(diào)到我們找到的IMP,并執(zhí)行
2.在慢速查找中找到

//如果在CacheLookup中沒有在緩存中找到則會調(diào)用__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會調(diào)用到c++完成IMP的查找
    MethodTableLookup
    TailCallFunctionPointer x17

    END_ENTRY __objc_msgSend_uncached

TailCallFunctionPointer的實現(xiàn)就是調(diào)到我們查找到的IMP去執(zhí)行

面試題

我們創(chuàng)建一個類MYTeacher,另外在NSObject的Category中添加一個方法-(void)myNSObjectMethod;并實現(xiàn)

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

問會報錯嗎?
答案是能正常運行并打印[NSObject(MYCategory) myNSObjectMethod]
因為我們調(diào)用MYTeacher的類的方法系統(tǒng)會查詢元類和沿著元類的繼承樹的實例方法,最后查詢到NSObject, myNSObjectMethod是NSObject的實例。
再試想如果myNSObjectMethod是NSObject的類方法能不能正常呢?答案是能正常運行isa流程圖送上


isa流程圖.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容