001--alloc、init、new底层实现流程

一、alloc实现流程

image.png
image.png
Person *p = [Person alloc];

在Foundation层我们初始化一个对象需要调用alloc方法,通过查看堆栈信息我们可以大致知道函数调用过程如下:

[图片上传失败...(image-488e4f-1599590590512)]

1. alloc函数调用 _objc_rootAlloc 函数,传入相应的类,并且调用 callAlloc 函数。

+ (id)alloc {
    return _objc_rootAlloc(self);
}
// Base class implementation of +alloc. cls is not nil.
// Calls [cls allocWithZone:nil].
id
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

2.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__
    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底层一些特性:

  • 先看一下ALWAYS_INLINE
    inline 是一种降低函数调用成本的方法,其本质是在调用声明为 inline 的函数时,会直接把函数的实现替换过去,这样减少了调用函数的成本。 是一种以空间换时间的做法。

define ALWAYS_INLINE inline attribute((always_inline))

ALWAYS_INLINE宏会强制开启inline。

  • slowpath & fastpath

define fastpath(x) (__builtin_expect(bool(x), 1))

define slowpath(x) (__builtin_expect(bool(x), 0))

这两个宏使用__builtin_expect函数

__builtin_expect(EXP, N)

这个指令的意思是EXP==N的概率更大。用于上方就是对于> fastpath(x) x为真可能性更大,对于> slowpath(x) x为假可能性更大。
这个指令的作用是允许程序员将最有可能执行的分支告诉编译器,用于优化代码执行效率,提高预读指令的命中率,以减少指令跳转带来的性能下降!
所以我们在分析的时候,以实际为准。

对于下面代码:

if (fastpath(!cls->ISA()->hasCustomAWZ()))

此句代码为判断当前class or superclass 是否有自定义的alloc/allocWithZone 方法实现 ?
如果cls->ISA()->hasCustomAWZ()返回YES,意味着有自定义的allocWithZone方法实现。这个值会存储在metaclass中。

虽然这里是fastpath,但是对于初次创建的类是还没有默认的实现的。所以继续向下执行进入到msgSend消息发送流程,调用alloc函数。

3、alloc

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

4、_objc_rootAlloc

// Base class implementation of +alloc. cls is not nil.
// Calls [cls allocWithZone:nil].
id
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

执行到这个过程会再次进入到 callAlloc 函数,但是这一次当前类的默认实现已经注册完毕,所以会执行到 _objc_rootAllocWithZone 函数中。

5.callAlloc

if (fastpath(!cls->ISA()->hasCustomAWZ())) {
return _objc_rootAllocWithZone(cls, nil);
}

6. _objc_rootAllocWithZone

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

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

先看一下前面的几个bool值

bool hasCxxCtor = cls->hasCxxCtor();
bool hasCxxDtor = cls->hasCxxDtor();
bool fast = cls->canAllocNonpointer();

  • hasCxxCtor 判断当前class or superclass 是否有.cxx_construct构造方法的实现;
  • hasCxxDtor 判断当前class or superclass 是否有.cxx_destruct析构方法的实现;
  • canAllocNonpointer 是对 isa 的类型的区分,如果一个类和它父类的实例不能使用 isa_t 类型的 isa 的话,返回值为 false。在 Objective-C 2.0 中,大部分类都是支持的;

7.1 重要函数:计算所需空间大小:

size_t size = cls->instanceSize(extraBytes);

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

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


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

计算申请空间大小: 对于继承自NSObject没有任何属性的自定义类而言,默认有个isa结构体。占8字节。

@interface NSObject  {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
    Class isa  OBJC_ISA_AVAILABILITY;
#pragma clang diagnostic pop
}

最终经过 align16 函数计算方式:

(8 + 15)& ~15 (等同于>>4再<<4)

最终结果为16的倍数,且最小为16字节(这里的传入的x受类的属性个数的影响)。在Core Foundation 中,需要所有的对象的大小不小于 16 字节。

补充知识点:内存对齐原则

