上篇文章我們分析了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
主要是走兩個(gè)方法郁惜,MethodTableLookup
和TailCallFunctionPointer x17
。
MethodTableLookup
.macro MethodTableLookup
// push frame
SignLR
stp fp, lr, [sp, #-16]!
mov fp, sp
// save parameter registers: x0..x8, q0..q7
//把參數(shù)寫入到寄存器
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
//讀取寄存器里的參數(shù)
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
主要代碼是跳轉(zhuǎn)到_lookUpImpOrForward
著隆。
ldp/stp是 ldr/str 的衍生, 可以同時(shí)讀/寫兩個(gè)寄存器, ldr/str只能讀寫一個(gè)
sub sp, sp, #0x20 ; 拉伸椩浼撸空間32(20 = 2*16)個(gè)字節(jié)
stp x0 , x1, [sp, #0x10] ; sp往上加16(10 = 1 * 16)個(gè)字節(jié),存放x0 和 x1
ldp x1 , x0, [sp, #0x10] ; 將sp偏移16個(gè)字節(jié)的值取出來,放入x1 和 x0
_lookUpImpOrForward
直接搜索_lookUpImpOrForward
發(fā)現(xiàn)找不到源碼,這里拓展一個(gè)知識點(diǎn)食磕。
在斷點(diǎn)處
Debug -> Debug Workflow ->Always show Disassembly
查看寄存器信息在objc_msgSend
處打上斷點(diǎn)尽棕,按住control + step into
,進(jìn)入libobjc.A.dylib`objc_msgSend:找到_objc_msgSend_uncached
按住
control + step into
彬伦,進(jìn)入libobjc.A.dylib`_objc_msgSend_uncached:向下查找可找到這里
lookUpImpOrForward
實(shí)際位置是在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指向父類時(shí)搂橙,從緩存中查找一次imp
imp = cache_getImp(curClass, sel);
//imp == forward_imp 跳出循環(huán)
if (slowpath(imp == forward_imp)) {
break;
}
//查找到了 imp 跳轉(zhuǎn)到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.為避免多線程影響歉提,進(jìn)來先cache_getImp
從緩存中取一次,找到了直接返回imp
2.檢查cls
是否是IsKnownClass
3.從當(dāng)前類開始在繼承鏈中查找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是數(shù)組首元素 end是第二個(gè)元素
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 從第一個(gè)到最后一個(gè)废离,如果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加進(jìn)來的方法時(shí),將指針向前移動一位
//默認(rèn)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
是一個(gè)二分法查找過程悼尾,找到返回method_t
,沒有找到返回nil
肖方。到這里查找的流程就結(jié)束了闺魏,我們接著看一下找到imp
之后的處理。
注意:有
category
添加方法時(shí)窥妇,要指針向前平移一位舷胜,獲得返回值
- 回到
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
時(shí),調(diào)用log_and_fill_cache
然后調(diào)用cache_fill
把方法存入cache_t
中活翩。與前面內(nèi)容呼應(yīng)上了。
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);
}
消息轉(zhuǎn)發(fā)
沒有查找到imp
的時(shí)候翻伺,并不是返回nil
材泄,而是返回forward_imp
。
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
全局搜索_objc_msgForward_impcache
吨岭,在objc-msg-arm64.s
中找到源碼
__objc_msgForward_impcache
只是簡單的跳轉(zhuǎn)到__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
發(fā)現(xiàn)找不到源碼,__objc_forward_handler
其實(shí)是用C
寫的,去掉一個(gè)下劃線旦事,全局搜索魁巩。
這正是我們經(jīng)常找不到方法的報(bào)錯。
unrecognized selector sent to instance 0x101484880
動態(tài)方法決議
沒有找到imp
時(shí)姐浮,并不是直接報(bào)錯谷遂,還做了其他處理。
imp
被賦值為forward_imp
時(shí)卖鲤,break
跳出循環(huán)肾扰,會走到resolveMethod_locked
方法。