iOS底层 cache_t分析

类的结构源码如下,前面分析了isasuperclassbits都已经分析过了,现在来看看cache,首先查看cache所在的位置。
首先贴源码:

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() { 
        return bits.data();
    }
}

cache_t在结构体objc_class内,ISA占8个字节,superclass占8个字节,所以cache_t存在于步长为8的第三个位置。

以下是cache_t源码,结构体cache_t中有bucket_t结构体以及类型为mask_t的_mask和_occupied共占16个字节

struct cache_t {
    struct bucket_t *_buckets; // 8
    //typedef uint32_t mask_t;
    mask_t _mask;  // 4
    mask_t _occupied; // 4

public:
    struct bucket_t *buckets();
    mask_t mask();
    mask_t occupied();
    void incrementOccupied();
    void setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask);
    void initializeToEmpty();

    mask_t capacity();
    bool isConstantEmptyCache();
    bool canBeFreed();

    static size_t bytesForCapacity(uint32_t cap);
    static struct bucket_t * endMarker(struct bucket_t *b, uint32_t cap);

    void expand();
    void reallocate(mask_t oldCapacity, mask_t newCapacity);
    struct bucket_t * find(cache_key_t key, id receiver);

    static void bad_cache(id receiver, SEL sel, Class isa) __attribute__((noreturn));
};

接着查看查看bucket_t的结构,可以看出这里面有impkey

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__
    MethodCacheIMP _imp;
    cache_key_t _key;
#else
    cache_key_t _key;
    MethodCacheIMP _imp;
#endif

public:
    inline cache_key_t key() const { return _key; }
    inline IMP imp() const { return (IMP)_imp; }
    inline void setKey(cache_key_t newKey) { _key = newKey; }
    inline void setImp(IMP newImp) { _imp = newImp; }

    void set(cache_key_t newKey, IMP newImp);
};

首先查看cache调用过程,此处接iOS底层 消息查找流程
cache_fill

void cache_fill(Class cls, SEL sel, IMP imp, id receiver)
{
#if !DEBUG_TASK_THREADS
    mutex_locker_t lock(cacheUpdateLock);
    cache_fill_nolock(cls, sel, imp, receiver);
#else
    _collecting_in_critical();
    return;
#endif
}

查看cache_fill_nolock

static void cache_fill_nolock(Class cls, SEL sel, IMP imp, id receiver)
{
    cacheUpdateLock.assertLocked();

    // Never cache before +initialize is done
    if (!cls->isInitialized()) return;

    // Make sure the entry wasn't added to the cache by some other thread 
    // before we grabbed the cacheUpdateLock.
    if (cache_getImp(cls, sel)) return;

    cache_t *cache = getCache(cls);
    cache_key_t key = getKey(sel);

    // Use the cache as-is if it is less than 3/4 full
    mask_t newOccupied = cache->occupied() + 1;
    mask_t capacity = cache->capacity();
    if (cache->isConstantEmptyCache()) {
        // Cache is read-only. Replace it.
        cache->reallocate(capacity, capacity ?: INIT_CACHE_SIZE);
    }
    else if (newOccupied <= capacity / 4 * 3) {
        // Cache is less than 3/4 full. Use it as-is.
    }
    else {
        // Cache is too full. Expand it.
        cache->expand();
    }

    // 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.
    bucket_t *bucket = cache->find(key, receiver);
    if (bucket->key() == 0) cache->incrementOccupied();
    bucket->set(key, imp);
}

occupied

mask_t cache_t::occupied() 
{
    return _occupied;
}

capacity

mask_t cache_t::capacity() 
{
    return mask() ? mask()+1 : 0; 
}

reallocate 重新分配

void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity)
{
    bool freeOld = canBeFreed();

    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);
        cache_collect(false);
    }
}

expand扩容

void cache_t::expand()
{
    cacheUpdateLock.assertLocked();
    
    uint32_t oldCapacity = capacity();
    uint32_t newCapacity = oldCapacity ? oldCapacity*2 : INIT_CACHE_SIZE;

    if ((uint32_t)(mask_t)newCapacity != newCapacity) {
        // mask overflow - can't grow further
        // fixme this wastes one bit of mask
        newCapacity = oldCapacity;
    }

    reallocate(oldCapacity, newCapacity);
}

find 查找相应的存储

bucket_t * cache_t::find(cache_key_t k, id receiver)
{
    assert(k != 0);

    bucket_t *b = buckets();
    mask_t m = mask();
    // 通过cache_hash函数【begin  = k & m】计算出key值 k 对应的 index值 begin,用来记录查询起始索引
    mask_t begin = cache_hash(k, m);
    // begin 赋值给 i,用于切换索引
    mask_t i = begin;
    do {
        if (b[i].key() == 0  ||  b[i].key() == k) {
            //用这个i从散列表取值,如果取出来的bucket_t的 key = k,则查询成功,返回该bucket_t,
            //如果key = 0,说明在索引i的位置上还没有缓存过方法,同样需要返回该bucket_t,用于中止缓存查询。
            return &b[I];
        }
    } while ((i = cache_next(i, m)) != begin);
    
    // 这一步其实相当于 i = i-1,回到上面do循环里面,相当于查找散列表上一个单元格里面的元素,再次进行key值 k的比较,
    //当i=0时,也就i指向散列表最首个元素索引的时候重新将mask赋值给i,使其指向散列表最后一个元素,重新开始反向遍历散列表,
    //其实就相当于绕圈,把散列表头尾连起来,不就是一个圈嘛,从begin值开始,递减索引值,当走过一圈之后,必然会重新回到begin值,
    //如果此时还没有找到key对应的bucket_t,或者是空的bucket_t,则循环结束,说明查找失败,调用bad_cache方法。
 
    // 
    Class cls = (Class)((uintptr_t)this - offsetof(objc_class, cache));
    cache_t::bad_cache(receiver, (SEL)k, cls);
}

