objc_msgSend 慢速查找流程分析

慢速查找流程分析.jpg

1、objc_msgSend滿流程查找切入點

1.1在經(jīng)過objc_msgSend流程分析發(fā)現(xiàn),
開啟緩存查找流程CacheLookup 主要是找imp或者執(zhí)行objc_msgSend_uncached
會傳入如下參數(shù)

// calls imp or objc_msgSend_uncached
CacheLookup NORMAL, _objc_msgSend, __objc_msgSend_uncached

CacheLookup 具體實現(xiàn)晕翠,截取部分代碼僵驰,和部分對應的流程圖想际,詳細可看這里

macro CacheLookup Mode, Function, MissLabelDynamic, MissLabelConstant
...代碼省略...

1:  ldp p17, p9, [x13], #-BUCKET_SIZE   //     {imp, sel} = *bucket--
    cmp p9, p1              //     if (sel != _cmd) {
    b.ne    3f              //         scan more
                        //     } else {
2:  CacheHit \Mode              // hit:    call or return imp
                        //     }
3:  cbz p9, \MissLabelDynamic       //     if (sel == 0) goto Miss;
    cmp p13, p10            // } while (bucket >= buckets)
    b.hs    1b

...代碼省略...

最后一個元素查找完 if (sel == 0) goto Miss.png

執(zhí)行cbz p9, \MissLabelDynamic划栓,判斷if (sel == 0) goto Miss呢撞,直接返回MissLabelDynamic损姜,其對應的傳入?yún)?shù):__objc_msgSend_uncached匯編函數(shù)

接下來在objc-msg-arm64.s文件中查找__objc_msgSend_uncached的匯編實現(xiàn),其中的核心是MethodTableLookup(即查詢方法列表)殊霞,其源碼如下:

    STATIC_ENTRY __objc_msgLookup_uncached
    UNWIND __objc_msgLookup_uncached, FrameWithNoSaves

    // THIS IS NOT A CALLABLE C FUNCTION
    // Out-of-band p15 is the class to search
    
    MethodTableLookup
    ret

    END_ENTRY __objc_msgLookup_uncached

繼續(xù)查看MethodTableLookup匯編實現(xiàn)

.macro MethodTableLookup
    
    SAVE_REGS MSGSEND

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

mov x17, x0在匯編里面 x0是第一個寄存器摧阅,同樣也是返回值的存儲位置,所以可以發(fā)現(xiàn)bl _lookUpImpOrForward就是我們IMP要查找的地方绷蹲,_lookUpImpOrForward對應的我們查找lookUpImpOrForward(obj, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER)方法棒卷;

2顾孽、lookUpImpOrForward 實現(xiàn)源碼分析

我們使用_lookUpImpOrForward搜索,沒有發(fā)現(xiàn)匯編的實現(xiàn)代碼比规,繼而我們查找lookUpImpOrForward去這個函數(shù)若厚,在objc-runtime-new.mm里

extern IMP lookUpImpOrForward(id obj, SEL, Class cls, int behavior);

備注:lookUpImpOrForward我們要的目標就是為了找到找到當前IMP的返回值

NEVER_INLINE
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
    const IMP forward_imp = (IMP)_objc_msgForward_impcache;
    IMP imp = nil;  //初始化IMP
    Class curClass;

    runtimeLock.assertUnlocked();

//判斷是否進行一些初始化處理    
if (slowpath(!cls->isInitialized())) {
        // The first message sent to a class is often +new or +alloc, or +self
        // which goes through objc_opt_* or various optimized entry points.
        //
        // However, the class isn't realized/initialized yet at this point,
        // and the optimized entry points fall down through objc_msgSend,
        // which ends up here.
        //
        // We really want to avoid caching these, as it can cause IMP caches
        // to be made with a single entry forever.
        //
        // Note that this check is racy as several threads might try to
        // message a given class for the first time at the same time,
        // in which case we might cache anyway.
        behavior |= LOOKUP_NOCACHE;
    }

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

  ///判斷當前的的class是否注冊到當前的緩存表里面去
    checkIsKnownClass(cls);
