iOS-Runtime

Runtime源码剖析---图解消息发送机制

2019-08-24  本文已影响0人  祀梦_

Runtime源码剖析---图解消息发送机制

源码面前,了无秘密

前言

预备知识

选择子SEL

///Person.m
#import "Person.h"
@implementation Person
- (void)eat {
    NSLog(@"Person EAT");
}

- (void)eat:(NSString *)str {
    NSLog(@"Person EATSTR");
}

- (void)dayin {
    NSLog(@"dayin");
    SEL sell1 = @selector(eat:);
    NSLog(@"sell1:%p", sell1);
    SEL sell2 = @selector(eat);
    NSLog(@"sell2:%p", sell2);
}
@end

///main.m
#import <Foundation/Foundation.h>
#include "Student.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *newPerson = [[Person alloc] init];
        [newPerson dayin];
    }
    return 0;
}

//结果
//dayin
//sell1:0x100000f63
//sell2:0x100000f68

objc_msgSend()的执行流程

  1. 消息发送阶段:负责从类及父类的缓存列表及方法列表查找方法。
  2. 动态解析阶段:如果消息发送阶段没有找到方法,则会进入动态解析阶段,负责动态的添加方法实现。
  3. 消息转发阶段:如果也没有实现动态解析方法,则会进行消息转发阶段,将消息转发给可以处理消息的接受者来处理。
objc_msgSend流程

消息发送阶段

    //从这里开始
    ENTRY _objc_msgSend
    UNWIND _objc_msgSend, NoFrame
    //p0寄存器,消息接收者
⚠️cmp   p0, #0          // nil check and tagged pointer check
#if SUPPORT_TAGGED_POINTERS
⚠️b.le  LNilOrTagged    //b是跳转,le是小于等于,也就是p0小于等于0时,跳转到LNilOrTagged
#else
    b.eq    LReturnZero
#endif
    ldr p13, [x0]       // p13 = isa
    GetClassFromIsa_p16 p13     // p16 = class
LGetIsaDone:
⚠️CacheLookup NORMAL        //缓存查找

#if SUPPORT_TAGGED_POINTERS

LNilOrTagged:-------------------如果接收者为nil,跳转至此---------------------------

