上篇文章 objc_msgSend() 快速查找流程 分析中,当方法在 CacheLookup
方法没有被找到的时候,调用了CheckMiss
或者JumpMiss
,这篇文章来分析下,后面发生了什么。
看下两个方法定义:
.macro CheckMiss
// miss if bucket->sel == 0
.if $0 == GETIMP
cbz p9, LGetImpMiss
.elseif $0 == NORMAL
cbz p9, __objc_msgSend_uncached
.elseif $0 == LOOKUP
cbz p9, __objc_msgLookup_uncached
.else
.abort oops
.endif
.endmacro
.macro JumpMiss
.if $0 == GETIMP
b LGetImpMiss
.elseif $0 == NORMAL
b __objc_msgSend_uncached
.elseif $0 == LOOKUP
b __objc_msgLookup_uncached
.else
.abort oops
.endif
.endmacro
因为 _objc_msgSend
传入的是NORMAL
,我们找到__objc_msgSend_uncached
方法。
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
再找
.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
重点来了 _lookUpImpOrForward
,全局搜索_lookUpImpOrForward
只在汇编中找到调用(tip:汇编中调用C++方法名字前面加_
,C++调用汇编去 _
),所以全局搜索lookUpImpOrForward
。
开始分析:
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
// 赋值 forward_imp _objc_msgForward_impcache在汇编中声明
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
// 初始化imp 默认为nil
IMP imp = nil;
Class curClass;
// 解锁
runtimeLock.assertUnlocked();
// Optimistic cache lookup 是否查找缓存('say666'方法 behavior =3 --011) LOOKUP_CACHE == 4 --100
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().
// 开始死循环 最大次数 353024 unreasonableClassCount 也是类的最大继承上限
for (unsigned attempts = unreasonableClassCount();;) {
// curClass method list. 本类meth方法中循环查找
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
imp = meth->imp;
goto done;
}
if (slowpath((curClass = curClass->superclass) == nil)) { // 改变curClass 指向 父类,判断父类是否是没有父类的类(根类)
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = forward_imp; // 找到根类还没有找到 赋值imp为 forward_imp
break; //跳出 for循环
}
// 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)) { // 如果方法为 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.
// 开始进行方法动态解析 behavior =3 -- 011 LOOKUP_RESOLVER = 2 --010
if (slowpath(behavior & LOOKUP_RESOLVER)) {
behavior ^= LOOKUP_RESOLVER; // behavior = 1 控制流程只走一次
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;
}
lookUpImpOrForward 流程总结
getMethodNoSuper_nolock -> search_method_list_inline -> findMethodInSortedMethodList 流程二分查找源码分析
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; // 获取当前需要查找的 SEL 对应的值
uint32_t count; //方法列表长度 LGPerson长度为8
for (count = list->count; count != 0; count >>= 1) {
probe = base + (count >> 1); // 指针向后偏移 8/2 = 4 指向第5个元素(下标为4)
uintptr_t probeValue = (uintptr_t)probe->name; // 获取第5个元素SEL对应的值
if (keyValue == probeValue) {
// 如果命中 递归判断是否前一个方法是相同的,因为分类的同名方法会放在类中声明的方法后面。
while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
// 往前找
probe--;
}
return (method_t *)probe;
}
// 需要查找的key值大于当前key值向右查找
if (keyValue > probeValue) {
base = probe + 1;
count--;
}
}
return nil;
}