iOS原理探索11--dyld是如何關(guān)聯(lián)objc的

在上一篇文章iOS原理探索10-應(yīng)用程序的加載流程
中,我們梳理了dyld的加載流程,應(yīng)用程序的加載流程,本篇文章主要 來闡述一下dyld是如何關(guān)聯(lián)objc的。在探索之前,我們首先找到libObjc中的_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?
    //讀取環(huán)境變量
    environ_init();
    //線程key的綁定
    tls_init();
    //運行c++靜態(tài)構(gòu)造函數(shù),在dyld調(diào)用我們的靜態(tài)析構(gòu)函數(shù)之前,libc會調(diào)用_objc_init(),因此我們必須自己做
    static_init();
    //runtime運行時環(huán)境初始化,里面主要是unattachedCategories、allocatedClasses -- 分類初始化
    runtime_init();
//初始化libobjc的異常處理系統(tǒng)
    exception_init();
//緩存條件的初始化
    cache_init();
//啟動回調(diào)機制,通常這不會做什么,因為所有的初始化都是惰性的,但是對于某些進程,我們會迫不及待地加載trampolines dylib
    _imp_implementationWithBlock_init();

    // 什么時候調(diào)用? images 鏡像文件
    // map_images()
    // load_images()
    
    _dyld_objc_notify_register(& map_images, load_images, unmap_image);

#if __OBJC2__
    didCallDyldNotifyRegister = true;
#endif
}
1、 environ_init();:主要是讀取環(huán)境變量;
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);//析構(gòu)
#endif
}
3、 static_init();:運行c++靜態(tài)構(gòu)造函數(shù),在dyld調(diào)用我們的靜態(tài)析構(gòu)函數(shù)之前libc會調(diào)用_objc_init(),因此我們必須自己做。
/***********************************************************************
* static_init
* Run C++ static constructor functions.
* libc calls _objc_init() before dyld would call our static constructors, 
* so we have to do it ourselves.
**********************************************************************/
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();:runtime運行時環(huán)境初始化,里面主要是unattachedCategories、allocatedClasses -- 分類初始化
void runtime_init(void)
{
    objc::unattachedCategories.init(32);
    objc::allocatedClasses.init();
}

5、 exception_init();:主要是初始化libobjc的異常處理系統(tǒng),注冊異常處理的回調(diào),從而監(jiān)控異常的處理。
/***********************************************************************
* exception_init
* Initialize libobjc's exception handling system.
* Called by map_images().
**********************************************************************/
void exception_init(void)
{
    old_terminate = std::set_terminate(&_objc_terminate);
}
  • 當(dāng)有crash(crash是指系統(tǒng)發(fā)生的不允許的一些指令,然后系統(tǒng)給的一些信號)發(fā)生時,會來到_objc_terminate方法,走到uncaught_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_setUncaughtExceptionHandler拋出異常的函數(shù)。fn為外界傳入的函數(shù)。
objc_uncaught_exception_handler 
objc_setUncaughtExceptionHandler(objc_uncaught_exception_handler fn)
{
//    fn為設(shè)置的異常句柄 傳入的函數(shù),為外界給的
    objc_uncaught_exception_handler result = uncaught_handler;
    uncaught_handler = fn; //賦值
    return result;
}
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++;
    }
    //為當(dāng)前任務(wù)注冊一組可重新啟動的緩存
    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();:啟動回調(diào)機制
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的訪問。如果有任何調(diào)用imp_implementationWithBlock的操作(如AppKit開始執(zhí)行的操作),那么我們將在嘗試加載它時崩潰。將其加載到此處可在啟用沙箱配置文件之前對其進行設(shè)置并阻止它。
    // 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(& map_images, load_images, unmap_image);:這個方法的具體實現(xiàn)在iOS原理探索10-應(yīng)用程序的加載流程有詳細的講述,它的源碼實現(xiàn)是在dyld源碼中,以下是_dyld_objc_notify_register方法的聲明,主要是在運行時使用,來注冊處理程序,以便于映射、取消映射以及初始化obj對象時候使用
void _dyld_objc_notify_register(_dyld_objc_notify_mapped    mapped,
                                _dyld_objc_notify_init      init,
                                _dyld_objc_notify_unmapped  unmapped);

map_images : dyldimage鏡像加載進內(nèi)存;
load_images : dyld初始化image鏡像文件會觸發(fā)該函數(shù);
unmap_image: dyldimage鏡像文件移除的時候觸發(fā)該函數(shù);

二、map_images函數(shù)
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;
       ... 省略部分代碼 ....
}
  • 根據(jù)sNotifyObjCMapped,在項目中查找調(diào)用的地方
    sNotifyObjCMapped被調(diào)用的方法
三、load_images同上,查找sNotifyObjCInit被調(diào)用的地方
sNotifyObjCInit被調(diào)用的函數(shù)位置

四、unmap_image,刪除鏡像,同上查找sNotifyObjCUnmapped在dyld調(diào)用位置
sNotifyObjCUnmapped被調(diào)用的函數(shù)位置

總結(jié):dyld和obj的關(guān)系,在obj中dyld注冊,相當(dāng)于發(fā)送通知,在dyld中注冊回調(diào)函數(shù),相當(dāng)于觀察者,當(dāng)觸發(fā)回調(diào)的時候就會調(diào)用執(zhí)行通知執(zhí)行通知selector。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。