Cache_t 分析

类结构分析中 知道了属性和方法是如何获取的,可是为了看 class_data_bits_t bits; 中的内容,仅仅计算了 cache_t cache; 的大小,并无认真的了解和研究过 cache_t ,当前内容就是对 Cache_t 的分析。缓存

一、认识 cache_t

cache_t 是对 OC 程序中使用过方法的缓存,以便于下次调用方便。每次调用方法以前都须要先从 cache_t 中查找,若是有缓存,就不须要通过漫长的方法查找而直接调用了,若是没有就给 cache_t 中缓存一份。bash

struct cache_t {
    struct bucket_t *_buckets;
    mask_t _mask;
    mask_t _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__
    uintptr_t _imp;
    SEL _sel;
#else
    SEL _sel;
    uintptr_t _imp;
#endif

    //...

}

复制代码

上方代码就是 struct cache_t 中全部的成员,结构体中 _bucketsbucket_t * 的结构体指针类型, 存储的是缓存方法的 SEL 方法编号和 IMP 方法实现的指针地址;_mask 表明的是当前能缓存的方法的个数;_occupied 表明的是当前已经缓存的方法数。less

二、LLDB 打印 cache_t

既然知道 cache_t 成员所表明的含义,那如今经过 lldb 调试一下,main.m 文件中,写入下方代码。post

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        TestClass *object = [TestClass alloc];
        Class pClass = object_getClass(object);
        NSLog(@"%@ - %p",object,pClass);
    }
    return 0;
}

复制代码

lldb 调试结果以下:ui

类结构分析中 中说过:执行 x/4gx 后,第一个 8 字节表明 isa ,第二个 8 字节表明 superClass,因此首地址偏移 16 个字节就是 cache_t 的首地址,一系列的取值后发现是空的,没有缓存,那明明调用了 alloc 方法了啊,就算 alloc 方法特殊,可是也是方法啊,怎么没有缓存呢?this

缘由是:alloc 是类方法,类方法存储在当前类的元类里面,类里面存储的是实例方法。spa

明白了上述缘由,尝试添加实例方法再次打印。线程

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        TestClass *object = [TestClass alloc];
        Class pClass = object_getClass(object);
        [object testClassInstanceMethod];
        NSLog(@"%@ - %p",object,pClass);   
    }
    return 0;
}
复制代码

打印结果以下:3d

上方截图打印出来发现,_mask 为 3,_occupied 为 1,打印出了上方代码调用过的 testClassInstanceMethod 了,发现确实类的 cache_t 只是缓存的类的实例方法,而且调用一次后就会缓存。指针

三、自定义输出 cache_t

每次都使用上方 lldb 都累的够呛,当前使用一个自定义的方式去打印一下。自定义代码以下:

typedef unsigned long           uintptr_t;
typedef uint32_t mask_t;

struct custom_bucket_t {
#if __arm64__
    uintptr_t _imp;
    SEL _sel;
#else
    SEL _sel;
    uintptr_t _imp;
#endif
};

struct cache_t {
    struct custom_bucket_t *_buckets;
    mask_t _mask;
    mask_t _occupied;
};

struct custom_class_data_bits_t {
    
    // Values are the FAST_ flags above.
    uintptr_t bits;
};

struct custom_objc_class  {
    Class ISA;
    Class superclass;
    struct cache_t cache;             // formerly cache pointer and vtable
    struct custom_class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags
};

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        TestClass *object = [TestClass alloc];
        Class pClass = object_getClass(object);
        
        [object testClassInstanceMethod];
        [object testClassInstanceMethod_1];
        [object testClassInstanceMethod_2];
        
        struct custom_objc_class *custom_pClass = (__bridge struct custom_objc_class *)(pClass);
      
        for (mask_t i = 0; i < custom_pClass->cache._mask; i++) {
            struct custom_bucket_t bucket = custom_pClass->cache._buckets[i];
            NSLog(@"%s ---- %lu",bucket._sel,bucket._imp);
        }
        
        NSLog(@"结束打印:%@ - %p",object,pClass);
    }
    return 0;
}
复制代码

打印结果以下:

这样就能很清晰的看到 cache_t 中的缓存方法。

四、多个方法调用自定义输出 cache_t

上方代码调用了3个实例方法,那咱们调用4个或者多个呢?上方代码再添加一个调用 [object testClassInstanceMethod_3]; 打印结果以下:

发现居然只有一个缓存方法打印了,其余的呢?还有这里调用 4 个方法的打印了 7 条,上个调用 3 个方法的就打印了 3 条呢?

