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
}

通過(guò)名字我們猜測(cè)cache應(yīng)該是緩存躺坟,但是到底是緩存了什么呢沦补?這個(gè)就需要探索了
首先獲取cache,通過(guò)之前的篇章我們知道咪橙,要獲取cache夕膀,需要通過(guò)首地址編譯16字節(jié)得到虚倒。

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

我們?cè)趤?lái)看看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 地址長(zhǎng)度64位 
            uint16_t                   _flags;  // 2
#endif
            uint16_t                   _occupied; // 2
        };
        explicit_atomic<preopt_cache_t *> _originalPreoptCache; // 8
    };
}       

從打印結(jié)果來(lái)看,cache里有個(gè)_bucketsAndMaybeMask产舞,_flags魂奥,_occupied,_originalPreoptCache庞瘸,但是我們都不知道這些干嘛用的捧弃,我們到cache結(jié)構(gòu)里面看看有沒(méi)有什么方法可以輸出查看。
void insert(SEL sel, IMP imp, id receiver); 里面有個(gè)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
}

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

cache如何緩存方法

  1. 第一次進(jìn)來(lái)通過(guò)realloccate開(kāi)辟空間,默認(rèn)開(kāi)辟4個(gè)
    capacity = INIT_CACHE_SIZE(INIT_CACHE_SIZE = (1 << INIT_CACHE_SIZE_LOG2), INIT_CACHE_SIZE_LOG2 = 2)
    reallocate(oldCapacity, capacity, /* freeOld */false);
    \color{#f00}{注意:} 這邊雖然開(kāi)辟了capacity個(gè)空間幌陕,但是實(shí)際存放數(shù)據(jù)為capacity-1,因?yàn)樽詈笠粋€(gè)默認(rèn)為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); // 獲取最后一個(gè)位置
#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. 下次進(jìn)來(lái)查看是否小于3/4 小于則不需要擴(kuò)容直接添加
  2. 大于3/4 需要擴(kuò)容诵姜,擴(kuò)容規(guī)則capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;(2倍擴(kuò)容)
  3. 擴(kuò)容后并不會(huì)將舊的數(shù)據(jù)移到新容器里,只存放新數(shù)據(jù)(蘋(píng)果的原則搏熄,新數(shù)據(jù)更有存儲(chǔ)價(jià)值)
  4. 存放位置的設(shè)計(jì)
bucket_t *b = buckets();
    mask_t m = capacity - 1; // 4-1=3
    mask_t begin = cache_hash(sel, m); 通過(guò)哈希獲取到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)存放過(guò)當(dā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)存放過(guò)了心例,哈希碰撞宵凌,通過(guò)cache_next獲取下一個(gè)位置

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

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

輸出結(jié)果
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

通過(guò)打印cache結(jié)果,可以看出止后,存儲(chǔ)并不是數(shù)組存儲(chǔ)而是通過(guò)哈希存儲(chǔ)瞎惫。在say3的時(shí)候進(jìn)行了擴(kuò)容,那是因?yàn)橐胫辏瑂ay1微饥,say2在加上末尾的1剛好是3/4,在say3的時(shí)候超過(guò)了即進(jìn)行了擴(kuò)容所以沒(méi)有打印say1和say2.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末古戴,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子矩肩,更是在濱河造成了極大的恐慌现恼,老刑警劉巖肃续,帶你破解...
    沈念sama閱讀 211,884評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異叉袍,居然都是意外死亡始锚,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,347評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門(mén)喳逛,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)瞧捌,“玉大人,你說(shuō)我怎么就攤上這事润文〗隳牛” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 157,435評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵典蝌,是天一觀的道長(zhǎng)曙砂。 經(jīng)常有香客問(wèn)我,道長(zhǎng)骏掀,這世上最難降的妖魔是什么鸠澈? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,509評(píng)論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮截驮,結(jié)果婚禮上笑陈,老公的妹妹穿的比我還像新娘。我一直安慰自己葵袭,他們只是感情好涵妥,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,611評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著眶熬,像睡著了一般妹笆。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上娜氏,一...
    開(kāi)封第一講書(shū)人閱讀 49,837評(píng)論 1 290
  • 那天拳缠,我揣著相機(jī)與錄音,去河邊找鬼贸弥。 笑死窟坐,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的绵疲。 我是一名探鬼主播哲鸳,決...
    沈念sama閱讀 38,987評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼盔憨!你這毒婦竟也來(lái)了徙菠?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,730評(píng)論 0 267
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤郁岩,失蹤者是張志新(化名)和其女友劉穎婿奔,沒(méi)想到半個(gè)月后缺狠,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,194評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡萍摊,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,525評(píng)論 2 327
  • 正文 我和宋清朗相戀三年挤茄,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片冰木。...
    茶點(diǎn)故事閱讀 38,664評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡穷劈,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出踊沸,到底是詐尸還是另有隱情歇终,我是刑警寧澤,帶...
    沈念sama閱讀 34,334評(píng)論 4 330
  • 正文 年R本政府宣布雕沿,位于F島的核電站练湿,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏审轮。R本人自食惡果不足惜肥哎,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,944評(píng)論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望疾渣。 院中可真熱鬧篡诽,春花似錦、人聲如沸榴捡。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,764評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)吊圾。三九已至达椰,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間项乒,已是汗流浹背啰劲。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,997評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留檀何,地道東北人蝇裤。 一個(gè)月前我還...
    沈念sama閱讀 46,389評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像频鉴,于是被迫代替她去往敵國(guó)和親栓辜。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,554評(píng)論 2 349

推薦閱讀更多精彩內(nèi)容