美文网首页OC底层
OC方法调用 objc_msgSend 流程(中)

OC方法调用 objc_msgSend 流程(中)

作者: H丶ym | 来源:发表于2020-10-09 15:39 被阅读0次

OC底层原理学习

本章主要探索 慢速查找

分析cache_t 时,我们发现调用方法后,插入缓存时的桟信息里面的__objc_msgSend_uncached方法

在上一章分析流程中,也得到了找不到缓存后,会来到__objc_msgSend_uncached这个方法,这一章来分析一下这个方法

全局搜索__objc_msgSend_uncached,找到它的在arm64下汇编实现

...
STATIC_ENTRY __objc_msgSend_uncached
UNWIND __objc_msgSend_uncached, FrameWithNoSaves

// THIS IS NOT A CALLABLE C FUNCTION
// Out-of-band p16 is the class to search
    
MethodTableLookup // 开始查询方法列表
TailCallFunctionPointer x17

END_ENTRY __objc_msgSend_uncached
...

MethodTableLookup的汇编实现

.macro MethodTableLookup
    
    // push frame
    SignLR
    stp fp, lr, [sp, #-16]!
    mov fp, sp

    // save parameter registers: x0..x8, q0..q7
    ...
    // lookUpImpOrForward(obj, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER)
    // receiver and selector already in x0 and x1
    mov x2, x16
    mov x3, #3
    bl  _lookUpImpOrForward //核心源码

    // IMP in x0
    mov x17, x0
  ...

全局搜索_lookUpImpOrForward找不到实现了,去掉_,搜索lookUpImpOrForward,在objc-runtime-new.mm中找到了它的实现

注:
1、C/C++中调用 汇编 ,去查找汇编时,C/C++调用的方法需要多加一个下划线
2、汇编 中调用 C/C++方法时,去查找C/C++方法,需要将汇编调用的方法去掉一个下划线

lookUpImpOrForward实现

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

    // 快速查找,如果找到则直接返回imp
    //目的:防止多线程操作时,刚好调用函数,此时缓存进来了
    if (fastpath(behavior & LOOKUP_CACHE)) { 
        imp = cache_getImp(cls, sel);
        if (imp) goto done_nolock;
    }
    
    //加锁,目的是保证读取的线程安全
    runtimeLock.lock();
    
    //判断是否是一个已知的类:判断当前类是否是已经被认可的类,即已经加载的类
    checkIsKnownClass(cls); 
    
    //判断类是否实现,如果没有,需要先实现,此时的目的是为了确定父类链,方法后续的循环
    if (slowpath(!cls->isRealized())) { 
        cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
    }

    //判断类是否初始化,如果没有,需要先初始化
    if (slowpath((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized())) { 
        cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
    }

    runtimeLock.assertLocked();
    curClass = cls;

    //----查找类的缓存
    for (unsigned attempts = unreasonableClassCount();;) { 
        //---当前类方法列表(采用二分查找算法),如果找到,则返回,将方法缓存到cache中
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp;
            goto done;
        }
        //当前类 = 当前类的父类,并判断父类是否为nil
        if (slowpath((curClass = curClass->superclass) == nil)) {
            //--未找到方法实现,方法解析器也不行,使用转发
            imp = forward_imp;
            break;
        }

        // 如果父类链中存在循环,则停止
        if (slowpath(--attempts == 0)) {
            _objc_fatal("Memory corruption in class list.");
        }

        // --父类缓存
        imp = cache_getImp(curClass, sel);
        if (slowpath(imp == forward_imp)) { 
            // 如果在父类中找到了forward,则停止查找,且不缓存,首先调用此类的方法解析器
            break;
        }
        if (fastpath(imp)) {
            //如果在父类中,找到了此方法,将其存储到cache中
            goto done;
        }
    }

    //没有找到方法实现,尝试一次方法解析

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

方法查找流程
对象的实例方法->自己有
对象的实例方法->自己没有->找父类的
对象的实例方法->自己没有->父类没有的->找NSObject
对象的实例方法->自己没有->父类没有的->NSObject没有的 - 崩溃

类方法->自己有
类方法->自己没有->找父类的
类方法->自己没有->父类没有的->找NSObject
类方法->自己没有->父类没有的->NSObject没有的 ->NSobjcet的对象方法
类方法->自己没有->父类没有的->NSObject没有的 ->NSobjcet的对象方法也没有的 - 崩溃

这个图不就是isa的走势图么 😆

方法查找必须足够快,苹果在查找时,使用的方法是getMethodNoSuper_nolock->search_method_list_inline->search_method_list_inline,本质二分查找,那他是什么时候排序的呢,猜测是插入时候的那个哈希算法

search_method_list_inline源码

ALWAYS_INLINE static method_t *
findMethodInSortedMethodList(SEL key, const method_list_t *list)
{
    ASSERT(list);

    const method_t * const first = &list->first;
    const method_t *base = first;
    const method_t *probe;
    uintptr_t keyValue = (uintptr_t)key; //key 等于方法名
    uint32_t count;
    //base相当于low,count是max,probe是middle,这就是二分
    for (count = list->count; count != 0; count >>= 1) {
        //从首地址+下标 --> 移动到中间位置(count >> 1 右移1位即 count/2 = 4)
        probe = base + (count >> 1); 
        
        uintptr_t probeValue = (uintptr_t)probe->name;
        
        //如果查找的key的keyvalue等于中间位置(probe)的probeValue,则直接返回中间位置
        if (keyValue == probeValue) { 
            // -- while 平移 -- 排除分类重名方法
            while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
                //排除分类重名方法(方法的存储是先存储类方法,在存储分类---按照先进后出的原则,分类方法最先出,而我们要取的类方法,所以需要先排除分类方法)
                //如果是两个分类,就看谁先进行加载
                probe--;
            }
            return (method_t *)probe;
        }
        
        //如果keyValue 大于 probeValue,就往probe即中间位置的右边查找
        if (keyValue > probeValue) { 
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}

相关文章

网友评论

    本文标题:OC方法调用 objc_msgSend 流程(中)

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