[iOS] 類的加載(上)

1. 類的加載

在之前了解了dyldobjc是如何關(guān)聯(lián)的,本文主要是理解類的相關(guān)信息是如何加載到內(nèi)存的,其中重點(diǎn)關(guān)注的是 map_imagesload_images

  • map_images
    主要是管理文件中和動(dòng)態(tài)庫(kù)中的所有符號(hào),即 class protocol selector category
  • load_images
    加載執(zhí)行 load 方法

其中代碼通過(guò)編譯,讀取到Mach-O可執(zhí)行文件中,再?gòu)?code>Mach-O中讀取到內(nèi)存,如下圖所示:

image.png

1.1 map_images:加載鏡像文件到內(nèi)存

在查看源碼之前,這里說(shuō)一下為什么map_images&,而 load_images沒(méi)有?

  • map_images是引用類型,外界變了,跟著變
  • load_images是值類型
1.1.1 map_images源碼流程

map_images方法的主要作用是將 Mach-O中的類信息加載到內(nèi)存。

  • 進(jìn)入 map_images的源碼:
void
map_images(unsigned count, const char * const paths[],
           const struct mach_header * const mhdrs[])
{
    mutex_locker_t lock(runtimeLock);
    return map_images_nolock(count, paths, mhdrs);
}
  • 進(jìn)入 map_images_nolock源碼,其關(guān)鍵代碼是_read_images
void
map_images_nolock(unsigned mhCount, const char * const mhPaths[],
                  const struct mach_header * const mhdrs[])
{
    //...省略

    // Find all images with Objective-C metadata.查找所有帶有Objective-C元數(shù)據(jù)的映像
    hCount = 0;

    // Count classes. Size various table based on the total.計(jì)算類的個(gè)數(shù)
    int totalClasses = 0;
    int unoptimizedTotalClasses = 0;
    //代碼塊:作用域,進(jìn)行局部處理,即局部處理一些事件
    {
        //...省略
    }
    
    //...省略

    if (hCount > 0) {
        //加載鏡像文件
        _read_images(hList, hCount, totalClasses, unoptimizedTotalClasses);
    }

    firstTime = NO;
    
    // Call image load funcs after everything is set up.一切設(shè)置完成后,調(diào)用鏡像加載功能。
    for (auto func : loadImageFuncs) {
        for (uint32_t i = 0; i < mhCount; i++) {
            func(mhdrs[I]);
        }
    }
}
  • _read_images源碼實(shí)現(xiàn)
    _read_images主要是加載類信息,即類、分類、協(xié)議等,進(jìn)入_read_images源碼實(shí)現(xiàn),主要分為以下幾個(gè)部分:
    a.條件控制進(jìn)行的一次加載
    b.修復(fù)預(yù)編譯階段的@selector 的混亂問(wèn)題
    c.錯(cuò)誤混亂的類處理
    d.修復(fù)重映射一些沒(méi)有被鏡像文件加載進(jìn)來(lái)的類
    e.修復(fù)一些消息
    f.當(dāng)類里邊有協(xié)議時(shí),readProtocol讀取協(xié)議
    g.修復(fù)沒(méi)有被加載的協(xié)議
    h.分類處理
    i.類的加載處理
    j.沒(méi)有被處理的類,優(yōu)化那些被侵犯的類

a. 條件控制進(jìn)行的一次加載
doneOnce 流程中通過(guò) NXCreateMapTable創(chuàng)建表,存放類信息,即創(chuàng)建一張類的哈希表gdb_objc_realized_classes,其目的是為了類查找方便,快捷:

if (!doneOnce) {
     
    //...省略
    
    // namedClasses
    // Preoptimized classes don't go in this table.
    // 4/3 is NXMapTable's load factor
    int namedClassesSize = 
        (isPreoptimized() ? unoptimizedTotalClasses : totalClasses) * 4 / 3;
//創(chuàng)建表(哈希表key-value),目的是查找快
    gdb_objc_realized_classes =
        NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize);

    ts.log("IMAGE TIMES: first time tasks");
}

查看gdb_objc_realized_classes的注釋說(shuō)明,這個(gè)哈希表用于存儲(chǔ)不在共享緩存且已命名類,無(wú)論類是否實(shí)現(xiàn),其容量是類總數(shù)量的 3/4

// This is a misnomer: gdb_objc_realized_classes is actually a list of 
// named classes not in the dyld shared cache, whether realized or not.
//gdb_objc_realized_classes實(shí)際上是不在dyld共享緩存中的已命名類的列表,無(wú)論是否實(shí)現(xiàn)
NXMapTable *gdb_objc_realized_classes;  // exported for debuggers in objc-gdb.h

b.修復(fù)預(yù)編譯階段@selector 的混亂問(wèn)題
主要是通過(guò)_getObjc2SelectorRefs拿到 Mach_O中的靜態(tài)段__objc_selrefs,遍歷列表調(diào)用sel_registerNameNoLock,將 SEL 添加到 namedSelector 哈希表中:

// Fix up @selector references 修復(fù)@selector引用
//sel 不是簡(jiǎn)單的字符串,而是帶地址的字符串
static size_t UnfixedSelectors;
{
    mutex_locker_t lock(selLock);
    for (EACH_HEADER) {
        if (hi->hasPreoptimizedSelectors()) continue;

        bool isBundle = hi->isBundle();
        //通過(guò)_getObjc2SelectorRefs拿到Mach-O中的靜態(tài)段__objc_selrefs
        SEL *sels = _getObjc2SelectorRefs(hi, &count);
        UnfixedSelectors += count;
        for (i = 0; i < count; i++) { //列表遍歷
            const char *name = sel_cname(sels[i]);
            //注冊(cè)sel操作,即將sel添加到
            SEL sel = sel_registerNameNoLock(name, isBundle);
            if (sels[i] != sel) {//當(dāng)sel與sels[i]地址不一致時(shí),需要調(diào)整為一致的
                sels[i] = sel;
            }
        }
    }
}
  • 其中_getObjc2SelectorRefs的源碼如下,表示獲取 Mach-O中的靜態(tài)段__objc_selrefs,可以看到后續(xù)通過(guò)_getObjc2開(kāi)頭的Mach-O靜態(tài)段獲取,都對(duì)應(yīng)不同的section name
//      function name                 content type     section name
GETSECT(_getObjc2SelectorRefs,        SEL,             "__objc_selrefs"); 
GETSECT(_getObjc2MessageRefs,         message_ref_t,   "__objc_msgrefs"); 
GETSECT(_getObjc2ClassRefs,           Class,           "__objc_classrefs");
GETSECT(_getObjc2SuperRefs,           Class,           "__objc_superrefs");
GETSECT(_getObjc2ClassList,           classref_t const,      "__objc_classlist");
GETSECT(_getObjc2NonlazyClassList,    classref_t const,      "__objc_nlclslist");
GETSECT(_getObjc2CategoryList,        category_t * const,    "__objc_catlist");
GETSECT(_getObjc2CategoryList2,       category_t * const,    "__objc_catlist2");
GETSECT(_getObjc2NonlazyCategoryList, category_t * const,    "__objc_nlcatlist");
GETSECT(_getObjc2ProtocolList,        protocol_t * const,    "__objc_protolist");
GETSECT(_getObjc2ProtocolRefs,        protocol_t *,    "__objc_protorefs");
GETSECT(getLibobjcInitializers,       UnsignedInitializer, "__objc_init_func");
  • sel_registerNameNoLock的源碼路徑如下:sel_registerNameNoLock-> __sel_registerName,如下所示:其關(guān)鍵代碼是auto it = namedSelectors.get().insert(name);,即將name插入namedSelectors哈希表:
