OC底层探究(5)-- cache_t分析

cache_t的结构

struct objc_class : objc_object {
    // Class ISA;  继承自objc_object  //8
    Class superclass;  //8
    cache_t cache;  //16           // formerly cache pointer and vtable
    class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags
   
    ...
}

在上一篇类的结构分析中, 我们从类的结构体源码中看到,类中存有一个cache_t cache(方法缓存),但是没有做具体分体分析,这篇博客就来具体分析一下cache_t 。
先来看一下cache_t的源码结构:

struct cache_t {
    struct bucket_t *_buckets;
    mask_t _mask;
    mask_t _occupied;

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));
};

_buckets: 一个存放bucket_t 结构体的数组,用来存放缓存方法的imp和缓存的key。
_mask:缓存数组的大小
_occupied:当前已缓存的方法数


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
...
};

using MethodCacheIMP = IMP;
typedef uintptr_t cache_key_t;

//获取key
cache_key_t getKey(SEL sel) 
{
    assert(sel);
    return (cache_key_t)sel;
}

_imp: 缓存的方法的imp。
_key: 有sel强转而来,其实就是SEL的内存地址。

了解完了cache_t的结构,我们通过代码来验证一下,实际的类中的cache_t是否如我们分析的一样呢?我们创建一个简单的person对象,然后调用一下它的sayHappy方法,然后进入断点调试:


image.png

在控制台做如下输出:

//打印person的类对象的内存地址
(lldb) x/4gx person.class
0x100002518: 0x001d8001000024f1 0x0000000100b37140
0x100002528: 0x0000000100fc4320 0x0000000300000003

//根据内存便宜找到cache_t并打印cache_t的指针
(lldb) p (cache_t *)0x100002528
(cache_t *) $1 = 0x0000000100002528

//打印cache_t
(lldb) p *$1
(cache_t) $2 = {
  _buckets = 0x0000000100fc4320
  _mask = 3
  _occupied = 3
}

//打印_buckets的指针
(lldb) p $2._buckets
(bucket_t *) $3 = 0x0000000100fc4320

//打印_buckets指针指向的地址,也就是_buckets的第一个元素。
(lldb) p *$3
(bucket_t) $4 = {
  _key = 4294974988
  _imp = 0x0000000100001a20 (LGTest`-[ZPerson sayHello] at main.m:124)
}

我们发现打印出的sayHello方法,正式在上面调用的[person sayHello]。说明cache_t里确实缓存了我们曾经调用过的方法。那么cache_t是如何进行方法的缓存的呢?请继续往下看。

cache_t的缓存查找

在cache_t的结构体里我们看到有这样一个方法:

struct bucket_t * find(cache_key_t key, id receiver);

点进去看它的具体实现:

bucket_t * cache_t::find(cache_key_t k, id receiver)
{
    assert(k != 0);
    //取出当前cache_t的buckets
    bucket_t *b = buckets();
    //取出当前cache_t的mask
    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);
    
   //如果此时还没有找到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);

这个方法的作用就是根据传进来的key遍历查找buckets,然后返回存有方法imp的bucket_t。这个方法应该属于查找流程中的一个过程。我们再在源码中全局搜索一下,是谁什么时候调用了这个方法。

我们在cache_fill_nolock方法中找到了find方法调用。先贴一下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);
}

1、cache_fill_nolock方法传进来4个参数:类cls、方法的sel、方法的imp和方法的调用者。
2、加一把cacheUpdateLock。
3、然后进行一下安全检查。
4、取出cls中的cahce。
5、根据sel生成相对应的key。
6、取出当前cache缓存方法的个数,然后加1,得到newOccupied,新的缓存方法个数。
7、得到当前cache的最大容量。
8、进行总容量与缓存个数的判断:
a.当前cache里面是空的,调用reallocate开去开辟新的buckets赋值的当前的cache_t
b.当前缓存个数小于总容量的3/4,不做操作
c.当前缓存个数不小于总容量的3/4,就调用expand()去扩容。
9、调用cache的find方法查找缓存
10、如果没找到,将已缓存的数目occupied加1,再将key和imp存入bucket

关于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);
}

我们可以看到,方法中先去取了一下旧的容量大小oldCapacity,然后将oldCapacity乘以2,也就是将oldCapacity扩大了一倍,得到新的容量大小newCapacity。在调用reallocate()去进行内存的开辟,需要将oldCapacity和newCapacity作为参数传递进去。
我们再看一下reallocate()方法的源码:

{
    bool freeOld = canBeFreed();
      
    //获取原来的buckets
    bucket_t *oldBuckets = buckets();
    //根据新的容量大小,创新出新的newBuckets,这个newBuckets是空的
    bucket_t *newBuckets = allocateBuckets(newCapacity);

    assert(newCapacity > 0);
    assert((uintptr_t)(mask_t)(newCapacity-1) == newCapacity-1);
   
    //将新的newCapacity-1作为新的mask大小,再将_buckets和mask存入cache_t,并将occupied置为0
    setBucketsAndMask(newBuckets, newCapacity - 1);
    //将旧的buckets释放
    if (freeOld) {
        cache_collect_free(oldBuckets, oldCapacity);
        cache_collect(false);
    }
}

根据上面源码的注释,我们可以知道reallocate()方法具体做了哪些操作。然后我们再看一下系统都在哪些方法调用了reallocate()。根据全局搜索可以找到,有两处代码进行了reallocate()方法的调用。一个是cache_t为空,第一次开辟的时候,再有就就是调用expand()方法进行扩容的时候。

image.png

第一次调用的时候,cache->reallocate(capacity, capacity ?: INIT_CACHE_SIZE);capacity为0, INIT_CACHE_SIZE((1 << INIT_CACHE_SIZE_LOG2))= 4。所以第一次传进的参数为(0,4)。结合上面的代码我们可以知道,第一次的容量大小mask为4-1=3。

关于cache_fill_nolock我们已经分析的差不多了。接下来我们再找找哪里调用了cache_fill_nolock,自下而上的查找一下,尽量到刨根儿,哈哈。

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方法调用了cache_fill_nolock。再继续查找,找到lookUpImpOrForwardlookupMethodInClassAndLoadCache两个方法。根据方法名可以知道,当进行方法调用的时候,会进行cache_filll,也就是填充方法缓存。关于方法的调用,我们后面的博客再将。关于cache_t的分析基本上就是这些了。最后附上一张流程图,方便理清思路。

cache_t流程图.png

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

推荐阅读更多精彩内容