iOS底层探索之alloc(上)

546 阅读3分钟

前言

这是我参与更文挑战的第1天,活动详情查看: 更文挑战

作为一名iOS开发人员,日常接触最多的就是alloc,虽然知道allc的作用是给对象开辟内存空间,但不知道其背后的原理和逻辑。本篇分享一下如何借助objc的源码深入了解alloc

准备工作

objc的源码苹果官方是开源的,可以从官方的opensource上下载。最新的是824,但最近不能下载了,可以下载818,应该是大差不差的。

image.png 官方提供的源码需要一些配置才可以运行,这里可参考macOS 11.1 Xcode12.2 objc818源码编译

借助源码探索

  1. 创建对象
  Person *person = [Person alloc];

2.点击alloc进入实现方法。

+ (id)alloc {
    return _objc_rootAlloc(self);
}
----
id
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
----
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));
}

可以看到callAlloc是核心方法。 __OBJC2__这个宏表示objc2.0,目前我们使用的就是2.0版本。

slowpathfastpath两个宏定义如下,作用是将最有可能执行的分支告诉编译器,编译器在编译是时会调整指令的结构,减少指令跳转,达到优化的目的。 这里cls大概率是有值的。

#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))

3.此时不知道!cls->ISA()->hasCustomAWZ())的值,在此处下断点运行,所以能运行的作用就体现出来了。

4.成功在目标对象PersoncallAlloc断下,然后来到了这句代码

image.png 继续往下走发现来到了

image.png

此时的调用栈如下 image.png 由此可见[Person alloc]调用的是objc_alloc,来到callAlloc,至于这里为什么会来到objc_alloc,会再后续的文章中再去探索。 接着会再次来到了callAlloc,此时会调用_objc_rootAllocWithZone这个方法。

5.可以看到最终调用了_class_createInstanceFromZone这个最核心的方法。

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);
}
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);
}
  1. _class_createInstanceFromZone做了三件事情:
  • cls->instanceSize:计算需要开辟的内存空间大小
  • calloc:申请内存,返回地址指针
  • obj->initInstanceIsa:将 类 与 isa 关联 7.可以看到一个类的实例对象所需内存大小会先去缓存了里取,其实在类被加载到内存时就已经计算好了,所以大概率情况下能从缓存里直接取。 __builtin_constant_p是Gcc的内建函数,用于判断extra是否为编译时常数,这里的extra是入参不成立,会来到else分支,取出大小之后,并16字节对齐,align16是16字节对齐的方法。
    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.
        // 最小值为16
        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);
        }
    }
    ------------
   // 16字节对齐算法
   static inline size_t align16(size_t x) {
    return (x + size_t(15)) & ~size_t(15);
   }
 
}

8.计算后的所需内存大小给 calloc开辟内存,并返回指向该内存地址的指针。 如图 calloc之后,打印obj的值,此时改地址还没有跟类关联。

image.png 9.如图 obj->initInstanceIsa之后,打印obj的值,此时已经跟类关联。

image.png

总结

借助源码探索之后,对alloc有了更深入的了解,其功能就是核心方法_class_createInstanceFromZone所做的三件事:计算需要开辟的内存空间大小,申请内存,返回地址指针将类与isa关联,最终返回该地址指针。附上最终的流程图。

image.png