objc庫源碼分析(1)-加載

objc庫中初始化方法如下

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();//初始化運行環(huán)境
    tls_init();
    static_init();//初始化靜態(tài)變量方法
    runtime_init();//初始化運行時環(huán)境
    exception_init();//初始化異常
    cache_init();//初始化緩存
    _imp_implementationWithBlock_init();

    _dyld_objc_notify_register(&map_images, load_images, unmap_image);

#if __OBJC2__
    didCallDyldNotifyRegister = true;
#endif
}

其中包含了一些列的初始化,以及image的映射和image的加載。
其中 _dyld_objc_notify_register(&map_images, load_images, unmap_image);是供dyld做回調(diào)使用,其中&map_images是方法是處理image的映射的,
map_images函數(shù)最最終會調(diào)用 runtime-new.mm中_read_images的函數(shù),
其中_read_images函數(shù)的調(diào)用邏輯如下

_read_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) {
        doneOnce = YES;//控制{}里面的代碼只執(zhí)行一次
        launchTime = YES;

#if SUPPORT_NONPOINTER_ISA
        // Disable non-pointer isa under some conditions.

# if SUPPORT_INDEXED_ISA //如果庫中有舊版本swift代碼 則不支持isa指針優(yōu)化
        // Disable nonpointer isa if any image contains old Swift code
        for (EACH_HEADER) {
            if (hi->info()->containsSwift()  &&
                hi->info()->swiftUnstableVersion() < objc_image_info::SwiftVersion3)
            {
                DisableNonpointerIsa = true;
                if (PrintRawIsa) {
                    _objc_inform("RAW ISA: disabling non-pointer isa because "
                                 "the app or a framework contains Swift code "
                                 "older than Swift 3.0");
                }
                break;
            }
        }
# endif

# if TARGET_OS_OSX //如果是 OS X 10.11之前的系統(tǒng),不支持isa指針優(yōu)化
        // Disable non-pointer isa if the app is too old
        // (linked before OS X 10.11)
        if (dyld_get_program_sdk_version() < DYLD_MACOSX_VERSION_10_11) {
            DisableNonpointerIsa = true;
            if (PrintRawIsa) {
                _objc_inform("RAW ISA: disabling non-pointer isa because "
                             "the app is too old (SDK version " SDK_FORMAT ")",
                             FORMAT_SDK(dyld_get_program_sdk_version()));
            }
        }

        // Disable non-pointer isa if the app has a __DATA,__objc_rawisa section
        // New apps that load old extensions may need this.
        for (EACH_HEADER) {
            if (hi->mhdr()->filetype != MH_EXECUTE) continue;
            unsigned long size;
            if (getsectiondata(hi->mhdr(), "__DATA", "__objc_rawisa", &size)) {
                DisableNonpointerIsa = true;
                if (PrintRawIsa) {
                    _objc_inform("RAW ISA: disabling non-pointer isa because "
                                 "the app has a __DATA,__objc_rawisa section");
                }
            }
            break;  // assume only one MH_EXECUTE image
        }
# endif

#endif

        if (DisableTaggedPointers) {
            //經(jīng)過前面的判斷,如果不支持指針優(yōu)化,
            disableTaggedPointers();
        }
        //tagged pointer混淆,讓指針地址對開發(fā)者看起來像是正常的內(nèi)存地址
        initializeTaggedPointerObfuscator();

        if (PrintConnecting) {
            _objc_inform("CLASS: found %d classes during launch", totalClasses);
        }

        // namedClasses
        // Preoptimized classes don't go in this table.
        // 4/3 is NXMapTable's load factor
        //創(chuàng)建存儲已識別類的哈希表
        //只會執(zhí)行一次
        int namedClassesSize = 
            (isPreoptimized() ? unoptimizedTotalClasses : totalClasses) * 4 / 3;
        gdb_objc_realized_classes =
            NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize);

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

    // Fix up @selector references
