今天我們來研究一下cache_t
是什么
前文書我們說過霹疫,在類的結(jié)構(gòu)體中有個(gè)cache_t迫皱,我們來看看在類中的位置
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() const {
return bits.data();
}
//...此處省略很多坨代碼
}
cache_t的結(jié)構(gòu)
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);
void initializeToEmpty();
unsigned capacity();
bool isConstantEmptyCache();
bool canBeFreed();
//此處省略
cache_t 的結(jié)構(gòu)分三個(gè)架構(gòu)來處理捐名,macOS i386
箩做,模擬器x86
近忙,真機(jī)arm64
下面的三個(gè)宏定義:
-
#define CACHE_MASK_STORAGE_OUTLINED 1
運(yùn)行環(huán)境為macOS 或 模擬器 -
#define CACHE_MASK_STORAGE_HIGH_16 2
運(yùn)行環(huán)境為64位真機(jī) -
#define CACHE_MASK_STORAGE_LOW_4 3
運(yùn)行環(huán)境為非64位真機(jī)等
在真機(jī)環(huán)境下田晚,由于為了進(jìn)一步優(yōu)化內(nèi)存嘱兼,將bucket和mask
寫到了一起,使用_maskAndBuckets
贤徒,通過掩碼
來獲取相應(yīng)數(shù)據(jù)
bucket_t源碼
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__
explicit_atomic<uintptr_t> _imp;
explicit_atomic<SEL> _sel;
#else
explicit_atomic<SEL> _sel;
explicit_atomic<uintptr_t> _imp;
#endif
//....省
public:
inline SEL sel() const { return _sel.load(memory_order::memory_order_relaxed); }
inline IMP imp(Class cls) const {
uintptr_t imp = _imp.load(memory_order::memory_order_relaxed);
if (!imp) return nil;
#if CACHE_IMP_ENCODING == CACHE_IMP_ENCODING_PTRAUTH
SEL sel = _sel.load(memory_order::memory_order_relaxed);
return (IMP)
ptrauth_auth_and_resign((const void *)imp,
ptrauth_key_process_dependent_code,
modifierForSEL(sel, cls),
ptrauth_key_function_pointer, 0);
#elif CACHE_IMP_ENCODING == CACHE_IMP_ENCODING_ISA_XOR
return (IMP)(imp ^ (uintptr_t)cls);
#elif CACHE_IMP_ENCODING == CACHE_IMP_ENCODING_NONE
return (IMP)imp;
#else
#error Unknown method cache IMP encoding.
#endif
}
template <Atomicity, IMPEncoding>
void set(SEL newSel, IMP newImp, Class cls);
};
上面的源碼我們可以得出:IMP
和SEL
就存在bucket_t
中芹壕。
一 通過源碼查找 sel和imp
下一個(gè)斷點(diǎn)
根據(jù)汇四,地址偏移,指針 和類中提供的方法等一系列操作踢涌,查看打印結(jié)果通孽,當(dāng)前斷點(diǎn)前調(diào)用了兩個(gè)方法,_occupied = 2睁壁,說明方法調(diào)用一次背苦,就會(huì)緩存一次。
二 脫離源碼通過項(xiàng)目查找
在工程中我們定義與cache_t結(jié)構(gòu)類似的類潘明,然后進(jìn)行強(qiáng)轉(zhuǎn)行剂。
#import "LGPerson.h"
#import <objc/runtime.h>
typedef uint32_t mask_t; // x86_64 & arm64 asm are less efficient with 16-bits
struct lg_bucket_t {
SEL _sel;
IMP _imp;
};
struct lg_cache_t {
struct lg_bucket_t * _buckets;
mask_t _mask;
uint16_t _flags;
uint16_t _occupied;
};
struct lg_class_data_bits_t {
uintptr_t bits;
};
struct lg_objc_class {
Class ISA;
Class superclass;
struct lg_cache_t cache; // formerly cache pointer and vtable
struct lg_class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags
};
int main(int argc, const char * argv[]) {
@autoreleasepool {
LGPerson *p = [LGPerson alloc];
Class pClass = [LGPerson class]; // objc_clas
[p say1];
[p say2];
[p say3];
[p say4];
// _occupied _mask 是什么 cup - 1
// 會(huì)變化 2-3 -> 2-7
// bucket 會(huì)有丟失 重新申請
// 順序有點(diǎn)問題 哈希
// 線索 :
struct lg_objc_class *lg_pClass = (__bridge struct lg_objc_class *)(pClass);
NSLog(@"%hu - %u",lg_pClass->cache._occupied,lg_pClass->cache._mask);
for (mask_t i = 0; i<lg_pClass->cache._mask; i++) {
// 打印獲取的 bucket
struct lg_bucket_t bucket = lg_pClass->cache._buckets[i];
NSLog(@"%@ - %p",NSStringFromSelector(bucket._sel),bucket._imp);
}
NSLog(@"Hello, World!");
}
return 0;
}
- 我們先只調(diào)用兩個(gè)方法 [p say1] 和[p say2] 我們看打印結(jié)果
- 打開say3和say4方法,再次運(yùn)行看打印
看到上面的打印钳降,我們不禁有些疑問
- 1厚宰、
_mask
是什么? - 2遂填、
_occupied
是什么固阁? - 3、為什么隨著方法調(diào)用的增多城菊,其打印的
occupied
和mask
會(huì)變化备燃? - 4、bucket數(shù)據(jù)為什么會(huì)有丟失的情況凌唬?并齐,例如2-7中,只有say3客税、say4方法有函數(shù)指針
- 5况褪、2-7中say3、say4的打印順序?yàn)槭裁词莝ay4先打印更耻,say3后打印测垛,且還是挨著的,即順序有問題秧均?
- 6食侮、打印的cache_t中的_ocupied為什么是從2開始?
亂序存儲(chǔ)目胡,我們一幫會(huì)想到哈希锯七,那么是否和哈希有關(guān),我們繼續(xù)探索
cache_t底層原理分析
實(shí)現(xiàn):
void cache_t::incrementOccupied()
{
_occupied++;
}
我們看到cache_t中有一個(gè)incrementOccupied
方法:增加Occupied
全局搜索一下哪里調(diào)用了
在cache_t的插入方法里
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());
// Use the cache as-is if it is less than 3/4 full
mask_t newOccupied = occupied() + 1;
unsigned oldCapacity = capacity(), capacity = oldCapacity;
if (slowpath(isConstantEmptyCache())) {
// Cache is read-only. Replace it.
if (!capacity) capacity = INIT_CACHE_SIZE;
reallocate(oldCapacity, capacity, /* freeOld */false);
}
else if (fastpath(newOccupied + CACHE_END_MARKER <= capacity / 4 * 3)) {
// Cache is less than 3/4 full. Use it as-is.
}
else {
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;
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 {
if (fastpath(b[i].sel() == 0)) {
incrementOccupied();
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;
}
} while (fastpath((i = cache_next(i, m)) != begin));
cache_t::bad_cache(receiver, (SEL)sel, cls);
}
首先開辟