初探OC底层原理之《消息慢速查找obc_msgSend_uncached》

分析lookUpImpOrForward源码流程

.macro MethodTableLookup
    
    SAVE_REGS MSGSEND

    // 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

    RESTORE_REGS MSGSEND

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();

    if (slowpath(!cls->isInitialized())) {
        // The first message sent to a class is often +new or +alloc, or +self
        // which goes through objc_opt_* or various optimized entry points.
        //
        // However, the class isn't realized/initialized yet at this point,
        // and the optimized entry points fall down through objc_msgSend,
        // which ends up here.
        //
        // We really want to avoid caching these, as it can cause IMP caches
        // to be made with a single entry forever.
        //
        // Note that this check is racy as several threads might try to
        // message a given class for the first time at the same time,
        // in which case we might cache anyway.
        behavior |= LOOKUP_NOCACHE;
    }

    // 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.
    checkIsKnownClass(cls);

    cls = realizeAndInitializeIfNeeded_locked(inst, cls, behavior & LOOKUP_INITIALIZE);
    // runtimeLock may have been dropped but is now locked again
    runtimeLock.assertLocked();
    curClass = cls;

    // The code used to lookup 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();;) {
        if (curClass->cache.isConstantOptimizedCache(/* strict */true)) {
#if CONFIG_USE_PREOPT_CACHES
            imp = cache_getImp(curClass, sel);
            if (imp) goto done_unlock;
            curClass = curClass->cache.preoptFallbackClass();
#endif
        } else {
            // curClass method list.
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
                imp = meth->imp(false);
                goto done;
            }

            if (slowpath((curClass = curClass->getSuperclass()) == 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;
        }
    }

    // No implementation found. Try method resolver once.

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

 done:
    if (fastpath((behavior & LOOKUP_NOCACHE) == 0)) {
#if CONFIG_USE_PREOPT_CACHES
        while (cls->cache.isConstantOptimizedCache(/* strict */true)) {
            cls = cls->cache.preoptFallbackClass();
        }
#endif
        log_and_fill_cache(cls, imp, sel, inst, curClass);
    }
 done_unlock:
    runtimeLock.unlock();
    if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
        return nil;
    }
    return imp;
}
  • 1.方法流程汇编当objc_msgSend 快速查找找不imp时 会调用MethodTableLookup 然后bl 跳转到_lookUpImpOrForward方法进行慢速查找
  • 2.if (slowpath(!cls->isInitialized())) 是进行初始化操作 checkIsKnownClass(cls)“检测类是否注册过, 如果未注册过抛异常”
  • realizeAndInitializeIfNeeded_locked(inst, cls, behavior & LOOKUP_INITIALIZE)递归查找父类或者元类的父类是否有
  • for (unsigned attempts = unreasonableClassCount();;)查找自己方法列表, 再查找 superclass 链
  • 总结:1.检查是否注册过 -否 -> 检查父类或者元类的父类是否已经存在 否 -> 进入for循环查找如果imp = forward_imp 命中 返回退出 ,找不到继续寻找直到 Method meth = getMethodNoSuper_nolock(curClass, sel);找不到 imp = meth->imp(false); 退出循环 反之-->log_and_fill_cache 进行缓存填充并返回 如果都找不递归再来一次,直到nil
image.png

了解getMethodNoSuper_nolock里面查找imp的算法

findMethodInSortedMethodList(SEL key, const method_list_t *list, const getNameFunc &getName)
{
    ASSERT(list);

    auto first = list->begin();
    auto base = first;
    decltype(first) 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)getName(probe);
        
        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)getName((probe - 1))) {
                probe--;
            }
            return &*probe;
        }
        
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}
  • 这是一个金典的二分查找算法,用oc原生代码返原验证
const char *getName(uintptr_t sel)
{
    if (!sel) return "";
    return (const char *)(const void*)sel;
}

void sead_find (NSArray *nums, NSInteger target){

    if (nums.count == 0) return;
    NSInteger base = 0;
    NSInteger count = 0;
    NSInteger probe = 0;
    uintptr_t keyValue = (uintptr_t)target;
    NSInteger forcount = 0; //进入循环多少次

    for (count = nums.count; nums.count != 0; count >>= 1) {
        probe = base + (count >> 1);

        forcount ++;
        uintptr_t probeValue = (uintptr_t)getName(probe);
        NSLog(@"进入循环的次数----------------------\n %ld-----probeValue--\n%lu---base--\n%lu---count--%ld",forcount,probeValue,base,count);
        probe = base + (count >> 1);
        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)getName((probe - 1))) {
//                probe--;
//            }
//            return probe;
            NSLog(@"--------命中目标------------");
            return;
        }
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
            NSLog(@"--------找不到---------------base--\n%lu---count--%ld--probeValue--%lu",base,count,probeValue);

        }
    }
}

  • 输出如下:
2021-07-01 17:46:52.291675+0800 004-instrumentObjcMessageSends辅助分析[4227:192071] 进入循环的次数----------------------
 1-----probeValue--
5---base--
0---count--10
2021-07-01 17:46:52.292279+0800 004-instrumentObjcMessageSends辅助分析[4227:192071] --------找不到---------------base--
6---count--9--probeValue--5
2021-07-01 17:46:52.292360+0800 004-instrumentObjcMessageSends辅助分析[4227:192071] 进入循环的次数----------------------
 2-----probeValue--
8---base--
6---count--4
2021-07-01 17:46:52.292457+0800 004-instrumentObjcMessageSends辅助分析[4227:192071] --------找不到---------------base--
9---count--3--probeValue--8
2021-07-01 17:46:52.292520+0800 004-instrumentObjcMessageSends辅助分析[4227:192071] 进入循环的次数----------------------
 3-----probeValue--
9---base--
9---count--1
2021-07-01 17:46:52.292596+0800 004-instrumentObjcMessageSends辅助分析[4227:192071] --------命中目标------------

你可能感兴趣的:(初探OC底层原理之《消息慢速查找obc_msgSend_uncached》)