iOS底层原理01:alloc&init&new源码分析

1,831 阅读4分钟

前言

在iOS日常开发中,我们经常使用alloc init 方法来初始化对象,却没有去深究alloc在底层是如何执行的,这篇文章将从底层源码探索alloc的原理。

首先,我们新建一个工程,并初始化一组对象,打印他们的3个对象的内容内存地址指针地址

从上图我们可以看出,3个对象指向的是同一个内存空间,所以其内容和内存地址是相同的,但是对象的指针地址是不同的,为什么会这样呢,OC的底层是如何创建对象的呢?带着问题,我们进入下一步的探索。

%p -> p1: 对象指针指向的的内存地址
%p -> &p1:对象的指针地址

3种探索的方式

1.下符号断点的形式,跟着流程走

  • 先打个断点,代码运行到断点处,打个符号断点
  • 输入alloc
  • 点击下一步 由上面流程可以看出objc_alloc是在libobjc.A.dylib动态库创建的。

2.按住control+step into

  • 在代码运行至断点处
  • 接着打个符号断点objc_alloc 由此发现objc_alloclibobjc.A.dylib这个库里面。

3.汇编查看

-运行代码,在断点处,点击Debug->Debug Workflow->Always Show Disassembly

  • 从汇编代码callq处,我们看到汇编调用了objc_alloc
  • 下个符号断点objc_alloc

从以上的探索我们得知,对象的alloclibobjc.A.dylib中,于是我们从苹果开发源中去下载源码。

源码下载

源码探索

Person *objc1 = [Person alloc] ;

1.首先我们打开源码,创建一个对象,点击进入alloc方法的源码实现。

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

2.点击_objc_rootAlloc方法跳转至_objc_rootAlloc

id
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

3.点击callAlloc方法跳转至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方法。

关于slowpathfastpath,系统的定义如下:

#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))
  • 首先我们要知道__builtin_expect是什么。其实,这个指令是gcc引入的,作用是允许程序员将最有可能执行的分支告诉编译器。这个指令的写法为:__builtin_expect(EXP, N)
  • 目的:编译器可以对代码进行优化,以减少指令跳转带来的性能下降,即性能优化;
  • 作用:允许程序员将最有可能执行的分支告诉编译器;
  • 指令的写法为:__builtin_expect(EXP, N)。表示 EXP==N的概率很大;
  • fastpath定义中__builtin_expect((x),1)表示 x 的值为真的可能性更大;即执行 if 里面语句的机会更大;
  • slowpath定义中的__builtin_expect((x),0)表示 x 的值为假的可能性更大,即执行 else 里面语句的机会更大;

ls->ISA()->hasCustomAWZ(),这里用来判断当前class是否有自定义的allocWithZone。显然我们没有自定义allocWithZone方法,所以!cls->ISA()->hasCustomAWZ())true,代码执行_objc_rootAllocWithZone方法。

4.跳转至_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);
}

5.跳转至_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;
    // 1:要开辟多少内存
    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:怎么去申请内存
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }

    // 3:将当前的类和指针地址绑定在一起
    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);
}

alloc核心内容

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

通过断点调试,代码执行fastInstanceSize方法

 size_t fastInstanceSize(size_t extra) const
{
    ASSERT(hasFastInstanceSize(extra));

    //Gcc的内建函数 __builtin_constant_p 用于判断一个值是否为编译时常数,如果参数EXP 的值是常数,函数返回 1,否则返回 0
    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
        //删除由setFastInstanceSize添加的FAST_CACHE_ALLOC_DELTA16 8个字节
        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);
}
    1. 通过calloc申请内存,并赋值给obj,因此 obj是指向内存地址的指针
obj = (id)calloc(1, size);
    1. 通过initInstanceIsa,将当前的指针地址关联在一起
obj->initInstanceIsa(cls, hasCxxDtor);

以上就是alloc的探索过程,总结流程图如下:

总结

  • 通过对alloc源码的分析,可以得知alloc开辟内存最小为16字节且为16的整数倍。
  • 核心步骤:计算内存空间大小->向系统申请->关联到相应的类

init方法和new方法做了什么?

  • 查看源码
+ (id)init {
    return (id)self;
}

init方法返回了强转的self,这是构造方法也是工厂设计,方便我们重写init方法。

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

new方法则返回[callAlloc init]