您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

從源代碼看 Objective-C 中消息的發送與方法查找

編輯:iOS 開發基礎

本文授權轉載,作者:左書祺(關注倉庫,及時獲得更新:iOS-Source-Code-Analyze)

由於 Objective-C 的 runtime 只能在 Mac OS 下編譯,文中程式碼都運行在 Mac OS(x86_64 架構)環境;對於 arm64 上的差異會特別說明。

寫在前面

你會點開這篇文章,大概對 Objective-C 已經相當熟悉,也有幾年經驗。本文假設你已經知道:

  1. Objective-C 中的「方法呼叫」其實應該叫消息傳遞
  2. [receiver message] 會被翻譯成 objc_msgSend(receiver, @selector(message))
  3. 消息的響應鏈中可能會呼叫 -resolveInstanceMethod: 或 -forwardInvocation: 等方法
  4. 關於選擇子 SEL 的基本知識。若對上述內容不熟,可以先看 Objective-C Runtime 那篇文章,不過其中關於 objc_class 結構體的程式碼已經過時,不影響閱讀與理解
  5. 方法在記憶體中的存放位置,可參考〈深入解析 ObjC 中方法的結構〉。文中不會刻意區分方法與函式、消息傳遞與方法呼叫
  6. 能翻牆(會出現一個 YouTube 連結)

概述

談 Objective-C 消息傳遞的文章實在太多了,這篇的差別在哪?由於整個系列都是對 Objective-C 源代碼的分析,本文會從源代碼出發,去分析並合理推測消息傳遞的相關問題。

關於 @selector() 你需要知道的

在 Objective-C 中,所有消息傳遞裡的「消息」都會被轉換成一個 selector,作為 objc_msgSend 的參數:

[object hello] -> objc_msgSend(object, @selector(hello))

這裡由 @selector(hello) 產生的選擇子 SEL 是這節的重點。我們要先解決一個問題:由 @selector(hello) 產生的選擇子,會不會因為類的不同而不同?

先給結論:不會。選擇子的記憶體位址在編譯期就已經確定,也就是說,向不同的類發送相同的消息,產生的選擇子完全相同。

XXObject *xx = [[XXObject alloc] init];
YYObject *yy = [[YYObject alloc] init];

objc_msgSend(xx, @selector(hello));
objc_msgSend(yy, @selector(hello));

接下來驗證這個結論。測試程式碼如下:

// XXObject.h
#import 

@interface XXObject : NSObject
- (void)hello;
@end

// XXObject.m
#import "XXObject.h"

@implementation XXObject
- (void)hello {
    NSLog(@"Hello");
}
@end

// main.m
#import 
#import "XXObject.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        XXObject *object = [[XXObject alloc] init];
        [object hello];
    }
    return 0;
}

在 main 函式任意位置下中斷點,例如 -> [object hello]; 這一行,然後在 lldb 中輸入:

這裡我們列印了兩個選擇子的位址:@selector(hello) 與 @selector(undefined_hello_method)。要注意的是,前者是編譯期就宣告的選擇子,後者在編譯期並不存在,是執行期才產生的,所以記憶體位址明顯比 hello 大很多。

如果修改程式碼:

由於我們在程式碼中明確寫出了 @selector(undefined_hello_method),此時在 lldb 中再次列印這個 SEL 的位址,跟先前相比有了明顯變化。

更關鍵的是:我並沒有透過任何指標操作去取得 hello 選擇子的位址,僅僅靠 @selector(hello) 就拿到了它。

從這些現象可以推斷選擇子具有以下特性:

  1. Objective-C 為我們維護了一個巨大的選擇子表
  2. 使用 @selector() 時,會在這個表中依名稱查找對應的 SEL;找不到則建立一個並加入表中
  3. 編譯期會掃描全部標頭檔與實作檔,把其中定義的方法以及 @selector() 產生的選擇子都收進這張表

在 runtime 初始化之前,列印 hello 選擇子的位址:

message.h

objc_msgSend 的實作並未開源,它只存在於 message.h 這個標頭檔中:

/**
 * @note When it encounters a method call, the compiler generates a call to one of the
 * functions \c objc_msgSend, \c objc_msgSend_stret, \c objc_msgSendSuper, or \c objc_msgSendSuper_stret.
 * Messages sent to an object’s superclass (using the \c super keyword) are sent using \c objc_msgSendSuper;
 * other messages are sent using \c objc_msgSend.
 * Methods that have data structures as return values are sent using \c objc_msgSendSuper_stret and \c objc_msgSend_stret.
 */
OBJC_EXPORT id objc_msgSend(id self, SEL op, ...)