⚠️b.eq  LReturnZero     //如果消息接收者为空,直接退出这个函数

    // tagged
    adrp    x10, _objc_debug_taggedpointer_classes@PAGE
    add x10, x10, _objc_debug_taggedpointer_classes@PAGEOFF
    ubfx    x11, x0, #60, #4
    ldr x16, [x10, x11, LSL #3]
    adrp    x10, _OBJC_CLASS_$___NSUnrecognizedTaggedPointer@PAGE
    add x10, x10, _OBJC_CLASS_$___NSUnrecognizedTaggedPointer@PAGEOFF
    cmp x10, x16
    b.ne    LGetIsaDone

    // ext tagged
    adrp    x10, _objc_debug_taggedpointer_ext_classes@PAGE
    add x10, x10, _objc_debug_taggedpointer_ext_classes@PAGEOFF
    ubfx    x11, x0, #52, #8
    ldr x16, [x10, x11, LSL #3]
    b   LGetIsaDone
// SUPPORT_TAGGED_POINTERS
#endif

LReturnZero:
    // x0 is already zero
    mov x1, #0
    movi    d0, #0
    movi    d1, #0
    movi    d2, #0
    movi    d3, #0
    ret

    END_ENTRY _objc_msgSend
    //结束
  1. 首先从cmp p0, #0开始,这里p0是寄存器,里面是消息接收者。b.le LNilOrTaggedb是跳转的意思,le是如果p0小于等于0,总体意思是若p0小于等于0,则跳转到LNilOrTagged(我在上述代码中已标出),执行b.eq LReturnZero就是直接退出程序。
  2. 如果消息接收者不为nil,汇编代码继续执行,到CacheLookup NORMAL,通过字面意思可以知道这是从缓存中查找方法的实现。我们在本文件中搜索一下:
//开始
.macro CacheLookup  //这里是一个宏定义
    // p1 = SEL, p16 = isa
    ldp p10, p11, [x16, #CACHE] // p10 = buckets, p11 = occupied|mask
#if !__LP64__
    and w11, w11, 0xffff    // p11 = mask
#endif
    and w12, w1, w11        // x12 = _cmd & mask
    add p12, p10, p12, LSL #(1+PTRSHIFT)
                     // p12 = buckets + ((_cmd & mask) << (1+PTRSHIFT))

    ldp p17, p9, [x12]      // {imp, sel} = *bucket
1:  cmp p9, p1          // if (bucket->sel != _cmd)
    b.ne    2f          //     scan more
    CacheHit $0         // call or return imp
    
2:  // not hit: p12 = not-hit bucket
    CheckMiss $0            // miss if bucket->sel == 0
    cmp p12, p10        // wrap if bucket == buckets
    b.eq    3f
    ldp p17, p9, [x12, #-BUCKET_SIZE]!  // {imp, sel} = *--bucket
    b   1b          // loop

3:  // wrap: p12 = first bucket, w11 = mask
    add p12, p12, w11, UXTW #(1+PTRSHIFT)
                                // p12 = buckets + (mask << 1+PTRSHIFT)

    // Clone scanning loop to miss instead of hang when cache is corrupt.
    // The slow path may detect any corruption and halt later.

    ldp p17, p9, [x12]      // {imp, sel} = *bucket
1:  cmp p9, p1          // if (bucket->sel != _cmd)
    b.ne    2f          //     scan more
    
⚠️CacheHit $0-------------//缓存命中,在缓存中找到了对应的方法及其实现-----------------
    
2:  // not hit: p12 = not-hit bucket
⚠️CheckMiss $0------------//在缓存中没有找到对应的方法-------------------------------
    cmp p12, p10        // wrap if bucket == buckets
    b.eq    3f
    ldp p17, p9, [x12, #-BUCKET_SIZE]!  // {imp, sel} = *--bucket
    b   1b          // loop

3:  // double wrap
    JumpMiss $0
    
.endmacro
//结束
  1. 在缓存中找到了方法那就直接调用,下面主要看一下从缓存中没有找到方法怎么办。没有找到方法则会执行CheckMiss我们搜索一下它的汇编
//开始
.macro CheckMiss//这是一个宏定义
    // miss if bucket->sel == 0
.if $0 == GETIMP
    cbz p9, LGetImpMiss
.elseif $0 == NORMAL
⚠️cbz   p9, __objc_msgSend_uncached//放缓存中没有找到方法时,主要执行这个方法
.elseif $0 == LOOKUP
    cbz p9, __objc_msgLookup_uncached
.else
.abort oops
.endif
.endmacro

.macro JumpMiss
.if $0 == GETIMP
    b   LGetImpMiss
.elseif $0 == NORMAL
    b   __objc_msgSend_uncached
.elseif $0 == LOOKUP
    b   __objc_msgLookup_uncached
.else
.abort oops
.endif
.endmacro
//结束
STATIC_ENTRY __objc_msgSend_uncached
    UNWIND __objc_msgSend_uncached, FrameWithNoSaves

    // THIS IS NOT A CALLABLE C FUNCTION
    // Out-of-band p16 is the class to search
    
⚠️MethodTableLookup--------//去方法列表中去查找方法---------------
    TailCallFunctionPointer x17
    
    END_ENTRY __objc_msgSend_uncached
//开始
.macro MethodTableLookup
    
    // push frame
    SignLR
    stp fp, lr, [sp, #-16]!
    mov fp, sp

    // save parameter registers: x0..x8, q0..q7
    sub sp, sp, #(10*8 + 8*16)
    stp q0, q1, [sp, #(0*16)]
    stp q2, q3, [sp, #(2*16)]
    stp q4, q5, [sp, #(4*16)]
    stp q6, q7, [sp, #(6*16)]
    stp x0, x1, [sp, #(8*16+0*8)]
    stp x2, x3, [sp, #(8*16+2*8)]
    stp x4, x5, [sp, #(8*16+4*8)]
    stp x6, x7, [sp, #(8*16+6*8)]
    str x8,     [sp, #(8*16+8*8)]

    // receiver and selector already in x0 and x1
    mov x2, x16
⚠️bl    __class_lookupMethodAndLoadCache3//通过这个方法来查找缓存和方法列表

    // IMP in x0
    mov x17, x0
    
    // restore registers and return
    ldp q0, q1, [sp, #(0*16)]
    ldp q2, q3, [sp, #(2*16)]
    ldp q4, q5, [sp, #(4*16)]
    ldp q6, q7, [sp, #(6*16)]
    ldp x0, x1, [sp, #(8*16+0*8)]
    ldp x2, x3, [sp, #(8*16+2*8)]
    ldp x4, x5, [sp, #(8*16+4*8)]
    ldp x6, x7, [sp, #(8*16+6*8)]
    ldr x8,     [sp, #(8*16+8*8)]

    mov sp, fp
    ldp fp, lr, [sp], #16
    AuthenticateLR

.endmacro
//结束
  1. 我们在objc-runtime-new.mm这个文件中找到了_class_lookupMethodAndLoadCache3的实现:
IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
    return lookUpImpOrForward(cls, sel, obj, 
                              YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}
IMP lookUpImpOrForward(Class cls, SEL sel, id inst, 
                       bool initialize, bool cache, bool resolver)
{
    IMP imp = nil;
    bool triedResolver = NO;

    runtimeLock.assertUnlocked();

    // Optimistic cache lookup
⚠️  if (cache) { //由于我们在此之前进行过一次缓存查找,所以不会进入这里
        imp = cache_getImp(cls, sel);
        if (imp) return imp;
    }
  
    runtimeLock.lock();
    checkIsKnownClass(cls);

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

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

 retry:    
    runtimeLock.assertLocked();
  
//再查找一次缓存中有没有,因为担心代码在运行中动态添加了方法
⚠️  imp = cache_getImp(cls, sel);
    if (imp) goto done;
    
    //如果是类对象
    // Try this class's method lists.
⚠️  //这一个代码块从类的方法列表中去查找
---------------------------------------------------------------------------------
-   {                                                                                                                               
-  ⚠️⚠️⚠️Method meth = getMethodNoSuper_nolock(cls, sel);   //查找方法   
-         if (meth) {                                                                                                   
-                       //把方法缓存到类对象的缓存列表中,并返回方法的IMP                          
-             log_and_fill_cache(cls, meth->imp, sel, inst, cls);           
-           imp = meth->imp;                                                                                
-           goto done;                                                                                  
-         }                                                           
-       }                                                             
---------------------------------------------------------------------------------
  
    // Try superclass caches and method lists.
⚠️  //这一个代码块沿着继承链,从类对象的父类中去查找
---------------------------------------------------------------------------------
-   {
-       unsigned attempts = unreasonableClassCount();
-       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.");
-           }
-           // Superclass cache.
-                   //再查找一次缓存中有没有,因为担心代码在运行中动态添加了方法
-         ⚠️imp = cache_getImp(curClass, sel);
-           if (imp) {
-               if (imp != (IMP)_objc_msgForward_impcache) {
-                   // Found the method in a superclass. Cache it in this class.
-                   log_and_fill_cache(cls, imp, sel, inst, curClass);
-                   goto done;
-               }
-               else {
-                   break;
-               }
-           }
-           // Superclass method list.
-                       //查找父类的方法列表
-         ⚠️Method meth = getMethodNoSuper_nolock(curClass, sel);
-           if (meth) {
-               log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
-               imp = meth->imp;
-               goto done;
-           }
-       }
-   }
---------------------------------------------------------------------------------
  
  ...........................
  //省略部分涉及到动态方法解析和消息转发
  //我在下面拿出来仔细讲解
  
}   
  1. 我们具体看一下是怎么从类对象中查找方法的,这个主要是在getMethodNoSuper_nolock()这个方法,拥有⚠️⚠️⚠️这一行代码。
static method_t *
getMethodNoSuper_nolock(Class cls, SEL sel)
{
    runtimeLock.assertLocked();

    assert(cls->isRealized());
    // fixme nil cls? 
    // fixme nil sel?

    //cls->data()->methods就是类对象的方法列表
    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;
}

动态解析阶段

动态解析流程

    // No implementation found. Try method resolver once.
        //如果上述在类对象和父类对象中没有查到方法
        //我们进入动态方法解析
     if (resolver  &&  !triedResolver) {//triedResolver用来判断是否曾经进行过动态方法解析,如果没有那就进入动态方法解析,如果进行过,就跳过
       runtimeLock.unlock();
    ⚠️ _class_resolveMethod(cls, sel, inst);//动态方法解析函数
       runtimeLock.lock();
       // Don't cache the result; we don't hold the lock so it may have 
       // changed already. Re-do the search from scratch instead.
     ⚠️triedResolver = YES;//进行过动态方法解析就把这个标志位设置为YES
     ⚠️goto retry;//retry是前面消息发送的整个过程,也就是说进行了方法解析后还要回到前面从类对象的缓存和方法列表中查找。如果动态方法解析添加了方法实现,那么自然能找到,如果没有,那么还是找不到方法实现,这个时候也不会再进入动态方法解析了,而是直接进入下一步,消息转发
   }
void _class_resolveMethod(Class cls, SEL sel, id inst)
{
    //判断是不是元类对象
    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]
        //调用类的resolveInstanceMethod方法
       ⚠️ _class_resolveInstanceMethod(cls, sel, inst);
    } 
    //不是类对象肯定就是元类对象
    else {
        // try [nonMetaClass resolveClassMethod:sel]
        // and [cls resolveInstanceMethod:sel]
        //调用元类的resolveClassMethod方法
        ⚠️_class_resolveClassMethod(cls, sel, inst);
        if (!lookUpImpOrNil(cls, sel, inst, 
                            NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
        {
            _class_resolveInstanceMethod(cls, sel, inst);
        }
    }
}
  • 其实实现很简单,就是判断是类对象还是元类对象,如果是类对象则说明调用的实例方法,则调用类的resolveInstanceMethod:方法,

  • 如果是元类对象,则说明是调用的类方法,则调用类的resolveClassMethod:方法。

class_addMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp, 
                const char * _Nullable types) 
  
@cls : 给哪个类对象添加方法
@name : SEL类型的,给哪个方法名添加方法实现
@imp : IMP类型的,要把哪个方法实现添加给给定的方法名
@types :在讲method_t的结构时讲过这个,就是表示返回值和参数类型的字符串,比如"v16@0:8"
Method _Nullable
class_getInstanceMethod(Class _Nullable cls, SEL _Nonnull name)
IMP _Nonnull
method_getImplementation(Method _Nonnull m) 

动态解析例子

//创建一个Person对象,并在.h文件中声明test方法,但在.m文件中并未实现

#import "ViewController.h"
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    Person *person = [[Person alloc] init];
    [person test];
}

@end

程序崩溃很容易理解,因为在第一步查找方法中,在自己的类对象以及父类的类对象中都没有找到这个方法,

所以转向动态方法解析,动态方法解析我们什么也没做,所以会转向消息转发,消息转发我们也什么都没做,所以最后产生崩溃。

接下来我们实现一下动态方法解析。

//我现在Person.m文件中实现了test2方法:
//通过class_addMethod的方法动态添加方法
+ (BOOL)resolveInstanceMethod:(SEL)sel{
    if (sel == @selector(test)) {
        Method method = class_getInstanceMethod(self, @selector(test2));
        class_addMethod(self, sel, method_getImplementation(method), "v16@0:8");
        return YES;
    }
    
    return [super resolveInstanceMethod:sel];
}

- (void)test2{
    NSLog(@"测试动态方法解析");
}

消息转发阶段

消息转发流程

     //如果上述在类对象和父类对象中没有查到方法
         //我们进入动态方法解析
    if (resolver  &&  !triedResolver) {//triedResolver用来判断是否曾经进行过动态方法解析,如果没有那就进入动态方法解析,如果进行过,就跳过
        runtimeLock.unlock();
    ⚠️ _class_resolveMethod(cls, sel, inst);//动态方法解析函数
        runtimeLock.lock();
        // Don't cache the result; we don't hold the lock so it may have 
        // changed already. Re-do the search from scratch instead.
      ⚠️triedResolver = YES;//进行过动态方法解析就把这个标志位设置为YES
      ⚠️goto retry;
      //retry是前面消息发送的整个过程,也就是说进行了方法解析后还要回到前面从类对象的缓存和方法列表中查找。如果动态方法解析添加了方法实现,那么自然能找到,如果没有,那么还是找不到方法实现,这个时候也不会再进入动态方法解析了,而是直接进入下一步,消息转发
     }
  

  ⚠️ //如果动态方法解析失败,进入消息转发

  ⚠️imp = (IMP)_objc_msgForward_impcache;//这一步进入消息转发
    cache_fill(cls, sel, imp, inst);
  
   //如果消息转发失败,程序崩溃
 done:
  ⚠️runtimeLock.unlock();
    //开始
    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
    //结束
int __forwarding__(void *frameStackPointer, int isStret) { 
    id receiver = *(id *)frameStackPointer; 
    SEL sel = *(SEL *)(frameStackPointer + 8); 
    const char *selName = sel_getName(sel); 
    Class receiverClass = object_getClass(receiver); 

    // 调用 forwardingTargetForSelector: 
    if (class_respondsToSelector(receiverClass,@selector(forwardingTargetForSelector:))) { 
      //首先调用消息接收者的forwardingTargetForSelector方法来获取消息转发对象
      ⚠️id forwardingTarget = [receiver forwardingTargetForSelector:sel]; 
        if (forwardingTarget && forwarding != receiver) { 
            if (isStret == 1) { 
                    int ret; 
                    objc_msgSend_stret(&ret,forwardingTarget, sel, ...); 
                    return ret; 
            } 
            //然后直接给这个消息转发对象发送消息
            return objc_msgSend(forwardingTarget, sel, ...); 
       } 
  } 

// 僵尸对象 
const char *className = class_getName(receiverClass); 
const char *zombiePrefix = "_NSZombie_"; 
size_t prefixLen = strlen(zombiePrefix); // 0xa 
if (strncmp(className, zombiePrefix, prefixLen) == 0) { 
    CFLog(kCFLogLevelError, 
            @"*** -[%s %s]: message sent to deallocated instance %p", 
            className + prefixLen, 
            selName, 
            receiver); 
    <breakpoint-interrupt> 
} 

//如果forwardingTargetForSelector没有实现或者返回值为0都会继续往下执行
  
// 调用 methodSignatureForSelector 获取方法签名后再调用forwardInvocation 
⚠️if (class_respondsToSelector(receiverClass, @selector(methodSignatureForSelector:))) { 
  //如果methodSignatureForSelector返回值不为nil
  ⚠️NSMethodSignature *methodSignature = [receiver methodSignatureForSelector:sel]; 
    if (methodSignature) { 
       BOOL signatureIsStret = [methodSignature _frameDescriptor]->returnArgInfo.flags.isStruct; 
       if (signatureIsStret != isStret) { 
         CFLog(kCFLogLevelWarning , 
                    @"*** NSForwarding: warning: method signature and compiler disagree on struct-return-edness of '%s'. Signature thinks it does%s return a struct, and compiler thinks it does%s.", 
            selName, 
            signatureIsStret ? "" : not, 
            isStret ? "" : not); 
} 

   //并且实现了forwardInvocation方法
⚠️if (class_respondsToSelector(receiverClass, @selector(forwardInvocation:))) { 
    NSInvocation *invocation = [NSInvocation _invocationWithMethodSignature:methodSignature frame:frameStackPointer]; 

    [receiver forwardInvocation:invocation]; 

    void *returnValue = NULL;
    [invocation getReturnValue:&value]; 
    return returnValue; 
    } 
    else { 
        CFLog(kCFLogLevelWarning , 
                @"*** NSForwarding: warning: object %p of class '%s' does not implement forwardInvocation: -- dropping message",
             receiver, 
             className); 
        return 0; 
        } 
    } 
} 

SEL *registeredSel = sel_getUid(selName); 

// selector 是否已经在 Runtime 注册过 
if (sel != registeredSel) { 
    CFLog(kCFLogLevelWarning , 
            @"*** NSForwarding: warning: selector (%p) for message '%s' does not match selector known to Objective C runtime (%p)-- abort", 
            sel, 
            selName, 
            registeredSel); 
}
  
⚠️//如果上面两个方法都未实现,那么就会崩溃
// doesNotRecognizeSelector 
else if (class_respondsToSelector(receiverClass,@selector(doesNotRecognizeSelector:))) { 
    [receiver doesNotRecognizeSelector:sel]; 
}  else { 
    CFLog(kCFLogLevelWarning , 
            @"*** NSForwarding: warning: object %p of class '%s' does not implement doesNotRecognizeSelector: -- abort", 
            receiver, 
            className); 
} 

// The point of no return. 
kill(getpid(), 9);
}

消息转发例子

//Person.h中有- (void)testAge:(int)age;但是在Person.m中并没有实现
[person testAge:10];
//现在我们在第二阶段动态方法解析阶段没有做任何处理,
//在- (id)forwardingTargetForSelector:(SEL)aSelector这个函数中也不做处理。
//那么代码就会执行到- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector这个函数,
//在这个函数中我们要返回一个方法签名:

//方法签名:返回值类型,参数类型
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{
    if(aSelector == @selector(testAge:)){
        return [NSMethodSignature signatureWithObjCTypes:"v20@0:8i16"];
    }
    return [super methodSignatureForSelector:aSelector];
}
上一篇下一篇

猜你喜欢

热点阅读