objc_class 中的cache

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
}

通過名字我們猜測cache應該是緩存,但是到底是緩存了什么呢?這個就需要探索了
首先獲取cache,通過之前的篇章我們知道,要獲取cache,需要通過首地址編譯16字節(jié)得到。

LGPerson *p  = [LGPerson alloc];
Class pClass = [LGPerson class]; //cache_t
通過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
      }
    }
  }
}

我們在來看看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 地址長度64位 
            uint16_t                   _flags;  // 2
#endif
            uint16_t                   _occupied; // 2
        };
        explicit_atomic<preopt_cache_t *> _originalPreoptCache; // 8
    };
}       

從打印結果來看,cache里有個_bucketsAndMaybeMask,_flags,_occupied,_originalPreoptCache,但是我們都不知道這些干嘛用的,我們到cache結構里面看看有沒有什么方法可以輸出查看。
void insert(SEL sel, IMP imp, id receiver); 里面有個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
}

通過insert源碼我們發(fā)現(xiàn),insert是將sel和imp放到了buckets里面
接下來我們看看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,原來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 指針,查詢bucket結構體里發(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
    }
  }
}
看起來這個數(shù)組里面并沒有存放數(shù)據(jù),想來也是我們并沒有調(diào)用什么實例方法
(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
    }
  }
}
直到第四個才有數(shù)值
(lldb) p $19[4].sel()
(SEL) $24 = "saySomething"
我們調(diào)用的saySomething找到了,果然這邊緩存的就是我們調(diào)用過的函數(shù),但是為什么緩存在4的位置呢?
接下來我們又要去研究insert函數(shù)了

cache如何緩存方法

  1. 第一次進來通過realloccate開辟空間,默認開辟4個
    capacity = INIT_CACHE_SIZE(INIT_CACHE_SIZE = (1 << INIT_CACHE_SIZE_LOG2), INIT_CACHE_SIZE_LOG2 = 2)
    reallocate(oldCapacity, capacity, /* freeOld */false);
    \color{#f00}{注意:} 這邊雖然開辟了capacity個空間,但是實際存放數(shù)據(jù)為capacity-1,因為最后一個默認為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); // 獲取最后一個位置
#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;
}
  1. 下次進來查看是否小于3/4 小于則不需要擴容直接添加
  2. 大于3/4 需要擴容,擴容規(guī)則capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;(2倍擴容)
  3. 擴容后并不會將舊的數(shù)據(jù)移到新容器里,只存放新數(shù)據(jù)(蘋果的原則,新數(shù)據(jù)更有存儲價值)
  4. 存放位置的設計
bucket_t *b = buckets();
    mask_t m = capacity - 1; // 4-1=3
    mask_t begin = cache_hash(sel, m); 通過哈希獲取到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)存放過當前的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)存放過了,哈希碰撞,通過cache_next獲取下一個位置

#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是往前查找下一個位置
#else

不通過源碼打印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;
    
}

輸出結果
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

通過打印cache結果,可以看出,存儲并不是數(shù)組存儲而是通過哈希存儲。在say3的時候進行了擴容,那是因為,say1,say2在加上末尾的1剛好是3/4,在say3的時候超過了即進行了擴容所以沒有打印say1和say2.

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

相關閱讀更多精彩內(nèi)容

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