iOS底層原理 14 :類的加載(上)

iOS底層原理 13 :dyld與objc的關(guān)聯(lián)中,我們初步探索了dyld和objc的關(guān)聯(lián),也因此引出將類加載到內(nèi)存中,最關(guān)鍵的就是兩個(gè)函數(shù)map_imagesload_images

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

靜態(tài)庫(kù)、動(dòng)態(tài)庫(kù)以及自己寫(xiě)的代碼通過(guò)編譯會(huì)生成mach-o形式的可執(zhí)行文件,再?gòu)?code>Mach-O中讀取到內(nèi)存。

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

map_images方法的主要作用就是將Mach-O可執(zhí)行文件中的類信息加載到內(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é)議等)內(nèi)存,進(jìn)入_read_images源碼實(shí)現(xiàn),主要分為以下幾部分:

  • 條件控制進(jìn)行的一次加載
  • 修復(fù)預(yù)編譯階段的@selector的混亂問(wèn)題
  • 錯(cuò)誤混亂的類處理
  • 修復(fù)重映射一些沒(méi)有被鏡像文件加載進(jìn)來(lái)的類
  • 修復(fù)一些消息
  • 當(dāng)類里面有協(xié)議時(shí):readProtocol 讀取協(xié)議
  • 修復(fù)沒(méi)有被加載的協(xié)議
  • 分類處理
  • 類的加載處理
  • 沒(méi)有被處理的類,優(yōu)化那些被侵犯的類
1、條件控制進(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ō)明,這張哈希表用于存儲(chǔ)不在dyld共享緩存中且已命名的類,無(wú)論類是否實(shí)現(xiàn)。

// 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.
NXMapTable *gdb_objc_realized_classes;  // exported for debuggers in objc-gdb.h
2.修復(fù)預(yù)編譯階段的@selector的混亂問(wèn)題

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

 static size_t UnfixedSelectors;
    {
        mutex_locker_t lock(selLock);
        for (EACH_HEADER) {
            if (hi->hasPreoptimizedSelectors()) continue;

            bool isBundle = hi->isBundle();
            SEL *sels = _getObjc2SelectorRefs(hi, &count);
            UnfixedSelectors += count;
            for (i = 0; i < count; i++) {
                const char *name = sel_cname(sels[i]);
                SEL sel = sel_registerNameNoLock(name, isBundle);
                if (sels[i] != sel) {
                    sels[i] = sel;
                }
            }
        }
    }
3、錯(cuò)誤混亂的類處理

主要是從Mach-O中取出所有類,在遍歷進(jìn)行處理。當(dāng)某些類已經(jīng)被移動(dòng)了,但未被刪除的時(shí)候,就會(huì)在這里進(jìn)行處理

for (EACH_HEADER) {
        if (! mustReadClasses(hi, hasDyldRoots)) {
            // Image is sufficiently optimized that we need not call readClass()
            continue;
        }

        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];
            Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);

            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.
                resolvedFutureClasses = (Class *)
                    realloc(resolvedFutureClasses, 
                            (resolvedFutureClassCount+1) * sizeof(Class));
                resolvedFutureClasses[resolvedFutureClassCount++] = newCls;
            }
        }
    }
  • 通過(guò)斷點(diǎn)調(diào)試,在未執(zhí)行readClass方法前,cls只是一個(gè)地址
  • 在執(zhí)行完readClass方法之后,newCls是一個(gè)類的名稱
    readClass.png

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

4、修復(fù)重映射一些沒(méi)有被鏡像文件加載進(jìn)來(lái)的類

