OC底层原理16-objc_init初探 & dyld和objc关联

  • 引入
    在 OC底层原理15-dyld加载流程 中,我们初步窥探了dyld的加载流程:_dyld_start -> dyldbootstrap -> dyld::_main,在dyld::_main流程的最后一步寻找主程序入口,我们进入了recursiveInitialization方法,首先调用了context.notifySingle方法进行单个通知注入,调用回调函数load_images,调用doInitialization方法的时候,会从dyld -> libSystem -> libdispatch -> objc中的_objc_init_objc_init又调用了dyld中实现的_dyld_objc_notify_register注册回调函数,这样就构成了跨库闭环,如下图
    recursiveInitialization流程.png

一、_objc_init源码初探

image.png
1.1、environ_init()

读取影响运行时的环境变量

  • 进入 objc可编译源码
  • 修改void environ_init(void)方法如下,打印所以设置的环境变量
  • 运行打印环境变量
void environ_init(void) 
{
    for (size_t i = 0; i < sizeof(Settings)/sizeof(Settings[0]); i++) {
        const option_t *opt = &Settings[i];
        _objc_inform("%s: %s", opt->env, opt->help);
        _objc_inform("%s is set", opt->env);
    }
}

打印如下:由于太多,只展示部分
objc[11514]: OBJC_PRINT_IMAGES: log image and library names as they are loaded
objc[11514]: OBJC_PRINT_IMAGES is set
objc[11514]: OBJC_PRINT_IMAGE_TIMES: measure duration of image loading steps
objc[11514]: OBJC_PRINT_IMAGE_TIMES is set
...
  • 环境变量的设置 Product -> Scheme -> Edit Scheme
    环境变量的设置.png
  • OBJC_PRINT_LOAD_METHODS为例设置成YES,打印所有实现了load方法的类
    打印结果.png
1.2、environ_init()

关于线程key的绑定

void tls_init(void)
{
#if SUPPORT_DIRECT_THREAD_KEYS
//: -- init方法
    pthread_key_init_np(TLS_DIRECT_KEY, &_objc_pthread_destroyspecific);
#else
//: -- 析构
    _objc_pthread_key = tls_create(&_objc_pthread_destroyspecific);
#endif
}
1.3、static_init()

初始化objc库里面的构造函数,比dyld的析构c++还早,主动调用

1.4、runtime_init()

运行时初始化

void runtime_init(void)
{
//: -- 分类处理的初始化
    objc::unattachedCategories.init(32);
//: -- 初始化class表
    objc::allocatedClasses.init();
}
1.5、exception_init()

初始化libobjc的异常处理系统

  • crash不是崩溃,是违反系统的规定,系统给出的信号
  • 系统会调用一个默认回调函数,中断你的进程,即崩溃
  • 我们可以指定一个回调函数,拦截中断,就可以拦截崩溃
1.6、cache_init()

缓存条件初始化

1.7、_imp_implementationWithBlock_init()

通常这不会做什么,因为所有的初始化都是惰性的,但是对于某些进程,我们会迫不及待地加载trampolines dylib

1.8、_dyld_objc_notify_register(&map_images, load_images, unmap_image)

注册回调函数

二、dyld和objc关联

  • 我们发现objc的源码中,并没有实现_dyld_objc_notify_register函数,但是在dyld的源码中,我们找到了_dyld_objc_notify_register的实现,这里是跨库调用
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);
}

map_images:映射镜像文件,管理文件中和动态库中所有的符号
load_images:加载镜像文件
unmap_image:移除镜像文件
注意:map_images前面有&,属于引用类型,外界条件变,它就会跟着变,要传递值
注意:load_images属于值类型,不传递值

  • 调用registerObjCNotifiers
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;

    // call 'mapped' function with all images mapped so far
    try {
        notifyBatchPartial(dyld_image_state_bound, true, NULL, false, true);
    }
    catch (const char* msg) {
        // ignore request to abort during registration
    }

    //  call 'init' function on all images already init'ed (below libSystem)
    for (std::vector::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());
        }
    }
}

