1#!/usr/bin/env python
2
3#----------------------------------------------------------------------
4# Be sure to add the python path that points to the LLDB shared library.
5#
6# To use this in the embedded python interpreter using "lldb":
7#
8#   cd /path/containing/crashlog.py
9#   lldb
10#   (lldb) script import crashlog
11#   "crashlog" command installed, type "crashlog --help" for detailed help
12#   (lldb) crashlog ~/Library/Logs/DiagnosticReports/a.crash
13#
14# The benefit of running the crashlog command inside lldb in the
15# embedded python interpreter is when the command completes, there
16# will be a target with all of the files loaded at the locations
17# described in the crash log. Only the files that have stack frames
18# in the backtrace will be loaded unless the "--load-all" option
19# has been specified. This allows users to explore the program in the
20# state it was in right at crash time.
21#
22# On MacOSX csh, tcsh:
23#   ( setenv PYTHONPATH /path/to/LLDB.framework/Resources/Python ; ./crashlog.py ~/Library/Logs/DiagnosticReports/a.crash )
24#
25# On MacOSX sh, bash:
26#   PYTHONPATH=/path/to/LLDB.framework/Resources/Python ./crashlog.py ~/Library/Logs/DiagnosticReports/a.crash
27#----------------------------------------------------------------------
28
29from __future__ import print_function
30import lldb
31import optparse
32import os
33import plistlib
34import re
35import shlex
36import sys
37import time
38import uuid
39
40
41class Address:
42    """Class that represents an address that will be symbolicated"""
43
44    def __init__(self, target, load_addr):
45        self.target = target
46        self.load_addr = load_addr  # The load address that this object represents
47        # the resolved lldb.SBAddress (if any), named so_addr for
48        # section/offset address
49        self.so_addr = None
50        self.sym_ctx = None  # The cached symbol context for this address
51        # Any original textual description of this address to be used as a
52        # backup in case symbolication fails
53        self.description = None
54        self.symbolication = None  # The cached symbolicated string that describes this address
55        self.inlined = False
56
57    def __str__(self):
58        s = "%#16.16x" % (self.load_addr)
59        if self.symbolication:
60            s += " %s" % (self.symbolication)
61        elif self.description:
62            s += " %s" % (self.description)
63        elif self.so_addr:
64            s += " %s" % (self.so_addr)
65        return s
66
67    def resolve_addr(self):
68        if self.so_addr is None:
69            self.so_addr = self.target.ResolveLoadAddress(self.load_addr)
70        return self.so_addr
71
72    def is_inlined(self):
73        return self.inlined
74
75    def get_symbol_context(self):
76        if self.sym_ctx is None:
77            sb_addr = self.resolve_addr()
78            if sb_addr:
79                self.sym_ctx = self.target.ResolveSymbolContextForAddress(
80                    sb_addr, lldb.eSymbolContextEverything)
81            else:
82                self.sym_ctx = lldb.SBSymbolContext()
83        return self.sym_ctx
84
85    def get_instructions(self):
86        sym_ctx = self.get_symbol_context()
87        if sym_ctx:
88            function = sym_ctx.GetFunction()
89            if function:
90                return function.GetInstructions(self.target)
91            return sym_ctx.GetSymbol().GetInstructions(self.target)
92        return None
93
94    def symbolicate(self, verbose=False):
95        if self.symbolication is None:
96            self.symbolication = ''
97            self.inlined = False
98            sym_ctx = self.get_symbol_context()
99            if sym_ctx:
100                module = sym_ctx.GetModule()
101                if module:
102                    # Print full source file path in verbose mode
103                    if verbose:
104                        self.symbolication += str(module.GetFileSpec()) + '`'
105                    else:
106                        self.symbolication += module.GetFileSpec().GetFilename() + '`'
107                    function_start_load_addr = -1
108                    function = sym_ctx.GetFunction()
109                    block = sym_ctx.GetBlock()
110                    line_entry = sym_ctx.GetLineEntry()
111                    symbol = sym_ctx.GetSymbol()
112                    inlined_block = block.GetContainingInlinedBlock()
113                    if function:
114                        self.symbolication += function.GetName()
115
116                        if inlined_block:
117                            self.inlined = True
118                            self.symbolication += ' [inlined] ' + \
119                                inlined_block.GetInlinedName()
120                            block_range_idx = inlined_block.GetRangeIndexForBlockAddress(
121                                self.so_addr)
122                            if block_range_idx < lldb.UINT32_MAX:
123                                block_range_start_addr = inlined_block.GetRangeStartAddress(
124                                    block_range_idx)
125                                function_start_load_addr = block_range_start_addr.GetLoadAddress(
126                                    self.target)
127                        if function_start_load_addr == -1:
128                            function_start_load_addr = function.GetStartAddress().GetLoadAddress(self.target)
129                    elif symbol:
130                        self.symbolication += symbol.GetName()
131                        function_start_load_addr = symbol.GetStartAddress().GetLoadAddress(self.target)
132                    else:
133                        self.symbolication = ''
134                        return False
135
136                    # Dump the offset from the current function or symbol if it
137                    # is non zero
138                    function_offset = self.load_addr - function_start_load_addr
139                    if function_offset > 0:
140                        self.symbolication += " + %u" % (function_offset)
141                    elif function_offset < 0:
142                        self.symbolication += " %i (invalid negative offset, file a bug) " % function_offset
143
144                    # Print out any line information if any is available
145                    if line_entry.GetFileSpec():
146                        # Print full source file path in verbose mode
147                        if verbose:
148                            self.symbolication += ' at %s' % line_entry.GetFileSpec()
149                        else:
150                            self.symbolication += ' at %s' % line_entry.GetFileSpec().GetFilename()
151                        self.symbolication += ':%u' % line_entry.GetLine()
152                        column = line_entry.GetColumn()
153                        if column > 0:
154                            self.symbolication += ':%u' % column
155                    return True
156        return False
157
158
159class Section:
160    """Class that represents an load address range"""
161    sect_info_regex = re.compile('(?P<name>[^=]+)=(?P<range>.*)')
162    addr_regex = re.compile('^\s*(?P<start>0x[0-9A-Fa-f]+)\s*$')
163    range_regex = re.compile(
164        '^\s*(?P<start>0x[0-9A-Fa-f]+)\s*(?P<op>[-+])\s*(?P<end>0x[0-9A-Fa-f]+)\s*$')
165
166    def __init__(self, start_addr=None, end_addr=None, name=None):
167        self.start_addr = start_addr
168        self.end_addr = end_addr
169        self.name = name
170
171    @classmethod
172    def InitWithSBTargetAndSBSection(cls, target, section):
173        sect_load_addr = section.GetLoadAddress(target)
174        if sect_load_addr != lldb.LLDB_INVALID_ADDRESS:
175            obj = cls(
176                sect_load_addr,
177                sect_load_addr +
178                section.size,
179                section.name)
180            return obj
181        else:
182            return None
183
184    def contains(self, addr):
185        return self.start_addr <= addr and addr < self.end_addr
186
187    def set_from_string(self, s):
188        match = self.sect_info_regex.match(s)
189        if match:
190            self.name = match.group('name')
191            range_str = match.group('range')
192            addr_match = self.addr_regex.match(range_str)
193            if addr_match:
194                self.start_addr = int(addr_match.group('start'), 16)
195                self.end_addr = None
196                return True
197
198            range_match = self.range_regex.match(range_str)
199            if range_match:
200                self.start_addr = int(range_match.group('start'), 16)
201                self.end_addr = int(range_match.group('end'), 16)
202                op = range_match.group('op')
203                if op == '+':
204                    self.end_addr += self.start_addr
205                return True
206        print('error: invalid section info string "%s"' % s)
207        print('Valid section info formats are:')
208        print('Format                Example                    Description')
209        print('--------------------- -----------------------------------------------')
210        print('<name>=<base>        __TEXT=0x123000             Section from base address only')
211        print('<name>=<base>-<end>  __TEXT=0x123000-0x124000    Section from base address and end address')
212        print('<name>=<base>+<size> __TEXT=0x123000+0x1000      Section from base address and size')
213        return False
214
215    def __str__(self):
216        if self.name:
217            if self.end_addr is not None:
218                if self.start_addr is not None:
219                    return "%s=[0x%16.16x - 0x%16.16x)" % (
220                        self.name, self.start_addr, self.end_addr)
221            else:
222                if self.start_addr is not None:
223                    return "%s=0x%16.16x" % (self.name, self.start_addr)
224            return self.name
225        return "<invalid>"
226
227
228class Image:
229    """A class that represents an executable image and any associated data"""
230
231    def __init__(self, path, uuid=None):
232        self.path = path
233        self.resolved_path = None
234        self.resolved = False
235        self.unavailable = False
236        self.uuid = uuid
237        self.section_infos = list()
238        self.identifier = None
239        self.version = None
240        self.arch = None
241        self.module = None
242        self.symfile = None
243        self.slide = None
244
245    @classmethod
246    def InitWithSBTargetAndSBModule(cls, target, module):
247        '''Initialize this Image object with a module from a target.'''
248        obj = cls(module.file.fullpath, module.uuid)
249        obj.resolved_path = module.platform_file.fullpath
250        obj.resolved = True
251        for section in module.sections:
252            symb_section = Section.InitWithSBTargetAndSBSection(
253                target, section)
254            if symb_section:
255                obj.section_infos.append(symb_section)
256        obj.arch = module.triple
257        obj.module = module
258        obj.symfile = None
259        obj.slide = None
260        return obj
261
262    def dump(self, prefix):
263        print("%s%s" % (prefix, self))
264
265    def debug_dump(self):
266        print('path = "%s"' % (self.path))
267        print('resolved_path = "%s"' % (self.resolved_path))
268        print('resolved = %i' % (self.resolved))
269        print('unavailable = %i' % (self.unavailable))
270        print('uuid = %s' % (self.uuid))
271        print('section_infos = %s' % (self.section_infos))
272        print('identifier = "%s"' % (self.identifier))
273        print('version = %s' % (self.version))
274        print('arch = %s' % (self.arch))
275        print('module = %s' % (self.module))
276        print('symfile = "%s"' % (self.symfile))
277        print('slide = %i (0x%x)' % (self.slide, self.slide))
278
279    def __str__(self):
280        s = ''
281        if self.uuid:
282            s += "%s " % (self.get_uuid())
283        if self.arch:
284            s += "%s " % (self.arch)
285        if self.version:
286            s += "%s " % (self.version)
287        resolved_path = self.get_resolved_path()
288        if resolved_path:
289            s += "%s " % (resolved_path)
290        for section_info in self.section_infos:
291            s += ", %s" % (section_info)
292        if self.slide is not None:
293            s += ', slide = 0x%16.16x' % self.slide
294        return s
295
296    def add_section(self, section):
297        # print "added '%s' to '%s'" % (section, self.path)
298        self.section_infos.append(section)
299
300    def get_section_containing_load_addr(self, load_addr):
301        for section_info in self.section_infos:
302            if section_info.contains(load_addr):
303                return section_info
304        return None
305
306    def get_resolved_path(self):
307        if self.resolved_path:
308            return self.resolved_path
309        elif self.path:
310            return self.path
311        return None
312
313    def get_resolved_path_basename(self):
314        path = self.get_resolved_path()
315        if path:
316            return os.path.basename(path)
317        return None
318
319    def symfile_basename(self):
320        if self.symfile:
321            return os.path.basename(self.symfile)
322        return None
323
324    def has_section_load_info(self):
325        return self.section_infos or self.slide is not None
326
327    def load_module(self, target):
328        if self.unavailable:
329            return None  # We already warned that we couldn't find this module, so don't return an error string
330        # Load this module into "target" using the section infos to
331        # set the section load addresses
332        if self.has_section_load_info():
333            if target:
334                if self.module:
335                    if self.section_infos:
336                        num_sections_loaded = 0
337                        for section_info in self.section_infos:
338                            if section_info.name:
339                                section = self.module.FindSection(
340                                    section_info.name)
341                                if section:
342                                    error = target.SetSectionLoadAddress(
343                                        section, section_info.start_addr)
344                                    if error.Success():
345                                        num_sections_loaded += 1
346                                    else:
347                                        return 'error: %s' % error.GetCString()
348                                else:
349                                    return 'error: unable to find the section named "%s"' % section_info.name
350                            else:
351                                return 'error: unable to find "%s" section in "%s"' % (
352                                    range.name, self.get_resolved_path())
353                        if num_sections_loaded == 0:
354                            return 'error: no sections were successfully loaded'
355                    else:
356                        err = target.SetModuleLoadAddress(
357                            self.module, self.slide)
358                        if err.Fail():
359                            return err.GetCString()
360                    return None
361                else:
362                    return 'error: invalid module'
363            else:
364                return 'error: invalid target'
365        else:
366            return 'error: no section infos'
367
368    def add_module(self, target):
369        '''Add the Image described in this object to "target" and load the sections if "load" is True.'''
370        if target:
371            # Try and find using UUID only first so that paths need not match
372            # up
373            uuid_str = self.get_normalized_uuid_string()
374            if uuid_str:
375                self.module = target.AddModule(None, None, uuid_str)
376            if not self.module:
377                self.locate_module_and_debug_symbols()
378                if self.unavailable:
379                    return None
380                resolved_path = self.get_resolved_path()
381                self.module = target.AddModule(
382                    resolved_path, str(self.arch), uuid_str, self.symfile)
383            if not self.module:
384                return 'error: unable to get module for (%s) "%s"' % (
385                    self.arch, self.get_resolved_path())
386            if self.has_section_load_info():
387                return self.load_module(target)
388            else:
389                return None  # No sections, the module was added to the target, so success
390        else:
391            return 'error: invalid target'
392
393    def locate_module_and_debug_symbols(self):
394        # By default, just use the paths that were supplied in:
395        # self.path
396        # self.resolved_path
397        # self.module
398        # self.symfile
399        # Subclasses can inherit from this class and override this function
400        self.resolved = True
401        return True
402
403    def get_uuid(self):
404        if not self.uuid and self.module:
405            self.uuid = uuid.UUID(self.module.GetUUIDString())
406        return self.uuid
407
408    def get_normalized_uuid_string(self):
409        if self.uuid:
410            return str(self.uuid).upper()
411        return None
412
413    def create_target(self, debugger):
414        '''Create a target using the information in this Image object.'''
415        if self.unavailable:
416            return None
417
418        if self.locate_module_and_debug_symbols():
419            resolved_path = self.get_resolved_path()
420            path_spec = lldb.SBFileSpec(resolved_path)
421            error = lldb.SBError()
422            target = debugger.CreateTarget(
423                resolved_path, self.arch, None, False, error)
424            if target:
425                self.module = target.FindModule(path_spec)
426                if self.has_section_load_info():
427                    err = self.load_module(target)
428                    if err:
429                        print('ERROR: ', err)
430                return target
431            else:
432                print('error: unable to create a valid target for (%s) "%s"' % (self.arch, self.path))
433        else:
434            print('error: unable to locate main executable (%s) "%s"' % (self.arch, self.path))
435        return None
436
437
438class Symbolicator:
439
440    def __init__(self, debugger):
441        """A class the represents the information needed to symbolicate addresses in a program"""
442        self.debugger = debugger
443        self.target = None
444        self.images = list()  # a list of images to be used when symbolicating
445        self.addr_mask = 0xffffffffffffffff
446
447    @classmethod
448    def InitWithSBTarget(cls, target):
449        obj = cls()
450        obj.target = target
451        obj.images = list()
452        triple = target.triple
453        if triple:
454            arch = triple.split('-')[0]
455            if "arm" in arch:
456                obj.addr_mask = 0xfffffffffffffffe
457
458        for module in target.modules:
459            image = Image.InitWithSBTargetAndSBModule(target, module)
460            obj.images.append(image)
461        return obj
462
463    def __str__(self):
464        s = "Symbolicator:\n"
465        if self.target:
466            s += "Target = '%s'\n" % (self.target)
467            s += "Target modules:\n"
468            for m in self.target.modules:
469                s += str(m) + "\n"
470        s += "Images:\n"
471        for image in self.images:
472            s += '    %s\n' % (image)
473        return s
474
475    def find_images_with_identifier(self, identifier):
476        images = list()
477        for image in self.images:
478            if image.identifier == identifier:
479                images.append(image)
480        if len(images) == 0:
481            regex_text = '^.*\.%s$' % (re.escape(identifier))
482            regex = re.compile(regex_text)
483            for image in self.images:
484                if regex.match(image.identifier):
485                    images.append(image)
486        return images
487
488    def find_image_containing_load_addr(self, load_addr):
489        for image in self.images:
490            if image.get_section_containing_load_addr(load_addr):
491                return image
492        return None
493
494    def create_target(self):
495        if self.target:
496            return self.target
497
498        if self.images:
499            for image in self.images:
500                self.target = image.create_target(self.debugger)
501                if self.target:
502                    if self.target.GetAddressByteSize() == 4:
503                        triple = self.target.triple
504                        if triple:
505                            arch = triple.split('-')[0]
506                            if "arm" in arch:
507                                self.addr_mask = 0xfffffffffffffffe
508                    return self.target
509        return None
510
511    def symbolicate(self, load_addr, verbose=False):
512        if not self.target:
513            self.create_target()
514        if self.target:
515            live_process = False
516            process = self.target.process
517            if process:
518                state = process.state
519                if state > lldb.eStateUnloaded and state < lldb.eStateDetached:
520                    live_process = True
521            # If we don't have a live process, we can attempt to find the image
522            # that a load address belongs to and lazily load its module in the
523            # target, but we shouldn't do any of this if we have a live process
524            if not live_process:
525                image = self.find_image_containing_load_addr(load_addr)
526                if image:
527                    image.add_module(self.target)
528            symbolicated_address = Address(self.target, load_addr)
529            if symbolicated_address.symbolicate(verbose):
530                if symbolicated_address.so_addr:
531                    symbolicated_addresses = list()
532                    symbolicated_addresses.append(symbolicated_address)
533                    # See if we were able to reconstruct anything?
534                    while True:
535                        inlined_parent_so_addr = lldb.SBAddress()
536                        inlined_parent_sym_ctx = symbolicated_address.sym_ctx.GetParentOfInlinedScope(
537                            symbolicated_address.so_addr, inlined_parent_so_addr)
538                        if not inlined_parent_sym_ctx:
539                            break
540                        if not inlined_parent_so_addr:
541                            break
542
543                        symbolicated_address = Address(
544                            self.target, inlined_parent_so_addr.GetLoadAddress(
545                                self.target))
546                        symbolicated_address.sym_ctx = inlined_parent_sym_ctx
547                        symbolicated_address.so_addr = inlined_parent_so_addr
548                        symbolicated_address.symbolicate(verbose)
549
550                        # push the new frame onto the new frame stack
551                        symbolicated_addresses.append(symbolicated_address)
552
553                    if symbolicated_addresses:
554                        return symbolicated_addresses
555        else:
556            print('error: no target in Symbolicator')
557        return None
558
559
560def disassemble_instructions(
561        target,
562        instructions,
563        pc,
564        insts_before_pc,
565        insts_after_pc,
566        non_zeroeth_frame):
567    lines = list()
568    pc_index = -1
569    comment_column = 50
570    for inst_idx, inst in enumerate(instructions):
571        inst_pc = inst.GetAddress().GetLoadAddress(target)
572        if pc == inst_pc:
573            pc_index = inst_idx
574        mnemonic = inst.GetMnemonic(target)
575        operands = inst.GetOperands(target)
576        comment = inst.GetComment(target)
577        lines.append("%#16.16x: %8s %s" % (inst_pc, mnemonic, operands))
578        if comment:
579            line_len = len(lines[-1])
580            if line_len < comment_column:
581                lines[-1] += ' ' * (comment_column - line_len)
582                lines[-1] += "; %s" % comment
583
584    if pc_index >= 0:
585        # If we are disassembling the non-zeroeth frame, we need to backup the
586        # PC by 1
587        if non_zeroeth_frame and pc_index > 0:
588            pc_index = pc_index - 1
589        if insts_before_pc == -1:
590            start_idx = 0
591        else:
592            start_idx = pc_index - insts_before_pc
593        if start_idx < 0:
594            start_idx = 0
595        if insts_before_pc == -1:
596            end_idx = inst_idx
597        else:
598            end_idx = pc_index + insts_after_pc
599        if end_idx > inst_idx:
600            end_idx = inst_idx
601        for i in range(start_idx, end_idx + 1):
602            if i == pc_index:
603                print(' -> ', lines[i])
604            else:
605                print('    ', lines[i])
606
607
608def print_module_section_data(section):
609    print(section)
610    section_data = section.GetSectionData()
611    if section_data:
612        ostream = lldb.SBStream()
613        section_data.GetDescription(ostream, section.GetFileAddress())
614        print(ostream.GetData())
615
616
617def print_module_section(section, depth):
618    print(section)
619    if depth > 0:
620        num_sub_sections = section.GetNumSubSections()
621        for sect_idx in range(num_sub_sections):
622            print_module_section(
623                section.GetSubSectionAtIndex(sect_idx), depth - 1)
624
625
626def print_module_sections(module, depth):
627    for sect in module.section_iter():
628        print_module_section(sect, depth)
629
630
631def print_module_symbols(module):
632    for sym in module:
633        print(sym)
634
635
636def Symbolicate(debugger, command_args):
637
638    usage = "usage: %prog [options] <addr1> [addr2 ...]"
639    description = '''Symbolicate one or more addresses using LLDB's python scripting API..'''
640    parser = optparse.OptionParser(
641        description=description,
642        prog='crashlog.py',
643        usage=usage)
644    parser.add_option(
645        '-v',
646        '--verbose',
647        action='store_true',
648        dest='verbose',
649        help='display verbose debug info',
650        default=False)
651    parser.add_option(
652        '-p',
653        '--platform',
654        type='string',
655        metavar='platform',
656        dest='platform',
657        help='Specify the platform to use when creating the debug target. Valid values include "localhost", "darwin-kernel", "ios-simulator", "remote-freebsd", "remote-macosx", "remote-ios", "remote-linux".')
658    parser.add_option(
659        '-f',
660        '--file',
661        type='string',
662        metavar='file',
663        dest='file',
664        help='Specify a file to use when symbolicating')
665    parser.add_option(
666        '-a',
667        '--arch',
668        type='string',
669        metavar='arch',
670        dest='arch',
671        help='Specify a architecture to use when symbolicating')
672    parser.add_option(
673        '-s',
674        '--slide',
675        type='int',
676        metavar='slide',
677        dest='slide',
678        help='Specify the slide to use on the file specified with the --file option',
679        default=None)
680    parser.add_option(
681        '--section',
682        type='string',
683        action='append',
684        dest='section_strings',
685        help='specify <sect-name>=<start-addr> or <sect-name>=<start-addr>-<end-addr>')
686    try:
687        (options, args) = parser.parse_args(command_args)
688    except:
689        return
690    symbolicator = Symbolicator(debugger)
691    images = list()
692    if options.file:
693        image = Image(options.file)
694        image.arch = options.arch
695        # Add any sections that were specified with one or more --section
696        # options
697        if options.section_strings:
698            for section_str in options.section_strings:
699                section = Section()
700                if section.set_from_string(section_str):
701                    image.add_section(section)
702                else:
703                    sys.exit(1)
704        if options.slide is not None:
705            image.slide = options.slide
706        symbolicator.images.append(image)
707
708    target = symbolicator.create_target()
709    if options.verbose:
710        print(symbolicator)
711    if target:
712        for addr_str in args:
713            addr = int(addr_str, 0)
714            symbolicated_addrs = symbolicator.symbolicate(
715                addr, options.verbose)
716            for symbolicated_addr in symbolicated_addrs:
717                print(symbolicated_addr)
718            print()
719    else:
720        print('error: no target for %s' % (symbolicator))
721
722if __name__ == '__main__':
723    # Create a new debugger instance
724    debugger = lldb.SBDebugger.Create()
725    Symbolicate(debugger, sys.argv[1:])
726    SBDebugger.Destroy(debugger)
727