黑箱中的retain 和 release

在接口设计时,我们经常要考虑某些意义上的平衡。在内存管理中,Objective-C 同时为我们提供了增加引用计数的 retain 和减少引用计数的 release 方法。

这篇文章会在源代码层面介绍 Objective-C 中 retain 和 release 的实现,它们是如何达到平衡的。

从 retain 开始

如今我们已经进入了全面使用 ARC 的时代, retain 和 release 方法已经很难出现于我们的视野中了,绝大多数内存管理的实现细节都由编译器代劳。

在这里,我们还要从 retain 方法开始,对内存管理的实现细节一探究竟。

下面是 retain 方法的调用栈:

- [NSObject retain]
└── id objc_object::rootRetain()
    └── id objc_object::rootRetain(bool tryRetain, bool handleOverflow)
        ├── uintptr_t LoadExclusive(uintptr_t *src)
        ├── uintptr_t addc(uintptr_t lhs, uintptr_t rhs, uintptr_t carryin, uintptr_t *carryout)
        ├── uintptr_t bits
        │   └── uintptr_t has_sidetable_rc  
        ├── bool StoreExclusive(uintptr_t *dst, uintptr_t oldvalue, uintptr_t value)
        └── bool objc_object::sidetable_addExtraRC_nolock(size_t delta_rc)                
            └── uintptr_t addc(uintptr_t lhs, uintptr_t rhs, uintptr_t carryin, uintptr_t *carryout)

调用栈中的前两个方法的实现直接调用了下一个方法:

- (id)retain {
    return ((id)self)->rootRetain();
}

id objc_object::rootRetain() {
    return rootRetain(false, false);
}

而 id objc_object::rootRetain(bool tryRetain, bool handleOverflow) 方法是调用栈中最重要的方法,其原理就是将 isa 结构体中的 extra_rc 的值加一。

extra_rc 就是用于保存自动引用计数的标志位,下面就是 isa 结构体中的结构, 可以看到有19位都是保存引用计数的(arm64下19位,x86下8位),

nonpointer也很重要, 下面的很多判断都会根据这个nonpointer进不同的if,

  • 0,代表普通的指针,存储着Class、Meta-Class对象的内存地址
  • 1,代表优化过,使用位域存储更多的信息, 在64位的系统上应该都是1

先说结论, 这样看代码会比较好理解. rootRetain分成 3 个小分支:

  • TaggedPointer:值存在指针内,直接返回。
  • !newisa.nonpointer:未优化的 isa ,使用sidetable_retain()
  • newisa.nonpointer:已优化的 isa , 这其中又分 extra_rc 溢出和未溢出的两种情况。
    • 未溢出时,isa.extra_rc + 1 完事。
    • 溢出时,将 isa.extra_rc 中一半值转移至sidetable中,然后将isa.has_sidetable_rc设置为true,表示使用了sidetable来计算引用次数, 下次再retain又是把isa.extra_rc+1

正常的 rootRetain

这是简化后的 rootRetain 方法的实现,其中只有处理一般情况的代码:

id objc_object::rootRetain(bool tryRetain, bool handleOverflow) {
    isa_t oldisa;
    isa_t newisa;

    do {
        oldisa = LoadExclusive(&isa.bits);
        newisa = oldisa;

        uintptr_t carry;
        newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry);
    } while (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits));

    return (id)this;
}

在这里我们假设的条件是 isa 中的 extra_rc 的位数足以存储 retainCount

  1. 使用 LoadExclusive 加载 isa 的值
  2. 调用 addc(newisa.bits, RC_ONE, 0, &carry) 方法将 isa 的值加一
  3. 调用 StoreExclusive(&isa.bits, oldisa.bits, newisa.bits) 更新 isa 的值
  4. 返回当前对象

有进位版本的 rootRetain

在这里调用 addc 方法为 extra_rc 加一时,19 位的 extra_rc 可能不足以保存引用计数。

id objc_object::rootRetain(bool tryRetain, bool handleOverflow) {
    transcribeToSideTable = false;
    isa_t oldisa = LoadExclusive(&isa.bits);
    isa_t newisa = oldisa;

    uintptr_t carry;
    newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry);

    if (carry && !handleOverflow)
        return rootRetain_overflow(tryRetain);
}

extra_rc 不足以保存引用计数,并且 handleOverflow = false

当方法传入的 handleOverflow = false 时(这也是通常情况),我们会调用 rootRetain_overflow 方法:

id objc_object::rootRetain_overflow(bool tryRetain) {
    return rootRetain(tryRetain, true);
}

这个方法其实就是重新执行 rootRetain 方法,并传入 handleOverflow = true

当传入的 handleOverflow = true 时,我们就会在 rootRetain 方法中处理引用计数的溢出。这一次走的流程变成了这样

