iOS-類的加載(上)

前言

在之前的文章dyld與objc的關(guān)聯(lián)分析削罩,我們分析了_objc_init方法中的各個(gè)初始化方法及
_dyld_objc_notify_register方法與dyld鏈接之間的關(guān)系哮内,那么接下來我們就探究一下的相關(guān)信息是如何加載到內(nèi)存的以及懶加載類非懶加載類

map_images分析

在上文的最后逐沙,我們分析到了map_images方法,map_images方法的主要作用是將Mach-O中的類信息加載到內(nèi)存

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

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分析

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

/***********************************************************************
* _read_images
* Perform initial processing of the headers in the linked 
* list beginning with headerList. 
*
* Called by: map_images_nolock
*
* Locking: runtimeLock acquired by map_images
**********************************************************************/
void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
{
    header_info *hi;
    uint32_t hIndex;
    size_t count;
    size_t I;
    Class *resolvedFutureClasses = nil;
    size_t resolvedFutureClassCount = 0;
    static bool doneOnce;
    bool launchTime = NO;
    TimeLogger ts(PrintImageTimes);

    runtimeLock.assertLocked();

#define EACH_HEADER \
    hIndex = 0;         \
    hIndex < hCount && (hi = hList[hIndex]); \
    hIndex++

    if (!doneOnce) {...}
    // Fix up @selector references
    static size_t UnfixedSelectors;
    {...}

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

    // Discover classes. Fix up unresolved future classes. Mark bundle classes.
    bool hasDyldRoots = dyld_shared_cache_some_image_overridden();

    for (EACH_HEADER) {...}
    ts.log("IMAGE TIMES: discover classes");

    // Fix up remapped classes
    // Class list and nonlazy class list remain unremapped.
    // Class refs and super refs are remapped for message dispatching.

    if (!noClassesRemapped()) {...}
    ts.log("IMAGE TIMES: remap classes");

#if SUPPORT_FIXUP
    // Fix up old objc_msgSend_fixup call sites
    for (EACH_HEADER) {...}
    ts.log("IMAGE TIMES: fix up objc_msgSend_fixup");
#endif

    bool cacheSupportsProtocolRoots = sharedCacheSupportsProtocolRoots();

    // Discover protocols. Fix up protocol refs.
    for (EACH_HEADER) {...}
    ts.log("IMAGE TIMES: discover protocols");

    // Fix up @protocol references
    // Preoptimized images may have the right 
    // answer already but we don't know for sure.
    for (EACH_HEADER) {...}
    ts.log("IMAGE TIMES: fix up @protocol references");

    // Discover categories. Only do this after the initial category
    // 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) {...}
    ts.log("IMAGE TIMES: discover categories");

    // Category discovery MUST BE Late to avoid potential races
    // 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) {...}
    ts.log("IMAGE TIMES: realize non-lazy classes");

    // Realize newly-resolved future classes, in case CF manipulates them
    if (resolvedFutureClasses) {...}
    ts.log("IMAGE TIMES: realize future classes");

    if (DebugNonFragileIvars) {...}
    // Print preoptimization statistics
    if (PrintPreopt) {...}

#undef EACH_HEADER
}


代碼非常長族操,400多行,這里我們把不是重點(diǎn)的代碼折疊起來比被。注釋有Fix up字段的先不看色难,已ts.log()方法為界一塊一塊的分析觀察,發(fā)現(xiàn)一共做了下面幾件事

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

接下來挨個(gè)分析:

1、條件控制進(jìn)行的一次加載

doneOnce流程中通過NXCreateMapTable 創(chuàng)建表严蓖,存放類信息薄嫡,即創(chuàng)建一張類的哈希表gdb_objc_realized_classes,其目的是為了類查找方便颗胡、快捷