带着疑问接着看 cache_t, 以前都是只看了成员是什么?成员的含义是什么?可是没有看过这些值是怎么赋值的吧。

五、对 cache_t 结构体中的方法追踪

随意个 cache_tmask_t cache_t::mask() 方法打个断点 ,而后再在咱们调用方法前打个断点,先让程序走到咱们调用方法以前,不然就会不断的进入系统方法的调用。

程序进入了 mask() 的断点,看下调用队栈信息:

从上方队栈信息能看到,先开始查找方法,而后缓存方法,这里只关注方法缓存,看到关于缓存的字样 cache_fill() 继续上述操做,断点进入 cache_fill(),再下一步进入 cache_fill_nolock(),发现此时才是当前 cache_t 的重头戏。

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_t 缓存源码 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 was not added to the cache by some other thread 
    // before we grabbed the cacheUpdateLock.
    //确保在获取cacheUpdateLock以前,条目没有被其余线程添加到缓存中。

    
    //若是缓存中找到了,就 return 什么也不须要干
    if (cache_getImp(cls, sel)) return;

    //取出类对象中的 cache_t
    cache_t *cache = getCache(cls);

    // Use the cache as-is if it is less than 3/4 full
    //若是缓存不足3/4,则按原样使用缓存
    
    //获取当前保存的缓存已经使用的大小,而后进行 + 1 ,由于当前须要缓存新的。
    mask_t newOccupied = cache->occupied() + 1;
    
    //获取当前 cache 的最大容量 _mask + 1
    mask_t capacity = cache->capacity();
    
    //若是是一个只读的空缓存就进入
    if (cache->isConstantEmptyCache()) {
        // Cache is read-only. Replace it.
        //缓存是只读的。取代它
        
        //开辟一个缓存空间 capacity > 0 ? capacity : 4
        // INIT_CACHE_SIZE : (1 << INIT_CACHE_SIZE_LOG2) -----> 4
        cache->reallocate(capacity, capacity ?: INIT_CACHE_SIZE);
    }
    else if (newOccupied <= capacity / 4 * 3) {
        // Cache is less than 3/4 full. Use it as-is.
        //缓存小于3/4满。按原样使用它。
    }
    else {
        // Cache is too full. Expand it.
        
        //超出了缓存大小的 4分之3 就须要 扩容
        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.
    
    //扫描第一个未使用的插槽并插入。
    //保证有一个空槽,由于最小尺寸是4,咱们调整了3/4满的尺寸。
    
    //哈希去查找
    bucket_t *bucket = cache->find(sel, receiver);
    
    if (bucket->sel() == 0) {
        // 若是 _sel 没找到
        /**
         *  incrementOccupied() {
         *    //当前已经缓存的方法总数+1;
         *     _occupied++;
         *  }
         */
        cache->incrementOccupied();
    }
        
    //将当前要调用方法缓存
    bucket->set<Atomic>(sel, imp);
}
复制代码

七、对 cache_t 缓存源码 expand 扩容的分析

void cache_t::expand()
{
    //锁
    cacheUpdateLock.assertLocked();
    
    //获取原来缓存的最大容量
    uint32_t oldCapacity = capacity();
    
    //若是原来缓存的最大容量 > 0,就在原来的容量上 * 2,不然就返回 4
    uint32_t newCapacity = oldCapacity ? oldCapacity*2 : INIT_CACHE_SIZE;

    //若是新容量不等于旧容量就赋值
    if ((uint32_t)(mask_t)newCapacity != newCapacity) {
        // mask overflow - can not grow further
        // fixme this wastes one bit of mask
        newCapacity = oldCapacity;
    }

    reallocate(oldCapacity, newCapacity);
}

复制代码

八、对 cache_t 缓存源码 reallocate 的分析

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

    //获取旧的缓存池
    bucket_t *oldBuckets = buckets();
    
    //开辟新的缓存池
    bucket_t *newBuckets = allocateBuckets(newCapacity);

    // Cache is 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);

    //给cache 从新赋值缓存池 _buckets,能存储的_mask = newCapacity - 1 的值,而后把当前已经缓存的方法个数置为0
    setBucketsAndMask(newBuckets, newCapacity - 1);
    
    //若是能够释放就释放掉旧的缓存池
    if (freeOld) {
        cache_collect_free(oldBuckets, oldCapacity);
        cache_collect(false);
    }
}
复制代码

以上就是对 cache_t 的缓存方法的流程了。

相关文章
相关标签/搜索