///對當前rw ro進行處理
    cls = realizeAndInitializeIfNeeded_locked(inst, cls, behavior & LOOKUP_INITIALIZE);
    // runtimeLock may have been dropped but is now locked again
    runtimeLock.assertLocked();
    curClass = cls;

    // The code used to lookup 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();;) {
        if (curClass->cache.isConstantOptimizedCache(/* strict */true)) {
#if CONFIG_USE_PREOPT_CACHES
            imp = cache_getImp(curClass, sel);
            if (imp) goto done_unlock;
            curClass = curClass->cache.preoptFallbackClass();
#endif
        } else {
            // curClass method list.
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
                imp = meth->imp(false);
                goto done;
            }

            if (slowpath((curClass = curClass->getSuperclass()) == 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:
    if (fastpath((behavior & LOOKUP_NOCACHE) == 0)) {
#if CONFIG_USE_PREOPT_CACHES
        while (cls->cache.isConstantOptimizedCache(/* strict */true)) {
            cls = cls->cache.preoptFallbackClass();
        }
#endif
        log_and_fill_cache(cls, imp, sel, inst, curClass);
    }
 done_unlock:
    runtimeLock.unlock();
    if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
        return nil;
    }
    return imp;
}

備注:

2.1、slowpath(!cls->isInitialized())判斷是否進行一些初始化處理

2.2蜒什、checkIsKnownClass(cls)判斷當前的的class是否注冊到當前的緩存表allocatedClasses里面去了测秸,下面是調(diào)用源碼

static void
checkIsKnownClass(Class cls)
{
    if (slowpath(!isKnownClass(cls))) {
        _objc_fatal("Attempt to use unknown class %p.", cls);
    }
}
static bool
isKnownClass(Class cls)
{
    if (fastpath(objc::dataSegmentsRanges.contains(cls->data()->witness, (uintptr_t)cls))) {
        return true;
    }
    auto &set = objc::allocatedClasses.get();
    return set.find(cls) != set.end() || dataSegmentsContain(cls);
}

2.3、 cls = realizeAndInitializeIfNeeded_locked(inst, cls, behavior & LOOKUP_INITIALIZE),如果類沒有實現(xiàn)吃谣,則實現(xiàn)給定的類乞封,如果還沒有初始化做裙,則先初始化岗憋;
inst:是cls的一個實例一個子類,如果不知道則為nil锚贱;
cls:要初始化或者實現(xiàn)的類仔戈;
behavior & LOOKUP_INITIALIZE:YES來初始化類,為NO來跳過初始化

static Class
realizeAndInitializeIfNeeded_locked(id inst, Class cls, bool initialize)
{
    runtimeLock.assertLocked();
    if (slowpath(!cls->isRealized())) {
        cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
    }

    if (slowpath(initialize && !cls->isInitialized())) {
        cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
    }
    return cls;
}
realizeClassMaybeSwiftAndLeaveLocked(Class cls, mutex_t& lock)
{
    return realizeClassMaybeSwiftMaybeRelock(cls, lock, true);
}
realizeClassMaybeSwiftMaybeRelock(Class cls, mutex_t& lock, bool leaveLocked)
{
    lock.assertLocked();

    if (!cls->isSwiftStable_ButAllowLegacyForNow()) {
   //處理非Swift類的初始化執(zhí)行如下:
        realizeClassWithoutSwift(cls, nil);
        if (!leaveLocked) lock.unlock();
    } else {
        //處理Swift類的初始化執(zhí)行如下:
        lock.unlock();
        cls = realizeSwiftClass(cls);
        ASSERT(cls->isRealized());    // callback must have provoked realization
        if (leaveLocked) lock.lock();
    }

    return cls;
}

realizeClassWithoutSwift類cls進行首次初始化拧廊,分配類cls讀寫數(shù)據(jù)监徘,不執(zhí)行任何swift端初始化。最終返回類的實際類結(jié)構(gòu)吧碾。

