iOS底層學習 - cache_t的原理分析

本文的主要目的是理解cache_t以及sel-imp緩存原理

cache中存儲的是什么?

首先,我們需要知道cache存儲的到底是什么?

  • 查看cache_t的源碼,發(fā)現(xiàn)分成了3個架構(gòu)的處理,其中真機的架構(gòu)中,mask和bucket是寫在一起,目的是為了優(yōu)化,可以通過各自的掩碼來獲取相應的數(shù)據(jù)
    • CACHE_MASK_STORAGE_OUTLINED 表示運行的環(huán)境 模擬器 或者 macOS
    • CACHE_MASK_STORAGE_HIGH_16 表示運行環(huán)境是 64位的真機
    • CACHE_MASK_STORAGE_LOW_4 表示運行環(huán)境是 非64位 的真機
struct cache_t {
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED//macOS、模擬器 -- 主要是架構(gòu)區(qū)分
    // 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;//寫在一起的目的是為了優(yōu)化
    mask_t _mask_unused;

    //以下都是掩碼,即面具 -- 類似于isa的掩碼,即位域
    // 掩碼省略....
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4 //非64位 真機
    explicit_atomic<uintptr_t> _maskAndBuckets;
    mask_t _mask_unused;

    //以下都是掩碼,即面具 -- 類似于isa的掩碼,即位域
    // 掩碼省略....
#else
#error Unknown cache mask storage type.
#endif

#if __LP64__
    uint16_t _flags;
#endif
    uint16_t _occupied;

    //方法省略.....
}

  • 查看bucket_t的源碼,同樣分為兩個版本,真機非真機,不同的區(qū)別在于selimp的順序不一致
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
    //方法等其他部分省略
}

所以通過上面兩個結(jié)構(gòu)體源碼可知,cache中緩存的是sel-imp

整體的結(jié)構(gòu)如下圖所示

image

在cache中查找sel-imp

準備工作

在main中定義一個LGPersons類,并定義兩個屬性及4個實例方法及其實現(xiàn),并在main函數(shù)中調(diào)用

@interface LGPersons : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSString *nickName;

- (void)sayHello;

- (void)sayCode;

- (void)say1;

- (void)say2;

@end

@implementation LGPersons

- (void)sayHello{
    NSLog(@"%s",__func__);
}

- (void)sayCode{
    NSLog(@" %s",__func__);
}

- (void)say1{
    NSLog(@" %s",__func__);
}

- (void)say2{
    NSLog(@" %s",__func__);
}

LGPersons *person=[LGPersons alloc];
Class pClass=[LGPersons class];
[person sayHello];
[person sayCode];
[person say1];
[person say2];

通過源碼查找

  • 運行執(zhí)行,斷在[person sayHello];部分,此時執(zhí)行以下lldb調(diào)試流程

    cache分析1.png

    • 因為在類的結(jié)構(gòu)中,cache之前有isa和superclass,各占用了8個字節(jié),總共16個字節(jié),所以cache屬性的獲取,需要通過pclass的首地址平移16字節(jié),再強轉(zhuǎn)為cache_t,打印地址。

    • 此時_occupied的值為0。

  • 執(zhí)行代碼,到達[person sayCode]一行。再次打印cache_t內(nèi)容:


    cache分析2.png
    • 此時imp有值了,_occupied占用位置也由0變成了1 。
  • 我們繼續(xù)跟進,打印_buckets內(nèi)容,確定他存儲的是不是我們所定義的方法:


    cache分析3.png
    • 從源碼的分析中,我們知道sel-imp是在cache_t_buckets屬性中(目前處于macOS環(huán)境),而在cache_t結(jié)構(gòu)體中提供了獲取_buckets屬性的方法buckets()

    • 獲取了_buckets屬性,就可以獲取sel-imp了,這兩個的獲取在bucket_t結(jié)構(gòu)體中同樣提供了相應的獲取方法sel() 以及 imp(pClass),打印出來就是sayHello

  • 照著上面的邏輯繼續(xù)執(zhí)行一行代碼,運行[person sayCode],打印buckets數(shù)組。


    cache分析4.png

    *如圖,既然拿到了數(shù)組首地址,而數(shù)組的元素類型都是一致的,我們可以通過內(nèi)存偏移讀取元素。當然因為buckets是一個數(shù)組,就可以直接使用數(shù)組下標進行讀取,例如p $10[1].sel()就可直接打印出相應的結(jié)果

cache_t的緩存原理

查看cache_t結(jié)構(gòu),發(fā)現(xiàn)源碼中,有incrementOccupied函數(shù)和setBucketsAndMask函數(shù)。
看到incrementOccupied方法就應該想到添加,cache的含義就是緩存,進入incrementOccupied方法中

void cache_t::incrementOccupied() 
{
    _occupied++;
}

全局搜索執(zhí)行該方法的位置,找到void cache_t::insert(Class cls, SEL sel, IMP imp, id receiver)中
cache_insert.png

跟隨源碼繼續(xù)探究insert方法是在何時調(diào)用的,全局搜索cache->insert,只有一個地方
cahce_fill.png

