iOS 類的加載

本文是基于objc4-818來進(jìn)行編寫的

_objc_init

void _objc_init(void)
{
    static bool initialized = false;
    if (initialized) return;
    initialized = true;
    
    // fixme defer initialization until an objc-using image is found?
    environ_init();
    tls_init();
    static_init();
    runtime_init();
    exception_init();
#if __OBJC2__
    cache_t::init();
#endif
    _imp_implementationWithBlock_init();

    _dyld_objc_notify_register(&map_images, load_images, unmap_image);

#if __OBJC2__
    didCallDyldNotifyRegister = true;
#endif 
}
  • environ_init()
    讀取影響運(yùn)行時(shí)的環(huán)境變量靠汁。
  • tls_init()
    關(guān)于線程key的綁定 - 比如每線程數(shù)據(jù)的析構(gòu)函數(shù)
  • static_init()
    運(yùn)行C++靜態(tài)構(gòu)造函數(shù)诗轻。在dyld調(diào)用我們的靜態(tài)構(gòu)造函數(shù)之前续扔,libc 會(huì)調(diào)用_objc_init(),因此我們必須自己做
  • runtime_init()
    runtime運(yùn)行時(shí)環(huán)境初始化
  • exception_init()
    初始化libobjc的異常處理系統(tǒng)
  • cache_t::init()
    準(zhǔn)備緩存铭若,緩存初始化
  • _imp_implementationWithBlock_init()
    啟動(dòng)回調(diào)機(jī)制枫匾。通常這不會(huì)做什么,因?yàn)樗械某跏蓟?br> 是惰性的堵幽,但是對(duì)于某些進(jìn)程狗超,我們會(huì)迫不及待地加載trampolines dylib
  • _dyld_objc_notify_register(&map_images, load_images, unmap_image)
    dyld通過map_imagesload_imagesunmap_imagemacho中的類信息加載到內(nèi)存朴下,并加載類信息

_dyld_objc_notify_register(&map_images, load_images, unmap_image)

我們知道代碼編譯后會(huì)產(chǎn)生macho文件努咐,macho文件中就存儲(chǔ)了所有的符號(hào),程序的運(yùn)行殴胧,就是符號(hào)的調(diào)用結(jié)果渗稍。
代碼 → 編譯 → Macho → 內(nèi)存,我們的程序就能運(yùn)行起來了

  • map_images
    管理文件和動(dòng)態(tài)庫中的符號(hào)(class团滥、selector竿屹、category、……)
  • load_images
    加載load方法

map_images

這里的map_images前面加了&符號(hào)灸姊,是引用類型拱燃,內(nèi)部產(chǎn)生變化,外界會(huì)跟著一起變化

  • 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源碼
void 
map_images_nolock(unsigned mhCount, const char * const mhPaths[],
                  const struct mach_header * const mhdrs[])
{
    // 省略準(zhǔn)備代碼

    // Find all images with Objective-C metadata. 找出images中所有Objective-C元數(shù)據(jù)
    hCount = 0;

    // Count classes. Size various table based on the total.
    int totalClasses = 0;  //類的個(gè)數(shù)
    int unoptimizedTotalClasses = 0; // 未優(yōu)化的Classes
    {
      // 省略計(jì)算totalClasses力惯、unoptimizedTotalClasses碗誉、hCount的個(gè)數(shù)的代碼
    }

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

    firstTime = NO;
    
    // Call image load funcs after everything is set up.調(diào)用鏡像加載功能
    for (auto func : loadImageFuncs) {
        for (uint32_t i = 0; i < mhCount; i++) {
            func(mhdrs[i]);
        }
    }
}

這部分代碼召嘶,主要做一系列的準(zhǔn)備工作,其目的是找出hCount哮缺、totalClasses弄跌,unoptimizedTotalClassesread_image做準(zhǔn)備。

_read_images

_read_images主要有以下的幾部分

  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)化那些被侵犯的類
條件控制進(jìn)行的一次加載
if (!doneOnce) { // 這里只會(huì)執(zhí)行一次
        doneOnce = YES; 
        launchTime = YES;

        // ……省略各種系統(tǒng)判斷和支持
        // namedClasses
        // Preoptimized classes don't go in this table.
        // 4/3 is NXMapTable's load factor
        int namedClassesSize = 
            (isPreoptimized() ? unoptimizedTotalClasses : totalClasses) * 4 / 3;
        gdb_objc_realized_classes =
            NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize);

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