主要是將未映射的Class 和Super 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í)行的
//4、修復(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");
5、修復(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
6、當(dāng)類里面有協(xié)議時(shí):readProtocol 讀取協(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");
7、修復(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");
8、分類處理

分類的加載,會(huì)在后面的文章中介紹...

// 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、類的加載處理

主要是實(shí)現(xiàn)類的加載處理,實(shí)現(xiàn)非懶加載類

  • 通過(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)榍懊?中的readClass讀取到內(nèi)存的僅僅只有地址+名稱,類的data數(shù)據(jù)并沒(méi)有加載出來(lái)

// when other threads call the new category code before
    // this thread finishes its fixups.

    // +load handled by prepare_load_methods()

    // Realize non-lazy classes (for +load methods and static instances)
    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);

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

    ts.log("IMAGE TIMES: realize non-lazy classes");
10、沒(méi)有被處理的類,優(yōu)化那些被侵犯的類

主要是實(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();
    }

接下來(lái) 我們需要重點(diǎn)關(guān)注一下readClass以及realizeClassWithoutSwift這兩個(gè)方法。

readClass:讀取類

readClass主要是去讀取類,在未執(zhí)行readClass之前,cls只是一個(gè)地址,在執(zhí)行完readClass之后,返回的newCls已經(jīng)有了名稱。

  • 為了讓自己定義的LGPerson類進(jìn)來(lái),我們開(kāi)readClass源碼里面寫(xiě)了一些判斷條件
   // 如果想自定義的類進(jìn)入,自己加一個(gè)判斷
    const char *LGPersonName = "LGPerson";
    if (strcmp(mangledName, LGPersonName) == 0) {
        auto kc_ro = (const class_ro_t *)cls->data();
        printf("%s -- 研究重點(diǎn)--%s\n", __func__,mangledName);
    }
  • readClass源碼實(shí)現(xiàn)如下,關(guān)鍵代碼是addNamedClass和addClassTableEntry
Class readClass(Class cls, bool headerIsBundle, bool headerIsPreoptimized)
{
    const char *mangledName = cls->mangledName();

    const char *LGPersonName = "LGPerson";
    if (strcmp(mangledName, LGPersonName) == 0) {
        auto kc_ro = (const class_ro_t *)cls->data();
        printf("%s -- 研究重點(diǎn)--%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();
    Class replacing = nil;
   //判斷是不是后期要處理的類
    //正常情況下,不會(huì)走到popFutureNamedClass,因?yàn)檫@是專門針對(duì)未來(lái)待處理的類的操作
    //通過(guò)斷點(diǎn)調(diào)試,不會(huì)走到if流程里面,因此也不會(huì)對(duì)ro、rw進(jìn)行操作
    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_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;
    }
    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);
    }
    // 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)檫@是專門針對(duì)未來(lái)待處理的類的操作,也可以通過(guò)斷點(diǎn)調(diào)試,可知不會(huì)走到if流程里面,因此也不會(huì)對(duì)ro、rw進(jìn)行操作
  • 通過(guò)addNamedClass將當(dāng)前類添加到已經(jīng)創(chuàng)建好的gdb_objc_realized_classes哈希表,該表用于存放所有類
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());
}
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)
        //添加到allocatedClasses哈希表
        addClassTableEntry(cls->ISA(), false);
}

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

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方法化類
【第一步】:讀取data數(shù)據(jù)

讀取class的data數(shù)據(jù),并將其強(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ì)變成 ditry 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.
    rw = cls->data(); //dirty memory 進(jìn)行賦值
    ro = cls->data()->ro();
    ASSERT(!isMeta);
    cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
} else { //此時(shí)將數(shù)據(jù)讀取進(jìn)來(lái)了,也賦值完畢了
    // Normal class. Allocate writeable class data.
    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形式
}
【第二步】遞歸調(diào)用 realizeClassWithoutSwift 完善 繼承鏈

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

  • 遞歸調(diào)用 realizeClassWithoutSwift設(shè)置父類、元類
  • 設(shè)置父類和元類的isa指向
  • 通過(guò)addSubclassaddRootClass設(shè)置父子的雙向鏈表指向關(guān)系,即父類中可以找到子類,子類中可以找到父類
    //遞歸調(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。 所以根元類的isa雖然指向己,但此時(shí)根元類已經(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
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;

