iOS 底层原理之alloc

832 阅读4分钟

前言

作为一名iOS小码农,每天接触最多的就是对象的创建,alloc ,init; 但是alloc和init到底干了些什么?今天咱们来一起研究下,废话不多说,直接上代码.

WX20211021-214855@2x.png

分析图中代码:p1,p2,p3指向了同一块内存0x600002400780,但是p1,p2,p3这三个指针的地址是不相同的,且有一定的规律排列;0x7ffeef2790780x7ffeef2790700x7ffeef279068; 这是16进制数,所以每个之间相差值为8,正好是指针的大小;且是依次变小,并且0x7代表的是栈空间;从而得出指针是在栈区,且是从高地址向低地址开辟;继续分析看 p3,p4,p5指向的内存地址 0x6000024007800x6000024007900x6000024007a0 可得出对象存放在堆区且堆区是由低位置想高位置开辟。下面画一张图

image.png

总结

alloc 开辟了一块空间,init没有开辟空间

栈区开辟的内存是高地址到低地址,堆区则是低地址到高地址。

这里简单说一下堆栈的内容

栈:是一种具有特殊的访问方式的存储空间(后进先出, Last In Out Firt,LIFO)

image.png 注意:以前的栈:是往里放一个数据,sp往上挪一格,出去一个往下挪一格,也就是push,pop。 但是现在的ARM64是先开辟一块空间(可能是空的),sp直接指向栈顶,然后往里面放的东西,sp跟随者往下挪。iOS中栈的开口方向是往低地址,编译器通过编译来决定开辟栈空间的大小。局部变量,参数等放在栈空间中。

image.png 回归正题,接下来我们研究alloc,init中到底做了些什么来证实我们上面的结论是否正确。 有三种方式来查看alloc流程 1.打符号断点; 2.看汇编; 3.看源码走流程

一 : 简单介绍下怎么打符号断点

image.png

image.png

二:看汇编

image.png 步骤,Debug ----> Debug Workflow -------> Always Show Disassembly 通过汇编看流程,(取消也是同样的步骤)

image.png

三 看源码

苹果开源源码汇总

这个地址用的更直接

底层源码分析

我们在main函数中创建一个对象,然后点击alloc进入源码NSObject.mm中,然后依次点击进入

+ (id)alloc {
    return _objc_rootAlloc(self);
}
_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时发现有了if else分支了,这是我们不能确定走哪时,可以通过打断点调试发现进入了_objc_rootAllocWithZone这个方法,接下来我们继续跟进去

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);
}
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;
    // 1:要开辟多少内存
    size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;
    id obj;
    if (zone) {
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
        // 2;怎么去申请内存
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }
    if (!zone && fast) {
        // 3.对象关联到 类 里
        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);
}

进入_class_createInstanceFromZone 这个方法中我们发现代码比较长,不知道从何下手阅读,这时我们通过看返回值来找到这段代码的重点。接下来我们打断点调试看下流程 image.png 这时我们发现obj竟然有地址,这其实是系统给的脏地址,咱们继续往下走 image.png

image.png 可以看出走obj = (id)calloc(1, size);去创建对象,并且打印地址是个新址。细心的小伙伴可能会发现打印出来的信息和我们正常打印对象不一样;

image.png 这是因为此时obj对象还没关联到我们的类里面,继续往下走

image.png

image.png 这时obj就关联到类里面了,接下来return出去。所以我们暂时可以得出alloc的流程(这个流程还不完善,且继续往下看)

image.png 这时我们通过断点+汇编来验证下这个流程是否正确

image.png

查看汇编流程发现并不是_objc_rootAlloc,这是为什么?难道源码出问题了?其实这是苹果对alloc做了特殊处理,底层llvm对alloc方法做了拦截,先执行objc_alloc方法,然后callAlloc方法中执行return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));消息发送执行alloc方法,并做标记receiver,下次再进入callAlloc方法中执行_objc_rootAllocWithZone,所以正确的流程应该是:

alloc流程图

image.png

小总结:

1.instanceSize() 方法结算开辟内存的大小。
2.calloc() 方法开辟内存。
3.initInstanceIsa(cls, hasCxxDtor); 讲对象关联到类里