类的结构源码如下,前面分析了isa,superclass,bits都已经分析过了,现在来看看cache,首先查看cache所在的位置。
首先贴源码:
struct objc_class : objc_object {
// Class ISA;
Class superclass;
cache_t cache; // formerly cache pointer and vtable
class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags
class_rw_t *data() {
return bits.data();
}
}
cache_t在结构体objc_class内,ISA占8个字节,superclass占8个字节,所以cache_t存在于步长为8的第三个位置。
以下是cache_t源码,结构体cache_t中有bucket_t结构体以及类型为mask_t的_mask和_occupied共占16个字节
struct cache_t {
struct bucket_t *_buckets; // 8
//typedef uint32_t mask_t;
mask_t _mask; // 4
mask_t _occupied; // 4
public:
struct bucket_t *buckets();
mask_t mask();
mask_t occupied();
void incrementOccupied();
void setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask);
void initializeToEmpty();
mask_t capacity();
bool isConstantEmptyCache();
bool canBeFreed();
static size_t bytesForCapacity(uint32_t cap);
static struct bucket_t * endMarker(struct bucket_t *b, uint32_t cap);
void expand();
void reallocate(mask_t oldCapacity, mask_t newCapacity);
struct bucket_t * find(cache_key_t key, id receiver);
static void bad_cache(id receiver, SEL sel, Class isa) __attribute__((noreturn));
};
接着查看查看bucket_t的结构,可以看出这里面有imp和key
struct bucket_t {
private:
// IMP-first is better for arm64e ptrauth and no worse for arm64.
// SEL-first is better for armv7* and i386 and x86_64.
#if __arm64__
MethodCacheIMP _imp;
cache_key_t _key;
#else
cache_key_t _key;
MethodCacheIMP _imp;
#endif
public:
inline cache_key_t key() const { return _key; }
inline IMP imp() const { return (IMP)_imp; }
inline void setKey(cache_key_t newKey) { _key = newKey; }
inline void setImp(IMP newImp) { _imp = newImp; }
void set(cache_key_t newKey, IMP newImp);
};
首先查看cache调用过程,此处接iOS底层 消息查找流程
cache_fill
void cache_fill(Class cls, SEL sel, IMP imp, id receiver)
{
#if !DEBUG_TASK_THREADS
mutex_locker_t lock(cacheUpdateLock);
cache_fill_nolock(cls, sel, imp, receiver);
#else
_collecting_in_critical();
return;
#endif
}
查看cache_fill_nolock
static void cache_fill_nolock(Class cls, SEL sel, IMP imp, id receiver)
{
cacheUpdateLock.assertLocked();
// Never cache before +initialize is done
if (!cls->isInitialized()) return;
// Make sure the entry wasn't added to the cache by some other thread
// before we grabbed the cacheUpdateLock.
if (cache_getImp(cls, sel)) return;
cache_t *cache = getCache(cls);
cache_key_t key = getKey(sel);
// Use the cache as-is if it is less than 3/4 full
mask_t newOccupied = cache->occupied() + 1;
mask_t capacity = cache->capacity();
if (cache->isConstantEmptyCache()) {
// Cache is read-only. Replace it.
cache->reallocate(capacity, capacity ?: INIT_CACHE_SIZE);
}
else if (newOccupied <= capacity / 4 * 3) {
// Cache is less than 3/4 full. Use it as-is.
}
else {
// Cache is too full. Expand it.
cache->expand();
}
// 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.
bucket_t *bucket = cache->find(key, receiver);
if (bucket->key() == 0) cache->incrementOccupied();
bucket->set(key, imp);
}
occupied
mask_t cache_t::occupied()
{
return _occupied;
}
capacity
mask_t cache_t::capacity()
{
return mask() ? mask()+1 : 0;
}
reallocate 重新分配
void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity)
{
bool freeOld = canBeFreed();
bucket_t *oldBuckets = 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
assert(newCapacity > 0);
assert((uintptr_t)(mask_t)(newCapacity-1) == newCapacity-1);
setBucketsAndMask(newBuckets, newCapacity - 1);
if (freeOld) {
cache_collect_free(oldBuckets, oldCapacity);
cache_collect(false);
}
}
expand扩容
void cache_t::expand()
{
cacheUpdateLock.assertLocked();
uint32_t oldCapacity = capacity();
uint32_t newCapacity = oldCapacity ? oldCapacity*2 : INIT_CACHE_SIZE;
if ((uint32_t)(mask_t)newCapacity != newCapacity) {
// mask overflow - can't grow further
// fixme this wastes one bit of mask
newCapacity = oldCapacity;
}
reallocate(oldCapacity, newCapacity);
}
find 查找相应的存储
bucket_t * cache_t::find(cache_key_t k, id receiver)
{
assert(k != 0);
bucket_t *b = buckets();
mask_t m = mask();
// 通过cache_hash函数【begin = k & m】计算出key值 k 对应的 index值 begin,用来记录查询起始索引
mask_t begin = cache_hash(k, m);
// begin 赋值给 i,用于切换索引
mask_t i = begin;
do {
if (b[i].key() == 0 || b[i].key() == k) {
//用这个i从散列表取值,如果取出来的bucket_t的 key = k,则查询成功,返回该bucket_t,
//如果key = 0,说明在索引i的位置上还没有缓存过方法,同样需要返回该bucket_t,用于中止缓存查询。
return &b[I];
}
} while ((i = cache_next(i, m)) != begin);
// 这一步其实相当于 i = i-1,回到上面do循环里面,相当于查找散列表上一个单元格里面的元素,再次进行key值 k的比较,
//当i=0时,也就i指向散列表最首个元素索引的时候重新将mask赋值给i,使其指向散列表最后一个元素,重新开始反向遍历散列表,
//其实就相当于绕圈,把散列表头尾连起来,不就是一个圈嘛,从begin值开始,递减索引值,当走过一圈之后,必然会重新回到begin值,
//如果此时还没有找到key对应的bucket_t,或者是空的bucket_t,则循环结束,说明查找失败,调用bad_cache方法。
//
Class cls = (Class)((uintptr_t)this - offsetof(objc_class, cache));
cache_t::bad_cache(receiver, (SEL)k, cls);
}
incrementOccupied occupied占用+1
void cache_t::incrementOccupied()
{
_occupied++;
}
cache验证
1.新建类
// TWPerson.h
#import
NS_ASSUME_NONNULL_BEGIN
@interface TWPerson : NSObject
- (void)talk1;
- (void)talk2;
- (void)talk3;
@end
// TWPerson.m
#import "TWPerson.h"
@implementation TWPerson
- (void)talk1 {
NSLog(@"%s", __func__);
}
- (void)talk2 {
NSLog(@"%s", __func__);
}
- (void)talk3 {
NSLog(@"%s", __func__);
}
@end
2.调用和断点位置
3.lldb调试,在每个断点处打印调试结果
2020-01-02 16:04:28.414128+0800 TWDemo[35887:282758] Hello, World!
2020-01-02 16:04:28.414324+0800 TWDemo[35887:282758] -[TWPerson talk1]//断点1
(lldb) x/4gx p.class
0x1000012b0: 0x001d800100001289 0x0000000100b34140
0x1000012c0: 0x0000000101a29050 0x0000000300000003
(lldb) p (cache_t *)0x1000012c0
(cache_t *) $1 = 0x00000001000012c0
(lldb) p $1[0]
(cache_t) $2 = {
_buckets = 0x0000000101a29050
_mask = 3
_occupied = 3
}
(lldb) p $2._buckets[0]
(bucket_t) $3 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[1]
(bucket_t) $4 = {
_key = 4294971209
_imp = 0x0000000100000d40 (TWDemo`-[TWPerson talk1] at TWPerson.m:16)
}
(lldb) p $2._buckets[2]
(bucket_t) $5 = {
_key = 4309412966
_imp = 0x00000001003c7f90 (libobjc.A.dylib`::-[NSObject class]() at NSObject.mm:1988)
}
(lldb) p $2._buckets[3]
(bucket_t) $6 = {
_key = 140735242647635
_imp = 0x00000001003c8300 (libobjc.A.dylib`::-[NSObject respondsToSelector:](SEL) at NSObject.mm:2046)
}
(lldb) p $2._buckets[4]
(bucket_t) $7 = {
_key = 1
_imp = 0x0000000101a29050 (0x0000000101a29050)
}
(lldb) p $2._buckets[45]
(bucket_t) $8 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[5]
(bucket_t) $9 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[6]
(bucket_t) $10 = {
_key = 0
_imp = 0x0000000000000000
}
2020-01-02 16:05:45.153536+0800 TWDemo[35887:282758] -[TWPerson talk2]//断点2
(lldb) p $2._buckets[0]
(bucket_t) $11 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[1]
(bucket_t) $12 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[2]
(bucket_t) $13 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[3]
(bucket_t) $14 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[4]
(bucket_t) $15 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[5]
(bucket_t) $16 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[6]
(bucket_t) $17 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[7]
(bucket_t) $18 = {
_key = 4294971215
_imp = 0x0000000100000d70 (TWDemo`-[TWPerson talk2] at TWPerson.m:20)
}
(lldb) p $2._buckets[8]
(bucket_t) $19 = {
_key = 1
_imp = 0x0000000101f349f0 (0x0000000101f349f0)
}
(lldb) p $2._buckets[9]
(bucket_t) $20 = {
_key = 0
_imp = 0x0000000000000000
}
2020-01-02 16:06:23.964333+0800 TWDemo[35887:282758] -[TWPerson talk3]//断点3
(lldb) p $2._buckets[0]
(bucket_t) $21 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[1]
(bucket_t) $22 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[2]
(bucket_t) $23 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[3]
(bucket_t) $24 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[4]
(bucket_t) $25 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[5]
(bucket_t) $26 = {
_key = 4294971221
_imp = 0x0000000100000da0 (TWDemo`-[TWPerson talk3] at TWPerson.m:24)
}
(lldb) p $2._buckets[6]
(bucket_t) $27 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[7]
(bucket_t) $28 = {
_key = 4294971215
_imp = 0x0000000100000d70 (TWDemo`-[TWPerson talk2] at TWPerson.m:20)
}
(lldb) p $2._buckets[8]
(bucket_t) $29 = {
_key = 1
_imp = 0x0000000101f349f0 (0x0000000101f349f0)
}
(lldb) p $2._buckets[9]
(bucket_t) $30 = {
_key = 0
_imp = 0x0000000000000000
}
(lldb) p $2._buckets[10]
(bucket_t) $31 = {
_key = 140735685066801
_imp = 0x00007fff9484c250 ((void *)0x00007fff37421928)
}
2020-01-02 16:07:23.480901+0800 TWDemo[35887:282758]
Program ended with exit code: 0
分析
通过调试,在断点1处打印的时候,可以找到talk1方法,断点2处,可以找到talk2方法但是没有talk1方法,断点3处,可以找到talk2和talk3方法,但是没有talk1方法,因为在调用talk2的时候,缓存超出容量,进行了扩容,清除之前的缓存填充新的缓存导致的。
附上流程图: