iOS Crash 捕获处理

上一篇见iOS常见Crash案例总结

iOS Crash捕获

iOS端的crash分为两类,一类是NSException异常,另外一类是Signal信号异常。这两类异常我们都可以通过注册相关函数来捕获。

Crash种类
1、对于unrecognized selector sent to instance找不到方法iOS系统抛出异常崩溃,给NSObject添加一个分类,实现消息转发的几个方法
当无实现的方法时消息转发流程.jpeg

利用runtime消息转发处理未实现的方法crash,代码如下:

#import 

static NSString *_errorFunctionName;
void dynamicMethodIMP(id self,SEL _cmd) {}

static inline void change_method(Class _originalClass ,SEL _originalSel,Class _newClass ,SEL _newSel) {
    Method methodOriginal = class_getInstanceMethod(_originalClass, _originalSel);
    Method methodNew = class_getInstanceMethod(_newClass, _newSel);
    method_exchangeImplementations(methodOriginal, methodNew);
}

@implementation NSObject(UnRecognized)
+ (void)load {
    change_method([self class], @selector(methodSignatureForSelector:), [self class], @selector(ws_methodSignatureForSelector:));
    change_method([self class], @selector(forwardInvocation:), [self class], @selector(ws_forwardInvocation:));
}

- (NSMethodSignature *)ws_methodSignatureForSelector:(SEL)aSelector {
    if (![self respondsToSelector:aSelector]) {
        _errorFunctionName = NSStringFromSelector(aSelector);
        NSMethodSignature *methodSignature = [self ws_methodSignatureForSelector:aSelector];
        if (class_addMethod([self class], aSelector, (IMP)dynamicMethodIMP, method_getTypeEncoding(class_getInstanceMethod([self class], @selector(methodSignatureForSelector:))))) {
            NSLog(@"添加临时方法成功!");
        }
        if (!methodSignature) {
            methodSignature = [self ws_methodSignatureForSelector:aSelector];
        }
        return methodSignature;
    }else{
        return [self ws_methodSignatureForSelector:aSelector];
    }
}

- (void)ws_forwardInvocation:(NSInvocation *)anInvocation{
    SEL selector = [anInvocation selector];
    if ([self respondsToSelector:selector]) {
        [anInvocation invokeWithTarget:self];
    }else{
        [self ws_forwardInvocation:anInvocation];
    }
}

@end

2、对于signal产生的crash,创建一个crash捕获的单例,里面进行信号捕捉处理,只需要在AppDelegate中进行初始化

#import "WSCrashHandler.h"
#include 
#include 
#include 
NSString * const kSignalExceptionName = @"kSignalExceptionName";
NSString * const kSignalKey = @"kSignalKey";
NSString * const kCaughtExceptionStackInfoKey = @"kCaughtExceptionStackInfoKey";

static void HandleException(NSException *exception);
static void SignalHandler(int signal);

@interface WSCrashHandler ()
@property (nonatomic, assign) BOOL dismissed;
@end

@implementation WSCrashHandler

+ (instancetype)shared {
    static WSCrashHandler *sharedHelper = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedHelper = [[WSCrashHandler alloc] init];
    });
    return sharedHelper;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        // 1.捕获一些异常导致的崩溃
        NSSetUncaughtExceptionHandler(&HandleException);
        
        // 2.捕获非异常情况,通过signal传递出来的崩溃
        //signal是一个函数,有2个参数,第一个是int类型,第二个参数是一个函数指针
        //添加想要监听的signal类型,当发出相应类型的signal时,会回调SignalHandler方法
        signal(SIGABRT, SignalHandler);// SIGABRT--程序中止命令中止信号
        signal(SIGILL, SignalHandler);//SIGILL--程序非法指令信号
        signal(SIGSEGV, SignalHandler);//SIGSEGV--程序无效内存中止信号
        signal(SIGFPE, SignalHandler);//SIGFPE--程序浮点异常信号
        signal(SIGBUS, SignalHandler);//SIGBUS--程序内存字节未对齐中止信号
        signal(SIGPIPE, SignalHandler);//SIGPIPE--程序Socket发送失败中止信号
    }
    return self;
}

