iOS alloc 流程分析

1,213 阅读4分钟

alloc源码流程分析

首先抛出一张流程图,oc对象alloc的一般流程如下图所示

XXXObject *object1 = [XXXObject alloc];
XXXObject *object2 = [XXXObject alloc]init];
XXXObject *object3 = [XXXObject new];

这几行代码是大家耳熟能详的代码。作用就是创建并返回一个类的实例。那么它的内部流程是什么呢?allocinit以及new分别都做了什么呢?接下来就会对此进行探索。

环境:xcode 11.5

源码:objc4-781

[XXXObject alloc]

通过源码可以发现,alloc方法应该会调用到NSObject的alloc方法

+ (id)alloc {
    return _objc_rootAlloc(self);
}

但是打断点发现,在执行到alloc方法之前,首先会进入objc_alloc方法,然后才会执行[NSObject alloc] 内部实现如下:

// Calls [cls alloc]. 表示会调起alloc方法
id objc_alloc(Class cls)
{
//注意此处的参数&1
    return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
}

如果我们把代码写成如下:

XXXObject *object2 = [XXXObject alloc]init];

那么会先进入objc_alloc_init方法,堆栈如下图: 内部实现如下:

// Calls [[cls alloc] init].
id
objc_alloc_init(Class cls)
{
    return [callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/) init];
}

同样都调用到了callAlloc函数,而且参数是一模摸一样样的,不同的是后面加上了init方法。

至于具体原因,应该是llvm编译器在编译过程中搞的鬼,在llvm的源码中找到如下的注释:

/// Instead of '[[MyClass alloc] init]', try to generate
/// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
/// caller side, as well as the optimized objc_alloc.

猜想是编译过程中,llvm对类似[[MyClass alloc] init]或者[MyClass alloc]这种代码做了优化。

alloc、_objc_rootAlloc

不管是objc_alloc还是objc_alloc_init,最终都会调用[NSObject alloc]方法,我们直接来看这个方法,源码如下:

+ (id)alloc {
	//此时self指的是类对象
    return _objc_rootAlloc(self);
}

+ (id)_objc_rootAlloc(Class cls) {
	//注意此处的参数&2
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

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) {
        return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
    }
    return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}

上文中说道过,objc_allocobjc_alloc_init方法也会调起callAlloc,最终会执行最后一行的objc_msgSend消息发送,最终重新调起[NSObject alloc]方法,然后alloc方法也会再次调起callAlloc方法,这一次会调起_objc_rootAllocWithZone(cls, nil)方法。

需要注意的几个点为:

  • slowpath(x)、fastpath(x)宏 用于编译优化,编译器可以通过这两个宏来调整指令的顺序,增加执行效率。
#define fastpath(x) (__builtin_expect(bool(x), 1)) 
表示x很有可能为1
#define slowpath(x) (__builtin_expect(bool(x), 0))
表示x很有可能为0
  • hasCustomAWZ() 是否有自定义的allocWithZone方法。
bool hasCustomAWZ() const {
        return !cache.getBit(FAST_CACHE_HAS_DEFAULT_AWZ);
    }

可以看到该函数的返回值和cache有一定的关系。

_objc_rootAllocWithZone

NEVER_INLINE
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
{
    // allocWithZone under __OBJC2__ ignores the zone parameter
    // 在OBJC2中忽略了zone参数
    return _class_createInstanceFromZone(cls, 0, nil,
                                         OBJECT_CONSTRUCT_CALL_BADALLOC);
}

_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(); // 获取 cls 及其父类是否有构造函数
    bool hasCxxDtor = cls->hasCxxDtor(); // 获取 cls 及其父类是否有析构函数
    bool fast = cls->canAllocNonpointer(); // 是对 isa 的类型的区分,如果一个类和它父类的实例不能使用 isa_t 类型的 isa 的话,返回值为 false,但是在 Objective-C 2.0 中,大部分类都是支持的
	// 1. 获取需要申请的空间大小
    size_t size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;
    
    id obj;
    if (zone) {
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
        // 2. 申请内存并返回id类型的指针
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }
    
    if (!zone && fast) {
    	// 3. 初始化实例对象的isa
        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;
    }
}

核心流程如下:

  1. 获取实例需要开辟的内存大小size
  2. 根据size开辟对应的内存空间并返回id类型的指针
  3. 初始化对应的isa指针

instanceSize计算内存空间

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;
        return size;
    }

会调用cache_t中的fastInstanceSize函数

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

最后会调用align16方法来返回真正需要开启的内存大小,返回值必然是16的倍数。

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

obj->initInstanceIsa

initInstanceIsa方法最终会调用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, 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;
    }
}

暂且放上源码,具体细节会下次分析。

init

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

+ (id)new {
    return [callAlloc(self, false/*checkNil*/) init];
}

可以发现,new其实是alloc、init连在一起的写法,平常在开发过程中,我们并不一定会调用init方法,有可能会调用initWithXXX:等方法,因此建议大家还是分开来写。