美文网首页iOS学习
iOS-底层原理03-isa

iOS-底层原理03-isa

作者: 一亩三分甜 | 来源:发表于2020-10-03 21:29 被阅读0次

    《iOS底层原理文章汇总》

    对象中如果包含float或double类型的属性的读取方式

    double类型无法po@2x.png
    @interface DCPerson : NSObject
    @property(nonatomic,copy)NSString *name;
    @property(nonatomic,copy)NSString *nickName;
    @property(nonatomic,copy)NSString *hobby;
    @property(nonatomic,assign)int age;
    @property(nonatomic,assign)float height;
    @property(nonatomic,assign)char c1;
    @property(nonatomic,assign)char c2;
    @end
    
    (lldb) po p1
    <DCPerson: 0x100674390>
    
    (lldb) x/8gx 0x100674390
    0x100674390: 0x001d800100003545 0x0000001200006261
    0x1006743a0: 0x0000000043340000 0x0000000100002018
    0x1006743b0: 0x0000000100002038 0x0000000100002058
    0x1006743c0: 0x0000000000000000 0x0000000000000000
    (lldb) po 0x001d800100003545
    8303516107945285
    
    (lldb) p 0x001d800100003545
    (long) $2 = 8303516107945285
    (lldb) po 0x0000001200006261
    14305649625132105900
    
    (lldb) po 0x0000000043340000
    1127481344
    
    (lldb) po 0x0000000100002018
    Cloud
    
    (lldb) po 0x0000000100002018
    Cloud
    
    (lldb) po 0x0000000100002058
    女
    
    (lldb) po 0x0000000100002038
    fish
    
    (lldb) x/f (float)1180
    error: memory read failed for 0x400
    (lldb) p/x (float)180
    (float) $10 = 0x43340000
    (lldb) p/x (double)180
    (double) $11 = 0x4066800000000000
    (lldb)
    

    通过代码转换类型

    void lg_float2HEX(float f){
        union uuf{float f;char s[4];} uf;
        uf.f = f;
        printf("0x");
        for (int i=3; i>=0; i--) {
            printf("%02x",0xff & uf.s[i]);
        }
        printf("\n");
    }
    void lg_double2HEX(double d){
        union uud {double d; char s[8];} ud;
        ud.d = d;
        printf("0x");
        for (int i = 7; i>=0; i--) {
            printf("%02x",0xff & ud.s[i]);
        }
        printf("\n");
    }
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            lg_float2HEX(190.5);
            lg_double2HEX(180.5);
            DCPerson *p1 = [DCPerson alloc];
            p1.name = @"Cloud";
            p1.nickName = @"fish";
            p1.hobby = @"女";
            p1.age = 18;
            p1.height = 190.5;
            p1.measurements = 180.5;
            p1.c1 = 'a';
            p1.c2 = 'b';
            DCNSLog(@"%@ - %p - %p",p1,p1,&p1);
        
        }
        
    //输出   
    0x433e8000
    0x4066900000000000
    DCPerson was compiled with optimization - stepping may behave oddly; variables may not be available.
    (lldb) po p1
    <DCPerson: 0x101020fe0>
    
    (lldb) x/8gx 0x101020fe0
    0x101020fe0: 0x001d8001000035b5 0x0000001200006261
    0x101020ff0: 0x00000000433e8000 0x0000000100002018
    0x101021000: 0x0000000100002038 0x0000000100002058
    0x101021010: 0x4066900000000000 0x0000000000000000
    
    float和double类型转十六进制@2x.png

    对象的本质

    Clang是一个由Apple主导编写,基于LLVM的C/C++/Objective-C编译器,clang -rewrite-objc main.m -o main.cpp 把目标文件编译成c++文件

    clang编译@2x.png
    clang得到cpp文件@2x.png
    QQ20201002-193323@2x.png

    加上name属性之后重新编译得到:对象的本质是结构体

    #ifndef _REWRITER_typedef_DCPerson
    #define _REWRITER_typedef_DCPerson
    typedef struct objc_object DCPerson;
    typedef struct {} _objc_exc_DCPerson;
    #endif
    
    extern "C" unsigned long OBJC_IVAR_$_DCPerson$_name;
    struct DCPerson_IMPL {
        struct NSObject_IMPL NSObject_IVARS;//isa
        NSString *_name;//成员变量
    };
    
    getter方法和setter方法
    static NSString * _I_DCPerson_name(DCPerson * self, SEL _cmd) { return (*(NSString **)((char *)self + OBJC_IVAR_$_DCPerson$_name)); }
    extern "C" __declspec(dllimport) void objc_setProperty (id, SEL, long, id, bool, bool);
    
    static void _I_DCPerson_setName_(DCPerson * self, SEL _cmd, NSString *name) { objc_setProperty (self, _cmd, __OFFSETOFIVAR__(struct DCPerson, _name), (id)name, 0, 1); }
    
    通用setter方法
    void objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy) 
    {
        bool copy = (shouldCopy && shouldCopy != MUTABLE_COPY);
        bool mutableCopy = (shouldCopy == MUTABLE_COPY);
        reallySetProperty(self, _cmd, newValue, offset, atomic, copy, mutableCopy);
    }
    
    对新值的retain,对旧值的release
    static inline void reallySetProperty(id self, SEL _cmd, id newValue, ptrdiff_t offset, bool atomic, bool copy, bool mutableCopy)
    {
        if (offset == 0) {
            object_setClass(self, newValue);
            return;
        }
    
        id oldValue;
        id *slot = (id*) ((char*)self + offset);
    
        if (copy) {
            newValue = [newValue copyWithZone:nil];
        } else if (mutableCopy) {
            newValue = [newValue mutableCopyWithZone:nil];
        } else {
            if (*slot == newValue) return;
            newValue = objc_retain(newValue);
        }
    
        if (!atomic) {
            oldValue = *slot;
            *slot = newValue;
        } else {
            spinlock_t& slotlock = PropertyLocks[slot];
            slotlock.lock();
            oldValue = *slot;
            *slot = newValue;        
            slotlock.unlock();
        }
    
        objc_release(oldValue);
    }
    

    联合体(共用体)位域

    结构体变量所占内存长度是各成员占的内存长度之和。每个成员分别占有其自己的内存单元。而共用体变量所占的内存长度等于最长的成员的长度。


    共用体.png

    这儿按照浮点数输出为什么是0.000000呢,浮点数的二进制存储方式如下:
    float和double在存储方式上都是遵从IEEE的规范的,float遵从的是IEEE R32.24 ,而double 遵从的是R64.53。

    无论是单精度还是双精度在存储中都分为三个部分:

    符号位(Sign) : 0代表正,1代表为负
    指数位(Exponent):用于存储科学计数法中的指数数据,并且采用移位存储
    尾数部分(Mantissa):尾数部分

    将一个float型转化为内存存储格式的步骤为:

     (1)先将这个实数的绝对值化为二进制格式。 
     (2)将这个二进制格式实数的小数点左移或右移n位,直到小数点移动到第一个有效数字的右边。 
     (3)从小数点右边第一位开始数出二十三位数字放入第22到第0位。 
     (4)如果实数是正的,则在第31位放入“0”,否则放入“1”。 
     (5)如果n 是左移得到的,说明指数是正的,第30位放入“1”。如果n是右移得到的或n=0,则第30位放入“0”。 
     (6)如果n是左移得到的,则将n减去1后化为二进制,并在左边加“0”补足七位,放入第29到第23位。
         如果n是右移得到的或n=0,则将n化为二进制后在左边加“0”补足七位,再各位求反,再放入第29到第23位。
    

    R32.24和R64.53的存储方式都是用科学计数法来存储数据的,比如8.25用十进制的科学计数法表示就为:8.2510^0,而120.5可以表示为:1.205102,计算机根本不认识十进制的数据,他只认识0,1,所以在计算机存储中,首先要将上面的数更改为二进制的科学计数法表示,8.25用二进制表示可表示为1000.01,120.5用二进制表示为:1111000.1用二进制的科学计数法表示1.1110001*26,1000.01可以表示为1.00012^3,任何一个数都的科学计数法表示都为1.xxx2^x,尾数部分就可以表示为xxxx,第一位都是1嘛,干嘛还要表示呀?可以将小数点前面的1省略,所以23bit的尾数部分,可以表示的精度却变成了24bit,道理就是在这里,那24bit能精确到小数点后几位呢,我们知道9的二进制表示为1001,所以4bit能精确十进制中的1位小数点,24bit就能使float能精确到小数点后6位,而对于指数部分,因为指数可正可负,8位的指数位能表示的指数范围就应该为:-127-128了,所以指数部分的存储采用移位存储,存储的数据为元数据+127,下面就看看8.25和120.5在内存中真正的存储方式。

    按照上面的存储方式,符号位为:0,表示为正,指数位为:3+127=130 ,位数部分为,故8.25的存储方式如下图所示:

    1006828-20161219191553385-1603336307.png

    而单精度浮点数120.5的存储方式如下图所示:这儿120.5的二进制表示应该是1.1110001*2^6


    1006828-20161219191633869-470721450.png

    将一个内存存储的float二进制格式转化为十进制的步骤:

     (1)将第22位到第0位的二进制数写出来,在最左边补一位“1”,得到二十四位有效数字。将小数点点在最左边那个“1”的右边。 
     (2)取出第29到第23位所表示的值n。当30位是“0”时将n各位求反。当30位是“1”时将n增1。 
     (3)将小数点左移n位(当30位是“0”时)或右移n位(当30位是“1”时),得到一个二进制表示的实数。 
     (4)将这个二进制实数化为十进制,并根据第31位是“0”还是“1”加上正号或负号即可。
    

    大部分自定义的类都为nonpoint_isa,8字节64位存满了信息

    # if __arm64__
    # define ISA_MASK 0x0000000ffffffff8ULL
    # define ISA_MAGIC_MASK 0x000003f000000001ULL
    # define ISA_MAGIC_VALUE 0x000001a000000001ULL
    # define ISA_BITFIELD
    : 1;
     uintptr_t nonpointer
    uintptr_t has_assoc
    uintptr_t has_cxx_dtor
    uintptr_t shiftcls : 33; 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)
    

    结构体(struct)中所有变量是“共存”的——优点是“有容乃大”, 全面;缺点是struct内存空间的分配是粗放的,不管用不用,全分配。

    联合体(union)中是各变量是“互斥”的——缺点就是不够“包容”; 但优点是内存使

    用更为精细灵活,也节省了内存空间

    nonpointer:表示是否对 isa 指针开启指针优化 0:纯isa指针,1:不止是类对象地址,isa 中包含了类信息、对象的引用计数等

    has_assoc:关联对象标志位,0没有,1存在

    has_cxx_dtor:该对象是否有 C++ 或者 Objc 的析构器,如果有析构函数,则需要做析构逻辑, 如果没有,则可以更快的释放对象

    magic:用于调试器判断当前对象是真的对象还是没有初始化的空间 weakly_referenced:志对象是否被指向或者曾经指向一个 ARC 的弱变量,
    没有弱引用的对象可以更快释放。

    deallocating:标志对象是否正在释放内存

    has_sidetable_rc:当对象引用技术大于 10 时,则需要借用该变量存储进位

    extra_rc:当表示该对象的引用计数值,实际上是引用计数值减 1, 例如,如果对象的引用计数为 10,那么 extra_rc 为 9。如果引用计数大于 10, 则需要使用到下面的 has_sidetable_rc。

    isa初始化

    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;
        }
    }
    
    (lldb) p newisa
    (isa_t) $1 = {
      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
      }
    }
    
    isa赋值@2x.png
    (lldb) p newisa
    (isa_t) $5 = {
      cls = DCPerson
      bits = 8303516107940113
       = {
        nonpointer = 1
        has_assoc = 0
        has_cxx_dtor = 0
        shiftcls = 536871970
        magic = 59
        weakly_referenced = 0
        deallocating = 0
        has_sidetable_rc = 0
        extra_rc = 0
      }
    }
    

    magic从第47位开始到第52位共6位,数字分别为111011,十进制位59

    # 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)
    
    7.gif

    isa指针和类关联起来

    shiftcls怎么关联isa(DCPerson),(uintptr_t)cls右移三位,newisa.shiftcls = (uintptr_t)cls >> 3;

    (lldb) po (uintptr_t)cls
    DCPerson
    
    (lldb) p (uintptr_t)cls
    (uintptr_t) $7 = 4294975760
    (lldb) p newisa
    (isa_t) $8 = {
      cls = DCPerson
      bits = 8303516107940113
       = {
        nonpointer = 1
        has_assoc = 0
        has_cxx_dtor = 0
        shiftcls = 536871970
        magic = 59
        weakly_referenced = 0
        deallocating = 0
        has_sidetable_rc = 0
        extra_rc = 0
      }
    }
    (lldb) p (uintptr_t)cls >> 3
    (uintptr_t) $9 = 536871970
    
    shiftcls@2x.png

    isa关联指针和当前类

    打印obj的对象,打印出isa指针

    (lldb) po obj
    <DCPerson: 0x10074ca50>
    
    (lldb) x/4gx 0x10074ca50
    0x10074ca50: 0x001d800100002111 0x0000000000000000
    0x10074ca60: 0x75736956534e5b2d 0x6369506261546c61
    (lldb) po 0x001d800100002111
    -1004303003905715
    
    (lldb) p 0x001d800100002111
    (long) $12 = 8303516107940113
    (lldb) p 0x001d800100002111 & 0x00007ffffffffff8ULL
    (unsigned long long) $13 = 4294975760
    (lldb) po 0x001d800100002111 & 0x00007ffffffffff8ULL
    DCPerson
    

    相当于通过object_getClass进去赋值

    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
    }
    
    (Class)(isa.bits & ISA_MASK);
    #   define ISA_MASK        0x00007ffffffffff8ULL
    

    isa关联类左移右移算法

    针对x86和64架构的Mac(若为arm64的真机架构中间为33位),中间的44位代表类信息,通过右移三位抹掉后三位,再左移20位抹掉前面17位,之后右移17位得到44位类信息的原来的值,和直接获取类DCPerson的内存地址的值一模一样。

    # 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)
    
    # 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)
    
    isa关联类左移右移的值@2x.png
    (lldb) x/4gx obj
    0x10074ca50: 0x001d800100002111 0x0000000000000000
    0x10074ca60: 0x75736956534e5b2d 0x6369506261546c61
    (lldb) p/x 0x001d800100002111 >> 3
    (long) $20 = 0x0003b00020000422
    (lldb) p/x 0x0003b00020000422 << 20
    (long) $21 = 0x0002000042200000
    (lldb) p/x 0x0002000042200000 >> 17
    (long) $22 = 0x0000000100002110
    (lldb) p/x cls
    (Class) $23 = 0x0000000100002110 DCPerson
    (lldb) 两个值相等
    

    相关文章

      网友评论

        本文标题:iOS-底层原理03-isa

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