static Class realizeClassWithoutSwift(Class cls, Class previously)
{
    runtimeLock.assertLocked();

    class_rw_t *rw;
    Class supercls;
    Class metacls;

    if (!cls) return nil;
    if (cls->isRealized()) {
        validateAlreadyRealizedClass(cls);
        return cls;
    }
    ASSERT(cls == remapClass(cls));

    // fixme verify class is not in an un-dlopened part of the shared cache?

    auto ro = (const class_ro_t *)cls->data();
    auto isMeta = ro->flags & RO_META;
    if (ro->flags & RO_FUTURE) {
        // 未知的類凰盔,提前已經(jīng)分配了Rw數(shù)據(jù)。
        rw = cls->data();
        ro = cls->data()->ro();
        ASSERT(!isMeta);
        cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
    } else {
        // 正常的類倦春。分配可寫的類數(shù)據(jù)户敬。.
        rw = objc::zalloc<class_rw_t>();
        rw->set_ro(ro);
        rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
        cls->setData(rw);
    }
   ....
    代碼省略
   ...
    return cls;
}

2.4 for (unsigned attempts = unreasonableClassCount();;)二分查找流程代碼查看分析

for (unsigned attempts = unreasonableClassCount();;) {
//判斷是否有共享緩存,為什么還要判斷在共享緩存里面找一遍呢睁本?我們在執(zhí)行g(shù)etMethodNoSuper_nolock之前尿庐,前面做了很多ro,rw的的操作,可能在某一時刻呢堰,已經(jīng)將方法寫入到緩存里面了抄瑟,所以做多一次判斷
        if (curClass->cache.isConstantOptimizedCache(/* strict */true)) {
#if CONFIG_USE_PREOPT_CACHES
            imp = cache_getImp(curClass, sel);
            if (imp) goto done_unlock;
            curClass = curClass->cache.preoptFallbackClass();
#endif
        } else {
            // curClass method list.
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
                imp = meth->imp(false);
                goto done;
            }

            if (slowpath((curClass = curClass->getSuperclass()) == nil)) {
                // No implementation found, and method resolver didn't help.
                // Use forwarding.
                imp = forward_imp;
                break;
            }
        }

getMethodNoSuper_nolock

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

search_method_list_inline

search_method_list_inline(const method_list_t *mlist, SEL sel)
{
    int methodListIsFixedUp = mlist->isFixedUp();
    int methodListHasExpectedSize = mlist->isExpectedSize();
    
    if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
        return findMethodInSortedMethodList(sel, mlist);
    } else {
        // Linear search of unsorted method list
        if (auto *m = findMethodInUnsortedMethodList(sel, mlist))
            return m;
    }

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

findMethodInSortedMethodList

findMethodInSortedMethodList(SEL key, const method_list_t *list)
{
    if (list->isSmallList()) {
        if (CONFIG_SHARED_CACHE_RELATIVE_DIRECT_SELECTORS && objc::inSharedCache((uintptr_t)list)) {
            return findMethodInSortedMethodList(key, list, [](method_t &m) { return m.getSmallNameAsSEL(); });
        } else {
            return findMethodInSortedMethodList(key, list, [](method_t &m) { return m.getSmallNameAsSELRef(); });
        }
    } else {
        return findMethodInSortedMethodList(key, list, [](method_t &m) { return m.big().name; });
    }
}

findMethodInSortedMethodList