//NSException异常是OC代码导致的crash
void HandleException(NSException *exception) {
    NSString *message = [NSString stringWithFormat:@"崩溃原因如下:\n%@\n%@",
                         [exception reason],
                         [[exception userInfo] objectForKey:kCaughtExceptionStackInfoKey]];
    NSLog(@"%@",message);
    
    // 获取NSException异常的堆栈信息
    NSArray *callStack = [exception callStackSymbols];
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:[exception userInfo]];
    [userInfo setObject:callStack forKey:kCaughtExceptionStackInfoKey];
    
    WSCrashHandler *crashObject = [WSCrashHandler shared];
    NSException *customException = [NSException exceptionWithName:[exception name] reason:[exception reason] userInfo:userInfo];
    [crashObject performSelectorOnMainThread:@selector(handleException:) withObject:customException waitUntilDone:YES];
}
//signal信号抛出的异常处理
void SignalHandler(int signal) {
    NSArray *callStack = [WSCrashHandler backtrace];
    NSLog(@"signal信号捕获崩溃,堆栈信息:%@",callStack);
    
    WSCrashHandler *crashObject = [WSCrashHandler shared];
    NSException *customException = [NSException exceptionWithName:kSignalExceptionName
                                                           reason:[NSString stringWithFormat:NSLocalizedString(@"Signal %d was raised.", nil),signal]
                                                         userInfo:@{kSignalKey:[NSNumber numberWithInt:signal]}];
    
    [crashObject performSelectorOnMainThread:@selector(handleException:) withObject:customException waitUntilDone:YES];
}

- (void)handleException:(NSException *)exception {
    // 打印或弹出框
    // TODO :
#ifdef DEBUG
    NSString *message = [NSString stringWithFormat:@"抱歉,APP发生了异常,点击屏幕继续并自动复制错误信息到剪切板。\n\n异常报告:\n异常名称:%@\n异常原因:%@\n", [exception name], [exception reason]];
    NSLog(@"%@",message);
    [self showCrashToastWithMessage:message];
    
    CFRunLoopRef runLoop = CFRunLoopGetCurrent();
    CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop);
    while (!self.dismissed) {
        for (NSString *mode in (__bridge NSArray *)allModes) {
            //为阻止线程退出,使用 CFRunLoopRunInMode(model, 0.001, false)等待系统消息,false表示RunLoop没有超时时间
            CFRunLoopRunInMode((CFStringRef)mode, 0.001, false);
        }
    }
    CFRelease(allModes);
#endif
    // 本地保存exception异常信息并上传服务器
    // TODO :
    
    // 下面等同于清空之前设置的
    NSSetUncaughtExceptionHandler(NULL);
    signal(SIGABRT, SIG_DFL);
    signal(SIGILL, SIG_DFL);
    signal(SIGSEGV, SIG_DFL);
    signal(SIGFPE, SIG_DFL);
    signal(SIGBUS, SIG_DFL);
    signal(SIGPIPE, SIG_DFL);
    
    // 杀死 或 唤起
    if ([[exception name] isEqual:kSignalExceptionName]) {
        kill(getpid(), [[[exception userInfo] objectForKey:kSignalKey] intValue]);
    } else {
        [exception raise];
    }
}

//该函数用来获取当前线程调用堆栈的信息,并且转化为字符串数组。
+ (NSArray *)backtrace {
    void *callStack[128];//堆栈方法数组
    int frames = backtrace(callStack, 128);//获取错误堆栈方法指针数组,返回数目
    char **strs = backtrace_symbols(callStack, frames);//符号化
    
    NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames]; //函数调用信息依照顺序存在NSMutableArray backtrace
    for (int i = 0; i < frames; i++) {
        [backtrace addObject:[NSString stringWithUTF8String:strs[i]]];
    }
    free(strs);
    return backtrace;
}

