dyld和objc的关联

2020-10-18  本文已影响0人  lkm_0bdc

接下来让我们一起探索dyld和objc的关联
首先查看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?
    environ_init();
    tls_init();
    static_init();
    runtime_init();
    exception_init();
    cache_init();
    _imp_implementationWithBlock_init();

    // 什么时候调用? images 镜像文件
    // map_images()
    // load_images()
    
    _dyld_objc_notify_register(&map_images, load_images, unmap_image);

#if __OBJC2__
    didCallDyldNotifyRegister = true;
#endif
}

environ_init源码

我们可以在PrintHelp这里查看环境变量,但是由于一些条件限制,无法打印环境变量,那么我们可以将for循环单独写出来进行打印。

//打印环境变量
//    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);
//    }
    // Print OBJC_HELP and OBJC_PRINT_OPTIONS output.
    if (PrintHelp  ||  PrintOptions) {
        if (PrintHelp) {
            _objc_inform("Objective-C runtime debugging. Set variable=YES to enable.");
            _objc_inform("OBJC_HELP: describe available environment variables");
            if (PrintOptions) {
                _objc_inform("OBJC_HELP is set");
            }
            _objc_inform("OBJC_PRINT_OPTIONS: list which options are set");
        }
        if (PrintOptions) {
            _objc_inform("OBJC_PRINT_OPTIONS is set");
        }

        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);
        }
    }

打印结果


也可以通过终端进行打印输入:export OBJC_hrlp=1,打印环境变量

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

tls_init()源码

关于线程key的绑定 - 比如每线程数据的析构函数

void tls_init(void)
{
#if SUPPORT_DIRECT_THREAD_KEYS
    pthread_key_init_np(TLS_DIRECT_KEY, &_objc_pthread_destroyspecific);
#else
    _objc_pthread_key = tls_create(&_objc_pthread_destroyspecific);
#endif
}
static_init()源码

运行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]();
    }
}
runtime_init()源码

runtime运行时环境初始化,里面主要是:unattachedCategories,allocatedClasses (后面会分析)

void runtime_init(void)
{
    objc::unattachedCategories.init(32);
    objc::allocatedClasses.init();
}
exception_init()源码

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

void exception_init(void)
{
    old_terminate = std::set_terminate(&_objc_terminate);
}

当有crash(系统发生的不允许的一些指令,然后系统给的一些信号)发生时,会进入_objc_terminate方法,走到uncaught_handler扔出异常

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)();
        }
    }
}

搜索uncaught_handlerapp层传入的函数,用于处理异常,以便调用函数

objc_setUncaughtExceptionHandler(objc_uncaught_exception_handler fn)
{
    //fn外界传入的函数
    objc_uncaught_exception_handler result = uncaught_handler;
    uncaught_handler = fn;
    return result;
}

crash分类

crash的主要原因是收到了未处理的信号,主要来源于三个地方:

crash也分为了3种:

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

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
}
_imp_implementationWithBlock_init()源码

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

_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.
    //
    // 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
}
_dyld_objc_notify_register()源码
void _dyld_objc_notify_register(_dyld_objc_notify_mapped    mapped,
                                _dyld_objc_notify_init      init,
                                _dyld_objc_notify_unmapped  unmapped);

方法中的三个参数分别表示的含义如下:

探索什么时候调用map_images和load_image

dyld与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);
}

可以看出,load_images是在notifySingle方法中,通过sNotifyObjCInit调用的,如图所示

通过_dyld_objc_notify_register --> registerObjCNotifiers在该方法中将_dyld_objc_notify_register传入的参数赋值给了3个回调方法

它们的关系
sNotifyObjCMapped == mapped == map_images
sNotifyObjCInit == init == load_images
sNotifyObjCUnmapped == unmapped == unmap_image

map_images调用时机

dyld中全局搜索 sNotifyObjcMappedregisterObjCNotifiers -- notifyBatchPartial -- sNotifyObjCMapped

全局搜索notifyBatchPartial,在registerObjCNotifiers方法中调用

结论:map_images是先于load_images调用

上一篇 下一篇

猜你喜欢

热点阅读