findMethodInSortedMethodList(SEL key, const method_list_t *list, const getNameFunc &getName)
{
    ASSERT(list);

    auto first = list->begin();
    auto base = first;
    decltype(first) probe;

    uintptr_t keyValue = (uintptr_t)key;
    uint32_t count;
    
    //分析
    //假定count = 8 ,進行右移1操作
    //1000 - 0100
    //8 - 1 = 7  >>  -> 0011  3 >> 1 == 1
    //0 + 4 = 4
    //5 - 8
    // 6- 7
    for (count = list->count; count != 0; count >>= 1) {
        probe = base + (count >> 1);
        
        uintptr_t probeValue = (uintptr_t)getName(probe);
        
        if (keyValue == probeValue) {
            // `probe` is a match.
            // Rewind looking for the *first* occurrence of this value.
            // This is required for correct category overrides.
            //分類和主類有相同的方法枉疼,優(yōu)先調(diào)用分類的方法
            while (probe > first && keyValue == (uintptr_t)getName((probe - 1))) {
                probe--;
            }
            return &*probe;
        }
        
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}

2.5二分查找流程結(jié)束后 獲取到imp皮假,之后進行 goto done方法調(diào)用,在調(diào)用log_and_fill_cache方法進行一個方法緩存填充骂维,也就是說記錄一個方法的調(diào)用钞翔,如果有記錄的話,就會來進行方法的緩存填充席舍。這樣以來就不用每次都進行二分查找的操作布轿,下次查找時直接走快速查找流程,具體代碼如下:

tatic void
log_and_fill_cache(Class cls, IMP imp, SEL sel, id receiver, Class implementer)
{
#if SUPPORT_MESSAGE_LOGGING
    if (slowpath(objcMsgLogEnabled && implementer)) {
        bool cacheIt = logMessageSend(implementer->isMetaClass(), 
                                      cls->nameForLogging(),
                                      implementer->nameForLogging(), 
                                      sel);
        if (!cacheIt) return;
    }
#endif
    cls->cache.insert(sel, imp, receiver);
}

2.6二分查找流程結(jié)束后如果沒有獲取到imp,則會進行父類的方法查找流程(slowpath((curClass = curClass->getSuperclass()) == nil))汰扭,最后會進行父類快速查找和慢速度流程稠肘,如果最終找不到,系統(tǒng)會進行消息動態(tài)決議消息轉(zhuǎn)發(fā)萝毛,這個具體后面章節(jié)在做分析

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末项阴,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子笆包,更是在濱河造成了極大的恐慌环揽,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,252評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件庵佣,死亡現(xiàn)場離奇詭異歉胶,居然都是意外死亡,警方通過查閱死者的電腦和手機巴粪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評論 3 399
  • 文/潘曉璐 我一進店門通今,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人肛根,你說我怎么就攤上這事辫塌。” “怎么了派哲?”我有些...
    開封第一講書人閱讀 168,814評論 0 361
  • 文/不壞的土叔 我叫張陵臼氨,是天一觀的道長。 經(jīng)常有香客問我芭届,道長储矩,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,869評論 1 299
  • 正文 為了忘掉前任喉脖,我火速辦了婚禮椰苟,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘树叽。我一直安慰自己舆蝴,他們只是感情好,可當我...
    茶點故事閱讀 68,888評論 6 398
  • 文/花漫 我一把揭開白布题诵。 她就那樣靜靜地躺著洁仗,像睡著了一般。 火紅的嫁衣襯著肌膚如雪性锭。 梳的紋絲不亂的頭發(fā)上赠潦,一...
    開封第一講書人閱讀 52,475評論 1 312
  • 那天,我揣著相機與錄音草冈,去河邊找鬼她奥。 笑死瓮增,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的哩俭。 我是一名探鬼主播绷跑,決...
    沈念sama閱讀 41,010評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼凡资!你這毒婦竟也來了砸捏?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,924評論 0 277
  • 序言:老撾萬榮一對情侶失蹤隙赁,失蹤者是張志新(化名)和其女友劉穎垦藏,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體伞访,經(jīng)...
    沈念sama閱讀 46,469評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡掂骏,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,552評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了咐扭。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片芭挽。...
    茶點故事閱讀 40,680評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡滑废,死狀恐怖蝗肪,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蠕趁,我是刑警寧澤薛闪,帶...
    沈念sama閱讀 36,362評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站俺陋,受9級特大地震影響豁延,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜腊状,卻給世界環(huán)境...
    茶點故事閱讀 42,037評論 3 335
  • 文/蒙蒙 一诱咏、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧缴挖,春花似錦袋狞、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至棚点,卻和暖如春早处,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背瘫析。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評論 1 274
  • 我被黑心中介騙來泰國打工砌梆, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留默责,地道東北人。 一個月前我還...
    沈念sama閱讀 49,099評論 3 378
  • 正文 我出身青樓咸包,卻偏偏與公主長得像傻丝,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子诉儒,可洞房花燭夜當晚...
    茶點故事閱讀 45,691評論 2 361

推薦閱讀更多精彩內(nèi)容