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