這里doneOnce只會(huì)進(jìn)來一次铛只,我們可以看到進(jìn)入這個(gè)if條件之后doneOnce就被改變?yōu)?code>YES了,然后獲取到namedClasses的大小茎匠,然后創(chuàng)建NXMapTable哈希表來快速存儲(chǔ)格仲,根據(jù)官方注釋創(chuàng)建的哈希表的大小為namedClassesSize4/3倍。

  • gdb_objc_realized_classes
    查看gdb_objc_realized_classes的源碼得知诵冒,gdb_objc_realized_classes的真正類型是NXMapTable凯肋,根據(jù)注釋,我們知道gdb_objc_realized_classes實(shí)際上是不存在與dyld共享緩存的命名列表中汽馋,無論其是否實(shí)現(xiàn)侮东,這個(gè)列表排除了懶加載類,這個(gè)列表的類必須通過getClass來獲取
// 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.
// This list excludes lazily named classes, which have to be looked up
// using a getClass hook.
NXMapTable *gdb_objc_realized_classes;  // exported for debuggers in objc-gdb.h
修復(fù)預(yù)編譯階段的@selector的混亂問題
// Fix up @selector references
    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]);
                //注冊(cè)sel操作豹芯,即將sel添加到
                SEL sel = sel_registerNameNoLock(name, isBundle);
                //當(dāng)sel與sels[i]地址不一致時(shí)悄雅,需要調(diào)整為一致的
                if (sels[i] != sel) {
                    sels[i] = sel;
                }
            }
        }
    }
    ts.log("IMAGE TIMES: fix up selector references");

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

  • _getObjc2SelectorRefs
    _getObjc2*铁蹈,從Mach_O中讀取所需信息
//      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_registerName
    通過sel_registerNameNoLock__sel_registerName探索宽闲,如果!name則返回為0的SEL,search_builtins_dyld_get_objc_selector握牧,然后去_dyld中查找容诬,如果找到了,則返回result(SEL)沿腰,沒有則做inset览徒,即將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);
    if (it.second) {
        // No match. Insert.
        *it.first = (const char *)sel_alloc(name, copy);
    }
    return (SEL)*it.first;
}
錯(cuò)誤混亂的類處理
//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");

Mach_O中獲取所有的類枫慷,遍歷所有的類,處理錯(cuò)誤混亂的類,從最后的注釋可知流礁,這里處理的都只是非懶加載類

  • cls
    這里我們看到了異常熟悉的cls,但:
    • 再?zèng)]有經(jīng)過readClass之前罗丰,即Class cls = (Class)classlist[i]時(shí)神帅,這里的cls只是一個(gè)地址
    • 經(jīng)過readClass之后,cls就轉(zhuǎn)變?yōu)橐粋€(gè)類名稱了
修復(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.
    
    if (!noClassesRemapped()) {
        for (EACH_HEADER) {
            Class *classrefs = _getObjc2ClassRefs(hi, &count);
            for (i = 0; i < count; i++) {
                remapClassRef(&classrefs[i]);
            }
            // fixme why doesn't test future1 catch the absence of this?
            classrefs = _getObjc2SuperRefs(hi, &count);
            for (i = 0; i < count; i++) {
                remapClassRef(&classrefs[i]);
            }
        }
    }

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

如果有重新映射的類萌抵,分別讀取Mach_O__objc_classrefs__objc_superrefs的符號(hào)信息找御,通過remapClass來達(dá)到修復(fù)和重新映射的目的。

修復(fù)一些消息

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

#if SUPPORT_FIXUP
    //修復(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)行注冊(cè)讨永,并fix為新的函數(shù)指針
        for (i = 0; i < count; i++) {
            fixupMessageRef(refs+i);
        }
    }

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

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

    bool isBundle = hi->isBundle();
    //通過_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");

創(chuàng)建協(xié)議表protocol_map锻霎,類型為NXMapTable著角。即NXMapTable *protocol_map = protocols();protocols()的源碼如下

static NXMapTable *protocols(void)
{
    static NXMapTable *protocol_map = nil;
    
    runtimeLock.assertLocked();

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

    return protocol_map;
}

獲取macho中的協(xié)議列表旋恼,循環(huán)遍歷通過readProtocol將協(xié)議寫入protocol_map哈希表

        protocol_t * const *protolist = _getObjc2ProtocolList(hi, &count);
        for (i = 0; i < count; i++) {
            readProtocol(protolist[i], cls, protocol_map, 
                         isPreoptimized, isBundle);
        }
