ios isa的探索

作者: Jeffery_zc | 来源:发表于2020-12-08 09:35 被阅读0次

1. isa在alloc中的实现

alloc探索的过程中,我们在_class_createInstanceFromZone方法中,探索到,类在alloc过程中,通过initInstanceIsa或者initIsa方法,将我们开辟出来的空间的指针地址关联到当前的类。

具体实现代码如下:

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

    initIsa(cls, true, hasCxxDtor);
}
inline void 
objc_object::initIsa(Class cls)
{
    initIsa(cls, false, false);
}

inline void 
objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor) 
{ 
    ASSERT(!isTaggedPointer()); 
    
    if (!nonpointer) {
        isa = isa_t((uintptr_t)cls);
    } else {
        ASSERT(!DisableNonpointerIsa);
        ASSERT(!cls->instancesRequireRawIsa());

        isa_t newisa(0);

#if SUPPORT_INDEXED_ISA
        ASSERT(cls->classArrayIndex() > 0);
        newisa.bits = ISA_INDEX_MAGIC_VALUE;
        // isa.magic is part of ISA_MAGIC_VALUE
        // isa.nonpointer is part of ISA_MAGIC_VALUE
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.indexcls = (uintptr_t)cls->classArrayIndex();
#else
        newisa.bits = ISA_MAGIC_VALUE;
        // isa.magic is part of ISA_MAGIC_VALUE
        // isa.nonpointer is part of ISA_MAGIC_VALUE
        newisa.has_cxx_dtor = hasCxxDtor;
        newisa.shiftcls = (uintptr_t)cls >> 3;
#endif

        // This write must be performed in a single store in some cases
        // (for example when realizing a class because other threads
        // may simultaneously try to use the class).
        // fixme use atomics here to guarantee single-store and to
        // guarantee memory order w.r.t. the class index table
        // ...but not too atomic because we don't want to hurt instantiation
        isa = newisa;
    }
}

1.2 isa 结构

在上述initIsa(Class cls, bool nonpointer, bool hasCxxDtor)方法中,通过isa初始化时可以发现,isaisa_t类型,在源码中表现如下:

union isa_t {
    isa_t() { }
    isa_t(uintptr_t value) : bits(value) { }

    Class cls;
    uintptr_t bits;
#if defined(ISA_BITFIELD)
    struct {
        ISA_BITFIELD;  // defined in isa.h
    };
#endif
};

arm64和x86下 bits的结构

# if __arm64__
#   define ISA_MASK        0x0000000ffffffff8ULL
#   define ISA_MAGIC_MASK  0x000003f000000001ULL
#   define ISA_MAGIC_VALUE 0x000001a000000001ULL
#   define ISA_BITFIELD                                                      \
      uintptr_t nonpointer        : 1;                                       \
      uintptr_t has_assoc         : 1;                                       \
      uintptr_t has_cxx_dtor      : 1;                                       \
      uintptr_t shiftcls          : 33; /*MACH_VM_MAX_ADDRESS 0x1000000000*/ \
      uintptr_t magic             : 6;                                       \
      uintptr_t weakly_referenced : 1;                                       \
      uintptr_t deallocating      : 1;                                       \
      uintptr_t has_sidetable_rc  : 1;                                       \
      uintptr_t extra_rc          : 19
#   define RC_ONE   (1ULL<<45)
#   define RC_HALF  (1ULL<<18)

# elif __x86_64__
#   define ISA_MASK        0x00007ffffffffff8ULL
#   define ISA_MAGIC_MASK  0x001f800000000001ULL
#   define ISA_MAGIC_VALUE 0x001d800000000001ULL
#   define ISA_BITFIELD                                                        \
      uintptr_t nonpointer        : 1;                                         \
      uintptr_t has_assoc         : 1;                                         \
      uintptr_t has_cxx_dtor      : 1;                                         \
      uintptr_t shiftcls          : 44; /*MACH_VM_MAX_ADDRESS 0x7fffffe00000*/ \
      uintptr_t magic             : 6;                                         \
      uintptr_t weakly_referenced : 1;                                         \
      uintptr_t deallocating      : 1;                                         \
      uintptr_t has_sidetable_rc  : 1;                                         \
      uintptr_t extra_rc          : 8
#   define RC_ONE   (1ULL<<56)
#   define RC_HALF  (1ULL<<7)

//   上述右边表示标志位
# else
#   error unknown architecture for packed isa
# endif

由上可知,isa是联合体类型,这说明了clsbits在isa内存中是互斥的,在initIsa方法中可得出,当不存在nonpointer时,isa只是一个cls,当存在nonpointer时,isa将会存放更多类信息的值。这样做是为了节省了更多的内存空间。我们自定义大部分的类都是属于nonpointer_isa

nonpointer_isa结构:

nonpointer:表示是否对isa指针开启指针优化,0表示纯isa指针,1表示不止是类对象地址,isa还包含了类信息,引用计数等信息。
has_assoc:关联对象标志位,0表示没有,1表示存在。
has_cxx_dtor:该对象是否有C++或者Objc的析构器,如果有析构函数,则要做析构分析,如果没有,则可以更快的释放对象。
shiftcls:存储类指针的值。开启指针优化的情况下,在arm64架构中,有33位来存放类的指针。
magic:用于调试器判断当前对象是真的对象还是没有初始化的空间。
weakly_referenced:标志对象是否被指向或者曾经指向一个ARC的弱变量,没有弱引用的对象可以更快释放。
deallocating:标志对象是否正在释放内存。
has_sidetable_rc:标志对象是否存在散列表,当对象引用计数大于10时,则需要改变量存储进位。
extra_rc:表示该对象的引用计数值,实际上表示该对象引用计数减1。例如,如果对象的引用计数为 10,那么 extra_rc 为 9。如果引用计数大于 10, 则需要使用到下面的 has_sidetable_rc。

1.3 isa是如何关联到当前的类

此调试在objc-781源码中调试。
定义一个ZCPerson类,继承NSObject,然后在main函数中实现alloc方法。

#import <Foundation/Foundation.h>
#import "ZCPerson.h"

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

       ZCPerson *objc1 = [ZCPerson alloc];
   
    }
    return 0;
}

在alloc处先打上断点,然后运行源码程序,当程序停在断点,我们可以将源码的断点打开。这样的做法是为了保证我们的研究对象是ZCPerson

initIsa.png
当断点在第一处停下时,我们输出一下clsnonpointer,确保我们得到的是正确研究对象:
(lldb) po cls 
ZCPerson

(lldb) po nonpointer
true

通过输出,也说明了我们定义的ZCPerson类是nonpointer_isa,然后约过下一个断点,输出newisa:

(lldb) p newisa
(isa_t) $4 = {
  cls = nil
  bits = 0
   = {
    nonpointer = 0
    has_assoc = 0
    has_cxx_dtor = 0
    shiftcls = 0
    magic = 0
    weakly_referenced = 0
    deallocating = 0
    has_sidetable_rc = 0
    extra_rc = 0
  }
}
(lldb)

通过输出,可以看到newisa只是调用了isa_t的初始化方法,并没有做其他操作。然后开始给newisa的赋值。首先是给bits赋值,因为此时调试是Mac终端调试,所以是在x86的环境,此时bits值为ISA_MAGIC_VALUE(0x001d800000000001ULL),此时,再输出newisa,打印如下

(lldb) p newisa
(isa_t) $5 = {
  cls = 0x001d800000000001
  bits = 8303511812964353
   = {
    nonpointer = 1
    has_assoc = 0
    has_cxx_dtor = 0
    shiftcls = 0
    magic = 59
    weakly_referenced = 0
    deallocating = 0
    has_sidetable_rc = 0
    extra_rc = 0
  }
}
(lldb) 

此时,发现magic有值等于59。打开计算器:

0x001d800000000001.png
59.png
通过二进制数据发现,二者的值都为111011,说明了此时的59是magic从47位开始存储的值。
这也就说明了magic此时有值的原因。接着过断点得到shiftcls
我们知道,initIsa的过程,是将calloc的指针与当前的类关联,从nonpointer得知,类的信息都存储shiftcls中,在newisa.shiftcls = (uintptr_t)cls >> 3;这一步,将当前的cls通过类型强转,然后向右偏移3为的位运算,将得到的值存储在shiftcls中,输出得到最后的newisa:
(lldb) p newisa
(isa_t) $6 = {
  cls = ZCPerson
  bits = 8303516107940713
   = {
    nonpointer = 1
    has_assoc = 0
    has_cxx_dtor = 0
    shiftcls = 536872045
    magic = 59
    weakly_referenced = 0
    deallocating = 0
    has_sidetable_rc = 0
    extra_rc = 0
  }
}
(lldb) 

右移3位的原因:在nonpointer_isa中,shiftcls是从第3位开始存的,因此在赋值的时候需要右移三位,如果直接赋值的话,会把原来的3位给抹掉,导致初始化的时候会出问题。
然后我们点击下一步,回到_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);
    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);
}

这个时候,输出当前的obj:

(lldb) po obj
<ZCPerson: 0x102004100>

然后打印当前的内存情况:

x/4gx 0x102004100
0x102004100: 0x001d800100002369 0x0000000000000000
0x102004110: 0x0000000000000000 0x0000000000000000

打印isa:

p 0x001d800100002369
(long) $10 = 8303516107940713

我们知道,当前内存打印出来的第一个是类自带的isa属性,可是通过打印,我们发现是一串数值,说明此时的isa还需要进行一些处理。因为我们想要得到的类的信息,而类的信息是存储在shiftcls中,我们需要通过一些位运算,将isa里类信息取出来,也可以通过&mask(0x00007ffffffffff8ULL)得到isa

po 0x00007ffffffffff8ULL & 0x001d800100002369
ZCPerson

1.3 object_getClass源码解析

在runtime中,我们常常可以使用object_getClass()方法获取当前的类,通过源码我们可以找到isa的get方法:

Class object_getClass(id obj)
{
    if (obj) return obj->getIsa();
    else return Nil;
}
inline Class 
objc_object::getIsa() 
{
    if (fastpath(!isTaggedPointer())) return ISA();

    extern objc_class OBJC_CLASS_$___NSUnrecognizedTaggedPointer;
    uintptr_t slot, ptr = (uintptr_t)this;
    Class cls;

    slot = (ptr >> _OBJC_TAG_SLOT_SHIFT) & _OBJC_TAG_SLOT_MASK;
    cls = objc_tag_classes[slot];
    if (slowpath(cls == (Class)&OBJC_CLASS_$___NSUnrecognizedTaggedPointer)) {
        slot = (ptr >> _OBJC_TAG_EXT_SLOT_SHIFT) & _OBJC_TAG_EXT_SLOT_MASK;
        cls = objc_tag_ext_classes[slot];
    }
    return cls;
}
inline Class 
objc_object::ISA() 
{
    ASSERT(!isTaggedPointer()); 
#if SUPPORT_INDEXED_ISA
    if (isa.nonpointer) {
        uintptr_t slot = isa.indexcls;
        return classForIndex((unsigned)slot);
    }
    return (Class)isa.bits;
#else
    return (Class)(isa.bits & ISA_MASK);
#endif
}

看到源码最后,会发现isa.bits & ISA_MASK,正好是从这里取到了shiftcls,也证实了isa关联到了当前的类。

相关文章

  • iOS 探索isa

    一、OC对象的本质是什么? 可能有很多同学都知道答案,即对象的本质是结构体。但是怎么证明呢?今天我们就来一起验证下...

  • iOS底层探索004-类分析

    iOS底层探索-目录 1. 类的分析 主要分析两个部分:isa的走向和继承关系 isa分析 类的isa走向,参考这...

  • iOS底层-isa结构(isa_t)

    在iOS 底层-- isa指向探究中探索了isa的指向,那么isa的结构具体是什么样的。从源码中来着手研究。 一、...

  • ios isa的探索

    1. isa在alloc中的实现 在alloc探索[https://www.jianshu.com/p/08079...

  • iOS底层-类的探索分析之cache

    前言 前面两篇文章我们介绍了isa,继承链(iOS底层-类的探索分析之isa及继承链[https://www.ji...

  • 类的结构分析

    isa继续探索 在对象探索-初探isa文章中,简单探索了isa的构成,这篇文章主要将isa之间的关系及类的内存结构...

  • iOS底层探索之对象原理(三)

    前言 iOS底层探索之对象原理(二)我们了解到 isa是一个联合体位域,ISA_BITFIELD存储了类的一些信息...

  • iOS 底层探索:isa与类关联的原理

    iOS 底层探索: 学习大纲 OC篇[/p/9d73ee7aae64] 前言 这篇主要内容探索 类与isa是如何关...

  • iOS底层探索--isa位域

    我们知道isa在OC的底层随处可见,非常经典的一个图是isa的走位图,可查看这篇文章:iOS底层探索--OC对象的...

  • OC对象底层探索 — alloc创建对象

    用于记录iOS底层学习,以备后续回顾 OC对象底层探索alloc创建对象由字节对齐到对象内存大小探索isa的初始化...

网友评论

    本文标题:ios isa的探索

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