IOS异常处理

来源:互联网 发布:熊孩子 知乎 编辑:程序博客网 时间:2024/05/20 04:11

开发iOS应用,解决Crash问题始终是一个难题。
Crash分为两种,
一种是由EXC_BAD_ACCESS引起的,原因是访问了不属于本进程的内存地址,有可能是访问已被释放的内存;
另一种是未被捕获的Objective-C异常(NSException),导致程序向自身发送了SIGABRT信号而崩溃。
其实对于未捕获的Objective-C异常,我们是有办法将它记录下来的,如果日志记录得当,能够解决绝大部分崩溃的问题。这里对于UI线程与后台线程分别说明

<h1 id="一-系统crash">一. 系统Crash

对于系统Crash而引起的程序异常退出,可以通过NSSetUncaughtExceptionHandler机制捕获,代码:
实现一个用于处理异常的方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<code>voidHandleException(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];
}
 
 
</code>

然后在启动appdidFinishLaunchingWithOptions的时候设置

?
1
<code><code>NSSetUncaughtExceptionHandler (&UncaughtExceptionHandlers);//系统异常捕获</code></code>

当捕获到异常时,就会调用UncaughtExceptionHandlers来出来异常

二. 处理signal

使用Objective-C的异常处理是不能得到signal的,如果要处理它,我们还要利用unix标准的signal机制,注册SIGABRT, SIGBUS, SIGSEGV等信号发生时的处理函数。该函数中我们可以输出栈信息,版本信息等其他一切我们所想要的。
NSSetUncaughtExceptionHandler 用来做异常处理,但功能非常有限.而引起崩溃的大多数原因如:内存访问错误,重复释放等错误就无能为力了,因为这种错误它抛出的是Signal,所以必须要专门做Signal处理
代码如下:
首先定义并实现一个方法如:

?
1
2
3
4
5
6
7
8
9
10
<code><code>#include <execinfo.h>
//Signal处理方法
voidMySignalHandler(intsignal)
{
  NSMutableString *mstr = [[NSMutableString alloc] init];
    [mstr appendString:@"Stack:\n"];
    void* callstack[128];
    inti, frames = backtrace(callstack, 128);
    char** strs = backtrace_symbols(callstack, frames);
    for(i = 0; i <frames; atomically:yes=""documents=""encoding:nsutf8stringencoding=""exceptioninfo=""logpath="[NSString"mstr=""nsstring=""pre=""writetofile:logpath=""></frames;></execinfo.h></code></code>

在启动app的时候设置各种信号的回调处理

?
1
2
3
4
5
6
7
<code><code>//信号量截断
    signal(SIGABRT, MySignalHandler);
    signal(SIGILL, MySignalHandler);
    signal(SIGSEGV, MySignalHandler);
    signal(SIGFPE, MySignalHandler);
    signal(SIGBUS, MySignalHandler);
    signal(SIGPIPE, MySignalHandler);</code></code>

这样当接收到信号的时候,就会调用MySignalHandler方法

三. 实战

首先定义一个UncaughtExceptionHandler类,用来捕获处理所有的崩溃信息

?
1
2
3
4
5
6
7
8
<code><code><code>@interfaceUncaughtExceptionHandler : NSObject
{
    BOOL dismissed;
}
 
+ (void)InstallUncaughtExceptionHandler;
 
@end</code></code></code>
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
<code><code><code>#import<uikit uikit.h="">
#import"UncaughtExceptionHandler.h"
#include <libkern osatomic.h="">
#include <execinfo.h>
 
NSString * constUncaughtExceptionHandlerSignalExceptionName = @"UncaughtExceptionHandlerSignalExceptionName";
NSString * constUncaughtExceptionHandlerSignalKey = @"UncaughtExceptionHandlerSignalKey";
NSString * constUncaughtExceptionHandlerAddressesKey = @"UncaughtExceptionHandlerAddressesKey";
NSString * constUncaughtExceptionHandlerFileKey = @"UncaughtExceptionHandlerFileKey";
 
volatileint32_t UncaughtExceptionCount = 0;
constint32_t UncaughtExceptionMaximum = 10;
constNSInteger UncaughtExceptionHandlerSkipAddressCount = 4;
constNSInteger UncaughtExceptionHandlerReportAddressCount = 5;
 
voidMySignalHandler(intsignal);
 
 
@implementationUncaughtExceptionHandler
 
+(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];
    intframes = backtrace(callstack, 128);//用于获取当前线程的函数调用堆栈,返回实际获取的指针个数
    char**strs = backtrace_symbols(callstack, frames);//从backtrace函数获取的信息转化为一个字符串数组
    inti;
    NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];
    for(i = UncaughtExceptionHandlerSkipAddressCount;
         i < UncaughtExceptionHandlerSkipAddressCount+UncaughtExceptionHandlerReportAddressCount;
         i++)
    {
        [backtrace addObject:[NSString stringWithUTF8String:strs[i]]];
    }
    free(strs);
    returnbacktrace;
}
 
 
- (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
{
    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);
    if([[exception name] isEqual:UncaughtExceptionHandlerSignalExceptionName])
    {
        kill(getpid(), [[[exception userInfo] objectForKey:UncaughtExceptionHandlerSignalKey] intValue]);
    }
    else
    {
        [exception raise];
    }
}   
 
 
//获取应用信息
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);
    returnappInfo;
}
 
 
//NSSetUncaughtExceptionHandler捕获异常的调用方法
//利用 NSSetUncaughtExceptionHandler,当程序异常退出的时候,可以先进行处理,然后做一些自定义的动作
voidUncaughtExceptionHandlers (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处理方法
voidMySignalHandler(intsignal)
{
    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];
 
}
@end</execinfo.h></libkern></uikit></code></code></code>