註解把規則講得很清楚:編譯器遇到方法呼叫時,會翻譯成 objc_msgSend、objc_msgSend_stret、objc_msgSendSuper 或 objc_msgSendSuper_stret 其中之一。送給父類的消息用 objc_msgSendSuper;有資料結構作為回傳值的方法用 objc_msgSendSuper_stret 或 objc_msgSend_stret;其餘一律用 objc_msgSend。

本文只分析消息發送的過程,不討論上述幾個函式彼此的差異,一律以 objc_msgSend 代稱。

objc_msgSend 的呼叫棧

這節以向 XXObject 實例發送 hello 消息為例,在 Xcode 中觀察整個過程中呼叫棧的變化。

在呼叫 hello 的那一行下中斷點,當我們嘗試 Step Into 時,會直接跳進方法實作,而不會進入 objc_msgSend:

因為 objc_msgSend 是私有方法,我們沒辦法進入它的實作。但我們可以在它的呼叫棧上「攔下」這個過程。

呼叫 objc_msgSend 時傳入了 self 與 SEL。既然要執行對應的方法,就一定要去找選擇子對應的實作。

objc-runtime-new.mm 中有一個函式 lookUpImpOrForward,職責正是查找方法的實作。於是讓程式跑到 hello 這一行,觸發 lookUpImpOrForward 中的中斷點。

由於轉成 gif 檔案實在太大,筆者嘗試了各種方法都得不到理想效果,只能貼一個 YouTube 視頻連結(能翻牆的開發者應該沒問題,手動微笑)。如果跟著視頻看呼叫棧覺得一團亂,那是正常的——下一節會詳細拆解。

解析 objc_msgSend

我們會向 XXObject 的實例發送兩次 hello 消息,分別模擬「無緩存」與「有緩存」兩種情況。

無緩存

在 -> [object hello] 處下中斷點,程式跑到這裡後,再在 lookUpImpOrForward 的第一行下中斷點,確保攔到的是 @selector(hello) 的呼叫棧,而不是其他選擇子。

從變數區域可以看到,傳入的選擇子是 "hello",對應的類是 XXObject,確認這正是呼叫 hello 時執行的函式。Xcode 左側的呼叫棧是:

0 lookUpImpOrForward
1 _class_lookupMethodAndLoadCache3
2 objc_msgSend
3 main
4 start

也就是說,lookUpImpOrForward 並不是 objc_msgSend 直接呼叫的,中間還隔著 _class_lookupMethodAndLoadCache3:

IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls) {
    return lookUpImpOrForward(cls, sel, obj,
                              YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}

這個函式只提供給派發器(dispatcher)做方法查找,其他程式碼應該使用 lookUpImpOrNil()(不進行方法轉發)。它傳入 cache=NO,避免在沒加鎖的情況下查緩存,因為派發器已經做過這件事了。

實作的查找:lookUpImpOrForward

這個函式牽涉大量呼叫,拆成幾段來看:

  1. 無鎖的緩存查找
  2. 若類尚未 realize 或 initialize,則先完成這兩件事
  3. 加鎖
  4. 查找緩存與當前類的方法
  5. 查找父類的緩存與方法列表
  6. 找不到時嘗試方法解析器
  7. 進行消息轉發
  8. 解鎖、回傳實作

無鎖的緩存查找。這段在沒加鎖時先查一次緩存,用來提升效能:

runtimeLock.assertUnlocked();

// Optimistic cache lookup
if (cache) {
    imp = cache_getImp(cls, sel);
    if (imp) return imp;
}

不過因為 _class_lookupMethodAndLoadCache3 傳入的 cache=NO,這裡會直接跳過 if 中的程式碼——在 objc_msgSend 中已經用組語查過了。

類的實現與初始化。Objective-C runtime 初始化過程中會對類做第一次初始化,也就是執行 realizeClass,為類配置可讀寫結構體 class_rw_t 的空間並回傳正確的類結構。而 _class_initialize 則會呼叫類的 initialize 方法。

if (!cls->isRealized()) {
    rwlock_writer_t lock(runtimeLock);
    realizeClass(cls);
}

if (initialize && !cls->isInitialized()) {
    _class_initialize(_class_getNonMetaClass(cls, inst));
}

加鎖。只有一行,目的是保證方法查找與緩存填充(cache-fill)的原子性,避免執行期間新方法被加入導致緩存被沖洗(flush)。

runtimeLock.read();

在當前類中查找實作。先用 cache_getImp 從該類的 cache 屬性取出選擇子對應的實作:

imp = cache_getImp(cls, sel);
if (imp) goto done;

cache_getImp 的實作目測同樣不開源,而且是組語寫的。Step Into 時會進入類似下面的組語:

它會跳到一個 CacheLookup 標籤去取實作。用組語的原因顯然是為了加速查找,原理推測就是在類的 cache 中尋找對應實作,只是做了效能上的優化。

如果找到實作就跳到 done。但本節假設是無緩存(第一次呼叫 hello),所以會進入下面的程式碼塊,從類的方法列表中尋找:

meth = getMethodNoSuper_nolock(cls, sel);
if (meth) {
    log_and_fill_cache(cls, meth->imp, sel, inst, cls);
    imp = meth->imp;
    goto done;
}

getMethodNoSuper_nolock 負責查找對應的方法結構體指標 method_t:

static method_t *getMethodNoSuper_nolock(Class cls, SEL sel) {
    for (auto mlists = cls->data()->methods.beginLists(),
              end = cls->data()->methods.endLists();
         mlists != end;
         ++mlists) {
        method_t *m = search_method_list(*mlists, sel);
        if (m) return m;
    }
    return nil;
}

類中的方法列表 methods 是一個二維陣列 method_array_t,所以要用 for 迴圈遍歷,而 search_method_list 的實作也很直白:

static method_t *search_method_list(const method_list_t *mlist, SEL sel) {
    int methodListIsFixedUp = mlist->isFixedUp();
    int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t);

    if (__builtin_expect(methodListIsFixedUp && methodListHasExpectedSize, 1)) {
        return findMethodInSortedMethodList(sel, mlist);
    } else {
        for (auto &meth : *mlist) {
            if (meth.name == sel) return &meth;
        }
    }
    return nil;
}

