iOS类的加载原理(下)

前言

我们在iOS类的加载原理(上)我们介绍了类的加载原理的大致流程,由篇幅过长,上篇文章未介绍完,这篇文章继续展开类的加载原理分析。

rwe,rw,ro的介绍

我们在iOS类的加载原理(上)简单介绍了,rwe,rw,ro,那么为什么会这些呢?
clean memory是指加载后不会发生更改的内存,可以进行移除从而节省更多的内存空间

dirty memory是指在进程运行时会发生更改的内存,类结构一经使用就会变 成dirty memory,因为运行时会向它写入新的数据,比如:创建一个新的方法缓存并从类中指向它,它比clean memory要昂贵得多,只要进程在运行,它就必须一直存在,,因为如果你需要clean memory,系统可以从磁盘中重新加载,macOS可以选择唤出dirty memory,因为iOS不使用swap所以diry memory在iOS中代价很大,dirty memory是这个类数据被分成两部分的原因,可以保持清的数据越多越好,可以保持清洁的数据越多越好,通过分离那些永远不会更改的数据,可以把大部分的类数据存在clean memory

ro(class_ro_t)属于clean memory,因为它是只读的,从磁盘加载进来的(沙盒)

rw(class_rw_t)属于dirty memory, 当类第一次使用的时候运行时会为类分配额外的存储容量,这个运行时分配的存储容量是class_rw_t用于读取-编写数据,在这个数据结构中,存储了只在在运于时才会生成的新信息,比如:所有的类都会链接成一个树状结构,通过First Subclass和Next Sibling Class指针实现的,这允许运行时遍历当前使用的所有类,这对于使方法缓存无效非常有用,它的数据是从ro中复制过来的 drity memory是在手机端是非常昂贵的

rwe 当category加载,添加新的方法时,需要用到运行时,由ro只读,我们无法更改,就需要rw,就会占用相当多的内存,不可能所有的类都会需要动态修改,如果全部写到rw就会浪费很多内存,当我们需要rwe的时候,就会根据一个ext的标识创建,对rw做一些扩展,优化内存,像我们的方法,协议,属性会有变化的可能,所以存在rwe中,而类的父类信息,名字放在rw中。

指针强转到数据结构

在iOS类的加载原理(上)中我们介绍read_class中有cls->data()可以得到data的数据,那么data的数据从哪来,我们接着分析。
我们搜索realizeClassWithoutSwift找到相关实现,我们找到下面两行代码:

 auto ro = (const class_ro_t *)cls->data();
 auto isMeta = ro->flags & RO_META;

我们运行并断点调试一下,如图:


1

cls是一个地址,调用了data()就得到了ro这是为什么呢?我们接着往下看。
我们看下data这个函数的源码

 class_rw_t *data() const {
        return bits.data();
    }

是从bits里面拿到的data我们再看下bits,如下:

class_rw_t* data() const {
        return (class_rw_t *)(bits & FAST_DATA_MASK);
    }

这里bits& FAST_DATA_MASK这个值强转成了指向class_rw_t类型的指针,结构体指针可以取结构中的数据。

attachCategories反推思路

我们上面介绍了rwe,rw,ro那么 rwe是在什么时候有赋值的呢,我们继续分析。
methodizeClass这个函数中auto rwe = rw->ext();由这行代码控制rwe,经过查找extAllocIfNeeded由这个函数控制,iOS类的加载原理(上)里面有介绍extAllocIfNeeded这个函数的赋值的点在attachCategories,而它又在attachToClassload_categories_nolock有调用。
我们先在attachToClass打个断点,我们再找attachToClass的调用点,结果发现是在methodizeClass调用的,我们先看下里面调用的代码:

// Attach categories.
    if (previously) {
        if (isMeta) {
            objc::unattachedCategories.attachToClass(cls, previously,
                                                     ATTACH_METACLASS);
        } else {
            // When a class relocates, categories with class methods
            // may be registered on the class itself rather than on
            // the metaclass. Tell attachToClass to look for those.
            objc::unattachedCategories.attachToClass(cls, previously,
                                                     ATTACH_CLASS_AND_METACLASS);
        }
    }
    objc::unattachedCategories.attachToClass(cls, cls,
                                             isMeta ? ATTACH_METACLASS : ATTACH_CLASS);