if (!doneOnce) {
     
    //...省略
    
   // namedClasses
   //這個(gè)表中不包含預(yù)先優(yōu)化的類毫深。
   // 4/3是NXMapTable的裝載因子
    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的注釋說明毒姨,這個(gè)哈希表用于存儲不在共享緩存且已命名類哑蔫,無論類是否實(shí)現(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實(shí)際上是不在dyld共享緩存中的已命名類的列表弧呐,無論是否實(shí)現(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]地址不一致時(shí),需要調(diào)整為一致的
                sels[i] = sel;
            }
        }
    }
}

3鸠蚪、錯(cuò)誤混亂的類處理

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

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

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

    for (i = 0; i < count; i++) {
        Class cls = (Class)classlist[i];//此時(shí)獲取的cls只是一個(gè)地址
        Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized); //讀取類墓臭,經(jīng)過這步后,cls獲取的值才是一個(gè)名字
        //經(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");

這里有一個(gè)值得注意的地方窖维,我們通過LLDB調(diào)試榆综,發(fā)現(xiàn)了在未執(zhí)行readClass方法前,cls是一個(gè)地址铸史,而執(zhí)行過readClass方法后鼻疮,cls變成了類的名稱,所以readClass方法肯定做了些特殊的事情琳轿,這個(gè)我們稍后分析判沟!

cls前后對比

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

主要是將未映射的Class 和Super Class進(jìn)行重映射崭篡,其中

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

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

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

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

主要是通過_getObjc2MessageRefs獲取Mach-O的靜態(tài)段 __objc_msgrefs,并遍歷通過fixupMessageRef將函數(shù)指針進(jìn)行注冊蛀蜜,并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ù)指針進(jìn)行注冊滴某,并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é)議

//6、當(dāng)類里面有協(xié)議時(shí):readProtocol 讀取協(xié)議
// Discover protocols. Fix up protocol refs. 發(fā)現(xiàn)協(xié)議霎奢。修正協(xié)議參考
//遍歷所有協(xié)議列表户誓,并且將協(xié)議列表加載到Protocol的哈希表中
for (EACH_HEADER) {
    extern objc_class OBJC_CLASS_$_Protocol;
    //cls = Protocol類,所有協(xié)議和對象的結(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哈希表

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

主要是通過_getObjc2ProtocolRefs 獲取到Mach-O的靜態(tài)段 __objc_protorefs(與6中的__objc_protolist并不是同一個(gè)東西)橙依,然后遍歷需要修復(fù)的協(xié)議证舟,通過remapProtocolRef比較當(dāng)前協(xié)議和協(xié)議列表中的同一個(gè)內(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é)議列表中的同一個(gè)內(nèi)存地址的協(xié)議是否相同女责,如果不同則替換
        remapProtocolRef(&protolist[i]);//經(jīng)過代碼調(diào)試,并未執(zhí)行
    }
}

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

8创译、分類處理

主要是處理分類抵知,需要在分類初始化并將數(shù)據(jù)加載到類后才執(zhí)行,對于運(yùn)行時(shí)出現(xiàn)的分類软族,將分類的發(fā)現(xiàn)推遲推遲到對_dyld_objc_notify_register的調(diào)用完成后的第一個(gè)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、類的加載處理

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

  • 通過_getObjc2NonlazyClassList獲取Mach-O的靜態(tài)段__objc_nlclslist非懶加載類表
  • 通過addClassTableEntry將非懶加載類插入類表掖疮,存儲到內(nèi)存,如果已經(jīng)添加就不會(huì)載添加颗祝,需要確保整個(gè)結(jié)構(gòu)都被添加
  • 通過realizeClassWithoutSwift實(shí)現(xiàn)當(dāng)前的類浊闪,因?yàn)榍懊?中的readClass讀取到內(nèi)存的僅僅只有地址+名稱,類的data數(shù)據(jù)并沒有加載出來
// Realize non-lazy classes (for +load methods and static instances) 初始化非懶加載類螺戳,進(jìn)行rw搁宾、ro等操作:realizeClassWithoutSwift
    //懶加載類 -- 別人不動(dòng)我,我就不動(dòng)
    //實(shí)現(xiàn)非懶加載的類倔幼,對于load方法和靜態(tài)實(shí)例變量
    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: 這個(gè)是我要研究的 %s \n",LGPersonName);
             }
            
            if (!cls) continue;

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

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

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

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

