前言
上两篇文章分析了类的结构中的isa和class_data_bits,并用LLDB的方式验证了isa的存储信息和class_data_bits中存储的属性,方法列表以及class_rw_t中ro()函数存储的内容.本篇文章主要探究的是类结构体中的另一个重要属性**cache_t.**
一.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;public: static bucket_t *emptyBuckets(); struct bucket_t *buckets(); mask_t mask(); mask_t occupied(); void incrementOccupied(); void setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask);
...
}
由上面的代码块可以看出 **cache_t**是一个**struct**型数据模块,根据数据的判断条件可以个分为两个:
这个结构体非常长,剔除不必要的参数结构,可以看到
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;
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
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;
};
特别说明:
CACHE_MASK_STORAGE: 当前是使用**mac**调试,所以会进入
// 是真机且是64位系统
#if defined(__arm64__) && __LP64__
#define CACHE_MASK_STORAGE CACHE_MASK_STORAGE_HIGH_16
// 是真机但不是64位系统
#elif defined(__arm64__) && !__LP64__
#define CACHE_MASK_STORAGE CACHE_MASK_STORAGE_LOW_4
// 其他
#else
#define CACHE_MASK_STORAGE CACHE_MASK_STORAGE_OUTLINED
#endif
优化后就可以**mac**看到:
struct cache_t {
explicit_atomic<struct bucket_t *> _buckets;
explicit_atomic<mask_t> _mask;
uint16_t _flags;
uint16_t _occupied;
};
如果在**真机**状态下:
struct cache_t {
explicit_atomic<uintptr_t> _maskAndBuckets;
mask_t _mask_unused; // 猜测是系统暂时没用到的参数。或者苹果还在优化内存,暂时还没有使用到
// mask掩码移动位数
static constexpr uintptr_t maskShift = 48;
// 掩码清零4位
static constexpr uintptr_t maskZeroBits = 4;
// 可以存储的最大mask掩码值(2^16 - 1)
static constexpr uintptr_t maxMask = ((uintptr_t)1 << (64 - maskShift)) - 1;
// 用于从`_maskAndBuckets`中找回`buckets`的指针位置
// (1 << (48 - 4)) - 1 buckets最大位数只有43位
static constexpr uintptr_t bucketsMask = ((uintptr_t)1 << (maskShift - maskZeroBits)) - 1;
// 没有足够的空间来存放buckets了
static_assert(bucketsMask >= MACH_VM_MAX_ADDRESS, "Bucket field doesn't have enough bits for arbitrary pointers.");
uint16_t _flags;
uint16_t _occupied;
}
继续探究优化后mac中带结构:
_buckets
explicit_atomic<struct bucket_t *> _buckets;
数组,存储**bucket_t**的数组,点击跟进到**bucket_t**中
继续探究**_sel**和**_imp**的实现
_mask
掩码(面具)用来获取制定位数的数据,如获取isa中的代表对象信息的33位或者44位数据指针信息
_flags
标记
_occupied
占用位置个数
上面总结cache_t可以用下图表示:
在第五篇文章,通过指针首地址偏移的方式,分析过bits的结构,现在用同样的方式分析下cache_t的结构
首次运行
继续执行下行代码
上图可看出当执行sayhello方法的时候,buckets中存储了一组数据_sel和_imp,那么它们是如何存储,bucket_t又执行了哪些方法才能添加到buckets``数组中的,那么下面我们继续探究
二.cache_t的缓存原理
查看**cache_t**结构,发现**public**处,有**incrementOccupied**函数和**setBucketsAndMask**函数。
看到**incrementOccupied方法就应该想到添加,cache的含义就是缓存,进入incrementOccupied**方法中
全局搜索执行该方法的位置
看到这个方法: void cache_t::insert(Class cls, SEL sel, IMP imp, id receiver)继续探究insert方法是在调用的,全局搜索,运气比较好,只有一个地方
**注意⚠️:**搜索的方式**cache->insert**
分析当**cls->isInitialized()**为真,**获取cache**,把**cls的sel和imp以及receiver**插入到**cache**中
执行到这个部分,就着重分析下**insert函数**都干了什么
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());
// 原occupied计数+1
mask_t newOccupied = occupied() + 1;
// 进入查看: return mask() ? mask()+1 : 0;
// 就是当前mask有值就+1,否则设置初始值0
unsigned oldCapacity = capacity(), capacity = oldCapacity;
// 当前缓存是否为空
if (slowpath(isConstantEmptyCache())) {
// Cache is read-only. Replace it.
// 如果为空,就给空间设置初始值4
// (进入INIT_CACHE_SIZE查看,可以发现就是1<<2,就是二进制100,十进制为4)
if (!capacity) capacity = INIT_CACHE_SIZE;
// 创建新空间(第三个入参为false,表示不需要释放旧空间)
reallocate(oldCapacity, capacity, /* freeOld */false);
}
// CACHE_END_MARKER 就是 1
// 如果当前计数+1 < 空间的 3/4。 就不用处理
// 表示空间够用。 不需要空间扩容
else if (fastpath(newOccupied + CACHE_END_MARKER <= capacity / 4 * 3)) {
// Cache is less than 3/4 full. Use it as-is.
}
// 如果计数大于3/4, 就需要进行扩容操作
else {
// 如果空间存在,就2倍扩容。 如果不存在,就设为初始值4
capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
// 防止超出最大空间值(2^16 - 1)
if (capacity > MAX_CACHE_SIZE) {
capacity = MAX_CACHE_SIZE;
}
// 创建新空间(第三个入参为true,表示需要释放旧空间)
reallocate(oldCapacity, capacity, true);
}
// 读取现在的buckets数组
bucket_t *b = buckets();
// 新的mask值(当前空间最大存储大小)
mask_t m = capacity - 1;
// 使用hash计算当前函数的位置(内部就是sel & m, 就是取余操作,保障begin值在m当前可用空间内)
mask_t begin = cache_hash(sel, m);
mask_t i = begin;
do {
// 如果当前位置为空(空间位置没被占用)
if (fastpath(b[i].sel() == 0)) {
// Occupied计数+1
incrementOccupied();
// 将sle和imp与cls关联起来并写入内存中
b[i].set<Atomic, Encoded>(sel, imp, cls);
return;
}
// 如果当前位置有值(位置被占用)
if (b[i].sel() == sel) {
// The entry was added to the cache by some other thread
// before we grabbed the cacheUpdateLock.
// 直接返回
return;
}
// 如果位置有值,再次使用哈希算法找下一个空位置去写入
// 需要注意的是,cache_next内部有分支:
// 如果是arm64真机环境: 从最大空间位置开始,依次-1往回找空位
// 如果是arm旧版真机、x86_64电脑、i386模拟器: 从当前位置开始,依次+1往后找空位。不能超过最大空间。
// 因为当前空间是没超出mask最大空间的,所以一定有空位置可以放置的。
} while (fastpath((i = cache_next(i, m)) != begin));
// 各种错误处理
cache_t::bad_cache(receiver, (SEL)sel, cls);
}
reallocate : 上面创建新空间并释放旧空间的函数
void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity, bool freeOld)
{
// 读取旧buckets数组
bucket_t *oldBuckets = buckets();
// 创建新空间大小的buckets数组
bucket_t *newBuckets = allocateBuckets(newCapacity);
// Cache's old contents are not propagated.
// This is thought to save cache memory at the cost of extra cache fills.
// fixme re-measure this
// 新空间必须大于0
ASSERT(newCapacity > 0);
// 新空间-1 转为mask_t类型,再与新空间-1 进行判断
ASSERT((uintptr_t)(mask_t)(newCapacity-1) == newCapacity-1);
// 设置新的bucktes数组和mask
// 【重点】我们发现mask就是newCapacity - 1, 表示当前最大可存储空间
setBucketsAndMask(newBuckets, newCapacity - 1);
// 释放旧内存空间
if (freeOld) {
cache_collect_free(oldBuckets, oldCapacity);
}
}
allocateBuckets: 创建新空间大小的buckets数组
bucket_t *allocateBuckets(mask_t newCapacity)
{
// 创建1个bucket
bucket_t *newBuckets = (bucket_t *)
calloc(cache_t::bytesForCapacity(newCapacity), 1);
// 将创建的bucket放到当前空间的最尾部,标记数组的结束
bucket_t *end = cache_t::endMarker(newBuckets, newCapacity);
#if __arm__
// End marker's sel is 1 and imp points BEFORE the first bucket.
// This saves an instruction in objc_msgSend.
end->set<NotAtomic, Raw>((SEL)(uintptr_t)1, (IMP)(newBuckets - 1), nil);
#else
// 将结束标记为sel为1,imp为这个buckets
end->set<NotAtomic, Raw>((SEL)(uintptr_t)1, (IMP)newBuckets, nil);
#endif
// 只是打印记录
if (PrintCaches) recordNewCache(newCapacity);
// 返回这个bucket
return newBuckets;
}
cache_collect_free:释放内存空间
static void cache_collect_free(bucket_t *data, mask_t capacity)
{
#if CONFIG_USE_CACHE_LOCK
cacheUpdateLock.assertLocked();
#else
runtimeLock.assertLocked();
#endif
if (PrintCaches) recordDeadCache(capacity);
// 垃圾房: 开辟空间 (如果首次,就开辟初始空间,如果不是,就空间*2进行拓展)
_garbage_make_room ();
// 将当前扩容后的capacity加入垃圾房的尺寸中,便于后续释放。
garbage_byte_size += cache_t::bytesForCapacity(capacity);
// 将当前新数据data存放到 garbage_count 后面 这样可以释放前面的,而保留后面的新值
garbage_refs[garbage_count++] = data;
// 不记录之前的缓存 = 【清空之前的缓存】。
cache_collect(false);
}
以上就是cache_t的代码分析流程,为了方便理解和查看,下面用流程图的方式具体实现下:
总结:
cache_t作为类结构体中的一个元素,作用缓存类的sel和imp.使得类在调用方法时能快速的发送消息,减少类查找方法的时间.到这片文章为止,类的结构以及分析完成.下篇文章开始分析类的方法执行,具体结构如下:
特做此标记,以后方便复习...