incrementOccupied occupied占用+1

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

cache验证

1.新建类

//  TWPerson.h
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface TWPerson : NSObject

- (void)talk1;

- (void)talk2;

- (void)talk3;

@end


//  TWPerson.m
#import "TWPerson.h"
@implementation TWPerson

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

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

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

@end

2.调用和断点位置


断点调试.png

3.lldb调试,在每个断点处打印调试结果

2020-01-02 16:04:28.414128+0800 TWDemo[35887:282758] Hello, World!
2020-01-02 16:04:28.414324+0800 TWDemo[35887:282758] -[TWPerson talk1]//断点1
(lldb) x/4gx p.class
0x1000012b0: 0x001d800100001289 0x0000000100b34140
0x1000012c0: 0x0000000101a29050 0x0000000300000003
(lldb) p (cache_t *)0x1000012c0
(cache_t *) $1 = 0x00000001000012c0
(lldb) p $1[0]
(cache_t) $2 = {
  _buckets = 0x0000000101a29050
  _mask = 3
  _occupied = 3
}
(lldb) p $2._buckets[0]
(bucket_t) $3 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[1]
(bucket_t) $4 = {
  _key = 4294971209
  _imp = 0x0000000100000d40 (TWDemo`-[TWPerson talk1] at TWPerson.m:16)
}
(lldb) p $2._buckets[2]
(bucket_t) $5 = {
  _key = 4309412966
  _imp = 0x00000001003c7f90 (libobjc.A.dylib`::-[NSObject class]() at NSObject.mm:1988)
}
(lldb) p $2._buckets[3]
(bucket_t) $6 = {
  _key = 140735242647635
  _imp = 0x00000001003c8300 (libobjc.A.dylib`::-[NSObject respondsToSelector:](SEL) at NSObject.mm:2046)
}
(lldb) p $2._buckets[4]
(bucket_t) $7 = {
  _key = 1
  _imp = 0x0000000101a29050 (0x0000000101a29050)
}
(lldb) p $2._buckets[45]
(bucket_t) $8 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[5]
(bucket_t) $9 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[6]
(bucket_t) $10 = {
  _key = 0
  _imp = 0x0000000000000000
}
2020-01-02 16:05:45.153536+0800 TWDemo[35887:282758] -[TWPerson talk2]//断点2
(lldb) p $2._buckets[0]
(bucket_t) $11 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[1]
(bucket_t) $12 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[2]
(bucket_t) $13 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[3]
(bucket_t) $14 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[4]
(bucket_t) $15 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[5]
(bucket_t) $16 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[6]
(bucket_t) $17 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[7]
(bucket_t) $18 = {
  _key = 4294971215
  _imp = 0x0000000100000d70 (TWDemo`-[TWPerson talk2] at TWPerson.m:20)
}
(lldb) p $2._buckets[8]
(bucket_t) $19 = {
  _key = 1
  _imp = 0x0000000101f349f0 (0x0000000101f349f0)
}
(lldb) p $2._buckets[9]
(bucket_t) $20 = {
  _key = 0
  _imp = 0x0000000000000000
}
2020-01-02 16:06:23.964333+0800 TWDemo[35887:282758] -[TWPerson talk3]//断点3
(lldb) p $2._buckets[0]
(bucket_t) $21 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[1]
(bucket_t) $22 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[2]
(bucket_t) $23 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[3]
(bucket_t) $24 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[4]
(bucket_t) $25 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[5]
(bucket_t) $26 = {
  _key = 4294971221
  _imp = 0x0000000100000da0 (TWDemo`-[TWPerson talk3] at TWPerson.m:24)
}
(lldb) p $2._buckets[6]
(bucket_t) $27 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[7]
(bucket_t) $28 = {
  _key = 4294971215
  _imp = 0x0000000100000d70 (TWDemo`-[TWPerson talk2] at TWPerson.m:20)
}
(lldb) p $2._buckets[8]
(bucket_t) $29 = {
  _key = 1
  _imp = 0x0000000101f349f0 (0x0000000101f349f0)
}
(lldb) p $2._buckets[9]
(bucket_t) $30 = {
  _key = 0
  _imp = 0x0000000000000000
}
(lldb) p $2._buckets[10]
(bucket_t) $31 = {
  _key = 140735685066801
  _imp = 0x00007fff9484c250 ((void *)0x00007fff37421928)
}
2020-01-02 16:07:23.480901+0800 TWDemo[35887:282758] <TWPerson: 0x101a24de0>
Program ended with exit code: 0

分析
通过调试,在断点1处打印的时候,可以找到talk1方法,断点2处,可以找到talk2方法但是没有talk1方法,断点3处,可以找到talk2和talk3方法,但是没有talk1方法,因为在调用talk2的时候,缓存超出容量,进行了扩容,清除之前的缓存填充新的缓存导致的。

附上流程图:

cache_t流程图.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,376评论 6 491
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,126评论 2 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,966评论 0 347
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,432评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,519评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,792评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,933评论 3 406
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,701评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,143评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,488评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,626评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,292评论 4 329
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,896评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,742评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,977评论 1 265
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,324评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,494评论 2 348