最后,在didFinishLaunchingWithOptions中调用该函数:

?
1
2
3
4
<code><code><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [UncaughtExceptionHandler InstallUncaughtExceptionHandler];//捕获内存访问错误,处理Signal
    returnYES;
}</code></code></code>

四.测试

当运行时遇到系统错误或内存错误Signal,就会被截获处理并把错误日志保存下来(一般可等下次启动时判断一下,把日志上传),可自己测试一下:

?
1
2
3
4
5
6
7
8
9
<code><code><code>//1.信号量
    intlist[2]={1,2};
    int*p = list;
    free(p);//导致SIGABRT的错误,因为内存中根本就没有这个空间,哪来的free,就在栈中的对象而已
    p[1] = 5;
 
    //2.ios崩溃
    NSArray *array= @[@"tom",@"xxx",@"ooo"];
    [array objectAtIndex:5];</code></code></code>

PS: SignalHandler不要在debug环境下测试。因为系统的debug会优先去拦截。我们要运行一次后,关闭debug状态。应该直接在模拟器上点击我们build上去的app去运行。而UncaughtExceptionHandler可以在调试状态下捕捉。

附录科普:

一些信号说明

1) SIGHUP 本信号在用户终端连接(正常或非正常)结束时发出, 通常是在终端的控制进程结束时, 通知同一session内的各个作业, 这时它们与控制终端不再关联。 登录Linux时,系统会分配给登录用户一个终端(Session)。在这个终端运行的所有程序,包括前台进程组和后台进程组,一般都属于这个 Session。当用户退出Linux登录时,前台进程组和后台有对终端输出的进程将会收到SIGHUP信号。这个信号的默认操作为终止进程,因此前台进 程组和后台有终端输出的进程就会中止。不过可以捕获这个信号,比如wget能捕获SIGHUP信号,并忽略它,这样就算退出了Linux登录, wget也 能继续下载。 此外,对于与终端脱离关系的守护进程,这个信号用于通知它重新读取配置文件。

2) SIGINT 程序终止(interrupt)信号, 在用户键入INTR字符(通常是Ctrl-C)时发出,用于通知前台进程组终止进程。

3) SIGQUIT 和SIGINT类似, 但由QUIT字符(通常是Ctrl-)来控制. 进程在因收到SIGQUIT退出时会产生core文件, 在这个意义上类似于一个程序错误信号。

4) SIGILL 执行了非法指令. 通常是因为可执行文件本身出现错误, 或者试图执行数据段. 堆栈溢出时也有可能产生这个信号。

5) SIGTRAP 由断点指令或其它trap指令产生. 由debugger使用。

6) SIGABRT 调用abort函数生成的信号。

7) SIGBUS 非法地址, 包括内存地址对齐(alignment)出错。比如访问一个四个字长的整数, 但其地址不是4的倍数。它与SIGSEGV的区别在于后者是由于对合法存储地址的非法访问触发的(如访问不属于自己存储空间或只读存储空间)。

8) SIGFPE 在发生致命的算术运算错误时发出. 不仅包括浮点运算错误, 还包括溢出及除数为0等其它所有的算术的错误。

9) SIGKILL 用来立即结束程序的运行. 本信号不能被阻塞、处理和忽略。如果管理员发现某个进程终止不了,可尝试发送这个信号。

10) SIGUSR1 留给用户使用

