dyld分析

相信大家在项目开发中都使用过重写+(void)load方法来进行一些初始化。那它的调用为什么比main函数调用还要靠前,整体调用流程到底是怎么样的,今天我们就来分析一下吧~

查看调用堆栈

新建一个iOS工程,在ViewController中重写+(void)load方法并打个断点,bt打印日志如下:

* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 2.1
  * frame #0: 0x00000001092ffe17 testObjc`+[ViewController load](self=ViewController, _cmd="load") at ViewController.m:17:5
    frame #1: 0x0000000109b165e3 libobjc.A.dylib`load_images + 1442
    frame #2: 0x0000000109313e54 dyld_sim`dyld::notifySingle(dyld_image_states, ImageLoader const*, ImageLoader::InitializerTimingList*) + 425
    frame #3: 0x0000000109322887 dyld_sim`ImageLoader::recursiveInitialization(ImageLoader::LinkContext const&, unsigned int, char const*, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) + 437
    frame #4: 0x0000000109320bb0 dyld_sim`ImageLoader::processInitializers(ImageLoader::LinkContext const&, unsigned int, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) + 188
    frame #5: 0x0000000109320c50 dyld_sim`ImageLoader::runInitializers(ImageLoader::LinkContext const&, ImageLoader::InitializerTimingList&) + 82
    frame #6: 0x00000001093142a9 dyld_sim`dyld::initializeMainExecutable() + 199
    frame #7: 0x0000000109318d50 dyld_sim`dyld::_main(macho_header const*, unsigned long, int, char const**, char const**, char const**, unsigned long*) + 4431
    frame #8: 0x00000001093131c7 dyld_sim`start_sim + 122
    frame #9: 0x000000010ee8985c dyld`dyld::useSimulatorDyld(int, macho_header const*, char const*, int, char const**, char const**, char const**, unsigned long*, unsigned long*) + 2308
    frame #10: 0x000000010ee874f4 dyld`dyld::_main(macho_header const*, unsigned long, int, char const**, char const**, char const**, unsigned long*) + 837
    frame #11: 0x000000010ee82227 dyld`dyldbootstrap::start(dyld3::MachOLoaded const*, int, char const**, dyld3::MachOLoaded const*, unsigned long*) + 453
    frame #12: 0x000000010ee82025 dyld`_dyld_start + 37

接下来继续往下执行,在main函数上打个断点,然后bt打印日志如下:

* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 3.1
    frame #0: 0x000000010930009d testObjc`main(argc=1, argv=0x00007ffee68ffcc0) at main.m:16:16
  * frame #1: 0x000000010b267415 libdyld.dylib`start + 1

可以看到这两个调用栈都是从libdyld.dylib中的方法开始的。dyld负责了我们应用程序的启动加载,那它到底做了什么,接下来我们就从dyld的源码层面开始分析吧(相关代码可以从苹果的openSource上下载到)。

dyld流程分析

在dyld开源代码中搜索_dyld_start,其使用汇编语言实现,后续调用流程为dyldbootstrap::start->dyld::_main可以看到在main方法中做了很多事情,主要是准备环境,初始化,加载主程序等。其中比较关键的是主程序的初始化流程:initializeMainExecutable->runInitializers->processInitializers->recursiveInitialization->doInitialization,看一下实现:

bool ImageLoaderMachO::doInitialization(const LinkContext& context)
{
    CRSetCrashLogMessage2(this->getPath());

    // mach-o has -init and static initializers
    //执行所有image的初始化
    doImageInit(context);
    //执行被声明成构造函数属性的函数
    doModInitFunctions(context);
    
    CRSetCrashLogMessage2(NULL);
    
    return (fHasDashInit || fHasInitializers);
}

doModInitFunctions中会确保libSystem.dylib的初始化方法libSystem_initializer先被调用,然后内部调用libdispatch.dylib库中的libdispatch_init -> _os_object_init -> _objc_init,
然而_objc_init的实现是在runtime源码中,看一下其源码实现:

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();
    cache_init();
    _imp_implementationWithBlock_init();
    //调用dyld中的注册方法,把load_images函数地址传过去
    _dyld_objc_notify_register(&map_images, load_images, unmap_image);

#if __OBJC2__
    didCallDyldNotifyRegister = true;
#endif
}

其中比较关键的是_dyld_objc_notify_register -> registerObjCNotifiers方法的调用,registerObjCNotifiers方法又回到了libdyld.dylib中,所以这个调用链是把runtime中的load_images函数地址存储在libdyld.dylib中的全局变量sNotifyObjCInit上。

至此dylddoInitialization方法中执行完毕,继续回到recursiveInitialization方法往下执行调用context.notifySingle -> sNotifyObjCInit(),流程又回到runtime层的load_images方法来,看一下方法实现:

void load_images(const char *path __unused, const struct mach_header *mh)
{
    if (!didInitialAttachCategories && didCallDyldNotifyRegister) {
        didInitialAttachCategories = true;
        loadAllCategories();
    }

    // Return without taking locks if there are no +load methods here.
    if (!hasLoadMethods((const headerType *)mh)) return;

    recursive_mutex_locker_t lock(loadMethodLock);

    // Discover load methods
    {
        mutex_locker_t lock2(runtimeLock);
        //准备待调用的load方法列表
        prepare_load_methods((const headerType *)mh);
    }

    // Call +load methods (without runtimeLock - re-entrant)
    //一次性加载所有load方法
    call_load_methods();
}

主要是加载category,准备待执行的load方法列表,然后一次性调用所有的load方法。
看一下prepare_load_methods中的实现:

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

    runtimeLock.assertLocked();

    //读取所有的类信息
    classref_t const *classlist = 
        _getObjc2NonlazyClassList(mhdr, &count);
    for (i = 0; i < count; i++) {
            //把类的load方法加到list列表
        schedule_class_load(remapClass(classlist[i]));
    }
    
    //加载所有的分类信息
    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()) {
            _objc_fatal("Swift class extensions and categories on Swift "
                        "classes are not allowed to have +load methods");
        }
        realizeClassWithoutSwift(cls, nil);
        ASSERT(cls->ISA()->isRealized());
        //把分类中的load方法加到list中
        add_category_to_loadable_list(cat);
    }
}

就是把所有类的load方法和所有分类的load方法分别放到两个list中。并且schedule_class_load中加载类的load方法是时是递归调用的,所以父类的load方法在前面。接下来调用了call_load_methods

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;
    loading = YES;

    void *pool = objc_autoreleasePoolPush();

    do {
        // 1. Repeatedly call class +loads until there aren't any more
        //先调用类的load方法
        while (loadable_classes_used > 0) {
            call_class_loads();
        }

        // 2. Call category +loads ONCE
        //再调用分类的load方法
        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;
}

可以看到是先调用了call_class_loads,然后调用call_category_loads,所以load方法的调用顺序是,父类->子类->category,至此,load方法的调用流程就分析结束了。
initializeMainExecutable方法流程结束后就通知可以进入main方法中了,也也是为什么loadmain方法先执行的原因。

你可能感兴趣的:(dyld分析)