美文网首页
iOS-OC对象原理_objc_msgSend(二)

iOS-OC对象原理_objc_msgSend(二)

作者: 泽泽伐木类 | 来源:发表于2020-09-24 14:21 被阅读0次

前言

iOS-OC对象原理_objc_msgSend(一)
在上篇文章中我们探索了objc_msgSend()慢速查找流程,即先从cache_t cache中的buckets中查找是否有sel == _cmd,存在则返回;不存在,将进入慢速查找流程,即_lookUpImpOrForward流程,今天我们就详细的探索下它的具体实现。

回顾

我们第一次看到_lookUpImpOrForward是在objc-msg.arm64.s汇编文件中(这里以arm64为例):

// lookUpImpOrForward(obj, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER)
// receiver and selector already in x0 and x1
mov x2, x16
mov x3, #3
bl  _lookUpImpOrForward

// IMP in x0
mov x17, x0

但是我们在该文件下搜索,并没有找到该跳转指令的实现;然后通过全局搜索依然没有找到:


截屏2020-09-24 上午10.36.14.png

然后在汇编代码片段开始有两行醒目的注释:

// lookUpImpOrForward(obj, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER)
// receiver and selector already in x0 and x1

全局搜索lookUpImpOrForward,豁然开朗,这一跳转就又来到了C++代码(骚的一批),我们锁定了objc-runtime-new.mm:

截屏2020-09-24 上午10.43.29.png
lookUpImpOrForward实现源码:
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
    const IMP forward_imp = (IMP)_objc_msgForward_impcache;
    IMP imp = nil;
    Class curClass;

    runtimeLock.assertUnlocked();

    // Optimistic cache lookup
    if (fastpath(behavior & LOOKUP_CACHE)) {
        imp = cache_getImp(cls, sel);
        if (imp) goto done_nolock;
    }

    // runtimeLock is held during isRealized and isInitialized checking
    // to prevent races against concurrent realization.

    // runtimeLock is held during method search to make
    // method-lookup + cache-fill atomic with respect to method addition.
    // Otherwise, a category could be added but ignored indefinitely because
    // the cache was re-filled with the old value after the cache flush on
    // behalf of the category.

    runtimeLock.lock();

    // We don't want people to be able to craft a binary blob that looks like
    // a class but really isn't one and do a CFI attack.
    //
    // To make these harder we want to make sure this is a class that was
    // either built into the binary or legitimately registered through
    // objc_duplicateClass, objc_initializeClassPair or objc_allocateClassPair.
    //
    // TODO: this check is quite costly during process startup.
    checkIsKnownClass(cls);

    if (slowpath(!cls->isRealized())) {
        cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
        // runtimeLock may have been dropped but is now locked again
    }

    if (slowpath((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized())) {
        cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
        // runtimeLock may have been dropped but is now locked again

        // If sel == initialize, class_initialize will send +initialize and 
        // then the messenger will send +initialize again after this 
        // procedure finishes. Of course, if this is not being called 
        // from the messenger then it won't happen. 2778172
    }

    runtimeLock.assertLocked();
    curClass = cls;

    // The code used to lookpu the class's cache again right after
    // we take the lock but for the vast majority of the cases
    // evidence shows this is a miss most of the time, hence a time loss.
    //
    // The only codepath calling into this without having performed some
    // kind of cache lookup is class_getInstanceMethod().

    for (unsigned attempts = unreasonableClassCount();;) {
        // curClass method list.
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp;
            goto done;
        }

        if (slowpath((curClass = curClass->superclass) == nil)) {
            // No implementation found, and method resolver didn't help.
            // Use forwarding.
            imp = forward_imp;
            break;
        }

        // Halt if there is a cycle in the superclass chain.
        if (slowpath(--attempts == 0)) {
            _objc_fatal("Memory corruption in class list.");
        }

        // Superclass cache.
        imp = cache_getImp(curClass, sel); // 有问题???? cache_getImp - lookup - lookUpImpOrForward
        if (slowpath(imp == forward_imp)) {
            // Found a forward:: entry in a superclass.
            // Stop searching, but don't cache yet; call method
            // resolver for this class first.
            break;
        }
        if (fastpath(imp)) {
            // Found the method in a superclass. Cache it in this class.
            goto done;
        }
    }

    // No implementation found. Try method resolver once.

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

 done:
    log_and_fill_cache(cls, imp, sel, inst, curClass);
    runtimeLock.unlock();
 done_nolock:
    if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
        return nil;
    }
    return imp;
}

核心代码片段:

