探究如何从cache_t中读取数据
之前我们讲解了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_msgSend
与objc_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
继承LGPerson
在LGTeacher.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
的描述以及参数。
对于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
是用汇编写的
分析并可以得到以下结论:
objc_msgSend(receiver,sel...)
1.判断receiver(消息的接受者)
是否存在
2.根据receiver
的isa指针
&掩码
得到class
3.class
内存平移16字节
得到cache_t
4.调用cache_t
的buckets()
方法获取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
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
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;
} ```
总结:当快速查找没有找到时,会在当前类的方法列表中进行二分查找。