OC_Alloc 响应流程

709 阅读2分钟

调用流程

alloc -> objc_alloc -> 
callAlloc -> objc_msgSend -> alloc -> objc_rootAlloc ->
callAlloc -> _objc_rootAllocithZone -> _class_createInstanceFromZone

alloc流程解析:

Animal * animal = [Animal alloc];

1、alloc -> objc_alloc
程序在调用alloc的时候会调用fixupMessageRef方法,将alloc指向objc_alloc, 原因是llvm对底层方法进行了优化,alloc被hook成objc_alloc,这样做的目的就是标记一个receiver,在标记完这个类为receiver之后都会进入普通的消息发送判断(调用fixupMessageRef,然后第二次进入的alloc方法),这样做的目的其实就是间接符号的绑定。

static void 
fixupMessageRef(message_ref_t *msg)
{    
   msg->sel = sel_registerName((const char *)msg->sel);

   if (msg->imp == &objc_msgSend_fixup) { 
       //alloc -> objc_alloc
       if (msg->sel == SEL_alloc) {
           msg->imp = (IMP)&objc_alloc;
       } else if (msg->sel == SEL_allocWithZone) {
           msg->imp = (IMP)&objc_allocWithZone;
       } else if (msg->sel == SEL_retain) {
           msg->imp = (IMP)&objc_retain;
       } else if (msg->sel == SEL_release) {
           msg->imp = (IMP)&objc_release;
       } else if (msg->sel == SEL_autorelease) {
           msg->imp = (IMP)&objc_autorelease;
       } else {
           msg->imp = &objc_msgSend_fixedup;
       }
   } 
   //...
}

汇编查看 指向objc_alloc image.png

2、objc_alloc -> callAlloc

// Calls [cls alloc].
id
objc_alloc(Class cls)
{
    return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
}

3、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));
}
//__builtin_expect(EXP, N)。表示 EXP==N的概率很大。
//目的:编译器可以对代码进行优化,以减少指令跳转带来的性能下降。即性能优化 
//作用:允许程序员将最有可能执行的分支告诉编译器
//x很可能为真, fastpath可以简称为真值判断, 执行if 里面语句的机会更大
#define fastpath(x) (__builtin_expect(bool(x), 1))
//x很可能为假,slowpath 可以简称为 假值判断, 执行else 里面语句的机会更大
#define slowpath(x) (__builtin_ecallAllocl(x), 0))

4、objc_msgSend -> alloc -> _objc_rootAlloc -> callAlloc

//这里是第二次进入callAlloc
id
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

5、callAlloc -> _objc_rootAllocWithZone -> _class_createInstanceFromZone
进入 _objc_rootAllocWithZone 中,调用 _class_createInstanceFromZone 开始创建对象

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

6、 _class_createInstanceFromZone

/***********************************************************************
* class_createInstance
* fixme
* Locking: none
*
* Note: this function has been carefully written so that the fastpath
* takes no branch.
**********************************************************************/
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
    //判断当前class或者superclass是否有`.cxx_construct` 构造方法的实现
    bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
    //判断判断当前class或者superclass是否有`.cxx_destruct` 析构方法的实现
    bool hasCxxDtor = cls->hasCxxDtor();
    //canAllocNonpointer()具体标记某个类是否支持优化的isa
    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) {
        //内部调用 initIsa(cls, true, hasCxxDtor) 初始化isa
        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);
}

7、instanceSize()

    // Class's ivar size rounded up to a pointer-size boundary.
    uint32_t alignedInstanceSize() const {
        return word_align(unalignedInstanceSize());
    }
    
    inline size_t instanceSize(size_t extraBytes) const {
        //若存在缓存,就16字节对齐
        if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
            return cache.fastInstanceSize(extraBytes);
        }
        //alignedInstanceSize():字节对齐的算法
        size_t size = alignedInstanceSize() + extraBytes;
        // CF requires all objects be at least 16 bytes.
        //16字节对齐
        if (size < 16) size = 16;
        return size;
    }

new与alloc关系
[NSObject new] = [[NSObject alloc] init];

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