美文网首页iOS开发技巧
OC底层原理03— isa探究

OC底层原理03— isa探究

作者: 夏天的枫_ | 来源:发表于2020-09-11 22:27 被阅读0次
    对象的本质

    在分析isa前,先分析一下我们常见的解除最多的——对象。为了探究OC对象的本质是什么,就有必要了解Clang

    Clang是⼀个C语⾔、C++、Objective-C语⾔的轻量级编译器。源代码发布于BSD协议下。Clang将⽀持其普通lambda表达式、返回类型的简化处理以及更好的处理constexpr关键字。Clang是⼀个由Apple主导编写,基于LLVM的C/C++/Objective-C编译器。

    • 利用Clang解析OC文件
      将OC代码通过Clang命令解析,就能探究OC对象低层是怎样的一个数据形式。用到的命令:clang -rewrite-objc main.m -o main.cpp,目的是将目标文件编译成C++的文件,这是基于OC文件的一种编译方式,如果要对UIKit框架下的UI文件比如ViewController.m
    // 模拟器sdk路径替换自己的即可
    clang -rewrite-objc -fobjc-arc -fobjc-runtime=ios-12.0.0 -isysroot /
    Applications/Xcode.app/Contents/Developer/Platforms/
    iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk ViewController.m
    

    xcode安装的时候顺带安装了xcrun命令,xcrun命令在clang的基础上进⾏了
    ⼀些封装,要更好⽤⼀些
    xcrun -sdk iphonesimulator clang -arch arm64 -rewrite-objc main.m -o main-arm64.cpp-- iPhoneSimulator
    xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m -o main�arm64.cpp -- iPhone
    通过搜索定义的对象名

    // 对象的本质——结构体
    struct Book_IMPL {
        struct NSObject_IMPL NSObject_IVARS;
        NSString *_name;
    };
    
    // @property (nonatomic, copy) NSString *bookName;
    /* @end */
    // @implementation Book
    
    static NSString * _I_Book_name(Book * self, SEL _cmd) { return (*(NSString **)((char *)self + OBJC_IVAR_$Book$_name)); }
    extern "C" __declspec(dllimport) void objc_setProperty (id, SEL, long, id, bool, bool);
    static void _I_Book_setName_(Book * self, SEL _cmd, NSString *name) {
        objc_setProperty (self, _cmd, __OFFSETOFIVAR__(struct Book, _name), (id)name, 0, 1);
    }
    // @end
    

    对象:对象的本质是结构体。

    isa的分析

    利用之前的objc781源码工程进行底层isa的分析:
    alloc -> _objc_rootAlloc -> callAlloc -> _objc_rootAllocWithZone -> _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 {
            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);
    }
    

    其中 initInstanceIsa, initIsa就发现isa踪迹;继续跟入:

    
    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, 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_t((uintptr_t)cls);这段代码是一个关键点,进入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
    };
    

    哦豁,ISA_BITFIELD; // defined in isa.h该来的它终究还是来了,终于看到了isa的定义文件,进入发现了下面的代码:

    // 针对iOS系统时的isa
    # 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)
    // 针对macOS系统时的isa
    # 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
    
    // SUPPORT_PACKED_ISA
    #endif
    

    这就是isa的结构,在iOS和macOS有这不同的字节占比,却有着相同的定义:
    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。
    通过以下图片可以更加形象的理解isa的结构:

    isa结构-网络图

    相关文章

      网友评论

        本文标题:OC底层原理03— isa探究

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