在iOS - objc_msgSend分析一文中我們提到了__class_lookupMethodAndLoadCache3方法可以通過,全局搜索找到,那么還有其他的方式能看到_class_lookupMethodAndLoadCache3方法在哪里面呢?下面就介紹另一種方法:
1、通過查看匯編,找到_class_lookupMethodAndLoadCache3
1.1打斷點,查看匯編
1.2運行程序,由iOS - objc_msgSend分析一文我們知道,方法的快速查找會進入objc_msgSend方法中,因此我們在此處打斷點,按住control點擊Step into 進入該方法中;
1.3在_objc_msgSend_uncached出打斷點,按住control點擊Step into 進入方法中
至此我們完美的看到:_class_lookupMethodAndLoadCache3(id, SEL, Class) at objc-runtime-new.mm:4845證明了_class_lookupMethodAndLoadCache3方法實現(xiàn)在objc-runtime-new.mm文件中.
IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
/**
查找當前的imp或者轉(zhuǎn)發(fā)
cls:如果是實例方法那就是類半夷,如果是類方法那就是元類
sel:方法名
obj:方法調(diào)用者
NO/*cache*/ //因為是CheckMiss狀態(tài)下點用的該方法,所以此處為NO
*/
return lookUpImpOrForward(cls, sel, obj,
YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}
2、方法查找流程
1.1 lookUpImpOrForward源碼分析
/**此處省略部分代碼*/
//為查找方法做準備條件,判斷類有沒有加載好,如果沒有加載好揩页,那就先加載一下類信息,準備好父類砚作、元類
if (!cls->isRealized()) {
realizeClass(cls);
}
//確定類已經(jīng)加載完畢
if (initialize && !cls->isInitialized()) {
runtimeLock.unlock();
_class_initialize (_class_getNonMetaClass(cls, inst));
runtimeLock.lock();
// 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
}
retry:
runtimeLock.assertLocked();//加鎖,防止多個方法調(diào)用時產(chǎn)生沖突
// Try this class's cache.
imp = cache_getImp(cls, sel);//從該類的方法緩存中找imp,明顯緩存為NO,此處勢必拿不到方法的,因此會繼續(xù)走接下來的流程
if (imp) goto done;//拿到方法就返回
// Try this class's method lists.
{
Method meth = getMethodNoSuper_nolock(cls, sel);//在該類中查找該方法
if (meth) {
//如果找到了則進行方法的緩存, log_and_fill_cache->cache_fill->cache_fill_nolock
log_and_fill_cache(cls, meth->imp, sel, inst, cls);//進行緩存
imp = meth->imp;//拿到imp
goto done;
}
}
// Try superclass caches and method lists.
{
unsigned attempts = unreasonableClassCount();
//遍歷父類,父類的父類等等一系列父類,直到為nil
for (Class curClass = cls->superclass;
curClass != nil;
curClass = curClass->superclass)
{
// Halt if there is a cycle in the superclass chain.
if (--attempts == 0) {
_objc_fatal("Memory corruption in class list.");
}
// Superclass cache.
imp = cache_getImp(curClass, sel);//從父類的方法緩存中查找該方法,如果拿到該方法則直接goto done
if (imp) {
if (imp != (IMP)_objc_msgForward_impcache) {
// Found the method in a superclass. Cache it in this class.
log_and_fill_cache(cls, imp, sel, inst, curClass);
goto done;
}
else {
// Found a forward:: entry in a superclass.
// Stop searching, but don't cache yet; call method
// resolver for this class first.
break;
}
}
// Superclass method list.
//如果在父類的方法緩存中沒有找到該方法,則從發(fā)類的方法列表中查到
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
imp = meth->imp;
goto done;
}
}
}
// No implementation found. Try method resolver once.
//如果方法仍然沒找到,就開始做方法消息動態(tài)解析了
if (resolver && !triedResolver) {
runtimeLock.unlock();
/*
實例方法解析:_class_resolveInstanceMethod
類方法解析:_class_resolveClassMethod
*/
_class_resolveMethod(cls, sel, inst);
runtimeLock.lock();
// Don't cache the result; we don't hold the lock so it may have
// changed already. Re-do the search from scratch instead.
//將triedResolver標記為YES嘹锁,下次就不會再進入動態(tài)方法解析
triedResolver = YES;
goto retry;
}
// No implementation found, and method resolver didn't help.
// Use forwarding.
//動態(tài)解析階段完成,進入消息轉(zhuǎn)發(fā)階段
imp = (IMP)_objc_msgForward_impcache;
cache_fill(cls, sel, imp, inst);
done:
runtimeLock.unlock();
return imp;
}
getMethodNoSuper_nolock獲取方法列表
static method_t *
getMethodNoSuper_nolock(Class cls, SEL sel)
{
runtimeLock.assertLocked();
assert(cls->isRealized());
// fixme nil cls?
// fixme nil sel?
for (auto mlists = cls->data()->methods.beginLists(),
end = cls->data()->methods.endLists();
mlists != end;
++mlists)
{
method_t *m = search_method_list(*mlists, sel);//通過二分查找獲取m,此處不做詳解,有興趣的可以自己看下源碼
if (m) return m;
}
return nil;
}
_class_resolveMethod
void _class_resolveMethod(Class cls, SEL sel, id inst)
{
//首先會判斷cls是不是元類葫录,如果cls不是元類的話,說明調(diào)用的是實例方法领猾,那就就會調(diào)用_class_resolveInstanceMethod函數(shù)米同,
if (! cls->isMetaClass()) {
// try [cls resolveInstanceMethod:sel]
_class_resolveInstanceMethod(cls, sel, inst);
}
else {
//如果是元類的話,說明調(diào)用的是類方法摔竿,那么就會調(diào)用_class_resolveClassMethod函數(shù)面粮,
// try [nonMetaClass resolveClassMethod:sel]
// and [cls resolveInstanceMethod:sel]
_class_resolveClassMethod(cls, sel, inst);
if (!lookUpImpOrNil(cls, sel, inst,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
{
_class_resolveInstanceMethod(cls, sel, inst);
}
}
}
_objc_msgForward_impcache
STATIC_ENTRY __objc_msgForward_impcache
// No stret specialization.
b __objc_msgForward //調(diào)用__objc_msgForward
END_ENTRY __objc_msgForward_impcache
ENTRY __objc_msgForward
adrp x17, __objc_forward_handler@PAGE
ldr p17, [x17, __objc_forward_handler@PAGEOFF]//調(diào)用該方法
TailCallFunctionPointer x17
END_ENTRY __objc_msgForward
通過全局搜索_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;
這便是我們經(jīng)常看到的,方法查找不到時所報的錯誤.
流程總結:
1.對需要的變量進行初始化操作和加鎖操作
2.在該類的方法緩存中進行查找,如果找到就就直接goto done;
3.緩存中查找不到時,則從該類的方法列表中進行查找,如果找到,則在緩存中備份一份,方便下次查找,然后goto done;
4.如果該類的方法列表用依舊找不到,則從該類的父類,父類的父類,一直找到NSObject類,依舊是先從父類的緩存中查找,緩存中有則直接goto done,否則就遍歷父類的方法列表,如果找到就直接goto done,找不到則break,進行方法決議;
5.實例方法會轉(zhuǎn)發(fā)+(BOOL) resolveInstanceMethod:(SEL)sel拯坟;類方法會轉(zhuǎn)發(fā)+(BOOL) resolveClassMethod:(SEL)sel,并且類方法轉(zhuǎn)發(fā)完后會再次走查找流程韭山,如果還沒找到的話會走一下實例方法轉(zhuǎn)發(fā)流程郁季;轉(zhuǎn)發(fā)邏輯完成后,會再次走一下方法查找邏輯
6.如果第一次轉(zhuǎn)發(fā)依然后還沒找到IMP钱磅,那么就會返回_objc_msgForward_impcache方法指針,調(diào)用_objc_forward_handler->objc_defaultForwardHandler,報出方法錯誤