SEL sel_registerNameNoLock(const char *name, bool copy) {
    return __sel_registerName(name, 0, copy);  // NO lock, maybe copy
}

??
static SEL __sel_registerName(const char *name, bool shouldLock, bool copy) 
{
    SEL result = 0;

    if (shouldLock) selLock.assertUnlocked();
    else selLock.assertLocked();

    if (!name) return (SEL)0;

    result = search_builtins(name);
    if (result) return result;
    
    conditional_mutex_locker_t lock(selLock, shouldLock);
    auto it = namedSelectors.get().insert(name);//sel插入表
    if (it.second) {
        // No match. Insert.
        *it.first = (const char *)sel_alloc(name, copy);
    }
    return (SEL)*it.first;
}
  • 其中 selector -> sel 并不是簡(jiǎn)單的字符串,是帶地址的字符串
    如下所示,sels[i]sel 字符串一致,但是地址不一致,所以需要調(diào)整為一致的。即fix up,可以通過(guò)調(diào)試:
    image.jpeg

c.錯(cuò)誤混亂的類的處理
主要是從Mach-O中取出所有的類,再遍歷進(jìn)行處理:

//錯(cuò)誤混亂的類處理
// Discover classes. Fix up unresolved future classes. Mark bundle classes.
bool hasDyldRoots = dyld_shared_cache_some_image_overridden();
//讀取類:readClass
for (EACH_HEADER) {
    if (! mustReadClasses(hi, hasDyldRoots)) {
        // Image is sufficiently optimized that we need not call readClass()
        continue;
    }
    //從編譯后的類列表中取出所有類,即從Mach-O中獲取靜態(tài)段__objc_classlist,是一個(gè)classref_t類型的指針
    classref_t const *classlist = _getObjc2ClassList(hi, &count);

    bool headerIsBundle = hi->isBundle();
    bool headerIsPreoptimized = hi->hasPreoptimizedClasses();

    for (i = 0; i < count; i++) {
        Class cls = (Class)classlist[i];//此時(shí)獲取的cls只是一個(gè)地址
        Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized); //讀取類,經(jīng)過(guò)這步后,cls獲取的值才是一個(gè)名字
        //經(jīng)過(guò)調(diào)試,并未執(zhí)行if里面的流程
        //初始化所有懶加載的類需要的內(nèi)存空間,但是懶加載類的數(shù)據(jù)現(xiàn)在是沒(méi)有加載到的,連類都沒(méi)有初始化
        if (newCls != cls  &&  newCls) {
            // Class was moved but not deleted. Currently this occurs 
            // only when the new class resolved a future class.
            // Non-lazily realize the class below.
            //將懶加載的類添加到數(shù)組中
            resolvedFutureClasses = (Class *)
                realloc(resolvedFutureClasses, 
                        (resolvedFutureClassCount+1) * sizeof(Class));
            resolvedFutureClasses[resolvedFutureClassCount++] = newCls;
        }
    }
}
ts.log("IMAGE TIMES: discover classes");
  • 通過(guò)代碼調(diào)試,確定了在沒(méi)有執(zhí)行 readClass方法之前,cls只是一個(gè)地址:

    image.jpeg

  • 執(zhí)行后,cls 是一個(gè)類的名稱

    image.jpeg

所以到這步為止,類的信息目前僅存儲(chǔ)了地址 + 名稱。

d.修復(fù)重映射一些沒(méi)有被鏡像文件加載進(jìn)來(lái)的類
主要是將未映射的ClassSuper Class進(jìn)行重映射,其中

  • _getObjc2ClassRefs是獲取Mach-O中的靜態(tài)段__objc_classrefs類的引用
    -_getObjc2SuperRefs是獲取Mach-O中的靜態(tài)段__objc_superrefs父類的引用
  • 通過(guò)注釋可以得知,被 remapClassRef的類都是懶加載的類,所以最初經(jīng)過(guò)調(diào)試時(shí),這部分代碼是沒(méi)有執(zhí)行的
// 修復(fù)重映射一些沒(méi)有被鏡像文件加載進(jìn)來(lái)的類
// Fix up remapped classes 修正重新映射的類
// Class list and nonlazy class list remain unremapped.類列表和非惰性類列表保持未映射
// Class refs and super refs are remapped for message dispatching.類引用和超級(jí)引用將重新映射以進(jìn)行消息分發(fā)
//經(jīng)過(guò)調(diào)試,并未執(zhí)行if里面的流程
//將未映射的Class 和 Super Class重映射,被remap的類都是懶加載的類
if (!noClassesRemapped()) {
    for (EACH_HEADER) {
        Class *classrefs = _getObjc2ClassRefs(hi, &count);//Mach-O的靜態(tài)段 __objc_classrefs
        for (i = 0; i < count; i++) {
            remapClassRef(&classrefs[I]);
        }
        // fixme why doesn't test future1 catch the absence of this?
        classrefs = _getObjc2SuperRefs(hi, &count);//Mach_O中的靜態(tài)段 __objc_superrefs
        for (i = 0; i < count; i++) {
            remapClassRef(&classrefs[I]);
        }
    }
}

ts.log("IMAGE TIMES: remap classes");

e.修復(fù)一些消息
主要是通過(guò)_getObjc2MessageRefs 獲取Mach-O的靜態(tài)段 __objc_msgrefs,并遍歷通過(guò)fixupMessageRef將函數(shù)指針進(jìn)行注冊(cè),并fix為新的函數(shù)指針

#if SUPPORT_FIXUP
//5、修復(fù)一些消息
    // Fix up old objc_msgSend_fixup call sites
    for (EACH_HEADER) {
        // _getObjc2MessageRefs 獲取Mach-O的靜態(tài)段 __objc_msgrefs
        message_ref_t *refs = _getObjc2MessageRefs(hi, &count);
        if (count == 0) continue;

        if (PrintVtables) {
            _objc_inform("VTABLES: repairing %zu unsupported vtable dispatch "
                         "call sites in %s", count, hi->fname());
        }
        //經(jīng)過(guò)調(diào)試,并未執(zhí)行for里面的流程
        //遍歷將函數(shù)指針進(jìn)行注冊(cè),并fix為新的函數(shù)指針
        for (i = 0; i < count; i++) {
            fixupMessageRef(refs+i);
        }
    }

    ts.log("IMAGE TIMES: fix up objc_msgSend_fixup");
#endif

f.當(dāng)有協(xié)議時(shí):readProtocol 讀取協(xié)議

// 當(dāng)類里面有協(xié)議時(shí):readProtocol 讀取協(xié)議
// Discover protocols. Fix up protocol refs. 發(fā)現(xiàn)協(xié)議。修正協(xié)議參考
//遍歷所有協(xié)議列表,并且將協(xié)議列表加載到Protocol的哈希表中
for (EACH_HEADER) {
    extern objc_class OBJC_CLASS_$_Protocol;
    //cls = Protocol類,所有協(xié)議和對(duì)象的結(jié)構(gòu)體都類似,isa都對(duì)應(yīng)Protocol類
    Class cls = (Class)&OBJC_CLASS_$_Protocol;
    ASSERT(cls);
    //獲取protocol哈希表 -- protocol_map
    NXMapTable *protocol_map = protocols();
    bool isPreoptimized = hi->hasPreoptimizedProtocols();

    // Skip reading protocols if this is an image from the shared cache
    // and we support roots
    // Note, after launch we do need to walk the protocol as the protocol
    // in the shared cache is marked with isCanonical() and that may not
    // be true if some non-shared cache binary was chosen as the canonical
    // definition
    if (launchTime && isPreoptimized && cacheSupportsProtocolRoots) {
        if (PrintProtocols) {
            _objc_inform("PROTOCOLS: Skipping reading protocols in image: %s",
                         hi->fname());
        }
        continue;
    }

    bool isBundle = hi->isBundle();
    //通過(guò)_getObjc2ProtocolList 獲取到Mach-O中的靜態(tài)段__objc_protolist協(xié)議列表,
    //即從編譯器中讀取并初始化protocol
    protocol_t * const *protolist = _getObjc2ProtocolList(hi, &count);
    for (i = 0; i < count; i++) {
        //通過(guò)添加protocol到protocol_map哈希表中
        readProtocol(protolist[i], cls, protocol_map, 
                     isPreoptimized, isBundle);
    }
}

ts.log("IMAGE TIMES: discover protocols");
  • 通過(guò)NXMapTable *protocol_map = protocols();創(chuàng)建 protocol 哈希表,表的名稱為 protocol_map:
/***********************************************************************
* protocols
* Returns the protocol name => protocol map for protocols.
* Locking: runtimeLock must read- or write-locked by the caller
**********************************************************************/
static NXMapTable *protocols(void)
{
    static NXMapTable *protocol_map = nil;
    
    runtimeLock.assertLocked();

    INIT_ONCE_PTR(protocol_map, 
                  NXCreateMapTable(NXStrValueMapPrototype, 16), 
                  NXFreeMapTable(v) );

    return protocol_map;
}
  • 通過(guò)_getObjc2ProtocolList獲取到Mach-O中的靜態(tài)段__objc_protolist協(xié)議列表,即從編譯器中讀取并初始化protocol:
protocol_t * const *protolist = _getObjc2ProtocolList(hi, &count);

  • 循環(huán)遍歷協(xié)議列表,通過(guò)readProtocol方法將協(xié)議添加到 protocol_map哈希表中:
readProtocol(protolist[i], cls, protocol_map, 
                         isPreoptimized, isBundle);

G.修復(fù)沒(méi)有被加載的協(xié)議
主要是通過(guò)_getObjc2ProtocolRefs 獲取到Mach-O的靜態(tài)段 __objc_protorefs(與上面??的__objc_protolist并不是同一個(gè)東西),然后遍歷需要修復(fù)的協(xié)議,通過(guò)remapProtocolRef比較當(dāng)前協(xié)議和協(xié)議列表中的同一個(gè)內(nèi)存地址的協(xié)議是否相同,如果不同則替換:

// 修復(fù)沒(méi)有被加載的協(xié)議
// Fix up @protocol references
// Preoptimized images may have the right 
// answer already but we don't know for sure.
for (EACH_HEADER) {
    // At launch time, we know preoptimized image refs are pointing at the
    // shared cache definition of a protocol.  We can skip the check on
    // launch, but have to visit @protocol refs for shared cache images
    // loaded later.
    if (launchTime && cacheSupportsProtocolRoots && hi->isPreoptimized())
        continue;
    //_getObjc2ProtocolRefs 獲取到Mach-O的靜態(tài)段 __objc_protorefs
    protocol_t **protolist = _getObjc2ProtocolRefs(hi, &count);
    for (i = 0; i < count; i++) {//遍歷
        //比較當(dāng)前協(xié)議和協(xié)議列表中的同一個(gè)內(nèi)存地址的協(xié)議是否相同,如果不同則替換
        remapProtocolRef(&protolist[i]);//經(jīng)過(guò)代碼調(diào)試,并未執(zhí)行
    }
}

ts.log("IMAGE TIMES: fix up @protocol references");

其中remapProtocolRef 的源碼實(shí)現(xiàn)如下:

/***********************************************************************
* remapProtocolRef
* Fix up a protocol ref, in case the protocol referenced has been reallocated.
* Locking: runtimeLock must be read- or write-locked by the caller
**********************************************************************/
static size_t UnfixedProtocolReferences;
static void remapProtocolRef(protocol_t **protoref)
{
    runtimeLock.assertLocked();
    //獲取協(xié)議列表中統(tǒng)一內(nèi)存地址的協(xié)議
    protocol_t *newproto = remapProtocol((protocol_ref_t)*protoref);
    if (*protoref != newproto) {//如果當(dāng)前協(xié)議 與 同一內(nèi)存地址協(xié)議不同,則替換
        *protoref = newproto;
        UnfixedProtocolReferences++;
    }
}

H.分類處理
這一步主要是處理分類,需要在分類初始化并且將數(shù)據(jù)加載到類之后才執(zhí)行,對(duì)于運(yùn)行時(shí)出現(xiàn)的分類,將分類的發(fā)現(xiàn)推遲到對(duì)_dyld_objc_notify_register的調(diào)用完成后的第一個(gè)load_images調(diào)用為止

//、分類處理
// Discover categories. Only do this after the initial category 發(fā)現(xiàn)分類
// attachment has been done. For categories present at startup,
// discovery is deferred until the first load_images call after
// the call to _dyld_objc_notify_register completes. rdar://problem/53119145
if (didInitialAttachCategories) {
    for (EACH_HEADER) {
        load_categories_nolock(hi);
    }
}

ts.log("IMAGE TIMES: discover categories");

I.類的加載處理
主要是實(shí)現(xiàn)類的加載處理,實(shí)現(xiàn)非懶加載類(下面會(huì)有介紹):

  • 通過(guò)_getObjc2NonlazyClassList獲取Mach-O的靜態(tài)段__objc_nlclslist非懶加載類表
  • 通過(guò)addClassTableEntry將非懶加載類插入類表,存儲(chǔ)到內(nèi)存,如果已經(jīng)添加就不會(huì)載添加,需要確保整個(gè)結(jié)構(gòu)都被添加
  • 通過(guò)realizeClassWithoutSwift實(shí)現(xiàn)當(dāng)前的類,因?yàn)榍懊娴?code>readClass讀取到內(nèi)存的僅僅只有地址+名稱,類的data數(shù)據(jù)并沒(méi)有加載出來(lái)
// Realize non-lazy classes (for +load methods and static instances) 初始化非懶加載類,進(jìn)行rw、ro等操作:realizeClassWithoutSwift
    //懶加載類 -- 別人不動(dòng)我,我就不動(dòng)
    //實(shí)現(xiàn)非懶加載的類,對(duì)于load方法和靜態(tài)實(shí)例變量
    for (EACH_HEADER) {
        //通過(guò)_getObjc2NonlazyClassList獲取Mach-O的靜態(tài)段__objc_nlclslist非懶加載類表
        classref_t const *classlist = 
            _getObjc2NonlazyClassList(hi, &count);
        for (i = 0; i < count; i++) {
            Class cls = remapClass(classlist[i]);
            
   
            
            if (!cls) continue;

            addClassTableEntry(cls);//插入表,但是前面已經(jīng)插入過(guò)了,所以不會(huì)重新插入

            if (cls->isSwiftStable()) {
                if (cls->swiftMetadataInitializer()) {
                    _objc_fatal("Swift class %s with a metadata initializer "
                                "is not allowed to be non-lazy",
                                cls->nameForLogging());
                }
                // fixme also disallow relocatable classes
                // We can't disallow all Swift classes because of
                // classes like Swift.__EmptyArrayStorage
            }
            //實(shí)現(xiàn)當(dāng)前的類,因?yàn)榍懊鎟eadClass讀取到內(nèi)存的僅僅只有地址+名稱,類的data數(shù)據(jù)并沒(méi)有加載出來(lái)
            //實(shí)現(xiàn)所有非懶加載的類(實(shí)例化類對(duì)象的一些信息,例如rw)
            realizeClassWithoutSwift(cls, nil);
        }
    }

J.實(shí)現(xiàn)沒(méi)有被處理的類,優(yōu)化哪些被侵犯的類

// Realize newly-resolved future classes, in case CF manipulates them
    if (resolvedFutureClasses) {
        for (i = 0; i < resolvedFutureClassCount; i++) {
            Class cls = resolvedFutureClasses[I];
            if (cls->isSwiftStable()) {
                _objc_fatal("Swift class is not allowed to be future");
            }
            //實(shí)現(xiàn)類
            realizeClassWithoutSwift(cls, nil);
            cls->setInstancesRequireRawIsaRecursively(false/*inherited*/);
        }
        free(resolvedFutureClasses);
    }

    ts.log("IMAGE TIMES: realize future classes");

    if (DebugNonFragileIvars) {
        //實(shí)現(xiàn)所有類
        realizeAllClasses();
    }

我們需要重點(diǎn)關(guān)注的是我們需要重點(diǎn)關(guān)注的是readClass以及realizeClassWithoutSwift兩個(gè)方法。

2. readClass & realizeClassWithoutSwift

2.1 readClass 讀取類

readClass 主要是讀取類,在未調(diào)用該方法前,cls 只是一個(gè)地址,執(zhí)行該方法后,cls 是類的名稱,其源碼實(shí)現(xiàn)如下,關(guān)鍵代碼是 addNamedClassaddClassTableEntry,源碼實(shí)現(xiàn)如下:

/***********************************************************************
* readClass
* Read a class and metaclass as written by a compiler. 讀取編譯器編寫(xiě)的類和元類
* Returns the new class pointer. This could be:  返回新的類指針,可能是:
* - cls
* - nil  (cls has a missing weak-linked superclass)
* - something else (space for this class was reserved by a future class)
*
* Note that all work performed by this function is preflighted by 
* mustReadClasses(). Do not change this function without updating that one.
*
* Locking: runtimeLock acquired by map_images or objc_readClassPair
**********************************************************************/
Class readClass(Class cls, bool headerIsBundle, bool headerIsPreoptimized)
{
    const char *mangledName = cls->mangledName();//名字
    
    //當(dāng)前類的父類中若有丟失的weak-linked類,則返回nil
    if (missingWeakSuperclass(cls)) {
        // No superclass (probably weak-linked). 
        // Disavow any knowledge of this subclass.
        if (PrintConnecting) {
            _objc_inform("CLASS: IGNORING class '%s' with "
                         "missing weak-linked superclass", 
                         cls->nameForLogging());
        }
        addRemappedClass(cls, nil);
        cls->superclass = nil;
        return nil;
    }
    
    cls->fixupBackwardDeployingStableSwift();
//判斷是不是后期要處理的類
    //正常情況下,不會(huì)走到popFutureNamedClass,因?yàn)檫@是專門(mén)針對(duì)未來(lái)待處理的類的操作
    //通過(guò)斷點(diǎn)調(diào)試,不會(huì)走到if流程里面,因此也不會(huì)對(duì)ro、rw進(jìn)行操作
    Class replacing = nil;
    if (Class newCls = popFutureNamedClass(mangledName)) {
        // This name was previously allocated as a future class.
        // Copy objc_class to future class's struct.
        // Preserve future's rw data block.
        
        if (newCls->isAnySwift()) {
            _objc_fatal("Can't complete future class request for '%s' "
                        "because the real class is too big.", 
                        cls->nameForLogging());
        }
        //讀取class的data,設(shè)置ro、rw
        //經(jīng)過(guò)調(diào)試,并不會(huì)走到這里
        class_rw_t *rw = newCls->data();
        const class_ro_t *old_ro = rw->ro();
        memcpy(newCls, cls, sizeof(objc_class));
        rw->set_ro((class_ro_t *)newCls->data());
        newCls->setData(rw);
        freeIfMutable((char *)old_ro->name);
        free((void *)old_ro);
        
        addRemappedClass(cls, newCls);
        
        replacing = cls;
        cls = newCls;
    }
    //判斷是否類是否已經(jīng)加載到內(nèi)存
    if (headerIsPreoptimized  &&  !replacing) {
        // class list built in shared cache
        // fixme strict assert doesn't work because of duplicates
        // ASSERT(cls == getClass(name));
        ASSERT(getClassExceptSomeSwift(mangledName));
    } else {
        addNamedClass(cls, mangledName, replacing);//加載共享緩存中的類
        addClassTableEntry(cls);//插入表,即相當(dāng)于從mach-O文件 讀取到 內(nèi)存 中
    }

    // for future reference: shared cache never contains MH_BUNDLEs
    if (headerIsBundle) {
        cls->data()->flags |= RO_FROM_BUNDLE;
        cls->ISA()->data()->flags |= RO_FROM_BUNDLE;
    }
    
    return cls;
}

通過(guò)源碼實(shí)現(xiàn),主要分為以下幾步:

  • 通過(guò) mangledName獲取類的名字,其中 mangledName 方法的源碼實(shí)現(xiàn)如下:
const char *mangledName() { 
        // fixme can't assert locks here
        ASSERT(this);

        if (isRealized()  ||  isFuture()) { //這個(gè)初始化判斷在lookupImp也有類似的
            return data()->ro()->name;//如果已經(jīng)實(shí)例化,則從ro中獲取name
        } else {
            return ((const class_ro_t *)data())->name;//反之,從mach-O的數(shù)據(jù)data中獲取name
        }
    }
  • 當(dāng)前類的父類中若有丟失的weak-linked類,則返回 nil

  • 判斷是不是后期需要處理的類,在正常情況下,不會(huì)走到 popFutureNamedClass,因?yàn)檫@是專門(mén)針對(duì)未來(lái)待處理類的操作,也可以通過(guò)斷點(diǎn)調(diào)試,就可以知道不會(huì)走到if 流程里邊,因此也不會(huì)對(duì)ro rw進(jìn)行操作。

    • datamach-o的數(shù)據(jù),并不在 class的內(nèi)存中
    • ro 的賦值是從 mach-o 中的data強(qiáng)轉(zhuǎn)賦值的
    • rw 里的ro是從ro 復(fù)制過(guò)去的
  • 通過(guò)addNamedClass將當(dāng)前類添加到已經(jīng)創(chuàng)建好的 gdb_objc_realized_classes哈希表,該表用于存放所有類

/***********************************************************************
* addNamedClass 加載共享緩存中的類 插入表
* Adds name => cls to the named non-meta class map. 將name=> cls添加到命名的非元類映射
* Warns about duplicate class names and keeps the old mapping.
* Locking: runtimeLock must be held by the caller
**********************************************************************/
static void addNamedClass(Class cls, const char *name, Class replacing = nil)
{
    runtimeLock.assertLocked();
    Class old;
    if ((old = getClassExceptSomeSwift(name))  &&  old != replacing) {
        inform_duplicate(name, old, cls);

        // getMaybeUnrealizedNonMetaClass uses name lookups.
        // Classes not found by name lookup must be in the
        // secondary meta->nonmeta table.
        addNonMetaClass(cls);
    } else {
        //添加到gdb_objc_realized_classes哈希表
        NXMapInsert(gdb_objc_realized_classes, name, cls);
    }
    ASSERT(!(cls->data()->flags & RO_META));

    // wrong: constructed classes are already realized when they get here
    // ASSERT(!cls->isRealized());
}
  • 通過(guò) addClassTableEntry,將初始化的類添加到allocatedClasses表,這個(gè)表在之前介紹dyld 與 objc 的關(guān)聯(lián)中提到過(guò),是在_objc_init中的runtime_init就創(chuàng)建了allocatedClasses表:
/***********************************************************************
* addClassTableEntry 將一個(gè)類添加到所有類的表中
* Add a class to the table of all classes. If addMeta is true,
* automatically adds the metaclass of the class as well.
* Locking: runtimeLock must be held by the caller.
**********************************************************************/
static void
addClassTableEntry(Class cls, bool addMeta = true)
{
    runtimeLock.assertLocked();

    // This class is allowed to be a known class via the shared cache or via
    // data segments, but it is not allowed to be in the dynamic table already.
    auto &set = objc::allocatedClasses.get();//開(kāi)辟的類的表,在objc_init中的runtime_init就創(chuàng)建了表

    ASSERT(set.find(cls) == set.end());

    if (!isKnownClass(cls))
        set.insert(cls);
    if (addMeta)
        // addMeta  默認(rèn)為 true,將元類也添加allocatedClasses哈希表
        addClassTableEntry(cls->ISA(), false);
}

注意:其實(shí)gdb_objc_realized_classes對(duì)allocatedClasses是一種包含關(guān)系,一張是類的總表,一張是已經(jīng)開(kāi)辟了內(nèi)存的類表,

  • 如果我們想在 readClass 源碼中定位到自定義的類,可以自定義 加 if 判斷

總結(jié):
所以 readClass的主要作用就是將Mach-O中的類讀取到內(nèi)存,即插入表中,但是目前的類僅有兩個(gè)信息:地址以及名稱,而 mach-o的其中的 data 數(shù)據(jù)還沒(méi)有讀取出來(lái)。

2.2 realizeClassWithoutSwift 實(shí)現(xiàn)類

realizeClassWithoutSwift方法中有ro、rw 的相關(guān)操作,這個(gè)方法在消息流程的慢速查找中有所提及,方法路徑為:慢速查找(lookUpImpOrForward) --realizeClassMaybeSwiftAndLeaveLocked -- realizeClassMaybeSwiftMaybeRelock -- realizeClassWithoutSwift(實(shí)現(xiàn)類)

realizeClassWithoutSwift方法主要的作用是實(shí)現(xiàn)類,將類的 data 數(shù)據(jù)加載到內(nèi)存中,主要有以下幾部分操作:
[第一步]:讀取 data 數(shù)據(jù),并設(shè)置ro、rw
[第二步]:遞歸調(diào)用realizeClassWithoutSwift完善繼承鏈
[第三步]:通過(guò)methodizeClass方法化類
[第四步]:attachToClass 加入分類中的方法

[第一步]:讀取 data 數(shù)據(jù)
讀取classdata數(shù)據(jù)(此時(shí)的數(shù)據(jù)是從 mach-o文件讀取出來(lái)的),并將其強(qiáng)轉(zhuǎn)為ro,以及rw 初始化ro 拷貝一份到 rw 中的 ro
-ro表示 readOnly,只讀,在編譯時(shí)就已經(jīng)確定了內(nèi)存,包含類名稱、方法、協(xié)議和實(shí)例變量的信息,由于是只讀的,所以屬于Clean Memory,而Clean Memory是指加載后不會(huì)發(fā)生更改的內(nèi)存。

-rw 表示readWrite,即可讀可寫(xiě),由于其動(dòng)態(tài)性,可能會(huì)往類中添加屬性、方法、添加協(xié)議,在最新的2020的WWDC的對(duì)內(nèi)存優(yōu)化的說(shuō)明Advancements in the Objective-C runtime - WWDC 2020 - Videos - Apple Developer中,提到rw,其實(shí)在rw 中只有 10%的類真正改變了它們的方法,所以有了rwe,即類的額外信息。對(duì)于那些確實(shí)需要額外信息的類,可以分配 rwe 擴(kuò)展記錄中的一個(gè),并將其劃入類中供其使用。其中rw 就屬于dirty memory,而dirty memory 是指在進(jìn)行運(yùn)行時(shí)會(huì)發(fā)生更改的內(nèi)存,類結(jié)構(gòu)一經(jīng)使用就會(huì)變成 dirty memory,因?yàn)檫\(yùn)行時(shí)會(huì)向他寫(xiě)入新數(shù)據(jù),例如創(chuàng)建一個(gè)新的方法緩存,并從類中指向它。

// fixme verify class is not in an un-dlopened part of the shared cache?
//讀取class的data(),以及ro/rw創(chuàng)建
auto ro = (const class_ro_t *)cls->data(); //讀取類結(jié)構(gòu)的bits屬性、//ro -- clean memory,在編譯時(shí)就已經(jīng)確定了內(nèi)存
auto isMeta = ro->flags & RO_META; //判斷元類
if (ro->flags & RO_FUTURE) {
    // This was a future class. rw data is already allocated.
  // 這是一個(gè)未來(lái)的類,rw 數(shù)據(jù)已經(jīng)開(kāi)辟過(guò)了
    rw = cls->data(); //dirty memory 進(jìn)行賦值
    ro = cls->data()->ro();
    ASSERT(!isMeta);
    cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
} else { 
    // Normal class. Allocate writeable class data.
    // 大多數(shù)的類都會(huì)走這個(gè)方法 
    rw = objc::zalloc<class_rw_t>(); //申請(qǐng)開(kāi)辟zalloc -- rw
    rw->set_ro(ro);//rw中的ro設(shè)置為臨時(shí)變量ro
    rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
    cls->setData(rw);//將cls的data賦值為rw形式
}
  • class_ro_t & class_rw_t

class_ro_t 存儲(chǔ)了當(dāng)前類在編譯期就已經(jīng)確定的屬性、方法以及遵循的協(xié)議,里面是沒(méi)有分類的方法的,那些運(yùn)行時(shí)添加的方法將會(huì)存儲(chǔ)在運(yùn)行時(shí)生成的 class_rw_t中。
class_rw_t存儲(chǔ)類中的屬性、方法還有協(xié)議等,在運(yùn)行時(shí)生成

在編譯期間,class_ro_t結(jié)構(gòu)體就已經(jīng)確定,oblc_classbitsdata 部分存放著該結(jié)構(gòu)體的地址。在運(yùn)行期間,也就是上面的方法中,會(huì)生成class_rw_t結(jié)構(gòu)體,將class_ro_t結(jié)構(gòu)體設(shè)置為 class_rw_t結(jié)構(gòu)體的ro部分,并且更新類的data 部分,換成 class_rw_t結(jié)構(gòu)體的地址:

類實(shí)現(xiàn)之前:


image.png

類實(shí)現(xiàn)之后:


image.png

此時(shí) rw 還是空的,這里只是對(duì) rw 進(jìn)行了初始化,但是方法、屬性、協(xié)議這些還沒(méi)有被添加上。

[第二步]:遞歸調(diào)用 realizeClassWithoutSwift 完善繼承鏈
遞歸調(diào)用realizeClassWithoutSwift完善繼承鏈,并設(shè)置當(dāng)前類、父類、元類的rw

  • 遞歸調(diào)用realizeClassWithoutSwift設(shè)置父類、元類
  • 設(shè)置父類和元類的isa 指向
  • 通過(guò) addSubClassaddRootClass 設(shè)置父子的雙向鏈表指向關(guān)系,即父類中可以找到子類,子類中可以找到父類
 // Realize superclass and metaclass, if they aren't already.
    // This needs to be done after RW_REALIZED is set above, for root classes.
    // This needs to be done after class index is chosen, for root metaclasses.
    // This assumes that none of those classes have Swift contents,
    //   or that Swift's initializers have already been called.
    //   fixme that assumption will be wrong if we add support
    //   for ObjC subclasses of Swift classes. --
    //遞歸調(diào)用realizeClassWithoutSwift完善繼承鏈,并處理當(dāng)前類的父類、元類
    //遞歸實(shí)現(xiàn) 設(shè)置當(dāng)前類、父類、元類的 rw,主要目的是確定繼承鏈 (類繼承鏈、元類繼承鏈)
    //實(shí)現(xiàn)元類、父類
    //當(dāng)isa找到根元類之后,根元類的isa是指向自己的,不會(huì)返回nil從而導(dǎo)致死循環(huán)——remapClass中對(duì)類在表中進(jìn)行查找的操作,如果表中已有該類,則返回一個(gè)空值;如果沒(méi)有則返回當(dāng)前類,這樣保證了類只加載一次并結(jié)束遞歸
    supercls = realizeClassWithoutSwift(remapClass(cls->superclass), nil);
    metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);
    
...

// Update superclass and metaclass in case of remapping -- class 是 雙向鏈表結(jié)構(gòu) 即父子關(guān)系都確認(rèn)了
// 將父類和元類給我們的類 分別是isa和父類的對(duì)應(yīng)值
cls->superclass = supercls;
cls->initClassIsa(metacls);

...

// Connect this class to its superclass's subclass lists
//雙向鏈表指向關(guān)系 父類中可以找到子類 子類中也可以找到父類
//通過(guò)addSubclass把當(dāng)前類放到父類的子類列表中去
if (supercls) {
    addSubclass(supercls, cls);
} else {
    addRootClass(cls);
}

這里有一個(gè)問(wèn)題,realizeClassWithoutSwift遞歸調(diào)用時(shí),isa 找到根元類之后,根元類的isa 指向自己,并不會(huì)返回 nil,所以有了下面的遞歸終止條件,其目的是保證類只加載一次。

  • realizeClassWithoutSwift
    • 如果類不存在,則返回 nil
    • 如果類已經(jīng)實(shí)現(xiàn),則直接返回 cls
static Class realizeClassWithoutSwift(Class cls, Class previously)
{
    runtimeLock.assertLocked();
    
    //如果類不存在,則返回nil
    if (!cls) return nil;
    如果類已經(jīng)實(shí)現(xiàn),則直接返回cls
    if (cls->isRealized()) return cls;
    ASSERT(cls == remapClass(cls));
    
    ...
}
  • remapClass 方法中,如果cls不存在,則直接返回 nil
/***********************************************************************
* remapClass
* Returns the live class pointer for cls, which may be pointing to 
* a class struct that has been reallocated.
* Returns nil if cls is ignored because of weak linking.
* Locking: runtimeLock must be read- or write-locked by the caller
**********************************************************************/
static Class remapClass(Class cls)
{
    runtimeLock.assertLocked();

    if (!cls) return nil;//如果cls不存在,則返回nil

    auto *map = remappedClasses(NO);
    if (!map)
        return cls;
    
    auto iterator = map->find(cls);
    if (iterator == map->end())
        return cls;
    return std::get<1>(*iterator);
}

[第三步]:通過(guò) methodizeClass方法化類
通過(guò)methodizeClass方法,從ro中讀取方法列表(包括分類中的方法)、屬性列表、協(xié)議列表賦值給rw,并返回cls

// Attach categories 附加類別 -- 疑問(wèn):ro中也有方法列表 rw中也有方法列表,下面這個(gè)方法可以說(shuō)明
//將ro數(shù)據(jù)寫(xiě)入到rw
methodizeClass(cls, previously);

return cls;

其中methodizeClass的源碼實(shí)現(xiàn)如下,主要分為幾部分:

  • 屬性列表、方法列表、協(xié)議列表等貼到 rwe
  • 附加分類中的方法
static void methodizeClass(Class cls, Class previously)
{
    runtimeLock.assertLocked();

    bool isMeta = cls->isMetaClass();
    auto rw = cls->data(); // 初始化一個(gè)rw
    auto ro = rw->ro();
    auto rwe = rw->ext();
    
    ...

    // Install methods and properties that the class implements itself.
    //將屬性列表、方法列表、協(xié)議列表等貼到rw中
    // 將ro中的方法列表加入到rw中
    method_list_t *list = ro->baseMethods();//獲取ro的baseMethods
    if (list) {
        prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls));//methods進(jìn)行排序
        if (rwe) rwe->methods.attachLists(&list, 1);//對(duì)rwe進(jìn)行處理
    }
    // 加入屬性
    property_list_t *proplist = ro->baseProperties;
    if (rwe && proplist) {
        rwe->properties.attachLists(&proplist, 1);
    }
    // 加入?yún)f(xié)議
    protocol_list_t *protolist = ro->baseProtocols;
    if (rwe && protolist) {
        rwe->protocols.attachLists(&protolist, 1);
    }

    // Root classes get bonus method implementations if they don't have 
    // them already. These apply before category replacements.
    if (cls->isRootMetaclass()) {
        // root metaclass
        addMethod(cls, @selector(initialize), (IMP)&objc_noop_imp, "", NO);
    }

    // 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);

    ....
}

方法列表加入rwe的邏輯如下:

  • 獲取 robaseMethods
  • 通過(guò) perpareMethodLists方法排序
  • 對(duì) rwe 進(jìn)行處理,即通過(guò) attachList插入

方法如何排序?
在消息流程的慢速查找流程中,方法的查找算法是二分查找算法,說(shuō)明sel-imp是有排序的,那么是如何排序的呢?

  • 進(jìn)入 perpareMethodLists的源碼實(shí)現(xiàn),其內(nèi)部是通過(guò) fixupMethodList 方法排序的
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*/);//排序
        }
    }
    
    ...
}
  • 進(jìn)入fixupMethodList源碼,是根據(jù)selector address 排序的
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.根據(jù)sel地址排序
    if (sort) {
        method_t::SortBySELAddress sorter;
        std::stable_sort(mlist->begin(), mlist->end(), sorter);
    }
    
    // Mark method list as uniqued and sorted
    mlist->setFixedUp();
}

[第四步]:attachToClass 加入分類

     // 加入分類
    // 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);

主要調(diào)用了unattachedCategories.attachToClass方法,源碼實(shí)現(xiàn)如下:

void attachToClass(Class cls, Class previously, int flags)
{
    runtimeLock.assertLocked();
    ASSERT((flags & ATTACH_CLASS) ||
           (flags & ATTACH_METACLASS) ||
           (flags & ATTACH_CLASS_AND_METACLASS));

    
    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: 這個(gè)是我要研究的 %s \n",__func__,LGPersonName);
        }
    }
    
    
    auto &map = get();
    auto it = map.find(previously);//找到一個(gè)分類進(jìn)來(lái)一次,即一個(gè)個(gè)加載分類,不要混亂

    if (it != map.end()) {//這里會(huì)走進(jìn)來(lái):當(dāng)主類沒(méi)有實(shí)現(xiàn)load,分類開(kāi)始加載,迫使主類加載,會(huì)走到if流程里面
        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);//實(shí)例方法
            attachCategories(cls->ISA(), list.array(), list.count(), otherFlags | ATTACH_METACLASS);//類方法
        } else {
            //如果不是元類,則只走一次 attachCategories
            attachCategories(cls, list.array(), list.count(), flags);
        }
        map.erase(it);
    }
}

因?yàn)?attachToClass中的外部循環(huán)是找到一個(gè)分類就會(huì)進(jìn)到 attachCategories一次,即找一個(gè)就循環(huán)一次。

attachCategories方法中主要是準(zhǔn)備分類的數(shù)據(jù),其源碼實(shí)現(xiàn)如下:

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);
    /*
     rwe的創(chuàng)建,
     那么為什么要在這里進(jìn)行`rwe的初始化`?因?yàn)槲覀儸F(xiàn)在要做一件事:往`本類`中`添加屬性、方法、協(xié)議`等
     */
    auto rwe = cls->data()->extAllocIfNeeded();
        
    //mlists 是一個(gè)二維數(shù)組
    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) {//mcount = 0,ATTACH_BUFSIZ= 64,不會(huì)走到if里面的流程
                prepareMethodLists(cls, mlists, mcount, NO, fromBundle);//準(zhǔn)備排序
                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);//排序
        rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);//mlists + ATTACH_BUFSIZ - mcount 為內(nèi)存平移
        if (flags & ATTACH_EXISTING) flushCaches(cls);
    }

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

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

auto rwe = cls->data()->extAllocIfNeeded();是進(jìn)行 rwe 的創(chuàng)建,那么為什么要在這里進(jìn)行rwe 的初始化?因?yàn)槲覀儸F(xiàn)在要做一件事:往本類中添加屬性、方法、協(xié)議等,即對(duì)原來(lái)的clean memory要進(jìn)行處理了:

  • 進(jìn)入extAllocIfNeeded方法的源碼實(shí)現(xiàn),判斷rwe 是否存在,如果存在則直接獲取,如果不存在則開(kāi)辟
  • 進(jìn)入extAlloc 源碼實(shí)現(xiàn),即對(duì) rwe`` 0 - 1的過(guò)程,在此過(guò)程中,就將本類的data數(shù)據(jù)加載進(jìn)去了
class_rw_ext_t *extAllocIfNeeded() {
    auto v = get_ro_or_rwe();
    if (fastpath(v.is<class_rw_ext_t *>())) { //判斷rwe是否存在
        return v.get<class_rw_ext_t *>();//如果存在,則直接獲取
    } else {
        return extAlloc(v.get<const class_ro_t *>());//如果不存在則進(jìn)行開(kāi)辟
    }
}

??//extAlloc源碼實(shí)現(xiàn)
class_rw_ext_t *
class_rw_t::extAlloc(const class_ro_t *ro, bool deepCopy)
{
    runtimeLock.assertLocked();
    //此時(shí)只有rw,需要對(duì)rwe進(jìn)行數(shù)據(jù)添加,即0-1的過(guò)程
    auto rwe = objc::zalloc<class_rw_ext_t>();//創(chuàng)建
    
    rwe->version = (ro->flags & RO_META) ? 7 : 0;

    method_list_t *list = ro->baseMethods();
    if (list) {
        if (deepCopy) list = list->duplicate();
        rwe->methods.attachLists(&list, 1);
    }

    // See comments in objc_duplicateClass
    // property lists and protocol lists historically
    // have not been deep-copied
    //
    // This is probably wrong and ought to be fixed some day
    property_list_t *proplist = ro->baseProperties;
    if (proplist) {
        rwe->properties.attachLists(&proplist, 1);
    }

    protocol_list_t *protolist = ro->baseProtocols;
    if (protolist) {
        rwe->protocols.attachLists(&protolist, 1);
    }

    set_ro_or_rwe(rwe, ro);
    return rwe;
}

總結(jié):本類中需要添加屬性、方法等,所以需要初始化rwe,rwe的初始化主要涉及:分類、addMethod、addProperty、addprotocol,即對(duì)原始類進(jìn)行修改或者處理時(shí),才會(huì)進(jìn)行rwe的初始化。

attachLists 方法:插入
為什么方法、屬性、協(xié)議都能調(diào)用這個(gè)方法呢?

  • 其中方法、屬性繼承于 entsize_list_tt,協(xié)議則是類似 entsize_list_tt實(shí)現(xiàn),都是二維數(shù)組
struct method_list_t : entsize_list_tt<method_t, method_list_t, 0x3> 

struct property_list_t : entsize_list_tt<property_t, property_list_t, 0> 

struct protocol_list_t {
    // count is pointer-sized by accident.
    uintptr_t count;
    protocol_ref_t list[0]; // variable-size

    size_t byteSize() const {
        return sizeof(*this) + count*sizeof(list[0]);
    }

    protocol_list_t *duplicate() const {
        return (protocol_list_t *)memdup(this, this->byteSize());
    }
    ...
}

-進(jìn)入attachLists方法的源碼實(shí)現(xiàn)

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

    if (hasArray()) {
        // many lists -> many lists
        //計(jì)算數(shù)組中舊lists的大小
        uint32_t oldCount = array()->count;
        //計(jì)算新的容量大小 = 舊數(shù)據(jù)大小+新數(shù)據(jù)大小
        uint32_t newCount = oldCount + addedCount;
        //根據(jù)新的容量大小,開(kāi)辟一個(gè)數(shù)組,類型是 array_t,通過(guò)array()獲取
        setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
        //設(shè)置數(shù)組大小
        array()->count = newCount;
        //舊的數(shù)據(jù)從 addedCount 數(shù)組下標(biāo)開(kāi)始 存放舊的lists,大小為 舊數(shù)據(jù)大小 * 單個(gè)舊list大小
        memmove(array()->lists + addedCount, array()->lists, 
                oldCount * sizeof(array()->lists[0]));
        //新數(shù)據(jù)從數(shù)組 首位置開(kāi)始存儲(chǔ),存放新的lists,大小為 新數(shù)據(jù)大小 * 單個(gè)list大小
        memcpy(
               array()->lists, addedLists, 
               addedCount * sizeof(array()->lists[0]));
    }
    else if (!list  &&  addedCount == 1) {
        // 0 lists -> 1 list
        list = addedLists[0];//將list加入mlists的第一個(gè)元素,此時(shí)的list是一個(gè)一維數(shù)組
    } 
    else {
        // 1 list -> many lists 有了一個(gè)list,有往里加很多l(xiāng)ist
        //新的list就是分類,來(lái)自LRU的算法思維,即最近最少使用
        //獲取舊的list
        List* oldList = list;
        uint32_t oldCount = oldList ? 1 : 0;
        //計(jì)算容量和 = 舊list個(gè)數(shù)+新lists的個(gè)數(shù)
        uint32_t newCount = oldCount + addedCount;
        //開(kāi)辟一個(gè)容量和大小的集合,類型是 array_t,即創(chuàng)建一個(gè)數(shù)組,放到array中,通過(guò)array()獲取
        setArray((array_t *)malloc(array_t::byteSize(newCount)));
        //設(shè)置數(shù)組的大小
        array()->count = newCount;
        //判斷old是否存在,old肯定是存在的,將舊的list放入到數(shù)組的末尾
        if (oldList) array()->lists[addedCount] = oldList;
        // memcpy(開(kāi)始位置,放什么,放多大) 是內(nèi)存平移,從數(shù)組起始位置存入新的list
        //其中array()->lists 表示首位元素位置
        memcpy(array()->lists, addedLists, 
               addedCount * sizeof(array()->lists[0]));
    }
}

