美文网首页
捕获崩溃

捕获崩溃

作者: heart_领 | 来源:发表于2018-10-18 10:13 被阅读1次

一、捕获崩溃的方法


捕获崩溃方法.png

二、符号化


未符号化.png
已符号化.png
符号化条件.png

symbolicatecrash路径:
/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash

把dSYM,iOS,symbolicatecrash放入一个文件夹执行以下命令即可符号化
./symbolicatecrash ./.crash ./.dSYM > crash.log
如果报错:
export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
在执行
./symbolicatecrash ./.crash ./.dSYM > crash.log
三、收集崩溃

#import <Foundation/Foundation.h>
@interface UncaughtExceptionHandler : NSObject
{
  BOOL dismissed;
}

+ (void)InstallUncaughtExceptionHandler;

@end

#import "UncaughtExceptionHandler.h"
#import <UIKit/UIKit.h>

#include <libkern/OSAtomic.h>
#include <execinfo.h>

NSString * const UncaughtExceptionHandlerSignalExceptionName = @"UncaughtExceptionHandlerSignalExceptionName";
NSString * const UncaughtExceptionHandlerSignalKey = @"UncaughtExceptionHandlerSignalKey";
NSString * const UncaughtExceptionHandlerAddressesKey = @"UncaughtExceptionHandlerAddressesKey";
NSString * const UncaughtExceptionHandlerFileKey = @"UncaughtExceptionHandlerFileKey";

volatile int32_t UncaughtExceptionCount = 0;
const int32_t UncaughtExceptionMaximum = 10;
const NSInteger UncaughtExceptionHandlerSkipAddressCount = 4;
const NSInteger UncaughtExceptionHandlerReportAddressCount = 5;

void MySignalHandler(int signal);
void MyUncaughtExceptionHandler(NSException * exception);


@implementation UncaughtExceptionHandler

static  UncaughtExceptionHandler *handler = nil;

+ (void) InstallUncaughtExceptionHandler
{
  NSSetUncaughtExceptionHandler(&UncaughtExceptionHandlers); //系统异常捕获(越界)
  //信号量截断
  signal(SIGABRT, MySignalHandler);
  signal(SIGILL, MySignalHandler);
  signal(SIGSEGV, MySignalHandler);
  signal(SIGFPE, MySignalHandler);
  signal(SIGBUS, MySignalHandler);
  signal(SIGPIPE, MySignalHandler);
}

//获取函数堆栈信息
+ (NSArray *)backtrace
{
  
  void* callstack[128];
  int frames = backtrace(callstack, 128);//用于获取当前线程的函数调用堆栈,返回实际获取的指针个数
  char **strs = backtrace_symbols(callstack, frames);//从backtrace函数获取的信息转化为一个字符串数组
  int I;
  NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];
  for (i = UncaughtExceptionHandlerSkipAddressCount;
       i < UncaughtExceptionHandlerSkipAddressCount+UncaughtExceptionHandlerReportAddressCount;
       I++)
  {
      [backtrace addObject:[NSString stringWithUTF8String:strs[i]]];
  }
  free(strs);
  return backtrace;
}

- (void)saveCreash:(NSException *)exception file:(NSString *)file
{
  NSArray *stackArray = [exception callStackSymbols];// 异常的堆栈信息
  NSString *reason = [exception reason];// 出现异常的原因
  NSString *name = [exception name];// 异常名称
  
  //或者直接用代码,输入这个崩溃信息,以便在console中进一步分析错误原因
  NSLog(@"CRASH: %@", exception);
  NSLog(@"Stack Trace: %@", [exception callStackSymbols]);
  
  
  NSString * _libPath  = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:file];
  
  //    NSString *_libPath=[NSHomeDirectory() stringByAppendingPathComponent:file];
  
  if (![[NSFileManager defaultManager] fileExistsAtPath:_libPath]){
      [[NSFileManager defaultManager] createDirectoryAtPath:_libPath withIntermediateDirectories:YES attributes:nil error:nil];
  }
  
  NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
  NSTimeInterval a=[dat timeIntervalSince1970];
  NSString *timeString = [NSString stringWithFormat:@"%f", a];
  
  NSString * savePath = [_libPath stringByAppendingFormat:@"/error%@.log",timeString];
  
  NSString *exceptionInfo = [NSString stringWithFormat:@"Exception reason:%@\nException name:%@\nException stack:%@",name, reason, stackArray];
  
  BOOL sucess = [exceptionInfo writeToFile:savePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  
  NSLog(@"保存崩溃日志 sucess:%d,%@",sucess,savePath);
}

