Objc_msgSend流程(二)之方法慢速查找

上篇文章Objc_msgSend流程 说到objc_msg_Send快速查找流程,最后调用_lookUpImpOrForward,但是_lookUpImpOrForward在哪里呢?

查找_lookUpImpOrForward

在objc源码工程调用一个方法并在该处新增一个断点,运行工程

断点调试.png

开启菜单栏Debug->Debug Workflow->Always Show Disassembly

Always Show Disassembly.png

objc_msgSend处新增一个断点,让程序运行至断点处

objc_msgSend断点调试.png

按住ctrl,点击step Into,进入objc_msgSend方法调试

step Into.png

objc_msgSend调试中找到_objc_msgSend_uncached,让程序运行至断点处,同样的按住ctrl,点击step Into;

_objc_msgSend_uncached.png

_objc_msgSend_uncached找到发现lookUpImpOrForward位于objc-runtime-new.mm文件

lookUpImpOrForward.png
探索 lookupImpOrForward

找到lookupImpOrForward源码,lookupImpOrForward开始objc_msgSend的慢速查找

if (fastpath(behavior & LOOKUP_CACHE)),增加断点,使代码运行到断点处,并输出参数的值

调试lookupImpOrForward.png
慢速查找流程

查看lookupImpOrForward

  1. 首先查看当前cls是否有SEL的缓存

     if (fastpath(behavior & LOOKUP_CACHE)) {
            imp = cache_getImp(cls, sel);
            if (imp) goto done_nolock;
        }
    
  2. 继续查看是否当前类已知

    checkIsKnownClass(cls);
    //
    static void
    checkIsKnownClass(Class cls)
    {
        if (slowpath(!isKnownClass(cls))) {
            _objc_fatal("Attempt to use unknown class %p.", cls);
        }
    }
    
  3. 查看当前类是否已经实现,若未实现,则对class进行创建,并递归寻找父类及元类的继承链

    realizeClassMaybeSwiftAndLeaveLocked 调用realizeClassMaybeSwiftMaybeRelock调用

    realizeClassWithoutSwift

    if (slowpath(!cls->isRealized())) {
            cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
            // runtimeLock may have been dropped but is now locked again
    }
    
  4. 查看当前类是否已经初始化,若未初始化,则对class进行初始化,并递归寻找父类及元类的继承链;

    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
    }
    
  5. 进行查找

    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;
           }
       }
    
    • Method meth = getMethodNoSuper_nolock(curClass, sel);

      调用search_method_list_inline

      调用findMethodInSortedMethodList(SEL key, const method_list_t *list)进行折半查找。

      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;
      }
      
      • 如果找到方法直接调用log_and_fill_cache,缓存该方法cache_fill(cls, sel, imp, receiver);方便下次直接在缓存中快速查找;
      • 如果未找到,则将superClass赋值给当前的class
    • 从父类中的缓存中查找,

      • 若找到该方法调用log_and_fill_cache,缓存该方法cache_fill(cls, sel, imp, receiver);方便下次直接在缓存中快速查找
      • 如果未找到,则会再次调用_lookupImpOrForward进行递归
    • 若根类未找到该方法,将forward_imp赋值给imp

      if (slowpath((curClass = curClass->superclass) == nil)) {
                 // No implementation found, and method resolver didn't help.
                 // Use forwarding.
                 imp = forward_imp;
                 break;
      }
      
    • 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;
      }
      
  6. forward_imp_objc_msgForward_impcache返回的,那么forward_imp是什么呢?全局搜索找到__objc_msgForward_impcache,找到进入消息转发流程__objc_msgForward,消息转发__objc_forward_handler

    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
    
  7. 那么__objc_forward_handler是什么呢?我们找到__objc_forward_handlerobjc_defaultForwardHandler,而objc_defaultForwardHandler就是我们平常看到的未找到方法的提示语

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