上篇文章我们分析了objc_msgSend
在缓存里查找imp
的流程,我们紧接着上一篇分析__objc_msgSend_uncached
。
__objc_msgSend_uncached
.endmacro
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
和TailCallFunctionPointer x17
。
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
。
ldp/stp是 ldr/str 的衍生, 可以同时读/写两个寄存器, ldr/str只能读写一个
sub sp, sp, #0x20 ; 拉伸栈空间32(20 = 2*16)个字节
stp x0 , x1, [sp, #0x10] ; sp往上加16(10 = 1 * 16)个字节,存放x0 和 x1
ldp x1 , x0, [sp, #0x10] ; 将sp偏移16个字节的值取出来,放入x1 和 x0
_lookUpImpOrForward
直接搜索_lookUpImpOrForward
发现找不到源码,这里拓展一个知识点。
在断点处
Debug -> Debug Workflow ->Always show Disassembly
查看寄存器信息在objc_msgSend
处打上断点,按住control + step into
,进入libobjc.A.dylib`objc_msgSend:找到_objc_msgSend_uncached
按住
control + step into
,进入libobjc.A.dylib`_objc_msgSend_uncached:向下查找可找到这里
lookUpImpOrForward
实际位置是在objc-runtime-new.mm:6095
-
lookUpImpOrForward
源码
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
IMP imp = nil;
Class curClass;
runtimeLock.assertUnlocked();
// 重新查找一次缓存,避免多线程的影响
if (fastpath(behavior & LOOKUP_CACHE)) {
imp = cache_getImp(cls, sel);
if (imp) goto done_nolock;
}
runtimeLock.lock();
//检查类是否是已知的类
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().
for (unsigned attempts = unreasonableClassCount();;) {
// 在类中查找imp,没有返回nil,不找父类
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
imp = meth->imp;
goto done;
}
//curClass = curClass->superclass
//查找继承链,直到nil;没有找到的话赋值forward_imp
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.");
}
// curClass指向父类时,从缓存中查找一次imp
imp = cache_getImp(curClass, sel);
//imp == forward_imp 跳出循环
if (slowpath(imp == forward_imp)) {
break;
}
//查找到了 imp 跳转到done
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;
}
主要流程:
1.为避免多线程影响,进来先cache_getImp
从缓存中取一次,找到了直接返回imp
2.检查cls
是否是IsKnownClass
3.从当前类开始在继承链中查找imp
,找到就返回imp
;没找到就返回forward_imp
;
-
getMethodNoSuper_nolock
源码
static method_t *
getMethodNoSuper_nolock(Class cls, SEL sel)
{
runtimeLock.assertLocked();
ASSERT(cls->isRealized());
//获取类的method_list
auto const methods = cls->data()->methods();
//mlists是数组首元素 end是第二个元素
for (auto mlists = methods.beginLists(),
end = methods.endLists();
mlists != end;
++mlists)
{
method_t *m = search_method_list_inline(*mlists, sel);
if (m) return m;
}
return nil;
}
search_method_list_inline
ALWAYS_INLINE static method_t *
search_method_list_inline(const method_list_t *mlist, SEL sel)
{
int methodListIsFixedUp = mlist->isFixedUp();
int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t);
if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
//在有序MethodList查找
return findMethodInSortedMethodList(sel, mlist);
} else {
// 遍历mlist 从第一个到最后一个,如果sel相等,返回元素地址
for (auto& meth : *mlist) {
if (meth.name == sel) return &meth;
}
}
#if DEBUG
// sanity-check negative results
if (mlist->isFixedUp()) {
for (auto& meth : *mlist) {
if (meth.name == sel) {
_objc_fatal("linear search worked when binary search did not");
}
}
}
#endif
return nil;
}
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;
uint32_t count;
for (count = list->count; count != 0; count >>= 1) {
probe = base + (count >> 1);
uintptr_t probeValue = (uintptr_t)probe->name;
if (keyValue == probeValue) {
// `probe` is a match.
// Rewind looking for the *first* occurrence of this value.
// This is required for correct category overrides.
//找到的是category加进来的方法时,将指针向前移动一位
//默认category写的方法存在前面,类本身在后面一位
while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
probe--;
}
return (method_t *)probe;
}
if (keyValue > probeValue) {
base = probe + 1;
count--;
}
}
return nil;
}
findMethodInSortedMethodList
是一个二分法查找过程,找到返回method_t
,没有找到返回nil
。到这里查找的流程就结束了,我们接着看一下找到imp
之后的处理。
注意:有
category
添加方法时,要指针向前平移一位,获得返回值
- 回到
lookUpImpOrForward
里的done
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;
查找到imp
时,调用log_and_fill_cache
然后调用cache_fill
把方法存入cache_t
中。与前面内容呼应上了。
static void
log_and_fill_cache(Class cls, IMP imp, SEL sel, id receiver, Class implementer)
{
#if SUPPORT_MESSAGE_LOGGING
if (slowpath(objcMsgLogEnabled && implementer)) {
bool cacheIt = logMessageSend(implementer->isMetaClass(),
cls->nameForLogging(),
implementer->nameForLogging(),
sel);
if (!cacheIt) return;
}
#endif
cache_fill(cls, sel, imp, receiver);
}
消息转发
没有查找到imp
的时候,并不是返回nil
,而是返回forward_imp
。
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
全局搜索_objc_msgForward_impcache
,在objc-msg-arm64.s
中找到源码
__objc_msgForward_impcache
只是简单的跳转到__objc_msgForward
__objc_msgForward
ENTRY __objc_msgForward
//将__objc_forward_handler@PAGE地址存到 x17
adrp x17, __objc_forward_handler@PAGE
//x17偏移__objc_forward_handler@PAGEOFF加载到p17
ldr p17, [x17, __objc_forward_handler@PAGEOFF]
TailCallFunctionPointer x17
END_ENTRY __objc_msgForward
主要研究的还是__objc_forward_handler
方法。全局搜索__objc_forward_handler
发现找不到源码,__objc_forward_handler
其实是用C
写的,去掉一个下划线,全局搜索。
这正是我们经常找不到方法的报错。
unrecognized selector sent to instance 0x101484880
动态方法决议
没有找到imp
时,并不是直接报错,还做了其他处理。
imp
被赋值为forward_imp
时,break
跳出循环,会走到resolveMethod_locked
方法。