11) SIGSEGV 试图访问未分配给自己的内存, 或试图往没有写权限的内存地址写数据.

12) SIGUSR2 留给用户使用

13) SIGPIPE 管道破裂。这个信号通常在进程间通信产生,比如采用FIFO(管道)通信的两个进程,读管道没打开或者意外终止就往管道写,写进程会收到SIGPIPE信号。此外用Socket通信的两个进程,写进程在写Socket的时候,读进程已经终止。

14) SIGALRM 时钟定时信号, 计算的是实际的时间或时钟时间. alarm函数使用该信号.

15) SIGTERM 程序结束(terminate)信号, 与SIGKILL不同的是该信号可以被阻塞和处理。通常用来要求程序自己正常退出,shell命令kill缺省产生这个信号。如果进程终止不了,我们才会尝试SIGKILL。

17) SIGCHLD 子进程结束时, 父进程会收到这个信号。 如果父进程没有处理这个信号,也没有等待(wait)子进程,子进程虽然终止,但是还会在内核进程表中占有表项,这时的子进程称为僵尸进程。这种情 况我们应该避免(父进程或者忽略SIGCHILD信号,或者捕捉它,或者wait它派生的子进程,或者父进程先终止,这时子进程的终止自动由init进程 来接管)。

18) SIGCONT 让一个停止(stopped)的进程继续执行. 本信号不能被阻塞. 可以用一个handler来让程序在由stopped状态变为继续执行时完成特定的工作. 例如, 重新显示提示符

19) SIGSTOP 停止(stopped)进程的执行. 注意它和terminate以及interrupt的区别:该进程还未结束, 只是暂停执行. 本信号不能被阻塞, 处理或忽略.

20) SIGTSTP 停止进程的运行, 但该信号可以被处理和忽略. 用户键入SUSP字符时(通常是Ctrl-Z)发出这个信号

21) SIGTTIN 当后台作业要从用户终端读数据时, 该作业中的所有进程会收到SIGTTIN信号. 缺省时这些进程会停止执行.

22) SIGTTOU 类似于SIGTTIN, 但在写终端(或修改终端模式)时收到.

23) SIGURG 有”紧急”数据或out-of-band数据到达socket时产生.

24) SIGXCPU 超过CPU时间资源限制. 这个限制可以由getrlimit/setrlimit来读取/改变。

25) SIGXFSZ 当进程企图扩大文件以至于超过文件大小资源限制。

26) SIGVTALRM 虚拟时钟信号. 类似于SIGALRM, 但是计算的是该进程占用的CPU时间.

27) SIGPROF 类似于SIGALRM/SIGVTALRM, 但包括该进程用的CPU时间以及系统调用的时间.

28) SIGWINCH 窗口大小改变时发出.

29) SIGIO 文件描述符准备就绪, 可以开始进行输入/输出操作.

30) SIGPWR Power failure

31) SIGSYS 非法的系统调用。

关键点注意

在以上列出的信号中,程序不可捕获、阻塞或忽略的信号有:SIGKILL,SIGSTOP 不能恢复至默认动作的信号有:SIGILL,SIGTRAP 默认会导致进程流产的信号有:SIGABRT,SIGBUS,SIGFPE,SIGILL,SIGIOT,SIGQUIT,SIGSEGV,SIGTRAP,SIGXCPU,SIGXFSZ 默认会导致进程退出的信号有: SIGALRM,SIGHUP,SIGINT,SIGKILL,SIGPIPE,SIGPOLL,SIGPROF,SIGSYS,SIGTERM,SIGUSR1,SIGUSR2,SIGVTALRM 默认会导致进程停止的信号有:SIGSTOP,SIGTSTP,SIGTTIN,SIGTTOU 默认进程忽略的信号有:SIGCHLD,SIGPWR,SIGURG,SIGWINCH 此外,SIGIO在SVR4是退出,在4.3BSD中是忽略;SIGCONT在进程挂起时是继续,否则是忽略,不能被阻塞。

Crash Callstack分析 – 进?一步分析

属性 说明 0x8badf00d 在启动、终?止应?用或响应系统事件花费过?长时间,意为“ate bad food”。 0xdeadfa11 ?用户强制退出,意为“dead fall”。(系统?无响应时,?用户按电源开关和HOME) 0xbaaaaaad ?用户按住Home键和?音量键,获取当前内存状态,不代表崩溃 0xbad22222 VoIP应?用因为恢复得太频繁导致crash 0xc00010ff 因为太烫了被干掉,意为“cool off” 0xdead10cc 因为在后台时仍然占据系统资源(?比如通讯录)被干掉,意为“dead lock”