cache的獲取
struct objc_class : objc_object {
Class superclass;
cache_t cache; // formerly cache pointer and vtable
class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags
}
通過(guò)名字我們猜測(cè)cache應(yīng)該是緩存躺坟,但是到底是緩存了什么呢沦补?這個(gè)就需要探索了
首先獲取cache,通過(guò)之前的篇章我們知道咪橙,要獲取cache夕膀,需要通過(guò)首地址編譯16字節(jié)得到虚倒。
LGPerson *p = [LGPerson alloc];
Class pClass = [LGPerson class]; //cache_t
通過(guò)lldb調(diào)試
(lldb) p/x pClass
(Class) $0 = 0x0000000100008608 LGPerson
(lldb) p (cache_t *)0x0000000100008618
(cache_t *) $1 = 0x0000000100008618
(lldb) p *$1
(cache_t) $2 = {
_bucketsAndMaybeMask = {
std::__1::atomic<unsigned long> = {
Value = 4298523568
}
}
= {
= {
_maybeMask = {
std::__1::atomic<unsigned int> = {
Value = 0
}
}
_flags = 32808
_occupied = 0
}
_originalPreoptCache = {
std::__1::atomic<preopt_cache_t *> = {
Value = 0x0000802800000000
}
}
}
}
我們?cè)趤?lái)看看cache_t
struct cache_t {
explicit_atomic<uintptr_t> _bucketsAndMaybeMask; // 8
union {
struct {
explicit_atomic<mask_t> _maybeMask; // 4
#if __LP64__ //__LP64__ Linux/Unix/MacOS 地址長(zhǎng)度64位
uint16_t _flags; // 2
#endif
uint16_t _occupied; // 2
};
explicit_atomic<preopt_cache_t *> _originalPreoptCache; // 8
};
}
從打印結(jié)果來(lái)看,cache里有個(gè)_bucketsAndMaybeMask产舞,_flags魂奥,_occupied,_originalPreoptCache庞瘸,但是我們都不知道這些干嘛用的捧弃,我們到cache結(jié)構(gòu)里面看看有沒(méi)有什么方法可以輸出查看。
void insert(SEL sel, IMP imp, id receiver); 里面有個(gè)insert方法擦囊,而且參數(shù)是sel和imp违霞,似乎就是換成sel和imp。
void cache_t::insert(SEL sel, IMP imp, id receiver)
{
runtimeLock.assertLocked();
// Never cache before +initialize is done
if (slowpath(!cls()->isInitialized())) {
return;
}
if (isConstantOptimizedCache()) {
_objc_fatal("cache_t::insert() called with a preoptimized cache for %s",
cls()->nameForLogging());
}
#if DEBUG_TASK_THREADS
return _collecting_in_critical();
#else
#if CONFIG_USE_CACHE_LOCK
mutex_locker_t lock(cacheUpdateLock);
#endif
ASSERT(sel != 0 && cls()->isInitialized());
// Use the cache as-is if until we exceed our expected fill ratio.
mask_t newOccupied = occupied() + 1; // 1+1
unsigned oldCapacity = capacity(), capacity = oldCapacity;
if (slowpath(isConstantEmptyCache())) {
// Cache is read-only. Replace it.
if (!capacity) capacity = INIT_CACHE_SIZE;//4
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.
}
#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 {// 4*2 = 8
capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
if (capacity > MAX_CACHE_SIZE) {
capacity = MAX_CACHE_SIZE;
}
reallocate(oldCapacity, capacity, true);
}
bucket_t *b = buckets();
mask_t m = capacity - 1; // 4-1=3
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)) {
incrementOccupied();
b[i].set<Atomic, Encoded>(b, 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;
}
} while (fastpath((i = cache_next(i, m)) != begin));
bad_cache(receiver, (SEL)sel);
#endif // !DEBUG_TASK_THREADS
}
通過(guò)insert源碼我們發(fā)現(xiàn)瞬场,insert是將sel和imp放到了buckets里面
接下來(lái)我們看看buckets源碼和bucket_t 定義
struct bucket_t *cache_t::buckets() const
{
uintptr_t addr = _bucketsAndMaybeMask.load(memory_order_relaxed);
return (bucket_t *)(addr & bucketsMask);
}
struct bucket_t {
#if __arm64__
explicit_atomic<uintptr_t> _imp;
explicit_atomic<SEL> _sel;
#else
explicit_atomic<SEL> _sel;
explicit_atomic<uintptr_t> _imp;
#endif
}
似乎被我們發(fā)現(xiàn)了_bucketsAndMaybeMask买鸽,原來(lái)sel和imp緩存在這里
繼續(xù)lldb調(diào)試
(lldb) p $2._bucketsAndMaybeMask
(explicit_atomic<unsigned long>) $3 = {
std::__1::atomic<unsigned long> = {
Value = 4298523568
}
}
(lldb) p $2.buckets()
(bucket_t *) $4 = 0x00000001003643b0
(lldb) p/x 4298523568
(long) $5 = 0x00000001003643b0
到這里我們就知道了,cache緩存的是sel和imp
cache 緩存方法
繼續(xù)lldb調(diào)試
(lldb) p $2.buckets()
(bucket_t *) $4 = 0x00000001003643b0
這邊獲取到了bucket_t 指針贯被,查詢(xún)bucket結(jié)構(gòu)體里發(fā)現(xiàn)有sel()方法
(lldb) p *$4
(bucket_t) $13 = {
_sel = {
std::__1::atomic<objc_selector *> = (null) {
Value = nil
}
}
_imp = {
std::__1::atomic<unsigned long> = {
Value = 0
}
}
}
(lldb) p $4[1]
(bucket_t) $15 = {
_sel = {
std::__1::atomic<objc_selector *> = (null) {
Value = nil
}
}
_imp = {
std::__1::atomic<unsigned long> = {
Value = 0
}
}
}
(lldb) p $4[2]
(bucket_t) $16 = {
_sel = {
std::__1::atomic<objc_selector *> = (null) {
Value = nil
}
}
_imp = {
std::__1::atomic<unsigned long> = {
Value = 0
}
}
}
看起來(lái)這個(gè)數(shù)組里面并沒(méi)有存放數(shù)據(jù)眼五,想來(lái)也是我們并沒(méi)有調(diào)用什么實(shí)例方法
(lldb) p [p saySomething]
2021-06-25 15:26:10.825784+0800 KCObjcBuild[14332:1681446] -[LGPerson saySomething]
(lldb) p $2.buckets()
(bucket_t *) $19 = 0x0000000100629430
(lldb) p *$19
(bucket_t) $20 = {
_sel = {
std::__1::atomic<objc_selector *> = (null) {
Value = nil
}
}
_imp = {
std::__1::atomic<unsigned long> = {
Value = 0
}
}
}
(lldb) p $19[1]
(bucket_t) $21 = {
_sel = {
std::__1::atomic<objc_selector *> = (null) {
Value = nil
}
}
_imp = {
std::__1::atomic<unsigned long> = {
Value = 0
}
}
}
(lldb) p $19[3]
(bucket_t) $22 = {
_sel = {
std::__1::atomic<objc_selector *> = (null) {
Value = nil
}
}
_imp = {
std::__1::atomic<unsigned long> = {
Value = 0
}
}
}
(lldb) p $19[4]
(bucket_t) $23 = {
_sel = {
std::__1::atomic<objc_selector *> = "" {
Value = ""
}
}
_imp = {
std::__1::atomic<unsigned long> = {
Value = 48312
}
}
}
直到第四個(gè)才有數(shù)值
(lldb) p $19[4].sel()
(SEL) $24 = "saySomething"
我們調(diào)用的saySomething找到了,果然這邊緩存的就是我們調(diào)用過(guò)的函數(shù)彤灶,但是為什么緩存在4的位置呢看幼?
接下來(lái)我們又要去研究insert函數(shù)了
cache如何緩存方法
- 第一次進(jìn)來(lái)通過(guò)realloccate開(kāi)辟空間,默認(rèn)開(kāi)辟4個(gè)
capacity = INIT_CACHE_SIZE(INIT_CACHE_SIZE = (1 << INIT_CACHE_SIZE_LOG2), INIT_CACHE_SIZE_LOG2 = 2)
reallocate(oldCapacity, capacity, /* freeOld */false);
這邊雖然開(kāi)辟了capacity個(gè)空間幌陕,但是實(shí)際存放數(shù)據(jù)為capacity-1,因?yàn)樽詈笠粋€(gè)默認(rèn)為1
bucket_t *cache_t::allocateBuckets(mask_t newCapacity)
{
// Allocate one extra bucket to mark the end of the list.
// This can't overflow mask_t because newCapacity is a power of 2.
bucket_t *newBuckets = (bucket_t *)calloc(bytesForCapacity(newCapacity), 1);
bucket_t *end = endMarker(newBuckets, newCapacity); // 獲取最后一個(gè)位置
#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>(newBuckets, (SEL)(uintptr_t)1, (IMP)(newBuckets - 1), nil);
#else
// End marker's sel is 1 and imp points to the first bucket.
end->set<NotAtomic, Raw>(newBuckets, (SEL)(uintptr_t)1, (IMP)newBuckets, nil); // 在最后位置插入1
#endif
if (PrintCaches) recordNewCache(newCapacity);
return newBuckets;
}
- 下次進(jìn)來(lái)查看是否小于3/4 小于則不需要擴(kuò)容直接添加
- 大于3/4 需要擴(kuò)容诵姜,擴(kuò)容規(guī)則capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;(2倍擴(kuò)容)
- 擴(kuò)容后并不會(huì)將舊的數(shù)據(jù)移到新容器里,只存放新數(shù)據(jù)(蘋(píng)果的原則搏熄,新數(shù)據(jù)更有存儲(chǔ)價(jià)值)
- 存放位置的設(shè)計(jì)
bucket_t *b = buckets();
mask_t m = capacity - 1; // 4-1=3
mask_t begin = cache_hash(sel, m); 通過(guò)哈希獲取到begin位置
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)) { 如果I位置為空棚唆,直接存放sel
incrementOccupied();
b[i].set<Atomic, Encoded>(b, sel, imp, cls());
return;
}
if (b[i].sel() == sel) { // 如果i的位置已經(jīng)存放過(guò)當(dāng)前的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)); 如果i已經(jīng)存放過(guò)了心例,哈希碰撞宵凌,通過(guò)cache_next獲取下一個(gè)位置
#if CACHE_END_MARKER
static inline mask_t cache_next(mask_t i, mask_t mask) {
return (i+1) & mask;
}
#elif __arm64__
static inline mask_t cache_next(mask_t i, mask_t mask) {
return i ? i-1 : mask;
}
注意:arm64是往前查找下一個(gè)位置
#else
不通過(guò)源碼打印cache緩存
typedef uint32_t mask_t;
typedef unsigned long uintptr_t;
struct hf_bucket_t {
SEL _sel;
IMP _imp;
};
struct hf_objc_object {
Class _Nonnull isa;
};
struct hf_cache_t {
// uintptr_t _bucketsAndMaybeMask; // 8
struct hf_bucket_t *buckets;
mask_t _maybeMask;
uint16_t _flags;
uint16_t _occupied;
};
struct hf_class_data_bits_t {
// Values are the FAST_ flags above.
uintptr_t bits;
};
struct hf_objc_class : hf_objc_object {
// Class ISA;
Class superclass;
struct hf_cache_t cache; // formerly cache pointer and vtable
struct hf_class_data_bits_t bits;
};
int main(int argc, char * argv[]) {
HFObject *p = [HFObject alloc];
[p say1];
[p say2];
[p say3];
[p say4];
[p say5];
[p say6];
Class pClass = [HFObject class];
hf_objc_class *hfClass = (__bridge hf_objc_class *)pClass;
NSLog(@"cache:%p", hfClass->cache);
NSLog(@"%p---%d---%d", hfClass->cache.buckets, hfClass->cache._maybeMask, hfClass->cache._occupied);
for (int i=0; i<hfClass->cache._maybeMask; i++) {
hf_bucket_t bucket = hfClass->cache.buckets[i];
NSLog(@"%@----%p", NSStringFromSelector(bucket._sel), bucket._imp);
}
return 0;
}
輸出結(jié)果
2021-06-28 13:17:36.115573+0800 cache_tDemo[20872:2889296] -[HFObject say1]
2021-06-28 13:17:36.116421+0800 cache_tDemo[20872:2889296] -[HFObject say2]
2021-06-28 13:17:36.116530+0800 cache_tDemo[20872:2889296] -[HFObject say3]
2021-06-28 13:17:36.116637+0800 cache_tDemo[20872:2889296] -[HFObject say4]
2021-06-28 13:17:36.116735+0800 cache_tDemo[20872:2889296] -[HFObject say5]
2021-06-28 13:17:36.116851+0800 cache_tDemo[20872:2889296] -[HFObject say6]
2021-06-28 13:17:36.116956+0800 cache_tDemo[20872:2889296] cache:0x6000012b0280
2021-06-28 13:17:36.117100+0800 cache_tDemo[20872:2889296] 0x6000012b0280---7---4
2021-06-28 13:17:36.117459+0800 cache_tDemo[20872:2889296] (null)----0x0
2021-06-28 13:17:36.117863+0800 cache_tDemo[20872:2889296] say4----0x5598
2021-06-28 13:17:36.118024+0800 cache_tDemo[20872:2889296] (null)----0x0
2021-06-28 13:17:36.118349+0800 cache_tDemo[20872:2889296] say6----0x5478
2021-06-28 13:17:36.118618+0800 cache_tDemo[20872:2889296] say3----0x55e8
2021-06-28 13:17:36.118914+0800 cache_tDemo[20872:2889296] (null)----0x0
2021-06-28 13:17:36.119255+0800 cache_tDemo[20872:2889296] say5----0x5448
通過(guò)打印cache結(jié)果,可以看出止后,存儲(chǔ)并不是數(shù)組存儲(chǔ)而是通過(guò)哈希存儲(chǔ)瞎惫。在say3的時(shí)候進(jìn)行了擴(kuò)容,那是因?yàn)橐胫辏瑂ay1微饥,say2在加上末尾的1剛好是3/4,在say3的時(shí)候超過(guò)了即進(jìn)行了擴(kuò)容所以沒(méi)有打印say1和say2.