修復(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 && hi->isPreoptimized())
            continue;
        protocol_t **protolist = _getObjc2ProtocolRefs(hi, &count);
        for (i = 0; i < count; i++) {
            remapProtocolRef(&protolist[i]);
        }
    }

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

獲取macho中靜態(tài)段__objc_protorefs的內(nèi)容吏口,通過remapProtocolRef來修復(fù)未加載的協(xié)議。

分類的處理
    // 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) {
        for (EACH_HEADER) {
            load_categories_nolock(hi);
        }
    }

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

發(fā)現(xiàn)分類冰更。只有在分類的初始化才能這樣做产徊。對(duì)于在啟動(dòng)時(shí)出現(xiàn)的類別,發(fā)現(xiàn)延遲到對(duì)_dyld_objc_notify_register的調(diào)用完成后的第一次load_images調(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)
    for (EACH_HEADER) {
        classref_t const *classlist = hi->nlclslist(&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
            }
            realizeClassWithoutSwift(cls, nil);
        }
    }

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

加載非懶加載類

  • classref_t const *classlist = hi->nlclslist(&count)冬殃,獲取macho中非懶加載類表
  • 通過remapClass來判斷當(dāng)前非懶加載類的指針是否已經(jīng)存在
    • 如果不存在囚痴,則通過addClassTableEntry加當(dāng)前非懶加載類插入類表,通過realizeClassWithoutSwift實(shí)現(xiàn)當(dāng)前的類
沒有被處理的類审葬,優(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();
    }

readClass

讀取類深滚,我們?cè)?strong>混亂類的處理中,通過readClass涣觉,我們由一個(gè)地址得到了類的名稱痴荐。其源碼如下:

/***********************************************************************
* 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->nonlazyMangledName();
    
    const char *practiseName = "Person";
    if (strcmp(mangledName, practiseName) == 0) { 
        printf("-------- %s", 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->setSuperclass(nil);
        return nil;
    }
    
    cls->fixupBackwardDeployingStableSwift();

    // 判斷是不是后期需要處理的類
    // 正常情況下官册,不會(huì)走到popFutureNamedClass生兆,因?yàn)檫@是專門針對(duì)未來待處理的類的操作
    // 通過斷點(diǎn)調(diào)試,不會(huì)走到if流程里面膝宁,因此也不會(huì)對(duì)ro鸦难、rw進(jìn)行操作
    Class replacing = nil;
    if (mangledName != nullptr) {
        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));

            // Manually set address-discriminated ptrauthed fields
            // so that newCls gets the correct signatures.
            newCls->setSuperclass(cls->getSuperclass());
            newCls->initIsa(cls->getIsa());

            rw->set_ro((class_ro_t *)newCls->data());
            newCls->setData(rw);
            freeIfMutable((char *)old_ro->getName());
            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(mangledName == nullptr || getClassExceptSomeSwift(mangledName));
    } else {
        if (mangledName) { //some Swift generic classes can lazily generate their names
            //加載共享緩存中的類
            addNamedClass(cls, mangledName, replacing);
        } else {
            Class meta = cls->ISA();
            const class_ro_t *metaRO = meta->bits.safe_ro();
            ASSERT(metaRO->getNonMetaclass() && "Metaclass with lazy name must have a pointer to the corresponding nonmetaclass.");
            ASSERT(metaRO->getNonMetaclass() == cls && "Metaclass nonmetaclass pointer must equal the original class.");
        }
        //插入表击敌,即相當(dāng)于從mach-O文件 讀取到 內(nèi)存 中
        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;
}
  • 通過cls->nonlazyMangledName()獲取類名
    // Get the class's mangled name, or NULL if the class has a lazy
    // name that hasn't been created yet.
    const char *nonlazyMangledName() const {
        return bits.safe_ro()->getName();
    }

從注釋我們知道,這里獲取的是非懶加載類的類名拴事,如果是懶加載類則會(huì)返回NULL沃斤,這里與之前版本的源碼有所區(qū)別

  • 當(dāng)前類的父類中若有丟失的weak-linked類,則返回nil
  • 判斷是不是后期需要處理的類刃宵,在正常情況下衡瓶,不會(huì)走到popFutureNamedClass,因?yàn)檫@是專門針對(duì)未來待處理的類的操作牲证,也可以通過斷點(diǎn)調(diào)試哮针,可知不會(huì)走到if流程里面,因此也不會(huì)對(duì)ro从隆、rw進(jìn)行操作
    • datamacho中的數(shù)據(jù)诚撵,并不存在class內(nèi)存中
    • ro的賦值是從macho中的data強(qiáng)轉(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表寿烟,allocatedClasses_objc_init中的runtime_init就創(chuàng)建了。
/***********************************************************************
* 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();

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

    if (!isKnownClass(cls))
        set.insert(cls);
    if (addMeta)
        addClassTableEntry(cls->ISA(), false);
}

總結(jié)
所以綜上所述辛燥,readClass的主要作用就是將macho中的非懶加載類讀取到內(nèi)存筛武,即插入表中,但是目前的類僅有兩個(gè)信息:地址以及名稱挎塌,而macho的其中的data數(shù)據(jù)還未讀取出來

realizeClassWithoutSwift

realizeClassWithoutSwift中有ro徘六,rw的相關(guān)操作,realizeClassWithoutSwift的作用是實(shí)現(xiàn)類榴都,將類的data加載到內(nèi)存中

1. 讀取data數(shù)據(jù)
// 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)來了竿音,也賦值完畢了
    // Normal class. Allocate writeable class data.
    rw = objc::zalloc<class_rw_t>(); //申請(qǐng)開辟zalloc -- rw
    rw->set_ro(ro);//rw中的ro設(shè)置為臨時(shí)變量ro
    rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
    cls->setData(rw);//將cls的data賦值為rw形式
}

讀取classdata數(shù)據(jù),賦值rw拴驮,ro

  • ro表示readOnly春瞬,即只讀,其在編譯時(shí)就已經(jīng)確定了內(nèi)存套啤,包含類名稱宽气、方法、協(xié)議和實(shí)例變量的信息,由于是只讀的萄涯,所以屬于Clean Memory绪氛,而Clean Memory是指加載后不會(huì)發(fā)生更改的內(nèi)存
  • rw 表示 readWrite,即可讀可寫涝影,由于其動(dòng)態(tài)性钞楼,可能會(huì)往類中添加屬性、方法袄琳、添加協(xié)議,在2020的WWDC的對(duì)內(nèi)存優(yōu)化的說明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ì)向它寫入新數(shù)據(jù),例如創(chuàng)建一個(gè)新的方法緩存召调,并從類中指向它
2. 確定類的繼承鏈膨桥,及isa鏈
  • supercls = realizeClassWithoutSwift(remapClass(cls->getSuperclass()), nil)確定父類
  • metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil)確定元類
    // 調(diào)用realizeClassWithoutSwift查找父類和元類
    supercls = realizeClassWithoutSwift(remapClass(cls->getSuperclass()), nil);
    metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);

  • realizeClassWithoutSwift的開頭有如下代碼,通過對(duì)查找類是否已實(shí)現(xiàn)的判斷唠叛,來防止無限循環(huán)找下的情況發(fā)生
    // 如果沒有找到只嚣,則返回nil
    // 如果類以初始化,則返回cls
    if (!cls) return nil;
    if (cls->isRealized()) {
        validateAlreadyRealizedClass(cls);
        return cls;
    }

  • 如果類沒有找到艺沼,則返回nil册舞,我們知道即NSObject的父類是nil,元類是通過isa來確定其繼承關(guān)系障般,rootmateclsisa指向的還是自己调鲸,所以這里元類不會(huì)返回nil
  • 判斷當(dāng)前的cls是否已實(shí)現(xiàn)
    // Locking: To prevent concurrent realization, hold runtimeLock.
    bool isRealized() const {
        return !isStubClass() && (data()->flags & RW_REALIZED);
    }

這里我們可以知道,判斷一個(gè)類是否已經(jīng)完成實(shí)現(xiàn)剩拢,其實(shí)就是在看其是否已近完成了rw的實(shí)現(xiàn)

  • 如果類已實(shí)現(xiàn)线得,驗(yàn)證其實(shí)現(xiàn),并返回該類
static void validateAlreadyRealizedClass(Class cls) {
    ASSERT(cls->isRealized());
#if TARGET_OS_OSX
    class_rw_t *rw = cls->data();
    size_t rwSize = malloc_size(rw);

    // Note: this check will need some adjustment if class_rw_t's
    // size changes to not match the malloc bucket.
    if (rwSize != sizeof(class_rw_t))
        _objc_fatal("realized class %p has corrupt data pointer %p", cls, rw);
#endif
}

這里我們?cè)俅悟?yàn)證了判斷類的實(shí)現(xiàn)其實(shí)就是在對(duì)其的rw進(jìn)行驗(yàn)證

  • 如果沒有實(shí)現(xiàn)徐伐,則會(huì)回到這里的第一步讀取data數(shù)據(jù)

  • 完成當(dāng)前需要實(shí)現(xiàn)類的父類及元類的重新映射
    // Update superclass and metaclass in case of remapping
    // 重新映射并設(shè)置父類和初始化其元類
    cls->setSuperclass(supercls);
    cls->initClassIsa(metacls);
  • setSuperclass重新映射父類
    void setSuperclass(Class newSuperclass) {
#if ISA_SIGNING_SIGN_MODE == ISA_SIGNING_SIGN_ALL
        superclass = (Class)ptrauth_sign_unauthenticated((void *)newSuperclass, ISA_SIGNING_KEY, ptrauth_blend_discriminator(&superclass, ISA_SIGNING_DISCRIMINATOR_CLASS_SUPERCLASS));
#else
        superclass = newSuperclass;
#endif
    }
  • initClassIsa給當(dāng)前類設(shè)置元類

  • 如果supercls存在贯钩,則將cls加入父類的子類列表中
  • 如果supercls不存在,則將cls作為根類
    // 將類鏈接到父類的子類列表
    // Connect this class to its superclass's subclass lists
    if (supercls) {
        addSubclass(supercls, cls);
    } else {
        addRootClass(cls);
    }

3. 通過methodizeClass修復(fù)類的方法列表、協(xié)議列表角雷、屬性列表
/***********************************************************************
* methodizeClass
* Fixes up cls's method list, protocol list, and property list.
* Attaches any outstanding categories.
* Locking: runtimeLock must be held by the caller
**********************************************************************/
static void methodizeClass(Class cls, Class previously)
{
    runtimeLock.assertLocked();

    bool isMeta = cls->isMetaClass();
    auto rw = cls->data();
    auto ro = rw->ro();
    auto rwe = rw->ext();

    // Methodizing for the first time
    if (PrintConnecting) {
        _objc_inform("CLASS: methodizing class '%s' %s", 
                     cls->nameForLogging(), isMeta ? "(meta)" : "");
    }

    // Install methods and properties that the class implements itself.
    method_list_t *list = ro->baseMethods();
    if (list) {
        prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls), nullptr);
        if (rwe) rwe->methods.attachLists(&list, 1);
    }

    property_list_t *proplist = ro->baseProperties;
    if (rwe && proplist) {
        rwe->properties.attachLists(&proplist, 1);
    }

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

#if DEBUG
    // Debug: sanity-check all SELs; log method list contents
    for (const auto& meth : rw->methods()) {
        if (PrintConnecting) {
            _objc_inform("METHOD %c[%s %s]", isMeta ? '+' : '-', 
                         cls->nameForLogging(), sel_getName(meth.name()));
        }
        ASSERT(sel_registerName(sel_getName(meth.name())) == meth.name());
    }
#endif
}
將ro的方法列表加到rw中
  1. 從ro中獲取到方法列表
    // Install methods and properties that the class implements itself.
    method_list_t *list = ro->baseMethods();
    if (list) {
        prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls), nullptr);
        if (rwe) rwe->methods.attachLists(&list, 1);
    }
  1. 調(diào)用prepareMethodLists將方法寫入方法列表
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.setName(sel_registerNameNoLock(name, bundleCopy));
        }
    }

    // Sort by selector address.
    // Don't try to sort small lists, as they're immutable.
    // Don't try to sort big lists of nonstandard size, as stable_sort
    // won't copy the entries properly.
    if (sort && !mlist->isSmallList() && mlist->entsize() == method_t::bigSize) {
        method_t::SortBySELAddress sorter;
        std::stable_sort(&mlist->begin()->big(), &mlist->end()->big(), sorter);
    }
    
    // Mark method list as uniqued and sorted.
    // Can't mark small lists, since they're immutable.
    if (!mlist->isSmallList()) {
        mlist->setFixedUp();
    }
}


static void 
prepareMethodLists(Class cls, method_list_t **addedLists, int addedCount,
                   bool baseMethods, bool methodsFromBundle, const char *why)
{
    runtimeLock.assertLocked();

    if (addedCount == 0) return;
    // 省略部分代碼
    // 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*/);
        }
    }
    // 省略部分代碼
}
  1. 調(diào)用fixupMethodList通過SELAddress對(duì)方法進(jìn)行排序
