OC底层之alloc流程探索

通过[[XXXX alloc] init]创建实例对象我们再熟悉不过了,今天我们来探索一下alloc的底层原理,我们先写下面一行代码,打上断点并执行。

JPerson *p = [JPerson alloc];
复制代码

按住control点击step into可以看到符号objc_alloc,我们设置符号断点objc_alloc可以看到objc_alloc是在libobjc.A.dylib

libobjc.A.dylib`objc_alloc
复制代码

这里使用的是objc4-781.2版本

objc_alloc

// Calls [cls alloc].
id
objc_alloc(Class cls)
{
    return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
}
复制代码

callAlloc

// Call [cls alloc] or [cls allocWithZone:nil], with appropriate 
// shortcutting optimizations.
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__
    // 目前我们使用的是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));
}
复制代码

目前我们使用的都是objc2版本,所以先看_objc_rootAllocWithZone

hasCustomAWZ()是否有自定义的allocWithZone方法,我们后面研究isa的时候再来探索

bool hasCustomAWZ() const {
        return !cache.getBit(FAST_CACHE_HAS_DEFAULT_AWZ);
    }
复制代码

_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

/***********************************************************************
* class_createInstance
* fixme
* Locking: none
*
* Note: this function has been carefully written so that the fastpath
* takes no branch.
**********************************************************************/
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)
{
    // 避免多线程问题,这里同样涉及到isa
    ASSERT(cls->isRealized());

    // Read class's info bits all at once for performance
    // cls及其父类是否有c++构造函数和析构函数
    bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
    bool hasCxxDtor = cls->hasCxxDtor();
    // 实例对象的isa是一个单纯的指针true,isa不是一个纯粹的指针为false
    // 后面研究isa的之后还会涉及到
    bool fast = cls->canAllocNonpointer();
    size_t size;

    // 获取需要开辟的空间大小
    size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (zone) { // zone为nil
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
        obj = (id)calloc(1, size);
    }
    
    // 处理obj空间开辟失败的情况
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }

    // objc2版本中canAllocNonpointer()=true
    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);
}
复制代码

这个方法实现了:获取要开辟空间的大小,并开辟空间,初始化isa然后返回指针

instanceSize

size_t instanceSize(size_t extraBytes) const {
        // 是否缓存过需要开辟的空间大小
        if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
            return cache.fastInstanceSize(extraBytes);
        }

        // 8字节对齐,如果小于16字节,那么返回16字节
        size_t size = alignedInstanceSize() + extraBytes;
        // CF requires all objects be at least 16 bytes.
        if (size < 16) size = 16;
        return size;
    }
复制代码

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

static inline size_t align16(size_t x) {
    return (x + size_t(15)) & ~size_t(15);
}
复制代码

x加上15以后低四位清零,即16字节对齐

initInstanceIsa

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) 
{ 
    // 不能是taggetPointer对象
    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然后赋上了一些值,具体这些值是什么意思我们分析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;
}

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

init其实什么都没有实现,只是为开发者提供了一个便捷的接口,new其实是allocinit连着写的写法

本文中涉及到了很多isa相关的操作,我们将会在下一篇文章中详细讨论isa

参考文章

# iOS alloc 流程分析

猜你喜欢

转载自juejin.im/post/7019129133884162078
今日推荐