主要是實(shí)現(xiàn)沒有被處理的類,優(yōu)化被侵犯的類

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

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

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

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

readClass:讀取類

readClass主要是讀取類蹄梢,在未調(diào)用該方法前疙筹,cls只是一個(gè)地址,執(zhí)行該方法后禁炒,cls是類的名稱而咆,其源碼實(shí)現(xiàn)如下,關(guān)鍵代碼是addNamedClass和addClassTableEntry幕袱,源碼實(shí)現(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();//名字
    
    // **自己加的** ----判斷自己的類
    const char *ZGPersonName = "ZGPerson";
    if (strcmp(mangledName, ZGPersonName) == 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();
//判斷是不是后期要處理的類
    //正常情況下们豌,不會(huì)走到popFutureNamedClass涯捻,因?yàn)檫@是專門針對未來待處理的類的操作
    //通過斷點(diǎn)調(diào)試浅妆,不會(huì)走到if流程里面,因此也不會(huì)對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)試涛浙,并不會(huì)走到這里
        class_rw_t *rw = newCls->data();
        const class_ro_t *old_ro = rw->ro();
        memcpy(newCls, cls, sizeof(objc_class));
        rw->set_ro((class_ro_t *)newCls->data());
        newCls->setData(rw);
        freeIfMutable((char *)old_ro->name);
        free((void *)old_ro);
        
        addRemappedClass(cls, newCls);
        
        replacing = cls;
        cls = newCls;
    }
    //判斷是否類是否已經(jīng)加載到內(nèi)存
    if (headerIsPreoptimized  &&  !replacing) {
        // class list built in shared cache
        // fixme strict assert doesn't work because of duplicates
        // ASSERT(cls == getClass(name));
        ASSERT(getClassExceptSomeSwift(mangledName));
    } else {
        addNamedClass(cls, mangledName, replacing);//加載共享緩存中的類
        addClassTableEntry(cls);//插入表康辑,即相當(dāng)于從mach-O文件 讀取到 內(nèi)存 中
    }

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

主要分為以下幾步:

    1. 通過mangledName獲取類的名字,源碼如下
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
        }
    }
    1. 當(dāng)前類的父類中若有丟失的weak-linked類,則返回nil
    1. 判斷是不是后期需要處理的類我注,在正常情況下按咒,不會(huì)走到popFutureNamedClass,這是專門針對未來待處理的類的操作但骨,也可以通過斷點(diǎn)調(diào)試胖齐,可知不會(huì)走到if流程里面,因此也不會(huì)對ro嗽冒、rw進(jìn)行操作
    1. 通過addNamedClass將當(dāng)前類添加到已經(jīng)創(chuàng)建好的gdb_objc_realized_classes哈希表呀伙,該表用于存放所有類

addNamedClass源碼

/***********************************************************************
* 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());
}
    1. 通過addClassTableEntry,將初始化的類添加到allocatedClasses表添坊,_objc_init中的runtime_init就創(chuàng)建了allocatedClasses

addClassTableEntry源碼

/***********************************************************************
* addClassTableEntry 將一個(gè)類添加到所有類的表中
* Add a class to the table of all classes. If addMeta is true,
* automatically adds the metaclass of the class as well.
* Locking: runtimeLock must be held by the caller.
**********************************************************************/
static void
addClassTableEntry(Class cls, bool addMeta = true)
{
    runtimeLock.assertLocked();

    // This class is allowed to be a known class via the shared cache or via
    // data segments, but it is not allowed to be in the dynamic table already.
    auto &set = objc::allocatedClasses.get();//開辟的類的表剿另,在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);
}

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

realizeClassWithoutSwift

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

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

    1. 讀取data數(shù)據(jù)讼稚,并設(shè)置ro、rw
    1. 遞歸調(diào)用realizeClassWithoutSwift完善繼承鏈
    1. 通過methodizeClass方法化類
