iOS objc_msgsend流程分析(二)

概述

接著上一篇文章,我們繼續(xù)探索消息發(fā)送的后續(xù)流程

消息轉(zhuǎn)發(fā)(報(bào)錯(cuò))

通過(guò)上一篇文章發(fā)現(xiàn),都找不到的時(shí)候會(huì)返回一個(gè)forward_imp,
通過(guò)源碼發(fā)現(xiàn)找到_objc_msgForward_impcache,

 const IMP forward_imp = (IMP)_objc_msgForward_impcache;

源碼搜索objc_msgForward_impcache

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

然后會(huì)跳轉(zhuǎn)objc_msgForward

知識(shí)補(bǔ)充:adrp 通過(guò)基地址 + 偏移 獲得一個(gè)字符串(全局變量)
繼續(xù)查找objc_forward_handler

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);
}
void *_objc_forward_handler = (void*)objc_defaultForwardHandler;

這里我們看到了一個(gè)iOS開(kāi)發(fā)人員都熟知的報(bào)錯(cuò)提示 unrecognized selector sent to instance,對(duì)就是它

方法動(dòng)態(tài)解析

當(dāng)然如果imp沒(méi)有找到實(shí)現(xiàn),系統(tǒng)還不會(huì)直接立馬報(bào)錯(cuò),還會(huì)尋找解析的機(jī)會(huì),繼續(xù)閱讀lookimporforward還會(huì)發(fā)現(xiàn)如下代碼:

    // No implementation found. Try method resolver once.

    if (slowpath(behavior & LOOKUP_RESOLVER)) {
        behavior ^= LOOKUP_RESOLVER;
        return resolveMethod_locked(inst, sel, cls, behavior);
    }

注釋?zhuān)喝绻麤](méi)有實(shí)現(xiàn),會(huì)嘗試一次方法解析
繼續(xù)查看resolveMethod_locked

static NEVER_INLINE IMP
resolveMethod_locked(id inst, SEL sel, Class cls, int behavior){
...
if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]
        resolveInstanceMethod(inst, sel, cls);
    } 
    else {
        // try [nonMetaClass resolveClassMethod:sel]
        // and [cls resolveInstanceMethod:sel]
        resolveClassMethod(inst, sel, cls);
        if (!lookUpImpOrNilTryCache(inst, sel, cls)) {
            resolveInstanceMethod(inst, sel, cls);
        }
    }
...
}
  • 如果是實(shí)例方法會(huì)先調(diào)用resolveInstanceMethod,看實(shí)例方法,有沒(méi)有實(shí)現(xiàn)
  • 進(jìn)入resolveClassMethod方法,發(fā)現(xiàn)其與resolveInstanceMethod實(shí)現(xiàn)十分相似;不同地方在于resolveInstanceMethod里邊需要類(lèi)中實(shí)現(xiàn)一個(gè)類(lèi)方法resolveInstanceMethod,而resolveClassMethod是需要在元類(lèi)里實(shí)現(xiàn)一個(gè)對(duì)象方法resolveClassMethod,因?yàn)轭?lèi)方法在元類(lèi)中都是以對(duì)象方法的形式存在的;那么如何在元類(lèi)中實(shí)現(xiàn)一個(gè)對(duì)象方法呢?只需要在當(dāng)前類(lèi)中實(shí)現(xiàn)類(lèi)方法resolveClassMethod即可:
實(shí)例方法動(dòng)態(tài)實(shí)現(xiàn):
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
    if (sel == @selector(teacherSay)) {
       // return YES;
        IMP r_teacherSay = class_getMethodImplementation(self, @selector(r_teacherSay));
        Method method = class_getInstanceMethod(self, @selector(r_teacherSay));
        const char *type = method_getTypeEncoding(method);
        
        return  class_addMethod(self, sel, r_teacherSay, type);
    }
    return NO;
}
- (void)r_teacherSay
{
    NSLog(@"%s",__func__);
}
類(lèi)方法動(dòng)態(tài)解析實(shí)現(xiàn)
+ (BOOL)resolveClassMethod:(SEL)sel
{
    if (sel == @selector(sayNB)) {
        IMP r_teacherSay = class_getMethodImplementation(objc_getMetaClass("QHTeacher"), @selector(r_sayNB));
        Method method = class_getInstanceMethod(self, @selector(r_sayNB));
        const char *type = method_getTypeEncoding(method);
        
        return  class_addMethod(objc_getMetaClass("QHTeacher"), sel, r_teacherSay, type);
    }
    
    return NO;
}
+ (void)r_sayNB
{
    NSLog(@"%s",__func__);
}

