objc_msgSend-慢速查找流程

objc_msgSend-快速查找流程中我們講到摹闽,objc_msgSend首先通過匯編快速查找方法緩存粘驰,如果找到簇捍,調(diào)用TailCallCachedImp直接將方法緩存起來然后進行調(diào)用就可以了周荐,如果查找不到就跳到CheckMiss稳摄,然后走慢速查找流程公般。接下來我們分析一下objc_msgSend慢速查找流程忍啸。

objc_msgSend查找流程:

  • 獲取傳入對象所屬的類
  • 獲取該類的方法緩存表
  • 使用傳入的sel選擇器在緩存中查詢
  • 如果緩存中不存在砰琢,則開始慢速查找流程
  • 慢速查找流程蘸嘶,找到后,跳轉(zhuǎn)到IMP映射位置的方法

objc_msgSend-快速查找流程中我們分析了陪汽,先通過GetClassFromIsa_p16獲取到傳入對象所屬的類训唱,然后通過CacheLookup在方法緩存表中查找,如果緩存命中則走CacheHit方法挚冤,緩存沒命中走CheckMiss方法况增。

一、CheckMiss 方法

  .macro CheckMiss
// miss if bucket->sel == 0
.if $0 == GETIMP
cbz p9, LGetImpMiss
.elseif $0 == NORMAL //傳進來的是NORMAL,所以走這里
cbz p9, __objc_msgSend_uncached
.elseif $0 == LOOKUP
cbz p9, __objc_msgLookup_uncached
.else
.abort oops
.endif
.endmacro

傳進來的是NORMAL训挡,所以會走到 __objc_msgSend_uncached 方法

二澳骤、__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
TailCallFunctionPointer x17

END_ENTRY __objc_msgSend_uncached

緊接著又會來到 MethodTableLookup 方法

三、MethodTableLookup 方法

.macro MethodTableLookup