attachToClass的调用是由previously控制的,我们发现previously是methodizeClass这个函数的形参,我们再次查找发现是在realizeClassWithoutSwift这里调用了methodizeClass并传入previously参数,realizeClassWithoutSwift的previously也是由形参传过来的,经过一系的分析,它是一个备用参数(nil),这里不会调用,
我们再看下张图:

2

只会调用1559的attachToClass
我们的推导过程顺序如下:
realizeClassWithoutSwift-> methodizeClass-> attachToClass-> attachCategories

attachList算法

我们看下** attachCategories**的代码,如下:

static void
attachCategories(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count,
                 int flags)
{
    if (slowpath(PrintReplacedMethods)) {
        printReplacements(cls, cats_list, cats_count);
    }
    if (slowpath(PrintConnecting)) {
        _objc_inform("CLASS: attaching %d categories to%s class '%s'%s",
                     cats_count, (flags & ATTACH_EXISTING) ? " existing" : "",
                     cls->nameForLogging(), (flags & ATTACH_METACLASS) ? " (meta)" : "");
    }

    /*
     * Only a few classes have more than 64 categories during launch.
     * This uses a little stack, and avoids malloc.
     *
     * Categories must be added in the proper order, which is back
     * to front. To do that with the chunking, we iterate cats_list
     * from front to back, build up the local buffers backwards,
     * and call attachLists on the chunks. attachLists prepends the
     * lists, so the final result is in the expected order.
     */
    constexpr uint32_t ATTACH_BUFSIZ = 64;
    method_list_t   *mlists[ATTACH_BUFSIZ];
    property_list_t *proplists[ATTACH_BUFSIZ];
    protocol_list_t *protolists[ATTACH_BUFSIZ];

    uint32_t mcount = 0;
    uint32_t propcount = 0;
    uint32_t protocount = 0;
    bool fromBundle = NO;
    bool isMeta = (flags & ATTACH_METACLASS);
    auto rwe = cls->data()->extAllocIfNeeded();
    
    const char *mangledName = cls->nonlazyMangledName();
    if (strcmp(mangledName, "LGPerson") == 0)
    {
        if (!isMeta) {
            printf("LGPerson....\n");
        }
    }

    for (uint32_t i = 0; i < cats_count; i++) {
        auto& entry = cats_list[I];

        method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        if (mlist) {
            if (mcount == ATTACH_BUFSIZ) {
                prepareMethodLists(cls, mlists, mcount, NO, fromBundle, __func__);
                rwe->methods.attachLists(mlists, mcount);
                mcount = 0;
            }
            mlists[ATTACH_BUFSIZ - ++mcount] = mlist;
            fromBundle |= entry.hi->isBundle();
        }

        property_list_t *proplist =
            entry.cat->propertiesForMeta(isMeta, entry.hi);
        if (proplist) {
            if (propcount == ATTACH_BUFSIZ) {
                rwe->properties.attachLists(proplists, propcount);
                propcount = 0;
            }
            proplists[ATTACH_BUFSIZ - ++propcount] = proplist;
        }

        protocol_list_t *protolist = entry.cat->protocolsForMeta(isMeta);
        if (protolist) {
            if (protocount == ATTACH_BUFSIZ) {
                rwe->protocols.attachLists(protolists, protocount);
                protocount = 0;
            }
            protolists[ATTACH_BUFSIZ - ++protocount] = protolist;
        }
    }

    if (mcount > 0) {
        prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount,
                           NO, fromBundle, __func__);
        rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
        if (flags & ATTACH_EXISTING) {
            flushCaches(cls, __func__, [](Class c){
                // constant caches have been dealt with in prepareMethodLists
                // if the class still is constant here, it's fine to keep
                return !c->cache.isConstantOptimizedCache();
            });
        }
    }

    rwe->properties.attachLists(proplists + ATTACH_BUFSIZ - propcount, propcount);

    rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}

这里面调用的rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
我们看下attachLists这个函数,代码如下:

