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

在上一篇文章iOS-底層原理14:dyld與objc的關(guān)聯(lián) 中理解了dyld與objc的關(guān)聯(lián),本文的主要目的是理解類的相關(guān)信息是如何加載到內(nèi)存的。

本文重點需要理解map_imagesload_image

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

1.1 map_images的調(diào)用

_dyld_objc_notify_register(&map_images, load_images, unmap_image);

為什么map_images&,而load_images不帶?

  • map_images引用類型;
  • load_image值類型;

1.2 map_images源碼

step1: 進(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);
}

其中關(guān)鍵函數(shù)map_images_nolock

step2: 進(jìn)入map_images_nolock源碼

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;
    //代碼塊:作用域,進(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]);
        }
    }
}

其中關(guān)鍵代碼_read_images

step3: 查看_read_images源碼,由于代碼過多,就在下面局部分析時貼上關(guān)鍵代碼

_read_images主要是主要是加載類信息,即、分類、協(xié)議等,進(jìn)入_read_images源碼實現(xiàn),主要分為以下幾部分:

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

源碼局部分析
1、條件控制進(jìn)行的一次加載
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");
}

在沒有執(zhí)行 if 條件時會進(jìn)入該流程中,通過NXCreateMapTable 創(chuàng)建表,存放類信息,即創(chuàng)建一張類的哈希表gdb_objc_realized_classes,其目的是為了類查找方便、快捷

查看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的混亂問題
// 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;
            }
        }
    }
}
測試一下@selector的混亂問題

我們可以看到兩個方法的名稱相同,但是方法的地址卻不相同

為什么會這樣?

是因為,我們整個蘋果系統(tǒng)中,會有很多庫,比如 libobjc、 libsystem 等等,當(dāng)不同庫有相同方法時,比如上圖的 class 方法的時候,我們就需要將方法平移到程序的最前面進(jìn)行執(zhí)行,例如 CoreFoundation 的 class 方法的 index = 0,而 CoreMedia 的 class 方法 index = 0 + CoreFoundation 的大小。所以我們要將方法進(jìn)行平移操作。

3、錯誤混亂的類處理

主要是從Mach-O中取出所有類,在遍歷進(jìn)行處理

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

step1:readClass方法前打一個斷點,等程序運行到此處,打印下cls信息

可以看到cls只是一個地址

step2: 繼續(xù)執(zhí)行

可以看到,readClass調(diào)用后,對 cls 進(jìn)行了類名的賦值操作。此時類的信息目前僅存儲了地址名稱。

readClass 的源碼后面會摘出來分析

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

主要是將未映射的ClassSuper Class進(jìn)行重映射,其中:

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

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

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

5、 修復(fù)一些消息
#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ù)指針進(jìn)行注冊,并fix為新的函數(shù)指針
        for (i = 0; i < count; i++) {
            fixupMessageRef(refs+i);
        }
    }

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

主要是通過_getObjc2MessageRefs 獲取Mach-O的靜態(tài)段__objc_msgrefs,并遍歷通過fixupMessageRef將函數(shù)指針進(jìn)行注冊,并fix為新的函數(shù)指針

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

通過_getObjc2ProtocolList 獲取到Mach-O中的靜態(tài)段__objc_protolist協(xié)議列表,即從編譯器中讀取并初始化protocol

7、 修復(fù)沒有被加載的協(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");

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

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

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

9、 類的加載處理
// Realize non-lazy classes (for +load methods and static instances) 初始化非懶加載類,進(jìn)行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");

主要是實現(xiàn)類的加載處理,實現(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ù)并沒有加載出來

10、 沒有被處理的類,優(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");
            }
            //實現(xiàn)類
            realizeClassWithoutSwift(cls, nil);
            cls->setInstancesRequireRawIsaRecursively(false/*inherited*/);
        }
        free(resolvedFutureClasses);
    }

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

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

1.3 重要方法分析

1.3.1 readClass:讀取類
/***********************************************************************
* 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();//名字
    
    //  ----如果想進(jìn)入自定義,自己加一個判斷
    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進(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)過調(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;
}

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

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

step1: 通過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
        }
    }

step2: 當(dāng)前類的父類中若有丟失的weak-linked類,則返回nil

step3: 判斷是不是后期需要處理的類,在正常情況下,不會走到popFutureNamedClass,因為這是專門針對未來待處理的類的操作,也可以通過斷點調(diào)試,可知不會走到if流程里面,因此也不會對ro、rw進(jìn)行操作

  • datamach-O的數(shù)據(jù),并不在class的內(nèi)存

  • ro的賦值是從mach-O中的data強(qiáng)轉(zhuǎn)賦值

  • rw里的ro是從ro復(fù)制過去的

step4: 通過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());
}

step5: 通過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ù)還未讀取出來

1.3.2 realizeClassWithoutSwift:實現(xiàn)類

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

realizeClassWithoutSwift方法主要作用是實現(xiàn)類,將類的data數(shù)據(jù)加載到內(nèi)存中,主要有以下幾部分操作:

  • 【第一步】讀取data數(shù)據(jù),并設(shè)置rorw
  • 【第二步】遞歸調(diào)用realizeClassWithoutSwift完善繼承鏈
  • 【第三步】通過methodizeClass方法化類
第一步:讀取data數(shù)據(jù)

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

  • ro 表示 readOnly,即只讀,其在編譯時就已經(jīng)確定了內(nèi)存,包含類名稱、方法、協(xié)議和實例變量的信息,由于是只讀的,所以屬于Clean Memory,而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,即類的額外信息。其中rw就屬于dirty memory,而 dirty memory是指在進(jìn)程運行時會發(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 進(jìn)行賦值
    ro = cls->data()->ro();
    ASSERT(!isMeta);
    cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
} else { //此時將數(shù)據(jù)讀取進(jìn)來了,也賦值完畢了
    // 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指向

  • 通過addSubclass 和 addRootClass設(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中對類在表中進(jìn)行查找的操作,如果表中已有該類,則返回一個空值;如果沒有則返回當(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;
斷點調(diào)試 realizeClassWithoutSwift

如果我們需要跟蹤自定義類,同樣需要_read_images方法中的第九步的realizeClassWithoutSwift調(diào)用前,以及realizeClassWithoutSwift方法中增加自定義邏輯,主要是為了方便調(diào)試自定義類

  • _read_images方法中的第九步的realizeClassWithoutSwift調(diào)用前增加自定義邏輯
最后編輯于
?著作權(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ù)。

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

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