#pragma mark // 注冊方法
    static size_t UnfixedSelectors;
    {
        mutex_locker_t lock(selLock);
        for (EACH_HEADER) {
            if (hi->hasPreoptimizedSelectors()) continue;

            bool isBundle = hi->isBundle();
            SEL *sels = _getObjc2SelectorRefs(hi, &count);//獲取可執(zhí)行文件中待注冊的方法
           
            for (i = 0; i < count; i++) {
                const char *name = sel_cname(sels[i]);
                SEL sel = sel_registerNameNoLock(name, isBundle);//注冊方法
                if (sels[i] != sel) {
                    sels[i] = sel;
                }
            }
        }
    }

    ts.log("IMAGE TIMES: fix up selector references");
#pragma mark 類
    // Discover classes. Fix up unresolved future classes. Mark bundle classes.
    bool hasDyldRoots = dyld_shared_cache_some_image_overridden();

    for (EACH_HEADER) {
        if (! mustReadClasses(hi, hasDyldRoots)) {
            // Image is sufficiently optimized that we need not call readClass() 判斷是否需要執(zhí)行readclass()方法
            continue;
        }

        classref_t const *classlist = _getObjc2ClassList(hi, &count);

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

        for (i = 0; i < count; i++) {
            Class cls = (Class)classlist[i];
            Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);

            if (newCls != cls  &&  newCls) {
                // Class was moved but not deleted. Currently this occurs 
                // only when the new class resolved a future class.
                // Non-lazily realize the class below.
                //如果readClass返回的結(jié)果不是原來的class,則將class放入帶解決的class列表
                resolvedFutureClasses = (Class *)
                    realloc(resolvedFutureClasses, 
                            (resolvedFutureClassCount+1) * sizeof(Class));
                resolvedFutureClasses[resolvedFutureClassCount++] = newCls;//已解決的futurec class
            }
        }
    }

    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.
    // ref是源文件,才用了ASLR (Address Space Layout Randomization) 地址空間布局隨機化技術(shù)
    // 所以要映射類的地址,才可以找到真實地址
    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");

#if SUPPORT_FIXUP
    
#pragma mark    // Fix up old objc_msgSend_fixup call sites 修正引用計數(shù)和消息發(fā)送相關(guān)的方法
    for (EACH_HEADER) {
        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());
        }
        for (i = 0; i < count; i++) {
            fixupMessageRef(refs+i);
        }
    }

    ts.log("IMAGE TIMES: fix up objc_msgSend_fixup");
#endif
#pragma mark 協(xié)議
    bool cacheSupportsProtocolRoots = sharedCacheSupportsProtocolRoots();

    // Discover protocols. Fix up protocol refs. 影射協(xié)議和影射協(xié)議的修正
    for (EACH_HEADER) {
        extern objc_class OBJC_CLASS_$_Protocol;
        Class cls = (Class)&OBJC_CLASS_$_Protocol;
        ASSERT(cls);
        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) { //如果是在運行過程中,而且是動態(tài)庫的協(xié)議,則跳過,不加載該類的協(xié)議
            if (PrintProtocols) {
                _objc_inform("PROTOCOLS: Skipping reading protocols in image: %s",
                             hi->fname());
            }
            continue;
        }

        bool isBundle = hi->isBundle();

        //
        protocol_t * const *protolist = _getObjc2ProtocolList(hi, &count);
        for (i = 0; i < count; i++) {
            readProtocol(protolist[i], cls, protocol_map, 
                         isPreoptimized, isBundle);//這一步會把符合條件的協(xié)議(之前不存在同名的協(xié)議)添加到協(xié)議列表
        }
    }

    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) {
        // 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;
        protocol_t **protolist = _getObjc2ProtocolRefs(hi, &count);
        for (i = 0; i < count; i++) {
            remapProtocolRef(&protolist[i]);//重新影射一次協(xié)議。如果協(xié)議中存在不符合條件的協(xié)議,統(tǒng)計出其中的數(shù)量
        }
    }

    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) {//等所有的分類綁定完以后才影射
        for (EACH_HEADER) {
            load_categories_nolock(hi);//把分類里面的內(nèi)容添加到類里面
        }
    }

    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) {
        classref_t const *classlist = 
            _getObjc2NonlazyClassList(hi, &count);
        for (i = 0; i < count; i++) {
            Class cls = remapClass(classlist[i]);
            if (!cls) continue;

            addClassTableEntry(cls);

            if (cls->isSwiftStable()) {
                if (cls->swiftMetadataInitializer()) {
                    _objc_fatal("Swift class %s with a metadata initializer "
                                "is not allowed to be non-lazy",
                                cls->nameForLogging());
                }
                // fixme also disallow relocatable classes
                // We can't disallow all Swift classes because of
                // classes like Swift.__EmptyArrayStorage
            }
            realizeClassWithoutSwift(cls, nil);
        }
    }

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

    // Realize newly-resolved future classes, in case CF manipulates them 對readclass()以后那些待處理的類,重新創(chuàng)建。以防CoreFoundate去調(diào)用
    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");
            }
            realizeClassWithoutSwift(cls, nil);//重新創(chuàng)建類
            cls->setInstancesRequireRawIsaRecursively(false/*inherited*/);//
        }
        free(resolvedFutureClasses);
    }

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

    //如果不存在帶修正的變量,則realize所有類
    //什么是帶修正的變量?帶修正的變量是指類繼承了別的類,別的類有變量,則子類的結(jié)構(gòu)要修改
    if (DebugNonFragileIvars) {
        realizeAllClasses();
    }


    // Print preoptimization statistics 輸出動態(tài)庫中由dyld進行了預(yù)先優(yōu)化的類
    if (PrintPreopt) {
        static unsigned int PreoptTotalMethodLists;
        static unsigned int PreoptOptimizedMethodLists;
        static unsigned int PreoptTotalClasses;
        static unsigned int PreoptOptimizedClasses;

        for (EACH_HEADER) {
            if (hi->hasPreoptimizedSelectors()) {
                _objc_inform("PREOPTIMIZATION: honoring preoptimized selectors "
                             "in %s", hi->fname());
            }
            else if (hi->info()->optimizedByDyld()) {//如果由dyld進行了優(yōu)化,則不用執(zhí)行
                _objc_inform("PREOPTIMIZATION: IGNORING preoptimized selectors "
                             "in %s", hi->fname());
            }

            classref_t const *classlist = _getObjc2ClassList(hi, &count);
            for (i = 0; i < count; i++) {
                Class cls = remapClass(classlist[i]);
                if (!cls) continue;

                PreoptTotalClasses++;
                if (hi->hasPreoptimizedClasses()) {
                    PreoptOptimizedClasses++;
                }
                
                const method_list_t *mlist;
                if ((mlist = ((class_ro_t *)cls->data())->baseMethods())) {
                    PreoptTotalMethodLists++;
                    if (mlist->isFixedUp()) {
                        PreoptOptimizedMethodLists++;
                    }
                }
                if ((mlist=((class_ro_t *)cls->ISA()->data())->baseMethods())) {
                    PreoptTotalMethodLists++;
                    if (mlist->isFixedUp()) {
                        PreoptOptimizedMethodLists++;
                    }
                }
            }
        }

        _objc_inform("PREOPTIMIZATION: %zu selector references not "
                     "pre-optimized", UnfixedSelectors);
        _objc_inform("PREOPTIMIZATION: %u/%u (%.3g%%) method lists pre-sorted",
                     PreoptOptimizedMethodLists, PreoptTotalMethodLists, 
                     PreoptTotalMethodLists
                     ? 100.0*PreoptOptimizedMethodLists/PreoptTotalMethodLists 
                     : 0.0);
        _objc_inform("PREOPTIMIZATION: %u/%u (%.3g%%) classes pre-registered",
                     PreoptOptimizedClasses, PreoptTotalClasses, 
                     PreoptTotalClasses 
                     ? 100.0*PreoptOptimizedClasses/PreoptTotalClasses
                     : 0.0);
        _objc_inform("PREOPTIMIZATION: %zu protocol references not "
                     "pre-optimized", UnfixedProtocolReferences);
    }