void attachLists(List* const * addedLists, uint32_t addedCount) {
        if (addedCount == 0) return;

        if (hasArray()) {
            // many lists -> many lists
            uint32_t oldCount = array()->count;
            uint32_t newCount = oldCount + addedCount;
            array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount));
            newArray->count = newCount;
            array()->count = newCount;

            for (int i = oldCount - 1; i >= 0; I--)
                newArray->lists[i + addedCount] = array()->lists[I];
            for (unsigned i = 0; i < addedCount; I++)
                newArray->lists[i] = addedLists[I];
            free(array());
            setArray(newArray);
            validate();
        }
        else if (!list  &&  addedCount == 1) {
            // 0 lists -> 1 list
            list = addedLists[0];
            validate();
        } 
        else {
            // 1 list -> many lists
            Ptr oldList = list;
            uint32_t oldCount = oldList ? 1 : 0;
            uint32_t newCount = oldCount + addedCount;
            setArray((array_t *)malloc(array_t::byteSize(newCount)));
            array()->count = newCount;
            if (oldList) array()->lists[addedCount] = oldList;
            for (unsigned i = 0; i < addedCount; I++)
                array()->lists[i] = addedLists[I];
            validate();
        }
    }

这是核心重点,我们来分析下。

  else if (!list  &&  addedCount == 1) {
            // 0 lists -> 1 list
            list = addedLists[0];
            validate();
        } 

这个流程把addedLists[0]给了List,list是一维数组。

else {
            // 1 list -> many lists
            Ptr oldList = list;
            uint32_t oldCount = oldList ? 1 : 0;
            uint32_t newCount = oldCount + addedCount;
            setArray((array_t *)malloc(array_t::byteSize(newCount)));
            array()->count = newCount;
            if (oldList) array()->lists[addedCount] = oldList;
            for (unsigned i = 0; i < addedCount; I++)
                array()->lists[i] = addedLists[I];
            validate();
        }

这段代码就是如果oldList为1,在lists的第addedCount元素插入数据,接着再把addedLists元素从lists的0元素开始插入。

   if (hasArray()) {
            // many lists -> many lists
            uint32_t oldCount = array()->count;
            uint32_t newCount = oldCount + addedCount;
            array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount));
            newArray->count = newCount;
            array()->count = newCount;

            for (int i = oldCount - 1; i >= 0; I--)
                newArray->lists[i + addedCount] = array()->lists[I];
            for (unsigned i = 0; i < addedCount; I++)
                newArray->lists[i] = addedLists[I];
            free(array());
            setArray(newArray);
            validate();
        }

这段代码倒序一个一个的插入到newArray中,最后会把newArray释放掉 。

分类和主类加载的4种情况

我们添加一个RoPerson的分类RoPerson+RoA,并且写一个Load方法,验证是否是必须用Load方法才可以调用attachCategories
同样需要加入以下代码,方便测试,如下:

  const char *mangledName = cls->nonlazyMangledName();
    if (strcmp(mangledName, "RoPerson") == 0)
    {
        if (!isMeta) {
            printf("RoPerson....\n");
        }
    }

然后我们在attachCategories的上面测试代码中打断点调试,如图:

3

我们的断点进入了attachCategories函数中。
1.RoPerson与其分类都有实现load方法(非懒加载)。
2.分类实现Load方法,主类不实现Load方法,经过测试并没有进入attachCategories函数中。
3.分类没有实现Load方法,主类有实现Load方法,经过测试并没有进入attachCategories函数中。
4.分类没有实现Load方法,主类也没有实现Load方法,经过测试并没有进入attachCategories函数中。
那么分类加载的流程是什么,我们接着分析。

分类加载流程跟踪

我们先讲上面的第一种情况RoPerson与其分类都有实现load方法。的流程。
我们在_read_images这个函数加入的测试代码中断点,如下图:

4

然后断点进入realizeClassWithoutSwift函数,在终端执行以下命令,如图:
5

当我们取到第10的时候,报错了,也就是说分类的方法,我们继续往下执行,走到了load_categories_nolock这个函数中。
我们看下当前的堆栈,如图:
6

接着我们在终端在执行以下命令,如图:
7

在这是里打印出了我们的RoA这个分类,说明加载了,也就是在运行时的时候才加载
这个时候,再继续执行,走到了attachCategories这个函数。
在以下代码可以看出在处理方法,协议,属性

 method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        if (mlist) {
            if (mcount == ATTACH_BUFSIZ) {
                prepareMethodLists(cls, mlists, mcount, NO, fromBundle, __func__);
                rwe->methods.attachLists(mlists, mcount);
                mcount = 0;
            }
            mlists[ATTACH_BUFSIZ - ++mcount] = mlist;
            fromBundle |= entry.hi->isBundle();
        }
