總綱領(lǐng): OC底層探尋
有關(guān)上篇文章分析了objc_msgSend快速查找流程, 當(dāng)在類的方法緩存中查找不到的話, objc_msgSend就會進(jìn)入慢速查找流程, 我們來分析一下: (注, 以下代碼都是在arm64環(huán)境下的)
objc_msgSend慢速查找流程
1. CheckMiss還是JumpMiss方法實現(xiàn)
在快速查找流程中, 如果沒有找到方法實現(xiàn), 無論是走到CheckMiss還是JumpMiss, 最終都會走到__objc_msgSend_uncached匯編函數(shù).
//有關(guān)CheckMiss 以及 JumpMiss代碼, 以為沒有找到, 所以傳進(jìn)來的參數(shù)都為NORMAL, 轉(zhuǎn)而走_(dá)_objc_msgSend_uncached
.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
2. __objc_msgSend_uncached匯編實現(xiàn)
//其中最重要的方法是MethodTableLookup, 即查詢方法列表
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
3. 注意點
在MethodTableLookup的匯編實現(xiàn)中, 我們可以看到最重要的是_lookUpImpOrForward的方法, 然后全局搜索_lookUpImpOrForward發(fā)現(xiàn)搜不到實現(xiàn)方法, 說明該方法并不是匯編實現(xiàn)的, 需要去C/C++方法中查找
- c/c++中調(diào)動匯編, 去查找匯編時, 需要將需要搜索的方法多加一個下劃線.
- 匯編中調(diào)用c/c++方法, 去查找c/c++方法時, 需要將需要查找的方法去掉一個下劃線.
4. lookUpImpOrForward實現(xiàn)
全局搜索lookUpImpOrForward方法, 在objc-runtime-new.mm中可以找到實現(xiàn)代碼, 如下:
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
// 定義的消息轉(zhuǎn)發(fā)
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
IMP imp = nil;
Class curClass;
runtimeLock.assertUnlocked();
// 快速查找,如果找到則直接返回imp
//目的:防止多線程操作時,剛好調(diào)用函數(shù),此時緩存進(jìn)來了
if (fastpath(behavior & LOOKUP_CACHE)) {
imp = cache_getImp(cls, sel);
if (imp) goto done_nolock;
}
//加鎖,目的是保證讀取的線程安全
runtimeLock.lock();
//判斷是否是一個已知的類:判斷當(dāng)前類是否是已經(jīng)被認(rèn)可的類,即已經(jīng)加載的類
checkIsKnownClass(cls);
//判斷類是否實現(xiàn),如果沒有,需要先實現(xiàn),此時的目的是為了確定父類鏈,方法后續(xù)的循環(huán)
if (slowpath(!cls->isRealized())) {
cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
}
//判斷類是否初始化,如果沒有,需要先初始化
if (slowpath((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized())) {
cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
}
runtimeLock.assertLocked();
curClass = cls;
//----查找類的緩存
// unreasonableClassCount -- 表示類的迭代的上限
//(猜測這里遞歸的原因是attempts在第一次循環(huán)時作了減一操作,然后再次循環(huán)時,仍在上限的范圍內(nèi),所以可以繼續(xù)遞歸)
for (unsigned attempts = unreasonableClassCount();;) {
//---當(dāng)前類方法列表(采用二分查找算法),如果找到,則返回,將方法緩存到cache中
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
imp = meth->imp;
goto done;
}
//當(dāng)前類 = 當(dāng)前類的父類,并判斷父類是否為nil
if (slowpath((curClass = curClass->superclass) == nil)) {
//--未找到方法實現(xiàn),方法解析器也不行,使用轉(zhuǎn)發(fā)
imp = forward_imp;
break;
}
// 如果父類鏈中存在循環(huán),則停止
if (slowpath(--attempts == 0)) {
_objc_fatal("Memory corruption in class list.");
}
// --父類緩存
imp = cache_getImp(curClass, sel);
if (slowpath(imp == forward_imp)) {
// 如果在父類中找到了forward,則停止查找,且不緩存,首先調(diào)用此類的方法解析器
break;
}
if (fastpath(imp)) {
//如果在父類中,找到了此方法,將其存儲到cache中
goto done;
}
}
//沒有找到方法實現(xiàn),嘗試一次方法解析
if (slowpath(behavior & LOOKUP_RESOLVER)) {
//動態(tài)方法決議的控制條件,表示流程只走一次
behavior ^= LOOKUP_RESOLVER;
return resolveMethod_locked(inst, sel, cls, behavior);
}
done:
//存儲到緩存 (為下次直接從緩存里面快速查找做準(zhǔn)備)
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;
}
5. 分析getMethodNoSuper_nolock
//其實就是查找類的方法鏈表methed_list
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;
}
//search_method_list_inline的實現(xiàn)
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)) {
return findMethodInSortedMethodList(sel, mlist);
} else {
// Linear search of unsorted method list
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;
}
6. findMethodInSortedMethodList中用的是二分查找
二分查找也稱折半查找(Binary Search),它是一種效率較高的查找方法。但是,折半查找要求線性表必須采用順序存儲結(jié)構(gòu),而且表中元素按關(guān)鍵字有序排列。
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; //key 等于 say666
uint32_t count;
//base相當(dāng)于low,count是max,probe是middle,這就是二分
for (count = list->count; count != 0; count >>= 1) {
//從首地址+下標(biāo) --> 移動到中間位置(count >> 1 左移1位即 count/2 = 4)
probe = base + (count >> 1);
uintptr_t probeValue = (uintptr_t)probe->name;
//如果查找的key的keyvalue等于中間位置(probe)的probeValue,則直接返回中間位置
if (keyValue == probeValue) {
// -- while 平移 -- 排除分類重名方法
while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
//排除分類重名方法(方法的存儲是先存儲類方法,在存儲分類---按照先進(jìn)后出的原則,分類方法最先出,而我們要取的類方法,所以需要先排除分類方法)
//如果是兩個分類,就看誰先進(jìn)行加載
probe--;
}
return (method_t *)probe;
}
//如果keyValue 大于 probeValue,就往probe即中間位置的右邊查找
if (keyValue > probeValue) {
base = probe + 1;
count--;
}
}
return nil;
}
消息轉(zhuǎn)發(fā)流程
1. forward_imp
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
2. _objc_msgForward_impcache 匯編實現(xiàn):
//__objc_msgForward_impcache調(diào)用__objc_msgForward
STATIC_ENTRY __objc_msgForward_impcache
// No stret specialization.
b __objc_msgForward
END_ENTRY __objc_msgForward_impcache
//__objc_msgForward調(diào)用TailCallFunctionPointer x17
ENTRY __objc_msgForward
adrp x17, __objc_forward_handler@PAGE
ldr p17, [x17, __objc_forward_handler@PAGEOFF]
TailCallFunctionPointer x17
END_ENTRY __objc_msgForward
3. TailCallFunctionPointer
TailCallFunctionPointer 就是返回指針的值, 返回x17, x17的值是__objc_forward_handler方法確定的
.macro TailCallFunctionPointer
// $0 = function pointer value
braaz $0
.endmacro
4. __objc_forward_handler
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;