forked from llvm/llvm-project
- Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathcrashlog.py
executable file
·1885 lines (1710 loc) · 71.2 KB
/
crashlog.py
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/env python3
# ----------------------------------------------------------------------
# Be sure to add the python path that points to the LLDB shared library.
#
# To use this in the embedded python interpreter using "lldb":
#
# cd /path/containing/crashlog.py
# lldb
# (lldb) script import crashlog
# "crashlog" command installed, type "crashlog --help" for detailed help
# (lldb) crashlog ~/Library/Logs/DiagnosticReports/a.crash
#
# The benefit of running the crashlog command inside lldb in the
# embedded python interpreter is when the command completes, there
# will be a target with all of the files loaded at the locations
# described in the crash log. Only the files that have stack frames
# in the backtrace will be loaded unless the "--load-all" option
# has been specified. This allows users to explore the program in the
# state it was in right at crash time.
#
# On MacOSX csh, tcsh:
# ( setenv PYTHONPATH /path/to/LLDB.framework/Resources/Python ; ./crashlog.py ~/Library/Logs/DiagnosticReports/a.crash )
#
# On MacOSX sh, bash:
# PYTHONPATH=/path/to/LLDB.framework/Resources/Python ./crashlog.py ~/Library/Logs/DiagnosticReports/a.crash
# ----------------------------------------------------------------------
importabc
importargparse
importconcurrent.futures
importcontextlib
importdatetime
importjson
importos
importplatform
importplistlib
importre
importshlex
importstring
importsubprocess
importsys
importtempfile
importthreading
importtime
importuuid
print_lock=threading.RLock()
try:
# First try for LLDB in case PYTHONPATH is already correctly setup.
importlldb
exceptImportError:
# Ask the command line driver for the path to the lldb module. Copy over
# the environment so that SDKROOT is propagated to xcrun.
command= (
["xcrun", "lldb", "-P"] ifplatform.system() =="Darwin"else ["lldb", "-P"]
)
# Extend the PYTHONPATH if the path exists and isn't already there.
lldb_python_path=subprocess.check_output(command).decode("utf-8").strip()
ifos.path.exists(lldb_python_path) andnotsys.path.__contains__(lldb_python_path):
sys.path.append(lldb_python_path)
# Try importing LLDB again.
try:
importlldb
exceptImportError:
print(
"error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly"
)
sys.exit(1)
fromlldb.utilsimportsymbolication
fromlldb.plugins.scripted_processimportINTEL64_GPR, ARM64_GPR
defread_plist(s):
ifsys.version_info.major==3:
returnplistlib.loads(s)
else:
returnplistlib.readPlistFromString(s)
classCrashLog(symbolication.Symbolicator):
classThread:
"""Class that represents a thread in a darwin crash log"""
def__init__(self, index, app_specific_backtrace, arch):
self.index=index
self.id=index
self.images=list()
self.frames=list()
self.idents=list()
self.registers=dict()
self.reason=None
self.name=None
self.queue=None
self.crashed=False
self.app_specific_backtrace=app_specific_backtrace
self.arch=arch
defdump_registers(self, prefix=""):
registers_info=None
sorted_registers= {}
defsort_dict(d):
sorted_keys=list(d.keys())
sorted_keys.sort()
return {k: d[k] forkinsorted_keys}
ifself.arch:
if"x86_64"==self.arch:
registers_info=INTEL64_GPR
elif"arm64"inself.arch:
registers_info=ARM64_GPR
else:
print("unknown target architecture: %s"%self.arch)
return
# Add registers available in the register information dictionary.
forreg_infoinregisters_info:
reg_name=None
ifreg_info["name"] inself.registers:
reg_name=reg_info["name"]
elif (
"generic"inreg_infoandreg_info["generic"] inself.registers
):
reg_name=reg_info["generic"]
else:
# Skip register that are present in the register information dictionary but not present in the report.
continue
reg_val=self.registers[reg_name]
sorted_registers[reg_name] =reg_val
unknown_parsed_registers= {}
forreg_nameinself.registers:
ifreg_namenotinsorted_registers:
unknown_parsed_registers[reg_name] =self.registers[reg_name]
sorted_registers.update(sort_dict(unknown_parsed_registers))
else:
sorted_registers=sort_dict(self.registers)
forreg_name, reg_valinsorted_registers.items():
print("%s %-8s = %#16.16x"% (prefix, reg_name, reg_val))
defdump(self, prefix=""):
ifself.app_specific_backtrace:
print(
"%Application Specific Backtrace[%u] %s"
% (prefix, self.index, self.reason)
)
else:
print("%sThread[%u] %s"% (prefix, self.index, self.reason))
ifself.frames:
print("%s Frames:"% (prefix))
forframeinself.frames:
frame.dump(prefix+" ")
ifself.registers:
print("%s Registers:"% (prefix))
self.dump_registers(prefix)
defdump_symbolicated(self, crash_log, options):
this_thread_crashed=self.app_specific_backtrace
ifnotthis_thread_crashed:
this_thread_crashed=self.did_crash()
ifoptions.crashed_onlyandnotthis_thread_crashed:
return
print("%s"%self)
display_frame_idx=-1
forframe_idx, frameinenumerate(self.frames):
disassemble= (
this_thread_crashedoroptions.disassemble_all_threads
) andframe_idx<options.disassemble_depth
# Except for the zeroth frame, we should subtract 1 from every
# frame pc to get the previous line entry.
pc=frame.pc&crash_log.addr_mask
pc=pcifframe_idx==0orpc==0elsepc-1
symbolicated_frame_addresses=crash_log.symbolicate(
pc, options.verbose
)
ifsymbolicated_frame_addresses:
symbolicated_frame_address_idx=0
forsymbolicated_frame_addressinsymbolicated_frame_addresses:
display_frame_idx+=1
print("[%3u] %s"% (frame_idx, symbolicated_frame_address))
if (
(options.source_allorself.did_crash())
anddisplay_frame_idx<options.source_frames
andoptions.source_context
):
source_context=options.source_context
line_entry= (
symbolicated_frame_address.get_symbol_context().line_entry
)
ifline_entry.IsValid():
strm=lldb.SBStream()
ifline_entry:
crash_log.debugger.GetSourceManager().DisplaySourceLinesWithLineNumbers(
line_entry.file,
line_entry.line,
source_context,
source_context,
"->",
strm,
)
source_text=strm.GetData()
ifsource_text:
# Indent the source a bit
indent_str=" "
join_str="\n"+indent_str
print(
"%s%s"
% (
indent_str,
join_str.join(source_text.split("\n")),
)
)
ifsymbolicated_frame_address_idx==0:
ifdisassemble:
instructions= (
symbolicated_frame_address.get_instructions()
)
ifinstructions:
print()
symbolication.disassemble_instructions(
crash_log.get_target(),
instructions,
frame.pc,
options.disassemble_before,
options.disassemble_after,
frame.index>0,
)
print()
symbolicated_frame_address_idx+=1
else:
print(frame)
ifself.registers:
print()
self.dump_registers()
elifself.crashed:
print()
print("No thread state (register information) available")
defadd_ident(self, ident):
ifidentnotinself.idents:
self.idents.append(ident)
defdid_crash(self):
returnself.crashed
def__str__(self):
ifself.app_specific_backtrace:
s="Application Specific Backtrace[%u]"%self.index
else:
s="Thread[%u]"%self.index
ifself.reason:
s+=" %s"%self.reason
returns
classFrame:
"""Class that represents a stack frame in a thread in a darwin crash log"""
def__init__(self, index, pc, description):
self.pc=pc
self.description=description
self.index=index
def__str__(self):
ifself.description:
return"[%3u] 0x%16.16x %s"% (self.index, self.pc, self.description)
else:
return"[%3u] 0x%16.16x"% (self.index, self.pc)
defdump(self, prefix):
print("%s%s"% (prefix, str(self)))
classDarwinImage(symbolication.Image):
"""Class that represents a binary images in a darwin crash log"""
dsymForUUIDBinary="/usr/local/bin/dsymForUUID"
if"LLDB_APPLE_DSYMFORUUID_EXECUTABLE"inos.environ:
dsymForUUIDBinary=os.environ["LLDB_APPLE_DSYMFORUUID_EXECUTABLE"]
elifnotos.path.exists(dsymForUUIDBinary):
try:
dsymForUUIDBinary= (
subprocess.check_output("which dsymForUUID", shell=True)
.decode("utf-8")
.rstrip("\n")
)
except:
dsymForUUIDBinary=""
dwarfdump_uuid_regex=re.compile(r"UUID: ([-0-9a-fA-F]+) \(([^\(]+)\) .*")
def__init__(
self, text_addr_lo, text_addr_hi, identifier, version, uuid, path, verbose
):
symbolication.Image.__init__(self, path, uuid)
self.add_section(
symbolication.Section(text_addr_lo, text_addr_hi, "__TEXT")
)
self.identifier=identifier
self.version=version
self.verbose=verbose
defshow_symbol_progress(self):
"""
Hide progress output and errors from system frameworks as they are plentiful.
"""
ifself.verbose:
returnTrue
returnnot (
self.path.startswith("/System/Library/")
orself.path.startswith("/usr/lib/")
)
deffind_matching_slice(self):
dwarfdump_cmd_output=subprocess.check_output(
'dwarfdump --uuid "%s"'%self.path, shell=True
).decode("utf-8")
self_uuid=self.get_uuid()
forlineindwarfdump_cmd_output.splitlines():
match=self.dwarfdump_uuid_regex.search(line)
ifmatch:
dwarf_uuid_str=match.group(1)
dwarf_uuid=uuid.UUID(dwarf_uuid_str)
ifself_uuid==dwarf_uuid:
self.resolved_path=self.path
self.arch=match.group(2)
returnTrue
ifnotself.resolved_path:
self.unavailable=True
ifself.show_symbol_progress():
print(
(
"error\n error: unable to locate '%s' with UUID %s"
% (self.path, self.get_normalized_uuid_string())
)
)
returnFalse
deflocate_module_and_debug_symbols(self):
# Don't load a module twice...
ifself.resolved:
returnTrue
# Mark this as resolved so we don't keep trying
self.resolved=True
uuid_str=self.get_normalized_uuid_string()
ifself.show_symbol_progress():
withprint_lock:
print("Getting symbols for %s %s..."% (uuid_str, self.path))
# Keep track of unresolved source paths.
unavailable_source_paths=set()
ifos.path.exists(self.dsymForUUIDBinary):
dsym_for_uuid_command= (
"{} --copyExecutable --ignoreNegativeCache {}".format(
self.dsymForUUIDBinary, uuid_str
)
)
s=subprocess.check_output(dsym_for_uuid_command, shell=True)
ifs:
try:
plist_root=read_plist(s)
except:
withprint_lock:
print(
(
"Got exception: ",
sys.exc_info()[1],
" handling dsymForUUID output: \n",
s,
)
)
raise
ifplist_root:
plist=plist_root[uuid_str]
ifplist:
if"DBGArchitecture"inplist:
self.arch=plist["DBGArchitecture"]
if"DBGDSYMPath"inplist:
self.symfile=os.path.realpath(plist["DBGDSYMPath"])
if"DBGSymbolRichExecutable"inplist:
self.path=os.path.expanduser(
plist["DBGSymbolRichExecutable"]
)
self.resolved_path=self.path
if"DBGSourcePathRemapping"inplist:
path_remapping=plist["DBGSourcePathRemapping"]
for_, valueinpath_remapping.items():
source_path=os.path.expanduser(value)
ifnotos.path.exists(source_path):
unavailable_source_paths.add(source_path)
ifnotself.resolved_pathandos.path.exists(self.path):
ifnotself.find_matching_slice():
returnFalse
ifnotself.resolved_pathandnotos.path.exists(self.path):
try:
mdfind_results= (
subprocess.check_output(
[
"/usr/bin/mdfind",
"com_apple_xcode_dsym_uuids == %s"%uuid_str,
]
)
.decode("utf-8")
.splitlines()
)
found_matching_slice=False
fordsyminmdfind_results:
dwarf_dir=os.path.join(dsym, "Contents/Resources/DWARF")
ifnotos.path.exists(dwarf_dir):
# Not a dSYM bundle, probably an Xcode archive.
continue
withprint_lock:
print('falling back to binary inside "%s"'%dsym)
self.symfile=dsym
# Look for the executable next to the dSYM bundle.
parent_dir=os.path.dirname(dsym)
executables= []
forroot, _, filesinos.walk(parent_dir):
forfileinfiles:
abs_path=os.path.join(root, file)
ifos.path.isfile(abs_path) andos.access(
abs_path, os.X_OK
):
executables.append(abs_path)
forbinaryinexecutables:
basename=os.path.basename(binary)
ifbasename==self.identifier:
self.path=binary
found_matching_slice=True
break
iffound_matching_slice:
break
except:
pass
if (self.resolved_pathandos.path.exists(self.resolved_path)) or (
self.pathandos.path.exists(self.path)
):
withprint_lock:
print("Resolved symbols for %s %s..."% (uuid_str, self.path))
iflen(unavailable_source_paths):
forsource_pathinunavailable_source_paths:
print(
"Could not access remapped source path for %s %s"
% (uuid_str, source_path)
)
returnTrue
else:
self.unavailable=True
returnFalse
def__init__(self, debugger, path, verbose):
"""CrashLog constructor that take a path to a darwin crash log file"""
symbolication.Symbolicator.__init__(self, debugger)
self.path=os.path.expanduser(path)
self.info_lines=list()
self.system_profile=list()
self.threads=list()
self.backtraces=list() # For application specific backtraces
self.idents= (
list()
) # A list of the required identifiers for doing all stack backtraces
self.errors=list()
self.exception=dict()
self.crashed_thread_idx=-1
self.version=-1
self.target=None
self.verbose=verbose
self.process_id=None
self.process_identifier=None
self.process_path=None
self.process_arch=None
defdump(self):
print("Crash Log File: %s"% (self.path))
ifself.backtraces:
print("\nApplication Specific Backtraces:")
forthreadinself.backtraces:
thread.dump(" ")
print("\nThreads:")
forthreadinself.threads:
thread.dump(" ")
print("\nImages:")
forimageinself.images:
image.dump(" ")
defset_main_image(self, identifier):
fori, imageinenumerate(self.images):
ifimage.identifier==identifier:
self.images.insert(0, self.images.pop(i))
break
deffind_image_with_identifier(self, identifier):
forimageinself.images:
ifimage.identifier==identifier:
returnimage
regex_text=r"^.*\.%s$"% (re.escape(identifier))
regex=re.compile(regex_text)
forimageinself.images:
ifregex.match(image.identifier):
returnimage
returnNone
defcreate_target(self):
ifself.targetisNone:
self.target=symbolication.Symbolicator.create_target(self)
ifself.target:
returnself.target
# We weren't able to open the main executable as, but we can still
# symbolicate
print("crashlog.create_target()...2")
ifself.idents:
foridentinself.idents:
image=self.find_image_with_identifier(ident)
ifimage:
self.target=image.create_target(self.debugger)
ifself.target:
returnself.target# success
print("crashlog.create_target()...3")
forimageinself.images:
self.target=image.create_target(self.debugger)
ifself.target:
returnself.target# success
print("crashlog.create_target()...4")
print("error: Unable to locate any executables from the crash log.")
print(" Try loading the executable into lldb before running crashlog")
print(
" and/or make sure the .dSYM bundles can be found by Spotlight."
)
returnself.target
defget_target(self):
returnself.target
defload_images(self, options, loaded_images=None):
ifnotloaded_images:
loaded_images= []
images_to_load=self.images
ifoptions.load_all_images:
forimageinself.images:
image.resolve=True
elifoptions.crashed_only:
images_to_load= []
forthreadinself.threads:
ifthread.did_crash() orthread.app_specific_backtrace:
foridentinthread.idents:
forimageinself.find_images_with_identifier(ident):
image.resolve=True
images_to_load.append(image)
futures= []
withtempfile.TemporaryDirectory() asobj_dir:
defadd_module(image, target, obj_dir):
returnimage, image.add_module(target, obj_dir)
max_worker=None
ifoptions.no_parallel_image_loading:
max_worker=1
withconcurrent.futures.ThreadPoolExecutor(max_worker) asexecutor:
forimageinimages_to_load:
ifimagenotinloaded_images:
ifimage.uuid==uuid.UUID(int=0):
continue
futures.append(
executor.submit(
add_module,
image=image,
target=self.target,
obj_dir=obj_dir,
)
)
forfutureinconcurrent.futures.as_completed(futures):
image, err=future.result()
iferr:
print(err)
else:
loaded_images.append(image)
classCrashLogFormatException(Exception):
pass
classCrashLogParseException(Exception):
pass
classInteractiveCrashLogException(Exception):
pass
classCrashLogParser:
@staticmethod
defcreate(debugger, path, options):
data=JSONCrashLogParser.is_valid_json(path)
ifdata:
parser=JSONCrashLogParser(debugger, path, options)
parser.data=data
returnparser
else:
returnTextCrashLogParser(debugger, path, options)
def__init__(self, debugger, path, options):
self.path=os.path.expanduser(path)
self.options=options
self.crashlog=CrashLog(debugger, self.path, self.options.verbose)
@abc.abstractmethod
defparse(self):
pass
classJSONCrashLogParser(CrashLogParser):
@staticmethod
defis_valid_json(path):
defparse_json(buffer):
try:
returnjson.loads(buffer)
except:
# The first line can contain meta data. Try stripping it and
# try again.
head, _, tail=buffer.partition("\n")
returnjson.loads(tail)
withopen(path, "r", encoding="utf-8") asf:
buffer=f.read()
try:
returnparse_json(buffer)
except:
returnNone
def__init__(self, debugger, path, options):
super().__init__(debugger, path, options)
defparse(self):
try:
self.parse_process_info(self.data)
self.parse_images(self.data["usedImages"])
self.parse_main_image(self.data)
self.parse_threads(self.data["threads"])
if"asi"inself.data:
self.crashlog.asi=self.data["asi"]
# FIXME: With the current design, we can either show the ASI or Last
# Exception Backtrace, not both. Is there a situation where we would
# like to show both ?
if"asiBacktraces"inself.data:
self.parse_app_specific_backtraces(self.data["asiBacktraces"])
if"lastExceptionBacktrace"inself.data:
self.parse_last_exception_backtraces(
self.data["lastExceptionBacktrace"]
)
self.parse_errors(self.data)
thread=self.crashlog.threads[self.crashlog.crashed_thread_idx]
reason=self.parse_crash_reason(self.data["exception"])
ifthread.reason:
thread.reason="{} {}".format(thread.reason, reason)
else:
thread.reason=reason
except (KeyError, ValueError, TypeError) ase:
raiseCrashLogParseException(
"Failed to parse JSON crashlog: {}: {}".format(type(e).__name__, e)
)
returnself.crashlog
defget_used_image(self, idx):
returnself.data["usedImages"][idx]
defparse_process_info(self, json_data):
self.crashlog.process_id=json_data["pid"]
self.crashlog.process_identifier=json_data["procName"]
if"procPath"injson_data:
self.crashlog.process_path=json_data["procPath"]
defparse_crash_reason(self, json_exception):
self.crashlog.exception=json_exception
exception_type=json_exception["type"]
exception_signal=" "
if"signal"injson_exception:
exception_signal+="({})".format(json_exception["signal"])
if"codes"injson_exception:
exception_extra=" ({})".format(json_exception["codes"])
elif"subtype"injson_exception:
exception_extra=" ({})".format(json_exception["subtype"])
else:
exception_extra=""
return"{}{}{}".format(exception_type, exception_signal, exception_extra)
defparse_images(self, json_images):
forjson_imageinjson_images:
img_uuid=uuid.UUID(json_image["uuid"])
low=int(json_image["base"])
high=low+int(json_image["size"]) if"size"injson_imageelselow
name=json_image["name"] if"name"injson_imageelse""
path=json_image["path"] if"path"injson_imageelse""
version=""
darwin_image=self.crashlog.DarwinImage(
low, high, name, version, img_uuid, path, self.options.verbose
)
if"arch"injson_image:
darwin_image.arch=json_image["arch"]
ifpath==self.crashlog.process_path:
self.crashlog.process_arch=darwin_image.arch
self.crashlog.images.append(darwin_image)
defparse_main_image(self, json_data):
if"procName"injson_data:
proc_name=json_data["procName"]
self.crashlog.set_main_image(proc_name)
defparse_frames(self, thread, json_frames):
idx=0
forjson_frameinjson_frames:
image_id=int(json_frame["imageIndex"])
json_image=self.get_used_image(image_id)
ident=json_image["name"] if"name"injson_imageelse""
thread.add_ident(ident)
ifidentnotinself.crashlog.idents:
self.crashlog.idents.append(ident)
frame_offset=int(json_frame["imageOffset"])
image_addr=self.get_used_image(image_id)["base"]
pc=image_addr+frame_offset
if"symbol"injson_frame:
symbol=json_frame["symbol"]
location=0
if"symbolLocation"injson_frameandjson_frame["symbolLocation"]:
location=int(json_frame["symbolLocation"])
image=self.crashlog.images[image_id]
image.symbols[symbol] = {
"name": symbol,
"type": "code",
"address": frame_offset-location,
}
thread.frames.append(self.crashlog.Frame(idx, pc, frame_offset))
# on arm64 systems, if it jump through a null function pointer,
# we end up at address 0 and the crash reporter unwinder
# misses the frame that actually faulted.
# But $lr can tell us where the last BL/BLR instruction used
# was at, so insert that address as the caller stack frame.
ifidx==0andpc==0and"lr"inthread.registers:
pc=thread.registers["lr"]
forimageinself.data["usedImages"]:
text_lo=image["base"]
text_hi=text_lo+image["size"]
iftext_lo<=pc<text_hi:
idx+=1
frame_offset=pc-text_lo
thread.frames.append(self.crashlog.Frame(idx, pc, frame_offset))
break
idx+=1
defparse_threads(self, json_threads):
idx=0
forjson_threadinjson_threads:
thread=self.crashlog.Thread(idx, False, self.crashlog.process_arch)
if"name"injson_thread:
thread.name=json_thread["name"]
thread.reason=json_thread["name"]
if"id"injson_thread:
thread.id=int(json_thread["id"])
ifjson_thread.get("triggered", False):
self.crashlog.crashed_thread_idx=idx
thread.crashed=True
if"threadState"injson_thread:
thread.registers=self.parse_thread_registers(
json_thread["threadState"]
)
if"queue"injson_thread:
thread.queue=json_thread.get("queue")
self.parse_frames(thread, json_thread.get("frames", []))
self.crashlog.threads.append(thread)
idx+=1
defparse_asi_backtrace(self, thread, bt):
forlineinbt.split("\n"):
frame_match=TextCrashLogParser.frame_regex.search(line)
ifnotframe_match:
print("error: can't parse application specific backtrace.")
returnFalse
frame_id= (
frame_img_name
) = (
frame_addr
) = (
frame_symbol
) =frame_offset=frame_file=frame_line=frame_column=None
iflen(frame_match.groups()) ==3:
# Get the image UUID from the frame image name.
(frame_id, frame_img_name, frame_addr) =frame_match.groups()
eliflen(frame_match.groups()) ==5:
(
frame_id,
frame_img_name,
frame_addr,
frame_symbol,
frame_offset,
) =frame_match.groups()
eliflen(frame_match.groups()) ==7:
(
frame_id,
frame_img_name,
frame_addr,
frame_symbol,
frame_offset,
frame_file,
frame_line,
) =frame_match.groups()
eliflen(frame_match.groups()) ==8:
(
frame_id,
frame_img_name,
frame_addr,
frame_symbol,
frame_offset,
frame_file,
frame_line,
frame_column,
) =frame_match.groups()
thread.add_ident(frame_img_name)
ifframe_img_namenotinself.crashlog.idents:
self.crashlog.idents.append(frame_img_name)
description=""
ifframe_img_nameandframe_addrandframe_symbol:
description=frame_symbol
frame_offset_value=0
ifframe_offset:
description+=" + "+frame_offset
frame_offset_value=int(frame_offset, 0)
forimageinself.crashlog.images:
ifimage.identifier==frame_img_name:
image.symbols[frame_symbol] = {
"name": frame_symbol,
"type": "code",
"address": int(frame_addr, 0) -frame_offset_value,
}
thread.frames.append(
self.crashlog.Frame(int(frame_id), int(frame_addr, 0), description)
)
returnTrue
defparse_app_specific_backtraces(self, json_app_specific_bts):
thread=self.crashlog.Thread(
len(self.crashlog.threads), True, self.crashlog.process_arch
)
thread.name="Application Specific Backtrace"
ifself.parse_asi_backtrace(thread, json_app_specific_bts[0]):
self.crashlog.threads.append(thread)
else:
print("error: Couldn't parse Application Specific Backtrace.")
defparse_last_exception_backtraces(self, json_last_exc_bts):
thread=self.crashlog.Thread(
len(self.crashlog.threads), True, self.crashlog.process_arch
)
thread.name="Last Exception Backtrace"
self.parse_frames(thread, json_last_exc_bts)
self.crashlog.threads.append(thread)
defparse_thread_registers(self, json_thread_state, prefix=None):
registers=dict()
forkey, stateinjson_thread_state.items():
ifkey=="rosetta":
registers.update(self.parse_thread_registers(state))
continue
ifkey=="x":
gpr_dict= {str(idx): regforidx, reginenumerate(state)}
registers.update(self.parse_thread_registers(gpr_dict, key))
continue
ifkey=="flavor":
ifnotself.crashlog.process_arch:
ifstate=="ARM_THREAD_STATE64":
self.crashlog.process_arch="arm64"
elifstate=="X86_THREAD_STATE":
self.crashlog.process_arch="x86_64"
continue
try:
value=int(state["value"])
registers["{}{}".format(prefixor"", key)] =value
except (KeyError, ValueError, TypeError):
pass
returnregisters
defparse_errors(self, json_data):
if"reportNotes"injson_data:
self.crashlog.errors=json_data["reportNotes"]
classTextCrashLogParser(CrashLogParser):
parent_process_regex=re.compile(r"^Parent Process:\s*(.*)\[(\d+)\]")
thread_state_regex=re.compile(r"^Thread (\d+ crashed with|State)")
thread_instrs_regex=re.compile(r"^Thread \d+ instruction stream")
thread_regex=re.compile(r"^Thread (\d+).*")
app_backtrace_regex=re.compile(r"^Application Specific Backtrace (\d+).*")
classVersionRegex:
version=r"\(.+\)|(?:arm|x86_)[0-9a-z]+"
classFrameRegex(VersionRegex):
@classmethod
defget(cls):
index=r"^(\d+)\s+"
img_name=r"(.+?)\s+"
version=r"(?:"+super().version+r"\s+)?"
address=r"(0x[0-9a-fA-F]{4,})"# 4 digits or more
symbol=r"""
(?:
[ ]+
(?P<symbol>.+)
(?:
[ ]\+[ ]
(?P<symbol_offset>\d+)
)
(?:
[ ]\(
(?P<file_name>[^:]+):(?P<line_number>\d+)
(?:
:(?P<column_num>\d+)
)?
)?
)?
"""
returnre.compile(
index+img_name+version+address+symbol, flags=re.VERBOSE
)
frame_regex=FrameRegex.get()
null_frame_regex=re.compile(r"^\d+\s+\?\?\?\s+0{4,} +")
image_regex_uuid=re.compile(
r"(0x[0-9a-fA-F]+)"# img_lo
r"\s+-\s+"# -
r"(0x[0-9a-fA-F]+)\s+"# img_hi
r"[+]?(.+?)\s+"# img_name
r"(?:("+VersionRegex.version+r")\s+)?"# img_version
r"(?:<([-0-9a-fA-F]+)>\s+)?"# img_uuid
r"(\?+|/.*)"# img_path
)
exception_type_regex=re.compile(
r"^Exception Type:\s+(EXC_[A-Z_]+)(?:\s+\((.*)\))?"
)
exception_codes_regex=re.compile(
r"^Exception Codes:\s+(0x[0-9a-fA-F]+),\s*(0x[0-9a-fA-F]+)"
)
exception_extra_regex=re.compile(r"^Exception\s+.*:\s+(.*)")
classCrashLogParseMode:
NORMAL=0
THREAD=1
IMAGES=2
THREGS=3
SYSTEM=4
INSTRS=5
def__init__(self, debugger, path, options):
super().__init__(debugger, path, options)
self.thread=None
self.app_specific_backtrace=False
self.parse_mode=self.CrashLogParseMode.NORMAL
self.parsers= {
self.CrashLogParseMode.NORMAL: self.parse_normal,
self.CrashLogParseMode.THREAD: self.parse_thread,
self.CrashLogParseMode.IMAGES: self.parse_images,
self.CrashLogParseMode.THREGS: self.parse_thread_registers,
self.CrashLogParseMode.SYSTEM: self.parse_system,
self.CrashLogParseMode.INSTRS: self.parse_instructions,
}
self.symbols= {}
defparse(self):
withopen(self.path, "r", encoding="utf-8") asf:
lines=f.read().splitlines()
idx=0
lines_count=len(lines)
whileTrue:
ifidx>=lines_count:
break