美文网首页
消息转发之动态方法决议 & 消息转发

消息转发之动态方法决议 & 消息转发

作者: Y丶舜禹 | 来源:发表于2020-09-27 16:37 被阅读0次

    前言

    前面的两篇文章我们已经探索了消息的快速查找慢速查找的流程。

    objc_msgSend 流程之缓存查找
    objc_msgSend 流程之慢速查找

    总结一下就是:对象接收到消息后 objc_msgSend首先会在对象本类的缓存cache中的方法列表 method list 查找,如果查找不到就会沿着继承链一直向上查找,直到查到nil仍然查不到方法的话,这样的话苹果就会给我们三次挽救的机会,也就是我们这片文章所要讲述的内容----消息转发

    消息转发

    消息转发分成两大阶段。

    • 第一阶段:动态方法解析 dynamic method resolution:先询问当前类,是否动态添加方法并处理这个未知的 selector,如果接收者没有动态添加方法或者动态添加的方法依然不能处理这个未知的 selector,则当前接收者自己就没有办法通过动态新增方法的手段来响应这个 selector了,之后就进入消息转发的第二阶段。

    • 第二阶段可以分成快速转发慢速转发
      快速转发: 查看是否存在其他备选对象能处理这条消息(就像是备胎一样),如果有,则这个处理消息的对象叫备援接收者 replacement receiverruntime系统会把消息转发给这个对象,由这个对象进行处理。
      慢速转发:如果连replacement receiver都没有,则启动完整的消息转发,runtime系统会把和消息有关的所有信息都放进NSInvocation对象中,再给接收者一次机会,处理未知的 selector,如果这一步都失败了,就会抛出unrecognize selector send to instance xxx这个异常。

    而消息转发的过程就是苹果给我们的三次拯救的机会

    • 动态方法解析 Method resolution
    • 快速转发 Fast forwarding
    • 完整消息转发 Normal forwarding
    动态方法解析 Method resolution

    其源码如下:

    // No implementation found. Try method resolver once.
    
    if (slowpath(behavior & LOOKUP_RESOLVER)) {
      behavior ^= LOOKUP_RESOLVER;
      return resolveMethod_locked(inst, sel, cls, behavior);
    }
    
    ...分割线
    
    static NEVER_INLINE IMP
    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
        //resolver很可能已经填充了缓存,再试一次缓存
        return lookUpImpOrForward(inst, sel, cls, behavior | LOOKUP_CACHE);
    }
    
    

    这里实例方法会调用resolveInstanceMethod,类方法会调用resolveClassMethod,这里有一点疑问,类方法在调用了resolveClassMethod之后,又调用了一下resolveInstanceMethod,这是为什么呢?原来是因为类方法在元类中都是对象方法,所以还是需要查询元类中对象方法

    resolveInstanceMethod

    static void resolveInstanceMethod(id inst, SEL sel, Class cls)
    {
        runtimeLock.assertUnlocked();
        ASSERT(cls->isRealized());
        SEL resolve_sel = @selector(resolveInstanceMethod:);
        // 1\. 判断系统是否实现SEL_resolveInstanceMethod方法
        // 即+(BOOL)resolveInstanceMethod:(SEL)sel,
        // 继承自NSObject的类,默认实现,返回NO
        if (!lookUpImpOrNil(cls, resolve_sel, cls->ISA())) {
            // Resolver not implemented.
            // 不是NSObject的子类,也未实现+(BOOL)resolveInstanceMethod:(SEL)sel,
            // 直接返回,没有动态解析的必要
            return;
        }
        //系统给你一次机会 - 你要不要针对 sel 来操作一下下
        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 imp = lookUpImpOrNil(inst, sel, cls);
        // 只有这用了resolved, 所以返回NO或YES不影响forward
        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));
            }
        }
    }
    
    

    resolveClassMethod

    static void resolveClassMethod(id inst, SEL sel, Class cls)
    {
        runtimeLock.assertUnlocked();
        ASSERT(cls->isRealized());
        ASSERT(cls->isMetaClass());
    
        if (!lookUpImpOrNil(inst, @selector(resolveClassMethod:), cls)) {
            // Resolver not implemented.
            return;
        }
    
        Class nonmeta;
        {
            mutex_locker_t lock(runtimeLock);
            nonmeta = getMaybeUnrealizedNonMetaClass(cls, inst);
            // +initialize path should have realized nonmeta already
            if (!nonmeta->isRealized()) {
                _objc_fatal("nonmeta class %s (%p) unexpectedly not realized",
                            nonmeta->nameForLogging(), nonmeta);
            }
        }
        BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
        bool resolved = msg(nonmeta, @selector(resolveClassMethod:), sel);
    
        // Cache the result (good or bad) so the resolver doesn't fire next time.
        // +resolveClassMethod adds to self->ISA() 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 resolveClassMethod:%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));
            }
        }
    }
    

    由此:我们可以在+(BOOL)resolveInstanceMethod:(SEL)sel方法中对未实现的方法指定已实现方法的IMP,并添加到类中,实现方法动态解析,防止系统崩溃

    这里我们在上篇文章已经验证过了,这里就不再验证了,另外类方法的动态解析有些许不一样,需要在元类中resolveInstanceMethod,感兴趣的同学可以自己尝试一下哦,实践出真知嘛。

    快速转发 Fast forwarding

    如果动态决议也不能正确的处理方法,那么就会进入到消息转发,这是苹果给我们第二次挽救的机会,但是,我们找遍了源码也没有发现消息转发的相关源码,所以接下来我们转换思维,通过instrumentObjcMessageSends函数看看方法崩溃前都走了哪些方法?

    instrumentObjcMessageSends介绍

    instrumentObjcMessageSends是苹果提供的一个方法,它可以打印出方法调用的日志,下面我们使用一下。

    在源码中通过lookUpImpOrForward --> log_and_fill_cache --> logMessageSend,logMessageSend源码下方找到instrumentObjcMessageSends的源码实现,所以,在main中调用
    instrumentObjcMessageSends打印方法调用的日志信息,有以下两点准备工作:

    • 打开 objcMsgLogEnabled 开关,即调用instrumentObjcMessageSends方法时,传入YES,结束传NO
    • main中通过extern 声明instrumentObjcMessageSends方法,然后在sayHello方法打上断点,运行
    #import "ZGPerson.h"
    extern void instrumentObjcMessageSends(BOOL flag);
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            // insert code here...
            ZGPerson *person = [ZGPerson alloc];
            instrumentObjcMessageSends(YES);
            [person sayHello];
            instrumentObjcMessageSends(NO);
    
        }
        return 0;
    }
    

    我们在logMessageSend的源码中发现,打印的日志储存在/tmp/msgSends-%d文件路径中

    bool logMessageSend(bool isClassMethod,
                        const char *objectsClass,
                        const char *implementingClass,
                        SEL selector)
    {
        char    buf[ 1024 ];
    
        // Create/open the log file
        if (objcMsgLogFD == (-1))
        {
            snprintf (buf, sizeof(buf), "/tmp/msgSends-%d", (int) getpid ());
            objcMsgLogFD = secure_open (buf, O_WRONLY | O_CREAT, geteuid());
            if (objcMsgLogFD < 0) {
                // no log file - disable logging
                objcMsgLogEnabled = false;
                objcMsgLogFD = -1;
                return true;
            }
        }
    
    

    我们去查看发现多了一个msgSends文件


    msgSends文件

    因为我们只声明而没有实现sayHello,所有程序崩溃了,不过崩溃之前打印出了方法的调用顺序。

    main

    我们查看msgSends文件

    msgSends文件

    我们发现了崩溃前的调用

    • 两次动态方法决议resolveInstanceMethod方法
    • 两次消息快速转发forwardingTargetForSelector方法
    • 两次消息慢速转发methodSignatureForSelector + resolveInstanceMethod

    接下来我们尝试在快速转发方法forwardingTargetForSelector中处理一下引起崩溃的方法
    我们新建一个ZGStudent类,并在其中实现sayHello方法

    @interface ZGStudent : NSObject
    - (void)sayHello;
    @end
    
    @implementation ZGStudent
    - (void)sayHello{
        NSLog(@"%s",__func__);
    }
    
    @end
    

    接着在ZGPerson.m中将消息的接收者指定为ZGStudent,在ZGStudent中查找sayHello的实现

    #import "ZGPerson.h"
    #import "ZGStudent.h"
    
    @implementation ZGPerson
    
    // 1: 快速转发
    
    - (id)forwardingTargetForSelector:(SEL)aSelector{
        NSLog(@"%s - %@",__func__,NSStringFromSelector(aSelector));
         //将消息的接收者指定为ZGStudent,在ZGStudent中查找sayHello的实现
        // runtime + aSelector + addMethod + imp
         return [ZGStudent alloc];
    }
    @end
    

    发现程序已经能够正常运行


    ZGStudent sayHello

    注意:
    如果快速转发中指定的对象,仍然没有实现被转发的方法的话,程序依然会报unrecognized selector sent to instance ...的错误

    完整消息转发 Normal forwarding

    如果在快速转发中依然无法正确的对方法进行处理,则进入最后的一次挽救机会,即完整消息转发 Normal forwarding

    接下来我们尝试在ZGPerson中尝试完整消息转发 Normal forwarding
    ,启动完整的消息转发机制时,运行期系统会把与消息有关的全部细节都封装到NSInvocation对象中,再给接收者最后一次机会,令其设法解决当前还未处理的这条消息。所以,需要配合 forwardInvocation:方法 搭配使用:

    注意:
    v@:* : 这里第一字符v代表函数返回类型void,第二个字符@代表self的类型id,第三个字符:代表_cmd的类型SEL。这些符号可在Xcode中的开发者文档中搜索Type Encodings就可看到符号对应的含义,更详细的官方文档传送门 Type Encodings,此处不再列举了。

    #import "ZGPerson.h"
    #import "ZGStudent.h"
    
    @implementation ZGPerson
    
    // 1: 快速转发
    //
    //- (id)forwardingTargetForSelector:(SEL)aSelector{
    //    NSLog(@"%s - %@",__func__,NSStringFromSelector(aSelector));
    //
    //    // runtime + aSelector + addMethod + imp
    //     return [super forwardingTargetForSelector:aSelector];
    ////     return [ZGStudent alloc];
    //}
    //
    //
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{
        NSLog(@"%s - %@",__func__,NSStringFromSelector(aSelector));
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    //    return nil;
    }
    
    - (void)forwardInvocation:(NSInvocation *)anInvocation{
        NSLog(@"%s - %@",__func__,anInvocation);
        // GM  sayHello - anInvocation - 漂流瓶 - anInvocation
        anInvocation.target = [ZGStudent alloc];
        // anInvocation 保存 - 方法
        [anInvocation invoke];
    }
    
    

    总结

    到目前为止,objc_msgSend发送消息的流程就分析完成了,在这里简单总结下

    • 【快速查找流程】首先,在类的缓存cache中查找指定方法的实现

    • 【慢速查找流程】如果缓存中没有找到,则在类的方法列表中查找,如果还是没找到,则去父类链的缓存和方法列表中查找

    • 【动态方法决议】如果慢速查找还是没有找到时,第一次补救机会就是尝试一次动态方法决议,即重写resolveInstanceMethod/resolveClassMethod 方法

    • 【消息转发】如果动态方法决议还是没有找到,则进行消息转发,消息转发中有两次补救机会:快速转发+慢速转发

    • 如果转发之后也没有,则程序直接报错崩溃unrecognized selector sent to instance

    相关文章

      网友评论

          本文标题:消息转发之动态方法决议 & 消息转发

          本文链接:https://www.haomeiwen.com/subject/wvzzyktx.html