一段weak代碼引發(fā)的探索

話不多說,直接看代碼


0x00 code

void testCode() {
    NSObject *obj = [NSObject new];
    __weak NSObject *weakObj = obj;
    CFTypeRef cf_weakObj = (__bridge CFTypeRef)weakObj;
    
    printf("-----%lu-----\n", CFGetRetainCount((__bridge CFTypeRef)weakObj));
    printf("-----%lu-----\n", CFGetRetainCount(cf_weakObj));
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        testCode();
    }
    return 0;
}

看到輸出結(jié)果后直接傻眼,腦子里迅速產(chǎn)生了幾個(gè)疑問:

  1. 為什么輸出的兩個(gè)值不一樣?
  2. 2是哪來的?
  3. 2后面是怎么變成1的?

0x01 debug

testCode()處打上斷點(diǎn),運(yùn)行程序后控制臺(tái)做如下操作(以下為部分截圖):

先找到testCode的函數(shù)地址,接著反匯編。從截圖的紅框中可以看到調(diào)用了objc_loadWeakRetained_objc_release這兩個(gè)函數(shù)

既然調(diào)用了release,在ARC下,objc_loadWeakRetained調(diào)用后的retainCount必然增加了1。查看源碼發(fā)現(xiàn),objc_loadWeakRetained會(huì)調(diào)用rootRetain,函數(shù)調(diào)用棧如下:

0x02 rootRetain

ALWAYS_INLINE id objc_object::rootRetain(bool tryRetain, bool handleOverflow)
{
    if (isTaggedPointer()) return (id)this;
    bool sideTableLocked = false;
    bool transcribeToSideTable = false;
    isa_t oldisa;
    isa_t newisa;

    do {
        transcribeToSideTable = false;
        oldisa = LoadExclusive(&isa.bits);
        newisa = oldisa;
      
        ...
        
        uintptr_t carry;
        newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry);  // extra_rc++

        if (slowpath(carry)) {
            if (!handleOverflow) {
                ClearExclusive(&isa.bits);
                return rootRetain_overflow(tryRetain);
            }
            if (!tryRetain && !sideTableLocked) sidetable_lock();
            sideTableLocked = true;
            transcribeToSideTable = true;
            newisa.extra_rc = RC_HALF;
            newisa.has_sidetable_rc = true;
        }
    } while (slowpath(!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)));

    if (slowpath(transcribeToSideTable)) {
        // Copy the other half of the retain counts to the side table.
        sidetable_addExtraRC_nolock(RC_HALF);
    }

    if (slowpath(!tryRetain && sideTableLocked)) sidetable_unlock();
    return (id)this;
}

這里確實(shí)有對isaextra_rc字段進(jìn)行加1操作,執(zhí)行后的新舊isa對比如下:

newisa 的extra_rc 字段為1,而oldisa 的extra_rc 字段為0。如果extra_rc 字段溢出,會(huì)將extra_rc 設(shè)置為RC_HALF,并將has_sidetable_rc字段設(shè)置為true,顯然has_sidetable_rc 是用來標(biāo)識(shí)是否溢出的,溢出后會(huì)通過sidetable_addExtraRC_nolock函數(shù)計(jì)算并重新存儲(chǔ)retainCount的值。

0x03 isa_t

union isa_t {
    isa_t() { }
    isa_t(uintptr_t value) : bits(value) { }

    Class cls;
    uintptr_t bits;
#if defined(ISA_BITFIELD)
    struct {
        ISA_BITFIELD;  // defined in isa.h
    };
#endif
};

isa_t是個(gè)union,如果定義了ISA_BITFIELD,則會(huì)存在以下字段:

#if SUPPORT_PACKED_ISA

# if __arm64__
#   define ISA_MASK        0x0000000ffffffff8ULL
#   define ISA_MAGIC_MASK  0x000003f000000001ULL
#   define ISA_MAGIC_VALUE 0x000001a000000001ULL
#   define ISA_BITFIELD                                                      \
      uintptr_t nonpointer        : 1;                                       \
      uintptr_t has_assoc         : 1;                                       \
      uintptr_t has_cxx_dtor      : 1;                                       \
      uintptr_t shiftcls          : 33; /*MACH_VM_MAX_ADDRESS 0x1000000000*/ \
      uintptr_t magic             : 6;                                       \
      uintptr_t weakly_referenced : 1;                                       \
      uintptr_t deallocating      : 1;                                       \
      uintptr_t has_sidetable_rc  : 1;                                       \
      uintptr_t extra_rc          : 19
#   define RC_ONE   (1ULL<<45)
#   define RC_HALF  (1ULL<<18)

# elif __x86_64__
#   define ISA_MASK        0x00007ffffffffff8ULL
#   define ISA_MAGIC_MASK  0x001f800000000001ULL
#   define ISA_MAGIC_VALUE 0x001d800000000001ULL
#   define ISA_BITFIELD                                                        \
      uintptr_t nonpointer        : 1;                                         \
      uintptr_t has_assoc         : 1;                                         \
      uintptr_t has_cxx_dtor      : 1;                                         \
      uintptr_t shiftcls          : 44; /*MACH_VM_MAX_ADDRESS 0x7fffffe00000*/ \
      uintptr_t magic             : 6;                                         \
      uintptr_t weakly_referenced : 1;                                         \
      uintptr_t deallocating      : 1;                                         \
      uintptr_t has_sidetable_rc  : 1;                                         \
      uintptr_t extra_rc          : 8