static void 
fixupMethodList(method_list_t *mlist, bool bundleCopy, bool sort)
{
    runtimeLock.assertLocked();
    ASSERT(!mlist->isFixedUp());

    // Sort by selector address.
    // Don't try to sort small lists, as they're immutable.
    // Don't try to sort big lists of nonstandard size, as stable_sort
    // won't copy the entries properly.
    if (sort && !mlist->isSmallList() && mlist->entsize() == method_t::bigSize) {
        method_t::SortBySELAddress sorter;
        std::stable_sort(&mlist->begin()->big(), &mlist->end()->big(), sorter);
    }
   
}
  1. 如果rwe存在祸穷,則調(diào)用attachListslist寫入rwe
如果有屬性且存在rwe,將屬性列表寫入rwe
    property_list_t *proplist = ro->baseProperties;
    if (rwe && proplist) {
        rwe->properties.attachLists(&proplist, 1);
    }
如果有協(xié)議且存在rwe勺三,將協(xié)議列表寫入rwe
    protocol_list_t *protolist = ro->baseProtocols;
    if (rwe && protolist) {
        rwe->protocols.attachLists(&protolist, 1);
    }
添加分類
void attachToClass(Class cls, Class previously, int flags)
{
    runtimeLock.assertLocked();
    ASSERT((flags & ATTACH_CLASS) ||
           (flags & ATTACH_METACLASS) ||
           (flags & ATTACH_CLASS_AND_METACLASS));
    
    auto &map = get();
    auto it = map.find(previously);//找到一個(gè)分類進(jìn)來一次雷滚,即一個(gè)個(gè)加載分類,不要混亂

    if (it != map.end()) {//這里會(huì)走進(jìn)來:當(dāng)主類沒有實(shí)現(xiàn)load吗坚,分類開始加載祈远,迫使主類加載,會(huì)走到if流程里面
        category_list &list = it->second;
        if (flags & ATTACH_CLASS_AND_METACLASS) {//判斷是否是元類
            int otherFlags = flags & ~ATTACH_CLASS_AND_METACLASS;
            attachCategories(cls, list.array(), list.count(), otherFlags | ATTACH_CLASS);//實(shí)例方法
            attachCategories(cls->ISA(), list.array(), list.count(), otherFlags | ATTACH_METACLASS);//類方法
        } else {
            //如果不是元類商源,則只走一次 attachCategories
            attachCategories(cls, list.array(), list.count(), flags);
        }
        map.erase(it);
    }
}
attachCategories將分類的方法车份、屬性、協(xié)議添加到主類中
// Attach method lists and properties and protocols from categories to a class.
// Assumes the categories in cats are all loaded and sorted by load order, 
// oldest categories first.
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);
    auto rwe = cls->data()->extAllocIfNeeded();

    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) {
                prepareMethodLists(cls, mlists, mcount, NO, fromBundle, __func__);
                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, __func__);
        rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
        if (flags & ATTACH_EXISTING) {
            flushCaches(cls, __func__, [](Class c){
                // constant caches have been dealt with in prepareMethodLists
                // if the class still is constant here, it's fine to keep
                return !c->cache.isConstantOptimizedCache();
            });
        }
    }

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

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

通過上述源碼牡彻,我們可以發(fā)現(xiàn)這里操作的都是rwe扫沼,rwe = cls->data()->extAllocIfNeeded(),在本類中也有rwe庄吼,但是我們發(fā)現(xiàn)缎除,本類的屬性及協(xié)議會(huì)存在rwe中,如果存在rwe总寻,則方法列表也會(huì)添加到rwe中器罐。

  • 如果本類本來就存在rwe,則直接使用
  • 如果本類不存在rwe, 則開辟
class_rw_ext_t *extAllocIfNeeded() {
    auto v = get_ro_or_rwe();
    if (fastpath(v.is<class_rw_ext_t *>())) { //判斷rwe是否存在
        return v.get<class_rw_ext_t *>();//如果存在渐行,則直接獲取
    } else {
        return extAlloc(v.get<const class_ro_t *>());//如果不存在則進(jìn)行開辟
    }
}

