和谐学习!不急不躁!!我是你们的老朋友小青龙~
今天我们来探究下objc_class结构体里的cache,command+单机进入cache_t结构:
//objc_class结构如下
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
...
};
//cache_t结构如下
struct cache_t {
private:
explicit_atomic<uintptr_t> _bucketsAndMaybeMask;
union {
struct {
explicit_atomic<mask_t> _maybeMask;
#if __LP64__
uint16_t _flags;
#endif
uint16_t _occupied;
};
explicit_atomic<preopt_cache_t *> _originalPreoptCache;
};
...
};
我们可以看到,它的主要结构是_bucketsAndMaybeMask和联合体。似乎从结构上也看不出什么?只是cache字面上是叫缓存,具体缓存的是属性还是方法还不得而知。
我们先来lldb打印下吧:
从图片上似乎也看不出什么缓存了?但是我们可以分析一下,既然是缓存就肯定有读写的功能,可以在源码struct cache_t结构体内部找找有没有这方面的方法,于是我们看到了这样的代码块:
void insert(SEL sel, IMP imp, id receiver);
我们点击进入insert:
void cache_t::insert(SEL sel, IMP imp, id receiver)
{
bucket_t *b = buckets();
mask_t m = capacity - 1;
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.
do {
if (fastpath(b[i].sel() == 0)) {
//如果是空槽,就sel、imp插入,并且return
incrementOccupied();
b[i].set<Atomic, Encoded>(b, sel, imp, cls());
return;
}
///如果匹配到已经缓存了,也return
if (b[i].sel() == sel) {
// The entry was added to the cache by some other thread
// before we grabbed the cacheUpdateLock.
return;
}
} while (fastpath((i = cache_next(i, m)) != begin));
bad_cache(receiver, (SEL)sel);
#endif // !DEBUG_TASK_THREADS
}
/** 分析
这里出现了一个方法:buckets(),bucket(水桶),是用来装东西的,大概猜测是存放缓存的。
下面是一个do...while循环,
意思就是遍历查找空位插入,在找空位的过程中发现已经有这个sel和imp了,就不用插入,直接return。
do里面的比较是b[i].sel() == sel,意味着sel是通过sel()方法读取。
*/
接下来,我们参考do里面的方式lldb打印:
至此,我们打印了sel,接下来我们想打印一下imp,我们找到了3个名字带imp的:
struct bucket_t {
...
uintptr_t encodeImp(UNUSED_WITHOUT_PTRAUTH bucket_t *base, IMP newImp, UNUSED_WITHOUT_PTRAUTH SEL newSel, Class cls) const {...}
inline IMP rawImp(MAYBE_UNUSED_ISA objc_class *cls) const{...}
inline IMP imp(UNUSED_WITHOUT_PTRAUTH bucket_t *base, Class cls) const {...}
...
/**因为这我们要找的是imp方法,所以筛选出3个方法:encodeImp、rawImp、imp。
目前我们也不知道哪个才是,怎么办呢,只能一个一个试试了,lldb玩起来
*/
};
接下来lldb打印下这三个:
以上是通过LLDB的方法调试,而且依赖于源码环境,一旦想要在自己的工程里看下SEL、IMP就不可行。那么如果我一定要在自己工程里看,有什么办法可以打印呢?
OK,能看到这里的小伙伴,想必都对class的结构有了一定了解(还没了解的同学,请翻牌我之前的文章)。
既然如此,我们何不模仿系统的样子,也自己定一个objc_class结构体呢?说干就干~
自定义 - - - - - - - - - - - - objc_class结构体
因为我们主要分析的是buckets
struct cache_t {
...
public:
struct bucket_t *buckets() const;
...
};
command+单机进入“buckets”:
struct bucket_t *cache_t::buckets() const
{
uintptr_t addr = _bucketsAndMaybeMask.load(memory_order_relaxed);
return (bucket_t *)(addr & bucketsMask);
}
我们可以看到,buckets是通过_bucketsAndMaybeMask去内存里加载的,所以自定义cache_t的结构体内部,可以把_bucketsAndMaybeMask直接换成“struct bucket_t *”,所以最终的自定义结构体如下:
typedef uint32_t mask_t; // x86_64 & arm64 asm are less efficient with 16-bits
///自定义ssj_bucket_t 替换系统的 bucket_t
//这里注意_sel和_imp的先后顺序,错了可能就打印不出来
struct ssj_bucket_t {
SEL _sel;
IMP _imp;//uintptr_t
};
///自定义ssj_cache_t 替换系统的 cache_t
//因为当前操作系统支持LP64位,所以联合体内部不互斥,可以把“uint16_t _flags”拎出来,下面的代码删掉
///struct嵌套struct,因为里面的struct内部数据饱和,所以可以拎出来放到外面的struct中
struct ssj_cache_t {
struct ssj_bucket_t *_buckets;
mask_t _maybeMask;///可以查看内部类型,是uint32_t
uint16_t _flags;
uint16_t _occupied;//当前已缓存的方法数。即数组中已使用了多少位置
};
///自定义ssj_class_data_bits_t 替换系统的 class_data_bits_t
struct ssj_class_data_bits_t {
//friend objc_class;///这行也可以去掉,不是我们关心的
uintptr_t bits;
};
///自定义ssj_objc_class 替换系统的 objc_class
struct ssj_objc_class {
Class ISA;///这里如果不打开,那么在取cache的时候会因为内存偏移不对,导致取到的cache不对,最后的打印结果也不对
Class superclass;
struct ssj_cache_t cache; // formerly cache pointer and vtable
struct ssj_class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags
};
接下来,我们打印一下:
int main(int argc, char * argv[]) {
Student *stu = [Student alloc];
Class stuClass = stu.class;
[stu run];//实例方法
struct ssj_objc_class *ssjClass = (__bridge struct ssj_objc_class *)(stuClass);
NSLog(@"-->%hu \n",ssjClass->cache._occupied);
NSLog(@"-->%hu \n",ssjClass->cache._flags);
NSLog(@"-->%u \n",ssjClass->cache._maybeMask);
for (mask_t i = 0; i< ssjClass->cache._maybeMask;i++) {
struct ssj_bucket_t bucket = ssjClass->cache._buckets[i];
NSLog(@"sel->%@ imp->%pf",NSStringFromSelector(bucket._sel),bucket._imp);
}
...
};
打印结果:
_occupied打印2是因为调用了两个方法:class和run,建议把stu.class改成Student.class。
我们再多调用几个方法:
int main(int argc, char * argv[]) {
Student *stu = [Student alloc];
Class stuClass = stu.class;
[stu run];//实例方法
[stu sleep];//实例方法
[stu dump];//实例方法
[stuClass eat];//类方法
struct ssj_objc_class *ssjClass = (__bridge struct ssj_objc_class *)(stuClass);
NSLog(@"-->%hu \n",ssjClass->cache._occupied);
NSLog(@"-->%hu \n",ssjClass->cache._flags);
NSLog(@"-->%u \n",ssjClass->cache._maybeMask);
for (mask_t i = 0; i< ssjClass->cache._maybeMask;i++) {
struct ssj_bucket_t bucket = ssjClass->cache._buckets[i];
NSLog(@"sel->%@ imp->%pf",NSStringFromSelector(bucket._sel),bucket._imp);
}
...
};
打印结果:
我们发现,
_maybeMask的打印从原先的3变成了7,而且有的方法没打印出来,这是为什么呢?要先探究这个问题,我们首先要知道,以上的这些打印操作都是bucket读取,我们可以先看看内部是怎么插入bucket数据的。
进入cache_t结构,搜索"insert"找到:
void insert(SEL sel, IMP imp, id receiver);
command + 单机进入insert:
void cache_t::insert(SEL sel, IMP imp, id receiver)
{
...
// Use the cache as-is if until we exceed our expected fill ratio.
//每一次insert,occupied就会+1,统计方法的个数
mask_t newOccupied = occupied() + 1;
unsigned oldCapacity = capacity(), capacity = oldCapacity;
///第一次insert,Cache为空,会进入第一个if语句块
if (slowpath(isConstantEmptyCache())) {
// Cache is read-only. Replace it.
if (!capacity) capacity = INIT_CACHE_SIZE;//capacity = 4
///设置_bucketsAndMaybeMask和_maybeMask,以及是否是之前创建的buckets
reallocate(oldCapacity, capacity, /* freeOld */false);
}
else if (fastpath(newOccupied + CACHE_END_MARKER <= cache_fill_ratio(capacity))) {
// Cache is less than 3/4 or 7/8 full. Use it as-is.
/**当左边相加的值小于右边的值,就会进入语句块
分析左边值:
newOccupied每次都会 + 1;
CACHE_END_MARKER是常量 1;
分析右边值:参数capacity = _maybeMask + 1
返回值:capacity * 3 / 4;
根据上面推导如下:
第二次insert会进入这个if判断:
(1+1)+ 1 <= (3 + 1) *3/4
即 3 <= 3,符合要求,不会进入下面那个else if判断;
第三次insert会进入这个if判断:
(2+1)+ 1 <= (3 + 1) *3/4
即 4 <= 3,不符合要求,进入下一个else if判断;
*/
}
#if CACHE_ALLOW_FULL_UTILIZATION
else if (capacity <= FULL_UTILIZATION_CACHE_SIZE && newOccupied + CACHE_END_MARKER <= capacity) {
// Allow 100% cache utilization for small buckets. Use it as-is.
}
#endif
else {
/**
第三次insert会进入这里:
capacity进行两倍扩容
*/
capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
if (capacity > MAX_CACHE_SIZE) {
capacity = MAX_CACHE_SIZE;
}
/**执行了下面的reallocate之后,_maybeMask变为7,
这就是解释了之前控制台打印,_maybeMask打印出7;
注意reallocate最后一个参数,true表示需要清空之前的oldBuckets数据,因为在底层,
扩容实际上是新开辟了内存空间,而数组的平移比较消耗性能,
所以之前旧的buckets就没有加进来,只是把新的加进来。
*/
reallocate(oldCapacity, capacity, true);
}
///获得当前buckets
bucket_t *b = buckets();
mask_t m = capacity - 1;//这就是为什么=3或7的原因了
///得到一个哈希地址
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.
do {
///如果i位当前sel为空就进入语句块
if (fastpath(b[i].sel() == 0)) {
///incrementOccupied里面就是_occupied的值累加1
incrementOccupied();
///sel、imp绑定
b[i].set<Atomic, Encoded>(b, sel, imp, cls());
return;
}
//如果b[i].sel不为空,那就直接返回
if (b[i].sel() == sel) {
// The entry was added to the cache by some other thread
// before we grabbed the cacheUpdateLock.
return;
}
} while (fastpath((i = cache_next(i, m)) != begin));
}
cache_t结构:
oid cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity, bool freeOld)
{
//获取buckets的地址
bucket_t *oldBuckets = buckets();
///开辟newCapacity数量个空间
bucket_t *newBuckets = allocateBuckets(newCapacity);
...
///设置_bucketsAndMaybeMask和_maybeMask,其中_maybeMask = newCapacity - 1
setBucketsAndMask(newBuckets, newCapacity - 1);
///根据freeOld判断,是否需要释放之前的buckets
if (freeOld) {
collect_free(oldBuckets, oldCapacity);
}
}
setBucketsAndMask方法:
void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
{
#ifdef __arm__
...
///_bucketsAndMaybeMask赋值
_bucketsAndMaybeMask.store((uintptr_t)newBuckets, memory_order_relaxed);
...
///_maybeMask赋值
_maybeMask.store(newMask, memory_order_relaxed);
///_occupied等于0是因为这个时候,sel、imp还没绑定
_occupied = 0;
#elif __x86_64__ || i386
///_bucketsAndMaybeMask赋值
_bucketsAndMaybeMask.store((uintptr_t)newBuckets, memory_order_release);
///_maybeMask赋值
_maybeMask.store(newMask, memory_order_release);
///_occupied等于0是因为这个时候,insert方法还没结束
_occupied = 0;
#else
#error Don't know how to do setBucketsAndMask on this architecture.
#endif
}
collect_free方法:
//简单理解就是bucket_t的内存释放,已经垃圾的回收
void cache_t::collect_free(bucket_t *data, mask_t capacity)
{
#if CONFIG_USE_CACHE_LOCK
cacheUpdateLock.assertLocked();
#else
runtimeLock.assertLocked();
#endif
if (PrintCaches) recordDeadCache(capacity);
_garbage_make_room ();
garbage_byte_size += cache_t::bytesForCapacity(capacity);
garbage_refs[garbage_count++] = data;
cache_t::collectNolock(false);
}
cache和buckets关系图 - - - - - - - - - - - -
一个cache只有8个字节大小,而buckets内部的bucket可以成千上百个,所以为了节省空间,也为了提升类信息的加载速度,cache存储的是buckets的地址,可以通过这个地址去访问。
追更 - - - - - - - - - - - -解惑 (20216月30日)
看到这儿,小伙伴们是否有所疑问?反正我是有几个疑问的:
- 前面通过buckets[i]这样的形式得到bucket,难道说buckets也是一个数组吗?
- 在打印cache_t结构的时候,_bucketsAndMaybeMask的value一串数字代表什么呢?
- bucket在insert的时候,要考虑3/4扩容,那么为什么要是3/4,不能是1/2吗?这样做有什么好处呢? 带着这几个问题,我们进行探索,打开objc源码进行lldb调试:
通过打印,我们发现_bucketsAndMaybeMask的value一串数字代表什么呢所代表的地址,恰好指向了buckets的首地址,是否真的这样我们还需要进一步认证,打开源码定位到buckets所在:
struct bucket_t *cache_t::buckets() const
{
uintptr_t addr = _bucketsAndMaybeMask.load(memory_order_relaxed);
return (bucket_t *)(addr & bucketsMask);
}
// _bucketsAndMaybeMask is a buckets_t pointer
// _maybeMask is the buckets mask
static constexpr uintptr_t bucketsMask = ~0ul;
0UL是无符号长整型 0, ~ 表示按位取反,即:0xffff,因此我们可以得出结论,_bucketsAndMaybeMask记录着buckets首地址的信息,buckets()返回的是bucket_t指针。
我们接着查看bucket结构:
struct bucket_t {...}
我们发现,bucket_t是一个结构体,那么为什么它可以以类似数组的方式取获取一个个bucket呢?
这里涉及到一个“内存偏移”的概念,数组也好,bucket访问也罢,都是通过首地址去偏移一定大小的位置来访问。关于内存偏移的概念和论证,数组方面的内存偏移论证,看我之前写的文章isa分析之类的探究(上),搜索"内存偏移"。接下来,我们验证下bucket访问是否也如此:
接下来,用内存平移的方法来访问:
接下来是回答第三个疑问,3/4扩容因为负载因子在0.75的时候利用率比较高,可以有效的避免哈希冲突。
cache - - - - - - - - - - - -insert进一步分析
由于本文章篇幅过长,cache 其他部分的内容,放置另一篇文章:
iOS底层分析之类的探究-cache之 insert、objc_msgSend
代码已上传 百度网盘:
objc4-818.2源码:链接:pan.baidu.com/s/1v09V2YGj…
密码:y8mz
Demo链接:链接:pan.baidu.com/s/1WRE2VpMP…
密码:9y8s