for (unsigned attempts = unreasonableClassCount();;) {
        // curClass method list.
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp;
            goto done;
        }

        if (slowpath((curClass = curClass->superclass) == nil)) {
            // No implementation found, and method resolver didn't help.
            // Use forwarding.
            imp = forward_imp;
            break;
        }

        // Halt if there is a cycle in the superclass chain.
        if (slowpath(--attempts == 0)) {
            _objc_fatal("Memory corruption in class list.");
        }

        // Superclass cache.
        imp = cache_getImp(curClass, sel); 
        if (slowpath(imp == forward_imp)) {
            // Found a forward:: entry in a superclass.
            // Stop searching, but don't cache yet; call method
            // resolver for this class first.
            break;
        }
        if (fastpath(imp)) {
            // Found the method in a superclass. Cache it in this class.
            goto done;
        }
    }

该片段会进入一个循环,开始从curClass->superClass->NSObject->nil,如果查询到执行goto done跳出循环,如果没有找到,即curClass == nil时,break跳出循环。如下图:

拓补图.006.jpeg
上面的流程图中就简单的展示了lookUpImpOrForward方法实现的大致逻辑。
这里的log_and_fill_cacahe()会触发cache_t内部的fill_cache()方法,然后再到insert(),最终插入到缓存列表。

这里在更深入的看下getMethodNoSuper_nolock的内部实现:

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

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

    auto const methods = cls->data()->methods();
    for (auto mlists = methods.beginLists(),
              end = methods.endLists();
         mlists != end;
         ++mlists)
    {
        // <rdar://problem/46904873> getMethodNoSuper_nolock is the hottest
        // caller of search_method_list, inlining it turns
        // getMethodNoSuper_nolock into a frame-less function and eliminates
        // any store from this codepath.
        method_t *m = search_method_list_inline(*mlists, sel);
        if (m) return m;
    }

    return nil;
}

auto const methods = cls->data()->methods(),这里其实就是获取当前classclass_data_bits_t *bit下的bit->data(),也就是class_rw_t这个结构体的内容,并读取了该结构体的methods(),获取方法列表。
继续将获取到的methods传递给search_method_list_inline()方法:

ALWAYS_INLINE static method_t *
search_method_list_inline(const method_list_t *mlist, SEL sel)
{
    int methodListIsFixedUp = mlist->isFixedUp();
    int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t);
    
    if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
        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;
}

经过一个判断后,又将方法列表mlist和目标sel,传递到findMethodInSortedMethodList()方法中:

ALWAYS_INLINE 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;
}

这里是真正的开始查找流程,这里采用了二分法查询,当查询到就返回method_t,否则返回nil
大致流程图如下:

拓补图.007.jpeg

补充

forward_imp

const IMP forward_imp = (IMP)_objc_msgForward_impcache;

lookUpImpOrForward()方法中,在某种情况下会imp = forward_imp,当返回forward_imp后,又做了哪些处理呐?我们来探索下:

#if !OBJC_OLD_DISPATCH_PROTOTYPES
extern void _objc_msgForward_impcache(void);
#else
extern id _objc_msgForward_impcache(id, SEL, ...);
#endif

又看不到实现了,经验告诉我又要跳转到汇编:

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_msgForward_impcache->__objc_msgForward->__objc_forward_handler,在汇编中又找不到__objc_forward_handler的实现了,妈妈的~,回到C++:

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

好熟悉的味道 😃😀,unrecognized selector sent to instance xxxx,看到了让你大脑瞬间崩溃的东西,原来是来自这里。
这也就意味着,当imp = forward_imp,系统也就放弃治疗了,直接进入Crash流程。

总结

我们以 [person sayHello]为例:
该方法在编译后变为objc_msgSend(person,sel_registerName("sayHello"))
首先会进入快速查找流程,该流程的实现在汇编指令中完成:
1.查到person的类对象,person->isa->Class;
2.查找缓存列表,Class->offset(16)->cache->_maskAndBuckets->buckets;
3.在buckets列表中查询是否有sel == _cmd,存在则返回,否则进入CheckMiss->__objc_msgSend_uncached->MethodTableLookup->_lookUpImpOrForward,由此进入慢速查找流程
开始慢速查找流程
1.查找curClass类对象的方法列表,curCls->data()->methods()(objc_class->class_rw_t->methods());
2.通过二分遍历查询当前方法列表中是有sel==_cmd,如果存在则返回并执行4,否则执行3;
3.将当前的curCls= curCls->superclass,首先在父类中的cache->_maskAndBuckets->buckets缓存列表查询(imp = cache_getImp(curCls,sel)),如果存在,执行4,否则执行1;直到curClass = nil时,依然没有匹配,跳出循环,执行5;
4.找到目标imp,添加到缓存列表,并返回;
5.没有找到对应的imp,进入消息转发流程消息转发流程

相关文章

网友评论

      本文标题:iOS-OC对象原理_objc_msgSend(二)

      本文链接:https://www.haomeiwen.com/subject/hprzyktx.html