OC底层探索(九)objc_msgSend 流程之方法慢速查找

在上篇文章OC底层探索(八)objc_msgSend 流程之方法快速查找中探索了在cache中查找方法,如果查找命中,一切好说;如果没有查找到那么就会执行慢速查找,并存入缓存中,以便下次查找。

执行慢速查找的时机

  • 在缓存中没有找到需要执行的方法,则会进入__objc_msgSend_uncached,其中的核心是MethodTableLookup(即查询方法列表)
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的汇编实现,其中的核心是_lookUpImpOrForward,汇编源码实现如下
.macro MethodTableLookup
	
	// push frame
	SignLR
	stp	fp, lr, [sp, #-16]!
	mov	fp, sp

	// save parameter registers: x0..x8, q0..q7
	sub	sp, sp, #(10*8 + 8*16)
	stp	q0, q1, [sp, #(0*16)]
	stp	q2, q3, [sp, #(2*16)]
	stp	q4, q5, [sp, #(4*16)]
	stp	q6, q7, [sp, #(6*16)]
	stp	x0, x1, [sp, #(8*16+0*8)]
	stp	x2, x3, [sp, #(8*16+2*8)]
	stp	x4, x5, [sp, #(8*16+4*8)]
	stp	x6, x7, [sp, #(8*16+6*8)]
	str	x8,     [sp, #(8*16+8*8)]

	// 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
	
	// restore registers and return
	ldp	q0, q1, [sp, #(0*16)]
	ldp	q2, q3, [sp, #(2*16)]
	ldp	q4, q5, [sp, #(4*16)]
	ldp	q6, q7, [sp, #(6*16)]
	ldp	x0, x1, [sp, #(8*16+0*8)]
	ldp	x2, x3, [sp, #(8*16+2*8)]
	ldp	x4, x5, [sp, #(8*16+4*8)]
	ldp	x6, x7, [sp, #(8*16+6*8)]
	ldr	x8,     [sp, #(8*16+8*8)]

	mov	sp, fp
	ldp	fp, lr, [sp], #16
	AuthenticateLR

.endmacro
  • 接下来就会执行_looUpImpOrForward,但是在objc-msg-arm64.s文件中没有找到_looUpImpOrForward实现函数;
  • 由于快速查找时由汇编来执行的,那么慢速查找则会有C/C++来实现,那么就需要找函数looUpImpOrForward(汇编 => C/C++ 方法名一样,只会少一个“_”)。

慢速查找

looUpImpOrForward 源码

全局搜索looUpImpOrForward ,我们在objc-runtime-new.mm中查看源码:

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

//part1: 再此去缓存中查找
    // Optimistic cache lookup
    if (fastpath(behavior & LOOKUP_CACHE)) {
        imp = cache_getImp(cls, sel);
        if (imp) goto done_nolock;
    }
    
    runtimeLock.lock();
	//判断是否是一个已知的类:判断当前类是否是已经被认可的类,即已经加载的类
    checkIsKnownClass(cls);
	判断类是否实现,如果没有,需要先实现,
    if (slowpath(!cls->isRealized())) {
    //Part2:确定当前类的继承链和iSA的继承链
        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.assertLocked();
    curClass = cls;

	//死循环
    for (unsigned attempts = unreasonableClassCount();;) {
        // curClass method list.
        //part3:在当前类的methodList中使用二分法查找方法
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp;
            goto done;
        }
		
		//part4: 1.在methodList中没有找到,则将指针指向父类
        if (slowpath((curClass = curClass->superclass) == nil)) {
          
            //part4: 3.如果父类中没有找到方法,则将imp赋值成forwad_imp,死循环结束
            imp = forward_imp;
            break;
        }
        
        if (slowpath(--attempts == 0)) {
            _objc_fatal("Memory corruption in class list.");
        }

        // Superclass cache.
        //part4:2.在父类的缓存中查找方法
        imp = cache_getImp(curClass, sel);
        cache_getImp - lookup - lookUpImpOrForward
        //没有找到方法,死循环结束
        if (slowpath(imp == forward_imp)) {
            break;
        }
        //找到方法 跳转到done
        if (fastpath(imp)) {
            goto done;
        }
    }

	
    if (slowpath(behavior & LOOKUP_RESOLVER)) {
        behavior ^= LOOKUP_RESOLVER;
        //part5:动态方法决议
        return resolveMethod_locked(inst, sel, cls, behavior);
    }

 done:
 //part6:找到方法后,将方法写入缓存,方便下次查找
    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;
}


其整体的流程图:
在这里插入图片描述

解析

part1: 再次查找缓存

  • 在执行过程中有可能多线程调用,所以再次查找一次缓存
 if (fastpath(behavior & LOOKUP_CACHE)) {
        imp = cache_getImp(cls, sel);
        if (imp) goto done_nolock;
    }

part2: 确定当前类的继承链和isa的继承链

  • 确定当前父类,并且递归执行,最终确定继承链
  • 确定元类,并把元类继承链也递归确定下来;
  • initlize时,执行addSubClass(),将子类也存入父类中,从而实现了双向链表
static Class
realizeClassMaybeSwiftAndLeaveLocked(Class cls, mutex_t& lock)
{
    return realizeClassMaybeSwiftMaybeRelock(cls, lock, true);
}
.
.
.
🔽
.
.
.

static Class
realizeClassMaybeSwiftMaybeRelock(Class cls, mutex_t& lock, bool leaveLocked)
{
    lock.assertLocked();

    if (!cls->isSwiftStable_ButAllowLegacyForNow()) {
        // Non-Swift class. Realize it now with the lock still held.
        // fixme wrong in the future for objc subclasses of swift classes
        realizeClassWithoutSwift(cls, nil);
        if (!leaveLocked) lock.unlock();
    } else {
        // Swift class. We need to drop locks and call the Swift
        // runtime to initialize it.
        lock.unlock();
        cls = realizeSwiftClass(cls);
        ASSERT(cls->isRealized());    // callback must have provoked realization
        if (leaveLocked) lock.lock();
    }

    return cls;
}
.
.
.
🔽
.
.
.

static Class realizeClassWithoutSwift(Class cls, Class previously)
{
    runtimeLock.assertLocked();

    ......
   //获取到父类
    supercls = realizeClassWithoutSwift(remapClass(cls->superclass), nil);
    //获取到元类
    metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);
    
	.......
	
#endif

    // Update superclass and metaclass in case of remapping
    //指定父类
    cls->superclass = supercls;
    //指定元类
    cls->initClassIsa(metacls);

    ......
    // Connect this class to its superclass's subclass lists
    if (supercls) {
    //父类中添加当前类,形成环式链表
        addSubclass(supercls, cls);
    } else {
        addRootClass(cls);
    }

    // Attach categories
    methodizeClass(cls, previously);

    return cls;
}

part3: 在当前类的methodList中使用二分法查找方法

  • realizeClassMaybeSwiftAndLeaveLocked函数中查找方法时,是使用二分查找方法,特点:
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;
    uint32_t count;
    
    for (count = list->count; count != 0; count >>= 1) {
        probe = base + (count >> 1);
        
        uintptr_t probeValue = (uintptr_t)probe->name;
        
        if (keyValue == probeValue) {
            // `probe` is a match.
            // Rewind looking for the *first* occurrence of this value.
            // This is required for correct category overrides.
            while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
                probe--;
            }
            return (method_t *)probe;
        }
        
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}

二分法分析
  • list看成[0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80]数量为8的数组;

  • base初始值为0x10

  • count初始值为8

  • keyValue0x70;
    count: 8 7 3
    base: 0x10 0x60
    probe: 0x50 0x70
    value: 0x70 找到0x70

  • keyValue 为0x20;
    count: 8 4 2
    base: 0x10 0x10 0x10
    probe: 0x50 0x30 0x20
    value: 0x20 找到0x70

part4: 在父类中查找

  • 此时for循环调用,是一个死循环,只有找到IMP或者IMP=forword时,才循环,否则一直执行;
for (unsigned attempts = unreasonableClassCount();;) {
......
}
  • 在当前中的methodList没有找到方法,那么就会执行下面方法

    · 首先将curClass设置为当前类的父类
    · 判断父类是否为nil,如果为空跳出循环

if (slowpath((curClass = curClass->superclass) == nil)){
	imp = forward_imp;
            break;
}
  • 在父类的缓存中查找方法
    · 由于curClass是指向的父类,所以此时查找的是父类cache
    · 如果在父类缓存中没有找到,那么就会循环执行父类慢速查找;
    · 在执行父类的慢速查找时,如果在父类的methodlist中也没有找到,那么就会找父类父类
    · 当父类为nil时,那么imp就会赋值为forward_imp跳出循环;
    · 或者在父类中找到方法,跳出循环。
 imp = cache_getImp(curClass, sel);

part5: 动态方法决议

  • ^ (异或运算):相同0不同1。0 ^ 0 = 0; 0 ^ 1 = 1; 1 ^ 0 = 1; 1 ^ 1 = 0;
  • &(与运算):同时为1,结果才为1,否则为0。0&0=0; 0&1=0; 1&0=0; 1&1=1;
  • 具体逻辑分析请看下一篇文章详细介绍。
LOOKUP_RESOLVER = 2;

 if (slowpath(behavior & LOOKUP_RESOLVER)) {
        behavior ^= LOOKUP_RESOLVER;
        //part5:动态方法决议
        return resolveMethod_locked(inst, sel, cls, behavior);
    }

part6: 找到方法后,将方法写入缓存,方便下次查找

  • 找到方法后,将方法写入缓存,方便下次查找
 log_and_fill_cache(cls, imp, sel, inst, curClass);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值