iOS-OC對象原理_cache_t

前言

本篇文章開始深度探索objc_class結(jié)構(gòu)下的cache_t cache成員,cache_t結(jié)構(gòu)在整個(gè)objc底層還是非常重要的,簡單的結(jié)構(gòu)分布如下:

拓補(bǔ)圖.003.jpeg

開始

創(chuàng)建一個(gè)簡單的ZZPerson類,同時(shí)定義2個(gè)實(shí)例方法

@interface ZZPerson : NSObject
- (void)toDoSomething0;
- (void)toDoSayHello;
@end

main.m中添加代碼片段:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        ZZPerson *person = [ZZPerson alloc];
        Class pClass = [person class];
        [person toDoSomething0];
        [person toDoSayHello];
        NSLog(@"hello world");
    }
    return 0;
}

通過LLDB調(diào)試輸出結(jié)構(gòu)體信息:

(lldb) p/x ZZPerson.class
(Class) $0 = 0x0000000100002230 ZZPerson
(lldb) p (cache_t *)0x0000000100002240
(cache_t *) $1 = 0x0000000100002240
(lldb) p *$1
(cache_t) $2 = {
  _buckets = {
    std::__1::atomic<bucket_t *> = 0x0000000100719980 {
      _sel = {
        std::__1::atomic<objc_selector *> = ""
      }
      _imp = {
        std::__1::atomic<unsigned long> = 11504
      }
    }
  }
  _mask = {
    std::__1::atomic<unsigned int> = 3
  }
  _flags = 32784
  _occupied = 2
}
(lldb) p $2.buckets()
(bucket_t *) $3 = 0x0000000100719980
(lldb) p *$3
(bucket_t) $4 = {
  _sel = {
    std::__1::atomic<objc_selector *> = ""
  }
  _imp = {
    std::__1::atomic<unsigned long> = 11504
  }
}
(lldb) p $4.sel()
(SEL) $5 = "toDoSomething0"
(lldb) p $4.imp(pClass)
(IMP) $6 = 0x0000000100000ec0 (KCObjc`-[ZZPerson toDoSomething0])
(lldb) p $3 + 1
(bucket_t *) $7 = 0x0000000100719990
(lldb) p *$7
(bucket_t) $8 = {
  _sel = {
    std::__1::atomic<objc_selector *> = ""
  }
  _imp = {
    std::__1::atomic<unsigned long> = 11472
  }
}
(lldb) p $8.sel()
(SEL) $9 = "toDoSayHello"
(lldb) p $8.imp(pClass)
(IMP) $10 = 0x0000000100000ee0 (KCObjc`-[ZZPerson toDoSayHello])
(lldb) 

針對 _mask_occupied 探索,從cache_t::insert()開始:

ALWAYS_INLINE
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());
   //1.=========內(nèi)存分配部分===========
    // 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;  //擴(kuò)容
        if (capacity > MAX_CACHE_SIZE) {
            capacity = MAX_CACHE_SIZE;
        }
        reallocate(oldCapacity, capacity, true); //重新梳理 擴(kuò)容
    }
    //2.========插值部分===========
    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);
}

上面的源碼我們大致可以分為 內(nèi)存分配插值處理 2個(gè)部分來探索分析:

  • 內(nèi)存分配部分:這里的開始部分就有一個(gè)非常重要的注釋信息:Use the cache as-is if it is less than 3/4 full,大致的示意圖:
    拓補(bǔ)圖.001.jpeg

這里有幾個(gè)枚舉值INIT_CACHE_SIZE,MAX_CACHE_SIZE,CACHE_END_MARKER注意下:

#define CACHE_END_MARKER 1
enum {
    INIT_CACHE_SIZE_LOG2 = 2,
    INIT_CACHE_SIZE      = (1 << INIT_CACHE_SIZE_LOG2),
    MAX_CACHE_SIZE_LOG2  = 16,
    MAX_CACHE_SIZE       = (1 << MAX_CACHE_SIZE_LOG2),
};

在流程圖中我們看到reallocate()方法,直譯過來就是重新分配的意思,我們繼續(xù)看下它的內(nèi)部實(shí)現(xiàn):

