weak实现原理

在ARC模式中weak关键字常常用来处理对象之间的互相强引用导致的内存泄漏问题,主要是因为使用weak修饰变量不会导致引用计数的增加不会影响对象的生命周期,而且在对象释放之后会将自动指针置空避免也指针访问问题.那么系统是和实现weak管理的?

定位实现文件

  • 首先在Xcode中,打开汇编调试
  • Xcode->Debug->Debug Workflow->Always Show Disassembly
  • 创建对象并进行弱引用,并在弱引用处设置断点.
  • int main(int argc, const char * argv[]) {
        @autoreleasepool {
            NSObject *obj = [[NSObject alloc] init];
            __weak typeof(obj) weakObj = obj;//在此处断点
        }
    }
  • 执行
  • ...
    0x100000ece <+62>:  movq   %rax, -0x18(%rbp)
    ->  0x100000ed2 <+66>:  movq   -0x18(%rbp), %rax
        0x100000ed6 <+70>:  leaq   -0x20(%rbp), %rsi
        0x100000eda <+74>:  movq   %rsi, %rdi
        0x100000edd <+77>:  movq   %rax, %rsi
        0x100000ee0 <+80>:  callq  0x100000f2e               ; symbol stub for: objc_initWeak
        0x100000ee5 <+85>:  leaq   -0x20(%rbp), %rsi
        0x100000ee9 <+89>:  movq   %rsi, %rdi
        0x100000eec <+92>:  movq   %rax, -0x30(%rbp)
        0x100000ef0 <+96>:  callq  0x100000f28               ; symbol stub for: objc_destroyWeak
        0x100000ef5 <+101>: xorl   %ecx, %ecx
        0x100000ef7 <+103>: movl   %ecx, %esi
        0x100000ef9 <+105>: leaq   -0x18(%rbp), %rax
        0x100000efd <+109>: movq   %rax, %rdi
        0x100000f00 <+112>: callq  0x100000f34               ; symbol stub for: objc_storeStrong
        0x100000f05 <+117>: movq   -0x28(%rbp), %rdi
        0x100000f09 <+121>: callq  0x100000f1c               ; symbol stub for: objc_autoreleasePoolPop
        0x100000f0e <+126>: xorl   %eax, %eax
        0x100000f10 <+128>: addq   $0x30, %rsp
        0x100000f14 <+132>: popq   %rbp
        0x100000f15 <+133>: retq   
    
  • 发现下一步要执行的函数是objc_initWeak,为符号objc_initWeak设置断点
  • Xcode->Show the Breakpoint navigator->左下角 "+" ->Symbolic Breakpoint...
  • 发现在objc_initWeak函数的实现在libobjc.A.dylib中
  • libobjc.A.dylib`::objc_initWeak(id *, id):
        0x1003c6c40 <+0>:  pushq  %rbp
        0x1003c6c41 <+1>:  movq   %rsp, %rbp
        0x1003c6c44 <+4>:  subq   $0x20, %rsp
        0x1003c6c48 <+8>:  movq   %rdi, -0x10(%rbp)
        0x1003c6c4c <+12>: movq   %rsi, -0x18(%rbp)
    ->  0x1003c6c50 <+16>: cmpq   $0x0, -0x18(%rbp)
        0x1003c6c55 <+21>: jne    0x1003c6c73               ; <+51> at NSObject.mm:415:10
        0x1003c6c5b <+27>: movq   -0x10(%rbp), %rax
        0x1003c6c5f <+31>: movq   $0x0, (%rax)
        0x1003c6c66 <+38>: movq   $0x0, -0x8(%rbp)
        0x1003c6c6e <+46>: jmp    0x1003c6c87               ; <+71> at NSObject.mm:416:1
    ...

所以可以通过objc的源代码来查找相关实现.

查看实现

以下探讨使用objc756.2进行说明.

首先了解需要的数据结构

  • StripedMap

    • reinterpret_cast<new_type> (expression)是C++中用来处理无关类型转化的一个运算符,它会产生一个新的值,这个值会有与原始参数有完全相同的比特位.在该实现中用于将一个证书类型转化为指针类型,可以理解为生成一个开辟置顶大小空间的指针;
  • 使用场景:
    
    从指针类型到一个足够大的整数类型
    从整数类型或者枚举类型到指针类型
    从一个指向函数的指针到另一个不同类型的指向函数的指针
    从一个指向对象的指针到另一个不同类型的指向对象的指针
    从一个指向类函数成员的指针到另一个指向不同类型的函数成员的指针
    从一个指向类数据成员的指针到另一个指向不同类型的数据成员的指针

     

    • 全局维护了一个StripedMap变量,其内部实现是一个静态数组.在TARGET_OS_IPHONE非模拟器上数组元素的最大个数为8,否则数组元素的最大个数为64.
    • 通过将被引用对象的地址做indexForPointer运算使得每个被引用对象运算之后的结果在[0, StripeCount)之间;
    • 存储的值是抽象的PaddedT,在弱引用管理中存储的是结构体SideTable的实例.
  • static StripedMap<SideTable>& SideTables() {
        return *reinterpret_cast<StripedMap<SideTable>*>(SideTableBuf);
    }
    
    
    class StripedMap {
    #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
        enum { StripeCount = 8 };
    #else
        enum { StripeCount = 64 };
    #endif
    
        
        struct PaddedT {
            T value alignas(CacheLineSize);
        };
    
        PaddedT array[StripeCount];
        int count = StripeCount;
    
        //将被引用对象的指针索引化,结果在[0, StripeCount)
        static unsigned int indexForPointer(const void *p) {
            uintptr_t addr = reinterpret_cast<uintptr_t>(p);
            int count = StripeCount;
            return ((addr >> 4) ^ (addr >> 9)) % StripeCount;
        }
    
     public:
        T& operator[] (const void *p) { 
            return array[indexForPointer(p)].value; 
        }
        const T& operator[] (const void *p) const { 
            return const_cast<StripedMap<T>>(this)[p]; 
        }
    
        // Shortcuts for StripedMaps of locks.
        void lockAll() {
            for (unsigned int i = 0; i < StripeCount; i++) {
                array[i].value.lock();
            }
        }
    
        void unlockAll() {
            for (unsigned int i = 0; i < StripeCount; i++) {
                array[i].value.unlock();
            }
        }
    
        void forceResetAll() {
            for (unsigned int i = 0; i < StripeCount; i++) {
                array[i].value.forceReset();
            }
        }
    
        void defineLockOrder() {
            for (unsigned int i = 1; i < StripeCount; i++) {
                lockdebug_lock_precedes_lock(&array[i-1].value, &array[i].value);
            }
        }
    
        void precedeLock(const void *newlock) {
            // assumes defineLockOrder is also called
            lockdebug_lock_precedes_lock(&array[StripeCount-1].value, newlock);
        }
    
        void succeedLock(const void *oldlock) {
            // assumes defineLockOrder is also called
            lockdebug_lock_precedes_lock(oldlock, &array[0].value);
        }
    
        const void *getLock(int i) {
            if (i < StripeCount) return &array[i].value;
            else return nil;
        }
        
    #if DEBUG
        StripedMap() {
            // Verify alignment expectations.
            uintptr_t base = (uintptr_t)&array[0].value;
            uintptr_t delta = (uintptr_t)&array[1].value - base;
            assert(delta % CacheLineSize == 0);
            assert(base % CacheLineSize == 0);
        }
    #else
        constexpr StripedMap() {}
    #endif
    };
  • SideTable:主要用于辅助管理对象的引用计数和弱引用依赖.
    • slock:保证操作线程安全的自旋锁;
    • 用于辅助管理对象的引用计数:当对象isa中extra_rc不足以存储对象引用对象时,has_sidetable_rc会被置为1,然后对引用计数进行折半,一半存储在isa中extra_rc位区,另一半存储在对应的sidetable中,可以通过对象的地址查找到存储的sidetable实例.
  • ​struct SideTable {
        spinlock_t slock; //保障操作安全的锁
        RefcountMap refcnts;//保存对应的引用计数:当isa中extra_rc不足以保存时,使用散列表保存refcnts.find(obj)
        weak_table_t weak_table;//保存weak_table_t
    
        //默认构造函数
        SideTable() {
            memset(&weak_table, 0, sizeof(weak_table));
        }
        
        //析构函数
        ~SideTable() {
            _objc_fatal("Do not delete SideTable.");
        }
    
        void lock() { slock.lock(); }
        void unlock() { slock.unlock(); }
        void forceReset() { slock.forceReset(); }
    
        // Address-ordered lock discipline for a pair of side tables.
    
        template<HaveOld, HaveNew>
        static void lockTwo(SideTable *lock1, SideTable *lock2);
        template<HaveOld, HaveNew>
        static void unlockTwo(SideTable *lock1, SideTable *lock2);
    };
    
  • struct weak_table_t:全局的弱引用表,所有的弱引用都在该表中进行存储,使用不定类型对象的地址作为 key,用 weak_entry_t 类型结构体对象作为 value 
  • /**
     * The global weak references table. Stores object ids as keys,
     * and weak_entry_t structs as their values.
     */
    struct weak_table_t {
        weak_entry_t *weak_entries; //保存了所有指向指定对象的weak指针
        size_t    num_entries; // weak对象的存储空间大小
        uintptr_t mask;参与判断引用计数辅助量
        uintptr_t max_hash_displacement;//hash key 最大偏移值:hash冲撞时最大尝试次数,用于优化搜索算法
    };
    
  • struct weak_entry_t:用来存储具体某一对象的所有弱引用指针
    • 当对象的弱引用指针小于4个时,使用静态数组inline_referrers进行保存,同时out_of_line_ness = 0;
    • 当对象弱引用指针大于4个时,使用二维数组referrers保存,out_of_line_ness = 2;
  • struct weak_entry_t {
        DisguisedPtr<objc_object> referent;
        union {
            //当弱引用指针个数大于WEAK_INLINE_COUNT时,使用二维指针进行存储
            struct {
                weak_referrer_t *referrers;
                uintptr_t        out_of_line_ness : 2;
                uintptr_t        num_refs : PTR_MINUS_2;
                uintptr_t        mask;
                uintptr_t        max_hash_displacement;
            };
    
            //当弱引用指针个数小于WEAK_INLINE_COUNT时,使用一位数组进行存储
            struct {
                // out_of_line_ness field is low bits of inline_referrers[1]
                weak_referrer_t  inline_referrers[WEAK_INLINE_COUNT];
            };
        };
        //判断当前是否是离线存储
        bool out_of_line() {
            return (out_of_line_ness == REFERRERS_OUT_OF_LINE);
        }
        //重载运算符=
        weak_entry_t& operator=(const weak_entry_t& other) {
            memcpy(this, &other, sizeof(other));
            return *this;
        }
        //第一个弱引用指针使用该方法存储
        weak_entry_t(objc_object *newReferent, objc_object **newReferrer)
            : referent(newReferent)
        {
            inline_referrers[0] = newReferrer;
            for (int i = 1; i < WEAK_INLINE_COUNT; i++) {
                inline_referrers[i] = nil;
            }
        }
    };

 

实现原理

在NSObject.mm(line 406-426)中找到了相关实现.

  • objc_initWeak:runtime会调用objc_initWeak函数,初始化一个新的weak指针指向对象的地址;
  • 
    objc_initWeak(id *location, id newObj)
    {
        //判断原始引用对象是否为空;
        if (!newObj) {
            *location = nil;
            return nil;
        }
        // 这里传递了三个 bool 数值
        // 使用 template 进行常量参数传递是为了优化性能,预判了大概率会发生的事情处理优先
        return storeWeak<DontHaveOld, DoHaveNew, DoCrashIfDeallocating>
            (location, (objc_object*)newObj);
    }
  • storeWeak函数:objc_initWeak函数会调用 objc_storeWeak() 函数, objc_storeWeak() 的作用是更新指针指向,创建对应的弱引用表。
  • static id 
    storeWeak(id *location, objc_object *newObj)
    {
           //断言在模板参数中新值和旧值至少有一个是存在:这个参数只是表明我觉得很大可能是有(新值/旧值)或者没有(新值/旧值),实际上有或者没有还是要做具体判断
           assert(haveOld  ||  haveNew);
           if (!haveNew) assert(newObj == nil);
           //在类没有完成+initialized方法之前调用weakStore时,作为初始化的标识
           Class previouslyInitializedClass = nil;
           id oldObj;
           SideTable *oldTable;
           SideTable *newTable;
    
           // Acquire locks for old and new values.
           // Order by lock address to prevent lock ordering problems.
           // Retry if the old value changes underneath us.
        //定义代码块,供关键字goto使用
        retry:
           if (haveOld) {
               //获取弱引用指针的旧指向
               oldObj = *location;
                //获取oldObj对应的弱引用表
               oldTable = &SideTables()[oldObj];
           } else {
               oldTable = nil;
           }
           if (haveNew) {
            //获取newObj对应的弱引用表
               newTable = &SideTables()[newObj];
           } else {
               newTable = nil;
           }
    
    
        SideTable::lockTwo<haveOld, haveNew>(oldTable, newTable);
    
        //location存在弱引用指向
        if (haveOld  &&  *location != oldObj) {
            SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
            goto retry;
        }
    
        // Prevent a deadlock between the weak reference machinery
        // and the +initialize machinery by ensuring that no 
        // weakly-referenced object has an un-+initialized isa.
        //主要防止在自定义的+initialize方法未完成时,调用storeWeak方法形成死锁(例如在+initialize添加弱引用)
        if (haveNew  &&  newObj) {
            Class cls = newObj->getIsa();
            if (cls != previouslyInitializedClass  &&  
                !((objc_class *)cls)->isInitialized()) 
            {
                SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
                class_initialize(cls, (id)newObj);
    
                // If this class is finished with +initialize then we're good.
                // If this class is still running +initialize on this thread 
                // (i.e. +initialize called storeWeak on an instance of itself)
                // then we may proceed but it will appear initializing and 
                // not yet initialized to the check above.
                // Instead set previouslyInitializedClass to recognize it on retry.
                previouslyInitializedClass = cls;
    
                goto retry;
            }
        }
    
        // Clean up old value, if any.
        //如果旧值存在就清理旧值
        if (haveOld) {
            weak_unregister_no_lock(&oldTable->weak_table, oldObj, location);
        }
    
        // Assign new value, if any.
        //绑定新值
        if (haveNew) {
            newObj = (objc_object *)
                weak_register_no_lock(&newTable->weak_table, (id)newObj, location, 
                                      crashIfDeallocating);
            // weak_register_no_lock returns nil if weak store should be rejected
    
            // Set is-weakly-referenced bit in refcount table.
            if (newObj  &&  !newObj->isTaggedPointer()) {
                newObj->setWeaklyReferenced_nolock();
            }
    
            // Do not set *location anywhere else. That would introduce a race.
            *location = (id)newObj;
        }
        else {
            // No new value. The storage is not changed.
        }
        
        SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
    
        return (id)newObj;
    }

绑定存储

  • weak_register_no_lock:向指定的弱引用表weak_table中添加新的弱应用指针.
    • 如果被引用对象referent为空或者referent是标签指针则直接返回referent_id;
    • 判断当前对象是否正在释放.如果当前对象正在释放,当crashIfDeallocating=true,则抛出异常;当crashIfDeallocating=false时直接返回nil。通过这个函数,还可以得到一个意外的知识点:在自定义的dealloc实现中,不允许增加新的弱引用指针,否则会报错.通过这个函数可以知道在自定义的dealloc实现中,不允许增加新的弱引用指针,否则会报错.
    • 判断当前的弱引用表中是否存在referent对应的weak_entry_t:如果存在则直接进行append_referrer,否则需要创建新的weak_entry_t实例并添加到当前的弱应用表中.
  • id 
    weak_register_no_lock(weak_table_t *weak_table, id referent_id, 
                          id *referrer_id, bool crashIfDeallocating)
    {
        //获取被引用对象
        objc_object *referent = (objc_object *)referent_id;
        //强转referrer_id为二级指针
        objc_object **referrer = (objc_object **)referrer_id;
    
        //如果被引用对象不存在或者被引用对象为TaggedPointer(标签指针),直接返回被引用对象的指针
        if (!referent  ||  referent->isTaggedPointer()) return referent_id;
    
        // ensure that the referenced object is viable
        bool deallocating;
        
        /*
         查看是否有自定义的RR函数,RR函数包括:
         retain
         release
         autorelease
         retainCount
         tryRetain
         SEL_retainWeakReference
         isDeallocating
         allowsWeakReference);
         */
        if (!referent->ISA()->hasCustomRR()) {
    
            deallocating = referent->rootIsDeallocating();
        }
        else {
            BOOL (*allowsWeakReference)(objc_object *, SEL) = 
                (BOOL(*)(objc_object *, SEL))
                object_getMethodImplementation((id)referent, 
                                               SEL_allowsWeakReference);
            if ((IMP)allowsWeakReference == _objc_msgForward) {
                return nil;
            }
            deallocating =
                ! (*allowsWeakReference)(referent, SEL_allowsWeakReference);
        }
    
        if (deallocating) {
            //如果对象正在释放,不能增加新的弱引用指针
            if (crashIfDeallocating) {
                _objc_fatal("Cannot form weak reference to instance (%p) of "
                            "class %s. It is possible that this object was "
                            "over-released, or is in the process of deallocation.",
                            (void*)referent, object_getClassName((id)referent));
            } else {
                return nil;
            }
        }
    
        // now remember it and where it is being stored
        weak_entry_t *entry;
        if ((entry = weak_entry_for_referent(weak_table, referent))) {
            //在weak_table找到referent对应的weak_entry_t
            append_referrer(entry, referrer); //在entry中添加新的弱引用指针referrer
        } 
        else {
            //在weak_table中未找到referent对应的weak_entry_t
            weak_entry_t new_entry(referent, referrer); //初始化新的weak_entry_t
            weak_grow_maybe(weak_table); //查看是否需要重新开辟weak_table空间
            weak_entry_insert(weak_table, &new_entry); //在weak_table中插入new_entry
        }
    
        // Do not set *referrer. objc_storeWeak() requires that the 
        // value not change.
    
        return referent_id;
    }
  • weak_grow_maybe:尝试增加弱引用表的容量.
    • 若weaktable当前的使用量不小于总量的3/4,则进行扩容;否则不做任何处理.同时也可以看出弱引用表中容量的初始化值为64.
  • static void weak_grow_maybe(weak_table_t *weak_table)
    {
        size_t old_size = TABLE_SIZE(weak_table);
    
        // Grow if at least 3/4 full.
        if (weak_table->num_entries >= old_size * 3 / 4) {
            //扩容之后开辟新的空间并复制
            weak_resize(weak_table, old_size ? old_size*2 : 64);
        }
    }
    

     

  • weak_entry_insert:向弱引用表中插入新的entry.
    • 使用hash_pointer(new_entry->referent) & (weak_table->mask)获取起始索引;
    • 循环查找weak_entries中为空的位置;
    • 在index位置保存new_entry并num_entries进行自增;
    • 保存哈希碰撞最大的尝试次数,在查找时可以减少搜索次数.
  • static void weak_entry_insert(weak_table_t *weak_table, weak_entry_t *new_entry)
    {
        weak_entry_t *weak_entries = weak_table->weak_entries;
        assert(weak_entries != nil);
    
        //使用hash_pointer对new_entry->referent进行哈希运算并对容量取与
        size_t begin = hash_pointer(new_entry->referent) & (weak_table->mask);
        size_t index = begin;
        size_t hash_displacement = 0;
        while (weak_entries[index].referent != nil) {
            index = (index+1) & weak_table->mask;
            if (index == begin) bad_weak_table(weak_entries);
            //hash碰撞hash_displacement自增
            hash_displacement++;
        }
        //获取到哈希索引保存new_entry
        weak_entries[index] = *new_entry;
        //weak_table->num_entries自增
        weak_table->num_entries++;
    
        if (hash_displacement > weak_table->max_hash_displacement) {
            //保存哈希碰撞最大尝试次数,由于优化搜索算法减少搜索次数
            weak_table->max_hash_displacement = hash_displacement;
        }
    }
    

     

  • append_referrer: 在weak_entry_t中添加新的弱引用指针.
    • 当前没有使用离线存储,遍历内部静态数组inline_referrers,有空余的位置则直接保存new_referrer;否则开辟新的空间指针new_referrers,并将原始静态数组的元素复制到新开辟空间中的对应位置,然后重置entry相关属性(此时entry->num_refs=WEAK_INLINE_COUNT是大于TABLE_SIZE(entry) * 3/4).
    • 判断离线存储的实际使用量(num_refs)是否大于空间总量的(TABLESIZE(entry)),如果为真则需要扩容并添加新的弱引用指针,直接返回grow_refs_and_insert;否则正常存储.
  • static void append_referrer(weak_entry_t *entry, objc_object **new_referrer)
    {
        //在增加新的弱引用指针之前使用非离线存储弱引用指针:使用静态数组inline_referrers来进行存储
        if (! entry->out_of_line()) {
            //遍历inline_referrers查看是否存在空的位置
            for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) {
                if (entry->inline_referrers[i] == nil) {
                    //存在则直接将新的弱引用指针存储在该位置,并返回
                    entry->inline_referrers[i] = new_referrer;
                    return;
                }
            }
    
            // 在静态数组中没有可用的存储位置,需要开辟离线空间
            weak_referrer_t *new_referrers = (weak_referrer_t *)
                calloc(WEAK_INLINE_COUNT, sizeof(weak_referrer_t));
            //将之前使用静态数组进行存储的元素复制到新的new_referrers中,虽然目前来讲这部分操作并没开辟足够的空间存储新的new_referrer,但是不用紧张会在grow_refs_and_inser进行修复并对元素进行哈希
            for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) {
                new_referrers[i] = entry->inline_referrers[i];
            }
            entry->referrers = new_referrers;
            entry->num_refs = WEAK_INLINE_COUNT;
            entry->out_of_line_ness = REFERRERS_OUT_OF_LINE;
            entry->mask = WEAK_INLINE_COUNT-1;//entry->mask永远是最大容量-1
            entry->max_hash_displacement = 0; //重置max_hash_displacement
        }
        //断言:代码执行到这个位置时entry应该是离线存储,即:entry->out_of_line() = true
        assert(entry->out_of_line());
    
        //如果当前已经使用了总量的3/4,则l扩容并添加新的引用,并返回
        if (entry->num_refs >= TABLE_SIZE(entry) * 3/4) {
            return grow_refs_and_insert(entry, new_referrer);
        }
        //如果当前已经使用量小于总量的3/4,则直接添加 
        size_t begin = w_hash_pointer(new_referrer) & (entry->mask); //hash new_referrer并与entry->mask作&运算得到起始索引
        size_t index = begin;
        size_t hash_displacement = 0;
        //发生hash碰撞
        while (entry->referrers[index] != nil) {
            hash_displacement++;
            index = (index+1) & entry->mask;
            if (index == begin) bad_weak_table(entry);
        }
        //更新存储时最大的hash碰撞次数,由于优化取值时算法减少搜索次数
        if (hash_displacement > entry->max_hash_displacement) {
            entry->max_hash_displacement = hash_displacement;
        }
        weak_referrer_t &ref = entry->referrers[index];
        ref = new_referrer;
        entry->num_refs++;
    }
  • grow_refs_and_insert:扩容并增加新的弱引用指针,最终的存储还是依靠append_referrer完成.
    • 如果当前entry容量为0则初始化new_size=8;否则置new_size=2*old_size;
    • 开辟新的空间指针赋值给entry->referrers并重置entry相关属性;
    • 插入新的弱引用指针.
  • __attribute__((noinline, used))
    static void grow_refs_and_insert(weak_entry_t *entry, 
                                     objc_object **new_referrer)
    {
        assert(entry->out_of_line());
        //获取当前的entry容量
        size_t old_size = TABLE_SIZE(entry);
        //如果当前容量为0则置new_size = 8;否则new_size=2*old_size;
        size_t new_size = old_size ? old_size * 2 : 8;
    
        size_t num_refs = entry->num_refs;
        weak_referrer_t *old_refs = entry->referrers;
        //重置entry->mask
        entry->mask = new_size - 1;
        //开辟新的空间指针进行扩容
        entry->referrers = (weak_referrer_t *)
            calloc(TABLE_SIZE(entry), sizeof(weak_referrer_t));
        entry->num_refs = 0;
        entry->max_hash_displacement = 0;
        
        for (size_t i = 0; i < old_size && num_refs > 0; i++) {
            if (old_refs[i] != nil) {
                append_referrer(entry, old_refs[i]);
                num_refs--;
            }
        }
        // Insert
        append_referrer(entry, new_referrer);
        //释放旧指针空间
        if (old_refs) free(old_refs);
    }
    
  • setWeaklyReferenced_nolock:保存对象的弱引用标记
    • 判断是否支持nonpointer,若不支持则直接在sidetable中保存弱引用标记;否则继续执行.
    • 若支持nonpointer且已经被标记为存在弱引用指针,则直接返回;否则继续执行.
    • 在isa中保存弱引用标记;
    • 进行newisa保存.

 

inline void
objc_object::setWeaklyReferenced_nolock()
{
 retry:
    isa_t oldisa = LoadExclusive(&isa.bits);
    isa_t newisa = oldisa;
    //若当前对象不支持nonpointer
    if (slowpath(!newisa.nonpointer)) {
        ClearExclusive(&isa.bits);
        //在弱引用表中存储弱引用标志
        sidetable_setWeaklyReferenced_nolock();
        return;
    }
    //当前对象支持nonpointer且已经被标识为弱引用
    if (newisa.weakly_referenced) {
        ClearExclusive(&isa.bits);
        return;
    }
    //当前对象支持nonpointer,则添加弱引用标记
    newisa.weakly_referenced = true;
    //保存弱引用标记
    if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;
}

解除存储

  • weak_unregister_no_lock:移除指定的弱引用指针
    • 在weak_table中查找对应的entry;
    • 从entry中移除referrer,并判断移除之后entry是否为空;
    • 若移除之后当前entry为空,则从weak_table中移除entry.
void
weak_unregister_no_lock(weak_table_t *weak_table, id referent_id, 
                        id *referrer_id)
{
    //获取被引用对象
    objc_object *referent = (objc_object *)referent_id;
    //强转referrer_id为二级指针
    objc_object **referrer = (objc_object **)referrer_id;

    weak_entry_t *entry;

    if (!referent) return;
    //获取weak_table_t中的weak_entry_t *weak_entries;
    if ((entry = weak_entry_for_referent(weak_table, referent))) {
        //如果弱引用指针存在,则从entry移除referrer
        remove_referrer(entry, referrer);
        bool empty = true;//判断移除referrer之后entry是否为空
        if (entry->out_of_line()  &&  entry->num_refs != 0) {
            empty = false;
        }
        else {
            for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) {
                if (entry->inline_referrers[i]) {
                    empty = false; 
                    break;
                }
            }
        }
        //如果移除referrer之后entry为空则从表中移除entry
        if (empty) {
            weak_entry_remove(weak_table, entry);
        }
    }

    // Do not set *referrer = nil. objc_storeWeak() requires that the 
    // value not change.
}
  • remove_referrer: 从当前weak_entry_t实例中移除弱引用指针.
    • 判断是否是弱引用是否是离线存储:如果使用飞离线存储,则遍历inline_referrers查找old_referrer,查找到则置空,否则只需执行;
    • 使用离线存储机制:使用 w_hash_pointer(old_referrer) & (entry->mask)获取起始索引,遍历entry->referrers,找到之后置空,并entry->num_refs自减.
static void remove_referrer(weak_entry_t *entry, objc_object **old_referrer)
{
    
    //如果entry没有使用离线机制存储:对象弱引用个数不大于WEAK_INLINE_COUNT
    if (! entry->out_of_line()) {
        for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) {
            if (entry->inline_referrers[i] == old_referrer) {
                //置空对应的弱引用指针
                entry->inline_referrers[i] = nil;
                return;
            }
        }
        _objc_inform("Attempted to unregister unknown __weak variable "
                     "at %p. This is probably incorrect use of "
                     "objc_storeWeak() and objc_loadWeak(). "
                     "Break on objc_weak_error to debug.\n", 
                     old_referrer);
        objc_weak_error();
        return;
    }
    //如果entry使用离线机制存储:对象弱引用个数大于WEAK_INLINE_COUNT
    size_t begin = w_hash_pointer(old_referrer) & (entry->mask);
    size_t index = begin;
    size_t hash_displacement = 0;
    while (entry->referrers[index] != old_referrer) {
        index = (index+1) & entry->mask;
        if (index == begin) bad_weak_table(entry);
        //搜索次数+1
        hash_displacement++;
        if (hash_displacement > entry->max_hash_displacement) {
            _objc_inform("Attempted to unregister unknown __weak variable "
                         "at %p. This is probably incorrect use of "
                         "objc_storeWeak() and objc_loadWeak(). "
                         "Break on objc_weak_error to debug.\n", 
                         old_referrer);
            objc_weak_error();
            return;
        }
    }
    //将index对应的referrer置空
    entry->referrers[index] = nil;
    //弱引用计数-1
    entry->num_refs--;
}

对象释放

使用weak一个最重要的特性就是在对象释放时,指向对象的所有弱引用都会被自动置为nil,从而可以有效滴防止非法访问造成的也指针问题.当一个对象的引用计数为零时,对象会进行释放销毁,调用过程大概这个样子:

  • 在对象释放时会调用dealloc方法,而dealloc会调用_objc_rootDealloc方法:
// Replaced by NSZombies
- (void)dealloc {
    _objc_rootDealloc(self);
}

  • _objc_rootDealloc调用objc->rootDealloc:
inline void
objc_object::rootDealloc()
{
    if (isTaggedPointer()) return;  // fixme necessary?

    if (fastpath(isa.nonpointer  &&  
                 !isa.weakly_referenced  &&  
                 !isa.has_assoc  &&  
                 !isa.has_cxx_dtor  &&  
                 !isa.has_sidetable_rc))
    {
        assert(!sidetable_present());
        free(this);
    } 
    else {
        object_dispose((id)this);
    }
}
  • objc->rootDealloc调用objc_dispose:
/***********************************************************************
* object_dispose
* fixme
* Locking: none
**********************************************************************/
id 
object_dispose(id obj)
{
    if (!obj) return nil;

    objc_destructInstance(obj);    
    free(obj);

    return nil;
}
  • objc-dispose调用objc_destructInstance:
/***********************************************************************
* objc_destructInstance
* Destroys an instance without freeing memory. 
* Calls C++ destructors.
* Calls ARC ivar cleanup.
* Removes associative references.
* Returns `obj`. Does nothing if `obj` is nil.
**********************************************************************/
void *objc_destructInstance(id obj) 
{
    if (obj) {
        // Read all of the flags at once for performance.
        bool cxx = obj->hasCxxDtor();
        bool assoc = obj->hasAssociatedObjects();

        // This order is important.
        if (cxx) object_cxxDestruct(obj);
        if (assoc) _object_remove_assocations(obj);
        obj->clearDeallocating();
    }

    return obj;
}

  • objc_desctructInstance调用objc->clearDeallocating:

inline void 
objc_object::clearDeallocating()
{
    //若果不支持nonpointer技术,则直接释放
    if (slowpath(!isa.nonpointer)) {
        // Slow path for raw pointer isa.
        sidetable_clearDeallocating();
    }
    else if (slowpath(isa.weakly_referenced  ||  isa.has_sidetable_rc)) {
    //支持nonpointer&有弱引用指针&(弱引用指针 || 引用计数存储在弱引用表中)
        // Slow path for non-pointer isa with weak refs and/or side table data.
        clearDeallocating_slow();
    }

    assert(!sidetable_present());
}
  • 如果当前对象不支持nonpointer则执行sidetable_clearDeallocating;否则当前对象存在弱引用指针或者引用计数存在弱引用表中,则执行clearDeallocating_slow.
    • sidetable_clearDeallocating:当前对象不支持nonpointer时,清除sidetable中的弱引用指针以及引用计数:此时是否存在弱引用指针的标志存储在RefcountMap::iterator中的成员变量second中.
  • void 
    objc_object::sidetable_clearDeallocating()
    {
        SideTable& table = SideTables()[this];
    
        // clear any weak table items
        // clear extra retain count and deallocating bit
        // (fixme warn or abort if extra retain count == 0 ?)
        //添加线程锁
        table.lock();
        RefcountMap::iterator it = table.refcnts.find(this);
        if (it != table.refcnts.end()) {
            //清除弱引用表
            if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) {
                weak_clear_no_lock(&table.weak_table, (id)this);
            }
            //清除引用计数
            table.refcnts.erase(it);
        }
        table.unlock();
    }
    • clearDeallocating_slow:当前对象支持nonpointer时,清除弱引用指针以及引用计数:此时是否存在弱引用的标志存储在isa的weakly_referenced位域中.
  • NEVER_INLINE void
    objc_object::clearDeallocating_slow()
    {
        assert(isa.nonpointer  &&  (isa.weakly_referenced || isa.has_sidetable_rc));
    
        SideTable& table = SideTables()[this];
        table.lock();
        if (isa.weakly_referenced) {
            //清除弱引用表
            weak_clear_no_lock(&table.weak_table, (id)this);
        }
        if (isa.has_sidetable_rc) {
            //清除引用计数
            table.refcnts.erase(this);
        }
        table.unlock();
    }
    
  • weak_clear_no_lock:清理指向referent的弱引用指针.
/** 
 * Called by dealloc; nils out all weak pointers that point to the 
 * provided object so that they can no longer be used.
 * 
 * @param weak_table 
 * @param referent The object being deallocated. 
 */
void 
weak_clear_no_lock(weak_table_t *weak_table, id referent_id) 
{
    objc_object *referent = (objc_object *)referent_id;

    weak_entry_t *entry = weak_entry_for_referent(weak_table, referent);
    //若entry为空则证明当前对象不存在弱引用指针.
    if (entry == nil) {
        /// XXX shouldn't happen, but does with mismatched CF/objc
        //printf("XXX no entry for clear deallocating %p\n", referent);
        return;
    }

    // zero out references
    weak_referrer_t *referrers;
    size_t count;
    
    
    if (entry->out_of_line()) {
        //使用离线存储弱引用指针
        referrers = entry->referrers;
        count = TABLE_SIZE(entry);
    } 
    else {
        //使用内部静态数组存储弱引用指针
        referrers = entry->inline_referrers;
        count = WEAK_INLINE_COUNT;
    }
    //遍历弱引用数组逐个置空指向referent的弱引用指针
    for (size_t i = 0; i < count; ++i) {
        objc_object **referrer = referrers[i];
        if (referrer) {
            //当前弱指针指向对象referent
            if (*referrer == referent) {
                //置空弱引用指针
                *referrer = nil;
            }
            else if (*referrer) {
                _objc_inform("__weak variable at %p holds %p instead of %p. "
                             "This is probably incorrect use of "
                             "objc_storeWeak() and objc_loadWeak(). "
                             "Break on objc_weak_error to debug.\n", 
                             referrer, (void*)*referrer, (void*)referent);
                objc_weak_error();
            }
        }
    }
    
    //从weak_table中移除entry
    weak_entry_remove(weak_table, entry);
}

 

总结

  • entry存储使用了hash_pointer,referrer存储使用了w_hash_pointer,其实两个函数的实现是一样的.

static inline uintptr_t hash_pointer(objc_object *key) {
    return ptr_hash((uintptr_t)key);
}

static inline uintptr_t w_hash_pointer(objc_object **key) {
    return ptr_hash((uintptr_t)key);
}
  • 全局的SideTables()方法获取的其实是一个StripedMap<SideTable>*类型的对象,该对象内部创建了一个最大容量为StripeCount(在iOS真机中StripeCount=8;iOS模拟器中StripeCount=64)的静态数组,所有的对象都通过indexForPointer函数映射到[0,StripeCount)的索引位置进行存储;
  • weak_table_t中weak_entries数量的初始化数量mask是64
static void weak_grow_maybe(weak_table_t *weak_table)
{
    size_t old_size = TABLE_SIZE(weak_table);

    // Grow if at least 3/4 full.
    if (weak_table->num_entries >= old_size * 3 / 4) {
        weak_resize(weak_table, old_size ? old_size*2 : 64);
    }
}
  • weak_entry_t中referrers的初始化数量mask是8
__attribute__((noinline, used))
static void grow_refs_and_insert(weak_entry_t *entry, 
                                 objc_object **new_referrer)
{
    assert(entry->out_of_line());

    size_t old_size = TABLE_SIZE(entry);
    size_t new_size = old_size ? old_size * 2 : 8;

    size_t num_refs = entry->num_refs;
    weak_referrer_t *old_refs = entry->referrers;
    entry->mask = new_size - 1;
    ...
}
  • weak_table_t和weak_entry_t都是在使用量超过总量3/4时开始扩容
//weak_table_t扩容
static void weak_grow_maybe(weak_table_t *weak_table)
{
    size_t old_size = TABLE_SIZE(weak_table);

    // Grow if at least 3/4 full.
    if (weak_table->num_entries >= old_size * 3 / 4) {
        weak_resize(weak_table, old_size ? old_size*2 : 64);
    }
}




//weak_entry_t进行扩容
static void append_referrer(weak_entry_t *entry, objc_object **new_referrer)
{
    ...
    //如果当前已经使用了总量的3/4,则扩容并添加新的引用,并返回
    if (entry->num_refs >= TABLE_SIZE(entry) * 3/4) {
        return grow_refs_and_insert(entry, new_referrer);
    }
    ...
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值