xref: /openbsd-src/gnu/llvm/lldb/utils/lui/lldbutil.py (revision 061da546b983eb767bad15e67af1174fb0bcf31c)
1*061da546Spatrick##===-- lldbutil.py ------------------------------------------*- Python -*-===##
2*061da546Spatrick##
3*061da546Spatrick# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*061da546Spatrick# See https://llvm.org/LICENSE.txt for license information.
5*061da546Spatrick# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*061da546Spatrick##
7*061da546Spatrick##===----------------------------------------------------------------------===##
8*061da546Spatrick
9*061da546Spatrick"""
10*061da546SpatrickThis LLDB module contains miscellaneous utilities.
11*061da546SpatrickSome of the test suite takes advantage of the utility functions defined here.
12*061da546SpatrickThey can also be useful for general purpose lldb scripting.
13*061da546Spatrick"""
14*061da546Spatrick
15*061da546Spatrickfrom __future__ import print_function
16*061da546Spatrick
17*061da546Spatrickimport lldb
18*061da546Spatrickimport os
19*061da546Spatrickimport sys
20*061da546Spatrickimport io
21*061da546Spatrick
22*061da546Spatrick# ===================================================
23*061da546Spatrick# Utilities for locating/checking executable programs
24*061da546Spatrick# ===================================================
25*061da546Spatrick
26*061da546Spatrick
27*061da546Spatrickdef is_exe(fpath):
28*061da546Spatrick    """Returns True if fpath is an executable."""
29*061da546Spatrick    return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
30*061da546Spatrick
31*061da546Spatrick
32*061da546Spatrickdef which(program):
33*061da546Spatrick    """Returns the full path to a program; None otherwise."""
34*061da546Spatrick    fpath, fname = os.path.split(program)
35*061da546Spatrick    if fpath:
36*061da546Spatrick        if is_exe(program):
37*061da546Spatrick            return program
38*061da546Spatrick    else:
39*061da546Spatrick        for path in os.environ["PATH"].split(os.pathsep):
40*061da546Spatrick            exe_file = os.path.join(path, program)
41*061da546Spatrick            if is_exe(exe_file):
42*061da546Spatrick                return exe_file
43*061da546Spatrick    return None
44*061da546Spatrick
45*061da546Spatrick# ===================================================
46*061da546Spatrick# Disassembly for an SBFunction or an SBSymbol object
47*061da546Spatrick# ===================================================
48*061da546Spatrick
49*061da546Spatrick
50*061da546Spatrickdef disassemble(target, function_or_symbol):
51*061da546Spatrick    """Disassemble the function or symbol given a target.
52*061da546Spatrick
53*061da546Spatrick    It returns the disassembly content in a string object.
54*061da546Spatrick    """
55*061da546Spatrick    buf = io.StringIO()
56*061da546Spatrick    insts = function_or_symbol.GetInstructions(target)
57*061da546Spatrick    for i in insts:
58*061da546Spatrick        print(i, file=buf)
59*061da546Spatrick    return buf.getvalue()
60*061da546Spatrick
61*061da546Spatrick# ==========================================================
62*061da546Spatrick# Integer (byte size 1, 2, 4, and 8) to bytearray conversion
63*061da546Spatrick# ==========================================================
64*061da546Spatrick
65*061da546Spatrick
66*061da546Spatrickdef int_to_bytearray(val, bytesize):
67*061da546Spatrick    """Utility function to convert an integer into a bytearray.
68*061da546Spatrick
69*061da546Spatrick    It returns the bytearray in the little endian format.  It is easy to get the
70*061da546Spatrick    big endian format, just do ba.reverse() on the returned object.
71*061da546Spatrick    """
72*061da546Spatrick    import struct
73*061da546Spatrick
74*061da546Spatrick    if bytesize == 1:
75*061da546Spatrick        return bytearray([val])
76*061da546Spatrick
77*061da546Spatrick    # Little endian followed by a format character.
78*061da546Spatrick    template = "<%c"
79*061da546Spatrick    if bytesize == 2:
80*061da546Spatrick        fmt = template % 'h'
81*061da546Spatrick    elif bytesize == 4:
82*061da546Spatrick        fmt = template % 'i'
83*061da546Spatrick    elif bytesize == 4:
84*061da546Spatrick        fmt = template % 'q'
85*061da546Spatrick    else:
86*061da546Spatrick        return None
87*061da546Spatrick
88*061da546Spatrick    packed = struct.pack(fmt, val)
89*061da546Spatrick    return bytearray(ord(x) for x in packed)
90*061da546Spatrick
91*061da546Spatrick
92*061da546Spatrickdef bytearray_to_int(bytes, bytesize):
93*061da546Spatrick    """Utility function to convert a bytearray into an integer.
94*061da546Spatrick
95*061da546Spatrick    It interprets the bytearray in the little endian format. For a big endian
96*061da546Spatrick    bytearray, just do ba.reverse() on the object before passing it in.
97*061da546Spatrick    """
98*061da546Spatrick    import struct
99*061da546Spatrick
100*061da546Spatrick    if bytesize == 1:
101*061da546Spatrick        return bytes[0]
102*061da546Spatrick
103*061da546Spatrick    # Little endian followed by a format character.
104*061da546Spatrick    template = "<%c"
105*061da546Spatrick    if bytesize == 2:
106*061da546Spatrick        fmt = template % 'h'
107*061da546Spatrick    elif bytesize == 4:
108*061da546Spatrick        fmt = template % 'i'
109*061da546Spatrick    elif bytesize == 4:
110*061da546Spatrick        fmt = template % 'q'
111*061da546Spatrick    else:
112*061da546Spatrick        return None
113*061da546Spatrick
114*061da546Spatrick    unpacked = struct.unpack(fmt, str(bytes))
115*061da546Spatrick    return unpacked[0]
116*061da546Spatrick
117*061da546Spatrick
118*061da546Spatrick# ==============================================================
119*061da546Spatrick# Get the description of an lldb object or None if not available
120*061da546Spatrick# ==============================================================
121*061da546Spatrickdef get_description(obj, option=None):
122*061da546Spatrick    """Calls lldb_obj.GetDescription() and returns a string, or None.
123*061da546Spatrick
124*061da546Spatrick    For SBTarget, SBBreakpointLocation, and SBWatchpoint lldb objects, an extra
125*061da546Spatrick    option can be passed in to describe the detailed level of description
126*061da546Spatrick    desired:
127*061da546Spatrick        o lldb.eDescriptionLevelBrief
128*061da546Spatrick        o lldb.eDescriptionLevelFull
129*061da546Spatrick        o lldb.eDescriptionLevelVerbose
130*061da546Spatrick    """
131*061da546Spatrick    method = getattr(obj, 'GetDescription')
132*061da546Spatrick    if not method:
133*061da546Spatrick        return None
134*061da546Spatrick    tuple = (lldb.SBTarget, lldb.SBBreakpointLocation, lldb.SBWatchpoint)
135*061da546Spatrick    if isinstance(obj, tuple):
136*061da546Spatrick        if option is None:
137*061da546Spatrick            option = lldb.eDescriptionLevelBrief
138*061da546Spatrick
139*061da546Spatrick    stream = lldb.SBStream()
140*061da546Spatrick    if option is None:
141*061da546Spatrick        success = method(stream)
142*061da546Spatrick    else:
143*061da546Spatrick        success = method(stream, option)
144*061da546Spatrick    if not success:
145*061da546Spatrick        return None
146*061da546Spatrick    return stream.GetData()
147*061da546Spatrick
148*061da546Spatrick
149*061da546Spatrick# =================================================
150*061da546Spatrick# Convert some enum value to its string counterpart
151*061da546Spatrick# =================================================
152*061da546Spatrick
153*061da546Spatrickdef state_type_to_str(enum):
154*061da546Spatrick    """Returns the stateType string given an enum."""
155*061da546Spatrick    if enum == lldb.eStateInvalid:
156*061da546Spatrick        return "invalid"
157*061da546Spatrick    elif enum == lldb.eStateUnloaded:
158*061da546Spatrick        return "unloaded"
159*061da546Spatrick    elif enum == lldb.eStateConnected:
160*061da546Spatrick        return "connected"
161*061da546Spatrick    elif enum == lldb.eStateAttaching:
162*061da546Spatrick        return "attaching"
163*061da546Spatrick    elif enum == lldb.eStateLaunching:
164*061da546Spatrick        return "launching"
165*061da546Spatrick    elif enum == lldb.eStateStopped:
166*061da546Spatrick        return "stopped"
167*061da546Spatrick    elif enum == lldb.eStateRunning:
168*061da546Spatrick        return "running"
169*061da546Spatrick    elif enum == lldb.eStateStepping:
170*061da546Spatrick        return "stepping"
171*061da546Spatrick    elif enum == lldb.eStateCrashed:
172*061da546Spatrick        return "crashed"
173*061da546Spatrick    elif enum == lldb.eStateDetached:
174*061da546Spatrick        return "detached"
175*061da546Spatrick    elif enum == lldb.eStateExited:
176*061da546Spatrick        return "exited"
177*061da546Spatrick    elif enum == lldb.eStateSuspended:
178*061da546Spatrick        return "suspended"
179*061da546Spatrick    else:
180*061da546Spatrick        raise Exception("Unknown StateType enum")
181*061da546Spatrick
182*061da546Spatrick
183*061da546Spatrickdef stop_reason_to_str(enum):
184*061da546Spatrick    """Returns the stopReason string given an enum."""
185*061da546Spatrick    if enum == lldb.eStopReasonInvalid:
186*061da546Spatrick        return "invalid"
187*061da546Spatrick    elif enum == lldb.eStopReasonNone:
188*061da546Spatrick        return "none"
189*061da546Spatrick    elif enum == lldb.eStopReasonTrace:
190*061da546Spatrick        return "trace"
191*061da546Spatrick    elif enum == lldb.eStopReasonBreakpoint:
192*061da546Spatrick        return "breakpoint"
193*061da546Spatrick    elif enum == lldb.eStopReasonWatchpoint:
194*061da546Spatrick        return "watchpoint"
195*061da546Spatrick    elif enum == lldb.eStopReasonSignal:
196*061da546Spatrick        return "signal"
197*061da546Spatrick    elif enum == lldb.eStopReasonException:
198*061da546Spatrick        return "exception"
199*061da546Spatrick    elif enum == lldb.eStopReasonPlanComplete:
200*061da546Spatrick        return "plancomplete"
201*061da546Spatrick    elif enum == lldb.eStopReasonThreadExiting:
202*061da546Spatrick        return "threadexiting"
203*061da546Spatrick    else:
204*061da546Spatrick        raise Exception("Unknown StopReason enum")
205*061da546Spatrick
206*061da546Spatrick
207*061da546Spatrickdef symbol_type_to_str(enum):
208*061da546Spatrick    """Returns the symbolType string given an enum."""
209*061da546Spatrick    if enum == lldb.eSymbolTypeInvalid:
210*061da546Spatrick        return "invalid"
211*061da546Spatrick    elif enum == lldb.eSymbolTypeAbsolute:
212*061da546Spatrick        return "absolute"
213*061da546Spatrick    elif enum == lldb.eSymbolTypeCode:
214*061da546Spatrick        return "code"
215*061da546Spatrick    elif enum == lldb.eSymbolTypeData:
216*061da546Spatrick        return "data"
217*061da546Spatrick    elif enum == lldb.eSymbolTypeTrampoline:
218*061da546Spatrick        return "trampoline"
219*061da546Spatrick    elif enum == lldb.eSymbolTypeRuntime:
220*061da546Spatrick        return "runtime"
221*061da546Spatrick    elif enum == lldb.eSymbolTypeException:
222*061da546Spatrick        return "exception"
223*061da546Spatrick    elif enum == lldb.eSymbolTypeSourceFile:
224*061da546Spatrick        return "sourcefile"
225*061da546Spatrick    elif enum == lldb.eSymbolTypeHeaderFile:
226*061da546Spatrick        return "headerfile"
227*061da546Spatrick    elif enum == lldb.eSymbolTypeObjectFile:
228*061da546Spatrick        return "objectfile"
229*061da546Spatrick    elif enum == lldb.eSymbolTypeCommonBlock:
230*061da546Spatrick        return "commonblock"
231*061da546Spatrick    elif enum == lldb.eSymbolTypeBlock:
232*061da546Spatrick        return "block"
233*061da546Spatrick    elif enum == lldb.eSymbolTypeLocal:
234*061da546Spatrick        return "local"
235*061da546Spatrick    elif enum == lldb.eSymbolTypeParam:
236*061da546Spatrick        return "param"
237*061da546Spatrick    elif enum == lldb.eSymbolTypeVariable:
238*061da546Spatrick        return "variable"
239*061da546Spatrick    elif enum == lldb.eSymbolTypeVariableType:
240*061da546Spatrick        return "variabletype"
241*061da546Spatrick    elif enum == lldb.eSymbolTypeLineEntry:
242*061da546Spatrick        return "lineentry"
243*061da546Spatrick    elif enum == lldb.eSymbolTypeLineHeader:
244*061da546Spatrick        return "lineheader"
245*061da546Spatrick    elif enum == lldb.eSymbolTypeScopeBegin:
246*061da546Spatrick        return "scopebegin"
247*061da546Spatrick    elif enum == lldb.eSymbolTypeScopeEnd:
248*061da546Spatrick        return "scopeend"
249*061da546Spatrick    elif enum == lldb.eSymbolTypeAdditional:
250*061da546Spatrick        return "additional"
251*061da546Spatrick    elif enum == lldb.eSymbolTypeCompiler:
252*061da546Spatrick        return "compiler"
253*061da546Spatrick    elif enum == lldb.eSymbolTypeInstrumentation:
254*061da546Spatrick        return "instrumentation"
255*061da546Spatrick    elif enum == lldb.eSymbolTypeUndefined:
256*061da546Spatrick        return "undefined"
257*061da546Spatrick
258*061da546Spatrick
259*061da546Spatrickdef value_type_to_str(enum):
260*061da546Spatrick    """Returns the valueType string given an enum."""
261*061da546Spatrick    if enum == lldb.eValueTypeInvalid:
262*061da546Spatrick        return "invalid"
263*061da546Spatrick    elif enum == lldb.eValueTypeVariableGlobal:
264*061da546Spatrick        return "global_variable"
265*061da546Spatrick    elif enum == lldb.eValueTypeVariableStatic:
266*061da546Spatrick        return "static_variable"
267*061da546Spatrick    elif enum == lldb.eValueTypeVariableArgument:
268*061da546Spatrick        return "argument_variable"
269*061da546Spatrick    elif enum == lldb.eValueTypeVariableLocal:
270*061da546Spatrick        return "local_variable"
271*061da546Spatrick    elif enum == lldb.eValueTypeRegister:
272*061da546Spatrick        return "register"
273*061da546Spatrick    elif enum == lldb.eValueTypeRegisterSet:
274*061da546Spatrick        return "register_set"
275*061da546Spatrick    elif enum == lldb.eValueTypeConstResult:
276*061da546Spatrick        return "constant_result"
277*061da546Spatrick    else:
278*061da546Spatrick        raise Exception("Unknown ValueType enum")
279*061da546Spatrick
280*061da546Spatrick
281*061da546Spatrick# ==================================================
282*061da546Spatrick# Get stopped threads due to each stop reason.
283*061da546Spatrick# ==================================================
284*061da546Spatrick
285*061da546Spatrickdef sort_stopped_threads(process,
286*061da546Spatrick                         breakpoint_threads=None,
287*061da546Spatrick                         crashed_threads=None,
288*061da546Spatrick                         watchpoint_threads=None,
289*061da546Spatrick                         signal_threads=None,
290*061da546Spatrick                         exiting_threads=None,
291*061da546Spatrick                         other_threads=None):
292*061da546Spatrick    """ Fills array *_threads with threads stopped for the corresponding stop
293*061da546Spatrick        reason.
294*061da546Spatrick    """
295*061da546Spatrick    for lst in [breakpoint_threads,
296*061da546Spatrick                watchpoint_threads,
297*061da546Spatrick                signal_threads,
298*061da546Spatrick                exiting_threads,
299*061da546Spatrick                other_threads]:
300*061da546Spatrick        if lst is not None:
301*061da546Spatrick            lst[:] = []
302*061da546Spatrick
303*061da546Spatrick    for thread in process:
304*061da546Spatrick        dispatched = False
305*061da546Spatrick        for (reason, list) in [(lldb.eStopReasonBreakpoint, breakpoint_threads),
306*061da546Spatrick                               (lldb.eStopReasonException, crashed_threads),
307*061da546Spatrick                               (lldb.eStopReasonWatchpoint, watchpoint_threads),
308*061da546Spatrick                               (lldb.eStopReasonSignal, signal_threads),
309*061da546Spatrick                               (lldb.eStopReasonThreadExiting, exiting_threads),
310*061da546Spatrick                               (None, other_threads)]:
311*061da546Spatrick            if not dispatched and list is not None:
312*061da546Spatrick                if thread.GetStopReason() == reason or reason is None:
313*061da546Spatrick                    list.append(thread)
314*061da546Spatrick                    dispatched = True
315*061da546Spatrick
316*061da546Spatrick# ==================================================
317*061da546Spatrick# Utility functions for setting breakpoints
318*061da546Spatrick# ==================================================
319*061da546Spatrick
320*061da546Spatrick
321*061da546Spatrickdef run_break_set_by_file_and_line(
322*061da546Spatrick        test,
323*061da546Spatrick        file_name,
324*061da546Spatrick        line_number,
325*061da546Spatrick        extra_options=None,
326*061da546Spatrick        num_expected_locations=1,
327*061da546Spatrick        loc_exact=False,
328*061da546Spatrick        module_name=None):
329*061da546Spatrick    """Set a breakpoint by file and line, returning the breakpoint number.
330*061da546Spatrick
331*061da546Spatrick    If extra_options is not None, then we append it to the breakpoint set command.
332*061da546Spatrick
333*061da546Spatrick    If num_expected_locations is -1 we check that we got AT LEAST one location, otherwise we check that num_expected_locations equals the number of locations.
334*061da546Spatrick
335*061da546Spatrick    If loc_exact is true, we check that there is one location, and that location must be at the input file and line number."""
336*061da546Spatrick
337*061da546Spatrick    if file_name is None:
338*061da546Spatrick        command = 'breakpoint set -l %d' % (line_number)
339*061da546Spatrick    else:
340*061da546Spatrick        command = 'breakpoint set -f "%s" -l %d' % (file_name, line_number)
341*061da546Spatrick
342*061da546Spatrick    if module_name:
343*061da546Spatrick        command += " --shlib '%s'" % (module_name)
344*061da546Spatrick
345*061da546Spatrick    if extra_options:
346*061da546Spatrick        command += " " + extra_options
347*061da546Spatrick
348*061da546Spatrick    break_results = run_break_set_command(test, command)
349*061da546Spatrick
350*061da546Spatrick    if num_expected_locations == 1 and loc_exact:
351*061da546Spatrick        check_breakpoint_result(
352*061da546Spatrick            test,
353*061da546Spatrick            break_results,
354*061da546Spatrick            num_locations=num_expected_locations,
355*061da546Spatrick            file_name=file_name,
356*061da546Spatrick            line_number=line_number,
357*061da546Spatrick            module_name=module_name)
358*061da546Spatrick    else:
359*061da546Spatrick        check_breakpoint_result(
360*061da546Spatrick            test,
361*061da546Spatrick            break_results,
362*061da546Spatrick            num_locations=num_expected_locations)
363*061da546Spatrick
364*061da546Spatrick    return get_bpno_from_match(break_results)
365*061da546Spatrick
366*061da546Spatrick
367*061da546Spatrickdef run_break_set_by_symbol(
368*061da546Spatrick        test,
369*061da546Spatrick        symbol,
370*061da546Spatrick        extra_options=None,
371*061da546Spatrick        num_expected_locations=-1,
372*061da546Spatrick        sym_exact=False,
373*061da546Spatrick        module_name=None):
374*061da546Spatrick    """Set a breakpoint by symbol name.  Common options are the same as run_break_set_by_file_and_line.
375*061da546Spatrick
376*061da546Spatrick    If sym_exact is true, then the output symbol must match the input exactly, otherwise we do a substring match."""
377*061da546Spatrick    command = 'breakpoint set -n "%s"' % (symbol)
378*061da546Spatrick
379*061da546Spatrick    if module_name:
380*061da546Spatrick        command += " --shlib '%s'" % (module_name)
381*061da546Spatrick
382*061da546Spatrick    if extra_options:
383*061da546Spatrick        command += " " + extra_options
384*061da546Spatrick
385*061da546Spatrick    break_results = run_break_set_command(test, command)
386*061da546Spatrick
387*061da546Spatrick    if num_expected_locations == 1 and sym_exact:
388*061da546Spatrick        check_breakpoint_result(
389*061da546Spatrick            test,
390*061da546Spatrick            break_results,
391*061da546Spatrick            num_locations=num_expected_locations,
392*061da546Spatrick            symbol_name=symbol,
393*061da546Spatrick            module_name=module_name)
394*061da546Spatrick    else:
395*061da546Spatrick        check_breakpoint_result(
396*061da546Spatrick            test,
397*061da546Spatrick            break_results,
398*061da546Spatrick            num_locations=num_expected_locations)
399*061da546Spatrick
400*061da546Spatrick    return get_bpno_from_match(break_results)
401*061da546Spatrick
402*061da546Spatrick
403*061da546Spatrickdef run_break_set_by_selector(
404*061da546Spatrick        test,
405*061da546Spatrick        selector,
406*061da546Spatrick        extra_options=None,
407*061da546Spatrick        num_expected_locations=-1,
408*061da546Spatrick        module_name=None):
409*061da546Spatrick    """Set a breakpoint by selector.  Common options are the same as run_break_set_by_file_and_line."""
410*061da546Spatrick
411*061da546Spatrick    command = 'breakpoint set -S "%s"' % (selector)
412*061da546Spatrick
413*061da546Spatrick    if module_name:
414*061da546Spatrick        command += ' --shlib "%s"' % (module_name)
415*061da546Spatrick
416*061da546Spatrick    if extra_options:
417*061da546Spatrick        command += " " + extra_options
418*061da546Spatrick
419*061da546Spatrick    break_results = run_break_set_command(test, command)
420*061da546Spatrick
421*061da546Spatrick    if num_expected_locations == 1:
422*061da546Spatrick        check_breakpoint_result(
423*061da546Spatrick            test,
424*061da546Spatrick            break_results,
425*061da546Spatrick            num_locations=num_expected_locations,
426*061da546Spatrick            symbol_name=selector,
427*061da546Spatrick            symbol_match_exact=False,
428*061da546Spatrick            module_name=module_name)
429*061da546Spatrick    else:
430*061da546Spatrick        check_breakpoint_result(
431*061da546Spatrick            test,
432*061da546Spatrick            break_results,
433*061da546Spatrick            num_locations=num_expected_locations)
434*061da546Spatrick
435*061da546Spatrick    return get_bpno_from_match(break_results)
436*061da546Spatrick
437*061da546Spatrick
438*061da546Spatrickdef run_break_set_by_regexp(
439*061da546Spatrick        test,
440*061da546Spatrick        regexp,
441*061da546Spatrick        extra_options=None,
442*061da546Spatrick        num_expected_locations=-1):
443*061da546Spatrick    """Set a breakpoint by regular expression match on symbol name.  Common options are the same as run_break_set_by_file_and_line."""
444*061da546Spatrick
445*061da546Spatrick    command = 'breakpoint set -r "%s"' % (regexp)
446*061da546Spatrick    if extra_options:
447*061da546Spatrick        command += " " + extra_options
448*061da546Spatrick
449*061da546Spatrick    break_results = run_break_set_command(test, command)
450*061da546Spatrick
451*061da546Spatrick    check_breakpoint_result(
452*061da546Spatrick        test,
453*061da546Spatrick        break_results,
454*061da546Spatrick        num_locations=num_expected_locations)
455*061da546Spatrick
456*061da546Spatrick    return get_bpno_from_match(break_results)
457*061da546Spatrick
458*061da546Spatrick
459*061da546Spatrickdef run_break_set_by_source_regexp(
460*061da546Spatrick        test,
461*061da546Spatrick        regexp,
462*061da546Spatrick        extra_options=None,
463*061da546Spatrick        num_expected_locations=-1):
464*061da546Spatrick    """Set a breakpoint by source regular expression.  Common options are the same as run_break_set_by_file_and_line."""
465*061da546Spatrick    command = 'breakpoint set -p "%s"' % (regexp)
466*061da546Spatrick    if extra_options:
467*061da546Spatrick        command += " " + extra_options
468*061da546Spatrick
469*061da546Spatrick    break_results = run_break_set_command(test, command)
470*061da546Spatrick
471*061da546Spatrick    check_breakpoint_result(
472*061da546Spatrick        test,
473*061da546Spatrick        break_results,
474*061da546Spatrick        num_locations=num_expected_locations)
475*061da546Spatrick
476*061da546Spatrick    return get_bpno_from_match(break_results)
477*061da546Spatrick
478*061da546Spatrick
479*061da546Spatrickdef run_break_set_command(test, command):
480*061da546Spatrick    """Run the command passed in - it must be some break set variant - and analyze the result.
481*061da546Spatrick    Returns a dictionary of information gleaned from the command-line results.
482*061da546Spatrick    Will assert if the breakpoint setting fails altogether.
483*061da546Spatrick
484*061da546Spatrick    Dictionary will contain:
485*061da546Spatrick        bpno          - breakpoint of the newly created breakpoint, -1 on error.
486*061da546Spatrick        num_locations - number of locations set for the breakpoint.
487*061da546Spatrick
488*061da546Spatrick    If there is only one location, the dictionary MAY contain:
489*061da546Spatrick        file          - source file name
490*061da546Spatrick        line_no       - source line number
491*061da546Spatrick        symbol        - symbol name
492*061da546Spatrick        inline_symbol - inlined symbol name
493*061da546Spatrick        offset        - offset from the original symbol
494*061da546Spatrick        module        - module
495*061da546Spatrick        address       - address at which the breakpoint was set."""
496*061da546Spatrick
497*061da546Spatrick    patterns = [
498*061da546Spatrick        r"^Breakpoint (?P<bpno>[0-9]+): (?P<num_locations>[0-9]+) locations\.$",
499*061da546Spatrick        r"^Breakpoint (?P<bpno>[0-9]+): (?P<num_locations>no) locations \(pending\)\.",
500*061da546Spatrick        r"^Breakpoint (?P<bpno>[0-9]+): where = (?P<module>.*)`(?P<symbol>[+\-]{0,1}[^+]+)( \+ (?P<offset>[0-9]+)){0,1}( \[inlined\] (?P<inline_symbol>.*)){0,1} at (?P<file>[^:]+):(?P<line_no>[0-9]+), address = (?P<address>0x[0-9a-fA-F]+)$",
501*061da546Spatrick        r"^Breakpoint (?P<bpno>[0-9]+): where = (?P<module>.*)`(?P<symbol>.*)( \+ (?P<offset>[0-9]+)){0,1}, address = (?P<address>0x[0-9a-fA-F]+)$"]
502*061da546Spatrick    match_object = test.match(command, patterns)
503*061da546Spatrick    break_results = match_object.groupdict()
504*061da546Spatrick
505*061da546Spatrick    # We always insert the breakpoint number, setting it to -1 if we couldn't find it
506*061da546Spatrick    # Also, make sure it gets stored as an integer.
507*061da546Spatrick    if not 'bpno' in break_results:
508*061da546Spatrick        break_results['bpno'] = -1
509*061da546Spatrick    else:
510*061da546Spatrick        break_results['bpno'] = int(break_results['bpno'])
511*061da546Spatrick
512*061da546Spatrick    # We always insert the number of locations
513*061da546Spatrick    # If ONE location is set for the breakpoint, then the output doesn't mention locations, but it has to be 1...
514*061da546Spatrick    # We also make sure it is an integer.
515*061da546Spatrick
516*061da546Spatrick    if not 'num_locations' in break_results:
517*061da546Spatrick        num_locations = 1
518*061da546Spatrick    else:
519*061da546Spatrick        num_locations = break_results['num_locations']
520*061da546Spatrick        if num_locations == 'no':
521*061da546Spatrick            num_locations = 0
522*061da546Spatrick        else:
523*061da546Spatrick            num_locations = int(break_results['num_locations'])
524*061da546Spatrick
525*061da546Spatrick    break_results['num_locations'] = num_locations
526*061da546Spatrick
527*061da546Spatrick    if 'line_no' in break_results:
528*061da546Spatrick        break_results['line_no'] = int(break_results['line_no'])
529*061da546Spatrick
530*061da546Spatrick    return break_results
531*061da546Spatrick
532*061da546Spatrick
533*061da546Spatrickdef get_bpno_from_match(break_results):
534*061da546Spatrick    return int(break_results['bpno'])
535*061da546Spatrick
536*061da546Spatrick
537*061da546Spatrickdef check_breakpoint_result(
538*061da546Spatrick        test,
539*061da546Spatrick        break_results,
540*061da546Spatrick        file_name=None,
541*061da546Spatrick        line_number=-1,
542*061da546Spatrick        symbol_name=None,
543*061da546Spatrick        symbol_match_exact=True,
544*061da546Spatrick        module_name=None,
545*061da546Spatrick        offset=-1,
546*061da546Spatrick        num_locations=-1):
547*061da546Spatrick
548*061da546Spatrick    out_num_locations = break_results['num_locations']
549*061da546Spatrick
550*061da546Spatrick    if num_locations == -1:
551*061da546Spatrick        test.assertTrue(out_num_locations > 0,
552*061da546Spatrick                        "Expecting one or more locations, got none.")
553*061da546Spatrick    else:
554*061da546Spatrick        test.assertTrue(
555*061da546Spatrick            num_locations == out_num_locations,
556*061da546Spatrick            "Expecting %d locations, got %d." %
557*061da546Spatrick            (num_locations,
558*061da546Spatrick             out_num_locations))
559*061da546Spatrick
560*061da546Spatrick    if file_name:
561*061da546Spatrick        out_file_name = ""
562*061da546Spatrick        if 'file' in break_results:
563*061da546Spatrick            out_file_name = break_results['file']
564*061da546Spatrick        test.assertTrue(
565*061da546Spatrick            file_name == out_file_name,
566*061da546Spatrick            "Breakpoint file name '%s' doesn't match resultant name '%s'." %
567*061da546Spatrick            (file_name,
568*061da546Spatrick             out_file_name))
569*061da546Spatrick
570*061da546Spatrick    if line_number != -1:
571*061da546Spatrick        out_file_line = -1
572*061da546Spatrick        if 'line_no' in break_results:
573*061da546Spatrick            out_line_number = break_results['line_no']
574*061da546Spatrick
575*061da546Spatrick        test.assertTrue(
576*061da546Spatrick            line_number == out_line_number,
577*061da546Spatrick            "Breakpoint line number %s doesn't match resultant line %s." %
578*061da546Spatrick            (line_number,
579*061da546Spatrick             out_line_number))
580*061da546Spatrick
581*061da546Spatrick    if symbol_name:
582*061da546Spatrick        out_symbol_name = ""
583*061da546Spatrick        # Look first for the inlined symbol name, otherwise use the symbol
584*061da546Spatrick        # name:
585*061da546Spatrick        if 'inline_symbol' in break_results and break_results['inline_symbol']:
586*061da546Spatrick            out_symbol_name = break_results['inline_symbol']
587*061da546Spatrick        elif 'symbol' in break_results:
588*061da546Spatrick            out_symbol_name = break_results['symbol']
589*061da546Spatrick
590*061da546Spatrick        if symbol_match_exact:
591*061da546Spatrick            test.assertTrue(
592*061da546Spatrick                symbol_name == out_symbol_name,
593*061da546Spatrick                "Symbol name '%s' doesn't match resultant symbol '%s'." %
594*061da546Spatrick                (symbol_name,
595*061da546Spatrick                 out_symbol_name))
596*061da546Spatrick        else:
597*061da546Spatrick            test.assertTrue(
598*061da546Spatrick                out_symbol_name.find(symbol_name) != -
599*061da546Spatrick                1,
600*061da546Spatrick                "Symbol name '%s' isn't in resultant symbol '%s'." %
601*061da546Spatrick                (symbol_name,
602*061da546Spatrick                 out_symbol_name))
603*061da546Spatrick
604*061da546Spatrick    if module_name:
605*061da546Spatrick        out_nodule_name = None
606*061da546Spatrick        if 'module' in break_results:
607*061da546Spatrick            out_module_name = break_results['module']
608*061da546Spatrick
609*061da546Spatrick        test.assertTrue(
610*061da546Spatrick            module_name.find(out_module_name) != -
611*061da546Spatrick            1,
612*061da546Spatrick            "Symbol module name '%s' isn't in expected module name '%s'." %
613*061da546Spatrick            (out_module_name,
614*061da546Spatrick             module_name))
615*061da546Spatrick
616*061da546Spatrick# ==================================================
617*061da546Spatrick# Utility functions related to Threads and Processes
618*061da546Spatrick# ==================================================
619*061da546Spatrick
620*061da546Spatrick
621*061da546Spatrickdef get_stopped_threads(process, reason):
622*061da546Spatrick    """Returns the thread(s) with the specified stop reason in a list.
623*061da546Spatrick
624*061da546Spatrick    The list can be empty if no such thread exists.
625*061da546Spatrick    """
626*061da546Spatrick    threads = []
627*061da546Spatrick    for t in process:
628*061da546Spatrick        if t.GetStopReason() == reason:
629*061da546Spatrick            threads.append(t)
630*061da546Spatrick    return threads
631*061da546Spatrick
632*061da546Spatrick
633*061da546Spatrickdef get_stopped_thread(process, reason):
634*061da546Spatrick    """A convenience function which returns the first thread with the given stop
635*061da546Spatrick    reason or None.
636*061da546Spatrick
637*061da546Spatrick    Example usages:
638*061da546Spatrick
639*061da546Spatrick    1. Get the stopped thread due to a breakpoint condition
640*061da546Spatrick
641*061da546Spatrick    ...
642*061da546Spatrick        from lldbutil import get_stopped_thread
643*061da546Spatrick        thread = get_stopped_thread(process, lldb.eStopReasonPlanComplete)
644*061da546Spatrick        self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
645*061da546Spatrick    ...
646*061da546Spatrick
647*061da546Spatrick    2. Get the thread stopped due to a breakpoint
648*061da546Spatrick
649*061da546Spatrick    ...
650*061da546Spatrick        from lldbutil import get_stopped_thread
651*061da546Spatrick        thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
652*061da546Spatrick        self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
653*061da546Spatrick    ...
654*061da546Spatrick
655*061da546Spatrick    """
656*061da546Spatrick    threads = get_stopped_threads(process, reason)
657*061da546Spatrick    if len(threads) == 0:
658*061da546Spatrick        return None
659*061da546Spatrick    return threads[0]
660*061da546Spatrick
661*061da546Spatrick
662*061da546Spatrickdef get_threads_stopped_at_breakpoint(process, bkpt):
663*061da546Spatrick    """ For a stopped process returns the thread stopped at the breakpoint passed in bkpt"""
664*061da546Spatrick    stopped_threads = []
665*061da546Spatrick    threads = []
666*061da546Spatrick
667*061da546Spatrick    stopped_threads = get_stopped_threads(process, lldb.eStopReasonBreakpoint)
668*061da546Spatrick
669*061da546Spatrick    if len(stopped_threads) == 0:
670*061da546Spatrick        return threads
671*061da546Spatrick
672*061da546Spatrick    for thread in stopped_threads:
673*061da546Spatrick        # Make sure we've hit our breakpoint...
674*061da546Spatrick        break_id = thread.GetStopReasonDataAtIndex(0)
675*061da546Spatrick        if break_id == bkpt.GetID():
676*061da546Spatrick            threads.append(thread)
677*061da546Spatrick
678*061da546Spatrick    return threads
679*061da546Spatrick
680*061da546Spatrick
681*061da546Spatrickdef continue_to_breakpoint(process, bkpt):
682*061da546Spatrick    """ Continues the process, if it stops, returns the threads stopped at bkpt; otherwise, returns None"""
683*061da546Spatrick    process.Continue()
684*061da546Spatrick    if process.GetState() != lldb.eStateStopped:
685*061da546Spatrick        return None
686*061da546Spatrick    else:
687*061da546Spatrick        return get_threads_stopped_at_breakpoint(process, bkpt)
688*061da546Spatrick
689*061da546Spatrick
690*061da546Spatrickdef get_caller_symbol(thread):
691*061da546Spatrick    """
692*061da546Spatrick    Returns the symbol name for the call site of the leaf function.
693*061da546Spatrick    """
694*061da546Spatrick    depth = thread.GetNumFrames()
695*061da546Spatrick    if depth <= 1:
696*061da546Spatrick        return None
697*061da546Spatrick    caller = thread.GetFrameAtIndex(1).GetSymbol()
698*061da546Spatrick    if caller:
699*061da546Spatrick        return caller.GetName()
700*061da546Spatrick    else:
701*061da546Spatrick        return None
702*061da546Spatrick
703*061da546Spatrick
704*061da546Spatrickdef get_function_names(thread):
705*061da546Spatrick    """
706*061da546Spatrick    Returns a sequence of function names from the stack frames of this thread.
707*061da546Spatrick    """
708*061da546Spatrick    def GetFuncName(i):
709*061da546Spatrick        return thread.GetFrameAtIndex(i).GetFunctionName()
710*061da546Spatrick
711*061da546Spatrick    return [GetFuncName(i) for i in range(thread.GetNumFrames())]
712*061da546Spatrick
713*061da546Spatrick
714*061da546Spatrickdef get_symbol_names(thread):
715*061da546Spatrick    """
716*061da546Spatrick    Returns a sequence of symbols for this thread.
717*061da546Spatrick    """
718*061da546Spatrick    def GetSymbol(i):
719*061da546Spatrick        return thread.GetFrameAtIndex(i).GetSymbol().GetName()
720*061da546Spatrick
721*061da546Spatrick    return [GetSymbol(i) for i in range(thread.GetNumFrames())]
722*061da546Spatrick
723*061da546Spatrick
724*061da546Spatrickdef get_pc_addresses(thread):
725*061da546Spatrick    """
726*061da546Spatrick    Returns a sequence of pc addresses for this thread.
727*061da546Spatrick    """
728*061da546Spatrick    def GetPCAddress(i):
729*061da546Spatrick        return thread.GetFrameAtIndex(i).GetPCAddress()
730*061da546Spatrick
731*061da546Spatrick    return [GetPCAddress(i) for i in range(thread.GetNumFrames())]
732*061da546Spatrick
733*061da546Spatrick
734*061da546Spatrickdef get_filenames(thread):
735*061da546Spatrick    """
736*061da546Spatrick    Returns a sequence of file names from the stack frames of this thread.
737*061da546Spatrick    """
738*061da546Spatrick    def GetFilename(i):
739*061da546Spatrick        return thread.GetFrameAtIndex(
740*061da546Spatrick            i).GetLineEntry().GetFileSpec().GetFilename()
741*061da546Spatrick
742*061da546Spatrick    return [GetFilename(i) for i in range(thread.GetNumFrames())]
743*061da546Spatrick
744*061da546Spatrick
745*061da546Spatrickdef get_line_numbers(thread):
746*061da546Spatrick    """
747*061da546Spatrick    Returns a sequence of line numbers from the stack frames of this thread.
748*061da546Spatrick    """
749*061da546Spatrick    def GetLineNumber(i):
750*061da546Spatrick        return thread.GetFrameAtIndex(i).GetLineEntry().GetLine()
751*061da546Spatrick
752*061da546Spatrick    return [GetLineNumber(i) for i in range(thread.GetNumFrames())]
753*061da546Spatrick
754*061da546Spatrick
755*061da546Spatrickdef get_module_names(thread):
756*061da546Spatrick    """
757*061da546Spatrick    Returns a sequence of module names from the stack frames of this thread.
758*061da546Spatrick    """
759*061da546Spatrick    def GetModuleName(i):
760*061da546Spatrick        return thread.GetFrameAtIndex(
761*061da546Spatrick            i).GetModule().GetFileSpec().GetFilename()
762*061da546Spatrick
763*061da546Spatrick    return [GetModuleName(i) for i in range(thread.GetNumFrames())]
764*061da546Spatrick
765*061da546Spatrick
766*061da546Spatrickdef get_stack_frames(thread):
767*061da546Spatrick    """
768*061da546Spatrick    Returns a sequence of stack frames for this thread.
769*061da546Spatrick    """
770*061da546Spatrick    def GetStackFrame(i):
771*061da546Spatrick        return thread.GetFrameAtIndex(i)
772*061da546Spatrick
773*061da546Spatrick    return [GetStackFrame(i) for i in range(thread.GetNumFrames())]
774*061da546Spatrick
775*061da546Spatrick
776*061da546Spatrickdef print_stacktrace(thread, string_buffer=False):
777*061da546Spatrick    """Prints a simple stack trace of this thread."""
778*061da546Spatrick
779*061da546Spatrick    output = io.StringIO() if string_buffer else sys.stdout
780*061da546Spatrick    target = thread.GetProcess().GetTarget()
781*061da546Spatrick
782*061da546Spatrick    depth = thread.GetNumFrames()
783*061da546Spatrick
784*061da546Spatrick    mods = get_module_names(thread)
785*061da546Spatrick    funcs = get_function_names(thread)
786*061da546Spatrick    symbols = get_symbol_names(thread)
787*061da546Spatrick    files = get_filenames(thread)
788*061da546Spatrick    lines = get_line_numbers(thread)
789*061da546Spatrick    addrs = get_pc_addresses(thread)
790*061da546Spatrick
791*061da546Spatrick    if thread.GetStopReason() != lldb.eStopReasonInvalid:
792*061da546Spatrick        desc = "stop reason=" + stop_reason_to_str(thread.GetStopReason())
793*061da546Spatrick    else:
794*061da546Spatrick        desc = ""
795*061da546Spatrick    print("Stack trace for thread id={0:#x} name={1} queue={2} ".format(
796*061da546Spatrick        thread.GetThreadID(), thread.GetName(), thread.GetQueueName()) + desc, file=output)
797*061da546Spatrick
798*061da546Spatrick    for i in range(depth):
799*061da546Spatrick        frame = thread.GetFrameAtIndex(i)
800*061da546Spatrick        function = frame.GetFunction()
801*061da546Spatrick
802*061da546Spatrick        load_addr = addrs[i].GetLoadAddress(target)
803*061da546Spatrick        if not function:
804*061da546Spatrick            file_addr = addrs[i].GetFileAddress()
805*061da546Spatrick            start_addr = frame.GetSymbol().GetStartAddress().GetFileAddress()
806*061da546Spatrick            symbol_offset = file_addr - start_addr
807*061da546Spatrick            print("  frame #{num}: {addr:#016x} {mod}`{symbol} + {offset}".format(
808*061da546Spatrick                num=i, addr=load_addr, mod=mods[i], symbol=symbols[i], offset=symbol_offset), file=output)
809*061da546Spatrick        else:
810*061da546Spatrick            print("  frame #{num}: {addr:#016x} {mod}`{func} at {file}:{line} {args}".format(
811*061da546Spatrick                num=i, addr=load_addr, mod=mods[i], func='%s [inlined]' %
812*061da546Spatrick                funcs[i] if frame.IsInlined() else funcs[i], file=files[i], line=lines[i], args=get_args_as_string(
813*061da546Spatrick                    frame, showFuncName=False) if not frame.IsInlined() else '()'), file=output)
814*061da546Spatrick
815*061da546Spatrick    if string_buffer:
816*061da546Spatrick        return output.getvalue()
817*061da546Spatrick
818*061da546Spatrick
819*061da546Spatrickdef print_stacktraces(process, string_buffer=False):
820*061da546Spatrick    """Prints the stack traces of all the threads."""
821*061da546Spatrick
822*061da546Spatrick    output = io.StringIO() if string_buffer else sys.stdout
823*061da546Spatrick
824*061da546Spatrick    print("Stack traces for " + str(process), file=output)
825*061da546Spatrick
826*061da546Spatrick    for thread in process:
827*061da546Spatrick        print(print_stacktrace(thread, string_buffer=True), file=output)
828*061da546Spatrick
829*061da546Spatrick    if string_buffer:
830*061da546Spatrick        return output.getvalue()
831*061da546Spatrick
832*061da546Spatrick# ===================================
833*061da546Spatrick# Utility functions related to Frames
834*061da546Spatrick# ===================================
835*061da546Spatrick
836*061da546Spatrick
837*061da546Spatrickdef get_parent_frame(frame):
838*061da546Spatrick    """
839*061da546Spatrick    Returns the parent frame of the input frame object; None if not available.
840*061da546Spatrick    """
841*061da546Spatrick    thread = frame.GetThread()
842*061da546Spatrick    parent_found = False
843*061da546Spatrick    for f in thread:
844*061da546Spatrick        if parent_found:
845*061da546Spatrick            return f
846*061da546Spatrick        if f.GetFrameID() == frame.GetFrameID():
847*061da546Spatrick            parent_found = True
848*061da546Spatrick
849*061da546Spatrick    # If we reach here, no parent has been found, return None.
850*061da546Spatrick    return None
851*061da546Spatrick
852*061da546Spatrick
853*061da546Spatrickdef get_args_as_string(frame, showFuncName=True):
854*061da546Spatrick    """
855*061da546Spatrick    Returns the args of the input frame object as a string.
856*061da546Spatrick    """
857*061da546Spatrick    # arguments     => True
858*061da546Spatrick    # locals        => False
859*061da546Spatrick    # statics       => False
860*061da546Spatrick    # in_scope_only => True
861*061da546Spatrick    vars = frame.GetVariables(True, False, False, True)  # type of SBValueList
862*061da546Spatrick    args = []  # list of strings
863*061da546Spatrick    for var in vars:
864*061da546Spatrick        args.append("(%s)%s=%s" % (var.GetTypeName(),
865*061da546Spatrick                                   var.GetName(),
866*061da546Spatrick                                   var.GetValue()))
867*061da546Spatrick    if frame.GetFunction():
868*061da546Spatrick        name = frame.GetFunction().GetName()
869*061da546Spatrick    elif frame.GetSymbol():
870*061da546Spatrick        name = frame.GetSymbol().GetName()
871*061da546Spatrick    else:
872*061da546Spatrick        name = ""
873*061da546Spatrick    if showFuncName:
874*061da546Spatrick        return "%s(%s)" % (name, ", ".join(args))
875*061da546Spatrick    else:
876*061da546Spatrick        return "(%s)" % (", ".join(args))
877*061da546Spatrick
878*061da546Spatrick
879*061da546Spatrickdef print_registers(frame, string_buffer=False):
880*061da546Spatrick    """Prints all the register sets of the frame."""
881*061da546Spatrick
882*061da546Spatrick    output = io.StringIO() if string_buffer else sys.stdout
883*061da546Spatrick
884*061da546Spatrick    print("Register sets for " + str(frame), file=output)
885*061da546Spatrick
886*061da546Spatrick    registerSet = frame.GetRegisters()  # Return type of SBValueList.
887*061da546Spatrick    print("Frame registers (size of register set = %d):" % registerSet.GetSize(
888*061da546Spatrick    ), file=output)
889*061da546Spatrick    for value in registerSet:
890*061da546Spatrick        #print >> output, value
891*061da546Spatrick        print("%s (number of children = %d):" % (
892*061da546Spatrick            value.GetName(), value.GetNumChildren()), file=output)
893*061da546Spatrick        for child in value:
894*061da546Spatrick            print("Name: %s, Value: %s" % (
895*061da546Spatrick                child.GetName(), child.GetValue()), file=output)
896*061da546Spatrick
897*061da546Spatrick    if string_buffer:
898*061da546Spatrick        return output.getvalue()
899*061da546Spatrick
900*061da546Spatrick
901*061da546Spatrickdef get_registers(frame, kind):
902*061da546Spatrick    """Returns the registers given the frame and the kind of registers desired.
903*061da546Spatrick
904*061da546Spatrick    Returns None if there's no such kind.
905*061da546Spatrick    """
906*061da546Spatrick    registerSet = frame.GetRegisters()  # Return type of SBValueList.
907*061da546Spatrick    for value in registerSet:
908*061da546Spatrick        if kind.lower() in value.GetName().lower():
909*061da546Spatrick            return value
910*061da546Spatrick
911*061da546Spatrick    return None
912*061da546Spatrick
913*061da546Spatrick
914*061da546Spatrickdef get_GPRs(frame):
915*061da546Spatrick    """Returns the general purpose registers of the frame as an SBValue.
916*061da546Spatrick
917*061da546Spatrick    The returned SBValue object is iterable.  An example:
918*061da546Spatrick        ...
919*061da546Spatrick        from lldbutil import get_GPRs
920*061da546Spatrick        regs = get_GPRs(frame)
921*061da546Spatrick        for reg in regs:
922*061da546Spatrick            print "%s => %s" % (reg.GetName(), reg.GetValue())
923*061da546Spatrick        ...
924*061da546Spatrick    """
925*061da546Spatrick    return get_registers(frame, "general purpose")
926*061da546Spatrick
927*061da546Spatrick
928*061da546Spatrickdef get_FPRs(frame):
929*061da546Spatrick    """Returns the floating point registers of the frame as an SBValue.
930*061da546Spatrick
931*061da546Spatrick    The returned SBValue object is iterable.  An example:
932*061da546Spatrick        ...
933*061da546Spatrick        from lldbutil import get_FPRs
934*061da546Spatrick        regs = get_FPRs(frame)
935*061da546Spatrick        for reg in regs:
936*061da546Spatrick            print "%s => %s" % (reg.GetName(), reg.GetValue())
937*061da546Spatrick        ...
938*061da546Spatrick    """
939*061da546Spatrick    return get_registers(frame, "floating point")
940*061da546Spatrick
941*061da546Spatrick
942*061da546Spatrickdef get_ESRs(frame):
943*061da546Spatrick    """Returns the exception state registers of the frame as an SBValue.
944*061da546Spatrick
945*061da546Spatrick    The returned SBValue object is iterable.  An example:
946*061da546Spatrick        ...
947*061da546Spatrick        from lldbutil import get_ESRs
948*061da546Spatrick        regs = get_ESRs(frame)
949*061da546Spatrick        for reg in regs:
950*061da546Spatrick            print "%s => %s" % (reg.GetName(), reg.GetValue())
951*061da546Spatrick        ...
952*061da546Spatrick    """
953*061da546Spatrick    return get_registers(frame, "exception state")
954*061da546Spatrick
955*061da546Spatrick# ======================================
956*061da546Spatrick# Utility classes/functions for SBValues
957*061da546Spatrick# ======================================
958*061da546Spatrick
959*061da546Spatrick
960*061da546Spatrickclass BasicFormatter(object):
961*061da546Spatrick    """The basic formatter inspects the value object and prints the value."""
962*061da546Spatrick
963*061da546Spatrick    def format(self, value, buffer=None, indent=0):
964*061da546Spatrick        if not buffer:
965*061da546Spatrick            output = io.StringIO()
966*061da546Spatrick        else:
967*061da546Spatrick            output = buffer
968*061da546Spatrick        # If there is a summary, it suffices.
969*061da546Spatrick        val = value.GetSummary()
970*061da546Spatrick        # Otherwise, get the value.
971*061da546Spatrick        if val is None:
972*061da546Spatrick            val = value.GetValue()
973*061da546Spatrick        if val is None and value.GetNumChildren() > 0:
974*061da546Spatrick            val = "%s (location)" % value.GetLocation()
975*061da546Spatrick        print("{indentation}({type}) {name} = {value}".format(
976*061da546Spatrick            indentation=' ' * indent,
977*061da546Spatrick            type=value.GetTypeName(),
978*061da546Spatrick            name=value.GetName(),
979*061da546Spatrick            value=val), file=output)
980*061da546Spatrick        return output.getvalue()
981*061da546Spatrick
982*061da546Spatrick
983*061da546Spatrickclass ChildVisitingFormatter(BasicFormatter):
984*061da546Spatrick    """The child visiting formatter prints the value and its immediate children.
985*061da546Spatrick
986*061da546Spatrick    The constructor takes a keyword arg: indent_child, which defaults to 2.
987*061da546Spatrick    """
988*061da546Spatrick
989*061da546Spatrick    def __init__(self, indent_child=2):
990*061da546Spatrick        """Default indentation of 2 SPC's for the children."""
991*061da546Spatrick        self.cindent = indent_child
992*061da546Spatrick
993*061da546Spatrick    def format(self, value, buffer=None):
994*061da546Spatrick        if not buffer:
995*061da546Spatrick            output = io.StringIO()
996*061da546Spatrick        else:
997*061da546Spatrick            output = buffer
998*061da546Spatrick
999*061da546Spatrick        BasicFormatter.format(self, value, buffer=output)
1000*061da546Spatrick        for child in value:
1001*061da546Spatrick            BasicFormatter.format(
1002*061da546Spatrick                self, child, buffer=output, indent=self.cindent)
1003*061da546Spatrick
1004*061da546Spatrick        return output.getvalue()
1005*061da546Spatrick
1006*061da546Spatrick
1007*061da546Spatrickclass RecursiveDecentFormatter(BasicFormatter):
1008*061da546Spatrick    """The recursive decent formatter prints the value and the decendents.
1009*061da546Spatrick
1010*061da546Spatrick    The constructor takes two keyword args: indent_level, which defaults to 0,
1011*061da546Spatrick    and indent_child, which defaults to 2.  The current indentation level is
1012*061da546Spatrick    determined by indent_level, while the immediate children has an additional
1013*061da546Spatrick    indentation by inden_child.
1014*061da546Spatrick    """
1015*061da546Spatrick
1016*061da546Spatrick    def __init__(self, indent_level=0, indent_child=2):
1017*061da546Spatrick        self.lindent = indent_level
1018*061da546Spatrick        self.cindent = indent_child
1019*061da546Spatrick
1020*061da546Spatrick    def format(self, value, buffer=None):
1021*061da546Spatrick        if not buffer:
1022*061da546Spatrick            output = io.StringIO()
1023*061da546Spatrick        else:
1024*061da546Spatrick            output = buffer
1025*061da546Spatrick
1026*061da546Spatrick        BasicFormatter.format(self, value, buffer=output, indent=self.lindent)
1027*061da546Spatrick        new_indent = self.lindent + self.cindent
1028*061da546Spatrick        for child in value:
1029*061da546Spatrick            if child.GetSummary() is not None:
1030*061da546Spatrick                BasicFormatter.format(
1031*061da546Spatrick                    self, child, buffer=output, indent=new_indent)
1032*061da546Spatrick            else:
1033*061da546Spatrick                if child.GetNumChildren() > 0:
1034*061da546Spatrick                    rdf = RecursiveDecentFormatter(indent_level=new_indent)
1035*061da546Spatrick                    rdf.format(child, buffer=output)
1036*061da546Spatrick                else:
1037*061da546Spatrick                    BasicFormatter.format(
1038*061da546Spatrick                        self, child, buffer=output, indent=new_indent)
1039*061da546Spatrick
1040*061da546Spatrick        return output.getvalue()
1041