美文网首页
1.二刷之探索alloc

1.二刷之探索alloc

作者: 牛牛大王奥利给 | 来源:发表于2023-01-11 18:07 被阅读0次

1.准备工作

  • 我的运行环境
    • macOS 13.1
    • M1 芯片
    • Xcode 14.0.1
  • 首先准备好一份源码,链接地址:https://github.com/LGCooci/KCObjc4_debug ,我使用的是 objc4-866.9,初次运行报错如下:
image.png

__dyld_get_dlopen_image_header__dyld_objc_register_callbacks报错。
解决办法:分别搜一下这两个方法改成如下

image.png image.png

clean一下,再运行就成功了。不过偶尔也报错,但是再clean一次就可以了。

2.从alloc入手

 LGPerson *p = [LGPerson alloc];
 LGPerson * p1 = [p init];
 LGPerson * p2 = [p init];
 NSLog(@"对象p:%@,p的指针:%p",p,&p);
 NSLog(@"对象p1:%@,p1的指针:%p",p1,&p1);
 NSLog(@"对象p2:%@,p2的指针:%p",p2,&p2);

输出:

对象p :<LGPerson: 0x600000c0c000>,p的指针: 0x30410b230
对象p1:<LGPerson: 0x600000c0c000>,p1的指针:0x30410b220
对象p2:<LGPerson: 0x600000c0c000>,p2的指针:0x30410b228

从输出来看p,p1,p2指向的是一个对象,也就是同一片内存,但是p,p1,p2本身是不同的。

image.png

alloc方法开辟了一块内存空间,下面的init方法相当于又创建了几个指针来指向这块内存。但是他们具体做了什么操作,需要进一步的探究源码,一探究竟。

3.探究源码的方式

跟着KC学习到了探究源码的三种方式。

  • 使用Control+Step Into进行调试
  • 通过汇编查看调用流程
  • 通过已知符号来探索具体调用

通过这三种方式都可以找到最终的libobjc.A.dylib-objc_alloc

4.alloc的具体探究

打开我们准备好的objc4-866.9,然后运行代码跟着流程和调用来看看一个alloc下面到底藏了多少方法。

4.1 alloc的实现方法

跟着源码,点击进入到alloc的实现:

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

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

调用流程alloc->_objc_rootAlloc->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 (slowpath(checkNil && !cls)) return nil;

    if (fastpath(!cls->ISA()->hasCustomAWZ())) {

        return _objc_rootAllocWithZone(cls, nil);

    }


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

这里出现了几个比较重要的判断和方法:

1、slowpathfastpath

这是宏定义

// 表示x的值为假的可能性更大
#define slowpath(x) (__builtin_expect(bool(x), 0))

// 表示x的值为真的可能性更大
#define fastpath(x) (__builtin_expect(bool(x), 1))

__builtin_expect是GCC提供给程序员使用,目的是将“分支转移”的信息提供给编译器,这样编译器可以对代码进行优化,以减少指令跳转带来的性能下降。

if (slowpath(checkNil && !cls))的意思就是cls大概率是有值的,告诉编译器编译时优化掉这个部分,也就是nil这个部分几乎不会走,那么就直接来到了判断if (fastpath(!cls->ISA()->hasCustomAWZ()))的部分。

2、hasCustomAWZ

它的实现如下:

bool hasCustomAWZ() const {
    return !cache.getBit(FAST_CACHE_HAS_DEFAULT_AWZ);
}

FAST_CACHE_HAS_DEFAULT_AWZ的描述是:

// class or superclass has default alloc/allocWithZone: implementation
// Note this is is stored in the metaclass.

#define FAST_CACHE_HAS_DEFAULT_AWZ  (1<<14)

它是判断这个类或者它的父类有没有实现allocWithZone的,而方法hasCustomAWZ大概率全称是hasCustomAllocWithZone后面AllocWithZone缩写成了AWZ😂。

而类本身是有懒加载的概念的,第一次给这个类发送消息之前,该类是没有加载的,所以收到alloc消息的时候,那么allocWithZone是没有默认实现的,所以hasCustomAWZ返回false,会走流程_objc_rootAllocWithZone

第一次进到该方法:

image.png

而方法_objc_rootAllocWithZone的具体实现接着看下面。

3、_objc_rootAllocWithZone

id
_objc_rootAllocWithZone(Class cls, objc_zone_t zone __unused)
{
    // allocWithZone under __OBJC2__ ignores the zone parameter
    return _class_createInstanceFromZone(cls, 0, nil,
                                         OBJECT_CONSTRUCT_CALL_BADALLOC);
}

调用了_class_createInstanceFromZone,这个方法就内容挺长的还挺多的,下面来着重的看一下。

4.2 class_createInstanceFromZone方法开辟空间

e9a4376a15044ef1b05a1a167e214ec2~tplv-k3u1fbpfcp-zoom-in-crop-mark-3024-0-0-0.image.png
  • hasCxxCtor()hasCxxDtor()

