ios 内存管理(上)

作者: Jeffery_zc | 来源:发表于2022-01-05 17:09 被阅读0次

1.内存布局

内存布局.png
  • 内核区:假设在4GB的手机内存中,通常我们使用的只有3GB,而另外的1GB则交给内核区去处理;
  • 栈:通过寄存器直接读取内存(函数,方法),速度比堆快,但是内存比较小,一般以0x7开头;
  • 堆:通过alloc分配的对象,block copy等存储在堆;
  • 全局区:
    • BSS段: 未初始化的全局变量,静态变量,一般以0x1开头;
    • data段:初始化的全局变量,静态变量,一般以0x1开头;
  • 常量区:存放常量字符串;
  • text:程序代码,加载到内存中;
  • 保留区:保留一定的字段给保留区。

2. TarggedPointer

- (void)taggedPointerDemo1 {
  
    self.queue = dispatch_queue_create("com.jeffery.cn", DISPATCH_QUEUE_CONCURRENT);
    
    for (int i = 0; i<10000; i++) {
        dispatch_async(self.queue, ^{
            self.nameStr = [NSString stringWithFormat:@"jeffery"];  // alloc 堆 iOS优化 - taggedpointer
             NSLog(@"%@",self.nameStr);
        });
    }
}
- (void)taggedPointerDemo2 {
    
    for (int i = 0; i<10000; i++) {
        dispatch_async(self.queue, ^{
            self.nameStr = [NSString stringWithFormat:@"jeffery_学习使我快乐"];
            NSLog(@"%@",self.nameStr);
        });
    }
}

通过运行以上2个demo发现,第一个正常运行,第二个则是崩溃了。在对nameStr进行赋值(set)和读取(get)中,不断地会有对新值的retain和对旧值的release,在某一时间点,因为在前一线程还没有release完毕的时候后一线程进行retain,这样就release多次导致访问了野指针而程序崩溃。而在第一个程序运行为什么没有崩溃呢,这就要引出TarggedPointer了。
我们在赋值处打一个断点,可以发现两个程序的string类型不一样。在taggedPointerDemo1中,通过断点可以看到nameStrNSTarggedPointerString类型,而在taggedPointerDemo2NSCFString

  • 分析
  1. objc_release
void 
objc_release(id obj)
{
    if (!obj) return;
    if (obj->isTaggedPointer()) return;
    return obj->release();
}
  1. objc_retain
id 
objc_retain(id obj)
{
    if (!obj) return obj;
    if (obj->isTaggedPointer()) return obj;
    return obj->retain();
}

通过分析源码发现,在进行retainrelease操作时,都对TarggedPointer做了判断处理,所以我们接下来需要对TaggedPointer进行分析:

static inline void * _Nonnull
_objc_encodeTaggedPointer(uintptr_t ptr)
{
    return (void *)(objc_debug_taggedpointer_obfuscator ^ ptr);
}

static inline uintptr_t
_objc_decodeTaggedPointer(const void * _Nullable ptr)
{
    return (uintptr_t)ptr ^ objc_debug_taggedpointer_obfuscator;
}

static void
initializeTaggedPointerObfuscator(void)
{
    if (sdkIsOlderThan(10_14, 12_0, 12_0, 5_0, 3_0) ||
        // Set the obfuscator to zero for apps linked against older SDKs,
        // in case they're relying on the tagged pointer representation.
        DisableTaggedPointerObfuscation) {
        objc_debug_taggedpointer_obfuscator = 0;
    } else {
        // Pull random data into the variable, then shift away all non-payload bits.
        arc4random_buf(&objc_debug_taggedpointer_obfuscator,
                       sizeof(objc_debug_taggedpointer_obfuscator));
        objc_debug_taggedpointer_obfuscator &= ~_OBJC_TAG_MASK;
    }
}

通过源码发现,在ios10.14之前,objc_debug_taggedpointer_obfuscator直接赋值为0,而在之后则进行一次位运算处理,这也是ios底层的常规操作了。通过encode或者decode操作对当前传进来的对象与objc_debug_taggedpointer_obfuscator进行异或标识直接存储在内存中。

