在探索objc_msgSend時,我們需要先了解OC的runtime機制。
Runtime 介紹
runtime 是 OC底層的一套C/C++的API(引入 <objc/runtime.h> 或<objc/message.h>),編譯器最終都會將OC代碼轉化為運行時代碼
runtime 交互的三種方式
? 直接通過 OC 代碼;
? NSObject的方法:NSSelectorFromString 方法等;
? Runtime 的API: sel_registerName, class_getInstanceSize等。
方法的本質
我們需要借助源碼來探索方法的本質,新建一個LGPerson類,聲明實例方法,在main中初始化,并調用sayHello方法,同時使用clang,編譯出cpp文件。
@interface LGPerson : NSObject
-(void)sayHello;
-(void)sayCode;
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
LGPerson *person=[LGPerson alloc];
[person sayHello];
}
return 0;
}
int main(int argc, const char * argv[]) {
/* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;
LGPerson *person=((LGPerson *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("LGPerson"), sel_registerName("alloc"));
((void (*)(id, SEL))(void *)objc_msgSend)((id)person, sel_registerName("sayHello"));
}
return 0;
}
通過上述代碼可以看出,方法的本質就是objc_msgSend消息發送。
我們繼續探索,新建一個LGStudent類,繼承自LGPerson,在LGStudent中調用sayCode方法;同時使用objc_msgSendSuper也調用sayCode。
LGStudent *student=[LGStudent alloc];
[student sayCode];
struct objc_super lgsuper;
lgsuper.receiver = student; //消息的接收者
lgsuper.super_class = [LGPerson class]; //父類
objc_msgSendSuper(&lgsuper, sel_registerName("sayCode"));
二者的輸出結果相同,由此我們可知,OC調用方法等價于runtime中objc_msgSend和objc_msgSendSuper消息發送。同時也可以得到一個猜測:方法調用,首先是在類中查找,如果類中沒有找到,會到類的父類中查找。
下面我們來探索objc_msgSend的源碼實現,看看是否符合猜測:
objc_msgSend 匯編源碼
objc_msgSend是消息發送的源碼的入口,其使用匯編實現的,_objc_msgSend源碼實現如下
//---- 消息發送 -- 匯編入口--objc_msgSend主要是拿到接收者的isa信息
ENTRY _objc_msgSend
//---- 無窗口
UNWIND _objc_msgSend, NoFrame
//---- p0 和空對比,即判斷接收者是否存在,其中p0是objc_msgSend的第一個參數-消息接收者receiver
cmp p0, #0 // nil check and tagged pointer check
//---- le小于 --支持taggedpointer(小對象類型)的流程
#if SUPPORT_TAGGED_POINTERS
b.le LNilOrTagged // (MSB tagged pointer looks negative)
#else
//---- p0 等于 0 時,直接返回 空
b.eq LReturnZero
#endif
//---- p0即receiver 肯定存在的流程
//---- 根據對象拿出isa ,即從x0寄存器指向的地址 取出 isa,存入 p13寄存器
ldr p13, [x0] // p13 = isa
//---- 在64位架構下通過 p16 = isa(p13) & ISA_MASK,拿出shiftcls信息,得到class信息
GetClassFromIsa_p16 p13 // p16 = class
LGetIsaDone:
// calls imp or objc_msgSend_uncached
//---- 如果有isa,走到CacheLookup 即緩存查找流程,也就是所謂的sel-imp快速查找流程
CacheLookup NORMAL, _objc_msgSend
#if SUPPORT_TAGGED_POINTERS
LNilOrTagged:
//---- 等于空,返回空
b.eq LReturnZero // nil check
// tagged
adrp x10, _objc_debug_taggedpointer_classes@PAGE
add x10, x10, _objc_debug_taggedpointer_classes@PAGEOFF
ubfx x11, x0, #60, #4
ldr x16, [x10, x11, LSL #3]
adrp x10, _OBJC_CLASS_$___NSUnrecognizedTaggedPointer@PAGE
add x10, x10, _OBJC_CLASS_$___NSUnrecognizedTaggedPointer@PAGEOFF
cmp x10, x16
b.ne LGetIsaDone
// ext tagged
adrp x10, _objc_debug_taggedpointer_ext_classes@PAGE
add x10, x10, _objc_debug_taggedpointer_ext_classes@PAGEOFF
ubfx x11, x0, #52, #8
ldr x16, [x10, x11, LSL #3]
b LGetIsaDone
// SUPPORT_TAGGED_POINTERS
#endif
LReturnZero:
// x0 is already zero
mov x1, #0
movi d0, #0
movi d1, #0
movi d2, #0
movi d3, #0
ret
END_ENTRY _objc_msgSend
主要有以下幾步
- 【第一步】判斷objc_msgSend方法的第一個參數receiver是否為空
- 如果支持tagged pointer,跳轉至LNilOrTagged,
- 如果小對象為空,則直接返回空,即LReturnZero
- 如果小對象不為空,則處理小對象的isa,走到【第二步】
- 如果即不是小對象,receiver也不為空,有以下兩步
- 從receiver中取出isa存入p13寄存器,
- 通過 GetClassFromIsa_p16中,arm64架構下通過 isa & ISA_MASK 獲取shiftcls位域的類信息,即class,GetClassFromIsa_p16的匯編實現如下,然后走到【第二步】
- 如果支持tagged pointer,跳轉至LNilOrTagged,
.macro GetClassFromIsa_p16 /* src */
//---- 此處用于watchOS
#if SUPPORT_INDEXED_ISA
// Indexed isa
//---- 將isa的值存入p16寄存器
mov p16, $0 // optimistically set dst = src
tbz p16, #ISA_INDEX_IS_NPI_BIT, 1f // done if not non-pointer isa -- 判斷是否是 nonapointer isa
// isa in p16 is indexed
//---- 將_objc_indexed_classes所在的頁的基址 讀入x10寄存器
adrp x10, _objc_indexed_classes@PAGE
//---- x10 = x10 + _objc_indexed_classes(page中的偏移量) --x10基址 根據 偏移量 進行 內存偏移
add x10, x10, _objc_indexed_classes@PAGEOFF
//---- 從p16的第ISA_INDEX_SHIFT位開始,提取 ISA_INDEX_BITS 位 到 p16寄存器,剩余的高位用0補充
ubfx p16, p16, #ISA_INDEX_SHIFT, #ISA_INDEX_BITS // extract index
ldr p16, [x10, p16, UXTP #PTRSHIFT] // load class from array
1:
//--用于64位系統
#elif __LP64__
// 64-bit packed isa
//---- p16 = class = isa & ISA_MASK(位運算 & 即獲取isa中的shiftcls信息)
and p16, $0, #ISA_MASK
#else
// 32-bit raw isa ---- 用于32位系統
mov p16, $0
#endif
.endmacro
- 【第二步】獲取isa完畢,進入慢速查找流程CacheLookup NORMAL
CacheLookup 緩存查找匯編源碼
//!!!!!!!!!重點!!!!!!!!!!!!
.macro CacheLookup
//
// Restart protocol:
//
// As soon as we're past the LLookupStart$1 label we may have loaded
// an invalid cache pointer or mask.
//
// When task_restartable_ranges_synchronize() is called,
// (or when a signal hits us) before we're past LLookupEnd$1,
// then our PC will be reset to LLookupRecover$1 which forcefully
// jumps to the cache-miss codepath which have the following
// requirements:
//
// GETIMP:
// The cache-miss is just returning NULL (setting x0 to 0)
//
// NORMAL and LOOKUP:
// - x0 contains the receiver
// - x1 contains the selector
// - x16 contains the isa
// - other registers are set as per calling conventions
//
LLookupStart$1:
//---- p1 = SEL, p16 = isa --- #define CACHE (2 * __SIZEOF_POINTER__),其中 __SIZEOF_POINTER__表示pointer的大小 ,即 2*8 = 16
//---- p11 = mask|buckets -- 從x16(即isa)中平移16字節,取出cache 存入p11寄存器 -- isa距離cache 正好16字節:isa(8字節)-superClass(8字節)-cache(mask高16位 + buckets低48位)
ldr p11, [x16, #CACHE]
//---- 64位真機
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16
//--- p11(cache) & 0x0000ffffffffffff ,mask高16位抹零,得到buckets 存入p10寄存器-- 即去掉mask,留下buckets
and p10, p11, #0x0000ffffffffffff // p10 = buckets
//--- p11(cache)右移48位,得到mask(即p11 存儲mask),mask & p1(msgSend的第二個參數 cmd-sel) ,得到sel-imp的下標index(即搜索下標) 存入p12(cache insert寫入時的哈希下標計算是 通過 sel & mask,讀取時也需要通過這種方式)
and p12, p1, p11, LSR #48 // x12 = _cmd & mask
//--- 非64位真機
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
and p10, p11, #~0xf // p10 = buckets
and p11, p11, #0xf // p11 = maskShift
mov p12, #0xffff
lsr p11, p12, p11 // p11 = mask = 0xffff >> p11
and p12, p1, p11 // x12 = _cmd & mask
#else
#error Unsupported cache mask storage for ARM64.
#endif
//--- p12是下標 p10是buckets數組首地址,下標 * 1<<4(即16) 得到實際內存的偏移量,通過buckets的首地址偏移,獲取bucket存入p12寄存器
//--- LSL #(1+PTRSHIFT)-- 實際含義就是得到一個bucket占用的內存大小 -- 相當于mask = occupied -1-- _cmd & mask -- 取余數
add p12, p10, p12, LSL #(1+PTRSHIFT)
// p12 = buckets + ((_cmd & mask) << (1+PTRSHIFT)) -- PTRSHIFT是3
//--- 從x12(即p12)中取出 bucket 分別將imp和sel 存入 p17(存儲imp) 和 p9(存儲sel)
ldp p17, p9, [x12] // {imp, sel} = *bucket
//--- 比較 sel 與 p1(傳入的參數cmd)
1: cmp p9, p1 // if (bucket->sel != _cmd)
//--- 如果不相等,即沒有找到,請跳轉至 2f
b.ne 2f // scan more
//--- 如果相等 即cacheHit 緩存命中,直接返回imp
CacheHit $0 // call or return imp
2: // not hit: p12 = not-hit bucket
//--- 如果一直都找不到, 因為是normal ,跳轉至__objc_msgSend_uncached
CheckMiss $0 // miss if bucket->sel == 0
//--- 判斷p12(下標對應的bucket) 是否 等于 p10(buckets數組第一個元素,),如果等于,則跳轉至第3步
cmp p12, p10 // wrap if bucket == buckets
//--- 定位到最后一個元素(即第一個bucket)
b.eq 3f
//--- 從x12(即p12 buckets首地址)- 實際需要平移的內存大小BUCKET_SIZE,得到得到第二個bucket元素,imp-sel分別存入p17-p9,即向前查找
ldp p17, p9, [x12, #-BUCKET_SIZE]! // {imp, sel} = *--bucket
//--- 跳轉至第1步,繼續對比 sel 與 cmd
b 1b // loop
3: // wrap: p12 = first bucket, w11 = mask
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16
//--- 人為設置到最后一個元素
//--- p11(mask)右移44位 相當于mask左移4位,直接定位到buckets的最后一個元素,緩存查找順序是向前查找
add p12, p12, p11, LSR #(48 - (1+PTRSHIFT))
// p12 = buckets + (mask << 1+PTRSHIFT)
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
add p12, p12, p11, LSL #(1+PTRSHIFT)
// p12 = buckets + (mask << 1+PTRSHIFT)
#else
#error Unsupported cache mask storage for ARM64.
#endif
// Clone scanning loop to miss instead of hang when cache is corrupt.
// The slow path may detect any corruption and halt later.
//--- 再查找一遍緩存()
//--- 拿到x12(即p12)bucket中的 imp-sel 分別存入 p17-p9
ldp p17, p9, [x12] // {imp, sel} = *bucket
//--- 比較 sel 與 p1(傳入的參數cmd)
1: cmp p9, p1 // if (bucket->sel != _cmd)
//--- 如果不相等,即走到第二步
b.ne 2f // scan more
//--- 如果相等 即命中,直接返回imp
CacheHit $0 // call or return imp
2: // not hit: p12 = not-hit bucket
//--- 如果一直找不到,則CheckMiss
CheckMiss $0 // miss if bucket->sel == 0
//--- 判斷p12(下標對應的bucket) 是否 等于 p10(buckets數組第一個元素)-- 表示前面已經沒有了,但是還是沒有找到
cmp p12, p10 // wrap if bucket == buckets
b.eq 3f //如果等于,跳轉至第3步
//--- 從x12(即p12 buckets首地址)- 實際需要平移的內存大小BUCKET_SIZE,得到得到第二個bucket元素,imp-sel分別存入p17-p9,即向前查找
ldp p17, p9, [x12, #-BUCKET_SIZE]! // {imp, sel} = *--bucket
//--- 跳轉至第1步,繼續對比 sel 與 cmd
b 1b // loop
LLookupEnd$1:
LLookupRecover$1:
3: // double wrap
//--- 跳轉至JumpMiss 因為是normal ,跳轉至__objc_msgSend_uncached
JumpMiss $0
.endmacro
//以下是最后跳轉的匯編函數
.macro CacheHit
.if $0 == NORMAL
TailCallCachedImp x17, x12, x1, x16 // authenticate and call imp
.elseif $0 == GETIMP
mov p0, p17
cbz p0, 9f // don't ptrauth a nil imp
AuthAndResignAsIMP x0, x12, x1, x16 // authenticate imp and re-sign as IMP
9: ret // return IMP
.elseif $0 == LOOKUP
// No nil check for ptrauth: the caller would crash anyway when they
// jump to a nil IMP. We don't care if that jump also fails ptrauth.
AuthAndResignAsIMP x17, x12, x1, x16 // authenticate imp and re-sign as IMP
ret // return imp via x17
.else
.abort oops
.endif
.endmacro
.macro CheckMiss
// miss if bucket->sel == 0
.if $0 == GETIMP
//--- 如果為GETIMP ,則跳轉至 LGetImpMiss
cbz p9, LGetImpMiss
.elseif $0 == NORMAL
//--- 如果為NORMAL ,則跳轉至 __objc_msgSend_uncached
cbz p9, __objc_msgSend_uncached
.elseif $0 == LOOKUP
//--- 如果為LOOKUP ,則跳轉至 __objc_msgLookup_uncached
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
主要分為以下幾步
【第一步】通過cache首地址平移16字節(因為在objc_class中,首地址距離cache正好16字節,即isa 占8字節,superClass占8字節),獲取cahce,cache中高16位存mask,低48位存buckets,即p11 = cache
-
【第二步】從cache中分別取出buckets和mask,并由mask根據哈希算法計算出哈希下標
- 通過cache和掩碼(即0x0000ffffffffffff)的 & 運算,將高16位mask抹零,得到buckets指針地址,即p10 = buckets
- 將cache右移48位,得到mask,即p11 = mask
- 將objc_msgSend的參數p1(即第二個參數_cmd)& msak,通過哈希算法,得到需要查找存儲sel-imp的bucket下標index,即p12 = index = _cmd & mask,為什么通過這種方式呢?因為在存儲sel-imp時,也是通過同樣哈希算法計算哈希下標進行存儲,所以讀取也需要通過同樣的方式讀取。
-
【第三步】根據所得的哈希下標index 和 buckets首地址,取出哈希下標對應的bucket
- 其中PTRSHIFT等于3,左移4位(即2^4 = 16字節)的目的是計算出一個bucket實際占用的大小,結構體bucket_t中sel占8字節,imp占8字節
- 根據計算的哈希下標index 乘以 單個bucket占用的內存大小,得到buckets首地址在實際內存中的偏移量
- 通過首地址 + 實際偏移量,獲取哈希下標index對應的bucket
【第四步】根據獲取的bucket,取出其中的imp存入p17,即p17 = imp,取出sel存入p9,即p9 = sel
-
【第五步】第一次遞歸循環
- 比較獲取的bucket中sel 與 objc_msgSend的第二個參數的_cmd(即p1)是否相等
- 如果相等,則直接跳轉至CacheHit,即緩存命中,返回imp
- 如果不相等,有以下兩種情況
- 如果一直都找不到,直接跳轉至CheckMiss,因為$0是normal,會跳轉至__objc_msgSend_uncached,即進入慢速查找流程
- 如果根據index獲取的bucket 等于 buckets的第一個元素,則人為的將當前bucket設置為buckets的最后一個元素(通過buckets首地址+mask右移44位(等同于左移4位)直接定位到bucker的最后一個元素),然后繼續進行遞歸循環(第一個遞歸循環嵌套第二個遞歸循環),即【第六步】
- 如果當前bucket不等于buckets的第一個元素,則繼續向前查找,進入第一次遞歸循環
【第六步】第二次遞歸循環:重復【第五步】的操作,與【第五步】中唯一區別是,如果當前的bucket還是等于 buckets的第一個元素,則直接跳轉至JumpMiss,此時的$0是normal,也是直接跳轉至__objc_msgSend_uncached,即進入慢速查找流程。
整個objc_msgSend流程如下