-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCrashReportSender.m
executable file
·875 lines (707 loc) · 27.9 KB
/
CrashReportSender.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
/*
* Author: Andreas Linde <[email protected]>
* Kent Sutherland
*
* Copyright (c) 2009 Andreas Linde & Kent Sutherland. All rights reserved.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#import <CrashReporter/CrashReporter.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import "CrashReportSender.h"
#define USER_AGENT @"CrashReportSender/1.0"
@interface CrashReportSender ()
- (void)attemptCrashReportSubmission;
- (void)showCrashStatusMessage;
- (void)handleCrashReport;
- (void)_cleanCrashReports;
- (void)_sendCrashReports;
- (NSString *)_crashLogStringForReport:(PLCrashReport *)report;
- (void)_postXML:(NSString*)xml toURL:(NSURL*)url;
- (BOOL)_isSubmissionHostReachable;
- (BOOL)hasPendingCrashReport;
- (void)wentOnline:(NSNotification *)note;
@end
@implementation CrashReportSender
+ (CrashReportSender *)sharedCrashReportSender
{
static CrashReportSender *crashReportSender = nil;
if (crashReportSender == nil) {
crashReportSender = [[CrashReportSender alloc] init];
}
return crashReportSender;
}
- (id) init
{
self = [super init];
if ( self != nil)
{
_serverResult = -1;
_amountCrashes = 0;
_crashIdenticalCurrentVersion = YES;
_crashReportFeedbackActivated = NO;
_delegate = nil;
NSString *testValue = [[NSUserDefaults standardUserDefaults] stringForKey:kCrashReportAnalyzerStarted];
if (testValue == nil)
{
_crashReportAnalyzerStarted = 0;
} else {
_crashReportAnalyzerStarted = [[NSUserDefaults standardUserDefaults] integerForKey:kCrashReportAnalyzerStarted];
}
testValue = nil;
testValue = [[NSUserDefaults standardUserDefaults] stringForKey:kCrashReportActivated];
if (testValue == nil)
{
_crashReportActivated = YES;
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:YES] forKey:kCrashReportActivated];
} else {
_crashReportActivated = [[NSUserDefaults standardUserDefaults] boolForKey:kCrashReportActivated];
}
if (_crashReportActivated)
{
_crashFiles = [[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
_crashesDir = [[NSString stringWithFormat:@"%@", [[paths objectAtIndex:0] stringByAppendingPathComponent:@"/crashes/"]] retain];
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:_crashesDir])
{
NSDictionary *attributes = [NSDictionary dictionaryWithObject: [NSNumber numberWithUnsignedLong: 0755] forKey: NSFilePosixPermissions];
NSError *theError = NULL;
[fm createDirectoryAtPath:_crashesDir withIntermediateDirectories: YES attributes: attributes error: &theError];
}
PLCrashReporter *crashReporter = [PLCrashReporter sharedReporter];
NSError *error;
// Check if we previously crashed
if ([crashReporter hasPendingCrashReport])
[self handleCrashReport];
// Enable the Crash Reporter
if (![crashReporter enableCrashReporterAndReturnError: &error])
NSLog(@"Warning: Could not enable crash reporter: %@", error);
}
}
return self;
}
- (void) dealloc
{
[super dealloc];
[_crashesDir release];
[_crashFiles release];
if (_submitTimer != nil)
{
[_submitTimer invalidate];
[_submitTimer release];
}
}
- (BOOL)hasPendingCrashReport
{
if (_crashReportActivated)
{
NSFileManager *fm = [NSFileManager defaultManager];
if ([_crashFiles count] == 0 && [fm fileExistsAtPath:_crashesDir])
{
NSString *file;
NSError *error = nil;
NSDirectoryEnumerator *dirEnum = [fm enumeratorAtPath: _crashesDir];
while (file = [dirEnum nextObject])
{
NSDictionary *fileAttributes = [fm attributesOfItemAtPath:[_crashesDir stringByAppendingPathComponent:file] error:&error];
if ([[fileAttributes objectForKey:NSFileSize] intValue] > 0)
{
[_crashFiles addObject:file];
}
}
}
if ([_crashFiles count] > 0)
{
_amountCrashes = [_crashFiles count];
return YES;
}
else
return NO;
} else
return NO;
}
- (void)sendCrashReportToURL:(NSURL *)submissionURL delegate:(id <CrashReportSenderDelegate>)delegate activateFeedback:(BOOL)activateFeedback;
{
if ([self hasPendingCrashReport])
{
[_submissionURL autorelease];
_submissionURL = [submissionURL copy];
_crashReportFeedbackActivated = activateFeedback;
_delegate = delegate;
if (_submitTimer == nil) {
_submitTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(attemptCrashReportSubmission) userInfo:nil repeats:NO];
}
}
}
- (void)registerOnline
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(wentOnline:)
name:@"kNetworkReachabilityChangedNotification"
object:nil];
}
- (void)unregisterOnline
{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"kNetworkReachabilityChangedNotification"
object:nil];
}
- (void)wentOnline:(NSNotification *)note
{
[self unregisterOnline];
[self attemptCrashReportSubmission];
}
- (void)attemptCrashReportSubmission
{
_submitTimer = nil;
if (![self _isSubmissionHostReachable]) {
[self registerOnline];
} else if ([self hasPendingCrashReport]) {
[self unregisterOnline];
if (![[NSUserDefaults standardUserDefaults] boolForKey: kAutomaticallySendCrashReports]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"CrashDataFoundTitle", @"Title showing in the alert box when crash report data has been found")
message:NSLocalizedString(@"CrashDataFoundDescription", @"Description explaining that crash data has been found and ask the user if the data might be uplaoded to the developers server")
delegate:self
cancelButtonTitle:NSLocalizedString(@"No", @"")
otherButtonTitles:NSLocalizedString(@"Yes", @""), NSLocalizedString(@"Always", @""), nil];
[alertView setTag: CrashAlertTypeSend];
[alertView show];
[alertView release];
} else {
[self _sendCrashReports];
}
}
}
- (void) showCrashStatusMessage
{
UIAlertView *alertView;
_amountCrashes--;
if (_crashReportFeedbackActivated && _amountCrashes == 0 && _serverResult >= CrashReportStatusAssigned && _crashIdenticalCurrentVersion)
{
// show some feedback to the user about the crash status
switch (_serverResult) {
case CrashReportStatusAssigned:
alertView = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"CrashResponseTitle", @"Title for the alertview giving feedback about the crash")
message: NSLocalizedString(@"CrashResponseNextRelease", @"Full text telling the bug is fixed and will be available in an upcoming release")
delegate: self
cancelButtonTitle: NSLocalizedString(@"Ok", @"")
otherButtonTitles: nil];
break;
case CrashReportStatusSubmitted:
alertView = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"CrashResponseTitle", @"Title for the alertview giving feedback about the crash")
message: NSLocalizedString(@"CrashResponseWaitingApple", @"Full text telling the bug is fixed and the new release is waiting at Apple for approval")
delegate: self
cancelButtonTitle: NSLocalizedString(@"Ok", @"")
otherButtonTitles: nil];
break;
case CrashReportStatusAvailable:
alertView = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"CrashResponseTitle", @"Title for the alertview giving feedback about the crash")
message: NSLocalizedString(@"CrashResponseAvailable", @"Full text telling the bug is fixed and an update is available in the AppStore for download")
delegate: self
cancelButtonTitle: NSLocalizedString(@"Ok", @"")
otherButtonTitles: nil];
break;
default:
alertView = nil;
break;
}
if (alertView != nil)
{
[alertView setTag: CrashAlertTypeFeedback];
[alertView show];
[alertView release];
}
}
}
#pragma mark -
#pragma mark UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if ([alertView tag] == CrashAlertTypeSend)
{
switch (buttonIndex) {
case 0:
[self _cleanCrashReports];
break;
case 1:
[self _sendCrashReports];
break;
case 2:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:kAutomaticallySendCrashReports];
[self _sendCrashReports];
break;
}
}
}
#pragma mark -
#pragma mark NSXMLParser Delegate
#pragma mark NSXMLParser
- (void)parseXMLFileAtURL:(NSString *)url parseError:(NSError **)error
{
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[parser setDelegate:self];
// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
NSError *parseError = [parser parserError];
if (parseError && error) {
*error = parseError;
}
[parser release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if (qName)
{
elementName = qName;
}
if ([elementName isEqualToString:@"result"]) {
_contentOfProperty = [NSMutableString string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if (qName)
{
elementName = qName;
}
if ([elementName isEqualToString: @"result"]) {
if ([_contentOfProperty intValue] > _serverResult) {
_serverResult = [_contentOfProperty intValue];
} else {
CrashReportStatus errorcode = [_contentOfProperty intValue];
NSLog(@"CrashReporter ended in error code: %i", errorcode);
}
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (_contentOfProperty)
{
// If the current element is one whose content we care about, append 'string'
// to the property that holds the content of the current element.
if (string != nil)
{
[_contentOfProperty appendString:string];
}
}
}
#pragma mark -
#pragma mark Private
- (void)_cleanCrashReports
{
NSError *error;
NSFileManager *fm = [NSFileManager defaultManager];
for (int i=0; i < [_crashFiles count]; i++)
{
[fm removeItemAtPath:[_crashesDir stringByAppendingPathComponent:[_crashFiles objectAtIndex:i]] error:&error];
}
[_crashFiles removeAllObjects];
}
- (NSString*) getLastCrashReport
{
NSError *error;
NSString *xml;
//NSString *userid = @"";
//NSString *contact = @"";
//NSString *description = @"";
for (int i=0; i < [_crashFiles count]; i++)
{
NSString *filename = [_crashesDir stringByAppendingPathComponent:[_crashFiles objectAtIndex:i]];
NSData *crashData = [NSData dataWithContentsOfFile:filename];
if ([crashData length] > 0)
{
PLCrashReport *report = [[[PLCrashReport alloc] initWithData:crashData error:&error] autorelease];
NSString *crashLogString = [self _crashLogStringForReport:report];
if ([report.applicationInfo.applicationVersion compare:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]] != NSOrderedSame)
{
_crashIdenticalCurrentVersion = NO;
}
/*
xml = [NSString stringWithFormat:@"<crash><applicationname>%s</applicationname><bundleidentifier>%@</bundleidentifier><systemversion>%@</systemversion><senderversion>%@</senderversion><version>%@</version><userid>%@</userid><contact>%@</contact><description>%@</description><log><![CDATA[%@]]></log></crash>",
[[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleExecutable"] UTF8String],
report.applicationInfo.applicationIdentifier,
[[UIDevice currentDevice] systemVersion],
[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"],
report.applicationInfo.applicationVersion,
userid,
contact,
description,
crashLogString];
*/
xml = crashLogString;
//[self _postXML:xml toURL:_submissionURL];
}
}
[self _cleanCrashReports];
return xml;
}
- (void)_sendCrashReports
{
NSError *error;
NSString *userid = @"";
NSString *contact = @"";
NSString *description = @"";
if (_delegate != nil && [_delegate respondsToSelector:@selector(crashReportUserID)])
{
userid = [_delegate crashReportUserID];
}
if (_delegate != nil && [_delegate respondsToSelector:@selector(crashReportContact)])
{
contact = [_delegate crashReportContact];
}
if (_delegate != nil && [_delegate respondsToSelector:@selector(crashReportDescription)])
{
description = [_delegate crashReportDescription];
}
for (int i=0; i < [_crashFiles count]; i++)
{
NSString *filename = [_crashesDir stringByAppendingPathComponent:[_crashFiles objectAtIndex:i]];
NSData *crashData = [NSData dataWithContentsOfFile:filename];
if ([crashData length] > 0)
{
PLCrashReport *report = [[[PLCrashReport alloc] initWithData:crashData error:&error] autorelease];
NSString *crashLogString = [self _crashLogStringForReport:report];
if ([report.applicationInfo.applicationVersion compare:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]] != NSOrderedSame)
{
_crashIdenticalCurrentVersion = NO;
}
NSString *xml = [NSString stringWithFormat:@"<crash><applicationname>%s</applicationname><bundleidentifier>%@</bundleidentifier><systemversion>%@</systemversion><senderversion>%@</senderversion><version>%@</version><userid>%@</userid><contact>%@</contact><description>%@</description><log><![CDATA[%@]]></log></crash>",
[[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleExecutable"] UTF8String],
report.applicationInfo.applicationIdentifier,
[[UIDevice currentDevice] systemVersion],
[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"],
report.applicationInfo.applicationVersion,
userid,
contact,
description,
crashLogString];
[self _postXML:xml toURL:_submissionURL];
}
}
[self _cleanCrashReports];
}
- (NSString *)_crashLogStringForReport:(PLCrashReport *)report
{
NSMutableString *xmlString = [NSMutableString string];
/* Header */
boolean_t lp64;
/* Map to apple style OS nane */
const char *osName;
switch (report.systemInfo.operatingSystem) {
case PLCrashReportOperatingSystemiPhoneOS:
osName = "iPhone OS";
break;
case PLCrashReportOperatingSystemiPhoneSimulator:
osName = "Mac OS X";
break;
default:
osName = "iPhone OS";
break;
}
/* Map to Apple-style code type */
NSString *codeType;
switch (report.systemInfo.architecture) {
case PLCrashReportArchitectureARM:
codeType = @"ARM (Native)";
lp64 = false;
break;
case PLCrashReportArchitectureX86_32:
codeType = @"X86";
lp64 = false;
break;
case PLCrashReportArchitectureX86_64:
codeType = @"X86-64";
lp64 = true;
break;
case PLCrashReportArchitecturePPC:
codeType = @"PPC";
lp64 = false;
break;
default:
codeType = @"ARM (Native)";
lp64 = false;
break;
}
[xmlString appendString:@"Incident Identifier: [TODO]\n"];
[xmlString appendString:@"CrashReporter Key: [TODO]\n"];
/* Application and process info */
{
NSString *unknownString = @"???";
NSString *processName = unknownString;
NSString *processId = unknownString;
NSString *processPath = unknownString;
NSString *parentProcessName = unknownString;
NSString *parentProcessId = unknownString;
/* Process information was not available in earlier crash report versions */
if (report.hasProcessInfo) {
/* Process Name */
if (report.processInfo.processName != nil)
processName = report.processInfo.processName;
/* PID */
processId = [[NSNumber numberWithUnsignedInteger: report.processInfo.processID] stringValue];
/* Process Path */
if (report.processInfo.processPath != nil)
processPath = report.processInfo.processPath;
/* Parent Process Name */
if (report.processInfo.parentProcessName != nil)
parentProcessName = report.processInfo.parentProcessName;
/* Parent Process ID */
parentProcessId = [[NSNumber numberWithUnsignedInteger: report.processInfo.parentProcessID] stringValue];
}
[xmlString appendFormat: @"Process: %@ [%@]\n", processName, processId];
[xmlString appendFormat: @"Path: %@\n", processPath];
[xmlString appendFormat: @"Identifier: %@\n", report.applicationInfo.applicationIdentifier];
[xmlString appendFormat: @"Version: %@\n", report.applicationInfo.applicationVersion];
[xmlString appendFormat: @"Code Type: %@\n", codeType];
[xmlString appendFormat: @"Parent Process: %@ [%@]\n", parentProcessName, parentProcessId];
}
[xmlString appendString:@"\n"];
/* System info */
[xmlString appendFormat:@"Date/Time: %s\n", [[report.systemInfo.timestamp description] UTF8String]];
[xmlString appendFormat:@"OS Version: %s %s\n", osName, [report.systemInfo.operatingSystemVersion UTF8String]];
[xmlString appendString:@"Report Version: 104\n"];
[xmlString appendString:@"\n"];
/* Exception code */
[xmlString appendFormat:@"Exception Type: %s\n", [report.signalInfo.name UTF8String]];
[xmlString appendFormat:@"Exception Codes: %@ at 0x%" PRIx64 "\n", report.signalInfo.code, report.signalInfo.address];
for (PLCrashReportThreadInfo *thread in report.threads) {
if (thread.crashed) {
[xmlString appendFormat: @"Crashed Thread: %ld\n", (long) thread.threadNumber];
break;
}
}
[xmlString appendString:@"\n"];
if (report.hasExceptionInfo) {
[xmlString appendString:@"Application Specific Information:\n"];
[xmlString appendFormat: @"*** Terminating app due to uncaught exception '%@', reason: '%@'\n",
report.exceptionInfo.exceptionName, report.exceptionInfo.exceptionReason];
[xmlString appendString:@"\n"];
}
/* Threads */
PLCrashReportThreadInfo *crashed_thread = nil;
for (PLCrashReportThreadInfo *thread in report.threads) {
if (thread.crashed) {
[xmlString appendFormat: @"Thread %ld Crashed:\n", (long) thread.threadNumber];
crashed_thread = thread;
} else {
[xmlString appendFormat: @"Thread %ld:\n", (long) thread.threadNumber];
}
for (NSUInteger frame_idx = 0; frame_idx < [thread.stackFrames count]; frame_idx++) {
PLCrashReportStackFrameInfo *frameInfo = [thread.stackFrames objectAtIndex: frame_idx];
PLCrashReportBinaryImageInfo *imageInfo;
/* Base image address containing instrumention pointer, offset of the IP from that base
* address, and the associated image name */
uint64_t baseAddress = 0x0;
uint64_t pcOffset = 0x0;
NSString *imageName = @"\?\?\?";
imageInfo = [report imageForAddress: frameInfo.instructionPointer];
if (imageInfo != nil) {
imageName = [imageInfo.imageName lastPathComponent];
baseAddress = imageInfo.imageBaseAddress;
pcOffset = frameInfo.instructionPointer - imageInfo.imageBaseAddress;
}
[xmlString appendFormat: @"%-4ld%-36s0x%08" PRIx64 " 0x%" PRIx64 " + %" PRId64 "\n",
(long) frame_idx, [imageName UTF8String], frameInfo.instructionPointer, baseAddress, pcOffset];
}
[xmlString appendString: @"\n"];
}
/* Registers */
if (crashed_thread != nil) {
[xmlString appendFormat: @"Thread %ld crashed with %@ Thread State:\n", (long) crashed_thread.threadNumber, codeType];
int regColumn = 1;
for (PLCrashReportRegisterInfo *reg in crashed_thread.registers) {
NSString *reg_fmt;
/* Use 32-bit or 64-bit fixed width format for the register values */
if (lp64)
reg_fmt = @"%6s:\t0x%016" PRIx64 " ";
else
reg_fmt = @"%6s:\t0x%08" PRIx64 " ";
[xmlString appendFormat: reg_fmt, [reg.registerName UTF8String], reg.registerValue];
if (regColumn % 4 == 0)
[xmlString appendString: @"\n"];
regColumn++;
}
if (regColumn % 3 != 0)
[xmlString appendString: @"\n"];
[xmlString appendString: @"\n"];
}
/* Images */
[xmlString appendFormat:@"Binary Images:\n"];
for (PLCrashReportBinaryImageInfo *imageInfo in report.images) {
NSString *uuid;
/* Fetch the UUID if it exists */
if (imageInfo.hasImageUUID)
uuid = imageInfo.imageUUID;
else
uuid = @"???";
NSString *device = @"\?\?\? (\?\?\?)";
#ifdef _ARM_ARCH_6
device = @"armv6";
#endif
#ifdef _ARM_ARCH_7
device = @"armv7";
#endif
/* base_address - terminating_address file_name identifier (<version>) <uuid> file_path */
[xmlString appendFormat:@"0x%" PRIx64 " - 0x%" PRIx64 " %@ %@ <%@> %@\n",
imageInfo.imageBaseAddress,
imageInfo.imageBaseAddress + imageInfo.imageSize,
[imageInfo.imageName lastPathComponent],
device,
uuid,
imageInfo.imageName];
}
return xmlString;
}
- (void)_postXML:(NSString*)xml toURL:(NSURL*)url
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *boundary = @"----FOO";
[request setCachePolicy: NSURLRequestReloadIgnoringLocalCacheData];
[request setValue:USER_AGENT forHTTPHeaderField:@"User-Agent"];
[request setTimeoutInterval: 15];
[request setHTTPMethod:@"POST"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data, boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-type"];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"xmlstring\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[xml dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
_serverResult = CrashReportStatusUnknown;
_statusCode = 200;
//Release when done in the delegate method
_responseData = [[NSMutableData alloc] init];
if (_delegate != nil && [_delegate respondsToSelector:@selector(connectionOpened)])
{
[_delegate connectionOpened];
}
[[NSURLConnection connectionWithRequest:request delegate:self] retain];
}
#pragma mark NSURLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
_statusCode = [(NSHTTPURLResponse *)response statusCode];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[_responseData release];
_responseData = nil;
[connection autorelease];
if (_delegate != nil && [_delegate respondsToSelector:@selector(connectionClosed)])
{
[_delegate connectionClosed];
}
[self showCrashStatusMessage];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (_statusCode >= 200 && _statusCode < 400)
{
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:_responseData];
// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[parser setDelegate:self];
// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
[parser release];
}
[_responseData release];
_responseData = nil;
[connection autorelease];
if (_delegate != nil && [_delegate respondsToSelector:@selector(connectionClosed)])
{
[_delegate connectionClosed];
}
[self showCrashStatusMessage];
}
#pragma mark PLCrashReporter
//
// Called to handle a pending crash report.
//
- (void) handleCrashReport
{
PLCrashReporter *crashReporter = [PLCrashReporter sharedReporter];
NSError *error;
// Try loading the crash report
NSData *crashData = [NSData dataWithData:[crashReporter loadPendingCrashReportDataAndReturnError: &error]];
NSString *cacheFilename = [NSString stringWithFormat: @"%.0f", [NSDate timeIntervalSinceReferenceDate]];
if (crashData == nil) {
NSLog(@"Could not load crash report: %@", error);
goto finish;
} else {
[crashData writeToFile:[_crashesDir stringByAppendingPathComponent: cacheFilename] atomically:YES];
}
// check if the next call ran successfully the last time
if (_crashReportAnalyzerStarted == 0)
{
// mark the start of the routine
_crashReportAnalyzerStarted = 1;
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:_crashReportAnalyzerStarted] forKey:kCrashReportAnalyzerStarted];
// We could send the report from here, but we'll just print out
// some debugging info instead
PLCrashReport *report = [[[PLCrashReport alloc] initWithData: [crashData retain] error: &error] autorelease];
if (report == nil) {
NSLog(@"Could not parse crash report");
goto finish;
}
}
// Purge the report
finish:
// mark the end of the routine
_crashReportAnalyzerStarted = 0;
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:_crashReportAnalyzerStarted] forKey:kCrashReportAnalyzerStarted];
[crashReporter purgePendingCrashReport];
return;
}
#pragma mark Reachability
- (BOOL)_isSubmissionHostReachable
{
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityRef reachabilityRef = nil;
if (![_submissionURL host] || ![[_submissionURL host] length]) {
return NO;
}
reachabilityRef = SCNetworkReachabilityCreateWithName(NULL, [[_submissionURL host] UTF8String]);
if (!reachabilityRef) {
return NO;
}
BOOL gotFlags = SCNetworkReachabilityGetFlags(reachabilityRef, &flags);
if (reachabilityRef != nil)
CFRelease(reachabilityRef);
return gotFlags && flags & kSCNetworkReachabilityFlagsReachable && (flags & kSCNetworkReachabilityFlagsIsWWAN || !(flags & kSCNetworkReachabilityFlagsConnectionRequired));
}
@end