1. 程式人生 > IOS開發 >iOS 引用計數 retainCount、retain、release 原始碼分析+註釋+實驗

iOS 引用計數 retainCount、retain、release 原始碼分析+註釋+實驗

這篇文章與上一篇有較大的關聯,沒看過的可以先去看看 ^ _ ^

物件alloc後retainCount為什麼引用計數為1

        Person *p = [Person alloc]; // extrac = 0
        // alloc出來的引用計數為多少 -- 0 -- 1
        NSLog(@"%lu",(unsigned long)[p retainCount]); // 1
        [p retain]; // extrac = 0  -  1
        NSLog(@"%lu",(unsigned long)[p retainCount]); // extrac+1 = 2
        [p release];// -1
        NSLog(@"1 == %lu"
,(unsigned long)[p retainCount]); // 1 [p release];// 1-1 -- 引用計數位0的時候 我就析構 ? -- 響應 訊息 NSLog(@" 0 == %lu",(unsigned long)[p retainCount]); // 0 [p release];// -1 NSLog(@"-1 == %lu",(unsigned long)[p retainCount]); // -1 NSLog(@"完了"); 複製程式碼

物件alloc的時候,最終會走向建立isa

image.png
並沒有進行retainCount,引用計數為0,進行列印retainCount的時候由於當前引用計數為0,如果一直為0,那麼物件就會被銷燬,導致我們現在在做無用功,所以在objc_object::rootRetainCount()
中有判斷if (bits.nonpointer) {},isa初始化的時候,nonpointer為1,所以在呼叫retainCount時,會預設給該物件的引用計數+1。

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(); } 複製程式碼

retain & release

retain

執行順序 <1> - (id)retain {} <2> objc_object::rootRetain()引數分別:false,false <3> objc_object::rootRetain(bool tryRetain,bool handleOverflow) <4> 判斷新舊isa是否一致迴圈,一致就執行<9>,否則執行<5> <5> 迴圈獲取舊值,並賦給新值,為新值進行extra_rc+1 <6> 判斷是否溢位(x86_64 256),沒溢位就執行<9>,溢位走<7> <7> 執行rootRetain_overflow,回到<3>,handleOverflow為true,下次過來時執行<8> <8> x86_64留下引用計數的一半128,複製另一半存進去散列表 <9> return

// 並且呼叫retain的時候,傳入的兩個引數均為false
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;

    
    // 迴圈條件:判斷是否獨一份儲存,對比新舊isa,如果不是,就迴圈
    do {
        transcribeToSideTable = false;
        oldisa = LoadExclusive(&isa.bits);
        newisa = oldisa;
        if (slowpath(!newisa.nonpointer)) {
            ClearExclusive(&isa.bits);
            if (!tryRetain && sideTableLocked) sidetable_unlock();
            if (tryRetain) return sidetable_tryRetain() ? (id)this : nil;
            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;
        }
        //是否溢位,
        //經過實驗:在x86_64架構下,當newisa.extra_rc為255時,在進行addc,就會發生溢位
        //溢位之後,將會拿2的7次方的extra_rc 存到散列表中,newisa.extra_rc回到128
        uintptr_t carry;
        //這裡newisa.extra_rc 會+1 RC_ONE
        newisa.bits = addc(newisa.bits,RC_ONE,&carry);  // extra_rc++
        printf("%lu,",newisa.extra_rc);
        //newisa.extra_rc++如果溢位
        if (slowpath(carry)) {
            // newisa.extra_rc++ overflowed
            //第一次來的話,handleOverflow是false,會進判斷語句
            if (!handleOverflow) {
                ClearExclusive(&isa.bits);
                //這裡重新呼叫了當前方法rootRetain,但是handleOverflow = true
                return rootRetain_overflow(tryRetain);
            }
            // Leave half of the retain counts inline and 
            // prepare to copy the other half to the side table.
            // retry之後會來到這裡
            // 翻譯:留下內部關聯物件的一半,準備複製另一半存進去散列表
            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.
        // 拷貝一半(128)進散列表
        sidetable_addExtraRC_nolock(RC_HALF);
    }

    if (slowpath(!tryRetain && sideTableLocked)) sidetable_unlock();
    return (id)this;
}
複製程式碼
sidetable_addExtraRC_nolock散列表新增引用計數

這個在上一篇文章,記憶體管理方案中已經有提到過了,這裡在發一次,加點印象。

bool 
objc_object::sidetable_addExtraRC_nolock(size_t delta_rc)
{
    assert(isa.nonpointer);
    // 通過SideTables() 獲取SideTable
    SideTable& table = SideTables()[this];

    //獲取引用計數的size
    size_t& refcntStorage = table.refcnts[this];
    // 賦值給oldRefcnt
    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);

    // 如果oldRefcnt & SIDE_TABLE_RC_PINNED = 1
    // 就是 oldRefcnt = 2147483648 (32位情況)
    if (oldRefcnt & SIDE_TABLE_RC_PINNED) return true;
    
    //引用計數也溢位判斷引數
    uintptr_t carry;
    
    // 引用計數 add
    //delta_rc左移兩位,右邊的兩位分別是DEALLOCATING(銷燬ing) 跟WEAKLY_REFERENCED(弱引用計數)
    size_t newRefcnt = 
        addc(oldRefcnt,delta_rc << SIDE_TABLE_RC_SHIFT,&carry);
    //如果sidetable也溢位了。
    //這裡我for了幾百萬次,也沒有溢位,可見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;
    }
}
複製程式碼
release

