dyld和objc的联系

2021-04-03  本文已影响0人  木扬音

本文主要分析dyld和objc的联系

_objc_init源码解析

libObjc_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?
    //读取影响运行时的环境变量,如果需要,还可以打开环境变量帮助 export OBJC_HELP = 1
    environ_init();
    //关于线程key的绑定,例如线程数据的析构函数
    tls_init();
    //运行C++静态构造函数,在dyld调用我们的静态析构函数之前,libc会调用_objc_init(),因此我们必须自己做
    static_init();
    //runtime运行时环境初始化,里面主要是unattachedCategories、allocatedClasses -- 分类初始化
    runtime_init();
    //初始化libobjc的异常处理系统
    exception_init();
    //缓存条件初始化
    cache_init();
    //启动回调机制,通常这不会做什么,因为所有的初始化都是惰性的,但是对于某些进程,我们会迫不及待地加载trampolines dylib
    _imp_implementationWithBlock_init();

    /*
     _dyld_objc_notify_register -- dyld 注册的地方
     - 仅供objc运行时使用
     - 注册处理程序,以便在映射、取消映射 和初始化objc镜像文件时使用,dyld将使用包含objc_image_info的镜像文件数组,回调 mapped 函数
     
     map_images:dyld将image镜像文件加载进内存时,会触发该函数
     load_images:dyld初始化image会触发该函数
     unmap_image:dyld将image移除时会触发该函数
     */
    _dyld_objc_notify_register(&map_images, load_images, unmap_image);

#if __OBJC2__
    didCallDyldNotifyRegister = true;
#endif
}

根据_objc_init源码可知,主要分为以下几个部分:

1、environ_init():环境变量初始化

environ_init源码如下,其关键代码时for循环

void environ_init(void) 
{
    //...省略部分逻辑
if (PrintHelp  ||  PrintOptions) {
        //...省略部分逻辑
        for (size_t i = 0; i < sizeof(Settings)/sizeof(Settings[0]); i++) {
            const option_t *opt = &Settings[i];            
            if (PrintHelp) _objc_inform("%s: %s", opt->env, opt->help);
            if (PrintOptions && *opt->var) _objc_inform("%s is set", opt->env);
        }
    }
}

我们可以通过下面两种方法打印出所有的环境变量

这些环境变量我们可以通过target -- Edit Scheme -- Run --Arguments -- Environment Variables配置

环境变量配置

2、tls_init:线程key的绑定

主要是本地线程池的初始化和析构,源码如下

void tls_init(void)
{
#if SUPPORT_DIRECT_THREAD_KEYS//本地线程池,用来进行处理
    pthread_key_init_np(TLS_DIRECT_KEY, &_objc_pthread_destroyspecific);//初始init
#else
    _objc_pthread_key = tls_create(&_objc_pthread_destroyspecific);//析构
#endif
}

3、static_init:运行系统级别的C++静态构造函数

主要是运行系统级别的C++静态构造函数,在dyld调用我们的静态构造函数前,libc调用_objc_init方法,源码如下:

static void static_init()
{
    size_t count;
    auto inits = getLibobjcInitializers(&_mh_dylib_header, &count);
    for (size_t i = 0; i < count; i++) {
        inits[i]();
    }
}

4、runtime_init:运行时环境初始化

分为两个部分:分类初始化类的表初始化

void runtime_init(void)
{
    objc::unattachedCategories.init(32);
    objc::allocatedClasses.init(); //初始化 -- 开辟的类的表
}

5、exception_init:初始化libobjc的异常处理系统

初始化libobjc的异常处理系统,注册异常处理回调,从而监控异常的处理,源码如下

void exception_init(void)
{
    old_terminate = std::set_terminate(&_objc_terminate);
}
/***********************************************************************
* _objc_terminate
* Custom std::terminate handler.
*
* The uncaught exception callback is implemented as a std::terminate handler. 
* 1. Check if there's an active exception
* 2. If so, check if it's an Objective-C exception
* 3. If so, call our registered callback with the object.
* 4. Finally, call the previous terminate handler.
**********************************************************************/
static void (*old_terminate)(void) = nil;
static void _objc_terminate(void)
{
    if (PrintExceptions) {
        _objc_inform("EXCEPTIONS: terminating");
    }

    if (! __cxa_current_exception_type()) {
        // No current exception.
        (*old_terminate)();
    }
    else {
        // There is a current exception. Check if it's an objc exception.
        @try {
            __cxa_rethrow();
        } @catch (id e) {
            // It's an objc object. Call Foundation's handler, if any.
            (*uncaught_handler)((id)e);//扔出异常
            (*old_terminate)();
        } @catch (...) {
            // It's not an objc object. Continue to C++ terminate.
            (*old_terminate)();
        }
    }
}
objc_uncaught_exception_handler 
objc_setUncaughtExceptionHandler(objc_uncaught_exception_handler fn)
{
//    fn为设置的异常句柄 传入的函数,为外界给的
    objc_uncaught_exception_handler result = uncaught_handler;
    uncaught_handler = fn; //赋值
    return result;
}
crash分类

