iOS objc_msgsend流程分析(二)

概述

接着上一篇文章,我们继续探索消息发送的后续流程

消息转发(报错)

通过上一篇文章发现,都找不到的时候会返回一个forward_imp,
通过源码发现找到_objc_msgForward_impcache

 const IMP forward_imp = (IMP)_objc_msgForward_impcache;

源码搜索objc_msgForward_impcache

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

然后会跳转objc_msgForward

知识补充:adrp 通过基地址 + 偏移 获得一个字符串(全局变量)
继续查找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;

这里我们看到了一个iOS开发人员都熟知的报错提示 unrecognized selector sent to instance,对就是它

方法动态解析

当然如果imp没有找到实现,系统还不会直接立马报错,还会寻找解析的机会,继续阅读lookimporforward还会发现如下代码:

    // No implementation found. Try method resolver once.

    if (slowpath(behavior & LOOKUP_RESOLVER)) {
        behavior ^= LOOKUP_RESOLVER;
        return resolveMethod_locked(inst, sel, cls, behavior);
    }

注释:如果没有实现,会尝试一次方法解析
继续查看resolveMethod_locked

static NEVER_INLINE IMP
resolveMethod_locked(id inst, SEL sel, Class cls, int behavior){
...
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 (!lookUpImpOrNilTryCache(inst, sel, cls)) {
            resolveInstanceMethod(inst, sel, cls);
        }
    }
...
}
  • 如果是实例方法会先调用resolveInstanceMethod,看实例方法,有没有实现
  • 进入resolveClassMethod方法,发现其与resolveInstanceMethod实现十分相似;不同地方在于resolveInstanceMethod里边需要类中实现一个类方法resolveInstanceMethod,而resolveClassMethod是需要在元类里实现一个对象方法resolveClassMethod,因为类方法在元类中都是以对象方法的形式存在的;那么如何在元类中实现一个对象方法呢?只需要在当前类中实现类方法resolveClassMethod即可:
实例方法动态实现:
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
    if (sel == @selector(teacherSay)) {
       // return YES;
        IMP r_teacherSay = class_getMethodImplementation(self, @selector(r_teacherSay));
        Method method = class_getInstanceMethod(self, @selector(r_teacherSay));
        const char *type = method_getTypeEncoding(method);
        
        return  class_addMethod(self, sel, r_teacherSay, type);
    }
    return NO;
}
- (void)r_teacherSay
{
    NSLog(@"%s",__func__);
}
类方法动态解析实现
+ (BOOL)resolveClassMethod:(SEL)sel
{
    if (sel == @selector(sayNB)) {
        IMP r_teacherSay = class_getMethodImplementation(objc_getMetaClass("QHTeacher"), @selector(r_sayNB));
        Method method = class_getInstanceMethod(self, @selector(r_sayNB));
        const char *type = method_getTypeEncoding(method);
        
        return  class_addMethod(objc_getMetaClass("QHTeacher"), sel, r_teacherSay, type);
    }
    
    return NO;
}
+ (void)r_sayNB
{
    NSLog(@"%s",__func__);
}

通过上面的源码我们发现,调用类方法的resolveClassMethod后有调用了resolveInstanceMethod,通过这个源码和isa分析,我们可以得出一个结论,无论是调用类方法还是实例方法,最终都会调用resolveInstanceMethod方法。这样我们就可以通过实现一个NSObject的分类,然后通过实现+ (BOOL)resolveInstanceMethod:(SEL)sel,来处理所有的异常。而不用再每个类里面都去添加。

instrumentObjcMessageSends引出方法

lookUpImpOrForward这个方法里面找到imp后会调用log_and_fill_cache这个方法,改方法会通过objcMsgLogEnabled来控制是否打印msg日志,全局搜索objcMsgLogEnabled,这个参数会由instrumentObjcMessageSends这个外部函数来控制:

extern void instrumentObjcMessageSends(BOOL flag);
int main(int argc, const char * argv[]) {
    @autoreleasepool {

        QHPerson *person = [QHPerson alloc];
        instrumentObjcMessageSends(YES);
        [person sayHello];
        instrumentObjcMessageSends(NO);


        NSLog(@"Hello, World!");
    }
    return 0;
}
```objectivec
在看看打印的方法```logMessageSend```,
```objectivec
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;
        }
    }

发现日志会保存到/tmp/目录下,如下图:

日志.png

消息快速转发forwardingTargetForSelector

通过上面的日志发现调用了forwardingTargetForSelector,发现在源码里面也没有找到该方法,那么查看一下苹果文档


转发.png

翻译:如果一个对象实现(或继承)这个方法,并返回一个非nil(非self)结果,那么返回的对象将被用作新的接收方对象,消息调度将恢复到这个新对象(显然,如果您从这个方法返回self,代码将落入一个无限循环。)
代码展示:

QHPerson *p = [QHPerson alloc];
[p sayHello];

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    return [QHTeacher alloc];
}

将p对象里面没有实现的方法转发给QHTeacher对象

消息慢速转发forwardingTargetForSelector

慢速转法.png

翻译:返回一个NSMethodSignature对象,该对象包含由给定选择器标识的方法的描述
该方法会关联一个forwardInvocation方法

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    if (aSelector == @selector(sayHello)) {
        
        return  [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }
    return  [super methodSignatureForSelector:aSelector];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    
    NSLog(@"%@-%@",anInvocation.target,NSStringFromSelector(anInvocation.selector));
    [anInvocation invokeWithTarget:[QHStutent alloc]];
}

forwardInvocation也可以不用处理,程序也不会出现崩溃,但是也耗费程序性能,也不方便快速定位问题

你可能感兴趣的:(iOS objc_msgsend流程分析(二))