// fixme verify class is not in an un-dlopened part of the shared cache?

    auto ro = (const class_ro_t *)cls->data();
    auto isMeta = ro->flags & RO_META;
    if (ro->flags & RO_FUTURE) {
        // This was a future class. rw data is already allocated.
        rw = cls->data();
        ro = cls->data()->ro();
        ASSERT(!isMeta);
        cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
    } else {
        // Normal class. Allocate writeable class data.
        rw = objc::zalloc<class_rw_t>();
        rw->set_ro(ro);
        rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
        cls->setData(rw);
    }

1. 讀取data數(shù)據(jù)

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

這里對一些名詞作出解釋:

  • ro ro 表示 readOnly,即只讀乍狐,其在編譯時(shí)就已經(jīng)確定了內(nèi)存赠摇,包含類名稱、方法、協(xié)議和實(shí)例變量的信息藕帜,由于是只讀的烫罩,所以屬于Clean Memory,而Clean Memory是指加載后不會(huì)發(fā)生更改的內(nèi)存

  • rwrw 表示 readWrite洽故,即可讀可寫嗡髓,由于其動(dòng)態(tài)性,可能會(huì)往類中添加屬性收津、方法、添加協(xié)議浊伙,在最新的2020的WWDC的對內(nèi)存優(yōu)化的說明Advancements in the Objective-C runtime - WWDC 2020 - Videos - Apple Developer中撞秋,提到rw,其實(shí)在rw中只有10%的類真正的更改了它們的方法嚣鄙,所以有了rwe吻贿,即類的額外信息。對于那些確實(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ì)向它寫入新數(shù)據(jù).

  • rw可以理解為 rw的內(nèi)存大小 = ro內(nèi)存 + rwe額外內(nèi)存信息

2. 遞歸調(diào)用realizeClassWithoutSwift完善繼承鏈

 // Realize superclass and metaclass, if they aren't already.
    // This needs to be done after RW_REALIZED is set above, for root classes.
    // This needs to be done after class index is chosen, for root metaclasses.
    // This assumes that none of those classes have Swift contents,
    //   or that Swift's initializers have already been called.
    //   fixme that assumption will be wrong if we add support
    //   for ObjC subclasses of Swift classes. --
    //遞歸調(diào)用realizeClassWithoutSwift完善繼承鏈,并處理當(dāng)前類的父類弥奸、元類
    //遞歸實(shí)現(xiàn) 設(shè)置當(dāng)前類榨惠、父類、元類的 rw盛霎,主要目的是確定繼承鏈 (類繼承鏈赠橙、元類繼承鏈)
    //實(shí)現(xiàn)元類、父類
    //當(dāng)isa找到根元類之后愤炸,根元類的isa是指向自己的期揪,不會(huì)返回nil從而導(dǎo)致死循環(huán)——remapClass中對類在表中進(jìn)行查找的操作,如果表中已有該類规个,則返回一個(gè)空值凤薛;如果沒有則返回當(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);
}

這里通過遞歸調(diào)用realizeClassWithoutSwift設(shè)置父類诞仓、元類枉侧,并設(shè)置父類和元類的isa指向,最后通過addSubclassaddRootClass設(shè)置父子的雙向鏈表指向關(guān)系狂芋,即父類中可以找到子類榨馁,子類中可以找到父類。

這里遞歸結(jié)束的條件值得注意一下:

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

當(dāng)isa找到根元類之后屑柔,根元類的isa是指向根類,根類的isa指向nil珍剑,所以有上面的遞歸終止條件掸宛,其目的是保證類只加載一次

3. 通過 methodizeClass 方法化類

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

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

    ....
}

這里將屬性列表唧瘾、方法列表、協(xié)議列表等通過attachLists方法加入到rwe中别凤,其中Attach categories.為附加分類中的方法饰序,我們下回分解。

prepareMethodLists方法排序

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

  • 進(jìn)入prepareMethodLists的源碼實(shí)現(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*/);//排序
        }
    }

    ...
}

  • 進(jìn)入fixupMethodList源碼實(shí)現(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();
}