#   define RC_ONE   (1ULL<<56)
#   define RC_HALF  (1ULL<<7)

# else
#   error unknown architecture for packed isa
# endif

// SUPPORT_PACKED_ISA
#endif

arm64x86_64架構(gòu)下ISA_BITFIELD 是有定義的,并且兩者shiftclsextra_rc字段占用的bit不同,而他們的定義又受到SUPPORT_PACKED_ISA控制:

#if (!__LP64__  ||  TARGET_OS_WIN32  ||  \
     (TARGET_OS_SIMULATOR && !TARGET_OS_IOSMAC))
#   define SUPPORT_PACKED_ISA 0
#else
#   define SUPPORT_PACKED_ISA 1
#endif

顯然,64位系統(tǒng)下的SUPPORT_PACKED_ISA 值是1

0x04 nonpointer字段的值是如何確定的

inline void objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor)
{
    assert(!isTaggedPointer());
    
    if (!nonpointer) {
        isa.cls = cls;
    } else {
        assert(!DisableNonpointerIsa);
        assert(!cls->instancesRequireRawIsa());

        isa_t newisa(0);

#if SUPPORT_INDEXED_ISA
        assert(cls->classArrayIndex() > 0);
        newisa.bits = ISA_INDEX_MAGIC_VALUE;
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.indexcls = (uintptr_t)cls->classArrayIndex();
#else
        newisa.bits = ISA_MAGIC_VALUE;
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.shiftcls = (uintptr_t)cls >> 3;
#endif
        isa = newisa;
    }
}

#if __ARM_ARCH_7K__ >= 2  ||  (__arm64__ && !__LP64__)
#   define SUPPORT_INDEXED_ISA 1
#else
#   define SUPPORT_INDEXED_ISA 0
#endif

如果參數(shù)nonpointer 的值為true,走else 分支。對于64位系統(tǒng)而言,SUPPORT_INDEXED_ISA 始終是0,所以bits被賦值為ISA_MAGIC_VALUE。上文介紹isa 時(shí)說過,對于arm64來說,這個(gè)值為0x000001a000000001ULL,對于x86_64來說,這個(gè)值為0x001d800000000001ULL

這兩個(gè)值轉(zhuǎn)成二進(jìn)制后對應(yīng)的首位都是1,而首位存儲(chǔ)的就是isa_t 中nonpointer字段的值。

inline void objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
    assert(!cls->instancesRequireRawIsa());
    assert(hasCxxDtor == cls->hasCxxDtor());

    initIsa(cls, true, hasCxxDtor);
}

initInstanceIsa中調(diào)用的initIsa傳遞的nonpointer參數(shù)為true,所以64位系統(tǒng)下isa_t中nonpointer字段是1,而以下3個(gè)函數(shù)會(huì)調(diào)用initInstanceIsa

可見,在64位系統(tǒng)下,對于實(shí)例變量而言,isa_t中的nonpointer字段始終是1

0x05 引用計(jì)數(shù)器的獲取

- (NSUInteger)retainCount {
    return ((id)self)->rootRetainCount();
}

inline uintptr_t objc_object::rootRetainCount()
{
    if (isTaggedPointer()) return (uintptr_t)this;

    sidetable_lock();
    isa_t bits = LoadExclusive(&isa.bits);
    ClearExclusive(&isa.bits);
    if (bits.nonpointer) {
        uintptr_t rc = 1 + bits.extra_rc;
        if (bits.has_sidetable_rc) {
            rc += sidetable_getExtraRC_nolock();
        }
        sidetable_unlock();
        return rc;
    }

    sidetable_unlock();
    return sidetable_retainCount();
}

由于bits.nonpointer等于1,所以會(huì)走if 內(nèi)部邏輯,引用計(jì)數(shù)器的值等于1 + bits.extra_rc,如果has_sidetable_rc 字段存儲(chǔ)的是1,再通過sidetable_getExtraRC_nolock()加上溢出部分的值

0x06 answer

有了以上認(rèn)知,文章開頭的幾個(gè)疑問可以統(tǒng)一這樣解釋:

在ARC下,使用弱引用對象會(huì)調(diào)用objc_loadWeakRetained ,這個(gè)函數(shù)內(nèi)會(huì)調(diào)用rootRetain,而rootRetain 會(huì)使isa 中的extra_rc 字段加1,從而導(dǎo)致引用計(jì)數(shù)器加1。objc_loadWeakRetained 之后會(huì)調(diào)用_objc_release ,CFTypeRef cf_weakObj = (__bridge CFTypeRef)weakObj這句代碼執(zhí)行后,因rootRetain 引起的引用計(jì)數(shù)器加1已經(jīng)被_objc_release 減1,所以CFGetRetainCount(cf_weakObj)獲取到的值是1。而CFGetRetainCount((__bridge CFTypeRef)weakObj)執(zhí)行時(shí)還未執(zhí)行_objc_release 減1操作,所以獲取的值是2


Have fun!

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

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

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