上一篇之前进行从class的缓存中查找,没查找到进入__objc_msgSend_uncached,接下来分析下慢速查找
1.慢速查找
源码:
END_ENTRY __objc_msgSend_uncached
STATIC_ENTRY __objc_msgLookup_uncached
UNWIND __objc_msgLookup_uncached, FrameWithNoSaves
// THIS IS NOT A CALLABLE C FUNCTION
// Out-of-band p15 is the class to search
MethodTableLookup
ret
END_ENTRY __objc_msgLookup_uncached
很简单,就是去方法列表查询,看下MethodTableLookup
.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
mov x17, x0
RESTORE_REGS MSGSEND
.endmacro
核心是_lookUpImpOrForward
1.1 _lookUpImpOrForward分析
在objc-msg-arm64.s并没有找到,全局搜索得到
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
const IMP forward_imp = (IMP)_objc_msgForward_impcache;//定义forward_imp
IMP imp = nil;
Class curClass;
runtimeLock.assertUnlocked();//不上锁
if (slowpath(!cls->isInitialized())) {
// The first message sent to a class is often +new or +alloc, or +self
// which goes through objc_opt_* or various optimized entry points.
//
// However, the class isn't realized/initialized yet at this point,
// and the optimized entry points fall down through objc_msgSend,
// which ends up here.
//
// We really want to avoid caching these, as it can cause IMP caches
// to be made with a single entry forever.
//
// Note that this check is racy as several threads might try to
// message a given class for the first time at the same time,
// in which case we might cache anyway.
behavior |= LOOKUP_NOCACHE;
}//判断类是否初始化,没有把初始化方法进行标记
// 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.
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().
// unreasonableClassCount()表示类的迭代上限。for循环类和父类
for (unsigned attempts = unreasonableClassCount();;) {
//苹果说虽然上锁了,但是多数的案例证据表示这个时候还是会错过缓存,相比之后的时间,所以在此进行缓存查找,先判断缓存是否发生变化
if (curClass->cache.isConstantOptimizedCache(/* strict */true)) {
#if CONFIG_USE_PREOPT_CACHES
imp = cache_getImp(curClass, sel);//发生变化了,如果curClass 的缓存有这个方法就返回imp
if (imp) goto done_unlock;
curClass = curClass->cache.preoptFallbackClass();
#endif
} else {
// curClass method list.//进行方法列表查询,进行二分法查找,找到了就返回imp 并把方法缓存起来
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
imp = meth->imp(false);
goto done;
}
//当前类的父类是否为nil
if (slowpath((curClass = curClass->getSuperclass()) == nil)) {
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = forward_imp;//父类为nil,也没找到方法,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.//找到父类的forward 就停止查询,但是不缓存方法,调用此类的方法解析器
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:
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;
}
realizeAndInitializeIfNeeded_locked(id inst, Class cls, bool initialize)
{
runtimeLock.assertLocked();
if (slowpath(!cls->isRealized())) {//类没有实现,没有的话进行实现
cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
// runtimeLock may have been dropped but is now locked again
}
if (slowpath(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
}
return cls;
}
- 首先
runtime不上锁,如果当前对象没有初始化的话进行标识,这个方法可能是+alloc,+new,不去缓存这些方法。 - 判断当前类是否
加载和初始化,没有的话进行实现和初始化,为了后面确定它的父类链,在父类链中查找方法。
3.苹果说这个时候还是有可能存在缓存,并且大多数证据表明如果有缓存的话,这个时候缓存的概率最大。所以在每次for循环当前类列表的时候再此进行一次缓存查找,找到直接返回imp - 没找到的话进行
for循环套for循环,外面的for循环是当前类的父类列表,里面当前类的方法列表方法列表找到的话就返回imp,并缓存方法。当前的父类为nil,也没找到方法,进行方法转发。结束循环 父类链存在循环的时候,终止循环。没有的话查找父类的缓存,有的话返回imp。没有的话返回nil 继续查找- 判断是否执行过
动态解析方法,没有的话执行动态解析,有的话执行方法转发
1.2 getMethodNoSuper_nolock 二分法
getMethodNoSuper_nolock(Class cls, SEL sel)
{
runtimeLock.assertLocked();
ASSERT(cls->isRealized());
// fixme nil cls?
// fixme nil sel?
auto const methods = cls->data()->methods();//获取当前类的方法列表
//拿到方法列表的起始位置和末尾,开始和结尾不一样的话,每次开始位置向后移动一个位置
for (auto mlists = methods.beginLists(),
end = methods.endLists();
mlists != end;
++mlists)
{
// <rdar://problem/46904873> getMethodNoSuper_nolock is the hottest
// caller of search_method_list, inlining it turns
// getMethodNoSuper_nolock into a frame-less function and eliminates
// any store from this codepath.
method_t *m = search_method_list_inline(*mlists, sel);//对sel和method进行比较,相同的话返回方法。
if (m) return m;
}
return nil;
}
1.2.1 findMethodInSortedMethodList分析
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; //把方法转换为uintptr_t指针
uint32_t count;
for (count = list->count; count != 0; count >>= 1) {
probe = base + (count >> 1);
/* 假设方法列表 01,02,03,04,05,06,07,08 我们要找的是第一个元素01 probe = 0+8>>1 =0+4 = 4
判断4号位这个方法是否和要查找的相等,相等话就找到了,没有的话 比较01和04谁大 01>04 = false 继续走第一步
probe = 0 + (4 >> 1) = 0+2 = 2;
判断2号位这个方法和01是否相等 01 != 02 & 01>02为false
probe = 0 + 2>>1 = 0+1 = 1;
就找到了。判断找有重名的分类方法
假如要找07
probe = 0+8>>1 =0+4 = 4
判断4号位是04这个方法是否和要查找的相等,相等话就找到了,没有的话 比较07和04谁大 07>04 = ture
base = 4+1 =5;
count = 4-- = 2;
probe = 5+ 2>>1 = 5+1 = 6;
判断06和目标07是否相等,比较07和06谁大 07>06 = ture
base = 6+1 =7
count = 2-- =1;
probe = 7+ 1>>1 = 7
07和07相等
就找到了。判断找有重名的分类方法
*/
uintptr_t probeValue = (uintptr_t)getName(probe);
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;
}
- 二分法在一个有序列表下我们要取28,第一次取中间的数,和要比较的下标进行比较,如果在上部分0~100,取50,50和28比较28小于50,说明28在50的区间,取0-50的中间数25,25和28比较28大于25则我们取25-50的中间数得到37.5在进行比较,
不断的缩小目标值所在的区间,正常内存是1个字节是8bit是8的倍数,指针内存对象方式也是8字节对齐,不会有小数的,我这里随便举的列子。这样通过几次算法就能得到了100中的28,大大节约了时间,算法确实有魅力。
1.2.2 __objc_msgForward_impcache
STATIC_ENTRY __objc_msgForward_impcache
// No stret specialization.
b __objc_msgForward
END_ENTRY __objc_msgForward_impcache
ENTRY __objc_msgForward
__attribute__((noreturn, cold)) void
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;
这里就是常见的报错打印。
2. 汇编验证
我们也可以通过汇编的方式验证下
断点进入
objc_msgSend
接着断点进入
_objc_msgSend_uncached
找到了
lookUpImpOrForward在objc—runtime-new.mm文件的6394行
3.总结
- 在没有在当前类的缓存中查找到对应的方法时进入
慢速查找,其中慢速查找还会进行1次快速查找,防止多线程下缓存写入 - 在当前类的父类链中循环查找
方法列表,找到了,就缓存,返回imp。没找到,当前类的父类也是nil则进入一次动态方法解析,没走过就走,走过了则走消息转发。 - 在查找父类的方法列表的时候,会先查询
父类缓存方法 - 方法列表查询使用的是
二分法查询。 大概的流程图如下: