在上一篇文章iOS原理探索10-應用程序的加載流程
中,我們梳理了dyld的加載流程,應用程序的加載流程
,本篇文章主要 來闡述一下dyld是如何關聯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?
//讀取環境變量
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();
// 什么時候調用? images 鏡像文件
// map_images()
// load_images()
_dyld_objc_notify_register(& map_images, load_images, unmap_image);
#if __OBJC2__
didCallDyldNotifyRegister = true;
#endif
}
1、 environ_init();
:主要是讀取環境變量;
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++
靜態構造函數,在dyld
調用我們的靜態析構函數之前
,libc會調用_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運行時環境初始化
,里面主要是unattachedCategories、allocatedClasses -- 分類初始化
。
void runtime_init(void)
{
objc::unattachedCategories.init(32);
objc::allocatedClasses.init();
}
5、 exception_init();
:主要是初始化libobjc的異常處理系統
,注冊異常處理的回調,從而監控異常的處理。
/***********************************************************************
* exception_init
* Initialize libobjc's exception handling system.
* Called by map_images().
**********************************************************************/
void exception_init(void)
{
old_terminate = std::set_terminate(&_objc_terminate);
}
- 當有
crash(crash是指系統發生的不允許的一些指令,然后系統給的一些信號)發生時
,會來到_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
拋出異常的函數。fn
為外界傳入的函數。
objc_uncaught_exception_handler
objc_setUncaughtExceptionHandler(objc_uncaught_exception_handler fn)
{
// fn為設置的異常句柄 傳入的函數,為外界給的
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++;
}
//為當前任務注冊一組可重新啟動的緩存
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();
:啟動回調機制
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(& map_images, load_images, unmap_image);
:這個方法的具體實現在iOS原理探索10-應用程序的加載流程有詳細的講述,它的源碼實現是在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
: dyld
將image鏡像
加載進內存;
load_images
: dyld
初始化image鏡像文件
會觸發該函數;
unmap_image
: dyld
將image
鏡像文件移除
的時候觸發該函數;
二、map_images
函數
- map_images我們結合上篇iOS原理探索10-應用程序的加載流程,知道在dyld的源碼中的調用順序為:
_dyld_objc_notify_register ---> registerObjCNotifiers --> sNotifyObjCMapped
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;
... 省略部分代碼 ....
}
- 根據
sNotifyObjCMapped
,在項目中查找調用的地方
sNotifyObjCMapped被調用的方法
三、load_images
同上,查找sNotifyObjCInit
被調用的地方
sNotifyObjCInit被調用的函數位置
四、unmap_image
,刪除鏡像,同上查找sNotifyObjCUnmapped
在dyld調用位置
sNotifyObjCUnmapped被調用的函數位置
sNotifyObjCUnmapped被調用的函數位置