iOS類的加載(上)

本文我們主要是為了理解類的相關(guān)信息是如何加載到內(nèi)存中,可以重點關(guān)注map_imagesload_images

  • map_images:管理文件和動態(tài)庫中所有的符號,即class、protocol、selector、category等,是應(yīng)用類型,外界變了,跟著變
  • load_images:加載執(zhí)行load方法,是值類型,不傳遞值

代碼通過編譯,讀取到Mach-O可執(zhí)行文件中,再從Mach-O中讀取到內(nèi)存,如下圖所示

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

map_images源碼流程

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

  • 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);
}
  • 進入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.計算類的個數(shù)
    int totalClasses = 0;
    int unoptimizedTotalClasses = 0;
    //代碼塊:作用域,進行局部處理,即局部處理一些事件
    {
        //...省略
    }
    
    //...省略

    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源碼實現(xiàn)

_read_images主要是加載類信息,即類、分類、協(xié)議等,主要分為以下幾個部分

  • 1、條件控制進行的一次加載
  • 2、修復(fù)預(yù)編譯階段的@selector混亂問題
  • 3、錯誤混亂的類處理
  • 4、修復(fù)和重映射一些沒有被鏡像文件加載進來的類
  • 5、修復(fù)一些消息
  • 6、當(dāng)類里面有協(xié)議時:readProtocol讀取協(xié)議
  • 7、修復(fù)沒有被加載的協(xié)議
  • 8、分類處理
  • 9、類的加載處理
  • 10、沒有被處理的類,優(yōu)化被侵犯的類
1、條件控制進行的一次加載

doneOnce流程中通過NXCreateMapTable創(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的注釋說明,這個哈希表用于存儲不在共享緩存且已命名類,無論類是否實現(xiàn),其容量是類數(shù)量的4/3

// 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實際上是不在dyld共享緩存中的已命名類的列表,無論是否實現(xiàn)
NXMapTable *gdb_objc_realized_classes;  // exported for debuggers in objc-gdb.h
2、修復(fù)預(yù)編譯階段@selector的混亂問題

主要是通過_getObjc2SelectorRefs拿到Mach_O中的靜態(tài)段__objc_selrefs,遍歷列表,調(diào)用sel_registerNameNoLockSEL添加到namedSelectors哈希表中

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

        bool isBundle = hi->isBundle();
        //通過_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]);
            //注冊sel操作,即將sel添加到
            SEL sel = sel_registerNameNoLock(name, isBundle);
            if (sels[i] != sel) {//當(dāng)sel與sels[i]地址不一致時,需要調(diào)整為一致的
                sels[i] = sel;
            }
        }
    }
}
  • 其中_getObjc2SelectorRefs源碼如下,獲取Mach-O中的靜態(tài)段__objc_selrefs,通過_getObjc2開頭的Mach-O靜態(tài)段獲取,對應(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);,即將sel插入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帶地址的字符串
    如下所示,sels[i]sel字符串一致,但是地址不一樣,所以需要調(diào)整為一致
    sel

3、錯誤混亂的類處理

從Mach-O中取出所以類,遍歷處理

//3、錯誤混亂的類處理
// 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,是一個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];//此時獲取的cls只是一個地址
        Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized); //讀取類,經(jīng)過這步后,cls獲取的值才是一個名字
        //經(jīng)過調(diào)試,并未執(zhí)行if里面的流程
        //初始化所有懶加載的類需要的內(nèi)存空間,但是懶加載類的數(shù)據(jù)現(xiàn)在是沒有加載到的,連類都沒有初始化
        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");
  • 通過代碼調(diào)試,可以發(fā)現(xiàn)在未執(zhí)行readClass方法前,cls只是一個地址
    打印readClass執(zhí)行前的cls
  • 執(zhí)行后,cls是一個類的名稱![打印執(zhí)行后的cls](https://upload-images.jianshu.io/upload_images/16490557-d0ea05a62a12a162.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    所以到這步為止,類的信息目前僅存儲了地址+名稱

4、重映射沒有被鏡像文件加載進來的類

將未映射的ClassSuper Class進行重新映射

  • _getObjc2ClassRefs 獲取Mach-O中的靜態(tài)段__objc_classrefs,類的引用

  • _getObjc2SuperRefs獲取Mach-O中的靜態(tài)段__objc_superrefs,父類的引用

  • 通過注釋可知,被remapClassRef的類都是懶加載的類,所以最初調(diào)試時,這部分代碼沒有被執(zhí)行

//4、修復(fù)重映射一些沒有被鏡像文件加載進來的類
// Fix up remapped classes 修正重新映射的類
// Class list and nonlazy class list remain unremapped.類列表和非惰性類列表保持未映射
// Class refs and super refs are remapped for message dispatching.類引用和超級引用將重新映射以進行消息分發(fā)
//經(jīng)過調(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");

5、修復(fù)一些消息

通過_getObjc2MessageRefs獲取Mach-O的靜態(tài)段__objc_msgrefs,遍歷,通過fixupMessageRef將函數(shù)指針進行注冊,并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)過調(diào)試,并未執(zhí)行for里面的流程
        //遍歷將函數(shù)指針進行注冊,并fix為新的函數(shù)指針
        for (i = 0; i < count; i++) {
            fixupMessageRef(refs+i);
        }
    }

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

6、當(dāng)類里面有協(xié)議時:readProtocol讀取協(xié)議

//6、當(dāng)類里面有協(xié)議時: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é)議和對象的結(jié)構(gòu)體都類似,isa都對應(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();
    //通過_getObjc2ProtocolList 獲取到Mach-O中的靜態(tài)段__objc_protolist協(xié)議列表,
    //即從編譯器中讀取并初始化protocol
    protocol_t * const *protolist = _getObjc2ProtocolList(hi, &count);
    for (i = 0; i < count; i++) {
        //通過添加protocol到protocol_map哈希表中
        readProtocol(protolist[i], cls, protocol_map, 
                     isPreoptimized, isBundle);
    }
}

ts.log("IMAGE TIMES: discover protocols");
  • 通過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;
}
  • 通過_getObjc2ProtocolList獲取到Mach-O中的靜態(tài)段__objc_protolist協(xié)議列表,即從編譯器中讀取并初始化protocol
protocol_t * const *protolist = _getObjc2ProtocolList(hi, &count);
  • 循環(huán)遍歷協(xié)議列表,通過readProtocol方法將協(xié)議添加到protocol_map哈希表
readProtocol(protolist[i], cls, protocol_map, 
                         isPreoptimized, isBundle);

7、修復(fù)沒有被加載的協(xié)議

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

//7、修復(fù)沒有被加載的協(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é)議列表中的同一個內(nèi)存地址的協(xié)議是否相同,如果不同則替換
        remapProtocolRef(&protolist[i]);//經(jīng)過代碼調(diào)試,并未執(zhí)行
    }
}

ts.log("IMAGE TIMES: fix up @protocol references");
  • 其中remapProtocolRef的源碼實現(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++;
    }
}

8、分類的處理

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

//8、分類處理
// 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");

9、類的加載處理

實現(xiàn)非懶加載類的加載處理

  • 通過_getObjc2NonlazyClassList獲取Mach-O的靜態(tài)段__objc_nlclslist非懶加載類表
  • 通過addClassTableEntry將非懶加載類插入類表,存儲到內(nèi)存,如果已經(jīng)添加就不會載添加,需要確保整個結(jié)構(gòu)都被添加
  • 通過realizeClassWithoutSwift實現(xiàn)當(dāng)前的類,因為前面3中的readClass讀取到內(nèi)存的僅僅只有地址+名稱,類的data數(shù)據(jù)并沒有加載出來
// Realize non-lazy classes (for +load methods and static instances) 初始化非懶加載類,進行rw、ro等操作:realizeClassWithoutSwift
    //懶加載類 -- 別人不動我,我就不動
    //實現(xiàn)非懶加載的類,對于load方法和靜態(tài)實例變量
    for (EACH_HEADER) {
        //通過_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]);
            
            const char *mangledName  = cls->mangledName();
             const char *LGPersonName = "LGPerson";
            
             if (strcmp(mangledName, LGPersonName) == 0) {
                 auto kc_ro = (const class_ro_t *)cls->data();
                 printf("_getObjc2NonlazyClassList: 這個是我要研究的 %s \n",LGPersonName);
             }
            
            if (!cls) continue;

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

            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
            }
            //實現(xiàn)當(dāng)前的類,因為前面readClass讀取到內(nèi)存的僅僅只有地址+名稱,類的data數(shù)據(jù)并沒有加載出來
            //實現(xiàn)所有非懶加載的類(實例化類對象的一些信息,例如rw)
            realizeClassWithoutSwift(cls, nil);
        }
    }

    ts.log("IMAGE TIMES: realize non-lazy classes");

10、沒有被處理的類,優(yōu)化那些被侵犯的類

實現(xiàn)沒有被處理的類,優(yōu)化被侵犯的類
需要重點關(guān)注的是3中的readClass以及9中realizeClassWithoutSwift兩個方法

// 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");
            }
            //實現(xiàn)類
            realizeClassWithoutSwift(cls, nil);
            cls->setInstancesRequireRawIsaRecursively(false/*inherited*/);
        }
        free(resolvedFutureClasses);
    }

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

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

readClass:讀取類

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

/***********************************************************************
* readClass
* Read a class and metaclass as written by a compiler. 讀取編譯器編寫的類和元類
* 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();//名字
    
    // **CJL寫的** ----如果想進入自定義,自己加一個判斷
    const char *LGPersonName = "LGPerson";
    if (strcmp(mangledName, LGPersonName) == 0) {
        auto kc_ro = (const class_ro_t *)cls->data();
        printf("%s -- 研究重點--%s\n", __func__,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();
//判斷是不是后期要處理的類
    //正常情況下,不會走到popFutureNamedClass,因為這是專門針對未來待處理的類的操作
    //通過斷點調(diào)試,不會走到if流程里面,因此也不會對ro、rw進行操作
    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)過調(diào)試,并不會走到這里
        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;
}
  • 通過mangledName獲取類的名字,其中mangledName方法的源碼實現(xiàn)如下
const char *mangledName() { 
        // fixme can't assert locks here
        ASSERT(this);

        if (isRealized()  ||  isFuture()) { //這個初始化判斷在lookupImp也有類似的
            return data()->ro()->name;//如果已經(jīng)實例化,則從ro中獲取name
        } else {
            return ((const class_ro_t *)data())->name;//反之,從mach-O的數(shù)據(jù)data中獲取name
        }
    }
  • 當(dāng)前類的父類中若有丟失的weak-linked類,則返回nil
  • 判斷是不是需要后期處理的類,在正常情況下,不會走到popFutureNamedClass,因為這是專門針對未來待處理的類的操作,也可以通過斷點調(diào)試,可知不會走到if流程里面,因此也不會有ro、rw操作
    • datamach-O的數(shù)據(jù),并不在class的內(nèi)存
    • ro的賦值是從mach-O中的data強轉(zhuǎn)賦值
    • rw里的ro是從ro復(fù)制過去的
  • 通過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());
}
  • 通過addClassTableEntry,將初始化的類添加到allocatedClasses表,是在_objc_init中的runtime_init就創(chuàng)建了allocatedClasses
/***********************************************************************
* addClassTableEntry 將一個類添加到所有類的表中
* 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();//開辟的類的表,在objc_init中的runtime_init就創(chuàng)建了表

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

    if (!isKnownClass(cls))
        set.insert(cls);
    if (addMeta)
        //添加到allocatedClasses哈希表
        addClassTableEntry(cls->ISA(), false);
}

總結(jié)

所以綜上所述,readClass的主要作用就是將Mach-O中的類讀取到內(nèi)存,即插入表中,但是目前的類僅有兩個信息:地址以及名稱,而mach-O的其中的data數(shù)據(jù)還未讀取出來

realizeClassWithoutSwift:實現(xiàn)類

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

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

第一步:讀取data數(shù)據(jù)

讀取classdata數(shù)據(jù),并將其強轉(zhuǎn)為ro,以及rw初始化拷貝一份ro到rw中的ro

  • ro表示readOnly只讀,在編譯時就已經(jīng)確定了內(nèi)存,包含了類名,方法,協(xié)議和實例變量信息,由于是只讀,所以屬于Clean Memory(加載后不會發(fā)生改變的內(nèi)存)
  • rw 表示 readWrite,即可讀可寫,由于其動態(tài)性,可能會往類中添加屬性、方法、添加協(xié)議,在最新的2020的WWDC的對內(nèi)存優(yōu)化的說明Advancements in the Objective-C runtime - WWDC 2020 - Videos - Apple Developer中,提到rw,其實在rw中只有10%的類真正的更改了它們的方法,所以有了rwe,即類的額外信息。對于那些確實需要額外信息的類,可以分配rwe擴展記錄中的一個,并將其滑入類中供其使用。其中rw就屬于dirty memory(在進程運行時會發(fā)生更改的內(nèi)存)類結(jié)構(gòu)一經(jīng)使用就會變成 ditry memory,因為運行時會向它寫入新數(shù)據(jù),例如 創(chuàng)建一個新的方法緩存,并從類中指向它
// 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,在編譯時就已經(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.
    rw = cls->data(); //dirty memory 進行賦值
    ro = cls->data()->ro();
    ASSERT(!isMeta);
    cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
} else { //此時將數(shù)據(jù)讀取進來了,也賦值完畢了
    // Normal class. Allocate writeable class data.
    rw = objc::zalloc<class_rw_t>(); //申請開辟zalloc -- rw
    rw->set_ro(ro);//rw中的ro設(shè)置為臨時變量ro
    rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
    cls->setData(rw);//將cls的data賦值為rw形式
}

【第二步】遞歸調(diào)用`realizeClassWithoutSwift 完善 繼承鏈

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

  • 遞歸調(diào)用 realizeClassWithoutSwift設(shè)置父類、元類
  • 設(shè)置父類和元類的isa指向
  • 通過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)前類的父類、元類
    //遞歸實現(xiàn) 設(shè)置當(dāng)前類、父類、元類的 rw,主要目的是確定繼承鏈 (類繼承鏈、元類繼承鏈)
    //實現(xiàn)元類、父類
    //當(dāng)isa找到根元類之后,根元類的isa是指向自己的,不會返回nil從而導(dǎo)致死循環(huán)——remapClass中對類在表中進行查找的操作,如果表中已有該類,則返回一個空值;如果沒有則返回當(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和父類的對應(yīng)值
cls->superclass = supercls;
cls->initClassIsa(metacls);

...

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

realizeClassWithoutSwift遞歸調(diào)用時,isa找到根元類之后,根元類的isa是指向自己,并不會返回nil,所以有以下遞歸終止條件,其目的是保證類只加載一次`

  • 在realizeClassWithoutSwift中
    • 如果類不存在,則返回nil
    • 如果類已經(jīng)實現(xiàn),則直接返回cls
static Class realizeClassWithoutSwift(Class cls, Class previously)
{
    runtimeLock.assertLocked();
    
    //如果類不存在,則返回nil
    if (!cls) return nil;
    如果類已經(jīng)實現(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);
}

【第三步】通過 methodizeClass 方法化類

通過methodizeClass方法,從ro中讀取方法列表(包括分類中的方法)、屬性列表、協(xié)議列表賦值給rw,并返回cls

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

return cls;

methodizeClass:方法化類

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

  • 屬性列表、方法列表、協(xié)議列表等貼到rwe
  • 附加分類中的方法(將在下一篇文章中進行解釋說明)
static void methodizeClass(Class cls, Class previously)
{
    runtimeLock.assertLocked();

    bool isMeta = cls->isMetaClass();
    auto rw = cls->data(); // 初始化一個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進行排序
        if (rwe) rwe->methods.attachLists(&list, 1);//對rwe進行處理
    }
    // 加入屬性
    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的邏輯

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

  • 獲取robaseMethods
  • 通過prepareMethodLists方法排序
  • rwe進行處理即通過attachLists插入

方法如何排序
在消息流程的慢速查找流程objc_msgSend消息流程之慢速查找文章中,方法的查找算法是通過二分查找算法,說明sel-imp是有排序的,那么是如何排序的呢?

  • 進入prepareMethodLists的源碼實現(xiàn),其內(nèi)部是通過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*/);//排序
        }
    }
    
    ...
}
  • 進入fixupMethodList源碼實現(xiàn),是根據(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方法

methodlist方法主要是將分類添加到主類中,其源碼實現(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: 這個是我要研究的 %s \n",__func__,LGPersonName);
        }
    }
    
    
    auto &map = get();
    auto it = map.find(previously);//找到一個分類進來一次,即一個個加載分類,不要混亂

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

因為attachToClass中的外部循環(huán)是找到一個分類就會進到attachCategories一次,即找一個就循環(huán)一次

attachCategories方法

attachCategories方法中準(zhǔn)備分類的數(shù)據(jù),其源碼實現(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)建,
     那么為什么要在這里進行`rwe的初始化`?因為我們現(xiàn)在要做一件事:往`本類`中`添加屬性、方法、協(xié)議`等
     */
    auto rwe = cls->data()->extAllocIfNeeded();
        
    //mlists 是一個二維數(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,不會走到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();是進行rwe的創(chuàng)建,因為我們現(xiàn)在要做一件事:往本類添加屬性、方法、協(xié)議等,即對原來的 clean memory要進行處理了
    • 進入extAllocIfNeeded方法的源碼實現(xiàn),判斷rwe是否存在,如果存在則直接獲取,如果不存在則開辟
    • 進入extAlloc源碼實現(xiàn),即對rwe 0-1的過程,在此過程中,就將本類的data數(shù)據(jù)加載進去了
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 *>());//如果不存在則進行開辟
    }
}

??//extAlloc源碼實現(xiàn)
class_rw_ext_t *
class_rw_t::extAlloc(const class_ro_t *ro, bool deepCopy)
{
    runtimeLock.assertLocked();
    //此時只有rw,需要對rwe進行數(shù)據(jù)添加,即0-1的過程
    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;
}
  • 其中關(guān)鍵代碼是rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);即存入mlists的末尾,mlists的數(shù)據(jù)來源前面的for循環(huán)
  • 在調(diào)試運行時,發(fā)現(xiàn)category_t中的name編譯時是LGPerson(參考clang編譯時的那么),運行時是LGA即分類的名字
  • 代碼mlists[ATTACH_BUFSIZ - ++mcount] = mlist;,經(jīng)過調(diào)試發(fā)現(xiàn)此時的mcount等于1,即可以理解為 倒序插入,64的原因是允許容納64個(最多64個分類)

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

attachLists方法:插入

其中方法、屬性繼承于entsize_list_tt,協(xié)議則是類似entsize_list_tt實現(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());
    }
    ...
}
  • 進入attachLists方法的源碼實現(xiàn)
void attachLists(List* const * addedLists, uint32_t addedCount) {
    if (addedCount == 0) return;

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

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

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

    • 計算數(shù)組中舊lists的大小
    • 計算新的容量大小 = 舊數(shù)據(jù)大小+新數(shù)據(jù)大小
    • 根據(jù)新的容量大小,開辟一個數(shù)組,類型是 array_t,通過array()獲取
    • 設(shè)置數(shù)組大小
    • 舊的數(shù)據(jù)從 addedCount 數(shù)組下標(biāo)開始 存放舊的lists,大小為 舊數(shù)據(jù)大小 * 單個舊list大小,即整段平移,可以簡單理解為原來的數(shù)據(jù)移動到后面,即指針偏移
    • 新數(shù)據(jù)從數(shù)組 首位置開始存儲,存放新的lists,大小為 新數(shù)據(jù)大小 * 單個list大小,可以簡單理解為越晚加進來,越在前面,越在前面,調(diào)用時則優(yōu)先調(diào)用
  • 【情況2:0對一】如果調(diào)用attachListslist_array_tt二維數(shù)組為空且新增大小數(shù)目為 1

    • 直接賦值addedList第一個list
  • 【情況3:一對多】如果當(dāng)前調(diào)用attachListslist_array_tt二維數(shù)組只有一個一維數(shù)組

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

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

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

綜上所述,attachLists方法主要是將類 和 分類 的數(shù)據(jù)加載到rwe

  • 首先加載本類的data數(shù)據(jù),此時的rwe沒有數(shù)據(jù)為空,走0對1流程
  • 當(dāng)加入一個分類時,此時的rwe僅有一個list,即本類的list,走1對多流程
  • 再加入一個分類時,此時的rwe中有兩個list,即本類+分類的list,走多對多流程

如下圖所示


attachLists的三種流程

懶加載類 和 非懶加載類

懶加載類和非懶加載類

總結(jié)

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

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

類加載流程

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

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