美文网首页iOS学习
iOS-底层原理14-类的加载中

iOS-底层原理14-类的加载中

作者: 一亩三分甜 | 来源:发表于2020-12-10 00:25 被阅读0次

    《iOS底层原理文章汇总》

    上一篇文章《iOS-底层原理13-类的加载上》介绍了类从MachO文件中读取到内存中并和类名进行绑定,并添加到已知类的表中,也就是类转化为名字,但是并没有给ro,rw,rwe中写入数据。
    read_images->readClass:地址->name insert MAP
    dyld->dylib-objc-init
    LGPerson->属性 方法......->编译 - macho -> 内存(表)

    MachO文件中能读到data()的数据格式,怎么读取到ro,rw,rwe中呢?

    1.程序进入realizeClassWithoutSwift方法,alloc和init方法执行是在本类存在,且完备后,按照此模子初始化实例出来,在realizeClassWithoutSwift没有执行完之前,模子都不存在,无法进行初始化和实例化,此方法中读取了data(),存放到临时变量ro中,再copy一份赋值给rw,那么rwe什么时候赋值的呢?继续往后探索。

    static Class realizeClassWithoutSwift(Class cls, Class previously)
    {
        runtimeLock.assertLocked();
        class_rw_t *rw;
        Class supercls;
        Class metacls;
        if (!cls) return nil;
        if (cls->isRealized()) return cls;
        // fixme verify class is not in an un-dlopened part of the shared cache?
        auto ro = (const class_ro_t *)cls->data();
        auto isMeta = ro->flags & RO_META;
        if (ro->flags & RO_FUTURE) {
            // This was a future class. rw data is already allocated.
            rw = cls->data();
            ro = cls->data()->ro();
            ASSERT(!isMeta);
            cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
        } else {
            // Normal class. Allocate writeable class data.
            rw = objc::zalloc<class_rw_t>();
            rw->set_ro(ro);
            rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
            cls->setData(rw);
        } 
        supercls = realizeClassWithoutSwift(remapClass(cls->superclass), nil);
        metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);   
        // Connect this class to its superclass's subclass lists
        if (supercls) {
            addSubclass(supercls, cls);
        } else {
            addRootClass(cls);
        }
        // Attach categories
        methodizeClass(cls, previously);
        return cls;
    }
    

    readonly 干净的内存地址,因为有运行时runtime的存在,要不断的往类中添加和删除属性,方法,协议,categories,对readonly的操作会比较严重,为了防止对原始数据的修改

    将原来干净的内存从readonly中copy了一份到rw中,但并不是每一个类都会进行动态的插入,几万个几十万个类可能就只有几个或几十个类进行动态操作,只要你动态处理了,才生成相应的rwe,一般情况下的rw是从ro里面读取的,如果有运行时,则从rwe中读取,取值的逻辑是判断有没有运行时

        const class_ro_t *ro() const {
            auto v = get_ro_or_rwe();
            if (slowpath(v.is<class_rw_ext_t *>())) {
                return v.get<class_rw_ext_t *>()->ro;
            }
            return v.get<const class_ro_t *>();
        }
    

    rwe就是所谓的“脏内存”的概念

    2.类的信息处理->父类->元类,LGPerson的继承链进行递归supercls = realizeClassWithoutSwift(remapClass(cls->superclass), nil)metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil)

    子类父类元类递归.png

    3.realizeClassWithoutSwift方法中尽管看到了data()的读取,强制赋值到临时变量ro,copy一份到了类的rw里面,程序继续往下进入methodizeClass()方法,方法化当前类,在lookupImpForward方法中进行二分查找的时候,methodList是排过序的,是在什么时候排序的呢?

    methodizeClass.png
    static Class realizeClassWithoutSwift(Class cls, Class previously)
    {
        runtimeLock.assertLocked();
    
        class_rw_t *rw;
        Class supercls;
        Class metacls;
    
        if (!cls) return nil;
        if (cls->isRealized()) return cls;
        ASSERT(cls == remapClass(cls));
        auto ro = (const class_ro_t *)cls->data();
        auto isMeta = ro->flags & RO_META;
        if (ro->flags & RO_FUTURE) {
            // This was a future class. rw data is already allocated.
            rw = cls->data();
            ro = cls->data()->ro();
            ASSERT(!isMeta);
            cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
        } else {
            // Normal class. Allocate writeable class data.
            rw = objc::zalloc<class_rw_t>();
            rw->set_ro(ro);
            rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
            cls->setData(rw);
        }
        supercls = realizeClassWithoutSwift(remapClass(cls->superclass), nil);
        metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);
    
        // Attach categories
        methodizeClass(cls, previously);
        return cls;
    }
    
    • 通过lldb读取ro中的方法:得知当前ro中存储了8个方法,程序继续往下执行,
      methodizeClass->prepareMethodLists->fixupMethodList->std::stable_sort(mlist->begin(), mlist->end(), sorter),排序通过Sort by selector address,


      ro@2x.png
    static void methodizeClass(Class cls, Class previously){
        // Install methods and properties that the class implements itself.
        method_list_t *list = ro->baseMethods();
        if (list) {
            prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls));
            if (rwe) rwe->methods.attachLists(&list, 1);
        }
    }
        
    static void 
    prepareMethodLists(Class cls, method_list_t **addedLists, int addedCount,
                       bool baseMethods, bool methodsFromBundle)
    {
        // Add method lists to array.
        // Reallocate un-fixed method lists.
        // The new methods are PREPENDED to the method list array.
        for (int i = 0; i < addedCount; i++) {
            method_list_t *mlist = addedLists[i];
            ASSERT(mlist);
    
            // Fixup selectors if necessary
            if (!mlist->isFixedUp()) {
                fixupMethodList(mlist, methodsFromBundle, true/*sort*/);
            }
    }
    
    static void 
    fixupMethodList(method_list_t *mlist, bool bundleCopy, bool sort)
    {
        runtimeLock.assertLocked();
        ASSERT(!mlist->isFixedUp());
    
        // fixme lock less in attachMethodLists ?
        // dyld3 may have already uniqued, but not sorted, the list
        if (!mlist->isUniqued()) {
            mutex_locker_t lock(selLock);
        
            // Unique selectors in list.
            for (auto& meth : *mlist) {
                const char *name = sel_cname(meth.name);
                meth.name = sel_registerNameNoLock(name, bundleCopy);
            }
        }
    
        // Sort by selector address.
        if (sort) {
            method_t::SortBySELAddress sorter;
            std::stable_sort(mlist->begin(), mlist->end(), sorter);
        }
        
        // Mark method list as uniqued and sorted
        mlist->setFixedUp();
    }
    
    • 我们将LGPerson类中的方法进行顺序错乱,查看经过排序方法后,排序是否生效


      LGPerson中kc_instanceMethod2方法在前@2x.png
      LGPerson实现类@2x.png
    • 在fixupMethodList方法之前ro中的方法顺序,排序为什么没有生效?实质上排序已经生效了,并不是根据我们以为的方法名字的字符串顺序排序,而是根据selector的地址进行排序,详情在下一篇文章中进行分析。


      fixupMethodList方法之前@2x.png
    • 在fixupMethodList方法之后ro中的方法顺序


      fixupMethodList方法之后ro中方法排序@2x.png
    • 方法进行排序后,if (rwe) rwe->methods.attachLists(&list, 1)将list复制到rwe中,但此时发现rwe为NULL,则方法并没有被拷贝进rwe中,data()->rw->ro->rwe(没有走),为何没有走?
      rwe为NULL@2x.png

    3.前面read_images中,是怎么进入realizeClassWithoutSwift(cls, nil);方法的呢?下面有一句话说明了原因Realize non-lazy classes (for +load methods and static instances),非懒加载类和静态实例才会进入下面的realizeClassWithoutSwift方法

    懒加载类:懒,别人不动我不动
    非懒加载类:实现+(void)load方法,让它提前加载了,load方法在load_images时候就会直接调用,若非懒加载类(实现了load方法的类)没有提前加载,则在load_images中调用所有类的load方法的时候如何调用???所以非懒加载类实现了load方法,让它提前加载,进入realizeClassWithoutSwift方法
    给LGPerson实现+(void)load方法,则会在main函数之前进入到realizeClassWithoutSwift中进行类的加载


    非懒加载类进入realizeClassWithoutSwift方法@2x.png 非懒加载类的加载@2x.png

    4.懒加载:只有在第一次调用了这个类中的方法(第一次进行消息发送)的时候才会去实现这个类,从而调用realizeClassWithoutSwift方法,那为什么要懒加载呢?实现这个类的加载的时候有很多的代码,排序,临时变量,如果把所有的类都推迟到main函数启动之前,整个main函数的启动就会非常非常的慢,也有可能实现写进的这个类,从来都没有被调用过,造成内存资源的浪费,还有必要去耗费内存嘛?这也是为什么+(void)load方法尽量不要随便写的原因了。苹果默认是懒加载类,给了开发人员更多自由。

    懒加载消息发送@2x.png alloc消息发送进行加载@2x.png
    (lldb) bt
    * thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 3.1
      * frame #0: 0x000000010013dc03 libobjc.A.dylib`realizeClassWithoutSwift(cls=0x0000000100002240, previously=0x0000000000000000) at objc-runtime-new.mm:2486:17
        frame #1: 0x000000010015a460 libobjc.A.dylib`realizeClassMaybeSwiftMaybeRelock(cls=0x0000000100002240, lock=0x0000000100196000, leaveLocked=true) at objc-runtime-new.mm:2759:9
        frame #2: 0x0000000100145db2 libobjc.A.dylib`realizeClassMaybeSwiftAndLeaveLocked(cls=0x0000000100002240, lock=0x0000000100196000) at objc-runtime-new.mm:2782:12
        frame #3: 0x0000000100145adb libobjc.A.dylib`lookUpImpOrForward(inst=0x0000000100002268, sel="alloc", cls=0x0000000100002240, behavior=3) at objc-runtime-new.mm:6141:15
        frame #4: 0x0000000100121159 libobjc.A.dylib`_objc_msgSend_uncached at objc-msg-x86_64.s:1101
        frame #5: 0x000000010017c1e5 libobjc.A.dylib`objc_alloc [inlined] callAlloc(cls=LGPerson, checkNil=true, allocWithZone=false) at NSObject.mm:1714:12
        frame #6: 0x000000010017c13e libobjc.A.dylib`objc_alloc(cls=LGPerson) at NSObject.mm:1730
        frame #7: 0x0000000100000bcb KCObjc`main(argc=1, argv=0x00007ffeefbff4c8) at main.m:14:28 [opt]
        frame #8: 0x00007fff69395cc9 libdyld.dylib`start + 1
        frame #9: 0x00007fff69395cc9 libdyld.dylib`start + 1
    
    懒加载和非懒加载类@2x.png

    5.分类的本质:结构体_category_t

    通过clang查看分类的源码clang -rewrite-objc main.m -o main.cpp_category_t中成员如下,分类中的属性没有通过runtime添加,不会生成setter和getter方法

    struct _category_t {
        const char *name;
        struct _class_t *cls;
        const struct _method_list_t *instance_methods;
        const struct _method_list_t *class_methods;
        const struct _protocol_list_t *protocols;
        const struct _prop_list_t *properties;
    }; 
    
    分类@2x.png
    category_t@2x.png

    分类中的方法

    static struct /*_method_list_t*/ {
        unsigned int entsize;  // sizeof(struct _objc_method)
        unsigned int method_count;
        struct _objc_method method_list[3];
    } _OBJC_$_CATEGORY_INSTANCE_METHODS_LGPerson_$_LG __attribute__ ((used, section ("__DATA,__objc_const"))) = {
        sizeof(_objc_method),
        3,
        {{(struct objc_selector *)"cate_instancedMethod1", "v16@0:8", (void *)_I_LGPerson_LG_cate_instancedMethod1},
        {(struct objc_selector *)"cate_instancedMethod3", "v16@0:8", (void *)_I_LGPerson_LG_cate_instancedMethod3},
        {(struct objc_selector *)"cate_instancedMethod2", "v16@0:8", (void *)_I_LGPerson_LG_cate_instancedMethod2}}
    };
    

    分类中的属性

    static struct /*_prop_list_t*/ {
        unsigned int entsize;  // sizeof(struct _prop_t)
        unsigned int count_of_properties;
        struct _prop_t prop_list[2];
    } _OBJC_$_PROP_LIST_LGPerson_$_LG __attribute__ ((used, section ("__DATA,__objc_const"))) = {
        sizeof(_prop_t),
        2,
        {{"cate_name","T@\"NSString\",C,N"},
        {"cate_age","Ti,N"}}
    };
    

    对分类的本质了解,之后,那分类中的方法是怎么加载到类里面的呢?

    6.realizeClassWithoutSwift方法之后进入methodizeClass(cls, previously)添加分类,先对类中的方法进行排序,从而进入objc::unattachedCategories.attachToClass方法中

    methodizeClass中对方法进行排序@2x.png 添加分类中的方法到类中@2x.png
    unattachedCategories@2x.png

    objc::unattachedCategories.attachToClass的初始化在runtime_init()方法中

    7.objc::unattachedCategories.attachToClass方法主要做了什么?

    添加方法到类中,若同时存在对象方法和类方法,则添加两次,若只存在对象方法,则只添加一次,进入到attachCategories方法中,将类中的方法先排序,后以数组中的第64个从后往前插入


    attachToClass@2x.png
    attachCategories@2x.png
    void attachToClass(Class cls, Class previously, int flags)
        {        
            const char *mangledName  = cls->mangledName();
            const char *LGPersonName = "LGPerson";
    
            if (strcmp(mangledName, LGPersonName) == 0) {
                bool kc_isMeta = cls->isMetaClass();
                auto kc_rw = cls->data();
                auto kc_ro = kc_rw->ro();
                if (!kc_isMeta) {
                    printf("%s: 这个是我要研究的 %s \n",__func__,LGPersonName);
                }
            }
            auto &map = get();
            auto it = map.find(previously);
            if (it != map.end()) {
                category_list &list = it->second;
                if (flags & ATTACH_CLASS_AND_METACLASS) {
                    int otherFlags = flags & ~ATTACH_CLASS_AND_METACLASS;
                    attachCategories(cls, list.array(), list.count(), otherFlags | ATTACH_CLASS);
                    attachCategories(cls->ISA(), list.array(), list.count(), otherFlags | ATTACH_METACLASS);
                } else {
                    attachCategories(cls, list.array(), list.count(), flags);
                }
                map.erase(it);
            }
        }
    

    8.在objc源码中全局搜索extAllocIfNeeded方法的调用,发现rwe只有在分类、+addMethod、+addProperty、+addProtocol进行添加的时候才会初始化,上面对类中的方法进行添加的时候,先要对rwe进行初始化

    rwe初始化@2x.png
    rwe@2x.png

    9:第一步:什么时机加载分类中的方法,未知;第二步:加载什么样的数据格式,知道;第三步:怎么加载数据到类中的,未知请看下一篇博客

    相关文章

      网友评论

        本文标题:iOS-底层原理14-类的加载中

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