-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
symbolicatecrash
executable file
·1490 lines (1198 loc) · 52.4 KB
/
symbolicatecrash
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl -w
#
# This script parses a crashdump file and attempts to resolve addresses into function names.
#
# It finds symbol-rich binaries by:
# a) searching in Spotlight to find .dSYM files by UUID, then finding the executable from there.
# That finds the symbols for binaries that a developer has built with "DWARF with dSYM File".
# b) searching in various SDK directories.
#
# Copyright (c) 2008-2015 Apple Inc. All Rights Reserved.
#
#
use strict;
use warnings;
use Getopt::Long;
use Cwd qw(realpath);
use List::MoreUtils qw(uniq);
use File::Basename qw(basename);
use File::Glob ':glob';
use File::Find::Rule;
use Env qw(DEVELOPER_DIR);
use Config;
no warnings "portable";
require bigint;
if($Config{ivsize} < 8) {
bigint->import(qw(hex));
}
#############################
# Forward definitons
sub usage();
#############################
# read and parse command line
my $opt_help = 0;
my $opt_verbose = 0;
my $opt_output = "-";
my @opt_dsyms = ();
my $opt_spotlight = 1;
Getopt::Long::Configure ("bundling");
GetOptions ("help|h" => \$opt_help,
"verbose|v" => \$opt_verbose,
"output|o=s" => \$opt_output,
"dsym|d=s" => \@opt_dsyms,
"spotlight!" => \$opt_spotlight)
or die("Error in command line arguments\n");
usage() if $opt_help;
#############################
# have this thing to de-HTMLize Leopard-era plists
my %entity2char = (
# Some normal chars that have special meaning in SGML context
amp => '&', # ampersand
'gt' => '>', # greater than
'lt' => '<', # less than
quot => '"', # double quote
apos => "'", # single quote
);
#############################
if(!defined($DEVELOPER_DIR)) {
die "Error: \"DEVELOPER_DIR\" is not defined";
}
# We will find these tools once we can guess the right SDK
my $otool = undef;
my $atos = undef;
my $symbolstool = undef;
my $size = undef;
#############################
# run the script
symbolicate_log(@ARGV);
exit 0;
#############################
# begin subroutines
sub HELP_MESSAGE() {
usage();
}
sub usage() {
print STDERR <<EOF;
usage:
$0 [--help] [--dsym=DSYM] [--output OUTPUT_FILE] <LOGFILE> [SYMBOL_PATH ...]
<LOGFILE> The crash log to be symbolicated. If "-", then the log will be read from stdin
<SYMBOL_PATH> Additional search paths in which to search for symbol rich binaries
-o | --output <OUTPUT_FILE> The symbolicated log will be written to OUTPUT_FILE. Defaults to "-" (i.e. stdout) if not specified
-d | --dsym <DSYM_BUNDLE> Adds additional dSYM that will be consulted if and when a binary's UUID matches (may be specified more than once)
-h | --help Display this help message
-v | --verbose Enables additional output
EOF
exit 1;
}
##############
sub getToolPath {
my ($toolName, $sdkGuess) = @_;
if (!defined($sdkGuess)) {
$sdkGuess = "macosx";
}
my $toolPath = `'/usr/bin/xcrun' -sdk $sdkGuess -find $toolName`;
if (!defined($toolPath) || $? != 0) {
if ($sdkGuess eq "macosx") {
die "Error: can't find tool named '$toolName' in the $sdkGuess SDK or any fallback SDKs";
} elsif ($sdkGuess eq "iphoneos") {
print STDERR "## Warning: can't find tool named '$toolName' in iOS SDK, falling back to searching the Mac OS X SDK\n";
return getToolPath($toolName, "macosx");
} else {
print STDERR "## Warning: can't find tool named '$toolName' in the $sdkGuess SDK, falling back to searching the iOS SDK\n";
return getToolPath($toolName, "iphoneos");
}
}
chomp $toolPath;
print STDERR "$toolName path is '$toolPath'\n" if $opt_verbose;
return $toolPath;
}
##############
sub getSymbolDirPaths {
my ($hwModel, $osVersion, $osBuild) = @_;
print STDERR "(\$hwModel, \$osVersion, \$osBuild) = ($hwModel, $osVersion, $osBuild)\n" if $opt_verbose;
# We don't match on '$osVersion *' because it matches across device families.
my $versionPattern = "{$hwModel $osVersion ($osBuild),$hwModel $osVersion ($osBuild) *,$osVersion ($osBuild),$osVersion ($osBuild) *,$osVersion,$osBuild,$osBuild *}";
#my $versionPattern = '*';
print STDERR "\$versionPattern = $versionPattern\n" if $opt_verbose;
my @result = grep { -e && -d } bsd_glob('{/System,,~}/Library/Developer/Xcode/*DeviceSupport/'.$versionPattern.'/Symbols*', GLOB_BRACE | GLOB_TILDE);
foreach my $foundPath (`mdfind "kMDItemCFBundleIdentifier == 'com.apple.dt.Xcode' || kMDItemCFBundleIdentifier == 'com.apple.Xcode'"`) {
chomp $foundPath;
my @pathResults = grep { -e && -d && !/Simulator/ } bsd_glob($foundPath.'/Contents/Developer/Platforms/*.platform/DeviceSupport/'.$versionPattern.'/Symbols*/');
push(@result, @pathResults);
}
print STDERR "Symbol directory paths: @result\n" if $opt_verbose;
return @result;
}
sub getSymbolPathAndArchFor_searchpaths {
my ($bin,$path,$build,$uuid,@extra_search_paths) = @_;
my @results;
if (! (defined $bin && length($bin)) && !(defined $path && length($path)) ) {
return undef;
}
for my $item (@extra_search_paths) {
push(@results, File::Find::Rule->file()->name($bin)->in($item));
}
for my $out_path (@results) {
my $arch = archForUUID($out_path, $uuid);
if (defined($arch) && length($arch)) {
return ($out_path, $arch);
}
}
return undef;
}
sub getSymbolPathFor_uuid{
my ($uuid, $uuidsPath) = @_;
$uuid or return undef;
$uuid =~ /(.{4})(.{4})(.{4})(.{4})(.{4})(.{4})(.{8})/;
return Cwd::realpath("$uuidsPath/$1/$2/$3/$4/$5/$6/$7");
}
# Convert a uuid from the canonical format, like "C42A118D-722D-2625-F235-7463535854FD",
# to crash log format like "c42a118d722d2625f2357463535854fd".
sub getCrashLogUUIDForCanonicalUUID{
my ($uuid) = @_;
$uuid = lc($uuid);
$uuid =~ s/\-//g;
return $uuid;
}
# Convert a uuid from the crash log, like "c42a118d722d2625f2357463535854fd",
# to canonical format like "C42A118D-722D-2625-F235-7463535854FD".
sub getCanonicalUUIDForCrashLogUUID{
my ($uuid) = @_;
my $cononical_uuid = uc($uuid); # uuid's in Spotlight database and from other tools are all uppercase
$cononical_uuid =~ /(.{8})(.{4})(.{4})(.{4})(.{12})/;
$cononical_uuid = "$1-$2-$3-$4-$5";
return $cononical_uuid;
}
# Look up a dsym file by UUID in Spotlight, then find the executable from the dsym.
sub getSymbolPathAndArchFor_dsymUuid{
my ($uuid) = @_;
$uuid or return undef;
# Convert a uuid from the crash log, like "c42a118d722d2625f2357463535854fd",
# to canonical format like "C42A118D-722D-2625-F235-7463535854FD".
my $canonical_uuid = getCanonicalUUIDForCrashLogUUID($uuid);
# Do the search in Spotlight.
my $cmd = "mdfind \"com_apple_xcode_dsym_uuids == $canonical_uuid\"";
print STDERR "Running $cmd\n" if $opt_verbose;
my @dsym_paths = ();
my @archive_paths = ();
foreach my $dsymdir (split(/\n/, `$cmd`)) {
$cmd = "mdls -name com_apple_xcode_dsym_paths ".quotemeta($dsymdir);
print STDERR "Running $cmd\n" if $opt_verbose;
my $com_apple_xcode_dsym_paths = `$cmd`;
$com_apple_xcode_dsym_paths =~ s/^com_apple_xcode_dsym_paths\ \= \(\n//;
$com_apple_xcode_dsym_paths =~ s/\n\)//;
my @subpaths = split(/,\n/, $com_apple_xcode_dsym_paths);
map(s/^[[:space:]]*\"//, @subpaths);
map(s/\"[[:space:]]*$//, @subpaths);
push(@dsym_paths, map($dsymdir."/".$_, @subpaths));
if($dsymdir =~ m/\.xcarchive$/) {
push(@archive_paths, $dsymdir);
}
}
@dsym_paths = uniq(@dsym_paths);
if ( @dsym_paths >= 1 ) {
foreach my $dsym_path (@dsym_paths) {
my $arch = archForUUID($dsym_path, $uuid);
if (defined($arch) && length($arch)) {
print STDERR "Found dSYM $dsym_path ($arch)\n" if $opt_verbose;
return ($dsym_path, $arch);
}
}
}
print STDERR "Did not find dsym for $uuid\n" if $opt_verbose;
return undef;
}
#########
sub archForUUID {
my ($path, $uuid) = @_;
if ( ! -f $path ) {
print STDERR "## $path doesn't exist \n" if $opt_verbose;
return undef;
}
my $cmd;
$cmd = "/usr/bin/file '$path'";
print STDERR "Running $cmd\n" if $opt_verbose;
my $file_result = `$cmd`;
my $is_dsym = index($file_result, "dSYM companion file") >= 0;
my $canonical_uuid = getCanonicalUUIDForCrashLogUUID($uuid);
my $architectures = "armv[4-8][tfsk]?|arm64\\S*|i386|x86_64\\S?";
my $arch;
$cmd = "'$symbolstool' -uuid '$path'";
print STDERR "Running $cmd\n" if $opt_verbose;
my $symbols_result = `$cmd`;
if($symbols_result =~ /$canonical_uuid\s+($architectures)/) {
$arch = $1;
print STDERR "## $path contains $uuid ($arch)\n" if $opt_verbose;
} else {
print STDERR "## $path doesn't contain $uuid\n" if $opt_verbose;
return undef;
}
$cmd = "'$otool' -arch $arch -l '$path'";
print STDERR "Running $cmd\n" if $opt_verbose;
my $TEST_uuid = `$cmd`;
if ( $TEST_uuid =~ /uuid ((0x[0-9A-Fa-f]{2}\s+?){16})/ || $TEST_uuid =~ /uuid ([^\s]+)\s/ ) {
my $test = $1;
if ( $test =~ /^0x/ ) {
# old style 0xnn 0xnn 0xnn ... on two lines
$test = join("", split /\s*0x/, $test);
$test =~ s/0x//g; ## remove 0x
$test =~ s/\s//g; ## remove spaces
} else {
# new style XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
$test =~ s/-//g; ## remove -
$test = lc($test);
}
if ( $test eq $uuid ) {
if ( $is_dsym ) {
return $arch;
} else {
## See that it isn't stripped. Even fully stripped apps have one symbol, so ensure that there is more than one.
my ($nlocalsym) = $TEST_uuid =~ /nlocalsym\s+([0-9A-Fa-f]+)/;
my ($nextdefsym) = $TEST_uuid =~ /nextdefsym\s+([0-9A-Fa-f]+)/;
my $totalsym = $nextdefsym + $nlocalsym;
print STDERR "\nNumber of symbols in $path: $nextdefsym + $nlocalsym = $totalsym\n" if $opt_verbose;
return $arch if ( $totalsym > 1 );
print STDERR "## $path appears to be stripped, skipping.\n" if $opt_verbose;
}
} else {
print STDERR "Given UUID $uuid for '$path' is really UUID $test\n" if $opt_verbose;
}
} else {
print STDERR "Can't understand the output from otool ($TEST_uuid -> $cmd)\n";
return undef;
}
return undef;
}
sub getSymbolPathAndArchFor_manualDSYM {
my ($uuid) = @_;
my @dsym_machos = ();
for my $dsym_path (@opt_dsyms) {
if( -d $dsym_path ) {
#test_path is a directory, assume it's a dSYM bundle and find the mach-o file(s) within
push @dsym_machos, bsd_glob("$dsym_path/Contents/Resources/DWARF/*");
next;
}
if ( -f $dsym_path ) {
#test_path is a file, assume it's a dSYM macho file
push @dsym_machos, $dsym_path;
next;
}
}
#Check the uuid's of each of the found files
for my $macho_path (@dsym_machos) {
print STDERR "Checking “$macho_path”\n";
my $arch = archForUUID($macho_path, $uuid);
if (defined($arch) && length($arch)) {
print STDERR "$macho_path matches $uuid ($arch)\n";
return ($macho_path, $arch);
} else {
print STDERR "$macho_path does not match $uuid\n";
}
}
return undef;
}
sub getSymbolPathAndArchFor {
my ($path,$build,$uuid,@extra_search_paths) = @_;
# derive a few more parameters...
my $bin = ($path =~ /^.*?([^\/]+)$/)[0]; # basename
# Look in any of the manually-passed dSYMs
if( @opt_dsyms ) {
print STDERR "-- [$uuid] CHECK (manual)\n" if $opt_verbose;
my ($out_path, $arch) = getSymbolPathAndArchFor_manualDSYM($uuid);
if(defined($out_path) && length($out_path) && defined($arch) && length($arch)) {
print STDERR "-- [$uuid] MATCH (manual): $out_path ($arch)\n" if $opt_verbose;
return ($out_path, $arch);
}
print STDERR "-- [$uuid] NO MATCH (manual)\n\n" if $opt_verbose;
}
# Look for a UUID match in the cache directory
my $uuidsPath = "/Volumes/Build/UUIDToSymbolMap";
if ( -d $uuidsPath ) {
print STDERR "-- [$uuid] CHECK (uuid cache)\n" if $opt_verbose;
my $out_path = getSymbolPathFor_uuid($uuid, $uuidsPath);
if(defined($out_path) && length($out_path)) {
my $arch = archForUUID($out_path, $uuid);
if (defined($arch) && length($arch)) {
print STDERR "-- [$uuid] MATCH (uuid cache): $out_path ($arch)\n" if $opt_verbose;
return ($out_path, $arch);
}
}
print STDERR "-- [$uuid] NO MATCH (uuid cache)\n\n" if $opt_verbose;
}
# Look in the search paths (e.g. the device support directories)
print STDERR "-- [$uuid] CHECK (device support)\n" if $opt_verbose;
for my $func ( \&getSymbolPathAndArchFor_searchpaths, ) {
my ($out_path, $arch) = &$func($bin,$path,$build,$uuid,@extra_search_paths);
if ( defined($out_path) && length($out_path) && defined($arch) && length($arch) ) {
print STDERR "-- [$uuid] MATCH (device support): $out_path ($arch)\n" if $opt_verbose;
return ($out_path, $arch);
}
}
print STDERR "-- [$uuid] NO MATCH (device support)\n\n" if $opt_verbose;
# Ask spotlight
if( $opt_spotlight ) {
print STDERR "-- [$uuid] CHECK (spotlight)\n" if $opt_verbose;
my ($out_path, $arch) = getSymbolPathAndArchFor_dsymUuid($uuid);
if(defined($out_path) && length($out_path) && defined($arch) && length($arch)) {
print STDERR "-- [$uuid] MATCH (spotlight): $out_path ($arch)\n" if $opt_verbose;
return ($out_path, $arch);
}
print STDERR "-- [$uuid] NO MATCH (spotlight)\n\n" if $opt_verbose;
}
print STDERR "-- [$uuid] NO MATCH\n\n" if $opt_verbose;
print STDERR "## Warning: Can't find any unstripped binary that matches version of $path\n" if $opt_verbose;
print STDERR "\n" if $opt_verbose;
return undef;
}
###########################
# crashlog parsing
###########################
# options:
# - regex: don't escape regex metas in name
# - continuous: don't reset pos when done.
# - multiline: expect content to be on many lines following name
# - nocolon: when multiline, the header line does not contain a colon
sub parse_section {
my ($log_ref, $name, %arg ) = @_;
my $content;
$name = quotemeta($name)
unless $arg{regex};
my $colon = ':';
if ($arg{nocolon}) {
$colon = ''
}
# content is thing from name to end of line...
if( $$log_ref =~ m{ ^($name)$colon [[:blank:]]* (.*?) $ }mgx ) {
$content = $2;
$name = $1;
$name =~ s/^\s+//;
# or thing after that line.
if($arg{multiline}) {
$content = $1 if( $$log_ref =~ m{
\G\n # from end of last thing...
(.*?)
(?:\n\s*\n|$) # until next blank line or the end
}sgx );
}
}
pos($$log_ref) = 0
unless $arg{continuous};
return ($name,$content) if wantarray;
return $content;
}
# convenience method over above
sub parse_sections {
my ($log_ref,$re,%arg) = @_;
my ($name,$content);
my %sections = ();
while(1) {
($name,$content) = parse_section($log_ref,$re, regex=>1,continuous=>1,%arg);
last unless defined $content;
$sections{$name} = $content;
}
pos($$log_ref) = 0;
return \%sections;
}
sub parse_threads {
my ($log_ref,%arg) = @_;
my $nocolon = 0;
my $stack_delimeter = 'Thread\s+\d+\s?(Highlighted|Crashed)?'; # Crash reports
if ($arg{event_type}) {
# Spindump reports
if ($arg{event_type} eq "cpu usage" ||
$arg{event_type} eq "wakeups" ||
$arg{event_type} eq "disk writes" ||
$arg{event_type} eq "powerstats") {
# Microstackshots report
$stack_delimeter = 'Powerstats\sfor:.*';
$nocolon = 1;
} else {
# Regular spindump
$stack_delimeter = '\s+Thread\s+\S+(\s+DispatchQueue\s+\S+)?';
$nocolon = 1;
}
}
return parse_sections($log_ref,$stack_delimeter,multiline=>1,nocolon=>$nocolon)
}
sub parse_processes {
my ($log_ref, $is_spindump_report, $event_type) = @_;
if (! $is_spindump_report) {
# Crash Reports only have one process
return ($log_ref);
}
my $process_delimeter;
if ($event_type eq "cpu usage" ||
$event_type eq "wakeups" ||
$event_type eq "disk writes" ||
$event_type eq "powerstats") {
# Microstackshots report
$process_delimeter = '^Powerstats\s+for';
} else {
# Regular spindump
$process_delimeter = '^Process';
}
return \split(/(?=$process_delimeter)/m, $$log_ref);
}
sub parse_images {
my ($log_ref, $report_version, $is_spindump_report) = @_;
my $section = parse_section($log_ref,'Binary Images Description',multiline=>1);
if (!defined($section)) {
$section = parse_section($log_ref,'\\s*Binary\\s*Images',multiline=>1,regex=>1); # new format
}
if (!defined($section)) {
die "Error: Can't find \"Binary Images\" section in log file";
}
my @lines = split /\n/, $section;
scalar @lines or die "Can't find binary images list: $$log_ref" if !$is_spindump_report;
my %images = ();
my ($pat, $app, %captures);
#To get all the architectures for string matching.
my $architectures = "armv[4-8][tfsk]?|arm64\\S*|i386|x86_64\\S?";
# Once Perl 5.10 becomes the default in Mac OS X, named regexp
# capture buffers of the style (?<name>pattern) would make this
# code much more sane.
if(! $is_spindump_report) {
if($report_version == 102 || $report_version == 103) { # Leopard GM
$pat = '
^\s* (\w+) \s* \- \s* (\w+) \s* (?# the range base and extent [1,2] )
(\+)? (?# the application may have a + in front of the name [3] )
(.+) (?# bundle name [4] )
\s+ .+ \(.+\) \s* (?# the versions--generally "??? [???]" )
\<?([[:xdigit:]]{32})?\>? (?# possible UUID [5] )
\s* (\/.*)\s*$ (?# first fwdslash to end we hope is path [6] )
';
%captures = ( 'base' => \$1, 'extent' => \$2, 'plus' => \$3,
'bundlename' => \$4, 'uuid' => \$5, 'path' => \$6);
}
elsif($report_version == 104 || $report_version == 105) { # Kirkwood
# 0x182155000 - 0x1824c6fff CoreFoundation arm64 <f0d21c6db8d83cf3a0c4712fd6e69a8e> /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
$pat = '
^\s* (\w+) \s* \- \s* (\w+) \s* (?# the range base and extent [1,2] )
(\+)? (?# the application may have a + in front of the name [3] )
(.+) (?# bundle name [4] )
\s+ ('.$architectures.') \s+ (?# the image arch [5] )
\<?([[:xdigit:]]{32})?\>? (?# possible UUID [6] )
\s* (\/.*)\s*$ (?# first fwdslash to end we hope is path [7] )
';
%captures = ( 'base' => \$1, 'extent' => \$2, 'plus' => \$3,
'bundlename' => \$4, 'arch' => \$5, 'uuid' => \$6,
'path' => \$7);
}
else {
die "Unsupported crash log version: $report_version";
}
}
else { # Spindump reports
# 0x7fffa5f55000 - 0x7fffa63ddff7 com.apple.CoreFoundation 6.9 (1333.19) <08238AC4-4618-39AC-878B-B1562CD6B235> /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation
$pat = '
^ (?# Beginning of the line )
\s* \*? (?# indent and kernel dot)
(\S+) \s* \- \s* (\S+) (?# the range base and extent [1,2] )
\s+ (.+?) (?# bundle name [3] )
(?: \s+ (\S+) )? (?# optional short version [4] )
(?: \s+ \( (\S+) \) )? (?# optional version [5] )
\s+ \< ( .* ) \> (?# UUID [6] )
(?: \s+ (\/.*) )? (?# optional path [7] )
\s*$ (?# End of the line )
';
%captures = ( 'base' => \$1, 'extent' => \$2, 'bundleid' => \$3,
'shortversion' => \$4, 'version' => \$5, 'uuid' => \$6,
'path' => \$7);
}
for my $line (@lines) {
next if $line =~ /PEF binary:/; # ignore these
$line =~ s/(&(\w+);?)/$entity2char{$2} || $1/eg;
if ($line =~ /$pat/ox) {
# Dereference references
my %image;
while((my $key, my $val) = each(%captures)) {
$image{$key} = ${$captures{$key}} || '';
#print STDERR "image{$key} = $image{$key}\n";
}
if (defined $image{bundleid} && $image{bundleid} eq "???") {
delete $image{bundleid};
}
if (! defined $image{bundlename}) {
# (Only occurs in spindump)
# Match what string frames will use as the binary's identifier
if (defined $image{path} && $image{path} ne '') {
$image{bundlename} = ($image{path} =~ /^.*?([^\/]+)$/)[0]; # basename of path
} elsif (defined $image{bundleid} && $image{bundleid} ne '') {
$image{bundlename} = $image{bundleid};
} else {
$image{bundlename} = "<$image{uuid}>";
}
}
if ($image{extent} eq "???") {
$image{extent} = '';
}
# Spindump uses canonical UUID, but the rest of the code here expects CrashLog style UUIDs
$image{uuid} = getCrashLogUUIDForCanonicalUUID($image{uuid});
# Just take the first instance. That tends to be the app.
my $bundlename = $image{bundlename};
$app = $bundlename if (!defined $app && defined $image{plus} && length $image{plus});
# frameworks and apps (and whatever) may share the same name, so disambiguate
if ( defined($images{$bundlename}) ) {
# follow the chain of hash items until the end
my $nextIDKey = $bundlename;
while ( length($nextIDKey) ) {
last if ( !length($images{$nextIDKey}{nextID}) );
$nextIDKey = $images{$nextIDKey}{nextID};
}
# add ourselves to that chain
$images{$nextIDKey}{nextID} = $image{base};
# and store under the key we just recorded
$bundlename = $bundlename . $image{base};
}
# we are the end of the nextID chain
$image{nextID} = "";
$images{$bundlename} = \%image;
}
}
return (\%images, $app);
}
# if this is actually a partial binary identifier we know about, then
# return the full name. else return undef.
my %_partial_cache = ();
sub resolve_partial_id {
my ($bundle,$images) = @_;
# is this partial? note: also stripping elipsis here
return undef unless $bundle =~ s/^\.\.\.//;
return $_partial_cache{$bundle} if exists $_partial_cache{$bundle};
my $re = qr/\Q$bundle\E$/;
for (keys %$images) {
if( /$re/ ) {
$_partial_cache{$bundle} = $_;
return $_;
}
}
return undef;
}
sub fixup_last_exception_backtrace {
my ($log_ref,$exception,$images) = @_;
my $repl = $exception;
if ($exception =~ m/^.0x/) {
my @lines = split / /, substr($exception, 1, length($exception)-2);
my $counter = 0;
$repl = "";
for my $line (@lines) {
my ($image,$image_base) = findImageByAddress($images, $line);
my $offset = hex($line) - hex($image_base);
my $formattedTrace = sprintf("%-3d %-30s\t0x%08x %s + %d", $counter, $image, hex($line), $image_base, $offset);
$repl .= $formattedTrace . "\n";
++$counter;
}
$log_ref = replace_chunk($log_ref, $exception, $repl);
# may need to do this a second time since there could be First throw call stack too
$log_ref = replace_chunk($log_ref, $exception, $repl);
}
return ($log_ref, $repl);
}
#sub parse_last_exception_backtrace {
# print STDERR "Parsing last exception backtrace\n" if $opt_verbose;
# my ($backtrace,$images, $inHex) = @_;
# my @lines = split /\n/,$backtrace;
#
# my %frames = ();
#
# # these two have to be parallel; we'll lookup by hex, and replace decimal if needed
# my @hexAddr;
# my @replAddr;
#
# for my $line (@lines) {
# # end once we're done with the frames
# last if $line =~ /\)/;
# last if !length($line);
#
# if ($inHex && $line =~ /0x([[:xdigit:]]+)/) {
# push @hexAddr, sprintf("0x%08s", $1);
# push @replAddr, "0x".$1;
# }
# elsif ($line =~ /(\d+)/) {
# push @hexAddr, sprintf("0x%08x", $1);
# push @replAddr, $1;
# }
# }
#
# # we don't have a hint as to the binary assignment of these frames
# # map_addresses will do it for us
# return map_addresses(\@hexAddr,$images,\@replAddr);
#}
# returns an oddly-constructed hash:
# 'string-to-replace' => { bundle=>..., address=>... }
sub parse_backtrace {
my ($backtrace,$images,$decrement,$is_spindump_report) = @_;
my @lines = split /\n/,$backtrace;
my %frames = ();
if ( ! $is_spindump_report ) {
# Crash report
my $is_first = 1;
for my $line (@lines) {
if( $line =~ m{
^\d+ \s+ # stack frame number
(\S.*?) \s+ # bundle [1]
( # description to replace [2]
(0x\w+) \s+ # address [3]
(0x\w+ \s+)? # library address
(?: \+ \s+ (\d+))? # offset [4], optional
.* # remainder of description
) # end of capture
\s* # new line
$ # end of line
}x ) {
my($bundle,$replace,$address,$offset) = ($1,$2,$3,$4);
#print STDERR "Parse_bt: $bundle,$replace,$address\n" if ($opt_verbose);
# disambiguate within our hash of binaries
$bundle = findImageByNameAndAddress($images, $bundle, $address);
# skip unless we know about the image of this frame
next unless
$$images{$bundle} or
$bundle = resolve_partial_id($bundle,$images);
my $raw_address = $address;
if($decrement && !$is_first) {
$address = sprintf("0x%X", (hex($address) & ~1) - 1);
}
$frames{$replace} = {
'address' => $address,
'raw_address' => $raw_address,
'bundle' => $bundle,
};
if (defined $offset) {
$frames{$replace}{offset} = $offset
}
$is_first = 0;
}
# else { print STDERR "unable to parse backtrace line $line\n" }
}
} else {
# Spindump report
my $previousFrame;
my $previousIndentLength;
for my $line (@lines) {
# *138 unix_syscall64 + 675 (systemcalls.c:376,10 in kernel.development + 6211555) [0xffffff80007ec7e3] 1-138
if( $line =~ m{
^ # Start of line
( \s* \*? ) # indent and kernel dot [1]
( \d+ ) \s+ # count [2]
( # Start of string to replace (symbol, binary, address) [3]
( .+? ) # symbol [4]
(?: \s* \+ \s* (\d+) )? # offset from symbol [5], optional
(?: \s+ \( # Start of binary info, entire section optional
(?: ( .*? ) \s+ in \s+ )? # source info [6], optional
(.+?) # Binary name (or UUID, if no name) [7]
(?: \s* \+ \s* (\d+) )? # Offset in binary [8], optional
\) )? # End of binary info, entire section optional
\s* \[ (.+) \] # address [9]
) # End of string to replace
(?: \s+ \(.*\) )? # state [10], optional
(?: \s+ # Start of timeline info, entire section optional
(\d+) # Start time index [11]
(?: \s* \- \s* (\d+))? # End time index [12], optional
)? # End of timeline info, entire section optional
$ # End of line
}x ) {
my($indent,$count,$replace,$symbol,$offsetInSymbol,$sourceInfo,$binaryName,$offsetInBinary,$address,$state,$timeIndexStart,$timeIndexEnd) = ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11);
# print STDERR "Parse_bt $line:\n$indent,$count,$symbol,$offsetInSymbol,$sourceInfo,$binaryName,$offsetInBinary,$address,$timeIndexStart,$timeIndexEnd\n" if ($opt_verbose);
next if defined $sourceInfo; # Don't bother trying to sybolicate frames that already have source info
next unless defined $binaryName;
# disambiguate within our hash of binaries
my $binaryKey = findImageByNameAndAddress($images, $binaryName, $address);
# skip unless we know about the image of this frame
next unless
$$images{$binaryName};
$frames{$replace} = {
'address' => $address, # To be fixed up for non-leaf frames in the next loop
'raw_address' => $address,
'bundle' => $binaryKey,
};
# Fixed up symbolication address the non-leaf previous frame
if (defined $previousFrame && defined $previousIndentLength &&
length $indent > $previousIndentLength) {
$$previousFrame{'address'} = sprintf("0x%X", (hex($$previousFrame{'address'}) & ~1) - 1);
# print STDERR "Updated symbolication address: $$previousFrame{'raw_address'} -> $$previousFrame{'address'}\n";
}
$previousIndentLength = length $indent;
$previousFrame = $frames{$replace};
}
# else { print STDERR "unable to parse backtrace line $line\n" }
}
}
return \%frames;
}
sub slurp_file {
my ($file) = @_;
my $data;
my $fh;
my $readingFromStdin = 0;
local $/ = undef;
# - or "" mean read from stdin, otherwise use the given filename
if($file && $file ne '-') {
open $fh,"<",$file or die "while reading $file, $! : ";
} else {
open $fh,"<&STDIN" or die "while readin STDIN, $! : ";
$readingFromStdin = 1;
}
$data = <$fh>;
# Replace DOS-style line endings
$data =~ s/\r\n/\n/g;
# Replace Mac-style line endings
$data =~ s/\r/\n/g;
# Replace "NO-BREAK SPACE" (these often get inserted when copying from Safari)
# \xC2\xA0 == U+00A0
$data =~ s/\xc2\xa0/ /g;
close $fh or die $!;
return \$data;
}
sub parse_OSVersion {
my ($log_ref) = @_;
my $section = parse_section($log_ref,'OS Version');
if ( $section =~ /\s([0-9\.]+)\s+\(Build (\w+)/ ) {
return ($1, $2)
}
if ( $section =~ /\s([0-9\.]+)\s+\((\w+)/ ) {
return ($1, $2)
}
if ( $section =~ /\s([0-9\.]+)/ ) {
return ($1, "")
}
die "Error: can't parse OS Version string $section";
}
sub parse_HardwareModel {
my ($log_ref) = @_;
my $model = parse_section($log_ref, 'Hardware Model');
if (!defined($model)) {
$model = parse_section($log_ref, 'Hardware model'); # spindump format
}
$model or return undef;
# HACK: replace the comma in model names because bsd_glob can't handle commas (even escaped ones) in
# the {} groups
$model =~ s/,/\?/g;
$model =~ /(\S+)/;
return $1;
}
sub parse_SDKGuess {
my ($log_ref) = @_;
# It turns out that most SDKs are named "lowercased(HardwareModelWithoutNumbers) + os",
# so attempt to form a valid SDK name from that. Any code that uses this must NOT rely
# on this guess being accurate and should fallback to whatever logic makes sense for the situation
my $model = parse_HardwareModel($log_ref);
$model or return undef;
$model =~ /(\D+)\d/;
$1 or return undef;
my $sdk = lc($1) . "os";
if($sdk eq "ipodos" || $sdk eq "ipados") {
$sdk = "iphoneos";
}
if ( $sdk =~ /mac/) {
$sdk = "macosx";
}
return $sdk;
}
sub parse_event_type {
my ($log_ref) = @_;
my $event = parse_section($log_ref,'Event');
return $event;
}
sub parse_steps {
my ($log_ref) = @_;
my $steps = parse_section($log_ref,'Steps');
$steps or return undef;
$steps =~ /(\d+)/;
return $1;
}
sub parse_report_version {
my ($log_ref) = @_;
my $version = parse_section($log_ref,'Report Version');
$version or return undef;
$version =~ /(\d+)/;
return $1;
}
sub findImageByAddress {