findMethodInSortedMethodList 對有序方法列表做線性探測,回傳 method_t。

若在此找到實作,會把它加入類的緩存,這一步由 cache_fill_nolock 完成:

static void cache_fill_nolock(Class cls, SEL sel, IMP imp, id receiver) {
    if (!cls->isInitialized()) return;
    if (cache_getImp(cls, sel)) return;

    cache_t *cache = getCache(cls);
    cache_key_t key = getKey(sel);

    mask_t newOccupied = cache->occupied() + 1;
    mask_t capacity = cache->capacity();

    if (cache->isConstantEmptyCache()) {
        cache->reallocate(capacity, capacity ?: INIT_CACHE_SIZE);
    } else if (newOccupied > capacity * 3 / 4) {
        cache->expand();
    }

    bucket_t *bucket = cache->find(key, receiver);
    if (bucket->key() == 0) cache->incrementOccupied();
    bucket->set(key, imp);
}

當緩存內容超過容量的四分之三時會擴容,大小翻倍。擴容過程中當前類的全部緩存都會被清空——出於效能考量,Objective-C 不會把舊的 bucket_t 複製到新配置的記憶體中。最後找到第一個空的 bucket_t,以 (SEL, IMP) 的形式填入。

在父類中尋找實作。邏輯與上面幾乎相同,只是多了一層迴圈來判斷根類:先查緩存,再搜方法列表。

curClass = cls;
while ((curClass = curClass->superclass)) {
    imp = cache_getImp(curClass, sel);
    if (imp) {
        if (imp != (IMP)_objc_msgForward_impcache) {
            log_and_fill_cache(cls, imp, sel, inst, curClass);
            goto done;
        } else {
            break;
        }
    }

    meth = getMethodNoSuper_nolock(curClass, sel);
    if (meth) {
        log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
        imp = meth->imp;
        goto done;
    }
}

與在當前類中查找的差別在於:在父類中找到的 _objc_msgForward_impcache 會交給當前類處理。

方法決議。選擇子在當前類與父類都找不到實作,就進入方法決議(method resolve):

if (resolver && !triedResolver) {
    _class_resolveMethod(cls, sel, inst);
    triedResolver = YES;
    goto retry;
}

_class_resolveMethod 負責解析找不到實作的方法:

void _class_resolveMethod(Class cls, SEL sel, id inst) {
    if (!cls->isMetaClass()) {
        _class_resolveInstanceMethod(cls, sel, inst);
    } else {
        _class_resolveClassMethod(cls, sel, inst);
        if (!lookUpImpOrNil(cls, sel, inst,
                            NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) {
            _class_resolveInstanceMethod(cls, sel, inst);
        }
    }
}

它會依當前類是否為元類,在 _class_resolveInstanceMethod 與 _class_resolveClassMethod 之間做選擇:

static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst) {
    if (!lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls,
                        NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) {
        // 沒有找到 resolveInstanceMethod: 方法,直接返回
        return;
    }

    BOOL (*msg)(Class, SEL, SEL) = (__typeof__(msg))objc_msgSend;
    bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);

    // 快取結果,避免下次呼叫 resolveInstanceMethod: 影響效能
    IMP imp = lookUpImpOrNil(cls, sel, inst,
                             NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
}

