objc_msgSend-慢速查找流程

objc_msgSend-快速查找流程中我们讲到,objc_msgSend首先通过汇编快速查找方法缓存,如果找到,调用TailCallCachedImp直接将方法缓存起来然后进行调用就可以了,如果查找不到就跳到CheckMiss,然后走慢速查找流程。接下来我们分析一下objc_msgSend慢速查找流程。

objc_msgSend查找流程:

  • 获取传入对象所属的类
  • 获取该类的方法缓存表
  • 使用传入的sel选择器在缓存中查询
  • 如果缓存中不存在,则开始慢速查找流程
  • 慢速查找流程,找到后,跳转到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 相关类信息判断
  • 根据所有已知类的列表检查给定的类,有问题直接内部抛出异常。

  • 判断类是否已经被实现,未实现则去实现,这部分后面类的加载篇章会详细分析,主要是按照superclass和isa走向去递归实现父类和元类,同时准备好对象方法和类方法的查找链。

  • 判断类是否被初始化,未初始化则去初始化。

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

调用调用 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 方法

调用 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 方法
  • 如果找到了,进入本方法,调用 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 查找本类的方法列表 如果找不到,就递归查找父类的缓存
  • 调用 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 方法 调用 __objc_msgForward 方法

  • __objc_msgForward 方法 调用 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;

如果方法没有实现,imp 会置换成 forward_imp , forward_imp 最终会走到 __objc_forward_handler 方法 返回 unrecognized selector sent to instance ... 信息,我们查看一下方法没有实现的报错信息会发现,报错信息的模板原来在这。

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

4.8 动态方法决议

在4.7中将 imp 置换成 forward_imp 后,会 break 跳出循环,走到动态方法决议这里:

 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 方法`
  • 我们发现在 resolveInstanceMethod 方法 中将 IMP imp = lookUpImpOrNil(inst, sel, cls); ,所以我们跳进 lookUpImpOrNil 方法 看一下会发现又回到了 lookUpImpOrForward 方法 ,那对之前做了什么产生了好奇。

  • 往上走我们发现有下面两行代码
    BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend; bool resolved = msg(cls, resolve_sel, sel);

  • 如果我们实现 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 动态方法决议实现
#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 ,本类没有找到就会去递归的去父类当中查找。
  • 如果本类和父类都没有找到,就会进行动态方法决议 _class_resolveMethod ,这是苹果爸爸给我们的最后的机会。

最终到 _objc_forward_handler 方法 崩溃报错 unrecognized selector sent to instance ...。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容