forked from Countly/countly-sdk-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountlyCrashReporter.m
317 lines (258 loc) · 12.5 KB
/
CountlyCrashReporter.m
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// CountlyCrashReporter.m
//
// This code is provided under the MIT License.
//
// Please visit www.count.ly for more information.
#import "CountlyCommon.h"
#import <mach-o/dyld.h>
#include <execinfo.h>
NSString* const kCountlyExceptionUserInfoBacktraceKey = @"kCountlyExceptionUserInfoBacktraceKey";
NSString* const kCountlyCRKeyBinaryImages = @"_binary_images";
NSString* const kCountlyCRKeyOS = @"_os";
NSString* const kCountlyCRKeyOSVersion = @"_os_version";
NSString* const kCountlyCRKeyDevice = @"_device";
NSString* const kCountlyCRKeyArchitecture = @"_architecture";
NSString* const kCountlyCRKeyResolution = @"_resolution";
NSString* const kCountlyCRKeyAppVersion = @"_app_version";
NSString* const kCountlyCRKeyAppBuild = @"_app_build";
NSString* const kCountlyCRKeyBuildUUID = @"_build_uuid";
NSString* const kCountlyCRKeyExecutableName = @"_executable_name";
NSString* const kCountlyCRKeyName = @"_name";
NSString* const kCountlyCRKeyType = @"_type";
NSString* const kCountlyCRKeyError = @"_error";
NSString* const kCountlyCRKeyNonfatal = @"_nonfatal";
NSString* const kCountlyCRKeyRAMCurrent = @"_ram_current";
NSString* const kCountlyCRKeyRAMTotal = @"_ram_total";
NSString* const kCountlyCRKeyDiskCurrent = @"_disk_current";
NSString* const kCountlyCRKeyDiskTotal = @"_disk_total";
NSString* const kCountlyCRKeyBattery = @"_bat";
NSString* const kCountlyCRKeyOrientation = @"_orientation";
NSString* const kCountlyCRKeyOnline = @"_online";
NSString* const kCountlyCRKeyOpenGL = @"_opengl";
NSString* const kCountlyCRKeyRoot = @"_root";
NSString* const kCountlyCRKeyBackground = @"_background";
NSString* const kCountlyCRKeyRun = @"_run";
NSString* const kCountlyCRKeyCustom = @"_custom";
NSString* const kCountlyCRKeyLogs = @"_logs";
NSString* const kCountlyCRKeySignalCode = @"signal_code";
NSString* const kCountlyCRKeyImageLoadAddress = @"la";
NSString* const kCountlyCRKeyImageBuildUUID = @"id";
@interface CountlyCrashReporter ()
@property (nonatomic) NSMutableArray* customCrashLogs;
@property (nonatomic) NSDateFormatter* dateFormatter;
@property (nonatomic) NSString* buildUUID;
@property (nonatomic) NSString* executableName;
@end
@implementation CountlyCrashReporter
#if TARGET_OS_IOS
+ (instancetype)sharedInstance
{
if (!CountlyCommon.sharedInstance.hasStarted)
return nil;
static CountlyCrashReporter *s_sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{s_sharedInstance = self.new;});
return s_sharedInstance;
}
- (instancetype)init
{
if (self = [super init])
{
self.crashSegmentation = nil;
self.customCrashLogs = NSMutableArray.new;
self.dateFormatter = NSDateFormatter.new;
self.dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
}
return self;
}
- (void)startCrashReporting
{
if (!self.isEnabledOnInitialConfig)
return;
if (!CountlyConsentManager.sharedInstance.consentForCrashReporting)
return;
NSSetUncaughtExceptionHandler(&CountlyUncaughtExceptionHandler);
signal(SIGABRT, CountlySignalHandler);
signal(SIGILL, CountlySignalHandler);
signal(SIGSEGV, CountlySignalHandler);
signal(SIGFPE, CountlySignalHandler);
signal(SIGBUS, CountlySignalHandler);
signal(SIGPIPE, CountlySignalHandler);
signal(SIGTRAP, CountlySignalHandler);
}
- (void)stopCrashReporting
{
if (!self.isEnabledOnInitialConfig)
return;
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);
signal(SIGTRAP, SIG_DFL);
self.customCrashLogs = nil;
}
- (void)recordException:(NSException *)exception withStackTrace:(NSArray *)stackTrace isFatal:(BOOL)isFatal
{
if (!CountlyConsentManager.sharedInstance.consentForCrashReporting)
return;
if (stackTrace)
{
NSMutableDictionary* userInfo = [NSMutableDictionary dictionaryWithDictionary:exception.userInfo];
userInfo[kCountlyExceptionUserInfoBacktraceKey] = stackTrace;
exception = [NSException exceptionWithName:exception.name reason:exception.reason userInfo:userInfo];
}
CountlyExceptionHandler(exception, isFatal, false);
}
void CountlyUncaughtExceptionHandler(NSException *exception)
{
CountlyExceptionHandler(exception, true, true);
}
void CountlyExceptionHandler(NSException *exception, bool isFatal, bool isAutoDetect)
{
NSMutableDictionary* crashReport = NSMutableDictionary.dictionary;
const NSInteger kCLYMebibit = 1048576;
NSArray* stackTrace = exception.userInfo[kCountlyExceptionUserInfoBacktraceKey];
if (!stackTrace)
stackTrace = exception.callStackSymbols;
crashReport[kCountlyCRKeyError] = [stackTrace componentsJoinedByString:@"\n"];
crashReport[kCountlyCRKeyBinaryImages] = [CountlyCrashReporter.sharedInstance binaryImagesForStackTrace:stackTrace];
crashReport[kCountlyCRKeyOS] = CountlyDeviceInfo.osName;
crashReport[kCountlyCRKeyOSVersion] = CountlyDeviceInfo.osVersion;
crashReport[kCountlyCRKeyDevice] = CountlyDeviceInfo.device;
crashReport[kCountlyCRKeyArchitecture] = CountlyDeviceInfo.architecture;
crashReport[kCountlyCRKeyResolution] = CountlyDeviceInfo.resolution;
crashReport[kCountlyCRKeyAppVersion] = CountlyDeviceInfo.appVersion;
crashReport[kCountlyCRKeyAppBuild] = CountlyDeviceInfo.appBuild;
crashReport[kCountlyCRKeyBuildUUID] = CountlyCrashReporter.sharedInstance.buildUUID ?: @"";
crashReport[kCountlyCRKeyExecutableName] = CountlyCrashReporter.sharedInstance.executableName ?: @"";
crashReport[kCountlyCRKeyName] = exception.description;
crashReport[kCountlyCRKeyType] = exception.name;
crashReport[kCountlyCRKeyNonfatal] = @(!isFatal);
crashReport[kCountlyCRKeyRAMCurrent] = @((CountlyDeviceInfo.totalRAM - CountlyDeviceInfo.freeRAM) / kCLYMebibit);
crashReport[kCountlyCRKeyRAMTotal] = @(CountlyDeviceInfo.totalRAM / kCLYMebibit);
crashReport[kCountlyCRKeyDiskCurrent] = @((CountlyDeviceInfo.totalDisk - CountlyDeviceInfo.freeDisk) / kCLYMebibit);
crashReport[kCountlyCRKeyDiskTotal] = @(CountlyDeviceInfo.totalDisk / kCLYMebibit);
crashReport[kCountlyCRKeyBattery] = @(CountlyDeviceInfo.batteryLevel);
crashReport[kCountlyCRKeyOrientation] = CountlyDeviceInfo.orientation;
crashReport[kCountlyCRKeyOnline] = @((CountlyDeviceInfo.connectionType) ? 1 : 0 );
crashReport[kCountlyCRKeyOpenGL] = CountlyDeviceInfo.OpenGLESversion;
crashReport[kCountlyCRKeyRoot] = @(CountlyDeviceInfo.isJailbroken);
crashReport[kCountlyCRKeyBackground] = @(CountlyDeviceInfo.isInBackground);
crashReport[kCountlyCRKeyRun] = @(CountlyCommon.sharedInstance.timeSinceLaunch);
NSMutableDictionary* custom = NSMutableDictionary.new;
if (CountlyCrashReporter.sharedInstance.crashSegmentation)
[custom addEntriesFromDictionary:CountlyCrashReporter.sharedInstance.crashSegmentation];
NSMutableDictionary* userInfo = exception.userInfo.mutableCopy;
[userInfo removeObjectForKey:kCountlyExceptionUserInfoBacktraceKey];
[custom addEntriesFromDictionary:userInfo];
if (custom.allKeys.count)
crashReport[kCountlyCRKeyCustom] = custom;
if (CountlyCrashReporter.sharedInstance.customCrashLogs)
crashReport[kCountlyCRKeyLogs] = [CountlyCrashReporter.sharedInstance.customCrashLogs componentsJoinedByString:@"\n"];
if (!isAutoDetect)
{
[CountlyConnectionManager.sharedInstance sendCrashReport:[crashReport cly_JSONify] immediately:NO];
return;
}
[CountlyConnectionManager.sharedInstance sendCrashReport:[crashReport cly_JSONify] immediately:YES];
[CountlyCrashReporter.sharedInstance stopCrashReporting];
}
void CountlySignalHandler(int signalCode)
{
const NSInteger kCountlyStackFramesMax = 128;
void *stack[kCountlyStackFramesMax];
NSInteger frameCount = backtrace(stack, kCountlyStackFramesMax);
char **lines = backtrace_symbols(stack, (int)frameCount);
NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frameCount];
for (NSInteger i = 1; i < frameCount; i++)
[backtrace addObject:[NSString stringWithUTF8String:lines[i]]];
free(lines);
NSDictionary *userInfo = @{kCountlyCRKeySignalCode: @(signalCode), kCountlyExceptionUserInfoBacktraceKey: backtrace};
NSString *reason = [NSString stringWithFormat:@"App terminated by SIG%@", [NSString stringWithUTF8String:sys_signame[signalCode]].uppercaseString];
NSException *e = [NSException exceptionWithName:@"Fatal Signal" reason:reason userInfo:userInfo];
CountlyUncaughtExceptionHandler(e);
}
- (void)log:(NSString *)log
{
if (!CountlyConsentManager.sharedInstance.consentForCrashReporting)
return;
const NSInteger kCountlyCustomCrashLogLengthLimit = 1000;
if (log.length > kCountlyCustomCrashLogLengthLimit)
log = [log substringToIndex:kCountlyCustomCrashLogLengthLimit];
NSString* logWithDateTime = [NSString stringWithFormat:@"<%@> %@",[self.dateFormatter stringFromDate:NSDate.date], log];
[self.customCrashLogs addObject:logWithDateTime];
if (self.customCrashLogs.count > self.crashLogLimit)
[self.customCrashLogs removeObjectAtIndex:0];
}
- (NSDictionary *)binaryImagesForStackTrace:(NSArray *)stackTrace
{
NSMutableSet* binaryImagesInStack = NSMutableSet.new;
for (NSString* line in stackTrace)
{
//NOTE: See _BACKTRACE_FORMAT in https://opensource.apple.com/source/Libc/Libc-498/gen/backtrace.c.auto.html
NSRange rangeOfBinaryImageName = (NSRange){4, 35};
if (line.length >= rangeOfBinaryImageName.location + rangeOfBinaryImageName.length)
{
NSString* binaryImageName = [line substringWithRange:rangeOfBinaryImageName];
binaryImageName = [binaryImageName stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
[binaryImagesInStack addObject:binaryImageName];
}
}
NSMutableDictionary* binaryImages = NSMutableDictionary.new;
uint32_t imageCount = _dyld_image_count();
for (uint32_t i = 0; i < imageCount; i++)
{
const char* imageNameChar = _dyld_get_image_name(i);
if (imageNameChar == NULL)
{
COUNTLY_LOG(@"Image Name can not be retrieved!");
continue;
}
NSString *imageName = [NSString stringWithUTF8String:imageNameChar].lastPathComponent;
if (![binaryImagesInStack containsObject:imageName])
{
//NOTE: Image Name is not in the stack trace, so it will be ignored!
continue;
}
COUNTLY_LOG(@"Image Name is in the stack trace, so it will be used!\n%@", imageName);
const struct mach_header* imageHeader = _dyld_get_image_header(i);
if (imageHeader == NULL)
{
COUNTLY_LOG(@"Image Header can not be retrieved!");
continue;
}
BOOL is64bit = imageHeader->magic == MH_MAGIC_64 || imageHeader->magic == MH_CIGAM_64;
uintptr_t ptr = (uintptr_t)imageHeader + (is64bit ? sizeof(struct mach_header_64) : sizeof(struct mach_header));
NSString* imageUUID = nil;
for (uint32_t j = 0; j < imageHeader->ncmds; j++)
{
const struct segment_command_64* segCmd = (struct segment_command_64*)ptr;
if (segCmd->cmd == LC_UUID)
{
const uint8_t* uuid = ((const struct uuid_command*)segCmd)->uuid;
imageUUID = [NSUUID.alloc initWithUUIDBytes:uuid].UUIDString;
break;
}
ptr += segCmd->cmdsize;
}
if (!imageUUID)
{
COUNTLY_LOG(@"Image UUID can not be retrieved!");
continue;
}
//NOTE: Include app's own build UUID directly in crash report object, as Countly Server needs it for fast lookup
if (imageHeader->filetype == MH_EXECUTE)
{
CountlyCrashReporter.sharedInstance.buildUUID = imageUUID;
CountlyCrashReporter.sharedInstance.executableName = imageName;
}
NSString *imageLoadAddress = [NSString stringWithFormat:@"0x%llX", (uint64_t)imageHeader];
binaryImages[imageName] = @{kCountlyCRKeyImageLoadAddress: imageLoadAddress, kCountlyCRKeyImageBuildUUID: imageUUID};
}
return [NSDictionary dictionaryWithDictionary:binaryImages];
}
#endif
@end