//异常处理方法
- (void)handleException:(NSException *)exception
{
  
  CFRunLoopRef runLoop = CFRunLoopGetCurrent();
  CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop);
  
  UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"程序出现问题啦" message:exception.name delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
  [alertView show];
  alertView = nil;
  
  //当接收到异常处理消息时,让程序开始runloop,防止程序死亡
  while (!dismissed) {
      for (NSString *mode in (__bridge NSArray *)allModes)
      {
          CFRunLoopRunInMode((CFStringRef)mode, 0.001, false);
      }
  }
  //当点击弹出视图的Cancel按钮哦,isDimissed = YES,上边的循环跳出
  CFRelease(allModes);

  
  NSDictionary *userInfo=[exception userInfo];
  [self saveCreash:exception file:[userInfo objectForKey:UncaughtExceptionHandlerFileKey]];
  
  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);
  
  
  [exception raise];

  if ([[exception name] isEqual:UncaughtExceptionHandlerSignalExceptionName])
  {
      kill(getpid(), [[[exception userInfo] objectForKey:UncaughtExceptionHandlerSignalKey] intValue]);
  }
  else
  {
      [exception raise];
  }
}

- (void)alertView:(UIAlertView *)anAlertView clickedButtonAtIndex:(NSInteger)anIndex
{
  //因为这个弹出视图只有一个Cancel按钮,所以直接进行修改isDimsmissed这个变量了
  dismissed = YES;
}

//获取应用信息
NSString* getAppInfo()
{
  NSString *appInfo = [NSString stringWithFormat:@"App : %@ %@(%@)\nDevice : %@\nOS Version : %@ %@\n",
                       [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"],
                       [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"],
                       [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"],
                       [UIDevice currentDevice].model,
                       [UIDevice currentDevice].systemName,
                       [UIDevice currentDevice].systemVersion];
  //                         [UIDevice currentDevice].uniqueIdentifier];
  NSLog(@"Crash!!!! %@", appInfo);
  return appInfo;
}


//NSSetUncaughtExceptionHandler捕获异常的调用方法
//利用 NSSetUncaughtExceptionHandler,当程序异常退出的时候,可以先进行处理,然后做一些自定义的动作
void UncaughtExceptionHandlers(NSException *exception) {
  
  int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);
  if (exceptionCount > UncaughtExceptionMaximum)
  {
      return;
  }
  
  NSArray *callStack = [UncaughtExceptionHandler backtrace];
  NSMutableDictionary *userInfo =
  [NSMutableDictionary dictionaryWithDictionary:[exception userInfo]];
  [userInfo setObject:callStack forKey:UncaughtExceptionHandlerAddressesKey];
  [userInfo setObject:@"OCCrash" forKey:UncaughtExceptionHandlerFileKey];
  
  
  [[[UncaughtExceptionHandler alloc] init]
   performSelectorOnMainThread:@selector(handleException:)
   withObject:
   [NSException
    exceptionWithName:[exception name]
    reason:[exception reason]
    userInfo:userInfo]
   waitUntilDone:YES];
  
}

//Signal处理方法
void MySignalHandler(int signal)
{
  int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);//自动增加一个32位的值
  if (exceptionCount > UncaughtExceptionMaximum)
  {
      return;
  }
  
  NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:signal] forKey:UncaughtExceptionHandlerSignalKey];
  NSArray *callStack = [UncaughtExceptionHandler backtrace];
  [userInfo setObject:callStack forKey:UncaughtExceptionHandlerAddressesKey];
  [userInfo setObject:@"SigCrash" forKey:UncaughtExceptionHandlerFileKey];
  
  [[[UncaughtExceptionHandler alloc] init]
   performSelectorOnMainThread:@selector(handleException:) withObject:
   [NSException exceptionWithName:UncaughtExceptionHandlerSignalExceptionName reason: [NSString stringWithFormat:NSLocalizedString(@"Signal %d was raised.\n"
                                                                                                                                   @"%@", nil),
                                                                                       signal, getAppInfo()] userInfo:userInfo]
   waitUntilDone:YES];
  
}

void MyUncaughtExceptionHandler(NSException * exception) {
  
  // 异常的堆栈信息
  NSArray *stackArray = [exception callStackSymbols];
  
  // 出现异常的原因
  NSString *reason = [exception reason];
  
  // 异常名称
  NSString *name = [exception name];
  
  NSString *exceptionInfo = [NSString stringWithFormat:@"Exception reason:%@\nException name:%@\nException stack:%@",name, reason, stackArray];
  
  NSLog(@"%@", exceptionInfo);
  NSString *logPath=[NSString stringWithFormat:@"%@/Documents/error.log",NSHomeDirectory()];
  [exceptionInfo writeToFile:logPath  atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
@end

相关文章

网友评论

      本文标题:捕获崩溃

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