ALWAYS_INLINE
void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity, bool freeOld)
{
    bucket_t *oldBuckets = buckets();
    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

    ASSERT(newCapacity > 0);
    ASSERT((uintptr_t)(mask_t)(newCapacity-1) == newCapacity-1);

    setBucketsAndMask(newBuckets, newCapacity - 1);
    
    if (freeOld) {
        cache_collect_free(oldBuckets, oldCapacity);
    }
}
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED

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.store(newBuckets, memory_order::memory_order_release);
    
    // ensure other threads see new buckets before new mask
    _mask.store(newMask, memory_order::memory_order_release);
    _occupied = 0;
#else
#error Don't know how to do setBucketsAndMask on this architecture.
#endif
}

大致流程:
1.通過buckets(),獲取當(dāng)前oldBuckets;
2.通過allocateBuckets(newCapacity),創(chuàng)建新的newBuckets;
3.通過setBucketsAndMask設(shè)置新的newBucketsnewMask,這里我們可以看到newMask = newCapacity - 1,即_mask_capacity的關(guān)系。該方法內(nèi)部將_occupied = 0。
4.當(dāng)非首次開辟時(shí),freeOld = true,此時(shí)會觸發(fā)cache_collect_free()方法,將oldBuckets數(shù)據(jù)抹除掉。
到此,完成了一次重新分配。這意味著當(dāng)需要擴(kuò)容重新分配空間時(shí),會將舊數(shù)據(jù)清空。

  • 插值處理部分
    這里有幾個(gè)比較重要的方法:
  1. cache_hash(sel,m)
static inline mask_t cache_hash(SEL sel, mask_t mask) 
{
    return (mask_t)(uintptr_t)sel & mask;
}

該方法是通過hash運(yùn)算來獲取插值的起始位置begin,這也意味著插值的起始位置是不確定的

  1. cache_next(i,m):
static inline mask_t cache_next(mask_t i, mask_t mask) {
//    printf("\ni:%d mask:%d cache_next : %d",i,mask,(i+1) & mask);
    return (i+1) & mask;
}
/*
i:1 mask:3 cache_next : 2
i:1 mask:3 cache_next : 2
i:0 mask:3 cache_next : 1
i:3 mask:3 cache_next : 0
i:3 mask:3 cache_next : 0
i:7 mask:7 cache_next : 0
i:0 mask:7 cache_next : 1
*/

這個(gè)方式是在do while循環(huán)中獲取下個(gè)索引的方法。

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

當(dāng)執(zhí)行一次插值時(shí),_occupied++一次;

接下來將整個(gè)cache_t結(jié)構(gòu)抽離出一個(gè)簡單的版本:

struct zz_bucket_t {
    SEL _sel;
    IMP _imp;
};
struct zz_cache_t {
    struct bucket_t * _buckets;
    uint32_t _mask;
};
struct zz_class_data_bits_t {
    uintptr_t bits;
};
struct zz_objc_class {
    Class ISA;
    Class superclass;
    struct zz_cache_t cache;
    struct zz_class_data_bits_t bits;
};

我們在main.m中通過多次調(diào)用實(shí)例方法,然后看下cache_t的打印情況:

void printCache_tLayout(Class pClass){
    struct zz_objc_class *myClass = (__bridge struct zz_objc_class *)pClass;
    printf("\n========>start<==========");
    printf("\n_occupied:%hu,_mask:%u,capacity:%u ",myClass->cache._occupied,myClass->cache._mask,myClass->cache._mask+1);
//    NSLog(@"_occupied : %hu,_mask:%u",myClass->cache._occupied,myClass->cache._mask);
    for(mask_t i = 0;i< myClass->cache._mask;i++){
        struct zz_bucket_t bucket = myClass->cache._buckets[i];
        printf("\n%s - %p",(char *)(bucket._sel),bucket._imp);
//        NSLog(@"%@ - %p",NSStringFromSelector(bucket._sel),bucket._imp);
    }
    printf("\n=========>end<==========");
}
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        ZZPerson *person = [ZZPerson alloc];
        Class pClass = [person class];
        [person toDoSayHello0];
        printCache_tLayout(pClass);
        [person toDoSayHello1];
        printCache_tLayout(pClass);
        [person toDoSayHello2];
        printCache_tLayout(pClass);
        [person toDoSayHello3];
        printCache_tLayout(pClass);
        [person toDoSayHello4];
        printCache_tLayout(pClass);
        [person toDoHaHaHa];
        printCache_tLayout(pClass);
        [person toDoSomething0];
        printCache_tLayout(pClass);
        [person toDoSayHello0];
        printCache_tLayout(pClass);
    }
    return 0;
}

