OC底层 - 消息流程 - 慢速查找
前言
一、lookUpImpOrForward慢速查找方法
二、二分查找法
三、objc_defaultForwardHandler
四、慢速消息查找流程图总结
经过对objc_msgSend快速方法查找流程分析之后,当缓存命中之后直接返回imp执行方法。当缓存未找到时呢,我们继续分析下面的流程。
一、lookUpImpOrForward慢速查找方法
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
MethodTableLookup
TailCallFunctionPointer x17
继续通过汇编分析(查了好多汇编基础😂),找到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,但是在objc-msg-arm64.s中并没有搜索到 _lookUpImpOrForward的实现。
那么通过断点来找_lookUpImpOrForward到底在哪里。


定位到objc-runtime-new.mm,直接command+o 进入objc-runtime-new.mm, command+L 定位到6394行代码
NEVER_INLINE
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
//转发的imp
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
IMP imp = nil;
Class curClass;
runtimeLock.assertUnlocked();
if (slowpath(!cls->isInitialized())) {
behavior |= LOOKUP_NOCACHE;
}
runtimeLock.lock();
//是否是合法的注册类
checkIsKnownClass(cls);
cls = realizeAndInitializeIfNeeded_locked(inst, cls, behavior & LOOKUP_INITIALIZE);
/*
if (slowpath(!cls->isRealized())) {
对整个继承链和元类 都进行ro->rw->rwe 进行赋值,同时也验证了class为一个双向链表结构 (做类数据的准备工作)
cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
// runtimeLock may have been dropped but is now locked again
}
if (slowpath(initialize && !cls->isInitialized())) {
//如果类没有初始化, 会进行初始化,并执行callInitialize(cls); 也就是每一个类在第一次使用的时候会默认走+ (void)initialize;方法的原因.
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 may have been dropped but is now locked again
runtimeLock.assertLocked();
//采用一个临时节点来存放,不会对原来的cls有影响
curClass = cls;
//开始遍历查找imp
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) {
imp = meth->imp(false);
goto done;
}
//赋值为其父类
if (slowpath((curClass = curClass->getSuperclass()) == 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)) {
// 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:
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;
}
通过源码可以看到:
1、会先避免初始化的方法被缓存
2、检查要查找的类是否是合法注册过的
3、如果类没有初始化会对类的整个继承链和元类进行从ro(clean memery)拿到数据赋值,做数据准备工作以及发送Initialize消息。

4、开始循环遍历查找方法。
5、方法找到,插入缓存。
6、方法未找到,进入动态方法解析
那么我研究的重点应该是第4步,方法是如何遍历查找出来的。
二、二分查找法
static method_t *
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);
if (m) return m;
}
return nil;
}
ALWAYS_INLINE static method_t *
search_method_list_inline(const method_list_t *mlist, SEL sel)
{
int methodListIsFixedUp = mlist->isFixedUp();
int methodListHasExpectedSize = mlist->isExpectedSize();
if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
//排序过的方法列表进行二分查找
return findMethodInSortedMethodList(sel, mlist);
} else {
// Linear search of unsorted method list
//如果没有排序过,进行线性遍历查找
if (auto *m = findMethodInUnsortedMethodList(sel, mlist))
return m;
}
return nil;
}
核心方法:
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) {
//相当于mid,base是左指针
probe = base + (count >> 1);
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;
}
通过二分查找找到了method_t。
如果当前类没有找到,临时变量curClass赋值为其父类, imp =forward_imp,继续从父类的缓存去查找,缓存没有找到,继续二分查找父类的方法。直到父类为nil的时候跳出循环。
三、objc_defaultForwardHandler
我们根据lookUpImpOrForword方法最开始声明的const IMP forward_imp = (IMP)_objc_msgForward_impcache;来探究
STATIC_ENTRY __objc_msgForward_impcache
// No stret specialization.
b __objc_msgForward
END_ENTRY __objc_msgForward_impcache
__objc_msgForward_impcache 并没有开源,接下来看跳转到__objc_msgForward
ENTRY __objc_msgForward
adrp x17, __objc_forward_handler@PAGE
ldr p17, [x17, __objc_forward_handler@PAGEOFF]
TailCallFunctionPointer x17
END_ENTRY __objc_msgForward
TailCallFunctionPointer 也没有找到,暂时也不关心这个的调用,直接看__objc_forward_handler
__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;
从c++代码可以看到,_objc_forward_handler = objc_defaultForwardHandler。而objc_defaultForwardHandler是在没有消息转发方法实现的时候抛出的异常,这里我的理解是"消息转发的处理是在CoreFoundation框架中,而objc_forward_handler这个句柄会判断是否绑定了消息转发的方法,如果没有就会崩溃,但是绝大部分情况不会走到这个崩溃"。从“class_isMetaClass(object_getClass(self)) ? '+' : '-'” 也可以证明,所谓的实例方法和类方法只过是在底层追加了+ 和 -,本质上来说都是实例方法。
四、慢速消息查找流程图总结