id objc_object::rootRetain(bool tryRetain, bool handleOverflow) {
    bool sideTableLocked = false;

    isa_t oldisa;
    isa_t newisa;

    do {
        oldisa = LoadExclusive(&isa.bits);
        newisa = oldisa;
        uintptr_t carry;
        newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry);

        if (carry) {
            newisa.extra_rc = RC_HALF;
            newisa.has_sidetable_rc = true;
        }
    } while (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits));

    sidetable_addExtraRC_nolock(RC_HALF);

    return (id)this;
}

当调用这个方法,并且 handleOverflow = true 时,我们就可以确定 carry 一定是存在的了,

因为 extra_rc 已经溢出了,extra_rc 总共为 19 位,所以要更新它的值为最大值的一半 RC_HALF

define RC_HALF  (1ULL<<18)

然后设置 has_sidetable_rc 为真,存储新的 isa 的值之后,调用 sidetable_addExtraRC_nolock 方法。

bool objc_object::sidetable_addExtraRC_nolock(size_t delta_rc) {
    SideTable& table = SideTables()[this];

    size_t& refcntStorage = table.refcnts[this];
    size_t oldRefcnt = refcntStorage;

    if (oldRefcnt & SIDE_TABLE_RC_PINNED) return true;

    uintptr_t carry;
    // 最重要的一句, oldRefcnt+delta_rc
    size_t newRefcnt =
        addc(oldRefcnt, delta_rc << SIDE_TABLE_RC_SHIFT, 0, &carry);
    if (carry) {
        refcntStorage = SIDE_TABLE_RC_PINNED | (oldRefcnt & SIDE_TABLE_FLAG_MASK);
        return true;
    } else {
        refcntStorage = newRefcnt;
        return false;
    }
}

因为 refcnts 中的 64 为的最低两位是有意义的标志位,所以在使用 addc 时要将 delta_rc 左移两位,获得一个新的引用计数 newRefcnt

如果这时出现了溢出,那么就会撤销这次的行为。否则,会将新的引用计数存储到 refcntStorage 指针中。


回顾上面内容可以发现, 在 iOS 的内存管理中,我们使用了 isa 结构体中的 extra_rc 和 SideTable 来存储某个对象的自动引用计数.

好了, 我们已经从头梳理了 retain 方法的调用栈及其实现。再看一遍完整的代码, 加上了注释 

ALWAYS_INLINE id objc_object::rootRetain(bool tryRetain, bool handleOverflow) {
    // 如果是 TaggedPointer 直接返回
    if (isTaggedPointer()) return (id)this;

    bool sideTableLocked = false;
    bool transcribeToSideTable = false;

    isa_t oldisa;
    isa_t newisa;

    do {
        transcribeToSideTable = false;
        // 获取 isa
        oldisa = LoadExclusive(&isa.bits);
        newisa = oldisa;
        if (slowpath(!newisa.nonpointer)) {
            // 未优化的 isa 部分, 在hash表中增加引用计数
            ClearExclusive(&isa.bits);
            if (!tryRetain && sideTableLocked) sidetable_unlock();
            // sidetable_tryRetain真正干活的, 在SideTables中+1
            if (tryRetain) return sidetable_tryRetain() ? (id)this : nil;
            else return sidetable_retain();
        }
        // 正在被释放的处理
        // donot check newisa.fast_rr; we already called any RR overrides
        if (slowpath(tryRetain && newisa.deallocating)) {
            ClearExclusive(&isa.bits);
            if (!tryRetain && sideTableLocked) sidetable_unlock();
            return nil;
        }
        // extra_rc 未溢出时引用计数++
        uintptr_t carry;
        newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry);  // extra_rc++

        // extra_rc 溢出
        if (slowpath(carry)) {
            // newisa.extra_rc++ overflowed
            if (!handleOverflow) {
                ClearExclusive(&isa.bits);
                // 重新调用该函数 入参 handleOverflow 为 true
                return rootRetain_overflow(tryRetain);
            }
            // isa中保留一半引用计数,设置has_sidetable_rc表明使用了hash表保存
            // 设置了标志位transcribeToSideTable为true,下面会把另一半复制到 side table.
            if (!tryRetain && !sideTableLocked) sidetable_lock();
            sideTableLocked = true;
            transcribeToSideTable = true;
            newisa.extra_rc = RC_HALF;
            newisa.has_sidetable_rc = true;
        }
        //  更新 isa 值
    } while (slowpath(!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)));

    if (slowpath(transcribeToSideTable)) {
        // 根据上面的标志位transcribeToSideTable,此处将另一半复制到 side table side table.
        sidetable_addExtraRC_nolock(RC_HALF);
    }

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

下面要介绍的是在内存管理中如何使用 release 方法平衡这个方法的。

以 release 结束

