Runtime 介紹
runtime稱為運行時,它區別于編譯時
運行時
是代碼跑起來,被裝載到內存中
的過程,如果此時出錯,則程序會崩潰,是一個動態
階段編譯時
是源代碼翻譯成機器能識別的代碼
的過程,主要是對語言進行最基本的檢查報錯,即詞法分析、語法分析等,是一個靜態
的階段
runtime
的使用
有以下三種方式,其三種實現方法與編譯層和底層的關系如圖所示
通過
OC代碼
,例如[person sayNB]
通過
NSObject方法
,例如isKindOfClass
通過
Runtime API
,例如class_getInstanceSize
其中的compiler
就是我們了解的編譯器
,即LLVM
,例如OC的alloc
對應底層的objc_alloc
, runtime system libarary
就是底層庫
探索方法的本質
方法的本質
使用clang編譯main.cpp文件,通過查看main函數中方法調用的實現,如下所示
//main.m中方法的調用
LGPerson *person = [LGPerson alloc];
[person sayNB];
[person sayHello];
//??clang編譯后的底層實現
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("sayNB"));
((void (*)(id, SEL))(void *)objc_msgSend)((id)person, sel_registerName("sayHello"));
通過上述代碼可以看出,方法的本質
就是objc_msgSend消息發送
為了驗證,通過objc_msgSend
方法來完成[person sayNB]
的調用,查看其打印是否是一致
注:
1、直接調用objc_msgSend
,需要導入頭文件#import <objc/message.h>
2、需要將target --> Build Setting -->搜索msg
-- 將enable strict checking of obc_msgSend calls
由YES
改為NO
,將嚴厲的檢查機制關掉,否則objc_msgSend的參數會報錯
LGPerson *person = [LGPerson alloc];
objc_msgSend(person,sel_registerName("sayNB"));
[person sayNB];
其打印結果如下,發現是一致的,所以 [person sayNB]
等價于objc_msgSend(person,sel_registerName("sayNB"))
對象方法調用-實際執行是父類的實現
除了驗證,我們還可以嘗試讓person的調用執行父類中實現,通過objc_msgSendSuper
實現
-
定義兩個類:LGPerson 和 LGTeacher,父類中實現了sayHello方法
image main中的調用
LGPerson *person = [LGPerson alloc];
LGTeacher *teacher = [LGTeacher alloc];
[person sayHello];
struct objc_super lgsuper;
lgsuper.receiver = person; //消息的接收者還是person
lgsuper.super_class = [LGTeacher class]; //告訴父類是誰
//消息的接受者還是自己 - 父類 - 請你直接找我的父親
objc_msgSendSuper(&lgsuper, sel_registerName("sayHello"));
objc_msgSendSuper
方法中有兩個參數(結構體,sel)
,其結構體類型是objc_super
定義的結構體對象,且需要指定receiver
和 super_class
兩個屬性,源碼實現 & 定義如下
-
objc_msgSendSuper
方法參數image -
objc_super
源碼定義image
打印結果如下
發現不論是[person sayHello]
還是objc_msgSendSuper
都執行的是父類
中sayHello
的實現,所以這里,我們可以作一個猜測:方法調用,首先是在類中查找,如果類中沒有找到,會到類的父類中查找。
帶著我們的猜測,下面我們來探索objc_msgSend的源碼實現
objc_msgSend 快速查找流程分析
在objc4-781源碼中,搜索objc_msgSend
,由于我們日常開發的都是架構是arm64,所以需要在arm64.s
后綴的文件中查找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
的匯編實現如下,然后走到【第二步】
- 從
- 如果支持
.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
時,也是通過同樣哈希算法計算哈希下標進行存儲
,所以讀取
也需要通過同樣的方式讀取
,如下所示image
-
【第三步】根據所得的
哈希下標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
,即進入慢速查找流程
以下是整個快速查找
過程值的變化
過程