方法查找流程-快速查找流程

2020-12-30  本文已影响0人  丸疯

上一篇我们讲了方法写入流程:objc_class cache分析
本篇将介绍,方法的查找流程,在这之前,我们先了解一下runtime

Runtime

方法调用的本质

定义一个类,申明两个方法,并完成实现。

@interface Person : NSObject
- (void)sayHello;
+ (void)sayHoney;

@end

@implementation Person
- (void)sayHello{
    NSLog(@"hello");
}
+ (void)sayHoney{
    NSLog(@"honey");
}

@end

在main函数中完成调用

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        Person * person = [Person alloc];
        [Person sayHoney];
        [person sayHello];
        
        NSLog(@"Hello, World!");
    }
    return 0;
}

main.m文件对main.m进行clang,在终端执行:

xcrun -sdk iphonesimulator clang -arch x86_64 -rewrite-objc main.m

得到一个main.cpp文件
我们看到[Person sayHoney],和[person sayHello]这两个方法的调用在底层被编译成了:

((void (*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("Person"), sel_registerName("sayHoney"));
((void (*)(id, SEL))(void *)objc_msgSend)((id)person, sel_registerName("sayHello"))

从这两段代码,我们可以看出,方法的调用在底层其实就是objc_msgSend的调用。实际代码中验证一下。
要使用objc_msgSend方法,需要导入#import <objc/message.h>,然后关闭msg_msgSend严厉的检验机制,关闭方法如下图:

关闭消息发送严格的检查机制.png
然后在main函数中通过objc_msgSend来调用:
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        Person * person = [Person alloc];
        objc_msgSend(person, sel_registerName("sayHello"));
        objc_msgSend(objc_getClass("Person"), sel_registerName("sayHoney"));
        NSLog(@"------------------");
        [person sayHello];
        [Person sayHoney];
    }
    return 0;
}

打印结果如下:

2020-12-30 15:44:20.845622+0800 runtime感受[29642:236248] hello
2020-12-30 15:44:20.846451+0800 runtime感受[29642:236248] honey
2020-12-30 15:44:20.846557+0800 runtime感受[29642:236248] ------------------
2020-12-30 15:44:20.846638+0800 runtime感受[29642:236248] hello
2020-12-30 15:44:20.846802+0800 runtime感受[29642:236248] honey

发现,其实调用objc_msgSendoc代码的调用,结果都是一样的。
接下来我们就开始研究objc_msgSend

objc_msgSend

在源码环境搜索objc_msgSend,发现只有汇编的实现源码,我们找到在arm64下的objc_msgSend作为我们的研究对象。其源码如下,我们进行逐行的翻译

    ENTRY _objc_msgSend
    UNWIND _objc_msgSend, NoFrame

    cmp p0, #0          // nil check and tagged pointer check
#if SUPPORT_TAGGED_POINTERS
    b.le    LNilOrTagged        //  (MSB tagged pointer looks negative)
#else
    b.eq    LReturnZero
#endif
    ldr p13, [x0]       // p13 = isa
    GetClassFromIsa_p16 p13     // p16 = class
LGetIsaDone:
    // calls imp or objc_msgSend_uncached
    CacheLookup NORMAL, _objc_msgSend

#if SUPPORT_TAGGED_POINTERS
LNilOrTagged:
    b.eq    LReturnZero     // nil check

    // 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
    cmp p0, #0          // nil check and tagged pointer check
#if SUPPORT_TAGGED_POINTERS
    b.le    LNilOrTagged        //  (MSB tagged pointer looks negative)
#else
    b.eq    LReturnZero
#endif

接下来进入快速查找流程CacheLookup

方法的快速查找流程

.macro CacheLookup
    //
    // Restart protocol:
    //
    //   As soon as we're past the LLookupStart$1 label we may have loaded
    //   an invalid cache pointer or mask.
    //
    //   When task_restartable_ranges_synchronize() is called,
    //   (or when a signal hits us) before we're past LLookupEnd$1,
    //   then our PC will be reset to LLookupRecover$1 which forcefully
    //   jumps to the cache-miss codepath which have the following
    //   requirements:
    //
    //   GETIMP:
    //     The cache-miss is just returning NULL (setting x0 to 0)
    //
    //   NORMAL and LOOKUP:
    //   - x0 contains the receiver
    //   - x1 contains the selector
    //   - x16 contains the isa
    //   - other registers are set as per calling conventions
    //
LLookupStart$1:

    // p1 = SEL, p16 = isa
    ldr p11, [x16, #CACHE]              // p11 = mask|buckets

#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16
    and p10, p11, #0x0000ffffffffffff   // p10 = buckets
    and p12, p1, p11, LSR #48       // x12 = _cmd & mask
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
    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

    // 0x00010
    // 0x10000

    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
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16
    add p12, p12, p11, LSR #(48 - (1+PTRSHIFT))
                    // p12 = buckets + (mask << 1+PTRSHIFT)
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
    add p12, p12, p11, LSL #(1+PTRSHIFT)
                    // p12 = buckets + (mask << 1+PTRSHIFT)
#else
#error Unsupported cache mask storage for ARM64.
#endif

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

LLookupEnd$1:
LLookupRecover$1:
3:  // double wrap
    JumpMiss $0

.endmacro

逐行解读:


获取maskAndbuckets.png
上一篇下一篇

猜你喜欢

热点阅读