crash的主要原因是收到了未处理的信号,主要来源于三个地方:kernel内核其他进行app本身,所以crash对应的也分为了三种

针对应用级异常,可以通过注册异常捕获的函数,即NSSetUncaughtExceptionHandler机制,实现线程保活, 收集上传崩溃日志

应用级crash拦截

在开发中,我们可以在代码中给一个异常句柄NSSetUncaughtExceptionHandler,传入一个函数给系统,当异常发生后,调用函数(该函数可以线程保活,收集并上传奔溃日志),然后回到原有的app层,本质就是一个回调函数

crash处理

6、cache_init:缓存初始化

源码如下

void cache_init()
{
#if HAVE_TASK_RESTARTABLE_RANGES
    mach_msg_type_number_t count = 0;
    kern_return_t kr;

    while (objc_restartableRanges[count].location) {
        count++;
    }
    //为当前任务注册一组可重新启动的缓存
    kr = task_restartable_ranges_register(mach_task_self(),
                                          objc_restartableRanges, count);
    if (kr == KERN_SUCCESS) return;
    _objc_fatal("task_restartable_ranges_register failed (result 0x%x: %s)",
                kr, mach_error_string(kr));
#endif // HAVE_TASK_RESTARTABLE_RANGES
}

7、_imp_implementationWithBlock_init:启动回调机制

该方法主要是启动回调机制,通常这不会做什么,因为所有的初始化都是惰性的,但是对于某些进程,我们会迫不及待地加载libobjc-trampolines.dylib,其源码如下

void
_imp_implementationWithBlock_init(void)
{
#if TARGET_OS_OSX
    // Eagerly load libobjc-trampolines.dylib in certain processes. Some
    // programs (most notably QtWebEngineProcess used by older versions of
    // embedded Chromium) enable a highly restrictive sandbox profile which
    // blocks access to that dylib. If anything calls
    // imp_implementationWithBlock (as AppKit has started doing) then we'll
    // crash trying to load it. Loading it here sets it up before the sandbox
    // profile is enabled and blocks it.
    // 在某些进程中渴望加载libobjc-trampolines.dylib。一些程序(最著名的是嵌入式Chromium的较早版本使用的QtWebEngineProcess)启用了严格限制的沙箱配置文件,从而阻止了对该dylib的访问。如果有任何调用imp_implementationWithBlock的操作(如AppKit开始执行的操作),那么我们将在尝试加载它时崩溃。将其加载到此处可在启用沙箱配置文件之前对其进行设置并阻止它。
    // This fixes EA Origin (rdar://problem/50813789)
    // and Steam (rdar://problem/55286131)
    if (__progname &&
        (strcmp(__progname, "QtWebEngineProcess") == 0 ||
         strcmp(__progname, "Steam Helper") == 0)) {
        Trampolines.Initialize();
    }
#endif
}

8、_dyld_objc_notify_register:dyld注册

_dyld_objc_notify_register方法

_dyld_objc_notify_register方法实现在dyld加载流程有详细说明
下面是_dyld_objc_notify_register方法的声明

//
// Note: only for use by objc runtime
// Register handlers to be called when objc images are mapped, unmapped, and initialized.
// Dyld will call back the "mapped" function with an array of images that contain an objc-image-info section.
// Those images that are dylibs will have the ref-counts automatically bumped, so objc will no longer need to
// call dlopen() on them to keep them from being unloaded.  During the call to _dyld_objc_notify_register(),
// dyld will call the "mapped" function with already loaded objc images.  During any later dlopen() call,
// dyld will also call the "mapped" function.  Dyld will call the "init" function when dyld would be called
// initializers in that image.  This is when objc calls any +load methods in that image.
//
void _dyld_objc_notify_register(_dyld_objc_notify_mapped    mapped,
                                _dyld_objc_notify_init      init,
                                _dyld_objc_notify_unmapped  unmapped);

我们可以冲注释中得出

dyld与Objc的关联

===> dyld源码--具体实现
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);
}

🔽
===> libobjc源码中--调用
_dyld_objc_notify_register(&map_images, load_images, unmap_image);

从上可以得出

结合dyld加载流程,dyld与Objc的关联如下图所示

dyld与Objc的关联

环境变量汇总

环境变量
上一篇 下一篇

猜你喜欢

热点阅读