美文网首页
objc_msgSend消息查找流程分析

objc_msgSend消息查找流程分析

作者: 半边枫叶 | 来源:发表于2019-12-29 19:20 被阅读0次

在开始介绍objc_msgSend之前,我们首先得链接runtime。OC中的runtime是什么呢?
runtime是一套api, 使用C、C++和汇编编写,为OC提供运行时环境的api。
runtime有两个版本,Legacy(过时版本)和Modern(当前版本)。

我们在直接调用OC对象的方法时,OC底层是怎么找到方法的实现进行调用的呢?例如main.m文件里面的一段代码:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        LGPerson *person = [LGPerson alloc];
        [person sayNB];
    }
    return 0;
}

我们可以使用clang命令查看下源码实现:
使用命令行切换到对应main.m目录下,然后输入命令
clang -rewrite-objc main.m
就可以得到对应的main.cpp文件,也就是对应的C++实现文件。在C++文件中我们可以找到对应的实现:

int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        LGPerson *person = ((LGPerson *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("LGPerson"), sel_registerName("alloc"));
        ((void (*)(id, SEL))(void *)objc_msgSend)((id)person, sel_registerName("sayNB"));
    }
    return 0;
}

可以看出[person sayNB];的实现就是调用objc_msgSend,接受两个参数,一个是调用方法的对象,另外一个是对应的方法。
我们在main.m文件中添加另外一个方法run(),然后在main函数中调用。

void run(){
    NSLog(@"%s",__func__);
}
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        LGPerson *person = [LGPerson alloc];
        [person sayNB];
        
        run();
    }
    return 0;
}

run()方法会不会走objc_msgSend呢?我们重新使用clang命令跑下,结果如下:

int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        LGPerson *person = ((LGPerson *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("LGPerson"), sel_registerName("alloc"));
        ((void (*)(id, SEL))(void *)objc_msgSend)((id)person, sel_registerName("sayNB"));
        
        run();
    }
    return 0;
}

可以看出,run()的调用并没有走消息发送。因为run()是C语言函数,可以直接找到C实现,不像OC对象的方法,需要通过消息发送来寻找方法的实现函数。
到这里,我们知道了OC方法的调用是通过objc_msgSend来实现的,下面我们开始研究objc_msgSend。
OC方法的调用分为:实例方法调用、类方法调用、调用父类的实例方法、调用父类的类方法几种,代码如下:

        LGStudent *s = [LGStudent new];
        [s sayCode];
        // 方法调用底层编译
        // 方法的本质: 消息 : 消息接受者 消息编号 ....参数 (消息体)
        objc_msgSend(s, sel_registerName("sayCode"));
        
        // 类方法编译底层
        objc_msgSend(objc_getClass("LGStudent"), sel_registerName("sayNB"));

        // 向父类发消息(对象方法)
        struct objc_super lgSuper;
        lgSuper.receiver = s;
        lgSuper.super_class = [LGPerson class];
        objc_msgSendSuper(&lgSuper, @selector(sayHello));

        //向父类发消息(类方法)
        struct objc_super myClassSuper;
        myClassSuper.receiver = [s class];
        myClassSuper.super_class = class_getSuperclass(object_getClass([s class]));// 元类
        objc_msgSendSuper(&myClassSuper, sel_registerName("sayNB"));

Objc_msgSend流程
Objc_msgSend中的快速流程

Objc_msgSend中的快速流程(也就是查找类中缓存方法的流程)是用汇编写的,为什么是汇编,而不是C语言或者C++语言呢?
第一,因为汇编的速度更快;
第二,C和C++都是静态语言,不能通过写一个函数来保留未知的参数并且跳转到任意的函数指针。
如果快速流程没有在缓存中找到函数的话,就会走慢速流程,慢速流程是C语言实现的。

objc_msgSend的慢速流程

使用汇编在缓存中如果没有找到方法的话,就会进入慢速C语言实现的慢速流程查找。慢速流程主要做了哪些事情呢?主要包括查找类中的方法列表,查找父类的方法列表,进行消息转发等一系列的流程。
在快速方法流程中我们得到,汇编代码中调用了C语言方法:
_class_lookupMethodAndLoadCache3
我们在源码中从这个方法开始入手进行跟踪。

IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
    return lookUpImpOrForward(cls, sel, obj, 
                              YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}
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) {
        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.lock();
    checkIsKnownClass(cls);

    if (!cls->isRealized()) {
        realizeClass(cls);
    }

    if (initialize  &&  !cls->isInitialized()) {
        runtimeLock.unlock();
        _class_initialize (_class_getNonMetaClass(cls, inst));
        runtimeLock.lock();
        // 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.assertLocked();

    // Try this class's cache.

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

    // Try this class's method lists.
    {
        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.
    {
        unsigned attempts = unreasonableClassCount();
        for (Class curClass = cls->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.
            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;
                }
                else {
                    // Found a forward:: entry in a superclass.
                    // Stop searching, but don't cache yet; call method 
                    // resolver for this class first.
                    break;
                }
            }
            
            // Superclass method list.
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
                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.unlock();
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.lock();
        // 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.unlock();

    return imp;
}

首先通过cache_getImp来查找缓存,如果有缓存直接返回。
然后调用了getMethodNoSuper_nolock方法,从类中的methodList查找该方法,这里使用了二分查找。如果找到了该方法就会调用log_and_fill_cache进行缓存处理。
进入log_and_fill_cache方法

log_and_fill_cache(Class cls, IMP imp, SEL sel, id receiver, Class implementer)
{
#if SUPPORT_MESSAGE_LOGGING
    if (objcMsgLogEnabled) {
        bool cacheIt = logMessageSend(implementer->isMetaClass(), 
                                      cls->nameForLogging(),
                                      implementer->nameForLogging(), 
                                      sel);
        if (!cacheIt) return;
    }
#endif
    cache_fill (cls, sel, imp, receiver);
}

可以发现,此处的cache_fill方法,就是将方法进行缓存到cachet_t的方法。

如果在类中找不到的话,就会去父类中查找。
先查找父类的cache缓存中有没有,如果找到的话,将该方法缓存到自己的catche中。然后返回该方法。
父类缓存中没找到就会去父类的methodList中查找。如果找到就缓存、返回。
如果找不到的就继续找父类的父类。
如果一直查找到NSObject都没有找到该方法,就会调用_objc_msgForward_impcache,查找该方法的实现,定位到了汇编里面。然后汇编里面又调用了C方法_objc_forward_handler,

void *_objc_forward_handler = (void*)objc_defaultForwardHandler;
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);
}

最后定位到了未实现方法的报错。

相关文章

网友评论

      本文标题:objc_msgSend消息查找流程分析

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