通過(guò)上面的源碼我們發(fā)現(xiàn),調(diào)用類(lèi)方法的resolveClassMethod后有調(diào)用了resolveInstanceMethod,通過(guò)這個(gè)源碼和isa分析,我們可以得出一個(gè)結(jié)論,無(wú)論是調(diào)用類(lèi)方法還是實(shí)例方法,最終都會(huì)調(diào)用resolveInstanceMethod方法。這樣我們就可以通過(guò)實(shí)現(xiàn)一個(gè)NSObject的分類(lèi),然后通過(guò)實(shí)現(xiàn)+ (BOOL)resolveInstanceMethod:(SEL)sel,來(lái)處理所有的異常。而不用再每個(gè)類(lèi)里面都去添加。

instrumentObjcMessageSends引出方法

lookUpImpOrForward這個(gè)方法里面找到imp后會(huì)調(diào)用log_and_fill_cache這個(gè)方法,改方法會(huì)通過(guò)objcMsgLogEnabled來(lái)控制是否打印msg日志,全局搜索objcMsgLogEnabled,這個(gè)參數(shù)會(huì)由instrumentObjcMessageSends這個(gè)外部函數(shù)來(lái)控制:

extern void instrumentObjcMessageSends(BOOL flag);
int main(int argc, const char * argv[]) {
    @autoreleasepool {

        QHPerson *person = [QHPerson alloc];
        instrumentObjcMessageSends(YES);
        [person sayHello];
        instrumentObjcMessageSends(NO);


        NSLog(@"Hello, World!");
    }
    return 0;
}
```objectivec
在看看打印的方法```logMessageSend```,
```objectivec
if (objcMsgLogFD == (-1))
    {
        snprintf (buf, sizeof(buf), "/tmp/msgSends-%d", (int) getpid ());
        objcMsgLogFD = secure_open (buf, O_WRONLY | O_CREAT, geteuid());
        if (objcMsgLogFD < 0) {
            // no log file - disable logging
            objcMsgLogEnabled = false;
            objcMsgLogFD = -1;
            return true;
        }
    }

發(fā)現(xiàn)日志會(huì)保存到/tmp/目錄下,如下圖:

日志.png

消息快速轉(zhuǎn)發(fā)forwardingTargetForSelector

通過(guò)上面的日志發(fā)現(xiàn)調(diào)用了forwardingTargetForSelector,發(fā)現(xiàn)在源碼里面也沒(méi)有找到該方法,那么查看一下蘋(píng)果文檔


轉(zhuǎn)發(fā).png

翻譯:如果一個(gè)對(duì)象實(shí)現(xiàn)(或繼承)這個(gè)方法,并返回一個(gè)非nil(非self)結(jié)果,那么返回的對(duì)象將被用作新的接收方對(duì)象,消息調(diào)度將恢復(fù)到這個(gè)新對(duì)象(顯然,如果您從這個(gè)方法返回self,代碼將落入一個(gè)無(wú)限循環(huán)。)
代碼展示:

QHPerson *p = [QHPerson alloc];
[p sayHello];

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    return [QHTeacher alloc];
}

將p對(duì)象里面沒(méi)有實(shí)現(xiàn)的方法轉(zhuǎn)發(fā)給QHTeacher對(duì)象

消息慢速轉(zhuǎn)發(fā)forwardingTargetForSelector

慢速轉(zhuǎn)法.png

翻譯:返回一個(gè)NSMethodSignature對(duì)象,該對(duì)象包含由給定選擇器標(biāo)識(shí)的方法的描述
該方法會(huì)關(guān)聯(lián)一個(gè)forwardInvocation方法

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    if (aSelector == @selector(sayHello)) {
        
        return  [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }
    return  [super methodSignatureForSelector:aSelector];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    
    NSLog(@"%@-%@",anInvocation.target,NSStringFromSelector(anInvocation.selector));
    [anInvocation invokeWithTarget:[QHStutent alloc]];
}

forwardInvocation也可以不用處理,程序也不會(huì)出現(xiàn)崩潰,但是也耗費(fèi)程序性能,也不方便快速定位問(wèn)題

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容