#undef EACH_HEADER
}

_read_images的調(diào)用邏輯如下

_read_images執(zhí)行流程.jpg

最主要做了下面幾個事情
1 初始化
2 修正方法 Fix up @selector references
3 發(fā)現(xiàn)類Discover classes
4 修正消息發(fā)送相關(guān)fixupMessageRef
5 發(fā)現(xiàn)協(xié)議discover protocols
6 加載分類到類中
7 realize實現(xiàn)了load方法的類
8 輸出動態(tài)庫優(yōu)化的內(nèi)容

為什么要fix up呢?

在加載所有的動態(tài)鏈接庫之后,它們只是處在相互獨立的狀態(tài),需要將它們綁定起來,這就是 Fix-ups。代碼簽名使得我們不能修改指令,那樣就不能讓一個 dylib 的調(diào)用另一個 dylib。這時需要加很多間接層。
現(xiàn)代 code-gen 被叫做動態(tài) PIC(Position Independent Code),意味著代碼可以被加載到間接的地址上。當調(diào)用發(fā)生時,code-gen 實際上會在 __DATA 段中創(chuàng)建一個指向被調(diào)用者的指針,然后加載指針并跳轉(zhuǎn)過去。所以 dyld 做的事情就是修正(fix-up)指針和數(shù)據(jù)。Fix-up 有兩種類型,rebasing 和 binding。
Rebasing:在鏡像內(nèi)部調(diào)整指針的指向
Binding:將指針指向鏡像外部的內(nèi)容

簡而言之,fix up就是為了找到調(diào)整指針的指向,找到我們所需要的內(nèi)容。

discover class

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

    for (EACH_HEADER) {
        if (! mustReadClasses(hi, hasDyldRoots)) {
            // Image is sufficiently optimized that we need not call readClass() 判斷是否需要執(zhí)行readclass()方法
            continue;
        }

        classref_t const *classlist = _getObjc2ClassList(hi, &count);

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

        for (i = 0; i < count; i++) {
            Class cls = (Class)classlist[i];
            Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);

            if (newCls != cls  &&  newCls) {
                // Class was moved but not deleted. Currently this occurs 
                // only when the new class resolved a future class.
                // Non-lazily realize the class below.
                //如果readClass返回的結(jié)果不是原來的class,則將class放入帶解決的class列表
                resolvedFutureClasses = (Class *)
                    realloc(resolvedFutureClasses, 
                            (resolvedFutureClassCount+1) * sizeof(Class));
                resolvedFutureClasses[resolvedFutureClassCount++] = newCls;//已解決的futurec class
            }
        }
    }

判斷是否是動態(tài)庫的內(nèi)容,如果不是動態(tài)庫。則遍歷這個可執(zhí)行文件里的類。


load_images

load_images的實現(xiàn)如下

load_images(const char *path __unused, const struct mach_header *mh)
{
    recursive_mutex_locker_t lock(loadMethodLock);

    // Discover +load methods
    prepare_load_methods((const headerType *)mh);

    // Call +load methods (without classLock - re-entrant)
    call_load_methods();
}

做了兩個事情
1 準備load方法prepare_load_methods()
2 執(zhí)行l(wèi)oad方法call_load_methods()

準備load方法prepare_load_methods


void prepare_load_methods(const headerType *mhdr)
{
    size_t count, i;

    runtimeLock.assertLocked();

    classref_t const *classlist = 
        _getObjc2NonlazyClassList(mhdr, &count);//獲取有l(wèi)oad方法的類
    for (i = 0; i < count; i++) {
    //將實現(xiàn)了load方法的類放到loadable_classes數(shù)組中
        schedule_class_load(remapClass(classlist[i]));
    }


    //將實現(xiàn)了load方法的分類放到loadable_categories數(shù)組中
    category_t * const *categorylist = _getObjc2NonlazyCategoryList(mhdr, &count);
    for (i = 0; i < count; i++) {
        category_t *cat = categorylist[i];
        Class cls = remapClass(cat->cls);
        if (!cls) continue;  // category for ignored weak-linked class//忽略弱連接的類
        if (cls->isSwiftStable()) {//swfit 的extensions 和 catrogry不支持load方法
            _objc_fatal("Swift class extensions and categories on Swift "
                        "classes are not allowed to have +load methods");
        }
        realizeClassWithoutSwift(cls, nil);
        ASSERT(cls->ISA()->isRealized());
        add_category_to_loadable_list(cat);
    }
}