??//extAlloc源碼實(shí)現(xiàn)
class_rw_ext_t *
class_rw_t::extAlloc(const class_ro_t *ro, bool deepCopy)
{
    runtimeLock.assertLocked();

    auto rwe = objc::zalloc<class_rw_ext_t>();

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

這里我們可以看到首先是加載的本類的baseMethods技矮,然后是baseProperties,再然后是baseProtocols殊轴,最后返回rwe


小結(jié)
rwe會(huì)伴隨屬性衰倦、協(xié)議、分類的產(chǎn)生而產(chǎn)生旁理;

attachLists將方法寫入rwe
void attachLists(List* const * addedLists, uint32_t addedCount) {
    if (addedCount == 0) return;

    if (hasArray()) {
        // many lists -> many lists
        //計(jì)算數(shù)組中舊lists的大小
        uint32_t oldCount = array()->count;
        //計(jì)算新的容量大小 = 舊數(shù)據(jù)大小+新數(shù)據(jù)大小
        uint32_t newCount = oldCount + addedCount;
        //根據(jù)新的容量大小樊零,開辟一個(gè)數(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ù)大小 * 單個(gè)舊list大小
        memmove(array()->lists + addedCount, array()->lists, 
                oldCount * sizeof(array()->lists[0]));
        //新數(shù)據(jù)從數(shù)組 首位置開始存儲(chǔ),存放新的lists芋哭,大小為 新數(shù)據(jù)大小 * 單個(gè)list大小
        memcpy(
               array()->lists, addedLists, 
               addedCount * sizeof(array()->lists[0]));
    }
    else if (!list  &&  addedCount == 1) {
        // 0 lists -> 1 list
        list = addedLists[0];//將list加入mlists的第一個(gè)元素沉衣,此時(shí)的list是一個(gè)一維數(shù)組
        validate();
    } 
    else {
        // 1 list -> many lists 有了一個(gè)list,有往里加很多l(xiāng)ist
        //新的list就是分類减牺,來自LRU的算法思維豌习,即最近最少使用
        //獲取舊的list
        List* oldList = list;
        uint32_t oldCount = oldList ? 1 : 0;
        //計(jì)算容量和 = 舊list個(gè)數(shù)+新lists的個(gè)數(shù)
        uint32_t newCount = oldCount + addedCount;
        //開辟一個(gè)容量和大小的集合存谎,類型是 array_t,即創(chuàng)建一個(gè)數(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]));
    }
}

memmove和memcpy的區(qū)別

  • 在不知道需要平移的內(nèi)存大小時(shí)晴叨,需要memmove進(jìn)行內(nèi)存平移,保證安全
  • memcpy從原內(nèi)存地址的起始位置開始拷貝若干個(gè)字節(jié)到目標(biāo)內(nèi)存地址中矾屯,速度快
    存儲(chǔ)過程
    0-1
    如果還沒有數(shù)據(jù)篙螟,將傳入的列表加入第一個(gè)位置
    1-many
    首先計(jì)算出需要的大小,然后之前的舊數(shù)據(jù)放入末尾问拘,再將添加的數(shù)據(jù)從0號(hào)位置拷貝到array里面
    已經(jīng)有了很多數(shù)據(jù)的時(shí)候
    首先計(jì)算出需要的大小
    接著將舊數(shù)據(jù)平移到新增數(shù)據(jù)大小的位置下,進(jìn)行存放
    最后將添加的數(shù)據(jù)從0號(hào)位置拷貝到array里面

從上述源碼就能解釋為什么同名的分類的方法會(huì)先于本類的方法調(diào)用惧所,在上面我們知道骤坐,開辟rwe之后,寫入順序是baseMethodsbasePropertiesbaseProtocols下愈,最后才是分類纽绍,所以分類的同名方法會(huì)被優(yōu)先調(diào)用

非懶加載類的加載流程

通過上面的分析,我們知道了當(dāng)執(zhí)行到realizeClassWithoutSwift的時(shí)候势似,即代表開始加載該類了拌夏,我們的非懶加載類的加載流程_dyld_start_os_object_init_objc_initdyld::notifyBatchPartialmap_imagesmap_images_nolock_read_imagesrealizeClassWithoutSwiftmethodizeClass
我們通過自定義的類履因,并重寫了+ (void)load方法來定一個(gè)非懶加載類障簿。然后在realizeClassWithoutSwift源碼中加入如下代碼,來研究自己定義的類來探索栅迄。

    const char *mangledName = cls->nonlazyMangledName();
    const char *exploreName = "Person";
    if (strcmp(mangledName, exploreName) == 0) {
        printf("%s------%s\n", __func__, mangledName);
    }

在斷點(diǎn)處查看bt站故,和當(dāng)前線程的執(zhí)行記錄

非懶加載類的加載流程.png

懶加載類的加載流程

根據(jù)上面的經(jīng)驗(yàn),我們?nèi)c(diǎn)自定義類中的+ (void)load方法毅舆,將其變?yōu)閼屑虞d類西篓,然后運(yùn)行

懶加載類的加載流程

