iOS底层探索之alloc

前言

作为一名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,由于Person类对象一开始还没有alllc方法的缓存,调用objc_msgSend来调用alloc并加入方法缓存列表,Person没有实现alloc方法,最终找到了NSObjectalloc,再次来到了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.可以看到一个类的实例对象所需内存大小也被会被缓存,提供之后使用。

    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;
    }
    
    uint32_t alignedInstanceSize() const {
        return word_align(unalignedInstanceSize());
    }
    ------------
    #   define WORD_MASK 7UL
   static inline size_t word_align(size_t x) {
       //WORD_MASK是常量7,进行8字节对齐运算
       // 比如x=8,15的二进制值为 0000 1111
       // 与上7的取反,值为       1111 1000
       // 结果为00001000 = 8
        return (x + WORD_MASK) & ~WORD_MASK;
   }   
   
 
}
复制代码

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

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

image.png

总结

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

image.png

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享