与 release 方法相似,我们看一下这个方法简化后的调用栈:

- [NSObject release]
└── id objc_object::rootRelease()
    └── id objc_object::rootRelease(bool performDealloc, bool handleUnderflow)

前面的两个方法的实现和 retain 中的相差无几,这里就直接跳过了。

同样,在分析 release 方法时,我们也根据上下文的不同,将 release 方法的实现拆分为三部分,说明它到底是如何调用的。

这么一长串代码,说了结论之后才好理解,  将其分解后和 rootRetain 逻辑类似:

  • TaggedPointer: 直接返回 false。
  • !nonpointer: 未优化的 isa 执行 sidetable_release。
  • nonpointer:已优化的 isa ,分下溢和未下溢两种情况。
    • 未下溢: extra_rc--。
    • 下溢:从 sidetable 中借位给 extra_rc 达到半满,如果无法借位则说明引用计数归零需要进行dealloc释放。其中借位时可能保存失败会不断重试。

正常的 release

这一个版本的方法调用可以说是最简版本的方法调用了:

bool objc_object::rootRelease(bool performDealloc, bool handleUnderflow) {
    isa_t oldisa;
    isa_t newisa;

    do {
        oldisa = LoadExclusive(&isa.bits);
        newisa = oldisa;

        uintptr_t carry;
        newisa.bits = subc(newisa.bits, RC_ONE, 0, &carry);
    } while (!StoreReleaseExclusive(&isa.bits, oldisa.bits, newisa.bits));

    return false;
}
  1. 使用 LoadExclusive 获取 isa 内容
  2. 将 isa 中的引用计数减一
  3. 调用 StoreReleaseExclusive 方法保存新的 isa

从 SideTable 借位

接下来,我们就要看两种相对比较复杂的情况了,首先是从 SideTable 借位成功的版本:

bool objc_object::rootRelease(bool performDealloc, bool handleUnderflow) {
    isa_t oldisa;
    isa_t newisa;

    do {
        oldisa = LoadExclusive(&isa.bits);
        newisa = oldisa;

        uintptr_t carry;
        newisa.bits = subc(newisa.bits, RC_ONE, 0, &carry);
        if (carry) goto underflow;
    } while (!StoreReleaseExclusive(&isa.bits, oldisa.bits, newisa.bits));

    ...

 underflow:
    newisa = oldisa;

    if (newisa.has_sidetable_rc) {
        if (!handleUnderflow) {
            return rootRelease_underflow(performDealloc);
        }

        size_t borrowed = sidetable_subExtraRC_nolock(RC_HALF);

        if (borrowed > 0) {
            newisa.extra_rc = borrowed - 1;
            bool stored = StoreExclusive(&isa.bits, oldisa.bits, newisa.bits);

            return false;
        }
    }
}

这里省去了使用锁来防止竞争条件以及调用 StoreExclusive 失败后恢复现场的代码。 我们会默认这里存在 SideTable,也就是 has_sidetable_rc = true

你可以看到,这里也有一个 handleUnderflow,与 retain 中的相同,如果发生了 underflow,会重新调用该 rootRelease 方法,并传入 handleUnderflow = true

在调用 sidetable_subExtraRC_nolock 成功借位之后,我们会重新设置 newisa 的值 newisa.extra_rc = borrowed - 1 并更新 isa

release 中调用 dealloc

如果在 SideTable 中也没有获取到借位的话,就说明没有任何的变量引用了当前对象(即 retainCount = 0),就需要向它发送 dealloc 消息了。

bool objc_object::rootRelease(bool performDealloc, bool handleUnderflow) {
    isa_t oldisa;
    isa_t newisa;

 retry:
    do {
        oldisa = LoadExclusive(&isa.bits);
        newisa = oldisa;

        uintptr_t carry;
        newisa.bits = subc(newisa.bits, RC_ONE, 0, &carry);
        if (carry) goto underflow;
    } while (!StoreReleaseExclusive(&isa.bits, oldisa.bits, newisa.bits));

    ...

 underflow:
    newisa = oldisa;

    if (newisa.deallocating) {
        return overrelease_error();
    }
    newisa.deallocating = true;
    StoreExclusive(&isa.bits, oldisa.bits, newisa.bits);

    if (performDealloc) {
        ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc);
    }
    return true;
}

上述代码会直接调用 objc_msgSend 向当前对象发送 dealloc 消息。

不过为了确保消息只会发送一次,我们使用 deallocating 标记位。

