上一篇文章中我们探索了消息的快速查找(缓存),本文我们探索慢速查找。
汇编探索回到C++
探索
上一篇我们已经知道当快速查找找不到的时候会执行到__objc_msgSend_uncached
方法,我们先看一下这个方法的源码:
STATIC_ENTRY __objc_msgSend_uncached
UNWIND __objc_msgSend_uncached, FrameWithNoSaves
// THIS IS NOT A CALLABLE C FUNCTION
// Out-of-band p15 is the class to search
// imp
//方法表查找
MethodTableLookup
//调用返回 x17
TailCallFunctionPointer x17
END_ENTRY __objc_msgSend_uncached
.macro MethodTableLookup
///
SAVE_REGS MSGSEND
// 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 --
//将查找到的方法传给 x17
mov x17, x0
RESTORE_REGS MSGSEND
.endmacro
因为x17
是反回值,mov x17, x0
是将查找结果传给x17
,必然前面的代码是查找过程,或者通过名字我们也很容易猜到_lookUpImpOrForward
就是具体查找的方法。我们在objc
源码中全局搜索_lookUpImpOrForward
,发现并没有搜索到定义方法的代码。因为汇编的方法相比c++
会有前缀_
,所以我们尝试去掉下划线看有没有对应c++
的方法,在objc-runtime-new.mm
文件的6400
行,找到了方法的定义。
lookUpImpOrForward
NEVER_INLINE
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
///省略代码
//判断类是否已加载
checkIsKnownClass(cls);
///加载类 本文不探讨
cls = realizeAndInitializeIfNeeded_locked(inst, cls, behavior & LOOKUP_INITIALIZE);
// runtimeLock may have been dropped but is now locked again
runtimeLock.assertLocked();
curClass = cls;
// The code used to lookup 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();;) {
if (curClass->cache.isConstantOptimizedCache(/* strict */true)) {
#if CONFIG_USE_PREOPT_CACHES
///共享缓存查找
imp = cache_getImp(curClass, sel);
if (imp) goto done_unlock;
curClass = curClass->cache.preoptFallbackClass();
#endif
} else {
// curClass method list.
// 二分法 查找当前类的方法列表
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
///找到方法 结束循环跳转到done:
imp = meth->imp(false);
goto done;
}
if (slowpath((curClass = curClass->getSuperclass()) == nil)) {
// No implementation found, and method resolver didn't help.
// Use forwarding.
/// 找到根类也没找到方法实现 进行下一步操作forward_imp 下一篇探索
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)) {
//找到done
// Found the method in a superclass. Cache it in this class.
goto done;
}
//父类缓存没找到继续for循环 现在curClass实际是superclass
}
// No implementation found. Try method resolver once.
if (slowpath(behavior & LOOKUP_RESOLVER)) {
behavior ^= LOOKUP_RESOLVER;
return resolveMethod_locked(inst, sel, cls, behavior);
}
done:
if (fastpath((behavior & LOOKUP_NOCACHE) == 0)) {
#if CONFIG_USE_PREOPT_CACHES
while (cls->cache.isConstantOptimizedCache(/* strict */true)) {
cls = cls->cache.preoptFallbackClass();
}
#endif
//查找成功 添加到缓存
log_and_fill_cache(cls, imp, sel, inst, curClass);
}
done_unlock:
runtimeLock.unlock();
if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
return nil;
}
return imp;
}
看代码和注释,我们可以清楚的看到方法实现的递归
查找流程
- 查找共享缓存是否有实现
- 查找当前类是否有方法,如果有查找有没有分类方法有实现,如果分类有实现就返回分类的实现即
imp
,如果分类没有实现返回查找到的实现imp
- 如果当前类没有实现方法,继续查找父类的缓存是否有实现
- 如果父类缓存有实现,则到
done:
插入查找的类(注意不是父类)的缓存 - 如果父类没有缓存实现,就继续
for
循环查找父类的方法列表 - 最后如果找到根类还是没找到,就执行
imp = forward_imp;
也就是动态方法解析,动态方法解析我们下一篇探索。
二分法查找
getMethodNoSuper_nolock
一步步跟进查找,我们可以看到查找遍历方法列表的方法是findMethodInSortedMethodList
,它巧妙的使用了二分查找
的方式遍历方法列表,源码如下
ALWAYS_INLINE static method_t *
findMethodInSortedMethodList(SEL key, const method_list_t *list, const getNameFunc &getName)
{
ASSERT(list);
auto first = list->begin();
auto base = first;
decltype(first) 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)getName(probe);
//当前sel==要查找的sel
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)getName((probe - 1))) {
probe--;
}
return &*probe;
}
if (keyValue > probeValue) {
base = probe + 1;
count--;
}
}
return nil;
}
二分查找可能不是很容易发现,我们举个例子验证一下:
- 1、假设
count
初始值是9,要查找的sel
在6号位,count != 0
执行for
循环 - 2、
probe
=base
(0) +4
(9>>1=4) = 4 - 3、
keyValue == probeValue
标示找到sel
退出 - 4、
keyValue > probeValue == true
,此时base
= 4+1 = 5 ,count
=count--
=8 - 5、
count
=count >>1
= 4 - 6、第二次进入
for
循环,probe
=base
(5) +2
(4>>1=2) = 7 - 7、
keyValue > probeValue == false
,count
=count >>1
= 2 - 8、第三次进入
for
循环,probe
=base
(5) +1
(1>>1=2) = 6 - 9、此时
keyValue == probeValue
找到了方法返回,循环了3次找到实现。
我们这个例子是sel
实际的位置大于中间值的情况,小于中间值的情况也类似,就不举例验证了。
总结
本节我们探索了消息的慢速查找流程,具体流程上面已列出,大体流程就是递归查找类以及其父类的sel
,如果找到就添加到缓存后返回imp
,如果找到根类也没有找到就是走动态方法解析
过程,我们下一篇继续探索。