iOS-OC對(duì)象原理_objc_msgSend(二)

前言

iOS-OC對(duì)象原理_objc_msgSend(一)
在上篇文章中我們探索了objc_msgSend()慢速查找流程衣撬,即先從cache_t cache中的buckets中查找是否有sel == _cmd,存在則返回勾效;不存在三圆,將進(jìn)入慢速查找流程宫莱,即_lookUpImpOrForward流程盆驹,今天我們就詳細(xì)的探索下它的具體實(shí)現(xiàn)衣洁。

回顧

我們第一次看到_lookUpImpOrForward是在objc-msg.arm64.s匯編文件中(這里以arm64為例):

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

但是我們?cè)谠撐募滤阉鞔畚颍]有找到該跳轉(zhuǎn)指令的實(shí)現(xiàn)距帅;然后通過全局搜索依然沒有找到:


截屏2020-09-24 上午10.36.14.png

然后在匯編代碼片段開始有兩行醒目的注釋:

// lookUpImpOrForward(obj, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER)
// receiver and selector already in x0 and x1

全局搜索lookUpImpOrForward右锨,豁然開朗,這一跳轉(zhuǎn)就又來到了C++代碼(騷的一批)碌秸,我們鎖定了objc-runtime-new.mm:

截屏2020-09-24 上午10.43.29.png

lookUpImpOrForward實(shí)現(xià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();

    // 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); // 有問題???? cache_getImp - lookup - lookUpImpOrForward
        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;
}

核心代碼片段:

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

該片段會(huì)進(jìn)入一個(gè)循環(huán)绍移,開始從curClass->superClass->NSObject->nil,如果查詢到執(zhí)行goto done跳出循環(huán)讥电,如果沒有找到登夫,即curClass == nil時(shí),break跳出循環(huán)允趟。如下圖:

拓補(bǔ)圖.006.jpeg

上面的流程圖中就簡(jiǎn)單的展示了lookUpImpOrForward方法實(shí)現(xiàn)的大致邏輯恼策。
這里的log_and_fill_cacahe()會(huì)觸發(fā)cache_t內(nèi)部的fill_cache()方法,然后再到insert(),最終插入到緩存列表。

這里在更深入的看下getMethodNoSuper_nolock的內(nèi)部實(shí)現(xiàn):

static method_t *
getMethodNoSuper_nolock(Class cls, SEL sel)
{
    runtimeLock.assertLocked();

    ASSERT(cls->isRealized());
    // fixme nil cls? 
    // fixme nil sel?

    auto const methods = cls->data()->methods();
    for (auto mlists = methods.beginLists(),
              end = methods.endLists();
         mlists != end;
         ++mlists)
    {
        // <rdar://problem/46904873> getMethodNoSuper_nolock is the hottest
        // caller of search_method_list, inlining it turns
        // getMethodNoSuper_nolock into a frame-less function and eliminates
        // any store from this codepath.
        method_t *m = search_method_list_inline(*mlists, sel);
        if (m) return m;
    }

    return nil;
}

auto const methods = cls->data()->methods()涣楷,這里其實(shí)就是獲取當(dāng)前classclass_data_bits_t *bit下的bit->data()分唾,也就是class_rw_t這個(gè)結(jié)構(gòu)體的內(nèi)容,并讀取了該結(jié)構(gòu)體的methods()狮斗,獲取方法列表绽乔。
繼續(xù)將獲取到的methods傳遞給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;
}

經(jīng)過一個(gè)判斷后,又將方法列表mlist和目標(biāo)sel,傳遞到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;
}

這里是真正的開始查找流程碳褒,這里采用了二分法查詢折砸,當(dāng)查詢到就返回method_t,否則返回nil
大致流程圖如下:

拓補(bǔ)圖.007.jpeg

補(bǔ)充

forward_imp

const IMP forward_imp = (IMP)_objc_msgForward_impcache;

lookUpImpOrForward()方法中沙峻,在某種情況下會(huì)imp = forward_imp,當(dāng)返回forward_imp后睦授,又做了哪些處理吶?我們來探索下:

#if !OBJC_OLD_DISPATCH_PROTOTYPES
extern void _objc_msgForward_impcache(void);
#else
extern id _objc_msgForward_impcache(id, SEL, ...);
#endif

又看不到實(shí)現(xiàn)了摔寨,經(jīng)驗(yàn)告訴我又要跳轉(zhuǎn)到匯編:

STATIC_ENTRY __objc_msgForward_impcache

    // No stret specialization.
    b   __objc_msgForward

    END_ENTRY __objc_msgForward_impcache

    
    ENTRY __objc_msgForward

    adrp    x17, __objc_forward_handler@PAGE
    ldr p17, [x17, __objc_forward_handler@PAGEOFF]
    TailCallFunctionPointer x17
    
    END_ENTRY __objc_msgForward

這里面的流程:__objc_msgForward_impcache->__objc_msgForward->__objc_forward_handler去枷,在匯編中又找不到__objc_forward_handler的實(shí)現(xiàn)了,媽媽的~是复,回到C++:

// Default forward handler halts the process.
__attribute__((noreturn, cold)) void
objc_defaultForwardHandler(id self, SEL sel)
{
    _objc_fatal("%c[%s %s]: unrecognized selector sent to instance %p "
                "(no message forward handler is installed)", 
                class_isMetaClass(object_getClass(self)) ? '+' : '-', 
                object_getClassName(self), sel_getName(sel), self);
}
void *_objc_forward_handler = (void*)objc_defaultForwardHandler;

好熟悉的味道 ????,unrecognized selector sent to instance xxxx,看到了讓你大腦瞬間崩潰的東西删顶,原來是來自這里。
這也就意味著淑廊,當(dāng)imp = forward_imp,系統(tǒng)也就放棄治療了逗余,直接進(jìn)入Crash流程。

總結(jié)

我們以 [person sayHello]為例:
該方法在編譯后變?yōu)?code>objc_msgSend(person,sel_registerName("sayHello"))季惩;
首先會(huì)進(jìn)入快速查找流程录粱,該流程的實(shí)現(xiàn)在匯編指令中完成:
1.查到person的類對(duì)象,person->isa->Class;
2.查找緩存列表蜀备,Class->offset(16)->cache->_maskAndBuckets->buckets;
3.在buckets列表中查詢是否有sel == _cmd关摇,存在則返回荒叶,否則進(jìn)入CheckMiss->__objc_msgSend_uncached->MethodTableLookup->_lookUpImpOrForward,由此進(jìn)入慢速查找流程碾阁;
開始慢速查找流程
1.查找curClass類對(duì)象的方法列表,curCls->data()->methods()(objc_class->class_rw_t->methods());
2.通過二分遍歷查詢當(dāng)前方法列表中是有sel==_cmd,如果存在則返回并執(zhí)行4,否則執(zhí)行3些楣;
3.將當(dāng)前的curCls= curCls->superclass,首先在父類中的cache->_maskAndBuckets->buckets緩存列表查詢(imp = cache_getImp(curCls,sel))脂凶,如果存在,執(zhí)行4愁茁,否則執(zhí)行1蚕钦;直到curClass = nil時(shí),依然沒有匹配鹅很,跳出循環(huán)嘶居,執(zhí)行5;
4.找到目標(biāo)imp,添加到緩存列表邮屁,并返回整袁;
5.沒有找到對(duì)應(yīng)的imp,進(jìn)入消息轉(zhuǎn)發(fā)流程佑吝;消息轉(zhuǎn)發(fā)流程

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末坐昙,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子芋忿,更是在濱河造成了極大的恐慌炸客,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,290評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件戈钢,死亡現(xiàn)場(chǎng)離奇詭異痹仙,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)逆趣,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門蝶溶,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人宣渗,你說我怎么就攤上這事抖所。” “怎么了痕囱?”我有些...
    開封第一講書人閱讀 156,872評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵田轧,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我鞍恢,道長(zhǎng)傻粘,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,415評(píng)論 1 283
  • 正文 為了忘掉前任帮掉,我火速辦了婚禮弦悉,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蟆炊。我一直安慰自己稽莉,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,453評(píng)論 6 385
  • 文/花漫 我一把揭開白布涩搓。 她就那樣靜靜地躺著污秆,像睡著了一般。 火紅的嫁衣襯著肌膚如雪昧甘。 梳的紋絲不亂的頭發(fā)上良拼,一...
    開封第一講書人閱讀 49,784評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音充边,去河邊找鬼庸推。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的贬媒。 我是一名探鬼主播刮吧,決...
    沈念sama閱讀 38,927評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼掖蛤!你這毒婦竟也來了杀捻?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,691評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤蚓庭,失蹤者是張志新(化名)和其女友劉穎致讥,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體器赞,經(jīng)...
    沈念sama閱讀 44,137評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡垢袱,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,472評(píng)論 2 326
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了港柜。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片请契。...
    茶點(diǎn)故事閱讀 38,622評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖夏醉,靈堂內(nèi)的尸體忽然破棺而出爽锥,到底是詐尸還是另有隱情,我是刑警寧澤畔柔,帶...
    沈念sama閱讀 34,289評(píng)論 4 329
  • 正文 年R本政府宣布氯夷,位于F島的核電站,受9級(jí)特大地震影響靶擦,放射性物質(zhì)發(fā)生泄漏腮考。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,887評(píng)論 3 312
  • 文/蒙蒙 一玄捕、第九天 我趴在偏房一處隱蔽的房頂上張望踩蔚。 院中可真熱鬧,春花似錦枚粘、人聲如沸馅闽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽捞蛋。三九已至孝冒,卻和暖如春柬姚,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背庄涡。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來泰國(guó)打工量承, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,316評(píng)論 2 360
  • 正文 我出身青樓撕捍,卻偏偏與公主長(zhǎng)得像拿穴,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子忧风,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,490評(píng)論 2 348