iOS底层原理

iOS底层原理-001 探索alloc

2020-09-07  本文已影响0人  杨奇

alloc与init在对象初始化的作用

先列出一段代码与输出结果

    LGPerson *p1 = [LGPerson alloc];
    LGPerson *p2 = [p1 init];
    LGPerson *p3 = [p1 init];
    LGNSLog(@"%@ - %p - %p",p1,p1,&p1);
    LGNSLog(@"%@ - %p - %p",p2,p2,&p2);
    LGNSLog(@"%@ - %p - %p",p3,p3,&p3);

输出结果

    <LGPerson: 0x600000459a80> - 0x600000459a80 - 0x7ffeea9431c8
    <LGPerson: 0x600000459a80> - 0x600000459a80 - 0x7ffeea9431c0
    <LGPerson: 0x600000459a80> - 0x600000459a80 - 0x7ffeea9431b8

发现三个对象都指向同一块内存空间,初步认定init并没有对p1做了处理,内存空间由alloc申请开辟。
在p1初始化出打断点句号,进入断点alloc

+ (instancetype)alloc OBJC_SWIFT_UNAVAILABLE("use object initializers instead");

跳到这里就不能更近一步了,显然这样不行。

使用汇编

打开汇编

在这里设置打开汇编,运行代码

    0x10004dc66 <+54>:  movq   0x47d3(%rip), %rax        ; (void *)0x0000000100052538: LGPerson
    0x10004dc6d <+61>:  movq   %rax, %rdi
    0x10004dc70 <+64>:  callq  0x10004e430               ; symbol stub for: objc_alloc

在callq这一行发现symbol stub for: objc_alloc, 打断点,按住ctl,step into进入objc_alloc

设置符号断点

跳转后的代码是这样:

001-alloc&init探索`objc_alloc:

使用设置符号断点,可以看到所在库为libobjc.A.dylib ID 6.1


objc_alloc所在库

开源库

进入苹果开源库,下载objc最新版本。

objc开源库

打开下载好的开源库,全局搜索alloc方法,结果如下

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

然后进入_objc_rootAlloc方法

_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

继续进入callAlloc

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

会看到if语句,不确定执行哪一个。然后返回我们的代码,将每一个方法都设置符号断点。


符号断点

会发现最后停止在libobjc.A.dylib`_objc_rootAllocWithZone:

libobjc.A.dylib`_objc_rootAllocWithZone:

继续往下 _objc_rootAllocWithZone

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

再往下跳转就进入了alloc的核心方法_class_createInstanceFromZone内部

_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)要开辟多少内存

cls->canAllocNonpointer方法

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

通过断点会发现执行的是cache.fastInstanceSize

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

会发现最后返回align16

static inline size_t align16(size_t x) {
    return (x + size_t(15)) & ~size_t(15);
}

可以看到是返回的是一个16字节对齐算法
x为需要开辟多少内存 +15 然后对与取反后的15进行位与运算

2)怎么申请内存

calloc方法
po当前obj后得出: 0x000000010114f040; 已经开辟了内存空间,但是发现只是有指针,并不是正常的对象打印,没有与对象关联

3)将开辟的内存与对象绑定

obj->initInstanceIsa方法

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

此时在进行一次 po obj
<LGPerson: 0x10114f040>

到这里就已经完成了alloc的整个流程
可以得出alloc是开辟内存的操作

init

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

可以看出 init将传入的对象转化了一个id类型的对象。
疑惑,为什么要alloc其实已经完成了开辟内存的操作,init构造方法是不是多此一举。
其实,这样做为工厂设计提供了便捷。为开发者提供了一个构造方法的入口。

new

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

好像在哪见过,找一下,在alloc中的_objc_rootAlloc找到了

_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

new方法是在callAlloc后添加了一个init方法
可以得出new = alloc init
所以在重写init方法后,使用new并没有调用重写后的init。

流程图 alloc流程图

上一篇 下一篇

猜你喜欢

热点阅读