美文网首页
dyld源码阅读

dyld源码阅读

作者: 拧发条鸟xds | 来源:发表于2021-09-30 14:11 被阅读0次

    参考

    dyld版本

    dyld-852.2

    源码

    1. dyld启动

    - _dyld_start () // 汇编实现
    - dyldbootstrap::start(macho_header const*, int, char const**, long, macho_header const*, unsigned long*) ()
    - dyld::_main((macho_header*)appsMachHeader, appsSlide, argc, argv, envp, apple, startGlue)
    

    ::表示命名空间下的某个函数或属性。

    2. 在dyld::_main()中执行的操作

    2.1 设置上下文

    这里会设置一些要执行的函数的地址, 如notifySingle等,这些函数会在后续某些阶段进行调用。

    setContext(mainExecutableMH, argc, argv, envp, apple);
    
    2.2 加载共享缓存
    mapSharedCache(mainExecutableSlide);
    

    程序启动运行时会依赖很多系统动态库,而系统动态库会通过dyld加载到内存中,
    最开始系统内核读取程序可执行文件的Header段信息做一些准备工作,之后就会将工作交给dyld。
    由于不止一个程序需要使用系统动态库,所以不可能在每个程序加载时都去加载所有的系统动态库,
    为了优化程序启动速度和利用动态库缓存,苹果从iOS3.1之后,
    将所有系统库(私有与公有)编译成一个大的缓存文件,这就是dyld_shared_cache
    ,该缓存文件存在iOS系统下的/System/Library/Caches/com.apple.dyld/目录下

    2.3 实例化主执行文件
    ImageLoaderMachO* sMainExecutable = instantiateFromLoadedImage(mainExecutableMH, mainExecutableSlide, sExecPath);
    
    2.4 加载插入动态库

    越狱插件会使用

    for (const char* const* lib = sEnv.DYLD_INSERT_LIBRARIES; *lib != NULL; ++lib) 
        loadInsertedDylib(*lib);
    
    2.5 链接主程序

    此时会链接动态库, 进行rebase操作, 同时会记录启动时间

    - link(sMainExecutable, sEnv.DYLD_BIND_AT_LAUNCH, true, ImageLoader::RPathChain(NULL, NULL), -1);
    
    - image->link(gLinkContext, forceLazysBound, false, neverUnload, loaderRPaths, path);
    
    
    2.5.1 递归加载依赖的动态库

    主程序依赖的动态库会被加载,依赖层级较低的会先加载

    this->recursiveLoadLibraries(context, preflightOnly, loaderRPaths, imagePath);
    
    2.5.2 递归进行重定位rebase

    与ASLR,全称为 Address Space Layout Randomization,地址空间布局随机化相关

    this->recursiveRebaseWithAccounting(context);
    
    2.5.3 递归进行符号绑定bind
    this->recursiveBindWithAccounting(context, forceLazysBound, neverUnload);
    
    2.6 链接插入动态库(通常越狱插件使用)
    if ( sInsertedDylibCount > 0 ) {
        for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
            ImageLoader* image = sAllImages[i+1];
            link(image, sEnv.DYLD_BIND_AT_LAUNCH, true, ImageLoader::RPathChain(NULL, NULL), -1);
            image->setNeverUnloadRecursive();
        }
        // only INSERTED libraries can interpose
        // register interposing info after all inserted libraries are bound so chaining works
        for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
            ImageLoader* image = sAllImages[i+1];
            image->registerInterposing(gLinkContext);
        }
    }
    
    
    2.7 初始化主执行文件
    initializeMainExecutable(); 
    
    
    2.7.1 初始化主执行文件
    sMainExecutable->runInitializers(gLinkContext, initializerTimes[0]);
    
    processInitializers(context, thisThread, timingInfo, up);
    
    

    2.7.1.1 递归进行初始化

    for (uintptr_t i=0; i < images.count; ++i) {
        // xds: 递归初始化所有image, 第一个初始化的是libSystem
        images.imagesAndPaths[i].first->recursiveInitialization(context, thisThread, images.imagesAndPaths[i].second, timingInfo, ups);
    }
    

    2.7.1.2 首先初始化更低层级的库

    // initialize lower level libraries first
    for(unsigned int i=0; i < libraryCount(); ++i) {
        ImageLoader* dependentImage = libImage(i);
        if ( dependentImage != NULL ) {
            // don't try to initialize stuff "above" me yet
            if ( libIsUpward(i) ) {
                uninitUps.imagesAndPaths[uninitUps.count] = { dependentImage, libPath(i) };
                uninitUps.count++;
            }
            else if ( dependentImage->fDepth >= fDepth ) {
                dependentImage->recursiveInitialization(context, this_thread, libPath(i), timingInfo, uninitUps);
            }
        }
    }
    
    

    重点

    libSystem会首先初始化,libSystem会调用_objc_init进行objc的初始化,_objc_init中会调用_dyld_objc_notify_register注册回调:

    • mapped回调: 注册的时候会立即进行调用(notifyBatchPartial函数),对所有映射的镜像进行objc setup操作;搜索(*sNotifyObjCMapped)(objcImageCount, paths, mhs);

    • init回调:注册的时候会对所有镜像立即进行调用;另外会在镜像初始化时调用;搜索(*sNotifyObjCInit)(image->getRealPath(), image->machHeader());

    • unmapped回调:卸载时调用;

    mapped回调具体操作看objc源码阅读

    void _dyld_objc_notify_register(_dyld_objc_notify_mapped    mapped,
                                    _dyld_objc_notify_init      init,
                                    _dyld_objc_notify_unmapped  unmapped)
    {
        dyld::registerObjCNotifiers(mapped, init, unmapped);
    }
    
    void registerObjCNotifiers(_dyld_objc_notify_mapped mapped, _dyld_objc_notify_init init, _dyld_objc_notify_unmapped unmapped)
    {
        // record functions to call
        sNotifyObjCMapped   = mapped; 
        sNotifyObjCInit     = init;
        sNotifyObjCUnmapped = unmapped;
    
        try {
            notifyBatchPartial(dyld_image_state_bound, true, NULL, false, true);
        }
        catch (const char* msg) {
            // ignore request to abort during registration
        }
    
        for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
            ImageLoader* image = *it;
            if ( (image->getState() == dyld_image_state_initialized) && image->notifyObjC() ) {
                dyld3::ScopedTimer timer(DBG_DYLD_TIMING_OBJC_INIT, (uint64_t)image->machHeader(), 0, 0);
                (*sNotifyObjCInit)(image->getRealPath(), image->machHeader());
            }
        }
    }
    

    2.7.1.3 notifySingle执行_dyld_objc_notify_register的init回调

    +load方法在此时调用

    context.notifySingle(dyld_image_state_dependents_initialized, this, &timingInfo);
    

    2.7.1.4 初始化当前镜像

    bool hasInitializers = this->doInitialization(context);
    

    2.7.1.4.1 调用_mod_init_func

    即 C++ Static Initializers 和 attribute((constructor))

    doModInitFunctions(context);
    

    2.7.2 打印各个阶段的时间

    ImageLoader::printStatistics((unsigned int)allImagesCount(), initializerTimes[0]);
    
    2.8 找到主执行文件的main函数
    // find entry point for main executable
    result = (uintptr_t)sMainExecutable->getEntryFromLC_MAIN();
    

    _dyld_objc_notify_register 的调用时机

    看这篇https://www.jianshu.com/p/3a238256a190的3.4,是在初始化第一个库libSystem时,libSystem 又会去初始化 libDispatch,在 libDispatch 初始化方法里面又会有一步 _os_object_init,在 _os_object_init 内部就会调起 _objc_init

    相关文章

      网友评论

          本文标题:dyld源码阅读

          本文链接:https://www.haomeiwen.com/subject/jrsenltx.html