isa结构分析

作者: 深圳_你要的昵称 | 来源:发表于2020-09-11 16:39 被阅读0次

    背景

    书接上回alloc流程图分析中,在最后calloc分配空间,可得到空间的地址,那么calloc中系统是如何分配空间?如何将分配的空间与isa指针进行绑定?isa到底是个什么东东?带着这些疑问,下面将大致分析calloc的处理流程,以及所涉及到isa内部结构的分析。

    calloc大致流程

    先上源码

    static ALWAYS_INLINE id
    callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
    {
        if (slowpath(checkNil && !cls)) return nil;
    
    #if __OBJC2__
        if (fastpath(!cls->ISA()->hasCustomAWZ())) {
            // No alloc/allocWithZone implementation. Go straight to the allocator.
            // fixme store hasCustomAWZ in the non-meta class and 
            // add it to canAllocFast's summary
            if (fastpath(cls->canAllocFast())) {
                // No ctors, raw isa, etc. Go straight to the metal.
                bool dtor = cls->hasCxxDtor();
                id obj = (id)calloc(1, cls->bits.fastInstanceSize());
                if (slowpath(!obj)) return callBadAllocHandler(cls);
                obj->initInstanceIsa(cls, dtor);
                return obj;
            }
            else {
                // Has ctor or raw isa or something. Use the slower path.
                id obj = class_createInstance(cls, 0);
                if (slowpath(!obj)) return callBadAllocHandler(cls);
                return obj;
            }
        }
    #endif
    
        // No shortcuts available.
        if (allocWithZone) return [cls allocWithZone:nil];
        return [cls alloc];
    }
    

    大致流程如下:

    1. 首先判断cls->ISA()->hasCustomAWZ(),是否有默认的allocWithZone方法
    • cls->ISA()即获取当前class的isa指针
    • hasDefaultAWZ ()源码如下:
      bool hasDefaultAWZ() {
          return data()->flags & RW_HAS_DEFAULT_AWZ;
      }
      #define RW_HAS_DEFAULT_AWZ    (1<<16)
    

    RW_HAS_DEFAULT_AWZ标识当前class或者superclass是否有默认的alloc/mallocWithZone:,有则直接对class进行allocWithZone,申请内存空间。

     if (allocWithZone) return [cls allocWithZone:nil];
    
    1. 没有默认的allocWithZone方法,则cls->canAllocFast()再次判断当前的class是否支持快速alloc
    • 如果可以,直接调用calloc函数,申请一块bits.fastInstanceSize()大小的内存空间, 如果申请失败,也会调用callBadAllocHandler函数;如果申请成功,就会obj->initInstanceIsa(cls, dtor)初始化isa指针。
    bool dtor = cls->hasCxxDtor();
    bool hasCxxDtor() {
        return data()->flags & RW_HAS_CXX_DTOR;
    }
     
    // 是否实现了析构函数
    // class or superclass has .cxx_destruct implementation
    #define RW_HAS_CXX_DTOR       (1<<17)
    
    • 不能快速alloc的话,则调用class_createInstance(cls, 0)乖乖的去创建一个新的对象。

    这个流程后面再详细分析。

    1. obj->initInstanceIsa(cls, dtor)初始化isa指针
    inline void 
    objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
    {
        assert(!cls->instancesRequireRawIsa());
        assert(hasCxxDtor == cls->hasCxxDtor());
    
        initIsa(cls, true, hasCxxDtor);
    }
    

    调用initIsa(cls, true, hasCxxDtor)初始化isa指针,并与cls绑定。

    inline void 
    objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor) 
    { 
        assert(!isTaggedPointer()); 
        
        if (!nonpointer) {
            isa.cls = 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;
            newisa.has_cxx_dtor = hasCxxDtor;
            newisa.indexcls = (uintptr_t)cls->classArrayIndex();
    #else
            newisa.bits = ISA_MAGIC_VALUE;
            newisa.has_cxx_dtor = hasCxxDtor;
            newisa.shiftcls = (uintptr_t)cls >> 3;
    #endif
            isa = newisa;
        }
    }
    

    既然是初始化isa,那么紧跟isa,发现是将newisa赋值给isa,newisa是isa_t这个类型,下面详解isa_t这个结构类型。

    isa内部结构

    isa_t的内部结构如下。 当前只分析x86_64架构,其它架构同理。

    union isa_t 
    {
        isa_t() { }
        isa_t(uintptr_t value) : bits(value) { }
    
        Class cls;
        uintptr_t bits;
    
    #if SUPPORT_PACKED_ISA
    
    # if __arm64__
    #   define ISA_MASK        0x0000000ffffffff8ULL
    #   define ISA_MAGIC_MASK  0x000003f000000001ULL
    #   define ISA_MAGIC_VALUE 0x000001a000000001ULL
        struct {
            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
    
    // SUPPORT_PACKED_ISA
    #endif
    };
    

    分析:

    1. isa_t是一个联合体,即所有成员共用一个内存空间。

    2. 首先是2个构造函数 isa_t()默认构造函数和isa_t(uintptr_t value) 构造函数。

    3. 2个成员 Class clsuintptr_t bits,大家都知道,实例对象的isa指针指向类对象,类对象的isa指针指向元类对象,这就是Class cls为何存在的原因。uintptr_t其实就是unsigned long 类型,明显就是isa所占的空间大小。

    4. 结构体struct中所有成员所占的控件大小值加起来是64位,即8字节,正好印证了isa指针8字节的大小,这64位空间就固定分配给了struct中的各个成员。

    5. 再看结构体内部成员,分布图如下


      bits位域分布图.jpg
      • nonpointer表示是否对 isa 指针开启指针优化
      • has_assoc 是否有关联对象
      • has_cxx_dtor标记对象是否使用到的C++相关内容,在ARC环境下标记对象是否通过ARC来管理
      • shiftcls标记当前对象的类对象的指针地址
      • magic判断对象是否初始化完成, 是调试器判断当前对象是真的对象还是没有初始化的空间。
      • weakly_referenced标记对象是否有弱引用指针
      • deallocating标记对象是否正在进行dealloc操作
      • has_sidetable_rc标记是否有sitetable结构用于存储引用计数
      • extra_rc标记对象的引用计数(首先会存储在该字段中,当到达上限后,在存入对应的引用计数表中)
    6. isa_t内部结构分析得出,成员shiftcls中存放的是类对象Class的指针,这就印证了当前对象的isa指针关联的是其类对象

    验证isa与Class的关联

    示例.png
    1. x/4gx p16进制,每4段打印p指针地址
    2. p/t二进制打印第一段地址(即isa指针)的内存值
    3. p/t $1>>3 右移3位,代表抹零nonpointer has_assochas_cxx_dtor
    4. p/t $2<<17左移17位,代表抹零magic weakly_referenced deallocating
      extra_rc
    5. p/t $3>>17再右移17位,还原shiftcls的起始位置,此时剩余的地址只包含shiftcls
    6. p/t (uintptr_t)FXPerson.class >> 3 对类对象FXPerson右移3位,同第3步,后3位抹零,同第5步得到的地址作比较,抛开前17位,发现结果一模一样,证明shiftcls中存放的就是Class对象FXPerson。

    总结

    我们通过跟进calloc的流程,跟进obj->initInstanceIsa(cls, dtor)这一步,调用initIsa(cls, true, hasCxxDtor)初始化isa指针并与cls绑定时,发现在isa_t联合体的位域shiftcls中,存放就是类对象指针,最后通过示例,打印shiftcls的二进制值,印证了这一判断。

    相关文章

      网友评论

        本文标题:isa结构分析

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