Runtime原理探究(四)—— 刨根问底消息机制

1,601 阅读17分钟

Runtime系列文章

Runtime原理探究(一)—— isa的深入体会(苹果对isa的优化)

Runtime原理探究(二)—— Class结构的深入分析

Runtime原理探究(三)—— OC Class的方法缓存cache_t

Runtime原理探究(四)—— 刨根问底消息机制

Runtime原理探究(五)—— super的本质

Runtime原理探究(六)—— 面试题中的Runtime


  上一篇里面,我们从Classcache_t作为切入点,完善了我们对于OC类对象的认识,而且还详细了解了Runtime的消息发送流程和方法缓存策略,不过对于消息机制这个话题只是热身而已。接下来,本文就从源头开始,完整地来研究Runtime的消息机制

消息机制流程框架

[obj message] ➡️ 消息发送 ➡️ 动态方法解析 ➡️ 消息转发

(一)消息发送

消息发送流程上一篇文章已经分析过,这里再从[obj message]为出发点,从objc源码里进行一次正向梳理。

首先,要查看[obj message]的底层表示,可以通过xcode调试工具调出其汇编代码进行分析,但是这个方法需要你至少有熟练的汇编代码阅读能力,有不少难度。如果把要求降低一点,可以在命令行工具里面通过

xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc xxx.m -o yyy.cpp

生成一个中间代码,这个中间代码基本上都是C或C++代码,阅读起来相对容易。但是需要说明一下,这个中间代码仅作为参考,因为目前xcode编译器已经不使用用这种格式的中间代码的,取而代之的是另一种语法格式的中间代码,但是虽然语法不同,但是实现思路和逻辑大致是相同的,因此老的中间代码还是能够借来参考一下的。

通过上面的命令行操作,[obj message]编译之后的底层表示是

((void (*)(id, SEL))(void *)objc_msgSend)((id)obj, sel_registerName("message"));

去掉类型转换后,简化一下可以表示成

objc_msgSend(obj, sel_registerName("message"));

其中第一个参数obj就是消息接受者,后面的sel_registerName,可以在objc源码中搜到它的函数声明

SEL _Nonnull sel_registerName(const char * _Nonnull str)

很明显这里是根据一个C字符串返回一个SEL,其实就等同于OC里面的@selector()。这两个参数都没什么太大疑问,然后我们来从源码里看一看能否找到objc_msgSend的实现。但最终,你无法在源码里面找到对应的C函数实现,因为在objc源码里面,是通过汇编来实现的,并且对应不同架构有不同的版本,这里我们就关注arm64版本的实现。objc源码中的汇编文件其实objc源码总共也没多少文件,如上图所示,除了msg,还有涉及到block相关的一些内容也是用汇编实现的,还有一个objc-sel-table.s,受限本人知识储备,暂时还解读不了,不过没关系,它跟我们现在讨论的话题不相关。

你或许会疑惑,苹果为什么要用汇编来实现某些函数呢?主要原因是因为对于一些调用频率太高的函数或操作,使用汇编来实现能够提高效率。在汇编源码里面,可以按照下面的方法来定位函数实现 接下来我们开始阅读汇编_objc_msgSend 然后查找一下CacheLookup,看看缓存怎么查询的,注意,这里的NORMAL是参数。CacheLookup流程

如果是命中缓存,找到了方法,那就简单了,直接返回并调用就好了,如果没找,就会进入上图中的__objc_msgSend_uncached __objc_msgSend_uncached中调用了MethodTableLookup image.png我们发现在MethodTableLookup里面,调用了__class_lookupMethodAndLoadCache3函数,而这个函数在当前的汇编代码里面是找不到实现的。你去objc源码进行全局搜索,也搜不到,这里经过大佬指点,如果是一个C函数,在底层汇编里面如果需要调用的话,苹果会为其加一个下划线_,因此上面的的函数删去一个下划线,_class_lookupMethodAndLoadCache3,你就可以在源码里面找到它对应的C函数,它是objc-runtime-new.mm里面的一个C函数


IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
    return lookUpImpOrForward(cls, sel, obj, 
                              YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}