//將實現(xiàn)了load方法的類放到loadable_classes數(shù)組中
static void schedule_class_load(Class cls)
{
    if (!cls) return;
    ASSERT(cls->isRealized());  // _read_images should realize

    if (cls->data()->flags & RW_LOADED) return;

    // Ensure superclass-first ordering  遞歸調(diào)用方法,確保父類的load優(yōu)先執(zhí)行
    schedule_class_load(cls->superclass);

    add_class_to_loadable_list(cls);
    cls->setInfo(RW_LOADED); 
}

prepare_load_methods方法主要是執(zhí)行了兩個事情

1 將實現(xiàn)了load方法的類放到loadable_classes數(shù)組中
2 將實現(xiàn)了load方法的分類放到loadable_categories數(shù)組中

_getObjc2NonlazyClassList返回的是image中帶有l(wèi)oad方法的class的數(shù)組,會按照編譯的順序添加到數(shù)組loadable_classes當中。
_getObjc2NonlazyCategoryList返回的是image中帶有l(wèi)oad方法的category的數(shù)組,會按照編譯的順序添加到數(shù)組loadable_categories當中。

一般來說,先編譯的class和category,其的load方法會先執(zhí)行
注意在prepare_load_methods()中調(diào)用schedule_class_load()方法,schedule_class_load()方法是一個遞歸調(diào)用,如果存在父類,則調(diào)用schedule_class_load()方法,這樣保證了實現(xiàn)了load的方法可以放在loadable_classes數(shù)組的前面,這樣也就保證了父類的load方法比子類的load方法優(yōu)先執(zhí)行

執(zhí)行l(wèi)oad方法call_load_methods()

call_load_methods()實現(xiàn)如下

void call_load_methods(void)
{
    static bool loading = NO;
    bool more_categories;

    loadMethodLock.assertLocked();

    // Re-entrant calls do nothing; the outermost call will finish the job.
    if (loading) return; //保證call_load_methods只執(zhí)行一次
    loading = YES;

    void *pool = objc_autoreleasePoolPush();//自動釋放池

    do {
        // 1. Repeatedly call class +loads until there aren't any more
        //循環(huán)執(zhí)行類的load的方法
        while (loadable_classes_used > 0) {
            call_class_loads();
        }
        // 2. Call category +loads ONCE
        //執(zhí)行完類的load方法后才cagetgory中的方法
        //檢測是否有未執(zhí)行l(wèi)oad方法的category,如果有,則循環(huán)執(zhí)行
        //為什么會有未執(zhí)行l(wèi)oad方法的category?因為category可能會引入別的有l(wèi)oad方法class,別的class的load要先執(zhí)行,category中的load要等待執(zhí)行
          more_categories = call_category_loads();

        // 3. Run more +loads if there are classes OR more untried categories
    } while (loadable_classes_used > 0  ||  more_categories);

    objc_autoreleasePoolPop(pool);

    loading = NO;
}

可以看到,通過do while循環(huán)中確保所有的類和分類的load方法都被調(diào)用。

do while中優(yōu)先call_class_loads(),再執(zhí)行call_category_loads(),也就是說類的load方法比分類的load方法先執(zhí)行

call_class_loads方法會從loadable_classes數(shù)組中找到對應(yīng)的類,并通過直接調(diào)用的方法,調(diào)用類的loadable_classes方法。

call_category_loads()方法會從loadable_categories中找到相應(yīng)的分類load方法。并調(diào)用load方法.

在前面可知,在類和分類的加載過程中,有三個結(jié)果

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

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