iOS - 方法查找流程

在iOS - objc_msgSend分析一文中我们提到了__class_lookupMethodAndLoadCache3方法可以通过,全局搜索找到,那么还有其他的方式能看到_class_lookupMethodAndLoadCache3方法在哪里面呢?下面就介绍另一种方法:

1、通过查看汇编,找到_class_lookupMethodAndLoadCache3
1.1打断点,查看汇编
1.2运行程序,由iOS - objc_msgSend分析一文我们知道,方法的快速查找会进入objc_msgSend方法中,因此我们在此处打断点,按住control点击Step into 进入该方法中;
1.3在_objc_msgSend_uncached出打断点,按住control点击Step into 进入方法中


至此我们完美的看到:_class_lookupMethodAndLoadCache3(id, SEL, Class) at objc-runtime-new.mm:4845证明了_class_lookupMethodAndLoadCache3方法实现在objc-runtime-new.mm文件中.

IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
/**
查找当前的imp或者转发
     cls:如果是实例方法那就是类,如果是类方法那就是元类
     sel:方法名
     obj:方法调用者
     NO/*cache*/ //因为是CheckMiss状态下点用的该方法,所以此处为NO
*/
    return lookUpImpOrForward(cls, sel, obj, 
                              YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}

2、方法查找流程

1.1 lookUpImpOrForward源码分析
/**此处省略部分代码*/

//为查找方法做准备条件,判断类有没有加载好,如果没有加载好,那就先加载一下类信息,准备好父类、元类
    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);//从该类的方法缓存中找imp,明显缓存为NO,此处势必拿不到方法的,因此会继续走接下来的流程
    if (imp) goto done;//拿到方法就返回

    // Try this class's method lists.
    {
        Method meth = getMethodNoSuper_nolock(cls, sel);//在该类中查找该方法
        if (meth) {
//如果找到了则进行方法的缓存, log_and_fill_cache->cache_fill->cache_fill_nolock
            log_and_fill_cache(cls, meth->imp, sel, inst, cls);//进行缓存
            imp = meth->imp;//拿到imp
            goto done;
        }
    }

    // Try superclass caches and method lists.
    {
        unsigned attempts = unreasonableClassCount();
//遍历父类,父类的父类等等一系列父类,直到为nil
        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);//从父类的方法缓存中查找该方法,如果拿到该方法则直接goto done
            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_resolveInstanceMethod
         类方法解析:_class_resolveClassMethod
         */
        _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,下次就不会再进入动态方法解析
        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;
}

getMethodNoSuper_nolock获取方法列表
static method_t *
getMethodNoSuper_nolock(Class cls, SEL sel)
{
    runtimeLock.assertLocked();

    assert(cls->isRealized());
    // fixme nil cls? 
    // fixme nil sel?

    for (auto mlists = cls->data()->methods.beginLists(), 
              end = cls->data()->methods.endLists(); 
         mlists != end;
         ++mlists)
    {
        method_t *m = search_method_list(*mlists, sel);//通过二分查找获取m,此处不做详解,有兴趣的可以自己看下源码
        if (m) return m;
    }

    return nil;
}
_class_resolveMethod
void _class_resolveMethod(Class cls, SEL sel, id inst)
{
//首先会判断cls是不是元类,如果cls不是元类的话,说明调用的是实例方法,那就就会调用_class_resolveInstanceMethod函数,
    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]

        _class_resolveInstanceMethod(cls, sel, inst);
    } 
    else {
//如果是元类的话,说明调用的是类方法,那么就会调用_class_resolveClassMethod函数,
        // 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);
        }
    }
}
_objc_msgForward_impcache
STATIC_ENTRY __objc_msgForward_impcache

    // No stret specialization.
    b   __objc_msgForward //调用__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_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;

这便是我们经常看到的,方法查找不到时所报的错误.

流程总结:

1.对需要的变量进行初始化操作和加锁操作
2.在该类的方法缓存中进行查找,如果找到就就直接goto done;
3.缓存中查找不到时,则从该类的方法列表中进行查找,如果找到,则在缓存中备份一份,方便下次查找,然后goto done;
4.如果该类的方法列表用依旧找不到,则从该类的父类,父类的父类,一直找到NSObject类,依旧是先从父类的缓存中查找,缓存中有则直接goto done,否则就遍历父类的方法列表,如果找到就直接goto done,找不到则break,进行方法决议;
5.实例方法会转发+(BOOL) resolveInstanceMethod:(SEL)sel;类方法会转发+(BOOL) resolveClassMethod:(SEL)sel,并且类方法转发完后会再次走查找流程,如果还没找到的话会走一下实例方法转发流程;转发逻辑完成后,会再次走一下方法查找逻辑
6.如果第一次转发依然后还没找到IMP,那么就会返回_objc_msgForward_impcache方法指针,调用_objc_forward_handler->objc_defaultForwardHandler,报出方法错误

附:方法查找流程图
方法查找流程

你可能感兴趣的:(iOS - 方法查找流程)