01 - alloc init new 流程,源码解析

2020-09-06  本文已影响0人  思路不美

一. 源码探索的三种方式

在OC中我们以alloc为例,查找alloc所在的源码库

1.符号断点

添加 symBolic Breakpoin

2. control + step into

3 .汇编查找

注意(以下是Apple 提供的源码下载地址):
1、Apple 所有开源源码汇总地址,根据相应的版本查找对应的源码,以mac 10.15为例: macOS --> 10.15 --> 选择10.15 --> 搜索 objc
2、Apple 比较直接的源码下载地址,直接搜索想要下载的源码名称即可,例如objc直接搜索 objc --> objc4/ --> 选择相应的objc的版本

二 alloc 流程 源码解析

准备工作: 下载 objc4-781 源码并编译

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

但当我们运行调试时发现先走的是

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

这里我们先在下一篇文章中讨论,涉及到LLVM优化 也是我们创建的类与系统类如NSObject alloc方法一点区别

//第二层
// 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*/);
}

-3 通过断点调试发现走_objc_rootAllocWithZone方法

// Call [cls alloc] or [cls allocWithZone:nil], with appropriate 
// shortcutting optimizations.
static ALWAYS_INLINE id
//#define ALWAYS_INLINE inline __attribute__((always_inline)) 
// ALWAYS_INLINE强制开启 inline inline  是一种降低函数调用成本的方法,其本质是在调用声明为 inline 的函数时,会直接把函数的实现替换过去,这样减少了调用函数的成本。 是一种以空间换时间的做法 
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__ 
//这里会进行 slowpath fastpath判断
//#define fastpath(x) (__builtin_expect(bool(x), 1))  x可能为真
//#define slowpath(x) (__builtin_expect(bool(x), 0)) x很可能为假
    if (slowpath(checkNil && !cls)) return nil;
    if (fastpath(!cls->ISA()->hasCustomAWZ())) { //cls->ISA()->hasCustomAWZ()判断一个类是否有自定义的 +allocWithZone 实现 如果有 值会存储在metaclass中
        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));
}

这里解释下 slowpath fastpath, __builtin_expect是 GCC (version >= 2.96)提供给程序员使用的,目的是将“分支转移”的信息提供给编译器,即提高预读指令的命中率 这样编译器可以对代码进行优化,以减少指令跳转带来的性能下降

int x, y;
 if((fastpath (x > 0)) //在x的值大于0 的概率比较小的情况下可以使用,编译器可以预先读取y = 1这条指令,减少重新取指
    y = 1; 
else 
    y = 0;
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);
}
/***********************************************************************
* 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
    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 {
        // alloc 开辟内存的地方
        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);
}

这里我们查看下三个重点方法

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

以align16(8)为例 返回 8 + 15 = 23 -> 0000 0000 0001 0111
15 -> 0000 0000 0000 1111 取反为 1111 1111 1111 0000
&运算得 0000 0000 0001 0000 = 16
&运算 每位都为1 结果为1 反之为0
字节对齐原因

-5.3 obj->initInstanceIsa(cls, hasCxxDtor);
类与地址关联 return obj;

init

+ (id)init {
    return (id)self;
}

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

这个就比较简单了 直接返回self

四 new

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

由源码可以看出相当于 alloc init,但使用new方法无法调用 重写的init方法如initWIthName:...所以一般不推荐使用

上一篇 下一篇

猜你喜欢

热点阅读