iOS底层-3:源码探索:alloc & init & new 源码分析

前一篇文章介绍了objc4 779.1的调试环境搭建,这里以allocinitnew方法为例看一下详细的执行过程。

alloc流程图
  • LYPerson alloc 流程

    1.png

  • NSObject alloc 流程

    2.png

上图是一步步断点调试而来,调试方法请参考源码探索方法。我们简单分析一下,不管是NSObjec还是LYPersonalloc都不是首先调用的方法,甚至NSObjecalloc都没有调用。

为什么首先调用的是objc_alloc方法?查找llvm源码得知,在编译时进行了优化。当shouldUseRuntimeFunctionsForAlloc返回true时,对alloc进行优化。

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

探索发现LYPerson走到最后一步,调用alloc方法;NSObjec调用的是_objc_rootAllocWithZonehasCustomAWZ()判断当前类是否有默认的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 表示你可以确认该条件是极少发生的,相反 fastpath 表示该条件多数情况下会发生。编译器会产生相应的代码来优化 cpu 执行效率。

参考:
gcc 编译器 , __builtin_expect() 研究
iOS性能优化系列之__builtin_expect分支预测优化

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关联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
/*
*字节对齐
*LP64机器下8字节对齐
*其他4字节对齐
*/
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;
}
/*
*返回字节对齐后的内存大小
*/
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字节时,返回16字节
    return size;
}

然而现在objc源码普遍走的是fastInstanceSize函数,快速计算内存大小。而当前版本内存对齐是16字节对齐,苹果早期是8字节对齐

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()函数连续地为count对象分配足够的空间,这些对象是内存的大小字节,并返回一个指向所分配内存的指针。分配的内存充满了值为零的字节。

申请完内存,还需要初始化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流程就走完了,主要就是计算并分配内存,关联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在内存中的地址一致,只是指针地址不同。

你可能感兴趣的:(iOS底层-3:源码探索:alloc & init & new 源码分析)