美文网首页
iOS runtime方法查找流程

iOS runtime方法查找流程

作者: 如意神王 | 来源:发表于2019-05-14 20:35 被阅读0次

    1.objc_msgSend探索 和 方法查找流程
    OC的方法调用在编译的时候实际上就是消息发送,如下
    Person * p = [Person alloc] init];
    [p test];
    objc_msgSend(p, sel),sel 是方法编号,字符串,选择子,
    sel 地址打印方法 p (void *)@selector(test),打印结果(void *)$X=0x.....
    当前的接受者是谁-p,消息是什么-sel

    主要汇编函数调用顺序,这个不是重点
    _objc_msgSend_uncached->_class_lookupMethodAndLoadChache3(id,SEL,Class)

    runtime核心源码起始函数 _class_lookupMethodAndLoadChache3
    _class_lookupMethodAndLoadChache3-> lookUpImpOrForward
    _class_lookupMethodAndLoadChache3到这里就到了runtime里面的核心源码,如下函数所示,lookUpImpOrForward这个方法是runtime 里面方法查找的核心逻辑和流程

    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;
    

    }

    类的结构体如下
    struct objc_class {
    Class _Nonnull isa OBJC_ISA_AVAILABILITY;

    if !OBJC2

    Class _Nullable super_class                              OBJC2_UNAVAILABLE;
    const char * _Nonnull name                               OBJC2_UNAVAILABLE;
    long version                                             OBJC2_UNAVAILABLE;
    long info                                                OBJC2_UNAVAILABLE;
    long instance_size                                       OBJC2_UNAVAILABLE;
    struct objc_ivar_list * _Nullable ivars                  OBJC2_UNAVAILABLE;
    struct objc_method_list * _Nullable * _Nullable methodLists                    OBJC2_UNAVAILABLE;
    struct objc_cache * _Nonnull cache                       OBJC2_UNAVAILABLE;
    struct objc_protocol_list * _Nullable protocols          OBJC2_UNAVAILABLE;
    

    endif

    } OBJC2_UNAVAILABLE;

    核心逻辑1,查找方法缓存区
    查找方法缓存cache_getImp,返回imp,参数cls, sel
    与之对应的是查找类结构体的这个散列表 struct objc_cache * _Nonnull cache OBJC2_UNAVAILABLE;

    runtime查找方法缓存1.png

    核心代码2 查找方法列表
    struct objc_method_list * _Nullable * _Nullable methodLists
    getMethodNoSuper_nolock 参数 cls, sel 返回值 Method
    log_and_fill_cache 如果找到将方法的sel,即meth->imp,保存在缓存区,我们可以看到在查询方法列表之前再次查询了缓存
    objc_cache

    runtime查找方法缓存和方法列表查找.png

    上面查找缓存列表和方法列表都是通过对象的或者类的isa,找到对应的类或者元类,然后查找里面的方法,那么如何实现父类逐级查找以上两个方法列表的呢?通过循环遍历移动cls 指针的指向,再重复上面两个步骤


    runtime for循环逐级遍历父类.png

    通过for循环 修改临时变量curClass的指向,直到没有父类位置,然后每一级父类分别调用上面的两个方法cache_getImp和getMethodNoSuper_nolock

    那么cache_getImp和getMethodNoSuper_nolock内部实现是什么,cache_getImp没有开源,getMethodNoSuper_nolock开源代码如下图所示

    getMethodNoSuper_nolock函数.png

    search_method_list 循环遍历查找方法列表

    本类的和逐级父类的cache和methodList里面如果都没有找到对应的方法,iOS系统在崩溃之前给了我们三次挽救的机会
    第1次,动态决议,动态解析,本类中和逐级父类中是否实现了为找不到的sel添加了动态的对象方法或者类方法?

    runtime本类中尝试动态解析.png

    _class_resolveMethod(cls, sel, inst); 这个方法里面解析了对象方法和类方法,代码如图所示


    runtime动态解析内部实现.png

    相关文章

      网友评论

          本文标题:iOS runtime方法查找流程

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