斷點(diǎn)調(diào)試 realizeClassWithoutSwift

  • 在LGPerson中重寫(xiě)+load函數(shù)


    load.png
  • realizeClassWithoutSwift方法中增加自定義邏輯


  • 運(yùn)行程序,讓LGPerson進(jìn)到_read_Images里面


  • 跳轉(zhuǎn)到下一個(gè)斷點(diǎn),進(jìn)入realizeClassWithoutSwift, 并且此時(shí)的類就是LGPerson


  • 繼續(xù)在auto ro =加斷點(diǎn),繼續(xù)運(yùn)行,斷住 -- 這部分主要是讀取data


  • 查看ro,其中auto isMeta = ro->flags & RO_META; //判斷元類


  • 在rw->set_ro(ro);處加斷點(diǎn),斷住,查看rw,此時(shí)的rw是0x0,查看rw,其中包括ro 和 rwe

  • 通過(guò)x/4gx cls ,查看cls內(nèi)存情況,此時(shí)bits值為0


    圖片.png
  • 繼續(xù)運(yùn)行,然后查看x/4gx cls,此時(shí)bits還是為0x0

  • 這里我們需要去查看set_ro的源碼實(shí)現(xiàn),其路徑為:set_ro -- set_ro_or_rwe(找到 get_ro_or_rwe,是通過(guò)ro_or_rw_ext_t類型從ro_or_rw_ext中獲?。?-- ro_or_rw_ext_t中的ro


通過(guò)源碼可知ro的獲取主要分兩種情況:有沒(méi)有運(yùn)行時(shí)

  • 如果有運(yùn)行時(shí),從rw中讀取
  • 反之,如果沒(méi)有運(yùn)行時(shí),從ro中讀取

methodizeClass:方法化類

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

  • 將屬性列表、方法列表、協(xié)議列表等貼到rwe中
  • 附加分類中的方法(將在后面的文章中進(jìn)行解釋說(shuō)明)
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);

    ....
}
方法如何排序
  • 進(jìn)入prepareMethodLists的源碼實(shí)現(xiàn),其內(nèi)部是通過(guò)fixupMethodList方法排序
  • 通過(guò)fixupMethodList找到SortBySELAddress
  • 在SortBySELAddress方法里面return lhs.name < rhs.name ,我們知道方法的排序是根據(jù)method_t里面的name的地址進(jìn)行排序
prepareMethodLists(Class cls, method_list_t **addedLists, int addedCount,
                   bool baseMethods, bool methodsFromBundle)
{
    runtimeLock.assertLocked();
    if (addedCount == 0) return;
    if (baseMethods) {
        ASSERT(cls->hasCustomAWZ() && cls->hasCustomRR() && cls->hasCustomCore());
    }
    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(method_list_t *mlist, bool bundleCopy, bool sort)
{
    runtimeLock.assertLocked();
    ASSERT(!mlist->isFixedUp());
    if (!mlist->isUniqued()) {
        mutex_locker_t lock(selLock);
    
        // Unique selectors in list.
        for (auto& meth : *mlist) {
            const char *name = sel_cname(meth.name);
            meth.name = sel_registerNameNoLock(name, bundleCopy);
        }
    }
    // Sort by selector address.
    if (sort) {
        method_t::SortBySELAddress sorter;
        std::stable_sort(mlist->begin(), mlist->end(), sorter);
    }
    
    // Mark method list as uniqued and sorted
    mlist->setFixedUp();
}
    struct SortBySELAddress :
        public std::binary_function<const method_t&,
                                    const method_t&, bool>
    {
        bool operator() (const method_t& lhs,
                         const method_t& rhs)
        { return lhs.name < rhs.name; }
    };
};
attachLists

通過(guò)rwe->methods.attachLists(&list, 1),從list中添加方法列表到rwe的methods中

method_list_t *list = ro->baseMethods();
    if (list) {
        prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls));
        if (rwe) rwe->methods.attachLists(&list, 1);
    }

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;
            setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
            array()->count = newCount;
            memmove(array()->lists + addedCount, array()->lists, 
                    oldCount * sizeof(array()->lists[0]));
            memcpy(array()->lists, addedLists, 
                   addedCount * sizeof(array()->lists[0]));
        }
        else if (!list  &&  addedCount == 1) {
            // 0 lists -> 1 list
            list = addedLists[0];
        } 
        else {
            // 1 list -> many lists
            List* 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;
            memcpy(array()->lists, addedLists, 
                   addedCount * sizeof(array()->lists[0]));
        }
    }

通過(guò)對(duì)源碼的分析:
attachLists方法主要是將類 和 分類 的數(shù)據(jù)加載到rwe中

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

懶加載類和非懶加載類

區(qū)別: 非懶加載類實(shí)現(xiàn)了+load方法,而懶加載類沒(méi)有

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


最后編輯于
?著作權(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ù)。

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