[iOS] 内存管理-引用计数

作者: 沉江小鱼 | 来源:发表于2021-04-09 22:19 被阅读0次

    isa结构分析中有提到对象的引用计数会存储到isa中,这篇文章来具体分析一下对象引用计数的存储操作。

    1. ARC 自动引用计数

    自动引用计数(Automatic Reference Count),也就是我们常说的 ARC,也是目前 OC 中使用的内存管理计数,这里就不做赘述了。

    ARC 的工作原理大致是这样的:当我们编译源码的时候,编译器会分析源码中每个对象的生命周期,然后基于这些对象的生命周期,来添加相应的引用计数操作代码。所以,ARC 是工作在编译期的一种技术方案。

    在编译之后,ARCMRC 代码是没有什么区别的,所以二者可以在源码中共存。相对于垃圾回收这类内存管理方案,ARC 不会带来运行时的额外开销,所以对于应用的运行效率不会有影响。相反,由于 ARC 能够深度分析每一个对象的生命周期,它能够做到比人工管理引用计数更加高效。

    2. 获取对象的引用计数

    调用方法如下:

    uintptr_t
    _objc_rootRetainCount(id obj)
    {
        ASSERT(obj);
    
        return obj->rootRetainCount();
    }
    
    ⏬
    
    inline uintptr_t 
    objc_object::rootRetainCount()
    {
        if (isTaggedPointer()) return (uintptr_t)this;
    
        sidetable_lock();
        isa_t bits = LoadExclusive(&isa.bits);
        ClearExclusive(&isa.bits);
        // 如果是优化过的isa
        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();
    }
    

    rootRetainCount()方法中可以看出:

    • 会先判断当前对象是否为TaggedPointer,如果是,则直接将自身指针作为引用计数返回,这个判断在很多地方都会用到,在之后会进行详细介绍
    • 如果是优化过的isa引用计数 = bits.extra_rc + 1 + sidetable_getExtraRC_nolock(如果bits.has_sidetable_rctrue)
    • 如果是未优化过的isa引用计数 = sidetable_retainCount

    接下来我们去看下sidetable_getExtraRC_nolock()sidetable_retainCount()方法。

    2.1 sidetable_getExtraRC_nolock()

    被优化过的isa,会调用sidetable_getExtraRC_nolock方法获取存储在SideTable中的引用计数,该方法的代码实现如下:

    size_t 
    objc_object::sidetable_getExtraRC_nolock()
    {
        ASSERT(isa.nonpointer);
        SideTable& table = SideTables()[this];
        RefcountMap::iterator it = table.refcnts.find(this);
        if (it == table.refcnts.end()) return 0;
        else return it->second >> SIDE_TABLE_RC_SHIFT;
    }
    

    从代码实现中可以看到对象的引用计数也会在SideTable中进行存储,会从SideTables中取出对象对应的SideTable,然后遍历tablerefcnts

    这里的refcnts属性就是存储引用计数的散列表,如下:

    typedef objc::DenseMap RefcountMap;
    🔽
    struct SideTable {
        spinlock_t slock;
        RefcountMap refcnts;
        weak_table_t weak_table;
        ...
    };
    

    需要注意的是,这里把键值对的值做了向右移位操作:it->second >> SIDE_TABLE_RC_SHIFT:

    #ifdef __LP64__
    #   define WORD_SHIFT 3UL
    #   define WORD_MASK 7UL
    #   define WORD_BITS 64
    #else
    #   define WORD_SHIFT 2UL
    #   define WORD_MASK 3UL
    #   define WORD_BITS 32
    #endif
    
    #define SIDE_TABLE_WEAKLY_REFERENCED (1UL<<0)
    #define SIDE_TABLE_DEALLOCATING      (1UL<<1)  // MSB-ward of weak bit
    #define SIDE_TABLE_RC_ONE            (1UL<<2)  // MSB-ward of deallocating bit
    #define SIDE_TABLE_RC_PINNED         (1UL<<(WORD_BITS-1))
    
    #define SIDE_TABLE_RC_SHIFT 2
    #define SIDE_TABLE_FLAG_MASK (SIDE_TABLE_RC_ONE-1)
    

    可以看出SIDE_TABLE_WEAKLY_REFERENCED 值为1UL<<0,用第一个bit位标识对象是否有过weak对象,SIDE_TABLE_DEALLOCATING 值为1UL<<1,第二个bit位标识对象是否正在释放,所以从第三个 bit 位开始才是存储引用计数数值的地方,所以这里要做向右移两位的操作。而对引用计数的 +1 和 -1 使用SIDE_TABLE_RC_ONE进行操作,用SIDE_TABLE_RC_PINNED 来判断是否引用计数值有可能溢出。

    2.2 sidetable_retainCount()

    没有被优化过的isa,则会调用sidetable_retainCount方法,代码如下:

    uintptr_t
    objc_object::sidetable_retainCount()
    {
        SideTable& table = SideTables()[this];
    
        size_t refcnt_result = 1;
        
        table.lock();
        RefcountMap::iterator it = table.refcnts.find(this);
        if (it != table.refcnts.end()) {
            // this is valid for SIDE_TABLE_RC_PINNED too
            refcnt_result += it->second >> SIDE_TABLE_RC_SHIFT;
        }
        table.unlock();
        return refcnt_result;
    }
    

    该方法会获取存储在 SideTable中的引用计数,然后+1,即为对象的引用计数,操作和上面那个方法类似。

    3. retain操作

    在调用retain方法时,最终会调用到rootRetain这个方法,源码如下:

    // 两个参数都是 false false
    ALWAYS_INLINE id 
    objc_object::rootRetain(bool tryRetain, bool handleOverflow)
    {
        // 判断是否为 TaggedPointer
        if (isTaggedPointer()) return (id)this;
        // 默认不加锁,也就是默认不使用 sideTable
        bool sideTableLocked = false;
        // 是否需要将引用计数存到 sideTable
        bool transcribeToSideTable = false;
    
        // 需要对引用计数+1,即 retainCount + 1,而引用计数存储在 isa 的 bits 中,需要进行新旧 isa 的替换
        isa_t oldisa;
        isa_t newisa;
    
        do {
            transcribeToSideTable = false;
            // 通过 LoadExclusive  方法加载 isa 的值,并加锁
            oldisa = LoadExclusive(&isa.bits);
            newisa = oldisa;
            // 如果isa没有被优化过,slowpath表示为小概率事件
            if (slowpath(!newisa.nonpointer)) {
                // 解锁
                ClearExclusive(&isa.bits);
                // rawISA() = (Class)isa.bits,如果当前对象 isa 指向元类,直接返回
                if (rawISA()->isMetaClass()) return (id)this;
                // 如果不需要 retain 对象,且 sideTable 已经上锁,则解锁
                if (!tryRetain && sideTableLocked) sidetable_unlock();
                //  sidetable_tryRetain 尝试对引用计数器进行+1的操作 返回+1操作是否成功,这里 tryRetain 为 fasle
                if (tryRetain) return sidetable_tryRetain() ? (id)this : nil;
                // 将sidetable中保存的引用计数+1同时返回引用计数
                else return sidetable_retain();
            }
            // don't check newisa.fast_rr; we already called any RR overrides
            // 判断isa 是否正在销毁
            if (slowpath(tryRetain && newisa.deallocating)) {
                ClearExclusive(&isa.bits);
                if (!tryRetain && sideTableLocked) sidetable_unlock();
                return nil;
            }
            // 标记引用计数是否溢出
            // 之前文章中介绍过,isa的ectra_rc在 x86_64架构下占 8 位,也就是最多存储 255,之后如果再 addc,就会发生溢出,在溢出之后,将会拿 2 的 7 次方存储到散列表中,newisa.extra_rc 回到 128
            uintptr_t carry;
            newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry);  // extra_rc++
            // 如果溢出了
            if (slowpath(carry)) {
                // newisa.extra_rc++ overflowed
                if (!handleOverflow) {
                    ClearExclusive(&isa.bits);
                    return rootRetain_overflow(tryRetain);
                }
                // Leave half of the retain counts inline and 
                // prepare to copy the other half to the side table.
                // 保留 isa 中 extra_rc一半的值,将另一半存到 sideTable 中
                if (!tryRetain && !sideTableLocked) sidetable_lock();
                sideTableLocked = true;
                transcribeToSideTable = true;
                // 重新设置为 2 的 7 次方,x86_64下 #   define RC_HALF  (1ULL<<7)
                newisa.extra_rc = RC_HALF;
                newisa.has_sidetable_rc = true;
            }
            // while循环开始 直到 isa.bits 中的值被成功更新成 newisa.bits
            // 将更新后的newisa的值更新到isabit中
        } while (slowpath(!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)));
        
        // 如果需要转移引用计数到sidetable中
        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;
    }
    

    如果isa是没有被优化过的,需要将 sideTable存储的引用计数+1,方法为:sidetable_retain,源码如下:

    // 将 SideTable 表中的引用计数 +1
    id
    objc_object::sidetable_retain()
    {
    #if SUPPORT_NONPOINTER_ISA
        ASSERT(!isa.nonpointer);
    #endif
        // 根据对象获取 存储引用计数的sidetable
        SideTable& table = SideTables()[this];
        
        table.lock();
        // 获取sidetable中存储的引用计数值
        size_t& refcntStorage = table.refcnts[this];
        // 如果引用计数值没有溢出
        if (! (refcntStorage & SIDE_TABLE_RC_PINNED)) {
            // 引用计数值+SIDE_TABLE_RC_ONE
            // #define SIDE_TABLE_RC_ONE            (1UL<<2)
            refcntStorage += SIDE_TABLE_RC_ONE;
        }
        table.unlock();
    
        return (id)this;
    }
    

    方法中将引用计数+1,实际上是加了SIDE_TABLE_RC_ONE,值为1UL << 2,这个我们在上面提到过,这是因为是从第3 位才开始存储引用计数的,第 1、2 位用来标记是否被弱引用,是否处于销毁状态。

    3.1 sidetable_addExtraRC_nolock

    上面说到会将 RC_HALF的值存储到SideTable中,该方法代码如下:

    bool 
    objc_object::sidetable_addExtraRC_nolock(size_t delta_rc)
    {
        ASSERT(isa.nonpointer);
        // 获取对象对应的 SideTable
        SideTable& table = SideTables()[this];
    
        // 获取当前存储的引用计数
        size_t& refcntStorage = table.refcnts[this];
        // 赋值给旧的
        size_t oldRefcnt = refcntStorage;
        // isa-side bits should not be set here
        ASSERT((oldRefcnt & SIDE_TABLE_DEALLOCATING) == 0);
        ASSERT((oldRefcnt & SIDE_TABLE_WEAKLY_REFERENCED) == 0);
    
        if (oldRefcnt & SIDE_TABLE_RC_PINNED) return true;
    
        //引用计数也溢出判断参数
        uintptr_t carry;
        // delta_rc左移两位,右边的两位分别用来记录DEALLOCATING(销毁ing) 跟WEAKLY_REFERENCED(弱引用计数)
        size_t newRefcnt = 
            addc(oldRefcnt, delta_rc << SIDE_TABLE_RC_SHIFT, 0, &carry);
        //如果sidetable也溢出了。
        if (carry) {
            // 如果是32位的情况 SIDE_TABLE_RC_PINNED = 1<< (32-1)
            // int的最大值 SIDE_TABLE_RC_PINNED = 2147483648
            //  SIDE_TABLE_FLAG_MASK = 3
            // refcntStorage = 2147483648 | (oldRefcnt & 3)
            // 如果溢出,直接把refcntStorage 设置成最大值
            refcntStorage =
                SIDE_TABLE_RC_PINNED | (oldRefcnt & SIDE_TABLE_FLAG_MASK);
            return true;
        }
        else {
            refcntStorage = newRefcnt;
            return false;
        }
    }
    

    4. release 操作

    对象的release方法,最终会调用到rootRelease方法,代码如下:

    // // 两个参数分别是 是否需要调用dealloc函数,是否需要处理 向下溢出的问题
    ALWAYS_INLINE bool 
    objc_object::rootRelease(bool performDealloc, bool handleUnderflow)
    {
        // 如果是TaggedPointer 不需要进行release操作
        if (isTaggedPointer()) return false;
        // 局部变量sideTable是否上锁 默认false
        bool sideTableLocked = false;
    
        // 用来记录这个对象的 isa 指针
        isa_t oldisa;
        isa_t newisa;
    
     retry:
        do {
            // 加载 isa
            oldisa = LoadExclusive(&isa.bits);
            newisa = oldisa;
            // isa是否为nonpointer
            if (slowpath(!newisa.nonpointer)) {
                ClearExclusive(&isa.bits);
                // isa 指向元类,说明当前为类对象,不需要 release
                if (rawISA()->isMetaClass()) return false;
                if (sideTableLocked) sidetable_unlock();
                // 调用 sidetable_release 进行引用计数-1 操作
                return sidetable_release(performDealloc);
            }
            // don't check newisa.fast_rr; we already called any RR overrides
            // 判断溢出,也就是判断是否向下溢出,结果成为负数了
            uintptr_t carry;
            // 进行引用计数 -1 操作,即 extra_rc - 1
            newisa.bits = subc(newisa.bits, RC_ONE, 0, &carry);  // extra_rc--
            if (slowpath(carry)) {
                // don't ClearExclusive()
                // 调用 underflow 进行向下溢出的处理
                goto underflow;
            }
            //  开启循环,直到 isa.bits 中的值被成功更新成 newisa.bits
        } while (slowpath(!StoreReleaseExclusive(&isa.bits, 
                                                 oldisa.bits, newisa.bits)));
        // 到这里,说明引用计数-1 已经完成了
        if (slowpath(sideTableLocked)) sidetable_unlock();
        return false;
    
     underflow:
        // newisa.extra_rc-- underflowed: borrow from side table or deallocate
        // newisa 的 extra_rc 在执行-1 操作之后成为负数了,也就是向下溢出
        // abandon newisa to undo the decrement
        // 这里重新赋值,不用 extra_rc 中减了,从 sideTable 中减
        newisa = oldisa;
        // 判断是否在 sideTable 中存储了引用计数
        if (slowpath(newisa.has_sidetable_rc)) {
            // 判断是否需要处理向下溢出
            if (!handleUnderflow) {
                ClearExclusive(&isa.bits);
                // 如果不需要处理下溢 直接调用 rootRelease_underflow方法
                return rootRelease_underflow(performDealloc);
            }
    
            // Transfer retain count from side table to inline storage.
    
            if (!sideTableLocked) {
                ClearExclusive(&isa.bits);
                sidetable_lock();
                sideTableLocked = true;
                // Need to start over to avoid a race against 
                // the nonpointer -> raw pointer transition.
                goto retry;
            }
    
            // Try to remove some retain counts from the side table.
            // 从散列表中取出存储的一半引用计数
            size_t borrowed = sidetable_subExtraRC_nolock(RC_HALF);
    
            // To avoid races, has_sidetable_rc must remain set 
            // even if the side table count is now zero.
            // 为了避免冲突 has_sidetable_rc 标志位必须保留1的状态,即使sidetable中的个数为0
            if (borrowed > 0) {
                // Side table retain count decreased.
                // Try to add them to the inline count.
                // 进行 -1 操作,然后存储到 extra_rc 中
                newisa.extra_rc = borrowed - 1;  // redo the original decrement too
                // 然后将修改同步到isa中
                bool stored = StoreReleaseExclusive(&isa.bits, 
                                                    oldisa.bits, newisa.bits);
                if (!stored) {
                    // Inline update failed. 
                    // Try it again right now. This prevents livelock on LL/SC 
                    // architectures where the side table access itself may have 
                    // dropped the reservation.
                    isa_t oldisa2 = LoadExclusive(&isa.bits);
                    isa_t newisa2 = oldisa2;
                    if (newisa2.nonpointer) {
                        uintptr_t overflow;
                        newisa2.bits = 
                            addc(newisa2.bits, RC_ONE * (borrowed-1), 0, &overflow);
                        if (!overflow) {
                            stored = StoreReleaseExclusive(&isa.bits, oldisa2.bits, 
                                                           newisa2.bits);
                        }
                    }
                }
    
                if (!stored) {
                    // Inline update failed.
                    // Put the retains back in the side table.
                    sidetable_addExtraRC_nolock(borrowed);
                    goto retry;
                }
    
                // Decrement successful after borrowing from side table.
                // This decrement cannot be the deallocating decrement - the side 
                // table lock and has_sidetable_rc bit ensure that if everyone 
                // else tried to -release while we worked, the last one would block.
                sidetable_unlock();
                return false;
            }
            else {
                // Side table is empty after all. Fall-through to the dealloc path.
                // 在从Side table拿出一部分引用计数之后 Side table为空
            }
        }
    
        // Really deallocate.
        //此时extra_rc中值为0,散列表中也是空的,则直接进行析构,即自动触发dealloc流程
        // Really deallocate.
        //触发dealloc的时机
        if (slowpath(newisa.deallocating)) {
            ClearExclusive(&isa.bits);
            if (sideTableLocked) sidetable_unlock();
            return overrelease_error();
            // does not actually return
        }
        // 将对象被释放的标志位置为true
        newisa.deallocating = true;
        // 将newisa同步到isa中 如果失败 进行重试
        if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;
    
        if (slowpath(sideTableLocked)) sidetable_unlock();
    
        __c11_atomic_thread_fence(__ATOMIC_ACQUIRE);
        // 如果需要执行dealloc方法 那么调用该对象的dealloc方法
        if (performDealloc) {
            //发送一个dealloc消息
            ((void(*)(objc_object *, SEL))objc_msgSend)(this, @selector(dealloc));
        }
        return true;
    }
    
    4.1 sidetable_release方法

    isa没有被优化时,-1操作实际上操作的是SideTable中存储的值,源码如下:

    uintptr_t
    objc_object::sidetable_release(bool performDealloc)
    {
    #if SUPPORT_NONPOINTER_ISA
        ASSERT(!isa.nonpointer);
    #endif
        SideTable& table = SideTables()[this];
    
        bool do_dealloc = false;
    
        table.lock();
        auto it = table.refcnts.try_emplace(this, SIDE_TABLE_DEALLOCATING);
        auto &refcnt = it.first->second;
        // 如果当前对象之前不存在 map 中
        if (it.second) {
            do_dealloc = true;
        } else if (refcnt < SIDE_TABLE_DEALLOCATING) {
            // 如果引用计数的值小于 SIDE_TABLE_DEALLOCATING = 2(0010)
            // 这个对象需要被销毁
            // SIDE_TABLE_WEAKLY_REFERENCED may be set. Don't change it.
            do_dealloc = true;
            refcnt |= SIDE_TABLE_DEALLOCATING;
        } else if (! (refcnt & SIDE_TABLE_RC_PINNED)) {
            // 如果引用计数有值且未溢出那么-1
            refcnt -= SIDE_TABLE_RC_ONE;
        }
        table.unlock();
        // 如果需要执行dealloc 那么就调用这个对象的dealloc
        if (do_dealloc  &&  performDealloc) {
            ((void(*)(objc_object *, SEL))objc_msgSend)(this, @selector(dealloc));
        }
        return do_dealloc;
    }
    

    5. 总结

    主要是记录了 ARC的实现原理,以及对于引用计数的获取和 retain&release操作,还有当retain时,extra_rc不足以存储引用计数时,如何将一部分引用计数存储到SideTable中的,release时,如果extra_rc为负数时,如何将存储到SideTable中的引用计数又转回到extra_rc中的。

    相关文章

      网友评论

        本文标题:[iOS] 内存管理-引用计数

        本文链接:https://www.haomeiwen.com/subject/oavvkltx.html