日志輸出:

========>start<==========
_occupied:1,_mask:3,capacity:4 
toDoSayHello0 - 0x2e08
(null) - 0x0
(null) - 0x0
=========>end<==========
========>start<==========
_occupied:2,_mask:3,capacity:4 
toDoSayHello0 - 0x2e08
(null) - 0x0
toDoSayHello1 - 0x2e18
=========>end<==========
========>start<==========
_occupied:1,_mask:7,capacity:8 
toDoSayHello2 - 0x2e28
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
=========>end<==========
========>start<==========
_occupied:2,_mask:7,capacity:8 
toDoSayHello2 - 0x2e28
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
toDoSayHello3 - 0x2e38
=========>end<==========
========>start<==========
_occupied:3,_mask:7,capacity:8 
toDoSayHello2 - 0x2e28
(null) - 0x0
(null) - 0x0
(null) - 0x0
toDoSayHello4 - 0x2ec8
(null) - 0x0
toDoSayHello3 - 0x2e38
=========>end<==========
========>start<==========
_occupied:4,_mask:7,capacity:8 
toDoSayHello2 - 0x2e28
(null) - 0x0
toDoHaHaHa - 0x2e78
(null) - 0x0
toDoSayHello4 - 0x2ec8
(null) - 0x0
toDoSayHello3 - 0x2e38
=========>end<==========
========>start<==========
_occupied:5,_mask:7,capacity:8 
toDoSayHello2 - 0x2e28
(null) - 0x0
toDoHaHaHa - 0x2e78
(null) - 0x0
toDoSayHello4 - 0x2ec8
toDoSomething0 - 0x2e68
toDoSayHello3 - 0x2e38
=========>end<==========
========>start<==========
_occupied:1,_mask:15,capacity:16 
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
toDoSayHello0 - 0x2e08
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
(null) - 0x0
=========>end<==========

現(xiàn)在我們再看日志,就會非常的清晰,從start=>end為每次調(diào)用方法后cache_t的變化情況:
第1次:首次分配內(nèi)存,默認(rèn)capacity(容量)為4,maskcapacity - 1=3,執(zhí)行一次插值后_occupied++ = 1;
第2次:進(jìn)入newOccupied + CACHE_END_MARKER <= capacity / 4 * 3)判斷,這里對應(yīng)的就是2+1<=4/4*3,這里條件滿足,所以直接插值,_occupied++ = 2;
第3次:進(jìn)入newOccupied + CACHE_END_MARKER <= capacity / 4 * 3)判斷,這里對應(yīng)3+1<= 4/4 *3,條件不滿足,開始擴(kuò)容,capacity = 4 * 2 = 8,內(nèi)存重分配,創(chuàng)建全新的buckets,并抹除oldBuckets,mask = newCapacity - 1 = 7, _occupied = 0重置;執(zhí)行插值,_occupied++ = 1。
....
....
....
第n次
以此類推...
從日志中同樣可以看到每次插入的SEL位置都是不定的,這是由于cache_hash()決定的。

總結(jié)

capacity:開辟容量大小,當(dāng)occupied + 1 + CACHE_END_MARKER 超過capacity的3/4時(shí),開始擴(kuò)容(capacity * 2),該容量有最大值;
mask: capacity - 1 得到,存在的意義為了防止越界;
occupied: 當(dāng)開始插值時(shí),occupied++,當(dāng)重新分配內(nèi)存后,occupied = 0;
cache_hash()的巧妙使用;

問題

void cache_t::insert(Class cls, SEL sel, IMP imp, id receiver)是什么時(shí)候調(diào)用的吶?
未完待續(xù)....

參考:objc_781源碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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