iOS底層-3:源碼探索:alloc & init & new 源碼分析

前一篇文章介紹了objc4 779.1的調試環(huán)境搭建,這里以alloc、initnew方法為例看一下詳細的執(zhí)行過程。

alloc流程圖
  • LYPerson alloc 流程

    1.png

  • NSObject alloc 流程

    2.png

上圖是一步步斷點調試而來,調試方法請參考源碼探索方法。我們簡單分析一下,不管是NSObjec還是LYPerson,alloc都不是首先調用的方法,甚至NSObjecalloc都沒有調用。

為什么首先調用的是objc_alloc方法?查找llvm源碼得知,在編譯時進行了優(yōu)化。當shouldUseRuntimeFunctionsForAlloc返回true時,對alloc進行優(yōu)化。

image.png

  • 搜索shouldUseRuntimeFunctionsForAlloc
    image.png
  • 搜索EmitObjCAlloc(
    image.png

    可以看到這兩個方法把alloc就轉換成了objc_alloc
1、objc_alloc
objc_alloc(Class cls)
{
    return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
}

直接調用callAlloc方法。

2、callAlloc
static ALWAYS_INLINE id callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__
    if (slowpath(checkNil && !cls)) return nil;
    if (fastpath(!cls->ISA()->hasCustomAWZ())) {
        return _objc_rootAllocWithZone(cls, nil);
    }
#endif

    // No shortcuts available.
    if (allocWithZone) {//傳入參數為false
        return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
    }
    return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}

探索發(fā)現(xiàn)LYPerson走到最后一步,調用alloc方法;NSObjec調用的是_objc_rootAllocWithZone。hasCustomAWZ()判斷當前類是否有默認的allocWithZone方法

bool hasCustomAWZ() const {
        return !cache.getBit(FAST_CACHE_HAS_DEFAULT_AWZ);
}
 bool getBit(uint16_t flags) const {
        return _flags & flags;
}

#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))

簡述一下fastpath(x)slowpath(x),這兩個方法的返回值是一樣的。x 值為正返回為真,反之返回為假。引入這兩個宏目的是增加條件分支預測的準確性,cpu 會提前裝載后面的指令,遇到條件轉移指令時會提前預測并裝載某個分支的指令。slowpath 表示你可以確認該條件是極少發(fā)生的,相反 fastpath 表示該條件多數情況下會發(fā)生。編譯器會產生相應的代碼來優(yōu)化 cpu 執(zhí)行效率。

參考:
gcc 編譯器 , __builtin_expect() 研究
iOS性能優(yōu)化系列之__builtin_expect分支預測優(yōu)化

3、alloc
+ (id)alloc {
    return _objc_rootAlloc(self);
}
4、_objc_rootAlloc
id _objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

直接調用callAlloc,但是這次callAlloc中調用的是_objc_rootAllocWithZone

5、 _objc_rootAllocWithZone
id _objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
{
    // allocWithZone under __OBJC2__ ignores the zone parameter
    return _class_createInstanceFromZone(cls, 0, nil,
                                         OBJECT_CONSTRUCT_CALL_BADALLOC);
}

直接調用_class_createInstanceFromZone。

6、_class_createInstanceFromZone
static ALWAYS_INLINE id 
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
                              int construct_flags = OBJECT_CONSTRUCT_NONE,
                              bool cxxConstruct = true,
                              size_t *outAllocatedSize = nil)
{
    ASSERT(cls->isRealized());

    // Read class's info bits all at once for performance
    bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
    bool hasCxxDtor = cls->hasCxxDtor();
    bool fast = cls->canAllocNonpointer();
    size_t size;

    size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (zone) {
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }

    if (!zone && fast) {
        obj->initInstanceIsa(cls, hasCxxDtor);
    } else {
        // Use raw pointer isa on the assumption that they might be
        // doing something weird with the zone or RR.
        obj->initIsa(cls);
    }

    if (fastpath(!hasCxxCtor)) {
        return obj;
    }

    construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;
    return object_cxxConstructFromClass(obj, cls, construct_flags);
}

大致分為以下幾個步驟:

  • instanceSize計算出類的所需內存
  • calloc開辟內存
  • initInstanceIsa關聯(lián)Isa指針

1.instanceSize

