iOS底层原理(1)-- OC对象原理上

807 阅读4分钟

探究alloc底层的原理

初步分析

直接上代码,打印p的内容,地址,指针地址

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

打印结果:

<LGPerson: 0x600001cfc1a0>-0x600001cfc1a0-0x7ffee77ae0a8
<LGPerson: 0x600001cfc1a0>-0x600001cfc1a0-0x7ffee77ae0a0
<LGPerson: 0x600001cfc1a0>-0x600001cfc1a0-0x7ffee77ae098
<LGPerson: 0x600001cfc1b0>-0x600001cfc1b0-0x7ffee77ae090
<LGPerson: 0x600001cfc1c0>-0x600001cfc1c0-0x7ffee77ae088

直观结果:

三者的内容是一样的,地址是一样的,指针地址是不一样的。

分析:

1、指针存放在栈空间里面,指针地址空间的分配是连续的,从高地址向低地址分配,且为8个字节

0x7ffee68b80a8 - 8 = 0x7ffee68b80a0
0x7ffee68b80a0 - 8 = 0x7ffee68b8098
0x7ffee77ae098 - 8 = 0x7ffee77ae090
0x7ffee77ae090 - 8 = 0x7ffee77ae088

2、alloc 分配内存空间,init 不分配内存空间 3、对象的内容分配在堆空间,堆空间的分配也是连续的,从低地址向高地址分配,为16个字节(跟对象的大小可能有关系)

<LGPerson: 0x600001cfc1a0>
<LGPerson: 0x600001cfc1b0>
<LGPerson: 0x600001cfc1c0>

引申: 为什么栈内存从高到低分配,堆内存从低到高分配?

底层探索的三种方法

1、符号断点

运行到断点位置,按住control,点击step into ,加符号断点objc_alloc,继续运行,最终找到了libobjc.A.dylib objc_alloc

image.png Screen Shot 2021-06-05 at 7.58.12 PM.png image.png image.png

2、汇编

打开 Always Show Disassembly 开关,开始运行到断点,加符号断点objc_alloc,继续运行得到结果

image.png

image.png

image.png

3、符号断点 确定位置

直接加 alloc 的符号断点

image.png

分析:

上面三种方法都离不开符号断点,不外乎就是最外层的符号还是内层的符号,层层剥开总会找到的。

源码

以上三种方法均是在推测源码的基础上进行动态调试,不方便。苹果提供了相关objc的源码,那么就好办了,编译源码并运行,接下来直接分析源码。

这次不需要按住control ,直接step into

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        LGPerson *p = [LGPerson alloc] ;
        p.name      = @"fengle";
        p.nickName  = @"fl";
        p.age       = 18;
        p.height    = 1;
        p.ch1    = 1;
        p.ch2    = 1;
        p.ch3    = 1;
        p.ch4    = 1;

        NSLog(@"%@",p);
    }
    return 0;
}

alloc

接下来进入alloc

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

_objc_rootAlloc 相当于一个函数空壳,用来装callalloc

接下来进入 _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*/);
}

callAlloc核心方法:分配内存

接下来进入 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 __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));
}

_objc_rootAllocWithZone

接下来进入 _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);
}

_class_createInstanceFromZone

接下来进入 _class_createInstanceFromZone

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);//计算在编译时确定的成员变量的大小,在class_root_t中
    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);//初始化isa指针,并关联cls
    } 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);
}

流程图:

image.png

从流程图和源代码可以看出,最底层的方法是_class_createInstanceFromZone ,而该方法中有三个关键的方法:

  • cls->instanceSize : 计算内存大小

  • (id)calloc(1, size) : 分配内存,返回指向该内存地址的指针

  • obj->initInstanceIsa :初始化指针,和类关联起来

内存大小的计算 :cls->instanceSize

inline size_t instanceSize(size_t extraBytes) const {
//快速计算内存大小
        if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
            return cache.fastInstanceSize(extraBytes);
        }
//计算类中所有变量需要的内存大小   extraBytes额外字节数一般是0
        size_t size = alignedInstanceSize() + extraBytes;
        // CF requires all objects be at least 16 bytes.
        //最小是16字节
        if (size < 16) size = 16;  
        return size;
    }

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

开辟内存:(id)calloc(1, size)

上一步已经计算出需要的内存大小size, calloc 向系统申请 size 大小的内存,返回给objc,因此objc是指向内存地址的指针

calloc 只负责分配内存

初始化ISA并关联cls: obj->initInstanceIsa

inline void 
objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
    ASSERT(!cls->instancesRequireRawIsa());
    ASSERT(hasCxxDtor == cls->hasCxxDtor());

    initIsa(cls, true, hasCxxDtor);
}

指针初始化之后与cls进行关联,最终得到完整的objc。