1:数据成员对其规则(struct)(或联 合(union))的数据成员,第
⼀个数据成员放在offset为0的地⽅,以后每个数据成员存储的起始位置要
从该成员⼤⼩或者成员的⼦成员⼤⼩(只要该成员有⼦成员,⽐如说是数组,
结构体等)的整数倍开始(⽐如int为4字节,则要从4的整数倍地址开始存
储。
2:结构体作为成员:如果⼀个结构⾥有某些结构体成员,则结构体成员要从
其内部最⼤元素⼤⼩的整数倍地址开始存储.(struct a⾥存有struct b,b
⾥有char,int ,double等元素,那b应该从8的整数倍开始存储.)
3:收尾⼯作:结构体的总⼤⼩,也就是sizeof的结果,.必须是其内部最⼤
成员的整数倍.不⾜的要补⻬。

7.2 重要函数:calloc

id obj;
if (zone) {
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
} else {
obj = (id)calloc(1, size);
}

alloc 开辟内存的地方。
按计算大小通过 calloc()函数为对象分配内存空间, calloc()会默认的把申请出来的空间初始化为0或者nil。(这里的zone基本是不会走的,苹果废弃了zone开辟空间,并且这里zone的入参传入的也是nil)

补充知识点:

函数malloc()和calloc()都可以用来动态分配内存空间,但两者稍有区别
malloc()函数有一个参数,即要分配的内存空间的大小:
void *malloc(size_t size);
calloc()函数有两个参数,分别为元素的数目和每个元素的大小,这两个参数的乘积就是要分配的内存空间的大小。
void *calloc(size_t numElements,size_t sizeOfElement);
如果调用成功,函数malloc()和函数calloc()都将返回所分配的内存空间的首地址。
函数malloc()和函数calloc()的主要区别是前者不能初始化所分配的内存空间,而后者能。如果由malloc()函数分配的内存空间原来没有被使用过,则其中的每一位可能都是0;反之,如果这部分内存曾经被分配过,则其中可能遗留有各种各样的数据。也就是说,使用malloc()函数的程序开始时(内存空间还没有被重新分配)能正常进行,但经过一段时间(内存空间还已经被重新分配)可能会出现问题。
经常用memset()进行清零
函数calloc()会将所分配的内存空间中的每一位都初始化为零,也就是说,如果你是为字符类型或整数类型的元素分配内存,那麽这些元素将保证会被初始化为0;如果你是为指针类型的元素分配内存,那麽这些元素通常会被初始化为空指针;如果你为实型数据分配内存,则这些元素会被初始化为浮点型的

  • 函数声明(函数原型):
    void malloc(int size);
    说明:malloc 向系统申请分配指定size个字节的内存空间。返回类型是 void
    类型。void* 表示未确定类型的指针。C,C++规定,void* 类型可以强制转换为任何其它类型的指针。从函数声明上可以看出。malloc 和 new 至少两个不同: new 返回指定类型的指针,并且可以自动计算所需要大小。
    比如:
    int p;
    p = new int; //返回类型为int
    类型(整数型指针),分配大小为 sizeof(int);
    或:
    int* parr;
    parr = new int [100]; //返回类型为 int* 类型(整数型指针),分配大小为 sizeof(int) * 100;
    而 malloc 则必须由我们计算要字节数,并且在返回后强行转换为实际类型的指针。
    int* p;
    p = (int *) malloc (sizeof(int));
  • 第一、malloc 函数返回的是 void * 类型,如果你写成:p = malloc (sizeof(int)); 则程序无法通过编译,报错:“不能将 void* 赋值给 int * 类型变量”。所以必须通过 (int *) 来将强制转换。
  • 第二、函数的实参为 sizeof(int) ,用于指明一个整型数据需要的大小。如果你写成:
    int* p = (int ) malloc (1);代码也能通过编译,但事实上只分配了1个字节大小的内存空间,当你往里头存入一个整数,就会有3个字节无家可归,而直接“住进邻居家”!造成的结果是后面的内存中原有数据内容全部被清空。
    malloc 也可以达到 new [] 的效果,申请出一段连续的内存,方法无非是指定你所需要内存大小。
    比如想分配100个int类型的空间:
    int
    p = (int *) malloc ( sizeof(int) * 100 ); //分配可以放得下100个整数的内存空间。
    另外有一点不能直接看出的区别是,malloc 只管分配内存,并不能对所得的内存进行初始化,所以得到的一片新内存中,其值将是随机的。除了分配及最后释放的方法不一样以外,通过malloc或new得到指针,在其它操作上保持一致

7.3重要函数: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) 
{ 
    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结构体初始化的过程。

关于Isa类型

Isa类型有如下宏定义

// Define SUPPORT_INDEXED_ISA=1 on platforms that store the class in the isa 
// field as an index into a class table.
// Note, keep this in sync with any .s files which also define it.
// Be sure to edit objc-abi.h as well.
#if __ARM_ARCH_7K__ >= 2  ||  (__arm64__ && !__LP64__)
#   define SUPPORT_INDEXED_ISA 1
#else
#   define SUPPORT_INDEXED_ISA 0
#endif

// Define SUPPORT_PACKED_ISA=1 on platforms that store the class in the isa 
// field as a maskable pointer with other data around it.
#if (!__LP64__  ||  TARGET_OS_WIN32  ||  \
     (TARGET_OS_SIMULATOR && !TARGET_OS_IOSMAC))
#   define SUPPORT_PACKED_ISA 0
#else
#   define SUPPORT_PACKED_ISA 1
#endif

// Define SUPPORT_NONPOINTER_ISA=1 on any platform that may store something
// in the isa field that is not a raw pointer.
#if !SUPPORT_INDEXED_ISA  &&  !SUPPORT_PACKED_ISA
#   define SUPPORT_NONPOINTER_ISA 0
#else
#   define SUPPORT_NONPOINTER_ISA 1
#endif
  • SUPPORT_INDEXED_ISA 的含义是,如果为 1,则会在 isa field 中存储 class 在 class table 的索引。SUPPORT_PACKED_ISA 为 1 时则是在 isa field 中通过 mask 的方式存储 class 的指针信息。

  • SUPPORT_NONPOINTER_ISA 用于标记是否支持优化的 isa 指针,其字面含义意思是 isa 的内容不再是类的指针了,而是包含了更多信息,比如引用计数,析构状态,被其他 weak 变量引用情况

_class_createInstanceFromZone 中,主要做了3件事,

  • 1.计算对象所需的空间大小;
  • 2.根据计算大小开辟空间;
  • 3.初始化isa,使其与当前对象关联。
补充知识点:isa流程图
截屏2020-06-11 下午2.34.32.png

二、init函数

通过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函数返回了当前对象而已!那么苹果如此设计的目的是什么呢?其实每个对象从出生并非是完全相同的,允许我们对各个对象进行不同的配置,这就是init的函数的目的所在。

三、new函数

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

包装了 alloc init,允许我们快速的生成一个对象。

四、总结

  • alloc是孕育的过程,孕育完成之时,对象的“遗传基因”等信息就已经确定了
  • init是出生的过程,允许我们在出生之后进行不同的装配。

你可能感兴趣的:(001--alloc、init、new底层实现流程)