懶加載類 和 非懶加載類

  • 懶加載:推遲到第一次消息發(fā)送的時(shí)候才加載
  • 非懶加載:當(dāng)map_images的時(shí)候,加載所有類數(shù)據(jù)的時(shí)候就加載
    其中懶加載和非懶加載的區(qū)別標(biāo)志:當(dāng)前類是否實(shí)現(xiàn)load方法

_read_images方法中的第九步的realizeClassWithoutSwift調(diào)用前增加自定義邏輯

// Category discovery MUST BE Late to avoid potential races
// 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) 是否有l(wèi)oad方法
for (EACH_HEADER) {
        classref_t const *classlist = 
            _getObjc2NonlazyClassList(hi, &count);
        for (i = 0; i < count; i++) {
            Class cls = remapClass(classlist[i]);
            if (!cls) continue;

            addClassTableEntry(cls);
            //自己增加的代碼
            const char *mangledName  = cls->mangledName();
            const char *ZGPersonName = "ZGPerson";
            
            if (strcmp(mangledName, ZGPersonName) == 0) {
                
                auto kc_rw = cls->data();
                
                printf("%s: 這個(gè)是我要研究的 %s \n",__func__,ZGPersonName);
            }

            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
            }
            realizeClassWithoutSwift(cls, nil);
        }
    }

同時(shí)在ZGPerson中增加load方法

@implementation ZGPerson
+ (void)load{

}
@end

發(fā)現(xiàn)如果增加load方法會(huì)加入我們的判斷杯巨,如果沒有load方法則不會(huì)進(jìn)入判斷

增加判斷

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蚤告,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子服爷,更是在濱河造成了極大的恐慌罩缴,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,378評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件层扶,死亡現(xiàn)場離奇詭異翻默,居然都是意外死亡巡莹,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來擎宝,“玉大人溯警,你說我怎么就攤上這事鄙煤「枥粒” “怎么了?”我有些...
    開封第一講書人閱讀 152,702評論 0 342
  • 文/不壞的土叔 我叫張陵匾旭,是天一觀的道長镣屹。 經(jīng)常有香客問我,道長价涝,這世上最難降的妖魔是什么女蜈? 我笑而不...
    開封第一講書人閱讀 55,259評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上伪窖,老公的妹妹穿的比我還像新娘逸寓。我一直安慰自己,他們只是感情好覆山,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,263評論 5 371
  • 文/花漫 我一把揭開白布竹伸。 她就那樣靜靜地躺著,像睡著了一般簇宽。 火紅的嫁衣襯著肌膚如雪勋篓。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,036評論 1 285
  • 那天魏割,我揣著相機(jī)與錄音譬嚣,去河邊找鬼。 笑死见妒,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的甸陌。 我是一名探鬼主播须揣,決...
    沈念sama閱讀 38,349評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼钱豁!你這毒婦竟也來了耻卡?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,979評論 0 259
  • 序言:老撾萬榮一對情侶失蹤牲尺,失蹤者是張志新(化名)和其女友劉穎卵酪,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體谤碳,經(jīng)...
    沈念sama閱讀 43,469評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡溃卡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,938評論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蜒简。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瘸羡。...
    茶點(diǎn)故事閱讀 38,059評論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖搓茬,靈堂內(nèi)的尸體忽然破棺而出犹赖,到底是詐尸還是另有隱情,我是刑警寧澤卷仑,帶...
    沈念sama閱讀 33,703評論 4 323
  • 正文 年R本政府宣布峻村,位于F島的核電站,受9級特大地震影響锡凝,放射性物質(zhì)發(fā)生泄漏粘昨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,257評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望雾棺。 院中可真熱鬧膊夹,春花似錦、人聲如沸捌浩。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,262評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽尸饺。三九已至进统,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間浪听,已是汗流浹背螟碎。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留迹栓,地道東北人掉分。 一個(gè)月前我還...
    沈念sama閱讀 45,501評論 2 354
  • 正文 我出身青樓,卻偏偏與公主長得像克伊,于是被迫代替她去往敵國和親酥郭。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,792評論 2 345