Runtime原理探究(一)—— isa的深刻體會(蘋果對isa的優化)html
Runtime原理探究(二)—— Class結構的深刻分析ios
Runtime原理探究(三)—— OC Class的方法緩存cache_t面試
Runtime原理探究(四)—— 刨根問底消息機制xcode
Runtime原理探究(六)—— 面試題中的Runtimemarkdown
上一篇裏面,咱們從Class
的cache_t
做爲切入點,完善了咱們對於OC類對象的認識,並且還詳細瞭解了Runtime的消息發送流程和方法緩存策略,不過對於消息機制這個話題只是熱身而已。接下來,本文就從源頭開始,完整地來研究Runtime的消息機制。架構
[obj message]
➡️ 消息發送 ➡️ 動態方法解析 ➡️ 消息轉發app
消息發送流程上一篇文章已經分析過,這裏再從[obj message]
爲出發點,從objc源碼裏進行一次正向梳理。框架
首先,要查看[obj message]
的底層表示,能夠經過xcode調試工具調出其彙編代碼進行分析,可是這個方法須要你至少有熟練的彙編代碼閱讀能力,有很多難度。若是把要求下降一點,能夠在命令行工具裏面經過iphone
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版本的實現。其實objc源碼總共也沒多少文件,如上圖所示,除了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原理探究(一)—— isa的深刻體會(蘋果對isa的優化)