執行順序 <1> - (oneway void)release {} <2> objc_object::rootRelease() 引數分別:true,false <3> objc_object::rootRelease(bool performDealloc,bool handleUnderflow) <4> 判斷新舊isa是否一致迴圈,一致就執行return,否則執行<5> <5> 迴圈獲取舊值,並賦給新值,為新值進行extra_rc-1 <6> 判斷是否溢位,沒溢位就執行return,溢位走<7> underflow <7> 判斷是否有用到散列表 <8> 從散列表中拿出RC_HALF,將這部分存進newisa <9> 存成功就return,不成功就重試,再不行就把拿出來的放回去,然後goto retry; <10> dealloc

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

    bool sideTableLocked = false;
    //新舊isa
    isa_t oldisa;
    isa_t newisa;

 retry:
    //跟retain一樣的判斷條件
    do {
        oldisa = LoadExclusive(&isa.bits);
        newisa = oldisa;
        if (slowpath(!newisa.nonpointer)) {
            ClearExclusive(&isa.bits);
            if (sideTableLocked) sidetable_unlock();
            return sidetable_release(performDealloc);
        }
        // don't check newisa.fast_rr; we already called any RR overrides
        uintptr_t carry;
        //newisa.extra_rc-1
        //如果溢位的時候, newisa.extra_rc = 255
        newisa.bits = subc(newisa.bits,&carry);  // extra_rc--
        if (slowpath(carry)) {
            // don't ClearExclusive()
            //如果溢位走這
            printf("釋放溢位了,underflow\n");
            goto underflow;
        }
    } while (slowpath(!StoreReleaseExclusive(&isa.bits,newisa.bits)));

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

 underflow:
    // newisa.extra_rc-- underflowed: borrow from side table or deallocate

    // abandon newisa to undo the decrement
    // 重新把舊isa給新isa,意思是把引用計數-1操作還原
    // 這時候的 newisa.extra_rc = 0
    newisa = oldisa;
    // retain的時候。如果有用到散列表,會 newisa.has_sidetable_rc = true;
    if (slowpath(newisa.has_sidetable_rc)) {
        printf("發現has_sidetable_rc = true \n");
        // 呼叫release的時候handleUnderflow = false
        if (!handleUnderflow) {
            ClearExclusive(&isa.bits);
            //類似retain時候retry,重新來一次,但是handleUnderflow為true
            return rootRelease_underflow(performDealloc);
        }

        // Transfer retain count from side table to inline storage.
        // 進判斷前 sideTableLocked 沒有重新賦值,所以一直是false
        if (!sideTableLocked) {
            ClearExclusive(&isa.bits);
            sidetable_lock();
            sideTableLocked = true;
            // Need to start over to avoid a race against 
            // the nonpointer -> raw pointer transition.
            // 去retry,重新回到上面,重複走一遍
            goto retry;
        }

        // Try to remove some retain counts from the side table.
        // 從散列表中拿出RC_HALF的引用計數
        size_t borrowed = sidetable_subExtraRC_nolock(RC_HALF);
        printf("借出來的 size === %lu \n",borrowed);
        // To avoid races,has_sidetable_rc must remain set 
        // even if the side table count is now zero.

        if (borrowed > 0) {
            // Side table retain count decreased.
            // Try to add them to the inline count.
            newisa.extra_rc = borrowed - 1;  // redo the original decrement too
            // 把拿出來的引用計數存到newisa
            bool stored = StoreReleaseExclusive(&isa.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),&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.
        }
    }

    // Really deallocate.
    // 如果newisa.has_sidetable_rc != true;
    // 就拋錯,release太多
    if (slowpath(newisa.deallocating)) {
        ClearExclusive(&isa.bits);
        if (sideTableLocked) sidetable_unlock();
        return overrelease_error();
        // does not actually return
    }
    newisa.deallocating = true;
    if (!StoreExclusive(&isa.bits,newisa.bits)) goto retry;

    if (slowpath(sideTableLocked)) sidetable_unlock();

    __sync_synchronize();
    if (performDealloc) {
        ((void(*)(objc_object *,SEL))objc_msgSend)(this,SEL_dealloc);
    }
    return true;
}
複製程式碼

###實驗: 在這個實驗中

  1. 我先對p retain了257次,256次保證溢位,在第257次時觀察在已經使用到了sidetable的情況下的引用計數。
  2. 然後再對p release了260次,保證能release次數大於retain次數,保證p dealloc,並且觀察在dealloc後,繼續release的情況。
        Person *p =[Person alloc]; // extrac = 0
        NSLog(@"開始retain\n");
        // 在Mac下 保證能retain溢位,並多retain一次
        for (int i = 0 ; i<257; i++) {
            [p retain];
        }
        NSLog(@"開始release\n");
        // 在Mac下 保證能release溢位,並且多釋放幾次
        for (int i = 0 ; i<260; i++) {
            [p release];
        }
複製程式碼
  1. 然後我在原始碼中各個位置都做了log處理,觀察進行lldb除錯

    retainlog標記.png
    releaselog標記.png

  2. 先看retain的log

    image.png

  3. retain結論:在retain發生溢位後,會存入128到散列表,newisa的當前引用計數為128,再繼續retain就在128的基礎上+1。

  4. 看release的log ,此時p的引用計數為129(但是如果呼叫retainCount就會是130)

    image.png

  5. release總結:

<1> 在release發生溢位,且當前newisa的has_sidetable_rc為true後> <2> 走performDealloc,將handleUnderflow設定成true,然後再遞迴一次 <3> 過了handleUnderflow這關之後,繼續遇到了sideTableLocked <4> release的時候sideTableLocked預設為false,把sideTableLocked設定為true後,就又要回到retry(這裡應該不算遞迴),又走了一遍上面的一大串程式碼。 <5> 可謂是過關斬將遇到兩個攔路虎handleUnderflow 、sideTableLocked,過了兩關後,從sidetable中拿出RC_HALF(2^7)的引用計數,-1 之後交給當前newisa.extra_rc。

TO BE CONTINUE ~