前言
這篇文章主要是分析cache_t
流程。通過源碼探索下類的cache_t
主要緩存了哪些信息,又是怎么緩存的。
分析環境:arm64 構架,iPhone 真機 編譯環境下。
cache的存儲內容
我們先來看下cache_t的源碼
struct cache_t {
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED//macOS、模擬器 -- 主要是架構區分
// explicit_atomic 顯示原子性,目的是為了能夠 保證 增刪改查時 線程的安全性
//等價于 struct bucket_t * _buckets;
//_buckets 中放的是 sel imp
//_buckets的讀取 有提供相應名稱的方法 buckets()
explicit_atomic<struct bucket_t *> _buckets;
explicit_atomic<mask_t> _mask;
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16 //64位真機
explicit_atomic<uintptr_t> _maskAndBuckets;//寫在一起的目的是為了優化
mask_t _mask_unused;
//以下都是掩碼,即mask -- 類似于isa的掩碼,即位域
// 掩碼省略....
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4 //非64位 真機
explicit_atomic<uintptr_t> _maskAndBuckets;
mask_t _mask_unused;
//以下都是掩碼,即mask -- 類似于isa的掩碼,即位域
// 掩碼省略....
#else
#error Unknown cache mask storage type.
#endif
#if __LP64__
uint16_t _flags;
#endif
uint16_t _occupied;
public: //對外公開可以調用的方法
static bucket_t *emptyBuckets(); // 清空buckets
struct bucket_t *buckets(); //這個方法的實現很簡單就是_buckets對外的一個獲取函數
mask_t mask(); //獲取緩存容量_mask
mask_t occupied(); //獲取已經占用的緩存個數_occupied
void incrementOccupied(); //增加緩存,_occupied自++
void setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask); //這個函數是設置一個新的Buckets
void initializeToEmpty();
unsigned capacity();
bool isConstantEmptyCache();
bool canBeFreed();
}
我們再來看下bucket_t
的源碼實現
struct bucket_t {
private:
#if __arm64__ //真機
//explicit_atomic 是加了原子性的保護
explicit_atomic<uintptr_t> _imp;
explicit_atomic<SEL> _sel;
#else //非真機
explicit_atomic<SEL> _sel;
explicit_atomic<uintptr_t> _imp;
#endif
//方法等其他部分省略
}
通過源碼分析可知,cache
中緩存的是sel-imp
,也就是方法索引和方法實現。
通過例子分析cache的緩存內容
準備工作,定義一個WJPerson
類,然后添加一下方法和屬性
@interface WJPerson : NSObject
{
NSString *habby;
}
@property (nonatomic, copy) NSString *name;
- (void)sayHello;
- (void)sayHowAreYou;
- (void)sayIamFine;
- (void)sayThanksYou;
- (void)sayAndYou;
+ (void)sayGoodbye;
@end
@implementation WJPerson
- (void)sayHello{
NSLog(@"%s",__func__);
}
- (void)sayHowAreYou{
NSLog(@"%s",__func__);
}
- (void)sayIamFine{
NSLog(@"%s",__func__);
}
- (void)sayThanksYou{
NSLog(@"%s",__func__);
}
- (void)sayAndYou{
NSLog(@"%s",__func__);
}
+ (void)sayGoodbye{
NSLog(@"%s",__func__);
}
@end
然后在main.m
中創建一個對象,并調用方法打好斷點,然后運行啟動。
sel
和imp
了呢。有的同學會說是init
,到底是不是呢,接下來我們驗證一下。init
方法。接下來我們走的第二個斷點,看下接下來的數據。我們再執行下上面的步驟
init
方法嗎。是不是不在第一個位置啊,我們再看一下buckets
中的其他元素。lldb
這樣找太麻煩了,有沒有一種更簡單的方式。接下來我們通過更簡單的方式來看一下。
typedef uint32_t mask_t; // x86_64 & arm64 asm are less efficient with 16-bits
struct wj_bucket_t {
SEL _sel;
IMP _imp;
};
struct wj_cache_t {
struct wj_bucket_t * _buckets;
mask_t _mask;
uint16_t _flags;
uint16_t _occupied;
};
struct wj_class_data_bits_t {
uintptr_t bits;
};
struct wj_objc_class {
Class ISA;
Class superclass;
struct wj_cache_t cache; // formerly cache pointer and vtable
struct wj_class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags
};
int main(int argc, const char * argv[]) {
@autoreleasepool {
WJPerson *person = [[WJPerson alloc] init];
Class personClass = [person class];
[person sayHello];
// [person sayHowAreYou];
// [person sayIamFine];
// [person sayThanksYou];
// [person sayAndYou];
[personClass sayGoodbye];
struct wj_objc_class *wj_pClass = (__bridge struct wj_objc_class *)(personClass);
NSLog(@"%hu - %u",wj_pClass->cache._occupied,wj_pClass->cache._mask);
for (mask_t i = 0; i<wj_pClass->cache._mask; i++) {
// 打印獲取的 bucket
struct wj_bucket_t bucket = wj_pClass->cache._buckets[i];
NSLog(@"%@ - %p",NSStringFromSelector(bucket._sel),bucket._imp);
}
NSLog(@"%@", personClass);
}
return 0;
}
我們把cache_t
相關的源碼拷貝過來,加工成我們自己的wj_cache_t
,然后通過我們自己的wj_cache_t
看一下緩存結果。
首先我們只調用其中一個方法,看下打印結果
-
occupied
和mask
是什么,又是怎么變化的呢。 - 為什么會出現有的方法沒有打印的情況呢。
- 為什么
buckets
中方法的順序和我們的調用順序不一致呢。
接下來我們分析下cache_t
的源碼
cache_t源碼分析
cache_t
結構,發現public
方法處,有incrementOccupied
函數和setBucketsAndMask
函數。進入
incrementOccupied
發現只是執行了_occupied++
。
void cache_t::incrementOccupied()
{
_occupied++;
}
進入setBucketsAndMask
發現每次都是重新設置_buckets
和_mask
,并且把_occupied
設置為0
void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
{
// objc_msgSend uses mask and buckets with no locks.
// It is safe for objc_msgSend to see new buckets but old mask.
// (It will get a cache miss but not overrun the buckets' bounds).
// It is unsafe for objc_msgSend to see old buckets and new mask.
// Therefore we write new buckets, wait a lot, then write new mask.
// objc_msgSend reads mask first, then buckets.
#ifdef __arm__
// ensure other threads see buckets contents before buckets pointer
mega_barrier();
_buckets.store(newBuckets, memory_order::memory_order_relaxed);
// ensure other threads see new buckets before new mask
mega_barrier();
_mask.store(newMask, memory_order::memory_order_relaxed);
_occupied = 0;
#elif __x86_64__ || i386
// ensure other threads see buckets contents before buckets pointer
// 存儲新的buckets
_buckets.store(newBuckets, memory_order::memory_order_release);
// ensure other threads see new buckets before new mask
// 存儲新的mask
_mask.store(newMask, memory_order::memory_order_release);
// occupied占用z設為0
_occupied = 0;
#else
#error Don't know how to do setBucketsAndMask on this architecture.
#endif
}
通過這兩個方法的實現,我們發現incrementOccupied
是執行計數加一操作,那么我們判斷調用incrementOccupied
方法的地方應該就是核心業務處理的過程,所以我們搜索incrementOccupied
去看看哪里調用了它。發現只有cache_t::insert
使用到了它。那我們再找下cache->insert
又在哪里被使用了呢,發現只有一處cache_fill
調用了cache->insert
,然后我們再往上找,發現找不到調用cache_fill
的地方,說明這里又是經過編譯器做了處理,所以我們今天就只討論cache_fill —>insert
里的操作。
我們先來看下cache_fill
的源碼
void cache_fill(Class cls, SEL sel, IMP imp, id receiver)
{
runtimeLock.assertLocked(); // runtime鎖 assert斷言
#if !DEBUG_TASK_THREADS
// Never cache before +initialize is done
if (cls->isInitialized()) {
cache_t *cache = getCache(cls);//獲取當前的cache緩存池
#if CONFIG_USE_CACHE_LOCK
mutex_locker_t lock(cacheUpdateLock);
#endif
cache->insert(cls, sel, imp, receiver);//向緩存池中插入信息
}
#else
_collecting_in_critical();
#endif
}
然后我們看下cache_t::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
方法的實現,看下他是怎么對內存空間進行操作的
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;
}
我們看下allocateBuckets
開辟新空間的操作
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);
}
最后我們可以總結一個流程圖
經過我們的分析,相信你對前面的疑問已經有了答案。
1.
occupied
和 mask
是什么,又是怎么變化的呢。函數寫入
cache
緩存時,occupied
會加1,mask
記錄當前cache
最大可存儲空間。當
inset
緩存的操作,觸發空間使用率超過3/4
,空間2倍擴容
時,mask
記錄新空間的最大可存儲大小,因為舊空間被釋放
,之前cache
的所有內容都被垃圾房清空了,所以occupied
重置為0。從新開始計數2. 為什么會出現有的方法沒有打印的情況呢。
因為觸發空間擴容時,
舊空間被釋放
,所以cache
中的舊值都被清空。 新值插入新cache
空間。3. 為什么
buckets
中方法的順序和我們的調用順序不一致呢。插入操作是使用的
hash
算法。插入位置是經過取余計算的。且如果插入位置已經有值,就會不停的后移1位,直到找到空位置完成插入位置。