第十节课 消息动态决议
在经过我们的快速与慢速查找之后依旧没有找到的怎么办呢?
cache_getImp
的父类查找流程中LGETImpMissDynamic
返回为空的情况下,并没有直接慢速查找,而是进行递归查找父类的父类的缓存,都查不到的情况下最终再往下继续
unrecognized selector sent to instance
相信大多人都看过这个错误吧?如果没看过当我没说😂
调用未实现的对象方法会报出这个错误,但是我们只知道报错,从来没有去研究过是怎么报的这个错误,接下来我们就来看看底层报错的实现原理
全局搜索lookUpImpOrForward
我们根据之前的查找流程已经知道了,最终如果没有找到的话,是返回的一个forward_imp
if (slowpath((curClass = curClass->getSuperclass()) == nil)) {
imp = forward_imp;
break;
}
但是具体是什么呢?我们来往上看下赋值部分
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
//进入_objc_msgForward_impcache
STATIC_ENTRY __objc_msgForward_impcache
// No stret specialization.
b __objc_msgForward
END_ENTRY __objc_msgForward_impcache
//进入__objc_msgForward
ENTRY __objc_msgForward
adrp x17, __objc_forward_handler@PAGE
ldr p17, [x17, __objc_forward_handler@PAGEOFF]
TailCallFunctionPointer x17
END_ENTRY __objc_msgForward
//进入TailCallFunctionPointer x17
.macro TailCallFunctionPointer
// $0 = function pointer value
br $0
.endmacro
//发现实际就是br $0,那我们就直接看x17-> __objc_forward_handler
//全局搜索__objc_forward_handler搜不到,就搜索objc_forward_handler
objc_defaultForwardHandler(id self, SEL sel)
{
_objc_fatal("%c[%s %s]: unrecognized selector sent to instance %p "
"(no message forward handler is installed)",
class_isMetaClass(object_getClass(self)) ? '+' : '-',
object_getClassName(self), sel_getName(sel), self);
}
我们可以看到实际输出的错误原因就是这里打印的,但是这中间底层实际做了很多的事情哟,接下来我们就来详细的剖析一下
方法动态决议
首先,还是回到lookUpImpOrForward
主函数中
来看这个函数
// No implementation found. Try method resolver once.
//behavior = 3
//LOOKUP_RESOLVER = 2
//behavior & LOOKUP_RESOLVER = 3 & 2 = 0x11 & 0x10 = 0x10 = 2
if (slowpath(behavior & LOOKUP_RESOLVER)) {
//behavior & LOOKUP_RESOLVER = 1 & 2 = 0x01 & 0x10 = 0x00 = 0
behavior ^= LOOKUP_RESOLVER;
return resolveMethod_locked(inst, sel, cls, behavior);
}
behavior为0后,不在进入此代码,保证了每一个lookUpImpOrForward函数最多只能执行一次resolveMethod_locked(动态方法决议),直到behavior被重新赋值
tips:在底层经常看到一些运算符,补充几个这次用到的:
&
:按位与,参与运算的两数各对应的二进位相与。只有对应的两个二进位都为1时,结果位才为1。
^
:按位异或,比较的是二进制位,相同位置数字不同为1,相同为0
^=
:按位异或,比较的是二进制位,相同位置数字不同为1,相同为0,将结果赋值为运算符左边。
进入resolveMethod_locked
static NEVER_INLINE IMP
resolveMethod_locked(id inst, SEL sel, Class cls, int behavior)
{
runtimeLock.assertLocked();
ASSERT(cls->isRealized());
runtimeLock.unlock();
// 给你一次机会 拯救地球 -> imp
if (! cls->isMetaClass()) {//非元类
// try [cls resolveInstanceMethod:sel]
//
resolveInstanceMethod(inst, sel, cls);
}
else {//元类
// try [nonMetaClass resolveClassMethod:sel]
// and [cls resolveInstanceMethod:sel]
resolveClassMethod(inst, sel, cls);
if (!lookUpImpOrNilTryCache(inst, sel, cls)) {
resolveInstanceMethod(inst, sel, cls);
}
}
// chances are that calling the resolver have populated the cache
// so attempt using it
return lookUpImpOrForwardTryCache(inst, sel, cls, behavior);
}
此函数里面有三个关键的函数:
resolveInstanceMethod
:实例方法动态添加imp
resolveClassMethod
:类方法动态添加imp
lookUpImpOrForwardTryCache
,当完成添加之后,回到之前的慢速查找流程再来一遍
resolveInstanceMethod
static void resolveInstanceMethod(id inst, SEL sel, Class cls)
{
runtimeLock.assertUnlocked();
ASSERT(cls->isRealized());
SEL resolve_sel = @selector(resolveInstanceMethod:);
//不会进入return,因为系统有默认实现resolveInstanceMethod
if (!lookUpImpOrNilTryCache(cls, resolve_sel, cls->ISA(/*authenticated*/true))) {
// Resolver not implemented.
return;
}
//系统会在此处为你发送一个消息resolve_sel
//当你的这个类检测了这个消息,并且做了处理
BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
bool resolved = msg(cls, resolve_sel, sel);
// Cache the result (good or bad) so the resolver doesn't fire next time.
// +resolveInstanceMethod adds to self a.k.a. cls
//那么此时系统会重新查找,此函数最终会触发LookUpImpOrForward
IMP imp = lookUpImpOrNilTryCache(inst, sel, cls);
if (resolved && PrintResolving) {
if (imp) {
_objc_inform("RESOLVE: method %c[%s %s] "
"dynamically resolved to %p",
cls->isMetaClass() ? '+' : '-',
cls->nameForLogging(), sel_getName(sel), imp);
}
else {
// Method resolver didn't add anything?
_objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
", but no new implementation of %c[%s %s] was found",
cls->nameForLogging(), sel_getName(sel),
cls->isMetaClass() ? '+' : '-',
cls->nameForLogging(), sel_getName(sel));
}
}
}
resolveClassMethod 类方法的动态决议
static void resolveClassMethod(id inst, SEL sel, Class cls)
{
runtimeLock.assertUnlocked();
ASSERT(cls->isRealized());
ASSERT(cls->isMetaClass());
//系统给resolveClassMethod函数默认返回NO,即默认实现了,不会return
if (!lookUpImpOrNilTryCache(inst, @selector(resolveClassMethod:), cls)) {
// Resolver not implemented.
return;
}
//容错处理,对元类局部操作,防止没有实现
Class nonmeta;
{
mutex_locker_t lock(runtimeLock);
nonmeta = getMaybeUnrealizedNonMetaClass(cls, inst);
// +initialize path should have realized nonmeta already
if (!nonmeta->isRealized()) {
_objc_fatal("nonmeta class %s (%p) unexpectedly not realized",
nonmeta->nameForLogging(), nonmeta);
}
}
//系统会在此处为你发送一个消息resolve_sel
//当你的这个类检测了这个消息,并且做了处理
BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
//类的类方法,就相当于元类的对象方法
bool resolved = msg(nonmeta, @selector(resolveClassMethod:), sel);
// Cache the result (good or bad) so the resolver doesn't fire next time.
// +resolveClassMethod adds to self->ISA() a.k.a. cls
IMP imp = lookUpImpOrNilTryCache(inst, sel, cls);
if (resolved && PrintResolving) {
if (imp) {
_objc_inform("RESOLVE: method %c[%s %s] "
"dynamically resolved to %p",
cls->isMetaClass() ? '+' : '-',
cls->nameForLogging(), sel_getName(sel), imp);
}
else {
// Method resolver didn't add anything?
_objc_inform("RESOLVE: +[%s resolveClassMethod:%s] returned YES"
", but no new implementation of %c[%s %s] was found",
cls->nameForLogging(), sel_getName(sel),
cls->isMetaClass() ? '+' : '-',
cls->nameForLogging(), sel_getName(sel));
}
}
}
lookUpImpOrForwardTryCache
通过动态添加方法之后,再次尝试查找sel
对应的最新添加的imp
IMP lookUpImpOrForwardTryCache(id inst, SEL sel, Class cls, int behavior)
{
return _lookUpImpTryCache(inst, sel, cls, behavior);
}
ALWAYS_INLINE
static IMP _lookUpImpTryCache(id inst, SEL sel, Class cls, int behavior)
{
runtimeLock.assertUnlocked();
//当类未初始化的时候,进入lookUpImpOrForward
//在里面处理不缓存任何方法
if (slowpath(!cls->isInitialized())) {
// see comment in lookUpImpOrForward
return lookUpImpOrForward(inst, sel, cls, behavior);
}
//通过汇编查找
IMP imp = cache_getImp(cls, sel);
if (imp != NULL) goto done;
#if CONFIG_USE_PREOPT_CACHES
//共享缓存查找
if (fastpath(cls->cache.isConstantOptimizedCache(/* strict */true))) {
imp = cache_getImp(cls->cache.preoptFallbackClass(), sel);
}
#endif
//如果依然找不到,证明方法真的不存在,也就是说,只能依靠方法的动态添加了
//那么此时再次进入方法的慢速查找流程
if (slowpath(imp == NULL)) {
return lookUpImpOrForward(inst, sel, cls, behavior);
}
done:
//此判断是当前imp已经存在了,并且这个imp是默认赋值的forward_imp
//此时返回imp为nil;
if ((behavior & LOOKUP_NIL) && imp == (IMP)_objc_msgForward_impcache) {
return nil;
}
return imp;
}
整合实例对象/类对象的动态方法决议
根据上述源码分析,我们可以看到,只要我们实现了resolveInstanceMethod/resolveClassMethod
这两个方法,我们就可以拦截到崩溃前执行的步骤,并做出一定改造的话,就可以拦截崩溃。
话不多说,上代码。创建NSObject分类
的方式将此实现都放在分类中:
@implementation NSObject (FF)
//为实例对象创建一个IMP
- (void)sayHelloCrash {
NSLog(@"%s",__func__);
}
//为元类对象创建创建一个IMP
+ (void)sayHelloBug {
NSLog(@"%@ - %s",self,__func__);
}
#pragma clang diagnostic push
// 让编译器忽略错误
#pragma clang diagnostic ignored "-Wundeclared-selector"
+ (BOOL)resolveInstanceMethod:(SEL)sel {
NSLog(@"人工介入resolveInstanceMethod :%@-%@",self,NSStringFromSelector(sel));
if (sel == @selector(say666)) {
IMP sayHelloCrashImp = class_getMethodImplementation(self, @selector(sayHelloCrash));
Method method = class_getInstanceMethod(self, @selector(sayHelloCrash));
const char * type = method_getTypeEncoding(method);
return class_addMethod(self, sel, sayHelloCrashImp, type);
} else if (sel == @selector(sayHappy)) {
IMP enjoyTimeImp = class_getMethodImplementation(objc_getMetaClass("HZMTeacher"), @selector(enjoyTime));
Method method = class_getInstanceMethod(objc_getMetaClass("HZMPerson"), @selector(enjoyTime));
const char * type = method_getTypeEncoding(method);
return class_addMethod(objc_getMetaClass("HZMPerson"), sel, enjoyTimeImp, type);
}
return NO;
}
#pragma clang diagnostic pop
@end
为什么要写在NSObject分类里呢?我们来分析下
其实通过方法慢速查找流程可以发现其查找路径有两条:
实例方法:类 -- 父类 -- 根类 -- nil
类方法:元类 -- 根元类 -- 根类 -- nil
它们的共同点是如果前面没找到,都会来到根类即NSObject中查找,所以我们将上述的两个方法统一整合在一起,以NSObject添加分类的方式来实现统一处理。而且由于类方法的查找,在其继承链,查找的也是实例方法,所以可以将实例方法 和 类方法的统一处理放在resolveInstanceMethod
这种方式的实现,正好与源码中针对类方法的处理逻辑是一致的,即完美阐述为什么调用了类方法动态方法决议,还要调用对象方法动态方法决议(也就是resolveInstanceMethod
为什么走了两次
的原因),其根本原因还是类方法在元类中的实例方法。
当然,上面这种写法还是会有其他的问题,比如系统方法也会被更改,针对这一点,我们可以针对自定义类中方法统一方法名的前缀,根据前缀来判断是否是自定义方法,然后统一处理自定义方法,例如可以在崩溃前pop到首页,再上报自己的服务器告知出问题的原因,主要是用于app线上防崩溃的处理,提升用户的体验