一段weak代码引发的探索

话不多说,直接看代码


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

看到输出结果后直接傻眼,脑子里迅速产生了几个疑问:

  1. 为什么输出的两个值不一样?
  2. 2是哪来的?
  3. 2后面是怎么变成1的?

0x01 debug

testCode()处打上断点,运行程序后控制台做如下操作(以下为部分截图):

先找到testCode的函数地址,接着反汇编。从截图的红框中可以看到调用了objc_loadWeakRetained_objc_release这两个函数

既然调用了release,在ARC下,objc_loadWeakRetained调用后的retainCount必然增加了1。查看源码发现,objc_loadWeakRetained会调用rootRetain,函数调用栈如下:

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

这里确实有对isaextra_rc字段进行加1操作,执行后的新旧isa对比如下:

newisa 的extra_rc 字段为1,而oldisa 的extra_rc 字段为0。如果extra_rc 字段溢出,会将extra_rc 设置为RC_HALF,并将has_sidetable_rc字段设置为true,显然has_sidetable_rc 是用来标识是否溢出的,溢出后会通过sidetable_addExtraRC_nolock函数计算并重新存储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是个union,如果定义了ISA_BITFIELD,则会存在以下字段:

#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架构下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位系统下的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

如果参数nonpointer 的值为true,走else 分支。对于64位系统而言,SUPPORT_INDEXED_ISA 始终是0,所以bits被赋值为ISA_MAGIC_VALUE。上文介绍isa 时说过,对于arm64来说,这个值为0x000001a000000001ULL,对于x86_64来说,这个值为0x001d800000000001ULL

这两个值转成二进制后对应的首位都是1,而首位存储的就是isa_t 中nonpointer字段的值。

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

    initIsa(cls, true, hasCxxDtor);
}

initInstanceIsa中调用的initIsa传递的nonpointer参数为true,所以64位系统下isa_t中nonpointer字段是1,而以下3个函数会调用initInstanceIsa

可见,在64位系统下,对于实例变量而言,isa_t中的nonpointer字段始终是1

0x05 引用计数器的获取

- (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,所以会走if 内部逻辑,引用计数器的值等于1 + bits.extra_rc,如果has_sidetable_rc 字段存储的是1,再通过sidetable_getExtraRC_nolock()加上溢出部分的值

0x06 answer

有了以上认知,文章开头的几个疑问可以统一这样解释:

在ARC下,使用弱引用对象会调用objc_loadWeakRetained ,这个函数内会调用rootRetain,而rootRetain 会使isa 中的extra_rc 字段加1,从而导致引用计数器加1。objc_loadWeakRetained 之后会调用_objc_release ,CFTypeRef cf_weakObj = (__bridge CFTypeRef)weakObj这句代码执行后,因rootRetain 引起的引用计数器加1已经被_objc_release 减1,所以CFGetRetainCount(cf_weakObj)获取到的值是1。而CFGetRetainCount((__bridge CFTypeRef)weakObj)执行时还未执行_objc_release 减1操作,所以获取的值是2


Have fun!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容