探究如何從cache_t中讀取數據

語言: CN / TW / HK

之前我們講解了cache_t的數據結構以及擴容規則,知道cache_t的作用就是緩存方法,目的就是為了當這個方法再次被調用時能夠更快得進行響應。那麼,是如何從cache_t中讀取數據的呢?今天我們來探索一下。

objc_msgSend objc_msgSendSuper 解析

* * Cache readers (PC-checked by collecting_in_critical()) * objc_msgSend* * cache_getImp * 首先看一下代碼

```

import "AppDelegate.h"

import

import

@interface LGPerson : NSObject

  • (void)study;
  • (void)happy;

@end

@implementation LGPerson

  • (void)study{ NSLog(@"%s",func); }

  • (void)happy{ NSLog(@"%s",func); }

@end

int main(int argc, char * argv[]) { NSString * appDelegateClassName; @autoreleasepool { // Setup code that might create autoreleased objects goes here. appDelegateClassName = NSStringFromClass([AppDelegate class]);

    LGPerson *p = [LGPerson alloc];
    [p study];
    [p happy];

}
return UIApplicationMain(argc, argv, nil, appDelegateClassName);

} ```

cd main.m 文件所在的文件夾
xcrun -sdk iphonesimulator clang -rewrite-objc main.m

int main(int argc, char * argv[]) { NSString * appDelegateClassName; /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; appDelegateClassName = NSStringFromClass(((Class (*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("AppDelegate"), sel_registerName("class"))); LGPerson *p = ((LGPerson *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("LGPerson"), sel_registerName("alloc")); ((void (*)(id, SEL))(void *)objc_msgSend)((id)p, sel_registerName("study")); ((void (*)(id, SEL))(void *)objc_msgSend)((id)p, sel_registerName("happy")); } return UIApplicationMain(argc, argv, __null, appDelegateClassName); } 在main.cpp文件裏我們可以看到下面的代碼

__OBJC_RW_DLLIMPORT void objc_msgSend(void); __OBJC_RW_DLLIMPORT void objc_msgSendSuper(void); __OBJC_RW_DLLIMPORT void objc_msgSend_stret(void); __OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void); __OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);

接下來我們就看一下objc_msgSendobjc_msgSendSuper的區別

看下面的代碼

```

import "LGPerson.h"

NS_ASSUME_NONNULL_BEGIN

@interface LGTeacher : LGPerson

@end

NS_ASSUME_NONNULL_END ```

```

import "LGTeacher.h"

import

@implementation LGTeacher

-(instancetype)init { if (self = [super init]) { NSLog(@"%@",[self class]); NSLog(@"%@",[super class]); } return self; }

@end ```

LGTeacher繼承LGPersonLGTeacher.m內重寫init方法 分別打印[self class] [super class] 看一下打印結果:

2022-05-01 12:50:57.456129+0800 002--objc_msgSendSuper[53554:1619027] LGTeacher 2022-05-01 12:50:57.456257+0800 002--objc_msgSendSuper[53554:1619027] LGTeacher 我們看到打印的結果都是LGTeacher,這是為什麼呢? 先看一下.cpp文件

static instancetype _I_LGTeacher_init(LGTeacher * self, SEL _cmd) { if (self = ((LGTeacher *(*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("LGTeacher"))}, sel_registerName("init"))) { NSLog((NSString *)&__NSConstantStringImpl__var_folders_55_v0dk5ypx4c1frzh0fjm9y28h0000gn_T_LGTeacher_007eea_mi_0,((Class (*)(id, SEL))(void *)objc_msgSend)((id)self, sel_registerName("class"))); NSLog((NSString *)&__NSConstantStringImpl__var_folders_55_v0dk5ypx4c1frzh0fjm9y28h0000gn_T_LGTeacher_007eea_mi_1,((Class (*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("LGTeacher"))}, sel_registerName("class"))); } return self; }

通過.cpp文件我們可以清晰地看到 當我們通過[self class] 的時候編譯成為 objc_msgSend函數,當我們通過[super class]時候編譯成為objc_msgSendSuper函數。
我們通過xcode->help->Developer Documentation->search objc_msgSendSuper可以看到關於objc_msgSendSuper的描述以及參數。

圖片.png

對於objc_msgSendSuper的描述:
意思就是當方法調用時,編譯器會生成對objc_msgSend、objc_msgsend_street、objc_msgSendSuper或objc_msgsendsuper_street函數之一的調用。如果使用關鍵字super 發送到對象的超類的消息時使用objc_msgSendSuper發送,其他消息使用objc_msgSend發送。

對於objc_msgSendSuper參數的描述:
objc_super結構體指針,包括要接收消息的類的實例和開始搜索方法實現的超類。

``` struct objc_super { /// Specifies an instance of a class. __unsafe_unretained _Nonnull id receiver;

/// Specifies the particular superclass of the instance to message.

if !defined(cplusplus) && !__OBJC2

/* For compatibility with old objc-runtime.h header */
__unsafe_unretained _Nonnull Class class;

else

__unsafe_unretained _Nonnull Class super_class;

endif

/* super_class is the first class to search */

}; ```

結合上面的.cpp文件的代碼,我們可以總結出無論是[self class] 還是[super class],消息接受者都是LGTeacher,不同的地方就是找方法的初始位置不一樣,[super class]要從其父類開始找。

方法的快速查找流程

首先我們在源碼中搜索objc_msgSend,在objc-msg-arm64中找到ENTRY _objc_msgSend,會發現 objc_msgSend是用匯編寫的 圖片.png 圖片.png 圖片.png 圖片.png 圖片.png 圖片.png

分析並可以得到以下結論:

objc_msgSend(receiver,sel...) 1.判斷receiver(消息的接受者)是否存在
2.根據receiverisa指針&掩碼得到class
3.class內存平移16字節得到cache_t
4.調用cache_tbuckets() 方法獲取buckets
5.遍歷buckets ,對比sel,在緩存中有沒有我們要找的sel
6.如果bucket(sel,imp)對比sel 相等 -->cacheHit-->調用imp
7.如果cache裏面沒有找到對應的sel,調用_objc_msgSend_uncached

方法的慢速查找算法

消息的快速查找也就是在cache中沒有找到對應的方法,就會調用_objc_msgSend_uncached這個函數,接下來我們就來研究一下_objc_msgSend_uncached

圖片.png 圖片.png

lookUpImpOrForward方法實現代碼

``` IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior) { ...

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_t *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; } ```

從當前類的方法列表查找流程 ``` 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;

}

`二分查找`算法 template ALWAYS_INLINE static method_t * 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;

} ```

總結:當快速查找沒有找到時,會在當前類的方法列表中進行二分查找。