#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
/*
*字節(jié)對齊
*LP64機器下8字節(jié)對齊
*其他4字節(jié)對齊
*/
static inline uint32_t word_align(uint32_t x) {
    return (x + WORD_MASK) & ~WORD_MASK;
}
/*
*實例大小
*實例大小instanceSize會存在ro中
*/
uint32_t unalignedInstanceSize() const {
    ASSERT(isRealized());
    return data()->ro->instanceSize;
}
/*
*返回字節(jié)對齊后的內存大小
*/
uint32_t alignedInstanceSize() const {
    return word_align(unalignedInstanceSize());
}
size_t instanceSize(size_t extraBytes) const {
    if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
            return cache.fastInstanceSize(extraBytes);
    }
    size_t size = alignedInstanceSize() + extraBytes;
    // CF requires all objects be at least 16 bytes.
    if (size < 16) size = 16;//當內存小于16字節(jié)時,返回16字節(jié)
    return size;
}

然而現(xiàn)在objc源碼普遍走的是fastInstanceSize函數,快速計算內存大小。而當前版本內存對齊是16字節(jié)對齊,蘋果早期是8字節(jié)對齊。

static inline size_t align16(size_t x) {
    return (x + size_t(15)) & ~size_t(15);
}

size_t fastInstanceSize(size_t extra) const
    {
        ASSERT(hasFastInstanceSize(extra));

        if (__builtin_constant_p(extra) && extra == 0) {
            return _flags & FAST_CACHE_ALLOC_MASK16;
        } else {
            size_t size = _flags & FAST_CACHE_ALLOC_MASK;
            // remove the FAST_CACHE_ALLOC_DELTA16 that was added
            // by setFastInstanceSize
            return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
        }
    }

獲取內存大小后,直接調用calloc函數為對象分配內存空間

  1. calloc

The calloc( ) function contiguously allocates enough space for count objects that are size bytes of memory each and returns a pointer to the allocated memory. The allocated memory is filled with bytes of value zero. // calloc()函數連續(xù)地為count對象分配足夠的空間,這些對象是內存的大小字節(jié),并返回一個指向所分配內存的指針。分配的內存充滿了值為零的字節(jié)。

申請完內存,還需要初始化Isa指針。

  1. initIsa
inline void objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
    ASSERT(!cls->instancesRequireRawIsa());
    ASSERT(hasCxxDtor == cls->hasCxxDtor());

    initIsa(cls, true, hasCxxDtor);
}

inline void objc_object::initIsa(Class cls)
{
    initIsa(cls, false, false);
}

initIsainitInstanceIsa最后調用的都是initIsa方法,就是參數不同而已

inline void 
objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor) 
{ 
    ASSERT(!isTaggedPointer()); 
    
    if (!nonpointer) {
        isa = isa_t((uintptr_t)cls);
    } else {
        ASSERT(!DisableNonpointerIsa);
        ASSERT(!cls->instancesRequireRawIsa());

        isa_t newisa(0);

#if SUPPORT_INDEXED_ISA
        ASSERT(cls->classArrayIndex() > 0);
        newisa.bits = ISA_INDEX_MAGIC_VALUE;
        // isa.magic is part of ISA_MAGIC_VALUE
        // isa.nonpointer is part of ISA_MAGIC_VALUE
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.indexcls = (uintptr_t)cls->classArrayIndex();
#else
        newisa.bits = ISA_MAGIC_VALUE;
        // isa.magic is part of ISA_MAGIC_VALUE
        // isa.nonpointer is part of ISA_MAGIC_VALUE
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.shiftcls = (uintptr_t)cls >> 3;
#endif

        // This write must be performed in a single store in some cases
        // (for example when realizing a class because other threads
        // may simultaneously try to use the class).
        // fixme use atomics here to guarantee single-store and to
        // guarantee memory order w.r.t. the class index table
        // ...but not too atomic because we don't want to hurt instantiation
        isa = newisa;
    }
}

初始化的過程就是對isa_t結構體初始化的過程。
到此alloc流程就走完了,主要就是計算并分配內存,關聯(lián)Isa。

init分析
- (id)init {
    return _objc_rootInit(self);
}
id _objc_rootInit(id obj)
{
    // In practice, it will be hard to rely on this function.
    // Many classes do not properly chain -init calls.
    return obj;
}

init方法的僅僅就是返回了當前對象而已。

new分析
// Calls [cls new]
id objc_opt_new(Class cls)
{
#if __OBJC2__
    if (fastpath(cls && !cls->ISA()->hasCustomCore())) {
        return [callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/) init];
    }
#endif
    return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(new));
}
+ (id)new {
    return [callAlloc(self, false/*checkNil*/) init];
}

new類方法里同樣調用callAllocinit方法,相當于[[cls alloc] init].

最后我們來看一道面試題


image.png

結果打印如下:


image.png

你們答對了嗎?
對象的內存實際上是在alloc方法里面開辟的,故p1、p2、p3在內存中的地址一致,只是指針地址不同。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容