iOS Runtime02 - 方法查找流程分析

iOS Runtime02 - 方法查找流程分析

技术杂谈小彩虹2021-07-11 1:43:2190A+A-

前沿

即上一遍objc_msgSend消息发送初探原理,本编重点探索方法查找流程,若有理解不到位请各位大大指出谢谢。下面开始方法查找探索之路: 总所周知:方法查找可以分,快速查找慢速查找

慢速查找流程

首先准备探索方法断点如图所示: 并且开启汇编调试【Debug -- Debug worlflow -- 勾选Always show Disassembly】,运行程序,注意在不使用此调试模式下请去掉勾选项,那么会出现意想不到的彩蛋。程序运行至断点处,在汇编代码中objc_msgSend处添加断点,如图所示 通过按住control + stepinto,进入objc_msgSend的汇编,找到_objc_msgSend_uncached,如图所示会进入C/C++方法实现中。 再次按住control + stepinto,进入_objc_msgSend_uncached的汇编

慢速查找C/C++实现部分

在源代码项目中全局搜索lookUpImpOrForward方法,其实在上图中已经指出了该方法的实现文件在objc-runtime-new.mm:6095处。

IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
    const IMP forward_imp = (IMP)_objc_msgForward_impcache;
    IMP imp = nil;
    Class curClass;

    runtimeLock.assertUnlocked();

    // Optimistic cache lookup
    if (fastpath(behavior & LOOKUP_CACHE)) {
        imp = cache_getImp(cls, sel);
        if (imp) goto done_nolock;
    }

    // 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();

    // We don't want people to be able to craft a binary blob that looks like
    // a class but really isn't one and do a CFI attack.
    //
    // To make these harder we want to make sure this is a class that was
    // either built into the binary or legitimately registered through
    // objc_duplicateClass, objc_initializeClassPair or objc_allocateClassPair.
    //
    // TODO: this check is quite costly during process startup.
    checkIsKnownClass(cls);

    if (slowpath(!cls->isRealized())) {
        cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
        // runtimeLock may have been dropped but is now locked again
    }

    if (slowpath((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized())) {
        cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
        // runtimeLock may have been dropped but is now locked again

        // 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
    }

    runtimeLock.assertLocked();
    curClass = cls;

    // The code used to lookpu the class's cache again right after
    // we take the lock but for the vast majority of the cases
    // evidence shows this is a miss most of the time, hence a time loss.
    //
    // The only codepath calling into this without having performed some
    // kind of cache lookup is class_getInstanceMethod().

    for (unsigned attempts = unreasonableClassCount();;) {
        // curClass method list.
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp;
            goto done;
        }

        if (slowpath((curClass = curClass->superclass) == nil)) {
            // No implementation found, and method resolver didn't help.
            // Use forwarding.
            imp = forward_imp;
            break;
        }

        // Halt if there is a cycle in the superclass chain.
        if (slowpath(--attempts == 0)) {
            _objc_fatal("Memory corruption in class list.");
        }

        // Superclass cache.
        imp = cache_getImp(curClass, sel);
        if (slowpath(imp == forward_imp)) {
            // Found a forward:: entry in a superclass.
            // Stop searching, but don't cache yet; call method
            // resolver for this class first.
            break;
        }
        if (fastpath(imp)) {
            // Found the method in a superclass. Cache it in this class.
            goto done;
        }
    }

    // No implementation found. Try method resolver once.

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

 done:
    log_and_fill_cache(cls, imp, sel, inst, curClass);
    runtimeLock.unlock();
 done_nolock:
    if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
        return nil;
    }
    return imp;
}

流程图如下: 步骤如下:

1->cache_getImp进入快速在缓存中查找,若是找到返回直接方法相应的imp,没找到进入步骤:2

2->checkIsKnownClass先判断是否是已知类, -> 则报错 -> 在判断类是否实现,如果没有,则需要先实现,确定其父类链,此时实例化的目的是为了确定父类链,方法后续的循环 是否初始化,如果没有,则初始化

3->for循环,依次按照类继承链 或者 元类继承链的顺序查找. getMethodNoSuper_nolock,使用二分查找算法查找方法,并返回imp,如果没有找到,则返回nil

当前curClass类被赋值为(curClass = curClass->superclass) == nil)父类,

如果父类等于nil,则imp = 消息转发,并终止递归,进入 4

父类缓存中查找方法

如果找到,则直接返回imp,执行cache_fill写入流程

没找到->返回nil,继续循环查找

4->判断是否执行过动态方法解析 slowpath(behavior & LOOKUP_RESOLVER) ,条件流程只执行一次

但是苹果会给出一次补救的机会查找 如果还是没找到则会报错

消息转发流程!

以上就是方法慢速查找流程。

点击这里复制本文地址 以上内容由权冠洲的博客整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

支持Ctrl+Enter提交

联系我们| 本站介绍| 留言建议 | 交换友链 | 域名展示
本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除

权冠洲的博客 © All Rights Reserved.  Copyright quanguanzhou.top All Rights Reserved
苏公网安备 32030302000848号   苏ICP备20033101号-1

联系我们