之前咱们讲解了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 <objc/runtime.h>
#import <objc/message.h>
@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 <objc/message.h>
@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<class getNameFunc>
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;
}
总结:当快速查找没有找到时,会在当时类的办法列表中进行二分查找。