前言
类的结构objc_class中,除了isa,superclass和bits,还有一个非常重要的成员:cache,接下来我们就探索下这个cache
cache_t内存结构
研究肯定要从源码开始:
struct cache_t {
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED
explicit_atomic<struct bucket_t *> _buckets;
explicit_atomic<mask_t> _mask;
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16
explicit_atomic<uintptr_t> _maskAndBuckets;
mask_t _mask_unused;
// How much the mask is shifted by.
static constexpr uintptr_t maskShift = 48;
// Additional bits after the mask which must be zero. msgSend
// takes advantage of these additional bits to construct the value
// `mask << 4` from `_maskAndBuckets` in a single instruction.
static constexpr uintptr_t maskZeroBits = 4;
// The largest mask value we can store.
static constexpr uintptr_t maxMask = ((uintptr_t)1 << (64 - maskShift)) - 1;
// The mask applied to `_maskAndBuckets` to retrieve the buckets pointer.
static constexpr uintptr_t bucketsMask = ((uintptr_t)1 << (maskShift - maskZeroBits)) - 1;
// Ensure we have enough bits for the buckets pointer.
static_assert(bucketsMask >= MACH_VM_MAX_ADDRESS, "Bucket field doesn't have enough bits for arbitrary pointers.");
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
// _maskAndBuckets stores the mask shift in the low 4 bits, and
// the buckets pointer in the remainder of the value. The mask
// shift is the value where (0xffff >> shift) produces the correct
// mask. This is equal to 16 - log2(cache_size).
explicit_atomic<uintptr_t> _maskAndBuckets;
mask_t _mask_unused;
static constexpr uintptr_t maskBits = 4;
static constexpr uintptr_t maskMask = (1 << maskBits) - 1;
static constexpr uintptr_t bucketsMask = ~maskMask;
#else
#error Unknown cache mask storage type.
#endif
#if __LP64__
uint16_t _flags;
#endif
uint16_t _occupied;
...
}
分析源码,可以逐级精简:
精简宏定义:
struct cache_t {
#if // mac或者模拟器
explicit_atomic<struct bucket_t *> _buckets;
explicit_atomic<mask_t> _mask;
#elif // 真机
explicit_atomic<uintptr_t> _maskAndBuckets;
mask_t _mask_unused;
// How much the mask is shifted by.
static constexpr uintptr_t maskShift = 48;
// Additional bits after the mask which must be zero. msgSend
// takes advantage of these additional bits to construct the value
// `mask << 4` from `_maskAndBuckets` in a single instruction.
static constexpr uintptr_t maskZeroBits = 4;
// The largest mask value we can store.
static constexpr uintptr_t maxMask = ((uintptr_t)1 << (64 - maskShift)) - 1;
// The mask applied to `_maskAndBuckets` to retrieve the buckets pointer.
static constexpr uintptr_t bucketsMask = ((uintptr_t)1 << (maskShift - maskZeroBits)) - 1;
// Ensure we have enough bits for the buckets pointer.
static_assert(bucketsMask >= MACH_VM_MAX_ADDRESS, "Bucket field doesn't have enough bits for arbitrary pointers.");
#elif // 真机,非LP64
// _maskAndBuckets stores the mask shift in the low 4 bits, and
// the buckets pointer in the remainder of the value. The mask
// shift is the value where (0xffff >> shift) produces the correct
// mask. This is equal to 16 - log2(cache_size).
explicit_atomic<uintptr_t> _maskAndBuckets;
mask_t _mask_unused;
static constexpr uintptr_t maskBits = 4;
static constexpr uintptr_t maskMask = (1 << maskBits) - 1;
static constexpr uintptr_t bucketsMask = ~maskMask;
#else
#error Unknown cache mask storage type.
#endif
#if LP64
uint16_t _flags;
#endif
uint16_t _occupied;
...
}
精简static变量
分析下变量名_maskAndBuckets和static变量名称,可猜测,static的变量应该是一些掩码运算相关,_maskAndBuckets类似于isa那样,存储了将mask和buckets数据存到一个变量中,可以精简
struct cache_t {
#if // mac或者模拟器
explicit_atomic<struct bucket_t *> _buckets;
explicit_atomic<mask_t> _mask;
#elif // 真机
explicit_atomic<uintptr_t> _maskAndBuckets;
mask_t _mask_unused;
#elif // 真机,非LP64
explicit_atomic<uintptr_t> _maskAndBuckets;
mask_t _mask_unused;
#else
#error Unknown cache mask storage type.
#endif
#if LP64
uint16_t _flags;
#endif
uint16_t _occupied;
...
}
精简explicit_atomic
explicit_atomic看定义是一个泛型结构,从名字分析,应该是为了数据操作的原子性,与内存结构没有太大关系,可精简:
struct cache_t {
#if // mac或者模拟器
struct bucket_t * _buckets;
mask_t _mask;
#elif // 真机
uintptr_t _maskAndBuckets;
mask_t _mask_unused;
#elif // 真机,非LP64
uintptr_t _maskAndBuckets;
mask_t _mask_unused;
#else
#error Unknown cache mask storage type.
#endif
#if LP64
uint16_t _flags;
#endif
uint16_t _occupied;
...
}
完整的精简后结构
添加一些对于成员的操作接口后,完整的精简结构,如下:
struct cache_t {
#if // mac或者模拟器
struct bucket_t * _buckets;
mask_t _mask;
#elif // 真机
uintptr_t _maskAndBuckets;
mask_t _mask_unused;
#elif // 真机,非LP64
uintptr_t _maskAndBuckets;
mask_t _mask_unused;
#else
#error Unknown cache mask storage type.
#endif
#if LP64
uint16_t _flags;
#endif
uint16_t _occupied;
struct bucket_t *buckets();
mask_t mask();
mask_t occupied();
void incrementOccupied();
}
cache_t的存储内容
分析完内存结构后,我们肯定想知道具体存储的数据是什么。主要的存储变量应该是buckets,猜测对应的应该是个数组或者说集合。
bucket_t
精简后的bucket_t源码定义:
struct bucket_t {
private:
#if __arm64__
uintptr_t _imp;
SEL _sel;
#else
SEL _sel;
uintptr_t _imp;
#endif
public:
inline SEL sel()
inline IMP imp(Class cls)
}
即一个bucket_t存储了一对数据:sel、imp,有两个重要api来获取对应的数据。
验证
我们通过代码调试来看一下cache和bucket具体存储的内容
int main(int argc, const char * argv[]) {
@autoreleasepool {
LGPerson *p = [LGPerson alloc];
Class pClass = [LGPerson class];
[p sayHello];
[p sayCode];
[p sayMaster];
}
return 0;
}
在sayHello、sayCode调用行设断点.
方法调用前
在sayHello调用行设断点,LLDB指令打印下cache.利用内存偏移,cache在class中偏移了16字节(isa+superclass)。
(lldb) p/x pClass //类对象地址
(Class) $0 = 0x0000000100002298 LGPerson
(lldb) p (cache_t*)0x00000001000022a8 // 地址偏移16字节
(cache_t *) $1 = 0x00000001000022a8
(lldb) p *$1 // 打印cache_t
(cache_t) $2 = {
_buckets = {
std::__1::atomic<bucket_t *> = 0x00000001003eb460 {
_sel = {
std::__1::atomic<objc_selector *> = 0x0000000000000000
}
_imp = {
std::__1::atomic<unsigned long> = 0
}
}
}
_mask = {
std::__1::atomic<unsigned int> = 0
}
_flags = 32804
_occupied = 0 // _occupied 为0
}
(lldb) p (bucket_t*)$2.buckets() // 读取buckets
(bucket_t *) $3 = 0x00000001003eb460
(lldb) p $3->sel()
(SEL) $4 = <no value available>
(lldb) p $3->imp(pClass)
(IMP) $5 = 0x0000000000000000
(lldb)
方法调用前,cache_t的buckets内没有内容,occupied = 0
调用第一个方法后
断点sayCode处再次打印:
(lldb) p *$1
(cache_t) $6 = {
_buckets = {
std::__1::atomic<bucket_t *> = 0x0000000100706a60 {
_sel = {
std::__1::atomic<objc_selector *> = 0x0000000100000e3c
}
_imp = {
std::__1::atomic<unsigned long> = 11928
}
}
}
_mask = {
std::__1::atomic<unsigned int> = 3
}
_flags = 32804
_occupied = 1
}
(lldb) p $6.buckets()
(bucket_t *) $7 = 0x0000000100706a60
(lldb) p $7->sel()
(SEL) $8 = "sayHello"
(lldb) p $7->imp(pClass)
(IMP) $9 = 0x0000000100000c00 (KCObjc`-[LGPerson sayHello])
(lldb)
cache中buckets有值,sel是"sayHello",imp是对应的函数指针, occupied=1。
继续调用方法
(lldb) p *$1
(cache_t) $10 = {
_buckets = {
std::__1::atomic<bucket_t *> = 0x0000000102b04270 {
_sel = {
std::__1::atomic<objc_selector *> = 0x0000000100000e3c
}
_imp = {
std::__1::atomic<unsigned long> = 11928
}
}
}
_mask = {
std::__1::atomic<unsigned int> = 3
}
_flags = 32804
_occupied = 2
}
(lldb) p $10.buckets()
(bucket_t *) $11 = 0x0000000102b04270
(lldb) p $11->sel()
(SEL) $12 = "sayHello"
(lldb) p (bucket_t *)0x0000000102b04280
(bucket_t *) $13 = 0x0000000102b04280
(lldb) p $13->sel()
(SEL) $14 = "sayCode"
(lldb)
cache中buckets存储了两个bucket_t指针,分别是"sayHello""sayCode"以及对应的imp occupied=2。
总结: cache_t中存储了调用过的方法的sel和imp,即缓存了最近调用的方法
cache如何存储的sel和imp
incrementOccupied
cache存储增长时,_occupied会跟着增长。搜索_occupied,发现除了初始化为0外,只有incrementOccupied中会增长_occupied,可以得出cache存储时会调用incrementOccupied
void cache_t::incrementOccupied()
{
_occupied++;
}
cahce_t::insert: 向cache中增加一条sel和imp记录
搜索incrementOccupied,只有cache_t::insert中使用。分析源码:
ALWAYS_INLINE
void cache_t::insert(Class cls, SEL sel, IMP imp, id receiver)
{
#if CONFIG_USE_CACHE_LOCK
cacheUpdateLock.assertLocked();
#else
runtimeLock.assertLocked();
#endif
ASSERT(sel != 0 && cls->isInitialized());
// 1. 容量控制:开辟或者扩容
// Use the cache as-is if it is less than 3/4 full
mask_t newOccupied = occupied() + 1;
unsigned oldCapacity = capacity(), capacity = oldCapacity;
// 1.1 如果cache为空,开辟空间:初始容量为4
if (slowpath(isConstantEmptyCache())) {
// Cache is read-only. Replace it.
if (!capacity) capacity = INIT_CACHE_SIZE;
reallocate(oldCapacity, capacity, /* freeOld */false);
}
// 1.2 如果插入后,占用将会少于容量的四分之三,不做处理
else if (fastpath(newOccupied + CACHE_END_MARKER <= capacity / 4 * 3)) {
// Cache is less than 3/4 full. Use it as-is.
}
// 1.3 插入后,占用等于或超过四分之三,扩容容量翻倍。注意扩容是重新分配空间,原来的存储将会释放,即以前的数据会丢失掉
else {
capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
if (capacity > MAX_CACHE_SIZE) {
capacity = MAX_CACHE_SIZE;
}
reallocate(oldCapacity, capacity, true);
}
// 2. 开始插入数据
bucket_t *b = buckets();
mask_t m = capacity - 1;
// 2.1 利用hash算法,计算出插入的位置
mask_t begin = cache_hash(sel, m);
mask_t i = begin;
// Scan for the first unused slot and insert there.
// There is guaranteed to be an empty slot because the
// minimum size is 4 and we resized at 3/4 full.
do {
// 2.2 如果该位置为空,直接插入
if (fastpath(b[i].sel() == 0)) {
incrementOccupied();
b[i].set<Atomic, Encoded>(sel, imp, cls);
return;
}
// 2.3 如果该位置已经插入对应的sel,直接返回
if (b[i].sel() == sel) {
// The entry was added to the cache by some other thread
// before we grabbed the cacheUpdateLock.
return;
}
// 2.4 否则,该位置已经放了别的sel,则需要通过chche_next找到下一个存储位置
} while (fastpath((i = cache_next(i, m)) != begin));
// 2.5 出错处理
cache_t::bad_cache(receiver, (SEL)sel, cls);
}
cache_hash散列函数
{
return (mask_t)(uintptr_t)sel & mask;
}
三列函数:sel的地址和掩码mask进行位与运算。mask值是容量减去1,确保计算出的index不会超出。
cache_nexthash碰撞的解决
#if __arm__ || __x86_64__ || __i386__
// objc_msgSend has few registers available.
// Cache scan increments and wraps at special end-marking bucket.
#define CACHE_END_MARKER 1
static inline mask_t cache_next(mask_t i, mask_t mask) {
return (i+1) & mask;
}
#elif __arm64__
// objc_msgSend has lots of registers available.
// Cache scan decrements. No end marker needed.
#define CACHE_END_MARKER 0
static inline mask_t cache_next(mask_t i, mask_t mask) {
return i ? i-1 : mask;
}
#else
#error unknown architecture
#endif
当位置冲突是,采用开放定址法查找下一个位置:基本上就是向前或者向后注意查找。
总结: cache采用散列表的方式存储方法sel和imp:
- 初始容量为4
- 超过3/4则扩容,同时以前的存储丢弃
- 采用sel作为key,进行hash计算,确定存储位置
- 采用开放定址法解决hash碰撞