// push frame
SignLR
stp fp, lr, [sp, #-16]!
mov fp, sp

// save parameter registers: x0..x8, q0..q7
sub sp, sp, #(10*8 + 8*16)
stp q0, q1, [sp, #(0*16)]
stp q2, q3, [sp, #(2*16)]
stp q4, q5, [sp, #(4*16)]
stp q6, q7, [sp, #(6*16)]
stp x0, x1, [sp, #(8*16+0*8)]
stp x2, x3, [sp, #(8*16+2*8)]
stp x4, x5, [sp, #(8*16+4*8)]
stp x6, x7, [sp, #(8*16+6*8)]
str x8,     [sp, #(8*16+8*8)]

// 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 registers and return
ldp q0, q1, [sp, #(0*16)]
ldp q2, q3, [sp, #(2*16)]
ldp q4, q5, [sp, #(4*16)]
ldp q6, q7, [sp, #(6*16)]
ldp x0, x1, [sp, #(8*16+0*8)]
ldp x2, x3, [sp, #(8*16+2*8)]
ldp x4, x5, [sp, #(8*16+4*8)]
ldp x6, x7, [sp, #(8*16+6*8)]
ldr x8,     [sp, #(8*16+8*8)]

mov sp, fp
ldp fp, lr, [sp], #16
AuthenticateLR

.endmacro

接著又會來到 lookUpImpOrForward 方法

四澜薄、lookUpImpOrForward 方法

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.lock();


// 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.assertLocked();
curClass = cls;

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)) {
        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)) {
        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;
}
4.1 判斷緩存是否存在为肮,存在則直接通過cls和sel直接獲取imp,并返回表悬。
if (fastpath(behavior & LOOKUP_CACHE)) {
   imp = cache_getImp(cls, sel);
   if (imp) goto done_nolock;
 }
4.2 相關類信息判斷
  • 根據(jù)所有已知類的列表檢查給定的類弥锄,有問題直接內(nèi)部拋出異常。

  • 判斷類是否已經(jīng)被實現(xiàn)蟆沫,未實現(xiàn)則去實現(xiàn)籽暇,這部分后面類的加載篇章會詳細分析,主要是按照superclass和isa走向去遞歸實現(xiàn)父類和元類饭庞,同時準備好對象方法和類方法的查找鏈戒悠。

  • 判斷類是否被初始化,未初始化則去初始化舟山。

    checkIsKnownClass(cls);
    
    if (slowpath(!cls->isRealized())) {
     cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
    }
    
    if (slowpath((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized())) {
    cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
    }
    
4.3 查找本類的方法列表
4.3.1 利用 getMethodNoSuper_nolock 查找本類的方法列表绸狐,如果找到了卤恳,進入 goto done;
4.3.2 getMethodNoSuper_nolock 方法

調(diào)用調(diào)用 search_method_list_inline 方法 對本類方法列表進行查找

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;
}
4.3.3 search_method_list_inline 方法

調(diào)用 findMethodInSortedMethodList 方法 對本類方法列表進行二分查找

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;
}
4.3.4 findMethodInSortedMethodList 方法

對本類方法列表進行二分查找

  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;
}
4.4 done 方法
  • 如果找到了,進入本方法寒矿,調(diào)用 log_and_fill_cache 方法

    done:
    log_and_fill_cache(cls, imp, sel, inst, curClass);
    runtimeLock.unlock();
    
4.5 log_and_fill_cache 方法
  • 利用 cache_fill 方法 寫入到緩存里面突琳,為了下次直接從緩存里面快速查找到。

     static 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
     // objc_msgSend -> 二分查找自己 -> cache_fill -> objc_msgSend
     //
     cache_fill(cls, sel, imp, receiver);
    }
    
4.6 遞歸查找父類的緩存
4.6.1 查找本類的方法列表 如果找不到符相,就遞歸查找父類的緩存
  • 調(diào)用 cache_getImp 方法 找到父類

    // Superclass cache.
    imp = cache_getImp(curClass, sel); // 有問題???? cache_getImp -     lookUpImpOrForward
    
  • cache_getImp 方法

    STATIC_ENTRY _cache_getImp
    
    GetClassFromIsa_p16 p0
    CacheLookup GETIMP, _cache_getImp
    
    LGetImpMiss:
     mov  p0, #0
     ret
    
     END_ENTRY _cache_getImp
    
4.7 遞歸父類緩存查找不到拆融,利用 imp = forward_imp
if (slowpath((curClass = curClass->superclass) == nil)) {
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = forward_imp;
break;
}
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;
}
4.7.1 forward_imp
  • const IMP forward_imp = (IMP)_objc_msgForward_impcache;
4.7.2 _objc_msgForward_impcache
  • _objc_msgForward_impcache 方法 調(diào)用 __objc_msgForward 方法

  • __objc_msgForward 方法 調(diào)用 TailCallFunctionPointer x17

    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
    
4.7.3 TailCallFunctionPointer 方法

TailCallFunctionPointer 方法 就是返回指針的值,返回 x17 的值啊终,x17 的值是 __objc_forward_handler 方法 確定的

.macro TailCallFunctionPointer
// $0 = function pointer value
braaz   $0
.endmacro
4.7.4 __objc_forward_handler 方法
 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;

如果方法沒有實現(xiàn)镜豹,imp 會置換成 forward_imp , forward_imp 最終會走到 __objc_forward_handler 方法 返回 unrecognized selector sent to instance ... 信息,我們查看一下方法沒有實現(xiàn)的報錯信息會發(fā)現(xiàn)蓝牲,報錯信息的模板原來在這趟脂。

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[LGPerson say666]: unrecognized selector sent to instance 0x1007738f0'

4.8 動態(tài)方法決議

在4.7中將 imp 置換成 forward_imp 后,會 break 跳出循環(huán)例衍,走到動態(tài)方法決議這里:

 if (slowpath(behavior & LOOKUP_RESOLVER)) {
    behavior ^= LOOKUP_RESOLVER;
    return resolveMethod_locked(inst, sel, cls, behavior);
 }
4.8.1 resolveMethod_locked 方法
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);
}
4.8.2 resolveInstanceMethod 方法`
  • 我們發(fā)現(xiàn)在 resolveInstanceMethod 方法 中將 IMP imp = lookUpImpOrNil(inst, sel, cls); 昔期,所以我們跳進 lookUpImpOrNil 方法 看一下會發(fā)現(xiàn)又回到了 lookUpImpOrForward 方法 ,那對之前做了什么產(chǎn)生了好奇佛玄。

  • 往上走我們發(fā)現(xiàn)有下面兩行代碼
    BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend; bool resolved = msg(cls, resolve_sel, sel);

  • 如果我們實現(xiàn) resolveInstanceMethod 方法 將方法的 imp 進行賦值镇眷,然后再回到 lookUpImpOrForward 方法 之后 imp 有值,就不會報錯了翎嫡。

    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));
       }
     }
    }
    
4.8.3 動態(tài)方法決議實現(xiàn)
#import "LGPerson.h"
#import <objc/message.h>

@implementation LGPerson

- (void)askHelp{
NSLog(@"%s",__func__);
}

+ (BOOL)resolveInstanceMethod:(SEL)sel{

if (sel == @selector(say666)) {
    NSLog(@"%@ 來了老弟",NSStringFromSelector(sel));
    
    IMP imp           = class_getMethodImplementation(self, @selector(askHelp));
    Method sayAskHelpMethod = class_getInstanceMethod(self, @selector(askHelp));
    const char *type  = method_getTypeEncoding(sayAskHelpMethod);
    return class_addMethod(self, sel, imp, type);
}

  return [super resolveInstanceMethod:sel];
}

5. 總結

  • 當在 objc_msgSend 緩存中沒有找到方法,就會來到 CheckMiss -> __objc_msgSend_uncached -> MethodTableLookup -> lookUpImpOrForward 進行慢速查找流程永乌。
  • 在 lookUpImpOrForward 里面會先去本類當中查找方法 getMethodNoSuper_nolock 惑申,本類沒有找到就會去遞歸的去父類當中查找。
  • 如果本類和父類都沒有找到翅雏,就會進行動態(tài)方法決議 _class_resolveMethod 圈驼,這是蘋果爸爸給我們的最后的機會。

最終到 _objc_forward_handler 方法 崩潰報錯 unrecognized selector sent to instance ...望几。

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末绩脆,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子橄抹,更是在濱河造成了極大的恐慌靴迫,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件楼誓,死亡現(xiàn)場離奇詭異玉锌,居然都是意外死亡,警方通過查閱死者的電腦和手機疟羹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門主守,熙熙樓的掌柜王于貴愁眉苦臉地迎上來禀倔,“玉大人,你說我怎么就攤上這事参淫【群” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵涎才,是天一觀的道長鞋既。 經(jīng)常有香客問我,道長憔维,這世上最難降的妖魔是什么涛救? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮业扒,結果婚禮上检吆,老公的妹妹穿的比我還像新娘。我一直安慰自己程储,他們只是感情好蹭沛,可當我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著章鲤,像睡著了一般摊灭。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上败徊,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天帚呼,我揣著相機與錄音,去河邊找鬼皱蹦。 笑死煤杀,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的沪哺。 我是一名探鬼主播沈自,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼辜妓!你這毒婦竟也來了枯途?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤籍滴,失蹤者是張志新(化名)和其女友劉穎酪夷,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體孽惰,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡捶索,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了灰瞻。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片腥例。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡辅甥,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出燎竖,到底是詐尸還是另有隱情璃弄,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布构回,位于F島的核電站夏块,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏纤掸。R本人自食惡果不足惜脐供,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望借跪。 院中可真熱鬧政己,春花似錦、人聲如沸掏愁。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽果港。三九已至沦泌,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間辛掠,已是汗流浹背谢谦。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留萝衩,地道東北人他宛。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像欠气,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子镜撩,可洞房花燭夜當晚...
    茶點故事閱讀 44,713評論 2 354

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