分析這段代碼,是當cls->isInitialized()為真,則獲取cache,把cls的sel和imp以及receiver插入到cache中。內(nèi)容不多,我們再回頭看看void cache_t::insert(Class cls, SEL sel, IMP imp, id receiver)方法具體做了些什么
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計數(shù)+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查看,可以發(fā)現(xiàn)就是1<<2,就是二進制100,十進制為4)
        if (!capacity) capacity = INIT_CACHE_SIZE;
        // 創(chuàng)建新空間(第三個入?yún)閒alse,表示不需要釋放舊空間)
        reallocate(oldCapacity, capacity, /* freeOld */false);
    }
    // CACHE_END_MARKER 就是 1
    // 如果當前計數(shù)+1 < 空間的 3/4。 就不用處理
    // 表示空間夠用。 不需要空間擴容
    else if (fastpath(newOccupied + CACHE_END_MARKER <= capacity / 4 * 3)) {
        // Cache is less than 3/4 full. Use it as-is.
    }
    // 如果計數(shù)大于3/4, 就需要進行擴容操作
    else {
        // 如果空間存在,就2倍擴容。 如果不存在,就設為初始值4
        capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
        // 防止超出最大空間值(2^16 - 1)
        if (capacity > MAX_CACHE_SIZE) {
            capacity = MAX_CACHE_SIZE;
        }
        // 創(chuàng)建新空間(第三個入?yún)閠rue,表示需要釋放舊空間)
        reallocate(oldCapacity, capacity, true);
    }
    // 讀取現(xiàn)在的buckets數(shù)組
    bucket_t *b = buckets();
    // 新的mask值(當前空間最大存儲大小)
    mask_t m = capacity - 1;
    // 使用hash計算當前函數(shù)的位置(內(nèi)部就是sel & m, 就是取余操作,保障begin值在m當前可用空間內(nèi))
    mask_t begin = cache_hash(sel, m);
    mask_t i = begin;
    do {
        // 如果當前位置為空(空間位置沒被占用)
        if (fastpath(b[i].sel() == 0)) {
            // Occupied計數(shù)+1
            incrementOccupied();
            // 將sle和imp與cls關聯(lián)起來并寫入內(nèi)存中
            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內(nèi)部有分支: 
        // 如果是arm64真機環(huán)境: 從最大空間位置開始,依次-1往回找空位
        // 如果是arm舊版真機、x86_64電腦、i386模擬器: 從當前位置開始,依次+1往后找空位。不能超過最大空間。
        // 因為當前空間是沒超出mask最大空間的,所以一定有空位置可以放置的。
    } while (fastpath((i = cache_next(i, m)) != begin));
    // 各種錯誤處理
    cache_t::bad_cache(receiver, (SEL)sel, cls);
}

其中的reallocate方法 : 創(chuàng)建新空間并釋放舊空間的函數(shù)

void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity, bool freeOld)
{
    // 讀取舊buckets數(shù)組
    bucket_t *oldBuckets = buckets();
    // 創(chuàng)建新空間大小的buckets數(shù)組
    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
    // 新空間必須大于0
    ASSERT(newCapacity > 0);
    // 新空間-1 轉(zhuǎn)為mask_t類型,再與新空間-1 進行判斷
    ASSERT((uintptr_t)(mask_t)(newCapacity-1) == newCapacity-1);
    // 設置新的bucktes數(shù)組和mask
    // 【重點】我們發(fā)現(xiàn)mask就是newCapacity - 1, 表示當前最大可存儲空間
    setBucketsAndMask(newBuckets, newCapacity - 1);
    // 釋放舊內(nèi)存空間
    if (freeOld) {
        cache_collect_free(oldBuckets, oldCapacity);
    }
}

核心方法allocateBuckets: 創(chuàng)建新空間大小的buckets數(shù)組

bucket_t *allocateBuckets(mask_t newCapacity)
{
    // 創(chuàng)建1個bucket
    bucket_t *newBuckets = (bucket_t *)
        calloc(cache_t::bytesForCapacity(newCapacity), 1);
    // 將創(chuàng)建的bucket放到當前空間的最尾部,標記數(shù)組的結(jié)束
    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
    // 將結(jié)束標記為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:釋放內(nèi)存空間

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加入垃圾房的尺寸中,便于后續(xù)釋放。
    garbage_byte_size += cache_t::bytesForCapacity(capacity);
    // 將當前新數(shù)據(jù)data存放到 garbage_count 后面 這樣可以釋放前面的,而保留后面的新值
    garbage_refs[garbage_count++] = data;
    // 不記錄之前的緩存 = 【清空之前的緩存】。
    cache_collect(false);
}

以上就是cache_t的代碼分析流程,為了方便理解和查看,下面用流程圖的方式具體實現(xiàn)下:
cache_t流程.png

總結(jié):

  • cache_t作為類結(jié)構(gòu)體中的一個元素,作用是緩存類的sel和imp.使得類在調(diào)用方法時能快速的發(fā)送消息,減少類查找方法的時間,具體來說就是objc_msgSend執(zhí)行時會觸發(fā)方法查找,找到方法后會調(diào)用cache_fill()方法把方法緩存到cache中。其中的objc_msgSend 和 cache_getImp為讀取流程。
  • occupied存儲的是當前占用的空間大小,函數(shù)寫入cache緩存時,occupied會加1,mask記錄當前cache最大可存儲空間。當觸發(fā)insert操作時,會判斷當前空間使用率是否超過3/4,超過則會進行空間的2倍擴容,釋放原來的緩存空間,之前cache的所有內(nèi)容都被清空了,所以occupied重置為0,從新開始計數(shù),mask記錄新空間的最大可存儲大小。也因為舊空間被釋放,此時cache中的buckets數(shù)組打印的值就會有丟失的情況。
  • buckets數(shù)組的順序與執(zhí)行順序也不相同,因為插入操作是使用的hash算法,插入位置是經(jīng)過取余計算的,且如果插入位置已經(jīng)有值,就會不停的后移1位,直到找到空位置完成插入位置。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容