isa 底层结构分析

2020-09-11  本文已影响0人  远方竹叶

OC 对象的本质

在我们日常的开发中,会创建很多个自定义的对象,大部分是继承自 NSObject,但是具体到源码实现,就看不到了,怎么办呢?编译器 clang 就要登场了

Clang

探索

在 main 函数中创建一个 LCPerson 类,添加 name 属性

@interface LCPerson : NSObject
@property (nonatomic, copy) NSString *name;
@end

@implementation LCPerson
@end
//1、将 main.m 编译成 main.cpp
clang -rewrite-objc main.m -o main.cpp

//2、将 ViewController.m 编译成  ViewController.cpp(注意模拟器的路径)
clang -rewrite-objc -fobjc-arc -fobjc-runtime=ios-13.0.0 -isysroot / /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.7.sdk ViewController.m

//以下两种方式是通过指定架构模式的命令行,使用xcode工具 xcrun
//3、模拟器文件编译
- xcrun -sdk iphonesimulator clang -arch arm64 -rewrite-objc main.m -o main-arm64.cpp 

//4、真机文件编译
- xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m -o main- arm64.cpp 
struct LCPerson_IMPL {
    struct NSObject_IMPL NSObject_IVARS;
    NSString *_name;
};

再来看下 NSObject 的定义以及底层编译

//NSObject的定义
@interface NSObject <NSObject> {
    Class isa  OBJC_ISA_AVAILABILITY;
}

//NSObject 的底层编译
struct NSObject_IMPL {
    Class isa;
};

通过以上源码可以得出,OC 对象的本质就是结构体

cls 与 类的关联

alloc 源码分析 & init & new中分析了 alloc 中核心三步的前两个,下面来探索initInstanceIsa是如何将clsisa关联的

联合体

构造数据类型的方式有两种:结构体(struct)和 联合体(union)

所有变量是共存的,不管用不用,都会分配内存。优点是容量大,包容性强;缺点是 struct 内存空间的分配是粗放的,所有属性都会分配内存,容易造成内存浪费

各变量是“互斥”的,所有的成员共占一段内存。同一时刻只能保存一个成员的值,如果对新的成员赋值,就会将原来成员的值覆盖掉。优点是内存的使用更为精细灵活,节省内存空间,缺点是包容性弱

isa 的类型

源码中查看 isa_t 的定义,可以看出是通过联合体(union)定义的

union isa_t { //联合体
    isa_t() { }
    isa_t(uintptr_t value) : bits(value) { }
    //提供了cls 和 bits ,两者是互斥关系
    Class cls;
    uintptr_t bits;
#if defined(ISA_BITFIELD)
    struct {
        ISA_BITFIELD;  // defined in isa.h
    };
#endif
};

isa_t 的定义源码可以看出

# 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__ //模拟器/Mac os
#   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)

isa_t 使用联合体的原因也是基于 内存优化 的考虑,这里的内存优化是指在isa 指针中通过 char + 位域的原理实现。isa 占用 8 字节,即 64 位,已经足够存储很多的信息了,这样可以极大的节省内存,提高性能

原理探索

下面进入 initInstanceIsa 的探索,首先查看它的源码实现

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

    initIsa(cls, true, hasCxxDtor);
}

initInstanceIsa 的源码实现中,主要是调用了 initIsa,继续跳到 initIsa 的源码

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

源码主要是初始化 isa,两种方式

验证

方式一:通过 isa & ISA_MASK
方式二:通过位运算

shiftcls 的位置在中间 44 位,需要通过位运算才能获取到类信息,即将高位的 17 位与低位的 3 位全部抹零处理

上一篇 下一篇

猜你喜欢

热点阅读