iOS底層學習 - Runtime之方法消息的前世此生(一)

通過前幾章的探索,已經瞭解了對象和類的底層實現,對屬性、成員變量和方法的存儲也有了必定的瞭解,明白了方法的緩存機制,那麼方法究竟是如何進行調用的,它的整個流程是什麼樣的,怎麼進行轉發的,咱們本章來探究一下編程

傳送門☞iOS底層學習 - 類的前世此生(一)數組

傳送門☞iOS底層學習 - 類的前世此生(二)緩存

RunTime簡介

咱們都知道OC是一門動態語言,分爲編譯時和運行時,而Runtime是OC進行運行時支持APIsass

  • Objective-C是一門動態性比較強的編程語言,根C、C++等語言有很大不一樣
  • Objective-C的動態性是由Runtime API來支撐的
  • Runtime API提供的接口基本都是C語言的,源碼由C/C++/彙編語言編寫

主要代碼

一、Objective-C code:例如@selector()bash

二、NSObject的方法:例如NSSelectorFromString()編程語言

三、Runtime Api:例如sel_registerNameide

運行時

將代碼裝載在內存在須要的是進行調用就叫作運行時函數

編譯時

Xcode中command+B就是編譯時操做,將語法翻譯成機器能識別的語言,編譯成的可執行文件,運行的時候就是將這個可執行文件加載到內存中 post

方法的本質

經過運行clang命令,查看方法sayNB在編譯後是如何運行的性能