property_list_t *proplist =
            entry.cat->propertiesForMeta(isMeta, entry.hi);
        if (proplist) {
            if (propcount == ATTACH_BUFSIZ) {
                rwe->properties.attachLists(proplists, propcount);
                propcount = 0;
            }
            proplists[ATTACH_BUFSIZ - ++propcount] = proplist;
        }

        protocol_list_t *protolist = entry.cat->protocolsForMeta(isMeta);
        if (protolist) {
            if (protocount == ATTACH_BUFSIZ) {
                rwe->protocols.attachLists(protolists, protocount);
                protocount = 0;
            }
            protolists[ATTACH_BUFSIZ - ++protocount] = protolist;
        }
 if (mcount > 0) {
        prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount,
                           NO, fromBundle, __func__);
        rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
        if (flags & ATTACH_EXISTING) {
            flushCaches(cls, __func__, [](Class c){
                // constant caches have been dealt with in prepareMethodLists
                // if the class still is constant here, it's fine to keep
                return !c->cache.isConstantOptimizedCache();
            });
        }
    }

这里对方法又进行了排序,mlists + ATTACH_BUFSIZ - mcount这里得到是二级指针,通过p mlists + ATTACH_BUFSIZ - mcount可以查看。
** rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);**这个函数把分类的方法加入到主类中。

多个分类加载

我们再为RoPerson创建一个分类RoPerson+RoB,然后加入方法和属性,重新运行。
在进入load_categories_nolock这个函数是,我们打印下count变量是2,如图:

8

然后执行以下命令,如图:
9

这里是RoB的加载,我们过掉,继续执行,然后在load_categories_nolock中打印以下命令,如图:
10

这里是RoA的加载,而这个时候在attachLists这个函数中走到了

 if (hasArray()) {
            // many lists -> many lists
            uint32_t oldCount = array()->count;
            uint32_t newCount = oldCount + addedCount;
            array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount));
            newArray->count = newCount;
            array()->count = newCount;

            for (int i = oldCount - 1; i >= 0; I--)
                newArray->lists[i + addedCount] = array()->lists[I];
            for (unsigned i = 0; i < addedCount; I++)
                newArray->lists[i] = addedLists[I];
            free(array());
            setArray(newArray);
            validate();
        }

这段代码,newArray也是二维存储,存的是分类以及主类方法的的指针。

五种情况ro-rw数据的加载

以上几个是分类与主类都有load的方法实现时的数据加载,那么其它的情况呢,我们接着分析。第一种情况以上已经介绍。
2.我们先看分类实现,主类没有的情况,重新运行工程。
如图:

11

这里进入了非懒加载的方式,也就是说分类实现的load方法,导致主类进入了非懒加载,那么主类的数据怎么来呢,我们断点进入realizeClassWithoutSwift这个函数查看,如图:
12

这说明主类与分类的数据已经存在,伴随着类的加载合到一起了,在data()获取。
3.我们再来看分类没有,主类有Load方法的实现情况,重新运行工程,经过分析,如图:
13

这说明主类实现了load方法,分类的方法也有了,同样在data()获取数据。
4.我们继续看主类没有实现load方法,分类也没有实现Load方法的情况,重新运行工程,先在main函数打个断点,如图:
14

继续执行走到了realizeClassWithoutSwift这个函数,是在第一次发送消息的时候加载的(懒加载),我们再看下堆栈
15

是推迟到第一次发送消息的时候加载。
5.主类有Load方法,分类也有load方法,但是有多个分类的情况(分类不全有),我们创建RoPerson+RoB这个分类,重新运行工程,进入的也是Realize non-lazy classes(非懒加载) (for +load methods and static instances)模式,也会走到load_categories_nolock这个函数,这个函 数的count是2,也就是一个一个的加载,这里的count是在processCatlist(hi->catlist(&count));(闭包)得到的,其实也就是在_getObjc2CategoryList这个地方获取的,由Macho决定的。

结语

这篇文章主要介绍了分类的加载,跟iOS类的加载原理(上)一起整体介绍了分类的加载原理,如有错误,烦请大家留言指正,相互交流学习。

你可能感兴趣的:(iOS类的加载原理(下))