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