從上圖我們可以看出,懶加載類的加載延后到了憋活,類alloc的時(shí)機(jī)岂津,通過消息轉(zhuǎn)發(fā)來完成類的加載其流程
objc_alloc_objc_msgSend_uncachedlookUpImpOrForwardrealizeAndInitializeIfNeeded_lockedrealizeClassMaybeSwiftAndLeaveLockedrealizeClassMaybeSwiftMaybeRelockrealizeClassWithoutSwiftmethodizeClass
總結(jié)
非懶加載&懶加載對(duì)比

  • 懶加載類的加載悦即,需要使用到該類吮成,進(jìn)行消息發(fā)送的時(shí)候橱乱,才開始加載該類
  • 非懶加載類,在map_images_read_images之后便開始加載到內(nèi)存中
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末赁豆,一起剝皮案震驚了整個(gè)濱河市仅醇,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌魔种,老刑警劉巖析二,帶你破解...
    沈念sama閱讀 206,378評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異节预,居然都是意外死亡叶摄,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門安拟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蛤吓,“玉大人,你說我怎么就攤上這事糠赦』岚粒” “怎么了?”我有些...
    開封第一講書人閱讀 152,702評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵拙泽,是天一觀的道長淌山。 經(jīng)常有香客問我,道長顾瞻,這世上最難降的妖魔是什么泼疑? 我笑而不...
    開封第一講書人閱讀 55,259評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮荷荤,結(jié)果婚禮上退渗,老公的妹妹穿的比我還像新娘。我一直安慰自己蕴纳,他們只是感情好会油,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,263評(píng)論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著古毛,像睡著了一般钞啸。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上喇潘,一...
    開封第一講書人閱讀 49,036評(píng)論 1 285
  • 那天体斩,我揣著相機(jī)與錄音,去河邊找鬼颖低。 笑死絮吵,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的忱屑。 我是一名探鬼主播蹬敲,決...
    沈念sama閱讀 38,349評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼暇昂,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼!你這毒婦竟也來了伴嗡?” 一聲冷哼從身側(cè)響起急波,我...
    開封第一講書人閱讀 36,979評(píng)論 0 259
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎瘪校,沒想到半個(gè)月后澄暮,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,469評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡阱扬,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,938評(píng)論 2 323
  • 正文 我和宋清朗相戀三年泣懊,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片麻惶。...
    茶點(diǎn)故事閱讀 38,059評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡馍刮,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出窃蹋,到底是詐尸還是另有隱情卡啰,我是刑警寧澤,帶...
    沈念sama閱讀 33,703評(píng)論 4 323
  • 正文 年R本政府宣布警没,位于F島的核電站匈辱,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏惠奸。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,257評(píng)論 3 307
  • 文/蒙蒙 一恰梢、第九天 我趴在偏房一處隱蔽的房頂上張望佛南。 院中可真熱鬧,春花似錦嵌言、人聲如沸嗅回。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,262評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽绵载。三九已至,卻和暖如春苛白,著一層夾襖步出監(jiān)牢的瞬間娃豹,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評(píng)論 1 262
  • 我被黑心中介騙來泰國打工购裙, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留懂版,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,501評(píng)論 2 354
  • 正文 我出身青樓躏率,卻偏偏與公主長得像躯畴,于是被迫代替她去往敵國和親民鼓。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,792評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容

  • 在 iOS 應(yīng)用程序加載[http://www.reibang.com/p/bffb5bdb4f13] 一篇蓬抄,我...
    賣饃工程師閱讀 979評(píng)論 0 5
  • 1. 類的加載 在之前了解了dyld 和 objc是如何關(guān)聯(lián)的丰嘉,本文主要是理解類的相關(guān)信息是如何加載到內(nèi)存的,其中...
    沉江小魚閱讀 314評(píng)論 0 2
  • 前言 在之前的文章dyld與objc的關(guān)聯(lián)分析[http://www.reibang.com/p/86fcb05...
    Y丶舜禹閱讀 581評(píng)論 0 1
  • 在上一篇iOS-底層原理 16:dyld與objc的關(guān)聯(lián)[http://www.reibang.com/p/25...
    輝輝歲月閱讀 134評(píng)論 0 0
  • 一嚷缭,應(yīng)用程序加載回顧 通過前面的學(xué)習(xí)我們對(duì)iOS應(yīng)用程序的加載有了一個(gè)大致的認(rèn)識(shí)饮亏, 1 系統(tǒng)調(diào)用exec() 會(huì)讓...
    攜YOU手同行閱讀 655評(píng)論 0 0