1# This implements the "diagnose-unwind" command, usually installed
2# in the debug session like
3#   command script import lldb.diagnose
4# it is used when lldb's backtrace fails -- it collects and prints
5# information about the stack frames, and tries an alternate unwind
6# algorithm, that will help to understand why lldb's unwind algorithm
7# did not succeed.
8
9import optparse
10import lldb
11import re
12import shlex
13
14# Print the frame number, pc, frame pointer, module UUID and function name
15# Returns the SBModule that contains the PC, if it could be found
16def backtrace_print_frame (target, frame_num, addr, fp):
17  process = target.GetProcess()
18  addr_for_printing = addr
19  addr_width = process.GetAddressByteSize() * 2
20  if frame_num > 0:
21    addr = addr - 1
22
23  sbaddr = lldb.SBAddress()
24  try:
25    sbaddr.SetLoadAddress(addr, target)
26    module_description = ""
27    if sbaddr.GetModule():
28      module_filename = ""
29      module_uuid_str = sbaddr.GetModule().GetUUIDString()
30      if module_uuid_str == None:
31        module_uuid_str = ""
32      if sbaddr.GetModule().GetFileSpec():
33        module_filename = sbaddr.GetModule().GetFileSpec().GetFilename()
34        if module_filename == None:
35          module_filename = ""
36      if module_uuid_str != "" or module_filename != "":
37        module_description = '%s %s' % (module_filename, module_uuid_str)
38  except Exception:
39    print '%2d: pc==0x%-*x fp==0x%-*x' % (frame_num, addr_width, addr_for_printing, addr_width, fp)
40    return
41
42  sym_ctx = target.ResolveSymbolContextForAddress(sbaddr, lldb.eSymbolContextEverything)
43  if sym_ctx.IsValid() and sym_ctx.GetSymbol().IsValid():
44    function_start = sym_ctx.GetSymbol().GetStartAddress().GetLoadAddress(target)
45    offset = addr - function_start
46    print '%2d: pc==0x%-*x fp==0x%-*x %s %s + %d' % (frame_num, addr_width, addr_for_printing, addr_width, fp, module_description, sym_ctx.GetSymbol().GetName(), offset)
47  else:
48    print '%2d: pc==0x%-*x fp==0x%-*x %s' % (frame_num, addr_width, addr_for_printing, addr_width, fp, module_description)
49  return sbaddr.GetModule()
50
51# A simple stack walk algorithm that follows the frame chain.
52# Returns a two-element list; the first element is a list of modules
53# seen and the second element is a list of addresses seen during the backtrace.
54def simple_backtrace(debugger):
55  target = debugger.GetSelectedTarget()
56  process = target.GetProcess()
57  cur_thread = process.GetSelectedThread()
58
59  initial_fp = cur_thread.GetFrameAtIndex(0).GetFP()
60
61  # If the pseudoreg "fp" isn't recognized, on arm hardcode to r7 which is correct for Darwin programs.
62  if initial_fp == lldb.LLDB_INVALID_ADDRESS and target.triple[0:3] == "arm":
63    for reggroup in cur_thread.GetFrameAtIndex(1).registers:
64      if reggroup.GetName() == "General Purpose Registers":
65        for reg in reggroup:
66          if reg.GetName() == "r7":
67            initial_fp = int (reg.GetValue(), 16)
68
69  module_list = []
70  address_list = [cur_thread.GetFrameAtIndex(0).GetPC()]
71  this_module = backtrace_print_frame (target, 0, cur_thread.GetFrameAtIndex(0).GetPC(), initial_fp)
72  print_stack_frame (process, initial_fp)
73  print ""
74  if this_module != None:
75    module_list.append (this_module)
76  if cur_thread.GetNumFrames() < 2:
77    return [module_list, address_list]
78
79  cur_fp = process.ReadPointerFromMemory (initial_fp, lldb.SBError())
80  cur_pc = process.ReadPointerFromMemory (initial_fp + process.GetAddressByteSize(), lldb.SBError())
81
82  frame_num = 1
83
84  while cur_pc != 0 and cur_fp != 0 and cur_pc != lldb.LLDB_INVALID_ADDRESS and cur_fp != lldb.LLDB_INVALID_ADDRESS:
85    address_list.append (cur_pc)
86    this_module = backtrace_print_frame (target, frame_num, cur_pc, cur_fp)
87    print_stack_frame (process, cur_fp)
88    print ""
89    if this_module != None:
90      module_list.append (this_module)
91    frame_num = frame_num + 1
92    next_pc = 0
93    next_fp = 0
94    if target.triple[0:6] == "x86_64" or target.triple[0:4] == "i386" or target.triple[0:3] == "arm":
95      error = lldb.SBError()
96      next_pc = process.ReadPointerFromMemory(cur_fp + process.GetAddressByteSize(), error)
97      if not error.Success():
98        next_pc = 0
99      next_fp = process.ReadPointerFromMemory(cur_fp, error)
100      if not error.Success():
101        next_fp = 0
102    # Clear the 0th bit for arm frames - this indicates it is a thumb frame
103    if target.triple[0:3] == "arm" and (next_pc & 1) == 1:
104      next_pc = next_pc & ~1
105    cur_pc = next_pc
106    cur_fp = next_fp
107  this_module = backtrace_print_frame (target, frame_num, cur_pc, cur_fp)
108  print_stack_frame (process, cur_fp)
109  print ""
110  if this_module != None:
111    module_list.append (this_module)
112  return [module_list, address_list]
113
114def print_stack_frame(process, fp):
115  if fp == 0 or fp == lldb.LLDB_INVALID_ADDRESS or fp == 1:
116    return
117  addr_size = process.GetAddressByteSize()
118  addr = fp - (2 * addr_size)
119  i = 0
120  outline = "Stack frame from $fp-%d: " % (2 * addr_size)
121  error = lldb.SBError()
122  try:
123    while i < 5 and error.Success():
124      address = process.ReadPointerFromMemory(addr + (i * addr_size), error)
125      outline += " 0x%x" % address
126      i += 1
127    print outline
128  except Exception:
129    return
130
131def diagnose_unwind(debugger, command, result, dict):
132  """
133Gather diagnostic information to help debug incorrect unwind (backtrace)
134behavior in lldb.  When there is a backtrace that doesn't look
135correct, run this command with the correct thread selected and a
136large amount of diagnostic information will be printed, it is likely
137to be helpful when reporting the problem.
138  """
139
140  command_args = shlex.split(command)
141  parser = create_diagnose_unwind_options()
142  try:
143    (options, args) = parser.parse_args(command_args)
144  except:
145   return
146  target = debugger.GetSelectedTarget()
147  if target:
148    process = target.GetProcess()
149    if process:
150      thread = process.GetSelectedThread()
151      if thread:
152        lldb_versions_match = re.search(r'[lL][lL][dD][bB]-(\d+)([.](\d+))?([.](\d+))?', debugger.GetVersionString())
153        lldb_version = 0
154        lldb_minor = 0
155        if len(lldb_versions_match.groups()) >= 1 and lldb_versions_match.groups()[0]:
156          lldb_major = int(lldb_versions_match.groups()[0])
157        if len(lldb_versions_match.groups()) >= 5 and lldb_versions_match.groups()[4]:
158          lldb_minor = int(lldb_versions_match.groups()[4])
159
160        modules_seen = []
161        addresses_seen = []
162
163        print 'LLDB version %s' % debugger.GetVersionString()
164        print 'Unwind diagnostics for thread %d' % thread.GetIndexID()
165        print ""
166        print "============================================================================================="
167        print ""
168        print "OS plugin setting:"
169        debugger.HandleCommand("settings show target.process.python-os-plugin-path")
170        print ""
171        print "Live register context:"
172        thread.SetSelectedFrame(0)
173        debugger.HandleCommand("register read")
174        print ""
175        print "============================================================================================="
176        print ""
177        print "lldb's unwind algorithm:"
178        print ""
179        frame_num = 0
180        for frame in thread.frames:
181          if not frame.IsInlined():
182            this_module = backtrace_print_frame (target, frame_num, frame.GetPC(), frame.GetFP())
183            print_stack_frame (process, frame.GetFP())
184            print ""
185            if this_module != None:
186              modules_seen.append (this_module)
187            addresses_seen.append (frame.GetPC())
188            frame_num = frame_num + 1
189        print ""
190        print "============================================================================================="
191        print ""
192        print "Simple stack walk algorithm:"
193        print ""
194        (module_list, address_list) = simple_backtrace(debugger)
195        if module_list and module_list != None:
196          modules_seen += module_list
197        if address_list and address_list != None:
198          addresses_seen = set(addresses_seen)
199          addresses_seen.update(set(address_list))
200
201        print ""
202        print "============================================================================================="
203        print ""
204        print "Modules seen in stack walks:"
205        print ""
206        modules_already_seen = set()
207        for module in modules_seen:
208          if module != None and module.GetFileSpec().GetFilename() != None:
209            if not module.GetFileSpec().GetFilename() in modules_already_seen:
210              debugger.HandleCommand('image list %s' % module.GetFileSpec().GetFilename())
211              modules_already_seen.add(module.GetFileSpec().GetFilename())
212
213        print ""
214        print "============================================================================================="
215        print ""
216        print "Disassembly ofaddresses seen in stack walks:"
217        print ""
218        additional_addresses_to_disassemble = addresses_seen
219        for frame in thread.frames:
220          if not frame.IsInlined():
221            print "--------------------------------------------------------------------------------------"
222            print ""
223            print "Disassembly of %s, frame %d, address 0x%x" % (frame.GetFunctionName(), frame.GetFrameID(), frame.GetPC())
224            print ""
225            if target.triple[0:6] == "x86_64" or target.triple[0:4] == "i386":
226              debugger.HandleCommand('disassemble -F att -a 0x%x' % frame.GetPC())
227            else:
228              debugger.HandleCommand('disassemble -a 0x%x' % frame.GetPC())
229            if frame.GetPC() in additional_addresses_to_disassemble:
230              additional_addresses_to_disassemble.remove (frame.GetPC())
231
232        for address in list(additional_addresses_to_disassemble):
233          print "--------------------------------------------------------------------------------------"
234          print ""
235          print "Disassembly of 0x%x" % address
236          print ""
237          if target.triple[0:6] == "x86_64" or target.triple[0:4] == "i386":
238            debugger.HandleCommand('disassemble -F att -a 0x%x' % address)
239          else:
240            debugger.HandleCommand('disassemble -a 0x%x' % address)
241
242        print ""
243        print "============================================================================================="
244        print ""
245        additional_addresses_to_show_unwind = addresses_seen
246        for frame in thread.frames:
247          if not frame.IsInlined():
248            print "--------------------------------------------------------------------------------------"
249            print ""
250            print "Unwind instructions for %s, frame %d" % (frame.GetFunctionName(), frame.GetFrameID())
251            print ""
252            debugger.HandleCommand('image show-unwind -a "0x%x"' % frame.GetPC())
253            if frame.GetPC() in additional_addresses_to_show_unwind:
254              additional_addresses_to_show_unwind.remove (frame.GetPC())
255
256        for address in list(additional_addresses_to_show_unwind):
257          print "--------------------------------------------------------------------------------------"
258          print ""
259          print "Unwind instructions for 0x%x" % address
260          print ""
261          debugger.HandleCommand('image show-unwind -a "0x%x"' % address)
262
263def create_diagnose_unwind_options():
264  usage = "usage: %prog"
265  description='''Print diagnostic information about a thread backtrace which will help to debug unwind problems'''
266  parser = optparse.OptionParser(description=description, prog='diagnose_unwind',usage=usage)
267  return parser
268
269lldb.debugger.HandleCommand('command script add -f %s.diagnose_unwind diagnose-unwind' % __name__)
270print 'The "diagnose-unwind" command has been installed, type "help diagnose-unwind" for detailed help.'
271