LGPerson *person = [LGPerson alloc];
[person sayNB];
複製代碼
LGPerson *person = ((LGPerson *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("LGPerson"), sel_registerName("alloc"));
((void (*)(id, SEL))(void *)objc_msgSend)((id)person, sel_registerName("sayNB"));
複製代碼

經過上面的例子咱們知道,方法再底層會變成objc_msgSend方法,即經過objc_msgSend來發送消息,其實obj表示消息接受者,sel_registerName是Runtime的API,表示根據一個方法名,返回一個SEL

objc_msgSend(obj, sel_registerName("sayNB"));
複製代碼
SEL sel_registerName(const char *name) {
    return __sel_registerName(name, 1, 1);     // YES lock, YES copy
}
複製代碼

消息的發送

既然知道了方法的本質即爲objc_msgSend的消息發送,那麼他是怎麼實現的呢,經過objc源碼,咱們能夠知道objc_msgSend方法再底層是由彙編來實現的,咱們主要研究iOS設備的arm64結構的彙編實現

使用匯編的主要緣由:

  • 對於一些調用頻率過高的函數或操做,使用匯編來實現可以提升效率和性能,容易被機器來識別。
  • 一些未知參數的識別,用C或者C++來實現比較困難

咱們能夠先到 objc_msgSend相關彙編實現以下

GetClassFromIsa_p16方法即表明經過對象的 isa & mask便可獲得類,這個和以前章節講過的方式是同樣的,只不過這裏是彙編實現

快速查找流程

快速流程即經過底層彙編代碼快速找到方法的調用IMP,經過上面的代碼分析,咱們能夠查看CacheLookup NORMAL相關代碼

經過註釋咱們可知,該方法有3中參數NORMAL,GETIMP,LOOKUP,咱們目前使用的是NORMAL參數

CacheLookup NORMAL主要查找流程以下,基本就是經過彙編來實現上一章節中,對類的cache_find的操做,從而找到對應緩存的IMP

CacheHit即爲把響應的 IMP返回給接受者
CheckMiss說明類的緩存中沒有響應的IMP,會調用 __objc_msgSend_uncached進行下一步查找
能夠發現 __objc_msgSend_uncached的實現中,主要進行了 MethodTableLookup操做
MethodTableLookup中主要對未知的參數進行了一系列的處理,而後,調用 __class_lookupMethodAndLoadCache3進行 慢速查找,這是一個C和C++函數,因此調用起來比彙編要慢

流程小結

1.對接受者進行判空處理

2.進行taggedPoint等異常處理

3.獲取到接受者isa,對isa & mask 獲取到class

4.經過對class的isa進行指針偏移,獲取到cache_t

5.經過對cache_t中key & mask 獲取到下標,查找到對應的bucket,獲取到其中的IMP

6.若是上述沒有找到IMP,走到__objc_msgSend_uncached中的MethodTableLookup開始慢速查找

慢速查找流程

經過上述的彙編快速查找,若是沒有方法的緩存,則會進入這個慢速查找的流程,那麼慢速查找流程的起點是什麼,咱們能夠經過打斷點,看彙編代碼查看

首先斷點在須要跟蹤的方法,打開Xcode中的Always Show Disassembly便可跟蹤到相對應的彙編實現

經過跟蹤彙編調用的實現,總到了快速查找的最後一步 __objc_msgSend_uncached

繼續跟蹤,咱們能夠發現調用了方法 _class_lookupMethodAndLoadCache3,自此開始了慢速查找的流程

lookUpImpOrForward方法分析

IMP lookUpImpOrForward(Class cls, SEL sel, id inst, 
                       bool initialize, bool cache, bool resolver)
{
    💡//️接收傳入的參數, initialize = YES , cache = NO , resolver = YES
    💡//初始化相關參數
    IMP imp = nil;
    bool triedResolver = NO;
    runtimeLock.assertUnlocked();

    💡// 緩存查找, 由於cache傳入的爲NO,這裏不會進行緩存查找,由於在彙編語言中CacheLookup已經查找過
    if (cache) {
        imp = cache_getImp(cls, sel);
        if (imp) return imp;
    }
    ❗️// 當類沒有初始化時,初始化類和父類、元類等,保證後面方法的查找流程
    runtimeLock.read();
    if (!cls->isRealized()) {
        runtimeLock.unlockRead();
        runtimeLock.write();
        realizeClass(cls);
        runtimeLock.unlockWrite();
        runtimeLock.read();
    }
    if (initialize  &&  !cls->isInitialized()) {
        runtimeLock.unlockRead();
        _class_initialize (_class_getNonMetaClass(cls, inst));
        runtimeLock.read();
    }

 retry:    
    runtimeLock.assertReading();

    💡// 防止動態添加方法,緩存會變化,再次查找緩存。imp = cache_getImp(cls, sel);
    💡// 若是找到imp方法地址, 直接調用done, 返回方法地址
    if (imp) goto done;

    ❗️// 查找方法列表, 傳入類對象和方法名
    {
        💡// 根據sel去類對象裏面查找方法
        Method meth = getMethodNoSuper_nolock(cls, sel);
        if (meth) {
            💡// 若是方法存在,則緩存方法,
            💡// 內部調用的就是 cache_fill。
            log_and_fill_cache(cls, meth->imp, sel, inst, cls);
            💡// 方法緩存以後, 取出函數地址imp並返回
            imp = meth->imp;
            goto done;
        }
    }

    ❗️// 若是類方法列表中沒有找到, 則去父類的緩存中或方法列表中查找方法
    {
        unsigned attempts = unreasonableClassCount();
        ❗️// 若是父類緩存列表及方法列表均找不到方法,則去父類的父類去查找。一層層進行遞歸查找,直到找到NSObject類
        for (Class curClass = cls->superclass;
             curClass != nil;
             curClass = curClass->superclass)
        {
            // Halt if there is a cycle in the superclass chain.
            if (--attempts == 0) {
                _objc_fatal("Memory corruption in class list.");
            }
            
             ❗️// 查找父類的cache_t緩存
            imp = cache_getImp(curClass, sel);
            if (imp) {
                if (imp != (IMP)_objc_msgForward_impcache) {
                    💡// 在父類中找到方法, 在本類中緩存方法, 注意這裏傳入的是cls, 將方法緩存在本類緩存列表中, 而非父類中
                    log_and_fill_cache(cls, imp, sel, inst, curClass);
                    // 執行done, 返回imp
                    goto done;
                }
                else {
                    // 跳出循環, 中止搜索
                    break;
                }
            }
            
            ❗️// 查找父類的方法列表
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
                💡// 一樣拿到方法, 在本類進行緩存
                log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
                imp = meth->imp;
                // 執行done, 返回imp
                goto done;
            }
        }
    }
    
     ❗️// ---------------- 消息發送階段完成,沒有找到方法實現,進入動態解析階段 ---------------------
     ❗️//首先檢查是否已經被標記爲動態方法解析,若是沒有才會進入動態方法解析
    if (resolver  &&  !triedResolver) {
        runtimeLock.unlockRead();
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.read();
       💡 //將triedResolver標記爲YES,下次就不會再進入動態方法解析
        triedResolver = YES;
        goto retry;
    }

     ❗️// ---------------- 動態解析階段完成,進入消息轉發階段 ---------------------
    imp = (IMP)_objc_msgForward_impcache;
    cache_fill(cls, sel, imp, inst);

 done:
    runtimeLock.unlockRead();
    💡// 返回方法地址
    return imp;
}
複製代碼

getMethodNoSuper_nolock方法

getMethodNoSuper_nolock方法就是一個簡單的一個遍歷方法列表

static method_t *
getMethodNoSuper_nolock(Class cls, SEL sel)
{
    runtimeLock.assertLocked();

    assert(cls->isRealized());
    // fixme nil cls? 
    // fixme nil 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;
}
複製代碼

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 {
        // Linear search of unsorted method list
         💡//若是方法列表沒有排序好就遍歷查找
        for (auto& meth : *mlist) {
            if (meth.name == sel) return &meth;
        }
    }

#if DEBUG
    // sanity-check negative results
    if (mlist->isFixedUp()) {
        for (auto& meth : *mlist) {
            if (meth.name == sel) {
                _objc_fatal("linear search worked when binary search did not");
            }
        }
    }
#endif

    return nil;
}
複製代碼

findMethodInSortedMethodList二分查找方法具體實現

static method_t *findMethodInSortedMethodList(SEL key, const method_list_t *list)
{
    assert(list);

    const method_t * const first = &list->first;
    const method_t *base = first;
    const method_t *probe;
    uintptr_t keyValue = (uintptr_t)key;
    uint32_t count;
     ❗️// >>1 表示將變量n的各個二進制位順序右移1位,最高位補二進制0。
     ❗️// count >>= 1 若是count爲偶數則值變爲(count / 2)。若是count爲奇數則值變爲(count-1) / 2 
    for (count = list->count; count != 0; count >>= 1) {
        ❗️// probe 指向數組中間的值
        probe = base + (count >> 1);
        
         💡// 取出中間method_t的name,也就是SEL
        uintptr_t probeValue = (uintptr_t)probe->name;
        
        if (keyValue == probeValue) {
            // `probe` is a match.
            // Rewind looking for the *first* occurrence of this value.
            // This is required for correct category overrides.
            💡// 繼續向前二分查詢
            while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
                probe--;
            }
            // 取出 probe
            return (method_t *)probe;
        }
        💡// 若是keyValue > probeValue 則折半向後查詢
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}
複製代碼

_objc_msgForward_impcache簡述

在經過消息查找和動態解析失敗後,最後會走到_objc_msgForward_impcache方法,調用__objc_msgForward,最終調用__objc_forward_handler

STATIC_ENTRY __objc_msgForward_impcache

	// No stret specialization.
	b	__objc_msgForward

	END_ENTRY __objc_msgForward_impcache

	
	ENTRY __objc_msgForward

	adrp	x17, __objc_forward_handler@PAGE
	ldr	p17, [x17, __objc_forward_handler@PAGEOFF]
	TailCallFunctionPointer x17
	
	END_ENTRY __objc_msgForward
複製代碼

搜索__objc_forward_handler發現這是一個C++方法,最終實現以下,這就是最終找不到方法時,LLDB打印輸出的內容

objc_defaultForwardHandler(id self, SEL sel)
{
    _objc_fatal("%c[%s %s]: unrecognized selector sent to instance %p "
                "(no message forward handler is installed)", 
                class_isMetaClass(object_getClass(self)) ? '+' : '-', 
                object_getClassName(self), sel_getName(sel), self);
}
複製代碼

流程小結

1.首先對須要的變量進行初始化操做和加鎖操做

2.其次若是沒有進行初始化,則初始化類,父類、元類等,保證方法的查找

3.在receive的方法列表中進行二分查找,若是找到,則返回,並寫入緩存

4.若是沒找到,則一層層遞歸receive的父類的緩存和方法列表,直到NSObject,找到即返回,並寫入receive的緩存

5.若是沒找到,則進入動態方法解析流程,進行動態方法的解析,有則執行

6.若是沒有動態方法解析,則進入消息轉發流程

7.若是上述都沒有實現和處理,則最終沒法找到方法,會崩潰

總結

OC的消息機制能夠分爲一下三個階段:

  • 消息發送階段:從類及父類的方法緩存列表及方法列表查找方法;
  • 動態解析階段:若是消息發送階段沒有找到方法,則會進入動態解析階段,負責動態的添加方法實現;
  • 消息轉發階段:若是也沒有實現動態解析方法,則會進行消息轉發階段,將消息轉發給能夠處理消息的接受者來處理;

經過本章,咱們基本瞭解了方法的本質和方法的查找流程,可是對於消息動態解析和消息轉發的流程並無深刻了解,下一章節會着重講解這兩個部分

相關文章
相關標籤/搜索