上一篇我們分析了objc_msgSend的快速查找方法的流程,我們調(diào)用方法實(shí)際上就是發(fā)送消息,然后首先會到cache中進(jìn)行查找,也即是快速查找。objc_msgSend 通過匯編快速查找方法緩存 ,如果能找到則調(diào)用 TailCallCachedImp 直接將方法緩存起來然后進(jìn)行調(diào)用,如果查找不到就跳到 CheckMiss,然后走慢速查找流程 。這一篇我們接著來分析一下objc_msgSend的慢速查找方法的流程。
一、 checkMiss和jumpMiss
在前面的快速查找流程中,有兩個(gè)判斷是夠沒有找到的方法,就是checkMiss和jumpMiss。我們先看下他們的源碼:
.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
如果沒有找到方法進(jìn)入他們的時(shí)候,都會執(zhí)行__objc_msgSend_uncached方法,我們再看下__objc_msgSend_uncached的源碼:
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
非常簡單,關(guān)鍵代碼就是MethodTableLookup這一行,表示從方法列表中進(jìn)行查找,我們接著看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
是不是看著很懵逼?我也是,我們需要過濾下,找出其中的關(guān)鍵代碼,從上到下看一遍,是不是發(fā)現(xiàn)有一個(gè)很可疑的代碼:_lookUpImpOrForward,沒錯,除了它,其它的我們基本不需要看。那我們怎么知道它就是我們要找的關(guān)鍵代碼呢?
接下來我們在項(xiàng)目中驗(yàn)證下:
首先創(chuàng)建工程,新建LPPerson類,具體代碼如下:
@interface LPPerson : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSString *nickName;
- (void)say666;
- (void)sayHello;
@end
@implementation LGPerson
- (void)sayHello{
NSLog(@"%s",__func__);
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
LPPerson *person = [LPPerson alloc];
[person sayHello];
[person say666];
}
return 0;
}
并在[person sayHello];這一行打上斷點(diǎn):

然后運(yùn)行,在來到斷點(diǎn)后,開啟匯編調(diào)試【Debug -- Debug worlflow -- 勾選Always show Disassembly】就可以看到下面這樣:

我們在objc_msgSend這一行打上斷點(diǎn),并執(zhí)行到此斷點(diǎn),按照我們前面說的方法,按住control點(diǎn)擊stepInto即可進(jìn)入objc_msgSend內(nèi)部:

同樣的方法,在_objc_msgSend_uncached加上斷點(diǎn),并stepInto進(jìn)去:

DuangDuang,是不是我們前面找到的關(guān)鍵代碼:_lookUpImpOrForward,只不過這里少了個(gè)下劃線,這是因?yàn)閰R編和C/C++的語法問題導(dǎo)致:
- 1、
C/C++中調(diào)用 匯編 ,去查找匯編時(shí),C/C++調(diào)用的方法需要多加一個(gè)下劃線 - 2、匯編 中調(diào)用
C/C++方法時(shí),去查找C/C++方法,需要將匯編調(diào)用的方法去掉一個(gè)下劃線
二、lookUpImpOrForward
ok,接下來我們就要重點(diǎn)分析_lookUpImpOrForward它的內(nèi)部做了做什么了,全局搜索lookUpImpOrForward,記得去掉下劃線:

