blob: ee2069b9f639983c78b3e3d5c63c2629099ba08e [file] [log] [blame]
Jason Molendacaae3812013-04-23 03:40:32 +00001#!/usr/bin/python
2
3# This implements the unwind-diagnose command, usually installed in the debug session like
4# script import lldb.macosx
5# it is used when lldb's backtrace fails -- it collects and prints information about the stack frames,
6# and tries an alternate unwind algorithm, that will help to understand why lldb's unwind algorithm did
7# not succeed.
8
9import commands
10import optparse
11import os
12import platform
13import re
14import shlex
15import sys
16
17try:
18 # Just try for LLDB in case PYTHONPATH is already correctly setup
19 import lldb
20except ImportError:
21 lldb_python_dirs = list()
22 # lldb is not in the PYTHONPATH, try some defaults for the current platform
23 platform_system = platform.system()
24 if platform_system == 'Darwin':
25 # On Darwin, try the currently selected Xcode directory
26 xcode_dir = commands.getoutput("xcode-select --print-path")
27 if xcode_dir:
28 lldb_python_dirs.append(os.path.realpath(xcode_dir + '/../SharedFrameworks/LLDB.framework/Resources/Python'))
29 lldb_python_dirs.append(xcode_dir + '/Library/PrivateFrameworks/LLDB.framework/Resources/Python')
30 lldb_python_dirs.append('/System/Library/PrivateFrameworks/LLDB.framework/Resources/Python')
31 success = False
32 for lldb_python_dir in lldb_python_dirs:
33 if os.path.exists(lldb_python_dir):
34 if not (sys.path.__contains__(lldb_python_dir)):
35 sys.path.append(lldb_python_dir)
36 try:
37 import lldb
38 except ImportError:
39 pass
40 else:
41 print 'imported lldb from: "%s"' % (lldb_python_dir)
42 success = True
43 break
44 if not success:
45 print "error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly"
46 sys.exit(1)
47
48# Print the frame number, pc, frame pointer, module UUID and function name
49def backtrace_print_frame (target, frame_num, addr, fp):
50 process = target.GetProcess()
51 addr_for_printing = addr
52 if frame_num > 0:
53 addr = addr - 1
54
55 sbaddr = lldb.SBAddress()
56 sbaddr.SetLoadAddress(addr, target)
57 module_description = ""
58 if sbaddr.GetModule():
59 module_filename = ""
60 module_uuid_str = sbaddr.GetModule().GetUUIDString()
61 if module_uuid_str == None:
62 module_uuid_str = ""
63 if sbaddr.GetModule().GetFileSpec():
64 module_filename = sbaddr.GetModule().GetFileSpec().GetFilename()
65 if module_filename == None:
66 module_filename = ""
67 if module_uuid_str != "" or module_filename != "":
68 module_description = '%s %s' % (module_filename, module_uuid_str)
69
70 addr_width = process.GetAddressByteSize() * 2
71 sym_ctx = target.ResolveSymbolContextForAddress(sbaddr, lldb.eSymbolContextEverything)
72 if sym_ctx.IsValid() and sym_ctx.GetSymbol().IsValid():
73 function_start = sym_ctx.GetSymbol().GetStartAddress().GetLoadAddress(target)
74 offset = addr - function_start
75 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)
76 else:
77 print '%2d: pc==0x%-*x fp==0x%-*x %s' % (frame_num, addr_width, addr_for_printing, addr_width, fp, module_description)
78
79# A simple stack walk algorithm that follows the frame chain after the first two frames.
80def simple_backtrace(debugger):
81 target = debugger.GetSelectedTarget()
82 process = target.GetProcess()
83 cur_thread = process.GetSelectedThread()
84
85 backtrace_print_frame (target, 0, cur_thread.GetFrameAtIndex(0).GetPC(), cur_thread.GetFrameAtIndex(0).GetFP())
86 if cur_thread.GetNumFrames() < 2:
87 return
88
89 cur_fp = cur_thread.GetFrameAtIndex(1).GetFP()
90 cur_pc = cur_thread.GetFrameAtIndex(1).GetPC()
91
92 # If the pseudoreg "fp" isn't recognized, on arm hardcode to r7 which is correct for Darwin programs.
93 if cur_fp == lldb.LLDB_INVALID_ADDRESS and target.triple[0:3] == "arm":
94 for reggroup in cur_thread.GetFrameAtIndex(1).registers:
95 if reggroup.GetName() == "General Purpose Registers":
96 for reg in reggroup:
97 if reg.GetName() == "r7":
98 cur_fp = int (reg.GetValue(), 16)
99
100 frame_num = 1
101
102 while cur_pc != 0 and cur_fp != 0 and cur_pc != lldb.LLDB_INVALID_ADDRESS and cur_fp != lldb.LLDB_INVALID_ADDRESS:
103 backtrace_print_frame (target, frame_num, cur_pc, cur_fp)
104 frame_num = frame_num + 1
105 next_pc = 0
106 next_fp = 0
107 if target.triple[0:6] == "x86_64" or target.triple[0:4] == "i386" or target.triple[0:3] == "arm":
108 error = lldb.SBError()
109 next_pc = process.ReadPointerFromMemory(cur_fp + process.GetAddressByteSize(), error)
110 if not error.Success():
111 next_pc = 0
112 next_fp = process.ReadPointerFromMemory(cur_fp, error)
113 if not error.Success():
114 next_fp = 0
115 # Clear the 0th bit for arm frames - this indicates it is a thumb frame
116 if target.triple[0:3] == "arm" and (next_pc & 1) == 1:
117 next_pc = next_pc & ~1
118 cur_pc = next_pc
119 cur_fp = next_fp
120 backtrace_print_frame (target, frame_num, cur_pc, cur_fp)
121
122def unwind_diagnose(debugger, command, result, dict):
123 # Use the Shell Lexer to properly parse up command options just like a
124 # shell would
125 command_args = shlex.split(command)
126 parser = create_unwind_diagnose_options()
127 try:
128 (options, args) = parser.parse_args(command_args)
129 except:
130 return
131 target = debugger.GetSelectedTarget()
132 if target:
133 process = target.GetProcess()
134 if process:
135 thread = process.GetSelectedThread()
136 if thread:
137 lldb_versions_match = re.search(r'lldb-(\d+)([.](\d+))?([.](\d+))?', debugger.GetVersionString())
138 lldb_version = 0
139 lldb_minor = 0
140 if len(lldb_versions_match.groups()) >= 1:
141 lldb_major = lldb_versions_match.groups(1)
142 if len(lldb_versions_match.groups()) >= 5:
143 lldb_minor = lldb_versions_match.groups(5)
144
145 print 'Unwind diagnostics for thread %d' % thread.GetIndexID()
146 print ""
147 print "lldb's unwind algorithm:"
148 print ""
149 frame_num = 0
150 for frame in thread.frames:
151 if not frame.IsInlined():
152 backtrace_print_frame (target, frame_num, frame.GetPC(), frame.GetFP())
153 frame_num = frame_num + 1
154 print ""
155 print "============================================================================================="
156 print ""
157 print "Simple stack walk algorithm:"
158 print ""
159 simple_backtrace(debugger)
160 print ""
161 print "============================================================================================="
162 print ""
163 for frame in thread.frames:
164 if not frame.IsInlined():
165 print "--------------------------------------------------------------------------------------"
166 print ""
167 print "Disassembly of %s, frame %d" % (frame.GetFunctionName(), frame.GetFrameID())
168 print ""
169 if lldb_major > 300 or (lldb_major == 300 and lldb_minor >= 18):
170 if target.triple[0:6] == "x86_64" or target.triple[0:4] == "i386":
171 debugger.HandleCommand('disassemble -F att -a 0x%x' % frame.GetPC())
172 else:
173 debugger.HandleCommand('disassemble -a 0x%x' % frame.GetPC())
174 else:
175 debugger.HandleCommand('disassemble -n "%s"' % frame.GetFunctionName())
176 print ""
177 print "============================================================================================="
178 print ""
179 for frame in thread.frames:
180 if not frame.IsInlined():
181 print "--------------------------------------------------------------------------------------"
182 print ""
183 print "Unwind instructions for %s, frame %d" % (frame.GetFunctionName(), frame.GetFrameID())
184 print ""
185 debugger.HandleCommand('image show-unwind -n "%s"' % frame.GetFunctionName())
186
187def create_unwind_diagnose_options():
188 usage = "usage: %prog"
189 description='''Print diagnostic information about a thread backtrace which will help to debug unwind problems'''
190 parser = optparse.OptionParser(description=description, prog='unwind_diagnose',usage=usage)
191 return parser
192
193if __name__ == '__main__':
194 print 'This is not meant to be run from the command line, import it into lldb with a command like "script import lldb.macosx"'
195elif getattr(lldb, 'debugger', None):
196 lldb.debugger.HandleCommand('command script add -f lldb.macosx.unwind_diagnose.unwind_diagnose unwind-diagnose')
197 print 'The "unwind-diagnose" command has been installed, type "help unwind-diagnose" for detailed help.'