從源碼可以得知,插入表主要分為三種情況:

【情況1:多對(duì)多】
如果當(dāng)前調(diào)用attachListslist_array_tt二維數(shù)組中有多個(gè)一維數(shù)組

  • 計(jì)算數(shù)組中舊lists的大小
  • 計(jì)算新的容量大小 = 舊數(shù)據(jù)大小+新數(shù)據(jù)大小
  • 根據(jù)新的容量大小,開(kāi)辟一個(gè)數(shù)組,類型是 array_t,通過(guò)array()獲取
  • 設(shè)置數(shù)組大小
  • 舊的數(shù)據(jù)從addedCount數(shù)組下標(biāo)開(kāi)始 存放舊的lists,大小為 舊數(shù)據(jù)大小 * 單個(gè)舊list大小,即整段平移,可以簡(jiǎn)單理解為原來(lái)的數(shù)據(jù)移動(dòng)到后面,即指針偏移
  • 新數(shù)據(jù)從數(shù)組 首位置開(kāi)始存儲(chǔ),存放新的lists,大小為 新數(shù)據(jù)大小* 單個(gè)list大小,可以簡(jiǎn)單理解為越晚加進(jìn)來(lái),越在前面,越在前面,調(diào)用時(shí)則優(yōu)先調(diào)用

【情況2:0對(duì)一】
如果調(diào)用attachListslist_array_tt二維數(shù)組為空且新增大小數(shù)目為 1

  • 直接賦值addedList的第一個(gè)list

【情況3:一對(duì)多】如果當(dāng)前調(diào)用attachListslist_array_tt二維數(shù)組只有一個(gè)一維數(shù)組

  • 獲取舊的list
  • 計(jì)算容量和 = 舊list個(gè)數(shù)+新lists的個(gè)數(shù)
  • 開(kāi)辟一個(gè)容量和大小的集合,類型是 array_t,即創(chuàng)建一個(gè)數(shù)組,放到array中,通過(guò)array()獲取
  • 設(shè)置數(shù)組的大小
  • 判斷old是否存在,old肯定是存在的,將舊的list放入到數(shù)組的末尾
  • memcpy(開(kāi)始位置,放什么,放多大) 是內(nèi)存平移,從數(shù)組起始位置開(kāi)始存入新的list,其中array()->lists表示首位元素位置

針對(duì)情況3,這里的lists是指分類:

  • 這是日常開(kāi)發(fā)中,為什么子類實(shí)現(xiàn)父類方法會(huì)把父類方法覆蓋的原因
  • 同理,對(duì)于同名方法,分類方法覆蓋類方法的原因
  • 這個(gè)操作來(lái)自一個(gè)算法思維LRU即最近最少使用,加這個(gè)newlist的目的是由于要使用這個(gè)newlist中的方法,這個(gè)newlist對(duì)于用戶的價(jià)值要高,即優(yōu)先調(diào)用
  • 會(huì)來(lái)到1對(duì)多的原因 ,主要是有分類的添加,即舊的元素在后面,新的元素在前面 ,究其根本原因主要是優(yōu)先調(diào)用category,這也是分類的意義所在。

memmovememcpy的區(qū)別

  • 在不知道需要平移的內(nèi)存大小時(shí),需要memmove進(jìn)行內(nèi)存平移,保證安全
  • memcpy從原內(nèi)存地址的起始位置開(kāi)始拷貝若干個(gè)字節(jié)到目標(biāo)內(nèi)存地址中,速度快

3. 懶加載類和非懶加載類

我們?cè)?_read_image方法的第九步中提到實(shí)現(xiàn)非加載類,那么什么是非加載類呢?如何將懶加載類變成非懶加載類呢?
注釋中有提到過(guò),如果實(shí)現(xiàn)了自定義類的 +load 方法,那么這個(gè)類就是非懶加載類了。
我們自定義一個(gè) Person 類,實(shí)現(xiàn)+load方法,在第九步中打上我們的斷點(diǎn),可以看到走到斷點(diǎn)中了:

截屏2021-01-13 下午1.38.03.png

為什么實(shí)現(xiàn)load方法就會(huì)變成非懶加載類了?
因?yàn)?load 會(huì)提前加載(load方法會(huì)在load_images調(diào)用,前提是類存在)

那么不實(shí)現(xiàn)+load 方法,是懶加載類,會(huì)在什么時(shí)候加載呢?
當(dāng)然是在調(diào)用的時(shí)候進(jìn)行加載了,我們?nèi)サ?code>+load 方法的實(shí)現(xiàn),并在 main 中實(shí)例化 person :

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person = [[Person alloc] init];
    }
    return 0;
}

然后在realizeClassWithoutSwift方法處下一個(gè)斷點(diǎn):

截屏2021-01-13 下午1.46.44.png

執(zhí)行,并通過(guò)bt查看堆棧信息:

截屏2021-01-13 下午1.47.41.png

從上圖可以看到其本質(zhì)是調(diào)用 alloc方法,走了方法的慢速查找流程,所以才走到了realizeClassWithoutSwift。

所以懶加載類 和 非懶加載類的數(shù)據(jù)加載時(shí)機(jī)如下圖所示:


image.png

4.總結(jié)

  • readClass主要是讀取類,即此時(shí)的類僅有地址 + 名稱,還沒(méi)有 data 數(shù)據(jù)
  • realizeClassWithoutSwift主要是實(shí)現(xiàn)類,即將類的 data 數(shù)據(jù)讀取到內(nèi)存中
    • methodizeClass方法中實(shí)現(xiàn)類中方法(協(xié)議等)的序列化
    • attachCategories方法中實(shí)現(xiàn)類以及分類的數(shù)據(jù)加載

綜上所述,類從 Mach-O加載到內(nèi)存的流程圖如下所示:


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前言 在之前的文章dyld與objc的關(guān)聯(lián)分析[http://www.itdecent.cn/p/86fcb05...
    Y丶舜禹閱讀 645評(píng)論 0 1
  • 一,應(yīng)用程序加載回顧 通過(guò)前面的學(xué)習(xí)我們對(duì)iOS應(yīng)用程序的加載有了一個(gè)大致的認(rèn)識(shí), 1 系統(tǒng)調(diào)用exec() 會(huì)讓...
    攜YOU手同行閱讀 758評(píng)論 0 0
  • iOS 底層原理 文章匯總[http://www.itdecent.cn/p/412b20d9a0f6] 在上一...
    Style_月月閱讀 3,831評(píng)論 10 14
  • 在分析dyld和objc關(guān)聯(lián)的時(shí)候,我們發(fā)現(xiàn)_read_images方法中有讀取類的方法也有實(shí)現(xiàn)類的方法,我們這篇...
    含笑州閱讀 281評(píng)論 0 0
  • 在上一篇文章 iOS 底層 dyld 與 objc 的關(guān)聯(lián)[http://www.itdecent.cn/p/5...
    遠(yuǎn)方竹葉閱讀 479評(píng)論 0 1

友情鏈接更多精彩內(nèi)容