Runtime系列文章
Runtime原理探究(一)—— isa的深入體會(蘋果對isa的優化)
Runtime原理探究(二)—— Class結構的深入分析
Runtime原理探究(三)—— OC Class的方法緩存cache_t
Runtime原理探究(四)—— 刨根問底消息機制
Runtime原理探究(五)—— super的本質
[Runtime原理探究(六)—— Runtime的應用...待續]-()
[Runtime原理探究(七)—— Runtime的API...待續]-()
Runtime原理探究(八)—— 面試題中的Runtime
上一篇里面,我們從Class
的cache_t
作為切入點,完善了我們對于OC類對象的認識,而且還詳細了解了Runtime的消息發送流程和方法緩存策略,不過對于消息機制這個話題只是熱身而已。接下來,本文就從源頭開始,完整地來研究Runtime的消息機制。
消息機制流程框架
[obj message] ?? 消息發送 ?? 動態方法解析 ?? 消息轉發
(一)消息發送
消息發送流程上一篇文章已經分析過,這里再從[obj message]
為出發點,從objc源碼里進行一次正向梳理。
首先,要查看[obj message]
的底層表示,可以通過xcode調試工具調出其匯編代碼進行分析,但是這個方法需要你至少有熟練的匯編代碼閱讀能力,有不少難度。如果把要求降低一點,可以在命令行工具里面通過
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc xxx.m -o yyy.cpp
生成一個中間代碼,這個中間代碼基本上都是C或C++代碼,閱讀起來相對容易。但是需要說明一下,這個中間代碼僅作為參考,因為目前xcode編譯器已經不使用用這種格式的中間代碼的,取而代之的是另一種語法格式的中間代碼,但是雖然語法不同,但是實現思路和邏輯大致是相同的,因此老的中間代碼還是能夠借來參考一下的。
通過上面的命令行操作,[obj message]
編譯之后的底層表示是
((void (*)(id, SEL))(void *)objc_msgSend)((id)obj, sel_registerName("message"));
去掉類型轉換后,簡化一下可以表示成
objc_msgSend(obj, sel_registerName("message"));
其中第一個參數obj
就是消息接受者,后面的sel_registerName
,可以在objc
源碼中搜到它的函數聲明
SEL _Nonnull sel_registerName(const char * _Nonnull str)
很明顯這里是根據一個C字符串返回一個SEL
,其實就等同于OC里面的@selector()
。這兩個參數都沒什么太大疑問,然后我們來從源碼里看一看能否找到objc_msgSend
的實現。但最終,你無法在源碼里面找到對應的C函數實現,因為在objc源碼里面,是通過匯編來實現的,并且對應不同架構有不同的版本,這里我們就關注arm64版本的實現。
msg
,還有涉及到block
相關的一些內容也是用匯編實現的,還有一個objc-sel-table.s
,受限本人知識儲備,暫時還解讀不了,不過沒關系,它跟我們現在討論的話題不相關。
你或許會疑惑,蘋果為什么要用匯編來實現某些函數呢?主要原因是因為對于一些調用頻率太高的函數或操作,使用匯編來實現能夠提高效率。在匯編源碼里面,可以按照下面的方法來定位函數實現
接下來我們開始閱讀匯編
然后查找一下CacheLookup,看看緩存怎么查詢的,注意,這里的NORMAL是參數。
如果是命中緩存,找到了方法,那就簡單了,直接返回并調用就好了,如果沒找,就會進入上圖中的__objc_msgSend_uncached
__objc_msgSend_uncached
中調用了MethodTableLookup
MethodTableLookup
里面,調用了__class_lookupMethodAndLoadCache3
函數,而這個函數在當前的匯編代碼里面是找不到實現的。你去objc源碼進行全局搜索,也搜不到,這里經過大佬指點,如果是一個C函數,在底層匯編里面如果需要調用的話,蘋果會為其加一個下劃線_
,因此上面的的函數刪去一個下劃線,_class_lookupMethodAndLoadCache3
,你就可以在源碼里面找到它對應的C函數,它是objc-runtime-new.mm
里面的一個C函數
IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
return lookUpImpOrForward(cls, sel, obj,
YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}
而這個函數里面最終是調用了lookUpImpOrForward
函數,從這個函數開始的后面的流程,我在上一篇文章里面已經做過完整解讀了,這里不再做詳細論述,只將之前的結論貼出來
- (1) 當一個對象接收到消息時
[obj message];
,首先根據obj
的isa
指針進入它的類對象cls
里面。- (2) 在
obj
的cls
里面,首先到緩存cache_t
里面查詢方法message
的函數實現,如果找到,就直接調用該函數。- (3) 如果上一步沒有找到對應函數,在對該
cls
的方法列表進行二分/遍歷查找,如果找到了對應函數,首先會將該方法緩存到obj
的類對象cls
的cache_t
里面,然后對函數進行調用。- (4) 在每次進行緩存操作之前,首先需要檢查緩存容量,如果緩存內的方法數量超過規定的臨界值(
設定容量的3/4
),需要先對緩存進行2倍擴容,原先緩存過的方法全部丟棄,然后將當前方法存入擴容后的新緩存內。- (5) 如果在
obj
的cls
對象里面,發現緩存和方法列表都找不到mssage
方法,則通過cls
的superclass
指針進入它的父類對象f_cls
里面- (6) 進入
f_cls
后,首先在它的cache_t
里面查找mssage
,如果找到了該方法,那么會首先將方法緩存到消息接受者obj
的類對象cls
的cache_t
里面,然后調用方法對應的函數。- (7) 如果上一步沒有找到方法,將會對
f_cls
的方法列表進行遍歷二分/遍歷查找,如果找到了mssage
方法,那么同樣,會首先將方法緩存到消息接受者obj
的類對象cls
的cache_t
里面,然后調用方法對應的函數。需要注意的是,這里并不會將方法緩存到當前父類對象f_cls
的cache_t里面。- (8) 如果還沒找到方法,則會通過
f_cls
的superclass
進入更上層的父類對象里面,按照(6)->(7)->(8)
步驟流程重復。如果此時已經到了基類對象NSObject
,仍沒有找到mssage
,則進入步驟(9)
- (9) 接下來將會轉到消息機制的 動態方法解析 階段
消息發送流程
到此,消息發送機制的正向解讀就到這里。關于上面的匯編代碼,我自己也只是借助相關注釋說明,間接挖掘蘋果的底層思路,其實匯編里面還有更多的細節,只有你自己親自讀一遍,才會有更跟深的體會和領悟。
(二)動態方法解析
接下來,一起來認識一下方法的動態解析。上面的章節,我們講到了lookUpImpOrForward
函數,這個函數我在之前的文章也具體討論過了,但是僅僅是解讀完了消息發送和方法緩存的內容,這里我先貼出該函數的代碼
/***********************************************************************
* lookUpImpOrForward.
* The standard IMP lookup. ------------->??????標準的IMP查找流程
* initialize==NO tries to avoid +initialize (but sometimes fails)
* cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)
* Most callers should use initialize==YES and cache==YES.
* inst is an instance of cls or a subclass thereof, or nil if none is known.
* If cls is an un-initialized metaclass then a non-nil inst is faster.
* May return _objc_msgForward_impcache. IMPs destined for external use
* must be converted to _objc_msgForward or _objc_msgForward_stret.
* If you don't want forwarding at all, use lookUpImpOrNil() instead.
**********************************************************************/
IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
bool initialize, bool cache, bool resolver)
{
IMP imp = nil;
bool triedResolver = NO;
runtimeLock.assertUnlocked();
// Optimistic cache lookup
if (cache) {//------------------>??????查詢當前Class對象的緩存,如果找到方法,就返回該方法
imp = cache_getImp(cls, sel);
if (imp) return imp;
}
// runtimeLock is held during isRealized and isInitialized checking
// to prevent races against concurrent realization.
// runtimeLock is held during method search to make
// method-lookup + cache-fill atomic with respect to method addition.
// Otherwise, a category could be added but ignored indefinitely because
// the cache was re-filled with the old value after the cache flush on
// behalf of the category.
runtimeLock.read();
if (!cls->isRealized()) {//--------------->??????當前Class如果沒有被realized,就進行realize操作
// Drop the read-lock and acquire the write-lock.
// realizeClass() checks isRealized() again to prevent
// a race while the lock is down.
runtimeLock.unlockRead();
runtimeLock.write();
realizeClass(cls);
runtimeLock.unlockWrite();
runtimeLock.read();
}
if (initialize && !cls->isInitialized()) {//--------->??????當前Class如果沒有初始化,就進行初始化操作
runtimeLock.unlockRead();
_class_initialize (_class_getNonMetaClass(cls, inst));
runtimeLock.read();
// 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.assertReading();
// Try this class's cache.//------------>??????嘗試從該Class對象的緩存中查找,如果找到,就跳到done處返回該方法
imp = cache_getImp(cls, sel);
if (imp) goto done;
// Try this class's method lists.//---------------->??????嘗試從該Class對象的方法列表中查找,找到的話,就緩存到該Class的cache_t里面,并跳到done處返回該方法
{
Method meth = getMethodNoSuper_nolock(cls, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, cls);
imp = meth->imp;
goto done;
}
}
// Try superclass caches and method lists.------>??????進入當前Class對象的superclass對象
{
unsigned attempts = unreasonableClassCount();
for (Class curClass = cls->superclass;//------>??????該for循環每循環一次,就會進入上一層的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.------>??????在當前superclass對象的緩存進行查找
imp = cache_getImp(curClass, sel);
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;//------>??????如果在當前superclass的緩存里找到了方法,就調用log_and_fill_cache進行方法緩存,注意這里傳入的參數是cls,也就是將方法緩存到消息接受對象所對應的Class對象的cache_t中,然后跳到done處返回該方法
}
else {
// Found a forward:: entry in a superclass.
// Stop searching, but don't cache yet; call method
// resolver for this class first.
break;//---->??????如果緩存里找到的方法是_objc_msgForward_impcache,就跳出該輪循環,進入上一層的superclass,再次進行查找
}
}
// Superclass method list.---->??????如過畫緩存里面沒有找到方法,則對當前superclass的方法列表進行查找
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
//------>??????如果在當前superclass的方法列表里找到了方法,就調用log_and_fill_cache進行方法緩存,注意這里傳入的參數是cls,也就是將方法緩存到消息接受對象所對應的Class對象的cache_t中,然后跳到done處返回該方法
log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
imp = meth->imp;
goto done;
}
}
}
//**********************???消息發送流程結束???*************************
//??????動態方法解析
// No implementation found. Try method resolver once.//------>??????如果到基類還沒有找到方法,就嘗試進行方法解析
if (resolver && !triedResolver) {
runtimeLock.unlockRead();
_class_resolveMethod(cls, sel, inst);
runtimeLock.read();
// 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;
goto retry;
}
//??????消息轉發
// No implementation found, and method resolver didn't help. //------>??????如果方法解析不成功,就進行消息轉發
// Use forwarding.
imp = (IMP)_objc_msgForward_impcache;
cache_fill(cls, sel, imp, inst);
done:
runtimeLock.unlockRead();
return imp;
}
根據上面代碼里面的??????動態方法解析
標記處,我們繼續解讀消息機制的 動態方法解析階段。
首先注意一個細節,這里有一個標簽triedResolver
用來判斷是否進行該類是否進行過動態方法解析。如果首次走到這里,triedResolver = NO
,當動態方法解析進行過一次之后,會設置triedResolver = YES
,這樣下次走到這里的時候,就不會再次進行動態方法解析,因為這個流程只需要進行一次就夠了,并且實在首次調用一個該類沒有實現的方法的時候,才會進行這個流程,仔細體會一下
goto retry
回到的地方是本函數的如下位置【新增的方法會存放在 消息接受者->ISA() 的rw的方法列表里面去】
),會重新走一遍緩存查找和消息發送。
下面再繼續看一下方法動態解析里面的核心函數_class_resolveMethod(cls, sel, inst);
***********************************************************************
* _class_resolveMethod
* Call +resolveClassMethod or +resolveInstanceMethod.
* Returns nothing; any result would be potentially out-of-date already.
* Does not check if the method already exists.
**********************************************************************/
void _class_resolveMethod(Class cls, SEL sel, id inst)
{
if (! cls->isMetaClass()) {
// try [cls resolveInstanceMethod:sel]
_class_resolveInstanceMethod(cls, sel, inst);
}
else {
// 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);
}
}
}
很明顯,if (! cls->isMetaClass())
這句代碼實在判斷當前的參數cls
是否是一個meta-class
對象,也就是說,調用對象方法(-方法
)和調用類方法(+方法
)過程里面的動態方法解析,走的都是這個方法啊,這里我們先關注對象方法(-方法
)的解析處理邏輯。也就是_class_resolveInstanceMethod(cls, sel, inst);
,進入它的函數實現如下
static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
{
//---??????查看cls的meta-class對象的方法列表里面是否有SEL_resolveInstanceMethod函數,
//---??????也就是看是否實現了+(BOOL)resolveInstanceMethod:(SEL)sel方法
if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
{
//---??????如果沒找到,直接返回,
// Resolver not implemented.
return;
}
//---??????如果找到,則通過objc_msgSend調用一下+(BOOL)resolveInstanceMethod:(SEL)sel方法
//---??????完成里面的動態增加方法的步驟
//---??????接下來是一些對解析結果的打印信息
BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
// Cache the result (good or bad) so the resolver doesn't fire next time.
// +resolveInstanceMethod adds to self a.k.a. cls
IMP imp = lookUpImpOrNil(cls, sel, inst,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
if (resolved && PrintResolving) {
if (imp) {
_objc_inform("RESOLVE: method %c[%s %s] "
"dynamically resolved to %p",
cls->isMetaClass() ? '+' : '-',
cls->nameForLogging(), sel_getName(sel), imp);
}
else {
// Method resolver didn't add anything?
_objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
", but no new implementation of %c[%s %s] was found",
cls->nameForLogging(), sel_getName(sel),
cls->isMetaClass() ? '+' : '-',
cls->nameForLogging(), sel_getName(sel));
}
}
}
動態方法解析的核心步驟完成之后,會一層一層往上返回到lookUpImpOrForward
函數,跳到retry
標記處,重新查詢方法,因為在方法解析這一步,如果對某個目標方法名xxx
有過處理,為其動態增加了方法實現,那么再次查詢該方法,則一定可以在消息發送階段被找到并調用。 對于類方法(+方法
)的動態解析其實跟上面的過程大致相同,只不過解析的時候調用的+(BOOL)resolveClassMethod:(SEL)sel
方法,來完成類方法的動態添加綁定。
小結
首先用圖來總結一下動態方法解析
動態方法解析真的有必要嗎?
其實這個我覺得沒有固定答案,根據個人的理解因人而異,就我個人的膚淺看法,好像除了在面試里面可以增加一點逼格外,實際項目中好像沒太多使用場景,因為與其在動態解析步驟里面動態增加方法,還不如直接在類里面實現該方法呢,不知道大家有什么心得體會,歡迎留言交流。
好了,動態方法解析流程解讀完畢。
(三)消息轉發
經過前兩個流程之后,如果還沒能找到方法對應的函數,說明當前類已經盡力了,但是確實沒有能力處理目標方法,因子只能把方法拋給別人,也就丟給其他的類去處理,因此最后一個流程為什么叫消息轉發,顧名思義。
下面,我們來搞定消息轉發,入口如下,位于lookUpImpOrForward
函數的尾部
(IMP)_objc_msgForward_impcache
指針。對源碼搜索一下,發現它其實也是一段匯編實現
STATIC_ENTRY __objc_msgForward_impcache
MESSENGER_START
nop
MESSENGER_END_SLOW
// No stret specialization.
b __objc_msgForward
END_ENTRY __objc_msgForward_impcache
//**************************************************************
ENTRY __objc_msgForward
adrp x17, __objc_forward_handler@PAGE
ldr x17, [x17, __objc_forward_handler@PAGEOFF]
br x17
END_ENTRY __objc_msgForward
匯編中的調用順序是這樣
_objc_msgForward_impcache
->__objc_msgForward
->__objc_forward_handler
,我們可以嘗試搜索一下objc_forward_handler
,最終,我們可以在objc-runtime.mm
里面可以找到與objc_forward_handler
相關的信息
__attribute__((noreturn)) 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;
發現_objc_forward_handler
其實是一個函數指針,指向objc_defaultForwardHandler
,但是這個函數只有打印信息,再往下深入,無法看出消息轉發更底層的執行邏輯,蘋果對此并沒有開源。如果想要繼續挖掘,就只通過匯編碼逆向反推C函數的實現,逆向是一個很大的話題,需要很多知識儲備,本文無法展開介紹。
其實,如果消息機制的前兩個流程都沒命中,進入消息轉發階段,則會調用__forwarding__
函數。這個可以從xcode的打印信息里面驗證,如果調用一個沒有實現的方法,并且動態解析和消息轉發都沒有處理,最終打印結果如下
可以看到從底層上來,調用了CF框架的
_CF_forwarding_prep_0
,然后就調用了___forwarding___
。該函數就屬于蘋果未開源部分,感謝大神MJ老師的分享,以下貼出他為我提供的一份消息轉發流程的C函數實現,
int __forwarding__(void *frameStackPointer, int isStret) {
id receiver = *(id *)frameStackPointer;
SEL sel = *(SEL *)(frameStackPointer + 8);
const char *selName = sel_getName(sel);
Class receiverClass = object_getClass(receiver);
// 調用 forwardingTargetForSelector:
if (class_respondsToSelector(receiverClass, @selector(forwardingTargetForSelector:))) {
id forwardingTarget = [receiver forwardingTargetForSelector:sel];
if (forwardingTarget && forwardingTarget != receiver) {
return objc_msgSend(forwardingTarget, sel, ...);
}
}
// 調用 methodSignatureForSelector 獲取方法簽名后再調用 forwardInvocation
if (class_respondsToSelector(receiverClass, @selector(methodSignatureForSelector:))) {
NSMethodSignature *methodSignature = [receiver methodSignatureForSelector:sel];
if (methodSignature && class_respondsToSelector(receiverClass, @selector(forwardInvocation:))) {
NSInvocation *invocation = [NSInvocation _invocationWithMethodSignature:methodSignature frame:frameStackPointer];
[receiver forwardInvocation:invocation];
void *returnValue = NULL;
[invocation getReturnValue:&value];
return returnValue;
}
}
if (class_respondsToSelector(receiverClass,@selector(doesNotRecognizeSelector:))) {
[receiver doesNotRecognizeSelector:sel];
}
// The point of no return.
kill(getpid(), 9);
}
__forwarding__
函數邏輯可以簡單概括成
forwardingTargetForSelector:
->methodSignatureForSelector
->forwardInvocation
。我在功過一個流程圖來解讀一下上面的代碼
-(id)forwardingTargetForSelector:(SEL)aSelector
——__forwarding__
首先會看類有沒有實現這個方法,這個方法返回的是一個id
類型的轉發對象forwardingTarget
,如果其不為空,則會通過objc_msgSend
函數對其直接發送消息objc_msgSend(forwardingTarget, sel, ...);
,也就是說讓轉發對象forwardingTarget
去處理當前的方法SEL。如果forwardingTarget
為nil
,則進入下面的方法-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
——這個方法是讓我們根據方法選擇器SEL
生成一個NSMethodSignature方法簽名
并返回,這個方法簽名里面其實就是封裝了返回值類型,參數類型的信息。
__forwarding__
會利用這個方法簽名,生成一個NSInvocation
,將其作為參數,調用- (void)forwardInvocation:(NSInvocation *)anInvocation
方法。如果我們在這里沒有返回方法簽名,系統則認為我們徹底不想處理這個方法了,就會調用doesNotRecognizeSelector:
方法拋出經典的報錯報錯unrecognized selector sent to instance 0xXXXXXXXX
,結束消息機制的全部流程。- (void)forwardInvocation:(NSInvocation *)anInvocation
——如果我們在上面提供了方法簽名,__forwarding__
則會最終調用這個方法。在這個方法里面,我們會拿到一個參數(NSInvocation *)anInvocation
,這個anInvocation
其實是__forwarding__
對如下三個信息的封裝:
anInvocation.target
-- 方法調用者anInvocation.selector
-- 方法名- (void)getArgument:(void *)argumentLocation atIndex:(NSInteger)idx;
-- 方法參數
因此在此方法里面,我們可以決定將消息轉發給誰(target
),甚至還可以修改消息的參數,由于anInvocation
會存儲消息selector
里面帶來的參數,并且可以根據消息所對應的方法簽名確定消息參數的個數,所以我們通過- (void)setArgument:(void *)argumentLocation atIndex:(NSInteger)idx;
可以對參數進行修改。總之你可以按照你的意愿,配置好anInvocation
,然后簡單一句[anInvocation invoke];
即可完成消息的轉發調用,也可以不做任何處理,輕輕地來,輕輕地走,但是不會導致程序報錯。
至此,Runtime的消息機制就全部梳理完畢~~
Runtime系列文章
Runtime原理探究(一)—— isa的深入體會(蘋果對isa的優化)
Runtime原理探究(二)—— Class結構的深入分析
Runtime原理探究(三)—— OC Class的方法緩存cache_t
Runtime原理探究(四)—— 刨根問底消息機制
Runtime原理探究(五)—— super的本質
[Runtime原理探究(六)—— Runtime的應用...待續]-()
[Runtime原理探究(七)—— Runtime的API...待續]-()
Runtime原理探究(八)—— 面試題中的Runtime