iOS底层(七)-objc_msgSend分析(二)

624 阅读11分钟

前言

上文得知OC方法的本质就是通过objc_msgSend进行发送消息 , 并且有一个消息查找机制来进行方法执行. 那么这里就探究一下消息是如何进行方法查找的.

一、探索方法查找的入口(快速查找流程)

对一个类进行初始化, 断点进行调试.

通过XCode的 Debug -> debug Workflow -> Always show Disassembly 进入汇编. 断点到 objc_msgSend , 此处就是方法调用的本质.

通过按住control进入 objc_msgSend, 发现 _objc_msgSend_uncached. 标志着没有找到缓存, 断点 _objc_msgSend_uncached

同样操作进入 _objc_msgSend_uncached, 看到确切的一句:

在 objc-runtime-new.mm 类的 4845 行的 _class_lookupMethodAndLoadCache3 方法. 此时通过汇编来进入 _class_lookupMethodAndLoadCache3 方法也称作消息查找流程的快速查找流程.

二、消息查找流程(慢速查找流程)

首先新建如下几个类

@interface NSObject (CA)
- (void)sayMaster;
+ (void)sayEasy;
@end

@interface People : NSObject
- (void)sayNB;
+ (void)sayHappay;
@end

@interface Student : People
- (void)sayHello;
+ (void)sayObjc;
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
#pragma clang diagnostic push // 让编译器忽略错误
#pragma clang diagnostic ignored "-Wundeclared-selector"

        Student *std = [[Student alloc] init];
        [std sayHello];
        
#pragma clang diagnostic pop
    }
    return 0;
}

通过全局搜索找到 _class_lookupMethodAndLoadCache3 方法, 在方法执行后加上断点进行调试:

因为在之前 _objc_msgSend_uncached 意味着没用命中缓存, 那么此处就应该不需要重新查找缓存, 所以cache参数应该是NO.

跟进 lookUpImpOrForward:

IMP lookUpImpOrForward(Class cls, SEL sel, id inst, 
                       bool initialize, bool cache, bool resolver)
{
    ...//省略
 retry:    
    runtimeLock.assertLocked();

    // Try this class's cache.

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

    // Try this class's method lists.
    {
        Method meth = getMethodNoSuper_nolock(cls, sel);
        if (meth) {
            log_and_fill_cache(cls, meth->imp, sel, inst, cls);
            imp = meth->imp;
            goto done;
        }
    }
    ...//省略
}

从 retry: 标签开始可以看到, 首先并没有从父类中查找, 而是从自己类的方法列表里去查找: 跟进 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;
}


/***********************************************************************
* getMethodNoSuper_nolock
* fixme
* Locking: runtimeLock must be read- or write-locked by the caller
**********************************************************************/
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;
}


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;
    
    for (count = list->count; count != 0; count >>= 1) {
        probe = base + (count >> 1);
        
        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--;
            }
            return (method_t *)probe;
        }
        
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}

可以看到是直接去当前类的 rw里面去查找(二分法)方法, 来找到所需要的方法.

如果找到了对应的方法, 那么就会进入 log_and_fill_cache , 在cache_t 中来对当前调用的方法进行一次方法缓存填充, 方便下次调用方法.然后直接跳往done返回imp

static void cache_fill_nolock(Class cls, SEL sel, IMP imp, id receiver)
{
    cacheUpdateLock.assertLocked();

    // Never cache before +initialize is done
    if (!cls->isInitialized()) return;

    // Make sure the entry wasn't added to the cache by some other thread 
    // before we grabbed the cacheUpdateLock.
    if (cache_getImp(cls, sel)) return;

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

    // Use the cache as-is if it is less than 3/4 full
    mask_t newOccupied = cache->occupied() + 1;
    mask_t capacity = cache->capacity();
    if (cache->isConstantEmptyCache()) {
        // Cache is read-only. Replace it.
        cache->reallocate(capacity, capacity ?: INIT_CACHE_SIZE);
    }
    else if (newOccupied <= capacity / 4 * 3) {
        // Cache is less than 3/4 full. Use it as-is.
    }
    else {
        // Cache is too full. Expand it.
        cache->expand();
    }

    // Scan for the first unused slot and insert there.
    // There is guaranteed to be an empty slot because the 
    // minimum size is 4 and we resized at 3/4 full.
    bucket_t *bucket = cache->find(key, receiver);
    if (bucket->key() == 0) cache->incrementOccupied();
    bucket->set(key, imp);
}

如果从自己类的方法列表里面找不到方法,那么它就会去从自己的父类中进行查找:

    // 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 {
                    // Found a forward:: entry in a superclass.
                    // Stop searching, but don't cache yet; call method 
                    // resolver for this class first.
                    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;
            }
        }
    }

可以看到首先并没有直接去父类的方法列表中去按照一系列的二分查找来进行方法查找. 它先是去父类的方法缓存中去进行一次缓存查找. 如果命中缓存, 那么就会对自身进行一次缓存填充. 如果未命中缓存, 则会依照自身的方法查找的样式去父类的方法列表里面重新查找方法.

假如在本类以及父类都查找不到对应的方法:

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]

进入 __objc_msgForward_impcache 进入 __objc_msgForward 最后 __objc_msgForward 中调用了 __objc_forward_handler, 汇编中搜索不到**__objc_forward_handler**, 搜索**_objc_forward_handler**:

// Default forward handler halts the process.
__attribute__((noreturn)) void 
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;

告诉我们找不到方法会造成异常崩溃.

三、消息转发机制

3.1 对象方法的动态方法决议

我们在使用runtime的时候, 经常会通过一个名字去调用方法. 但是名字如果不小心写错, 那么就会对整个工程造成很大的问题.

当消息查找在本类与父类中均未查找到, 那么就不回进入 goto done; 这个环节. 由上文得知, 在 **imp = (IMP)_objc_msgForward_impcache;**后会报错, 那么我们要处理的话应该是在报错前进行一次处理.

可以得知当查找不到方法时, 会走这里:

    if (resolver  &&  !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;
        goto retry;
    }

调用了一个方法, 跟进 _class_resolveMethod(cls, sel, inst) :

/***********************************************************************
* _class_resolveMethod
* Call +resolveClassMethod or +resolveInstanceMethod.
* Returns nothing; any result would be potentially out-of-date already.
* Does not check if the method already exists.
**********************************************************************/
void _class_resolveMethod(Class cls, SEL sel, id inst)
{
    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]

        _class_resolveInstanceMethod(cls, sel, inst);
    } 
    else {
        // try [nonMetaClass resolveClassMethod:sel]
        // and [cls resolveInstanceMethod:sel]
        _class_resolveClassMethod(cls, sel, inst);
        if (!lookUpImpOrNil(cls, sel, inst, 
                            NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
        {
            _class_resolveInstanceMethod(cls, sel, inst);
        }
    }
}

判断是否为元类, 表示得对类方法和对象方法进行分开处理. 先跟进对象方法 _class_resolveInstanceMethod(cls, sel, inst) :

/***********************************************************************
* _class_resolveInstanceMethod
* Call +resolveInstanceMethod, looking for a method to be added to class cls.
* cls may be a metaclass or a non-meta class.
* Does not check if the method already exists.
**********************************************************************/
static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
{
    if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls, 
                         NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
    {
        // Resolver not implemented.
        return;
    }

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

    // Cache the result (good or bad) so the resolver doesn't fire next time.
    // +resolveInstanceMethod adds to self a.k.a. cls
    IMP imp = lookUpImpOrNil(cls, sel, inst, 
                             NO/*initialize*/, YES/*cache*/, NO/*resolver*/);

    if (resolved  &&  PrintResolving) {
        if (imp) {
            _objc_inform("RESOLVE: method %c[%s %s] "
                         "dynamically resolved to %p", 
                         cls->isMetaClass() ? '+' : '-', 
                         cls->nameForLogging(), sel_getName(sel), imp);
        }
        else {
            // Method resolver didn't add anything?
            _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
                         ", but no new implementation of %c[%s %s] was found",
                         cls->nameForLogging(), sel_getName(sel), 
                         cls->isMetaClass() ? '+' : '-', 
                         cls->nameForLogging(), sel_getName(sel));
        }
    }
}

首先进行了一次判断, 用作来判断类中是否有 resolveInstanceMethod 这个方法. 全局搜索:

在NSObjcet中就已经实现了.

当系统找不到对应的sel方法时, 系统会去响应一个 resolveInstanceMethod 方法. 那么我们就可以这么做. 在自己类中重写这个方法:

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    return [super resolveInstanceMethod:sel];
}

为了防止找不到对应方法造成崩溃, 我们就可以在这里进行一步处理:

//声明sayHello方法, 但是未实现sayHello方法
//- (void)sayHello{
//    NSLog(@"%s",__func__);
//}
- (void)sayNew{
    NSLog(@"%s",__func__);
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(sayHello)) {
        IMP sayHIMP = class_getMethodImplementation(self, @selector(sayNew));
        Method sayHMethod = class_getInstanceMethod(self, @selector(sayNew));
        const char *types = method_getTypeEncoding(sayHMethod);
        
        return class_addMethod(self, sel, sayHIMP, types);
        
    }
    return [super resolveInstanceMethod: sel];
}

当重新在 resolveInstanceMethod 里添加一个方法后, 紧接着又调用了 **IMP imp = lookUpImpOrNil(cls, sel, inst, NO/ *initialize */, YES/ *cache */, NO / resolver /) , 又会重新调用 lookUpImpOrForward 再去查找是否有相应的sel方法. 因为在 resolveInstanceMethod 里添加一个方法, 所以势必会查找到对应方法, 执行 goto done 返回而不是 走到 _objc_msgForward_impcache;

3.2 类方法的方法动态决议

不难发现, 当在动态方法决议里, 也就是重写 resolveInstanceMethod. 在里面并没有处理相关SEL方法, 那么系统会走两次 resolveInstanceMethod. 但是一旦处理了相关SEL方法, 动态方法决议只会一次. 这也就代表着在动态方法决议后, 系统仍会有下一步处理.

当消息查找在本类与父类中均未查找到的时候,会进入**_class_resolveMethod(cls, sel, inst)**, 可以看到里面有一次判断处理, 判断是否为其元类. 已知类方法才是存在其元类里的, 那么这个判断应该就是当类方法查找不到的时候会走这里:

_class_resolveClassMethod(cls, sel, inst);
if (!lookUpImpOrNil(cls, sel, inst, 
                    NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
{
    _class_resolveInstanceMethod(cls, sel, inst);
}

根据代码可以得知, 假如在 resolveClassMethod 中没有进行一次类方法处理, 那么最后还是会调用 resolveInstanceMethod .

四、消息转发流程

4.1 快速转发流程

当我们调用一个不存在的方法的时候, 系统肯定会给我们一个崩溃信息:

+ 可以很清楚的看到在崩溃前其中还调用了一些 forwarding等相关的东西. 由上文得知, 假如当我们调用一个正确的方法的时候, 会对方法进行一次填充缓存: log_and_fill_cache(cls, meth->imp, sel, inst, cls); 看名字得知还有一个log日志的操作.

if (objcMsgLogEnabled) {
    bool cacheIt = logMessageSend(implementer->isMetaClass(), 
                                  cls->nameForLogging(),
                                  implementer->nameForLogging(), 
                                  sel);
    if (!cacheIt) return;
}

进入 logMessageSend :

    // Create/open the log file
    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;
        }
    }

能看到一个记录日志的操作, 放在/temp/目录下的一个msgSends-xx文件, 根据注释能知道 objcMsgLogEnabled 是是否保存日志文件的开关. 当前文件搜索一下 ‘ objcMsgLogEnabled = ‘ :

void instrumentObjcMessageSends(BOOL flag)
{
    bool enable = flag;

    // Shortcut NOP
    if (objcMsgLogEnabled == enable)
        return;

    // If enabling, flush all method caches so we get some traces
    if (enable)
        _objc_flush_caches(Nil);

    // Sync our log file
    if (objcMsgLogFD != -1)
        fsync (objcMsgLogFD);

    objcMsgLogEnabled = enable;
}

是通过 instrumentObjcMessageSends传递一个参数来告诉系统是否需要保存日志. 那么我们就在声明对象的时候调用 instrumentObjcMessageSends 来获取日志信息:

在tmp中得到一个 msgSends-xxx文件:

在动态方法决议之后, 又相继调用了 forwardingTargetForSelectormethodSignatureForSelector. 通过Developer Documentation中查找到相关方法:

将未识别的消息定向到的一个对象. 拿上文的例子, 也就是说, 当调用了saySomething方法时, 查找不到响应的方法, 可以通过 forwardingTargetForSelector将这个调用方法的任务交给其他可以调saySomething的类来处理.
Student没有saySomething方法, 就交给有saySomething方法的Teacher类来处理.

4.2快速转发流程

假如通过forwardingTargetForSelector将方法交给另一个类去处理, 另一个类也无法处理呢? 根据日志可以看到下面还有个methodSignatureForSelector. Developer Documentation中也有相应说明会走到forwardInvocation:这个流程.

并且还说明了必须实现methodSignatureForSelector:
methodSignatureForSelector方法返回对应的方法签名, forwardInvocation:有官方示例. 官方示例其中会将方法交给一个friend 去执行, 这个friend 就是将事务交给它去处理.即使它匹配不到这个方法, 也会直接将此事务闲置.而不会跳转到**_objc_msgForward_impcache**崩溃掉.

附: 动态方法决议中未处理消息会执行两次

在3.2中提到过. 当未处理消息的时候, 会调用两次 resolveInstanceMethod.

通过调试可以发现第二次调用 resolveInstanceMethod 是在返回方法签名之后执行的. 那么我们可以在返回方法签名处断点来通过汇编一步一步调试, 直至找到调用哪一条汇编才会出现的

通过调试得到在调用完104行的 objc_msgSend 消息发送, 就会进入第二次的resolveInstanceMethod 流程. 而在objc_msgSend上面是有一个 class_respondsToSelector. 进行全局搜索:

也就是当返回方法签名后, 系统会进行一次方法响应, 通过imp去查找方法, 重新进入一个消息查找流程来发送消息. 在返回方法签名后, 系统做了一些处理, 因为官方未开源, 所以无法探究.

所以只能猜测一下: 可能是签名处理完毕后, 在底层里面, 系统做了一个匹配, 将返回的方法签名来跟需要调用的saySomething方法去做匹配, 要找到原来的需要调用的saySomething方法.