hasCxxCtorhasCxxDtor是用来处理C++成员变量的构造和析构。

hasCxxCtor是判断当前class或者superclass是否有.cxx_construct的实现;

hasCxxDtor是判断当前class或者superclass是否有.cxx_destruct的实现。

// class or superclass has .cxx_construct/.cxx_destruct implementation
// FAST_CACHE_HAS_CXX_DTOR is chosen to alias with isa_t::has_cxx_dtor
#define FAST_CACHE_HAS_CXX_CTOR       (1<<1)

bool hasCxxCtor() {
    ASSERT(isRealized());
    return cache.getBit(FAST_CACHE_HAS_CXX_CTOR);
}
  • instanceSize()
//extraBytes 传进来是0
inline 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.
    //至少16个字节!!!!!!!!!!!!!!!!!!!!!
    if(size < 16) size = 16;
    return size;
}

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

static inline uint32_t word_align(uint32_t x) {
   return (x + WORD_MASK) & ~WORD_MASK;
}

#ifdef __LP64__
#define WORD_SHIFT 3UL
#define WORD_MASK 7UL
#define WORD_BITS 64

#else
#define WORD_SHIFT 2UL
#define WORD_MASK 3UL
#define WORD_BITS 32
#endif

在调用方法instanceSize传进来的参数extraBytes是0;
hasFastInstanceSize在64位下才启用;

alignedInstanceSize是对齐方式,根据代码可以看到64位下是8字节对齐,32位下是4字节对齐,计算方式是对WORD_MASK取反,然后进行与的操作。所以这个方法计算了需要开辟的空间大小。

我们回到方法_class_createInstanceFromZone中,zone这个值传进来的是nil,所以下面走的方法是 obj = (id)calloc(1, size);
而实际去开空间的操作是在calloc,它的具体实现在libmalloc中,它开辟了内存空间,并且返回了一个指向该内存地址的指针。

4.3 initInstanceIsa 将类和isa指针关联

上面的instanceSizecalloc完成了空间的计算和开辟,接下来执行来到

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

zone是nil,fast是是否可以创建Nonpointer的返回。会来到方法initInstanceIsa

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

主要调用方法initIsa

  • initIsa
inline void

objc_object::initIsa(Class cls, bool nonpointer, UNUSED_WITHOUT_INDEXED_ISA_AND_DTOR_BIT bool hasCxxDtor)
{ 
    isa_t newisa(0);
    // nonpointer:ture
    if (!nonpointer) {
        newisa.setClass(cls, this);
    } else {
        newisa.bits = ISA_MAGIC_VALUE;
        newisa.setClass(cls, **this**);
        newisa.extra_rc = 1;
    }
    isa() = newisa;
}

从方法initInstanceIsa传进来的第二个参数nonpointerture,所以走流程 else

SUPPORT_INDEXED_ISA不同的架构下处理不同。64位下的直接走else的部分。走setClass。该方法关键代码:

inline void
isa_t::setClass(Class newCls, UNUSED_WITHOUT_PTRAUTH objc_object *obj)
{
    shiftcls = (uintptr_t)newCls >> 3;
}

该方法其实就是初始化一个isa_t然后绑定指向给cls。至于右移3位,因为是八字节对齐,指针后三位是无用的0,0与上任何都是0,估计是为了省内存减少消耗吧。

5. alloc的流程图

133b10bdbb4a4a3e8b08b68f5f4b6467~tplv-k3u1fbpfcp-zoom-in-crop-mark-3024-0-0-0.image.png

6. init 和 new

看过了上面alloc的流程,也简单看一下我们常用的init还有new。

6.1 init

进行断点调试,我们找到方法_objc_rootInit

image.png

它的实现:

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

嗯,传进来啥,返回啥😂。

6.2 new

同样的,new的实际实现方法是objc_opt_new。它的实现:

id
objc_opt_new(Class cls)
{

    if (fastpath(cls && !cls->ISA()->hasCustomCore())) {
        return [callAlloc(cls, false/checkNil/) init];
    }
    return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(new));
}

关键代码是[callAlloc(cls, false/checkNil/) init],实际上也是调用的 [alloc init]

7.总结

alloc的主要流程:

  1. 类没有被加载进来时,也就是没有实现allocWithZone方法时,那么再发送一遍alloc消息,直到已经allocWithZone了,确保已经被加载进来。
  2. 通过instanceSize计算需要的空间。
  3. calloc开辟实际的空间。
  4. initInstanceIsa将class与isa进行关联。
  • init 本质返回传入的self对象
  • new 等价于alloc+init

关于(uintptr_t)newCls >> 3,到底为啥还是有点模糊,只是猜测是节约内存,后面有新的发现再补充~

相关文章

网友评论

      本文标题:1.二刷之探索alloc

      本文链接:https://www.haomeiwen.com/subject/vtticdtx.html