咱們都知道,Runtime 是 Objective-C 這門動態語言的核心,只有理解了它,咱們纔可以更好的理解 Objective-C 究竟是如何工做的,在編程時,也會更加駕輕就熟。因爲時間和精力有限,這次我主要想從如下幾方面來進行 Runtime 源碼的閱讀,往後將會逐步完善。因爲整體篇幅較長,因此我將會每一部分拆分紅一篇文章來具體分析。html
1、對象的本質,瞭解 isa編程
2、對象的生命週期數組
3、對象的引用計數緩存
4、對象的擴展方法app
5、Runtime 的應用ide
/// Represents an instance of a class.
struct objc_object {
private:
isa_t isa;
public:
// ISA() assumes this is NOT a tagged pointer object
Class ISA();
};
// 其內部有一個指向 Class 的指針,而 Class 是什麼呢
// An opaque type that represents an Objective-C class.
typedef struct objc_class *Class;
// 再來看一下 objc_class 的定義,須要注意的是,objc_class 也是繼承自 objc_object, 因爲 objc_object 中已經定義了一個 isa 指針,因爲結構體中全部的成員都是 public 的,因此 objc_class 也就擁有了 isa 而且也擁有訪問 isa 的權限。
struct objc_class : objc_object {
// Class ISA; // 此時,類中的 isa 指針指向的是 metaClass 元類
Class superclass; // 父類
cache_t cache; // formerly cache pointer and vtable 類的方法緩存,由於 Runtime 時會把第一次遇到的方法緩存到方法緩存中,此後將直接從緩存中讀取方法,極大提升了效率
class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags
// class_data_bits_t <==> class_rw_t + 一個 rr/alloc 位
};
複製代碼
因此到這裏,咱們也就理解到了,實際上,類也是一個對象源碼分析
咱們須要知道的是,在 Objective-C 中,對象的方法並沒有存儲於對象的結構體中(若是每個對象都保存了本身能執行的方法,那麼對內存的佔用有極大的影響)。在調用實例方法時,而是經過 isa 指針來尋找相應的類,經過 class_data_bits_t 來尋找類中的方法。具體是如何尋找的,咱們看👇ui
// 首先 class_data_bits_t 中有一個 bits 位
struct class_data_bits_t {
// Values are the FAST_ flags above.
uintptr_t bits;
public:
// 這裏返回的數據是 class_rw_t* 指針類型的數據,在這個方法中咱們能夠看出,將 bits 與 FAST_DATA_MASK 進行位運算,只取其中的 [3, 47] 位轉換成 class_rw_t * 返回。
class_rw_t* data() {
return (class_rw_t *)(bits & FAST_DATA_MASK);
}
}
// data() 返回的是一個 class_rw_t* 指針, class_rw_t 又是什麼?
// 類中的屬性、方法還有遵循的協議等信息都保存在 class_rw_t 中:
struct class_rw_t {
// Be warned that Symbolication knows the layout of this structure.
uint32_t flags;
uint32_t version;
const class_ro_t *ro;
method_array_t methods;
property_array_t properties;
protocol_array_t protocols;
Class firstSubclass;
Class nextSiblingClass;
char *demangledName;
#if SUPPORT_INDEXED_ISA
uint32_t index;
#endif
};
// 由此咱們能夠看出, class_rw_t 中包含了一些關於類的信息,好比 flag, 版本號, 方法數組, 屬性數組等。而其中又有一個指向 class_ro_t 的指針, class_ro_t 又是什麼?
// 原來,class_ro_t 中存儲了當前類在編譯期就已經肯定的屬性、方法以及遵循的協議。
struct class_ro_t {
uint32_t flags;
uint32_t instanceStart;
uint32_t instanceSize;
#ifdef __LP64__
uint32_t reserved;
#endif
const uint8_t * ivarLayout;
const char * name;
method_list_t * baseMethodList;
protocol_list_t * baseProtocols;
const ivar_list_t * ivars;
const uint8_t * weakIvarLayout;
property_list_t *baseProperties;
method_list_t *baseMethods() const {
return baseMethodList;
}
};
複製代碼
因此由此,咱們知道 class_ro_t 保存的是在編譯期時就已經肯定的方法,因此當在編譯期時, class_data_bits_t 將直接指向 class_ro_t ,然後在 Runtime 時,將會調用 class_data_bits_t 的 data() 直接將結果從 class_rw_t 轉化成 class_ro_t 指針, 而後再初始化一個 class_rw_t 指針,此時它中的數據都爲空,而後再設置它的 ro 變量和 flag, 最後再爲其設置正確的 datathis
/*********************************************************************** * realizeClass * Performs first-time initialization on class cls, * including allocating its read-write data. * Returns the real class structure for the class. * Locking: runtimeLock must be write-locked by the caller **********************************************************************/
static Class realizeClass(Class cls) {
runtimeLock.assertWriting();
const class_ro_t *ro;
class_rw_t *rw;
Class supercls;
Class metacls;
bool isMeta;
if (!cls) return nil;
if (cls->isRealized()) return cls;
assert(cls == remapClass(cls));
// fixme verify class is not in an un-dlopened part of the shared cache?
// 強制轉化爲 ro
ro = (const class_ro_t *)cls->data();
if (ro->flags & RO_FUTURE) {
// This was a future class. rw data is already allocated.
rw = cls->data();
ro = cls->data()->ro;
cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
} else {
// Normal class. Allocate writeable class data.
// 這時候首先給 rw 分配內存空間而且初始化爲 0
rw = (class_rw_t *)calloc(sizeof(class_rw_t), 1);
// 使 rw 指向 ro
rw->ro = ro;
// 設置 rw 的 flag 爲 正在初始化和已經初始化
/** // class is realized - must never be set by compiler #define RO_REALIZED (1<<31) // Values for class_rw_t->flags // These are not emitted by the compiler and are never used in class_ro_t. // Their presence should be considered in future ABI versions. // class_t->data is class_rw_t, not class_ro_t #define RW_REALIZED (1<<31) */
rw->flags = RW_REALIZED|RW_REALIZING;
cls->setData(rw);
}
// 判斷是否爲 metaClass RO_META (1 << 0)
isMeta = ro->flags & RO_META;
rw->version = isMeta ? 7 : 0; // old runtime went up to 6
// Choose an index for this class.
// Sets cls->instancesRequireRawIsa if indexes no more indexes are available
cls->chooseClassArrayIndex();
if (PrintConnecting) {
_objc_inform("CLASS: realizing class '%s'%s %p %p #%u",
cls->nameForLogging(), isMeta ? " (meta)" : "",
(void*)cls, ro, cls->classArrayIndex());
}
// Realize superclass and metaclass, if they aren't already.
// This needs to be done after RW_REALIZED is set above, for root classes.
// This needs to be done after class index is chosen, for root metaclasses.
supercls = realizeClass(remapClass(cls->superclass));
metacls = realizeClass(remapClass(cls->ISA()));
#if SUPPORT_NONPOINTER_ISA
// Disable non-pointer isa for some classes and/or platforms.
// Set instancesRequireRawIsa.
bool instancesRequireRawIsa = cls->instancesRequireRawIsa();
bool rawIsaIsInherited = false;
static bool hackedDispatch = false;
if (DisableNonpointerIsa) {
// Non-pointer isa disabled by environment or app SDK version
instancesRequireRawIsa = true;
}
else if (!hackedDispatch && !(ro->flags & RO_META) &&
0 == strcmp(ro->name, "OS_object"))
{
// hack for libdispatch et al - isa also acts as vtable pointer
hackedDispatch = true;
instancesRequireRawIsa = true;
}
else if (supercls && supercls->superclass &&
supercls->instancesRequireRawIsa())
{
// This is also propagated by addSubclass()
// but nonpointer isa setup needs it earlier.
// Special case: instancesRequireRawIsa does not propagate
// from root class to root metaclass
instancesRequireRawIsa = true;
rawIsaIsInherited = true;
}
if (instancesRequireRawIsa) {
cls->setInstancesRequireRawIsa(rawIsaIsInherited);
}
// SUPPORT_NONPOINTER_ISA
#endif
// Update superclass and metaclass in case of remapping
cls->superclass = supercls;
cls->initClassIsa(metacls);
// Reconcile instance variable offsets / layout.
// This may reallocate class_ro_t, updating our ro variable.
if (supercls && !isMeta) reconcileInstanceVariables(cls, supercls, ro);
// Set fastInstanceSize if it wasn't set already.
cls->setInstanceSize(ro->instanceSize);
// Copy some flags from ro to rw
if (ro->flags & RO_HAS_CXX_STRUCTORS) {
cls->setHasCxxDtor();
if (! (ro->flags & RO_HAS_CXX_DTOR_ONLY)) {
cls->setHasCxxCtor();
}
}
// Connect this class to its superclass's subclass lists
if (supercls) {
addSubclass(supercls, cls);
} else {
addRootClass(cls);
}
// Attach categories
// 在這個方法中將 rw 的方法列表,屬性列表,協議列表賦值
methodizeClass(cls);
return cls;
};
複製代碼
此時,通過 Runtime 的做用以後,如今內存中的關係是,類中的 data 指針指向 class_data_bits_t, class_data_bits_t 結構體中的 data() 方法獲取到的是 class_rw_t 指針, class_rw_t 結構體中的 ro 指針指向 class_ro_t。圖以下:atom
可是問題來了,類的方法是如何被查找和調用的呢?因爲咱們已經知道了,在 ObjC 中,實際上類也是一個特殊的對象,查找類的方法實際上就和查找實例方法採用一樣的機制,可是如何才能讓他們採用一樣的機制呢?這時,元類的做用就顯現了出來。
isa
在類中獲取方法的實現isa
在元類中獲取方法的實現咱們在 Runtime 的源碼中能夠看到,在不一樣的處理器上,這個共同體所分配的內存位數是不一樣的。
union isa_t
{
isa_t() { }
isa_t(uintptr_t value) : bits(value) { }
Class cls;
uintptr_t bits;
#if SUPPORT_PACKED_ISA
// extra_rc must be the MSB-most field (so it matches carry/overflow flags)
// nonpointer must be the LSB (fixme or get rid of it)
// shiftcls must occupy the same bits that a real class pointer would
// bits + RC_ONE is equivalent to extra_rc + 1
// RC_HALF is the high bit of extra_rc (i.e. half of its range)
// future expansion:
// uintptr_t fast_rr : 1; // no r/r overrides
// uintptr_t lock : 2; // lock for atomic property, @synch
// uintptr_t extraBytes : 1; // allocated with extra bytes
# if __arm64__
# define ISA_MASK 0x0000000ffffffff8ULL
# define ISA_MAGIC_MASK 0x000003f000000001ULL
# define ISA_MAGIC_VALUE 0x000001a000000001ULL
struct {
uintptr_t nonpointer : 1;
uintptr_t has_assoc : 1;
uintptr_t has_cxx_dtor : 1;
uintptr_t shiftcls : 33; // MACH_VM_MAX_ADDRESS 0x1000000000
uintptr_t magic : 6;
uintptr_t weakly_referenced : 1;
uintptr_t deallocating : 1;
uintptr_t has_sidetable_rc : 1;
uintptr_t extra_rc : 19;
# define RC_ONE (1ULL<<45)
# define RC_HALF (1ULL<<18)
};
# elif __x86_64__
# define ISA_MASK 0x00007ffffffffff8ULL
# define ISA_MAGIC_MASK 0x001f800000000001ULL
# define ISA_MAGIC_VALUE 0x001d800000000001ULL
struct {
uintptr_t nonpointer : 1;
uintptr_t has_assoc : 1;
uintptr_t has_cxx_dtor : 1;
uintptr_t shiftcls : 44; // MACH_VM_MAX_ADDRESS 0x7fffffe00000
uintptr_t magic : 6;
uintptr_t weakly_referenced : 1;
uintptr_t deallocating : 1;
uintptr_t has_sidetable_rc : 1;
uintptr_t extra_rc : 8;
# define RC_ONE (1ULL<<56)
# define RC_HALF (1ULL<<7)
};
};
複製代碼
以 x86_64_ 爲例,
更深一步,從 isa 的初始化來看 isa 的結構
inline void
objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
initIsa(cls, true, hasCxxDtor);
}
inline void
objc_object::initIsa(Class cls, bool indexed, bool hasCxxDtor)
{
if (!indexed) {
isa.cls = cls;
} else {
isa.bits = ISA_MAGIC_VALUE;
isa.has_cxx_dtor = hasCxxDtor;
isa.shiftcls = (uintptr_t)cls >> 3;
}
}
// 因爲對象的 isa 初始化時傳入 indexed 爲 true ,因此,可簡化爲
inline void
objc_object::initIsa(Class cls, bool indexed, bool hasCxxDtor)
{
// 其中 ISA_MAGIC_VALUE 爲 0x000001a000000001ULL
isa.bits = ISA_MAGIC_VALUE;
isa.has_cxx_dtor = hasCxxDtor;
isa.shiftcls = (uintptr_t)cls >> 3;
}
複製代碼
此時,當執行完 isa.bits = ISA_MAGIC_VALUE; 後 isa 的結構爲 ,能夠看到 ISA_MAGIC_VALUE 將 magic 和 indexed 都初始化了
接着 isa.has_cxx_dtor = hasCxxDtor; 這一位會設置 has_cxx_dtor 的值,若是是 1, 則表示當前對象是否有析構器,若是沒有,就會快速釋放
最後, isa.shiftcls = (uintptr_t)cls >> 3; 將當前對象對應的類指針賦值給 shiftcls 這些位,之因此向右移三位,移三位的主要緣由是用於將 Class 指針中無用的後三位清楚減少內存的消耗,由於類的指針要按照字節(8 bits)對齊內存,其指針後三位都是沒有意義的 0。賦值以後以下
至此,也就證實了咱們以前對於初始化 isa
時對 initIsa
方法的分析是正確的。它設置了 indexed
、magic
以及 shiftcls
。
因爲咱們如今使用告終構體 isa_t 來替代 Class 類型的指針, 因此咱們也就須要一個指針可以返回 isa 所指的類,因此咱們此時須要一個 ISA() 方法。
inline Class
objc_object::ISA()
{
assert(!isTaggedPointer());
#if SUPPORT_INDEXED_ISA
if (isa.nonpointer) {
uintptr_t slot = isa.indexcls;
return classForIndex((unsigned)slot);
}
return (Class)isa.bits;
#else
return (Class)(isa.bits & ISA_MASK);
#endif
}
// 簡化後以下
inline Class
objc_object::ISA()
{
assert(!isTaggedPointer());
// 由此能夠看到,實際上 ISA() 返回的是 isa.bits 與 0x0000000ffffffff8ULL 進行的按位與操做,確實能夠返回當前的類
return (Class)(isa.bits & ISA_MASK);
}
複製代碼