在上面一篇文章objc_msgSend 消息发送之快速查找我们知道了无论是CheckMiss
还是 JumpMiss
都会来到_ _objc_msgSend_uncached
方法而这个方法也就是慢速查找流程
的入口下面我们来分析它
_ _objc_msgSend_uncached
全局搜索 找到了其汇编实现(在objc-msg-arm64.s
)
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
为其方法核心 继续搜索它
- MethodTableLookup
.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
在当前
文件和所有.s
文件中并未搜索出什么,我们把_
去掉再全局搜索一下在objc-runtime-new.mm
发现了它的实现由c/c++
写的
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
/// 获取一个imp 用于消息转发的:
/// 当向一个对象发送一条消息,但它并没有实现的时候,_objc_msgForward会尝试做消息转发。
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
IMP imp = nil;
Class curClass;
runtimeLock.assertUnlocked();
/// 从缓存中再次快速查找一遍
/// 目的:多线程 可能走到这里的时候 cache里有了此方法(乐观的情况下)
// Optimistic cache lookup
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可能已被删除,但现在再次锁定
// runtimeLock may have been dropped but is now locked again
/// 如果sel == initialize,则class_initialize将发送+initialize and
// If sel == initialize, class_initialize will send +initialize and
/// 然后信使将发送+initialize再次在此之后
// 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().
/// 循环查找 方法
/// unreasonableClassCount():为类的任何迭代提供上限,防止运行时元数据损坏时旋转。
for (unsigned attempts = unreasonableClassCount();;) {
// curClass method list.
/// 查找当前类方法列表
Method meth = getMethodNoSuper_nolock(curClass, sel);
/// 找到 返回,并 将方法缓存到cache中
if (meth) {
imp = meth->imp;
/// log_and_fill_cache(cls, imp, sel, inst, curClass);
goto done;
}
/// 如果当前类的父类 ==nil 打破循环 并将superclass 赋值 curClass
if (slowpath((curClass = curClass->superclass) == nil)) {
// No implementation found, and method resolver didn't help.
// Use forwarding.
/// 未找到实现 方法解析器 没有帮助 使用转发
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)) {
//在父类中找到一个forward ::条目。
//停止搜索,但不缓存; 调用方法
//此类的解析器。
// 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.
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;
}