美文网首页项目常见崩溃iOS Developer深入浅出iOS
利用消息转发机制屏蔽unrecognized selector

利用消息转发机制屏蔽unrecognized selector

作者: bigParis | 来源:发表于2016-05-31 11:55 被阅读810次

    受到JSPatch的启发, 想到利用消息转发机制屏蔽unrecognized selector sent to instance这种崩溃, 这种崩溃的意思是, 给没有实现的方法发消息

    产生原因

    不管是什么原因造成的, 可能是通过运行时performSelector调用了不存在的方法而并没有判断, 也可能是访问了不存在的属性或方法编译器没有报错, 导致运行崩溃, 也可能使用了强转等手段但是消息响应者并不是我们希望的类型, 都可能会导致程序崩溃. 那先不说如何解决崩溃, 先看看如何让程序不崩溃(有时候不让程序崩溃可能也不好, 问题被隐藏起来了, 更难发现了)

    解决原理

    原理1

    程序在崩溃前系统会给你3次机会进行补救, 可以通过重写

    + (BOOL)resolveInstanceMethod:(SEL)aSEL
    

    也可以通过重写

    - (id)forwardingTargetForSelector:(SEL)aSelector
    

    还可以重写

    - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
    

    - (void)forwardInvocation:(NSInvocation *)invocation
    

    具体的道理文献1文献2已经有比较详细的解释了, 这里不再赘述, 重点说下为什么不用前两种方式, 因为信息量不够, 前两种方式只有一个SEL类型的参数, 也就是只能知道调用了哪个方法而不知道是谁调用的, 也就是不知道target是谁, 那么在这里去addMethod是没法做到通用的, 因为你连target都不知道.怎么能准确给出程序想要的去处呢! 而且, 实践时候发现forwardingTargetForSelector会拦截很多系统的方法, 可能是在这里进行重定向, 所以也不适合拦截这个方法.

    原理2

    利用黑魔法, 通过交换2个方法来达到拦截系统的forwardInvocationmethodSignatureForSelector的目的, 这里要说明的是, 不一定要在+ load里去交换, 当然要做的彻底一些还是应该在+ load去做, 因为+ load的执行要在main之前, 也就是程序启动前, 这里仅仅说明原理而且这里用类方法也有其他的好处, 所以本文选择程序启动后去Swizzling Method

    + (void)hookNotRecognizeSelector
    {
        [MethodsHooker hookMethedClass:[NSObject class] hookSEL:@selector(methodSignatureForSelector:) originalSEL:@selector(methodSignatureForSelectorOriginal:) myselfSEL:@selector(methodSignatureForSelectorMySelf:)];
        [MethodsHooker hookMethedClass:[NSObject class] hookSEL:@selector(forwardInvocation:) originalSEL:@selector(forwardInvocationOriginal:) myselfSEL:@selector(forwardInvocationMySelf:)];
    }
    
    + (void)hookMethedClass:(Class)class hookSEL:(SEL)hookSEL originalSEL:(SEL)originalSEL myselfSEL:(SEL)mySelfSEL
    {
        Method hookMethod = class_getInstanceMethod(class, hookSEL);
        Method mySelfMethod = class_getInstanceMethod(self, mySelfSEL);
        
        IMP hookMethodIMP = method_getImplementation(hookMethod);
        class_addMethod(class, originalSEL, hookMethodIMP, method_getTypeEncoding(hookMethod));
        
        IMP hookMethodMySelfIMP = method_getImplementation(mySelfMethod);
        class_replaceMethod(class, hookSEL, hookMethodMySelfIMP, method_getTypeEncoding(hookMethod));
    }
    

    这里给一个类方法出来, 里面和可以hook很多崩溃, 我们的unrecognized selector也是其中一种, 可以在AppDelegatedidFinishLaunch里去调用, 好了看最关键的代码吧

    - (NSMethodSignature *)methodSignatureForSelectorMySelf:(SEL)aSelector {
        NSString *sel = NSStringFromSelector(aSelector);
        if ([sel rangeOfString:@"set"].location == 0) {
            return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
        } else {
            return [NSMethodSignature signatureWithObjCTypes:"@@:"];
        }
    }
    
    - (NSMethodSignature *)methodSignatureForSelectorOriginal:(SEL)aSelector {
        return nil;
    }
    
    - (void)forwardInvocationMySelf:(NSInvocation *)anInvocation {
        Class cls = [anInvocation.target class];
        id forwardInvocation = [[cls alloc] init];
        class_addMethod(cls, anInvocation.selector, (IMP)crashFunction, "v@:");
        if ([forwardInvocation respondsToSelector:anInvocation.selector]) {
            [anInvocation invokeWithTarget:forwardInvocation];
        }
    }
    
    - (void)forwardInvocationOriginal:(NSInvocation *)anInvocation {
        
    }
    
    void crashFunction(id self, SEL _cmd) {
        MFLogError(@"MethodsHook", @"程序崩溃");
        
    }
    

    methodSignatureForSelectorMySelfforwardInvocationMySelf是我们用来替换系统methodSignatureForSelectorforwardInvocationMySelf的实现, 这里可以随便返回一个签名可以和aSelector没任何关系, 这里的目的就是要让系统调用forwardInvocationMySelf, 在这里anInvocation可以拿到造成崩溃的类名和Selector, 所以这里动态的去给这个类添加一个实现crashFunction, 这里crashFunction只是简单的打印了一下日志, 然而, 程序的命运却完全不一样了, 这里程序不会崩溃了, 可以继续运行了, 这里只是给出一个简单的demo, 有兴趣的读者可以根据返回值类型,去造不同的crashFunction, 目的就是让程序继续运行.

    <NSInvocation: 0x7fb34a407830>
    return value: {@} 0x0
    target: {@} 0x7fb34a4134b0
    selector: {:} pushTitle
    

    展望

    这里分析出崩溃的原因并且屏蔽它并不是我们解决问题的方式, 最终还是要利用JSPatch去修复, 但对用户的体验可能不一样了, 尤其对那些不是很好重现的崩溃(可能是服务端包乱序, 服务端返回数据错误, 并且客户端没有保护)还是有很大帮助的, 用户不会觉得闪退, 可能只是自己卡了下, 这里crashFunction可以扩展的点很多, 可以是去重新进行网络请求, 或者干脆直接重启app, 具体的点大家可以多多发现, 有兴趣的可以留言和我进行交流.

    代码

    https://github.com/bigParis/BPUnrecognizedDemo

    参考文献
    [文献1](http://www.csdn.net/article/2015-07-06/2825133-objective-c-runtime/5)
    [文献2](http://www.cnblogs.com/biosli/p/NSObject_inherit_2.html)
    

    相关文章

      网友评论

      • Ilovecoding822:楼主,类方法貌似不行啊
      • Best_Kai:有没有demo可以提供下
        bigParis:@Best_Kai 替换不就没有了, 不能调到原来的方法了
        Best_Kai:@bigParis 有点不明白的是,为什么不直接替换实例方法,而要 再添加一个methodSignatureForSelectorOriginal 这样的方法?
        bigParis:@Best_Kai https://github.com/bigParis/BPUnrecognizedDemo
      • 酷酷的哀殿:行内代码建议用``包住
        另外,这里好像是错别字,前2中→前两种
        bigParis:@酷酷的哀殿 多谢提醒, 已改正

      本文标题:利用消息转发机制屏蔽unrecognized selector

      本文链接:https://www.haomeiwen.com/subject/mqvcdttx.html