- (void)showCrashToastWithMessage:(NSString *)message {
    UILabel *crashLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 64, [UIApplication sharedApplication].keyWindow.bounds.size.width, [UIApplication sharedApplication].keyWindow.bounds.size.height - 64)];
    crashLabel.textColor = [UIColor redColor];
    crashLabel.font = [UIFont systemFontOfSize:15];
    crashLabel.text = message;
    crashLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
    crashLabel.numberOfLines = 0;
    [[UIApplication sharedApplication].keyWindow addSubview:crashLabel];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(crashToastTapAction:)];
    crashLabel.userInteractionEnabled = YES;
    [crashLabel addGestureRecognizer:tap];
}
- (void)crashToastTapAction:(UITapGestureRecognizer *)tap {
    UILabel *crashLabel = (UILabel *)tap.view;
    [UIPasteboard generalPasteboard].string = crashLabel.text;
    self.dismissed = YES;
}

@end

3、实例测试:

关键点:SignalHandler不要在debug环境下测试。因为系统的debug会优先去拦截。先在run的切换Release状态,运行安装后,再手动点击启动app去测试。

搞成relese模式.png

实例测试代码如下:

#import "ViewController.h"

@interface ViewController ()

@end

typedef struct Test {
    int a;
    int b;
}Test;

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    
    UIButton *crashExcButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 44, self.view.bounds.size.width, 50)];
    crashExcButton.backgroundColor = [UIColor redColor];
    [crashExcButton setTitle:@"Exception" forState:UIControlStateNormal];
    [crashExcButton addTarget:self action:@selector(crashExcClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:crashExcButton];
    
    UIButton *crashSignalEGVButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 60+44, self.view.bounds.size.width, 50)];
    crashSignalEGVButton.backgroundColor = [UIColor redColor];
    [crashSignalEGVButton setTitle:@"Signal(EGV)" forState:UIControlStateNormal];
    [crashSignalEGVButton addTarget:self action:@selector(crashSignalEGVClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:crashSignalEGVButton];
    
    UIButton *crashSignalBRTButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 120+44, self.view.bounds.size.width, 50)];
    crashSignalBRTButton.backgroundColor = [UIColor redColor];
    [crashSignalBRTButton setTitle:@"Signal(ABRT)" forState:UIControlStateNormal];
    [crashSignalBRTButton addTarget:self action:@selector(crashSignalBRTClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:crashSignalBRTButton];
    
    UIButton *crashSignalBUSButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 180+44, self.view.bounds.size.width, 50)];
    crashSignalBUSButton.backgroundColor = [UIColor redColor];
    [crashSignalBUSButton setTitle:@"Signal(BUS)" forState:UIControlStateNormal];
    [crashSignalBUSButton addTarget:self action:@selector(crashSignalBUSClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:crashSignalBUSButton];
}

- (void)crashSignalEGVClick {
    UIView *view = [[UIView alloc] init];
    [view performSelector:NSSelectorFromString(@"release")];//导致SIGSEGV的错误,一般会导致进程流产
    view.backgroundColor = [UIColor whiteColor];
}

- (void)crashSignalBRTClick {
    Test *pTest = {1,2};
    free(pTest);//导致SIGABRT的错误,因为内存中根本就没有这个空间,哪来的free,就在栈中的对象而已
    pTest->a = 5;
}

- (void)crashSignalBUSClick {
    //SIGBUS,内存地址未对齐
    //EXC_BAD_ACCESS(code=1,address=0x1000dba58)
    char *s = "hello world";
    *s = 'H';
}

- (void)crashExcClick {
    [self performSelector:@selector(aaaa)];
}

@end

你可能感兴趣的:(iOS Crash 捕获处理)