兩者的實作本質相同:判斷當前類是否實作了 resolveInstanceMethod: 或 resolveClassMethod:,若有則用 objc_msgSend 執行它,並把需要決議的選擇子傳進去。

執行完 resolveInstanceMethod: 之後會跳到 retry 標籤,重新走一遍查找流程,只是不會再呼叫解析器(triedResolver 已標記為 YES)。

消息轉發。當緩存、當前類、父類以及 resolveInstanceMethod: 都無法解決問題時,Objective-C 還留了最後一次機會:

imp = (IMP)_objc_msgForward_impcache;
cache_fill(cls, sel, imp, inst);

回傳 _objc_msgForward_impcache 並加入緩存。至此,第一次呼叫的完整流程結束:緩存未命中,但在當前類的方法列表中找到了 hello 的實作並執行了它。

緩存命中

如果選擇子命中緩存,情況就完全不同了。修改主程式:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        XXObject *object = [[XXObject alloc] init];
        [object hello];
        [object hello];
    }
    return 0;
}

在第二次呼叫 hello 時下中斷點:

objc_msgSend 完全沒有走 lookUpImpOrForward,而是直接結束並列印了另一個 hello 字串。

那我們怎麼確認 objc_msgSend 的實作究竟是什麼?老實說沒辦法確認,因為它是組語寫的且不開源。但我們可以驗證它是否真的存取類中的緩存來加速查找。

重新執行到第二次 hello 呼叫之前:

列印緩存中 bucket 的內容:

(lldb) p (objc_class *)[XXObject class]
(objc_class *) $0 = 0x0000000100001230

(lldb) p (cache_t *)0x0000000100001240
(cache_t *) $1 = 0x0000000100001240

(lldb) p *$1
(cache_t) $2 = {
  _buckets = 0x0000000100604bd0
  _mask    = 3
  _occupied = 2
}

(lldb) p $2.capacity()
(mask_t) $3 = 4

(lldb) p $2.buckets()[0]
(bucket_t) $4 = { _key = 0, _imp = 0x0000000000000000 }

(lldb) p $2.buckets()[1]
(bucket_t) $5 = { _key = 0, _imp = 0x0000000000000000 }

(lldb) p $2.buckets()[2]
(bucket_t) $6 = {
  _key = 4294971294
  _imp = 0x0000000100000e60 (debug-objc`-[XXObject hello] at XXObject.m:17)
}

(lldb) p $2.buckets()[3]
(bucket_t) $7 = {
  _key = 4300169955
  _imp = 0x00000001000622e0 (libobjc.A.dylib`-[NSObject init] at NSObject.mm:2216)
}

這個緩存裡只有 hello 與 init 兩個方法的實作。我們把 hello 的緩存清掉:

(lldb) expr $2.buckets()[2] = $2.buckets()[1]
(bucket_t) $8 = { _key = 0, _imp = 0x0000000000000000 }

此時 XXObject 中已經沒有 hello 對應實作的緩存了。繼續執行:

雖然是第二次呼叫 hello,但因為我們清掉了緩存,程式又再次進入了 lookUpImpOrForward。

再換個方式驗證:在 hello 呼叫之前先塞入緩存。定義一個新的實作 cached_imp:

#import 
#import 
#import "XXObject.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        __unused IMP cached_imp = imp_implementationWithBlock(^() {
            NSLog(@"CachedHello");
        });

        XXObject *object = [[XXObject alloc] init];
        [object hello];
        [object hello];
    }
    return 0;
}

以 @selector(hello) 與 cached_imp 為鍵值對,把它加入類結構體的緩存。這個 cached_imp 會列印 "CachedHello" 而非 "Hello"。在第一個 hello 呼叫之前完成插入:

可以看到,我們完全沒有改動 hello 方法的實作,但在 objc_msgSend 的鏈路中,錯誤的緩存實作 cached_imp 攔截了查找,列印出了 CachedHello。

由此可以推定:objc_msgSend 在實作中確實會檢查緩存;若無緩存,才會呼叫 lookUpImpOrForward 進行查找。而為了提升消息傳遞效率,Objective-C 用組語實作了 objc_msgSend 與 cache_getImp。

小結

這篇文章與其說在講消息發送的過程,不如說在講方法實作是如何被找到的。Objective-C 的查找路徑相當符合直覺:

  • 緩存命中
  • 查找當前類的緩存及方法
  • 查找父類的緩存及方法
  • 方法決議
  • 消息轉發

關於方法呼叫棧的錄影最初是用 gif 做的,但時長較長,試了很多轉換器都得不到理想的品質與檔案大小,最後改用 YouTube 視頻呈現。

參考資料

深入解析 ObjC 中方法的結構

Objective-C Runtime

Let's Build objc_msgSend

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved