OC源码分析之对象的建立

前言

抛出问题

进入主题以前,先请你们思考一下下面代码的输出git

#import <Foundation/Foundation.h>

@interface Person : NSObject

@end

@implementation Person

@end int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *p = [Person alloc];
        Person *p1 = [p init];
        Person *p2 = [p init];
        CCNSLog(@"p ==> %@", p);
        CCNSLog(@"p1 ==> %@", p1);
        CCNSLog(@"p2 ==> %@", p2);
    }
    return 0;
}
复制代码

执行的结果是:github

显而易见,对象p、p一、p2的内存地址一致,即这三者是同一个对象。那么问题来了,为何这三个对象地址是同样的?allocinit底层到底作了什么?带着这些问题,咱们从源码的角度探索一下吧。sass

准备工做

  1. 苹果官方开源代码列表 找到 objc4源码。

博主用到是最新版(objc4-756.2源码),同时,XCode版本是Version 11.3 (11C29)
源码版本和XCode版本不须要与博主一致~bash

  1. 下载到本地后,须要对工程进行一番编译调试,具体步骤可参考 Cooci大佬 的博客 iOS_objc4-756.2 最新源码编译调试app

  2. 编译经过后,就能够新建个target耍耍了。函数

博主已经把编译好的objc4-756.2项目传到 github 了,感兴趣的同窗能够下载哈~源码分析

1. alloc源码分析

由于oc语言的runtime特性,咱们并不能确定入口必定是+alloc方法,也就是说首先须要找到真正的入口。post

经常使用的代码跟踪方式:性能

  1. XCode菜单栏依次点击Debug->Debug Workflow->Always show Disassembly
  2. control + step into
  3. 下符号断点,如alloc

博主经常使用第一种,无他,手熟尔优化

1.1 objc_alloc——alloc的真正入口

[Person alloc]加断点

此时,在XCode的菜单栏依次点击Debug->Debug Workflow->Always show Disassembly,获得汇编代码

不难发现,接下来会执行objc_alloc。源码以下图:

思考:为何[Person alloc]会调用objc_alloc?(答案会在文末揭晓)

1.2 callAlloc分析——第一次的亲密接触

objc_alloc()内部调用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 (slowpath(checkNil && !cls)) return nil;

#if __OBJC2__
    if (fastpath(!cls->ISA()->hasCustomAWZ())) {
        // No alloc/allocWithZone implementation. Go straight to the allocator.
        // fixme store hasCustomAWZ in the non-meta class and 
        // add it to canAllocFast's summary
        if (fastpath(cls->canAllocFast())) {
            // No ctors, raw isa, etc. Go straight to the metal.
            bool dtor = cls->hasCxxDtor();
            id obj = (id)calloc(1, cls->bits.fastInstanceSize());
            if (slowpath(!obj)) return callBadAllocHandler(cls);
            obj->initInstanceIsa(cls, dtor);
            return obj;
        }
        else {
            // Has ctor or raw isa or something. Use the slower path.
            id obj = class_createInstance(cls, 0);
            if (slowpath(!obj)) return callBadAllocHandler(cls);
            return obj;
        }
    }
#endif

    // No shortcuts available.
    if (allocWithZone) return [cls allocWithZone:nil];
    return [cls alloc];
}
复制代码

callAlloc()的分析以下:

  1. slowpath(bool)fastpath(bool):经常使用于if-else,能够优化判断的速度。
// fastpath(x):表示x为1(执行if代码块)的可能性更大
#define fastpath(x) (__builtin_expect(bool(x), 1))
// slowpath(x):表示x为0(执行else代码块)的可能性更大
#define slowpath(x) (__builtin_expect(bool(x), 0))
复制代码
  1. hasCustomAWZ():意思是hasCustomAllocWithZone,便是否有重写类的+allocWithZone:方法,可是它的值并不能简单地这么判断!先看源码
bool hasCustomAWZ() {
    return ! bits.hasDefaultAWZ();
}
复制代码

注意:hasCustomAWZ()的值问题

  • 类的+initialize:方法主要用于初始化静态变量。在其执行以前,hasDefaultAWZ()值为false,即hasCustomAWZ()true;其执行以后,若是当前类重写了+allocWithZone:方法,hasCustomAWZ()true,不然为false
  • 类的+initialize:方法会在第一次初始化该类以前调用。当调用[cls alloc]时,会触发objc_msgSend,而后会执行+initialize:。(感兴趣的同窗能够分别打印+alloc+initialize:方法加以验证)

所以,当类第一次来到callAlloc()时,最终会执行[cls alloc]

  1. canAllocFast()源码以下:
bool canAllocFast() {
    assert(!isFuture());
    return bits.canAllocFast();
}
复制代码

再往底层找bits.canAllocFast(),发现关键宏FAST_ALLOC

#if FAST_ALLOC
    ...
    bool canAllocFast() {
        return bits & FAST_ALLOC;
    }
#else
    ...
    bool canAllocFast() {
        return false;
    }
#endif
复制代码

继续深刻,来到了FAST_ALLOC宏定义之处

#if !__LP64__ // 当前操做系统不是64位
...
#elif 1 // 当前操做系统是64位
...
#else
...
#define FAST_ALLOC (1UL<<2)
...
#endif
复制代码

从上面宏代码能够得出这样的结论,即不管当前操做系统是否是64位,都没有定义FAST_ALLOC,也就是说,canAllocFast()永远是false!

所以,若是hasCustomAWZ()false时,会直接去到class_createInstance()

1.3 alloc->_objc_rootAlloc->callAlloc->class_createInstance

经过对hasCustomAWZ()的分析,咱们知道类的第一次初始化最终是走到callAlloc的最后,即return [cls alloc];

  1. 因为执行了[cls alloc],此次真的来到alloc()方法了
+ (id)alloc {
    return _objc_rootAlloc(self);
}
复制代码
  1. 接着是_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*/);
}
复制代码
  1. 而后是callAlloc()->class_createInstance()

再次来到callAlloc,此时hasCustomAWZ()的值取决于当前类是否重写了+allocWithZone:方法。

因为Person类没有重写,fastpath(!cls->ISA()->hasCustomAWZ())为true,而canAllocFast()永远为false

所以,接下来会走到class_createInstance(),其源码以下:

id class_createInstance(Class cls, size_t extraBytes) {
    return _class_createInstanceFromZone(cls, extraBytes, nil);
}
复制代码

1.4 _class_createInstanceFromZone

顾名思义,这是要建立对象!可是,alloc的时候就建立对象???如今,咱们暂时把疑问放下,先分析一下源码:

static __attribute__((always_inline)) 
id
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone, 
                              bool cxxConstruct = true, 
                              size_t *outAllocatedSize = nil)
{
    if (!cls) return nil;

    assert(cls->isRealized());

    // 一次读取类的信息位以提升性能
    bool hasCxxCtor = cls->hasCxxCtor();    // 是否有构造函数
    bool hasCxxDtor = cls->hasCxxDtor();    // 是否有析构函数
    bool fast = cls->canAllocNonpointer();
    
    // 计算内存
    size_t size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (!zone  &&  fast) {
        // 分配1块大小为size的连续内存
        obj = (id)calloc(1, size);
        if (!obj) return nil;
        // 初始化对象的isa
        obj->initInstanceIsa(cls, hasCxxDtor);
    } 
    else {
        if (zone) {
            obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size);
        } else {
            obj = (id)calloc(1, size);
        }
        if (!obj) return nil;

        // Use raw pointer isa on the assumption that they might be 
        // doing something weird with the zone or RR.
        obj->initIsa(cls);
    }

    if (cxxConstruct && hasCxxCtor) {
        obj = _objc_constructOrFree(obj, cls);
    }

    return obj;
}
复制代码

_class_createInstanceFromZone()的分析以下:

  1. instanceSize(extraBytes)计算内存,此时的extraBytes0,其源码是
size_t instanceSize(size_t extraBytes) {
    size_t size = alignedInstanceSize() + extraBytes;
    // CF requires all objects be at least 16 bytes.
    if (size < 16) size = 16;
    return size;
}

uint32_t alignedInstanceSize() {
    return word_align(unalignedInstanceSize());
}

static inline uint32_t word_align(uint32_t x) {
    return (x + WORD_MASK) & ~WORD_MASK;
}
static inline size_t word_align(size_t x) {
    return (x + WORD_MASK) & ~WORD_MASK;
}
复制代码

WORD_MASK64位操做系统下是7,不然是3,所以,word_align()64位系统下是8字节对齐,其余位系统下是4字节对齐

instanceSize()函数同时对内存大小又进行了最小16字节的限制。

  1. canAllocNonpointer()是对isa的类型的区分,在 __OBJC2__ 中,若是一个类使用isa_t类型的isa的话,fast就是true;而在__OBJC2__中,zone会被忽略,因此!zone也是true

综上,接着就是calloc()initInstanceIsa()

  1. calloc()的底层源码是在 苹果开源的libmalloc 中,通过调试,calloc分配的内存大小受segregated_size_to_fit()影响,看下面源码:
static MALLOC_INLINE size_t segregated_size_to_fit(nanozone_t *nanozone, size_t size, size_t *pKey) {
	size_t k, slot_bytes;

	if (0 == size) {
	    // Historical behavior
	    size = NANO_REGIME_QUANTA_SIZE;
	}
	// round up and shift for number of quanta
	k = (size + NANO_REGIME_QUANTA_SIZE - 1) >> SHIFT_NANO_QUANTUM; 
	// multiply by power of two quanta size
	slot_bytes = k << SHIFT_NANO_QUANTUM;							
	// Zero-based!
	*pKey = k - 1;													

	return slot_bytes;
}

#define SHIFT_NANO_QUANTUM 4
#define NANO_REGIME_QUANTA_SIZE (1 << SHIFT_NANO_QUANTUM) // 16
复制代码

其中,slot_bytes至关于(size + 16-1) >> 4 << 4,也就是16字节对齐

  1. initInstanceIsa()就是初始化isa,而且关联cls

isa 是 objc 类结构中极其重要的一环,关于它的结构、初始化过程、继承关系等内容,博主会另起一篇文章讲述,敬请期待。

从上面的代码能够看出,_class_createInstanceFromZone()作了不少事情,而且最终确实建立了对象,几乎干了全部事情,那么,init又到底作了什么呢?请接着看下去。

2. init和new

1. 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仅仅是将alloc建立的对象返回。为何这样设计呢?其实并不难理解,在平时的开发中,咱们经常会根据业务需求重写init,进行一些自定义的配置。

NSObjectinit是一种工厂设计方案,方便子类重写。

2. new

咱们再看看new

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

很明显,new至关于alloc+init

3. 总结

关于allocinit以及new的源码分析就到这了。在alloc的过程当中,callAlloc_class_createInstanceFromZone这两个函数是重点。

以上源码流程分析,是创建在objc4-756.2源码的基础上的,756.2是目前最新的版本。

下面用流程图总结一下alloc建立对象的过程

4. 结束语

以上就是OC对象源码建立的所有内容了。回首整个过程,有顺利也有坎坷,整体比较烧脑,可是通过alloc这一条龙服务后,仿佛完成了某项重任,身心无比愉悦。

OC源码分析之路,必将是荣誉之路,但愿你们且行且珍惜,你我共勉!

补充

  1. Q:思考:为何[Person alloc]会调用objc_alloc
    A:项目编译的时候,会读取镜像文件,在_read_images()函数中,有这样一段代码:
void _read_images(...)
{
...
#if SUPPORT_FIXUP
    // Fix up old objc_msgSend_fixup call sites
    for (EACH_HEADER) {
        message_ref_t *refs = _getObjc2MessageRefs(hi, &count);
        if (count == 0) continue;
        ...
        for (i = 0; i < count; i++) {
            fixupMessageRef(refs+i);
        }
    }
    ts.log("IMAGE TIMES: fix up objc_msgSend_fixup");
#endif
...
}
复制代码

而在fixupMessageRef()中,有对SEL_alloc进行IMP的修复绑定

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

    if (msg->imp == &objc_msgSend_fixup) { 
        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;
        }
    } 
...
}
复制代码

经过[Person alloc]调用的是objc_alloc()这个既定事实,咱们能够猜想,在项目编译生成Mach-O文件期间,造成了SEL_allocobjc_alloc的对应关系。

你们能够将编译生成的Mach-O文件拖到MachOView中,验证一下,看看可否找到objc_alloc

最后的问题

  1. 下面的两次alloc,底层流程区别?若是Person类重写了+allocWithZone:呢?
Person *p1 = [Person alloc];
Person *p2 = [Person alloc];
复制代码

你们能够本身试试,经过比较会帮助你们理解记忆alloc的流程。

相关文章
相关标签/搜索