而这个函数里面最终是调用了lookUpImpOrForward函数,从这个函数开始的后面的流程,我在上一篇文章里面已经做过完整解读了,这里不再做详细论述,只将之前的结论贴出来

  • (1) 当一个对象接收到消息时[obj message];,首先根据objisa指针进入它的类对象cls里面。
  • (2) 在objcls里面,首先到缓存cache_t里面查询方法message的函数实现,如果找到,就直接调用该函数。
  • (3) 如果上一步没有找到对应函数,在对该cls的方法列表进行二分/遍历查找,如果找到了对应函数,首先会将该方法缓存到obj的类对象clscache_t里面,然后对函数进行调用。
  • (4) 在每次进行缓存操作之前,首先需要检查缓存容量,如果缓存内的方法数量超过规定的临界值(设定容量的3/4),需要先对缓存进行2倍扩容,原先缓存过的方法全部丢弃,然后将当前方法存入扩容后的新缓存内。
  • (5) 如果在objcls对象里面,发现缓存和方法列表都找不到mssage方法,则通过clssuperclass指针进入它的父类对象f_cls里面
  • (6) 进入f_cls后,首先在它的cache_t里面查找mssage,如果找到了该方法,那么会首先将方法缓存到消息接受者obj的类对象clscache_t里面,然后调用方法对应的函数。
  • (7) 如果上一步没有找到方法,将会对f_cls的方法列表进行遍历二分/遍历查找,如果找到了mssage方法,那么同样,会首先将方法缓存到消息接受者obj的类对象clscache_t里面,然后调用方法对应的函数。需要注意的是,这里并不会将方法缓存到当前父类对象f_cls的cache_t里面。
  • (8) 如果还没找到方法,则会通过f_clssuperclass进入更上层的父类对象里面,按照(6)->(7)->(8)步骤流程重复。如果此时已经到了基类对象NSObject,仍没有找到mssage,则进入步骤(9)
  • (9) 接下来将会转到消息机制的 动态方法解析 阶段消息发送流程

到此,消息发送机制的正向解读就到这里。关于上面的汇编代码,我自己也只是借助相关注释说明,间接挖掘苹果的底层思路,其实汇编里面还有更多的细节,只有你自己亲自读一遍,才会有更跟深的体会和领悟。

(二)动态方法解析

接下来,一起来认识一下方法的动态解析。上面的章节,我们讲到了lookUpImpOrForward函数,这个函数我在之前的文章也具体讨论过了,但是仅仅是解读完了消息发送和方法缓存的内容,这里我先贴出该函数的代码

/***********************************************************************
* lookUpImpOrForward.
* The standard IMP lookup. ------------->⚠️⚠️⚠️标准的IMP查找流程
* initialize==NO tries to avoid +initialize (but sometimes fails)
* cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)
* Most callers should use initialize==YES and cache==YES.
* inst is an instance of cls or a subclass thereof, or nil if none is known. 
*   If cls is an un-initialized metaclass then a non-nil inst is faster.
* May return _objc_msgForward_impcache. IMPs destined for external use 
*   must be converted to _objc_msgForward or _objc_msgForward_stret.
*   If you don't want forwarding at all, use lookUpImpOrNil() instead.
**********************************************************************/
IMP lookUpImpOrForward(Class cls, SEL sel, id inst, 
                       bool initialize, bool cache, bool resolver)
{
    IMP imp = nil;
    bool triedResolver = NO;

    runtimeLock.assertUnlocked();

    // Optimistic cache lookup
    if (cache) {//------------------>⚠️⚠️⚠️查询当前Class对象的缓存,如果找到方法,就返回该方法
        imp = cache_getImp(cls, sel);
        if (imp) return imp;
    }

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

    if (!cls->isRealized()) {//--------------->⚠️⚠️⚠️当前Class如果没有被realized,就进行realize操作
        // Drop the read-lock and acquire the write-lock.
        // realizeClass() checks isRealized() again to prevent
        // a race while the lock is down.
        runtimeLock.unlockRead();
        runtimeLock.write();

        realizeClass(cls);

        runtimeLock.unlockWrite();
        runtimeLock.read();
    }

    if (initialize  &&  !cls->isInitialized()) {//--------->⚠️⚠️⚠️当前Class如果没有初始化,就进行初始化操作
        runtimeLock.unlockRead();
        _class_initialize (_class_getNonMetaClass(cls, inst));
        runtimeLock.read();
        // 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
    }

    
 retry:    
    runtimeLock.assertReading();

    // Try this class's cache.//------------>⚠️⚠️⚠️尝试从该Class对象的缓存中查找,如果找到,就跳到done处返回该方法

    imp = cache_getImp(cls, sel);
    if (imp) goto done;

    // Try this class's method lists.//---------------->⚠️⚠️⚠️尝试从该Class对象的方法列表中查找,找到的话,就缓存到该Class的cache_t里面,并跳到done处返回该方法
    {
        Method meth = getMethodNoSuper_nolock(cls, sel);
        if (meth) {
            log_and_fill_cache(cls, meth->imp, sel, inst, cls);
            imp = meth->imp;
            goto done;
        }
    }

    // Try superclass caches and method lists.------>⚠️⚠️⚠️进入当前Class对象的superclass对象
    {
        unsigned attempts = unreasonableClassCount();
        for (Class curClass = cls->superclass;//------>⚠️⚠️⚠️该for循环每循环一次,就会进入上一层的superclass对象,进行循环内部方法查询流程
             curClass != nil;
             curClass = curClass->superclass)
        {
            // Halt if there is a cycle in the superclass chain.
            if (--attempts == 0) {
                _objc_fatal("Memory corruption in class list.");
            }
            
            // Superclass cache.------>⚠️⚠️⚠️在当前superclass对象的缓存进行查找
            imp = cache_getImp(curClass, sel);
            if (imp) {
                if (imp != (IMP)_objc_msgForward_impcache) {
                    // Found the method in a superclass. Cache it in this class.
                    log_and_fill_cache(cls, imp, sel, inst, curClass);
                    goto done;//------>⚠️⚠️⚠️如果在当前superclass的缓存里找到了方法,就调用log_and_fill_cache进行方法缓存,注意这里传入的参数是cls,也就是将方法缓存到消息接受对象所对应的Class对象的cache_t中,然后跳到done处返回该方法
                }
                else {
                    // Found a forward:: entry in a superclass.
                    // Stop searching, but don't cache yet; call method 
                    // resolver for this class first.
                    break;//---->⚠️⚠️⚠️如果缓存里找到的方法是_objc_msgForward_impcache,就跳出该轮循环,进入上一层的superclass,再次进行查找
                }
            }
            // Superclass method list.---->⚠️⚠️⚠️如过画缓存里面没有找到方法,则对当前superclass的方法列表进行查找
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
            //------>⚠️⚠️⚠️如果在当前superclass的方法列表里找到了方法,就调用log_and_fill_cache进行方法缓存,注意这里传入的参数是cls,也就是将方法缓存到消息接受对象所对应的Class对象的cache_t中,然后跳到done处返回该方法
                log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
                imp = meth->imp;
                goto done;
            }
        }
    }
