OC底层探索 - 方法的底层原理

74 阅读8分钟

objc_msgSend 初见

在 main.m代码中定义一个类,和几个方法,然后调用一下。

image.png

在终端中,main.m 所在目录下,执行 clang -rewrite-objc main.m ,把代码转换成C++代码。从中可以找到以下代码:

int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        TestObject *t = ((TestObject *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("TestObject"), sel_registerName("new"));
        ((void (*)(id, SEL))(void *)objc_msgSend)((id)t, sel_registerName("func1"));
        ((void (*)(id, SEL))(void *)objc_msgSend)((id)t, sel_registerName("func2"));
        ((void (*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("TestObject"), sel_registerName("func3"));
        ((void (*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("TestObject"), sel_registerName("func3"));
    }
    return 0;
}

可以看出,方法调用实际上是执行的 objc_msgSend

查一下官方文档:objc_msgSend

objc_msgSend作用是:向类的实例发送消息

默认第一个参数: self 指向要接收消息的类实例的指针

默认第二个参数:op 处理消息的方法的选择器

 Messages sent to an object’s superclass (using the super keyword) are sent using objc_msgSendSuper; other messages are sent using objc_msgSend.

这里说,当使用 super 关键字调用方法时,会使用 objc_msgSendSuper, 其他的都是使用 objc_msgSend.

那我们测试一下 objc_msgSendSuper 的情况。

objc_msgSendSuper 初见

定义一个 AClass ,再定义一个 BClass 继承自 ACLass.

image.png 然后把 BClass.m    转换成C++代码。从中找到 func1 方法。

// @implementation BClass

static void _I_BClass_func1(BClass * self, SEL _cmd) {
    ((void (*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("BClass"))}, sel_registerName("func1"));
    NSLog((NSString *)&__NSConstantStringImpl__var_folders__q_pqvbk4dj1hq66p78cc77xnqr0000gn_T_BClass_1102d0_mi_0);
}
// @end

可见 [super xxxx] 实际执行的是 objc_msgSendSuper

官方文档:objc_msgSendSuper

objc_msgSendSuper作用是:向类实例的父类发送消息

默认第一个参数:super指向objc_super数据结构的指针。objc_super 结构体中 receiver 是当前实例的指针; super_class 是指向当前实例的父类的指针。

默认第二个参数:op 处理消息的方法的选择器。

方法的快速查找

通过源码查看,objc_msgSend 在不同架构下有不同的实现。现在以 objc-msg-arm64 下面的来分析。

我们可以看到 objc_msgSend 的源码实现是通过汇编实现的。这样的优点是 执行速度更快

//进入objc_msgSend流程
    ENTRY _objc_msgSend
//流程开始,无需frame
    UNWIND _objc_msgSend, NoFrame

//判断p0(消息接受者)是否存在,不存在则重新开始执行objc_msgSend
    cmp    p0, #0            // nil check and tagged pointer check

//如果支持小对象类型。返回小对象或空
#if SUPPORT_TAGGED_POINTERS
//b是进行跳转,b.le是小于判断,也就是小于的时候LNilOrTagged
    b.le    LNilOrTagged        //  (MSB tagged pointer looks negative)
#else
//等于,如果不支持小对象,就LReturnZero
    b.eq    LReturnZero
#endif
//通过p13取isa
    ldr    p13, [x0]        // p13 = isa
//通过isa取class并保存到p16寄存器中
    GetClassFromIsa_p16 p13, 1, x0    // p16 = class
//LGetIsaDone是一个入口
LGetIsaDone:
    // calls imp or objc_msgSend_uncached
//进入到缓存查找或者没有缓存查找方法的流程
    CacheLookup NORMAL, _objc_msgSend, __objc_msgSend_uncached

#if SUPPORT_TAGGED_POINTERS
LNilOrTagged:
// nil check判空处理,直接退出
    b.eq    LReturnZero        // nil check
    GetTaggedClass
    b    LGetIsaDone
// SUPPORT_TAGGED_POINTERS
#endif

CacheLookup源码

//在cache中通过sel查找imp的核心流程
.macro CacheLookup Mode, Function, MissLabelDynamic, MissLabelConstant
//从x16中取出class移到x15中
    mov    x15, x16            // stash the original isa
//开始查找
LLookupStart\Function:
    // p1 = SEL, p16 = isa
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16_BIG_ADDRS
//ldr表示将一个值存入到p10寄存器中
//x16表示p16寄存器存储的值,当前是Class
//#数值表示一个值,这里的CACHE经过全局搜索发现是2倍的指针地址,也就是16个字节
//#define CACHE (2 * __SIZEOF_POINTER__)
//经计算,p10就是cache
    ldr    p10, [x16, #CACHE]                // p10 = mask|buckets
    lsr    p11, p10, #48            // p11 = mask
    and    p10, p10, #0xffffffffffff    // p10 = buckets
    and    w12, w1, w11            // x12 = _cmd & mask
//真机64位看这个
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16
//CACHE 16字节,也就是通过isa内存平移获取cache,然后cache的首地址就是 (bucket_t *)
    ldr    p11, [x16, #CACHE]            // p11 = mask|buckets
#if CONFIG_USE_PREOPT_CACHES
//获取buckets
#if __has_feature(ptrauth_calls)
    tbnz    p11, #0, LLookupPreopt\Function
    and    p10, p11, #0x0000ffffffffffff    // p10 = buckets
#else
//and表示与运算,将与上mask后的buckets值保存到p10寄存器
    and    p10, p11, #0x0000fffffffffffe    // p10 = buckets
//p11与#0比较,如果p11不存在,就走Function,如果存在走LLookupPreopt
    tbnz    p11, #0, LLookupPreopt\Function
#endif
//按位右移7个单位,存到p12里面,p0是对象,p1是_cmd
    eor    p12, p1, p1, LSR #7
    and    p12, p12, p11, LSR #48        // x12 = (_cmd ^ (_cmd >> 7)) & mask
#else
    and    p10, p11, #0x0000ffffffffffff    // p10 = buckets
//LSR表示逻辑向右偏移
//p11, LSR #48表示cache偏移48位,拿到前16位,也就是得到mask
//这个是哈希算法,p12存储的就是搜索下标(哈希地址)
//整句表示_cmd & mask并保存到p12
    and    p12, p1, p11, LSR #48        // x12 = _cmd & mask
#endif // CONFIG_USE_PREOPT_CACHES
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
    ldr    p11, [x16, #CACHE]                // p11 = mask|buckets
    and    p10, p11, #~0xf            // p10 = buckets
    and    p11, p11, #0xf            // p11 = maskShift
    mov    p12, #0xffff
    lsr    p11, p12, p11            // p11 = mask = 0xffff >> p11
    and    p12, p1, p11            // x12 = _cmd & mask
#else
#error Unsupported cache mask storage for ARM64.
#endif

//去除掩码后bucket的内存平移
//PTRSHIFT经全局搜索发现是3
//LSL #(1+PTRSHIFT)表示逻辑左移4位,也就是*16
//通过bucket的首地址进行左平移下标的16倍数并与p12相与得到bucket,并存入到p13中
    add    p13, p10, p12, LSL #(1+PTRSHIFT)
                        // p13 = buckets + ((_cmd & mask) << (1+PTRSHIFT))

                        // do {

//ldp表示出栈,取出bucket中的imp和sel分别存放到p17和p9
1:    ldp    p17, p9, [x13], #-BUCKET_SIZE    //     {imp, sel} = *bucket--
//cmp表示比较,对比p9和p1,如果相同就找到了对应的方法,返回对应imp,走CacheHit
    cmp    p9, p1                //     if (sel != _cmd) {
//b.ne表示如果不相同则跳转到2f
    b.ne    3f                //         scan more
                        //     } else {
2:    CacheHit \Mode                // hit:    call or return imp
                        //     }
//向前查找下一个bucket,一直循环直到找到对应的方法,循环完都没有找到就调用_objc_msgSend_uncached
3:    cbz    p9, \MissLabelDynamic        //     if (sel == 0) goto Miss;
//通过p13和p10来判断是否是第一个bucket
    cmp    p13, p10            // } while (bucket >= buckets)
    b.hs    1b

简单概括一下 objc_msgSend 中方法的快速查找流程:

  1. 判断消息接收者是否存在,不存在就不继续下面的查找了
  2. 通过消息接收者的isa找到,相应的 class
  3. class 经过内存平移找到 cache,然后 cache 内存平移找到 buckets
  4. 在 buckets 中查找是否有当前 sel
  5. 如果找到,则执行 CacheHit,来调用 imp
  6. 如果没找到,调用 _objc_msgSend_uncached

方法的慢速查找

// 慢速查找
STATIC_ENTRY __objc_msgSend_uncached
UNWIND __objc_msgSend_uncached, FrameWithNoSaves

// THIS IS NOT A CALLABLE C FUNCTION
// Out-of-band p15 is the class to search

MethodTableLookup
TailCallFunctionPointer x17

END_ENTRY __objc_msgSend_uncached


// 方法表查找
.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
    // 调用 lookUpImpOrForward 方法
    bl    _lookUpImpOrForward

    // IMP in x0
    mov    x17, x0

    RESTORE_REGS MSGSEND

lookUpImpOrForward 源码

这里已经不是汇编语言了,而是C++,它位于objc-runtime-new.mm文件中。


NEVER_INLINE
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
    // 定义消息转发 创建一个默认forward_imp,并赋值_objc_msgForward_impcache
    const IMP forward_imp = (IMP)_objc_msgForward_impcache;
    // 创建一个imp,值为nil
    IMP imp = nil;
    // 创建一个类curClass
    Class curClass;

    runtimeLock.assertUnlocked();
    // 判断类对象是否初始化
    if (slowpath(!cls->isInitialized())) {
        behavior |= LOOKUP_NOCACHE;
    }
    // 加锁防止并发实现的竞争
    runtimeLock.lock();
    // 检查是否是已知的类
    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
            // 再一次从cache中查找imp,
            // 这样做的目的是为了防止多线程操作时,其他线程加入cache,所以再取一次cache
            // 原因是这个慢速查找相对快速查找更加耗时,所以能在快速查找找到就不需要消耗这么多时间了
            // 如果找到了,则跳转到done_nolock
            imp = cache_getImp(curClass, sel);
            if (imp) goto done_unlock;
            curClass = curClass->cache.preoptFallbackClass();
#endif
        } else {
            // curClass method list.
            // 从curClass的方法列表中查找, 找到就执行 done
            // 先将方法加入cache,然后返回出去
            method_t *meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
                imp = meth->imp(false);
                goto done;
            }
            // 如果没找到,则 curClass 指向父类,如果 curClass == nil, 返回 消息转发 imp
            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.
        // curClass已经被赋值为它的父类,所以这里从父类的缓存里面找imp
        imp = cache_getImp(curClass, sel);
        // 当curClass的父类为nil的时候,imp会被赋值forward_imp,就会走这里,跳出循环
        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.
            // 找到就执行 done ,先将方法加入cache,然后返回出去
            goto done;
        }
    }

    // No implementation found. Try method resolver once.
    // 如果遍历完了父类都没有找到imp,则进行消息处理机制,动态方法决议,这个因为判断只会走一次的
    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
        // 把方法加入cls的 cache, 方便下次可以直接走快速查找
        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;
}




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



ALWAYS_INLINE static method_t *
search_method_list_inline(const method_list_t *mlist, SEL sel)
{
    int methodListIsFixedUp = mlist->isFixedUp();
    int methodListHasExpectedSize = mlist->isExpectedSize();

    if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
        // 在排序方法列表中查找方法
        return findMethodInSortedMethodList(sel, mlist);
    } else {
        // Linear search of unsorted method list
        if (auto *m = findMethodInUnsortedMethodList(sel, mlist))
            return m;
    }

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




ALWAYS_INLINE static method_t *
findMethodInSortedMethodList(SEL key, const method_list_t *list)
{
    if (list->isSmallList()) {
        if (CONFIG_SHARED_CACHE_RELATIVE_DIRECT_SELECTORS && objc::inSharedCache((uintptr_t)list)) {
            return findMethodInSortedMethodList(key, list, [](method_t &m) { return m.getSmallNameAsSEL(); });
        } else {
            return findMethodInSortedMethodList(key, list, [](method_t &m) { return m.getSmallNameAsSELRef(); });
        }
    } else {
        return findMethodInSortedMethodList(key, list, [](method_t &m) { return m.big().name; });
    }
}



template<class getNameFunc>
ALWAYS_INLINE static method_t *
findMethodInSortedMethodList(SEL key, const method_list_t *list, const getNameFunc &getName)
{

    ASSERT(list);
    // 二分查找,来找 method_t
    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;
}

简单概括一下方法的慢速查找流程流程:

  1. __objc_msgSend_uncached 中调用 MethodTableLookup
  2. MethodTableLookup 中调用 lookUpImpOrForward
  3. lookUpImpOrForward 中会从当前类沿着继承链向上遍历,直到当前类为 nil
  4. 每次都先找一次当前类的 cache, 再 从当前类方法中二分查找,再找父类的 cache, 然后当前类指向父类,再次循环
  5. 如果找到,加入消息接收者的 cache 中,然后返回
  6. 找不到如果是第一次会先走一次动态方法决议(对同一个cls仅执行一次),还不行走消息转发。