对象本质和ISA指针

2020-10-20  本文已影响0人  spades_K

1.什么是对象?

@interface NSObject <NSObject> {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
    Class isa  OBJC_ISA_AVAILABILITY;
#pragma clang diagnostic pop
}

这是NSObject的声明,里面只有一个Class类型的isa变量,声明一个继承NSObject的类LGPerson

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

clang编译文件:在main.m文件目录下输入clang -rewrite-objc main.m -o main.cpp会得到main.cpp文件。

//NSObject编译后
struct NSObject_IMPL {
    Class isa;
};

//LGPerson编译后
#ifndef _REWRITER_typedef_LGPerson
#define _REWRITER_typedef_LGPerson
typedef struct objc_object LGPerson;
typedef struct {} _objc_exc_LGPerson;
#endif

extern "C" unsigned long OBJC_IVAR_$_LGPerson$_name;
struct LGPerson_IMPL {
    struct NSObject_IMPL NSObject_IVARS;
    NSString *_name;
};

// @property (nonatomic, copy) NSString *name;
/* @end */


// @implementation LGPerson
// name get方法
static NSString * _I_LGPerson_name(LGPerson * self, SEL _cmd) { return (*(NSString **)((char *)self + OBJC_IVAR_$_LGPerson$_name)); }
extern "C" __declspec(dllimport) void objc_setProperty (id, SEL, long, id, bool, bool);
// name set方法
static void _I_LGPerson_setName_(LGPerson * self, SEL _cmd, NSString *name) { objc_setProperty (self, _cmd, __OFFSETOFIVAR__(struct LGPerson, _name), (id)name, 0, 1); }
// @end

NSObject声明可知 struct NSObject_IMPL NSObject_IVARS 其实就是 isa,声明中的isa为什么为class类型?我们去objc4-781源码中找答案,alloc方法核心方法initInstanceIsa方法中initIsa方法创建isa_t类型初始化。
isa指针返回的是类的相关信息,所以使用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
}

clang编译补充: 如果直接编译ViewController.m等有依赖的库的文件会报错,可以用以下方法编译得到cpp文件。
xcode安装的时候顺带安装了xcrun命令,xcrun命令在clang的基础上进行了 一些封装,要更好用一些

//指定模拟器
$ xcrun -sdk iphonesimulator clang -rewrite-objc ViewController.m
// 指定真机
$ xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc ViewController.m

总结:对象本质其实就是结构体,都会包含从NSObject里面继承Class类型的isa变量用作储存相关的类信息。

2.ISA指针

ISA指针是isa_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
};

union---联合体联合体中各个变量是互斥的,缺点是不够包容,优点是内存使用更加精细灵活,也节省内存空间。
struct---结构体,所有变量是共存的,缺点是内存空间的分配是粗放的,用不用,全分配,优点是有容乃大,全面。

isa_t为联合体,clsbits为互斥,ISA_BITFIELD 是一个宏定义,是一个位域,定义如下:

# 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_BITFIELD分别在arm64x86_64架构上定义一样,只是占用的位数不一样。

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_rc9。如果引用计数大于 10, 则需要使用到下面的has_sidetable_rc

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

验证

isa64情况

因为跑的是MAC程序,所以isax86_64结构,通过二进制左右移动方式取出shiftcls中值。左右移动的位置把上图倒过来看比较形象。

终端打印下

(lldb) po objc1
<LGPerson: 0x101335e80>

(lldb) x/4gx 0x101335e80
0x101335e80: 0x001d800100002255 0x0000000000000000
0x101335e90: 0x0000000000000000 0x0000000000000000
(lldb) p/t 0x001d800100002255  
(long) $1 = 0b0000000000011101100000000000000100000000000000000010001001010101
(lldb) p/t $1 >> 3
(long) $2 = 0b0000000000000011101100000000000000100000000000000000010001001010
(lldb) p/t $2 << 3
(long) $3 = 0b0000000000011101100000000000000100000000000000000010001001010000
(lldb) p/t $3 << 17
(long) $4 = 0b0000000000000010000000000000000001000100101000000000000000000000
(lldb) p/t $4 >> 17
(long) $5 = 0b0000000000000000000000000000000100000000000000000010001001010000
(lldb) po $5
LGPerson

我们用ISA_MASK 0x00007ffffffffff8ULL来验证下。

验证结果

其实 & ISA_MASK是二进制的另一种算法实现的效果一样,&运算,两个二进制都是1才能为1,存在0位则会为0

二进制表示
上一篇 下一篇

猜你喜欢

热点阅读