//**********************✅✅✅消息发送流程结束✅✅✅*************************


//📦📦📦动态方法解析
    // No implementation found. Try method resolver once.//------>⚠️⚠️⚠️如果到基类还没有找到方法,就尝试进行方法解析

    if (resolver  &&  !triedResolver) {
        runtimeLock.unlockRead();
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.read();
        // Don't cache the result; we don't hold the lock so it may have 
        // changed already. Re-do the search from scratch instead.
        triedResolver = YES;
        goto retry;
    }



//📦📦📦消息转发
    // No implementation found, and method resolver didn't help. //------>⚠️⚠️⚠️如果方法解析不成功,就进行消息转发
    // Use forwarding.

    imp = (IMP)_objc_msgForward_impcache;
    cache_fill(cls, sel, imp, inst);

 done:
    runtimeLock.unlockRead();

    return imp;
}

动态方法解析

根据上面代码里面的📦📦📦动态方法解析标记处,我们继续解读消息机制的 动态方法解析阶段。 首先注意一个细节,这里有一个标签triedResolver用来判断是否进行该类是否进行过动态方法解析。如果首次走到这里,triedResolver = NO,当动态方法解析进行过一次之后,会设置triedResolver = YES,这样下次走到这里的时候,就不会再次进行动态方法解析,因为这个流程只需要进行一次就够了,并且实在首次调用一个该类没有实现的方法的时候,才会进行这个流程,仔细体会一下而最后这个goto retry回到的地方是本函数的如下位置这个就是消息发送和缓存查询流程的开始步骤,啥意思呢?就是说经过动态方法解析流程处理过之后(在这个流程我们可以动态给类增加方法【新增的方法会存放在 消息接受者->ISA() 的rw的方法列表里面去】),会重新走一遍缓存查找和消息发送。

下面再继续看一下方法动态解析里面的核心函数_class_resolveMethod(cls, sel, inst);

