OC底層08:消息慢速查找流程

前言

上章寫了消息流程中,查找cache的過程,當(dāng)cache中不存在需要的方法時(shí),系統(tǒng)會(huì)調(diào)用lookUpImpOrForward進(jìn)入慢速查找流程涌穆。

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();
    if (fastpath(behavior & LOOKUP_CACHE)) {
        imp = cache_getImp(cls, sel);
        if (imp) goto done_nolock;
    }
    runtimeLock.lock();
    checkIsKnownClass(cls);
    if (slowpath(!cls->isRealized())) {
        cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
    }
    if (slowpath((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized())) {
        cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
    }
    runtimeLock.assertLocked();
    curClass = cls;
    for (unsigned attempts = unreasonableClassCount();;) {
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp;
            goto done;
        }
        if (slowpath((curClass = curClass->superclass) == nil)) {
            imp = forward_imp;
            break;
        }

        if (slowpath(--attempts == 0)) {
            _objc_fatal("Memory corruption in class list.");
        }
        imp = cache_getImp(curClass, sel);
        if (slowpath(imp == forward_imp)) {
            break;
        }
        if (fastpath(imp)) {
            goto done;
        }
    }
    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;
}
  1. 先再查找一遍cache,避免異步造成的影響
    if (fastpath(behavior & LOOKUP_CACHE)) {
        imp = cache_getImp(cls, sel);
        if (imp) goto done_nolock;
    }
  1. checkIsKnownClass(cls);檢查當(dāng)前類是否是已加載的類
  2. realizeClassMaybeSwiftAndLeaveLocked確定繼承鏈
  3. initializeAndLeaveLocked確定全部初始化
  4. 慢速查找的關(guān)鍵流程for (unsigned attempts = unreasonableClassCount();;)不斷循環(huán)遞歸查找需要的方法
  5. Method meth = getMethodNoSuper_nolock(curClass, sel);二分法查找方法,找到則進(jìn)入done執(zhí)行,沒有繼續(xù)后續(xù)步驟
//二分查找算法
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.  
            //往前查找 -- 分類的方法會(huì)覆蓋類的方法
            while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
                probe--;
            }
            return (method_t *)probe;
        }
        
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}
  1. 當(dāng)前類沒找到,會(huì)進(jìn)入父類先查找cache再查找父類方法列表,找到也跳出循環(huán)。
  2. 當(dāng)循環(huán)結(jié)束后,跳出循環(huán)統(tǒng)一進(jìn)行一次處理,也是OC的容錯(cuò)處理
    if (slowpath(behavior & LOOKUP_RESOLVER)) {
        behavior ^= LOOKUP_RESOLVER;
        return resolveMethod_locked(inst, sel, cls, behavior);
    }

static NEVER_INLINE IMP
resolveMethod_locked(id inst, SEL sel, Class cls, int behavior)
{
    runtimeLock.assertLocked();
    ASSERT(cls->isRealized());

    runtimeLock.unlock();

    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]
        resolveInstanceMethod(inst, sel, cls);
    } 
    else {
        // try [nonMetaClass resolveClassMethod:sel]
        // and [cls resolveInstanceMethod:sel]
        resolveClassMethod(inst, sel, cls);
        if (!lookUpImpOrNil(inst, sel, cls)) {
            resolveInstanceMethod(inst, sel, cls);
        }
    }

    // chances are that calling the resolver have populated the cache
    // so attempt using it
    return lookUpImpOrForward(inst, sel, cls, behavior | LOOKUP_CACHE);
}

static void resolveInstanceMethod(id inst, SEL sel, Class cls)
{
    runtimeLock.assertUnlocked();
    ASSERT(cls->isRealized());
    SEL resolve_sel = @selector(resolveInstanceMethod:);

    if (!lookUpImpOrNil(cls, resolve_sel, cls->ISA())) {
        // Resolver not implemented.
        return;
    }

    BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
    bool resolved = msg(cls, resolve_sel, sel);

    // Cache the result (good or bad) so the resolver doesn't fire next time.
    // +resolveInstanceMethod adds to self a.k.a. cls
    IMP imp = lookUpImpOrNil(inst, sel, cls);

    if (resolved  &&  PrintResolving) {
        if (imp) {
            _objc_inform("RESOLVE: method %c[%s %s] "
                         "dynamically resolved to %p", 
                         cls->isMetaClass() ? '+' : '-', 
                         cls->nameForLogging(), sel_getName(sel), imp);
        }
        else {
            // Method resolver didn't add anything?
            _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
                         ", but no new implementation of %c[%s %s] was found",
                         cls->nameForLogging(), sel_getName(sel), 
                         cls->isMetaClass() ? '+' : '-', 
                         cls->nameForLogging(), sel_getName(sel));
        }
    }
}
  1. 消息會(huì)在resolveInstanceMethod:進(jìn)行第一次處理,處理完后會(huì)再走一遍lookUpImpOrNil,返回新的處理結(jié)果
    加上上章cache查找,消息處理流程可以總結(jié)如圖:(圖片來源于iOS-底層原理 13:消息流程分析之慢速查找)
    消息查找流程
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子踢京,更是在濱河造成了極大的恐慌跨算,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蚁吝,死亡現(xiàn)場離奇詭異,居然都是意外死亡霹粥,警方通過查閱死者的電腦和手機(jī)灭将,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來后控,“玉大人庙曙,你說我怎么就攤上這事『铺裕” “怎么了捌朴?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長张抄。 經(jīng)常有香客問我砂蔽,道長,這世上最難降的妖魔是什么署惯? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任左驾,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘诡右。我一直安慰自己安岂,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布帆吻。 她就那樣靜靜地躺著域那,像睡著了一般。 火紅的嫁衣襯著肌膚如雪猜煮。 梳的紋絲不亂的頭發(fā)上次员,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天,我揣著相機(jī)與錄音王带,去河邊找鬼淑蔚。 笑死,一個(gè)胖子當(dāng)著我的面吹牛辫秧,可吹牛的內(nèi)容都是我干的束倍。 我是一名探鬼主播,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼盟戏,長吁一口氣:“原來是場噩夢啊……” “哼绪妹!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起柿究,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤邮旷,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后蝇摸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體婶肩,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年貌夕,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了律歼。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,615評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡啡专,死狀恐怖险毁,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情们童,我是刑警寧澤畔况,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站慧库,受9級特大地震影響跷跪,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜齐板,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一吵瞻、第九天 我趴在偏房一處隱蔽的房頂上張望葛菇。 院中可真熱鬧,春花似錦橡羞、人聲如沸熟呛。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至吗冤,卻和暖如春又厉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背椎瘟。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工覆致, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人肺蔚。 一個(gè)月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓煌妈,卻偏偏與公主長得像,于是被迫代替她去往敵國和親宣羊。 傳聞我的和親對象是個(gè)殘疾皇子璧诵,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,630評論 2 359