OC底层原理初探之alloc的探索上

524 阅读4分钟

前言

OC对象初始化时都要调用alloc方法,那么在底层,alloc方法又做了哪些来创建一个对象呢,今天就来探索alloc底层流程。

首先做一个小测试,对一个对象进行alloc和init操作,分别打印对象的内容,对象的地址以及对象指针的地址。代码和打印结果如下:

XQPerson *xq1 = [XQPerson alloc];
XQPerson *xq2 = [xq1 init];
XQPerson *xq3 = [xq1 init];

XQPerson *xq4 = [XQPerson alloc];

NSLog(@"%@-%p-%p",xq1,xq1,&xq1);
NSLog(@"%@-%p-%p",xq2,xq2,&xq2);
NSLog(@"%@-%p-%p",xq3,xq3,&xq3);

NSLog(@"%@-%p-%p",xq4,xq4,&xq4);
        
****************** 打印结果 ******************
        
2022-01-22 17:46:55.962006+0800 AllocDemo[7190:137926] <XQPerson: 0x1004084d0>-0x1004084d0-0x7ffeefbff478

2022-01-22 17:46:55.962547+0800 AllocDemo[7190:137926] <XQPerson: 0x1004084d0>-0x1004084d0-0x7ffeefbff470

2022-01-22 17:46:55.962599+0800 AllocDemo[7190:137926] <XQPerson: 0x1004084d0>-0x1004084d0-0x7ffeefbff468

2022-01-22 17:46:55.962634+0800 AllocDemo[7190:137926] <XQPerson: 0x100408520>-0x100408520-0x7ffeefbff460
        

堆栈地址排序.drawio.png

分析打印结果可得出:

xq1,xq2,xq3的内容,对象的地址是一样的, 但是指针的地址不一样。 xq4和xq1,xq2,xq3的内容,对象的地址,指针都是不一样的。

由此可得出结论:

1.alloc开辟了内存,而init没有开辟内存。 2.栈区分配的内存是由高到低,堆区分配的内存地址是由低到高。

下面正式开始探索alloc方法到底做了什么

准备工作:

1.下载源码objc-818.2

2.编译源码objc4-750源码编译,仅供参考

探索流程如下:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        XQPerson *xq1 = [XQPerson alloc];
        NSLog(@"%@",xq1);
    }
    return 0;
}

XQPerson *xq1 = [XQPerson alloc处添加断点,程序运行到断点后,按住control + command + step into 进入alloc方法

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

继续按上面同样的操作,进入 _objc_rootAlloc

id
_objc_rootAlloc(Class cls)
{
    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_rootAllocWithZone方法,继续按上面操作进入_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,这里是我们真正关心的核心代码了。

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

通过实际调试发现对obj影响较大的核心方法有三个:

1.cls->instanceSize(extraBytes);:计算需要开辟的内存空间的大小

2.(id)calloc(1, size);向系统申请开辟内存,返回地址指针

3.obj->initInstanceIsa(cls, hasCxxDtor); 初始化isa,将开辟的内存空间通过isa关联到当前cls

下面重点分析这三个方法: instanceSize:计算需要开辟的内存空间的大小

进入instanceSize

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

继续上面操作进入fastInstanceSize(size_t extra)

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

}

探究下align16方法的具体实现,以align16(8)为例

x = 8;
(x + size(15)) & ~ size_t(15)
8 + 15 = 23 0001 0111
15          0000 1111
~15         1111 0000
23 & ~15    0001 0111
          & 1111 0000
结果:       0001 0000  16

总结:align16算法实际上就是取16的整数倍。

为什么需要16字节对齐?

  1. 数据以字节对齐的方式存储,cpu读取数据时以固定字节长度来读取就可以了,不用频繁变换读取字节长度,这是一种以空间换时间的做法。
  2. 更安全 由于在一个对象中isa指针是占8个字节,如果不进行节对齐 ,对象之间就会紧挨着,容易造成访问混乱。16字节对齐,会预留部分空间,访问更安全

calloc:向系统申请开辟内存,返回地址指针

instanceSize计算所需内存大小后, 向系统申请大小为size的内存空间并返回给obj

截屏2022-01-22 下午9.19.43.png

截屏2022-01-22 下午9.20.27.png

图中可以看出,执行calloc后地址发生了改变,说明系统给obj分配了内存空间,但是此时执行po没有打印出类的信息,说明calloc开辟了内存空间,但是并没有将obj和cls进行绑定

initInstanceIsa 初始化isa,将开辟的内存空间通过isa关联到当前cls

进入objc_object::initInstanceIsa

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

进入objc_object::initIsa

inline void 

objc_object::initIsa(Class cls, bool nonpointer, UNUSED_WITHOUT_INDEXED_ISA_AND_DTOR_BIT bool hasCxxDtor)

{ 
    ASSERT(!isTaggedPointer()); 
    isa_t newisa(0);
    if (!nonpointer) {
        newisa.setClass(cls, this);
    } else {
        ASSERT(!DisableNonpointerIsa);
        ASSERT(!cls->instancesRequireRawIsa());


#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
#   if ISA_HAS_CXX_DTOR_BIT
        newisa.has_cxx_dtor = hasCxxDtor;
#   endif
        newisa.setClass(cls, this);
#endif
        newisa.extra_rc = 1;
    }
    // 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;
}

截屏2022-01-22 下午9.39.42.png

obj->initInstanceIsa(cls, hasCxxDtor)之后po打印obj

截屏2022-01-22 下午9.45.58.png

发现此时指针和类以及关联起来了。

通过源码探索alloc方法流程图如下

alloc流程1.drawio.png

总结: alloc 方法的核心作用是计算内存大小,分配内存空间并通过isa指针与类进行关联。