找到如圖所以的地方,
lookUpImpOrForward就是一個(gè)函數(shù):
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
//目的:防止多線程操作時(shí),剛好調(diào)用函數(shù),此時(shí)緩存進(jìn)來了
if (fastpath(behavior & LOOKUP_CACHE)) {
imp = cache_getImp(cls, sel);
if (imp) goto done_nolock;
}
//加鎖,目的是保證讀取的線程安全
runtimeLock.lock();
//判斷是否是一個(gè)已知的類:判斷當(dāng)前類是否是已經(jīng)被認(rèn)可的類,即已經(jīng)加載的類
checkIsKnownClass(cls);
//判斷類是否實(shí)現(xiàn),如果沒有,需要先實(shí)現(xiàn),此時(shí)的目的是為了確定父類鏈,方法后續(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)時(shí)作了減一操作,然后再次循環(huán)時(shí),仍在上限的范圍內(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)) {
//--未找到方法實(shí)現(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;
}
}
//沒有找到方法實(shí)現(xiàn),嘗試一次方法解析
if (slowpath(behavior & LOOKUP_RESOLVER)) {
//動態(tài)方法決議的控制條件,表示流程只走一次
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;
}
整個(gè)lookUpImpOrForward,我們大體上可以分為4個(gè)部分:
- 1、再次快速查找,防止因?yàn)榫€程的原因,導(dǎo)致查找到這個(gè)地方的時(shí)候,剛好有了緩存,那么就需要獲取緩存并返回
- 2、獲取類信息,這個(gè)一步不僅是獲取當(dāng)前的類的信息,還要獲取父類,父類的父類等,確保類的繼承鏈,方便我們的方法查找一定是走到最后。主要包括以下幾步:
判斷當(dāng)前cls是否是已知類,如果不是,則報(bào)錯
類是否實(shí)現(xiàn),如果沒有,則需要先實(shí)現(xiàn),確定其父類鏈,此時(shí)實(shí)例化的目的是為了確定父類鏈、
ro、以及rw等,方法后續(xù)數(shù)據(jù)的讀取以及查找的循環(huán)是否初始化,如果沒有,則初始化
- 3、按照繼承鏈循環(huán)查找,查找過程中使用二分查找,保證效率。注意
for (unsigned attempts = unreasonableClassCount();;)是一個(gè)死循環(huán),一直找到nil,如果找到了則存儲到cache中,并返回imp,找不到則imp = forward_imp;。 - 4、判斷是否執(zhí)行過動態(tài)方法解析,如果沒有,執(zhí)行動態(tài)方法解析,如果執(zhí)行過一次動態(tài)方法解析,則走到消息轉(zhuǎn)發(fā)流程。
需要注意的兩個(gè)地方:
第一、二分查找
二分查找的原理是:從第一次查找開始,每次都取中間位置,與想查找的key的value值作比較,如果相等,則需要排除分類方法,然后將查詢到的位置的方法實(shí)現(xiàn)返回,如果不相等,則需要繼續(xù)二分查找,如果循環(huán)至count = 0還是沒有找到,則直接返回nil。
具體流程是:
- 首先進(jìn)入
getMethodNoSuper_nolock:
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;
}
- 然后進(jìn)入
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)) {
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;
}
再進(jìn)入二分查找的核心代碼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; //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)后出的原則,分類方法最先出,而我們要取的類方法,所以需要先排除分類方法)
//如果是兩個(gè)分類,就看誰先進(jìn)行加載
probe--;
}
return (method_t *)probe;
}
//如果keyValue 大于 probeValue,就往probe即中間位置的右邊查找
if (keyValue > probeValue) {
base = probe + 1;
count--;
}
}
return nil;
}
第二、cache_getImp
cache_getImp方法是通過匯編_cache_getImp實(shí)現(xiàn),傳入的$0 是 GETIMP。源碼如下:
STATIC_ENTRY _cache_getImp
GetClassFromIsa_p16 p0
CacheLookup GETIMP, _cache_getImp
LGetImpMiss:
mov p0, #0
ret
END_ENTRY _cache_getImp
如果父類緩存中找到了方法實(shí)現(xiàn),則跳轉(zhuǎn)至CacheHit即命中,則直接返回imp
如果在父類緩存中,沒有找到方法實(shí)現(xiàn),則跳轉(zhuǎn)至CheckMiss 或者 JumpMiss,通過判斷$0 跳轉(zhuǎn)至LGetImpMiss,直接返回nil。
從前面探索isa中我們知道對象和類的繼承鏈:
- 對象方法(即實(shí)例方法),即在類中查找,其慢速查找的父類鏈?zhǔn)牵?code>類--父類--根類--nil
- 類方法,即在元類中查找,其慢速查找的父類鏈?zhǔn)牵?code>元類--根元類--根類--nil
三、消息轉(zhuǎn)發(fā)流程
如果在快速查找、慢速查找、方法解析流程中,均沒有找到實(shí)現(xiàn),則使用消息轉(zhuǎn)發(fā)。lookUpImpOrForward 源碼中定義了一個(gè)消息轉(zhuǎn)發(fā)嗎?
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
IMP imp = nil;
...
}
即_objc_msgForward_impcache,我們查看它的源碼:
STATIC_ENTRY __objc_msgForward_impcache
// No stret specialization.
b __objc_msgForward
END_ENTRY __objc_msgForward_impcache
ENTRY __objc_msgForward
adrp x17, __objc_forward_handler@PAGE
ldr p17, [x17, __objc_forward_handler@PAGEOFF]
TailCallFunctionPointer x17
END_ENTRY __objc_msgForward
_objc_msgForward_impcache是匯編實(shí)現(xiàn),會跳轉(zhuǎn)至__objc_msgForward,其核心是__objc_forward_handler,全局搜索__objc_forward_handler,搜索不到,去掉一個(gè)下劃線,繼續(xù)搜索

_objc_forward_handler,有如下實(shí)現(xiàn),本質(zhì)是調(diào)用的objc_defaultForwardHandler方法:
__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;
噔噔,我們發(fā)現(xiàn)了什么?這個(gè)報(bào)錯是不是我們常見的執(zhí)行未實(shí)現(xiàn)方法的時(shí)候報(bào)的錯啊。
覺得不錯記得點(diǎn)贊哦!聽說看完點(diǎn)贊的人逢考必過,逢獎必中。?( ′???` )比心