好了, 最后再看一遍rootRelease完整的代码, 加上了注释 

 
ALWAYS_INLINE bool objc_object::rootRelease(bool performDealloc, bool handleUnderflow)
{
    if (isTaggedPointer()) return false;

    bool sideTableLocked = false;

    isa_t oldisa;
    isa_t newisa;

 retry:
    do {
        oldisa = LoadExclusive(&isa.bits);
        newisa = oldisa;
        if (slowpath(!newisa.nonpointer)) {
            // 未优化 isa, 引用计数全部在hash表中
            ClearExclusive(&isa.bits);
            if (sideTableLocked) sidetable_unlock();
            // 入参是否要执行 Dealloc 函数,如果为 true 则执行 SEL_dealloc
            return sidetable_release(performDealloc);
        }

        // extra_rc --
        newisa.bits = subc(newisa.bits, RC_ONE, 0, &carry);  // extra_rc--
        if (slowpath(carry)) {
            // donot ClearExclusive()
            goto underflow;
        }
        // 更新 isa 值
    } while (slowpath(!StoreReleaseExclusive(&isa.bits, 
                                             oldisa.bits, newisa.bits)));

    if (slowpath(sideTableLocked)) sidetable_unlock();
    return false;

 underflow:
 	// 处理下溢,从 side table 中借位或者释放

    newisa = oldisa;
    // 如果使用了 sidetable_rc
    if (slowpath(newisa.has_sidetable_rc)) {
        if (!handleUnderflow) {
        	// 调用本函数处理下溢
            ClearExclusive(&isa.bits);
            return rootRelease_underflow(performDealloc);
        }

        // 从 sidetable 中借位引用计数给 extra_rc
        size_t borrowed = sidetable_subExtraRC_nolock(RC_HALF);

        if (borrowed > 0) {
			// extra_rc 是计算额外的引用计数,0 即表示被引用一次
            newisa.extra_rc = borrowed - 1;  // redo the original decrement too
            bool stored = StoreReleaseExclusive(&isa.bits, 
                                                oldisa.bits, newisa.bits);
                                                
            // 保存失败,恢复现场,重试                                    
            if (!stored) {
                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);
                    }
                }
            }

			// 如果还是保存失败,则还回 side table
            if (!stored) {
                sidetable_addExtraRC_nolock(borrowed);
                goto retry;
            }

            sidetable_unlock();
            return false;
        }
        else {
            // Side table is empty after all. Fall-through to the dealloc path.
        }
    }
    // 没有使用 sidetable_rc ,或者 sidetable_rc 计数 == 0 的就直接释放

    // 如果已经是释放中,抛个过度释放错误
    if (slowpath(newisa.deallocating)) {
        ClearExclusive(&isa.bits);
        if (sideTableLocked) sidetable_unlock();
        return overrelease_error();
        // does not actually return
    }
    // 更新 isa 状态
    newisa.deallocating = true;
    if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;

    if (slowpath(sideTableLocked)) sidetable_unlock();

	// 执行 SEL_dealloc 事件
    __sync_synchronize();
    if (performDealloc) {
        ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc);
    }
    return true;
}

到这里, 总结一下retain/release,  引用计数分别保存在isa.extra_rcsidetable中,当isa.extra_rc溢出时,将一半计数转移至sidetable中,而当其下溢时,又会将计数转回。当二者都为空时,会执行释放流程 。 

获取自动引用计数

最后还有 retainCount 的值是怎么计算的,我们直接来看 retainCount 方法的实现:

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

inline uintptr_t objc_object::rootRetainCount()
{
	// TaggedPointer 直接返回
    if (isTaggedPointer()) return (uintptr_t)this;

    sidetable_lock();
    // 加载 isa
    isa_t bits = LoadExclusive(&isa.bits);
    ClearExclusive(&isa.bits);
    // 优化的 isa 需要 sidetable + bits.extra_rc + 1
    if (bits.nonpointer) {
        uintptr_t rc = 1 + bits.extra_rc;
        if (bits.has_sidetable_rc) {
            rc += sidetable_getExtraRC_nolock();
        }
        sidetable_unlock();
        return rc;
    }
	// 未优化返回 sidetable_retainCount
    sidetable_unlock();
    return sidetable_retainCount();
}

根据方法的实现,如果自动引用计数为 1,extra_rc 实际上为 0,因为它保存的是额外的引用计数,我们通过这个行为能够减少很多不必要的函数调用。

  • 如果启动了指针优化, retainCount = extra_rc 中存储的值+sidetable_getExtraRC_nolock 返回的值
  • 如果未启用指针优化, retainCount = sidetable_getExtraRC_nolock 返回的值

小结

我们在这篇文章中已经介绍了 retain 和 release 这一对用于内存管理的方法是如何实现的,这里总结一下文章一下比较重要的问题。

  • extra_rc 只会保存额外的自动引用计数,对象实际的引用计数会在这个基础上 +1
  • Objective-C 使用 isa 中的 extra_rc 和 SideTable 来存储对象的引用计数
  • 在对象的引用计数归零时,会调用 dealloc 方法回收对象
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值