总结:

  • TaggedPointer是专门用来存储小的对象,例如NSNumberNSDate`;
  • TaggedPointer指针的值不是地址,而是真正的值。所以,实际上它也不再是一个对象,而是一个套着对象外壳的普通变量。所以,他的存储不再堆中,也不需要进行mallocfree
  • 在内存读取上有着3倍的效率,创建时比以前快106倍。

3. 引用计数

retain源码:

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;
        if (slowpath(!newisa.nonpointer)) {
            ClearExclusive(&isa.bits);
            if (rawISA()->isMetaClass()) return (id)this;
            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
        if (slowpath(tryRetain && newisa.deallocating)) {
            ClearExclusive(&isa.bits);
            if (!tryRetain && sideTableLocked) sidetable_unlock();
            return nil;
        }
        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.
            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;
}

当对象进行retain或者copy的时候,因为ARC的关系会使得自动引用计数进行+1,但是这个是如何进行操作的呢,我们可以从以上源码逐层分析。当对象进行retain时会调用rootRetain方法如上所示。首先是分别定义了一个新值与旧值,研究过ios类的小伙伴都知道,类的一些重要信息大都存储在isabit中,所以我们可以看到源码中取出了bit赋值给旧值,再将旧值赋值给新值。然后,我们对新值进行了是否为nonpointer的判断,通过isa探索可知,当为非nonpointer_isa时,表示纯isa指针,此时会调用sidetable_retain()

struct SideTable {
    spinlock_t slock;
    RefcountMap refcnts;
    weak_table_t weak_table;

    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);
};
id
objc_object::sidetable_retain()
{
#if SUPPORT_NONPOINTER_ISA
    ASSERT(!isa.nonpointer);
#endif
    SideTable& table = SideTables()[this];
    
    table.lock();
    size_t& refcntStorage = table.refcnts[this];
    if (! (refcntStorage & SIDE_TABLE_RC_PINNED)) {
        refcntStorage += SIDE_TABLE_RC_ONE;
    }
    table.unlock();

    return (id)this;
}

通过以上两份源码可以看到,在散列表里有spinlock_t,RefcountMap以及weak_table_t。在sidetable_retain()方法中,取出了当前散列表里的引用计数表进行refcntStorage += SIDE_TABLE_RC_ONE操作。 细心的你会发现,当你在全局搜索sideTable时出现更多的是sideTables,这说明在整个应用程序中,存在多个散列表。假设当前整个应该程序只有一个散列表,当我们进行引用计数操作或者弱引用时会不断的进行加锁以及解锁的操作,这样就大大降低了工作效率,所以苹果就为应用程序创建多个散列表,使得app运行更为流畅。

# if __arm64__
#   define RC_ONE   (1ULL<<45)
...
# elif __x86_64__
#   define RC_ONE   (1ULL<<56)
...

isa探索中我们已经可以知道nonpointer的结构。当为非nonpointer_isa时,newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry),直接进行add,carry表示extra_rc存储的引用计数是否占满。当占满时,会获取当前的散列表,将extra_rc里一半的引用计数分配到散列表里的引用计数表里.

总结

  • 当进行retain时,会先进行判断当前对象是否为taggedPointer,如果是,则直接返回不进行引用计数操作;
  • 当前对象如果不是taggedPointer,则会调用root_retain方法,在root_retain方法里会做进一步判断;
  • 如果当前对象是nonpointer,则会取出当前对应的散列表里的引用计数表进行位运算操作然后返回;
  • 如果当前对象不是nonpointer,则会在当前isaextra_rc里进行引用计数加1,当通过carry判断当前的extra_rc已经加满,则会从extra_rc里取出一半存到当前的引用计数表里,等下一次再进行引用计数+1时会依然加到extra_rc中。

4.dealloc

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

当对象进行释放的时候,会首先判断是否为TaggedPointer,如果不是,则判断当前对象是否是nonpointer_isa以及一些isa占位符,如果都不存在,则直接调用free函数进行释放,如果存在,则调用object_dispose函数进行下一步处理。

id 
object_dispose(id obj)
{
    if (!obj) return nil;

    objc_destructInstance(obj);    
    free(obj);

    return 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;
}
inline void 
objc_object::clearDeallocating()
{
    if (slowpath(!isa.nonpointer)) {
        // Slow path for raw pointer isa.
        sidetable_clearDeallocating();
    }
    else if (slowpath(isa.weakly_referenced  ||  isa.has_sidetable_rc)) {
        // Slow path for non-pointer isa with weak refs and/or side table data.
        clearDeallocating_slow();
    }

    assert(!sidetable_present());
}
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();
}

由源码可知,在进行释放前,对cxx做了析构处理,对关联对象做了删除,对弱引用表以及引用计数表做了clear以及erase清楚处理,最后得到一个干净的obj,再进行free释放。

总结

  • 根据当前对象的状态决定是否直接调用free()释放;
  • 是否存在C++的析构函数,移除这个对象的关联属性;
  • 将指向该对象的弱引用指针置为nil;
  • 从引用计数表中擦除对该对象的引用计数。

相关文章

网友评论

    本文标题:ios 内存管理(上)

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