***********************************************************************
* _class_resolveMethod
* Call +resolveClassMethod or +resolveInstanceMethod.
* Returns nothing; any result would be potentially out-of-date already.
* Does not check if the method already exists.
**********************************************************************/
void _class_resolveMethod(Class cls, SEL sel, id inst)
{
    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]
        _class_resolveInstanceMethod(cls, sel, inst);
    } 
    else {
        // try [nonMetaClass resolveClassMethod:sel]
        // and [cls resolveInstanceMethod:sel]
        _class_resolveClassMethod(cls, sel, inst);
        if (!lookUpImpOrNil(cls, sel, inst, 
                            NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
        {
            _class_resolveInstanceMethod(cls, sel, inst);
        }
    }
}

很明显,if (! cls->isMetaClass()) 这句代码实在判断当前的参数cls是否是一个meta-class对象,也就是说,调用对象方法(-方法)和调用类方法(+方法)过程里面的动态方法解析,走的都是这个方法啊,这里我们先关注对象方法(-方法)的解析处理逻辑。也就是_class_resolveInstanceMethod(cls, sel, inst);,进入它的函数实现如下

static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
{
//---⚠️⚠️⚠️查看cls的meta-class对象的方法列表里面是否有SEL_resolveInstanceMethod函数,
//---⚠️⚠️⚠️也就是看是否实现了+(BOOL)resolveInstanceMethod:(SEL)sel方法
    if (!  lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls, 
                         NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
    {

//---⚠️⚠️⚠️如果没找到,直接返回,
        // Resolver not implemented.
        return;
    }

//---⚠️⚠️⚠️如果找到,则通过objc_msgSend调用一下+(BOOL)resolveInstanceMethod:(SEL)sel方法
//---⚠️⚠️⚠️完成里面的动态增加方法的步骤


//---⚠️⚠️⚠️接下来是一些对解析结果的打印信息
    BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
    bool resolved = msg(cls, SEL_resolveInstanceMethod, 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(cls, sel, inst, 
                             NO/*initialize*/, YES/*cache*/, NO/*resolver*/);

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

动态方法解析的核心步骤完成之后,会一层一层往上返回到lookUpImpOrForward函数,跳到retry标记处,重新查询方法,因为在方法解析这一步,如果对某个目标方法名xxx有过处理,为其动态增加了方法实现,那么再次查询该方法,则一定可以在消息发送阶段被找到并调用。 对于类方法(+方法)的动态解析其实跟上面的过程大致相同,只不过解析的时候调用的+(BOOL)resolveClassMethod:(SEL)sel方法,来完成类方法的动态添加绑定。

小结

首先用图来总结一下动态方法解析

动态方法解析真的有必要吗? 其实这个我觉得没有固定答案,根据个人的理解因人而异,就我个人的肤浅看法,好像除了在面试里面可以增加一点逼格外,实际项目中好像没太多使用场景,因为与其在动态解析步骤里面动态增加方法,还不如直接在类里面实现该方法呢,不知道大家有什么心得体会,欢迎留言交流。

好了,动态方法解析流程解读完毕。

(三)消息转发

经过前两个流程之后,如果还没能找到方法对应的函数,说明当前类已经尽力了,但是确实没有能力处理目标方法,因子只能把方法抛给别人,也就丢给其他的类去处理,因此最后一个流程为什么叫消息转发,顾名思义。 下面,我们来搞定消息转发,入口如下,位于lookUpImpOrForward函数的尾部 从截图中可以看出,消息转发这里直接就是返回了一个(IMP)_objc_msgForward_impcache指针。对源码搜索一下,发现它其实也是一段汇编实现

STATIC_ENTRY __objc_msgForward_impcache

	MESSENGER_START
	nop
	MESSENGER_END_SLOW

	// No stret specialization.
	b	__objc_msgForward

	END_ENTRY __objc_msgForward_impcache

//**************************************************************
	
	ENTRY __objc_msgForward

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

汇编中的调用顺序是这样 _objc_msgForward_impcache->__objc_msgForward->__objc_forward_handler,我们可以尝试搜索一下objc_forward_handler,最终,我们可以在objc-runtime.mm里面可以找到与objc_forward_handler相关的信息

__attribute__((noreturn)) 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;

发现_objc_forward_handler 其实是一个函数指针,指向objc_defaultForwardHandler,但是这个函数只有打印信息,再往下深入,无法看出消息转发更底层的执行逻辑,苹果对此并没有开源。如果想要继续挖掘,就只通过汇编码逆向反推C函数的实现,逆向是一个很大的话题,需要很多知识储备,本文无法展开介绍。 其实,如果消息机制的前两个流程都没命中,进入消息转发阶段,则会调用 __forwarding__函数。这个可以从xcode的打印信息里面验证,如果调用一个没有实现的方法,并且动态解析和消息转发都没有处理,最终打印结果如下 可以看到从底层上来,调用了CF框架的_CF_forwarding_prep_0,然后就调用了___forwarding___。该函数就属于苹果未开源部分,感谢大神MJ老师的分享,以下贴出他为我提供的一份消息转发流程的C函数实现,

int __forwarding__(void *frameStackPointer, int isStret) {
    id receiver = *(id *)frameStackPointer;
    SEL sel = *(SEL *)(frameStackPointer + 8);
    const char *selName = sel_getName(sel);
    Class receiverClass = object_getClass(receiver);

    // 调用 forwardingTargetForSelector:

    if (class_respondsToSelector(receiverClass, @selector(forwardingTargetForSelector:))) {
        id forwardingTarget = [receiver forwardingTargetForSelector:sel];
        if (forwardingTarget && forwardingTarget != receiver) {
            return objc_msgSend(forwardingTarget, sel, ...);
        }
    }

    // 调用 methodSignatureForSelector 获取方法签名后再调用 forwardInvocation
    if (class_respondsToSelector(receiverClass, @selector(methodSignatureForSelector:))) {
        NSMethodSignature *methodSignature = [receiver methodSignatureForSelector:sel];
        if (methodSignature && class_respondsToSelector(receiverClass, @selector(forwardInvocation:))) {
            NSInvocation *invocation = [NSInvocation _invocationWithMethodSignature:methodSignature frame:frameStackPointer];

            [receiver forwardInvocation:invocation];

            void *returnValue = NULL;
            [invocation getReturnValue:&value];
            return returnValue;
        }
    }

    if (class_respondsToSelector(receiverClass,@selector(doesNotRecognizeSelector:))) {
        [receiver doesNotRecognizeSelector:sel];
    }

    // The point of no return.
    kill(getpid(), 9);
}

__forwarding__函数逻辑可以简单概括成 forwardingTargetForSelector:->methodSignatureForSelector->forwardInvocation。我在功过一个流程图来解读一下上面的代码消息转发流程

  • -(id)forwardingTargetForSelector:(SEL)aSelector—— __forwarding__首先会看类有没有实现这个方法,这个方法返回的是一个id 类型的转发对象forwardingTarget,如果其不为空,则会通过objc_msgSend函数对其直接发送消息objc_msgSend(forwardingTarget, sel, ...);,也就是说让转发对象forwardingTarget去处理当前的方法SEL。如果forwardingTargetnil,则进入下面的方法
  • -(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector——这个方法是让我们根据方法选择器SEL生成一个NSMethodSignature方法签名并返回,这个方法签名里面其实就是封装了返回值类型,参数类型的信息。 __forwarding__会利用这个方法签名,生成一个NSInvocation,将其作为参数,调用- (void)forwardInvocation:(NSInvocation *)anInvocation方法。如果我们在这里没有返回方法签名,系统则认为我们彻底不想处理这个方法了,就会调用doesNotRecognizeSelector:方法抛出经典的报错报错unrecognized selector sent to instance 0xXXXXXXXX,结束消息机制的全部流程。
  • - (void)forwardInvocation:(NSInvocation *)anInvocation ——如果我们在上面提供了方法签名,__forwarding__则会最终调用这个方法。在这个方法里面,我们会拿到一个参数(NSInvocation *)anInvocation,这个anInvocation其实是__forwarding__对如下三个信息的封装:
    1. anInvocation.target -- 方法调用者
    2. anInvocation.selector -- 方法名
    3. - (void)getArgument:(void *)argumentLocation atIndex:(NSInteger)idx; -- 方法参数 因此在此方法里面,我们可以决定将消息转发给谁(target),甚至还可以修改消息的参数,由于anInvocation会存储消息selector里面带来的参数,并且可以根据消息所对应的方法签名确定消息参数的个数,所以我们通过- (void)setArgument:(void *)argumentLocation atIndex:(NSInteger)idx;可以对参数进行修改。总之你可以按照你的意愿,配置好anInvocation,然后简单一句[anInvocation invoke];即可完成消息的转发调用,也可以不做任何处理,轻轻地来,轻轻地走,但是不会导致程序报错。

至此,Runtime的消息机制就全部梳理完毕~~


🦋🦋🦋传送门🦋🦋🦋

Runtime原理探究(一)—— isa的深入体会(苹果对isa的优化)

Runtime原理探究(二)—— Class结构的深入分析

Runtime原理探究(三)—— OC Class的方法缓存cache_t

Runtime原理探究(四)—— 刨根问底消息机制

Runtime原理探究(五)—— super的本质

Runtime原理探究(六)—— 面试题中的Runtime