對象的本質(zhì)
在分析isa
前战惊,先分析一下我們常見的接觸最多的——對象噪裕。為了探究OC對象的本質(zhì)是什么捺弦,就有必要了解Clang
躁垛。
Clang是?個C語?俩莽、C++川梅、Objective-C語?的輕量級編譯器疯兼。源代碼發(fā)布于BSD協(xié)議下然遏。Clang將?持其普通lambda表達式、返回類型的簡化處理以及更好的處理constexpr關(guān)鍵字吧彪。Clang是?個由Apple主導編寫待侵,基于LLVM的C/C++/Objective-C編譯器。
-
利用Clang解析OC文件
將OC代碼通過Clang命令解析姨裸,就能探究OC對象低層是怎樣的一個數(shù)據(jù)形式秧倾。用到的命令:clang -rewrite-objc main.m -o main.cpp
,目的是將目標文件編譯成C++的文件,這是基于OC文件的一種編譯方式傀缩,如果要對UIKit框架下的UI文件比如ViewController.m
那先。
// 模擬器sdk路徑替換自己的即可
clang -rewrite-objc -fobjc-arc -fobjc-runtime=ios-12.0.0 -isysroot /
Applications/Xcode.app/Contents/Developer/Platforms/
iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk ViewController.m
xcode
安裝的時候順帶安裝了xcrun
命令,xcrun
命令在clang
的基礎(chǔ)上進?了
?些封裝赡艰,要更好??些
xcrun -sdk iphonesimulator clang -arch arm64 -rewrite-objc main.m -o main-arm64.cpp
-- iPhoneSimulator
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m -o main?arm64.cpp
-- iPhone
通過搜索定義的對象名
// 對象的本質(zhì)——結(jié)構(gòu)體
struct Book_IMPL {
struct NSObject_IMPL NSObject_IVARS;
NSString *_name;
};
// @property (nonatomic, copy) NSString *bookName;
/* @end */
// @implementation Book
static NSString * _I_Book_name(Book * self, SEL _cmd) { return (*(NSString **)((char *)self + OBJC_IVAR_$Book$_name)); }
extern "C" __declspec(dllimport) void objc_setProperty (id, SEL, long, id, bool, bool);
static void _I_Book_setName_(Book * self, SEL _cmd, NSString *name) {
objc_setProperty (self, _cmd, __OFFSETOFIVAR__(struct Book, _name), (id)name, 0, 1);
}
// @end
對象:對象的本質(zhì)是結(jié)構(gòu)體售淡。
聯(lián)合體位域(union)
再來稍稍剖析下聯(lián)合體位域。聯(lián)合體位域的目的是為了優(yōu)化存儲空間瞄摊,節(jié)省內(nèi)存勋又。
當多個數(shù)據(jù)需要共享內(nèi)存或者多個數(shù)據(jù)每次只取其一時,可以利用聯(lián)合體(union):
1)聯(lián)合體是一個結(jié)構(gòu)换帜;
2)它的所有成員相對于基地址的偏移量都為0楔壤;
3)此結(jié)構(gòu)空間要大到足夠容納最"寬"的成員;
使用位域的主要目的是壓縮存儲惯驼,其大致規(guī)則為:
如果相鄰位域字段的類型相同蹲嚣,且其位寬之和小于類型的sizeof大小,則后面的字段將緊鄰前一個字段存儲祟牲,直到不能容納為止隙畜;
如果相鄰位域字段的類型相同,但其位寬之和大于類型的sizeof大小说贝,則后面的字段將從新的存儲單元開始议惰,其偏移量為其類型大小的整數(shù)倍;
如果相鄰的位域字段的類型不同乡恕,則各編譯器的具體實現(xiàn)有差異言询,VC6采取不壓縮方式,Dev-C++采取壓縮方式傲宜;
如果位域字段之間穿插著非位域字段运杭,則不進行壓縮;
結(jié)構(gòu)體總大小為最大對齊數(shù)的整數(shù)倍函卒。
比如定義一個車的類辆憔,它有前后左右的屬性,每一個屬性就是占4個字節(jié),4 x 4 = 16字節(jié) x 8位 = 128位,這樣就浪費存儲空間虱咧。如果優(yōu)化一下熊榛,使用聯(lián)合體位域,通過0: NO, 1: YES
這樣的形式來存儲前后左右彤钟,那它就能用1個字節(jié)存儲下來来候。
// car.h
@interface Car : NSObject
@property (nonatomic, assign) BOOL front;
@property (nonatomic, assign) BOOL back;
@property (nonatomic, assign) BOOL left;
@property (nonatomic, assign) BOOL right;
// 對象 - 屬性
// 存儲 : 1字節(jié) = 8位 0000 1111 char + 位域 bit 結(jié)構(gòu)體
- (void)setFront:(BOOL)isFront;
- (BOOL)isFront;
- (void)setBack:(BOOL)isBack;
- (BOOL)isBack;
@end
// car.m
#import "Car.h"
#define DirectionFrontMask (1 << 0)
#define DirectionBackMask (1 << 1)
#define DirectionLeftMask (1 << 2)
#define DirectionRightMask (1 << 3)
// ISA 8字節(jié) 64 信息 性能
// 2^64
@interface Car(){
// 聯(lián)合體
union {
char bits;
// 位域
struct { // 0000 1111
char front : 1;
char back : 1;
char left : 1;
char right : 1;
};
} _direction;
}
@end
@implementation Car
- (instancetype)init
{
self = [super init];
if (self) {
// 使它們有相同的基地址
_direction.bits = 0b0000000000;
}
return self;
}
- (void)setFront:(BOOL)isFront {
if (isFront) {
// 如果向前,_direction.bits | DirectionFrontMask逸雹,則代表得到向前為真 营搅,有了新的 _direction.bits = 0b0000000001;
_direction.bits |= DirectionFrontMask;
} else {
// 否則,_direction.bits = 0b0000000000梆砸;
_direction.bits |= ~DirectionFrontMask;
}
NSLog(@"%s",__func__);
}
- (BOOL)isFront{
return _direction.front;
}
- (void)setBack:(BOOL)isBack {
_direction.back = isBack;
NSLog(@"%s",__func__);
}
- (BOOL)isBack{
return _direction.back;
}
@end
通過對基地址進行左移的形式转质,將其4個結(jié)構(gòu)體成員所代表的信息,用一個字節(jié)就表達了帖世,蘋果大量采用了這樣的編碼方式休蟹。
isa的分析
利用之前的objc781源碼工程進行底層isa
的分析:
alloc -> _objc_rootAlloc -> callAlloc -> _objc_rootAllocWithZone -> _class_createInstanceFromZone
會進入以下的代碼
static ALWAYS_INLINE id
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
int construct_flags = OBJECT_CONSTRUCT_NONE,
bool cxxConstruct = true,
size_t *outAllocatedSize = nil)
{
ASSERT(cls->isRealized());
// Read class's info bits all at once for performance
bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
bool hasCxxDtor = cls->hasCxxDtor();
bool fast = cls->canAllocNonpointer();
size_t size;
size = cls->instanceSize(extraBytes);
if (outAllocatedSize) *outAllocatedSize = size;
id obj;
if (zone) {
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
} else {
obj = (id)calloc(1, size);
}
if (slowpath(!obj)) {
if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
return _objc_callBadAllocHandler(cls);
}
return nil;
}
if (!zone && fast) {
obj->initInstanceIsa(cls, hasCxxDtor);
} else {
// Use raw pointer isa on the assumption that they might be
// doing something weird with the zone or RR.
obj->initIsa(cls);
}
if (fastpath(!hasCxxCtor)) {
return obj;
}
construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;
return object_cxxConstructFromClass(obj, cls, construct_flags);
}
其中 initInstanceIsa, initIsa
就發(fā)現(xiàn)isa
蹤跡;繼續(xù)跟入:
inline void
objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
ASSERT(!cls->instancesRequireRawIsa());
ASSERT(hasCxxDtor == cls->hasCxxDtor());
initIsa(cls, true, hasCxxDtor);
}
inline void
objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor)
{
ASSERT(!isTaggedPointer());
if (!nonpointer) {
isa = isa_t((uintptr_t)cls);
} else {
ASSERT(!DisableNonpointerIsa);
ASSERT(!cls->instancesRequireRawIsa());
// 初始化
isa_t newisa(0);
#if SUPPORT_INDEXED_ISA
// iOS系統(tǒng)下走這
ASSERT(cls->classArrayIndex() > 0);
newisa.bits = ISA_INDEX_MAGIC_VALUE;
// isa.magic is part of ISA_MAGIC_VALUE
// isa.nonpointer is part of ISA_MAGIC_VALUE
newisa.has_cxx_dtor = hasCxxDtor;
newisa.indexcls = (uintptr_t)cls->classArrayIndex();
#else
// newisa 就是一個聯(lián)合體日矫,對bits進行默認賦值
newisa.bits = ISA_MAGIC_VALUE;
// isa.magic is part of ISA_MAGIC_VALUE
// isa.nonpointer is part of ISA_MAGIC_VALUE
//
newisa.has_cxx_dtor = hasCxxDtor;
newisa.shiftcls = (uintptr_t)cls >> 3;
#endif
// This write must be performed in a single store in some cases
// (for example when realizing a class because other threads
// may simultaneously try to use the class).
// fixme use atomics here to guarantee single-store and to
// guarantee memory order w.r.t. the class index table
// ...but not too atomic because we don't want to hurt instantiation
isa = newisa;
}
}
分析這段代碼赂弓,isa = isa_t((uintptr_t)cls);
這段代碼是一個關(guān)鍵點,進入isa_t
:
union isa_t {
isa_t() { }
isa_t(uintptr_t value) : bits(value) { }
Class cls;
uintptr_t bits;
#if defined(ISA_BITFIELD)
struct {
ISA_BITFIELD; // defined in isa.h
};
#endif
};
ISA_BITFIELD; // defined in isa.h
終于看到了isa的定義文件哪轿,進入發(fā)現(xiàn)了下面的代碼:
// 針對iOS系統(tǒng)時的isa
# if __arm64__
# define ISA_MASK 0x0000000ffffffff8ULL
# define ISA_MAGIC_MASK 0x000003f000000001ULL
# define ISA_MAGIC_VALUE 0x000001a000000001ULL
# define ISA_BITFIELD \
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)
// 針對macOS系統(tǒng)時的isa
# elif __x86_64__
# define ISA_MASK 0x00007ffffffffff8ULL
# define ISA_MAGIC_MASK 0x001f800000000001ULL
# define ISA_MAGIC_VALUE 0x001d800000000001ULL
# define ISA_BITFIELD \
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)
# else
# error unknown architecture for packed isa
# endif
// SUPPORT_PACKED_ISA
#endif
這就是isa
的結(jié)構(gòu)盈魁,在iOS和macOS有這不同的字節(jié)占比,卻有著相同的定義:
nonpointer:
表示是否對 isa 指針開啟指針優(yōu)化窃诉,0:純isa指針杨耙,1:不?是類對象地址,isa 中包含了類信息、對象的引?計數(shù)等;
has_assoc:
關(guān)聯(lián)對象標志位飘痛,0沒有珊膜,1存在;
has_cxx_dtor:
該對象是否有 C++ 或者 Objc 的析構(gòu)器,如果有析構(gòu)函數(shù),則需要做析構(gòu)邏輯, 如果沒有,則可以更快的釋放對象;
shiftcls:
存儲類指針的值。開啟指針優(yōu)化的情況下宣脉,在 arm64 架構(gòu)中有 33 位?來存儲類指針;
magic:
?于調(diào)試器判斷當前對象是真的對象還是沒有初始化的空間;
weakly_referenced:
志對象是否被指向或者曾經(jīng)指向?個 ARC 的弱變量车柠,沒有弱引?的對象可以更快釋放;
deallocating:
標志對象是否正在釋放內(nèi)存;
has_sidetable_rc:
當對象引?技術(shù)?于 10 時,則需要借?該變量存儲進位;
extra_rc:
當表示該對象的引?計數(shù)值塑猖,實際上是引?計數(shù)值減 1堪遂,
例如,如果對象的引?計數(shù)為 10萌庆,那么 extra_rc 為 9。如果引?計數(shù)?于 10币旧,則需要使?到下?的 has_sidetable_rc践险。
通過以下圖片可以更加形象的理解isa
的結(jié)構(gòu):
其中我們需要關(guān)注的是shiftcls
,它存儲的事類指針的值,事關(guān)整個類的關(guān)鍵信息∥〕妫可以通過調(diào)試objc源碼工程進行實操彭则。
- newisa 初始化
進入到inline void objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor)
,這個方法中占遥,下一個斷點
利用LLDB調(diào)試俯抖,打印一些信息
(lldb) x cls
0x1000020e8: c0 20 00 00 01 00 00 00 40 41 33 00 01 00 00 00 . ......@A3.....
0x1000020f8: 10 e4 32 00 01 00 00 00 00 00 00 00 10 80 00 00 ..2.............
(lldb) x/4gx cls
0x1000020e8: 0x00000001000020c0 0x0000000100334140
0x1000020f8: 0x000000010032e410 0x0000801000000000
(lldb) p newisa
(isa_t) $2 = {
cls = nil
bits = 0
= {
nonpointer = 0
has_assoc = 0
has_cxx_dtor = 0
shiftcls = 0
magic = 0
weakly_referenced = 0
deallocating = 0
has_sidetable_rc = 0
extra_rc = 0
}
}
x == memory read : 打印內(nèi)存情況 ; x/4gx :用4行的形式打印內(nèi)存瓦胎;
這是剛開始創(chuàng)建的newisa
信息情況芬萍,當它執(zhí)行了上圖中newisa.bits = ISA_MAGIC_VALUE;
之后,newisa
就有了新的值:
(isa_t) $4 = {
cls = 0x001d800000000001
bits = 8303511812964353
= {
nonpointer = 1
has_assoc = 0
has_cxx_dtor = 0
shiftcls = 0
magic = 59
weakly_referenced = 0
deallocating = 0
has_sidetable_rc = 0
extra_rc = 0
}
}
cls
不再為nil搔啊,bits中的成員也有了初始值柬祠,其中的magic = 59
,二進制是11 1011
;它對應16進制下64位中的47 ~ 52中的值:
-
關(guān)聯(lián)isa指針與類
newisa.shiftcls = (uintptr_t)cls >> 3;
這個執(zhí)行的操作就是將(uintptr_t)cls
右移三位负芋,再打印它的信息驗證一下漫蛔,newisa
的信息就與類關(guān)聯(lián)起來了。
(lldb) p (uintptr_t)cls
(uintptr_t) $7 = 4294975720
(lldb) p $5 >> 3
(uintptr_t) $8 = 536871965
(lldb) p newisa
(isa_t) $9 = {
cls = LGPerson
bits = 8303516107940073
= {
nonpointer = 1
has_assoc = 0
has_cxx_dtor = 0
shiftcls = 536871965
magic = 59
weakly_referenced = 0
deallocating = 0
has_sidetable_rc = 0
extra_rc = 0
}
}
將isa返回賦值到obj:
在這個頁面繼續(xù)LLDB調(diào)試旧蛾,打印obj對象信息莽龟,在打印它的內(nèi)存信息,其實:
0x001d8001000020e9
就是這個類的isa信息锨天,通過窺探isa
的源碼毯盈,我們有兩種方式獲得LGPerson類關(guān)聯(lián),return (Class)(isa.bits & ISA_MASK);
绍绘,執(zhí)行這段代碼同樣能得出類信息奶镶。
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
}
(lldb) po obj
<LGPerson: 0x101305150>
(lldb) x/4gx 0x101305150
0x101305150: 0x001d8001000020e9 0x0000000000000000
0x101305160: 0x00007fff8b974738 0x000000010063eff0
(lldb) po 0x001d8001000020e9 & 0x00007ffffffffff8ULL
LGPerson
- 通過位移預算再驗證類信息
根據(jù)之前分析的isa結(jié)構(gòu),其中shiftcls
存儲的就是類的信息陪拘,那么就可根據(jù)isa指針厂镇,通過向右位移3位,再向左位移17 + 3 = 20左刽,再通過右位移17還原出isa地址中shiftcls
信息捺信,這個計算的操作就是為了將isa其他位上的信息進行抹零處理,得到了第 3 ~ 46的信息欠痴。(iOS為3~35)
(lldb) x/4gx 0x101305150
0x101305150: 0x001d8001000020e9 0x0000000000000000
0x101305160: 0x00007fff8b974738 0x000000010063eff0
(lldb) p/x 0x001d8001000020e9 >> 3
(long) $13 = 0x0003b0002000041d
(lldb) p/x 0x0003b0002000041d << 20
(long) $14 = 0x0002000041d00000
(lldb) p/x 0x0002000041d00000 >> 17
(long) $15 = 0x00000001000020e8
(lldb) p/x cls
(Class) $16 = 0x00000001000020e8 LGPerson
// 驗證了cls的信息與位移后的結(jié)果