objc把回调函数map_imagesload_imagesunmap_image分别传给了dyldsNotifyObjCMappedsNotifyObjCInitsNotifyObjCUnmapped

  • 现在研究sNotifyObjCMappedsNotifyObjCInitsNotifyObjCUnmapped是何时被调用的
  • 全局搜索sNotifyObjCMapped,发现在notifyBatchPartial方法中调用了sNotifyObjCMapped
static void notifyBatchPartial(dyld_image_states state, bool orLater, dyld_image_state_change_handler onlyHandler, bool preflightOnly, bool onlyObjCMappedNotification)
{
...
//: -- sNotifyObjCMapped 调用
(*sNotifyObjCMapped)(objcImageCount, paths, mhs);
...
}

在上面的registerObjCNotifiers方法中就对notifyBatchPartial进行了调用,即objc中调用_dyld_objc_notify_register进入dyld后,就会回调map_images,进行镜像文件的映射

  • 全局搜索sNotifyObjCInit,发现在notifySingle方法中调用了sNotifyObjCInit
static void notifySingle(dyld_image_states state, const ImageLoader* image, ImageLoader::InitializerTimingList* timingInfo)
{
    ...
    if ( (state == dyld_image_state_dependents_initialized) && (sNotifyObjCInit != NULL) && image->notifyObjC() ) {
        uint64_t t0 = mach_absolute_time();
        dyld3::ScopedTimer timer(DBG_DYLD_TIMING_OBJC_INIT, (uint64_t)image->machHeader(), 0, 0);
//: -- sNotifyObjCInit 调用
        (*sNotifyObjCInit)(image->getRealPath(), image->machHeader());
        uint64_t t1 = mach_absolute_time();
        uint64_t t2 = mach_absolute_time();
        uint64_t timeInObjC = t1-t0;
        uint64_t emptyTime = (t2-t1)*100;
        if ( (timeInObjC > emptyTime) && (timingInfo != NULL) ) {
            timingInfo->addTime(image->getShortName(), timeInObjC);
        }
    }
    ...
}

dyld_image_states == dyld_image_state_dependents_initialized时,会开始调用sNotifyObjCInit

  • 在文章开头的引入中,我们分析了recursiveInitialization方法,里面调用了``
void ImageLoader::recursiveInitialization(const LinkContext& context, mach_port_t this_thread, const char* pathToInitialize,
                                          InitializerTimingList& timingInfo, UninitedUpwards& uninitUps)
{
    ...
    // let objc know we are about to initialize this image
    uint64_t t1 = mach_absolute_time();
    fState = dyld_image_state_dependents_initialized;
    oldState = fState;
//: -- 调用notifySingle,并且`dyld_image_states` == `dyld_image_state_dependents_initialized `
    context.notifySingle(dyld_image_state_dependents_initialized, this, &timingInfo);
            
    // initialize this image
    bool hasInitializers = this->doInitialization(context);

    // let anyone know we finished initializing this image
    fState = dyld_image_state_initialized;
    oldState = fState;
    context.notifySingle(dyld_image_state_initialized, this, NULL);
    ...
}
  • 全局搜索sNotifyObjCUnmapped,发现在removeImage方法中调用了sNotifyObjCUnmapped
void removeImage(ImageLoader* image)
{
    ...
    (*sNotifyObjCUnmapped)(image->getRealPath(), image->machHeader());
    ...
}

dyld的加载流程从_dyld_start -> dyldbootstrap -> dyld::_main,在dyld::_main流程的最后一步寻找主程序入口,进入了recursiveInitialization方法,首先调用了context.notifySingle方法进行单个通知注入,调用回调函数load_images,调用doInitialization方法的时候,会从dyld -> libSystem -> libdispatch -> objc中的_objc_init_objc_init又调用了dyld中实现的_dyld_objc_notify_register注册回调函数,调用dyld中的_dyld_objc_notify_register的时候,又调用了回调函数map_images,这样就构成了跨库闭环,就把objcdyld进行了关联。

你可能感兴趣的:(OC底层原理16-objc_init初探 & dyld和objc关联)