diff --git a/lldb/docs/_lldb/__init__.py b/lldb/docs/_lldb/__init__.py --- a/lldb/docs/_lldb/__init__.py +++ b/lldb/docs/_lldb/__init__.py @@ -5,5 +5,5 @@ # This package acts as a mock implementation of the native _lldb module so # that generating the LLDB documentation doesn't actually require building all # of LLDB. -module_name = '_lldb' +module_name = "_lldb" sys.modules[module_name] = Mock() diff --git a/lldb/docs/conf.py b/lldb/docs/conf.py --- a/lldb/docs/conf.py +++ b/lldb/docs/conf.py @@ -15,7 +15,7 @@ import sys, os, re, shutil from datetime import date -building_man_page = tags.has('builder-man') +building_man_page = tags.has("builder-man") # For the website we need to setup the path to the generated LLDB module that # we can generate documentation for its API. @@ -33,43 +33,43 @@ # Put the generated Python API documentation in the 'python_api' folder. This # also defines the URL these files will have in the generated website. -automodapi_toctreedirnm = 'python_api' +automodapi_toctreedirnm = "python_api" # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +# needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.todo', 'sphinx.ext.mathjax', 'sphinx.ext.intersphinx'] +extensions = ["sphinx.ext.todo", "sphinx.ext.mathjax", "sphinx.ext.intersphinx"] autodoc_default_options = { - 'special-members': '__int__, __len__, __hex__, __oct__, __iter__', + "special-members": "__int__, __len__, __hex__, __oct__, __iter__", } # Unless we only generate the basic manpage we need the plugin for generating # the Python API documentation. if not building_man_page: - extensions.append('sphinx_automodapi.automodapi') + extensions.append("sphinx_automodapi.automodapi") # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix of source filenames. source_suffix = { - '.rst': 'restructuredtext', + ".rst": "restructuredtext", } # The encoding of source files. -#source_encoding = 'utf-8-sig' +# source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'LLDB' -copyright = u'2007-%d, The LLDB Team' % date.today().year +project = "LLDB" +copyright = "2007-%d, The LLDB Team" % date.today().year # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -78,23 +78,23 @@ # everytime a new release comes out. # # The short version. -#version = '0' +# version = '0' # The full version, including alpha/beta/rc tags. -#release = '0' +# release = '0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -#language = None +# language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: -#today = '' +# today = '' # Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +# today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build', 'analyzer'] +exclude_patterns = ["_build", "analyzer"] # Ignore the generated Python documentation that is only used on the website. # Without this we will get a lot of warnings about doc pages that aren't # included by any doctree (as the manpage ignores those pages but they are @@ -103,116 +103,114 @@ exclude_patterns.append(automodapi_toctreedirnm) # Use the recommended 'any' rule so that referencing SB API classes is possible # by just writing `SBData`. -default_role = 'any' +default_role = "any" # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +# add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). -#add_module_names = True +# add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +# show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'friendly' +pygments_style = "friendly" # A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] +# modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'alabaster' +html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { - 'font_size': '11pt', + "font_size": "11pt", # Don't generate any links to GitHub. - 'github_button' : 'false', + "github_button": "false", } # Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] +# html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -html_title = 'The LLDB Debugger' +html_title = "The LLDB Debugger" # A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None +# html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. -#html_logo = None +# html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = None +# html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] html_context = { - 'css_files': [ - '_static/lldb.css' - ], - } + "css_files": ["_static/lldb.css"], +} -html_extra_path = ['.htaccess'] +html_extra_path = [".htaccess"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -html_last_updated_fmt = '%b %d, %Y' +html_last_updated_fmt = "%b %d, %Y" # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. -#html_use_smartypants = True +# html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +# html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +# html_additional_pages = {} # If false, no module index is generated. -#html_domain_indices = True +# html_domain_indices = True # If false, no index is generated. -#html_use_index = True +# html_use_index = True # If true, the index is split into individual pages for each letter. -#html_split_index = False +# html_split_index = False # If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True +# html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True +# html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +# html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. -#html_use_opensearch = '' +# html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None +# html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'LLDBdoc' +htmlhelp_basename = "LLDBdoc" # If true, the reST sources are included in the HTML build as # _sources/name. The default is True. @@ -221,54 +219,52 @@ # -- Options for LaTeX output -------------------------------------------------- latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ('index', 'LLDB.tex', u'LLDB Documentation', - u'The LLDB Team', 'manual'), + ("index", "LLDB.tex", "LLDB Documentation", "The LLDB Team", "manual"), ] # The name of an image file (relative to this directory) to place at the top of # the title page. -#latex_logo = None +# latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. -#latex_use_parts = False +# latex_use_parts = False # If true, show page references after internal links. -#latex_show_pagerefs = False +# latex_show_pagerefs = False # If true, show URL addresses after external links. -#latex_show_urls = False +# latex_show_urls = False # Documents to append as an appendix to all manuals. -#latex_appendices = [] +# latex_appendices = [] # If false, no module index is generated. -#latex_domain_indices = True +# latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [('man/lldb', 'lldb', u'LLDB Documentation', [u'LLVM project'], 1), - ('man/lldb-server', 'lldb-server', u'LLDB Documentation', [u'LLVM project'], 1), - ] +man_pages = [ + ("man/lldb", "lldb", "LLDB Documentation", ["LLVM project"], 1), + ("man/lldb-server", "lldb-server", "LLDB Documentation", ["LLVM project"], 1), +] # If true, show URL addresses after external links. -#man_show_urls = False +# man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ @@ -276,28 +272,39 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'LLDB', u'LLDB Documentation', - u'The LLDB Team', 'LLDB', 'One line description of project.', - 'Miscellaneous'), + ( + "index", + "LLDB", + "LLDB Documentation", + "The LLDB Team", + "LLDB", + "One line description of project.", + "Miscellaneous", + ), ] # Documents to append as an appendix to all manuals. -#texinfo_appendices = [] +# texinfo_appendices = [] # If false, no module index is generated. -#texinfo_domain_indices = True +# texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' +# texinfo_show_urls = 'footnote' + +empty_attr_summary = re.compile( + r"\.\. rubric:: Attributes Summary\s*\.\. autosummary::\s*\.\. rubric::" +) +empty_attr_documentation = re.compile( + r"\.\. rubric:: Attributes Documentation\s*\.\. rubric::" +) -empty_attr_summary = re.compile(r'\.\. rubric:: Attributes Summary\s*\.\. autosummary::\s*\.\. rubric::') -empty_attr_documentation = re.compile(r'\.\. rubric:: Attributes Documentation\s*\.\. rubric::') def preprocess_source(app, docname, source): - """ Preprocesses source files generated by automodapi. """ + """Preprocesses source files generated by automodapi.""" # Don't cleanup anything beside automodapi-generated sources. if not automodapi_toctreedirnm in docname: - return + return processed = source[0] # Don't show the list of inheritance info as there is no inheritance in the @@ -307,25 +314,27 @@ processed = processed.replace(":show-inheritance:", "") # Remove the SWIG generated 'thisown' attribute. It just bloats the generated # documentation and users shouldn't fiddle with the value anyway. - processed = re.sub(r'~SB[a-zA-Z]+\.thisown', "", processed) + processed = re.sub(r"~SB[a-zA-Z]+\.thisown", "", processed) processed = processed.replace(" .. autoattribute:: thisown", "") # After removing 'thisown', many objects don't have any attributes left. # Remove all now empty attribute summary/documentation sections with # some rather ugly regex. - processed = empty_attr_summary.sub('.. rubric::', processed) - processed = empty_attr_documentation.sub('.. rubric::', processed) + processed = empty_attr_summary.sub(".. rubric::", processed) + processed = empty_attr_documentation.sub(".. rubric::", processed) # Replace the original source with the processed one (source is a single # element list). source[0] = processed + def cleanup_source(app, exception): - """ Remove files generated by automodapi in the source tree. """ - if hasattr(app.config, 'automodapi_toctreedirnm'): - api_source_dir = os.path.join(app.srcdir, app.config.automodapi_toctreedirnm) - shutil.rmtree(api_source_dir, ignore_errors=True) + """Remove files generated by automodapi in the source tree.""" + if hasattr(app.config, "automodapi_toctreedirnm"): + api_source_dir = os.path.join(app.srcdir, app.config.automodapi_toctreedirnm) + shutil.rmtree(api_source_dir, ignore_errors=True) + def setup(app): - app.connect('source-read', preprocess_source) - app.connect('build-finished', cleanup_source) + app.connect("source-read", preprocess_source) + app.connect("build-finished", cleanup_source) diff --git a/lldb/examples/customization/bin-utils/binutils.py b/lldb/examples/customization/bin-utils/binutils.py --- a/lldb/examples/customization/bin-utils/binutils.py +++ b/lldb/examples/customization/bin-utils/binutils.py @@ -1,4 +1,5 @@ -"Collection of tools for displaying bit representation of numbers.""" +"Collection of tools for displaying bit representation of numbers." "" + def binary(n, width=None): """ @@ -26,7 +27,7 @@ Return a list of (0|1)'s for the binary representation of a width-bit two's complement numeral system of an integer n which may be negative. """ - val = 2**(width - 1) + val = 2 ** (width - 1) if n >= 0: if n > (val - 1): return None @@ -39,6 +40,7 @@ # It is safe to represent n (a negative int) with width-bits. return binary(val * 2 - abs(n)) + # print binary(0xABCD) # [1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1] # print binary(0x1F, 8) @@ -57,7 +59,7 @@ """Helper function returning a list describing the bit positions. Bit positions greater than 99 are truncated to 2 digits, for example, 100 -> 00 and 127 -> 27.""" - return ['{0:2}'.format(i)[-2:] for i in reversed(range(width))] + return ["{0:2}".format(i)[-2:] for i in reversed(range(width))] def utob(debugger, command_line, result, dict): @@ -88,8 +90,8 @@ return if verbose and width > 0: pos = positions(width) - print(' ' + ' '.join(pos)) - print(' %s' % str(bits)) + print(" " + " ".join(pos)) + print(" %s" % str(bits)) def itob(debugger, command_line, result, dict): @@ -118,5 +120,5 @@ return if verbose and width > 0: pos = positions(width) - print(' ' + ' '.join(pos)) - print(' %s' % str(bits)) + print(" " + " ".join(pos)) + print(" %s" % str(bits)) diff --git a/lldb/examples/customization/import-python/importcmd.py b/lldb/examples/customization/import-python/importcmd.py --- a/lldb/examples/customization/import-python/importcmd.py +++ b/lldb/examples/customization/import-python/importcmd.py @@ -14,9 +14,9 @@ def do_import(debugger, modname): - if (len(modname) > 4 and modname[-4:] == '.pyc'): + if len(modname) > 4 and modname[-4:] == ".pyc": modname = modname[:-4] - if (len(modname) > 3 and modname[-3:] == '.py'): + if len(modname) > 3 and modname[-3:] == ".py": modname = modname[:-3] debugger.HandleCommand("script import " + modname) @@ -28,10 +28,10 @@ return "no module path given" if not (os.sep in args): modname = args - ensure_has_dir_in_path('.') + ensure_has_dir_in_path(".") else: endofdir = args.rfind(os.sep) - modname = args[endofdir + 1:] + modname = args[endofdir + 1 :] args = args[0:endofdir] ensure_has_dir_in_path(args) do_import(debugger, modname) diff --git a/lldb/examples/customization/pwd-cd-and-system/utils.py b/lldb/examples/customization/pwd-cd-and-system/utils.py --- a/lldb/examples/customization/pwd-cd-and-system/utils.py +++ b/lldb/examples/customization/pwd-cd-and-system/utils.py @@ -9,6 +9,7 @@ class Holder: """Holds the _prev_dir_ class attribute for chdir() function.""" + _prev_dir_ = None @classmethod @@ -25,8 +26,8 @@ You can also issue 'cd -' to change to the previous working directory.""" new_dir = args.strip() if not new_dir: - new_dir = os.path.expanduser('~') - elif new_dir == '-': + new_dir = os.path.expanduser("~") + elif new_dir == "-": if not Holder.prev_dir(): # Bad directory, not changing. print("bad directory, not changing") @@ -42,10 +43,7 @@ def system(debugger, command_line, result, dict): """Execute the command (a string) in a subshell.""" args = shlex.split(command_line) - process = subprocess.Popen( - args, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE) + process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = process.communicate() retcode = process.poll() if output and error: diff --git a/lldb/examples/darwin/heap_find/heap.py b/lldb/examples/darwin/heap_find/heap.py --- a/lldb/examples/darwin/heap_find/heap.py +++ b/lldb/examples/darwin/heap_find/heap.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # This module is designed to live inside the "lldb" python package # in the "lldb.macosx" package. To use this in the embedded python # interpreter using "lldb" just import it: # # (lldb) script import lldb.macosx.heap -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- import lldb import optparse @@ -23,12 +23,8 @@ g_libheap_dylib_dict = dict() -def get_iterate_memory_expr( - options, - process, - user_init_code, - user_return_code): - expr = ''' +def get_iterate_memory_expr(options, process, user_init_code, user_return_code): + expr = """ typedef unsigned natural_t; typedef uintptr_t vm_size_t; typedef uintptr_t vm_address_t; @@ -36,9 +32,9 @@ typedef int kern_return_t; #define KERN_SUCCESS 0 typedef void (*range_callback_t)(task_t, void *, unsigned, uintptr_t, uintptr_t); -''' +""" if options.search_vm_regions: - expr += ''' + expr += """ typedef int vm_prot_t; typedef unsigned int vm_inherit_t; typedef unsigned long long memory_object_offset_t; @@ -71,10 +67,10 @@ vm32_object_id_t object_id; // obj/map name, not a handle unsigned short user_wired_count; } vm_region_submap_short_info_data_64_t; -#define VM_REGION_SUBMAP_SHORT_INFO_COUNT_64 ((mach_msg_type_number_t)(sizeof(vm_region_submap_short_info_data_64_t)/sizeof(int)))''' +#define VM_REGION_SUBMAP_SHORT_INFO_COUNT_64 ((mach_msg_type_number_t)(sizeof(vm_region_submap_short_info_data_64_t)/sizeof(int)))""" if user_init_code: expr += user_init_code - expr += ''' + expr += """ task_t task = (task_t)mach_task_self(); mach_vm_address_t vm_region_base_addr; mach_vm_size_t vm_region_size; @@ -104,7 +100,7 @@ vm_region_base_addr, vm_region_size); } -}''' +}""" else: if options.search_stack: expr += get_thread_stack_ranges_struct(process) @@ -113,7 +109,7 @@ if user_init_code: expr += user_init_code if options.search_heap: - expr += ''' + expr += """ #define MALLOC_PTR_IN_USE_RANGE_TYPE 1 typedef struct vm_range_t { vm_address_t address; @@ -156,10 +152,10 @@ } }); } -}''' +}""" if options.search_stack: - expr += ''' + expr += """ #ifdef NUM_STACKS // Call the callback for the thread stack ranges for (uint32_t i=0; i 0 and var_addr <= match_addr and match_addr < ( - var_addr + byte_size): + if ( + byte_size > 0 + and var_addr <= match_addr + and match_addr < (var_addr + byte_size) + ): if verbose: - print('match') + print("match") return var return None @@ -425,24 +456,23 @@ def type_flags_to_description( - process, - type_flags, - ptr_addr, - ptr_size, - offset, - match_addr): + process, type_flags, ptr_addr, ptr_size, offset, match_addr +): show_offset = False if type_flags == 0 or type_flags & 4: - type_str = 'free(%#x)' % (ptr_addr,) + type_str = "free(%#x)" % (ptr_addr,) elif type_flags & 2 or type_flags & 1: - type_str = 'malloc(%6u) -> %#x' % (ptr_size, ptr_addr) + type_str = "malloc(%6u) -> %#x" % (ptr_size, ptr_addr) show_offset = True elif type_flags & 8: - type_str = 'stack' + type_str = "stack" frame = find_frame_for_stack_address(process, match_addr) if frame: - type_str += ' in frame #%u of thread #%u: tid %#x' % (frame.GetFrameID( - ), frame.GetThread().GetIndexID(), frame.GetThread().GetThreadID()) + type_str += " in frame #%u of thread #%u: tid %#x" % ( + frame.GetFrameID(), + frame.GetThread().GetIndexID(), + frame.GetThread().GetThreadID(), + ) variables = frame.GetVariables(True, True, True, True) matching_var = None for var in variables: @@ -455,28 +485,43 @@ break else: byte_size = var.GetType().GetByteSize() - if byte_size > 0 and var_addr <= match_addr and match_addr < ( - var_addr + byte_size): + if ( + byte_size > 0 + and var_addr <= match_addr + and match_addr < (var_addr + byte_size) + ): matching_var = var break if matching_var: - type_str += ' in variable at %#x:\n %s' % ( - matching_var.GetLoadAddress(), matching_var) + type_str += " in variable at %#x:\n %s" % ( + matching_var.GetLoadAddress(), + matching_var, + ) elif type_flags & 16: - type_str = 'stack (red zone)' + type_str = "stack (red zone)" elif type_flags & 32: sb_addr = process.GetTarget().ResolveLoadAddress(ptr_addr + offset) - type_str = 'segment [%#x - %#x), %s + %u, %s' % ( - ptr_addr, ptr_addr + ptr_size, sb_addr.section.name, sb_addr.offset, sb_addr) + type_str = "segment [%#x - %#x), %s + %u, %s" % ( + ptr_addr, + ptr_addr + ptr_size, + sb_addr.section.name, + sb_addr.offset, + sb_addr, + ) elif type_flags & 64: sb_addr = process.GetTarget().ResolveLoadAddress(ptr_addr + offset) - type_str = 'vm_region [%#x - %#x), %s + %u, %s' % ( - ptr_addr, ptr_addr + ptr_size, sb_addr.section.name, sb_addr.offset, sb_addr) + type_str = "vm_region [%#x - %#x), %s + %u, %s" % ( + ptr_addr, + ptr_addr + ptr_size, + sb_addr.section.name, + sb_addr.offset, + sb_addr, + ) else: - type_str = '%#x' % (ptr_addr,) + type_str = "%#x" % (ptr_addr,) show_offset = True if show_offset and offset != 0: - type_str += ' + %-6u' % (offset,) + type_str += " + %-6u" % (offset,) return type_str @@ -488,8 +533,8 @@ symbolicator.target = lldb.debugger.GetSelectedTarget() type_str = type_flags_to_string(type_flags) result.AppendMessage( - 'stack[%u]: addr = 0x%x, type=%s, frames:' % - (idx, address, type_str)) + "stack[%u]: addr = 0x%x, type=%s, frames:" % (idx, address, type_str) + ) frame_idx = 0 idx = 0 pc = int(stack_history_entry.frames[idx]) @@ -498,12 +543,10 @@ frames = symbolicator.symbolicate(pc) if frames: for frame in frames: - result.AppendMessage( - ' [%u] %s' % - (frame_idx, frame)) + result.AppendMessage(" [%u] %s" % (frame_idx, frame)) frame_idx += 1 else: - result.AppendMessage(' [%u] 0x%x' % (frame_idx, pc)) + result.AppendMessage(" [%u] 0x%x" % (frame_idx, pc)) frame_idx += 1 idx = idx + 1 pc = int(stack_history_entry.frames[idx]) @@ -511,15 +554,16 @@ pc = 0 if idx >= options.max_frames: result.AppendMessage( - 'warning: the max number of stack frames (%u) was reached, use the "--max-frames=" option to see more frames' % - (options.max_frames)) + 'warning: the max number of stack frames (%u) was reached, use the "--max-frames=" option to see more frames' + % (options.max_frames) + ) - result.AppendMessage('') + result.AppendMessage("") def dump_stack_history_entries(options, result, addr, history): # malloc_stack_entry *get_stack_history_for_address (const void * addr) - expr_prefix = ''' + expr_prefix = """ typedef int kern_return_t; typedef struct $malloc_stack_entry { uint64_t address; @@ -529,8 +573,8 @@ uint64_t frames[512]; kern_return_t err; } $malloc_stack_entry; -''' - single_expr = ''' +""" + single_expr = """ #define MAX_FRAMES %u typedef unsigned task_t; $malloc_stack_entry stack; @@ -549,9 +593,12 @@ stack.frames[stack.num_frames] = 0; else stack.frames[MAX_FRAMES-1] = 0; -stack''' % (options.max_frames, addr) +stack""" % ( + options.max_frames, + addr, + ) - history_expr = ''' + history_expr = """ typedef int kern_return_t; typedef unsigned task_t; #define MAX_FRAMES %u @@ -600,10 +647,18 @@ ++lldb_info->idx; }; (kern_return_t)__mach_stack_logging_enumerate_records (lldb_info.task, (uint64_t)0x%x, callback, &lldb_info); -lldb_info''' % (options.max_frames, options.max_history, addr) - - frame = lldb.debugger.GetSelectedTarget().GetProcess( - ).GetSelectedThread().GetSelectedFrame() +lldb_info""" % ( + options.max_frames, + options.max_history, + addr, + ) + + frame = ( + lldb.debugger.GetSelectedTarget() + .GetProcess() + .GetSelectedThread() + .GetSelectedFrame() + ) if history: expr = history_expr else: @@ -630,40 +685,44 @@ i_max = options.max_history for i in range(i_max): stack_history_entry = malloc_stack_history.entries[i] - dump_stack_history_entry( - options, result, stack_history_entry, i) + dump_stack_history_entry(options, result, stack_history_entry, i) if num_stacks > options.max_history: result.AppendMessage( - 'warning: the max number of stacks (%u) was reached, use the "--max-history=%u" option to see all of the stacks' % - (options.max_history, num_stacks)) + 'warning: the max number of stacks (%u) was reached, use the "--max-history=%u" option to see all of the stacks' + % (options.max_history, num_stacks) + ) else: stack_history_entry = lldb.value(expr_sbvalue) dump_stack_history_entry(options, result, stack_history_entry, 0) else: result.AppendMessage( - 'error: expression failed "%s" => %s' % - (expr, expr_sbvalue.error)) + 'error: expression failed "%s" => %s' % (expr, expr_sbvalue.error) + ) def display_match_results( - process, - result, - options, - arg_str_description, - expr, - print_no_matches, - expr_prefix=None): - frame = lldb.debugger.GetSelectedTarget().GetProcess( - ).GetSelectedThread().GetSelectedFrame() + process, + result, + options, + arg_str_description, + expr, + print_no_matches, + expr_prefix=None, +): + frame = ( + lldb.debugger.GetSelectedTarget() + .GetProcess() + .GetSelectedThread() + .GetSelectedFrame() + ) if not frame: - result.AppendMessage('error: invalid frame') + result.AppendMessage("error: invalid frame") return 0 expr_options = lldb.SBExpressionOptions() expr_options.SetIgnoreBreakpoints(True) expr_options.SetFetchDynamicValue(lldb.eNoDynamicValues) - expr_options.SetTimeoutInMicroSeconds( - 30 * 1000 * 1000) # 30 second timeout + expr_options.SetTimeoutInMicroSeconds(30 * 1000 * 1000) # 30 second timeout expr_options.SetTryAllThreads(False) expr_options.SetLanguage(lldb.eLanguageTypeObjC_plus_plus) if expr_prefix: @@ -684,8 +743,9 @@ i += 1 if i > options.max_matches: result.AppendMessage( - 'warning: the max number of matches (%u) was reached, use the --max-matches option to get more results' % - (options.max_matches)) + "warning: the max number of matches (%u) was reached, use the --max-matches option to get more results" + % (options.max_matches) + ) break malloc_addr = match_entry.addr.sbvalue.unsigned if malloc_addr == 0: @@ -698,7 +758,7 @@ else: match_addr = malloc_addr + offset type_flags = int(match_entry.type) - #result.AppendMessage (hex(malloc_addr + offset)) + # result.AppendMessage (hex(malloc_addr + offset)) if type_flags == 64: search_stack_old = options.search_stack search_segments_old = options.search_segments @@ -708,36 +768,48 @@ options.search_segments = True options.search_heap = True options.search_vm_regions = False - if malloc_info_impl(lldb.debugger, result, options, [ - hex(malloc_addr + offset)]): + if malloc_info_impl( + lldb.debugger, result, options, [hex(malloc_addr + offset)] + ): print_entry = False options.search_stack = search_stack_old options.search_segments = search_segments_old options.search_heap = search_heap_old options.search_vm_regions = search_vm_regions if print_entry: - description = '%#16.16x: %s' % (match_addr, type_flags_to_description( - process, type_flags, malloc_addr, malloc_size, offset, match_addr)) + description = "%#16.16x: %s" % ( + match_addr, + type_flags_to_description( + process, + type_flags, + malloc_addr, + malloc_size, + offset, + match_addr, + ), + ) if options.show_size: - description += ' <%5u>' % (malloc_size) + description += " <%5u>" % (malloc_size) if options.show_range: - description += ' [%#x - %#x)' % ( - malloc_addr, malloc_addr + malloc_size) + description += " [%#x - %#x)" % ( + malloc_addr, + malloc_addr + malloc_size, + ) derefed_dynamic_value = None dynamic_value = match_entry.addr.sbvalue.GetDynamicValue( - lldb.eDynamicCanRunTarget) - if dynamic_value.type.name == 'void *': - if options.type == 'pointer' and malloc_size == 4096: + lldb.eDynamicCanRunTarget + ) + if dynamic_value.type.name == "void *": + if options.type == "pointer" and malloc_size == 4096: error = lldb.SBError() process = expr_sbvalue.GetProcess() target = expr_sbvalue.GetTarget() - data = bytearray( - process.ReadMemory( - malloc_addr, 16, error)) - if data == '\xa1\xa1\xa1\xa1AUTORELEASE!': + data = bytearray(process.ReadMemory(malloc_addr, 16, error)) + if data == "\xa1\xa1\xa1\xa1AUTORELEASE!": ptr_size = target.addr_size thread = process.ReadUnsignedFromMemory( - malloc_addr + 16 + ptr_size, ptr_size, error) + malloc_addr + 16 + ptr_size, ptr_size, error + ) # 4 bytes 0xa1a1a1a1 # 12 bytes 'AUTORELEASE!' # ptr bytes autorelease insertion point @@ -746,8 +818,9 @@ # ptr bytes next hotter page # 4 bytes this page's depth in the list # 4 bytes high-water mark - description += ' AUTORELEASE! for pthread_t %#x' % ( - thread) + description += " AUTORELEASE! for pthread_t %#x" % ( + thread + ) # else: # description += 'malloc(%u)' % (malloc_size) # else: @@ -758,58 +831,69 @@ derefed_dynamic_type = derefed_dynamic_value.type derefed_dynamic_type_size = derefed_dynamic_type.size derefed_dynamic_type_name = derefed_dynamic_type.name - description += ' ' + description += " " description += derefed_dynamic_type_name if offset < derefed_dynamic_type_size: member_list = list() get_member_types_for_offset( - derefed_dynamic_type, offset, member_list) + derefed_dynamic_type, offset, member_list + ) if member_list: - member_path = '' + member_path = "" for member in member_list: member_name = member.name if member_name: if member_path: - member_path += '.' + member_path += "." member_path += member_name if member_path: if options.ivar_regex_exclusions: - for ivar_regex in options.ivar_regex_exclusions: - if ivar_regex.match( - member_path): + for ( + ivar_regex + ) in options.ivar_regex_exclusions: + if ivar_regex.match(member_path): print_entry = False - description += '.%s' % (member_path) + description += ".%s" % (member_path) else: - description += '%u bytes after %s' % ( - offset - derefed_dynamic_type_size, derefed_dynamic_type_name) + description += "%u bytes after %s" % ( + offset - derefed_dynamic_type_size, + derefed_dynamic_type_name, + ) else: # strip the "*" from the end of the name since we # were unable to dereference this description += dynamic_value.type.name[0:-1] if print_entry: match_idx += 1 - result_output = '' + result_output = "" if description: result_output += description if options.print_type and derefed_dynamic_value: - result_output += ' %s' % (derefed_dynamic_value) + result_output += " %s" % (derefed_dynamic_value) if options.print_object_description and dynamic_value: desc = dynamic_value.GetObjectDescription() if desc: - result_output += '\n%s' % (desc) + result_output += "\n%s" % (desc) if result_output: result.AppendMessage(result_output) if options.memory: cmd_result = lldb.SBCommandReturnObject() if options.format is None: memory_command = "memory read --force 0x%x 0x%x" % ( - malloc_addr, malloc_addr + malloc_size) + malloc_addr, + malloc_addr + malloc_size, + ) else: memory_command = "memory read --force -f %s 0x%x 0x%x" % ( - options.format, malloc_addr, malloc_addr + malloc_size) + options.format, + malloc_addr, + malloc_addr + malloc_size, + ) if options.verbose: result.AppendMessage(memory_command) - lldb.debugger.GetCommandInterpreter().HandleCommand(memory_command, cmd_result) + lldb.debugger.GetCommandInterpreter().HandleCommand( + memory_command, cmd_result + ) result.AppendMessage(cmd_result.GetOutput()) if options.stack_history: dump_stack_history_entries(options, result, malloc_addr, 1) @@ -823,34 +907,35 @@ def get_ptr_refs_options(): usage = "usage: %prog [options] [EXPR ...]" - description = '''Searches all allocations on the heap for pointer values on + description = """Searches all allocations on the heap for pointer values on darwin user space programs. Any matches that were found will dump the malloc blocks that contain the pointers and might be able to print what kind of objects the pointers are contained in using dynamic type information in the -program.''' +program.""" parser = optparse.OptionParser( - description=description, - prog='ptr_refs', - usage=usage) + description=description, prog="ptr_refs", usage=usage + ) add_common_options(parser) return parser def find_variable(debugger, command, result, dict): usage = "usage: %prog [options] [ADDR ...]" - description = '''Searches for a local variable in all frames that contains a hex ADDR.''' + description = ( + """Searches for a local variable in all frames that contains a hex ADDR.""" + ) command_args = shlex.split(command) parser = optparse.OptionParser( - description=description, - prog='find_variable', - usage=usage) + description=description, prog="find_variable", usage=usage + ) parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', - help='display verbose debug info', - default=False) + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="display verbose debug info", + default=False, + ) try: (options, args) = parser.parse_args(command_args) except: @@ -858,7 +943,7 @@ process = debugger.GetSelectedTarget().GetProcess() if not process: - result.AppendMessage('error: invalid process') + result.AppendMessage("error: invalid process") return for arg in args: @@ -867,8 +952,7 @@ done = False for thread in process: for frame in thread: - var = find_variable_containing_address( - options.verbose, frame, var_addr) + var = find_variable_containing_address(options.verbose, frame, var_addr) if var: print(var) done = True @@ -887,14 +971,14 @@ process = debugger.GetSelectedTarget().GetProcess() if not process: - result.AppendMessage('error: invalid process') + result.AppendMessage("error: invalid process") return frame = process.GetSelectedThread().GetSelectedFrame() if not frame: - result.AppendMessage('error: invalid frame') + result.AppendMessage("error: invalid frame") return - options.type = 'pointer' + options.type = "pointer" if options.format is None: options.format = "A" # 'A' is "address" format @@ -907,15 +991,15 @@ # a member named "callback" whose type is "range_callback_t". This # will be used by our zone callbacks to call the range callback for # each malloc range. - expr_prefix = ''' + expr_prefix = """ struct $malloc_match { void *addr; uintptr_t size; uintptr_t offset; uintptr_t type; }; -''' - user_init_code_format = ''' +""" + user_init_code_format = """ #define MAX_MATCHES %u typedef struct callback_baton_t { range_callback_t callback; @@ -941,46 +1025,40 @@ } }; callback_baton_t baton = { range_callback, 0, {0}, (void *)%s }; -''' +""" # We must also define a snippet of code to be run that returns # the result of the expression we run. # Here we return NULL if our pointer was not found in any malloc blocks, # and we return the address of the matches array so we can then access # the matching results - user_return_code = '''if (baton.num_matches < MAX_MATCHES) + user_return_code = """if (baton.num_matches < MAX_MATCHES) baton.matches[baton.num_matches].addr = 0; // Terminate the matches array -baton.matches''' +baton.matches""" # Iterate through all of our pointer expressions and display the # results for ptr_expr in args: - user_init_code = user_init_code_format % ( - options.max_matches, ptr_expr) + user_init_code = user_init_code_format % (options.max_matches, ptr_expr) expr = get_iterate_memory_expr( - options, process, user_init_code, user_return_code) - arg_str_description = 'malloc block containing pointer %s' % ptr_expr + options, process, user_init_code, user_return_code + ) + arg_str_description = "malloc block containing pointer %s" % ptr_expr display_match_results( - process, - result, - options, - arg_str_description, - expr, - True, - expr_prefix) + process, result, options, arg_str_description, expr, True, expr_prefix + ) else: - result.AppendMessage('error: no pointer arguments were given') + result.AppendMessage("error: no pointer arguments were given") def get_cstr_refs_options(): usage = "usage: %prog [options] [CSTR ...]" - description = '''Searches all allocations on the heap for C string values on + description = """Searches all allocations on the heap for C string values on darwin user space programs. Any matches that were found will dump the malloc blocks that contain the C strings and might be able to print what kind of objects the pointers are contained in using dynamic type information in the -program.''' +program.""" parser = optparse.OptionParser( - description=description, - prog='cstr_refs', - usage=usage) + description=description, prog="cstr_refs", usage=usage + ) add_common_options(parser) return parser @@ -995,14 +1073,14 @@ process = debugger.GetSelectedTarget().GetProcess() if not process: - result.AppendMessage('error: invalid process') + result.AppendMessage("error: invalid process") return frame = process.GetSelectedThread().GetSelectedFrame() if not frame: - result.AppendMessage('error: invalid frame') + result.AppendMessage("error: invalid frame") return - options.type = 'cstr' + options.type = "cstr" if options.format is None: options.format = "Y" # 'Y' is "bytes with ASCII" format @@ -1015,15 +1093,15 @@ # a member named "callback" whose type is "range_callback_t". This # will be used by our zone callbacks to call the range callback for # each malloc range. - expr_prefix = ''' + expr_prefix = """ struct $malloc_match { void *addr; uintptr_t size; uintptr_t offset; uintptr_t type; }; -''' - user_init_code_format = ''' +""" + user_init_code_format = """ #define MAX_MATCHES %u typedef struct callback_baton_t { range_callback_t callback; @@ -1051,47 +1129,40 @@ } }; const char *cstr = "%s"; -callback_baton_t baton = { range_callback, 0, {0}, cstr, (unsigned)strlen(cstr) };''' +callback_baton_t baton = { range_callback, 0, {0}, cstr, (unsigned)strlen(cstr) };""" # We must also define a snippet of code to be run that returns # the result of the expression we run. # Here we return NULL if our pointer was not found in any malloc blocks, # and we return the address of the matches array so we can then access # the matching results - user_return_code = '''if (baton.num_matches < MAX_MATCHES) + user_return_code = """if (baton.num_matches < MAX_MATCHES) baton.matches[baton.num_matches].addr = 0; // Terminate the matches array -baton.matches''' +baton.matches""" # Iterate through all of our pointer expressions and display the # results for cstr in args: - user_init_code = user_init_code_format % ( - options.max_matches, cstr) + user_init_code = user_init_code_format % (options.max_matches, cstr) expr = get_iterate_memory_expr( - options, process, user_init_code, user_return_code) + options, process, user_init_code, user_return_code + ) arg_str_description = 'malloc block containing "%s"' % cstr display_match_results( - process, - result, - options, - arg_str_description, - expr, - True, - expr_prefix) + process, result, options, arg_str_description, expr, True, expr_prefix + ) else: - result.AppendMessage( - 'error: command takes one or more C string arguments') + result.AppendMessage("error: command takes one or more C string arguments") def get_malloc_info_options(): usage = "usage: %prog [options] [EXPR ...]" - description = '''Searches the heap a malloc block that contains the addresses + description = """Searches the heap a malloc block that contains the addresses specified as one or more address expressions. Any matches that were found will dump the malloc blocks that match or contain the specified address. The matching blocks might be able to show what kind of objects they are using dynamic type -information in the program.''' +information in the program.""" parser = optparse.OptionParser( - description=description, - prog='malloc_info', - usage=usage) + description=description, prog="malloc_info", usage=usage + ) add_common_options(parser) return parser @@ -1108,26 +1179,26 @@ def malloc_info_impl(debugger, result, options, args): # We are specifically looking for something on the heap only - options.type = 'malloc_info' + options.type = "malloc_info" process = debugger.GetSelectedTarget().GetProcess() if not process: - result.AppendMessage('error: invalid process') + result.AppendMessage("error: invalid process") return frame = process.GetSelectedThread().GetSelectedFrame() if not frame: - result.AppendMessage('error: invalid frame') + result.AppendMessage("error: invalid frame") return - expr_prefix = ''' + expr_prefix = """ struct $malloc_match { void *addr; uintptr_t size; uintptr_t offset; uintptr_t type; }; -''' +""" - user_init_code_format = ''' + user_init_code_format = """ typedef struct callback_baton_t { range_callback_t callback; unsigned num_matches; @@ -1151,27 +1222,28 @@ }; callback_baton_t baton = { range_callback, 0, {0}, (void *)%s }; baton.matches[0].addr = 0; -baton.matches[1].addr = 0;''' +baton.matches[1].addr = 0;""" if args: total_matches = 0 for ptr_expr in args: user_init_code = user_init_code_format % (ptr_expr) expr = get_iterate_memory_expr( - options, process, user_init_code, 'baton.matches') - arg_str_description = 'malloc block that contains %s' % ptr_expr + options, process, user_init_code, "baton.matches" + ) + arg_str_description = "malloc block that contains %s" % ptr_expr total_matches += display_match_results( - process, result, options, arg_str_description, expr, True, expr_prefix) + process, result, options, arg_str_description, expr, True, expr_prefix + ) return total_matches else: - result.AppendMessage( - 'error: command takes one or more pointer expressions') + result.AppendMessage("error: command takes one or more pointer expressions") return 0 def get_thread_stack_ranges_struct(process): - '''Create code that defines a structure that represents threads stack bounds + """Create code that defines a structure that represents threads stack bounds for all threads. It returns a static sized array initialized with all of - the tid, base, size structs for all the threads.''' + the tid, base, size structs for all the threads.""" stack_dicts = list() if process: i = 0 @@ -1185,87 +1257,105 @@ if sp > max_sp: max_sp = sp if min_sp < max_sp: - stack_dicts.append({'tid': thread.GetThreadID( - ), 'base': min_sp, 'size': max_sp - min_sp, 'index': i}) + stack_dicts.append( + { + "tid": thread.GetThreadID(), + "base": min_sp, + "size": max_sp - min_sp, + "index": i, + } + ) i += 1 stack_dicts_len = len(stack_dicts) if stack_dicts_len > 0: - result = ''' + result = """ #define NUM_STACKS %u #define STACK_RED_ZONE_SIZE %u typedef struct thread_stack_t { uint64_t tid, base, size; } thread_stack_t; -thread_stack_t stacks[NUM_STACKS];''' % (stack_dicts_len, process.target.GetStackRedZoneSize()) +thread_stack_t stacks[NUM_STACKS];""" % ( + stack_dicts_len, + process.target.GetStackRedZoneSize(), + ) for stack_dict in stack_dicts: - result += ''' + result += ( + """ stacks[%(index)u].tid = 0x%(tid)x; stacks[%(index)u].base = 0x%(base)x; -stacks[%(index)u].size = 0x%(size)x;''' % stack_dict +stacks[%(index)u].size = 0x%(size)x;""" + % stack_dict + ) return result else: - return '' + return "" def get_sections_ranges_struct(process): - '''Create code that defines a structure that represents all segments that + """Create code that defines a structure that represents all segments that can contain data for all images in "target". It returns a static sized - array initialized with all of base, size structs for all the threads.''' + array initialized with all of base, size structs for all the threads.""" target = process.target segment_dicts = list() - for (module_idx, module) in enumerate(target.modules): + for module_idx, module in enumerate(target.modules): for sect_idx in range(module.GetNumSections()): section = module.GetSectionAtIndex(sect_idx) if not section: break name = section.name - if name != '__TEXT' and name != '__LINKEDIT' and name != '__PAGEZERO': + if name != "__TEXT" and name != "__LINKEDIT" and name != "__PAGEZERO": base = section.GetLoadAddress(target) size = section.GetByteSize() if base != lldb.LLDB_INVALID_ADDRESS and size > 0: - segment_dicts.append({'base': base, 'size': size}) + segment_dicts.append({"base": base, "size": size}) segment_dicts_len = len(segment_dicts) if segment_dicts_len > 0: - result = ''' + result = """ #define NUM_SEGMENTS %u typedef struct segment_range_t { uint64_t base; uint32_t size; } segment_range_t; -segment_range_t segments[NUM_SEGMENTS];''' % (segment_dicts_len,) - for (idx, segment_dict) in enumerate(segment_dicts): - segment_dict['index'] = idx - result += ''' +segment_range_t segments[NUM_SEGMENTS];""" % ( + segment_dicts_len, + ) + for idx, segment_dict in enumerate(segment_dicts): + segment_dict["index"] = idx + result += ( + """ segments[%(index)u].base = 0x%(base)x; -segments[%(index)u].size = 0x%(size)x;''' % segment_dict +segments[%(index)u].size = 0x%(size)x;""" + % segment_dict + ) return result else: - return '' + return "" def section_ptr_refs(debugger, command, result, dict): command_args = shlex.split(command) usage = "usage: %prog [options] [EXPR ...]" - description = '''Searches section contents for pointer values in darwin user space programs.''' + description = """Searches section contents for pointer values in darwin user space programs.""" parser = optparse.OptionParser( - description=description, - prog='section_ptr_refs', - usage=usage) + description=description, prog="section_ptr_refs", usage=usage + ) add_common_options(parser) parser.add_option( - '--section', - action='append', - type='string', - dest='section_names', - help='section name to search', - default=list()) + "--section", + action="append", + type="string", + dest="section_names", + help="section name to search", + default=list(), + ) try: (options, args) = parser.parse_args(command_args) except: return - options.type = 'pointer' + options.type = "pointer" sections = list() section_modules = list() if not options.section_names: result.AppendMessage( - 'error: at least one section must be specified with the --section option') + "error: at least one section must be specified with the --section option" + ) return target = debugger.GetSelectedTarget() @@ -1282,13 +1372,25 @@ return frame = target.GetProcess().GetSelectedThread().GetSelectedFrame() for expr_str in args: - for (idx, section) in enumerate(sections): - expr = 'find_pointer_in_memory(0x%xllu, %ullu, (void *)%s)' % ( - section.addr.load_addr, section.size, expr_str) + for idx, section in enumerate(sections): + expr = "find_pointer_in_memory(0x%xllu, %ullu, (void *)%s)" % ( + section.addr.load_addr, + section.size, + expr_str, + ) arg_str_description = 'section %s.%s containing "%s"' % ( - section_modules[idx].file.fullpath, section.name, expr_str) + section_modules[idx].file.fullpath, + section.name, + expr_str, + ) num_matches = display_match_results( - target.GetProcess(), result, options, arg_str_description, expr, False) + target.GetProcess(), + result, + options, + arg_str_description, + expr, + False, + ) if num_matches: if num_matches < options.max_matches: options.max_matches = options.max_matches - num_matches @@ -1298,23 +1400,22 @@ return else: result.AppendMessage( - 'error: no sections were found that match any of %s' % - (', '.join( - options.section_names))) + "error: no sections were found that match any of %s" + % (", ".join(options.section_names)) + ) def get_objc_refs_options(): usage = "usage: %prog [options] [CLASS ...]" - description = '''Searches all allocations on the heap for instances of + description = """Searches all allocations on the heap for instances of objective C classes, or any classes that inherit from the specified classes in darwin user space programs. Any matches that were found will dump the malloc blocks that contain the C strings and might be able to print what kind of objects the pointers are contained in using dynamic type information in the -program.''' +program.""" parser = optparse.OptionParser( - description=description, - prog='objc_refs', - usage=usage) + description=description, prog="objc_refs", usage=usage + ) add_common_options(parser) return parser @@ -1329,33 +1430,32 @@ process = debugger.GetSelectedTarget().GetProcess() if not process: - result.AppendMessage('error: invalid process') + result.AppendMessage("error: invalid process") return frame = process.GetSelectedThread().GetSelectedFrame() if not frame: - result.AppendMessage('error: invalid frame') + result.AppendMessage("error: invalid frame") return - options.type = 'isa' + options.type = "isa" if options.format is None: options.format = "A" # 'A' is "address" format expr_options = lldb.SBExpressionOptions() expr_options.SetIgnoreBreakpoints(True) - expr_options.SetTimeoutInMicroSeconds( - 3 * 1000 * 1000) # 3 second infinite timeout + expr_options.SetTimeoutInMicroSeconds(3 * 1000 * 1000) # 3 second infinite timeout expr_options.SetTryAllThreads(True) expr_options.SetLanguage(lldb.eLanguageTypeObjC_plus_plus) num_objc_classes_value = frame.EvaluateExpression( - "(int)objc_getClassList((void *)0, (int)0)", expr_options) + "(int)objc_getClassList((void *)0, (int)0)", expr_options + ) if not num_objc_classes_value.error.Success(): - result.AppendMessage('error: %s' % - num_objc_classes_value.error.GetCString()) + result.AppendMessage("error: %s" % num_objc_classes_value.error.GetCString()) return num_objc_classes = num_objc_classes_value.GetValueAsUnsigned() if num_objc_classes == 0: - result.AppendMessage('error: no objective C classes in program') + result.AppendMessage("error: no objective C classes in program") return if args: @@ -1367,16 +1467,16 @@ # a member named "callback" whose type is "range_callback_t". This # will be used by our zone callbacks to call the range callback for # each malloc range. - expr_prefix = ''' + expr_prefix = """ struct $malloc_match { void *addr; uintptr_t size; uintptr_t offset; uintptr_t type; }; -''' +""" - user_init_code_format = ''' + user_init_code_format = """ #define MAX_MATCHES %u typedef int (*compare_callback_t)(const void *a, const void *b); typedef struct callback_baton_t { @@ -1438,38 +1538,41 @@ }; callback_baton_t baton = { range_callback, compare_callback, 0, {0}, (void *)0x%x, {0} }; int nc = (int)objc_getClassList(baton.classes, sizeof(baton.classes)/sizeof(Class)); -(void)qsort (baton.classes, sizeof(baton.classes)/sizeof(Class), sizeof(Class), compare_callback);''' +(void)qsort (baton.classes, sizeof(baton.classes)/sizeof(Class), sizeof(Class), compare_callback);""" # We must also define a snippet of code to be run that returns # the result of the expression we run. # Here we return NULL if our pointer was not found in any malloc blocks, # and we return the address of the matches array so we can then access # the matching results - user_return_code = '''if (baton.num_matches < MAX_MATCHES) + user_return_code = """if (baton.num_matches < MAX_MATCHES) baton.matches[baton.num_matches].addr = 0; // Terminate the matches array - baton.matches''' + baton.matches""" # Iterate through all of our ObjC class name arguments for class_name in args: addr_expr_str = "(void *)[%s class]" % class_name expr_options = lldb.SBExpressionOptions() expr_options.SetIgnoreBreakpoints(True) - expr_options.SetTimeoutInMicroSeconds( - 1 * 1000 * 1000) # 1 second timeout + expr_options.SetTimeoutInMicroSeconds(1 * 1000 * 1000) # 1 second timeout expr_options.SetTryAllThreads(True) expr_options.SetLanguage(lldb.eLanguageTypeObjC_plus_plus) - expr_sbvalue = frame.EvaluateExpression( - addr_expr_str, expr_options) + expr_sbvalue = frame.EvaluateExpression(addr_expr_str, expr_options) if expr_sbvalue.error.Success(): isa = expr_sbvalue.unsigned if isa: - options.type = 'isa' + options.type = "isa" result.AppendMessage( - 'Searching for all instances of classes or subclasses of "%s" (isa=0x%x)' % - (class_name, isa)) + 'Searching for all instances of classes or subclasses of "%s" (isa=0x%x)' + % (class_name, isa) + ) user_init_code = user_init_code_format % ( - options.max_matches, num_objc_classes, isa) + options.max_matches, + num_objc_classes, + isa, + ) expr = get_iterate_memory_expr( - options, process, user_init_code, user_return_code) - arg_str_description = 'objective C classes with isa 0x%x' % isa + options, process, user_init_code, user_return_code + ) + arg_str_description = "objective C classes with isa 0x%x" % isa display_match_results( process, result, @@ -1477,22 +1580,26 @@ arg_str_description, expr, True, - expr_prefix) + expr_prefix, + ) else: result.AppendMessage( - 'error: Can\'t find isa for an ObjC class named "%s"' % - (class_name)) + 'error: Can\'t find isa for an ObjC class named "%s"' + % (class_name) + ) else: result.AppendMessage( - 'error: expression error for "%s": %s' % - (addr_expr_str, expr_sbvalue.error)) + 'error: expression error for "%s": %s' + % (addr_expr_str, expr_sbvalue.error) + ) else: - result.AppendMessage( - 'error: command takes one or more C string arguments') + result.AppendMessage("error: command takes one or more C string arguments") -if __name__ == '__main__': + +if __name__ == "__main__": lldb.debugger = lldb.SBDebugger.Create() + def __lldb_init_module(debugger, internal_dict): # Make the options so we can generate the help text for the new LLDB # command line command prior to registering it with LLDB below. This way @@ -1502,20 +1609,16 @@ cstr_refs.__doc__ = get_cstr_refs_options().format_help() malloc_info.__doc__ = get_malloc_info_options().format_help() objc_refs.__doc__ = get_objc_refs_options().format_help() + debugger.HandleCommand("command script add -o -f %s.ptr_refs ptr_refs" % __name__) + debugger.HandleCommand("command script add -o -f %s.cstr_refs cstr_refs" % __name__) debugger.HandleCommand( - 'command script add -o -f %s.ptr_refs ptr_refs' % - __name__) - debugger.HandleCommand( - 'command script add -o -f %s.cstr_refs cstr_refs' % - __name__) + "command script add -o -f %s.malloc_info malloc_info" % __name__ + ) debugger.HandleCommand( - 'command script add -o -f %s.malloc_info malloc_info' % - __name__) - debugger.HandleCommand( - 'command script add -o -f %s.find_variable find_variable' % - __name__) + "command script add -o -f %s.find_variable find_variable" % __name__ + ) # debugger.HandleCommand('command script add -o -f %s.section_ptr_refs section_ptr_refs' % package_name) - debugger.HandleCommand( - 'command script add -o -f %s.objc_refs objc_refs' % - __name__) - print('"malloc_info", "ptr_refs", "cstr_refs", "find_variable", and "objc_refs" commands have been installed, use the "--help" options on these commands for detailed help.') + debugger.HandleCommand("command script add -o -f %s.objc_refs objc_refs" % __name__) + print( + '"malloc_info", "ptr_refs", "cstr_refs", "find_variable", and "objc_refs" commands have been installed, use the "--help" options on these commands for detailed help.' + ) diff --git a/lldb/examples/python/armv7_cortex_m_target_defintion.py b/lldb/examples/python/armv7_cortex_m_target_defintion.py --- a/lldb/examples/python/armv7_cortex_m_target_defintion.py +++ b/lldb/examples/python/armv7_cortex_m_target_defintion.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -#===-- armv7_cortex_m_target_definition.py.py ------------------*- C++ -*-===// +# ===-- armv7_cortex_m_target_definition.py.py ------------------*- C++ -*-===// # # The LLVM Compiler Infrastructure # @@ -7,134 +7,252 @@ # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # -#===----------------------------------------------------------------------===// +# ===----------------------------------------------------------------------===// -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # DESCRIPTION # # This file can be used with the following setting: # plugin.process.gdb-remote.target-definition-file -# This setting should be used when you are trying to connect to a +# This setting should be used when you are trying to connect to a # remote GDB server that doesn't support any of the register discovery -# packets that LLDB normally uses. +# packets that LLDB normally uses. # # Why is this necessary? LLDB doesn't require a new build of LLDB that # targets each new architecture you will debug with. Instead, all -# architectures are supported and LLDB relies on extra GDB server +# architectures are supported and LLDB relies on extra GDB server # packets to discover the target we are connecting to so that is can # show the right registers for each target. This allows the GDB server # to change and add new registers without requiring a new LLDB build # just so we can see new registers. # # This file implements the x86_64 registers for the darwin version of -# GDB and allows you to connect to servers that use this register set. -# +# GDB and allows you to connect to servers that use this register set. +# # USAGE # # (lldb) settings set plugin.process.gdb-remote.target-definition-file /path/to/armv7_cortex_m_target_definition.py # (lldb) gdb-remote other.baz.com:1234 # -# The target definition file will get used if and only if the +# The target definition file will get used if and only if the # qRegisterInfo packets are not supported when connecting to a remote # GDB server. -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- from lldb import * # DWARF register numbers name_to_dwarf_regnum = { - 'r0' : 0 , - 'r1' : 1 , - 'r2' : 2 , - 'r3' : 3 , - 'r4' : 4 , - 'r5' : 5 , - 'r6' : 6 , - 'r7' : 7 , - 'r9' : 8 , - 'r10' : 9 , - 'r11' : 10, - 'r12' : 11, - 'sp' : 12, - 'lr' : 13, - 'pc' : 14, - 'r15' : 15, - 'xpsr' : 16, -}; + "r0": 0, + "r1": 1, + "r2": 2, + "r3": 3, + "r4": 4, + "r5": 5, + "r6": 6, + "r7": 7, + "r9": 8, + "r10": 9, + "r11": 10, + "r12": 11, + "sp": 12, + "lr": 13, + "pc": 14, + "r15": 15, + "xpsr": 16, +} name_to_generic_regnum = { - 'pc' : LLDB_REGNUM_GENERIC_PC, - 'sp' : LLDB_REGNUM_GENERIC_SP, - 'r7' : LLDB_REGNUM_GENERIC_FP, - 'lr' : LLDB_REGNUM_GENERIC_RA, - 'r0' : LLDB_REGNUM_GENERIC_ARG1, - 'r1' : LLDB_REGNUM_GENERIC_ARG2, - 'r2' : LLDB_REGNUM_GENERIC_ARG3, - 'r3' : LLDB_REGNUM_GENERIC_ARG4 -}; - - -def get_reg_num (reg_num_dict, reg_name): + "pc": LLDB_REGNUM_GENERIC_PC, + "sp": LLDB_REGNUM_GENERIC_SP, + "r7": LLDB_REGNUM_GENERIC_FP, + "lr": LLDB_REGNUM_GENERIC_RA, + "r0": LLDB_REGNUM_GENERIC_ARG1, + "r1": LLDB_REGNUM_GENERIC_ARG2, + "r2": LLDB_REGNUM_GENERIC_ARG3, + "r3": LLDB_REGNUM_GENERIC_ARG4, +} + + +def get_reg_num(reg_num_dict, reg_name): if reg_name in reg_num_dict: return reg_num_dict[reg_name] return LLDB_INVALID_REGNUM -def get_reg_num (reg_num_dict, reg_name): + +def get_reg_num(reg_num_dict, reg_name): if reg_name in reg_num_dict: return reg_num_dict[reg_name] return LLDB_INVALID_REGNUM - + + armv7_register_infos = [ -{ 'name':'r0' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo, 'alt-name':'arg1' }, -{ 'name':'r1' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo, 'alt-name':'arg2' }, -{ 'name':'r2' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo, 'alt-name':'arg3' }, -{ 'name':'r3' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo, 'alt-name':'arg4' }, -{ 'name':'r4' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo }, -{ 'name':'r5' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo }, -{ 'name':'r6' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo }, -{ 'name':'r7' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo, 'alt-name':'fp' }, -{ 'name':'r8' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo }, -{ 'name':'r9' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo }, -{ 'name':'r10' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo }, -{ 'name':'r11' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo }, -{ 'name':'r12' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo }, -{ 'name':'sp' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo, 'alt-name':'r13' }, -{ 'name':'lr' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo, 'alt-name':'r14' }, -{ 'name':'pc' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo, 'alt-name':'r15' }, -{ 'name':'xpsr' , 'set':0, 'bitsize':32 , 'encoding':eEncodingUint , 'format':eFormatAddressInfo, 'alt-name':'cpsr' }, -]; + { + "name": "r0", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg1", + }, + { + "name": "r1", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg2", + }, + { + "name": "r2", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg3", + }, + { + "name": "r3", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg4", + }, + { + "name": "r4", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r5", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r6", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r7", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "fp", + }, + { + "name": "r8", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r9", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r10", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r11", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r12", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "sp", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "r13", + }, + { + "name": "lr", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "r14", + }, + { + "name": "pc", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "r15", + }, + { + "name": "xpsr", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "cpsr", + }, +] g_target_definition = None -def get_target_definition (): + +def get_target_definition(): global g_target_definition if g_target_definition == None: g_target_definition = {} offset = 0 for reg_info in armv7_register_infos: - reg_name = reg_info['name'] + reg_name = reg_info["name"] - if 'slice' not in reg_info and 'composite' not in reg_info: - reg_info['offset'] = offset - offset += reg_info['bitsize'] / 8 + if "slice" not in reg_info and "composite" not in reg_info: + reg_info["offset"] = offset + offset += reg_info["bitsize"] / 8 - # Set the DWARF/eh_frame register number for this register if it has one + # Set the DWARF/eh_frame register number for this register if it has one reg_num = get_reg_num(name_to_dwarf_regnum, reg_name) if reg_num != LLDB_INVALID_REGNUM: - reg_info['gcc'] = reg_num - reg_info['ehframe'] = reg_num + reg_info["gcc"] = reg_num + reg_info["ehframe"] = reg_num - # Set the generic register number for this register if it has one + # Set the generic register number for this register if it has one reg_num = get_reg_num(name_to_generic_regnum, reg_name) if reg_num != LLDB_INVALID_REGNUM: - reg_info['generic'] = reg_num + reg_info["generic"] = reg_num - g_target_definition['sets'] = ['General Purpose Registers'] - g_target_definition['registers'] = armv7_register_infos - g_target_definition['host-info'] = { 'triple' : 'armv7em--', 'endian': eByteOrderLittle } - g_target_definition['g-packet-size'] = offset + g_target_definition["sets"] = ["General Purpose Registers"] + g_target_definition["registers"] = armv7_register_infos + g_target_definition["host-info"] = { + "triple": "armv7em--", + "endian": eByteOrderLittle, + } + g_target_definition["g-packet-size"] = offset return g_target_definition + def get_dynamic_setting(target, setting_name): - if setting_name == 'gdb-server-target-definition': + if setting_name == "gdb-server-target-definition": return get_target_definition() diff --git a/lldb/examples/python/bsd.py b/lldb/examples/python/bsd.py --- a/lldb/examples/python/bsd.py +++ b/lldb/examples/python/bsd.py @@ -14,20 +14,18 @@ def memdump(src, bytes_per_line=16, address=0): - FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' - for x in range(256)]) + FILTER = "".join([(len(repr(chr(x))) == 3) and chr(x) or "." for x in range(256)]) for i in range(0, len(src), bytes_per_line): - s = src[i:i+bytes_per_line] - hex_bytes = ' '.join(["%02x" % (ord(x)) for x in s]) + s = src[i : i + bytes_per_line] + hex_bytes = " ".join(["%02x" % (ord(x)) for x in s]) ascii = s.translate(FILTER) - print("%#08.8x: %-*s %s" % (address+i, bytes_per_line*3, hex_bytes, - ascii)) + print("%#08.8x: %-*s %s" % (address + i, bytes_per_line * 3, hex_bytes, ascii)) class Object(object): def __init__(self, file): def read_str(file, str_len): - return file.read(str_len).rstrip('\0 ') + return file.read(str_len).rstrip("\0 ") def read_int(file, str_len, base): return int(read_str(file, str_len), base) @@ -41,12 +39,11 @@ self.mode = read_int(file, 8, 8) self.size = read_int(file, 10, 10) if file.read(2) != ARFMAG: - raise ValueError('invalid BSD object at offset %#08.8x' % ( - self.offset)) + raise ValueError("invalid BSD object at offset %#08.8x" % (self.offset)) # If we have an extended name read it. Extended names start with name_len = 0 if self.name.startswith(AR_EFMT1): - name_len = int(self.name[len(AR_EFMT1):], 10) + name_len = int(self.name[len(AR_EFMT1) :], 10) self.name = read_str(file, name_len) self.obj_offset = file.tell() self.obj_size = self.size - name_len @@ -54,20 +51,29 @@ def dump(self, f=sys.stdout, flat=True): if flat: - f.write('%#08.8x: %#08.8x %5u %5u %6o %#08.8x %s\n' % (self.offset, - self.date, self.uid, self.gid, self.mode, self.size, - self.name)) + f.write( + "%#08.8x: %#08.8x %5u %5u %6o %#08.8x %s\n" + % ( + self.offset, + self.date, + self.uid, + self.gid, + self.mode, + self.size, + self.name, + ) + ) else: - f.write('%#08.8x: \n' % self.offset) + f.write("%#08.8x: \n" % self.offset) f.write(' name = "%s"\n' % self.name) - f.write(' date = %#08.8x\n' % self.date) - f.write(' uid = %i\n' % self.uid) - f.write(' gid = %i\n' % self.gid) - f.write(' mode = %o\n' % self.mode) - f.write(' size = %#08.8x\n' % (self.size)) + f.write(" date = %#08.8x\n" % self.date) + f.write(" uid = %i\n" % self.uid) + f.write(" gid = %i\n" % self.gid) + f.write(" mode = %o\n" % self.mode) + f.write(" size = %#08.8x\n" % (self.size)) self.file.seek(self.obj_offset, 0) first_bytes = self.file.read(4) - f.write('bytes = ') + f.write("bytes = ") memdump(first_bytes) def get_bytes(self): @@ -78,11 +84,11 @@ return bytes def save(self, path=None, overwrite=False): - ''' - Save the contents of the object to disk using 'path' argument as - the path, or save it to the current working directory using the - object name. - ''' + """ + Save the contents of the object to disk using 'path' argument as + the path, or save it to the current working directory using the + object name. + """ if path is None: path = self.name @@ -90,7 +96,7 @@ print('error: outfile "%s" already exists' % (path)) return print('Saving "%s" to "%s"...' % (self.name, path)) - with open(path, 'w') as f: + with open(path, "w") as f: f.write(self.get_bytes()) @@ -102,13 +108,13 @@ length = len(self.bytes) if offset >= length: return None - return self.bytes[offset:self.bytes.find('\0', offset)] + return self.bytes[offset : self.bytes.find("\0", offset)] class Archive(object): def __init__(self, path): self.path = path - self.file = open(path, 'r') + self.file = open(path, "r") self.objects = [] self.offset_to_object = {} if self.file.read(SARMAG) != ARMAG: @@ -129,12 +135,12 @@ return None def find(self, name, mtime=None, f=sys.stdout): - ''' - Find an object(s) by name with optional modification time. There - can be multple objects with the same name inside and possibly with - the same modification time within a BSD archive so clients must be - prepared to get multiple results. - ''' + """ + Find an object(s) by name with optional modification time. There + can be multple objects with the same name inside and possibly with + the same modification time within a BSD archive so clients must be + prepared to get multiple results. + """ matches = [] for obj in self.objects: if obj.name == name and (mtime is None or mtime == obj.date): @@ -143,14 +149,15 @@ @classmethod def dump_header(self, f=sys.stdout): - f.write(' DATE UID GID MODE SIZE NAME\n') - f.write(' ---------- ----- ----- ------ ---------- ' - '--------------\n') + f.write(" DATE UID GID MODE SIZE NAME\n") + f.write( + " ---------- ----- ----- ------ ---------- " "--------------\n" + ) def get_symdef(self): def get_uint32(file): - '''Extract a uint32_t from the current file position.''' - v, = struct.unpack('=I', file.read(4)) + """Extract a uint32_t from the current file position.""" + (v,) = struct.unpack("=I", file.read(4)) return v for obj in self.objects: @@ -158,7 +165,7 @@ if obj.name.startswith("__.SYMDEF"): self.file.seek(obj.obj_offset, 0) ranlib_byte_size = get_uint32(self.file) - num_ranlib_structs = ranlib_byte_size/8 + num_ranlib_structs = ranlib_byte_size / 8 str_offset_pairs = [] for _ in range(num_ranlib_structs): strx = get_uint32(self.file) @@ -171,62 +178,66 @@ return symdef def get_object_dicts(self): - ''' - Returns an array of object dictionaries that contain they following - keys: - 'object': the actual bsd.Object instance - 'symdefs': an array of symbol names that the object contains - as found in the "__.SYMDEF" item in the archive - ''' + """ + Returns an array of object dictionaries that contain they following + keys: + 'object': the actual bsd.Object instance + 'symdefs': an array of symbol names that the object contains + as found in the "__.SYMDEF" item in the archive + """ symdefs = self.get_symdef() symdef_dict = {} if symdefs: - for (name, offset) in symdefs: + for name, offset in symdefs: if offset in symdef_dict: object_dict = symdef_dict[offset] else: object_dict = { - 'object': self.get_object_at_offset(offset), - 'symdefs': [] + "object": self.get_object_at_offset(offset), + "symdefs": [], } symdef_dict[offset] = object_dict - object_dict['symdefs'].append(name) + object_dict["symdefs"].append(name) object_dicts = [] for offset in sorted(symdef_dict): object_dicts.append(symdef_dict[offset]) return object_dicts def dump(self, f=sys.stdout, flat=True): - f.write('%s:\n' % self.path) + f.write("%s:\n" % self.path) if flat: self.dump_header(f=f) for obj in self.objects: obj.dump(f=f, flat=flat) + class Interactive(cmd.Cmd): - '''Interactive prompt for exploring contents of BSD archive files, type - "help" to see a list of supported commands.''' + """Interactive prompt for exploring contents of BSD archive files, type + "help" to see a list of supported commands.""" + image_option_parser = None def __init__(self, archives): cmd.Cmd.__init__(self) self.use_rawinput = False - self.intro = ('Interactive BSD archive prompt, type "help" to see a ' - 'list of supported commands.') + self.intro = ( + 'Interactive BSD archive prompt, type "help" to see a ' + "list of supported commands." + ) self.archives = archives - self.prompt = '% ' + self.prompt = "% " def default(self, line): - '''Catch all for unknown command, which will exit the interpreter.''' + """Catch all for unknown command, which will exit the interpreter.""" print("unknown command: %s" % line) return True def do_q(self, line): - '''Quit command''' + """Quit command""" return True def do_quit(self, line): - '''Quit command''' + """Quit command""" return True def do_extract(self, line): @@ -241,10 +252,9 @@ object.save(overwrite=False) extracted = True if not extracted: - print('error: no object matches "%s" in any archives' % ( - object_name)) + print('error: no object matches "%s" in any archives' % (object_name)) else: - print('error: must specify the name of an object to extract') + print("error: must specify the name of an object to extract") def do_ls(self, line): args = shlex.split(line) @@ -256,78 +266,103 @@ for object in matches: object.dump(flat=False) else: - print('error: no object matches "%s" in "%s"' % ( - object_name, archive.path)) + print( + 'error: no object matches "%s" in "%s"' + % (object_name, archive.path) + ) else: for archive in self.archives: archive.dump(flat=True) - print('') - + print("") def main(): - parser = optparse.OptionParser( - prog='bsd', - description='Utility for BSD archives') + parser = optparse.OptionParser(prog="bsd", description="Utility for BSD archives") parser.add_option( - '--object', - type='string', - dest='object_name', + "--object", + type="string", + dest="object_name", default=None, - help=('Specify the name of a object within the BSD archive to get ' - 'information on')) + help=( + "Specify the name of a object within the BSD archive to get " + "information on" + ), + ) parser.add_option( - '-s', '--symbol', - type='string', - dest='find_symbol', + "-s", + "--symbol", + type="string", + dest="find_symbol", default=None, - help=('Specify the name of a symbol within the BSD archive to get ' - 'information on from SYMDEF')) + help=( + "Specify the name of a symbol within the BSD archive to get " + "information on from SYMDEF" + ), + ) parser.add_option( - '--symdef', - action='store_true', - dest='symdef', + "--symdef", + action="store_true", + dest="symdef", default=False, - help=('Dump the information in the SYMDEF.')) + help=("Dump the information in the SYMDEF."), + ) parser.add_option( - '-v', '--verbose', - action='store_true', - dest='verbose', + "-v", + "--verbose", + action="store_true", + dest="verbose", default=False, - help='Enable verbose output') + help="Enable verbose output", + ) parser.add_option( - '-e', '--extract', - action='store_true', - dest='extract', + "-e", + "--extract", + action="store_true", + dest="extract", default=False, - help=('Specify this to extract the object specified with the --object ' - 'option. There must be only one object with a matching name or ' - 'the --mtime option must be specified to uniquely identify a ' - 'single object.')) + help=( + "Specify this to extract the object specified with the --object " + "option. There must be only one object with a matching name or " + "the --mtime option must be specified to uniquely identify a " + "single object." + ), + ) parser.add_option( - '-m', '--mtime', - type='int', - dest='mtime', + "-m", + "--mtime", + type="int", + dest="mtime", default=None, - help=('Specify the modification time of the object an object. This ' - 'option is used with either the --object or --extract options.')) + help=( + "Specify the modification time of the object an object. This " + "option is used with either the --object or --extract options." + ), + ) parser.add_option( - '-o', '--outfile', - type='string', - dest='outfile', + "-o", + "--outfile", + type="string", + dest="outfile", default=None, - help=('Specify a different name or path for the file to extract when ' - 'using the --extract option. If this option isn\'t specified, ' - 'then the extracted object file will be extracted into the ' - 'current working directory if a file doesn\'t already exist ' - 'with that name.')) + help=( + "Specify a different name or path for the file to extract when " + "using the --extract option. If this option isn't specified, " + "then the extracted object file will be extracted into the " + "current working directory if a file doesn't already exist " + "with that name." + ), + ) parser.add_option( - '-i', '--interactive', - action='store_true', - dest='interactive', + "-i", + "--interactive", + action="store_true", + dest="interactive", default=False, - help=('Enter an interactive shell that allows users to interactively ' - 'explore contents of .a files.')) + help=( + "Enter an interactive shell that allows users to interactively " + "explore contents of .a files." + ), + ) (options, args) = parser.parse_args(sys.argv[1:]) @@ -342,7 +377,7 @@ for path in args: archive = Archive(path) if options.object_name: - print('%s:\n' % (path)) + print("%s:\n" % (path)) matches = archive.find(options.object_name, options.mtime) if matches: dump_all = True @@ -351,58 +386,63 @@ dump_all = False matches[0].save(path=options.outfile, overwrite=False) else: - print('error: multiple objects match "%s". Specify ' - 'the modification time using --mtime.' % ( - options.object_name)) + print( + 'error: multiple objects match "%s". Specify ' + "the modification time using --mtime." + % (options.object_name) + ) if dump_all: for obj in matches: obj.dump(flat=False) else: - print('error: object "%s" not found in archive' % ( - options.object_name)) + print('error: object "%s" not found in archive' % (options.object_name)) elif options.find_symbol: symdefs = archive.get_symdef() if symdefs: success = False - for (name, offset) in symdefs: + for name, offset in symdefs: obj = archive.get_object_at_offset(offset) if name == options.find_symbol: print('Found "%s" in:' % (options.find_symbol)) obj.dump(flat=False) success = True if not success: - print('Didn\'t find "%s" in any objects' % ( - options.find_symbol)) + print('Didn\'t find "%s" in any objects' % (options.find_symbol)) else: print("error: no __.SYMDEF was found") elif options.symdef: object_dicts = archive.get_object_dicts() for object_dict in object_dicts: - object_dict['object'].dump(flat=False) + object_dict["object"].dump(flat=False) print("symbols:") - for name in object_dict['symdefs']: + for name in object_dict["symdefs"]: print(" %s" % (name)) else: archive.dump(flat=not options.verbose) -if __name__ == '__main__': +if __name__ == "__main__": main() def print_mtime_error(result, dmap_mtime, actual_mtime): - print("error: modification time in debug map (%#08.8x) doesn't " - "match the .o file modification time (%#08.8x)" % ( - dmap_mtime, actual_mtime), file=result) + print( + "error: modification time in debug map (%#08.8x) doesn't " + "match the .o file modification time (%#08.8x)" % (dmap_mtime, actual_mtime), + file=result, + ) def print_file_missing_error(result, path): - print("error: file \"%s\" doesn't exist" % (path), file=result) + print('error: file "%s" doesn\'t exist' % (path), file=result) def print_multiple_object_matches(result, object_name, mtime, matches): - print("error: multiple matches for object '%s' with with " - "modification time %#08.8x:" % (object_name, mtime), file=result) + print( + "error: multiple matches for object '%s' with with " + "modification time %#08.8x:" % (object_name, mtime), + file=result, + ) Archive.dump_header(f=result) for match in matches: match.dump(f=result, flat=True) @@ -411,15 +451,18 @@ def print_archive_object_error(result, object_name, mtime, archive): matches = archive.find(object_name, f=result) if len(matches) > 0: - print("error: no objects have a modification time that " - "matches %#08.8x for '%s'. Potential matches:" % ( - mtime, object_name), file=result) + print( + "error: no objects have a modification time that " + "matches %#08.8x for '%s'. Potential matches:" % (mtime, object_name), + file=result, + ) Archive.dump_header(f=result) for match in matches: match.dump(f=result, flat=True) else: - print("error: no object named \"%s\" found in archive:" % ( - object_name), file=result) + print( + 'error: no object named "%s" found in archive:' % (object_name), file=result + ) Archive.dump_header(f=result) for match in archive.objects: match.dump(f=result, flat=True) @@ -431,21 +474,21 @@ def create_options(self): usage = "usage: %prog [options]" - description = '''This command reports any .o files that are missing -or whose modification times don't match in the debug map of an executable.''' + description = """This command reports any .o files that are missing +or whose modification times don't match in the debug map of an executable.""" self.parser = optparse.OptionParser( - description=description, - prog=self.name, - usage=usage, - add_help_option=False) + description=description, prog=self.name, usage=usage, add_help_option=False + ) self.parser.add_option( - '-e', '--errors', - action='store_true', - dest='errors', + "-e", + "--errors", + action="store_true", + dest="errors", default=False, - help="Only show errors") + help="Only show errors", + ) def get_short_help(self): return "Verify debug map object files." @@ -459,6 +502,7 @@ def __call__(self, debugger, command, exe_ctx, result): import lldb + # Use the Shell Lexer to properly parse up command options just like a # shell would command_args = shlex.split(command) @@ -478,9 +522,11 @@ for module_spec in args: module = target.module[module_spec] if not (module and module.IsValid()): - result.SetError('error: invalid module specification: "%s". ' - 'Specify the full path, basename, or UUID of ' - 'a module ' % (module_spec)) + result.SetError( + 'error: invalid module specification: "%s". ' + "Specify the full path, basename, or UUID of " + "a module " % (module_spec) + ) return num_symbols = module.GetNumSymbols() num_errors = 0 @@ -493,30 +539,28 @@ continue # Extract the value of the symbol by dumping the # symbol. The value is the mod time. - dmap_mtime = int(str(symbol).split('value = ') - [1].split(',')[0], 16) + dmap_mtime = int(str(symbol).split("value = ")[1].split(",")[0], 16) if not options.errors: - print('%s' % (path), file=result) + print("%s" % (path), file=result) if os.path.exists(path): actual_mtime = int(os.stat(path).st_mtime) if dmap_mtime != actual_mtime: num_errors += 1 if options.errors: - print('%s' % (path), end=' ', file=result) - print_mtime_error(result, dmap_mtime, - actual_mtime) - elif path[-1] == ')': - (archive_path, object_name) = path[0:-1].split('(') + print("%s" % (path), end=" ", file=result) + print_mtime_error(result, dmap_mtime, actual_mtime) + elif path[-1] == ")": + (archive_path, object_name) = path[0:-1].split("(") if not archive_path and not object_name: num_errors += 1 if options.errors: - print('%s' % (path), end=' ', file=result) + print("%s" % (path), end=" ", file=result) print_file_missing_error(path) continue if not os.path.exists(archive_path): num_errors += 1 if options.errors: - print('%s' % (path), end=' ', file=result) + print("%s" % (path), end=" ", file=result) print_file_missing_error(archive_path) continue if archive_path in archives: @@ -527,26 +571,27 @@ matches = archive.find(object_name, dmap_mtime) num_matches = len(matches) if num_matches == 1: - print('1 match', file=result) + print("1 match", file=result) obj = matches[0] if obj.date != dmap_mtime: num_errors += 1 if options.errors: - print('%s' % (path), end=' ', file=result) + print("%s" % (path), end=" ", file=result) print_mtime_error(result, dmap_mtime, obj.date) elif num_matches == 0: num_errors += 1 if options.errors: - print('%s' % (path), end=' ', file=result) - print_archive_object_error(result, object_name, - dmap_mtime, archive) + print("%s" % (path), end=" ", file=result) + print_archive_object_error( + result, object_name, dmap_mtime, archive + ) elif num_matches > 1: num_errors += 1 if options.errors: - print('%s' % (path), end=' ', file=result) - print_multiple_object_matches(result, - object_name, - dmap_mtime, matches) + print("%s" % (path), end=" ", file=result) + print_multiple_object_matches( + result, object_name, dmap_mtime, matches + ) if num_errors > 0: print("%u errors found" % (num_errors), file=result) else: @@ -558,7 +603,10 @@ # interpreter. # Add any commands contained in this module to LLDB debugger.HandleCommand( - 'command script add -o -c %s.VerifyDebugMapCommand %s' % ( - __name__, VerifyDebugMapCommand.name)) - print('The "%s" command has been installed, type "help %s" for detailed ' - 'help.' % (VerifyDebugMapCommand.name, VerifyDebugMapCommand.name)) + "command script add -o -c %s.VerifyDebugMapCommand %s" + % (__name__, VerifyDebugMapCommand.name) + ) + print( + 'The "%s" command has been installed, type "help %s" for detailed ' + "help." % (VerifyDebugMapCommand.name, VerifyDebugMapCommand.name) + ) diff --git a/lldb/examples/python/cmdtemplate.py b/lldb/examples/python/cmdtemplate.py --- a/lldb/examples/python/cmdtemplate.py +++ b/lldb/examples/python/cmdtemplate.py @@ -17,31 +17,36 @@ class FrameStatCommand: - program = 'framestats' + program = "framestats" @classmethod def register_lldb_command(cls, debugger, module_name): parser = cls.create_options() cls.__doc__ = parser.format_help() # Add any commands contained in this module to LLDB - command = 'command script add -o -c %s.%s %s' % (module_name, - cls.__name__, - cls.program) + command = "command script add -o -c %s.%s %s" % ( + module_name, + cls.__name__, + cls.program, + ) debugger.HandleCommand(command) - print('The "{0}" command has been installed, type "help {0}" or "{0} ' - '--help" for detailed help.'.format(cls.program)) + print( + 'The "{0}" command has been installed, type "help {0}" or "{0} ' + '--help" for detailed help.'.format(cls.program) + ) @classmethod def create_options(cls): - usage = "usage: %prog [options]" - description = ('This command is meant to be an example of how to make ' - 'an LLDB command that does something useful, follows ' - 'best practices, and exploits the SB API. ' - 'Specifically, this command computes the aggregate ' - 'and average size of the variables in the current ' - 'frame and allows you to tweak exactly which variables ' - 'are to be accounted in the computation.') + description = ( + "This command is meant to be an example of how to make " + "an LLDB command that does something useful, follows " + "best practices, and exploits the SB API. " + "Specifically, this command computes the aggregate " + "and average size of the variables in the current " + "frame and allows you to tweak exactly which variables " + "are to be accounted in the computation." + ) # Pass add_help_option = False, since this keeps the command in line # with lldb commands, and we wire up "help command" to work by @@ -50,39 +55,44 @@ description=description, prog=cls.program, usage=usage, - add_help_option=False) + add_help_option=False, + ) parser.add_option( - '-i', - '--in-scope', - action='store_true', - dest='inscope', - help='in_scope_only = True', - default=True) + "-i", + "--in-scope", + action="store_true", + dest="inscope", + help="in_scope_only = True", + default=True, + ) parser.add_option( - '-a', - '--arguments', - action='store_true', - dest='arguments', - help='arguments = True', - default=True) + "-a", + "--arguments", + action="store_true", + dest="arguments", + help="arguments = True", + default=True, + ) parser.add_option( - '-l', - '--locals', - action='store_true', - dest='locals', - help='locals = True', - default=True) + "-l", + "--locals", + action="store_true", + dest="locals", + help="locals = True", + default=True, + ) parser.add_option( - '-s', - '--statics', - action='store_true', - dest='statics', - help='statics = True', - default=True) + "-s", + "--statics", + action="store_true", + dest="statics", + help="statics = True", + default=True, + ) return parser @@ -118,10 +128,8 @@ return variables_list = frame.GetVariables( - options.arguments, - options.locals, - options.statics, - options.inscope) + options.arguments, options.locals, options.statics, options.inscope + ) variables_count = variables_list.GetSize() if variables_count == 0: print("no variables here", file=result) @@ -132,16 +140,19 @@ variable_type = variable.GetType() total_size = total_size + variable_type.GetByteSize() average_size = float(total_size) / variables_count - print("Your frame has %d variables. Their total size " - "is %d bytes. The average size is %f bytes" % ( - variables_count, total_size, average_size), file=result) + print( + "Your frame has %d variables. Their total size " + "is %d bytes. The average size is %f bytes" + % (variables_count, total_size, average_size), + file=result, + ) # not returning anything is akin to returning success def __lldb_init_module(debugger, dict): # Register all classes that have a register_lldb_command method for _name, cls in inspect.getmembers(sys.modules[__name__]): - if inspect.isclass(cls) and callable(getattr(cls, - "register_lldb_command", - None)): + if inspect.isclass(cls) and callable( + getattr(cls, "register_lldb_command", None) + ): cls.register_lldb_command(debugger, __name__) diff --git a/lldb/examples/python/crashlog.py b/lldb/examples/python/crashlog.py --- a/lldb/examples/python/crashlog.py +++ b/lldb/examples/python/crashlog.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # Be sure to add the python path that points to the LLDB shared library. # # To use this in the embedded python interpreter using "lldb": @@ -24,7 +24,7 @@ # # On MacOSX sh, bash: # PYTHONPATH=/path/to/LLDB.framework/Resources/Python ./crashlog.py ~/Library/Logs/DiagnosticReports/a.crash -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- import abc import concurrent.futures @@ -54,7 +54,9 @@ except ImportError: # Ask the command line driver for the path to the lldb module. Copy over # the environment so that SDKROOT is propagated to xcrun. - command = ['xcrun', 'lldb', '-P'] if platform.system() == 'Darwin' else ['lldb', '-P'] + command = ( + ["xcrun", "lldb", "-P"] if platform.system() == "Darwin" else ["lldb", "-P"] + ) # Extend the PYTHONPATH if the path exists and isn't already there. lldb_python_path = subprocess.check_output(command).decode("utf-8").strip() if os.path.exists(lldb_python_path) and not sys.path.__contains__(lldb_python_path): @@ -63,17 +65,21 @@ try: import lldb except ImportError: - print("error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly") + print( + "error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly" + ) sys.exit(1) from lldb.utils import symbolication + def read_plist(s): if sys.version_info.major == 3: return plistlib.loads(s) else: return plistlib.readPlistFromString(s) + class CrashLog(symbolication.Symbolicator): class Thread: """Class that represents a thread in a darwin crash log""" @@ -93,13 +99,16 @@ def dump(self, prefix): if self.app_specific_backtrace: - print("%Application Specific Backtrace[%u] %s" % (prefix, self.index, self.reason)) + print( + "%Application Specific Backtrace[%u] %s" + % (prefix, self.index, self.reason) + ) else: print("%sThread[%u] %s" % (prefix, self.index, self.reason)) if self.frames: print("%s Frames:" % (prefix)) for frame in self.frames: - frame.dump(prefix + ' ') + frame.dump(prefix + " ") if self.registers: print("%s Registers:" % (prefix)) for reg in self.registers.keys(): @@ -116,37 +125,59 @@ display_frame_idx = -1 for frame_idx, frame in enumerate(self.frames): disassemble = ( - this_thread_crashed or options.disassemble_all_threads) and frame_idx < options.disassemble_depth + this_thread_crashed or options.disassemble_all_threads + ) and frame_idx < options.disassemble_depth # Except for the zeroth frame, we should subtract 1 from every # frame pc to get the previous line entry. pc = frame.pc & crash_log.addr_mask pc = pc if frame_idx == 0 or pc == 0 else pc - 1 - symbolicated_frame_addresses = crash_log.symbolicate(pc, options.verbose) + symbolicated_frame_addresses = crash_log.symbolicate( + pc, options.verbose + ) if symbolicated_frame_addresses: symbolicated_frame_address_idx = 0 for symbolicated_frame_address in symbolicated_frame_addresses: display_frame_idx += 1 - print('[%3u] %s' % (frame_idx, symbolicated_frame_address)) - if (options.source_all or self.did_crash( - )) and display_frame_idx < options.source_frames and options.source_context: + print("[%3u] %s" % (frame_idx, symbolicated_frame_address)) + if ( + (options.source_all or self.did_crash()) + and display_frame_idx < options.source_frames + and options.source_context + ): source_context = options.source_context - line_entry = symbolicated_frame_address.get_symbol_context().line_entry + line_entry = ( + symbolicated_frame_address.get_symbol_context().line_entry + ) if line_entry.IsValid(): strm = lldb.SBStream() if line_entry: crash_log.debugger.GetSourceManager().DisplaySourceLinesWithLineNumbers( - line_entry.file, line_entry.line, source_context, source_context, "->", strm) + line_entry.file, + line_entry.line, + source_context, + source_context, + "->", + strm, + ) source_text = strm.GetData() if source_text: # Indent the source a bit - indent_str = ' ' - join_str = '\n' + indent_str - print('%s%s' % (indent_str, join_str.join(source_text.split('\n')))) + indent_str = " " + join_str = "\n" + indent_str + print( + "%s%s" + % ( + indent_str, + join_str.join(source_text.split("\n")), + ) + ) if symbolicated_frame_address_idx == 0: if disassemble: - instructions = symbolicated_frame_address.get_instructions() + instructions = ( + symbolicated_frame_address.get_instructions() + ) if instructions: print() symbolication.disassemble_instructions( @@ -155,7 +186,8 @@ frame.pc, options.disassemble_before, options.disassemble_after, - frame.index > 0) + frame.index > 0, + ) print() symbolicated_frame_address_idx += 1 else: @@ -165,8 +197,8 @@ for reg in self.registers.keys(): print(" %-8s = %#16.16x" % (reg, self.registers[reg])) elif self.crashed: - print() - print("No thread state (register information) available") + print() + print("No thread state (register information) available") def add_ident(self, ident): if ident not in self.idents: @@ -181,7 +213,7 @@ else: s = "Thread[%u]" % self.index if self.reason: - s += ' %s' % self.reason + s += " %s" % self.reason return s class Frame: @@ -194,8 +226,7 @@ def __str__(self): if self.description: - return "[%3u] 0x%16.16x %s" % ( - self.index, self.pc, self.description) + return "[%3u] 0x%16.16x %s" % (self.index, self.pc, self.description) else: return "[%3u] 0x%16.16x" % (self.index, self.pc) @@ -204,32 +235,27 @@ class DarwinImage(symbolication.Image): """Class that represents a binary images in a darwin crash log""" - dsymForUUIDBinary = '/usr/local/bin/dsymForUUID' + + dsymForUUIDBinary = "/usr/local/bin/dsymForUUID" if not os.path.exists(dsymForUUIDBinary): try: - dsymForUUIDBinary = subprocess.check_output('which dsymForUUID', - shell=True).decode("utf-8").rstrip('\n') + dsymForUUIDBinary = ( + subprocess.check_output("which dsymForUUID", shell=True) + .decode("utf-8") + .rstrip("\n") + ) except: dsymForUUIDBinary = "" - dwarfdump_uuid_regex = re.compile( - 'UUID: ([-0-9a-fA-F]+) \(([^\(]+)\) .*') + dwarfdump_uuid_regex = re.compile("UUID: ([-0-9a-fA-F]+) \(([^\(]+)\) .*") def __init__( - self, - text_addr_lo, - text_addr_hi, - identifier, - version, - uuid, - path, - verbose): + self, text_addr_lo, text_addr_hi, identifier, version, uuid, path, verbose + ): symbolication.Image.__init__(self, path, uuid) self.add_section( - symbolication.Section( - text_addr_lo, - text_addr_hi, - "__TEXT")) + symbolication.Section(text_addr_lo, text_addr_hi, "__TEXT") + ) self.identifier = identifier self.version = version self.verbose = verbose @@ -240,13 +266,15 @@ """ if self.verbose: return True - return not (self.path.startswith("/System/Library/") or - self.path.startswith("/usr/lib/")) - + return not ( + self.path.startswith("/System/Library/") + or self.path.startswith("/usr/lib/") + ) def find_matching_slice(self): dwarfdump_cmd_output = subprocess.check_output( - 'dwarfdump --uuid "%s"' % self.path, shell=True).decode("utf-8") + 'dwarfdump --uuid "%s"' % self.path, shell=True + ).decode("utf-8") self_uuid = self.get_uuid() for line in dwarfdump_cmd_output.splitlines(): match = self.dwarfdump_uuid_regex.search(line) @@ -260,8 +288,12 @@ if not self.resolved_path: self.unavailable = True if self.show_symbol_progress(): - print(("error\n error: unable to locate '%s' with UUID %s" - % (self.path, self.get_normalized_uuid_string()))) + print( + ( + "error\n error: unable to locate '%s' with UUID %s" + % (self.path, self.get_normalized_uuid_string()) + ) + ) return False def locate_module_and_debug_symbols(self): @@ -273,41 +305,54 @@ uuid_str = self.get_normalized_uuid_string() if self.show_symbol_progress(): with print_lock: - print('Getting symbols for %s %s...' % (uuid_str, self.path)) + print("Getting symbols for %s %s..." % (uuid_str, self.path)) if os.path.exists(self.dsymForUUIDBinary): - dsym_for_uuid_command = '%s %s' % ( - self.dsymForUUIDBinary, uuid_str) + dsym_for_uuid_command = "%s %s" % (self.dsymForUUIDBinary, uuid_str) s = subprocess.check_output(dsym_for_uuid_command, shell=True) if s: try: plist_root = read_plist(s) except: with print_lock: - print(("Got exception: ", sys.exc_info()[1], " handling dsymForUUID output: \n", s)) + print( + ( + "Got exception: ", + sys.exc_info()[1], + " handling dsymForUUID output: \n", + s, + ) + ) raise if plist_root: plist = plist_root[uuid_str] if plist: - if 'DBGArchitecture' in plist: - self.arch = plist['DBGArchitecture'] - if 'DBGDSYMPath' in plist: - self.symfile = os.path.realpath( - plist['DBGDSYMPath']) - if 'DBGSymbolRichExecutable' in plist: + if "DBGArchitecture" in plist: + self.arch = plist["DBGArchitecture"] + if "DBGDSYMPath" in plist: + self.symfile = os.path.realpath(plist["DBGDSYMPath"]) + if "DBGSymbolRichExecutable" in plist: self.path = os.path.expanduser( - plist['DBGSymbolRichExecutable']) + plist["DBGSymbolRichExecutable"] + ) self.resolved_path = self.path if not self.resolved_path and os.path.exists(self.path): if not self.find_matching_slice(): return False if not self.resolved_path and not os.path.exists(self.path): try: - mdfind_results = subprocess.check_output( - ["/usr/bin/mdfind", - "com_apple_xcode_dsym_uuids == %s" % uuid_str]).decode("utf-8").splitlines() + mdfind_results = ( + subprocess.check_output( + [ + "/usr/bin/mdfind", + "com_apple_xcode_dsym_uuids == %s" % uuid_str, + ] + ) + .decode("utf-8") + .splitlines() + ) found_matching_slice = False for dsym in mdfind_results: - dwarf_dir = os.path.join(dsym, 'Contents/Resources/DWARF') + dwarf_dir = os.path.join(dsym, "Contents/Resources/DWARF") if not os.path.exists(dwarf_dir): # Not a dSYM bundle, probably an Xcode archive. continue @@ -315,18 +360,19 @@ print('falling back to binary inside "%s"' % dsym) self.symfile = dsym for filename in os.listdir(dwarf_dir): - self.path = os.path.join(dwarf_dir, filename) - if self.find_matching_slice(): - found_matching_slice = True - break + self.path = os.path.join(dwarf_dir, filename) + if self.find_matching_slice(): + found_matching_slice = True + break if found_matching_slice: - break + break except: pass if (self.resolved_path and os.path.exists(self.resolved_path)) or ( - self.path and os.path.exists(self.path)): + self.path and os.path.exists(self.path) + ): with print_lock: - print('Resolved symbols for %s %s...' % (uuid_str, self.path)) + print("Resolved symbols for %s %s..." % (uuid_str, self.path)) return True else: self.unavailable = True @@ -340,7 +386,9 @@ self.system_profile = list() self.threads = list() self.backtraces = list() # For application specific backtraces - self.idents = list() # A list of the required identifiers for doing all stack backtraces + self.idents = ( + list() + ) # A list of the required identifiers for doing all stack backtraces self.errors = list() self.exception = dict() self.crashed_thread_idx = -1 @@ -353,13 +401,13 @@ if self.backtraces: print("\nApplication Specific Backtraces:") for thread in self.backtraces: - thread.dump(' ') + thread.dump(" ") print("\nThreads:") for thread in self.threads: - thread.dump(' ') + thread.dump(" ") print("\nImages:") for image in self.images: - image.dump(' ') + image.dump(" ") def set_main_image(self, identifier): for i, image in enumerate(self.images): @@ -371,7 +419,7 @@ for image in self.images: if image.identifier == identifier: return image - regex_text = '^.*\.%s$' % (re.escape(identifier)) + regex_text = "^.*\.%s$" % (re.escape(identifier)) regex = re.compile(regex_text) for image in self.images: if regex.match(image.identifier): @@ -385,7 +433,7 @@ return self.target # We weren't able to open the main executable as, but we can still # symbolicate - print('crashlog.create_target()...2') + print("crashlog.create_target()...2") if self.idents: for ident in self.idents: image = self.find_image_with_identifier(ident) @@ -393,15 +441,17 @@ self.target = image.create_target(self.debugger) if self.target: return self.target # success - print('crashlog.create_target()...3') + print("crashlog.create_target()...3") for image in self.images: self.target = image.create_target(self.debugger) if self.target: return self.target # success - print('crashlog.create_target()...4') - print('error: Unable to locate any executables from the crash log.') - print(' Try loading the executable into lldb before running crashlog') - print(' and/or make sure the .dSYM bundles can be found by Spotlight.') + print("crashlog.create_target()...4") + print("error: Unable to locate any executables from the crash log.") + print(" Try loading the executable into lldb before running crashlog") + print( + " and/or make sure the .dSYM bundles can be found by Spotlight." + ) return self.target def get_target(self): @@ -415,9 +465,11 @@ class CrashLogParseException(Exception): pass + class InteractiveCrashLogException(Exception): pass + class CrashLogParser: @staticmethod def create(debugger, path, verbose): @@ -450,10 +502,10 @@ except: # The first line can contain meta data. Try stripping it and # try again. - head, _, tail = buffer.partition('\n') + head, _, tail = buffer.partition("\n") return json.loads(tail) - with open(path, 'r', encoding='utf-8') as f: + with open(path, "r", encoding="utf-8") as f: buffer = f.read() try: return parse_json(buffer) @@ -466,94 +518,92 @@ def parse(self): try: self.parse_process_info(self.data) - self.parse_images(self.data['usedImages']) + self.parse_images(self.data["usedImages"]) self.parse_main_image(self.data) - self.parse_threads(self.data['threads']) - if 'asi' in self.data: - self.crashlog.asi = self.data['asi'] - if 'asiBacktraces' in self.data: - self.parse_app_specific_backtraces(self.data['asiBacktraces']) - if 'lastExceptionBacktrace' in self.data: - self.crashlog.asb = self.data['lastExceptionBacktrace'] + self.parse_threads(self.data["threads"]) + if "asi" in self.data: + self.crashlog.asi = self.data["asi"] + if "asiBacktraces" in self.data: + self.parse_app_specific_backtraces(self.data["asiBacktraces"]) + if "lastExceptionBacktrace" in self.data: + self.crashlog.asb = self.data["lastExceptionBacktrace"] self.parse_errors(self.data) thread = self.crashlog.threads[self.crashlog.crashed_thread_idx] - reason = self.parse_crash_reason(self.data['exception']) + reason = self.parse_crash_reason(self.data["exception"]) if thread.reason: - thread.reason = '{} {}'.format(thread.reason, reason) + thread.reason = "{} {}".format(thread.reason, reason) else: thread.reason = reason except (KeyError, ValueError, TypeError) as e: raise CrashLogParseException( - 'Failed to parse JSON crashlog: {}: {}'.format( - type(e).__name__, e)) + "Failed to parse JSON crashlog: {}: {}".format(type(e).__name__, e) + ) return self.crashlog def get_used_image(self, idx): - return self.data['usedImages'][idx] + return self.data["usedImages"][idx] def parse_process_info(self, json_data): - self.crashlog.process_id = json_data['pid'] - self.crashlog.process_identifier = json_data['procName'] + self.crashlog.process_id = json_data["pid"] + self.crashlog.process_identifier = json_data["procName"] def parse_crash_reason(self, json_exception): self.crashlog.exception = json_exception - exception_type = json_exception['type'] + exception_type = json_exception["type"] exception_signal = " " - if 'signal' in json_exception: - exception_signal += "({})".format(json_exception['signal']) + if "signal" in json_exception: + exception_signal += "({})".format(json_exception["signal"]) - if 'codes' in json_exception: - exception_extra = " ({})".format(json_exception['codes']) - elif 'subtype' in json_exception: - exception_extra = " ({})".format(json_exception['subtype']) + if "codes" in json_exception: + exception_extra = " ({})".format(json_exception["codes"]) + elif "subtype" in json_exception: + exception_extra = " ({})".format(json_exception["subtype"]) else: exception_extra = "" - return "{}{}{}".format(exception_type, exception_signal, - exception_extra) + return "{}{}{}".format(exception_type, exception_signal, exception_extra) def parse_images(self, json_images): for json_image in json_images: - img_uuid = uuid.UUID(json_image['uuid']) - low = int(json_image['base']) - high = low + int( - json_image['size']) if 'size' in json_image else low - name = json_image['name'] if 'name' in json_image else '' - path = json_image['path'] if 'path' in json_image else '' - version = '' - darwin_image = self.crashlog.DarwinImage(low, high, name, version, - img_uuid, path, - self.verbose) + img_uuid = uuid.UUID(json_image["uuid"]) + low = int(json_image["base"]) + high = low + int(json_image["size"]) if "size" in json_image else low + name = json_image["name"] if "name" in json_image else "" + path = json_image["path"] if "path" in json_image else "" + version = "" + darwin_image = self.crashlog.DarwinImage( + low, high, name, version, img_uuid, path, self.verbose + ) self.images.append(darwin_image) self.crashlog.images.append(darwin_image) def parse_main_image(self, json_data): - if 'procName' in json_data: - proc_name = json_data['procName'] + if "procName" in json_data: + proc_name = json_data["procName"] self.crashlog.set_main_image(proc_name) def parse_frames(self, thread, json_frames): idx = 0 for json_frame in json_frames: - image_id = int(json_frame['imageIndex']) + image_id = int(json_frame["imageIndex"]) json_image = self.get_used_image(image_id) - ident = json_image['name'] if 'name' in json_image else '' + ident = json_image["name"] if "name" in json_image else "" thread.add_ident(ident) if ident not in self.crashlog.idents: self.crashlog.idents.append(ident) - frame_offset = int(json_frame['imageOffset']) - image_addr = self.get_used_image(image_id)['base'] + frame_offset = int(json_frame["imageOffset"]) + image_addr = self.get_used_image(image_id)["base"] pc = image_addr + frame_offset - if 'symbol' in json_frame: - symbol = json_frame['symbol'] - location = int(json_frame['symbolLocation']) + if "symbol" in json_frame: + symbol = json_frame["symbol"] + location = int(json_frame["symbolLocation"]) image = self.images[image_id] image.symbols[symbol] = { "name": symbol, "type": "code", - "address": frame_offset - location + "address": frame_offset - location, } thread.frames.append(self.crashlog.Frame(idx, pc, frame_offset)) @@ -565,14 +615,14 @@ # was at, so insert that address as the caller stack frame. if idx == 0 and pc == 0 and "lr" in thread.registers: pc = thread.registers["lr"] - for image in self.data['usedImages']: - text_lo = image['base'] - text_hi = text_lo + image['size'] + for image in self.data["usedImages"]: + text_lo = image["base"] + text_hi = text_lo + image["size"] if text_lo <= pc < text_hi: - idx += 1 - frame_offset = pc - text_lo - thread.frames.append(self.crashlog.Frame(idx, pc, frame_offset)) - break + idx += 1 + frame_offset = pc - text_lo + thread.frames.append(self.crashlog.Frame(idx, pc, frame_offset)) + break idx += 1 @@ -580,46 +630,71 @@ idx = 0 for json_thread in json_threads: thread = self.crashlog.Thread(idx, False) - if 'name' in json_thread: - thread.name = json_thread['name'] - thread.reason = json_thread['name'] - if 'id' in json_thread: - thread.id = int(json_thread['id']) - if json_thread.get('triggered', False): + if "name" in json_thread: + thread.name = json_thread["name"] + thread.reason = json_thread["name"] + if "id" in json_thread: + thread.id = int(json_thread["id"]) + if json_thread.get("triggered", False): self.crashlog.crashed_thread_idx = idx thread.crashed = True - if 'threadState' in json_thread: + if "threadState" in json_thread: thread.registers = self.parse_thread_registers( - json_thread['threadState']) - if 'queue' in json_thread: - thread.queue = json_thread.get('queue') - self.parse_frames(thread, json_thread.get('frames', [])) + json_thread["threadState"] + ) + if "queue" in json_thread: + thread.queue = json_thread.get("queue") + self.parse_frames(thread, json_thread.get("frames", [])) self.crashlog.threads.append(thread) idx += 1 def parse_asi_backtrace(self, thread, bt): - for line in bt.split('\n'): + for line in bt.split("\n"): frame_match = TextCrashLogParser.frame_regex.search(line) if not frame_match: print("error: can't parse application specific backtrace.") return False - frame_id = frame_img_name = frame_addr = frame_symbol = frame_offset = frame_file = frame_line = frame_column = None + frame_id = ( + frame_img_name + ) = ( + frame_addr + ) = ( + frame_symbol + ) = frame_offset = frame_file = frame_line = frame_column = None if len(frame_match.groups()) == 3: # Get the image UUID from the frame image name. (frame_id, frame_img_name, frame_addr) = frame_match.groups() elif len(frame_match.groups()) == 5: - (frame_id, frame_img_name, frame_addr, - frame_symbol, frame_offset) = frame_match.groups() + ( + frame_id, + frame_img_name, + frame_addr, + frame_symbol, + frame_offset, + ) = frame_match.groups() elif len(frame_match.groups()) == 7: - (frame_id, frame_img_name, frame_addr, - frame_symbol, frame_offset, - frame_file, frame_line) = frame_match.groups() + ( + frame_id, + frame_img_name, + frame_addr, + frame_symbol, + frame_offset, + frame_file, + frame_line, + ) = frame_match.groups() elif len(frame_match.groups()) == 8: - (frame_id, frame_img_name, frame_addr, - frame_symbol, frame_offset, - frame_file, frame_line, frame_column) = frame_match.groups() + ( + frame_id, + frame_img_name, + frame_addr, + frame_symbol, + frame_offset, + frame_file, + frame_line, + frame_column, + ) = frame_match.groups() thread.add_ident(frame_img_name) if frame_img_name not in self.crashlog.idents: @@ -660,19 +735,19 @@ registers.update(self.parse_thread_registers(state)) continue if key == "x": - gpr_dict = { str(idx) : reg for idx,reg in enumerate(state) } + gpr_dict = {str(idx): reg for idx, reg in enumerate(state)} registers.update(self.parse_thread_registers(gpr_dict, key)) continue try: - value = int(state['value']) - registers["{}{}".format(prefix or '',key)] = value + value = int(state["value"]) + registers["{}{}".format(prefix or "", key)] = value except (KeyError, ValueError, TypeError): pass return registers def parse_errors(self, json_data): - if 'reportNotes' in json_data: - self.crashlog.errors = json_data['reportNotes'] + if "reportNotes" in json_data: + self.crashlog.errors = json_data["reportNotes"] class CrashLogParseMode: @@ -683,25 +758,26 @@ SYSTEM = 4 INSTRS = 5 + class TextCrashLogParser(CrashLogParser): - parent_process_regex = re.compile(r'^Parent Process:\s*(.*)\[(\d+)\]') - thread_state_regex = re.compile(r'^Thread \d+ crashed with') - thread_instrs_regex = re.compile(r'^Thread \d+ instruction stream') - thread_regex = re.compile(r'^Thread (\d+).*:') - app_backtrace_regex = re.compile(r'^Application Specific Backtrace (\d+).*:') + parent_process_regex = re.compile(r"^Parent Process:\s*(.*)\[(\d+)\]") + thread_state_regex = re.compile(r"^Thread \d+ crashed with") + thread_instrs_regex = re.compile(r"^Thread \d+ instruction stream") + thread_regex = re.compile(r"^Thread (\d+).*:") + app_backtrace_regex = re.compile(r"^Application Specific Backtrace (\d+).*:") class VersionRegex: - version = r'\(.+\)|(?:arm|x86_)[0-9a-z]+' + version = r"\(.+\)|(?:arm|x86_)[0-9a-z]+" class FrameRegex(VersionRegex): @classmethod def get(cls): - index = r'^(\d+)\s+' - img_name = r'(.+?)\s+' - version = r'(?:' + super().version + r'\s+)?' - address = r'(0x[0-9a-fA-F]{4,})' # 4 digits or more + index = r"^(\d+)\s+" + img_name = r"(.+?)\s+" + version = r"(?:" + super().version + r"\s+)?" + address = r"(0x[0-9a-fA-F]{4,})" # 4 digits or more - symbol = """ + symbol = """ (?: [ ]+ (?P.+) @@ -719,24 +795,28 @@ )? """ - return re.compile(index + img_name + version + address + symbol, - flags=re.VERBOSE) + return re.compile( + index + img_name + version + address + symbol, flags=re.VERBOSE + ) frame_regex = FrameRegex.get() - null_frame_regex = re.compile(r'^\d+\s+\?\?\?\s+0{4,} +') - image_regex_uuid = re.compile(r'(0x[0-9a-fA-F]+)' # img_lo - r'\s+-\s+' # - - r'(0x[0-9a-fA-F]+)\s+' # img_hi - r'[+]?(.+?)\s+' # img_name - r'(?:(' + - VersionRegex.version + # img_version - r')\s+)?' - r'(?:<([-0-9a-fA-F]+)>\s+)?' # img_uuid - r'(\?+|/.*)' # img_path - ) - exception_type_regex = re.compile(r'^Exception Type:\s+(EXC_[A-Z_]+)(?:\s+\((.*)\))?') - exception_codes_regex = re.compile(r'^Exception Codes:\s+(0x[0-9a-fA-F]+),\s*(0x[0-9a-fA-F]+)') - exception_extra_regex = re.compile(r'^Exception\s+.*:\s+(.*)') + null_frame_regex = re.compile(r"^\d+\s+\?\?\?\s+0{4,} +") + image_regex_uuid = re.compile( + r"(0x[0-9a-fA-F]+)" # img_lo + r"\s+-\s+" # - + r"(0x[0-9a-fA-F]+)\s+" # img_hi + r"[+]?(.+?)\s+" # img_name + r"(?:(" + VersionRegex.version + r")\s+)?" # img_version + r"(?:<([-0-9a-fA-F]+)>\s+)?" # img_uuid + r"(\?+|/.*)" # img_path + ) + exception_type_regex = re.compile( + r"^Exception Type:\s+(EXC_[A-Z_]+)(?:\s+\((.*)\))?" + ) + exception_codes_regex = re.compile( + r"^Exception Codes:\s+(0x[0-9a-fA-F]+),\s*(0x[0-9a-fA-F]+)" + ) + exception_extra_regex = re.compile(r"^Exception\s+.*:\s+(.*)") def __init__(self, debugger, path, verbose): super().__init__(debugger, path, verbose) @@ -744,17 +824,17 @@ self.app_specific_backtrace = False self.parse_mode = CrashLogParseMode.NORMAL self.parsers = { - CrashLogParseMode.NORMAL : self.parse_normal, - CrashLogParseMode.THREAD : self.parse_thread, - CrashLogParseMode.IMAGES : self.parse_images, - CrashLogParseMode.THREGS : self.parse_thread_registers, - CrashLogParseMode.SYSTEM : self.parse_system, - CrashLogParseMode.INSTRS : self.parse_instructions, + CrashLogParseMode.NORMAL: self.parse_normal, + CrashLogParseMode.THREAD: self.parse_thread, + CrashLogParseMode.IMAGES: self.parse_images, + CrashLogParseMode.THREGS: self.parse_thread_registers, + CrashLogParseMode.SYSTEM: self.parse_system, + CrashLogParseMode.INSTRS: self.parse_instructions, } self.symbols = {} def parse(self): - with open(self.path,'r', encoding='utf-8') as f: + with open(self.path, "r", encoding="utf-8") as f: lines = f.read().splitlines() for line in lines: @@ -763,11 +843,13 @@ if self.thread: if self.parse_mode == CrashLogParseMode.THREAD: if self.thread.index == self.crashlog.crashed_thread_idx: - self.thread.reason = '' - if hasattr(self.crashlog, 'thread_exception'): + self.thread.reason = "" + if hasattr(self.crashlog, "thread_exception"): self.thread.reason += self.crashlog.thread_exception - if hasattr(self.crashlog, 'thread_exception_data'): - self.thread.reason += " (%s)" % self.crashlog.thread_exception_data + if hasattr(self.crashlog, "thread_exception_data"): + self.thread.reason += ( + " (%s)" % self.crashlog.thread_exception_data + ) if self.app_specific_backtrace: self.crashlog.backtraces.append(self.thread) else: @@ -776,7 +858,9 @@ else: # only append an extra empty line if the previous line # in the info_lines wasn't empty - if len(self.crashlog.info_lines) > 0 and len(self.crashlog.info_lines[-1]): + if len(self.crashlog.info_lines) > 0 and len( + self.crashlog.info_lines[-1] + ): self.crashlog.info_lines.append(line) self.parse_mode = CrashLogParseMode.NORMAL else: @@ -785,83 +869,88 @@ return self.crashlog def parse_exception(self, line): - if not line.startswith('Exception'): + if not line.startswith("Exception"): return - if line.startswith('Exception Type:'): + if line.startswith("Exception Type:"): self.crashlog.thread_exception = line[15:].strip() exception_type_match = self.exception_type_regex.search(line) if exception_type_match: exc_type, exc_signal = exception_type_match.groups() - self.crashlog.exception['type'] = exc_type + self.crashlog.exception["type"] = exc_type if exc_signal: - self.crashlog.exception['signal'] = exc_signal - elif line.startswith('Exception Subtype:'): + self.crashlog.exception["signal"] = exc_signal + elif line.startswith("Exception Subtype:"): self.crashlog.thread_exception_subtype = line[18:].strip() - if 'type' in self.crashlog.exception: - self.crashlog.exception['subtype'] = self.crashlog.thread_exception_subtype - elif line.startswith('Exception Codes:'): + if "type" in self.crashlog.exception: + self.crashlog.exception[ + "subtype" + ] = self.crashlog.thread_exception_subtype + elif line.startswith("Exception Codes:"): self.crashlog.thread_exception_data = line[16:].strip() - if 'type' not in self.crashlog.exception: + if "type" not in self.crashlog.exception: return exception_codes_match = self.exception_codes_regex.search(line) if exception_codes_match: - self.crashlog.exception['codes'] = self.crashlog.thread_exception_data + self.crashlog.exception["codes"] = self.crashlog.thread_exception_data code, subcode = exception_codes_match.groups() - self.crashlog.exception['rawCodes'] = [int(code, base=16), - int(subcode, base=16)] + self.crashlog.exception["rawCodes"] = [ + int(code, base=16), + int(subcode, base=16), + ] else: - if 'type' not in self.crashlog.exception: + if "type" not in self.crashlog.exception: return exception_extra_match = self.exception_extra_regex.search(line) if exception_extra_match: - self.crashlog.exception['message'] = exception_extra_match.group(1) + self.crashlog.exception["message"] = exception_extra_match.group(1) def parse_normal(self, line): - if line.startswith('Process:'): - (self.crashlog.process_name, pid_with_brackets) = line[ - 8:].strip().split(' [') - self.crashlog.process_id = pid_with_brackets.strip('[]') - elif line.startswith('Identifier:'): + if line.startswith("Process:"): + (self.crashlog.process_name, pid_with_brackets) = ( + line[8:].strip().split(" [") + ) + self.crashlog.process_id = pid_with_brackets.strip("[]") + elif line.startswith("Identifier:"): self.crashlog.process_identifier = line[11:].strip() - elif line.startswith('Version:'): + elif line.startswith("Version:"): version_string = line[8:].strip() matched_pair = re.search("(.+)\((.+)\)", version_string) if matched_pair: self.crashlog.process_version = matched_pair.group(1) - self.crashlog.process_compatability_version = matched_pair.group( - 2) + self.crashlog.process_compatability_version = matched_pair.group(2) else: self.crashlog.process = version_string self.crashlog.process_compatability_version = version_string elif self.parent_process_regex.search(line): - parent_process_match = self.parent_process_regex.search( - line) + parent_process_match = self.parent_process_regex.search(line) self.crashlog.parent_process_name = parent_process_match.group(1) self.crashlog.parent_process_id = parent_process_match.group(2) - elif line.startswith('Exception'): + elif line.startswith("Exception"): self.parse_exception(line) return - elif line.startswith('Crashed Thread:'): + elif line.startswith("Crashed Thread:"): self.crashlog.crashed_thread_idx = int(line[15:].strip().split()[0]) return - elif line.startswith('Triggered by Thread:'): # iOS + elif line.startswith("Triggered by Thread:"): # iOS self.crashlog.crashed_thread_idx = int(line[20:].strip().split()[0]) return - elif line.startswith('Report Version:'): + elif line.startswith("Report Version:"): self.crashlog.version = int(line[15:].strip()) return - elif line.startswith('System Profile:'): + elif line.startswith("System Profile:"): self.parse_mode = CrashLogParseMode.SYSTEM return - elif (line.startswith('Interval Since Last Report:') or - line.startswith('Crashes Since Last Report:') or - line.startswith('Per-App Interval Since Last Report:') or - line.startswith('Per-App Crashes Since Last Report:') or - line.startswith('Sleep/Wake UUID:') or - line.startswith('Anonymous UUID:')): + elif ( + line.startswith("Interval Since Last Report:") + or line.startswith("Crashes Since Last Report:") + or line.startswith("Per-App Interval Since Last Report:") + or line.startswith("Per-App Crashes Since Last Report:") + or line.startswith("Sleep/Wake UUID:") + or line.startswith("Anonymous UUID:") + ): # ignore these return - elif line.startswith('Thread'): + elif line.startswith("Thread"): thread_state_match = self.thread_state_regex.search(line) if thread_state_match: self.app_specific_backtrace = False @@ -870,7 +959,7 @@ self.parse_mode = CrashLogParseMode.THREGS self.thread = self.crashlog.threads[thread_idx] return - thread_insts_match = self.thread_instrs_regex.search(line) + thread_insts_match = self.thread_instrs_regex.search(line) if thread_insts_match: self.parse_mode = CrashLogParseMode.INSTRS return @@ -882,17 +971,17 @@ self.thread = self.crashlog.Thread(thread_idx, False) return return - elif line.startswith('Binary Images:'): + elif line.startswith("Binary Images:"): self.parse_mode = CrashLogParseMode.IMAGES return - elif line.startswith('Application Specific Backtrace'): + elif line.startswith("Application Specific Backtrace"): app_backtrace_match = self.app_backtrace_regex.search(line) if app_backtrace_match: self.parse_mode = CrashLogParseMode.THREAD self.app_specific_backtrace = True idx = int(app_backtrace_match.group(1)) self.thread = self.crashlog.Thread(idx, True) - elif line.startswith('Last Exception Backtrace:'): # iOS + elif line.startswith("Last Exception Backtrace:"): # iOS self.parse_mode = CrashLogParseMode.THREAD self.app_specific_backtrace = True idx = 1 @@ -900,7 +989,7 @@ self.crashlog.info_lines.append(line.strip()) def parse_thread(self, line): - if line.startswith('Thread'): + if line.startswith("Thread"): return if self.null_frame_regex.search(line): print('warning: thread parser ignored null-frame: "%s"' % line) @@ -910,22 +999,44 @@ print('error: frame regex failed for line: "%s"' % line) return - frame_id = frame_img_name = frame_addr = frame_symbol = frame_offset = frame_file = frame_line = frame_column = None + frame_id = ( + frame_img_name + ) = ( + frame_addr + ) = frame_symbol = frame_offset = frame_file = frame_line = frame_column = None if len(frame_match.groups()) == 3: # Get the image UUID from the frame image name. (frame_id, frame_img_name, frame_addr) = frame_match.groups() elif len(frame_match.groups()) == 5: - (frame_id, frame_img_name, frame_addr, - frame_symbol, frame_offset) = frame_match.groups() + ( + frame_id, + frame_img_name, + frame_addr, + frame_symbol, + frame_offset, + ) = frame_match.groups() elif len(frame_match.groups()) == 7: - (frame_id, frame_img_name, frame_addr, - frame_symbol, frame_offset, - frame_file, frame_line) = frame_match.groups() + ( + frame_id, + frame_img_name, + frame_addr, + frame_symbol, + frame_offset, + frame_file, + frame_line, + ) = frame_match.groups() elif len(frame_match.groups()) == 8: - (frame_id, frame_img_name, frame_addr, - frame_symbol, frame_offset, - frame_file, frame_line, frame_column) = frame_match.groups() + ( + frame_id, + frame_img_name, + frame_addr, + frame_symbol, + frame_offset, + frame_file, + frame_line, + frame_column, + ) = frame_match.groups() self.thread.add_ident(frame_img_name) if frame_img_name not in self.crashlog.idents: @@ -956,15 +1067,24 @@ def parse_images(self, line): image_match = self.image_regex_uuid.search(line) if image_match: - (img_lo, img_hi, img_name, img_version, - img_uuid, img_path) = image_match.groups() - - image = self.crashlog.DarwinImage(int(img_lo, 0), int(img_hi, 0), - img_name.strip(), - img_version.strip() - if img_version else "", - uuid.UUID(img_uuid), img_path, - self.verbose) + ( + img_lo, + img_hi, + img_name, + img_version, + img_uuid, + img_path, + ) = image_match.groups() + + image = self.crashlog.DarwinImage( + int(img_lo, 0), + int(img_hi, 0), + img_name.strip(), + img_version.strip() if img_version else "", + uuid.UUID(img_uuid), + img_path, + self.verbose, + ) unqualified_img_name = os.path.basename(img_path) if unqualified_img_name in self.symbols: for symbol in self.symbols[unqualified_img_name]: @@ -980,10 +1100,9 @@ else: print("error: image regex failed for: %s" % line) - def parse_thread_registers(self, line): # "r12: 0x00007fff6b5939c8 r13: 0x0000000007000006 r14: 0x0000000000002a03 r15: 0x0000000000000c00" - reg_values = re.findall('([a-z0-9]+): (0x[0-9a-f]+)', line, re.I) + reg_values = re.findall("([a-z0-9]+): (0x[0-9a-f]+)", line, re.I) for reg, value in reg_values: self.thread.registers[reg] = int(value, 16) @@ -1001,18 +1120,18 @@ def save_crashlog(debugger, command, exe_ctx, result, dict): usage = "usage: %prog [options] " - description = '''Export the state of current target into a crashlog file''' + description = """Export the state of current target into a crashlog file""" parser = optparse.OptionParser( - description=description, - prog='save_crashlog', - usage=usage) + description=description, prog="save_crashlog", usage=usage + ) parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', - help='display verbose debug info', - default=False) + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="display verbose debug info", + default=False, + ) try: (options, args) = parser.parse_args(shlex.split(command)) except: @@ -1020,13 +1139,12 @@ return if len(args) != 1: result.PutCString( - "error: invalid arguments, a single output file is the only valid argument") + "error: invalid arguments, a single output file is the only valid argument" + ) return - out_file = open(args[0], 'w', encoding='utf-8') + out_file = open(args[0], "w", encoding="utf-8") if not out_file: - result.PutCString( - "error: failed to open file '%s' for writing...", - args[0]) + result.PutCString("error: failed to open file '%s' for writing...", args[0]) return target = exe_ctx.target if target: @@ -1035,21 +1153,27 @@ if process: pid = process.id if pid != lldb.LLDB_INVALID_PROCESS_ID: - out_file.write( - 'Process: %s [%u]\n' % - (identifier, pid)) - out_file.write('Path: %s\n' % (target.executable.fullpath)) - out_file.write('Identifier: %s\n' % (identifier)) - out_file.write('\nDate/Time: %s\n' % - (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) + out_file.write("Process: %s [%u]\n" % (identifier, pid)) + out_file.write("Path: %s\n" % (target.executable.fullpath)) + out_file.write("Identifier: %s\n" % (identifier)) out_file.write( - 'OS Version: Mac OS X %s (%s)\n' % - (platform.mac_ver()[0], subprocess.check_output('sysctl -n kern.osversion', shell=True).decode("utf-8"))) - out_file.write('Report Version: 9\n') + "\nDate/Time: %s\n" + % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + ) + out_file.write( + "OS Version: Mac OS X %s (%s)\n" + % ( + platform.mac_ver()[0], + subprocess.check_output("sysctl -n kern.osversion", shell=True).decode( + "utf-8" + ), + ) + ) + out_file.write("Report Version: 9\n") for thread_idx in range(process.num_threads): thread = process.thread[thread_idx] - out_file.write('\nThread %u:\n' % (thread_idx)) - for (frame_idx, frame) in enumerate(thread.frames): + out_file.write("\nThread %u:\n" % (thread_idx)) + for frame_idx, frame in enumerate(thread.frames): frame_pc = frame.pc frame_offset = 0 if frame.function: @@ -1057,51 +1181,60 @@ block_range = block.range[frame.addr] if block_range: block_start_addr = block_range[0] - frame_offset = frame_pc - block_start_addr.GetLoadAddress(target) + frame_offset = frame_pc - block_start_addr.GetLoadAddress( + target + ) else: - frame_offset = frame_pc - frame.function.addr.GetLoadAddress(target) + frame_offset = frame_pc - frame.function.addr.GetLoadAddress( + target + ) elif frame.symbol: frame_offset = frame_pc - frame.symbol.addr.GetLoadAddress(target) out_file.write( - '%-3u %-32s 0x%16.16x %s' % - (frame_idx, frame.module.file.basename, frame_pc, frame.name)) + "%-3u %-32s 0x%16.16x %s" + % (frame_idx, frame.module.file.basename, frame_pc, frame.name) + ) if frame_offset > 0: - out_file.write(' + %u' % (frame_offset)) + out_file.write(" + %u" % (frame_offset)) line_entry = frame.line_entry if line_entry: if options.verbose: # This will output the fullpath + line + column - out_file.write(' %s' % (line_entry)) + out_file.write(" %s" % (line_entry)) else: out_file.write( - ' %s:%u' % - (line_entry.file.basename, line_entry.line)) + " %s:%u" % (line_entry.file.basename, line_entry.line) + ) column = line_entry.column if column: - out_file.write(':%u' % (column)) - out_file.write('\n') + out_file.write(":%u" % (column)) + out_file.write("\n") - out_file.write('\nBinary Images:\n') + out_file.write("\nBinary Images:\n") for module in target.modules: - text_segment = module.section['__TEXT'] + text_segment = module.section["__TEXT"] if text_segment: text_segment_load_addr = text_segment.GetLoadAddress(target) if text_segment_load_addr != lldb.LLDB_INVALID_ADDRESS: - text_segment_end_load_addr = text_segment_load_addr + text_segment.size + text_segment_end_load_addr = ( + text_segment_load_addr + text_segment.size + ) identifier = module.file.basename - module_version = '???' + module_version = "???" module_version_array = module.GetVersion() if module_version_array: - module_version = '.'.join( - map(str, module_version_array)) + module_version = ".".join(map(str, module_version_array)) out_file.write( - ' 0x%16.16x - 0x%16.16x %s (%s - ???) <%s> %s\n' % - (text_segment_load_addr, - text_segment_end_load_addr, - identifier, - module_version, - module.GetUUIDString(), - module.file.fullpath)) + " 0x%16.16x - 0x%16.16x %s (%s - ???) <%s> %s\n" + % ( + text_segment_load_addr, + text_segment_end_load_addr, + identifier, + module_version, + module.GetUUIDString(), + module.file.fullpath, + ) + ) out_file.close() else: result.PutCString("error: invalid target") @@ -1126,7 +1259,7 @@ if options.debug: crash_log.dump() if not crash_log.images: - print('error: no images in crash log') + print("error: no images in crash log") return if options.dump_image_list: @@ -1141,7 +1274,6 @@ if not target: return - if options.load_all_images: for image in crash_log.images: image.resolve = True @@ -1187,10 +1319,13 @@ for error in crash_log.errors: print(error) + def load_crashlog_in_scripted_process(debugger, crash_log_file, options, result): crashlog_path = os.path.expanduser(crash_log_file) if not os.path.exists(crashlog_path): - raise InteractiveCrashLogException("crashlog file %s does not exist" % crashlog_path) + raise InteractiveCrashLogException( + "crashlog file %s does not exist" % crashlog_path + ) crashlog = CrashLogParser.create(debugger, crashlog_path, False).parse() @@ -1199,13 +1334,15 @@ if options.target_path: target = debugger.CreateTarget(options.target_path) if not target: - raise InteractiveCrashLogException("couldn't create target provided by the user (%s)" % options.target_path) + raise InteractiveCrashLogException( + "couldn't create target provided by the user (%s)" % options.target_path + ) # 2. If the user didn't provide a target, try to create a target using the symbolicator if not target or not target.IsValid(): target = crashlog.create_target() # 3. If that didn't work, and a target is already loaded, use it - if (target is None or not target.IsValid()) and debugger.GetNumTargets() > 0: + if (target is None or not target.IsValid()) and debugger.GetNumTargets() > 0: target = debugger.GetTargetAtIndex(0) # 4. Fail if target is None or not target.IsValid(): @@ -1215,16 +1352,23 @@ if not ci: raise InteractiveCrashLogException("couldn't get command interpreter") - ci.HandleCommand('script from lldb.macosx import crashlog_scripted_process', result) + ci.HandleCommand("script from lldb.macosx import crashlog_scripted_process", result) if not result.Succeeded(): - raise InteractiveCrashLogException("couldn't import crashlog scripted process module") + raise InteractiveCrashLogException( + "couldn't import crashlog scripted process module" + ) structured_data = lldb.SBStructuredData() - structured_data.SetFromJSON(json.dumps({ "file_path" : crashlog_path, - "load_all_images": options.load_all_images })) + structured_data.SetFromJSON( + json.dumps( + {"file_path": crashlog_path, "load_all_images": options.load_all_images} + ) + ) launch_info = lldb.SBLaunchInfo(None) launch_info.SetProcessPluginName("ScriptedProcess") - launch_info.SetScriptedProcessClassName("crashlog_scripted_process.CrashLogScriptedProcess") + launch_info.SetScriptedProcessClassName( + "crashlog_scripted_process.CrashLogScriptedProcess" + ) launch_info.SetScriptedProcessDictionary(structured_data) launch_info.SetLaunchFlags(lldb.eLaunchFlagStopAtEntry) @@ -1238,6 +1382,7 @@ process.Continue() if not options.skip_status: + @contextlib.contextmanager def synchronous(debugger): async_state = debugger.GetAsync() @@ -1260,151 +1405,171 @@ if error.Success(): debugger.RunCommandInterpreter(True, False, run_options, 0, False, True) + def CreateSymbolicateCrashLogOptions( - command_name, - description, - add_interactive_options): + command_name, description, add_interactive_options +): usage = "usage: %prog [options] [FILE ...]" option_parser = optparse.OptionParser( - description=description, prog='crashlog', usage=usage) + description=description, prog="crashlog", usage=usage + ) option_parser.add_option( - '--version', - '-V', - dest='version', - action='store_true', - help='Show crashlog version', - default=False) + "--version", + "-V", + dest="version", + action="store_true", + help="Show crashlog version", + default=False, + ) option_parser.add_option( - '--verbose', - '-v', - action='store_true', - dest='verbose', - help='display verbose debug info', - default=False) + "--verbose", + "-v", + action="store_true", + dest="verbose", + help="display verbose debug info", + default=False, + ) option_parser.add_option( - '--debug', - '-g', - action='store_true', - dest='debug', - help='display verbose debug logging', - default=False) + "--debug", + "-g", + action="store_true", + dest="debug", + help="display verbose debug logging", + default=False, + ) option_parser.add_option( - '--load-all', - '-a', - action='store_true', - dest='load_all_images', - help='load all executable images, not just the images found in the ' - 'crashed stack frames, loads stackframes for all the threads in ' - 'interactive mode.', - default=False) + "--load-all", + "-a", + action="store_true", + dest="load_all_images", + help="load all executable images, not just the images found in the " + "crashed stack frames, loads stackframes for all the threads in " + "interactive mode.", + default=False, + ) option_parser.add_option( - '--images', - action='store_true', - dest='dump_image_list', - help='show image list', - default=False) + "--images", + action="store_true", + dest="dump_image_list", + help="show image list", + default=False, + ) option_parser.add_option( - '--debug-delay', - type='int', - dest='debug_delay', - metavar='NSEC', - help='pause for NSEC seconds for debugger', - default=0) + "--debug-delay", + type="int", + dest="debug_delay", + metavar="NSEC", + help="pause for NSEC seconds for debugger", + default=0, + ) option_parser.add_option( - '--crashed-only', - '-c', - action='store_true', - dest='crashed_only', - help='only symbolicate the crashed thread', - default=False) + "--crashed-only", + "-c", + action="store_true", + dest="crashed_only", + help="only symbolicate the crashed thread", + default=False, + ) option_parser.add_option( - '--disasm-depth', - '-d', - type='int', - dest='disassemble_depth', - help='set the depth in stack frames that should be disassembled (default is 1)', - default=1) + "--disasm-depth", + "-d", + type="int", + dest="disassemble_depth", + help="set the depth in stack frames that should be disassembled (default is 1)", + default=1, + ) option_parser.add_option( - '--disasm-all', - '-D', - action='store_true', - dest='disassemble_all_threads', - help='enabled disassembly of frames on all threads (not just the crashed thread)', - default=False) + "--disasm-all", + "-D", + action="store_true", + dest="disassemble_all_threads", + help="enabled disassembly of frames on all threads (not just the crashed thread)", + default=False, + ) option_parser.add_option( - '--disasm-before', - '-B', - type='int', - dest='disassemble_before', - help='the number of instructions to disassemble before the frame PC', - default=4) + "--disasm-before", + "-B", + type="int", + dest="disassemble_before", + help="the number of instructions to disassemble before the frame PC", + default=4, + ) option_parser.add_option( - '--disasm-after', - '-A', - type='int', - dest='disassemble_after', - help='the number of instructions to disassemble after the frame PC', - default=4) + "--disasm-after", + "-A", + type="int", + dest="disassemble_after", + help="the number of instructions to disassemble after the frame PC", + default=4, + ) option_parser.add_option( - '--source-context', - '-C', - type='int', - metavar='NLINES', - dest='source_context', - help='show NLINES source lines of source context (default = 4)', - default=4) + "--source-context", + "-C", + type="int", + metavar="NLINES", + dest="source_context", + help="show NLINES source lines of source context (default = 4)", + default=4, + ) option_parser.add_option( - '--source-frames', - type='int', - metavar='NFRAMES', - dest='source_frames', - help='show source for NFRAMES (default = 4)', - default=4) + "--source-frames", + type="int", + metavar="NFRAMES", + dest="source_frames", + help="show source for NFRAMES (default = 4)", + default=4, + ) option_parser.add_option( - '--source-all', - action='store_true', - dest='source_all', - help='show source for all threads, not just the crashed thread', - default=False) + "--source-all", + action="store_true", + dest="source_all", + help="show source for all threads, not just the crashed thread", + default=False, + ) if add_interactive_options: option_parser.add_option( - '-i', - '--interactive', - action='store_true', - help='parse a crash log and load it in a ScriptedProcess', - default=False) + "-i", + "--interactive", + action="store_true", + help="parse a crash log and load it in a ScriptedProcess", + default=False, + ) option_parser.add_option( - '-b', - '--batch', - action='store_true', - help='dump symbolicated stackframes without creating a debug session', - default=True) + "-b", + "--batch", + action="store_true", + help="dump symbolicated stackframes without creating a debug session", + default=True, + ) option_parser.add_option( - '--target', - '-t', - dest='target_path', - help='the target binary path that should be used for interactive crashlog (optional)', - default=None) + "--target", + "-t", + dest="target_path", + help="the target binary path that should be used for interactive crashlog (optional)", + default=None, + ) option_parser.add_option( - '--skip-status', - '-s', - dest='skip_status', - action='store_true', - help='prevent the interactive crashlog to dump the process status and thread backtrace at launch', - default=False) + "--skip-status", + "-s", + dest="skip_status", + action="store_true", + help="prevent the interactive crashlog to dump the process status and thread backtrace at launch", + default=False, + ) return option_parser def CrashLogOptionParser(): - description = '''Symbolicate one or more darwin crash log files to provide source file and line information, + description = """Symbolicate one or more darwin crash log files to provide source file and line information, inlined stack frames back to the concrete functions, and disassemble the location of the crash for the first frame of the crashed thread. If this script is imported into the LLDB command interpreter, a "crashlog" command will be added to the interpreter for use at the LLDB command line. After a crash log has been parsed and symbolicated, a target will have been created that has all of the shared libraries loaded at the load addresses found in the crash log file. This allows you to explore the program as if it were stopped at the locations described in the crash log and functions can -be disassembled and lookups can be performed using the addresses found in the crash log.''' - return CreateSymbolicateCrashLogOptions('crashlog', description, True) +be disassembled and lookups can be performed using the addresses found in the crash log.""" + return CreateSymbolicateCrashLogOptions("crashlog", description, True) + def SymbolicateCrashLogs(debugger, command_args, result): option_parser = CrashLogOptionParser() @@ -1423,9 +1588,9 @@ return if options.debug: - print('command_args = %s' % command_args) - print('options', options) - print('args', args) + print("command_args = %s" % command_args) + print("options", options) + print("args", args) if options.debug_delay > 0: print("Waiting %u seconds for debugger to attach..." % options.debug_delay) @@ -1448,25 +1613,34 @@ for crash_log_file in args: if should_run_in_interactive_mode(options, ci): try: - load_crashlog_in_scripted_process(debugger, crash_log_file, - options, result) + load_crashlog_in_scripted_process( + debugger, crash_log_file, options, result + ) except InteractiveCrashLogException as e: result.SetError(str(e)) else: - crash_log = CrashLogParser.create(debugger, crash_log_file, options.verbose).parse() + crash_log = CrashLogParser.create( + debugger, crash_log_file, options.verbose + ).parse() SymbolicateCrashLog(crash_log, options) -if __name__ == '__main__': + +if __name__ == "__main__": # Create a new debugger instance debugger = lldb.SBDebugger.Create() result = lldb.SBCommandReturnObject() SymbolicateCrashLogs(debugger, sys.argv[1:], result) lldb.SBDebugger.Destroy(debugger) + def __lldb_init_module(debugger, internal_dict): debugger.HandleCommand( - 'command script add -o -c lldb.macosx.crashlog.Symbolicate crashlog') + "command script add -o -c lldb.macosx.crashlog.Symbolicate crashlog" + ) debugger.HandleCommand( - 'command script add -o -f lldb.macosx.crashlog.save_crashlog save_crashlog') - print('"crashlog" and "save_crashlog" commands have been installed, use ' - 'the "--help" options on these commands for detailed help.') + "command script add -o -f lldb.macosx.crashlog.save_crashlog save_crashlog" + ) + print( + '"crashlog" and "save_crashlog" commands have been installed, use ' + 'the "--help" options on these commands for detailed help.' + ) diff --git a/lldb/examples/python/delta.py b/lldb/examples/python/delta.py --- a/lldb/examples/python/delta.py +++ b/lldb/examples/python/delta.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # This module will enable GDB remote packet logging when the # 'start_gdb_log' command is called with a filename to log to. When the # 'stop_gdb_log' command is called, it will disable the logging and @@ -14,7 +14,7 @@ # (lldb) command script import /path/to/gdbremote.py # Or it can be added to your ~/.lldbinit file so this module is always # available. -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- import optparse import os @@ -24,14 +24,14 @@ def start_gdb_log(debugger, command, result, dict): - '''Start logging GDB remote packets by enabling logging with timestamps and + """Start logging GDB remote packets by enabling logging with timestamps and thread safe logging. Follow a call to this function with a call to "stop_gdb_log" - in order to dump out the commands.''' + in order to dump out the commands.""" global log_file if log_file: result.PutCString( - 'error: logging is already in progress with file "%s"', - log_file) + 'error: logging is already in progress with file "%s"', log_file + ) else: args_len = len(args) if args_len == 0: @@ -41,14 +41,16 @@ if log_file: debugger.HandleCommand( - 'log enable --threadsafe --timestamp --file "%s" gdb-remote packets' % - log_file) + 'log enable --threadsafe --timestamp --file "%s" gdb-remote packets' + % log_file + ) result.PutCString( - "GDB packet logging enable with log file '%s'\nUse the 'stop_gdb_log' command to stop logging and show packet statistics." % - log_file) + "GDB packet logging enable with log file '%s'\nUse the 'stop_gdb_log' command to stop logging and show packet statistics." + % log_file + ) return - result.PutCString('error: invalid log file path') + result.PutCString("error: invalid log file path") result.PutCString(usage) @@ -61,18 +63,18 @@ def parse_time_log_args(command_args): usage = "usage: parse_time_log [options] []" - description = '''Parse a log file that contains timestamps and convert the timestamps to delta times between log lines.''' + description = """Parse a log file that contains timestamps and convert the timestamps to delta times between log lines.""" parser = optparse.OptionParser( - description=description, - prog='parse_time_log', - usage=usage) + description=description, prog="parse_time_log", usage=usage + ) parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', - help='display verbose debug info', - default=False) + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="display verbose debug info", + default=False, + ) try: (options, args) = parser.parse_args(command_args) except: @@ -82,7 +84,7 @@ def parse_log_file(file, options): - '''Parse a log file that was contains timestamps. These logs are typically + """Parse a log file that was contains timestamps. These logs are typically generated using: (lldb) log enable --threadsafe --timestamp --file .... @@ -91,13 +93,13 @@ show delta times between log lines and also keep track of how long it takes for GDB remote commands to make a send/receive round trip. This can be handy when trying to figure out why some operation in the debugger is taking - a long time during a preset set of debugger commands.''' + a long time during a preset set of debugger commands.""" - print('#----------------------------------------------------------------------') + print("#----------------------------------------------------------------------") print("# Log file: '%s'" % file) - print('#----------------------------------------------------------------------') + print("#----------------------------------------------------------------------") - timestamp_regex = re.compile('(\s*)([1-9][0-9]+\.[0-9]+)([^0-9].*)$') + timestamp_regex = re.compile("(\s*)([1-9][0-9]+\.[0-9]+)([^0-9].*)$") base_time = 0.0 last_time = 0.0 @@ -113,20 +115,27 @@ else: base_time = curr_time - print('%s%.6f %+.6f%s' % (match.group(1), curr_time - base_time, delta, match.group(3))) + print( + "%s%.6f %+.6f%s" + % (match.group(1), curr_time - base_time, delta, match.group(3)) + ) last_time = curr_time else: print(line) -if __name__ == '__main__': +if __name__ == "__main__": import sys + parse_time_log_args(sys.argv[1:]) def __lldb_init_module(debugger, internal_dict): - # This initializer is being run from LLDB in the embedded command interpreter - # Add any commands contained in this module to LLDB - debugger.HandleCommand( - 'command script add -o -f delta.parse_time_log parse_time_log') - print('The "parse_time_log" command is now installed and ready for use, type "parse_time_log --help" for more information') + # This initializer is being run from LLDB in the embedded command interpreter + # Add any commands contained in this module to LLDB + debugger.HandleCommand( + "command script add -o -f delta.parse_time_log parse_time_log" + ) + print( + 'The "parse_time_log" command is now installed and ready for use, type "parse_time_log --help" for more information' + ) diff --git a/lldb/examples/python/diagnose_nsstring.py b/lldb/examples/python/diagnose_nsstring.py --- a/lldb/examples/python/diagnose_nsstring.py +++ b/lldb/examples/python/diagnose_nsstring.py @@ -19,13 +19,13 @@ data = data + "0x%x" % byte if byte == 0: data = data + "(\\0)" - elif byte == 0xa: + elif byte == 0xA: data = data + "(\\a)" - elif byte == 0xb: + elif byte == 0xB: data = data + "(\\b)" - elif byte == 0xc: + elif byte == 0xC: data = data + "(\\c)" - elif byte == '\n': + elif byte == "\n": data = data + "(\\n)" else: data = data + "(%s)" % chr(byte) @@ -105,22 +105,37 @@ dumped = target.EvaluateExpression(expression, options) print(str(dumped), file=result) - little_endian = (target.byte_order == lldb.eByteOrderLittle) + little_endian = target.byte_order == lldb.eByteOrderLittle ptr_size = target.addr_size - info_bits = dumped.GetChildMemberWithName("_cfinfo").GetChildAtIndex( - 0 if little_endian else 3).GetValueAsUnsigned(0) + info_bits = ( + dumped.GetChildMemberWithName("_cfinfo") + .GetChildAtIndex(0 if little_endian else 3) + .GetValueAsUnsigned(0) + ) is_mutable = (info_bits & 1) == 1 is_inline = (info_bits & 0x60) == 0 has_explicit_length = (info_bits & (1 | 4)) != 4 is_unicode = (info_bits & 0x10) == 0x10 is_special = ( - nsstring.GetDynamicValue( - lldb.eDynamicCanRunTarget).GetTypeName() == "NSPathStore2") + nsstring.GetDynamicValue(lldb.eDynamicCanRunTarget).GetTypeName() + == "NSPathStore2" + ) has_null = (info_bits & 8) == 8 - print("\nInfo=%d\nMutable=%s\nInline=%s\nExplicit=%s\nUnicode=%s\nSpecial=%s\nNull=%s\n" % \ - (info_bits, "yes" if is_mutable else "no", "yes" if is_inline else "no", "yes" if has_explicit_length else "no", "yes" if is_unicode else "no", "yes" if is_special else "no", "yes" if has_null else "no"), file=result) + print( + "\nInfo=%d\nMutable=%s\nInline=%s\nExplicit=%s\nUnicode=%s\nSpecial=%s\nNull=%s\n" + % ( + info_bits, + "yes" if is_mutable else "no", + "yes" if is_inline else "no", + "yes" if has_explicit_length else "no", + "yes" if is_unicode else "no", + "yes" if is_special else "no", + "yes" if has_null else "no", + ), + file=result, + ) explicit_length_offset = 0 if not has_null and has_explicit_length and not is_special: @@ -139,20 +154,33 @@ else: explicit_length_offset = nsstring_address + explicit_length_offset explicit_length = process.ReadUnsignedFromMemory( - explicit_length_offset, 4, error) - print("Explicit length location is at 0x%x - read value is %d\n" % ( - explicit_length_offset, explicit_length), file=result) + explicit_length_offset, 4, error + ) + print( + "Explicit length location is at 0x%x - read value is %d\n" + % (explicit_length_offset, explicit_length), + file=result, + ) if is_mutable: location = 2 * ptr_size + nsstring_address location = process.ReadPointerFromMemory(location, error) - elif is_inline and has_explicit_length and not is_unicode and not is_special and not is_mutable: + elif ( + is_inline + and has_explicit_length + and not is_unicode + and not is_special + and not is_mutable + ): location = 3 * ptr_size + nsstring_address elif is_unicode: location = 2 * ptr_size + nsstring_address if is_inline: if not has_explicit_length: - print("Unicode & Inline & !Explicit is a new combo - no formula for it", file=result) + print( + "Unicode & Inline & !Explicit is a new combo - no formula for it", + file=result, + ) else: location += ptr_size else: @@ -167,17 +195,26 @@ location = 2 * ptr_size + nsstring_address location = process.ReadPointerFromMemory(location, error) print("Expected data location: 0x%x\n" % (location), file=result) - print("1K of data around location: %s\n" % read_memory( - process, location, 1024), file=result) - print("5K of data around string pointer: %s\n" % read_memory( - process, nsstring_address, 1024 * 5), file=result) + print( + "1K of data around location: %s\n" % read_memory(process, location, 1024), + file=result, + ) + print( + "5K of data around string pointer: %s\n" + % read_memory(process, nsstring_address, 1024 * 5), + file=result, + ) def __lldb_init_module(debugger, internal_dict): debugger.HandleCommand( - "command script add -o -f %s.diagnose_nsstring_Command_Impl diagnose-nsstring" % - __name__) - print('The "diagnose-nsstring" command has been installed, type "help diagnose-nsstring" for detailed help.') + "command script add -o -f %s.diagnose_nsstring_Command_Impl diagnose-nsstring" + % __name__ + ) + print( + 'The "diagnose-nsstring" command has been installed, type "help diagnose-nsstring" for detailed help.' + ) + __lldb_init_module(lldb.debugger, None) __lldb_init_module = None diff --git a/lldb/examples/python/diagnose_unwind.py b/lldb/examples/python/diagnose_unwind.py --- a/lldb/examples/python/diagnose_unwind.py +++ b/lldb/examples/python/diagnose_unwind.py @@ -36,22 +36,48 @@ if module_filename is None: module_filename = "" if module_uuid_str != "" or module_filename != "": - module_description = '%s %s' % ( - module_filename, module_uuid_str) + module_description = "%s %s" % (module_filename, module_uuid_str) except Exception: - print('%2d: pc==0x%-*x fp==0x%-*x' % (frame_num, addr_width, addr_for_printing, addr_width, fp)) + print( + "%2d: pc==0x%-*x fp==0x%-*x" + % (frame_num, addr_width, addr_for_printing, addr_width, fp) + ) return sym_ctx = target.ResolveSymbolContextForAddress( - sbaddr, lldb.eSymbolContextEverything) + sbaddr, lldb.eSymbolContextEverything + ) if sym_ctx.IsValid() and sym_ctx.GetSymbol().IsValid(): function_start = sym_ctx.GetSymbol().GetStartAddress().GetLoadAddress(target) offset = addr - function_start - print('%2d: pc==0x%-*x fp==0x%-*x %s %s + %d' % (frame_num, addr_width, addr_for_printing, addr_width, fp, module_description, sym_ctx.GetSymbol().GetName(), offset)) + print( + "%2d: pc==0x%-*x fp==0x%-*x %s %s + %d" + % ( + frame_num, + addr_width, + addr_for_printing, + addr_width, + fp, + module_description, + sym_ctx.GetSymbol().GetName(), + offset, + ) + ) else: - print('%2d: pc==0x%-*x fp==0x%-*x %s' % (frame_num, addr_width, addr_for_printing, addr_width, fp, module_description)) + print( + "%2d: pc==0x%-*x fp==0x%-*x %s" + % ( + frame_num, + addr_width, + addr_for_printing, + addr_width, + fp, + module_description, + ) + ) return sbaddr.GetModule() + # A simple stack walk algorithm that follows the frame chain. # Returns a two-element list; the first element is a list of modules # seen and the second element is a list of addresses seen during the backtrace. @@ -76,7 +102,8 @@ module_list = [] address_list = [cur_thread.GetFrameAtIndex(0).GetPC()] this_module = backtrace_print_frame( - target, 0, cur_thread.GetFrameAtIndex(0).GetPC(), initial_fp) + target, 0, cur_thread.GetFrameAtIndex(0).GetPC(), initial_fp + ) print_stack_frame(process, initial_fp) print("") if this_module is not None: @@ -86,11 +113,17 @@ cur_fp = process.ReadPointerFromMemory(initial_fp, lldb.SBError()) cur_pc = process.ReadPointerFromMemory( - initial_fp + process.GetAddressByteSize(), lldb.SBError()) + initial_fp + process.GetAddressByteSize(), lldb.SBError() + ) frame_num = 1 - while cur_pc != 0 and cur_fp != 0 and cur_pc != lldb.LLDB_INVALID_ADDRESS and cur_fp != lldb.LLDB_INVALID_ADDRESS: + while ( + cur_pc != 0 + and cur_fp != 0 + and cur_pc != lldb.LLDB_INVALID_ADDRESS + and cur_fp != lldb.LLDB_INVALID_ADDRESS + ): address_list.append(cur_pc) this_module = backtrace_print_frame(target, frame_num, cur_pc, cur_fp) print_stack_frame(process, cur_fp) @@ -100,13 +133,15 @@ frame_num = frame_num + 1 next_pc = 0 next_fp = 0 - if target.triple[ - 0:6] == "x86_64" or target.triple[ - 0:4] == "i386" or target.triple[ - 0:3] == "arm": + if ( + target.triple[0:6] == "x86_64" + or target.triple[0:4] == "i386" + or target.triple[0:3] == "arm" + ): error = lldb.SBError() next_pc = process.ReadPointerFromMemory( - cur_fp + process.GetAddressByteSize(), error) + cur_fp + process.GetAddressByteSize(), error + ) if not error.Success(): next_pc = 0 next_fp = process.ReadPointerFromMemory(cur_fp, error) @@ -135,8 +170,7 @@ error = lldb.SBError() try: while i < 5 and error.Success(): - address = process.ReadPointerFromMemory( - addr + (i * addr_size), error) + address = process.ReadPointerFromMemory(addr + (i * addr_size), error) outline += " 0x%x" % address i += 1 print(outline) @@ -146,11 +180,11 @@ def diagnose_unwind(debugger, command, result, dict): """ - Gather diagnostic information to help debug incorrect unwind (backtrace) - behavior in lldb. When there is a backtrace that doesn't look - correct, run this command with the correct thread selected and a - large amount of diagnostic information will be printed, it is likely - to be helpful when reporting the problem. + Gather diagnostic information to help debug incorrect unwind (backtrace) + behavior in lldb. When there is a backtrace that doesn't look + correct, run this command with the correct thread selected and a + large amount of diagnostic information will be printed, it is likely + to be helpful when reporting the problem. """ command_args = shlex.split(command) @@ -166,34 +200,44 @@ thread = process.GetSelectedThread() if thread: lldb_versions_match = re.search( - r'[lL][lL][dD][bB]-(\d+)([.](\d+))?([.](\d+))?', - debugger.GetVersionString()) + r"[lL][lL][dD][bB]-(\d+)([.](\d+))?([.](\d+))?", + debugger.GetVersionString(), + ) lldb_version = 0 lldb_minor = 0 - if len(lldb_versions_match.groups() - ) >= 1 and lldb_versions_match.groups()[0]: + if ( + len(lldb_versions_match.groups()) >= 1 + and lldb_versions_match.groups()[0] + ): lldb_major = int(lldb_versions_match.groups()[0]) - if len(lldb_versions_match.groups() - ) >= 5 and lldb_versions_match.groups()[4]: + if ( + len(lldb_versions_match.groups()) >= 5 + and lldb_versions_match.groups()[4] + ): lldb_minor = int(lldb_versions_match.groups()[4]) modules_seen = [] addresses_seen = [] - print('LLDB version %s' % debugger.GetVersionString()) - print('Unwind diagnostics for thread %d' % thread.GetIndexID()) + print("LLDB version %s" % debugger.GetVersionString()) + print("Unwind diagnostics for thread %d" % thread.GetIndexID()) print("") - print("=============================================================================================") + print( + "=============================================================================================" + ) print("") print("OS plugin setting:") debugger.HandleCommand( - "settings show target.process.python-os-plugin-path") + "settings show target.process.python-os-plugin-path" + ) print("") print("Live register context:") thread.SetSelectedFrame(0) debugger.HandleCommand("register read") print("") - print("=============================================================================================") + print( + "=============================================================================================" + ) print("") print("lldb's unwind algorithm:") print("") @@ -201,7 +245,8 @@ for frame in thread.frames: if not frame.IsInlined(): this_module = backtrace_print_frame( - target, frame_num, frame.GetPC(), frame.GetFP()) + target, frame_num, frame.GetPC(), frame.GetFP() + ) print_stack_frame(process, frame.GetFP()) print("") if this_module is not None: @@ -209,7 +254,9 @@ addresses_seen.append(frame.GetPC()) frame_num = frame_num + 1 print("") - print("=============================================================================================") + print( + "=============================================================================================" + ) print("") print("Simple stack walk algorithm:") print("") @@ -221,94 +268,122 @@ addresses_seen.update(set(address_list)) print("") - print("=============================================================================================") + print( + "=============================================================================================" + ) print("") print("Modules seen in stack walks:") print("") modules_already_seen = set() for module in modules_seen: - if module is not None and module.GetFileSpec().GetFilename() is not None: - if not module.GetFileSpec().GetFilename() in modules_already_seen: + if ( + module is not None + and module.GetFileSpec().GetFilename() is not None + ): + if ( + not module.GetFileSpec().GetFilename() + in modules_already_seen + ): debugger.HandleCommand( - 'image list %s' % - module.GetFileSpec().GetFilename()) - modules_already_seen.add( - module.GetFileSpec().GetFilename()) + "image list %s" % module.GetFileSpec().GetFilename() + ) + modules_already_seen.add(module.GetFileSpec().GetFilename()) print("") - print("=============================================================================================") + print( + "=============================================================================================" + ) print("") print("Disassembly ofaddresses seen in stack walks:") print("") additional_addresses_to_disassemble = addresses_seen for frame in thread.frames: if not frame.IsInlined(): - print("--------------------------------------------------------------------------------------") + print( + "--------------------------------------------------------------------------------------" + ) print("") - print("Disassembly of %s, frame %d, address 0x%x" % (frame.GetFunctionName(), frame.GetFrameID(), frame.GetPC())) + print( + "Disassembly of %s, frame %d, address 0x%x" + % ( + frame.GetFunctionName(), + frame.GetFrameID(), + frame.GetPC(), + ) + ) print("") - if target.triple[ - 0:6] == "x86_64" or target.triple[ - 0:4] == "i386": + if ( + target.triple[0:6] == "x86_64" + or target.triple[0:4] == "i386" + ): debugger.HandleCommand( - 'disassemble -F att -a 0x%x' % frame.GetPC()) + "disassemble -F att -a 0x%x" % frame.GetPC() + ) else: debugger.HandleCommand( - 'disassemble -a 0x%x' % - frame.GetPC()) + "disassemble -a 0x%x" % frame.GetPC() + ) if frame.GetPC() in additional_addresses_to_disassemble: - additional_addresses_to_disassemble.remove( - frame.GetPC()) + additional_addresses_to_disassemble.remove(frame.GetPC()) for address in list(additional_addresses_to_disassemble): - print("--------------------------------------------------------------------------------------") + print( + "--------------------------------------------------------------------------------------" + ) print("") print("Disassembly of 0x%x" % address) print("") - if target.triple[ - 0:6] == "x86_64" or target.triple[ - 0:4] == "i386": - debugger.HandleCommand( - 'disassemble -F att -a 0x%x' % address) + if target.triple[0:6] == "x86_64" or target.triple[0:4] == "i386": + debugger.HandleCommand("disassemble -F att -a 0x%x" % address) else: - debugger.HandleCommand('disassemble -a 0x%x' % address) + debugger.HandleCommand("disassemble -a 0x%x" % address) print("") - print("=============================================================================================") + print( + "=============================================================================================" + ) print("") additional_addresses_to_show_unwind = addresses_seen for frame in thread.frames: if not frame.IsInlined(): - print("--------------------------------------------------------------------------------------") + print( + "--------------------------------------------------------------------------------------" + ) print("") - print("Unwind instructions for %s, frame %d" % (frame.GetFunctionName(), frame.GetFrameID())) + print( + "Unwind instructions for %s, frame %d" + % (frame.GetFunctionName(), frame.GetFrameID()) + ) print("") debugger.HandleCommand( - 'image show-unwind -a "0x%x"' % frame.GetPC()) + 'image show-unwind -a "0x%x"' % frame.GetPC() + ) if frame.GetPC() in additional_addresses_to_show_unwind: - additional_addresses_to_show_unwind.remove( - frame.GetPC()) + additional_addresses_to_show_unwind.remove(frame.GetPC()) for address in list(additional_addresses_to_show_unwind): - print("--------------------------------------------------------------------------------------") + print( + "--------------------------------------------------------------------------------------" + ) print("") print("Unwind instructions for 0x%x" % address) print("") - debugger.HandleCommand( - 'image show-unwind -a "0x%x"' % address) + debugger.HandleCommand('image show-unwind -a "0x%x"' % address) def create_diagnose_unwind_options(): usage = "usage: %prog" - description = '''Print diagnostic information about a thread backtrace which will help to debug unwind problems''' + description = """Print diagnostic information about a thread backtrace which will help to debug unwind problems""" parser = optparse.OptionParser( - description=description, - prog='diagnose_unwind', - usage=usage) + description=description, prog="diagnose_unwind", usage=usage + ) return parser + def __lldb_init_module(debugger, internal_dict): debugger.HandleCommand( - 'command script add -o -f %s.diagnose_unwind diagnose-unwind' % - __name__) - print('The "diagnose-unwind" command has been installed, type "help diagnose-unwind" for detailed help.') + "command script add -o -f %s.diagnose_unwind diagnose-unwind" % __name__ + ) + print( + 'The "diagnose-unwind" command has been installed, type "help diagnose-unwind" for detailed help.' + ) diff --git a/lldb/examples/python/dict_utils.py b/lldb/examples/python/dict_utils.py --- a/lldb/examples/python/dict_utils.py +++ b/lldb/examples/python/dict_utils.py @@ -1,4 +1,3 @@ - class LookupDictionary(dict): """ a dictionary which can lookup value by key, or keys by value @@ -30,7 +29,6 @@ class Enum(LookupDictionary): - def __init__(self, initial_value=0, items=[]): """items can be a list of pair_lists or a dictionary""" LookupDictionary.__init__(self, items) @@ -38,7 +36,7 @@ def set_value(self, v): v_typename = typeof(v).__name__ - if v_typename == 'str': + if v_typename == "str": if str in self: v = self[v] else: diff --git a/lldb/examples/python/disasm-stress-test.py b/lldb/examples/python/disasm-stress-test.py --- a/lldb/examples/python/disasm-stress-test.py +++ b/lldb/examples/python/disasm-stress-test.py @@ -8,51 +8,60 @@ import time parser = argparse.ArgumentParser( - description="Run an exhaustive test of the LLDB disassembler for a specific architecture.") + description="Run an exhaustive test of the LLDB disassembler for a specific architecture." +) parser.add_argument( - '--arch', + "--arch", required=True, - action='store', - help='The architecture whose disassembler is to be tested') + action="store", + help="The architecture whose disassembler is to be tested", +) parser.add_argument( - '--bytes', + "--bytes", required=True, - action='store', + action="store", type=int, - help='The byte width of instructions for that architecture') + help="The byte width of instructions for that architecture", +) parser.add_argument( - '--random', + "--random", required=False, - action='store_true', - help='Enables non-sequential testing') + action="store_true", + help="Enables non-sequential testing", +) parser.add_argument( - '--start', + "--start", required=False, - action='store', + action="store", type=int, - help='The first instruction value to test') + help="The first instruction value to test", +) parser.add_argument( - '--skip', + "--skip", required=False, - action='store', + action="store", type=int, - help='The interval between instructions to test') + help="The interval between instructions to test", +) parser.add_argument( - '--log', + "--log", required=False, - action='store', - help='A log file to write the most recent instruction being tested') + action="store", + help="A log file to write the most recent instruction being tested", +) parser.add_argument( - '--time', + "--time", required=False, - action='store_true', - help='Every 100,000 instructions, print an ETA to standard out') + action="store_true", + help="Every 100,000 instructions, print an ETA to standard out", +) parser.add_argument( - '--lldb', + "--lldb", required=False, - action='store', - help='The path to LLDB.framework, if LLDB should be overridden') + action="store", + help="The path to LLDB.framework, if LLDB should be overridden", +) arguments = sys.argv[1:] @@ -76,6 +85,7 @@ sys.path.append(lldb_framework_path + "/Resources/Python") + if arg_ns.lldb is None: AddLLDBToSysPathOnMacOSX() else: @@ -103,12 +113,11 @@ def PrintByteArray(log_file, byte_array): for byte in byte_array: - print(hex(byte) + " ", end=' ', file=log_file) + print(hex(byte) + " ", end=" ", file=log_file) print(file=log_file) class SequentialInstructionProvider: - def __init__(self, byte_width, log_file, start=0, skip=1): self.m_byte_width = byte_width self.m_log_file = log_file @@ -146,11 +155,10 @@ class RandomInstructionProvider: - def __init__(self, byte_width, log_file): self.m_byte_width = byte_width self.m_log_file = log_file - self.m_random_file = open("/dev/random", 'r') + self.m_random_file = open("/dev/random", "r") def PrintCurrentState(self, ret): ResetLogFile(self.m_log_file) @@ -172,13 +180,14 @@ raise StopIteration return ret + log_file = None def GetProviderWithArguments(args): global log_file if args.log is not None: - log_file = open(args.log, 'w') + log_file = open(args.log, "w") else: log_file = sys.stdout instruction_provider = None @@ -192,9 +201,11 @@ if args.skip is not None: skip = args.skip instruction_provider = SequentialInstructionProvider( - args.bytes, log_file, start, skip) + args.bytes, log_file, start, skip + ) return instruction_provider + instruction_provider = GetProviderWithArguments(arg_ns) fake_address = lldb.SBAddress() @@ -208,13 +219,12 @@ for inst_bytes in instruction_provider: if actually_time: - if (num_instructions_logged != 0) and ( - num_instructions_logged % 100000 == 0): + if (num_instructions_logged != 0) and (num_instructions_logged % 100000 == 0): curr_time = time.time() elapsed_time = curr_time - start_time - remaining_time = float( - total_num_instructions - num_instructions_logged) * ( - float(elapsed_time) / float(num_instructions_logged)) + remaining_time = float(total_num_instructions - num_instructions_logged) * ( + float(elapsed_time) / float(num_instructions_logged) + ) print(str(datetime.timedelta(seconds=remaining_time))) num_instructions_logged = num_instructions_logged + 1 inst_list = target.GetInstructions(fake_address, inst_bytes) diff --git a/lldb/examples/python/disasm.py b/lldb/examples/python/disasm.py --- a/lldb/examples/python/disasm.py +++ b/lldb/examples/python/disasm.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # Be sure to add the python path that points to the LLDB shared library. # On MacOSX csh, tcsh: # setenv PYTHONPATH /Developer/Library/PrivateFrameworks/LLDB.framework/Resources/Python # On MacOSX sh, bash: # export PYTHONPATH=/Developer/Library/PrivateFrameworks/LLDB.framework/Resources/Python -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- import lldb import os @@ -23,11 +23,12 @@ print(" By default, it breaks at and disassembles the 'main' function.") sys.exit(0) + if len(sys.argv) == 2: - fname = 'main' + fname = "main" exe = sys.argv[1] elif len(sys.argv) == 4: - if sys.argv[1] != '-n': + if sys.argv[1] != "-n": usage() else: fname = sys.argv[2] @@ -49,8 +50,7 @@ if target: # If the target is valid set a breakpoint at main - main_bp = target.BreakpointCreateByName( - fname, target.GetExecutable().GetFilename()) + main_bp = target.BreakpointCreateByName(fname, target.GetExecutable().GetFilename()) print(main_bp) @@ -98,16 +98,26 @@ disassemble_instructions(insts) registerList = frame.GetRegisters() - print("Frame registers (size of register set = %d):" % registerList.GetSize()) + print( + "Frame registers (size of register set = %d):" + % registerList.GetSize() + ) for value in registerList: # print value - print("%s (number of children = %d):" % (value.GetName(), value.GetNumChildren())) + print( + "%s (number of children = %d):" + % (value.GetName(), value.GetNumChildren()) + ) for child in value: - print("Name: ", child.GetName(), " Value: ", child.GetValue()) + print( + "Name: ", child.GetName(), " Value: ", child.GetValue() + ) - print("Hit the breakpoint at main, enter to continue and wait for program to exit or 'Ctrl-D'/'quit' to terminate the program") + print( + "Hit the breakpoint at main, enter to continue and wait for program to exit or 'Ctrl-D'/'quit' to terminate the program" + ) next = sys.stdin.readline() - if not next or next.rstrip('\n') == 'quit': + if not next or next.rstrip("\n") == "quit": print("Terminating the inferior process...") process.Kill() else: @@ -119,7 +129,10 @@ elif state == lldb.eStateExited: print("Didn't hit the breakpoint at main, program has exited...") else: - print("Unexpected process state: %s, killing process..." % debugger.StateAsCString(state)) + print( + "Unexpected process state: %s, killing process..." + % debugger.StateAsCString(state) + ) process.Kill() diff --git a/lldb/examples/python/disassembly_mode.py b/lldb/examples/python/disassembly_mode.py --- a/lldb/examples/python/disassembly_mode.py +++ b/lldb/examples/python/disassembly_mode.py @@ -1,41 +1,42 @@ """ Adds the 'toggle-disassembly' command to switch you into a disassembly only mode """ import lldb + class DisassemblyMode: def __init__(self, debugger, unused): self.dbg = debugger self.interp = debugger.GetCommandInterpreter() self.store_state() self.mode_off = True - + def store_state(self): self.dis_count = self.get_string_value("stop-disassembly-count") self.dis_display = self.get_string_value("stop-disassembly-display") self.before_count = self.get_string_value("stop-line-count-before") self.after_count = self.get_string_value("stop-line-count-after") - + def get_string_value(self, setting): result = lldb.SBCommandReturnObject() self.interp.HandleCommand("settings show " + setting, result) value = result.GetOutput().split(" = ")[1].rstrip("\n") return value - + def set_value(self, setting, value): result = lldb.SBCommandReturnObject() self.interp.HandleCommand("settings set " + setting + " " + value, result) - + def __call__(self, debugger, command, exe_ctx, result): if self.mode_off: self.mode_off = False self.store_state() - self.set_value("stop-disassembly-display","always") + self.set_value("stop-disassembly-display", "always") self.set_value("stop-disassembly-count", "8") self.set_value("stop-line-count-before", "0") self.set_value("stop-line-count-after", "0") result.AppendMessage("Disassembly mode on.") else: self.mode_off = True - self.set_value("stop-disassembly-display",self.dis_display) + self.set_value("stop-disassembly-display", self.dis_display) self.set_value("stop-disassembly-count", self.dis_count) self.set_value("stop-line-count-before", self.before_count) self.set_value("stop-line-count-after", self.after_count) @@ -44,5 +45,8 @@ def get_short_help(self): return "Toggles between a disassembly only mode and normal source mode\n" + def __lldb_init_module(debugger, unused): - debugger.HandleCommand("command script add -o -c disassembly_mode.DisassemblyMode toggle-disassembly") + debugger.HandleCommand( + "command script add -o -c disassembly_mode.DisassemblyMode toggle-disassembly" + ) diff --git a/lldb/examples/python/file_extract.py b/lldb/examples/python/file_extract.py --- a/lldb/examples/python/file_extract.py +++ b/lldb/examples/python/file_extract.py @@ -6,10 +6,10 @@ class FileExtract: - '''Decode binary data from a file''' + """Decode binary data from a file""" - def __init__(self, f, b='='): - '''Initialize with an open binary file and optional byte order''' + def __init__(self, f, b="="): + """Initialize with an open binary file and optional byte order""" self.file = f self.byte_order = b @@ -17,16 +17,16 @@ def set_byte_order(self, b): '''Set the byte order, valid values are "big", "little", "swap", "native", "<", ">", "@", "="''' - if b == 'big': - self.byte_order = '>' - elif b == 'little': - self.byte_order = '<' - elif b == 'swap': + if b == "big": + self.byte_order = ">" + elif b == "little": + self.byte_order = "<" + elif b == "swap": # swap what ever the current byte order is self.byte_order = swap_unpack_char() - elif b == 'native': - self.byte_order = '=' - elif b == '<' or b == '>' or b == '@' or b == '=': + elif b == "native": + self.byte_order = "=" + elif b == "<" or b == ">" or b == "@" or b == "=": self.byte_order = b else: print("error: invalid byte order specified: '%s'" % b) @@ -56,91 +56,89 @@ self.file.seek(offset, 0) def pop_offset_and_seek(self): - '''Pop a previously pushed file offset, or do nothing if there were no previously pushed offsets''' + """Pop a previously pushed file offset, or do nothing if there were no previously pushed offsets""" if len(self.offsets) > 0: self.file.seek(self.offsets.pop()) def get_sint8(self, fail_value=0): - '''Extract a single int8_t from the binary file at the current file position, returns a single integer''' + """Extract a single int8_t from the binary file at the current file position, returns a single integer""" s = self.read_size(1) if s: - v, = struct.unpack(self.byte_order + 'b', s) + (v,) = struct.unpack(self.byte_order + "b", s) return v else: return fail_value def get_uint8(self, fail_value=0): - '''Extract a single uint8_t from the binary file at the current file position, returns a single integer''' + """Extract a single uint8_t from the binary file at the current file position, returns a single integer""" s = self.read_size(1) if s: - v, = struct.unpack(self.byte_order + 'B', s) + (v,) = struct.unpack(self.byte_order + "B", s) return v else: return fail_value def get_sint16(self, fail_value=0): - '''Extract a single int16_t from the binary file at the current file position, returns a single integer''' + """Extract a single int16_t from the binary file at the current file position, returns a single integer""" s = self.read_size(2) if s: - v, = struct.unpack(self.byte_order + 'h', s) + (v,) = struct.unpack(self.byte_order + "h", s) return v else: return fail_value def get_uint16(self, fail_value=0): - '''Extract a single uint16_t from the binary file at the current file position, returns a single integer''' + """Extract a single uint16_t from the binary file at the current file position, returns a single integer""" s = self.read_size(2) if s: - v, = struct.unpack(self.byte_order + 'H', s) + (v,) = struct.unpack(self.byte_order + "H", s) return v else: return fail_value def get_sint32(self, fail_value=0): - '''Extract a single int32_t from the binary file at the current file position, returns a single integer''' + """Extract a single int32_t from the binary file at the current file position, returns a single integer""" s = self.read_size(4) if s: - v, = struct.unpack(self.byte_order + 'i', s) + (v,) = struct.unpack(self.byte_order + "i", s) return v else: return fail_value def get_uint32(self, fail_value=0): - '''Extract a single uint32_t from the binary file at the current file position, returns a single integer''' + """Extract a single uint32_t from the binary file at the current file position, returns a single integer""" s = self.read_size(4) if s: - v, = struct.unpack(self.byte_order + 'I', s) + (v,) = struct.unpack(self.byte_order + "I", s) return v else: return fail_value def get_sint64(self, fail_value=0): - '''Extract a single int64_t from the binary file at the current file position, returns a single integer''' + """Extract a single int64_t from the binary file at the current file position, returns a single integer""" s = self.read_size(8) if s: - v, = struct.unpack(self.byte_order + 'q', s) + (v,) = struct.unpack(self.byte_order + "q", s) return v else: return fail_value def get_uint64(self, fail_value=0): - '''Extract a single uint64_t from the binary file at the current file position, returns a single integer''' + """Extract a single uint64_t from the binary file at the current file position, returns a single integer""" s = self.read_size(8) if s: - v, = struct.unpack(self.byte_order + 'Q', s) + (v,) = struct.unpack(self.byte_order + "Q", s) return v else: return fail_value def get_fixed_length_c_string( - self, - n, - fail_value='', - isprint_only_with_space_padding=False): - '''Extract a single fixed length C string from the binary file at the current file position, returns a single C string''' + self, n, fail_value="", isprint_only_with_space_padding=False + ): + """Extract a single fixed length C string from the binary file at the current file position, returns a single C string""" s = self.read_size(n) if s: - cstr, = struct.unpack(self.byte_order + ("%i" % n) + 's', s) + (cstr,) = struct.unpack(self.byte_order + ("%i" % n) + "s", s) # Strip trialing NULLs cstr = string.strip(cstr, "\0") if isprint_only_with_space_padding: @@ -153,8 +151,8 @@ return fail_value def get_c_string(self): - '''Extract a single NULL terminated C string from the binary file at the current file position, returns a single C string''' - cstr = '' + """Extract a single NULL terminated C string from the binary file at the current file position, returns a single C string""" + cstr = "" byte = self.get_uint8() while byte != 0: cstr += "%c" % byte @@ -162,65 +160,65 @@ return cstr def get_n_sint8(self, n, fail_value=0): - '''Extract "n" int8_t integers from the binary file at the current file position, returns a list of integers''' + """Extract "n" int8_t integers from the binary file at the current file position, returns a list of integers""" s = self.read_size(n) if s: - return struct.unpack(self.byte_order + ("%u" % n) + 'b', s) + return struct.unpack(self.byte_order + ("%u" % n) + "b", s) else: return (fail_value,) * n def get_n_uint8(self, n, fail_value=0): - '''Extract "n" uint8_t integers from the binary file at the current file position, returns a list of integers''' + """Extract "n" uint8_t integers from the binary file at the current file position, returns a list of integers""" s = self.read_size(n) if s: - return struct.unpack(self.byte_order + ("%u" % n) + 'B', s) + return struct.unpack(self.byte_order + ("%u" % n) + "B", s) else: return (fail_value,) * n def get_n_sint16(self, n, fail_value=0): - '''Extract "n" int16_t integers from the binary file at the current file position, returns a list of integers''' + """Extract "n" int16_t integers from the binary file at the current file position, returns a list of integers""" s = self.read_size(2 * n) if s: - return struct.unpack(self.byte_order + ("%u" % n) + 'h', s) + return struct.unpack(self.byte_order + ("%u" % n) + "h", s) else: return (fail_value,) * n def get_n_uint16(self, n, fail_value=0): - '''Extract "n" uint16_t integers from the binary file at the current file position, returns a list of integers''' + """Extract "n" uint16_t integers from the binary file at the current file position, returns a list of integers""" s = self.read_size(2 * n) if s: - return struct.unpack(self.byte_order + ("%u" % n) + 'H', s) + return struct.unpack(self.byte_order + ("%u" % n) + "H", s) else: return (fail_value,) * n def get_n_sint32(self, n, fail_value=0): - '''Extract "n" int32_t integers from the binary file at the current file position, returns a list of integers''' + """Extract "n" int32_t integers from the binary file at the current file position, returns a list of integers""" s = self.read_size(4 * n) if s: - return struct.unpack(self.byte_order + ("%u" % n) + 'i', s) + return struct.unpack(self.byte_order + ("%u" % n) + "i", s) else: return (fail_value,) * n def get_n_uint32(self, n, fail_value=0): - '''Extract "n" uint32_t integers from the binary file at the current file position, returns a list of integers''' + """Extract "n" uint32_t integers from the binary file at the current file position, returns a list of integers""" s = self.read_size(4 * n) if s: - return struct.unpack(self.byte_order + ("%u" % n) + 'I', s) + return struct.unpack(self.byte_order + ("%u" % n) + "I", s) else: return (fail_value,) * n def get_n_sint64(self, n, fail_value=0): - '''Extract "n" int64_t integers from the binary file at the current file position, returns a list of integers''' + """Extract "n" int64_t integers from the binary file at the current file position, returns a list of integers""" s = self.read_size(8 * n) if s: - return struct.unpack(self.byte_order + ("%u" % n) + 'q', s) + return struct.unpack(self.byte_order + ("%u" % n) + "q", s) else: return (fail_value,) * n def get_n_uint64(self, n, fail_value=0): - '''Extract "n" uint64_t integers from the binary file at the current file position, returns a list of integers''' + """Extract "n" uint64_t integers from the binary file at the current file position, returns a list of integers""" s = self.read_size(8 * n) if s: - return struct.unpack(self.byte_order + ("%u" % n) + 'Q', s) + return struct.unpack(self.byte_order + ("%u" % n) + "Q", s) else: return (fail_value,) * n diff --git a/lldb/examples/python/gdb_disassemble.py b/lldb/examples/python/gdb_disassemble.py --- a/lldb/examples/python/gdb_disassemble.py +++ b/lldb/examples/python/gdb_disassemble.py @@ -16,12 +16,20 @@ inst_offset = inst_addr - start_addr comment = inst.comment if comment: - print("<%s + %-4u> 0x%x %8s %s ; %s" % (name, inst_offset, inst_addr, inst.mnemonic, inst.operands, comment)) + print( + "<%s + %-4u> 0x%x %8s %s ; %s" + % (name, inst_offset, inst_addr, inst.mnemonic, inst.operands, comment) + ) else: - print("<%s + %-4u> 0x%x %8s %s" % (name, inst_offset, inst_addr, inst.mnemonic, inst.operands)) + print( + "<%s + %-4u> 0x%x %8s %s" + % (name, inst_offset, inst_addr, inst.mnemonic, inst.operands) + ) + # Install the command when the module gets imported def __lldb_init_module(debugger, internal_dict): debugger.HandleCommand( - 'command script add -o -f gdb_disassemble.disassemble gdb-disassemble') + "command script add -o -f gdb_disassemble.disassemble gdb-disassemble" + ) print('Installed "gdb-disassemble" command for disassembly') diff --git a/lldb/examples/python/gdbremote.py b/lldb/examples/python/gdbremote.py --- a/lldb/examples/python/gdbremote.py +++ b/lldb/examples/python/gdbremote.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # This module will enable GDB remote packet logging when the # 'start_gdb_log' command is called with a filename to log to. When the # 'stop_gdb_log' command is called, it will disable the logging and @@ -14,7 +14,7 @@ # (lldb) command script import /path/to/gdbremote.py # Or it can be added to your ~/.lldbinit file so this module is always # available. -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- import binascii import subprocess @@ -29,17 +29,17 @@ import tempfile import xml.etree.ElementTree as ET -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # Global variables -#---------------------------------------------------------------------- -g_log_file = '' -g_byte_order = 'little' -g_number_regex = re.compile('^(0x[0-9a-fA-F]+|[0-9]+)') -g_thread_id_regex = re.compile('^(-1|[0-9a-fA-F]+|0)') +# ---------------------------------------------------------------------- +g_log_file = "" +g_byte_order = "little" +g_number_regex = re.compile("^(0x[0-9a-fA-F]+|[0-9]+)") +g_thread_id_regex = re.compile("^(-1|[0-9a-fA-F]+|0)") class TerminalColors: - '''Simple terminal colors class''' + """Simple terminal colors class""" def __init__(self, enabled=True): # TODO: discover terminal type from "file" and disable if @@ -47,167 +47,176 @@ self.enabled = enabled def reset(self): - '''Reset all terminal colors and formatting.''' + """Reset all terminal colors and formatting.""" if self.enabled: return "\x1b[0m" - return '' + return "" def bold(self, on=True): - '''Enable or disable bold depending on the "on" parameter.''' + """Enable or disable bold depending on the "on" parameter.""" if self.enabled: if on: return "\x1b[1m" else: return "\x1b[22m" - return '' + return "" def italics(self, on=True): - '''Enable or disable italics depending on the "on" parameter.''' + """Enable or disable italics depending on the "on" parameter.""" if self.enabled: if on: return "\x1b[3m" else: return "\x1b[23m" - return '' + return "" def underline(self, on=True): - '''Enable or disable underline depending on the "on" parameter.''' + """Enable or disable underline depending on the "on" parameter.""" if self.enabled: if on: return "\x1b[4m" else: return "\x1b[24m" - return '' + return "" def inverse(self, on=True): - '''Enable or disable inverse depending on the "on" parameter.''' + """Enable or disable inverse depending on the "on" parameter.""" if self.enabled: if on: return "\x1b[7m" else: return "\x1b[27m" - return '' + return "" def strike(self, on=True): - '''Enable or disable strike through depending on the "on" parameter.''' + """Enable or disable strike through depending on the "on" parameter.""" if self.enabled: if on: return "\x1b[9m" else: return "\x1b[29m" - return '' + return "" def black(self, fg=True): - '''Set the foreground or background color to black. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to black. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[30m" else: return "\x1b[40m" - return '' + return "" def red(self, fg=True): - '''Set the foreground or background color to red. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to red. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[31m" else: return "\x1b[41m" - return '' + return "" def green(self, fg=True): - '''Set the foreground or background color to green. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to green. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[32m" else: return "\x1b[42m" - return '' + return "" def yellow(self, fg=True): - '''Set the foreground or background color to yellow. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to yellow. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[33m" else: return "\x1b[43m" - return '' + return "" def blue(self, fg=True): - '''Set the foreground or background color to blue. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to blue. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[34m" else: return "\x1b[44m" - return '' + return "" def magenta(self, fg=True): - '''Set the foreground or background color to magenta. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to magenta. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[35m" else: return "\x1b[45m" - return '' + return "" def cyan(self, fg=True): - '''Set the foreground or background color to cyan. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to cyan. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[36m" else: return "\x1b[46m" - return '' + return "" def white(self, fg=True): - '''Set the foreground or background color to white. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to white. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[37m" else: return "\x1b[47m" - return '' + return "" def default(self, fg=True): - '''Set the foreground or background color to the default. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to the default. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[39m" else: return "\x1b[49m" - return '' + return "" def start_gdb_log(debugger, command, result, dict): - '''Start logging GDB remote packets by enabling logging with timestamps and + """Start logging GDB remote packets by enabling logging with timestamps and thread safe logging. Follow a call to this function with a call to "stop_gdb_log" - in order to dump out the commands.''' + in order to dump out the commands.""" global g_log_file command_args = shlex.split(command) usage = "usage: start_gdb_log [options] []" - description = '''The command enables GDB remote packet logging with timestamps. The packets will be logged to if supplied, or a temporary file will be used. Logging stops when stop_gdb_log is called and the packet times will - be aggregated and displayed.''' + description = """The command enables GDB remote packet logging with timestamps. The packets will be logged to if supplied, or a temporary file will be used. Logging stops when stop_gdb_log is called and the packet times will + be aggregated and displayed.""" parser = optparse.OptionParser( - description=description, - prog='start_gdb_log', - usage=usage) + description=description, prog="start_gdb_log", usage=usage + ) parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', - help='display verbose debug info', - default=False) + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="display verbose debug info", + default=False, + ) try: (options, args) = parser.parse_args(command_args) except: @@ -215,8 +224,8 @@ if g_log_file: result.PutCString( - 'error: logging is already in progress with file "%s"' % - g_log_file) + 'error: logging is already in progress with file "%s"' % g_log_file + ) else: args_len = len(args) if args_len == 0: @@ -226,73 +235,80 @@ if g_log_file: debugger.HandleCommand( - 'log enable --threadsafe --timestamp --file "%s" gdb-remote packets' % - g_log_file) + 'log enable --threadsafe --timestamp --file "%s" gdb-remote packets' + % g_log_file + ) result.PutCString( - "GDB packet logging enable with log file '%s'\nUse the 'stop_gdb_log' command to stop logging and show packet statistics." % - g_log_file) + "GDB packet logging enable with log file '%s'\nUse the 'stop_gdb_log' command to stop logging and show packet statistics." + % g_log_file + ) return - result.PutCString('error: invalid log file path') + result.PutCString("error: invalid log file path") result.PutCString(usage) def stop_gdb_log(debugger, command, result, dict): - '''Stop logging GDB remote packets to the file that was specified in a call + """Stop logging GDB remote packets to the file that was specified in a call to "start_gdb_log" and normalize the timestamps to be relative to the first timestamp in the log file. Also print out statistics for how long each - command took to allow performance bottlenecks to be determined.''' + command took to allow performance bottlenecks to be determined.""" global g_log_file # Any commands whose names might be followed by more valid C identifier # characters must be listed here command_args = shlex.split(command) usage = "usage: stop_gdb_log [options]" - description = '''The command stops a previously enabled GDB remote packet logging command. Packet logging must have been previously enabled with a call to start_gdb_log.''' + description = """The command stops a previously enabled GDB remote packet logging command. Packet logging must have been previously enabled with a call to start_gdb_log.""" parser = optparse.OptionParser( - description=description, - prog='stop_gdb_log', - usage=usage) + description=description, prog="stop_gdb_log", usage=usage + ) parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', - help='display verbose debug info', - default=False) + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="display verbose debug info", + default=False, + ) parser.add_option( - '--plot', - action='store_true', - dest='plot', - help='plot packet latencies by packet type', - default=False) + "--plot", + action="store_true", + dest="plot", + help="plot packet latencies by packet type", + default=False, + ) parser.add_option( - '-q', - '--quiet', - action='store_true', - dest='quiet', - help='display verbose debug info', - default=False) + "-q", + "--quiet", + action="store_true", + dest="quiet", + help="display verbose debug info", + default=False, + ) parser.add_option( - '-C', - '--color', - action='store_true', - dest='color', - help='add terminal colors', - default=False) + "-C", + "--color", + action="store_true", + dest="color", + help="add terminal colors", + default=False, + ) parser.add_option( - '-c', - '--sort-by-count', - action='store_true', - dest='sort_count', - help='display verbose debug info', - default=False) + "-c", + "--sort-by-count", + action="store_true", + dest="sort_count", + help="display verbose debug info", + default=False, + ) parser.add_option( - '-s', - '--symbolicate', - action='store_true', - dest='symbolicate', + "-s", + "--symbolicate", + action="store_true", + dest="symbolicate", help='symbolicate addresses in log using current "lldb.target"', - default=False) + default=False, + ) try: (options, args) = parser.parse_args(command_args) except: @@ -302,6 +318,7 @@ if options.symbolicate: if lldb.target: import lldb.utils.symbolication + options.symbolicator = lldb.utils.symbolication.Symbolicator() options.symbolicator.target = lldb.target else: @@ -309,13 +326,14 @@ if not g_log_file: result.PutCString( - 'error: logging must have been previously enabled with a call to "stop_gdb_log"') + 'error: logging must have been previously enabled with a call to "stop_gdb_log"' + ) elif os.path.exists(g_log_file): if len(args) == 0: - debugger.HandleCommand('log disable gdb-remote packets') + debugger.HandleCommand("log disable gdb-remote packets") result.PutCString( - "GDB packet logging disabled. Logged packets are in '%s'" % - g_log_file) + "GDB packet logging disabled. Logged packets are in '%s'" % g_log_file + ) parse_gdb_log_file(g_log_file, options) else: result.PutCString(usage) @@ -328,6 +346,7 @@ return str[0] in string.hexdigits and str[1] in string.hexdigits return False + def get_hex_string_if_all_printable(str): try: s = binascii.unhexlify(str).decode() @@ -337,6 +356,7 @@ pass return None + # global register info list g_register_infos = list() g_max_register_info_name_len = 0 @@ -353,54 +373,54 @@ self.info[key] = value def name(self): - '''Get the name of the register.''' - if self.info and 'name' in self.info: - return self.info['name'] + """Get the name of the register.""" + if self.info and "name" in self.info: + return self.info["name"] return None def bit_size(self): - '''Get the size in bits of the register.''' - if self.info and 'bitsize' in self.info: - return int(self.info['bitsize']) + """Get the size in bits of the register.""" + if self.info and "bitsize" in self.info: + return int(self.info["bitsize"]) return 0 def byte_size(self): - '''Get the size in bytes of the register.''' + """Get the size in bytes of the register.""" return self.bit_size() / 8 def get_value_from_hex_string(self, hex_str): - '''Dump the register value given a native byte order encoded hex ASCII byte string.''' - encoding = self.info['encoding'] + """Dump the register value given a native byte order encoded hex ASCII byte string.""" + encoding = self.info["encoding"] bit_size = self.bit_size() packet = Packet(hex_str) - if encoding == 'uint': + if encoding == "uint": uval = packet.get_hex_uint(g_byte_order) if bit_size == 8: - return '0x%2.2x' % (uval) + return "0x%2.2x" % (uval) elif bit_size == 16: - return '0x%4.4x' % (uval) + return "0x%4.4x" % (uval) elif bit_size == 32: - return '0x%8.8x' % (uval) + return "0x%8.8x" % (uval) elif bit_size == 64: - return '0x%16.16x' % (uval) + return "0x%16.16x" % (uval) bytes = list() uval = packet.get_hex_uint8() while uval is not None: bytes.append(uval) uval = packet.get_hex_uint8() - value_str = '0x' - if g_byte_order == 'little': + value_str = "0x" + if g_byte_order == "little": bytes.reverse() for byte in bytes: - value_str += '%2.2x' % byte - return '%s' % (value_str) + value_str += "%2.2x" % byte + return "%s" % (value_str) def __str__(self): - '''Dump the register info key/value pairs''' - s = '' + """Dump the register info key/value pairs""" + s = "" for key in self.info.keys(): if s: - s += ', ' + s += ", " s += "%s=%s " % (key, self.info[key]) return s @@ -426,7 +446,7 @@ def skip_exact_string(self, s): if self.str and self.str.startswith(s): - self.str = self.str[len(s):] + self.str = self.str[len(s) :] return True else: return False @@ -435,14 +455,18 @@ match = g_number_regex.match(self.str) if match: number_str = match.group(1) - self.str = self.str[len(number_str):] + self.str = self.str[len(number_str) :] return int(number_str, 0) else: return fail_value def get_hex_uint8(self): - if self.str and len(self.str) >= 2 and self.str[ - 0] in string.hexdigits and self.str[1] in string.hexdigits: + if ( + self.str + and len(self.str) >= 2 + and self.str[0] in string.hexdigits + and self.str[1] in string.hexdigits + ): uval = int(self.str[0:2], 16) self.str = self.str[2:] return uval @@ -450,7 +474,7 @@ def get_hex_uint16(self, byte_order): uval = 0 - if byte_order == 'big': + if byte_order == "big": uval |= self.get_hex_uint8() << 8 uval |= self.get_hex_uint8() else: @@ -460,7 +484,7 @@ def get_hex_uint32(self, byte_order): uval = 0 - if byte_order == 'big': + if byte_order == "big": uval |= self.get_hex_uint8() << 24 uval |= self.get_hex_uint8() << 16 uval |= self.get_hex_uint8() << 8 @@ -474,7 +498,7 @@ def get_hex_uint64(self, byte_order): uval = 0 - if byte_order == 'big': + if byte_order == "big": uval |= self.get_hex_uint8() << 56 uval |= self.get_hex_uint8() << 48 uval |= self.get_hex_uint8() << 40 @@ -495,13 +519,13 @@ return uval def get_number(self, fail_value=-1): - '''Get a number from the packet. The number must be in big endian format and should be parsed + """Get a number from the packet. The number must be in big endian format and should be parsed according to its prefix (starts with "0x" means hex, starts with "0" means octal, starts with - [1-9] means decimal, etc)''' + [1-9] means decimal, etc)""" match = g_number_regex.match(self.str) if match: number_str = match.group(1) - self.str = self.str[len(number_str):] + self.str = self.str[len(number_str) :] return int(number_str, 0) else: return fail_value @@ -534,7 +558,7 @@ return hex_str def get_hex_uint(self, byte_order, n=0): - if byte_order == 'big': + if byte_order == "big": hex_str = self.get_hex_chars(n) if hex_str is None: return None @@ -546,18 +570,18 @@ uval_result = 0 shift = 0 while uval is not None: - uval_result |= (uval << shift) + uval_result |= uval << shift shift += 8 uval = self.get_hex_uint8() return uval_result def get_key_value_pairs(self): kvp = list() - if ';' in self.str: - key_value_pairs = self.str.split(';') + if ";" in self.str: + key_value_pairs = self.str.split(";") for key_value_pair in key_value_pairs: if len(key_value_pair): - kvp.append(key_value_pair.split(':', 1)) + kvp.append(key_value_pair.split(":", 1)) return kvp def split(self, ch): @@ -576,7 +600,8 @@ def __len__(self): return len(self.str) -g_thread_suffix_regex = re.compile(';thread:([0-9a-fA-F]+);') + +g_thread_suffix_regex = re.compile(";thread:([0-9a-fA-F]+);") def get_thread_from_thread_suffix(str): @@ -589,7 +614,7 @@ def cmd_qThreadStopInfo(options, cmd, args): packet = Packet(args) - tid = packet.get_hex_uint('big') + tid = packet.get_hex_uint("big") print("get_thread_stop_info (tid = 0x%x)" % (tid)) @@ -602,7 +627,7 @@ global g_byte_order packet = Packet(rsp) stop_type = packet.get_char() - if stop_type == 'T' or stop_type == 'S': + if stop_type == "T" or stop_type == "S": signo = packet.get_hex_uint8() key_value_pairs = packet.get_key_value_pairs() for key_value_pair in key_value_pairs: @@ -613,16 +638,17 @@ reg_info = g_register_infos[reg_num] key_value_pair[0] = reg_info.name() key_value_pair[1] = reg_info.get_value_from_hex_string( - key_value_pair[1]) - elif key == 'jthreads' or key == 'jstopinfo': + key_value_pair[1] + ) + elif key == "jthreads" or key == "jstopinfo": key_value_pair[1] = binascii.unhexlify(key_value_pair[1]) - key_value_pairs.insert(0, ['signal', signo]) - print('stop_reply():') + key_value_pairs.insert(0, ["signal", signo]) + print("stop_reply():") dump_key_value_pairs(key_value_pairs) - elif stop_type == 'W': + elif stop_type == "W": exit_status = packet.get_hex_uint8() - print('stop_reply(): exit (status=%i)' % exit_status) - elif stop_type == 'O': + print("stop_reply(): exit (status=%i)" % exit_status) + elif stop_type == "O": print('stop_reply(): stdout = "%s"' % packet.str) @@ -635,32 +661,36 @@ def cmd_qSymbol(options, cmd, args): - if args == ':': - print('ready to serve symbols') + if args == ":": + print("ready to serve symbols") else: packet = Packet(args) - symbol_addr = packet.get_hex_uint('big') + symbol_addr = packet.get_hex_uint("big") if symbol_addr is None: - if packet.skip_exact_string(':'): + if packet.skip_exact_string(":"): symbol_name = packet.get_hex_ascii_str() print('lookup_symbol("%s") -> symbol not available yet' % (symbol_name)) else: - print('error: bad command format') + print("error: bad command format") else: - if packet.skip_exact_string(':'): + if packet.skip_exact_string(":"): symbol_name = packet.get_hex_ascii_str() print('lookup_symbol("%s") -> 0x%x' % (symbol_name, symbol_addr)) else: - print('error: bad command format') + print("error: bad command format") + def cmd_QSetWithHexString(options, cmd, args): print('%s("%s")' % (cmd[:-1], binascii.unhexlify(args))) + def cmd_QSetWithString(options, cmd, args): print('%s("%s")' % (cmd[:-1], args)) + def cmd_QSetWithUnsigned(options, cmd, args): - print('%s(%i)' % (cmd[:-1], int(args))) + print("%s(%i)" % (cmd[:-1], int(args))) + def rsp_qSymbol(options, cmd, cmd_args, rsp): if len(rsp) == 0: @@ -674,7 +704,10 @@ symbol_name = packet.get_hex_ascii_str() print('lookup_symbol("%s")' % (symbol_name)) else: - print('error: response string should start with "qSymbol:": respnse is "%s"' % (rsp)) + print( + 'error: response string should start with "qSymbol:": respnse is "%s"' + % (rsp) + ) def cmd_qXfer(options, cmd, args): @@ -684,55 +717,57 @@ def rsp_qXfer(options, cmd, cmd_args, rsp): - data = cmd_args.split(':') - if data[0] == 'features': - if data[1] == 'read': + data = cmd_args.split(":") + if data[0] == "features": + if data[1] == "read": filename, extension = os.path.splitext(data[2]) - if extension == '.xml': + if extension == ".xml": response = Packet(rsp) xml_string = response.get_hex_ascii_str() if xml_string: ch = xml_string[0] - if ch == 'l': + if ch == "l": xml_string = xml_string[1:] xml_root = ET.fromstring(xml_string) for reg_element in xml_root.findall("./feature/reg"): - if not 'value_regnums' in reg_element.attrib: + if not "value_regnums" in reg_element.attrib: reg_info = RegisterInfo([]) - if 'name' in reg_element.attrib: - reg_info.info[ - 'name'] = reg_element.attrib['name'] + if "name" in reg_element.attrib: + reg_info.info["name"] = reg_element.attrib["name"] else: - reg_info.info['name'] = 'unspecified' - if 'encoding' in reg_element.attrib: - reg_info.info['encoding'] = reg_element.attrib[ - 'encoding'] + reg_info.info["name"] = "unspecified" + if "encoding" in reg_element.attrib: + reg_info.info["encoding"] = reg_element.attrib[ + "encoding" + ] else: - reg_info.info['encoding'] = 'uint' - if 'offset' in reg_element.attrib: - reg_info.info[ - 'offset'] = reg_element.attrib['offset'] - if 'bitsize' in reg_element.attrib: - reg_info.info[ - 'bitsize'] = reg_element.attrib['bitsize'] + reg_info.info["encoding"] = "uint" + if "offset" in reg_element.attrib: + reg_info.info["offset"] = reg_element.attrib[ + "offset" + ] + if "bitsize" in reg_element.attrib: + reg_info.info["bitsize"] = reg_element.attrib[ + "bitsize" + ] g_register_infos.append(reg_info) print('XML for "%s":' % (data[2])) ET.dump(xml_root) def cmd_A(options, cmd, args): - print('launch process:') + print("launch process:") packet = Packet(args) while True: arg_len = packet.get_number() if arg_len == -1: break - if not packet.skip_exact_string(','): + if not packet.skip_exact_string(","): break arg_idx = packet.get_number() if arg_idx == -1: break - if not packet.skip_exact_string(','): + if not packet.skip_exact_string(","): break arg_value = packet.get_hex_ascii_str(arg_len) print('argv[%u] = "%s"' % (arg_idx, arg_value)) @@ -764,18 +799,18 @@ def rsp_ok_means_supported(options, cmd, cmd_args, rsp): - if rsp == 'OK': + if rsp == "OK": print("%s%s is supported" % (cmd, cmd_args)) - elif rsp == '': + elif rsp == "": print("%s%s is not supported" % (cmd, cmd_args)) else: print("%s%s -> %s" % (cmd, cmd_args, rsp)) def rsp_ok_means_success(options, cmd, cmd_args, rsp): - if rsp == 'OK': + if rsp == "OK": print("success") - elif rsp == '': + elif rsp == "": print("%s%s is not supported" % (cmd, cmd_args)) else: print("%s%s -> %s" % (cmd, cmd_args, rsp)) @@ -799,7 +834,7 @@ def rsp_dump_key_value_pairs(options, cmd, cmd_args, rsp): if rsp: - print('%s response:' % (cmd)) + print("%s response:" % (cmd)) packet = Packet(rsp) key_value_pairs = packet.get_key_value_pairs() dump_key_value_pairs(key_value_pairs) @@ -826,31 +861,31 @@ def cmd_vCont(options, cmd, args): - if args == '?': + if args == "?": print("%s: get supported extended continue modes" % (cmd)) else: got_other_threads = 0 - s = '' - for thread_action in args[1:].split(';'): - (short_action, thread) = thread_action.split(':', 1) + s = "" + for thread_action in args[1:].split(";"): + (short_action, thread) = thread_action.split(":", 1) tid = int(thread, 16) - if short_action == 'c': - action = 'continue' - elif short_action == 's': - action = 'step' - elif short_action[0] == 'C': - action = 'continue with signal 0x%s' % (short_action[1:]) - elif short_action == 'S': - action = 'step with signal 0x%s' % (short_action[1:]) + if short_action == "c": + action = "continue" + elif short_action == "s": + action = "step" + elif short_action[0] == "C": + action = "continue with signal 0x%s" % (short_action[1:]) + elif short_action == "S": + action = "step with signal 0x%s" % (short_action[1:]) else: action = short_action if s: - s += ', ' + s += ", " if tid == -1: got_other_threads = 1 - s += 'other-threads:' + s += "other-threads:" else: - s += 'thread 0x%4.4x: %s' % (tid, action) + s += "thread 0x%4.4x: %s" % (tid, action) if got_other_threads: print("extended_continue (%s)" % (s)) else: @@ -859,41 +894,43 @@ def rsp_vCont(options, cmd, cmd_args, rsp): - if cmd_args == '?': + if cmd_args == "?": # Skip the leading 'vCont;' rsp = rsp[6:] - modes = rsp.split(';') + modes = rsp.split(";") s = "%s: supported extended continue modes include: " % (cmd) for i, mode in enumerate(modes): if i: - s += ', ' - if mode == 'c': - s += 'continue' - elif mode == 'C': - s += 'continue with signal' - elif mode == 's': - s += 'step' - elif mode == 'S': - s += 'step with signal' - elif mode == 't': - s += 'stop' + s += ", " + if mode == "c": + s += "continue" + elif mode == "C": + s += "continue with signal" + elif mode == "s": + s += "step" + elif mode == "S": + s += "step with signal" + elif mode == "t": + s += "stop" # else: # s += 'unrecognized vCont mode: ', str(mode) print(s) elif rsp: - if rsp[0] == 'T' or rsp[0] == 'S' or rsp[0] == 'W' or rsp[0] == 'X': + if rsp[0] == "T" or rsp[0] == "S" or rsp[0] == "W" or rsp[0] == "X": rsp_stop_reply(options, cmd, cmd_args, rsp) return - if rsp[0] == 'O': + if rsp[0] == "O": print("stdout: %s" % (rsp)) return else: - print("not supported (cmd = '%s', args = '%s', rsp = '%s')" % (cmd, cmd_args, rsp)) + print( + "not supported (cmd = '%s', args = '%s', rsp = '%s')" % (cmd, cmd_args, rsp) + ) def cmd_vAttach(options, cmd, args): - (extra_command, args) = args.split(';') + (extra_command, args) = args.split(";") if extra_command: print("%s%s(%s)" % (cmd, extra_command, args)) else: @@ -902,20 +939,20 @@ def cmd_qRegisterInfo(options, cmd, args): - print('query_register_info(reg_num=%i)' % (int(args, 16))) + print("query_register_info(reg_num=%i)" % (int(args, 16))) return False def rsp_qRegisterInfo(options, cmd, cmd_args, rsp): global g_max_register_info_name_len - print('query_register_info(reg_num=%i):' % (int(cmd_args, 16)), end=' ') - if len(rsp) == 3 and rsp[0] == 'E': + print("query_register_info(reg_num=%i):" % (int(cmd_args, 16)), end=" ") + if len(rsp) == 3 and rsp[0] == "E": g_max_register_info_name_len = 0 for reg_info in g_register_infos: name_len = len(reg_info.name()) if g_max_register_info_name_len < name_len: g_max_register_info_name_len = name_len - print(' DONE') + print(" DONE") else: packet = Packet(rsp) reg_info = RegisterInfo(packet.get_key_value_pairs()) @@ -925,132 +962,135 @@ def cmd_qThreadInfo(options, cmd, args): - if cmd == 'qfThreadInfo': - query_type = 'first' + if cmd == "qfThreadInfo": + query_type = "first" else: - query_type = 'subsequent' - print('get_current_thread_list(type=%s)' % (query_type)) + query_type = "subsequent" + print("get_current_thread_list(type=%s)" % (query_type)) return False def rsp_qThreadInfo(options, cmd, cmd_args, rsp): packet = Packet(rsp) response_type = packet.get_char() - if response_type == 'm': - tids = packet.split_hex(';', 'big') + if response_type == "m": + tids = packet.split_hex(";", "big") for i, tid in enumerate(tids): if i: - print(',', end=' ') - print('0x%x' % (tid), end=' ') + print(",", end=" ") + print("0x%x" % (tid), end=" ") print() - elif response_type == 'l': - print('END') + elif response_type == "l": + print("END") def rsp_hex_big_endian(options, cmd, cmd_args, rsp): - if rsp == '': + if rsp == "": print("%s%s is not supported" % (cmd, cmd_args)) else: packet = Packet(rsp) - uval = packet.get_hex_uint('big') - print('%s: 0x%x' % (cmd, uval)) + uval = packet.get_hex_uint("big") + print("%s: 0x%x" % (cmd, uval)) def cmd_read_mem_bin(options, cmd, args): # x0x7fff5fc39200,0x200 packet = Packet(args) - addr = packet.get_hex_uint('big') + addr = packet.get_hex_uint("big") comma = packet.get_char() - size = packet.get_hex_uint('big') - print('binary_read_memory (addr = 0x%16.16x, size = %u)' % (addr, size)) + size = packet.get_hex_uint("big") + print("binary_read_memory (addr = 0x%16.16x, size = %u)" % (addr, size)) return False def rsp_mem_bin_bytes(options, cmd, cmd_args, rsp): packet = Packet(cmd_args) - addr = packet.get_hex_uint('big') + addr = packet.get_hex_uint("big") comma = packet.get_char() - size = packet.get_hex_uint('big') - print('memory:') + size = packet.get_hex_uint("big") + print("memory:") if size > 0: dump_hex_memory_buffer(addr, rsp) def cmd_read_memory(options, cmd, args): packet = Packet(args) - addr = packet.get_hex_uint('big') + addr = packet.get_hex_uint("big") comma = packet.get_char() - size = packet.get_hex_uint('big') - print('read_memory (addr = 0x%16.16x, size = %u)' % (addr, size)) + size = packet.get_hex_uint("big") + print("read_memory (addr = 0x%16.16x, size = %u)" % (addr, size)) return False def dump_hex_memory_buffer(addr, hex_byte_str): packet = Packet(hex_byte_str) idx = 0 - ascii = '' + ascii = "" uval = packet.get_hex_uint8() while uval is not None: - if ((idx % 16) == 0): + if (idx % 16) == 0: if ascii: - print(' ', ascii) - ascii = '' - print('0x%x:' % (addr + idx), end=' ') - print('%2.2x' % (uval), end=' ') - if 0x20 <= uval and uval < 0x7f: - ascii += '%c' % uval + print(" ", ascii) + ascii = "" + print("0x%x:" % (addr + idx), end=" ") + print("%2.2x" % (uval), end=" ") + if 0x20 <= uval and uval < 0x7F: + ascii += "%c" % uval else: - ascii += '.' + ascii += "." uval = packet.get_hex_uint8() idx = idx + 1 if ascii: - print(' ', ascii) - ascii = '' + print(" ", ascii) + ascii = "" def cmd_write_memory(options, cmd, args): packet = Packet(args) - addr = packet.get_hex_uint('big') - if packet.get_char() != ',': - print('error: invalid write memory command (missing comma after address)') + addr = packet.get_hex_uint("big") + if packet.get_char() != ",": + print("error: invalid write memory command (missing comma after address)") return - size = packet.get_hex_uint('big') - if packet.get_char() != ':': - print('error: invalid write memory command (missing colon after size)') + size = packet.get_hex_uint("big") + if packet.get_char() != ":": + print("error: invalid write memory command (missing colon after size)") return - print('write_memory (addr = 0x%16.16x, size = %u, data:' % (addr, size)) + print("write_memory (addr = 0x%16.16x, size = %u, data:" % (addr, size)) dump_hex_memory_buffer(addr, packet.str) return False def cmd_alloc_memory(options, cmd, args): packet = Packet(args) - byte_size = packet.get_hex_uint('big') - if packet.get_char() != ',': - print('error: invalid allocate memory command (missing comma after address)') + byte_size = packet.get_hex_uint("big") + if packet.get_char() != ",": + print("error: invalid allocate memory command (missing comma after address)") return - print('allocate_memory (byte-size = %u (0x%x), permissions = %s)' % (byte_size, byte_size, packet.str)) + print( + "allocate_memory (byte-size = %u (0x%x), permissions = %s)" + % (byte_size, byte_size, packet.str) + ) return False def rsp_alloc_memory(options, cmd, cmd_args, rsp): packet = Packet(rsp) - addr = packet.get_hex_uint('big') - print('addr = 0x%x' % addr) + addr = packet.get_hex_uint("big") + print("addr = 0x%x" % addr) def cmd_dealloc_memory(options, cmd, args): packet = Packet(args) - addr = packet.get_hex_uint('big') - if packet.get_char() != ',': - print('error: invalid allocate memory command (missing comma after address)') + addr = packet.get_hex_uint("big") + if packet.get_char() != ",": + print("error: invalid allocate memory command (missing comma after address)") else: - print('deallocate_memory (addr = 0x%x, permissions = %s)' % (addr, packet.str)) + print("deallocate_memory (addr = 0x%x, permissions = %s)" % (addr, packet.str)) return False def rsp_memory_bytes(options, cmd, cmd_args, rsp): - addr = Packet(cmd_args).get_hex_uint('big') + addr = Packet(cmd_args).get_hex_uint("big") dump_hex_memory_buffer(addr, rsp) @@ -1058,25 +1098,24 @@ if reg_num < len(g_register_infos): reg_info = g_register_infos[reg_num] value_str = reg_info.get_value_from_hex_string(hex_value_str) - s = reg_info.name() + ' = ' + s = reg_info.name() + " = " if options.symbolicator: - symbolicated_addresses = options.symbolicator.symbolicate( - int(value_str, 0)) + symbolicated_addresses = options.symbolicator.symbolicate(int(value_str, 0)) if symbolicated_addresses: s += options.colors.magenta() - s += '%s' % symbolicated_addresses[0] + s += "%s" % symbolicated_addresses[0] s += options.colors.reset() return s s += value_str return s else: reg_value = Packet(hex_value_str).get_hex_uint(g_byte_order) - return 'reg(%u) = 0x%x' % (reg_num, reg_value) + return "reg(%u) = 0x%x" % (reg_num, reg_value) def cmd_read_one_reg(options, cmd, args): packet = Packet(args) - reg_num = packet.get_hex_uint('big') + reg_num = packet.get_hex_uint("big") tid = get_thread_from_thread_suffix(packet.str) name = None if reg_num < len(g_register_infos): @@ -1085,39 +1124,39 @@ packet.get_char() # skip ; thread_info = packet.get_key_value_pairs() tid = int(thread_info[0][1], 16) - s = 'read_register (reg_num=%u' % reg_num + s = "read_register (reg_num=%u" % reg_num if name: - s += ' (%s)' % (name) + s += " (%s)" % (name) if tid is not None: - s += ', tid = 0x%4.4x' % (tid) - s += ')' + s += ", tid = 0x%4.4x" % (tid) + s += ")" print(s) return False def rsp_read_one_reg(options, cmd, cmd_args, rsp): packet = Packet(cmd_args) - reg_num = packet.get_hex_uint('big') + reg_num = packet.get_hex_uint("big") print(get_register_name_equal_value(options, reg_num, rsp)) def cmd_write_one_reg(options, cmd, args): packet = Packet(args) - reg_num = packet.get_hex_uint('big') - if packet.get_char() != '=': - print('error: invalid register write packet') + reg_num = packet.get_hex_uint("big") + if packet.get_char() != "=": + print("error: invalid register write packet") else: name = None hex_value_str = packet.get_hex_chars() tid = get_thread_from_thread_suffix(packet.str) - s = 'write_register (reg_num=%u' % reg_num + s = "write_register (reg_num=%u" % reg_num if name: - s += ' (%s)' % (name) - s += ', value = ' + s += " (%s)" % (name) + s += ", value = " s += get_register_name_equal_value(options, reg_num, hex_value_str) if tid is not None: - s += ', tid = 0x%4.4x' % (tid) - s += ')' + s += ", tid = 0x%4.4x" % (tid) + s += ")" print(s) return False @@ -1128,7 +1167,7 @@ hex_value_str = packet.get_hex_chars(nibble_size) if hex_value_str is not None: value = reg_info.get_value_from_hex_string(hex_value_str) - print('%*s = %s' % (g_max_register_info_name_len, reg_info.name(), value)) + print("%*s = %s" % (g_max_register_info_name_len, reg_info.name(), value)) else: return @@ -1138,9 +1177,9 @@ packet.get_char() # toss the 'g' command character tid = get_thread_from_thread_suffix(packet.str) if tid is not None: - print('read_all_register(thread = 0x%4.4x)' % tid) + print("read_all_register(thread = 0x%4.4x)" % tid) else: - print('read_all_register()') + print("read_all_register()") return False @@ -1151,24 +1190,25 @@ def cmd_write_all_regs(options, cmd, args): packet = Packet(args) - print('write_all_registers()') + print("write_all_registers()") dump_all_regs(packet) return False + g_bp_types = ["software_bp", "hardware_bp", "write_wp", "read_wp", "access_wp"] def cmd_bp(options, cmd, args): - if cmd == 'Z': - s = 'set_' + if cmd == "Z": + s = "set_" else: - s = 'clear_' + s = "clear_" packet = Packet(args) - bp_type = packet.get_hex_uint('big') + bp_type = packet.get_hex_uint("big") packet.get_char() # Skip , - bp_addr = packet.get_hex_uint('big') + bp_addr = packet.get_hex_uint("big") packet.get_char() # Skip , - bp_size = packet.get_hex_uint('big') + bp_size = packet.get_hex_uint("big") s += g_bp_types[bp_type] s += " (addr = 0x%x, size = %u)" % (bp_addr, bp_size) print(s) @@ -1178,29 +1218,29 @@ def cmd_mem_rgn_info(options, cmd, args): packet = Packet(args) packet.get_char() # skip ':' character - addr = packet.get_hex_uint('big') - print('get_memory_region_info (addr=0x%x)' % (addr)) + addr = packet.get_hex_uint("big") + print("get_memory_region_info (addr=0x%x)" % (addr)) return False def cmd_kill(options, cmd, args): - print('kill_process()') + print("kill_process()") return False def cmd_jThreadsInfo(options, cmd, args): - print('jThreadsInfo()') + print("jThreadsInfo()") return False def cmd_jGetLoadedDynamicLibrariesInfos(options, cmd, args): - print('jGetLoadedDynamicLibrariesInfos()') + print("jGetLoadedDynamicLibrariesInfos()") return False def decode_packet(s, start_index=0): # print '\ndecode_packet("%s")' % (s[start_index:]) - index = s.find('}', start_index) + index = s.find("}", start_index) have_escapes = index != -1 if have_escapes: normal_s = s[start_index:index] @@ -1208,7 +1248,7 @@ normal_s = s[start_index:] # print 'normal_s = "%s"' % (normal_s) if have_escapes: - escape_char = '%c' % (ord(s[index + 1]) ^ 0x20) + escape_char = "%c" % (ord(s[index + 1]) ^ 0x20) # print 'escape_char for "%s" = %c' % (s[index:index+2], escape_char) return normal_s + escape_char + decode_packet(s, index + 2) else: @@ -1216,69 +1256,207 @@ def rsp_json(options, cmd, cmd_args, rsp): - print('%s() reply:' % (cmd)) + print("%s() reply:" % (cmd)) if not rsp: return try: json_tree = json.loads(rsp) - print(json.dumps(json_tree, indent=4, separators=(',', ': '))) + print(json.dumps(json_tree, indent=4, separators=(",", ": "))) except json.JSONDecodeError: return + def rsp_jGetLoadedDynamicLibrariesInfos(options, cmd, cmd_args, rsp): if cmd_args: rsp_json(options, cmd, cmd_args, rsp) else: rsp_ok_means_supported(options, cmd, cmd_args, rsp) + gdb_remote_commands = { - '\\?': {'cmd': cmd_stop_reply, 'rsp': rsp_stop_reply, 'name': "stop reply pacpket"}, - 'qThreadStopInfo': {'cmd': cmd_qThreadStopInfo, 'rsp': rsp_stop_reply, 'name': "stop reply pacpket"}, - 'QStartNoAckMode': {'cmd': cmd_query_packet, 'rsp': rsp_ok_means_supported, 'name': "query if no ack mode is supported"}, - 'QThreadSuffixSupported': {'cmd': cmd_query_packet, 'rsp': rsp_ok_means_supported, 'name': "query if thread suffix is supported"}, - 'QListThreadsInStopReply': {'cmd': cmd_query_packet, 'rsp': rsp_ok_means_supported, 'name': "query if threads in stop reply packets are supported"}, - 'QSetDetachOnError:': {'cmd': cmd_QSetWithUnsigned, 'rsp': rsp_ok_means_success, 'name': "set if we should detach on error"}, - 'QSetDisableASLR:': {'cmd': cmd_QSetWithUnsigned, 'rsp': rsp_ok_means_success, 'name': "set if we should disable ASLR"}, - 'qLaunchSuccess': {'cmd': cmd_query_packet, 'rsp': rsp_ok_means_success, 'name': "check on launch success for the A packet"}, - 'A': {'cmd': cmd_A, 'rsp': rsp_ok_means_success, 'name': "launch process"}, - 'QLaunchArch:': {'cmd': cmd_QSetWithString, 'rsp': rsp_ok_means_supported, 'name': "set the arch to launch in case the file contains multiple architectures"}, - 'qVAttachOrWaitSupported': {'cmd': cmd_query_packet, 'rsp': rsp_ok_means_supported, 'name': "set the launch architecture"}, - 'qHostInfo': {'cmd': cmd_query_packet, 'rsp': rsp_dump_key_value_pairs, 'name': "get host information"}, - 'qC': {'cmd': cmd_qC, 'rsp': rsp_qC, 'name': "return the current thread ID"}, - 'vCont': {'cmd': cmd_vCont, 'rsp': rsp_vCont, 'name': "extended continue command"}, - 'qSpeedTest': {'cmd':cmd_qSpeedTest, 'rsp': rsp_qSpeedTest, 'name': 'speed test packdet'}, - 'vAttach': {'cmd': cmd_vAttach, 'rsp': rsp_stop_reply, 'name': "attach to process"}, - 'c': {'cmd': cmd_c, 'rsp': rsp_stop_reply, 'name': "continue"}, - 's': {'cmd': cmd_s, 'rsp': rsp_stop_reply, 'name': "step"}, - 'qRegisterInfo': {'cmd': cmd_qRegisterInfo, 'rsp': rsp_qRegisterInfo, 'name': "query register info"}, - 'qfThreadInfo': {'cmd': cmd_qThreadInfo, 'rsp': rsp_qThreadInfo, 'name': "get current thread list"}, - 'qsThreadInfo': {'cmd': cmd_qThreadInfo, 'rsp': rsp_qThreadInfo, 'name': "get current thread list"}, - 'qShlibInfoAddr': {'cmd': cmd_query_packet, 'rsp': rsp_hex_big_endian, 'name': "get shared library info address"}, - 'qMemoryRegionInfo': {'cmd': cmd_mem_rgn_info, 'rsp': rsp_dump_key_value_pairs, 'name': "get memory region information"}, - 'qProcessInfo': {'cmd': cmd_query_packet, 'rsp': rsp_dump_key_value_pairs, 'name': "get process info"}, - 'qSupported': {'cmd': cmd_query_packet, 'rsp': rsp_ok_means_supported, 'name': "query supported"}, - 'qXfer:': {'cmd': cmd_qXfer, 'rsp': rsp_qXfer, 'name': "qXfer"}, - 'qSymbol:': {'cmd': cmd_qSymbol, 'rsp': rsp_qSymbol, 'name': "qSymbol"}, - 'QSetSTDIN:' : {'cmd' : cmd_QSetWithHexString, 'rsp' : rsp_ok_means_success, 'name': "set STDIN prior to launching with A packet"}, - 'QSetSTDOUT:' : {'cmd' : cmd_QSetWithHexString, 'rsp' : rsp_ok_means_success, 'name': "set STDOUT prior to launching with A packet"}, - 'QSetSTDERR:' : {'cmd' : cmd_QSetWithHexString, 'rsp' : rsp_ok_means_success, 'name': "set STDERR prior to launching with A packet"}, - 'QEnvironment:' : {'cmd' : cmd_QSetWithString, 'rsp' : rsp_ok_means_success, 'name': "set an environment variable prior to launching with A packet"}, - 'QEnvironmentHexEncoded:' : {'cmd' : cmd_QSetWithHexString, 'rsp' : rsp_ok_means_success, 'name': "set an environment variable prior to launching with A packet"}, - 'x': {'cmd': cmd_read_mem_bin, 'rsp': rsp_mem_bin_bytes, 'name': "read memory binary"}, - 'X': {'cmd': cmd_write_memory, 'rsp': rsp_ok_means_success, 'name': "write memory binary"}, - 'm': {'cmd': cmd_read_memory, 'rsp': rsp_memory_bytes, 'name': "read memory"}, - 'M': {'cmd': cmd_write_memory, 'rsp': rsp_ok_means_success, 'name': "write memory"}, - '_M': {'cmd': cmd_alloc_memory, 'rsp': rsp_alloc_memory, 'name': "allocate memory"}, - '_m': {'cmd': cmd_dealloc_memory, 'rsp': rsp_ok_means_success, 'name': "deallocate memory"}, - 'p': {'cmd': cmd_read_one_reg, 'rsp': rsp_read_one_reg, 'name': "read single register"}, - 'P': {'cmd': cmd_write_one_reg, 'rsp': rsp_ok_means_success, 'name': "write single register"}, - 'g': {'cmd': cmd_read_all_regs, 'rsp': rsp_read_all_regs, 'name': "read all registers"}, - 'G': {'cmd': cmd_write_all_regs, 'rsp': rsp_ok_means_success, 'name': "write all registers"}, - 'z': {'cmd': cmd_bp, 'rsp': rsp_ok_means_success, 'name': "clear breakpoint or watchpoint"}, - 'Z': {'cmd': cmd_bp, 'rsp': rsp_ok_means_success, 'name': "set breakpoint or watchpoint"}, - 'k': {'cmd': cmd_kill, 'rsp': rsp_stop_reply, 'name': "kill process"}, - 'jThreadsInfo': {'cmd': cmd_jThreadsInfo, 'rsp': rsp_json, 'name': "JSON get all threads info"}, - 'jGetLoadedDynamicLibrariesInfos:': {'cmd': cmd_jGetLoadedDynamicLibrariesInfos, 'rsp': rsp_jGetLoadedDynamicLibrariesInfos, 'name': 'JSON get loaded dynamic libraries'}, + "\\?": {"cmd": cmd_stop_reply, "rsp": rsp_stop_reply, "name": "stop reply pacpket"}, + "qThreadStopInfo": { + "cmd": cmd_qThreadStopInfo, + "rsp": rsp_stop_reply, + "name": "stop reply pacpket", + }, + "QStartNoAckMode": { + "cmd": cmd_query_packet, + "rsp": rsp_ok_means_supported, + "name": "query if no ack mode is supported", + }, + "QThreadSuffixSupported": { + "cmd": cmd_query_packet, + "rsp": rsp_ok_means_supported, + "name": "query if thread suffix is supported", + }, + "QListThreadsInStopReply": { + "cmd": cmd_query_packet, + "rsp": rsp_ok_means_supported, + "name": "query if threads in stop reply packets are supported", + }, + "QSetDetachOnError:": { + "cmd": cmd_QSetWithUnsigned, + "rsp": rsp_ok_means_success, + "name": "set if we should detach on error", + }, + "QSetDisableASLR:": { + "cmd": cmd_QSetWithUnsigned, + "rsp": rsp_ok_means_success, + "name": "set if we should disable ASLR", + }, + "qLaunchSuccess": { + "cmd": cmd_query_packet, + "rsp": rsp_ok_means_success, + "name": "check on launch success for the A packet", + }, + "A": {"cmd": cmd_A, "rsp": rsp_ok_means_success, "name": "launch process"}, + "QLaunchArch:": { + "cmd": cmd_QSetWithString, + "rsp": rsp_ok_means_supported, + "name": "set the arch to launch in case the file contains multiple architectures", + }, + "qVAttachOrWaitSupported": { + "cmd": cmd_query_packet, + "rsp": rsp_ok_means_supported, + "name": "set the launch architecture", + }, + "qHostInfo": { + "cmd": cmd_query_packet, + "rsp": rsp_dump_key_value_pairs, + "name": "get host information", + }, + "qC": {"cmd": cmd_qC, "rsp": rsp_qC, "name": "return the current thread ID"}, + "vCont": {"cmd": cmd_vCont, "rsp": rsp_vCont, "name": "extended continue command"}, + "qSpeedTest": { + "cmd": cmd_qSpeedTest, + "rsp": rsp_qSpeedTest, + "name": "speed test packdet", + }, + "vAttach": {"cmd": cmd_vAttach, "rsp": rsp_stop_reply, "name": "attach to process"}, + "c": {"cmd": cmd_c, "rsp": rsp_stop_reply, "name": "continue"}, + "s": {"cmd": cmd_s, "rsp": rsp_stop_reply, "name": "step"}, + "qRegisterInfo": { + "cmd": cmd_qRegisterInfo, + "rsp": rsp_qRegisterInfo, + "name": "query register info", + }, + "qfThreadInfo": { + "cmd": cmd_qThreadInfo, + "rsp": rsp_qThreadInfo, + "name": "get current thread list", + }, + "qsThreadInfo": { + "cmd": cmd_qThreadInfo, + "rsp": rsp_qThreadInfo, + "name": "get current thread list", + }, + "qShlibInfoAddr": { + "cmd": cmd_query_packet, + "rsp": rsp_hex_big_endian, + "name": "get shared library info address", + }, + "qMemoryRegionInfo": { + "cmd": cmd_mem_rgn_info, + "rsp": rsp_dump_key_value_pairs, + "name": "get memory region information", + }, + "qProcessInfo": { + "cmd": cmd_query_packet, + "rsp": rsp_dump_key_value_pairs, + "name": "get process info", + }, + "qSupported": { + "cmd": cmd_query_packet, + "rsp": rsp_ok_means_supported, + "name": "query supported", + }, + "qXfer:": {"cmd": cmd_qXfer, "rsp": rsp_qXfer, "name": "qXfer"}, + "qSymbol:": {"cmd": cmd_qSymbol, "rsp": rsp_qSymbol, "name": "qSymbol"}, + "QSetSTDIN:": { + "cmd": cmd_QSetWithHexString, + "rsp": rsp_ok_means_success, + "name": "set STDIN prior to launching with A packet", + }, + "QSetSTDOUT:": { + "cmd": cmd_QSetWithHexString, + "rsp": rsp_ok_means_success, + "name": "set STDOUT prior to launching with A packet", + }, + "QSetSTDERR:": { + "cmd": cmd_QSetWithHexString, + "rsp": rsp_ok_means_success, + "name": "set STDERR prior to launching with A packet", + }, + "QEnvironment:": { + "cmd": cmd_QSetWithString, + "rsp": rsp_ok_means_success, + "name": "set an environment variable prior to launching with A packet", + }, + "QEnvironmentHexEncoded:": { + "cmd": cmd_QSetWithHexString, + "rsp": rsp_ok_means_success, + "name": "set an environment variable prior to launching with A packet", + }, + "x": { + "cmd": cmd_read_mem_bin, + "rsp": rsp_mem_bin_bytes, + "name": "read memory binary", + }, + "X": { + "cmd": cmd_write_memory, + "rsp": rsp_ok_means_success, + "name": "write memory binary", + }, + "m": {"cmd": cmd_read_memory, "rsp": rsp_memory_bytes, "name": "read memory"}, + "M": {"cmd": cmd_write_memory, "rsp": rsp_ok_means_success, "name": "write memory"}, + "_M": {"cmd": cmd_alloc_memory, "rsp": rsp_alloc_memory, "name": "allocate memory"}, + "_m": { + "cmd": cmd_dealloc_memory, + "rsp": rsp_ok_means_success, + "name": "deallocate memory", + }, + "p": { + "cmd": cmd_read_one_reg, + "rsp": rsp_read_one_reg, + "name": "read single register", + }, + "P": { + "cmd": cmd_write_one_reg, + "rsp": rsp_ok_means_success, + "name": "write single register", + }, + "g": { + "cmd": cmd_read_all_regs, + "rsp": rsp_read_all_regs, + "name": "read all registers", + }, + "G": { + "cmd": cmd_write_all_regs, + "rsp": rsp_ok_means_success, + "name": "write all registers", + }, + "z": { + "cmd": cmd_bp, + "rsp": rsp_ok_means_success, + "name": "clear breakpoint or watchpoint", + }, + "Z": { + "cmd": cmd_bp, + "rsp": rsp_ok_means_success, + "name": "set breakpoint or watchpoint", + }, + "k": {"cmd": cmd_kill, "rsp": rsp_stop_reply, "name": "kill process"}, + "jThreadsInfo": { + "cmd": cmd_jThreadsInfo, + "rsp": rsp_json, + "name": "JSON get all threads info", + }, + "jGetLoadedDynamicLibrariesInfos:": { + "cmd": cmd_jGetLoadedDynamicLibrariesInfos, + "rsp": rsp_jGetLoadedDynamicLibrariesInfos, + "name": "JSON get loaded dynamic libraries", + }, } @@ -1313,14 +1491,14 @@ # import numpy as np import matplotlib.pyplot as plt - for (i, name) in enumerate(sec_times.keys()): + for i, name in enumerate(sec_times.keys()): times = sec_times[name] if len(times) <= 1: continue plt.subplot(2, 1, 1) plt.title('Packet "%s" Times' % (name)) - plt.xlabel('Packet') - units = 'ms' + plt.xlabel("Packet") + units = "ms" adj_times = [] max_time = 0.0 for time in times: @@ -1329,13 +1507,13 @@ if time > max_time: max_time = time if max_time < 1.0: - units = 'us' + units = "us" max_time = 0.0 for i in range(len(adj_times)): adj_times[i] *= 1000.0 if adj_times[i] > max_time: max_time = adj_times[i] - plt.ylabel('Time (%s)' % (units)) + plt.ylabel("Time (%s)" % (units)) max_y = None for i in [5.0, 10.0, 25.0, 50.0]: if max_time < i: @@ -1344,29 +1522,29 @@ if max_y is None: max_y = round_up(max_time, 100.0) plt.ylim(0.0, max_y) - plt.plot(adj_times, 'o-') + plt.plot(adj_times, "o-") plt.show() def parse_gdb_log(file, options): - '''Parse a GDB log file that was generated by enabling logging with: + """Parse a GDB log file that was generated by enabling logging with: (lldb) log enable --threadsafe --timestamp --file gdb-remote packets This log file will contain timestamps and this function will then normalize those packets to be relative to the first value timestamp that is found and show delta times between log lines and also keep track of how long it takes for GDB remote commands to make a send/receive round trip. This can be handy when trying to figure out why some operation in the debugger is taking - a long time during a preset set of debugger commands.''' + a long time during a preset set of debugger commands.""" - tricky_commands = ['qRegisterInfo'] - timestamp_regex = re.compile('(\s*)([1-9][0-9]+\.[0-9]+)([^0-9].*)$') - packet_name_regex = re.compile('([A-Za-z_]+)[^a-z]') + tricky_commands = ["qRegisterInfo"] + timestamp_regex = re.compile("(\s*)([1-9][0-9]+\.[0-9]+)([^0-9].*)$") + packet_name_regex = re.compile("([A-Za-z_]+)[^a-z]") packet_transmit_name_regex = re.compile( - '(?Psend|read) packet: (?P.*)') - packet_contents_name_regex = re.compile('\$([^#]*)#[0-9a-fA-F]{2}') - packet_checksum_regex = re.compile('.*#[0-9a-fA-F]{2}$') - packet_names_regex_str = '(' + \ - '|'.join(gdb_remote_commands.keys()) + ')(.*)' + "(?Psend|read) packet: (?P.*)" + ) + packet_contents_name_regex = re.compile("\$([^#]*)#[0-9a-fA-F]{2}") + packet_checksum_regex = re.compile(".*#[0-9a-fA-F]{2}$") + packet_names_regex_str = "(" + "|".join(gdb_remote_commands.keys()) + ")(.*)" packet_names_regex = re.compile(packet_names_regex_str) base_time = 0.0 @@ -1383,7 +1561,7 @@ hide_next_response = False num_lines = len(lines) skip_count = 0 - for (line_index, line) in enumerate(lines): + for line_index, line in enumerate(lines): # See if we need to skip any lines if skip_count > 0: skip_count -= 1 @@ -1392,40 +1570,40 @@ is_command = False direction = None if m: - direction = m.group('direction') - is_command = direction == 'send' - packet = m.group('packet') + direction = m.group("direction") + is_command = direction == "send" + packet = m.group("packet") sys.stdout.write(options.colors.green()) if not options.quiet and not hide_next_response: - print('# ', line) + print("# ", line) sys.stdout.write(options.colors.reset()) # print 'direction = "%s", packet = "%s"' % (direction, packet) - if packet[0] == '+': + if packet[0] == "+": if is_command: - print('-->', end=' ') + print("-->", end=" ") else: - print('<--', end=' ') + print("<--", end=" ") if not options.quiet: - print('ACK') + print("ACK") continue - elif packet[0] == '-': + elif packet[0] == "-": if is_command: - print('-->', end=' ') + print("-->", end=" ") else: - print('<--', end=' ') + print("<--", end=" ") if not options.quiet: - print('NACK') + print("NACK") continue - elif packet[0] == '$': + elif packet[0] == "$": m = packet_contents_name_regex.match(packet) - if not m and packet[0] == '$': + if not m and packet[0] == "$": multiline_packet = packet idx = line_index + 1 while idx < num_lines: if not options.quiet and not hide_next_response: - print('# ', lines[idx]) + print("# ", lines[idx]) multiline_packet += lines[idx] m = packet_contents_name_regex.match(multiline_packet) if m: @@ -1436,22 +1614,23 @@ idx += 1 if m: if is_command: - print('-->', end=' ') + print("-->", end=" ") else: - print('<--', end=' ') + print("<--", end=" ") contents = decode_packet(m.group(1)) if is_command: hide_next_response = False m = packet_names_regex.match(contents) if m: last_command = m.group(1) - if last_command == '?': - last_command = '\\?' + if last_command == "?": + last_command = "\\?" packet_name = last_command last_command_args = m.group(2) last_command_packet = contents hide_next_response = gdb_remote_commands[last_command][ - 'cmd'](options, last_command, last_command_args) + "cmd" + ](options, last_command, last_command_args) else: packet_match = packet_name_regex.match(contents) if packet_match: @@ -1465,14 +1644,15 @@ last_command_args = None last_command_packet = None elif last_command: - gdb_remote_commands[last_command]['rsp']( - options, last_command, last_command_args, contents) + gdb_remote_commands[last_command]["rsp"]( + options, last_command, last_command_args, contents + ) else: print('error: invalid packet: "', packet, '"') else: - print('???') + print("???") else: - print('## ', line) + print("## ", line) match = timestamp_regex.match(line) if match: curr_time = float(match.group(2)) @@ -1486,7 +1666,7 @@ base_time = curr_time if not is_command: - if line.find('read packet: $') >= 0 and packet_name: + if line.find("read packet: $") >= 0 and packet_name: if packet_name in packet_total_times: packet_total_times[packet_name] += delta packet_counts[packet_name] += 1 @@ -1501,16 +1681,19 @@ min_time = delta if not options or not options.quiet: - print('%s%.6f %+.6f%s' % (match.group(1), - curr_time - base_time, - delta, - match.group(3))) + print( + "%s%.6f %+.6f%s" + % (match.group(1), curr_time - base_time, delta, match.group(3)) + ) last_time = curr_time # else: # print line (average, std_dev) = calculate_mean_and_standard_deviation(all_packet_times) if average and std_dev: - print('%u packets with average packet time of %f and standard deviation of %f' % (len(all_packet_times), average, std_dev)) + print( + "%u packets with average packet time of %f and standard deviation of %f" + % (len(all_packet_times), average, std_dev) + ) if packet_total_times: total_packet_time = 0.0 total_packet_count = 0 @@ -1522,111 +1705,131 @@ for key, vvv in packet_counts.items(): total_packet_count += vvv - print('#------------------------------------------------------------') - print('# Packet timing summary:') - print('# Totals: time = %6f, count = %6d' % (total_packet_time, - total_packet_count)) - print('# Min packet time: time = %6f' % (min_time)) - print('#------------------------------------------------------------') - print('# Packet Time (sec) Percent Count Latency') - print('#------------------------- ----------- ------- ------ -------') + print("#------------------------------------------------------------") + print("# Packet timing summary:") + print( + "# Totals: time = %6f, count = %6d" + % (total_packet_time, total_packet_count) + ) + print("# Min packet time: time = %6f" % (min_time)) + print("#------------------------------------------------------------") + print("# Packet Time (sec) Percent Count Latency") + print("#------------------------- ----------- ------- ------ -------") if options and options.sort_count: - res = sorted( - packet_counts, - key=packet_counts.__getitem__, - reverse=True) + res = sorted(packet_counts, key=packet_counts.__getitem__, reverse=True) else: res = sorted( - packet_total_times, - key=packet_total_times.__getitem__, - reverse=True) + packet_total_times, key=packet_total_times.__getitem__, reverse=True + ) if last_time > 0.0: for item in res: packet_total_time = packet_total_times[item] - packet_percent = ( - packet_total_time / total_packet_time) * 100.0 + packet_percent = (packet_total_time / total_packet_time) * 100.0 packet_count = packet_counts[item] - print(" %24s %11.6f %5.2f%% %6d %9.6f" % ( - item, packet_total_time, packet_percent, packet_count, - float(packet_total_time) / float(packet_count))) + print( + " %24s %11.6f %5.2f%% %6d %9.6f" + % ( + item, + packet_total_time, + packet_percent, + packet_count, + float(packet_total_time) / float(packet_count), + ) + ) if options and options.plot: plot_latencies(packet_times) -if __name__ == '__main__': + +if __name__ == "__main__": usage = "usage: gdbremote [options]" - description = '''The command disassembles a GDB remote packet log.''' + description = """The command disassembles a GDB remote packet log.""" parser = optparse.OptionParser( - description=description, - prog='gdbremote', - usage=usage) + description=description, prog="gdbremote", usage=usage + ) parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', - help='display verbose debug info', - default=False) + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="display verbose debug info", + default=False, + ) parser.add_option( - '-q', - '--quiet', - action='store_true', - dest='quiet', - help='display verbose debug info', - default=False) + "-q", + "--quiet", + action="store_true", + dest="quiet", + help="display verbose debug info", + default=False, + ) parser.add_option( - '-C', - '--color', - action='store_true', - dest='color', - help='add terminal colors', - default=False) + "-C", + "--color", + action="store_true", + dest="color", + help="add terminal colors", + default=False, + ) parser.add_option( - '-c', - '--sort-by-count', - action='store_true', - dest='sort_count', - help='display verbose debug info', - default=False) + "-c", + "--sort-by-count", + action="store_true", + dest="sort_count", + help="display verbose debug info", + default=False, + ) parser.add_option( - '--crashlog', - type='string', - dest='crashlog', - help='symbolicate using a darwin crash log file', - default=False) + "--crashlog", + type="string", + dest="crashlog", + help="symbolicate using a darwin crash log file", + default=False, + ) try: (options, args) = parser.parse_args(sys.argv[1:]) except: - print('error: argument error') + print("error: argument error") sys.exit(1) options.colors = TerminalColors(options.color) options.symbolicator = None if options.crashlog: import lldb + lldb.debugger = lldb.SBDebugger.Create() import lldb.macosx.crashlog + options.symbolicator = lldb.macosx.crashlog.CrashLog(options.crashlog) - print('%s' % (options.symbolicator)) + print("%s" % (options.symbolicator)) # This script is being run from the command line, create a debugger in case we are # going to use any debugger functions in our function. if len(args): for file in args: - print('#----------------------------------------------------------------------') + print( + "#----------------------------------------------------------------------" + ) print("# GDB remote log file: '%s'" % file) - print('#----------------------------------------------------------------------') + print( + "#----------------------------------------------------------------------" + ) parse_gdb_log_file(file, options) if options.symbolicator: - print('%s' % (options.symbolicator)) + print("%s" % (options.symbolicator)) else: parse_gdb_log(sys.stdin, options) + def __lldb_init_module(debugger, internal_dict): # This initializer is being run from LLDB in the embedded command interpreter # Add any commands contained in this module to LLDB debugger.HandleCommand( - 'command script add -o -f gdbremote.start_gdb_log start_gdb_log') + "command script add -o -f gdbremote.start_gdb_log start_gdb_log" + ) debugger.HandleCommand( - 'command script add -o -f gdbremote.stop_gdb_log stop_gdb_log') - print('The "start_gdb_log" and "stop_gdb_log" commands are now installed and ready for use, type "start_gdb_log --help" or "stop_gdb_log --help" for more information') + "command script add -o -f gdbremote.stop_gdb_log stop_gdb_log" + ) + print( + 'The "start_gdb_log" and "stop_gdb_log" commands are now installed and ready for use, type "start_gdb_log --help" or "stop_gdb_log --help" for more information' + ) diff --git a/lldb/examples/python/globals.py b/lldb/examples/python/globals.py --- a/lldb/examples/python/globals.py +++ b/lldb/examples/python/globals.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # For the shells csh, tcsh: # ( setenv PYTHONPATH /Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python ; ./globals.py [ ...]) # # For the shells sh, bash: # PYTHONPATH=/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python ./globals.py [ ...] -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- import lldb import optparse @@ -21,7 +21,8 @@ path = os.path.expanduser(raw_path) # Create a target using path + options target = lldb.debugger.CreateTarget( - path, options.arch, options.platform, False, error) + path, options.arch, options.platform, False, error + ) if target: # Get the executable module module = target.module[target.executable.basename] @@ -40,58 +41,63 @@ global_names.append(global_name) # Find all global variables by name global_variable_list = module.FindGlobalVariables( - target, global_name, lldb.UINT32_MAX) + target, global_name, lldb.UINT32_MAX + ) if global_variable_list: # Print results for anything that matched for global_variable in global_variable_list: # returns the global variable name as a string - print('name = %s' % global_variable.name) + print("name = %s" % global_variable.name) # Returns the variable value as a string - print('value = %s' % global_variable.value) - print('type = %s' % global_variable.type) # Returns an lldb.SBType object + print("value = %s" % global_variable.value) + print( + "type = %s" % global_variable.type + ) # Returns an lldb.SBType object # Returns an lldb.SBAddress (section offset # address) for this global - print('addr = %s' % global_variable.addr) + print("addr = %s" % global_variable.addr) # Returns the file virtual address for this # global - print('file_addr = 0x%x' % global_variable.addr.file_addr) + print( + "file_addr = 0x%x" % global_variable.addr.file_addr + ) # returns the global variable value as a string - print('location = %s' % global_variable.location) + print("location = %s" % global_variable.location) # Returns the size in bytes of this global # variable - print('size = %s' % global_variable.size) + print("size = %s" % global_variable.size) print() def globals(command_args): - '''Extract all globals from any arguments which must be paths to object files.''' + """Extract all globals from any arguments which must be paths to object files.""" usage = "usage: %prog [options] [PATH ...]" - description = '''This command will find all globals in the specified object file and return an list() of lldb.SBValue objects (which might be empty).''' - parser = optparse.OptionParser( - description=description, - prog='globals', - usage=usage) + description = """This command will find all globals in the specified object file and return an list() of lldb.SBValue objects (which might be empty).""" + parser = optparse.OptionParser(description=description, prog="globals", usage=usage) parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', - help='display verbose debug info', - default=False) + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="display verbose debug info", + default=False, + ) parser.add_option( - '-a', - '--arch', - type='string', - metavar='arch', - dest='arch', - help='Specify an architecture (or triple) to use when extracting from a file.') + "-a", + "--arch", + type="string", + metavar="arch", + dest="arch", + help="Specify an architecture (or triple) to use when extracting from a file.", + ) parser.add_option( - '-p', - '--platform', - type='string', - metavar='platform', - dest='platform', - help='Specify the platform to use when creating the debug target. Valid values include "localhost", "darwin-kernel", "ios-simulator", "remote-freebsd", "remote-macosx", "remote-ios", "remote-linux".') + "-p", + "--platform", + type="string", + metavar="platform", + dest="platform", + help='Specify the platform to use when creating the debug target. Valid values include "localhost", "darwin-kernel", "ios-simulator", "remote-freebsd", "remote-macosx", "remote-ios", "remote-linux".', + ) try: (options, args) = parser.parse_args(command_args) except: @@ -100,6 +106,7 @@ for path in args: get_globals(path, options) -if __name__ == '__main__': + +if __name__ == "__main__": lldb.debugger = lldb.SBDebugger.Create() globals(sys.argv[1:]) diff --git a/lldb/examples/python/in_call_stack.py b/lldb/examples/python/in_call_stack.py --- a/lldb/examples/python/in_call_stack.py +++ b/lldb/examples/python/in_call_stack.py @@ -2,23 +2,23 @@ def __lldb_init_module(debugger, internal_dict): - debugger.HandleCommand( - f'command alias in_call_stack breakpoint command add --python-function {__name__}.in_call_stack -k name -v %1' - ) + debugger.HandleCommand( + f"command alias in_call_stack breakpoint command add --python-function {__name__}.in_call_stack -k name -v %1" + ) def in_call_stack(frame, bp_loc, arg_dict, _): - """Only break if the given name is in the current call stack.""" - name = arg_dict.GetValueForKey('name').GetStringValue(1000) - thread = frame.GetThread() - found = False - for frame in thread.frames: - # Check the symbol. - symbol = frame.GetSymbol() - if symbol and name in frame.GetSymbol().GetName(): - return True - # Check the function. - function = frame.GetFunction() - if function and name in function.GetName(): - return True - return False + """Only break if the given name is in the current call stack.""" + name = arg_dict.GetValueForKey("name").GetStringValue(1000) + thread = frame.GetThread() + found = False + for frame in thread.frames: + # Check the symbol. + symbol = frame.GetSymbol() + if symbol and name in frame.GetSymbol().GetName(): + return True + # Check the function. + function = frame.GetFunction() + if function and name in function.GetName(): + return True + return False diff --git a/lldb/examples/python/jump.py b/lldb/examples/python/jump.py --- a/lldb/examples/python/jump.py +++ b/lldb/examples/python/jump.py @@ -5,91 +5,97 @@ def parse_linespec(linespec, frame, result): """Handles a subset of GDB-style linespecs. Specifically: - number - A line in the current file - +offset - The line /offset/ lines after this line - -offset - The line /offset/ lines before this line - filename:number - Line /number/ in file /filename/ - function - The start of /function/ - *address - The pointer target of /address/, which must be a literal (but see `` in LLDB) + number - A line in the current file + +offset - The line /offset/ lines after this line + -offset - The line /offset/ lines before this line + filename:number - Line /number/ in file /filename/ + function - The start of /function/ + *address - The pointer target of /address/, which must be a literal (but see `` in LLDB) - We explicitly do not handle filename:function because it is ambiguous in Objective-C. + We explicitly do not handle filename:function because it is ambiguous in Objective-C. - This function returns a list of addresses.""" + This function returns a list of addresses.""" breakpoint = None target = frame.GetThread().GetProcess().GetTarget() matched = False - if (not matched): + if not matched: mo = re.match("^([0-9]+)$", linespec) - if (mo is not None): + if mo is not None: matched = True # print "Matched " line_number = int(mo.group(1)) line_entry = frame.GetLineEntry() if not line_entry.IsValid(): result.AppendMessage( - "Specified a line in the current file, but the current frame doesn't have line table information.") + "Specified a line in the current file, but the current frame doesn't have line table information." + ) return breakpoint = target.BreakpointCreateByLocation( - line_entry.GetFileSpec(), line_number) + line_entry.GetFileSpec(), line_number + ) - if (not matched): + if not matched: mo = re.match("^\+([0-9]+)$", linespec) - if (mo is not None): + if mo is not None: matched = True # print "Matched +" line_number = int(mo.group(1)) line_entry = frame.GetLineEntry() if not line_entry.IsValid(): result.AppendMessage( - "Specified a line in the current file, but the current frame doesn't have line table information.") + "Specified a line in the current file, but the current frame doesn't have line table information." + ) return breakpoint = target.BreakpointCreateByLocation( - line_entry.GetFileSpec(), (line_entry.GetLine() + line_number)) + line_entry.GetFileSpec(), (line_entry.GetLine() + line_number) + ) - if (not matched): + if not matched: mo = re.match("^\-([0-9]+)$", linespec) - if (mo is not None): + if mo is not None: matched = True # print "Matched -" line_number = int(mo.group(1)) line_entry = frame.GetLineEntry() if not line_entry.IsValid(): result.AppendMessage( - "Specified a line in the current file, but the current frame doesn't have line table information.") + "Specified a line in the current file, but the current frame doesn't have line table information." + ) return breakpoint = target.BreakpointCreateByLocation( - line_entry.GetFileSpec(), (line_entry.GetLine() - line_number)) + line_entry.GetFileSpec(), (line_entry.GetLine() - line_number) + ) - if (not matched): + if not matched: mo = re.match("^(.*):([0-9]+)$", linespec) - if (mo is not None): + if mo is not None: matched = True # print "Matched :" file_name = mo.group(1) line_number = int(mo.group(2)) - breakpoint = target.BreakpointCreateByLocation( - file_name, line_number) + breakpoint = target.BreakpointCreateByLocation(file_name, line_number) - if (not matched): + if not matched: mo = re.match("\*((0x)?([0-9a-f]+))$", linespec) - if (mo is not None): + if mo is not None: matched = True # print "Matched " address = int(mo.group(1), base=0) breakpoint = target.BreakpointCreateByAddress(address) - if (not matched): + if not matched: # print "Trying " breakpoint = target.BreakpointCreateByName(linespec) num_locations = breakpoint.GetNumLocations() - if (num_locations == 0): + if num_locations == 0: result.AppendMessage( - "The line specification provided doesn't resolve to any addresses.") + "The line specification provided doesn't resolve to any addresses." + ) addr_list = [] @@ -119,7 +125,7 @@ def jump(debugger, command, result, internal_dict): - if (command == ""): + if command == "": result.AppendMessage(usage_string()) args = command.split() @@ -164,33 +170,31 @@ desired_address = addresses[desired_index] else: result.AppendMessage( - "Desired index " + - args[1] + - " is not one of the options.") + "Desired index " + args[1] + " is not one of the options." + ) return else: index = 0 - result.AppendMessage( - "The specified location resolves to multiple targets.") + result.AppendMessage("The specified location resolves to multiple targets.") for address in addresses: stream.Clear() address.GetDescription(stream) result.AppendMessage( - " Location ID " + - str(index) + - ": " + - stream.GetData()) + " Location ID " + str(index) + ": " + stream.GetData() + ) index = index + 1 result.AppendMessage( - "Please type 'jump " + - command + - " ' to choose one.") + "Please type 'jump " + command + " ' to choose one." + ) return frame.SetPC(desired_address.GetLoadAddress(target)) + def __lldb_init_module(debugger, internal_dict): # Module is being run inside the LLDB interpreter jump.__doc__ = usage_string() - debugger.HandleCommand('command script add -o -f jump.jump jump') - print('The "jump" command has been installed, type "help jump" or "jump " for detailed help.') + debugger.HandleCommand("command script add -o -f jump.jump jump") + print( + 'The "jump" command has been installed, type "help jump" or "jump " for detailed help.' + ) diff --git a/lldb/examples/python/lldb_module_utils.py b/lldb/examples/python/lldb_module_utils.py --- a/lldb/examples/python/lldb_module_utils.py +++ b/lldb/examples/python/lldb_module_utils.py @@ -9,22 +9,25 @@ class DumpLineTables: command_name = "dump-line-tables" - short_description = "Dumps full paths to compile unit files and optionally all line table files." - description = 'Dumps all line tables from all compile units for any modules specified as arguments. Specifying the --verbose flag will output address ranges for each line entry.' + short_description = ( + "Dumps full paths to compile unit files and optionally all line table files." + ) + description = "Dumps all line tables from all compile units for any modules specified as arguments. Specifying the --verbose flag will output address ranges for each line entry." usage = "usage: %prog [options] MODULE1 [MODULE2 ...]" + def create_options(self): self.parser = optparse.OptionParser( - description=self.description, - prog=self.command_name, - usage=self.usage) + description=self.description, prog=self.command_name, usage=self.usage + ) self.parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', - help='Display verbose output.', - default=False) + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="Display verbose output.", + default=False, + ) def get_short_help(self): return self.short_description @@ -61,14 +64,14 @@ result.SetError('no module found that matches "%s".' % (module_path)) return num_cus = module.GetNumCompileUnits() - print('Module: "%s"' % (module.file.fullpath), end=' ', file=result) + print('Module: "%s"' % (module.file.fullpath), end=" ", file=result) if num_cus == 0: - print('no debug info.', file=result) + print("no debug info.", file=result) continue - print('has %u compile units:' % (num_cus), file=result) + print("has %u compile units:" % (num_cus), file=result) for cu_idx in range(num_cus): cu = module.GetCompileUnitAtIndex(cu_idx) - print(' Compile Unit: %s' % (cu.file.fullpath), file=result) + print(" Compile Unit: %s" % (cu.file.fullpath), file=result) for line_idx in range(cu.GetNumLineEntries()): line_entry = cu.GetLineEntryAtIndex(line_idx) start_file_addr = line_entry.addr.file_addr @@ -78,25 +81,27 @@ if options.verbose: if start_file_addr != end_file_addr: result.PutCString( - ' [%#x - %#x): %s' % - (start_file_addr, end_file_addr, line_entry)) + " [%#x - %#x): %s" + % (start_file_addr, end_file_addr, line_entry) + ) else: if start_file_addr == end_file_addr: - result.PutCString(' %#x: END' % - (start_file_addr)) + result.PutCString(" %#x: END" % (start_file_addr)) else: result.PutCString( - ' %#x: %s' % - (start_file_addr, line_entry)) + " %#x: %s" % (start_file_addr, line_entry) + ) if start_file_addr == end_file_addr: result.PutCString("\n") class DumpFiles: command_name = "dump-files" - short_description = "Dumps full paths to compile unit files and optionally all line table files." + short_description = ( + "Dumps full paths to compile unit files and optionally all line table files." + ) usage = "usage: %prog [options] MODULE1 [MODULE2 ...]" - description = '''This class adds a dump-files command to the LLDB interpreter. + description = """This class adds a dump-files command to the LLDB interpreter. This command will dump all compile unit file paths found for each source file for the binaries specified as arguments in the current target. Specify the @@ -106,23 +111,26 @@ line breakpoints. Sometimes symlinks cause the debug info to contain the symlink path and an IDE will resolve the path to the actual file and use the resolved path when setting breakpoints. -''' +""" + def create_options(self): # Pass add_help_option = False, since this keeps the command in line with lldb commands, # and we wire up "help command" to work by providing the long & short help methods below. self.parser = optparse.OptionParser( - description = self.description, - prog = self.command_name, - usage = self.usage, - add_help_option = False) + description=self.description, + prog=self.command_name, + usage=self.usage, + add_help_option=False, + ) self.parser.add_option( - '-s', - '--support-files', - action = 'store_true', - dest = 'support_files', - help = 'Dumps full paths to all files used in a compile unit.', - default = False) + "-s", + "--support-files", + action="store_true", + dest="support_files", + help="Dumps full paths to all files used in a compile unit.", + default=False, + ) def get_short_help(self): return self.short_description @@ -163,19 +171,19 @@ result.SetError('no module found that matches "%s".' % (module_path)) return num_cus = module.GetNumCompileUnits() - print('Module: "%s"' % (module.file.fullpath), end=' ', file=result) + print('Module: "%s"' % (module.file.fullpath), end=" ", file=result) if num_cus == 0: - print('no debug info.', file=result) + print("no debug info.", file=result) continue - print('has %u compile units:' % (num_cus), file=result) + print("has %u compile units:" % (num_cus), file=result) for i in range(num_cus): cu = module.GetCompileUnitAtIndex(i) - print(' Compile Unit: %s' % (cu.file.fullpath), file=result) + print(" Compile Unit: %s" % (cu.file.fullpath), file=result) if options.support_files: num_support_files = cu.GetNumSupportFiles() for j in range(num_support_files): path = cu.GetSupportFileAtIndex(j).fullpath - print(' file[%u]: %s' % (j, path), file=result) + print(" file[%u]: %s" % (j, path), file=result) def __lldb_init_module(debugger, dict): @@ -183,9 +191,13 @@ # Add any commands contained in this module to LLDB debugger.HandleCommand( - 'command script add -o -c %s.DumpLineTables %s' % (__name__, - DumpLineTables.command_name)) + "command script add -o -c %s.DumpLineTables %s" + % (__name__, DumpLineTables.command_name) + ) debugger.HandleCommand( - 'command script add -o -c %s.DumpFiles %s' % (__name__, DumpFiles.command_name)) - print('The "%s" and "%s" commands have been installed.' % (DumpLineTables.command_name, - DumpFiles.command_name)) + "command script add -o -c %s.DumpFiles %s" % (__name__, DumpFiles.command_name) + ) + print( + 'The "%s" and "%s" commands have been installed.' + % (DumpLineTables.command_name, DumpFiles.command_name) + ) diff --git a/lldb/examples/python/lldbtk.py b/lldb/examples/python/lldbtk.py --- a/lldb/examples/python/lldbtk.py +++ b/lldb/examples/python/lldbtk.py @@ -3,6 +3,7 @@ import lldb import shlex import sys + try: from tkinter import * import tkinter.ttk as ttk @@ -12,62 +13,58 @@ class ValueTreeItemDelegate(object): - def __init__(self, value): self.value = value def get_item_dictionary(self): name = self.value.name if name is None: - name = '' + name = "" typename = self.value.type if typename is None: - typename = '' + typename = "" value = self.value.value if value is None: - value = '' + value = "" summary = self.value.summary if summary is None: - summary = '' + summary = "" has_children = self.value.MightHaveChildren() - return {'#0': name, - 'typename': typename, - 'value': value, - 'summary': summary, - 'children': has_children, - 'tree-item-delegate': self} + return { + "#0": name, + "typename": typename, + "value": value, + "summary": summary, + "children": has_children, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() for i in range(self.value.num_children): - item_delegate = ValueTreeItemDelegate( - self.value.GetChildAtIndex(i)) + item_delegate = ValueTreeItemDelegate(self.value.GetChildAtIndex(i)) item_dicts.append(item_delegate.get_item_dictionary()) return item_dicts class FrameTreeItemDelegate(object): - def __init__(self, frame): self.frame = frame def get_item_dictionary(self): id = self.frame.GetFrameID() - name = 'frame #%u' % (id) - value = '0x%16.16x' % (self.frame.GetPC()) + name = "frame #%u" % (id) + value = "0x%16.16x" % (self.frame.GetPC()) stream = lldb.SBStream() self.frame.GetDescription(stream) summary = stream.GetData().split("`")[1] return { - '#0': name, - 'value': value, - 'summary': summary, - 'children': self.frame.GetVariables( - True, - True, - True, - True).GetSize() > 0, - 'tree-item-delegate': self} + "#0": name, + "value": value, + "summary": summary, + "children": self.frame.GetVariables(True, True, True, True).GetSize() > 0, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() @@ -80,20 +77,21 @@ class ThreadTreeItemDelegate(object): - def __init__(self, thread): self.thread = thread def get_item_dictionary(self): num_frames = self.thread.GetNumFrames() - name = 'thread #%u' % (self.thread.GetIndexID()) - value = '0x%x' % (self.thread.GetThreadID()) - summary = '%u frames' % (num_frames) - return {'#0': name, - 'value': value, - 'summary': summary, - 'children': num_frames > 0, - 'tree-item-delegate': self} + name = "thread #%u" % (self.thread.GetIndexID()) + value = "0x%x" % (self.thread.GetThreadID()) + summary = "%u frames" % (num_frames) + return { + "#0": name, + "value": value, + "summary": summary, + "children": num_frames > 0, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() @@ -104,7 +102,6 @@ class ProcessTreeItemDelegate(object): - def __init__(self, process): self.process = process @@ -113,11 +110,13 @@ num_threads = self.process.GetNumThreads() value = str(self.process.GetProcessID()) summary = self.process.target.executable.fullpath - return {'#0': 'process', - 'value': value, - 'summary': summary, - 'children': num_threads > 0, - 'tree-item-delegate': self} + return { + "#0": "process", + "value": value, + "summary": summary, + "children": num_threads > 0, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() @@ -128,18 +127,19 @@ class TargetTreeItemDelegate(object): - def __init__(self, target): self.target = target def get_item_dictionary(self): value = str(self.target.triple) summary = self.target.executable.fullpath - return {'#0': 'target', - 'value': value, - 'summary': summary, - 'children': True, - 'tree-item-delegate': self} + return { + "#0": "target", + "value": value, + "summary": summary, + "children": True, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() @@ -149,7 +149,6 @@ class TargetImagesTreeItemDelegate(object): - def __init__(self, target): self.target = target @@ -157,70 +156,74 @@ value = str(self.target.triple) summary = self.target.executable.fullpath num_modules = self.target.GetNumModules() - return {'#0': 'images', - 'value': '', - 'summary': '%u images' % num_modules, - 'children': num_modules > 0, - 'tree-item-delegate': self} + return { + "#0": "images", + "value": "", + "summary": "%u images" % num_modules, + "children": num_modules > 0, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() for i in range(self.target.GetNumModules()): module = self.target.GetModuleAtIndex(i) - image_item_delegate = ModuleTreeItemDelegate( - self.target, module, i) + image_item_delegate = ModuleTreeItemDelegate(self.target, module, i) item_dicts.append(image_item_delegate.get_item_dictionary()) return item_dicts class ModuleTreeItemDelegate(object): - def __init__(self, target, module, index): self.target = target self.module = module self.index = index def get_item_dictionary(self): - name = 'module %u' % (self.index) + name = "module %u" % (self.index) value = self.module.file.basename summary = self.module.file.dirname - return {'#0': name, - 'value': value, - 'summary': summary, - 'children': True, - 'tree-item-delegate': self} + return { + "#0": name, + "value": value, + "summary": summary, + "children": True, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() sections_item_delegate = ModuleSectionsTreeItemDelegate( - self.target, self.module) + self.target, self.module + ) item_dicts.append(sections_item_delegate.get_item_dictionary()) - symbols_item_delegate = ModuleSymbolsTreeItemDelegate( - self.target, self.module) + symbols_item_delegate = ModuleSymbolsTreeItemDelegate(self.target, self.module) item_dicts.append(symbols_item_delegate.get_item_dictionary()) comp_units_item_delegate = ModuleCompileUnitsTreeItemDelegate( - self.target, self.module) + self.target, self.module + ) item_dicts.append(comp_units_item_delegate.get_item_dictionary()) return item_dicts class ModuleSectionsTreeItemDelegate(object): - def __init__(self, target, module): self.target = target self.module = module def get_item_dictionary(self): - name = 'sections' - value = '' - summary = '%u sections' % (self.module.GetNumSections()) - return {'#0': name, - 'value': value, - 'summary': summary, - 'children': True, - 'tree-item-delegate': self} + name = "sections" + value = "" + summary = "%u sections" % (self.module.GetNumSections()) + return { + "#0": name, + "value": value, + "summary": summary, + "children": True, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() @@ -233,7 +236,6 @@ class SectionTreeItemDelegate(object): - def __init__(self, target, section): self.target = target self.section = section @@ -242,15 +244,17 @@ name = self.section.name section_load_addr = self.section.GetLoadAddress(self.target) if section_load_addr != lldb.LLDB_INVALID_ADDRESS: - value = '0x%16.16x' % (section_load_addr) + value = "0x%16.16x" % (section_load_addr) else: - value = '0x%16.16x *' % (self.section.file_addr) - summary = '' - return {'#0': name, - 'value': value, - 'summary': summary, - 'children': self.section.GetNumSubSections() > 0, - 'tree-item-delegate': self} + value = "0x%16.16x *" % (self.section.file_addr) + summary = "" + return { + "#0": name, + "value": value, + "summary": summary, + "children": self.section.GetNumSubSections() > 0, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() @@ -263,20 +267,21 @@ class ModuleCompileUnitsTreeItemDelegate(object): - def __init__(self, target, module): self.target = target self.module = module def get_item_dictionary(self): - name = 'compile units' - value = '' - summary = '%u compile units' % (self.module.GetNumSections()) - return {'#0': name, - 'value': value, - 'summary': summary, - 'children': self.module.GetNumCompileUnits() > 0, - 'tree-item-delegate': self} + name = "compile units" + value = "" + summary = "%u compile units" % (self.module.GetNumSections()) + return { + "#0": name, + "value": value, + "summary": summary, + "children": self.module.GetNumCompileUnits() > 0, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() @@ -289,21 +294,22 @@ class CompileUnitTreeItemDelegate(object): - def __init__(self, target, cu): self.target = target self.cu = cu def get_item_dictionary(self): name = self.cu.GetFileSpec().basename - value = '' + value = "" num_lines = self.cu.GetNumLineEntries() - summary = '' - return {'#0': name, - 'value': value, - 'summary': summary, - 'children': num_lines > 0, - 'tree-item-delegate': self} + summary = "" + return { + "#0": name, + "value": value, + "summary": summary, + "children": num_lines > 0, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() @@ -313,35 +319,34 @@ class LineTableTreeItemDelegate(object): - def __init__(self, target, cu): self.target = target self.cu = cu def get_item_dictionary(self): - name = 'line table' - value = '' + name = "line table" + value = "" num_lines = self.cu.GetNumLineEntries() - summary = '%u line entries' % (num_lines) - return {'#0': name, - 'value': value, - 'summary': summary, - 'children': num_lines > 0, - 'tree-item-delegate': self} + summary = "%u line entries" % (num_lines) + return { + "#0": name, + "value": value, + "summary": summary, + "children": num_lines > 0, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() num_lines = self.cu.GetNumLineEntries() for i in range(num_lines): line_entry = self.cu.GetLineEntryAtIndex(i) - item_delegate = LineEntryTreeItemDelegate( - self.target, line_entry, i) + item_delegate = LineEntryTreeItemDelegate(self.target, line_entry, i) item_dicts.append(item_delegate.get_item_dictionary()) return item_dicts class LineEntryTreeItemDelegate(object): - def __init__(self, target, line_entry, index): self.target = target self.line_entry = line_entry @@ -352,16 +357,19 @@ address = self.line_entry.GetStartAddress() load_addr = address.GetLoadAddress(self.target) if load_addr != lldb.LLDB_INVALID_ADDRESS: - value = '0x%16.16x' % (load_addr) + value = "0x%16.16x" % (load_addr) else: - value = '0x%16.16x *' % (address.file_addr) - summary = self.line_entry.GetFileSpec().fullpath + ':' + \ - str(self.line_entry.line) - return {'#0': name, - 'value': value, - 'summary': summary, - 'children': False, - 'tree-item-delegate': self} + value = "0x%16.16x *" % (address.file_addr) + summary = ( + self.line_entry.GetFileSpec().fullpath + ":" + str(self.line_entry.line) + ) + return { + "#0": name, + "value": value, + "summary": summary, + "children": False, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() @@ -369,7 +377,6 @@ class InstructionTreeItemDelegate(object): - def __init__(self, target, instr): self.target = target self.instr = instr @@ -378,48 +385,52 @@ address = self.instr.GetAddress() load_addr = address.GetLoadAddress(self.target) if load_addr != lldb.LLDB_INVALID_ADDRESS: - name = '0x%16.16x' % (load_addr) + name = "0x%16.16x" % (load_addr) else: - name = '0x%16.16x *' % (address.file_addr) - value = self.instr.GetMnemonic( - self.target) + ' ' + self.instr.GetOperands(self.target) + name = "0x%16.16x *" % (address.file_addr) + value = ( + self.instr.GetMnemonic(self.target) + + " " + + self.instr.GetOperands(self.target) + ) summary = self.instr.GetComment(self.target) - return {'#0': name, - 'value': value, - 'summary': summary, - 'children': False, - 'tree-item-delegate': self} + return { + "#0": name, + "value": value, + "summary": summary, + "children": False, + "tree-item-delegate": self, + } class ModuleSymbolsTreeItemDelegate(object): - def __init__(self, target, module): self.target = target self.module = module def get_item_dictionary(self): - name = 'symbols' - value = '' - summary = '%u symbols' % (self.module.GetNumSymbols()) - return {'#0': name, - 'value': value, - 'summary': summary, - 'children': True, - 'tree-item-delegate': self} + name = "symbols" + value = "" + summary = "%u symbols" % (self.module.GetNumSymbols()) + return { + "#0": name, + "value": value, + "summary": summary, + "children": True, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() num_symbols = self.module.GetNumSymbols() for i in range(num_symbols): symbol = self.module.GetSymbolAtIndex(i) - image_item_delegate = SymbolTreeItemDelegate( - self.target, symbol, i) + image_item_delegate = SymbolTreeItemDelegate(self.target, symbol, i) item_dicts.append(image_item_delegate.get_item_dictionary()) return item_dicts class SymbolTreeItemDelegate(object): - def __init__(self, target, symbol, index): self.target = target self.symbol = symbol @@ -427,18 +438,20 @@ def get_item_dictionary(self): address = self.symbol.GetStartAddress() - name = '[%u]' % self.index + name = "[%u]" % self.index symbol_load_addr = address.GetLoadAddress(self.target) if symbol_load_addr != lldb.LLDB_INVALID_ADDRESS: - value = '0x%16.16x' % (symbol_load_addr) + value = "0x%16.16x" % (symbol_load_addr) else: - value = '0x%16.16x *' % (address.file_addr) + value = "0x%16.16x *" % (address.file_addr) summary = self.symbol.name - return {'#0': name, - 'value': value, - 'summary': summary, - 'children': False, - 'tree-item-delegate': self} + return { + "#0": name, + "value": value, + "summary": summary, + "children": False, + "tree-item-delegate": self, + } def get_child_item_dictionaries(self): item_dicts = list() @@ -446,7 +459,6 @@ class DelegateTree(ttk.Frame): - def __init__(self, column_dicts, delegate, title, name): ttk.Frame.__init__(self, name=name) self.pack(expand=Y, fill=BOTH) @@ -465,25 +477,23 @@ column_ids = list() for i in range(1, len(self.columns_dicts)): - column_ids.append(self.columns_dicts[i]['id']) + column_ids.append(self.columns_dicts[i]["id"]) # create the tree and scrollbars self.tree = ttk.Treeview(columns=column_ids) scroll_bar_v = ttk.Scrollbar(orient=VERTICAL, command=self.tree.yview) - scroll_bar_h = ttk.Scrollbar( - orient=HORIZONTAL, command=self.tree.xview) - self.tree['yscroll'] = scroll_bar_v.set - self.tree['xscroll'] = scroll_bar_h.set + scroll_bar_h = ttk.Scrollbar(orient=HORIZONTAL, command=self.tree.xview) + self.tree["yscroll"] = scroll_bar_v.set + self.tree["xscroll"] = scroll_bar_h.set # setup column headings and columns properties for columns_dict in self.columns_dicts: self.tree.heading( - columns_dict['id'], - text=columns_dict['text'], - anchor=columns_dict['anchor']) - self.tree.column( - columns_dict['id'], - stretch=columns_dict['stretch']) + columns_dict["id"], + text=columns_dict["text"], + anchor=columns_dict["anchor"], + ) + self.tree.column(columns_dict["id"], stretch=columns_dict["stretch"]) # add tree and scrollbars to frame self.tree.grid(in_=frame, row=0, column=0, sticky=NSEW) @@ -495,7 +505,7 @@ frame.columnconfigure(0, weight=1) # action to perform when a node is expanded - self.tree.bind('<>', self._update_tree) + self.tree.bind("<>", self._update_tree) def insert_items(self, parent_id, item_dicts): for item_dict in item_dicts: @@ -504,43 +514,43 @@ first = True for columns_dict in self.columns_dicts: if first: - name = item_dict[columns_dict['id']] + name = item_dict[columns_dict["id"]] first = False else: - values.append(item_dict[columns_dict['id']]) - item_id = self.tree.insert(parent_id, # root item has an empty name - END, - text=name, - values=values) + values.append(item_dict[columns_dict["id"]]) + item_id = self.tree.insert( + parent_id, END, text=name, values=values # root item has an empty name + ) self.item_id_to_item_dict[item_id] = item_dict - if item_dict['children']: - self.tree.insert(item_id, END, text='dummy') + if item_dict["children"]: + self.tree.insert(item_id, END, text="dummy") def _populate_root(self): # use current directory as root node - self.insert_items('', self.delegate.get_child_item_dictionaries()) + self.insert_items("", self.delegate.get_child_item_dictionaries()) def _update_tree(self, event): # user expanded a node - build the related directory - item_id = self.tree.focus() # the id of the expanded node + item_id = self.tree.focus() # the id of the expanded node children = self.tree.get_children(item_id) if len(children): first_child = children[0] # if the node only has a 'dummy' child, remove it and # build new directory; skip if the node is already # populated - if self.tree.item(first_child, option='text') == 'dummy': + if self.tree.item(first_child, option="text") == "dummy": self.tree.delete(first_child) item_dict = self.item_id_to_item_dict[item_id] item_dicts = item_dict[ - 'tree-item-delegate'].get_child_item_dictionaries() + "tree-item-delegate" + ].get_child_item_dictionaries() self.insert_items(item_id, item_dicts) @lldb.command("tk-variables") def tk_variable_display(debugger, command, result, dict): # needed for tree creation in TK library as it uses sys.argv... - sys.argv = ['tk-variables'] + sys.argv = ["tk-variables"] target = debugger.GetSelectedTarget() if not target: print("invalid target", file=result) @@ -559,22 +569,22 @@ return # Parse command line args command_args = shlex.split(command) - column_dicts = [{'id': '#0', 'text': 'Name', 'anchor': W, 'stretch': 0}, - {'id': 'typename', 'text': 'Type', 'anchor': W, 'stretch': 0}, - {'id': 'value', 'text': 'Value', 'anchor': W, 'stretch': 0}, - {'id': 'summary', 'text': 'Summary', 'anchor': W, 'stretch': 1}] + column_dicts = [ + {"id": "#0", "text": "Name", "anchor": W, "stretch": 0}, + {"id": "typename", "text": "Type", "anchor": W, "stretch": 0}, + {"id": "value", "text": "Value", "anchor": W, "stretch": 0}, + {"id": "summary", "text": "Summary", "anchor": W, "stretch": 1}, + ] tree = DelegateTree( - column_dicts, - FrameTreeItemDelegate(frame), - 'Variables', - 'lldb-tk-variables') + column_dicts, FrameTreeItemDelegate(frame), "Variables", "lldb-tk-variables" + ) tree.mainloop() @lldb.command("tk-process") def tk_process_display(debugger, command, result, dict): # needed for tree creation in TK library as it uses sys.argv... - sys.argv = ['tk-process'] + sys.argv = ["tk-process"] target = debugger.GetSelectedTarget() if not target: print("invalid target", file=result) @@ -584,34 +594,34 @@ print("invalid process", file=result) return # Parse command line args - columnd_dicts = [{'id': '#0', 'text': 'Name', 'anchor': W, 'stretch': 0}, - {'id': 'value', 'text': 'Value', 'anchor': W, 'stretch': 0}, - {'id': 'summary', 'text': 'Summary', 'anchor': W, 'stretch': 1}] + columnd_dicts = [ + {"id": "#0", "text": "Name", "anchor": W, "stretch": 0}, + {"id": "value", "text": "Value", "anchor": W, "stretch": 0}, + {"id": "summary", "text": "Summary", "anchor": W, "stretch": 1}, + ] command_args = shlex.split(command) tree = DelegateTree( - columnd_dicts, - ProcessTreeItemDelegate(process), - 'Process', - 'lldb-tk-process') + columnd_dicts, ProcessTreeItemDelegate(process), "Process", "lldb-tk-process" + ) tree.mainloop() @lldb.command("tk-target") def tk_target_display(debugger, command, result, dict): # needed for tree creation in TK library as it uses sys.argv... - sys.argv = ['tk-target'] + sys.argv = ["tk-target"] target = debugger.GetSelectedTarget() if not target: print("invalid target", file=result) return # Parse command line args - columnd_dicts = [{'id': '#0', 'text': 'Name', 'anchor': W, 'stretch': 0}, - {'id': 'value', 'text': 'Value', 'anchor': W, 'stretch': 0}, - {'id': 'summary', 'text': 'Summary', 'anchor': W, 'stretch': 1}] + columnd_dicts = [ + {"id": "#0", "text": "Name", "anchor": W, "stretch": 0}, + {"id": "value", "text": "Value", "anchor": W, "stretch": 0}, + {"id": "summary", "text": "Summary", "anchor": W, "stretch": 1}, + ] command_args = shlex.split(command) tree = DelegateTree( - columnd_dicts, - TargetTreeItemDelegate(target), - 'Target', - 'lldb-tk-target') + columnd_dicts, TargetTreeItemDelegate(target), "Target", "lldb-tk-target" + ) tree.mainloop() diff --git a/lldb/examples/python/mach_o.py b/lldb/examples/python/mach_o.py --- a/lldb/examples/python/mach_o.py +++ b/lldb/examples/python/mach_o.py @@ -12,12 +12,12 @@ import uuid # Mach header "magic" constants -MH_MAGIC = 0xfeedface -MH_CIGAM = 0xcefaedfe -MH_MAGIC_64 = 0xfeedfacf -MH_CIGAM_64 = 0xcffaedfe -FAT_MAGIC = 0xcafebabe -FAT_CIGAM = 0xbebafeca +MH_MAGIC = 0xFEEDFACE +MH_CIGAM = 0xCEFAEDFE +MH_MAGIC_64 = 0xFEEDFACF +MH_CIGAM_64 = 0xCFFAEDFE +FAT_MAGIC = 0xCAFEBABE +FAT_CIGAM = 0xBEBAFECA # Mach haeder "filetype" constants MH_OBJECT = 0x00000001 @@ -29,8 +29,8 @@ MH_DYLINKER = 0x00000007 MH_BUNDLE = 0x00000008 MH_DYLIB_STUB = 0x00000009 -MH_DSYM = 0x0000000a -MH_KEXT_BUNDLE = 0x0000000b +MH_DSYM = 0x0000000A +MH_KEXT_BUNDLE = 0x0000000B # Mach haeder "flag" constant bits MH_NOUNDEFS = 0x00000001 @@ -70,12 +70,12 @@ LC_IDFVMLIB = 0x00000007 LC_IDENT = 0x00000008 LC_FVMFILE = 0x00000009 -LC_PREPAGE = 0x0000000a -LC_DYSYMTAB = 0x0000000b -LC_LOAD_DYLIB = 0x0000000c -LC_ID_DYLIB = 0x0000000d -LC_LOAD_DYLINKER = 0x0000000e -LC_ID_DYLINKER = 0x0000000f +LC_PREPAGE = 0x0000000A +LC_DYSYMTAB = 0x0000000B +LC_LOAD_DYLIB = 0x0000000C +LC_ID_DYLIB = 0x0000000D +LC_LOAD_DYLINKER = 0x0000000E +LC_ID_DYLINKER = 0x0000000F LC_PREBOUND_DYLIB = 0x00000010 LC_ROUTINES = 0x00000011 LC_SUB_FRAMEWORK = 0x00000012 @@ -86,12 +86,12 @@ LC_PREBIND_CKSUM = 0x00000017 LC_LOAD_WEAK_DYLIB = 0x00000018 | LC_REQ_DYLD LC_SEGMENT_64 = 0x00000019 -LC_ROUTINES_64 = 0x0000001a -LC_UUID = 0x0000001b -LC_RPATH = 0x0000001c | LC_REQ_DYLD -LC_CODE_SIGNATURE = 0x0000001d -LC_SEGMENT_SPLIT_INFO = 0x0000001e -LC_REEXPORT_DYLIB = 0x0000001f | LC_REQ_DYLD +LC_ROUTINES_64 = 0x0000001A +LC_UUID = 0x0000001B +LC_RPATH = 0x0000001C | LC_REQ_DYLD +LC_CODE_SIGNATURE = 0x0000001D +LC_SEGMENT_SPLIT_INFO = 0x0000001E +LC_REEXPORT_DYLIB = 0x0000001F | LC_REQ_DYLD LC_LAZY_LOAD_DYLIB = 0x00000020 LC_ENCRYPTION_INFO = 0x00000021 LC_DYLD_INFO = 0x00000022 @@ -103,9 +103,9 @@ LC_DYLD_ENVIRONMENT = 0x00000027 # Mach CPU constants -CPU_ARCH_MASK = 0xff000000 +CPU_ARCH_MASK = 0xFF000000 CPU_ARCH_ABI64 = 0x01000000 -CPU_TYPE_ANY = 0xffffffff +CPU_TYPE_ANY = 0xFFFFFFFF CPU_TYPE_VAX = 1 CPU_TYPE_MC680x0 = 6 CPU_TYPE_I386 = 7 @@ -127,17 +127,17 @@ VM_PROT_EXECUTE = 4 # VM protection constants -N_STAB = 0xe0 +N_STAB = 0xE0 N_PEXT = 0x10 -N_TYPE = 0x0e +N_TYPE = 0x0E N_EXT = 0x01 # Values for nlist N_TYPE bits of the "Mach.NList.type" field. N_UNDF = 0x0 N_ABS = 0x2 -N_SECT = 0xe -N_PBUD = 0xc -N_INDR = 0xa +N_SECT = 0xE +N_PBUD = 0xC +N_INDR = 0xA # Section indexes for the "Mach.NList.sect_idx" fields NO_SECT = 0 @@ -149,11 +149,11 @@ N_FUN = 0x24 N_STSYM = 0x26 N_LCSYM = 0x28 -N_BNSYM = 0x2e -N_OPT = 0x3c +N_BNSYM = 0x2E +N_OPT = 0x3C N_RSYM = 0x40 N_SLINE = 0x44 -N_ENSYM = 0x4e +N_ENSYM = 0x4E N_SSYM = 0x60 N_SO = 0x64 N_OSO = 0x66 @@ -163,53 +163,53 @@ N_PARAMS = 0x86 N_VERSION = 0x88 N_OLEVEL = 0x8A -N_PSYM = 0xa0 -N_EINCL = 0xa2 -N_ENTRY = 0xa4 -N_LBRAC = 0xc0 -N_EXCL = 0xc2 -N_RBRAC = 0xe0 -N_BCOMM = 0xe2 -N_ECOMM = 0xe4 -N_ECOML = 0xe8 -N_LENG = 0xfe +N_PSYM = 0xA0 +N_EINCL = 0xA2 +N_ENTRY = 0xA4 +N_LBRAC = 0xC0 +N_EXCL = 0xC2 +N_RBRAC = 0xE0 +N_BCOMM = 0xE2 +N_ECOMM = 0xE4 +N_ECOML = 0xE8 +N_LENG = 0xFE -vm_prot_names = ['---', 'r--', '-w-', 'rw-', '--x', 'r-x', '-wx', 'rwx'] +vm_prot_names = ["---", "r--", "-w-", "rw-", "--x", "r-x", "-wx", "rwx"] def dump_memory(base_addr, data, hex_bytes_len, num_per_line): - hex_bytes = data.encode('hex') + hex_bytes = data.encode("hex") if hex_bytes_len == -1: hex_bytes_len = len(hex_bytes) addr = base_addr - ascii_str = '' + ascii_str = "" i = 0 while i < hex_bytes_len: if ((i / 2) % num_per_line) == 0: if i > 0: - print(' %s' % (ascii_str)) - ascii_str = '' - print('0x%8.8x:' % (addr + i), end=' ') - hex_byte = hex_bytes[i:i + 2] - print(hex_byte, end=' ') + print(" %s" % (ascii_str)) + ascii_str = "" + print("0x%8.8x:" % (addr + i), end=" ") + hex_byte = hex_bytes[i : i + 2] + print(hex_byte, end=" ") int_byte = int(hex_byte, 16) - ascii_char = '%c' % (int_byte) + ascii_char = "%c" % (int_byte) if int_byte >= 32 and int_byte < 127: ascii_str += ascii_char else: - ascii_str += '.' + ascii_str += "." i = i + 2 if ascii_str: if (i / 2) % num_per_line: padding = num_per_line - ((i / 2) % num_per_line) else: padding = 0 - print('%*s%s' % (padding * 3 + 1, '', ascii_str)) + print("%*s%s" % (padding * 3 + 1, "", ascii_str)) print() class TerminalColors: - '''Simple terminal colors class''' + """Simple terminal colors class""" def __init__(self, enabled=True): # TODO: discover terminal type from "file" and disable if @@ -217,162 +217,171 @@ self.enabled = enabled def reset(self): - '''Reset all terminal colors and formatting.''' + """Reset all terminal colors and formatting.""" if self.enabled: return "\x1b[0m" - return '' + return "" def bold(self, on=True): - '''Enable or disable bold depending on the "on" parameter.''' + """Enable or disable bold depending on the "on" parameter.""" if self.enabled: if on: return "\x1b[1m" else: return "\x1b[22m" - return '' + return "" def italics(self, on=True): - '''Enable or disable italics depending on the "on" parameter.''' + """Enable or disable italics depending on the "on" parameter.""" if self.enabled: if on: return "\x1b[3m" else: return "\x1b[23m" - return '' + return "" def underline(self, on=True): - '''Enable or disable underline depending on the "on" parameter.''' + """Enable or disable underline depending on the "on" parameter.""" if self.enabled: if on: return "\x1b[4m" else: return "\x1b[24m" - return '' + return "" def inverse(self, on=True): - '''Enable or disable inverse depending on the "on" parameter.''' + """Enable or disable inverse depending on the "on" parameter.""" if self.enabled: if on: return "\x1b[7m" else: return "\x1b[27m" - return '' + return "" def strike(self, on=True): - '''Enable or disable strike through depending on the "on" parameter.''' + """Enable or disable strike through depending on the "on" parameter.""" if self.enabled: if on: return "\x1b[9m" else: return "\x1b[29m" - return '' + return "" def black(self, fg=True): - '''Set the foreground or background color to black. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to black. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[30m" else: return "\x1b[40m" - return '' + return "" def red(self, fg=True): - '''Set the foreground or background color to red. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to red. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[31m" else: return "\x1b[41m" - return '' + return "" def green(self, fg=True): - '''Set the foreground or background color to green. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to green. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[32m" else: return "\x1b[42m" - return '' + return "" def yellow(self, fg=True): - '''Set the foreground or background color to yellow. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to yellow. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[43m" else: return "\x1b[33m" - return '' + return "" def blue(self, fg=True): - '''Set the foreground or background color to blue. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to blue. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[34m" else: return "\x1b[44m" - return '' + return "" def magenta(self, fg=True): - '''Set the foreground or background color to magenta. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to magenta. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[35m" else: return "\x1b[45m" - return '' + return "" def cyan(self, fg=True): - '''Set the foreground or background color to cyan. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to cyan. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[36m" else: return "\x1b[46m" - return '' + return "" def white(self, fg=True): - '''Set the foreground or background color to white. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to white. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[37m" else: return "\x1b[47m" - return '' + return "" def default(self, fg=True): - '''Set the foreground or background color to the default. - The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' + """Set the foreground or background color to the default. + The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. + """ if self.enabled: if fg: return "\x1b[39m" else: return "\x1b[49m" - return '' + return "" def swap_unpack_char(): """Returns the unpack prefix that will for non-native endian-ness.""" - if struct.pack('H', 1).startswith("\x00"): - return '<' - return '>' + if struct.pack("H", 1).startswith("\x00"): + return "<" + return ">" def dump_hex_bytes(addr, s, bytes_per_line=16): i = 0 - line = '' + line = "" for ch in s: if (i % bytes_per_line) == 0: if line: print(line) - line = '%#8.8x: ' % (addr + i) + line = "%#8.8x: " % (addr + i) line += "%02X " % ord(ch) i += 1 print(line) @@ -380,7 +389,7 @@ def dump_hex_byte_string_diff(addr, a, b, bytes_per_line=16): i = 0 - line = '' + line = "" a_len = len(a) b_len = len(b) if a_len < b_len: @@ -405,7 +414,7 @@ if (i % bytes_per_line) == 0: if line: print(line) - line = '%#8.8x: ' % (addr + i) + line = "%#8.8x: " % (addr + i) if mismatch: line += tty_colors.red() line += "%02X " % ord(ch) @@ -478,39 +487,47 @@ def __str__(self): for info in self.cpu_infos: - if self.cpu == info[1] and (self.sub & 0x00ffffff) == info[2]: + if self.cpu == info[1] and (self.sub & 0x00FFFFFF) == info[2]: return info[0] return "{0}.{1}".format(self.cpu, self.sub) class Magic(dict_utils.Enum): - enum = { - 'MH_MAGIC': MH_MAGIC, - 'MH_CIGAM': MH_CIGAM, - 'MH_MAGIC_64': MH_MAGIC_64, - 'MH_CIGAM_64': MH_CIGAM_64, - 'FAT_MAGIC': FAT_MAGIC, - 'FAT_CIGAM': FAT_CIGAM + "MH_MAGIC": MH_MAGIC, + "MH_CIGAM": MH_CIGAM, + "MH_MAGIC_64": MH_MAGIC_64, + "MH_CIGAM_64": MH_CIGAM_64, + "FAT_MAGIC": FAT_MAGIC, + "FAT_CIGAM": FAT_CIGAM, } def __init__(self, initial_value=0): dict_utils.Enum.__init__(self, initial_value, self.enum) def is_skinny_mach_file(self): - return self.value == MH_MAGIC or self.value == MH_CIGAM or self.value == MH_MAGIC_64 or self.value == MH_CIGAM_64 + return ( + self.value == MH_MAGIC + or self.value == MH_CIGAM + or self.value == MH_MAGIC_64 + or self.value == MH_CIGAM_64 + ) def is_universal_mach_file(self): return self.value == FAT_MAGIC or self.value == FAT_CIGAM def unpack(self, data): - data.set_byte_order('native') + data.set_byte_order("native") self.value = data.get_uint32() def get_byte_order(self): - if self.value == MH_CIGAM or self.value == MH_CIGAM_64 or self.value == FAT_CIGAM: + if ( + self.value == MH_CIGAM + or self.value == MH_CIGAM_64 + or self.value == FAT_CIGAM + ): return swap_unpack_char() else: - return '=' + return "=" def is_64_bit(self): return self.value == MH_MAGIC_64 or self.value == MH_CIGAM_64 @@ -528,7 +545,7 @@ self.path = path try: f = open(self.path) - file_extractor = file_extract.FileExtract(f, '=') + file_extractor = file_extract.FileExtract(f, "=") self.unpack(file_extractor) # f.close() except IOError as xxx_todo_changeme: @@ -583,24 +600,23 @@ return self.content is not None class Universal: - def __init__(self, path): self.path = path - self.type = 'universal' + self.type = "universal" self.file_off = 0 self.magic = None self.nfat_arch = 0 self.archs = list() def description(self): - s = '%#8.8x: %s (' % (self.file_off, self.path) - archs_string = '' + s = "%#8.8x: %s (" % (self.file_off, self.path) + archs_string = "" for arch in self.archs: if len(archs_string): - archs_string += ', ' - archs_string += '%s' % arch.arch + archs_string += ", " + archs_string += "%s" % arch.arch s += archs_string - s += ')' + s += ")" return s def unpack(self, data, magic=None): @@ -612,7 +628,7 @@ self.magic = magic self.file_off = self.file_off - 4 # Universal headers are always in big endian - data.set_byte_order('big') + data.set_byte_order("big") self.nfat_arch = data.get_uint32() for i in range(self.nfat_arch): self.archs.append(Mach.Universal.ArchInfo()) @@ -625,13 +641,16 @@ self.archs[i].mach.unpack(data, skinny_magic) def compare(self, rhs): - print('error: comparing two universal files is not supported yet') + print("error: comparing two universal files is not supported yet") return False def dump(self, options): if options.dump_header: print() - print("Universal Mach File: magic = %s, nfat_arch = %u" % (self.magic, self.nfat_arch)) + print( + "Universal Mach File: magic = %s, nfat_arch = %u" + % (self.magic, self.nfat_arch) + ) print() if self.nfat_arch > 0: if options.dump_header: @@ -678,11 +697,9 @@ def dump_symbol_names_matching_regex(self, regex, file=None): for i in range(self.nfat_arch): - self.archs[i].mach.dump_symbol_names_matching_regex( - regex, file) + self.archs[i].mach.dump_symbol_names_matching_regex(regex, file) class ArchInfo: - def __init__(self): self.arch = Mach.Arch(0, 0) self.offset = 0 @@ -692,9 +709,14 @@ def unpack(self, data): # Universal headers are always in big endian - data.set_byte_order('big') - self.arch.cpu, self.arch.sub, self.offset, self.size, self.align = data.get_n_uint32( - 5) + data.set_byte_order("big") + ( + self.arch.cpu, + self.arch.sub, + self.offset, + self.size, + self.align, + ) = data.get_n_uint32(5) def dump_header(self, dump_description=True, options=None): if options.verbose: @@ -706,9 +728,21 @@ def dump_flat(self, options): if options.verbose: - print("%#8.8x %#8.8x %#8.8x %#8.8x %#8.8x" % (self.arch.cpu, self.arch.sub, self.offset, self.size, self.align)) + print( + "%#8.8x %#8.8x %#8.8x %#8.8x %#8.8x" + % ( + self.arch.cpu, + self.arch.sub, + self.offset, + self.size, + self.align, + ) + ) else: - print("%-10s %#8.8x %#8.8x %#8.8x" % (self.arch, self.offset, self.size, self.align)) + print( + "%-10s %#8.8x %#8.8x %#8.8x" + % (self.arch, self.offset, self.size, self.align) + ) def dump(self): print(" cputype: %#8.8x" % self.arch.cpu) @@ -719,98 +753,105 @@ def __str__(self): return "Mach.Universal.ArchInfo: %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x" % ( - self.arch.cpu, self.arch.sub, self.offset, self.size, self.align) + self.arch.cpu, + self.arch.sub, + self.offset, + self.size, + self.align, + ) def __repr__(self): return "Mach.Universal.ArchInfo: %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x" % ( - self.arch.cpu, self.arch.sub, self.offset, self.size, self.align) + self.arch.cpu, + self.arch.sub, + self.offset, + self.size, + self.align, + ) class Flags: - def __init__(self, b): self.bits = b def __str__(self): - s = '' + s = "" if self.bits & MH_NOUNDEFS: - s += 'MH_NOUNDEFS | ' + s += "MH_NOUNDEFS | " if self.bits & MH_INCRLINK: - s += 'MH_INCRLINK | ' + s += "MH_INCRLINK | " if self.bits & MH_DYLDLINK: - s += 'MH_DYLDLINK | ' + s += "MH_DYLDLINK | " if self.bits & MH_BINDATLOAD: - s += 'MH_BINDATLOAD | ' + s += "MH_BINDATLOAD | " if self.bits & MH_PREBOUND: - s += 'MH_PREBOUND | ' + s += "MH_PREBOUND | " if self.bits & MH_SPLIT_SEGS: - s += 'MH_SPLIT_SEGS | ' + s += "MH_SPLIT_SEGS | " if self.bits & MH_LAZY_INIT: - s += 'MH_LAZY_INIT | ' + s += "MH_LAZY_INIT | " if self.bits & MH_TWOLEVEL: - s += 'MH_TWOLEVEL | ' + s += "MH_TWOLEVEL | " if self.bits & MH_FORCE_FLAT: - s += 'MH_FORCE_FLAT | ' + s += "MH_FORCE_FLAT | " if self.bits & MH_NOMULTIDEFS: - s += 'MH_NOMULTIDEFS | ' + s += "MH_NOMULTIDEFS | " if self.bits & MH_NOFIXPREBINDING: - s += 'MH_NOFIXPREBINDING | ' + s += "MH_NOFIXPREBINDING | " if self.bits & MH_PREBINDABLE: - s += 'MH_PREBINDABLE | ' + s += "MH_PREBINDABLE | " if self.bits & MH_ALLMODSBOUND: - s += 'MH_ALLMODSBOUND | ' + s += "MH_ALLMODSBOUND | " if self.bits & MH_SUBSECTIONS_VIA_SYMBOLS: - s += 'MH_SUBSECTIONS_VIA_SYMBOLS | ' + s += "MH_SUBSECTIONS_VIA_SYMBOLS | " if self.bits & MH_CANONICAL: - s += 'MH_CANONICAL | ' + s += "MH_CANONICAL | " if self.bits & MH_WEAK_DEFINES: - s += 'MH_WEAK_DEFINES | ' + s += "MH_WEAK_DEFINES | " if self.bits & MH_BINDS_TO_WEAK: - s += 'MH_BINDS_TO_WEAK | ' + s += "MH_BINDS_TO_WEAK | " if self.bits & MH_ALLOW_STACK_EXECUTION: - s += 'MH_ALLOW_STACK_EXECUTION | ' + s += "MH_ALLOW_STACK_EXECUTION | " if self.bits & MH_ROOT_SAFE: - s += 'MH_ROOT_SAFE | ' + s += "MH_ROOT_SAFE | " if self.bits & MH_SETUID_SAFE: - s += 'MH_SETUID_SAFE | ' + s += "MH_SETUID_SAFE | " if self.bits & MH_NO_REEXPORTED_DYLIBS: - s += 'MH_NO_REEXPORTED_DYLIBS | ' + s += "MH_NO_REEXPORTED_DYLIBS | " if self.bits & MH_PIE: - s += 'MH_PIE | ' + s += "MH_PIE | " if self.bits & MH_DEAD_STRIPPABLE_DYLIB: - s += 'MH_DEAD_STRIPPABLE_DYLIB | ' + s += "MH_DEAD_STRIPPABLE_DYLIB | " if self.bits & MH_HAS_TLV_DESCRIPTORS: - s += 'MH_HAS_TLV_DESCRIPTORS | ' + s += "MH_HAS_TLV_DESCRIPTORS | " if self.bits & MH_NO_HEAP_EXECUTION: - s += 'MH_NO_HEAP_EXECUTION | ' + s += "MH_NO_HEAP_EXECUTION | " # Strip the trailing " |" if we have any flags if len(s) > 0: s = s[0:-2] return s class FileType(dict_utils.Enum): - enum = { - 'MH_OBJECT': MH_OBJECT, - 'MH_EXECUTE': MH_EXECUTE, - 'MH_FVMLIB': MH_FVMLIB, - 'MH_CORE': MH_CORE, - 'MH_PRELOAD': MH_PRELOAD, - 'MH_DYLIB': MH_DYLIB, - 'MH_DYLINKER': MH_DYLINKER, - 'MH_BUNDLE': MH_BUNDLE, - 'MH_DYLIB_STUB': MH_DYLIB_STUB, - 'MH_DSYM': MH_DSYM, - 'MH_KEXT_BUNDLE': MH_KEXT_BUNDLE + "MH_OBJECT": MH_OBJECT, + "MH_EXECUTE": MH_EXECUTE, + "MH_FVMLIB": MH_FVMLIB, + "MH_CORE": MH_CORE, + "MH_PRELOAD": MH_PRELOAD, + "MH_DYLIB": MH_DYLIB, + "MH_DYLINKER": MH_DYLINKER, + "MH_BUNDLE": MH_BUNDLE, + "MH_DYLIB_STUB": MH_DYLIB_STUB, + "MH_DSYM": MH_DSYM, + "MH_KEXT_BUNDLE": MH_KEXT_BUNDLE, } def __init__(self, initial_value=0): dict_utils.Enum.__init__(self, initial_value, self.enum) class Skinny: - def __init__(self, path): self.path = path - self.type = 'skinny' + self.type = "skinny" self.data = None self.file_off = 0 self.magic = 0 @@ -827,7 +868,7 @@ self.sections.append(Mach.Section()) def description(self): - return '%#8.8x: %s (%s)' % (self.file_off, self.path, self.arch) + return "%#8.8x: %s (%s)" % (self.file_off, self.path, self.arch) def unpack(self, data, magic=None): self.data = data @@ -839,8 +880,14 @@ self.magic = magic self.file_off = self.file_off - 4 data.set_byte_order(self.magic.get_byte_order()) - self.arch.cpu, self.arch.sub, self.filetype.value, self.ncmds, self.sizeofcmds, bits = data.get_n_uint32( - 6) + ( + self.arch.cpu, + self.arch.sub, + self.filetype.value, + self.ncmds, + self.sizeofcmds, + bits, + ) = data.get_n_uint32(6) self.flags.bits = bits if self.is_64_bit(): @@ -860,46 +907,51 @@ lc = Mach.LoadCommand() lc.unpack(self, data) lc_command = lc.command.get_enum_value() - if (lc_command == LC_SEGMENT or - lc_command == LC_SEGMENT_64): + if lc_command == LC_SEGMENT or lc_command == LC_SEGMENT_64: lc = Mach.SegmentLoadCommand(lc) lc.unpack(self, data) - elif (lc_command == LC_LOAD_DYLIB or - lc_command == LC_ID_DYLIB or - lc_command == LC_LOAD_WEAK_DYLIB or - lc_command == LC_REEXPORT_DYLIB): + elif ( + lc_command == LC_LOAD_DYLIB + or lc_command == LC_ID_DYLIB + or lc_command == LC_LOAD_WEAK_DYLIB + or lc_command == LC_REEXPORT_DYLIB + ): lc = Mach.DylibLoadCommand(lc) lc.unpack(self, data) - elif (lc_command == LC_LOAD_DYLINKER or - lc_command == LC_SUB_FRAMEWORK or - lc_command == LC_SUB_CLIENT or - lc_command == LC_SUB_UMBRELLA or - lc_command == LC_SUB_LIBRARY or - lc_command == LC_ID_DYLINKER or - lc_command == LC_RPATH): + elif ( + lc_command == LC_LOAD_DYLINKER + or lc_command == LC_SUB_FRAMEWORK + or lc_command == LC_SUB_CLIENT + or lc_command == LC_SUB_UMBRELLA + or lc_command == LC_SUB_LIBRARY + or lc_command == LC_ID_DYLINKER + or lc_command == LC_RPATH + ): lc = Mach.LoadDYLDLoadCommand(lc) lc.unpack(self, data) - elif (lc_command == LC_DYLD_INFO_ONLY): + elif lc_command == LC_DYLD_INFO_ONLY: lc = Mach.DYLDInfoOnlyLoadCommand(lc) lc.unpack(self, data) - elif (lc_command == LC_SYMTAB): + elif lc_command == LC_SYMTAB: lc = Mach.SymtabLoadCommand(lc) lc.unpack(self, data) - elif (lc_command == LC_DYSYMTAB): + elif lc_command == LC_DYSYMTAB: lc = Mach.DYLDSymtabLoadCommand(lc) lc.unpack(self, data) - elif (lc_command == LC_UUID): + elif lc_command == LC_UUID: lc = Mach.UUIDLoadCommand(lc) lc.unpack(self, data) - elif (lc_command == LC_CODE_SIGNATURE or - lc_command == LC_SEGMENT_SPLIT_INFO or - lc_command == LC_FUNCTION_STARTS): + elif ( + lc_command == LC_CODE_SIGNATURE + or lc_command == LC_SEGMENT_SPLIT_INFO + or lc_command == LC_FUNCTION_STARTS + ): lc = Mach.DataBlobLoadCommand(lc) lc.unpack(self, data) - elif (lc_command == LC_UNIXTHREAD): + elif lc_command == LC_UNIXTHREAD: lc = Mach.UnixThreadLoadCommand(lc) lc.unpack(self, data) - elif (lc_command == LC_ENCRYPTION_INFO): + elif lc_command == LC_ENCRYPTION_INFO: lc = Mach.EncryptionInfoLoadCommand(lc) lc.unpack(self, data) lc.skip(data) @@ -914,13 +966,17 @@ for lhs_section in self.sections[1:]: rhs_section = rhs.get_section_by_section(lhs_section) if rhs_section: - print('comparing %s.%s...' % (lhs_section.segname, lhs_section.sectname), end=' ') + print( + "comparing %s.%s..." + % (lhs_section.segname, lhs_section.sectname), + end=" ", + ) sys.stdout.flush() lhs_data = lhs_section.get_contents(self) rhs_data = rhs_section.get_contents(rhs) if lhs_data and rhs_data: if lhs_data == rhs_data: - print('ok') + print("ok") else: lhs_data_len = len(lhs_data) rhs_data_len = len(rhs_data) @@ -938,51 +994,86 @@ # result = False # else: result = False - print('error: sections differ') + print("error: sections differ") # print 'a) %s' % (lhs_section) # dump_hex_byte_string_diff(0, lhs_data, rhs_data) # print 'b) %s' % (rhs_section) # dump_hex_byte_string_diff(0, rhs_data, lhs_data) elif lhs_data and not rhs_data: - print('error: section data missing from b:') - print('a) %s' % (lhs_section)) - print('b) %s' % (rhs_section)) + print("error: section data missing from b:") + print("a) %s" % (lhs_section)) + print("b) %s" % (rhs_section)) result = False elif not lhs_data and rhs_data: - print('error: section data missing from a:') - print('a) %s' % (lhs_section)) - print('b) %s' % (rhs_section)) + print("error: section data missing from a:") + print("a) %s" % (lhs_section)) + print("b) %s" % (rhs_section)) result = False elif lhs_section.offset or rhs_section.offset: - print('error: section data missing for both a and b:') - print('a) %s' % (lhs_section)) - print('b) %s' % (rhs_section)) + print("error: section data missing for both a and b:") + print("a) %s" % (lhs_section)) + print("b) %s" % (rhs_section)) result = False else: - print('ok') + print("ok") else: result = False - print('error: section %s is missing in %s' % (lhs_section.sectname, rhs.path)) + print( + "error: section %s is missing in %s" + % (lhs_section.sectname, rhs.path) + ) else: - print('error: comparing a %s mach-o file with a %s mach-o file is not supported' % (self.type, rhs.type)) + print( + "error: comparing a %s mach-o file with a %s mach-o file is not supported" + % (self.type, rhs.type) + ) result = False if not result: - print('error: mach files differ') + print("error: mach files differ") return result def dump_header(self, dump_description=True, options=None): if options.verbose: - print("MAGIC CPU SUBTYPE FILETYPE NUM CMDS SIZE CMDS FLAGS") - print("---------- ---------- ---------- ---------- -------- ---------- ----------") + print( + "MAGIC CPU SUBTYPE FILETYPE NUM CMDS SIZE CMDS FLAGS" + ) + print( + "---------- ---------- ---------- ---------- -------- ---------- ----------" + ) else: - print("MAGIC ARCH FILETYPE NUM CMDS SIZE CMDS FLAGS") - print("------------ ---------- -------------- -------- ---------- ----------") + print( + "MAGIC ARCH FILETYPE NUM CMDS SIZE CMDS FLAGS" + ) + print( + "------------ ---------- -------------- -------- ---------- ----------" + ) def dump_flat(self, options): if options.verbose: - print("%#8.8x %#8.8x %#8.8x %#8.8x %#8u %#8.8x %#8.8x" % (self.magic, self.arch.cpu, self.arch.sub, self.filetype.value, self.ncmds, self.sizeofcmds, self.flags.bits)) + print( + "%#8.8x %#8.8x %#8.8x %#8.8x %#8u %#8.8x %#8.8x" + % ( + self.magic, + self.arch.cpu, + self.arch.sub, + self.filetype.value, + self.ncmds, + self.sizeofcmds, + self.flags.bits, + ) + ) else: - print("%-12s %-10s %-14s %#8u %#8.8x %s" % (self.magic, self.arch, self.filetype, self.ncmds, self.sizeofcmds, self.flags)) + print( + "%-12s %-10s %-14s %#8u %#8.8x %s" + % ( + self.magic, + self.arch, + self.filetype, + self.ncmds, + self.sizeofcmds, + self.flags, + ) + ) def dump(self, options): if options.dump_header: @@ -1000,7 +1091,7 @@ else: print("No symbols") if options.find_mangled: - self.dump_symbol_names_matching_regex(re.compile('^_?_Z')) + self.dump_symbol_names_matching_regex(re.compile("^_?_Z")) def dump_header(self, dump_description=True, options=None): if dump_description: @@ -1009,7 +1100,10 @@ print(" magic: %#8.8x %s" % (self.magic.value, self.magic)) print(" cputype: %#8.8x %s" % (self.arch.cpu, self.arch)) print(" cpusubtype: %#8.8x" % self.arch.sub) - print(" filetype: %#8.8x %s" % (self.filetype.get_enum_value(), self.filetype.get_enum_name())) + print( + " filetype: %#8.8x %s" + % (self.filetype.get_enum_value(), self.filetype.get_enum_name()) + ) print(" ncmds: %#8.8x %u" % (self.ncmds, self.ncmds)) print(" sizeofcmds: %#8.8x" % self.sizeofcmds) print(" flags: %#8.8x %s" % (self.flags.bits, self.flags)) @@ -1028,7 +1122,10 @@ def get_section_by_section(self, other_section): for section in self.sections: - if section.sectname == other_section.sectname and section.segname == other_section.segname: + if ( + section.sectname == other_section.sectname + and section.segname == other_section.segname + ): return section return None @@ -1049,11 +1146,12 @@ sect_bytes = section.get_contents(self) if options.outfile: if not saved_section_to_disk: - outfile = open(options.outfile, 'w') + outfile = open(options.outfile, "w") if options.extract_modules: # print "Extracting modules from mach file..." data = file_extract.FileExtract( - io.BytesIO(sect_bytes), self.data.byte_order) + io.BytesIO(sect_bytes), self.data.byte_order + ) version = data.get_uint32() num_modules = data.get_uint32() # print "version = %u, num_modules = %u" % @@ -1075,22 +1173,28 @@ data.seek(data_offset) outfile.write(data.read_size(data_size)) else: - print("Saving section %s to '%s'" % (sectname, options.outfile)) + print( + "Saving section %s to '%s'" + % (sectname, options.outfile) + ) outfile.write(sect_bytes) outfile.close() saved_section_to_disk = True else: - print("error: you can only save a single section to disk at a time, skipping section '%s'" % (sectname)) + print( + "error: you can only save a single section to disk at a time, skipping section '%s'" + % (sectname) + ) else: - print('section %s:\n' % (sectname)) + print("section %s:\n" % (sectname)) section.dump_header() - print('%s\n' % (section)) + print("%s\n" % (section)) dump_memory(0, sect_bytes, options.max_count, 16) else: print('error: no section named "%s" was found' % (sectname)) def get_segment(self, segname): - if len(self.segments) == 1 and self.segments[0].segname == '': + if len(self.segments) == 1 and self.segments[0].segname == "": return self.segments[0] for segment in self.segments: if segment.segname == segname: @@ -1109,12 +1213,16 @@ if lc_symtab: symtab_offset = self.file_off if self.data.is_in_memory(): - linkedit_segment = self.get_segment('__LINKEDIT') + linkedit_segment = self.get_segment("__LINKEDIT") if linkedit_segment: linkedit_vmaddr = linkedit_segment.vmaddr linkedit_fileoff = linkedit_segment.fileoff - symtab_offset = linkedit_vmaddr + lc_symtab.symoff - linkedit_fileoff - symtab_offset = linkedit_vmaddr + lc_symtab.stroff - linkedit_fileoff + symtab_offset = ( + linkedit_vmaddr + lc_symtab.symoff - linkedit_fileoff + ) + symtab_offset = ( + linkedit_vmaddr + lc_symtab.stroff - linkedit_fileoff + ) else: symtab_offset += lc_symtab.symoff @@ -1132,7 +1240,7 @@ if dump_description: print(self.description()) for i, symbol in enumerate(self.symbols): - print('[%5u] %s' % (i, symbol)) + print("[%5u] %s" % (i, symbol)) def dump_symbol_names_matching_regex(self, regex, file=None): self.get_symtab() @@ -1140,55 +1248,54 @@ if symbol.name and regex.search(symbol.name): print(symbol.name) if file: - file.write('%s\n' % (symbol.name)) + file.write("%s\n" % (symbol.name)) def is_64_bit(self): return self.magic.is_64_bit() class LoadCommand: - class Command(dict_utils.Enum): enum = { - 'LC_SEGMENT': LC_SEGMENT, - 'LC_SYMTAB': LC_SYMTAB, - 'LC_SYMSEG': LC_SYMSEG, - 'LC_THREAD': LC_THREAD, - 'LC_UNIXTHREAD': LC_UNIXTHREAD, - 'LC_LOADFVMLIB': LC_LOADFVMLIB, - 'LC_IDFVMLIB': LC_IDFVMLIB, - 'LC_IDENT': LC_IDENT, - 'LC_FVMFILE': LC_FVMFILE, - 'LC_PREPAGE': LC_PREPAGE, - 'LC_DYSYMTAB': LC_DYSYMTAB, - 'LC_LOAD_DYLIB': LC_LOAD_DYLIB, - 'LC_ID_DYLIB': LC_ID_DYLIB, - 'LC_LOAD_DYLINKER': LC_LOAD_DYLINKER, - 'LC_ID_DYLINKER': LC_ID_DYLINKER, - 'LC_PREBOUND_DYLIB': LC_PREBOUND_DYLIB, - 'LC_ROUTINES': LC_ROUTINES, - 'LC_SUB_FRAMEWORK': LC_SUB_FRAMEWORK, - 'LC_SUB_UMBRELLA': LC_SUB_UMBRELLA, - 'LC_SUB_CLIENT': LC_SUB_CLIENT, - 'LC_SUB_LIBRARY': LC_SUB_LIBRARY, - 'LC_TWOLEVEL_HINTS': LC_TWOLEVEL_HINTS, - 'LC_PREBIND_CKSUM': LC_PREBIND_CKSUM, - 'LC_LOAD_WEAK_DYLIB': LC_LOAD_WEAK_DYLIB, - 'LC_SEGMENT_64': LC_SEGMENT_64, - 'LC_ROUTINES_64': LC_ROUTINES_64, - 'LC_UUID': LC_UUID, - 'LC_RPATH': LC_RPATH, - 'LC_CODE_SIGNATURE': LC_CODE_SIGNATURE, - 'LC_SEGMENT_SPLIT_INFO': LC_SEGMENT_SPLIT_INFO, - 'LC_REEXPORT_DYLIB': LC_REEXPORT_DYLIB, - 'LC_LAZY_LOAD_DYLIB': LC_LAZY_LOAD_DYLIB, - 'LC_ENCRYPTION_INFO': LC_ENCRYPTION_INFO, - 'LC_DYLD_INFO': LC_DYLD_INFO, - 'LC_DYLD_INFO_ONLY': LC_DYLD_INFO_ONLY, - 'LC_LOAD_UPWARD_DYLIB': LC_LOAD_UPWARD_DYLIB, - 'LC_VERSION_MIN_MACOSX': LC_VERSION_MIN_MACOSX, - 'LC_VERSION_MIN_IPHONEOS': LC_VERSION_MIN_IPHONEOS, - 'LC_FUNCTION_STARTS': LC_FUNCTION_STARTS, - 'LC_DYLD_ENVIRONMENT': LC_DYLD_ENVIRONMENT + "LC_SEGMENT": LC_SEGMENT, + "LC_SYMTAB": LC_SYMTAB, + "LC_SYMSEG": LC_SYMSEG, + "LC_THREAD": LC_THREAD, + "LC_UNIXTHREAD": LC_UNIXTHREAD, + "LC_LOADFVMLIB": LC_LOADFVMLIB, + "LC_IDFVMLIB": LC_IDFVMLIB, + "LC_IDENT": LC_IDENT, + "LC_FVMFILE": LC_FVMFILE, + "LC_PREPAGE": LC_PREPAGE, + "LC_DYSYMTAB": LC_DYSYMTAB, + "LC_LOAD_DYLIB": LC_LOAD_DYLIB, + "LC_ID_DYLIB": LC_ID_DYLIB, + "LC_LOAD_DYLINKER": LC_LOAD_DYLINKER, + "LC_ID_DYLINKER": LC_ID_DYLINKER, + "LC_PREBOUND_DYLIB": LC_PREBOUND_DYLIB, + "LC_ROUTINES": LC_ROUTINES, + "LC_SUB_FRAMEWORK": LC_SUB_FRAMEWORK, + "LC_SUB_UMBRELLA": LC_SUB_UMBRELLA, + "LC_SUB_CLIENT": LC_SUB_CLIENT, + "LC_SUB_LIBRARY": LC_SUB_LIBRARY, + "LC_TWOLEVEL_HINTS": LC_TWOLEVEL_HINTS, + "LC_PREBIND_CKSUM": LC_PREBIND_CKSUM, + "LC_LOAD_WEAK_DYLIB": LC_LOAD_WEAK_DYLIB, + "LC_SEGMENT_64": LC_SEGMENT_64, + "LC_ROUTINES_64": LC_ROUTINES_64, + "LC_UUID": LC_UUID, + "LC_RPATH": LC_RPATH, + "LC_CODE_SIGNATURE": LC_CODE_SIGNATURE, + "LC_SEGMENT_SPLIT_INFO": LC_SEGMENT_SPLIT_INFO, + "LC_REEXPORT_DYLIB": LC_REEXPORT_DYLIB, + "LC_LAZY_LOAD_DYLIB": LC_LAZY_LOAD_DYLIB, + "LC_ENCRYPTION_INFO": LC_ENCRYPTION_INFO, + "LC_DYLD_INFO": LC_DYLD_INFO, + "LC_DYLD_INFO_ONLY": LC_DYLD_INFO_ONLY, + "LC_LOAD_UPWARD_DYLIB": LC_LOAD_UPWARD_DYLIB, + "LC_VERSION_MIN_MACOSX": LC_VERSION_MIN_MACOSX, + "LC_VERSION_MIN_IPHONEOS": LC_VERSION_MIN_IPHONEOS, + "LC_FUNCTION_STARTS": LC_FUNCTION_STARTS, + "LC_DYLD_ENVIRONMENT": LC_DYLD_ENVIRONMENT, } def __init__(self, initial_value=0): @@ -1211,11 +1318,9 @@ def __str__(self): lc_name = self.command.get_enum_name() - return '%#8.8x: <%#4.4x> %-24s' % (self.file_off, - self.length, lc_name) + return "%#8.8x: <%#4.4x> %-24s" % (self.file_off, self.length, lc_name) class Section: - def __init__(self): self.index = 0 self.is_64 = False @@ -1234,37 +1339,90 @@ def unpack(self, is_64, data): self.is_64 = is_64 - self.sectname = data.get_fixed_length_c_string(16, '', True) - self.segname = data.get_fixed_length_c_string(16, '', True) + self.sectname = data.get_fixed_length_c_string(16, "", True) + self.segname = data.get_fixed_length_c_string(16, "", True) if self.is_64: self.addr, self.size = data.get_n_uint64(2) - self.offset, self.align, self.reloff, self.nreloc, self.flags, self.reserved1, self.reserved2, self.reserved3 = data.get_n_uint32( - 8) + ( + self.offset, + self.align, + self.reloff, + self.nreloc, + self.flags, + self.reserved1, + self.reserved2, + self.reserved3, + ) = data.get_n_uint32(8) else: self.addr, self.size = data.get_n_uint32(2) - self.offset, self.align, self.reloff, self.nreloc, self.flags, self.reserved1, self.reserved2 = data.get_n_uint32( - 7) + ( + self.offset, + self.align, + self.reloff, + self.nreloc, + self.flags, + self.reserved1, + self.reserved2, + ) = data.get_n_uint32(7) def dump_header(self): if self.is_64: - print("INDEX ADDRESS SIZE OFFSET ALIGN RELOFF NRELOC FLAGS RESERVED1 RESERVED2 RESERVED3 NAME") - print("===== ------------------ ------------------ ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------------------") + print( + "INDEX ADDRESS SIZE OFFSET ALIGN RELOFF NRELOC FLAGS RESERVED1 RESERVED2 RESERVED3 NAME" + ) + print( + "===== ------------------ ------------------ ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------------------" + ) else: - print("INDEX ADDRESS SIZE OFFSET ALIGN RELOFF NRELOC FLAGS RESERVED1 RESERVED2 NAME") - print("===== ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------------------") + print( + "INDEX ADDRESS SIZE OFFSET ALIGN RELOFF NRELOC FLAGS RESERVED1 RESERVED2 NAME" + ) + print( + "===== ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------------------" + ) def __str__(self): if self.is_64: - return "[%3u] %#16.16x %#16.16x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %s.%s" % ( - self.index, self.addr, self.size, self.offset, self.align, self.reloff, self.nreloc, self.flags, self.reserved1, self.reserved2, self.reserved3, self.segname, self.sectname) + return ( + "[%3u] %#16.16x %#16.16x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %s.%s" + % ( + self.index, + self.addr, + self.size, + self.offset, + self.align, + self.reloff, + self.nreloc, + self.flags, + self.reserved1, + self.reserved2, + self.reserved3, + self.segname, + self.sectname, + ) + ) else: - return "[%3u] %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %s.%s" % ( - self.index, self.addr, self.size, self.offset, self.align, self.reloff, self.nreloc, self.flags, self.reserved1, self.reserved2, self.segname, self.sectname) + return ( + "[%3u] %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %s.%s" + % ( + self.index, + self.addr, + self.size, + self.offset, + self.align, + self.reloff, + self.nreloc, + self.flags, + self.reserved1, + self.reserved2, + self.segname, + self.sectname, + ) + ) def get_contents(self, mach_file): - '''Get the section contents as a python string''' - if self.size > 0 and mach_file.get_segment( - self.segname).filesize > 0: + """Get the section contents as a python string""" + if self.size > 0 and mach_file.get_segment(self.segname).filesize > 0: data = mach_file.get_data() if data: section_data_offset = mach_file.file_off + self.offset @@ -1278,7 +1436,6 @@ return None class DylibLoadCommand(LoadCommand): - def __init__(self, lc): Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off) self.name = None @@ -1288,21 +1445,26 @@ def unpack(self, mach_file, data): byte_order_char = mach_file.magic.get_byte_order() - name_offset, self.timestamp, self.current_version, self.compatibility_version = data.get_n_uint32( - 4) + ( + name_offset, + self.timestamp, + self.current_version, + self.compatibility_version, + ) = data.get_n_uint32(4) data.seek(self.file_off + name_offset, 0) self.name = data.get_fixed_length_c_string(self.length - 24) def __str__(self): s = Mach.LoadCommand.__str__(self) - s += "%#8.8x %#8.8x %#8.8x " % (self.timestamp, - self.current_version, - self.compatibility_version) + s += "%#8.8x %#8.8x %#8.8x " % ( + self.timestamp, + self.current_version, + self.compatibility_version, + ) s += self.name return s class LoadDYLDLoadCommand(LoadCommand): - def __init__(self, lc): Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off) self.name = None @@ -1317,9 +1479,7 @@ return s class UnixThreadLoadCommand(LoadCommand): - class ThreadState: - def __init__(self): self.flavor = 0 self.count = 0 @@ -1330,8 +1490,7 @@ self.register_values = data.get_n_uint32(self.count) def __str__(self): - s = "flavor = %u, count = %u, regs =" % ( - self.flavor, self.count) + s = "flavor = %u, count = %u, regs =" % (self.flavor, self.count) i = 0 for register_value in self.register_values: if i % 8 == 0: @@ -1356,7 +1515,6 @@ return s class DYLDInfoOnlyLoadCommand(LoadCommand): - def __init__(self, lc): Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off) self.rebase_off = 0 @@ -1372,25 +1530,41 @@ def unpack(self, mach_file, data): byte_order_char = mach_file.magic.get_byte_order() - self.rebase_off, self.rebase_size, self.bind_off, self.bind_size, self.weak_bind_off, self.weak_bind_size, self.lazy_bind_off, self.lazy_bind_size, self.export_off, self.export_size = data.get_n_uint32( - 10) + ( + self.rebase_off, + self.rebase_size, + self.bind_off, + self.bind_size, + self.weak_bind_off, + self.weak_bind_size, + self.lazy_bind_off, + self.lazy_bind_size, + self.export_off, + self.export_size, + ) = data.get_n_uint32(10) def __str__(self): s = Mach.LoadCommand.__str__(self) s += "rebase_off = %#8.8x, rebase_size = %u, " % ( - self.rebase_off, self.rebase_size) - s += "bind_off = %#8.8x, bind_size = %u, " % ( - self.bind_off, self.bind_size) + self.rebase_off, + self.rebase_size, + ) + s += "bind_off = %#8.8x, bind_size = %u, " % (self.bind_off, self.bind_size) s += "weak_bind_off = %#8.8x, weak_bind_size = %u, " % ( - self.weak_bind_off, self.weak_bind_size) + self.weak_bind_off, + self.weak_bind_size, + ) s += "lazy_bind_off = %#8.8x, lazy_bind_size = %u, " % ( - self.lazy_bind_off, self.lazy_bind_size) + self.lazy_bind_off, + self.lazy_bind_size, + ) s += "export_off = %#8.8x, export_size = %u, " % ( - self.export_off, self.export_size) + self.export_off, + self.export_size, + ) return s class DYLDSymtabLoadCommand(LoadCommand): - def __init__(self, lc): Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off) self.ilocalsym = 0 @@ -1414,8 +1588,26 @@ def unpack(self, mach_file, data): byte_order_char = mach_file.magic.get_byte_order() - self.ilocalsym, self.nlocalsym, self.iextdefsym, self.nextdefsym, self.iundefsym, self.nundefsym, self.tocoff, self.ntoc, self.modtaboff, self.nmodtab, self.extrefsymoff, self.nextrefsyms, self.indirectsymoff, self.nindirectsyms, self.extreloff, self.nextrel, self.locreloff, self.nlocrel = data.get_n_uint32( - 18) + ( + self.ilocalsym, + self.nlocalsym, + self.iextdefsym, + self.nextdefsym, + self.iundefsym, + self.nundefsym, + self.tocoff, + self.ntoc, + self.modtaboff, + self.nmodtab, + self.extrefsymoff, + self.nextrefsyms, + self.indirectsymoff, + self.nindirectsyms, + self.extreloff, + self.nextrel, + self.locreloff, + self.nlocrel, + ) = data.get_n_uint32(18) def __str__(self): s = Mach.LoadCommand.__str__(self) @@ -1430,27 +1622,44 @@ # s += "locreloff = %#8.8x, nlocrel = %u" % (self.locreloff, # self.nlocrel) s += "ilocalsym = %-10u, nlocalsym = %u\n" % ( - self.ilocalsym, self.nlocalsym) - s += " iextdefsym = %-10u, nextdefsym = %u\n" % ( - self.iextdefsym, self.nextdefsym) - s += " iundefsym = %-10u, nundefsym = %u\n" % ( - self.iundefsym, self.nundefsym) - s += " tocoff = %#8.8x, ntoc = %u\n" % ( - self.tocoff, self.ntoc) - s += " modtaboff = %#8.8x, nmodtab = %u\n" % ( - self.modtaboff, self.nmodtab) - s += " extrefsymoff = %#8.8x, nextrefsyms = %u\n" % ( - self.extrefsymoff, self.nextrefsyms) - s += " indirectsymoff = %#8.8x, nindirectsyms = %u\n" % ( - self.indirectsymoff, self.nindirectsyms) - s += " extreloff = %#8.8x, nextrel = %u\n" % ( - self.extreloff, self.nextrel) - s += " locreloff = %#8.8x, nlocrel = %u" % ( - self.locreloff, self.nlocrel) + self.ilocalsym, + self.nlocalsym, + ) + s += ( + " iextdefsym = %-10u, nextdefsym = %u\n" + % (self.iextdefsym, self.nextdefsym) + ) + s += ( + " iundefsym = %-10u, nundefsym = %u\n" + % (self.iundefsym, self.nundefsym) + ) + s += ( + " tocoff = %#8.8x, ntoc = %u\n" + % (self.tocoff, self.ntoc) + ) + s += ( + " modtaboff = %#8.8x, nmodtab = %u\n" + % (self.modtaboff, self.nmodtab) + ) + s += ( + " extrefsymoff = %#8.8x, nextrefsyms = %u\n" + % (self.extrefsymoff, self.nextrefsyms) + ) + s += ( + " indirectsymoff = %#8.8x, nindirectsyms = %u\n" + % (self.indirectsymoff, self.nindirectsyms) + ) + s += ( + " extreloff = %#8.8x, nextrel = %u\n" + % (self.extreloff, self.nextrel) + ) + s += ( + " locreloff = %#8.8x, nlocrel = %u" + % (self.locreloff, self.nlocrel) + ) return s class SymtabLoadCommand(LoadCommand): - def __init__(self, lc): Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off) self.symoff = 0 @@ -1460,26 +1669,28 @@ def unpack(self, mach_file, data): byte_order_char = mach_file.magic.get_byte_order() - self.symoff, self.nsyms, self.stroff, self.strsize = data.get_n_uint32( - 4) + self.symoff, self.nsyms, self.stroff, self.strsize = data.get_n_uint32(4) def __str__(self): s = Mach.LoadCommand.__str__(self) s += "symoff = %#8.8x, nsyms = %u, stroff = %#8.8x, strsize = %u" % ( - self.symoff, self.nsyms, self.stroff, self.strsize) + self.symoff, + self.nsyms, + self.stroff, + self.strsize, + ) return s class UUIDLoadCommand(LoadCommand): - def __init__(self, lc): Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off) self.uuid = None def unpack(self, mach_file, data): uuid_data = data.get_n_uint8(16) - uuid_str = '' + uuid_str = "" for byte in uuid_data: - uuid_str += '%2.2x' % byte + uuid_str += "%2.2x" % byte self.uuid = uuid.UUID(uuid_str) mach_file.uuid = self.uuid @@ -1489,7 +1700,6 @@ return s class DataBlobLoadCommand(LoadCommand): - def __init__(self, lc): Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off) self.dataoff = 0 @@ -1501,12 +1711,10 @@ def __str__(self): s = Mach.LoadCommand.__str__(self) - s += "dataoff = %#8.8x, datasize = %u" % ( - self.dataoff, self.datasize) + s += "dataoff = %#8.8x, datasize = %u" % (self.dataoff, self.datasize) return s class EncryptionInfoLoadCommand(LoadCommand): - def __init__(self, lc): Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off) self.cryptoff = 0 @@ -1520,11 +1728,14 @@ def __str__(self): s = Mach.LoadCommand.__str__(self) s += "file-range = [%#8.8x - %#8.8x), cryptsize = %u, cryptid = %u" % ( - self.cryptoff, self.cryptoff + self.cryptsize, self.cryptsize, self.cryptid) + self.cryptoff, + self.cryptoff + self.cryptsize, + self.cryptsize, + self.cryptid, + ) return s class SegmentLoadCommand(LoadCommand): - def __init__(self, lc): Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off) self.segname = None @@ -1539,15 +1750,22 @@ def unpack(self, mach_file, data): is_64 = self.command.get_enum_value() == LC_SEGMENT_64 - self.segname = data.get_fixed_length_c_string(16, '', True) + self.segname = data.get_fixed_length_c_string(16, "", True) if is_64: - self.vmaddr, self.vmsize, self.fileoff, self.filesize = data.get_n_uint64( - 4) + ( + self.vmaddr, + self.vmsize, + self.fileoff, + self.filesize, + ) = data.get_n_uint64(4) else: - self.vmaddr, self.vmsize, self.fileoff, self.filesize = data.get_n_uint32( - 4) - self.maxprot, self.initprot, self.nsects, self.flags = data.get_n_uint32( - 4) + ( + self.vmaddr, + self.vmsize, + self.fileoff, + self.filesize, + ) = data.get_n_uint32(4) + self.maxprot, self.initprot, self.nsects, self.flags = data.get_n_uint32(4) mach_file.segments.append(self) for i in range(self.nsects): section = Mach.Section() @@ -1559,50 +1777,60 @@ s = Mach.LoadCommand.__str__(self) if self.command.get_enum_value() == LC_SEGMENT: s += "%#8.8x %#8.8x %#8.8x %#8.8x " % ( - self.vmaddr, self.vmsize, self.fileoff, self.filesize) + self.vmaddr, + self.vmsize, + self.fileoff, + self.filesize, + ) else: s += "%#16.16x %#16.16x %#16.16x %#16.16x " % ( - self.vmaddr, self.vmsize, self.fileoff, self.filesize) - s += "%s %s %3u %#8.8x" % (vm_prot_names[self.maxprot], vm_prot_names[ - self.initprot], self.nsects, self.flags) - s += ' ' + self.segname + self.vmaddr, + self.vmsize, + self.fileoff, + self.filesize, + ) + s += "%s %s %3u %#8.8x" % ( + vm_prot_names[self.maxprot], + vm_prot_names[self.initprot], + self.nsects, + self.flags, + ) + s += " " + self.segname return s class NList: - class Type: - class Stab(dict_utils.Enum): enum = { - 'N_GSYM': N_GSYM, - 'N_FNAME': N_FNAME, - 'N_FUN': N_FUN, - 'N_STSYM': N_STSYM, - 'N_LCSYM': N_LCSYM, - 'N_BNSYM': N_BNSYM, - 'N_OPT': N_OPT, - 'N_RSYM': N_RSYM, - 'N_SLINE': N_SLINE, - 'N_ENSYM': N_ENSYM, - 'N_SSYM': N_SSYM, - 'N_SO': N_SO, - 'N_OSO': N_OSO, - 'N_LSYM': N_LSYM, - 'N_BINCL': N_BINCL, - 'N_SOL': N_SOL, - 'N_PARAMS': N_PARAMS, - 'N_VERSION': N_VERSION, - 'N_OLEVEL': N_OLEVEL, - 'N_PSYM': N_PSYM, - 'N_EINCL': N_EINCL, - 'N_ENTRY': N_ENTRY, - 'N_LBRAC': N_LBRAC, - 'N_EXCL': N_EXCL, - 'N_RBRAC': N_RBRAC, - 'N_BCOMM': N_BCOMM, - 'N_ECOMM': N_ECOMM, - 'N_ECOML': N_ECOML, - 'N_LENG': N_LENG + "N_GSYM": N_GSYM, + "N_FNAME": N_FNAME, + "N_FUN": N_FUN, + "N_STSYM": N_STSYM, + "N_LCSYM": N_LCSYM, + "N_BNSYM": N_BNSYM, + "N_OPT": N_OPT, + "N_RSYM": N_RSYM, + "N_SLINE": N_SLINE, + "N_ENSYM": N_ENSYM, + "N_SSYM": N_SSYM, + "N_SO": N_SO, + "N_OSO": N_OSO, + "N_LSYM": N_LSYM, + "N_BINCL": N_BINCL, + "N_SOL": N_SOL, + "N_PARAMS": N_PARAMS, + "N_VERSION": N_VERSION, + "N_OLEVEL": N_OLEVEL, + "N_PSYM": N_PSYM, + "N_EINCL": N_EINCL, + "N_ENTRY": N_ENTRY, + "N_LBRAC": N_LBRAC, + "N_EXCL": N_EXCL, + "N_RBRAC": N_RBRAC, + "N_BCOMM": N_BCOMM, + "N_ECOMM": N_ECOMM, + "N_ECOML": N_ECOML, + "N_LENG": N_LENG, } def __init__(self, magic=0): @@ -1615,26 +1843,26 @@ n_type = self.value if n_type & N_STAB: stab = Mach.NList.Type.Stab(self.value) - return '%s' % stab + return "%s" % stab else: type = self.value & N_TYPE - type_str = '' + type_str = "" if type == N_UNDF: - type_str = 'N_UNDF' + type_str = "N_UNDF" elif type == N_ABS: - type_str = 'N_ABS ' + type_str = "N_ABS " elif type == N_SECT: - type_str = 'N_SECT' + type_str = "N_SECT" elif type == N_PBUD: - type_str = 'N_PBUD' + type_str = "N_PBUD" elif type == N_INDR: - type_str = 'N_INDR' + type_str = "N_INDR" else: type_str = "??? (%#2.2x)" % type if n_type & N_PEXT: - type_str += ' | PEXT' + type_str += " | PEXT" if n_type & N_EXT: - type_str += ' | EXT ' + type_str += " | EXT " return type_str def __init__(self): @@ -1656,159 +1884,180 @@ else: self.value = data.get_uint32() data.push_offset_and_seek( - mach_file.file_off + - symtab_lc.stroff + - self.name_offset) + mach_file.file_off + symtab_lc.stroff + self.name_offset + ) # print "get string for symbol[%u]" % self.index self.name = data.get_c_string() data.pop_offset_and_seek() def __str__(self): - name_display = '' + name_display = "" if len(self.name): name_display = ' "%s"' % self.name - return '%#8.8x %#2.2x (%-20s) %#2.2x %#4.4x %16.16x%s' % (self.name_offset, - self.type.value, self.type, self.sect_idx, self.desc, self.value, name_display) + return "%#8.8x %#2.2x (%-20s) %#2.2x %#4.4x %16.16x%s" % ( + self.name_offset, + self.type.value, + self.type, + self.sect_idx, + self.desc, + self.value, + name_display, + ) class Interactive(cmd.Cmd): - '''Interactive command interpreter to mach-o files.''' + """Interactive command interpreter to mach-o files.""" def __init__(self, mach, options): cmd.Cmd.__init__(self) - self.intro = 'Interactive mach-o command interpreter' - self.prompt = 'mach-o: %s %% ' % mach.path + self.intro = "Interactive mach-o command interpreter" + self.prompt = "mach-o: %s %% " % mach.path self.mach = mach self.options = options def default(self, line): - '''Catch all for unknown command, which will exit the interpreter.''' + """Catch all for unknown command, which will exit the interpreter.""" print("uknown command: %s" % line) return True def do_q(self, line): - '''Quit command''' + """Quit command""" return True def do_quit(self, line): - '''Quit command''' + """Quit command""" return True def do_header(self, line): - '''Dump mach-o file headers''' + """Dump mach-o file headers""" self.mach.dump_header(True, self.options) return False def do_load(self, line): - '''Dump all mach-o load commands''' + """Dump all mach-o load commands""" self.mach.dump_load_commands(True, self.options) return False def do_sections(self, line): - '''Dump all mach-o sections''' + """Dump all mach-o sections""" self.mach.dump_sections(True, self.options) return False def do_symtab(self, line): - '''Dump all mach-o symbols in the symbol table''' + """Dump all mach-o symbols in the symbol table""" self.mach.dump_symtab(True, self.options) return False -if __name__ == '__main__': + +if __name__ == "__main__": parser = optparse.OptionParser( - description='A script that parses skinny and universal mach-o files.') + description="A script that parses skinny and universal mach-o files." + ) parser.add_option( - '--arch', - '-a', - type='string', - metavar='arch', - dest='archs', - action='append', - help='specify one or more architectures by name') + "--arch", + "-a", + type="string", + metavar="arch", + dest="archs", + action="append", + help="specify one or more architectures by name", + ) parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', - help='display verbose debug info', - default=False) + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="display verbose debug info", + default=False, + ) parser.add_option( - '-H', - '--header', - action='store_true', - dest='dump_header', - help='dump the mach-o file header', - default=False) + "-H", + "--header", + action="store_true", + dest="dump_header", + help="dump the mach-o file header", + default=False, + ) parser.add_option( - '-l', - '--load-commands', - action='store_true', - dest='dump_load_commands', - help='dump the mach-o load commands', - default=False) + "-l", + "--load-commands", + action="store_true", + dest="dump_load_commands", + help="dump the mach-o load commands", + default=False, + ) parser.add_option( - '-s', - '--symtab', - action='store_true', - dest='dump_symtab', - help='dump the mach-o symbol table', - default=False) + "-s", + "--symtab", + action="store_true", + dest="dump_symtab", + help="dump the mach-o symbol table", + default=False, + ) parser.add_option( - '-S', - '--sections', - action='store_true', - dest='dump_sections', - help='dump the mach-o sections', - default=False) + "-S", + "--sections", + action="store_true", + dest="dump_sections", + help="dump the mach-o sections", + default=False, + ) parser.add_option( - '--section', - type='string', - metavar='sectname', - dest='section_names', - action='append', - help='Specify one or more section names to dump', - default=[]) + "--section", + type="string", + metavar="sectname", + dest="section_names", + action="append", + help="Specify one or more section names to dump", + default=[], + ) parser.add_option( - '-o', - '--out', - type='string', - dest='outfile', - help='Used in conjunction with the --section=NAME option to save a single section\'s data to disk.', - default=False) + "-o", + "--out", + type="string", + dest="outfile", + help="Used in conjunction with the --section=NAME option to save a single section's data to disk.", + default=False, + ) parser.add_option( - '-i', - '--interactive', - action='store_true', - dest='interactive', - help='enable interactive mode', - default=False) + "-i", + "--interactive", + action="store_true", + dest="interactive", + help="enable interactive mode", + default=False, + ) parser.add_option( - '-m', - '--mangled', - action='store_true', - dest='find_mangled', - help='dump all mangled names in a mach file', - default=False) + "-m", + "--mangled", + action="store_true", + dest="find_mangled", + help="dump all mangled names in a mach file", + default=False, + ) parser.add_option( - '-c', - '--compare', - action='store_true', - dest='compare', - help='compare two mach files', - default=False) + "-c", + "--compare", + action="store_true", + dest="compare", + help="compare two mach files", + default=False, + ) parser.add_option( - '-M', - '--extract-modules', - action='store_true', - dest='extract_modules', - help='Extract modules from file', - default=False) + "-M", + "--extract-modules", + action="store_true", + dest="extract_modules", + help="Extract modules from file", + default=False, + ) parser.add_option( - '-C', - '--count', - type='int', - dest='max_count', - help='Sets the max byte count when dumping section data', - default=-1) + "-C", + "--count", + type="int", + dest="max_count", + help="Sets the max byte count when dumping section data", + default=-1, + ) (options, mach_files) = parser.parse_args() if options.extract_modules: @@ -1816,7 +2065,9 @@ print("error: can't use --section option with the --extract-modules option") exit(1) if not options.outfile: - print("error: the --output=FILE option must be specified with the --extract-modules option") + print( + "error: the --output=FILE option must be specified with the --extract-modules option" + ) exit(1) options.section_names.append("__apple_ast") if options.compare: @@ -1827,14 +2078,21 @@ mach_b.parse(mach_files[1]) mach_a.compare(mach_b) else: - print('error: --compare takes two mach files as arguments') + print("error: --compare takes two mach files as arguments") else: - if not (options.dump_header or options.dump_load_commands or options.dump_symtab or options.dump_sections or options.find_mangled or options.section_names): + if not ( + options.dump_header + or options.dump_load_commands + or options.dump_symtab + or options.dump_sections + or options.find_mangled + or options.section_names + ): options.dump_header = True options.dump_load_commands = True if options.verbose: - print('options', options) - print('mach_files', mach_files) + print("options", options) + print("mach_files", mach_files) for path in mach_files: mach = Mach() mach.parse(path) diff --git a/lldb/examples/python/memory.py b/lldb/examples/python/memory.py --- a/lldb/examples/python/memory.py +++ b/lldb/examples/python/memory.py @@ -1,13 +1,13 @@ #!/usr/bin/env python -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # Be sure to add the python path that points to the LLDB shared library. # # # To use this in the embedded python interpreter using "lldb" just # import it with the full path using the "command script import" # command # (lldb) command script import /path/to/cmdtemplate.py -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- import platform import os @@ -22,18 +22,21 @@ lldb_python_dirs = list() # lldb is not in the PYTHONPATH, try some defaults for the current platform platform_system = platform.system() - if platform_system == 'Darwin': + if platform_system == "Darwin": # On Darwin, try the currently selected Xcode directory xcode_dir = subprocess.check_output("xcode-select --print-path", shell=True) if xcode_dir: lldb_python_dirs.append( os.path.realpath( - xcode_dir + - '/../SharedFrameworks/LLDB.framework/Resources/Python')) + xcode_dir + "/../SharedFrameworks/LLDB.framework/Resources/Python" + ) + ) lldb_python_dirs.append( - xcode_dir + '/Library/PrivateFrameworks/LLDB.framework/Resources/Python') + xcode_dir + "/Library/PrivateFrameworks/LLDB.framework/Resources/Python" + ) lldb_python_dirs.append( - '/System/Library/PrivateFrameworks/LLDB.framework/Resources/Python') + "/System/Library/PrivateFrameworks/LLDB.framework/Resources/Python" + ) success = False for lldb_python_dir in lldb_python_dirs: if os.path.exists(lldb_python_dir): @@ -48,7 +51,9 @@ success = True break if not success: - print("error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly") + print( + "error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly" + ) sys.exit(1) import optparse @@ -61,120 +66,126 @@ def append_data_callback(option, opt_str, value, parser): if opt_str == "--uint8": int8 = int(value, 0) - parser.values.data += struct.pack('1B', int8) + parser.values.data += struct.pack("1B", int8) if opt_str == "--uint16": int16 = int(value, 0) - parser.values.data += struct.pack('1H', int16) + parser.values.data += struct.pack("1H", int16) if opt_str == "--uint32": int32 = int(value, 0) - parser.values.data += struct.pack('1I', int32) + parser.values.data += struct.pack("1I", int32) if opt_str == "--uint64": int64 = int(value, 0) - parser.values.data += struct.pack('1Q', int64) + parser.values.data += struct.pack("1Q", int64) if opt_str == "--int8": int8 = int(value, 0) - parser.values.data += struct.pack('1b', int8) + parser.values.data += struct.pack("1b", int8) if opt_str == "--int16": int16 = int(value, 0) - parser.values.data += struct.pack('1h', int16) + parser.values.data += struct.pack("1h", int16) if opt_str == "--int32": int32 = int(value, 0) - parser.values.data += struct.pack('1i', int32) + parser.values.data += struct.pack("1i", int32) if opt_str == "--int64": int64 = int(value, 0) - parser.values.data += struct.pack('1q', int64) + parser.values.data += struct.pack("1q", int64) def create_memfind_options(): usage = "usage: %prog [options] STARTADDR [ENDADDR]" - description = '''This command can find data in a specified address range. + description = """This command can find data in a specified address range. Options are used to specify the data that is to be looked for and the options can be specified multiple times to look for longer streams of data. -''' - parser = optparse.OptionParser( - description=description, - prog='memfind', - usage=usage) +""" + parser = optparse.OptionParser(description=description, prog="memfind", usage=usage) parser.add_option( - '-s', - '--size', - type='int', - metavar='BYTESIZE', - dest='size', - help='Specify the byte size to search.', - default=0) + "-s", + "--size", + type="int", + metavar="BYTESIZE", + dest="size", + help="Specify the byte size to search.", + default=0, + ) parser.add_option( - '--int8', + "--int8", action="callback", callback=append_data_callback, - type='string', - metavar='INT', - dest='data', - help='Specify a 8 bit signed integer value to search for in memory.', - default='') + type="string", + metavar="INT", + dest="data", + help="Specify a 8 bit signed integer value to search for in memory.", + default="", + ) parser.add_option( - '--int16', + "--int16", action="callback", callback=append_data_callback, - type='string', - metavar='INT', - dest='data', - help='Specify a 16 bit signed integer value to search for in memory.', - default='') + type="string", + metavar="INT", + dest="data", + help="Specify a 16 bit signed integer value to search for in memory.", + default="", + ) parser.add_option( - '--int32', + "--int32", action="callback", callback=append_data_callback, - type='string', - metavar='INT', - dest='data', - help='Specify a 32 bit signed integer value to search for in memory.', - default='') + type="string", + metavar="INT", + dest="data", + help="Specify a 32 bit signed integer value to search for in memory.", + default="", + ) parser.add_option( - '--int64', + "--int64", action="callback", callback=append_data_callback, - type='string', - metavar='INT', - dest='data', - help='Specify a 64 bit signed integer value to search for in memory.', - default='') + type="string", + metavar="INT", + dest="data", + help="Specify a 64 bit signed integer value to search for in memory.", + default="", + ) parser.add_option( - '--uint8', + "--uint8", action="callback", callback=append_data_callback, - type='string', - metavar='INT', - dest='data', - help='Specify a 8 bit unsigned integer value to search for in memory.', - default='') + type="string", + metavar="INT", + dest="data", + help="Specify a 8 bit unsigned integer value to search for in memory.", + default="", + ) parser.add_option( - '--uint16', + "--uint16", action="callback", callback=append_data_callback, - type='string', - metavar='INT', - dest='data', - help='Specify a 16 bit unsigned integer value to search for in memory.', - default='') + type="string", + metavar="INT", + dest="data", + help="Specify a 16 bit unsigned integer value to search for in memory.", + default="", + ) parser.add_option( - '--uint32', + "--uint32", action="callback", callback=append_data_callback, - type='string', - metavar='INT', - dest='data', - help='Specify a 32 bit unsigned integer value to search for in memory.', - default='') + type="string", + metavar="INT", + dest="data", + help="Specify a 32 bit unsigned integer value to search for in memory.", + default="", + ) parser.add_option( - '--uint64', + "--uint64", action="callback", callback=append_data_callback, - type='string', - metavar='INT', - dest='data', - help='Specify a 64 bit unsigned integer value to search for in memory.', - default='') + type="string", + metavar="INT", + dest="data", + help="Specify a 64 bit unsigned integer value to search for in memory.", + default="", + ) return parser @@ -209,7 +220,8 @@ print_error( "error: --size must be specified if there is no ENDADDR argument", True, - result) + result, + ) return start_addr = int(args[0], 0) elif num_args == 2: @@ -217,14 +229,17 @@ print_error( "error: --size can't be specified with an ENDADDR argument", True, - result) + result, + ) return start_addr = int(args[0], 0) end_addr = int(args[1], 0) if start_addr >= end_addr: print_error( - "error: inavlid memory range [%#x - %#x)" % - (start_addr, end_addr), True, result) + "error: inavlid memory range [%#x - %#x)" % (start_addr, end_addr), + True, + result, + ) return options.size = end_addr - start_addr else: @@ -232,45 +247,52 @@ return if not options.data: - print('error: no data specified to search for', file=result) + print("error: no data specified to search for", file=result) return if not target: - print('error: invalid target', file=result) + print("error: invalid target", file=result) return process = target.process if not process: - print('error: invalid process', file=result) + print("error: invalid process", file=result) return error = lldb.SBError() bytes = process.ReadMemory(start_addr, options.size, error) if error.Success(): num_matches = 0 - print("Searching memory range [%#x - %#x) for" % ( - start_addr, end_addr), end=' ', file=result) + print( + "Searching memory range [%#x - %#x) for" % (start_addr, end_addr), + end=" ", + file=result, + ) for byte in options.data: - print('%2.2x' % ord(byte), end=' ', file=result) + print("%2.2x" % ord(byte), end=" ", file=result) print(file=result) match_index = string.find(bytes, options.data) while match_index != -1: num_matches = num_matches + 1 - print('%#x: %#x + %u' % (start_addr + - match_index, start_addr, match_index), file=result) + print( + "%#x: %#x + %u" % (start_addr + match_index, start_addr, match_index), + file=result, + ) match_index = string.find(bytes, options.data, match_index + 1) if num_matches == 0: print("error: no matches found", file=result) else: - print('error: %s' % (error.GetCString()), file=result) + print("error: %s" % (error.GetCString()), file=result) + +if __name__ == "__main__": + print( + "error: this script is designed to be used within the embedded script interpreter in LLDB" + ) -if __name__ == '__main__': - print('error: this script is designed to be used within the embedded script interpreter in LLDB') def __lldb_init_module(debugger, internal_dict): memfind_command.__doc__ = create_memfind_options().format_help() - debugger.HandleCommand( - 'command script add -o -f memory.memfind_command memfind') + debugger.HandleCommand("command script add -o -f memory.memfind_command memfind") print('"memfind" command installed, use the "--help" option for detailed help') diff --git a/lldb/examples/python/operating_system.py b/lldb/examples/python/operating_system.py --- a/lldb/examples/python/operating_system.py +++ b/lldb/examples/python/operating_system.py @@ -8,10 +8,10 @@ """Class that provides data for an instance of a LLDB 'OperatingSystemPython' plug-in class""" def __init__(self, process): - '''Initialization needs a valid.SBProcess object. + """Initialization needs a valid.SBProcess object. This plug-in will get created after a live process is valid and has stopped for the - first time.''' + first time.""" self.process = None self.registers = None self.threads = None @@ -28,11 +28,12 @@ def create_thread(self, tid, context): if tid == 0x444444444: thread_info = { - 'tid': tid, - 'name': 'four', - 'queue': 'queue4', - 'state': 'stopped', - 'stop_reason': 'none'} + "tid": tid, + "name": "four", + "queue": "queue4", + "state": "stopped", + "stop_reason": "none", + } self.threads.append(thread_info) return thread_info return None @@ -56,22 +57,30 @@ # in memory. Don't specify this if your register layout in memory doesn't match the layout # described by the dictionary returned from a call to the # get_register_info() method. - self.threads = [{'tid': 0x111111111, - 'name': 'one', - 'queue': 'queue1', - 'state': 'stopped', - 'stop_reason': 'breakpoint'}, - {'tid': 0x222222222, - 'name': 'two', - 'queue': 'queue2', - 'state': 'stopped', - 'stop_reason': 'none'}, - {'tid': 0x333333333, - 'name': 'three', - 'queue': 'queue3', - 'state': 'stopped', - 'stop_reason': 'trace', - 'register_data_addr': 0x100000000}] + self.threads = [ + { + "tid": 0x111111111, + "name": "one", + "queue": "queue1", + "state": "stopped", + "stop_reason": "breakpoint", + }, + { + "tid": 0x222222222, + "name": "two", + "queue": "queue2", + "state": "stopped", + "stop_reason": "none", + }, + { + "tid": 0x333333333, + "name": "three", + "queue": "queue3", + "state": "stopped", + "stop_reason": "trace", + "register_data_addr": 0x100000000, + }, + ] return self.threads def get_register_info(self): @@ -79,38 +88,239 @@ self.registers = dict() triple = self.process.target.triple if triple: - arch = triple.split('-')[0] - if arch == 'x86_64': - self.registers['sets'] = ['GPR', 'FPU', 'EXC'] - self.registers['registers'] = [ - {'name': 'rax', 'bitsize': 64, 'offset': 0, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 0, 'dwarf': 0}, - {'name': 'rbx', 'bitsize': 64, 'offset': 8, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 3, 'dwarf': 3}, - {'name': 'rcx', 'bitsize': 64, 'offset': 16, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 2, 'dwarf': 2, 'generic': 'arg4', 'alt-name': 'arg4', }, - {'name': 'rdx', 'bitsize': 64, 'offset': 24, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 1, 'dwarf': 1, 'generic': 'arg3', 'alt-name': 'arg3', }, - {'name': 'rdi', 'bitsize': 64, 'offset': 32, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 5, 'dwarf': 5, 'generic': 'arg1', 'alt-name': 'arg1', }, - {'name': 'rsi', 'bitsize': 64, 'offset': 40, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 4, 'dwarf': 4, 'generic': 'arg2', 'alt-name': 'arg2', }, - {'name': 'rbp', 'bitsize': 64, 'offset': 48, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 6, 'dwarf': 6, 'generic': 'fp', 'alt-name': 'fp', }, - {'name': 'rsp', 'bitsize': 64, 'offset': 56, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 7, 'dwarf': 7, 'generic': 'sp', 'alt-name': 'sp', }, - {'name': 'r8', 'bitsize': 64, 'offset': 64, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 8, 'dwarf': 8, 'generic': 'arg5', 'alt-name': 'arg5', }, - {'name': 'r9', 'bitsize': 64, 'offset': 72, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 9, 'dwarf': 9, 'generic': 'arg6', 'alt-name': 'arg6', }, - {'name': 'r10', 'bitsize': 64, 'offset': 80, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 10, 'dwarf': 10}, - {'name': 'r11', 'bitsize': 64, 'offset': 88, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 11, 'dwarf': 11}, - {'name': 'r12', 'bitsize': 64, 'offset': 96, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 12, 'dwarf': 12}, - {'name': 'r13', 'bitsize': 64, 'offset': 104, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 13, 'dwarf': 13}, - {'name': 'r14', 'bitsize': 64, 'offset': 112, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 14, 'dwarf': 14}, - {'name': 'r15', 'bitsize': 64, 'offset': 120, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 15, 'dwarf': 15}, - {'name': 'rip', 'bitsize': 64, 'offset': 128, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 16, 'dwarf': 16, 'generic': 'pc', 'alt-name': 'pc'}, - {'name': 'rflags', 'bitsize': 64, 'offset': 136, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'generic': 'flags', 'alt-name': 'flags'}, - {'name': 'cs', 'bitsize': 64, 'offset': 144, 'encoding': 'uint', 'format': 'hex', 'set': 0}, - {'name': 'fs', 'bitsize': 64, 'offset': 152, 'encoding': 'uint', 'format': 'hex', 'set': 0}, - {'name': 'gs', 'bitsize': 64, 'offset': 160, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + arch = triple.split("-")[0] + if arch == "x86_64": + self.registers["sets"] = ["GPR", "FPU", "EXC"] + self.registers["registers"] = [ + { + "name": "rax", + "bitsize": 64, + "offset": 0, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 0, + "dwarf": 0, + }, + { + "name": "rbx", + "bitsize": 64, + "offset": 8, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 3, + "dwarf": 3, + }, + { + "name": "rcx", + "bitsize": 64, + "offset": 16, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 2, + "dwarf": 2, + "generic": "arg4", + "alt-name": "arg4", + }, + { + "name": "rdx", + "bitsize": 64, + "offset": 24, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 1, + "dwarf": 1, + "generic": "arg3", + "alt-name": "arg3", + }, + { + "name": "rdi", + "bitsize": 64, + "offset": 32, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 5, + "dwarf": 5, + "generic": "arg1", + "alt-name": "arg1", + }, + { + "name": "rsi", + "bitsize": 64, + "offset": 40, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 4, + "dwarf": 4, + "generic": "arg2", + "alt-name": "arg2", + }, + { + "name": "rbp", + "bitsize": 64, + "offset": 48, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 6, + "dwarf": 6, + "generic": "fp", + "alt-name": "fp", + }, + { + "name": "rsp", + "bitsize": 64, + "offset": 56, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 7, + "dwarf": 7, + "generic": "sp", + "alt-name": "sp", + }, + { + "name": "r8", + "bitsize": 64, + "offset": 64, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 8, + "dwarf": 8, + "generic": "arg5", + "alt-name": "arg5", + }, + { + "name": "r9", + "bitsize": 64, + "offset": 72, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 9, + "dwarf": 9, + "generic": "arg6", + "alt-name": "arg6", + }, + { + "name": "r10", + "bitsize": 64, + "offset": 80, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 10, + "dwarf": 10, + }, + { + "name": "r11", + "bitsize": 64, + "offset": 88, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 11, + "dwarf": 11, + }, + { + "name": "r12", + "bitsize": 64, + "offset": 96, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 12, + "dwarf": 12, + }, + { + "name": "r13", + "bitsize": 64, + "offset": 104, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 13, + "dwarf": 13, + }, + { + "name": "r14", + "bitsize": 64, + "offset": 112, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 14, + "dwarf": 14, + }, + { + "name": "r15", + "bitsize": 64, + "offset": 120, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 15, + "dwarf": 15, + }, + { + "name": "rip", + "bitsize": 64, + "offset": 128, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 16, + "dwarf": 16, + "generic": "pc", + "alt-name": "pc", + }, + { + "name": "rflags", + "bitsize": 64, + "offset": 136, + "encoding": "uint", + "format": "hex", + "set": 0, + "generic": "flags", + "alt-name": "flags", + }, + { + "name": "cs", + "bitsize": 64, + "offset": 144, + "encoding": "uint", + "format": "hex", + "set": 0, + }, + { + "name": "fs", + "bitsize": 64, + "offset": 152, + "encoding": "uint", + "format": "hex", + "set": 0, + }, + { + "name": "gs", + "bitsize": 64, + "offset": 160, + "encoding": "uint", + "format": "hex", + "set": 0, + }, ] return self.registers def get_register_data(self, tid): if tid == 0x111111111: return struct.pack( - '21Q', + "21Q", 1, 2, 3, @@ -131,10 +341,11 @@ 18, 19, 20, - 21) + 21, + ) elif tid == 0x222222222: return struct.pack( - '21Q', + "21Q", 11, 12, 13, @@ -155,10 +366,11 @@ 118, 119, 120, - 121) + 121, + ) elif tid == 0x333333333: return struct.pack( - '21Q', + "21Q", 21, 22, 23, @@ -179,10 +391,11 @@ 218, 219, 220, - 221) + 221, + ) elif tid == 0x444444444: return struct.pack( - '21Q', + "21Q", 31, 32, 33, @@ -203,10 +416,11 @@ 318, 319, 320, - 321) + 321, + ) else: return struct.pack( - '21Q', + "21Q", 41, 42, 43, @@ -227,5 +441,6 @@ 418, 419, 420, - 421) + 421, + ) return None diff --git a/lldb/examples/python/performance.py b/lldb/examples/python/performance.py --- a/lldb/examples/python/performance.py +++ b/lldb/examples/python/performance.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # Be sure to add the python path that points to the LLDB shared library. # On MacOSX csh, tcsh: # setenv PYTHONPATH /Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python # On MacOSX sh, bash: # export PYTHONPATH=/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- import optparse import os @@ -18,9 +18,9 @@ import time import types -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # Code that auto imports LLDB -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- try: # Just try for LLDB in case PYTHONPATH is already correctly setup import lldb @@ -28,18 +28,21 @@ lldb_python_dirs = list() # lldb is not in the PYTHONPATH, try some defaults for the current platform platform_system = platform.system() - if platform_system == 'Darwin': + if platform_system == "Darwin": # On Darwin, try the currently selected Xcode directory xcode_dir = subprocess.check_output("xcode-select --print-path", shell=True) if xcode_dir: lldb_python_dirs.append( os.path.realpath( - xcode_dir + - '/../SharedFrameworks/LLDB.framework/Resources/Python')) + xcode_dir + "/../SharedFrameworks/LLDB.framework/Resources/Python" + ) + ) lldb_python_dirs.append( - xcode_dir + '/Library/PrivateFrameworks/LLDB.framework/Resources/Python') + xcode_dir + "/Library/PrivateFrameworks/LLDB.framework/Resources/Python" + ) lldb_python_dirs.append( - '/System/Library/PrivateFrameworks/LLDB.framework/Resources/Python') + "/System/Library/PrivateFrameworks/LLDB.framework/Resources/Python" + ) success = False for lldb_python_dir in lldb_python_dirs: if os.path.exists(lldb_python_dir): @@ -54,12 +57,13 @@ success = True break if not success: - print("error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly") + print( + "error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly" + ) sys.exit(1) class Timer: - def __enter__(self): self.start = time.clock() return self @@ -77,11 +81,12 @@ self.callback_owner = callback_owner def ThreadStopped(self, thread): - assert False, "performance.Action.ThreadStopped(self, thread) must be overridden in a subclass" - + assert ( + False + ), "performance.Action.ThreadStopped(self, thread) must be overridden in a subclass" -class PlanCompleteAction (Action): +class PlanCompleteAction(Action): def __init__(self, callback=None, callback_owner=None): Action.__init__(self, callback, callback_owner) @@ -96,17 +101,17 @@ return False -class BreakpointAction (Action): - +class BreakpointAction(Action): def __init__( - self, - callback=None, - callback_owner=None, - name=None, - module=None, - file=None, - line=None, - breakpoint=None): + self, + callback=None, + callback_owner=None, + name=None, + module=None, + file=None, + line=None, + breakpoint=None, + ): Action.__init__(self, callback, callback_owner) self.modules = lldb.SBFileSpecList() self.files = lldb.SBFileSpecList() @@ -118,8 +123,7 @@ if module: if isinstance(module, types.ListType): for module_path in module: - self.modules.Append( - lldb.SBFileSpec(module_path, False)) + self.modules.Append(lldb.SBFileSpec(module_path, False)) elif isinstance(module, types.StringTypes): self.modules.Append(lldb.SBFileSpec(module, False)) if name: @@ -132,12 +136,12 @@ elif isinstance(file, types.StringTypes): self.files.Append(lldb.SBFileSpec(file, False)) self.breakpoints.append( - self.target.BreakpointCreateByName( - name, self.modules, self.files)) + self.target.BreakpointCreateByName(name, self.modules, self.files) + ) elif file and line: self.breakpoints.append( - self.target.BreakpointCreateByLocation( - file, line)) + self.target.BreakpointCreateByLocation(file, line) + ) def ThreadStopped(self, thread): if thread.GetStopReason() == lldb.eStopReasonBreakpoint: @@ -181,8 +185,11 @@ if not error.Success(): print("error: %s" % error.GetCString()) if self.process: - self.process.GetBroadcaster().AddListener(self.listener, - lldb.SBProcess.eBroadcastBitStateChanged | lldb.SBProcess.eBroadcastBitInterrupt) + self.process.GetBroadcaster().AddListener( + self.listener, + lldb.SBProcess.eBroadcastBitStateChanged + | lldb.SBProcess.eBroadcastBitInterrupt, + ) return True return False @@ -197,10 +204,23 @@ print("event = %s" % (lldb.SBDebugger.StateAsCString(state))) if lldb.SBProcess.GetRestartedFromEvent(process_event): continue - if state == lldb.eStateInvalid or state == lldb.eStateDetached or state == lldb.eStateCrashed or state == lldb.eStateUnloaded or state == lldb.eStateExited: + if ( + state == lldb.eStateInvalid + or state == lldb.eStateDetached + or state == lldb.eStateCrashed + or state == lldb.eStateUnloaded + or state == lldb.eStateExited + ): event = process_event self.done = True - elif state == lldb.eStateConnected or state == lldb.eStateAttaching or state == lldb.eStateLaunching or state == lldb.eStateRunning or state == lldb.eStateStepping or state == lldb.eStateSuspended: + elif ( + state == lldb.eStateConnected + or state == lldb.eStateAttaching + or state == lldb.eStateLaunching + or state == lldb.eStateRunning + or state == lldb.eStateStepping + or state == lldb.eStateSuspended + ): continue elif state == lldb.eStateStopped: event = process_event @@ -213,7 +233,11 @@ stop_reason = thread.GetStopReason() if self.verbose: - print("tid = %#x pc = %#x " % (thread.GetThreadID(), frame.GetPC()), end=' ') + print( + "tid = %#x pc = %#x " + % (thread.GetThreadID(), frame.GetPC()), + end=" ", + ) if stop_reason == lldb.eStopReasonNone: if self.verbose: print("none") @@ -248,25 +272,36 @@ elif stop_reason == lldb.eStopReasonWatchpoint: select_thread = True if self.verbose: - print("watchpoint id = %d" % (thread.GetStopReasonDataAtIndex(0))) + print( + "watchpoint id = %d" + % (thread.GetStopReasonDataAtIndex(0)) + ) elif stop_reason == lldb.eStopReasonSignal: select_thread = True if self.verbose: - print("signal %d" % (thread.GetStopReasonDataAtIndex(0))) + print( + "signal %d" + % (thread.GetStopReasonDataAtIndex(0)) + ) elif stop_reason == lldb.eStopReasonFork: if self.verbose: - print("fork pid = %d" % (thread.GetStopReasonDataAtIndex(0))) + print( + "fork pid = %d" + % (thread.GetStopReasonDataAtIndex(0)) + ) elif stop_reason == lldb.eStopReasonVFork: if self.verbose: - print("vfork pid = %d" % (thread.GetStopReasonDataAtIndex(0))) + print( + "vfork pid = %d" + % (thread.GetStopReasonDataAtIndex(0)) + ) elif stop_reason == lldb.eStopReasonVForkDone: if self.verbose: print("vfork done") if select_thread and not selected_thread: self.thread = thread - selected_thread = self.process.SetSelectedThread( - thread) + selected_thread = self.process.SetSelectedThread(thread) for action in self.user_actions: action.ThreadStopped(thread) @@ -279,7 +314,7 @@ class Measurement: - '''A class that encapsulates a measurement''' + """A class that encapsulates a measurement""" def __init__(self): object.__init__(self) @@ -289,7 +324,7 @@ class MemoryMeasurement(Measurement): - '''A class that can measure memory statistics for a process.''' + """A class that can measure memory statistics for a process.""" def __init__(self, pid): Measurement.__init__(self) @@ -304,33 +339,33 @@ "kshrd", "faults", "cow", - "pageins"] - self.command = "top -l 1 -pid %u -stats %s" % ( - self.pid, ",".join(self.stats)) + "pageins", + ] + self.command = "top -l 1 -pid %u -stats %s" % (self.pid, ",".join(self.stats)) self.value = dict() def Measure(self): output = subprocess.getoutput(self.command).split("\n")[-1] - values = re.split('[-+\s]+', output) - for (idx, stat) in enumerate(values): + values = re.split("[-+\s]+", output) + for idx, stat in enumerate(values): multiplier = 1 if stat: - if stat[-1] == 'K': + if stat[-1] == "K": multiplier = 1024 stat = stat[:-1] - elif stat[-1] == 'M': + elif stat[-1] == "M": multiplier = 1024 * 1024 stat = stat[:-1] - elif stat[-1] == 'G': + elif stat[-1] == "G": multiplier = 1024 * 1024 * 1024 - elif stat[-1] == 'T': + elif stat[-1] == "T": multiplier = 1024 * 1024 * 1024 * 1024 stat = stat[:-1] self.value[self.stats[idx]] = int(stat) * multiplier def __str__(self): - '''Dump the MemoryMeasurement current value''' - s = '' + """Dump the MemoryMeasurement current value""" + s = "" for key in self.value.keys(): if s: s += "\n" @@ -339,7 +374,6 @@ class TesterTestCase(TestCase): - def __init__(self): TestCase.__init__(self) self.verbose = True @@ -348,7 +382,10 @@ def BreakpointHit(self, thread): bp_id = thread.GetStopReasonDataAtIndex(0) loc_id = thread.GetStopReasonDataAtIndex(1) - print("Breakpoint %i.%i hit: %s" % (bp_id, loc_id, thread.process.target.FindBreakpointByID(bp_id))) + print( + "Breakpoint %i.%i hit: %s" + % (bp_id, loc_id, thread.process.target.FindBreakpointByID(bp_id)) + ) thread.StepOver() def PlanComplete(self, thread): @@ -365,19 +402,20 @@ if self.target: with Timer() as breakpoint_timer: bp = self.target.BreakpointCreateByName("main") - print( - 'Breakpoint time = %.03f sec.' % - breakpoint_timer.interval) + print("Breakpoint time = %.03f sec." % breakpoint_timer.interval) self.user_actions.append( BreakpointAction( breakpoint=bp, callback=TesterTestCase.BreakpointHit, - callback_owner=self)) + callback_owner=self, + ) + ) self.user_actions.append( PlanCompleteAction( - callback=TesterTestCase.PlanComplete, - callback_owner=self)) + callback=TesterTestCase.PlanComplete, callback_owner=self + ) + ) if self.Launch(): while not self.done: @@ -386,10 +424,10 @@ print("error: failed to launch process") else: print("error: failed to create target with '%s'" % (args[0])) - print('Total time = %.03f sec.' % total_time.interval) + print("Total time = %.03f sec." % total_time.interval) -if __name__ == '__main__': +if __name__ == "__main__": lldb.SBDebugger.Initialize() test = TesterTestCase() test.Run(sys.argv[1:]) diff --git a/lldb/examples/python/process_events.py b/lldb/examples/python/process_events.py --- a/lldb/examples/python/process_events.py +++ b/lldb/examples/python/process_events.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # Be sure to add the python path that points to the LLDB shared library. # On MacOSX csh, tcsh: # setenv PYTHONPATH /Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python # On MacOSX sh, bash: # export PYTHONPATH=/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- import optparse import os @@ -14,9 +14,9 @@ import sys import subprocess -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # Code that auto imports LLDB -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- try: # Just try for LLDB in case PYTHONPATH is already correctly setup import lldb @@ -24,18 +24,21 @@ lldb_python_dirs = list() # lldb is not in the PYTHONPATH, try some defaults for the current platform platform_system = platform.system() - if platform_system == 'Darwin': + if platform_system == "Darwin": # On Darwin, try the currently selected Xcode directory xcode_dir = subprocess.check_output("xcode-select --print-path", shell=True) if xcode_dir: lldb_python_dirs.append( os.path.realpath( - xcode_dir + - '/../SharedFrameworks/LLDB.framework/Resources/Python')) + xcode_dir + "/../SharedFrameworks/LLDB.framework/Resources/Python" + ) + ) lldb_python_dirs.append( - xcode_dir + '/Library/PrivateFrameworks/LLDB.framework/Resources/Python') + xcode_dir + "/Library/PrivateFrameworks/LLDB.framework/Resources/Python" + ) lldb_python_dirs.append( - '/System/Library/PrivateFrameworks/LLDB.framework/Resources/Python') + "/System/Library/PrivateFrameworks/LLDB.framework/Resources/Python" + ) success = False for lldb_python_dir in lldb_python_dirs: if os.path.exists(lldb_python_dir): @@ -50,14 +53,16 @@ success = True break if not success: - print("error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly") + print( + "error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly" + ) sys.exit(1) def print_threads(process, options): if options.show_threads: for thread in process: - print('%s %s' % (thread, thread.GetFrameAtIndex(0))) + print("%s %s" % (thread, thread.GetFrameAtIndex(0))) def run_commands(command_interpreter, commands): @@ -73,8 +78,8 @@ def main(argv): - description = '''Debugs a program using the LLDB python API and uses asynchronous broadcast events to watch for process state changes.''' - epilog = '''Examples: + description = """Debugs a program using the LLDB python API and uses asynchronous broadcast events to watch for process state changes.""" + epilog = """Examples: #---------------------------------------------------------------------- # Run "/bin/ls" with the arguments "-lAF /tmp/", and set a breakpoint @@ -82,146 +87,164 @@ #---------------------------------------------------------------------- % ./process_events.py --breakpoint malloc --stop-command bt --stop-command 'register read' -- /bin/ls -lAF /tmp/ -''' +""" optparse.OptionParser.format_epilog = lambda self, formatter: self.epilog parser = optparse.OptionParser( description=description, - prog='process_events', - usage='usage: process_events [options] program [arg1 arg2]', - epilog=epilog) + prog="process_events", + usage="usage: process_events [options] program [arg1 arg2]", + epilog=epilog, + ) parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', + "-v", + "--verbose", + action="store_true", + dest="verbose", help="Enable verbose logging.", - default=False) + default=False, + ) parser.add_option( - '-b', - '--breakpoint', - action='append', - type='string', - metavar='BPEXPR', - dest='breakpoints', - help='Breakpoint commands to create after the target has been created, the values will be sent to the "_regexp-break" command which supports breakpoints by name, file:line, and address.') + "-b", + "--breakpoint", + action="append", + type="string", + metavar="BPEXPR", + dest="breakpoints", + help='Breakpoint commands to create after the target has been created, the values will be sent to the "_regexp-break" command which supports breakpoints by name, file:line, and address.', + ) parser.add_option( - '-a', - '--arch', - type='string', - dest='arch', - help='The architecture to use when creating the debug target.', - default=None) + "-a", + "--arch", + type="string", + dest="arch", + help="The architecture to use when creating the debug target.", + default=None, + ) parser.add_option( - '--platform', - type='string', - metavar='platform', - dest='platform', + "--platform", + type="string", + metavar="platform", + dest="platform", help='Specify the platform to use when creating the debug target. Valid values include "localhost", "darwin-kernel", "ios-simulator", "remote-freebsd", "remote-macosx", "remote-ios", "remote-linux".', - default=None) + default=None, + ) parser.add_option( - '-l', - '--launch-command', - action='append', - type='string', - metavar='CMD', - dest='launch_commands', - help='LLDB command interpreter commands to run once after the process has launched. This option can be specified more than once.', - default=[]) + "-l", + "--launch-command", + action="append", + type="string", + metavar="CMD", + dest="launch_commands", + help="LLDB command interpreter commands to run once after the process has launched. This option can be specified more than once.", + default=[], + ) parser.add_option( - '-s', - '--stop-command', - action='append', - type='string', - metavar='CMD', - dest='stop_commands', - help='LLDB command interpreter commands to run each time the process stops. This option can be specified more than once.', - default=[]) + "-s", + "--stop-command", + action="append", + type="string", + metavar="CMD", + dest="stop_commands", + help="LLDB command interpreter commands to run each time the process stops. This option can be specified more than once.", + default=[], + ) parser.add_option( - '-c', - '--crash-command', - action='append', - type='string', - metavar='CMD', - dest='crash_commands', - help='LLDB command interpreter commands to run in case the process crashes. This option can be specified more than once.', - default=[]) + "-c", + "--crash-command", + action="append", + type="string", + metavar="CMD", + dest="crash_commands", + help="LLDB command interpreter commands to run in case the process crashes. This option can be specified more than once.", + default=[], + ) parser.add_option( - '-x', - '--exit-command', - action='append', - type='string', - metavar='CMD', - dest='exit_commands', - help='LLDB command interpreter commands to run once after the process has exited. This option can be specified more than once.', - default=[]) + "-x", + "--exit-command", + action="append", + type="string", + metavar="CMD", + dest="exit_commands", + help="LLDB command interpreter commands to run once after the process has exited. This option can be specified more than once.", + default=[], + ) parser.add_option( - '-T', - '--no-threads', - action='store_false', - dest='show_threads', + "-T", + "--no-threads", + action="store_false", + dest="show_threads", help="Don't show threads when process stops.", - default=True) + default=True, + ) parser.add_option( - '--ignore-errors', - action='store_false', - dest='stop_on_error', + "--ignore-errors", + action="store_false", + dest="stop_on_error", help="Don't stop executing LLDB commands if the command returns an error. This applies to all of the LLDB command interpreter commands that get run for launch, stop, crash and exit.", - default=True) + default=True, + ) parser.add_option( - '-n', - '--run-count', - type='int', - dest='run_count', - metavar='N', - help='How many times to run the process in case the process exits.', - default=1) + "-n", + "--run-count", + type="int", + dest="run_count", + metavar="N", + help="How many times to run the process in case the process exits.", + default=1, + ) parser.add_option( - '-t', - '--event-timeout', - type='int', - dest='event_timeout', - metavar='SEC', - help='Specify the timeout in seconds to wait for process state change events.', - default=lldb.UINT32_MAX) + "-t", + "--event-timeout", + type="int", + dest="event_timeout", + metavar="SEC", + help="Specify the timeout in seconds to wait for process state change events.", + default=lldb.UINT32_MAX, + ) parser.add_option( - '-e', - '--environment', - action='append', - type='string', - metavar='ENV', - dest='env_vars', - help='Environment variables to set in the inferior process when launching a process.') + "-e", + "--environment", + action="append", + type="string", + metavar="ENV", + dest="env_vars", + help="Environment variables to set in the inferior process when launching a process.", + ) parser.add_option( - '-d', - '--working-dir', - type='string', - metavar='DIR', - dest='working_dir', - help='The current working directory when launching a process.', - default=None) + "-d", + "--working-dir", + type="string", + metavar="DIR", + dest="working_dir", + help="The current working directory when launching a process.", + default=None, + ) parser.add_option( - '-p', - '--attach-pid', - type='int', - dest='attach_pid', - metavar='PID', - help='Specify a process to attach to by process ID.', - default=-1) + "-p", + "--attach-pid", + type="int", + dest="attach_pid", + metavar="PID", + help="Specify a process to attach to by process ID.", + default=-1, + ) parser.add_option( - '-P', - '--attach-name', - type='string', - dest='attach_name', - metavar='PROCESSNAME', - help='Specify a process to attach to by name.', - default=None) + "-P", + "--attach-name", + type="string", + dest="attach_name", + metavar="PROCESSNAME", + help="Specify a process to attach to by name.", + default=None, + ) parser.add_option( - '-w', - '--attach-wait', - action='store_true', - dest='attach_wait', - help='Wait for the next process to launch when attaching to a process by name.', - default=False) + "-w", + "--attach-wait", + action="store_true", + dest="attach_wait", + help="Wait for the next process to launch when attaching to a process by name.", + default=False, + ) try: (options, args) = parser.parse_args(argv) except: @@ -245,13 +268,14 @@ sys.exit(1) elif not options.attach_name is None: if options.run_count == 1: - attach_info = lldb.SBAttachInfo( - options.attach_name, options.attach_wait) + attach_info = lldb.SBAttachInfo(options.attach_name, options.attach_wait) else: print("error: --run-count can't be used with the --attach-name option") sys.exit(1) else: - print('error: a program path for a program to debug and its arguments are required') + print( + "error: a program path for a program to debug and its arguments are required" + ) sys.exit(1) # Create a new debugger instance @@ -263,18 +287,16 @@ if exe: print("Creating a target for '%s'" % exe) error = lldb.SBError() - target = debugger.CreateTarget( - exe, options.arch, options.platform, True, error) + target = debugger.CreateTarget(exe, options.arch, options.platform, True, error) if target: - # Set any breakpoints that were specified in the args if we are launching. We use the # command line command to take advantage of the shorthand breakpoint # creation if launch_info and options.breakpoints: for bp in options.breakpoints: debugger.HandleCommand("_regexp-break %s" % (bp)) - run_commands(command_interpreter, ['breakpoint list']) + run_commands(command_interpreter, ["breakpoint list"]) for run_idx in range(options.run_count): # Launch the process. Since we specified synchronous mode, we won't return @@ -285,24 +307,32 @@ if options.run_count == 1: print('Launching "%s"...' % (exe)) else: - print('Launching "%s"... (launch %u of %u)' % (exe, run_idx + 1, options.run_count)) + print( + 'Launching "%s"... (launch %u of %u)' + % (exe, run_idx + 1, options.run_count) + ) process = target.Launch(launch_info, error) else: if options.attach_pid != -1: - print('Attaching to process %i...' % (options.attach_pid)) + print("Attaching to process %i..." % (options.attach_pid)) else: if options.attach_wait: - print('Waiting for next to process named "%s" to launch...' % (options.attach_name)) + print( + 'Waiting for next to process named "%s" to launch...' + % (options.attach_name) + ) else: - print('Attaching to existing process named "%s"...' % (options.attach_name)) + print( + 'Attaching to existing process named "%s"...' + % (options.attach_name) + ) process = target.Attach(attach_info, error) # Make sure the launch went ok if process and process.GetProcessID() != lldb.LLDB_INVALID_PROCESS_ID: - pid = process.GetProcessID() - print('Process is %i' % (pid)) + print("Process is %i" % (pid)) if attach_info: # continue process if we attached as we won't get an # initial event @@ -319,15 +349,19 @@ state = lldb.SBProcess.GetStateFromEvent(event) if state == lldb.eStateInvalid: # Not a state event - print('process event = %s' % (event)) + print("process event = %s" % (event)) else: - print("process state changed event: %s" % (lldb.SBDebugger.StateAsCString(state))) + print( + "process state changed event: %s" + % (lldb.SBDebugger.StateAsCString(state)) + ) if state == lldb.eStateStopped: if stop_idx == 0: if launch_info: print("process %u launched" % (pid)) run_commands( - command_interpreter, ['breakpoint list']) + command_interpreter, ["breakpoint list"] + ) else: print("attached to process %u" % (pid)) for m in target.modules: @@ -335,16 +369,21 @@ if options.breakpoints: for bp in options.breakpoints: debugger.HandleCommand( - "_regexp-break %s" % (bp)) + "_regexp-break %s" % (bp) + ) run_commands( - command_interpreter, ['breakpoint list']) + command_interpreter, + ["breakpoint list"], + ) run_commands( - command_interpreter, options.launch_commands) + command_interpreter, options.launch_commands + ) else: if options.verbose: print("process %u stopped" % (pid)) run_commands( - command_interpreter, options.stop_commands) + command_interpreter, options.stop_commands + ) stop_idx += 1 print_threads(process, options) print("continuing process %u" % (pid)) @@ -352,17 +391,25 @@ elif state == lldb.eStateExited: exit_desc = process.GetExitDescription() if exit_desc: - print("process %u exited with status %u: %s" % (pid, process.GetExitStatus(), exit_desc)) + print( + "process %u exited with status %u: %s" + % (pid, process.GetExitStatus(), exit_desc) + ) else: - print("process %u exited with status %u" % (pid, process.GetExitStatus())) + print( + "process %u exited with status %u" + % (pid, process.GetExitStatus()) + ) run_commands( - command_interpreter, options.exit_commands) + command_interpreter, options.exit_commands + ) done = True elif state == lldb.eStateCrashed: print("process %u crashed" % (pid)) print_threads(process, options) run_commands( - command_interpreter, options.crash_commands) + command_interpreter, options.crash_commands + ) done = True elif state == lldb.eStateDetached: print("process %u detached" % (pid)) @@ -374,7 +421,10 @@ if options.verbose: print("process %u resumed" % (pid)) elif state == lldb.eStateUnloaded: - print("process %u unloaded, this shouldn't happen" % (pid)) + print( + "process %u unloaded, this shouldn't happen" + % (pid) + ) done = True elif state == lldb.eStateConnected: print("process connected") @@ -383,10 +433,13 @@ elif state == lldb.eStateLaunching: print("process launching") else: - print('event = %s' % (event)) + print("event = %s" % (event)) else: # timeout waiting for an event - print("no process event for %u seconds, killing the process..." % (options.event_timeout)) + print( + "no process event for %u seconds, killing the process..." + % (options.event_timeout) + ) done = True # Now that we are done dump the stdout and stderr process_stdout = process.GetSTDOUT(1024) @@ -407,11 +460,12 @@ print(error) else: if launch_info: - print('error: launch failed') + print("error: launch failed") else: - print('error: attach failed') + print("error: attach failed") lldb.SBDebugger.Terminate() -if __name__ == '__main__': + +if __name__ == "__main__": main(sys.argv[1:]) diff --git a/lldb/examples/python/pytracer.py b/lldb/examples/python/pytracer.py --- a/lldb/examples/python/pytracer.py +++ b/lldb/examples/python/pytracer.py @@ -4,7 +4,6 @@ class TracebackFancy: - def __init__(self, traceback): self.t = traceback @@ -20,13 +19,11 @@ def __str__(self): if self.t is None: return "" - str_self = "%s @ %s" % ( - self.getFrame().getName(), self.getLineNumber()) + str_self = "%s @ %s" % (self.getFrame().getName(), self.getLineNumber()) return str_self + "\n" + self.getNext().__str__() class ExceptionFancy: - def __init__(self, frame): self.etraceback = frame.f_exc_traceback self.etype = frame.exc_type @@ -41,7 +38,11 @@ return TracebackFancy(self.etraceback) def __nonzero__(self): - return self.etraceback is not None or self.etype is not None or self.evalue is not None + return ( + self.etraceback is not None + or self.etype is not None + or self.evalue is not None + ) def getType(self): return str(self.etype) @@ -51,7 +52,6 @@ class CodeFancy: - def __init__(self, code): self.c = code @@ -72,7 +72,6 @@ class ArgsFancy: - def __init__(self, frame, arginfo): self.f = frame self.a = arginfo @@ -127,7 +126,6 @@ class FrameFancy: - def __init__(self, frame): self.f = frame @@ -153,13 +151,14 @@ return self.f.f_locals if self.f is not None else {} def getArgumentInfo(self): - return ArgsFancy( - self.f, inspect.getargvalues( - self.f)) if self.f is not None else None + return ( + ArgsFancy(self.f, inspect.getargvalues(self.f)) + if self.f is not None + else None + ) class TracerClass: - def callEvent(self, frame): pass @@ -181,6 +180,7 @@ def cExceptionEvent(self, frame, cfunct): pass + tracer_impl = TracerClass() @@ -202,7 +202,8 @@ elif event == "exception": exty, exva, extb = args exception_retval = tracer_impl.exceptionEvent( - FrameFancy(frame), ExceptionFancy(extb, exty, exva)) + FrameFancy(frame), ExceptionFancy(extb, exty, exva) + ) if not exception_retval: return None return the_tracer_entrypoint @@ -227,40 +228,78 @@ class LoggingTracer: - def callEvent(self, frame): - print("call " + frame.getName() + " from " + frame.getCaller().getName() + " @ " + str(frame.getCaller().getLineNumber()) + " args are " + str(frame.getArgumentInfo())) + print( + "call " + + frame.getName() + + " from " + + frame.getCaller().getName() + + " @ " + + str(frame.getCaller().getLineNumber()) + + " args are " + + str(frame.getArgumentInfo()) + ) def lineEvent(self, frame): - print("running " + frame.getName() + " @ " + str(frame.getLineNumber()) + " locals are " + str(frame.getLocals()) + " in " + frame.getFileName()) + print( + "running " + + frame.getName() + + " @ " + + str(frame.getLineNumber()) + + " locals are " + + str(frame.getLocals()) + + " in " + + frame.getFileName() + ) def returnEvent(self, frame, retval): - print("return from " + frame.getName() + " value is " + str(retval) + " locals are " + str(frame.getLocals())) + print( + "return from " + + frame.getName() + + " value is " + + str(retval) + + " locals are " + + str(frame.getLocals()) + ) def exceptionEvent(self, frame, exception): - print("exception %s %s raised from %s @ %s" % (exception.getType(), str(exception.getValue()), frame.getName(), frame.getLineNumber())) + print( + "exception %s %s raised from %s @ %s" + % ( + exception.getType(), + str(exception.getValue()), + frame.getName(), + frame.getLineNumber(), + ) + ) print("tb: " + str(exception.getTraceback())) + # the same functionality as LoggingTracer, but with a little more # lldb-specific smarts class LLDBAwareTracer: - def callEvent(self, frame): if frame.getName() == "": return if frame.getName() == "run_one_line": - print("call run_one_line(%s)" % (frame.getArgumentInfo().getArgs()["input_string"])) + print( + "call run_one_line(%s)" + % (frame.getArgumentInfo().getArgs()["input_string"]) + ) return if "Python.framework" in frame.getFileName(): print("call into Python at " + frame.getName()) return - if frame.getName() == "__init__" and frame.getCaller().getName( - ) == "run_one_line" and frame.getCaller().getLineNumber() == 101: + if ( + frame.getName() == "__init__" + and frame.getCaller().getName() == "run_one_line" + and frame.getCaller().getLineNumber() == 101 + ): return False strout = "call " + frame.getName() - if (frame.getCaller().getFileName() == ""): + if frame.getCaller().getFileName() == "": strout += " from LLDB - args are " args = frame.getArgumentInfo().getArgs() for arg in args: @@ -268,22 +307,44 @@ continue strout = strout + ("%s = %s " % (arg, args[arg])) else: - strout += " from " + frame.getCaller().getName() + " @ " + \ - str(frame.getCaller().getLineNumber()) + " args are " + str(frame.getArgumentInfo()) + strout += ( + " from " + + frame.getCaller().getName() + + " @ " + + str(frame.getCaller().getLineNumber()) + + " args are " + + str(frame.getArgumentInfo()) + ) print(strout) def lineEvent(self, frame): if frame.getName() == "": return if frame.getName() == "run_one_line": - print("running run_one_line(%s) @ %s" % (frame.getArgumentInfo().getArgs()["input_string"], frame.getLineNumber())) + print( + "running run_one_line(%s) @ %s" + % ( + frame.getArgumentInfo().getArgs()["input_string"], + frame.getLineNumber(), + ) + ) return if "Python.framework" in frame.getFileName(): - print("running into Python at " + frame.getName() + " @ " + str(frame.getLineNumber())) + print( + "running into Python at " + + frame.getName() + + " @ " + + str(frame.getLineNumber()) + ) return - strout = "running " + frame.getName() + " @ " + str(frame.getLineNumber()) + \ - " locals are " - if (frame.getCaller().getFileName() == ""): + strout = ( + "running " + + frame.getName() + + " @ " + + str(frame.getLineNumber()) + + " locals are " + ) + if frame.getCaller().getFileName() == "": locals = frame.getLocals() for local in locals: if local == "dict" or local == "internal_dict": @@ -298,14 +359,27 @@ if frame.getName() == "": return if frame.getName() == "run_one_line": - print("return from run_one_line(%s) return value is %s" % (frame.getArgumentInfo().getArgs()["input_string"], retval)) + print( + "return from run_one_line(%s) return value is %s" + % (frame.getArgumentInfo().getArgs()["input_string"], retval) + ) return if "Python.framework" in frame.getFileName(): - print("return from Python at " + frame.getName() + " return value is " + str(retval)) + print( + "return from Python at " + + frame.getName() + + " return value is " + + str(retval) + ) return - strout = "return from " + frame.getName() + " return value is " + \ - str(retval) + " locals are " - if (frame.getCaller().getFileName() == ""): + strout = ( + "return from " + + frame.getName() + + " return value is " + + str(retval) + + " locals are " + ) + if frame.getCaller().getFileName() == "": locals = frame.getLocals() for local in locals: if local == "dict" or local == "internal_dict": @@ -319,7 +393,15 @@ def exceptionEvent(self, frame, exception): if frame.getName() == "": return - print("exception %s %s raised from %s @ %s" % (exception.getType(), str(exception.getValue()), frame.getName(), frame.getLineNumber())) + print( + "exception %s %s raised from %s @ %s" + % ( + exception.getType(), + str(exception.getValue()), + frame.getName(), + frame.getLineNumber(), + ) + ) print("tb: " + str(exception.getTraceback())) @@ -347,6 +429,7 @@ count += keywords[key] return count + if __name__ == "__main__": enable(LoggingTracer()) f(5) diff --git a/lldb/examples/python/sbvalue.py b/lldb/examples/python/sbvalue.py --- a/lldb/examples/python/sbvalue.py +++ b/lldb/examples/python/sbvalue.py @@ -4,7 +4,7 @@ class value(object): - '''A class that wraps an lldb.SBValue object and returns an object that + """A class that wraps an lldb.SBValue object and returns an object that can be used as an object with attribytes:\n argv = a.value(lldb.frame.FindVariable('argv'))\n argv.name - return the name of the value that this object contains\n @@ -24,7 +24,7 @@ argv.frame - return the lldb.SBFrame for this value argv.num_children - return the number of children this value has argv.children - return a list of sbvalue objects that represents all of the children of this value - ''' + """ def __init__(self, sbvalue): self.sbvalue = sbvalue @@ -40,55 +40,50 @@ def __getitem__(self, key): if isinstance(key, int): - return value( - self.sbvalue.GetChildAtIndex( - key, lldb.eNoDynamicValues, True)) + return value(self.sbvalue.GetChildAtIndex(key, lldb.eNoDynamicValues, True)) raise TypeError def __getattr__(self, name): - if name == 'name': + if name == "name": return self.sbvalue.GetName() - if name == 'type': + if name == "type": return self.sbvalue.GetType() - if name == 'type_name': + if name == "type_name": return self.sbvalue.GetTypeName() - if name == 'size': + if name == "size": return self.sbvalue.GetByteSize() - if name == 'is_in_scope': + if name == "is_in_scope": return self.sbvalue.IsInScope() - if name == 'is_pointer': + if name == "is_pointer": return self.sbvalue.TypeIsPointerType() - if name == 'format': + if name == "format": return self.sbvalue.GetFormat() - if name == 'value': + if name == "value": return self.sbvalue.GetValue() - if name == 'summary': + if name == "summary": return self.sbvalue.GetSummary() - if name == 'description': + if name == "description": return self.sbvalue.GetObjectDescription() - if name == 'location': + if name == "location": return self.sbvalue.GetLocation() - if name == 'target': + if name == "target": return self.sbvalue.GetTarget() - if name == 'process': + if name == "process": return self.sbvalue.GetProcess() - if name == 'thread': + if name == "thread": return self.sbvalue.GetThread() - if name == 'frame': + if name == "frame": return self.sbvalue.GetFrame() - if name == 'num_children': + if name == "num_children": return self.sbvalue.GetNumChildren() - if name == 'children': + if name == "children": # Returns an array of sbvalue objects, one for each child of # the value for the lldb.SBValue children = [] for i in range(self.sbvalue.GetNumChildren()): children.append( - value( - self.sbvalue.GetChildAtIndex( - i, - lldb.eNoDynamicValues, - True))) + value(self.sbvalue.GetChildAtIndex(i, lldb.eNoDynamicValues, True)) + ) return children raise AttributeError @@ -113,10 +108,7 @@ def __getitem__(self, key): # Allow array access if this value has children... if isinstance(key, int): - return variable( - self.sbvalue.GetValueForExpressionPath( - "[%i]" % - key)) + return variable(self.sbvalue.GetValueForExpressionPath("[%i]" % key)) raise TypeError def __getattr__(self, name): @@ -262,7 +254,7 @@ return float(self.sbvalue.GetValueAsSigned()) def __oct__(self): - return '0%o' % self.sbvalue.GetValueAsSigned() + return "0%o" % self.sbvalue.GetValueAsSigned() def __hex__(self): - return '0x%x' % self.sbvalue.GetValueAsSigned() + return "0x%x" % self.sbvalue.GetValueAsSigned() diff --git a/lldb/examples/python/scripted_process/crashlog_scripted_process.py b/lldb/examples/python/scripted_process/crashlog_scripted_process.py --- a/lldb/examples/python/scripted_process/crashlog_scripted_process.py +++ b/lldb/examples/python/scripted_process/crashlog_scripted_process.py @@ -6,7 +6,8 @@ from lldb.plugins.scripted_process import ScriptedProcess from lldb.plugins.scripted_process import ScriptedThread -from lldb.macosx.crashlog import CrashLog,CrashLogParser +from lldb.macosx.crashlog import CrashLog, CrashLogParser + class CrashLogScriptedProcess(ScriptedProcess): def set_crashlog(self, crashlog): @@ -23,9 +24,9 @@ self.loaded_images = [] self.exception = self.crashlog.exception self.app_specific_thread = None - if hasattr(self.crashlog, 'asi'): - self.metadata['asi'] = self.crashlog.asi - if hasattr(self.crashlog, 'asb'): + if hasattr(self.crashlog, "asi"): + self.metadata["asi"] = self.crashlog.asi + if hasattr(self.crashlog, "asb"): self.extended_thread_info = self.crashlog.asb if self.load_all_images: @@ -51,7 +52,10 @@ self.loaded_images.append(image) for thread in self.crashlog.threads: - if hasattr(thread, 'app_specific_backtrace') and thread.app_specific_backtrace: + if ( + hasattr(thread, "app_specific_backtrace") + and thread.app_specific_backtrace + ): # We don't want to include the Application Specific Backtrace # Thread into the Scripted Process' Thread list. # Instead, we will try to extract the stackframe pcs from the @@ -61,14 +65,12 @@ self.threads[thread.index] = CrashLogScriptedThread(self, None, thread) - if self.app_specific_thread: - self.extended_thread_info = \ - CrashLogScriptedThread.resolve_stackframes(self.app_specific_thread, - self.addr_mask, - self.target) + self.extended_thread_info = CrashLogScriptedThread.resolve_stackframes( + self.app_specific_thread, self.addr_mask, self.target + ) - def __init__(self, exe_ctx: lldb.SBExecutionContext, args : lldb.SBStructuredData): + def __init__(self, exe_ctx: lldb.SBExecutionContext, args: lldb.SBStructuredData): super().__init__(exe_ctx, args) if not self.target or not self.target.IsValid(): @@ -99,7 +101,9 @@ self.exception = None self.extended_thread_info = None - def read_memory_at_address(self, addr: int, size: int, error: lldb.SBError) -> lldb.SBData: + def read_memory_at_address( + self, addr: int, size: int, error: lldb.SBError + ) -> lldb.SBData: # NOTE: CrashLogs don't contain any memory. return lldb.SBData() @@ -120,16 +124,21 @@ def get_process_metadata(self): return self.metadata + class CrashLogScriptedThread(ScriptedThread): def create_register_ctx(self): if not self.has_crashed: - return dict.fromkeys([*map(lambda reg: reg['name'], self.register_info['registers'])] , 0) + return dict.fromkeys( + [*map(lambda reg: reg["name"], self.register_info["registers"])], 0 + ) if not self.backing_thread or not len(self.backing_thread.registers): - return dict.fromkeys([*map(lambda reg: reg['name'], self.register_info['registers'])] , 0) + return dict.fromkeys( + [*map(lambda reg: reg["name"], self.register_info["registers"])], 0 + ) - for reg in self.register_info['registers']: - reg_name = reg['name'] + for reg in self.register_info["registers"]: + reg_name = reg["name"] if reg_name in self.backing_thread.registers: self.register_ctx[reg_name] = self.backing_thread.registers[reg_name] else: @@ -141,7 +150,7 @@ frames = [] for frame in thread.frames: frame_pc = frame.pc & addr_mask - pc = frame_pc if frame.index == 0 or frame_pc == 0 else frame_pc - 1 + pc = frame_pc if frame.index == 0 or frame_pc == 0 else frame_pc - 1 sym_addr = lldb.SBAddress() sym_addr.SetLoadAddress(pc, target) if not sym_addr.IsValid(): @@ -149,7 +158,6 @@ frames.append({"idx": frame.index, "pc": pc}) return frames - def create_stackframes(self): if not (self.scripted_process.load_all_images or self.has_crashed): return None @@ -157,9 +165,9 @@ if not self.backing_thread or not len(self.backing_thread.frames): return None - self.frames = CrashLogScriptedThread.resolve_stackframes(self.backing_thread, - self.scripted_process.addr_mask, - self.target) + self.frames = CrashLogScriptedThread.resolve_stackframes( + self.backing_thread, self.scripted_process.addr_mask, self.target + ) return self.frames @@ -174,7 +182,7 @@ else: self.name = self.backing_thread.name self.queue = self.backing_thread.queue - self.has_crashed = (self.scripted_process.crashed_thread_idx == self.idx) + self.has_crashed = self.scripted_process.crashed_thread_idx == self.idx self.create_stackframes() def get_state(self): @@ -184,21 +192,22 @@ def get_stop_reason(self) -> Dict[str, Any]: if not self.has_crashed: - return { "type": lldb.eStopReasonNone } + return {"type": lldb.eStopReasonNone} # TODO: Investigate what stop reason should be reported when crashed - stop_reason = { "type": lldb.eStopReasonException, "data": { }} + stop_reason = {"type": lldb.eStopReasonException, "data": {}} if self.scripted_process.exception: - stop_reason['data']['mach_exception'] = self.scripted_process.exception + stop_reason["data"]["mach_exception"] = self.scripted_process.exception return stop_reason def get_register_context(self) -> str: if not self.register_ctx: self.register_ctx = self.create_register_ctx() - return struct.pack("{}Q".format(len(self.register_ctx)), *self.register_ctx.values()) + return struct.pack( + "{}Q".format(len(self.register_ctx)), *self.register_ctx.values() + ) def get_extended_info(self): - if (self.has_crashed): + if self.has_crashed: self.extended_info = self.scripted_process.extended_thread_info return self.extended_info - diff --git a/lldb/examples/python/scripted_process/scripted_platform.py b/lldb/examples/python/scripted_process/scripted_platform.py --- a/lldb/examples/python/scripted_process/scripted_platform.py +++ b/lldb/examples/python/scripted_process/scripted_platform.py @@ -2,6 +2,7 @@ import lldb + class ScriptedPlatform(metaclass=ABCMeta): """ @@ -18,7 +19,7 @@ @abstractmethod def __init__(self, exe_ctx, args): - """ Construct a scripted platform. + """Construct a scripted platform. Args: exe_ctx (lldb.SBExecutionContext): The execution context for the scripted platform @@ -29,7 +30,7 @@ @abstractmethod def list_processes(self): - """ Get a list of processes that are running or that can be attached to on the platform. + """Get a list of processes that are running or that can be attached to on the platform. processes = { 420: { @@ -51,7 +52,7 @@ pass def get_process_info(self, pid): - """ Get the dictionary describing the process. + """Get the dictionary describing the process. Returns: Dict: The dictionary of process info that matched process ID. @@ -61,7 +62,7 @@ @abstractmethod def attach_to_process(self, attach_info): - """ Attach to a process. + """Attach to a process. Args: attach_info (lldb.SBAttachInfo): The information related to attach to a process. @@ -73,7 +74,7 @@ @abstractmethod def launch_process(self, launch_info): - """ Launch a process. + """Launch a process. Args: launch_info (lldb.SBLaunchInfo): The information related to the process launch. @@ -85,7 +86,7 @@ @abstractmethod def kill_process(self, pid): - """ Kill a process. + """Kill a process. Args: pid (int): Process ID for the process to be killed. diff --git a/lldb/examples/python/scripted_process/scripted_process.py b/lldb/examples/python/scripted_process/scripted_process.py --- a/lldb/examples/python/scripted_process/scripted_process.py +++ b/lldb/examples/python/scripted_process/scripted_process.py @@ -2,6 +2,7 @@ import lldb + class ScriptedProcess(metaclass=ABCMeta): """ @@ -22,7 +23,7 @@ @abstractmethod def __init__(self, exe_ctx, args): - """ Construct a scripted process. + """Construct a scripted process. Args: exe_ctx (lldb.SBExecutionContext): The execution context for the scripted process. @@ -39,7 +40,7 @@ self.target = target triple = self.target.triple if triple: - self.arch = triple.split('-')[0] + self.arch = triple.split("-")[0] self.dbg = target.GetDebugger() if isinstance(args, lldb.SBStructuredData) and args.IsValid(): self.args = args @@ -50,7 +51,7 @@ self.pid = 42 def get_capabilities(self): - """ Get a dictionary containing the process capabilities. + """Get a dictionary containing the process capabilities. Returns: Dict[str:bool]: The dictionary of capability, with the capability @@ -60,7 +61,7 @@ return self.capabilities def get_memory_region_containing_address(self, addr): - """ Get the memory region for the scripted process, containing a + """Get the memory region for the scripted process, containing a specific address. Args: @@ -74,7 +75,7 @@ return None def get_threads_info(self): - """ Get the dictionary describing the process' Scripted Threads. + """Get the dictionary describing the process' Scripted Threads. Returns: Dict: The dictionary of threads, with the thread ID as the key and @@ -85,7 +86,7 @@ @abstractmethod def read_memory_at_address(self, addr, size, error): - """ Get a memory buffer from the scripted process at a certain address, + """Get a memory buffer from the scripted process at a certain address, of a certain size. Args: @@ -100,7 +101,7 @@ pass def write_memory_at_address(self, addr, data, error): - """ Write a buffer to the scripted process memory. + """Write a buffer to the scripted process memory. Args: addr (int): Address from which we should start reading. @@ -111,11 +112,13 @@ Returns: size (int): Size of the memory to read. """ - error.SetErrorString("%s doesn't support memory writes." % self.__class__.__name__) + error.SetErrorString( + "%s doesn't support memory writes." % self.__class__.__name__ + ) return 0 def get_loaded_images(self): - """ Get the list of loaded images for the scripted process. + """Get the list of loaded images for the scripted process. ``` scripted_image = { @@ -134,7 +137,7 @@ return self.loaded_images def get_process_id(self): - """ Get the scripted process identifier. + """Get the scripted process identifier. Returns: int: The scripted process identifier. @@ -142,7 +145,7 @@ return self.pid def launch(self): - """ Simulate the scripted process launch. + """Simulate the scripted process launch. Returns: lldb.SBError: An `lldb.SBError` with error code 0. @@ -150,7 +153,7 @@ return lldb.SBError() def attach(self, attach_info): - """ Simulate the scripted process attach. + """Simulate the scripted process attach. Args: attach_info (lldb.SBAttachInfo): The information related to the @@ -162,7 +165,7 @@ return lldb.SBError() def resume(self, should_stop=True): - """ Simulate the scripted process resume. + """Simulate the scripted process resume. Args: should_stop (bool): If True, resume will also force the process @@ -177,14 +180,14 @@ error.SetErrorString("Invalid process.") return error - process.ForceScriptedState(lldb.eStateRunning); - if (should_stop): - process.ForceScriptedState(lldb.eStateStopped); + process.ForceScriptedState(lldb.eStateRunning) + if should_stop: + process.ForceScriptedState(lldb.eStateStopped) return lldb.SBError() @abstractmethod def is_alive(self): - """ Check if the scripted process is alive. + """Check if the scripted process is alive. Returns: bool: True if scripted process is alive. False otherwise. @@ -193,7 +196,7 @@ @abstractmethod def get_scripted_thread_plugin(self): - """ Get scripted thread plugin name. + """Get scripted thread plugin name. Returns: str: Name of the scripted thread plugin. @@ -201,7 +204,7 @@ return None def get_process_metadata(self): - """ Get some metadata for the scripted process. + """Get some metadata for the scripted process. Returns: Dict: A dictionary containing metadata for the scripted process. @@ -210,7 +213,7 @@ return self.metadata def create_breakpoint(self, addr, error): - """ Create a breakpoint in the scripted process from an address. + """Create a breakpoint in the scripted process from an address. This is mainly used with interactive scripted process debugging. Args: @@ -221,8 +224,9 @@ SBBreakpoint: A valid breakpoint object that was created a the specified address. None if the breakpoint creation failed. """ - error.SetErrorString("%s doesn't support creating breakpoints." - % self.__class__.__name__) + error.SetErrorString( + "%s doesn't support creating breakpoints." % self.__class__.__name__ + ) return False @@ -240,7 +244,7 @@ @abstractmethod def __init__(self, scripted_process, args): - """ Construct a scripted thread. + """Construct a scripted thread. Args: process (ScriptedProcess): The scripted process owning this thread. @@ -270,7 +274,7 @@ self.get_register_info() def get_thread_idx(self): - """ Get the scripted thread index. + """Get the scripted thread index. Returns: int: The index of the scripted thread in the scripted process. @@ -278,7 +282,7 @@ return self.idx def get_thread_id(self): - """ Get the scripted thread identifier. + """Get the scripted thread identifier. Returns: int: The identifier of the scripted thread. @@ -286,7 +290,7 @@ return self.tid def get_name(self): - """ Get the scripted thread name. + """Get the scripted thread name. Returns: str: The name of the scripted thread. @@ -294,7 +298,7 @@ return self.name def get_state(self): - """ Get the scripted thread state type. + """Get the scripted thread state type. eStateStopped, ///< Process or thread is stopped and can be examined. eStateRunning, ///< Process or thread is running and can't be examined. @@ -309,7 +313,7 @@ return lldb.eStateStopped def get_queue(self): - """ Get the scripted thread associated queue name. + """Get the scripted thread associated queue name. This method is optional. Returns: @@ -319,7 +323,7 @@ @abstractmethod def get_stop_reason(self): - """ Get the dictionary describing the stop reason type with some data. + """Get the dictionary describing the stop reason type with some data. This method is optional. Returns: @@ -329,7 +333,7 @@ pass def get_stackframes(self): - """ Get the list of stack frames for the scripted thread. + """Get the list of stack frames for the scripted thread. ``` scripted_frame = { @@ -349,18 +353,19 @@ def get_register_info(self): if self.register_info is None: self.register_info = dict() - if self.scripted_process.arch == 'x86_64': - self.register_info['sets'] = ['General Purpose Registers'] - self.register_info['registers'] = INTEL64_GPR - elif 'arm64' in self.scripted_process.arch: - self.register_info['sets'] = ['General Purpose Registers'] - self.register_info['registers'] = ARM64_GPR - else: raise ValueError('Unknown architecture', self.scripted_process.arch) + if self.scripted_process.arch == "x86_64": + self.register_info["sets"] = ["General Purpose Registers"] + self.register_info["registers"] = INTEL64_GPR + elif "arm64" in self.scripted_process.arch: + self.register_info["sets"] = ["General Purpose Registers"] + self.register_info["registers"] = ARM64_GPR + else: + raise ValueError("Unknown architecture", self.scripted_process.arch) return self.register_info @abstractmethod def get_register_context(self): - """ Get the scripted thread register context + """Get the scripted thread register context Returns: str: A byte representing all register's value. @@ -368,7 +373,7 @@ pass def get_extended_info(self): - """ Get scripted thread extended information. + """Get scripted thread extended information. Returns: List: A list containing the extended information for the scripted process. @@ -376,63 +381,595 @@ """ return self.extended_info -ARM64_GPR = [ {'name': 'x0', 'bitsize': 64, 'offset': 0, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 0, 'dwarf': 0, 'generic': 'arg0', 'alt-name': 'arg0'}, - {'name': 'x1', 'bitsize': 64, 'offset': 8, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 1, 'dwarf': 1, 'generic': 'arg1', 'alt-name': 'arg1'}, - {'name': 'x2', 'bitsize': 64, 'offset': 16, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 2, 'dwarf': 2, 'generic': 'arg2', 'alt-name': 'arg2'}, - {'name': 'x3', 'bitsize': 64, 'offset': 24, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 3, 'dwarf': 3, 'generic': 'arg3', 'alt-name': 'arg3'}, - {'name': 'x4', 'bitsize': 64, 'offset': 32, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 4, 'dwarf': 4, 'generic': 'arg4', 'alt-name': 'arg4'}, - {'name': 'x5', 'bitsize': 64, 'offset': 40, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 5, 'dwarf': 5, 'generic': 'arg5', 'alt-name': 'arg5'}, - {'name': 'x6', 'bitsize': 64, 'offset': 48, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 6, 'dwarf': 6, 'generic': 'arg6', 'alt-name': 'arg6'}, - {'name': 'x7', 'bitsize': 64, 'offset': 56, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 7, 'dwarf': 7, 'generic': 'arg7', 'alt-name': 'arg7'}, - {'name': 'x8', 'bitsize': 64, 'offset': 64, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 8, 'dwarf': 8 }, - {'name': 'x9', 'bitsize': 64, 'offset': 72, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 9, 'dwarf': 9 }, - {'name': 'x10', 'bitsize': 64, 'offset': 80, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 10, 'dwarf': 10}, - {'name': 'x11', 'bitsize': 64, 'offset': 88, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 11, 'dwarf': 11}, - {'name': 'x12', 'bitsize': 64, 'offset': 96, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 12, 'dwarf': 12}, - {'name': 'x13', 'bitsize': 64, 'offset': 104, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 13, 'dwarf': 13}, - {'name': 'x14', 'bitsize': 64, 'offset': 112, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 14, 'dwarf': 14}, - {'name': 'x15', 'bitsize': 64, 'offset': 120, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 15, 'dwarf': 15}, - {'name': 'x16', 'bitsize': 64, 'offset': 128, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 16, 'dwarf': 16}, - {'name': 'x17', 'bitsize': 64, 'offset': 136, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 17, 'dwarf': 17}, - {'name': 'x18', 'bitsize': 64, 'offset': 144, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 18, 'dwarf': 18}, - {'name': 'x19', 'bitsize': 64, 'offset': 152, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 19, 'dwarf': 19}, - {'name': 'x20', 'bitsize': 64, 'offset': 160, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 20, 'dwarf': 20}, - {'name': 'x21', 'bitsize': 64, 'offset': 168, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 21, 'dwarf': 21}, - {'name': 'x22', 'bitsize': 64, 'offset': 176, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 22, 'dwarf': 22}, - {'name': 'x23', 'bitsize': 64, 'offset': 184, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 23, 'dwarf': 23}, - {'name': 'x24', 'bitsize': 64, 'offset': 192, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 24, 'dwarf': 24}, - {'name': 'x25', 'bitsize': 64, 'offset': 200, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 25, 'dwarf': 25}, - {'name': 'x26', 'bitsize': 64, 'offset': 208, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 26, 'dwarf': 26}, - {'name': 'x27', 'bitsize': 64, 'offset': 216, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 27, 'dwarf': 27}, - {'name': 'x28', 'bitsize': 64, 'offset': 224, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 28, 'dwarf': 28}, - {'name': 'x29', 'bitsize': 64, 'offset': 232, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 29, 'dwarf': 29, 'generic': 'fp', 'alt-name': 'fp'}, - {'name': 'x30', 'bitsize': 64, 'offset': 240, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 30, 'dwarf': 30, 'generic': 'lr', 'alt-name': 'lr'}, - {'name': 'sp', 'bitsize': 64, 'offset': 248, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 31, 'dwarf': 31, 'generic': 'sp', 'alt-name': 'sp'}, - {'name': 'pc', 'bitsize': 64, 'offset': 256, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 32, 'dwarf': 32, 'generic': 'pc', 'alt-name': 'pc'}, - {'name': 'cpsr', 'bitsize': 32, 'offset': 264, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 33, 'dwarf': 33} - ] - -INTEL64_GPR = [ {'name': 'rax', 'bitsize': 64, 'offset': 0, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 0, 'dwarf': 0}, - {'name': 'rbx', 'bitsize': 64, 'offset': 8, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 3, 'dwarf': 3}, - {'name': 'rcx', 'bitsize': 64, 'offset': 16, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 2, 'dwarf': 2, 'generic': 'arg4', 'alt-name': 'arg4'}, - {'name': 'rdx', 'bitsize': 64, 'offset': 24, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 1, 'dwarf': 1, 'generic': 'arg3', 'alt-name': 'arg3'}, - {'name': 'rdi', 'bitsize': 64, 'offset': 32, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 5, 'dwarf': 5, 'generic': 'arg1', 'alt-name': 'arg1'}, - {'name': 'rsi', 'bitsize': 64, 'offset': 40, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 4, 'dwarf': 4, 'generic': 'arg2', 'alt-name': 'arg2'}, - {'name': 'rbp', 'bitsize': 64, 'offset': 48, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 6, 'dwarf': 6, 'generic': 'fp', 'alt-name': 'fp'}, - {'name': 'rsp', 'bitsize': 64, 'offset': 56, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 7, 'dwarf': 7, 'generic': 'sp', 'alt-name': 'sp'}, - {'name': 'r8', 'bitsize': 64, 'offset': 64, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 8, 'dwarf': 8, 'generic': 'arg5', 'alt-name': 'arg5'}, - {'name': 'r9', 'bitsize': 64, 'offset': 72, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 9, 'dwarf': 9, 'generic': 'arg6', 'alt-name': 'arg6'}, - {'name': 'r10', 'bitsize': 64, 'offset': 80, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 10, 'dwarf': 10}, - {'name': 'r11', 'bitsize': 64, 'offset': 88, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 11, 'dwarf': 11}, - {'name': 'r12', 'bitsize': 64, 'offset': 96, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 12, 'dwarf': 12}, - {'name': 'r13', 'bitsize': 64, 'offset': 104, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 13, 'dwarf': 13}, - {'name': 'r14', 'bitsize': 64, 'offset': 112, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 14, 'dwarf': 14}, - {'name': 'r15', 'bitsize': 64, 'offset': 120, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 15, 'dwarf': 15}, - {'name': 'rip', 'bitsize': 64, 'offset': 128, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 16, 'dwarf': 16, 'generic': 'pc', 'alt-name': 'pc'}, - {'name': 'rflags', 'bitsize': 64, 'offset': 136, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'generic': 'flags', 'alt-name': 'flags'}, - {'name': 'cs', 'bitsize': 64, 'offset': 144, 'encoding': 'uint', 'format': 'hex', 'set': 0}, - {'name': 'fs', 'bitsize': 64, 'offset': 152, 'encoding': 'uint', 'format': 'hex', 'set': 0}, - {'name': 'gs', 'bitsize': 64, 'offset': 160, 'encoding': 'uint', 'format': 'hex', 'set': 0} - ] - +ARM64_GPR = [ + { + "name": "x0", + "bitsize": 64, + "offset": 0, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 0, + "dwarf": 0, + "generic": "arg0", + "alt-name": "arg0", + }, + { + "name": "x1", + "bitsize": 64, + "offset": 8, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 1, + "dwarf": 1, + "generic": "arg1", + "alt-name": "arg1", + }, + { + "name": "x2", + "bitsize": 64, + "offset": 16, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 2, + "dwarf": 2, + "generic": "arg2", + "alt-name": "arg2", + }, + { + "name": "x3", + "bitsize": 64, + "offset": 24, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 3, + "dwarf": 3, + "generic": "arg3", + "alt-name": "arg3", + }, + { + "name": "x4", + "bitsize": 64, + "offset": 32, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 4, + "dwarf": 4, + "generic": "arg4", + "alt-name": "arg4", + }, + { + "name": "x5", + "bitsize": 64, + "offset": 40, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 5, + "dwarf": 5, + "generic": "arg5", + "alt-name": "arg5", + }, + { + "name": "x6", + "bitsize": 64, + "offset": 48, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 6, + "dwarf": 6, + "generic": "arg6", + "alt-name": "arg6", + }, + { + "name": "x7", + "bitsize": 64, + "offset": 56, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 7, + "dwarf": 7, + "generic": "arg7", + "alt-name": "arg7", + }, + { + "name": "x8", + "bitsize": 64, + "offset": 64, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 8, + "dwarf": 8, + }, + { + "name": "x9", + "bitsize": 64, + "offset": 72, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 9, + "dwarf": 9, + }, + { + "name": "x10", + "bitsize": 64, + "offset": 80, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 10, + "dwarf": 10, + }, + { + "name": "x11", + "bitsize": 64, + "offset": 88, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 11, + "dwarf": 11, + }, + { + "name": "x12", + "bitsize": 64, + "offset": 96, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 12, + "dwarf": 12, + }, + { + "name": "x13", + "bitsize": 64, + "offset": 104, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 13, + "dwarf": 13, + }, + { + "name": "x14", + "bitsize": 64, + "offset": 112, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 14, + "dwarf": 14, + }, + { + "name": "x15", + "bitsize": 64, + "offset": 120, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 15, + "dwarf": 15, + }, + { + "name": "x16", + "bitsize": 64, + "offset": 128, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 16, + "dwarf": 16, + }, + { + "name": "x17", + "bitsize": 64, + "offset": 136, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 17, + "dwarf": 17, + }, + { + "name": "x18", + "bitsize": 64, + "offset": 144, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 18, + "dwarf": 18, + }, + { + "name": "x19", + "bitsize": 64, + "offset": 152, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 19, + "dwarf": 19, + }, + { + "name": "x20", + "bitsize": 64, + "offset": 160, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 20, + "dwarf": 20, + }, + { + "name": "x21", + "bitsize": 64, + "offset": 168, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 21, + "dwarf": 21, + }, + { + "name": "x22", + "bitsize": 64, + "offset": 176, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 22, + "dwarf": 22, + }, + { + "name": "x23", + "bitsize": 64, + "offset": 184, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 23, + "dwarf": 23, + }, + { + "name": "x24", + "bitsize": 64, + "offset": 192, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 24, + "dwarf": 24, + }, + { + "name": "x25", + "bitsize": 64, + "offset": 200, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 25, + "dwarf": 25, + }, + { + "name": "x26", + "bitsize": 64, + "offset": 208, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 26, + "dwarf": 26, + }, + { + "name": "x27", + "bitsize": 64, + "offset": 216, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 27, + "dwarf": 27, + }, + { + "name": "x28", + "bitsize": 64, + "offset": 224, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 28, + "dwarf": 28, + }, + { + "name": "x29", + "bitsize": 64, + "offset": 232, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 29, + "dwarf": 29, + "generic": "fp", + "alt-name": "fp", + }, + { + "name": "x30", + "bitsize": 64, + "offset": 240, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 30, + "dwarf": 30, + "generic": "lr", + "alt-name": "lr", + }, + { + "name": "sp", + "bitsize": 64, + "offset": 248, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 31, + "dwarf": 31, + "generic": "sp", + "alt-name": "sp", + }, + { + "name": "pc", + "bitsize": 64, + "offset": 256, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 32, + "dwarf": 32, + "generic": "pc", + "alt-name": "pc", + }, + { + "name": "cpsr", + "bitsize": 32, + "offset": 264, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 33, + "dwarf": 33, + }, +] + +INTEL64_GPR = [ + { + "name": "rax", + "bitsize": 64, + "offset": 0, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 0, + "dwarf": 0, + }, + { + "name": "rbx", + "bitsize": 64, + "offset": 8, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 3, + "dwarf": 3, + }, + { + "name": "rcx", + "bitsize": 64, + "offset": 16, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 2, + "dwarf": 2, + "generic": "arg4", + "alt-name": "arg4", + }, + { + "name": "rdx", + "bitsize": 64, + "offset": 24, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 1, + "dwarf": 1, + "generic": "arg3", + "alt-name": "arg3", + }, + { + "name": "rdi", + "bitsize": 64, + "offset": 32, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 5, + "dwarf": 5, + "generic": "arg1", + "alt-name": "arg1", + }, + { + "name": "rsi", + "bitsize": 64, + "offset": 40, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 4, + "dwarf": 4, + "generic": "arg2", + "alt-name": "arg2", + }, + { + "name": "rbp", + "bitsize": 64, + "offset": 48, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 6, + "dwarf": 6, + "generic": "fp", + "alt-name": "fp", + }, + { + "name": "rsp", + "bitsize": 64, + "offset": 56, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 7, + "dwarf": 7, + "generic": "sp", + "alt-name": "sp", + }, + { + "name": "r8", + "bitsize": 64, + "offset": 64, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 8, + "dwarf": 8, + "generic": "arg5", + "alt-name": "arg5", + }, + { + "name": "r9", + "bitsize": 64, + "offset": 72, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 9, + "dwarf": 9, + "generic": "arg6", + "alt-name": "arg6", + }, + { + "name": "r10", + "bitsize": 64, + "offset": 80, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 10, + "dwarf": 10, + }, + { + "name": "r11", + "bitsize": 64, + "offset": 88, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 11, + "dwarf": 11, + }, + { + "name": "r12", + "bitsize": 64, + "offset": 96, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 12, + "dwarf": 12, + }, + { + "name": "r13", + "bitsize": 64, + "offset": 104, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 13, + "dwarf": 13, + }, + { + "name": "r14", + "bitsize": 64, + "offset": 112, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 14, + "dwarf": 14, + }, + { + "name": "r15", + "bitsize": 64, + "offset": 120, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 15, + "dwarf": 15, + }, + { + "name": "rip", + "bitsize": 64, + "offset": 128, + "encoding": "uint", + "format": "hex", + "set": 0, + "gcc": 16, + "dwarf": 16, + "generic": "pc", + "alt-name": "pc", + }, + { + "name": "rflags", + "bitsize": 64, + "offset": 136, + "encoding": "uint", + "format": "hex", + "set": 0, + "generic": "flags", + "alt-name": "flags", + }, + { + "name": "cs", + "bitsize": 64, + "offset": 144, + "encoding": "uint", + "format": "hex", + "set": 0, + }, + { + "name": "fs", + "bitsize": 64, + "offset": 152, + "encoding": "uint", + "format": "hex", + "set": 0, + }, + { + "name": "gs", + "bitsize": 64, + "offset": 160, + "encoding": "uint", + "format": "hex", + "set": 0, + }, +] diff --git a/lldb/examples/python/scripted_step.py b/lldb/examples/python/scripted_step.py --- a/lldb/examples/python/scripted_step.py +++ b/lldb/examples/python/scripted_step.py @@ -101,7 +101,6 @@ class SimpleStep: - def __init__(self, thread_plan, dict): self.thread_plan = thread_plan self.start_address = thread_plan.GetThread().GetFrameAtIndex(0).GetPC() @@ -129,13 +128,14 @@ def stop_description(self, stream): stream.Print("Simple step completed") -class StepWithPlan: +class StepWithPlan: def __init__(self, thread_plan, dict): self.thread_plan = thread_plan self.start_address = thread_plan.GetThread().GetFrameAtIndex(0).GetPCAddress() self.step_thread_plan = thread_plan.QueueThreadPlanForStepOverRange( - self.start_address, 20) + self.start_address, 20 + ) def explains_stop(self, event): # Since all I'm doing is running a plan, I will only ever get askedthis @@ -155,13 +155,13 @@ def stop_description(self, stream): self.step_thread_plan.GetDescription(stream, lldb.eDescriptionLevelBrief) + # Here's another example which does "step over" through the current function, # and when it stops at each line, it checks some condition (in this example the # value of a variable) and stops if that condition is true. class StepCheckingCondition: - def __init__(self, thread_plan, dict): self.thread_plan = thread_plan self.start_frame = thread_plan.GetThread().GetFrameAtIndex(0) @@ -174,7 +174,8 @@ end_address = cur_line_entry.GetEndAddress() line_range = end_address.GetFileAddress() - start_address.GetFileAddress() self.step_thread_plan = self.thread_plan.QueueThreadPlanForStepOverRange( - start_address, line_range) + start_address, line_range + ) def explains_stop(self, event): # We are stepping, so if we stop for any other reason, it isn't @@ -217,6 +218,7 @@ def stop_description(self, stream): stream.Print(f"Stepped until a == 20") + # Here's an example that steps out of the current frame, gathers some information # and then continues. The information in this case is rax. Currently the thread # plans are not a safe place to call lldb command-line commands, so the information @@ -224,11 +226,9 @@ class FinishPrintAndContinue: - def __init__(self, thread_plan, dict): self.thread_plan = thread_plan - self.step_out_thread_plan = thread_plan.QueueThreadPlanForStepOut( - 0, True) + self.step_out_thread_plan = thread_plan.QueueThreadPlanForStepOut(0, True) self.thread = self.thread_plan.GetThread() def is_stale(self): diff --git a/lldb/examples/python/shadow.py b/lldb/examples/python/shadow.py --- a/lldb/examples/python/shadow.py +++ b/lldb/examples/python/shadow.py @@ -6,12 +6,15 @@ @lldb.command("shadow") def check_shadow_command(debugger, command, exe_ctx, result, dict): - '''Check the currently selected stack frame for shadowed variables''' + """Check the currently selected stack frame for shadowed variables""" process = exe_ctx.GetProcess() state = process.GetState() if state != lldb.eStateStopped: - print("process must be stopped, state is %s" % lldb.SBDebugger.StateAsCString( - state), file=result) + print( + "process must be stopped, state is %s" + % lldb.SBDebugger.StateAsCString(state), + file=result, + ) return frame = exe_ctx.GetFrame() if not frame: @@ -55,4 +58,4 @@ for shadow_var in shadow_vars: print(str(shadow_var.GetDeclaration()), file=result) if num_shadowed_variables == 0: - print('no variables are shadowed', file=result) + print("no variables are shadowed", file=result) diff --git a/lldb/examples/python/sources.py b/lldb/examples/python/sources.py --- a/lldb/examples/python/sources.py +++ b/lldb/examples/python/sources.py @@ -13,7 +13,7 @@ def info_sources(debugger, command, result, dict): - description = '''This command will dump all compile units in any modules that are listed as arguments, or for all modules if no arguments are supplied.''' + description = """This command will dump all compile units in any modules that are listed as arguments, or for all modules if no arguments are supplied.""" module_names = shlex.split(command) target = debugger.GetSelectedTarget() if module_names: @@ -26,6 +26,7 @@ def __lldb_init_module(debugger, dict): # Add any commands contained in this module to LLDB - debugger.HandleCommand( - 'command script add -o -f sources.info_sources info_sources') - print('The "info_sources" command has been installed, type "help info_sources" or "info_sources --help" for detailed help.') + debugger.HandleCommand("command script add -o -f sources.info_sources info_sources") + print( + 'The "info_sources" command has been installed, type "help info_sources" or "info_sources --help" for detailed help.' + ) diff --git a/lldb/examples/python/stacks.py b/lldb/examples/python/stacks.py --- a/lldb/examples/python/stacks.py +++ b/lldb/examples/python/stacks.py @@ -7,16 +7,16 @@ def stack_frames(debugger, command, result, dict): command_args = shlex.split(command) usage = "usage: %prog [options] [PATH ...]" - description = '''This command will enumerate all stack frames, print the stack size for each, and print an aggregation of which functions have the largest stack frame sizes at the end.''' - parser = optparse.OptionParser( - description=description, prog='ls', usage=usage) + description = """This command will enumerate all stack frames, print the stack size for each, and print an aggregation of which functions have the largest stack frame sizes at the end.""" + parser = optparse.OptionParser(description=description, prog="ls", usage=usage) parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', - help='display verbose debug info', - default=False) + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="display verbose debug info", + default=False, + ) try: (options, args) = parser.parse_args(command_args) except: @@ -63,6 +63,7 @@ def __lldb_init_module(debugger, internal_dict): - debugger.HandleCommand( - "command script add -o -f stacks.stack_frames stack_frames") - print("A new command called 'stack_frames' was added, type 'stack_frames --help' for more information.") + debugger.HandleCommand("command script add -o -f stacks.stack_frames stack_frames") + print( + "A new command called 'stack_frames' was added, type 'stack_frames --help' for more information." + ) diff --git a/lldb/examples/python/step_and_print.py b/lldb/examples/python/step_and_print.py --- a/lldb/examples/python/step_and_print.py +++ b/lldb/examples/python/step_and_print.py @@ -1,6 +1,7 @@ """ Does a step-over then prints the local variables or only the ones passed in """ import lldb + class StepAndPrint: def __init__(self, debugger, unused): return @@ -13,12 +14,15 @@ debugger.HandleCommand("thread step-over") print("---------- Values: -------------------\n") - debugger.HandleCommand("frame variable %s"%(command)) + debugger.HandleCommand("frame variable %s" % (command)) debugger.SetAsync(old_async) def get_short_help(self): - return "Does a step-over then runs frame variable passing the command args to it\n" + return ( + "Does a step-over then runs frame variable passing the command args to it\n" + ) + def __lldb_init_module(debugger, unused): debugger.HandleCommand("command script add -o -c step_and_print.StepAndPrint sap") diff --git a/lldb/examples/python/symbolication.py b/lldb/examples/python/symbolication.py --- a/lldb/examples/python/symbolication.py +++ b/lldb/examples/python/symbolication.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # Be sure to add the python path that points to the LLDB shared library. # # To use this in the embedded python interpreter using "lldb": @@ -24,7 +24,7 @@ # # On MacOSX sh, bash: # PYTHONPATH=/path/to/LLDB.framework/Resources/Python ./crashlog.py ~/Library/Logs/DiagnosticReports/a.crash -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- import lldb import optparse @@ -52,7 +52,9 @@ # Any original textual description of this address to be used as a # backup in case symbolication fails self.description = None - self.symbolication = None # The cached symbolicated string that describes this address + self.symbolication = ( + None # The cached symbolicated string that describes this address + ) self.inlined = False def __str__(self): @@ -78,7 +80,8 @@ sb_addr = self.resolve_addr() if sb_addr: self.sym_ctx = self.target.ResolveSymbolContextForAddress( - sb_addr, lldb.eSymbolContextEverything) + sb_addr, lldb.eSymbolContextEverything + ) else: self.sym_ctx = lldb.SBSymbolContext() return self.sym_ctx @@ -94,7 +97,7 @@ def symbolicate(self, verbose=False): if self.symbolication is None: - self.symbolication = '' + self.symbolication = "" self.inlined = False sym_ctx = self.get_symbol_context() if sym_ctx: @@ -102,9 +105,9 @@ if module: # Print full source file path in verbose mode if verbose: - self.symbolication += str(module.GetFileSpec()) + '`' + self.symbolication += str(module.GetFileSpec()) + "`" else: - self.symbolication += module.GetFileSpec().GetFilename() + '`' + self.symbolication += module.GetFileSpec().GetFilename() + "`" function_start_load_addr = -1 function = sym_ctx.GetFunction() block = sym_ctx.GetBlock() @@ -116,22 +119,30 @@ if inlined_block: self.inlined = True - self.symbolication += ' [inlined] ' + \ - inlined_block.GetInlinedName() - block_range_idx = inlined_block.GetRangeIndexForBlockAddress( - self.so_addr) + self.symbolication += ( + " [inlined] " + inlined_block.GetInlinedName() + ) + block_range_idx = ( + inlined_block.GetRangeIndexForBlockAddress(self.so_addr) + ) if block_range_idx < lldb.UINT32_MAX: - block_range_start_addr = inlined_block.GetRangeStartAddress( - block_range_idx) - function_start_load_addr = block_range_start_addr.GetLoadAddress( - self.target) + block_range_start_addr = ( + inlined_block.GetRangeStartAddress(block_range_idx) + ) + function_start_load_addr = ( + block_range_start_addr.GetLoadAddress(self.target) + ) if function_start_load_addr == -1: - function_start_load_addr = function.GetStartAddress().GetLoadAddress(self.target) + function_start_load_addr = ( + function.GetStartAddress().GetLoadAddress(self.target) + ) elif symbol: self.symbolication += symbol.GetName() - function_start_load_addr = symbol.GetStartAddress().GetLoadAddress(self.target) + function_start_load_addr = ( + symbol.GetStartAddress().GetLoadAddress(self.target) + ) else: - self.symbolication = '' + self.symbolication = "" return False # Dump the offset from the current function or symbol if it @@ -140,29 +151,36 @@ if function_offset > 0: self.symbolication += " + %u" % (function_offset) elif function_offset < 0: - self.symbolication += " %i (invalid negative offset, file a bug) " % function_offset + self.symbolication += ( + " %i (invalid negative offset, file a bug) " + % function_offset + ) # Print out any line information if any is available if line_entry.GetFileSpec(): # Print full source file path in verbose mode if verbose: - self.symbolication += ' at %s' % line_entry.GetFileSpec() + self.symbolication += " at %s" % line_entry.GetFileSpec() else: - self.symbolication += ' at %s' % line_entry.GetFileSpec().GetFilename() - self.symbolication += ':%u' % line_entry.GetLine() + self.symbolication += ( + " at %s" % line_entry.GetFileSpec().GetFilename() + ) + self.symbolication += ":%u" % line_entry.GetLine() column = line_entry.GetColumn() if column > 0: - self.symbolication += ':%u' % column + self.symbolication += ":%u" % column return True return False class Section: """Class that represents an load address range""" - sect_info_regex = re.compile('(?P[^=]+)=(?P.*)') - addr_regex = re.compile('^\s*(?P0x[0-9A-Fa-f]+)\s*$') + + sect_info_regex = re.compile("(?P[^=]+)=(?P.*)") + addr_regex = re.compile("^\s*(?P0x[0-9A-Fa-f]+)\s*$") range_regex = re.compile( - '^\s*(?P0x[0-9A-Fa-f]+)\s*(?P[-+])\s*(?P0x[0-9A-Fa-f]+)\s*$') + "^\s*(?P0x[0-9A-Fa-f]+)\s*(?P[-+])\s*(?P0x[0-9A-Fa-f]+)\s*$" + ) def __init__(self, start_addr=None, end_addr=None, name=None): self.start_addr = start_addr @@ -173,11 +191,7 @@ def InitWithSBTargetAndSBSection(cls, target, section): sect_load_addr = section.GetLoadAddress(target) if sect_load_addr != lldb.LLDB_INVALID_ADDRESS: - obj = cls( - sect_load_addr, - sect_load_addr + - section.size, - section.name) + obj = cls(sect_load_addr, sect_load_addr + section.size, section.name) return obj else: return None @@ -188,29 +202,35 @@ def set_from_string(self, s): match = self.sect_info_regex.match(s) if match: - self.name = match.group('name') - range_str = match.group('range') + self.name = match.group("name") + range_str = match.group("range") addr_match = self.addr_regex.match(range_str) if addr_match: - self.start_addr = int(addr_match.group('start'), 16) + self.start_addr = int(addr_match.group("start"), 16) self.end_addr = None return True range_match = self.range_regex.match(range_str) if range_match: - self.start_addr = int(range_match.group('start'), 16) - self.end_addr = int(range_match.group('end'), 16) - op = range_match.group('op') - if op == '+': + self.start_addr = int(range_match.group("start"), 16) + self.end_addr = int(range_match.group("end"), 16) + op = range_match.group("op") + if op == "+": self.end_addr += self.start_addr return True print('error: invalid section info string "%s"' % s) - print('Valid section info formats are:') - print('Format Example Description') - print('--------------------- -----------------------------------------------') - print('= __TEXT=0x123000 Section from base address only') - print('=- __TEXT=0x123000-0x124000 Section from base address and end address') - print('=+ __TEXT=0x123000+0x1000 Section from base address and size') + print("Valid section info formats are:") + print("Format Example Description") + print("--------------------- -----------------------------------------------") + print( + "= __TEXT=0x123000 Section from base address only" + ) + print( + "=- __TEXT=0x123000-0x124000 Section from base address and end address" + ) + print( + "=+ __TEXT=0x123000+0x1000 Section from base address and size" + ) return False def __str__(self): @@ -218,7 +238,10 @@ if self.end_addr is not None: if self.start_addr is not None: return "%s=[0x%16.16x - 0x%16.16x)" % ( - self.name, self.start_addr, self.end_addr) + self.name, + self.start_addr, + self.end_addr, + ) else: if self.start_addr is not None: return "%s=0x%16.16x" % (self.name, self.start_addr) @@ -247,13 +270,12 @@ @classmethod def InitWithSBTargetAndSBModule(cls, target, module): - '''Initialize this Image object with a module from a target.''' + """Initialize this Image object with a module from a target.""" obj = cls(module.file.fullpath, module.uuid) obj.resolved_path = module.platform_file.fullpath obj.resolved = True for section in module.sections: - symb_section = Section.InitWithSBTargetAndSBSection( - target, section) + symb_section = Section.InitWithSBTargetAndSBSection(target, section) if symb_section: obj.section_infos.append(symb_section) obj.arch = module.triple @@ -268,19 +290,19 @@ def debug_dump(self): print('path = "%s"' % (self.path)) print('resolved_path = "%s"' % (self.resolved_path)) - print('resolved = %i' % (self.resolved)) - print('unavailable = %i' % (self.unavailable)) - print('uuid = %s' % (self.uuid)) - print('section_infos = %s' % (self.section_infos)) + print("resolved = %i" % (self.resolved)) + print("unavailable = %i" % (self.unavailable)) + print("uuid = %s" % (self.uuid)) + print("section_infos = %s" % (self.section_infos)) print('identifier = "%s"' % (self.identifier)) - print('version = %s' % (self.version)) - print('arch = %s' % (self.arch)) - print('module = %s' % (self.module)) + print("version = %s" % (self.version)) + print("arch = %s" % (self.arch)) + print("module = %s" % (self.module)) print('symfile = "%s"' % (self.symfile)) - print('slide = %i (0x%x)' % (self.slide, self.slide)) + print("slide = %i (0x%x)" % (self.slide, self.slide)) def __str__(self): - s = '' + s = "" if self.uuid: s += "%s " % (self.get_uuid()) if self.arch: @@ -293,7 +315,7 @@ for section_info in self.section_infos: s += ", %s" % (section_info) if self.slide is not None: - s += ', slide = 0x%16.16x' % self.slide + s += ", slide = 0x%16.16x" % self.slide return s def add_section(self, section): @@ -339,37 +361,41 @@ num_sections_loaded = 0 for section_info in self.section_infos: if section_info.name: - section = self.module.FindSection( - section_info.name) + section = self.module.FindSection(section_info.name) if section: error = target.SetSectionLoadAddress( - section, section_info.start_addr) + section, section_info.start_addr + ) if error.Success(): num_sections_loaded += 1 else: - return 'error: %s' % error.GetCString() + return "error: %s" % error.GetCString() else: - return 'error: unable to find the section named "%s"' % section_info.name + return ( + 'error: unable to find the section named "%s"' + % section_info.name + ) else: return 'error: unable to find "%s" section in "%s"' % ( - range.name, self.get_resolved_path()) + range.name, + self.get_resolved_path(), + ) if num_sections_loaded == 0: - return 'error: no sections were successfully loaded' + return "error: no sections were successfully loaded" else: - err = target.SetModuleLoadAddress( - self.module, self.slide) + err = target.SetModuleLoadAddress(self.module, self.slide) if err.Fail(): return err.GetCString() return None else: - return 'error: invalid module' + return "error: invalid module" else: - return 'error: invalid target' + return "error: invalid target" else: - return 'error: no section infos' + return "error: no section infos" def add_module(self, target, obj_dir=None): - '''Add the Image described in this object to "target" and load the sections if "load" is True.''' + """Add the Image described in this object to "target" and load the sections if "load" is True.""" if target: # Try and find using UUID only first so that paths need not match # up @@ -381,23 +407,26 @@ if not self.unavailable: resolved_path = self.get_resolved_path() self.module = target.AddModule( - resolved_path, None, uuid_str, self.symfile) + resolved_path, None, uuid_str, self.symfile + ) if not self.module and self.section_infos: name = os.path.basename(self.path) if obj_dir and os.path.isdir(obj_dir): data = { - 'triple': target.triple, - 'uuid': uuid_str, - 'type': 'sharedlibrary', - 'sections': list(), - 'symbols': list() + "triple": target.triple, + "uuid": uuid_str, + "type": "sharedlibrary", + "sections": list(), + "symbols": list(), } for section in self.section_infos: - data['sections'].append({ - 'name' : section.name, - 'size': section.end_addr - section.start_addr - }) - data['symbols'] = list(self.symbols.values()) + data["sections"].append( + { + "name": section.name, + "size": section.end_addr - section.start_addr, + } + ) + data["symbols"] = list(self.symbols.values()) obj_file = os.path.join(obj_dir, name) with open(obj_file, "w") as f: f.write(json.dumps(data, indent=4)) @@ -409,13 +438,17 @@ self.unavailable = False if not self.module and not self.unavailable: return 'error: unable to get module for (%s) "%s"' % ( - self.arch, self.get_resolved_path()) + self.arch, + self.get_resolved_path(), + ) if self.has_section_load_info(): return self.load_module(target) else: - return None # No sections, the module was added to the target, so success + return ( + None # No sections, the module was added to the target, so success + ) else: - return 'error: invalid target' + return "error: invalid target" def locate_module_and_debug_symbols(self): # By default, just use the paths that were supplied in: @@ -438,7 +471,7 @@ return None def create_target(self, debugger): - '''Create a target using the information in this Image object.''' + """Create a target using the information in this Image object.""" if self.unavailable: return None @@ -446,24 +479,28 @@ resolved_path = self.get_resolved_path() path_spec = lldb.SBFileSpec(resolved_path) error = lldb.SBError() - target = debugger.CreateTarget( - resolved_path, self.arch, None, False, error) + target = debugger.CreateTarget(resolved_path, self.arch, None, False, error) if target: self.module = target.FindModule(path_spec) if self.has_section_load_info(): err = self.load_module(target) if err: - print('ERROR: ', err) + print("ERROR: ", err) return target else: - print('error: unable to create a valid target for (%s) "%s"' % (self.arch, self.path)) + print( + 'error: unable to create a valid target for (%s) "%s"' + % (self.arch, self.path) + ) else: - print('error: unable to locate main executable (%s) "%s"' % (self.arch, self.path)) + print( + 'error: unable to locate main executable (%s) "%s"' + % (self.arch, self.path) + ) return None class Symbolicator: - def __init__(self, debugger=None, target=None, images=list()): """A class the represents the information needed to symbolicate addresses in a program. @@ -474,7 +511,7 @@ self.debugger = debugger self.target = target self.images = images # a list of images to be used when symbolicating - self.addr_mask = 0xffffffffffffffff + self.addr_mask = 0xFFFFFFFFFFFFFFFF @classmethod def InitWithSBTarget(cls, target): @@ -482,9 +519,9 @@ obj = cls(target=target) triple = target.triple if triple: - arch = triple.split('-')[0] + arch = triple.split("-")[0] if "arm" in arch: - obj.addr_mask = 0xfffffffffffffffe + obj.addr_mask = 0xFFFFFFFFFFFFFFFE for module in target.modules: image = Image.InitWithSBTargetAndSBModule(target, module) @@ -507,7 +544,7 @@ s += str(m) + "\n" s += "Images:\n" for image in self.images: - s += ' %s\n' % (image) + s += " %s\n" % (image) return s def find_images_with_identifier(self, identifier): @@ -516,7 +553,7 @@ if image.identifier == identifier: images.append(image) if len(images) == 0: - regex_text = '^.*\.%s$' % (re.escape(identifier)) + regex_text = "^.*\.%s$" % (re.escape(identifier)) regex = re.compile(regex_text) for image in self.images: if regex.match(image.identifier): @@ -540,9 +577,9 @@ if self.target.GetAddressByteSize() == 4: triple = self.target.triple if triple: - arch = triple.split('-')[0] + arch = triple.split("-")[0] if "arm" in arch: - self.addr_mask = 0xfffffffffffffffe + self.addr_mask = 0xFFFFFFFFFFFFFFFE return self.target return None @@ -571,16 +608,20 @@ # See if we were able to reconstruct anything? while True: inlined_parent_so_addr = lldb.SBAddress() - inlined_parent_sym_ctx = symbolicated_address.sym_ctx.GetParentOfInlinedScope( - symbolicated_address.so_addr, inlined_parent_so_addr) + inlined_parent_sym_ctx = ( + symbolicated_address.sym_ctx.GetParentOfInlinedScope( + symbolicated_address.so_addr, inlined_parent_so_addr + ) + ) if not inlined_parent_sym_ctx: break if not inlined_parent_so_addr: break symbolicated_address = Address( - self.target, inlined_parent_so_addr.GetLoadAddress( - self.target)) + self.target, + inlined_parent_so_addr.GetLoadAddress(self.target), + ) symbolicated_address.sym_ctx = inlined_parent_sym_ctx symbolicated_address.so_addr = inlined_parent_so_addr symbolicated_address.symbolicate(verbose) @@ -591,17 +632,13 @@ if symbolicated_addresses: return symbolicated_addresses else: - print('error: no target in Symbolicator') + print("error: no target in Symbolicator") return None def disassemble_instructions( - target, - instructions, - pc, - insts_before_pc, - insts_after_pc, - non_zeroeth_frame): + target, instructions, pc, insts_before_pc, insts_after_pc, non_zeroeth_frame +): lines = list() pc_index = -1 comment_column = 50 @@ -616,7 +653,7 @@ if comment: line_len = len(lines[-1]) if line_len < comment_column: - lines[-1] += ' ' * (comment_column - line_len) + lines[-1] += " " * (comment_column - line_len) lines[-1] += "; %s" % comment if pc_index >= 0: @@ -638,9 +675,9 @@ end_idx = inst_idx for i in range(start_idx, end_idx + 1): if i == pc_index: - print(' -> ', lines[i]) + print(" -> ", lines[i]) else: - print(' ', lines[i]) + print(" ", lines[i]) def print_module_section_data(section): @@ -657,8 +694,7 @@ if depth > 0: num_sub_sections = section.GetNumSubSections() for sect_idx in range(num_sub_sections): - print_module_section( - section.GetSubSectionAtIndex(sect_idx), depth - 1) + print_module_section(section.GetSubSectionAtIndex(sect_idx), depth - 1) def print_module_sections(module, depth): @@ -672,55 +708,61 @@ def Symbolicate(debugger, command_args): - usage = "usage: %prog [options] [addr2 ...]" - description = '''Symbolicate one or more addresses using LLDB's python scripting API..''' + description = ( + """Symbolicate one or more addresses using LLDB's python scripting API..""" + ) parser = optparse.OptionParser( - description=description, - prog='crashlog.py', - usage=usage) + description=description, prog="crashlog.py", usage=usage + ) parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', - help='display verbose debug info', - default=False) + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="display verbose debug info", + default=False, + ) parser.add_option( - '-p', - '--platform', - type='string', - metavar='platform', - dest='platform', - help='Specify the platform to use when creating the debug target. Valid values include "localhost", "darwin-kernel", "ios-simulator", "remote-freebsd", "remote-macosx", "remote-ios", "remote-linux".') + "-p", + "--platform", + type="string", + metavar="platform", + dest="platform", + help='Specify the platform to use when creating the debug target. Valid values include "localhost", "darwin-kernel", "ios-simulator", "remote-freebsd", "remote-macosx", "remote-ios", "remote-linux".', + ) parser.add_option( - '-f', - '--file', - type='string', - metavar='file', - dest='file', - help='Specify a file to use when symbolicating') + "-f", + "--file", + type="string", + metavar="file", + dest="file", + help="Specify a file to use when symbolicating", + ) parser.add_option( - '-a', - '--arch', - type='string', - metavar='arch', - dest='arch', - help='Specify a architecture to use when symbolicating') + "-a", + "--arch", + type="string", + metavar="arch", + dest="arch", + help="Specify a architecture to use when symbolicating", + ) parser.add_option( - '-s', - '--slide', - type='int', - metavar='slide', - dest='slide', - help='Specify the slide to use on the file specified with the --file option', - default=None) + "-s", + "--slide", + type="int", + metavar="slide", + dest="slide", + help="Specify the slide to use on the file specified with the --file option", + default=None, + ) parser.add_option( - '--section', - type='string', - action='append', - dest='section_strings', - help='specify = or =-') + "--section", + type="string", + action="append", + dest="section_strings", + help="specify = or =-", + ) try: (options, args) = parser.parse_args(command_args) except: @@ -749,15 +791,15 @@ if target: for addr_str in args: addr = int(addr_str, 0) - symbolicated_addrs = symbolicator.symbolicate( - addr, options.verbose) + symbolicated_addrs = symbolicator.symbolicate(addr, options.verbose) for symbolicated_addr in symbolicated_addrs: print(symbolicated_addr) print() else: - print('error: no target for %s' % (symbolicator)) + print("error: no target for %s" % (symbolicator)) + -if __name__ == '__main__': +if __name__ == "__main__": # Create a new debugger instance debugger = lldb.SBDebugger.Create() Symbolicate(debugger, sys.argv[1:]) diff --git a/lldb/examples/python/types.py b/lldb/examples/python/types.py --- a/lldb/examples/python/types.py +++ b/lldb/examples/python/types.py @@ -1,13 +1,13 @@ #!/usr/bin/env python -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # Be sure to add the python path that points to the LLDB shared library. # # # To use this in the embedded python interpreter using "lldb" just # import it with the full path using the "command script import" # command # (lldb) command script import /path/to/cmdtemplate.py -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- import platform import os @@ -23,18 +23,21 @@ lldb_python_dirs = list() # lldb is not in the PYTHONPATH, try some defaults for the current platform platform_system = platform.system() - if platform_system == 'Darwin': + if platform_system == "Darwin": # On Darwin, try the currently selected Xcode directory xcode_dir = subprocess.check_output("xcode-select --print-path", shell=True) if xcode_dir: lldb_python_dirs.append( os.path.realpath( - xcode_dir + - '/../SharedFrameworks/LLDB.framework/Resources/Python')) + xcode_dir + "/../SharedFrameworks/LLDB.framework/Resources/Python" + ) + ) lldb_python_dirs.append( - xcode_dir + '/Library/PrivateFrameworks/LLDB.framework/Resources/Python') + xcode_dir + "/Library/PrivateFrameworks/LLDB.framework/Resources/Python" + ) lldb_python_dirs.append( - '/System/Library/PrivateFrameworks/LLDB.framework/Resources/Python') + "/System/Library/PrivateFrameworks/LLDB.framework/Resources/Python" + ) success = False for lldb_python_dir in lldb_python_dirs: if os.path.exists(lldb_python_dir): @@ -49,7 +52,9 @@ success = True break if not success: - print("error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly") + print( + "error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly" + ) sys.exit(1) import optparse @@ -59,7 +64,7 @@ def regex_option_callback(option, opt_str, value, parser): if opt_str == "--std": - value = '^std::' + value = "^std::" regex = re.compile(value) parser.values.skip_type_regexes.append(regex) @@ -67,91 +72,98 @@ def create_types_options(for_lldb_command): if for_lldb_command: usage = "usage: %prog [options]" - description = '''This command will help check for padding in between + description = """This command will help check for padding in between base classes and members in structs and classes. It will summarize the types and how much padding was found. If no types are specified with the --types TYPENAME option, all structure and class types will be verified. If no modules are specified with the --module option, only the target's main executable will be searched. -''' +""" else: usage = "usage: %prog [options] EXEPATH [EXEPATH ...]" - description = '''This command will help check for padding in between + description = """This command will help check for padding in between base classes and members in structures and classes. It will summarize the types and how much padding was found. One or more paths to executable files must be specified and targets will be created with these modules. If no types are specified with the --types TYPENAME option, all structure and class types will be verified in all specified modules. -''' +""" parser = optparse.OptionParser( - description=description, - prog='framestats', - usage=usage) + description=description, prog="framestats", usage=usage + ) if not for_lldb_command: parser.add_option( - '-a', - '--arch', - type='string', - dest='arch', - help='The architecture to use when creating the debug target.', - default=None) + "-a", + "--arch", + type="string", + dest="arch", + help="The architecture to use when creating the debug target.", + default=None, + ) parser.add_option( - '-p', - '--platform', - type='string', - metavar='platform', - dest='platform', - help='Specify the platform to use when creating the debug target. Valid values include "localhost", "darwin-kernel", "ios-simulator", "remote-freebsd", "remote-macosx", "remote-ios", "remote-linux".') + "-p", + "--platform", + type="string", + metavar="platform", + dest="platform", + help='Specify the platform to use when creating the debug target. Valid values include "localhost", "darwin-kernel", "ios-simulator", "remote-freebsd", "remote-macosx", "remote-ios", "remote-linux".', + ) parser.add_option( - '-m', - '--module', - action='append', - type='string', - metavar='MODULE', - dest='modules', - help='Specify one or more modules which will be used to verify the types.', - default=[]) + "-m", + "--module", + action="append", + type="string", + metavar="MODULE", + dest="modules", + help="Specify one or more modules which will be used to verify the types.", + default=[], + ) parser.add_option( - '-d', - '--debug', - action='store_true', - dest='debug', - help='Pause 10 seconds to wait for a debugger to attach.', - default=False) + "-d", + "--debug", + action="store_true", + dest="debug", + help="Pause 10 seconds to wait for a debugger to attach.", + default=False, + ) parser.add_option( - '-t', - '--type', - action='append', - type='string', - metavar='TYPENAME', - dest='typenames', - help='Specify one or more type names which should be verified. If no type names are specified, all class and struct types will be verified.', - default=[]) + "-t", + "--type", + action="append", + type="string", + metavar="TYPENAME", + dest="typenames", + help="Specify one or more type names which should be verified. If no type names are specified, all class and struct types will be verified.", + default=[], + ) parser.add_option( - '-v', - '--verbose', - action='store_true', - dest='verbose', - help='Enable verbose logging and information.', - default=False) + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="Enable verbose logging and information.", + default=False, + ) parser.add_option( - '-s', - '--skip-type-regex', + "-s", + "--skip-type-regex", action="callback", callback=regex_option_callback, - type='string', - metavar='REGEX', - dest='skip_type_regexes', - help='Regular expressions that, if they match the current member typename, will cause the type to no be recursively displayed.', - default=[]) + type="string", + metavar="REGEX", + dest="skip_type_regexes", + help="Regular expressions that, if they match the current member typename, will cause the type to no be recursively displayed.", + default=[], + ) parser.add_option( - '--std', + "--std", action="callback", callback=regex_option_callback, - metavar='REGEX', - dest='skip_type_regexes', + metavar="REGEX", + dest="skip_type_regexes", help="Don't' recurse into types in the std namespace.", - default=[]) + default=[], + ) return parser @@ -159,35 +171,35 @@ print(type) typename = type.GetName() # print 'type: %s' % (typename) - (end_offset, padding) = verify_type_recursive( - target, options, type, None, 0, 0, 0) + (end_offset, padding) = verify_type_recursive(target, options, type, None, 0, 0, 0) byte_size = type.GetByteSize() # if end_offset < byte_size: # last_member_padding = byte_size - end_offset # print '%+4u <%u> padding' % (end_offset, last_member_padding) # padding += last_member_padding - print('Total byte size: %u' % (byte_size)) - print('Total pad bytes: %u' % (padding)) + print("Total byte size: %u" % (byte_size)) + print("Total pad bytes: %u" % (padding)) if padding > 0: - print('Padding percentage: %2.2f %%' % ((float(padding) / float(byte_size)) * 100.0)) + print( + "Padding percentage: %2.2f %%" + % ((float(padding) / float(byte_size)) * 100.0) + ) print() def verify_type_recursive( - target, - options, - type, - member_name, - depth, - base_offset, - padding): + target, options, type, member_name, depth, base_offset, padding +): prev_end_offset = base_offset typename = type.GetName() byte_size = type.GetByteSize() if member_name and member_name != typename: - print('%+4u <%3u> %s%s %s;' % (base_offset, byte_size, ' ' * depth, typename, member_name)) + print( + "%+4u <%3u> %s%s %s;" + % (base_offset, byte_size, " " * depth, typename, member_name) + ) else: - print('%+4u {%3u} %s%s' % (base_offset, byte_size, ' ' * depth, typename)) + print("%+4u {%3u} %s%s" % (base_offset, byte_size, " " * depth, typename)) for type_regex in options.skip_type_regexes: match = type_regex.match(typename) @@ -205,44 +217,82 @@ member_total_offset = member_offset + base_offset member_byte_size = member_type.GetByteSize() member_is_class_or_struct = False - if member_type_class == lldb.eTypeClassStruct or member_type_class == lldb.eTypeClassClass: + if ( + member_type_class == lldb.eTypeClassStruct + or member_type_class == lldb.eTypeClassClass + ): member_is_class_or_struct = True - if member_idx == 0 and member_offset == target.GetAddressByteSize( - ) and type.IsPolymorphicClass(): + if ( + member_idx == 0 + and member_offset == target.GetAddressByteSize() + and type.IsPolymorphicClass() + ): ptr_size = target.GetAddressByteSize() - print('%+4u <%3u> %s__vtbl_ptr_type * _vptr;' % (prev_end_offset, ptr_size, ' ' * (depth + 1))) + print( + "%+4u <%3u> %s__vtbl_ptr_type * _vptr;" + % (prev_end_offset, ptr_size, " " * (depth + 1)) + ) prev_end_offset = ptr_size else: if prev_end_offset < member_total_offset: member_padding = member_total_offset - prev_end_offset padding = padding + member_padding - print('%+4u <%3u> %s' % (prev_end_offset, member_padding, ' ' * (depth + 1))) + print( + "%+4u <%3u> %s" + % (prev_end_offset, member_padding, " " * (depth + 1)) + ) if member_is_class_or_struct: - (prev_end_offset, - padding) = verify_type_recursive(target, - options, - member_canonical_type, - member_name, - depth + 1, - member_total_offset, - padding) + (prev_end_offset, padding) = verify_type_recursive( + target, + options, + member_canonical_type, + member_name, + depth + 1, + member_total_offset, + padding, + ) else: prev_end_offset = member_total_offset + member_byte_size member_typename = member_type.GetName() if member.IsBitfield(): - print('%+4u <%3u> %s%s:%u %s;' % (member_total_offset, member_byte_size, ' ' * (depth + 1), member_typename, member.GetBitfieldSizeInBits(), member_name)) + print( + "%+4u <%3u> %s%s:%u %s;" + % ( + member_total_offset, + member_byte_size, + " " * (depth + 1), + member_typename, + member.GetBitfieldSizeInBits(), + member_name, + ) + ) else: - print('%+4u <%3u> %s%s %s;' % (member_total_offset, member_byte_size, ' ' * (depth + 1), member_typename, member_name)) + print( + "%+4u <%3u> %s%s %s;" + % ( + member_total_offset, + member_byte_size, + " " * (depth + 1), + member_typename, + member_name, + ) + ) if prev_end_offset < byte_size: last_member_padding = byte_size - prev_end_offset - print('%+4u <%3u> %s' % (prev_end_offset, last_member_padding, ' ' * (depth + 1))) + print( + "%+4u <%3u> %s" + % (prev_end_offset, last_member_padding, " " * (depth + 1)) + ) padding += last_member_padding else: if type.IsPolymorphicClass(): ptr_size = target.GetAddressByteSize() - print('%+4u <%3u> %s__vtbl_ptr_type * _vptr;' % (prev_end_offset, ptr_size, ' ' * (depth + 1))) + print( + "%+4u <%3u> %s__vtbl_ptr_type * _vptr;" + % (prev_end_offset, ptr_size, " " * (depth + 1)) + ) prev_end_offset = ptr_size prev_end_offset = base_offset + byte_size @@ -281,9 +331,8 @@ def verify_types(target, options): - if not target: - print('error: invalid target') + print("error: invalid target") return modules = list() @@ -300,26 +349,32 @@ if modules: for module in modules: - print('module: %s' % (module.file)) + print("module: %s" % (module.file)) if options.typenames: for typename in options.typenames: types = module.FindTypes(typename) if types.GetSize(): - print('Found %u types matching "%s" in "%s"' % (len(types), typename, module.file)) + print( + 'Found %u types matching "%s" in "%s"' + % (len(types), typename, module.file) + ) for type in types: verify_type(target, options, type) else: - print('error: no type matches "%s" in "%s"' % (typename, module.file)) + print( + 'error: no type matches "%s" in "%s"' + % (typename, module.file) + ) else: - types = module.GetTypes( - lldb.eTypeClassClass | lldb.eTypeClassStruct) + types = module.GetTypes(lldb.eTypeClassClass | lldb.eTypeClassStruct) print('Found %u types in "%s"' % (len(types), module.file)) for type in types: verify_type(target, options, type) else: - print('error: no modules') + print("error: no modules") + -if __name__ == '__main__': +if __name__ == "__main__": debugger = lldb.SBDebugger.Create() parser = create_types_options(False) @@ -339,17 +394,19 @@ # this is the best practice to access those objects from within a # command error = lldb.SBError() - target = debugger.CreateTarget(path, - options.arch, - options.platform, - True, - error) + target = debugger.CreateTarget( + path, options.arch, options.platform, True, error + ) if error.Fail(): print(error.GetCString()) continue verify_types(target, options) + def __lldb_init_module(debugger, internal_dict): debugger.HandleCommand( - 'command script add -o -f types.check_padding_command check_padding') - print('"check_padding" command installed, use the "--help" option for detailed help') + "command script add -o -f types.check_padding_command check_padding" + ) + print( + '"check_padding" command installed, use the "--help" option for detailed help' + ) diff --git a/lldb/examples/python/x86_64_linux_target_definition.py b/lldb/examples/python/x86_64_linux_target_definition.py --- a/lldb/examples/python/x86_64_linux_target_definition.py +++ b/lldb/examples/python/x86_64_linux_target_definition.py @@ -1,13 +1,13 @@ #!/usr/bin/env python -#===-- x86_64_linux_target_definition.py -----------------------------*- C++ -*-===// +# ===-- x86_64_linux_target_definition.py -----------------------------*- C++ -*-===// # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # -#===----------------------------------------------------------------------===// +# ===----------------------------------------------------------------------===// -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # DESCRIPTION # # This file can be used with the following setting: @@ -35,156 +35,156 @@ # The target definition file will get used if and only if the # qRegisterInfo packets are not supported when connecting to a remote # GDB server. -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- from lldb import * # Compiler and DWARF register numbers name_to_gcc_dwarf_regnum = { - 'rax': 0, - 'rdx': 1, - 'rcx': 2, - 'rbx': 3, - 'rsi': 4, - 'rdi': 5, - 'rbp': 6, - 'rsp': 7, - 'r8': 8, - 'r9': 9, - 'r10': 10, - 'r11': 11, - 'r12': 12, - 'r13': 13, - 'r14': 14, - 'r15': 15, - 'rip': 16, - 'xmm0': 17, - 'xmm1': 18, - 'xmm2': 19, - 'xmm3': 20, - 'xmm4': 21, - 'xmm5': 22, - 'xmm6': 23, - 'xmm7': 24, - 'xmm8': 25, - 'xmm9': 26, - 'xmm10': 27, - 'xmm11': 28, - 'xmm12': 29, - 'xmm13': 30, - 'xmm14': 31, - 'xmm15': 32, - 'stmm0': 33, - 'stmm1': 34, - 'stmm2': 35, - 'stmm3': 36, - 'stmm4': 37, - 'stmm5': 38, - 'stmm6': 39, - 'stmm7': 30, - 'ymm0': 41, - 'ymm1': 42, - 'ymm2': 43, - 'ymm3': 44, - 'ymm4': 45, - 'ymm5': 46, - 'ymm6': 47, - 'ymm7': 48, - 'ymm8': 49, - 'ymm9': 40, - 'ymm10': 41, - 'ymm11': 42, - 'ymm12': 43, - 'ymm13': 44, - 'ymm14': 45, - 'ymm15': 46 + "rax": 0, + "rdx": 1, + "rcx": 2, + "rbx": 3, + "rsi": 4, + "rdi": 5, + "rbp": 6, + "rsp": 7, + "r8": 8, + "r9": 9, + "r10": 10, + "r11": 11, + "r12": 12, + "r13": 13, + "r14": 14, + "r15": 15, + "rip": 16, + "xmm0": 17, + "xmm1": 18, + "xmm2": 19, + "xmm3": 20, + "xmm4": 21, + "xmm5": 22, + "xmm6": 23, + "xmm7": 24, + "xmm8": 25, + "xmm9": 26, + "xmm10": 27, + "xmm11": 28, + "xmm12": 29, + "xmm13": 30, + "xmm14": 31, + "xmm15": 32, + "stmm0": 33, + "stmm1": 34, + "stmm2": 35, + "stmm3": 36, + "stmm4": 37, + "stmm5": 38, + "stmm6": 39, + "stmm7": 30, + "ymm0": 41, + "ymm1": 42, + "ymm2": 43, + "ymm3": 44, + "ymm4": 45, + "ymm5": 46, + "ymm6": 47, + "ymm7": 48, + "ymm8": 49, + "ymm9": 40, + "ymm10": 41, + "ymm11": 42, + "ymm12": 43, + "ymm13": 44, + "ymm14": 45, + "ymm15": 46, } name_to_gdb_regnum = { - 'rax': 0, - 'rbx': 1, - 'rcx': 2, - 'rdx': 3, - 'rsi': 4, - 'rdi': 5, - 'rbp': 6, - 'rsp': 7, - 'r8': 8, - 'r9': 9, - 'r10': 10, - 'r11': 11, - 'r12': 12, - 'r13': 13, - 'r14': 14, - 'r15': 15, - 'rip': 16, - 'rflags': 17, - 'cs': 18, - 'ss': 19, - 'ds': 20, - 'es': 21, - 'fs': 22, - 'gs': 23, - 'stmm0': 24, - 'stmm1': 25, - 'stmm2': 26, - 'stmm3': 27, - 'stmm4': 28, - 'stmm5': 29, - 'stmm6': 30, - 'stmm7': 31, - 'fctrl': 32, - 'fstat': 33, - 'ftag': 34, - 'fiseg': 35, - 'fioff': 36, - 'foseg': 37, - 'fooff': 38, - 'fop': 39, - 'xmm0': 40, - 'xmm1': 41, - 'xmm2': 42, - 'xmm3': 43, - 'xmm4': 44, - 'xmm5': 45, - 'xmm6': 46, - 'xmm7': 47, - 'xmm8': 48, - 'xmm9': 49, - 'xmm10': 50, - 'xmm11': 51, - 'xmm12': 52, - 'xmm13': 53, - 'xmm14': 54, - 'xmm15': 55, - 'mxcsr': 56, - 'ymm0': 57, - 'ymm1': 58, - 'ymm2': 59, - 'ymm3': 60, - 'ymm4': 61, - 'ymm5': 62, - 'ymm6': 63, - 'ymm7': 64, - 'ymm8': 65, - 'ymm9': 66, - 'ymm10': 67, - 'ymm11': 68, - 'ymm12': 69, - 'ymm13': 70, - 'ymm14': 71, - 'ymm15': 72 + "rax": 0, + "rbx": 1, + "rcx": 2, + "rdx": 3, + "rsi": 4, + "rdi": 5, + "rbp": 6, + "rsp": 7, + "r8": 8, + "r9": 9, + "r10": 10, + "r11": 11, + "r12": 12, + "r13": 13, + "r14": 14, + "r15": 15, + "rip": 16, + "rflags": 17, + "cs": 18, + "ss": 19, + "ds": 20, + "es": 21, + "fs": 22, + "gs": 23, + "stmm0": 24, + "stmm1": 25, + "stmm2": 26, + "stmm3": 27, + "stmm4": 28, + "stmm5": 29, + "stmm6": 30, + "stmm7": 31, + "fctrl": 32, + "fstat": 33, + "ftag": 34, + "fiseg": 35, + "fioff": 36, + "foseg": 37, + "fooff": 38, + "fop": 39, + "xmm0": 40, + "xmm1": 41, + "xmm2": 42, + "xmm3": 43, + "xmm4": 44, + "xmm5": 45, + "xmm6": 46, + "xmm7": 47, + "xmm8": 48, + "xmm9": 49, + "xmm10": 50, + "xmm11": 51, + "xmm12": 52, + "xmm13": 53, + "xmm14": 54, + "xmm15": 55, + "mxcsr": 56, + "ymm0": 57, + "ymm1": 58, + "ymm2": 59, + "ymm3": 60, + "ymm4": 61, + "ymm5": 62, + "ymm6": 63, + "ymm7": 64, + "ymm8": 65, + "ymm9": 66, + "ymm10": 67, + "ymm11": 68, + "ymm12": 69, + "ymm13": 70, + "ymm14": 71, + "ymm15": 72, } name_to_generic_regnum = { - 'rip': LLDB_REGNUM_GENERIC_PC, - 'rsp': LLDB_REGNUM_GENERIC_SP, - 'rbp': LLDB_REGNUM_GENERIC_FP, - 'rdi': LLDB_REGNUM_GENERIC_ARG1, - 'rsi': LLDB_REGNUM_GENERIC_ARG2, - 'rdx': LLDB_REGNUM_GENERIC_ARG3, - 'rcx': LLDB_REGNUM_GENERIC_ARG4, - 'r8': LLDB_REGNUM_GENERIC_ARG5, - 'r9': LLDB_REGNUM_GENERIC_ARG6 + "rip": LLDB_REGNUM_GENERIC_PC, + "rsp": LLDB_REGNUM_GENERIC_SP, + "rbp": LLDB_REGNUM_GENERIC_FP, + "rdi": LLDB_REGNUM_GENERIC_ARG1, + "rsi": LLDB_REGNUM_GENERIC_ARG2, + "rdx": LLDB_REGNUM_GENERIC_ARG3, + "rcx": LLDB_REGNUM_GENERIC_ARG4, + "r8": LLDB_REGNUM_GENERIC_ARG5, + "r9": LLDB_REGNUM_GENERIC_ARG6, } @@ -193,536 +193,841 @@ return reg_num_dict[reg_name] return LLDB_INVALID_REGNUM + x86_64_register_infos = [ - {'name': 'rax', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'rbx', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'rcx', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg4'}, - {'name': 'rdx', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg3'}, - {'name': 'rsi', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg2'}, - {'name': 'rdi', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg1'}, - {'name': 'rbp', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'fp'}, - {'name': 'rsp', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'sp'}, - {'name': 'r8', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg5'}, - {'name': 'r9', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg6'}, - {'name': 'r10', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r11', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r12', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r13', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r14', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r15', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'rip', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'pc'}, - {'name': 'rflags', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'cs', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'ss', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'ds', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'es', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fs', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'gs', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'stmm0', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm1', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm2', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm3', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm4', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm5', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm6', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm7', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'fctrl', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fstat', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'ftag', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fiseg', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fioff', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'foseg', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fooff', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fop', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'xmm0', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm1', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm2', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm3', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm4', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm5', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm6', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm7', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm8', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm9', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm10', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm11', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm12', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm13', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm14', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm15', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'mxcsr', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'orig_rax', 'set': 1, 'bitsize': 64, - 'encoding': eEncodingUint, 'format': eFormatHex}, + { + "name": "rax", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "rbx", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "rcx", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg4", + }, + { + "name": "rdx", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg3", + }, + { + "name": "rsi", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg2", + }, + { + "name": "rdi", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg1", + }, + { + "name": "rbp", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "fp", + }, + { + "name": "rsp", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "sp", + }, + { + "name": "r8", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg5", + }, + { + "name": "r9", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg6", + }, + { + "name": "r10", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r11", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r12", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r13", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r14", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r15", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "rip", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "pc", + }, + { + "name": "rflags", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "cs", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "ss", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "ds", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "es", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fs", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "gs", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "stmm0", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm1", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm2", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm3", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm4", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm5", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm6", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm7", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "fctrl", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fstat", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "ftag", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fiseg", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fioff", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "foseg", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fooff", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fop", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "xmm0", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm1", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm2", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm3", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm4", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm5", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm6", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm7", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm8", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm9", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm10", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm11", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm12", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm13", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm14", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm15", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "mxcsr", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "orig_rax", + "set": 1, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatHex, + }, # Registers that are contained in or composed of one of more other # registers - {'name': 'eax', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rax[31:0]'}, - {'name': 'ebx', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbx[31:0]'}, - {'name': 'ecx', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rcx[31:0]'}, - {'name': 'edx', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdx[31:0]'}, - {'name': 'edi', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdi[31:0]'}, - {'name': 'esi', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsi[31:0]'}, - {'name': 'ebp', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbp[31:0]'}, - {'name': 'esp', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsp[31:0]'}, - {'name': 'r8d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r8[31:0]'}, - {'name': 'r9d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r9[31:0]'}, - {'name': 'r10d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r10[31:0]'}, - {'name': 'r11d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r11[31:0]'}, - {'name': 'r12d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r12[31:0]'}, - {'name': 'r13d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r13[31:0]'}, - {'name': 'r14d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r14[31:0]'}, - {'name': 'r15d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r15[31:0]'}, - - {'name': 'ax', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rax[15:0]'}, - {'name': 'bx', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbx[15:0]'}, - {'name': 'cx', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rcx[15:0]'}, - {'name': 'dx', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdx[15:0]'}, - {'name': 'di', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdi[15:0]'}, - {'name': 'si', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsi[15:0]'}, - {'name': 'bp', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbp[15:0]'}, - {'name': 'sp', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsp[15:0]'}, - {'name': 'r8w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r8[15:0]'}, - {'name': 'r9w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r9[15:0]'}, - {'name': 'r10w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r10[15:0]'}, - {'name': 'r11w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r11[15:0]'}, - {'name': 'r12w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r12[15:0]'}, - {'name': 'r13w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r13[15:0]'}, - {'name': 'r14w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r14[15:0]'}, - {'name': 'r15w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r15[15:0]'}, - - {'name': 'ah', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rax[15:8]'}, - {'name': 'bh', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbx[15:8]'}, - {'name': 'ch', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rcx[15:8]'}, - {'name': 'dh', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdx[15:8]'}, - - {'name': 'al', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rax[7:0]'}, - {'name': 'bl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbx[7:0]'}, - {'name': 'cl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rcx[7:0]'}, - {'name': 'dl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdx[7:0]'}, - {'name': 'dil', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdi[7:0]'}, - {'name': 'sil', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsi[7:0]'}, - {'name': 'bpl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbp[7:0]'}, - {'name': 'spl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsp[7:0]'}, - {'name': 'r8l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r8[7:0]'}, - {'name': 'r9l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r9[7:0]'}, - {'name': 'r10l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r10[7:0]'}, - {'name': 'r11l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r11[7:0]'}, - {'name': 'r12l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r12[7:0]'}, - {'name': 'r13l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r13[7:0]'}, - {'name': 'r14l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r14[7:0]'}, - {'name': 'r15l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r15[7:0]'}, + { + "name": "eax", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rax[31:0]", + }, + { + "name": "ebx", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbx[31:0]", + }, + { + "name": "ecx", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rcx[31:0]", + }, + { + "name": "edx", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdx[31:0]", + }, + { + "name": "edi", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdi[31:0]", + }, + { + "name": "esi", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsi[31:0]", + }, + { + "name": "ebp", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbp[31:0]", + }, + { + "name": "esp", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsp[31:0]", + }, + { + "name": "r8d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r8[31:0]", + }, + { + "name": "r9d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r9[31:0]", + }, + { + "name": "r10d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r10[31:0]", + }, + { + "name": "r11d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r11[31:0]", + }, + { + "name": "r12d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r12[31:0]", + }, + { + "name": "r13d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r13[31:0]", + }, + { + "name": "r14d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r14[31:0]", + }, + { + "name": "r15d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r15[31:0]", + }, + { + "name": "ax", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rax[15:0]", + }, + { + "name": "bx", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbx[15:0]", + }, + { + "name": "cx", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rcx[15:0]", + }, + { + "name": "dx", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdx[15:0]", + }, + { + "name": "di", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdi[15:0]", + }, + { + "name": "si", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsi[15:0]", + }, + { + "name": "bp", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbp[15:0]", + }, + { + "name": "sp", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsp[15:0]", + }, + { + "name": "r8w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r8[15:0]", + }, + { + "name": "r9w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r9[15:0]", + }, + { + "name": "r10w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r10[15:0]", + }, + { + "name": "r11w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r11[15:0]", + }, + { + "name": "r12w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r12[15:0]", + }, + { + "name": "r13w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r13[15:0]", + }, + { + "name": "r14w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r14[15:0]", + }, + { + "name": "r15w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r15[15:0]", + }, + { + "name": "ah", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rax[15:8]", + }, + { + "name": "bh", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbx[15:8]", + }, + { + "name": "ch", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rcx[15:8]", + }, + { + "name": "dh", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdx[15:8]", + }, + { + "name": "al", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rax[7:0]", + }, + { + "name": "bl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbx[7:0]", + }, + { + "name": "cl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rcx[7:0]", + }, + { + "name": "dl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdx[7:0]", + }, + { + "name": "dil", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdi[7:0]", + }, + { + "name": "sil", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsi[7:0]", + }, + { + "name": "bpl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbp[7:0]", + }, + { + "name": "spl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsp[7:0]", + }, + { + "name": "r8l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r8[7:0]", + }, + { + "name": "r9l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r9[7:0]", + }, + { + "name": "r10l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r10[7:0]", + }, + { + "name": "r11l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r11[7:0]", + }, + { + "name": "r12l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r12[7:0]", + }, + { + "name": "r13l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r13[7:0]", + }, + { + "name": "r14l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r14[7:0]", + }, + { + "name": "r15l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r15[7:0]", + }, ] g_target_definition = None @@ -734,41 +1039,44 @@ g_target_definition = {} offset = 0 for reg_info in x86_64_register_infos: - reg_name = reg_info['name'] + reg_name = reg_info["name"] # Only fill in the offset if there is no 'slice' in the register # info - if 'slice' not in reg_info and 'composite' not in reg_info: - reg_info['offset'] = offset - offset += reg_info['bitsize'] // 8 + if "slice" not in reg_info and "composite" not in reg_info: + reg_info["offset"] = offset + offset += reg_info["bitsize"] // 8 # Set the GCC/DWARF register number for this register if it has one reg_num = get_reg_num(name_to_gcc_dwarf_regnum, reg_name) if reg_num != LLDB_INVALID_REGNUM: - reg_info['gcc'] = reg_num - reg_info['dwarf'] = reg_num + reg_info["gcc"] = reg_num + reg_info["dwarf"] = reg_num # Set the generic register number for this register if it has one reg_num = get_reg_num(name_to_generic_regnum, reg_name) if reg_num != LLDB_INVALID_REGNUM: - reg_info['generic'] = reg_num + reg_info["generic"] = reg_num # Set the GDB register number for this register if it has one reg_num = get_reg_num(name_to_gdb_regnum, reg_name) if reg_num != LLDB_INVALID_REGNUM: - reg_info['gdb'] = reg_num + reg_info["gdb"] = reg_num - g_target_definition['sets'] = [ - 'General Purpose Registers', - 'Floating Point Registers'] - g_target_definition['registers'] = x86_64_register_infos - g_target_definition[ - 'host-info'] = {'triple': 'x86_64-*-linux', 'endian': eByteOrderLittle} - g_target_definition['g-packet-size'] = offset - g_target_definition['breakpoint-pc-offset'] = -1 + g_target_definition["sets"] = [ + "General Purpose Registers", + "Floating Point Registers", + ] + g_target_definition["registers"] = x86_64_register_infos + g_target_definition["host-info"] = { + "triple": "x86_64-*-linux", + "endian": eByteOrderLittle, + } + g_target_definition["g-packet-size"] = offset + g_target_definition["breakpoint-pc-offset"] = -1 return g_target_definition def get_dynamic_setting(target, setting_name): - if setting_name == 'gdb-server-target-definition': + if setting_name == "gdb-server-target-definition": return get_target_definition() diff --git a/lldb/examples/python/x86_64_qemu_target_definition.py b/lldb/examples/python/x86_64_qemu_target_definition.py --- a/lldb/examples/python/x86_64_qemu_target_definition.py +++ b/lldb/examples/python/x86_64_qemu_target_definition.py @@ -1,13 +1,13 @@ #!/usr/bin/env python -#===-- x86_64_qemu_target_definition.py -----------------------------*- C++ -*-===// +# ===-- x86_64_qemu_target_definition.py -----------------------------*- C++ -*-===// # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # -#===----------------------------------------------------------------------===// +# ===----------------------------------------------------------------------===// -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # DESCRIPTION # # This file can be used with the following setting: @@ -35,156 +35,156 @@ # The target definition file will get used if and only if the # qRegisterInfo packets are not supported when connecting to a remote # GDB stub. -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- from lldb import * # Compiler and DWARF register numbers name_to_gcc_dwarf_regnum = { - 'rax': 0, - 'rdx': 1, - 'rcx': 2, - 'rbx': 3, - 'rsi': 4, - 'rdi': 5, - 'rbp': 6, - 'rsp': 7, - 'r8': 8, - 'r9': 9, - 'r10': 10, - 'r11': 11, - 'r12': 12, - 'r13': 13, - 'r14': 14, - 'r15': 15, - 'rip': 16, - 'xmm0': 17, - 'xmm1': 18, - 'xmm2': 19, - 'xmm3': 20, - 'xmm4': 21, - 'xmm5': 22, - 'xmm6': 23, - 'xmm7': 24, - 'xmm8': 25, - 'xmm9': 26, - 'xmm10': 27, - 'xmm11': 28, - 'xmm12': 29, - 'xmm13': 30, - 'xmm14': 31, - 'xmm15': 32, - 'stmm0': 33, - 'stmm1': 34, - 'stmm2': 35, - 'stmm3': 36, - 'stmm4': 37, - 'stmm5': 38, - 'stmm6': 39, - 'stmm7': 30, - 'ymm0': 41, - 'ymm1': 42, - 'ymm2': 43, - 'ymm3': 44, - 'ymm4': 45, - 'ymm5': 46, - 'ymm6': 47, - 'ymm7': 48, - 'ymm8': 49, - 'ymm9': 40, - 'ymm10': 41, - 'ymm11': 42, - 'ymm12': 43, - 'ymm13': 44, - 'ymm14': 45, - 'ymm15': 46 + "rax": 0, + "rdx": 1, + "rcx": 2, + "rbx": 3, + "rsi": 4, + "rdi": 5, + "rbp": 6, + "rsp": 7, + "r8": 8, + "r9": 9, + "r10": 10, + "r11": 11, + "r12": 12, + "r13": 13, + "r14": 14, + "r15": 15, + "rip": 16, + "xmm0": 17, + "xmm1": 18, + "xmm2": 19, + "xmm3": 20, + "xmm4": 21, + "xmm5": 22, + "xmm6": 23, + "xmm7": 24, + "xmm8": 25, + "xmm9": 26, + "xmm10": 27, + "xmm11": 28, + "xmm12": 29, + "xmm13": 30, + "xmm14": 31, + "xmm15": 32, + "stmm0": 33, + "stmm1": 34, + "stmm2": 35, + "stmm3": 36, + "stmm4": 37, + "stmm5": 38, + "stmm6": 39, + "stmm7": 30, + "ymm0": 41, + "ymm1": 42, + "ymm2": 43, + "ymm3": 44, + "ymm4": 45, + "ymm5": 46, + "ymm6": 47, + "ymm7": 48, + "ymm8": 49, + "ymm9": 40, + "ymm10": 41, + "ymm11": 42, + "ymm12": 43, + "ymm13": 44, + "ymm14": 45, + "ymm15": 46, } name_to_gdb_regnum = { - 'rax': 0, - 'rbx': 1, - 'rcx': 2, - 'rdx': 3, - 'rsi': 4, - 'rdi': 5, - 'rbp': 6, - 'rsp': 7, - 'r8': 8, - 'r9': 9, - 'r10': 10, - 'r11': 11, - 'r12': 12, - 'r13': 13, - 'r14': 14, - 'r15': 15, - 'rip': 16, - 'rflags': 17, - 'cs': 18, - 'ss': 19, - 'ds': 20, - 'es': 21, - 'fs': 22, - 'gs': 23, - 'stmm0': 24, - 'stmm1': 25, - 'stmm2': 26, - 'stmm3': 27, - 'stmm4': 28, - 'stmm5': 29, - 'stmm6': 30, - 'stmm7': 31, - 'fctrl': 32, - 'fstat': 33, - 'ftag': 34, - 'fiseg': 35, - 'fioff': 36, - 'foseg': 37, - 'fooff': 38, - 'fop': 39, - 'xmm0': 40, - 'xmm1': 41, - 'xmm2': 42, - 'xmm3': 43, - 'xmm4': 44, - 'xmm5': 45, - 'xmm6': 46, - 'xmm7': 47, - 'xmm8': 48, - 'xmm9': 49, - 'xmm10': 50, - 'xmm11': 51, - 'xmm12': 52, - 'xmm13': 53, - 'xmm14': 54, - 'xmm15': 55, - 'mxcsr': 56, - 'ymm0': 57, - 'ymm1': 58, - 'ymm2': 59, - 'ymm3': 60, - 'ymm4': 61, - 'ymm5': 62, - 'ymm6': 63, - 'ymm7': 64, - 'ymm8': 65, - 'ymm9': 66, - 'ymm10': 67, - 'ymm11': 68, - 'ymm12': 69, - 'ymm13': 70, - 'ymm14': 71, - 'ymm15': 72 + "rax": 0, + "rbx": 1, + "rcx": 2, + "rdx": 3, + "rsi": 4, + "rdi": 5, + "rbp": 6, + "rsp": 7, + "r8": 8, + "r9": 9, + "r10": 10, + "r11": 11, + "r12": 12, + "r13": 13, + "r14": 14, + "r15": 15, + "rip": 16, + "rflags": 17, + "cs": 18, + "ss": 19, + "ds": 20, + "es": 21, + "fs": 22, + "gs": 23, + "stmm0": 24, + "stmm1": 25, + "stmm2": 26, + "stmm3": 27, + "stmm4": 28, + "stmm5": 29, + "stmm6": 30, + "stmm7": 31, + "fctrl": 32, + "fstat": 33, + "ftag": 34, + "fiseg": 35, + "fioff": 36, + "foseg": 37, + "fooff": 38, + "fop": 39, + "xmm0": 40, + "xmm1": 41, + "xmm2": 42, + "xmm3": 43, + "xmm4": 44, + "xmm5": 45, + "xmm6": 46, + "xmm7": 47, + "xmm8": 48, + "xmm9": 49, + "xmm10": 50, + "xmm11": 51, + "xmm12": 52, + "xmm13": 53, + "xmm14": 54, + "xmm15": 55, + "mxcsr": 56, + "ymm0": 57, + "ymm1": 58, + "ymm2": 59, + "ymm3": 60, + "ymm4": 61, + "ymm5": 62, + "ymm6": 63, + "ymm7": 64, + "ymm8": 65, + "ymm9": 66, + "ymm10": 67, + "ymm11": 68, + "ymm12": 69, + "ymm13": 70, + "ymm14": 71, + "ymm15": 72, } name_to_generic_regnum = { - 'rip': LLDB_REGNUM_GENERIC_PC, - 'rsp': LLDB_REGNUM_GENERIC_SP, - 'rbp': LLDB_REGNUM_GENERIC_FP, - 'rdi': LLDB_REGNUM_GENERIC_ARG1, - 'rsi': LLDB_REGNUM_GENERIC_ARG2, - 'rdx': LLDB_REGNUM_GENERIC_ARG3, - 'rcx': LLDB_REGNUM_GENERIC_ARG4, - 'r8': LLDB_REGNUM_GENERIC_ARG5, - 'r9': LLDB_REGNUM_GENERIC_ARG6 + "rip": LLDB_REGNUM_GENERIC_PC, + "rsp": LLDB_REGNUM_GENERIC_SP, + "rbp": LLDB_REGNUM_GENERIC_FP, + "rdi": LLDB_REGNUM_GENERIC_ARG1, + "rsi": LLDB_REGNUM_GENERIC_ARG2, + "rdx": LLDB_REGNUM_GENERIC_ARG3, + "rcx": LLDB_REGNUM_GENERIC_ARG4, + "r8": LLDB_REGNUM_GENERIC_ARG5, + "r9": LLDB_REGNUM_GENERIC_ARG6, } @@ -193,534 +193,834 @@ return reg_num_dict[reg_name] return LLDB_INVALID_REGNUM + x86_64_register_infos = [ - {'name': 'rax', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'rbx', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'rcx', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg4'}, - {'name': 'rdx', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg3'}, - {'name': 'rsi', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg2'}, - {'name': 'rdi', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg1'}, - {'name': 'rbp', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'fp'}, - {'name': 'rsp', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'sp'}, - {'name': 'r8', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg5'}, - {'name': 'r9', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg6'}, - {'name': 'r10', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r11', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r12', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r13', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r14', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r15', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'rip', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'pc'}, - {'name': 'rflags', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'cs', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'ss', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'ds', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'es', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fs', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'gs', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'stmm0', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm1', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm2', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm3', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm4', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm5', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm6', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm7', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'fctrl', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fstat', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'ftag', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fiseg', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fioff', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'foseg', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fooff', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fop', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'xmm0', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm1', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm2', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm3', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm4', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm5', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm6', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm7', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm8', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm9', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm10', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm11', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm12', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm13', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm14', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm15', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'mxcsr', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, + { + "name": "rax", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "rbx", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "rcx", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg4", + }, + { + "name": "rdx", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg3", + }, + { + "name": "rsi", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg2", + }, + { + "name": "rdi", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg1", + }, + { + "name": "rbp", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "fp", + }, + { + "name": "rsp", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "sp", + }, + { + "name": "r8", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg5", + }, + { + "name": "r9", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg6", + }, + { + "name": "r10", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r11", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r12", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r13", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r14", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r15", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "rip", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "pc", + }, + { + "name": "rflags", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "cs", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "ss", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "ds", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "es", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fs", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "gs", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "stmm0", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm1", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm2", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm3", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm4", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm5", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm6", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm7", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "fctrl", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fstat", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "ftag", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fiseg", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fioff", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "foseg", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fooff", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fop", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "xmm0", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm1", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm2", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm3", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm4", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm5", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm6", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm7", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm8", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm9", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm10", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm11", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm12", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm13", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm14", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm15", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "mxcsr", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, # Registers that are contained in or composed of one of more other # registers - {'name': 'eax', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rax[31:0]'}, - {'name': 'ebx', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbx[31:0]'}, - {'name': 'ecx', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rcx[31:0]'}, - {'name': 'edx', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdx[31:0]'}, - {'name': 'edi', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdi[31:0]'}, - {'name': 'esi', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsi[31:0]'}, - {'name': 'ebp', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbp[31:0]'}, - {'name': 'esp', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsp[31:0]'}, - {'name': 'r8d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r8[31:0]'}, - {'name': 'r9d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r9[31:0]'}, - {'name': 'r10d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r10[31:0]'}, - {'name': 'r11d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r11[31:0]'}, - {'name': 'r12d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r12[31:0]'}, - {'name': 'r13d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r13[31:0]'}, - {'name': 'r14d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r14[31:0]'}, - {'name': 'r15d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r15[31:0]'}, - - {'name': 'ax', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rax[15:0]'}, - {'name': 'bx', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbx[15:0]'}, - {'name': 'cx', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rcx[15:0]'}, - {'name': 'dx', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdx[15:0]'}, - {'name': 'di', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdi[15:0]'}, - {'name': 'si', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsi[15:0]'}, - {'name': 'bp', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbp[15:0]'}, - {'name': 'sp', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsp[15:0]'}, - {'name': 'r8w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r8[15:0]'}, - {'name': 'r9w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r9[15:0]'}, - {'name': 'r10w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r10[15:0]'}, - {'name': 'r11w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r11[15:0]'}, - {'name': 'r12w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r12[15:0]'}, - {'name': 'r13w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r13[15:0]'}, - {'name': 'r14w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r14[15:0]'}, - {'name': 'r15w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r15[15:0]'}, - - {'name': 'ah', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rax[15:8]'}, - {'name': 'bh', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbx[15:8]'}, - {'name': 'ch', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rcx[15:8]'}, - {'name': 'dh', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdx[15:8]'}, - - {'name': 'al', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rax[7:0]'}, - {'name': 'bl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbx[7:0]'}, - {'name': 'cl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rcx[7:0]'}, - {'name': 'dl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdx[7:0]'}, - {'name': 'dil', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdi[7:0]'}, - {'name': 'sil', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsi[7:0]'}, - {'name': 'bpl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbp[7:0]'}, - {'name': 'spl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsp[7:0]'}, - {'name': 'r8l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r8[7:0]'}, - {'name': 'r9l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r9[7:0]'}, - {'name': 'r10l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r10[7:0]'}, - {'name': 'r11l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r11[7:0]'}, - {'name': 'r12l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r12[7:0]'}, - {'name': 'r13l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r13[7:0]'}, - {'name': 'r14l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r14[7:0]'}, - {'name': 'r15l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r15[7:0]'}, + { + "name": "eax", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rax[31:0]", + }, + { + "name": "ebx", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbx[31:0]", + }, + { + "name": "ecx", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rcx[31:0]", + }, + { + "name": "edx", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdx[31:0]", + }, + { + "name": "edi", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdi[31:0]", + }, + { + "name": "esi", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsi[31:0]", + }, + { + "name": "ebp", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbp[31:0]", + }, + { + "name": "esp", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsp[31:0]", + }, + { + "name": "r8d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r8[31:0]", + }, + { + "name": "r9d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r9[31:0]", + }, + { + "name": "r10d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r10[31:0]", + }, + { + "name": "r11d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r11[31:0]", + }, + { + "name": "r12d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r12[31:0]", + }, + { + "name": "r13d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r13[31:0]", + }, + { + "name": "r14d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r14[31:0]", + }, + { + "name": "r15d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r15[31:0]", + }, + { + "name": "ax", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rax[15:0]", + }, + { + "name": "bx", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbx[15:0]", + }, + { + "name": "cx", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rcx[15:0]", + }, + { + "name": "dx", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdx[15:0]", + }, + { + "name": "di", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdi[15:0]", + }, + { + "name": "si", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsi[15:0]", + }, + { + "name": "bp", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbp[15:0]", + }, + { + "name": "sp", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsp[15:0]", + }, + { + "name": "r8w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r8[15:0]", + }, + { + "name": "r9w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r9[15:0]", + }, + { + "name": "r10w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r10[15:0]", + }, + { + "name": "r11w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r11[15:0]", + }, + { + "name": "r12w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r12[15:0]", + }, + { + "name": "r13w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r13[15:0]", + }, + { + "name": "r14w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r14[15:0]", + }, + { + "name": "r15w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r15[15:0]", + }, + { + "name": "ah", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rax[15:8]", + }, + { + "name": "bh", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbx[15:8]", + }, + { + "name": "ch", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rcx[15:8]", + }, + { + "name": "dh", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdx[15:8]", + }, + { + "name": "al", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rax[7:0]", + }, + { + "name": "bl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbx[7:0]", + }, + { + "name": "cl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rcx[7:0]", + }, + { + "name": "dl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdx[7:0]", + }, + { + "name": "dil", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdi[7:0]", + }, + { + "name": "sil", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsi[7:0]", + }, + { + "name": "bpl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbp[7:0]", + }, + { + "name": "spl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsp[7:0]", + }, + { + "name": "r8l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r8[7:0]", + }, + { + "name": "r9l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r9[7:0]", + }, + { + "name": "r10l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r10[7:0]", + }, + { + "name": "r11l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r11[7:0]", + }, + { + "name": "r12l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r12[7:0]", + }, + { + "name": "r13l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r13[7:0]", + }, + { + "name": "r14l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r14[7:0]", + }, + { + "name": "r15l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r15[7:0]", + }, ] g_target_definition = None @@ -732,41 +1032,44 @@ g_target_definition = {} offset = 0 for reg_info in x86_64_register_infos: - reg_name = reg_info['name'] + reg_name = reg_info["name"] # Only fill in the offset if there is no 'slice' in the register # info - if 'slice' not in reg_info and 'composite' not in reg_info: - reg_info['offset'] = offset - offset += reg_info['bitsize'] // 8 + if "slice" not in reg_info and "composite" not in reg_info: + reg_info["offset"] = offset + offset += reg_info["bitsize"] // 8 # Set the GCC/DWARF register number for this register if it has one reg_num = get_reg_num(name_to_gcc_dwarf_regnum, reg_name) if reg_num != LLDB_INVALID_REGNUM: - reg_info['gcc'] = reg_num - reg_info['dwarf'] = reg_num + reg_info["gcc"] = reg_num + reg_info["dwarf"] = reg_num # Set the generic register number for this register if it has one reg_num = get_reg_num(name_to_generic_regnum, reg_name) if reg_num != LLDB_INVALID_REGNUM: - reg_info['generic'] = reg_num + reg_info["generic"] = reg_num # Set the GDB register number for this register if it has one reg_num = get_reg_num(name_to_gdb_regnum, reg_name) if reg_num != LLDB_INVALID_REGNUM: - reg_info['gdb'] = reg_num + reg_info["gdb"] = reg_num - g_target_definition['sets'] = [ - 'General Purpose Registers', - 'Floating Point Registers'] - g_target_definition['registers'] = x86_64_register_infos - g_target_definition[ - 'host-info'] = {'triple': 'x86_64-*-linux', 'endian': eByteOrderLittle} - g_target_definition['g-packet-size'] = offset - g_target_definition['breakpoint-pc-offset'] = -1 + g_target_definition["sets"] = [ + "General Purpose Registers", + "Floating Point Registers", + ] + g_target_definition["registers"] = x86_64_register_infos + g_target_definition["host-info"] = { + "triple": "x86_64-*-linux", + "endian": eByteOrderLittle, + } + g_target_definition["g-packet-size"] = offset + g_target_definition["breakpoint-pc-offset"] = -1 return g_target_definition def get_dynamic_setting(target, setting_name): - if setting_name == 'gdb-server-target-definition': + if setting_name == "gdb-server-target-definition": return get_target_definition() diff --git a/lldb/examples/python/x86_64_target_definition.py b/lldb/examples/python/x86_64_target_definition.py --- a/lldb/examples/python/x86_64_target_definition.py +++ b/lldb/examples/python/x86_64_target_definition.py @@ -1,13 +1,13 @@ #!/usr/bin/env python -#===-- x86_64_target_definition.py -----------------------------*- C++ -*-===// +# ===-- x86_64_target_definition.py -----------------------------*- C++ -*-===// # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # -#===----------------------------------------------------------------------===// +# ===----------------------------------------------------------------------===// -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- # DESCRIPTION # # This file can be used with the following setting: @@ -35,156 +35,156 @@ # The target definition file will get used if and only if the # qRegisterInfo packets are not supported when connecting to a remote # GDB server. -#---------------------------------------------------------------------- +# ---------------------------------------------------------------------- from lldb import * # Compiler and DWARF register numbers name_to_gcc_dwarf_regnum = { - 'rax': 0, - 'rdx': 1, - 'rcx': 2, - 'rbx': 3, - 'rsi': 4, - 'rdi': 5, - 'rbp': 6, - 'rsp': 7, - 'r8': 8, - 'r9': 9, - 'r10': 10, - 'r11': 11, - 'r12': 12, - 'r13': 13, - 'r14': 14, - 'r15': 15, - 'rip': 16, - 'xmm0': 17, - 'xmm1': 18, - 'xmm2': 19, - 'xmm3': 20, - 'xmm4': 21, - 'xmm5': 22, - 'xmm6': 23, - 'xmm7': 24, - 'xmm8': 25, - 'xmm9': 26, - 'xmm10': 27, - 'xmm11': 28, - 'xmm12': 29, - 'xmm13': 30, - 'xmm14': 31, - 'xmm15': 32, - 'stmm0': 33, - 'stmm1': 34, - 'stmm2': 35, - 'stmm3': 36, - 'stmm4': 37, - 'stmm5': 38, - 'stmm6': 39, - 'stmm7': 30, - 'ymm0': 41, - 'ymm1': 42, - 'ymm2': 43, - 'ymm3': 44, - 'ymm4': 45, - 'ymm5': 46, - 'ymm6': 47, - 'ymm7': 48, - 'ymm8': 49, - 'ymm9': 40, - 'ymm10': 41, - 'ymm11': 42, - 'ymm12': 43, - 'ymm13': 44, - 'ymm14': 45, - 'ymm15': 46 + "rax": 0, + "rdx": 1, + "rcx": 2, + "rbx": 3, + "rsi": 4, + "rdi": 5, + "rbp": 6, + "rsp": 7, + "r8": 8, + "r9": 9, + "r10": 10, + "r11": 11, + "r12": 12, + "r13": 13, + "r14": 14, + "r15": 15, + "rip": 16, + "xmm0": 17, + "xmm1": 18, + "xmm2": 19, + "xmm3": 20, + "xmm4": 21, + "xmm5": 22, + "xmm6": 23, + "xmm7": 24, + "xmm8": 25, + "xmm9": 26, + "xmm10": 27, + "xmm11": 28, + "xmm12": 29, + "xmm13": 30, + "xmm14": 31, + "xmm15": 32, + "stmm0": 33, + "stmm1": 34, + "stmm2": 35, + "stmm3": 36, + "stmm4": 37, + "stmm5": 38, + "stmm6": 39, + "stmm7": 30, + "ymm0": 41, + "ymm1": 42, + "ymm2": 43, + "ymm3": 44, + "ymm4": 45, + "ymm5": 46, + "ymm6": 47, + "ymm7": 48, + "ymm8": 49, + "ymm9": 40, + "ymm10": 41, + "ymm11": 42, + "ymm12": 43, + "ymm13": 44, + "ymm14": 45, + "ymm15": 46, } name_to_gdb_regnum = { - 'rax': 0, - 'rbx': 1, - 'rcx': 2, - 'rdx': 3, - 'rsi': 4, - 'rdi': 5, - 'rbp': 6, - 'rsp': 7, - 'r8': 8, - 'r9': 9, - 'r10': 10, - 'r11': 11, - 'r12': 12, - 'r13': 13, - 'r14': 14, - 'r15': 15, - 'rip': 16, - 'rflags': 17, - 'cs': 18, - 'ss': 19, - 'ds': 20, - 'es': 21, - 'fs': 22, - 'gs': 23, - 'stmm0': 24, - 'stmm1': 25, - 'stmm2': 26, - 'stmm3': 27, - 'stmm4': 28, - 'stmm5': 29, - 'stmm6': 30, - 'stmm7': 31, - 'fctrl': 32, - 'fstat': 33, - 'ftag': 34, - 'fiseg': 35, - 'fioff': 36, - 'foseg': 37, - 'fooff': 38, - 'fop': 39, - 'xmm0': 40, - 'xmm1': 41, - 'xmm2': 42, - 'xmm3': 43, - 'xmm4': 44, - 'xmm5': 45, - 'xmm6': 46, - 'xmm7': 47, - 'xmm8': 48, - 'xmm9': 49, - 'xmm10': 50, - 'xmm11': 51, - 'xmm12': 52, - 'xmm13': 53, - 'xmm14': 54, - 'xmm15': 55, - 'mxcsr': 56, - 'ymm0': 57, - 'ymm1': 58, - 'ymm2': 59, - 'ymm3': 60, - 'ymm4': 61, - 'ymm5': 62, - 'ymm6': 63, - 'ymm7': 64, - 'ymm8': 65, - 'ymm9': 66, - 'ymm10': 67, - 'ymm11': 68, - 'ymm12': 69, - 'ymm13': 70, - 'ymm14': 71, - 'ymm15': 72 + "rax": 0, + "rbx": 1, + "rcx": 2, + "rdx": 3, + "rsi": 4, + "rdi": 5, + "rbp": 6, + "rsp": 7, + "r8": 8, + "r9": 9, + "r10": 10, + "r11": 11, + "r12": 12, + "r13": 13, + "r14": 14, + "r15": 15, + "rip": 16, + "rflags": 17, + "cs": 18, + "ss": 19, + "ds": 20, + "es": 21, + "fs": 22, + "gs": 23, + "stmm0": 24, + "stmm1": 25, + "stmm2": 26, + "stmm3": 27, + "stmm4": 28, + "stmm5": 29, + "stmm6": 30, + "stmm7": 31, + "fctrl": 32, + "fstat": 33, + "ftag": 34, + "fiseg": 35, + "fioff": 36, + "foseg": 37, + "fooff": 38, + "fop": 39, + "xmm0": 40, + "xmm1": 41, + "xmm2": 42, + "xmm3": 43, + "xmm4": 44, + "xmm5": 45, + "xmm6": 46, + "xmm7": 47, + "xmm8": 48, + "xmm9": 49, + "xmm10": 50, + "xmm11": 51, + "xmm12": 52, + "xmm13": 53, + "xmm14": 54, + "xmm15": 55, + "mxcsr": 56, + "ymm0": 57, + "ymm1": 58, + "ymm2": 59, + "ymm3": 60, + "ymm4": 61, + "ymm5": 62, + "ymm6": 63, + "ymm7": 64, + "ymm8": 65, + "ymm9": 66, + "ymm10": 67, + "ymm11": 68, + "ymm12": 69, + "ymm13": 70, + "ymm14": 71, + "ymm15": 72, } name_to_generic_regnum = { - 'rip': LLDB_REGNUM_GENERIC_PC, - 'rsp': LLDB_REGNUM_GENERIC_SP, - 'rbp': LLDB_REGNUM_GENERIC_FP, - 'rdi': LLDB_REGNUM_GENERIC_ARG1, - 'rsi': LLDB_REGNUM_GENERIC_ARG2, - 'rdx': LLDB_REGNUM_GENERIC_ARG3, - 'rcx': LLDB_REGNUM_GENERIC_ARG4, - 'r8': LLDB_REGNUM_GENERIC_ARG5, - 'r9': LLDB_REGNUM_GENERIC_ARG6 + "rip": LLDB_REGNUM_GENERIC_PC, + "rsp": LLDB_REGNUM_GENERIC_SP, + "rbp": LLDB_REGNUM_GENERIC_FP, + "rdi": LLDB_REGNUM_GENERIC_ARG1, + "rsi": LLDB_REGNUM_GENERIC_ARG2, + "rdx": LLDB_REGNUM_GENERIC_ARG3, + "rcx": LLDB_REGNUM_GENERIC_ARG4, + "r8": LLDB_REGNUM_GENERIC_ARG5, + "r9": LLDB_REGNUM_GENERIC_ARG6, } @@ -199,534 +199,834 @@ return reg_num_dict[reg_name] return LLDB_INVALID_REGNUM + x86_64_register_infos = [ - {'name': 'rax', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'rbx', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'rcx', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg4'}, - {'name': 'rdx', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg3'}, - {'name': 'rsi', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg2'}, - {'name': 'rdi', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg1'}, - {'name': 'rbp', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'fp'}, - {'name': 'rsp', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'sp'}, - {'name': 'r8', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg5'}, - {'name': 'r9', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'arg6'}, - {'name': 'r10', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r11', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r12', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r13', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r14', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'r15', - 'set': 0, - 'bitsize': 64, - 'encoding': eEncodingUint, - 'format': eFormatAddressInfo}, - {'name': 'rip', 'set': 0, 'bitsize': 64, 'encoding': eEncodingUint, - 'format': eFormatAddressInfo, 'alt-name': 'pc'}, - {'name': 'rflags', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'cs', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'ss', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'ds', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'es', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fs', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'gs', 'set': 0, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'stmm0', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm1', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm2', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm3', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm4', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm5', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm6', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'stmm7', - 'set': 1, - 'bitsize': 80, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'fctrl', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fstat', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'ftag', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fiseg', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fioff', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'foseg', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fooff', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'fop', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, - {'name': 'xmm0', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm1', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm2', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm3', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm4', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm5', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm6', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm7', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm8', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm9', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm10', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm11', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm12', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm13', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm14', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'xmm15', - 'set': 1, - 'bitsize': 128, - 'encoding': eEncodingVector, - 'format': eFormatVectorOfUInt8}, - {'name': 'mxcsr', 'set': 1, 'bitsize': 32, - 'encoding': eEncodingUint, 'format': eFormatHex}, + { + "name": "rax", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "rbx", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "rcx", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg4", + }, + { + "name": "rdx", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg3", + }, + { + "name": "rsi", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg2", + }, + { + "name": "rdi", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg1", + }, + { + "name": "rbp", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "fp", + }, + { + "name": "rsp", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "sp", + }, + { + "name": "r8", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg5", + }, + { + "name": "r9", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "arg6", + }, + { + "name": "r10", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r11", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r12", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r13", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r14", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "r15", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + }, + { + "name": "rip", + "set": 0, + "bitsize": 64, + "encoding": eEncodingUint, + "format": eFormatAddressInfo, + "alt-name": "pc", + }, + { + "name": "rflags", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "cs", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "ss", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "ds", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "es", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fs", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "gs", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "stmm0", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm1", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm2", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm3", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm4", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm5", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm6", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "stmm7", + "set": 1, + "bitsize": 80, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "fctrl", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fstat", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "ftag", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fiseg", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fioff", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "foseg", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fooff", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "fop", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, + { + "name": "xmm0", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm1", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm2", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm3", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm4", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm5", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm6", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm7", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm8", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm9", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm10", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm11", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm12", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm13", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm14", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "xmm15", + "set": 1, + "bitsize": 128, + "encoding": eEncodingVector, + "format": eFormatVectorOfUInt8, + }, + { + "name": "mxcsr", + "set": 1, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + }, # Registers that are contained in or composed of one of more other # registers - {'name': 'eax', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rax[31:0]'}, - {'name': 'ebx', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbx[31:0]'}, - {'name': 'ecx', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rcx[31:0]'}, - {'name': 'edx', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdx[31:0]'}, - {'name': 'edi', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdi[31:0]'}, - {'name': 'esi', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsi[31:0]'}, - {'name': 'ebp', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbp[31:0]'}, - {'name': 'esp', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsp[31:0]'}, - {'name': 'r8d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r8[31:0]'}, - {'name': 'r9d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r9[31:0]'}, - {'name': 'r10d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r10[31:0]'}, - {'name': 'r11d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r11[31:0]'}, - {'name': 'r12d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r12[31:0]'}, - {'name': 'r13d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r13[31:0]'}, - {'name': 'r14d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r14[31:0]'}, - {'name': 'r15d', - 'set': 0, - 'bitsize': 32, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r15[31:0]'}, - - {'name': 'ax', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rax[15:0]'}, - {'name': 'bx', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbx[15:0]'}, - {'name': 'cx', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rcx[15:0]'}, - {'name': 'dx', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdx[15:0]'}, - {'name': 'di', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdi[15:0]'}, - {'name': 'si', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsi[15:0]'}, - {'name': 'bp', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbp[15:0]'}, - {'name': 'sp', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsp[15:0]'}, - {'name': 'r8w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r8[15:0]'}, - {'name': 'r9w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r9[15:0]'}, - {'name': 'r10w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r10[15:0]'}, - {'name': 'r11w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r11[15:0]'}, - {'name': 'r12w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r12[15:0]'}, - {'name': 'r13w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r13[15:0]'}, - {'name': 'r14w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r14[15:0]'}, - {'name': 'r15w', - 'set': 0, - 'bitsize': 16, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r15[15:0]'}, - - {'name': 'ah', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rax[15:8]'}, - {'name': 'bh', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbx[15:8]'}, - {'name': 'ch', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rcx[15:8]'}, - {'name': 'dh', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdx[15:8]'}, - - {'name': 'al', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rax[7:0]'}, - {'name': 'bl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbx[7:0]'}, - {'name': 'cl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rcx[7:0]'}, - {'name': 'dl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdx[7:0]'}, - {'name': 'dil', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rdi[7:0]'}, - {'name': 'sil', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsi[7:0]'}, - {'name': 'bpl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rbp[7:0]'}, - {'name': 'spl', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'rsp[7:0]'}, - {'name': 'r8l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r8[7:0]'}, - {'name': 'r9l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r9[7:0]'}, - {'name': 'r10l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r10[7:0]'}, - {'name': 'r11l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r11[7:0]'}, - {'name': 'r12l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r12[7:0]'}, - {'name': 'r13l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r13[7:0]'}, - {'name': 'r14l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r14[7:0]'}, - {'name': 'r15l', - 'set': 0, - 'bitsize': 8, - 'encoding': eEncodingUint, - 'format': eFormatHex, - 'slice': 'r15[7:0]'}, + { + "name": "eax", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rax[31:0]", + }, + { + "name": "ebx", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbx[31:0]", + }, + { + "name": "ecx", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rcx[31:0]", + }, + { + "name": "edx", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdx[31:0]", + }, + { + "name": "edi", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdi[31:0]", + }, + { + "name": "esi", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsi[31:0]", + }, + { + "name": "ebp", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbp[31:0]", + }, + { + "name": "esp", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsp[31:0]", + }, + { + "name": "r8d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r8[31:0]", + }, + { + "name": "r9d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r9[31:0]", + }, + { + "name": "r10d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r10[31:0]", + }, + { + "name": "r11d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r11[31:0]", + }, + { + "name": "r12d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r12[31:0]", + }, + { + "name": "r13d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r13[31:0]", + }, + { + "name": "r14d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r14[31:0]", + }, + { + "name": "r15d", + "set": 0, + "bitsize": 32, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r15[31:0]", + }, + { + "name": "ax", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rax[15:0]", + }, + { + "name": "bx", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbx[15:0]", + }, + { + "name": "cx", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rcx[15:0]", + }, + { + "name": "dx", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdx[15:0]", + }, + { + "name": "di", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdi[15:0]", + }, + { + "name": "si", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsi[15:0]", + }, + { + "name": "bp", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbp[15:0]", + }, + { + "name": "sp", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsp[15:0]", + }, + { + "name": "r8w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r8[15:0]", + }, + { + "name": "r9w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r9[15:0]", + }, + { + "name": "r10w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r10[15:0]", + }, + { + "name": "r11w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r11[15:0]", + }, + { + "name": "r12w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r12[15:0]", + }, + { + "name": "r13w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r13[15:0]", + }, + { + "name": "r14w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r14[15:0]", + }, + { + "name": "r15w", + "set": 0, + "bitsize": 16, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r15[15:0]", + }, + { + "name": "ah", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rax[15:8]", + }, + { + "name": "bh", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbx[15:8]", + }, + { + "name": "ch", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rcx[15:8]", + }, + { + "name": "dh", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdx[15:8]", + }, + { + "name": "al", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rax[7:0]", + }, + { + "name": "bl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbx[7:0]", + }, + { + "name": "cl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rcx[7:0]", + }, + { + "name": "dl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdx[7:0]", + }, + { + "name": "dil", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rdi[7:0]", + }, + { + "name": "sil", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsi[7:0]", + }, + { + "name": "bpl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rbp[7:0]", + }, + { + "name": "spl", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "rsp[7:0]", + }, + { + "name": "r8l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r8[7:0]", + }, + { + "name": "r9l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r9[7:0]", + }, + { + "name": "r10l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r10[7:0]", + }, + { + "name": "r11l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r11[7:0]", + }, + { + "name": "r12l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r12[7:0]", + }, + { + "name": "r13l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r13[7:0]", + }, + { + "name": "r14l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r14[7:0]", + }, + { + "name": "r15l", + "set": 0, + "bitsize": 8, + "encoding": eEncodingUint, + "format": eFormatHex, + "slice": "r15[7:0]", + }, ] g_target_definition = None @@ -738,40 +1038,43 @@ g_target_definition = {} offset = 0 for reg_info in x86_64_register_infos: - reg_name = reg_info['name'] + reg_name = reg_info["name"] # Only fill in the offset if there is no 'slice' in the register # info - if 'slice' not in reg_info and 'composite' not in reg_info: - reg_info['offset'] = offset - offset += reg_info['bitsize'] // 8 + if "slice" not in reg_info and "composite" not in reg_info: + reg_info["offset"] = offset + offset += reg_info["bitsize"] // 8 # Set the GCC/DWARF register number for this register if it has one reg_num = get_reg_num(name_to_gcc_dwarf_regnum, reg_name) if reg_num != LLDB_INVALID_REGNUM: - reg_info['gcc'] = reg_num - reg_info['dwarf'] = reg_num + reg_info["gcc"] = reg_num + reg_info["dwarf"] = reg_num # Set the generic register number for this register if it has one reg_num = get_reg_num(name_to_generic_regnum, reg_name) if reg_num != LLDB_INVALID_REGNUM: - reg_info['generic'] = reg_num + reg_info["generic"] = reg_num # Set the GDB register number for this register if it has one reg_num = get_reg_num(name_to_gdb_regnum, reg_name) if reg_num != LLDB_INVALID_REGNUM: - reg_info['gdb'] = reg_num + reg_info["gdb"] = reg_num - g_target_definition['sets'] = [ - 'General Purpose Registers', - 'Floating Point Registers'] - g_target_definition['registers'] = x86_64_register_infos - g_target_definition[ - 'host-info'] = {'triple': 'x86_64-apple-macosx', 'endian': eByteOrderLittle} - g_target_definition['g-packet-size'] = offset + g_target_definition["sets"] = [ + "General Purpose Registers", + "Floating Point Registers", + ] + g_target_definition["registers"] = x86_64_register_infos + g_target_definition["host-info"] = { + "triple": "x86_64-apple-macosx", + "endian": eByteOrderLittle, + } + g_target_definition["g-packet-size"] = offset return g_target_definition def get_dynamic_setting(target, setting_name): - if setting_name == 'gdb-server-target-definition': + if setting_name == "gdb-server-target-definition": return get_target_definition() diff --git a/lldb/examples/scripting/tree_utils.py b/lldb/examples/scripting/tree_utils.py --- a/lldb/examples/scripting/tree_utils.py +++ b/lldb/examples/scripting/tree_utils.py @@ -47,7 +47,7 @@ if root_word[0] == '"' and root_word[end] == '"': root_word = root_word[1:end] end = len(root_word) - 1 - if root_word[0] == '\'' and root_word[end] == '\'': + if root_word[0] == "'" and root_word[end] == "'": root_word = root_word[1:end] # Main depth first search @@ -55,7 +55,6 @@ if root_word == word: return cur_path elif word < root_word: - # Check to see if left child is NULL if left_child_ptr.GetValue() is None: @@ -64,7 +63,6 @@ cur_path = cur_path + "L" return DFS(left_child_ptr, word, cur_path) else: - # Check to see if right child is NULL if right_child_ptr.GetValue() is None: @@ -83,10 +81,10 @@ the one defined in dictionary.c It uses LLDB API functions to examine and traverse the tree nodes. """ - if (root.GetValue is None): + if root.GetValue is None: return 0 - if (int(root.GetValue(), 16) == 0): + if int(root.GetValue(), 16) == 0: return 0 left_size = tree_size(root.GetChildAtIndex(1)) @@ -107,11 +105,13 @@ functions to examine and traverse the tree nodes. """ if (root.GetChildAtIndex(1).GetValue() is not None) and ( - int(root.GetChildAtIndex(1).GetValue(), 16) != 0): + int(root.GetChildAtIndex(1).GetValue(), 16) != 0 + ): print_tree(root.GetChildAtIndex(1)) print(root.GetChildAtIndex(0).GetSummary()) if (root.GetChildAtIndex(2).GetValue() is not None) and ( - int(root.GetChildAtIndex(2).GetValue(), 16) != 0): + int(root.GetChildAtIndex(2).GetValue(), 16) != 0 + ): print_tree(root.GetChildAtIndex(2)) diff --git a/lldb/examples/summaries/cocoa/CFArray.py b/lldb/examples/summaries/cocoa/CFArray.py --- a/lldb/examples/summaries/cocoa/CFArray.py +++ b/lldb/examples/summaries/cocoa/CFArray.py @@ -14,10 +14,10 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # much less functional than the other two cases below # just runs code to get to the count and then returns @@ -25,7 +25,6 @@ class NSArrayKVC_SynthProvider: - def adjust_for_architecture(self): pass @@ -43,18 +42,19 @@ stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) num_children_vo = self.valobj.CreateValueFromExpression( - "count", "(int)[" + stream.GetData() + " count]") + "count", "(int)[" + stream.GetData() + " count]" + ) if num_children_vo.IsValid(): return num_children_vo.GetValueAsUnsigned(0) return "" + # much less functional than the other two cases below # just runs code to get to the count and then returns # no children class NSArrayCF_SynthProvider: - def adjust_for_architecture(self): pass @@ -63,8 +63,9 @@ self.valobj = valobj self.sys_params = params if not (self.sys_params.types_cache.ulong): - self.sys_params.types_cache.ulong = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + self.sys_params.types_cache.ulong = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeUnsignedLong + ) self.update() def update(self): @@ -74,12 +75,12 @@ def num_children(self): logger = lldb.formatters.Logger.Logger() num_children_vo = self.valobj.CreateChildAtOffset( - "count", self.sys_params.cfruntime_size, self.sys_params.types_cache.ulong) + "count", self.sys_params.cfruntime_size, self.sys_params.types_cache.ulong + ) return num_children_vo.GetValueAsUnsigned(0) class NSArrayI_SynthProvider: - def adjust_for_architecture(self): pass @@ -87,9 +88,10 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.long): - self.sys_params.types_cache.long = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeLong) + if not (self.sys_params.types_cache.long): + self.sys_params.types_cache.long = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeLong + ) self.update() def update(self): @@ -100,14 +102,12 @@ def num_children(self): logger = lldb.formatters.Logger.Logger() count = self.valobj.CreateChildAtOffset( - "count", - self.sys_params.pointer_size, - self.sys_params.types_cache.long) + "count", self.sys_params.pointer_size, self.sys_params.types_cache.long + ) return count.GetValueAsUnsigned(0) class NSArrayM_SynthProvider: - def adjust_for_architecture(self): pass @@ -115,9 +115,10 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.long): - self.sys_params.types_cache.long = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeLong) + if not (self.sys_params.types_cache.long): + self.sys_params.types_cache.long = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeLong + ) self.update() def update(self): @@ -128,18 +129,17 @@ def num_children(self): logger = lldb.formatters.Logger.Logger() count = self.valobj.CreateChildAtOffset( - "count", - self.sys_params.pointer_size, - self.sys_params.types_cache.long) + "count", self.sys_params.pointer_size, self.sys_params.types_cache.long + ) return count.GetValueAsUnsigned(0) + # this is the actual synth provider, but is just a wrapper that checks # whether valobj is an instance of __NSArrayI or __NSArrayM and sets up an # appropriate backend layer to do the computations class NSArray_SynthProvider: - def adjust_for_architecture(self): pass @@ -149,7 +149,7 @@ self.adjust_for_architecture() self.error = False self.wrapper = self.make_wrapper() - self.invalid = (self.wrapper is None) + self.invalid = self.wrapper is None def num_children(self): logger = lldb.formatters.Logger.Logger() @@ -169,12 +169,15 @@ logger = lldb.formatters.Logger.Logger() if self.valobj.GetValueAsUnsigned() == 0: self.error = True - return lldb.runtime.objc.objc_runtime.InvalidPointer_Description( - True) + return lldb.runtime.objc.objc_runtime.InvalidPointer_Description(True) else: global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - self.valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + self.valobj, statistics + ) if wrapper: self.error = True return wrapper @@ -183,24 +186,20 @@ logger >> "Class name is " + str(name_string) - if name_string == '__NSArrayI': - wrapper = NSArrayI_SynthProvider( - self.valobj, dict, class_data.sys_params) - statistics.metric_hit('code_notrun', self.valobj.GetName()) - elif name_string == '__NSArrayM': - wrapper = NSArrayM_SynthProvider( - self.valobj, dict, class_data.sys_params) - statistics.metric_hit('code_notrun', self.valobj.GetName()) - elif name_string == '__NSCFArray': - wrapper = NSArrayCF_SynthProvider( - self.valobj, dict, class_data.sys_params) - statistics.metric_hit('code_notrun', self.valobj.GetName()) + if name_string == "__NSArrayI": + wrapper = NSArrayI_SynthProvider(self.valobj, dict, class_data.sys_params) + statistics.metric_hit("code_notrun", self.valobj.GetName()) + elif name_string == "__NSArrayM": + wrapper = NSArrayM_SynthProvider(self.valobj, dict, class_data.sys_params) + statistics.metric_hit("code_notrun", self.valobj.GetName()) + elif name_string == "__NSCFArray": + wrapper = NSArrayCF_SynthProvider(self.valobj, dict, class_data.sys_params) + statistics.metric_hit("code_notrun", self.valobj.GetName()) else: - wrapper = NSArrayKVC_SynthProvider( - self.valobj, dict, class_data.sys_params) + wrapper = NSArrayKVC_SynthProvider(self.valobj, dict, class_data.sys_params) statistics.metric_hit( - 'unknown_class', str( - self.valobj.GetName()) + " seen as " + name_string) + "unknown_class", str(self.valobj.GetName()) + " seen as " + name_string + ) return wrapper @@ -216,18 +215,20 @@ summary = None logger >> "provider gave me " + str(summary) if summary is None: - summary = '' + summary = "" elif isinstance(summary, str): pass else: # we format it like it were a CFString to make it look the same as # the summary from Xcode - summary = '@"' + str(summary) + \ - (" objects" if summary != 1 else " object") + '"' + summary = ( + '@"' + str(summary) + (" objects" if summary != 1 else " object") + '"' + ) return summary - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F CFArray.CFArray_SummaryProvider NSArray CFArrayRef CFMutableArrayRef") + "type summary add -F CFArray.CFArray_SummaryProvider NSArray CFArrayRef CFMutableArrayRef" + ) diff --git a/lldb/examples/summaries/cocoa/CFBag.py b/lldb/examples/summaries/cocoa/CFBag.py --- a/lldb/examples/summaries/cocoa/CFBag.py +++ b/lldb/examples/summaries/cocoa/CFBag.py @@ -14,10 +14,10 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # despite the similary to synthetic children providers, these classes are not # trying to provide anything but the length for an CFBag, so they need not @@ -25,7 +25,6 @@ class CFBagRef_SummaryProvider: - def adjust_for_architecture(self): pass @@ -33,13 +32,15 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSUInteger): + if not (self.sys_params.types_cache.NSUInteger): if self.sys_params.is_64_bit: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedLong) + ) else: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedInt) + ) self.update() def update(self): @@ -59,12 +60,12 @@ def length(self): logger = lldb.formatters.Logger.Logger() size = self.valobj.CreateChildAtOffset( - "count", self.offset(), self.sys_params.types_cache.NSUInteger) + "count", self.offset(), self.sys_params.types_cache.NSUInteger + ) return size.GetValueAsUnsigned(0) class CFBagUnknown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -83,7 +84,8 @@ stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) num_children_vo = self.valobj.CreateValueFromExpression( - "count", "(int)CFBagGetCount(" + stream.GetData() + " )") + "count", "(int)CFBagGetCount(" + stream.GetData() + " )" + ) if num_children_vo.IsValid(): return num_children_vo.GetValueAsUnsigned(0) return "" @@ -92,16 +94,21 @@ def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper name_string = class_data.class_name() actual_name = name_string - logger >> "name string got was " + \ - str(name_string) + " but actual name is " + str(actual_name) + logger >> "name string got was " + str(name_string) + " but actual name is " + str( + actual_name + ) if class_data.is_cftype(): # CFBag does not expose an actual NSWrapper type, so we have to check that this is @@ -111,17 +118,12 @@ valobj_type = valobj_type.GetPointeeType() if valobj_type.IsValid(): actual_name = valobj_type.GetName() - if actual_name == '__CFBag' or \ - actual_name == 'const struct __CFBag': + if actual_name == "__CFBag" or actual_name == "const struct __CFBag": wrapper = CFBagRef_SummaryProvider(valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + statistics.metric_hit("code_notrun", valobj) return wrapper wrapper = CFBagUnknown_SummaryProvider(valobj, class_data.sys_params) - statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - actual_name) + statistics.metric_hit("unknown_class", valobj.GetName() + " seen as " + actual_name) return wrapper @@ -130,8 +132,8 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.length() @@ -144,20 +146,21 @@ # (if counts start looking weird, then most probably # the mask needs to be changed) if summary is None: - summary = '' + summary = "" elif isinstance(summary, str): pass else: if provider.sys_params.is_64_bit: - summary = summary & ~0x1fff000000000000 + summary = summary & ~0x1FFF000000000000 if summary == 1: summary = '@"1 value"' else: summary = '@"' + str(summary) + ' values"' return summary - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F CFBag.CFBag_SummaryProvider CFBagRef CFMutableBagRef") + "type summary add -F CFBag.CFBag_SummaryProvider CFBagRef CFMutableBagRef" + ) diff --git a/lldb/examples/summaries/cocoa/CFBinaryHeap.py b/lldb/examples/summaries/cocoa/CFBinaryHeap.py --- a/lldb/examples/summaries/cocoa/CFBinaryHeap.py +++ b/lldb/examples/summaries/cocoa/CFBinaryHeap.py @@ -14,10 +14,10 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # despite the similary to synthetic children providers, these classes are not # trying to provide anything but the length for an CFBinaryHeap, so they need not @@ -25,7 +25,6 @@ class CFBinaryHeapRef_SummaryProvider: - def adjust_for_architecture(self): pass @@ -33,13 +32,15 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSUInteger): + if not (self.sys_params.types_cache.NSUInteger): if self.sys_params.is_64_bit: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedLong) + ) else: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedInt) + ) self.update() def update(self): @@ -56,12 +57,12 @@ def length(self): logger = lldb.formatters.Logger.Logger() size = self.valobj.CreateChildAtOffset( - "count", self.offset(), self.sys_params.types_cache.NSUInteger) + "count", self.offset(), self.sys_params.types_cache.NSUInteger + ) return size.GetValueAsUnsigned(0) class CFBinaryHeapUnknown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -80,25 +81,31 @@ stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) num_children_vo = self.valobj.CreateValueFromExpression( - "count", "(int)CFBinaryHeapGetCount(" + stream.GetData() + " )") + "count", "(int)CFBinaryHeapGetCount(" + stream.GetData() + " )" + ) if num_children_vo.IsValid(): return num_children_vo.GetValueAsUnsigned(0) - return '' + return "" def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper name_string = class_data.class_name() actual_name = class_data.class_name() - logger >> "name string got was " + \ - str(name_string) + " but actual name is " + str(actual_name) + logger >> "name string got was " + str(name_string) + " but actual name is " + str( + actual_name + ) if class_data.is_cftype(): # CFBinaryHeap does not expose an actual NSWrapper type, so we have to check that this is @@ -108,18 +115,12 @@ valobj_type = valobj_type.GetPointeeType() if valobj_type.IsValid(): actual_name = valobj_type.GetName() - if actual_name == '__CFBinaryHeap': - wrapper = CFBinaryHeapRef_SummaryProvider( - valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + if actual_name == "__CFBinaryHeap": + wrapper = CFBinaryHeapRef_SummaryProvider(valobj, class_data.sys_params) + statistics.metric_hit("code_notrun", valobj) return wrapper - wrapper = CFBinaryHeapUnknown_SummaryProvider( - valobj, class_data.sys_params) - statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + wrapper = CFBinaryHeapUnknown_SummaryProvider(valobj, class_data.sys_params) + statistics.metric_hit("unknown_class", valobj.GetName() + " seen as " + name_string) return wrapper @@ -128,8 +129,8 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.length() @@ -142,20 +143,21 @@ # (if counts start looking weird, then most probably # the mask needs to be changed) if summary is None: - summary = '' + summary = "" elif isinstance(summary, str): pass else: if provider.sys_params.is_64_bit: - summary = summary & ~0x1fff000000000000 + summary = summary & ~0x1FFF000000000000 if summary == 1: return '@"1 item"' else: summary = '@"' + str(summary) + ' items"' return summary - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F CFBinaryHeap.CFBinaryHeap_SummaryProvider CFBinaryHeapRef") + "type summary add -F CFBinaryHeap.CFBinaryHeap_SummaryProvider CFBinaryHeapRef" + ) diff --git a/lldb/examples/summaries/cocoa/CFBitVector.py b/lldb/examples/summaries/cocoa/CFBitVector.py --- a/lldb/examples/summaries/cocoa/CFBitVector.py +++ b/lldb/examples/summaries/cocoa/CFBitVector.py @@ -37,11 +37,12 @@ logger = lldb.formatters.Logger.Logger() return pointer.GetPointeeData(index, 1) + statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # despite the similary to synthetic children providers, these classes are not # trying to provide anything but a summary for a CF*BitVector, so they need not @@ -49,7 +50,6 @@ class CFBitVectorKnown_SummaryProvider: - def adjust_for_architecture(self): logger = lldb.formatters.Logger.Logger() self.uiint_size = self.sys_params.types_cache.NSUInteger.GetByteSize() @@ -59,16 +59,19 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSUInteger): + if not (self.sys_params.types_cache.NSUInteger): if self.sys_params.is_64_bit: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedLong) + ) else: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) - if not(self.sys_params.types_cache.charptr): - self.sys_params.types_cache.charptr = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeChar).GetPointerType() + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedInt) + ) + if not (self.sys_params.types_cache.charptr): + self.sys_params.types_cache.charptr = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeChar).GetPointerType() + ) self.update() def update(self): @@ -85,17 +88,17 @@ count_vo = self.valobj.CreateChildAtOffset( "count", self.sys_params.cfruntime_size, - self.sys_params.types_cache.NSUInteger) + self.sys_params.types_cache.NSUInteger, + ) count = count_vo.GetValueAsUnsigned(0) if count == 0: - return '(empty)' + return "(empty)" array_vo = self.valobj.CreateChildAtOffset( "data", - self.sys_params.cfruntime_size + - 2 * - self.uiint_size, - self.sys_params.types_cache.charptr) + self.sys_params.cfruntime_size + 2 * self.uiint_size, + self.sys_params.types_cache.charptr, + ) data_list = [] cur_byte_pos = None @@ -113,16 +116,15 @@ cur_byte_val = cur_byte.uint8[0] bit = get_bit(cur_byte_val, bit_index(i)) if (i % 4) == 0: - data_list.append(' ') + data_list.append(" ") if bit == 1: - data_list.append('1') + data_list.append("1") else: - data_list.append('0') - return ''.join(data_list) + data_list.append("0") + return "".join(data_list) class CFBitVectorUnknown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -138,22 +140,27 @@ def contents(self): logger = lldb.formatters.Logger.Logger() - return '' + return "" def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper name_string = class_data.class_name() actual_name = name_string - logger >> "name string got was " + \ - str(name_string) + " but actual name is " + str(actual_name) + logger >> "name string got was " + str(name_string) + " but actual name is " + str( + actual_name + ) if class_data.is_cftype(): # CFBitVectorRef does not expose an actual NSWrapper type, so we have to check that this is @@ -163,23 +170,18 @@ valobj_type = valobj_type.GetPointeeType() if valobj_type.IsValid(): actual_name = valobj_type.GetName() - if actual_name == '__CFBitVector' or actual_name == '__CFMutableBitVector': - wrapper = CFBitVectorKnown_SummaryProvider( - valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + if actual_name == "__CFBitVector" or actual_name == "__CFMutableBitVector": + wrapper = CFBitVectorKnown_SummaryProvider(valobj, class_data.sys_params) + statistics.metric_hit("code_notrun", valobj) else: - wrapper = CFBitVectorUnknown_SummaryProvider( - valobj, class_data.sys_params) + wrapper = CFBitVectorUnknown_SummaryProvider(valobj, class_data.sys_params) print(actual_name) else: - wrapper = CFBitVectorUnknown_SummaryProvider( - valobj, class_data.sys_params) + wrapper = CFBitVectorUnknown_SummaryProvider(valobj, class_data.sys_params) print(name_string) statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + "unknown_class", valobj.GetName() + " seen as " + name_string + ) return wrapper @@ -188,20 +190,21 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.contents() except: summary = None logger >> "summary got from provider: " + str(summary) - if summary is None or summary == '': - summary = '' + if summary is None or summary == "": + summary = "" return summary - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F CFBitVector.CFBitVector_SummaryProvider CFBitVectorRef CFMutableBitVectorRef") + "type summary add -F CFBitVector.CFBitVector_SummaryProvider CFBitVectorRef CFMutableBitVectorRef" + ) diff --git a/lldb/examples/summaries/cocoa/CFDictionary.py b/lldb/examples/summaries/cocoa/CFDictionary.py --- a/lldb/examples/summaries/cocoa/CFDictionary.py +++ b/lldb/examples/summaries/cocoa/CFDictionary.py @@ -14,10 +14,10 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # despite the similary to synthetic children providers, these classes are not # trying to provide anything but the count for an NSDictionary, so they need not @@ -25,7 +25,6 @@ class NSCFDictionary_SummaryProvider: - def adjust_for_architecture(self): pass @@ -33,13 +32,15 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSUInteger): + if not (self.sys_params.types_cache.NSUInteger): if self.sys_params.is_64_bit: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedLong) + ) else: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedInt) + ) self.update() def update(self): @@ -60,12 +61,12 @@ def num_children(self): logger = lldb.formatters.Logger.Logger() num_children_vo = self.valobj.CreateChildAtOffset( - "count", self.offset(), self.sys_params.types_cache.NSUInteger) + "count", self.offset(), self.sys_params.types_cache.NSUInteger + ) return num_children_vo.GetValueAsUnsigned(0) class NSDictionaryI_SummaryProvider: - def adjust_for_architecture(self): pass @@ -73,13 +74,15 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSUInteger): + if not (self.sys_params.types_cache.NSUInteger): if self.sys_params.is_64_bit: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedLong) + ) else: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedInt) + ) self.update() def update(self): @@ -94,7 +97,8 @@ def num_children(self): logger = lldb.formatters.Logger.Logger() num_children_vo = self.valobj.CreateChildAtOffset( - "count", self.offset(), self.sys_params.types_cache.NSUInteger) + "count", self.offset(), self.sys_params.types_cache.NSUInteger + ) value = num_children_vo.GetValueAsUnsigned(0) if value is not None: # the MS6bits on immutable dictionaries seem to be taken by the LSB of capacity @@ -108,7 +112,6 @@ class NSDictionaryM_SummaryProvider: - def adjust_for_architecture(self): pass @@ -116,13 +119,15 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSUInteger): + if not (self.sys_params.types_cache.NSUInteger): if self.sys_params.is_64_bit: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedLong) + ) else: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedInt) + ) self.update() def update(self): @@ -136,7 +141,8 @@ def num_children(self): logger = lldb.formatters.Logger.Logger() num_children_vo = self.valobj.CreateChildAtOffset( - "count", self.offset(), self.sys_params.types_cache.NSUInteger) + "count", self.offset(), self.sys_params.types_cache.NSUInteger + ) value = num_children_vo.GetValueAsUnsigned(0) if value is not None: # the MS6bits on immutable dictionaries seem to be taken by the LSB of capacity @@ -150,7 +156,6 @@ class NSDictionaryUnknown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -169,17 +174,22 @@ stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) num_children_vo = self.valobj.CreateValueFromExpression( - "count", "(int)[" + stream.GetData() + " count]") + "count", "(int)[" + stream.GetData() + " count]" + ) if num_children_vo.IsValid(): return num_children_vo.GetValueAsUnsigned(0) - return '' + return "" def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper @@ -187,23 +197,20 @@ logger >> "class name is: " + str(name_string) - if name_string == '__NSCFDictionary': + if name_string == "__NSCFDictionary": wrapper = NSCFDictionary_SummaryProvider(valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) - elif name_string == '__NSDictionaryI': + statistics.metric_hit("code_notrun", valobj) + elif name_string == "__NSDictionaryI": wrapper = NSDictionaryI_SummaryProvider(valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) - elif name_string == '__NSDictionaryM': + statistics.metric_hit("code_notrun", valobj) + elif name_string == "__NSDictionaryM": wrapper = NSDictionaryM_SummaryProvider(valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + statistics.metric_hit("code_notrun", valobj) else: - wrapper = NSDictionaryUnknown_SummaryProvider( - valobj, class_data.sys_params) + wrapper = NSDictionaryUnknown_SummaryProvider(valobj, class_data.sys_params) statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + "unknown_class", valobj.GetName() + " seen as " + name_string + ) return wrapper @@ -212,8 +219,8 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.num_children() @@ -221,12 +228,13 @@ summary = None logger >> "got summary " + str(summary) if summary is None: - return '' + return "" if isinstance(summary, str): return summary - return str(summary) + (" key/value pairs" if summary != - 1 else " key/value pair") - return 'Summary Unavailable' + return str(summary) + ( + " key/value pairs" if summary != 1 else " key/value pair" + ) + return "Summary Unavailable" def CFDictionary_SummaryProvider2(valobj, dict): @@ -234,8 +242,8 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.num_children() @@ -243,21 +251,22 @@ summary = None logger >> "got summary " + str(summary) if summary is None: - summary = '' + summary = "" if isinstance(summary, str): return summary else: # needed on OSX Mountain Lion if provider.sys_params.is_64_bit: - summary = summary & ~0x0f1f000000000000 - summary = '@"' + str(summary) + \ - (' entries"' if summary != 1 else ' entry"') + summary = summary & ~0x0F1F000000000000 + summary = '@"' + str(summary) + (' entries"' if summary != 1 else ' entry"') return summary - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F CFDictionary.CFDictionary_SummaryProvider NSDictionary") + "type summary add -F CFDictionary.CFDictionary_SummaryProvider NSDictionary" + ) debugger.HandleCommand( - "type summary add -F CFDictionary.CFDictionary_SummaryProvider2 CFDictionaryRef CFMutableDictionaryRef") + "type summary add -F CFDictionary.CFDictionary_SummaryProvider2 CFDictionaryRef CFMutableDictionaryRef" + ) diff --git a/lldb/examples/summaries/cocoa/CFString.py b/lldb/examples/summaries/cocoa/CFString.py --- a/lldb/examples/summaries/cocoa/CFString.py +++ b/lldb/examples/summaries/cocoa/CFString.py @@ -16,13 +16,13 @@ except NameError: unichr = chr + def CFString_SummaryProvider(valobj, dict): logger = lldb.formatters.Logger.Logger() provider = CFStringSynthProvider(valobj, dict) if not provider.invalid: try: - summary = provider.get_child_at_index( - provider.get_child_index("content")) + summary = provider.get_child_at_index(provider.get_child_index("content")) if isinstance(summary, lldb.SBValue): summary = summary.GetSummary() else: @@ -30,45 +30,47 @@ except: summary = None if summary is None: - summary = '' - return '@' + summary - return '' + summary = "" + return "@" + summary + return "" def CFAttributedString_SummaryProvider(valobj, dict): logger = lldb.formatters.Logger.Logger() offset = valobj.GetTarget().GetProcess().GetAddressByteSize() pointee = valobj.GetValueAsUnsigned(0) - summary = '' + summary = "" if pointee is not None and pointee != 0: pointee = pointee + offset child_ptr = valobj.CreateValueFromAddress( - "string_ptr", pointee, valobj.GetType()) + "string_ptr", pointee, valobj.GetType() + ) child = child_ptr.CreateValueFromAddress( - "string_data", - child_ptr.GetValueAsUnsigned(), - valobj.GetType()).AddressOf() + "string_data", child_ptr.GetValueAsUnsigned(), valobj.GetType() + ).AddressOf() provider = CFStringSynthProvider(child, dict) if not provider.invalid: try: summary = provider.get_child_at_index( - provider.get_child_index("content")).GetSummary() + provider.get_child_index("content") + ).GetSummary() except: - summary = '' + summary = "" if summary is None: - summary = '' - return '@' + summary + summary = "" + return "@" + summary def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F CFString.CFString_SummaryProvider NSString CFStringRef CFMutableStringRef") + "type summary add -F CFString.CFString_SummaryProvider NSString CFStringRef CFMutableStringRef" + ) debugger.HandleCommand( - "type summary add -F CFString.CFAttributedString_SummaryProvider NSAttributedString") + "type summary add -F CFString.CFAttributedString_SummaryProvider NSAttributedString" + ) class CFStringSynthProvider: - def __init__(self, valobj, dict): logger = lldb.formatters.Logger.Logger() self.valobj = valobj @@ -86,7 +88,7 @@ logger = lldb.formatters.Logger.Logger() process = self.valobj.GetTarget().GetProcess() error = lldb.SBError() - pystr = u'' + pystr = "" # cannot do the read at once because the length value has # a weird encoding. better play it safe here while max_len > 0: @@ -121,21 +123,22 @@ pointer = self.valobj.GetValueAsUnsigned(0) + offset pystr = self.read_unicode(pointer) return self.valobj.CreateValueFromExpression( - "content", "(char*)\"" + pystr.encode('utf-8') + "\"") + "content", '(char*)"' + pystr.encode("utf-8") + '"' + ) # last resort call, use ObjC code to read; the final aim is to # be able to strip this call away entirely and only do the read # ourselves def handle_unicode_string_safe(self): return self.valobj.CreateValueFromExpression( - "content", "(char*)\"" + self.valobj.GetObjectDescription() + "\"") + "content", '(char*)"' + self.valobj.GetObjectDescription() + '"' + ) def handle_unicode_string(self): logger = lldb.formatters.Logger.Logger() # step 1: find offset if self.inline: - pointer = self.valobj.GetValueAsUnsigned( - 0) + self.size_of_cfruntime_base() + pointer = self.valobj.GetValueAsUnsigned(0) + self.size_of_cfruntime_base() if not self.explicit: # untested, use the safe code path return self.handle_unicode_string_safe() @@ -144,79 +147,93 @@ # data pointer = pointer + self.pointer_size else: - pointer = self.valobj.GetValueAsUnsigned( - 0) + self.size_of_cfruntime_base() + pointer = self.valobj.GetValueAsUnsigned(0) + self.size_of_cfruntime_base() # read 8 bytes here and make an address out of them try: - char_type = self.valobj.GetType().GetBasicType( - lldb.eBasicTypeChar).GetPointerType() + char_type = ( + self.valobj.GetType() + .GetBasicType(lldb.eBasicTypeChar) + .GetPointerType() + ) vopointer = self.valobj.CreateValueFromAddress( - "dummy", pointer, char_type) + "dummy", pointer, char_type + ) pointer = vopointer.GetValueAsUnsigned(0) except: return self.valobj.CreateValueFromExpression( - "content", '(char*)"@\"invalid NSString\""') + "content", '(char*)"@"invalid NSString""' + ) # step 2: read Unicode data at pointer pystr = self.read_unicode(pointer) # step 3: return it - return pystr.encode('utf-8') + return pystr.encode("utf-8") def handle_inline_explicit(self): logger = lldb.formatters.Logger.Logger() offset = 3 * self.pointer_size offset = offset + self.valobj.GetValueAsUnsigned(0) return self.valobj.CreateValueFromExpression( - "content", "(char*)(" + str(offset) + ")") + "content", "(char*)(" + str(offset) + ")" + ) def handle_mutable_string(self): logger = lldb.formatters.Logger.Logger() offset = 2 * self.pointer_size data = self.valobj.CreateChildAtOffset( - "content", offset, self.valobj.GetType().GetBasicType( - lldb.eBasicTypeChar).GetPointerType()) + "content", + offset, + self.valobj.GetType().GetBasicType(lldb.eBasicTypeChar).GetPointerType(), + ) data_value = data.GetValueAsUnsigned(0) if self.explicit and self.unicode: - return self.read_unicode(data_value).encode('utf-8') + return self.read_unicode(data_value).encode("utf-8") else: data_value = data_value + 1 return self.valobj.CreateValueFromExpression( - "content", "(char*)(" + str(data_value) + ")") + "content", "(char*)(" + str(data_value) + ")" + ) def handle_UTF8_inline(self): logger = lldb.formatters.Logger.Logger() - offset = self.valobj.GetValueAsUnsigned( - 0) + self.size_of_cfruntime_base() + offset = self.valobj.GetValueAsUnsigned(0) + self.size_of_cfruntime_base() if not self.explicit: offset = offset + 1 return self.valobj.CreateValueFromAddress( - "content", offset, self.valobj.GetType().GetBasicType( - lldb.eBasicTypeChar)).AddressOf() + "content", offset, self.valobj.GetType().GetBasicType(lldb.eBasicTypeChar) + ).AddressOf() def handle_UTF8_not_inline(self): logger = lldb.formatters.Logger.Logger() offset = self.size_of_cfruntime_base() return self.valobj.CreateChildAtOffset( - "content", offset, self.valobj.GetType().GetBasicType( - lldb.eBasicTypeChar).GetPointerType()) + "content", + offset, + self.valobj.GetType().GetBasicType(lldb.eBasicTypeChar).GetPointerType(), + ) def get_child_at_index(self, index): logger = lldb.formatters.Logger.Logger() logger >> "Querying for child [" + str(index) + "]" if index == 0: return self.valobj.CreateValueFromExpression( - "mutable", str(int(self.mutable))) + "mutable", str(int(self.mutable)) + ) if index == 1: - return self.valobj.CreateValueFromExpression("inline", - str(int(self.inline))) + return self.valobj.CreateValueFromExpression( + "inline", str(int(self.inline)) + ) if index == 2: return self.valobj.CreateValueFromExpression( - "explicit", str(int(self.explicit))) + "explicit", str(int(self.explicit)) + ) if index == 3: return self.valobj.CreateValueFromExpression( - "unicode", str(int(self.unicode))) + "unicode", str(int(self.unicode)) + ) if index == 4: return self.valobj.CreateValueFromExpression( - "special", str(int(self.special))) + "special", str(int(self.special)) + ) if index == 5: # we are handling the several possible combinations of flags. # for each known combination we have a function that knows how to @@ -233,9 +250,13 @@ # print 'special = ' + str(self.special) if self.mutable: return self.handle_mutable_string() - elif self.inline and self.explicit and \ - self.unicode == False and self.special == False and \ - self.mutable == False: + elif ( + self.inline + and self.explicit + and self.unicode == False + and self.special == False + and self.mutable == False + ): return self.handle_inline_explicit() elif self.unicode: return self.handle_unicode_string() @@ -287,8 +308,8 @@ cfinfo = self.valobj.CreateChildAtOffset( "cfinfo", self.offset_of_info_bits(), - self.valobj.GetType().GetBasicType( - lldb.eBasicTypeChar)) + self.valobj.GetType().GetBasicType(lldb.eBasicTypeChar), + ) cfinfo.SetFormat(11) info = cfinfo.GetValue() if info is not None: @@ -333,8 +354,9 @@ logger = lldb.formatters.Logger.Logger() self.pointer_size = self.valobj.GetTarget().GetProcess().GetAddressByteSize() self.is_64_bit = self.pointer_size == 8 - self.is_little = self.valobj.GetTarget().GetProcess( - ).GetByteOrder() == lldb.eByteOrderLittle + self.is_little = ( + self.valobj.GetTarget().GetProcess().GetByteOrder() == lldb.eByteOrderLittle + ) # reading info bits out of the CFString and computing # useful values to get at the real data diff --git a/lldb/examples/summaries/cocoa/Class.py b/lldb/examples/summaries/cocoa/Class.py --- a/lldb/examples/summaries/cocoa/Class.py +++ b/lldb/examples/summaries/cocoa/Class.py @@ -12,11 +12,10 @@ def Class_Summary(valobj, dict): logger = lldb.formatters.Logger.Logger() - runtime = lldb.runtime.objc.objc_runtime.ObjCRuntime.runtime_from_isa( - valobj) + runtime = lldb.runtime.objc.objc_runtime.ObjCRuntime.runtime_from_isa(valobj) if runtime is None or not runtime.is_valid(): - return '' + return "" class_data = runtime.read_class_data() if class_data is None or not class_data.is_valid(): - return '' + return "" return class_data.class_name() diff --git a/lldb/examples/summaries/cocoa/Logger.py b/lldb/examples/summaries/cocoa/Logger.py --- a/lldb/examples/summaries/cocoa/Logger.py +++ b/lldb/examples/summaries/cocoa/Logger.py @@ -4,7 +4,6 @@ class NopLogger: - def __init__(self): pass @@ -19,7 +18,6 @@ class StdoutLogger: - def __init__(self): pass @@ -34,15 +32,14 @@ class FileLogger: - def __init__(self, name): self.file = None try: name = os.path.abspath(name) - self.file = open(name, 'a') + self.file = open(name, "a") except: try: - self.file = open('formatters.log', 'a') + self.file = open("formatters.log", "a") except: pass @@ -61,6 +58,7 @@ self.file.close() self.file = None + # to enable logging: # define lldb.formatters.Logger._lldb_formatters_debug_level to any number greater than 0 # if you define it to any value greater than 1, the log will be automatically flushed after each write (slower but should make sure most of the stuff makes it to the log even if we crash) @@ -71,14 +69,13 @@ class Logger: - def __init__(self, autoflush=False, logcaller=False): global _lldb_formatters_debug_level global _lldb_formatters_debug_filename self.autoflush = autoflush want_log = False try: - want_log = (_lldb_formatters_debug_level > 0) + want_log = _lldb_formatters_debug_level > 0 except: pass if not (want_log): @@ -86,8 +83,11 @@ return want_file = False try: - want_file = (_lldb_formatters_debug_filename is not None and _lldb_formatters_debug_filename != - '' and _lldb_formatters_debug_filename != 0) + want_file = ( + _lldb_formatters_debug_filename is not None + and _lldb_formatters_debug_filename != "" + and _lldb_formatters_debug_filename != 0 + ) except: pass if want_file: @@ -95,12 +95,12 @@ else: self.impl = StdoutLogger() try: - self.autoflush = (_lldb_formatters_debug_level > 1) + self.autoflush = _lldb_formatters_debug_level > 1 except: self.autoflush = autoflush want_caller_info = False try: - want_caller_info = (_lldb_formatters_debug_level > 2) + want_caller_info = _lldb_formatters_debug_level > 2 except: pass if want_caller_info: @@ -110,10 +110,11 @@ caller = inspect.stack()[2] try: if caller is not None and len(caller) > 3: - self.write('Logging from function ' + str(caller)) + self.write("Logging from function " + str(caller)) else: self.write( - 'Caller info not available - Required caller logging not possible') + "Caller info not available - Required caller logging not possible" + ) finally: del caller # needed per Python docs to avoid keeping objects alive longer than we care diff --git a/lldb/examples/summaries/cocoa/NSBundle.py b/lldb/examples/summaries/cocoa/NSBundle.py --- a/lldb/examples/summaries/cocoa/NSBundle.py +++ b/lldb/examples/summaries/cocoa/NSBundle.py @@ -15,10 +15,10 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # despite the similary to synthetic children providers, these classes are not # trying to provide anything but a summary for an NSURL, so they need not @@ -26,7 +26,6 @@ class NSBundleKnown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -34,9 +33,10 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSString): - self.sys_params.types_cache.NSString = self.valobj.GetTarget( - ).FindFirstType('NSString').GetPointerType() + if not (self.sys_params.types_cache.NSString): + self.sys_params.types_cache.NSString = ( + self.valobj.GetTarget().FindFirstType("NSString").GetPointerType() + ) self.update() def update(self): @@ -54,21 +54,23 @@ logger = lldb.formatters.Logger.Logger() global statistics text = self.valobj.CreateChildAtOffset( - "text", self.offset(), self.sys_params.types_cache.NSString) + "text", self.offset(), self.sys_params.types_cache.NSString + ) my_string = text.GetSummary() - if (my_string is None) or (my_string == ''): + if (my_string is None) or (my_string == ""): statistics.metric_hit( - 'unknown_class', str( - self.valobj.GetName()) + " triggered unknown pointer location") + "unknown_class", + str(self.valobj.GetName()) + " triggered unknown pointer location", + ) return NSBundleUnknown_SummaryProvider( - self.valobj, self.sys_params).url_text() + self.valobj, self.sys_params + ).url_text() else: - statistics.metric_hit('code_notrun', self.valobj) + statistics.metric_hit("code_notrun", self.valobj) return my_string class NSBundleUnknown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -90,34 +92,35 @@ url_text_vo = self.valobj.CreateValueFromExpression("path", expr) if url_text_vo.IsValid(): return url_text_vo.GetSummary() - return '' + return "" def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper name_string = class_data.class_name() logger >> "class name is: " + str(name_string) - if name_string == 'NSBundle': + if name_string == "NSBundle": wrapper = NSBundleKnown_SummaryProvider(valobj, class_data.sys_params) # [NSBundle mainBundle] does return an object that is # not correctly filled out for our purposes, so we still # end up having to run code in that case # statistics.metric_hit('code_notrun',valobj) else: - wrapper = NSBundleUnknown_SummaryProvider( - valobj, class_data.sys_params) + wrapper = NSBundleUnknown_SummaryProvider(valobj, class_data.sys_params) statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + "unknown_class", valobj.GetName() + " seen as " + name_string + ) return wrapper @@ -126,20 +129,21 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.url_text() except: summary = None logger >> "got summary " + str(summary) - if summary is None or summary == '': - summary = '' + if summary is None or summary == "": + summary = "" return summary - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F NSBundle.NSBundle_SummaryProvider NSBundle") + "type summary add -F NSBundle.NSBundle_SummaryProvider NSBundle" + ) diff --git a/lldb/examples/summaries/cocoa/NSData.py b/lldb/examples/summaries/cocoa/NSData.py --- a/lldb/examples/summaries/cocoa/NSData.py +++ b/lldb/examples/summaries/cocoa/NSData.py @@ -14,10 +14,10 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # despite the similary to synthetic children providers, these classes are not # trying to provide anything but the length for an NSData, so they need not @@ -25,7 +25,6 @@ class NSConcreteData_SummaryProvider: - def adjust_for_architecture(self): pass @@ -34,13 +33,15 @@ logger >> "NSConcreteData_SummaryProvider __init__" self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSUInteger): + if not (self.sys_params.types_cache.NSUInteger): if self.sys_params.is_64_bit: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedLong) + ) else: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedInt) + ) self.update() def update(self): @@ -58,14 +59,14 @@ logger = lldb.formatters.Logger.Logger() logger >> "NSConcreteData_SummaryProvider length" size = self.valobj.CreateChildAtOffset( - "count", self.offset(), self.sys_params.types_cache.NSUInteger) + "count", self.offset(), self.sys_params.types_cache.NSUInteger + ) logger >> str(size) logger >> str(size.GetValueAsUnsigned(0)) return size.GetValueAsUnsigned(0) class NSDataUnknown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -86,40 +87,46 @@ self.valobj.GetExpressionPath(stream) logger >> stream.GetData() num_children_vo = self.valobj.CreateValueFromExpression( - "count", "(int)[" + stream.GetData() + " length]") + "count", "(int)[" + stream.GetData() + " length]" + ) logger >> "still in after expression: " + str(num_children_vo) if num_children_vo.IsValid(): - logger >> "wow - expr output is valid: " + \ - str(num_children_vo.GetValueAsUnsigned()) + logger >> "wow - expr output is valid: " + str( + num_children_vo.GetValueAsUnsigned() + ) return num_children_vo.GetValueAsUnsigned(0) logger >> "invalid expr output - too bad" - return '' + return "" def GetSummary_Impl(valobj): global statistics logger = lldb.formatters.Logger.Logger() logger >> "NSData GetSummary_Impl" - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: logger >> "got a wrapper summary - using it" return wrapper name_string = class_data.class_name() logger >> "class name: " + name_string - if name_string == 'NSConcreteData' or \ - name_string == 'NSConcreteMutableData' or \ - name_string == '__NSCFData': + if ( + name_string == "NSConcreteData" + or name_string == "NSConcreteMutableData" + or name_string == "__NSCFData" + ): wrapper = NSConcreteData_SummaryProvider(valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + statistics.metric_hit("code_notrun", valobj) else: wrapper = NSDataUnknown_SummaryProvider(valobj, class_data.sys_params) statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + "unknown_class", valobj.GetName() + " seen as " + name_string + ) return wrapper @@ -135,16 +142,16 @@ summary = None logger >> "got a summary: it is " + str(summary) if summary is None: - summary = '' + summary = "" elif isinstance(summary, str): pass else: if summary == 1: - summary = '1 byte' + summary = "1 byte" else: - summary = str(summary) + ' bytes' + summary = str(summary) + " bytes" return summary - return 'Summary Unavailable' + return "Summary Unavailable" def NSData_SummaryProvider2(valobj, dict): @@ -154,8 +161,8 @@ logger >> "found a summary provider, it is: " + str(provider) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.length() @@ -163,7 +170,7 @@ summary = None logger >> "got a summary: it is " + str(summary) if summary is None: - summary = '' + summary = "" elif isinstance(summary, str): pass else: @@ -172,11 +179,11 @@ else: summary = '@"' + str(summary) + ' bytes"' return summary - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): + debugger.HandleCommand("type summary add -F NSData.NSData_SummaryProvider NSData") debugger.HandleCommand( - "type summary add -F NSData.NSData_SummaryProvider NSData") - debugger.HandleCommand( - "type summary add -F NSData.NSData_SummaryProvider2 CFDataRef CFMutableDataRef") + "type summary add -F NSData.NSData_SummaryProvider2 CFDataRef CFMutableDataRef" + ) diff --git a/lldb/examples/summaries/cocoa/NSDate.py b/lldb/examples/summaries/cocoa/NSDate.py --- a/lldb/examples/summaries/cocoa/NSDate.py +++ b/lldb/examples/summaries/cocoa/NSDate.py @@ -18,10 +18,10 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # Python promises to start counting time at midnight on Jan 1st on the epoch year # hence, all we need to know is the epoch year @@ -34,6 +34,7 @@ logger = lldb.formatters.Logger.Logger() return time.mktime(t) - time.timezone + osx_epoch = mkgmtime(osx_epoch) @@ -44,12 +45,14 @@ else: return osx - osx_epoch + # represent a struct_time as a string in the format used by Xcode def xcode_format_time(X): logger = lldb.formatters.Logger.Logger() - return time.strftime('%Y-%m-%d %H:%M:%S %Z', X) + return time.strftime("%Y-%m-%d %H:%M:%S %Z", X) + # represent a count-since-epoch as a string in the format used by Xcode @@ -58,13 +61,13 @@ logger = lldb.formatters.Logger.Logger() return xcode_format_time(time.localtime(X)) + # despite the similary to synthetic children providers, these classes are not # trying to provide anything but the summary for NSDate, so they need not # obey the interface specification for synthetic children providers class NSTaggedDate_SummaryProvider: - def adjust_for_architecture(self): pass @@ -75,7 +78,7 @@ self.update() # NSDate is not using its info_bits for info like NSNumber is # so we need to regroup info_bits and data - self.data = ((data << 8) | (info_bits << 4)) + self.data = (data << 8) | (info_bits << 4) def update(self): logger = lldb.formatters.Logger.Logger() @@ -87,14 +90,13 @@ # unfortunately, it is made as a time-delta after Jan 1 2001 midnight GMT # while all Python knows about is the "epoch", which is a platform-dependent # year (1970 of *nix) whose Jan 1 at midnight is taken as reference - value_double = struct.unpack('d', struct.pack('Q', self.data))[0] + value_double = struct.unpack("d", struct.pack("Q", self.data))[0] if value_double == -63114076800.0: - return '0001-12-30 00:00:00 +0000' + return "0001-12-30 00:00:00 +0000" return xcode_format_count(osx_to_python_time(value_double)) class NSUntaggedDate_SummaryProvider: - def adjust_for_architecture(self): pass @@ -103,8 +105,9 @@ self.valobj = valobj self.sys_params = params if not (self.sys_params.types_cache.double): - self.sys_params.types_cache.double = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeDouble) + self.sys_params.types_cache.double = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeDouble + ) self.update() def update(self): @@ -118,17 +121,17 @@ def value(self): logger = lldb.formatters.Logger.Logger() value = self.valobj.CreateChildAtOffset( - "value", self.offset(), self.sys_params.types_cache.double) - value_double = struct.unpack( - 'd', struct.pack( - 'Q', value.GetData().uint64[0]))[0] + "value", self.offset(), self.sys_params.types_cache.double + ) + value_double = struct.unpack("d", struct.pack("Q", value.GetData().uint64[0]))[ + 0 + ] if value_double == -63114076800.0: - return '0001-12-30 00:00:00 +0000' + return "0001-12-30 00:00:00 +0000" return xcode_format_count(osx_to_python_time(value_double)) class NSCalendarDate_SummaryProvider: - def adjust_for_architecture(self): pass @@ -137,8 +140,9 @@ self.valobj = valobj self.sys_params = params if not (self.sys_params.types_cache.double): - self.sys_params.types_cache.double = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeDouble) + self.sys_params.types_cache.double = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeDouble + ) self.update() def update(self): @@ -152,15 +156,15 @@ def value(self): logger = lldb.formatters.Logger.Logger() value = self.valobj.CreateChildAtOffset( - "value", self.offset(), self.sys_params.types_cache.double) - value_double = struct.unpack( - 'd', struct.pack( - 'Q', value.GetData().uint64[0]))[0] + "value", self.offset(), self.sys_params.types_cache.double + ) + value_double = struct.unpack("d", struct.pack("Q", value.GetData().uint64[0]))[ + 0 + ] return xcode_format_count(osx_to_python_time(value_double)) class NSTimeZoneClass_SummaryProvider: - def adjust_for_architecture(self): pass @@ -169,8 +173,9 @@ self.valobj = valobj self.sys_params = params if not (self.sys_params.types_cache.voidptr): - self.sys_params.types_cache.voidptr = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeVoid).GetPointerType() + self.sys_params.types_cache.voidptr = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeVoid).GetPointerType() + ) self.update() def update(self): @@ -184,12 +189,12 @@ def timezone(self): logger = lldb.formatters.Logger.Logger() tz_string = self.valobj.CreateChildAtOffset( - "tz_name", self.offset(), self.sys_params.types_cache.voidptr) + "tz_name", self.offset(), self.sys_params.types_cache.voidptr + ) return CFString.CFString_SummaryProvider(tz_string, None) class NSUnknownDate_SummaryProvider: - def adjust_for_architecture(self): pass @@ -210,43 +215,51 @@ num_children_vo = self.valobj.CreateValueFromExpression("str", expr) if num_children_vo.IsValid(): return num_children_vo.GetSummary() - return '' + return "" def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper name_string = class_data.class_name() logger >> "class name is: " + str(name_string) - if name_string == 'NSDate' or name_string == '__NSDate' or name_string == '__NSTaggedDate': + if ( + name_string == "NSDate" + or name_string == "__NSDate" + or name_string == "__NSTaggedDate" + ): if class_data.is_tagged(): wrapper = NSTaggedDate_SummaryProvider( - valobj, class_data.info_bits(), class_data.value(), class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + valobj, + class_data.info_bits(), + class_data.value(), + class_data.sys_params, + ) + statistics.metric_hit("code_notrun", valobj) else: - wrapper = NSUntaggedDate_SummaryProvider( - valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) - elif name_string == 'NSCalendarDate': + wrapper = NSUntaggedDate_SummaryProvider(valobj, class_data.sys_params) + statistics.metric_hit("code_notrun", valobj) + elif name_string == "NSCalendarDate": wrapper = NSCalendarDate_SummaryProvider(valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) - elif name_string == '__NSTimeZone': - wrapper = NSTimeZoneClass_SummaryProvider( - valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + statistics.metric_hit("code_notrun", valobj) + elif name_string == "__NSTimeZone": + wrapper = NSTimeZoneClass_SummaryProvider(valobj, class_data.sys_params) + statistics.metric_hit("code_notrun", valobj) else: wrapper = NSUnknownDate_SummaryProvider(valobj) statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + "unknown_class", valobj.GetName() + " seen as " + name_string + ) return wrapper @@ -255,17 +268,17 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.value() except: summary = None if summary is None: - summary = '' + summary = "" return str(summary) - return 'Summary Unavailable' + return "Summary Unavailable" def NSTimeZone_SummaryProvider(valobj, dict): @@ -273,8 +286,8 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.timezone() @@ -282,26 +295,27 @@ summary = None logger >> "got summary " + str(summary) if summary is None: - summary = '' + summary = "" return str(summary) - return 'Summary Unavailable' + return "Summary Unavailable" def CFAbsoluteTime_SummaryProvider(valobj, dict): logger = lldb.formatters.Logger.Logger() try: - value_double = struct.unpack( - 'd', struct.pack( - 'Q', valobj.GetData().uint64[0]))[0] + value_double = struct.unpack("d", struct.pack("Q", valobj.GetData().uint64[0]))[ + 0 + ] return xcode_format_count(osx_to_python_time(value_double)) except: - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): + debugger.HandleCommand("type summary add -F NSDate.NSDate_SummaryProvider NSDate") debugger.HandleCommand( - "type summary add -F NSDate.NSDate_SummaryProvider NSDate") - debugger.HandleCommand( - "type summary add -F NSDate.CFAbsoluteTime_SummaryProvider CFAbsoluteTime") + "type summary add -F NSDate.CFAbsoluteTime_SummaryProvider CFAbsoluteTime" + ) debugger.HandleCommand( - "type summary add -F NSDate.NSTimeZone_SummaryProvider NSTimeZone CFTimeZoneRef") + "type summary add -F NSDate.NSTimeZone_SummaryProvider NSTimeZone CFTimeZoneRef" + ) diff --git a/lldb/examples/summaries/cocoa/NSException.py b/lldb/examples/summaries/cocoa/NSException.py --- a/lldb/examples/summaries/cocoa/NSException.py +++ b/lldb/examples/summaries/cocoa/NSException.py @@ -13,14 +13,13 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") class NSKnownException_SummaryProvider: - def adjust_for_architecture(self): pass @@ -29,8 +28,9 @@ self.valobj = valobj self.sys_params = params if not (self.sys_params.types_cache.id): - self.sys_params.types_cache.id = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeObjCID) + self.sys_params.types_cache.id = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeObjCID + ) self.update() def update(self): @@ -48,15 +48,20 @@ def description(self): logger = lldb.formatters.Logger.Logger() name_ptr = self.valobj.CreateChildAtOffset( - "name", self.offset_name(), self.sys_params.types_cache.id) + "name", self.offset_name(), self.sys_params.types_cache.id + ) reason_ptr = self.valobj.CreateChildAtOffset( - "reason", self.offset_reason(), self.sys_params.types_cache.id) - return 'name:' + CFString.CFString_SummaryProvider( - name_ptr, None) + ' reason:' + CFString.CFString_SummaryProvider(reason_ptr, None) + "reason", self.offset_reason(), self.sys_params.types_cache.id + ) + return ( + "name:" + + CFString.CFString_SummaryProvider(name_ptr, None) + + " reason:" + + CFString.CFString_SummaryProvider(reason_ptr, None) + ) class NSUnknownException_SummaryProvider: - def adjust_for_architecture(self): pass @@ -75,38 +80,43 @@ stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) name_vo = self.valobj.CreateValueFromExpression( - "name", "(NSString*)[" + stream.GetData() + " name]") + "name", "(NSString*)[" + stream.GetData() + " name]" + ) reason_vo = self.valobj.CreateValueFromExpression( - "reason", "(NSString*)[" + stream.GetData() + " reason]") + "reason", "(NSString*)[" + stream.GetData() + " reason]" + ) if name_vo.IsValid() and reason_vo.IsValid(): - return CFString.CFString_SummaryProvider( - name_vo, None) + ' ' + CFString.CFString_SummaryProvider(reason_vo, None) - return '' + return ( + CFString.CFString_SummaryProvider(name_vo, None) + + " " + + CFString.CFString_SummaryProvider(reason_vo, None) + ) + return "" def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper name_string = class_data.class_name() logger >> "class name is: " + str(name_string) - if name_string == 'NSException': - wrapper = NSKnownException_SummaryProvider( - valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + if name_string == "NSException": + wrapper = NSKnownException_SummaryProvider(valobj, class_data.sys_params) + statistics.metric_hit("code_notrun", valobj) else: - wrapper = NSUnknownException_SummaryProvider( - valobj, class_data.sys_params) + wrapper = NSUnknownException_SummaryProvider(valobj, class_data.sys_params) statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + "unknown_class", valobj.GetName() + " seen as " + name_string + ) return wrapper @@ -115,8 +125,8 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.description() @@ -124,11 +134,12 @@ summary = None logger >> "got summary " + str(summary) if summary is None: - summary = '' + summary = "" return str(summary) - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F NSException.NSException_SummaryProvider NSException") + "type summary add -F NSException.NSException_SummaryProvider NSException" + ) diff --git a/lldb/examples/summaries/cocoa/NSIndexSet.py b/lldb/examples/summaries/cocoa/NSIndexSet.py --- a/lldb/examples/summaries/cocoa/NSIndexSet.py +++ b/lldb/examples/summaries/cocoa/NSIndexSet.py @@ -14,10 +14,10 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # despite the similary to synthetic children providers, these classes are not # trying to provide anything but the count of values for an NSIndexSet, so they need not @@ -25,7 +25,6 @@ class NSIndexSetClass_SummaryProvider: - def adjust_for_architecture(self): pass @@ -33,20 +32,25 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSUInteger): + if not (self.sys_params.types_cache.NSUInteger): if self.sys_params.is_64_bit: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) - self.sys_params.types_cache.uint32 = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedLong) + ) + self.sys_params.types_cache.uint32 = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeUnsignedInt + ) else: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) - self.sys_params.types_cache.uint32 = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) - if not(self.sys_params.types_cache.uint32): - self.sys_params.types_cache.uint32 = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedInt) + ) + self.sys_params.types_cache.uint32 = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeUnsignedInt + ) + if not (self.sys_params.types_cache.uint32): + self.sys_params.types_cache.uint32 = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeUnsignedInt + ) self.update() def update(self): @@ -64,7 +68,8 @@ mode_chooser_vo = self.valobj.CreateChildAtOffset( "mode_chooser", self.sys_params.pointer_size, - self.sys_params.types_cache.uint32) + self.sys_params.types_cache.uint32, + ) mode_chooser = mode_chooser_vo.GetValueAsUnsigned(0) if self.sys_params.is_64_bit: mode_chooser = mode_chooser & 0x00000000FFFFFFFF @@ -81,23 +86,23 @@ count_vo = self.valobj.CreateChildAtOffset( "count", 3 * self.sys_params.pointer_size, - self.sys_params.types_cache.NSUInteger) + self.sys_params.types_cache.NSUInteger, + ) else: count_ptr = self.valobj.CreateChildAtOffset( "count_ptr", 2 * self.sys_params.pointer_size, - self.sys_params.types_cache.NSUInteger) + self.sys_params.types_cache.NSUInteger, + ) count_vo = self.valobj.CreateValueFromAddress( "count", - count_ptr.GetValueAsUnsigned() + - 2 * - self.sys_params.pointer_size, - self.sys_params.types_cache.NSUInteger) + count_ptr.GetValueAsUnsigned() + 2 * self.sys_params.pointer_size, + self.sys_params.types_cache.NSUInteger, + ) return count_vo.GetValueAsUnsigned(0) class NSIndexSetUnknown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -119,32 +124,32 @@ num_children_vo = self.valobj.CreateValueFromExpression("count", expr) if num_children_vo.IsValid(): return num_children_vo.GetValueAsUnsigned(0) - return '' + return "" def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper name_string = class_data.class_name() logger >> "class name is: " + str(name_string) - if name_string == 'NSIndexSet' or name_string == 'NSMutableIndexSet': - wrapper = NSIndexSetClass_SummaryProvider( - valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + if name_string == "NSIndexSet" or name_string == "NSMutableIndexSet": + wrapper = NSIndexSetClass_SummaryProvider(valobj, class_data.sys_params) + statistics.metric_hit("code_notrun", valobj) else: - wrapper = NSIndexSetUnknown_SummaryProvider( - valobj, class_data.sys_params) + wrapper = NSIndexSetUnknown_SummaryProvider(valobj, class_data.sys_params) statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + "unknown_class", valobj.GetName() + " seen as " + name_string + ) return wrapper @@ -153,8 +158,8 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.count() @@ -162,15 +167,16 @@ summary = None logger >> "got summary " + str(summary) if summary is None: - summary = '' + summary = "" if isinstance(summary, str): return summary else: - summary = str(summary) + (' indexes' if summary != 1 else ' index') + summary = str(summary) + (" indexes" if summary != 1 else " index") return summary - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F NSIndexSet.NSIndexSet_SummaryProvider NSIndexSet NSMutableIndexSet") + "type summary add -F NSIndexSet.NSIndexSet_SummaryProvider NSIndexSet NSMutableIndexSet" + ) diff --git a/lldb/examples/summaries/cocoa/NSMachPort.py b/lldb/examples/summaries/cocoa/NSMachPort.py --- a/lldb/examples/summaries/cocoa/NSMachPort.py +++ b/lldb/examples/summaries/cocoa/NSMachPort.py @@ -14,10 +14,10 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # despite the similary to synthetic children providers, these classes are not # trying to provide anything but the port number of an NSMachPort, so they need not @@ -25,7 +25,6 @@ class NSMachPortKnown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -33,13 +32,15 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSUInteger): + if not (self.sys_params.types_cache.NSUInteger): if self.sys_params.is_64_bit: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedLong) + ) else: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedInt) + ) self.update() def update(self): @@ -59,12 +60,12 @@ def port(self): logger = lldb.formatters.Logger.Logger() vport = self.valobj.CreateChildAtOffset( - "port", self.offset(), self.sys_params.types_cache.NSUInteger) + "port", self.offset(), self.sys_params.types_cache.NSUInteger + ) return vport.GetValueAsUnsigned(0) class NSMachPortUnknown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -83,35 +84,36 @@ stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) num_children_vo = self.valobj.CreateValueFromExpression( - "port", "(int)[" + stream.GetData() + " machPort]") + "port", "(int)[" + stream.GetData() + " machPort]" + ) if num_children_vo.IsValid(): return num_children_vo.GetValueAsUnsigned(0) - return '' + return "" def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper name_string = class_data.class_name() logger >> "class name is: " + str(name_string) - if name_string == 'NSMachPort': - wrapper = NSMachPortKnown_SummaryProvider( - valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + if name_string == "NSMachPort": + wrapper = NSMachPortKnown_SummaryProvider(valobj, class_data.sys_params) + statistics.metric_hit("code_notrun", valobj) else: - wrapper = NSMachPortUnknown_SummaryProvider( - valobj, class_data.sys_params) + wrapper = NSMachPortUnknown_SummaryProvider(valobj, class_data.sys_params) statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + "unknown_class", valobj.GetName() + " seen as " + name_string + ) return wrapper @@ -120,8 +122,8 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.port() @@ -129,13 +131,14 @@ summary = None logger >> "got summary " + str(summary) if summary is None: - summary = '' + summary = "" if isinstance(summary, str): return summay - return 'mach port: ' + str(summary) - return 'Summary Unavailable' + return "mach port: " + str(summary) + return "Summary Unavailable" def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F NSMachPort.NSMachPort_SummaryProvider NSMachPort") + "type summary add -F NSMachPort.NSMachPort_SummaryProvider NSMachPort" + ) diff --git a/lldb/examples/summaries/cocoa/NSNotification.py b/lldb/examples/summaries/cocoa/NSNotification.py --- a/lldb/examples/summaries/cocoa/NSNotification.py +++ b/lldb/examples/summaries/cocoa/NSNotification.py @@ -14,14 +14,13 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") class NSConcreteNotification_SummaryProvider: - def adjust_for_architecture(self): pass @@ -30,8 +29,9 @@ self.valobj = valobj self.sys_params = params if not (self.sys_params.types_cache.id): - self.sys_params.types_cache.id = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeObjCID) + self.sys_params.types_cache.id = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeObjCID + ) self.update() def update(self): @@ -46,12 +46,12 @@ def name(self): logger = lldb.formatters.Logger.Logger() string_ptr = self.valobj.CreateChildAtOffset( - "name", self.offset(), self.sys_params.types_cache.id) + "name", self.offset(), self.sys_params.types_cache.id + ) return CFString.CFString_SummaryProvider(string_ptr, None) class NSNotificationUnknown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -70,35 +70,36 @@ stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) name_vo = self.valobj.CreateValueFromExpression( - "name", "(NSString*)[" + stream.GetData() + " name]") + "name", "(NSString*)[" + stream.GetData() + " name]" + ) if name_vo.IsValid(): return CFString.CFString_SummaryProvider(name_vo, None) - return '' + return "" def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper name_string = class_data.class_name() logger >> "class name is: " + str(name_string) - if name_string == 'NSConcreteNotification': - wrapper = NSConcreteNotification_SummaryProvider( - valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + if name_string == "NSConcreteNotification": + wrapper = NSConcreteNotification_SummaryProvider(valobj, class_data.sys_params) + statistics.metric_hit("code_notrun", valobj) else: - wrapper = NSNotificationUnknown_SummaryProvider( - valobj, class_data.sys_params) + wrapper = NSNotificationUnknown_SummaryProvider(valobj, class_data.sys_params) statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + "unknown_class", valobj.GetName() + " seen as " + name_string + ) return wrapper @@ -107,8 +108,8 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.name() @@ -116,11 +117,12 @@ summary = None logger >> "got summary " + str(summary) if summary is None: - summary = '' + summary = "" return str(summary) - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F NSNotification.NSNotification_SummaryProvider NSNotification") + "type summary add -F NSNotification.NSNotification_SummaryProvider NSNotification" + ) diff --git a/lldb/examples/summaries/cocoa/NSNumber.py b/lldb/examples/summaries/cocoa/NSNumber.py --- a/lldb/examples/summaries/cocoa/NSNumber.py +++ b/lldb/examples/summaries/cocoa/NSNumber.py @@ -16,10 +16,10 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # despite the similary to synthetic children providers, these classes are not # trying to provide anything but the port number of an NSNumber, so they need not @@ -27,7 +27,6 @@ class NSTaggedNumber_SummaryProvider: - def adjust_for_architecture(self): pass @@ -50,23 +49,26 @@ # unfortunately, the original type information appears to be lost # so we try to at least recover the proper magnitude of the data if self.info_bits == 0: - return '(char)' + \ - str(ord(ctypes.c_char(chr(self.data % 256)).value)) + return "(char)" + str(ord(ctypes.c_char(chr(self.data % 256)).value)) if self.info_bits == 4: - return '(short)' + \ - str(ctypes.c_short(self.data % (256 * 256)).value) + return "(short)" + str(ctypes.c_short(self.data % (256 * 256)).value) if self.info_bits == 8: - return '(int)' + str(ctypes.c_int(self.data % - (256 * 256 * 256 * 256)).value) + return "(int)" + str( + ctypes.c_int(self.data % (256 * 256 * 256 * 256)).value + ) if self.info_bits == 12: - return '(long)' + str(ctypes.c_long(self.data).value) + return "(long)" + str(ctypes.c_long(self.data).value) else: - return 'unexpected value:(info=' + str(self.info_bits) + \ - ", value = " + str(self.data) + ')' + return ( + "unexpected value:(info=" + + str(self.info_bits) + + ", value = " + + str(self.data) + + ")" + ) class NSUntaggedNumber_SummaryProvider: - def adjust_for_architecture(self): pass @@ -74,35 +76,46 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.char): - self.sys_params.types_cache.char = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeChar) - if not(self.sys_params.types_cache.short): - self.sys_params.types_cache.short = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeShort) - if not(self.sys_params.types_cache.ushort): - self.sys_params.types_cache.ushort = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedShort) - if not(self.sys_params.types_cache.int): - self.sys_params.types_cache.int = self.valobj.GetType().GetBasicType(lldb.eBasicTypeInt) - if not(self.sys_params.types_cache.long): - self.sys_params.types_cache.long = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeLong) - if not(self.sys_params.types_cache.ulong): - self.sys_params.types_cache.ulong = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) - if not(self.sys_params.types_cache.longlong): - self.sys_params.types_cache.longlong = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeLongLong) - if not(self.sys_params.types_cache.ulonglong): - self.sys_params.types_cache.ulonglong = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLongLong) - if not(self.sys_params.types_cache.float): - self.sys_params.types_cache.float = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeFloat) - if not(self.sys_params.types_cache.double): - self.sys_params.types_cache.double = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeDouble) + if not (self.sys_params.types_cache.char): + self.sys_params.types_cache.char = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeChar + ) + if not (self.sys_params.types_cache.short): + self.sys_params.types_cache.short = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeShort + ) + if not (self.sys_params.types_cache.ushort): + self.sys_params.types_cache.ushort = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeUnsignedShort + ) + if not (self.sys_params.types_cache.int): + self.sys_params.types_cache.int = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeInt + ) + if not (self.sys_params.types_cache.long): + self.sys_params.types_cache.long = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeLong + ) + if not (self.sys_params.types_cache.ulong): + self.sys_params.types_cache.ulong = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeUnsignedLong + ) + if not (self.sys_params.types_cache.longlong): + self.sys_params.types_cache.longlong = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeLongLong + ) + if not (self.sys_params.types_cache.ulonglong): + self.sys_params.types_cache.ulonglong = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeUnsignedLongLong + ) + if not (self.sys_params.types_cache.float): + self.sys_params.types_cache.float = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeFloat + ) + if not (self.sys_params.types_cache.double): + self.sys_params.types_cache.double = self.valobj.GetType().GetBasicType( + lldb.eBasicTypeDouble + ) self.update() def update(self): @@ -117,73 +130,81 @@ # if we are fetching an int64 value, one more pointer must be skipped # to get at our data data_type_vo = self.valobj.CreateChildAtOffset( - "dt", self.sys_params.pointer_size, self.sys_params.types_cache.char) - data_type = ((data_type_vo.GetValueAsUnsigned(0) % 256) & 0x1F) + "dt", self.sys_params.pointer_size, self.sys_params.types_cache.char + ) + data_type = (data_type_vo.GetValueAsUnsigned(0) % 256) & 0x1F data_offset = 2 * self.sys_params.pointer_size - if data_type == 0B00001: + if data_type == 0b00001: data_vo = self.valobj.CreateChildAtOffset( - "data", data_offset, self.sys_params.types_cache.char) - statistics.metric_hit('code_notrun', self.valobj) - return '(char)' + \ - str(ord(ctypes.c_char(chr(data_vo.GetValueAsUnsigned(0))).value)) - elif data_type == 0B0010: + "data", data_offset, self.sys_params.types_cache.char + ) + statistics.metric_hit("code_notrun", self.valobj) + return "(char)" + str( + ord(ctypes.c_char(chr(data_vo.GetValueAsUnsigned(0))).value) + ) + elif data_type == 0b0010: data_vo = self.valobj.CreateChildAtOffset( - "data", data_offset, self.sys_params.types_cache.short) - statistics.metric_hit('code_notrun', self.valobj) - return '(short)' + str( - ctypes.c_short( - data_vo.GetValueAsUnsigned(0) % - (256 * 256)).value) + "data", data_offset, self.sys_params.types_cache.short + ) + statistics.metric_hit("code_notrun", self.valobj) + return "(short)" + str( + ctypes.c_short(data_vo.GetValueAsUnsigned(0) % (256 * 256)).value + ) # IF tagged pointers are possible on 32bit+v2 runtime # (of which the only existing instance should be iOS) # then values of this type might be tagged - elif data_type == 0B0011: + elif data_type == 0b0011: data_vo = self.valobj.CreateChildAtOffset( - "data", data_offset, self.sys_params.types_cache.int) - statistics.metric_hit('code_notrun', self.valobj) - return '(int)' + str(ctypes.c_int(data_vo.GetValueAsUnsigned(0) % - (256 * 256 * 256 * 256)).value) + "data", data_offset, self.sys_params.types_cache.int + ) + statistics.metric_hit("code_notrun", self.valobj) + return "(int)" + str( + ctypes.c_int( + data_vo.GetValueAsUnsigned(0) % (256 * 256 * 256 * 256) + ).value + ) # apparently, on is_64_bit architectures, these are the only values that will ever # be represented by a non tagged pointers - elif data_type == 0B10001: + elif data_type == 0b10001: data_offset = data_offset + 8 # 8 is needed even if we are on 32bit data_vo = self.valobj.CreateChildAtOffset( - "data", data_offset, self.sys_params.types_cache.longlong) - statistics.metric_hit('code_notrun', self.valobj) - return '(long)' + \ - str(ctypes.c_long(data_vo.GetValueAsUnsigned(0)).value) - elif data_type == 0B0100: + "data", data_offset, self.sys_params.types_cache.longlong + ) + statistics.metric_hit("code_notrun", self.valobj) + return "(long)" + str(ctypes.c_long(data_vo.GetValueAsUnsigned(0)).value) + elif data_type == 0b0100: if self.sys_params.is_64_bit: data_offset = data_offset + self.sys_params.pointer_size data_vo = self.valobj.CreateChildAtOffset( - "data", data_offset, self.sys_params.types_cache.longlong) - statistics.metric_hit('code_notrun', self.valobj) - return '(long)' + \ - str(ctypes.c_long(data_vo.GetValueAsUnsigned(0)).value) - elif data_type == 0B0101: + "data", data_offset, self.sys_params.types_cache.longlong + ) + statistics.metric_hit("code_notrun", self.valobj) + return "(long)" + str(ctypes.c_long(data_vo.GetValueAsUnsigned(0)).value) + elif data_type == 0b0101: data_vo = self.valobj.CreateChildAtOffset( - "data", data_offset, self.sys_params.types_cache.longlong) - data_plain = int( - str(data_vo.GetValueAsUnsigned(0) & 0x00000000FFFFFFFF)) - packed = struct.pack('I', data_plain) - data_float = struct.unpack('f', packed)[0] - statistics.metric_hit('code_notrun', self.valobj) - return '(float)' + str(data_float) - elif data_type == 0B0110: + "data", data_offset, self.sys_params.types_cache.longlong + ) + data_plain = int(str(data_vo.GetValueAsUnsigned(0) & 0x00000000FFFFFFFF)) + packed = struct.pack("I", data_plain) + data_float = struct.unpack("f", packed)[0] + statistics.metric_hit("code_notrun", self.valobj) + return "(float)" + str(data_float) + elif data_type == 0b0110: data_vo = self.valobj.CreateChildAtOffset( - "data", data_offset, self.sys_params.types_cache.longlong) + "data", data_offset, self.sys_params.types_cache.longlong + ) data_plain = data_vo.GetValueAsUnsigned(0) - data_double = struct.unpack('d', struct.pack('Q', data_plain))[0] - statistics.metric_hit('code_notrun', self.valobj) - return '(double)' + str(data_double) + data_double = struct.unpack("d", struct.pack("Q", data_plain))[0] + statistics.metric_hit("code_notrun", self.valobj) + return "(double)" + str(data_double) statistics.metric_hit( - 'unknown_class', str( - valobj.GetName()) + " had unknown data_type " + str(data_type)) - return 'unexpected: dt = ' + str(data_type) + "unknown_class", + str(valobj.GetName()) + " had unknown data_type " + str(data_type), + ) + return "unexpected: dt = " + str(data_type) class NSUnknownNumber_SummaryProvider: - def adjust_for_architecture(self): pass @@ -205,38 +226,42 @@ num_children_vo = self.valobj.CreateValueFromExpression("str", expr) if num_children_vo.IsValid(): return num_children_vo.GetSummary() - return '' + return "" def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper name_string = class_data.class_name() logger >> "class name is: " + str(name_string) - if name_string == 'NSNumber' or name_string == '__NSCFNumber': + if name_string == "NSNumber" or name_string == "__NSCFNumber": if class_data.is_tagged(): wrapper = NSTaggedNumber_SummaryProvider( - valobj, class_data.info_bits(), class_data.value(), class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + valobj, + class_data.info_bits(), + class_data.value(), + class_data.sys_params, + ) + statistics.metric_hit("code_notrun", valobj) else: # the wrapper might be unable to decipher what is into the NSNumber # and then have to run code on it - wrapper = NSUntaggedNumber_SummaryProvider( - valobj, class_data.sys_params) + wrapper = NSUntaggedNumber_SummaryProvider(valobj, class_data.sys_params) else: - wrapper = NSUnknownNumber_SummaryProvider( - valobj, class_data.sys_params) + wrapper = NSUnknownNumber_SummaryProvider(valobj, class_data.sys_params) statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + "unknown_class", valobj.GetName() + " seen as " + name_string + ) return wrapper @@ -245,26 +270,29 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.value() except Exception as foo: print(foo) -# except: + # except: summary = None logger >> "got summary " + str(summary) if summary is None: - summary = '' + summary = "" return str(summary) - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F NSNumber.NSNumber_SummaryProvider NSNumber") + "type summary add -F NSNumber.NSNumber_SummaryProvider NSNumber" + ) debugger.HandleCommand( - "type summary add -F NSNumber.NSNumber_SummaryProvider __NSCFBoolean") + "type summary add -F NSNumber.NSNumber_SummaryProvider __NSCFBoolean" + ) debugger.HandleCommand( - "type summary add -F NSNumber.NSNumber_SummaryProvider __NSCFNumber") + "type summary add -F NSNumber.NSNumber_SummaryProvider __NSCFNumber" + ) diff --git a/lldb/examples/summaries/cocoa/NSSet.py b/lldb/examples/summaries/cocoa/NSSet.py --- a/lldb/examples/summaries/cocoa/NSSet.py +++ b/lldb/examples/summaries/cocoa/NSSet.py @@ -14,10 +14,10 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # despite the similary to synthetic children providers, these classes are not # trying to provide anything but the port number of an NSMachPort, so they need not @@ -25,7 +25,6 @@ class NSCFSet_SummaryProvider: - def adjust_for_architecture(self): pass @@ -33,13 +32,15 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSUInteger): + if not (self.sys_params.types_cache.NSUInteger): if self.sys_params.is_64_bit: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedLong) + ) else: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedInt) + ) self.update() def update(self): @@ -59,12 +60,12 @@ def count(self): logger = lldb.formatters.Logger.Logger() vcount = self.valobj.CreateChildAtOffset( - "count", self.offset(), self.sys_params.types_cache.NSUInteger) + "count", self.offset(), self.sys_params.types_cache.NSUInteger + ) return vcount.GetValueAsUnsigned(0) class NSSetUnknown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -86,11 +87,10 @@ num_children_vo = self.valobj.CreateValueFromExpression("count", expr) if num_children_vo.IsValid(): return num_children_vo.GetValueAsUnsigned(0) - return '' + return "" class NSSetI_SummaryProvider: - def adjust_for_architecture(self): pass @@ -98,13 +98,15 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSUInteger): + if not (self.sys_params.types_cache.NSUInteger): if self.sys_params.is_64_bit: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedLong) + ) else: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedInt) + ) self.update() def update(self): @@ -119,7 +121,8 @@ def count(self): logger = lldb.formatters.Logger.Logger() num_children_vo = self.valobj.CreateChildAtOffset( - "count", self.offset(), self.sys_params.types_cache.NSUInteger) + "count", self.offset(), self.sys_params.types_cache.NSUInteger + ) value = num_children_vo.GetValueAsUnsigned(0) if value is not None: # the MSB on immutable sets seems to be taken by some other data @@ -134,7 +137,6 @@ class NSSetM_SummaryProvider: - def adjust_for_architecture(self): pass @@ -142,13 +144,15 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSUInteger): + if not (self.sys_params.types_cache.NSUInteger): if self.sys_params.is_64_bit: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedLong) + ) else: - self.sys_params.types_cache.NSUInteger = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.sys_params.types_cache.NSUInteger = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeUnsignedInt) + ) self.update() def update(self): @@ -163,12 +167,12 @@ def count(self): logger = lldb.formatters.Logger.Logger() num_children_vo = self.valobj.CreateChildAtOffset( - "count", self.offset(), self.sys_params.types_cache.NSUInteger) + "count", self.offset(), self.sys_params.types_cache.NSUInteger + ) return num_children_vo.GetValueAsUnsigned(0) class NSCountedSet_SummaryProvider: - def adjust_for_architecture(self): pass @@ -177,8 +181,9 @@ self.valobj = valobj self.sys_params = params if not (self.sys_params.types_cache.voidptr): - self.sys_params.types_cache.voidptr = self.valobj.GetType( - ).GetBasicType(lldb.eBasicTypeVoid).GetPointerType() + self.sys_params.types_cache.voidptr = ( + self.valobj.GetType().GetBasicType(lldb.eBasicTypeVoid).GetPointerType() + ) self.update() def update(self): @@ -194,41 +199,43 @@ def count(self): logger = lldb.formatters.Logger.Logger() cfbag_vo = self.valobj.CreateChildAtOffset( - "bag_impl", self.offset(), self.sys_params.types_cache.voidptr) - return CFBag.CFBagRef_SummaryProvider( - cfbag_vo, self.sys_params).length() + "bag_impl", self.offset(), self.sys_params.types_cache.voidptr + ) + return CFBag.CFBagRef_SummaryProvider(cfbag_vo, self.sys_params).length() def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper name_string = class_data.class_name() logger >> "class name is: " + str(name_string) - if name_string == '__NSCFSet': + if name_string == "__NSCFSet": wrapper = NSCFSet_SummaryProvider(valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) - elif name_string == '__NSSetI': + statistics.metric_hit("code_notrun", valobj) + elif name_string == "__NSSetI": wrapper = NSSetI_SummaryProvider(valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) - elif name_string == '__NSSetM': + statistics.metric_hit("code_notrun", valobj) + elif name_string == "__NSSetM": wrapper = NSSetM_SummaryProvider(valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) - elif name_string == 'NSCountedSet': + statistics.metric_hit("code_notrun", valobj) + elif name_string == "NSCountedSet": wrapper = NSCountedSet_SummaryProvider(valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + statistics.metric_hit("code_notrun", valobj) else: wrapper = NSSetUnknown_SummaryProvider(valobj, class_data.sys_params) statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + "unknown_class", valobj.GetName() + " seen as " + name_string + ) return wrapper @@ -241,14 +248,13 @@ except: summary = None if summary is None: - summary = '' + summary = "" if isinstance(summary, str): return summary else: - summary = str(summary) + \ - (' objects' if summary != 1 else ' object') + summary = str(summary) + (" objects" if summary != 1 else " object") return summary - return 'Summary Unavailable' + return "Summary Unavailable" def NSSet_SummaryProvider2(valobj, dict): @@ -256,8 +262,8 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.count() @@ -270,20 +276,19 @@ # experimentation (if counts start looking weird, then most probably # the mask needs to be changed) if summary is None: - summary = '' + summary = "" if isinstance(summary, str): return summary else: if provider.sys_params.is_64_bit: - summary = summary & ~0x1fff000000000000 - summary = '@"' + str(summary) + \ - (' values"' if summary != 1 else ' value"') + summary = summary & ~0x1FFF000000000000 + summary = '@"' + str(summary) + (' values"' if summary != 1 else ' value"') return summary - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): + debugger.HandleCommand("type summary add -F NSSet.NSSet_SummaryProvider NSSet") debugger.HandleCommand( - "type summary add -F NSSet.NSSet_SummaryProvider NSSet") - debugger.HandleCommand( - "type summary add -F NSSet.NSSet_SummaryProvider2 CFSetRef CFMutableSetRef") + "type summary add -F NSSet.NSSet_SummaryProvider2 CFSetRef CFMutableSetRef" + ) diff --git a/lldb/examples/summaries/cocoa/NSURL.py b/lldb/examples/summaries/cocoa/NSURL.py --- a/lldb/examples/summaries/cocoa/NSURL.py +++ b/lldb/examples/summaries/cocoa/NSURL.py @@ -14,10 +14,10 @@ import lldb.formatters.Logger statistics = lldb.formatters.metrics.Metrics() -statistics.add_metric('invalid_isa') -statistics.add_metric('invalid_pointer') -statistics.add_metric('unknown_class') -statistics.add_metric('code_notrun') +statistics.add_metric("invalid_isa") +statistics.add_metric("invalid_pointer") +statistics.add_metric("unknown_class") +statistics.add_metric("code_notrun") # despite the similary to synthetic children providers, these classes are not # trying to provide anything but a summary for an NSURL, so they need not @@ -25,7 +25,6 @@ class NSURLKnown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -33,12 +32,14 @@ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.sys_params = params - if not(self.sys_params.types_cache.NSString): - self.sys_params.types_cache.NSString = self.valobj.GetTarget( - ).FindFirstType('NSString').GetPointerType() - if not(self.sys_params.types_cache.NSURL): - self.sys_params.types_cache.NSURL = self.valobj.GetTarget( - ).FindFirstType('NSURL').GetPointerType() + if not (self.sys_params.types_cache.NSString): + self.sys_params.types_cache.NSString = ( + self.valobj.GetTarget().FindFirstType("NSString").GetPointerType() + ) + if not (self.sys_params.types_cache.NSURL): + self.sys_params.types_cache.NSURL = ( + self.valobj.GetTarget().FindFirstType("NSURL").GetPointerType() + ) self.update() def update(self): @@ -63,14 +64,16 @@ def url_text(self): logger = lldb.formatters.Logger.Logger() text = self.valobj.CreateChildAtOffset( - "text", self.offset_text(), self.sys_params.types_cache.NSString) + "text", self.offset_text(), self.sys_params.types_cache.NSString + ) base = self.valobj.CreateChildAtOffset( - "base", self.offset_base(), self.sys_params.types_cache.NSURL) + "base", self.offset_base(), self.sys_params.types_cache.NSURL + ) my_string = CFString.CFString_SummaryProvider(text, None) if len(my_string) > 0 and base.GetValueAsUnsigned(0) != 0: # remove final " from myself - my_string = my_string[0:len(my_string) - 1] - my_string = my_string + ' -- ' + my_string = my_string[0 : len(my_string) - 1] + my_string = my_string + " -- " my_base_string = NSURL_SummaryProvider(base, None) if len(my_base_string) > 2: # remove @" marker from base URL string @@ -80,7 +83,6 @@ class NSURLUnknown_SummaryProvider: - def adjust_for_architecture(self): pass @@ -99,33 +101,36 @@ stream = lldb.SBStream() self.valobj.GetExpressionPath(stream) url_text_vo = self.valobj.CreateValueFromExpression( - "url", "(NSString*)[" + stream.GetData() + " description]") + "url", "(NSString*)[" + stream.GetData() + " description]" + ) if url_text_vo.IsValid(): return CFString.CFString_SummaryProvider(url_text_vo, None) - return '' + return "" def GetSummary_Impl(valobj): logger = lldb.formatters.Logger.Logger() global statistics - class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( - valobj, statistics) + ( + class_data, + wrapper, + ) = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection( + valobj, statistics + ) if wrapper: return wrapper name_string = class_data.class_name() logger >> "class name is: " + str(name_string) - if name_string == 'NSURL': + if name_string == "NSURL": wrapper = NSURLKnown_SummaryProvider(valobj, class_data.sys_params) - statistics.metric_hit('code_notrun', valobj) + statistics.metric_hit("code_notrun", valobj) else: wrapper = NSURLUnknown_SummaryProvider(valobj, class_data.sys_params) statistics.metric_hit( - 'unknown_class', - valobj.GetName() + - " seen as " + - name_string) + "unknown_class", valobj.GetName() + " seen as " + name_string + ) return wrapper @@ -134,20 +139,21 @@ provider = GetSummary_Impl(valobj) if provider is not None: if isinstance( - provider, - lldb.runtime.objc.objc_runtime.SpecialSituation_Description): + provider, lldb.runtime.objc.objc_runtime.SpecialSituation_Description + ): return provider.message() try: summary = provider.url_text() except: summary = None logger >> "got summary " + str(summary) - if summary is None or summary == '': - summary = '' + if summary is None or summary == "": + summary = "" return summary - return 'Summary Unavailable' + return "Summary Unavailable" def __lldb_init_module(debugger, dict): debugger.HandleCommand( - "type summary add -F NSURL.NSURL_SummaryProvider NSURL CFURLRef") + "type summary add -F NSURL.NSURL_SummaryProvider NSURL CFURLRef" + ) diff --git a/lldb/examples/summaries/cocoa/Selector.py b/lldb/examples/summaries/cocoa/Selector.py --- a/lldb/examples/summaries/cocoa/Selector.py +++ b/lldb/examples/summaries/cocoa/Selector.py @@ -9,11 +9,18 @@ def SEL_Summary(valobj, dict): - return valobj.Cast(valobj.GetType().GetBasicType( - lldb.eBasicTypeChar).GetPointerType()).GetSummary() + return valobj.Cast( + valobj.GetType().GetBasicType(lldb.eBasicTypeChar).GetPointerType() + ).GetSummary() def SELPointer_Summary(valobj, dict): - return valobj.CreateValueFromAddress( - 'text', valobj.GetValueAsUnsigned(0), valobj.GetType().GetBasicType( - lldb.eBasicTypeChar)).AddressOf().GetSummary() + return ( + valobj.CreateValueFromAddress( + "text", + valobj.GetValueAsUnsigned(0), + valobj.GetType().GetBasicType(lldb.eBasicTypeChar), + ) + .AddressOf() + .GetSummary() + ) diff --git a/lldb/examples/summaries/cocoa/attrib_fromdict.py b/lldb/examples/summaries/cocoa/attrib_fromdict.py --- a/lldb/examples/summaries/cocoa/attrib_fromdict.py +++ b/lldb/examples/summaries/cocoa/attrib_fromdict.py @@ -8,11 +8,10 @@ class AttributesDictionary: - def __init__(self, allow_reset=True): # need to do it this way to prevent endless recursion - self.__dict__['_dictionary'] = {} - self.__dict__['_allow_reset'] = allow_reset + self.__dict__["_dictionary"] = {} + self.__dict__["_allow_reset"] = allow_reset def __getattr__(self, name): if not self._check_exists(name): diff --git a/lldb/examples/summaries/cocoa/cache.py b/lldb/examples/summaries/cocoa/cache.py --- a/lldb/examples/summaries/cocoa/cache.py +++ b/lldb/examples/summaries/cocoa/cache.py @@ -9,12 +9,11 @@ class Cache: - def __init__(self): self.data = {} self.statistics = lldb.formatters.metrics.Metrics() - self.statistics.add_metric('hit') - self.statistics.add_metric('miss') + self.statistics.add_metric("hit") + self.statistics.add_metric("miss") def look_for_key(self, key): if key in self.data: @@ -22,15 +21,15 @@ return False def add_item(self, key, value, ok_to_replace=True): - if not(ok_to_replace) and self.look_for_key(key): + if not (ok_to_replace) and self.look_for_key(key): return False self.data[key] = value return True def get_value(self, key, default=None): if self.look_for_key(key): - self.statistics.metric_hit('hit', key) + self.statistics.metric_hit("hit", key) return self.data[key] else: - self.statistics.metric_hit('miss', key) + self.statistics.metric_hit("miss", key) return default diff --git a/lldb/examples/summaries/cocoa/metrics.py b/lldb/examples/summaries/cocoa/metrics.py --- a/lldb/examples/summaries/cocoa/metrics.py +++ b/lldb/examples/summaries/cocoa/metrics.py @@ -12,7 +12,6 @@ class TimeMetrics: - @staticmethod def generate(label=None): return TimeMetrics(label) @@ -28,13 +27,17 @@ def __exit__(self, a, b, c): self.exit_time = time.clock() - print("It took " + str(self.exit_time - self.enter_time) + - " time units to run through " + self.function + self.label) + print( + "It took " + + str(self.exit_time - self.enter_time) + + " time units to run through " + + self.function + + self.label + ) return False class Counter: - def __init__(self): self.count = 0 self.list = [] @@ -53,7 +56,6 @@ class MetricsPrinter_Verbose: - def __init__(self, metrics): self.metrics = metrics @@ -65,20 +67,24 @@ class MetricsPrinter_Compact: - def __init__(self, metrics): self.metrics = metrics def __str__(self): string = "" for key, value in self.metrics.metrics.items(): - string = string + "metric " + \ - str(key) + " was hit " + str(value.count) + " times\n" + string = ( + string + + "metric " + + str(key) + + " was hit " + + str(value.count) + + " times\n" + ) return string class Metrics: - def __init__(self): self.metrics = {} @@ -92,12 +98,13 @@ return self.metrics[key] def __getattr__(self, name): - if name == 'compact': + if name == "compact": return MetricsPrinter_Compact(self) - if name == 'verbose': + if name == "verbose": return MetricsPrinter_Verbose(self) - raise AttributeError("%r object has no attribute %r" % - (type(self).__name__, name)) + raise AttributeError( + "%r object has no attribute %r" % (type(self).__name__, name) + ) def __str__(self): return str(self.verbose) diff --git a/lldb/examples/summaries/cocoa/objc_runtime.py b/lldb/examples/summaries/cocoa/objc_runtime.py --- a/lldb/examples/summaries/cocoa/objc_runtime.py +++ b/lldb/examples/summaries/cocoa/objc_runtime.py @@ -13,7 +13,6 @@ class Utilities: - @staticmethod def read_ascii(process, pointer, max_len=128): logger = lldb.formatters.Logger.Logger() @@ -36,7 +35,7 @@ return allow_NULL if allow_tagged and (pointer % 2) == 1: return 1 - return ((pointer % pointer_size) == 0) + return (pointer % pointer_size) == 0 # Objective-C runtime has a rule that pointers in a class_t will only have bits 0 thru 46 set # so if any pointer has bits 47 thru 63 high we know that this is not a @@ -46,7 +45,7 @@ logger = lldb.formatters.Logger.Logger() if pointer is None: return 0 - return ((pointer & 0xFFFF800000000000) == 0) + return (pointer & 0xFFFF800000000000) == 0 @staticmethod def read_child_of(valobj, offset, type): @@ -71,7 +70,8 @@ # WARNING: this means that you cannot use this runtime implementation if you need to deal # with class names that use anything but what is allowed here ok_values = dict.fromkeys( - "$%_.-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890") + "$%_.-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890" + ) return all(c in ok_values for c in name) @staticmethod @@ -80,7 +80,7 @@ # assume the only thing that has a Foundation.framework is a Mac # assume anything < Lion does not even exist try: - mod = target.module['Foundation'] + mod = target.module["Foundation"] except: mod = None if mod is None or mod.IsValid() == 0: @@ -88,7 +88,7 @@ ver = mod.GetVersion() if ver is None or ver == []: return None - return (ver[0] < 900) + return ver[0] < 900 # a utility method that factors out code common to almost all the formatters # takes in an SBValue and a metrics object @@ -99,46 +99,47 @@ logger = lldb.formatters.Logger.Logger() class_data = ObjCRuntime(valobj) if class_data.is_valid() == 0: - statistics.metric_hit('invalid_pointer', valobj) - wrapper = InvalidPointer_Description( - valobj.GetValueAsUnsigned(0) == 0) + statistics.metric_hit("invalid_pointer", valobj) + wrapper = InvalidPointer_Description(valobj.GetValueAsUnsigned(0) == 0) return class_data, wrapper class_data = class_data.read_class_data() if class_data.is_valid() == 0: - statistics.metric_hit('invalid_isa', valobj) + statistics.metric_hit("invalid_isa", valobj) wrapper = InvalidISA_Description() return class_data, wrapper if class_data.is_kvo(): class_data = class_data.get_superclass() - if class_data.class_name() == '_NSZombie_OriginalClass': + if class_data.class_name() == "_NSZombie_OriginalClass": wrapper = ThisIsZombie_Description() return class_data, wrapper return class_data, None class RoT_Data: - def __init__(self, rot_pointer, params): logger = lldb.formatters.Logger.Logger() - if (Utilities.is_valid_pointer(rot_pointer.GetValueAsUnsigned(), - params.pointer_size, allow_tagged=0)): + if Utilities.is_valid_pointer( + rot_pointer.GetValueAsUnsigned(), params.pointer_size, allow_tagged=0 + ): self.sys_params = params self.valobj = rot_pointer - #self.flags = Utilities.read_child_of(self.valobj,0,self.sys_params.uint32_t) - #self.instanceStart = Utilities.read_child_of(self.valobj,4,self.sys_params.uint32_t) + # self.flags = Utilities.read_child_of(self.valobj,0,self.sys_params.uint32_t) + # self.instanceStart = Utilities.read_child_of(self.valobj,4,self.sys_params.uint32_t) self.instanceSize = None # lazy fetching offset = 24 if self.sys_params.is_64_bit else 16 - #self.ivarLayoutPtr = Utilities.read_child_of(self.valobj,offset,self.sys_params.addr_ptr_type) + # self.ivarLayoutPtr = Utilities.read_child_of(self.valobj,offset,self.sys_params.addr_ptr_type) self.namePointer = Utilities.read_child_of( - self.valobj, offset, self.sys_params.types_cache.addr_ptr_type) + self.valobj, offset, self.sys_params.types_cache.addr_ptr_type + ) self.valid = 1 # self.check_valid() else: logger >> "Marking as invalid - rot is invalid" self.valid = 0 if self.valid: self.name = Utilities.read_ascii( - self.valobj.GetTarget().GetProcess(), self.namePointer) - if not(Utilities.is_valid_identifier(self.name)): + self.valobj.GetTarget().GetProcess(), self.namePointer + ) + if not (Utilities.is_valid_identifier(self.name)): logger >> "Marking as invalid - name is invalid" self.valid = 0 @@ -147,14 +148,20 @@ self.valid = 1 # misaligned pointers seem to be possible for this field # if not(Utilities.is_valid_pointer(self.namePointer,self.sys_params.pointer_size,allow_tagged=0)): - # self.valid = 0 - # pass + # self.valid = 0 + # pass def __str__(self): logger = lldb.formatters.Logger.Logger() - return \ - "instanceSize = " + hex(self.instance_size()) + "\n" + \ - "namePointer = " + hex(self.namePointer) + " --> " + self.name + return ( + "instanceSize = " + + hex(self.instance_size()) + + "\n" + + "namePointer = " + + hex(self.namePointer) + + " --> " + + self.name + ) def is_valid(self): return self.valid @@ -165,7 +172,8 @@ return None if self.instanceSize is None: self.instanceSize = Utilities.read_child_of( - self.valobj, 8, self.sys_params.types_cache.uint32_t) + self.valobj, 8, self.sys_params.types_cache.uint32_t + ) if align: unalign = self.instance_size(0) if self.sys_params.is_64_bit: @@ -177,45 +185,50 @@ class RwT_Data: - def __init__(self, rwt_pointer, params): logger = lldb.formatters.Logger.Logger() - if (Utilities.is_valid_pointer(rwt_pointer.GetValueAsUnsigned(), - params.pointer_size, allow_tagged=0)): + if Utilities.is_valid_pointer( + rwt_pointer.GetValueAsUnsigned(), params.pointer_size, allow_tagged=0 + ): self.sys_params = params self.valobj = rwt_pointer - #self.flags = Utilities.read_child_of(self.valobj,0,self.sys_params.uint32_t) - #self.version = Utilities.read_child_of(self.valobj,4,self.sys_params.uint32_t) + # self.flags = Utilities.read_child_of(self.valobj,0,self.sys_params.uint32_t) + # self.version = Utilities.read_child_of(self.valobj,4,self.sys_params.uint32_t) self.roPointer = Utilities.read_child_of( - self.valobj, 8, self.sys_params.types_cache.addr_ptr_type) + self.valobj, 8, self.sys_params.types_cache.addr_ptr_type + ) self.check_valid() else: logger >> "Marking as invalid - rwt is invald" self.valid = 0 if self.valid: self.rot = self.valobj.CreateValueFromData( - "rot", lldb.SBData.CreateDataFromUInt64Array( - self.sys_params.endianness, self.sys_params.pointer_size, [ - self.roPointer]), self.sys_params.types_cache.addr_ptr_type) -# self.rot = self.valobj.CreateValueFromAddress("rot",self.roPointer,self.sys_params.types_cache.addr_ptr_type).AddressOf() + "rot", + lldb.SBData.CreateDataFromUInt64Array( + self.sys_params.endianness, + self.sys_params.pointer_size, + [self.roPointer], + ), + self.sys_params.types_cache.addr_ptr_type, + ) + # self.rot = self.valobj.CreateValueFromAddress("rot",self.roPointer,self.sys_params.types_cache.addr_ptr_type).AddressOf() self.data = RoT_Data(self.rot, self.sys_params) # perform sanity checks on the contents of this class_rw_t def check_valid(self): logger = lldb.formatters.Logger.Logger() self.valid = 1 - if not( + if not ( Utilities.is_valid_pointer( - self.roPointer, - self.sys_params.pointer_size, - allow_tagged=0)): + self.roPointer, self.sys_params.pointer_size, allow_tagged=0 + ) + ): logger >> "Marking as invalid - ropointer is invalid" self.valid = 0 def __str__(self): logger = lldb.formatters.Logger.Logger() - return \ - "roPointer = " + hex(self.roPointer) + return "roPointer = " + hex(self.roPointer) def is_valid(self): logger = lldb.formatters.Logger.Logger() @@ -225,11 +238,13 @@ class Class_Data_V2: - def __init__(self, isa_pointer, params): logger = lldb.formatters.Logger.Logger() - if (isa_pointer is not None) and (Utilities.is_valid_pointer( - isa_pointer.GetValueAsUnsigned(), params.pointer_size, allow_tagged=0)): + if (isa_pointer is not None) and ( + Utilities.is_valid_pointer( + isa_pointer.GetValueAsUnsigned(), params.pointer_size, allow_tagged=0 + ) + ): self.sys_params = params self.valobj = isa_pointer self.check_valid() @@ -238,10 +253,15 @@ self.valid = 0 if self.valid: self.rwt = self.valobj.CreateValueFromData( - "rwt", lldb.SBData.CreateDataFromUInt64Array( - self.sys_params.endianness, self.sys_params.pointer_size, [ - self.dataPointer]), self.sys_params.types_cache.addr_ptr_type) -# self.rwt = self.valobj.CreateValueFromAddress("rwt",self.dataPointer,self.sys_params.types_cache.addr_ptr_type).AddressOf() + "rwt", + lldb.SBData.CreateDataFromUInt64Array( + self.sys_params.endianness, + self.sys_params.pointer_size, + [self.dataPointer], + ), + self.sys_params.types_cache.addr_ptr_type, + ) + # self.rwt = self.valobj.CreateValueFromAddress("rwt",self.dataPointer,self.sys_params.types_cache.addr_ptr_type).AddressOf() self.data = RwT_Data(self.rwt, self.sys_params) # perform sanity checks on the contents of this class_t @@ -252,16 +272,17 @@ self.valid = 1 self.isaPointer = Utilities.read_child_of( - self.valobj, 0, self.sys_params.types_cache.addr_ptr_type) - if not( + self.valobj, 0, self.sys_params.types_cache.addr_ptr_type + ) + if not ( Utilities.is_valid_pointer( - self.isaPointer, - self.sys_params.pointer_size, - allow_tagged=0)): + self.isaPointer, self.sys_params.pointer_size, allow_tagged=0 + ) + ): logger >> "Marking as invalid - isaPointer is invalid" self.valid = 0 return - if not(Utilities.is_allowed_pointer(self.isaPointer)): + if not (Utilities.is_allowed_pointer(self.isaPointer)): logger >> "Marking as invalid - isaPointer is not allowed" self.valid = 0 return @@ -269,32 +290,34 @@ self.cachePointer = Utilities.read_child_of( self.valobj, 2 * self.sys_params.pointer_size, - self.sys_params.types_cache.addr_ptr_type) - if not( + self.sys_params.types_cache.addr_ptr_type, + ) + if not ( Utilities.is_valid_pointer( - self.cachePointer, - self.sys_params.pointer_size, - allow_tagged=0)): + self.cachePointer, self.sys_params.pointer_size, allow_tagged=0 + ) + ): logger >> "Marking as invalid - cachePointer is invalid" self.valid = 0 return - if not(Utilities.is_allowed_pointer(self.cachePointer)): + if not (Utilities.is_allowed_pointer(self.cachePointer)): logger >> "Marking as invalid - cachePointer is not allowed" self.valid = 0 return self.dataPointer = Utilities.read_child_of( self.valobj, 4 * self.sys_params.pointer_size, - self.sys_params.types_cache.addr_ptr_type) - if not( + self.sys_params.types_cache.addr_ptr_type, + ) + if not ( Utilities.is_valid_pointer( - self.dataPointer, - self.sys_params.pointer_size, - allow_tagged=0)): + self.dataPointer, self.sys_params.pointer_size, allow_tagged=0 + ) + ): logger >> "Marking as invalid - dataPointer is invalid" self.valid = 0 return - if not(Utilities.is_allowed_pointer(self.dataPointer)): + if not (Utilities.is_allowed_pointer(self.dataPointer)): logger >> "Marking as invalid - dataPointer is not allowed" self.valid = 0 return @@ -302,17 +325,20 @@ self.superclassIsaPointer = Utilities.read_child_of( self.valobj, 1 * self.sys_params.pointer_size, - self.sys_params.types_cache.addr_ptr_type) - if not( + self.sys_params.types_cache.addr_ptr_type, + ) + if not ( Utilities.is_valid_pointer( self.superclassIsaPointer, self.sys_params.pointer_size, allow_tagged=0, - allow_NULL=1)): + allow_NULL=1, + ) + ): logger >> "Marking as invalid - superclassIsa is invalid" self.valid = 0 return - if not(Utilities.is_allowed_pointer(self.superclassIsaPointer)): + if not (Utilities.is_allowed_pointer(self.superclassIsaPointer)): logger >> "Marking as invalid - superclassIsa is not allowed" self.valid = 0 return @@ -335,13 +361,16 @@ def is_cftype(self): logger = lldb.formatters.Logger.Logger() if self.is_valid(): - return self.class_name() == '__NSCFType' or self.class_name() == 'NSCFType' + return self.class_name() == "__NSCFType" or self.class_name() == "NSCFType" def get_superclass(self): logger = lldb.formatters.Logger.Logger() if self.is_valid(): parent_isa_pointer = self.valobj.CreateChildAtOffset( - "parent_isa", self.sys_params.pointer_size, self.sys_params.addr_ptr_type) + "parent_isa", + self.sys_params.pointer_size, + self.sys_params.addr_ptr_type, + ) return Class_Data_V2(parent_isa_pointer, self.sys_params) else: return None @@ -361,10 +390,19 @@ def __str__(self): logger = lldb.formatters.Logger.Logger() - return 'isaPointer = ' + hex(self.isaPointer) + "\n" + \ - "superclassIsaPointer = " + hex(self.superclassIsaPointer) + "\n" + \ - "cachePointer = " + hex(self.cachePointer) + "\n" + \ - "data = " + hex(self.dataPointer) + return ( + "isaPointer = " + + hex(self.isaPointer) + + "\n" + + "superclassIsaPointer = " + + hex(self.superclassIsaPointer) + + "\n" + + "cachePointer = " + + hex(self.cachePointer) + + "\n" + + "data = " + + hex(self.dataPointer) + ) def is_tagged(self): return 0 @@ -375,16 +413,19 @@ return None return self.rwt.rot.instance_size(align) + # runtime v1 is much less intricate than v2 and stores relevant # information directly in the class_t object class Class_Data_V1: - def __init__(self, isa_pointer, params): logger = lldb.formatters.Logger.Logger() - if (isa_pointer is not None) and (Utilities.is_valid_pointer( - isa_pointer.GetValueAsUnsigned(), params.pointer_size, allow_tagged=0)): + if (isa_pointer is not None) and ( + Utilities.is_valid_pointer( + isa_pointer.GetValueAsUnsigned(), params.pointer_size, allow_tagged=0 + ) + ): self.valid = 1 self.sys_params = params self.valobj = isa_pointer @@ -394,8 +435,9 @@ self.valid = 0 if self.valid: self.name = Utilities.read_ascii( - self.valobj.GetTarget().GetProcess(), self.namePointer) - if not(Utilities.is_valid_identifier(self.name)): + self.valobj.GetTarget().GetProcess(), self.namePointer + ) + if not (Utilities.is_valid_identifier(self.name)): logger >> "Marking as invalid - name is not valid" self.valid = 0 @@ -405,12 +447,13 @@ self.valid = 1 self.isaPointer = Utilities.read_child_of( - self.valobj, 0, self.sys_params.types_cache.addr_ptr_type) - if not( + self.valobj, 0, self.sys_params.types_cache.addr_ptr_type + ) + if not ( Utilities.is_valid_pointer( - self.isaPointer, - self.sys_params.pointer_size, - allow_tagged=0)): + self.isaPointer, self.sys_params.pointer_size, allow_tagged=0 + ) + ): logger >> "Marking as invalid - isaPointer is invalid" self.valid = 0 return @@ -418,13 +461,16 @@ self.superclassIsaPointer = Utilities.read_child_of( self.valobj, 1 * self.sys_params.pointer_size, - self.sys_params.types_cache.addr_ptr_type) - if not( + self.sys_params.types_cache.addr_ptr_type, + ) + if not ( Utilities.is_valid_pointer( self.superclassIsaPointer, self.sys_params.pointer_size, allow_tagged=0, - allow_NULL=1)): + allow_NULL=1, + ) + ): logger >> "Marking as invalid - superclassIsa is invalid" self.valid = 0 return @@ -432,10 +478,11 @@ self.namePointer = Utilities.read_child_of( self.valobj, 2 * self.sys_params.pointer_size, - self.sys_params.types_cache.addr_ptr_type) + self.sys_params.types_cache.addr_ptr_type, + ) # if not(Utilities.is_valid_pointer(self.namePointer,self.sys_params.pointer_size,allow_tagged=0,allow_NULL=0)): - # self.valid = 0 - # return + # self.valid = 0 + # return # in general, KVO is implemented by transparently subclassing # however, there could be exceptions where a class does something else @@ -455,13 +502,16 @@ def is_cftype(self): logger = lldb.formatters.Logger.Logger() if self.is_valid(): - return self.class_name() == '__NSCFType' or self.class_name() == 'NSCFType' + return self.class_name() == "__NSCFType" or self.class_name() == "NSCFType" def get_superclass(self): logger = lldb.formatters.Logger.Logger() if self.is_valid(): parent_isa_pointer = self.valobj.CreateChildAtOffset( - "parent_isa", self.sys_params.pointer_size, self.sys_params.addr_ptr_type) + "parent_isa", + self.sys_params.pointer_size, + self.sys_params.addr_ptr_type, + ) return Class_Data_V1(parent_isa_pointer, self.sys_params) else: return None @@ -478,10 +528,21 @@ def __str__(self): logger = lldb.formatters.Logger.Logger() - return 'isaPointer = ' + hex(self.isaPointer) + "\n" + \ - "superclassIsaPointer = " + hex(self.superclassIsaPointer) + "\n" + \ - "namePointer = " + hex(self.namePointer) + " --> " + self.name + \ - "instanceSize = " + hex(self.instanceSize()) + "\n" + return ( + "isaPointer = " + + hex(self.isaPointer) + + "\n" + + "superclassIsaPointer = " + + hex(self.superclassIsaPointer) + + "\n" + + "namePointer = " + + hex(self.namePointer) + + " --> " + + self.name + + "instanceSize = " + + hex(self.instanceSize()) + + "\n" + ) def is_tagged(self): return 0 @@ -494,7 +555,8 @@ self.instanceSize = Utilities.read_child_of( self.valobj, 5 * self.sys_params.pointer_size, - self.sys_params.types_cache.addr_ptr_type) + self.sys_params.types_cache.addr_ptr_type, + ) if align: unalign = self.instance_size(0) if self.sys_params.is_64_bit: @@ -504,23 +566,27 @@ else: return self.instanceSize + # these are the only tagged pointers values for current versions # of OSX - they might change in future OS releases, and no-one is # advised to rely on these values, or any of the bitmasking formulas # in TaggedClass_Data. doing otherwise is at your own risk -TaggedClass_Values_Lion = {1: 'NSNumber', - 5: 'NSManagedObject', - 6: 'NSDate', - 7: 'NSDateTS'} -TaggedClass_Values_NMOS = {0: 'NSAtom', - 3: 'NSNumber', - 4: 'NSDateTS', - 5: 'NSManagedObject', - 6: 'NSDate'} +TaggedClass_Values_Lion = { + 1: "NSNumber", + 5: "NSManagedObject", + 6: "NSDate", + 7: "NSDateTS", +} +TaggedClass_Values_NMOS = { + 0: "NSAtom", + 3: "NSNumber", + 4: "NSDateTS", + 5: "NSManagedObject", + 6: "NSDate", +} class TaggedClass_Data: - def __init__(self, pointer, params): logger = lldb.formatters.Logger.Logger() global TaggedClass_Values_Lion, TaggedClass_Values_NMOS @@ -586,7 +652,6 @@ class InvalidClass_Data: - def __init__(self): pass @@ -595,7 +660,6 @@ class Version: - def __init__(self, major, minor, release, build_string): self._major = major self._minor = minor @@ -620,21 +684,23 @@ build_string = property(get_build_string, None) def __lt__(self, other): - if (self.major < other.major): + if self.major < other.major: return 1 - if (self.minor < other.minor): + if self.minor < other.minor: return 1 - if (self.release < other.release): + if self.release < other.release: return 1 # build strings are not compared since they are heavily platform-dependent and might not always # be available return 0 def __eq__(self, other): - return (self.major == other.major) and \ - (self.minor == other.minor) and \ - (self.release == other.release) and \ - (self.build_string == other.build_string) + return ( + (self.major == other.major) + and (self.minor == other.minor) + and (self.release == other.release) + and (self.build_string == other.build_string) + ) # Python 2.6 doesn't have functools.total_ordering, so we have to implement # other comparators @@ -655,7 +721,6 @@ class SystemParameters: - def __init__(self, valobj): logger = lldb.formatters.Logger.Logger() self.adjust_for_architecture(valobj) @@ -689,12 +754,15 @@ self.types_cache = types_caches.get_value(self.pid) else: self.types_cache = lldb.formatters.attrib_fromdict.AttributesDictionary( - allow_reset=0) - self.types_cache.addr_type = valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedLong) + allow_reset=0 + ) + self.types_cache.addr_type = valobj.GetType().GetBasicType( + lldb.eBasicTypeUnsignedLong + ) self.types_cache.addr_ptr_type = self.types_cache.addr_type.GetPointerType() - self.types_cache.uint32_t = valobj.GetType( - ).GetBasicType(lldb.eBasicTypeUnsignedInt) + self.types_cache.uint32_t = valobj.GetType().GetBasicType( + lldb.eBasicTypeUnsignedInt + ) types_caches.add_item(self.pid, self.types_cache) if isa_caches.look_for_key(self.pid): @@ -706,9 +774,9 @@ def adjust_for_architecture(self, valobj): process = valobj.GetTarget().GetProcess() self.pointer_size = process.GetAddressByteSize() - self.is_64_bit = (self.pointer_size == 8) + self.is_64_bit = self.pointer_size == 8 self.endianness = process.GetByteOrder() - self.is_little = (self.endianness == lldb.eByteOrderLittle) + self.is_little = self.endianness == lldb.eByteOrderLittle self.cfruntime_size = 16 if self.is_64_bit else 8 # a simple helper function that makes it more explicit that one is calculating @@ -717,18 +785,12 @@ # you can pass that in and it will be taken into account (since padding may be different between # 32 and 64 bit versions, you can pass padding value for both, the right # one will be used) - def calculate_offset( - self, - num_pointers=0, - bytes_count=0, - padding32=0, - padding64=0): + def calculate_offset(self, num_pointers=0, bytes_count=0, padding32=0, padding64=0): value = bytes_count + num_pointers * self.pointer_size return value + padding64 if self.is_64_bit else value + padding32 class ObjCRuntime: - # the ObjC runtime has no explicit "version" field that we can use # instead, we discriminate v1 from v2 by looking for the presence # of a well-known section only present in v1 @@ -743,7 +805,7 @@ module_objc = None for idx in range(num_modules): module = target.GetModuleAtIndex(idx) - if module.GetFileSpec().GetFilename() == 'libobjc.A.dylib': + if module.GetFileSpec().GetFilename() == "libobjc.A.dylib": module_objc = module break if module_objc is None or module_objc.IsValid() == 0: @@ -753,7 +815,7 @@ section_objc = None for idx in range(num_sections): section = module.GetSectionAtIndex(idx) - if section.GetName() == '__OBJC': + if section.GetName() == "__OBJC": section_objc = section break if section_objc is not None and section_objc.IsValid(): @@ -780,20 +842,18 @@ def adjust_for_architecture(self): pass -# an ObjC pointer can either be tagged or must be aligned + # an ObjC pointer can either be tagged or must be aligned def is_tagged(self): logger = lldb.formatters.Logger.Logger() if self.valobj is None: return 0 - return ( + return Utilities.is_valid_pointer( + self.unsigned_value, self.sys_params.pointer_size, allow_tagged=1 + ) and not ( Utilities.is_valid_pointer( - self.unsigned_value, - self.sys_params.pointer_size, - allow_tagged=1) and not( - Utilities.is_valid_pointer( - self.unsigned_value, - self.sys_params.pointer_size, - allow_tagged=0))) + self.unsigned_value, self.sys_params.pointer_size, allow_tagged=0 + ) + ) def is_valid(self): logger = lldb.formatters.Logger.Logger() @@ -802,9 +862,8 @@ if self.valobj.IsInScope() == 0: return 0 return Utilities.is_valid_pointer( - self.unsigned_value, - self.sys_params.pointer_size, - allow_tagged=1) + self.unsigned_value, self.sys_params.pointer_size, allow_tagged=1 + ) def is_nil(self): return self.unsigned_value == 0 @@ -815,7 +874,8 @@ logger >> "using cached isa" return self.isa_value self.isa_pointer = self.valobj.CreateChildAtOffset( - "cfisa", 0, self.sys_params.types_cache.addr_ptr_type) + "cfisa", 0, self.sys_params.types_cache.addr_ptr_type + ) if self.isa_pointer is None or self.isa_pointer.IsValid() == 0: logger >> "invalid isa - bailing out" return None @@ -837,7 +897,8 @@ # but unless performance requires it, this seems a cleaner way # to tackle the task tentative_tagged = TaggedClass_Data( - self.unsigned_value, self.sys_params) + self.unsigned_value, self.sys_params + ) if tentative_tagged.is_valid(): logger >> "truly tagged" return tentative_tagged @@ -849,8 +910,7 @@ return InvalidClass_Data() if self.is_valid() == 0 or self.read_isa() is None: return InvalidClass_Data() - data = self.sys_params.isa_cache.get_value( - self.isa_value, default=None) + data = self.sys_params.isa_cache.get_value(self.isa_value, default=None) if data is not None: return data if self.sys_params.runtime_version == 2: @@ -860,22 +920,20 @@ if data is None: return InvalidClass_Data() if data.is_valid(): - self.sys_params.isa_cache.add_item( - self.isa_value, data, ok_to_replace=1) + self.sys_params.isa_cache.add_item(self.isa_value, data, ok_to_replace=1) return data + # these classes below can be used by the data formatters to provide a # consistent message that describes a given runtime-generated situation class SpecialSituation_Description: - def message(self): - return '' + return "" class InvalidPointer_Description(SpecialSituation_Description): - def __init__(self, nil): self.is_nil = nil @@ -883,19 +941,17 @@ if self.is_nil: return '@""' else: - return '' + return "" class InvalidISA_Description(SpecialSituation_Description): - def __init__(self): pass def message(self): - return '' + return "" class ThisIsZombie_Description(SpecialSituation_Description): - def message(self): - return '' + return "" diff --git a/lldb/examples/summaries/pysummary.py b/lldb/examples/summaries/pysummary.py --- a/lldb/examples/summaries/pysummary.py +++ b/lldb/examples/summaries/pysummary.py @@ -6,19 +6,25 @@ return "" refcnt = value.GetChildMemberWithName("ob_refcnt") expr = "(char*)PyString_AsString( (PyObject*)PyObject_Str( (PyObject*)0x%x) )" % ( - value.GetValueAsUnsigned(0)) + value.GetValueAsUnsigned(0) + ) expr_summary = value.target.EvaluateExpression( - expr, lldb.SBExpressionOptions()).GetSummary() + expr, lldb.SBExpressionOptions() + ).GetSummary() refcnt_value = "rc = %d" % (refcnt.GetValueAsUnsigned(0)) return "%s (%s)" % (expr_summary, refcnt_value) def __lldb_init_module(debugger, unused): debugger.HandleCommand( - "type summary add PyObject --python-function pysummary.pyobj_summary") + "type summary add PyObject --python-function pysummary.pyobj_summary" + ) debugger.HandleCommand( - "type summary add lldb_private::PythonObject -s ${var.m_py_obj%S}") + "type summary add lldb_private::PythonObject -s ${var.m_py_obj%S}" + ) debugger.HandleCommand( - "type summary add lldb_private::PythonDictionary -s ${var.m_py_obj%S}") + "type summary add lldb_private::PythonDictionary -s ${var.m_py_obj%S}" + ) debugger.HandleCommand( - "type summary add lldb_private::PythonString -s ${var.m_py_obj%S}") + "type summary add lldb_private::PythonString -s ${var.m_py_obj%S}" + ) diff --git a/lldb/examples/summaries/sp_cp.py b/lldb/examples/summaries/sp_cp.py --- a/lldb/examples/summaries/sp_cp.py +++ b/lldb/examples/summaries/sp_cp.py @@ -8,7 +8,6 @@ class SharedPtr_SyntheticChildrenProvider: - def __init__(self, valobj, dict): self.valobj = valobj self.update() @@ -28,20 +27,21 @@ def get_child_at_index(self, index): if index == 0: - return self.valobj.GetChildMemberWithName('_M_ptr') + return self.valobj.GetChildMemberWithName("_M_ptr") if index == 1: - return self.valobj.GetChildMemberWithName('_M_refcount').GetChildMemberWithName( - '_M_pi').GetChildMemberWithName('_M_use_count') + return ( + self.valobj.GetChildMemberWithName("_M_refcount") + .GetChildMemberWithName("_M_pi") + .GetChildMemberWithName("_M_use_count") + ) return None def SharedPtr_SummaryProvider(valobj, dict): - return 'use = ' + \ - str(valobj.GetChildMemberWithName("count").GetValueAsUnsigned()) + return "use = " + str(valobj.GetChildMemberWithName("count").GetValueAsUnsigned()) class ValueObjectSP_SyntheticChildrenProvider: - def __init__(self, valobj, dict): self.valobj = valobj self.update() @@ -61,24 +61,30 @@ def get_child_at_index(self, index): if index == 0: - return self.valobj.GetChildMemberWithName('ptr_') + return self.valobj.GetChildMemberWithName("ptr_") if index == 1: - return self.valobj.GetChildMemberWithName( - 'cntrl_').GetChildMemberWithName('shared_owners_') + return self.valobj.GetChildMemberWithName("cntrl_").GetChildMemberWithName( + "shared_owners_" + ) return None def ValueObjectSP_SummaryProvider(valobj, dict): - return 'use = ' + \ - str(1 + valobj.GetChildMemberWithName("count").GetValueAsUnsigned()) + return "use = " + str( + 1 + valobj.GetChildMemberWithName("count").GetValueAsUnsigned() + ) def __lldb_init_module(debugger, dict): debugger.HandleCommand( - 'type summary add -x ".*ValueObjectSP" --expand -F sp_cp.ValueObjectSP_SummaryProvider') + 'type summary add -x ".*ValueObjectSP" --expand -F sp_cp.ValueObjectSP_SummaryProvider' + ) debugger.HandleCommand( - 'type synthetic add -x ".*ValueObjectSP" -l sp_cp.ValueObjectSP_SyntheticChildrenProvider') + 'type synthetic add -x ".*ValueObjectSP" -l sp_cp.ValueObjectSP_SyntheticChildrenProvider' + ) debugger.HandleCommand( - 'type summary add -x ".*SP" --expand -F sp_cp.SharedPtr_SummaryProvider') + 'type summary add -x ".*SP" --expand -F sp_cp.SharedPtr_SummaryProvider' + ) debugger.HandleCommand( - 'type synthetic add -x ".*SP" -l sp_cp.SharedPtr_SyntheticChildrenProvider') + 'type synthetic add -x ".*SP" -l sp_cp.SharedPtr_SyntheticChildrenProvider' + ) diff --git a/lldb/examples/summaries/synth.py b/lldb/examples/summaries/synth.py --- a/lldb/examples/summaries/synth.py +++ b/lldb/examples/summaries/synth.py @@ -2,7 +2,6 @@ class PythonObjectSyntheticChildProvider(object): - def __init__(self, value, internal_dict): self.value = value self.values = self.make_children() @@ -34,18 +33,16 @@ data = None type = None if isinstance(value, int): - data = lldb.SBData.CreateDataFromUInt64Array( - self.bo, self.ps, [value]) + data = lldb.SBData.CreateDataFromUInt64Array(self.bo, self.ps, [value]) type = self.value.target.GetBasicType(lldb.eBasicTypeLong) elif isinstance(value, float): - data = lldb.SBData.CreateDataFromDoubleArray( - self.bo, self.ps, [value]) + data = lldb.SBData.CreateDataFromDoubleArray(self.bo, self.ps, [value]) type = self.value.target.GetBasicType(lldb.eBasicTypeDouble) elif isinstance(value, str): data = lldb.SBData.CreateDataFromCString(self.bo, self.ps, value) - type = self.value.target.GetBasicType( - lldb.eBasicTypeChar).GetArrayType( - len(value)) + type = self.value.target.GetBasicType(lldb.eBasicTypeChar).GetArrayType( + len(value) + ) if (data is not None) and (type is not None): return self.value.CreateValueFromData(name, data, type) return None diff --git a/lldb/examples/summaries/unicode_strings.py b/lldb/examples/summaries/unicode_strings.py --- a/lldb/examples/summaries/unicode_strings.py +++ b/lldb/examples/summaries/unicode_strings.py @@ -36,7 +36,7 @@ error = lldb.SBError() string_data = value.process.ReadMemory(pointer, length, error) # utf8 is safe to emit as-is on OSX - return '"%s"' % (string_data.decode('utf-16').encode('utf-8')) + return '"%s"' % (string_data.decode("utf-16").encode("utf-8")) def utf32_summary(value, unused): @@ -50,4 +50,4 @@ error = lldb.SBError() string_data = value.process.ReadMemory(pointer, length, error) # utf8 is safe to emit as-is on OSX - return '"%s"' % (string_data.decode('utf-32').encode('utf-8')) + return '"%s"' % (string_data.decode("utf-32").encode("utf-8")) diff --git a/lldb/examples/synthetic/bitfield/example.py b/lldb/examples/synthetic/bitfield/example.py --- a/lldb/examples/synthetic/bitfield/example.py +++ b/lldb/examples/synthetic/bitfield/example.py @@ -6,7 +6,6 @@ class MaskedData_SyntheticChildrenProvider: - def __init__(self, valobj, dict): # remember the SBValue since you will not have another chance to get it # :-) @@ -58,45 +57,48 @@ return self.valobj.GetChildMemberWithName("value") if index == 1: # fetch the value of the operator - op_chosen = self.valobj.GetChildMemberWithName( - "oper").GetValueAsUnsigned() + op_chosen = self.valobj.GetChildMemberWithName("oper").GetValueAsUnsigned() # if it is a known value, return a descriptive string for it # we are not doing this in the most efficient possible way, but the code is very readable # and easy to maintain - if you change the values on the C++ side, # the same changes must be made here if op_chosen == 0: return self.valobj.CreateValueFromExpression( - "operator", '(const char*)"none"') + "operator", '(const char*)"none"' + ) elif op_chosen == 1: return self.valobj.CreateValueFromExpression( - "operator", '(const char*)"AND"') + "operator", '(const char*)"AND"' + ) elif op_chosen == 2: return self.valobj.CreateValueFromExpression( - "operator", '(const char*)"OR"') + "operator", '(const char*)"OR"' + ) elif op_chosen == 3: return self.valobj.CreateValueFromExpression( - "operator", '(const char*)"XOR"') + "operator", '(const char*)"XOR"' + ) elif op_chosen == 4: return self.valobj.CreateValueFromExpression( - "operator", '(const char*)"NAND"') + "operator", '(const char*)"NAND"' + ) elif op_chosen == 5: return self.valobj.CreateValueFromExpression( - "operator", '(const char*)"NOR"') + "operator", '(const char*)"NOR"' + ) else: return self.valobj.CreateValueFromExpression( - "operator", '(const char*)"unknown"') # something else + "operator", '(const char*)"unknown"' + ) # something else if index == 2: return self.valobj.GetChildMemberWithName("mask") if index == 3: # for this, we must fetch all the other elements # in an efficient implementation, we would be caching this data for # efficiency - value = self.valobj.GetChildMemberWithName( - "value").GetValueAsUnsigned() - operator = self.valobj.GetChildMemberWithName( - "oper").GetValueAsUnsigned() - mask = self.valobj.GetChildMemberWithName( - "mask").GetValueAsUnsigned() + value = self.valobj.GetChildMemberWithName("value").GetValueAsUnsigned() + operator = self.valobj.GetChildMemberWithName("oper").GetValueAsUnsigned() + mask = self.valobj.GetChildMemberWithName("mask").GetValueAsUnsigned() # compute the masked value according to the operator if operator == 1: value = value & mask @@ -110,12 +112,15 @@ value = ~(value | mask) else: pass - value &= 0xFFFFFFFF # make sure Python does not extend our values to 64-bits + value &= ( + 0xFFFFFFFF # make sure Python does not extend our values to 64-bits + ) # return it - again, not the most efficient possible way. we should actually be pushing the computed value # into an SBData, and using the SBData to create an SBValue - this # has the advantage of readability return self.valobj.CreateValueFromExpression( - "apply()", '(uint32_t)(' + str(value) + ')') + "apply()", "(uint32_t)(" + str(value) + ")" + ) def update(self): # we do not do anything special in update - but this would be the right place to lookup diff --git a/lldb/examples/synthetic/gnu_libstdcpp.py b/lldb/examples/synthetic/gnu_libstdcpp.py --- a/lldb/examples/synthetic/gnu_libstdcpp.py +++ b/lldb/examples/synthetic/gnu_libstdcpp.py @@ -5,6 +5,7 @@ # implementation for your platform before relying on these formatters to do the right # thing for your setup + def ForwardListSummaryProvider(valobj, dict): list_capping_size = valobj.GetTarget().GetMaximumNumberOfChildrenToDisplay() text = "size=" + str(valobj.GetNumChildren()) @@ -13,6 +14,7 @@ else: return text + def StdOptionalSummaryProvider(valobj, dict): has_value = valobj.GetNumChildren() > 0 # We add wrapping spaces for consistency with the libcxx formatter @@ -25,14 +27,16 @@ def update(self): try: - self.payload = self.valobj.GetChildMemberWithName('_M_payload') - self.value = self.payload.GetChildMemberWithName('_M_payload') - self.has_value = self.payload.GetChildMemberWithName('_M_engaged').GetValueAsUnsigned(0) != 0 + self.payload = self.valobj.GetChildMemberWithName("_M_payload") + self.value = self.payload.GetChildMemberWithName("_M_payload") + self.has_value = ( + self.payload.GetChildMemberWithName("_M_engaged").GetValueAsUnsigned(0) + != 0 + ) except: self.has_value = False return False - def num_children(self): return 1 if self.has_value else 0 @@ -41,15 +45,18 @@ def get_child_at_index(self, index): # some versions of libstdcpp have an additional _M_value child with the actual value - possible_value = self.value.GetChildMemberWithName('_M_value') + possible_value = self.value.GetChildMemberWithName("_M_value") if possible_value.IsValid(): - return possible_value.Clone('Value') - return self.value.Clone('Value') + return possible_value.Clone("Value") + return self.value.Clone("Value") + """ This formatter can be applied to all unordered map-like structures (unordered_map, unordered_multimap, unordered_set, unordered_multiset) """ + + class StdUnorderedMapSynthProvider: def __init__(self, valobj, dict): self.valobj = valobj @@ -76,9 +83,9 @@ # later self.count = None try: - self.head = self.valobj.GetChildMemberWithName('_M_h') - self.before_begin = self.head.GetChildMemberWithName('_M_before_begin') - self.next = self.before_begin.GetChildMemberWithName('_M_nxt') + self.head = self.valobj.GetChildMemberWithName("_M_h") + self.before_begin = self.head.GetChildMemberWithName("_M_before_begin") + self.next = self.before_begin.GetChildMemberWithName("_M_nxt") self.data_type = self.extract_type() self.skip_size = self.next.GetType().GetByteSize() self.data_size = self.data_type.GetByteSize() @@ -90,7 +97,7 @@ def get_child_index(self, name): try: - return int(name.lstrip('[').rstrip(']')) + return int(name.lstrip("[").rstrip("]")) except: return -1 @@ -105,9 +112,11 @@ offset = index current = self.next while offset > 0: - current = current.GetChildMemberWithName('_M_nxt') + current = current.GetChildMemberWithName("_M_nxt") offset = offset - 1 - return current.CreateChildAtOffset( '[' + str(index) + ']', self.skip_size, self.data_type) + return current.CreateChildAtOffset( + "[" + str(index) + "]", self.skip_size, self.data_type + ) except: logger >> "Cannot get child" @@ -121,7 +130,9 @@ def num_children_impl(self): logger = lldb.formatters.Logger.Logger() try: - count = self.head.GetChildMemberWithName('_M_element_count').GetValueAsUnsigned(0) + count = self.head.GetChildMemberWithName( + "_M_element_count" + ).GetValueAsUnsigned(0) return count except: logger >> "Could not determine the size" @@ -130,22 +141,25 @@ class AbstractListSynthProvider: def __init__(self, valobj, dict, has_prev): - ''' + """ :param valobj: The value object of the list :param dict: A dict with metadata provided by LLDB :param has_prev: Whether the list supports a 'prev' pointer besides a 'next' one - ''' + """ logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.count = None self.has_prev = has_prev - self.list_capping_size = self.valobj.GetTarget().GetMaximumNumberOfChildrenToDisplay() - logger >> "Providing synthetic children for a list named " + \ - str(valobj.GetName()) + self.list_capping_size = ( + self.valobj.GetTarget().GetMaximumNumberOfChildrenToDisplay() + ) + logger >> "Providing synthetic children for a list named " + str( + valobj.GetName() + ) def next_node(self, node): logger = lldb.formatters.Logger.Logger() - return node.GetChildMemberWithName('_M_next') + return node.GetChildMemberWithName("_M_next") def is_valid(self, node): logger = lldb.formatters.Logger.Logger() @@ -159,8 +173,7 @@ def value(self, node): logger = lldb.formatters.Logger.Logger() value = node.GetValueAsUnsigned() - logger >> "synthetic value for {}: {}".format( - str(self.valobj.GetName()), value) + logger >> "synthetic value for {}: {}".format(str(self.valobj.GetName()), value) return value # Floyd's cycle-finding algorithm @@ -178,8 +191,7 @@ slow_value = self.value(slow) fast1 = self.next_node(fast2) fast2 = self.next_node(fast1) - if self.value(fast1) == slow_value or self.value( - fast2) == slow_value: + if self.value(fast1) == slow_value or self.value(fast2) == slow_value: return True slow = self.next_node(slow) return False @@ -188,7 +200,7 @@ logger = lldb.formatters.Logger.Logger() if self.count is None: # libstdc++ 6.0.21 added dedicated count field. - count_child = self.node.GetChildMemberWithName('_M_data') + count_child = self.node.GetChildMemberWithName("_M_data") if count_child and count_child.IsValid(): self.count = count_child.GetValueAsUnsigned(0) if self.count is None: @@ -215,9 +227,11 @@ return 1 size = 1 current = self.next - while current.GetChildMemberWithName( - '_M_next').GetValueAsUnsigned(0) != self.get_end_of_list_address(): - current = current.GetChildMemberWithName('_M_next') + while ( + current.GetChildMemberWithName("_M_next").GetValueAsUnsigned(0) + != self.get_end_of_list_address() + ): + current = current.GetChildMemberWithName("_M_next") if not current.IsValid(): break size = size + 1 @@ -232,7 +246,7 @@ def get_child_index(self, name): logger = lldb.formatters.Logger.Logger() try: - return int(name.lstrip('[').rstrip(']')) + return int(name.lstrip("[").rstrip("]")) except: return -1 @@ -247,14 +261,15 @@ offset = index current = self.next while offset > 0: - current = current.GetChildMemberWithName('_M_next') + current = current.GetChildMemberWithName("_M_next") offset = offset - 1 # C++ lists store the data of a node after its pointers. In the case of a forward list, there's just one pointer (next), and # in the case of a double-linked list, there's an additional pointer (prev). return current.CreateChildAtOffset( - '[' + str(index) + ']', - (2 if self.has_prev else 1) * current.GetType().GetByteSize(), - self.data_type) + "[" + str(index) + "]", + (2 if self.has_prev else 1) * current.GetType().GetByteSize(), + self.data_type, + ) except: return None @@ -273,7 +288,7 @@ # later self.count = None try: - self.impl = self.valobj.GetChildMemberWithName('_M_impl') + self.impl = self.valobj.GetChildMemberWithName("_M_impl") self.data_type = self.extract_type() if (not self.data_type.IsValid()) or (not self.impl.IsValid()): self.count = 0 @@ -285,34 +300,35 @@ self.count = 0 return False - ''' + """ Method is used to extract the list pointers into the variables (e.g self.node, self.next, and optionally to self.prev) and is mandatory to be overriden in each AbstractListSynthProvider subclass. This should return True or False depending on wheter it found valid data. - ''' + """ + def updateNodes(self): raise NotImplementedError def has_children(self): return True - ''' + """ Method is used to identify if a node traversal has reached its end and is mandatory to be overriden in each AbstractListSynthProvider subclass - ''' + """ + def get_end_of_list_address(self): raise NotImplementedError class StdForwardListSynthProvider(AbstractListSynthProvider): - def __init__(self, valobj, dict): has_prev = False super().__init__(valobj, dict, has_prev) def updateNodes(self): - self.node = self.impl.GetChildMemberWithName('_M_head') - self.next = self.node.GetChildMemberWithName('_M_next') + self.node = self.impl.GetChildMemberWithName("_M_head") + self.next = self.node.GetChildMemberWithName("_M_next") if (not self.node.IsValid()) or (not self.next.IsValid()): return False return True @@ -322,17 +338,21 @@ class StdListSynthProvider(AbstractListSynthProvider): - def __init__(self, valobj, dict): has_prev = True super().__init__(valobj, dict, has_prev) def updateNodes(self): self.node_address = self.valobj.AddressOf().GetValueAsUnsigned(0) - self.node = self.impl.GetChildMemberWithName('_M_node') - self.prev = self.node.GetChildMemberWithName('_M_prev') - self.next = self.node.GetChildMemberWithName('_M_next') - if self.node_address == 0 or (not self.node.IsValid()) or (not self.next.IsValid()) or (not self.prev.IsValid()): + self.node = self.impl.GetChildMemberWithName("_M_node") + self.prev = self.node.GetChildMemberWithName("_M_prev") + self.next = self.node.GetChildMemberWithName("_M_next") + if ( + self.node_address == 0 + or (not self.node.IsValid()) + or (not self.next.IsValid()) + or (not self.prev.IsValid()) + ): return False return True @@ -341,9 +361,7 @@ class StdVectorSynthProvider: - class StdVectorImplementation(object): - def __init__(self, valobj): self.valobj = valobj self.count = None @@ -379,7 +397,7 @@ # this check might fail, unless the sizeof() we get is itself incremented to take the # padding bytes into account - on current clang it looks like # this is the case - num_children = (finish_val - start_val) + num_children = finish_val - start_val if (num_children % self.data_size) != 0: return 0 else: @@ -398,7 +416,8 @@ try: offset = index * self.data_size return self.start.CreateChildAtOffset( - '[' + str(index) + ']', offset, self.data_type) + "[" + str(index) + "]", offset, self.data_type + ) except: return None @@ -407,16 +426,20 @@ # mind later self.count = None try: - impl = self.valobj.GetChildMemberWithName('_M_impl') - self.start = impl.GetChildMemberWithName('_M_start') - self.finish = impl.GetChildMemberWithName('_M_finish') - self.end = impl.GetChildMemberWithName('_M_end_of_storage') + impl = self.valobj.GetChildMemberWithName("_M_impl") + self.start = impl.GetChildMemberWithName("_M_start") + self.finish = impl.GetChildMemberWithName("_M_finish") + self.end = impl.GetChildMemberWithName("_M_end_of_storage") self.data_type = self.start.GetType().GetPointeeType() self.data_size = self.data_type.GetByteSize() # if any of these objects is invalid, it means there is no # point in trying to fetch anything - if self.start.IsValid() and self.finish.IsValid( - ) and self.end.IsValid() and self.data_type.IsValid(): + if ( + self.start.IsValid() + and self.finish.IsValid() + and self.end.IsValid() + and self.data_type.IsValid() + ): self.count = None else: self.count = 0 @@ -425,7 +448,6 @@ return False class StdVBoolImplementation(object): - def __init__(self, valobj, bool_type): self.valobj = valobj self.bool_type = bool_type @@ -445,28 +467,31 @@ return None element_type = self.start_p.GetType().GetPointeeType() element_bits = 8 * element_type.GetByteSize() - element_offset = (index // element_bits) * \ - element_type.GetByteSize() + element_offset = (index // element_bits) * element_type.GetByteSize() bit_offset = index % element_bits element = self.start_p.CreateChildAtOffset( - '[' + str(index) + ']', element_offset, element_type) + "[" + str(index) + "]", element_offset, element_type + ) bit = element.GetValueAsUnsigned(0) & (1 << bit_offset) if bit != 0: value_expr = "(bool)true" else: value_expr = "(bool)false" - return self.valobj.CreateValueFromExpression( - "[%d]" % index, value_expr) + return self.valobj.CreateValueFromExpression("[%d]" % index, value_expr) def update(self): try: - m_impl = self.valobj.GetChildMemberWithName('_M_impl') - self.m_start = m_impl.GetChildMemberWithName('_M_start') - self.m_finish = m_impl.GetChildMemberWithName('_M_finish') - self.start_p = self.m_start.GetChildMemberWithName('_M_p') - self.finish_p = self.m_finish.GetChildMemberWithName('_M_p') - self.offset = self.m_finish.GetChildMemberWithName('_M_offset') - if self.offset.IsValid() and self.start_p.IsValid() and self.finish_p.IsValid(): + m_impl = self.valobj.GetChildMemberWithName("_M_impl") + self.m_start = m_impl.GetChildMemberWithName("_M_start") + self.m_finish = m_impl.GetChildMemberWithName("_M_finish") + self.start_p = self.m_start.GetChildMemberWithName("_M_p") + self.finish_p = self.m_finish.GetChildMemberWithName("_M_p") + self.offset = self.m_finish.GetChildMemberWithName("_M_offset") + if ( + self.offset.IsValid() + and self.start_p.IsValid() + and self.finish_p.IsValid() + ): self.valid = True else: self.valid = False @@ -478,19 +503,19 @@ logger = lldb.formatters.Logger.Logger() first_template_arg_type = valobj.GetType().GetTemplateArgumentType(0) if str(first_template_arg_type.GetName()) == "bool": - self.impl = self.StdVBoolImplementation( - valobj, first_template_arg_type) + self.impl = self.StdVBoolImplementation(valobj, first_template_arg_type) else: self.impl = self.StdVectorImplementation(valobj) - logger >> "Providing synthetic children for a vector named " + \ - str(valobj.GetName()) + logger >> "Providing synthetic children for a vector named " + str( + valobj.GetName() + ) def num_children(self): return self.impl.num_children() def get_child_index(self, name): try: - return int(name.lstrip('[').rstrip(']')) + return int(name.lstrip("[").rstrip("]")) except: return -1 @@ -507,21 +532,27 @@ This formatter can be applied to all map-like structures (map, multimap, set, multiset) """ -class StdMapLikeSynthProvider: + +class StdMapLikeSynthProvider: def __init__(self, valobj, dict): logger = lldb.formatters.Logger.Logger() self.valobj = valobj self.count = None self.kind = self.get_object_kind(valobj) - logger >> "Providing synthetic children for a " + self.kind + " named " + \ - str(valobj.GetName()) + ( + logger + >> "Providing synthetic children for a " + + self.kind + + " named " + + str(valobj.GetName()) + ) def get_object_kind(self, valobj): type_name = valobj.GetTypeName() for kind in ["multiset", "multimap", "set", "map"]: - if kind in type_name: - return kind + if kind in type_name: + return kind return type_name # we need this function as a temporary workaround for rdar://problem/10801549 @@ -533,14 +564,26 @@ # to find the type name def fixup_class_name(self, class_name): logger = lldb.formatters.Logger.Logger() - if class_name == 'std::basic_string, std::allocator >': - return 'std::basic_string', True - if class_name == 'basic_string, std::allocator >': - return 'std::basic_string', True - if class_name == 'std::basic_string, std::allocator >': - return 'std::basic_string', True - if class_name == 'basic_string, std::allocator >': - return 'std::basic_string', True + if ( + class_name + == "std::basic_string, std::allocator >" + ): + return "std::basic_string", True + if ( + class_name + == "basic_string, std::allocator >" + ): + return "std::basic_string", True + if ( + class_name + == "std::basic_string, std::allocator >" + ): + return "std::basic_string", True + if ( + class_name + == "basic_string, std::allocator >" + ): + return "std::basic_string", True return class_name, False def update(self): @@ -553,9 +596,9 @@ # if this gets set to True, then we will merrily return None for # any child from that moment on self.garbage = False - self.Mt = self.valobj.GetChildMemberWithName('_M_t') - self.Mimpl = self.Mt.GetChildMemberWithName('_M_impl') - self.Mheader = self.Mimpl.GetChildMemberWithName('_M_header') + self.Mt = self.valobj.GetChildMemberWithName("_M_t") + self.Mimpl = self.Mt.GetChildMemberWithName("_M_impl") + self.Mheader = self.Mimpl.GetChildMemberWithName("_M_header") if not self.Mheader.IsValid(): self.count = 0 else: @@ -572,11 +615,13 @@ # GCC does not emit DW_TAG_template_type_parameter for # std::allocator<...>. For such a case, get the type of # std::pair from a member of std::map. - rep_type = self.valobj.GetChildMemberWithName('_M_t').GetType() - self.data_type = rep_type.GetTypedefedType().GetTemplateArgumentType(1) + rep_type = self.valobj.GetChildMemberWithName("_M_t").GetType() + self.data_type = ( + rep_type.GetTypedefedType().GetTemplateArgumentType(1) + ) # from libstdc++ implementation of _M_root for rbtree - self.Mroot = self.Mheader.GetChildMemberWithName('_M_parent') + self.Mroot = self.Mheader.GetChildMemberWithName("_M_parent") self.data_size = self.data_type.GetByteSize() self.skip_size = self.Mheader.GetType().GetByteSize() except: @@ -596,7 +641,8 @@ if root_ptr_val == 0: return 0 count = self.Mimpl.GetChildMemberWithName( - '_M_node_count').GetValueAsUnsigned(0) + "_M_node_count" + ).GetValueAsUnsigned(0) logger >> "I have " + str(count) + " children available" return count except: @@ -605,7 +651,7 @@ def get_child_index(self, name): logger = lldb.formatters.Logger.Logger() try: - return int(name.lstrip('[').rstrip(']')) + return int(name.lstrip("[").rstrip("]")) except: return -1 @@ -627,7 +673,8 @@ offset = offset - 1 # skip all the base stuff and get at the data return current.CreateChildAtOffset( - '[' + str(index) + ']', self.skip_size, self.data_type) + "[" + str(index) + "]", self.skip_size, self.data_type + ) except: return None @@ -667,7 +714,7 @@ x = node y = self.parent(x) max_steps -= 1 - while(self.node_ptr_value(x) == self.node_ptr_value(self.right(y))): + while self.node_ptr_value(x) == self.node_ptr_value(self.right(y)): x = y y = self.parent(y) max_steps -= 1 @@ -682,8 +729,10 @@ def has_children(self): return True + _list_uses_loop_detector = True + class StdDequeSynthProvider: def __init__(self, valobj, d): self.valobj = valobj @@ -693,7 +742,6 @@ self.element_size = -1 self.find_block_size() - def find_block_size(self): # in order to use the deque we must have the block size, or else # it's impossible to know what memory addresses are valid @@ -707,7 +755,7 @@ # #define _GLIBCXX_DEQUE_BUF_SIZE 512 # # return (__size < _GLIBCXX_DEQUE_BUF_SIZE - # ? size_t(_GLIBCXX_DEQUE_BUF_SIZE / __size) : size_t(1)); + # ? size_t(_GLIBCXX_DEQUE_BUF_SIZE / __size) : size_t(1)); if self.element_size < 512: self.block_size = 512 // self.element_size else: @@ -723,7 +771,7 @@ def get_child_index(self, name): try: - return int(name.lstrip('[').rstrip(']')) + return int(name.lstrip("[").rstrip("]")) except: return -1 @@ -733,13 +781,15 @@ if index >= self.num_children(): return None try: - name = '[' + str(index) + ']' + name = "[" + str(index) + "]" # We first look for the element in the first subarray, # which might be incomplete. if index < self.first_node_size: # The following statement is valid because self.first_elem is the pointer # to the first element - return self.first_elem.CreateChildAtOffset(name, index * self.element_size, self.element_type) + return self.first_elem.CreateChildAtOffset( + name, index * self.element_size, self.element_type + ) # Now the rest of the subarrays except for maybe the last one # are going to be complete, so the final expression is simpler @@ -747,10 +797,13 @@ # We first move to the beginning of the node/subarray were our element is node = self.start_node.CreateChildAtOffset( - '', + "", (1 + i) * self.valobj.GetProcess().GetAddressByteSize(), - self.element_type.GetPointerType()) - return node.CreateChildAtOffset(name, j * self.element_size, self.element_type) + self.element_type.GetPointerType(), + ) + return node.CreateChildAtOffset( + name, j * self.element_size, self.element_type + ) except: return None @@ -774,42 +827,66 @@ count = 0 - impl = self.valobj.GetChildMemberWithName('_M_impl') + impl = self.valobj.GetChildMemberWithName("_M_impl") # we calculate the size of the first node (i.e. first internal array) - self.start = impl.GetChildMemberWithName('_M_start') - self.start_node = self.start.GetChildMemberWithName('_M_node') + self.start = impl.GetChildMemberWithName("_M_start") + self.start_node = self.start.GetChildMemberWithName("_M_node") first_node_address = self.start_node.GetValueAsUnsigned(0) - first_node_last_elem = self.start.GetChildMemberWithName('_M_last').GetValueAsUnsigned(0) - self.first_elem = self.start.GetChildMemberWithName('_M_cur') + first_node_last_elem = self.start.GetChildMemberWithName( + "_M_last" + ).GetValueAsUnsigned(0) + self.first_elem = self.start.GetChildMemberWithName("_M_cur") first_node_first_elem = self.first_elem.GetValueAsUnsigned(0) - - finish = impl.GetChildMemberWithName('_M_finish') - last_node_address = finish.GetChildMemberWithName('_M_node').GetValueAsUnsigned(0) - last_node_first_elem = finish.GetChildMemberWithName('_M_first').GetValueAsUnsigned(0) - last_node_last_elem = finish.GetChildMemberWithName('_M_cur').GetValueAsUnsigned(0) - - if first_node_first_elem == 0 or first_node_last_elem == 0 or first_node_first_elem > first_node_last_elem: + finish = impl.GetChildMemberWithName("_M_finish") + last_node_address = finish.GetChildMemberWithName( + "_M_node" + ).GetValueAsUnsigned(0) + last_node_first_elem = finish.GetChildMemberWithName( + "_M_first" + ).GetValueAsUnsigned(0) + last_node_last_elem = finish.GetChildMemberWithName( + "_M_cur" + ).GetValueAsUnsigned(0) + + if ( + first_node_first_elem == 0 + or first_node_last_elem == 0 + or first_node_first_elem > first_node_last_elem + ): return False - if last_node_first_elem == 0 or last_node_last_elem == 0 or last_node_first_elem > last_node_last_elem: + if ( + last_node_first_elem == 0 + or last_node_last_elem == 0 + or last_node_first_elem > last_node_last_elem + ): return False - if last_node_address == first_node_address: - self.first_node_size = (last_node_last_elem - first_node_first_elem) // self.element_size + self.first_node_size = ( + last_node_last_elem - first_node_first_elem + ) // self.element_size count += self.first_node_size else: - self.first_node_size = (first_node_last_elem - first_node_first_elem) // self.element_size + self.first_node_size = ( + first_node_last_elem - first_node_first_elem + ) // self.element_size count += self.first_node_size # we calculate the size of the last node - finish = impl.GetChildMemberWithName('_M_finish') - last_node_address = finish.GetChildMemberWithName('_M_node').GetValueAsUnsigned(0) - count += (last_node_last_elem - last_node_first_elem) // self.element_size + finish = impl.GetChildMemberWithName("_M_finish") + last_node_address = finish.GetChildMemberWithName( + "_M_node" + ).GetValueAsUnsigned(0) + count += ( + last_node_last_elem - last_node_first_elem + ) // self.element_size # we calculate the size of the intermediate nodes - num_intermediate_nodes = (last_node_address - first_node_address - 1) // self.valobj.GetProcess().GetAddressByteSize() + num_intermediate_nodes = ( + last_node_address - first_node_address - 1 + ) // self.valobj.GetProcess().GetAddressByteSize() count += self.block_size * num_intermediate_nodes self.count = count except: diff --git a/lldb/examples/synthetic/libcxx.py b/lldb/examples/synthetic/libcxx.py --- a/lldb/examples/synthetic/libcxx.py +++ b/lldb/examples/synthetic/libcxx.py @@ -15,7 +15,7 @@ def make_string(F, L): - strval = '' + strval = "" G = F.GetData().uint8 for X in range(L): V = G[X] @@ -24,6 +24,7 @@ strval = strval + chr(V % 256) return '"' + strval + '"' + # if we ever care about big-endian, these two functions might need to change @@ -32,7 +33,8 @@ def extract_short_size(value): - return ((value >> 1) % 256) + return (value >> 1) % 256 + # some of the members of libc++ std::string are anonymous or have internal names that convey # no external significance - we access them by index since this saves a name lookup that would add @@ -67,13 +69,12 @@ error = lldb.SBError() strval = data.GetString(error, 0) if error.Fail(): - return '' + return "" else: return '"' + strval + '"' class stdvector_SynthProvider: - def __init__(self, valobj, dict): logger = lldb.formatters.Logger.Logger() self.valobj = valobj @@ -97,7 +98,7 @@ if start_val >= finish_val: return 0 - num_children = (finish_val - start_val) + num_children = finish_val - start_val if (num_children % self.data_size) != 0: return 0 else: @@ -109,7 +110,7 @@ def get_child_index(self, name): logger = lldb.formatters.Logger.Logger() try: - return int(name.lstrip('[').rstrip(']')) + return int(name.lstrip("[").rstrip("]")) except: return -1 @@ -123,20 +124,22 @@ try: offset = index * self.data_size return self.start.CreateChildAtOffset( - '[' + str(index) + ']', offset, self.data_type) + "[" + str(index) + "]", offset, self.data_type + ) except: return None def update(self): logger = lldb.formatters.Logger.Logger() try: - self.start = self.valobj.GetChildMemberWithName('__begin_') - self.finish = self.valobj.GetChildMemberWithName('__end_') + self.start = self.valobj.GetChildMemberWithName("__begin_") + self.finish = self.valobj.GetChildMemberWithName("__end_") # the purpose of this field is unclear, but it is the only field whose type is clearly T* for a vector # if this ends up not being correct, we can use the APIs to get at # template arguments data_type_finder = self.valobj.GetChildMemberWithName( - '__end_cap_').GetChildMemberWithName('__first_') + "__end_cap_" + ).GetChildMemberWithName("__first_") self.data_type = data_type_finder.GetType().GetPointeeType() self.data_size = self.data_type.GetByteSize() except: @@ -145,28 +148,28 @@ def has_children(self): return True + # Just an example: the actual summary is produced by a summary string: # size=${svar%#} def stdvector_SummaryProvider(valobj, dict): prov = stdvector_SynthProvider(valobj, None) - return 'size=' + str(prov.num_children()) + return "size=" + str(prov.num_children()) class stdlist_entry: - def __init__(self, entry): logger = lldb.formatters.Logger.Logger() self.entry = entry def _next_impl(self): logger = lldb.formatters.Logger.Logger() - return stdlist_entry(self.entry.GetChildMemberWithName('__next_')) + return stdlist_entry(self.entry.GetChildMemberWithName("__next_")) def _prev_impl(self): logger = lldb.formatters.Logger.Logger() - return stdlist_entry(self.entry.GetChildMemberWithName('__prev_')) + return stdlist_entry(self.entry.GetChildMemberWithName("__prev_")) def _value_impl(self): logger = lldb.formatters.Logger.Logger() @@ -187,7 +190,6 @@ class stdlist_iterator: - def increment_node(self, node): logger = lldb.formatters.Logger.Logger() if node.is_null: @@ -206,7 +208,7 @@ def next(self): logger = lldb.formatters.Logger.Logger() node = self.increment_node(self.node) - if node is not None and node.sbvalue.IsValid() and not(node.is_null): + if node is not None and node.sbvalue.IsValid() and not (node.is_null): self.node = node return self.value() else: @@ -227,7 +229,6 @@ class stdlist_SynthProvider: - def __init__(self, valobj, dict): logger = lldb.formatters.Logger.Logger() self.valobj = valobj @@ -235,7 +236,7 @@ def next_node(self, node): logger = lldb.formatters.Logger.Logger() - return node.GetChildMemberWithName('__next_') + return node.GetChildMemberWithName("__next_") def value(self, node): logger = lldb.formatters.Logger.Logger() @@ -293,14 +294,14 @@ current = current.next if size > _list_capping_size: return _list_capping_size - return (size - 1) + return size - 1 except: return 0 def get_child_index(self, name): logger = lldb.formatters.Logger.Logger() try: - return int(name.lstrip('[').rstrip(']')) + return int(name.lstrip("[").rstrip("]")) except: return -1 @@ -317,10 +318,11 @@ # we do not return __value_ because then all our children would be named __value_ # we need to make a copy of __value__ with the right name - # unfortunate - obj = current.GetChildMemberWithName('__value_') + obj = current.GetChildMemberWithName("__value_") obj_data = obj.GetData() return self.valobj.CreateValueFromData( - '[' + str(index) + ']', obj_data, self.data_type) + "[" + str(index) + "]", obj_data, self.data_type + ) except: return None @@ -339,10 +341,10 @@ logger = lldb.formatters.Logger.Logger() self.count = None try: - impl = self.valobj.GetChildMemberWithName('__end_') + impl = self.valobj.GetChildMemberWithName("__end_") self.node_address = self.valobj.AddressOf().GetValueAsUnsigned(0) - self.head = impl.GetChildMemberWithName('__next_') - self.tail = impl.GetChildMemberWithName('__prev_') + self.head = impl.GetChildMemberWithName("__next_") + self.tail = impl.GetChildMemberWithName("__prev_") self.data_type = self.extract_type() self.data_size = self.data_type.GetByteSize() except: @@ -356,28 +358,25 @@ # size=${svar%#} def stdlist_SummaryProvider(valobj, dict): prov = stdlist_SynthProvider(valobj, None) - return 'size=' + str(prov.num_children()) + return "size=" + str(prov.num_children()) + # a tree node - this class makes the syntax in the actual iterator nicer # to read and maintain class stdmap_iterator_node: - def _left_impl(self): logger = lldb.formatters.Logger.Logger() - return stdmap_iterator_node( - self.node.GetChildMemberWithName("__left_")) + return stdmap_iterator_node(self.node.GetChildMemberWithName("__left_")) def _right_impl(self): logger = lldb.formatters.Logger.Logger() - return stdmap_iterator_node( - self.node.GetChildMemberWithName("__right_")) + return stdmap_iterator_node(self.node.GetChildMemberWithName("__right_")) def _parent_impl(self): logger = lldb.formatters.Logger.Logger() - return stdmap_iterator_node( - self.node.GetChildMemberWithName("__parent_")) + return stdmap_iterator_node(self.node.GetChildMemberWithName("__parent_")) def _value_impl(self): logger = lldb.formatters.Logger.Logger() @@ -402,17 +401,17 @@ is_null = property(_null_impl, None) sbvalue = property(_sbvalue_impl, None) + # a Python implementation of the tree iterator used by libc++ class stdmap_iterator: - def tree_min(self, x): logger = lldb.formatters.Logger.Logger() steps = 0 if x.is_null: return None - while (not x.left.is_null): + while not x.left.is_null: x = x.left steps += 1 if steps > self.max_count: @@ -424,7 +423,7 @@ logger = lldb.formatters.Logger.Logger() if x.is_null: return None - while (not x.right.is_null): + while not x.right.is_null: x = x.right return x @@ -441,7 +440,7 @@ if not node.right.is_null: return self.tree_min(node.right) steps = 0 - while (not self.tree_is_left_child(node)): + while not self.tree_is_left_child(node): steps += 1 if steps > self.max_count: logger >> "Returning None - we overflowed" @@ -462,7 +461,7 @@ def next(self): logger = lldb.formatters.Logger.Logger() node = self.increment_node(self.node) - if node is not None and node.sbvalue.IsValid() and not(node.is_null): + if node is not None and node.sbvalue.IsValid() and not (node.is_null): self.node = node return self.value() else: @@ -484,7 +483,6 @@ class stdmap_SynthProvider: - def __init__(self, valobj, dict): logger = lldb.formatters.Logger.Logger() self.valobj = valobj @@ -499,8 +497,8 @@ # if this gets set to True, then we will merrily return None for # any child from that moment on self.garbage = False - self.tree = self.valobj.GetChildMemberWithName('__tree_') - self.root_node = self.tree.GetChildMemberWithName('__begin_node_') + self.tree = self.valobj.GetChildMemberWithName("__tree_") + self.root_node = self.tree.GetChildMemberWithName("__begin_node_") # this data is either lazily-calculated, or cannot be inferred at this moment # we still need to mark it as None, meaning "please set me ASAP" self.data_type = None @@ -521,8 +519,12 @@ def num_children_impl(self): logger = lldb.formatters.Logger.Logger() try: - return self.valobj.GetChildMemberWithName('__tree_').GetChildMemberWithName( - '__pair3_').GetChildMemberWithName('__first_').GetValueAsUnsigned() + return ( + self.valobj.GetChildMemberWithName("__tree_") + .GetChildMemberWithName("__pair3_") + .GetChildMemberWithName("__first_") + .GetValueAsUnsigned() + ) except: return 0 @@ -535,10 +537,10 @@ if self.num_children() == 0: return False deref = self.root_node.Dereference() - if not(deref.IsValid()): + if not (deref.IsValid()): return False - value = deref.GetChildMemberWithName('__value_') - if not(value.IsValid()): + value = deref.GetChildMemberWithName("__value_") + if not (value.IsValid()): return False self.data_type = value.GetType() self.data_size = self.data_type.GetByteSize() @@ -554,15 +556,15 @@ fields_count = node_type.GetNumberOfFields() for i in range(fields_count): field = node_type.GetFieldAtIndex(i) - if field.GetName() == '__value_': + if field.GetName() == "__value_": self.skip_size = field.GetOffsetInBytes() break - return (self.skip_size is not None) + return self.skip_size is not None def get_child_index(self, name): logger = lldb.formatters.Logger.Logger() try: - return int(name.lstrip('[').rstrip(']')) + return int(name.lstrip("[").rstrip("]")) except: return -1 @@ -577,60 +579,70 @@ logger >> "Returning None since this tree is garbage" return None try: - iterator = stdmap_iterator( - self.root_node, max_count=self.num_children()) + iterator = stdmap_iterator(self.root_node, max_count=self.num_children()) # the debug info for libc++ std::map is such that __begin_node_ has a very nice and useful type # out of which we can grab the information we need - every other node has a less informative # type which omits all value information and only contains housekeeping information for the RB tree # hence, we need to know if we are at a node != 0, so that we can # still get at the data - need_to_skip = (index > 0) + need_to_skip = index > 0 current = iterator.advance(index) if current is None: logger >> "Tree is garbage - returning None" self.garbage = True return None if self.get_data_type(): - if not(need_to_skip): + if not (need_to_skip): current = current.Dereference() - obj = current.GetChildMemberWithName('__value_') + obj = current.GetChildMemberWithName("__value_") obj_data = obj.GetData() # make sure we have a valid offset for the next items self.get_value_offset(current) # we do not return __value_ because then we would end up with a child named # __value_ instead of [0] return self.valobj.CreateValueFromData( - '[' + str(index) + ']', obj_data, self.data_type) + "[" + str(index) + "]", obj_data, self.data_type + ) else: # FIXME we need to have accessed item 0 before accessing # any other item! if self.skip_size is None: - logger >> "You asked for item > 0 before asking for item == 0, I will fetch 0 now then retry" + ( + logger + >> "You asked for item > 0 before asking for item == 0, I will fetch 0 now then retry" + ) if self.get_child_at_index(0): return self.get_child_at_index(index) else: - logger >> "item == 0 could not be found. sorry, nothing can be done here." + ( + logger + >> "item == 0 could not be found. sorry, nothing can be done here." + ) return None return current.CreateChildAtOffset( - '[' + str(index) + ']', self.skip_size, self.data_type) + "[" + str(index) + "]", self.skip_size, self.data_type + ) else: - logger >> "Unable to infer data-type - returning None (should mark tree as garbage here?)" + ( + logger + >> "Unable to infer data-type - returning None (should mark tree as garbage here?)" + ) return None except Exception as err: logger >> "Hit an exception: " + str(err) return None + # Just an example: the actual summary is produced by a summary string: # size=${svar%#} def stdmap_SummaryProvider(valobj, dict): prov = stdmap_SynthProvider(valobj, None) - return 'size=' + str(prov.num_children()) + return "size=" + str(prov.num_children()) class stddeque_SynthProvider: - def __init__(self, valobj, d): logger = lldb.formatters.Logger.Logger() logger.write("init") @@ -643,8 +655,8 @@ self.block_size = -1 self.element_size = -1 logger.write( - "block_size=%d, element_size=%d" % - (self.block_size, self.element_size)) + "block_size=%d, element_size=%d" % (self.block_size, self.element_size) + ) def find_block_size(self): # in order to use the deque we must have the block size, or else @@ -678,7 +690,7 @@ def get_child_index(self, name): logger = lldb.formatters.Logger.Logger() try: - return int(name.lstrip('[').rstrip(']')) + return int(name.lstrip("[").rstrip("]")) except: return -1 @@ -693,8 +705,9 @@ i, j = divmod(self.start + index, self.block_size) return self.first.CreateValueFromExpression( - '[' + str(index) + ']', '*(*(%s + %d) + %d)' % - (self.map_begin.get_expr_path(), i, j)) + "[" + str(index) + "]", + "*(*(%s + %d) + %d)" % (self.map_begin.get_expr_path(), i, j), + ) except: return None @@ -722,30 +735,28 @@ # one, and the 'size' element gives the number of elements # in the deque. count = self._get_value_of_compressed_pair( - self.valobj.GetChildMemberWithName('__size_')) + self.valobj.GetChildMemberWithName("__size_") + ) # give up now if we cant access memory reliably if self.block_size < 0: logger.write("block_size < 0") return - map_ = self.valobj.GetChildMemberWithName('__map_') - start = self.valobj.GetChildMemberWithName( - '__start_').GetValueAsUnsigned(0) - first = map_.GetChildMemberWithName('__first_') + map_ = self.valobj.GetChildMemberWithName("__map_") + start = self.valobj.GetChildMemberWithName("__start_").GetValueAsUnsigned(0) + first = map_.GetChildMemberWithName("__first_") map_first = first.GetValueAsUnsigned(0) - self.map_begin = map_.GetChildMemberWithName( - '__begin_') + self.map_begin = map_.GetChildMemberWithName("__begin_") map_begin = self.map_begin.GetValueAsUnsigned(0) - map_end = map_.GetChildMemberWithName( - '__end_').GetValueAsUnsigned(0) + map_end = map_.GetChildMemberWithName("__end_").GetValueAsUnsigned(0) map_endcap = self._get_value_of_compressed_pair( - map_.GetChildMemberWithName( '__end_cap_')) + map_.GetChildMemberWithName("__end_cap_") + ) # check consistency if not map_first <= map_begin <= map_end <= map_endcap: logger.write("map pointers are not monotonic") return - total_rows, junk = divmod( - map_endcap - map_first, self.pointer_size) + total_rows, junk = divmod(map_endcap - map_first, self.pointer_size) if junk: logger.write("endcap-first doesnt align correctly") return @@ -759,8 +770,8 @@ return logger.write( - "update success: count=%r, start=%r, first=%r" % - (count, start, first)) + "update success: count=%r, start=%r, first=%r" % (count, start, first) + ) # if consistent, save all we really need: self.count = count self.start = start @@ -774,12 +785,11 @@ class stdsharedptr_SynthProvider: - def __init__(self, valobj, d): logger = lldb.formatters.Logger.Logger() logger.write("init") self.valobj = valobj - #self.element_ptr_type = self.valobj.GetType().GetTemplateArgumentType(0).GetPointerType() + # self.element_ptr_type = self.valobj.GetType().GetTemplateArgumentType(0).GetPointerType() self.ptr = None self.cntrl = None process = valobj.GetProcess() @@ -809,32 +819,50 @@ if self.cntrl is None: count = 0 else: - count = 1 + \ - self.cntrl.GetChildMemberWithName('__shared_owners_').GetValueAsSigned() + count = ( + 1 + + self.cntrl.GetChildMemberWithName( + "__shared_owners_" + ).GetValueAsSigned() + ) return self.valobj.CreateValueFromData( - "count", lldb.SBData.CreateDataFromUInt64Array( - self.endianness, self.pointer_size, [count]), self.count_type) + "count", + lldb.SBData.CreateDataFromUInt64Array( + self.endianness, self.pointer_size, [count] + ), + self.count_type, + ) if index == 2: if self.cntrl is None: count = 0 else: - count = 1 + \ - self.cntrl.GetChildMemberWithName('__shared_weak_owners_').GetValueAsSigned() + count = ( + 1 + + self.cntrl.GetChildMemberWithName( + "__shared_weak_owners_" + ).GetValueAsSigned() + ) return self.valobj.CreateValueFromData( - "weak_count", lldb.SBData.CreateDataFromUInt64Array( - self.endianness, self.pointer_size, [count]), self.count_type) + "weak_count", + lldb.SBData.CreateDataFromUInt64Array( + self.endianness, self.pointer_size, [count] + ), + self.count_type, + ) return None def update(self): logger = lldb.formatters.Logger.Logger() self.ptr = self.valobj.GetChildMemberWithName( - '__ptr_') # .Cast(self.element_ptr_type) - cntrl = self.valobj.GetChildMemberWithName('__cntrl_') + "__ptr_" + ) # .Cast(self.element_ptr_type) + cntrl = self.valobj.GetChildMemberWithName("__cntrl_") if cntrl.GetValueAsUnsigned(0): self.cntrl = cntrl.Dereference() else: self.cntrl = None + # we can use two different categories for old and new formatters - type names are different enough that we should make no confusion # talking with libc++ developer: "std::__1::class_name is set in stone # until we decide to change the ABI. That shouldn't happen within a 5 year @@ -843,29 +871,41 @@ def __lldb_init_module(debugger, dict): debugger.HandleCommand( - 'type summary add -F libcxx.stdstring_SummaryProvider "std::__1::string" -w libcxx') + 'type summary add -F libcxx.stdstring_SummaryProvider "std::__1::string" -w libcxx' + ) debugger.HandleCommand( - 'type summary add -F libcxx.stdstring_SummaryProvider "std::__1::basic_string, class std::__1::allocator >" -w libcxx') + 'type summary add -F libcxx.stdstring_SummaryProvider "std::__1::basic_string, class std::__1::allocator >" -w libcxx' + ) debugger.HandleCommand( - 'type synthetic add -l libcxx.stdvector_SynthProvider -x "^(std::__1::)vector<.+>$" -w libcxx') + 'type synthetic add -l libcxx.stdvector_SynthProvider -x "^(std::__1::)vector<.+>$" -w libcxx' + ) debugger.HandleCommand( - 'type summary add -F libcxx.stdvector_SummaryProvider -e -x "^(std::__1::)vector<.+>$" -w libcxx') + 'type summary add -F libcxx.stdvector_SummaryProvider -e -x "^(std::__1::)vector<.+>$" -w libcxx' + ) debugger.HandleCommand( - 'type synthetic add -l libcxx.stdlist_SynthProvider -x "^(std::__1::)list<.+>$" -w libcxx') + 'type synthetic add -l libcxx.stdlist_SynthProvider -x "^(std::__1::)list<.+>$" -w libcxx' + ) debugger.HandleCommand( - 'type summary add -F libcxx.stdlist_SummaryProvider -e -x "^(std::__1::)list<.+>$" -w libcxx') + 'type summary add -F libcxx.stdlist_SummaryProvider -e -x "^(std::__1::)list<.+>$" -w libcxx' + ) debugger.HandleCommand( - 'type synthetic add -l libcxx.stdmap_SynthProvider -x "^(std::__1::)map<.+> >$" -w libcxx') + 'type synthetic add -l libcxx.stdmap_SynthProvider -x "^(std::__1::)map<.+> >$" -w libcxx' + ) debugger.HandleCommand( - 'type summary add -F libcxx.stdmap_SummaryProvider -e -x "^(std::__1::)map<.+> >$" -w libcxx') + 'type summary add -F libcxx.stdmap_SummaryProvider -e -x "^(std::__1::)map<.+> >$" -w libcxx' + ) debugger.HandleCommand("type category enable libcxx") debugger.HandleCommand( - 'type synthetic add -l libcxx.stddeque_SynthProvider -x "^(std::__1::)deque<.+>$" -w libcxx') + 'type synthetic add -l libcxx.stddeque_SynthProvider -x "^(std::__1::)deque<.+>$" -w libcxx' + ) debugger.HandleCommand( - 'type synthetic add -l libcxx.stdsharedptr_SynthProvider -x "^(std::__1::)shared_ptr<.+>$" -w libcxx') + 'type synthetic add -l libcxx.stdsharedptr_SynthProvider -x "^(std::__1::)shared_ptr<.+>$" -w libcxx' + ) # turns out the structs look the same, so weak_ptr can be handled the same! debugger.HandleCommand( - 'type synthetic add -l libcxx.stdsharedptr_SynthProvider -x "^(std::__1::)weak_ptr<.+>$" -w libcxx') + 'type synthetic add -l libcxx.stdsharedptr_SynthProvider -x "^(std::__1::)weak_ptr<.+>$" -w libcxx' + ) + _map_capping_size = 255 _list_capping_size = 255 diff --git a/lldb/examples/synthetic/recognizer_function/example.py b/lldb/examples/synthetic/recognizer_function/example.py --- a/lldb/examples/synthetic/recognizer_function/example.py +++ b/lldb/examples/synthetic/recognizer_function/example.py @@ -7,57 +7,60 @@ import sys + def is_message_type(t, internal_dict): - for base in t.get_bases_array(): - if base.GetName() == "Message": - return True - return False + for base in t.get_bases_array(): + if base.GetName() == "Message": + return True + return False + def message_summary(value, internal_dict): - # Could have used a summary string as well. All the work is done by the child - # provider. - return "Message" + # Could have used a summary string as well. All the work is done by the child + # provider. + return "Message" + class MessageChildProvider: - def __init__(self, value, internal_dict): - self.value = value - self.synthetic_children = self._analyze_children(value) - - def has_children(self): - return self.num_children() > 0 - - def num_children(self): - return len(self.synthetic_children) - - def get_child_index(self, name): - for index, child in enumerate(self.synthetic_children): - if child.GetName() == name: - return index - return None - - def get_child_at_index(self, index): - return self.synthetic_children[index] - - def _rename_sbvalue(self, value): - # We want to display the field with its original name without a trailing - # underscore. So we create a new SBValue with the same type and address but - # a different name. - name = value.GetName() - assert name.endswith("_") - new_name = name[:-1] - return value.CreateValueFromAddress(new_name, value.GetLoadAddress(), - value.GetType()) - - def _analyze_children(self, value): - result = [] - for i in range(value.GetNumChildren()): - child = value.GetChildAtIndex(i) - child_name = child.GetName() - if child_name.startswith("_"): - continue # Internal field, skip - # Normal field. Check presence bit. - presence_bit = value.GetChildMemberWithName("_has_" + child_name) - if presence_bit.GetValueAsUnsigned() != 0: - result.append(self._rename_sbvalue(child)) - return result + def __init__(self, value, internal_dict): + self.value = value + self.synthetic_children = self._analyze_children(value) + + def has_children(self): + return self.num_children() > 0 + + def num_children(self): + return len(self.synthetic_children) + + def get_child_index(self, name): + for index, child in enumerate(self.synthetic_children): + if child.GetName() == name: + return index + return None + + def get_child_at_index(self, index): + return self.synthetic_children[index] + + def _rename_sbvalue(self, value): + # We want to display the field with its original name without a trailing + # underscore. So we create a new SBValue with the same type and address but + # a different name. + name = value.GetName() + assert name.endswith("_") + new_name = name[:-1] + return value.CreateValueFromAddress( + new_name, value.GetLoadAddress(), value.GetType() + ) + def _analyze_children(self, value): + result = [] + for i in range(value.GetNumChildren()): + child = value.GetChildAtIndex(i) + child_name = child.GetName() + if child_name.startswith("_"): + continue # Internal field, skip + # Normal field. Check presence bit. + presence_bit = value.GetChildMemberWithName("_has_" + child_name) + if presence_bit.GetValueAsUnsigned() != 0: + result.append(self._rename_sbvalue(child)) + return result diff --git a/lldb/examples/synthetic/unordered_multi.py b/lldb/examples/synthetic/unordered_multi.py --- a/lldb/examples/synthetic/unordered_multi.py +++ b/lldb/examples/synthetic/unordered_multi.py @@ -4,7 +4,6 @@ class libcxx_hash_table_SynthProvider: - def __init__(self, valobj, dict): self.valobj = valobj self.num_elements = None @@ -34,23 +33,38 @@ # # We will calculate other values about the map because they will be useful for the summary. # - table = self.valobj.GetChildMemberWithName('__table_') + table = self.valobj.GetChildMemberWithName("__table_") bl_ptr = table.GetChildMemberWithName( - '__bucket_list_').GetChildMemberWithName('__ptr_') + "__bucket_list_" + ).GetChildMemberWithName("__ptr_") self.bucket_array_ptr = bl_ptr.GetChildMemberWithName( - '__first_').GetValueAsUnsigned(0) - self.bucket_count = bl_ptr.GetChildMemberWithName('__second_').GetChildMemberWithName( - '__data_').GetChildMemberWithName('__first_').GetValueAsUnsigned(0) + "__first_" + ).GetValueAsUnsigned(0) + self.bucket_count = ( + bl_ptr.GetChildMemberWithName("__second_") + .GetChildMemberWithName("__data_") + .GetChildMemberWithName("__first_") + .GetValueAsUnsigned(0) + ) logger >> "Bucket count = %r" % self.bucket_count - self.begin_ptr = table.GetChildMemberWithName('__p1_').GetChildMemberWithName( - '__first_').GetChildMemberWithName('__next_') - - self.num_elements = table.GetChildMemberWithName( - '__p2_').GetChildMemberWithName('__first_').GetValueAsUnsigned(0) - self.max_load_factor = table.GetChildMemberWithName( - '__p3_').GetChildMemberWithName('__first_').GetValueAsUnsigned(0) + self.begin_ptr = ( + table.GetChildMemberWithName("__p1_") + .GetChildMemberWithName("__first_") + .GetChildMemberWithName("__next_") + ) + + self.num_elements = ( + table.GetChildMemberWithName("__p2_") + .GetChildMemberWithName("__first_") + .GetValueAsUnsigned(0) + ) + self.max_load_factor = ( + table.GetChildMemberWithName("__p3_") + .GetChildMemberWithName("__first_") + .GetValueAsUnsigned(0) + ) logger >> "Num elements = %r" % self.num_elements # save the pointers as we get them @@ -78,7 +92,7 @@ def get_child_index(self, name): logger = lldb.formatters.Logger.Logger() try: - return int(name.lstrip('[').rstrip(']')) + return int(name.lstrip("[").rstrip("]")) except: return -1 @@ -91,8 +105,7 @@ return None # extend - logger >> " : cache size starts with %d elements" % len( - self.elements_cache) + logger >> " : cache size starts with %d elements" % len(self.elements_cache) while index >= len(self.elements_cache): # if we hit the end before we get the index, give up: if not self.next_element: @@ -101,24 +114,23 @@ node = self.next_element.Dereference() - value = node.GetChildMemberWithName('__value_') - hash_value = node.GetChildMemberWithName( - '__hash_').GetValueAsUnsigned() + value = node.GetChildMemberWithName("__value_") + hash_value = node.GetChildMemberWithName("__hash_").GetValueAsUnsigned() self.elements_cache.append((value, hash_value)) - self.next_element = node.GetChildMemberWithName('__next_') + self.next_element = node.GetChildMemberWithName("__next_") if not self.next_element.GetValueAsUnsigned(0): self.next_element = None # hit the index! so we have the value - logger >> " : cache size ends with %d elements" % len( - self.elements_cache) + logger >> " : cache size ends with %d elements" % len(self.elements_cache) value, hash_value = self.elements_cache[index] return self.valobj.CreateValueFromData( - '[%d] ' % - (index, hash_value), value.GetData(), value.GetType()) + "[%d] " % (index, hash_value), value.GetData(), value.GetType() + ) def __lldb_init_module(debugger, dict): debugger.HandleCommand( - 'type synthetic add -l unordered_multi.libcxx_hash_table_SynthProvider -x "^(std::__1::)unordered_(multi)?(map|set)<.+> >$" -w libcxx') + 'type synthetic add -l unordered_multi.libcxx_hash_table_SynthProvider -x "^(std::__1::)unordered_(multi)?(map|set)<.+> >$" -w libcxx' + ) diff --git a/lldb/packages/Python/lldbsuite/__init__.py b/lldb/packages/Python/lldbsuite/__init__.py --- a/lldb/packages/Python/lldbsuite/__init__.py +++ b/lldb/packages/Python/lldbsuite/__init__.py @@ -7,10 +7,11 @@ def find_lldb_root(): lldb_root = os.path.realpath( - os.path.dirname(inspect.getfile(inspect.currentframe()))) + os.path.dirname(inspect.getfile(inspect.currentframe())) + ) while True: parent = os.path.dirname(lldb_root) - if parent == lldb_root: # dirname('/') == '/' + if parent == lldb_root: # dirname('/') == '/' raise Exception("use_lldb_suite_root.py not found") lldb_root = parent @@ -18,6 +19,7 @@ if os.path.isfile(test_path): return lldb_root + # lldbsuite.lldb_root refers to the root of the git/svn source checkout lldb_root = find_lldb_root() diff --git a/lldb/packages/Python/lldbsuite/support/encoded_file.py b/lldb/packages/Python/lldbsuite/support/encoded_file.py --- a/lldb/packages/Python/lldbsuite/support/encoded_file.py +++ b/lldb/packages/Python/lldbsuite/support/encoded_file.py @@ -19,24 +19,22 @@ s = s.decode(encoding, "replace") # Filter unreadable characters, Python 3 is stricter than python 2 about them. import re - s = re.sub(r'[^\x00-\x7f]',r' ',s) + + s = re.sub(r"[^\x00-\x7f]", r" ", s) return old_write(s) + return impl -''' + +""" Create a Text I/O file object that can be written to with either unicode strings or byte strings. -''' +""" def open( - file, - encoding, - mode='r', - buffering=-1, - errors=None, - newline=None, - closefd=True): + file, encoding, mode="r", buffering=-1, errors=None, newline=None, closefd=True +): wrapped_file = io.open( file, mode=mode, @@ -44,7 +42,8 @@ encoding=encoding, errors=errors, newline=newline, - closefd=closefd) - new_write = _encoded_write(getattr(wrapped_file, 'write'), encoding) - setattr(wrapped_file, 'write', new_write) + closefd=closefd, + ) + new_write = _encoded_write(getattr(wrapped_file, "write"), encoding) + setattr(wrapped_file, "write", new_write) return wrapped_file diff --git a/lldb/packages/Python/lldbsuite/support/funcutils.py b/lldb/packages/Python/lldbsuite/support/funcutils.py --- a/lldb/packages/Python/lldbsuite/support/funcutils.py +++ b/lldb/packages/Python/lldbsuite/support/funcutils.py @@ -1,15 +1,13 @@ import inspect + def requires_self(func): func_argc = len(inspect.getfullargspec(func).args) - if func_argc == 0 or ( - getattr( - func, - 'im_self', - None) is not None) or ( - hasattr( - func, - '__self__')): + if ( + func_argc == 0 + or (getattr(func, "im_self", None) is not None) + or (hasattr(func, "__self__")) + ): return False else: return True diff --git a/lldb/packages/Python/lldbsuite/support/gmodules.py b/lldb/packages/Python/lldbsuite/support/gmodules.py --- a/lldb/packages/Python/lldbsuite/support/gmodules.py +++ b/lldb/packages/Python/lldbsuite/support/gmodules.py @@ -22,8 +22,7 @@ else: # Check the compiler help for the -gmodules option. clang_help = os.popen("%s --help" % compiler_path).read() - return GMODULES_HELP_REGEX.search( - clang_help, re.DOTALL) is not None + return GMODULES_HELP_REGEX.search(clang_help, re.DOTALL) is not None GMODULES_SUPPORT_MAP[compiler_path] = _gmodules_supported_internal() return GMODULES_SUPPORT_MAP[compiler_path] diff --git a/lldb/packages/Python/lldbsuite/support/seven.py b/lldb/packages/Python/lldbsuite/support/seven.py --- a/lldb/packages/Python/lldbsuite/support/seven.py +++ b/lldb/packages/Python/lldbsuite/support/seven.py @@ -2,15 +2,16 @@ import shlex import subprocess + def get_command_output(command): try: return subprocess.check_output( - command, - shell=True, - universal_newlines=True).rstrip() + command, shell=True, universal_newlines=True + ).rstrip() except subprocess.CalledProcessError as e: return e.output + def bitcast_to_string(b: bytes) -> str: """ Take a bytes object and return a string. The returned string contains the @@ -19,6 +20,7 @@ """ return b.decode("latin1") + def bitcast_to_bytes(s: str) -> bytes: """ Take a string and return a bytes object. The returned object contains the @@ -27,14 +29,17 @@ """ return s.encode("latin1") + def unhexlify(hexstr): """Hex-decode a string. The result is always a string.""" return bitcast_to_string(binascii.unhexlify(hexstr)) + def hexlify(data): """Hex-encode string data. The result if always a string.""" return bitcast_to_string(binascii.hexlify(bitcast_to_bytes(data))) + # TODO: Replace this with `shlex.join` when minimum Python version is >= 3.8 def join_for_shell(split_command): return " ".join([shlex.quote(part) for part in split_command]) diff --git a/lldb/packages/Python/lldbsuite/test/bench.py b/lldb/packages/Python/lldbsuite/test/bench.py --- a/lldb/packages/Python/lldbsuite/test/bench.py +++ b/lldb/packages/Python/lldbsuite/test/bench.py @@ -23,36 +23,42 @@ benches = [ # Measure startup delays creating a target, setting a breakpoint, and run # to breakpoint stop. - './dotest.py -v +b %E %X -n -p TestStartupDelays.py', - + "./dotest.py -v +b %E %X -n -p TestStartupDelays.py", # Measure 'frame variable' response after stopping at a breakpoint. - './dotest.py -v +b %E %X -n -p TestFrameVariableResponse.py', - + "./dotest.py -v +b %E %X -n -p TestFrameVariableResponse.py", # Measure stepping speed after stopping at a breakpoint. - './dotest.py -v +b %E %X -n -p TestSteppingSpeed.py', - + "./dotest.py -v +b %E %X -n -p TestSteppingSpeed.py", # Measure expression cmd response with a simple custom executable program. - './dotest.py +b -n -p TestExpressionCmd.py', - + "./dotest.py +b -n -p TestExpressionCmd.py", # Attach to a spawned process then run disassembly benchmarks. - './dotest.py -v +b -n %E -p TestDoAttachThenDisassembly.py' + "./dotest.py -v +b -n %E -p TestDoAttachThenDisassembly.py", ] def main(): """Read the items from 'benches' and run the command line one by one.""" - parser = OptionParser(usage="""\ + parser = OptionParser( + usage="""\ %prog [options] Run the standard benchmarks defined in the list named 'benches'.\ -""") - parser.add_option('-e', '--executable', - type='string', action='store', - dest='exe', - help='The target program launched by lldb.') - parser.add_option('-x', '--breakpoint-spec', - type='string', action='store', - dest='break_spec', - help='The lldb breakpoint spec for the target program.') +""" + ) + parser.add_option( + "-e", + "--executable", + type="string", + action="store", + dest="exe", + help="The target program launched by lldb.", + ) + parser.add_option( + "-x", + "--breakpoint-spec", + type="string", + action="store", + dest="break_spec", + help="The lldb breakpoint spec for the target program.", + ) # Parses the options, if any. opts, args = parser.parse_args() @@ -60,14 +66,15 @@ print("Starting bench runner....") for item in benches: - command = item.replace('%E', - '-e "%s"' % opts.exe if opts.exe else '') - command = command.replace('%X', '-x "%s"' % - opts.break_spec if opts.break_spec else '') + command = item.replace("%E", '-e "%s"' % opts.exe if opts.exe else "") + command = command.replace( + "%X", '-x "%s"' % opts.break_spec if opts.break_spec else "" + ) print("Running %s" % (command)) os.system(command) print("Bench runner done.") -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/lldb/packages/Python/lldbsuite/test/builders/__init__.py b/lldb/packages/Python/lldbsuite/test/builders/__init__.py --- a/lldb/packages/Python/lldbsuite/test/builders/__init__.py +++ b/lldb/packages/Python/lldbsuite/test/builders/__init__.py @@ -7,10 +7,12 @@ def get_builder(platform): - """Returns a Builder instance for the given platform.""" - if platform == 'darwin': - from .darwin import BuilderDarwin - return BuilderDarwin() + """Returns a Builder instance for the given platform.""" + if platform == "darwin": + from .darwin import BuilderDarwin - from .builder import Builder - return Builder() + return BuilderDarwin() + + from .builder import Builder + + return Builder() diff --git a/lldb/packages/Python/lldbsuite/test/builders/builder.py b/lldb/packages/Python/lldbsuite/test/builders/builder.py --- a/lldb/packages/Python/lldbsuite/test/builders/builder.py +++ b/lldb/packages/Python/lldbsuite/test/builders/builder.py @@ -47,19 +47,31 @@ # Construct the base make invocation. lldb_test = os.environ["LLDB_TEST"] - if not (lldb_test and configuration.test_build_dir and test_subdir - and test_name and (not os.path.isabs(test_subdir))): + if not ( + lldb_test + and configuration.test_build_dir + and test_subdir + and test_name + and (not os.path.isabs(test_subdir)) + ): raise Exception("Could not derive test directories") - build_dir = os.path.join(configuration.test_build_dir, test_subdir, - test_name) + build_dir = os.path.join(configuration.test_build_dir, test_subdir, test_name) src_dir = os.path.join(configuration.test_src_root, test_subdir) # This is a bit of a hack to make inline testcases work. makefile = os.path.join(src_dir, "Makefile") if not os.path.isfile(makefile): makefile = os.path.join(build_dir, "Makefile") return [ - make, "VPATH=" + src_dir, "-C", build_dir, "-I", src_dir, "-I", - os.path.join(lldb_test, "make"), "-f", makefile + make, + "VPATH=" + src_dir, + "-C", + build_dir, + "-I", + src_dir, + "-I", + os.path.join(lldb_test, "make"), + "-f", + makefile, ] def getCmdLine(self, d): @@ -76,7 +88,7 @@ append_vars = ["CFLAGS", "CFLAGS_EXTRAS", "LD_EXTRAS"] if k in append_vars and k in os.environ: v = os.environ[k] + " " + v - return '%s=%s' % (k, v) + return "%s=%s" % (k, v) cmdline = [setOrAppendVariable(k, v) for k, v in list(d.items())] @@ -98,7 +110,7 @@ if not cc and configuration.compiler: cc = configuration.compiler if cc: - return ["CC=\"%s\"" % cc] + return ['CC="%s"' % cc] return [] def getSDKRootSpec(self): @@ -116,17 +128,23 @@ module cache used for the make system. """ if configuration.clang_module_cache_dir: - return ["CLANG_MODULE_CACHE_DIR={}".format( - configuration.clang_module_cache_dir)] + return [ + "CLANG_MODULE_CACHE_DIR={}".format(configuration.clang_module_cache_dir) + ] return [] def getLibCxxArgs(self): if configuration.libcxx_include_dir and configuration.libcxx_library_dir: - libcpp_args = ["LIBCPP_INCLUDE_DIR={}".format(configuration.libcxx_include_dir), - "LIBCPP_LIBRARY_DIR={}".format(configuration.libcxx_library_dir)] + libcpp_args = [ + "LIBCPP_INCLUDE_DIR={}".format(configuration.libcxx_include_dir), + "LIBCPP_LIBRARY_DIR={}".format(configuration.libcxx_library_dir), + ] if configuration.libcxx_include_target_dir: - libcpp_args.append("LIBCPP_INCLUDE_TARGET_DIR={}".format( - configuration.libcxx_include_target_dir)) + libcpp_args.append( + "LIBCPP_INCLUDE_TARGET_DIR={}".format( + configuration.libcxx_include_target_dir + ) + ) return libcpp_args return [] @@ -141,19 +159,34 @@ return ["MAKE_DSYM=NO", "MAKE_GMODULES=YES"] return None - def getBuildCommand(self, debug_info, architecture=None, compiler=None, - dictionary=None, testdir=None, testname=None, make_targets=None): + def getBuildCommand( + self, + debug_info, + architecture=None, + compiler=None, + dictionary=None, + testdir=None, + testname=None, + make_targets=None, + ): debug_info_args = self._getDebugInfoArgs(debug_info) if debug_info_args is None: return None if make_targets is None: make_targets = ["all"] command_parts = [ - self.getMake(testdir, testname), debug_info_args, make_targets, - self.getArchCFlags(architecture), self.getArchSpec(architecture), - self.getCCSpec(compiler), self.getExtraMakeArgs(), - self.getSDKRootSpec(), self.getModuleCacheSpec(), - self.getLibCxxArgs(), self.getCmdLine(dictionary)] + self.getMake(testdir, testname), + debug_info_args, + make_targets, + self.getArchCFlags(architecture), + self.getArchSpec(architecture), + self.getCCSpec(compiler), + self.getExtraMakeArgs(), + self.getSDKRootSpec(), + self.getModuleCacheSpec(), + self.getLibCxxArgs(), + self.getCmdLine(dictionary), + ] command = list(itertools.chain(*command_parts)) return command diff --git a/lldb/packages/Python/lldbsuite/test/builders/darwin.py b/lldb/packages/Python/lldbsuite/test/builders/darwin.py --- a/lldb/packages/Python/lldbsuite/test/builders/darwin.py +++ b/lldb/packages/Python/lldbsuite/test/builders/darwin.py @@ -21,7 +21,7 @@ def get_os_from_sdk(sdk): - return sdk[:sdk.find('.')], "" + return sdk[: sdk.find(".")], "" def get_os_and_env(): @@ -61,7 +61,7 @@ component = [arch, vendor, os + version] if env: components.append(env) - return '-'.join(component) + return "-".join(component) class BuilderDarwin(Builder): @@ -77,32 +77,31 @@ args = dict() if configuration.dsymutil: - args['DSYMUTIL'] = configuration.dsymutil + args["DSYMUTIL"] = configuration.dsymutil - if configuration.apple_sdk and 'internal' in configuration.apple_sdk: + if configuration.apple_sdk and "internal" in configuration.apple_sdk: sdk_root = lldbutil.get_xcode_sdk_root(configuration.apple_sdk) if sdk_root: - private_frameworks = os.path.join(sdk_root, 'System', - 'Library', - 'PrivateFrameworks') - args['FRAMEWORK_INCLUDES'] = '-F{}'.format(private_frameworks) + private_frameworks = os.path.join( + sdk_root, "System", "Library", "PrivateFrameworks" + ) + args["FRAMEWORK_INCLUDES"] = "-F{}".format(private_frameworks) operating_system, env = get_os_and_env() if operating_system and operating_system != "macosx": builder_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(builder_dir) if env == "simulator": - entitlements_file = 'entitlements-simulator.plist' + entitlements_file = "entitlements-simulator.plist" else: - entitlements_file = 'entitlements.plist' - entitlements = os.path.join(test_dir, 'make', entitlements_file) - args['CODESIGN'] = 'codesign --entitlements {}'.format( - entitlements) + entitlements_file = "entitlements.plist" + entitlements = os.path.join(test_dir, "make", entitlements_file) + args["CODESIGN"] = "codesign --entitlements {}".format(entitlements) else: - args['CODESIGN'] = 'codesign' + args["CODESIGN"] = "codesign" # Return extra args as a formatted string. - return ['{}={}'.format(key, value) for key, value in args.items()] + return ["{}={}".format(key, value) for key, value in args.items()] def getArchCFlags(self, arch): """Returns the ARCH_CFLAGS for the make system.""" diff --git a/lldb/packages/Python/lldbsuite/test/concurrent_base.py b/lldb/packages/Python/lldbsuite/test/concurrent_base.py --- a/lldb/packages/Python/lldbsuite/test/concurrent_base.py +++ b/lldb/packages/Python/lldbsuite/test/concurrent_base.py @@ -18,7 +18,6 @@ class ConcurrentEventsBase(TestBase): - # Concurrency is the primary test factor here, not debug info variants. NO_DEBUG_INFO_TESTCASE = True @@ -26,13 +25,16 @@ # Call super's setUp(). super(ConcurrentEventsBase, self).setUp() # Find the line number for our breakpoint. - self.filename = 'main.cpp' + self.filename = "main.cpp" self.thread_breakpoint_line = line_number( - self.filename, '// Set breakpoint here') + self.filename, "// Set breakpoint here" + ) self.setup_breakpoint_line = line_number( - self.filename, '// Break here and adjust num') + self.filename, "// Break here and adjust num" + ) self.finish_breakpoint_line = line_number( - self.filename, '// Break here and verify one thread is active') + self.filename, "// Break here and verify one thread is active" + ) def describe_threads(self): ret = [] @@ -45,66 +47,83 @@ bpid = x.GetStopReasonDataAtIndex(0) bp = self.inferior_target.FindBreakpointByID(bpid) reason_str = "%s hit %d times" % ( - lldbutil.get_description(bp), bp.GetHitCount()) + lldbutil.get_description(bp), + bp.GetHitCount(), + ) elif reason == lldb.eStopReasonWatchpoint: watchid = x.GetStopReasonDataAtIndex(0) watch = self.inferior_target.FindWatchpointByID(watchid) reason_str = "%s hit %d times" % ( - lldbutil.get_description(watch), watch.GetHitCount()) + lldbutil.get_description(watch), + watch.GetHitCount(), + ) elif reason == lldb.eStopReasonSignal: signals = self.inferior_process.GetUnixSignals() - signal_name = signals.GetSignalAsCString( - x.GetStopReasonDataAtIndex(0)) + signal_name = signals.GetSignalAsCString(x.GetStopReasonDataAtIndex(0)) reason_str = "signal %s" % signal_name - location = "\t".join([lldbutil.get_description( - x.GetFrameAtIndex(i)) for i in range(x.GetNumFrames())]) + location = "\t".join( + [ + lldbutil.get_description(x.GetFrameAtIndex(i)) + for i in range(x.GetNumFrames()) + ] + ) ret.append( - "thread %d %s due to %s at\n\t%s" % - (id, status, reason_str, location)) + "thread %d %s due to %s at\n\t%s" % (id, status, reason_str, location) + ) return ret def add_breakpoint(self, line, descriptions): - """ Adds a breakpoint at self.filename:line and appends its description to descriptions, and - returns the LLDB SBBreakpoint object. + """Adds a breakpoint at self.filename:line and appends its description to descriptions, and + returns the LLDB SBBreakpoint object. """ bpno = lldbutil.run_break_set_by_file_and_line( - self, self.filename, line, num_expected_locations=-1) + self, self.filename, line, num_expected_locations=-1 + ) bp = self.inferior_target.FindBreakpointByID(bpno) descriptions.append(": file = 'main.cpp', line = %d" % line) return bp def inferior_done(self): - """ Returns true if the inferior is done executing all the event threads (and is stopped at self.finish_breakpoint, - or has terminated execution. + """Returns true if the inferior is done executing all the event threads (and is stopped at self.finish_breakpoint, + or has terminated execution. """ - return self.finish_breakpoint.GetHitCount() > 0 or \ - self.crash_count > 0 or \ - self.inferior_process.GetState() == lldb.eStateExited + return ( + self.finish_breakpoint.GetHitCount() > 0 + or self.crash_count > 0 + or self.inferior_process.GetState() == lldb.eStateExited + ) def count_signaled_threads(self): count = 0 for thread in self.inferior_process: - if thread.GetStopReason() == lldb.eStopReasonSignal and thread.GetStopReasonDataAtIndex( - 0) == self.inferior_process.GetUnixSignals().GetSignalNumberFromName('SIGUSR1'): + if ( + thread.GetStopReason() == lldb.eStopReasonSignal + and thread.GetStopReasonDataAtIndex(0) + == self.inferior_process.GetUnixSignals().GetSignalNumberFromName( + "SIGUSR1" + ) + ): count += 1 return count - def do_thread_actions(self, - num_breakpoint_threads=0, - num_signal_threads=0, - num_watchpoint_threads=0, - num_crash_threads=0, - num_delay_breakpoint_threads=0, - num_delay_signal_threads=0, - num_delay_watchpoint_threads=0, - num_delay_crash_threads=0): - """ Sets a breakpoint in the main thread where test parameters (numbers of threads) can be adjusted, runs the inferior - to that point, and modifies the locals that control the event thread counts. Also sets a breakpoint in - breakpoint_func (the function executed by each 'breakpoint' thread) and a watchpoint on a global modified in - watchpoint_func. The inferior is continued until exit or a crash takes place, and the number of events seen by LLDB - is verified to match the expected number of events. + def do_thread_actions( + self, + num_breakpoint_threads=0, + num_signal_threads=0, + num_watchpoint_threads=0, + num_crash_threads=0, + num_delay_breakpoint_threads=0, + num_delay_signal_threads=0, + num_delay_watchpoint_threads=0, + num_delay_crash_threads=0, + ): + """Sets a breakpoint in the main thread where test parameters (numbers of threads) can be adjusted, runs the inferior + to that point, and modifies the locals that control the event thread counts. Also sets a breakpoint in + breakpoint_func (the function executed by each 'breakpoint' thread) and a watchpoint on a global modified in + watchpoint_func. The inferior is continued until exit or a crash takes place, and the number of events seen by LLDB + is verified to match the expected number of events. """ exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) @@ -116,27 +135,34 @@ # Initialize all the breakpoints (main thread/aux thread) self.setup_breakpoint = self.add_breakpoint( - self.setup_breakpoint_line, expected_bps) + self.setup_breakpoint_line, expected_bps + ) self.finish_breakpoint = self.add_breakpoint( - self.finish_breakpoint_line, expected_bps) + self.finish_breakpoint_line, expected_bps + ) # Set the thread breakpoint if num_breakpoint_threads + num_delay_breakpoint_threads > 0: self.thread_breakpoint = self.add_breakpoint( - self.thread_breakpoint_line, expected_bps) + self.thread_breakpoint_line, expected_bps + ) # Verify breakpoints self.expect( "breakpoint list -f", "Breakpoint locations shown correctly", - substrs=expected_bps) + substrs=expected_bps, + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # Check we are at line self.setup_breakpoint - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=["stop reason = breakpoint 1."]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."], + ) # Initialize the (single) watchpoint on the global variable (g_watchme) if num_watchpoint_threads + num_delay_watchpoint_threads > 0: @@ -144,9 +170,9 @@ for w in self.inferior_target.watchpoint_iter(): self.thread_watchpoint = w self.assertTrue( - "g_watchme" in str( - self.thread_watchpoint), - "Watchpoint location not shown correctly") + "g_watchme" in str(self.thread_watchpoint), + "Watchpoint location not shown correctly", + ) # Get the process self.inferior_process = self.inferior_target.GetProcess() @@ -156,7 +182,8 @@ self.assertEqual( self.inferior_process.GetNumThreads(), 1, - 'Expected to stop before any additional threads are spawned.') + "Expected to stop before any additional threads are spawned.", + ) self.runCmd("expr num_breakpoint_threads=%d" % num_breakpoint_threads) self.runCmd("expr num_crash_threads=%d" % num_crash_threads) @@ -164,17 +191,13 @@ self.runCmd("expr num_watchpoint_threads=%d" % num_watchpoint_threads) self.runCmd( - "expr num_delay_breakpoint_threads=%d" % - num_delay_breakpoint_threads) - self.runCmd( - "expr num_delay_crash_threads=%d" % - num_delay_crash_threads) + "expr num_delay_breakpoint_threads=%d" % num_delay_breakpoint_threads + ) + self.runCmd("expr num_delay_crash_threads=%d" % num_delay_crash_threads) + self.runCmd("expr num_delay_signal_threads=%d" % num_delay_signal_threads) self.runCmd( - "expr num_delay_signal_threads=%d" % - num_delay_signal_threads) - self.runCmd( - "expr num_delay_watchpoint_threads=%d" % - num_delay_watchpoint_threads) + "expr num_delay_watchpoint_threads=%d" % num_delay_watchpoint_threads + ) # Continue the inferior so threads are spawned self.runCmd("continue") @@ -183,23 +206,28 @@ # the inferior program ensures all threads are started and running # before any thread triggers its 'event'. num_threads = self.inferior_process.GetNumThreads() - expected_num_threads = num_breakpoint_threads + num_delay_breakpoint_threads \ - + num_signal_threads + num_delay_signal_threads \ - + num_watchpoint_threads + num_delay_watchpoint_threads \ - + num_crash_threads + num_delay_crash_threads + 1 + expected_num_threads = ( + num_breakpoint_threads + + num_delay_breakpoint_threads + + num_signal_threads + + num_delay_signal_threads + + num_watchpoint_threads + + num_delay_watchpoint_threads + + num_crash_threads + + num_delay_crash_threads + + 1 + ) self.assertEqual( num_threads, expected_num_threads, - 'Expected to see %d threads, but seeing %d. Details:\n%s' % - (expected_num_threads, - num_threads, - "\n\t".join( - self.describe_threads()))) + "Expected to see %d threads, but seeing %d. Details:\n%s" + % (expected_num_threads, num_threads, "\n\t".join(self.describe_threads())), + ) self.signal_count = self.count_signaled_threads() self.crash_count = len( - lldbutil.get_crashed_threads( - self, self.inferior_process)) + lldbutil.get_crashed_threads(self, self.inferior_process) + ) # Run to completion (or crash) while not self.inferior_done(): @@ -208,16 +236,16 @@ self.runCmd("continue") self.signal_count += self.count_signaled_threads() self.crash_count += len( - lldbutil.get_crashed_threads( - self, self.inferior_process)) + lldbutil.get_crashed_threads(self, self.inferior_process) + ) if num_crash_threads > 0 or num_delay_crash_threads > 0: # Expecting a crash self.assertTrue( self.crash_count > 0, - "Expecting at least one thread to crash. Details: %s" % - "\t\n".join( - self.describe_threads())) + "Expecting at least one thread to crash. Details: %s" + % "\t\n".join(self.describe_threads()), + ) # Ensure the zombie process is reaped self.runCmd("process kill") @@ -228,53 +256,61 @@ self.assertEqual( 1, self.finish_breakpoint.GetHitCount(), - "Expected main thread (finish) breakpoint to be hit once") + "Expected main thread (finish) breakpoint to be hit once", + ) num_threads = self.inferior_process.GetNumThreads() self.assertEqual( 1, num_threads, - "Expecting 1 thread but seeing %d. Details:%s" % - (num_threads, - "\n\t".join( - self.describe_threads()))) + "Expecting 1 thread but seeing %d. Details:%s" + % (num_threads, "\n\t".join(self.describe_threads())), + ) self.runCmd("continue") # The inferior process should have exited without crashing self.assertEqual( - 0, - self.crash_count, - "Unexpected thread(s) in crashed state") + 0, self.crash_count, "Unexpected thread(s) in crashed state" + ) self.assertEqual( - self.inferior_process.GetState(), - lldb.eStateExited, - PROCESS_EXITED) + self.inferior_process.GetState(), lldb.eStateExited, PROCESS_EXITED + ) # Verify the number of actions took place matches expected numbers - expected_breakpoint_threads = num_delay_breakpoint_threads + num_breakpoint_threads - breakpoint_hit_count = self.thread_breakpoint.GetHitCount( - ) if expected_breakpoint_threads > 0 else 0 + expected_breakpoint_threads = ( + num_delay_breakpoint_threads + num_breakpoint_threads + ) + breakpoint_hit_count = ( + self.thread_breakpoint.GetHitCount() + if expected_breakpoint_threads > 0 + else 0 + ) self.assertEqual( expected_breakpoint_threads, breakpoint_hit_count, - "Expected %d breakpoint hits, but got %d" % - (expected_breakpoint_threads, - breakpoint_hit_count)) + "Expected %d breakpoint hits, but got %d" + % (expected_breakpoint_threads, breakpoint_hit_count), + ) expected_signal_threads = num_delay_signal_threads + num_signal_threads self.assertEqual( expected_signal_threads, self.signal_count, - "Expected %d stops due to signal delivery, but got %d" % - (expected_signal_threads, - self.signal_count)) - - expected_watchpoint_threads = num_delay_watchpoint_threads + num_watchpoint_threads - watchpoint_hit_count = self.thread_watchpoint.GetHitCount( - ) if expected_watchpoint_threads > 0 else 0 + "Expected %d stops due to signal delivery, but got %d" + % (expected_signal_threads, self.signal_count), + ) + + expected_watchpoint_threads = ( + num_delay_watchpoint_threads + num_watchpoint_threads + ) + watchpoint_hit_count = ( + self.thread_watchpoint.GetHitCount() + if expected_watchpoint_threads > 0 + else 0 + ) self.assertEqual( expected_watchpoint_threads, watchpoint_hit_count, - "Expected %d watchpoint hits, got %d" % - (expected_watchpoint_threads, - watchpoint_hit_count)) + "Expected %d watchpoint hits, got %d" + % (expected_watchpoint_threads, watchpoint_hit_count), + ) diff --git a/lldb/packages/Python/lldbsuite/test/configuration.py b/lldb/packages/Python/lldbsuite/test/configuration.py --- a/lldb/packages/Python/lldbsuite/test/configuration.py +++ b/lldb/packages/Python/lldbsuite/test/configuration.py @@ -62,7 +62,7 @@ # The arch might dictate some specific CFLAGS to be passed to the toolchain to build # the inferior programs. The global variable cflags_extras provides a hook to do # just that. -cflags_extras = '' +cflags_extras = "" # The filters (testclass.testmethod) used to admit tests into our test suite. filters = [] @@ -78,7 +78,7 @@ # Set this flag if there is any session info dumped during the test run. sdir_has_content = False # svn_info stores the output from 'svn info lldb.base.dir'. -svn_info = '' +svn_info = "" # Default verbosity is 0. verbose = 0 @@ -93,7 +93,7 @@ test_src_root = lldbsuite.lldb_test_root # Separator string. -separator = '-' * 70 +separator = "-" * 70 failed = False @@ -133,8 +133,10 @@ def shouldSkipBecauseOfCategories(test_categories): if use_categories: - if len(test_categories) == 0 or len( - categories_list & set(test_categories)) == 0: + if ( + len(test_categories) == 0 + or len(categories_list & set(test_categories)) == 0 + ): return True for category in skip_categories: @@ -151,6 +153,7 @@ if filecheck and os.path.lexists(filecheck): return filecheck + def get_yaml2obj_path(): """ Get the path to the yaml2obj tool. diff --git a/lldb/packages/Python/lldbsuite/test/decorators.py b/lldb/packages/Python/lldbsuite/test/decorators.py --- a/lldb/packages/Python/lldbsuite/test/decorators.py +++ b/lldb/packages/Python/lldbsuite/test/decorators.py @@ -34,23 +34,28 @@ # and linux, oslist=no_match(["windows", "linux"]) skips *unless* windows # or linux. class no_match: - def __init__(self, item): self.item = item def _check_expected_version(comparison, expected, actual): - def fn_leq(x, y): return x <= y + def fn_leq(x, y): + return x <= y - def fn_less(x, y): return x < y + def fn_less(x, y): + return x < y - def fn_geq(x, y): return x >= y + def fn_geq(x, y): + return x >= y - def fn_greater(x, y): return x > y + def fn_greater(x, y): + return x > y - def fn_eq(x, y): return x == y + def fn_eq(x, y): + return x == y - def fn_neq(x, y): return x != y + def fn_neq(x, y): + return x != y op_lookup = { "==": fn_eq, @@ -60,48 +65,50 @@ ">": fn_greater, "<": fn_less, ">=": fn_geq, - "<=": fn_leq + "<=": fn_leq, } - expected_str = '.'.join([str(x) for x in expected]) - actual_str = '.'.join([str(x) for x in actual]) + expected_str = ".".join([str(x) for x in expected]) + actual_str = ".".join([str(x) for x in actual]) - return op_lookup[comparison]( - LooseVersion(actual_str), - LooseVersion(expected_str)) + return op_lookup[comparison](LooseVersion(actual_str), LooseVersion(expected_str)) def _match_decorator_property(expected, actual): if expected is None: return True - if actual is None : + if actual is None: return False if isinstance(expected, no_match): return not _match_decorator_property(expected.item, actual) # Python 3.6 doesn't declare a `re.Pattern` type, get the dynamic type. - pattern_type = type(re.compile('')) + pattern_type = type(re.compile("")) if isinstance(expected, (pattern_type, str)): return re.search(expected, actual) is not None if hasattr(expected, "__iter__"): - return any([x is not None and _match_decorator_property(x, actual) - for x in expected]) + return any( + [x is not None and _match_decorator_property(x, actual) for x in expected] + ) return expected == actual -def _compiler_supports(compiler, - flag, - source='int main() {}', - output_file=tempfile.NamedTemporaryFile()): +def _compiler_supports( + compiler, flag, source="int main() {}", output_file=tempfile.NamedTemporaryFile() +): """Test whether the compiler supports the given flag.""" - if platform.system() == 'Darwin': + if platform.system() == "Darwin": compiler = "xcrun " + compiler try: - cmd = "echo '%s' | %s %s -x c -o %s -" % (source, compiler, flag, - output_file.name) + cmd = "echo '%s' | %s %s -x c -o %s -" % ( + source, + compiler, + flag, + output_file.name, + ) subprocess.check_call(cmd, shell=True) except subprocess.CalledProcessError: return False @@ -111,11 +118,11 @@ def expectedFailure(func): return unittest2.expectedFailure(func) + def expectedFailureIfFn(expected_fn, bugnumber=None): def expectedFailure_impl(func): if isinstance(func, type) and issubclass(func, unittest2.TestCase): - raise Exception( - "Decorator can only be used to decorate a test method") + raise Exception("Decorator can only be used to decorate a test method") @wraps(func) def wrapper(*args, **kwargs): @@ -125,7 +132,9 @@ xfail_func(*args, **kwargs) else: func(*args, **kwargs) + return wrapper + # Some decorators can be called both with no arguments (e.g. @expectedFailureWindows) # or with arguments (e.g. @expectedFailureWindows(compilers=['gcc'])). When called # the first way, the first argument will be the actual function because decorators are @@ -157,6 +166,7 @@ self.skipTest(reason) else: return func(*args, **kwargs) + return wrapper # Some decorators can be called both with no arguments (e.g. @expectedFailureWindows) @@ -170,70 +180,86 @@ return skipTestIfFn_impl -def _decorateTest(mode, - bugnumber=None, oslist=None, hostoslist=None, - compiler=None, compiler_version=None, - archs=None, triple=None, - debug_info=None, - swig_version=None, py_version=None, - macos_version=None, - remote=None, dwarf_version=None, - setting=None): +def _decorateTest( + mode, + bugnumber=None, + oslist=None, + hostoslist=None, + compiler=None, + compiler_version=None, + archs=None, + triple=None, + debug_info=None, + swig_version=None, + py_version=None, + macos_version=None, + remote=None, + dwarf_version=None, + setting=None, +): def fn(self): skip_for_os = _match_decorator_property( - lldbplatform.translate(oslist), self.getPlatform()) + lldbplatform.translate(oslist), self.getPlatform() + ) skip_for_hostos = _match_decorator_property( - lldbplatform.translate(hostoslist), - lldbplatformutil.getHostPlatform()) + lldbplatform.translate(hostoslist), lldbplatformutil.getHostPlatform() + ) skip_for_compiler = _match_decorator_property( - compiler, self.getCompiler()) and self.expectedCompilerVersion(compiler_version) - skip_for_arch = _match_decorator_property( - archs, self.getArchitecture()) - skip_for_debug_info = _match_decorator_property( - debug_info, self.getDebugInfo()) + compiler, self.getCompiler() + ) and self.expectedCompilerVersion(compiler_version) + skip_for_arch = _match_decorator_property(archs, self.getArchitecture()) + skip_for_debug_info = _match_decorator_property(debug_info, self.getDebugInfo()) skip_for_triple = _match_decorator_property( - triple, lldb.selected_platform.GetTriple()) + triple, lldb.selected_platform.GetTriple() + ) skip_for_remote = _match_decorator_property( - remote, lldb.remote_platform is not None) + remote, lldb.remote_platform is not None + ) skip_for_swig_version = ( - swig_version is None) or ( - not hasattr( - lldb, - 'swig_version')) or ( + (swig_version is None) + or (not hasattr(lldb, "swig_version")) + or ( _check_expected_version( - swig_version[0], - swig_version[1], - lldb.swig_version)) - skip_for_py_version = ( - py_version is None) or _check_expected_version( - py_version[0], py_version[1], sys.version_info) + swig_version[0], swig_version[1], lldb.swig_version + ) + ) + ) + skip_for_py_version = (py_version is None) or _check_expected_version( + py_version[0], py_version[1], sys.version_info + ) skip_for_macos_version = (macos_version is None) or ( - (platform.mac_ver()[0] != "") and (_check_expected_version( - macos_version[0], - macos_version[1], - platform.mac_ver()[0]))) + (platform.mac_ver()[0] != "") + and ( + _check_expected_version( + macos_version[0], macos_version[1], platform.mac_ver()[0] + ) + ) + ) skip_for_dwarf_version = (dwarf_version is None) or ( - _check_expected_version(dwarf_version[0], dwarf_version[1], - self.getDwarfVersion())) - skip_for_setting = (setting is None) or ( - setting in configuration.settings) + _check_expected_version( + dwarf_version[0], dwarf_version[1], self.getDwarfVersion() + ) + ) + skip_for_setting = (setting is None) or (setting in configuration.settings) # For the test to be skipped, all specified (e.g. not None) parameters must be True. # An unspecified parameter means "any", so those are marked skip by default. And we skip # the final test if all conditions are True. - conditions = [(oslist, skip_for_os, "target o/s"), - (hostoslist, skip_for_hostos, "host o/s"), - (compiler, skip_for_compiler, "compiler or version"), - (archs, skip_for_arch, "architecture"), - (debug_info, skip_for_debug_info, "debug info format"), - (triple, skip_for_triple, "target triple"), - (swig_version, skip_for_swig_version, "swig version"), - (py_version, skip_for_py_version, "python version"), - (macos_version, skip_for_macos_version, "macOS version"), - (remote, skip_for_remote, "platform locality (remote/local)"), - (dwarf_version, skip_for_dwarf_version, "dwarf version"), - (setting, skip_for_setting, "setting")] + conditions = [ + (oslist, skip_for_os, "target o/s"), + (hostoslist, skip_for_hostos, "host o/s"), + (compiler, skip_for_compiler, "compiler or version"), + (archs, skip_for_arch, "architecture"), + (debug_info, skip_for_debug_info, "debug info format"), + (triple, skip_for_triple, "target triple"), + (swig_version, skip_for_swig_version, "swig version"), + (py_version, skip_for_py_version, "python version"), + (macos_version, skip_for_macos_version, "macOS version"), + (remote, skip_for_remote, "platform locality (remote/local)"), + (dwarf_version, skip_for_dwarf_version, "dwarf version"), + (setting, skip_for_setting, "setting"), + ] reasons = [] final_skip_result = True for this_condition in conditions: @@ -242,13 +268,14 @@ reasons.append(this_condition[2]) reason_str = None if final_skip_result: - mode_str = { - DecorateMode.Skip: "skipping", - DecorateMode.Xfail: "xfailing"}[mode] + mode_str = {DecorateMode.Skip: "skipping", DecorateMode.Xfail: "xfailing"}[ + mode + ] if len(reasons) > 0: reason_str = ",".join(reasons) reason_str = "{} due to the following parameter(s): {}".format( - mode_str, reason_str) + mode_str, reason_str + ) else: reason_str = "{} unconditionally".format(mode_str) if bugnumber is not None and not callable(bugnumber): @@ -262,6 +289,7 @@ else: return None + # provide a function to xfail on defined oslist, compiler version, and archs # if none is specified for any argument, that argument won't be checked and thus means for all # for example, @@ -270,25 +298,39 @@ # @expectedFailureAll(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), xfail for gcc>=4.9 on linux with i386 -def expectedFailureAll(bugnumber=None, - oslist=None, hostoslist=None, - compiler=None, compiler_version=None, - archs=None, triple=None, - debug_info=None, - swig_version=None, py_version=None, - macos_version=None, - remote=None, dwarf_version=None, - setting=None): - return _decorateTest(DecorateMode.Xfail, - bugnumber=bugnumber, - oslist=oslist, hostoslist=hostoslist, - compiler=compiler, compiler_version=compiler_version, - archs=archs, triple=triple, - debug_info=debug_info, - swig_version=swig_version, py_version=py_version, - macos_version=macos_version, - remote=remote,dwarf_version=dwarf_version, - setting=setting) +def expectedFailureAll( + bugnumber=None, + oslist=None, + hostoslist=None, + compiler=None, + compiler_version=None, + archs=None, + triple=None, + debug_info=None, + swig_version=None, + py_version=None, + macos_version=None, + remote=None, + dwarf_version=None, + setting=None, +): + return _decorateTest( + DecorateMode.Xfail, + bugnumber=bugnumber, + oslist=oslist, + hostoslist=hostoslist, + compiler=compiler, + compiler_version=compiler_version, + archs=archs, + triple=triple, + debug_info=debug_info, + swig_version=swig_version, + py_version=py_version, + macos_version=macos_version, + remote=remote, + dwarf_version=dwarf_version, + setting=setting, + ) # provide a function to skip on defined oslist, compiler version, and archs @@ -297,32 +339,48 @@ # @skipIf, skip for all platform/compiler/arch, # @skipIf(compiler='gcc'), skip for gcc on all platform/architecture # @skipIf(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), skip for gcc>=4.9 on linux with i386 -def skipIf(bugnumber=None, - oslist=None, hostoslist=None, - compiler=None, compiler_version=None, - archs=None, triple=None, - debug_info=None, - swig_version=None, py_version=None, - macos_version=None, - remote=None, dwarf_version=None, - setting=None): - return _decorateTest(DecorateMode.Skip, - bugnumber=bugnumber, - oslist=oslist, hostoslist=hostoslist, - compiler=compiler, compiler_version=compiler_version, - archs=archs, triple=triple, - debug_info=debug_info, - swig_version=swig_version, py_version=py_version, - macos_version=macos_version, - remote=remote, dwarf_version=dwarf_version, - setting=setting) +def skipIf( + bugnumber=None, + oslist=None, + hostoslist=None, + compiler=None, + compiler_version=None, + archs=None, + triple=None, + debug_info=None, + swig_version=None, + py_version=None, + macos_version=None, + remote=None, + dwarf_version=None, + setting=None, +): + return _decorateTest( + DecorateMode.Skip, + bugnumber=bugnumber, + oslist=oslist, + hostoslist=hostoslist, + compiler=compiler, + compiler_version=compiler_version, + archs=archs, + triple=triple, + debug_info=debug_info, + swig_version=swig_version, + py_version=py_version, + macos_version=macos_version, + remote=remote, + dwarf_version=dwarf_version, + setting=setting, + ) def _skip_for_android(reason, api_levels, archs): def impl(obj): result = lldbplatformutil.match_android_device( - obj.getArchitecture(), valid_archs=archs, valid_api_levels=api_levels) + obj.getArchitecture(), valid_archs=archs, valid_api_levels=api_levels + ) return reason if result else None + return impl @@ -333,13 +391,14 @@ def impl(func): if isinstance(func, type) and issubclass(func, unittest2.TestCase): raise Exception( - "@add_test_categories can only be used to decorate a test method") + "@add_test_categories can only be used to decorate a test method" + ) try: if hasattr(func, "categories"): cat.extend(func.categories) setattr(func, "categories", cat) except AttributeError: - raise Exception('Cannot assign categories to inline tests.') + raise Exception("Cannot assign categories to inline tests.") return func @@ -348,6 +407,7 @@ def benchmarks_test(func): """Decorate the item as a benchmarks test.""" + def should_skip_benchmarks_test(): return "benchmarks test" @@ -359,10 +419,11 @@ def no_debug_info_test(func): """Decorate the item as a test what don't use any debug info. If this annotation is specified - then the test runner won't generate a separate test for each debug info format. """ + then the test runner won't generate a separate test for each debug info format.""" if isinstance(func, type) and issubclass(func, unittest2.TestCase): raise Exception( - "@no_debug_info_test can only be used to decorate a test method") + "@no_debug_info_test can only be used to decorate a test method" + ) @wraps(func) def wrapper(self, *args, **kwargs): @@ -372,6 +433,7 @@ wrapper.__no_debug_info_test__ = True return wrapper + def apple_simulator_test(platform): """ Decorate the test as a test requiring a simulator for a specific platform. @@ -379,13 +441,16 @@ Consider that a simulator is available if you have the corresponding SDK installed. The SDK identifiers for simulators are iphonesimulator, appletvsimulator, watchsimulator """ + def should_skip_simulator_test(): - if lldbplatformutil.getHostPlatform() not in ['darwin', 'macosx']: + if lldbplatformutil.getHostPlatform() not in ["darwin", "macosx"]: return "simulator tests are run only on darwin hosts." try: - DEVNULL = open(os.devnull, 'w') - output = subprocess.check_output(["xcodebuild", "-showsdks"], stderr=DEVNULL).decode("utf-8") - if re.search('%ssimulator' % platform, output): + DEVNULL = open(os.devnull, "w") + output = subprocess.check_output( + ["xcodebuild", "-showsdks"], stderr=DEVNULL + ).decode("utf-8") + if re.search("%ssimulator" % platform, output): return None else: return "%s simulator is not supported on this system." % platform @@ -406,17 +471,15 @@ def expectedFailureOS( - oslist, - bugnumber=None, - compilers=None, - debug_info=None, - archs=None): + oslist, bugnumber=None, compilers=None, debug_info=None, archs=None +): return expectedFailureAll( oslist=oslist, bugnumber=bugnumber, compiler=compilers, archs=archs, - debug_info=debug_info) + debug_info=debug_info, + ) def expectedFailureDarwin(bugnumber=None, compilers=None, debug_info=None, archs=None): @@ -427,11 +490,12 @@ bugnumber, compilers, debug_info=debug_info, - archs=archs) + archs=archs, + ) def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None): - """ Mark a test as xfail for Android. + """Mark a test as xfail for Android. Arguments: bugnumber - The LLVM pr associated with the problem. @@ -441,17 +505,13 @@ for which a test is expected to fail. None means all architectures. """ return expectedFailureIfFn( - _skip_for_android( - "xfailing on android", - api_levels, - archs), - bugnumber) + _skip_for_android("xfailing on android", api_levels, archs), bugnumber + ) def expectedFailureNetBSD(bugnumber=None): - return expectedFailureOS( - ['netbsd'], - bugnumber) + return expectedFailureOS(["netbsd"], bugnumber) + # TODO: This decorator does not do anything. Remove it. def expectedFlakey(expected_fn, bugnumber=None): @@ -459,7 +519,9 @@ @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) + return wrapper + # Some decorators can be called both with no arguments (e.g. @expectedFailureWindows) # or with arguments (e.g. @expectedFailureWindows(compilers=['gcc'])). When called # the first way, the first argument will be the actual function because decorators are @@ -473,46 +535,48 @@ def expectedFlakeyOS(oslist, bugnumber=None, compilers=None): def fn(self): - return (self.getPlatform() in oslist and - self.expectedCompiler(compilers)) + return self.getPlatform() in oslist and self.expectedCompiler(compilers) + return expectedFlakey(fn, bugnumber) def expectedFlakeyDarwin(bugnumber=None, compilers=None): # For legacy reasons, we support both "darwin" and "macosx" as OS X # triples. - return expectedFlakeyOS( - lldbplatformutil.getDarwinOSTriples(), - bugnumber, - compilers) + return expectedFlakeyOS(lldbplatformutil.getDarwinOSTriples(), bugnumber, compilers) def expectedFlakeyFreeBSD(bugnumber=None, compilers=None): - return expectedFlakeyOS(['freebsd'], bugnumber, compilers) + return expectedFlakeyOS(["freebsd"], bugnumber, compilers) def expectedFlakeyLinux(bugnumber=None, compilers=None): - return expectedFlakeyOS(['linux'], bugnumber, compilers) + return expectedFlakeyOS(["linux"], bugnumber, compilers) def expectedFlakeyNetBSD(bugnumber=None, compilers=None): - return expectedFlakeyOS(['netbsd'], bugnumber, compilers) + return expectedFlakeyOS(["netbsd"], bugnumber, compilers) def expectedFlakeyAndroid(bugnumber=None, api_levels=None, archs=None): return expectedFlakey( - _skip_for_android( - "flakey on android", - api_levels, - archs), - bugnumber) + _skip_for_android("flakey on android", api_levels, archs), bugnumber + ) + def skipIfOutOfTreeDebugserver(func): """Decorate the item to skip tests if using an out-of-tree debugserver.""" + def is_out_of_tree_debugserver(): - return "out-of-tree debugserver" if lldbtest_config.out_of_tree_debugserver else None + return ( + "out-of-tree debugserver" + if lldbtest_config.out_of_tree_debugserver + else None + ) + return skipTestIfFn(is_out_of_tree_debugserver)(func) + def skipIfRemote(func): """Decorate the item to skip tests if testing remotely.""" return unittest2.skipIf(lldb.remote_platform, "skip on remote platform")(func) @@ -520,26 +584,28 @@ def skipIfNoSBHeaders(func): """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers.""" + def are_sb_headers_missing(): if lldb.remote_platform: return "skip because SBHeaders tests make no sense remotely" - if lldbplatformutil.getHostPlatform() == 'darwin' and configuration.lldb_framework_path: + if ( + lldbplatformutil.getHostPlatform() == "darwin" + and configuration.lldb_framework_path + ): header = os.path.join( configuration.lldb_framework_path, - 'Versions', - 'Current', - 'Headers', - 'LLDB.h') + "Versions", + "Current", + "Headers", + "LLDB.h", + ) if os.path.exists(header): return None header = os.path.join( - os.environ["LLDB_SRC"], - "include", - "lldb", - "API", - "LLDB.h") + os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h" + ) if not os.path.exists(header): return "skip because LLDB.h header not found" return None @@ -549,42 +615,54 @@ def skipIfRosetta(bugnumber): """Skip a test when running the testsuite on macOS under the Rosetta translation layer.""" + def is_running_rosetta(self): - if lldbplatformutil.getPlatform() in ['darwin', 'macosx']: + if lldbplatformutil.getPlatform() in ["darwin", "macosx"]: if (platform.uname()[5] == "arm") and (self.getArchitecture() == "x86_64"): return "skipped under Rosetta" return None + return skipTestIfFn(is_running_rosetta) + def skipIfiOSSimulator(func): """Decorate the item to skip tests that should be skipped on the iOS Simulator.""" + def is_ios_simulator(): - return "skip on the iOS Simulator" if configuration.lldb_platform_name == 'ios-simulator' else None + return ( + "skip on the iOS Simulator" + if configuration.lldb_platform_name == "ios-simulator" + else None + ) + return skipTestIfFn(is_ios_simulator)(func) + def skipIfiOS(func): return skipIfPlatform(lldbplatform.translate(lldbplatform.ios))(func) + def skipIftvOS(func): return skipIfPlatform(lldbplatform.translate(lldbplatform.tvos))(func) + def skipIfwatchOS(func): return skipIfPlatform(lldbplatform.translate(lldbplatform.watchos))(func) + def skipIfbridgeOS(func): return skipIfPlatform(lldbplatform.translate(lldbplatform.bridgeos))(func) + def skipIfDarwinEmbedded(func): """Decorate the item to skip tests that should be skipped on Darwin armv7/arm64 targets.""" - return skipIfPlatform( - lldbplatform.translate( - lldbplatform.darwin_embedded))(func) + return skipIfPlatform(lldbplatform.translate(lldbplatform.darwin_embedded))(func) + def skipIfDarwinSimulator(func): """Decorate the item to skip tests that should be skipped on Darwin simulator targets.""" - return skipIfPlatform( - lldbplatform.translate( - lldbplatform.darwin_simulator))(func) + return skipIfPlatform(lldbplatform.translate(lldbplatform.darwin_simulator))(func) + def skipIfFreeBSD(func): """Decorate the item to skip tests that should be skipped on FreeBSD.""" @@ -598,9 +676,7 @@ def skipIfDarwin(func): """Decorate the item to skip tests that should be skipped on Darwin.""" - return skipIfPlatform( - lldbplatform.translate( - lldbplatform.darwin_all))(func) + return skipIfPlatform(lldbplatform.translate(lldbplatform.darwin_all))(func) def skipIfLinux(func): @@ -612,17 +688,21 @@ """Decorate the item to skip tests that should be skipped on Windows.""" return skipIfPlatform(["windows"])(func) + def skipIfWindowsAndNonEnglish(func): """Decorate the item to skip tests that should be skipped on non-English locales on Windows.""" + def is_Windows_NonEnglish(self): if sys.platform != "win32": return None kernel = ctypes.windll.kernel32 - if locale.windows_locale[ kernel.GetUserDefaultUILanguage() ] == "en_US": + if locale.windows_locale[kernel.GetUserDefaultUILanguage()] == "en_US": return None return "skipping non-English Windows locale" + return skipTestIfFn(is_Windows_NonEnglish)(func) + def skipUnlessWindows(func): """Decorate the item to skip tests that should be skipped on any non-Windows platform.""" return skipUnlessPlatform(["windows"])(func) @@ -632,9 +712,11 @@ """Decorate the item to skip tests that should be skipped on any non Darwin platform.""" return skipUnlessPlatform(lldbplatformutil.getDarwinOSTriples())(func) + def skipUnlessTargetAndroid(func): - return unittest2.skipUnless(lldbplatformutil.target_is_android(), - "requires target to be Android")(func) + return unittest2.skipUnless( + lldbplatformutil.target_is_android(), "requires target to be Android" + )(func) def skipIfHostIncompatibleWithRemote(func): @@ -644,17 +726,24 @@ host_arch = self.getLldbArchitecture() host_platform = lldbplatformutil.getHostPlatform() target_arch = self.getArchitecture() - target_platform = 'darwin' if self.platformIsDarwin() else self.getPlatform() - if not (target_arch == 'x86_64' and host_arch == - 'i386') and host_arch != target_arch: - return "skipping because target %s is not compatible with host architecture %s" % ( - target_arch, host_arch) + target_platform = "darwin" if self.platformIsDarwin() else self.getPlatform() + if ( + not (target_arch == "x86_64" and host_arch == "i386") + and host_arch != target_arch + ): + return ( + "skipping because target %s is not compatible with host architecture %s" + % (target_arch, host_arch) + ) if target_platform != host_platform: return "skipping because target is %s but host is %s" % ( - target_platform, host_platform) + target_platform, + host_platform, + ) if lldbplatformutil.match_android_device(target_arch): return "skipping because target is android" return None + return skipTestIfFn(is_host_incompatible_with_remote)(func) @@ -662,16 +751,20 @@ """Decorate the item to skip tests if running on one of the listed platforms.""" # This decorator cannot be ported to `skipIf` yet because it is used on entire # classes, which `skipIf` explicitly forbids. - return unittest2.skipIf(lldbplatformutil.getPlatform() in oslist, - "skip on %s" % (", ".join(oslist))) + return unittest2.skipIf( + lldbplatformutil.getPlatform() in oslist, "skip on %s" % (", ".join(oslist)) + ) def skipUnlessPlatform(oslist): """Decorate the item to skip tests unless running on one of the listed platforms.""" # This decorator cannot be ported to `skipIf` yet because it is used on entire # classes, which `skipIf` explicitly forbids. - return unittest2.skipUnless(lldbplatformutil.getPlatform() in oslist, - "requires one of %s" % (", ".join(oslist))) + return unittest2.skipUnless( + lldbplatformutil.getPlatform() in oslist, + "requires one of %s" % (", ".join(oslist)), + ) + def skipUnlessArch(arch): """Decorate the item to skip tests unless running on the specified architecture.""" @@ -684,6 +777,7 @@ return skipTestIfFn(arch_doesnt_match) + def skipIfTargetAndroid(bugnumber=None, api_levels=None, archs=None): """Decorator to skip tests when the target is Android. @@ -694,36 +788,46 @@ for which a test is skipped. None means all architectures. """ return skipTestIfFn( - _skip_for_android( - "skipping for android", - api_levels, - archs), - bugnumber) + _skip_for_android("skipping for android", api_levels, archs), bugnumber + ) + def skipUnlessAppleSilicon(func): """Decorate the item to skip tests unless running on Apple Silicon.""" + def not_apple_silicon(test): - if platform.system() != 'Darwin' or test.getArchitecture() not in [ - 'arm64', 'arm64e' + if platform.system() != "Darwin" or test.getArchitecture() not in [ + "arm64", + "arm64e", ]: return "Test only runs on Apple Silicon" return None return skipTestIfFn(not_apple_silicon)(func) + def skipUnlessSupportedTypeAttribute(attr): """Decorate the item to skip test unless Clang supports type __attribute__(attr).""" + def compiler_doesnt_support_struct_attribute(self): compiler_path = self.getCompiler() f = tempfile.NamedTemporaryFile() cmd = [self.getCompiler(), "-x", "c++", "-c", "-o", f.name, "-"] - p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) - stdout, stderr = p.communicate('struct __attribute__((%s)) Test {};'%attr) + p = subprocess.Popen( + cmd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, + ) + stdout, stderr = p.communicate("struct __attribute__((%s)) Test {};" % attr) if attr in stderr: - return "Compiler does not support attribute %s"%(attr) + return "Compiler does not support attribute %s" % (attr) return None + return skipTestIfFn(compiler_doesnt_support_struct_attribute) + def skipUnlessHasCallSiteInfo(func): """Decorate the function to skip testing unless call site info from clang is available.""" @@ -734,20 +838,24 @@ return "Test requires clang as compiler" f = tempfile.NamedTemporaryFile() - cmd = "echo 'int main() {}' | " \ - "%s -g -glldb -O1 -S -emit-llvm -x c -o %s -" % (compiler_path, f.name) + cmd = ( + "echo 'int main() {}' | " + "%s -g -glldb -O1 -S -emit-llvm -x c -o %s -" % (compiler_path, f.name) + ) if os.popen(cmd).close() is not None: return "Compiler can't compile with call site info enabled" - with open(f.name, 'r') as ir_output_file: + with open(f.name, "r") as ir_output_file: buf = ir_output_file.read() - if 'DIFlagAllCallsDescribed' not in buf: + if "DIFlagAllCallsDescribed" not in buf: return "Compiler did not introduce DIFlagAllCallsDescribed IR flag" return None + return skipTestIfFn(is_compiler_clang_with_call_site_info)(func) + def skipUnlessThreadSanitizer(func): """Decorate the item to skip test unless Clang -fsanitize=thread is supported.""" @@ -759,41 +867,48 @@ compiler = os.path.basename(compiler_path) if not compiler.startswith("clang"): return "Test requires clang as compiler" - if lldbplatformutil.getPlatform() == 'windows': + if lldbplatformutil.getPlatform() == "windows": return "TSAN tests not compatible with 'windows'" # rdar://28659145 - TSAN tests don't look like they're supported on i386 - if self.getArchitecture() == 'i386' and platform.system() == 'Darwin': + if self.getArchitecture() == "i386" and platform.system() == "Darwin": return "TSAN tests not compatible with i386 targets" - if not _compiler_supports(compiler_path, '-fsanitize=thread'): + if not _compiler_supports(compiler_path, "-fsanitize=thread"): return "Compiler cannot compile with -fsanitize=thread" return None + return skipTestIfFn(is_compiler_clang_with_thread_sanitizer)(func) + def skipUnlessUndefinedBehaviorSanitizer(func): """Decorate the item to skip test unless -fsanitize=undefined is supported.""" def is_compiler_clang_with_ubsan(self): if is_running_under_asan(): - return "Undefined behavior sanitizer tests are disabled when runing under ASAN" + return ( + "Undefined behavior sanitizer tests are disabled when runing under ASAN" + ) # We need to write out the object into a named temp file for inspection. outputf = tempfile.NamedTemporaryFile() # Try to compile with ubsan turned on. - if not _compiler_supports(self.getCompiler(), '-fsanitize=undefined', - 'int main() { int x = 0; return x / x; }', - outputf): + if not _compiler_supports( + self.getCompiler(), + "-fsanitize=undefined", + "int main() { int x = 0; return x / x; }", + outputf, + ): return "Compiler cannot compile with -fsanitize=undefined" # Check that we actually see ubsan instrumentation in the binary. - cmd = 'nm %s' % outputf.name + cmd = "nm %s" % outputf.name with os.popen(cmd) as nm_output: - if '___ubsan_handle_divrem_overflow' not in nm_output.read(): + if "___ubsan_handle_divrem_overflow" not in nm_output.read(): return "Division by zero instrumentation is missing" # Find the ubsan dylib. # FIXME: This check should go away once compiler-rt gains support for __ubsan_on_report. - cmd = '%s -fsanitize=undefined -x c - -o - -### 2>&1' % self.getCompiler() + cmd = "%s -fsanitize=undefined -x c - -o - -### 2>&1" % self.getCompiler() with os.popen(cmd) as cc_output: driver_jobs = cc_output.read() m = re.search(r'"([^"]+libclang_rt.ubsan_osx_dynamic.dylib)"', driver_jobs) @@ -802,12 +917,12 @@ ubsan_dylib = m.group(1) # Check that the ubsan dylib has special monitor hooks. - cmd = 'nm -gU %s' % ubsan_dylib + cmd = "nm -gU %s" % ubsan_dylib with os.popen(cmd) as nm_output: syms = nm_output.read() - if '___ubsan_on_report' not in syms: + if "___ubsan_on_report" not in syms: return "Missing ___ubsan_on_report" - if '___ubsan_get_current_report_data' not in syms: + if "___ubsan_get_current_report_data" not in syms: return "Missing ___ubsan_get_current_report_data" # OK, this dylib + compiler works for us. @@ -815,11 +930,13 @@ return skipTestIfFn(is_compiler_clang_with_ubsan)(func) + def is_running_under_asan(): - if ('ASAN_OPTIONS' in os.environ): + if "ASAN_OPTIONS" in os.environ: return "ASAN unsupported" return None + def skipUnlessAddressSanitizer(func): """Decorate the item to skip test unless Clang -fsanitize=thread is supported.""" @@ -830,17 +947,20 @@ if is_running_under_asan(): return "Address sanitizer tests are disabled when runing under ASAN" - if lldbplatformutil.getPlatform() == 'windows': + if lldbplatformutil.getPlatform() == "windows": return "ASAN tests not compatible with 'windows'" - if not _compiler_supports(self.getCompiler(), '-fsanitize=address'): + if not _compiler_supports(self.getCompiler(), "-fsanitize=address"): return "Compiler cannot compile with -fsanitize=address" return None + return skipTestIfFn(is_compiler_with_address_sanitizer)(func) + def skipIfAsan(func): """Skip this test if the environment is set up to run LLDB *itself* under ASAN.""" return skipTestIfFn(is_running_under_asan)(func) + def skipUnlessAArch64MTELinuxCompiler(func): """Decorate the item to skip test unless MTE is supported by the test compiler.""" @@ -848,7 +968,7 @@ compiler_path = self.getCompiler() compiler = os.path.basename(compiler_path) f = tempfile.NamedTemporaryFile() - if lldbplatformutil.getPlatform() == 'windows': + if lldbplatformutil.getPlatform() == "windows": return "MTE tests are not compatible with 'windows'" cmd = "echo 'int main() {}' | %s -x c -o %s -" % (compiler_path, f.name) @@ -867,14 +987,19 @@ int main() { void* ptr = __arm_mte_create_random_tag((void*)(0), 0); }""" - cmd = "echo '%s' | %s -march=armv8.5-a+memtag -x c -o %s -" % (test_src, compiler_path, f.name) + cmd = "echo '%s' | %s -march=armv8.5-a+memtag -x c -o %s -" % ( + test_src, + compiler_path, + f.name, + ) if os.popen(cmd).close() is not None: return "Toolchain does not support MTE" return None return skipTestIfFn(is_toolchain_with_mte)(func) -def _get_bool_config(key, fail_value = True): + +def _get_bool_config(key, fail_value=True): """ Returns the current LLDB's build config value. :param key The key to lookup in LLDB's build configuration. @@ -886,22 +1011,28 @@ value_node = config.GetValueForKey(key) return value_node.GetValueForKey("value").GetBooleanValue(fail_value) + def _get_bool_config_skip_if_decorator(key): have = _get_bool_config(key) return unittest2.skipIf(not have, "requires " + key) + def skipIfCursesSupportMissing(func): return _get_bool_config_skip_if_decorator("curses")(func) + def skipIfXmlSupportMissing(func): return _get_bool_config_skip_if_decorator("xml")(func) + def skipIfEditlineSupportMissing(func): return _get_bool_config_skip_if_decorator("editline")(func) + def skipIfFBSDVMCoreSupportMissing(func): return _get_bool_config_skip_if_decorator("fbsdvmcore")(func) + def skipIfLLVMTargetMissing(target): config = lldb.SBDebugger.GetBuildConfiguration() targets = config.GetValueForKey("targets").GetValueForKey("value") @@ -913,19 +1044,23 @@ return unittest2.skipIf(not found, "requires " + target) + # Call sysctl on darwin to see if a specified hardware feature is available on this machine. def skipUnlessFeature(feature): def is_feature_enabled(self): - if platform.system() == 'Darwin': + if platform.system() == "Darwin": try: - DEVNULL = open(os.devnull, 'w') - output = subprocess.check_output(["/usr/sbin/sysctl", feature], stderr=DEVNULL).decode("utf-8") + DEVNULL = open(os.devnull, "w") + output = subprocess.check_output( + ["/usr/sbin/sysctl", feature], stderr=DEVNULL + ).decode("utf-8") # If 'feature: 1' was output, then this feature is available and # the test should not be skipped. - if re.match('%s: 1\s*' % feature, output): + if re.match("%s: 1\s*" % feature, output): return None else: return "%s is not supported on this system." % feature except subprocess.CalledProcessError: return "%s is not supported on this system." % feature + return skipTestIfFn(is_feature_enabled) diff --git a/lldb/packages/Python/lldbsuite/test/dotest.py b/lldb/packages/Python/lldbsuite/test/dotest.py --- a/lldb/packages/Python/lldbsuite/test/dotest.py +++ b/lldb/packages/Python/lldbsuite/test/dotest.py @@ -52,7 +52,7 @@ """Returns true if fpath is an executable.""" if fpath == None: return False - if sys.platform == 'win32': + if sys.platform == "win32": if not fpath.endswith(".exe"): fpath += ".exe" return os.path.isfile(fpath) and os.access(fpath, os.X_OK) @@ -75,7 +75,8 @@ def usage(parser): parser.print_help() if configuration.verbose > 0: - print(""" + print( + """ Examples: This is an example of using the -f option to pinpoint to a specific test class @@ -166,21 +167,22 @@ $ ./dotest.py --log-success -""") +""" + ) sys.exit(0) def parseExclusion(exclusion_file): """Parse an exclusion file, of the following format, where - 'skip files', 'skip methods', 'xfail files', and 'xfail methods' - are the possible list heading values: + 'skip files', 'skip methods', 'xfail files', and 'xfail methods' + are the possible list heading values: - skip files - - + skip files + + - xfail methods - + xfail methods + """ excl_type = None @@ -193,11 +195,11 @@ if not line: excl_type = None - elif excl_type == 'skip': + elif excl_type == "skip": if not configuration.skip_tests: configuration.skip_tests = [] configuration.skip_tests.append(line) - elif excl_type == 'xfail': + elif excl_type == "xfail": if not configuration.xfail_tests: configuration.xfail_tests = [] configuration.xfail_tests.append(line) @@ -231,14 +233,14 @@ if args.set_env_vars: for env_var in args.set_env_vars: - parts = env_var.split('=', 1) + parts = env_var.split("=", 1) if len(parts) == 1: os.environ[parts[0]] = "" else: os.environ[parts[0]] = parts[1] if args.set_inferior_env_vars: - lldbtest_config.inferior_env = ' '.join(args.set_inferior_env_vars) + lldbtest_config.inferior_env = " ".join(args.set_inferior_env_vars) if args.h: do_help = True @@ -249,19 +251,19 @@ configuration.compiler = which(args.compiler) if not is_exe(configuration.compiler): logging.error( - '%s is not a valid compiler executable; aborting...', - args.compiler) + "%s is not a valid compiler executable; aborting...", args.compiler + ) sys.exit(-1) else: # Use a compiler appropriate appropriate for the Apple SDK if one was # specified - if platform_system == 'Darwin' and args.apple_sdk: + if platform_system == "Darwin" and args.apple_sdk: configuration.compiler = seven.get_command_output( - 'xcrun -sdk "%s" -find clang 2> /dev/null' % - (args.apple_sdk)) + 'xcrun -sdk "%s" -find clang 2> /dev/null' % (args.apple_sdk) + ) else: # 'clang' on ubuntu 14.04 is 3.4 so we try clang-3.5 first - candidateCompilers = ['clang-3.5', 'clang', 'gcc'] + candidateCompilers = ["clang-3.5", "clang", "gcc"] for candidate in candidateCompilers: if which(candidate): configuration.compiler = candidate @@ -269,22 +271,27 @@ if args.dsymutil: configuration.dsymutil = args.dsymutil - elif platform_system == 'Darwin': + elif platform_system == "Darwin": configuration.dsymutil = seven.get_command_output( - 'xcrun -find -toolchain default dsymutil') + "xcrun -find -toolchain default dsymutil" + ) if args.llvm_tools_dir: configuration.filecheck = shutil.which("FileCheck", path=args.llvm_tools_dir) configuration.yaml2obj = shutil.which("yaml2obj", path=args.llvm_tools_dir) if not configuration.get_filecheck_path(): - logging.warning('No valid FileCheck executable; some tests may fail...') - logging.warning('(Double-check the --llvm-tools-dir argument to dotest.py)') + logging.warning("No valid FileCheck executable; some tests may fail...") + logging.warning("(Double-check the --llvm-tools-dir argument to dotest.py)") if args.libcxx_include_dir or args.libcxx_library_dir: if args.lldb_platform_name: - logging.warning('Custom libc++ is not supported for remote runs: ignoring --libcxx arguments') + logging.warning( + "Custom libc++ is not supported for remote runs: ignoring --libcxx arguments" + ) elif not (args.libcxx_include_dir and args.libcxx_library_dir): - logging.error('Custom libc++ requires both --libcxx-include-dir and --libcxx-library-dir') + logging.error( + "Custom libc++ requires both --libcxx-include-dir and --libcxx-library-dir" + ) sys.exit(-1) configuration.libcxx_include_dir = args.libcxx_include_dir configuration.libcxx_include_target_dir = args.libcxx_include_target_dir @@ -300,14 +307,12 @@ lldbtest_config.out_of_tree_debugserver = args.out_of_tree_debugserver # Set SDKROOT if we are using an Apple SDK - if platform_system == 'Darwin' and args.apple_sdk: + if platform_system == "Darwin" and args.apple_sdk: configuration.sdkroot = seven.get_command_output( - 'xcrun --sdk "%s" --show-sdk-path 2> /dev/null' % - (args.apple_sdk)) + 'xcrun --sdk "%s" --show-sdk-path 2> /dev/null' % (args.apple_sdk) + ) if not configuration.sdkroot: - logging.error( - 'No SDK found with the name %s; aborting...', - args.apple_sdk) + logging.error("No SDK found with the name %s; aborting...", args.apple_sdk) sys.exit(-1) if args.arch: @@ -317,47 +322,51 @@ if args.categories_list: configuration.categories_list = set( - test_categories.validate( - args.categories_list, False)) + test_categories.validate(args.categories_list, False) + ) configuration.use_categories = True else: configuration.categories_list = [] if args.skip_categories: configuration.skip_categories += test_categories.validate( - args.skip_categories, False) + args.skip_categories, False + ) if args.xfail_categories: configuration.xfail_categories += test_categories.validate( - args.xfail_categories, False) + args.xfail_categories, False + ) if args.E: - os.environ['CFLAGS_EXTRAS'] = args.E + os.environ["CFLAGS_EXTRAS"] = args.E if args.dwarf_version: configuration.dwarf_version = args.dwarf_version # We cannot modify CFLAGS_EXTRAS because they're used in test cases # that explicitly require no debug info. - os.environ['CFLAGS'] = '-gdwarf-{}'.format(configuration.dwarf_version) + os.environ["CFLAGS"] = "-gdwarf-{}".format(configuration.dwarf_version) if args.settings: for setting in args.settings: - if not len(setting) == 1 or not setting[0].count('='): - logging.error('"%s" is not a setting in the form "key=value"', - setting[0]) + if not len(setting) == 1 or not setting[0].count("="): + logging.error( + '"%s" is not a setting in the form "key=value"', setting[0] + ) sys.exit(-1) - setting_list = setting[0].split('=', 1) + setting_list = setting[0].split("=", 1) configuration.settings.append((setting_list[0], setting_list[1])) if args.d: sys.stdout.write( - "Suspending the process %d to wait for debugger to attach...\n" % - os.getpid()) + "Suspending the process %d to wait for debugger to attach...\n" + % os.getpid() + ) sys.stdout.flush() os.kill(os.getpid(), signal.SIGSTOP) if args.f: - if any([x.startswith('-') for x in args.f]): + if any([x.startswith("-") for x in args.f]): usage(parser) configuration.filters.extend(args.f) @@ -371,8 +380,8 @@ lldbtest_config.lldbExec = which(args.executable) if not is_exe(lldbtest_config.lldbExec): logging.error( - '%s is not a valid executable to test; aborting...', - args.executable) + "%s is not a valid executable to test; aborting...", args.executable + ) sys.exit(-1) if args.excluded: @@ -380,12 +389,12 @@ parseExclusion(excl_file) if args.p: - if args.p.startswith('-'): + if args.p.startswith("-"): usage(parser) configuration.regexp = args.p if args.t: - os.environ['LLDB_COMMAND_TRACE'] = 'YES' + os.environ["LLDB_COMMAND_TRACE"] = "YES" if args.v: configuration.verbose = 2 @@ -394,10 +403,9 @@ if args.sharp: configuration.count = args.sharp - if sys.platform.startswith('win32'): - os.environ['LLDB_DISABLE_CRASH_DIALOG'] = str( - args.disable_crash_dialog) - os.environ['LLDB_LAUNCH_INFERIORS_WITHOUT_CONSOLE'] = str(True) + if sys.platform.startswith("win32"): + os.environ["LLDB_DISABLE_CRASH_DIALOG"] = str(args.disable_crash_dialog) + os.environ["LLDB_LAUNCH_INFERIORS_WITHOUT_CONSOLE"] = str(True) if do_help: usage(parser) @@ -408,7 +416,7 @@ configuration.lldb_platform_url = args.lldb_platform_url if args.lldb_platform_working_dir: configuration.lldb_platform_working_dir = args.lldb_platform_working_dir - if platform_system == 'Darwin' and args.apple_sdk: + if platform_system == "Darwin" and args.apple_sdk: configuration.apple_sdk = args.apple_sdk if args.test_build_dir: configuration.test_build_dir = args.test_build_dir @@ -416,12 +424,14 @@ configuration.lldb_module_cache_dir = args.lldb_module_cache_dir else: configuration.lldb_module_cache_dir = os.path.join( - configuration.test_build_dir, 'module-cache-lldb') + configuration.test_build_dir, "module-cache-lldb" + ) if args.clang_module_cache_dir: configuration.clang_module_cache_dir = args.clang_module_cache_dir else: configuration.clang_module_cache_dir = os.path.join( - configuration.test_build_dir, 'module-cache-clang') + configuration.test_build_dir, "module-cache-clang" + ) if args.lldb_libs_dir: configuration.lldb_libs_dir = args.lldb_libs_dir @@ -431,10 +441,13 @@ # Gather all the dirs passed on the command line. if len(args.args) > 0: - configuration.testdirs = [os.path.realpath(os.path.abspath(x)) for x in args.args] + configuration.testdirs = [ + os.path.realpath(os.path.abspath(x)) for x in args.args + ] lldbtest_config.codesign_identity = args.codesign_identity + def registerFaulthandler(): try: import faulthandler @@ -444,9 +457,10 @@ faulthandler.enable() # faulthandler.register is not available on Windows. - if getattr(faulthandler, 'register', None): + if getattr(faulthandler, "register", None): faulthandler.register(signal.SIGTERM, chain=True) + def setupSysPath(): """ Add LLDB.framework/Resources/Python to the search paths for modules. @@ -458,7 +472,7 @@ scriptPath = os.environ["DOTEST_SCRIPT_DIR"] else: scriptPath = os.path.dirname(os.path.abspath(__file__)) - if not scriptPath.endswith('test'): + if not scriptPath.endswith("test"): print("This script expects to reside in lldb's test directory.") sys.exit(-1) @@ -473,10 +487,10 @@ # the LLDB source code. os.environ["LLDB_SRC"] = lldbsuite.lldb_root - pluginPath = os.path.join(scriptPath, 'plugins') - toolsLLDBVSCode = os.path.join(scriptPath, 'tools', 'lldb-vscode') - toolsLLDBServerPath = os.path.join(scriptPath, 'tools', 'lldb-server') - intelpt = os.path.join(scriptPath, 'tools', 'intelpt') + pluginPath = os.path.join(scriptPath, "plugins") + toolsLLDBVSCode = os.path.join(scriptPath, "tools", "lldb-vscode") + toolsLLDBServerPath = os.path.join(scriptPath, "tools", "lldb-server") + intelpt = os.path.join(scriptPath, "tools", "intelpt") # Insert script dir, plugin dir and lldb-server dir to the sys.path. sys.path.insert(0, pluginPath) @@ -509,19 +523,21 @@ if not lldbtest_config.lldbExec: # Last, check the path - lldbtest_config.lldbExec = which('lldb') + lldbtest_config.lldbExec = which("lldb") if lldbtest_config.lldbExec and not is_exe(lldbtest_config.lldbExec): print( - "'{}' is not a path to a valid executable".format( - lldbtest_config.lldbExec)) + "'{}' is not a path to a valid executable".format(lldbtest_config.lldbExec) + ) lldbtest_config.lldbExec = None if not lldbtest_config.lldbExec: - print("The 'lldb' executable cannot be located. Some of the tests may not be run as a result.") + print( + "The 'lldb' executable cannot be located. Some of the tests may not be run as a result." + ) sys.exit(-1) - os.system('%s -v' % lldbtest_config.lldbExec) + os.system("%s -v" % lldbtest_config.lldbExec) lldbDir = os.path.dirname(lldbtest_config.lldbExec) @@ -531,36 +547,47 @@ else: if not configuration.shouldSkipBecauseOfCategories(["lldb-vscode"]): print( - "The 'lldb-vscode' executable cannot be located. The lldb-vscode tests can not be run as a result.") + "The 'lldb-vscode' executable cannot be located. The lldb-vscode tests can not be run as a result." + ) configuration.skip_categories.append("lldb-vscode") lldbPythonDir = None # The directory that contains 'lldb/__init__.py' # If our lldb supports the -P option, use it to find the python path: - lldb_dash_p_result = subprocess.check_output([lldbtest_config.lldbExec, "-P"], universal_newlines=True) + lldb_dash_p_result = subprocess.check_output( + [lldbtest_config.lldbExec, "-P"], universal_newlines=True + ) if lldb_dash_p_result: for line in lldb_dash_p_result.splitlines(): - if os.path.isdir(line) and os.path.exists(os.path.join(line, 'lldb', '__init__.py')): + if os.path.isdir(line) and os.path.exists( + os.path.join(line, "lldb", "__init__.py") + ): lldbPythonDir = line break if not lldbPythonDir: print( - "Unable to load lldb extension module. Possible reasons for this include:") + "Unable to load lldb extension module. Possible reasons for this include:" + ) print(" 1) LLDB was built with LLDB_ENABLE_PYTHON=0") print( - " 2) PYTHONPATH and PYTHONHOME are not set correctly. PYTHONHOME should refer to") + " 2) PYTHONPATH and PYTHONHOME are not set correctly. PYTHONHOME should refer to" + ) print( - " the version of Python that LLDB built and linked against, and PYTHONPATH") + " the version of Python that LLDB built and linked against, and PYTHONPATH" + ) print( - " should contain the Lib directory for the same python distro, as well as the") - print(" location of LLDB\'s site-packages folder.") + " should contain the Lib directory for the same python distro, as well as the" + ) + print(" location of LLDB's site-packages folder.") print( - " 3) A different version of Python than that which was built against is exported in") - print(" the system\'s PATH environment variable, causing conflicts.") + " 3) A different version of Python than that which was built against is exported in" + ) + print(" the system's PATH environment variable, causing conflicts.") print( - " 4) The executable '%s' could not be found. Please check " % - lldbtest_config.lldbExec) + " 4) The executable '%s' could not be found. Please check " + % lldbtest_config.lldbExec + ) print(" that it exists and is executable.") if lldbPythonDir: @@ -569,18 +596,18 @@ # If the path we've constructed looks like that, then we'll strip out # the Versions/A part. (before, frameWithVersion, after) = lldbPythonDir.rpartition( - "LLDB.framework/Versions/A") + "LLDB.framework/Versions/A" + ) if frameWithVersion != "": lldbPythonDir = before + "LLDB.framework" + after lldbPythonDir = os.path.abspath(lldbPythonDir) if "freebsd" in sys.platform or "linux" in sys.platform: - os.environ['LLDB_LIB_DIR'] = os.path.join(lldbPythonDir, '..', '..') + os.environ["LLDB_LIB_DIR"] = os.path.join(lldbPythonDir, "..", "..") # If tests need to find LLDB_FRAMEWORK, now they can do it - os.environ["LLDB_FRAMEWORK"] = os.path.dirname( - os.path.dirname(lldbPythonDir)) + os.environ["LLDB_FRAMEWORK"] = os.path.dirname(os.path.dirname(lldbPythonDir)) # This is to locate the lldb.py module. Insert it right after # sys.path[0]. @@ -622,15 +649,15 @@ def iter_filters(): for filterspec in configuration.filters: - parts = filterspec.split('.') + parts = filterspec.split(".") if check(module, parts): yield filterspec elif parts[0] == base and len(parts) > 1 and check(module, parts[1:]): - yield '.'.join(parts[1:]) + yield ".".join(parts[1:]) else: - for key,value in module.__dict__.items(): + for key, value in module.__dict__.items(): if check(value, parts): - yield key + '.' + filterspec + yield key + "." + filterspec filtered = False for filterspec in iter_filters(): @@ -648,22 +675,22 @@ # Also the fail-over case when the filterspec branch # (base, filterspec) combo doesn't make sense. configuration.suite.addTests( - unittest2.defaultTestLoader.loadTestsFromName(base)) + unittest2.defaultTestLoader.loadTestsFromName(base) + ) def visit(prefix, dir, names): """Visitor function for os.path.walk(path, visit, arg).""" dir_components = set(dir.split(os.sep)) - excluded_components = set(['.svn', '.git']) + excluded_components = set([".svn", ".git"]) if dir_components.intersection(excluded_components): return # Gather all the Python test file names that follow the Test*.py pattern. python_test_files = [ - name - for name in names - if name.endswith('.py') and name.startswith(prefix)] + name for name in names if name.endswith(".py") and name.startswith(prefix) + ] # Visit all the python test files. for name in python_test_files: @@ -689,17 +716,15 @@ def checkDsymForUUIDIsNotOn(): cmd = ["defaults", "read", "com.apple.DebugSymbols"] - process = subprocess.Popen( - cmd, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) + process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) cmd_output = process.stdout.read() output_str = cmd_output.decode("utf-8") if "DBGFileMappedPaths = " in output_str: - print("%s =>" % ' '.join(cmd)) + print("%s =>" % " ".join(cmd)) print(output_str) print( - "Disable automatic lookup and caching of dSYMs before running the test suite!") + "Disable automatic lookup and caching of dSYMs before running the test suite!" + ) print("Exiting...") sys.exit(0) @@ -708,6 +733,7 @@ # lldb.py does SBDebugger.Initialize(). # Call SBDebugger.Terminate() on exit. import lldb + lldb.SBDebugger.Terminate() if exitCode: sys.exit(exitCode) @@ -715,11 +741,11 @@ def getVersionForSDK(sdk): sdk = str.lower(sdk) - full_path = seven.get_command_output('xcrun -sdk %s --show-sdk-path' % sdk) + full_path = seven.get_command_output("xcrun -sdk %s --show-sdk-path" % sdk) basename = os.path.basename(full_path) basename = os.path.splitext(basename)[0] basename = str.lower(basename) - ver = basename.replace(sdk, '') + ver = basename.replace(sdk, "") return ver @@ -734,14 +760,16 @@ raise Exception(c + " is not a valid compiler") pipe = subprocess.Popen( - ['xcrun', '-find', c], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + ["xcrun", "-find", c], stdout=subprocess.PIPE, stderr=subprocess.STDOUT + ) cmd_output = pipe.stdout.read() if not cmd_output or "not found" in cmd_output: raise Exception(c + " is not a valid compiler") - configuration.compiler = cmd_output.split('\n')[0] + configuration.compiler = cmd_output.split("\n")[0] print("'xcrun -find %s' returning %s" % (c, configuration.compiler)) + def canRunLibcxxTests(): from lldbsuite.test import lldbplatformutil @@ -753,24 +781,35 @@ if platform == "linux": with tempfile.NamedTemporaryFile() as f: cmd = [configuration.compiler, "-xc++", "-stdlib=libc++", "-o", f.name, "-"] - p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) + p = subprocess.Popen( + cmd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, + ) _, stderr = p.communicate("#include \nint main() {}") if not p.returncode: return True, "Compiling with -stdlib=libc++ works" - return False, "Compiling with -stdlib=libc++ fails with the error: %s" % stderr + return ( + False, + "Compiling with -stdlib=libc++ fails with the error: %s" % stderr, + ) return False, "Don't know how to build with libc++ on %s" % platform + def checkLibcxxSupport(): result, reason = canRunLibcxxTests() if result: - return # libc++ supported + return # libc++ supported if "libc++" in configuration.categories_list: - return # libc++ category explicitly requested, let it run. + return # libc++ category explicitly requested, let it run. if configuration.verbose: print("libc++ tests will not be run because: " + reason) configuration.skip_categories.append("libc++") + def canRunLibstdcxxTests(): from lldbsuite.test import lldbplatformutil @@ -781,16 +820,18 @@ return True, "libstdcxx always present" return False, "Don't know how to build with libstdcxx on %s" % platform + def checkLibstdcxxSupport(): result, reason = canRunLibstdcxxTests() if result: - return # libstdcxx supported + return # libstdcxx supported if "libstdcxx" in configuration.categories_list: - return # libstdcxx category explicitly requested, let it run. + return # libstdcxx category explicitly requested, let it run. if configuration.verbose: print("libstdcxx tests will not be run because: " + reason) configuration.skip_categories.append("libstdcxx") + def canRunWatchpointTests(): from lldbsuite.test import lldbplatformutil @@ -799,8 +840,13 @@ if os.geteuid() == 0: return True, "root can always write dbregs" try: - output = subprocess.check_output(["/sbin/sysctl", "-n", - "security.models.extensions.user_set_dbregs"]).decode().strip() + output = ( + subprocess.check_output( + ["/sbin/sysctl", "-n", "security.models.extensions.user_set_dbregs"] + ) + .decode() + .strip() + ) if output == "1": return True, "security.models.extensions.user_set_dbregs enabled" except subprocess.CalledProcessError: @@ -808,20 +854,23 @@ return False, "security.models.extensions.user_set_dbregs disabled" elif platform == "freebsd" and configuration.arch == "aarch64": import lldb + if lldb.SBPlatform.GetHostPlatform().GetOSMajorVersion() < 13: return False, "Watchpoint support on arm64 requires FreeBSD 13.0" return True, "watchpoint support available" + def checkWatchpointSupport(): result, reason = canRunWatchpointTests() if result: - return # watchpoints supported + return # watchpoints supported if "watchpoint" in configuration.categories_list: - return # watchpoint category explicitly requested, let it run. + return # watchpoint category explicitly requested, let it run. if configuration.verbose: print("watchpoint tests will not be run because: " + reason) configuration.skip_categories.append("watchpoint") + def checkObjcSupport(): from lldbsuite.test import lldbplatformutil @@ -830,6 +879,7 @@ print("objc tests will be skipped because of unsupported platform") configuration.skip_categories.append("objc") + def checkDebugInfoSupport(): from lldbsuite.test import lldbplatformutil @@ -837,11 +887,12 @@ compiler = configuration.compiler for cat in test_categories.debug_info_categories: if cat in configuration.categories_list: - continue # Category explicitly requested, let it run. + continue # Category explicitly requested, let it run. if test_categories.is_supported_on_platform(cat, platform, compiler): continue configuration.skip_categories.append(cat) + def checkDebugServerSupport(): from lldbsuite.test import lldbplatformutil import lldb @@ -853,13 +904,13 @@ # configuration.skip_categories.append("debugserver") if configuration.verbose: - print(skip_msg%"debugserver"); + print(skip_msg % "debugserver") else: configuration.skip_categories.append("debugserver") if lldb.remote_platform and lldbplatformutil.getPlatform() == "windows": configuration.skip_categories.append("llgs") if configuration.verbose: - print(skip_msg%"lldb-server"); + print(skip_msg % "lldb-server") def checkForkVForkSupport(): @@ -888,6 +939,7 @@ setupSysPath() import lldb + lldb.SBDebugger.Initialize() lldb.SBDebugger.PrintStackTraceOnError() @@ -899,46 +951,58 @@ from lldbsuite.test import lldbutil if configuration.lldb_platform_name: - print("Setting up remote platform '%s'" % - (configuration.lldb_platform_name)) - lldb.remote_platform = lldb.SBPlatform( - configuration.lldb_platform_name) + print("Setting up remote platform '%s'" % (configuration.lldb_platform_name)) + lldb.remote_platform = lldb.SBPlatform(configuration.lldb_platform_name) lldb.selected_platform = lldb.remote_platform if not lldb.remote_platform.IsValid(): print( - "error: unable to create the LLDB platform named '%s'." % - (configuration.lldb_platform_name)) + "error: unable to create the LLDB platform named '%s'." + % (configuration.lldb_platform_name) + ) exitTestSuite(1) if configuration.lldb_platform_url: # We must connect to a remote platform if a LLDB platform URL was # specified print( - "Connecting to remote platform '%s' at '%s'..." % - (configuration.lldb_platform_name, configuration.lldb_platform_url)) + "Connecting to remote platform '%s' at '%s'..." + % (configuration.lldb_platform_name, configuration.lldb_platform_url) + ) platform_connect_options = lldb.SBPlatformConnectOptions( - configuration.lldb_platform_url) + configuration.lldb_platform_url + ) err = lldb.remote_platform.ConnectRemote(platform_connect_options) if err.Success(): print("Connected.") else: - print("error: failed to connect to remote platform using URL '%s': %s" % ( - configuration.lldb_platform_url, err)) + print( + "error: failed to connect to remote platform using URL '%s': %s" + % (configuration.lldb_platform_url, err) + ) exitTestSuite(1) else: configuration.lldb_platform_url = None if configuration.lldb_platform_working_dir: - print("Setting remote platform working directory to '%s'..." % - (configuration.lldb_platform_working_dir)) + print( + "Setting remote platform working directory to '%s'..." + % (configuration.lldb_platform_working_dir) + ) error = lldb.remote_platform.MakeDirectory( - configuration.lldb_platform_working_dir, 448) # 448 = 0o700 + configuration.lldb_platform_working_dir, 448 + ) # 448 = 0o700 if error.Fail(): - raise Exception("making remote directory '%s': %s" % ( - configuration.lldb_platform_working_dir, error)) + raise Exception( + "making remote directory '%s': %s" + % (configuration.lldb_platform_working_dir, error) + ) if not lldb.remote_platform.SetWorkingDirectory( - configuration.lldb_platform_working_dir): - raise Exception("failed to set working directory '%s'" % configuration.lldb_platform_working_dir) + configuration.lldb_platform_working_dir + ): + raise Exception( + "failed to set working directory '%s'" + % configuration.lldb_platform_working_dir + ) lldb.selected_platform = lldb.remote_platform else: lldb.remote_platform = None @@ -958,11 +1022,15 @@ checkForkVForkSupport() skipped_categories_list = ", ".join(configuration.skip_categories) - print("Skipping the following test categories: {}".format(configuration.skip_categories)) + print( + "Skipping the following test categories: {}".format( + configuration.skip_categories + ) + ) for testdir in configuration.testdirs: - for (dirpath, dirnames, filenames) in os.walk(testdir): - visit('Test', dirpath, filenames) + for dirpath, dirnames, filenames in os.walk(testdir): + visit("Test", dirpath, filenames) # # Now that we have loaded all the test cases, run the whole test suite. @@ -980,8 +1048,7 @@ print("compiler=%s" % configuration.compiler) # Iterating over all possible architecture and compiler combinations. - configString = "arch=%s compiler=%s" % (configuration.arch, - configuration.compiler) + configString = "arch=%s compiler=%s" % (configuration.arch, configuration.compiler) # Output the configuration. if configuration.verbose: @@ -991,9 +1058,12 @@ if configuration.verbose: sys.stderr.write(configuration.separator + "\n") sys.stderr.write( - "Collected %d test%s\n\n" % - (configuration.suite.countTestCases(), - configuration.suite.countTestCases() != 1 and "s" or "")) + "Collected %d test%s\n\n" + % ( + configuration.suite.countTestCases(), + configuration.suite.countTestCases() != 1 and "s" or "", + ) + ) if configuration.suite.countTestCases() == 0: logging.error("did not discover any matching tests") @@ -1004,41 +1074,42 @@ result = unittest2.TextTestRunner( stream=sys.stderr, verbosity=configuration.verbose, - resultclass=test_result.LLDBTestResult).run( - configuration.suite) + resultclass=test_result.LLDBTestResult, + ).run(configuration.suite) else: # We are invoking the same test suite more than once. In this case, # mark __ignore_singleton__ flag as True so the signleton pattern is # not enforced. test_result.LLDBTestResult.__ignore_singleton__ = True for i in range(configuration.count): - result = unittest2.TextTestRunner( stream=sys.stderr, verbosity=configuration.verbose, - resultclass=test_result.LLDBTestResult).run( - configuration.suite) + resultclass=test_result.LLDBTestResult, + ).run(configuration.suite) configuration.failed = not result.wasSuccessful() if configuration.sdir_has_content and configuration.verbose: sys.stderr.write( "Session logs for test failures/errors/unexpected successes" - " can be found in the test build directory\n") + " can be found in the test build directory\n" + ) - if configuration.use_categories and len( - configuration.failures_per_category) > 0: + if configuration.use_categories and len(configuration.failures_per_category) > 0: sys.stderr.write("Failures per category:\n") for category in configuration.failures_per_category: sys.stderr.write( - "%s - %d\n" % - (category, configuration.failures_per_category[category])) + "%s - %d\n" % (category, configuration.failures_per_category[category]) + ) # Exiting. exitTestSuite(configuration.failed) + if __name__ == "__main__": print( - __file__ + - " is for use as a module only. It should not be run as a standalone script.") + __file__ + + " is for use as a module only. It should not be run as a standalone script." + ) sys.exit(-1) diff --git a/lldb/packages/Python/lldbsuite/test/dotest_args.py b/lldb/packages/Python/lldbsuite/test/dotest_args.py --- a/lldb/packages/Python/lldbsuite/test/dotest_args.py +++ b/lldb/packages/Python/lldbsuite/test/dotest_args.py @@ -12,227 +12,323 @@ def create_parser(): parser = argparse.ArgumentParser( - description='description', - prefix_chars='+-', - add_help=False) + description="description", prefix_chars="+-", add_help=False + ) group = None # Helper function for boolean options (group will point to the current # group when executing X) X = lambda optstr, helpstr, **kwargs: group.add_argument( - optstr, help=helpstr, action='store_true', **kwargs) + optstr, help=helpstr, action="store_true", **kwargs + ) - group = parser.add_argument_group('Help') + group = parser.add_argument_group("Help") group.add_argument( - '-h', - '--help', - dest='h', - action='store_true', - help="Print this help message and exit. Add '-v' for more detailed help.") + "-h", + "--help", + dest="h", + action="store_true", + help="Print this help message and exit. Add '-v' for more detailed help.", + ) # C and Python toolchain options - group = parser.add_argument_group('Toolchain options') - group.add_argument( - '-A', - '--arch', - metavar='arch', - dest='arch', - help=textwrap.dedent('''Specify the architecture(s) to test. This option can be specified more than once''')) - group.add_argument('-C', '--compiler', metavar='compiler', dest='compiler', help=textwrap.dedent( - '''Specify the compiler(s) used to build the inferior executables. The compiler path can be an executable basename or a full path to a compiler executable. This option can be specified multiple times.''')) - if sys.platform == 'darwin': - group.add_argument('--apple-sdk', metavar='apple_sdk', dest='apple_sdk', default="", help=textwrap.dedent( - '''Specify the name of the Apple SDK (macosx, macosx.internal, iphoneos, iphoneos.internal, or path to SDK) and use the appropriate tools from that SDK's toolchain.''')) - group.add_argument('--libcxx-include-dir', help=textwrap.dedent( - 'Specify the path to a custom libc++ include directory. Must be used in conjunction with --libcxx-library-dir.')) - group.add_argument('--libcxx-include-target-dir', help=textwrap.dedent( - 'Specify the path to a custom libc++ include target directory to use in addition to --libcxx-include-dir. Optional.')) - group.add_argument('--libcxx-library-dir', help=textwrap.dedent( - 'Specify the path to a custom libc++ library directory. Must be used in conjunction with --libcxx-include-dir.')) + group = parser.add_argument_group("Toolchain options") + group.add_argument( + "-A", + "--arch", + metavar="arch", + dest="arch", + help=textwrap.dedent( + """Specify the architecture(s) to test. This option can be specified more than once""" + ), + ) + group.add_argument( + "-C", + "--compiler", + metavar="compiler", + dest="compiler", + help=textwrap.dedent( + """Specify the compiler(s) used to build the inferior executables. The compiler path can be an executable basename or a full path to a compiler executable. This option can be specified multiple times.""" + ), + ) + if sys.platform == "darwin": + group.add_argument( + "--apple-sdk", + metavar="apple_sdk", + dest="apple_sdk", + default="", + help=textwrap.dedent( + """Specify the name of the Apple SDK (macosx, macosx.internal, iphoneos, iphoneos.internal, or path to SDK) and use the appropriate tools from that SDK's toolchain.""" + ), + ) + group.add_argument( + "--libcxx-include-dir", + help=textwrap.dedent( + "Specify the path to a custom libc++ include directory. Must be used in conjunction with --libcxx-library-dir." + ), + ) + group.add_argument( + "--libcxx-include-target-dir", + help=textwrap.dedent( + "Specify the path to a custom libc++ include target directory to use in addition to --libcxx-include-dir. Optional." + ), + ) + group.add_argument( + "--libcxx-library-dir", + help=textwrap.dedent( + "Specify the path to a custom libc++ library directory. Must be used in conjunction with --libcxx-include-dir." + ), + ) # FIXME? This won't work for different extra flags according to each arch. group.add_argument( - '-E', - metavar='extra-flags', - help=textwrap.dedent('''Specify the extra flags to be passed to the toolchain when building the inferior programs to be debugged - suggestions: do not lump the "-A arch1 -A arch2" together such that the -E option applies to only one of the architectures''')) + "-E", + metavar="extra-flags", + help=textwrap.dedent( + """Specify the extra flags to be passed to the toolchain when building the inferior programs to be debugged + suggestions: do not lump the "-A arch1 -A arch2" together such that the -E option applies to only one of the architectures""" + ), + ) - group.add_argument('--dsymutil', metavar='dsymutil', dest='dsymutil', help=textwrap.dedent('Specify which dsymutil to use.')) - group.add_argument('--llvm-tools-dir', metavar='dir', dest='llvm_tools_dir', - help=textwrap.dedent('The location of llvm tools used for testing (yaml2obj, FileCheck, etc.).')) + group.add_argument( + "--dsymutil", + metavar="dsymutil", + dest="dsymutil", + help=textwrap.dedent("Specify which dsymutil to use."), + ) + group.add_argument( + "--llvm-tools-dir", + metavar="dir", + dest="llvm_tools_dir", + help=textwrap.dedent( + "The location of llvm tools used for testing (yaml2obj, FileCheck, etc.)." + ), + ) # Test filtering options - group = parser.add_argument_group('Test filtering options') - group.add_argument( - '-f', - metavar='filterspec', - action='append', - help=('Specify a filter, which looks like "TestModule.TestClass.test_name". '+ - 'You may also use shortened filters, such as '+ - '"TestModule.TestClass", "TestClass.test_name", or just "test_name".')) - group.add_argument( - '-p', - metavar='pattern', - help='Specify a regexp filename pattern for inclusion in the test suite') - group.add_argument('--excluded', metavar='exclusion-file', action='append', help=textwrap.dedent( - '''Specify a file for tests to exclude. File should contain lists of regular expressions for test files or methods, - with each list under a matching header (xfail files, xfail methods, skip files, skip methods)''')) - group.add_argument( - '-G', - '--category', - metavar='category', - action='append', - dest='categories_list', - help=textwrap.dedent('''Specify categories of test cases of interest. Can be specified more than once.''')) - group.add_argument( - '--skip-category', - metavar='category', - action='append', - dest='skip_categories', - help=textwrap.dedent('''Specify categories of test cases to skip. Takes precedence over -G. Can be specified more than once.''')) - group.add_argument( - '--xfail-category', - metavar='category', - action='append', - dest='xfail_categories', - help=textwrap.dedent('''Specify categories of test cases that are expected to fail. Can be specified more than once.''')) + group = parser.add_argument_group("Test filtering options") + group.add_argument( + "-f", + metavar="filterspec", + action="append", + help=( + 'Specify a filter, which looks like "TestModule.TestClass.test_name". ' + + "You may also use shortened filters, such as " + + '"TestModule.TestClass", "TestClass.test_name", or just "test_name".' + ), + ) + group.add_argument( + "-p", + metavar="pattern", + help="Specify a regexp filename pattern for inclusion in the test suite", + ) + group.add_argument( + "--excluded", + metavar="exclusion-file", + action="append", + help=textwrap.dedent( + """Specify a file for tests to exclude. File should contain lists of regular expressions for test files or methods, + with each list under a matching header (xfail files, xfail methods, skip files, skip methods)""" + ), + ) + group.add_argument( + "-G", + "--category", + metavar="category", + action="append", + dest="categories_list", + help=textwrap.dedent( + """Specify categories of test cases of interest. Can be specified more than once.""" + ), + ) + group.add_argument( + "--skip-category", + metavar="category", + action="append", + dest="skip_categories", + help=textwrap.dedent( + """Specify categories of test cases to skip. Takes precedence over -G. Can be specified more than once.""" + ), + ) + group.add_argument( + "--xfail-category", + metavar="category", + action="append", + dest="xfail_categories", + help=textwrap.dedent( + """Specify categories of test cases that are expected to fail. Can be specified more than once.""" + ), + ) # Configuration options - group = parser.add_argument_group('Configuration options') + group = parser.add_argument_group("Configuration options") group.add_argument( - '--framework', - metavar='framework-path', - help='The path to LLDB.framework') + "--framework", metavar="framework-path", help="The path to LLDB.framework" + ) group.add_argument( - '--executable', - metavar='executable-path', - help='The path to the lldb executable') + "--executable", + metavar="executable-path", + help="The path to the lldb executable", + ) group.add_argument( - '--out-of-tree-debugserver', - dest='out_of_tree_debugserver', - action='store_true', - help='A flag to indicate an out-of-tree debug server is being used') + "--out-of-tree-debugserver", + dest="out_of_tree_debugserver", + action="store_true", + help="A flag to indicate an out-of-tree debug server is being used", + ) group.add_argument( - '--dwarf-version', - metavar='dwarf_version', - dest='dwarf_version', + "--dwarf-version", + metavar="dwarf_version", + dest="dwarf_version", type=int, - help='Override the DWARF version.') + help="Override the DWARF version.", + ) group.add_argument( - '--setting', - metavar='SETTING=VALUE', - dest='settings', + "--setting", + metavar="SETTING=VALUE", + dest="settings", type=str, nargs=1, - action='append', - help='Run "setting set SETTING VALUE" before executing any test.') + action="append", + help='Run "setting set SETTING VALUE" before executing any test.', + ) group.add_argument( - '-y', + "-y", type=int, - metavar='count', - help="Specify the iteration count used to collect our benchmarks. An example is the number of times to do 'thread step-over' to measure stepping speed.") + metavar="count", + help="Specify the iteration count used to collect our benchmarks. An example is the number of times to do 'thread step-over' to measure stepping speed.", + ) group.add_argument( - '-#', + "-#", type=int, - metavar='sharp', - dest='sharp', - help='Repeat the test suite for a specified number of times') - group.add_argument('--channel', metavar='channel', dest='channels', action='append', help=textwrap.dedent( - "Specify the log channels (and optional categories) e.g. 'lldb all' or 'gdb-remote packets' if no categories are specified, 'default' is used")) - group.add_argument( - '--log-success', - dest='log_success', - action='store_true', - help="Leave logs/traces even for successful test runs (useful for creating reference log files during debugging.)") - group.add_argument( - '--codesign-identity', - metavar='Codesigning identity', - default='lldb_codesign', - help='The codesigning identity to use') - group.add_argument( - '--build-dir', - dest='test_build_dir', - metavar='Test build directory', - default='lldb-test-build.noindex', - help='The root build directory for the tests. It will be removed before running.') - group.add_argument( - '--lldb-module-cache-dir', - dest='lldb_module_cache_dir', - metavar='The clang module cache directory used by LLDB', - help='The clang module cache directory used by LLDB. Defaults to /module-cache-lldb.') - group.add_argument( - '--clang-module-cache-dir', - dest='clang_module_cache_dir', - metavar='The clang module cache directory used by Clang', - help='The clang module cache directory used in the Make files by Clang while building tests. Defaults to /module-cache-clang.') - group.add_argument( - '--lldb-libs-dir', - dest='lldb_libs_dir', - metavar='path', - help='The path to LLDB library directory (containing liblldb)') - group.add_argument( - '--enable-plugin', - dest='enabled_plugins', - action='append', + metavar="sharp", + dest="sharp", + help="Repeat the test suite for a specified number of times", + ) + group.add_argument( + "--channel", + metavar="channel", + dest="channels", + action="append", + help=textwrap.dedent( + "Specify the log channels (and optional categories) e.g. 'lldb all' or 'gdb-remote packets' if no categories are specified, 'default' is used" + ), + ) + group.add_argument( + "--log-success", + dest="log_success", + action="store_true", + help="Leave logs/traces even for successful test runs (useful for creating reference log files during debugging.)", + ) + group.add_argument( + "--codesign-identity", + metavar="Codesigning identity", + default="lldb_codesign", + help="The codesigning identity to use", + ) + group.add_argument( + "--build-dir", + dest="test_build_dir", + metavar="Test build directory", + default="lldb-test-build.noindex", + help="The root build directory for the tests. It will be removed before running.", + ) + group.add_argument( + "--lldb-module-cache-dir", + dest="lldb_module_cache_dir", + metavar="The clang module cache directory used by LLDB", + help="The clang module cache directory used by LLDB. Defaults to /module-cache-lldb.", + ) + group.add_argument( + "--clang-module-cache-dir", + dest="clang_module_cache_dir", + metavar="The clang module cache directory used by Clang", + help="The clang module cache directory used in the Make files by Clang while building tests. Defaults to /module-cache-clang.", + ) + group.add_argument( + "--lldb-libs-dir", + dest="lldb_libs_dir", + metavar="path", + help="The path to LLDB library directory (containing liblldb)", + ) + group.add_argument( + "--enable-plugin", + dest="enabled_plugins", + action="append", type=str, - metavar='A plugin whose tests will be enabled', - help='A plugin whose tests will be enabled. The only currently supported plugin is intel-pt.') + metavar="A plugin whose tests will be enabled", + help="A plugin whose tests will be enabled. The only currently supported plugin is intel-pt.", + ) # Configuration options - group = parser.add_argument_group('Remote platform options') - group.add_argument( - '--platform-name', - dest='lldb_platform_name', - metavar='platform-name', - help='The name of a remote platform to use') - group.add_argument( - '--platform-url', - dest='lldb_platform_url', - metavar='platform-url', - help='A LLDB platform URL to use when connecting to a remote platform to run the test suite') - group.add_argument( - '--platform-working-dir', - dest='lldb_platform_working_dir', - metavar='platform-working-dir', - help='The directory to use on the remote platform.') + group = parser.add_argument_group("Remote platform options") + group.add_argument( + "--platform-name", + dest="lldb_platform_name", + metavar="platform-name", + help="The name of a remote platform to use", + ) + group.add_argument( + "--platform-url", + dest="lldb_platform_url", + metavar="platform-url", + help="A LLDB platform URL to use when connecting to a remote platform to run the test suite", + ) + group.add_argument( + "--platform-working-dir", + dest="lldb_platform_working_dir", + metavar="platform-working-dir", + help="The directory to use on the remote platform.", + ) # Test-suite behaviour - group = parser.add_argument_group('Runtime behaviour options') - X('-d', 'Suspend the process after launch to wait indefinitely for a debugger to attach') - X('-t', 'Turn on tracing of lldb command and other detailed test executions') - group.add_argument( - '-u', - dest='unset_env_varnames', - metavar='variable', - action='append', - help='Specify an environment variable to unset before running the test cases. e.g., -u DYLD_INSERT_LIBRARIES -u MallocScribble') - group.add_argument( - '--env', - dest='set_env_vars', - metavar='variable', - action='append', - help='Specify an environment variable to set to the given value before running the test cases e.g.: --env CXXFLAGS=-O3 --env DYLD_INSERT_LIBRARIES') - group.add_argument( - '--inferior-env', - dest='set_inferior_env_vars', - metavar='variable', - action='append', - help='Specify an environment variable to set to the given value for the inferior.') - X('-v', 'Do verbose mode of unittest framework (print out each test case invocation)') - group.add_argument( - '--enable-crash-dialog', - dest='disable_crash_dialog', - action='store_false', - help='(Windows only) When LLDB crashes, display the Windows crash dialog.') + group = parser.add_argument_group("Runtime behaviour options") + X( + "-d", + "Suspend the process after launch to wait indefinitely for a debugger to attach", + ) + X("-t", "Turn on tracing of lldb command and other detailed test executions") + group.add_argument( + "-u", + dest="unset_env_varnames", + metavar="variable", + action="append", + help="Specify an environment variable to unset before running the test cases. e.g., -u DYLD_INSERT_LIBRARIES -u MallocScribble", + ) + group.add_argument( + "--env", + dest="set_env_vars", + metavar="variable", + action="append", + help="Specify an environment variable to set to the given value before running the test cases e.g.: --env CXXFLAGS=-O3 --env DYLD_INSERT_LIBRARIES", + ) + group.add_argument( + "--inferior-env", + dest="set_inferior_env_vars", + metavar="variable", + action="append", + help="Specify an environment variable to set to the given value for the inferior.", + ) + X( + "-v", + "Do verbose mode of unittest framework (print out each test case invocation)", + ) + group.add_argument( + "--enable-crash-dialog", + dest="disable_crash_dialog", + action="store_false", + help="(Windows only) When LLDB crashes, display the Windows crash dialog.", + ) group.set_defaults(disable_crash_dialog=True) # Remove the reference to our helper function del X - group = parser.add_argument_group('Test directories') + group = parser.add_argument_group("Test directories") group.add_argument( - 'args', - metavar='test-dir', - nargs='*', - help='Specify a list of directory names to search for test modules named after Test*.py (test discovery). If empty, search from the current working directory instead.') + "args", + metavar="test-dir", + nargs="*", + help="Specify a list of directory names to search for test modules named after Test*.py (test discovery). If empty, search from the current working directory instead.", + ) return parser diff --git a/lldb/packages/Python/lldbsuite/test/gdbclientutils.py b/lldb/packages/Python/lldbsuite/test/gdbclientutils.py --- a/lldb/packages/Python/lldbsuite/test/gdbclientutils.py +++ b/lldb/packages/Python/lldbsuite/test/gdbclientutils.py @@ -6,6 +6,7 @@ import traceback from lldbsuite.support import seven + def checksum(message): """ Calculate the GDB server protocol checksum of the message. @@ -40,8 +41,8 @@ out = "" for c in message: d = ord(c) - if d in (0x23, 0x24, 0x7d): - out += chr(0x7d) + if d in (0x23, 0x24, 0x7D): + out += chr(0x7D) out += chr(d ^ 0x20) else: out += c @@ -68,7 +69,7 @@ hex_len = len(hex_bytes) i = 0 while i < hex_len - 1: - out += chr(int(hex_bytes[i:i + 2], 16)) + out += chr(int(hex_bytes[i : i + 2], 16)) i += 2 return out @@ -87,7 +88,9 @@ registerCount = 40 packetLog = None - class RESPONSE_DISCONNECT: pass + + class RESPONSE_DISCONNECT: + pass def __init__(self): self.packetLog = [] @@ -113,19 +116,19 @@ if packet[0] == "G": # Gxxxxxxxxxxx # Gxxxxxxxxxxx;thread:1234; - return self.writeRegisters(packet[1:].split(';')[0]) + return self.writeRegisters(packet[1:].split(";")[0]) if packet[0] == "p": - regnum = packet[1:].split(';')[0] + regnum = packet[1:].split(";")[0] return self.readRegister(int(regnum, 16)) if packet[0] == "P": register, value = packet[1:].split("=") return self.writeRegister(int(register, 16), value) if packet[0] == "m": - addr, length = [int(x, 16) for x in packet[1:].split(',')] + addr, length = [int(x, 16) for x in packet[1:].split(",")] return self.readMemory(addr, length) if packet[0] == "M": location, encoded_data = packet[1:].split(":") - addr, length = [int(x, 16) for x in location.split(',')] + addr, length = [int(x, 16) for x in location.split(",")] return self.writeMemory(addr, encoded_data) if packet[0:7] == "qSymbol": return self.qSymbol(packet[8:]) @@ -152,25 +155,25 @@ return self.selectThread(packet[1], int(tid, 16)) if packet[0:6] == "qXfer:": obj, read, annex, location = packet[6:].split(":") - offset, length = [int(x, 16) for x in location.split(',')] + offset, length = [int(x, 16) for x in location.split(",")] data, has_more = self.qXferRead(obj, annex, offset, length) if data is not None: return self._qXferResponse(data, has_more) return "" if packet.startswith("vAttach;"): - pid = packet.partition(';')[2] + pid = packet.partition(";")[2] return self.vAttach(int(pid, 16)) if packet[0] == "Z": return self.setBreakpoint(packet) if packet.startswith("qThreadStopInfo"): - threadnum = int (packet[15:], 16) + threadnum = int(packet[15:], 16) return self.threadStopInfo(threadnum) if packet == "QThreadSuffixSupported": return self.QThreadSuffixSupported() if packet == "QListThreadsInStopReply": return self.QListThreadsInStopReply() if packet.startswith("qMemoryRegionInfo:"): - return self.qMemoryRegionInfo(int(packet.split(':')[1], 16)) + return self.qMemoryRegionInfo(int(packet.split(":")[1], 16)) if packet == "qQueryGDBServer": return self.qQueryGDBServer() if packet == "qHostInfo": @@ -178,7 +181,7 @@ if packet == "qGetWorkingDir": return self.qGetWorkingDir() if packet == "qOffsets": - return self.qOffsets(); + return self.qOffsets() if packet == "qProcessInfo": return self.qProcessInfo() if packet == "qsProcessInfo": @@ -200,7 +203,7 @@ if packet.startswith("QEnvironmentHexEncoded:"): return self.QEnvironmentHexEncoded(packet) if packet.startswith("qRegisterInfo"): - regnum = int(packet[len("qRegisterInfo"):], 16) + regnum = int(packet[len("qRegisterInfo") :], 16) return self.qRegisterInfo(regnum) if packet == "k": return self.k() @@ -346,6 +349,7 @@ Override the responder class to implement behavior suitable for the test at hand. """ + class UnexpectedPacketException(Exception): pass @@ -416,7 +420,8 @@ class TCPServerSocket(ServerSocket): def __init__(self): family, type, proto, _, addr = socket.getaddrinfo( - "localhost", 0, proto=socket.IPPROTO_TCP)[0] + "localhost", 0, proto=socket.IPPROTO_TCP + )[0] super().__init__(family, type, proto, addr) def get_connect_address(self): @@ -441,10 +446,11 @@ def __init__(self): import pty import tty + primary, secondary = pty.openpty() tty.setraw(primary) - self._primary = io.FileIO(primary, 'r+b') - self._secondary = io.FileIO(secondary, 'r+b') + self._primary = io.FileIO(primary, "r+b") + self._secondary = io.FileIO(secondary, "r+b") def get_connect_address(self): libc = ctypes.CDLL(None) @@ -465,7 +471,7 @@ except OSError as e: # closing the pty results in EIO on Linux, convert it to EOF if e.errno == errno.EIO: - return b'' + return b"" raise def sendall(self, data): @@ -528,7 +534,9 @@ except self.TerminateConnectionException: pass except Exception as e: - print("An exception happened when receiving the response from the gdb server. Closing the client...") + print( + "An exception happened when receiving the response from the gdb server. Closing the client..." + ) traceback.print_exc() finally: self._socket.close_connection() @@ -567,22 +575,23 @@ # If we're looking at the start of the received data, that means # we're looking for the start of a new packet, denoted by a $. # It's also possible we'll see an ACK here, denoted by a + - if data[0] == '+': + if data[0] == "+": self._receivedData = data[1:] return self.PACKET_ACK if ord(data[0]) == 3: self._receivedData = data[1:] return self.PACKET_INTERRUPT - if data[0] == '$': + if data[0] == "$": i += 1 else: raise self.InvalidPacketException( - "Unexpected leading byte: %s" % data[0]) + "Unexpected leading byte: %s" % data[0] + ) # If we're looking beyond the start of the received data, then we're # looking for the end of the packet content, denoted by a #. # Note that we pick up searching from where we left off last time - while i < data_len and data[i] != '#': + while i < data_len and data[i] != "#": i += 1 # If there isn't enough data left for a checksum, just remember where @@ -596,14 +605,14 @@ packet = data[1:i] i += 1 try: - check = int(data[i:i + 2], 16) + check = int(data[i : i + 2], 16) except ValueError: raise self.InvalidPacketException("Checksum is not valid hex") i += 2 if check != checksum(packet): raise self.InvalidPacketException( - "Checksum %02x does not match content %02x" % - (check, checksum(packet))) + "Checksum %02x does not match content %02x" % (check, checksum(packet)) + ) # remove parsed bytes from _receivedData and reset offset so parsing # can start on the next packet the next time around self._receivedData = data[i:] @@ -623,7 +632,7 @@ # We'll handle the ack stuff here since it's not something any of the # tests will be concerned about, and it'll get turned off quickly anyway. if self._shouldSendAck: - self._socket.sendall(seven.bitcast_to_bytes('+')) + self._socket.sendall(seven.bitcast_to_bytes("+")) if packet == "QStartNoAckMode": self._shouldSendAck = False response = "OK" diff --git a/lldb/packages/Python/lldbsuite/test/lldb_pylint_helper.py b/lldb/packages/Python/lldbsuite/test/lldb_pylint_helper.py --- a/lldb/packages/Python/lldbsuite/test/lldb_pylint_helper.py +++ b/lldb/packages/Python/lldbsuite/test/lldb_pylint_helper.py @@ -113,16 +113,14 @@ try: lldb_module_path = None - if platform.system() == 'Darwin': + if platform.system() == "Darwin": # Use xcrun to find the selected lldb. lldb_module_path = subprocess.check_output(["xcrun", "lldb", "-P"]) - elif platform.system() == 'Windows': - lldb_module_path = subprocess.check_output( - ["lldb.exe", "-P"], shell=True) + elif platform.system() == "Windows": + lldb_module_path = subprocess.check_output(["lldb.exe", "-P"], shell=True) else: # Use the shell to run lldb from the path. - lldb_module_path = subprocess.check_output( - ["lldb", "-P"], shell=True) + lldb_module_path = subprocess.check_output(["lldb", "-P"], shell=True) # Trim the result. if lldb_module_path is not None: @@ -145,24 +143,27 @@ """ def child_dirs(parent_dir): - return [os.path.join(parent_dir, child) - for child in os.listdir(parent_dir) - if os.path.isdir(os.path.join(parent_dir, child))] + return [ + os.path.join(parent_dir, child) + for child in os.listdir(parent_dir) + if os.path.isdir(os.path.join(parent_dir, child)) + ] check_dir = os.path.realpath(check_dir) while check_dir and len(check_dir) > 0: # If the current directory contains a packages/Python # directory, add that directory to the path. - packages_python_child_dir = os.path.join( - check_dir, "packages", "Python") + packages_python_child_dir = os.path.join(check_dir, "packages", "Python") if os.path.exists(packages_python_child_dir): sys.path.insert(0, packages_python_child_dir) - sys.path.insert(0, os.path.join( - packages_python_child_dir, "test_runner", "lib")) + sys.path.insert( + 0, os.path.join(packages_python_child_dir, "test_runner", "lib") + ) # Handle third_party module/package directory. third_party_module_dir = os.path.join( - check_dir, "third_party", "Python", "module") + check_dir, "third_party", "Python", "module" + ) for child_dir in child_dirs(third_party_module_dir): # Yes, we embed the module in the module parent dir sys.path.insert(0, child_dir) diff --git a/lldb/packages/Python/lldbsuite/test/lldbbench.py b/lldb/packages/Python/lldbsuite/test/lldbbench.py --- a/lldb/packages/Python/lldbsuite/test/lldbbench.py +++ b/lldb/packages/Python/lldbsuite/test/lldbbench.py @@ -65,8 +65,7 @@ if self.__start__ is None: self.__start__ = time.time() else: - raise Exception( - "start() already called, did you forget to stop() first?") + raise Exception("start() already called, did you forget to stop() first?") # Return self to facilitate the context manager __enter__ protocol. return self @@ -96,8 +95,13 @@ # return numpy.std(self.__nums__) def __str__(self): - return "Avg: %f (Laps: %d, Total Elapsed Time: %f, min=%f, max=%f)" % (self.avg( - ), self.__laps__, self.__total_elapsed__, min(self.__nums__), max(self.__nums__)) + return "Avg: %f (Laps: %d, Total Elapsed Time: %f, min=%f, max=%f)" % ( + self.avg(), + self.__laps__, + self.__total_elapsed__, + min(self.__nums__), + max(self.__nums__), + ) class BenchBase(TestBase): diff --git a/lldb/packages/Python/lldbsuite/test/lldbdwarf.py b/lldb/packages/Python/lldbsuite/test/lldbdwarf.py --- a/lldb/packages/Python/lldbsuite/test/lldbdwarf.py +++ b/lldb/packages/Python/lldbsuite/test/lldbdwarf.py @@ -3,187 +3,185 @@ import lldb # DWARF Expression operators. -DW_OP_addr = 0x03 -DW_OP_deref = 0x06 -DW_OP_const1u = 0x08 -DW_OP_const1s = 0x09 -DW_OP_const2u = 0x0A -DW_OP_const2s = 0x0B -DW_OP_const4u = 0x0C -DW_OP_const4s = 0x0D -DW_OP_const8u = 0x0E -DW_OP_const8s = 0x0F -DW_OP_constu = 0x10 -DW_OP_consts = 0x11 -DW_OP_dup = 0x12 -DW_OP_drop = 0x13 -DW_OP_over = 0x14 -DW_OP_pick = 0x15 -DW_OP_swap = 0x16 -DW_OP_rot = 0x17 -DW_OP_xderef = 0x18 -DW_OP_abs = 0x19 -DW_OP_and = 0x1A -DW_OP_div = 0x1B -DW_OP_minus = 0x1C -DW_OP_mod = 0x1D -DW_OP_mul = 0x1E -DW_OP_neg = 0x1F -DW_OP_not = 0x20 -DW_OP_or = 0x21 -DW_OP_plus = 0x22 -DW_OP_plus_uconst = 0x23 -DW_OP_shl = 0x24 -DW_OP_shr = 0x25 -DW_OP_shra = 0x26 -DW_OP_xor = 0x27 -DW_OP_skip = 0x2F -DW_OP_bra = 0x28 -DW_OP_eq = 0x29 -DW_OP_ge = 0x2A -DW_OP_gt = 0x2B -DW_OP_le = 0x2C -DW_OP_lt = 0x2D -DW_OP_ne = 0x2E -DW_OP_lit0 = 0x30 -DW_OP_lit1 = 0x31 -DW_OP_lit2 = 0x32 -DW_OP_lit3 = 0x33 -DW_OP_lit4 = 0x34 -DW_OP_lit5 = 0x35 -DW_OP_lit6 = 0x36 -DW_OP_lit7 = 0x37 -DW_OP_lit8 = 0x38 -DW_OP_lit9 = 0x39 -DW_OP_lit10 = 0x3A -DW_OP_lit11 = 0x3B -DW_OP_lit12 = 0x3C -DW_OP_lit13 = 0x3D -DW_OP_lit14 = 0x3E -DW_OP_lit15 = 0x3F -DW_OP_lit16 = 0x40 -DW_OP_lit17 = 0x41 -DW_OP_lit18 = 0x42 -DW_OP_lit19 = 0x43 -DW_OP_lit20 = 0x44 -DW_OP_lit21 = 0x45 -DW_OP_lit22 = 0x46 -DW_OP_lit23 = 0x47 -DW_OP_lit24 = 0x48 -DW_OP_lit25 = 0x49 -DW_OP_lit26 = 0x4A -DW_OP_lit27 = 0x4B -DW_OP_lit28 = 0x4C -DW_OP_lit29 = 0x4D -DW_OP_lit30 = 0x4E -DW_OP_lit31 = 0x4F -DW_OP_reg0 = 0x50 -DW_OP_reg1 = 0x51 -DW_OP_reg2 = 0x52 -DW_OP_reg3 = 0x53 -DW_OP_reg4 = 0x54 -DW_OP_reg5 = 0x55 -DW_OP_reg6 = 0x56 -DW_OP_reg7 = 0x57 -DW_OP_reg8 = 0x58 -DW_OP_reg9 = 0x59 -DW_OP_reg10 = 0x5A -DW_OP_reg11 = 0x5B -DW_OP_reg12 = 0x5C -DW_OP_reg13 = 0x5D -DW_OP_reg14 = 0x5E -DW_OP_reg15 = 0x5F -DW_OP_reg16 = 0x60 -DW_OP_reg17 = 0x61 -DW_OP_reg18 = 0x62 -DW_OP_reg19 = 0x63 -DW_OP_reg20 = 0x64 -DW_OP_reg21 = 0x65 -DW_OP_reg22 = 0x66 -DW_OP_reg23 = 0x67 -DW_OP_reg24 = 0x68 -DW_OP_reg25 = 0x69 -DW_OP_reg26 = 0x6A -DW_OP_reg27 = 0x6B -DW_OP_reg28 = 0x6C -DW_OP_reg29 = 0x6D -DW_OP_reg30 = 0x6E -DW_OP_reg31 = 0x6F -DW_OP_breg0 = 0x70 -DW_OP_breg1 = 0x71 -DW_OP_breg2 = 0x72 -DW_OP_breg3 = 0x73 -DW_OP_breg4 = 0x74 -DW_OP_breg5 = 0x75 -DW_OP_breg6 = 0x76 -DW_OP_breg7 = 0x77 -DW_OP_breg8 = 0x78 -DW_OP_breg9 = 0x79 -DW_OP_breg10 = 0x7A -DW_OP_breg11 = 0x7B -DW_OP_breg12 = 0x7C -DW_OP_breg13 = 0x7D -DW_OP_breg14 = 0x7E -DW_OP_breg15 = 0x7F -DW_OP_breg16 = 0x80 -DW_OP_breg17 = 0x81 -DW_OP_breg18 = 0x82 -DW_OP_breg19 = 0x83 -DW_OP_breg20 = 0x84 -DW_OP_breg21 = 0x85 -DW_OP_breg22 = 0x86 -DW_OP_breg23 = 0x87 -DW_OP_breg24 = 0x88 -DW_OP_breg25 = 0x89 -DW_OP_breg26 = 0x8A -DW_OP_breg27 = 0x8B -DW_OP_breg28 = 0x8C -DW_OP_breg29 = 0x8D -DW_OP_breg30 = 0x8E -DW_OP_breg31 = 0x8F -DW_OP_regx = 0x90 -DW_OP_fbreg = 0x91 -DW_OP_bregx = 0x92 -DW_OP_piece = 0x93 -DW_OP_deref_size = 0x94 -DW_OP_xderef_size = 0x95 -DW_OP_nop = 0x96 -DW_OP_push_object_address = 0x97 -DW_OP_call2 = 0x98 -DW_OP_call4 = 0x99 -DW_OP_call_ref = 0x9A -DW_OP_form_tls_address = 0x9B -DW_OP_call_frame_cfa = 0x9C -DW_OP_bit_piece = 0x9D -DW_OP_implicit_value = 0x9E -DW_OP_stack_value = 0x9F -DW_OP_lo_user = 0xE0 -DW_OP_GNU_push_tls_address = 0xE0 -DW_OP_hi_user = 0xFF +DW_OP_addr = 0x03 +DW_OP_deref = 0x06 +DW_OP_const1u = 0x08 +DW_OP_const1s = 0x09 +DW_OP_const2u = 0x0A +DW_OP_const2s = 0x0B +DW_OP_const4u = 0x0C +DW_OP_const4s = 0x0D +DW_OP_const8u = 0x0E +DW_OP_const8s = 0x0F +DW_OP_constu = 0x10 +DW_OP_consts = 0x11 +DW_OP_dup = 0x12 +DW_OP_drop = 0x13 +DW_OP_over = 0x14 +DW_OP_pick = 0x15 +DW_OP_swap = 0x16 +DW_OP_rot = 0x17 +DW_OP_xderef = 0x18 +DW_OP_abs = 0x19 +DW_OP_and = 0x1A +DW_OP_div = 0x1B +DW_OP_minus = 0x1C +DW_OP_mod = 0x1D +DW_OP_mul = 0x1E +DW_OP_neg = 0x1F +DW_OP_not = 0x20 +DW_OP_or = 0x21 +DW_OP_plus = 0x22 +DW_OP_plus_uconst = 0x23 +DW_OP_shl = 0x24 +DW_OP_shr = 0x25 +DW_OP_shra = 0x26 +DW_OP_xor = 0x27 +DW_OP_skip = 0x2F +DW_OP_bra = 0x28 +DW_OP_eq = 0x29 +DW_OP_ge = 0x2A +DW_OP_gt = 0x2B +DW_OP_le = 0x2C +DW_OP_lt = 0x2D +DW_OP_ne = 0x2E +DW_OP_lit0 = 0x30 +DW_OP_lit1 = 0x31 +DW_OP_lit2 = 0x32 +DW_OP_lit3 = 0x33 +DW_OP_lit4 = 0x34 +DW_OP_lit5 = 0x35 +DW_OP_lit6 = 0x36 +DW_OP_lit7 = 0x37 +DW_OP_lit8 = 0x38 +DW_OP_lit9 = 0x39 +DW_OP_lit10 = 0x3A +DW_OP_lit11 = 0x3B +DW_OP_lit12 = 0x3C +DW_OP_lit13 = 0x3D +DW_OP_lit14 = 0x3E +DW_OP_lit15 = 0x3F +DW_OP_lit16 = 0x40 +DW_OP_lit17 = 0x41 +DW_OP_lit18 = 0x42 +DW_OP_lit19 = 0x43 +DW_OP_lit20 = 0x44 +DW_OP_lit21 = 0x45 +DW_OP_lit22 = 0x46 +DW_OP_lit23 = 0x47 +DW_OP_lit24 = 0x48 +DW_OP_lit25 = 0x49 +DW_OP_lit26 = 0x4A +DW_OP_lit27 = 0x4B +DW_OP_lit28 = 0x4C +DW_OP_lit29 = 0x4D +DW_OP_lit30 = 0x4E +DW_OP_lit31 = 0x4F +DW_OP_reg0 = 0x50 +DW_OP_reg1 = 0x51 +DW_OP_reg2 = 0x52 +DW_OP_reg3 = 0x53 +DW_OP_reg4 = 0x54 +DW_OP_reg5 = 0x55 +DW_OP_reg6 = 0x56 +DW_OP_reg7 = 0x57 +DW_OP_reg8 = 0x58 +DW_OP_reg9 = 0x59 +DW_OP_reg10 = 0x5A +DW_OP_reg11 = 0x5B +DW_OP_reg12 = 0x5C +DW_OP_reg13 = 0x5D +DW_OP_reg14 = 0x5E +DW_OP_reg15 = 0x5F +DW_OP_reg16 = 0x60 +DW_OP_reg17 = 0x61 +DW_OP_reg18 = 0x62 +DW_OP_reg19 = 0x63 +DW_OP_reg20 = 0x64 +DW_OP_reg21 = 0x65 +DW_OP_reg22 = 0x66 +DW_OP_reg23 = 0x67 +DW_OP_reg24 = 0x68 +DW_OP_reg25 = 0x69 +DW_OP_reg26 = 0x6A +DW_OP_reg27 = 0x6B +DW_OP_reg28 = 0x6C +DW_OP_reg29 = 0x6D +DW_OP_reg30 = 0x6E +DW_OP_reg31 = 0x6F +DW_OP_breg0 = 0x70 +DW_OP_breg1 = 0x71 +DW_OP_breg2 = 0x72 +DW_OP_breg3 = 0x73 +DW_OP_breg4 = 0x74 +DW_OP_breg5 = 0x75 +DW_OP_breg6 = 0x76 +DW_OP_breg7 = 0x77 +DW_OP_breg8 = 0x78 +DW_OP_breg9 = 0x79 +DW_OP_breg10 = 0x7A +DW_OP_breg11 = 0x7B +DW_OP_breg12 = 0x7C +DW_OP_breg13 = 0x7D +DW_OP_breg14 = 0x7E +DW_OP_breg15 = 0x7F +DW_OP_breg16 = 0x80 +DW_OP_breg17 = 0x81 +DW_OP_breg18 = 0x82 +DW_OP_breg19 = 0x83 +DW_OP_breg20 = 0x84 +DW_OP_breg21 = 0x85 +DW_OP_breg22 = 0x86 +DW_OP_breg23 = 0x87 +DW_OP_breg24 = 0x88 +DW_OP_breg25 = 0x89 +DW_OP_breg26 = 0x8A +DW_OP_breg27 = 0x8B +DW_OP_breg28 = 0x8C +DW_OP_breg29 = 0x8D +DW_OP_breg30 = 0x8E +DW_OP_breg31 = 0x8F +DW_OP_regx = 0x90 +DW_OP_fbreg = 0x91 +DW_OP_bregx = 0x92 +DW_OP_piece = 0x93 +DW_OP_deref_size = 0x94 +DW_OP_xderef_size = 0x95 +DW_OP_nop = 0x96 +DW_OP_push_object_address = 0x97 +DW_OP_call2 = 0x98 +DW_OP_call4 = 0x99 +DW_OP_call_ref = 0x9A +DW_OP_form_tls_address = 0x9B +DW_OP_call_frame_cfa = 0x9C +DW_OP_bit_piece = 0x9D +DW_OP_implicit_value = 0x9E +DW_OP_stack_value = 0x9F +DW_OP_lo_user = 0xE0 +DW_OP_GNU_push_tls_address = 0xE0 +DW_OP_hi_user = 0xFF class DwarfOpcodeParser(object): - def updateRegInfoBitsize(self, reg_info, byte_order): - """ Update the regInfo bit size. """ + """Update the regInfo bit size.""" # Evaluate Dwarf Expression - expr_result = self.evaluateDwarfExpression(reg_info["dynamic_size_dwarf_expr_bytes"], - byte_order) + expr_result = self.evaluateDwarfExpression( + reg_info["dynamic_size_dwarf_expr_bytes"], byte_order + ) if expr_result == 0: reg_info["bitsize"] = 32 elif expr_result == 1: reg_info["bitsize"] = 64 - def evaluateDwarfExpression(self, dwarf_opcode, byte_order): - """Evaluate Dwarf Expression. """ + """Evaluate Dwarf Expression.""" - dwarf_opcode = [dwarf_opcode[i:i+2] for i in range(0,len(dwarf_opcode),2)] + dwarf_opcode = [dwarf_opcode[i : i + 2] for i in range(0, len(dwarf_opcode), 2)] dwarf_data = [] for index in range(len(dwarf_opcode)): - if index < len(dwarf_opcode): val = int(dwarf_opcode[index], 16) else: @@ -197,9 +195,16 @@ self.reset_test_sequence() # Read register value self.test_sequence.add_log_lines( - ["read packet: $p{0:x}#00".format(reg_no), - {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", - "capture": {1: "p_response"}}],True) + [ + "read packet: $p{0:x}#00".format(reg_no), + { + "direction": "send", + "regex": r"^\$([0-9a-fA-F]+)#", + "capture": {1: "p_response"}, + }, + ], + True, + ) Context = self.expect_gdbremote_sequence() self.assertIsNotNone(Context) @@ -207,13 +212,19 @@ self.assertIsNotNone(p_response) if byte_order == lldb.eByteOrderLittle: - # In case of little endian - # first decode the HEX ASCII bytes and then reverse it - # to get actual value of SR register - p_response = "".join(reversed([p_response[i:i+2] for i in range(0, - len(p_response),2)])) + # In case of little endian + # first decode the HEX ASCII bytes and then reverse it + # to get actual value of SR register + p_response = "".join( + reversed( + [ + p_response[i : i + 2] + for i in range(0, len(p_response), 2) + ] + ) + ) # Push register value - dwarf_data.append(int(p_response,16)) + dwarf_data.append(int(p_response, 16)) elif val == DW_OP_lit1: # Push literal 1 @@ -252,4 +263,3 @@ self.assertTrue(len(dwarf_data) == 1) expr_result = dwarf_data.pop() return expr_result - diff --git a/lldb/packages/Python/lldbsuite/test/lldbgdbclient.py b/lldb/packages/Python/lldbsuite/test/lldbgdbclient.py --- a/lldb/packages/Python/lldbsuite/test/lldbgdbclient.py +++ b/lldb/packages/Python/lldbsuite/test/lldbgdbclient.py @@ -4,6 +4,7 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.gdbclientutils import * + class GDBRemoteTestBase(TestBase): """ Base class for GDB client tests. @@ -52,8 +53,9 @@ """ listener = self.dbg.GetListener() error = lldb.SBError() - process = target.ConnectRemote(listener, - self.server.get_connect_url(), "gdb-remote", error) + process = target.ConnectRemote( + listener, self.server.get_connect_url(), "gdb-remote", error + ) self.assertTrue(error.Success(), error.description) self.assertTrue(process, PROCESS_IS_VALID) return process @@ -79,8 +81,10 @@ i += 1 j += 1 if i < len(packets): - self.fail(u"Did not receive: %s\nLast 10 packets:\n\t%s" % - (packets[i], u'\n\t'.join(log))) + self.fail( + "Did not receive: %s\nLast 10 packets:\n\t%s" + % (packets[i], "\n\t".join(log)) + ) class GDBPlatformClientTestBase(GDBRemoteTestBase): diff --git a/lldb/packages/Python/lldbsuite/test/lldbinline.py b/lldb/packages/Python/lldbsuite/test/lldbinline.py --- a/lldb/packages/Python/lldbsuite/test/lldbinline.py +++ b/lldb/packages/Python/lldbsuite/test/lldbinline.py @@ -15,25 +15,25 @@ from . import lldbutil from .decorators import * + def source_type(filename): _, extension = os.path.splitext(filename) return { - '.c': 'C_SOURCES', - '.cpp': 'CXX_SOURCES', - '.cxx': 'CXX_SOURCES', - '.cc': 'CXX_SOURCES', - '.m': 'OBJC_SOURCES', - '.mm': 'OBJCXX_SOURCES' + ".c": "C_SOURCES", + ".cpp": "CXX_SOURCES", + ".cxx": "CXX_SOURCES", + ".cc": "CXX_SOURCES", + ".m": "OBJC_SOURCES", + ".mm": "OBJCXX_SOURCES", }.get(extension, None) class CommandParser: - def __init__(self): self.breakpoints = [] def parse_one_command(self, line): - parts = line.split('//%') + parts = line.split("//%") command = None new_breakpoint = True @@ -46,7 +46,7 @@ def parse_source_files(self, source_files): for source_file in source_files: - file_handle = io.open(source_file, encoding='utf-8') + file_handle = io.open(source_file, encoding="utf-8") lines = file_handle.readlines() line_number = 0 # non-NULL means we're looking through whitespace to find @@ -62,30 +62,31 @@ if command is not None: if current_breakpoint is None: current_breakpoint = {} - current_breakpoint['file_name'] = source_file - current_breakpoint['line_number'] = line_number - current_breakpoint['command'] = command + current_breakpoint["file_name"] = source_file + current_breakpoint["line_number"] = line_number + current_breakpoint["command"] = command self.breakpoints.append(current_breakpoint) else: - current_breakpoint['command'] = current_breakpoint[ - 'command'] + "\n" + command + current_breakpoint["command"] = ( + current_breakpoint["command"] + "\n" + command + ) for bkpt in self.breakpoints: - bkpt['command'] = textwrap.dedent(bkpt['command']) + bkpt["command"] = textwrap.dedent(bkpt["command"]) def set_breakpoints(self, target): for breakpoint in self.breakpoints: - breakpoint['breakpoint'] = target.BreakpointCreateByLocation( - breakpoint['file_name'], breakpoint['line_number']) + breakpoint["breakpoint"] = target.BreakpointCreateByLocation( + breakpoint["file_name"], breakpoint["line_number"] + ) def handle_breakpoint(self, test, breakpoint_id): for breakpoint in self.breakpoints: - if breakpoint['breakpoint'].GetID() == breakpoint_id: - test.execute_user_command(breakpoint['command']) + if breakpoint["breakpoint"].GetID() == breakpoint_id: + test.execute_user_command(breakpoint["command"]) return class InlineTest(TestBase): - def getBuildDirBasename(self): return self.__class__.__name__ + "." + self.testMethodName @@ -103,17 +104,17 @@ else: categories[t] = [f] - with open(makefilePath, 'w+') as makefile: + with open(makefilePath, "w+") as makefile: for t in list(categories.keys()): line = t + " := " + " ".join(categories[t]) makefile.write(line + "\n") - if ('OBJCXX_SOURCES' in list(categories.keys())) or \ - ('OBJC_SOURCES' in list(categories.keys())): - makefile.write( - "LDFLAGS = $(CFLAGS) -lobjc -framework Foundation\n") + if ("OBJCXX_SOURCES" in list(categories.keys())) or ( + "OBJC_SOURCES" in list(categories.keys()) + ): + makefile.write("LDFLAGS = $(CFLAGS) -lobjc -framework Foundation\n") - if ('CXX_SOURCES' in list(categories.keys())): + if "CXX_SOURCES" in list(categories.keys()): makefile.write("CXXFLAGS += -std=c++11\n") makefile.write("include Makefile.rules\n") @@ -135,8 +136,7 @@ def do_test(self): exe = self.getBuildArtifact("a.out") - source_files = [f for f in os.listdir(self.getSourceDir()) - if source_type(f)] + source_files = [f for f in os.listdir(self.getSourceDir()) if source_type(f)] target = self.dbg.CreateTarget(exe) parser = CommandParser() @@ -150,18 +150,19 @@ while lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint): hit_breakpoints += 1 - thread = lldbutil.get_stopped_thread( - process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) for bp_id in self._get_breakpoint_ids(thread): parser.handle_breakpoint(self, bp_id) process.Continue() - self.assertTrue(hit_breakpoints > 0, - "inline test did not hit a single breakpoint") + self.assertTrue( + hit_breakpoints > 0, "inline test did not hit a single breakpoint" + ) # Either the process exited or the stepping plan is complete. - self.assertTrue(process.GetState() in [lldb.eStateStopped, - lldb.eStateExited], - PROCESS_EXITED) + self.assertTrue( + process.GetState() in [lldb.eStateStopped, lldb.eStateExited], + PROCESS_EXITED, + ) def check_expression(self, expression, expected_result, use_summary=True): value = self.frame().EvaluateExpression(expression) @@ -173,8 +174,7 @@ answer = value.GetSummary() else: answer = value.GetValue() - report_str = "%s expected: %s got: %s" % ( - expression, expected_result, answer) + report_str = "%s expected: %s got: %s" % (expression, expected_result, answer) self.assertTrue(answer == expected_result, report_str) @@ -183,13 +183,12 @@ if isinstance(decorators, list): for decorator in decorators: tmp = decorator(tmp) - elif hasattr(decorators, '__call__'): + elif hasattr(decorators, "__call__"): tmp = decorators(tmp) return tmp -def MakeInlineTest(__file, __globals, decorators=None, name=None, - build_dict=None): +def MakeInlineTest(__file, __globals, decorators=None, name=None, build_dict=None): # Adjust the filename if it ends in .pyc. We want filenames to # reflect the source python file, not the compiled variant. if __file is not None and __file.endswith(".pyc"): @@ -203,8 +202,9 @@ test_func = ApplyDecoratorsToFunction(InlineTest._test, decorators) # Build the test case - test_class = type(name, (InlineTest,), dict(test=test_func, - name=name, _build_dict=build_dict)) + test_class = type( + name, (InlineTest,), dict(test=test_func, name=name, _build_dict=build_dict) + ) # Add the test case to the globals, and hide InlineTest __globals.update({name: test_class}) diff --git a/lldb/packages/Python/lldbsuite/test/lldbpexpect.py b/lldb/packages/Python/lldbsuite/test/lldbpexpect.py --- a/lldb/packages/Python/lldbsuite/test/lldbpexpect.py +++ b/lldb/packages/Python/lldbsuite/test/lldbpexpect.py @@ -10,34 +10,40 @@ from . import lldbutil from lldbsuite.test.decorators import * + @skipIfRemote @skipIfWindows # llvm.org/pr22274: need a pexpect replacement for windows class PExpectTest(TestBase): - NO_DEBUG_INFO_TESTCASE = True PROMPT = "(lldb) " def expect_prompt(self): self.child.expect_exact(self.PROMPT) - def launch(self, executable=None, extra_args=None, timeout=60, - dimensions=None, run_under=None, post_spawn=None, - use_colors=False): - logfile = getattr(sys.stdout, 'buffer', - sys.stdout) if self.TraceOn() else None + def launch( + self, + executable=None, + extra_args=None, + timeout=60, + dimensions=None, + run_under=None, + post_spawn=None, + use_colors=False, + ): + logfile = getattr(sys.stdout, "buffer", sys.stdout) if self.TraceOn() else None args = [] if run_under is not None: args += run_under - args += [lldbtest_config.lldbExec, '--no-lldbinit'] + args += [lldbtest_config.lldbExec, "--no-lldbinit"] if not use_colors: - args.append('--no-use-colors') + args.append("--no-use-colors") for cmd in self.setUpCommands(): if "use-color false" in cmd and use_colors: continue - args += ['-O', cmd] + args += ["-O", cmd] if executable is not None: - args += ['--file', executable] + args += ["--file", executable] if extra_args is not None: args.extend(extra_args) @@ -46,11 +52,17 @@ env["HOME"] = self.getBuildDir() import pexpect + self.child = pexpect.spawn( - args[0], args=args[1:], logfile=logfile, - timeout=timeout, dimensions=dimensions, env=env) - self.child.ptyproc.delayafterclose = timeout/10 - self.child.ptyproc.delayafterterminate = timeout/10 + args[0], + args=args[1:], + logfile=logfile, + timeout=timeout, + dimensions=dimensions, + env=env, + ) + self.child.ptyproc.delayafterclose = timeout / 10 + self.child.ptyproc.delayafterterminate = timeout / 10 if post_spawn is not None: post_spawn() @@ -66,11 +78,10 @@ self.expect_prompt() def expect(self, cmd, substrs=None): - self.assertNotIn('\n', cmd) + self.assertNotIn("\n", cmd) # If 'substrs' is a string then this code would just check that every # character of the string is in the output. - assert not isinstance(substrs, str), \ - "substrs must be a collection of strings" + assert not isinstance(substrs, str), "substrs must be a collection of strings" self.child.sendline(cmd) if substrs is not None: diff --git a/lldb/packages/Python/lldbsuite/test/lldbplatform.py b/lldb/packages/Python/lldbsuite/test/lldbplatform.py --- a/lldb/packages/Python/lldbsuite/test/lldbplatform.py +++ b/lldb/packages/Python/lldbsuite/test/lldbplatform.py @@ -8,9 +8,23 @@ # LLDB modules import lldb -windows, linux, macosx, darwin, ios, tvos, watchos, bridgeos, darwin_all, \ - darwin_embedded, darwin_simulator, freebsd, netbsd, bsd_all, android \ - = range(15) +( + windows, + linux, + macosx, + darwin, + ios, + tvos, + watchos, + bridgeos, + darwin_all, + darwin_embedded, + darwin_simulator, + freebsd, + netbsd, + bsd_all, + android, +) = range(15) __darwin_embedded = ["ios", "tvos", "watchos", "bridgeos"] __darwin_simulators = ["iphonesimulator", "watchsimulator", "appletvsimulator"] @@ -30,12 +44,11 @@ freebsd: ["freebsd"], netbsd: ["netbsd"], bsd_all: ["freebsd", "netbsd"], - android: ["android"] + android: ["android"], } def translate(values): - if isinstance(values, int): # This is a value from the platform enumeration, translate it. return __name_lookup[values] diff --git a/lldb/packages/Python/lldbsuite/test/lldbplatformutil.py b/lldb/packages/Python/lldbsuite/test/lldbplatformutil.py --- a/lldb/packages/Python/lldbsuite/test/lldbplatformutil.py +++ b/lldb/packages/Python/lldbsuite/test/lldbplatformutil.py @@ -20,23 +20,24 @@ def check_first_register_readable(test_case): arch = test_case.getArchitecture() - if arch in ['x86_64', 'i386']: - test_case.expect("register read eax", substrs=['eax = 0x']) - elif arch in ['arm', 'armv7', 'armv7k', 'armv8l', 'armv7l']: - test_case.expect("register read r0", substrs=['r0 = 0x']) - elif arch in ['aarch64', 'arm64', 'arm64e', 'arm64_32']: - test_case.expect("register read x0", substrs=['x0 = 0x']) + if arch in ["x86_64", "i386"]: + test_case.expect("register read eax", substrs=["eax = 0x"]) + elif arch in ["arm", "armv7", "armv7k", "armv8l", "armv7l"]: + test_case.expect("register read r0", substrs=["r0 = 0x"]) + elif arch in ["aarch64", "arm64", "arm64e", "arm64_32"]: + test_case.expect("register read x0", substrs=["x0 = 0x"]) elif re.match("mips", arch): - test_case.expect("register read zero", substrs=['zero = 0x']) - elif arch in ['s390x']: - test_case.expect("register read r0", substrs=['r0 = 0x']) - elif arch in ['powerpc64le']: - test_case.expect("register read r0", substrs=['r0 = 0x']) + test_case.expect("register read zero", substrs=["zero = 0x"]) + elif arch in ["s390x"]: + test_case.expect("register read r0", substrs=["r0 = 0x"]) + elif arch in ["powerpc64le"]: + test_case.expect("register read r0", substrs=["r0 = 0x"]) else: # TODO: Add check for other architectures test_case.fail( - "Unsupported architecture for test case (arch: %s)" % - test_case.getArchitecture()) + "Unsupported architecture for test case (arch: %s)" + % test_case.getArchitecture() + ) def _run_adb_command(cmd, device_id): @@ -44,10 +45,7 @@ if device_id: device_id_args = ["-s", device_id] full_cmd = ["adb"] + device_id_args + cmd - p = subprocess.Popen( - full_cmd, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE) + p = subprocess.Popen(full_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() return p.returncode, stdout, stderr @@ -55,26 +53,28 @@ def target_is_android(): return configuration.lldb_platform_name == "remote-android" + def android_device_api(): - if not hasattr(android_device_api, 'result'): + if not hasattr(android_device_api, "result"): assert configuration.lldb_platform_url is not None device_id = None parsed_url = urlparse(configuration.lldb_platform_url) host_name = parsed_url.netloc.split(":")[0] - if host_name != 'localhost': + if host_name != "localhost": device_id = host_name - if device_id.startswith('[') and device_id.endswith(']'): + if device_id.startswith("[") and device_id.endswith("]"): device_id = device_id[1:-1] retcode, stdout, stderr = _run_adb_command( - ["shell", "getprop", "ro.build.version.sdk"], device_id) + ["shell", "getprop", "ro.build.version.sdk"], device_id + ) if retcode == 0: android_device_api.result = int(stdout) else: raise LookupError( ">>> Unable to determine the API level of the Android device.\n" ">>> stdout:\n%s\n" - ">>> stderr:\n%s\n" % - (stdout, stderr)) + ">>> stderr:\n%s\n" % (stdout, stderr) + ) return android_device_api.result @@ -102,14 +102,14 @@ # Use the triple to determine the platform if set. triple = p.GetTriple() if triple: - platform = triple.split('-')[2] - if platform.startswith('freebsd'): - platform = 'freebsd' - elif platform.startswith('netbsd'): - platform = 'netbsd' + platform = triple.split("-")[2] + if platform.startswith("freebsd"): + platform = "freebsd" + elif platform.startswith("netbsd"): + platform = "netbsd" return platform - return '' + return "" def getHostPlatform(): @@ -120,16 +120,17 @@ def getDarwinOSTriples(): return lldbplatform.translate(lldbplatform.darwin_all) + def getPlatform(): """Returns the target platform which the tests are running on.""" # Use the Apple SDK to determine the platform if set. if configuration.apple_sdk: platform = configuration.apple_sdk - dot = platform.find('.') + dot = platform.find(".") if dot != -1: platform = platform[:dot] - if platform == 'iphoneos': - platform = 'ios' + if platform == "iphoneos": + platform = "ios" return platform return _get_platform_os(lldb.selected_platform) @@ -147,9 +148,9 @@ if getPlatform() in lldbplatform.translate(lldbplatform.darwin_embedded): return "/Developer/usr/lib/libMainThreadChecker.dylib" - with os.popen('xcode-select -p') as output: + with os.popen("xcode-select -p") as output: xcode_developer_path = output.read().strip() - mtc_dylib_path = '%s/usr/lib/libMainThreadChecker.dylib' % xcode_developer_path + mtc_dylib_path = "%s/usr/lib/libMainThreadChecker.dylib" % xcode_developer_path if os.path.isfile(mtc_dylib_path): return mtc_dylib_path @@ -159,7 +160,9 @@ class _PlatformContext(object): """Value object class which contains platform-specific options.""" - def __init__(self, shlib_environment_var, shlib_path_separator, shlib_prefix, shlib_extension): + def __init__( + self, shlib_environment_var, shlib_path_separator, shlib_prefix, shlib_extension + ): self.shlib_environment_var = shlib_environment_var self.shlib_path_separator = shlib_path_separator self.shlib_prefix = shlib_prefix @@ -168,16 +171,18 @@ def createPlatformContext(): if platformIsDarwin(): - return _PlatformContext('DYLD_LIBRARY_PATH', ':', 'lib', 'dylib') + return _PlatformContext("DYLD_LIBRARY_PATH", ":", "lib", "dylib") elif getPlatform() in ("freebsd", "linux", "netbsd"): - return _PlatformContext('LD_LIBRARY_PATH', ':', 'lib', 'so') + return _PlatformContext("LD_LIBRARY_PATH", ":", "lib", "so") else: - return _PlatformContext('PATH', ';', '', 'dll') + return _PlatformContext("PATH", ";", "", "dll") def hasChattyStderr(test_case): """Some targets produce garbage on the standard error output. This utility function determines whether the tests can be strict about the expected stderr contents.""" - if match_android_device(test_case.getArchitecture(), ['aarch64'], range(22, 25+1)): + if match_android_device( + test_case.getArchitecture(), ["aarch64"], range(22, 25 + 1) + ): return True # The dynamic linker on the device will complain about unknown DT entries return False diff --git a/lldb/packages/Python/lldbsuite/test/lldbtest.py b/lldb/packages/Python/lldbsuite/test/lldbtest.py --- a/lldb/packages/Python/lldbsuite/test/lldbtest.py +++ b/lldb/packages/Python/lldbsuite/test/lldbtest.py @@ -68,8 +68,7 @@ # LLDB_COMMAND_TRACE is set from '-t' option. # By default, traceAlways is False. -if "LLDB_COMMAND_TRACE" in os.environ and os.environ[ - "LLDB_COMMAND_TRACE"] == "YES": +if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"] == "YES": traceAlways = True else: traceAlways = False @@ -132,13 +131,17 @@ STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint" STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % ( - STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'") + STOPPED_DUE_TO_BREAKPOINT, + "instead, the actual stop reason is: '%s'", +) STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition" STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count" -STOPPED_DUE_TO_BREAKPOINT_JITTED_CONDITION = "Stopped due to breakpoint jitted condition" +STOPPED_DUE_TO_BREAKPOINT_JITTED_CONDITION = ( + "Stopped due to breakpoint jitted condition" +) STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal" @@ -176,49 +179,56 @@ def CMD_MSG(str): - '''A generic "Command '%s' did not return successfully" message generator.''' + """A generic "Command '%s' did not return successfully" message generator.""" return "Command '%s' did not return successfully" % str def COMPLETION_MSG(str_before, str_after, completions): - '''A generic assertion failed message generator for the completion mechanism.''' - return ("'%s' successfully completes to '%s', but completions were:\n%s" - % (str_before, str_after, "\n".join(completions))) + """A generic assertion failed message generator for the completion mechanism.""" + return "'%s' successfully completes to '%s', but completions were:\n%s" % ( + str_before, + str_after, + "\n".join(completions), + ) def EXP_MSG(str, actual, exe): - '''A generic "'%s' returned unexpected result" message generator if exe. - Otherwise, it generates "'%s' does not match expected result" message.''' + """A generic "'%s' returned unexpected result" message generator if exe. + Otherwise, it generates "'%s' does not match expected result" message.""" return "'%s' %s result, got '%s'" % ( - str, 'returned unexpected' if exe else 'does not match expected', actual.strip()) + str, + "returned unexpected" if exe else "does not match expected", + actual.strip(), + ) def SETTING_MSG(setting): - '''A generic "Value of setting '%s' is not correct" message generator.''' + """A generic "Value of setting '%s' is not correct" message generator.""" return "Value of setting '%s' is not correct" % setting def line_number(filename, string_to_match): """Helper function to return the line number of the first matched string.""" - with io.open(filename, mode='r', encoding="utf-8") as f: + with io.open(filename, mode="r", encoding="utf-8") as f: for i, line in enumerate(f): if line.find(string_to_match) != -1: # Found our match. return i + 1 - raise Exception( - "Unable to find '%s' within file %s" % - (string_to_match, filename)) + raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename)) + def get_line(filename, line_number): """Return the text of the line at the 1-based line number.""" - with io.open(filename, mode='r', encoding="utf-8") as f: + with io.open(filename, mode="r", encoding="utf-8") as f: return f.readlines()[line_number - 1] + def pointer_size(): """Return the pointer size of the host system.""" import ctypes - a_pointer = ctypes.c_void_p(0xffff) + + a_pointer = ctypes.c_void_p(0xFFFF) return 8 * ctypes.sizeof(a_pointer) @@ -226,7 +236,7 @@ """Returns true if fpath is an executable.""" if fpath == None: return False - if sys.platform == 'win32': + if sys.platform == "win32": if not fpath.endswith(".exe"): fpath += ".exe" return os.path.isfile(fpath) and os.access(fpath, os.X_OK) @@ -245,9 +255,17 @@ return exe_file return None + class ValueCheck: - def __init__(self, name=None, value=None, type=None, summary=None, - children=None, dereference=None): + def __init__( + self, + name=None, + value=None, + type=None, + summary=None, + children=None, + dereference=None, + ): """ :param name: The name that the SBValue should have. None if the summary should not be checked. @@ -287,28 +305,28 @@ test_base.assertSuccess(val.GetError()) # Python 3.6 doesn't declare a `re.Pattern` type, get the dynamic type. - pattern_type = type(re.compile('')) + pattern_type = type(re.compile("")) if self.expect_name: - test_base.assertEqual(self.expect_name, val.GetName(), - this_error_msg) + test_base.assertEqual(self.expect_name, val.GetName(), this_error_msg) if self.expect_value: if isinstance(self.expect_value, pattern_type): - test_base.assertRegex(val.GetValue(), self.expect_value, - this_error_msg) + test_base.assertRegex(val.GetValue(), self.expect_value, this_error_msg) else: - test_base.assertEqual(self.expect_value, val.GetValue(), - this_error_msg) + test_base.assertEqual(self.expect_value, val.GetValue(), this_error_msg) if self.expect_type: - test_base.assertEqual(self.expect_type, val.GetDisplayTypeName(), - this_error_msg) + test_base.assertEqual( + self.expect_type, val.GetDisplayTypeName(), this_error_msg + ) if self.expect_summary: if isinstance(self.expect_summary, pattern_type): - test_base.assertRegex(val.GetSummary(), self.expect_summary, - this_error_msg) + test_base.assertRegex( + val.GetSummary(), self.expect_summary, this_error_msg + ) else: - test_base.assertEqual(self.expect_summary, val.GetSummary(), - this_error_msg) + test_base.assertEqual( + self.expect_summary, val.GetSummary(), this_error_msg + ) if self.children is not None: self.check_value_children(test_base, val, error_msg) @@ -335,6 +353,7 @@ child_error = "Checking child with index " + str(i) + ":\n" + error_msg expected_child.check_value(test_base, actual_child, child_error) + class recording(io.StringIO): """ A nice little context manager for recording the debugger interactions into @@ -371,7 +390,6 @@ class _BaseProcess(object, metaclass=abc.ABCMeta): - @abc.abstractproperty def pid(self): """Returns process PID if has been launched already.""" @@ -386,7 +404,6 @@ class _LocalProcess(_BaseProcess): - def __init__(self, trace_on): self._proc = None self._trace_on = trace_on @@ -397,26 +414,24 @@ return self._proc.pid def launch(self, executable, args, extra_env): - env=None + env = None if extra_env: env = dict(os.environ) env.update([kv.split("=", 1) for kv in extra_env]) self._proc = Popen( [executable] + args, - stdout=open( - os.devnull) if not self._trace_on else None, + stdout=open(os.devnull) if not self._trace_on else None, stdin=PIPE, - env=env) + env=env, + ) def terminate(self): if self._proc.poll() is None: # Terminate _proc like it does the pexpect signals_to_try = [ - sig for sig in [ - 'SIGHUP', - 'SIGCONT', - 'SIGINT'] if sig in dir(signal)] + sig for sig in ["SIGHUP", "SIGCONT", "SIGINT"] if sig in dir(signal) + ] for sig in signals_to_try: try: self._proc.send_signal(getattr(signal, sig)) @@ -440,7 +455,6 @@ class _RemoteProcess(_BaseProcess): - def __init__(self, install_remote): self._pid = None self._install_remote = install_remote @@ -453,23 +467,25 @@ if self._install_remote: src_path = executable dst_path = lldbutil.join_remote_paths( - lldb.remote_platform.GetWorkingDirectory(), os.path.basename(executable)) + lldb.remote_platform.GetWorkingDirectory(), os.path.basename(executable) + ) dst_file_spec = lldb.SBFileSpec(dst_path, False) err = lldb.remote_platform.Install( - lldb.SBFileSpec(src_path, True), dst_file_spec) + lldb.SBFileSpec(src_path, True), dst_file_spec + ) if err.Fail(): raise Exception( - "remote_platform.Install('%s', '%s') failed: %s" % - (src_path, dst_path, err)) + "remote_platform.Install('%s', '%s') failed: %s" + % (src_path, dst_path, err) + ) else: dst_path = executable dst_file_spec = lldb.SBFileSpec(executable, False) launch_info = lldb.SBLaunchInfo(args) launch_info.SetExecutableFile(dst_file_spec, True) - launch_info.SetWorkingDirectory( - lldb.remote_platform.GetWorkingDirectory()) + launch_info.SetWorkingDirectory(lldb.remote_platform.GetWorkingDirectory()) # Redirect stdout and stderr to /dev/null launch_info.AddSuppressFileAction(1, False, True) @@ -481,19 +497,21 @@ err = lldb.remote_platform.Launch(launch_info) if err.Fail(): raise Exception( - "remote_platform.Launch('%s', '%s') failed: %s" % - (dst_path, args, err)) + "remote_platform.Launch('%s', '%s') failed: %s" % (dst_path, args, err) + ) self._pid = launch_info.GetProcessID() def terminate(self): lldb.remote_platform.Kill(self._pid) + def getsource_if_available(obj): """ Return the text of the source code for an object if available. Otherwise, a print representation is returned. """ import inspect + try: return inspect.getsource(obj) except: @@ -520,24 +538,25 @@ @staticmethod def compute_mydir(test_file): - '''Subclasses should call this function to correctly calculate the - required "mydir" attribute as follows: + """Subclasses should call this function to correctly calculate the + required "mydir" attribute as follows: - mydir = TestBase.compute_mydir(__file__) - ''' + mydir = TestBase.compute_mydir(__file__) + """ # /abs/path/to/packages/group/subdir/mytest.py -> group/subdir lldb_test_src = configuration.test_src_root if not test_file.startswith(lldb_test_src): raise Exception( "Test file '%s' must reside within lldb_test_src " - "(which is '%s')." % (test_file, lldb_test_src)) + "(which is '%s')." % (test_file, lldb_test_src) + ) return os.path.dirname(os.path.relpath(test_file, start=lldb_test_src)) def TraceOn(self): """Returns True if we are in trace mode (tracing detailed test execution).""" return traceAlways - def trace(self, *args,**kwargs): + def trace(self, *args, **kwargs): with recording(self, self.TraceOn()) as sbuf: print(*args, file=sbuf, **kwargs) @@ -582,7 +601,8 @@ print( "Call class-specific cleanup function for class:", cls, - file=sys.stderr) + file=sys.stderr, + ) try: cls.classCleanup() except: @@ -604,12 +624,12 @@ # confirm that the file is writeable host_log_path = "{}-host.log".format(log_basename) - open(host_log_path, 'w').close() + open(host_log_path, "w").close() self.log_files.append(host_log_path) log_enable = "log enable -Tpn -f {} ".format(host_log_path) for channel_with_categories in lldbtest_config.channels: - channel_then_categories = channel_with_categories.split(' ', 1) + channel_then_categories = channel_with_categories.split(" ", 1) channel = channel_then_categories[0] if len(channel_then_categories) > 1: categories = channel_then_categories[1] @@ -620,24 +640,23 @@ # communicate gdb-remote categories to debugserver os.environ["LLDB_DEBUGSERVER_LOG_FLAGS"] = categories - self.ci.HandleCommand( - log_enable + channel_with_categories, self.res) + self.ci.HandleCommand(log_enable + channel_with_categories, self.res) if not self.res.Succeeded(): raise Exception( - 'log enable failed (check LLDB_LOG_OPTION env variable)') + "log enable failed (check LLDB_LOG_OPTION env variable)" + ) # Communicate log path name to debugserver & lldb-server # For remote debugging, these variables need to be set when starting the platform # instance. if lldb.remote_platform is None: server_log_path = "{}-server.log".format(log_basename) - open(server_log_path, 'w').close() + open(server_log_path, "w").close() self.log_files.append(server_log_path) os.environ["LLDB_DEBUGSERVER_LOG_FILE"] = server_log_path # Communicate channels to lldb-server - os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join( - lldbtest_config.channels) + os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join(lldbtest_config.channels) self.addTearDownHook(self.disableLogChannelsForCurrentTest) @@ -645,11 +664,12 @@ # close all log files that we opened for channel_and_categories in lldbtest_config.channels: # channel format - [ [ ...]] - channel = channel_and_categories.split(' ', 1)[0] + channel = channel_and_categories.split(" ", 1)[0] self.ci.HandleCommand("log disable " + channel, self.res) if not self.res.Succeeded(): raise Exception( - 'log disable failed (check LLDB_LOG_OPTION env variable)') + "log disable failed (check LLDB_LOG_OPTION env variable)" + ) # Retrieve the server log (if any) from the remote system. It is assumed the server log # is writing to the "server.log" file in the current test directory. This can be @@ -658,23 +678,28 @@ if lldb.remote_platform: server_log_path = self.getLogBasenameForCurrentTest() + "-server.log" if lldb.remote_platform.Get( - lldb.SBFileSpec("server.log"), - lldb.SBFileSpec(server_log_path)).Success(): + lldb.SBFileSpec("server.log"), lldb.SBFileSpec(server_log_path) + ).Success(): self.log_files.append(server_log_path) def setPlatformWorkingDir(self): if not lldb.remote_platform or not configuration.lldb_platform_working_dir: return - components = self.mydir.split(os.path.sep) + [str(self.test_number), self.getBuildDirBasename()] + components = self.mydir.split(os.path.sep) + [ + str(self.test_number), + self.getBuildDirBasename(), + ] remote_test_dir = configuration.lldb_platform_working_dir for c in components: remote_test_dir = lldbutil.join_remote_paths(remote_test_dir, c) error = lldb.remote_platform.MakeDirectory( - remote_test_dir, 448) # 448 = 0o700 + remote_test_dir, 448 + ) # 448 = 0o700 if error.Fail(): - raise Exception("making remote directory '%s': %s" % ( - remote_test_dir, error)) + raise Exception( + "making remote directory '%s': %s" % (remote_test_dir, error) + ) lldb.remote_platform.SetWorkingDirectory(remote_test_dir) @@ -686,9 +711,9 @@ # TODO: Make it working on Windows when we need it for remote debugging support # TODO: Replace the heuristic to remove the files with a logic what collects the # list of files we have to remove during test runs. - shell_cmd = lldb.SBPlatformShellCommand( - "rm %s/*" % remote_test_dir) + shell_cmd = lldb.SBPlatformShellCommand("rm %s/*" % remote_test_dir) lldb.remote_platform.Run(shell_cmd) + self.addTearDownHook(clean_working_directory) def getSourceDir(self): @@ -700,8 +725,9 @@ def getBuildDir(self): """Return the full path to the current test.""" - return os.path.join(configuration.test_build_dir, self.mydir, - self.getBuildDirBasename()) + return os.path.join( + configuration.test_build_dir, self.mydir, self.getBuildDirBasename() + ) def makeBuildDir(self): """Create the test-specific working directory, deleting any previous @@ -724,43 +750,45 @@ commands = [ # First of all, clear all settings to have clean state of global properties. "settings clear -all", - # Disable Spotlight lookup. The testsuite creates # different binaries with the same UUID, because they only # differ in the debug info, which is not being hashed. "settings set symbols.enable-external-lookup false", - # Inherit the TCC permissions from the inferior's parent. "settings set target.inherit-tcc true", - # Kill rather than detach from the inferior if something goes wrong. "settings set target.detach-on-error false", - # Disable fix-its by default so that incorrect expressions in tests don't # pass just because Clang thinks it has a fix-it. "settings set target.auto-apply-fixits false", - # Testsuite runs in parallel and the host can have also other load. "settings set plugin.process.gdb-remote.packet-timeout 60", - 'settings set symbols.clang-modules-cache-path "{}"'.format( - configuration.lldb_module_cache_dir), + configuration.lldb_module_cache_dir + ), "settings set use-color false", ] # Set any user-overridden settings. for setting, value in configuration.settings: - commands.append('setting set %s %s'%(setting, value)) + commands.append("setting set %s %s" % (setting, value)) # Make sure that a sanitizer LLDB's environment doesn't get passed on. - if cls.platformContext and cls.platformContext.shlib_environment_var in os.environ: - commands.append('settings set target.env-vars {}='.format( - cls.platformContext.shlib_environment_var)) + if ( + cls.platformContext + and cls.platformContext.shlib_environment_var in os.environ + ): + commands.append( + "settings set target.env-vars {}=".format( + cls.platformContext.shlib_environment_var + ) + ) # Set environment variables for the inferior. if lldbtest_config.inferior_env: - commands.append('settings set target.env-vars {}'.format( - lldbtest_config.inferior_env)) + commands.append( + "settings set target.env-vars {}".format(lldbtest_config.inferior_env) + ) return commands def setUp(self): @@ -768,7 +796,7 @@ It works with the test driver to conditionally skip tests and does other initializations.""" - #import traceback + # import traceback # traceback.print_stack() if "LIBCXX_PATH" in os.environ: @@ -781,8 +809,7 @@ else: self.lldbVSCodeExec = None - self.lldbOption = " ".join( - "-o '" + s + "'" for s in self.setUpCommands()) + self.lldbOption = " ".join("-o '" + s + "'" for s in self.setUpCommands()) # If we spawn an lldb process for test (via pexpect), do not load the # init file unless told otherwise. @@ -825,7 +852,7 @@ # before creating the first log file. self.makeBuildDir() - session_file = self.getLogBasenameForCurrentTest()+".log" + session_file = self.getLogBasenameForCurrentTest() + ".log" self.log_files.append(session_file) # Python 3 doesn't support unbuffered I/O in text mode. Open buffered. @@ -862,12 +889,12 @@ self.dbg.SetSelectedPlatform(lldb.selected_platform) if not self.dbg: - raise Exception('Invalid debugger instance') + raise Exception("Invalid debugger instance") # Retrieve the associated command interpreter instance. self.ci = self.dbg.GetCommandInterpreter() if not self.ci: - raise Exception('Could not get the command interpreter') + raise Exception("Could not get the command interpreter") # And the result object. self.res = lldb.SBCommandReturnObject() @@ -881,14 +908,14 @@ if sys.platform.startswith("darwin") and configuration.lldb_framework_path: framework = configuration.lldb_framework_path - lib = os.path.join(framework, 'LLDB') + lib = os.path.join(framework, "LLDB") if os.path.exists(lib): self.framework_dir = os.path.dirname(framework) self.lib_lldb = lib self.darwinWithFramework = self.platformIsDarwin() def setAsync(self, value): - """ Sets async mode to True/False and ensures it is reset after the testcase completes.""" + """Sets async mode to True/False and ensures it is reset after the testcase completes.""" old_async = self.dbg.GetAsync() self.dbg.SetAsync(value) self.addTearDownHook(lambda: self.dbg.SetAsync(old_async)) @@ -901,11 +928,14 @@ del self.subprocesses[:] def spawnSubprocess(self, executable, args=[], extra_env=None, install_remote=True): - """ Creates a subprocess.Popen object with the specified executable and arguments, - saves it in self.subprocesses, and returns the object. + """Creates a subprocess.Popen object with the specified executable and arguments, + saves it in self.subprocesses, and returns the object. """ - proc = _RemoteProcess( - install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn()) + proc = ( + _RemoteProcess(install_remote) + if lldb.remote_platform + else _LocalProcess(self.TraceOn()) + ) proc.launch(executable, args, extra_env=extra_env) self.subprocesses.append(proc) return proc @@ -932,10 +962,11 @@ self.sys_stdout_hidden = True old_stdout = sys.stdout - sys.stdout = open(os.devnull, 'w') + sys.stdout = open(os.devnull, "w") def restore_stdout(): sys.stdout = old_stdout + self.addTearDownHook(restore_stdout) # ======================================================================= @@ -960,10 +991,7 @@ """ if callable(hook): with recording(self, traceAlways) as sbuf: - print( - "Adding tearDown hook:", - getsource_if_available(hook), - file=sbuf) + print("Adding tearDown hook:", getsource_if_available(hook), file=sbuf) self.hooks.append(hook) return self @@ -973,21 +1001,22 @@ # using pexpect. if self.child and self.child.isalive(): import pexpect + with recording(self, traceAlways) as sbuf: print("tearing down the child process....", file=sbuf) try: if self.child_in_script_interpreter: - self.child.sendline('quit()') + self.child.sendline("quit()") self.child.expect_exact(self.child_prompt) - self.child.sendline( - 'settings set interpreter.prompt-on-quit false') - self.child.sendline('quit') + self.child.sendline("settings set interpreter.prompt-on-quit false") + self.child.sendline("quit") self.child.expect(pexpect.EOF) except (ValueError, pexpect.ExceptionPexpect): # child is already terminated pass except OSError as exception: import errno + if exception.errno != errno.EIO: # unexpected error raise @@ -1004,9 +1033,8 @@ for hook in reversed(self.hooks): with recording(self, traceAlways) as sbuf: print( - "Executing tearDown hook:", - getsource_if_available(hook), - file=sbuf) + "Executing tearDown hook:", getsource_if_available(hook), file=sbuf + ) if funcutils.requires_self(hook): hook(self) else: @@ -1039,7 +1067,6 @@ # Assert that the global module cache is empty. self.assertEqual(lldb.SBModule.GetNumberAllocatedModules(), 0) - # ========================================================= # Various callbacks to allow introspection of test progress # ========================================================= @@ -1078,9 +1105,7 @@ if bugnumber is None: print("expected failure", file=sbuf) else: - print( - "expected failure (problem id:" + str(bugnumber) + ")", - file=sbuf) + print("expected failure (problem id:" + str(bugnumber) + ")", file=sbuf) def markSkippedTest(self): """Callback invoked when a test is skipped.""" @@ -1102,8 +1127,8 @@ print("unexpected success", file=sbuf) else: print( - "unexpected success (problem id:" + str(bugnumber) + ")", - file=sbuf) + "unexpected success (problem id:" + str(bugnumber) + ")", file=sbuf + ) def getRerunArgs(self): return " -f %s.%s" % (self.__class__.__name__, self._testMethodName) @@ -1140,22 +1165,22 @@ pairs = [] if self.__errored__: pairs = configuration.test_result.errors - prefix = 'Error' + prefix = "Error" elif self.__cleanup_errored__: pairs = configuration.test_result.cleanup_errors - prefix = 'CleanupError' + prefix = "CleanupError" elif self.__failed__: pairs = configuration.test_result.failures - prefix = 'Failure' + prefix = "Failure" elif self.__expected__: pairs = configuration.test_result.expectedFailures - prefix = 'ExpectedFailure' + prefix = "ExpectedFailure" elif self.__skipped__: - prefix = 'SkippedTest' + prefix = "SkippedTest" elif self.__unexpected__: - prefix = 'UnexpectedSuccess' + prefix = "UnexpectedSuccess" else: - prefix = 'Success' + prefix = "Success" if not self.__unexpected__ and not self.__skipped__: for test, traceback in pairs: @@ -1163,15 +1188,17 @@ print(traceback, file=self.session) import datetime + print( "Session info generated @", datetime.datetime.now().ctime(), - file=self.session) + file=self.session, + ) self.session.close() del self.session # process the log files - if prefix != 'Success' or lldbtest_config.log_success: + if prefix != "Success" or lldbtest_config.log_success: # keep all log files, rename them to include prefix src_log_basename = self.getLogBasenameForCurrentTest() dst_log_basename = self.getLogBasenameForCurrentTest(prefix) @@ -1229,7 +1256,7 @@ cpuinfo_path = "/proc/cpuinfo" try: - with open(cpuinfo_path, 'r') as f: + with open(cpuinfo_path, "r") as f: cpuinfo = f.read() except: return "" @@ -1254,7 +1281,7 @@ def isAArch64Windows(self): """Returns true if the architecture is AArch64 and platform windows.""" - if self.getPlatform() == 'windows': + if self.getPlatform() == "windows": arch = self.getArchitecture().lower() return arch in ["aarch64", "arm64", "arm64e"] return False @@ -1263,33 +1290,34 @@ """Returns the architecture in effect the test suite is running with.""" module = builder_module() arch = module.getArchitecture() - if arch == 'amd64': - arch = 'x86_64' - if arch in ['armv7l', 'armv8l'] : - arch = 'arm' + if arch == "amd64": + arch = "x86_64" + if arch in ["armv7l", "armv8l"]: + arch = "arm" return arch def getLldbArchitecture(self): """Returns the architecture of the lldb binary.""" - if not hasattr(self, 'lldbArchitecture'): - + if not hasattr(self, "lldbArchitecture"): # These two target settings prevent lldb from doing setup that does # nothing but slow down the end goal of printing the architecture. command = [ lldbtest_config.lldbExec, "-x", "-b", - "-o", "settings set target.preload-symbols false", - "-o", "settings set target.load-script-from-symbol-file false", - "-o", "file " + lldbtest_config.lldbExec, + "-o", + "settings set target.preload-symbols false", + "-o", + "settings set target.load-script-from-symbol-file false", + "-o", + "file " + lldbtest_config.lldbExec, ] output = check_output(command) str = output.decode() for line in str.splitlines(): - m = re.search( - r"Current executable set to '.*' \((.*)\)\.", line) + m = re.search(r"Current executable set to '.*' \((.*)\)\.", line) if m: self.lldbArchitecture = m.group(1) break @@ -1306,35 +1334,36 @@ return self.getCompiler().split()[0] def getCompilerVersion(self): - """ Returns a string that represents the compiler version. - Supports: llvm, clang. + """Returns a string that represents the compiler version. + Supports: llvm, clang. """ compiler = self.getCompilerBinary() version_output = check_output([compiler, "--version"], errors="replace") - m = re.search('version ([0-9.]+)', version_output) + m = re.search("version ([0-9.]+)", version_output) if m: return m.group(1) - return 'unknown' + return "unknown" def getDwarfVersion(self): - """ Returns the dwarf version generated by clang or '0'. """ + """Returns the dwarf version generated by clang or '0'.""" if configuration.dwarf_version: return str(configuration.dwarf_version) - if 'clang' in self.getCompiler(): + if "clang" in self.getCompiler(): try: triple = builder_module().getTriple(self.getArchitecture()) - target = ['-target', triple] if triple else [] + target = ["-target", triple] if triple else [] driver_output = check_output( - [self.getCompiler()] + target + '-g -c -x c - -o - -###'.split(), - stderr=STDOUT) + [self.getCompiler()] + target + "-g -c -x c - -o - -###".split(), + stderr=STDOUT, + ) driver_output = driver_output.decode("utf-8") for line in driver_output.split(os.linesep): - m = re.search('dwarf-version=([0-9])', line) + m = re.search("dwarf-version=([0-9])", line) if m: return m.group(1) except CalledProcessError: pass - return '0' + return "0" def platformIsDarwin(self): """Returns true if the OS triple for the selected platform is any valid apple OS""" @@ -1348,18 +1377,18 @@ return lldbplatformutil.getPlatform() def isIntelCompiler(self): - """ Returns true if using an Intel (ICC) compiler, false otherwise. """ + """Returns true if using an Intel (ICC) compiler, false otherwise.""" return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]]) def expectedCompilerVersion(self, compiler_version): """Returns True iff compiler_version[1] matches the current compiler version. - Use compiler_version[0] to specify the operator used to determine if a match has occurred. - Any operator other than the following defaults to an equality test: - '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not' + Use compiler_version[0] to specify the operator used to determine if a match has occurred. + Any operator other than the following defaults to an equality test: + '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not' - If the current compiler version cannot be determined, we assume it is close to the top - of trunk, so any less-than or equal-to comparisons will return False, and any - greater-than or not-equal-to comparisons will return True. + If the current compiler version cannot be determined, we assume it is close to the top + of trunk, so any less-than or equal-to comparisons will return False, and any + greater-than or not-equal-to comparisons will return True. """ if compiler_version is None: return True @@ -1370,25 +1399,25 @@ return True test_compiler_version = self.getCompilerVersion() - if test_compiler_version == 'unknown': + if test_compiler_version == "unknown": # Assume the compiler version is at or near the top of trunk. - return operator in ['>', '>=', '!', '!=', 'not'] + return operator in [">", ">=", "!", "!=", "not"] - if operator == '>': + if operator == ">": return LooseVersion(test_compiler_version) > LooseVersion(version) - if operator == '>=' or operator == '=>': + if operator == ">=" or operator == "=>": return LooseVersion(test_compiler_version) >= LooseVersion(version) - if operator == '<': + if operator == "<": return LooseVersion(test_compiler_version) < LooseVersion(version) - if operator == '<=' or operator == '=<': + if operator == "<=" or operator == "=<": return LooseVersion(test_compiler_version) <= LooseVersion(version) - if operator == '!=' or operator == '!' or operator == 'not': + if operator == "!=" or operator == "!" or operator == "not": return str(version) not in str(test_compiler_version) return str(version) in str(test_compiler_version) def expectedCompiler(self, compilers): """Returns True iff any element of compilers is a sub-string of the current compiler.""" - if (compilers is None): + if compilers is None: return True for compiler in compilers: @@ -1399,7 +1428,7 @@ def expectedArch(self, archs): """Returns True iff any element of archs is a sub-string of the current architecture.""" - if (archs is None): + if archs is None: return True for arch in archs: @@ -1425,12 +1454,13 @@ return getattr(method, "debug_info", None) def build( - self, - debug_info=None, - architecture=None, - compiler=None, - dictionary=None, - make_targets=None): + self, + debug_info=None, + architecture=None, + compiler=None, + dictionary=None, + make_targets=None, + ): """Platform specific way to build binaries.""" if not architecture and configuration.arch: architecture = configuration.arch @@ -1444,8 +1474,15 @@ testname = self.getBuildDirBasename() module = builder_module() - command = builder_module().getBuildCommand(debug_info, architecture, - compiler, dictionary, testdir, testname, make_targets) + command = builder_module().getBuildCommand( + debug_info, + architecture, + compiler, + dictionary, + testdir, + testname, + make_targets, + ) if command is None: raise Exception("Don't know how to build binary") @@ -1459,21 +1496,24 @@ raise build_exception.BuildError(cpe) self.trace(output) - # ================================================== # Build methods supported through a plugin interface # ================================================== def getstdlibFlag(self): - """ Returns the proper -stdlib flag, or empty if not required.""" - if self.platformIsDarwin() or self.getPlatform() == "freebsd" or self.getPlatform() == "openbsd": + """Returns the proper -stdlib flag, or empty if not required.""" + if ( + self.platformIsDarwin() + or self.getPlatform() == "freebsd" + or self.getPlatform() == "openbsd" + ): stdlibflag = "-stdlib=libc++" else: # this includes NetBSD stdlibflag = "" return stdlibflag def getstdFlag(self): - """ Returns the proper stdflag. """ + """Returns the proper stdflag.""" if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion(): stdflag = "-std=c++0x" else: @@ -1481,95 +1521,97 @@ return stdflag def buildDriver(self, sources, exe_name): - """ Platform-specific way to build a program that links with LLDB (via the liblldb.so - or LLDB.framework). + """Platform-specific way to build a program that links with LLDB (via the liblldb.so + or LLDB.framework). """ stdflag = self.getstdFlag() stdlibflag = self.getstdlibFlag() lib_dir = configuration.lldb_libs_dir if self.hasDarwinFramework(): - d = {'CXX_SOURCES': sources, - 'EXE': exe_name, - 'CFLAGS_EXTRAS': "%s %s" % (stdflag, stdlibflag), - 'FRAMEWORK_INCLUDES': "-F%s" % self.framework_dir, - 'LD_EXTRAS': "%s -Wl,-rpath,%s" % (self.lib_lldb, self.framework_dir), - } - elif sys.platform.startswith('win'): d = { - 'CXX_SOURCES': sources, - 'EXE': exe_name, - 'CFLAGS_EXTRAS': "%s %s -I%s" % (stdflag, - stdlibflag, - os.path.join( - os.environ["LLDB_SRC"], - "include")), - 'LD_EXTRAS': "-L%s -lliblldb" % lib_dir} + "CXX_SOURCES": sources, + "EXE": exe_name, + "CFLAGS_EXTRAS": "%s %s" % (stdflag, stdlibflag), + "FRAMEWORK_INCLUDES": "-F%s" % self.framework_dir, + "LD_EXTRAS": "%s -Wl,-rpath,%s" % (self.lib_lldb, self.framework_dir), + } + elif sys.platform.startswith("win"): + d = { + "CXX_SOURCES": sources, + "EXE": exe_name, + "CFLAGS_EXTRAS": "%s %s -I%s" + % ( + stdflag, + stdlibflag, + os.path.join(os.environ["LLDB_SRC"], "include"), + ), + "LD_EXTRAS": "-L%s -lliblldb" % lib_dir, + } else: d = { - 'CXX_SOURCES': sources, - 'EXE': exe_name, - 'CFLAGS_EXTRAS': "%s %s -I%s" % (stdflag, - stdlibflag, - os.path.join( - os.environ["LLDB_SRC"], - "include")), - 'LD_EXTRAS': "-L%s -llldb -Wl,-rpath,%s" % (lib_dir, lib_dir)} + "CXX_SOURCES": sources, + "EXE": exe_name, + "CFLAGS_EXTRAS": "%s %s -I%s" + % ( + stdflag, + stdlibflag, + os.path.join(os.environ["LLDB_SRC"], "include"), + ), + "LD_EXTRAS": "-L%s -llldb -Wl,-rpath,%s" % (lib_dir, lib_dir), + } if self.TraceOn(): - print( - "Building LLDB Driver (%s) from sources %s" % - (exe_name, sources)) + print("Building LLDB Driver (%s) from sources %s" % (exe_name, sources)) self.build(dictionary=d) def buildLibrary(self, sources, lib_name): - """Platform specific way to build a default library. """ + """Platform specific way to build a default library.""" stdflag = self.getstdFlag() lib_dir = configuration.lldb_libs_dir if self.hasDarwinFramework(): - d = {'DYLIB_CXX_SOURCES': sources, - 'DYLIB_NAME': lib_name, - 'CFLAGS_EXTRAS': "%s -stdlib=libc++" % stdflag, - 'FRAMEWORK_INCLUDES': "-F%s" % self.framework_dir, - 'LD_EXTRAS': "%s -Wl,-rpath,%s -dynamiclib" % (self.lib_lldb, self.framework_dir), - } - elif self.getPlatform() == 'windows': d = { - 'DYLIB_CXX_SOURCES': sources, - 'DYLIB_NAME': lib_name, - 'CFLAGS_EXTRAS': "%s -I%s " % (stdflag, - os.path.join( - os.environ["LLDB_SRC"], - "include")), - 'LD_EXTRAS': "-shared -l%s\liblldb.lib" % lib_dir} + "DYLIB_CXX_SOURCES": sources, + "DYLIB_NAME": lib_name, + "CFLAGS_EXTRAS": "%s -stdlib=libc++" % stdflag, + "FRAMEWORK_INCLUDES": "-F%s" % self.framework_dir, + "LD_EXTRAS": "%s -Wl,-rpath,%s -dynamiclib" + % (self.lib_lldb, self.framework_dir), + } + elif self.getPlatform() == "windows": + d = { + "DYLIB_CXX_SOURCES": sources, + "DYLIB_NAME": lib_name, + "CFLAGS_EXTRAS": "%s -I%s " + % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")), + "LD_EXTRAS": "-shared -l%s\liblldb.lib" % lib_dir, + } else: d = { - 'DYLIB_CXX_SOURCES': sources, - 'DYLIB_NAME': lib_name, - 'CFLAGS_EXTRAS': "%s -I%s -fPIC" % (stdflag, - os.path.join( - os.environ["LLDB_SRC"], - "include")), - 'LD_EXTRAS': "-shared -L%s -llldb -Wl,-rpath,%s" % (lib_dir, lib_dir)} + "DYLIB_CXX_SOURCES": sources, + "DYLIB_NAME": lib_name, + "CFLAGS_EXTRAS": "%s -I%s -fPIC" + % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")), + "LD_EXTRAS": "-shared -L%s -llldb -Wl,-rpath,%s" % (lib_dir, lib_dir), + } if self.TraceOn(): - print( - "Building LLDB Library (%s) from sources %s" % - (lib_name, sources)) + print("Building LLDB Library (%s) from sources %s" % (lib_name, sources)) self.build(dictionary=d) def buildProgram(self, sources, exe_name): - """ Platform specific way to build an executable from C/C++ sources. """ - d = {'CXX_SOURCES': sources, - 'EXE': exe_name} + """Platform specific way to build an executable from C/C++ sources.""" + d = {"CXX_SOURCES": sources, "EXE": exe_name} self.build(dictionary=d) def signBinary(self, binary_path): if sys.platform.startswith("darwin"): - codesign_cmd = "codesign --force --sign \"%s\" %s" % ( - lldbtest_config.codesign_identity, binary_path) + codesign_cmd = 'codesign --force --sign "%s" %s' % ( + lldbtest_config.codesign_identity, + binary_path, + ) call(codesign_cmd, shell=True) def findBuiltClang(self): @@ -1580,8 +1622,7 @@ "llvm-build/Release/x86_64/bin/clang", "llvm-build/Debug/x86_64/bin/clang", ] - lldb_root_path = os.path.join( - os.path.dirname(__file__), "..", "..", "..", "..") + lldb_root_path = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..") for p in paths_to_try: path = os.path.join(lldb_root_path, p) if os.path.exists(path): @@ -1595,7 +1636,6 @@ return os.environ["CC"] - def yaml2obj(self, yaml_path, obj_path, max_size=None): """ Create an object file at the given path from a yaml file. @@ -1615,30 +1655,33 @@ module = builder_module() if not module.cleanup(dictionary): raise Exception( - "Don't know how to do cleanup with dictionary: " + - dictionary) + "Don't know how to do cleanup with dictionary: " + dictionary + ) def invoke(self, obj, name, trace=False): """Use reflection to call a method dynamically with no argument.""" - trace = (True if traceAlways else trace) + trace = True if traceAlways else trace method = getattr(obj, name) import inspect - self.assertTrue(inspect.ismethod(method), - name + "is a method name of object: " + str(obj)) + + self.assertTrue( + inspect.ismethod(method), name + "is a method name of object: " + str(obj) + ) result = method() with recording(self, trace) as sbuf: print(str(method) + ":", result, file=sbuf) return result def getLLDBLibraryEnvVal(self): - """ Returns the path that the OS-specific library search environment variable - (self.dylibPath) should be set to in order for a program to find the LLDB - library. If an environment variable named self.dylibPath is already set, - the new path is appended to it and returned. + """Returns the path that the OS-specific library search environment variable + (self.dylibPath) should be set to in order for a program to find the LLDB + library. If an environment variable named self.dylibPath is already set, + the new path is appended to it and returned. """ - existing_library_path = os.environ[ - self.dylibPath] if self.dylibPath in os.environ else None + existing_library_path = ( + os.environ[self.dylibPath] if self.dylibPath in os.environ else None + ) if existing_library_path: return "%s:%s" % (existing_library_path, configuration.lldb_libs_dir) if sys.platform.startswith("darwin") and configuration.lldb_framework_path: @@ -1646,10 +1689,10 @@ return configuration.lldb_libs_dir def getLibcPlusPlusLibs(self): - if self.getPlatform() in ('freebsd', 'linux', 'netbsd', 'openbsd'): - return ['libc++.so.1'] + if self.getPlatform() in ("freebsd", "linux", "netbsd", "openbsd"): + return ["libc++.so.1"] else: - return ['libc++.1.dylib', 'libc++abi.'] + return ["libc++.1.dylib", "libc++abi."] def run_platform_command(self, cmd): platform = self.dbg.GetSelectedPlatform() @@ -1659,8 +1702,8 @@ def get_stats(self, options=None): """ - Get the output of the "statistics dump" with optional extra options - and return the JSON as a python dictionary. + Get the output of the "statistics dump" with optional extra options + and return the JSON as a python dictionary. """ return_obj = lldb.SBCommandReturnObject() command = "statistics dump " @@ -1670,6 +1713,7 @@ metrics_json = return_obj.GetOutput() return json.loads(metrics_json) + # Metaclass for TestBase to change the list of test metods when a new TestCase is loaded. # We change the test methods to create a new test method for each test for each debug info we are # testing. The name of the new test method will be '_' and with adding @@ -1679,34 +1723,36 @@ class LLDBTestCaseFactory(type): - def __new__(cls, name, bases, attrs): - original_testcase = super( - LLDBTestCaseFactory, cls).__new__( - cls, name, bases, attrs) + original_testcase = super(LLDBTestCaseFactory, cls).__new__( + cls, name, bases, attrs + ) if original_testcase.NO_DEBUG_INFO_TESTCASE: return original_testcase newattrs = {} for attrname, attrvalue in attrs.items(): if attrname.startswith("test") and not getattr( - attrvalue, "__no_debug_info_test__", False): - + attrvalue, "__no_debug_info_test__", False + ): # If any debug info categories were explicitly tagged, assume that list to be # authoritative. If none were specified, try with all debug # info formats. - all_dbginfo_categories = set(test_categories.debug_info_categories.keys()) - categories = set( - getattr( - attrvalue, - "categories", - [])) & all_dbginfo_categories + all_dbginfo_categories = set( + test_categories.debug_info_categories.keys() + ) + categories = ( + set(getattr(attrvalue, "categories", [])) & all_dbginfo_categories + ) if not categories: - categories = [category for category, can_replicate \ - in test_categories.debug_info_categories.items() \ - if can_replicate] + categories = [ + category + for category, can_replicate in test_categories.debug_info_categories.items() + if can_replicate + ] for cat in categories: + @decorators.add_test_categories([cat]) @wraps(attrvalue) def test_method(self, attrvalue=attrvalue): @@ -1719,13 +1765,8 @@ else: newattrs[attrname] = attrvalue - return super( - LLDBTestCaseFactory, - cls).__new__( - cls, - name, - bases, - newattrs) + return super(LLDBTestCaseFactory, cls).__new__(cls, name, bases, newattrs) + # Setup the metaclass for this class to change the list of the test # methods when a new class is loaded @@ -1791,13 +1832,12 @@ timeWaitNextLaunch = 1.0 def generateSource(self, source): - template = source + '.template' + template = source + ".template" temp = os.path.join(self.getSourceDir(), template) - with open(temp, 'r') as f: + with open(temp, "r") as f: content = f.read() - public_api_dir = os.path.join( - os.environ["LLDB_SRC"], "include", "lldb", "API") + public_api_dir = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API") # Look under the include/lldb/API directory and add #include statements # for all the SB API headers. @@ -1806,14 +1846,19 @@ if self.hasDarwinFramework(): include_stmt = "'#include <%s>' % os.path.join('LLDB', header)" else: - include_stmt = "'#include <%s>' % os.path.join(r'" + public_api_dir + "', header)" - list = [eval(include_stmt) for header in public_headers if ( - header.startswith("SB") and header.endswith(".h"))] - includes = '\n'.join(list) - new_content = content.replace('%include_SB_APIs%', includes) - new_content = new_content.replace('%SOURCE_DIR%', self.getSourceDir()) + include_stmt = ( + "'#include <%s>' % os.path.join(r'" + public_api_dir + "', header)" + ) + list = [ + eval(include_stmt) + for header in public_headers + if (header.startswith("SB") and header.endswith(".h")) + ] + includes = "\n".join(list) + new_content = content.replace("%include_SB_APIs%", includes) + new_content = new_content.replace("%SOURCE_DIR%", self.getSourceDir()) src = os.path.join(self.getBuildDir(), source) - with open(src, 'w') as f: + with open(src, "w") as f: f.write(new_content) self.addTearDownHook(lambda: os.remove(src)) @@ -1830,8 +1875,7 @@ self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"]) if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ: - self.timeWaitNextLaunch = float( - os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"]) + self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"]) # We want our debugger to be synchronous. self.dbg.SetAsync(False) @@ -1839,25 +1883,25 @@ # Retrieve the associated command interpreter instance. self.ci = self.dbg.GetCommandInterpreter() if not self.ci: - raise Exception('Could not get the command interpreter') + raise Exception("Could not get the command interpreter") # And the result object. self.res = lldb.SBCommandReturnObject() def registerSharedLibrariesWithTarget(self, target, shlibs): - '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing + """If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing Any modules in the target that have their remote install file specification set will get uploaded to the remote host. This function registers the local copies of the shared libraries with the target and sets their remote install locations so they will be uploaded when the target is run. - ''' + """ if not shlibs or not self.platformContext: return None shlib_environment_var = self.platformContext.shlib_environment_var shlib_prefix = self.platformContext.shlib_prefix - shlib_extension = '.' + self.platformContext.shlib_extension + shlib_extension = "." + self.platformContext.shlib_extension dirs = [] # Add any shared libraries to our target if remote so they get @@ -1868,30 +1912,35 @@ # basename like "libFoo.so". So figure out which one it is and resolve the local copy # of the shared library accordingly if os.path.isfile(name): - local_shlib_path = name # name is the full path to the local shared library + local_shlib_path = ( + name # name is the full path to the local shared library + ) else: # Check relative names local_shlib_path = os.path.join( - self.getBuildDir(), shlib_prefix + name + shlib_extension) + self.getBuildDir(), shlib_prefix + name + shlib_extension + ) if not os.path.exists(local_shlib_path): local_shlib_path = os.path.join( - self.getBuildDir(), name + shlib_extension) + self.getBuildDir(), name + shlib_extension + ) if not os.path.exists(local_shlib_path): local_shlib_path = os.path.join(self.getBuildDir(), name) # Make sure we found the local shared library in the above code self.assertTrue(os.path.exists(local_shlib_path)) - # Add the shared library to our target shlib_module = target.AddModule(local_shlib_path, None, None, None) if lldb.remote_platform: # We must set the remote install location if we want the shared library # to get uploaded to the remote target - remote_shlib_path = lldbutil.append_to_process_working_directory(self, - os.path.basename(local_shlib_path)) + remote_shlib_path = lldbutil.append_to_process_working_directory( + self, os.path.basename(local_shlib_path) + ) shlib_module.SetRemoteInstallFileSpec( - lldb.SBFileSpec(remote_shlib_path, False)) + lldb.SBFileSpec(remote_shlib_path, False) + ) dir_to_add = self.get_process_working_directory() else: dir_to_add = os.path.dirname(local_shlib_path) @@ -1900,41 +1949,46 @@ dirs.append(dir_to_add) env_value = self.platformContext.shlib_path_separator.join(dirs) - return ['%s=%s' % (shlib_environment_var, env_value)] + return ["%s=%s" % (shlib_environment_var, env_value)] def registerSanitizerLibrariesWithTarget(self, target): runtimes = [] for m in target.module_iter(): libspec = m.GetFileSpec() if "clang_rt" in libspec.GetFilename(): - runtimes.append(os.path.join(libspec.GetDirectory(), - libspec.GetFilename())) + runtimes.append( + os.path.join(libspec.GetDirectory(), libspec.GetFilename()) + ) return self.registerSharedLibrariesWithTarget(target, runtimes) # utility methods that tests can use to access the current objects def target(self): if not self.dbg: - raise Exception('Invalid debugger instance') + raise Exception("Invalid debugger instance") return self.dbg.GetSelectedTarget() def process(self): if not self.dbg: - raise Exception('Invalid debugger instance') + raise Exception("Invalid debugger instance") return self.dbg.GetSelectedTarget().GetProcess() def thread(self): if not self.dbg: - raise Exception('Invalid debugger instance') + raise Exception("Invalid debugger instance") return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread() def frame(self): if not self.dbg: - raise Exception('Invalid debugger instance') - return self.dbg.GetSelectedTarget().GetProcess( - ).GetSelectedThread().GetSelectedFrame() + raise Exception("Invalid debugger instance") + return ( + self.dbg.GetSelectedTarget() + .GetProcess() + .GetSelectedThread() + .GetSelectedFrame() + ) def get_process_working_directory(self): - '''Get the working directory that should be used when launching processes for local or remote processes.''' + """Get the working directory that should be used when launching processes for local or remote processes.""" if lldb.remote_platform: # Remote tests set the platform working directory up in # TestBase.setUp() @@ -1976,15 +2030,17 @@ 'stop_reason'. If no such thread exists, no select action is done. """ from .lldbutil import stop_reason_to_str - self.runCmd('thread list') + + self.runCmd("thread list") output = self.res.GetOutput() thread_line_pattern = re.compile( - "^[ *] thread #([0-9]+):.*stop reason = %s" % - stop_reason_to_str(stop_reason)) + "^[ *] thread #([0-9]+):.*stop reason = %s" + % stop_reason_to_str(stop_reason) + ) for line in output.splitlines(): matched = thread_line_pattern.match(line) if matched: - self.runCmd('thread select %s' % matched.group(1)) + self.runCmd("thread select %s" % matched.group(1)) def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False): """ @@ -1995,12 +2051,12 @@ if cmd is None: raise Exception("Bad 'cmd' parameter encountered") - trace = (True if traceAlways else trace) + trace = True if traceAlways else trace if cmd.startswith("target create "): cmd = cmd.replace("target create ", "file ") - running = (cmd.startswith("run") or cmd.startswith("process launch")) + running = cmd.startswith("run") or cmd.startswith("process launch") for i in range(self.maxLaunchCount if running else 1): self.ci.HandleCommand(cmd, self.res, inHistory) @@ -2033,42 +2089,32 @@ msg += output if cmd: cmd += output - self.assertTrue(self.res.Succeeded(), - msg if (msg) else CMD_MSG(cmd)) + self.assertTrue(self.res.Succeeded(), msg if (msg) else CMD_MSG(cmd)) def match( - self, - str, - patterns, - msg=None, - trace=False, - error=False, - matching=True, - exe=True): + self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True + ): """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern - Otherwise, all the arguments have the same meanings as for the expect function""" + Otherwise, all the arguments have the same meanings as for the expect function + """ - trace = (True if traceAlways else trace) + trace = True if traceAlways else trace if exe: # First run the command. If we are expecting error, set check=False. # Pass the assert message along since it provides more semantic # info. - self.runCmd( - str, - msg=msg, - trace=( - True if trace else False), - check=not error) + self.runCmd(str, msg=msg, trace=(True if trace else False), check=not error) # Then compare the output against expected strings. output = self.res.GetError() if error else self.res.GetOutput() # If error is True, the API client expects the command to fail! if error: - self.assertFalse(self.res.Succeeded(), - "Command '" + str + "' is expected to fail!") + self.assertFalse( + self.res.Succeeded(), "Command '" + str + "' is expected to fail!" + ) else: # No execution required, just compare str against the golden input. output = str @@ -2088,12 +2134,16 @@ if matched: break - self.assertTrue(matched if matching else not matched, - msg if msg else EXP_MSG(str, output, exe)) + self.assertTrue( + matched if matching else not matched, + msg if msg else EXP_MSG(str, output, exe), + ) return match_object - def check_completion_with_desc(self, str_input, match_desc_pairs, enforce_order=False): + def check_completion_with_desc( + self, str_input, match_desc_pairs, enforce_order=False + ): """ Checks that when the given input is completed at the given list of completions and descriptions is returned. @@ -2107,7 +2157,9 @@ interp = self.dbg.GetCommandInterpreter() match_strings = lldb.SBStringList() description_strings = lldb.SBStringList() - num_matches = interp.HandleCompletionWithDescriptions(str_input, len(str_input), 0, -1, match_strings, description_strings) + num_matches = interp.HandleCompletionWithDescriptions( + str_input, len(str_input), 0, -1, match_strings, description_strings + ) self.assertEqual(len(description_strings), len(match_strings)) # The index of the last matched description in description_strings or @@ -2123,11 +2175,18 @@ if match_candidate == pair[0] and description_candidate == pair[1]: found_pair = True if enforce_order and last_found_index > i: - new_err = ("Found completion " + pair[0] + " at index " + - str(i) + " in returned completion list but " + - "should have been after completion " + - match_strings.GetStringAtIndex(last_found_index) + - " (index:" + str(last_found_index) + ")\n") + new_err = ( + "Found completion " + + pair[0] + + " at index " + + str(i) + + " in returned completion list but " + + "should have been after completion " + + match_strings.GetStringAtIndex(last_found_index) + + " (index:" + + str(last_found_index) + + ")\n" + ) out_of_order_errors += new_err last_found_index = i break @@ -2145,11 +2204,21 @@ got_failure = True error_msg += out_of_order_errors if got_failure: - error_msg += "Got the following " + str(num_matches) + " completions back:\n" + error_msg += ( + "Got the following " + str(num_matches) + " completions back:\n" + ) for i in range(num_matches + 1): match_candidate = match_strings.GetStringAtIndex(i) description_candidate = description_strings.GetStringAtIndex(i) - error_msg += "[" + match_candidate + ":" + description_candidate + "] index " + str(i) + "\n" + error_msg += ( + "[" + + match_candidate + + ":" + + description_candidate + + "] index " + + str(i) + + "\n" + ) self.assertFalse(got_failure, error_msg) def complete_exactly(self, str_input, patterns): @@ -2169,7 +2238,9 @@ interp = self.dbg.GetCommandInterpreter() match_strings = lldb.SBStringList() - num_matches = interp.HandleCompletion(str_input, len(str_input), 0, -1, match_strings) + num_matches = interp.HandleCompletion( + str_input, len(str_input), 0, -1, match_strings + ) common_match = match_strings.GetStringAtIndex(0) if num_matches == 0: compare_string = str_input @@ -2178,18 +2249,24 @@ compare_string = str_input + common_match else: compare_string = "" - for idx in range(1, num_matches+1): + for idx in range(1, num_matches + 1): compare_string += match_strings.GetStringAtIndex(idx) + "\n" for p in patterns: if turn_off_re_match: self.expect( - compare_string, msg=COMPLETION_MSG( - str_input, p, match_strings), exe=False, substrs=[p]) + compare_string, + msg=COMPLETION_MSG(str_input, p, match_strings), + exe=False, + substrs=[p], + ) else: self.expect( - compare_string, msg=COMPLETION_MSG( - str_input, p, match_strings), exe=False, patterns=[p]) + compare_string, + msg=COMPLETION_MSG(str_input, p, match_strings), + exe=False, + patterns=[p], + ) def completions_match(self, command, completions): """Checks that the completions for the given command are equal to the @@ -2198,8 +2275,9 @@ match_strings = lldb.SBStringList() interp.HandleCompletion(command, len(command), 0, -1, match_strings) # match_strings is a 1-indexed list, so we have to slice... - self.assertItemsEqual(completions, list(match_strings)[1:], - "List of returned completion is wrong") + self.assertItemsEqual( + completions, list(match_strings)[1:], "List of returned completion is wrong" + ) def completions_contain(self, command, completions): """Checks that the completions for the given command contain the given @@ -2209,31 +2287,29 @@ interp.HandleCompletion(command, len(command), 0, -1, match_strings) for completion in completions: # match_strings is a 1-indexed list, so we have to slice... - self.assertIn(completion, list(match_strings)[1:], - "Couldn't find expected completion") + self.assertIn( + completion, list(match_strings)[1:], "Couldn't find expected completion" + ) def filecheck( - self, - command, - check_file, - filecheck_options = '', - expect_cmd_failure = False): + self, command, check_file, filecheck_options="", expect_cmd_failure=False + ): # Run the command. self.runCmd( - command, - check=(not expect_cmd_failure), - msg="FileCheck'ing result of `{0}`".format(command)) + command, + check=(not expect_cmd_failure), + msg="FileCheck'ing result of `{0}`".format(command), + ) self.assertTrue((not expect_cmd_failure) == self.res.Succeeded()) # Get the error text if there was an error, and the regular text if not. - output = self.res.GetOutput() if self.res.Succeeded() \ - else self.res.GetError() + output = self.res.GetOutput() if self.res.Succeeded() else self.res.GetError() # Assemble the absolute path to the check file. As a convenience for # LLDB inline tests, assume that the check file is a relative path to # a file within the inline test directory. - if check_file.endswith('.pyc'): + if check_file.endswith(".pyc"): check_file = check_file[:-1] check_file_abs = os.path.abspath(check_file) @@ -2244,7 +2320,13 @@ filecheck_args = [filecheck_bin, check_file_abs] if filecheck_options: filecheck_args.append(filecheck_options) - subproc = Popen(filecheck_args, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines = True) + subproc = Popen( + filecheck_args, + stdin=PIPE, + stdout=PIPE, + stderr=PIPE, + universal_newlines=True, + ) cmd_stdout, cmd_stderr = subproc.communicate(input=output) cmd_status = subproc.returncode @@ -2259,7 +2341,9 @@ FileCheck output: {3} {4} -""".format(cmd_status, filecheck_cmd, output, cmd_stdout, cmd_stderr) +""".format( + cmd_status, filecheck_cmd, output, cmd_stdout, cmd_stderr + ) trace = cmd_status != 0 or traceAlways with recording(self, trace) as sbuf: @@ -2268,19 +2352,20 @@ self.assertTrue(cmd_status == 0) def expect( - self, - string, - msg=None, - patterns=None, - startstr=None, - endstr=None, - substrs=None, - trace=False, - error=False, - ordered=True, - matching=True, - exe=True, - inHistory=False): + self, + string, + msg=None, + patterns=None, + startstr=None, + endstr=None, + substrs=None, + trace=False, + error=False, + ordered=True, + matching=True, + exe=True, + inHistory=False, + ): """ Similar to runCmd; with additional expect style output matching ability. @@ -2319,12 +2404,10 @@ assert False, "expect() missing a matcher argument" # Check `patterns` and `substrs` are not accidentally given as strings. - assert not isinstance(patterns, str), \ - "patterns must be a collection of strings" - assert not isinstance(substrs, str), \ - "substrs must be a collection of strings" + assert not isinstance(patterns, str), "patterns must be a collection of strings" + assert not isinstance(substrs, str), "substrs must be a collection of strings" - trace = (True if traceAlways else trace) + trace = True if traceAlways else trace if exe: # First run the command. If we are expecting error, set check=False. @@ -2333,18 +2416,20 @@ self.runCmd( string, msg=msg, - trace=( - True if trace else False), + trace=(True if trace else False), check=not error, - inHistory=inHistory) + inHistory=inHistory, + ) # Then compare the output against expected strings. output = self.res.GetError() if error else self.res.GetOutput() # If error is True, the API client expects the command to fail! if error: - self.assertFalse(self.res.Succeeded(), - "Command '" + string + "' is expected to fail!") + self.assertFalse( + self.res.Succeeded(), + "Command '" + string + "' is expected to fail!", + ) else: # No execution required, just compare string against the golden input. if isinstance(string, lldb.SBCommandReturnObject): @@ -2355,15 +2440,16 @@ print("looking at:", output, file=sbuf) expecting_str = "Expecting" if matching else "Not expecting" + def found_str(matched): return "was found" if matched else "was not found" # To be used as assert fail message and/or trace content log_lines = [ - "{}:".format("Ran command" if exe else "Checking string"), - "\"{}\"".format(string), - # Space out command and output - "", + "{}:".format("Ran command" if exe else "Checking string"), + '"{}"'.format(string), + # Space out command and output + "", ] if exe: # Newline before output to make large strings more readable @@ -2377,13 +2463,19 @@ # We will stop checking on first failure if startstr: matched = output.startswith(startstr) - log_lines.append("{} start string: \"{}\" ({})".format( - expecting_str, startstr, found_str(matched))) + log_lines.append( + '{} start string: "{}" ({})'.format( + expecting_str, startstr, found_str(matched) + ) + ) if endstr and matched == matching: matched = output.endswith(endstr) - log_lines.append("{} end string: \"{}\" ({})".format( - expecting_str, endstr, found_str(matched))) + log_lines.append( + '{} end string: "{}" ({})'.format( + expecting_str, endstr, found_str(matched) + ) + ) if substrs and matched == matching: start = 0 @@ -2391,8 +2483,11 @@ index = output[start:].find(substr) start = start + index + len(substr) if ordered and matching else 0 matched = index != -1 - log_lines.append("{} sub string: \"{}\" ({})".format( - expecting_str, substr, found_str(matched))) + log_lines.append( + '{} sub string: "{}" ({})'.format( + expecting_str, substr, found_str(matched) + ) + ) if matched != matching: break @@ -2401,11 +2496,11 @@ for pattern in patterns: matched = re.search(pattern, output) - pattern_line = "{} regex pattern: \"{}\" ({}".format( - expecting_str, pattern, found_str(matched)) + pattern_line = '{} regex pattern: "{}" ({}'.format( + expecting_str, pattern, found_str(matched) + ) if matched: - pattern_line += ", matched \"{}\"".format( - matched.group(0)) + pattern_line += ', matched "{}"'.format(matched.group(0)) pattern_line += ")" log_lines.append(pattern_line) @@ -2426,13 +2521,13 @@ self.fail(log_msg) def expect_expr( - self, - expr, - result_summary=None, - result_value=None, - result_type=None, - result_children=None - ): + self, + expr, + result_summary=None, + result_value=None, + result_type=None, + result_children=None, + ): """ Evaluates the given expression and verifies the result. :param expr: The expression as a string. @@ -2442,7 +2537,10 @@ :param result_children: The expected children of the expression result as a list of ValueChecks. None if the children shouldn't be checked. """ - self.assertTrue(expr.strip() == expr, "Expression contains trailing/leading whitespace: '" + expr + "'") + self.assertTrue( + expr.strip() == expr, + "Expression contains trailing/leading whitespace: '" + expr + "'", + ) frame = self.frame() options = lldb.SBExpressionOptions() @@ -2464,19 +2562,18 @@ target = self.dbg.GetDummyTarget() eval_result = target.EvaluateExpression(expr, options) - value_check = ValueCheck(type=result_type, value=result_value, - summary=result_summary, children=result_children) + value_check = ValueCheck( + type=result_type, + value=result_value, + summary=result_summary, + children=result_children, + ) value_check.check_value(self, eval_result, str(eval_result)) return eval_result def expect_var_path( - self, - var_path, - summary=None, - value=None, - type=None, - children=None - ): + self, var_path, summary=None, value=None, type=None, children=None + ): """ Evaluates the given variable path and verifies the result. See also 'frame variable' and SBFrame.GetValueForVariablePath. @@ -2487,49 +2584,59 @@ :param children: The expected children of the variable as a list of ValueChecks. None if the children shouldn't be checked. """ - self.assertTrue(var_path.strip() == var_path, - "Expression contains trailing/leading whitespace: '" + var_path + "'") + self.assertTrue( + var_path.strip() == var_path, + "Expression contains trailing/leading whitespace: '" + var_path + "'", + ) frame = self.frame() eval_result = frame.GetValueForVariablePath(var_path) - value_check = ValueCheck(type=type, value=value, - summary=summary, children=children) + value_check = ValueCheck( + type=type, value=value, summary=summary, children=children + ) value_check.check_value(self, eval_result, str(eval_result)) return eval_result """Assert that an lldb.SBError is in the "success" state.""" + def assertSuccess(self, obj, msg=None): if not obj.Success(): error = obj.GetCString() - self.fail(self._formatMessage(msg, - "'{}' is not success".format(error))) + self.fail(self._formatMessage(msg, "'{}' is not success".format(error))) """Assert that a command return object is successful""" + def assertCommandReturn(self, obj, msg=None): if not obj.Succeeded(): error = obj.GetError() - self.fail(self._formatMessage(msg, - "'{}' is not success".format(error))) + self.fail(self._formatMessage(msg, "'{}' is not success".format(error))) """Assert two states are equal""" + def assertState(self, first, second, msg=None): if first != second: error = "{} ({}) != {} ({})".format( - lldbutil.state_type_to_str(first), first, - lldbutil.state_type_to_str(second), second) + lldbutil.state_type_to_str(first), + first, + lldbutil.state_type_to_str(second), + second, + ) self.fail(self._formatMessage(msg, error)) """Assert two stop reasons are equal""" + def assertStopReason(self, first, second, msg=None): if first != second: error = "{} ({}) != {} ({})".format( - lldbutil.stop_reason_to_str(first), first, - lldbutil.stop_reason_to_str(second), second) + lldbutil.stop_reason_to_str(first), + first, + lldbutil.stop_reason_to_str(second), + second, + ) self.fail(self._formatMessage(msg, error)) - def createTestTarget(self, file_path=None, msg=None, - load_dependent_modules=True): + def createTestTarget(self, file_path=None, msg=None, load_dependent_modules=True): """ Creates a target from the file found at the given file path. Asserts that the resulting target is valid. @@ -2543,11 +2650,13 @@ error = lldb.SBError() triple = "" platform = "" - target = self.dbg.CreateTarget(file_path, triple, platform, - load_dependent_modules, error) + target = self.dbg.CreateTarget( + file_path, triple, platform, load_dependent_modules, error + ) if error.Fail(): - err = "Couldn't create target for path '{}': {}".format(file_path, - str(error)) + err = "Couldn't create target for path '{}': {}".format( + file_path, str(error) + ) self.fail(self._formatMessage(msg, err)) self.assertTrue(target.IsValid(), "Got invalid target without error") @@ -2566,24 +2675,17 @@ err = sys.stderr err.write(val.GetName() + ":\n") - err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n') - err.write('\t' + "ByteSize -> " + - str(val.GetByteSize()) + '\n') - err.write('\t' + "NumChildren -> " + - str(val.GetNumChildren()) + '\n') - err.write('\t' + "Value -> " + str(val.GetValue()) + '\n') - err.write('\t' + "ValueAsUnsigned -> " + - str(val.GetValueAsUnsigned()) + '\n') + err.write("\t" + "TypeName -> " + val.GetTypeName() + "\n") + err.write("\t" + "ByteSize -> " + str(val.GetByteSize()) + "\n") + err.write("\t" + "NumChildren -> " + str(val.GetNumChildren()) + "\n") + err.write("\t" + "Value -> " + str(val.GetValue()) + "\n") + err.write("\t" + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned()) + "\n") err.write( - '\t' + - "ValueType -> " + - value_type_to_str( - val.GetValueType()) + - '\n') - err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n') - err.write('\t' + "IsPointerType -> " + - str(val.TypeIsPointerType()) + '\n') - err.write('\t' + "Location -> " + val.GetLocation() + '\n') + "\t" + "ValueType -> " + value_type_to_str(val.GetValueType()) + "\n" + ) + err.write("\t" + "Summary -> " + str(val.GetSummary()) + "\n") + err.write("\t" + "IsPointerType -> " + str(val.TypeIsPointerType()) + "\n") + err.write("\t" + "Location -> " + val.GetLocation() + "\n") def DebugSBType(self, type): """Debug print a SBType object, if traceAlways is True.""" @@ -2592,14 +2694,10 @@ err = sys.stderr err.write(type.GetName() + ":\n") - err.write('\t' + "ByteSize -> " + - str(type.GetByteSize()) + '\n') - err.write('\t' + "IsAggregateType -> " + - str(type.IsAggregateType()) + '\n') - err.write('\t' + "IsPointerType -> " + - str(type.IsPointerType()) + '\n') - err.write('\t' + "IsReferenceType -> " + - str(type.IsReferenceType()) + '\n') + err.write("\t" + "ByteSize -> " + str(type.GetByteSize()) + "\n") + err.write("\t" + "IsAggregateType -> " + str(type.IsAggregateType()) + "\n") + err.write("\t" + "IsPointerType -> " + str(type.IsPointerType()) + "\n") + err.write("\t" + "IsReferenceType -> " + str(type.IsReferenceType()) + "\n") def DebugPExpect(self, child): """Debug the spwaned pexpect object.""" @@ -2613,6 +2711,7 @@ if os.path.exists(file): remove_file(file) + # On Windows, the first attempt to delete a recently-touched file can fail # because of a race with antimalware scanners. This function will detect a # failure and retry. diff --git a/lldb/packages/Python/lldbsuite/test/lldbutil.py b/lldb/packages/Python/lldbsuite/test/lldbutil.py --- a/lldb/packages/Python/lldbsuite/test/lldbutil.py +++ b/lldb/packages/Python/lldbsuite/test/lldbutil.py @@ -28,6 +28,7 @@ # Utilities for locating/checking executable programs # =================================================== + def is_exe(fpath): """Returns True if fpath is an executable.""" return os.path.isfile(fpath) and os.access(fpath, os.X_OK) @@ -46,6 +47,7 @@ return exe_file return None + def mkdir_p(path): try: os.makedirs(path) @@ -53,13 +55,14 @@ if e.errno != errno.EEXIST: raise if not os.path.isdir(path): - raise OSError(errno.ENOTDIR, "%s is not a directory"%path) + raise OSError(errno.ENOTDIR, "%s is not a directory" % path) # ============================ # Dealing with SDK and triples # ============================ + def get_xcode_sdk(os, env): # Respect --apple-sdk if it's specified. If the SDK is simply # mounted from some disk image, and not actually installed, this is the @@ -84,18 +87,27 @@ def get_xcode_sdk_version(sdk): - return subprocess.check_output( - ['xcrun', '--sdk', sdk, '--show-sdk-version']).rstrip().decode('utf-8') + return ( + subprocess.check_output(["xcrun", "--sdk", sdk, "--show-sdk-version"]) + .rstrip() + .decode("utf-8") + ) def get_xcode_sdk_root(sdk): - return subprocess.check_output(['xcrun', '--sdk', sdk, '--show-sdk-path' - ]).rstrip().decode('utf-8') + return ( + subprocess.check_output(["xcrun", "--sdk", sdk, "--show-sdk-path"]) + .rstrip() + .decode("utf-8") + ) def get_xcode_clang(sdk): - return subprocess.check_output(['xcrun', '-sdk', sdk, '-f', 'clang' - ]).rstrip().decode("utf-8") + return ( + subprocess.check_output(["xcrun", "-sdk", sdk, "-f", "clang"]) + .rstrip() + .decode("utf-8") + ) # =================================================== @@ -114,6 +126,7 @@ print(i, file=buf) return buf.getvalue() + # ========================================================== # Integer (byte size 1, 2, 4, and 8) to bytearray conversion # ========================================================== @@ -133,11 +146,11 @@ # Little endian followed by a format character. template = "<%c" if bytesize == 2: - fmt = template % 'h' + fmt = template % "h" elif bytesize == 4: - fmt = template % 'i' + fmt = template % "i" elif bytesize == 4: - fmt = template % 'q' + fmt = template % "q" else: return None @@ -159,11 +172,11 @@ # Little endian followed by a format character. template = "<%c" if bytesize == 2: - fmt = template % 'h' + fmt = template % "h" elif bytesize == 4: - fmt = template % 'i' + fmt = template % "i" elif bytesize == 4: - fmt = template % 'q' + fmt = template % "q" else: return None @@ -184,7 +197,7 @@ o lldb.eDescriptionLevelFull o lldb.eDescriptionLevelVerbose """ - method = getattr(obj, 'GetDescription') + method = getattr(obj, "GetDescription") if not method: return None tuple = (lldb.SBTarget, lldb.SBBreakpointLocation, lldb.SBWatchpoint) @@ -206,6 +219,7 @@ # Convert some enum value to its string counterpart # ================================================= + def _enum_names(prefix: str) -> Dict[int, str]: """Generate a mapping of enum value to name, for the enum prefix.""" suffix_start = len(prefix) @@ -218,6 +232,7 @@ _STATE_NAMES = _enum_names(prefix="eState") + def state_type_to_str(enum: int) -> str: """Returns the stateType string given an enum.""" name = _STATE_NAMES.get(enum) @@ -228,6 +243,7 @@ _STOP_REASON_NAMES = _enum_names(prefix="eStopReason") + def stop_reason_to_str(enum: int) -> str: """Returns the stopReason string given an enum.""" name = _STOP_REASON_NAMES.get(enum) @@ -238,6 +254,7 @@ _SYMBOL_TYPE_NAMES = _enum_names(prefix="eSymbolType") + def symbol_type_to_str(enum: int) -> str: """Returns the symbolType string given an enum.""" name = _SYMBOL_TYPE_NAMES.get(enum) @@ -248,6 +265,7 @@ _VALUE_TYPE_NAMES = _enum_names(prefix="eValueType") + def value_type_to_str(enum: int) -> str: """Returns the valueType string given an enum.""" name = _VALUE_TYPE_NAMES.get(enum) @@ -260,46 +278,53 @@ # Get stopped threads due to each stop reason. # ================================================== -def sort_stopped_threads(process, - breakpoint_threads=None, - crashed_threads=None, - watchpoint_threads=None, - signal_threads=None, - exiting_threads=None, - other_threads=None): - """ Fills array *_threads with threads stopped for the corresponding stop - reason. + +def sort_stopped_threads( + process, + breakpoint_threads=None, + crashed_threads=None, + watchpoint_threads=None, + signal_threads=None, + exiting_threads=None, + other_threads=None, +): + """Fills array *_threads with threads stopped for the corresponding stop + reason. """ - for lst in [breakpoint_threads, - watchpoint_threads, - signal_threads, - exiting_threads, - other_threads]: + for lst in [ + breakpoint_threads, + watchpoint_threads, + signal_threads, + exiting_threads, + other_threads, + ]: if lst is not None: lst[:] = [] for thread in process: dispatched = False - for (reason, list) in [(lldb.eStopReasonBreakpoint, breakpoint_threads), - (lldb.eStopReasonException, crashed_threads), - (lldb.eStopReasonWatchpoint, watchpoint_threads), - (lldb.eStopReasonSignal, signal_threads), - (lldb.eStopReasonThreadExiting, exiting_threads), - (None, other_threads)]: + for reason, list in [ + (lldb.eStopReasonBreakpoint, breakpoint_threads), + (lldb.eStopReasonException, crashed_threads), + (lldb.eStopReasonWatchpoint, watchpoint_threads), + (lldb.eStopReasonSignal, signal_threads), + (lldb.eStopReasonThreadExiting, exiting_threads), + (None, other_threads), + ]: if not dispatched and list is not None: if thread.GetStopReason() == reason or reason is None: list.append(thread) dispatched = True + # ================================================== # Utility functions for setting breakpoints # ================================================== + def run_break_set_by_script( - test, - class_name, - extra_options=None, - num_expected_locations=1): + test, class_name, extra_options=None, num_expected_locations=1 +): """Set a scripted breakpoint. Check that it got the right number of locations.""" test.assertTrue(class_name is not None, "Must pass in a class name.") command = "breakpoint set -P " + class_name @@ -310,14 +335,16 @@ check_breakpoint_result(test, break_results, num_locations=num_expected_locations) return get_bpno_from_match(break_results) + def 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): + test, + file_name, + line_number, + extra_options=None, + num_expected_locations=1, + loc_exact=False, + module_name=None, +): """Set a breakpoint by file and line, returning the breakpoint number. If extra_options is not None, then we append it to the breakpoint set command. @@ -325,10 +352,11 @@ If num_expected_locations is -1, we check that we got AT LEAST one location. If num_expected_locations is -2, we don't check the actual number at all. Otherwise, we check that num_expected_locations equals the number of locations. - If loc_exact is true, we check that there is one location, and that location must be at the input file and line number.""" + If loc_exact is true, we check that there is one location, and that location must be at the input file and line number. + """ if file_name is None: - command = 'breakpoint set -l %d' % (line_number) + command = "breakpoint set -l %d" % (line_number) else: command = 'breakpoint set -f "%s" -l %d' % (file_name, line_number) @@ -347,26 +375,28 @@ num_locations=num_expected_locations, file_name=file_name, line_number=line_number, - module_name=module_name) + module_name=module_name, + ) else: check_breakpoint_result( - test, - break_results, - num_locations=num_expected_locations) + test, break_results, num_locations=num_expected_locations + ) return get_bpno_from_match(break_results) def run_break_set_by_symbol( - test, - symbol, - extra_options=None, - num_expected_locations=-1, - sym_exact=False, - module_name=None): + test, + symbol, + extra_options=None, + num_expected_locations=-1, + sym_exact=False, + module_name=None, +): """Set a breakpoint by symbol name. Common options are the same as run_break_set_by_file_and_line. - If sym_exact is true, then the output symbol must match the input exactly, otherwise we do a substring match.""" + If sym_exact is true, then the output symbol must match the input exactly, otherwise we do a substring match. + """ command = 'breakpoint set -n "%s"' % (symbol) if module_name: @@ -383,22 +413,19 @@ break_results, num_locations=num_expected_locations, symbol_name=symbol, - module_name=module_name) + module_name=module_name, + ) else: check_breakpoint_result( - test, - break_results, - num_locations=num_expected_locations) + test, break_results, num_locations=num_expected_locations + ) return get_bpno_from_match(break_results) def run_break_set_by_selector( - test, - selector, - extra_options=None, - num_expected_locations=-1, - module_name=None): + test, selector, extra_options=None, num_expected_locations=-1, module_name=None +): """Set a breakpoint by selector. Common options are the same as run_break_set_by_file_and_line.""" command = 'breakpoint set -S "%s"' % (selector) @@ -418,21 +445,19 @@ num_locations=num_expected_locations, symbol_name=selector, symbol_match_exact=False, - module_name=module_name) + module_name=module_name, + ) else: check_breakpoint_result( - test, - break_results, - num_locations=num_expected_locations) + test, break_results, num_locations=num_expected_locations + ) return get_bpno_from_match(break_results) def run_break_set_by_regexp( - test, - regexp, - extra_options=None, - num_expected_locations=-1): + test, regexp, extra_options=None, num_expected_locations=-1 +): """Set a breakpoint by regular expression match on symbol name. Common options are the same as run_break_set_by_file_and_line.""" command = 'breakpoint set -r "%s"' % (regexp) @@ -441,19 +466,14 @@ break_results = run_break_set_command(test, command) - check_breakpoint_result( - test, - break_results, - num_locations=num_expected_locations) + check_breakpoint_result(test, break_results, num_locations=num_expected_locations) return get_bpno_from_match(break_results) def run_break_set_by_source_regexp( - test, - regexp, - extra_options=None, - num_expected_locations=-1): + test, regexp, extra_options=None, num_expected_locations=-1 +): """Set a breakpoint by source regular expression. Common options are the same as run_break_set_by_file_and_line.""" command = 'breakpoint set -p "%s"' % (regexp) if extra_options: @@ -461,22 +481,21 @@ break_results = run_break_set_command(test, command) - check_breakpoint_result( - test, - break_results, - num_locations=num_expected_locations) + check_breakpoint_result(test, break_results, num_locations=num_expected_locations) return get_bpno_from_match(break_results) + def run_break_set_by_file_colon_line( - test, - specifier, - path, - line_number, - column_number = 0, - extra_options=None, - num_expected_locations=-1): - command = 'breakpoint set -y "%s"'%(specifier) + test, + specifier, + path, + line_number, + column_number=0, + extra_options=None, + num_expected_locations=-1, +): + command = 'breakpoint set -y "%s"' % (specifier) if extra_options: command += " " + extra_options @@ -485,13 +504,15 @@ check_breakpoint_result( test, break_results, - num_locations = num_expected_locations, - file_name = path, - line_number = line_number, - column_number = column_number) + num_locations=num_expected_locations, + file_name=path, + line_number=line_number, + column_number=column_number, + ) return get_bpno_from_match(break_results) + def run_break_set_command(test, command): """Run the command passed in - it must be some break set variant - and analyze the result. Returns a dictionary of information gleaned from the command-line results. @@ -515,146 +536,147 @@ r"^Breakpoint (?P[0-9]+): (?P[0-9]+) locations\.$", r"^Breakpoint (?P[0-9]+): (?Pno) locations \(pending\)\.", r"^Breakpoint (?P[0-9]+): where = (?P.*)`(?P[+\-]{0,1}[^+]+)( \+ (?P[0-9]+)){0,1}( \[inlined\] (?P.*)){0,1} at (?P[^:]+):(?P[0-9]+)(?P(:[0-9]+)?), address = (?P
0x[0-9a-fA-F]+)$", - r"^Breakpoint (?P[0-9]+): where = (?P.*)`(?P.*)( \+ (?P[0-9]+)){0,1}, address = (?P
0x[0-9a-fA-F]+)$"] + r"^Breakpoint (?P[0-9]+): where = (?P.*)`(?P.*)( \+ (?P[0-9]+)){0,1}, address = (?P
0x[0-9a-fA-F]+)$", + ] match_object = test.match(command, patterns) break_results = match_object.groupdict() # We always insert the breakpoint number, setting it to -1 if we couldn't find it # Also, make sure it gets stored as an integer. - if not 'bpno' in break_results: - break_results['bpno'] = -1 + if not "bpno" in break_results: + break_results["bpno"] = -1 else: - break_results['bpno'] = int(break_results['bpno']) + break_results["bpno"] = int(break_results["bpno"]) # We always insert the number of locations # If ONE location is set for the breakpoint, then the output doesn't mention locations, but it has to be 1... # We also make sure it is an integer. - if not 'num_locations' in break_results: + if not "num_locations" in break_results: num_locations = 1 else: - num_locations = break_results['num_locations'] - if num_locations == 'no': + num_locations = break_results["num_locations"] + if num_locations == "no": num_locations = 0 else: - num_locations = int(break_results['num_locations']) + num_locations = int(break_results["num_locations"]) - break_results['num_locations'] = num_locations + break_results["num_locations"] = num_locations - if 'line_no' in break_results: - break_results['line_no'] = int(break_results['line_no']) + if "line_no" in break_results: + break_results["line_no"] = int(break_results["line_no"]) return break_results def get_bpno_from_match(break_results): - return int(break_results['bpno']) + return int(break_results["bpno"]) def check_breakpoint_result( - test, - break_results, - file_name=None, - line_number=-1, - column_number=0, - symbol_name=None, - symbol_match_exact=True, - module_name=None, - offset=-1, - num_locations=-1): - - out_num_locations = break_results['num_locations'] + test, + break_results, + file_name=None, + line_number=-1, + column_number=0, + symbol_name=None, + symbol_match_exact=True, + module_name=None, + offset=-1, + num_locations=-1, +): + out_num_locations = break_results["num_locations"] if num_locations == -1: - test.assertTrue(out_num_locations > 0, - "Expecting one or more locations, got none.") + test.assertTrue( + out_num_locations > 0, "Expecting one or more locations, got none." + ) elif num_locations != -2: test.assertTrue( num_locations == out_num_locations, - "Expecting %d locations, got %d." % - (num_locations, - out_num_locations)) + "Expecting %d locations, got %d." % (num_locations, out_num_locations), + ) if file_name: out_file_name = "" - if 'file' in break_results: - out_file_name = break_results['file'] + if "file" in break_results: + out_file_name = break_results["file"] test.assertTrue( file_name.endswith(out_file_name), - "Breakpoint file name '%s' doesn't match resultant name '%s'." % - (file_name, - out_file_name)) + "Breakpoint file name '%s' doesn't match resultant name '%s'." + % (file_name, out_file_name), + ) if line_number != -1: out_line_number = -1 - if 'line_no' in break_results: - out_line_number = break_results['line_no'] + if "line_no" in break_results: + out_line_number = break_results["line_no"] test.assertTrue( line_number == out_line_number, - "Breakpoint line number %s doesn't match resultant line %s." % - (line_number, - out_line_number)) + "Breakpoint line number %s doesn't match resultant line %s." + % (line_number, out_line_number), + ) if column_number != 0: out_column_number = 0 - if 'column' in break_results: - out_column_number = break_results['column'] + if "column" in break_results: + out_column_number = break_results["column"] test.assertTrue( column_number == out_column_number, - "Breakpoint column number %s doesn't match resultant column %s." % - (column_number, - out_column_number)) + "Breakpoint column number %s doesn't match resultant column %s." + % (column_number, out_column_number), + ) if symbol_name: out_symbol_name = "" # Look first for the inlined symbol name, otherwise use the symbol # name: - if 'inline_symbol' in break_results and break_results['inline_symbol']: - out_symbol_name = break_results['inline_symbol'] - elif 'symbol' in break_results: - out_symbol_name = break_results['symbol'] + if "inline_symbol" in break_results and break_results["inline_symbol"]: + out_symbol_name = break_results["inline_symbol"] + elif "symbol" in break_results: + out_symbol_name = break_results["symbol"] if symbol_match_exact: test.assertTrue( symbol_name == out_symbol_name, - "Symbol name '%s' doesn't match resultant symbol '%s'." % - (symbol_name, - out_symbol_name)) + "Symbol name '%s' doesn't match resultant symbol '%s'." + % (symbol_name, out_symbol_name), + ) else: test.assertTrue( - out_symbol_name.find(symbol_name) != - - 1, - "Symbol name '%s' isn't in resultant symbol '%s'." % - (symbol_name, - out_symbol_name)) + out_symbol_name.find(symbol_name) != -1, + "Symbol name '%s' isn't in resultant symbol '%s'." + % (symbol_name, out_symbol_name), + ) if module_name: out_module_name = None - if 'module' in break_results: - out_module_name = break_results['module'] + if "module" in break_results: + out_module_name = break_results["module"] 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)) + module_name.find(out_module_name) != -1, + "Symbol module name '%s' isn't in expected module name '%s'." + % (out_module_name, module_name), + ) + def check_breakpoint( - test, - bpno, - expected_locations = None, - expected_resolved_count = None, - expected_hit_count = None, - location_id = None, - expected_location_resolved = True, - expected_location_hit_count = None): + test, + bpno, + expected_locations=None, + expected_resolved_count=None, + expected_hit_count=None, + location_id=None, + expected_location_resolved=True, + expected_location_hit_count=None, +): """ Test breakpoint or breakpoint location. - Breakpoint resolved count is always checked. If not specified the assumption is that all locations - should be resolved. + Breakpoint resolved count is always checked. If not specified the assumption is that all locations + should be resolved. To test a breakpoint location, breakpoint number (bpno) and location_id must be set. In this case the resolved count for a breakpoint is not tested by default. The location is expected to be resolved, unless expected_location_resolved is set to False. @@ -697,7 +719,6 @@ test.assertEquals(expected_location_hit_count, loc_bkpt.GetHitCount()) - # ================================================== # Utility functions related to Threads and Processes # ================================================== @@ -745,7 +766,7 @@ def get_threads_stopped_at_breakpoint_id(process, bpid): - """ For a stopped process returns the thread stopped at the breakpoint passed in bkpt""" + """For a stopped process returns the thread stopped at the breakpoint passed in bkpt""" stopped_threads = [] threads = [] @@ -767,8 +788,7 @@ return get_threads_stopped_at_breakpoint_id(process, bkpt.GetID()) -def get_one_thread_stopped_at_breakpoint_id( - process, bpid, require_exactly_one=True): +def get_one_thread_stopped_at_breakpoint_id(process, bpid, require_exactly_one=True): threads = get_threads_stopped_at_breakpoint_id(process, bpid) if len(threads) == 0: return None @@ -778,21 +798,26 @@ return threads[0] -def get_one_thread_stopped_at_breakpoint( - process, bkpt, require_exactly_one=True): +def get_one_thread_stopped_at_breakpoint(process, bkpt, require_exactly_one=True): return get_one_thread_stopped_at_breakpoint_id( - process, bkpt.GetID(), require_exactly_one) + process, bkpt.GetID(), require_exactly_one + ) def is_thread_crashed(test, thread): """In the test suite we dereference a null pointer to simulate a crash. The way this is reported depends on the platform.""" if test.platformIsDarwin(): - return thread.GetStopReason( - ) == lldb.eStopReasonException and "EXC_BAD_ACCESS" in thread.GetStopDescription(100) + return ( + thread.GetStopReason() == lldb.eStopReasonException + and "EXC_BAD_ACCESS" in thread.GetStopDescription(100) + ) elif test.getPlatform() == "linux": - return thread.GetStopReason() == lldb.eStopReasonSignal and thread.GetStopReasonDataAtIndex( - 0) == thread.GetProcess().GetUnixSignals().GetSignalNumberFromName("SIGSEGV") + return ( + thread.GetStopReason() == lldb.eStopReasonSignal + and thread.GetStopReasonDataAtIndex(0) + == thread.GetProcess().GetUnixSignals().GetSignalNumberFromName("SIGSEGV") + ) elif test.getPlatform() == "windows": return "Exception 0xc0000005" in thread.GetStopDescription(200) else: @@ -808,24 +833,29 @@ threads.append(thread) return threads + # Helper functions for run_to_{source,name}_breakpoint: -def run_to_breakpoint_make_target(test, exe_name = "a.out", in_cwd = True): + +def run_to_breakpoint_make_target(test, exe_name="a.out", in_cwd=True): exe = test.getBuildArtifact(exe_name) if in_cwd else exe_name # Create the target target = test.dbg.CreateTarget(exe) - test.assertTrue(target, "Target: %s is not valid."%(exe_name)) + test.assertTrue(target, "Target: %s is not valid." % (exe_name)) # Set environment variables for the inferior. if lldbtest_config.inferior_env: - test.runCmd('settings set target.env-vars {}'.format( - lldbtest_config.inferior_env)) + test.runCmd( + "settings set target.env-vars {}".format(lldbtest_config.inferior_env) + ) return target -def run_to_breakpoint_do_run(test, target, bkpt, launch_info = None, - only_one_thread = True, extra_images = None): + +def run_to_breakpoint_do_run( + test, target, bkpt, launch_info=None, only_one_thread=True, extra_images=None +): # Launch the process, and do not stop at the entry point. if not launch_info: launch_info = target.GetLaunchInfo() @@ -840,20 +870,26 @@ # Unfortunate workaround for the iPhone simulator. retry = SIMULATOR_RETRY - while (retry and error.Fail() and error.GetCString() and - "Unable to boot the Simulator" in error.GetCString()): + while ( + retry + and error.Fail() + and error.GetCString() + and "Unable to boot the Simulator" in error.GetCString() + ): retry -= 1 - print("** Simulator is unresponsive. Retrying %d more time(s)"%retry) + print("** Simulator is unresponsive. Retrying %d more time(s)" % retry) import time + time.sleep(60) error = lldb.SBError() process = target.Launch(launch_info, error) - test.assertTrue(process, - "Could not create a valid process for %s: %s" % - (target.GetExecutable().GetFilename(), error.GetCString())) - test.assertFalse(error.Fail(), - "Process launch failed: %s" % (error.GetCString())) + test.assertTrue( + process, + "Could not create a valid process for %s: %s" + % (target.GetExecutable().GetFilename(), error.GetCString()), + ) + test.assertFalse(error.Fail(), "Process launch failed: %s" % (error.GetCString())) def processStateInfo(process): info = "state: {}".format(state_type_to_str(process.state)) @@ -870,115 +906,149 @@ return info if process.state != lldb.eStateStopped: - test.fail("Test process is not stopped at breakpoint: {}".format(processStateInfo(process))) + test.fail( + "Test process is not stopped at breakpoint: {}".format( + processStateInfo(process) + ) + ) # Frame #0 should be at our breakpoint. - threads = get_threads_stopped_at_breakpoint( - process, bkpt) + threads = get_threads_stopped_at_breakpoint(process, bkpt) num_threads = len(threads) if only_one_thread: - test.assertEqual(num_threads, 1, "Expected 1 thread to stop at breakpoint, %d did."%(num_threads)) + test.assertEqual( + num_threads, + 1, + "Expected 1 thread to stop at breakpoint, %d did." % (num_threads), + ) else: test.assertGreater(num_threads, 0, "No threads stopped at breakpoint") thread = threads[0] return (target, process, thread, bkpt) -def run_to_name_breakpoint (test, bkpt_name, launch_info = None, - exe_name = "a.out", - bkpt_module = None, - in_cwd = True, - only_one_thread = True, - extra_images = None): + +def run_to_name_breakpoint( + test, + bkpt_name, + launch_info=None, + exe_name="a.out", + bkpt_module=None, + in_cwd=True, + only_one_thread=True, + extra_images=None, +): """Start up a target, using exe_name as the executable, and run it to - a breakpoint set by name on bkpt_name restricted to bkpt_module. + a breakpoint set by name on bkpt_name restricted to bkpt_module. - If you want to pass in launch arguments or environment - variables, you can optionally pass in an SBLaunchInfo. If you - do that, remember to set the working directory as well. + If you want to pass in launch arguments or environment + variables, you can optionally pass in an SBLaunchInfo. If you + do that, remember to set the working directory as well. - If your executable isn't called a.out, you can pass that in. - And if your executable isn't in the CWD, pass in the absolute - path to the executable in exe_name, and set in_cwd to False. + If your executable isn't called a.out, you can pass that in. + And if your executable isn't in the CWD, pass in the absolute + path to the executable in exe_name, and set in_cwd to False. - If you need to restrict the breakpoint to a particular module, - pass the module name (a string not a FileSpec) in bkpt_module. If - nothing is passed in setting will be unrestricted. + If you need to restrict the breakpoint to a particular module, + pass the module name (a string not a FileSpec) in bkpt_module. If + nothing is passed in setting will be unrestricted. - If the target isn't valid, the breakpoint isn't found, or hit, the - function will cause a testsuite failure. + If the target isn't valid, the breakpoint isn't found, or hit, the + function will cause a testsuite failure. - If successful it returns a tuple with the target process and - thread that hit the breakpoint, and the breakpoint that we set - for you. + If successful it returns a tuple with the target process and + thread that hit the breakpoint, and the breakpoint that we set + for you. - If only_one_thread is true, we require that there be only one - thread stopped at the breakpoint. Otherwise we only require one - or more threads stop there. If there are more than one, we return - the first thread that stopped. + If only_one_thread is true, we require that there be only one + thread stopped at the breakpoint. Otherwise we only require one + or more threads stop there. If there are more than one, we return + the first thread that stopped. """ target = run_to_breakpoint_make_target(test, exe_name, in_cwd) breakpoint = target.BreakpointCreateByName(bkpt_name, bkpt_module) - - test.assertTrue(breakpoint.GetNumLocations() > 0, - "No locations found for name breakpoint: '%s'."%(bkpt_name)) - return run_to_breakpoint_do_run(test, target, breakpoint, launch_info, - only_one_thread, extra_images) - -def run_to_source_breakpoint(test, bkpt_pattern, source_spec, - launch_info = None, exe_name = "a.out", - bkpt_module = None, - in_cwd = True, - only_one_thread = True, - extra_images = None, - has_locations_before_run = True): + test.assertTrue( + breakpoint.GetNumLocations() > 0, + "No locations found for name breakpoint: '%s'." % (bkpt_name), + ) + return run_to_breakpoint_do_run( + test, target, breakpoint, launch_info, only_one_thread, extra_images + ) + + +def run_to_source_breakpoint( + test, + bkpt_pattern, + source_spec, + launch_info=None, + exe_name="a.out", + bkpt_module=None, + in_cwd=True, + only_one_thread=True, + extra_images=None, + has_locations_before_run=True, +): """Start up a target, using exe_name as the executable, and run it to - a breakpoint set by source regex bkpt_pattern. + a breakpoint set by source regex bkpt_pattern. - The rest of the behavior is the same as run_to_name_breakpoint. + The rest of the behavior is the same as run_to_name_breakpoint. """ target = run_to_breakpoint_make_target(test, exe_name, in_cwd) # Set the breakpoints breakpoint = target.BreakpointCreateBySourceRegex( - bkpt_pattern, source_spec, bkpt_module) + bkpt_pattern, source_spec, bkpt_module + ) if has_locations_before_run: - test.assertTrue(breakpoint.GetNumLocations() > 0, - 'No locations found for source breakpoint: "%s", file: "%s", dir: "%s"' - %(bkpt_pattern, source_spec.GetFilename(), source_spec.GetDirectory())) - return run_to_breakpoint_do_run(test, target, breakpoint, launch_info, - only_one_thread, extra_images) - -def run_to_line_breakpoint(test, source_spec, line_number, column = 0, - launch_info = None, exe_name = "a.out", - bkpt_module = None, - in_cwd = True, - only_one_thread = True, - extra_images = None): + test.assertTrue( + breakpoint.GetNumLocations() > 0, + 'No locations found for source breakpoint: "%s", file: "%s", dir: "%s"' + % (bkpt_pattern, source_spec.GetFilename(), source_spec.GetDirectory()), + ) + return run_to_breakpoint_do_run( + test, target, breakpoint, launch_info, only_one_thread, extra_images + ) + + +def run_to_line_breakpoint( + test, + source_spec, + line_number, + column=0, + launch_info=None, + exe_name="a.out", + bkpt_module=None, + in_cwd=True, + only_one_thread=True, + extra_images=None, +): """Start up a target, using exe_name as the executable, and run it to - a breakpoint set by (source_spec, line_number(, column)). + a breakpoint set by (source_spec, line_number(, column)). - The rest of the behavior is the same as run_to_name_breakpoint. + The rest of the behavior is the same as run_to_name_breakpoint. """ target = run_to_breakpoint_make_target(test, exe_name, in_cwd) # Set the breakpoints breakpoint = target.BreakpointCreateByLocation( - source_spec, line_number, column, 0, lldb.SBFileSpecList()) - test.assertTrue(breakpoint.GetNumLocations() > 0, + source_spec, line_number, column, 0, lldb.SBFileSpecList() + ) + test.assertTrue( + breakpoint.GetNumLocations() > 0, 'No locations found for line breakpoint: "%s:%d(:%d)", dir: "%s"' - %(source_spec.GetFilename(), line_number, column, - source_spec.GetDirectory())) - return run_to_breakpoint_do_run(test, target, breakpoint, launch_info, - only_one_thread, extra_images) + % (source_spec.GetFilename(), line_number, column, source_spec.GetDirectory()), + ) + return run_to_breakpoint_do_run( + test, target, breakpoint, launch_info, only_one_thread, extra_images + ) def continue_to_breakpoint(process, bkpt): - """ Continues the process, if it stops, returns the threads stopped at bkpt; otherwise, returns None""" + """Continues the process, if it stops, returns the threads stopped at bkpt; otherwise, returns None""" process.Continue() if process.GetState() != lldb.eStateStopped: return None @@ -992,10 +1062,13 @@ Otherwise the same as `continue_to_breakpoint` """ breakpoint = process.target.BreakpointCreateBySourceRegex( - bkpt_pattern, source_spec, None) - test.assertTrue(breakpoint.GetNumLocations() > 0, - 'No locations found for source breakpoint: "%s", file: "%s", dir: "%s"' - %(bkpt_pattern, source_spec.GetFilename(), source_spec.GetDirectory())) + bkpt_pattern, source_spec, None + ) + test.assertTrue( + breakpoint.GetNumLocations() > 0, + 'No locations found for source breakpoint: "%s", file: "%s", dir: "%s"' + % (bkpt_pattern, source_spec.GetFilename(), source_spec.GetDirectory()), + ) stopped_threads = continue_to_breakpoint(process, breakpoint) process.target.BreakpointDelete(breakpoint.GetID()) return stopped_threads @@ -1019,6 +1092,7 @@ """ Returns a sequence of function names from the stack frames of this thread. """ + def GetFuncName(i): return thread.GetFrameAtIndex(i).GetFunctionName() @@ -1029,6 +1103,7 @@ """ Returns a sequence of symbols for this thread. """ + def GetSymbol(i): return thread.GetFrameAtIndex(i).GetSymbol().GetName() @@ -1039,6 +1114,7 @@ """ Returns a sequence of pc addresses for this thread. """ + def GetPCAddress(i): return thread.GetFrameAtIndex(i).GetPCAddress() @@ -1049,9 +1125,9 @@ """ Returns a sequence of file names from the stack frames of this thread. """ + def GetFilename(i): - return thread.GetFrameAtIndex( - i).GetLineEntry().GetFileSpec().GetFilename() + return thread.GetFrameAtIndex(i).GetLineEntry().GetFileSpec().GetFilename() return list(map(GetFilename, list(range(thread.GetNumFrames())))) @@ -1060,6 +1136,7 @@ """ Returns a sequence of line numbers from the stack frames of this thread. """ + def GetLineNumber(i): return thread.GetFrameAtIndex(i).GetLineEntry().GetLine() @@ -1070,9 +1147,9 @@ """ Returns a sequence of module names from the stack frames of this thread. """ + def GetModuleName(i): - return thread.GetFrameAtIndex( - i).GetModule().GetFileSpec().GetFilename() + return thread.GetFrameAtIndex(i).GetModule().GetFileSpec().GetFilename() return list(map(GetModuleName, list(range(thread.GetNumFrames())))) @@ -1081,6 +1158,7 @@ """ Returns a sequence of stack frames for this thread. """ + def GetStackFrame(i): return thread.GetFrameAtIndex(i) @@ -1108,10 +1186,11 @@ desc = "" print( "Stack trace for thread id={0:#x} name={1} queue={2} ".format( - thread.GetThreadID(), - thread.GetName(), - thread.GetQueueName()) + desc, - file=output) + thread.GetThreadID(), thread.GetName(), thread.GetQueueName() + ) + + desc, + file=output, + ) for i in range(depth): frame = thread.GetFrameAtIndex(i) @@ -1128,22 +1207,25 @@ addr=load_addr, mod=mods[i], symbol=symbols[i], - offset=symbol_offset), - file=output) + offset=symbol_offset, + ), + file=output, + ) else: print( " frame #{num}: {addr:#016x} {mod}`{func} at {file}:{line} {args}".format( num=i, addr=load_addr, mod=mods[i], - func='%s [inlined]' % - funcs[i] if frame.IsInlined() else funcs[i], + func="%s [inlined]" % funcs[i] if frame.IsInlined() else funcs[i], file=files[i], line=lines[i], - args=get_args_as_string( - frame, - showFuncName=False) if not frame.IsInlined() else '()'), - file=output) + args=get_args_as_string(frame, showFuncName=False) + if not frame.IsInlined() + else "()", + ), + file=output, + ) if string_buffer: return output.getvalue() @@ -1165,35 +1247,40 @@ def expect_state_changes(test, listener, process, states, timeout=30): """Listens for state changed events on the listener and makes sure they match what we - expect. Stop-and-restart events (where GetRestartedFromEvent() returns true) are ignored.""" + expect. Stop-and-restart events (where GetRestartedFromEvent() returns true) are ignored. + """ for expected_state in states: + def get_next_event(): event = lldb.SBEvent() if not listener.WaitForEventForBroadcasterWithType( - timeout, - process.GetBroadcaster(), - lldb.SBProcess.eBroadcastBitStateChanged, - event): + timeout, + process.GetBroadcaster(), + lldb.SBProcess.eBroadcastBitStateChanged, + event, + ): test.fail( - "Timed out while waiting for a transition to state %s" % - lldb.SBDebugger.StateAsCString(expected_state)) + "Timed out while waiting for a transition to state %s" + % lldb.SBDebugger.StateAsCString(expected_state) + ) return event event = get_next_event() - while (lldb.SBProcess.GetStateFromEvent(event) == lldb.eStateStopped and - lldb.SBProcess.GetRestartedFromEvent(event)): + while lldb.SBProcess.GetStateFromEvent( + event + ) == lldb.eStateStopped and lldb.SBProcess.GetRestartedFromEvent(event): # Ignore restarted event and the subsequent running event. event = get_next_event() test.assertEqual( lldb.SBProcess.GetStateFromEvent(event), lldb.eStateRunning, - "Restarted event followed by a running event") + "Restarted event followed by a running event", + ) event = get_next_event() - test.assertEqual( - lldb.SBProcess.GetStateFromEvent(event), - expected_state) + test.assertEqual(lldb.SBProcess.GetStateFromEvent(event), expected_state) + def start_listening_from(broadcaster, event_mask): """Creates a listener for a specific event mask and add it to the source broadcaster.""" @@ -1202,6 +1289,7 @@ broadcaster.AddListener(listener, event_mask) return listener + def fetch_next_event(test, listener, broadcaster, match_class=False, timeout=10): """Fetch one event from the listener and return it if it matches the provided broadcaster. If `match_class` is set to True, this will match an event with an entire broadcaster class. @@ -1219,8 +1307,10 @@ stream = lldb.SBStream() event.GetDescription(stream) - test.fail("received event '%s' from unexpected broadcaster '%s'." % - (stream.GetData(), event.GetBroadcaster().GetName())) + test.fail( + "received event '%s' from unexpected broadcaster '%s'." + % (stream.GetData(), event.GetBroadcaster().GetName()) + ) test.fail("couldn't fetch an event before reaching the timeout.") @@ -1257,9 +1347,7 @@ vars = frame.GetVariables(True, False, False, True) # type of SBValueList args = [] # list of strings for var in vars: - args.append("(%s)%s=%s" % (var.GetTypeName(), - var.GetName(), - var.GetValue())) + args.append("(%s)%s=%s" % (var.GetTypeName(), var.GetName(), var.GetValue())) if frame.GetFunction(): name = frame.GetFunction().GetName() elif frame.GetSymbol(): @@ -1280,18 +1368,20 @@ print("Register sets for " + str(frame), file=output) registerSet = frame.GetRegisters() # Return type of SBValueList. - print("Frame registers (size of register set = %d):" % - registerSet.GetSize(), file=output) + print( + "Frame registers (size of register set = %d):" % registerSet.GetSize(), + file=output, + ) for value in registerSet: - #print(value, file=output) - print("%s (number of children = %d):" % - (value.GetName(), value.GetNumChildren()), file=output) + # print(value, file=output) + print( + "%s (number of children = %d):" % (value.GetName(), value.GetNumChildren()), + file=output, + ) for child in value: print( - "Name: %s, Value: %s" % - (child.GetName(), - child.GetValue()), - file=output) + "Name: %s, Value: %s" % (child.GetName(), child.GetValue()), file=output + ) if string_buffer: return output.getvalue() @@ -1351,6 +1441,7 @@ """ return get_registers(frame, "exception state") + # ====================================== # Utility classes/functions for SBValues # ====================================== @@ -1371,11 +1462,15 @@ val = value.GetValue() if val is None and value.GetNumChildren() > 0: val = "%s (location)" % value.GetLocation() - print("{indentation}({type}) {name} = {value}".format( - indentation=' ' * indent, - type=value.GetTypeName(), - name=value.GetName(), - value=val), file=output) + print( + "{indentation}({type}) {name} = {value}".format( + indentation=" " * indent, + type=value.GetTypeName(), + name=value.GetName(), + value=val, + ), + file=output, + ) return output.getvalue() @@ -1397,8 +1492,7 @@ BasicFormatter.format(self, value, buffer=output) for child in value: - BasicFormatter.format( - self, child, buffer=output, indent=self.cindent) + BasicFormatter.format(self, child, buffer=output, indent=self.cindent) return output.getvalue() @@ -1426,18 +1520,17 @@ new_indent = self.lindent + self.cindent for child in value: if child.GetSummary() is not None: - BasicFormatter.format( - self, child, buffer=output, indent=new_indent) + BasicFormatter.format(self, child, buffer=output, indent=new_indent) else: if child.GetNumChildren() > 0: rdf = RecursiveDecentFormatter(indent_level=new_indent) rdf.format(child, buffer=output) else: - BasicFormatter.format( - self, child, buffer=output, indent=new_indent) + BasicFormatter.format(self, child, buffer=output, indent=new_indent) return output.getvalue() + # =========================================================== # Utility functions for path manipulation on remote platforms # =========================================================== @@ -1445,9 +1538,9 @@ def join_remote_paths(*paths): # TODO: update with actual platform name for remote windows once it exists - if lldb.remote_platform.GetName() == 'remote-windows': - return os.path.join(*paths).replace(os.path.sep, '\\') - return os.path.join(*paths).replace(os.path.sep, '/') + if lldb.remote_platform.GetName() == "remote-windows": + return os.path.join(*paths).replace(os.path.sep, "\\") + return os.path.join(*paths).replace(os.path.sep, "/") def append_to_process_working_directory(test, *paths): @@ -1456,6 +1549,7 @@ return join_remote_paths(remote.GetWorkingDirectory(), *paths) return os.path.join(test.getBuildDir(), *paths) + # ================================================== # Utility functions to get the correct signal number # ================================================== @@ -1474,45 +1568,51 @@ # No remote platform; fall back to using local python signals. return getattr(signal, signal_name) -def get_actions_for_signal(testcase, signal_name, from_target=False, expected_absent=False): + +def get_actions_for_signal( + testcase, signal_name, from_target=False, expected_absent=False +): """Returns a triple of (pass, stop, notify)""" return_obj = lldb.SBCommandReturnObject() command = "process handle {0}".format(signal_name) if from_target: command += " -t" - testcase.dbg.GetCommandInterpreter().HandleCommand( - command, return_obj) + testcase.dbg.GetCommandInterpreter().HandleCommand(command, return_obj) match = re.match( - 'NAME *PASS *STOP *NOTIFY.*(false|true|not set) *(false|true|not set) *(false|true|not set)', + "NAME *PASS *STOP *NOTIFY.*(false|true|not set) *(false|true|not set) *(false|true|not set)", return_obj.GetOutput(), - re.IGNORECASE | re.DOTALL) + re.IGNORECASE | re.DOTALL, + ) if match and expected_absent: testcase.fail('Signal "{0}" was supposed to be absent'.format(signal_name)) if not match: if expected_absent: return (None, None, None) - testcase.fail('Unable to retrieve default signal disposition.') + testcase.fail("Unable to retrieve default signal disposition.") return (match.group(1), match.group(2), match.group(3)) +def set_actions_for_signal( + testcase, signal_name, pass_action, stop_action, notify_action, expect_success=True +): + return_obj = lldb.SBCommandReturnObject() + command = "process handle {0}".format(signal_name) + if pass_action != None: + command += " -p {0}".format(pass_action) + if stop_action != None: + command += " -s {0}".format(stop_action) + if notify_action != None: + command += " -n {0}".format(notify_action) -def set_actions_for_signal(testcase, signal_name, pass_action, stop_action, notify_action, expect_success=True): - return_obj = lldb.SBCommandReturnObject() - command = "process handle {0}".format(signal_name) - if pass_action != None: - command += " -p {0}".format(pass_action) - if stop_action != None: - command += " -s {0}".format(stop_action) - if notify_action != None: - command +=" -n {0}".format(notify_action) - - testcase.dbg.GetCommandInterpreter().HandleCommand(command, return_obj) - testcase.assertEqual(expect_success, - return_obj.Succeeded(), - "Setting signal handling for {0} worked as expected".format(signal_name)) + testcase.dbg.GetCommandInterpreter().HandleCommand(command, return_obj) + testcase.assertEqual( + expect_success, + return_obj.Succeeded(), + "Setting signal handling for {0} worked as expected".format(signal_name), + ) -class PrintableRegex(object): +class PrintableRegex(object): def __init__(self, text): self.regex = re.compile(text) self.text = text @@ -1542,36 +1642,41 @@ if isinstance(library, str): if library == filename: return False - elif hasattr(library, 'match'): + elif hasattr(library, "match"): if library.match(filename): return False return True def find_library_callable(test): return find_library(target, library) + return skip_if_callable( test, find_library_callable, - "could not find library matching '%s' in target %s" % - (library, - target)) + "could not find library matching '%s' in target %s" % (library, target), + ) def read_file_on_target(test, remote): if lldb.remote_platform: local = test.getBuildArtifact("file_from_target") - error = lldb.remote_platform.Get(lldb.SBFileSpec(remote, False), - lldb.SBFileSpec(local, True)) - test.assertTrue(error.Success(), "Reading file {0} failed: {1}".format(remote, error)) + error = lldb.remote_platform.Get( + lldb.SBFileSpec(remote, False), lldb.SBFileSpec(local, True) + ) + test.assertTrue( + error.Success(), "Reading file {0} failed: {1}".format(remote, error) + ) else: local = remote - with open(local, 'r') as f: + with open(local, "r") as f: return f.read() + def read_file_from_process_wd(test, name): path = append_to_process_working_directory(test, name) return read_file_on_target(test, path) + def wait_for_file_on_target(testcase, file_path, max_attempts=6): for i in range(max_attempts): err, retcode, msg = testcase.run_platform_command("ls %s" % file_path) @@ -1580,14 +1685,16 @@ if i < max_attempts: # Exponential backoff! import time + time.sleep(pow(2, i) * 0.25) else: testcase.fail( - "File %s not found even after %d attempts." % - (file_path, max_attempts)) + "File %s not found even after %d attempts." % (file_path, max_attempts) + ) return read_file_on_target(testcase, file_path) + def packetlog_get_process_info(log): """parse a gdb-remote packet log file and extract the response to qProcessInfo""" process_info = dict() @@ -1596,32 +1703,37 @@ expect_process_info_response = False for line in logfile: if expect_process_info_response: - for pair in line.split(';'): - keyval = pair.split(':') + for pair in line.split(";"): + keyval = pair.split(":") if len(keyval) == 2: process_info[keyval[0]] = keyval[1] break - if 'send packet: $qProcessInfo#' in line: + if "send packet: $qProcessInfo#" in line: expect_process_info_response = True return process_info + def packetlog_get_dylib_info(log): """parse a gdb-remote packet log file and extract the *last* complete (=> fetch_all_solibs=true) response to jGetLoadedDynamicLibrariesInfos""" import json + dylib_info = None with open(log, "r") as logfile: dylib_info = None expect_dylib_info_response = False for line in logfile: if expect_dylib_info_response: - while line[0] != '$': + while line[0] != "$": line = line[1:] line = line[1:] # Unescape '}'. - dylib_info = json.loads(line.replace('}]','}')[:-4]) + dylib_info = json.loads(line.replace("}]", "}")[:-4]) expect_dylib_info_response = False - if 'send packet: $jGetLoadedDynamicLibrariesInfos:{"fetch_all_solibs":true}' in line: + if ( + 'send packet: $jGetLoadedDynamicLibrariesInfos:{"fetch_all_solibs":true}' + in line + ): expect_dylib_info_response = True return dylib_info diff --git a/lldb/packages/Python/lldbsuite/test/test_categories.py b/lldb/packages/Python/lldbsuite/test/test_categories.py --- a/lldb/packages/Python/lldbsuite/test/test_categories.py +++ b/lldb/packages/Python/lldbsuite/test/test_categories.py @@ -15,37 +15,32 @@ # Key: Category name # Value: should be used in lldbtest's debug-info replication -debug_info_categories = { - 'dwarf' : True, - 'dwo' : True, - 'dsym' : True, - 'gmodules' : False -} +debug_info_categories = {"dwarf": True, "dwo": True, "dsym": True, "gmodules": False} all_categories = { - 'basic_process': 'Basic process execution sniff tests.', - 'cmdline': 'Tests related to the LLDB command-line interface', - 'dataformatters': 'Tests related to the type command and the data formatters subsystem', - 'debugserver': 'Debugserver tests', - 'dsym': 'Tests that can be run with DSYM debug information', - 'dwarf': 'Tests that can be run with DWARF debug information', - 'dwo': 'Tests that can be run with DWO debug information', - 'dyntype': 'Tests related to dynamic type support', - 'expression': 'Tests related to the expression parser', - 'flakey': 'Flakey test cases, i.e. tests that do not reliably pass at each execution', - 'fork': 'Tests requiring the process plugin fork/vfork event support', - 'gmodules': 'Tests that can be run with -gmodules debug information', - 'instrumentation-runtime': 'Tests for the instrumentation runtime plugins', - 'libc++': 'Test for libc++ data formatters', - 'libstdcxx': 'Test for libstdcxx data formatters', - 'lldb-server': 'Tests related to lldb-server', - 'lldb-vscode': 'Visual Studio Code debug adaptor tests', - 'llgs': 'Tests for the gdb-server functionality of lldb-server', - 'objc': 'Tests related to the Objective-C programming language support', - 'pyapi': 'Tests related to the Python API', - 'std-module': 'Tests related to importing the std module', - 'stresstest': 'Tests related to stressing lldb limits', - 'watchpoint': 'Watchpoint-related tests', + "basic_process": "Basic process execution sniff tests.", + "cmdline": "Tests related to the LLDB command-line interface", + "dataformatters": "Tests related to the type command and the data formatters subsystem", + "debugserver": "Debugserver tests", + "dsym": "Tests that can be run with DSYM debug information", + "dwarf": "Tests that can be run with DWARF debug information", + "dwo": "Tests that can be run with DWO debug information", + "dyntype": "Tests related to dynamic type support", + "expression": "Tests related to the expression parser", + "flakey": "Flakey test cases, i.e. tests that do not reliably pass at each execution", + "fork": "Tests requiring the process plugin fork/vfork event support", + "gmodules": "Tests that can be run with -gmodules debug information", + "instrumentation-runtime": "Tests for the instrumentation runtime plugins", + "libc++": "Test for libc++ data formatters", + "libstdcxx": "Test for libstdcxx data formatters", + "lldb-server": "Tests related to lldb-server", + "lldb-vscode": "Visual Studio Code debug adaptor tests", + "llgs": "Tests for the gdb-server functionality of lldb-server", + "objc": "Tests related to the Objective-C programming language support", + "pyapi": "Tests related to the Python API", + "std-module": "Tests related to importing the std module", + "stresstest": "Tests related to stressing lldb limits", + "watchpoint": "Watchpoint-related tests", } @@ -88,12 +83,15 @@ category = unique_string_match(category, all_categories) if (category not in all_categories) or category is None: print( - "fatal error: category '" + - origCategory + - "' is not a valid category") - print("if you have added a new category, please edit test_categories.py, adding your new category to all_categories") - print("else, please specify one or more of the following: " + - str(list(all_categories.keys()))) + "fatal error: category '" + origCategory + "' is not a valid category" + ) + print( + "if you have added a new category, please edit test_categories.py, adding your new category to all_categories" + ) + print( + "else, please specify one or more of the following: " + + str(list(all_categories.keys())) + ) sys.exit(1) result.append(category) return result diff --git a/lldb/packages/Python/lldbsuite/test/test_result.py b/lldb/packages/Python/lldbsuite/test/test_result.py --- a/lldb/packages/Python/lldbsuite/test/test_result.py +++ b/lldb/packages/Python/lldbsuite/test/test_result.py @@ -28,12 +28,14 @@ is used in the LLDB test framework to emit detailed trace messages to a log file for easier human inspection of test failures/errors. """ + __singleton__ = None __ignore_singleton__ = False @staticmethod def getTerminalSize(): import os + env = os.environ def ioctl_GWINSZ(fd): @@ -41,11 +43,12 @@ import fcntl import termios import struct - cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, - '1234')) + + cr = struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234")) except: return return cr + cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: try: @@ -55,7 +58,7 @@ except: pass if not cr: - cr = (env.get('LINES', 25), env.get('COLUMNS', 80)) + cr = (env.get("LINES", 25), env.get("COLUMNS", 80)) return int(cr[1]), int(cr[0]) def __init__(self, *args): @@ -68,7 +71,7 @@ # Computes the format string for displaying the counter. counterWidth = len(str(configuration.suite.countTestCases())) self.fmt = "%" + str(counterWidth) + "d: " - self.indentation = ' ' * (counterWidth + 2) + self.indentation = " " * (counterWidth + 2) # This counts from 1 .. suite.countTestCases(). self.counter = 0 (width, height) = LLDBTestResult.getTerminalSize() @@ -76,25 +79,24 @@ def _config_string(self, test): compiler = getattr(test, "getCompiler", None) arch = getattr(test, "getArchitecture", None) - return "%s-%s" % (compiler() if compiler else "", - arch() if arch else "") + return "%s-%s" % (compiler() if compiler else "", arch() if arch else "") def _exc_info_to_string(self, err, test): """Overrides superclass TestResult's method in order to append our test config info string to the exception info string.""" if hasattr(test, "getArchitecture") and hasattr(test, "getCompiler"): - return '%sConfig=%s-%s' % (super(LLDBTestResult, - self)._exc_info_to_string(err, - test), - test.getArchitecture(), - test.getCompiler()) + return "%sConfig=%s-%s" % ( + super(LLDBTestResult, self)._exc_info_to_string(err, test), + test.getArchitecture(), + test.getCompiler(), + ) else: return super(LLDBTestResult, self)._exc_info_to_string(err, test) def getDescription(self, test): doc_first_line = test.shortDescription() if self.descriptions and doc_first_line: - return '\n'.join((str(test), self.indentation + doc_first_line)) + return "\n".join((str(test), self.indentation + doc_first_line)) else: return str(test) @@ -107,6 +109,7 @@ return test.test_filename else: import inspect + return inspect.getsourcefile(test.__class__) def _getFileBasedCategories(self, test): @@ -118,20 +121,24 @@ start_path = self._getTestPath(test) import os.path + folder = os.path.dirname(start_path) from lldbsuite import lldb_test_root as test_root + if test_root != os.path.commonprefix([folder, test_root]): - raise Exception("The test file %s is outside the test root directory" % start_path) + raise Exception( + "The test file %s is outside the test root directory" % start_path + ) categories = set() while not os.path.samefile(folder, test_root): categories_file_name = os.path.join(folder, "categories") if os.path.exists(categories_file_name): - categories_file = open(categories_file_name, 'r') + categories_file = open(categories_file_name, "r") categories_str = categories_file.readline().strip() categories_file.close() - categories.update(categories_str.split(',')) + categories.update(categories_str.split(",")) folder = os.path.dirname(folder) return list(categories) @@ -152,27 +159,27 @@ def hardMarkAsSkipped(self, test): getattr(test, test._testMethodName).__func__.__unittest_skip__ = True getattr( - test, - test._testMethodName).__func__.__unittest_skip_why__ = "test case does not fall in any category of interest for this run" + test, test._testMethodName + ).__func__.__unittest_skip_why__ = ( + "test case does not fall in any category of interest for this run" + ) def checkExclusion(self, exclusion_list, name): if exclusion_list: import re + for item in exclusion_list: if re.search(item, name): return True return False def checkCategoryExclusion(self, exclusion_list, test): - return not set(exclusion_list).isdisjoint( - self.getCategoriesForTest(test)) + return not set(exclusion_list).isdisjoint(self.getCategoriesForTest(test)) def startTest(self, test): - if configuration.shouldSkipBecauseOfCategories( - self.getCategoriesForTest(test)): + if configuration.shouldSkipBecauseOfCategories(self.getCategoriesForTest(test)): self.hardMarkAsSkipped(test) - if self.checkExclusion( - configuration.skip_tests, test.id()): + if self.checkExclusion(configuration.skip_tests, test.id()): self.hardMarkAsSkipped(test) self.counter += 1 @@ -182,17 +189,16 @@ super(LLDBTestResult, self).startTest(test) def addSuccess(self, test): - if (self.checkExclusion( - configuration.xfail_tests, test.id()) or - self.checkCategoryExclusion( - configuration.xfail_categories, test)): + if self.checkExclusion( + configuration.xfail_tests, test.id() + ) or self.checkCategoryExclusion(configuration.xfail_categories, test): self.addUnexpectedSuccess(test, None) return super(LLDBTestResult, self).addSuccess(test) self.stream.write( - "PASS: LLDB (%s) :: %s\n" % - (self._config_string(test), str(test))) + "PASS: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)) + ) def _isBuildError(self, err_tuple): exception = err_tuple[1] @@ -203,8 +209,8 @@ # rather than an uninformative Python backtrace. build_error = err[1] error_description = "{}\nTest Directory:\n{}".format( - str(build_error), - os.path.dirname(self._getTestPath(test))) + str(build_error), os.path.dirname(self._getTestPath(test)) + ) self.errors.append((test, error_description)) self._mirrorOutput = True @@ -219,8 +225,8 @@ if method: method() self.stream.write( - "FAIL: LLDB (%s) :: %s\n" % - (self._config_string(test), str(test))) + "FAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)) + ) def addCleanupError(self, test, err): configuration.sdir_has_content = True @@ -229,14 +235,14 @@ if method: method() self.stream.write( - "CLEANUP ERROR: LLDB (%s) :: %s\n%s\n" % - (self._config_string(test), str(test), traceback.format_exc())) + "CLEANUP ERROR: LLDB (%s) :: %s\n%s\n" + % (self._config_string(test), str(test), traceback.format_exc()) + ) def addFailure(self, test, err): - if (self.checkExclusion( - configuration.xfail_tests, test.id()) or - self.checkCategoryExclusion( - configuration.xfail_categories, test)): + if self.checkExclusion( + configuration.xfail_tests, test.id() + ) or self.checkCategoryExclusion(configuration.xfail_categories, test): self.addExpectedFailure(test, err, None) return @@ -246,14 +252,15 @@ if method: method() self.stream.write( - "FAIL: LLDB (%s) :: %s\n" % - (self._config_string(test), str(test))) + "FAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)) + ) if configuration.use_categories: test_categories = self.getCategoriesForTest(test) for category in test_categories: if category in configuration.failures_per_category: - configuration.failures_per_category[ - category] = configuration.failures_per_category[category] + 1 + configuration.failures_per_category[category] = ( + configuration.failures_per_category[category] + 1 + ) else: configuration.failures_per_category[category] = 1 @@ -264,8 +271,8 @@ if method: method(err, bugnumber) self.stream.write( - "XFAIL: LLDB (%s) :: %s\n" % - (self._config_string(test), str(test))) + "XFAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)) + ) def addSkip(self, test, reason): configuration.sdir_has_content = True @@ -274,8 +281,9 @@ if method: method() self.stream.write( - "UNSUPPORTED: LLDB (%s) :: %s (%s) \n" % - (self._config_string(test), str(test), reason)) + "UNSUPPORTED: LLDB (%s) :: %s (%s) \n" + % (self._config_string(test), str(test), reason) + ) def addUnexpectedSuccess(self, test, bugnumber): configuration.sdir_has_content = True @@ -284,5 +292,5 @@ if method: method(bugnumber) self.stream.write( - "XPASS: LLDB (%s) :: %s\n" % - (self._config_string(test), str(test))) + "XPASS: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)) + ) diff --git a/lldb/packages/Python/lldbsuite/test/test_runner/process_control.py b/lldb/packages/Python/lldbsuite/test/test_runner/process_control.py --- a/lldb/packages/Python/lldbsuite/test/test_runner/process_control.py +++ b/lldb/packages/Python/lldbsuite/test/test_runner/process_control.py @@ -42,7 +42,9 @@ if self.output_file: self.output_file.write( "exception while using communicate() for pid: {}\n".format( - exception)) + exception + ) + ) finally: # Signal that the thread's run is complete. self.event.set() @@ -70,23 +72,22 @@ if units is None: # default is seconds. No conversion necessary. return value - elif units == 's': + elif units == "s": # Seconds. No conversion necessary. return value - elif units == 'm': + elif units == "m": # Value is in minutes. return 60.0 * value - elif units == 'h': + elif units == "h": # Value is in hours. return (60.0 * 60.0) * value - elif units == 'd': + elif units == "d": # Value is in days. return 24 * (60.0 * 60.0) * value else: raise Exception("unexpected units value '{}'".format(units)) else: - raise Exception("could not parse TIMEOUT spec '{}'".format( - timeout)) + raise Exception("could not parse TIMEOUT spec '{}'".format(timeout)) class ProcessHelper(object): @@ -306,7 +307,8 @@ stderr=subprocess.PIPE, universal_newlines=True, # Elicits automatic byte -> string decoding in Py3 close_fds=True, - preexec_fn=preexec_func) + preexec_fn=preexec_func, + ) # Remember whether we're using process groups for this # process. @@ -345,7 +347,9 @@ log_file.write( "requested to terminate pid {} but it has already " "terminated, returncode {}".format( - popen_process.pid, popen_process.returncode)) + popen_process.pid, popen_process.returncode + ) + ) # Move along... return False @@ -374,6 +378,7 @@ os.kill(popen_process.pid, signum) except OSError as error: import errno + if error.errno == errno.ESRCH: # This is okay - failed to find the process. It may be that # that the timeout pre-kill hook eliminated the process. We'll @@ -415,8 +420,10 @@ @classmethod def _signal_names_by_number(cls): return dict( - (k, v) for v, k in reversed(sorted(signal.__dict__.items())) - if v.startswith('SIG') and not v.startswith('SIG_')) + (k, v) + for v, k in reversed(sorted(signal.__dict__.items())) + if v.startswith("SIG") and not v.startswith("SIG_") + ) def exceptional_exit_details(self, popen_status): signo = -popen_status @@ -444,7 +451,8 @@ stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, # Elicits automatic byte -> string decoding in Py3 - creationflags=creation_flags) + creationflags=creation_flags, + ) def was_hard_terminate(self, returncode): return returncode != 0 @@ -528,15 +536,11 @@ if self.returncode is None: raise Exception( "no exit status available for pid {} after the " - " inferior dotest.py should have completed".format( - self.process.pid)) + " inferior dotest.py should have completed".format(self.process.pid) + ) # Notify of non-timeout exit. - self.on_process_exited( - command, - self.io_thread.output, - False, - self.returncode) + self.on_process_exited(command, self.io_thread.output, False, self.returncode) def run_command_with_timeout(self, command, timeout, want_core): # Figure out how many seconds our timeout description is requesting. @@ -563,8 +567,7 @@ # complete (i.e. the inferior process has finished). self.done_event.clear() - self.io_thread = CommunicatorThread( - self.process, self.done_event, self.write) + self.io_thread = CommunicatorThread(self.process, self.done_event, self.write) self.io_thread.start() def _attempt_soft_kill(self, want_core): @@ -573,9 +576,8 @@ # and/or generate a core dump). Often the OS can't guarantee # that the process will really terminate after this. self.process_helper.soft_terminate( - self.process, - want_core=want_core, - log_file=self) + self.process, want_core=want_core, log_file=self + ) # Now wait up to a certain timeout period for the io thread # to say that the communication ended. If that wraps up @@ -589,9 +591,12 @@ terminated = True done_trying = None else: - self.write("soft kill attempt of process {} timed out " - "after {} seconds\n".format( - self.process.pid, self.soft_terminate_timeout)) + self.write( + "soft kill attempt of process {} timed out " + "after {} seconds\n".format( + self.process.pid, self.soft_terminate_timeout + ) + ) terminated = False done_trying = False return terminated, done_trying @@ -599,9 +604,7 @@ def _attempt_hard_kill(self): # Instruct the process to terminate and really force it to # happen. Don't give the process a chance to ignore. - self.process_helper.hard_terminate( - self.process, - log_file=self) + self.process_helper.hard_terminate(self.process, log_file=self) # Reap the child process. This should not hang as the # hard_kill() mechanism is supposed to really kill it. @@ -619,7 +622,9 @@ self.write( "hard kill of process {} timed out after {} seconds waiting " "for the io thread (ignoring)\n".format( - self.process.pid, self.hard_terminate_timeout)) + self.process.pid, self.hard_terminate_timeout + ) + ) # Set if it terminated. (Set up for optional improvement above). terminated = self.returncode is not None @@ -661,7 +666,6 @@ # Reap the child process here. self.returncode = self.process.wait() else: - # Allow derived classes to do some work after we detected # a timeout but before we touch the timed-out process. self.on_timeout_pre_kill() @@ -676,7 +680,8 @@ terminate_attempt_count += 1 # Attempt to terminate. process_terminated, done_trying = self._attempt_termination( - terminate_attempt_count, want_core) + terminate_attempt_count, want_core + ) # Check if there's nothing more to try. if done_trying: # Break out of our termination attempt loop. @@ -686,10 +691,8 @@ # finished gracefully, was shut down after one or more # attempts, or we failed but gave it our best effort. self.on_process_exited( - command, - self.io_thread.output, - not completed_normally, - self.returncode) + command, self.io_thread.output, not completed_normally, self.returncode + ) def patched_init(self, *args, **kwargs): @@ -732,6 +735,7 @@ subprocess.Popen.original_poll = subprocess.Popen.poll subprocess.Popen.poll = patched_poll + # Replace key subprocess.Popen() threading-unprotected methods with # threading-protected versions. patch_up_subprocess_popen() diff --git a/lldb/packages/Python/lldbsuite/test/tools/intelpt/intelpt_testcase.py b/lldb/packages/Python/lldbsuite/test/tools/intelpt/intelpt_testcase.py --- a/lldb/packages/Python/lldbsuite/test/tools/intelpt/intelpt_testcase.py +++ b/lldb/packages/Python/lldbsuite/test/tools/intelpt/intelpt_testcase.py @@ -3,7 +3,8 @@ import time import json -ADDRESS_REGEX = '0x[0-9a-fA-F]*' +ADDRESS_REGEX = "0x[0-9a-fA-F]*" + # Decorator that runs a test with both modes of USE_SB_API. # It assumes that no tests can be executed in parallel. @@ -13,8 +14,10 @@ func(*args, **kwargs) TraceIntelPTTestCaseBase.USE_SB_API = False func(*args, **kwargs) + return wrapper + # Class that should be used by all python Intel PT tests. # # It has a handy check that skips the test if the intel-pt plugin is not enabled. @@ -22,7 +25,6 @@ # It also contains many functions that can test both the SB API or the command line version # of the most important tracing actions. class TraceIntelPTTestCaseBase(TestBase): - NO_DEBUG_INFO_TESTCASE = True # If True, the trace test methods will use the SB API, otherwise they'll use raw commands. @@ -30,7 +32,7 @@ def setUp(self): TestBase.setUp(self) - if 'intel-pt' not in configuration.enabled_plugins: + if "intel-pt" not in configuration.enabled_plugins: self.skipTest("The intel-pt test plugin is not enabled") def skipIfPerCpuTracingIsNotSupported(self): @@ -42,10 +44,13 @@ return True except: return False + if not is_supported(): - self.skipTest("Per cpu tracing is not supported. You need " + self.skipTest( + "Per cpu tracing is not supported. You need " "/proc/sys/kernel/perf_event_paranoid to be 0 or -1. " - "You can use `sudo sysctl -w kernel.perf_event_paranoid=-1` for that.") + "You can use `sudo sysctl -w kernel.perf_event_paranoid=-1` for that." + ) def getTraceOrCreate(self): if not self.target().GetTrace().IsValid(): @@ -59,9 +64,14 @@ else: self.assertSuccess(sberror) - def createConfiguration(self, iptTraceSize=None, - processBufferSizeLimit=None, enableTsc=False, - psbPeriod=None, perCpuTracing=False): + def createConfiguration( + self, + iptTraceSize=None, + processBufferSizeLimit=None, + enableTsc=False, + psbPeriod=None, + perCpuTracing=False, + ): obj = {} if processBufferSizeLimit is not None: obj["processBufferSizeLimit"] = processBufferSizeLimit @@ -76,14 +86,21 @@ configuration.SetFromJSON(json.dumps(obj)) return configuration - def traceStartThread(self, thread=None, error=False, substrs=None, - iptTraceSize=None, enableTsc=False, psbPeriod=None): + def traceStartThread( + self, + thread=None, + error=False, + substrs=None, + iptTraceSize=None, + enableTsc=False, + psbPeriod=None, + ): if self.USE_SB_API: trace = self.getTraceOrCreate() thread = thread if thread is not None else self.thread() configuration = self.createConfiguration( - iptTraceSize=iptTraceSize, enableTsc=enableTsc, - psbPeriod=psbPeriod) + iptTraceSize=iptTraceSize, enableTsc=enableTsc, psbPeriod=psbPeriod + ) self.assertSBError(trace.Start(thread, configuration), error) else: command = "thread trace start" @@ -97,14 +114,23 @@ command += " --psb-period " + str(psbPeriod) self.expect(command, error=error, substrs=substrs) - def traceStartProcess(self, processBufferSizeLimit=None, error=False, - substrs=None, enableTsc=False, psbPeriod=None, - perCpuTracing=False): + def traceStartProcess( + self, + processBufferSizeLimit=None, + error=False, + substrs=None, + enableTsc=False, + psbPeriod=None, + perCpuTracing=False, + ): if self.USE_SB_API: trace = self.getTraceOrCreate() configuration = self.createConfiguration( - processBufferSizeLimit=processBufferSizeLimit, enableTsc=enableTsc, - psbPeriod=psbPeriod, perCpuTracing=perCpuTracing) + processBufferSizeLimit=processBufferSizeLimit, + enableTsc=enableTsc, + psbPeriod=psbPeriod, + perCpuTracing=perCpuTracing, + ) self.assertSBError(trace.Start(configuration), error=error) else: command = "process trace start" @@ -149,7 +175,8 @@ if self.USE_SB_API: save_error = lldb.SBError() self.target().GetTrace().SaveToDisk( - save_error, lldb.SBFileSpec(traceBundleDir), compact) + save_error, lldb.SBFileSpec(traceBundleDir), compact + ) self.assertSBError(save_error, error) else: command = f"trace save {traceBundleDir}" diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/fork_testbase.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/fork_testbase.py --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/fork_testbase.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/fork_testbase.py @@ -2,157 +2,200 @@ class GdbRemoteForkTestBase(gdbremote_testcase.GdbRemoteTestCaseBase): - fork_regex = ("[$]T[0-9a-fA-F]{{2}}thread:p([0-9a-f]+)[.]([0-9a-f]+);.*" - "{}:p([0-9a-f]+)[.]([0-9a-f]+).*") - fork_regex_nonstop = ("%Stop:T[0-9a-fA-F]{{2}}" - "thread:p([0-9a-f]+)[.]([0-9a-f]+);.*" - "{}:p([0-9a-f]+)[.]([0-9a-f]+).*") - fork_capture = {1: "parent_pid", 2: "parent_tid", - 3: "child_pid", 4: "child_tid"} + fork_regex = ( + "[$]T[0-9a-fA-F]{{2}}thread:p([0-9a-f]+)[.]([0-9a-f]+);.*" + "{}:p([0-9a-f]+)[.]([0-9a-f]+).*" + ) + fork_regex_nonstop = ( + "%Stop:T[0-9a-fA-F]{{2}}" + "thread:p([0-9a-f]+)[.]([0-9a-f]+);.*" + "{}:p([0-9a-f]+)[.]([0-9a-f]+).*" + ) + fork_capture = {1: "parent_pid", 2: "parent_tid", 3: "child_pid", 4: "child_tid"} stop_regex_base = "T[0-9a-fA-F]{{2}}thread:p{}.{};.*reason:signal.*" stop_regex = "^[$]" + stop_regex_base def start_fork_test(self, args, variant="fork", nonstop=False): self.build() self.prep_debug_monitor_and_inferior(inferior_args=args) - self.add_qSupported_packets(["multiprocess+", - "{}-events+".format(variant)]) + self.add_qSupported_packets(["multiprocess+", "{}-events+".format(variant)]) ret = self.expect_gdbremote_sequence() self.assertIn("{}-events+".format(variant), ret["qSupported_response"]) self.reset_test_sequence() # continue and expect fork if nonstop: - self.test_sequence.add_log_lines([ - "read packet: $QNonStop:1#00", - "send packet: $OK#00", - "read packet: $c#00", - "send packet: $OK#00", - {"direction": "send", - "regex": self.fork_regex_nonstop.format(variant), - "capture": self.fork_capture}, - "read packet: $vStopped#00", - "send packet: $OK#00", - ], True) + self.test_sequence.add_log_lines( + [ + "read packet: $QNonStop:1#00", + "send packet: $OK#00", + "read packet: $c#00", + "send packet: $OK#00", + { + "direction": "send", + "regex": self.fork_regex_nonstop.format(variant), + "capture": self.fork_capture, + }, + "read packet: $vStopped#00", + "send packet: $OK#00", + ], + True, + ) else: - self.test_sequence.add_log_lines([ - "read packet: $c#00", - {"direction": "send", "regex": self.fork_regex.format(variant), - "capture": self.fork_capture}, - ], True) + self.test_sequence.add_log_lines( + [ + "read packet: $c#00", + { + "direction": "send", + "regex": self.fork_regex.format(variant), + "capture": self.fork_capture, + }, + ], + True, + ) ret = self.expect_gdbremote_sequence() self.reset_test_sequence() - return tuple(ret[x] for x in ("parent_pid", "parent_tid", - "child_pid", "child_tid")) + return tuple( + ret[x] for x in ("parent_pid", "parent_tid", "child_pid", "child_tid") + ) def fork_and_detach_test(self, variant, nonstop=False): - parent_pid, parent_tid, child_pid, child_tid = ( - self.start_fork_test([variant], variant, nonstop=nonstop)) + parent_pid, parent_tid, child_pid, child_tid = self.start_fork_test( + [variant], variant, nonstop=nonstop + ) # detach the forked child - self.test_sequence.add_log_lines([ - "read packet: $D;{}#00".format(child_pid), - "send packet: $OK#00", - # verify that the current process is correct - "read packet: $qC#00", - "send packet: $QCp{}.{}#00".format(parent_pid, parent_tid), - # verify that the correct processes are detached/available - "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), - "send packet: $Eff#00", - "read packet: $Hgp{}.{}#00".format(parent_pid, parent_tid), - "send packet: $OK#00", - ], True) + self.test_sequence.add_log_lines( + [ + "read packet: $D;{}#00".format(child_pid), + "send packet: $OK#00", + # verify that the current process is correct + "read packet: $qC#00", + "send packet: $QCp{}.{}#00".format(parent_pid, parent_tid), + # verify that the correct processes are detached/available + "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), + "send packet: $Eff#00", + "read packet: $Hgp{}.{}#00".format(parent_pid, parent_tid), + "send packet: $OK#00", + ], + True, + ) self.expect_gdbremote_sequence() self.reset_test_sequence() return parent_pid, parent_tid def fork_and_follow_test(self, variant, nonstop=False): - parent_pid, parent_tid, child_pid, child_tid = ( - self.start_fork_test([variant], variant, nonstop=nonstop)) + parent_pid, parent_tid, child_pid, child_tid = self.start_fork_test( + [variant], variant, nonstop=nonstop + ) # switch to the forked child - self.test_sequence.add_log_lines([ - "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), - "send packet: $OK#00", - "read packet: $Hcp{}.{}#00".format(child_pid, child_tid), - "send packet: $OK#00", - # detach the parent - "read packet: $D;{}#00".format(parent_pid), - "send packet: $OK#00", - # verify that the correct processes are detached/available - "read packet: $Hgp{}.{}#00".format(parent_pid, parent_tid), - "send packet: $Eff#00", - "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), - "send packet: $OK#00", - # then resume the child - "read packet: $c#00", - ], True) - - if nonstop: - self.test_sequence.add_log_lines([ + self.test_sequence.add_log_lines( + [ + "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), + "send packet: $OK#00", + "read packet: $Hcp{}.{}#00".format(child_pid, child_tid), "send packet: $OK#00", - "send packet: %Stop:W00;process:{}#00".format(child_pid), - "read packet: $vStopped#00", + # detach the parent + "read packet: $D;{}#00".format(parent_pid), "send packet: $OK#00", - ], True) + # verify that the correct processes are detached/available + "read packet: $Hgp{}.{}#00".format(parent_pid, parent_tid), + "send packet: $Eff#00", + "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), + "send packet: $OK#00", + # then resume the child + "read packet: $c#00", + ], + True, + ) + + if nonstop: + self.test_sequence.add_log_lines( + [ + "send packet: $OK#00", + "send packet: %Stop:W00;process:{}#00".format(child_pid), + "read packet: $vStopped#00", + "send packet: $OK#00", + ], + True, + ) else: - self.test_sequence.add_log_lines([ - "send packet: $W00;process:{}#00".format(child_pid), - ], True) + self.test_sequence.add_log_lines( + [ + "send packet: $W00;process:{}#00".format(child_pid), + ], + True, + ) self.expect_gdbremote_sequence() def detach_all_test(self, nonstop=False): - parent_pid, parent_tid, child_pid, child_tid = ( - self.start_fork_test(["fork"], nonstop=nonstop)) - - self.test_sequence.add_log_lines([ - # double-check our PIDs - "read packet: $Hgp{}.{}#00".format(parent_pid, parent_tid), - "send packet: $OK#00", - "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), - "send packet: $OK#00", - # detach all processes - "read packet: $D#00", - "send packet: $OK#00", - # verify that both PIDs are invalid now - "read packet: $Hgp{}.{}#00".format(parent_pid, parent_tid), - "send packet: $Eff#00", - "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), - "send packet: $Eff#00", - ], True) + parent_pid, parent_tid, child_pid, child_tid = self.start_fork_test( + ["fork"], nonstop=nonstop + ) + + self.test_sequence.add_log_lines( + [ + # double-check our PIDs + "read packet: $Hgp{}.{}#00".format(parent_pid, parent_tid), + "send packet: $OK#00", + "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), + "send packet: $OK#00", + # detach all processes + "read packet: $D#00", + "send packet: $OK#00", + # verify that both PIDs are invalid now + "read packet: $Hgp{}.{}#00".format(parent_pid, parent_tid), + "send packet: $Eff#00", + "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), + "send packet: $Eff#00", + ], + True, + ) self.expect_gdbremote_sequence() def vkill_test(self, kill_parent=False, kill_child=False, nonstop=False): assert kill_parent or kill_child - parent_pid, parent_tid, child_pid, child_tid = ( - self.start_fork_test(["fork"], nonstop=nonstop)) + parent_pid, parent_tid, child_pid, child_tid = self.start_fork_test( + ["fork"], nonstop=nonstop + ) if kill_parent: - self.test_sequence.add_log_lines([ - # kill the process - "read packet: $vKill;{}#00".format(parent_pid), - "send packet: $OK#00", - ], True) + self.test_sequence.add_log_lines( + [ + # kill the process + "read packet: $vKill;{}#00".format(parent_pid), + "send packet: $OK#00", + ], + True, + ) if kill_child: - self.test_sequence.add_log_lines([ - # kill the process - "read packet: $vKill;{}#00".format(child_pid), - "send packet: $OK#00", - ], True) - self.test_sequence.add_log_lines([ - # check child PID/TID - "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), - "send packet: ${}#00".format("Eff" if kill_child else "OK"), - # check parent PID/TID - "read packet: $Hgp{}.{}#00".format(parent_pid, parent_tid), - "send packet: ${}#00".format("Eff" if kill_parent else "OK"), - ], True) + self.test_sequence.add_log_lines( + [ + # kill the process + "read packet: $vKill;{}#00".format(child_pid), + "send packet: $OK#00", + ], + True, + ) + self.test_sequence.add_log_lines( + [ + # check child PID/TID + "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), + "send packet: ${}#00".format("Eff" if kill_child else "OK"), + # check parent PID/TID + "read packet: $Hgp{}.{}#00".format(parent_pid, parent_tid), + "send packet: ${}#00".format("Eff" if kill_parent else "OK"), + ], + True, + ) self.expect_gdbremote_sequence() def resume_one_test(self, run_order, use_vCont=False, nonstop=False): - parent_pid, parent_tid, child_pid, child_tid = ( - self.start_fork_test(["fork", "stop"], nonstop=nonstop)) + parent_pid, parent_tid, child_pid, child_tid = self.start_fork_test( + ["fork", "stop"], nonstop=nonstop + ) parent_expect = [ self.stop_regex_base.format(parent_pid, parent_tid), @@ -174,34 +217,49 @@ assert False, "unexpected x={}".format(x) if use_vCont: - self.test_sequence.add_log_lines([ - # continue the selected process - "read packet: $vCont;c:p{}.{}#00".format(*pidtid), - ], True) + self.test_sequence.add_log_lines( + [ + # continue the selected process + "read packet: $vCont;c:p{}.{}#00".format(*pidtid), + ], + True, + ) else: - self.test_sequence.add_log_lines([ - # continue the selected process - "read packet: $Hcp{}.{}#00".format(*pidtid), - "send packet: $OK#00", - "read packet: $c#00", - ], True) + self.test_sequence.add_log_lines( + [ + # continue the selected process + "read packet: $Hcp{}.{}#00".format(*pidtid), + "send packet: $OK#00", + "read packet: $c#00", + ], + True, + ) if nonstop: - self.test_sequence.add_log_lines([ - "send packet: $OK#00", - {"direction": "send", "regex": "%Stop:" + expect}, - "read packet: $vStopped#00", - "send packet: $OK#00", - ], True) + self.test_sequence.add_log_lines( + [ + "send packet: $OK#00", + {"direction": "send", "regex": "%Stop:" + expect}, + "read packet: $vStopped#00", + "send packet: $OK#00", + ], + True, + ) else: - self.test_sequence.add_log_lines([ - {"direction": "send", "regex": "[$]" + expect}, - ], True) + self.test_sequence.add_log_lines( + [ + {"direction": "send", "regex": "[$]" + expect}, + ], + True, + ) # if at least one process remained, check both PIDs if parent_expect or child_expect: - self.test_sequence.add_log_lines([ - "read packet: $Hgp{}.{}#00".format(parent_pid, parent_tid), - "send packet: ${}#00".format("OK" if parent_expect else "Eff"), - "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), - "send packet: ${}#00".format("OK" if child_expect else "Eff"), - ], True) + self.test_sequence.add_log_lines( + [ + "read packet: $Hgp{}.{}#00".format(parent_pid, parent_tid), + "send packet: ${}#00".format("OK" if parent_expect else "Eff"), + "read packet: $Hgp{}.{}#00".format(child_pid, child_tid), + "send packet: ${}#00".format("OK" if child_expect else "Eff"), + ], + True, + ) self.expect_gdbremote_sequence() diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py @@ -28,7 +28,6 @@ class GdbRemoteTestCaseFactory(type): - def __new__(cls, name, bases, attrs): newattrs = {} for attrname, attrvalue in attrs.items(): @@ -40,12 +39,12 @@ # that list to be authoritative. If none were specified, try # all of them. all_categories = set(["debugserver", "llgs"]) - categories = set( - getattr(attrvalue, "categories", [])) & all_categories + categories = set(getattr(attrvalue, "categories", [])) & all_categories if not categories: categories = all_categories for cat in categories: + @decorators.add_test_categories([cat]) @wraps(attrvalue) def test_method(self, attrvalue=attrvalue): @@ -56,15 +55,14 @@ test_method.debug_server = cat newattrs[method_name] = test_method - return super(GdbRemoteTestCaseFactory, cls).__new__( - cls, name, bases, newattrs) + return super(GdbRemoteTestCaseFactory, cls).__new__(cls, name, bases, newattrs) -class GdbRemoteTestCaseBase(Base, metaclass=GdbRemoteTestCaseFactory): +class GdbRemoteTestCaseBase(Base, metaclass=GdbRemoteTestCaseFactory): # Default time out in seconds. The timeout is increased tenfold under Asan. - DEFAULT_TIMEOUT = 20 * (10 if ('ASAN_OPTIONS' in os.environ) else 1) + DEFAULT_TIMEOUT = 20 * (10 if ("ASAN_OPTIONS" in os.environ) else 1) # Default sleep time in seconds. The sleep time is doubled under Asan. - DEFAULT_SLEEP = 5 * (2 if ('ASAN_OPTIONS' in os.environ) else 1) + DEFAULT_SLEEP = 5 * (2 if ("ASAN_OPTIONS" in os.environ) else 1) _GDBREMOTE_KILL_PACKET = b"$k#6b" @@ -88,8 +86,7 @@ TARGET_EXC_BREAKPOINT = 0x96 _verbose_log_handler = None - _log_formatter = logging.Formatter( - fmt='%(asctime)-15s %(levelname)-8s %(message)s') + _log_formatter = logging.Formatter(fmt="%(asctime)-15s %(levelname)-8s %(message)s") def setUpBaseLogging(self): self.logger = logging.getLogger(__name__) @@ -109,8 +106,7 @@ def isVerboseLoggingRequested(self): # We will report our detailed logs if the user requested that the "gdb-remote" channel is # logged. - return any(("gdb-remote" in channel) - for channel in lldbtest_config.channels) + return any(("gdb-remote" in channel) for channel in lldbtest_config.channels) def getDebugServer(self): method = getattr(self, self.testMethodName) @@ -125,7 +121,8 @@ if self.isVerboseLoggingRequested(): # If requested, full logs go to a log file self._verbose_log_handler = logging.FileHandler( - self.getLogBasenameForCurrentTest() + "-host.log") + self.getLogBasenameForCurrentTest() + "-host.log" + ) self._verbose_log_handler.setFormatter(self._log_formatter) self._verbose_log_handler.setLevel(logging.DEBUG) self.logger.addHandler(self._verbose_log_handler) @@ -135,15 +132,19 @@ self.port = self.get_next_port() self.stub_sends_two_stop_notifications_on_kill = False if configuration.lldb_platform_url: - if configuration.lldb_platform_url.startswith('unix-'): - url_pattern = '(.+)://\[?(.+?)\]?/.*' + if configuration.lldb_platform_url.startswith("unix-"): + url_pattern = "(.+)://\[?(.+?)\]?/.*" else: - url_pattern = '(.+)://(.+):\d+' + url_pattern = "(.+)://(.+):\d+" scheme, host = re.match( - url_pattern, configuration.lldb_platform_url).groups() - if configuration.lldb_platform_name == 'remote-android' and host != 'localhost': + url_pattern, configuration.lldb_platform_url + ).groups() + if ( + configuration.lldb_platform_name == "remote-android" + and host != "localhost" + ): self.stub_device = host - self.stub_hostname = 'localhost' + self.stub_hostname = "localhost" else: self.stub_device = None self.stub_hostname = host @@ -170,17 +171,21 @@ if lldb.remote_platform: log_file = lldbutil.join_remote_paths( - lldb.remote_platform.GetWorkingDirectory(), "server.log") + lldb.remote_platform.GetWorkingDirectory(), "server.log" + ) else: log_file = self.getLocalServerLogFile() if is_llgs: self.debug_monitor_extra_args.append("--log-file=" + log_file) self.debug_monitor_extra_args.append( - "--log-channels={}".format(":".join(lldbtest_config.channels))) + "--log-channels={}".format(":".join(lldbtest_config.channels)) + ) else: self.debug_monitor_extra_args = [ - "--log-file=" + log_file, "--log-flags=0x800000"] + "--log-file=" + log_file, + "--log-flags=0x800000", + ] def get_next_port(self): return 12000 + random.randint(0, 3999) @@ -188,7 +193,6 @@ def reset_test_sequence(self): self.test_sequence = GdbRemoteTestSequence(self.logger) - def _init_llgs_test(self): reverse_connect = True if lldb.remote_platform: @@ -198,29 +202,28 @@ # FIXME: This is extremely linux-oriented # Grab the ppid from /proc/[shell pid]/stat - err, retcode, shell_stat = self.run_platform_command( - "cat /proc/$$/stat") + err, retcode, shell_stat = self.run_platform_command("cat /proc/$$/stat") self.assertTrue( err.Success() and retcode == 0, - "Failed to read file /proc/$$/stat: %s, retcode: %d" % - (err.GetCString(), - retcode)) + "Failed to read file /proc/$$/stat: %s, retcode: %d" + % (err.GetCString(), retcode), + ) # [pid] ([executable]) [state] [*ppid*] pid = re.match(r"^\d+ \(.+\) . (\d+)", shell_stat).group(1) err, retcode, ls_output = self.run_platform_command( - "ls -l /proc/%s/exe" % pid) + "ls -l /proc/%s/exe" % pid + ) self.assertTrue( err.Success() and retcode == 0, - "Failed to read file /proc/%s/exe: %s, retcode: %d" % - (pid, - err.GetCString(), - retcode)) + "Failed to read file /proc/%s/exe: %s, retcode: %d" + % (pid, err.GetCString(), retcode), + ) exe = ls_output.split()[-1] # If the binary has been deleted, the link name has " (deleted)" appended. # Remove if it's there. - self.debug_monitor_exe = re.sub(r' \(deleted\)$', '', exe) + self.debug_monitor_exe = re.sub(r" \(deleted\)$", "", exe) else: self.debug_monitor_exe = get_lldb_server_exe() @@ -239,7 +242,7 @@ self.stub_sends_two_stop_notifications_on_kill = True def forward_adb_port(self, source, target, direction, device): - adb = ['adb'] + (['-s', device] if device else []) + [direction] + adb = ["adb"] + (["-s", device] if device else []) + [direction] def remove_port_forward(): subprocess.call(adb + ["--remove", "tcp:%d" % source]) @@ -275,16 +278,11 @@ triple = self.dbg.GetSelectedPlatform().GetTriple() if re.match(".*-.*-.*-android", triple): - self.forward_adb_port( - self.port, - self.port, - "forward", - self.stub_device) + self.forward_adb_port(self.port, self.port, "forward", self.stub_device) logger.info( - "Connecting to debug monitor on %s:%d", - self.stub_hostname, - self.port) + "Connecting to debug monitor on %s:%d", self.stub_hostname, self.port + ) connect_info = (self.stub_hostname, self.port) try: sock.connect(connect_info) @@ -301,14 +299,18 @@ except: logger.warning( "failed to send kill packet to debug monitor: {}; ignoring".format( - sys.exc_info()[0])) + sys.exc_info()[0] + ) + ) try: sock.close() except: logger.warning( "failed to close socket to debug monitor: {}; ignoring".format( - sys.exc_info()[0])) + sys.exc_info()[0] + ) + ) self.addTearDownHook(shutdown_socket) @@ -346,7 +348,9 @@ def launch_debug_monitor(self, attach_pid=None, logfile=None): if self.reverse_connect: - family, type, proto, _, addr = socket.getaddrinfo("localhost", 0, proto=socket.IPPROTO_TCP)[0] + family, type, proto, _, addr = socket.getaddrinfo( + "localhost", 0, proto=socket.IPPROTO_TCP + )[0] sock = socket.socket(family, type, proto) sock.settimeout(self.DEFAULT_TIMEOUT) @@ -355,16 +359,15 @@ addr = sock.getsockname() self.connect_address = "[{}]:{}".format(*addr) - # Create the command line. commandline_args = self.get_debug_monitor_command_line_args( - attach_pid=attach_pid) + attach_pid=attach_pid + ) # Start the server. server = self.spawnSubprocess( - self.debug_monitor_exe, - commandline_args, - install_remote=False) + self.debug_monitor_exe, commandline_args, install_remote=False + ) self.assertIsNotNone(server) if self.reverse_connect: @@ -417,8 +420,9 @@ # Increment attempts. print( - "connect to debug monitor on port %d failed, attempt #%d of %d" % - (self.port, attempts + 1, MAX_ATTEMPTS)) + "connect to debug monitor on port %d failed, attempt #%d of %d" + % (self.port, attempts + 1, MAX_ATTEMPTS) + ) attempts += 1 # And wait a random length of time before next attempt, to avoid @@ -429,14 +433,13 @@ self.port = self.get_next_port() raise Exception( - "failed to create a socket to the launched debug monitor after %d tries" % - attempts) + "failed to create a socket to the launched debug monitor after %d tries" + % attempts + ) def launch_process_for_attach( - self, - inferior_args=None, - sleep_seconds=3, - exe_path=None): + self, inferior_args=None, sleep_seconds=3, exe_path=None + ): # We're going to start a child process that the debug monitor stub can later attach to. # This process needs to be started so that it just hangs around for a while. We'll # have it sleep. @@ -452,11 +455,12 @@ return self.spawnSubprocess(exe_path, args) def prep_debug_monitor_and_inferior( - self, - inferior_args=None, - inferior_sleep_seconds=3, - inferior_exe_path=None, - inferior_env=None): + self, + inferior_args=None, + inferior_sleep_seconds=3, + inferior_exe_path=None, + inferior_env=None, + ): """Prep the debug monitor, the inferior, and the expected packet stream. Handle the separate cases of using the debug monitor in attach-to-inferior mode @@ -479,12 +483,16 @@ inferior = None attach_pid = None - if self._inferior_startup == self._STARTUP_ATTACH or self._inferior_startup == self._STARTUP_ATTACH_MANUALLY: + if ( + self._inferior_startup == self._STARTUP_ATTACH + or self._inferior_startup == self._STARTUP_ATTACH_MANUALLY + ): # Launch the process that we'll use as the inferior. inferior = self.launch_process_for_attach( inferior_args=inferior_args, sleep_seconds=inferior_sleep_seconds, - exe_path=inferior_exe_path) + exe_path=inferior_exe_path, + ) self.assertIsNotNone(inferior) self.assertTrue(inferior.pid > 0) if self._inferior_startup == self._STARTUP_ATTACH: @@ -498,15 +506,18 @@ inferior_exe_path = self.getBuildArtifact("a.out") if lldb.remote_platform: - remote_path = lldbutil.append_to_process_working_directory(self, - os.path.basename(inferior_exe_path)) + remote_path = lldbutil.append_to_process_working_directory( + self, os.path.basename(inferior_exe_path) + ) remote_file_spec = lldb.SBFileSpec(remote_path, False) - err = lldb.remote_platform.Install(lldb.SBFileSpec( - inferior_exe_path, True), remote_file_spec) + err = lldb.remote_platform.Install( + lldb.SBFileSpec(inferior_exe_path, True), remote_file_spec + ) if err.Fail(): raise Exception( - "remote_platform.Install('%s', '%s') failed: %s" % - (inferior_exe_path, remote_path, err)) + "remote_platform.Install('%s', '%s') failed: %s" + % (inferior_exe_path, remote_path, err) + ) inferior_exe_path = remote_path launch_args = [inferior_exe_path] @@ -538,29 +549,45 @@ def add_verified_launch_packets(self, launch_args): self.test_sequence.add_log_lines( - ["read packet: %s" % build_gdbremote_A_packet(launch_args), - "send packet: $OK#00", - "read packet: $qLaunchSuccess#a5", - "send packet: $OK#00"], - True) + [ + "read packet: %s" % build_gdbremote_A_packet(launch_args), + "send packet: $OK#00", + "read packet: $qLaunchSuccess#a5", + "send packet: $OK#00", + ], + True, + ) def add_thread_suffix_request_packets(self): self.test_sequence.add_log_lines( - ["read packet: $QThreadSuffixSupported#e4", - "send packet: $OK#00", - ], True) + [ + "read packet: $QThreadSuffixSupported#e4", + "send packet: $OK#00", + ], + True, + ) def add_process_info_collection_packets(self): self.test_sequence.add_log_lines( - ["read packet: $qProcessInfo#dc", - {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "process_info_raw"}}], - True) + [ + "read packet: $qProcessInfo#dc", + { + "direction": "send", + "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", + "capture": {1: "process_info_raw"}, + }, + ], + True, + ) def add_set_environment_packets(self, name, value): self.test_sequence.add_log_lines( - ["read packet: $QEnvironment:" + name + "=" + value + "#00", - "send packet: $OK#00", - ], True) + [ + "read packet: $QEnvironment:" + name + "=" + value + "#00", + "send packet: $OK#00", + ], + True, + ) _KNOWN_PROCESS_INFO_KEYS = [ "pid", @@ -576,7 +603,7 @@ "vendor", "endian", "elf_abi", - "ptrsize" + "ptrsize", ] def parse_process_info_response(self, context): @@ -587,11 +614,12 @@ # Pull out key:value; pairs. process_info_dict = { - match.group(1): match.group(2) for match in re.finditer( - r"([^:]+):([^;]+);", process_info_raw)} + match.group(1): match.group(2) + for match in re.finditer(r"([^:]+):([^;]+);", process_info_raw) + } # Validate keys are known. - for (key, val) in list(process_info_dict.items()): + for key, val in list(process_info_dict.items()): self.assertTrue(key in self._KNOWN_PROCESS_INFO_KEYS) self.assertIsNotNone(val) @@ -599,10 +627,17 @@ def add_register_info_collection_packets(self): self.test_sequence.add_log_lines( - [{"type": "multi_response", "query": "qRegisterInfo", "append_iteration_suffix": True, - "end_regex": re.compile(r"^\$(E\d+)?#[0-9a-fA-F]{2}$"), - "save_key": "reg_info_responses"}], - True) + [ + { + "type": "multi_response", + "query": "qRegisterInfo", + "append_iteration_suffix": True, + "end_regex": re.compile(r"^\$(E\d+)?#[0-9a-fA-F]{2}$"), + "save_key": "reg_info_responses", + } + ], + True, + ) def parse_register_info_packets(self, context): """Return an array of register info dictionaries, one per register info.""" @@ -610,8 +645,10 @@ self.assertIsNotNone(reg_info_responses) # Parse register infos. - return [parse_reg_info_response(reg_info_response) - for reg_info_response in reg_info_responses] + return [ + parse_reg_info_response(reg_info_response) + for reg_info_response in reg_info_responses + ] def expect_gdbremote_sequence(self): return expect_lldb_gdbserver_replay( @@ -619,7 +656,8 @@ self._server, self.test_sequence, self.DEFAULT_TIMEOUT * len(self.test_sequence), - self.logger) + self.logger, + ) _KNOWN_REGINFO_KEYS = [ "name", @@ -636,7 +674,7 @@ "container-regs", "invalidate-regs", "dynamic_size_dwarf_expr_bytes", - "dynamic_size_dwarf_len" + "dynamic_size_dwarf_len", ] def assert_valid_reg_info(self, reg_info): @@ -648,7 +686,7 @@ self.assertTrue("name" in reg_info) self.assertTrue("bitsize" in reg_info) - if not self.getArchitecture() == 'aarch64': + if not self.getArchitecture() == "aarch64": self.assertTrue("offset" in reg_info) self.assertTrue("encoding" in reg_info) @@ -678,9 +716,16 @@ def add_query_memory_region_packets(self, address): self.test_sequence.add_log_lines( - ["read packet: $qMemoryRegionInfo:{0:x}#00".format(address), - {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "memory_region_response"}}], - True) + [ + "read packet: $qMemoryRegionInfo:{0:x}#00".format(address), + { + "direction": "send", + "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", + "capture": {1: "memory_region_response"}, + }, + ], + True, + ) def parse_key_val_dict(self, key_val_text, allow_dupes=True): self.assertIsNotNone(key_val_text) @@ -698,7 +743,9 @@ else: self.fail( "key '{}' already present when attempting to add value '{}' (text='{}', dict={})".format( - key, val, key_val_text, kv_dict)) + key, val, key_val_text, kv_dict + ) + ) else: kv_dict[key] = val return kv_dict @@ -708,28 +755,30 @@ self.assertIsNotNone(context.get("memory_region_response")) # Pull out key:value; pairs. - mem_region_dict = self.parse_key_val_dict( - context.get("memory_region_response")) + mem_region_dict = self.parse_key_val_dict(context.get("memory_region_response")) # Validate keys are known. - for (key, val) in list(mem_region_dict.items()): - self.assertIn(key, - ["start", - "size", - "permissions", - "flags", - "name", - "error", - "dirty-pages", - "type"]) + for key, val in list(mem_region_dict.items()): + self.assertIn( + key, + [ + "start", + "size", + "permissions", + "flags", + "name", + "error", + "dirty-pages", + "type", + ], + ) self.assertIsNotNone(val) mem_region_dict["name"] = seven.unhexlify(mem_region_dict.get("name", "")) # Return the dictionary of key-value pairs for the memory region. return mem_region_dict - def assert_address_within_memory_region( - self, test_address, mem_region_dict): + def assert_address_within_memory_region(self, test_address, mem_region_dict): self.assertIsNotNone(mem_region_dict) self.assertTrue("start" in mem_region_dict) self.assertTrue("size" in mem_region_dict) @@ -741,24 +790,30 @@ if test_address < range_start: self.fail( "address 0x{0:x} comes before range 0x{1:x} - 0x{2:x} (size 0x{3:x})".format( - test_address, - range_start, - range_end, - range_size)) + test_address, range_start, range_end, range_size + ) + ) elif test_address >= range_end: self.fail( "address 0x{0:x} comes after range 0x{1:x} - 0x{2:x} (size 0x{3:x})".format( - test_address, - range_start, - range_end, - range_size)) + test_address, range_start, range_end, range_size + ) + ) def add_threadinfo_collection_packets(self): self.test_sequence.add_log_lines( - [{"type": "multi_response", "first_query": "qfThreadInfo", "next_query": "qsThreadInfo", - "append_iteration_suffix": False, "end_regex": re.compile(r"^\$(l)?#[0-9a-fA-F]{2}$"), - "save_key": "threadinfo_responses"}], - True) + [ + { + "type": "multi_response", + "first_query": "qfThreadInfo", + "next_query": "qsThreadInfo", + "append_iteration_suffix": False, + "end_regex": re.compile(r"^\$(l)?#[0-9a-fA-F]{2}$"), + "save_key": "threadinfo_responses", + } + ], + True, + ) def parse_threadinfo_packets(self, context): """Return an array of thread ids (decimal ints), one per thread.""" @@ -773,13 +828,20 @@ def launch_with_threads(self, thread_count): procs = self.prep_debug_monitor_and_inferior( - inferior_args=["thread:new"]*(thread_count-1) + ["trap"]) + inferior_args=["thread:new"] * (thread_count - 1) + ["trap"] + ) - self.test_sequence.add_log_lines([ + self.test_sequence.add_log_lines( + [ "read packet: $c#00", - {"direction": "send", + { + "direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})([^#]*)#..$", - "capture": {1: "stop_signo", 2: "stop_reply_kv"}}], True) + "capture": {1: "stop_signo", 2: "stop_reply_kv"}, + }, + ], + True, + ) self.add_threadinfo_collection_packets() context = self.expect_gdbremote_sequence() threads = self.parse_threadinfo_packets(context) @@ -787,49 +849,60 @@ return context, threads def add_set_breakpoint_packets( - self, - address, - z_packet_type=0, - do_continue=True, - breakpoint_kind=1): + self, address, z_packet_type=0, do_continue=True, breakpoint_kind=1 + ): self.test_sequence.add_log_lines( [ # Set the breakpoint. "read packet: $Z{2},{0:x},{1}#00".format( - address, breakpoint_kind, z_packet_type), + address, breakpoint_kind, z_packet_type + ), # Verify the stub could set it. "send packet: $OK#00", - ], True) + ], + True, + ) - if (do_continue): + if do_continue: self.test_sequence.add_log_lines( [ # Continue the inferior. "read packet: $c#63", # Expect a breakpoint stop report. - {"direction": "send", - "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", - "capture": {1: "stop_signo", - 2: "stop_thread_id"}}, - ], True) + { + "direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", + "capture": {1: "stop_signo", 2: "stop_thread_id"}, + }, + ], + True, + ) def add_remove_breakpoint_packets( - self, - address, - z_packet_type=0, - breakpoint_kind=1): + self, address, z_packet_type=0, breakpoint_kind=1 + ): self.test_sequence.add_log_lines( [ # Remove the breakpoint. "read packet: $z{2},{0:x},{1}#00".format( - address, breakpoint_kind, z_packet_type), + address, breakpoint_kind, z_packet_type + ), # Verify the stub could unset it. "send packet: $OK#00", - ], True) + ], + True, + ) def add_qSupported_packets(self, client_features=[]): - features = ''.join(';' + x for x in client_features) + features = "".join(";" + x for x in client_features) self.test_sequence.add_log_lines( - ["read packet: $qSupported{}#00".format(features), - {"direction": "send", "regex": r"^\$(.*)#[0-9a-fA-F]{2}", "capture": {1: "qSupported_response"}}, - ], True) + [ + "read packet: $qSupported{}#00".format(features), + { + "direction": "send", + "regex": r"^\$(.*)#[0-9a-fA-F]{2}", + "capture": {1: "qSupported_response"}, + }, + ], + True, + ) _KNOWN_QSUPPORTED_STUB_FEATURES = [ "augmented-libraries-svr4-read", @@ -872,18 +945,20 @@ else: if len(key) < 2: raise Exception( - "singular stub feature is too short: must be stub_feature{+,-,?}") + "singular stub feature is too short: must be stub_feature{+,-,?}" + ) supported_type = key[-1] key = key[:-1] if not supported_type in ["+", "-", "?"]: raise Exception( - "malformed stub feature: final character {} not in expected set (+,-,?)".format(supported_type)) + "malformed stub feature: final character {} not in expected set (+,-,?)".format( + supported_type + ) + ) supported_dict[key] = supported_type # Ensure we know the supported element if key not in self._KNOWN_QSUPPORTED_STUB_FEATURES: - raise Exception( - "unknown qSupported stub feature reported: %s" % - key) + raise Exception("unknown qSupported stub feature reported: %s" % key) return supported_dict @@ -905,7 +980,11 @@ def select_modifiable_register(self, reg_infos): """Find a register that can be read/written freely.""" - PREFERRED_REGISTER_NAMES = set(["rax", ]) + PREFERRED_REGISTER_NAMES = set( + [ + "rax", + ] + ) # First check for the first register from the preferred register name # set. @@ -913,12 +992,12 @@ self.assertIsNotNone(reg_infos) for reg_info in reg_infos: - if ("name" in reg_info) and ( - reg_info["name"] in PREFERRED_REGISTER_NAMES): + if ("name" in reg_info) and (reg_info["name"] in PREFERRED_REGISTER_NAMES): # We found a preferred register. Use it. return reg_info["lldb_register_index"] - if ("generic" in reg_info) and (reg_info["generic"] == "fp" or - reg_info["generic"] == "arg1"): + if ("generic" in reg_info) and ( + reg_info["generic"] == "fp" or reg_info["generic"] == "arg1" + ): # A frame pointer or first arg register will do as a # register to modify temporarily. alternative_register_index = reg_info["lldb_register_index"] @@ -932,7 +1011,7 @@ kv_dict = self.parse_key_val_dict(stop_key_vals_text) registers = {} - for (key, val) in list(kv_dict.items()): + for key, val in list(kv_dict.items()): if re.match(r"^[0-9a-fA-F]+$", key): registers[int(key, 16)] = val return registers @@ -953,8 +1032,7 @@ def find_generic_register_with_name(self, reg_infos, generic_name): self.assertIsNotNone(reg_infos) for reg_info in reg_infos: - if ("generic" in reg_info) and ( - reg_info["generic"] == generic_name): + if ("generic" in reg_info) and (reg_info["generic"] == generic_name): return reg_info return None @@ -999,7 +1077,7 @@ # break this test check for repeated keys. # # AT_IGNOREPPC = 22 - ignored_keys_for_arch = { 'powerpc64le' : [22] } + ignored_keys_for_arch = {"powerpc64le": [22]} arch = self.getArchitecture() ignore_keys = None if arch in ignored_keys_for_arch: @@ -1031,7 +1109,8 @@ auxv_dict[key] = value self.fail( - "should not reach here - implies required double zero entry not found") + "should not reach here - implies required double zero entry not found" + ) return auxv_dict def read_binary_data_in_chunks(self, command_prefix, chunk_length): @@ -1046,18 +1125,18 @@ self.test_sequence.add_log_lines( [ "read packet: ${}{:x},{:x}:#00".format( - command_prefix, - offset, - chunk_length), + command_prefix, offset, chunk_length + ), { "direction": "send", "regex": re.compile( - r"^\$([^E])(.*)#[0-9a-fA-F]{2}$", - re.MULTILINE | re.DOTALL), - "capture": { - 1: "response_type", - 2: "content_raw"}}], - True) + r"^\$([^E])(.*)#[0-9a-fA-F]{2}$", re.MULTILINE | re.DOTALL + ), + "capture": {1: "response_type", 2: "content_raw"}, + }, + ], + True, + ) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -1080,36 +1159,48 @@ return decoded_data def add_interrupt_packets(self): - self.test_sequence.add_log_lines([ - # Send the intterupt. - "read packet: {}".format(chr(3)), - # And wait for the stop notification. - {"direction": "send", - "regex": r"^\$T([0-9a-fA-F]{2})(.*)#[0-9a-fA-F]{2}$", - "capture": {1: "stop_signo", - 2: "stop_key_val_text"}}, - ], True) + self.test_sequence.add_log_lines( + [ + # Send the intterupt. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + { + "direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})(.*)#[0-9a-fA-F]{2}$", + "capture": {1: "stop_signo", 2: "stop_key_val_text"}, + }, + ], + True, + ) def parse_interrupt_packets(self, context): self.assertIsNotNone(context.get("stop_signo")) self.assertIsNotNone(context.get("stop_key_val_text")) - return (int(context["stop_signo"], 16), self.parse_key_val_dict( - context["stop_key_val_text"])) + return ( + int(context["stop_signo"], 16), + self.parse_key_val_dict(context["stop_key_val_text"]), + ) def add_QSaveRegisterState_packets(self, thread_id): if thread_id: # Use the thread suffix form. request = "read packet: $QSaveRegisterState;thread:{:x}#00".format( - thread_id) + thread_id + ) else: request = "read packet: $QSaveRegisterState#00" - self.test_sequence.add_log_lines([request, - {"direction": "send", - "regex": r"^\$(E?.*)#[0-9a-fA-F]{2}$", - "capture": {1: "save_response"}}, - ], - True) + self.test_sequence.add_log_lines( + [ + request, + { + "direction": "send", + "regex": r"^\$(E?.*)#[0-9a-fA-F]{2}$", + "capture": {1: "save_response"}, + }, + ], + True, + ) def parse_QSaveRegisterState_response(self, context): self.assertIsNotNone(context) @@ -1127,18 +1218,14 @@ if thread_id: # Use the thread suffix form. request = "read packet: $QRestoreRegisterState:{};thread:{:x}#00".format( - save_id, thread_id) + save_id, thread_id + ) else: - request = "read packet: $QRestoreRegisterState:{}#00".format( - save_id) + request = "read packet: $QRestoreRegisterState:{}#00".format(save_id) - self.test_sequence.add_log_lines([ - request, - "send packet: $OK#00" - ], True) + self.test_sequence.add_log_lines([request, "send packet: $OK#00"], True) - def flip_all_bits_in_each_register_value( - self, reg_infos, endian, thread_id=None): + def flip_all_bits_in_each_register_value(self, reg_infos, endian, thread_id=None): self.assertIsNotNone(reg_infos) successful_writes = 0 @@ -1157,24 +1244,31 @@ # Handle thread suffix. if thread_id: p_request = "read packet: $p{:x};thread:{:x}#00".format( - reg_index, thread_id) + reg_index, thread_id + ) else: p_request = "read packet: $p{:x}#00".format(reg_index) # Read the existing value. self.reset_test_sequence() - self.test_sequence.add_log_lines([ - p_request, - {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, - ], True) + self.test_sequence.add_log_lines( + [ + p_request, + { + "direction": "send", + "regex": r"^\$([0-9a-fA-F]+)#", + "capture": {1: "p_response"}, + }, + ], + True, + ) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) # Verify the response length. p_response = context.get("p_response") self.assertIsNotNone(p_response) - initial_reg_value = unpack_register_hex_unsigned( - endian, p_response) + initial_reg_value = unpack_register_hex_unsigned(endian, p_response) # Flip the value by xoring with all 1s all_one_bits_raw = "ff" * (int(reg_info["bitsize"]) // 8) @@ -1184,21 +1278,33 @@ # Handle thread suffix for P. if thread_id: P_request = "read packet: $P{:x}={};thread:{:x}#00".format( - reg_index, pack_register_hex( - endian, flipped_bits_int, byte_size=reg_byte_size), thread_id) + reg_index, + pack_register_hex( + endian, flipped_bits_int, byte_size=reg_byte_size + ), + thread_id, + ) else: P_request = "read packet: $P{:x}={}#00".format( - reg_index, pack_register_hex( - endian, flipped_bits_int, byte_size=reg_byte_size)) + reg_index, + pack_register_hex( + endian, flipped_bits_int, byte_size=reg_byte_size + ), + ) # Write the flipped value to the register. self.reset_test_sequence() - self.test_sequence.add_log_lines([P_request, - {"direction": "send", - "regex": r"^\$(OK|E[0-9a-fA-F]+)#[0-9a-fA-F]{2}", - "capture": {1: "P_response"}}, - ], - True) + self.test_sequence.add_log_lines( + [ + P_request, + { + "direction": "send", + "regex": r"^\$(OK|E[0-9a-fA-F]+)#[0-9a-fA-F]{2}", + "capture": {1: "P_response"}, + }, + ], + True, + ) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -1217,17 +1323,25 @@ # value. if P_response == "OK": self.reset_test_sequence() - self.test_sequence.add_log_lines([ - p_request, - {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, - ], True) + self.test_sequence.add_log_lines( + [ + p_request, + { + "direction": "send", + "regex": r"^\$([0-9a-fA-F]+)#", + "capture": {1: "p_response"}, + }, + ], + True, + ) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) verify_p_response_raw = context.get("p_response") self.assertIsNotNone(verify_p_response_raw) verify_bits = unpack_register_hex_unsigned( - endian, verify_p_response_raw) + endian, verify_p_response_raw + ) if verify_bits != flipped_bits_int: # Some registers, like mxcsrmask and others, will permute what's written. Adjust succeed/fail counts. @@ -1244,8 +1358,7 @@ return False if reg_info["set"] != "General Purpose Registers": return False - if ("container-regs" in reg_info) and ( - len(reg_info["container-regs"]) > 0): + if ("container-regs" in reg_info) and (len(reg_info["container-regs"]) > 0): # Don't try to bit flip registers contained in another register. return False if re.match("^.s$", reg_info["name"]): @@ -1271,16 +1384,24 @@ # Handle thread suffix. if thread_id: p_request = "read packet: $p{:x};thread:{:x}#00".format( - reg_index, thread_id) + reg_index, thread_id + ) else: p_request = "read packet: $p{:x}#00".format(reg_index) # Read it with p. self.reset_test_sequence() - self.test_sequence.add_log_lines([ - p_request, - {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, - ], True) + self.test_sequence.add_log_lines( + [ + p_request, + { + "direction": "send", + "regex": r"^\$([0-9a-fA-F]+)#", + "capture": {1: "p_response"}, + }, + ], + True, + ) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -1290,18 +1411,22 @@ self.assertTrue(len(p_response) > 0) self.assertFalse(p_response[0] == "E") - values[reg_index] = unpack_register_hex_unsigned( - endian, p_response) + values[reg_index] = unpack_register_hex_unsigned(endian, p_response) return values def add_vCont_query_packets(self): - self.test_sequence.add_log_lines(["read packet: $vCont?#49", - {"direction": "send", - "regex": r"^\$(vCont)?(.*)#[0-9a-fA-F]{2}$", - "capture": {2: "vCont_query_response"}}, - ], - True) + self.test_sequence.add_log_lines( + [ + "read packet: $vCont?#49", + { + "direction": "send", + "regex": r"^\$(vCont)?(.*)#[0-9a-fA-F]{2}$", + "capture": {2: "vCont_query_response"}, + }, + ], + True, + ) def parse_vCont_query_response(self, context): self.assertIsNotNone(context) @@ -1312,17 +1437,19 @@ if not vCont_query_response or len(vCont_query_response) == 0: return {} - return {key: 1 for key in vCont_query_response.split( - ";") if key and len(key) > 0} + return { + key: 1 for key in vCont_query_response.split(";") if key and len(key) > 0 + } def count_single_steps_until_true( - self, - thread_id, - predicate, - args, - max_step_count=100, - use_Hc_packet=True, - step_instruction="s"): + self, + thread_id, + predicate, + args, + max_step_count=100, + use_Hc_packet=True, + step_instruction="s", + ): """Used by single step test that appears in a few different contexts.""" single_step_count = 0 @@ -1332,7 +1459,8 @@ # Build the packet for the single step instruction. We replace # {thread}, if present, with the thread_id. step_packet = "read packet: ${}#00".format( - re.sub(r"{thread}", "{:x}".format(thread_id), step_instruction)) + re.sub(r"{thread}", "{:x}".format(thread_id), step_instruction) + ) # print("\nstep_packet created: {}\n".format(step_packet)) # Single step. @@ -1342,22 +1470,30 @@ [ # Set the continue thread. "read packet: $Hc{0:x}#00".format(thread_id), "send packet: $OK#00", - ], True) - self.test_sequence.add_log_lines([ - # Single step. - step_packet, - # "read packet: $vCont;s:{0:x}#00".format(thread_id), - # Expect a breakpoint stop report. - {"direction": "send", - "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", - "capture": {1: "stop_signo", - 2: "stop_thread_id"}}, - ], True) + ], + True, + ) + self.test_sequence.add_log_lines( + [ + # Single step. + step_packet, + # "read packet: $vCont;s:{0:x}#00".format(thread_id), + # Expect a breakpoint stop report. + { + "direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", + "capture": {1: "stop_signo", 2: "stop_thread_id"}, + }, + ], + True, + ) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) self.assertIsNotNone(context.get("stop_signo")) - self.assertEqual(int(context.get("stop_signo"), 16), - lldbutil.get_signal_number('SIGTRAP')) + self.assertEqual( + int(context.get("stop_signo"), 16), + lldbutil.get_signal_number("SIGTRAP"), + ) single_step_count += 1 @@ -1378,11 +1514,22 @@ # Read g_c1 and g_c2 contents. self.reset_test_sequence() self.test_sequence.add_log_lines( - ["read packet: $m{0:x},{1:x}#00".format(g_c1_address, 1), - {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "g_c1_contents"}}, - "read packet: $m{0:x},{1:x}#00".format(g_c2_address, 1), - {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "g_c2_contents"}}], - True) + [ + "read packet: $m{0:x},{1:x}#00".format(g_c1_address, 1), + { + "direction": "send", + "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", + "capture": {1: "g_c1_contents"}, + }, + "read packet: $m{0:x},{1:x}#00".format(g_c2_address, 1), + { + "direction": "send", + "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", + "capture": {1: "g_c2_contents"}, + }, + ], + True, + ) # Run the packet stream. context = self.expect_gdbremote_sequence() @@ -1393,10 +1540,12 @@ self.assertIsNotNone(context.get("g_c2_contents")) return (seven.unhexlify(context.get("g_c1_contents")) == expected_g_c1) and ( - seven.unhexlify(context.get("g_c2_contents")) == expected_g_c2) + seven.unhexlify(context.get("g_c2_contents")) == expected_g_c2 + ) def single_step_only_steps_one_instruction( - self, use_Hc_packet=True, step_instruction="s"): + self, use_Hc_packet=True, step_instruction="s" + ): """Used by single step test that appears in a few different contexts.""" # Start up the inferior. procs = self.prep_debug_monitor_and_inferior( @@ -1406,7 +1555,9 @@ "get-data-address-hex:g_c2", "sleep:1", "call-function:swap_chars", - "sleep:5"]) + "sleep:5", + ] + ) # Run the process self.test_sequence.add_log_lines( @@ -1414,13 +1565,26 @@ "read packet: $c#63", # Match output line that prints the memory address of the function call entry point. # Note we require launch-only testing so we can get inferior otuput. - {"type": "output_match", "regex": r"^code address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\n$", - "capture": {1: "function_address", 2: "g_c1_address", 3: "g_c2_address"}}, + { + "type": "output_match", + "regex": r"^code address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\n$", + "capture": { + 1: "function_address", + 2: "g_c1_address", + 3: "g_c2_address", + }, + }, # Now stop the inferior. "read packet: {}".format(chr(3)), # And wait for the stop notification. - {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], - True) + { + "direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", + "capture": {1: "stop_signo", 2: "stop_thread_id"}, + }, + ], + True, + ) # Run the packet stream. context = self.expect_gdbremote_sequence() @@ -1449,16 +1613,16 @@ BREAKPOINT_KIND = 1 self.reset_test_sequence() self.add_set_breakpoint_packets( - function_address, - do_continue=True, - breakpoint_kind=BREAKPOINT_KIND) + function_address, do_continue=True, breakpoint_kind=BREAKPOINT_KIND + ) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) # Remove the breakpoint. self.reset_test_sequence() self.add_remove_breakpoint_packets( - function_address, breakpoint_kind=BREAKPOINT_KIND) + function_address, breakpoint_kind=BREAKPOINT_KIND + ) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -1475,25 +1639,27 @@ # Might need to work through function entry prologue code. args["expected_g_c1"] = "1" args["expected_g_c2"] = "1" - (state_reached, - step_count) = self.count_single_steps_until_true(main_thread_id, - self.g_c1_c2_contents_are, - args, - max_step_count=25, - use_Hc_packet=use_Hc_packet, - step_instruction=step_instruction) + (state_reached, step_count) = self.count_single_steps_until_true( + main_thread_id, + self.g_c1_c2_contents_are, + args, + max_step_count=25, + use_Hc_packet=use_Hc_packet, + step_instruction=step_instruction, + ) self.assertTrue(state_reached) # Verify we hit the next state. args["expected_g_c1"] = "1" args["expected_g_c2"] = "0" - (state_reached, - step_count) = self.count_single_steps_until_true(main_thread_id, - self.g_c1_c2_contents_are, - args, - max_step_count=5, - use_Hc_packet=use_Hc_packet, - step_instruction=step_instruction) + (state_reached, step_count) = self.count_single_steps_until_true( + main_thread_id, + self.g_c1_c2_contents_are, + args, + max_step_count=5, + use_Hc_packet=use_Hc_packet, + step_instruction=step_instruction, + ) self.assertTrue(state_reached) expected_step_count = 1 arch = self.getArchitecture() @@ -1513,8 +1679,10 @@ if re.match("arm64", arch): before_materialization_step_count = 4 after_matrialization_step_count = 1 - self.assertIn(step_count, [before_materialization_step_count, - after_matrialization_step_count]) + self.assertIn( + step_count, + [before_materialization_step_count, after_matrialization_step_count], + ) expected_step_count = after_matrialization_step_count else: self.assertEqual(step_count, expected_step_count) @@ -1522,43 +1690,52 @@ # Verify we hit the next state. args["expected_g_c1"] = "0" args["expected_g_c2"] = "0" - (state_reached, - step_count) = self.count_single_steps_until_true(main_thread_id, - self.g_c1_c2_contents_are, - args, - max_step_count=5, - use_Hc_packet=use_Hc_packet, - step_instruction=step_instruction) + (state_reached, step_count) = self.count_single_steps_until_true( + main_thread_id, + self.g_c1_c2_contents_are, + args, + max_step_count=5, + use_Hc_packet=use_Hc_packet, + step_instruction=step_instruction, + ) self.assertTrue(state_reached) self.assertEqual(step_count, expected_step_count) # Verify we hit the next state. args["expected_g_c1"] = "0" args["expected_g_c2"] = "1" - (state_reached, - step_count) = self.count_single_steps_until_true(main_thread_id, - self.g_c1_c2_contents_are, - args, - max_step_count=5, - use_Hc_packet=use_Hc_packet, - step_instruction=step_instruction) + (state_reached, step_count) = self.count_single_steps_until_true( + main_thread_id, + self.g_c1_c2_contents_are, + args, + max_step_count=5, + use_Hc_packet=use_Hc_packet, + step_instruction=step_instruction, + ) self.assertTrue(state_reached) self.assertEqual(step_count, expected_step_count) def maybe_strict_output_regex(self, regex): - return '.*' + regex + \ - '.*' if lldbplatformutil.hasChattyStderr(self) else '^' + regex + '$' + return ( + ".*" + regex + ".*" + if lldbplatformutil.hasChattyStderr(self) + else "^" + regex + "$" + ) def install_and_create_launch_args(self): exe_path = self.getBuildArtifact("a.out") if not lldb.remote_platform: return [exe_path] - remote_path = lldbutil.append_to_process_working_directory(self, - os.path.basename(exe_path)) + remote_path = lldbutil.append_to_process_working_directory( + self, os.path.basename(exe_path) + ) remote_file_spec = lldb.SBFileSpec(remote_path, False) - err = lldb.remote_platform.Install(lldb.SBFileSpec(exe_path, True), - remote_file_spec) + err = lldb.remote_platform.Install( + lldb.SBFileSpec(exe_path, True), remote_file_spec + ) if err.Fail(): - raise Exception("remote_platform.Install('%s', '%s') failed: %s" % - (exe_path, remote_path, err)) + raise Exception( + "remote_platform.Install('%s', '%s') failed: %s" + % (exe_path, remote_path, err) + ) return [remote_path] diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py @@ -16,6 +16,7 @@ from textwrap import dedent import shutil + def _get_support_exe(basename): support_dir = lldb.SBHostOS.GetLLDBPath(lldb.ePathTypeSupportExecutableDir) @@ -40,14 +41,19 @@ A path to the debugserver exe if it is found to exist; otherwise, returns None. """ - if configuration.arch and configuration.arch == "x86_64" and \ - platform.machine().startswith("arm64"): - return '/Library/Apple/usr/libexec/oah/debugserver' + if ( + configuration.arch + and configuration.arch == "x86_64" + and platform.machine().startswith("arm64") + ): + return "/Library/Apple/usr/libexec/oah/debugserver" return _get_support_exe("debugserver") -_LOG_LINE_REGEX = re.compile(r'^(lldb-server|debugserver)\s+<\s*(\d+)>' + - '\s+(read|send)\s+packet:\s+(.+)$') + +_LOG_LINE_REGEX = re.compile( + r"^(lldb-server|debugserver)\s+<\s*(\d+)>" + "\s+(read|send)\s+packet:\s+(.+)$" +) def _is_packet_lldb_gdbserver_input(packet_type, llgs_input_is_read): @@ -65,11 +71,11 @@ True if the packet should be considered input for lldb-gdbserver; False otherwise. """ - if packet_type == 'read': + if packet_type == "read": # when llgs is the read side, then a read packet is meant for # input to llgs (when captured from the llgs/debugserver exe). return llgs_input_is_read - elif packet_type == 'send': + elif packet_type == "send": # when llgs is the send side, then a send packet is meant to # be input to llgs (when captured from the lldb exe). return not llgs_input_is_read @@ -78,7 +84,7 @@ raise "Unknown packet type: {}".format(packet_type) -_STRIP_CHECKSUM_REGEX = re.compile(r'#[0-9a-fA-F]{2}$') +_STRIP_CHECKSUM_REGEX = re.compile(r"#[0-9a-fA-F]{2}$") _STRIP_COMMAND_PREFIX_REGEX = re.compile(r"^\$") _STRIP_COMMAND_PREFIX_M_REGEX = re.compile(r"^\$m") @@ -87,17 +93,14 @@ # strip off the checksum digits of the packet. When we're in # no-ack mode, the # checksum is ignored, and should not be cause # for a mismatched packet. - actual_stripped = _STRIP_CHECKSUM_REGEX.sub('', actual_packet) - expected_stripped = _STRIP_CHECKSUM_REGEX.sub('', expected_packet) + actual_stripped = _STRIP_CHECKSUM_REGEX.sub("", actual_packet) + expected_stripped = _STRIP_CHECKSUM_REGEX.sub("", expected_packet) asserter.assertEqual(actual_stripped, expected_stripped) def expect_lldb_gdbserver_replay( - asserter, - server, - test_sequence, - timeout_seconds, - logger=None): + asserter, server, test_sequence, timeout_seconds, logger=None +): """Replay socket communication with lldb-gdbserver and verify responses. Args: @@ -149,8 +152,7 @@ packet_desc = "^C" else: packet_desc = send_packet - logger.info( - "sending packet to remote: {}".format(packet_desc)) + logger.info("sending packet to remote: {}".format(packet_desc)) server.send_raw(send_packet.encode()) else: # This is an entry expecting to receive content from the remote @@ -168,14 +170,16 @@ content = seven.bitcast_to_string(content) except socket.timeout: asserter.fail( - "timed out while waiting for '{}':\n{}".format(sequence_entry, server)) + "timed out while waiting for '{}':\n{}".format( + sequence_entry, server + ) + ) # Give the sequence entry the opportunity to match the content. # Output matchers might match or pass after more output accumulates. # Other packet types generally must match. asserter.assertIsNotNone(content) - context = sequence_entry.assert_match( - asserter, content, context=context) + context = sequence_entry.assert_match(asserter, content, context=context) # Move on to next sequence entry as needed. Some sequence entries support executing multiple # times in different states (for looping over query/response @@ -194,9 +198,9 @@ def gdbremote_hex_encode_string(str): - output = '' + output = "" for c in str: - output += '{0:02x}'.format(ord(c)) + output += "{0:02x}".format(ord(c)) return output @@ -208,12 +212,11 @@ checksum = 0 for c in str: checksum += ord(c) - return '$' + str + '#{0:02x}'.format(checksum % 256) + return "$" + str + "#{0:02x}".format(checksum % 256) def build_gdbremote_A_packet(args_list): - """Given a list of args, create a properly-formed $A packet containing each arg. - """ + """Given a list of args, create a properly-formed $A packet containing each arg.""" payload = "A" # build the arg content @@ -221,7 +224,7 @@ for arg in args_list: # Comma-separate the args. if arg_index > 0: - payload += ',' + payload += "," # Hex-encode the arg. hex_arg = gdbremote_hex_encode_string(arg) @@ -249,7 +252,7 @@ for kv in response_packet.split(";"): if len(kv) < 1: continue - (key, val) = kv.split(':') + (key, val) = kv.split(":") values[key] = val return values @@ -280,15 +283,15 @@ if not value_string or len(value_string) < 1: raise Exception("value_string cannot be None or empty") - if endian == 'little': + if endian == "little": value = 0 i = 0 while len(value_string) > 0: - value += (ord(value_string[0]) << i) + value += ord(value_string[0]) << i value_string = value_string[1:] i += 8 return value - elif endian == 'big': + elif endian == "big": value = 0 while len(value_string) > 0: value = (value << 8) + ord(value_string[0]) @@ -306,15 +309,15 @@ if not value_string or len(value_string) < 1: raise Exception("value_string cannot be None or empty") - if endian == 'little': + if endian == "little": value = 0 i = 0 while len(value_string) > 0: - value += (int(value_string[0:2], 16) << i) + value += int(value_string[0:2], 16) << i value_string = value_string[2:] i += 8 return value - elif endian == 'big': + elif endian == "big": return int(value_string, 16) else: # pdp is valid but need to add parse code once needed. @@ -326,21 +329,21 @@ if not endian: raise Exception("endian cannot be None") - if endian == 'little': + if endian == "little": # Create the litt-endian return value. retval = "" while value != 0: - retval = retval + "{:02x}".format(value & 0xff) + retval = retval + "{:02x}".format(value & 0xFF) value = value >> 8 if byte_size: # Add zero-fill to the right/end (MSB side) of the value. retval += "00" * (byte_size - len(retval) // 2) return retval - elif endian == 'big': + elif endian == "big": retval = "" while value != 0: - retval = "{:02x}".format(value & 0xff) + retval + retval = "{:02x}".format(value & 0xFF) + retval value = value >> 8 if byte_size: # Add zero-fill to the left/front (MSB side) of the value. @@ -353,19 +356,14 @@ class GdbRemoteEntryBase(object): - def is_output_matcher(self): return False class GdbRemoteEntry(GdbRemoteEntryBase): - def __init__( - self, - is_send_to_remote=True, - exact_payload=None, - regex=None, - capture=None): + self, is_send_to_remote=True, exact_payload=None, regex=None, capture=None + ): """Create an entry representing one piece of the I/O to/from a gdb remote debug monitor. Args: @@ -413,10 +411,12 @@ def get_send_packet(self): if not self.is_send_to_remote(): raise Exception( - "get_send_packet() called on GdbRemoteEntry that is not a send-to-remote packet") + "get_send_packet() called on GdbRemoteEntry that is not a send-to-remote packet" + ) if not self.exact_payload: raise Exception( - "get_send_packet() called on GdbRemoteEntry but it doesn't have an exact payload") + "get_send_packet() called on GdbRemoteEntry but it doesn't have an exact payload" + ) return self.exact_payload def _assert_exact_payload_match(self, asserter, actual_packet): @@ -429,7 +429,9 @@ if not match: asserter.fail( "regex '{}' failed to match against content '{}'".format( - self.regex.pattern, actual_packet)) + self.regex.pattern, actual_packet + ) + ) if self.capture: # Handle captures. @@ -447,7 +449,8 @@ # remote debug monitor. if self.is_send_to_remote(): raise Exception( - "Attempted to match a packet being sent to the remote debug monitor, doesn't make sense.") + "Attempted to match a packet being sent to the remote debug monitor, doesn't make sense." + ) # Create a new context if needed. if not context: @@ -463,7 +466,8 @@ return self._assert_regex_match(asserter, actual_packet, context) else: raise Exception( - "Don't know how to match a remote-sent packet when exact_payload isn't specified.") + "Don't know how to match a remote-sent packet when exact_payload isn't specified." + ) class MultiResponseGdbRemoteEntry(GdbRemoteEntryBase): @@ -507,13 +511,11 @@ raise "either next_query or query key must be specified for MultiResponseGdbRemoteEntry" self._first_query = params.get("first_query", self._next_query) - self._append_iteration_suffix = params.get( - "append_iteration_suffix", False) + self._append_iteration_suffix = params.get("append_iteration_suffix", False) self._iteration = 0 self._end_regex = params["end_regex"] self._save_key = params["save_key"] - self._runaway_response_count = params.get( - "runaway_response_count", 10000) + self._runaway_response_count = params.get("runaway_response_count", 10000) self._is_send_to_remote = True self._end_matched = False @@ -523,10 +525,12 @@ def get_send_packet(self): if not self.is_send_to_remote(): raise Exception( - "get_send_packet() called on MultiResponseGdbRemoteEntry that is not in the send state") + "get_send_packet() called on MultiResponseGdbRemoteEntry that is not in the send state" + ) if self._end_matched: raise Exception( - "get_send_packet() called on MultiResponseGdbRemoteEntry but end of query/response sequence has already been seen.") + "get_send_packet() called on MultiResponseGdbRemoteEntry but end of query/response sequence has already been seen." + ) # Choose the first or next query for the base payload. if self._iteration == 0 and self._first_query: @@ -556,11 +560,13 @@ # monitor. if self.is_send_to_remote(): raise Exception( - "assert_match() called on MultiResponseGdbRemoteEntry but state is set to send a query packet.") + "assert_match() called on MultiResponseGdbRemoteEntry but state is set to send a query packet." + ) if self._end_matched: raise Exception( - "assert_match() called on MultiResponseGdbRemoteEntry but end of query/response sequence has already been seen.") + "assert_match() called on MultiResponseGdbRemoteEntry but end of query/response sequence has already been seen." + ) # Set up a context as needed. if not context: @@ -580,12 +586,9 @@ # Check for a runaway response cycle. if len(context[self._save_key]) >= self._runaway_response_count: raise Exception( - "runaway query/response cycle detected: %d responses captured so far. Last response: %s" % - (len( - context[ - self._save_key]), context[ - self._save_key][ - -1])) + "runaway query/response cycle detected: %d responses captured so far. Last response: %s" + % (len(context[self._save_key]), context[self._save_key][-1]) + ) # Flip the mode to send for generating the query. self._is_send_to_remote = True @@ -630,8 +633,10 @@ if not self._regex_mode in ["match", "search"]: raise Exception( - "unsupported regex mode \"{}\": must be \"match\" or \"search\"".format( - self._regex_mode)) + 'unsupported regex mode "{}": must be "match" or "search"'.format( + self._regex_mode + ) + ) def is_output_matcher(self): return True @@ -653,7 +658,8 @@ # Validate that we haven't already matched. if self._matched: raise Exception( - "invalid state - already matched, attempting to match again") + "invalid state - already matched, attempting to match again" + ) # If we don't have any content yet, we don't match. if len(accumulated_output) < 1: @@ -665,9 +671,7 @@ elif self._regex_mode == "search": match = self._regex.search(accumulated_output) else: - raise Exception( - "Unexpected regex mode: {}".format( - self._regex_mode)) + raise Exception("Unexpected regex mode: {}".format(self._regex_mode)) # If we don't match, wait to try again after next $O content, or time # out. @@ -685,16 +689,14 @@ for group_index, var_name in list(self._capture.items()): capture_text = match.group(group_index) if not capture_text: - raise Exception( - "No content for group index {}".format(group_index)) + raise Exception("No content for group index {}".format(group_index)) context[var_name] = capture_text return context class GdbRemoteTestSequence(object): - - _LOG_LINE_REGEX = re.compile(r'^.*(read|send)\s+packet:\s+(.+)$') + _LOG_LINE_REGEX = re.compile(r"^.*(read|send)\s+packet:\s+(.+)$") def __init__(self, logger): self.entries = [] @@ -713,26 +715,26 @@ if match: playback_packet = match.group(2) direction = match.group(1) - if _is_packet_lldb_gdbserver_input( - direction, remote_input_is_read): + if _is_packet_lldb_gdbserver_input(direction, remote_input_is_read): # Handle as something to send to the remote debug monitor. # if self.logger: # self.logger.info("processed packet to send to remote: {}".format(playback_packet)) self.entries.append( GdbRemoteEntry( - is_send_to_remote=True, - exact_payload=playback_packet)) + is_send_to_remote=True, exact_payload=playback_packet + ) + ) else: # Log line represents content to be expected from the remote debug monitor. # if self.logger: # self.logger.info("receiving packet from llgs, should match: {}".format(playback_packet)) self.entries.append( GdbRemoteEntry( - is_send_to_remote=False, - exact_payload=playback_packet)) + is_send_to_remote=False, exact_payload=playback_packet + ) + ) else: - raise Exception( - "failed to interpret log line: {}".format(line)) + raise Exception("failed to interpret log line: {}".format(line)) elif isinstance(line, dict): entry_type = line.get("type", "regex_capture") if entry_type == "regex_capture": @@ -745,29 +747,27 @@ if regex and (isinstance(regex, str)): regex = re.compile(regex, re.DOTALL) - if _is_packet_lldb_gdbserver_input( - direction, remote_input_is_read): + if _is_packet_lldb_gdbserver_input(direction, remote_input_is_read): # Handle as something to send to the remote debug monitor. # if self.logger: # self.logger.info("processed dict sequence to send to remote") self.entries.append( GdbRemoteEntry( - is_send_to_remote=True, - regex=regex, - capture=capture)) + is_send_to_remote=True, regex=regex, capture=capture + ) + ) else: # Log line represents content to be expected from the remote debug monitor. # if self.logger: # self.logger.info("processed dict sequence to match receiving from remote") self.entries.append( GdbRemoteEntry( - is_send_to_remote=False, - regex=regex, - capture=capture)) + is_send_to_remote=False, regex=regex, capture=capture + ) + ) elif entry_type == "multi_response": self.entries.append(MultiResponseGdbRemoteEntry(line)) elif entry_type == "output_match": - regex = line.get("regex", None) # Compile the regex. if regex and (isinstance(regex, str)): @@ -777,11 +777,11 @@ capture = line.get("capture", None) self.entries.append( MatchRemoteOutputEntry( - regex=regex, - regex_mode=regex_mode, - capture=capture)) + regex=regex, regex_mode=regex_mode, capture=capture + ) + ) else: - raise Exception("unknown entry type \"%s\"" % entry_type) + raise Exception('unknown entry type "%s"' % entry_type) def process_is_running(pid, unknown_value=True): @@ -804,8 +804,8 @@ """ if not isinstance(pid, int): raise Exception( - "pid must be an integral type (actual type: %s)" % str( - type(pid))) + "pid must be an integral type (actual type: %s)" % str(type(pid)) + ) process_ids = [] @@ -813,20 +813,21 @@ # Don't know how to get list of running process IDs on a remote # platform return unknown_value - elif platform.system() in ['Darwin', 'Linux', 'FreeBSD', 'NetBSD']: + elif platform.system() in ["Darwin", "Linux", "FreeBSD", "NetBSD"]: # Build the list of running process ids output = subprocess.check_output( - "ps ax | awk '{ print $1; }'", shell=True).decode("utf-8") - text_process_ids = output.split('\n')[1:] + "ps ax | awk '{ print $1; }'", shell=True + ).decode("utf-8") + text_process_ids = output.split("\n")[1:] # Convert text pids to ints - process_ids = [int(text_pid) - for text_pid in text_process_ids if text_pid != ''] - elif platform.system() == 'Windows': + process_ids = [int(text_pid) for text_pid in text_process_ids if text_pid != ""] + elif platform.system() == "Windows": output = subprocess.check_output( - "for /f \"tokens=2 delims=,\" %F in ('tasklist /nh /fi \"PID ne 0\" /fo csv') do @echo %~F", shell=True).decode("utf-8") - text_process_ids = output.split('\n')[1:] - process_ids = [int(text_pid) - for text_pid in text_process_ids if text_pid != ''] + 'for /f "tokens=2 delims=," %F in (\'tasklist /nh /fi "PID ne 0" /fo csv\') do @echo %~F', + shell=True, + ).decode("utf-8") + text_process_ids = output.split("\n")[1:] + process_ids = [int(text_pid) for text_pid in text_process_ids if text_pid != ""] # elif {your_platform_here}: # fill in process_ids as a list of int type process IDs running on # the local system. @@ -851,13 +852,12 @@ class Server(object): - - _GDB_REMOTE_PACKET_REGEX = re.compile(br'^([\$%][^\#]*)#[0-9a-fA-F]{2}') + _GDB_REMOTE_PACKET_REGEX = re.compile(rb"^([\$%][^\#]*)#[0-9a-fA-F]{2}") class ChecksumMismatch(Exception): pass - def __init__(self, sock, proc = None): + def __init__(self, sock, proc=None): self._accumulated_output = b"" self._receive_buffer = b"" self._normal_queue = [] @@ -872,7 +872,7 @@ self.send_raw(b"+") def send_packet(self, packet): - self.send_raw(b'$%s#%02x'%(packet, self._checksum(packet))) + self.send_raw(b"$%s#%02x" % (packet, self._checksum(packet))) @staticmethod def _checksum(packet): @@ -901,13 +901,13 @@ self._normal_queue += [b"+"] self._receive_buffer = self._receive_buffer[1:] else: - packet_match = self._GDB_REMOTE_PACKET_REGEX.match( - self._receive_buffer) + packet_match = self._GDB_REMOTE_PACKET_REGEX.match(self._receive_buffer) if packet_match: # Our receive buffer matches a packet at the # start of the receive buffer. new_output_content = _handle_output_packet_string( - packet_match.group(1)) + packet_match.group(1) + ) if new_output_content: # This was an $O packet with new content. self._accumulated_output += new_output_content @@ -919,7 +919,8 @@ # Remove the parsed packet from the receive # buffer. self._receive_buffer = self._receive_buffer[ - len(packet_match.group(0)):] + len(packet_match.group(0)) : + ] else: # We don't have enough in the receive bufferto make a full # packet. Stop trying until we read more. @@ -941,7 +942,8 @@ def get_normal_packet(self): frame = self.get_raw_normal_packet() - if frame == b"+": return frame + if frame == b"+": + return frame return self._get_payload(frame) def get_accumulated_output(self): @@ -953,12 +955,19 @@ return output def __str__(self): - return dedent("""\ + return dedent( + """\ server '{}' on '{}' _receive_buffer: {} _normal_queue: {} _output_queue: {} _accumulated_output: {} - """).format(self._proc, self._sock, self._receive_buffer, - self._normal_queue, self._output_queue, - self._accumulated_output) + """ + ).format( + self._proc, + self._sock, + self._receive_buffer, + self._normal_queue, + self._output_queue, + self._accumulated_output, + ) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py @@ -1,4 +1,3 @@ - from lldbsuite.test.lldbtest import * import os import vscode @@ -6,53 +5,55 @@ class VSCodeTestCaseBase(TestBase): - NO_DEBUG_INFO_TESTCASE = True def create_debug_adaptor(self, lldbVSCodeEnv=None): - '''Create the Visual Studio Code debug adaptor''' - self.assertTrue(is_exe(self.lldbVSCodeExec), - 'lldb-vscode must exist and be executable') - log_file_path = self.getBuildArtifact('vscode.txt') + """Create the Visual Studio Code debug adaptor""" + self.assertTrue( + is_exe(self.lldbVSCodeExec), "lldb-vscode must exist and be executable" + ) + log_file_path = self.getBuildArtifact("vscode.txt") self.vscode = vscode.DebugAdaptor( - executable=self.lldbVSCodeExec, init_commands=self.setUpCommands(), - log_file=log_file_path, env=lldbVSCodeEnv) + executable=self.lldbVSCodeExec, + init_commands=self.setUpCommands(), + log_file=log_file_path, + env=lldbVSCodeEnv, + ) def build_and_create_debug_adaptor(self, lldbVSCodeEnv=None): self.build() self.create_debug_adaptor(lldbVSCodeEnv) def set_source_breakpoints(self, source_path, lines, data=None): - '''Sets source breakpoints and returns an array of strings containing - the breakpoint IDs ("1", "2") for each breakpoint that was set. - Parameter data is array of data objects for breakpoints. - Each object in data is 1:1 mapping with the entry in lines. - It contains optional location/hitCondition/logMessage parameters. - ''' - response = self.vscode.request_setBreakpoints( - source_path, lines, data) + """Sets source breakpoints and returns an array of strings containing + the breakpoint IDs ("1", "2") for each breakpoint that was set. + Parameter data is array of data objects for breakpoints. + Each object in data is 1:1 mapping with the entry in lines. + It contains optional location/hitCondition/logMessage parameters. + """ + response = self.vscode.request_setBreakpoints(source_path, lines, data) if response is None: return [] - breakpoints = response['body']['breakpoints'] + breakpoints = response["body"]["breakpoints"] breakpoint_ids = [] for breakpoint in breakpoints: - breakpoint_ids.append('%i' % (breakpoint['id'])) + breakpoint_ids.append("%i" % (breakpoint["id"])) return breakpoint_ids - def set_function_breakpoints(self, functions, condition=None, - hitCondition=None): - '''Sets breakpoints by function name given an array of function names - and returns an array of strings containing the breakpoint IDs - ("1", "2") for each breakpoint that was set. - ''' + def set_function_breakpoints(self, functions, condition=None, hitCondition=None): + """Sets breakpoints by function name given an array of function names + and returns an array of strings containing the breakpoint IDs + ("1", "2") for each breakpoint that was set. + """ response = self.vscode.request_setFunctionBreakpoints( - functions, condition=condition, hitCondition=hitCondition) + functions, condition=condition, hitCondition=hitCondition + ) if response is None: return [] - breakpoints = response['body']['breakpoints'] + breakpoints = response["body"]["breakpoints"] breakpoint_ids = [] for breakpoint in breakpoints: - breakpoint_ids.append('%i' % (breakpoint['id'])) + breakpoint_ids.append("%i" % (breakpoint["id"])) return breakpoint_ids def waitUntil(self, condition_callback): @@ -63,20 +64,20 @@ return False def verify_breakpoint_hit(self, breakpoint_ids): - '''Wait for the process we are debugging to stop, and verify we hit - any breakpoint location in the "breakpoint_ids" array. - "breakpoint_ids" should be a list of breakpoint ID strings - (["1", "2"]). The return value from self.set_source_breakpoints() - or self.set_function_breakpoints() can be passed to this function''' + """Wait for the process we are debugging to stop, and verify we hit + any breakpoint location in the "breakpoint_ids" array. + "breakpoint_ids" should be a list of breakpoint ID strings + (["1", "2"]). The return value from self.set_source_breakpoints() + or self.set_function_breakpoints() can be passed to this function""" stopped_events = self.vscode.wait_for_stopped() for stopped_event in stopped_events: - if 'body' in stopped_event: - body = stopped_event['body'] - if 'reason' not in body: + if "body" in stopped_event: + body = stopped_event["body"] + if "reason" not in body: continue - if body['reason'] != 'breakpoint': + if body["reason"] != "breakpoint": continue - if 'description' not in body: + if "description" not in body: continue # Descriptions for breakpoints will be in the form # "breakpoint 1.1", so look for any description that matches @@ -86,29 +87,29 @@ # So when looking at the description we just want to make sure # the right breakpoint matches and not worry about the actual # location. - description = body['description'] + description = body["description"] for breakpoint_id in breakpoint_ids: - match_desc = 'breakpoint %s.' % (breakpoint_id) + match_desc = "breakpoint %s." % (breakpoint_id) if match_desc in description: return self.assertTrue(False, "breakpoint not hit") def verify_stop_exception_info(self, expected_description): - '''Wait for the process we are debugging to stop, and verify the stop - reason is 'exception' and that the description matches - 'expected_description' - ''' + """Wait for the process we are debugging to stop, and verify the stop + reason is 'exception' and that the description matches + 'expected_description' + """ stopped_events = self.vscode.wait_for_stopped() for stopped_event in stopped_events: - if 'body' in stopped_event: - body = stopped_event['body'] - if 'reason' not in body: + if "body" in stopped_event: + body = stopped_event["body"] + if "reason" not in body: continue - if body['reason'] != 'exception': + if body["reason"] != "exception": continue - if 'description' not in body: + if "description" not in body: continue - description = body['description'] + description = body["description"] if expected_description == description: return True return False @@ -116,96 +117,96 @@ def verify_commands(self, flavor, output, commands): self.assertTrue(output and len(output) > 0, "expect console output") lines = output.splitlines() - prefix = '(lldb) ' + prefix = "(lldb) " for cmd in commands: found = False for line in lines: if line.startswith(prefix) and cmd in line: found = True break - self.assertTrue(found, - "verify '%s' found in console output for '%s'" % ( - cmd, flavor)) + self.assertTrue( + found, "verify '%s' found in console output for '%s'" % (cmd, flavor) + ) def get_dict_value(self, d, key_path): - '''Verify each key in the key_path array is in contained in each - dictionary within "d". Assert if any key isn't in the - corresponding dictionary. This is handy for grabbing values from VS - Code response dictionary like getting - response['body']['stackFrames'] - ''' + """Verify each key in the key_path array is in contained in each + dictionary within "d". Assert if any key isn't in the + corresponding dictionary. This is handy for grabbing values from VS + Code response dictionary like getting + response['body']['stackFrames'] + """ value = d for key in key_path: if key in value: value = value[key] else: - self.assertTrue(key in value, - 'key "%s" from key_path "%s" not in "%s"' % ( - key, key_path, d)) + self.assertTrue( + key in value, + 'key "%s" from key_path "%s" not in "%s"' % (key, key_path, d), + ) return value - def get_stackFrames_and_totalFramesCount(self, threadId=None, startFrame=None, - levels=None, dump=False): - response = self.vscode.request_stackTrace(threadId=threadId, - startFrame=startFrame, - levels=levels, - dump=dump) + def get_stackFrames_and_totalFramesCount( + self, threadId=None, startFrame=None, levels=None, dump=False + ): + response = self.vscode.request_stackTrace( + threadId=threadId, startFrame=startFrame, levels=levels, dump=dump + ) if response: - stackFrames = self.get_dict_value(response, ['body', 'stackFrames']) - totalFrames = self.get_dict_value(response, ['body', 'totalFrames']) - self.assertTrue(totalFrames > 0, - 'verify totalFrames count is provided by extension that supports ' - 'async frames loading') + stackFrames = self.get_dict_value(response, ["body", "stackFrames"]) + totalFrames = self.get_dict_value(response, ["body", "totalFrames"]) + self.assertTrue( + totalFrames > 0, + "verify totalFrames count is provided by extension that supports " + "async frames loading", + ) return (stackFrames, totalFrames) return (None, 0) - def get_stackFrames(self, threadId=None, startFrame=None, levels=None, - dump=False): + def get_stackFrames(self, threadId=None, startFrame=None, levels=None, dump=False): (stackFrames, totalFrames) = self.get_stackFrames_and_totalFramesCount( - threadId=threadId, - startFrame=startFrame, - levels=levels, - dump=dump) + threadId=threadId, startFrame=startFrame, levels=levels, dump=dump + ) return stackFrames def get_source_and_line(self, threadId=None, frameIndex=0): - stackFrames = self.get_stackFrames(threadId=threadId, - startFrame=frameIndex, - levels=1) + stackFrames = self.get_stackFrames( + threadId=threadId, startFrame=frameIndex, levels=1 + ) if stackFrames is not None: stackFrame = stackFrames[0] - ['source', 'path'] - if 'source' in stackFrame: - source = stackFrame['source'] - if 'path' in source: - if 'line' in stackFrame: - return (source['path'], stackFrame['line']) - return ('', 0) + ["source", "path"] + if "source" in stackFrame: + source = stackFrame["source"] + if "path" in source: + if "line" in stackFrame: + return (source["path"], stackFrame["line"]) + return ("", 0) def get_stdout(self, timeout=0.0): - return self.vscode.get_output('stdout', timeout=timeout) + return self.vscode.get_output("stdout", timeout=timeout) def get_console(self, timeout=0.0): - return self.vscode.get_output('console', timeout=timeout) + return self.vscode.get_output("console", timeout=timeout) def collect_console(self, duration): - return self.vscode.collect_output('console', duration=duration) + return self.vscode.collect_output("console", duration=duration) def get_local_as_int(self, name, threadId=None): value = self.vscode.get_local_variable_value(name, threadId=threadId) - if value.startswith('0x'): + if value.startswith("0x"): return int(value, 16) - elif value.startswith('0'): + elif value.startswith("0"): return int(value, 8) else: return int(value) def set_local(self, name, value, id=None): - '''Set a top level local variable only.''' + """Set a top level local variable only.""" return self.vscode.request_setVariable(1, name, str(value), id=id) def set_global(self, name, value, id=None): - '''Set a top level global variable only.''' + """Set a top level global variable only.""" return self.vscode.request_setVariable(2, name, str(value), id=id) def stepIn(self, threadId=None, waitForStop=True): @@ -236,27 +237,48 @@ def continue_to_exception_breakpoint(self, filter_label): self.vscode.request_continue() - self.assertTrue(self.verify_stop_exception_info(filter_label), - 'verify we got "%s"' % (filter_label)) + self.assertTrue( + self.verify_stop_exception_info(filter_label), + 'verify we got "%s"' % (filter_label), + ) def continue_to_exit(self, exitCode=0): self.vscode.request_continue() stopped_events = self.vscode.wait_for_stopped() - self.assertEquals(len(stopped_events), 1, - "stopped_events = {}".format(stopped_events)) - self.assertEquals(stopped_events[0]['event'], 'exited', - 'make sure program ran to completion') - self.assertEquals(stopped_events[0]['body']['exitCode'], exitCode, - 'exitCode == %i' % (exitCode)) - - def attach(self, program=None, pid=None, waitFor=None, trace=None, - initCommands=None, preRunCommands=None, stopCommands=None, - exitCommands=None, attachCommands=None, coreFile=None, - disconnectAutomatically=True, terminateCommands=None, - postRunCommands=None, sourceMap=None, sourceInitFile=False): - '''Build the default Makefile target, create the VSCode debug adaptor, - and attach to the process. - ''' + self.assertEquals( + len(stopped_events), 1, "stopped_events = {}".format(stopped_events) + ) + self.assertEquals( + stopped_events[0]["event"], "exited", "make sure program ran to completion" + ) + self.assertEquals( + stopped_events[0]["body"]["exitCode"], + exitCode, + "exitCode == %i" % (exitCode), + ) + + def attach( + self, + program=None, + pid=None, + waitFor=None, + trace=None, + initCommands=None, + preRunCommands=None, + stopCommands=None, + exitCommands=None, + attachCommands=None, + coreFile=None, + disconnectAutomatically=True, + terminateCommands=None, + postRunCommands=None, + sourceMap=None, + sourceInitFile=False, + ): + """Build the default Makefile target, create the VSCode debug adaptor, + and attach to the process. + """ + # Make sure we disconnect and terminate the VSCode debug adaptor even # if we throw an exception during the test case. def cleanup(): @@ -269,26 +291,52 @@ # Initialize and launch the program self.vscode.request_initialize(sourceInitFile) response = self.vscode.request_attach( - program=program, pid=pid, waitFor=waitFor, trace=trace, - initCommands=initCommands, preRunCommands=preRunCommands, - stopCommands=stopCommands, exitCommands=exitCommands, - attachCommands=attachCommands, terminateCommands=terminateCommands, - coreFile=coreFile, postRunCommands=postRunCommands, - sourceMap=sourceMap) - if not (response and response['success']): - self.assertTrue(response['success'], - 'attach failed (%s)' % (response['message'])) - - def launch(self, program=None, args=None, cwd=None, env=None, - stopOnEntry=False, disableASLR=True, - disableSTDIO=False, shellExpandArguments=False, - trace=False, initCommands=None, preRunCommands=None, - stopCommands=None, exitCommands=None, terminateCommands=None, - sourcePath=None, debuggerRoot=None, sourceInitFile=False, launchCommands=None, - sourceMap=None, disconnectAutomatically=True, runInTerminal=False, - expectFailure=False, postRunCommands=None): - '''Sending launch request to vscode - ''' + program=program, + pid=pid, + waitFor=waitFor, + trace=trace, + initCommands=initCommands, + preRunCommands=preRunCommands, + stopCommands=stopCommands, + exitCommands=exitCommands, + attachCommands=attachCommands, + terminateCommands=terminateCommands, + coreFile=coreFile, + postRunCommands=postRunCommands, + sourceMap=sourceMap, + ) + if not (response and response["success"]): + self.assertTrue( + response["success"], "attach failed (%s)" % (response["message"]) + ) + + def launch( + self, + program=None, + args=None, + cwd=None, + env=None, + stopOnEntry=False, + disableASLR=True, + disableSTDIO=False, + shellExpandArguments=False, + trace=False, + initCommands=None, + preRunCommands=None, + stopCommands=None, + exitCommands=None, + terminateCommands=None, + sourcePath=None, + debuggerRoot=None, + sourceInitFile=False, + launchCommands=None, + sourceMap=None, + disconnectAutomatically=True, + runInTerminal=False, + expectFailure=False, + postRunCommands=None, + ): + """Sending launch request to vscode""" # Make sure we disconnect and terminate the VSCode debug adapter, # if we throw an exception during the test case @@ -322,36 +370,67 @@ launchCommands=launchCommands, sourceMap=sourceMap, runInTerminal=runInTerminal, - postRunCommands=postRunCommands) + postRunCommands=postRunCommands, + ) if expectFailure: return response - if not (response and response['success']): - self.assertTrue(response['success'], - 'launch failed (%s)' % (response['message'])) + if not (response and response["success"]): + self.assertTrue( + response["success"], "launch failed (%s)" % (response["message"]) + ) return response - - def build_and_launch(self, program, args=None, cwd=None, env=None, - stopOnEntry=False, disableASLR=True, - disableSTDIO=False, shellExpandArguments=False, - trace=False, initCommands=None, preRunCommands=None, - stopCommands=None, exitCommands=None, - terminateCommands=None, sourcePath=None, - debuggerRoot=None, sourceInitFile=False, runInTerminal=False, - disconnectAutomatically=True, postRunCommands=None, - lldbVSCodeEnv=None): - '''Build the default Makefile target, create the VSCode debug adaptor, - and launch the process. - ''' + def build_and_launch( + self, + program, + args=None, + cwd=None, + env=None, + stopOnEntry=False, + disableASLR=True, + disableSTDIO=False, + shellExpandArguments=False, + trace=False, + initCommands=None, + preRunCommands=None, + stopCommands=None, + exitCommands=None, + terminateCommands=None, + sourcePath=None, + debuggerRoot=None, + sourceInitFile=False, + runInTerminal=False, + disconnectAutomatically=True, + postRunCommands=None, + lldbVSCodeEnv=None, + ): + """Build the default Makefile target, create the VSCode debug adaptor, + and launch the process. + """ self.build_and_create_debug_adaptor(lldbVSCodeEnv) - self.assertTrue(os.path.exists(program), 'executable must exist') - - return self.launch(program, args, cwd, env, stopOnEntry, disableASLR, - disableSTDIO, shellExpandArguments, trace, - initCommands, preRunCommands, stopCommands, exitCommands, - terminateCommands, sourcePath, debuggerRoot, sourceInitFile, - runInTerminal=runInTerminal, - disconnectAutomatically=disconnectAutomatically, - postRunCommands=postRunCommands) + self.assertTrue(os.path.exists(program), "executable must exist") + + return self.launch( + program, + args, + cwd, + env, + stopOnEntry, + disableASLR, + disableSTDIO, + shellExpandArguments, + trace, + initCommands, + preRunCommands, + stopCommands, + exitCommands, + terminateCommands, + sourcePath, + debuggerRoot, + sourceInitFile, + runInTerminal=runInTerminal, + disconnectAutomatically=disconnectAutomatically, + postRunCommands=postRunCommands, + ) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py @@ -14,14 +14,13 @@ def dump_memory(base_addr, data, num_per_line, outfile): - data_len = len(data) hex_string = binascii.hexlify(data) addr = base_addr - ascii_str = '' + ascii_str = "" i = 0 while i < data_len: - outfile.write('0x%8.8x: ' % (addr + i)) + outfile.write("0x%8.8x: " % (addr + i)) bytes_left = data_len - i if bytes_left >= num_per_line: curr_data_len = num_per_line @@ -34,38 +33,38 @@ # current line with no spaces between bytes t = iter(curr_hex_str) # Print hex bytes separated by space - outfile.write(' '.join(a + b for a, b in zip(t, t))) + outfile.write(" ".join(a + b for a, b in zip(t, t))) # Print two spaces - outfile.write(' ') + outfile.write(" ") # Calculate ASCII string for bytes into 'ascii_str' - ascii_str = '' + ascii_str = "" for j in range(i, i + curr_data_len): ch = data[j] if ch in string.printable and ch not in string.whitespace: - ascii_str += '%c' % (ch) + ascii_str += "%c" % (ch) else: - ascii_str += '.' + ascii_str += "." # Print ASCII representation and newline outfile.write(ascii_str) i = i + curr_data_len - outfile.write('\n') + outfile.write("\n") def read_packet(f, verbose=False, trace_file=None): - '''Decode a JSON packet that starts with the content length and is - followed by the JSON bytes from a file 'f'. Returns None on EOF. - ''' + """Decode a JSON packet that starts with the content length and is + followed by the JSON bytes from a file 'f'. Returns None on EOF. + """ line = f.readline().decode("utf-8") if len(line) == 0: return None # EOF. # Watch for line that starts with the prefix - prefix = 'Content-Length: ' + prefix = "Content-Length: " if line.startswith(prefix): # Decode length of JSON bytes if verbose: print('content: "%s"' % (line)) - length = int(line[len(prefix):]) + length = int(line[len(prefix) :]) if verbose: print('length: "%u"' % (length)) # Skip empty line @@ -77,7 +76,7 @@ if verbose: print('json: "%s"' % (json_str)) if trace_file: - trace_file.write('from adaptor:\n%s\n' % (json_str)) + trace_file.write("from adaptor:\n%s\n" % (json_str)) # Decode the JSON bytes into a python dictionary return json.loads(json_str) @@ -85,7 +84,8 @@ def packet_type_is(packet, packet_type): - return 'type' in packet and packet['type'] == packet_type + return "type" in packet and packet["type"] == packet_type + def dump_dap_log(log_file): print("========= DEBUG ADAPTER PROTOCOL LOGS =========") @@ -111,15 +111,15 @@ class DebugCommunication(object): - def __init__(self, recv, send, init_commands, log_file=None): self.trace_file = None self.send = send self.recv = recv self.recv_packets = [] self.recv_condition = threading.Condition() - self.recv_thread = threading.Thread(target=read_packet_thread, - args=(self, log_file)) + self.recv_thread = threading.Thread( + target=read_packet_thread, args=(self, log_file) + ) self.process_event_body = None self.exit_status = None self.initialize_body = None @@ -141,16 +141,16 @@ @classmethod def validate_response(cls, command, response): - if command['command'] != response['command']: - raise ValueError('command mismatch in response') - if command['seq'] != response['request_seq']: - raise ValueError('seq mismatch in response') + if command["command"] != response["command"]: + raise ValueError("command mismatch in response") + if command["seq"] != response["request_seq"]: + raise ValueError("seq mismatch in response") def get_modules(self): - module_list = self.request_modules()['body']['modules'] + module_list = self.request_modules()["body"]["modules"] modules = {} for module in module_list: - modules[module['name']] = module + modules[module["name"]] = module return modules def get_output(self, category, timeout=0.0, clear=True): @@ -185,12 +185,12 @@ self.recv_condition.release() def handle_recv_packet(self, packet): - '''Called by the read thread that is waiting for all incoming packets - to store the incoming packet in "self.recv_packets" in a thread safe - way. This function will then signal the "self.recv_condition" to - indicate a new packet is available. Returns True if the caller - should keep calling this function for more packets. - ''' + """Called by the read thread that is waiting for all incoming packets + to store the incoming packet in "self.recv_packets" in a thread safe + way. This function will then signal the "self.recv_condition" to + indicate a new packet is available. Returns True if the caller + should keep calling this function for more packets. + """ # If EOF, notify the read thread by enqueuing a None. if not packet: self.enqueue_recv_packet(None) @@ -198,18 +198,18 @@ # Check the packet to see if is an event packet keepGoing = True - packet_type = packet['type'] - if packet_type == 'event': - event = packet['event'] + packet_type = packet["type"] + if packet_type == "event": + event = packet["event"] body = None - if 'body' in packet: - body = packet['body'] + if "body" in packet: + body = packet["body"] # Handle the event packet and cache information from these packets # as they come in - if event == 'output': + if event == "output": # Store any output we receive so clients can retrieve it later. - category = body['category'] - output = body['output'] + category = body["category"] + output = body["output"] self.output_condition.acquire() if category in self.output: self.output[category] += output @@ -219,26 +219,26 @@ self.output_condition.release() # no need to add 'output' event packets to our packets list return keepGoing - elif event == 'process': + elif event == "process": # When a new process is attached or launched, remember the # details that are available in the body of the event self.process_event_body = body - elif event == 'stopped': + elif event == "stopped": # Each thread that stops with a reason will send a # 'stopped' event. We need to remember the thread stop # reasons since the 'threads' command doesn't return # that information. self._process_stopped() - tid = body['threadId'] + tid = body["threadId"] self.thread_stop_reasons[tid] = body - elif event == 'breakpoint': + elif event == "breakpoint": # Breakpoint events come in when a breakpoint has locations # added or removed. Keep track of them so we can look for them # in tests. self.breakpoint_events.append(packet) # no need to add 'breakpoint' event packets to our packets list return keepGoing - elif event.startswith('progress'): + elif event.startswith("progress"): # Progress events come in as 'progressStart', 'progressUpdate', # and 'progressEnd' events. Keep these around in case test # cases want to verify them. @@ -246,24 +246,24 @@ # No need to add 'progress' event packets to our packets list. return keepGoing - elif packet_type == 'response': - if packet['command'] == 'disconnect': + elif packet_type == "response": + if packet["command"] == "disconnect": keepGoing = False self.enqueue_recv_packet(packet) return keepGoing def send_packet(self, command_dict, set_sequence=True): - '''Take the "command_dict" python dictionary and encode it as a JSON - string and send the contents as a packet to the VSCode debug - adaptor''' + """Take the "command_dict" python dictionary and encode it as a JSON + string and send the contents as a packet to the VSCode debug + adaptor""" # Set the sequence ID for this command automatically if set_sequence: - command_dict['seq'] = self.sequence + command_dict["seq"] = self.sequence self.sequence += 1 # Encode our command dictionary as a JSON string - json_str = json.dumps(command_dict, separators=(',', ':')) + json_str = json.dumps(command_dict, separators=(",", ":")) if self.trace_file: - self.trace_file.write('to adaptor:\n%s\n' % (json_str)) + self.trace_file.write("to adaptor:\n%s\n" % (json_str)) length = len(json_str) if length > 0: # Send the encoded JSON packet and flush the 'send' file @@ -271,24 +271,25 @@ self.send.flush() def recv_packet(self, filter_type=None, filter_event=None, timeout=None): - '''Get a JSON packet from the VSCode debug adaptor. This function - assumes a thread that reads packets is running and will deliver - any received packets by calling handle_recv_packet(...). This - function will wait for the packet to arrive and return it when - it does.''' + """Get a JSON packet from the VSCode debug adaptor. This function + assumes a thread that reads packets is running and will deliver + any received packets by calling handle_recv_packet(...). This + function will wait for the packet to arrive and return it when + it does.""" while True: try: self.recv_condition.acquire() packet = None while True: - for (i, curr_packet) in enumerate(self.recv_packets): + for i, curr_packet in enumerate(self.recv_packets): if not curr_packet: raise EOFError - packet_type = curr_packet['type'] + packet_type = curr_packet["type"] if filter_type is None or packet_type in filter_type: - if (filter_event is None or - (packet_type == 'event' and - curr_packet['event'] in filter_event)): + if filter_event is None or ( + packet_type == "event" + and curr_packet["event"] in filter_event + ): packet = self.recv_packets.pop(i) break if packet: @@ -308,80 +309,89 @@ return None def send_recv(self, command): - '''Send a command python dictionary as JSON and receive the JSON - response. Validates that the response is the correct sequence and - command in the reply. Any events that are received are added to the - events list in this object''' + """Send a command python dictionary as JSON and receive the JSON + response. Validates that the response is the correct sequence and + command in the reply. Any events that are received are added to the + events list in this object""" self.send_packet(command) done = False while not done: - response_or_request = self.recv_packet(filter_type=['response', 'request']) + response_or_request = self.recv_packet(filter_type=["response", "request"]) if response_or_request is None: - desc = 'no response for "%s"' % (command['command']) + desc = 'no response for "%s"' % (command["command"]) raise ValueError(desc) - if response_or_request['type'] == 'response': + if response_or_request["type"] == "response": self.validate_response(command, response_or_request) return response_or_request else: - if response_or_request['command'] == 'runInTerminal': - subprocess.Popen(response_or_request['arguments']['args'], - env=response_or_request['arguments']['env']) - self.send_packet({ - "type": "response", - "seq": -1, - "request_seq": response_or_request['seq'], - "success": True, - "command": "runInTerminal", - "body": {} - }, set_sequence=False) + if response_or_request["command"] == "runInTerminal": + subprocess.Popen( + response_or_request["arguments"]["args"], + env=response_or_request["arguments"]["env"], + ) + self.send_packet( + { + "type": "response", + "seq": -1, + "request_seq": response_or_request["seq"], + "success": True, + "command": "runInTerminal", + "body": {}, + }, + set_sequence=False, + ) else: - desc = 'unkonwn reverse request "%s"' % (response_or_request['command']) + desc = 'unkonwn reverse request "%s"' % ( + response_or_request["command"] + ) raise ValueError(desc) return None def wait_for_event(self, filter=None, timeout=None): while True: - return self.recv_packet(filter_type='event', filter_event=filter, - timeout=timeout) + return self.recv_packet( + filter_type="event", filter_event=filter, timeout=timeout + ) return None def wait_for_stopped(self, timeout=None): stopped_events = [] - stopped_event = self.wait_for_event(filter=['stopped', 'exited'], - timeout=timeout) + stopped_event = self.wait_for_event( + filter=["stopped", "exited"], timeout=timeout + ) exited = False while stopped_event: stopped_events.append(stopped_event) # If we exited, then we are done - if stopped_event['event'] == 'exited': - self.exit_status = stopped_event['body']['exitCode'] + if stopped_event["event"] == "exited": + self.exit_status = stopped_event["body"]["exitCode"] exited = True break # Otherwise we stopped and there might be one or more 'stopped' # events for each thread that stopped with a reason, so keep # checking for more 'stopped' events and return all of them - stopped_event = self.wait_for_event(filter='stopped', timeout=0.25) + stopped_event = self.wait_for_event(filter="stopped", timeout=0.25) if exited: self.threads = [] return stopped_events def wait_for_exited(self): - event_dict = self.wait_for_event('exited') + event_dict = self.wait_for_event("exited") if event_dict is None: raise ValueError("didn't get exited event") return event_dict def wait_for_terminated(self): - event_dict = self.wait_for_event('terminated') + event_dict = self.wait_for_event("terminated") if event_dict is None: raise ValueError("didn't get terminated event") return event_dict def get_initialize_value(self, key): - '''Get a value for the given key if it there is a key/value pair in - the "initialize" request response body. - ''' + """Get a value for the given key if it there is a key/value pair in + the "initialize" request response body. + """ if self.initialize_body and key in self.initialize_body: return self.initialize_body[key] return None @@ -392,172 +402,179 @@ return self.threads def get_thread_id(self, threadIndex=0): - '''Utility function to get the first thread ID in the thread list. - If the thread list is empty, then fetch the threads. - ''' + """Utility function to get the first thread ID in the thread list. + If the thread list is empty, then fetch the threads. + """ if self.threads is None: self.request_threads() if self.threads and threadIndex < len(self.threads): - return self.threads[threadIndex]['id'] + return self.threads[threadIndex]["id"] return None def get_stackFrame(self, frameIndex=0, threadId=None): - '''Get a single "StackFrame" object from a "stackTrace" request and - return the "StackFrame as a python dictionary, or None on failure - ''' + """Get a single "StackFrame" object from a "stackTrace" request and + return the "StackFrame as a python dictionary, or None on failure + """ if threadId is None: threadId = self.get_thread_id() if threadId is None: - print('invalid threadId') + print("invalid threadId") return None - response = self.request_stackTrace(threadId, startFrame=frameIndex, - levels=1) + response = self.request_stackTrace(threadId, startFrame=frameIndex, levels=1) if response: - return response['body']['stackFrames'][0] - print('invalid response') + return response["body"]["stackFrames"][0] + print("invalid response") return None def get_completions(self, text): response = self.request_completions(text) - return response['body']['targets'] + return response["body"]["targets"] def get_scope_variables(self, scope_name, frameIndex=0, threadId=None): - stackFrame = self.get_stackFrame(frameIndex=frameIndex, - threadId=threadId) + stackFrame = self.get_stackFrame(frameIndex=frameIndex, threadId=threadId) if stackFrame is None: return [] - frameId = stackFrame['id'] + frameId = stackFrame["id"] if frameId in self.frame_scopes: frame_scopes = self.frame_scopes[frameId] else: scopes_response = self.request_scopes(frameId) - frame_scopes = scopes_response['body']['scopes'] + frame_scopes = scopes_response["body"]["scopes"] self.frame_scopes[frameId] = frame_scopes for scope in frame_scopes: - if scope['name'] == scope_name: - varRef = scope['variablesReference'] + if scope["name"] == scope_name: + varRef = scope["variablesReference"] variables_response = self.request_variables(varRef) if variables_response: - if 'body' in variables_response: - body = variables_response['body'] - if 'variables' in body: - vars = body['variables'] + if "body" in variables_response: + body = variables_response["body"] + if "variables" in body: + vars = body["variables"] return vars return [] def get_global_variables(self, frameIndex=0, threadId=None): - return self.get_scope_variables('Globals', frameIndex=frameIndex, - threadId=threadId) + return self.get_scope_variables( + "Globals", frameIndex=frameIndex, threadId=threadId + ) def get_local_variables(self, frameIndex=0, threadId=None): - return self.get_scope_variables('Locals', frameIndex=frameIndex, - threadId=threadId) + return self.get_scope_variables( + "Locals", frameIndex=frameIndex, threadId=threadId + ) def get_registers(self, frameIndex=0, threadId=None): - return self.get_scope_variables('Registers', frameIndex=frameIndex, - threadId=threadId) + return self.get_scope_variables( + "Registers", frameIndex=frameIndex, threadId=threadId + ) def get_local_variable(self, name, frameIndex=0, threadId=None): - locals = self.get_local_variables(frameIndex=frameIndex, - threadId=threadId) + locals = self.get_local_variables(frameIndex=frameIndex, threadId=threadId) for local in locals: - if 'name' in local and local['name'] == name: + if "name" in local and local["name"] == name: return local return None def get_local_variable_value(self, name, frameIndex=0, threadId=None): - variable = self.get_local_variable(name, frameIndex=frameIndex, - threadId=threadId) - if variable and 'value' in variable: - return variable['value'] + variable = self.get_local_variable( + name, frameIndex=frameIndex, threadId=threadId + ) + if variable and "value" in variable: + return variable["value"] return None def replay_packets(self, replay_file_path): - f = open(replay_file_path, 'r') - mode = 'invalid' + f = open(replay_file_path, "r") + mode = "invalid" set_sequence = False command_dict = None - while mode != 'eof': - if mode == 'invalid': + while mode != "eof": + if mode == "invalid": line = f.readline() - if line.startswith('to adapter:'): - mode = 'send' - elif line.startswith('from adapter:'): - mode = 'recv' - elif mode == 'send': + if line.startswith("to adapter:"): + mode = "send" + elif line.startswith("from adapter:"): + mode = "recv" + elif mode == "send": command_dict = read_packet(f) # Skip the end of line that follows the JSON f.readline() if command_dict is None: - raise ValueError('decode packet failed from replay file') - print('Sending:') + raise ValueError("decode packet failed from replay file") + print("Sending:") pprint.PrettyPrinter(indent=2).pprint(command_dict) # raw_input('Press ENTER to send:') self.send_packet(command_dict, set_sequence) - mode = 'invalid' - elif mode == 'recv': - print('Replay response:') + mode = "invalid" + elif mode == "recv": + print("Replay response:") replay_response = read_packet(f) # Skip the end of line that follows the JSON f.readline() pprint.PrettyPrinter(indent=2).pprint(replay_response) actual_response = self.recv_packet() if actual_response: - type = actual_response['type'] - print('Actual response:') - if type == 'response': + type = actual_response["type"] + print("Actual response:") + if type == "response": self.validate_response(command_dict, actual_response) pprint.PrettyPrinter(indent=2).pprint(actual_response) else: print("error: didn't get a valid response") - mode = 'invalid' - - def request_attach(self, program=None, pid=None, waitFor=None, trace=None, - initCommands=None, preRunCommands=None, - stopCommands=None, exitCommands=None, - attachCommands=None, terminateCommands=None, - coreFile=None, postRunCommands=None, - sourceMap=None): + mode = "invalid" + + def request_attach( + self, + program=None, + pid=None, + waitFor=None, + trace=None, + initCommands=None, + preRunCommands=None, + stopCommands=None, + exitCommands=None, + attachCommands=None, + terminateCommands=None, + coreFile=None, + postRunCommands=None, + sourceMap=None, + ): args_dict = {} if pid is not None: - args_dict['pid'] = pid + args_dict["pid"] = pid if program is not None: - args_dict['program'] = program + args_dict["program"] = program if waitFor is not None: - args_dict['waitFor'] = waitFor + args_dict["waitFor"] = waitFor if trace: - args_dict['trace'] = trace - args_dict['initCommands'] = self.init_commands + args_dict["trace"] = trace + args_dict["initCommands"] = self.init_commands if initCommands: - args_dict['initCommands'].extend(initCommands) + args_dict["initCommands"].extend(initCommands) if preRunCommands: - args_dict['preRunCommands'] = preRunCommands + args_dict["preRunCommands"] = preRunCommands if stopCommands: - args_dict['stopCommands'] = stopCommands + args_dict["stopCommands"] = stopCommands if exitCommands: - args_dict['exitCommands'] = exitCommands + args_dict["exitCommands"] = exitCommands if terminateCommands: - args_dict['terminateCommands'] = terminateCommands + args_dict["terminateCommands"] = terminateCommands if attachCommands: - args_dict['attachCommands'] = attachCommands + args_dict["attachCommands"] = attachCommands if coreFile: - args_dict['coreFile'] = coreFile + args_dict["coreFile"] = coreFile if postRunCommands: - args_dict['postRunCommands'] = postRunCommands + args_dict["postRunCommands"] = postRunCommands if sourceMap: - args_dict['sourceMap'] = sourceMap - command_dict = { - 'command': 'attach', - 'type': 'request', - 'arguments': args_dict - } + args_dict["sourceMap"] = sourceMap + command_dict = {"command": "attach", "type": "request", "arguments": args_dict} return self.send_recv(command_dict) def request_configurationDone(self): command_dict = { - 'command': 'configurationDone', - 'type': 'request', - 'arguments': {} + "command": "configurationDone", + "type": "request", + "arguments": {}, } response = self.send_recv(command_dict) if response: @@ -570,7 +587,7 @@ def request_continue(self, threadId=None): if self.exit_status is not None: - raise ValueError('request_continue called after process exited') + raise ValueError("request_continue called after process exited") # If we have launched or attached, then the first continue is done by # sending the 'configurationDone' request if not self.configuration_done_sent: @@ -578,11 +595,11 @@ args_dict = {} if threadId is None: threadId = self.get_thread_id() - args_dict['threadId'] = threadId + args_dict["threadId"] = threadId command_dict = { - 'command': 'continue', - 'type': 'request', - 'arguments': args_dict + "command": "continue", + "type": "request", + "arguments": args_dict, } response = self.send_recv(command_dict) # Caller must still call wait_for_stopped. @@ -590,11 +607,11 @@ def request_restart(self, restartArguments=None): command_dict = { - 'command': 'restart', - 'type': 'request', + "command": "restart", + "type": "request", } if restartArguments: - command_dict['arguments'] = restartArguments + command_dict["arguments"] = restartArguments response = self.send_recv(command_dict) # Caller must still call wait_for_stopped. @@ -604,323 +621,303 @@ args_dict = {} if terminateDebuggee is not None: if terminateDebuggee: - args_dict['terminateDebuggee'] = True + args_dict["terminateDebuggee"] = True else: - args_dict['terminateDebuggee'] = False + args_dict["terminateDebuggee"] = False command_dict = { - 'command': 'disconnect', - 'type': 'request', - 'arguments': args_dict + "command": "disconnect", + "type": "request", + "arguments": args_dict, } return self.send_recv(command_dict) def request_evaluate(self, expression, frameIndex=0, threadId=None, context=None): - stackFrame = self.get_stackFrame(frameIndex=frameIndex, - threadId=threadId) + stackFrame = self.get_stackFrame(frameIndex=frameIndex, threadId=threadId) if stackFrame is None: return [] args_dict = { - 'expression': expression, - 'context': context, - 'frameId': stackFrame['id'], + "expression": expression, + "context": context, + "frameId": stackFrame["id"], } command_dict = { - 'command': 'evaluate', - 'type': 'request', - 'arguments': args_dict + "command": "evaluate", + "type": "request", + "arguments": args_dict, } return self.send_recv(command_dict) def request_initialize(self, sourceInitFile): command_dict = { - 'command': 'initialize', - 'type': 'request', - 'arguments': { - 'adapterID': 'lldb-native', - 'clientID': 'vscode', - 'columnsStartAt1': True, - 'linesStartAt1': True, - 'locale': 'en-us', - 'pathFormat': 'path', - 'supportsRunInTerminalRequest': True, - 'supportsVariablePaging': True, - 'supportsVariableType': True, - 'sourceInitFile': sourceInitFile - } + "command": "initialize", + "type": "request", + "arguments": { + "adapterID": "lldb-native", + "clientID": "vscode", + "columnsStartAt1": True, + "linesStartAt1": True, + "locale": "en-us", + "pathFormat": "path", + "supportsRunInTerminalRequest": True, + "supportsVariablePaging": True, + "supportsVariableType": True, + "sourceInitFile": sourceInitFile, + }, } response = self.send_recv(command_dict) if response: - if 'body' in response: - self.initialize_body = response['body'] + if "body" in response: + self.initialize_body = response["body"] return response - def request_launch(self, program, args=None, cwd=None, env=None, - stopOnEntry=False, disableASLR=True, - disableSTDIO=False, shellExpandArguments=False, - trace=False, initCommands=None, preRunCommands=None, - stopCommands=None, exitCommands=None, - terminateCommands=None ,sourcePath=None, - debuggerRoot=None, launchCommands=None, sourceMap=None, - runInTerminal=False, postRunCommands=None): - args_dict = { - 'program': program - } + def request_launch( + self, + program, + args=None, + cwd=None, + env=None, + stopOnEntry=False, + disableASLR=True, + disableSTDIO=False, + shellExpandArguments=False, + trace=False, + initCommands=None, + preRunCommands=None, + stopCommands=None, + exitCommands=None, + terminateCommands=None, + sourcePath=None, + debuggerRoot=None, + launchCommands=None, + sourceMap=None, + runInTerminal=False, + postRunCommands=None, + ): + args_dict = {"program": program} if args: - args_dict['args'] = args + args_dict["args"] = args if cwd: - args_dict['cwd'] = cwd + args_dict["cwd"] = cwd if env: - args_dict['env'] = env + args_dict["env"] = env if stopOnEntry: - args_dict['stopOnEntry'] = stopOnEntry + args_dict["stopOnEntry"] = stopOnEntry if disableASLR: - args_dict['disableASLR'] = disableASLR + args_dict["disableASLR"] = disableASLR if disableSTDIO: - args_dict['disableSTDIO'] = disableSTDIO + args_dict["disableSTDIO"] = disableSTDIO if shellExpandArguments: - args_dict['shellExpandArguments'] = shellExpandArguments + args_dict["shellExpandArguments"] = shellExpandArguments if trace: - args_dict['trace'] = trace - args_dict['initCommands'] = self.init_commands + args_dict["trace"] = trace + args_dict["initCommands"] = self.init_commands if initCommands: - args_dict['initCommands'].extend(initCommands) + args_dict["initCommands"].extend(initCommands) if preRunCommands: - args_dict['preRunCommands'] = preRunCommands + args_dict["preRunCommands"] = preRunCommands if stopCommands: - args_dict['stopCommands'] = stopCommands + args_dict["stopCommands"] = stopCommands if exitCommands: - args_dict['exitCommands'] = exitCommands + args_dict["exitCommands"] = exitCommands if terminateCommands: - args_dict['terminateCommands'] = terminateCommands + args_dict["terminateCommands"] = terminateCommands if sourcePath: - args_dict['sourcePath'] = sourcePath + args_dict["sourcePath"] = sourcePath if debuggerRoot: - args_dict['debuggerRoot'] = debuggerRoot + args_dict["debuggerRoot"] = debuggerRoot if launchCommands: - args_dict['launchCommands'] = launchCommands + args_dict["launchCommands"] = launchCommands if sourceMap: - args_dict['sourceMap'] = sourceMap + args_dict["sourceMap"] = sourceMap if runInTerminal: - args_dict['runInTerminal'] = runInTerminal + args_dict["runInTerminal"] = runInTerminal if postRunCommands: - args_dict['postRunCommands'] = postRunCommands - command_dict = { - 'command': 'launch', - 'type': 'request', - 'arguments': args_dict - } + args_dict["postRunCommands"] = postRunCommands + command_dict = {"command": "launch", "type": "request", "arguments": args_dict} response = self.send_recv(command_dict) - if response['success']: + if response["success"]: # Wait for a 'process' and 'initialized' event in any order - self.wait_for_event(filter=['process', 'initialized']) - self.wait_for_event(filter=['process', 'initialized']) + self.wait_for_event(filter=["process", "initialized"]) + self.wait_for_event(filter=["process", "initialized"]) return response def request_next(self, threadId): if self.exit_status is not None: - raise ValueError('request_continue called after process exited') - args_dict = {'threadId': threadId} - command_dict = { - 'command': 'next', - 'type': 'request', - 'arguments': args_dict - } + raise ValueError("request_continue called after process exited") + args_dict = {"threadId": threadId} + command_dict = {"command": "next", "type": "request", "arguments": args_dict} return self.send_recv(command_dict) def request_stepIn(self, threadId): if self.exit_status is not None: - raise ValueError('request_continue called after process exited') - args_dict = {'threadId': threadId} - command_dict = { - 'command': 'stepIn', - 'type': 'request', - 'arguments': args_dict - } + raise ValueError("request_continue called after process exited") + args_dict = {"threadId": threadId} + command_dict = {"command": "stepIn", "type": "request", "arguments": args_dict} return self.send_recv(command_dict) def request_stepOut(self, threadId): if self.exit_status is not None: - raise ValueError('request_continue called after process exited') - args_dict = {'threadId': threadId} - command_dict = { - 'command': 'stepOut', - 'type': 'request', - 'arguments': args_dict - } + raise ValueError("request_continue called after process exited") + args_dict = {"threadId": threadId} + command_dict = {"command": "stepOut", "type": "request", "arguments": args_dict} return self.send_recv(command_dict) def request_pause(self, threadId=None): if self.exit_status is not None: - raise ValueError('request_continue called after process exited') + raise ValueError("request_continue called after process exited") if threadId is None: threadId = self.get_thread_id() - args_dict = {'threadId': threadId} - command_dict = { - 'command': 'pause', - 'type': 'request', - 'arguments': args_dict - } + args_dict = {"threadId": threadId} + command_dict = {"command": "pause", "type": "request", "arguments": args_dict} return self.send_recv(command_dict) def request_scopes(self, frameId): - args_dict = {'frameId': frameId} - command_dict = { - 'command': 'scopes', - 'type': 'request', - 'arguments': args_dict - } + args_dict = {"frameId": frameId} + command_dict = {"command": "scopes", "type": "request", "arguments": args_dict} return self.send_recv(command_dict) def request_setBreakpoints(self, file_path, line_array, data=None): - ''' data is array of parameters for breakpoints in line_array. - Each parameter object is 1:1 mapping with entries in line_entry. - It contains optional location/hitCondition/logMessage parameters. - ''' + """data is array of parameters for breakpoints in line_array. + Each parameter object is 1:1 mapping with entries in line_entry. + It contains optional location/hitCondition/logMessage parameters. + """ (dir, base) = os.path.split(file_path) - source_dict = { - 'name': base, - 'path': file_path - } + source_dict = {"name": base, "path": file_path} args_dict = { - 'source': source_dict, - 'sourceModified': False, + "source": source_dict, + "sourceModified": False, } if line_array is not None: - args_dict['lines'] = '%s' % line_array + args_dict["lines"] = "%s" % line_array breakpoints = [] for i, line in enumerate(line_array): breakpoint_data = None if data is not None and i < len(data): breakpoint_data = data[i] - bp = {'line': line} + bp = {"line": line} if breakpoint_data is not None: - if 'condition' in breakpoint_data and breakpoint_data['condition']: - bp['condition'] = breakpoint_data['condition'] - if 'hitCondition' in breakpoint_data and breakpoint_data['hitCondition']: - bp['hitCondition'] = breakpoint_data['hitCondition'] - if 'logMessage' in breakpoint_data and breakpoint_data['logMessage']: - bp['logMessage'] = breakpoint_data['logMessage'] + if "condition" in breakpoint_data and breakpoint_data["condition"]: + bp["condition"] = breakpoint_data["condition"] + if ( + "hitCondition" in breakpoint_data + and breakpoint_data["hitCondition"] + ): + bp["hitCondition"] = breakpoint_data["hitCondition"] + if ( + "logMessage" in breakpoint_data + and breakpoint_data["logMessage"] + ): + bp["logMessage"] = breakpoint_data["logMessage"] breakpoints.append(bp) - args_dict['breakpoints'] = breakpoints + args_dict["breakpoints"] = breakpoints command_dict = { - 'command': 'setBreakpoints', - 'type': 'request', - 'arguments': args_dict + "command": "setBreakpoints", + "type": "request", + "arguments": args_dict, } return self.send_recv(command_dict) def request_setExceptionBreakpoints(self, filters): - args_dict = {'filters': filters} + args_dict = {"filters": filters} command_dict = { - 'command': 'setExceptionBreakpoints', - 'type': 'request', - 'arguments': args_dict + "command": "setExceptionBreakpoints", + "type": "request", + "arguments": args_dict, } return self.send_recv(command_dict) - def request_setFunctionBreakpoints(self, names, condition=None, - hitCondition=None): + def request_setFunctionBreakpoints(self, names, condition=None, hitCondition=None): breakpoints = [] for name in names: - bp = {'name': name} + bp = {"name": name} if condition is not None: - bp['condition'] = condition + bp["condition"] = condition if hitCondition is not None: - bp['hitCondition'] = hitCondition + bp["hitCondition"] = hitCondition breakpoints.append(bp) - args_dict = {'breakpoints': breakpoints} + args_dict = {"breakpoints": breakpoints} command_dict = { - 'command': 'setFunctionBreakpoints', - 'type': 'request', - 'arguments': args_dict + "command": "setFunctionBreakpoints", + "type": "request", + "arguments": args_dict, } return self.send_recv(command_dict) def request_compileUnits(self, moduleId): - args_dict = {'moduleId': moduleId} + args_dict = {"moduleId": moduleId} command_dict = { - 'command': 'compileUnits', - 'type': 'request', - 'arguments': args_dict + "command": "compileUnits", + "type": "request", + "arguments": args_dict, } response = self.send_recv(command_dict) return response def request_completions(self, text): - args_dict = { - 'text': text, - 'column': len(text) - } + args_dict = {"text": text, "column": len(text)} command_dict = { - 'command': 'completions', - 'type': 'request', - 'arguments': args_dict + "command": "completions", + "type": "request", + "arguments": args_dict, } return self.send_recv(command_dict) def request_modules(self): - return self.send_recv({ - 'command': 'modules', - 'type': 'request' - }) + return self.send_recv({"command": "modules", "type": "request"}) - def request_stackTrace(self, threadId=None, startFrame=None, levels=None, - dump=False): + def request_stackTrace( + self, threadId=None, startFrame=None, levels=None, dump=False + ): if threadId is None: threadId = self.get_thread_id() - args_dict = {'threadId': threadId} + args_dict = {"threadId": threadId} if startFrame is not None: - args_dict['startFrame'] = startFrame + args_dict["startFrame"] = startFrame if levels is not None: - args_dict['levels'] = levels + args_dict["levels"] = levels command_dict = { - 'command': 'stackTrace', - 'type': 'request', - 'arguments': args_dict + "command": "stackTrace", + "type": "request", + "arguments": args_dict, } response = self.send_recv(command_dict) if dump: - for (idx, frame) in enumerate(response['body']['stackFrames']): - name = frame['name'] - if 'line' in frame and 'source' in frame: - source = frame['source'] - if 'sourceReference' not in source: - if 'name' in source: - source_name = source['name'] - line = frame['line'] - print("[%3u] %s @ %s:%u" % (idx, name, source_name, - line)) + for idx, frame in enumerate(response["body"]["stackFrames"]): + name = frame["name"] + if "line" in frame and "source" in frame: + source = frame["source"] + if "sourceReference" not in source: + if "name" in source: + source_name = source["name"] + line = frame["line"] + print("[%3u] %s @ %s:%u" % (idx, name, source_name, line)) continue print("[%3u] %s" % (idx, name)) return response def request_threads(self): - '''Request a list of all threads and combine any information from any - "stopped" events since those contain more information about why a - thread actually stopped. Returns an array of thread dictionaries - with information about all threads''' - command_dict = { - 'command': 'threads', - 'type': 'request', - 'arguments': {} - } + """Request a list of all threads and combine any information from any + "stopped" events since those contain more information about why a + thread actually stopped. Returns an array of thread dictionaries + with information about all threads""" + command_dict = {"command": "threads", "type": "request", "arguments": {}} response = self.send_recv(command_dict) - body = response['body'] + body = response["body"] # Fill in "self.threads" correctly so that clients that call # self.get_threads() or self.get_thread_id(...) can get information # on threads when the process is stopped. - if 'threads' in body: - self.threads = body['threads'] + if "threads" in body: + self.threads = body["threads"] for thread in self.threads: # Copy the thread dictionary so we can add key/value pairs to # it without affecting the original info from the "threads" # command. - tid = thread['id'] + tid = thread["id"] if tid in self.thread_stop_reasons: thread_stop_info = self.thread_stop_reasons[tid] - copy_keys = ['reason', 'description', 'text'] + copy_keys = ["reason", "description", "text"] for key in copy_keys: if key in thread_stop_info: thread[key] = thread_stop_info[key] @@ -929,42 +926,42 @@ return response def request_variables(self, variablesReference, start=None, count=None): - args_dict = {'variablesReference': variablesReference} + args_dict = {"variablesReference": variablesReference} if start is not None: - args_dict['start'] = start + args_dict["start"] = start if count is not None: - args_dict['count'] = count + args_dict["count"] = count command_dict = { - 'command': 'variables', - 'type': 'request', - 'arguments': args_dict + "command": "variables", + "type": "request", + "arguments": args_dict, } return self.send_recv(command_dict) def request_setVariable(self, containingVarRef, name, value, id=None): args_dict = { - 'variablesReference': containingVarRef, - 'name': name, - 'value': str(value) + "variablesReference": containingVarRef, + "name": name, + "value": str(value), } if id is not None: - args_dict['id'] = id + args_dict["id"] = id command_dict = { - 'command': 'setVariable', - 'type': 'request', - 'arguments': args_dict + "command": "setVariable", + "type": "request", + "arguments": args_dict, } return self.send_recv(command_dict) def request_testGetTargetBreakpoints(self): - '''A request packet used in the LLDB test suite to get all currently - set breakpoint infos for all breakpoints currently set in the - target. - ''' + """A request packet used in the LLDB test suite to get all currently + set breakpoint infos for all breakpoints currently set in the + target. + """ command_dict = { - 'command': '_testGetTargetBreakpoints', - 'type': 'request', - 'arguments': {} + "command": "_testGetTargetBreakpoints", + "type": "request", + "arguments": {}, } return self.send_recv(command_dict) @@ -974,7 +971,9 @@ class DebugAdaptor(DebugCommunication): - def __init__(self, executable=None, port=None, init_commands=[], log_file=None, env=None): + def __init__( + self, executable=None, port=None, init_commands=[], log_file=None, env=None + ): self.process = None if executable is not None: adaptor_env = os.environ.copy() @@ -982,19 +981,23 @@ adaptor_env.update(env) if log_file: - adaptor_env['LLDBVSCODE_LOG'] = log_file - self.process = subprocess.Popen([executable], - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - env=adaptor_env) - DebugCommunication.__init__(self, self.process.stdout, - self.process.stdin, init_commands, log_file) + adaptor_env["LLDBVSCODE_LOG"] = log_file + self.process = subprocess.Popen( + [executable], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=adaptor_env, + ) + DebugCommunication.__init__( + self, self.process.stdout, self.process.stdin, init_commands, log_file + ) elif port is not None: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.connect(('127.0.0.1', port)) - DebugCommunication.__init__(self, s.makefile('r'), s.makefile('w'), - init_commands) + s.connect(("127.0.0.1", port)) + DebugCommunication.__init__( + self, s.makefile("r"), s.makefile("w"), init_commands + ) def get_pid(self): if self.process: @@ -1024,36 +1027,39 @@ def run_vscode(dbg, args, options): dbg.request_initialize(options.sourceInitFile) if attach_options_specified(options): - response = dbg.request_attach(program=options.program, - pid=options.pid, - waitFor=options.waitFor, - attachCommands=options.attachCmds, - initCommands=options.initCmds, - preRunCommands=options.preRunCmds, - stopCommands=options.stopCmds, - exitCommands=options.exitCmds, - terminateCommands=options.terminateCmds) + response = dbg.request_attach( + program=options.program, + pid=options.pid, + waitFor=options.waitFor, + attachCommands=options.attachCmds, + initCommands=options.initCmds, + preRunCommands=options.preRunCmds, + stopCommands=options.stopCmds, + exitCommands=options.exitCmds, + terminateCommands=options.terminateCmds, + ) else: - response = dbg.request_launch(options.program, - args=args, - env=options.envs, - cwd=options.workingDir, - debuggerRoot=options.debuggerRoot, - sourcePath=options.sourcePath, - initCommands=options.initCmds, - preRunCommands=options.preRunCmds, - stopCommands=options.stopCmds, - exitCommands=options.exitCmds, - terminateCommands=options.terminateCmds) - - if response['success']: + response = dbg.request_launch( + options.program, + args=args, + env=options.envs, + cwd=options.workingDir, + debuggerRoot=options.debuggerRoot, + sourcePath=options.sourcePath, + initCommands=options.initCmds, + preRunCommands=options.preRunCmds, + stopCommands=options.stopCmds, + exitCommands=options.exitCmds, + terminateCommands=options.terminateCmds, + ) + + if response["success"]: if options.sourceBreakpoints: source_to_lines = {} for file_line in options.sourceBreakpoints: - (path, line) = file_line.split(':') + (path, line) = file_line.split(":") if len(path) == 0 or len(line) == 0: - print('error: invalid source with line "%s"' % - (file_line)) + print('error: invalid source with line "%s"' % (file_line)) else: if path in source_to_lines: @@ -1067,202 +1073,257 @@ dbg.request_configurationDone() dbg.wait_for_stopped() else: - if 'message' in response: - print(response['message']) + if "message" in response: + print(response["message"]) dbg.request_disconnect(terminateDebuggee=True) def main(): parser = optparse.OptionParser( - description=('A testing framework for the Visual Studio Code Debug ' - 'Adaptor protocol')) + description=( + "A testing framework for the Visual Studio Code Debug " "Adaptor protocol" + ) + ) parser.add_option( - '--vscode', - type='string', - dest='vscode_path', - help=('The path to the command line program that implements the ' - 'Visual Studio Code Debug Adaptor protocol.'), - default=None) + "--vscode", + type="string", + dest="vscode_path", + help=( + "The path to the command line program that implements the " + "Visual Studio Code Debug Adaptor protocol." + ), + default=None, + ) parser.add_option( - '--program', - type='string', - dest='program', - help='The path to the program to debug.', - default=None) + "--program", + type="string", + dest="program", + help="The path to the program to debug.", + default=None, + ) parser.add_option( - '--workingDir', - type='string', - dest='workingDir', + "--workingDir", + type="string", + dest="workingDir", default=None, - help='Set the working directory for the process we launch.') + help="Set the working directory for the process we launch.", + ) parser.add_option( - '--sourcePath', - type='string', - dest='sourcePath', + "--sourcePath", + type="string", + dest="sourcePath", default=None, - help=('Set the relative source root for any debug info that has ' - 'relative paths in it.')) + help=( + "Set the relative source root for any debug info that has " + "relative paths in it." + ), + ) parser.add_option( - '--debuggerRoot', - type='string', - dest='debuggerRoot', + "--debuggerRoot", + type="string", + dest="debuggerRoot", default=None, - help=('Set the working directory for lldb-vscode for any object files ' - 'with relative paths in the Mach-o debug map.')) + help=( + "Set the working directory for lldb-vscode for any object files " + "with relative paths in the Mach-o debug map." + ), + ) parser.add_option( - '-r', '--replay', - type='string', - dest='replay', - help=('Specify a file containing a packet log to replay with the ' - 'current Visual Studio Code Debug Adaptor executable.'), - default=None) + "-r", + "--replay", + type="string", + dest="replay", + help=( + "Specify a file containing a packet log to replay with the " + "current Visual Studio Code Debug Adaptor executable." + ), + default=None, + ) parser.add_option( - '-g', '--debug', - action='store_true', - dest='debug', + "-g", + "--debug", + action="store_true", + dest="debug", default=False, - help='Pause waiting for a debugger to attach to the debug adaptor') + help="Pause waiting for a debugger to attach to the debug adaptor", + ) parser.add_option( - '--sourceInitFile', - action='store_true', - dest='sourceInitFile', + "--sourceInitFile", + action="store_true", + dest="sourceInitFile", default=False, - help='Whether lldb-vscode should source .lldbinit file or not') + help="Whether lldb-vscode should source .lldbinit file or not", + ) parser.add_option( - '--port', - type='int', - dest='port', + "--port", + type="int", + dest="port", help="Attach a socket to a port instead of using STDIN for VSCode", - default=None) + default=None, + ) parser.add_option( - '--pid', - type='int', - dest='pid', + "--pid", + type="int", + dest="pid", help="The process ID to attach to", - default=None) + default=None, + ) parser.add_option( - '--attach', - action='store_true', - dest='attach', + "--attach", + action="store_true", + dest="attach", default=False, - help=('Specify this option to attach to a process by name. The ' - 'process name is the basename of the executable specified with ' - 'the --program option.')) + help=( + "Specify this option to attach to a process by name. The " + "process name is the basename of the executable specified with " + "the --program option." + ), + ) parser.add_option( - '-f', '--function-bp', - type='string', - action='append', - dest='funcBreakpoints', - help=('Specify the name of a function to break at. ' - 'Can be specified more than once.'), - default=[]) + "-f", + "--function-bp", + type="string", + action="append", + dest="funcBreakpoints", + help=( + "Specify the name of a function to break at. " + "Can be specified more than once." + ), + default=[], + ) parser.add_option( - '-s', '--source-bp', - type='string', - action='append', - dest='sourceBreakpoints', + "-s", + "--source-bp", + type="string", + action="append", + dest="sourceBreakpoints", default=[], - help=('Specify source breakpoints to set in the format of ' - ':. ' - 'Can be specified more than once.')) + help=( + "Specify source breakpoints to set in the format of " + ":. " + "Can be specified more than once." + ), + ) parser.add_option( - '--attachCommand', - type='string', - action='append', - dest='attachCmds', + "--attachCommand", + type="string", + action="append", + dest="attachCmds", default=[], - help=('Specify a LLDB command that will attach to a process. ' - 'Can be specified more than once.')) + help=( + "Specify a LLDB command that will attach to a process. " + "Can be specified more than once." + ), + ) parser.add_option( - '--initCommand', - type='string', - action='append', - dest='initCmds', + "--initCommand", + type="string", + action="append", + dest="initCmds", default=[], - help=('Specify a LLDB command that will be executed before the target ' - 'is created. Can be specified more than once.')) + help=( + "Specify a LLDB command that will be executed before the target " + "is created. Can be specified more than once." + ), + ) parser.add_option( - '--preRunCommand', - type='string', - action='append', - dest='preRunCmds', + "--preRunCommand", + type="string", + action="append", + dest="preRunCmds", default=[], - help=('Specify a LLDB command that will be executed after the target ' - 'has been created. Can be specified more than once.')) + help=( + "Specify a LLDB command that will be executed after the target " + "has been created. Can be specified more than once." + ), + ) parser.add_option( - '--stopCommand', - type='string', - action='append', - dest='stopCmds', + "--stopCommand", + type="string", + action="append", + dest="stopCmds", default=[], - help=('Specify a LLDB command that will be executed each time the' - 'process stops. Can be specified more than once.')) + help=( + "Specify a LLDB command that will be executed each time the" + "process stops. Can be specified more than once." + ), + ) parser.add_option( - '--exitCommand', - type='string', - action='append', - dest='exitCmds', + "--exitCommand", + type="string", + action="append", + dest="exitCmds", default=[], - help=('Specify a LLDB command that will be executed when the process ' - 'exits. Can be specified more than once.')) + help=( + "Specify a LLDB command that will be executed when the process " + "exits. Can be specified more than once." + ), + ) parser.add_option( - '--terminateCommand', - type='string', - action='append', - dest='terminateCmds', + "--terminateCommand", + type="string", + action="append", + dest="terminateCmds", default=[], - help=('Specify a LLDB command that will be executed when the debugging ' - 'session is terminated. Can be specified more than once.')) + help=( + "Specify a LLDB command that will be executed when the debugging " + "session is terminated. Can be specified more than once." + ), + ) parser.add_option( - '--env', - type='string', - action='append', - dest='envs', + "--env", + type="string", + action="append", + dest="envs", default=[], - help=('Specify environment variables to pass to the launched ' - 'process.')) + help=("Specify environment variables to pass to the launched " "process."), + ) parser.add_option( - '--waitFor', - action='store_true', - dest='waitFor', + "--waitFor", + action="store_true", + dest="waitFor", default=False, - help=('Wait for the next process to be launched whose name matches ' - 'the basename of the program specified with the --program ' - 'option')) + help=( + "Wait for the next process to be launched whose name matches " + "the basename of the program specified with the --program " + "option" + ), + ) (options, args) = parser.parse_args(sys.argv[1:]) if options.vscode_path is None and options.port is None: - print('error: must either specify a path to a Visual Studio Code ' - 'Debug Adaptor vscode executable path using the --vscode ' - 'option, or a port to attach to for an existing lldb-vscode ' - 'using the --port option') + print( + "error: must either specify a path to a Visual Studio Code " + "Debug Adaptor vscode executable path using the --vscode " + "option, or a port to attach to for an existing lldb-vscode " + "using the --port option" + ) return dbg = DebugAdaptor(executable=options.vscode_path, port=options.port) if options.debug: - raw_input('Waiting for debugger to attach pid "%i"' % ( - dbg.get_pid())) + raw_input('Waiting for debugger to attach pid "%i"' % (dbg.get_pid())) if options.replay: dbg.replay_packets(options.replay) else: @@ -1270,5 +1331,5 @@ dbg.terminate() -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/lldb/packages/Python/lldbsuite/test_event/build_exception.py b/lldb/packages/Python/lldbsuite/test_event/build_exception.py --- a/lldb/packages/Python/lldbsuite/test_event/build_exception.py +++ b/lldb/packages/Python/lldbsuite/test_event/build_exception.py @@ -1,7 +1,7 @@ from lldbsuite.support import seven -class BuildError(Exception): +class BuildError(Exception): def __init__(self, called_process_error): super(BuildError, self).__init__("Error when building test subject") self.command = seven.join_for_shell(called_process_error.cmd) @@ -13,4 +13,5 @@ @staticmethod def format_build_error(command, command_output): return "Error when building test subject.\n\nBuild Command:\n{}\n\nBuild Command Output:\n{}".format( - command, command_output) + command, command_output + ) diff --git a/lldb/test/API/android/platform/TestDefaultCacheLineSize.py b/lldb/test/API/android/platform/TestDefaultCacheLineSize.py --- a/lldb/test/API/android/platform/TestDefaultCacheLineSize.py +++ b/lldb/test/API/android/platform/TestDefaultCacheLineSize.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -20,23 +19,17 @@ self.assertTrue(target and target.IsValid(), "Target is valid") breakpoint = target.BreakpointCreateByName("main") - self.assertTrue( - breakpoint and breakpoint.IsValid(), - "Breakpoint is valid") + self.assertTrue(breakpoint and breakpoint.IsValid(), "Breakpoint is valid") # Run the program. - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) - self.assertEqual( - process.GetState(), - lldb.eStateStopped, - PROCESS_STOPPED) + self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) # check the setting value self.expect( - "settings show target.process.memory-cache-line-size", - patterns=[" = 2048"]) + "settings show target.process.memory-cache-line-size", patterns=[" = 2048"] + ) # Run to completion. process.Continue() diff --git a/lldb/test/API/api/check_public_api_headers/TestPublicAPIHeaders.py b/lldb/test/API/api/check_public_api_headers/TestPublicAPIHeaders.py --- a/lldb/test/API/api/check_public_api_headers/TestPublicAPIHeaders.py +++ b/lldb/test/API/api/check_public_api_headers/TestPublicAPIHeaders.py @@ -16,7 +16,7 @@ def setUp(self): TestBase.setUp(self) - self.source = 'main.cpp' + self.source = "main.cpp" self.generateSource(self.source) def test_sb_api_directory(self): @@ -36,22 +36,28 @@ # This test uses a generated source file, so it's in the build directory. self.line_to_break = line_number( - self.getBuildArtifact(self.source), '// Set breakpoint here.') + self.getBuildArtifact(self.source), "// Set breakpoint here." + ) env_cmd = "settings set target.env-vars %s=%s" % ( - self.dylibPath, self.getLLDBLibraryEnvVal()) + self.dylibPath, + self.getLLDBLibraryEnvVal(), + ) if self.TraceOn(): print("Set environment to: ", env_cmd) self.runCmd(env_cmd) lldbutil.run_break_set_by_file_and_line( - self, self.source, self.line_to_break, num_expected_locations=-1) + self, self.source, self.line_to_break, num_expected_locations=-1 + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) - self.runCmd('frame variable') + self.runCmd("frame variable") diff --git a/lldb/test/API/api/command-return-object/TestSBCommandReturnObject.py b/lldb/test/API/api/command-return-object/TestSBCommandReturnObject.py --- a/lldb/test/API/api/command-return-object/TestSBCommandReturnObject.py +++ b/lldb/test/API/api/command-return-object/TestSBCommandReturnObject.py @@ -10,13 +10,13 @@ @skipIfNoSBHeaders @expectedFailureAll( - oslist=["windows"], archs=["i[3-6]86", "x86_64"], - bugnumber="llvm.org/pr43570") + oslist=["windows"], archs=["i[3-6]86", "x86_64"], bugnumber="llvm.org/pr43570" + ) def test_sb_command_return_object(self): env = {self.dylibPath: self.getLLDBLibraryEnvVal()} self.driver_exe = self.getBuildArtifact("command-return-object") - self.buildDriver('main.cpp', self.driver_exe) + self.buildDriver("main.cpp", self.driver_exe) self.addTearDownHook(lambda: os.remove(self.driver_exe)) self.signBinary(self.driver_exe) @@ -24,6 +24,10 @@ print("Running test %s" % self.driver_exe) check_call([self.driver_exe, self.driver_exe], env=env) else: - with open(os.devnull, 'w') as fnull: - check_call([self.driver_exe, self.driver_exe], - env=env, stdout=fnull, stderr=fnull) + with open(os.devnull, "w") as fnull: + check_call( + [self.driver_exe, self.driver_exe], + env=env, + stdout=fnull, + stderr=fnull, + ) diff --git a/lldb/test/API/api/listeners/TestListener.py b/lldb/test/API/api/listeners/TestListener.py --- a/lldb/test/API/api/listeners/TestListener.py +++ b/lldb/test/API/api/listeners/TestListener.py @@ -7,7 +7,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class ListenToModuleLoadedEvents (TestBase): + +class ListenToModuleLoadedEvents(TestBase): NO_DEBUG_INFO_TESTCASE = True def test_clearing_listener(self): @@ -21,15 +22,18 @@ my_listener.StartListeningForEventClass( self.dbg, lldb.SBTarget.GetBroadcasterClassName(), - lldb.SBTarget.eBroadcastBitBreakpointChanged) + lldb.SBTarget.eBroadcastBitBreakpointChanged, + ) my_first_listener.StartListeningForEventClass( self.dbg, lldb.SBTarget.GetBroadcasterClassName(), - lldb.SBTarget.eBroadcastBitWatchpointChanged) + lldb.SBTarget.eBroadcastBitWatchpointChanged, + ) my_third_listener.StartListeningForEventClass( self.dbg, lldb.SBTarget.GetBroadcasterClassName(), - lldb.SBTarget.eBroadcastBitModulesUnloaded) + lldb.SBTarget.eBroadcastBitModulesUnloaded, + ) my_listener.Clear() @@ -39,8 +43,10 @@ event = lldb.SBEvent() my_listener.WaitForEvent(1, event) - self.assertTrue(not event.IsValid(), "We don't get events we aren't listening to.") - + self.assertTrue( + not event.IsValid(), "We don't get events we aren't listening to." + ) + def test_receiving_breakpoint_added_from_debugger(self): """Test that we get breakpoint added events, waiting on event classes on the debugger""" self.build() @@ -50,7 +56,8 @@ my_listener.StartListeningForEventClass( self.dbg, lldb.SBTarget.GetBroadcasterClassName(), - lldb.SBTarget.eBroadcastBitBreakpointChanged) + lldb.SBTarget.eBroadcastBitBreakpointChanged, + ) target = self.createTestTarget() @@ -61,26 +68,34 @@ self.assertTrue(event.IsValid(), "Got a valid event.") self.assertTrue( - lldb.SBBreakpoint.EventIsBreakpointEvent(event), - "It is a breakpoint event.") - self.assertEqual(lldb.SBBreakpoint.GetBreakpointEventTypeFromEvent(event), - lldb.eBreakpointEventTypeAdded, "It is a breakpoint added event.") + lldb.SBBreakpoint.EventIsBreakpointEvent(event), "It is a breakpoint event." + ) self.assertEqual( - bkpt, lldb.SBBreakpoint.GetBreakpointFromEvent(event), - "It is our breakpoint.") + lldb.SBBreakpoint.GetBreakpointEventTypeFromEvent(event), + lldb.eBreakpointEventTypeAdded, + "It is a breakpoint added event.", + ) + self.assertEqual( + bkpt, + lldb.SBBreakpoint.GetBreakpointFromEvent(event), + "It is our breakpoint.", + ) # Now make sure if we stop listening for events we don't get them: my_listener.StopListeningForEventClass( self.dbg, lldb.SBTarget.GetBroadcasterClassName(), - lldb.SBTarget.eBroadcastBitBreakpointChanged) + lldb.SBTarget.eBroadcastBitBreakpointChanged, + ) my_listener.StopListeningForEvents( - target.GetBroadcaster(), - lldb.SBTarget.eBroadcastBitBreakpointChanged) - + target.GetBroadcaster(), lldb.SBTarget.eBroadcastBitBreakpointChanged + ) + bkpt2 = target.BreakpointCreateByName("main") my_listener.WaitForEvent(1, event) - self.assertTrue(not event.IsValid(), "We don't get events we aren't listening to.") + self.assertTrue( + not event.IsValid(), "We don't get events we aren't listening to." + ) def test_recieving_breakpoint_added_from_target(self): """Test that we get breakpoint added events, waiting on event classes on the debugger""" @@ -90,12 +105,16 @@ my_listener.StartListeningForEventClass( self.dbg, lldb.SBTarget.GetBroadcasterClassName(), - lldb.SBTarget.eBroadcastBitBreakpointChanged) + lldb.SBTarget.eBroadcastBitBreakpointChanged, + ) target = self.createTestTarget() - result = target.GetBroadcaster().AddListener(my_listener, - lldb.SBTarget.eBroadcastBitBreakpointChanged) - self.assertEqual(result, lldb.SBTarget.eBroadcastBitBreakpointChanged,"Got our bit") + result = target.GetBroadcaster().AddListener( + my_listener, lldb.SBTarget.eBroadcastBitBreakpointChanged + ) + self.assertEqual( + result, lldb.SBTarget.eBroadcastBitBreakpointChanged, "Got our bit" + ) bkpt = target.BreakpointCreateByName("main") @@ -104,18 +123,24 @@ self.assertTrue(event.IsValid(), "Got a valid event.") self.assertTrue( - lldb.SBBreakpoint.EventIsBreakpointEvent(event), - "It is a breakpoint event.") - self.assertEqual(lldb.SBBreakpoint.GetBreakpointEventTypeFromEvent(event), - lldb.eBreakpointEventTypeAdded, "It is a breakpoint added event.") + lldb.SBBreakpoint.EventIsBreakpointEvent(event), "It is a breakpoint event." + ) + self.assertEqual( + lldb.SBBreakpoint.GetBreakpointEventTypeFromEvent(event), + lldb.eBreakpointEventTypeAdded, + "It is a breakpoint added event.", + ) self.assertEqual( - bkpt, lldb.SBBreakpoint.GetBreakpointFromEvent(event), - "It is our breakpoint.") + bkpt, + lldb.SBBreakpoint.GetBreakpointFromEvent(event), + "It is our breakpoint.", + ) # Now make sure if we stop listening for events we don't get them: target.GetBroadcaster().RemoveListener(my_listener) - + bkpt2 = target.BreakpointCreateByName("main") my_listener.WaitForEvent(1, event) - self.assertTrue(not event.IsValid(), "We don't get events we aren't listening to.") - + self.assertTrue( + not event.IsValid(), "We don't get events we aren't listening to." + ) diff --git a/lldb/test/API/api/log/TestAPILog.py b/lldb/test/API/api/log/TestAPILog.py --- a/lldb/test/API/api/log/TestAPILog.py +++ b/lldb/test/API/api/log/TestAPILog.py @@ -10,7 +10,6 @@ class APILogTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True def test_api_log(self): @@ -24,21 +23,35 @@ target = self.dbg.CreateTarget(None) self.assertTrue(os.path.isfile(logfile)) - with open(logfile, 'r') as f: + with open(logfile, "r") as f: log = f.read() # Find the SBDebugger's address. debugger_addr = re.findall( - r"lldb::SBDebugger::GetScriptingLanguage\([^)]*\) \(0x([0-9a-fA-F]+),", - log) + r"lldb::SBDebugger::GetScriptingLanguage\([^)]*\) \(0x([0-9a-fA-F]+),", log + ) # Make sure we've found a match. self.assertTrue(debugger_addr, log) # Make sure the GetScriptingLanguage matches. - self.assertTrue(re.search(r'lldb::SBDebugger::GetScriptingLanguage\([^)]*\) \(0x{}, ""\)'.format( - debugger_addr[0]), log), log) + self.assertTrue( + re.search( + r'lldb::SBDebugger::GetScriptingLanguage\([^)]*\) \(0x{}, ""\)'.format( + debugger_addr[0] + ), + log, + ), + log, + ) # Make sure the address matches. - self.assertTrue(re.search(r'lldb::SBDebugger::CreateTarget\([^)]*\) \(0x{}, ""\)'.format( - debugger_addr[0]), log), log) + self.assertTrue( + re.search( + r'lldb::SBDebugger::CreateTarget\([^)]*\) \(0x{}, ""\)'.format( + debugger_addr[0] + ), + log, + ), + log, + ) diff --git a/lldb/test/API/api/multiple-debuggers/TestMultipleDebuggers.py b/lldb/test/API/api/multiple-debuggers/TestMultipleDebuggers.py --- a/lldb/test/API/api/multiple-debuggers/TestMultipleDebuggers.py +++ b/lldb/test/API/api/multiple-debuggers/TestMultipleDebuggers.py @@ -9,7 +9,6 @@ class TestMultipleSimultaneousDebuggers(TestBase): - NO_DEBUG_INFO_TESTCASE = True @skipIfNoSBHeaders @@ -18,17 +17,17 @@ env = {self.dylibPath: self.getLLDBLibraryEnvVal()} # We need this in order to run under ASAN, in case only LLDB is ASANified. - asan_options = os.getenv('ASAN_OPTIONS', None) - if (asan_options is not None): - env['ASAN_OPTIONS'] = asan_options + asan_options = os.getenv("ASAN_OPTIONS", None) + if asan_options is not None: + env["ASAN_OPTIONS"] = asan_options self.driver_exe = self.getBuildArtifact("multi-process-driver") - self.buildDriver('multi-process-driver.cpp', self.driver_exe) + self.buildDriver("multi-process-driver.cpp", self.driver_exe) self.addTearDownHook(lambda: os.remove(self.driver_exe)) self.signBinary(self.driver_exe) self.inferior_exe = self.getBuildArtifact("testprog") - self.buildDriver('testprog.cpp', self.inferior_exe) + self.buildDriver("testprog.cpp", self.inferior_exe) self.addTearDownHook(lambda: os.remove(self.inferior_exe)) # check_call will raise a CalledProcessError if multi-process-driver @@ -39,6 +38,10 @@ print("Running test %s" % self.driver_exe) check_call([self.driver_exe, self.inferior_exe], env=env) else: - with open(os.devnull, 'w') as fnull: - check_call([self.driver_exe, self.inferior_exe], - env=env, stdout=fnull, stderr=fnull) + with open(os.devnull, "w") as fnull: + check_call( + [self.driver_exe, self.inferior_exe], + env=env, + stdout=fnull, + stderr=fnull, + ) diff --git a/lldb/test/API/api/multiple-targets/TestMultipleTargets.py b/lldb/test/API/api/multiple-targets/TestMultipleTargets.py --- a/lldb/test/API/api/multiple-targets/TestMultipleTargets.py +++ b/lldb/test/API/api/multiple-targets/TestMultipleTargets.py @@ -15,25 +15,29 @@ @skipIfNoSBHeaders @skipIfHostIncompatibleWithRemote @expectedFailureAll( - oslist=["windows"], archs=["i[3-6]86", "x86_64"], - bugnumber="llvm.org/pr20282") + oslist=["windows"], archs=["i[3-6]86", "x86_64"], bugnumber="llvm.org/pr20282" + ) @expectedFlakeyNetBSD def test_multiple_targets(self): env = {self.dylibPath: self.getLLDBLibraryEnvVal()} self.driver_exe = self.getBuildArtifact("multi-target") - self.buildDriver('main.cpp', self.driver_exe) + self.buildDriver("main.cpp", self.driver_exe) self.addTearDownHook(lambda: os.remove(self.driver_exe)) self.signBinary(self.driver_exe) -# check_call will raise a CalledProcessError if multi-process-driver doesn't return -# exit code 0 to indicate success. We can let this exception go - the test harness -# will recognize it as a test failure. + # check_call will raise a CalledProcessError if multi-process-driver doesn't return + # exit code 0 to indicate success. We can let this exception go - the test harness + # will recognize it as a test failure. if self.TraceOn(): print("Running test %s" % self.driver_exe) check_call([self.driver_exe, self.driver_exe], env=env) else: - with open(os.devnull, 'w') as fnull: - check_call([self.driver_exe, self.driver_exe], - env=env, stdout=fnull, stderr=fnull) + with open(os.devnull, "w") as fnull: + check_call( + [self.driver_exe, self.driver_exe], + env=env, + stdout=fnull, + stderr=fnull, + ) diff --git a/lldb/test/API/api/multithreaded/TestMultithreaded.py b/lldb/test/API/api/multithreaded/TestMultithreaded.py --- a/lldb/test/API/api/multithreaded/TestMultithreaded.py +++ b/lldb/test/API/api/multithreaded/TestMultithreaded.py @@ -11,79 +11,83 @@ @skipIfNoSBHeaders class SBBreakpointCallbackCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True def setUp(self): TestBase.setUp(self) - self.generateSource('driver.cpp') - self.generateSource('listener_test.cpp') - self.generateSource('test_breakpoint_callback.cpp') - self.generateSource('test_breakpoint_location_callback.cpp') - self.generateSource('test_listener_event_description.cpp') - self.generateSource('test_listener_event_process_state.cpp') - self.generateSource('test_listener_resume.cpp') - self.generateSource('test_stop-hook.cpp') + self.generateSource("driver.cpp") + self.generateSource("listener_test.cpp") + self.generateSource("test_breakpoint_callback.cpp") + self.generateSource("test_breakpoint_location_callback.cpp") + self.generateSource("test_listener_event_description.cpp") + self.generateSource("test_listener_event_process_state.cpp") + self.generateSource("test_listener_resume.cpp") + self.generateSource("test_stop-hook.cpp") @skipIfRemote # clang-cl does not support throw or catch (llvm.org/pr24538) @skipIfWindows def test_python_stop_hook(self): - """Test that you can run a python command in a stop-hook when stdin is File based. """ - self.build_and_test('driver.cpp test_stop-hook.cpp', - 'test_python_stop_hook') + """Test that you can run a python command in a stop-hook when stdin is File based.""" + self.build_and_test("driver.cpp test_stop-hook.cpp", "test_python_stop_hook") @skipIfRemote # clang-cl does not support throw or catch (llvm.org/pr24538) @skipIfWindows def test_breakpoint_callback(self): - """Test the that SBBreakpoint callback is invoked when a breakpoint is hit. """ - self.build_and_test('driver.cpp test_breakpoint_callback.cpp', - 'test_breakpoint_callback') + """Test the that SBBreakpoint callback is invoked when a breakpoint is hit.""" + self.build_and_test( + "driver.cpp test_breakpoint_callback.cpp", "test_breakpoint_callback" + ) @skipIfRemote # clang-cl does not support throw or catch (llvm.org/pr24538) @skipIfWindows def test_breakpoint_location_callback(self): - """Test the that SBBreakpointLocation callback is invoked when a breakpoint is hit. """ - self.build_and_test('driver.cpp test_breakpoint_location_callback.cpp', - 'test_breakpoint_location_callback') + """Test the that SBBreakpointLocation callback is invoked when a breakpoint is hit.""" + self.build_and_test( + "driver.cpp test_breakpoint_location_callback.cpp", + "test_breakpoint_location_callback", + ) @skipIfRemote # clang-cl does not support throw or catch (llvm.org/pr24538) @skipIfWindows @expectedFlakeyFreeBSD def test_sb_api_listener_event_description(self): - """ Test the description of an SBListener breakpoint event is valid.""" + """Test the description of an SBListener breakpoint event is valid.""" self.build_and_test( - 'driver.cpp listener_test.cpp test_listener_event_description.cpp', - 'test_listener_event_description') + "driver.cpp listener_test.cpp test_listener_event_description.cpp", + "test_listener_event_description", + ) @skipIfRemote # clang-cl does not support throw or catch (llvm.org/pr24538) @skipIfWindows @expectedFlakeyFreeBSD def test_sb_api_listener_event_process_state(self): - """ Test that a registered SBListener receives events when a process - changes state. + """Test that a registered SBListener receives events when a process + changes state. """ self.build_and_test( - 'driver.cpp listener_test.cpp test_listener_event_process_state.cpp', - 'test_listener_event_process_state') + "driver.cpp listener_test.cpp test_listener_event_process_state.cpp", + "test_listener_event_process_state", + ) @skipIfRemote # clang-cl does not support throw or catch (llvm.org/pr24538) @skipIfWindows @expectedFlakeyFreeBSD - @skipIf(oslist=["linux"]) # flakey + @skipIf(oslist=["linux"]) # flakey def test_sb_api_listener_resume(self): - """ Test that a process can be resumed from a non-main thread. """ + """Test that a process can be resumed from a non-main thread.""" self.build_and_test( - 'driver.cpp listener_test.cpp test_listener_resume.cpp', - 'test_listener_resume') + "driver.cpp listener_test.cpp test_listener_resume.cpp", + "test_listener_resume", + ) def build_and_test(self, sources, test_name, args=None): - """ Build LLDB test from sources, and run expecting 0 exit code """ + """Build LLDB test from sources, and run expecting 0 exit code""" # These tests link against host lldb API. # Compiler's target triple must match liblldb triple @@ -91,30 +95,29 @@ # still need to check architecture if self.getLldbArchitecture() != self.getArchitecture(): self.skipTest( - "This test is only run if the target arch is the same as the lldb binary arch") + "This test is only run if the target arch is the same as the lldb binary arch" + ) - self.inferior = 'inferior_program' - self.buildProgram('inferior.cpp', self.inferior) - self.addTearDownHook(lambda: - os.remove(self.getBuildArtifact(self.inferior))) + self.inferior = "inferior_program" + self.buildProgram("inferior.cpp", self.inferior) + self.addTearDownHook(lambda: os.remove(self.getBuildArtifact(self.inferior))) self.buildDriver(sources, test_name) - self.addTearDownHook(lambda: - os.remove(self.getBuildArtifact(test_name))) + self.addTearDownHook(lambda: os.remove(self.getBuildArtifact(test_name))) test_exe = self.getBuildArtifact(test_name) self.signBinary(test_exe) exe = [test_exe, self.getBuildArtifact(self.inferior)] env = {self.dylibPath: self.getLLDBLibraryEnvVal()} - if 'LLDB_DEBUGSERVER_PATH' in os.environ: - env['LLDB_DEBUGSERVER_PATH'] = os.environ['LLDB_DEBUGSERVER_PATH'] + if "LLDB_DEBUGSERVER_PATH" in os.environ: + env["LLDB_DEBUGSERVER_PATH"] = os.environ["LLDB_DEBUGSERVER_PATH"] try: if self.TraceOn(): print("Running test %s" % " ".join(exe)) check_call(exe, env=env) else: - with open(os.devnull, 'w') as fnull: + with open(os.devnull, "w") as fnull: check_call(exe, env=env, stdout=fnull, stderr=fnull) except subprocess.CalledProcessError as e: self.fail(e) diff --git a/lldb/test/API/api/multithreaded/some_cmd.py b/lldb/test/API/api/multithreaded/some_cmd.py --- a/lldb/test/API/api/multithreaded/some_cmd.py +++ b/lldb/test/API/api/multithreaded/some_cmd.py @@ -3,9 +3,11 @@ did_run = False + class SomeCommand: def __init__(self, debugger, unused): self.dbg = debugger + def __call__(self, debugger, command, exe_ctx, result): global did_run did_run = True @@ -14,9 +16,11 @@ def get_short_help(self): return "Test command - sets a variable." + class OtherCommand: def __init__(self, debugger, unused): self.dbg = debugger + def __call__(self, debugger, command, exe_ctx, result): global did_run if did_run: @@ -27,6 +31,7 @@ def get_short_help(self): return "Test command - sets a variable." + def __lldb_init_module(debugger, unused): print("Adding command some-cmd and report-cmd") debugger.HandleCommand("command script add -c some_cmd.SomeCommand some-cmd") diff --git a/lldb/test/API/arm/breakpoint-it/TestBreakpointIt.py b/lldb/test/API/arm/breakpoint-it/TestBreakpointIt.py --- a/lldb/test/API/arm/breakpoint-it/TestBreakpointIt.py +++ b/lldb/test/API/arm/breakpoint-it/TestBreakpointIt.py @@ -20,12 +20,14 @@ exe = self.getBuildArtifact("a.out") self.runCmd("target create %s" % exe) - lldbutil.run_break_set_by_symbol(self, "bkpt_false", - extra_options="--skip-prologue 0") + lldbutil.run_break_set_by_symbol( + self, "bkpt_false", extra_options="--skip-prologue 0" + ) self.runCmd("run") - self.assertState(self.process().GetState(), lldb.eStateExited, - "Breakpoint does not get hit") + self.assertState( + self.process().GetState(), lldb.eStateExited, "Breakpoint does not get hit" + ) @skipIf(archs=no_match(["arm"])) @skipIf(archs=["arm64", "arm64e", "arm64_32"]) @@ -34,9 +36,11 @@ exe = self.getBuildArtifact("a.out") self.runCmd("target create %s" % exe) - bpid = lldbutil.run_break_set_by_symbol(self, "bkpt_true", - extra_options="--skip-prologue 0") + bpid = lldbutil.run_break_set_by_symbol( + self, "bkpt_true", extra_options="--skip-prologue 0" + ) self.runCmd("run") - self.assertIsNotNone(lldbutil.get_one_thread_stopped_at_breakpoint_id( - self.process(), bpid)) + self.assertIsNotNone( + lldbutil.get_one_thread_stopped_at_breakpoint_id(self.process(), bpid) + ) diff --git a/lldb/test/API/arm/breakpoint-thumb-codesection/TestBreakpointThumbCodesection.py b/lldb/test/API/arm/breakpoint-thumb-codesection/TestBreakpointThumbCodesection.py --- a/lldb/test/API/arm/breakpoint-thumb-codesection/TestBreakpointThumbCodesection.py +++ b/lldb/test/API/arm/breakpoint-thumb-codesection/TestBreakpointThumbCodesection.py @@ -11,22 +11,23 @@ class TestBreakpointThumbCodesection(TestBase): - @skipIf(archs=no_match(["arm"])) @skipIf(archs=["arm64"]) - @skipIfDarwinEmbedded # codegen on darwin always defaults to thumb for armv7/armv7k targets + @skipIfDarwinEmbedded # codegen on darwin always defaults to thumb for armv7/armv7k targets def test_breakpoint(self): self.build() exe = self.getBuildArtifact("a.out") - line = line_number('main.c', '// Set break point at this line.') + line = line_number("main.c", "// Set break point at this line.") self.runCmd("target create %s" % exe) bpid = lldbutil.run_break_set_by_file_and_line(self, "main.c", line) self.runCmd("run") - self.assertIsNotNone(lldbutil.get_one_thread_stopped_at_breakpoint_id( - self.process(), bpid), "Process is not stopped at breakpoint") + self.assertIsNotNone( + lldbutil.get_one_thread_stopped_at_breakpoint_id(self.process(), bpid), + "Process is not stopped at breakpoint", + ) self.process().Continue() self.assertState(self.process().GetState(), lldb.eStateExited, PROCESS_EXITED) diff --git a/lldb/test/API/arm/emulation/TestEmulations.py b/lldb/test/API/arm/emulation/TestEmulations.py --- a/lldb/test/API/arm/emulation/TestEmulations.py +++ b/lldb/test/API/arm/emulation/TestEmulations.py @@ -10,14 +10,13 @@ class ARMEmulationTestCase(TestBase): - @no_debug_info_test def test_thumb_emulations(self): test_dir = os.path.join(self.getSourceDir(), "new-test-files") files = os.listdir(test_dir) thumb_files = list() for f in files: - if f.endswith('-thumb.dat'): + if f.endswith("-thumb.dat"): thumb_files.append(f) for f in thumb_files: @@ -30,7 +29,7 @@ files = os.listdir(test_dir) arm_files = list() for f in files: - if f.endswith('-arm.dat'): + if f.endswith("-arm.dat"): arm_files.append(f) for f in arm_files: @@ -43,8 +42,7 @@ success = insn.TestEmulation(stream, filename) output = stream.GetData() if self.TraceOn(): - print('\nRunning test ' + os.path.basename(filename)) + print("\nRunning test " + os.path.basename(filename)) print(output) - self.assertTrue(success, 'Emulation test {} failed.'.format( - filename)) + self.assertTrue(success, "Emulation test {} failed.".format(filename)) diff --git a/lldb/test/API/assert_messages_test/TestAssertMessages.py b/lldb/test/API/assert_messages_test/TestAssertMessages.py --- a/lldb/test/API/assert_messages_test/TestAssertMessages.py +++ b/lldb/test/API/assert_messages_test/TestAssertMessages.py @@ -26,12 +26,13 @@ @expectedFailureAll(remote=True) def test_createTestTarget(self): try: - self.createTestTarget("doesnt_exist") + self.createTestTarget("doesnt_exist") except AssertionError as e: - self.assertIn("Couldn't create target for path 'doesnt_exist': " - "error: unable to find executable for 'doesnt_exist'", - str(e)) - + self.assertIn( + "Couldn't create target for path 'doesnt_exist': " + "error: unable to find executable for 'doesnt_exist'", + str(e), + ) def test_expect(self): """Test format of messages produced by expect(...)""" @@ -42,7 +43,8 @@ # content for the trace log too. # Will stop at startstr fail - self.assert_expect_fails_with("settings list prompt", + self.assert_expect_fails_with( + "settings list prompt", dict(startstr="dog", endstr="cat"), """\ Ran command: @@ -51,11 +53,13 @@ Got output: prompt -- The debugger command line prompt displayed for the user. - Expecting start string: "dog" (was not found)""") + Expecting start string: "dog" (was not found)""", + ) # startstr passes, endstr fails # We see both reported - self.assert_expect_fails_with("settings list prompt", + self.assert_expect_fails_with( + "settings list prompt", dict(startstr=" prompt -- ", endstr="foo"), """\ Ran command: @@ -65,26 +69,34 @@ prompt -- The debugger command line prompt displayed for the user. Expecting start string: " prompt -- " (was found) - Expecting end string: "foo" (was not found)""") + Expecting end string: "foo" (was not found)""", + ) # Same thing for substrs, regex patterns ignored because of substr failure # Any substr after the first missing is also ignored - self.assert_expect_fails_with("abcdefg", - dict(substrs=["abc", "ijk", "xyz"], - patterns=["foo", "bar"], exe=False), + self.assert_expect_fails_with( + "abcdefg", + dict(substrs=["abc", "ijk", "xyz"], patterns=["foo", "bar"], exe=False), """\ Checking string: "abcdefg" Expecting sub string: "abc" (was found) - Expecting sub string: "ijk" (was not found)""") + Expecting sub string: "ijk" (was not found)""", + ) # Regex patterns also stop at first failure, subsequent patterns ignored # They are last in the chain so no other check gets skipped # Including the rest of the conditions here to prove they are run and shown - self.assert_expect_fails_with("0123456789", - dict(startstr="012", endstr="789", substrs=["345", "678"], - patterns=["[0-9]+", "[a-f]+", "a|b|c"], exe=False), + self.assert_expect_fails_with( + "0123456789", + dict( + startstr="012", + endstr="789", + substrs=["345", "678"], + patterns=["[0-9]+", "[a-f]+", "a|b|c"], + exe=False, + ), """\ Checking string: "0123456789" @@ -94,13 +106,21 @@ Expecting sub string: "345" (was found) Expecting sub string: "678" (was found) Expecting regex pattern: "[0-9]+" (was found, matched "0123456789") - Expecting regex pattern: "[a-f]+" (was not found)""") + Expecting regex pattern: "[a-f]+" (was not found)""", + ) # This time we dont' want matches but we do get them - self.assert_expect_fails_with("the quick brown fox", + self.assert_expect_fails_with( + "the quick brown fox", # Note that the second pattern *will* match - dict(patterns=["[0-9]+", "fox"], exe=False, matching=False, - startstr="cat", endstr="rabbit", substrs=["abc", "def"]), + dict( + patterns=["[0-9]+", "fox"], + exe=False, + matching=False, + startstr="cat", + endstr="rabbit", + substrs=["abc", "def"], + ), """\ Checking string: "the quick brown fox" @@ -110,32 +130,43 @@ Not expecting sub string: "abc" (was not found) Not expecting sub string: "def" (was not found) Not expecting regex pattern: "[0-9]+" (was not found) - Not expecting regex pattern: "fox" (was found, matched "fox")""") + Not expecting regex pattern: "fox" (was found, matched "fox")""", + ) # Extra assert messages are only printed when we get a failure # So I can't test that from here, just how it looks when it's printed - self.assert_expect_fails_with("mouse", + self.assert_expect_fails_with( + "mouse", dict(startstr="cat", exe=False, msg="Reason for check goes here!"), """\ Checking string: "mouse" Expecting start string: "cat" (was not found) - Reason for check goes here!""") + Reason for check goes here!""", + ) # Verify expect() preconditions. # Both `patterns` and `substrs` cannot be of type string. - self.assert_expect_fails_with("any command", + self.assert_expect_fails_with( + "any command", dict(patterns="some substring"), - "patterns must be a collection of strings") - self.assert_expect_fails_with("any command", + "patterns must be a collection of strings", + ) + self.assert_expect_fails_with( + "any command", dict(substrs="some substring"), - "substrs must be a collection of strings") + "substrs must be a collection of strings", + ) # Prevent `self.expect("cmd", "substr")` - self.assert_expect_fails_with("any command", + self.assert_expect_fails_with( + "any command", dict(msg="some substring"), - "expect() missing a matcher argument") + "expect() missing a matcher argument", + ) # Prevent `self.expect("cmd", "msg", "substr")` - self.assert_expect_fails_with("any command", + self.assert_expect_fails_with( + "any command", dict(msg="a message", patterns="some substring"), - "must be a collection of strings") + "must be a collection of strings", + ) diff --git a/lldb/test/API/benchmarks/continue/TestBenchmarkContinue.py b/lldb/test/API/benchmarks/continue/TestBenchmarkContinue.py --- a/lldb/test/API/benchmarks/continue/TestBenchmarkContinue.py +++ b/lldb/test/API/benchmarks/continue/TestBenchmarkContinue.py @@ -10,7 +10,6 @@ class TestBenchmarkContinue(BenchBase): - @benchmarks_test def test_run_command(self): """Benchmark different ways to continue a process""" @@ -23,30 +22,29 @@ def data_formatter_commands(self): """Benchmark different ways to continue a process""" - self.runCmd("file "+self.getBuildArtifact("a.out"), - CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) bkpt = self.target().FindBreakpointByID( - lldbutil.run_break_set_by_source_regexp( - self, "// break here")) + lldbutil.run_break_set_by_source_regexp(self, "// break here") + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) diff --git a/lldb/test/API/benchmarks/expression/TestExpressionCmd.py b/lldb/test/API/benchmarks/expression/TestExpressionCmd.py --- a/lldb/test/API/benchmarks/expression/TestExpressionCmd.py +++ b/lldb/test/API/benchmarks/expression/TestExpressionCmd.py @@ -10,22 +10,21 @@ class ExpressionEvaluationCase(BenchBase): - def setUp(self): BenchBase.setUp(self) - self.source = 'main.cpp' - self.line_to_break = line_number( - self.source, '// Set breakpoint here.') + self.source = "main.cpp" + self.line_to_break = line_number(self.source, "// Set breakpoint here.") self.count = 25 @benchmarks_test @expectedFailureAll( oslist=["windows"], - bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows", + ) def test_expr_cmd(self): """Test lldb's expression commands and collect statistics.""" self.build() - self.exe_name = 'a.out' + self.exe_name = "a.out" print() self.run_lldb_repeated_exprs(self.exe_name, self.count) @@ -33,10 +32,11 @@ def run_lldb_repeated_exprs(self, exe_name, count): import pexpect + exe = self.getBuildArtifact(exe_name) # Set self.child_prompt, which is "(lldb) ". - self.child_prompt = '(lldb) ' + self.child_prompt = "(lldb) " prompt = self.child_prompt # Reset the stopwatch now. @@ -44,8 +44,8 @@ for i in range(count): # So that the child gets torn down after the test. self.child = pexpect.spawn( - '%s %s %s' % - (lldbtest_config.lldbExec, self.lldbOption, exe)) + "%s %s %s" % (lldbtest_config.lldbExec, self.lldbOption, exe) + ) child = self.child # Turn on logging for what the child sends back. @@ -54,13 +54,13 @@ child.expect_exact(prompt) child.sendline( - 'breakpoint set -f %s -l %d' % - (self.source, self.line_to_break)) + "breakpoint set -f %s -l %d" % (self.source, self.line_to_break) + ) child.expect_exact(prompt) - child.sendline('run') + child.sendline("run") child.expect_exact(prompt) - expr_cmd1 = 'expr ptr[j]->point.x' - expr_cmd2 = 'expr ptr[j]->point.y' + expr_cmd1 = "expr ptr[j]->point.x" + expr_cmd2 = "expr ptr[j]->point.y" with self.stopwatch: child.sendline(expr_cmd1) @@ -68,7 +68,7 @@ child.sendline(expr_cmd2) child.expect_exact(prompt) - child.sendline('quit') + child.sendline("quit") try: self.child.expect(pexpect.EOF) except: diff --git a/lldb/test/API/benchmarks/expression/TestRepeatedExprs.py b/lldb/test/API/benchmarks/expression/TestRepeatedExprs.py --- a/lldb/test/API/benchmarks/expression/TestRepeatedExprs.py +++ b/lldb/test/API/benchmarks/expression/TestRepeatedExprs.py @@ -10,12 +10,10 @@ class RepeatedExprsCase(BenchBase): - def setUp(self): BenchBase.setUp(self) - self.source = 'main.cpp' - self.line_to_break = line_number( - self.source, '// Set breakpoint here.') + self.source = "main.cpp" + self.line_to_break = line_number(self.source, "// Set breakpoint here.") self.lldb_avg = None self.gdb_avg = None self.count = 100 @@ -23,11 +21,12 @@ @benchmarks_test @expectedFailureAll( oslist=["windows"], - bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows", + ) def test_compare_lldb_to_gdb(self): """Test repeated expressions with lldb vs. gdb.""" self.build() - self.exe_name = 'a.out' + self.exe_name = "a.out" print() self.run_lldb_repeated_exprs(self.exe_name, self.count) @@ -38,16 +37,17 @@ def run_lldb_repeated_exprs(self, exe_name, count): import pexpect + exe = self.getBuildArtifact(exe_name) # Set self.child_prompt, which is "(lldb) ". - self.child_prompt = '(lldb) ' + self.child_prompt = "(lldb) " prompt = self.child_prompt # So that the child gets torn down after the test. self.child = pexpect.spawn( - '%s %s %s' % - (lldbtest_config.lldbExec, self.lldbOption, exe)) + "%s %s %s" % (lldbtest_config.lldbExec, self.lldbOption, exe) + ) child = self.child # Turn on logging for what the child sends back. @@ -55,14 +55,12 @@ child.logfile_read = sys.stdout child.expect_exact(prompt) - child.sendline( - 'breakpoint set -f %s -l %d' % - (self.source, self.line_to_break)) + child.sendline("breakpoint set -f %s -l %d" % (self.source, self.line_to_break)) child.expect_exact(prompt) - child.sendline('run') + child.sendline("run") child.expect_exact(prompt) - expr_cmd1 = 'expr ptr[j]->point.x' - expr_cmd2 = 'expr ptr[j]->point.y' + expr_cmd1 = "expr ptr[j]->point.x" + expr_cmd2 = "expr ptr[j]->point.y" # Reset the stopwatch now. self.stopwatch.reset() @@ -72,10 +70,10 @@ child.expect_exact(prompt) child.sendline(expr_cmd2) child.expect_exact(prompt) - child.sendline('process continue') + child.sendline("process continue") child.expect_exact(prompt) - child.sendline('quit') + child.sendline("quit") try: self.child.expect(pexpect.EOF) except: @@ -88,14 +86,15 @@ def run_gdb_repeated_exprs(self, exe_name, count): import pexpect + exe = self.getBuildArtifact(exe_name) # Set self.child_prompt, which is "(gdb) ". - self.child_prompt = '(gdb) ' + self.child_prompt = "(gdb) " prompt = self.child_prompt # So that the child gets torn down after the test. - self.child = pexpect.spawn('gdb --nx %s' % exe) + self.child = pexpect.spawn("gdb --nx %s" % exe) child = self.child # Turn on logging for what the child sends back. @@ -103,12 +102,12 @@ child.logfile_read = sys.stdout child.expect_exact(prompt) - child.sendline('break %s:%d' % (self.source, self.line_to_break)) + child.sendline("break %s:%d" % (self.source, self.line_to_break)) child.expect_exact(prompt) - child.sendline('run') + child.sendline("run") child.expect_exact(prompt) - expr_cmd1 = 'print ptr[j]->point.x' - expr_cmd2 = 'print ptr[j]->point.y' + expr_cmd1 = "print ptr[j]->point.x" + expr_cmd2 = "print ptr[j]->point.y" # Reset the stopwatch now. self.stopwatch.reset() @@ -118,12 +117,12 @@ child.expect_exact(prompt) child.sendline(expr_cmd2) child.expect_exact(prompt) - child.sendline('continue') + child.sendline("continue") child.expect_exact(prompt) - child.sendline('quit') - child.expect_exact('The program is running. Exit anyway?') - child.sendline('y') + child.sendline("quit") + child.expect_exact("The program is running. Exit anyway?") + child.sendline("y") try: self.child.expect(pexpect.EOF) except: diff --git a/lldb/test/API/benchmarks/frame_variable/TestFrameVariableResponse.py b/lldb/test/API/benchmarks/frame_variable/TestFrameVariableResponse.py --- a/lldb/test/API/benchmarks/frame_variable/TestFrameVariableResponse.py +++ b/lldb/test/API/benchmarks/frame_variable/TestFrameVariableResponse.py @@ -9,18 +9,18 @@ class FrameVariableResponseBench(BenchBase): - def setUp(self): BenchBase.setUp(self) self.exe = lldbtest_config.lldbExec - self.break_spec = '-n main' + self.break_spec = "-n main" self.count = 20 @benchmarks_test @no_debug_info_test @expectedFailureAll( oslist=["windows"], - bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows", + ) def test_startup_delay(self): """Test response time for the 'frame variable' command.""" print() @@ -29,8 +29,9 @@ def run_frame_variable_bench(self, exe, break_spec, count): import pexpect + # Set self.child_prompt, which is "(lldb) ". - self.child_prompt = '(lldb) ' + self.child_prompt = "(lldb) " prompt = self.child_prompt # Reset the stopwatchs now. @@ -38,8 +39,8 @@ for i in range(count): # So that the child gets torn down after the test. self.child = pexpect.spawn( - '%s %s %s' % - (lldbtest_config.lldbExec, self.lldbOption, exe)) + "%s %s %s" % (lldbtest_config.lldbExec, self.lldbOption, exe) + ) child = self.child # Turn on logging for what the child sends back. @@ -47,19 +48,19 @@ child.logfile_read = sys.stdout # Set our breakpoint. - child.sendline('breakpoint set %s' % break_spec) + child.sendline("breakpoint set %s" % break_spec) child.expect_exact(prompt) # Run the target and expect it to be stopped due to breakpoint. - child.sendline('run') # Aka 'process launch'. + child.sendline("run") # Aka 'process launch'. child.expect_exact(prompt) with self.stopwatch: # Measure the 'frame variable' response time. - child.sendline('frame variable') + child.sendline("frame variable") child.expect_exact(prompt) - child.sendline('quit') + child.sendline("quit") try: self.child.expect(pexpect.EOF) except: diff --git a/lldb/test/API/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py b/lldb/test/API/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py --- a/lldb/test/API/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py +++ b/lldb/test/API/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py @@ -10,7 +10,6 @@ class TestBenchmarkLibcxxList(BenchBase): - @benchmarks_test def test_run_command(self): """Benchmark the std::list data formatter (libc++)""" @@ -23,30 +22,29 @@ def data_formatter_commands(self): """Benchmark the std::list data formatter (libc++)""" - self.runCmd("file " + self.getBuildArtifact("a.out"), - CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) bkpt = self.target().FindBreakpointByID( - lldbutil.run_break_set_by_source_regexp( - self, "break here")) + lldbutil.run_break_set_by_source_regexp(self, "break here") + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -54,7 +52,7 @@ sw = Stopwatch() sw.start() - self.expect('frame variable -A list', substrs=['[300]', '300']) + self.expect("frame variable -A list", substrs=["[300]", "300"]) sw.stop() print("time to print: %s" % (sw)) diff --git a/lldb/test/API/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py b/lldb/test/API/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py --- a/lldb/test/API/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py +++ b/lldb/test/API/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py @@ -10,7 +10,6 @@ class TestBenchmarkLibcxxMap(BenchBase): - @benchmarks_test def test_run_command(self): """Benchmark the std::map data formatter (libc++)""" @@ -23,30 +22,29 @@ def data_formatter_commands(self): """Benchmark the std::map data formatter (libc++)""" - self.runCmd("file " +self.getBuildArtifact("a.out"), - CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) bkpt = self.target().FindBreakpointByID( - lldbutil.run_break_set_by_source_regexp( - self, "break here")) + lldbutil.run_break_set_by_source_regexp(self, "break here") + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -54,7 +52,7 @@ sw = Stopwatch() sw.start() - self.expect('frame variable -A map', substrs=['[300]', '300']) + self.expect("frame variable -A map", substrs=["[300]", "300"]) sw.stop() print("time to print: %s" % (sw)) diff --git a/lldb/test/API/benchmarks/startup/TestStartupDelays.py b/lldb/test/API/benchmarks/startup/TestStartupDelays.py --- a/lldb/test/API/benchmarks/startup/TestStartupDelays.py +++ b/lldb/test/API/benchmarks/startup/TestStartupDelays.py @@ -9,7 +9,6 @@ class StartupDelaysBench(BenchBase): - def setUp(self): BenchBase.setUp(self) # Create self.stopwatch2 for measuring "set first breakpoint". @@ -18,32 +17,28 @@ # Create self.stopwatch3 for measuring "run to breakpoint". self.stopwatch3 = Stopwatch() self.exe = lldbtest_config.lldbExec - self.break_spec = '-n main' + self.break_spec = "-n main" self.count = 30 @benchmarks_test @no_debug_info_test @expectedFailureAll( oslist=["windows"], - bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows", + ) def test_startup_delay(self): """Test start up delays creating a target, setting a breakpoint, and run to breakpoint stop.""" print() self.run_startup_delays_bench(self.exe, self.break_spec, self.count) - print( - "lldb startup delay (create fresh target) benchmark:", - self.stopwatch) - print( - "lldb startup delay (set first breakpoint) benchmark:", - self.stopwatch2) - print( - "lldb startup delay (run to breakpoint) benchmark:", - self.stopwatch3) + print("lldb startup delay (create fresh target) benchmark:", self.stopwatch) + print("lldb startup delay (set first breakpoint) benchmark:", self.stopwatch2) + print("lldb startup delay (run to breakpoint) benchmark:", self.stopwatch3) def run_startup_delays_bench(self, exe, break_spec, count): import pexpect + # Set self.child_prompt, which is "(lldb) ". - self.child_prompt = '(lldb) ' + self.child_prompt = "(lldb) " prompt = self.child_prompt # Reset the stopwatchs now. @@ -52,8 +47,8 @@ for i in range(count): # So that the child gets torn down after the test. self.child = pexpect.spawn( - '%s %s' % - (lldbtest_config.lldbExec, self.lldbOption)) + "%s %s" % (lldbtest_config.lldbExec, self.lldbOption) + ) child = self.child # Turn on logging for what the child sends back. @@ -62,20 +57,20 @@ with self.stopwatch: # Create a fresh target. - child.sendline('file %s' % exe) # Aka 'target create'. + child.sendline("file %s" % exe) # Aka 'target create'. child.expect_exact(prompt) with self.stopwatch2: # Read debug info and set the first breakpoint. - child.sendline('breakpoint set %s' % break_spec) + child.sendline("breakpoint set %s" % break_spec) child.expect_exact(prompt) with self.stopwatch3: # Run to the breakpoint just set. - child.sendline('run') + child.sendline("run") child.expect_exact(prompt) - child.sendline('quit') + child.sendline("quit") try: self.child.expect(pexpect.EOF) except: diff --git a/lldb/test/API/benchmarks/stepping/TestSteppingSpeed.py b/lldb/test/API/benchmarks/stepping/TestSteppingSpeed.py --- a/lldb/test/API/benchmarks/stepping/TestSteppingSpeed.py +++ b/lldb/test/API/benchmarks/stepping/TestSteppingSpeed.py @@ -11,11 +11,10 @@ class SteppingSpeedBench(BenchBase): - def setUp(self): BenchBase.setUp(self) self.exe = lldbtest_config.lldbExec - self.break_spec = '-n main' + self.break_spec = "-n main" self.count = 50 self.trace("self.exe=%s" % self.exe) @@ -25,7 +24,8 @@ @no_debug_info_test @expectedFailureAll( oslist=["windows"], - bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows", + ) def test_run_lldb_steppings(self): """Test lldb steppings on a large executable.""" print() @@ -34,14 +34,15 @@ def run_lldb_steppings(self, exe, break_spec, count): import pexpect + # Set self.child_prompt, which is "(lldb) ". - self.child_prompt = '(lldb) ' + self.child_prompt = "(lldb) " prompt = self.child_prompt # So that the child gets torn down after the test. self.child = pexpect.spawn( - '%s %s %s' % - (lldbtest_config.lldbExec, self.lldbOption, exe)) + "%s %s %s" % (lldbtest_config.lldbExec, self.lldbOption, exe) + ) child = self.child # Turn on logging for what the child sends back. @@ -49,9 +50,9 @@ child.logfile_read = sys.stdout child.expect_exact(prompt) - child.sendline('breakpoint set %s' % break_spec) + child.sendline("breakpoint set %s" % break_spec) child.expect_exact(prompt) - child.sendline('run') + child.sendline("run") child.expect_exact(prompt) # Reset the stopwatch now. @@ -59,10 +60,10 @@ for i in range(count): with self.stopwatch: # Disassemble the function. - child.sendline('next') # Aka 'thread step-over'. + child.sendline("next") # Aka 'thread step-over'. child.expect_exact(prompt) - child.sendline('quit') + child.sendline("quit") try: self.child.expect(pexpect.EOF) except: diff --git a/lldb/test/API/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py b/lldb/test/API/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py --- a/lldb/test/API/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py +++ b/lldb/test/API/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py @@ -10,11 +10,10 @@ class CompileRunToBreakpointBench(BenchBase): - def setUp(self): BenchBase.setUp(self) self.exe = lldbtest_config.lldbExec - self.function = 'Driver::MainLoop()' + self.function = "Driver::MainLoop()" self.count = 3 self.lldb_avg = None @@ -24,7 +23,8 @@ @no_debug_info_test @expectedFailureAll( oslist=["windows"], - bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows", + ) def test_run_lldb_then_gdb(self): """Benchmark turnaround time with lldb vs. gdb.""" print() @@ -42,8 +42,8 @@ # So that the child gets torn down after the test. self.child = pexpect.spawn( - '%s %s %s' % - (lldbtest_config.lldbExec, self.lldbOption, exe)) + "%s %s %s" % (lldbtest_config.lldbExec, self.lldbOption, exe) + ) child = self.child # Turn on logging for what the child sends back. @@ -51,13 +51,13 @@ child.logfile_read = sys.stdout child.expect_exact(prompt) - child.sendline('breakpoint set -F %s' % function) + child.sendline("breakpoint set -F %s" % function) child.expect_exact(prompt) - child.sendline('run') + child.sendline("run") child.expect_exact(prompt) # Set self.child_prompt, which is "(lldb) ". - self.child_prompt = '(lldb) ' + self.child_prompt = "(lldb) " # Reset the stopwatch now. self.stopwatch.reset() @@ -70,7 +70,7 @@ with self.stopwatch: run_one_round() - self.child.sendline('quit') + self.child.sendline("quit") try: self.child.expect(pexpect.EOF) except: @@ -86,7 +86,7 @@ prompt = self.child_prompt # So that the child gets torn down after the test. - self.child = pexpect.spawn('gdb --nx %s' % exe) + self.child = pexpect.spawn("gdb --nx %s" % exe) child = self.child # Turn on logging for what the child sends back. @@ -94,13 +94,13 @@ child.logfile_read = sys.stdout child.expect_exact(prompt) - child.sendline('break %s' % function) + child.sendline("break %s" % function) child.expect_exact(prompt) - child.sendline('run') + child.sendline("run") child.expect_exact(prompt) # Set self.child_prompt, which is "(gdb) ". - self.child_prompt = '(gdb) ' + self.child_prompt = "(gdb) " # Reset the stopwatch now. self.stopwatch.reset() @@ -113,9 +113,9 @@ with self.stopwatch: run_one_round() - self.child.sendline('quit') - self.child.expect_exact('The program is running. Exit anyway?') - self.child.sendline('y') + self.child.sendline("quit") + self.child.expect_exact("The program is running. Exit anyway?") + self.child.sendline("y") try: self.child.expect(pexpect.EOF) except: diff --git a/lldb/test/API/commands/add-dsym/uuid/TestAddDsymCommand.py b/lldb/test/API/commands/add-dsym/uuid/TestAddDsymCommand.py --- a/lldb/test/API/commands/add-dsym/uuid/TestAddDsymCommand.py +++ b/lldb/test/API/commands/add-dsym/uuid/TestAddDsymCommand.py @@ -1,7 +1,6 @@ """Test that the 'add-dsym', aka 'target symbols add', command informs the user about success or failure.""" - import os import time import lldb @@ -12,11 +11,10 @@ @skipUnlessDarwin class AddDsymCommandCase(TestBase): - def setUp(self): TestBase.setUp(self) - self.template = 'main.cpp.template' - self.source = 'main.cpp' + self.template = "main.cpp.template" + self.source = "main.cpp" self.teardown_hook_added = False @no_debug_info_test @@ -34,7 +32,7 @@ # Now call make again, but this time don't generate the dSYM. self.build(debug_info="dwarf") - self.exe_name = 'a.out' + self.exe_name = "a.out" self.do_add_dsym_with_error(self.exe_name) @no_debug_info_test @@ -45,7 +43,7 @@ self.generate_main_cpp(version=1) self.build(debug_info="dsym") - self.exe_name = 'a.out' + self.exe_name = "a.out" self.do_add_dsym_with_success(self.exe_name) @no_debug_info_test @@ -56,21 +54,20 @@ self.generate_main_cpp(version=1) self.build(debug_info="dsym") - self.exe_name = 'a.out' + self.exe_name = "a.out" self.do_add_dsym_with_dSYM_bundle(self.exe_name) def generate_main_cpp(self, version=0): """Generate main.cpp from main.cpp.template.""" temp = os.path.join(self.getSourceDir(), self.template) - with open(temp, 'r') as f: + with open(temp, "r") as f: content = f.read() new_content = content.replace( - '%ADD_EXTRA_CODE%', - 'printf("This is version %d\\n");' % - version) + "%ADD_EXTRA_CODE%", 'printf("This is version %d\\n");' % version + ) src = os.path.join(self.getBuildDir(), self.source) - with open(src, 'w') as f: + with open(src, "w") as f: f.write(new_content) # The main.cpp has been generated, add a teardown hook to remove it. @@ -83,21 +80,24 @@ exe_path = self.getBuildArtifact(exe_name) self.runCmd("file " + exe_path, CURRENT_EXECUTABLE_SET) - wrong_path = os.path.join(self.getBuildDir(), - "%s.dSYM" % exe_name, "Contents") - self.expect("add-dsym " + wrong_path, error=True, - substrs=['invalid module path']) + wrong_path = os.path.join(self.getBuildDir(), "%s.dSYM" % exe_name, "Contents") + self.expect( + "add-dsym " + wrong_path, error=True, substrs=["invalid module path"] + ) right_path = os.path.join( self.getBuildDir(), - "%s.dSYM" % - exe_path, + "%s.dSYM" % exe_path, "Contents", "Resources", "DWARF", - exe_name) - self.expect("add-dsym " + right_path, error=True, - substrs=['symbol file', 'does not match']) + exe_name, + ) + self.expect( + "add-dsym " + right_path, + error=True, + substrs=["symbol file", "does not match"], + ) def do_add_dsym_with_success(self, exe_name): """Test that the 'add-dsym' command informs the user about success.""" @@ -108,14 +108,15 @@ # lldb. right_path = os.path.join( self.getBuildDir(), - "%s.dSYM" % - exe_path, + "%s.dSYM" % exe_path, "Contents", "Resources", "DWARF", - exe_name) - self.expect("add-dsym " + right_path, - substrs=['symbol file', 'has been added to']) + exe_name, + ) + self.expect( + "add-dsym " + right_path, substrs=["symbol file", "has been added to"] + ) def do_add_dsym_with_dSYM_bundle(self, exe_name): """Test that the 'add-dsym' command informs the user about success when loading files in bundles.""" @@ -124,5 +125,6 @@ # This time, the UUID should be found inside the bundle right_path = "%s.dSYM" % exe_path - self.expect("add-dsym " + right_path, - substrs=['symbol file', 'has been added to']) + self.expect( + "add-dsym " + right_path, substrs=["symbol file", "has been added to"] + ) diff --git a/lldb/test/API/commands/apropos/basic/TestApropos.py b/lldb/test/API/commands/apropos/basic/TestApropos.py --- a/lldb/test/API/commands/apropos/basic/TestApropos.py +++ b/lldb/test/API/commands/apropos/basic/TestApropos.py @@ -2,23 +2,24 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * -class AproposTestCase(TestBase): +class AproposTestCase(TestBase): @no_debug_info_test def test_apropos(self): - self.expect("apropos", error=True, - substrs=[' must be called with exactly one argument']) - self.expect("apropos a b", error=True, - substrs=[' must be called with exactly one argument']) - self.expect("apropos ''", error=True, - substrs=['\'\' is not a valid search word']) + self.expect( + "apropos", error=True, substrs=[" must be called with exactly one argument"] + ) + self.expect( + "apropos a b", + error=True, + substrs=[" must be called with exactly one argument"], + ) + self.expect("apropos ''", error=True, substrs=["'' is not a valid search word"]) @no_debug_info_test def test_apropos_variable(self): """Test that 'apropos variable' prints the fully qualified command name""" self.expect( - 'apropos variable', - substrs=[ - 'frame variable', - 'target variable', - 'watchpoint set variable']) + "apropos variable", + substrs=["frame variable", "target variable", "watchpoint set variable"], + ) diff --git a/lldb/test/API/commands/apropos/with-process/TestAproposWithProcess.py b/lldb/test/API/commands/apropos/with-process/TestAproposWithProcess.py --- a/lldb/test/API/commands/apropos/with-process/TestAproposWithProcess.py +++ b/lldb/test/API/commands/apropos/with-process/TestAproposWithProcess.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil @@ -16,7 +15,7 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.line = line_number('main.cpp', '// break here') + self.line = line_number("main.cpp", "// break here") def test_apropos_with_process(self): """Test that apropos env doesn't crash trying to touch the process plugin command.""" @@ -26,15 +25,19 @@ # Break in main() after the variables are assigned values. lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # The breakpoint should have a hit count of 1. - lldbutil.check_breakpoint(self, bpno = 1, expected_hit_count = 1) + lldbutil.check_breakpoint(self, bpno=1, expected_hit_count=1) - self.runCmd('apropos env') + self.runCmd("apropos env") diff --git a/lldb/test/API/commands/breakpoint/command/list/TestBreakpointCommandList.py b/lldb/test/API/commands/breakpoint/command/list/TestBreakpointCommandList.py --- a/lldb/test/API/commands/breakpoint/command/list/TestBreakpointCommandList.py +++ b/lldb/test/API/commands/breakpoint/command/list/TestBreakpointCommandList.py @@ -6,8 +6,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @no_debug_info_test def test_list_commands(self): src_dir = self.getSourceDir() @@ -21,22 +21,36 @@ self.assertTrue(target, VALID_TARGET) # Test without any breakpoints. - self.expect("breakpoint command list 1", error=True, substrs=["error: No breakpoints exist for which to list commands"]) + self.expect( + "breakpoint command list 1", + error=True, + substrs=["error: No breakpoints exist for which to list commands"], + ) # Set a breakpoint self.runCmd("b foo") # Check list breakpoint commands for breakpoints that have no commands. - self.expect("breakpoint command list 1", startstr="Breakpoint 1 does not have an associated command.") + self.expect( + "breakpoint command list 1", + startstr="Breakpoint 1 does not have an associated command.", + ) # Add a breakpoint command. self.runCmd("breakpoint command add -o 'source list' 1") # List breakpoint command that we just created. - self.expect("breakpoint command list 1", startstr="""Breakpoint 1: + self.expect( + "breakpoint command list 1", + startstr="""Breakpoint 1: Breakpoint commands: source list -""") +""", + ) # List breakpoint command with invalid breakpoint ID. - self.expect("breakpoint command list 2", error=True, startstr="error: '2' is not a currently valid breakpoint ID.") + self.expect( + "breakpoint command list 2", + error=True, + startstr="error: '2' is not a currently valid breakpoint ID.", + ) diff --git a/lldb/test/API/commands/breakpoint/set/func-regex/TestBreakpointRegexError.py b/lldb/test/API/commands/breakpoint/set/func-regex/TestBreakpointRegexError.py --- a/lldb/test/API/commands/breakpoint/set/func-regex/TestBreakpointRegexError.py +++ b/lldb/test/API/commands/breakpoint/set/func-regex/TestBreakpointRegexError.py @@ -3,26 +3,49 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @no_debug_info_test def test_error(self): - self.expect("breakpoint set --func-regex (", error=True, - substrs=["error: Function name regular expression could " + - "not be compiled: parentheses not balanced"]) + self.expect( + "breakpoint set --func-regex (", + error=True, + substrs=[ + "error: Function name regular expression could " + + "not be compiled: parentheses not balanced" + ], + ) # Point out if looks like the user provided a globbing expression. - self.expect("breakpoint set --func-regex *a", error=True, - substrs=["error: Function name regular expression could " + - "not be compiled: repetition-operator operand invalid", - "warning: Function name regex does not accept glob patterns."]) - self.expect("breakpoint set --func-regex ?a", error=True, - substrs=["error: Function name regular expression could " + - "not be compiled: repetition-operator operand invalid", - "warning: Function name regex does not accept glob patterns."]) + self.expect( + "breakpoint set --func-regex *a", + error=True, + substrs=[ + "error: Function name regular expression could " + + "not be compiled: repetition-operator operand invalid", + "warning: Function name regex does not accept glob patterns.", + ], + ) + self.expect( + "breakpoint set --func-regex ?a", + error=True, + substrs=[ + "error: Function name regular expression could " + + "not be compiled: repetition-operator operand invalid", + "warning: Function name regex does not accept glob patterns.", + ], + ) # Make sure that warning is only shown for invalid regular expressions # that look like a globbing expression (i.e., they have a leading * or ?). - self.expect("breakpoint set --func-regex a*+", error=True, matching=False, - substrs=["warning: Function name regex does not accept glob patterns."]) - self.expect("breakpoint set --func-regex a?+", error=True, matching=False, - substrs=["warning: Function name regex does not accept glob patterns."]) + self.expect( + "breakpoint set --func-regex a*+", + error=True, + matching=False, + substrs=["warning: Function name regex does not accept glob patterns."], + ) + self.expect( + "breakpoint set --func-regex a?+", + error=True, + matching=False, + substrs=["warning: Function name regex does not accept glob patterns."], + ) diff --git a/lldb/test/API/commands/command/backticks/TestBackticksInAlias.py b/lldb/test/API/commands/command/backticks/TestBackticksInAlias.py --- a/lldb/test/API/commands/command/backticks/TestBackticksInAlias.py +++ b/lldb/test/API/commands/command/backticks/TestBackticksInAlias.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil @@ -15,29 +14,40 @@ def test_backticks_in_alias(self): """Test that an alias can contain active backticks.""" self.build() - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, "break here", lldb.SBFileSpec("main.c")) - interp = self.dbg.GetCommandInterpreter(); + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "break here", lldb.SBFileSpec("main.c") + ) + interp = self.dbg.GetCommandInterpreter() result = lldb.SBCommandReturnObject() - interp.HandleCommand('command alias _test-argv-cmd expression -Z \`argc\` -- argv', result) + interp.HandleCommand( + "command alias _test-argv-cmd expression -Z \`argc\` -- argv", result + ) self.assertCommandReturn(result, "Made the alias") interp.HandleCommand("_test-argv-cmd", result) self.assertCommandReturn(result, "The alias worked") # Now try a harder case where we create this using an alias: - interp.HandleCommand('command alias _test-argv-parray-cmd parray \`argc\` argv', result) + interp.HandleCommand( + "command alias _test-argv-parray-cmd parray \`argc\` argv", result + ) self.assertCommandReturn(result, "Made the alias") interp.HandleCommand("_test-argv-parray-cmd", result) - self.assertFalse(result.Succeeded(), "CommandAlias::Desugar currently fails if a alias substitutes %N arguments in another alias") + self.assertFalse( + result.Succeeded(), + "CommandAlias::Desugar currently fails if a alias substitutes %N arguments in another alias", + ) def test_backticks_in_parsed_cmd_argument(self): - """ break list is a parsed command, use a variable for the breakpoint number - and make sure that and the direct use of the ID get the same result. """ + """break list is a parsed command, use a variable for the breakpoint number + and make sure that and the direct use of the ID get the same result.""" self.build() - target, process, thread, bkpt = lldbutil.run_to_source_breakpoint(self, "break here", lldb.SBFileSpec("main.c")) + target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, "break here", lldb.SBFileSpec("main.c") + ) # Make a second breakpoint so that if the backtick part -> nothing we'll print too much: # It doesn't need to resolve to anything. dummy_bkpt = target.BreakpointCreateByName("dont_really_care_if_this_exists") - + bkpt_id = bkpt.GetID() self.runCmd(f"expr int $number = {bkpt_id}") direct_result = lldb.SBCommandReturnObject() @@ -47,27 +57,37 @@ self.assertTrue(direct_result.Succeeded(), "Break list with id works") interp.HandleCommand("break list `$number`", backtick_result) self.assertTrue(direct_result.Succeeded(), "Break list with backtick works") - self.assertEqual(direct_result.GetOutput(), backtick_result.GetOutput(), "Output is the same") + self.assertEqual( + direct_result.GetOutput(), backtick_result.GetOutput(), "Output is the same" + ) def test_backticks_in_parsed_cmd_option(self): # The script interpreter is a raw command, so try that one: self.build() - target, process, thread, bkpt = lldbutil.run_to_source_breakpoint(self, "break here", lldb.SBFileSpec("main.c")) + target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, "break here", lldb.SBFileSpec("main.c") + ) self.runCmd(f"expr int $number = 2") direct_result = lldb.SBCommandReturnObject() backtick_result = lldb.SBCommandReturnObject() interp = self.dbg.GetCommandInterpreter() interp.HandleCommand(f"memory read --count 2 argv", direct_result) - self.assertTrue(direct_result.Succeeded(), "memory read with direct count works") + self.assertTrue( + direct_result.Succeeded(), "memory read with direct count works" + ) interp.HandleCommand("memory read --count `$number` argv", backtick_result) self.assertTrue(direct_result.Succeeded(), "memory read with backtick works") - self.assertEqual(direct_result.GetOutput(), backtick_result.GetOutput(), "Output is the same") + self.assertEqual( + direct_result.GetOutput(), backtick_result.GetOutput(), "Output is the same" + ) def test_backticks_in_raw_cmd(self): # The script interpreter is a raw command, so try that one: self.build() - target, process, thread, bkpt = lldbutil.run_to_source_breakpoint(self, "break here", lldb.SBFileSpec("main.c")) + target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, "break here", lldb.SBFileSpec("main.c") + ) argc_valobj = thread.frames[0].FindVariable("argc") self.assertTrue(argc_valobj.GetError().Success(), "Made argc valobj") argc_value = argc_valobj.GetValueAsUnsigned(0) @@ -78,5 +98,3 @@ self.assertTrue(result.Succeeded(), "Command succeeded") fixed_output = result.GetOutput().rstrip() self.assertEqual("0", fixed_output, "Substitution worked") - - diff --git a/lldb/test/API/commands/command/container/TestContainerCommands.py b/lldb/test/API/commands/command/container/TestContainerCommands.py --- a/lldb/test/API/commands/command/container/TestContainerCommands.py +++ b/lldb/test/API/commands/command/container/TestContainerCommands.py @@ -20,121 +20,248 @@ self.runCmd("test-multi") self.runCmd("test-multi test-multi-sub") self.runCmd("test-multi test-multi-sub welcome") - + def container_add(self): # Make sure we can't overwrite built-in commands: - self.expect("command container add process", "Can't replace builtin container command", - substrs=["can't replace builtin command"], error=True) - self.expect("command container add process non_such_subcommand", "Can't add to built-in subcommand", - substrs=["Path component: 'process' is not a user command"], error=True) - self.expect("command container add process launch", "Can't replace builtin subcommand", - substrs=["Path component: 'process' is not a user command"], error=True) + self.expect( + "command container add process", + "Can't replace builtin container command", + substrs=["can't replace builtin command"], + error=True, + ) + self.expect( + "command container add process non_such_subcommand", + "Can't add to built-in subcommand", + substrs=["Path component: 'process' is not a user command"], + error=True, + ) + self.expect( + "command container add process launch", + "Can't replace builtin subcommand", + substrs=["Path component: 'process' is not a user command"], + error=True, + ) # Now lets make a container command: self.runCmd("command container add -h 'A test container command' test-multi") # Make sure the help works: - self.expect("help test-multi", "Help works for top-level multi", - substrs=["A test container command"]) + self.expect( + "help test-multi", + "Help works for top-level multi", + substrs=["A test container command"], + ) # Add a subcommand: - self.runCmd("command container add -h 'A test container sub-command' test-multi test-multi-sub") + self.runCmd( + "command container add -h 'A test container sub-command' test-multi test-multi-sub" + ) # Make sure the help works: - self.expect("help test-multi", "Help shows sub-multi", - substrs=["A test container command", "test-multi-sub -- A test container sub-command"]) - self.expect("help test-multi test-multi-sub", "Help shows sub-multi", - substrs=["A test container sub-command"]) + self.expect( + "help test-multi", + "Help shows sub-multi", + substrs=[ + "A test container command", + "test-multi-sub -- A test container sub-command", + ], + ) + self.expect( + "help test-multi test-multi-sub", + "Help shows sub-multi", + substrs=["A test container sub-command"], + ) # Now add a script based command to the container command: self.runCmd("command script import welcome.py") - self.runCmd("command script add -c welcome.WelcomeCommand test-multi test-multi-sub welcome") + self.runCmd( + "command script add -c welcome.WelcomeCommand test-multi test-multi-sub welcome" + ) # Make sure the help still works: - self.expect("help test-multi test-multi-sub", "Listing subcommands works", - substrs=["A test container sub-command", "welcome -- Just a docstring for Welcome"]) - self.expect("help test-multi test-multi-sub welcome", "Subcommand help works", - substrs=["Just a docstring for Welcome"]) + self.expect( + "help test-multi test-multi-sub", + "Listing subcommands works", + substrs=[ + "A test container sub-command", + "welcome -- Just a docstring for Welcome", + ], + ) + self.expect( + "help test-multi test-multi-sub welcome", + "Subcommand help works", + substrs=["Just a docstring for Welcome"], + ) # And make sure it actually works: - self.expect("test-multi test-multi-sub welcome friend", "Test command works", - substrs=["Hello friend, welcome to LLDB"]) + self.expect( + "test-multi test-multi-sub welcome friend", + "Test command works", + substrs=["Hello friend, welcome to LLDB"], + ) # Make sure we can make an alias to this: - self.runCmd("command alias my-welcome test-multi test-multi-sub welcome", "We can make an alias to multi-word") - self.expect("my-welcome friend", "Test command works", - substrs=["Hello friend, welcome to LLDB"]) + self.runCmd( + "command alias my-welcome test-multi test-multi-sub welcome", + "We can make an alias to multi-word", + ) + self.expect( + "my-welcome friend", + "Test command works", + substrs=["Hello friend, welcome to LLDB"], + ) self.runCmd("command unalias my-welcome") - + # Make sure overwriting works on the leaf command. First using the # explicit option so we should not be able to remove extant commands by default: - self.expect("command script add -c welcome.WelcomeCommand2 test-multi test-multi-sub welcome", - "overwrite command w/o -o", - substrs=["cannot add command: sub-command already exists"], error=True) + self.expect( + "command script add -c welcome.WelcomeCommand2 test-multi test-multi-sub welcome", + "overwrite command w/o -o", + substrs=["cannot add command: sub-command already exists"], + error=True, + ) # But we can with the -o option: - self.runCmd("command script add -c welcome.WelcomeCommand2 -o test-multi test-multi-sub welcome") + self.runCmd( + "command script add -c welcome.WelcomeCommand2 -o test-multi test-multi-sub welcome" + ) # Make sure we really did overwrite: - self.expect("test-multi test-multi-sub welcome friend", "Used the new command class", - substrs=["Hello friend, welcome again to LLDB"]) - self.expect("apropos welcome", "welcome should show up in apropos", substrs=["A docstring for the second Welcome"]) - self.expect("help test-multi test-multi-sub welcome", "welcome should show up in help", substrs=["A docstring for the second Welcome"]) + self.expect( + "test-multi test-multi-sub welcome friend", + "Used the new command class", + substrs=["Hello friend, welcome again to LLDB"], + ) + self.expect( + "apropos welcome", + "welcome should show up in apropos", + substrs=["A docstring for the second Welcome"], + ) + self.expect( + "help test-multi test-multi-sub welcome", + "welcome should show up in help", + substrs=["A docstring for the second Welcome"], + ) self.expect("help", "test-multi should show up in help", substrs=["test-multi"]) - + # Now switch the default and make sure we can now delete w/o the overwrite option: self.runCmd("settings set interpreter.require-overwrite 0") - self.runCmd("command script add -c welcome.WelcomeCommand test-multi test-multi-sub welcome") + self.runCmd( + "command script add -c welcome.WelcomeCommand test-multi test-multi-sub welcome" + ) # Make sure we really did overwrite: - self.expect("test-multi test-multi-sub welcome friend", "Used the new command class", - substrs=["Hello friend, welcome to LLDB"]) - + self.expect( + "test-multi test-multi-sub welcome friend", + "Used the new command class", + substrs=["Hello friend, welcome to LLDB"], + ) + # Make sure we give good errors when the input is wrong: - self.expect("command script delete test-mult test-multi-sub welcome", "Delete script command - wrong first path component", - substrs=["'test-mult' not found"], error=True) - - self.expect("command script delete test-multi test-multi-su welcome", "Delete script command - wrong second path component", - substrs=["'test-multi-su' not found"], error=True) + self.expect( + "command script delete test-mult test-multi-sub welcome", + "Delete script command - wrong first path component", + substrs=["'test-mult' not found"], + error=True, + ) + + self.expect( + "command script delete test-multi test-multi-su welcome", + "Delete script command - wrong second path component", + substrs=["'test-multi-su' not found"], + error=True, + ) self.check_command_tree_exists() - - self.expect("command script delete test-multi test-multi-sub welcom", "Delete script command - wrong leaf component", - substrs=["'welcom' not found"], error=True) + + self.expect( + "command script delete test-multi test-multi-sub welcom", + "Delete script command - wrong leaf component", + substrs=["'welcom' not found"], + error=True, + ) self.check_command_tree_exists() - - self.expect("command script delete test-multi test-multi-sub", "Delete script command - no leaf component", - substrs=["subcommand 'test-multi-sub' is not a user command"], error=True) + + self.expect( + "command script delete test-multi test-multi-sub", + "Delete script command - no leaf component", + substrs=["subcommand 'test-multi-sub' is not a user command"], + error=True, + ) self.check_command_tree_exists() # You can't use command script delete to delete container commands: - self.expect("command script delete test-multi", "Delete script - can't delete container", - substrs=["command 'test-multi' is a multi-word command."], error=True) - self.expect("command script delete test-multi test-multi-sub", "Delete script - can't delete container", - substrs=["subcommand 'test-multi-sub' is not a user command"], error = True) + self.expect( + "command script delete test-multi", + "Delete script - can't delete container", + substrs=["command 'test-multi' is a multi-word command."], + error=True, + ) + self.expect( + "command script delete test-multi test-multi-sub", + "Delete script - can't delete container", + substrs=["subcommand 'test-multi-sub' is not a user command"], + error=True, + ) # You can't use command container delete to delete scripted commands: - self.expect("command container delete test-multi test-multi-sub welcome", "command container can't delete user commands", - substrs=["subcommand 'welcome' is not a container command"], error = True) - + self.expect( + "command container delete test-multi test-multi-sub welcome", + "command container can't delete user commands", + substrs=["subcommand 'welcome' is not a container command"], + error=True, + ) + # Also make sure you can't alias on top of container commands: - self.expect("command alias test-multi process launch", "Tried to alias on top of a container command", - substrs=["'test-multi' is a user container command and cannot be overwritten."], error=True) + self.expect( + "command alias test-multi process launch", + "Tried to alias on top of a container command", + substrs=[ + "'test-multi' is a user container command and cannot be overwritten." + ], + error=True, + ) self.check_command_tree_exists() # Also assert that we can't delete builtin commands: - self.expect("command script delete process launch", "Delete builtin command fails", substrs=["command 'process' is not a user command"], error=True) + self.expect( + "command script delete process launch", + "Delete builtin command fails", + substrs=["command 'process' is not a user command"], + error=True, + ) # Now let's do the version that works - self.expect("command script delete test-multi test-multi-sub welcome", "Delete script command by path", substrs=["Deleted command: test-multi test-multi-sub welcome"]) + self.expect( + "command script delete test-multi test-multi-sub welcome", + "Delete script command by path", + substrs=["Deleted command: test-multi test-multi-sub welcome"], + ) # Now overwrite the sub-command, it should end up empty: - self.runCmd("command container add -h 'A different help string' -o test-multi test-multi-sub") + self.runCmd( + "command container add -h 'A different help string' -o test-multi test-multi-sub" + ) # welcome should be gone: - self.expect("test-multi test-multi-sub welcome friend", "did remove subcommand", - substrs=["'test-multi-sub' does not have any subcommands."], error=True) + self.expect( + "test-multi test-multi-sub welcome friend", + "did remove subcommand", + substrs=["'test-multi-sub' does not have any subcommands."], + error=True, + ) # We should have the new help: - self.expect("help test-multi test-multi-sub", "help changed", - substrs=["A different help string"]) + self.expect( + "help test-multi test-multi-sub", + "help changed", + substrs=["A different help string"], + ) # Now try deleting commands. self.runCmd("command container delete test-multi test-multi-sub") - self.expect("test-multi test-multi-sub", "Command is not active", error=True, - substrs = ["'test-multi' does not have any subcommands"]) + self.expect( + "test-multi test-multi-sub", + "Command is not active", + error=True, + substrs=["'test-multi' does not have any subcommands"], + ) self.expect("help test-multi", matching=False, substrs=["test-multi-sub"]) - # Next the root command: self.runCmd("command container delete test-multi") - self.expect("test-multi", "Root command gone", substrs=["'test-multi' is not a valid command."], error=True) + self.expect( + "test-multi", + "Root command gone", + substrs=["'test-multi' is not a valid command."], + error=True, + ) diff --git a/lldb/test/API/commands/command/container/welcome.py b/lldb/test/API/commands/command/container/welcome.py --- a/lldb/test/API/commands/command/container/welcome.py +++ b/lldb/test/API/commands/command/container/welcome.py @@ -3,7 +3,6 @@ class WelcomeCommand(object): - def __init__(self, debugger, session_dict): pass @@ -11,11 +10,11 @@ return "Just a docstring for Welcome\nA command that says hello to LLDB users" def __call__(self, debugger, args, exe_ctx, result): - print('Hello ' + args + ', welcome to LLDB', file=result) + print("Hello " + args + ", welcome to LLDB", file=result) return None -class WelcomeCommand2(object): +class WelcomeCommand2(object): def __init__(self, debugger, session_dict): pass @@ -23,5 +22,5 @@ return "A docstring for the second Welcome\nA command that says hello to LLDB users" def __call__(self, debugger, args, exe_ctx, result): - print('Hello ' + args + ', welcome again to LLDB', file=result) + print("Hello " + args + ", welcome again to LLDB", file=result) return None diff --git a/lldb/test/API/commands/command/delete/TestCommandDelete.py b/lldb/test/API/commands/command/delete/TestCommandDelete.py --- a/lldb/test/API/commands/command/delete/TestCommandDelete.py +++ b/lldb/test/API/commands/command/delete/TestCommandDelete.py @@ -2,14 +2,20 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * -class DeleteCommandTestCase(TestBase): +class DeleteCommandTestCase(TestBase): @no_debug_info_test def test_delete_builtin(self): - self.expect("command delete settings", error=True, - substrs=["'settings' is a permanent debugger command and cannot be removed."]) + self.expect( + "command delete settings", + error=True, + substrs=[ + "'settings' is a permanent debugger command and cannot be removed." + ], + ) @no_debug_info_test def test_delete_alias(self): - self.expect("command delete bt", error=True, - substrs=["'bt' is not a known command."]) + self.expect( + "command delete bt", error=True, substrs=["'bt' is not a known command."] + ) diff --git a/lldb/test/API/commands/command/invalid-args/TestInvalidArgsCommand.py b/lldb/test/API/commands/command/invalid-args/TestInvalidArgsCommand.py --- a/lldb/test/API/commands/command/invalid-args/TestInvalidArgsCommand.py +++ b/lldb/test/API/commands/command/invalid-args/TestInvalidArgsCommand.py @@ -2,55 +2,92 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * -class InvalidArgsCommandTestCase(TestBase): +class InvalidArgsCommandTestCase(TestBase): @no_debug_info_test def test_script_add(self): - self.expect("command script add 1 2", error=True, - substrs=["Path component: '1' not found"]) + self.expect( + "command script add 1 2", + error=True, + substrs=["Path component: '1' not found"], + ) - self.expect("command script add", error=True, - substrs=["'command script add' requires at least one argument"]) + self.expect( + "command script add", + error=True, + substrs=["'command script add' requires at least one argument"], + ) @no_debug_info_test def test_script_clear(self): - self.expect("command script clear f", error=True, - substrs=["'command script clear' doesn't take any arguments"]) + self.expect( + "command script clear f", + error=True, + substrs=["'command script clear' doesn't take any arguments"], + ) @no_debug_info_test def test_script_list(self): - self.expect("command script list f", error=True, - substrs=["'command script list' doesn't take any arguments"]) + self.expect( + "command script list f", + error=True, + substrs=["'command script list' doesn't take any arguments"], + ) @no_debug_info_test def test_script_import(self): - self.expect("command script import", error=True, - substrs=["command script import needs one or more arguments"]) + self.expect( + "command script import", + error=True, + substrs=["command script import needs one or more arguments"], + ) @no_debug_info_test def test_alias(self): - self.expect("command alias", error=True, - substrs=["'command alias' requires at least two arguments"]) + self.expect( + "command alias", + error=True, + substrs=["'command alias' requires at least two arguments"], + ) - self.expect("command alias blub foo", error=True, - substrs=["error: invalid command given to 'command alias'. 'foo' does not begin with a valid command. No alias created."]) + self.expect( + "command alias blub foo", + error=True, + substrs=[ + "error: invalid command given to 'command alias'. 'foo' does not begin with a valid command. No alias created." + ], + ) @no_debug_info_test def test_unalias(self): - self.expect("command unalias", error=True, - substrs=["must call 'unalias' with a valid alias"]) + self.expect( + "command unalias", + error=True, + substrs=["must call 'unalias' with a valid alias"], + ) @no_debug_info_test def test_delete(self): - self.expect("command delete", error=True, - substrs=["must call 'command delete' with one or more valid user"]) + self.expect( + "command delete", + error=True, + substrs=["must call 'command delete' with one or more valid user"], + ) @no_debug_info_test def test_regex(self): - self.expect("command regex", error=True, - substrs=["usage: 'command regex "]) + self.expect( + "command regex", + error=True, + substrs=["usage: 'command regex "], + ) @no_debug_info_test def test_source(self): - self.expect("command source", error=True, - substrs=["'command source' takes exactly one executable filename argument."]) + self.expect( + "command source", + error=True, + substrs=[ + "'command source' takes exactly one executable filename argument." + ], + ) diff --git a/lldb/test/API/commands/command/nested_alias/TestNestedAlias.py b/lldb/test/API/commands/command/nested_alias/TestNestedAlias.py --- a/lldb/test/API/commands/command/nested_alias/TestNestedAlias.py +++ b/lldb/test/API/commands/command/nested_alias/TestNestedAlias.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil @@ -16,7 +15,7 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.line = line_number('main.cpp', '// break here') + self.line = line_number("main.cpp", "// break here") def test_nested_alias(self): """Test that an alias can reference other aliases without crashing.""" @@ -26,82 +25,75 @@ # Break in main() after the variables are assigned values. lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # The breakpoint should have a hit count of 1. - lldbutil.check_breakpoint(self, bpno = 1, expected_hit_count = 1) + lldbutil.check_breakpoint(self, bpno=1, expected_hit_count=1) # This is the function to remove the custom aliases in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('command unalias read', check=False) - self.runCmd('command unalias rd', check=False) - self.runCmd('command unalias fo', check=False) - self.runCmd('command unalias foself', check=False) - self.runCmd('command unalias add_two', check=False) - self.runCmd('command unalias two', check=False) + self.runCmd("command unalias read", check=False) + self.runCmd("command unalias rd", check=False) + self.runCmd("command unalias fo", check=False) + self.runCmd("command unalias foself", check=False) + self.runCmd("command unalias add_two", check=False) + self.runCmd("command unalias two", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.runCmd('command alias read memory read -f A') - self.runCmd('command alias rd read -c 3') + self.runCmd("command alias read memory read -f A") + self.runCmd("command alias rd read -c 3") self.expect( - 'memory read -f A -c 3 `&my_ptr[0]`', - substrs=[ - 'deadbeef', - 'main.cpp:', - 'feedbeef']) - self.expect( - 'rd `&my_ptr[0]`', - substrs=[ - 'deadbeef', - 'main.cpp:', - 'feedbeef']) + "memory read -f A -c 3 `&my_ptr[0]`", + substrs=["deadbeef", "main.cpp:", "feedbeef"], + ) + self.expect("rd `&my_ptr[0]`", substrs=["deadbeef", "main.cpp:", "feedbeef"]) self.expect( - 'memory read -f A -c 3 `&my_ptr[0]`', - substrs=['deadfeed'], - matching=False) - self.expect('rd `&my_ptr[0]`', substrs=['deadfeed'], matching=False) + "memory read -f A -c 3 `&my_ptr[0]`", substrs=["deadfeed"], matching=False + ) + self.expect("rd `&my_ptr[0]`", substrs=["deadfeed"], matching=False) - self.runCmd('command alias fo frame variable -O --') - self.runCmd('command alias foself fo self') + self.runCmd("command alias fo frame variable -O --") + self.runCmd("command alias foself fo self") self.expect( - 'help foself', - substrs=[ - '--show-all-children', - '--raw-output'], - matching=False) + "help foself", + substrs=["--show-all-children", "--raw-output"], + matching=False, + ) self.expect( - 'help foself', - substrs=[ - 'Show variables for the current', - 'stack frame.'], - matching=True) + "help foself", + substrs=["Show variables for the current", "stack frame."], + matching=True, + ) # Check that foself was resolved and is now independent of 'fo'. - self.runCmd('command unalias fo') + self.runCmd("command unalias fo") self.expect( - 'help foself', - substrs=[ - 'Show variables for the current', - 'stack frame.'], - matching=True) + "help foself", + substrs=["Show variables for the current", "stack frame."], + matching=True, + ) # Check that aliases can be created for raw input commands. - self.expect('command alias two expr -- 2') - self.expect('command alias add_two two +') - self.expect('add_two 3', patterns=[' = 5$']) + self.expect("command alias two expr -- 2") + self.expect("command alias add_two two +") + self.expect("add_two 3", patterns=[" = 5$"]) # Check that aliases to aliases to raw input commands work the second # and subsequent times. - self.expect('add_two 3', patterns=[' = 5$']) - self.expect('add_two 3', patterns=[' = 5$']) + self.expect("add_two 3", patterns=[" = 5$"]) + self.expect("add_two 3", patterns=[" = 5$"]) diff --git a/lldb/test/API/commands/command/regex/TestRegexCommand.py b/lldb/test/API/commands/command/regex/TestRegexCommand.py --- a/lldb/test/API/commands/command/regex/TestRegexCommand.py +++ b/lldb/test/API/commands/command/regex/TestRegexCommand.py @@ -9,21 +9,36 @@ class TestCommandRegexParsing(TestBase): - NO_DEBUG_INFO_TESTCASE = True def test_sample_rename_this(self): """Try out some simple regex commands, make sure they parse correctly.""" - self.runCmd("command regex one-substitution 's/(.+)/echo-cmd %1-first %1-second %1-third/'") - self.expect("one-substitution ASTRING", - substrs = ["ASTRING-first", "ASTRING-second", "ASTRING-third"]) + self.runCmd( + "command regex one-substitution 's/(.+)/echo-cmd %1-first %1-second %1-third/'" + ) + self.expect( + "one-substitution ASTRING", + substrs=["ASTRING-first", "ASTRING-second", "ASTRING-third"], + ) + + self.runCmd( + "command regex two-substitution 's/([^ ]+) ([^ ]+)/echo-cmd %1-first %2-second %1-third %2-fourth/'" + ) + self.expect( + "two-substitution ASTRING BSTRING", + substrs=[ + "ASTRING-first", + "BSTRING-second", + "ASTRING-third", + "BSTRING-fourth", + ], + ) - self.runCmd("command regex two-substitution 's/([^ ]+) ([^ ]+)/echo-cmd %1-first %2-second %1-third %2-fourth/'") - self.expect("two-substitution ASTRING BSTRING", - substrs = ["ASTRING-first", "BSTRING-second", "ASTRING-third", "BSTRING-fourth"]) - def setUp(self): # Call super's setUp(). TestBase.setUp(self) - self.runCmd("command script import " + os.path.join(self.getSourceDir(), "echo_command.py")) + self.runCmd( + "command script import " + + os.path.join(self.getSourceDir(), "echo_command.py") + ) self.runCmd("command script add echo-cmd -f echo_command.echo_command") diff --git a/lldb/test/API/commands/command/regex/echo_command.py b/lldb/test/API/commands/command/regex/echo_command.py --- a/lldb/test/API/commands/command/regex/echo_command.py +++ b/lldb/test/API/commands/command/regex/echo_command.py @@ -1,6 +1,7 @@ import lldb + def echo_command(debugger, args, result, dict): - result.Print(args+'\n') + result.Print(args + "\n") result.SetStatus(lldb.eReturnStatusSuccessFinishResult) return True diff --git a/lldb/test/API/commands/command/script/TestCommandScript.py b/lldb/test/API/commands/command/script/TestCommandScript.py --- a/lldb/test/API/commands/command/script/TestCommandScript.py +++ b/lldb/test/API/commands/command/script/TestCommandScript.py @@ -41,29 +41,26 @@ # Verify command that specifies eCommandRequiresTarget returns failure # without a target. - self.expect('targetname', - substrs=['a.out'], matching=False, error=True) + self.expect("targetname", substrs=["a.out"], matching=False, error=True) exe = self.getBuildArtifact("a.out") - self.expect("file " + exe, - patterns=["Current executable set to .*a.out"]) + self.expect("file " + exe, patterns=["Current executable set to .*a.out"]) - self.expect('targetname', - substrs=['a.out'], matching=True, error=False) + self.expect("targetname", substrs=["a.out"], matching=True, error=False) # This is the function to remove the custom commands in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('command script delete welcome', check=False) - self.runCmd('command script delete targetname', check=False) - self.runCmd('command script delete longwait', check=False) - self.runCmd('command script delete mysto', check=False) - self.runCmd('command script delete tell_sync', check=False) - self.runCmd('command script delete tell_async', check=False) - self.runCmd('command script delete tell_curr', check=False) - self.runCmd('command script delete bug11569', check=False) - self.runCmd('command script delete takes_exe_ctx', check=False) - self.runCmd('command script delete decorated', check=False) + self.runCmd("command script delete welcome", check=False) + self.runCmd("command script delete targetname", check=False) + self.runCmd("command script delete longwait", check=False) + self.runCmd("command script delete mysto", check=False) + self.runCmd("command script delete tell_sync", check=False) + self.runCmd("command script delete tell_async", check=False) + self.runCmd("command script delete tell_curr", check=False) + self.runCmd("command script delete bug11569", check=False) + self.runCmd("command script delete takes_exe_ctx", check=False) + self.runCmd("command script delete decorated", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -75,68 +72,79 @@ if not self.TraceOn(): self.HideStdout() - self.expect('welcome Enrico', - substrs=['Hello Enrico, welcome to LLDB']) + self.expect("welcome Enrico", substrs=["Hello Enrico, welcome to LLDB"]) - self.expect("help welcome", - substrs=['Just a docstring for welcome_impl', - 'A command that says hello to LLDB users']) + self.expect( + "help welcome", + substrs=[ + "Just a docstring for welcome_impl", + "A command that says hello to LLDB users", + ], + ) decorated_commands = ["decorated" + str(n) for n in range(1, 5)] for name in decorated_commands: self.expect(name, substrs=["hello from " + name]) - self.expect("help " + name, - substrs=["Python command defined by @lldb.command"]) + self.expect( + "help " + name, substrs=["Python command defined by @lldb.command"] + ) - self.expect("help", - substrs=['For more information run'] - + decorated_commands + ['welcome']) + self.expect( + "help", + substrs=["For more information run"] + decorated_commands + ["welcome"], + ) - self.expect("help -a", - substrs=['For more information run'] - + decorated_commands + ['welcome']) + self.expect( + "help -a", + substrs=["For more information run"] + decorated_commands + ["welcome"], + ) - self.expect("help -u", matching=False, - substrs=['For more information run']) + self.expect("help -u", matching=False, substrs=["For more information run"]) self.runCmd("command script delete welcome") - self.expect('welcome Enrico', matching=False, error=True, - substrs=['Hello Enrico, welcome to LLDB']) + self.expect( + "welcome Enrico", + matching=False, + error=True, + substrs=["Hello Enrico, welcome to LLDB"], + ) - self.expect('targetname fail', error=True, - substrs=['a test for error in command']) + self.expect( + "targetname fail", error=True, substrs=["a test for error in command"] + ) - self.expect('command script list', - substrs=['targetname', - 'For more information run']) + self.expect( + "command script list", substrs=["targetname", "For more information run"] + ) - self.expect("help targetname", - substrs=['Expects', '\'raw\'', 'input', - 'help', 'raw-input']) + self.expect( + "help targetname", + substrs=["Expects", "'raw'", "input", "help", "raw-input"], + ) - self.expect("longwait", - substrs=['Done; if you saw the delays I am doing OK']) + self.expect("longwait", substrs=["Done; if you saw the delays I am doing OK"]) self.runCmd("break set -f main.cpp -l 48") self.runCmd("run") self.runCmd("mysto 3") - self.expect("frame variable array", - substrs=['[0] = 79630', '[1] = 388785018', '[2] = 0']) + self.expect( + "frame variable array", + substrs=["[0] = 79630", "[1] = 388785018", "[2] = 0"], + ) self.runCmd("mysto 3") - self.expect("frame variable array", - substrs=['[0] = 79630', '[4] = 388785018', '[5] = 0']) - -# we cannot use the stepover command to check for async execution mode since LLDB -# seems to get confused when events start to queue up - self.expect("tell_sync", - substrs=['running sync']) - self.expect("tell_async", - substrs=['running async']) - self.expect("tell_curr", - substrs=['I am running sync']) - -# check that the execution context is passed in to commands that ask for it + self.expect( + "frame variable array", + substrs=["[0] = 79630", "[4] = 388785018", "[5] = 0"], + ) + + # we cannot use the stepover command to check for async execution mode since LLDB + # seems to get confused when events start to queue up + self.expect("tell_sync", substrs=["running sync"]) + self.expect("tell_async", substrs=["running async"]) + self.expect("tell_curr", substrs=["I am running sync"]) + + # check that the execution context is passed in to commands that ask for it self.expect("takes_exe_ctx", substrs=["a.out"]) # Test that a python command can redefine itself @@ -145,33 +153,40 @@ self.runCmd("command script clear") # Test that re-defining an existing command works - self.runCmd( - 'command script add my_command --class welcome.WelcomeCommand') - self.expect('my_command Blah', substrs=['Hello Blah, welcome to LLDB']) + self.runCmd("command script add my_command --class welcome.WelcomeCommand") + self.expect("my_command Blah", substrs=["Hello Blah, welcome to LLDB"]) self.runCmd( - 'command script add my_command -o --class welcome.TargetnameCommand') - self.expect('my_command', substrs=['a.out']) + "command script add my_command -o --class welcome.TargetnameCommand" + ) + self.expect("my_command", substrs=["a.out"]) self.runCmd("command script clear") - self.expect('command script list', matching=False, - substrs=['targetname', - 'longwait']) + self.expect( + "command script list", matching=False, substrs=["targetname", "longwait"] + ) - self.expect('command script add -f foobar frame', error=True, - substrs=['cannot add command']) + self.expect( + "command script add -f foobar frame", + error=True, + substrs=["cannot add command"], + ) # http://llvm.org/bugs/show_bug.cgi?id=11569 # LLDBSwigPythonCallCommand crashes when a command script returns an # object - self.runCmd('command script add -f bug11569 bug11569') + self.runCmd("command script add -f bug11569 bug11569") # This should not crash. - self.runCmd('bug11569', check=False) + self.runCmd("bug11569", check=False) # Make sure that a reference to a non-existent class raises an error: bad_class_name = "LLDBNoSuchModule.LLDBNoSuchClass" - self.expect("command script add wont-work --class {0}".format(bad_class_name), error=True, substrs = [bad_class_name]) + self.expect( + "command script add wont-work --class {0}".format(bad_class_name), + error=True, + substrs=[bad_class_name], + ) def test_persistence(self): """ diff --git a/lldb/test/API/commands/command/script/callables.py b/lldb/test/API/commands/command/script/callables.py --- a/lldb/test/API/commands/command/script/callables.py +++ b/lldb/test/API/commands/command/script/callables.py @@ -1,62 +1,69 @@ - - import lldb # bunch of different kinds of python callables that should # all work as commands. + def check(debugger, command, context, result, internal_dict): - if (not isinstance(debugger, lldb.SBDebugger) or - not isinstance(command, str) or - not isinstance(result, lldb.SBCommandReturnObject) or - not isinstance(internal_dict, dict) or - (not context is None and - not isinstance(context, lldb.SBExecutionContext))): - raise Exception() + if ( + not isinstance(debugger, lldb.SBDebugger) + or not isinstance(command, str) + or not isinstance(result, lldb.SBCommandReturnObject) + or not isinstance(internal_dict, dict) + or (not context is None and not isinstance(context, lldb.SBExecutionContext)) + ): + raise Exception() result.AppendMessage("All good.") + def vfoobar(*args): check(*args) + def v5foobar(debugger, command, context, result, internal_dict, *args): check(debugger, command, context, result, internal_dict) + def foobar(debugger, command, context, result, internal_dict): check(debugger, command, context, result, internal_dict) + def foobar4(debugger, command, result, internal_dict): check(debugger, command, None, result, internal_dict) + class FooBar: @staticmethod def sfoobar(debugger, command, context, result, internal_dict): - check(debugger, command, context, result, internal_dict) + check(debugger, command, context, result, internal_dict) @classmethod def cfoobar(cls, debugger, command, context, result, internal_dict): - check(debugger, command, context, result, internal_dict) + check(debugger, command, context, result, internal_dict) def ifoobar(self, debugger, command, context, result, internal_dict): - check(debugger, command, context, result, internal_dict) + check(debugger, command, context, result, internal_dict) def __call__(self, debugger, command, context, result, internal_dict): - check(debugger, command, context, result, internal_dict) + check(debugger, command, context, result, internal_dict) @staticmethod def sfoobar4(debugger, command, result, internal_dict): - check(debugger, command, None, result, internal_dict) + check(debugger, command, None, result, internal_dict) @classmethod def cfoobar4(cls, debugger, command, result, internal_dict): - check(debugger, command, None, result, internal_dict) + check(debugger, command, None, result, internal_dict) def ifoobar4(self, debugger, command, result, internal_dict): - check(debugger, command, None, result, internal_dict) + check(debugger, command, None, result, internal_dict) + class FooBar4: def __call__(self, debugger, command, result, internal_dict): - check(debugger, command, None, result, internal_dict) + check(debugger, command, None, result, internal_dict) + FooBarObj = FooBar() -FooBar4Obj = FooBar4() \ No newline at end of file +FooBar4Obj = FooBar4() diff --git a/lldb/test/API/commands/command/script/import/TestImport.py b/lldb/test/API/commands/command/script/import/TestImport.py --- a/lldb/test/API/commands/command/script/import/TestImport.py +++ b/lldb/test/API/commands/command/script/import/TestImport.py @@ -1,7 +1,6 @@ """Test custom import command to import files by path.""" - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -9,8 +8,7 @@ class ImportTestCase(TestBase): - - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) @no_debug_info_test def test_import_command(self): """Import some Python scripts by path and test them""" @@ -22,13 +20,13 @@ # This is the function to remove the custom commands in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('command script delete foo2cmd', check=False) - self.runCmd('command script delete foocmd', check=False) - self.runCmd('command script delete foobarcmd', check=False) - self.runCmd('command script delete barcmd', check=False) - self.runCmd('command script delete barothercmd', check=False) - self.runCmd('command script delete TPcommandA', check=False) - self.runCmd('command script delete TPcommandB', check=False) + self.runCmd("command script delete foo2cmd", check=False) + self.runCmd("command script delete foocmd", check=False) + self.runCmd("command script delete foobarcmd", check=False) + self.runCmd("command script delete barcmd", check=False) + self.runCmd("command script delete barothercmd", check=False) + self.runCmd("command script delete TPcommandA", check=False) + self.runCmd("command script delete TPcommandB", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -38,12 +36,21 @@ self.runCmd("command script import ./foo/bar/foobar.py --allow-reload") self.runCmd("command script import ./bar/bar.py --allow-reload") - self.expect("command script import ''", - error=True, startstr="error: module importing failed: empty path") - self.expect("command script import ./nosuchfile.py", - error=True, startstr="error: module importing failed: invalid pathname './nosuchfile.py'") - self.expect("command script import ./nosuchfolder/", - error=True, startstr="error: module importing failed: invalid pathname './nosuchfolder/'") + self.expect( + "command script import ''", + error=True, + startstr="error: module importing failed: empty path", + ) + self.expect( + "command script import ./nosuchfile.py", + error=True, + startstr="error: module importing failed: invalid pathname './nosuchfile.py'", + ) + self.expect( + "command script import ./nosuchfolder/", + error=True, + startstr="error: module importing failed: invalid pathname './nosuchfolder/'", + ) self.expect("command script import ./foo/foo.py", error=False) self.runCmd("command script import --allow-reload ./thepackage") self.expect("TPcommandA", substrs=["hello world A"]) @@ -52,19 +59,16 @@ self.runCmd("script import dummymodule") self.expect("command script import ./dummymodule.py", error=False) self.expect( - "command script import --allow-reload ./dummymodule.py", - error=False) + "command script import --allow-reload ./dummymodule.py", error=False + ) self.runCmd("command script add -f foo.foo_function foocmd") self.runCmd("command script add -f foobar.foo_function foobarcmd") self.runCmd("command script add -f bar.bar_function barcmd") - self.expect("foocmd hello", - substrs=['foo says', 'hello']) - self.expect("foo2cmd hello", - substrs=['foo2 says', 'hello']) - self.expect("barcmd hello", - substrs=['barutil says', 'bar told me', 'hello']) - self.expect("barothercmd hello", - substrs=['barutil says', 'bar told me', 'hello']) - self.expect("foobarcmd hello", - substrs=['foobar says', 'hello']) + self.expect("foocmd hello", substrs=["foo says", "hello"]) + self.expect("foo2cmd hello", substrs=["foo2 says", "hello"]) + self.expect("barcmd hello", substrs=["barutil says", "bar told me", "hello"]) + self.expect( + "barothercmd hello", substrs=["barutil says", "bar told me", "hello"] + ) + self.expect("foobarcmd hello", substrs=["foobar says", "hello"]) diff --git a/lldb/test/API/commands/command/script/import/bar/bar.py b/lldb/test/API/commands/command/script/import/bar/bar.py --- a/lldb/test/API/commands/command/script/import/bar/bar.py +++ b/lldb/test/API/commands/command/script/import/bar/bar.py @@ -7,6 +7,5 @@ def __lldb_init_module(debugger, session_dict): global UtilityModule UtilityModule = __import__("barutil") - debugger.HandleCommand( - "command script add -f bar.bar_function barothercmd") + debugger.HandleCommand("command script add -f bar.bar_function barothercmd") return None diff --git a/lldb/test/API/commands/command/script/import/rdar-12586188/TestRdar12586188.py b/lldb/test/API/commands/command/script/import/rdar-12586188/TestRdar12586188.py --- a/lldb/test/API/commands/command/script/import/rdar-12586188/TestRdar12586188.py +++ b/lldb/test/API/commands/command/script/import/rdar-12586188/TestRdar12586188.py @@ -1,7 +1,6 @@ """Check that we handle an ImportError in a special way when command script importing files.""" - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -9,8 +8,7 @@ class Rdar12586188TestCase(TestBase): - - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) @no_debug_info_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" @@ -22,8 +20,10 @@ self.expect( "command script import ./fail12586188.py --allow-reload", error=True, - substrs=['raise ImportError("I do not want to be imported")']) + substrs=['raise ImportError("I do not want to be imported")'], + ) self.expect( "command script import ./fail212586188.py --allow-reload", error=True, - substrs=['raise ValueError("I do not want to be imported")']) + substrs=['raise ValueError("I do not want to be imported")'], + ) diff --git a/lldb/test/API/commands/command/script/import/rdar-12586188/fail12586188.py b/lldb/test/API/commands/command/script/import/rdar-12586188/fail12586188.py --- a/lldb/test/API/commands/command/script/import/rdar-12586188/fail12586188.py +++ b/lldb/test/API/commands/command/script/import/rdar-12586188/fail12586188.py @@ -1,4 +1,5 @@ def f(x): return x + 1 + raise ImportError("I do not want to be imported") diff --git a/lldb/test/API/commands/command/script/import/rdar-12586188/fail212586188.py b/lldb/test/API/commands/command/script/import/rdar-12586188/fail212586188.py --- a/lldb/test/API/commands/command/script/import/rdar-12586188/fail212586188.py +++ b/lldb/test/API/commands/command/script/import/rdar-12586188/fail212586188.py @@ -1,4 +1,5 @@ def f(x): return x + 1 + raise ValueError("I do not want to be imported") diff --git a/lldb/test/API/commands/command/script/import/thepackage/__init__.py b/lldb/test/API/commands/command/script/import/thepackage/__init__.py --- a/lldb/test/API/commands/command/script/import/thepackage/__init__.py +++ b/lldb/test/API/commands/command/script/import/thepackage/__init__.py @@ -4,6 +4,8 @@ def __lldb_init_module(debugger, *args): debugger.HandleCommand( - "command script add -f thepackage.TPunitA.command TPcommandA") + "command script add -f thepackage.TPunitA.command TPcommandA" + ) debugger.HandleCommand( - "command script add -f thepackage.TPunitB.command TPcommandB") + "command script add -f thepackage.TPunitB.command TPcommandB" + ) diff --git a/lldb/test/API/commands/command/script/mysto.py b/lldb/test/API/commands/command/script/mysto.py --- a/lldb/test/API/commands/command/script/mysto.py +++ b/lldb/test/API/commands/command/script/mysto.py @@ -9,8 +9,9 @@ print(type(arg_split)) count = int(arg_split[0]) for i in range(0, count): - debugger.GetSelectedTarget().GetProcess( - ).GetSelectedThread().StepOver(lldb.eOnlyThisThread) + debugger.GetSelectedTarget().GetProcess().GetSelectedThread().StepOver( + lldb.eOnlyThisThread + ) print("step<%d>" % i) diff --git a/lldb/test/API/commands/command/script/persistence.py b/lldb/test/API/commands/command/script/persistence.py --- a/lldb/test/API/commands/command/script/persistence.py +++ b/lldb/test/API/commands/command/script/persistence.py @@ -3,6 +3,7 @@ debugger_copy = None result_copy = None + def save_debugger(debugger, command, context, result, internal_dict): global debugger_copy, result_copy debugger_copy = debugger diff --git a/lldb/test/API/commands/command/script/welcome.py b/lldb/test/API/commands/command/script/welcome.py --- a/lldb/test/API/commands/command/script/welcome.py +++ b/lldb/test/API/commands/command/script/welcome.py @@ -3,29 +3,29 @@ class WelcomeCommand(object): - def __init__(self, debugger, session_dict): pass def get_short_help(self): - return "Just a docstring for welcome_impl\nA command that says hello to LLDB users" + return ( + "Just a docstring for welcome_impl\nA command that says hello to LLDB users" + ) def __call__(self, debugger, args, exe_ctx, result): - print('Hello ' + args + ', welcome to LLDB', file=result) + print("Hello " + args + ", welcome to LLDB", file=result) return None class TargetnameCommand(object): - def __init__(self, debugger, session_dict): pass def __call__(self, debugger, args, exe_ctx, result): target = debugger.GetSelectedTarget() file = target.GetExecutable() - print('Current target ' + file.GetFilename(), file=result) - if args == 'fail': - result.SetError('a test for error in command') + print("Current target " + file.GetFilename(), file=result) + if args == "fail": + result.SetError("a test for error in command") def get_flags(self): return lldb.eCommandRequiresTarget @@ -33,19 +33,20 @@ def print_wait_impl(debugger, args, result, dict): result.SetImmediateOutputFile(sys.stdout) - print('Trying to do long task..', file=result) + print("Trying to do long task..", file=result) import time + time.sleep(1) - print('Still doing long task..', file=result) + print("Still doing long task..", file=result) time.sleep(1) - print('Done; if you saw the delays I am doing OK', file=result) + print("Done; if you saw the delays I am doing OK", file=result) def check_for_synchro(debugger, args, result, dict): if debugger.GetAsync(): - print('I am running async', file=result) + print("I am running async", file=result) if debugger.GetAsync() == False: - print('I am running sync', file=result) + print("I am running sync", file=result) def takes_exe_ctx(debugger, args, exe_ctx, result, dict): diff --git a/lldb/test/API/commands/command/script_alias/TestCommandScriptAlias.py b/lldb/test/API/commands/command/script_alias/TestCommandScriptAlias.py --- a/lldb/test/API/commands/command/script_alias/TestCommandScriptAlias.py +++ b/lldb/test/API/commands/command/script_alias/TestCommandScriptAlias.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.lldbtest import * @@ -18,7 +17,7 @@ # This is the function to remove the custom commands in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('command script delete attach', check=False) + self.runCmd("command script delete attach", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -27,7 +26,7 @@ if not self.TraceOn(): self.HideStdout() - self.expect('attach a', substrs=['Victory is mine']) + self.expect("attach a", substrs=["Victory is mine"]) self.runCmd("command script delete attach") # this can't crash but we don't care whether the actual attach works - self.runCmd('attach noprocessexistswiththisname', check=False) + self.runCmd("attach noprocessexistswiththisname", check=False) diff --git a/lldb/test/API/commands/command/source/TestCommandSource.py b/lldb/test/API/commands/command/source/TestCommandSource.py --- a/lldb/test/API/commands/command/source/TestCommandSource.py +++ b/lldb/test/API/commands/command/source/TestCommandSource.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class CommandSourceTestCase(TestBase): - @no_debug_info_test def test_command_source(self): """Test that lldb command "command source" works correctly.""" @@ -20,7 +18,7 @@ # the "my" package that defines the date() function. self.runCmd("command source .lldb") self.check_results() - + @no_debug_info_test def test_command_source_relative(self): """Test that lldb command "command source" works correctly with relative paths.""" @@ -29,7 +27,7 @@ # the "my" package that defines the date() function. self.runCmd("command source commands2.txt") self.check_results() - + def check_results(self, failure=False): # Python should evaluate "my.date()" successfully. command_interpreter = self.dbg.GetCommandInterpreter() @@ -38,14 +36,22 @@ command_interpreter.HandleCommand("script my.date()", result) import datetime + if failure: - self.expect(result.GetOutput(), "script my.date() runs successfully", - exe=False, error=True) - else: - self.expect(result.GetOutput(), "script my.date() runs successfully", - exe=False, - substrs=[str(datetime.date.today())]) - + self.expect( + result.GetOutput(), + "script my.date() runs successfully", + exe=False, + error=True, + ) + else: + self.expect( + result.GetOutput(), + "script my.date() runs successfully", + exe=False, + substrs=[str(datetime.date.today())], + ) + @no_debug_info_test def test_command_source_relative_error(self): """Test that 'command source -C' gives an error for a relative path""" diff --git a/lldb/test/API/commands/command/source/my.py b/lldb/test/API/commands/command/source/my.py --- a/lldb/test/API/commands/command/source/my.py +++ b/lldb/test/API/commands/command/source/my.py @@ -1,4 +1,5 @@ def date(): import datetime + today = datetime.date.today() print(today) diff --git a/lldb/test/API/commands/disassemble/basic/TestDisassembleBreakpoint.py b/lldb/test/API/commands/disassemble/basic/TestDisassembleBreakpoint.py --- a/lldb/test/API/commands/disassemble/basic/TestDisassembleBreakpoint.py +++ b/lldb/test/API/commands/disassemble/basic/TestDisassembleBreakpoint.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -15,8 +14,9 @@ def test(self): self.build() - target, _, _, bkpt = lldbutil.run_to_source_breakpoint(self, - "Set a breakpoint here", lldb.SBFileSpec("main.cpp")) + target, _, _, bkpt = lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", lldb.SBFileSpec("main.cpp") + ) self.runCmd("dis -f") disassembly_with_break = self.res.GetOutput().splitlines() @@ -27,10 +27,10 @@ # Make sure all assembly instructions are the same as instructions # with the breakpoint removed. - self.assertEqual(len(disassembly_with_break), - len(disassembly_without_break)) - for dis_inst_with, dis_inst_without in \ - zip(disassembly_with_break, disassembly_without_break): - inst_with = dis_inst_with.split(':')[-1] - inst_without = dis_inst_without.split(':')[-1] + self.assertEqual(len(disassembly_with_break), len(disassembly_without_break)) + for dis_inst_with, dis_inst_without in zip( + disassembly_with_break, disassembly_without_break + ): + inst_with = dis_inst_with.split(":")[-1] + inst_without = dis_inst_without.split(":")[-1] self.assertEqual(inst_with, inst_without) diff --git a/lldb/test/API/commands/disassemble/basic/TestFrameDisassemble.py b/lldb/test/API/commands/disassemble/basic/TestFrameDisassemble.py --- a/lldb/test/API/commands/disassemble/basic/TestFrameDisassemble.py +++ b/lldb/test/API/commands/disassemble/basic/TestFrameDisassemble.py @@ -3,14 +3,12 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * class FrameDisassembleTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True def test_frame_disassemble(self): @@ -26,10 +24,11 @@ # Now create a breakpoint in main.c at the source matching # "Set a breakpoint here" breakpoint = target.BreakpointCreateBySourceRegex( - "Set a breakpoint here", lldb.SBFileSpec("main.cpp")) - self.assertTrue(breakpoint and - breakpoint.GetNumLocations() >= 1, - VALID_BREAKPOINT) + "Set a breakpoint here", lldb.SBFileSpec("main.cpp") + ) + self.assertTrue( + breakpoint and breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT + ) error = lldb.SBError() # This is the launch info. If you want to launch with arguments or @@ -42,10 +41,11 @@ # Did we hit our breakpoint? from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint + threads = get_threads_stopped_at_breakpoint(process, breakpoint) self.assertEqual( - len(threads), 1, - "There should be a thread stopped at our breakpoint") + len(threads), 1, "There should be a thread stopped at our breakpoint" + ) # The hit count for the breakpoint should be 1. self.assertEquals(breakpoint.GetHitCount(), 1) diff --git a/lldb/test/API/commands/dwim-print/TestDWIMPrint.py b/lldb/test/API/commands/dwim-print/TestDWIMPrint.py --- a/lldb/test/API/commands/dwim-print/TestDWIMPrint.py +++ b/lldb/test/API/commands/dwim-print/TestDWIMPrint.py @@ -50,10 +50,13 @@ # Verify dwim-print chose the expected command. self.runCmd("settings set dwim-print-verbosity full") - self.expect(dwim_cmd, substrs=[ - f"note: ran `{resolved_cmd}`", - dwim_cmd_output, - ]) + self.expect( + dwim_cmd, + substrs=[ + f"note: ran `{resolved_cmd}`", + dwim_cmd_output, + ], + ) def test_variables(self): """Test dwim-print with variables.""" @@ -118,7 +121,9 @@ def test_nested_values(self): """Test dwim-print with nested values (structs, etc).""" self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", lldb.SBFileSpec("main.c")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.c") + ) self.runCmd("settings set auto-one-line-summaries false") self._expect_cmd(f"dwim-print s", "frame variable") self._expect_cmd(f"dwim-print (struct Structure)s", "expression") @@ -126,7 +131,9 @@ def test_summary_strings(self): """Test dwim-print with nested values (structs, etc).""" self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", lldb.SBFileSpec("main.c")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.c") + ) self.runCmd("settings set auto-one-line-summaries false") self.runCmd("type summary add -e -s 'stub summary' Structure") self._expect_cmd(f"dwim-print s", "frame variable") diff --git a/lldb/test/API/commands/expression/anonymous-struct/TestCallUserAnonTypedef.py b/lldb/test/API/commands/expression/anonymous-struct/TestCallUserAnonTypedef.py --- a/lldb/test/API/commands/expression/anonymous-struct/TestCallUserAnonTypedef.py +++ b/lldb/test/API/commands/expression/anonymous-struct/TestCallUserAnonTypedef.py @@ -12,10 +12,12 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestExprLookupAnonStructTypedef(TestBase): +class TestExprLookupAnonStructTypedef(TestBase): def test(self): """Test typedeffed untagged struct arguments for function call expressions""" self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) self.expect_expr("multiply(&s)", result_type="double", result_value="1") diff --git a/lldb/test/API/commands/expression/argument_passing_restrictions/TestArgumentPassingRestrictions.py b/lldb/test/API/commands/expression/argument_passing_restrictions/TestArgumentPassingRestrictions.py --- a/lldb/test/API/commands/expression/argument_passing_restrictions/TestArgumentPassingRestrictions.py +++ b/lldb/test/API/commands/expression/argument_passing_restrictions/TestArgumentPassingRestrictions.py @@ -16,16 +16,18 @@ class TestArgumentPassingRestrictions(TestBase): + @skipIf(compiler="clang", compiler_version=["<", "7.0"]) + def test_argument_passing_restrictions(self): + self.build() - @skipIf(compiler="clang", compiler_version=['<', '7.0']) - def test_argument_passing_restrictions(self): - self.build() + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) - lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp")) + self.expect_expr( + "returnPassByRef()", + result_type="PassByRef", + result_children=[ValueCheck(name="x", value="11223344")], + ) - self.expect_expr("returnPassByRef()", result_type="PassByRef", result_children=[ - ValueCheck(name="x", value="11223344") - ]) - - self.expect_expr("takePassByRef(p)", result_type="int", result_value="42") + self.expect_expr("takePassByRef(p)", result_type="int", result_value="42") diff --git a/lldb/test/API/commands/expression/calculator_mode/TestCalculatorMode.py b/lldb/test/API/commands/expression/calculator_mode/TestCalculatorMode.py --- a/lldb/test/API/commands/expression/calculator_mode/TestCalculatorMode.py +++ b/lldb/test/API/commands/expression/calculator_mode/TestCalculatorMode.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -15,7 +14,14 @@ def test__calculator_mode(self): """Test calling expressions in the dummy target.""" - self.expect("expression 11 + 22", "11 + 22 didn't get the expected result", substrs=["33"]) + self.expect( + "expression 11 + 22", + "11 + 22 didn't get the expected result", + substrs=["33"], + ) # Now try it with a specific language: - self.expect("expression -l c -- 11 + 22", "11 + 22 didn't get the expected result", substrs=["33"]) - + self.expect( + "expression -l c -- 11 + 22", + "11 + 22 didn't get the expected result", + substrs=["33"], + ) diff --git a/lldb/test/API/commands/expression/call-function/TestCallBuiltinFunction.py b/lldb/test/API/commands/expression/call-function/TestCallBuiltinFunction.py --- a/lldb/test/API/commands/expression/call-function/TestCallBuiltinFunction.py +++ b/lldb/test/API/commands/expression/call-function/TestCallBuiltinFunction.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class ExprCommandCallBuiltinFunction(TestBase): - # Builtins are expanded by Clang, so debug info shouldn't matter. NO_DEBUG_INFO_TESTCASE = True @@ -21,6 +19,8 @@ target = self.createTestTarget() self.expect_expr("__builtin_isinf(0.0f)", result_type="int", result_value="0") - self.expect_expr("__builtin_isnormal(0.0f)", result_type="int", result_value="0") + self.expect_expr( + "__builtin_isnormal(0.0f)", result_type="int", result_value="0" + ) self.expect_expr("__builtin_constant_p(1)", result_type="int", result_value="1") self.expect_expr("__builtin_abs(-14)", result_type="int", result_value="14") diff --git a/lldb/test/API/commands/expression/call-function/TestCallStdStringFunction.py b/lldb/test/API/commands/expression/call-function/TestCallStdStringFunction.py --- a/lldb/test/API/commands/expression/call-function/TestCallStdStringFunction.py +++ b/lldb/test/API/commands/expression/call-function/TestCallStdStringFunction.py @@ -7,20 +7,21 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class ExprCommandCallFunctionTestCase(TestBase): +class ExprCommandCallFunctionTestCase(TestBase): @expectedFailureAll( - compiler="icc", - bugnumber="llvm.org/pr14437, fails with ICC 13.1") + compiler="icc", bugnumber="llvm.org/pr14437, fails with ICC 13.1" + ) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") - @skipIf(compiler="clang", compiler_version=['<', '9.0']) + @skipIf(compiler="clang", compiler_version=["<", "9.0"]) def test_with(self): """Test calling std::String member function.""" self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) - self.expect("expression str", - substrs=['Hello world']) + self.expect("expression str", substrs=["Hello world"]) # Calling this function now succeeds, but we follow the typedef return type through to # const char *, and thus don't invoke the Summary formatter. @@ -29,8 +30,14 @@ # skip this part of the test. triple = self.dbg.GetSelectedPlatform().GetTriple() do_cstr_test = True - if triple in ["arm64-apple-ios", "arm64e-apple-ios", "arm64-apple-tvos", "armv7k-apple-watchos", "arm64-apple-bridgeos", "arm64_32-apple-watchos"]: + if triple in [ + "arm64-apple-ios", + "arm64e-apple-ios", + "arm64-apple-tvos", + "armv7k-apple-watchos", + "arm64-apple-bridgeos", + "arm64_32-apple-watchos", + ]: do_cstr_test = False if do_cstr_test: - self.expect("expression str.c_str()", - substrs=['Hello world']) + self.expect("expression str.c_str()", substrs=["Hello world"]) diff --git a/lldb/test/API/commands/expression/call-function/TestCallStopAndContinue.py b/lldb/test/API/commands/expression/call-function/TestCallStopAndContinue.py --- a/lldb/test/API/commands/expression/call-function/TestCallStopAndContinue.py +++ b/lldb/test/API/commands/expression/call-function/TestCallStopAndContinue.py @@ -6,8 +6,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class ExprCommandCallStopContinueTestCase(TestBase): +class ExprCommandCallStopContinueTestCase(TestBase): def setUp(self): # Call super's setUp(). TestBase.setUp(self) @@ -16,21 +16,29 @@ def test(self): """Test gathering result from interrupted function call.""" self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) lldbutil.run_break_set_by_file_and_line( self, "main.cpp", - line_number('main.cpp', '{5, "five"}'), + line_number("main.cpp", '{5, "five"}'), num_expected_locations=-1, - loc_exact=True) + loc_exact=True, + ) - self.expect("expr -i false -- returnsFive()", error=True, - substrs=['Execution was interrupted, reason: breakpoint']) + self.expect( + "expr -i false -- returnsFive()", + error=True, + substrs=["Execution was interrupted, reason: breakpoint"], + ) self.runCmd("continue", "Continue completed") self.expect( "thread list", substrs=[ - 'stop reason = User Expression thread plan', - r'Completed expression: (Five) $0 = (number = 5, name = "five")']) + "stop reason = User Expression thread plan", + r'Completed expression: (Five) $0 = (number = 5, name = "five")', + ], + ) diff --git a/lldb/test/API/commands/expression/call-function/TestCallUserDefinedFunction.py b/lldb/test/API/commands/expression/call-function/TestCallUserDefinedFunction.py --- a/lldb/test/API/commands/expression/call-function/TestCallUserDefinedFunction.py +++ b/lldb/test/API/commands/expression/call-function/TestCallUserDefinedFunction.py @@ -12,12 +12,14 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class ExprCommandCallUserDefinedFunction(TestBase): +class ExprCommandCallUserDefinedFunction(TestBase): def test(self): """Test return values of user defined function calls.""" self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) # Test recursive function call. self.expect_expr("fib(5)", result_type="unsigned int", result_value="5") @@ -30,5 +32,13 @@ self.expect_expr("add(add(5,2),fib(5))", result_type="int", result_value="12") # Test function with pointer parameter - self.expect_expr('stringCompare((const char*) \"Hello world\")', result_type="bool", result_value="true") - self.expect_expr('stringCompare((const char*) \"Hellworld\")', result_type="bool", result_value="false") + self.expect_expr( + 'stringCompare((const char*) "Hello world")', + result_type="bool", + result_value="true", + ) + self.expect_expr( + 'stringCompare((const char*) "Hellworld")', + result_type="bool", + result_value="false", + ) diff --git a/lldb/test/API/commands/expression/call-restarts/TestCallThatRestarts.py b/lldb/test/API/commands/expression/call-restarts/TestCallThatRestarts.py --- a/lldb/test/API/commands/expression/call-restarts/TestCallThatRestarts.py +++ b/lldb/test/API/commands/expression/call-restarts/TestCallThatRestarts.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -32,34 +31,34 @@ def check_after_call(self, num_sigchld): after_call = self.sigchld_no.GetValueAsSigned(-1) self.assertEqual( - after_call - self.start_sigchld_no, num_sigchld, - "Really got %d SIGCHLD signals through the call." % - (num_sigchld)) + after_call - self.start_sigchld_no, + num_sigchld, + "Really got %d SIGCHLD signals through the call." % (num_sigchld), + ) self.start_sigchld_no = after_call # Check that we are back where we were before: frame = self.thread.GetFrameAtIndex(0) self.assertEqual( - self.orig_frame_pc, frame.GetPC(), - "Restored the zeroth frame correctly") + self.orig_frame_pc, frame.GetPC(), "Restored the zeroth frame correctly" + ) def call_function(self): - (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - 'Stop here in main.', self.main_source_spec) + (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Stop here in main.", self.main_source_spec + ) # Make sure the SIGCHLD behavior is pass/no-stop/no-notify: self.runCmd("process handle SIGCHLD -s 0 -p 1 -n 0") # The sigchld_no variable should be 0 at this point. self.sigchld_no = target.FindFirstGlobalVariable("sigchld_no") - self.assertTrue( - self.sigchld_no.IsValid(), - "Got a value for sigchld_no") + self.assertTrue(self.sigchld_no.IsValid(), "Got a value for sigchld_no") self.start_sigchld_no = self.sigchld_no.GetValueAsSigned(-1) self.assertNotEqual( - self.start_sigchld_no, -1, - "Got an actual value for sigchld_no") + self.start_sigchld_no, -1, "Got an actual value for sigchld_no" + ) options = lldb.SBExpressionOptions() # processing 30 signals takes a while, increase the expression timeout @@ -73,9 +72,7 @@ self.orig_frame_pc = frame.GetPC() num_sigchld = 30 - value = frame.EvaluateExpression( - "call_me (%d)" % - (num_sigchld), options) + value = frame.EvaluateExpression("call_me (%d)" % (num_sigchld), options) self.assertTrue(value.IsValid()) self.assertSuccess(value.GetError()) self.assertEquals(value.GetValueAsSigned(-1), num_sigchld) @@ -85,14 +82,13 @@ # Okay, now try with a breakpoint in the called code in the case where # we are ignoring breakpoint hits. handler_bkpt = target.BreakpointCreateBySourceRegex( - "Got sigchld %d.", self.main_source_spec) + "Got sigchld %d.", self.main_source_spec + ) self.assertTrue(handler_bkpt.GetNumLocations() > 0) options.SetIgnoreBreakpoints(True) options.SetUnwindOnError(True) - value = frame.EvaluateExpression( - "call_me (%d)" % - (num_sigchld), options) + value = frame.EvaluateExpression("call_me (%d)" % (num_sigchld), options) self.assertTrue(value.IsValid()) self.assertSuccess(value.GetError()) @@ -103,9 +99,7 @@ # still works: self.runCmd("process handle SIGCHLD -s 0 -p 1 -n 1") - value = frame.EvaluateExpression( - "call_me (%d)" % - (num_sigchld), options) + value = frame.EvaluateExpression("call_me (%d)" % (num_sigchld), options) self.assertTrue(value.IsValid()) self.assertSuccess(value.GetError()) @@ -115,9 +109,7 @@ # Now set this unwind on error to false, and make sure that we still # complete the call: options.SetUnwindOnError(False) - value = frame.EvaluateExpression( - "call_me (%d)" % - (num_sigchld), options) + value = frame.EvaluateExpression("call_me (%d)" % (num_sigchld), options) self.assertTrue(value.IsValid()) self.assertSuccess(value.GetError()) @@ -129,9 +121,7 @@ self.runCmd("process handle SIGCHLD -s 1 -p 1 -n 1") - value = frame.EvaluateExpression( - "call_me (%d)" % - (num_sigchld), options) + value = frame.EvaluateExpression("call_me (%d)" % (num_sigchld), options) self.assertTrue(value.IsValid()) self.assertFalse(value.GetError().Success()) @@ -140,10 +130,11 @@ self.runCmd("process handle SIGCHLD -s 0 -p 1 -n 1") error = process.Continue() - self.assertSuccess(error, - "Continuing after stopping for signal succeeds.") + self.assertSuccess(error, "Continuing after stopping for signal succeeds.") frame = self.thread.GetFrameAtIndex(0) self.assertEqual( - frame.GetPC(), self.orig_frame_pc, - "Continuing returned to the place we started.") + frame.GetPC(), + self.orig_frame_pc, + "Continuing returned to the place we started.", + ) diff --git a/lldb/test/API/commands/expression/call-throws/TestCallThatThrows.py b/lldb/test/API/commands/expression/call-throws/TestCallThatThrows.py --- a/lldb/test/API/commands/expression/call-throws/TestCallThatThrows.py +++ b/lldb/test/API/commands/expression/call-throws/TestCallThatThrows.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class ExprCommandWithThrowTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) @@ -29,13 +27,14 @@ # Check that we are back where we were before: frame = self.thread.GetFrameAtIndex(0) self.assertEqual( - self.orig_frame_pc, frame.GetPC(), - "Restored the zeroth frame correctly") + self.orig_frame_pc, frame.GetPC(), "Restored the zeroth frame correctly" + ) def call_function(self): """Test calling function that throws.""" - (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - 'I am about to throw.', self.main_source_spec) + (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "I am about to throw.", self.main_source_spec + ) options = lldb.SBExpressionOptions() options.SetUnwindOnError(True) @@ -54,21 +53,22 @@ # Okay, now try with a breakpoint in the called code in the case where # we are ignoring breakpoint hits. handler_bkpt = target.BreakpointCreateBySourceRegex( - "I felt like it", self.main_source_spec) + "I felt like it", self.main_source_spec + ) self.assertTrue(handler_bkpt.GetNumLocations() > 0) options.SetIgnoreBreakpoints(True) options.SetUnwindOnError(True) value = frame.EvaluateExpression("[my_class callMeIThrow]", options) - self.assertTrue( - value.IsValid() and value.GetError().Success() == False) + self.assertTrue(value.IsValid() and value.GetError().Success() == False) self.check_after_call() # Now set the ObjC language breakpoint and make sure that doesn't # interfere with the call: exception_bkpt = target.BreakpointCreateForException( - lldb.eLanguageTypeObjC, False, True) + lldb.eLanguageTypeObjC, False, True + ) self.assertTrue(exception_bkpt.GetNumLocations() > 0) options.SetIgnoreBreakpoints(True) @@ -76,8 +76,7 @@ value = frame.EvaluateExpression("[my_class callMeIThrow]", options) - self.assertTrue( - value.IsValid() and value.GetError().Success() == False) + self.assertTrue(value.IsValid() and value.GetError().Success() == False) self.check_after_call() # Now turn off exception trapping, and call a function that catches the exceptions, @@ -96,6 +95,5 @@ options.SetUnwindOnError(False) value = frame.EvaluateExpression("[my_class callMeIThrow]", options) - self.assertTrue( - value.IsValid() and value.GetError().Success() == False) + self.assertTrue(value.IsValid() and value.GetError().Success() == False) self.check_after_call() diff --git a/lldb/test/API/commands/expression/cast_int_to_anonymous_enum/TestCastIntToAnonymousEnum.py b/lldb/test/API/commands/expression/cast_int_to_anonymous_enum/TestCastIntToAnonymousEnum.py --- a/lldb/test/API/commands/expression/cast_int_to_anonymous_enum/TestCastIntToAnonymousEnum.py +++ b/lldb/test/API/commands/expression/cast_int_to_anonymous_enum/TestCastIntToAnonymousEnum.py @@ -9,12 +9,13 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCastIntToAnonymousEnum(TestBase): +class TestCastIntToAnonymousEnum(TestBase): def test_cast_int_to_anonymous_enum(self): self.build() - lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp", False)) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) self.expect_expr("(flow_e)0", result_type="flow_e", result_value="A") diff --git a/lldb/test/API/commands/expression/char/TestExprsChar.py b/lldb/test/API/commands/expression/char/TestExprsChar.py --- a/lldb/test/API/commands/expression/char/TestExprsChar.py +++ b/lldb/test/API/commands/expression/char/TestExprsChar.py @@ -3,13 +3,15 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class ExprCharTestCase(TestBase): +class ExprCharTestCase(TestBase): def do_test(self, dictionary=None): """These basic expression commands should work as expected.""" self.build(dictionary=dictionary) - lldbutil.run_to_source_breakpoint(self, '// Break here', lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Break here", lldb.SBFileSpec("main.cpp") + ) self.expect_expr("foo(c)", result_value="1") self.expect_expr("foo(sc)", result_value="2") @@ -22,7 +24,7 @@ self.do_test() def test_signed_char(self): - self.do_test(dictionary={'CFLAGS_EXTRAS': '-fsigned-char'}) + self.do_test(dictionary={"CFLAGS_EXTRAS": "-fsigned-char"}) def test_unsigned_char(self): - self.do_test(dictionary={'CFLAGS_EXTRAS': '-funsigned-char'}) + self.do_test(dictionary={"CFLAGS_EXTRAS": "-funsigned-char"}) diff --git a/lldb/test/API/commands/expression/class_template_specialization_empty_pack/TestClassTemplateSpecializationParametersHandling.py b/lldb/test/API/commands/expression/class_template_specialization_empty_pack/TestClassTemplateSpecializationParametersHandling.py --- a/lldb/test/API/commands/expression/class_template_specialization_empty_pack/TestClassTemplateSpecializationParametersHandling.py +++ b/lldb/test/API/commands/expression/class_template_specialization_empty_pack/TestClassTemplateSpecializationParametersHandling.py @@ -10,11 +10,12 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestClassTemplateSpecializationParametersHandling(TestBase): +class TestClassTemplateSpecializationParametersHandling(TestBase): def test_class_template_specialization(self): self.build() - lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp", False)) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) self.expect_expr("b.foo()", result_type="int", result_value="1") diff --git a/lldb/test/API/commands/expression/codegen-crash-import-def-arraytype-element/TestImportDefinitionArrayType.py b/lldb/test/API/commands/expression/codegen-crash-import-def-arraytype-element/TestImportDefinitionArrayType.py --- a/lldb/test/API/commands/expression/codegen-crash-import-def-arraytype-element/TestImportDefinitionArrayType.py +++ b/lldb/test/API/commands/expression/codegen-crash-import-def-arraytype-element/TestImportDefinitionArrayType.py @@ -3,10 +3,12 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestImportDefinitionArrayType(TestBase): +class TestImportDefinitionArrayType(TestBase): def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) self.expect_expr("__private->o", result_type="char", result_value="'A'") diff --git a/lldb/test/API/commands/expression/completion-crash-invalid-iterator/TestInvalidIteratorCompletionCrash.py b/lldb/test/API/commands/expression/completion-crash-invalid-iterator/TestInvalidIteratorCompletionCrash.py --- a/lldb/test/API/commands/expression/completion-crash-invalid-iterator/TestInvalidIteratorCompletionCrash.py +++ b/lldb/test/API/commands/expression/completion-crash-invalid-iterator/TestInvalidIteratorCompletionCrash.py @@ -4,15 +4,17 @@ class TestCase(TestBase): - - @skipIf # rdar://problem/53931074 + @skipIf # rdar://problem/53931074 def test(self): self.build() target = self.createTestTarget() callee_break = target.BreakpointCreateByName( - "SomeClass::SomeClass(ParamClass)", None) + "SomeClass::SomeClass(ParamClass)", None + ) self.assertTrue(callee_break.GetNumLocations() > 0) self.runCmd("run", RUN_SUCCEEDED) to_complete = "e ParamClass" - self.dbg.GetCommandInterpreter().HandleCompletion(to_complete, len(to_complete), 0, -1, lldb.SBStringList()) + self.dbg.GetCommandInterpreter().HandleCompletion( + to_complete, len(to_complete), 0, -1, lldb.SBStringList() + ) diff --git a/lldb/test/API/commands/expression/completion-in-lambda-and-unnamed-class/TestCompletionInLambdaAndUnnamedClass.py b/lldb/test/API/commands/expression/completion-in-lambda-and-unnamed-class/TestCompletionInLambdaAndUnnamedClass.py --- a/lldb/test/API/commands/expression/completion-in-lambda-and-unnamed-class/TestCompletionInLambdaAndUnnamedClass.py +++ b/lldb/test/API/commands/expression/completion-in-lambda-and-unnamed-class/TestCompletionInLambdaAndUnnamedClass.py @@ -1,4 +1,7 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(),) +lldbinline.MakeInlineTest( + __file__, + globals(), +) diff --git a/lldb/test/API/commands/expression/completion/TestExprCompletion.py b/lldb/test/API/commands/expression/completion/TestExprCompletion.py --- a/lldb/test/API/commands/expression/completion/TestExprCompletion.py +++ b/lldb/test/API/commands/expression/completion/TestExprCompletion.py @@ -9,8 +9,8 @@ from lldbsuite.test import lldbplatform from lldbsuite.test import lldbutil -class CommandLineExprCompletionTestCase(TestBase): +class CommandLineExprCompletionTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True def test_expr_completion(self): @@ -20,174 +20,231 @@ self.createTestTarget() # Try the completion before we have a context to complete on. - self.assume_no_completions('expr some_expr') - self.assume_no_completions('expr ') - self.assume_no_completions('expr f') + self.assume_no_completions("expr some_expr") + self.assume_no_completions("expr ") + self.assume_no_completions("expr f") - - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - '// Break here', self.main_source_spec) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// Break here", self.main_source_spec + ) # Completing member functions - self.complete_exactly('expr some_expr.FooNoArgs', - 'expr some_expr.FooNoArgsBar()') - self.complete_exactly('expr some_expr.FooWithArgs', - 'expr some_expr.FooWithArgsBar(') - self.complete_exactly('expr some_expr.FooWithMultipleArgs', - 'expr some_expr.FooWithMultipleArgsBar(') - self.complete_exactly('expr some_expr.FooUnderscore', - 'expr some_expr.FooUnderscoreBar_()') - self.complete_exactly('expr some_expr.FooNumbers', - 'expr some_expr.FooNumbersBar1()') - self.complete_exactly('expr some_expr.StaticMemberMethod', - 'expr some_expr.StaticMemberMethodBar()') + self.complete_exactly( + "expr some_expr.FooNoArgs", "expr some_expr.FooNoArgsBar()" + ) + self.complete_exactly( + "expr some_expr.FooWithArgs", "expr some_expr.FooWithArgsBar(" + ) + self.complete_exactly( + "expr some_expr.FooWithMultipleArgs", + "expr some_expr.FooWithMultipleArgsBar(", + ) + self.complete_exactly( + "expr some_expr.FooUnderscore", "expr some_expr.FooUnderscoreBar_()" + ) + self.complete_exactly( + "expr some_expr.FooNumbers", "expr some_expr.FooNumbersBar1()" + ) + self.complete_exactly( + "expr some_expr.StaticMemberMethod", + "expr some_expr.StaticMemberMethodBar()", + ) # Completing static functions - self.complete_exactly('expr Expr::StaticMemberMethod', - 'expr Expr::StaticMemberMethodBar()') + self.complete_exactly( + "expr Expr::StaticMemberMethod", "expr Expr::StaticMemberMethodBar()" + ) # Completing member variables - self.complete_exactly('expr some_expr.MemberVariab', - 'expr some_expr.MemberVariableBar') + self.complete_exactly( + "expr some_expr.MemberVariab", "expr some_expr.MemberVariableBar" + ) # Multiple completions - self.completions_contain('expr some_expr.', - ['some_expr.FooNumbersBar1()', - 'some_expr.FooUnderscoreBar_()', - 'some_expr.FooWithArgsBar(', - 'some_expr.MemberVariableBar']) - - self.completions_contain('expr some_expr.Foo', - ['some_expr.FooNumbersBar1()', - 'some_expr.FooUnderscoreBar_()', - 'some_expr.FooWithArgsBar(']) - - self.completions_contain('expr ', - ['static_cast', - 'reinterpret_cast', - 'dynamic_cast']) - - self.completions_contain('expr 1 + ', - ['static_cast', - 'reinterpret_cast', - 'dynamic_cast']) + self.completions_contain( + "expr some_expr.", + [ + "some_expr.FooNumbersBar1()", + "some_expr.FooUnderscoreBar_()", + "some_expr.FooWithArgsBar(", + "some_expr.MemberVariableBar", + ], + ) + + self.completions_contain( + "expr some_expr.Foo", + [ + "some_expr.FooNumbersBar1()", + "some_expr.FooUnderscoreBar_()", + "some_expr.FooWithArgsBar(", + ], + ) + + self.completions_contain( + "expr ", ["static_cast", "reinterpret_cast", "dynamic_cast"] + ) + + self.completions_contain( + "expr 1 + ", ["static_cast", "reinterpret_cast", "dynamic_cast"] + ) # Completion expr without spaces # This is a bit awkward looking for the user, but that's how # the completion API works at the moment. - self.completions_contain('expr 1+', - ['1+some_expr', "1+static_cast"]) + self.completions_contain("expr 1+", ["1+some_expr", "1+static_cast"]) # Test with spaces - self.complete_exactly('expr some_expr .FooNoArgs', - 'expr some_expr .FooNoArgsBar()') - self.complete_exactly('expr some_expr .FooNoArgs', - 'expr some_expr .FooNoArgsBar()') - self.complete_exactly('expr some_expr .FooNoArgs', - 'expr some_expr .FooNoArgsBar()') - self.complete_exactly('expr some_expr. FooNoArgs', - 'expr some_expr. FooNoArgsBar()') - self.complete_exactly('expr some_expr . FooNoArgs', - 'expr some_expr . FooNoArgsBar()') - self.complete_exactly('expr Expr :: StaticMemberMethod', - 'expr Expr :: StaticMemberMethodBar()') - self.complete_exactly('expr Expr ::StaticMemberMethod', - 'expr Expr ::StaticMemberMethodBar()') - self.complete_exactly('expr Expr:: StaticMemberMethod', - 'expr Expr:: StaticMemberMethodBar()') + self.complete_exactly( + "expr some_expr .FooNoArgs", "expr some_expr .FooNoArgsBar()" + ) + self.complete_exactly( + "expr some_expr .FooNoArgs", "expr some_expr .FooNoArgsBar()" + ) + self.complete_exactly( + "expr some_expr .FooNoArgs", "expr some_expr .FooNoArgsBar()" + ) + self.complete_exactly( + "expr some_expr. FooNoArgs", "expr some_expr. FooNoArgsBar()" + ) + self.complete_exactly( + "expr some_expr . FooNoArgs", "expr some_expr . FooNoArgsBar()" + ) + self.complete_exactly( + "expr Expr :: StaticMemberMethod", "expr Expr :: StaticMemberMethodBar()" + ) + self.complete_exactly( + "expr Expr ::StaticMemberMethod", "expr Expr ::StaticMemberMethodBar()" + ) + self.complete_exactly( + "expr Expr:: StaticMemberMethod", "expr Expr:: StaticMemberMethodBar()" + ) # Test that string literals don't break our parsing logic. - self.complete_exactly('expr const char *cstr = "some_e"; char c = *cst', - 'expr const char *cstr = "some_e"; char c = *cstr') - self.complete_exactly('expr const char *cstr = "some_e" ; char c = *cst', - 'expr const char *cstr = "some_e" ; char c = *cstr') + self.complete_exactly( + 'expr const char *cstr = "some_e"; char c = *cst', + 'expr const char *cstr = "some_e"; char c = *cstr', + ) + self.complete_exactly( + 'expr const char *cstr = "some_e" ; char c = *cst', + 'expr const char *cstr = "some_e" ; char c = *cstr', + ) # Requesting completions inside an incomplete string doesn't provide any # completions. - self.complete_exactly('expr const char *cstr = "some_e', - 'expr const char *cstr = "some_e') + self.complete_exactly( + 'expr const char *cstr = "some_e', 'expr const char *cstr = "some_e' + ) # Completing inside double dash should do nothing - self.assume_no_completions('expr -i0 -- some_expr.', 10) - self.assume_no_completions('expr -i0 -- some_expr.', 11) + self.assume_no_completions("expr -i0 -- some_expr.", 10) + self.assume_no_completions("expr -i0 -- some_expr.", 11) # Test with expr arguments - self.complete_exactly('expr -i0 -- some_expr .FooNoArgs', - 'expr -i0 -- some_expr .FooNoArgsBar()') - self.complete_exactly('expr -i0 -- some_expr .FooNoArgs', - 'expr -i0 -- some_expr .FooNoArgsBar()') + self.complete_exactly( + "expr -i0 -- some_expr .FooNoArgs", "expr -i0 -- some_expr .FooNoArgsBar()" + ) + self.complete_exactly( + "expr -i0 -- some_expr .FooNoArgs", + "expr -i0 -- some_expr .FooNoArgsBar()", + ) # Addrof and deref - self.complete_exactly('expr (*(&some_expr)).FooNoArgs', - 'expr (*(&some_expr)).FooNoArgsBar()') - self.complete_exactly('expr (*(&some_expr)) .FooNoArgs', - 'expr (*(&some_expr)) .FooNoArgsBar()') - self.complete_exactly('expr (* (&some_expr)) .FooNoArgs', - 'expr (* (&some_expr)) .FooNoArgsBar()') - self.complete_exactly('expr (* (& some_expr)) .FooNoArgs', - 'expr (* (& some_expr)) .FooNoArgsBar()') + self.complete_exactly( + "expr (*(&some_expr)).FooNoArgs", "expr (*(&some_expr)).FooNoArgsBar()" + ) + self.complete_exactly( + "expr (*(&some_expr)) .FooNoArgs", "expr (*(&some_expr)) .FooNoArgsBar()" + ) + self.complete_exactly( + "expr (* (&some_expr)) .FooNoArgs", "expr (* (&some_expr)) .FooNoArgsBar()" + ) + self.complete_exactly( + "expr (* (& some_expr)) .FooNoArgs", + "expr (* (& some_expr)) .FooNoArgsBar()", + ) # Addrof and deref (part 2) - self.complete_exactly('expr (&some_expr)->FooNoArgs', - 'expr (&some_expr)->FooNoArgsBar()') - self.complete_exactly('expr (&some_expr) ->FooNoArgs', - 'expr (&some_expr) ->FooNoArgsBar()') - self.complete_exactly('expr (&some_expr) -> FooNoArgs', - 'expr (&some_expr) -> FooNoArgsBar()') - self.complete_exactly('expr (&some_expr)-> FooNoArgs', - 'expr (&some_expr)-> FooNoArgsBar()') + self.complete_exactly( + "expr (&some_expr)->FooNoArgs", "expr (&some_expr)->FooNoArgsBar()" + ) + self.complete_exactly( + "expr (&some_expr) ->FooNoArgs", "expr (&some_expr) ->FooNoArgsBar()" + ) + self.complete_exactly( + "expr (&some_expr) -> FooNoArgs", "expr (&some_expr) -> FooNoArgsBar()" + ) + self.complete_exactly( + "expr (&some_expr)-> FooNoArgs", "expr (&some_expr)-> FooNoArgsBar()" + ) # Builtin arg - self.complete_exactly('expr static_ca', - 'expr static_cast') + self.complete_exactly("expr static_ca", "expr static_cast") # From other files - self.complete_exactly('expr fwd_decl_ptr->Hidden', - 'expr fwd_decl_ptr->HiddenMember') - + self.complete_exactly( + "expr fwd_decl_ptr->Hidden", "expr fwd_decl_ptr->HiddenMember" + ) # Types - self.complete_exactly('expr LongClassNa', - 'expr LongClassName') - self.complete_exactly('expr LongNamespaceName::NestedCla', - 'expr LongNamespaceName::NestedClass') + self.complete_exactly("expr LongClassNa", "expr LongClassName") + self.complete_exactly( + "expr LongNamespaceName::NestedCla", "expr LongNamespaceName::NestedClass" + ) # Namespaces - self.complete_exactly('expr LongNamespaceNa', - 'expr LongNamespaceName::') + self.complete_exactly("expr LongNamespaceNa", "expr LongNamespaceName::") # Multiple arguments - self.complete_exactly('expr &some_expr + &some_e', - 'expr &some_expr + &some_expr') - self.complete_exactly('expr SomeLongVarNameWithCapitals + SomeLongVarName', - 'expr SomeLongVarNameWithCapitals + SomeLongVarNameWithCapitals') - self.complete_exactly('expr SomeIntVar + SomeIntV', - 'expr SomeIntVar + SomeIntVar') + self.complete_exactly( + "expr &some_expr + &some_e", "expr &some_expr + &some_expr" + ) + self.complete_exactly( + "expr SomeLongVarNameWithCapitals + SomeLongVarName", + "expr SomeLongVarNameWithCapitals + SomeLongVarNameWithCapitals", + ) + self.complete_exactly( + "expr SomeIntVar + SomeIntV", "expr SomeIntVar + SomeIntVar" + ) # Multiple statements - self.complete_exactly('expr long LocalVariable = 0; LocalVaria', - 'expr long LocalVariable = 0; LocalVariable') + self.complete_exactly( + "expr long LocalVariable = 0; LocalVaria", + "expr long LocalVariable = 0; LocalVariable", + ) # Custom Decls - self.complete_exactly('expr auto l = [](int LeftHandSide, int bx){ return LeftHandS', - 'expr auto l = [](int LeftHandSide, int bx){ return LeftHandSide') - self.complete_exactly('expr struct LocalStruct { long MemberName; } ; LocalStruct S; S.Mem', - 'expr struct LocalStruct { long MemberName; } ; LocalStruct S; S.MemberName') + self.complete_exactly( + "expr auto l = [](int LeftHandSide, int bx){ return LeftHandS", + "expr auto l = [](int LeftHandSide, int bx){ return LeftHandSide", + ) + self.complete_exactly( + "expr struct LocalStruct { long MemberName; } ; LocalStruct S; S.Mem", + "expr struct LocalStruct { long MemberName; } ; LocalStruct S; S.MemberName", + ) # Completing function call arguments - self.complete_exactly('expr some_expr.FooWithArgsBar(some_exp', - 'expr some_expr.FooWithArgsBar(some_expr') - self.complete_exactly('expr some_expr.FooWithArgsBar(SomeIntV', - 'expr some_expr.FooWithArgsBar(SomeIntVar') - self.complete_exactly('expr some_expr.FooWithMultipleArgsBar(SomeIntVar, SomeIntVa', - 'expr some_expr.FooWithMultipleArgsBar(SomeIntVar, SomeIntVar') + self.complete_exactly( + "expr some_expr.FooWithArgsBar(some_exp", + "expr some_expr.FooWithArgsBar(some_expr", + ) + self.complete_exactly( + "expr some_expr.FooWithArgsBar(SomeIntV", + "expr some_expr.FooWithArgsBar(SomeIntVar", + ) + self.complete_exactly( + "expr some_expr.FooWithMultipleArgsBar(SomeIntVar, SomeIntVa", + "expr some_expr.FooWithMultipleArgsBar(SomeIntVar, SomeIntVar", + ) # Function return values - self.complete_exactly('expr some_expr.Self().FooNoArgs', - 'expr some_expr.Self().FooNoArgsBar()') - self.complete_exactly('expr some_expr.Self() .FooNoArgs', - 'expr some_expr.Self() .FooNoArgsBar()') - self.complete_exactly('expr some_expr.Self(). FooNoArgs', - 'expr some_expr.Self(). FooNoArgsBar()') + self.complete_exactly( + "expr some_expr.Self().FooNoArgs", "expr some_expr.Self().FooNoArgsBar()" + ) + self.complete_exactly( + "expr some_expr.Self() .FooNoArgs", "expr some_expr.Self() .FooNoArgsBar()" + ) + self.complete_exactly( + "expr some_expr.Self(). FooNoArgs", "expr some_expr.Self(). FooNoArgsBar()" + ) def test_expr_completion_with_descriptions(self): self.build() @@ -195,48 +252,71 @@ self.main_source_spec = lldb.SBFileSpec(self.main_source) self.createTestTarget() - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - '// Break here', self.main_source_spec) - - self.check_completion_with_desc("expr ", [ - # builtin types have no description. - ["int", ""], - ["float", ""], - # VarDecls have their type as description. - ["some_expr", "Expr &"], - ], enforce_order = True) - self.check_completion_with_desc("expr some_expr.", [ - # Functions have their signature as description. - ["some_expr.~Expr()", "inline ~Expr()"], - ["some_expr.operator=(", "inline Expr &operator=(const Expr &)"], - # FieldDecls have their type as description. - ["some_expr.MemberVariableBar", "int"], - ["some_expr.StaticMemberMethodBar()", "static int StaticMemberMethodBar()"], - ["some_expr.Self()", "Expr &Self()"], - ["some_expr.FooNoArgsBar()", "int FooNoArgsBar()"], - ["some_expr.FooWithArgsBar(", "int FooWithArgsBar(int)"], - ["some_expr.FooNumbersBar1()", "int FooNumbersBar1()"], - ["some_expr.FooUnderscoreBar_()", "int FooUnderscoreBar_()"], - ["some_expr.FooWithMultipleArgsBar(", "int FooWithMultipleArgsBar(int, int)"], - ], enforce_order = True) - - def assume_no_completions(self, str_input, cursor_pos = None): + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// Break here", self.main_source_spec + ) + + self.check_completion_with_desc( + "expr ", + [ + # builtin types have no description. + ["int", ""], + ["float", ""], + # VarDecls have their type as description. + ["some_expr", "Expr &"], + ], + enforce_order=True, + ) + self.check_completion_with_desc( + "expr some_expr.", + [ + # Functions have their signature as description. + ["some_expr.~Expr()", "inline ~Expr()"], + ["some_expr.operator=(", "inline Expr &operator=(const Expr &)"], + # FieldDecls have their type as description. + ["some_expr.MemberVariableBar", "int"], + [ + "some_expr.StaticMemberMethodBar()", + "static int StaticMemberMethodBar()", + ], + ["some_expr.Self()", "Expr &Self()"], + ["some_expr.FooNoArgsBar()", "int FooNoArgsBar()"], + ["some_expr.FooWithArgsBar(", "int FooWithArgsBar(int)"], + ["some_expr.FooNumbersBar1()", "int FooNumbersBar1()"], + ["some_expr.FooUnderscoreBar_()", "int FooUnderscoreBar_()"], + [ + "some_expr.FooWithMultipleArgsBar(", + "int FooWithMultipleArgsBar(int, int)", + ], + ], + enforce_order=True, + ) + + def assume_no_completions(self, str_input, cursor_pos=None): interp = self.dbg.GetCommandInterpreter() match_strings = lldb.SBStringList() if cursor_pos is None: - cursor_pos = len(str_input) - num_matches = interp.HandleCompletion(str_input, cursor_pos, 0, -1, match_strings) + cursor_pos = len(str_input) + num_matches = interp.HandleCompletion( + str_input, cursor_pos, 0, -1, match_strings + ) available_completions = [] for m in match_strings: available_completions.append(m) - self.assertEquals(num_matches, 0, "Got matches, but didn't expect any: " + str(available_completions)) + self.assertEquals( + num_matches, + 0, + "Got matches, but didn't expect any: " + str(available_completions), + ) def completions_contain(self, str_input, items): interp = self.dbg.GetCommandInterpreter() match_strings = lldb.SBStringList() - num_matches = interp.HandleCompletion(str_input, len(str_input), 0, -1, match_strings) + num_matches = interp.HandleCompletion( + str_input, len(str_input), 0, -1, match_strings + ) common_match = match_strings.GetStringAtIndex(0) for item in items: @@ -248,5 +328,11 @@ # Transform match_strings to a python list with strings available_completions = [] for m in match_strings: - available_completions.append(m) - self.assertTrue(found, "Couldn't find completion " + item + " in completions " + str(available_completions)) + available_completions.append(m) + self.assertTrue( + found, + "Couldn't find completion " + + item + + " in completions " + + str(available_completions), + ) diff --git a/lldb/test/API/commands/expression/context-object-objc/TestContextObjectObjc.py b/lldb/test/API/commands/expression/context-object-objc/TestContextObjectObjc.py --- a/lldb/test/API/commands/expression/context-object-objc/TestContextObjectObjc.py +++ b/lldb/test/API/commands/expression/context-object-objc/TestContextObjectObjc.py @@ -7,14 +7,16 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * -class ContextObjectObjcTestCase(TestBase): +class ContextObjectObjcTestCase(TestBase): @add_test_categories(["objc"]) def test_context_object_objc(self): """Tests expression evaluation in context of an objc class.""" self.build() - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, '// Break here', self.main_source_spec) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// Break here", self.main_source_spec + ) frame = thread.GetFrameAtIndex(0) # diff --git a/lldb/test/API/commands/expression/context-object/TestContextObject.py b/lldb/test/API/commands/expression/context-object/TestContextObject.py --- a/lldb/test/API/commands/expression/context-object/TestContextObject.py +++ b/lldb/test/API/commands/expression/context-object/TestContextObject.py @@ -6,13 +6,15 @@ import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * -class ContextObjectTestCase(TestBase): +class ContextObjectTestCase(TestBase): def test_context_object(self): """Tests expression evaluation in context of an object.""" self.build() - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, '// Break here', self.main_source_spec) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// Break here", self.main_source_spec + ) frame = thread.GetFrameAtIndex(0) # diff --git a/lldb/test/API/commands/expression/deleting-implicit-copy-constructor/TestDeletingImplicitCopyConstructor.py b/lldb/test/API/commands/expression/deleting-implicit-copy-constructor/TestDeletingImplicitCopyConstructor.py --- a/lldb/test/API/commands/expression/deleting-implicit-copy-constructor/TestDeletingImplicitCopyConstructor.py +++ b/lldb/test/API/commands/expression/deleting-implicit-copy-constructor/TestDeletingImplicitCopyConstructor.py @@ -1,5 +1,11 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), - [decorators.expectedFailureAll(bugnumber="llvm.org/pr50814", compiler="gcc"), decorators.expectedFailureAll(oslist=["windows"])]) +lldbinline.MakeInlineTest( + __file__, + globals(), + [ + decorators.expectedFailureAll(bugnumber="llvm.org/pr50814", compiler="gcc"), + decorators.expectedFailureAll(oslist=["windows"]), + ], +) diff --git a/lldb/test/API/commands/expression/diagnostics/TestExprDiagnostics.py b/lldb/test/API/commands/expression/diagnostics/TestExprDiagnostics.py --- a/lldb/test/API/commands/expression/diagnostics/TestExprDiagnostics.py +++ b/lldb/test/API/commands/expression/diagnostics/TestExprDiagnostics.py @@ -7,8 +7,8 @@ from lldbsuite.test import lldbutil from lldbsuite.test.decorators import * -class ExprDiagnosticsTestCase(TestBase): +class ExprDiagnosticsTestCase(TestBase): def setUp(self): # Call super's setUp(). TestBase.setUp(self) @@ -20,8 +20,9 @@ """Test that the source and caret positions LLDB prints are correct""" self.build() - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - '// Break here', self.main_source_spec) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// Break here", self.main_source_spec + ) frame = thread.GetFrameAtIndex(0) # Test that source/caret are at the right position. @@ -47,12 +48,14 @@ self.assertIn(":2:1", value.GetError().GetCString()) # Top-level expressions. - top_level_opts = lldb.SBExpressionOptions(); + top_level_opts = lldb.SBExpressionOptions() top_level_opts.SetTopLevel(True) value = frame.EvaluateExpression("void foo(unknown_type x) {}", top_level_opts) self.assertFalse(value.GetError().Success()) - self.assertIn("\nvoid foo(unknown_type x) {}\n ^\n", value.GetError().GetCString()) + self.assertIn( + "\nvoid foo(unknown_type x) {}\n ^\n", value.GetError().GetCString() + ) # Top-level expressions might use a different wrapper code, but the file name should still # be the same. self.assertIn(":1:10", value.GetError().GetCString()) @@ -64,34 +67,49 @@ self.assertIn(":2:6", value.GetError().GetCString()) # Test that we render Clang's 'notes' correctly. - value = frame.EvaluateExpression("struct SFoo{}; struct SFoo { int x; };", top_level_opts) + value = frame.EvaluateExpression( + "struct SFoo{}; struct SFoo { int x; };", top_level_opts + ) self.assertFalse(value.GetError().Success()) - self.assertIn(":1:8: previous definition is here\nstruct SFoo{}; struct SFoo { int x; };\n ^\n", value.GetError().GetCString()) + self.assertIn( + ":1:8: previous definition is here\nstruct SFoo{}; struct SFoo { int x; };\n ^\n", + value.GetError().GetCString(), + ) # Declarations from the debug information currently have no debug information. It's not clear what # we should do in this case, but we should at least not print anything that's wrong. # In the future our declarations should have valid source locations. value = frame.EvaluateExpression("struct FooBar { double x };", top_level_opts) self.assertFalse(value.GetError().Success()) - self.assertIn("error: :1:8: redefinition of 'FooBar'\nstruct FooBar { double x };\n ^\n", value.GetError().GetCString()) + self.assertIn( + "error: :1:8: redefinition of 'FooBar'\nstruct FooBar { double x };\n ^\n", + value.GetError().GetCString(), + ) value = frame.EvaluateExpression("foo(1, 2)") self.assertFalse(value.GetError().Success()) - self.assertIn("error: :1:1: no matching function for call to 'foo'\nfoo(1, 2)\n^~~\nnote: candidate function not viable: requires single argument 'x', but 2 arguments were provided\n\n", value.GetError().GetCString()) + self.assertIn( + "error: :1:1: no matching function for call to 'foo'\nfoo(1, 2)\n^~~\nnote: candidate function not viable: requires single argument 'x', but 2 arguments were provided\n\n", + value.GetError().GetCString(), + ) # Redefine something that we defined in a user-expression. We should use the previous expression file name # for the original decl. value = frame.EvaluateExpression("struct Redef { double x; };", top_level_opts) value = frame.EvaluateExpression("struct Redef { float y; };", top_level_opts) self.assertFalse(value.GetError().Success()) - self.assertIn("error: :1:8: redefinition of 'Redef'\nstruct Redef { float y; };\n ^\n:1:8: previous definition is here\nstruct Redef { double x; };\n ^", value.GetError().GetCString()) + self.assertIn( + "error: :1:8: redefinition of 'Redef'\nstruct Redef { float y; };\n ^\n:1:8: previous definition is here\nstruct Redef { double x; };\n ^", + value.GetError().GetCString(), + ) @add_test_categories(["objc"]) def test_source_locations_from_objc_modules(self): self.build() - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - '// Break here', self.main_source_spec) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// Break here", self.main_source_spec + ) frame = thread.GetFrameAtIndex(0) # Import foundation so that the Obj-C module is loaded (which contains source locations @@ -107,4 +125,3 @@ # The NSLog definition source line should be printed. Return value and # the first argument are probably stable enough that this test can check for them. self.assertIn("void NSLog(NSString *format", value.GetError().GetCString()) - diff --git a/lldb/test/API/commands/expression/dollar-in-variable/TestDollarInVariable.py b/lldb/test/API/commands/expression/dollar-in-variable/TestDollarInVariable.py --- a/lldb/test/API/commands/expression/dollar-in-variable/TestDollarInVariable.py +++ b/lldb/test/API/commands/expression/dollar-in-variable/TestDollarInVariable.py @@ -3,15 +3,19 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @expectedFailureAll(oslist=["windows"]) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", lldb.SBFileSpec("main.c")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.c") + ) self.expect_expr("$__lldb_expr_result", result_type="int", result_value="11") self.expect_expr("$foo", result_type="int", result_value="12") self.expect_expr("$R0", result_type="int", result_value="13") - self.expect("expr int $foo = 123", error=True, substrs=["declaration conflicts"]) + self.expect( + "expr int $foo = 123", error=True, substrs=["declaration conflicts"] + ) self.expect_expr("$0", result_type="int", result_value="11") diff --git a/lldb/test/API/commands/expression/dont_allow_jit/TestAllowJIT.py b/lldb/test/API/commands/expression/dont_allow_jit/TestAllowJIT.py --- a/lldb/test/API/commands/expression/dont_allow_jit/TestAllowJIT.py +++ b/lldb/test/API/commands/expression/dont_allow_jit/TestAllowJIT.py @@ -3,14 +3,13 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * -class TestAllowJIT(TestBase): +class TestAllowJIT(TestBase): # If your test case doesn't stress debug info, then # set this to true. That way it won't be run once for # each debug info format. @@ -29,27 +28,30 @@ self.expr_options_test() def expr_cmd_test(self): - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - "Set a breakpoint here", self.main_source_file) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", self.main_source_file + ) frame = thread.GetFrameAtIndex(0) - # First make sure we can call the function with + # First make sure we can call the function with interp = self.dbg.GetCommandInterpreter() - self.expect("expr --allow-jit 1 -- call_me(10)", - substrs = ["(int) $", "= 18"]) + self.expect("expr --allow-jit 1 -- call_me(10)", substrs=["(int) $", "= 18"]) # Now make sure it fails with the "can't IR interpret message" if allow-jit is false: - self.expect("expr --allow-jit 0 -- call_me(10)", - error=True, - substrs = ["Can't evaluate the expression without a running target"]) + self.expect( + "expr --allow-jit 0 -- call_me(10)", + error=True, + substrs=["Can't evaluate the expression without a running target"], + ) def expr_options_test(self): - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - "Set a breakpoint here", self.main_source_file) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", self.main_source_file + ) frame = thread.GetFrameAtIndex(0) - # First make sure we can call the function with the default option set. + # First make sure we can call the function with the default option set. options = lldb.SBExpressionOptions() # Check that the default is to allow JIT: self.assertEqual(options.GetAllowJIT(), True, "Default is true") @@ -62,12 +64,18 @@ # Now disallow JIT and make sure it fails: options.SetAllowJIT(False) # Check that we got the right value: - self.assertEqual(options.GetAllowJIT(), False, "Got False after setting to False") + self.assertEqual( + options.GetAllowJIT(), False, "Got False after setting to False" + ) # Again use it and ensure we fail: result = frame.EvaluateExpression("call_me(10)", options) self.assertTrue(result.GetError().Fail(), "expression failed with no JIT") - self.assertIn("Can't evaluate the expression without a running target", result.GetError().GetCString(), "Got right error") + self.assertIn( + "Can't evaluate the expression without a running target", + result.GetError().GetCString(), + "Got right error", + ) # Finally set the allow JIT value back to true and make sure that works: options.SetAllowJIT(True) @@ -82,12 +90,19 @@ """Test combined --allow-jit and --top-level flags""" # Can't force interpreting for top-level expressions which are always # injected. - self.expect("expr --allow-jit false --top-level -- int i;", error=True, - substrs=["Can't disable JIT compilation for top-level expressions."]) + self.expect( + "expr --allow-jit false --top-level -- int i;", + error=True, + substrs=["Can't disable JIT compilation for top-level expressions."], + ) self.build() - lldbutil.run_to_source_breakpoint(self, "Set a breakpoint here", lldb.SBFileSpec("main.c")) + lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", lldb.SBFileSpec("main.c") + ) # Allowing JITing for top-level expressions is redundant but should work. - self.expect("expr --allow-jit true --top-level -- int top_level_f() { return 2; }") + self.expect( + "expr --allow-jit true --top-level -- int top_level_f() { return 2; }" + ) # Make sure we actually declared a working top-level function. self.expect_expr("top_level_f()", result_value="2") diff --git a/lldb/test/API/commands/expression/entry-bp/TestExprEntryBP.py b/lldb/test/API/commands/expression/entry-bp/TestExprEntryBP.py --- a/lldb/test/API/commands/expression/entry-bp/TestExprEntryBP.py +++ b/lldb/test/API/commands/expression/entry-bp/TestExprEntryBP.py @@ -6,8 +6,8 @@ import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * -class ExprEntryBPTestCase(TestBase): +class ExprEntryBPTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True def test_expr_entry_bp(self): @@ -15,13 +15,22 @@ self.build() self.main_source_file = lldb.SBFileSpec("main.c") - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, "Set a breakpoint here", self.main_source_file) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", self.main_source_file + ) self.assertEqual(1, bkpt.GetNumLocations()) - entry = bkpt.GetLocationAtIndex(0).GetAddress().GetModule().GetObjectFileEntryPointAddress() + entry = ( + bkpt.GetLocationAtIndex(0) + .GetAddress() + .GetModule() + .GetObjectFileEntryPointAddress() + ) self.assertTrue(entry.IsValid(), "Can't get a module entry point") entry_bp = target.BreakpointCreateBySBAddress(entry) - self.assertTrue(entry_bp.IsValid(), "Can't set a breakpoint on the module entry point") + self.assertTrue( + entry_bp.IsValid(), "Can't set a breakpoint on the module entry point" + ) self.expect_expr("sum(7, 1)", result_type="int", result_value="8") diff --git a/lldb/test/API/commands/expression/error-limit/TestExprErrorLimit.py b/lldb/test/API/commands/expression/error-limit/TestExprErrorLimit.py --- a/lldb/test/API/commands/expression/error-limit/TestExprErrorLimit.py +++ b/lldb/test/API/commands/expression/error-limit/TestExprErrorLimit.py @@ -9,7 +9,6 @@ class TestCase(TestBase): - @no_debug_info_test def test(self): # FIXME: The only reason this test needs to create a real target is because diff --git a/lldb/test/API/commands/expression/expr-in-syscall/TestExpressionInSyscall.py b/lldb/test/API/commands/expression/expr-in-syscall/TestExpressionInSyscall.py --- a/lldb/test/API/commands/expression/expr-in-syscall/TestExpressionInSyscall.py +++ b/lldb/test/API/commands/expression/expr-in-syscall/TestExpressionInSyscall.py @@ -7,10 +7,10 @@ class ExprSyscallTestCase(TestBase): - @expectedFailureAll( oslist=["windows"], - bugnumber="llvm.org/pr21765, getpid() does not exist on Windows") + bugnumber="llvm.org/pr21765, getpid() does not exist on Windows", + ) @expectedFailureNetBSD def test_setpgid(self): self.build() @@ -26,16 +26,18 @@ self.dbg.SetAsync(True) error = lldb.SBError() flags = target.GetLaunchInfo().GetLaunchFlags() - process = target.Launch(listener, - None, # argv - None, # envp - None, # stdin_path - None, # stdout_path - None, # stderr_path - None, # working directory - flags, # launch flags - False, # Stop at entry - error) # error + process = target.Launch( + listener, + None, # argv + None, # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working directory + flags, # launch flags + False, # Stop at entry + error, + ) # error self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) @@ -48,10 +50,7 @@ pass # now the process should be running (blocked in the syscall) - self.assertEqual( - process.GetState(), - lldb.eStateRunning, - "Process is running") + self.assertEqual(process.GetState(), lldb.eStateRunning, "Process is running") # send the process a signal process.SendAsyncInterrupt() @@ -61,10 +60,7 @@ # as a result the process should stop # in all likelihood we have stopped in the middle of the sleep() # syscall - self.assertEqual( - process.GetState(), - lldb.eStateStopped, - PROCESS_STOPPED) + self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) thread = process.GetSelectedThread() # try evaluating a couple of expressions in this state diff --git a/lldb/test/API/commands/expression/expr_inside_lambda/TestExprInsideLambdas.py b/lldb/test/API/commands/expression/expr_inside_lambda/TestExprInsideLambdas.py --- a/lldb/test/API/commands/expression/expr_inside_lambda/TestExprInsideLambdas.py +++ b/lldb/test/API/commands/expression/expr_inside_lambda/TestExprInsideLambdas.py @@ -10,8 +10,7 @@ class ExprInsideLambdaTestCase(TestBase): - - def expectExprError(self, expr : str, expected : str): + def expectExprError(self, expr: str, expected: str): frame = self.thread.GetFrameAtIndex(0) value = frame.EvaluateExpression(expr) errmsg = value.GetError().GetCString() @@ -20,8 +19,9 @@ def test_expr_inside_lambda(self): """Test that lldb evaluating expressions inside lambda expressions works correctly.""" self.build() - (target, process, self.thread, bkpt) = \ - lldbutil.run_to_source_breakpoint(self, "break here", lldb.SBFileSpec("main.cpp")) + (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "break here", lldb.SBFileSpec("main.cpp") + ) # Inside 'Foo::method' @@ -46,14 +46,17 @@ self.expect_expr("global_var", result_type="int", result_value="-5") # Check access to multiple captures/member variables - self.expect_expr("(shadowed + this->shadowed) * (base_base_var + local_var - class_var)", - result_type="int", result_value="-5148") + self.expect_expr( + "(shadowed + this->shadowed) * (base_base_var + local_var - class_var)", + result_type="int", + result_value="-5148", + ) # Check base-class function call self.expect_expr("baz_virt()", result_type="int", result_value="2") self.expect_expr("base_var", result_type="int", result_value="14") self.expect_expr("this->shadowed", result_type="int", result_value="-1") - + # 'p this' should yield 'struct Foo*' frame = self.thread.GetFrameAtIndex(0) outer_class_addr = frame.GetValueForVariablePath("this->this") @@ -62,7 +65,7 @@ lldbutil.continue_to_breakpoint(process, bkpt) # Inside 'nested_lambda' - + # Check access to captured 'this'. Should still be 'struct Foo*' self.expect_expr("class_var", result_type="int", result_value="109") self.expect_expr("global_var", result_type="int", result_value="-5") @@ -90,7 +93,9 @@ # Check access to captured 'this' self.expect_expr("lambda_class_local", result_type="int", result_value="-12345") - self.expect_expr("this->lambda_class_local", result_type="int", result_value="-12345") + self.expect_expr( + "this->lambda_class_local", result_type="int", result_value="-12345" + ) self.expect_expr("outer_ptr->class_var", result_type="int", result_value="109") # 'p this' should yield 'struct LocalLambdaClass*' @@ -103,14 +108,22 @@ self.expect_expr("global_var", result_type="int", result_value="-5") # Check access to outer top-level structure's members - self.expectExprError("class_var", ("use of non-static data member" - " 'class_var' of 'Foo' from nested type")) - - self.expectExprError("base_var", ("use of non-static data member" - " 'base_var'")) - - self.expectExprError("local_var", ("use of non-static data member 'local_var'" - " of '(unnamed class)' from nested type 'LocalLambdaClass'")) + self.expectExprError( + "class_var", + ("use of non-static data member" " 'class_var' of 'Foo' from nested type"), + ) + + self.expectExprError( + "base_var", ("use of non-static data member" " 'base_var'") + ) + + self.expectExprError( + "local_var", + ( + "use of non-static data member 'local_var'" + " of '(unnamed class)' from nested type 'LocalLambdaClass'" + ), + ) # Inside non_capturing_method lldbutil.continue_to_breakpoint(process, bkpt) @@ -118,5 +131,7 @@ self.expect_expr("local2", result_type="int", result_value="10") self.expect_expr("local2 * local", result_type="int", result_value="50") - self.expectExprError("class_var", ("use of non-static data member" - " 'class_var' of 'Foo' from nested type")) + self.expectExprError( + "class_var", + ("use of non-static data member" " 'class_var' of 'Foo' from nested type"), + ) diff --git a/lldb/test/API/commands/expression/fixits/TestFixIts.py b/lldb/test/API/commands/expression/fixits/TestFixIts.py --- a/lldb/test/API/commands/expression/fixits/TestFixIts.py +++ b/lldb/test/API/commands/expression/fixits/TestFixIts.py @@ -9,7 +9,6 @@ class ExprCommandWithFixits(TestBase): - def test_with_dummy_target(self): """Test calling expressions in the dummy target with errors that can be fixed by the FixIts.""" @@ -17,16 +16,20 @@ self.runCmd("settings set target.auto-apply-fixits true") ret_val = lldb.SBCommandReturnObject() - result = self.dbg.GetCommandInterpreter().HandleCommand("expression ((1 << 16) - 1))", ret_val) - self.assertEqual(result, lldb.eReturnStatusSuccessFinishResult, ret_val.GetError()) + result = self.dbg.GetCommandInterpreter().HandleCommand( + "expression ((1 << 16) - 1))", ret_val + ) + self.assertEqual( + result, lldb.eReturnStatusSuccessFinishResult, ret_val.GetError() + ) self.assertIn("Fix-it applied", ret_val.GetError()) def test_with_target(self): """Test calling expressions with errors that can be fixed by the FixIts.""" self.build() - (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - 'Stop here to evaluate expressions', - lldb.SBFileSpec("main.cpp")) + (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Stop here to evaluate expressions", lldb.SBFileSpec("main.cpp") + ) options = lldb.SBExpressionOptions() options.SetAutoApplyFixIts(True) @@ -62,7 +65,7 @@ # Try a Fix-It that is stored in the 'note:' diagnostic of an error. # The Fix-It here is adding parantheses around the ToStr parameters. - fixit_in_note_expr ="#define ToStr(x) #x\nToStr(0 {, })" + fixit_in_note_expr = "#define ToStr(x) #x\nToStr(0 {, })" value = frame.EvaluateExpression(fixit_in_note_expr, options) self.assertTrue(value.IsValid()) self.assertSuccess(value.GetError()) @@ -75,37 +78,40 @@ self.assertTrue(value.GetError().Fail()) error_string = value.GetError().GetCString() self.assertTrue( - error_string.find("fixed expression suggested:") != -1, - "Fix was suggested") + error_string.find("fixed expression suggested:") != -1, "Fix was suggested" + ) self.assertTrue( - error_string.find("my_pointer->second.a") != -1, - "Fix was right") + error_string.find("my_pointer->second.a") != -1, "Fix was right" + ) def test_with_target_error_applies_fixit(self): - """ Check that applying a Fix-it which fails to execute correctly still - prints that the Fix-it was applied. """ + """Check that applying a Fix-it which fails to execute correctly still + prints that the Fix-it was applied.""" self.build() - (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - 'Stop here to evaluate expressions', - lldb.SBFileSpec("main.cpp")) + (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Stop here to evaluate expressions", lldb.SBFileSpec("main.cpp") + ) # Enable fix-its as they were intentionally disabled by TestBase.setUp. self.runCmd("settings set target.auto-apply-fixits true") ret_val = lldb.SBCommandReturnObject() - result = self.dbg.GetCommandInterpreter().HandleCommand("expression null_pointer.first", ret_val) + result = self.dbg.GetCommandInterpreter().HandleCommand( + "expression null_pointer.first", ret_val + ) self.assertEqual(result, lldb.eReturnStatusFailed, ret_val.GetError()) self.assertIn("Fix-it applied, fixed expression was:", ret_val.GetError()) self.assertIn("null_pointer->first", ret_val.GetError()) # The final function call runs into SIGILL on aarch64-linux. - @expectedFailureAll(archs=["aarch64"], oslist=["freebsd", "linux"], - bugnumber="llvm.org/pr49407") + @expectedFailureAll( + archs=["aarch64"], oslist=["freebsd", "linux"], bugnumber="llvm.org/pr49407" + ) def test_with_multiple_retries(self): """Test calling expressions with errors that can be fixed by the FixIts.""" self.build() - (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - 'Stop here to evaluate expressions', - lldb.SBFileSpec("main.cpp")) + (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Stop here to evaluate expressions", lldb.SBFileSpec("main.cpp") + ) # Test repeatedly applying Fix-Its to expressions and reparsing them. multiple_runs_options = lldb.SBExpressionOptions() @@ -149,8 +155,7 @@ value = frame.EvaluateExpression(two_runs_expr, multiple_runs_options) errmsg = value.GetError().GetCString() self.assertIn("expression failed to parse", errmsg) - self.assertIn("using declaration resolved to type without 'typename'", - errmsg) + self.assertIn("using declaration resolved to type without 'typename'", errmsg) self.assertIn("fixed expression suggested:", errmsg) self.assertIn("using typename T::TypeDef", errmsg) # The second Fix-It shouldn't be suggested here as Clang should have diff --git a/lldb/test/API/commands/expression/formatters/TestFormatters.py b/lldb/test/API/commands/expression/formatters/TestFormatters.py --- a/lldb/test/API/commands/expression/formatters/TestFormatters.py +++ b/lldb/test/API/commands/expression/formatters/TestFormatters.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,16 +10,14 @@ class ExprFormattersTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.cpp. - self.line = line_number('main.cpp', - '// Stop here') + self.line = line_number("main.cpp", "// Stop here") @skipIfTargetAndroid() # skipping to avoid crashing the test runner - @expectedFailureAndroid('llvm.org/pr24691') # we hit an assertion in clang + @expectedFailureAndroid("llvm.org/pr24691") # we hit an assertion in clang def test(self): """Test expr + formatters for good interoperability.""" self.build() @@ -28,8 +25,8 @@ # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type summary clear', check=False) - self.runCmd('type synthetic clear', check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synthetic clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -38,7 +35,8 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, loc_exact=True) + self, "main.cpp", self.line, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) self.runCmd("command script import formatters.py") @@ -49,8 +47,11 @@ self.runCmd("frame variable foo1.b --show-types") self.runCmd("frame variable foo1.b.b_ref --show-types") - self.filecheck("expression --show-types -- *(new_foo(47))", __file__, - '-check-prefix=EXPR-TYPES-NEW-FOO') + self.filecheck( + "expression --show-types -- *(new_foo(47))", + __file__, + "-check-prefix=EXPR-TYPES-NEW-FOO", + ) # EXPR-TYPES-NEW-FOO: (foo) ${{.*}} = { # EXPR-TYPES-NEW-FOO-NEXT: (int) a = 47 # EXPR-TYPES-NEW-FOO-NEXT: (int *) a_ptr = 0x @@ -65,9 +66,8 @@ # EXPR-TYPES-NEW-FOO-NEXT: } # EXPR-TYPES-NEW-FOO-NEXT: } - self.runCmd("type summary add -F formatters.foo_SummaryProvider3 foo") - self.filecheck("expression foo1", __file__, '-check-prefix=EXPR-FOO1opts') + self.filecheck("expression foo1", __file__, "-check-prefix=EXPR-FOO1opts") # EXPR-FOO1opts: (foo) $ # EXPR-FOO1opts-SAME: a = 12 # EXPR-FOO1opts-SAME: a_ptr = {{[0-9]+}} -> 13 @@ -82,19 +82,15 @@ self.runCmd("type summary add -F formatters.foo_SummaryProvider foo") - self.expect("expression new_int(12)", - substrs=['(int *) $', ' = 0x']) + self.expect("expression new_int(12)", substrs=["(int *) $", " = 0x"]) - self.runCmd( - "type summary add -s \"${var%pointer} -> ${*var%decimal}\" \"int *\"") + self.runCmd('type summary add -s "${var%pointer} -> ${*var%decimal}" "int *"') - self.expect("expression new_int(12)", - substrs=['(int *) $', '= 0x', ' -> 12']) + self.expect("expression new_int(12)", substrs=["(int *) $", "= 0x", " -> 12"]) - self.expect("expression foo1.a_ptr", - substrs=['(int *) $', '= 0x', ' -> 13']) + self.expect("expression foo1.a_ptr", substrs=["(int *) $", "= 0x", " -> 13"]) - self.filecheck("expression foo1", __file__, '-check-prefix=EXPR-FOO1') + self.filecheck("expression foo1", __file__, "-check-prefix=EXPR-FOO1") # EXPR-FOO1: (foo) $ # EXPR-FOO1-SAME: a = 12 # EXPR-FOO1-SAME: a_ptr = {{[0-9]+}} -> 13 @@ -104,15 +100,18 @@ # EXPR-FOO1-SAME: h = 27 # EXPR-FOO1-SAME: k = 29 - self.filecheck("expression --ptr-depth=1 -- new_foo(47)", __file__, - '-check-prefix=EXPR-PTR-DEPTH1') + self.filecheck( + "expression --ptr-depth=1 -- new_foo(47)", + __file__, + "-check-prefix=EXPR-PTR-DEPTH1", + ) # EXPR-PTR-DEPTH1: (foo *) $ # EXPR-PTR-DEPTH1-SAME: a = 47 # EXPR-PTR-DEPTH1-SAME: a_ptr = {{[0-9]+}} -> 48 # EXPR-PTR-DEPTH1-SAME: i = 94 # EXPR-PTR-DEPTH1-SAME: i_ptr = {{[0-9]+}} -> 95 - self.filecheck("expression foo2", __file__, '-check-prefix=EXPR-FOO2') + self.filecheck("expression foo2", __file__, "-check-prefix=EXPR-FOO2") # EXPR-FOO2: (foo) $ # EXPR-FOO2-SAME: a = 121 # EXPR-FOO2-SAME: a_ptr = {{[0-9]+}} -> 122 @@ -123,9 +122,9 @@ object_name = self.res.GetOutput() object_name = object_name[7:] - object_name = object_name[0:object_name.find(' =')] + object_name = object_name[0 : object_name.find(" =")] - self.filecheck("frame variable foo2", __file__, '-check-prefix=VAR-FOO2') + self.filecheck("frame variable foo2", __file__, "-check-prefix=VAR-FOO2") # VAR-FOO2: (foo) foo2 # VAR-FOO2-SAME: a = 121 # VAR-FOO2-SAME: a_ptr = {{[0-9]+}} -> 122 @@ -135,15 +134,19 @@ # VAR-FOO2-SAME: k = 247 # The object is the same as foo2, so use the EXPR-FOO2 checks. - self.filecheck("expression $" + object_name, __file__, - '-check-prefix=EXPR-FOO2') + self.filecheck( + "expression $" + object_name, __file__, "-check-prefix=EXPR-FOO2" + ) self.runCmd("type summary delete foo") self.runCmd( - "type synthetic add --python-class foosynth.FooSyntheticProvider foo") + "type synthetic add --python-class foosynth.FooSyntheticProvider foo" + ) - self.expect("expression --show-types -- $" + object_name, - substrs=['(foo) $', ' = {', '(int) *i_ptr = 243']) + self.expect( + "expression --show-types -- $" + object_name, + substrs=["(foo) $", " = {", "(int) *i_ptr = 243"], + ) self.runCmd("n") self.runCmd("n") @@ -154,40 +157,44 @@ self.expect( "expression foo2", substrs=[ - '(foo) $', - 'a = 7777', - 'a_ptr = ', - ' -> 122', - 'i = 242', - 'i_ptr = ', - ' -> 8888']) + "(foo) $", + "a = 7777", + "a_ptr = ", + " -> 122", + "i = 242", + "i_ptr = ", + " -> 8888", + ], + ) - self.expect("expression $" + object_name + '.a', - substrs=['7777']) + self.expect("expression $" + object_name + ".a", substrs=["7777"]) - self.expect("expression *$" + object_name + '.b.i_ptr', - substrs=['8888']) + self.expect("expression *$" + object_name + ".b.i_ptr", substrs=["8888"]) self.expect( - "expression $" + - object_name, + "expression $" + object_name, substrs=[ - '(foo) $', - 'a = 121', - 'a_ptr = ', - ' -> 122', - 'i = 242', - 'i_ptr = ', - ' -> 8888', - 'h = 245', - 'k = 247']) + "(foo) $", + "a = 121", + "a_ptr = ", + " -> 122", + "i = 242", + "i_ptr = ", + " -> 8888", + "h = 245", + "k = 247", + ], + ) self.runCmd("type summary delete foo") self.runCmd( - "type synthetic add --python-class foosynth.FooSyntheticProvider foo") + "type synthetic add --python-class foosynth.FooSyntheticProvider foo" + ) - self.expect("expression --show-types -- $" + object_name, - substrs=['(foo) $', ' = {', '(int) *i_ptr = 8888']) + self.expect( + "expression --show-types -- $" + object_name, + substrs=["(foo) $", " = {", "(int) *i_ptr = 8888"], + ) self.runCmd("n") @@ -195,17 +202,18 @@ self.runCmd("type summary add -F formatters.foo_SummaryProvider foo") self.expect( - "expression $" + - object_name, + "expression $" + object_name, substrs=[ - '(foo) $', - 'a = 121', - 'a_ptr = ', - ' -> 122', - 'i = 242', - 'i_ptr = ', - ' -> 8888', - 'k = 247']) + "(foo) $", + "a = 121", + "a_ptr = ", + " -> 122", + "i = 242", + "i_ptr = ", + " -> 8888", + "k = 247", + ], + ) process = self.dbg.GetSelectedTarget().GetProcess() thread = process.GetThreadAtIndex(0) @@ -216,55 +224,31 @@ a_data = frozen.GetPointeeData() error = lldb.SBError() - self.assertEqual( - a_data.GetUnsignedInt32(error, 0), 122, - '*a_ptr = 122') + self.assertEqual(a_data.GetUnsignedInt32(error, 0), 122, "*a_ptr = 122") ret = line_number("main.cpp", "Done initializing") self.runCmd("thread until " + str(ret)) - self.expect("frame variable numbers", - substrs=['1', '2', '3', '4', '5']) + self.expect("frame variable numbers", substrs=["1", "2", "3", "4", "5"]) - self.expect("expression numbers", - substrs=['1', '2', '3', '4', '5']) + self.expect("expression numbers", substrs=["1", "2", "3", "4", "5"]) frozen = frame.EvaluateExpression("&numbers") a_data = frozen.GetPointeeData(0, 1) - self.assertEqual( - a_data.GetUnsignedInt32(error, 0), 1, - 'numbers[0] == 1') - self.assertEqual( - a_data.GetUnsignedInt32(error, 4), 2, - 'numbers[1] == 2') - self.assertEqual( - a_data.GetUnsignedInt32(error, 8), 3, - 'numbers[2] == 3') - self.assertEqual( - a_data.GetUnsignedInt32(error, 12), 4, - 'numbers[3] == 4') - self.assertEqual( - a_data.GetUnsignedInt32(error, 16), 5, - 'numbers[4] == 5') + self.assertEqual(a_data.GetUnsignedInt32(error, 0), 1, "numbers[0] == 1") + self.assertEqual(a_data.GetUnsignedInt32(error, 4), 2, "numbers[1] == 2") + self.assertEqual(a_data.GetUnsignedInt32(error, 8), 3, "numbers[2] == 3") + self.assertEqual(a_data.GetUnsignedInt32(error, 12), 4, "numbers[3] == 4") + self.assertEqual(a_data.GetUnsignedInt32(error, 16), 5, "numbers[4] == 5") frozen = frame.EvaluateExpression("numbers") a_data = frozen.GetData() - self.assertEqual( - a_data.GetUnsignedInt32(error, 0), 1, - 'numbers[0] == 1') - self.assertEqual( - a_data.GetUnsignedInt32(error, 4), 2, - 'numbers[1] == 2') - self.assertEqual( - a_data.GetUnsignedInt32(error, 8), 3, - 'numbers[2] == 3') - self.assertEqual( - a_data.GetUnsignedInt32(error, 12), 4, - 'numbers[3] == 4') - self.assertEqual( - a_data.GetUnsignedInt32(error, 16), 5, - 'numbers[4] == 5') + self.assertEqual(a_data.GetUnsignedInt32(error, 0), 1, "numbers[0] == 1") + self.assertEqual(a_data.GetUnsignedInt32(error, 4), 2, "numbers[1] == 2") + self.assertEqual(a_data.GetUnsignedInt32(error, 8), 3, "numbers[2] == 3") + self.assertEqual(a_data.GetUnsignedInt32(error, 12), 4, "numbers[3] == 4") + self.assertEqual(a_data.GetUnsignedInt32(error, 16), 5, "numbers[4] == 5") diff --git a/lldb/test/API/commands/expression/formatters/foosynth.py b/lldb/test/API/commands/expression/formatters/foosynth.py --- a/lldb/test/API/commands/expression/formatters/foosynth.py +++ b/lldb/test/API/commands/expression/formatters/foosynth.py @@ -2,7 +2,6 @@ class FooSyntheticProvider: - def __init__(self, valobj, dict): self.valobj = valobj self.update() @@ -24,10 +23,10 @@ return None def adjust_for_architecture(self): - self.lp64 = ( - self.valobj.GetTarget().GetProcess().GetAddressByteSize() == 8) - self.is_little = (self.valobj.GetTarget().GetProcess( - ).GetByteOrder() == lldb.eByteOrderLittle) + self.lp64 = self.valobj.GetTarget().GetProcess().GetAddressByteSize() == 8 + self.is_little = ( + self.valobj.GetTarget().GetProcess().GetByteOrder() == lldb.eByteOrderLittle + ) self.pointer_size = self.valobj.GetTarget().GetProcess().GetAddressByteSize() - self.bar = self.valobj.GetChildMemberWithName('b') - self.i_ptr = self.bar.GetChildMemberWithName('i_ptr') + self.bar = self.valobj.GetChildMemberWithName("b") + self.i_ptr = self.bar.GetChildMemberWithName("i_ptr") diff --git a/lldb/test/API/commands/expression/formatters/formatters.py b/lldb/test/API/commands/expression/formatters/formatters.py --- a/lldb/test/API/commands/expression/formatters/formatters.py +++ b/lldb/test/API/commands/expression/formatters/formatters.py @@ -1,24 +1,40 @@ import lldb + def foo_SummaryProvider(valobj, dict): - a = valobj.GetChildMemberWithName('a') - a_ptr = valobj.GetChildMemberWithName('a_ptr') - bar = valobj.GetChildMemberWithName('b') - i = bar.GetChildMemberWithName('i') - i_ptr = bar.GetChildMemberWithName('i_ptr') - b_ref = bar.GetChildMemberWithName('b_ref') + a = valobj.GetChildMemberWithName("a") + a_ptr = valobj.GetChildMemberWithName("a_ptr") + bar = valobj.GetChildMemberWithName("b") + i = bar.GetChildMemberWithName("i") + i_ptr = bar.GetChildMemberWithName("i_ptr") + b_ref = bar.GetChildMemberWithName("b_ref") b_ref_ptr = b_ref.AddressOf() b_ref = b_ref_ptr.Dereference() - h = b_ref.GetChildMemberWithName('h') - k = b_ref.GetChildMemberWithName('k') - return 'a = ' + str(a.GetValueAsUnsigned(0)) + ', a_ptr = ' + \ - str(a_ptr.GetValueAsUnsigned(0)) + ' -> ' + str(a_ptr.Dereference().GetValueAsUnsigned(0)) + \ - ', i = ' + str(i.GetValueAsUnsigned(0)) + \ - ', i_ptr = ' + str(i_ptr.GetValueAsUnsigned(0)) + ' -> ' + str(i_ptr.Dereference().GetValueAsUnsigned(0)) + \ - ', b_ref = ' + str(b_ref.GetValueAsUnsigned(0)) + \ - ', h = ' + str(h.GetValueAsUnsigned(0)) + ' , k = ' + str(k.GetValueAsUnsigned(0)) + h = b_ref.GetChildMemberWithName("h") + k = b_ref.GetChildMemberWithName("k") + return ( + "a = " + + str(a.GetValueAsUnsigned(0)) + + ", a_ptr = " + + str(a_ptr.GetValueAsUnsigned(0)) + + " -> " + + str(a_ptr.Dereference().GetValueAsUnsigned(0)) + + ", i = " + + str(i.GetValueAsUnsigned(0)) + + ", i_ptr = " + + str(i_ptr.GetValueAsUnsigned(0)) + + " -> " + + str(i_ptr.Dereference().GetValueAsUnsigned(0)) + + ", b_ref = " + + str(b_ref.GetValueAsUnsigned(0)) + + ", h = " + + str(h.GetValueAsUnsigned(0)) + + " , k = " + + str(k.GetValueAsUnsigned(0)) + ) + def foo_SummaryProvider3(valobj, dict, options): if not isinstance(options, lldb.SBTypeSummaryOptions): raise Exception() - return foo_SummaryProvider(valobj, dict) + ", WITH_OPTS" \ No newline at end of file + return foo_SummaryProvider(valobj, dict) + ", WITH_OPTS" diff --git a/lldb/test/API/commands/expression/function_template_specialization_temp_args/TestFunctionTemplateSpecializationTempArgs.py b/lldb/test/API/commands/expression/function_template_specialization_temp_args/TestFunctionTemplateSpecializationTempArgs.py --- a/lldb/test/API/commands/expression/function_template_specialization_temp_args/TestFunctionTemplateSpecializationTempArgs.py +++ b/lldb/test/API/commands/expression/function_template_specialization_temp_args/TestFunctionTemplateSpecializationTempArgs.py @@ -3,13 +3,14 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestFunctionTemplateSpecializationTempArgs(TestBase): - @skipIf(oslist=['windows'], archs=['aarch64']) +class TestFunctionTemplateSpecializationTempArgs(TestBase): + @skipIf(oslist=["windows"], archs=["aarch64"]) def test_function_template_specialization_temp_args(self): self.build() - (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp", False)) + (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) self.expect_expr("p0", result_type="VType", result_children=[]) diff --git a/lldb/test/API/commands/expression/ignore-artificial-constructors/TestIgnoreArtificialConstructors.py b/lldb/test/API/commands/expression/ignore-artificial-constructors/TestIgnoreArtificialConstructors.py --- a/lldb/test/API/commands/expression/ignore-artificial-constructors/TestIgnoreArtificialConstructors.py +++ b/lldb/test/API/commands/expression/ignore-artificial-constructors/TestIgnoreArtificialConstructors.py @@ -1,5 +1,8 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [lldbinline.expectedFailureAll( - oslist=["windows"], bugnumber="llvm.org/pr43707")]) +lldbinline.MakeInlineTest( + __file__, + globals(), + [lldbinline.expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr43707")], +) diff --git a/lldb/test/API/commands/expression/import-std-module/array/TestArrayFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/array/TestArrayFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/array/TestArrayFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/array/TestArrayFromStdModule.py @@ -8,15 +8,14 @@ class TestCase(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") @@ -27,15 +26,20 @@ # Test inspecting an array of integers. array_type = "std::array" - self.expect_expr("a", - result_type=array_type, - result_children=[ - ValueCheck(name="__elems_", children=[ - ValueCheck(value="3"), - ValueCheck(value="1"), - ValueCheck(value="2"), - ]) - ]) + self.expect_expr( + "a", + result_type=array_type, + result_children=[ + ValueCheck( + name="__elems_", + children=[ + ValueCheck(value="3"), + ValueCheck(value="1"), + ValueCheck(value="2"), + ], + ) + ], + ) self.expect_expr("a.size()", result_type=size_type, result_value="3") self.expect_expr("a.front()", result_type=value_type, result_value="3") self.expect_expr("a[1]", result_type=value_type, result_value="1") @@ -50,29 +54,39 @@ self.expect_expr("a.at(0)", result_type=value_type, result_value="3") - # Same again with an array that has an element type from debug info. array_type = "std::array" dbg_info_elem_children = [ValueCheck(value="4")] dbg_info_elem = [ValueCheck(children=dbg_info_elem_children)] - self.expect_expr("b", - result_type=array_type, - result_children=[ - ValueCheck(name="__elems_", children=dbg_info_elem) - ]) + self.expect_expr( + "b", + result_type=array_type, + result_children=[ValueCheck(name="__elems_", children=dbg_info_elem)], + ) self.expect_expr("b.size()", result_type=size_type, result_value="1") - self.expect_expr("b.front()", result_type=value_type, result_children=dbg_info_elem_children) - self.expect_expr("b[0]", result_type=value_type, result_children=dbg_info_elem_children) - self.expect_expr("b.back()", result_type=value_type, result_children=dbg_info_elem_children) + self.expect_expr( + "b.front()", result_type=value_type, result_children=dbg_info_elem_children + ) + self.expect_expr( + "b[0]", result_type=value_type, result_children=dbg_info_elem_children + ) + self.expect_expr( + "b.back()", result_type=value_type, result_children=dbg_info_elem_children + ) # Both are just pointers to the underlying elements. self.expect_expr("b.begin()", result_type=iterator) self.expect_expr("b.rbegin()", result_type=riterator) - self.expect_expr("*b.begin()", result_type=value_type, result_children=dbg_info_elem_children) - self.expect_expr("*b.rbegin()", result_type="DbgInfo", result_children=dbg_info_elem_children) - - self.expect_expr("b.at(0)", result_type=value_type, result_children=dbg_info_elem_children) + self.expect_expr( + "*b.begin()", result_type=value_type, result_children=dbg_info_elem_children + ) + self.expect_expr( + "*b.rbegin()", result_type="DbgInfo", result_children=dbg_info_elem_children + ) + self.expect_expr( + "b.at(0)", result_type=value_type, result_children=dbg_info_elem_children + ) diff --git a/lldb/test/API/commands/expression/import-std-module/basic/TestImportStdModule.py b/lldb/test/API/commands/expression/import-std-module/basic/TestImportStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/basic/TestImportStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/basic/TestImportStdModule.py @@ -8,43 +8,42 @@ class ImportStdModule(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) # Activate importing of std module. self.runCmd("settings set target.import-std-module true") # Calling some normal std functions that return non-template types. self.expect_expr("std::abs(-42)", result_type="int", result_value="42") - self.expect_expr("std::minmax(1, 2).first", result_type="const int", - result_value="1") - self.expect_expr("std::div(2, 1).quot", - result_type="int", - result_value="2") + self.expect_expr( + "std::minmax(1, 2).first", result_type="const int", result_value="1" + ) + self.expect_expr("std::div(2, 1).quot", result_type="int", result_value="2") # Using types from std. - self.expect_expr("(std::size_t)33U", - result_type="std::size_t", - result_value="33") + self.expect_expr( + "(std::size_t)33U", result_type="std::size_t", result_value="33" + ) # Calling templated functions that return non-template types. self.expect_expr( "char char_a = 'b'; char char_b = 'a'; std::swap(char_a, char_b); char_a", result_type="char", - result_value="'a'") + result_value="'a'", + ) @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test_non_cpp_language(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) # Activate importing of std module. self.runCmd("settings set target.import-std-module true") diff --git a/lldb/test/API/commands/expression/import-std-module/conflicts/TestStdModuleWithConflicts.py b/lldb/test/API/commands/expression/import-std-module/conflicts/TestStdModuleWithConflicts.py --- a/lldb/test/API/commands/expression/import-std-module/conflicts/TestStdModuleWithConflicts.py +++ b/lldb/test/API/commands/expression/import-std-module/conflicts/TestStdModuleWithConflicts.py @@ -13,24 +13,22 @@ class TestImportStdModuleConflicts(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") self.expect_expr("std::abs(-42)", result_type="int", result_value="42") - self.expect_expr("std::div(2, 1).quot", - result_type="int", - result_value="2") - self.expect_expr("(std::size_t)33U", - result_type="std::size_t", - result_value="33") + self.expect_expr("std::div(2, 1).quot", result_type="int", result_value="2") + self.expect_expr( + "(std::size_t)33U", result_type="std::size_t", result_value="33" + ) self.expect( "expr char char_a = 'b'; char char_b = 'a'; std::swap(char_a, char_b); char_a", - substrs=["(char) $3 = 'a'"]) + substrs=["(char) $3 = 'a'"], + ) diff --git a/lldb/test/API/commands/expression/import-std-module/deque-basic/TestDequeFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/deque-basic/TestDequeFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/deque-basic/TestDequeFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/deque-basic/TestDequeFromStdModule.py @@ -8,19 +8,20 @@ class TestBasicDeque(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): deque_type = "std::deque" else: deque_type = "std::deque >" @@ -28,23 +29,22 @@ size_type = "size_type" value_type = "value_type" iterator = "iterator" - iterator_children = [ - ValueCheck(name="__m_iter_"), - ValueCheck(name="__ptr_") - ] + iterator_children = [ValueCheck(name="__m_iter_"), ValueCheck(name="__ptr_")] riterator = "reverse_iterator" riterator_children = [ - ValueCheck(), # Deprecated __t_ member; no need to check - ValueCheck(name="current") + ValueCheck(), # Deprecated __t_ member; no need to check + ValueCheck(name="current"), ] - self.expect_expr("a", - result_type=deque_type, - result_children=[ - ValueCheck(value='3'), - ValueCheck(value='1'), - ValueCheck(value='2'), - ]) + self.expect_expr( + "a", + result_type=deque_type, + result_children=[ + ValueCheck(value="3"), + ValueCheck(value="1"), + ValueCheck(value="2"), + ], + ) self.expect_expr("a.size()", result_type=size_type, result_value="3") self.expect_expr("a.front()", result_type=value_type, result_value="3") @@ -60,9 +60,9 @@ self.expect_expr("*a.begin()", result_type="int", result_value="3") self.expect_expr("*a.rbegin()", result_type="int", result_value="1") - self.expect_expr("a.begin()", - result_type=iterator, - result_children=iterator_children) - self.expect_expr("a.rbegin()", - result_type=riterator, - result_children=riterator_children) + self.expect_expr( + "a.begin()", result_type=iterator, result_children=iterator_children + ) + self.expect_expr( + "a.rbegin()", result_type=riterator, result_children=riterator_children + ) diff --git a/lldb/test/API/commands/expression/import-std-module/deque-dbg-info-content/TestDbgInfoContentDequeFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/deque-dbg-info-content/TestDbgInfoContentDequeFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/deque-dbg-info-content/TestDbgInfoContentDequeFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/deque-dbg-info-content/TestDbgInfoContentDequeFromStdModule.py @@ -8,20 +8,21 @@ class TestDbgInfoContentDeque(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) - @skipIf(compiler="clang", compiler_version=['<', '12.0']) + @skipIf(compiler="clang", compiler_version=["<", "12.0"]) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): deque_type = "std::deque" else: deque_type = "std::deque >" @@ -30,32 +31,31 @@ value_type = "value_type" iterator_type = "iterator" - iterator_children = [ - ValueCheck(name="__m_iter_"), - ValueCheck(name="__ptr_") - ] + iterator_children = [ValueCheck(name="__m_iter_"), ValueCheck(name="__ptr_")] riterator_type = "reverse_iterator" riterator_children = [ - ValueCheck(), # Deprecated __t_ member; no need to check - ValueCheck(name="current") + ValueCheck(), # Deprecated __t_ member; no need to check + ValueCheck(name="current"), ] - self.expect_expr("a", - result_type=deque_type, - result_children=[ - ValueCheck(children=[ValueCheck(value="3")]), - ValueCheck(children=[ValueCheck(value="1")]), - ValueCheck(children=[ValueCheck(value="2")]) - ]) + self.expect_expr( + "a", + result_type=deque_type, + result_children=[ + ValueCheck(children=[ValueCheck(value="3")]), + ValueCheck(children=[ValueCheck(value="1")]), + ValueCheck(children=[ValueCheck(value="2")]), + ], + ) self.expect_expr("a.size()", result_type=size_type, result_value="3") - self.expect_expr("a.front()", - result_type=value_type, - result_children=[ValueCheck(value="3")]) - self.expect_expr("a.back()", - result_type=value_type, - result_children=[ValueCheck(value="2")]) + self.expect_expr( + "a.front()", result_type=value_type, result_children=[ValueCheck(value="3")] + ) + self.expect_expr( + "a.back()", result_type=value_type, result_children=[ValueCheck(value="2")] + ) self.expect_expr("a.front().a", result_type="int", result_value="3") self.expect_expr("a.back().a", result_type="int", result_value="2") @@ -63,11 +63,11 @@ self.expect_expr("a.front().a", result_type="int", result_value="2") self.expect_expr("a.back().a", result_type="int", result_value="3") - self.expect_expr("a.begin()", - result_type=iterator_type, - result_children=iterator_children) - self.expect_expr("a.rbegin()", - result_type=riterator_type, - result_children=riterator_children) + self.expect_expr( + "a.begin()", result_type=iterator_type, result_children=iterator_children + ) + self.expect_expr( + "a.rbegin()", result_type=riterator_type, result_children=riterator_children + ) self.expect_expr("a.begin()->a", result_type="int", result_value="2") self.expect_expr("a.rbegin()->a", result_type="int", result_value="3") diff --git a/lldb/test/API/commands/expression/import-std-module/empty-module/TestEmptyStdModule.py b/lldb/test/API/commands/expression/import-std-module/empty-module/TestEmptyStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/empty-module/TestEmptyStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/empty-module/TestEmptyStdModule.py @@ -9,7 +9,6 @@ class ImportStdModule(TestBase): - # We only emulate a fake libc++ in this test and don't use the real libc++, # but we still add the libc++ category so that this test is only run in # test configurations where libc++ is actually supposed to be tested. @@ -22,21 +21,22 @@ sysroot = os.path.join(os.getcwd(), "root") # Set the sysroot. - self.runCmd("platform select --sysroot '" + sysroot + "' host", - CURRENT_EXECUTABLE_SET) + self.runCmd( + "platform select --sysroot '" + sysroot + "' host", CURRENT_EXECUTABLE_SET + ) - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") # Use the typedef that is only defined in our 'empty' module. If this fails, then LLDB # somehow figured out the correct define for the header and compiled the right # standard module that actually contains the std::vector template. - self.expect("expr MissingContent var = 3; var", substrs=['$0 = 3']) + self.expect("expr MissingContent var = 3; var", substrs=["$0 = 3"]) # Try to access our mock std::vector. This should fail but not crash LLDB as the # std::vector template should be missing from the std module. - self.expect("expr (size_t)v.size()", - substrs=["Couldn't lookup symbols"], - error=True) + self.expect( + "expr (size_t)v.size()", substrs=["Couldn't lookup symbols"], error=True + ) diff --git a/lldb/test/API/commands/expression/import-std-module/forward_decl_from_module/TestForwardDeclFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/forward_decl_from_module/TestForwardDeclFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/forward_decl_from_module/TestForwardDeclFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/forward_decl_from_module/TestForwardDeclFromStdModule.py @@ -9,7 +9,6 @@ class TestCase(TestBase): - # We only emulate a fake libc++ in this test and don't use the real libc++, # but we still add the libc++ category so that this test is only run in # test configurations where libc++ is actually supposed to be tested. @@ -22,12 +21,13 @@ sysroot = os.path.join(os.getcwd(), "root") # Set the sysroot where our dummy libc++ exists. - self.runCmd("platform select --sysroot '" + sysroot + "' host", - CURRENT_EXECUTABLE_SET) + self.runCmd( + "platform select --sysroot '" + sysroot + "' host", CURRENT_EXECUTABLE_SET + ) - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") @@ -36,5 +36,7 @@ # the raw output so LLDB has to show the member variable. # Both `std::vector` and the type of the member have forward # declarations before their definitions. - self.expect("expr --raw -- v", - patterns=[r'\(std::__[^:]*::vector\) \$0 = {', 'f = nullptr', '}']) + self.expect( + "expr --raw -- v", + patterns=[r"\(std::__[^:]*::vector\) \$0 = {", "f = nullptr", "}"], + ) diff --git a/lldb/test/API/commands/expression/import-std-module/forward_list-dbg-info-content/TestDbgInfoContentForwardListFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/forward_list-dbg-info-content/TestDbgInfoContentForwardListFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/forward_list-dbg-info-content/TestDbgInfoContentForwardListFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/forward_list-dbg-info-content/TestDbgInfoContentForwardListFromStdModule.py @@ -8,19 +8,20 @@ class TestDbgInfoContentForwardList(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): list_type = "std::forward_list" else: list_type = "std::forward_list >" diff --git a/lldb/test/API/commands/expression/import-std-module/forward_list/TestForwardListFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/forward_list/TestForwardListFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/forward_list/TestForwardListFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/forward_list/TestForwardListFromStdModule.py @@ -8,19 +8,20 @@ class TestBasicForwardList(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): list_type = "std::forward_list" else: list_type = "std::forward_list >" @@ -37,6 +38,4 @@ self.expect_expr("a.front()", result_type=value_type, result_value="1") # FIXME: Removing casting here causes LLDB to crash. - self.expect_expr("(int)*a.begin()", - result_type="int", - result_value="1") + self.expect_expr("(int)*a.begin()", result_type="int", result_value="1") diff --git a/lldb/test/API/commands/expression/import-std-module/iterator/TestIteratorFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/iterator/TestIteratorFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/iterator/TestIteratorFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/iterator/TestIteratorFromStdModule.py @@ -8,15 +8,14 @@ class TestCase(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") diff --git a/lldb/test/API/commands/expression/import-std-module/list-dbg-info-content/TestDbgInfoContentListFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/list-dbg-info-content/TestDbgInfoContentListFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/list-dbg-info-content/TestDbgInfoContentListFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/list-dbg-info-content/TestDbgInfoContentListFromStdModule.py @@ -9,20 +9,21 @@ class TestDbgInfoContentList(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) - @skipIf(compiler="clang", compiler_version=['<', '12.0']) + @skipIf(compiler="clang", compiler_version=["<", "12.0"]) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): list_type = "std::list" else: list_type = "std::list >" @@ -30,13 +31,15 @@ size_type = "size_type" value_type = "value_type" - self.expect_expr("a", - result_type=list_type, - result_children=[ - ValueCheck(children=[ValueCheck(value="3")]), - ValueCheck(children=[ValueCheck(value="1")]), - ValueCheck(children=[ValueCheck(value="2")]) - ]) + self.expect_expr( + "a", + result_type=list_type, + result_children=[ + ValueCheck(children=[ValueCheck(value="3")]), + ValueCheck(children=[ValueCheck(value="1")]), + ValueCheck(children=[ValueCheck(value="2")]), + ], + ) self.expect_expr("a.size()", result_type=size_type, result_value="3") self.expect_expr("a.front().a", result_type="int", result_value="3") diff --git a/lldb/test/API/commands/expression/import-std-module/list/TestListFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/list/TestListFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/list/TestListFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/list/TestListFromStdModule.py @@ -8,19 +8,20 @@ class TestBasicList(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): list_type = "std::list" else: list_type = "std::list >" @@ -31,13 +32,15 @@ iteratorvalue = "value_type" riterator_value = "value_type" - self.expect_expr("a", - result_type=list_type, - result_children=[ - ValueCheck(value="3"), - ValueCheck(value="1"), - ValueCheck(value="2") - ]) + self.expect_expr( + "a", + result_type=list_type, + result_children=[ + ValueCheck(value="3"), + ValueCheck(value="1"), + ValueCheck(value="2"), + ], + ) self.expect_expr("a.size()", result_type=size_type, result_value="3") self.expect_expr("a.front()", result_type=value_type, result_value="3") @@ -51,9 +54,5 @@ self.expect_expr("a.front()", result_type=value_type, result_value="3") self.expect_expr("a.back()", result_type=value_type, result_value="1") - self.expect_expr("*a.begin()", - result_type=iteratorvalue, - result_value="3") - self.expect_expr("*a.rbegin()", - result_type=riterator_value, - result_value="1") + self.expect_expr("*a.begin()", result_type=iteratorvalue, result_value="3") + self.expect_expr("*a.rbegin()", result_type=riterator_value, result_value="1") diff --git a/lldb/test/API/commands/expression/import-std-module/missing-module-sources/TestStdModuleSourcesMissing.py b/lldb/test/API/commands/expression/import-std-module/missing-module-sources/TestStdModuleSourcesMissing.py --- a/lldb/test/API/commands/expression/import-std-module/missing-module-sources/TestStdModuleSourcesMissing.py +++ b/lldb/test/API/commands/expression/import-std-module/missing-module-sources/TestStdModuleSourcesMissing.py @@ -10,7 +10,6 @@ class TestCase(TestBase): - # We only emulate a fake libc++ in this test and don't use the real libc++, # but we still add the libc++ category so that this test is only run in # test configurations where libc++ is actually supposed to be tested. @@ -34,26 +33,40 @@ # XPASS this test. self.runCmd("platform select --sysroot '" + target_sysroot + "' host") - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) # Import the std C++ module and run an expression. # As we deleted the sources, LLDB should refuse the load the module # and just print the normal error we get from the expression. self.runCmd("settings set target.import-std-module true") - self.expect("expr v.unknown_identifier", error=True, - substrs=["no member named 'unknown_identifier'"]) + self.expect( + "expr v.unknown_identifier", + error=True, + substrs=["no member named 'unknown_identifier'"], + ) # Check that there is no confusing error about failing to build the # module. - self.expect("expr v.unknown_identifier", error=True, matching=False, - substrs=["could not build module 'std'"]) + self.expect( + "expr v.unknown_identifier", + error=True, + matching=False, + substrs=["could not build module 'std'"], + ) # Test the fallback mode. It should also just print the normal # error but not mention a failed module build. self.runCmd("settings set target.import-std-module fallback") - self.expect("expr v.unknown_identifier", error=True, - substrs=["no member named 'unknown_identifier'"]) - self.expect("expr v.unknown_identifier", error=True, matching=False, - substrs=["could not build module 'std'"]) + self.expect( + "expr v.unknown_identifier", + error=True, + substrs=["no member named 'unknown_identifier'"], + ) + self.expect( + "expr v.unknown_identifier", + error=True, + matching=False, + substrs=["could not build module 'std'"], + ) diff --git a/lldb/test/API/commands/expression/import-std-module/module-build-errors/TestStdModuleBuildErrors.py b/lldb/test/API/commands/expression/import-std-module/module-build-errors/TestStdModuleBuildErrors.py --- a/lldb/test/API/commands/expression/import-std-module/module-build-errors/TestStdModuleBuildErrors.py +++ b/lldb/test/API/commands/expression/import-std-module/module-build-errors/TestStdModuleBuildErrors.py @@ -13,7 +13,6 @@ class TestCase(TestBase): - # We only emulate a fake libc++ in this test and don't use the real libc++, # but we still add the libc++ category so that this test is only run in # test configurations where libc++ is actually supposed to be tested. @@ -26,12 +25,13 @@ sysroot = os.path.join(os.getcwd(), "root") # Set the sysroot this test is using to provide a custom libc++. - self.runCmd("platform select --sysroot '" + sysroot + "' host", - CURRENT_EXECUTABLE_SET) + self.runCmd( + "platform select --sysroot '" + sysroot + "' host", CURRENT_EXECUTABLE_SET + ) - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) # The expected error message when the fake libc++ module in this test # fails to build from within LLDB (as it contains invalid code). @@ -40,20 +40,21 @@ # First force the std module to be imported. This should show the # module build error to the user. self.runCmd("settings set target.import-std-module true") - self.expect("expr (size_t)v.size()", - substrs=[module_build_error_msg], - error=True) + self.expect( + "expr (size_t)v.size()", substrs=[module_build_error_msg], error=True + ) # In the fallback mode the module build error should not be shown. self.runCmd("settings set target.import-std-module fallback") fallback_expr = "expr v ; error_to_trigger_fallback_mode" # First check for the actual expression error that should be displayed # and is useful for the user. - self.expect(fallback_expr, - substrs=["use of undeclared identifier 'error_to_trigger_fallback_mode'"], - error=True) + self.expect( + fallback_expr, + substrs=["use of undeclared identifier 'error_to_trigger_fallback_mode'"], + error=True, + ) # Test that the module build error is not displayed. - self.expect(fallback_expr, - substrs=[module_build_error_msg], - matching=False, - error=True) + self.expect( + fallback_expr, substrs=[module_build_error_msg], matching=False, error=True + ) diff --git a/lldb/test/API/commands/expression/import-std-module/no-std-module/TestMissingStdModule.py b/lldb/test/API/commands/expression/import-std-module/no-std-module/TestMissingStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/no-std-module/TestMissingStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/no-std-module/TestMissingStdModule.py @@ -14,15 +14,14 @@ class STLTestCase(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) # Activate importing of std module. self.runCmd("settings set target.import-std-module true") @@ -31,5 +30,4 @@ self.expect("expr std::abs(-42)", error=True) self.expect("expr std::div(2, 1).quot", error=True) self.expect("expr (std::size_t)33U", error=True) - self.expect("expr char a = 'b'; char b = 'a'; std::swap(a, b); a", - error=True) + self.expect("expr char a = 'b'; char b = 'a'; std::swap(a, b); a", error=True) diff --git a/lldb/test/API/commands/expression/import-std-module/non-module-type-separation/TestNonModuleTypeSeparation.py b/lldb/test/API/commands/expression/import-std-module/non-module-type-separation/TestNonModuleTypeSeparation.py --- a/lldb/test/API/commands/expression/import-std-module/non-module-type-separation/TestNonModuleTypeSeparation.py +++ b/lldb/test/API/commands/expression/import-std-module/non-module-type-separation/TestNonModuleTypeSeparation.py @@ -9,7 +9,6 @@ class TestCase(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): @@ -21,9 +20,9 @@ """ self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) children = [ ValueCheck(value="3"), @@ -31,7 +30,9 @@ ValueCheck(value="2"), ] - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): vector_type = "std::vector" dbg_vec_type = "std::vector" module_vector_type = "std::vector" @@ -41,47 +42,64 @@ module_vector_type = "std::vector" # First muddy the scratch AST with non-C++ module types. - self.expect_expr("a", result_type=vector_type, - result_children=children) - self.expect_expr("dbg_info_vec", - result_type=dbg_vec_type, - result_children=[ - ValueCheck(type="DbgInfoClass", children=[ - ValueCheck(name="ints", type=vector_type, children=[ - ValueCheck(value="1") - ]) - ]) - ]) + self.expect_expr("a", result_type=vector_type, result_children=children) + self.expect_expr( + "dbg_info_vec", + result_type=dbg_vec_type, + result_children=[ + ValueCheck( + type="DbgInfoClass", + children=[ + ValueCheck( + name="ints", + type=vector_type, + children=[ValueCheck(value="1")], + ) + ], + ) + ], + ) # Enable the C++ module import and get the module vector type. self.runCmd("settings set target.import-std-module true") - self.expect_expr("a", result_type=module_vector_type, - result_children=children) + self.expect_expr("a", result_type=module_vector_type, result_children=children) # Test mixed debug info/module types - self.expect_expr("dbg_info_vec", - result_type=dbg_vec_type, - result_children=[ - ValueCheck(type="DbgInfoClass", children=[ - ValueCheck(name="ints", type=module_vector_type, children=[ - ValueCheck(value="1") - ]) - ]) - ]) - + self.expect_expr( + "dbg_info_vec", + result_type=dbg_vec_type, + result_children=[ + ValueCheck( + type="DbgInfoClass", + children=[ + ValueCheck( + name="ints", + type=module_vector_type, + children=[ValueCheck(value="1")], + ) + ], + ) + ], + ) # Turn off the C++ module import and use debug info types again. self.runCmd("settings set target.import-std-module false") - self.expect_expr("a", result_type=vector_type, - result_children=children) + self.expect_expr("a", result_type=vector_type, result_children=children) # Test the types that were previoiusly mixed debug info/module types. - self.expect_expr("dbg_info_vec", - result_type=dbg_vec_type, - result_children=[ - ValueCheck(type="DbgInfoClass", children=[ - ValueCheck(name="ints", type=vector_type, children=[ - ValueCheck(value="1") - ]) - ]) - ]) + self.expect_expr( + "dbg_info_vec", + result_type=dbg_vec_type, + result_children=[ + ValueCheck( + type="DbgInfoClass", + children=[ + ValueCheck( + name="ints", + type=vector_type, + children=[ValueCheck(value="1")], + ) + ], + ) + ], + ) diff --git a/lldb/test/API/commands/expression/import-std-module/pair/TestPairFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/pair/TestPairFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/pair/TestPairFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/pair/TestPairFromStdModule.py @@ -8,7 +8,6 @@ class TestCase(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) # FIXME: This regressed in 69d5a6662115499198ebfa07a081e98a6ce4b915 @@ -18,28 +17,27 @@ def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - self.expect_expr("pair_int.first", - result_type="int", - result_value="1234") - self.expect_expr("pair_int.second", - result_type="int", - result_value="5678") - self.expect_expr("pair_int", - result_type="std::pair", - result_children=[ - ValueCheck(name="first", value="1234"), - ValueCheck(name="second", value="5678"), - ]) + self.expect_expr("pair_int.first", result_type="int", result_value="1234") + self.expect_expr("pair_int.second", result_type="int", result_value="5678") + self.expect_expr( + "pair_int", + result_type="std::pair", + result_children=[ + ValueCheck(name="first", value="1234"), + ValueCheck(name="second", value="5678"), + ], + ) self.expect_expr( "std::pair lp; lp.first = 3333; lp.second = 2344; lp", result_type="std::pair", result_children=[ ValueCheck(name="first", value="3333"), ValueCheck(name="second", value="2344"), - ]) + ], + ) diff --git a/lldb/test/API/commands/expression/import-std-module/queue/TestQueueFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/queue/TestQueueFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/queue/TestQueueFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/queue/TestQueueFromStdModule.py @@ -8,19 +8,20 @@ class TestQueue(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): queue_type = "std::queue" else: queue_type = "std::queue > >" @@ -32,31 +33,24 @@ self.expect_expr( "q_deque", result_type=queue_type, - result_children=[ValueCheck(children=[ValueCheck(value="1")])]) + result_children=[ValueCheck(children=[ValueCheck(value="1")])], + ) self.expect("expr q_deque.pop()") self.expect("expr q_deque.push({4})") - self.expect_expr("q_deque.size()", - result_type=size_type, - result_value="1") + self.expect_expr("q_deque.size()", result_type=size_type, result_value="1") self.expect_expr("q_deque.front()", result_type=value_type) self.expect_expr("q_deque.back()", result_type=value_type) - self.expect_expr("q_deque.front().i", - result_type="int", - result_value="4") - self.expect_expr("q_deque.back().i", - result_type="int", - result_value="4") - self.expect_expr("q_deque.empty()", - result_type="bool", - result_value="false") + self.expect_expr("q_deque.front().i", result_type="int", result_value="4") + self.expect_expr("q_deque.back().i", result_type="int", result_value="4") + self.expect_expr("q_deque.empty()", result_type="bool", result_value="false") self.expect("expr q_deque.pop()") self.expect("expr q_deque.emplace(5)") - self.expect_expr("q_deque.front().i", - result_type="int", - result_value="5") + self.expect_expr("q_deque.front().i", result_type="int", result_value="5") # Test std::queue functionality with a std::list. - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): queue_type = "std::queue >" else: queue_type = "std::queue > >" @@ -64,26 +58,17 @@ self.expect_expr( "q_list", result_type=queue_type, - result_children=[ValueCheck(children=[ValueCheck(value="1")])]) + result_children=[ValueCheck(children=[ValueCheck(value="1")])], + ) self.expect("expr q_list.pop()") self.expect("expr q_list.push({4})") - self.expect_expr("q_list.size()", - result_type=size_type, - result_value="1") + self.expect_expr("q_list.size()", result_type=size_type, result_value="1") self.expect_expr("q_list.front()", result_type=value_type) self.expect_expr("q_list.back()", result_type=value_type) - self.expect_expr("q_list.front().i", - result_type="int", - result_value="4") - self.expect_expr("q_list.back().i", - result_type="int", - result_value="4") - self.expect_expr("q_list.empty()", - result_type="bool", - result_value="false") + self.expect_expr("q_list.front().i", result_type="int", result_value="4") + self.expect_expr("q_list.back().i", result_type="int", result_value="4") + self.expect_expr("q_list.empty()", result_type="bool", result_value="false") self.expect("expr q_list.pop()") self.expect("expr q_list.emplace(5)") - self.expect_expr("q_list.front().i", - result_type="int", - result_value="5") + self.expect_expr("q_list.front().i", result_type="int", result_value="5") diff --git a/lldb/test/API/commands/expression/import-std-module/retry-with-std-module/TestRetryWithStdModule.py b/lldb/test/API/commands/expression/import-std-module/retry-with-std-module/TestRetryWithStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/retry-with-std-module/TestRetryWithStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/retry-with-std-module/TestRetryWithStdModule.py @@ -4,17 +4,18 @@ class TestCase(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): vec_type = "std::vector" else: vec_type = "std::vector >" @@ -34,24 +35,30 @@ # automatically fall back to import the C++ module to get this working. self.expect_expr("std::max(0U, a.size())", result_value="3") - # The 'a' and 'local' part can be parsed without loading a C++ module and will # load type/runtime information. The 'std::max...' part will fail to # parse without a C++ module. Make sure we reset all the relevant parts of # the C++ parser so that we don't end up with for example a second # definition of 'local' when retrying. - self.expect_expr("a; local; std::max(0U, a.size())", result_value="3") - + self.expect_expr( + "a; local; std::max(0U, a.size())", result_value="3" + ) # Try to declare top-level declarations that require a C++ module to parse. # Top-level expressions don't support importing the C++ module (yet), so # this should still fail as before. - self.expect("expr --top-level -- int i = std::max(1, 2);", error=True, - substrs=["no member named 'max' in namespace 'std'"]) + self.expect( + "expr --top-level -- int i = std::max(1, 2);", + error=True, + substrs=["no member named 'max' in namespace 'std'"], + ) # The proper diagnostic however should be shown on the retry. - self.expect("expr std::max(1, 2); unknown_identifier", error=True, - substrs=["use of undeclared identifier 'unknown_identifier'"]) + self.expect( + "expr std::max(1, 2); unknown_identifier", + error=True, + substrs=["use of undeclared identifier 'unknown_identifier'"], + ) # Turn on the 'import-std-module' setting and make sure we import the # C++ module. @@ -63,5 +70,8 @@ # the module (which should prevent parsing the expression involving # 'std::max'). self.runCmd("settings set target.import-std-module false") - self.expect("expr std::max(1, 2);", error=True, - substrs=["no member named 'max' in namespace 'std'"]) + self.expect( + "expr std::max(1, 2);", + error=True, + substrs=["no member named 'max' in namespace 'std'"], + ) diff --git a/lldb/test/API/commands/expression/import-std-module/shared_ptr-dbg-info-content/TestSharedPtrDbgInfoContentFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/shared_ptr-dbg-info-content/TestSharedPtrDbgInfoContentFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/shared_ptr-dbg-info-content/TestSharedPtrDbgInfoContentFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/shared_ptr-dbg-info-content/TestSharedPtrDbgInfoContentFromStdModule.py @@ -8,21 +8,22 @@ class TestSharedPtrDbgInfoContent(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - self.expect_expr("s", - result_type="std::shared_ptr", - result_children=[ValueCheck(name="__ptr_")]) + self.expect_expr( + "s", + result_type="std::shared_ptr", + result_children=[ValueCheck(name="__ptr_")], + ) self.expect_expr("s->a", result_type="int", result_value="3") self.expect_expr("s->a = 5", result_type="int", result_value="5") self.expect_expr("s->a", result_type="int", result_value="5") diff --git a/lldb/test/API/commands/expression/import-std-module/shared_ptr/TestSharedPtrFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/shared_ptr/TestSharedPtrFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/shared_ptr/TestSharedPtrFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/shared_ptr/TestSharedPtrFromStdModule.py @@ -8,22 +8,23 @@ class TestSharedPtr(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - self.expect_expr("s", - result_type="std::shared_ptr", - result_summary="3 strong=1 weak=1", - result_children=[ValueCheck(name="__ptr_")]) + self.expect_expr( + "s", + result_type="std::shared_ptr", + result_summary="3 strong=1 weak=1", + result_children=[ValueCheck(name="__ptr_")], + ) self.expect_expr("*s", result_type="int", result_value="3") self.expect_expr("*s = 5", result_type="int", result_value="5") self.expect_expr("*s", result_type="int", result_value="5") diff --git a/lldb/test/API/commands/expression/import-std-module/stack/TestStackFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/stack/TestStackFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/stack/TestStackFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/stack/TestStackFromStdModule.py @@ -6,17 +6,18 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestStack(TestBase): +class TestStack(TestBase): @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) - @skipIfLinux # Declaration in some Linux headers causes LLDB to crash. + @skipIfLinux # Declaration in some Linux headers causes LLDB to crash. @skipIf(bugnumber="rdar://97622854") def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") @@ -27,16 +28,10 @@ self.expect_expr("s_deque", result_type=stack_type) self.expect("expr s_deque.pop()") self.expect("expr s_deque.push({4})") - self.expect_expr("s_deque.size()", - result_type=size_type, - result_value="3") - self.expect_expr("s_deque.top().i", - result_type="int", - result_value="4") + self.expect_expr("s_deque.size()", result_type=size_type, result_value="3") + self.expect_expr("s_deque.top().i", result_type="int", result_value="4") self.expect("expr s_deque.emplace(5)") - self.expect_expr("s_deque.top().i", - result_type="int", - result_value="5") + self.expect_expr("s_deque.top().i", result_type="int", result_value="5") # Test std::stack functionality with a std::vector. stack_type = "std::stack >" @@ -45,16 +40,10 @@ self.expect_expr("s_vector", result_type=stack_type) self.expect("expr s_vector.pop()") self.expect("expr s_vector.push({4})") - self.expect_expr("s_vector.size()", - result_type=size_type, - result_value="3") - self.expect_expr("s_vector.top().i", - result_type="int", - result_value="4") + self.expect_expr("s_vector.size()", result_type=size_type, result_value="3") + self.expect_expr("s_vector.top().i", result_type="int", result_value="4") self.expect("expr s_vector.emplace(5)") - self.expect_expr("s_vector.top().i", - result_type="int", - result_value="5") + self.expect_expr("s_vector.top().i", result_type="int", result_value="5") # Test std::stack functionality with a std::list. stack_type = "std::stack >" @@ -62,9 +51,7 @@ self.expect_expr("s_list", result_type=stack_type) self.expect("expr s_list.pop()") self.expect("expr s_list.push({4})") - self.expect_expr("s_list.size()", - result_type=size_type, - result_value="3") + self.expect_expr("s_list.size()", result_type=size_type, result_value="3") self.expect_expr("s_list.top().i", result_type="int", result_value="4") self.expect("expr s_list.emplace(5)") self.expect_expr("s_list.top().i", result_type="int", result_value="5") diff --git a/lldb/test/API/commands/expression/import-std-module/sysroot/TestStdModuleSysroot.py b/lldb/test/API/commands/expression/import-std-module/sysroot/TestStdModuleSysroot.py --- a/lldb/test/API/commands/expression/import-std-module/sysroot/TestStdModuleSysroot.py +++ b/lldb/test/API/commands/expression/import-std-module/sysroot/TestStdModuleSysroot.py @@ -9,7 +9,6 @@ class ImportStdModule(TestBase): - # We only emulate a fake libc++ in this test and don't use the real libc++, # but we still add the libc++ category so that this test is only run in # test configurations where libc++ is actually supposed to be tested. @@ -22,12 +21,13 @@ sysroot = os.path.join(os.getcwd(), "root") # Set the sysroot. - self.runCmd("platform select --sysroot '" + sysroot + "' host", - CURRENT_EXECUTABLE_SET) + self.runCmd( + "platform select --sysroot '" + sysroot + "' host", CURRENT_EXECUTABLE_SET + ) - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") @@ -35,4 +35,4 @@ # If this gives us the correct result, then we used the sysroot. # We rely on the default argument of -123 to make sure we actually have the C++ module. # (We don't have default arguments in the debug information). - self.expect("expr std::myabs()", substrs=['(int) $0 = 123']) + self.expect("expr std::myabs()", substrs=["(int) $0 = 123"]) diff --git a/lldb/test/API/commands/expression/import-std-module/unique_ptr-dbg-info-content/TestUniquePtrDbgInfoContent.py b/lldb/test/API/commands/expression/import-std-module/unique_ptr-dbg-info-content/TestUniquePtrDbgInfoContent.py --- a/lldb/test/API/commands/expression/import-std-module/unique_ptr-dbg-info-content/TestUniquePtrDbgInfoContent.py +++ b/lldb/test/API/commands/expression/import-std-module/unique_ptr-dbg-info-content/TestUniquePtrDbgInfoContent.py @@ -8,21 +8,22 @@ class TestUniquePtrDbgInfoContent(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) - @skipIf(compiler="clang", compiler_version=['<', '9.0']) - @skipIfLinux # s.reset() causes link errors on ubuntu 18.04/Clang 9 + @skipIf(compiler="clang", compiler_version=["<", "9.0"]) + @skipIfLinux # s.reset() causes link errors on ubuntu 18.04/Clang 9 def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): ptr_type = "std::unique_ptr" else: ptr_type = "std::unique_ptr >" @@ -30,7 +31,8 @@ self.expect_expr( "s", result_type=ptr_type, - result_children=[ValueCheck(children=[ValueCheck(value="3")])]) + result_children=[ValueCheck(children=[ValueCheck(value="3")])], + ) self.expect_expr("s->a", result_type="int", result_value="3") self.expect_expr("s->a = 5", result_type="int", result_value="5") self.expect_expr("(int)s->a", result_type="int", result_value="5") diff --git a/lldb/test/API/commands/expression/import-std-module/unique_ptr/TestUniquePtrFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/unique_ptr/TestUniquePtrFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/unique_ptr/TestUniquePtrFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/unique_ptr/TestUniquePtrFromStdModule.py @@ -8,21 +8,22 @@ class TestUniquePtr(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) - @skipIf(compiler="clang", compiler_version=['<', '9.0']) - @skipIfLinux # s.reset() causes link errors on ubuntu 18.04/Clang 9 + @skipIf(compiler="clang", compiler_version=["<", "9.0"]) + @skipIfLinux # s.reset() causes link errors on ubuntu 18.04/Clang 9 def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): ptr_type = "std::unique_ptr" else: ptr_type = "std::unique_ptr >" @@ -31,7 +32,8 @@ "s", result_type=ptr_type, result_summary="3", - result_children=[ValueCheck(name="pointer")]) + result_children=[ValueCheck(name="pointer")], + ) self.expect_expr("*s", result_type="int", result_value="3") self.expect_expr("*s = 5", result_type="int", result_value="5") self.expect_expr("*s", result_type="int", result_value="5") diff --git a/lldb/test/API/commands/expression/import-std-module/vector-bool/TestVectorBoolFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/vector-bool/TestVectorBoolFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/vector-bool/TestVectorBoolFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/vector-bool/TestVectorBoolFromStdModule.py @@ -8,43 +8,36 @@ class TestBoolVector(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) @skipIf(bugnumber="rdar://100741983") def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) vector_type = "std::vector" size_type = "size_type" self.runCmd("settings set target.import-std-module true") - self.expect_expr("a", - result_type=vector_type, - result_children=[ - ValueCheck(value="false"), - ValueCheck(value="true"), - ValueCheck(value="false"), - ValueCheck(value="true"), - ]) + self.expect_expr( + "a", + result_type=vector_type, + result_children=[ + ValueCheck(value="false"), + ValueCheck(value="true"), + ValueCheck(value="false"), + ValueCheck(value="true"), + ], + ) self.expect_expr("a.size()", result_type=size_type, result_value="4") # FIXME: Without the casting the result can't be materialized. - self.expect_expr("(bool)a.front()", - result_type="bool", - result_value="false") + self.expect_expr("(bool)a.front()", result_type="bool", result_value="false") self.expect_expr("(bool)a[1]", result_type="bool", result_value="true") - self.expect_expr("(bool)a.back()", - result_type="bool", - result_value="true") - - self.expect_expr("(bool)*a.begin()", - result_type="bool", - result_value="false") - self.expect_expr("(bool)*a.rbegin()", - result_type="bool", - result_value="true") + self.expect_expr("(bool)a.back()", result_type="bool", result_value="true") + + self.expect_expr("(bool)*a.begin()", result_type="bool", result_value="false") + self.expect_expr("(bool)*a.rbegin()", result_type="bool", result_value="true") diff --git a/lldb/test/API/commands/expression/import-std-module/vector-dbg-info-content/TestDbgInfoContentVectorFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/vector-dbg-info-content/TestDbgInfoContentVectorFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/vector-dbg-info-content/TestDbgInfoContentVectorFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/vector-dbg-info-content/TestDbgInfoContentVectorFromStdModule.py @@ -9,20 +9,21 @@ class TestDbgInfoContentVector(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) - @skipIf(compiler="clang", compiler_version=['<', '12.0']) + @skipIf(compiler="clang", compiler_version=["<", "12.0"]) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): vector_type = "std::vector" else: vector_type = "std::vector >" @@ -34,17 +35,19 @@ iterator_children = [ValueCheck(name="item")] riterator = "reverse_iterator" riterator_children = [ - ValueCheck(), # Deprecated __t_ member; no need to check - ValueCheck(name="current") + ValueCheck(), # Deprecated __t_ member; no need to check + ValueCheck(name="current"), ] - self.expect_expr("a", - result_type=vector_type, - result_children=[ - ValueCheck(children=[ValueCheck(value="3")]), - ValueCheck(children=[ValueCheck(value="1")]), - ValueCheck(children=[ValueCheck(value="2")]), - ]) + self.expect_expr( + "a", + result_type=vector_type, + result_children=[ + ValueCheck(children=[ValueCheck(value="3")]), + ValueCheck(children=[ValueCheck(value="1")]), + ValueCheck(children=[ValueCheck(value="2")]), + ], + ) self.expect_expr("a.size()", result_type=size_type, result_value="3") self.expect_expr("a.front().a", result_type="int", result_value="3") @@ -67,9 +70,9 @@ self.expect_expr("a.back().a", result_type="int", result_value="4") self.expect_expr("a.size()", result_type=size_type, result_value="3") - self.expect_expr("a.begin()", - result_type=iterator, - result_children=iterator_children) - self.expect_expr("a.rbegin()", - result_type=riterator, - result_children=riterator_children) + self.expect_expr( + "a.begin()", result_type=iterator, result_children=iterator_children + ) + self.expect_expr( + "a.rbegin()", result_type=riterator, result_children=riterator_children + ) diff --git a/lldb/test/API/commands/expression/import-std-module/vector-of-vectors/TestVectorOfVectorsFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/vector-of-vectors/TestVectorOfVectorsFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/vector-of-vectors/TestVectorOfVectorsFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/vector-of-vectors/TestVectorOfVectorsFromStdModule.py @@ -8,22 +8,25 @@ class TestVectorOfVectors(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): vector_type = "std::vector" vector_of_vector_type = "std::vector >" else: vector_type = "std::vector" - vector_of_vector_type = "std::vector, std::allocator > >" + vector_of_vector_type = ( + "std::vector, std::allocator > >" + ) size_type = "size_type" value_type = "value_type" @@ -34,23 +37,27 @@ "a", result_type=vector_of_vector_type, result_children=[ - ValueCheck(type=vector_type, - children=[ - ValueCheck(value='1'), - ValueCheck(value='2'), - ValueCheck(value='3'), - ]), - ValueCheck(type=vector_type, - children=[ - ValueCheck(value='3'), - ValueCheck(value='2'), - ValueCheck(value='1'), - ]), - ]) + ValueCheck( + type=vector_type, + children=[ + ValueCheck(value="1"), + ValueCheck(value="2"), + ValueCheck(value="3"), + ], + ), + ValueCheck( + type=vector_type, + children=[ + ValueCheck(value="3"), + ValueCheck(value="2"), + ValueCheck(value="1"), + ], + ), + ], + ) self.expect_expr("a.size()", result_type=size_type, result_value="2") - front = self.expect_expr("a.front().front()", result_type=value_type, - result_value="1") + front = self.expect_expr( + "a.front().front()", result_type=value_type, result_value="1" + ) self.expect_expr("a[1][1]", result_type=value_type, result_value="2") - self.expect_expr("a.back().at(0)", - result_type=value_type, - result_value="3") + self.expect_expr("a.back().at(0)", result_type=value_type, result_value="3") diff --git a/lldb/test/API/commands/expression/import-std-module/vector/TestVectorFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/vector/TestVectorFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/vector/TestVectorFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/vector/TestVectorFromStdModule.py @@ -8,16 +8,15 @@ class TestBasicVector(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) @skipIf(bugnumber="rdar://100741983") def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") @@ -29,20 +28,21 @@ iterator_children = [ValueCheck(name="item")] riterator = "reverse_iterator" riterator_children = [ - ValueCheck(), # Deprecated __t_ member; no need to check - ValueCheck(name="current") + ValueCheck(), # Deprecated __t_ member; no need to check + ValueCheck(name="current"), ] - self.expect_expr("a", - result_type=vector_type, - result_children=[ - ValueCheck(value="3"), - ValueCheck(value="1"), - ValueCheck(value="2") - ]) + self.expect_expr( + "a", + result_type=vector_type, + result_children=[ + ValueCheck(value="3"), + ValueCheck(value="1"), + ValueCheck(value="2"), + ], + ) self.expect_expr("a.size()", result_type=size_type, result_value="3") - front = self.expect_expr("a.front()", result_type=value_type, - result_value="3") + front = self.expect_expr("a.front()", result_type=value_type, result_value="3") self.expect_expr("a[1]", result_type=value_type, result_value="1") self.expect_expr("a.back()", result_type=value_type, result_value="2") @@ -56,12 +56,12 @@ self.expect_expr("a[1]", result_type=value_type, result_value="2") self.expect_expr("a.back()", result_type=value_type, result_value="1") - self.expect_expr("a.begin()", - result_type=iterator, - result_children=iterator_children) - self.expect_expr("a.rbegin()", - result_type=riterator, - result_children=riterator_children) + self.expect_expr( + "a.begin()", result_type=iterator, result_children=iterator_children + ) + self.expect_expr( + "a.rbegin()", result_type=riterator, result_children=riterator_children + ) self.expect_expr("*a.begin()", result_type="int", result_value="3") self.expect_expr("*a.rbegin()", result_type="int", result_value="1") @@ -80,20 +80,25 @@ self.expect_expr("a.back()", result_type=value_type, result_value="5") self.expect_expr("a.size()", result_type=size_type, result_value="4") - self.expect_expr("a", - result_children=[ - ValueCheck(value="3"), - ValueCheck(value="2"), - ValueCheck(value="4"), - ValueCheck(value="5") - ]) + self.expect_expr( + "a", + result_children=[ + ValueCheck(value="3"), + ValueCheck(value="2"), + ValueCheck(value="4"), + ValueCheck(value="5"), + ], + ) # Test that the typedef'd vector type can be substituted. self.expect("expr b.emplace_back(6)") - self.expect_expr("b", result_type="vector_long", - result_children=[ - ValueCheck(value="3"), - ValueCheck(value="1"), - ValueCheck(value="2"), - ValueCheck(value="6"), - ]) + self.expect_expr( + "b", + result_type="vector_long", + result_children=[ + ValueCheck(value="3"), + ValueCheck(value="1"), + ValueCheck(value="2"), + ValueCheck(value="6"), + ], + ) diff --git a/lldb/test/API/commands/expression/import-std-module/weak_ptr-dbg-info-content/TestDbgInfoContentWeakPtrFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/weak_ptr-dbg-info-content/TestDbgInfoContentWeakPtrFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/weak_ptr-dbg-info-content/TestDbgInfoContentWeakPtrFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/weak_ptr-dbg-info-content/TestDbgInfoContentWeakPtrFromStdModule.py @@ -8,26 +8,25 @@ class TestDbgInfoContentWeakPtr(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - self.expect_expr("w", - result_type="std::weak_ptr", - result_children=[ValueCheck(name="__ptr_")]) + self.expect_expr( + "w", + result_type="std::weak_ptr", + result_children=[ValueCheck(name="__ptr_")], + ) self.expect_expr("*w.lock()", result_type="Foo") self.expect_expr("w.lock()->a", result_type="int", result_value="3") - self.expect_expr("w.lock()->a = 5", - result_type="int", - result_value="5") + self.expect_expr("w.lock()->a = 5", result_type="int", result_value="5") self.expect_expr("w.lock()->a", result_type="int", result_value="5") self.expect_expr("w.use_count()", result_type="long", result_value="1") self.expect("expr w.reset()") diff --git a/lldb/test/API/commands/expression/import-std-module/weak_ptr/TestWeakPtrFromStdModule.py b/lldb/test/API/commands/expression/import-std-module/weak_ptr/TestWeakPtrFromStdModule.py --- a/lldb/test/API/commands/expression/import-std-module/weak_ptr/TestWeakPtrFromStdModule.py +++ b/lldb/test/API/commands/expression/import-std-module/weak_ptr/TestWeakPtrFromStdModule.py @@ -8,22 +8,23 @@ class TestSharedPtr(TestBase): - @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.runCmd("settings set target.import-std-module true") - self.expect_expr("w", - result_type="std::weak_ptr", - result_summary="3 strong=1 weak=2", - result_children=[ValueCheck(name="__ptr_")]) + self.expect_expr( + "w", + result_type="std::weak_ptr", + result_summary="3 strong=1 weak=2", + result_children=[ValueCheck(name="__ptr_")], + ) self.expect_expr("*w.lock()", result_type="int", result_value="3") self.expect_expr("*w.lock() = 5", result_type="int", result_value="5") self.expect_expr("*w.lock()", result_type="int", result_value="5") diff --git a/lldb/test/API/commands/expression/import_builtin_fileid/TestImportBuiltinFileID.py b/lldb/test/API/commands/expression/import_builtin_fileid/TestImportBuiltinFileID.py --- a/lldb/test/API/commands/expression/import_builtin_fileid/TestImportBuiltinFileID.py +++ b/lldb/test/API/commands/expression/import_builtin_fileid/TestImportBuiltinFileID.py @@ -10,15 +10,18 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestImportBuiltinFileID(TestBase): +class TestImportBuiltinFileID(TestBase): @skipIfDarwinEmbedded @add_test_categories(["gmodules", "objc"]) def test_import_builtin_fileid(self): self.build() - lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.m", False)) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.m", False) + ) - self.expect("expr int (*DBG_CGImageGetRenderingIntent)(void *) = ((int (*)(void *))CGImageGetRenderingIntent); DBG_CGImageGetRenderingIntent((void *)0x00000000000000);", - substrs=['$0 = 0']) + self.expect( + "expr int (*DBG_CGImageGetRenderingIntent)(void *) = ((int (*)(void *))CGImageGetRenderingIntent); DBG_CGImageGetRenderingIntent((void *)0x00000000000000);", + substrs=["$0 = 0"], + ) diff --git a/lldb/test/API/commands/expression/inline-namespace/TestInlineNamespace.py b/lldb/test/API/commands/expression/inline-namespace/TestInlineNamespace.py --- a/lldb/test/API/commands/expression/inline-namespace/TestInlineNamespace.py +++ b/lldb/test/API/commands/expression/inline-namespace/TestInlineNamespace.py @@ -10,12 +10,12 @@ class TestInlineNamespace(TestBase): - def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) # The 'A::B::f' function must be found via 'A::f' as 'B' is an inline # namespace. @@ -41,12 +41,32 @@ self.expect_expr("A::E::F::other_var", result_type="int", result_value="3") self.expect_expr("A::E::other_var", result_type="int", result_value="3") - self.expect("expr A::E::global_var", error=True, substrs=["no member named 'global_var' in namespace 'A::E'"]) - self.expect("expr A::E::F::global_var", error=True, substrs=["no member named 'global_var' in namespace 'A::E::F'"]) + self.expect( + "expr A::E::global_var", + error=True, + substrs=["no member named 'global_var' in namespace 'A::E'"], + ) + self.expect( + "expr A::E::F::global_var", + error=True, + substrs=["no member named 'global_var' in namespace 'A::E::F'"], + ) - self.expect("expr A::other_var", error=True, substrs=["no member named 'other_var' in namespace 'A'"]) - self.expect("expr A::B::other_var", error=True, substrs=["no member named 'other_var' in namespace 'A::B'"]) - self.expect("expr B::other_var", error=True, substrs=["no member named 'other_var' in namespace 'A::B'"]) + self.expect( + "expr A::other_var", + error=True, + substrs=["no member named 'other_var' in namespace 'A'"], + ) + self.expect( + "expr A::B::other_var", + error=True, + substrs=["no member named 'other_var' in namespace 'A::B'"], + ) + self.expect( + "expr B::other_var", + error=True, + substrs=["no member named 'other_var' in namespace 'A::B'"], + ) # 'frame variable' can correctly distinguish between A::B::global_var and A::global_var gvars = self.target().FindGlobalVariables("A::global_var", 10) @@ -54,4 +74,6 @@ self.assertEqual(gvars[0].GetValueAsSigned(), 4) self.expect("frame variable A::global_var", substrs=["(int) A::global_var = 4"]) - self.expect("frame variable A::B::global_var", substrs=["(int) A::B::global_var = 0"]) + self.expect( + "frame variable A::B::global_var", substrs=["(int) A::B::global_var = 0"] + ) diff --git a/lldb/test/API/commands/expression/invalid-args/TestInvalidArgsExpression.py b/lldb/test/API/commands/expression/invalid-args/TestInvalidArgsExpression.py --- a/lldb/test/API/commands/expression/invalid-args/TestInvalidArgsExpression.py +++ b/lldb/test/API/commands/expression/invalid-args/TestInvalidArgsExpression.py @@ -2,44 +2,72 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * -class InvalidArgsExpressionTestCase(TestBase): +class InvalidArgsExpressionTestCase(TestBase): @no_debug_info_test def test_invalid_lang(self): - self.expect("expression -l foo --", error=True, - substrs=["error: unknown language type: 'foo' for expression", - "List of supported languages:", - "c++", "c++11", "c++14"]) + self.expect( + "expression -l foo --", + error=True, + substrs=[ + "error: unknown language type: 'foo' for expression", + "List of supported languages:", + "c++", + "c++11", + "c++14", + ], + ) @no_debug_info_test def test_invalid_all_thread(self): - self.expect("expression -a foo --", error=True, - substrs=['error: invalid all-threads value setting: "foo"']) + self.expect( + "expression -a foo --", + error=True, + substrs=['error: invalid all-threads value setting: "foo"'], + ) @no_debug_info_test def test_invalid_ignore_br(self): - self.expect("expression -i foo --", error=True, - substrs=['error: could not convert "foo" to a boolean value.']) + self.expect( + "expression -i foo --", + error=True, + substrs=['error: could not convert "foo" to a boolean value.'], + ) @no_debug_info_test def test_invalid_allow_jit(self): - self.expect("expression -j foo --", error=True, - substrs=['error: could not convert "foo" to a boolean value.']) + self.expect( + "expression -j foo --", + error=True, + substrs=['error: could not convert "foo" to a boolean value.'], + ) @no_debug_info_test def test_invalid_timeout(self): - self.expect("expression -t foo --", error=True, - substrs=['error: invalid timeout setting "foo"']) + self.expect( + "expression -t foo --", + error=True, + substrs=['error: invalid timeout setting "foo"'], + ) - self.expect("expression -t \"\" --", error=True, - substrs=['error: invalid timeout setting ""']) + self.expect( + 'expression -t "" --', + error=True, + substrs=['error: invalid timeout setting ""'], + ) @no_debug_info_test def test_invalid_unwind(self): - self.expect("expression -u foo --", error=True, - substrs=['error: could not convert "foo" to a boolean value.']) + self.expect( + "expression -u foo --", + error=True, + substrs=['error: could not convert "foo" to a boolean value.'], + ) @no_debug_info_test def test_invalid_fixits(self): - self.expect("expression -X foo --", error=True, - substrs=['error: could not convert "foo" to a boolean value.']) + self.expect( + "expression -X foo --", + error=True, + substrs=['error: could not convert "foo" to a boolean value.'], + ) diff --git a/lldb/test/API/commands/expression/ir-interpreter-phi-nodes/TestIRInterpreterPHINodes.py b/lldb/test/API/commands/expression/ir-interpreter-phi-nodes/TestIRInterpreterPHINodes.py --- a/lldb/test/API/commands/expression/ir-interpreter-phi-nodes/TestIRInterpreterPHINodes.py +++ b/lldb/test/API/commands/expression/ir-interpreter-phi-nodes/TestIRInterpreterPHINodes.py @@ -9,32 +9,35 @@ class IRInterpreterPHINodesTestCase(TestBase): - def test_phi_node_support(self): """Test support for PHI nodes in the IR interpreter.""" self.build() exe = self.getBuildArtifact("a.out") - self.runCmd('file ' + exe, CURRENT_EXECUTABLE_SET) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break on the first assignment to i - line = line_number('main.cpp', 'i = 5') + line = line_number("main.cpp", "i = 5") lldbutil.run_break_set_by_file_and_line( - self, 'main.cpp', line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", line, num_expected_locations=1, loc_exact=True + ) - self.runCmd('run', RUN_SUCCEEDED) + self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint - self.expect('thread list', STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) - self.runCmd('s') + self.runCmd("s") # The logical 'or' causes a PHI node to be generated. Execute without JIT # to test that the interpreter can handle this - self.expect('expr -j 0 -- i == 3 || i == 5', substrs=['true']) + self.expect("expr -j 0 -- i == 3 || i == 5", substrs=["true"]) - self.runCmd('s') - self.expect('expr -j 0 -- i == 3 || i == 5', substrs=['false']) - self.runCmd('s') - self.expect('expr -j 0 -- i == 3 || i == 5', substrs=['true']) + self.runCmd("s") + self.expect("expr -j 0 -- i == 3 || i == 5", substrs=["false"]) + self.runCmd("s") + self.expect("expr -j 0 -- i == 3 || i == 5", substrs=["true"]) diff --git a/lldb/test/API/commands/expression/ir-interpreter/TestIRInterpreter.py b/lldb/test/API/commands/expression/ir-interpreter/TestIRInterpreter.py --- a/lldb/test/API/commands/expression/ir-interpreter/TestIRInterpreter.py +++ b/lldb/test/API/commands/expression/ir-interpreter/TestIRInterpreter.py @@ -16,13 +16,11 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.c. - self.line = line_number('main.c', - '// Set breakpoint here') + self.line = line_number("main.c", "// Set breakpoint here") # Disable confirmation prompt to avoid infinite wait self.runCmd("settings set auto-confirm true") - self.addTearDownHook( - lambda: self.runCmd("settings clear auto-confirm")) + self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) def build_and_run(self): """Test the IR interpreter""" @@ -31,34 +29,40 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.c", self.line, num_expected_locations=1, loc_exact=False) + self, "main.c", self.line, num_expected_locations=1, loc_exact=False + ) self.runCmd("run", RUN_SUCCEEDED) - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) # getpid() is POSIX, among other problems, see bug - @expectedFailureAll( - oslist=['windows'], - bugnumber="http://llvm.org/pr21765") + @expectedFailureAll(oslist=["windows"], bugnumber="http://llvm.org/pr21765") def test_ir_interpreter(self): self.build_and_run() options = lldb.SBExpressionOptions() options.SetLanguage(lldb.eLanguageTypeC_plus_plus) - set_up_expressions = ["int $i = 9", "int $j = 3", "int $k = 5", - "unsigned long long $ull = -1", "unsigned $u = -1"] - - expressions = ["$i + $j", - "$i - $j", - "$i * $j", - "$i / $j", - "$i % $k", - "$i << $j", - "$i & $j", - "$i | $j", - "$i ^ $j", - "($ull & -1) == $u"] + set_up_expressions = [ + "int $i = 9", + "int $j = 3", + "int $k = 5", + "unsigned long long $ull = -1", + "unsigned $u = -1", + ] + + expressions = [ + "$i + $j", + "$i - $j", + "$i * $j", + "$i / $j", + "$i % $k", + "$i << $j", + "$i & $j", + "$i | $j", + "$i ^ $j", + "($ull & -1) == $u", + ] for expression in set_up_expressions: self.frame().EvaluateExpression(expression, options) @@ -67,20 +71,24 @@ interp_expression = expression jit_expression = "(int)getpid(); " + expression - interp_result = self.frame().EvaluateExpression( - interp_expression, options).GetValueAsSigned() - jit_result = self.frame().EvaluateExpression( - jit_expression, options).GetValueAsSigned() + interp_result = ( + self.frame() + .EvaluateExpression(interp_expression, options) + .GetValueAsSigned() + ) + jit_result = ( + self.frame() + .EvaluateExpression(jit_expression, options) + .GetValueAsSigned() + ) self.assertEqual( - interp_result, - jit_result, - "While evaluating " + - expression) + interp_result, jit_result, "While evaluating " + expression + ) def test_type_conversions(self): target = self.dbg.GetDummyTarget() short_val = target.EvaluateExpression("(short)-1") self.assertEqual(short_val.GetValueAsSigned(), -1) - long_val = target.EvaluateExpression("(long) "+ short_val.GetName()) + long_val = target.EvaluateExpression("(long) " + short_val.GetName()) self.assertEqual(long_val.GetValueAsSigned(), -1) diff --git a/lldb/test/API/commands/expression/issue_11588/Test11588.py b/lldb/test/API/commands/expression/issue_11588/Test11588.py --- a/lldb/test/API/commands/expression/issue_11588/Test11588.py +++ b/lldb/test/API/commands/expression/issue_11588/Test11588.py @@ -5,7 +5,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -13,13 +12,12 @@ class Issue11581TestCase(TestBase): - - @skipIfWindows #This test is now flaky on windows, see llvm.org/pr24778 + @skipIfWindows # This test is now flaky on windows, see llvm.org/pr24778 def test_11581_commands(self): # This is the function to remove the custom commands in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type synthetic clear', check=False) + self.runCmd("type synthetic clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -27,22 +25,28 @@ """valobj.AddressOf() should return correct values.""" self.build() - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - 'Set breakpoint here.', - lldb.SBFileSpec("main.cpp", False)) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set breakpoint here.", lldb.SBFileSpec("main.cpp", False) + ) self.runCmd("command script import --allow-reload s11588.py") self.runCmd( - "type synthetic add --python-class s11588.Issue11581SyntheticProvider StgClosure") + "type synthetic add --python-class s11588.Issue11581SyntheticProvider StgClosure" + ) - self.expect("expr --show-types -- *((StgClosure*)(r14-1))", - substrs=["(StgClosure) $", - "(StgClosure *) &$", "0x", - "addr = ", - "load_address = "]) + self.expect( + "expr --show-types -- *((StgClosure*)(r14-1))", + substrs=[ + "(StgClosure) $", + "(StgClosure *) &$", + "0x", + "addr = ", + "load_address = ", + ], + ) # register r14 is an x86_64 extension let's skip this part of the test # if we are on a different architecture - if self.getArchitecture() == 'x86_64': + if self.getArchitecture() == "x86_64": target = self.dbg.GetSelectedTarget() process = target.GetProcess() frame = process.GetSelectedThread().GetSelectedFrame() @@ -52,14 +56,18 @@ addr = addr - 1 self.runCmd("register write r14 %d" % addr) self.expect( - "register read r14", substrs=[ - "0x", hex(addr)[ - 2:].rstrip("L")]) # Remove trailing 'L' if it exists - self.expect("expr --show-types -- *(StgClosure*)$r14", - substrs=["(StgClosure) $", - "(StgClosure *) &$", "0x", - hex(addr)[2:].rstrip("L"), - "addr = ", - str(addr), - "load_address = ", - str(addr)]) + "register read r14", substrs=["0x", hex(addr)[2:].rstrip("L")] + ) # Remove trailing 'L' if it exists + self.expect( + "expr --show-types -- *(StgClosure*)$r14", + substrs=[ + "(StgClosure) $", + "(StgClosure *) &$", + "0x", + hex(addr)[2:].rstrip("L"), + "addr = ", + str(addr), + "load_address = ", + str(addr), + ], + ) diff --git a/lldb/test/API/commands/expression/issue_11588/s11588.py b/lldb/test/API/commands/expression/issue_11588/s11588.py --- a/lldb/test/API/commands/expression/issue_11588/s11588.py +++ b/lldb/test/API/commands/expression/issue_11588/s11588.py @@ -1,5 +1,4 @@ class Issue11581SyntheticProvider(object): - def __init__(self, valobj, dict): self.valobj = valobj self.addrOf = valobj.AddressOf() @@ -13,11 +12,11 @@ if index == 0: return self.addrOf if index == 1: - return self.valobj.CreateValueFromExpression( - "addr", str(self.addr)) + return self.valobj.CreateValueFromExpression("addr", str(self.addr)) if index == 2: return self.valobj.CreateValueFromExpression( - "load_address", str(self.load_address)) + "load_address", str(self.load_address) + ) def get_child_index(self, name): if name == "addrOf": diff --git a/lldb/test/API/commands/expression/macros/TestMacros.py b/lldb/test/API/commands/expression/macros/TestMacros.py --- a/lldb/test/API/commands/expression/macros/TestMacros.py +++ b/lldb/test/API/commands/expression/macros/TestMacros.py @@ -1,5 +1,3 @@ - - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -7,21 +5,20 @@ class TestMacros(TestBase): - - @skipIf(compiler="clang", compiler_version=['<', '9.0']) + @skipIf(compiler="clang", compiler_version=["<", "9.0"]) @expectedFailureAll( - compiler="clang", - bugnumber="clang does not emit .debug_macro[.dwo] sections.") + compiler="clang", bugnumber="clang does not emit .debug_macro[.dwo] sections." + ) @expectedFailureAll( debug_info="dwo", - bugnumber="GCC produces multiple .debug_macro.dwo sections and the spec is unclear as to what it means") + bugnumber="GCC produces multiple .debug_macro.dwo sections and the spec is unclear as to what it means", + ) + @expectedFailureAll(hostoslist=["windows"], compiler="gcc", triple=".*-android") @expectedFailureAll( - hostoslist=["windows"], compiler="gcc", - triple='.*-android') - @expectedFailureAll( - compiler="gcc", compiler_version=['<', '5.1'], - bugnumber=".debug_macro was introduced in DWARF 5, GCC supports it since version 5.1") + compiler_version=["<", "5.1"], + bugnumber=".debug_macro was introduced in DWARF 5, GCC supports it since version 5.1", + ) def test_expr_with_macros(self): self.build() @@ -32,64 +29,58 @@ self.assertTrue(src_file_spec.IsValid(), "Main source file") (target, process, thread, bp1) = lldbutil.run_to_source_breakpoint( - self, "Break here", src_file_spec) + self, "Break here", src_file_spec + ) # Get frame for current thread frame = thread.GetSelectedFrame() result = frame.EvaluateExpression("MACRO_1") self.assertTrue( - result.IsValid() and result.GetValue() == "100", - "MACRO_1 = 100") + result.IsValid() and result.GetValue() == "100", "MACRO_1 = 100" + ) result = frame.EvaluateExpression("MACRO_2") self.assertTrue( - result.IsValid() and result.GetValue() == "200", - "MACRO_2 = 200") + result.IsValid() and result.GetValue() == "200", "MACRO_2 = 200" + ) result = frame.EvaluateExpression("ONE") - self.assertTrue( - result.IsValid() and result.GetValue() == "1", - "ONE = 1") + self.assertTrue(result.IsValid() and result.GetValue() == "1", "ONE = 1") result = frame.EvaluateExpression("TWO") - self.assertTrue( - result.IsValid() and result.GetValue() == "2", - "TWO = 2") + self.assertTrue(result.IsValid() and result.GetValue() == "2", "TWO = 2") result = frame.EvaluateExpression("THREE") - self.assertTrue( - result.IsValid() and result.GetValue() == "3", - "THREE = 3") + self.assertTrue(result.IsValid() and result.GetValue() == "3", "THREE = 3") result = frame.EvaluateExpression("FOUR") - self.assertTrue( - result.IsValid() and result.GetValue() == "4", - "FOUR = 4") + self.assertTrue(result.IsValid() and result.GetValue() == "4", "FOUR = 4") result = frame.EvaluateExpression("HUNDRED") self.assertTrue( - result.IsValid() and result.GetValue() == "100", - "HUNDRED = 100") + result.IsValid() and result.GetValue() == "100", "HUNDRED = 100" + ) result = frame.EvaluateExpression("THOUSAND") self.assertTrue( - result.IsValid() and result.GetValue() == "1000", - "THOUSAND = 1000") + result.IsValid() and result.GetValue() == "1000", "THOUSAND = 1000" + ) result = frame.EvaluateExpression("MILLION") - self.assertTrue(result.IsValid() and result.GetValue() - == "1000000", "MILLION = 1000000") + self.assertTrue( + result.IsValid() and result.GetValue() == "1000000", "MILLION = 1000000" + ) result = frame.EvaluateExpression("MAX(ONE, TWO)") self.assertTrue( - result.IsValid() and result.GetValue() == "2", - "MAX(ONE, TWO) = 2") + result.IsValid() and result.GetValue() == "2", "MAX(ONE, TWO) = 2" + ) result = frame.EvaluateExpression("MAX(THREE, TWO)") self.assertTrue( - result.IsValid() and result.GetValue() == "3", - "MAX(THREE, TWO) = 3") + result.IsValid() and result.GetValue() == "3", "MAX(THREE, TWO) = 3" + ) # Get the thread of the process thread.StepOver() @@ -99,13 +90,13 @@ result = frame.EvaluateExpression("MACRO_2") self.assertTrue( - result.GetError().Fail(), - "Printing MACRO_2 fails in the mail file") + result.GetError().Fail(), "Printing MACRO_2 fails in the mail file" + ) result = frame.EvaluateExpression("FOUR") self.assertTrue( - result.GetError().Fail(), - "Printing FOUR fails in the main file") + result.GetError().Fail(), "Printing FOUR fails in the main file" + ) thread.StepInto() @@ -113,23 +104,23 @@ frame = thread.GetSelectedFrame() result = frame.EvaluateExpression("ONE") - self.assertTrue( - result.IsValid() and result.GetValue() == "1", - "ONE = 1") + self.assertTrue(result.IsValid() and result.GetValue() == "1", "ONE = 1") result = frame.EvaluateExpression("MAX(ONE, TWO)") self.assertTrue( - result.IsValid() and result.GetValue() == "2", - "MAX(ONE, TWO) = 2") + result.IsValid() and result.GetValue() == "2", "MAX(ONE, TWO) = 2" + ) # This time, MACRO_1 and MACRO_2 are not visible. result = frame.EvaluateExpression("MACRO_1") - self.assertTrue(result.GetError().Fail(), - "Printing MACRO_1 fails in the header file") + self.assertTrue( + result.GetError().Fail(), "Printing MACRO_1 fails in the header file" + ) result = frame.EvaluateExpression("MACRO_2") - self.assertTrue(result.GetError().Fail(), - "Printing MACRO_2 fails in the header file") + self.assertTrue( + result.GetError().Fail(), "Printing MACRO_2 fails in the header file" + ) # Check that the macro definitions do not trigger bogus Clang # diagnostics about macro redefinitions. diff --git a/lldb/test/API/commands/expression/memory-allocation/TestMemoryAllocSettings.py b/lldb/test/API/commands/expression/memory-allocation/TestMemoryAllocSettings.py --- a/lldb/test/API/commands/expression/memory-allocation/TestMemoryAllocSettings.py +++ b/lldb/test/API/commands/expression/memory-allocation/TestMemoryAllocSettings.py @@ -7,8 +7,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestMemoryAllocSettings(TestBase): +class TestMemoryAllocSettings(TestBase): def test(self): """Test changing settings for expression memory allocation.""" self.build() @@ -24,12 +24,15 @@ self.runCmd("expression -- int foo; &foo") self.assertTrue(os.path.isfile(self.log_file)) - with open(self.log_file, 'r') as f: + with open(self.log_file, "r") as f: log = f.read() - alloc0 = re.search('^.*IRMemoryMap::Malloc.+?0xdead0000.*$', log, re.MULTILINE) + alloc0 = re.search("^.*IRMemoryMap::Malloc.+?0xdead0000.*$", log, re.MULTILINE) # Malloc adds additional bytes to allocation size, hence 10007 - alloc1 = re.search('^.*IRMemoryMap::Malloc\s*?\(10007.+?0xdead1000.*$', log, re.MULTILINE) + alloc1 = re.search( + "^.*IRMemoryMap::Malloc\s*?\(10007.+?0xdead1000.*$", log, re.MULTILINE + ) self.assertTrue(alloc0, "Couldn't find an allocation at a given address.") - self.assertTrue(alloc1, "Couldn't find an allocation of a given size at a given address.") - + self.assertTrue( + alloc1, "Couldn't find an allocation of a given size at a given address." + ) diff --git a/lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py b/lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py --- a/lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py +++ b/lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py @@ -7,15 +7,15 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import PExpectTest -class MultilineCompletionTest(PExpectTest): +class MultilineCompletionTest(PExpectTest): def start_expression_editor(self): - """ Starts the multiline expression editor. """ + """Starts the multiline expression editor.""" self.child.send("expression\n") self.child.expect_exact("terminate with an empty line to evaluate") def exit_expression_editor(self): - """ Exits the multiline expression editor. """ + """Exits the multiline expression editor.""" # Send a newline to finish the current line. The second newline will # finish the new empty line which will exit the editor. The space at the # start prevents that the first newline already exits the editor (in @@ -28,13 +28,13 @@ # under ASAN on a loaded machine.. @skipIfAsan @skipIfEditlineSupportMissing - @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr49408') + @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr49408") @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) def test_basic_completion(self): """Test that we can complete a simple multiline expression""" self.build() - self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100,500)) + self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100, 500)) self.expect("b main", substrs=["Breakpoint 1", "address ="]) self.expect("run", substrs=["stop reason = breakpoint 1"]) @@ -42,13 +42,20 @@ self.child.send("to_\t") # editline might move the cursor back to the start of the line via \r # and then back to its original position. - self.child.expect(re.compile(b"to_(\r" + self.cursor_forward_escape_seq(len(" 1: to_")) + b")?complete")) + self.child.expect( + re.compile( + b"to_(\r" + + self.cursor_forward_escape_seq(len(" 1: to_")) + + b")?complete" + ) + ) self.exit_expression_editor() # Check that completion empty input in a function with only one # local variable works. - self.expect("breakpoint set -p 'break in single_local_func'", - substrs=["Breakpoint 2"]) + self.expect( + "breakpoint set -p 'break in single_local_func'", substrs=["Breakpoint 2"] + ) self.expect("continue", substrs=["stop reason = breakpoint 2"]) self.start_expression_editor() self.child.send("\t") diff --git a/lldb/test/API/commands/expression/multiline-navigation/TestMultilineNavigation.py b/lldb/test/API/commands/expression/multiline-navigation/TestMultilineNavigation.py --- a/lldb/test/API/commands/expression/multiline-navigation/TestMultilineNavigation.py +++ b/lldb/test/API/commands/expression/multiline-navigation/TestMultilineNavigation.py @@ -7,8 +7,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import PExpectTest -class TestCase(PExpectTest): +class TestCase(PExpectTest): arrow_up = "\033[A" arrow_down = "\033[B" @@ -16,8 +16,8 @@ # under ASAN on a loaded machine.. @skipIfAsan @skipIfEditlineSupportMissing - @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr48316') - @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot + @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr48316") + @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot def test_nav_arrow_up(self): """Tests that we can navigate back to the previous line with the up arrow""" self.launch() @@ -40,8 +40,8 @@ @skipIfAsan @skipIfEditlineSupportMissing - @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr48316') - @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot + @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr48316") + @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot def test_nav_arrow_down(self): """Tests that we can navigate to the next line with the down arrow""" self.launch() @@ -72,7 +72,7 @@ @skipIfAsan @skipIfEditlineSupportMissing - @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot + @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot def test_nav_arrow_up_empty(self): """ Tests that navigating with the up arrow doesn't crash and skips diff --git a/lldb/test/API/commands/expression/namespace-alias/TestInlineNamespaceAlias.py b/lldb/test/API/commands/expression/namespace-alias/TestInlineNamespaceAlias.py --- a/lldb/test/API/commands/expression/namespace-alias/TestInlineNamespaceAlias.py +++ b/lldb/test/API/commands/expression/namespace-alias/TestInlineNamespaceAlias.py @@ -10,13 +10,15 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestInlineNamespace(TestBase): - @skipIf(compiler="clang", compiler_version=['<', '16.0']) + @skipIf(compiler="clang", compiler_version=["<", "16.0"]) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "return A::B::C::a", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "return A::B::C::a", lldb.SBFileSpec("main.cpp") + ) self.expect_expr("A::C::a", result_type="int", result_value="-1") self.expect_expr("A::D::a", result_type="int", result_value="-1") diff --git a/lldb/test/API/commands/expression/namespace_local_var_same_name_cpp_and_c/TestNamespaceLocalVarSameNameCppAndC.py b/lldb/test/API/commands/expression/namespace_local_var_same_name_cpp_and_c/TestNamespaceLocalVarSameNameCppAndC.py --- a/lldb/test/API/commands/expression/namespace_local_var_same_name_cpp_and_c/TestNamespaceLocalVarSameNameCppAndC.py +++ b/lldb/test/API/commands/expression/namespace_local_var_same_name_cpp_and_c/TestNamespaceLocalVarSameNameCppAndC.py @@ -3,15 +3,16 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestNamespaceLocalVarSameNameCppAndC(TestBase): +class TestNamespaceLocalVarSameNameCppAndC(TestBase): @skipUnlessDarwin @add_test_categories(["gmodules"]) def test_namespace_local_var_same_name_cpp_and_c(self): self.build() - (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp", False)) + (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) self.expect_expr("error", result_type="int", result_value="1") lldbutil.continue_to_breakpoint(self.process, bkpt) diff --git a/lldb/test/API/commands/expression/namespace_local_var_same_name_obj_c/TestNamespaceLocalVarSameNameObjC.py b/lldb/test/API/commands/expression/namespace_local_var_same_name_obj_c/TestNamespaceLocalVarSameNameObjC.py --- a/lldb/test/API/commands/expression/namespace_local_var_same_name_obj_c/TestNamespaceLocalVarSameNameObjC.py +++ b/lldb/test/API/commands/expression/namespace_local_var_same_name_obj_c/TestNamespaceLocalVarSameNameObjC.py @@ -3,19 +3,18 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestNamespaceLocalVarSameNameObjC(TestBase): +class TestNamespaceLocalVarSameNameObjC(TestBase): @add_test_categories(["gmodules", "objc"]) def test_namespace_local_var_same_name_obj_c(self): self.build() - (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("util.mm", False)) + (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("util.mm", False) + ) - self.expect("expr error", - substrs=['(NSError *) $0 =']) + self.expect("expr error", substrs=["(NSError *) $0 ="]) lldbutil.continue_to_breakpoint(self.process, bkpt) - self.expect("expr error", - substrs=['(NSError *) $1 =']) + self.expect("expr error", substrs=["(NSError *) $1 ="]) diff --git a/lldb/test/API/commands/expression/no-deadlock/TestExprDoesntBlock.py b/lldb/test/API/commands/expression/no-deadlock/TestExprDoesntBlock.py --- a/lldb/test/API/commands/expression/no-deadlock/TestExprDoesntBlock.py +++ b/lldb/test/API/commands/expression/no-deadlock/TestExprDoesntBlock.py @@ -9,7 +9,6 @@ class ExprDoesntDeadlockTestCase(TestBase): - @add_test_categories(["basic_process"]) def test_with_run_command(self): """Test that expr will time out and allow other threads to run if it blocks.""" @@ -20,25 +19,25 @@ # gets called. main_file_spec = lldb.SBFileSpec("locking.cpp") - breakpoint = target.BreakpointCreateBySourceRegex( - 'Break here', main_file_spec) + breakpoint = target.BreakpointCreateBySourceRegex("Break here", main_file_spec) if self.TraceOn(): print("breakpoint:", breakpoint) - self.assertTrue(breakpoint and - breakpoint.GetNumLocations() == 1, - VALID_BREAKPOINT) + self.assertTrue( + breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT + ) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.line1 and the break condition should hold. from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( thread.IsValid(), - "There should be a thread stopped due to breakpoint condition") + "There should be a thread stopped due to breakpoint condition", + ) frame0 = thread.GetFrameAtIndex(0) diff --git a/lldb/test/API/commands/expression/options/TestExprOptions.py b/lldb/test/API/commands/expression/options/TestExprOptions.py --- a/lldb/test/API/commands/expression/options/TestExprOptions.py +++ b/lldb/test/API/commands/expression/options/TestExprOptions.py @@ -8,7 +8,6 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.decorators import * @@ -16,14 +15,13 @@ class ExprOptionsTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) self.main_source = "main.cpp" self.main_source_spec = lldb.SBFileSpec(self.main_source) - self.line = line_number('main.cpp', '// breakpoint_in_main') + self.line = line_number("main.cpp", "// breakpoint_in_main") self.exe = self.getBuildArtifact("a.out") def test_expr_options(self): @@ -34,7 +32,8 @@ self.dbg.SetAsync(False) (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, '// breakpoint_in_main', self.main_source_spec) + self, "// breakpoint_in_main", self.main_source_spec + ) frame = thread.GetFrameAtIndex(0) options = lldb.SBExpressionOptions() @@ -42,21 +41,21 @@ # test --language on C++ expression using the SB API's # Make sure we can evaluate a C++11 expression. - val = frame.EvaluateExpression('foo != nullptr') + val = frame.EvaluateExpression("foo != nullptr") self.assertTrue(val.IsValid()) self.assertSuccess(val.GetError()) self.DebugSBValue(val) # Make sure it still works if language is set to C++11: options.SetLanguage(lldb.eLanguageTypeC_plus_plus_11) - val = frame.EvaluateExpression('foo != nullptr', options) + val = frame.EvaluateExpression("foo != nullptr", options) self.assertTrue(val.IsValid()) self.assertSuccess(val.GetError()) self.DebugSBValue(val) # Make sure it fails if language is set to C: options.SetLanguage(lldb.eLanguageTypeC) - val = frame.EvaluateExpression('foo != nullptr', options) + val = frame.EvaluateExpression("foo != nullptr", options) self.assertTrue(val.IsValid()) self.assertFalse(val.GetError().Success()) @@ -69,20 +68,21 @@ self.dbg.SetAsync(False) (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, '// breakpoint_in_main', self.main_source_spec) + self, "// breakpoint_in_main", self.main_source_spec + ) frame = thread.GetFrameAtIndex(0) options = lldb.SBExpressionOptions() # Make sure we can retrieve `id` variable if language is set to C++11: options.SetLanguage(lldb.eLanguageTypeC_plus_plus_11) - val = frame.EvaluateExpression('id == 0', options) + val = frame.EvaluateExpression("id == 0", options) self.assertTrue(val.IsValid()) self.assertSuccess(val.GetError()) self.DebugSBValue(val) # Make sure we can't retrieve `id` variable if language is set to ObjC: options.SetLanguage(lldb.eLanguageTypeObjC) - val = frame.EvaluateExpression('id == 0', options) + val = frame.EvaluateExpression("id == 0", options) self.assertTrue(val.IsValid()) self.assertFalse(val.GetError().Success()) diff --git a/lldb/test/API/commands/expression/persist_objc_pointeetype/TestPersistObjCPointeeType.py b/lldb/test/API/commands/expression/persist_objc_pointeetype/TestPersistObjCPointeeType.py --- a/lldb/test/API/commands/expression/persist_objc_pointeetype/TestPersistObjCPointeeType.py +++ b/lldb/test/API/commands/expression/persist_objc_pointeetype/TestPersistObjCPointeeType.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,15 +10,16 @@ class PersistObjCPointeeType(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.cpp. - self.line = line_number('main.m', '// break here') + self.line = line_number("main.m", "// break here") @skipIf(archs=["i386", "i686"]) - @skipIf(debug_info="gmodules", archs=['arm64', 'armv7', 'armv7k', 'arm64e', 'arm64_32']) # compile error with gmodules for iOS + @skipIf( + debug_info="gmodules", archs=["arm64", "armv7", "armv7k", "arm64e", "arm64_32"] + ) # compile error with gmodules for iOS @add_test_categories(["objc"]) def test_with(self): """Test that we can p *objcObject""" @@ -34,7 +34,8 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.m", self.line, loc_exact=True) + self, "main.m", self.line, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) diff --git a/lldb/test/API/commands/expression/persistent_ptr_update/TestPersistentPtrUpdate.py b/lldb/test/API/commands/expression/persistent_ptr_update/TestPersistentPtrUpdate.py --- a/lldb/test/API/commands/expression/persistent_ptr_update/TestPersistentPtrUpdate.py +++ b/lldb/test/API/commands/expression/persistent_ptr_update/TestPersistentPtrUpdate.py @@ -3,14 +3,12 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * class PersistentPtrUpdateTestCase(TestBase): - def test(self): """Test that we can have persistent pointer variables""" self.build() @@ -23,7 +21,7 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) - self.runCmd('break set -p here') + self.runCmd("break set -p here") self.runCmd("run", RUN_SUCCEEDED) @@ -31,4 +29,4 @@ self.runCmd("continue") - self.expect("expr $foo", substrs=['$foo', '0x0']) + self.expect("expr $foo", substrs=["$foo", "0x0"]) diff --git a/lldb/test/API/commands/expression/persistent_types/TestNestedPersistentTypes.py b/lldb/test/API/commands/expression/persistent_types/TestNestedPersistentTypes.py --- a/lldb/test/API/commands/expression/persistent_types/TestNestedPersistentTypes.py +++ b/lldb/test/API/commands/expression/persistent_types/TestNestedPersistentTypes.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class NestedPersistentTypesTestCase(TestBase): - def test_persistent_types(self): """Test that nested persistent types work.""" self.build() @@ -24,16 +22,12 @@ self.runCmd("expression struct $foo { int a; int b; };") - self.runCmd( - "expression struct $bar { struct $foo start; struct $foo end; };") + self.runCmd("expression struct $bar { struct $foo start; struct $foo end; };") self.runCmd("expression struct $bar $my_bar = {{ 2, 3 }, { 4, 5 }};") - self.expect("expression $my_bar", - substrs=['a = 2', 'b = 3', 'a = 4', 'b = 5']) + self.expect("expression $my_bar", substrs=["a = 2", "b = 3", "a = 4", "b = 5"]) - self.expect("expression $my_bar.start.b", - substrs=['(int)', '3']) + self.expect("expression $my_bar.start.b", substrs=["(int)", "3"]) - self.expect("expression $my_bar.end.b", - substrs=['(int)', '5']) + self.expect("expression $my_bar.end.b", substrs=["(int)", "5"]) diff --git a/lldb/test/API/commands/expression/persistent_types/TestPersistentTypes.py b/lldb/test/API/commands/expression/persistent_types/TestPersistentTypes.py --- a/lldb/test/API/commands/expression/persistent_types/TestPersistentTypes.py +++ b/lldb/test/API/commands/expression/persistent_types/TestPersistentTypes.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class PersistenttypesTestCase(TestBase): - def test_persistent_types(self): """Test that lldb persistent types works correctly.""" self.build() @@ -26,65 +24,46 @@ self.expect( "expression struct $foo $my_foo; $my_foo.a = 2; $my_foo.b = 3;", - startstr="(int) $0 = 3") + startstr="(int) $0 = 3", + ) - self.expect("expression $my_foo", - substrs=['a = 2', 'b = 3']) + self.expect("expression $my_foo", substrs=["a = 2", "b = 3"]) self.runCmd("expression typedef int $bar") - self.expect("expression $bar i = 5; i", - startstr="($bar) $1 = 5") + self.expect("expression $bar i = 5; i", startstr="($bar) $1 = 5") - self.runCmd( - "expression struct $foobar { char a; char b; char c; char d; };") + self.runCmd("expression struct $foobar { char a; char b; char c; char d; };") self.runCmd("next") self.expect( "memory read foo -t $foobar", - substrs=[ - '($foobar) 0x', - ' = ', - "a = 'H'", - "b = 'e'", - "c = 'l'", - "d = 'l'"]) # persistent types are OK to use for memory read + substrs=["($foobar) 0x", " = ", "a = 'H'", "b = 'e'", "c = 'l'", "d = 'l'"], + ) # persistent types are OK to use for memory read self.expect( "memory read foo -t $foobar -x c", - substrs=[ - '($foobar) 0x', - ' = ', - "a = 'H'", - "b = 'e'", - "c = 'l'", - "d = 'l'"]) # persistent types are OK to use for memory read + substrs=["($foobar) 0x", " = ", "a = 'H'", "b = 'e'", "c = 'l'", "d = 'l'"], + ) # persistent types are OK to use for memory read self.expect( "memory read foo -t foobar", - substrs=[ - '($foobar) 0x', - ' = ', - "a = 'H'", - "b = 'e'", - "c = 'l'", - "d = 'l'"], + substrs=["($foobar) 0x", " = ", "a = 'H'", "b = 'e'", "c = 'l'", "d = 'l'"], matching=False, - error=True) # the type name is $foobar, make sure we settle for nothing less + error=True, + ) # the type name is $foobar, make sure we settle for nothing less - self.expect("expression struct { int a; int b; } x = { 2, 3 }; x", - substrs=['a = 2', 'b = 3']) + self.expect( + "expression struct { int a; int b; } x = { 2, 3 }; x", + substrs=["a = 2", "b = 3"], + ) self.expect( "expression struct { int x; int y; int z; } object; object.y = 1; object.z = 3; object.x = 2; object", - substrs=[ - 'x = 2', - 'y = 1', - 'z = 3']) + substrs=["x = 2", "y = 1", "z = 3"], + ) self.expect( "expression struct A { int x; int y; }; struct { struct A a; int z; } object; object.a.y = 1; object.z = 3; object.a.x = 2; object", - substrs=[ - 'x = 2', - 'y = 1', - 'z = 3']) + substrs=["x = 2", "y = 1", "z = 3"], + ) diff --git a/lldb/test/API/commands/expression/persistent_variables/TestPersistentVariables.py b/lldb/test/API/commands/expression/persistent_variables/TestPersistentVariables.py --- a/lldb/test/API/commands/expression/persistent_variables/TestPersistentVariables.py +++ b/lldb/test/API/commands/expression/persistent_variables/TestPersistentVariables.py @@ -3,17 +3,17 @@ """ - import lldb from lldbsuite.test.lldbtest import * class PersistentVariablesTestCase(TestBase): - def test_persistent_variables(self): """Test that lldb persistent variables works correctly.""" self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", lldb.SBFileSpec("main.c")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.c") + ) self.runCmd("expr int $i = i") self.expect_expr("$i == i", result_type="bool", result_value="true") @@ -28,28 +28,45 @@ self.expect_expr("(long)$4", result_type="long", result_value="-2") # Try assigning an existing persistent veriable with a numeric name. - self.expect("expr int $2 = 1234", error=True, - substrs=["Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names"]) + self.expect( + "expr int $2 = 1234", + error=True, + substrs=[ + "Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names" + ], + ) # $2 should still have its original value. self.expect_expr("$2", result_type="int", result_value="8") # Try assigning an non-existing persistent veriable with a numeric name. - self.expect("expr int $200 = 3", error=True, - substrs=["Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names"]) + self.expect( + "expr int $200 = 3", + error=True, + substrs=[ + "Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names" + ], + ) # Test that $200 wasn't created by the previous expression. - self.expect("expr $200", error=True, - substrs=["use of undeclared identifier '$200'"]) + self.expect( + "expr $200", error=True, substrs=["use of undeclared identifier '$200'"] + ) # Try redeclaring the persistent variable with the same type. # This should be rejected as we treat them as if they are globals. - self.expect("expr int $i = 123", error=True, - substrs=["error: redefinition of persistent variable '$i'"]) + self.expect( + "expr int $i = 123", + error=True, + substrs=["error: redefinition of persistent variable '$i'"], + ) self.expect_expr("$i", result_type="int", result_value="5") # Try redeclaring the persistent variable with another type. Should # also be rejected. - self.expect("expr long $i = 123", error=True, - substrs=["error: redefinition of persistent variable '$i'"]) + self.expect( + "expr long $i = 123", + error=True, + substrs=["error: redefinition of persistent variable '$i'"], + ) self.expect_expr("$i", result_type="int", result_value="5") # Try assigning the persistent variable a new value. diff --git a/lldb/test/API/commands/expression/po_verbosity/TestPoVerbosity.py b/lldb/test/API/commands/expression/po_verbosity/TestPoVerbosity.py --- a/lldb/test/API/commands/expression/po_verbosity/TestPoVerbosity.py +++ b/lldb/test/API/commands/expression/po_verbosity/TestPoVerbosity.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,13 +10,11 @@ class PoVerbosityTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.cpp. - self.line = line_number('main.m', - '// Stop here') + self.line = line_number("main.m", "// Stop here") @add_test_categories(["objc"]) def test(self): @@ -27,8 +24,8 @@ # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type summary clear', check=False) - self.runCmd('type synthetic clear', check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synthetic clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -37,26 +34,22 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.m", self.line, loc_exact=True) + self, "main.m", self.line, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) self.runCmd("settings set target.prefer-dynamic-value no-dynamic-values") - self.expect("expr -O -v -- foo", - substrs=['(id) $', ' = 0x', '1 = 2', '2 = 3;']) - self.expect("expr -O -vfull -- foo", - substrs=['(id) $', ' = 0x', '1 = 2', '2 = 3;']) - self.expect("expr -O -- foo", matching=False, - substrs=['(id) $']) + self.expect("expr -O -v -- foo", substrs=["(id) $", " = 0x", "1 = 2", "2 = 3;"]) + self.expect( + "expr -O -vfull -- foo", substrs=["(id) $", " = 0x", "1 = 2", "2 = 3;"] + ) + self.expect("expr -O -- foo", matching=False, substrs=["(id) $"]) - self.expect("expr -O -- 22", matching=False, - substrs=['(int) $']) - self.expect("expr -O -- 22", - substrs=['22']) + self.expect("expr -O -- 22", matching=False, substrs=["(int) $"]) + self.expect("expr -O -- 22", substrs=["22"]) - self.expect("expr -O -vfull -- 22", - substrs=['(int) $', ' = 22']) + self.expect("expr -O -vfull -- 22", substrs=["(int) $", " = 22"]) - self.expect("expr -O -v -- 22", - substrs=['(int) $', ' = 22']) + self.expect("expr -O -v -- 22", substrs=["(int) $", " = 22"]) diff --git a/lldb/test/API/commands/expression/pr35310/TestExprsBug35310.py b/lldb/test/API/commands/expression/pr35310/TestExprsBug35310.py --- a/lldb/test/API/commands/expression/pr35310/TestExprsBug35310.py +++ b/lldb/test/API/commands/expression/pr35310/TestExprsBug35310.py @@ -1,11 +1,10 @@ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class ExprBug35310(TestBase): +class ExprBug35310(TestBase): def setUp(self): # Call super's setUp(). TestBase.setUp(self) @@ -21,8 +20,7 @@ """ self.build() - lldbutil.run_to_source_breakpoint(self, - '// Break here', self.main_source_spec) + lldbutil.run_to_source_breakpoint(self, "// Break here", self.main_source_spec) - self.expect_expr("a.test_abi_tag()", result_value='1') - self.expect_expr("a.test_asm_name()", result_value='2') + self.expect_expr("a.test_abi_tag()", result_value="1") + self.expect_expr("a.test_asm_name()", result_value="2") diff --git a/lldb/test/API/commands/expression/pr52257/TestExprCrash.py b/lldb/test/API/commands/expression/pr52257/TestExprCrash.py --- a/lldb/test/API/commands/expression/pr52257/TestExprCrash.py +++ b/lldb/test/API/commands/expression/pr52257/TestExprCrash.py @@ -9,8 +9,9 @@ class ExprCrashTestCase(TestBase): - def test_pr52257(self): self.build() self.createTestTarget() - self.expect_expr("b", result_type="B", result_children=[ValueCheck(name="tag_set_")]) + self.expect_expr( + "b", result_type="B", result_children=[ValueCheck(name="tag_set_")] + ) diff --git a/lldb/test/API/commands/expression/radar_8638051/Test8638051.py b/lldb/test/API/commands/expression/radar_8638051/Test8638051.py --- a/lldb/test/API/commands/expression/radar_8638051/Test8638051.py +++ b/lldb/test/API/commands/expression/radar_8638051/Test8638051.py @@ -3,13 +3,11 @@ """ - import lldb from lldbsuite.test.lldbtest import * class Radar8638051TestCase(TestBase): - def test_expr_commands(self): """The following expression commands should not crash.""" self.build() @@ -25,6 +23,5 @@ # rdar://problem/8638051 # lldb expression command: Could this crash be avoided - self.expect("expression &val", - startstr="(int *) $2 = ") + self.expect("expression &val", startstr="(int *) $2 = ") # (int *) $2 = 0x.... diff --git a/lldb/test/API/commands/expression/radar_9531204/TestPrintfAfterUp.py b/lldb/test/API/commands/expression/radar_9531204/TestPrintfAfterUp.py --- a/lldb/test/API/commands/expression/radar_9531204/TestPrintfAfterUp.py +++ b/lldb/test/API/commands/expression/radar_9531204/TestPrintfAfterUp.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class Radar9531204TestCase(TestBase): - # rdar://problem/9531204 def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" @@ -20,7 +18,8 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_symbol( - self, 'foo', sym_exact=True, num_expected_locations=1) + self, "foo", sym_exact=True, num_expected_locations=1 + ) self.runCmd("run", RUN_SUCCEEDED) @@ -31,7 +30,7 @@ # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack - self.runCmd('up') # frame select -r 1 + self.runCmd("up") # frame select -r 1 self.runCmd("frame variable") diff --git a/lldb/test/API/commands/expression/radar_9673664/TestExprHelpExamples.py b/lldb/test/API/commands/expression/radar_9673664/TestExprHelpExamples.py --- a/lldb/test/API/commands/expression/radar_9673664/TestExprHelpExamples.py +++ b/lldb/test/API/commands/expression/radar_9673664/TestExprHelpExamples.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,13 +10,12 @@ class Radar9673644TestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). self.main_source = "main.c" - self.line = line_number(self.main_source, '// Set breakpoint here.') + self.line = line_number(self.main_source, "// Set breakpoint here.") def test_expr_commands(self): """The following expression commands should just work.""" @@ -26,17 +24,13 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, - self.main_source, - self.line, - num_expected_locations=1, - loc_exact=True) + self, self.main_source, self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # rdar://problem/9673664 lldb expression evaluation problem - self.expect('expr char str[] = "foo"; str[0]', - substrs=["'f'"]) + self.expect('expr char str[] = "foo"; str[0]', substrs=["'f'"]) # runCmd: expr char c[] = "foo"; c[0] # output: (char) $0 = 'f' diff --git a/lldb/test/API/commands/expression/rdar44436068/Test128BitsInteger.py b/lldb/test/API/commands/expression/rdar44436068/Test128BitsInteger.py --- a/lldb/test/API/commands/expression/rdar44436068/Test128BitsInteger.py +++ b/lldb/test/API/commands/expression/rdar44436068/Test128BitsInteger.py @@ -1,6 +1,6 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), - decorators.skipIf(archs=["arm", "armv7k", "i386"])) - +lldbinline.MakeInlineTest( + __file__, globals(), decorators.skipIf(archs=["arm", "armv7k", "i386"]) +) diff --git a/lldb/test/API/commands/expression/result_numbering/TestResultNumbering.py b/lldb/test/API/commands/expression/result_numbering/TestResultNumbering.py --- a/lldb/test/API/commands/expression/result_numbering/TestResultNumbering.py +++ b/lldb/test/API/commands/expression/result_numbering/TestResultNumbering.py @@ -4,14 +4,12 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * class TestExpressionResultNumbering(TestBase): - NO_DEBUG_INFO_TESTCASE = True def test_sample_rename_this(self): @@ -20,11 +18,13 @@ self.do_numbering_test() def do_numbering_test(self): - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - "Set a breakpoint here", self.main_source_file) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", self.main_source_file + ) - bkpt = target.BreakpointCreateBySourceRegex("Add conditions to this breakpoint", - self.main_source_file) + bkpt = target.BreakpointCreateBySourceRegex( + "Add conditions to this breakpoint", self.main_source_file + ) self.assertEqual(bkpt.GetNumLocations(), 1, "Set the breakpoint") bkpt.SetCondition("call_me(value) < 6") @@ -34,13 +34,15 @@ self.assertSuccess(result.GetError(), "Our expression succeeded") name = result.GetName() ordinal = int(name[1:]) - + process.Continue() # The condition evaluation had to run a 4 expressions, but we haven't # run any user expressions. result = thread.frames[0].EvaluateExpression("call_me(200)") - self.assertSuccess(result.GetError(), "Our expression succeeded the second time") + self.assertSuccess( + result.GetError(), "Our expression succeeded the second time" + ) after_name = result.GetName() after_ordinal = int(after_name[1:]) - self.assertEqual(ordinal + 1, after_ordinal) + self.assertEqual(ordinal + 1, after_ordinal) diff --git a/lldb/test/API/commands/expression/save_jit_objects/TestSaveJITObjects.py b/lldb/test/API/commands/expression/save_jit_objects/TestSaveJITObjects.py --- a/lldb/test/API/commands/expression/save_jit_objects/TestSaveJITObjects.py +++ b/lldb/test/API/commands/expression/save_jit_objects/TestSaveJITObjects.py @@ -9,8 +9,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class SaveJITObjectsTestCase(TestBase): +class SaveJITObjectsTestCase(TestBase): def enumerateJITFiles(self): return [f for f in os.listdir(self.getBuildDir()) if f.startswith("jit")] @@ -29,21 +29,28 @@ src_file_spec = lldb.SBFileSpec(src_file) (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, "break", src_file_spec) + self, "break", src_file_spec + ) frame = thread.frames[0] self.cleanJITFiles() frame.EvaluateExpression("(void*)malloc(0x1)") - self.assertEquals(self.countJITFiles(), 0, - "No files emitted with save-jit-objects-dir empty") - - self.runCmd("settings set target.save-jit-objects-dir {0}".format(self.getBuildDir())) + self.assertEquals( + self.countJITFiles(), 0, "No files emitted with save-jit-objects-dir empty" + ) + + self.runCmd( + "settings set target.save-jit-objects-dir {0}".format(self.getBuildDir()) + ) frame.EvaluateExpression("(void*)malloc(0x1)") jit_files_count = self.countJITFiles() self.cleanJITFiles() - self.assertNotEqual(jit_files_count, 0, - "At least one file emitted with save-jit-objects-dir set to the build dir") + self.assertNotEqual( + jit_files_count, + 0, + "At least one file emitted with save-jit-objects-dir set to the build dir", + ) process.Kill() os.chdir(self.getSourceDir()) diff --git a/lldb/test/API/commands/expression/scoped_enums/TestScopedEnumType.py b/lldb/test/API/commands/expression/scoped_enums/TestScopedEnumType.py --- a/lldb/test/API/commands/expression/scoped_enums/TestScopedEnumType.py +++ b/lldb/test/API/commands/expression/scoped_enums/TestScopedEnumType.py @@ -1,5 +1,3 @@ - - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -7,22 +5,21 @@ class ScopedEnumType(TestBase): - - @skipIf(dwarf_version=['<', '4']) + @skipIf(dwarf_version=["<", "4"]) def test(self): self.build() self.main_source = "main.cpp" self.main_source_spec = lldb.SBFileSpec(self.main_source) - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - '// Set break point at this line.', self.main_source_spec) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", self.main_source_spec + ) frame = thread.GetFrameAtIndex(0) - self.expect("expr f == Foo::FooBar", - substrs=['(bool) $0 = true']) + self.expect("expr f == Foo::FooBar", substrs=["(bool) $0 = true"]) - self.expect_expr("f == Foo::FooBar", result_value='true') - self.expect_expr("b == BarBar", result_value='true') + self.expect_expr("f == Foo::FooBar", result_value="true") + self.expect_expr("b == BarBar", result_value="true") ## b is not a Foo value = frame.EvaluateExpression("b == Foo::FooBar") diff --git a/lldb/test/API/commands/expression/static-initializers/TestStaticInitializers.py b/lldb/test/API/commands/expression/static-initializers/TestStaticInitializers.py --- a/lldb/test/API/commands/expression/static-initializers/TestStaticInitializers.py +++ b/lldb/test/API/commands/expression/static-initializers/TestStaticInitializers.py @@ -3,16 +3,20 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class StaticInitializers(TestBase): - @expectedFailureAll(archs="aarch64", oslist=["freebsd", "linux"], - bugnumber="https://bugs.llvm.org/show_bug.cgi?id=44053") +class StaticInitializers(TestBase): + @expectedFailureAll( + archs="aarch64", + oslist=["freebsd", "linux"], + bugnumber="https://bugs.llvm.org/show_bug.cgi?id=44053", + ) def test(self): - """ Test a static initializer. """ + """Test a static initializer.""" self.build() - lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp", False)) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) # We use counter to observe if the initializer was called. self.expect_expr("counter", result_type="int", result_value="0") @@ -20,17 +24,24 @@ self.expect_expr("counter", result_type="int", result_value="1") def test_failing_init(self): - """ Test a static initializer that fails to execute. """ + """Test a static initializer that fails to execute.""" self.build() - lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp", False)) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) # FIXME: This error message is not even remotely helpful. - self.expect("expr -p -- struct Foo2 { Foo2() { do_abort(); } }; Foo2 f;", error=True, - substrs=["error: couldn't run static initializer:"]) + self.expect( + "expr -p -- struct Foo2 { Foo2() { do_abort(); } }; Foo2 f;", + error=True, + substrs=["error: couldn't run static initializer:"], + ) def test_without_process(self): - """ Test a static initializer without a running process. """ - self.expect("expr -p -- int i = 0; struct Foo3 { Foo3() { ++i; } }; Foo3 f;", error=True, - substrs=["Top-level code needs to be inserted into a runnable target"]) + """Test a static initializer without a running process.""" + self.expect( + "expr -p -- int i = 0; struct Foo3 { Foo3() { ++i; } }; Foo3 f;", + error=True, + substrs=["Top-level code needs to be inserted into a runnable target"], + ) diff --git a/lldb/test/API/commands/expression/test/TestExprs.py b/lldb/test/API/commands/expression/test/TestExprs.py --- a/lldb/test/API/commands/expression/test/TestExprs.py +++ b/lldb/test/API/commands/expression/test/TestExprs.py @@ -12,7 +12,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -20,19 +19,17 @@ class BasicExprCommandsTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.c. self.line = line_number( - 'main.cpp', - '// Please test many expressions while stopped at this line:') + "main.cpp", "// Please test many expressions while stopped at this line:" + ) # Disable confirmation prompt to avoid infinite wait self.runCmd("settings set auto-confirm true") - self.addTearDownHook( - lambda: self.runCmd("settings clear auto-confirm")) + self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) def build_and_run(self): """These basic expression commands should work as expected.""" @@ -41,17 +38,18 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False + ) self.runCmd("run", RUN_SUCCEEDED) @expectedFailure( - "llvm.org/pr17135 APFloat::toString does not identify the correct (i.e. least) precision.") + "llvm.org/pr17135 APFloat::toString does not identify the correct (i.e. least) precision." + ) def test_floating_point_expr_commands(self): self.build_and_run() - self.expect("expression 2.234f", - patterns=["\(float\) \$.* = 2\.234"]) + self.expect("expression 2.234f", patterns=["\(float\) \$.* = 2\.234"]) # (float) $2 = 2.234 def test_many_expr_commands(self): @@ -66,12 +64,10 @@ self.expect_expr("argc + 22", result_type="int", result_value="23") self.expect_expr("argv", result_type="const char **") - self.expect("expression argv[0]", - substrs=["(const char *)", - "a.out"]) + self.expect("expression argv[0]", substrs=["(const char *)", "a.out"]) # (const char *) $8 = 0x... "/Volumes/data/lldb/svn/trunk/test/expression_command/test/a.out" - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) @expectedFlakeyNetBSD def test_evaluate_expression_python(self): """Test SBFrame.EvaluateExpression() API for evaluating an expression.""" @@ -84,35 +80,47 @@ self.assertTrue(breakpoint, VALID_BREAKPOINT) # Verify the breakpoint just created. - self.expect(str(breakpoint), BREAKPOINT_CREATED, exe=False, - substrs=['main.cpp', - str(self.line)]) + self.expect( + str(breakpoint), + BREAKPOINT_CREATED, + exe=False, + substrs=["main.cpp", str(self.line)], + ) # Launch the process, and do not stop at the entry point. # Pass 'X Y Z' as the args, which makes argc == 4. process = target.LaunchSimple( - ['X', 'Y', 'Z'], None, self.get_process_working_directory()) + ["X", "Y", "Z"], None, self.get_process_working_directory() + ) if not process: self.fail("SBTarget.LaunchProcess() failed") if process.GetState() != lldb.eStateStopped: - self.fail("Process should be in the 'stopped' state, " - "instead the actual state is: '%s'" % - lldbutil.state_type_to_str(process.GetState())) + self.fail( + "Process should be in the 'stopped' state, " + "instead the actual state is: '%s'" + % lldbutil.state_type_to_str(process.GetState()) + ) - thread = lldbutil.get_one_thread_stopped_at_breakpoint( - process, breakpoint) + thread = lldbutil.get_one_thread_stopped_at_breakpoint(process, breakpoint) self.assertIsNotNone( - thread, "Expected one thread to be stopped at the breakpoint") + thread, "Expected one thread to be stopped at the breakpoint" + ) # The filename of frame #0 should be 'main.cpp' and function is main. - self.expect(lldbutil.get_filenames(thread)[0], - "Break correctly at main.cpp", exe=False, - startstr="main.cpp") - self.expect(lldbutil.get_function_names(thread)[0], - "Break correctly at main()", exe=False, - startstr="main") + self.expect( + lldbutil.get_filenames(thread)[0], + "Break correctly at main.cpp", + exe=False, + startstr="main.cpp", + ) + self.expect( + lldbutil.get_function_names(thread)[0], + "Break correctly at main()", + exe=False, + startstr="main", + ) # We should be stopped on the breakpoint with a hit count of 1. self.assertEquals(breakpoint.GetHitCount(), 1, BREAKPOINT_HIT_ONCE) @@ -123,45 +131,49 @@ frame = thread.GetFrameAtIndex(0) val = frame.EvaluateExpression("2.234") - self.expect(val.GetValue(), "2.345 evaluated correctly", exe=False, - startstr="2.234") - self.expect(val.GetTypeName(), "2.345 evaluated correctly", exe=False, - startstr="double") + self.expect( + val.GetValue(), "2.345 evaluated correctly", exe=False, startstr="2.234" + ) + self.expect( + val.GetTypeName(), "2.345 evaluated correctly", exe=False, startstr="double" + ) self.DebugSBValue(val) val = frame.EvaluateExpression("argc") - self.expect(val.GetValue(), "Argc evaluated correctly", exe=False, - startstr="4") + self.expect(val.GetValue(), "Argc evaluated correctly", exe=False, startstr="4") self.DebugSBValue(val) val = frame.EvaluateExpression("*argv[1]") - self.expect(val.GetValue(), "Argv[1] evaluated correctly", exe=False, - startstr="'X'") + self.expect( + val.GetValue(), "Argv[1] evaluated correctly", exe=False, startstr="'X'" + ) self.DebugSBValue(val) val = frame.EvaluateExpression("*argv[2]") - self.expect(val.GetValue(), "Argv[2] evaluated correctly", exe=False, - startstr="'Y'") + self.expect( + val.GetValue(), "Argv[2] evaluated correctly", exe=False, startstr="'Y'" + ) self.DebugSBValue(val) val = frame.EvaluateExpression("*argv[3]") - self.expect(val.GetValue(), "Argv[3] evaluated correctly", exe=False, - startstr="'Z'") + self.expect( + val.GetValue(), "Argv[3] evaluated correctly", exe=False, startstr="'Z'" + ) self.DebugSBValue(val) - callee_break = target.BreakpointCreateByName( - "a_function_to_call", None) + callee_break = target.BreakpointCreateByName("a_function_to_call", None) self.assertTrue(callee_break.GetNumLocations() > 0) # Make sure ignoring breakpoints works from the command line: - self.expect("expression -i true -- a_function_to_call()", - substrs=['(int) $', ' 1']) + self.expect( + "expression -i true -- a_function_to_call()", substrs=["(int) $", " 1"] + ) self.assertEquals(callee_break.GetHitCount(), 1) # Now try ignoring breakpoints using the SB API's: options = lldb.SBExpressionOptions() options.SetIgnoreBreakpoints(True) - value = frame.EvaluateExpression('a_function_to_call()', options) + value = frame.EvaluateExpression("a_function_to_call()", options) self.assertTrue(value.IsValid()) self.assertEquals(value.GetValueAsSigned(0), 2) self.assertEquals(callee_break.GetHitCount(), 2) @@ -176,45 +188,38 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False + ) self.runCmd("run", RUN_SUCCEEDED) # runCmd: expression 'a' # output: (char) $0 = 'a' - self.expect("expression 'a'", - substrs=['(char) $', - "'a'"]) + self.expect("expression 'a'", substrs=["(char) $", "'a'"]) # runCmd: expression (int) printf ("\n\n\tHello there!\n") # output: (int) $1 = 16 - self.expect(r'''expression (int) printf ("\n\n\tHello there!\n")''', - substrs=['(int) $', - '16']) + self.expect( + r"""expression (int) printf ("\n\n\tHello there!\n")""", + substrs=["(int) $", "16"], + ) # runCmd: expression (int) printf("\t\x68\n") # output: (int) $2 = 3 - self.expect(r'''expression (int) printf("\t\x68\n")''', - substrs=['(int) $', - '3']) + self.expect( + r"""expression (int) printf("\t\x68\n")""", substrs=["(int) $", "3"] + ) # runCmd: expression (int) printf("\"\n") # output: (int) $3 = 2 - self.expect(r'''expression (int) printf("\"\n")''', - substrs=['(int) $', - '2']) + self.expect(r"""expression (int) printf("\"\n")""", substrs=["(int) $", "2"]) # runCmd: expression (int) printf("'\n") # output: (int) $4 = 2 - self.expect(r'''expression (int) printf("'\n")''', - substrs=['(int) $', - '2']) + self.expect(r"""expression (int) printf("'\n")""", substrs=["(int) $", "2"]) # runCmd: command alias print_hi expression (int) printf ("\n\tHi!\n") # output: - self.runCmd( - r'''command alias print_hi expression (int) printf ("\n\tHi!\n")''') + self.runCmd(r"""command alias print_hi expression (int) printf ("\n\tHi!\n")""") # This fails currently. - self.expect('print_hi', - substrs=['(int) $', - '6']) + self.expect("print_hi", substrs=["(int) $", "6"]) diff --git a/lldb/test/API/commands/expression/test/TestExprs2.py b/lldb/test/API/commands/expression/test/TestExprs2.py --- a/lldb/test/API/commands/expression/test/TestExprs2.py +++ b/lldb/test/API/commands/expression/test/TestExprs2.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,14 +10,13 @@ class ExprCommands2TestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.c. self.line = line_number( - 'main.cpp', - '// Please test many expressions while stopped at this line:') + "main.cpp", "// Please test many expressions while stopped at this line:" + ) def test_more_expr_commands(self): """Test some more expression commands.""" @@ -27,29 +25,25 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False + ) self.runCmd("run", RUN_SUCCEEDED) # Does static casting work? - self.expect("expression (int*)argv", - startstr="(int *) $0 = 0x") + self.expect("expression (int*)argv", startstr="(int *) $0 = 0x") # (int *) $0 = 0x00007fff5fbff258 # Do return values containing the contents of expression locals work? - self.expect("expression int i = 5; i", - startstr="(int) $1 = 5") + self.expect("expression int i = 5; i", startstr="(int) $1 = 5") # (int) $2 = 5 - self.expect("expression $1 + 1", - startstr="(int) $2 = 6") + self.expect("expression $1 + 1", startstr="(int) $2 = 6") # (int) $3 = 6 # Do return values containing the results of static expressions work? - self.expect("expression 20 + 3", - startstr="(int) $3 = 23") + self.expect("expression 20 + 3", startstr="(int) $3 = 23") # (int) $4 = 5 - self.expect("expression $3 + 1", - startstr="(int) $4 = 24") + self.expect("expression $3 + 1", startstr="(int) $4 = 24") # (int) $5 = 6 @skipIfLinux @@ -61,11 +55,11 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False + ) self.runCmd("run", RUN_SUCCEEDED) # Do anonymous symbols work? - self.expect("expression ((char**)environ)[0]", - startstr="(char *) $0 = 0x") + self.expect("expression ((char**)environ)[0]", startstr="(char *) $0 = 0x") # (char *) $1 = 0x00007fff5fbff298 "Apple_PubSub_Socket_Render=/tmp/launch-7AEsUD/Render" diff --git a/lldb/test/API/commands/expression/timeout/TestCallWithTimeout.py b/lldb/test/API/commands/expression/timeout/TestCallWithTimeout.py --- a/lldb/test/API/commands/expression/timeout/TestCallWithTimeout.py +++ b/lldb/test/API/commands/expression/timeout/TestCallWithTimeout.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class ExprCommandWithTimeoutsTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) @@ -20,16 +18,14 @@ self.main_source_spec = lldb.SBFileSpec(self.main_source) @expectedFlakeyFreeBSD("llvm.org/pr19605") - @expectedFailureAll( - oslist=[ - "windows"], - bugnumber="llvm.org/pr21765") + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") def test(self): """Test calling std::String member function.""" self.build() (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, 'stop here in main.', self.main_source_spec) + self, "stop here in main.", self.main_source_spec + ) # First set the timeout too short, and make sure we fail. options = lldb.SBExpressionOptions() @@ -48,7 +44,8 @@ result = lldb.SBCommandReturnObject() return_value = interp.HandleCommand( - "expr -t 100 -u true -- wait_a_while(1000000)", result) + "expr -t 100 -u true -- wait_a_while(1000000)", result + ) self.assertEquals(return_value, lldb.eReturnStatusFailed) # Okay, now do it again with long enough time outs: @@ -64,7 +61,8 @@ result = lldb.SBCommandReturnObject() return_value = interp.HandleCommand( - "expr -t 1000000 -u true -- wait_a_while(1000)", result) + "expr -t 1000000 -u true -- wait_a_while(1000)", result + ) self.assertEquals(return_value, lldb.eReturnStatusSuccessFinishResult) # Finally set the one thread timeout and make sure that doesn't change diff --git a/lldb/test/API/commands/expression/top-level/TestTopLevelExprs.py b/lldb/test/API/commands/expression/top-level/TestTopLevelExprs.py --- a/lldb/test/API/commands/expression/top-level/TestTopLevelExprs.py +++ b/lldb/test/API/commands/expression/top-level/TestTopLevelExprs.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,20 +10,16 @@ class TopLevelExpressionsTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.c. - self.line = line_number('main.cpp', - '// Set breakpoint here') - self.dummy_line = line_number('dummy.cpp', - '// Set breakpoint here') + self.line = line_number("main.cpp", "// Set breakpoint here") + self.dummy_line = line_number("dummy.cpp", "// Set breakpoint here") # Disable confirmation prompt to avoid infinite wait self.runCmd("settings set auto-confirm true") - self.addTearDownHook( - lambda: self.runCmd("settings clear auto-confirm")) + self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) def build_and_run(self): """Test top-level expressions.""" @@ -33,36 +28,39 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False + ) self.runCmd("run", RUN_SUCCEEDED) def run_dummy(self): - self.runCmd("file " + self.getBuildArtifact("dummy"), - CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("dummy"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( self, "dummy.cpp", self.dummy_line, num_expected_locations=1, - loc_exact=False) + loc_exact=False, + ) self.runCmd("run", RUN_SUCCEEDED) - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) @skipIf(debug_info="gmodules") # not relevant @skipIf(oslist=["windows"]) # Error in record layout on Windows def test_top_level_expressions(self): self.build_and_run() - resultFromCode = self.frame().EvaluateExpression("doTest()").GetValueAsUnsigned() + resultFromCode = ( + self.frame().EvaluateExpression("doTest()").GetValueAsUnsigned() + ) self.runCmd("kill") self.run_dummy() - codeFile = open('test.cpp', 'r') + codeFile = open("test.cpp", "r") expressions = [] current_expression = "" @@ -84,23 +82,32 @@ resultFromTopLevel = self.frame().EvaluateExpression("doTest()") self.assertTrue(resultFromTopLevel.IsValid()) - self.assertEqual( - resultFromCode, - resultFromTopLevel.GetValueAsUnsigned()) + self.assertEqual(resultFromCode, resultFromTopLevel.GetValueAsUnsigned()) # Make sure the command line version works as well: self.runCmd("expr --top-level -- int TopLevelFunction() { return 101; }") resultFromTopLevel = self.frame().EvaluateExpression("TopLevelFunction()") self.assertTrue(resultFromTopLevel.IsValid()) - self.assertEqual(101, resultFromTopLevel.GetValueAsUnsigned(), "Command line version works.") + self.assertEqual( + 101, resultFromTopLevel.GetValueAsUnsigned(), "Command line version works." + ) def test_top_level_expression_without_target(self): - self.expect("expr --top-level -- void func() {}", error=True, - substrs=["Top-level code needs to be inserted into a runnable target"]) + self.expect( + "expr --top-level -- void func() {}", + error=True, + substrs=["Top-level code needs to be inserted into a runnable target"], + ) # FIXME: This doesn't actually generate any code, so LLDB should probably # allow these expressions. - self.expect("expr --top-level -- template struct StructT { T m; };", error=True, - substrs=["Top-level code needs to be inserted into a runnable target"]) - self.expect("expr --top-level -- struct Struct { int i; };", error=True, - substrs=["Top-level code needs to be inserted into a runnable target"]) + self.expect( + "expr --top-level -- template struct StructT { T m; };", + error=True, + substrs=["Top-level code needs to be inserted into a runnable target"], + ) + self.expect( + "expr --top-level -- struct Struct { int i; };", + error=True, + substrs=["Top-level code needs to be inserted into a runnable target"], + ) diff --git a/lldb/test/API/commands/expression/two-files/TestObjCTypeQueryFromOtherCompileUnit.py b/lldb/test/API/commands/expression/two-files/TestObjCTypeQueryFromOtherCompileUnit.py --- a/lldb/test/API/commands/expression/two-files/TestObjCTypeQueryFromOtherCompileUnit.py +++ b/lldb/test/API/commands/expression/two-files/TestObjCTypeQueryFromOtherCompileUnit.py @@ -5,7 +5,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -13,13 +12,13 @@ class ObjCTypeQueryTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.m. self.line = line_number( - 'main.m', "// Set breakpoint here, then do 'expr (NSArray*)array_token'.") + "main.m", "// Set breakpoint here, then do 'expr (NSArray*)array_token'." + ) @add_test_categories(["objc"]) def test(self): @@ -28,13 +27,13 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + self, "main.m", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) self.runCmd("settings set target.prefer-dynamic-value no-dynamic-values") # Now do a NSArry type query from the 'main.m' compile uint. - self.expect("expression (NSArray*)array_token", - substrs=['(NSArray *) $0 = 0x']) + self.expect("expression (NSArray*)array_token", substrs=["(NSArray *) $0 = 0x"]) # (NSArray *) $0 = 0x00007fff70118398 diff --git a/lldb/test/API/commands/expression/unwind_expression/TestUnwindExpression.py b/lldb/test/API/commands/expression/unwind_expression/TestUnwindExpression.py --- a/lldb/test/API/commands/expression/unwind_expression/TestUnwindExpression.py +++ b/lldb/test/API/commands/expression/unwind_expression/TestUnwindExpression.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -16,16 +15,17 @@ def build_and_run_to_bkpt(self): self.build() - (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - "// Set a breakpoint here to get started", self.main_spec) + (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// Set a breakpoint here to get started", self.main_spec + ) # Next set a breakpoint in this function, set up Expression options to stop on # breakpoint hits, and call the function. self.fun_bkpt = self.target().BreakpointCreateBySourceRegex( - "// Stop inside the function here.", self.main_spec) + "// Stop inside the function here.", self.main_spec + ) self.assertTrue(self.fun_bkpt, VALID_BREAKPOINT) - @no_debug_info_test @expectedFailureAll(bugnumber="llvm.org/pr33164") def test_conditional_bktp(self): @@ -34,7 +34,7 @@ """ self.build_and_run_to_bkpt() - self.fun_bkpt.SetCondition("0") # Should not get hit + self.fun_bkpt.SetCondition("0") # Should not get hit options = lldb.SBExpressionOptions() options.SetIgnoreBreakpoints(False) options.SetUnwindOnError(False) @@ -44,8 +44,7 @@ self.assertSuccess(val.GetError(), "We did complete the execution.") self.assertEquals(47, val.GetValueAsSigned()) - - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) @expectedFlakeyNetBSD def test_unwind_expression(self): """Test unwinding from an expression.""" @@ -69,26 +68,21 @@ val = main_frame.EvaluateExpression("a_function_to_call()", options) - self.assertTrue( - val.GetError().Fail(), - "We did not complete the execution.") + self.assertTrue(val.GetError().Fail(), "We did not complete the execution.") error_str = val.GetError().GetCString() self.assertTrue( "Execution was interrupted, reason: breakpoint" in error_str, - "And the reason was right.") + "And the reason was right.", + ) - thread = lldbutil.get_one_thread_stopped_at_breakpoint( - self.process(), bkpt) - self.assertTrue( - thread.IsValid(), - "We are indeed stopped at our breakpoint") + thread = lldbutil.get_one_thread_stopped_at_breakpoint(self.process(), bkpt) + self.assertTrue(thread.IsValid(), "We are indeed stopped at our breakpoint") # Now unwind the expression, and make sure we got back to where we # started. - self.assertSuccess(thread.UnwindInnermostExpression(), - "We succeeded in unwinding") + self.assertSuccess( + thread.UnwindInnermostExpression(), "We succeeded in unwinding" + ) cur_frame = thread.GetFrameAtIndex(0) - self.assertTrue( - cur_frame.IsEqual(main_frame), - "We got back to the main frame.") + self.assertTrue(cur_frame.IsEqual(main_frame), "We got back to the main frame.") diff --git a/lldb/test/API/commands/expression/vector_of_enums/TestVectorOfEnums.py b/lldb/test/API/commands/expression/vector_of_enums/TestVectorOfEnums.py --- a/lldb/test/API/commands/expression/vector_of_enums/TestVectorOfEnums.py +++ b/lldb/test/API/commands/expression/vector_of_enums/TestVectorOfEnums.py @@ -9,19 +9,14 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestVectorOfEnums(TestBase): - @add_test_categories(["libc++"]) - def test_vector_of_enums(self): - self.build() +class TestVectorOfEnums(TestBase): + @add_test_categories(["libc++"]) + def test_vector_of_enums(self): + self.build() - lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp", False)) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) - self.expect("expr v", substrs=[ - 'size=3', - '[0] = a', - '[1] = b', - '[2] = c', - '}' - ]) + self.expect("expr v", substrs=["size=3", "[0] = a", "[1] = b", "[2] = c", "}"]) diff --git a/lldb/test/API/commands/expression/weak_symbols/TestWeakSymbols.py b/lldb/test/API/commands/expression/weak_symbols/TestWeakSymbols.py --- a/lldb/test/API/commands/expression/weak_symbols/TestWeakSymbols.py +++ b/lldb/test/API/commands/expression/weak_symbols/TestWeakSymbols.py @@ -4,7 +4,6 @@ """ - import os import lldb from lldbsuite.test.decorators import * @@ -13,18 +12,17 @@ class TestWeakSymbolsInExpressions(TestBase): - NO_DEBUG_INFO_TESTCASE = True @skipUnlessDarwin - @skipIf(compiler="clang", compiler_version=['<', '7.0']) + @skipIf(compiler="clang", compiler_version=["<", "7.0"]) def test_weak_symbol_in_expr(self): """Tests that we can refer to weak symbols in expressions.""" self.build() self.main_source_file = lldb.SBFileSpec("main.c") self.do_test() - def run_weak_var_check (self, weak_varname, present): + def run_weak_var_check(self, weak_varname, present): # The expression will modify present_weak_int to signify which branch # was taken. Set it to so we don't get confused by a previous run. value = self.target.FindFirstGlobalVariable("present_weak_int") @@ -36,10 +34,18 @@ # Note, I'm adding the "; 10" at the end of the expression to work around # the bug that expressions with no result currently return False for Success()... - expr = "if (&" + weak_varname + " != NULL) { present_weak_int = 10; } else { present_weak_int = 20;}; 10" + expr = ( + "if (&" + + weak_varname + + " != NULL) { present_weak_int = 10; } else { present_weak_int = 20;}; 10" + ) result = self.frame.EvaluateExpression(expr) self.assertSuccess(result.GetError(), "absent_weak_int expr failed") - self.assertEqual(value.GetValueAsSigned(), correct_value, "Didn't change present_weak_int correctly.") + self.assertEqual( + value.GetValueAsSigned(), + correct_value, + "Didn't change present_weak_int correctly.", + ) def do_test(self): hidden_dir = os.path.join(self.getBuildDir(), "hidden") @@ -50,15 +56,19 @@ launch_info.SetLaunchFlags(lldb.eLaunchFlagInheritTCCFromParent) (self.target, _, thread, _) = lldbutil.run_to_source_breakpoint( - self, "Set a breakpoint here", - self.main_source_file, - launch_info = launch_info, - extra_images = [hidden_dylib]) + self, + "Set a breakpoint here", + self.main_source_file, + launch_info=launch_info, + extra_images=[hidden_dylib], + ) # First we have to import the Dylib module so we get the type info # for the weak symbol. We need to add the source dir to the module # search paths, and then run @import to introduce it into the expression # context: - self.dbg.HandleCommand("settings set target.clang-module-search-paths " + self.getSourceDir()) + self.dbg.HandleCommand( + "settings set target.clang-module-search-paths " + self.getSourceDir() + ) self.frame = thread.frames[0] self.assertTrue(self.frame.IsValid(), "Got a good frame") diff --git a/lldb/test/API/commands/expression/xvalue/TestXValuePrinting.py b/lldb/test/API/commands/expression/xvalue/TestXValuePrinting.py --- a/lldb/test/API/commands/expression/xvalue/TestXValuePrinting.py +++ b/lldb/test/API/commands/expression/xvalue/TestXValuePrinting.py @@ -3,10 +3,12 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class ExprXValuePrintingTestCase(TestBase): +class ExprXValuePrintingTestCase(TestBase): def test(self): """Printing an xvalue should work.""" self.build() - lldbutil.run_to_source_breakpoint(self, '// Break here', lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Break here", lldb.SBFileSpec("main.cpp") + ) self.expect_expr("foo().data", result_value="1234") diff --git a/lldb/test/API/commands/frame/diagnose/array/TestArray.py b/lldb/test/API/commands/frame/diagnose/array/TestArray.py --- a/lldb/test/API/commands/frame/diagnose/array/TestArray.py +++ b/lldb/test/API/commands/frame/diagnose/array/TestArray.py @@ -10,17 +10,14 @@ class TestArray(TestBase): - @skipUnlessDarwin - @skipIf(archs=no_match(['x86_64'])) # frame diagnose doesn't work for armv7 or arm64 + @skipIf( + archs=no_match(["x86_64"]) + ) # frame diagnose doesn't work for armv7 or arm64 def test_array(self): self.build() exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread list", "Thread should be stopped", - substrs=['stopped']) - self.expect( - "frame diagnose", - "Crash diagnosis was accurate", - substrs=["a[10]"]) + self.expect("thread list", "Thread should be stopped", substrs=["stopped"]) + self.expect("frame diagnose", "Crash diagnosis was accurate", substrs=["a[10]"]) diff --git a/lldb/test/API/commands/frame/diagnose/bad-reference/TestBadReference.py b/lldb/test/API/commands/frame/diagnose/bad-reference/TestBadReference.py --- a/lldb/test/API/commands/frame/diagnose/bad-reference/TestBadReference.py +++ b/lldb/test/API/commands/frame/diagnose/bad-reference/TestBadReference.py @@ -10,16 +10,15 @@ class TestBadReference(TestBase): - @skipUnlessDarwin - @skipIf(archs=no_match(['x86_64'])) # frame diagnose doesn't work for armv7 or arm64 + @skipIf( + archs=no_match(["x86_64"]) + ) # frame diagnose doesn't work for armv7 or arm64 def test_bad_reference(self): TestBase.setUp(self) self.build() exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread list", "Thread should be stopped", - substrs=['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", - substrs=["f->b"]) + self.expect("thread list", "Thread should be stopped", substrs=["stopped"]) + self.expect("frame diagnose", "Crash diagnosis was accurate", substrs=["f->b"]) diff --git a/lldb/test/API/commands/frame/diagnose/complicated-expression/TestComplicatedExpression.py b/lldb/test/API/commands/frame/diagnose/complicated-expression/TestComplicatedExpression.py --- a/lldb/test/API/commands/frame/diagnose/complicated-expression/TestComplicatedExpression.py +++ b/lldb/test/API/commands/frame/diagnose/complicated-expression/TestComplicatedExpression.py @@ -10,18 +10,17 @@ class TestDiagnoseDereferenceArgument(TestBase): - @skipUnlessDarwin - @skipIf(archs=no_match(['x86_64'])) # frame diagnose doesn't work for armv7 or arm64 + @skipIf( + archs=no_match(["x86_64"]) + ) # frame diagnose doesn't work for armv7 or arm64 def test_diagnose_dereference_argument(self): TestBase.setUp(self) self.build() exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread list", "Thread should be stopped", - substrs=['stopped']) + self.expect("thread list", "Thread should be stopped", substrs=["stopped"]) self.expect( - "frame diagnose", - "Crash diagnosis was accurate", - substrs=["f->b->d"]) + "frame diagnose", "Crash diagnosis was accurate", substrs=["f->b->d"] + ) diff --git a/lldb/test/API/commands/frame/diagnose/dereference-argument/TestDiagnoseDereferenceArgument.py b/lldb/test/API/commands/frame/diagnose/dereference-argument/TestDiagnoseDereferenceArgument.py --- a/lldb/test/API/commands/frame/diagnose/dereference-argument/TestDiagnoseDereferenceArgument.py +++ b/lldb/test/API/commands/frame/diagnose/dereference-argument/TestDiagnoseDereferenceArgument.py @@ -10,18 +10,17 @@ class TestDiagnoseDereferenceArgument(TestBase): - @skipUnlessDarwin - @skipIf(archs=no_match(['x86_64'])) # frame diagnose doesn't work for armv7 or arm64 + @skipIf( + archs=no_match(["x86_64"]) + ) # frame diagnose doesn't work for armv7 or arm64 def test_diagnose_dereference_argument(self): TestBase.setUp(self) self.build() exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread list", "Thread should be stopped", - substrs=['stopped']) + self.expect("thread list", "Thread should be stopped", substrs=["stopped"]) self.expect( - "frame diagnose", - "Crash diagnosis was accurate", - substrs=["f->b->d"]) + "frame diagnose", "Crash diagnosis was accurate", substrs=["f->b->d"] + ) diff --git a/lldb/test/API/commands/frame/diagnose/dereference-function-return/TestDiagnoseDereferenceFunctionReturn.py b/lldb/test/API/commands/frame/diagnose/dereference-function-return/TestDiagnoseDereferenceFunctionReturn.py --- a/lldb/test/API/commands/frame/diagnose/dereference-function-return/TestDiagnoseDereferenceFunctionReturn.py +++ b/lldb/test/API/commands/frame/diagnose/dereference-function-return/TestDiagnoseDereferenceFunctionReturn.py @@ -10,21 +10,18 @@ class TestDiagnoseDereferenceFunctionReturn(TestBase): - @skipUnlessDarwin - @skipIf(archs=no_match(['x86_64'])) # frame diagnose doesn't work for armv7 or arm64 - @expectedFailureAll(oslist=['macosx'], archs=['i386'], bugnumber="rdar://28656408") + @skipIf( + archs=no_match(["x86_64"]) + ) # frame diagnose doesn't work for armv7 or arm64 + @expectedFailureAll(oslist=["macosx"], archs=["i386"], bugnumber="rdar://28656408") def test_diagnose_dereference_function_return(self): TestBase.setUp(self) self.build() exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread list", "Thread should be stopped", - substrs=['stopped']) + self.expect("thread list", "Thread should be stopped", substrs=["stopped"]) self.expect( - "frame diagnose", - "Crash diagnosis was accurate", - substrs=[ - "GetAFoo", - "->b"]) + "frame diagnose", "Crash diagnosis was accurate", substrs=["GetAFoo", "->b"] + ) diff --git a/lldb/test/API/commands/frame/diagnose/dereference-this/TestDiagnoseDereferenceThis.py b/lldb/test/API/commands/frame/diagnose/dereference-this/TestDiagnoseDereferenceThis.py --- a/lldb/test/API/commands/frame/diagnose/dereference-this/TestDiagnoseDereferenceThis.py +++ b/lldb/test/API/commands/frame/diagnose/dereference-this/TestDiagnoseDereferenceThis.py @@ -10,18 +10,17 @@ class TestDiagnoseDereferenceThis(TestBase): - @skipUnlessDarwin - @skipIf(archs=no_match(['x86_64'])) # frame diagnose doesn't work for armv7 or arm64 + @skipIf( + archs=no_match(["x86_64"]) + ) # frame diagnose doesn't work for armv7 or arm64 def test_diagnose_dereference_this(self): TestBase.setUp(self) self.build() exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread list", "Thread should be stopped", - substrs=['stopped']) + self.expect("thread list", "Thread should be stopped", substrs=["stopped"]) self.expect( - "frame diagnose", - "Crash diagnosis was accurate", - substrs=["this->a"]) + "frame diagnose", "Crash diagnosis was accurate", substrs=["this->a"] + ) diff --git a/lldb/test/API/commands/frame/diagnose/inheritance/TestDiagnoseInheritance.py b/lldb/test/API/commands/frame/diagnose/inheritance/TestDiagnoseInheritance.py --- a/lldb/test/API/commands/frame/diagnose/inheritance/TestDiagnoseInheritance.py +++ b/lldb/test/API/commands/frame/diagnose/inheritance/TestDiagnoseInheritance.py @@ -10,16 +10,15 @@ class TestDiagnoseInheritance(TestBase): - @skipUnlessDarwin - @skipIf(archs=no_match(['x86_64'])) # frame diagnose doesn't work for armv7 or arm64 + @skipIf( + archs=no_match(["x86_64"]) + ) # frame diagnose doesn't work for armv7 or arm64 def test_diagnose_inheritance(self): TestBase.setUp(self) self.build() exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread list", "Thread should be stopped", - substrs=['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", - substrs=["d"]) + self.expect("thread list", "Thread should be stopped", substrs=["stopped"]) + self.expect("frame diagnose", "Crash diagnosis was accurate", substrs=["d"]) diff --git a/lldb/test/API/commands/frame/diagnose/local-variable/TestLocalVariable.py b/lldb/test/API/commands/frame/diagnose/local-variable/TestLocalVariable.py --- a/lldb/test/API/commands/frame/diagnose/local-variable/TestLocalVariable.py +++ b/lldb/test/API/commands/frame/diagnose/local-variable/TestLocalVariable.py @@ -10,16 +10,15 @@ class TestLocalVariable(TestBase): - @skipUnlessDarwin - @skipIf(archs=no_match(['x86_64'])) # frame diagnose doesn't work for armv7 or arm64 + @skipIf( + archs=no_match(["x86_64"]) + ) # frame diagnose doesn't work for armv7 or arm64 def test_local_variable(self): TestBase.setUp(self) self.build() exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread list", "Thread should be stopped", - substrs=['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", - substrs=["myInt"]) + self.expect("thread list", "Thread should be stopped", substrs=["stopped"]) + self.expect("frame diagnose", "Crash diagnosis was accurate", substrs=["myInt"]) diff --git a/lldb/test/API/commands/frame/diagnose/virtual-method-call/TestDiagnoseDereferenceVirtualMethodCall.py b/lldb/test/API/commands/frame/diagnose/virtual-method-call/TestDiagnoseDereferenceVirtualMethodCall.py --- a/lldb/test/API/commands/frame/diagnose/virtual-method-call/TestDiagnoseDereferenceVirtualMethodCall.py +++ b/lldb/test/API/commands/frame/diagnose/virtual-method-call/TestDiagnoseDereferenceVirtualMethodCall.py @@ -10,16 +10,15 @@ class TestDiagnoseVirtualMethodCall(TestBase): - @skipUnlessDarwin - @skipIf(archs=no_match(['x86_64'])) # frame diagnose doesn't work for armv7 or arm64 + @skipIf( + archs=no_match(["x86_64"]) + ) # frame diagnose doesn't work for armv7 or arm64 def test_diagnose_virtual_method_call(self): TestBase.setUp(self) self.build() exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread list", "Thread should be stopped", - substrs=['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", - substrs=["foo"]) + self.expect("thread list", "Thread should be stopped", substrs=["stopped"]) + self.expect("frame diagnose", "Crash diagnosis was accurate", substrs=["foo"]) diff --git a/lldb/test/API/commands/frame/language/TestGuessLanguage.py b/lldb/test/API/commands/frame/language/TestGuessLanguage.py --- a/lldb/test/API/commands/frame/language/TestGuessLanguage.py +++ b/lldb/test/API/commands/frame/language/TestGuessLanguage.py @@ -3,7 +3,6 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.decorators import * @@ -11,13 +10,12 @@ class TestFrameGuessLanguage(TestBase): - # If your test case doesn't stress debug info, then # set this to true. That way it won't be run once for # each debug info format. NO_DEBUG_INFO_TESTCASE = True - @skipIf(compiler="clang", compiler_version=['<', '10.0']) + @skipIf(compiler="clang", compiler_version=["<", "10.0"]) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37658") def test_guess_language(self): """Test GuessLanguage for C and C++.""" @@ -26,7 +24,7 @@ def check_language(self, thread, frame_no, test_lang): frame = thread.frames[frame_no] - self.assertTrue(frame.IsValid(), "Frame %d was not valid."%(frame_no)) + self.assertTrue(frame.IsValid(), "Frame %d was not valid." % (frame_no)) lang = frame.GuessLanguage() self.assertEqual(lang, test_lang) @@ -37,10 +35,11 @@ # Now create a breakpoint in main.c at the source matching # "Set a breakpoint here" breakpoint = target.BreakpointCreateBySourceRegex( - "Set breakpoint here", lldb.SBFileSpec("somefunc.c")) - self.assertTrue(breakpoint and - breakpoint.GetNumLocations() >= 1, - VALID_BREAKPOINT) + "Set breakpoint here", lldb.SBFileSpec("somefunc.c") + ) + self.assertTrue( + breakpoint and breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT + ) error = lldb.SBError() # This is the launch info. If you want to launch with arguments or @@ -53,10 +52,11 @@ # Did we hit our breakpoint? from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint + threads = get_threads_stopped_at_breakpoint(process, breakpoint) self.assertEqual( - len(threads), 1, - "There should be a thread stopped at our breakpoint") + len(threads), 1, "There should be a thread stopped at our breakpoint" + ) # The hit count for the breakpoint should be 1. self.assertEquals(breakpoint.GetHitCount(), 1) @@ -73,6 +73,3 @@ self.check_language(thread, 0, c_frame_language) self.check_language(thread, 1, cxx_frame_language) self.check_language(thread, 2, lldb.eLanguageTypeC_plus_plus) - - - diff --git a/lldb/test/API/commands/frame/recognizer/TestFrameRecognizer.py b/lldb/test/API/commands/frame/recognizer/TestFrameRecognizer.py --- a/lldb/test/API/commands/frame/recognizer/TestFrameRecognizer.py +++ b/lldb/test/API/commands/frame/recognizer/TestFrameRecognizer.py @@ -10,6 +10,7 @@ import recognizer + class FrameRecognizerTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True @@ -21,59 +22,84 @@ # Clear internal & plugins recognizers that get initialized at launch self.runCmd("frame recognizer clear") - self.runCmd("command script import " + os.path.join(self.getSourceDir(), "recognizer.py")) + self.runCmd( + "command script import " + + os.path.join(self.getSourceDir(), "recognizer.py") + ) - self.expect("frame recognizer list", - substrs=['no matching results found.']) + self.expect("frame recognizer list", substrs=["no matching results found."]) - self.runCmd("frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo") + self.runCmd( + "frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo" + ) - self.expect("frame recognizer list", - substrs=['0: recognizer.MyFrameRecognizer, module a.out, symbol foo']) + self.expect( + "frame recognizer list", + substrs=["0: recognizer.MyFrameRecognizer, module a.out, symbol foo"], + ) - self.runCmd("frame recognizer add -l recognizer.MyOtherFrameRecognizer -s a.out -n bar -x") + self.runCmd( + "frame recognizer add -l recognizer.MyOtherFrameRecognizer -s a.out -n bar -x" + ) self.expect( "frame recognizer list", substrs=[ - '1: recognizer.MyOtherFrameRecognizer, module a.out, symbol bar (regexp)', - '0: recognizer.MyFrameRecognizer, module a.out, symbol foo' - ]) + "1: recognizer.MyOtherFrameRecognizer, module a.out, symbol bar (regexp)", + "0: recognizer.MyFrameRecognizer, module a.out, symbol foo", + ], + ) self.runCmd("frame recognizer delete 0") # Test that it deleted the recognizer with id 0. - self.expect("frame recognizer list", - substrs=['1: recognizer.MyOtherFrameRecognizer, module a.out, symbol bar (regexp)']) - self.expect("frame recognizer list", matching=False, - substrs=['MyFrameRecognizer']) + self.expect( + "frame recognizer list", + substrs=[ + "1: recognizer.MyOtherFrameRecognizer, module a.out, symbol bar (regexp)" + ], + ) + self.expect( + "frame recognizer list", matching=False, substrs=["MyFrameRecognizer"] + ) # Test that an invalid index and deleting the same index again # is an error and doesn't do any changes. - self.expect("frame recognizer delete 2", error=True, - substrs=["error: '2' is not a valid recognizer id."]) - self.expect("frame recognizer delete 0", error=True, - substrs=["error: '0' is not a valid recognizer id."]) + self.expect( + "frame recognizer delete 2", + error=True, + substrs=["error: '2' is not a valid recognizer id."], + ) + self.expect( + "frame recognizer delete 0", + error=True, + substrs=["error: '0' is not a valid recognizer id."], + ) # Recognizers should have the same state as above. - self.expect("frame recognizer list", - substrs=['1: recognizer.MyOtherFrameRecognizer, module a.out, symbol bar (regexp)']) - self.expect("frame recognizer list", matching=False, - substrs=['MyFrameRecognizer']) - + self.expect( + "frame recognizer list", + substrs=[ + "1: recognizer.MyOtherFrameRecognizer, module a.out, symbol bar (regexp)" + ], + ) + self.expect( + "frame recognizer list", matching=False, substrs=["MyFrameRecognizer"] + ) self.runCmd("frame recognizer clear") - self.expect("frame recognizer list", - substrs=['no matching results found.']) + self.expect("frame recognizer list", substrs=["no matching results found."]) - self.runCmd("frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo") + self.runCmd( + "frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo" + ) - target, process, thread, _ = lldbutil.run_to_name_breakpoint(self, "foo", - exe_name = exe) + target, process, thread, _ = lldbutil.run_to_name_breakpoint( + self, "foo", exe_name=exe + ) frame = thread.GetSelectedFrame() - self.expect("frame variable", - substrs=['(int) a = 42', '(int) b = 56']) + self.expect("frame variable", substrs=["(int) a = 42", "(int) b = 56"]) # Recognized arguments don't show up by default... variables = frame.GetVariables(lldb.SBVariablesOptions()) @@ -97,19 +123,28 @@ self.assertEqual(variables.GetSize(), 2) self.assertEqual(variables.GetValueAtIndex(0).name, "a") self.assertEqual(variables.GetValueAtIndex(0).signed, 42) - self.assertEqual(variables.GetValueAtIndex(0).GetValueType(), lldb.eValueTypeVariableArgument) + self.assertEqual( + variables.GetValueAtIndex(0).GetValueType(), lldb.eValueTypeVariableArgument + ) self.assertEqual(variables.GetValueAtIndex(1).name, "b") self.assertEqual(variables.GetValueAtIndex(1).signed, 56) - self.assertEqual(variables.GetValueAtIndex(1).GetValueType(), lldb.eValueTypeVariableArgument) + self.assertEqual( + variables.GetValueAtIndex(1).GetValueType(), lldb.eValueTypeVariableArgument + ) - self.expect("frame recognizer info 0", - substrs=['frame 0 is recognized by recognizer.MyFrameRecognizer']) + self.expect( + "frame recognizer info 0", + substrs=["frame 0 is recognized by recognizer.MyFrameRecognizer"], + ) - self.expect("frame recognizer info 999", error=True, - substrs=['no frame with index 999']) + self.expect( + "frame recognizer info 999", error=True, substrs=["no frame with index 999"] + ) - self.expect("frame recognizer info 1", - substrs=['frame 1 not recognized by any recognizer']) + self.expect( + "frame recognizer info 1", + substrs=["frame 1 not recognized by any recognizer"], + ) # FIXME: The following doesn't work yet, but should be fixed. """ @@ -135,29 +170,43 @@ # Clear internal & plugins recognizers that get initialized at launch self.runCmd("frame recognizer clear") - self.runCmd("command script import " + os.path.join(self.getSourceDir(), "recognizer.py")) + self.runCmd( + "command script import " + + os.path.join(self.getSourceDir(), "recognizer.py") + ) - self.expect("frame recognizer list", - substrs=['no matching results found.']) + self.expect("frame recognizer list", substrs=["no matching results found."]) - self.runCmd("frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo -n bar") + self.runCmd( + "frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo -n bar" + ) - self.expect("frame recognizer list", - substrs=['recognizer.MyFrameRecognizer, module a.out, symbol foo, symbol bar']) + self.expect( + "frame recognizer list", + substrs=[ + "recognizer.MyFrameRecognizer, module a.out, symbol foo, symbol bar" + ], + ) - target, process, thread, _ = lldbutil.run_to_name_breakpoint(self, "foo", - exe_name = exe) + target, process, thread, _ = lldbutil.run_to_name_breakpoint( + self, "foo", exe_name=exe + ) frame = thread.GetSelectedFrame() - self.expect("frame recognizer info 0", - substrs=['frame 0 is recognized by recognizer.MyFrameRecognizer']) + self.expect( + "frame recognizer info 0", + substrs=["frame 0 is recognized by recognizer.MyFrameRecognizer"], + ) - target, process, thread, _ = lldbutil.run_to_name_breakpoint(self, "bar", - exe_name = exe) + target, process, thread, _ = lldbutil.run_to_name_breakpoint( + self, "bar", exe_name=exe + ) frame = thread.GetSelectedFrame() - self.expect("frame recognizer info 0", - substrs=['frame 0 is recognized by recognizer.MyFrameRecognizer']) + self.expect( + "frame recognizer info 0", + substrs=["frame 0 is recognized by recognizer.MyFrameRecognizer"], + ) @skipUnlessDarwin def test_frame_recognizer_target_specific(self): @@ -168,40 +217,62 @@ self.runCmd("frame recognizer clear") # Create a target. - target, process, thread, _ = lldbutil.run_to_name_breakpoint(self, "foo", - exe_name = exe) + target, process, thread, _ = lldbutil.run_to_name_breakpoint( + self, "foo", exe_name=exe + ) - self.runCmd("command script import " + os.path.join(self.getSourceDir(), "recognizer.py")) + self.runCmd( + "command script import " + + os.path.join(self.getSourceDir(), "recognizer.py") + ) # Check that this doesn't contain our own FrameRecognizer somehow. - self.expect("frame recognizer list", - matching=False, substrs=['MyFrameRecognizer']) + self.expect( + "frame recognizer list", matching=False, substrs=["MyFrameRecognizer"] + ) # Add a frame recognizer in that target. - self.runCmd("frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo -n bar") + self.runCmd( + "frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo -n bar" + ) - self.expect("frame recognizer list", - substrs=['recognizer.MyFrameRecognizer, module a.out, symbol foo, symbol bar']) + self.expect( + "frame recognizer list", + substrs=[ + "recognizer.MyFrameRecognizer, module a.out, symbol foo, symbol bar" + ], + ) - self.expect("frame recognizer info 0", - substrs=['frame 0 is recognized by recognizer.MyFrameRecognizer']) + self.expect( + "frame recognizer info 0", + substrs=["frame 0 is recognized by recognizer.MyFrameRecognizer"], + ) # Create a second target. That one shouldn't have the frame recognizer. - target, process, thread, _ = lldbutil.run_to_name_breakpoint(self, "bar", - exe_name = exe) + target, process, thread, _ = lldbutil.run_to_name_breakpoint( + self, "bar", exe_name=exe + ) - self.expect("frame recognizer info 0", - substrs=['frame 0 not recognized by any recognizer']) + self.expect( + "frame recognizer info 0", + substrs=["frame 0 not recognized by any recognizer"], + ) # Add a frame recognizer to the new target. - self.runCmd("frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n bar") + self.runCmd( + "frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n bar" + ) - self.expect("frame recognizer list", - substrs=['recognizer.MyFrameRecognizer, module a.out, symbol bar']) + self.expect( + "frame recognizer list", + substrs=["recognizer.MyFrameRecognizer, module a.out, symbol bar"], + ) # Now the new target should also recognize the frame. - self.expect("frame recognizer info 0", - substrs=['frame 0 is recognized by recognizer.MyFrameRecognizer']) + self.expect( + "frame recognizer info 0", + substrs=["frame 0 is recognized by recognizer.MyFrameRecognizer"], + ) @skipUnlessDarwin def test_frame_recognizer_not_only_first_instruction(self): @@ -211,42 +282,57 @@ # Clear internal & plugins recognizers that get initialized at launch. self.runCmd("frame recognizer clear") - self.runCmd("command script import " + os.path.join(self.getSourceDir(), "recognizer.py")) + self.runCmd( + "command script import " + + os.path.join(self.getSourceDir(), "recognizer.py") + ) - self.expect("frame recognizer list", - substrs=['no matching results found.']) + self.expect("frame recognizer list", substrs=["no matching results found."]) # Create a target. - target, process, thread, _ = lldbutil.run_to_name_breakpoint(self, "foo", - exe_name = exe) + target, process, thread, _ = lldbutil.run_to_name_breakpoint( + self, "foo", exe_name=exe + ) # Move the PC one instruction further. self.runCmd("next") # Add a frame recognizer in that target. - self.runCmd("frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo -n bar") + self.runCmd( + "frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo -n bar" + ) # It's not applied to foo(), because frame's PC is not at the first instruction of the function. - self.expect("frame recognizer info 0", - substrs=['frame 0 not recognized by any recognizer']) + self.expect( + "frame recognizer info 0", + substrs=["frame 0 not recognized by any recognizer"], + ) # Add a frame recognizer with --first-instruction-only=true. self.runCmd("frame recognizer clear") - self.runCmd("frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo -n bar --first-instruction-only=true") + self.runCmd( + "frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo -n bar --first-instruction-only=true" + ) # It's not applied to foo(), because frame's PC is not at the first instruction of the function. - self.expect("frame recognizer info 0", - substrs=['frame 0 not recognized by any recognizer']) + self.expect( + "frame recognizer info 0", + substrs=["frame 0 not recognized by any recognizer"], + ) # Now add a frame recognizer with --first-instruction-only=false. self.runCmd("frame recognizer clear") - self.runCmd("frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo -n bar --first-instruction-only=false") + self.runCmd( + "frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo -n bar --first-instruction-only=false" + ) # This time it should recognize the frame. - self.expect("frame recognizer info 0", - substrs=['frame 0 is recognized by recognizer.MyFrameRecognizer']) + self.expect( + "frame recognizer info 0", + substrs=["frame 0 is recognized by recognizer.MyFrameRecognizer"], + ) opts = lldb.SBVariablesOptions() opts.SetIncludeRecognizedArguments(True) @@ -256,38 +342,75 @@ self.assertEqual(variables.GetSize(), 2) self.assertEqual(variables.GetValueAtIndex(0).name, "a") self.assertEqual(variables.GetValueAtIndex(0).signed, 42) - self.assertEqual(variables.GetValueAtIndex(0).GetValueType(), lldb.eValueTypeVariableArgument) + self.assertEqual( + variables.GetValueAtIndex(0).GetValueType(), lldb.eValueTypeVariableArgument + ) self.assertEqual(variables.GetValueAtIndex(1).name, "b") self.assertEqual(variables.GetValueAtIndex(1).signed, 56) - self.assertEqual(variables.GetValueAtIndex(1).GetValueType(), lldb.eValueTypeVariableArgument) + self.assertEqual( + variables.GetValueAtIndex(1).GetValueType(), lldb.eValueTypeVariableArgument + ) @no_debug_info_test def test_frame_recognizer_delete_invalid_arg(self): - self.expect("frame recognizer delete a", error=True, - substrs=["error: 'a' is not a valid recognizer id."]) - self.expect("frame recognizer delete \"\"", error=True, - substrs=["error: '' is not a valid recognizer id."]) - self.expect("frame recognizer delete -1", error=True, - substrs=["error: '-1' is not a valid recognizer id."]) - self.expect("frame recognizer delete 4294967297", error=True, - substrs=["error: '4294967297' is not a valid recognizer id."]) + self.expect( + "frame recognizer delete a", + error=True, + substrs=["error: 'a' is not a valid recognizer id."], + ) + self.expect( + 'frame recognizer delete ""', + error=True, + substrs=["error: '' is not a valid recognizer id."], + ) + self.expect( + "frame recognizer delete -1", + error=True, + substrs=["error: '-1' is not a valid recognizer id."], + ) + self.expect( + "frame recognizer delete 4294967297", + error=True, + substrs=["error: '4294967297' is not a valid recognizer id."], + ) @no_debug_info_test def test_frame_recognizer_info_invalid_arg(self): - self.expect("frame recognizer info a", error=True, - substrs=["error: 'a' is not a valid frame index."]) - self.expect("frame recognizer info \"\"", error=True, - substrs=["error: '' is not a valid frame index."]) - self.expect("frame recognizer info -1", error=True, - substrs=["error: '-1' is not a valid frame index."]) - self.expect("frame recognizer info 4294967297", error=True, - substrs=["error: '4294967297' is not a valid frame index."]) + self.expect( + "frame recognizer info a", + error=True, + substrs=["error: 'a' is not a valid frame index."], + ) + self.expect( + 'frame recognizer info ""', + error=True, + substrs=["error: '' is not a valid frame index."], + ) + self.expect( + "frame recognizer info -1", + error=True, + substrs=["error: '-1' is not a valid frame index."], + ) + self.expect( + "frame recognizer info 4294967297", + error=True, + substrs=["error: '4294967297' is not a valid frame index."], + ) @no_debug_info_test def test_frame_recognizer_add_invalid_arg(self): - self.expect("frame recognizer add -f", error=True, - substrs=["error: last option requires an argument"]) - self.expect("frame recognizer add -f -1", error=True, - substrs=["error: invalid boolean value '-1' passed for -f option"]) - self.expect("frame recognizer add -f foo", error=True, - substrs=["error: invalid boolean value 'foo' passed for -f option"]) + self.expect( + "frame recognizer add -f", + error=True, + substrs=["error: last option requires an argument"], + ) + self.expect( + "frame recognizer add -f -1", + error=True, + substrs=["error: invalid boolean value '-1' passed for -f option"], + ) + self.expect( + "frame recognizer add -f foo", + error=True, + substrs=["error: invalid boolean value 'foo' passed for -f option"], + ) diff --git a/lldb/test/API/commands/frame/recognizer/recognizer.py b/lldb/test/API/commands/frame/recognizer/recognizer.py --- a/lldb/test/API/commands/frame/recognizer/recognizer.py +++ b/lldb/test/API/commands/frame/recognizer/recognizer.py @@ -2,20 +2,37 @@ import lldb + class MyFrameRecognizer(object): def get_recognized_arguments(self, frame): if frame.name == "foo": arg1 = frame.EvaluateExpression("$arg1").signed arg2 = frame.EvaluateExpression("$arg2").signed - val1 = frame.GetThread().GetProcess().GetTarget().CreateValueFromExpression("a", "%d" % arg1) - val2 = frame.GetThread().GetProcess().GetTarget().CreateValueFromExpression("b", "%d" % arg2) + val1 = ( + frame.GetThread() + .GetProcess() + .GetTarget() + .CreateValueFromExpression("a", "%d" % arg1) + ) + val2 = ( + frame.GetThread() + .GetProcess() + .GetTarget() + .CreateValueFromExpression("b", "%d" % arg2) + ) return [val1, val2] elif frame.name == "bar": arg1 = frame.EvaluateExpression("$arg1").signed - val1 = frame.GetThread().GetProcess().GetTarget().CreateValueFromExpression("a", "(int *)%d" % arg1) + val1 = ( + frame.GetThread() + .GetProcess() + .GetTarget() + .CreateValueFromExpression("a", "(int *)%d" % arg1) + ) return [val1] return [] + class MyOtherFrameRecognizer(object): def get_recognized_arguments(self, frame): return [] diff --git a/lldb/test/API/commands/frame/select/TestFrameSelect.py b/lldb/test/API/commands/frame/select/TestFrameSelect.py --- a/lldb/test/API/commands/frame/select/TestFrameSelect.py +++ b/lldb/test/API/commands/frame/select/TestFrameSelect.py @@ -6,42 +6,72 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestFrameSelect(TestBase): +class TestFrameSelect(TestBase): @no_debug_info_test @skipIfWindows def test_relative(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) self.expect("frame select -r 1", substrs=["nested2() at"]) self.expect("frame select -r -1", substrs=["nested3() at"]) - self.expect("frame select -r -1", error=True, substrs=["Already at the bottom of the stack."]) - self.expect("frame select -r -2147483647", error=True, substrs=["Already at the bottom of the stack."]) - self.expect("frame select -r -2147483648", error=True, substrs=["error: invalid frame offset argument '-2147483648'"]) - self.expect("frame select -r -2147483649", error=True, substrs=["error: invalid frame offset argument '-2147483649'"]) + self.expect( + "frame select -r -1", + error=True, + substrs=["Already at the bottom of the stack."], + ) + self.expect( + "frame select -r -2147483647", + error=True, + substrs=["Already at the bottom of the stack."], + ) + self.expect( + "frame select -r -2147483648", + error=True, + substrs=["error: invalid frame offset argument '-2147483648'"], + ) + self.expect( + "frame select -r -2147483649", + error=True, + substrs=["error: invalid frame offset argument '-2147483649'"], + ) self.expect("frame select -r 1", substrs=["nested2() at"]) self.expect("frame select -r -2", substrs=["nested3() at"]) self.expect("frame select -r 1", substrs=["nested2() at"]) self.expect("frame select -r -2147483647", substrs=["nested3() at"]) self.expect("frame select -r 1", substrs=["nested2() at"]) - self.expect("frame select -r -2147483648", error=True, substrs=["error: invalid frame offset argument '-2147483648'"]) - self.expect("frame select -r -2147483649", error=True, substrs=["error: invalid frame offset argument '-2147483649'"]) + self.expect( + "frame select -r -2147483648", + error=True, + substrs=["error: invalid frame offset argument '-2147483648'"], + ) + self.expect( + "frame select -r -2147483649", + error=True, + substrs=["error: invalid frame offset argument '-2147483649'"], + ) self.expect("frame select -r 100") - self.expect("frame select -r 1", error=True, substrs=["Already at the top of the stack."]) + self.expect( + "frame select -r 1", + error=True, + substrs=["Already at the top of the stack."], + ) @no_debug_info_test @skipIfWindows def test_mixing_relative_and_abs(self): self.build() - lldbutil.run_to_source_breakpoint(self, - "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) # The function associated with each frame index can change depending # on the function calling main (e.g. `start`), so this only tests that diff --git a/lldb/test/API/commands/frame/var-scope/TestFrameVariableScope.py b/lldb/test/API/commands/frame/var-scope/TestFrameVariableScope.py --- a/lldb/test/API/commands/frame/var-scope/TestFrameVariableScope.py +++ b/lldb/test/API/commands/frame/var-scope/TestFrameVariableScope.py @@ -1,5 +1,4 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest( - __file__, globals(), []) +lldbinline.MakeInlineTest(__file__, globals(), []) diff --git a/lldb/test/API/commands/frame/var/TestFrameVar.py b/lldb/test/API/commands/frame/var/TestFrameVar.py --- a/lldb/test/API/commands/frame/var/TestFrameVar.py +++ b/lldb/test/API/commands/frame/var/TestFrameVar.py @@ -3,7 +3,6 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.decorators import * @@ -12,8 +11,8 @@ import shutil import time -class TestFrameVar(TestBase): +class TestFrameVar(TestBase): # If your test case doesn't stress debug info, then # set this to true. That way it won't be run once for # each debug info format. @@ -29,10 +28,11 @@ # Now create a breakpoint in main.c at the source matching # "Set a breakpoint here" breakpoint = target.BreakpointCreateBySourceRegex( - "Set a breakpoint here", lldb.SBFileSpec("main.c")) - self.assertTrue(breakpoint and - breakpoint.GetNumLocations() >= 1, - VALID_BREAKPOINT) + "Set a breakpoint here", lldb.SBFileSpec("main.c") + ) + self.assertTrue( + breakpoint and breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT + ) error = lldb.SBError() # This is the launch info. If you want to launch with arguments or @@ -45,10 +45,11 @@ # Did we hit our breakpoint? from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint + threads = get_threads_stopped_at_breakpoint(process, breakpoint) self.assertEqual( - len(threads), 1, - "There should be a thread stopped at our breakpoint") + len(threads), 1, "There should be a thread stopped at our breakpoint" + ) # The hit count for the breakpoint should be 1. self.assertEquals(breakpoint.GetHitCount(), 1) @@ -59,7 +60,9 @@ # Just get args: result = interp.HandleCommand("frame var -l", command_result) - self.assertEqual(result, lldb.eReturnStatusSuccessFinishResult, "frame var -a didn't succeed") + self.assertEqual( + result, lldb.eReturnStatusSuccessFinishResult, "frame var -a didn't succeed" + ) output = command_result.GetOutput() self.assertIn("argc", output, "Args didn't find argc") self.assertIn("argv", output, "Args didn't find argv") @@ -68,7 +71,9 @@ # Just get locals: result = interp.HandleCommand("frame var -a", command_result) - self.assertEqual(result, lldb.eReturnStatusSuccessFinishResult, "frame var -a didn't succeed") + self.assertEqual( + result, lldb.eReturnStatusSuccessFinishResult, "frame var -a didn't succeed" + ) output = command_result.GetOutput() self.assertNotIn("argc", output, "Locals found argc") self.assertNotIn("argv", output, "Locals found argv") @@ -77,20 +82,22 @@ # Get the file statics: result = interp.HandleCommand("frame var -l -a -g", command_result) - self.assertEqual(result, lldb.eReturnStatusSuccessFinishResult, "frame var -a didn't succeed") + self.assertEqual( + result, lldb.eReturnStatusSuccessFinishResult, "frame var -a didn't succeed" + ) output = command_result.GetOutput() self.assertNotIn("argc", output, "Globals found argc") self.assertNotIn("argv", output, "Globals found argv") self.assertNotIn("test_var", output, "Globals found test_var") self.assertIn("g_var", output, "Globals didn't find g_var") - def check_frame_variable_errors(self, thread, error_strings): command_result = lldb.SBCommandReturnObject() interp = self.dbg.GetCommandInterpreter() result = interp.HandleCommand("frame variable", command_result) - self.assertEqual(result, lldb.eReturnStatusFailed, - "frame var succeeded unexpectedly") + self.assertEqual( + result, lldb.eReturnStatusFailed, "frame var succeeded unexpectedly" + ) command_error = command_result.GetError() frame = thread.GetFrameAtIndex(0) @@ -103,15 +110,14 @@ for s in error_strings: self.assertIn(s, api_error) - @skipIfRemote @skipUnlessDarwin def test_darwin_dwarf_missing_obj(self): - ''' - Test that if we build a binary with DWARF in .o files and we remove - the .o file for main.cpp, that we get an appropriate error when we - do 'frame variable' that explains why we aren't seeing variables. - ''' + """ + Test that if we build a binary with DWARF in .o files and we remove + the .o file for main.cpp, that we get an appropriate error when we + do 'frame variable' that explains why we aren't seeing variables. + """ self.build(debug_info="dwarf") exe = self.getBuildArtifact("a.out") main_obj = self.getBuildArtifact("main.o") @@ -121,23 +127,22 @@ # We have to set a named breakpoint because we don't have any debug info # because we deleted the main.o file. - (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint(self, 'main') + (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint(self, "main") error_strings = [ 'debug map object file "', - 'main.o" containing debug info does not exist, debug info will not be loaded' + 'main.o" containing debug info does not exist, debug info will not be loaded', ] self.check_frame_variable_errors(thread, error_strings) - @skipIfRemote @skipUnlessDarwin def test_darwin_dwarf_obj_mod_time_mismatch(self): - ''' - Test that if we build a binary with DWARF in .o files and we update - the mod time of the .o file for main.cpp, that we get an appropriate - error when we do 'frame variable' that explains why we aren't seeing - variables. - ''' + """ + Test that if we build a binary with DWARF in .o files and we update + the mod time of the .o file for main.cpp, that we get an appropriate + error when we do 'frame variable' that explains why we aren't seeing + variables. + """ self.build(debug_info="dwarf") exe = self.getBuildArtifact("a.out") main_obj = self.getBuildArtifact("main.o") @@ -152,51 +157,52 @@ # We have to set a named breakpoint because we don't have any debug info # because we deleted the main.o file since the mod times don't match # and debug info won't be loaded - (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint(self, 'main') + (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint(self, "main") error_strings = [ 'debug map object file "', 'main.o" changed (actual: 0x', - ', debug map: 0x', - ') since this executable was linked, debug info will not be loaded' + ", debug map: 0x", + ") since this executable was linked, debug info will not be loaded", ] self.check_frame_variable_errors(thread, error_strings) - @skipIfRemote - @skipIfWindows # Windows can't set breakpoints by name 'main' in this case. + @skipIfWindows # Windows can't set breakpoints by name 'main' in this case. def test_gline_tables_only(self): - ''' - Test that if we build a binary with "-gline-tables-only" that we can - set a file and line breakpoint successfully, and get an error - letting us know that this build option was enabled when trying to - read variables. - ''' - self.build(dictionary={'CFLAGS_EXTRAS': '-gline-tables-only'}) + """ + Test that if we build a binary with "-gline-tables-only" that we can + set a file and line breakpoint successfully, and get an error + letting us know that this build option was enabled when trying to + read variables. + """ + self.build(dictionary={"CFLAGS_EXTRAS": "-gline-tables-only"}) exe = self.getBuildArtifact("a.out") # We have to set a named breakpoint because we don't have any debug info # because we deleted the main.o file since the mod times don't match # and debug info won't be loaded - (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint(self, 'main') + (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint(self, "main") error_strings = [ - 'no variable information is available in debug info for this compile unit' + "no variable information is available in debug info for this compile unit" ] self.check_frame_variable_errors(thread, error_strings) @skipUnlessPlatform(["linux", "freebsd"]) @add_test_categories(["dwo"]) def test_fission_missing_dwo(self): - ''' - Test that if we build a binary with "-gsplit-dwarf" that we can - set a file and line breakpoint successfully, and get an error - letting us know we were unable to load the .dwo file. - ''' - self.build(dictionary={'CFLAGS_EXTRAS': '-gsplit-dwarf'}) + """ + Test that if we build a binary with "-gsplit-dwarf" that we can + set a file and line breakpoint successfully, and get an error + letting us know we were unable to load the .dwo file. + """ + self.build(dictionary={"CFLAGS_EXTRAS": "-gsplit-dwarf"}) exe = self.getBuildArtifact("a.out") main_dwo = self.getBuildArtifact("main.dwo") - self.assertTrue(os.path.exists(main_dwo), 'Make sure "%s" file exists' % (main_dwo)) + self.assertTrue( + os.path.exists(main_dwo), 'Make sure "%s" file exists' % (main_dwo) + ) # Delete the main.dwo file that contains the debug info so we force an # error when we run to main and try to get variables. os.unlink(main_dwo) @@ -204,36 +210,38 @@ # We have to set a named breakpoint because we don't have any debug info # because we deleted the main.o file since the mod times don't match # and debug info won't be loaded - (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint(self, 'main') + (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint(self, "main") error_strings = [ 'unable to locate .dwo debug file "', - 'main.dwo" for skeleton DIE 0x' + 'main.dwo" for skeleton DIE 0x', ] self.check_frame_variable_errors(thread, error_strings) @skipUnlessPlatform(["linux", "freebsd"]) @add_test_categories(["dwo"]) def test_fission_invalid_dwo_objectfile(self): - ''' - Test that if we build a binary with "-gsplit-dwarf" that we can - set a file and line breakpoint successfully, and get an error - letting us know we were unable to load the .dwo file because it - existed, but it wasn't a valid object file. - ''' - self.build(dictionary={'CFLAGS_EXTRAS': '-gsplit-dwarf'}) + """ + Test that if we build a binary with "-gsplit-dwarf" that we can + set a file and line breakpoint successfully, and get an error + letting us know we were unable to load the .dwo file because it + existed, but it wasn't a valid object file. + """ + self.build(dictionary={"CFLAGS_EXTRAS": "-gsplit-dwarf"}) exe = self.getBuildArtifact("a.out") main_dwo = self.getBuildArtifact("main.dwo") - self.assertTrue(os.path.exists(main_dwo), 'Make sure "%s" file exists' % (main_dwo)) + self.assertTrue( + os.path.exists(main_dwo), 'Make sure "%s" file exists' % (main_dwo) + ) # Overwrite the main.dwo with the main.c source file so that the .dwo # file exists, but it isn't a valid object file as there is an error # for this case. - shutil.copyfile(self.getSourcePath('main.c'), main_dwo) + shutil.copyfile(self.getSourcePath("main.c"), main_dwo) # We have to set a named breakpoint because we don't have any debug info # because we deleted the main.o file since the mod times don't match # and debug info won't be loaded - (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint(self, 'main') + (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint(self, "main") error_strings = [ 'unable to load object file for .dwo debug file "' 'main.dwo" for unit DIE 0x', diff --git a/lldb/test/API/commands/frame/var/direct-ivar/cpp/TestFrameVarDirectIvarCpp.py b/lldb/test/API/commands/frame/var/direct-ivar/cpp/TestFrameVarDirectIvarCpp.py --- a/lldb/test/API/commands/frame/var/direct-ivar/cpp/TestFrameVarDirectIvarCpp.py +++ b/lldb/test/API/commands/frame/var/direct-ivar/cpp/TestFrameVarDirectIvarCpp.py @@ -7,5 +7,7 @@ class TestCase(TestBase): def test_cpp_this(self): self.build() - lldbutil.run_to_source_breakpoint(self, "// check this", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// check this", lldb.SBFileSpec("main.cpp") + ) self.expect("frame variable m_field", startstr="(int) m_field = 30") diff --git a/lldb/test/API/commands/frame/var/direct-ivar/objc/TestFrameVarDirectIvarObjC.py b/lldb/test/API/commands/frame/var/direct-ivar/objc/TestFrameVarDirectIvarObjC.py --- a/lldb/test/API/commands/frame/var/direct-ivar/objc/TestFrameVarDirectIvarObjC.py +++ b/lldb/test/API/commands/frame/var/direct-ivar/objc/TestFrameVarDirectIvarObjC.py @@ -8,13 +8,17 @@ @skipUnlessDarwin def test_objc_self(self): self.build() - lldbutil.run_to_source_breakpoint(self, "// check self", lldb.SBFileSpec("main.m")) + lldbutil.run_to_source_breakpoint( + self, "// check self", lldb.SBFileSpec("main.m") + ) self.expect("frame variable _ivar", startstr="(int) _ivar = 30") @skipUnlessDarwin def test_objc_self_capture_idiom(self): self.build() - lldbutil.run_to_source_breakpoint(self, "// check idiomatic self", lldb.SBFileSpec("main.m")) + lldbutil.run_to_source_breakpoint( + self, "// check idiomatic self", lldb.SBFileSpec("main.m") + ) self.expect("frame variable weakSelf", startstr="(Classic *) weakSelf = 0x") self.expect("frame variable self", startstr="(Classic *) self = 0x") self.expect("frame variable _ivar", startstr="(int) _ivar = 30") diff --git a/lldb/test/API/commands/frame/var/direct-ivar/objcpp/TestFrameVarDirectIvarObjCPlusPlus.py b/lldb/test/API/commands/frame/var/direct-ivar/objcpp/TestFrameVarDirectIvarObjCPlusPlus.py --- a/lldb/test/API/commands/frame/var/direct-ivar/objcpp/TestFrameVarDirectIvarObjCPlusPlus.py +++ b/lldb/test/API/commands/frame/var/direct-ivar/objcpp/TestFrameVarDirectIvarObjCPlusPlus.py @@ -8,17 +8,23 @@ @skipUnlessDarwin def test_objc_self(self): self.build() - lldbutil.run_to_source_breakpoint(self, "check self", lldb.SBFileSpec("main.mm")) + lldbutil.run_to_source_breakpoint( + self, "check self", lldb.SBFileSpec("main.mm") + ) self.expect("frame variable _ivar", startstr="(int) _ivar = 30") @skipUnlessDarwin def test_objc_explicit_self(self): self.build() - lldbutil.run_to_source_breakpoint(self, "check explicit self", lldb.SBFileSpec("main.mm")) + lldbutil.run_to_source_breakpoint( + self, "check explicit self", lldb.SBFileSpec("main.mm") + ) self.expect("frame variable _ivar", startstr="(int) _ivar = 30") @skipUnlessDarwin def test_cpp_this(self): self.build() - lldbutil.run_to_source_breakpoint(self, "check this", lldb.SBFileSpec("main.mm")) + lldbutil.run_to_source_breakpoint( + self, "check this", lldb.SBFileSpec("main.mm") + ) self.expect("frame variable m_field", startstr="(int) m_field = 41") diff --git a/lldb/test/API/commands/gui/basic/TestGuiBasic.py b/lldb/test/API/commands/gui/basic/TestGuiBasic.py --- a/lldb/test/API/commands/gui/basic/TestGuiBasic.py +++ b/lldb/test/API/commands/gui/basic/TestGuiBasic.py @@ -7,8 +7,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import PExpectTest -class BasicGuiCommandTest(PExpectTest): +class BasicGuiCommandTest(PExpectTest): # PExpect uses many timeouts internally and doesn't play well # under ASAN on a loaded machine.. @skipIfAsan @@ -17,11 +17,12 @@ def test_gui(self): self.build() - self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100,500)) - self.expect('br set -f main.c -p "// Break here"', substrs=["Breakpoint 1", "address ="]) + self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100, 500)) + self.expect( + 'br set -f main.c -p "// Break here"', substrs=["Breakpoint 1", "address ="] + ) self.expect("run", substrs=["stop reason ="]) - escape_key = chr(27).encode() # Start the GUI. diff --git a/lldb/test/API/commands/gui/basicdebug/TestGuiBasicDebug.py b/lldb/test/API/commands/gui/basicdebug/TestGuiBasicDebug.py --- a/lldb/test/API/commands/gui/basicdebug/TestGuiBasicDebug.py +++ b/lldb/test/API/commands/gui/basicdebug/TestGuiBasicDebug.py @@ -7,8 +7,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import PExpectTest -class TestGuiBasicDebugCommandTest(PExpectTest): +class TestGuiBasicDebugCommandTest(PExpectTest): # PExpect uses many timeouts internally and doesn't play well # under ASAN on a loaded machine.. @skipIfAsan @@ -17,8 +17,10 @@ def test_gui(self): self.build() - self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100,500)) - self.expect('br set -f main.c -p "// Break here"', substrs=["Breakpoint 1", "address ="]) + self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100, 500)) + self.expect( + 'br set -f main.c -p "// Break here"', substrs=["Breakpoint 1", "address ="] + ) self.expect("run", substrs=["stop reason ="]) escape_key = chr(27).encode() @@ -27,28 +29,28 @@ self.child.sendline("gui") # Simulate a simple debugging session. - self.child.send("s") # step + self.child.send("s") # step self.child.expect("return 1; // In function[^\r\n]+<<< Thread 1: step in") - self.child.send("u") # up + self.child.send("u") # up self.child.expect_exact("func(); // Break here") - self.child.send("d") # down + self.child.send("d") # down self.child.expect_exact("return 1; // In function") - self.child.send("f") # finish + self.child.send("f") # finish self.child.expect("<<< Thread 1: step out") - self.child.send("s") # move onto the second one + self.child.send("s") # move onto the second one self.child.expect("<<< Thread 1: step in") - self.child.send("n") # step over + self.child.send("n") # step over self.child.expect("// Dummy command 1[^\r\n]+<<< Thread 1: step over") self.child.send("n") # Test that 'up' + 'step out' steps out of the selected function. - self.child.send("s") # move into func_up() + self.child.send("s") # move into func_up() self.child.expect("// In func_up") - self.child.send("s") # move into func_down() + self.child.send("s") # move into func_down() self.child.expect("// In func_down") - self.child.send("u") # up + self.child.send("u") # up self.child.expect("// In func_up") - self.child.send("f") # finish + self.child.send("f") # finish self.child.expect("// Dummy command 2[^\r\n]+<<< Thread 1: step out") self.child.send("n") diff --git a/lldb/test/API/commands/gui/breakpoints/TestGuiBreakpoints.py b/lldb/test/API/commands/gui/breakpoints/TestGuiBreakpoints.py --- a/lldb/test/API/commands/gui/breakpoints/TestGuiBreakpoints.py +++ b/lldb/test/API/commands/gui/breakpoints/TestGuiBreakpoints.py @@ -7,8 +7,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import PExpectTest -class TestGuiBasicDebugCommandTest(PExpectTest): +class TestGuiBasicDebugCommandTest(PExpectTest): # PExpect uses many timeouts internally and doesn't play well # under ASAN on a loaded machine.. @skipIfAsan @@ -17,23 +17,26 @@ def test_gui(self): self.build() - self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100,500)) - self.expect('br set -o true -f main.c -p "// First break here"', substrs=["Breakpoint 1", "address ="]) + self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100, 500)) + self.expect( + 'br set -o true -f main.c -p "// First break here"', + substrs=["Breakpoint 1", "address ="], + ) self.expect("run", substrs=["stop reason ="]) self.child.sendline("breakpoint list") self.child.expect_exact("No breakpoints currently set.") escape_key = chr(27).encode() - down_key = chr(27)+'OB' # for vt100 terminal (lldbexpect sets TERM=vt100) + down_key = chr(27) + "OB" # for vt100 terminal (lldbexpect sets TERM=vt100) # Start the GUI. self.child.sendline("gui") - self.child.expect_exact("Sources") # wait for gui + self.child.expect_exact("Sources") # wait for gui # Go to next line, set a breakpoint. self.child.send(down_key) - self.child.send('b') + self.child.send("b") self.child.send(escape_key) self.expect_prompt() self.child.sendline("breakpoint list") @@ -44,7 +47,7 @@ # Go two lines down ("gui" resets position), set a breakpoint. self.child.send(down_key) self.child.send(down_key) - self.child.send('b') + self.child.send("b") self.child.send(escape_key) self.expect_prompt() self.child.sendline("breakpoint list") @@ -55,9 +58,9 @@ # Toggle both the breakpoints (remove them). self.child.send(down_key) - self.child.send('b') + self.child.send("b") self.child.send(down_key) - self.child.send('b') + self.child.send("b") self.child.send(escape_key) self.expect_prompt() self.child.sendline("breakpoint list") diff --git a/lldb/test/API/commands/gui/expand-threads-tree/TestGuiExpandThreadsTree.py b/lldb/test/API/commands/gui/expand-threads-tree/TestGuiExpandThreadsTree.py --- a/lldb/test/API/commands/gui/expand-threads-tree/TestGuiExpandThreadsTree.py +++ b/lldb/test/API/commands/gui/expand-threads-tree/TestGuiExpandThreadsTree.py @@ -9,8 +9,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import PExpectTest -class TestGuiExpandThreadsTree(PExpectTest): +class TestGuiExpandThreadsTree(PExpectTest): # PExpect uses many timeouts internally and doesn't play well # under ASAN on a loaded machine.. @skipIfAsan @@ -20,8 +20,10 @@ def test_gui(self): self.build() - self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100,500)) - self.expect("breakpoint set -n break_here", substrs=["Breakpoint 1", "address ="]) + self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100, 500)) + self.expect( + "breakpoint set -n break_here", substrs=["Breakpoint 1", "address ="] + ) self.expect("run", substrs=["stop reason ="]) escape_key = chr(27).encode() diff --git a/lldb/test/API/commands/gui/invalid-args/TestInvalidArgsGui.py b/lldb/test/API/commands/gui/invalid-args/TestInvalidArgsGui.py --- a/lldb/test/API/commands/gui/invalid-args/TestInvalidArgsGui.py +++ b/lldb/test/API/commands/gui/invalid-args/TestInvalidArgsGui.py @@ -2,10 +2,11 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * -class GuiTestCase(TestBase): +class GuiTestCase(TestBase): @no_debug_info_test @skipIfCursesSupportMissing def test_reproducer_generate_invalid_invocation(self): - self.expect("gui blub", error=True, - substrs=["'gui' doesn't take any arguments."]) + self.expect( + "gui blub", error=True, substrs=["'gui' doesn't take any arguments."] + ) diff --git a/lldb/test/API/commands/gui/viewlarge/TestGuiViewLarge.py b/lldb/test/API/commands/gui/viewlarge/TestGuiViewLarge.py --- a/lldb/test/API/commands/gui/viewlarge/TestGuiViewLarge.py +++ b/lldb/test/API/commands/gui/viewlarge/TestGuiViewLarge.py @@ -7,26 +7,28 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import PExpectTest -class GuiViewLargeCommandTest(PExpectTest): +class GuiViewLargeCommandTest(PExpectTest): # PExpect uses many timeouts internally and doesn't play well # under ASAN on a loaded machine.. @skipIfAsan @skipIfCursesSupportMissing - @skipIfRemote # "run" command will not work correctly for remote debug + @skipIfRemote # "run" command will not work correctly for remote debug @expectedFailureNetBSD @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) def test_gui(self): self.build() # Limit columns to 80, so that long lines will not be displayed completely. - self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100,80)) - self.expect('br set -f main.c -p "// Break here"', substrs=["Breakpoint 1", "address ="]) + self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100, 80)) + self.expect( + 'br set -f main.c -p "// Break here"', substrs=["Breakpoint 1", "address ="] + ) self.expect("run", substrs=["stop reason ="]) escape_key = chr(27).encode() - left_key = chr(27)+'OD' # for vt100 terminal (lldbexpect sets TERM=vt100) - right_key = chr(27)+'OC' + left_key = chr(27) + "OD" # for vt100 terminal (lldbexpect sets TERM=vt100) + right_key = chr(27) + "OC" ctrl_l = chr(12) # Start the GUI. @@ -36,16 +38,20 @@ self.child.expect_exact("Sources") # The string is copy&pasted from a 80-columns terminal. It will be followed by some # kind of an escape sequence (color, frame, etc.). - self.child.expect_exact("int a_variable_with_a_very_looooooooooooooooooooooooooo"+chr(27)) + self.child.expect_exact( + "int a_variable_with_a_very_looooooooooooooooooooooooooo" + chr(27) + ) # The escape here checks that there's no content drawn by the previous line. - self.child.expect_exact("int shortvar = 1;"+chr(27)) + self.child.expect_exact("int shortvar = 1;" + chr(27)) # Check the triggered breakpoint marker on a long line. - self.child.expect_exact("<<< Thread 1: breakpoint 1.1"+chr(27)) + self.child.expect_exact("<<< Thread 1: breakpoint 1.1" + chr(27)) # Check the variable window. self.child.expect_exact("Variables") - self.child.expect_exact("(int) a_variable_with_a_very_looooooooooooooooooooooooooooooo"+chr(27)) - self.child.expect_exact("(int) shortvar = 1"+chr(27)) + self.child.expect_exact( + "(int) a_variable_with_a_very_looooooooooooooooooooooooooooooo" + chr(27) + ) + self.child.expect_exact("(int) shortvar = 1" + chr(27)) # Scroll the sources view twice to the right. self.child.send(right_key) @@ -53,13 +59,17 @@ # Force a redraw, otherwise curses will optimize the drawing to not draw all 'o'. self.child.send(ctrl_l) # The source code is indented by two spaces, so there'll be just two extra 'o' on the right. - self.child.expect_exact("int a_variable_with_a_very_looooooooooooooooooooooooooooo"+chr(27)) + self.child.expect_exact( + "int a_variable_with_a_very_looooooooooooooooooooooooooooo" + chr(27) + ) # And scroll back to the left. self.child.send(left_key) self.child.send(left_key) self.child.send(ctrl_l) - self.child.expect_exact("int a_variable_with_a_very_looooooooooooooooooooooooooo"+chr(27)) + self.child.expect_exact( + "int a_variable_with_a_very_looooooooooooooooooooooooooo" + chr(27) + ) # Press escape to quit the gui self.child.send(escape_key) diff --git a/lldb/test/API/commands/help/TestHelp.py b/lldb/test/API/commands/help/TestHelp.py --- a/lldb/test/API/commands/help/TestHelp.py +++ b/lldb/test/API/commands/help/TestHelp.py @@ -5,7 +5,6 @@ """ - import os import lldb from lldbsuite.test.decorators import * @@ -14,39 +13,34 @@ class HelpCommandTestCase(TestBase): - @no_debug_info_test def test_simplehelp(self): """A simple test of 'help' command and its output.""" - self.expect("help", - startstr='Debugger commands:') + self.expect("help", startstr="Debugger commands:") - self.expect("help -a", matching=False, - substrs=['next']) + self.expect("help -a", matching=False, substrs=["next"]) - self.expect("help", matching=True, - substrs=['next']) + self.expect("help", matching=True, substrs=["next"]) @no_debug_info_test def test_help_on_help(self): """Testing the help on the help facility.""" - self.expect("help help", matching=True, - substrs=['--hide-aliases', - '--hide-user-commands']) + self.expect( + "help help", + matching=True, + substrs=["--hide-aliases", "--hide-user-commands"], + ) @no_debug_info_test def test_help_arch(self): """Test 'help arch' which should list of supported architectures.""" - self.expect("help arch", - substrs=['arm', 'i386', 'x86_64']) + self.expect("help arch", substrs=["arm", "i386", "x86_64"]) @no_debug_info_test def test_help_version(self): """Test 'help version' and 'version' commands.""" - self.expect("help version", - substrs=['Show the LLDB debugger version.']) - self.expect("version", - patterns=['lldb( version|-[0-9]+).*\n']) + self.expect("help version", substrs=["Show the LLDB debugger version."]) + self.expect("version", patterns=["lldb( version|-[0-9]+).*\n"]) @no_debug_info_test def test_help_should_not_crash_lldb(self): @@ -66,95 +60,98 @@ "settings set term-width 0", COMMAND_FAILED_AS_EXPECTED, error=True, - substrs=['error: 0 is out of range, valid values must be between']) + substrs=["error: 0 is out of range, valid values must be between"], + ) # self.runCmd("settings set term-width 0") - self.expect("help", - startstr='Debugger commands:') + self.expect("help", startstr="Debugger commands:") @no_debug_info_test def test_help_breakpoint_set(self): """Test that 'help breakpoint set' does not print out redundant lines of: 'breakpoint set [-s ] ...'.""" - self.expect("help breakpoint set", matching=False, - substrs=['breakpoint set [-s ]']) + self.expect( + "help breakpoint set", + matching=False, + substrs=["breakpoint set [-s ]"], + ) @no_debug_info_test def test_help_image_dump_symtab_should_not_crash(self): """Command 'help image dump symtab' should not crash lldb.""" # 'image' is an alias for 'target modules'. - self.expect("help image dump symtab", - substrs=['dump symtab', - 'sort-order']) + self.expect("help image dump symtab", substrs=["dump symtab", "sort-order"]) @no_debug_info_test def test_help_image_du_sym_is_ambiguous(self): """Command 'help image du sym' is ambiguous and spits out the list of candidates.""" - self.expect("help image du sym", - COMMAND_FAILED_AS_EXPECTED, error=True, - substrs=['error: ambiguous command image du sym', - 'symfile', - 'symtab']) + self.expect( + "help image du sym", + COMMAND_FAILED_AS_EXPECTED, + error=True, + substrs=["error: ambiguous command image du sym", "symfile", "symtab"], + ) @no_debug_info_test def test_help_image_du_line_should_work(self): """Command 'help image du line-table' is not ambiguous and should work.""" # 'image' is an alias for 'target modules'. - self.expect("help image du line", substrs=[ - 'Dump the line table for one or more compilation units']) + self.expect( + "help image du line", + substrs=["Dump the line table for one or more compilation units"], + ) @no_debug_info_test def test_help_image_list_shows_positional_args(self): """Command 'help image list' should describe positional args.""" # 'image' is an alias for 'target modules'. - self.expect("help image list", substrs=[ - ' [...]']) + self.expect("help image list", substrs=[" [...]"]) @no_debug_info_test def test_help_target_variable_syntax(self): """Command 'help target variable' should display ...""" - self.expect("help target variable", - substrs=[' [ [...]]']) + self.expect( + "help target variable", substrs=[" [ [...]]"] + ) @no_debug_info_test def test_help_watchpoint_and_its_args(self): """Command 'help watchpoint', 'help watchpt-id', and 'help watchpt-id-list' should work.""" - self.expect("help watchpoint", - substrs=['delete', 'disable', 'enable', 'list']) - self.expect("help watchpt-id", - substrs=['']) - self.expect("help watchpt-id-list", - substrs=['']) + self.expect("help watchpoint", substrs=["delete", "disable", "enable", "list"]) + self.expect("help watchpt-id", substrs=[""]) + self.expect("help watchpt-id-list", substrs=[""]) @no_debug_info_test def test_help_watchpoint_set(self): """Test that 'help watchpoint set' prints out 'expression' and 'variable' as the possible subcommands.""" - self.expect("help watchpoint set", - substrs=['The following subcommands are supported:'], - patterns=['expression +--', - 'variable +--']) + self.expect( + "help watchpoint set", + substrs=["The following subcommands are supported:"], + patterns=["expression +--", "variable +--"], + ) @no_debug_info_test def test_help_po_hides_options(self): """Test that 'help po' does not show all the options for expression""" self.expect( "help po", - substrs=[ - '--show-all-children', - '--object-description'], - matching=False) + substrs=["--show-all-children", "--object-description"], + matching=False, + ) @no_debug_info_test def test_help_run_hides_options(self): """Test that 'help run' does not show all the options for process launch""" - self.expect("help run", - substrs=['--arch', '--environment'], matching=False) + self.expect("help run", substrs=["--arch", "--environment"], matching=False) @no_debug_info_test def test_help_next_shows_options(self): """Test that 'help next' shows all the options for thread step-over""" - self.expect("help next", - substrs=['--step-out-avoids-no-debug', '--run-mode'], matching=True) + self.expect( + "help next", + substrs=["--step-out-avoids-no-debug", "--run-mode"], + matching=True, + ) @no_debug_info_test def test_help_provides_alternatives(self): @@ -165,8 +162,10 @@ "'thisisnotadebuggercommand' is not a known command.", "Try 'help' to see a current list of commands.", "Try 'apropos thisisnotadebuggercommand' for a list of related commands.", - "Try 'type lookup thisisnotadebuggercommand' for information on types, methods, functions, modules, etc."], - error=True) + "Try 'type lookup thisisnotadebuggercommand' for information on types, methods, functions, modules, etc.", + ], + error=True, + ) self.expect( "help process thisisnotadebuggercommand", @@ -174,62 +173,77 @@ "'process thisisnotadebuggercommand' is not a known command.", "Try 'help' to see a current list of commands.", "Try 'apropos thisisnotadebuggercommand' for a list of related commands.", - "Try 'type lookup thisisnotadebuggercommand' for information on types, methods, functions, modules, etc."]) + "Try 'type lookup thisisnotadebuggercommand' for information on types, methods, functions, modules, etc.", + ], + ) @no_debug_info_test def test_custom_help_alias(self): """Test that aliases pick up custom help text.""" + def cleanup(): - self.runCmd('command unalias afriendlyalias', check=False) - self.runCmd('command unalias averyfriendlyalias', check=False) + self.runCmd("command unalias afriendlyalias", check=False) + self.runCmd("command unalias averyfriendlyalias", check=False) self.addTearDownHook(cleanup) self.runCmd( - 'command alias --help "I am a friendly alias" -- afriendlyalias help') + 'command alias --help "I am a friendly alias" -- afriendlyalias help' + ) self.expect( - "help afriendlyalias", - matching=True, - substrs=['I am a friendly alias']) + "help afriendlyalias", matching=True, substrs=["I am a friendly alias"] + ) self.runCmd( - 'command alias --long-help "I am a very friendly alias" -- averyfriendlyalias help') - self.expect("help averyfriendlyalias", matching=True, - substrs=['I am a very friendly alias']) + 'command alias --long-help "I am a very friendly alias" -- averyfriendlyalias help' + ) + self.expect( + "help averyfriendlyalias", + matching=True, + substrs=["I am a very friendly alias"], + ) + @no_debug_info_test def test_alias_prints_origin(self): """Test that 'help ' prints the alias origin.""" + def cleanup(): - self.runCmd('command unalias alongaliasname', check=False) + self.runCmd("command unalias alongaliasname", check=False) self.addTearDownHook(cleanup) - self.runCmd('command alias alongaliasname help') - self.expect("help alongaliasna", matching=True, - substrs=["'alongaliasna' is an abbreviation for 'help'"]) + self.runCmd("command alias alongaliasname help") + self.expect( + "help alongaliasna", + matching=True, + substrs=["'alongaliasna' is an abbreviation for 'help'"], + ) @no_debug_info_test def test_hidden_help(self): - self.expect("help -h", - substrs=["_regexp-bt"]) + self.expect("help -h", substrs=["_regexp-bt"]) @no_debug_info_test def test_help_ambiguous(self): - self.expect("help g", - substrs=["Help requested with ambiguous command name, possible completions:", - "gdb-remote", "gui"]) + self.expect( + "help g", + substrs=[ + "Help requested with ambiguous command name, possible completions:", + "gdb-remote", + "gui", + ], + ) @no_debug_info_test def test_help_unknown_flag(self): - self.expect("help -z", error=True, - substrs=["unknown or ambiguous option"]) + self.expect("help -z", error=True, substrs=["unknown or ambiguous option"]) @no_debug_info_test def test_help_format_output(self): """Test that help output reaches TerminalWidth.""" - self.runCmd( - 'settings set term-width 108') + self.runCmd("settings set term-width 108") self.expect( "help format", matching=True, - substrs=[' -- One of the format names']) + substrs=[" -- One of the format names"], + ) @no_debug_info_test def test_help_option_group_format_options_usage(self): @@ -238,38 +252,54 @@ "help memory read", matching=True, substrs=[ - "-f ( --format )", "Specify a format to be used for display.", - "-s ( --size )", "The size in bytes to use when displaying with the selected format."]) + "-f ( --format )", + "Specify a format to be used for display.", + "-s ( --size )", + "The size in bytes to use when displaying with the selected format.", + ], + ) self.expect( "help memory write", matching=True, substrs=[ - "-f ( --format )", "The format to use for each of the value to be written.", - "-s ( --size )", "The size in bytes to write from input file or each value."]) + "-f ( --format )", + "The format to use for each of the value to be written.", + "-s ( --size )", + "The size in bytes to write from input file or each value.", + ], + ) @no_debug_info_test def test_help_shows_optional_short_options(self): """Test that optional short options are printed and that they are in - alphabetical order with upper case options first.""" - self.expect("help memory read", - substrs=["memory read [-br]", "memory read [-AFLORTr]"]) - self.expect("help target modules lookup", - substrs=["target modules lookup [-Airv]"]) + alphabetical order with upper case options first.""" + self.expect( + "help memory read", substrs=["memory read [-br]", "memory read [-AFLORTr]"] + ) + self.expect( + "help target modules lookup", substrs=["target modules lookup [-Airv]"] + ) @no_debug_info_test def test_help_shows_command_options_usage(self): """Test that we start the usage section with a specific line.""" - self.expect("help memory read", substrs=["Command Options Usage:\n memory read"]) + self.expect( + "help memory read", substrs=["Command Options Usage:\n memory read"] + ) @no_debug_info_test def test_help_detailed_information_spacing(self): """Test that we put a break between the usage and the options help lines, - and between the options themselves.""" - self.expect("help memory read", substrs=[ - "[]\n\n -A ( --show-all-children )", - # Starts with the end of the show-all-children line - "to show.\n\n -D"]) + and between the options themselves.""" + self.expect( + "help memory read", + substrs=[ + "[]\n\n -A ( --show-all-children )", + # Starts with the end of the show-all-children line + "to show.\n\n -D", + ], + ) @no_debug_info_test def test_help_detailed_information_ordering(self): @@ -285,7 +315,7 @@ options_lines = options_lines.lstrip().splitlines() # Skip over "memory read [-xyz] lines. - while("memory read" in options_lines[0]): + while "memory read" in options_lines[0]: options_lines.pop(0) # Plus the newline after that. options_lines.pop(0) @@ -306,28 +336,43 @@ # Save its short char name. short_options.append(line[1]) - self.assertEqual(sorted(short_options), short_options, - "Short option help displayed in an incorrect order!") + self.assertEqual( + sorted(short_options), + short_options, + "Short option help displayed in an incorrect order!", + ) @no_debug_info_test def test_help_show_tags(self): - """ Check that memory find and memory read have the --show-tags option - but only memory read mentions binary output. """ - self.expect("help memory read", patterns=[ - "--show-tags\n\s+Include memory tags in output " - "\(does not apply to binary output\)."]) - self.expect("help memory find", patterns=[ - "--show-tags\n\s+Include memory tags in output."]) + """Check that memory find and memory read have the --show-tags option + but only memory read mentions binary output.""" + self.expect( + "help memory read", + patterns=[ + "--show-tags\n\s+Include memory tags in output " + "\(does not apply to binary output\)." + ], + ) + self.expect( + "help memory find", + patterns=["--show-tags\n\s+Include memory tags in output."], + ) @no_debug_info_test def test_help_show_enum_values(self): - """ Check the help output for a argument type contains the enum values - and their descriptions. """ - self.expect("help ", substrs=[ - 'The log handle that will be used to write out log messages.', - 'default' , 'Use the default (stream) log handler', - 'stream' , 'Write log messages to the debugger output stream', - 'circular' , 'Write log messages to a fixed size circular buffer', - 'os' , 'Write log messages to the operating system log', - ]) - + """Check the help output for a argument type contains the enum values + and their descriptions.""" + self.expect( + "help ", + substrs=[ + "The log handle that will be used to write out log messages.", + "default", + "Use the default (stream) log handler", + "stream", + "Write log messages to the debugger output stream", + "circular", + "Write log messages to a fixed size circular buffer", + "os", + "Write log messages to the operating system log", + ], + ) diff --git a/lldb/test/API/commands/log/basic/TestLogHandlers.py b/lldb/test/API/commands/log/basic/TestLogHandlers.py --- a/lldb/test/API/commands/log/basic/TestLogHandlers.py +++ b/lldb/test/API/commands/log/basic/TestLogHandlers.py @@ -15,7 +15,7 @@ def setUp(self): TestBase.setUp(self) self.log_file = self.getBuildArtifact("log-file.txt") - if (os.path.exists(self.log_file)): + if os.path.exists(self.log_file): os.remove(self.log_file) def test_circular(self): @@ -23,7 +23,7 @@ self.runCmd("bogus", check=False) self.runCmd("log dump lldb -f {}".format(self.log_file)) - with open(self.log_file, 'r') as f: + with open(self.log_file, "r") as f: log_lines = f.readlines() self.assertEqual(len(log_lines), 5) @@ -32,9 +32,9 @@ found_command_bogus = False for line in log_lines: - if 'Processing command: log dump' in line: + if "Processing command: log dump" in line: found_command_log_dump = True - if 'Processing command: bogus' in line: + if "Processing command: bogus" in line: found_command_bogus = True self.assertTrue(found_command_log_dump) @@ -44,12 +44,13 @@ self.expect( "log enable -h circular lldb commands", error=True, - substrs=[ - 'the circular buffer handler requires a non-zero buffer size' - ]) + substrs=["the circular buffer handler requires a non-zero buffer size"], + ) def test_dump_unsupported(self): self.runCmd("log enable lldb commands -f {}".format(self.log_file)) - self.expect("log dump lldb", - error=True, - substrs=["log channel 'lldb' does not support dumping"]) + self.expect( + "log dump lldb", + error=True, + substrs=["log channel 'lldb' does not support dumping"], + ) diff --git a/lldb/test/API/commands/log/basic/TestLogging.py b/lldb/test/API/commands/log/basic/TestLogging.py --- a/lldb/test/API/commands/log/basic/TestLogging.py +++ b/lldb/test/API/commands/log/basic/TestLogging.py @@ -3,7 +3,6 @@ """ - import os import lldb from lldbsuite.test.decorators import * @@ -18,14 +17,12 @@ super(LogTestCase, self).setUp() self.log_file = self.getBuildArtifact("log-file.txt") - def test_file_writing(self): self.build() exe = self.getBuildArtifact("a.out") - self.expect("file " + exe, - patterns=["Current executable set to .*a.out"]) + self.expect("file " + exe, patterns=["Current executable set to .*a.out"]) - if (os.path.exists(self.log_file)): + if os.path.exists(self.log_file): os.remove(self.log_file) # By default, Debugger::EnableLog() will set log options to @@ -43,14 +40,11 @@ self.assertTrue(os.path.isfile(self.log_file)) - with open(self.log_file, 'r') as f: + with open(self.log_file, "r") as f: log_lines = f.read() os.remove(self.log_file) - self.assertGreater( - len(log_lines), - 0, - "Something was written to the log file.") + self.assertGreater(len(log_lines), 0, "Something was written to the log file.") # Check that lldb truncates its log files def test_log_truncate(self): @@ -76,12 +70,12 @@ with open(self.log_file, "w") as f: f.write("bacon\n") - self.runCmd( "log enable -a -f '%s' lldb commands" % self.log_file) + self.runCmd("log enable -a -f '%s' lldb commands" % self.log_file) self.runCmd("help log") self.runCmd("log disable lldb") self.assertTrue(os.path.isfile(self.log_file)) - with open(self.log_file, 'r') as f: + with open(self.log_file, "r") as f: contents = f.read() # check that it is still there @@ -90,10 +84,12 @@ # Enable all log options and check that nothing crashes. @skipIfWindows def test_all_log_options(self): - if (os.path.exists(self.log_file)): + if os.path.exists(self.log_file): os.remove(self.log_file) - self.runCmd("log enable -v -s -T -p -n -S -F -f '%s' lldb commands" % self.log_file) + self.runCmd( + "log enable -v -s -T -p -n -S -F -f '%s' lldb commands" % self.log_file + ) self.runCmd("help log") self.runCmd("log disable lldb") diff --git a/lldb/test/API/commands/log/invalid-args/TestInvalidArgsLog.py b/lldb/test/API/commands/log/invalid-args/TestInvalidArgsLog.py --- a/lldb/test/API/commands/log/invalid-args/TestInvalidArgsLog.py +++ b/lldb/test/API/commands/log/invalid-args/TestInvalidArgsLog.py @@ -2,20 +2,33 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * -class InvalidArgsLogTestCase(TestBase): +class InvalidArgsLogTestCase(TestBase): @no_debug_info_test def test_enable_empty(self): - self.expect("log enable", error=True, - substrs=["error: log enable takes a log channel and one or more log types."]) + self.expect( + "log enable", + error=True, + substrs=[ + "error: log enable takes a log channel and one or more log types." + ], + ) @no_debug_info_test def test_disable_empty(self): - self.expect("log disable", error=True, - substrs=["error: log disable takes a log channel and one or more log types."]) + self.expect( + "log disable", + error=True, + substrs=[ + "error: log disable takes a log channel and one or more log types." + ], + ) @no_debug_info_test def test_enable_empty(self): invalid_path = os.path.join("this", "is", "not", "a", "valid", "path") - self.expect("log enable lldb all -f " + invalid_path, error=True, - substrs=["Unable to open log file '" + invalid_path + "': ", "\n"]) + self.expect( + "log enable lldb all -f " + invalid_path, + error=True, + substrs=["Unable to open log file '" + invalid_path + "': ", "\n"], + ) diff --git a/lldb/test/API/commands/memory/read/TestMemoryRead.py b/lldb/test/API/commands/memory/read/TestMemoryRead.py --- a/lldb/test/API/commands/memory/read/TestMemoryRead.py +++ b/lldb/test/API/commands/memory/read/TestMemoryRead.py @@ -14,29 +14,32 @@ def build_run_stop(self): self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", - lldb.SBFileSpec("main.c")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.c") + ) def test_memory_read_c_string(self): """Test that reading memory as a c string respects the size limit given - and warns if the null terminator is missing.""" + and warns if the null terminator is missing.""" self.build_run_stop() # The size here is the size in memory so it includes the null terminator. - cmd = "memory read --format \"c-string\" --size {} &my_string" + cmd = 'memory read --format "c-string" --size {} &my_string' # Size matches the size of the array. - self.expect(cmd.format(8), substrs=['\"abcdefg\"']) + self.expect(cmd.format(8), substrs=['"abcdefg"']) # If size would take us past the terminator we stop at the terminator. - self.expect(cmd.format(10), substrs=['\"abcdefg\"']) + self.expect(cmd.format(10), substrs=['"abcdefg"']) # Size 3 means 2 chars and a terminator. So we print 2 chars but warn because # the third isn't 0 as expected. - self.expect(cmd.format(3), substrs=['\"ab\"']) - self.assertRegex(self.res.GetError(), + self.expect(cmd.format(3), substrs=['"ab"']) + self.assertRegex( + self.res.GetError(), "unable to find a NULL terminated string at 0x[0-9A-Fa-f]+." - " Consider increasing the maximum read length.") + " Consider increasing the maximum read length.", + ) def test_memory_read(self): """Test the 'memory read' command with plain and vector formats.""" @@ -50,7 +53,7 @@ # '--format uint32_t[] --size 4 --count 4' option increments the address # correctly. line = self.res.GetOutput().splitlines()[0] - items = line.split(':') + items = line.split(":") address = int(items[0], 0) argc = int(items[1], 0) self.assertGreater(address, 0) @@ -61,15 +64,13 @@ # 0x7fff5fbff9a4: {0x00000000} # 0x7fff5fbff9a8: {0x0ec0bf27} # 0x7fff5fbff9ac: {0x215db505} - self.runCmd( - "memory read --format uint32_t[] --size 4 --count 4 `&argc`") + self.runCmd("memory read --format uint32_t[] --size 4 --count 4 `&argc`") lines = self.res.GetOutput().splitlines() for i in range(4): if i == 0: # Verify that the printout for argc is correct. - self.assertEqual( - argc, int(lines[i].split(':')[1].strip(' {}'), 0)) - addr = int(lines[i].split(':')[0], 0) + self.assertEqual(argc, int(lines[i].split(":")[1].strip(" {}"), 0)) + addr = int(lines[i].split(":")[0], 0) # Verify that the printout for addr is incremented correctly. self.assertEqual(addr, (address + i * 4)) @@ -77,61 +78,59 @@ # 0x7fff5fbff990: {abcdefg} self.expect( "memory read --format char[] --size 7 --count 1 `&my_string`", - substrs=['abcdefg']) + substrs=["abcdefg"], + ) # (lldb) memory read --format 'hex float' --size 16 `&argc` # 0x7fff5fbff5b0: error: unsupported byte size (16) for hex float # format self.expect( "memory read --format 'hex float' --size 16 `&argc`", - substrs=['unsupported byte size (16) for hex float format']) + substrs=["unsupported byte size (16) for hex float format"], + ) self.expect( "memory read --format 'float' --count 1 --size 8 `&my_double`", - substrs=['1234.']) + substrs=["1234."], + ) # (lldb) memory read --format 'float' --count 1 --size 20 `&my_double` # 0x7fff5fbff598: error: unsupported byte size (20) for float format self.expect( "memory read --format 'float' --count 1 --size 20 `&my_double`", - substrs=['unsupported byte size (20) for float format']) + substrs=["unsupported byte size (20) for float format"], + ) - self.expect('memory read --type int --count 5 `&my_ints[0]`', - substrs=['(int) 0x', '2', '4', '6', '8', '10']) + self.expect( + "memory read --type int --count 5 `&my_ints[0]`", + substrs=["(int) 0x", "2", "4", "6", "8", "10"], + ) self.expect( - 'memory read --type int --count 5 --format hex `&my_ints[0]`', - substrs=[ - '(int) 0x', - '0x', - '0a']) + "memory read --type int --count 5 --format hex `&my_ints[0]`", + substrs=["(int) 0x", "0x", "0a"], + ) self.expect( - 'memory read --type int --count 5 --offset 5 `&my_ints[0]`', - substrs=[ - '(int) 0x', - '12', - '14', - '16', - '18', - '20']) + "memory read --type int --count 5 --offset 5 `&my_ints[0]`", + substrs=["(int) 0x", "12", "14", "16", "18", "20"], + ) # the gdb format specifier and the size in characters for # the returned values including the 0x prefix. - variations = [['b', 4], ['h', 6], ['w', 10], ['g', 18]] + variations = [["b", 4], ["h", 6], ["w", 10], ["g", 18]] for v in variations: - formatter = v[0] - expected_object_length = v[1] - self.runCmd( - "memory read --gdb-format 4%s &my_uint64s" % formatter) - lines = self.res.GetOutput().splitlines() - objects_read = [] - for l in lines: - objects_read.extend(l.split(':')[1].split()) - # Check that we got back 4 0x0000 etc bytes - for o in objects_read: - self.assertEqual(len(o), expected_object_length) - self.assertEquals(len(objects_read), 4) + formatter = v[0] + expected_object_length = v[1] + self.runCmd("memory read --gdb-format 4%s &my_uint64s" % formatter) + lines = self.res.GetOutput().splitlines() + objects_read = [] + for l in lines: + objects_read.extend(l.split(":")[1].split()) + # Check that we got back 4 0x0000 etc bytes + for o in objects_read: + self.assertEqual(len(o), expected_object_length) + self.assertEquals(len(objects_read), 4) def test_memory_read_file(self): self.build_run_stop() @@ -156,7 +155,7 @@ check_file_content([golden_output]) # Write some garbage to the file. - with open(memory_read_file, 'w') as f: + with open(memory_read_file, "w") as f: f.write("some garbage") # Make sure the file is truncated when we run the command again. @@ -166,5 +165,7 @@ # Make sure the file is appended when we run the command with --append-outfile. self.runCmd( "memory read -f d -c 1 -o '{}' --append-outfile `&argc`".format( - memory_read_file)) + memory_read_file + ) + ) check_file_content([golden_output, golden_output]) diff --git a/lldb/test/API/commands/memory/write/TestMemoryWrite.py b/lldb/test/API/commands/memory/write/TestMemoryWrite.py --- a/lldb/test/API/commands/memory/write/TestMemoryWrite.py +++ b/lldb/test/API/commands/memory/write/TestMemoryWrite.py @@ -10,12 +10,11 @@ class MemoryWriteTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.line = line_number('main.c', '// Set break point at this line.') + self.line = line_number("main.c", "// Set break point at this line.") def build_run_stop(self): self.build() @@ -23,21 +22,21 @@ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break in main() after the variables are assigned values. - lldbutil.run_break_set_by_file_and_line(self, - "main.c", - self.line, - num_expected_locations=1, - loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", - STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # The breakpoint should have a hit count of 1. - lldbutil.check_breakpoint(self, bpno = 1, expected_hit_count = 1) + lldbutil.check_breakpoint(self, bpno=1, expected_hit_count=1) @no_debug_info_test def test_memory_write(self): @@ -46,30 +45,41 @@ self.expect( "memory read --format c --size 7 --count 1 `&my_string`", - substrs=['abcdefg']) + substrs=["abcdefg"], + ) - self.expect( - "memory write --format c --size 7 `&my_string` ABCDEFG") + self.expect("memory write --format c --size 7 `&my_string` ABCDEFG") self.expect( "memory read --format c --size 7 --count 1 `&my_string`", - substrs=['ABCDEFG']) + substrs=["ABCDEFG"], + ) self.expect( "memory write --infile file.txt --size 7 `&my_string`", - substrs=['7 bytes were written']) + substrs=["7 bytes were written"], + ) self.expect( "memory read --format c --size 7 --count 1 `&my_string`", - substrs=['abcdefg']) + substrs=["abcdefg"], + ) self.expect( - "memory write --infile file.txt --size 7 `&my_string` ABCDEFG", error=True, - substrs=['error: memory write takes only a destination address when writing file contents']) + "memory write --infile file.txt --size 7 `&my_string` ABCDEFG", + error=True, + substrs=[ + "error: memory write takes only a destination address when writing file contents" + ], + ) self.expect( - "memory write --infile file.txt --size 7", error=True, - substrs=['error: memory write takes a destination address when writing file contents']) + "memory write --infile file.txt --size 7", + error=True, + substrs=[ + "error: memory write takes a destination address when writing file contents" + ], + ) @no_debug_info_test def test_memory_write_command_usage_syntax(self): @@ -78,4 +88,6 @@ "help memory write", substrs=[ "memory write [-f ] [-s ]
[ [...]]", - "memory write -i [-s ] [-o ]
"]) + "memory write -i [-s ] [-o ]
", + ], + ) diff --git a/lldb/test/API/commands/platform/basic/TestPlatformCommand.py b/lldb/test/API/commands/platform/basic/TestPlatformCommand.py --- a/lldb/test/API/commands/platform/basic/TestPlatformCommand.py +++ b/lldb/test/API/commands/platform/basic/TestPlatformCommand.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -19,86 +18,90 @@ @no_debug_info_test def test_help_shell_alias(self): - self.expect("help shell", substrs=["Run a shell command on the host.", - "shell ", - "'shell' is an abbreviation"]) + self.expect( + "help shell", + substrs=[ + "Run a shell command on the host.", + "shell ", + "'shell' is an abbreviation", + ], + ) # "platform shell" has options. The "shell" alias for it does not. self.expect("help shell", substrs=["Command Options:"], matching=False) @no_debug_info_test def test_list(self): - self.expect("platform list", - patterns=['^Available platforms:']) + self.expect("platform list", patterns=["^Available platforms:"]) @no_debug_info_test def test_process_list(self): - self.expect("platform process list", - substrs=['PID', 'TRIPLE', 'NAME']) + self.expect("platform process list", substrs=["PID", "TRIPLE", "NAME"]) @no_debug_info_test def test_process_info_with_no_arg(self): """This is expected to fail and to return a proper error message.""" - self.expect("platform process info", error=True, - substrs=['one or more process id(s) must be specified']) + self.expect( + "platform process info", + error=True, + substrs=["one or more process id(s) must be specified"], + ) @no_debug_info_test def test_status(self): self.expect( "platform status", substrs=[ - 'Platform', - 'Triple', - 'OS Version', - 'Hostname', - 'Kernel', - ]) + "Platform", + "Triple", + "OS Version", + "Hostname", + "Kernel", + ], + ) @expectedFailureAll(oslist=["windows"]) @no_debug_info_test def test_shell(self): - """ Test that the platform shell command can invoke ls. """ + """Test that the platform shell command can invoke ls.""" triple = self.dbg.GetSelectedPlatform().GetTriple() if re.match(".*-.*-windows", triple): - self.expect( - "platform shell dir c:\\", substrs=[ - "Windows", "Program Files"]) + self.expect("platform shell dir c:\\", substrs=["Windows", "Program Files"]) self.expect("shell dir c:\\", substrs=["Windows", "Program Files"]) elif re.match(".*-.*-.*-android", triple): - self.expect( - "platform shell ls /", - substrs=[ - "cache", - "dev", - "system"]) - self.expect("shell ls /", - substrs=["cache", "dev", "system"]) + self.expect("platform shell ls /", substrs=["cache", "dev", "system"]) + self.expect("shell ls /", substrs=["cache", "dev", "system"]) else: self.expect("platform shell ls /", substrs=["dev", "tmp", "usr"]) self.expect("shell ls /", substrs=["dev", "tmp", "usr"]) @no_debug_info_test def test_shell_builtin(self): - """ Test a shell built-in command (echo) """ - self.expect("platform shell echo hello lldb", - substrs=["hello lldb"]) - self.expect("shell echo hello lldb", - substrs=["hello lldb"]) - + """Test a shell built-in command (echo)""" + self.expect("platform shell echo hello lldb", substrs=["hello lldb"]) + self.expect("shell echo hello lldb", substrs=["hello lldb"]) @no_debug_info_test def test_shell_timeout(self): - """ Test a shell built-in command (sleep) that times out """ + """Test a shell built-in command (sleep) that times out""" self.skipTest("Alias with option not supported by the command interpreter.") - self.expect("platform shell -t 1 -- sleep 15", error=True, substrs=[ - "error: timed out waiting for shell command to complete"]) - self.expect("shell -t 1 -- sleep 3", error=True, substrs=[ - "error: timed out waiting for shell command to complete"]) + self.expect( + "platform shell -t 1 -- sleep 15", + error=True, + substrs=["error: timed out waiting for shell command to complete"], + ) + self.expect( + "shell -t 1 -- sleep 3", + error=True, + substrs=["error: timed out waiting for shell command to complete"], + ) @no_debug_info_test @skipIfRemote def test_host_shell_interpreter(self): - """ Test the host platform shell with a different interpreter """ + """Test the host platform shell with a different interpreter""" self.build() - exe = self.getBuildArtifact('a.out') - self.expect("platform shell -h -s " + exe + " -- 'echo $0'", - substrs=['SUCCESS', 'a.out']) + exe = self.getBuildArtifact("a.out") + self.expect( + "platform shell -h -s " + exe + " -- 'echo $0'", + substrs=["SUCCESS", "a.out"], + ) diff --git a/lldb/test/API/commands/platform/basic/TestPlatformPython.py b/lldb/test/API/commands/platform/basic/TestPlatformPython.py --- a/lldb/test/API/commands/platform/basic/TestPlatformPython.py +++ b/lldb/test/API/commands/platform/basic/TestPlatformPython.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,8 +10,7 @@ class PlatformPythonTestCase(TestBase): - - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) @no_debug_info_test def test_platform_list(self): """Test SBDebugger::GetNumPlatforms() & GetPlatformAtIndex() API""" @@ -20,17 +18,18 @@ initial_num_platforms = self.dbg.GetNumPlatforms() self.assertGreater(initial_num_platforms, 0) host_platform = self.dbg.GetPlatformAtIndex(0) - self.assertTrue(host_platform.IsValid() and - host_platform.GetName() == 'host', - 'The host platform is present') + self.assertTrue( + host_platform.IsValid() and host_platform.GetName() == "host", + "The host platform is present", + ) # Select another platform and verify that the platform is added to # the platform list. platform_idx = self.dbg.GetNumAvailablePlatforms() - 1 if platform_idx < 1: - self.fail('No platforms other than host are available') + self.fail("No platforms other than host are available") platform_data = self.dbg.GetAvailablePlatformInfoAtIndex(platform_idx) - platform_name = platform_data.GetValueForKey('name').GetStringValue(100) - self.assertNotEqual(platform_name, 'host') + platform_name = platform_data.GetValueForKey("name").GetStringValue(100) + self.assertNotEqual(platform_name, "host") self.dbg.SetCurrentPlatform(platform_name) selected_platform = self.dbg.GetSelectedPlatform() self.assertTrue(selected_platform.IsValid()) @@ -44,54 +43,57 @@ break self.assertTrue(platform_found) - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) @no_debug_info_test def test_host_is_connected(self): # We've already tested that this one IS the host platform. host_platform = self.dbg.GetPlatformAtIndex(0) - self.assertTrue(host_platform.IsConnected(), "The host platform is always connected") + self.assertTrue( + host_platform.IsConnected(), "The host platform is always connected" + ) - - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) @no_debug_info_test def test_available_platform_list(self): """Test SBDebugger::GetNumAvailablePlatforms() and GetAvailablePlatformInfoAtIndex() API""" num_platforms = self.dbg.GetNumAvailablePlatforms() self.assertGreater( - num_platforms, 0, - 'There should be at least one platform available') + num_platforms, 0, "There should be at least one platform available" + ) for i in range(num_platforms): platform_data = self.dbg.GetAvailablePlatformInfoAtIndex(i) - name_data = platform_data.GetValueForKey('name') - desc_data = platform_data.GetValueForKey('description') - self.assertTrue( - name_data and name_data.IsValid(), - 'Platform has a name') + name_data = platform_data.GetValueForKey("name") + desc_data = platform_data.GetValueForKey("description") + self.assertTrue(name_data and name_data.IsValid(), "Platform has a name") self.assertEqual( - name_data.GetType(), lldb.eStructuredDataTypeString, - 'Platform name is a string') + name_data.GetType(), + lldb.eStructuredDataTypeString, + "Platform name is a string", + ) self.assertTrue( - desc_data and desc_data.IsValid(), - 'Platform has a description') + desc_data and desc_data.IsValid(), "Platform has a description" + ) self.assertEqual( - desc_data.GetType(), lldb.eStructuredDataTypeString, - 'Platform description is a string') + desc_data.GetType(), + lldb.eStructuredDataTypeString, + "Platform description is a string", + ) - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) @no_debug_info_test @skipIfRemote def test_shell_interpreter(self): - """ Test a shell with a custom interpreter """ + """Test a shell with a custom interpreter""" platform = self.dbg.GetSelectedPlatform() self.assertTrue(platform.IsValid()) - sh_cmd = lldb.SBPlatformShellCommand('/bin/zsh', 'echo $0') - self.assertIn('/bin/zsh', sh_cmd.GetShell()) - self.assertIn('echo $0', sh_cmd.GetCommand()) + sh_cmd = lldb.SBPlatformShellCommand("/bin/zsh", "echo $0") + self.assertIn("/bin/zsh", sh_cmd.GetShell()) + self.assertIn("echo $0", sh_cmd.GetCommand()) self.build() - sh_cmd.SetShell(self.getBuildArtifact('a.out')) + sh_cmd.SetShell(self.getBuildArtifact("a.out")) err = platform.Run(sh_cmd) self.assertSuccess(err) self.assertIn("SUCCESS", sh_cmd.GetOutput()) diff --git a/lldb/test/API/commands/platform/connect/TestPlatformConnect.py b/lldb/test/API/commands/platform/connect/TestPlatformConnect.py --- a/lldb/test/API/commands/platform/connect/TestPlatformConnect.py +++ b/lldb/test/API/commands/platform/connect/TestPlatformConnect.py @@ -5,19 +5,20 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestPlatformProcessConnect(TestBase): NO_DEBUG_INFO_TESTCASE = True @skipIfRemote - @expectedFailureAll(hostoslist=["windows"], triple='.*-android') - @skipIfDarwin # lldb-server not found correctly - @expectedFailureAll(oslist=["windows"]) # process modules not loaded + @expectedFailureAll(hostoslist=["windows"], triple=".*-android") + @skipIfDarwin # lldb-server not found correctly + @expectedFailureAll(oslist=["windows"]) # process modules not loaded @add_test_categories(["lldb-server"]) def test_platform_process_connect(self): self.build() hostname = socket.getaddrinfo("localhost", 0, proto=socket.IPPROTO_TCP)[0][4][0] - listen_url = "[%s]:0"%hostname + listen_url = "[%s]:0" % hostname port_file = self.getBuildArtifact("port") commandline_args = [ @@ -28,10 +29,9 @@ port_file, "--", self.getBuildArtifact("a.out"), - "foo"] - self.spawnSubprocess( - lldbgdbserverutils.get_lldb_server_exe(), - commandline_args) + "foo", + ] + self.spawnSubprocess(lldbgdbserverutils.get_lldb_server_exe(), commandline_args) socket_id = lldbutil.wait_for_file_on_target(self, port_file) diff --git a/lldb/test/API/commands/platform/file/close/TestPlatformFileClose.py b/lldb/test/API/commands/platform/file/close/TestPlatformFileClose.py --- a/lldb/test/API/commands/platform/file/close/TestPlatformFileClose.py +++ b/lldb/test/API/commands/platform/file/close/TestPlatformFileClose.py @@ -3,11 +3,17 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @no_debug_info_test def test_file_close_invalid_arg(self): - self.expect("platform file close y", error=True, - substrs=["'y' is not a valid file descriptor."]) - self.expect("platform file close -1", error=True, - substrs=["'-1' is not a valid file descriptor."]) + self.expect( + "platform file close y", + error=True, + substrs=["'y' is not a valid file descriptor."], + ) + self.expect( + "platform file close -1", + error=True, + substrs=["'-1' is not a valid file descriptor."], + ) diff --git a/lldb/test/API/commands/platform/file/read/TestPlatformFileRead.py b/lldb/test/API/commands/platform/file/read/TestPlatformFileRead.py --- a/lldb/test/API/commands/platform/file/read/TestPlatformFileRead.py +++ b/lldb/test/API/commands/platform/file/read/TestPlatformFileRead.py @@ -3,12 +3,16 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @no_debug_info_test def test_file_close_invalid_arg(self): - self.expect("platform file read y", error=True, - substrs=["'y' is not a valid file descriptor."]) + self.expect( + "platform file read y", + error=True, + substrs=["'y' is not a valid file descriptor."], + ) # 'file read' takes an option, so this will be treated as an option. - self.expect("platform file read -1", error=True, - substrs=["unknown or ambiguous option"]) + self.expect( + "platform file read -1", error=True, substrs=["unknown or ambiguous option"] + ) diff --git a/lldb/test/API/commands/platform/process/list/TestProcessList.py b/lldb/test/API/commands/platform/process/list/TestProcessList.py --- a/lldb/test/API/commands/platform/process/list/TestProcessList.py +++ b/lldb/test/API/commands/platform/process/list/TestProcessList.py @@ -12,19 +12,17 @@ class ProcessListTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True @skipIfWindows # https://bugs.llvm.org/show_bug.cgi?id=43702 - @skipIfRemote # rdar://problem/66542336 + @skipIfRemote # rdar://problem/66542336 def test_process_list_with_args(self): """Test process list show process args""" self.build() exe = self.getBuildArtifact("TestProcess") # Spawn a new process - sync_file = lldbutil.append_to_process_working_directory(self, - "ready.txt") + sync_file = lldbutil.append_to_process_working_directory(self, "ready.txt") popen = self.spawnSubprocess(exe, args=[sync_file, "arg1", "--arg2", "arg3"]) lldbutil.wait_for_file_on_target(self, sync_file) diff --git a/lldb/test/API/commands/platform/sdk/TestPlatformSDK.py b/lldb/test/API/commands/platform/sdk/TestPlatformSDK.py --- a/lldb/test/API/commands/platform/sdk/TestPlatformSDK.py +++ b/lldb/test/API/commands/platform/sdk/TestPlatformSDK.py @@ -28,13 +28,13 @@ def no_debugserver(self): if get_debugserver_exe() is None: - return 'no debugserver' + return "no debugserver" return None def port_not_available(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - if s.connect_ex(('127.0.0.1', self.PORT)) == 0: - return '{} not available'.format(self.PORT) + if s.connect_ex(("127.0.0.1", self.PORT)) == 0: + return "{} not available".format(self.PORT) return None @no_debug_info_test @@ -45,8 +45,8 @@ def test_macos_sdk(self): self.build() - exe = self.getBuildArtifact('a.out') - token = self.getBuildArtifact('token') + exe = self.getBuildArtifact("a.out") + token = self.getBuildArtifact("token") # Remove the old token. try: @@ -55,25 +55,31 @@ pass # Create a fake 'SDK' directory. - test_home = os.path.join(self.getBuildDir(), 'fake_home.noindex') + test_home = os.path.join(self.getBuildDir(), "fake_home.noindex") test_home = os.path.realpath(test_home) macos_version = platform.mac_ver()[0] - sdk_dir = os.path.join(test_home, 'Library', 'Developer', 'Xcode', - 'macOS DeviceSupport', macos_version) - symbols_dir = os.path.join(sdk_dir, 'Symbols') + sdk_dir = os.path.join( + test_home, + "Library", + "Developer", + "Xcode", + "macOS DeviceSupport", + macos_version, + ) + symbols_dir = os.path.join(sdk_dir, "Symbols") lldbutil.mkdir_p(symbols_dir) # Save the current home directory and restore it afterwards. - old_home = os.getenv('HOME') + old_home = os.getenv("HOME") def cleanup(): if not old_home: - del os.environ['HOME'] + del os.environ["HOME"] else: - os.environ['HOME'] = old_home + os.environ["HOME"] = old_home self.addTearDownHook(cleanup) - os.environ['HOME'] = test_home + os.environ["HOME"] = test_home # Launch our test binary. inferior = self.spawnSubprocess(exe, [token]) @@ -83,28 +89,25 @@ lldbutil.wait_for_file_on_target(self, token) # Move the binary into the 'SDK'. - rel_exe_path = os.path.relpath(os.path.realpath(exe), '/') + rel_exe_path = os.path.relpath(os.path.realpath(exe), "/") exe_sdk_path = os.path.join(symbols_dir, rel_exe_path) lldbutil.mkdir_p(os.path.dirname(exe_sdk_path)) shutil.move(exe, exe_sdk_path) # Attach to it with debugserver. debugserver = get_debugserver_exe() - debugserver_args = [ - 'localhost:{}'.format(self.PORT), '--attach={}'.format(pid) - ] + debugserver_args = ["localhost:{}".format(self.PORT), "--attach={}".format(pid)] self.spawnSubprocess(debugserver, debugserver_args) # Select the platform. - self.expect('platform select remote-macosx', substrs=[sdk_dir]) + self.expect("platform select remote-macosx", substrs=[sdk_dir]) # Connect to debugserver interpreter = self.dbg.GetCommandInterpreter() connected = False for i in range(self.ATTEMPTS): result = lldb.SBCommandReturnObject() - interpreter.HandleCommand('gdb-remote {}'.format(self.PORT), - result) + interpreter.HandleCommand("gdb-remote {}".format(self.PORT), result) connected = result.Succeeded() if connected: break @@ -113,4 +116,4 @@ self.assertTrue(connected, "could not connect to debugserver") # Make sure the image was loaded from the 'SDK'. - self.expect('image list', substrs=[exe_sdk_path]) + self.expect("image list", substrs=[exe_sdk_path]) diff --git a/lldb/test/API/commands/process/attach-resume/TestAttachResume.py b/lldb/test/API/commands/process/attach-resume/TestAttachResume.py --- a/lldb/test/API/commands/process/attach-resume/TestAttachResume.py +++ b/lldb/test/API/commands/process/attach-resume/TestAttachResume.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -17,7 +16,7 @@ @skipIfRemote @expectedFailureNetBSD - @skipIfWindows # llvm.org/pr24778, llvm.org/pr21753 + @skipIfWindows # llvm.org/pr24778, llvm.org/pr21753 def test_attach_continue_interrupt_detach(self): """Test attach/continue/interrupt/detach""" self.build() @@ -37,53 +36,41 @@ process = self.dbg.GetSelectedTarget().GetProcess() self.runCmd("c") - lldbutil.expect_state_changes( - self, listener, process, [ - lldb.eStateRunning]) + lldbutil.expect_state_changes(self, listener, process, [lldb.eStateRunning]) self.runCmd("process interrupt") - lldbutil.expect_state_changes( - self, listener, process, [ - lldb.eStateStopped]) + lldbutil.expect_state_changes(self, listener, process, [lldb.eStateStopped]) # be sure to continue/interrupt/continue (r204504) self.runCmd("c") - lldbutil.expect_state_changes( - self, listener, process, [ - lldb.eStateRunning]) + lldbutil.expect_state_changes(self, listener, process, [lldb.eStateRunning]) self.runCmd("process interrupt") - lldbutil.expect_state_changes( - self, listener, process, [ - lldb.eStateStopped]) + lldbutil.expect_state_changes(self, listener, process, [lldb.eStateStopped]) # Second interrupt should have no effect. self.expect( - "process interrupt", - patterns=["Process is not running"], - error=True) + "process interrupt", patterns=["Process is not running"], error=True + ) # check that this breakpoint is auto-cleared on detach (r204752) - self.runCmd("br set -f main.cpp -l %u" % - (line_number('main.cpp', '// Set breakpoint here'))) + self.runCmd( + "br set -f main.cpp -l %u" + % (line_number("main.cpp", "// Set breakpoint here")) + ) self.runCmd("c") lldbutil.expect_state_changes( - self, listener, process, [ - lldb.eStateRunning, lldb.eStateStopped]) - self.expect('br list', 'Breakpoint not hit', - substrs=['hit count = 1']) + self, listener, process, [lldb.eStateRunning, lldb.eStateStopped] + ) + self.expect("br list", "Breakpoint not hit", substrs=["hit count = 1"]) # Make sure the breakpoint is not hit again. self.expect("expr debugger_flag = false", substrs=[" = false"]) self.runCmd("c") - lldbutil.expect_state_changes( - self, listener, process, [ - lldb.eStateRunning]) + lldbutil.expect_state_changes(self, listener, process, [lldb.eStateRunning]) # make sure to detach while in running state (r204759) self.runCmd("detach") - lldbutil.expect_state_changes( - self, listener, process, [ - lldb.eStateDetached]) + lldbutil.expect_state_changes(self, listener, process, [lldb.eStateDetached]) diff --git a/lldb/test/API/commands/process/attach/TestProcessAttach.py b/lldb/test/API/commands/process/attach/TestProcessAttach.py --- a/lldb/test/API/commands/process/attach/TestProcessAttach.py +++ b/lldb/test/API/commands/process/attach/TestProcessAttach.py @@ -3,7 +3,6 @@ """ - import os import lldb import shutil @@ -15,15 +14,13 @@ class ProcessAttachTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.c. - self.line = line_number('main.cpp', - '// Waiting to be attached...') + self.line = line_number("main.cpp", "// Waiting to be attached...") @skipIfiOSSimulator def test_attach_to_process_by_id(self): @@ -58,7 +55,7 @@ self.assertTrue(process, PROCESS_IS_VALID) self.assertTrue(process.GetState(), lldb.eStateRunning) - @skipIfWindows # This is flakey on Windows AND when it fails, it hangs: llvm.org/pr48806 + @skipIfWindows # This is flakey on Windows AND when it fails, it hangs: llvm.org/pr48806 def test_attach_to_process_from_different_dir_by_id(self): """Test attach by process id""" newdir = self.getBuildArtifact("newdir") @@ -68,8 +65,8 @@ if e.errno != os.errno.EEXIST: raise testdir = self.getBuildDir() - exe = os.path.join(newdir, 'proc_attach') - self.buildProgram('main.cpp', exe) + exe = os.path.join(newdir, "proc_attach") + self.buildProgram("main.cpp", exe) self.addTearDownHook(lambda: shutil.rmtree(newdir)) # Spawn a new process @@ -99,7 +96,7 @@ process = target.GetProcess() self.assertTrue(process, PROCESS_IS_VALID) - @skipIfWindows # This test is flaky on Windows + @skipIfWindows # This test is flaky on Windows @expectedFailureNetBSD def test_attach_to_process_by_id_correct_executable_offset(self): """ @@ -119,7 +116,8 @@ # Make sure we did not attach too early. lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False + ) self.runCmd("process continue") self.expect("v g_val", substrs=["12345"]) diff --git a/lldb/test/API/commands/process/attach/attach_denied/TestAttachDenied.py b/lldb/test/API/commands/process/attach/attach_denied/TestAttachDenied.py --- a/lldb/test/API/commands/process/attach/attach_denied/TestAttachDenied.py +++ b/lldb/test/API/commands/process/attach/attach_denied/TestAttachDenied.py @@ -3,14 +3,13 @@ """ - import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -exe_name = 'AttachDenied' # Must match Makefile +exe_name = "AttachDenied" # Must match Makefile class AttachDeniedTestCase(TestBase): @@ -25,18 +24,18 @@ exe = self.getBuildArtifact(exe_name) # Use a file as a synchronization point between test and inferior. - pid_file_path = lldbutil.append_to_process_working_directory(self, - "pid_file_%d" % (int(time.time()))) + pid_file_path = lldbutil.append_to_process_working_directory( + self, "pid_file_%d" % (int(time.time())) + ) self.addTearDownHook( - lambda: self.run_platform_command( - "rm %s" % - (pid_file_path))) + lambda: self.run_platform_command("rm %s" % (pid_file_path)) + ) # Spawn a new process popen = self.spawnSubprocess(exe, [pid_file_path]) pid = lldbutil.wait_for_file_on_target(self, pid_file_path) - self.expect('process attach -p ' + pid, - startstr='error: attach failed:', - error=True) + self.expect( + "process attach -p " + pid, startstr="error: attach failed:", error=True + ) diff --git a/lldb/test/API/commands/process/continue_to_bkpt/TestContinueToBkpts.py b/lldb/test/API/commands/process/continue_to_bkpt/TestContinueToBkpts.py --- a/lldb/test/API/commands/process/continue_to_bkpt/TestContinueToBkpts.py +++ b/lldb/test/API/commands/process/continue_to_bkpt/TestContinueToBkpts.py @@ -10,10 +10,9 @@ class TestContinueToBkpts(TestBase): - NO_DEBUG_INFO_TESTCASE = True - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) def test_continue_to_breakpoints(self): """Test that the continue to breakpoints feature works correctly.""" self.build() @@ -24,49 +23,83 @@ TestBase.setUp(self) self.main_source_spec = lldb.SBFileSpec("main.c") - def continue_and_check(self, stop_list, bkpt_to_hit, loc_to_hit = 0): + def continue_and_check(self, stop_list, bkpt_to_hit, loc_to_hit=0): """Build up a command that will run a continue -b commands using the breakpoints on stop_list, and - ensure that we hit bkpt_to_hit. - If loc_to_hit is not 0, also verify that we hit that location.""" + ensure that we hit bkpt_to_hit. + If loc_to_hit is not 0, also verify that we hit that location.""" command = "process continue" for elem in stop_list: command += " -b {0}".format(elem) self.expect(command) - self.assertStopReason(self.thread.stop_reason, lldb.eStopReasonBreakpoint, "Hit a breakpoint") - self.assertEqual(self.thread.GetStopReasonDataAtIndex(0), bkpt_to_hit, "Hit the right breakpoint") + self.assertStopReason( + self.thread.stop_reason, lldb.eStopReasonBreakpoint, "Hit a breakpoint" + ) + self.assertEqual( + self.thread.GetStopReasonDataAtIndex(0), + bkpt_to_hit, + "Hit the right breakpoint", + ) if loc_to_hit != 0: - self.assertEqual(self.thread.GetStopReasonDataAtIndex(1), loc_to_hit, "Hit the right location") + self.assertEqual( + self.thread.GetStopReasonDataAtIndex(1), + loc_to_hit, + "Hit the right location", + ) for bkpt_id in self.bkpt_list: bkpt = self.target.FindBreakpointByID(bkpt_id) self.assertTrue(bkpt.IsValid(), "Breakpoint id's round trip") if bkpt.MatchesName("disabled"): - self.assertFalse(bkpt.IsEnabled(), "Disabled breakpoints stay disabled: {0}".format(bkpt.GetID())) + self.assertFalse( + bkpt.IsEnabled(), + "Disabled breakpoints stay disabled: {0}".format(bkpt.GetID()), + ) else: - self.assertTrue(bkpt.IsEnabled(), "Enabled breakpoints stay enabled: {0}".format(bkpt.GetID())) + self.assertTrue( + bkpt.IsEnabled(), + "Enabled breakpoints stay enabled: {0}".format(bkpt.GetID()), + ) # Also do our multiple location one: bkpt = self.target.FindBreakpointByID(self.multiple_loc_id) self.assertTrue(bkpt.IsValid(), "Breakpoint with locations round trip") - for i in range(1,3): + for i in range(1, 3): loc = bkpt.FindLocationByID(i) self.assertTrue(loc.IsValid(), "Locations round trip") if i == 2: - self.assertTrue(loc.IsEnabled(), "Locations that were enabled stay enabled") + self.assertTrue( + loc.IsEnabled(), "Locations that were enabled stay enabled" + ) else: - self.assertFalse(loc.IsEnabled(), "Locations that were disabled stay disabled") - + self.assertFalse( + loc.IsEnabled(), "Locations that were disabled stay disabled" + ) + def do_test_continue_to_breakpoint(self): """Test the continue to breakpoint feature.""" - (self.target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - "Stop here to get started", self.main_source_spec) + (self.target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Stop here to get started", self.main_source_spec + ) # Now set up all our breakpoints: bkpt_pattern = "This is the {0} stop" - bkpt_elements = ["zeroth", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "nineth"] + bkpt_elements = [ + "zeroth", + "first", + "second", + "third", + "fourth", + "fifth", + "sixth", + "seventh", + "eighth", + "nineth", + ] disabled_bkpts = ["first", "eigth"] bkpts_for_MyBKPT = ["first", "sixth", "nineth"] self.bkpt_list = [] for elem in bkpt_elements: - bkpt = self.target.BreakpointCreateBySourceRegex(bkpt_pattern.format(elem), self.main_source_spec) + bkpt = self.target.BreakpointCreateBySourceRegex( + bkpt_pattern.format(elem), self.main_source_spec + ) self.assertGreater(bkpt.GetNumLocations(), 0, "Found a bkpt match") self.bkpt_list.append(bkpt.GetID()) bkpt.AddName(elem) @@ -76,11 +109,13 @@ if elem in bkpts_for_MyBKPT: bkpt.AddName("MyBKPT") # Also make one that has several locations, so we can test locations: - mult_bkpt = self.target.BreakpointCreateBySourceRegex(bkpt_pattern.format("(seventh|eighth|nineth)"), self.main_source_spec) + mult_bkpt = self.target.BreakpointCreateBySourceRegex( + bkpt_pattern.format("(seventh|eighth|nineth)"), self.main_source_spec + ) self.assertEqual(mult_bkpt.GetNumLocations(), 3, "Got three matches") mult_bkpt.AddName("Locations") # Disable all of these: - for i in range(1,4): + for i in range(1, 4): loc = mult_bkpt.FindLocationByID(i) self.assertTrue(loc.IsValid(), "Location {0} is valid".format(i)) loc.SetEnabled(False) @@ -90,20 +125,52 @@ # First test out various error conditions # All locations of the multiple_loc_id are disabled, so running to this should be an error: - self.expect("process continue -b {0}".format(self.multiple_loc_id), error=True, msg="Running to a disabled breakpoint by number") + self.expect( + "process continue -b {0}".format(self.multiple_loc_id), + error=True, + msg="Running to a disabled breakpoint by number", + ) # Now re-enable the middle one so we can run to it: loc = mult_bkpt.FindLocationByID(2) loc.SetEnabled(True) - self.expect("process continue -b {0}".format(self.bkpt_list[1]), error=True, msg="Running to a disabled breakpoint by number") - self.expect("process continue -b {0}.1".format(self.bkpt_list[1]), error=True, msg="Running to a location of a disabled breakpoint") - self.expect("process continue -b disabled", error=True, msg="Running to a disabled set of breakpoints") - self.expect("process continue -b {0}.{1}".format(self.multiple_loc_id, 1), error=True, msg="Running to a disabled breakpoint location") - self.expect("process continue -b {0}".format("THERE_ARE_NO_BREAKPOINTS_BY_THIS_NAME"), error=True, msg="Running to no such name") - self.expect("process continue -b {0}".format(1000), error=True, msg="Running to no such breakpoint") - self.expect("process continue -b {0}.{1}".format(self.multiple_loc_id, 1000), error=True, msg="Running to no such location") - + self.expect( + "process continue -b {0}".format(self.bkpt_list[1]), + error=True, + msg="Running to a disabled breakpoint by number", + ) + self.expect( + "process continue -b {0}.1".format(self.bkpt_list[1]), + error=True, + msg="Running to a location of a disabled breakpoint", + ) + self.expect( + "process continue -b disabled", + error=True, + msg="Running to a disabled set of breakpoints", + ) + self.expect( + "process continue -b {0}.{1}".format(self.multiple_loc_id, 1), + error=True, + msg="Running to a disabled breakpoint location", + ) + self.expect( + "process continue -b {0}".format("THERE_ARE_NO_BREAKPOINTS_BY_THIS_NAME"), + error=True, + msg="Running to no such name", + ) + self.expect( + "process continue -b {0}".format(1000), + error=True, + msg="Running to no such breakpoint", + ) + self.expect( + "process continue -b {0}.{1}".format(self.multiple_loc_id, 1000), + error=True, + msg="Running to no such location", + ) + # Now move forward, this time with breakpoint numbers. First time we don't skip other bkpts. bkpt = self.bkpt_list[0] self.continue_and_check([str(bkpt)], bkpt) @@ -117,7 +184,7 @@ after_value = self.dbg.GetAsync() self.dbg.SetAsync(orig_async) self.assertTrue(after_value, "Preserve async as True if it started that way") - + # Now try a name that has several breakpoints. # This time I'm also going to check that we put the debugger async mode back if # if was False to begin with: @@ -128,4 +195,6 @@ self.assertFalse(after_value, "Preserve async as False if it started that way") # Now let's run to a particular location. Also specify a breakpoint we've already hit: - self.continue_and_check([self.bkpt_list[0], self.multiple_loc_id], self.multiple_loc_id, 2) + self.continue_and_check( + [self.bkpt_list[0], self.multiple_loc_id], self.multiple_loc_id, 2 + ) diff --git a/lldb/test/API/commands/process/handle/TestProcessHandle.py b/lldb/test/API/commands/process/handle/TestProcessHandle.py --- a/lldb/test/API/commands/process/handle/TestProcessHandle.py +++ b/lldb/test/API/commands/process/handle/TestProcessHandle.py @@ -3,42 +3,52 @@ from lldbsuite.test import lldbutil from lldbsuite.test.decorators import * -class TestProcessHandle(TestBase): +class TestProcessHandle(TestBase): @no_debug_info_test @skipIfWindows def test_process_handle(self): """Test that calling process handle before we have a target, and before we - have a process will affect the process. Also that the signal settings - are preserved on rerun.""" + have a process will affect the process. Also that the signal settings + are preserved on rerun.""" self.build() # Make sure we don't accept signal values by signo with no process - we don't know what the # mapping will be so we can't do the right thing with bare numbers: - lldbutil.set_actions_for_signal(self, "9", "true", None, None, expect_success=False) + lldbutil.set_actions_for_signal( + self, "9", "true", None, None, expect_success=False + ) # First, I need a reference value so I can see whether changes actually took: - (target, process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', lldb.SBFileSpec("main.cpp")) - (default_pass, default_stop, default_notify) = lldbutil.get_actions_for_signal(self, "SIGSEGV") - + (target, process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) + (default_pass, default_stop, default_notify) = lldbutil.get_actions_for_signal( + self, "SIGSEGV" + ) + # Let's change the value here, then exit and make sure the changed value sticks: new_value = "false" if default_pass == "true": new_value = "false" # First make sure we get an error for bogus values when running: - lldbutil.set_actions_for_signal(self, "NOTSIGSEGV", new_value, None, None, expect_success=False) + lldbutil.set_actions_for_signal( + self, "NOTSIGSEGV", new_value, None, None, expect_success=False + ) # Then set the one we intend to change. lldbutil.set_actions_for_signal(self, "SIGSEGV", new_value, None, None) process.Continue() - + self.assertState(process.GetState(), lldb.eStateExited) self.assertEqual(process.GetExitStatus(), 0) - + # Check that we preserved the setting: - (curr_pass, curr_stop, curr_notify) = lldbutil.get_actions_for_signal(self, "SIGSEGV",from_target=True) + (curr_pass, curr_stop, curr_notify) = lldbutil.get_actions_for_signal( + self, "SIGSEGV", from_target=True + ) self.assertEqual(curr_pass, new_value, "Pass was set correctly") self.assertEqual(curr_stop, "not set", "Stop was not set by us") self.assertEqual(curr_notify, "not set", "Notify was not set by us") @@ -47,7 +57,9 @@ process = lldbutil.run_to_breakpoint_do_run(self, target, bkpt) # We check the process settings now, to see what got copied into the process: - (curr_pass, curr_stop, curr_notify) = lldbutil.get_actions_for_signal(self, "SIGSEGV") + (curr_pass, curr_stop, curr_notify) = lldbutil.get_actions_for_signal( + self, "SIGSEGV" + ) self.assertEqual(curr_pass, new_value, "Pass was set correctly") self.assertEqual(curr_stop, default_stop, "Stop was its default value") self.assertEqual(curr_notify, default_notify, "Notify was its default value") @@ -58,17 +70,19 @@ self.assertEqual(self.dbg.GetNumTargets(), 0, "We did delete all the targets.") # The signal settings should be back at their default - we were only setting this on the target: - lldbutil.get_actions_for_signal(self, "SIGSEGV", from_target=True, expected_absent=True) + lldbutil.get_actions_for_signal( + self, "SIGSEGV", from_target=True, expected_absent=True + ) # Set a valid one: lldbutil.set_actions_for_signal(self, "SIGSEGV", new_value, None, None) # Set a bogus one - we don't have a way to check pre-run so this is allowed # but we should get an error message when launching: lldbutil.set_actions_for_signal(self, "SIGNOTSIG", new_value, None, None) - out_filename = self.getBuildArtifact('output') + out_filename = self.getBuildArtifact("output") success = True try: - f = open(out_filename, 'w') + f = open(out_filename, "w") except: success = False @@ -77,13 +91,15 @@ self.dbg.SetErrorFileHandle(f, False) # Now make a new process and make sure the right values got copied into the new target - (target, process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', lldb.SBFileSpec("main.cpp")) + (target, process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) f.write("TESTPATTERN\n") f.flush() f.close() try: - f = open(out_filename, 'r') + f = open(out_filename, "r") except: success = False @@ -91,20 +107,26 @@ self.fail("Couldn't open error output file for reading") errors = f.read() f.close() - + self.assertIn("SIGNOTSIG", errors, "We warned about the unset signal") # Also make sure we didn't accidentally add this bogus setting to the process. - lldbutil.set_actions_for_signal(self, "SIGNOTSIG", "true", "true", "true", expect_success=False) - + lldbutil.set_actions_for_signal( + self, "SIGNOTSIG", "true", "true", "true", expect_success=False + ) + # Check that they went into the target: - (curr_pass, curr_stop, curr_notify) = lldbutil.get_actions_for_signal(self, "SIGSEGV",from_target=True) + (curr_pass, curr_stop, curr_notify) = lldbutil.get_actions_for_signal( + self, "SIGSEGV", from_target=True + ) self.assertEqual(curr_pass, new_value, "Pass was set correctly") self.assertEqual(curr_stop, "not set", "Stop was not set by us") self.assertEqual(curr_notify, "not set", "Notify was not set by us") # And the process: # Check that they went into the target: - (curr_pass, curr_stop, curr_notify) = lldbutil.get_actions_for_signal(self, "SIGSEGV") + (curr_pass, curr_stop, curr_notify) = lldbutil.get_actions_for_signal( + self, "SIGSEGV" + ) self.assertEqual(curr_pass, new_value, "Pass was set correctly") self.assertEqual(curr_stop, default_stop, "Stop was its default value") self.assertEqual(curr_notify, default_notify, "Notify was its default value") @@ -112,10 +134,16 @@ # Now clear the handling, and make sure that we get the right signal values again: self.runCmd("process handle -c SIGSEGV") # Check that there is no longer configuration for SIGSEGV in the target: - lldbutil.get_actions_for_signal(self, "SIGSEGV",from_target=True, expected_absent=True) + lldbutil.get_actions_for_signal( + self, "SIGSEGV", from_target=True, expected_absent=True + ) # Make a new process, to make sure we did indeed reset the values: - (target, process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', lldb.SBFileSpec("main.cpp")) - (curr_pass, curr_stop, curr_notify) = lldbutil.get_actions_for_signal(self, "SIGSEGV") + (target, process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) + (curr_pass, curr_stop, curr_notify) = lldbutil.get_actions_for_signal( + self, "SIGSEGV" + ) self.assertEqual(curr_pass, new_value, "Pass was set correctly") self.assertEqual(curr_stop, default_stop, "Stop was its default value") self.assertEqual(curr_notify, default_notify, "Notify was its default value") @@ -126,9 +154,13 @@ self.assertSuccess(error, "Killed the process") success = self.dbg.DeleteTarget(target) self.assertTrue(success, "Destroyed the target.") - - (target, process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', lldb.SBFileSpec("main.cpp")) - (curr_pass, curr_stop, curr_notify) = lldbutil.get_actions_for_signal(self, "SIGSEGV") + + (target, process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) + (curr_pass, curr_stop, curr_notify) = lldbutil.get_actions_for_signal( + self, "SIGSEGV" + ) self.assertEqual(curr_pass, default_pass, "Pass was set correctly") self.assertEqual(curr_stop, default_stop, "Stop was its default value") self.assertEqual(curr_notify, default_notify, "Notify was its default value") diff --git a/lldb/test/API/commands/process/launch-with-shellexpand/TestLaunchWithShellExpand.py b/lldb/test/API/commands/process/launch-with-shellexpand/TestLaunchWithShellExpand.py --- a/lldb/test/API/commands/process/launch-with-shellexpand/TestLaunchWithShellExpand.py +++ b/lldb/test/API/commands/process/launch-with-shellexpand/TestLaunchWithShellExpand.py @@ -14,12 +14,10 @@ NO_DEBUG_INFO_TESTCASE = True @expectedFailureAll( - oslist=[ - "windows", - "linux", - "freebsd"], - bugnumber="llvm.org/pr24778 llvm.org/pr22627 llvm.org/pr48349") - @skipIfDarwinEmbedded # iOS etc don't launch the binary via a shell, so arg expansion won't happen + oslist=["windows", "linux", "freebsd"], + bugnumber="llvm.org/pr24778 llvm.org/pr22627 llvm.org/pr48349", + ) + @skipIfDarwinEmbedded # iOS etc don't launch the binary via a shell, so arg expansion won't happen @expectedFailureNetBSD def test(self): self.build() @@ -27,31 +25,36 @@ # Create any breakpoints we need breakpoint = target.BreakpointCreateBySourceRegex( - 'break here', lldb.SBFileSpec("main.cpp", False)) + "break here", lldb.SBFileSpec("main.cpp", False) + ) self.assertTrue(breakpoint, VALID_BREAKPOINT) # Ensure we do the expansion with /bin/sh on POSIX. - os.environ["SHELL"] = '/bin/sh' + os.environ["SHELL"] = "/bin/sh" self.runCmd( - "process launch -X true -w %s -- fi*.tx? () > <" % - (self.getSourceDir())) + "process launch -X true -w %s -- fi*.tx? () > <" % (self.getSourceDir()) + ) process = self.process() - self.assertState(process.GetState(), lldb.eStateStopped, - STOPPED_DUE_TO_BREAKPOINT) + self.assertState( + process.GetState(), lldb.eStateStopped, STOPPED_DUE_TO_BREAKPOINT + ) thread = process.GetThreadAtIndex(0) - self.assertTrue(thread.IsValid(), - "Process stopped at 'main' should have a valid thread") + self.assertTrue( + thread.IsValid(), "Process stopped at 'main' should have a valid thread" + ) stop_reason = thread.GetStopReason() self.assertEqual( - stop_reason, lldb.eStopReasonBreakpoint, - "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint") + stop_reason, + lldb.eStopReasonBreakpoint, + "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint", + ) self.expect_var_path("argv[1]", summary='"file1.txt"') self.expect_var_path("argv[2]", summary='"file2.txt"') @@ -60,51 +63,56 @@ self.expect_var_path("argv[5]", summary='"()"') self.expect_var_path("argv[6]", summary='">"') self.expect_var_path("argv[7]", summary='"<"') - self.expect_var_path("argc", value='8') + self.expect_var_path("argc", value="8") self.runCmd("process kill") - self.runCmd( - 'process launch -X true -w %s -- "foo bar"' % - (self.getSourceDir())) + self.runCmd('process launch -X true -w %s -- "foo bar"' % (self.getSourceDir())) process = self.process() - self.assertState(process.GetState(), lldb.eStateStopped, - STOPPED_DUE_TO_BREAKPOINT) + self.assertState( + process.GetState(), lldb.eStateStopped, STOPPED_DUE_TO_BREAKPOINT + ) thread = process.GetThreadAtIndex(0) - self.assertTrue(thread.IsValid(), - "Process stopped at 'main' should have a valid thread") + self.assertTrue( + thread.IsValid(), "Process stopped at 'main' should have a valid thread" + ) stop_reason = thread.GetStopReason() self.assertEqual( - stop_reason, lldb.eStopReasonBreakpoint, - "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint") + stop_reason, + lldb.eStopReasonBreakpoint, + "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint", + ) - self.expect("frame variable argv[1]", substrs=['foo bar']) + self.expect("frame variable argv[1]", substrs=["foo bar"]) self.runCmd("process kill") - self.runCmd('process launch -X true -w %s -- foo\ bar' - % (self.getBuildDir())) + self.runCmd("process launch -X true -w %s -- foo\ bar" % (self.getBuildDir())) process = self.process() - self.assertState(process.GetState(), lldb.eStateStopped, - STOPPED_DUE_TO_BREAKPOINT) + self.assertState( + process.GetState(), lldb.eStateStopped, STOPPED_DUE_TO_BREAKPOINT + ) thread = process.GetThreadAtIndex(0) - self.assertTrue(thread.IsValid(), - "Process stopped at 'main' should have a valid thread") + self.assertTrue( + thread.IsValid(), "Process stopped at 'main' should have a valid thread" + ) stop_reason = thread.GetStopReason() self.assertEqual( - stop_reason, lldb.eStopReasonBreakpoint, - "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint") + stop_reason, + lldb.eStopReasonBreakpoint, + "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint", + ) - self.expect("frame variable argv[1]", substrs=['foo bar']) + self.expect("frame variable argv[1]", substrs=["foo bar"]) diff --git a/lldb/test/API/commands/process/launch/TestProcessLaunch.py b/lldb/test/API/commands/process/launch/TestProcessLaunch.py --- a/lldb/test/API/commands/process/launch/TestProcessLaunch.py +++ b/lldb/test/API/commands/process/launch/TestProcessLaunch.py @@ -27,8 +27,7 @@ """Test that process launch I/O redirection flags work properly.""" self.build() exe = self.getBuildArtifact("a.out") - self.expect("file " + exe, - patterns=["Current executable set to .*a.out"]) + self.expect("file " + exe, patterns=["Current executable set to .*a.out"]) in_file = os.path.join(self.getSourceDir(), "input-file.txt") out_file = lldbutil.append_to_process_working_directory(self, "output-test.out") @@ -46,14 +45,17 @@ pass launch_command = "process launch -i '{0}' -o '{1}' -e '{2}' -w '{3}'".format( - in_file, out_file, err_file, self.get_process_working_directory()) + in_file, out_file, err_file, self.get_process_working_directory() + ) if lldb.remote_platform: - self.runCmd('platform put-file "{local}" "{remote}"'.format( - local=in_file, remote=in_file)) + self.runCmd( + 'platform put-file "{local}" "{remote}"'.format( + local=in_file, remote=in_file + ) + ) - self.expect(launch_command, - patterns=["Process .* launched: .*a.out"]) + self.expect(launch_command, patterns=["Process .* launched: .*a.out"]) success = True err_msg = "" @@ -61,13 +63,16 @@ out = lldbutil.read_file_on_target(self, out_file) if out != "This should go to stdout.\n": success = False - err_msg = err_msg + " ERROR: stdout file does not contain correct output.\n" - + err_msg = ( + err_msg + " ERROR: stdout file does not contain correct output.\n" + ) err = lldbutil.read_file_on_target(self, err_file) if err != "This should go to stderr.\n": success = False - err_msg = err_msg + " ERROR: stderr file does not contain correct output.\n" + err_msg = ( + err_msg + " ERROR: stderr file does not contain correct output.\n" + ) if not success: self.fail(err_msg) @@ -80,13 +85,13 @@ @expectedFailureNetBSD def test_set_working_dir_nonexisting(self): """Test that '-w dir' fails to set the working dir when running the inferior with a dir which doesn't exist.""" - d = {'CXX_SOURCES': 'print_cwd.cpp'} + d = {"CXX_SOURCES": "print_cwd.cpp"} self.build(dictionary=d) self.setTearDownCleanup(d) exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe) - mywd = 'my_working_dir' + mywd = "my_working_dir" out_file_name = "my_working_dir_test.out" err_file_name = "my_working_dir_test.err" @@ -95,25 +100,29 @@ err_file_path = os.path.join(my_working_dir_path, err_file_name) # Check that we get an error when we have a nonexisting path - invalid_dir_path = mywd + 'z' + invalid_dir_path = mywd + "z" launch_command = "process launch -w %s -o %s -e %s" % ( - invalid_dir_path, out_file_path, err_file_path) + invalid_dir_path, + out_file_path, + err_file_path, + ) self.expect( - launch_command, error=True, patterns=[ - "error:.* No such file or directory: %s" % - invalid_dir_path]) + launch_command, + error=True, + patterns=["error:.* No such file or directory: %s" % invalid_dir_path], + ) @skipIfRemote def test_set_working_dir_existing(self): """Test that '-w dir' sets the working dir when running the inferior.""" - d = {'CXX_SOURCES': 'print_cwd.cpp'} + d = {"CXX_SOURCES": "print_cwd.cpp"} self.build(dictionary=d) self.setTearDownCleanup(d) exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe) - mywd = 'my_working_dir' + mywd = "my_working_dir" out_file_name = "my_working_dir_test.out" err_file_name = "my_working_dir_test.err" @@ -130,10 +139,12 @@ pass launch_command = "process launch -w %s -o %s -e %s" % ( - my_working_dir_path, out_file_path, err_file_path) + my_working_dir_path, + out_file_path, + err_file_path, + ) - self.expect(launch_command, - patterns=["Process .* launched: .*a.out"]) + self.expect(launch_command, patterns=["Process .* launched: .*a.out"]) success = True err_msg = "" @@ -151,7 +162,9 @@ print("line:", line) if not re.search(mywd, line): success = False - err_msg = err_msg + "The current working directory was not set correctly.\n" + err_msg = ( + err_msg + "The current working directory was not set correctly.\n" + ) out_f.close() # Try to delete the 'stdout' and 'stderr' files @@ -166,28 +179,25 @@ def test_environment_with_special_char(self): """Test that environment variables containing '*' and '}' are handled correctly by the inferior.""" - source = 'print_env.cpp' - d = {'CXX_SOURCES': source} + source = "print_env.cpp" + d = {"CXX_SOURCES": source} self.build(dictionary=d) self.setTearDownCleanup(d) - evil_var = 'INIT*MIDDLE}TAIL' + evil_var = "INIT*MIDDLE}TAIL" target = self.createTestTarget() main_source_spec = lldb.SBFileSpec(source) breakpoint = target.BreakpointCreateBySourceRegex( - '// Set breakpoint here.', main_source_spec) - - process = target.LaunchSimple(None, - ['EVIL=' + evil_var], - self.get_process_working_directory()) - self.assertEqual( - process.GetState(), - lldb.eStateStopped, - PROCESS_STOPPED) - - threads = lldbutil.get_threads_stopped_at_breakpoint( - process, breakpoint) + "// Set breakpoint here.", main_source_spec + ) + + process = target.LaunchSimple( + None, ["EVIL=" + evil_var], self.get_process_working_directory() + ) + self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) + + threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint) self.assertEqual(len(threads), 1) frame = threads[0].GetFrameAtIndex(0) sbvalue = frame.EvaluateExpression("evil") diff --git a/lldb/test/API/commands/process/signal/TestProcessSignal.py b/lldb/test/API/commands/process/signal/TestProcessSignal.py --- a/lldb/test/API/commands/process/signal/TestProcessSignal.py +++ b/lldb/test/API/commands/process/signal/TestProcessSignal.py @@ -3,13 +3,27 @@ from lldbsuite.test import lldbutil from lldbsuite.test.decorators import * -class TestCase(TestBase): +class TestCase(TestBase): @no_debug_info_test def test_invalid_arg(self): self.build() - lldbutil.run_to_source_breakpoint(self, '// break here', lldb.SBFileSpec("main.cpp")) - self.expect("process signal az", error=True, startstr="error: Invalid signal argument 'az'.") - self.expect("process signal 0x1ffffffff", error=True, startstr="error: Invalid signal argument '0x1ffffffff'.") - self.expect("process signal 0xffffffff", error=True, startstr="error: Invalid signal argument '0xffffffff'.") + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) + self.expect( + "process signal az", + error=True, + startstr="error: Invalid signal argument 'az'.", + ) + self.expect( + "process signal 0x1ffffffff", + error=True, + startstr="error: Invalid signal argument '0x1ffffffff'.", + ) + self.expect( + "process signal 0xffffffff", + error=True, + startstr="error: Invalid signal argument '0xffffffff'.", + ) diff --git a/lldb/test/API/commands/quit/TestQuit.py b/lldb/test/API/commands/quit/TestQuit.py --- a/lldb/test/API/commands/quit/TestQuit.py +++ b/lldb/test/API/commands/quit/TestQuit.py @@ -10,15 +10,16 @@ class QuitCommandTestCase(TestBase): - @no_debug_info_test def test_quit_exit_code_disallow(self): self.ci.AllowExitCodeOnQuit(False) self.expect( "quit 20", substrs=[ - "error: The current driver doesn't allow custom exit codes for the quit command"], - error=True) + "error: The current driver doesn't allow custom exit codes for the quit command" + ], + error=True, + ) self.assertFalse(self.ci.HasCustomQuitExitCode()) @no_debug_info_test diff --git a/lldb/test/API/commands/register/register/TestRegistersUnavailable.py b/lldb/test/API/commands/register/register/TestRegistersUnavailable.py --- a/lldb/test/API/commands/register/register/TestRegistersUnavailable.py +++ b/lldb/test/API/commands/register/register/TestRegistersUnavailable.py @@ -7,6 +7,7 @@ from lldbsuite.test.gdbclientutils import * from lldbsuite.test.lldbgdbclient import GDBRemoteTestBase + class MyResponder(MockGDBServerResponder): def readRegisters(self): return "E01" @@ -20,34 +21,40 @@ # The triple is hex encoded ASCII "x86_64-linux-gnu". return "triple:7838365F36342D6C696E75782D676E75;" + class TestRegistersUnavailable(GDBRemoteTestBase): @skipIfRemote # So that we have multiple register sets. @skipIfLLVMTargetMissing("X86") def test_unavailable_registers(self): self.server.responder = MyResponder() - target = self.dbg.CreateTarget('') + target = self.dbg.CreateTarget("") if self.TraceOn(): self.runCmd("log enable gdb-remote packets process") self.addTearDownHook( - lambda: self.runCmd("log disable gdb-remote packets process")) + lambda: self.runCmd("log disable gdb-remote packets process") + ) process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) # We are using a long regex pattern here to check that the indentation # is correct when you have multiple register sets and they all have # some missing registers. - self.expect("register read --all", patterns=[ - "(?sm)^general purpose registers:\n" - "^\s+rdx = 0x5555555555555555\n" - ".*" - "^3 registers were unavailable.\n" - "\n" - "^supplementary registers:\n" - "^\s+edx = 0x55555555\n" - ".*" - "^12 registers were unavailable." - ]) + self.expect( + "register read --all", + patterns=[ + "(?sm)^general purpose registers:\n" + "^\s+rdx = 0x5555555555555555\n" + ".*" + "^3 registers were unavailable.\n" + "\n" + "^supplementary registers:\n" + "^\s+edx = 0x55555555\n" + ".*" + "^12 registers were unavailable." + ], + ) diff --git a/lldb/test/API/commands/register/register/aarch64_dynamic_regset/TestArm64DynamicRegsets.py b/lldb/test/API/commands/register/register/aarch64_dynamic_regset/TestArm64DynamicRegsets.py --- a/lldb/test/API/commands/register/register/aarch64_dynamic_regset/TestArm64DynamicRegsets.py +++ b/lldb/test/API/commands/register/register/aarch64_dynamic_regset/TestArm64DynamicRegsets.py @@ -9,78 +9,88 @@ class RegisterCommandsTestCase(TestBase): - def check_sve_register_size(self, set, name, expected): reg_value = set.GetChildMemberWithName(name) - self.assertTrue(reg_value.IsValid(), - 'Expected a register named %s' % (name)) - self.assertEqual(reg_value.GetByteSize(), expected, - 'Expected a register %s size == %i bytes' % (name, expected)) + self.assertTrue(reg_value.IsValid(), "Expected a register named %s" % (name)) + self.assertEqual( + reg_value.GetByteSize(), + expected, + "Expected a register %s size == %i bytes" % (name, expected), + ) def sve_regs_read_dynamic(self, sve_registers): vg_reg = sve_registers.GetChildMemberWithName("vg") - vg_reg_value = sve_registers.GetChildMemberWithName( - "vg").GetValueAsUnsigned() + vg_reg_value = sve_registers.GetChildMemberWithName("vg").GetValueAsUnsigned() z_reg_size = vg_reg_value * 8 p_reg_size = int(z_reg_size / 8) for i in range(32): - z_regs_value = '{' + \ - ' '.join('0x{:02x}'.format(i + 1) - for _ in range(z_reg_size)) + '}' - self.expect('register read z%i' % - (i), substrs=[z_regs_value]) + z_regs_value = ( + "{" + + " ".join("0x{:02x}".format(i + 1) for _ in range(z_reg_size)) + + "}" + ) + self.expect("register read z%i" % (i), substrs=[z_regs_value]) # Set P registers with random test values. The P registers are predicate # registers, which hold one bit for each byte available in a Z register. # For below mentioned values of P registers, P(0,5,10,15) will have all # Z register lanes set while P(4,9,14) will have no lanes set. - p_value_bytes = ['0xff', '0x55', '0x11', '0x01', '0x00'] + p_value_bytes = ["0xff", "0x55", "0x11", "0x01", "0x00"] for i in range(16): - p_regs_value = '{' + \ - ' '.join(p_value_bytes[i % 5] for _ in range(p_reg_size)) + '}' - self.expect('register read p%i' % (i), substrs=[p_regs_value]) + p_regs_value = ( + "{" + " ".join(p_value_bytes[i % 5] for _ in range(p_reg_size)) + "}" + ) + self.expect("register read p%i" % (i), substrs=[p_regs_value]) self.expect("register read ffr", substrs=[p_regs_value]) for i in range(32): - z_regs_value = '{' + \ - ' '.join('0x{:02x}'.format(32 - i) - for _ in range(z_reg_size)) + '}' + z_regs_value = ( + "{" + + " ".join("0x{:02x}".format(32 - i) for _ in range(z_reg_size)) + + "}" + ) self.runCmd("register write z%i '%s'" % (i, z_regs_value)) - self.expect('register read z%i' % (i), substrs=[z_regs_value]) + self.expect("register read z%i" % (i), substrs=[z_regs_value]) for i in range(16): - p_regs_value = '{' + \ - ' '.join('0x{:02x}'.format(16 - i) - for _ in range(p_reg_size)) + '}' + p_regs_value = ( + "{" + + " ".join("0x{:02x}".format(16 - i) for _ in range(p_reg_size)) + + "}" + ) self.runCmd("register write p%i '%s'" % (i, p_regs_value)) - self.expect('register read p%i' % (i), substrs=[p_regs_value]) + self.expect("register read p%i" % (i), substrs=[p_regs_value]) - p_regs_value = '{' + \ - ' '.join('0x{:02x}'.format(8) - for _ in range(p_reg_size)) + '}' - self.runCmd('register write ffr ' + "'" + p_regs_value + "'") - self.expect('register read ffr', substrs=[p_regs_value]) + p_regs_value = ( + "{" + " ".join("0x{:02x}".format(8) for _ in range(p_reg_size)) + "}" + ) + self.runCmd("register write ffr " + "'" + p_regs_value + "'") + self.expect("register read ffr", substrs=[p_regs_value]) @no_debug_info_test @skipIf(archs=no_match(["aarch64"])) - @skipIf(oslist=no_match(['linux'])) + @skipIf(oslist=no_match(["linux"])) def test_aarch64_dynamic_regset_config(self): """Test AArch64 Dynamic Register sets configuration.""" self.build() - self.line = line_number('main.c', '// Set a break point here.') + self.line = line_number("main.c", "// Set a break point here.") exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.c", self.line, num_expected_locations=1) + self, "main.c", self.line, num_expected_locations=1 + ) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=["stop reason = breakpoint 1."]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."], + ) target = self.dbg.GetSelectedTarget() process = target.GetProcess() @@ -88,20 +98,25 @@ currentFrame = thread.GetFrameAtIndex(0) for registerSet in currentFrame.GetRegisters(): - if 'Scalable Vector Extension Registers' in registerSet.GetName(): - self.assertTrue(self.isAArch64SVE(), - 'LLDB enabled AArch64 SVE register set when it was disabled by target.') + if "Scalable Vector Extension Registers" in registerSet.GetName(): + self.assertTrue( + self.isAArch64SVE(), + "LLDB enabled AArch64 SVE register set when it was disabled by target.", + ) self.sve_regs_read_dynamic(registerSet) - if 'MTE Control Register' in registerSet.GetName(): - self.assertTrue(self.isAArch64MTE(), - 'LLDB enabled AArch64 MTE register set when it was disabled by target.') + if "MTE Control Register" in registerSet.GetName(): + self.assertTrue( + self.isAArch64MTE(), + "LLDB enabled AArch64 MTE register set when it was disabled by target.", + ) self.runCmd("register write mte_ctrl 0x7fff9") - self.expect("register read mte_ctrl", - substrs=['mte_ctrl = 0x000000000007fff9']) - if 'Pointer Authentication Registers' in registerSet.GetName(): - self.assertTrue(self.isAArch64PAuth(), - 'LLDB enabled AArch64 Pointer Authentication register set when it was disabled by target.') - self.expect("register read data_mask", - substrs=['data_mask = 0x']) - self.expect("register read code_mask", - substrs=['code_mask = 0x']) + self.expect( + "register read mte_ctrl", substrs=["mte_ctrl = 0x000000000007fff9"] + ) + if "Pointer Authentication Registers" in registerSet.GetName(): + self.assertTrue( + self.isAArch64PAuth(), + "LLDB enabled AArch64 Pointer Authentication register set when it was disabled by target.", + ) + self.expect("register read data_mask", substrs=["data_mask = 0x"]) + self.expect("register read code_mask", substrs=["code_mask = 0x"]) diff --git a/lldb/test/API/commands/register/register/aarch64_sve_registers/rw_access_dynamic_resize/TestSVEThreadedDynamic.py b/lldb/test/API/commands/register/register/aarch64_sve_registers/rw_access_dynamic_resize/TestSVEThreadedDynamic.py --- a/lldb/test/API/commands/register/register/aarch64_sve_registers/rw_access_dynamic_resize/TestSVEThreadedDynamic.py +++ b/lldb/test/API/commands/register/register/aarch64_sve_registers/rw_access_dynamic_resize/TestSVEThreadedDynamic.py @@ -9,79 +9,74 @@ class RegisterCommandsTestCase(TestBase): - def check_sve_registers(self, vg_test_value): z_reg_size = vg_test_value * 8 p_reg_size = int(z_reg_size / 8) - p_value_bytes = ['0xff', '0x55', '0x11', '0x01', '0x00'] + p_value_bytes = ["0xff", "0x55", "0x11", "0x01", "0x00"] for i in range(32): - s_reg_value = 's%i = 0x' % (i) + \ - ''.join('{:02x}'.format(i + 1) for _ in range(4)) + s_reg_value = "s%i = 0x" % (i) + "".join( + "{:02x}".format(i + 1) for _ in range(4) + ) - d_reg_value = 'd%i = 0x' % (i) + \ - ''.join('{:02x}'.format(i + 1) for _ in range(8)) + d_reg_value = "d%i = 0x" % (i) + "".join( + "{:02x}".format(i + 1) for _ in range(8) + ) - v_reg_value = 'v%i = 0x' % (i) + \ - ''.join('{:02x}'.format(i + 1) for _ in range(16)) + v_reg_value = "v%i = 0x" % (i) + "".join( + "{:02x}".format(i + 1) for _ in range(16) + ) - z_reg_value = '{' + \ - ' '.join('0x{:02x}'.format(i + 1) - for _ in range(z_reg_size)) + '}' + z_reg_value = ( + "{" + + " ".join("0x{:02x}".format(i + 1) for _ in range(z_reg_size)) + + "}" + ) - self.expect("register read -f hex " + 's%i' % - (i), substrs=[s_reg_value]) + self.expect("register read -f hex " + "s%i" % (i), substrs=[s_reg_value]) - self.expect("register read -f hex " + 'd%i' % - (i), substrs=[d_reg_value]) + self.expect("register read -f hex " + "d%i" % (i), substrs=[d_reg_value]) - self.expect("register read -f hex " + 'v%i' % - (i), substrs=[v_reg_value]) + self.expect("register read -f hex " + "v%i" % (i), substrs=[v_reg_value]) - self.expect("register read " + 'z%i' % - (i), substrs=[z_reg_value]) + self.expect("register read " + "z%i" % (i), substrs=[z_reg_value]) for i in range(16): - p_regs_value = '{' + \ - ' '.join(p_value_bytes[i % 5] for _ in range(p_reg_size)) + '}' - self.expect("register read " + 'p%i' % (i), substrs=[p_regs_value]) + p_regs_value = ( + "{" + " ".join(p_value_bytes[i % 5] for _ in range(p_reg_size)) + "}" + ) + self.expect("register read " + "p%i" % (i), substrs=[p_regs_value]) self.expect("register read ffr", substrs=[p_regs_value]) @no_debug_info_test @skipIf(archs=no_match(["aarch64"])) - @skipIf(oslist=no_match(['linux'])) + @skipIf(oslist=no_match(["linux"])) def test_sve_registers_dynamic_config(self): - """Test AArch64 SVE registers multi-threaded dynamic resize. """ + """Test AArch64 SVE registers multi-threaded dynamic resize.""" self.build() exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) if not self.isAArch64SVE(): - self.skipTest('SVE registers must be supported.') + self.skipTest("SVE registers must be supported.") - main_thread_stop_line = line_number( - "main.c", "// Break in main thread") - lldbutil.run_break_set_by_file_and_line( - self, "main.c", main_thread_stop_line) + main_thread_stop_line = line_number("main.c", "// Break in main thread") + lldbutil.run_break_set_by_file_and_line(self, "main.c", main_thread_stop_line) thX_break_line1 = line_number("main.c", "// Thread X breakpoint 1") - lldbutil.run_break_set_by_file_and_line( - self, "main.c", thX_break_line1) + lldbutil.run_break_set_by_file_and_line(self, "main.c", thX_break_line1) thX_break_line2 = line_number("main.c", "// Thread X breakpoint 2") - lldbutil.run_break_set_by_file_and_line( - self, "main.c", thX_break_line2) + lldbutil.run_break_set_by_file_and_line(self, "main.c", thX_break_line2) thY_break_line1 = line_number("main.c", "// Thread Y breakpoint 1") - lldbutil.run_break_set_by_file_and_line( - self, "main.c", thY_break_line1) + lldbutil.run_break_set_by_file_and_line(self, "main.c", thY_break_line1) thY_break_line2 = line_number("main.c", "// Thread Y breakpoint 2") - lldbutil.run_break_set_by_file_and_line( - self, "main.c", thY_break_line2) + lldbutil.run_break_set_by_file_and_line(self, "main.c", thY_break_line2) self.runCmd("run", RUN_SUCCEEDED) @@ -89,8 +84,11 @@ thread1 = process.GetThreadAtIndex(0) - self.expect("thread info 1", STOPPED_DUE_TO_BREAKPOINT, - substrs=["stop reason = breakpoint"]) + self.expect( + "thread info 1", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint"], + ) self.check_sve_registers(8) @@ -100,32 +98,28 @@ thread = process.GetThreadAtIndex(idx) if thread.GetStopReason() != lldb.eStopReasonBreakpoint: self.runCmd("thread continue %d" % (idx + 1)) - self.assertEqual(thread.GetStopReason(), - lldb.eStopReasonBreakpoint) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonBreakpoint) - stopped_at_line_number = thread.GetFrameAtIndex( - 0).GetLineEntry().GetLine() + stopped_at_line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() if stopped_at_line_number == thX_break_line1: self.runCmd("thread select %d" % (idx + 1)) self.check_sve_registers(4) - self.runCmd('register write vg 2') + self.runCmd("register write vg 2") elif stopped_at_line_number == thY_break_line1: self.runCmd("thread select %d" % (idx + 1)) self.check_sve_registers(2) - self.runCmd('register write vg 4') + self.runCmd("register write vg 4") self.runCmd("thread continue 2") self.runCmd("thread continue 3") for idx in range(1, process.GetNumThreads()): thread = process.GetThreadAtIndex(idx) - self.assertEqual(thread.GetStopReason(), - lldb.eStopReasonBreakpoint) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonBreakpoint) - stopped_at_line_number = thread.GetFrameAtIndex( - 0).GetLineEntry().GetLine() + stopped_at_line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() if stopped_at_line_number == thX_break_line2: self.runCmd("thread select %d" % (idx + 1)) diff --git a/lldb/test/API/commands/register/register/aarch64_sve_registers/rw_access_static_config/TestSVERegisters.py b/lldb/test/API/commands/register/register/aarch64_sve_registers/rw_access_static_config/TestSVERegisters.py --- a/lldb/test/API/commands/register/register/aarch64_sve_registers/rw_access_static_config/TestSVERegisters.py +++ b/lldb/test/API/commands/register/register/aarch64_sve_registers/rw_access_static_config/TestSVERegisters.py @@ -9,79 +9,82 @@ class RegisterCommandsTestCase(TestBase): - def check_sve_register_size(self, set, name, expected): reg_value = set.GetChildMemberWithName(name) - self.assertTrue(reg_value.IsValid(), - 'Verify we have a register named "%s"' % (name)) - self.assertEqual(reg_value.GetByteSize(), expected, - 'Verify "%s" == %i' % (name, expected)) + self.assertTrue( + reg_value.IsValid(), 'Verify we have a register named "%s"' % (name) + ) + self.assertEqual( + reg_value.GetByteSize(), expected, 'Verify "%s" == %i' % (name, expected) + ) def check_sve_regs_read(self, z_reg_size): p_reg_size = int(z_reg_size / 8) for i in range(32): - z_regs_value = '{' + \ - ' '.join('0x{:02x}'.format(i + 1) - for _ in range(z_reg_size)) + '}' - self.expect("register read " + 'z%i' % - (i), substrs=[z_regs_value]) - - p_value_bytes = ['0xff', '0x55', '0x11', '0x01', '0x00'] + z_regs_value = ( + "{" + + " ".join("0x{:02x}".format(i + 1) for _ in range(z_reg_size)) + + "}" + ) + self.expect("register read " + "z%i" % (i), substrs=[z_regs_value]) + + p_value_bytes = ["0xff", "0x55", "0x11", "0x01", "0x00"] for i in range(16): - p_regs_value = '{' + \ - ' '.join(p_value_bytes[i % 5] for _ in range(p_reg_size)) + '}' - self.expect("register read " + 'p%i' % (i), substrs=[p_regs_value]) + p_regs_value = ( + "{" + " ".join(p_value_bytes[i % 5] for _ in range(p_reg_size)) + "}" + ) + self.expect("register read " + "p%i" % (i), substrs=[p_regs_value]) self.expect("register read ffr", substrs=[p_regs_value]) def check_sve_regs_read_after_write(self, z_reg_size): p_reg_size = int(z_reg_size / 8) - z_regs_value = '{' + \ - ' '.join(('0x9d' for _ in range(z_reg_size))) + '}' + z_regs_value = "{" + " ".join(("0x9d" for _ in range(z_reg_size))) + "}" - p_regs_value = '{' + \ - ' '.join(('0xee' for _ in range(p_reg_size))) + '}' + p_regs_value = "{" + " ".join(("0xee" for _ in range(p_reg_size))) + "}" for i in range(32): - self.runCmd('register write ' + 'z%i' % - (i) + " '" + z_regs_value + "'") + self.runCmd("register write " + "z%i" % (i) + " '" + z_regs_value + "'") for i in range(32): - self.expect("register read " + 'z%i' % (i), substrs=[z_regs_value]) + self.expect("register read " + "z%i" % (i), substrs=[z_regs_value]) for i in range(16): - self.runCmd('register write ' + 'p%i' % - (i) + " '" + p_regs_value + "'") + self.runCmd("register write " + "p%i" % (i) + " '" + p_regs_value + "'") for i in range(16): - self.expect("register read " + 'p%i' % (i), substrs=[p_regs_value]) + self.expect("register read " + "p%i" % (i), substrs=[p_regs_value]) - self.runCmd('register write ' + 'ffr ' + "'" + p_regs_value + "'") + self.runCmd("register write " + "ffr " + "'" + p_regs_value + "'") - self.expect("register read " + 'ffr', substrs=[p_regs_value]) + self.expect("register read " + "ffr", substrs=[p_regs_value]) @no_debug_info_test @skipIf(archs=no_match(["aarch64"])) - @skipIf(oslist=no_match(['linux'])) + @skipIf(oslist=no_match(["linux"])) def test_sve_registers_configuration(self): """Test AArch64 SVE registers size configuration.""" self.build() - self.line = line_number('main.c', '// Set a break point here.') + self.line = line_number("main.c", "// Set a break point here.") exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) if not self.isAArch64SVE(): - self.skipTest('SVE registers must be supported.') + self.skipTest("SVE registers must be supported.") lldbutil.run_break_set_by_file_and_line( - self, "main.c", self.line, num_expected_locations=1) + self, "main.c", self.line, num_expected_locations=1 + ) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=["stop reason = breakpoint 1."]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."], + ) target = self.dbg.GetSelectedTarget() process = target.GetProcess() @@ -90,53 +93,53 @@ has_sve = False for registerSet in currentFrame.GetRegisters(): - if 'Scalable Vector Extension Registers' in registerSet.GetName(): + if "Scalable Vector Extension Registers" in registerSet.GetName(): has_sve = True - registerSets = process.GetThreadAtIndex( - 0).GetFrameAtIndex(0).GetRegisters() + registerSets = process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetRegisters() sve_registers = registerSets.GetValueAtIndex(2) vg_reg = sve_registers.GetChildMemberWithName("vg") - vg_reg_value = sve_registers.GetChildMemberWithName( - "vg").GetValueAsUnsigned() + vg_reg_value = sve_registers.GetChildMemberWithName("vg").GetValueAsUnsigned() z_reg_size = vg_reg_value * 8 p_reg_size = z_reg_size / 8 for i in range(32): - self.check_sve_register_size( - sve_registers, 'z%i' % (i), z_reg_size) + self.check_sve_register_size(sve_registers, "z%i" % (i), z_reg_size) for i in range(16): - self.check_sve_register_size( - sve_registers, 'p%i' % (i), p_reg_size) + self.check_sve_register_size(sve_registers, "p%i" % (i), p_reg_size) - self.check_sve_register_size(sve_registers, 'ffr', p_reg_size) + self.check_sve_register_size(sve_registers, "ffr", p_reg_size) @no_debug_info_test @skipIf(archs=no_match(["aarch64"])) - @skipIf(oslist=no_match(['linux'])) + @skipIf(oslist=no_match(["linux"])) def test_sve_registers_read_write(self): """Test AArch64 SVE registers read and write.""" self.build() - self.line = line_number('main.c', '// Set a break point here.') + self.line = line_number("main.c", "// Set a break point here.") exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) if not self.isAArch64SVE(): - self.skipTest('SVE registers must be supported.') + self.skipTest("SVE registers must be supported.") lldbutil.run_break_set_by_file_and_line( - self, "main.c", self.line, num_expected_locations=1) + self, "main.c", self.line, num_expected_locations=1 + ) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=["stop reason = breakpoint 1."]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."], + ) target = self.dbg.GetSelectedTarget() process = target.GetProcess() @@ -145,18 +148,16 @@ has_sve = False for registerSet in currentFrame.GetRegisters(): - if 'Scalable Vector Extension Registers' in registerSet.GetName(): + if "Scalable Vector Extension Registers" in registerSet.GetName(): has_sve = True - registerSets = process.GetThreadAtIndex( - 0).GetFrameAtIndex(0).GetRegisters() + registerSets = process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetRegisters() sve_registers = registerSets.GetValueAtIndex(2) vg_reg = sve_registers.GetChildMemberWithName("vg") - vg_reg_value = sve_registers.GetChildMemberWithName( - "vg").GetValueAsUnsigned() + vg_reg_value = sve_registers.GetChildMemberWithName("vg").GetValueAsUnsigned() z_reg_size = vg_reg_value * 8 @@ -166,8 +167,7 @@ self.expect("expression expr_eval_func", substrs=["= 0x"]) # Evaluate expression call function expr_eval_func. - self.expect_expr("expr_eval_func()", - result_type="int", result_value="1") + self.expect_expr("expr_eval_func()", result_type="int", result_value="1") # We called a jitted function above which must not have changed SVE # vector length or register values. diff --git a/lldb/test/API/commands/register/register/register_command/TestRegisters.py b/lldb/test/API/commands/register/register/register_command/TestRegisters.py --- a/lldb/test/API/commands/register/register/register_command/TestRegisters.py +++ b/lldb/test/API/commands/register/register/register_command/TestRegisters.py @@ -22,9 +22,8 @@ TestBase.tearDown(self) @skipIfiOSSimulator - @skipIf(archs=no_match(['amd64', 'arm', 'i386', 'x86_64'])) - @expectedFailureAll(oslist=["freebsd", "netbsd"], - bugnumber='llvm.org/pr48371') + @skipIf(archs=no_match(["amd64", "arm", "i386", "x86_64"])) + @expectedFailureAll(oslist=["freebsd", "netbsd"], bugnumber="llvm.org/pr48371") def test_register_commands(self): """Test commands related to registers, in particular vector registers.""" self.build() @@ -33,32 +32,42 @@ # verify that logging does not assert self.log_enable("registers") - self.expect("register read -a", MISSING_EXPECTED_REGISTERS, - substrs=['registers were unavailable'], matching=False) + self.expect( + "register read -a", + MISSING_EXPECTED_REGISTERS, + substrs=["registers were unavailable"], + matching=False, + ) all_registers = self.res.GetOutput() - if self.getArchitecture() in ['amd64', 'i386', 'x86_64']: + if self.getArchitecture() in ["amd64", "i386", "x86_64"]: self.runCmd("register read xmm0") if "ymm15 = " in all_registers: - self.runCmd("register read ymm15") # may be available + self.runCmd("register read ymm15") # may be available if "bnd0 = " in all_registers: - self.runCmd("register read bnd0") # may be available - elif self.getArchitecture() in ['arm', 'armv7', 'armv7k', 'arm64', 'arm64e', 'arm64_32']: + self.runCmd("register read bnd0") # may be available + elif self.getArchitecture() in [ + "arm", + "armv7", + "armv7k", + "arm64", + "arm64e", + "arm64_32", + ]: self.runCmd("register read s0") if "q15 = " in all_registers: - self.runCmd("register read q15") # may be available + self.runCmd("register read q15") # may be available self.expect( - "register read -s 4", - substrs=['invalid register set index: 4'], - error=True) + "register read -s 4", substrs=["invalid register set index: 4"], error=True + ) @skipIfiOSSimulator # Writing of mxcsr register fails, presumably due to a kernel/hardware # problem @skipIfTargetAndroid(archs=["i386"]) - @skipIf(archs=no_match(['amd64', 'arm', 'i386', 'x86_64'])) + @skipIf(archs=no_match(["amd64", "arm", "i386", "x86_64"])) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37995") def test_fp_register_write(self): """Test commands that write to registers, in particular floating-point registers.""" @@ -68,7 +77,7 @@ @skipIfiOSSimulator # "register read fstat" always return 0xffff @expectedFailureAndroid(archs=["i386"]) - @skipIf(archs=no_match(['amd64', 'i386', 'x86_64'])) + @skipIf(archs=no_match(["amd64", "i386", "x86_64"])) @skipIfOutOfTreeDebugserver @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37995") def test_fp_special_purpose_register_read(self): @@ -77,36 +86,32 @@ self.fp_special_purpose_register_read() @skipIfiOSSimulator - @skipIf(archs=no_match(['amd64', 'arm', 'i386', 'x86_64'])) + @skipIf(archs=no_match(["amd64", "arm", "i386", "x86_64"])) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37683") def test_register_expressions(self): """Test expression evaluation with commands related to registers.""" self.build() self.common_setup() - if self.getArchitecture() in ['amd64', 'i386', 'x86_64']: + if self.getArchitecture() in ["amd64", "i386", "x86_64"]: gpr = "eax" vector = "xmm0" - elif self.getArchitecture() in ['arm64', 'aarch64', 'arm64e', 'arm64_32']: + elif self.getArchitecture() in ["arm64", "aarch64", "arm64e", "arm64_32"]: gpr = "w0" vector = "v0" - elif self.getArchitecture() in ['arm', 'armv7', 'armv7k']: + elif self.getArchitecture() in ["arm", "armv7", "armv7k"]: gpr = "r0" vector = "q0" - self.expect("expr/x $%s" % gpr, substrs=['unsigned int', ' = 0x']) - self.expect("expr $%s" % vector, substrs=['vector_type']) - self.expect( - "expr (unsigned int)$%s[0]" % - vector, substrs=['unsigned int']) + self.expect("expr/x $%s" % gpr, substrs=["unsigned int", " = 0x"]) + self.expect("expr $%s" % vector, substrs=["vector_type"]) + self.expect("expr (unsigned int)$%s[0]" % vector, substrs=["unsigned int"]) - if self.getArchitecture() in ['amd64', 'x86_64']: - self.expect( - "expr -- ($rax & 0xffffffff) == $eax", - substrs=['true']) + if self.getArchitecture() in ["amd64", "x86_64"]: + self.expect("expr -- ($rax & 0xffffffff) == $eax", substrs=["true"]) @skipIfiOSSimulator - @skipIf(archs=no_match(['amd64', 'x86_64'])) + @skipIf(archs=no_match(["amd64", "x86_64"])) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37683") def test_convenience_registers(self): """Test convenience registers.""" @@ -114,14 +119,14 @@ self.convenience_registers() @skipIfiOSSimulator - @skipIf(archs=no_match(['amd64', 'x86_64'])) + @skipIf(archs=no_match(["amd64", "x86_64"])) def test_convenience_registers_with_process_attach(self): """Test convenience registers after a 'process attach'.""" self.build() self.convenience_registers_with_process_attach(test_16bit_regs=False) @skipIfiOSSimulator - @skipIf(archs=no_match(['amd64', 'x86_64'])) + @skipIf(archs=no_match(["amd64", "x86_64"])) def test_convenience_registers_16bit_with_process_attach(self): """Test convenience registers after a 'process attach'.""" self.build() @@ -133,61 +138,59 @@ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break in main(). - lldbutil.run_break_set_by_symbol( - self, "main", num_expected_locations=-1) + lldbutil.run_break_set_by_symbol(self, "main", num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # platform specific logging of the specified category def log_enable(self, category): # This intentionally checks the host platform rather than the target # platform as logging is host side. self.platform = "" - if (sys.platform.startswith("freebsd") or - sys.platform.startswith("linux") or - sys.platform.startswith("netbsd")): + if ( + sys.platform.startswith("freebsd") + or sys.platform.startswith("linux") + or sys.platform.startswith("netbsd") + ): self.platform = "posix" if self.platform != "": - self.log_file = self.getBuildArtifact('TestRegisters.log') + self.log_file = self.getBuildArtifact("TestRegisters.log") self.runCmd( - "log enable " + - self.platform + - " " + - str(category) + - " registers -v -f " + - self.log_file, - RUN_SUCCEEDED) + "log enable " + + self.platform + + " " + + str(category) + + " registers -v -f " + + self.log_file, + RUN_SUCCEEDED, + ) if not self.has_teardown: + def remove_log(self): if os.path.exists(self.log_file): os.remove(self.log_file) + self.has_teardown = True self.addTearDownHook(remove_log) def write_and_read(self, frame, register, new_value, must_exist=True): value = frame.FindValue(register, lldb.eValueTypeRegister) if must_exist: - self.assertTrue( - value.IsValid(), - "finding a value for register " + - register) + self.assertTrue(value.IsValid(), "finding a value for register " + register) elif not value.IsValid(): return # If register doesn't exist, skip this test # Also test the 're' alias. - self.runCmd("re write " + register + " \'" + new_value + "\'") - self.expect( - "register read " + - register, - substrs=[ - register + - ' = ', - new_value]) + self.runCmd("re write " + register + " '" + new_value + "'") + self.expect("register read " + register, substrs=[register + " = ", new_value]) # This test relies on ftag containing the 'abridged' value. Linux # and *BSD targets have been ported to report the full value instead @@ -198,26 +201,23 @@ target = self.createTestTarget() # Launch the process and stop. - self.expect("run", PROCESS_STOPPED, substrs=['stopped']) + self.expect("run", PROCESS_STOPPED, substrs=["stopped"]) # Check stop reason; Should be either signal SIGTRAP or EXC_BREAKPOINT output = self.res.GetOutput() matched = False - substrs = [ - 'stop reason = EXC_BREAKPOINT', - 'stop reason = signal SIGTRAP'] + substrs = ["stop reason = EXC_BREAKPOINT", "stop reason = signal SIGTRAP"] for str1 in substrs: matched = output.find(str1) != -1 with recording(self, False) as sbuf: - print("%s sub string: %s" % ('Expecting', str1), file=sbuf) + print("%s sub string: %s" % ("Expecting", str1), file=sbuf) print("Matched" if matched else "Not Matched", file=sbuf) if matched: break self.assertTrue(matched, STOPPED_DUE_TO_SIGNAL) process = target.GetProcess() - self.assertState(process.GetState(), lldb.eStateStopped, - PROCESS_STOPPED) + self.assertState(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) thread = process.GetThreadAtIndex(0) self.assertTrue(thread.IsValid(), "current thread is valid") @@ -249,27 +249,43 @@ # Verify fstat and save it to be used for verification in next # execution of 'si' command if not (reg_value_fstat_initial & 0x3800): - self.expect("register read fstat", substrs=[ - 'fstat' + ' = ', str("0x%0.4x" % ((reg_value_fstat_initial & ~(0x3800)) | 0x3800))]) - reg_value_fstat_initial = ( - (reg_value_fstat_initial & ~(0x3800)) | 0x3800) + self.expect( + "register read fstat", + substrs=[ + "fstat" + " = ", + str( + "0x%0.4x" % ((reg_value_fstat_initial & ~(0x3800)) | 0x3800) + ), + ], + ) + reg_value_fstat_initial = (reg_value_fstat_initial & ~(0x3800)) | 0x3800 fstat_top_pointer_initial = 7 else: - self.expect("register read fstat", substrs=[ - 'fstat' + ' = ', str("0x%0.4x" % (reg_value_fstat_initial - 0x0800))]) - reg_value_fstat_initial = (reg_value_fstat_initial - 0x0800) + self.expect( + "register read fstat", + substrs=[ + "fstat" + " = ", + str("0x%0.4x" % (reg_value_fstat_initial - 0x0800)), + ], + ) + reg_value_fstat_initial = reg_value_fstat_initial - 0x0800 fstat_top_pointer_initial -= 1 # Verify ftag and save it to be used for verification in next # execution of 'si' command self.expect( - "register read ftag", substrs=[ - 'ftag' + ' = ', str( - "0x%0.4x" % - (reg_value_ftag_initial | ( - 1 << fstat_top_pointer_initial)))]) + "register read ftag", + substrs=[ + "ftag" + " = ", + str( + "0x%0.4x" + % (reg_value_ftag_initial | (1 << fstat_top_pointer_initial)) + ), + ], + ) reg_value_ftag_initial = reg_value_ftag_initial | ( - 1 << fstat_top_pointer_initial) + 1 << fstat_top_pointer_initial + ) def fp_register_write(self): target = self.createTestTarget() @@ -278,18 +294,20 @@ error = lldb.SBError() flags = target.GetLaunchInfo().GetLaunchFlags() process = target.Launch( - lldb.SBListener(), - None, None, # argv, envp - None, None, None, # stdin/out/err - self.get_process_working_directory(), - flags, # launch flags - True, # stop at entry - error) + lldb.SBListener(), + None, + None, # argv, envp + None, + None, + None, # stdin/out/err + self.get_process_working_directory(), + flags, # launch flags + True, # stop at entry + error, + ) self.assertSuccess(error, "Launch succeeds") - self.assertEqual( - process.GetState(), lldb.eStateStopped, - PROCESS_STOPPED) + self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) thread = process.GetThreadAtIndex(0) self.assertTrue(thread.IsValid(), "current thread is valid") @@ -297,7 +315,7 @@ currentFrame = thread.GetFrameAtIndex(0) self.assertTrue(currentFrame.IsValid(), "current frame is valid") - if self.getArchitecture() in ['amd64', 'i386', 'x86_64']: + if self.getArchitecture() in ["amd64", "i386", "x86_64"]: reg_list = [ # reg value must-have ("fcw", "0x0000ff0e", False), @@ -320,16 +338,27 @@ # reg value # must-have reg_list.append( - (st0regname, "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x00 0x00}", True)) + ( + st0regname, + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x00 0x00}", + True, + ) + ) reg_list.append( - ("xmm0", - "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", - True)) + ( + "xmm0", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", + True, + ) + ) reg_list.append( - ("xmm15", - "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", - False)) - elif self.getArchitecture() in ['arm64', 'aarch64', 'arm64e', 'arm64_32']: + ( + "xmm15", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", + False, + ) + ) + elif self.getArchitecture() in ["arm64", "aarch64", "arm64e", "arm64_32"]: reg_list = [ # reg value # must-have @@ -338,12 +367,18 @@ ("s31", "0.75", True), ("d1", "123", True), ("d17", "987", False), - ("v1", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", True), - ("v14", - "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", - False), + ( + "v1", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", + True, + ), + ( + "v14", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", + False, + ), ] - elif self.getArchitecture() in ['armv7'] and self.platformIsDarwin(): + elif self.getArchitecture() in ["armv7"] and self.platformIsDarwin(): reg_list = [ # reg value # must-have @@ -352,12 +387,18 @@ ("s31", "0.75", True), ("d1", "123", True), ("d17", "987", False), - ("q1", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", True), - ("q14", - "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", - False), + ( + "q1", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", + True, + ), + ( + "q14", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", + False, + ), ] - elif self.getArchitecture() in ['arm', 'armv7k']: + elif self.getArchitecture() in ["arm", "armv7k"]: reg_list = [ # reg value # must-have @@ -366,34 +407,39 @@ ("s31", "0.75", True), ("d1", "123", True), ("d17", "987", False), - ("q1", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", True), - ("q14", - "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", - False), + ( + "q1", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", + True, + ), + ( + "q14", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", + False, + ), ] - for (reg, val, must) in reg_list: + for reg, val, must in reg_list: self.write_and_read(currentFrame, reg, val, must) - if self.getArchitecture() in ['amd64', 'i386', 'x86_64']: + if self.getArchitecture() in ["amd64", "i386", "x86_64"]: if st0regname is None: self.fail("st0regname could not be determined") self.runCmd( - "register write " + - st0regname + - " \"{0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00}\"") + "register write " + + st0regname + + ' "{0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00}"' + ) self.expect( - "register read " + - st0regname + - " --format f", - substrs=[ - st0regname + - ' = 0']) + "register read " + st0regname + " --format f", + substrs=[st0regname + " = 0"], + ) # Check if AVX/MPX registers are defined at all. registerSets = currentFrame.GetRegisters() - registers = frozenset(reg.GetName() for registerSet in registerSets - for reg in registerSet) + registers = frozenset( + reg.GetName() for registerSet in registerSets for reg in registerSet + ) has_avx_regs = "ymm0" in registers has_mpx_regs = "bnd0" in registers # Check if they are actually present. @@ -406,30 +452,36 @@ new_value = "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x0c 0x0d 0x0e 0x0f}" self.write_and_read(currentFrame, "ymm0", new_value) self.write_and_read(currentFrame, "ymm7", new_value) - self.expect("expr $ymm0", substrs=['vector_type']) + self.expect("expr $ymm0", substrs=["vector_type"]) elif has_avx_regs: self.expect("register read ymm0", substrs=["error: unavailable"]) else: - self.expect("register read ymm0", substrs=["Invalid register name 'ymm0'"], - error=True) + self.expect( + "register read ymm0", + substrs=["Invalid register name 'ymm0'"], + error=True, + ) if has_mpx: # Test write and read for bnd0. new_value_w = "{0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f 0x10}" - self.runCmd("register write bnd0 \'" + new_value_w + "\'") + self.runCmd("register write bnd0 '" + new_value_w + "'") new_value_r = "{0x0807060504030201 0x100f0e0d0c0b0a09}" - self.expect("register read bnd0", substrs = ['bnd0 = ', new_value_r]) - self.expect("expr $bnd0", substrs = ['vector_type']) + self.expect("register read bnd0", substrs=["bnd0 = ", new_value_r]) + self.expect("expr $bnd0", substrs=["vector_type"]) # Test write and for bndstatus. new_value = "{0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08}" self.write_and_read(currentFrame, "bndstatus", new_value) - self.expect("expr $bndstatus", substrs = ['vector_type']) + self.expect("expr $bndstatus", substrs=["vector_type"]) elif has_mpx_regs: self.expect("register read bnd0", substrs=["error: unavailable"]) else: - self.expect("register read bnd0", substrs=["Invalid register name 'bnd0'"], - error=True) + self.expect( + "register read bnd0", + substrs=["Invalid register name 'bnd0'"], + error=True, + ) def convenience_registers(self): """Test convenience registers.""" @@ -437,29 +489,25 @@ # The command "register read -a" does output a derived register like # eax... - self.expect("register read -a", matching=True, - substrs=['eax']) + self.expect("register read -a", matching=True, substrs=["eax"]) # ...however, the vanilla "register read" command should not output derived registers like eax. - self.expect("register read", matching=False, - substrs=['eax']) + self.expect("register read", matching=False, substrs=["eax"]) # Test reading of rax and eax. - self.expect("register read rax eax", - substrs=['rax = 0x', 'eax = 0x']) + self.expect("register read rax eax", substrs=["rax = 0x", "eax = 0x"]) # Now write rax with a unique bit pattern and test that eax indeed # represents the lower half of rax. self.runCmd("register write rax 0x1234567887654321") - self.expect("register read rax", - substrs=['0x1234567887654321']) + self.expect("register read rax", substrs=["0x1234567887654321"]) def convenience_registers_with_process_attach(self, test_16bit_regs): """Test convenience registers after a 'process attach'.""" exe = self.getBuildArtifact("a.out") # Spawn a new process - pid = self.spawnSubprocess(exe, ['wait_for_attach']).pid + pid = self.spawnSubprocess(exe, ["wait_for_attach"]).pid if self.TraceOn(): print("pid of spawned process: %d" % pid) @@ -469,36 +517,53 @@ # Check that "register read eax" works. self.runCmd("register read eax") - if self.getArchitecture() in ['amd64', 'x86_64']: - self.expect("expr -- ($rax & 0xffffffff) == $eax", - substrs=['true']) + if self.getArchitecture() in ["amd64", "x86_64"]: + self.expect("expr -- ($rax & 0xffffffff) == $eax", substrs=["true"]) if test_16bit_regs: - self.expect("expr -- $ax == (($ah << 8) | $al)", - substrs=['true']) + self.expect("expr -- $ax == (($ah << 8) | $al)", substrs=["true"]) @skipIfiOSSimulator - @skipIf(archs=no_match(['amd64', 'arm', 'i386', 'x86_64'])) + @skipIf(archs=no_match(["amd64", "arm", "i386", "x86_64"])) def test_invalid_invocation(self): self.build() self.common_setup() - self.expect("register read -a arg", error=True, - substrs=["the --all option can't be used when registers names are supplied as arguments"]) + self.expect( + "register read -a arg", + error=True, + substrs=[ + "the --all option can't be used when registers names are supplied as arguments" + ], + ) - self.expect("register read --set 0 r", error=True, - substrs=["the --set option can't be used when registers names are supplied as arguments"]) + self.expect( + "register read --set 0 r", + error=True, + substrs=[ + "the --set option can't be used when registers names are supplied as arguments" + ], + ) - self.expect("register write a", error=True, - substrs=["register write takes exactly 2 arguments: "]) - self.expect("register write a b c", error=True, - substrs=["register write takes exactly 2 arguments: "]) + self.expect( + "register write a", + error=True, + substrs=["register write takes exactly 2 arguments: "], + ) + self.expect( + "register write a b c", + error=True, + substrs=["register write takes exactly 2 arguments: "], + ) @skipIfiOSSimulator - @skipIf(archs=no_match(['amd64', 'arm', 'i386', 'x86_64'])) + @skipIf(archs=no_match(["amd64", "arm", "i386", "x86_64"])) def test_write_unknown_register(self): self.build() self.common_setup() - self.expect("register write blub 1", error=True, - substrs=["error: Register not found for 'blub'."]) + self.expect( + "register write blub 1", + error=True, + substrs=["error: Register not found for 'blub'."], + ) diff --git a/lldb/test/API/commands/session/history/TestSessionHistory.py b/lldb/test/API/commands/session/history/TestSessionHistory.py --- a/lldb/test/API/commands/session/history/TestSessionHistory.py +++ b/lldb/test/API/commands/session/history/TestSessionHistory.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,94 +10,102 @@ class SessionHistoryTestCase(TestBase): - @no_debug_info_test def test_history(self): - self.runCmd('session history --clear', inHistory=False) - self.runCmd('breakpoint list', check=False, inHistory=True) # 0 - self.runCmd('register read', check=False, inHistory=True) # 1 - self.runCmd('apropos hello', check=False, inHistory=True) # 2 - self.runCmd('memory write', check=False, inHistory=True) # 3 - self.runCmd('log list', check=False, inHistory=True) # 4 - self.runCmd('disassemble', check=False, inHistory=True) # 5 - self.runCmd('expression 1', check=False, inHistory=True) # 6 - self.runCmd( - 'type summary list -w default', - check=False, - inHistory=True) # 7 - self.runCmd('version', check=False, inHistory=True) # 8 - self.runCmd('frame select 1', check=False, inHistory=True) # 9 + self.runCmd("session history --clear", inHistory=False) + self.runCmd("breakpoint list", check=False, inHistory=True) # 0 + self.runCmd("register read", check=False, inHistory=True) # 1 + self.runCmd("apropos hello", check=False, inHistory=True) # 2 + self.runCmd("memory write", check=False, inHistory=True) # 3 + self.runCmd("log list", check=False, inHistory=True) # 4 + self.runCmd("disassemble", check=False, inHistory=True) # 5 + self.runCmd("expression 1", check=False, inHistory=True) # 6 + self.runCmd("type summary list -w default", check=False, inHistory=True) # 7 + self.runCmd("version", check=False, inHistory=True) # 8 + self.runCmd("frame select 1", check=False, inHistory=True) # 9 self.expect( "session history -s 3 -c 3", inHistory=True, - substrs=[ - '3: memory write', - '4: log list', - '5: disassemble']) + substrs=["3: memory write", "4: log list", "5: disassemble"], + ) - self.expect("session history -s 3 -e 3", inHistory=True, - substrs=['3: memory write']) + self.expect( + "session history -s 3 -e 3", inHistory=True, substrs=["3: memory write"] + ) self.expect( "session history -s 6 -e 7", inHistory=True, - substrs=[ - '6: expression 1', - '7: type summary list -w default']) + substrs=["6: expression 1", "7: type summary list -w default"], + ) - self.expect("session history -c 2", inHistory=True, - substrs=['0: breakpoint list', '1: register read']) + self.expect( + "session history -c 2", + inHistory=True, + substrs=["0: breakpoint list", "1: register read"], + ) - self.expect("session history -e 3 -c 1", inHistory=True, - substrs=['3: memory write']) + self.expect( + "session history -e 3 -c 1", inHistory=True, substrs=["3: memory write"] + ) self.expect( "session history -e 2", inHistory=True, - substrs=[ - '0: breakpoint list', - '1: register read', - '2: apropos hello']) + substrs=["0: breakpoint list", "1: register read", "2: apropos hello"], + ) self.expect( "session history -s 12", inHistory=True, substrs=[ - '12: session history -s 6 -e 7', - '13: session history -c 2', - '14: session history -e 3 -c 1', - '15: session history -e 2', - '16: session history -s 12']) + "12: session history -s 6 -e 7", + "13: session history -c 2", + "14: session history -e 3 -c 1", + "15: session history -e 2", + "16: session history -s 12", + ], + ) self.expect( "session history -s end -c 3", inHistory=True, substrs=[ - '15: session history -e 2', - '16: session history -s 12', - '17: session history -s end -c 3']) + "15: session history -e 2", + "16: session history -s 12", + "17: session history -s end -c 3", + ], + ) self.expect( "session history -s end -e 15", inHistory=True, substrs=[ - '15: session history -e 2', - '16: session history -s 12', - '17: session history -s end -c 3', - 'session history -s end -e 15']) + "15: session history -e 2", + "16: session history -s 12", + "17: session history -s end -c 3", + "session history -s end -e 15", + ], + ) - self.expect("session history -s 5 -c 1", inHistory=True, - substrs=['5: disassemble']) + self.expect( + "session history -s 5 -c 1", inHistory=True, substrs=["5: disassemble"] + ) - self.expect("session history -c 1 -s 5", inHistory=True, - substrs=['5: disassemble']) + self.expect( + "session history -c 1 -s 5", inHistory=True, substrs=["5: disassemble"] + ) - self.expect("session history -c 1 -e 3", inHistory=True, - substrs=['3: memory write']) + self.expect( + "session history -c 1 -e 3", inHistory=True, substrs=["3: memory write"] + ) self.expect( "session history -c 1 -e 3 -s 5", error=True, inHistory=True, - substrs=['error: --count, --start-index and --end-index cannot be all specified in the same invocation']) + substrs=[ + "error: --count, --start-index and --end-index cannot be all specified in the same invocation" + ], + ) diff --git a/lldb/test/API/commands/session/save/TestSessionSave.py b/lldb/test/API/commands/session/save/TestSessionSave.py --- a/lldb/test/API/commands/session/save/TestSessionSave.py +++ b/lldb/test/API/commands/session/save/TestSessionSave.py @@ -11,16 +11,14 @@ class SessionSaveTestCase(TestBase): - def raw_transcript_builder(self, cmd, res): raw = "(lldb) " + cmd + "\n" if res.GetOutputSize(): - raw += res.GetOutput() + raw += res.GetOutput() if res.GetErrorSize(): - raw += res.GetError() + raw += res.GetError() return raw - @skipIfWindows @no_debug_info_test def test_session_save(self): @@ -28,31 +26,31 @@ interpreter = self.dbg.GetCommandInterpreter() settings = [ - 'settings set interpreter.echo-commands true', - 'settings set interpreter.echo-comment-commands true', - 'settings set interpreter.stop-command-source-on-error false', - 'settings set interpreter.open-transcript-in-editor false', + "settings set interpreter.echo-commands true", + "settings set interpreter.echo-comment-commands true", + "settings set interpreter.stop-command-source-on-error false", + "settings set interpreter.open-transcript-in-editor false", ] for setting in settings: - interpreter.HandleCommand(setting, lldb.SBCommandReturnObject()) + interpreter.HandleCommand(setting, lldb.SBCommandReturnObject()) inputs = [ - '# This is a comment', # Comment - 'help session', # Valid command - 'Lorem ipsum' # Invalid command + "# This is a comment", # Comment + "help session", # Valid command + "Lorem ipsum", # Invalid command ] for cmd in inputs: - res = lldb.SBCommandReturnObject() - interpreter.HandleCommand(cmd, res) - raw += self.raw_transcript_builder(cmd, res) + res = lldb.SBCommandReturnObject() + interpreter.HandleCommand(cmd, res) + raw += self.raw_transcript_builder(cmd, res) self.assertTrue(interpreter.HasCommands()) self.assertTrue(len(raw) != 0) # Check for error - cmd = 'session save /root/file' + cmd = "session save /root/file" interpreter.HandleCommand(cmd, res) self.assertFalse(res.Succeeded()) raw += self.raw_transcript_builder(cmd, res) @@ -61,33 +59,35 @@ output_file = tf.name res = lldb.SBCommandReturnObject() - interpreter.HandleCommand('session save ' + output_file, res) + interpreter.HandleCommand("session save " + output_file, res) self.assertTrue(res.Succeeded()) raw += self.raw_transcript_builder(cmd, res) with open(output_file, "r") as file: - content = file.read() - # Exclude last line, since session won't record it's own output - lines = raw.splitlines()[:-1] - for line in lines: - self.assertIn(line, content) + content = file.read() + # Exclude last line, since session won't record it's own output + lines = raw.splitlines()[:-1] + for line in lines: + self.assertIn(line, content) td = tempfile.TemporaryDirectory() res = lldb.SBCommandReturnObject() - interpreter.HandleCommand('settings set interpreter.save-session-directory ' + td.name, res) + interpreter.HandleCommand( + "settings set interpreter.save-session-directory " + td.name, res + ) self.assertTrue(res.Succeeded()) res = lldb.SBCommandReturnObject() - interpreter.HandleCommand('session save', res) + interpreter.HandleCommand("session save", res) self.assertTrue(res.Succeeded()) raw += self.raw_transcript_builder(cmd, res) with open(os.path.join(td.name, os.listdir(td.name)[0]), "r") as file: - content = file.read() - # Exclude last line, since session won't record it's own output - lines = raw.splitlines()[:-1] - for line in lines: - self.assertIn(line, content) + content = file.read() + # Exclude last line, since session won't record it's own output + lines = raw.splitlines()[:-1] + for line in lines: + self.assertIn(line, content) @skipIfWindows @no_debug_info_test @@ -98,27 +98,24 @@ td = tempfile.TemporaryDirectory() settings = [ - 'settings set interpreter.echo-commands true', - 'settings set interpreter.echo-comment-commands true', - 'settings set interpreter.stop-command-source-on-error false', - 'settings set interpreter.save-session-on-quit true', - 'settings set interpreter.save-session-directory ' + td.name, - 'settings set interpreter.open-transcript-in-editor false', + "settings set interpreter.echo-commands true", + "settings set interpreter.echo-comment-commands true", + "settings set interpreter.stop-command-source-on-error false", + "settings set interpreter.save-session-on-quit true", + "settings set interpreter.save-session-directory " + td.name, + "settings set interpreter.open-transcript-in-editor false", ] for setting in settings: - res = lldb.SBCommandReturnObject() - interpreter.HandleCommand(setting, res) - raw += self.raw_transcript_builder(setting, res) + res = lldb.SBCommandReturnObject() + interpreter.HandleCommand(setting, res) + raw += self.raw_transcript_builder(setting, res) self.dbg.Destroy(self.dbg) with open(os.path.join(td.name, os.listdir(td.name)[0]), "r") as file: - content = file.read() - # Exclude last line, since session won't record it's own output - lines = raw.splitlines()[:-1] - for line in lines: - self.assertIn(line, content) - - - + content = file.read() + # Exclude last line, since session won't record it's own output + lines = raw.splitlines()[:-1] + for line in lines: + self.assertIn(line, content) diff --git a/lldb/test/API/commands/settings/TestSettings.py b/lldb/test/API/commands/settings/TestSettings.py --- a/lldb/test/API/commands/settings/TestSettings.py +++ b/lldb/test/API/commands/settings/TestSettings.py @@ -18,10 +18,14 @@ def test_apropos_should_also_search_settings_description(self): """Test that 'apropos' command should also search descriptions for the settings variables.""" - self.expect("apropos 'environment variable'", - substrs=["target.env-vars", - "environment variables", - "executable's environment"]) + self.expect( + "apropos 'environment variable'", + substrs=[ + "target.env-vars", + "environment variables", + "executable's environment", + ], + ) def test_set_interpreter_repeat_prev_command(self): """Test the `interpreter.repeat-previous-command` setting.""" @@ -32,82 +36,87 @@ setting = "interpreter.repeat-previous-command" def cleanup(setting): - self.runCmd( - "settings clear %s" % - setting, check=False) + self.runCmd("settings clear %s" % setting, check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup(setting)) # First, check for the setting default value. - self.expect("setting show %s" % setting, - substrs=["interpreter.repeat-previous-command (boolean) = true"]) + self.expect( + "setting show %s" % setting, + substrs=["interpreter.repeat-previous-command (boolean) = true"], + ) # Then, invert the setting, and check that was set correctly self.runCmd("setting set %s false" % setting) - self.expect("setting show %s" % setting, - substrs=["interpreter.repeat-previous-command (boolean) = false"]) - + self.expect( + "setting show %s" % setting, + substrs=["interpreter.repeat-previous-command (boolean) = false"], + ) - ci = self.dbg.GetCommandInterpreter() + ci = self.dbg.GetCommandInterpreter() self.assertTrue(ci.IsValid(), "Invalid command interpreter.") # Now, test the functionnality res = lldb.SBCommandReturnObject() - ci.HandleCommand('breakpoint set -n main', res) + ci.HandleCommand("breakpoint set -n main", res) self.assertTrue(res.Succeeded(), "Command failed.") - ci.HandleCommand('', res) + ci.HandleCommand("", res) self.assertTrue(res.Succeeded(), "Empty command failed.") self.assertEqual(self.dbg.GetSelectedTarget().GetNumBreakpoints(), 1) def test_append_target_env_vars(self): """Test that 'append target.env-vars' works.""" # Append the env-vars. - self.runCmd('settings append target.env-vars MY_ENV_VAR=YES') + self.runCmd("settings append target.env-vars MY_ENV_VAR=YES") # And add hooks to restore the settings during tearDown(). - self.addTearDownHook( - lambda: self.runCmd("settings clear target.env-vars")) + self.addTearDownHook(lambda: self.runCmd("settings clear target.env-vars")) # Check it immediately! - self.expect('settings show target.env-vars', - substrs=['MY_ENV_VAR=YES']) + self.expect("settings show target.env-vars", substrs=["MY_ENV_VAR=YES"]) def test_insert_before_and_after_target_run_args(self): """Test that 'insert-before/after target.run-args' works.""" # Set the run-args first. - self.runCmd('settings set target.run-args a b c') + self.runCmd("settings set target.run-args a b c") # And add hooks to restore the settings during tearDown(). - self.addTearDownHook( - lambda: self.runCmd("settings clear target.run-args")) + self.addTearDownHook(lambda: self.runCmd("settings clear target.run-args")) # Now insert-before the index-0 element with '__a__'. - self.runCmd('settings insert-before target.run-args 0 __a__') + self.runCmd("settings insert-before target.run-args 0 __a__") # And insert-after the index-1 element with '__A__'. - self.runCmd('settings insert-after target.run-args 1 __A__') + self.runCmd("settings insert-after target.run-args 1 __A__") # Check it immediately! - self.expect('settings show target.run-args', - substrs=['target.run-args', - '[0]: "__a__"', - '[1]: "a"', - '[2]: "__A__"', - '[3]: "b"', - '[4]: "c"']) + self.expect( + "settings show target.run-args", + substrs=[ + "target.run-args", + '[0]: "__a__"', + '[1]: "a"', + '[2]: "__A__"', + '[3]: "b"', + '[4]: "c"', + ], + ) def test_replace_target_run_args(self): """Test that 'replace target.run-args' works.""" # Set the run-args and then replace the index-0 element. - self.runCmd('settings set target.run-args a b c') + self.runCmd("settings set target.run-args a b c") # And add hooks to restore the settings during tearDown(). - self.addTearDownHook( - lambda: self.runCmd("settings clear target.run-args")) + self.addTearDownHook(lambda: self.runCmd("settings clear target.run-args")) # Now replace the index-0 element with 'A', instead. - self.runCmd('settings replace target.run-args 0 A') + self.runCmd("settings replace target.run-args 0 A") # Check it immediately! - self.expect('settings show target.run-args', - substrs=['target.run-args (arguments) =', - '[0]: "A"', - '[1]: "b"', - '[2]: "c"']) + self.expect( + "settings show target.run-args", + substrs=[ + "target.run-args (arguments) =", + '[0]: "A"', + '[1]: "b"', + '[2]: "c"', + ], + ) def test_set_prompt(self): """Test that 'set prompt' actually changes the prompt.""" @@ -116,12 +125,18 @@ self.runCmd("settings set prompt 'lldb2 '") # Immediately test the setting. - self.expect("settings show prompt", SETTING_MSG("prompt"), - startstr='prompt (string) = "lldb2 "') + self.expect( + "settings show prompt", + SETTING_MSG("prompt"), + startstr='prompt (string) = "lldb2 "', + ) # The overall display should also reflect the new setting. - self.expect("settings show", SETTING_MSG("prompt"), - substrs=['prompt (string) = "lldb2 "']) + self.expect( + "settings show", + SETTING_MSG("prompt"), + substrs=['prompt (string) = "lldb2 "'], + ) # Use '-r' option to reset to the original default prompt. self.runCmd("settings clear prompt") @@ -132,12 +147,18 @@ self.runCmd("settings set term-width 70") # Immediately test the setting. - self.expect("settings show term-width", SETTING_MSG("term-width"), - startstr="term-width (int) = 70") + self.expect( + "settings show term-width", + SETTING_MSG("term-width"), + startstr="term-width (int) = 70", + ) # The overall display should also reflect the new setting. - self.expect("settings show", SETTING_MSG("term-width"), - substrs=["term-width (int) = 70"]) + self.expect( + "settings show", + SETTING_MSG("term-width"), + substrs=["term-width (int) = 70"], + ) # rdar://problem/10712130 @skipIf(oslist=["windows"], bugnumber="llvm.org/pr44431") @@ -150,16 +171,14 @@ def cleanup(): self.runCmd( - "settings set frame-format %s" % - self.format_string, check=False) + "settings set frame-format %s" % self.format_string, check=False + ) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.runCmd("settings show frame-format") - m = re.match( - '^frame-format \(format-string\) = "(.*)\"$', - self.res.GetOutput()) + m = re.match('^frame-format \(format-string\) = "(.*)"$', self.res.GetOutput()) self.assertTrue(m, "Bad settings string") self.format_string = m.group(1) @@ -169,14 +188,20 @@ self.runCmd("settings set frame-format %s" % format_string) # Immediately test the setting. - self.expect("settings show frame-format", SETTING_MSG("frame-format"), - substrs=[format_string]) + self.expect( + "settings show frame-format", + SETTING_MSG("frame-format"), + substrs=[format_string], + ) self.runCmd("breakpoint set -n main") - self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()), - RUN_SUCCEEDED) - self.expect("thread backtrace", - substrs=["`main", self.getSourceDir()]) + self.runCmd( + "process launch --working-dir '{0}'".format( + self.get_process_working_directory() + ), + RUN_SUCCEEDED, + ) + self.expect("thread backtrace", substrs=["`main", self.getSourceDir()]) def test_set_auto_confirm(self): """Test that after 'set auto-confirm true', manual confirmation should not kick in.""" @@ -188,21 +213,26 @@ self.runCmd("settings set auto-confirm true") # Immediately test the setting. - self.expect("settings show auto-confirm", SETTING_MSG("auto-confirm"), - startstr="auto-confirm (boolean) = true") + self.expect( + "settings show auto-confirm", + SETTING_MSG("auto-confirm"), + startstr="auto-confirm (boolean) = true", + ) # Now 'breakpoint delete' should just work fine without confirmation # prompt from the command interpreter. self.runCmd("breakpoint set -n main") - self.expect("breakpoint delete", - startstr="All breakpoints removed") + self.expect("breakpoint delete", startstr="All breakpoints removed") # Restore the original setting of auto-confirm. self.runCmd("settings clear auto-confirm") - self.expect("settings show auto-confirm", SETTING_MSG("auto-confirm"), - startstr="auto-confirm (boolean) = false") + self.expect( + "settings show auto-confirm", + SETTING_MSG("auto-confirm"), + startstr="auto-confirm (boolean) = false", + ) - @skipIf(archs=no_match(['x86_64', 'i386', 'i686'])) + @skipIf(archs=no_match(["x86_64", "i386", "i686"])) def test_disassembler_settings(self): """Test that user options for the disassembler take effect.""" self.build() @@ -213,34 +243,28 @@ # AT&T syntax self.runCmd("settings set target.x86-disassembly-flavor att") self.runCmd("settings set target.use-hex-immediates false") - self.expect("disassemble -n numberfn", - substrs=["$90"]) + self.expect("disassemble -n numberfn", substrs=["$90"]) self.runCmd("settings set target.use-hex-immediates true") self.runCmd("settings set target.hex-immediate-style c") - self.expect("disassemble -n numberfn", - substrs=["$0x5a"]) + self.expect("disassemble -n numberfn", substrs=["$0x5a"]) self.runCmd("settings set target.hex-immediate-style asm") - self.expect("disassemble -n numberfn", - substrs=["$5ah"]) + self.expect("disassemble -n numberfn", substrs=["$5ah"]) # Intel syntax self.runCmd("settings set target.x86-disassembly-flavor intel") self.runCmd("settings set target.use-hex-immediates false") - self.expect("disassemble -n numberfn", - substrs=["90"]) + self.expect("disassemble -n numberfn", substrs=["90"]) self.runCmd("settings set target.use-hex-immediates true") self.runCmd("settings set target.hex-immediate-style c") - self.expect("disassemble -n numberfn", - substrs=["0x5a"]) + self.expect("disassemble -n numberfn", substrs=["0x5a"]) self.runCmd("settings set target.hex-immediate-style asm") - self.expect("disassemble -n numberfn", - substrs=["5ah"]) + self.expect("disassemble -n numberfn", substrs=["5ah"]) - @skipIfDarwinEmbedded # debugserver on ios etc can't write files + @skipIfDarwinEmbedded # debugserver on ios etc can't write files def test_run_args_and_env_vars(self): self.do_test_run_args_and_env_vars(use_launchsimple=False) - @skipIfDarwinEmbedded # debugserver on ios etc can't write files + @skipIfDarwinEmbedded # debugserver on ios etc can't write files def test_launchsimple_args_and_env_vars(self): self.do_test_run_args_and_env_vars(use_launchsimple=True) @@ -250,12 +274,10 @@ # Set the run-args and the env-vars. # And add hooks to restore the settings during tearDown(). - self.runCmd('settings set target.run-args A B C') - self.addTearDownHook( - lambda: self.runCmd("settings clear target.run-args")) + self.runCmd("settings set target.run-args A B C") + self.addTearDownHook(lambda: self.runCmd("settings clear target.run-args")) self.runCmd('settings set target.env-vars ["MY_ENV_VAR"]=YES') - self.addTearDownHook( - lambda: self.runCmd("settings clear target.env-vars")) + self.addTearDownHook(lambda: self.runCmd("settings clear target.env-vars")) exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) @@ -267,25 +289,21 @@ if launch_info.GetEnvironmentEntryAtIndex(i) == "MY_ENV_VAR=YES": found_env_var = True break - self.assertTrue(found_env_var, - "MY_ENV_VAR was not set in LaunchInfo object") + self.assertTrue(found_env_var, "MY_ENV_VAR was not set in LaunchInfo object") self.assertEqual(launch_info.GetNumArguments(), 3) self.assertEqual(launch_info.GetArgumentAtIndex(0), "A") self.assertEqual(launch_info.GetArgumentAtIndex(1), "B") self.assertEqual(launch_info.GetArgumentAtIndex(2), "C") - self.expect( - 'target show-launch-environment', - substrs=["MY_ENV_VAR=YES"]) + self.expect("target show-launch-environment", substrs=["MY_ENV_VAR=YES"]) wd = self.get_process_working_directory() if use_launchsimple: process = target.LaunchSimple(None, None, wd) self.assertTrue(process) else: - self.runCmd("process launch --working-dir '{0}'".format(wd), - RUN_SUCCEEDED) + self.runCmd("process launch --working-dir '{0}'".format(wd), RUN_SUCCEEDED) # Read the output file produced by running the program. output = lldbutil.read_file_from_process_wd(self, "output2.txt") @@ -297,23 +315,25 @@ "argv[1] matches", "argv[2] matches", "argv[3] matches", - "Environment variable 'MY_ENV_VAR' successfully passed."]) + "Environment variable 'MY_ENV_VAR' successfully passed.", + ], + ) # Check that env-vars overrides unset-env-vars. - self.runCmd('settings set target.unset-env-vars MY_ENV_VAR') + self.runCmd("settings set target.unset-env-vars MY_ENV_VAR") self.expect( - 'target show-launch-environment', - 'env-vars overrides unset-env-vars', - substrs=["MY_ENV_VAR=YES"]) + "target show-launch-environment", + "env-vars overrides unset-env-vars", + substrs=["MY_ENV_VAR=YES"], + ) wd = self.get_process_working_directory() if use_launchsimple: process = target.LaunchSimple(None, None, wd) self.assertTrue(process) else: - self.runCmd("process launch --working-dir '{0}'".format(wd), - RUN_SUCCEEDED) + self.runCmd("process launch --working-dir '{0}'".format(wd), RUN_SUCCEEDED) # Read the output file produced by running the program. output = lldbutil.read_file_from_process_wd(self, "output2.txt") @@ -321,8 +341,8 @@ self.expect( output, exe=False, - substrs=[ - "Environment variable 'MY_ENV_VAR' successfully passed."]) + substrs=["Environment variable 'MY_ENV_VAR' successfully passed."], + ) @skipIfRemote # it doesn't make sense to send host env to remote target def test_pass_host_env_vars(self): @@ -337,6 +357,7 @@ def unset_env_variables(): os.environ.pop("MY_HOST_ENV_VAR1") os.environ.pop("MY_HOST_ENV_VAR2") + self.addTearDownHook(unset_env_variables) exe = self.getBuildArtifact("a.out") @@ -344,16 +365,22 @@ # By default, inherit-env is 'true'. self.expect( - 'settings show target.inherit-env', + "settings show target.inherit-env", "Default inherit-env is 'true'", - startstr="target.inherit-env (boolean) = true") + startstr="target.inherit-env (boolean) = true", + ) self.expect( - 'target show-launch-environment', - 'Host environment is passed correctly', - substrs=['MY_HOST_ENV_VAR1=VAR1', 'MY_HOST_ENV_VAR2=VAR2']) - self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()), - RUN_SUCCEEDED) + "target show-launch-environment", + "Host environment is passed correctly", + substrs=["MY_HOST_ENV_VAR1=VAR1", "MY_HOST_ENV_VAR2=VAR2"], + ) + self.runCmd( + "process launch --working-dir '{0}'".format( + self.get_process_working_directory() + ), + RUN_SUCCEEDED, + ) # Read the output file produced by running the program. output = lldbutil.read_file_from_process_wd(self, "output1.txt") @@ -363,20 +390,27 @@ exe=False, substrs=[ "The host environment variable 'MY_HOST_ENV_VAR1' successfully passed.", - "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed."]) + "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed.", + ], + ) # Now test that we can prevent the inferior from inheriting the # environment. - self.runCmd('settings set target.inherit-env false') + self.runCmd("settings set target.inherit-env false") self.expect( - 'target show-launch-environment', - 'target.inherit-env affects `target show-launch-environment`', + "target show-launch-environment", + "target.inherit-env affects `target show-launch-environment`", matching=False, - substrs = ['MY_HOST_ENV_VAR1=VAR1', 'MY_HOST_ENV_VAR2=VAR2']) + substrs=["MY_HOST_ENV_VAR1=VAR1", "MY_HOST_ENV_VAR2=VAR2"], + ) - self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()), - RUN_SUCCEEDED) + self.runCmd( + "process launch --working-dir '{0}'".format( + self.get_process_working_directory() + ), + RUN_SUCCEEDED, + ) # Read the output file produced by running the program. output = lldbutil.read_file_from_process_wd(self, "output1.txt") @@ -387,40 +421,52 @@ matching=False, substrs=[ "The host environment variable 'MY_HOST_ENV_VAR1' successfully passed.", - "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed."]) + "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed.", + ], + ) # Now test that we can unset variables from the inherited environment. - self.runCmd('settings set target.inherit-env true') - self.runCmd('settings set target.unset-env-vars MY_HOST_ENV_VAR1') - self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()), - RUN_SUCCEEDED) + self.runCmd("settings set target.inherit-env true") + self.runCmd("settings set target.unset-env-vars MY_HOST_ENV_VAR1") + self.runCmd( + "process launch --working-dir '{0}'".format( + self.get_process_working_directory() + ), + RUN_SUCCEEDED, + ) # Read the output file produced by running the program. output = lldbutil.read_file_from_process_wd(self, "output1.txt") self.expect( - 'target show-launch-environment', - 'MY_HOST_ENV_VAR1 is unset, it shouldn\'t be in `target show-launch-environment`', + "target show-launch-environment", + "MY_HOST_ENV_VAR1 is unset, it shouldn't be in `target show-launch-environment`", matching=False, - substrs = ['MY_HOST_ENV_VAR1=VAR1']) + substrs=["MY_HOST_ENV_VAR1=VAR1"], + ) self.expect( - 'target show-launch-environment', - 'MY_HOST_ENV_VAR2 shouldn be in `target show-launch-environment`', - substrs = ['MY_HOST_ENV_VAR2=VAR2']) + "target show-launch-environment", + "MY_HOST_ENV_VAR2 shouldn be in `target show-launch-environment`", + substrs=["MY_HOST_ENV_VAR2=VAR2"], + ) self.expect( output, exe=False, matching=False, substrs=[ - "The host environment variable 'MY_HOST_ENV_VAR1' successfully passed."]) + "The host environment variable 'MY_HOST_ENV_VAR1' successfully passed." + ], + ) self.expect( output, exe=False, substrs=[ - "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed."]) + "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed." + ], + ) - @skipIfDarwinEmbedded # debugserver on ios etc can't write files + @skipIfDarwinEmbedded # debugserver on ios etc can't write files def test_set_error_output_path(self): """Test that setting target.error/output-path for the launched process works.""" self.build() @@ -429,26 +475,38 @@ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Set the error-path and output-path and verify both are set. - self.runCmd("settings set target.error-path '{0}'".format( - lldbutil.append_to_process_working_directory(self, "stderr.txt"))) - self.runCmd("settings set target.output-path '{0}".format( - lldbutil.append_to_process_working_directory(self, "stdout.txt"))) + self.runCmd( + "settings set target.error-path '{0}'".format( + lldbutil.append_to_process_working_directory(self, "stderr.txt") + ) + ) + self.runCmd( + "settings set target.output-path '{0}".format( + lldbutil.append_to_process_working_directory(self, "stdout.txt") + ) + ) # And add hooks to restore the original settings during tearDown(). - self.addTearDownHook( - lambda: self.runCmd("settings clear target.output-path")) - self.addTearDownHook( - lambda: self.runCmd("settings clear target.error-path")) + self.addTearDownHook(lambda: self.runCmd("settings clear target.output-path")) + self.addTearDownHook(lambda: self.runCmd("settings clear target.error-path")) - self.expect("settings show target.error-path", - SETTING_MSG("target.error-path"), - substrs=['target.error-path (file)', 'stderr.txt"']) + self.expect( + "settings show target.error-path", + SETTING_MSG("target.error-path"), + substrs=["target.error-path (file)", 'stderr.txt"'], + ) - self.expect("settings show target.output-path", - SETTING_MSG("target.output-path"), - substrs=['target.output-path (file)', 'stdout.txt"']) + self.expect( + "settings show target.output-path", + SETTING_MSG("target.output-path"), + substrs=["target.output-path (file)", 'stdout.txt"'], + ) - self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()), - RUN_SUCCEEDED) + self.runCmd( + "process launch --working-dir '{0}'".format( + self.get_process_working_directory() + ), + RUN_SUCCEEDED, + ) output = lldbutil.read_file_from_process_wd(self, "stderr.txt") message = "This message should go to standard error." @@ -458,57 +516,63 @@ self.expect(output, exe=False, startstr=message) output = lldbutil.read_file_from_process_wd(self, "stdout.txt") - self.expect(output, exe=False, - startstr="This message should go to standard out.") + self.expect( + output, exe=False, startstr="This message should go to standard out." + ) def test_print_dictionary_setting(self): self.runCmd("settings clear target.env-vars") - self.runCmd("settings set target.env-vars [\"MY_VAR\"]=some-value") - self.expect("settings show target.env-vars", - substrs=["MY_VAR=some-value"]) + self.runCmd('settings set target.env-vars ["MY_VAR"]=some-value') + self.expect("settings show target.env-vars", substrs=["MY_VAR=some-value"]) self.runCmd("settings clear target.env-vars") def test_print_array_setting(self): self.runCmd("settings clear target.run-args") self.runCmd("settings set target.run-args gobbledy-gook") - self.expect("settings show target.run-args", - substrs=['[0]: "gobbledy-gook"']) + self.expect("settings show target.run-args", substrs=['[0]: "gobbledy-gook"']) self.runCmd("settings clear target.run-args") def test_settings_with_quotes(self): self.runCmd("settings clear target.run-args") self.runCmd("settings set target.run-args a b c") - self.expect("settings show target.run-args", - substrs=['[0]: "a"', - '[1]: "b"', - '[2]: "c"']) + self.expect( + "settings show target.run-args", + substrs=['[0]: "a"', '[1]: "b"', '[2]: "c"'], + ) self.runCmd("settings set target.run-args 'a b c'") - self.expect("settings show target.run-args", - substrs=['[0]: "a b c"']) + self.expect("settings show target.run-args", substrs=['[0]: "a b c"']) self.runCmd("settings clear target.run-args") self.runCmd("settings clear target.env-vars") self.runCmd( - 'settings set target.env-vars ["MY_FILE"]="this is a file name with spaces.txt"') - self.expect("settings show target.env-vars", - substrs=['MY_FILE=this is a file name with spaces.txt']) + 'settings set target.env-vars ["MY_FILE"]="this is a file name with spaces.txt"' + ) + self.expect( + "settings show target.env-vars", + substrs=["MY_FILE=this is a file name with spaces.txt"], + ) self.runCmd("settings clear target.env-vars") # Test and make sure that setting "format-string" settings obeys quotes # if they are provided self.runCmd("settings set thread-format 'abc def' ") - self.expect("settings show thread-format", - startstr='thread-format (format-string) = "abc def"') + self.expect( + "settings show thread-format", + startstr='thread-format (format-string) = "abc def"', + ) self.runCmd('settings set thread-format "abc def" ') - self.expect("settings show thread-format", - startstr='thread-format (format-string) = "abc def"') + self.expect( + "settings show thread-format", + startstr='thread-format (format-string) = "abc def"', + ) # Make sure when no quotes are provided that we maintain any trailing # spaces - self.runCmd('settings set thread-format abc def ') - self.expect("settings show thread-format", - startstr='thread-format (format-string) = "abc def "') - self.runCmd('settings clear thread-format') + self.runCmd("settings set thread-format abc def ") + self.expect( + "settings show thread-format", + startstr='thread-format (format-string) = "abc def "', + ) + self.runCmd("settings clear thread-format") def test_settings_with_trailing_whitespace(self): - # boolean # Set to known value self.runCmd("settings set target.skip-prologue true") @@ -518,40 +582,48 @@ self.expect( "settings show target.skip-prologue", SETTING_MSG("target.skip-prologue"), - startstr="target.skip-prologue (boolean) = false") + startstr="target.skip-prologue (boolean) = false", + ) self.runCmd("settings clear target.skip-prologue", check=False) # integer - self.runCmd("settings set term-width 70") # Set to known value + self.runCmd("settings set term-width 70") # Set to known value # Set to new value with trailing whitespaces self.runCmd("settings set term-width 60 \t") - self.expect("settings show term-width", SETTING_MSG("term-width"), - startstr="term-width (int) = 60") + self.expect( + "settings show term-width", + SETTING_MSG("term-width"), + startstr="term-width (int) = 60", + ) self.runCmd("settings clear term-width", check=False) # string - self.runCmd("settings set target.arg0 abc") # Set to known value + self.runCmd("settings set target.arg0 abc") # Set to known value # Set to new value with trailing whitespaces self.runCmd("settings set target.arg0 cde\t ") - self.expect("settings show target.arg0", SETTING_MSG("target.arg0"), - startstr='target.arg0 (string) = "cde"') + self.expect( + "settings show target.arg0", + SETTING_MSG("target.arg0"), + startstr='target.arg0 (string) = "cde"', + ) self.runCmd("settings clear target.arg0", check=False) # file path1 = self.getBuildArtifact("path1.txt") path2 = self.getBuildArtifact("path2.txt") - self.runCmd( - "settings set target.output-path %s" % - path1) # Set to known value + self.runCmd("settings set target.output-path %s" % path1) # Set to known value self.expect( "settings show target.output-path", SETTING_MSG("target.output-path"), - startstr='target.output-path (file) = ', - substrs=[path1]) - self.runCmd("settings set target.output-path %s " % - path2) # Set to new value with trailing whitespaces + startstr="target.output-path (file) = ", + substrs=[path1], + ) + self.runCmd( + "settings set target.output-path %s " % path2 + ) # Set to new value with trailing whitespaces self.expect( "settings show target.output-path", SETTING_MSG("target.output-path"), - startstr='target.output-path (file) = ', - substrs=[path2]) + startstr="target.output-path (file) = ", + substrs=[path2], + ) self.runCmd("settings clear target.output-path", check=False) # enum # Set to known value @@ -561,7 +633,8 @@ self.expect( "settings show stop-disassembly-display", SETTING_MSG("stop-disassembly-display"), - startstr='stop-disassembly-display (enum) = always') + startstr="stop-disassembly-display (enum) = always", + ) self.runCmd("settings clear stop-disassembly-display", check=False) # language # Set to known value @@ -571,7 +644,8 @@ self.expect( "settings show target.language", SETTING_MSG("target.language"), - startstr="target.language (language) = c11") + startstr="target.language (language) = c11", + ) self.runCmd("settings clear target.language", check=False) # arguments self.runCmd("settings set target.run-args 1 2 3") # Set to known value @@ -581,10 +655,12 @@ "settings show target.run-args", SETTING_MSG("target.run-args"), substrs=[ - 'target.run-args (arguments) =', + "target.run-args (arguments) =", '[0]: "3"', '[1]: "4"', - '[2]: "5"']) + '[2]: "5"', + ], + ) self.runCmd("settings set target.run-args 1 2 3") # Set to known value # Set to new value with trailing whitespaces self.runCmd("settings set target.run-args 3 \ \ ") @@ -592,10 +668,12 @@ "settings show target.run-args", SETTING_MSG("target.run-args"), substrs=[ - 'target.run-args (arguments) =', + "target.run-args (arguments) =", '[0]: "3"', '[1]: " "', - '[2]: " "']) + '[2]: " "', + ], + ) self.runCmd("settings clear target.run-args", check=False) # dictionaries self.runCmd("settings clear target.env-vars") # Set to known value @@ -604,38 +682,43 @@ self.expect( "settings show target.env-vars", SETTING_MSG("target.env-vars"), - substrs=[ - 'target.env-vars (dictionary of strings) =', - 'A=B', - 'C=D']) + substrs=["target.env-vars (dictionary of strings) =", "A=B", "C=D"], + ) self.runCmd("settings clear target.env-vars", check=False) # regex # Set to known value self.runCmd("settings clear target.process.thread.step-avoid-regexp") # Set to new value with trailing whitespaces - self.runCmd( - "settings set target.process.thread.step-avoid-regexp foo\\ ") + self.runCmd("settings set target.process.thread.step-avoid-regexp foo\\ ") self.expect( "settings show target.process.thread.step-avoid-regexp", SETTING_MSG("target.process.thread.step-avoid-regexp"), - substrs=['target.process.thread.step-avoid-regexp (regex) = foo\\ ']) + substrs=["target.process.thread.step-avoid-regexp (regex) = foo\\ "], + ) self.runCmd( - "settings clear target.process.thread.step-avoid-regexp", - check=False) + "settings clear target.process.thread.step-avoid-regexp", check=False + ) # format-string self.runCmd("settings clear disassembly-format") # Set to known value # Set to new value with trailing whitespaces self.runCmd("settings set disassembly-format foo ") - self.expect("settings show disassembly-format", - SETTING_MSG("disassembly-format"), - substrs=['disassembly-format (format-string) = "foo "']) + self.expect( + "settings show disassembly-format", + SETTING_MSG("disassembly-format"), + substrs=['disassembly-format (format-string) = "foo "'], + ) self.runCmd("settings clear disassembly-format", check=False) def test_settings_list(self): # List settings (and optionally test the filter to only show 'target' settings). - self.expect("settings list target", substrs=["arg0", "detach-on-error", "language"]) + self.expect( + "settings list target", substrs=["arg0", "detach-on-error", "language"] + ) self.expect("settings list target", matching=False, substrs=["packet-timeout"]) - self.expect("settings list", substrs=["language", "arg0", "detach-on-error", "packet-timeout"]) + self.expect( + "settings list", + substrs=["language", "arg0", "detach-on-error", "packet-timeout"], + ) def test_settings_remove_single(self): # Set some environment variables and use 'remove' to delete them. @@ -645,30 +728,46 @@ self.expect("settings show target.env-vars", matching=False, substrs=["a=b"]) self.expect("settings show target.env-vars", substrs=["c=d"]) self.runCmd("settings remove target.env-vars c") - self.expect("settings show target.env-vars", matching=False, substrs=["a=b", "c=d"]) + self.expect( + "settings show target.env-vars", matching=False, substrs=["a=b", "c=d"] + ) def test_settings_remove_multiple(self): self.runCmd("settings set target.env-vars a=b c=d e=f") self.expect("settings show target.env-vars", substrs=["a=b", "c=d", "e=f"]) self.runCmd("settings remove target.env-vars a e") - self.expect("settings show target.env-vars", matching=False, substrs=["a=b", "e=f"]) + self.expect( + "settings show target.env-vars", matching=False, substrs=["a=b", "e=f"] + ) self.expect("settings show target.env-vars", substrs=["c=d"]) def test_settings_remove_nonexistent_value(self): - self.expect("settings remove target.env-vars doesntexist", error=True, - substrs=["no value found named 'doesntexist'"]) + self.expect( + "settings remove target.env-vars doesntexist", + error=True, + substrs=["no value found named 'doesntexist'"], + ) def test_settings_remove_nonexistent_settings(self): - self.expect("settings remove doesntexist alsodoesntexist", error=True, - substrs=["error: invalid value path 'doesntexist'"]) + self.expect( + "settings remove doesntexist alsodoesntexist", + error=True, + substrs=["error: invalid value path 'doesntexist'"], + ) def test_settings_remove_missing_arg(self): - self.expect("settings remove", error=True, - substrs=["'settings remove' takes an array or dictionary item, or"]) + self.expect( + "settings remove", + error=True, + substrs=["'settings remove' takes an array or dictionary item, or"], + ) def test_settings_remove_empty_arg(self): - self.expect("settings remove ''", error=True, - substrs=["'settings remove' command requires a valid variable name"]) + self.expect( + "settings remove ''", + error=True, + substrs=["'settings remove' command requires a valid variable name"], + ) def test_settings_clear_all(self): # Change a dictionary. @@ -684,8 +783,14 @@ self.runCmd("settings clear --all") # Check that settings have their default values after clearing. - self.expect("settings show target.env-vars", patterns=['^target.env-vars \(dictionary of strings\) =\s*$']) - self.expect("settings show target.run-args", patterns=['^target.run-args \(arguments\) =\s*$']) + self.expect( + "settings show target.env-vars", + patterns=["^target.env-vars \(dictionary of strings\) =\s*$"], + ) + self.expect( + "settings show target.run-args", + patterns=["^target.run-args \(arguments\) =\s*$"], + ) self.expect("settings show auto-confirm", substrs=["false"]) self.expect("settings show tab-size", substrs=["4"]) @@ -694,51 +799,55 @@ "settings clear --all auto-confirm", COMMAND_FAILED_AS_EXPECTED, error=True, - substrs=["'settings clear --all' doesn't take any arguments"]) + substrs=["'settings clear --all' doesn't take any arguments"], + ) def test_all_settings_exist(self): - self.expect("settings show", - substrs=["auto-confirm", - "frame-format", - "notify-void", - "prompt", - "script-lang", - "stop-disassembly-count", - "stop-disassembly-display", - "stop-line-count-after", - "stop-line-count-before", - "stop-show-column", - "term-width", - "thread-format", - "use-external-editor", - "target.breakpoints-use-platform-avoid-list", - "target.default-arch", - "target.disable-aslr", - "target.disable-stdio", - "target.x86-disassembly-flavor", - "target.enable-synthetic-value", - "target.env-vars", - "target.error-path", - "target.exec-search-paths", - "target.expr-prefix", - "target.hex-immediate-style", - "target.inherit-env", - "target.input-path", - "target.language", - "target.max-children-count", - "target.max-string-summary-length", - "target.move-to-nearest-code", - "target.output-path", - "target.prefer-dynamic-value", - "target.run-args", - "target.skip-prologue", - "target.source-map", - "target.use-hex-immediates", - "target.process.disable-memory-cache", - "target.process.extra-startup-command", - "target.process.thread.trace-thread", - "target.process.thread.step-avoid-regexp", - ]) + self.expect( + "settings show", + substrs=[ + "auto-confirm", + "frame-format", + "notify-void", + "prompt", + "script-lang", + "stop-disassembly-count", + "stop-disassembly-display", + "stop-line-count-after", + "stop-line-count-before", + "stop-show-column", + "term-width", + "thread-format", + "use-external-editor", + "target.breakpoints-use-platform-avoid-list", + "target.default-arch", + "target.disable-aslr", + "target.disable-stdio", + "target.x86-disassembly-flavor", + "target.enable-synthetic-value", + "target.env-vars", + "target.error-path", + "target.exec-search-paths", + "target.expr-prefix", + "target.hex-immediate-style", + "target.inherit-env", + "target.input-path", + "target.language", + "target.max-children-count", + "target.max-string-summary-length", + "target.move-to-nearest-code", + "target.output-path", + "target.prefer-dynamic-value", + "target.run-args", + "target.skip-prologue", + "target.source-map", + "target.use-hex-immediates", + "target.process.disable-memory-cache", + "target.process.extra-startup-command", + "target.process.thread.trace-thread", + "target.process.thread.step-avoid-regexp", + ], + ) # settings under an ".experimental" domain should have two properties: # 1. If the name does not exist with "experimental" in the name path, @@ -756,19 +865,34 @@ # Set target.arg0 to a known value, check that we can retrieve it via # the actual name and via .experimental. - self.expect('settings set target.arg0 first-value') - self.expect('settings show target.arg0', substrs=['first-value']) - self.expect('settings show target.experimental.arg0', substrs=['first-value'], error=False) + self.expect("settings set target.arg0 first-value") + self.expect("settings show target.arg0", substrs=["first-value"]) + self.expect( + "settings show target.experimental.arg0", + substrs=["first-value"], + error=False, + ) # Set target.arg0 to a new value via a target.experimental.arg0 name, # verify that we can read it back via both .experimental., and not. - self.expect('settings set target.experimental.arg0 second-value', error=False) - self.expect('settings show target.arg0', substrs=['second-value']) - self.expect('settings show target.experimental.arg0', substrs=['second-value'], error=False) + self.expect("settings set target.experimental.arg0 second-value", error=False) + self.expect("settings show target.arg0", substrs=["second-value"]) + self.expect( + "settings show target.experimental.arg0", + substrs=["second-value"], + error=False, + ) # showing & setting an undefined .experimental. setting should generate no errors. - self.expect('settings show target.experimental.setting-which-does-not-exist', patterns=['^\s$'], error=False) - self.expect('settings set target.experimental.setting-which-does-not-exist true', error=False) + self.expect( + "settings show target.experimental.setting-which-does-not-exist", + patterns=["^\s$"], + error=False, + ) + self.expect( + "settings set target.experimental.setting-which-does-not-exist true", + error=False, + ) # A domain component before .experimental. which does not exist should give an error # But the code does not yet do that. @@ -776,19 +900,19 @@ # finally, confirm that trying to set a setting that does not exist still fails. # (SHOWING a setting that does not exist does not currently yield an error.) - self.expect('settings set target.setting-which-does-not-exist true', error=True) + self.expect("settings set target.setting-which-does-not-exist true", error=True) def test_settings_set_exists(self): cmdinterp = self.dbg.GetCommandInterpreter() # An unknown option should succeed. - self.expect('settings set -e foo bar') - self.expect('settings set --exists foo bar') + self.expect("settings set -e foo bar") + self.expect("settings set --exists foo bar") # A known option should fail if its argument is invalid. self.expect("settings set auto-confirm bogus", error=True) - def get_setting_json(self, setting_path = None): + def get_setting_json(self, setting_path=None): settings_data = self.dbg.GetSetting(setting_path) stream = lldb.SBStream() settings_data.GetAsJSON(stream) @@ -801,15 +925,15 @@ def test_settings_api(self): """ - Test that ensures SBDebugger::GetSetting() APIs - can correctly fetch settings. + Test that ensures SBDebugger::GetSetting() APIs + can correctly fetch settings. """ # Test basic values and embedding special JSON escaping characters. self.runCmd("settings set auto-confirm true") self.runCmd("settings set tab-size 2") - arg_value = "hello \"world\"" - self.runCmd('settings set target.arg0 %s' % arg_value) + arg_value = 'hello "world"' + self.runCmd("settings set target.arg0 %s" % arg_value) settings_json = self.get_setting_json() self.assertEqual(settings_json["auto-confirm"], True) @@ -820,7 +944,9 @@ self.assertEqual(settings_data, arg_value) # Test OptionValueFileSpec - self.verify_setting_value_json("platform.module-cache-directory", self.get_process_working_directory()) + self.verify_setting_value_json( + "platform.module-cache-directory", self.get_process_working_directory() + ) # Test OptionValueArray setting_path = "target.run-args" @@ -839,7 +965,9 @@ self.verify_setting_value_json("thread-stop-format", setting_value) # Test OptionValueRegex - self.verify_setting_value_json("target.process.thread.step-avoid-regexp", "^std::") + self.verify_setting_value_json( + "target.process.thread.step-avoid-regexp", "^std::" + ) # Test OptionValueLanguage self.verify_setting_value_json("repl-lang", "c++") diff --git a/lldb/test/API/commands/settings/quoting/TestQuoting.py b/lldb/test/API/commands/settings/quoting/TestQuoting.py --- a/lldb/test/API/commands/settings/quoting/TestQuoting.py +++ b/lldb/test/API/commands/settings/quoting/TestQuoting.py @@ -32,13 +32,13 @@ self.expect_args("'a b\\' c", "a b\\\0c\0") # Double quote escape. self.expect_args('"a b\\" c"', 'a b" c\0') - self.expect_args('"a b\\\\" c', 'a b\\\0c\0') + self.expect_args('"a b\\\\" c', "a b\\\0c\0") # Single quote in double quotes. self.expect_args('"a\'b"', "a'b\0") # Double quotes in single quote. self.expect_args("'a\"b'", 'a"b\0') # Combined quotes. - self.expect_args('"a b"c\'d e\'', 'a bcd e\0') + self.expect_args("\"a b\"c'd e'", "a bcd e\0") # Bare single/double quotes. self.expect_args("a\\'b", "a'b\0") self.expect_args('a\\"b', 'a"b\0') @@ -51,7 +51,9 @@ outfile = self.getBuildArtifact(filename) if lldb.remote_platform: - outfile_arg = os.path.join(lldb.remote_platform.GetWorkingDirectory(), filename) + outfile_arg = os.path.join( + lldb.remote_platform.GetWorkingDirectory(), filename + ) else: outfile_arg = outfile @@ -62,7 +64,7 @@ dst_file_spec = lldb.SBFileSpec(outfile, True) lldb.remote_platform.Get(src_file_spec, dst_file_spec) - with open(outfile, 'r') as f: + with open(outfile, "r") as f: output = f.read() self.RemoveTempFile(outfile) diff --git a/lldb/test/API/commands/settings/use_source_cache/TestUseSourceCache.py b/lldb/test/API/commands/settings/use_source_cache/TestUseSourceCache.py --- a/lldb/test/API/commands/settings/use_source_cache/TestUseSourceCache.py +++ b/lldb/test/API/commands/settings/use_source_cache/TestUseSourceCache.py @@ -9,6 +9,7 @@ from lldbsuite.test import lldbutil from shutil import copy + class SettingsUseSourceCacheTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True @@ -17,7 +18,7 @@ self.set_use_source_cache_and_test(False) @skipIf(hostoslist=no_match(["windows"])) - @skipIf(oslist=['windows'], archs=['aarch64']) # Fails on windows 11 + @skipIf(oslist=["windows"], archs=["aarch64"]) # Fails on windows 11 def test_set_use_source_cache_true(self): """Test that after 'set use-source-cache false', files are locked.""" self.set_use_source_cache_and_test(True) @@ -28,19 +29,19 @@ # Enable/Disable source cache self.runCmd( - "settings set use-source-cache " + - ("true" if is_cache_enabled else "false")) + "settings set use-source-cache " + ("true" if is_cache_enabled else "false") + ) # Get paths for the main source file. src = self.getBuildArtifact("main-copy.cpp") self.assertTrue(src) # Make sure source file is bigger than 16K to trigger memory mapping - self.assertGreater(os.stat(src).st_size, 4*4096) + self.assertGreater(os.stat(src).st_size, 4 * 4096) target, process, thread, breakpoint = lldbutil.run_to_name_breakpoint( - self, - "calc") + self, "calc" + ) # Show the source file contents to make sure LLDB loads src file. self.runCmd("source list") @@ -50,13 +51,13 @@ if is_cache_enabled: self.assertFalse( - is_file_removed, - "Source cache is enabled, but delete file succeeded") - + is_file_removed, "Source cache is enabled, but delete file succeeded" + ) + if not is_cache_enabled: self.assertTrue( - is_file_removed, - "Source cache is disabled, but delete file failed") + is_file_removed, "Source cache is disabled, but delete file failed" + ) def removeFile(self, src): """Remove file and return true iff file was successfully removed.""" @@ -65,4 +66,3 @@ return True except Exception: return False - diff --git a/lldb/test/API/commands/statistics/basic/TestStats.py b/lldb/test/API/commands/statistics/basic/TestStats.py --- a/lldb/test/API/commands/statistics/basic/TestStats.py +++ b/lldb/test/API/commands/statistics/basic/TestStats.py @@ -5,8 +5,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True def test_enable_disable(self): @@ -20,25 +20,39 @@ self.build() target = self.createTestTarget() - self.expect("statistics disable", substrs=['need to enable statistics before disabling'], error=True) + self.expect( + "statistics disable", + substrs=["need to enable statistics before disabling"], + error=True, + ) self.expect("statistics enable") - self.expect("statistics enable", substrs=['already enabled'], error=True) + self.expect("statistics enable", substrs=["already enabled"], error=True) self.expect("statistics disable") - self.expect("statistics disable", substrs=['need to enable statistics before disabling'], error=True) + self.expect( + "statistics disable", + substrs=["need to enable statistics before disabling"], + error=True, + ) def verify_key_in_dict(self, key, d, description): - self.assertEqual(key in d, True, - 'make sure key "%s" is in dictionary %s' % (key, description)) + self.assertEqual( + key in d, + True, + 'make sure key "%s" is in dictionary %s' % (key, description), + ) def verify_key_not_in_dict(self, key, d, description): - self.assertEqual(key in d, False, - 'make sure key "%s" is in dictionary %s' % (key, description)) + self.assertEqual( + key in d, + False, + 'make sure key "%s" is in dictionary %s' % (key, description), + ) def verify_keys(self, dict, description, keys_exist, keys_missing=None): """ - Verify that all keys in "keys_exist" list are top level items in - "dict", and that all keys in "keys_missing" do not exist as top - level items in "dict". + Verify that all keys in "keys_exist" list are top level items in + "dict", and that all keys in "keys_missing" do not exist as top + level items in "dict". """ if keys_exist: for key in keys_exist: @@ -50,10 +64,12 @@ def verify_success_fail_count(self, stats, key, num_successes, num_fails): self.verify_key_in_dict(key, stats, 'stats["%s"]' % (key)) success_fail_dict = stats[key] - self.assertEqual(success_fail_dict['successes'], num_successes, - 'make sure success count') - self.assertEqual(success_fail_dict['failures'], num_fails, - 'make sure success count') + self.assertEqual( + success_fail_dict["successes"], num_successes, "make sure success count" + ) + self.assertEqual( + success_fail_dict["failures"], num_fails, "make sure success count" + ) def get_target_stats(self, debug_stats): if "targets" in debug_stats: @@ -62,14 +78,18 @@ def test_expressions_frame_var_counts(self): self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", - lldb.SBFileSpec("main.c")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.c") + ) - self.expect("expr patatino", substrs=['27']) + self.expect("expr patatino", substrs=["27"]) stats = self.get_target_stats(self.get_stats()) - self.verify_success_fail_count(stats, 'expressionEvaluation', 1, 0) - self.expect("expr doesnt_exist", error=True, - substrs=["undeclared identifier 'doesnt_exist'"]) + self.verify_success_fail_count(stats, "expressionEvaluation", 1, 0) + self.expect( + "expr doesnt_exist", + error=True, + substrs=["undeclared identifier 'doesnt_exist'"], + ) # Doesn't successfully execute. self.expect("expr int *i = nullptr; *i", error=True) # Interpret an integer as an array with 3 elements is a failure for @@ -79,23 +99,28 @@ # from all sources instead of just through the command, so this was # changed. If we want to track command success and fails, we can do # so using another metric. - self.expect("expr -Z 3 -- 1", error=True, - substrs=["expression cannot be used with --element-count"]) + self.expect( + "expr -Z 3 -- 1", + error=True, + substrs=["expression cannot be used with --element-count"], + ) # We should have gotten 3 new failures and the previous success. stats = self.get_target_stats(self.get_stats()) - self.verify_success_fail_count(stats, 'expressionEvaluation', 2, 2) + self.verify_success_fail_count(stats, "expressionEvaluation", 2, 2) self.expect("statistics enable") # 'frame var' with enabled statistics will change stats. - self.expect("frame var", substrs=['27']) + self.expect("frame var", substrs=["27"]) stats = self.get_target_stats(self.get_stats()) - self.verify_success_fail_count(stats, 'frameVariable', 1, 0) + self.verify_success_fail_count(stats, "frameVariable", 1, 0) # Test that "stopCount" is available when the process has run - self.assertEqual('stopCount' in stats, True, - 'ensure "stopCount" is in target JSON') - self.assertGreater(stats['stopCount'], 0, - 'make sure "stopCount" is greater than zero') + self.assertEqual( + "stopCount" in stats, True, 'ensure "stopCount" is in target JSON' + ) + self.assertGreater( + stats["stopCount"], 0, 'make sure "stopCount" is greater than zero' + ) def test_default_no_run(self): """Test "statistics dump" without running the target. @@ -135,33 +160,30 @@ target = self.createTestTarget() debug_stats = self.get_stats() debug_stat_keys = [ - 'memory', - 'modules', - 'targets', - 'totalSymbolTableParseTime', - 'totalSymbolTableIndexTime', - 'totalSymbolTablesLoadedFromCache', - 'totalSymbolTablesSavedToCache', - 'totalDebugInfoByteSize', - 'totalDebugInfoIndexTime', - 'totalDebugInfoIndexLoadedFromCache', - 'totalDebugInfoIndexSavedToCache', - 'totalDebugInfoParseTime', + "memory", + "modules", + "targets", + "totalSymbolTableParseTime", + "totalSymbolTableIndexTime", + "totalSymbolTablesLoadedFromCache", + "totalSymbolTablesSavedToCache", + "totalDebugInfoByteSize", + "totalDebugInfoIndexTime", + "totalDebugInfoIndexLoadedFromCache", + "totalDebugInfoIndexSavedToCache", + "totalDebugInfoParseTime", ] self.verify_keys(debug_stats, '"debug_stats"', debug_stat_keys, None) - stats = debug_stats['targets'][0] + stats = debug_stats["targets"][0] keys_exist = [ - 'expressionEvaluation', - 'frameVariable', - 'moduleIdentifiers', - 'targetCreateTime', - ] - keys_missing = [ - 'firstStopTime', - 'launchOrAttachTime' + "expressionEvaluation", + "frameVariable", + "moduleIdentifiers", + "targetCreateTime", ] + keys_missing = ["firstStopTime", "launchOrAttachTime"] self.verify_keys(stats, '"stats"', keys_exist, keys_missing) - self.assertGreater(stats['targetCreateTime'], 0.0) + self.assertGreater(stats["targetCreateTime"], 0.0) def test_default_with_run(self): """Test "statistics dump" when running the target to a breakpoint. @@ -201,134 +223,134 @@ """ self.build() target = self.createTestTarget() - lldbutil.run_to_source_breakpoint(self, "// break here", - lldb.SBFileSpec("main.c")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.c") + ) debug_stats = self.get_stats() debug_stat_keys = [ - 'memory', - 'modules', - 'targets', - 'totalSymbolTableParseTime', - 'totalSymbolTableIndexTime', - 'totalSymbolTablesLoadedFromCache', - 'totalSymbolTablesSavedToCache', - 'totalDebugInfoByteSize', - 'totalDebugInfoIndexTime', - 'totalDebugInfoIndexLoadedFromCache', - 'totalDebugInfoIndexSavedToCache', - 'totalDebugInfoParseTime', + "memory", + "modules", + "targets", + "totalSymbolTableParseTime", + "totalSymbolTableIndexTime", + "totalSymbolTablesLoadedFromCache", + "totalSymbolTablesSavedToCache", + "totalDebugInfoByteSize", + "totalDebugInfoIndexTime", + "totalDebugInfoIndexLoadedFromCache", + "totalDebugInfoIndexSavedToCache", + "totalDebugInfoParseTime", ] self.verify_keys(debug_stats, '"debug_stats"', debug_stat_keys, None) - stats = debug_stats['targets'][0] + stats = debug_stats["targets"][0] keys_exist = [ - 'expressionEvaluation', - 'firstStopTime', - 'frameVariable', - 'launchOrAttachTime', - 'moduleIdentifiers', - 'targetCreateTime', + "expressionEvaluation", + "firstStopTime", + "frameVariable", + "launchOrAttachTime", + "moduleIdentifiers", + "targetCreateTime", ] self.verify_keys(stats, '"stats"', keys_exist, None) - self.assertGreater(stats['firstStopTime'], 0.0) - self.assertGreater(stats['launchOrAttachTime'], 0.0) - self.assertGreater(stats['targetCreateTime'], 0.0) + self.assertGreater(stats["firstStopTime"], 0.0) + self.assertGreater(stats["launchOrAttachTime"], 0.0) + self.assertGreater(stats["targetCreateTime"], 0.0) def test_memory(self): """ - Test "statistics dump" and the memory information. + Test "statistics dump" and the memory information. """ self.build() exe = self.getBuildArtifact("a.out") target = self.createTestTarget(file_path=exe) debug_stats = self.get_stats() debug_stat_keys = [ - 'memory', - 'modules', - 'targets', - 'totalSymbolTableParseTime', - 'totalSymbolTableIndexTime', - 'totalSymbolTablesLoadedFromCache', - 'totalSymbolTablesSavedToCache', - 'totalDebugInfoParseTime', - 'totalDebugInfoIndexTime', - 'totalDebugInfoIndexLoadedFromCache', - 'totalDebugInfoIndexSavedToCache', - 'totalDebugInfoByteSize' + "memory", + "modules", + "targets", + "totalSymbolTableParseTime", + "totalSymbolTableIndexTime", + "totalSymbolTablesLoadedFromCache", + "totalSymbolTablesSavedToCache", + "totalDebugInfoParseTime", + "totalDebugInfoIndexTime", + "totalDebugInfoIndexLoadedFromCache", + "totalDebugInfoIndexSavedToCache", + "totalDebugInfoByteSize", ] self.verify_keys(debug_stats, '"debug_stats"', debug_stat_keys, None) - memory = debug_stats['memory'] - memory_keys= [ - 'strings', + memory = debug_stats["memory"] + memory_keys = [ + "strings", ] self.verify_keys(memory, '"memory"', memory_keys, None) - strings = memory['strings'] - strings_keys= [ - 'bytesTotal', - 'bytesUsed', - 'bytesUnused', + strings = memory["strings"] + strings_keys = [ + "bytesTotal", + "bytesUsed", + "bytesUnused", ] self.verify_keys(strings, '"strings"', strings_keys, None) - def find_module_in_metrics(self, path, stats): - modules = stats['modules'] + modules = stats["modules"] for module in modules: - if module['path'] == path: + if module["path"] == path: return module return None def find_module_by_id_in_metrics(self, id, stats): - modules = stats['modules'] + modules = stats["modules"] for module in modules: - if module['identifier'] == id: + if module["identifier"] == id: return module return None def test_modules(self): """ - Test "statistics dump" and the module information. + Test "statistics dump" and the module information. """ self.build() exe = self.getBuildArtifact("a.out") target = self.createTestTarget(file_path=exe) debug_stats = self.get_stats() debug_stat_keys = [ - 'memory', - 'modules', - 'targets', - 'totalSymbolTableParseTime', - 'totalSymbolTableIndexTime', - 'totalSymbolTablesLoadedFromCache', - 'totalSymbolTablesSavedToCache', - 'totalDebugInfoParseTime', - 'totalDebugInfoIndexTime', - 'totalDebugInfoIndexLoadedFromCache', - 'totalDebugInfoIndexSavedToCache', - 'totalDebugInfoByteSize' + "memory", + "modules", + "targets", + "totalSymbolTableParseTime", + "totalSymbolTableIndexTime", + "totalSymbolTablesLoadedFromCache", + "totalSymbolTablesSavedToCache", + "totalDebugInfoParseTime", + "totalDebugInfoIndexTime", + "totalDebugInfoIndexLoadedFromCache", + "totalDebugInfoIndexSavedToCache", + "totalDebugInfoByteSize", ] self.verify_keys(debug_stats, '"debug_stats"', debug_stat_keys, None) - stats = debug_stats['targets'][0] + stats = debug_stats["targets"][0] keys_exist = [ - 'moduleIdentifiers', + "moduleIdentifiers", ] self.verify_keys(stats, '"stats"', keys_exist, None) exe_module = self.find_module_in_metrics(exe, debug_stats) module_keys = [ - 'debugInfoByteSize', - 'debugInfoIndexLoadedFromCache', - 'debugInfoIndexTime', - 'debugInfoIndexSavedToCache', - 'debugInfoParseTime', - 'identifier', - 'path', - 'symbolTableIndexTime', - 'symbolTableLoadedFromCache', - 'symbolTableParseTime', - 'symbolTableSavedToCache', - 'triple', - 'uuid', + "debugInfoByteSize", + "debugInfoIndexLoadedFromCache", + "debugInfoIndexTime", + "debugInfoIndexSavedToCache", + "debugInfoParseTime", + "identifier", + "path", + "symbolTableIndexTime", + "symbolTableLoadedFromCache", + "symbolTableParseTime", + "symbolTableSavedToCache", + "triple", + "uuid", ] self.assertNotEqual(exe_module, None) self.verify_keys(exe_module, 'module dict for "%s"' % (exe), module_keys) @@ -384,57 +406,57 @@ self.runCmd("b a_function") debug_stats = self.get_stats() debug_stat_keys = [ - 'memory', - 'modules', - 'targets', - 'totalSymbolTableParseTime', - 'totalSymbolTableIndexTime', - 'totalSymbolTablesLoadedFromCache', - 'totalSymbolTablesSavedToCache', - 'totalDebugInfoParseTime', - 'totalDebugInfoIndexTime', - 'totalDebugInfoIndexLoadedFromCache', - 'totalDebugInfoIndexSavedToCache', - 'totalDebugInfoByteSize', + "memory", + "modules", + "targets", + "totalSymbolTableParseTime", + "totalSymbolTableIndexTime", + "totalSymbolTablesLoadedFromCache", + "totalSymbolTablesSavedToCache", + "totalDebugInfoParseTime", + "totalDebugInfoIndexTime", + "totalDebugInfoIndexLoadedFromCache", + "totalDebugInfoIndexSavedToCache", + "totalDebugInfoByteSize", ] self.verify_keys(debug_stats, '"debug_stats"', debug_stat_keys, None) - target_stats = debug_stats['targets'][0] + target_stats = debug_stats["targets"][0] keys_exist = [ - 'breakpoints', - 'expressionEvaluation', - 'frameVariable', - 'targetCreateTime', - 'moduleIdentifiers', - 'totalBreakpointResolveTime', + "breakpoints", + "expressionEvaluation", + "frameVariable", + "targetCreateTime", + "moduleIdentifiers", + "totalBreakpointResolveTime", ] self.verify_keys(target_stats, '"stats"', keys_exist, None) - self.assertGreater(target_stats['totalBreakpointResolveTime'], 0.0) - breakpoints = target_stats['breakpoints'] + self.assertGreater(target_stats["totalBreakpointResolveTime"], 0.0) + breakpoints = target_stats["breakpoints"] bp_keys_exist = [ - 'details', - 'id', - 'internal', - 'numLocations', - 'numResolvedLocations', - 'resolveTime' + "details", + "id", + "internal", + "numLocations", + "numResolvedLocations", + "resolveTime", ] for breakpoint in breakpoints: - self.verify_keys(breakpoint, 'target_stats["breakpoints"]', - bp_keys_exist, None) - + self.verify_keys( + breakpoint, 'target_stats["breakpoints"]', bp_keys_exist, None + ) @skipUnlessDarwin @no_debug_info_test def test_dsym_binary_has_symfile_in_stats(self): """ - Test that if our executable has a stand alone dSYM file containing - debug information, that the dSYM file path is listed as a key/value - pair in the "a.out" binaries module stats. Also verify the the main - executable's module statistics has a debug info size that is greater - than zero as the dSYM contains debug info. + Test that if our executable has a stand alone dSYM file containing + debug information, that the dSYM file path is listed as a key/value + pair in the "a.out" binaries module stats. Also verify the the main + executable's module statistics has a debug info size that is greater + than zero as the dSYM contains debug info. """ self.build(debug_info="dsym") - exe_name = 'a.out' + exe_name = "a.out" exe = self.getBuildArtifact(exe_name) dsym = self.getBuildArtifact(exe_name + ".dSYM") # Make sure the executable file exists after building. @@ -451,13 +473,13 @@ # If we have a dSYM file, there should be a key/value pair in the module # statistics and the path should match the dSYM file path in the build # artifacts. - self.assertIn('symbolFilePath', exe_stats) - stats_dsym = exe_stats['symbolFilePath'] + self.assertIn("symbolFilePath", exe_stats) + stats_dsym = exe_stats["symbolFilePath"] # Make sure main executable's module info has debug info size that is # greater than zero as the dSYM file and main executable work together # in the lldb.SBModule class to provide the data. - self.assertGreater(exe_stats['debugInfoByteSize'], 0) + self.assertGreater(exe_stats["debugInfoByteSize"], 0) # The "dsym" variable contains the bundle directory for the dSYM, while # the "stats_dsym" will have the @@ -465,24 +487,24 @@ # Since we have a dSYM file, we should not be loading DWARF from the .o # files and the .o file module identifiers should NOT be in the module # statistics. - self.assertNotIn('symbolFileModuleIdentifiers', exe_stats) + self.assertNotIn("symbolFileModuleIdentifiers", exe_stats) @skipUnlessDarwin @no_debug_info_test def test_no_dsym_binary_has_symfile_identifiers_in_stats(self): """ - Test that if our executable loads debug info from the .o files, - that the module statistics contains a 'symbolFileModuleIdentifiers' - key which is a list of module identifiers, and verify that the - module identifier can be used to find the .o file's module stats. - Also verify the the main executable's module statistics has a debug - info size that is zero, as the main executable itself has no debug - info, but verify that the .o files have debug info size that is - greater than zero. This test ensures that we don't double count - debug info. + Test that if our executable loads debug info from the .o files, + that the module statistics contains a 'symbolFileModuleIdentifiers' + key which is a list of module identifiers, and verify that the + module identifier can be used to find the .o file's module stats. + Also verify the the main executable's module statistics has a debug + info size that is zero, as the main executable itself has no debug + info, but verify that the .o files have debug info size that is + greater than zero. This test ensures that we don't double count + debug info. """ self.build(debug_info="dwarf") - exe_name = 'a.out' + exe_name = "a.out" exe = self.getBuildArtifact(exe_name) dsym = self.getBuildArtifact(exe_name + ".dSYM") # Make sure the executable file exists after building. @@ -502,14 +524,14 @@ exe_stats = self.find_module_in_metrics(exe, debug_stats) # If we don't have a dSYM file, there should not be a key/value pair in # the module statistics. - self.assertNotIn('symbolFilePath', exe_stats) + self.assertNotIn("symbolFilePath", exe_stats) # Make sure main executable's module info has debug info size that is # zero as there is no debug info in the main executable, only in the # .o files. The .o files will also only be loaded if something causes # them to be loaded, so we set a breakpoint to force the .o file debug # info to be loaded. - self.assertEqual(exe_stats['debugInfoByteSize'], 0) + self.assertEqual(exe_stats["debugInfoByteSize"], 0) # When we don't have a dSYM file, the SymbolFileDWARFDebugMap class # should create modules for each .o file that contains DWARF that the @@ -517,27 +539,27 @@ # identifier for main.o that is we should not be loading DWARF from the .o # files and the .o file module identifiers should NOT be in the module # statistics. - self.assertIn('symbolFileModuleIdentifiers', exe_stats) + self.assertIn("symbolFileModuleIdentifiers", exe_stats) - symfileIDs = exe_stats['symbolFileModuleIdentifiers'] + symfileIDs = exe_stats["symbolFileModuleIdentifiers"] for symfileID in symfileIDs: o_module = self.find_module_by_id_in_metrics(symfileID, debug_stats) self.assertNotEqual(o_module, None) # Make sure each .o file has some debug info bytes. - self.assertGreater(o_module['debugInfoByteSize'], 0) + self.assertGreater(o_module["debugInfoByteSize"], 0) @skipUnlessDarwin @no_debug_info_test def test_had_frame_variable_errors(self): """ - Test that if we have frame variable errors that we see this in the - statistics for the module that had issues. + Test that if we have frame variable errors that we see this in the + statistics for the module that had issues. """ self.build(debug_info="dwarf") - exe_name = 'a.out' + exe_name = "a.out" exe = self.getBuildArtifact(exe_name) dsym = self.getBuildArtifact(exe_name + ".dSYM") - main_obj = self.getBuildArtifact('main.o') + main_obj = self.getBuildArtifact("main.o") # Make sure the executable file exists after building. self.assertEqual(os.path.exists(exe), True) # Make sure the dSYM file doesn't exist after building. @@ -549,7 +571,7 @@ # error when we run to main and try to get variables os.unlink(main_obj) - (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint(self, 'main') + (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint(self, "main") # Get stats and verify we had errors. stats = self.get_stats() @@ -558,11 +580,11 @@ # Make sure we have "debugInfoHadVariableErrors" variable that is set to # false before failing to get local variables due to missing .o file. - self.assertEqual(exe_stats['debugInfoHadVariableErrors'], False) + self.assertEqual(exe_stats["debugInfoHadVariableErrors"], False) # Verify that the top level statistic that aggregates the number of # modules with debugInfoHadVariableErrors is zero - self.assertEqual(stats['totalModuleCountWithVariableErrors'], 0) + self.assertEqual(stats["totalModuleCountWithVariableErrors"], 0) # Try and fail to get variables vars = thread.GetFrameAtIndex(0).GetVariables(True, True, False, True) @@ -578,8 +600,8 @@ # Make sure we have "hadFrameVariableErrors" variable that is set to # true after failing to get local variables due to missing .o file. - self.assertEqual(exe_stats['debugInfoHadVariableErrors'], True) + self.assertEqual(exe_stats["debugInfoHadVariableErrors"], True) # Verify that the top level statistic that aggregates the number of # modules with debugInfoHadVariableErrors is greater than zero - self.assertGreater(stats['totalModuleCountWithVariableErrors'], 0) + self.assertGreater(stats["totalModuleCountWithVariableErrors"], 0) diff --git a/lldb/test/API/commands/target/auto-install-main-executable/TestAutoInstallMainExecutable.py b/lldb/test/API/commands/target/auto-install-main-executable/TestAutoInstallMainExecutable.py --- a/lldb/test/API/commands/target/auto-install-main-executable/TestAutoInstallMainExecutable.py +++ b/lldb/test/API/commands/target/auto-install-main-executable/TestAutoInstallMainExecutable.py @@ -15,14 +15,14 @@ NO_DEBUG_INFO_TESTCASE = True @skipIfRemote - @skipIfWindows # This test is flaky on Windows + @skipIfWindows # This test is flaky on Windows def test_target_auto_install_main_executable(self): if lldbgdbserverutils.get_lldb_server_exe() is None: - self.skipTest("lldb-server not found") + self.skipTest("lldb-server not found") self.build() hostname = socket.getaddrinfo("localhost", 0, proto=socket.IPPROTO_TCP)[0][4][0] - listen_url = "[%s]:0"%hostname + listen_url = "[%s]:0" % hostname port_file = self.getBuildArtifact("port") commandline_args = [ @@ -30,10 +30,9 @@ "--listen", listen_url, "--socket-file", - port_file] - self.spawnSubprocess( - lldbgdbserverutils.get_lldb_server_exe(), - commandline_args) + port_file, + ] + self.spawnSubprocess(lldbgdbserverutils.get_lldb_server_exe(), commandline_args) socket_id = lldbutil.wait_for_file_on_target(self, port_file) @@ -48,25 +47,29 @@ os.mkdir(wd) new_platform.SetWorkingDirectory(wd) - # Manually install the modified binary. src_device = lldb.SBFileSpec(self.getBuildArtifact("a.device.out")) dest = lldb.SBFileSpec(os.path.join(wd, "a.out")) self.assertSuccess(new_platform.Put(src_device, dest)) # Test the default setting. - self.expect("settings show target.auto-install-main-executable", - substrs=["target.auto-install-main-executable (boolean) = true"], - msg="Default settings for target.auto-install-main-executable failed.") + self.expect( + "settings show target.auto-install-main-executable", + substrs=["target.auto-install-main-executable (boolean) = true"], + msg="Default settings for target.auto-install-main-executable failed.", + ) # Disable the auto install. self.runCmd("settings set target.auto-install-main-executable false") - self.expect("settings show target.auto-install-main-executable", - substrs=["target.auto-install-main-executable (boolean) = false"]) + self.expect( + "settings show target.auto-install-main-executable", + substrs=["target.auto-install-main-executable (boolean) = false"], + ) # Create the target with the original file. - self.runCmd("target create --remote-file %s %s "% - (dest.fullpath, - self.getBuildArtifact("a.out"))) + self.runCmd( + "target create --remote-file %s %s " + % (dest.fullpath, self.getBuildArtifact("a.out")) + ) self.expect("process launch", substrs=["exited with status = 74"]) diff --git a/lldb/test/API/commands/target/basic/TestTargetCommand.py b/lldb/test/API/commands/target/basic/TestTargetCommand.py --- a/lldb/test/API/commands/target/basic/TestTargetCommand.py +++ b/lldb/test/API/commands/target/basic/TestTargetCommand.py @@ -13,27 +13,26 @@ class targetCommandTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line numbers for our breakpoints. - self.line_b = line_number('b.c', '// Set break point at this line.') - self.line_c = line_number('c.c', '// Set break point at this line.') + self.line_b = line_number("b.c", "// Set break point at this line.") + self.line_c = line_number("c.c", "// Set break point at this line.") def buildB(self): - db = {'C_SOURCES': 'b.c', 'EXE': self.getBuildArtifact('b.out')} + db = {"C_SOURCES": "b.c", "EXE": self.getBuildArtifact("b.out")} self.build(dictionary=db) self.addTearDownCleanup(dictionary=db) def buildAll(self): - da = {'C_SOURCES': 'a.c', 'EXE': self.getBuildArtifact('a.out')} + da = {"C_SOURCES": "a.c", "EXE": self.getBuildArtifact("a.out")} self.build(dictionary=da) self.addTearDownCleanup(dictionary=da) self.buildB() - dc = {'C_SOURCES': 'c.c', 'EXE': self.getBuildArtifact('c.out')} + dc = {"C_SOURCES": "c.c", "EXE": self.getBuildArtifact("c.out")} self.build(dictionary=dc) self.addTearDownCleanup(dictionary=dc) @@ -42,23 +41,23 @@ self.buildAll() self.do_target_command() - @skipIfDarwin # Chained Fixups + @skipIfDarwin # Chained Fixups def test_target_variable_command(self): """Test 'target variable' command before and after starting the inferior.""" - d = {'C_SOURCES': 'globals.c', 'EXE': self.getBuildArtifact('globals')} + d = {"C_SOURCES": "globals.c", "EXE": self.getBuildArtifact("globals")} self.build(dictionary=d) self.addTearDownCleanup(dictionary=d) - self.do_target_variable_command('globals') + self.do_target_variable_command("globals") - @skipIfDarwin # Chained Fixups + @skipIfDarwin # Chained Fixups def test_target_variable_command_no_fail(self): """Test 'target variable' command before and after starting the inferior.""" - d = {'C_SOURCES': 'globals.c', 'EXE': self.getBuildArtifact('globals')} + d = {"C_SOURCES": "globals.c", "EXE": self.getBuildArtifact("globals")} self.build(dictionary=d) self.addTearDownCleanup(dictionary=d) - self.do_target_variable_command_no_fail('globals') + self.do_target_variable_command_no_fail("globals") def do_target_command(self): """Exercise 'target create', 'target list', 'target select' commands.""" @@ -74,6 +73,7 @@ else: # Find the largest index of the existing list. import re + pattern = re.compile("target #(\d+):") for line in reversed(output.split(os.linesep)): match = pattern.search(line) @@ -88,12 +88,14 @@ self.runCmd("target create " + exe_b, CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, 'b.c', self.line_b, num_expected_locations=1, loc_exact=True) + self, "b.c", self.line_b, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) self.runCmd("target create " + exe_c, CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, 'c.c', self.line_c, num_expected_locations=1, loc_exact=True) + self, "c.c", self.line_c, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) self.runCmd("target list") @@ -102,22 +104,29 @@ self.runCmd("thread backtrace") self.runCmd("target select %d" % (base + 2)) - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stop reason = breakpoint' ,'c.c:%d' % self.line_c - ]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint", "c.c:%d" % self.line_c], + ) self.runCmd("target select %d" % (base + 1)) - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stop reason = breakpoint', 'b.c:%d' % self.line_b - ]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint", "b.c:%d" % self.line_b], + ) self.runCmd("target list") @no_debug_info_test def test_target_create_invalid_arch(self): exe = self.getBuildArtifact("a.out") - self.expect("target create {} --arch doesntexist".format(exe), error=True, - patterns=["error: invalid triple 'doesntexist'"]) + self.expect( + "target create {} --arch doesntexist".format(exe), + error=True, + patterns=["error: invalid triple 'doesntexist'"], + ) @no_debug_info_test def test_target_create_platform(self): @@ -130,47 +139,54 @@ yaml = os.path.join(self.getSourceDir(), "bogus.yaml") exe = self.getBuildArtifact("bogus") self.yaml2obj(yaml, exe) - self.expect("target create {}".format(exe), error=True, - patterns=['error: no matching platforms found for this file']) + self.expect( + "target create {}".format(exe), + error=True, + patterns=["error: no matching platforms found for this file"], + ) @no_debug_info_test def test_target_create_invalid_platform(self): self.buildB() exe = self.getBuildArtifact("b.out") - self.expect("target create {} --platform doesntexist".format(exe), error=True, - patterns=['error: unable to find a plug-in for the platform named "doesntexist"']) + self.expect( + "target create {} --platform doesntexist".format(exe), + error=True, + patterns=[ + 'error: unable to find a plug-in for the platform named "doesntexist"' + ], + ) def do_target_variable_command(self, exe_name): """Exercise 'target variable' command before and after starting the inferior.""" - self.runCmd("file " + self.getBuildArtifact(exe_name), - CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact(exe_name), CURRENT_EXECUTABLE_SET) self.expect( "target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - "my_global_char", - "'X'"]) + substrs=["my_global_char", "'X'"], + ) self.expect( "target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - 'my_global_str', - '"abc"']) + substrs=["my_global_str", '"abc"'], + ) self.expect( "target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - 'my_static_int', - '228']) - self.expect("target variable my_global_str_ptr", matching=False, - substrs=['"abc"']) - self.expect("target variable *my_global_str_ptr", matching=True, - substrs=['"abc"']) + substrs=["my_static_int", "228"], + ) + self.expect( + "target variable my_global_str_ptr", matching=False, substrs=['"abc"'] + ) + self.expect( + "target variable *my_global_str_ptr", matching=True, substrs=['"abc"'] + ) self.expect( "target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs=['a']) + substrs=["a"], + ) self.runCmd("b main") self.runCmd("run") @@ -178,90 +194,89 @@ self.expect( "target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - 'my_global_str', - '"abc"']) + substrs=["my_global_str", '"abc"'], + ) self.expect( "target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - 'my_static_int', - '228']) - self.expect("target variable my_global_str_ptr", matching=False, - substrs=['"abc"']) - self.expect("target variable *my_global_str_ptr", matching=True, - substrs=['"abc"']) + substrs=["my_static_int", "228"], + ) + self.expect( + "target variable my_global_str_ptr", matching=False, substrs=['"abc"'] + ) + self.expect( + "target variable *my_global_str_ptr", matching=True, substrs=['"abc"'] + ) self.expect( "target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs=['a']) + substrs=["a"], + ) self.expect( "target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - "my_global_char", - "'X'"]) + substrs=["my_global_char", "'X'"], + ) self.runCmd("c") self.expect( "target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - 'my_global_str', - '"abc"']) + substrs=["my_global_str", '"abc"'], + ) self.expect( "target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - 'my_static_int', - '228']) - self.expect("target variable my_global_str_ptr", matching=False, - substrs=['"abc"']) - self.expect("target variable *my_global_str_ptr", matching=True, - substrs=['"abc"']) + substrs=["my_static_int", "228"], + ) + self.expect( + "target variable my_global_str_ptr", matching=False, substrs=['"abc"'] + ) + self.expect( + "target variable *my_global_str_ptr", matching=True, substrs=['"abc"'] + ) self.expect( "target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs=['a']) + substrs=["a"], + ) self.expect( "target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - "my_global_char", - "'X'"]) + substrs=["my_global_char", "'X'"], + ) def do_target_variable_command_no_fail(self, exe_name): """Exercise 'target variable' command before and after starting the inferior.""" - self.runCmd("file " + self.getBuildArtifact(exe_name), - CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact(exe_name), CURRENT_EXECUTABLE_SET) self.expect( "target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - "my_global_char", - "'X'"]) + substrs=["my_global_char", "'X'"], + ) self.expect( "target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - 'my_global_str', - '"abc"']) + substrs=["my_global_str", '"abc"'], + ) self.expect( "target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - 'my_static_int', - '228']) - self.expect("target variable my_global_str_ptr", matching=False, - substrs=['"abc"']) - self.expect("target variable *my_global_str_ptr", matching=True, - substrs=['"abc"']) + substrs=["my_static_int", "228"], + ) + self.expect( + "target variable my_global_str_ptr", matching=False, substrs=['"abc"'] + ) + self.expect( + "target variable *my_global_str_ptr", matching=True, substrs=['"abc"'] + ) self.expect( "target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs=['a']) + substrs=["a"], + ) self.runCmd("b main") self.runCmd("run") @@ -269,90 +284,137 @@ # New feature: you don't need to specify the variable(s) to 'target vaiable'. # It will find all the global and static variables in the current # compile unit. - self.expect("target variable", - ordered=False, - substrs=['my_global_char', - 'my_static_int', - 'my_global_str', - 'my_global_str_ptr', - ]) + self.expect( + "target variable", + ordered=False, + substrs=[ + "my_global_char", + "my_static_int", + "my_global_str", + "my_global_str_ptr", + ], + ) self.expect( "target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - 'my_global_str', - '"abc"']) + substrs=["my_global_str", '"abc"'], + ) self.expect( "target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - 'my_static_int', - '228']) - self.expect("target variable my_global_str_ptr", matching=False, - substrs=['"abc"']) - self.expect("target variable *my_global_str_ptr", matching=True, - substrs=['"abc"']) + substrs=["my_static_int", "228"], + ) + self.expect( + "target variable my_global_str_ptr", matching=False, substrs=['"abc"'] + ) + self.expect( + "target variable *my_global_str_ptr", matching=True, substrs=['"abc"'] + ) self.expect( "target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs=['a']) + substrs=["a"], + ) self.expect( "target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY, - substrs=[ - "my_global_char", - "'X'"]) + substrs=["my_global_char", "'X'"], + ) @no_debug_info_test def test_target_stop_hook_disable_enable(self): self.buildB() self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) - self.expect("target stop-hook disable 1", error=True, substrs=['unknown stop hook id: "1"']) - self.expect("target stop-hook disable blub", error=True, substrs=['invalid stop hook id: "blub"']) - self.expect("target stop-hook enable 1", error=True, substrs=['unknown stop hook id: "1"']) - self.expect("target stop-hook enable blub", error=True, substrs=['invalid stop hook id: "blub"']) + self.expect( + "target stop-hook disable 1", + error=True, + substrs=['unknown stop hook id: "1"'], + ) + self.expect( + "target stop-hook disable blub", + error=True, + substrs=['invalid stop hook id: "blub"'], + ) + self.expect( + "target stop-hook enable 1", + error=True, + substrs=['unknown stop hook id: "1"'], + ) + self.expect( + "target stop-hook enable blub", + error=True, + substrs=['invalid stop hook id: "blub"'], + ) @no_debug_info_test def test_target_stop_hook_delete(self): self.buildB() self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) - self.expect("target stop-hook delete 1", error=True, substrs=['unknown stop hook id: "1"']) - self.expect("target stop-hook delete blub", error=True, substrs=['invalid stop hook id: "blub"']) + self.expect( + "target stop-hook delete 1", + error=True, + substrs=['unknown stop hook id: "1"'], + ) + self.expect( + "target stop-hook delete blub", + error=True, + substrs=['invalid stop hook id: "blub"'], + ) @no_debug_info_test def test_target_list_args(self): - self.expect("target list blub", error=True, - substrs=["'target list' doesn't take any arguments"]) + self.expect( + "target list blub", + error=True, + substrs=["'target list' doesn't take any arguments"], + ) @no_debug_info_test def test_target_select_no_index(self): - self.expect("target select", error=True, - substrs=["'target select' takes a single argument: a target index"]) + self.expect( + "target select", + error=True, + substrs=["'target select' takes a single argument: a target index"], + ) @no_debug_info_test def test_target_select_invalid_index(self): self.runCmd("target delete --all") - self.expect("target select 0", error=True, - substrs=["index 0 is out of range since there are no active targets"]) + self.expect( + "target select 0", + error=True, + substrs=["index 0 is out of range since there are no active targets"], + ) self.buildB() self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) - self.expect("target select 1", error=True, - substrs=["index 1 is out of range, valid target indexes are 0 - 0"]) - + self.expect( + "target select 1", + error=True, + substrs=["index 1 is out of range, valid target indexes are 0 - 0"], + ) @no_debug_info_test def test_target_create_multiple_args(self): - self.expect("target create a b", error=True, - substrs=["'target create' takes exactly one executable path"]) + self.expect( + "target create a b", + error=True, + substrs=["'target create' takes exactly one executable path"], + ) @skipIfWindowsAndNonEnglish @no_debug_info_test def test_target_create_nonexistent_core_file(self): - self.expect("target create -c doesntexist", error=True, - patterns=["Cannot open 'doesntexist'", ": (No such file or directory|The system cannot find the file specified)"]) + self.expect( + "target create -c doesntexist", + error=True, + patterns=[ + "Cannot open 'doesntexist'", + ": (No such file or directory|The system cannot find the file specified)", + ], + ) # Write only files don't seem to be supported on Windows. @skipIfWindows @@ -360,22 +422,33 @@ def test_target_create_unreadable_core_file(self): tf = tempfile.NamedTemporaryFile() os.chmod(tf.name, stat.S_IWRITE) - self.expect("target create -c '" + tf.name + "'", error=True, - substrs=["Cannot open '", "': Permission denied"]) + self.expect( + "target create -c '" + tf.name + "'", + error=True, + substrs=["Cannot open '", "': Permission denied"], + ) @skipIfWindowsAndNonEnglish @no_debug_info_test def test_target_create_nonexistent_sym_file(self): - self.expect("target create -s doesntexist doesntexisteither", error=True, - patterns=["Cannot open '", ": (No such file or directory|The system cannot find the file specified)"]) + self.expect( + "target create -s doesntexist doesntexisteither", + error=True, + patterns=[ + "Cannot open '", + ": (No such file or directory|The system cannot find the file specified)", + ], + ) @skipIfWindows @no_debug_info_test def test_target_create_invalid_core_file(self): invalid_core_path = os.path.join(self.getSourceDir(), "invalid_core_file") - self.expect("target create -c '" + invalid_core_path + "'", error=True, - substrs=["Unable to find process plug-in for core file '"]) - + self.expect( + "target create -c '" + invalid_core_path + "'", + error=True, + substrs=["Unable to find process plug-in for core file '"], + ) # Write only files don't seem to be supported on Windows. @skipIfWindows @@ -383,8 +456,11 @@ def test_target_create_unreadable_sym_file(self): tf = tempfile.NamedTemporaryFile() os.chmod(tf.name, stat.S_IWRITE) - self.expect("target create -s '" + tf.name + "' no_exe", error=True, - substrs=["Cannot open '", "': Permission denied"]) + self.expect( + "target create -s '" + tf.name + "' no_exe", + error=True, + substrs=["Cannot open '", "': Permission denied"], + ) @no_debug_info_test def test_target_delete_all(self): @@ -400,16 +476,22 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) self.runCmd("file " + self.getBuildArtifact("c.out"), CURRENT_EXECUTABLE_SET) - self.expect("target delete 3", error=True, - substrs=["target index 3 is out of range, valid target indexes are 0 - 2"]) + self.expect( + "target delete 3", + error=True, + substrs=["target index 3 is out of range, valid target indexes are 0 - 2"], + ) self.runCmd("target delete 1") self.expect("target list", matching=False, substrs=["b.out"]) self.runCmd("target delete 1") self.expect("target list", matching=False, substrs=["c.out"]) - self.expect("target delete 1", error=True, - substrs=["target index 1 is out of range, the only valid index is 0"]) + self.expect( + "target delete 1", + error=True, + substrs=["target index 1 is out of range, the only valid index is 0"], + ) self.runCmd("target delete 0") self.expect("target list", matching=False, substrs=["a.out"]) @@ -424,8 +506,11 @@ self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) self.runCmd("file " + self.getBuildArtifact("c.out"), CURRENT_EXECUTABLE_SET) - self.expect("target delete 0 1 2 3", error=True, - substrs=["target index 3 is out of range, valid target indexes are 0 - 2"]) + self.expect( + "target delete 0 1 2 3", + error=True, + substrs=["target index 3 is out of range, valid target indexes are 0 - 2"], + ) self.expect("target list", substrs=["a.out", "b.out", "c.out"]) self.runCmd("target delete 0 1 2") @@ -443,7 +528,9 @@ self.runCmd("target delete") self.runCmd("target delete") self.expect("target list", substrs=["No targets."]) - self.expect("target delete", error=True, substrs=["no target is currently selected"]) + self.expect( + "target delete", error=True, substrs=["no target is currently selected"] + ) @no_debug_info_test def test_target_modules_search_paths_clear(self): @@ -464,15 +551,20 @@ self.expect("target modules search-paths query faz", substrs=["faz"]) # Invalid arguments. - self.expect("target modules search-paths query faz baz", error=True, - substrs=["query requires one argument"]) + self.expect( + "target modules search-paths query faz baz", + error=True, + substrs=["query requires one argument"], + ) @no_debug_info_test - @expectedFailureAll(oslist=["freebsd"], - bugnumber="github.com/llvm/llvm-project/issues/56079") + @expectedFailureAll( + oslist=["freebsd"], bugnumber="github.com/llvm/llvm-project/issues/56079" + ) def test_target_modules_type(self): self.buildB() - self.runCmd("file " + self.getBuildArtifact("b.out"), - CURRENT_EXECUTABLE_SET) - self.expect("target modules lookup --type int", - substrs=["1 match found", 'name = "int"']) + self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) + self.expect( + "target modules lookup --type int", + substrs=["1 match found", 'name = "int"'], + ) diff --git a/lldb/test/API/commands/target/create-deps/TestTargetCreateDeps.py b/lldb/test/API/commands/target/create-deps/TestTargetCreateDeps.py --- a/lldb/test/API/commands/target/create-deps/TestTargetCreateDeps.py +++ b/lldb/test/API/commands/target/create-deps/TestTargetCreateDeps.py @@ -9,9 +9,9 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -@skipIfWindows # Windows deals differently with shared libs. -class TargetDependentsTestCase(TestBase): +@skipIfWindows # Windows deals differently with shared libs. +class TargetDependentsTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True def setUp(self): @@ -22,24 +22,27 @@ self.expect( "image list", "image list should contain at least one image", - substrs=['[ 0]']) + substrs=["[ 0]"], + ) should_match = not matching - self.expect( - "image list", msg, matching=should_match, substrs=['[ 1]']) - + self.expect("image list", msg, matching=should_match, substrs=["[ 1]"]) - @expectedFailureAll(oslist=["freebsd", "linux", "netbsd"], - bugnumber='llvm.org/pr48372', - triple=no_match(".*-android")) + @expectedFailureAll( + oslist=["freebsd", "linux", "netbsd"], + bugnumber="llvm.org/pr48372", + triple=no_match(".*-android"), + ) def test_dependents_implicit_default_exe(self): """Test default behavior""" exe = self.getBuildArtifact("a.out") self.runCmd("target create " + exe, CURRENT_EXECUTABLE_SET) self.has_exactly_one_image(False) - @expectedFailureAll(oslist=["freebsd", "linux", "netbsd"], - bugnumber='llvm.org/pr48372', - triple=no_match(".*-android")) + @expectedFailureAll( + oslist=["freebsd", "linux", "netbsd"], + bugnumber="llvm.org/pr48372", + triple=no_match(".*-android"), + ) def test_dependents_explicit_default_exe(self): """Test default behavior""" exe = self.getBuildArtifact("a.out") @@ -52,9 +55,11 @@ self.runCmd("target create -dtrue " + exe, CURRENT_EXECUTABLE_SET) self.has_exactly_one_image(True) - @expectedFailureAll(oslist=["freebsd", "linux", "netbsd"], - bugnumber='llvm.org/pr48372', - triple=no_match(".*-android")) + @expectedFailureAll( + oslist=["freebsd", "linux", "netbsd"], + bugnumber="llvm.org/pr48372", + triple=no_match(".*-android"), + ) def test_dependents_explicit_false_exe(self): """Test default behavior""" exe = self.getBuildArtifact("a.out") @@ -67,41 +72,43 @@ self.runCmd("target create -d " + exe, CURRENT_EXECUTABLE_SET) self.has_exactly_one_image(True) - @expectedFailureAndroid # android will return mutiple images + @expectedFailureAndroid # android will return mutiple images def test_dependents_implicit_default_lib(self): ctx = self.platformContext - dylibName = ctx.shlib_prefix + 'load_a.' + ctx.shlib_extension + dylibName = ctx.shlib_prefix + "load_a." + ctx.shlib_extension lib = self.getBuildArtifact(dylibName) self.runCmd("target create " + lib, CURRENT_EXECUTABLE_SET) self.has_exactly_one_image(True) def test_dependents_explicit_default_lib(self): ctx = self.platformContext - dylibName = ctx.shlib_prefix + 'load_a.' + ctx.shlib_extension + dylibName = ctx.shlib_prefix + "load_a." + ctx.shlib_extension lib = self.getBuildArtifact(dylibName) self.runCmd("target create -ddefault " + lib, CURRENT_EXECUTABLE_SET) self.has_exactly_one_image(True) def test_dependents_explicit_true_lib(self): ctx = self.platformContext - dylibName = ctx.shlib_prefix + 'load_a.' + ctx.shlib_extension + dylibName = ctx.shlib_prefix + "load_a." + ctx.shlib_extension lib = self.getBuildArtifact(dylibName) self.runCmd("target create -dtrue " + lib, CURRENT_EXECUTABLE_SET) self.has_exactly_one_image(True) - @expectedFailureAll(oslist=["freebsd", "linux", "netbsd"], - bugnumber='llvm.org/pr48372', - triple=no_match(".*-android")) + @expectedFailureAll( + oslist=["freebsd", "linux", "netbsd"], + bugnumber="llvm.org/pr48372", + triple=no_match(".*-android"), + ) def test_dependents_explicit_false_lib(self): ctx = self.platformContext - dylibName = ctx.shlib_prefix + 'load_a.' + ctx.shlib_extension + dylibName = ctx.shlib_prefix + "load_a." + ctx.shlib_extension lib = self.getBuildArtifact(dylibName) self.runCmd("target create -dfalse " + lib, CURRENT_EXECUTABLE_SET) self.has_exactly_one_image(False) def test_dependents_implicit_false_lib(self): ctx = self.platformContext - dylibName = ctx.shlib_prefix + 'load_a.' + ctx.shlib_extension + dylibName = ctx.shlib_prefix + "load_a." + ctx.shlib_extension lib = self.getBuildArtifact(dylibName) self.runCmd("target create -d " + lib, CURRENT_EXECUTABLE_SET) self.has_exactly_one_image(True) diff --git a/lldb/test/API/commands/target/create-no-such-arch/TestNoSuchArch.py b/lldb/test/API/commands/target/create-no-such-arch/TestNoSuchArch.py --- a/lldb/test/API/commands/target/create-no-such-arch/TestNoSuchArch.py +++ b/lldb/test/API/commands/target/create-no-such-arch/TestNoSuchArch.py @@ -18,8 +18,10 @@ # Check that passing an invalid arch via the command-line fails but # doesn't crash self.expect( - "target create --arch nothingtoseehere %s" % - (exe), error=True, substrs=["error: invalid triple 'nothingtoseehere'"]) + "target create --arch nothingtoseehere %s" % (exe), + error=True, + substrs=["error: invalid triple 'nothingtoseehere'"], + ) # Check that passing an invalid arch via the SB API fails but doesn't # crash diff --git a/lldb/test/API/commands/target/dump-pcm-info/TestDumpPCMInfo.py b/lldb/test/API/commands/target/dump-pcm-info/TestDumpPCMInfo.py --- a/lldb/test/API/commands/target/dump-pcm-info/TestDumpPCMInfo.py +++ b/lldb/test/API/commands/target/dump-pcm-info/TestDumpPCMInfo.py @@ -17,8 +17,7 @@ def test(self): self.build() - lldbutil.run_to_source_breakpoint( - self, "return", lldb.SBFileSpec("main.m")) + lldbutil.run_to_source_breakpoint(self, "return", lldb.SBFileSpec("main.m")) mod_cache = self.getBuildArtifact("private-module-cache") if os.path.isdir(mod_cache): @@ -30,11 +29,12 @@ self.runCmd("expression @import Darwin") # root//-.pcm - pcm_paths = glob.glob(os.path.join(mod_cache, '*', 'Darwin-*.pcm')) + pcm_paths = glob.glob(os.path.join(mod_cache, "*", "Darwin-*.pcm")) self.assertEqual(len(pcm_paths), 1, "Expected one Darwin pcm") pcm_path = pcm_paths[0] self.expect( f"target modules dump pcm-info '{pcm_path}'", startstr=f"Information for module file '{pcm_path}'", - substrs=["Module name: Darwin"]) + substrs=["Module name: Darwin"], + ) diff --git a/lldb/test/API/commands/target/dump-symtab-demangle/TestDumpSymtabDemangle.py b/lldb/test/API/commands/target/dump-symtab-demangle/TestDumpSymtabDemangle.py --- a/lldb/test/API/commands/target/dump-symtab-demangle/TestDumpSymtabDemangle.py +++ b/lldb/test/API/commands/target/dump-symtab-demangle/TestDumpSymtabDemangle.py @@ -6,8 +6,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @no_debug_info_test def test(self): src_dir = self.getSourceDir() @@ -22,7 +22,9 @@ # First test that we demangle by default and our mangled symbol isn't in the output. self.expect("target modules dump symtab", substrs=["foo::bar(int)"]) - self.expect("target modules dump symtab", matching=False, substrs=["_ZN3foo3barEi"]) + self.expect( + "target modules dump symtab", matching=False, substrs=["_ZN3foo3barEi"] + ) # Turn off demangling and make sure that we now see the mangled name in the output. self.expect("target modules dump symtab -m", substrs=["_ZN3foo3barEi"]) diff --git a/lldb/test/API/commands/target/dump/TestTargetDumpTypeSystem.py b/lldb/test/API/commands/target/dump/TestTargetDumpTypeSystem.py --- a/lldb/test/API/commands/target/dump/TestTargetDumpTypeSystem.py +++ b/lldb/test/API/commands/target/dump/TestTargetDumpTypeSystem.py @@ -3,16 +3,18 @@ from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @no_debug_info_test def test_dumping(self): - """ Tests dumping an empty and non-empty scratch AST. """ + """Tests dumping an empty and non-empty scratch AST.""" self.build() self.createTestTarget() # Make sure DummyStruct is not in the scratch AST by default. - self.expect("target dump typesystem", matching=False, substrs=["struct DummyStruct"]) + self.expect( + "target dump typesystem", matching=False, substrs=["struct DummyStruct"] + ) # Move DummyStruct into the scratch AST via the expression evaluator. # FIXME: Once there is an SB API for using variable paths on globals @@ -24,8 +26,11 @@ @no_debug_info_test def test_invalid_arg(self): - """ Test an invalid invocation on 'target dump typesystem'. """ + """Test an invalid invocation on 'target dump typesystem'.""" self.build() self.createTestTarget() - self.expect("target dump typesystem arg", error=True, - substrs=["'target dump typesystem' doesn't take any arguments."]) + self.expect( + "target dump typesystem arg", + error=True, + substrs=["'target dump typesystem' doesn't take any arguments."], + ) diff --git a/lldb/test/API/commands/target/modules/search-paths/insert/TestTargetModulesSearchpathsInsert.py b/lldb/test/API/commands/target/modules/search-paths/insert/TestTargetModulesSearchpathsInsert.py --- a/lldb/test/API/commands/target/modules/search-paths/insert/TestTargetModulesSearchpathsInsert.py +++ b/lldb/test/API/commands/target/modules/search-paths/insert/TestTargetModulesSearchpathsInsert.py @@ -3,16 +3,22 @@ from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @no_debug_info_test def test_invalid_arg(self): self.build() exe = self.getBuildArtifact("a.out") self.expect("target create %s" % (exe)) - self.expect("target modules search-paths insert -1 a b", error=True, - startstr="error: parameter is not an integer: '-1'.") + self.expect( + "target modules search-paths insert -1 a b", + error=True, + startstr="error: parameter is not an integer: '-1'.", + ) - self.expect("target modules search-paths insert abcdefx a b", error=True, - startstr="error: parameter is not an integer: 'abcdefx'.") + self.expect( + "target modules search-paths insert abcdefx a b", + error=True, + startstr="error: parameter is not an integer: 'abcdefx'.", + ) diff --git a/lldb/test/API/commands/target/select/TestTargetSelect.py b/lldb/test/API/commands/target/select/TestTargetSelect.py --- a/lldb/test/API/commands/target/select/TestTargetSelect.py +++ b/lldb/test/API/commands/target/select/TestTargetSelect.py @@ -3,11 +3,17 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @no_debug_info_test def test_invalid_arg(self): - self.expect("target select -1", error=True, - startstr="error: invalid index string value '-1'") - self.expect("target select abcdfx", error=True, - startstr="error: invalid index string value 'abcdfx'") + self.expect( + "target select -1", + error=True, + startstr="error: invalid index string value '-1'", + ) + self.expect( + "target select abcdfx", + error=True, + startstr="error: invalid index string value 'abcdfx'", + ) diff --git a/lldb/test/API/commands/target/stop-hook/delete/TestTargetStopHookDelete.py b/lldb/test/API/commands/target/stop-hook/delete/TestTargetStopHookDelete.py --- a/lldb/test/API/commands/target/stop-hook/delete/TestTargetStopHookDelete.py +++ b/lldb/test/API/commands/target/stop-hook/delete/TestTargetStopHookDelete.py @@ -3,11 +3,17 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @no_debug_info_test def test_invalid_arg(self): - self.expect("target stop-hook delete -1", error=True, - startstr="error: invalid stop hook id: \"-1\".") - self.expect("target stop-hook delete abcdfx", error=True, - startstr="error: invalid stop hook id: \"abcdfx\".") + self.expect( + "target stop-hook delete -1", + error=True, + startstr='error: invalid stop hook id: "-1".', + ) + self.expect( + "target stop-hook delete abcdfx", + error=True, + startstr='error: invalid stop hook id: "abcdfx".', + ) diff --git a/lldb/test/API/commands/target/stop-hook/disable/TestTargetStopHookDisable.py b/lldb/test/API/commands/target/stop-hook/disable/TestTargetStopHookDisable.py --- a/lldb/test/API/commands/target/stop-hook/disable/TestTargetStopHookDisable.py +++ b/lldb/test/API/commands/target/stop-hook/disable/TestTargetStopHookDisable.py @@ -3,11 +3,17 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @no_debug_info_test def test_invalid_arg(self): - self.expect("target stop-hook disable -1", error=True, - startstr="error: invalid stop hook id: \"-1\".") - self.expect("target stop-hook disable abcdfx", error=True, - startstr="error: invalid stop hook id: \"abcdfx\".") + self.expect( + "target stop-hook disable -1", + error=True, + startstr='error: invalid stop hook id: "-1".', + ) + self.expect( + "target stop-hook disable abcdfx", + error=True, + startstr='error: invalid stop hook id: "abcdfx".', + ) diff --git a/lldb/test/API/commands/target/stop-hook/enable/TestTargetStopHookEnable.py b/lldb/test/API/commands/target/stop-hook/enable/TestTargetStopHookEnable.py --- a/lldb/test/API/commands/target/stop-hook/enable/TestTargetStopHookEnable.py +++ b/lldb/test/API/commands/target/stop-hook/enable/TestTargetStopHookEnable.py @@ -3,11 +3,17 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @no_debug_info_test def test_invalid_arg(self): - self.expect("target stop-hook enable -1", error=True, - startstr="error: invalid stop hook id: \"-1\".") - self.expect("target stop-hook enable abcdfx", error=True, - startstr="error: invalid stop hook id: \"abcdfx\".") + self.expect( + "target stop-hook enable -1", + error=True, + startstr='error: invalid stop hook id: "-1".', + ) + self.expect( + "target stop-hook enable abcdfx", + error=True, + startstr='error: invalid stop hook id: "abcdfx".', + ) diff --git a/lldb/test/API/commands/target/stop-hooks/TestStopHookScripted.py b/lldb/test/API/commands/target/stop-hooks/TestStopHookScripted.py --- a/lldb/test/API/commands/target/stop-hooks/TestStopHookScripted.py +++ b/lldb/test/API/commands/target/stop-hooks/TestStopHookScripted.py @@ -3,14 +3,13 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * -class TestStopHooks(TestBase): +class TestStopHooks(TestBase): # If your test case doesn't stress debug info, then # set this to true. That way it won't be run once for # each debug info format. @@ -22,7 +21,7 @@ self.main_source_file = lldb.SBFileSpec("main.c") full_path = os.path.join(self.getSourceDir(), "main.c") self.main_start_line = line_number(full_path, "main()") - + def test_bad_handler(self): """Test that we give a good error message when the handler is bad""" self.script_setup() @@ -32,15 +31,23 @@ command = "target stop-hook add -P stop_hook.bad_handle_stop" self.interp.HandleCommand(command, result) self.assertFalse(result.Succeeded(), "Set the target stop hook") - self.assertIn("Wrong number of args", result.GetError(), "Got the wrong number of args error") + self.assertIn( + "Wrong number of args", + result.GetError(), + "Got the wrong number of args error", + ) # Next the no handler at all handler: command = "target stop-hook add -P stop_hook.no_handle_stop" - + self.interp.HandleCommand(command, result) self.assertFalse(result.Succeeded(), "Set the target stop hook") - self.assertIn('Class "stop_hook.no_handle_stop" is missing the required handle_stop callback', result.GetError(), "Got the right error") - + self.assertIn( + 'Class "stop_hook.no_handle_stop" is missing the required handle_stop callback', + result.GetError(), + "Got the right error", + ) + def test_stop_hooks_scripted(self): """Test that a scripted stop hook works with no specifiers""" self.stop_hooks_scripted(5) @@ -48,18 +55,18 @@ def test_stop_hooks_scripted_right_func(self): """Test that a scripted stop hook fires when there is a function match""" self.stop_hooks_scripted(5, "-n step_out_of_me") - + def test_stop_hooks_scripted_wrong_func(self): """Test that a scripted stop hook doesn't fire when the function does not match""" self.stop_hooks_scripted(0, "-n main") - + def test_stop_hooks_scripted_right_lines(self): """Test that a scripted stop hook fires when there is a function match""" - self.stop_hooks_scripted(5, "-f main.c -l 1 -e %d"%(self.main_start_line)) - + self.stop_hooks_scripted(5, "-f main.c -l 1 -e %d" % (self.main_start_line)) + def test_stop_hooks_scripted_wrong_lines(self): """Test that a scripted stop hook doesn't fire when the function does not match""" - self.stop_hooks_scripted(0, "-f main.c -l %d -e 100"%(self.main_start_line)) + self.stop_hooks_scripted(0, "-f main.c -l %d -e 100" % (self.main_start_line)) def test_stop_hooks_scripted_auto_continue(self): """Test that the --auto-continue flag works""" @@ -74,33 +81,38 @@ # We set auto-continue to 1 but the stop hook only applies to step_out_of_me, # so we should end up stopped in main, having run the expression only once. self.script_setup() - + result = lldb.SBCommandReturnObject() if return_true: - command = "target stop-hook add -P stop_hook.stop_handler -k increment -v 5 -k return_false -v 1 -n step_out_of_me" + command = "target stop-hook add -P stop_hook.stop_handler -k increment -v 5 -k return_false -v 1 -n step_out_of_me" else: - command = "target stop-hook add -G 1 -P stop_hook.stop_handler -k increment -v 5 -n step_out_of_me" - + command = "target stop-hook add -G 1 -P stop_hook.stop_handler -k increment -v 5 -n step_out_of_me" + self.interp.HandleCommand(command, result) self.assertTrue(result.Succeeded(), "Set the target stop hook") # First run to main. If we go straight to the first stop hook hit, # run_to_source_breakpoint will fail because we aren't at original breakpoint - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - "Stop here first", self.main_source_file) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Stop here first", self.main_source_file + ) # Now set the breakpoint on step_out_of_me, and make sure we run the # expression, then continue back to main. - bkpt = target.BreakpointCreateBySourceRegex("Set a breakpoint here and step out", self.main_source_file) - self.assertNotEqual(bkpt.GetNumLocations(), 0, "Got breakpoints in step_out_of_me") + bkpt = target.BreakpointCreateBySourceRegex( + "Set a breakpoint here and step out", self.main_source_file + ) + self.assertNotEqual( + bkpt.GetNumLocations(), 0, "Got breakpoints in step_out_of_me" + ) process.Continue() var = target.FindFirstGlobalVariable("g_var") self.assertTrue(var.IsValid()) self.assertEqual(var.GetValueAsUnsigned(), 6, "Updated g_var") - + func_name = process.GetSelectedThread().frames[0].GetFunctionName() self.assertEqual("main", func_name, "Didn't stop at the expected function.") @@ -112,28 +124,32 @@ script_name = os.path.join(self.getSourceDir(), "stop_hook.py") command = "command script import " + script_name self.interp.HandleCommand(command, result) - self.assertTrue(result.Succeeded(), "com scr imp failed: %s"%(result.GetError())) + self.assertTrue( + result.Succeeded(), "com scr imp failed: %s" % (result.GetError()) + ) # set a breakpoint at the end of main to catch our auto-continue tests. # Do it in the dummy target so it will get copied to our target even when # we don't have a chance to stop. dummy_target = self.dbg.GetDummyTarget() - dummy_target.BreakpointCreateBySourceRegex("return result", self.main_source_file) + dummy_target.BreakpointCreateBySourceRegex( + "return result", self.main_source_file + ) - - def stop_hooks_scripted(self, g_var_value, specifier = None): + def stop_hooks_scripted(self, g_var_value, specifier=None): self.script_setup() - + result = lldb.SBCommandReturnObject() command = "target stop-hook add -P stop_hook.stop_handler -k increment -v 5 " if specifier: command += specifier - + self.interp.HandleCommand(command, result) self.assertTrue(result.Succeeded(), "Set the target stop hook") - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - "Set a breakpoint here", self.main_source_file) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", self.main_source_file + ) # At this point we've hit our stop hook so we should have run our expression, # which increments g_var by the amount specified by the increment key's value. while process.GetState() == lldb.eStateRunning: diff --git a/lldb/test/API/commands/target/stop-hooks/TestStopHooks.py b/lldb/test/API/commands/target/stop-hooks/TestStopHooks.py --- a/lldb/test/API/commands/target/stop-hooks/TestStopHooks.py +++ b/lldb/test/API/commands/target/stop-hooks/TestStopHooks.py @@ -3,14 +3,12 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * class TestStopHooks(TestBase): - # If your test case doesn't stress debug info, then # set this to true. That way it won't be run once for # each debug info format. @@ -22,19 +20,20 @@ self.main_source_file = lldb.SBFileSpec("main.c") full_path = os.path.join(self.getSourceDir(), "main.c") self.main_start_line = line_number(full_path, "main()") - + def test_stop_hooks_step_out(self): """Test that stop hooks fire on step-out.""" self.step_out_test() def test_stop_hooks_after_expr(self): """Test that a stop hook fires when hitting a breakpoint - that runs an expression""" + that runs an expression""" self.after_expr_test() def step_out_test(self): - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - "Set a breakpoint here", self.main_source_file) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", self.main_source_file + ) interp = self.dbg.GetCommandInterpreter() result = lldb.SBCommandReturnObject() @@ -51,22 +50,25 @@ interp.HandleCommand("target stop-hook add -o 'expr g_var++'", result) self.assertTrue(result.Succeeded(), "Set the target stop hook") - (target, process, thread, first_bkpt) = lldbutil.run_to_source_breakpoint(self, - "Set a breakpoint here", self.main_source_file) + (target, process, thread, first_bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", self.main_source_file + ) var = target.FindFirstGlobalVariable("g_var") self.assertTrue(var.IsValid()) self.assertEqual(var.GetValueAsUnsigned(), 1, "Updated g_var") - bkpt = target.BreakpointCreateBySourceRegex("Continue to here", self.main_source_file) + bkpt = target.BreakpointCreateBySourceRegex( + "Continue to here", self.main_source_file + ) self.assertNotEqual(bkpt.GetNumLocations(), 0, "Set the second breakpoint") commands = lldb.SBStringList() commands.AppendString("expr increment_gvar()") - bkpt.SetCommandLineCommands(commands); - + bkpt.SetCommandLineCommands(commands) + threads = lldbutil.continue_to_breakpoint(process, bkpt) self.assertEqual(len(threads), 1, "Hit my breakpoint") - + self.assertTrue(var.IsValid()) self.assertEqual(var.GetValueAsUnsigned(), 3, "Updated g_var") @@ -76,7 +78,6 @@ threads[0].frames[0].EvaluateExpression("increment_gvar()") self.assertTrue(var.IsValid()) self.assertEqual(var.GetValueAsUnsigned(), 4, "Updated g_var") - # Make sure a rerun doesn't upset the state we've set up: process.Kill() @@ -84,5 +85,3 @@ var = target.FindFirstGlobalVariable("g_var") self.assertTrue(var.IsValid()) self.assertEqual(var.GetValueAsUnsigned(), 1, "Updated g_var") - - diff --git a/lldb/test/API/commands/target/stop-hooks/stop_hook.py b/lldb/test/API/commands/target/stop-hooks/stop_hook.py --- a/lldb/test/API/commands/target/stop-hooks/stop_hook.py +++ b/lldb/test/API/commands/target/stop-hooks/stop_hook.py @@ -1,5 +1,6 @@ import lldb + class stop_handler: def __init__(self, target, extra_args, dict): self.extra_args = extra_args @@ -13,7 +14,7 @@ def handle_stop(self, exe_ctx, stream): self.counter += 1 - stream.Print("I have stopped %d times.\n"%(self.counter)) + stream.Print("I have stopped %d times.\n" % (self.counter)) increment = 1 value = self.extra_args.GetValueForKey("increment") if value: @@ -21,18 +22,21 @@ else: stream.Print("Could not find increment in extra_args\n") frame = exe_ctx.GetFrame() - expression = "g_var += %d"%(increment) + expression = "g_var += %d" % (increment) expr_result = frame.EvaluateExpression(expression) if not expr_result.GetError().Success(): - stream.Print("Error running expression: %s"%(expr_result.GetError().GetCString())) + stream.Print( + "Error running expression: %s" % (expr_result.GetError().GetCString()) + ) value = exe_ctx.target.FindFirstGlobalVariable("g_var") if not value.IsValid(): stream.Print("Didn't get a valid value for g_var.") else: int_val = value.GetValueAsUnsigned() - stream.Print("Returning value: %d from handle_stop.\n"%(self.ret_val)) + stream.Print("Returning value: %d from handle_stop.\n" % (self.ret_val)) return self.ret_val + class bad_handle_stop: def __init__(self, target, extra_args, dict): print("I am okay") @@ -40,9 +44,7 @@ def handle_stop(self): print("I am bad") + class no_handle_stop: def __init__(self, target, extra_args, dict): print("I am okay") - - - diff --git a/lldb/test/API/commands/thread/backtrace/TestThreadBacktraceRepeat.py b/lldb/test/API/commands/thread/backtrace/TestThreadBacktraceRepeat.py --- a/lldb/test/API/commands/thread/backtrace/TestThreadBacktraceRepeat.py +++ b/lldb/test/API/commands/thread/backtrace/TestThreadBacktraceRepeat.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -15,13 +14,19 @@ def test_thread_backtrace_one_thread(self): """Run a simplified version of the test that just hits one breakpoint and - doesn't care about synchronizing the two threads - hopefully this will - run on more systems.""" + doesn't care about synchronizing the two threads - hopefully this will + run on more systems.""" def test_thread_backtrace_one_thread(self): self.build() - (self.inferior_target, self.process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, self.bkpt_string, lldb.SBFileSpec('main.cpp'), only_one_thread = False) + ( + self.inferior_target, + self.process, + thread, + bkpt, + ) = lldbutil.run_to_source_breakpoint( + self, self.bkpt_string, lldb.SBFileSpec("main.cpp"), only_one_thread=False + ) # We hit the breakpoint on at least one thread. If we hit it on both threads # simultaneously, we are ready to run our tests. Otherwise, suspend the thread @@ -29,20 +34,24 @@ # the breakpoint: (breakpoint_threads, other_threads) = ([], []) - lldbutil.sort_stopped_threads(self.process, - breakpoint_threads=breakpoint_threads, - other_threads=other_threads) - self.assertGreater(len(breakpoint_threads), 0, "We hit at least one breakpoint thread") + lldbutil.sort_stopped_threads( + self.process, + breakpoint_threads=breakpoint_threads, + other_threads=other_threads, + ) + self.assertGreater( + len(breakpoint_threads), 0, "We hit at least one breakpoint thread" + ) self.assertGreater(len(breakpoint_threads[0].frames), 2, "I can go up") thread_id = breakpoint_threads[0].idx name = breakpoint_threads[0].frame[1].name.split("(")[0] self.check_one_thread(thread_id, name) - + def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number for our breakpoint. - self.bkpt_string = '// Set breakpoint here' + self.bkpt_string = "// Set breakpoint here" def check_one_thread(self, thread_id, func_name): # Now issue some thread backtrace commands and make sure they @@ -52,7 +61,9 @@ # Run the real backtrace, remember to pass True for add_to_history since # we don't generate repeat commands for commands that aren't going into the history. - interp.HandleCommand("thread backtrace --count 10 {0}".format(thread_id), result, True) + interp.HandleCommand( + "thread backtrace --count 10 {0}".format(thread_id), result, True + ) self.assertTrue(result.Succeeded(), "bt with count succeeded") # There should be 11 lines: lines = result.GetOutput().splitlines() @@ -60,14 +71,20 @@ # First frame is stop_here: self.assertNotEqual(lines[1].find("stop_here"), -1, "Found Stop Here") for line in lines[2:10]: - self.assertNotEqual(line.find(func_name), -1, "Name {0} not found in line: {1}".format(func_name, line)) + self.assertNotEqual( + line.find(func_name), + -1, + "Name {0} not found in line: {1}".format(func_name, line), + ) # The last entry should be 43: self.assertNotEqual(lines[10].find("count=43"), -1, "First show ends at 43") - + # Now try a repeat, and make sure we get 10 more on this thread: - #import pdb; pdb.set_trace() + # import pdb; pdb.set_trace() interp.HandleCommand("", result, True) - self.assertTrue(result.Succeeded(), "repeat command failed: {0}".format(result.GetError())) + self.assertTrue( + result.Succeeded(), "repeat command failed: {0}".format(result.GetError()) + ) lines = result.GetOutput().splitlines() self.assertEqual(len(lines), 11, "Repeat got 11 lines") # Every line should now be the recurse function: @@ -75,32 +92,58 @@ self.assertNotEqual(line.find(func_name), -1, "Name in every line") self.assertNotEqual(lines[10].find("count=33"), -1, "Last one is now 33") - def check_two_threads(self, result_str, thread_id_1, name_1, thread_id_2, name_2, start_idx, end_idx): + def check_two_threads( + self, result_str, thread_id_1, name_1, thread_id_2, name_2, start_idx, end_idx + ): # We should have 2 occurrences ot the thread header: - self.assertEqual(result_str.count("thread #{0}".format(thread_id_1)), 1, "One for thread 1") - self.assertEqual(result_str.count("thread #{0}".format(thread_id_2)), 1, "One for thread 2") + self.assertEqual( + result_str.count("thread #{0}".format(thread_id_1)), 1, "One for thread 1" + ) + self.assertEqual( + result_str.count("thread #{0}".format(thread_id_2)), 1, "One for thread 2" + ) # We should have 10 occurrences of each name: self.assertEqual(result_str.count(name_1), 10, "Found 10 of {0}".format(name_1)) self.assertEqual(result_str.count(name_2), 10, "Found 10 of {0}".format(name_1)) # There should be two instances of count= and none of count=: - self.assertEqual(result_str.count("count={0}".format(start_idx)), 2, "Two instances of start_idx") - self.assertEqual(result_str.count("count={0}".format(start_idx-1)), 0, "No instances of start_idx - 1") + self.assertEqual( + result_str.count("count={0}".format(start_idx)), + 2, + "Two instances of start_idx", + ) + self.assertEqual( + result_str.count("count={0}".format(start_idx - 1)), + 0, + "No instances of start_idx - 1", + ) # There should be two instances of count= and none of count=: - self.assertEqual(result_str.count("count={0}".format(end_idx)), 2, "Two instances of end_idx") - self.assertEqual(result_str.count("count={0}".format(end_idx+1)), 0, "No instances after end idx") + self.assertEqual( + result_str.count("count={0}".format(end_idx)), 2, "Two instances of end_idx" + ) + self.assertEqual( + result_str.count("count={0}".format(end_idx + 1)), + 0, + "No instances after end idx", + ) # The setup of this test was copied from the step-out test, and I can't tell from # the comments whether it was getting two threads to the same breakpoint that was # problematic, or the step-out part. This test stops at the rendevous point so I'm # removing the skipIfLinux to see if we see any flakiness in just this part of the test. - @skipIfWindows # This test will hang on windows llvm.org/pr21753 + @skipIfWindows # This test will hang on windows llvm.org/pr21753 @expectedFailureAll(oslist=["windows"]) @expectedFailureNetBSD def test_thread_backtrace_two_threads(self): """Test that repeat works even when backtracing on more than one thread.""" self.build() - (self.inferior_target, self.process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, self.bkpt_string, lldb.SBFileSpec('main.cpp'), only_one_thread = False) + ( + self.inferior_target, + self.process, + thread, + bkpt, + ) = lldbutil.run_to_source_breakpoint( + self, self.bkpt_string, lldb.SBFileSpec("main.cpp"), only_one_thread=False + ) # We hit the breakpoint on at least one thread. If we hit it on both threads # simultaneously, we are ready to run our tests. Otherwise, suspend the thread @@ -108,14 +151,15 @@ # the breakpoint: (breakpoint_threads, other_threads) = ([], []) - lldbutil.sort_stopped_threads(self.process, - breakpoint_threads=breakpoint_threads, - other_threads=other_threads) + lldbutil.sort_stopped_threads( + self.process, + breakpoint_threads=breakpoint_threads, + other_threads=other_threads, + ) if len(breakpoint_threads) == 1: success = thread.Suspend() self.assertTrue(success, "Couldn't suspend a thread") - breakpoint_threads = lldbutil.continue_to_breakpoint(self.process, - bkpt) + breakpoint_threads = lldbutil.continue_to_breakpoint(self.process, bkpt) self.assertEqual(len(breakpoint_threads), 2, "Second thread stopped") # Figure out which thread is which: @@ -137,18 +181,28 @@ interp = self.dbg.GetCommandInterpreter() result = lldb.SBCommandReturnObject() - interp.HandleCommand("thread backtrace --count 10 --start 10 {0} {1}".format(thread_id_1, thread_id_2), result, True) + interp.HandleCommand( + "thread backtrace --count 10 --start 10 {0} {1}".format( + thread_id_1, thread_id_2 + ), + result, + True, + ) self.assertTrue(result.Succeeded(), "command succeeded for two threads") result.Clear() interp.HandleCommand("", result, True) self.assertTrue(result.Succeeded(), "repeat command succeeded for two threads") result_str = result.GetOutput() - self.check_two_threads(result_str, thread_id_1, name_1, thread_id_2, name_2, 23, 32) + self.check_two_threads( + result_str, thread_id_1, name_1, thread_id_2, name_2, 23, 32 + ) # Finally make sure the repeat repeats: result.Clear() interp.HandleCommand("", result, True) self.assertTrue(result.Succeeded(), "repeat command succeeded for two threads") result_str = result.GetOutput() - self.check_two_threads(result_str, thread_id_1, name_1, thread_id_2, name_2, 13, 22) + self.check_two_threads( + result_str, thread_id_1, name_1, thread_id_2, name_2, 13, 22 + ) diff --git a/lldb/test/API/commands/thread/select/TestThreadSelect.py b/lldb/test/API/commands/thread/select/TestThreadSelect.py --- a/lldb/test/API/commands/thread/select/TestThreadSelect.py +++ b/lldb/test/API/commands/thread/select/TestThreadSelect.py @@ -3,14 +3,26 @@ from lldbsuite.test import lldbutil from lldbsuite.test.decorators import * -class TestCase(TestBase): +class TestCase(TestBase): def test_invalid_arg(self): self.build() - lldbutil.run_to_source_breakpoint(self, '// break here', lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) - self.expect("thread select -1", error=True, startstr="error: Invalid thread index '-1'") - self.expect("thread select 0x1ffffffff", error=True, startstr="error: Invalid thread index '0x1ffffffff'") + self.expect( + "thread select -1", error=True, startstr="error: Invalid thread index '-1'" + ) + self.expect( + "thread select 0x1ffffffff", + error=True, + startstr="error: Invalid thread index '0x1ffffffff'", + ) # Parses but not a valid thread id. - self.expect("thread select 0xffffffff", error=True, startstr="error: invalid thread #0xffffffff.") + self.expect( + "thread select 0xffffffff", + error=True, + startstr="error: invalid thread #0xffffffff.", + ) diff --git a/lldb/test/API/commands/trace/TestTraceDumpFunctionCalls.py b/lldb/test/API/commands/trace/TestTraceDumpFunctionCalls.py --- a/lldb/test/API/commands/trace/TestTraceDumpFunctionCalls.py +++ b/lldb/test/API/commands/trace/TestTraceDumpFunctionCalls.py @@ -2,19 +2,31 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * + class TestTraceDumpInfo(TraceIntelPTTestCaseBase): def testDumpSimpleFunctionCalls(self): - self.expect("trace load -v " + - os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json")) + self.expect( + "trace load -v " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json") + ) - self.expect("thread trace dump function-calls 2", - error=True, substrs=['error: no thread with index: "2"']) + self.expect( + "thread trace dump function-calls 2", + error=True, + substrs=['error: no thread with index: "2"'], + ) - self.expect("thread trace dump function-calls 1 -j", - substrs=['[{"tracedSegments":[{"firstInstructionId":"3","lastInstructionId":"26"}]}]']) + self.expect( + "thread trace dump function-calls 1 -j", + substrs=[ + '[{"tracedSegments":[{"firstInstructionId":"3","lastInstructionId":"26"}]}]' + ], + ) - self.expect("thread trace dump function-calls 1 -J", - substrs=['''[ + self.expect( + "thread trace dump function-calls 1 -J", + substrs=[ + """[ { "tracedSegments": [ { @@ -23,31 +35,47 @@ } ] } -]''']) +]""" + ], + ) - # We test first some code without function call - self.expect("thread trace dump function-calls 1", - substrs=['''thread #1: tid = 3842849 + # We test first some code without function call + self.expect( + "thread trace dump function-calls 1", + substrs=[ + """thread #1: tid = 3842849 [call tree #0] -a.out`main + 4 at main.cpp:2 to 4:0 [3, 26]''']) +a.out`main + 4 at main.cpp:2 to 4:0 [3, 26]""" + ], + ) def testFunctionCallsWithErrors(self): - self.expect("trace load -v " + - os.path.join(self.getSourceDir(), "intelpt-multi-core-trace", "trace.json")) + self.expect( + "trace load -v " + + os.path.join( + self.getSourceDir(), "intelpt-multi-core-trace", "trace.json" + ) + ) - # We expect that tracing errors appear as a different tree - self.expect("thread trace dump function-calls 2", - substrs=['''thread #2: tid = 3497496 + # We expect that tracing errors appear as a different tree + self.expect( + "thread trace dump function-calls 2", + substrs=[ + """thread #2: tid = 3497496 [call tree #0] m.out`foo() + 65 at multi_thread.cpp:12:21 to 12:21 [4, 19524] [call tree #1] - [19526, 19526]''']) + [19526, 19526]""" + ], + ) - self.expect("thread trace dump function-calls 2 -J", - substrs=['''[ + self.expect( + "thread trace dump function-calls 2 -J", + substrs=[ + """[ { "tracedSegments": [ { @@ -64,19 +92,27 @@ } ] } -]''']) +]""" + ], + ) - self.expect("thread trace dump function-calls 3", - substrs=['''thread #3: tid = 3497497 + self.expect( + "thread trace dump function-calls 3", + substrs=[ + """thread #3: tid = 3497497 [call tree #0] m.out`bar() + 30 at multi_thread.cpp:19:3 to 20:6 [5, 61831] [call tree #1] - [61833, 61833]''']) + [61833, 61833]""" + ], + ) - self.expect("thread trace dump function-calls 3 -J", - substrs=['''[ + self.expect( + "thread trace dump function-calls 3 -J", + substrs=[ + """[ { "tracedSegments": [ { @@ -93,25 +129,35 @@ } ] } -]''']) +]""" + ], + ) def testInlineFunctionCalls(self): - self.expect("file " + os.path.join(self.getSourceDir(), "inline-function", "a.out")) - self.expect("b main") # we'll trace from the beginning of main - self.expect("b 17") - self.expect("r") - self.expect("thread trace start") - self.expect("c") - self.expect("thread trace dump function-calls", - substrs=['''[call tree #0] + self.expect( + "file " + os.path.join(self.getSourceDir(), "inline-function", "a.out") + ) + self.expect("b main") # we'll trace from the beginning of main + self.expect("b 17") + self.expect("r") + self.expect("thread trace start") + self.expect("c") + self.expect( + "thread trace dump function-calls", + substrs=[ + """[call tree #0] a.out`main + 8 at inline.cpp:15:7 to 16:14 [2, 6] a.out`foo(int) at inline.cpp:8:16 to 9:15 [7, 14] a.out`foo(int) + 22 [inlined] mult(int, int) at inline.cpp:2:7 to 5:10 [15, 22] a.out`foo(int) + 49 at inline.cpp:9:15 to 12:1 [23, 27] -a.out`main + 25 at inline.cpp:16:14 to 16:14 [28, 28]''']) +a.out`main + 25 at inline.cpp:16:14 to 16:14 [28, 28]""" + ], + ) - self.expect("thread trace dump function-calls -J", - substrs=['''[ + self.expect( + "thread trace dump function-calls -J", + substrs=[ + """[ { "tracedSegments": [ { @@ -144,25 +190,35 @@ } ] } -]''']) +]""" + ], + ) def testIncompleteInlineFunctionCalls(self): - self.expect("file " + os.path.join(self.getSourceDir(), "inline-function", "a.out")) - self.expect("b 4") # we'll trace from the middle of the inline method - self.expect("b 17") - self.expect("r") - self.expect("thread trace start") - self.expect("c") - self.expect("thread trace dump function-calls", - substrs=['''[call tree #0] + self.expect( + "file " + os.path.join(self.getSourceDir(), "inline-function", "a.out") + ) + self.expect("b 4") # we'll trace from the middle of the inline method + self.expect("b 17") + self.expect("r") + self.expect("thread trace start") + self.expect("c") + self.expect( + "thread trace dump function-calls", + substrs=[ + """[call tree #0] a.out`main a.out`foo(int) a.out`foo(int) + 36 [inlined] mult(int, int) + 14 at inline.cpp:4:5 to 5:10 [2, 6] a.out`foo(int) + 49 at inline.cpp:9:15 to 12:1 [7, 11] -a.out`main + 25 at inline.cpp:16:14 to 16:14 [12, 12]''']) +a.out`main + 25 at inline.cpp:16:14 to 16:14 [12, 12]""" + ], + ) - self.expect("thread trace dump function-calls -J", - substrs=['''[ + self.expect( + "thread trace dump function-calls -J", + substrs=[ + """[ { "untracedPrefixSegment": { "nestedCall": { @@ -191,23 +247,32 @@ } ] } -]''']) +]""" + ], + ) def testMultifileFunctionCalls(self): - # This test is extremely important because it first calls the method foo() which requires going through the dynamic linking. - # You'll see the entry "a.out`symbol stub for: foo()" which will invoke the ld linker, which will in turn find the actual foo - # function and eventually invoke it. However, we don't have the image of the linker in the trace bundle, so we'll see errors - # because the decoder couldn't find the linker binary! After those failures, the linker will resume right where we return to - # main after foo() finished. - # Then, we call foo() again, but because it has already been loaded by the linker, we don't invoke the linker anymore! And - # we'll see a nice tree without errors in this second invocation. Something interesting happens here. We still have an - # invocation to the symbol stub for foo(), but it modifies the stack so that when we return from foo() we don't stop again - # at the symbol stub, but instead we return directly to main. This is an example of returning several levels up in the - # call stack. - # Not only that, we also have an inline method in between. - self.expect("trace load " + os.path.join(self.getSourceDir(), "intelpt-trace-multi-file", "multi-file-no-ld.json")) - self.expect("thread trace dump function-calls", - substrs=['''thread #1: tid = 815455 + # This test is extremely important because it first calls the method foo() which requires going through the dynamic linking. + # You'll see the entry "a.out`symbol stub for: foo()" which will invoke the ld linker, which will in turn find the actual foo + # function and eventually invoke it. However, we don't have the image of the linker in the trace bundle, so we'll see errors + # because the decoder couldn't find the linker binary! After those failures, the linker will resume right where we return to + # main after foo() finished. + # Then, we call foo() again, but because it has already been loaded by the linker, we don't invoke the linker anymore! And + # we'll see a nice tree without errors in this second invocation. Something interesting happens here. We still have an + # invocation to the symbol stub for foo(), but it modifies the stack so that when we return from foo() we don't stop again + # at the symbol stub, but instead we return directly to main. This is an example of returning several levels up in the + # call stack. + # Not only that, we also have an inline method in between. + self.expect( + "trace load " + + os.path.join( + self.getSourceDir(), "intelpt-trace-multi-file", "multi-file-no-ld.json" + ) + ) + self.expect( + "thread trace dump function-calls", + substrs=[ + """thread #1: tid = 815455 [call tree #0] a.out`main + 15 at main.cpp:10 to 10:0 [3, 3] @@ -226,10 +291,14 @@ libfoo.so`symbol stub for: bar() to <+0> [43, 43] libbar.so`bar() at bar.cpp:1 to 4:0 [44, 52] libfoo.so`foo() + 13 at foo.cpp:4 to 6:0 [53, 60] -a.out`main + 68 at main.cpp:16 to 16:0 [61, 63]''']) +a.out`main + 68 at main.cpp:16 to 16:0 [61, 63]""" + ], + ) - self.expect("thread trace dump function-calls -J", - substrs=['''[ + self.expect( + "thread trace dump function-calls -J", + substrs=[ + """[ { "tracedSegments": [ { @@ -322,4 +391,6 @@ } ] } -]''']) +]""" + ], + ) diff --git a/lldb/test/API/commands/trace/TestTraceDumpInfo.py b/lldb/test/API/commands/trace/TestTraceDumpInfo.py --- a/lldb/test/API/commands/trace/TestTraceDumpInfo.py +++ b/lldb/test/API/commands/trace/TestTraceDumpInfo.py @@ -4,37 +4,51 @@ from lldbsuite.test import lldbutil from lldbsuite.test.decorators import * -class TestTraceDumpInfo(TraceIntelPTTestCaseBase): +class TestTraceDumpInfo(TraceIntelPTTestCaseBase): def testErrorMessages(self): # We first check the output when there are no targets - self.expect("thread trace dump info", - substrs=["error: invalid target, create a target using the 'target create' command"], - error=True) + self.expect( + "thread trace dump info", + substrs=[ + "error: invalid target, create a target using the 'target create' command" + ], + error=True, + ) # We now check the output when there's a non-running target - self.expect("target create " + - os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "target create " + + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) - self.expect("thread trace dump info", + self.expect( + "thread trace dump info", substrs=["error: Command requires a current process."], - error=True) + error=True, + ) # Now we check the output when there's a running target without a trace self.expect("b main") self.expect("run") - self.expect("thread trace dump info", + self.expect( + "thread trace dump info", substrs=["error: Process is not being traced"], - error=True) + error=True, + ) def testDumpRawTraceSize(self): - self.expect("trace load -v " + - os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), - substrs=["intel-pt"]) + self.expect( + "trace load -v " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), + substrs=["intel-pt"], + ) - self.expect("thread trace dump info", - substrs=['''thread #1: tid = 3842849 + self.expect( + "thread trace dump info", + substrs=[ + """thread #1: tid = 3842849 Trace technology: intel-pt @@ -46,22 +60,29 @@ Average memory usage per item (excluding raw trace): 9.00 bytes Timing for this thread: - Decoding instructions: ''', ''' + Decoding instructions: """, + """ Events: Number of individual events: 7 software disabled tracing: 2 hardware disabled tracing: 4 - trace synchronization point: 1'''], - patterns=["Decoding instructions: \d.\d\ds"]) + trace synchronization point: 1""", + ], + patterns=["Decoding instructions: \d.\d\ds"], + ) def testDumpRawTraceSizeJSON(self): - self.expect("trace load -v " + - os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), - substrs=["intel-pt"]) + self.expect( + "trace load -v " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), + substrs=["intel-pt"], + ) - self.expect("thread trace dump info --json ", - substrs=['''{ + self.expect( + "thread trace dump info --json ", + substrs=[ + """{ "traceTechnology": "intel-pt", "threadStats": { "tid": 3842849, @@ -71,7 +92,8 @@ "avgPerItemInBytes": 9 }, "timingInSeconds": { - "Decoding instructions": 0''', ''' + "Decoding instructions": 0""", + """ }, "events": { "totalCount": 7, @@ -91,4 +113,6 @@ "globalStats": { "timingInSeconds": {} } -}''']) +}""", + ], + ) diff --git a/lldb/test/API/commands/trace/TestTraceDumpInstructions.py b/lldb/test/API/commands/trace/TestTraceDumpInstructions.py --- a/lldb/test/API/commands/trace/TestTraceDumpInstructions.py +++ b/lldb/test/API/commands/trace/TestTraceDumpInstructions.py @@ -2,44 +2,62 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * -class TestTraceDumpInstructions(TraceIntelPTTestCaseBase): +class TestTraceDumpInstructions(TraceIntelPTTestCaseBase): def testErrorMessages(self): # We first check the output when there are no targets - self.expect("thread trace dump instructions", - substrs=["error: invalid target, create a target using the 'target create' command"], - error=True) + self.expect( + "thread trace dump instructions", + substrs=[ + "error: invalid target, create a target using the 'target create' command" + ], + error=True, + ) # We now check the output when there's a non-running target - self.expect("target create " + - os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "target create " + + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) - self.expect("thread trace dump instructions", + self.expect( + "thread trace dump instructions", substrs=["error: Command requires a current process."], - error=True) + error=True, + ) # Now we check the output when there's a running target without a trace self.expect("b main") self.expect("run") - self.expect("thread trace dump instructions", + self.expect( + "thread trace dump instructions", substrs=["error: Process is not being traced"], - error=True) + error=True, + ) def testRawDumpInstructionsInJSON(self): - self.expect("trace load -v " + - os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), - substrs=["intel-pt"]) - - self.expect("thread trace dump instructions --raw --count 5 --forwards --json", - substrs=['''[{"id":3,"loadAddress":"0x400511"}''', - '''{"id":7,"loadAddress":"0x400518"}''', - '''{"id":8,"loadAddress":"0x40051f"}''', - '''{"id":9,"loadAddress":"0x400529"}''', - '''{"id":10,"loadAddress":"0x40052d"}''']) - - self.expect("thread trace dump instructions --raw --count 5 --forwards --pretty-json", - substrs=['''[ + self.expect( + "trace load -v " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), + substrs=["intel-pt"], + ) + + self.expect( + "thread trace dump instructions --raw --count 5 --forwards --json", + substrs=[ + """[{"id":3,"loadAddress":"0x400511"}""", + """{"id":7,"loadAddress":"0x400518"}""", + """{"id":8,"loadAddress":"0x40051f"}""", + """{"id":9,"loadAddress":"0x400529"}""", + """{"id":10,"loadAddress":"0x40052d"}""", + ], + ) + + self.expect( + "thread trace dump instructions --raw --count 5 --forwards --pretty-json", + substrs=[ + """[ { "id": 3, "loadAddress": "0x400511" @@ -60,19 +78,28 @@ "id": 10, "loadAddress": "0x40052d" } -]''']) +]""" + ], + ) def testRawDumpInstructionsInJSONToFile(self): - self.expect("trace load -v " + - os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), - substrs=["intel-pt"]) + self.expect( + "trace load -v " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), + substrs=["intel-pt"], + ) outfile = os.path.join(self.getBuildDir(), "output.json") - self.expect("thread trace dump instructions --raw --count 5 --forwards --pretty-json --file " + outfile) + self.expect( + "thread trace dump instructions --raw --count 5 --forwards --pretty-json --file " + + outfile + ) with open(outfile, "r") as out: - self.assertEqual(out.read(), '''[ + self.assertEqual( + out.read(), + """[ { "id": 3, "loadAddress": "0x400511" @@ -93,15 +120,20 @@ "id": 10, "loadAddress": "0x40052d" } -]''') +]""", + ) def testRawDumpInstructions(self): - self.expect("trace load -v " + - os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), - substrs=["intel-pt"]) - - self.expect("thread trace dump instructions --raw --count 21 --forwards", - substrs=['''thread #1: tid = 3842849 + self.expect( + "trace load -v " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), + substrs=["intel-pt"], + ) + + self.expect( + "thread trace dump instructions --raw --count 21 --forwards", + substrs=[ + """thread #1: tid = 3842849 3: 0x0000000000400511 7: 0x0000000000400518 8: 0x000000000040051f @@ -122,125 +154,193 @@ 23: 0x0000000000400521 24: 0x0000000000400525 25: 0x0000000000400529 - 26: 0x000000000040052''']) + 26: 0x000000000040052""" + ], + ) # We check if we can pass count and skip - self.expect("thread trace dump instructions --count 5 --skip 6 --raw --forwards", - substrs=['''thread #1: tid = 3842849 + self.expect( + "thread trace dump instructions --count 5 --skip 6 --raw --forwards", + substrs=[ + """thread #1: tid = 3842849 7: 0x0000000000400518 8: 0x000000000040051f 9: 0x0000000000400529 10: 0x000000000040052d - 11: 0x0000000000400521''']) - - self.expect("thread trace dump instructions --count 5 --skip 6 --raw", - substrs=['''thread #1: tid = 3842849 + 11: 0x0000000000400521""" + ], + ) + + self.expect( + "thread trace dump instructions --count 5 --skip 6 --raw", + substrs=[ + """thread #1: tid = 3842849 21: 0x0000000000400529 20: 0x0000000000400525 19: 0x0000000000400521 18: 0x000000000040052d - 17: 0x0000000000400529''']) + 17: 0x0000000000400529""" + ], + ) # We check if we can pass count and skip and instruction id in hex - self.expect("thread trace dump instructions --count 5 --skip 6 --raw --id 0xE", - substrs=['''thread #1: tid = 3842849 + self.expect( + "thread trace dump instructions --count 5 --skip 6 --raw --id 0xE", + substrs=[ + """thread #1: tid = 3842849 8: 0x000000000040051f 7: 0x0000000000400518 3: 0x0000000000400511 - no more data''']) + no more data""" + ], + ) # We check if we can pass count and skip and instruction id in decimal - self.expect("thread trace dump instructions --count 5 --skip 6 --raw --id 14", - substrs=['''thread #1: tid = 3842849 + self.expect( + "thread trace dump instructions --count 5 --skip 6 --raw --id 14", + substrs=[ + """thread #1: tid = 3842849 8: 0x000000000040051f 7: 0x0000000000400518 3: 0x0000000000400511 - no more data''']) + no more data""" + ], + ) # We check if we can access the thread by index id - self.expect("thread trace dump instructions 1 --raw", - substrs=['''thread #1: tid = 3842849 - 26: 0x000000000040052d''']) + self.expect( + "thread trace dump instructions 1 --raw", + substrs=[ + """thread #1: tid = 3842849 + 26: 0x000000000040052d""" + ], + ) # We check that we get an error when using an invalid thread index id - self.expect("thread trace dump instructions 10", error=True, - substrs=['error: no thread with index: "10"']) + self.expect( + "thread trace dump instructions 10", + error=True, + substrs=['error: no thread with index: "10"'], + ) def testDumpFullInstructionsWithMultipleThreads(self): # We load a trace with two threads - self.expect("trace load -v " + - os.path.join(self.getSourceDir(), "intelpt-trace", "trace_2threads.json")) + self.expect( + "trace load -v " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace_2threads.json") + ) # We print the instructions of a specific thread - self.expect("thread trace dump instructions 2 --count 2", - substrs=['''thread #2: tid = 3842850 + self.expect( + "thread trace dump instructions 2 --count 2", + substrs=[ + """thread #2: tid = 3842850 a.out`main + 32 at main.cpp:4 26: 0x000000000040052d jle 0x400521 ; <+20> at main.cpp:5 - 25: 0x0000000000400529 cmpl $0x3, -0x8(%rbp)''']) + 25: 0x0000000000400529 cmpl $0x3, -0x8(%rbp)""" + ], + ) # We use custom --count and --skip, saving the command to history for later - self.expect("thread trace dump instructions 2 --count 2 --skip 2", inHistory=True, - substrs=['''thread #2: tid = 3842850 + self.expect( + "thread trace dump instructions 2 --count 2 --skip 2", + inHistory=True, + substrs=[ + """thread #2: tid = 3842850 a.out`main + 28 at main.cpp:4 25: 0x0000000000400529 cmpl $0x3, -0x8(%rbp) - 24: 0x0000000000400525 addl $0x1, -0x8(%rbp)''']) + 24: 0x0000000000400525 addl $0x1, -0x8(%rbp)""" + ], + ) # We use a repeat command twice and ensure the previous count is used and the # start position moves with each command. - self.expect("", inHistory=True, - substrs=['''thread #2: tid = 3842850 + self.expect( + "", + inHistory=True, + substrs=[ + """thread #2: tid = 3842850 a.out`main + 20 at main.cpp:5 23: 0x0000000000400521 xorl $0x1, -0x4(%rbp) a.out`main + 32 at main.cpp:4 - 22: 0x000000000040052d jle 0x400521 ; <+20> at main.cpp:5''']) - - self.expect("", inHistory=True, - substrs=['''thread #2: tid = 3842850 + 22: 0x000000000040052d jle 0x400521 ; <+20> at main.cpp:5""" + ], + ) + + self.expect( + "", + inHistory=True, + substrs=[ + """thread #2: tid = 3842850 a.out`main + 28 at main.cpp:4 21: 0x0000000000400529 cmpl $0x3, -0x8(%rbp) - 20: 0x0000000000400525 addl $0x1, -0x8(%rbp''']) + 20: 0x0000000000400525 addl $0x1, -0x8(%rbp""" + ], + ) def testInvalidBounds(self): - self.expect("trace load -v " + - os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json")) + self.expect( + "trace load -v " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json") + ) # The output should be work when too many instructions are asked - self.expect("thread trace dump instructions --count 20 --forwards", - substrs=['''thread #1: tid = 3842849 + self.expect( + "thread trace dump instructions --count 20 --forwards", + substrs=[ + """thread #1: tid = 3842849 a.out`main + 4 at main.cpp:2 3: 0x0000000000400511 movl $0x0, -0x4(%rbp) a.out`main + 11 at main.cpp:4 7: 0x0000000000400518 movl $0x0, -0x8(%rbp) - 8: 0x000000000040051f jmp 0x400529 ; <+28> at main.cpp:4''']) + 8: 0x000000000040051f jmp 0x400529 ; <+28> at main.cpp:4""" + ], + ) # Should print no instructions if the position is out of bounds - self.expect("thread trace dump instructions --skip 23", - endstr='no more data\n') + self.expect("thread trace dump instructions --skip 23", endstr="no more data\n") # Should fail with negative bounds self.expect("thread trace dump instructions --skip -1", error=True) self.expect("thread trace dump instructions --count -1", error=True) def testWrongImage(self): - self.expect("trace load " + - os.path.join(self.getSourceDir(), "intelpt-trace", "trace_bad_image.json")) - self.expect("thread trace dump instructions --forwards", - substrs=['''thread #1: tid = 3842849 + self.expect( + "trace load " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace_bad_image.json") + ) + self.expect( + "thread trace dump instructions --forwards", + substrs=[ + """thread #1: tid = 3842849 ...missing instructions - 3: (error) no memory mapped at this address: 0x0000000000400511''']) + 3: (error) no memory mapped at this address: 0x0000000000400511""" + ], + ) def testWrongCPU(self): - self.expect("trace load " + - os.path.join(self.getSourceDir(), "intelpt-trace", "trace_wrong_cpu.json")) - self.expect("thread trace dump instructions --forwards", - substrs=["error: unknown cpu"], error=True) + self.expect( + "trace load " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace_wrong_cpu.json") + ) + self.expect( + "thread trace dump instructions --forwards", + substrs=["error: unknown cpu"], + error=True, + ) def testMultiFileTraceWithMissingModuleInJSON(self): - self.expect("trace load " + - os.path.join(self.getSourceDir(), "intelpt-trace-multi-file", "multi-file-no-ld.json")) - - self.expect("thread trace dump instructions --count 4 --id 9 --forwards --pretty-json", - substrs=['''[ + self.expect( + "trace load " + + os.path.join( + self.getSourceDir(), "intelpt-trace-multi-file", "multi-file-no-ld.json" + ) + ) + + self.expect( + "thread trace dump instructions --count 4 --id 9 --forwards --pretty-json", + substrs=[ + """[ { "id": 9, "loadAddress": "0x40054b", @@ -276,10 +376,14 @@ "line": 10, "column": 0 } -]''']) - - self.expect("thread trace dump instructions --count 4 --id 20 --forwards --pretty-json", - substrs=['''[ +]""" + ], + ) + + self.expect( + "thread trace dump instructions --count 4 --id 20 --forwards --pretty-json", + substrs=[ + """[ { "id": 20, "loadAddress": "0x400677", @@ -320,11 +424,17 @@ "line": 4, "column": 0 } -]''']) +]""" + ], + ) def testMultiFileTraceWithMissingModule(self): - self.expect("trace load " + - os.path.join(self.getSourceDir(), "intelpt-trace-multi-file", "multi-file-no-ld.json")) + self.expect( + "trace load " + + os.path.join( + self.getSourceDir(), "intelpt-trace-multi-file", "multi-file-no-ld.json" + ) + ) # This instructions in this test covers the following flow: # @@ -340,8 +450,10 @@ # line is printed showing the symbol context change. # # Finally, the instruction disassembly is included in the dump. - self.expect("thread trace dump instructions --count 50 --forwards", - substrs=['''thread #1: tid = 815455 + self.expect( + "thread trace dump instructions --count 50 --forwards", + substrs=[ + """thread #1: tid = 815455 a.out`main + 15 at main.cpp:10 3: 0x000000000040066f callq 0x400540 ; symbol stub for: foo() a.out`symbol stub for: foo() @@ -395,8 +507,8 @@ libbar.so`bar() + 22 at bar.cpp:4 50: 0x00007ffff79d76a6 movl -0x4(%rbp), %eax 51: 0x00007ffff79d76a9 popq %rbp - 52: 0x00007ffff79d76aa retq''', - '''libfoo.so`foo() + 13 at foo.cpp:4 + 52: 0x00007ffff79d76aa retq""", + """libfoo.so`foo() + 13 at foo.cpp:4 53: 0x00007ffff7bd96ed movl %eax, -0x4(%rbp) libfoo.so`foo() + 16 at foo.cpp:5 54: 0x00007ffff7bd96f0 movl -0x4(%rbp), %eax @@ -406,23 +518,26 @@ 57: 0x00007ffff7bd96fb movl -0x4(%rbp), %eax 58: 0x00007ffff7bd96fe addq $0x10, %rsp 59: 0x00007ffff7bd9702 popq %rbp - 60: 0x00007ffff7bd9703 retq''', - '''a.out`main + 68 at main.cpp:16 + 60: 0x00007ffff7bd9703 retq""", + """a.out`main + 68 at main.cpp:16 61: 0x00000000004006a4 movl -0xc(%rbp), %ecx 62: 0x00000000004006a7 addl %eax, %ecx 63: 0x00000000004006a9 movl %ecx, -0xc(%rbp) - no more data''']) - - - self.expect("thread trace dump instructions --count 50", - substrs=['''thread #1: tid = 815455 + no more data""", + ], + ) + + self.expect( + "thread trace dump instructions --count 50", + substrs=[ + """thread #1: tid = 815455 a.out`main + 73 at main.cpp:16 63: 0x00000000004006a9 movl %ecx, -0xc(%rbp) 62: 0x00000000004006a7 addl %eax, %ecx 61: 0x00000000004006a4 movl -0xc(%rbp), %ecx libfoo.so`foo() + 35 at foo.cpp:6 - 60: 0x00007ffff7bd9703 retq''', - '''59: 0x00007ffff7bd9702 popq %rbp + 60: 0x00007ffff7bd9703 retq""", + """59: 0x00007ffff7bd9702 popq %rbp 58: 0x00007ffff7bd96fe addq $0x10, %rsp 57: 0x00007ffff7bd96fb movl -0x4(%rbp), %eax libfoo.so`foo() + 24 at foo.cpp:5 @@ -432,8 +547,8 @@ libfoo.so`foo() + 13 at foo.cpp:4 53: 0x00007ffff7bd96ed movl %eax, -0x4(%rbp) libbar.so`bar() + 26 at bar.cpp:4 - 52: 0x00007ffff79d76aa retq''', - '''51: 0x00007ffff79d76a9 popq %rbp + 52: 0x00007ffff79d76aa retq""", + """51: 0x00007ffff79d76a9 popq %rbp 50: 0x00007ffff79d76a6 movl -0x4(%rbp), %eax libbar.so`bar() + 19 at bar.cpp:3 49: 0x00007ffff79d76a3 movl %eax, -0x4(%rbp) @@ -485,25 +600,40 @@ 7: 0x0000000000400540 jmpq *0x200ae2(%rip) ; _GLOBAL_OFFSET_TABLE_ + 40 a.out`main + 15 at main.cpp:10 3: 0x000000000040066f callq 0x400540 ; symbol stub for: foo() - no more data''']) - - self.expect("thread trace dump instructions --skip 100 --forwards", inHistory=True, - substrs=['''thread #1: tid = 815455 - no more data''']) - - self.expect("", substrs=['''thread #1: tid = 815455 - no more data''']) - - - self.expect("thread trace dump instructions --raw --all --forwards", - substrs=['''thread #1: tid = 815455 + no more data""", + ], + ) + + self.expect( + "thread trace dump instructions --skip 100 --forwards", + inHistory=True, + substrs=[ + """thread #1: tid = 815455 + no more data""" + ], + ) + + self.expect( + "", + substrs=[ + """thread #1: tid = 815455 + no more data""" + ], + ) + + self.expect( + "thread trace dump instructions --raw --all --forwards", + substrs=[ + """thread #1: tid = 815455 3: 0x000000000040066f - 7: 0x0000000000400540''', - '''11: 0x0000000000400516 + 7: 0x0000000000400540""", + """11: 0x0000000000400516 ...missing instructions 12: (error) no memory mapped at this address: 0x00007ffff7df1950 - 16: 0x0000000000400674''', - '''61: 0x00000000004006a4 + 16: 0x0000000000400674""", + """61: 0x00000000004006a4 62: 0x00000000004006a7 63: 0x00000000004006a9 - no more data''']) + no more data""", + ], + ) diff --git a/lldb/test/API/commands/trace/TestTraceEvents.py b/lldb/test/API/commands/trace/TestTraceEvents.py --- a/lldb/test/API/commands/trace/TestTraceEvents.py +++ b/lldb/test/API/commands/trace/TestTraceEvents.py @@ -4,23 +4,35 @@ from lldbsuite.test import lldbutil from lldbsuite.test.decorators import * -class TestTraceEvents(TraceIntelPTTestCaseBase): +class TestTraceEvents(TraceIntelPTTestCaseBase): @testSBAPIAndCommands def testCPUEvents(self): - trace_description_file_path = os.path.join(self.getSourceDir(), "intelpt-multi-core-trace", "trace_missing_threads.json") - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"]) + trace_description_file_path = os.path.join( + self.getSourceDir(), + "intelpt-multi-core-trace", + "trace_missing_threads.json", + ) + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"] + ) - self.expect("thread trace dump instructions 3 -e --forward -c 5", - substrs=['''thread #3: tid = 3497496 + self.expect( + "thread trace dump instructions 3 -e --forward -c 5", + substrs=[ + """thread #3: tid = 3497496 0: (event) HW clock tick [40450075477621505] 1: (event) CPU core changed [new CPU=51] 2: (event) HW clock tick [40450075477657246] 3: (event) trace synchronization point [offset = 0x0x1331] - m.out`foo() + 65 at multi_thread.cpp:12:21''']) + m.out`foo() + 65 at multi_thread.cpp:12:21""" + ], + ) - self.expect("thread trace dump instructions 3 -e --forward -c 5 -J", - substrs=['''{ + self.expect( + "thread trace dump instructions 3 -e --forward -c 5 -J", + substrs=[ + """{ "id": 0, "event": "HW clock tick", "hwClock": 40450075477621505 @@ -29,28 +41,34 @@ "id": 1, "event": "CPU core changed", "cpuId": 51 - }''']) + }""" + ], + ) @testSBAPIAndCommands def testPauseEvents(self): - ''' + """ Everytime the target stops running on the CPU, a 'disabled' event will be emitted, which is represented by the TraceCursor API as a 'paused' event. - ''' - self.expect("target create " + - os.path.join(self.getSourceDir(), "intelpt-trace-multi-file", "a.out")) - self.expect("b 12") - self.expect("r") - self.traceStartThread() - self.expect("n") - self.expect("n") - self.expect("si") - self.expect("si") - self.expect("si") - # We ensure that the paused events are printed correctly forward - self.expect("thread trace dump instructions -e -f", - patterns=[f'''thread #1: tid = .* + """ + self.expect( + "target create " + + os.path.join(self.getSourceDir(), "intelpt-trace-multi-file", "a.out") + ) + self.expect("b 12") + self.expect("r") + self.traceStartThread() + self.expect("n") + self.expect("n") + self.expect("si") + self.expect("si") + self.expect("si") + # We ensure that the paused events are printed correctly forward + self.expect( + "thread trace dump instructions -e -f", + patterns=[ + f"""thread #1: tid = .* 0: \(event\) trace synchronization point \[offset \= 0x0xec0\] 1: \(event\) hardware disabled tracing a.out`main \+ 23 at main.cpp:12 @@ -76,11 +94,15 @@ 16: {ADDRESS_REGEX} callq .* ; symbol stub for: foo\(\) 17: \(event\) software disabled tracing a.out`symbol stub for: foo\(\) - 18: {ADDRESS_REGEX} jmpq''']) + 18: {ADDRESS_REGEX} jmpq""" + ], + ) - # We ensure that the paused events are printed correctly backward - self.expect("thread trace dump instructions -e --id 18", - patterns=[f'''thread #1: tid = .* + # We ensure that the paused events are printed correctly backward + self.expect( + "thread trace dump instructions -e --id 18", + patterns=[ + f"""thread #1: tid = .* a.out`symbol stub for: foo\(\) 18: {ADDRESS_REGEX} jmpq .* 17: \(event\) software disabled tracing @@ -106,4 +128,6 @@ 3: \(event\) software disabled tracing 2: {ADDRESS_REGEX} movl .* 1: \(event\) hardware disabled tracing - 0: \(event\) trace synchronization point \[offset \= 0x0xec0\]''']) + 0: \(event\) trace synchronization point \[offset \= 0x0xec0\]""" + ], + ) diff --git a/lldb/test/API/commands/trace/TestTraceExport.py b/lldb/test/API/commands/trace/TestTraceExport.py --- a/lldb/test/API/commands/trace/TestTraceExport.py +++ b/lldb/test/API/commands/trace/TestTraceExport.py @@ -7,34 +7,43 @@ from lldbsuite.test.decorators import * import os -class TestTraceExport(TraceIntelPTTestCaseBase): +class TestTraceExport(TraceIntelPTTestCaseBase): def testErrorMessages(self): ctf_test_file = self.getBuildArtifact("ctf-test.json") # We first check the output when there are no targets - self.expect(f"thread trace export ctf --file {ctf_test_file}", - substrs=["error: invalid target, create a target using the 'target create' command"], - error=True) + self.expect( + f"thread trace export ctf --file {ctf_test_file}", + substrs=[ + "error: invalid target, create a target using the 'target create' command" + ], + error=True, + ) # We now check the output when there's a non-running target - self.expect("target create " + - os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "target create " + + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) - self.expect(f"thread trace export ctf --file {ctf_test_file}", + self.expect( + f"thread trace export ctf --file {ctf_test_file}", substrs=["error: Command requires a current process."], - error=True) + error=True, + ) # Now we check the output when there's a running target without a trace self.expect("b main") self.expect("run") - self.expect(f"thread trace export ctf --file {ctf_test_file}", + self.expect( + f"thread trace export ctf --file {ctf_test_file}", substrs=["error: Process is not being traced"], - error=True) - + error=True, + ) def _testHtrBasicSuperBlockPassFullCheck(self): - ''' + """ Test the BasicSuperBlock pass of HTR. This test uses a very small trace so that the expected output is digestible and @@ -43,11 +52,13 @@ This test exhaustively checks that each entry in the output JSON is equal to the expected value. - ''' + """ - self.expect("trace load -v " + - os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), - substrs=["intel-pt"]) + self.expect( + "trace load -v " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), + substrs=["intel-pt"], + ) ctf_test_file = self.getBuildArtifact("ctf-test.json") @@ -57,7 +68,7 @@ with open(ctf_test_file) as f: data = json.load(f) - ''' + """ The expected JSON contained by "ctf-test.json" dur: number of instructions in the block @@ -73,41 +84,111 @@ See https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#heading=h.j75x71ritcoy for documentation on the Trace Event Format - ''' + """ # Comments on the right indicate if a block is a "head" and/or "tail" # See BasicSuperBlockMerge in TraceHTR.h for a description of the algorithm expected = [ - {"dur":1,"name":"0x400511","ph":"X","pid":0,"ts":0}, - {"dur":1,"name":"0x400518","ph":"X","pid":0,"ts":1}, - {"dur":1,"name":"0x40051f","ph":"X","pid":0,"ts":2}, - {"dur":1,"name":"0x400529","ph":"X","pid":0,"ts":3}, # head - {"dur":1,"name":"0x40052d","ph":"X","pid":0,"ts":4}, # tail - {"dur":1,"name":"0x400521","ph":"X","pid":0,"ts":5}, - {"dur":1,"name":"0x400525","ph":"X","pid":0,"ts":6}, - {"dur":1,"name":"0x400529","ph":"X","pid":0,"ts":7}, # head - {"dur":1,"name":"0x40052d","ph":"X","pid":0,"ts":8}, # tail - {"dur":1,"name":"0x400521","ph":"X","pid":0,"ts":9}, - {"dur":1,"name":"0x400525","ph":"X","pid":0,"ts":10}, - {"dur":1,"name":"0x400529","ph":"X","pid":0,"ts":11}, # head - {"dur":1,"name":"0x40052d","ph":"X","pid":0,"ts":12}, # tail - {"dur":1,"name":"0x400521","ph":"X","pid":0,"ts":13}, - {"dur":1,"name":"0x400525","ph":"X","pid":0,"ts":14}, - {"dur":1,"name":"0x400529","ph":"X","pid":0,"ts":15}, # head - {"dur":1,"name":"0x40052d","ph":"X","pid":0,"ts":16}, # tail - {"dur":1,"name":"0x400521","ph":"X","pid":0,"ts":17}, - {"dur":1,"name":"0x400525","ph":"X","pid":0,"ts":18}, - {"dur":1,"name":"0x400529","ph":"X","pid":0,"ts":19}, # head - {"dur":1,"name":"0x40052d","ph":"X","pid":0,"ts":20}, # tail - {"args":{"Metadata":{"Functions":[],"Number of Instructions":3}},"dur":3,"name":"0x400511","ph":"X","pid":1,"ts":0}, - {"args":{"Metadata":{"Functions":[],"Number of Instructions":2}},"dur":2,"name":"0x400529","ph":"X","pid":1,"ts":3}, # head, tail - {"args":{"Metadata":{"Functions":[],"Number of Instructions":2}},"dur":2,"name":"0x400521","ph":"X","pid":1,"ts":5}, - {"args":{"Metadata":{"Functions":[],"Number of Instructions":2}},"dur":2,"name":"0x400529","ph":"X","pid":1,"ts":7}, # head, tail - {"args":{"Metadata":{"Functions":[],"Number of Instructions":2}},"dur":2,"name":"0x400521","ph":"X","pid":1,"ts":9}, - {"args":{"Metadata":{"Functions":[],"Number of Instructions":2}},"dur":2,"name":"0x400529","ph":"X","pid":1,"ts":11}, # head, tail - {"args":{"Metadata":{"Functions":[],"Number of Instructions":2}},"dur":2,"name":"0x400521","ph":"X","pid":1,"ts":13}, - {"args":{"Metadata":{"Functions":[],"Number of Instructions":2}},"dur":2,"name":"0x400529","ph":"X","pid":1,"ts":15}, # head, tail - {"args":{"Metadata":{"Functions":[],"Number of Instructions":2}},"dur":2,"name":"0x400521","ph":"X","pid":1,"ts":17}, - {"args":{"Metadata":{"Functions":[],"Number of Instructions":2}},"dur":2,"name":"0x400529","ph":"X","pid":1,"ts":19} # head, tail + {"dur": 1, "name": "0x400511", "ph": "X", "pid": 0, "ts": 0}, + {"dur": 1, "name": "0x400518", "ph": "X", "pid": 0, "ts": 1}, + {"dur": 1, "name": "0x40051f", "ph": "X", "pid": 0, "ts": 2}, + {"dur": 1, "name": "0x400529", "ph": "X", "pid": 0, "ts": 3}, # head + {"dur": 1, "name": "0x40052d", "ph": "X", "pid": 0, "ts": 4}, # tail + {"dur": 1, "name": "0x400521", "ph": "X", "pid": 0, "ts": 5}, + {"dur": 1, "name": "0x400525", "ph": "X", "pid": 0, "ts": 6}, + {"dur": 1, "name": "0x400529", "ph": "X", "pid": 0, "ts": 7}, # head + {"dur": 1, "name": "0x40052d", "ph": "X", "pid": 0, "ts": 8}, # tail + {"dur": 1, "name": "0x400521", "ph": "X", "pid": 0, "ts": 9}, + {"dur": 1, "name": "0x400525", "ph": "X", "pid": 0, "ts": 10}, + {"dur": 1, "name": "0x400529", "ph": "X", "pid": 0, "ts": 11}, # head + {"dur": 1, "name": "0x40052d", "ph": "X", "pid": 0, "ts": 12}, # tail + {"dur": 1, "name": "0x400521", "ph": "X", "pid": 0, "ts": 13}, + {"dur": 1, "name": "0x400525", "ph": "X", "pid": 0, "ts": 14}, + {"dur": 1, "name": "0x400529", "ph": "X", "pid": 0, "ts": 15}, # head + {"dur": 1, "name": "0x40052d", "ph": "X", "pid": 0, "ts": 16}, # tail + {"dur": 1, "name": "0x400521", "ph": "X", "pid": 0, "ts": 17}, + {"dur": 1, "name": "0x400525", "ph": "X", "pid": 0, "ts": 18}, + {"dur": 1, "name": "0x400529", "ph": "X", "pid": 0, "ts": 19}, # head + {"dur": 1, "name": "0x40052d", "ph": "X", "pid": 0, "ts": 20}, # tail + { + "args": {"Metadata": {"Functions": [], "Number of Instructions": 3}}, + "dur": 3, + "name": "0x400511", + "ph": "X", + "pid": 1, + "ts": 0, + }, + { + "args": {"Metadata": {"Functions": [], "Number of Instructions": 2}}, + "dur": 2, + "name": "0x400529", + "ph": "X", + "pid": 1, + "ts": 3, + }, # head, tail + { + "args": {"Metadata": {"Functions": [], "Number of Instructions": 2}}, + "dur": 2, + "name": "0x400521", + "ph": "X", + "pid": 1, + "ts": 5, + }, + { + "args": {"Metadata": {"Functions": [], "Number of Instructions": 2}}, + "dur": 2, + "name": "0x400529", + "ph": "X", + "pid": 1, + "ts": 7, + }, # head, tail + { + "args": {"Metadata": {"Functions": [], "Number of Instructions": 2}}, + "dur": 2, + "name": "0x400521", + "ph": "X", + "pid": 1, + "ts": 9, + }, + { + "args": {"Metadata": {"Functions": [], "Number of Instructions": 2}}, + "dur": 2, + "name": "0x400529", + "ph": "X", + "pid": 1, + "ts": 11, + }, # head, tail + { + "args": {"Metadata": {"Functions": [], "Number of Instructions": 2}}, + "dur": 2, + "name": "0x400521", + "ph": "X", + "pid": 1, + "ts": 13, + }, + { + "args": {"Metadata": {"Functions": [], "Number of Instructions": 2}}, + "dur": 2, + "name": "0x400529", + "ph": "X", + "pid": 1, + "ts": 15, + }, # head, tail + { + "args": {"Metadata": {"Functions": [], "Number of Instructions": 2}}, + "dur": 2, + "name": "0x400521", + "ph": "X", + "pid": 1, + "ts": 17, + }, + { + "args": {"Metadata": {"Functions": [], "Number of Instructions": 2}}, + "dur": 2, + "name": "0x400529", + "ph": "X", + "pid": 1, + "ts": 19, + }, # head, tail ] # Check that the length of the expected JSON array is equal to the actual @@ -117,7 +198,7 @@ self.assertEqual(data[i], expected[i]) def _testHtrBasicSuperBlockPassSequenceCheck(self): - ''' + """ Test the BasicSuperBlock pass of HTR. This test exports a modest sized trace and only checks that a particular sequence of blocks are @@ -126,8 +207,10 @@ TODO: Once the "trace save" command is implemented, gather Intel PT trace of this program and load it like the other tests instead of manually executing the commands to trace the program. - ''' - self.expect(f"target create {os.path.join(self.getSourceDir(), 'intelpt-trace', 'export_ctf_test_program.out')}") + """ + self.expect( + f"target create {os.path.join(self.getSourceDir(), 'intelpt-trace', 'export_ctf_test_program.out')}" + ) self.expect("b main") self.expect("r") self.expect("b exit") @@ -139,14 +222,13 @@ self.expect(f"thread trace export ctf --file {ctf_test_file}") self.assertTrue(os.path.exists(ctf_test_file)) - with open(ctf_test_file) as f: data = json.load(f) num_units_by_layer = defaultdict(int) index_of_first_layer_1_block = None for i, event in enumerate(data): - layer_id = event.get('pid') + layer_id = event.get("pid") self.assertTrue(layer_id is not None) if layer_id == 1 and index_of_first_layer_1_block is None: index_of_first_layer_1_block = i @@ -154,19 +236,23 @@ # Check that there are only two layers and that the layer IDs are correct # Check that layer IDs are correct - self.assertTrue(len(num_units_by_layer) == 2 and 0 in num_units_by_layer and 1 in num_units_by_layer) + self.assertTrue( + len(num_units_by_layer) == 2 + and 0 in num_units_by_layer + and 1 in num_units_by_layer + ) # The expected block names for the first 7 blocks of layer 1 expected_block_names = [ - '0x4005f0', - '0x4005fe', - '0x400606: iterative_handle_request_by_id(int, int)', - '0x4005a7', - '0x4005af', - '0x4005b9: fast_handle_request(int)', - '0x4005d5: log_response(int)', + "0x4005f0", + "0x4005fe", + "0x400606: iterative_handle_request_by_id(int, int)", + "0x4005a7", + "0x4005af", + "0x4005b9: fast_handle_request(int)", + "0x4005d5: log_response(int)", ] data_index = index_of_first_layer_1_block for i in range(len(expected_block_names)): - self.assertEqual(data[data_index + i]['name'], expected_block_names[i]) + self.assertEqual(data[data_index + i]["name"], expected_block_names[i]) diff --git a/lldb/test/API/commands/trace/TestTraceLoad.py b/lldb/test/API/commands/trace/TestTraceLoad.py --- a/lldb/test/API/commands/trace/TestTraceLoad.py +++ b/lldb/test/API/commands/trace/TestTraceLoad.py @@ -4,24 +4,39 @@ from lldbsuite.test import lldbutil from lldbsuite.test.decorators import * + class TestTraceLoad(TraceIntelPTTestCaseBase): NO_DEBUG_INFO_TESTCASE = True @testSBAPIAndCommands def testLoadMultiCoreTrace(self): src_dir = self.getSourceDir() - trace_description_file_path = os.path.join(src_dir, "intelpt-multi-core-trace", "trace.json") - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"]) - self.expect("thread trace dump instructions 2 -t", - substrs=["19526: [19691636.212 ns] (error) decoding truncated: TSC 40450075478109270 exceeds maximum TSC value 40450075477704372, will skip decoding the remaining data of the PSB (skipping 774 of 825 bytes)", - "m.out`foo() + 65 at multi_thread.cpp:12:21", - "9524: [19691632.221 ns] 0x0000000000400ba7 jg 0x400bb3"]) - self.expect("thread trace dump instructions 3 -t", - substrs=["61831: [19736132.088 ns] 0x0000000000400bd7 addl $0x1, -0x4(%rbp)", - "m.out`bar() + 26 at multi_thread.cpp:20:6"]) - - self.expect("thread trace dump info --json", - substrs=['''{ + trace_description_file_path = os.path.join( + src_dir, "intelpt-multi-core-trace", "trace.json" + ) + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"] + ) + self.expect( + "thread trace dump instructions 2 -t", + substrs=[ + "19526: [19691636.212 ns] (error) decoding truncated: TSC 40450075478109270 exceeds maximum TSC value 40450075477704372, will skip decoding the remaining data of the PSB (skipping 774 of 825 bytes)", + "m.out`foo() + 65 at multi_thread.cpp:12:21", + "9524: [19691632.221 ns] 0x0000000000400ba7 jg 0x400bb3", + ], + ) + self.expect( + "thread trace dump instructions 3 -t", + substrs=[ + "61831: [19736132.088 ns] 0x0000000000400bd7 addl $0x1, -0x4(%rbp)", + "m.out`bar() + 26 at multi_thread.cpp:20:6", + ], + ) + + self.expect( + "thread trace dump info --json", + substrs=[ + """{ "traceTechnology": "intel-pt", "threadStats": { "tid": 3497234, @@ -31,7 +46,8 @@ "avgPerItemInBytes": null }, "timingInSeconds": { - "Decoding instructions": ''', ''' + "Decoding instructions": """, + """ }, "events": { "totalCount": 0, @@ -55,19 +71,25 @@ "totalPSBBlocks": 5, "totalContinuousExecutions": 153 } -}''']) - - self.expect("thread trace dump info 2 --json", - substrs=['''{ +}""", + ], + ) + + self.expect( + "thread trace dump info 2 --json", + substrs=[ + """{ "traceTechnology": "intel-pt", "threadStats": { "tid": 3497496, "traceItemsCount": 19527, "memoryUsage": { "totalInBytes": "175819", - "avgPerItemInBytes": 9.0038920469094084''', '''}, + "avgPerItemInBytes": 9.0038920469094084""", + """}, "timingInSeconds": { - "Decoding instructions": ''', ''' + "Decoding instructions": """, + """ }, "events": { "totalCount": 5, @@ -89,43 +111,72 @@ }, "globalStats": { "timingInSeconds": { - "Context switch and Intel PT traces correlation": 0''', '''}, + "Context switch and Intel PT traces correlation": 0""", + """}, "totalUnattributedPSBBlocks": 0, "totalCountinuosExecutions": 153, "totalPSBBlocks": 5, "totalContinuousExecutions": 153 } -}''']) +}""", + ], + ) @testSBAPIAndCommands def testLoadCompactMultiCoreTrace(self): src_dir = self.getSourceDir() - trace_description_file_path = os.path.join(src_dir, "intelpt-multi-core-trace", "trace.json") - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"]) - - self.expect("thread trace dump info 2", substrs=["Total number of continuous executions found: 153"]) + trace_description_file_path = os.path.join( + src_dir, "intelpt-multi-core-trace", "trace.json" + ) + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"] + ) + + self.expect( + "thread trace dump info 2", + substrs=["Total number of continuous executions found: 153"], + ) # we'll save the trace in compact format - compact_trace_bundle_dir = os.path.join(self.getBuildDir(), "intelpt-multi-core-trace-compact") + compact_trace_bundle_dir = os.path.join( + self.getBuildDir(), "intelpt-multi-core-trace-compact" + ) self.traceSave(compact_trace_bundle_dir, compact=True) # we'll delete the previous target and make sure it's trace object is deleted self.dbg.DeleteTarget(self.dbg.GetTargetAtIndex(0)) - self.expect("thread trace dump instructions 2 -t", substrs=["error: invalid target"], error=True) + self.expect( + "thread trace dump instructions 2 -t", + substrs=["error: invalid target"], + error=True, + ) # we'll load the compact trace and make sure it works - self.traceLoad(os.path.join(compact_trace_bundle_dir, "trace.json"), substrs=["intel-pt"]) - self.expect("thread trace dump instructions 2 -t", - substrs=["19526: [19691636.212 ns] (error) decoding truncated: TSC 40450075478109270 exceeds maximum TSC value 40450075477704372, will skip decoding the remaining data of the PSB (skipping 774 of 825 bytes)", - "m.out`foo() + 65 at multi_thread.cpp:12:21", - "19524: [19691632.221 ns] 0x0000000000400ba7 jg 0x400bb3"]) - self.expect("thread trace dump instructions 3 -t", - substrs=["61833: [19736136.079 ns] (error) decoding truncated: TSC 40450075478174268 exceeds maximum TSC value 40450075477820383, will skip decoding the remaining data of the PSB (skipping 296 of 297 bytes)", - "61831: [19736132.088 ns] 0x0000000000400bd7 addl $0x1, -0x4(%rbp)", - "m.out`bar() + 26 at multi_thread.cpp:20:6"]) + self.traceLoad( + os.path.join(compact_trace_bundle_dir, "trace.json"), substrs=["intel-pt"] + ) + self.expect( + "thread trace dump instructions 2 -t", + substrs=[ + "19526: [19691636.212 ns] (error) decoding truncated: TSC 40450075478109270 exceeds maximum TSC value 40450075477704372, will skip decoding the remaining data of the PSB (skipping 774 of 825 bytes)", + "m.out`foo() + 65 at multi_thread.cpp:12:21", + "19524: [19691632.221 ns] 0x0000000000400ba7 jg 0x400bb3", + ], + ) + self.expect( + "thread trace dump instructions 3 -t", + substrs=[ + "61833: [19736136.079 ns] (error) decoding truncated: TSC 40450075478174268 exceeds maximum TSC value 40450075477820383, will skip decoding the remaining data of the PSB (skipping 296 of 297 bytes)", + "61831: [19736132.088 ns] 0x0000000000400bd7 addl $0x1, -0x4(%rbp)", + "m.out`bar() + 26 at multi_thread.cpp:20:6", + ], + ) # This reduced the number of continuous executions to look at - self.expect("thread trace dump info 2", substrs=["Total number of continuous executions found: 3"]) + self.expect( + "thread trace dump info 2", + substrs=["Total number of continuous executions found: 3"], + ) # We clean up for the next run of this test self.dbg.DeleteTarget(self.dbg.GetTargetAtIndex(0)) @@ -133,34 +184,62 @@ @testSBAPIAndCommands def testLoadMultiCoreTraceWithStringNumbers(self): src_dir = self.getSourceDir() - trace_description_file_path = os.path.join(src_dir, "intelpt-multi-core-trace", "trace_with_string_numbers.json") - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"]) - self.expect("thread trace dump instructions 2 -t", - substrs=["19526: [19691636.212 ns] (error) decoding truncated: TSC 40450075478109270 exceeds maximum TSC value 40450075477704372, will skip decoding the remaining data of the PSB (skipping 774 of 825 bytes)", - "m.out`foo() + 65 at multi_thread.cpp:12:21", - "19524: [19691632.221 ns] 0x0000000000400ba7 jg 0x400bb3"]) - self.expect("thread trace dump instructions 3 -t", - substrs=["61831: [19736132.088 ns] 0x0000000000400bd7 addl $0x1, -0x4(%rbp)", - "m.out`bar() + 26 at multi_thread.cpp:20:6"]) + trace_description_file_path = os.path.join( + src_dir, "intelpt-multi-core-trace", "trace_with_string_numbers.json" + ) + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"] + ) + self.expect( + "thread trace dump instructions 2 -t", + substrs=[ + "19526: [19691636.212 ns] (error) decoding truncated: TSC 40450075478109270 exceeds maximum TSC value 40450075477704372, will skip decoding the remaining data of the PSB (skipping 774 of 825 bytes)", + "m.out`foo() + 65 at multi_thread.cpp:12:21", + "19524: [19691632.221 ns] 0x0000000000400ba7 jg 0x400bb3", + ], + ) + self.expect( + "thread trace dump instructions 3 -t", + substrs=[ + "61831: [19736132.088 ns] 0x0000000000400bd7 addl $0x1, -0x4(%rbp)", + "m.out`bar() + 26 at multi_thread.cpp:20:6", + ], + ) @testSBAPIAndCommands def testLoadMultiCoreTraceWithMissingThreads(self): src_dir = self.getSourceDir() - trace_description_file_path = os.path.join(src_dir, "intelpt-multi-core-trace", "trace_missing_threads.json") - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"]) - self.expect("thread trace dump instructions 3 -t", - substrs=["19526: [19691636.212 ns] (error) decoding truncated: TSC 40450075478109270 exceeds maximum TSC value 40450075477704372, will skip decoding the remaining data of the PSB (skipping 774 of 825 bytes)", - "m.out`foo() + 65 at multi_thread.cpp:12:21", - "19524: [19691632.221 ns] 0x0000000000400ba7 jg 0x400bb3"]) - self.expect("thread trace dump instructions 2 -t", - substrs=["61831: [19736132.088 ns] 0x0000000000400bd7 addl $0x1, -0x4(%rbp)", - "m.out`bar() + 26 at multi_thread.cpp:20:6"]) + trace_description_file_path = os.path.join( + src_dir, "intelpt-multi-core-trace", "trace_missing_threads.json" + ) + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"] + ) + self.expect( + "thread trace dump instructions 3 -t", + substrs=[ + "19526: [19691636.212 ns] (error) decoding truncated: TSC 40450075478109270 exceeds maximum TSC value 40450075477704372, will skip decoding the remaining data of the PSB (skipping 774 of 825 bytes)", + "m.out`foo() + 65 at multi_thread.cpp:12:21", + "19524: [19691632.221 ns] 0x0000000000400ba7 jg 0x400bb3", + ], + ) + self.expect( + "thread trace dump instructions 2 -t", + substrs=[ + "61831: [19736132.088 ns] 0x0000000000400bd7 addl $0x1, -0x4(%rbp)", + "m.out`bar() + 26 at multi_thread.cpp:20:6", + ], + ) @testSBAPIAndCommands def testLoadTrace(self): src_dir = self.getSourceDir() - trace_description_file_path = os.path.join(src_dir, "intelpt-trace", "trace.json") - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"]) + trace_description_file_path = os.path.join( + src_dir, "intelpt-trace", "trace.json" + ) + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"] + ) target = self.dbg.GetSelectedTarget() process = target.GetProcess() @@ -176,12 +255,17 @@ self.assertGreater(module.GetNumSections(), 0) self.assertEqual(module.GetSectionAtIndex(0).GetFileAddress(), 0x400000) - self.assertEqual("6AA9A4E2-6F28-2F33-377D-59FECE874C71-5B41261A", module.GetUUIDString()) + self.assertEqual( + "6AA9A4E2-6F28-2F33-377D-59FECE874C71-5B41261A", module.GetUUIDString() + ) # check that the Process and Thread objects were created correctly self.expect("thread info", substrs=["tid = 3842849"]) self.expect("thread list", substrs=["Process 1234 stopped", "tid = 3842849"]) - self.expect("thread trace dump info", substrs=['''thread #1: tid = 3842849 + self.expect( + "thread trace dump info", + substrs=[ + """thread #1: tid = 3842849 Trace technology: intel-pt @@ -193,21 +277,27 @@ Average memory usage per item (excluding raw trace): 9.00 bytes Timing for this thread: - Decoding instructions: ''', ''' + Decoding instructions: """, + """ Events: Number of individual events: 7 software disabled tracing: 2 hardware disabled tracing: 4 - trace synchronization point: 1''']) + trace synchronization point: 1""", + ], + ) @testSBAPIAndCommands def testLoadInvalidTraces(self): src_dir = self.getSourceDir() # We test first an invalid type - trace_description_file_path = os.path.join(src_dir, "intelpt-trace", "trace_bad.json") - expected_substrs = ['''error: expected object at traceBundle.processes[0] + trace_description_file_path = os.path.join( + src_dir, "intelpt-trace", "trace_bad.json" + ) + expected_substrs = [ + """error: expected object at traceBundle.processes[0] Context: { @@ -229,19 +319,35 @@ "family": integer, "model": integer, "stepping": integer - },'''] - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, error=True, substrs=expected_substrs) - + },""" + ] + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, + error=True, + substrs=expected_substrs, + ) # Now we test a wrong cpu family field in the global bundle description file - trace_description_file_path = os.path.join(src_dir, "intelpt-trace", "trace_bad2.json") - expected_substrs = ['error: expected uint64_t at traceBundle.cpuInfo.family', "Context", "Schema"] - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, error=True, substrs=expected_substrs) - + trace_description_file_path = os.path.join( + src_dir, "intelpt-trace", "trace_bad2.json" + ) + expected_substrs = [ + "error: expected uint64_t at traceBundle.cpuInfo.family", + "Context", + "Schema", + ] + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, + error=True, + substrs=expected_substrs, + ) # Now we test a missing field in the intel-pt settings - trace_description_file_path = os.path.join(src_dir, "intelpt-trace", "trace_bad4.json") - expected_substrs = ['''error: missing value at traceBundle.cpuInfo.family + trace_description_file_path = os.path.join( + src_dir, "intelpt-trace", "trace_bad4.json" + ) + expected_substrs = [ + """error: missing value at traceBundle.cpuInfo.family Context: { @@ -252,27 +358,48 @@ }, "processes": [], "type": "intel-pt" -}''', "Schema"] - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, error=True, substrs=expected_substrs) - +}""", + "Schema", + ] + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, + error=True, + substrs=expected_substrs, + ) # Now we test an incorrect load address in the intel-pt settings - trace_description_file_path = os.path.join(src_dir, "intelpt-trace", "trace_bad5.json") - expected_substrs = ['error: missing value at traceBundle.processes[1].pid', "Schema"] - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, error=True, substrs=expected_substrs) - + trace_description_file_path = os.path.join( + src_dir, "intelpt-trace", "trace_bad5.json" + ) + expected_substrs = [ + "error: missing value at traceBundle.processes[1].pid", + "Schema", + ] + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, + error=True, + substrs=expected_substrs, + ) # The following wrong schema will have a valid target and an invalid one. In the case of failure, # no targets should be created. self.assertEqual(self.dbg.GetNumTargets(), 0) - trace_description_file_path = os.path.join(src_dir, "intelpt-trace", "trace_bad3.json") - expected_substrs = ['error: missing value at traceBundle.processes[1].pid'] - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, error=True, substrs=expected_substrs) + trace_description_file_path = os.path.join( + src_dir, "intelpt-trace", "trace_bad3.json" + ) + expected_substrs = ["error: missing value at traceBundle.processes[1].pid"] + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, + error=True, + substrs=expected_substrs, + ) self.assertEqual(self.dbg.GetNumTargets(), 0) def testLoadTraceCursor(self): src_dir = self.getSourceDir() - trace_description_file_path = os.path.join(src_dir, "intelpt-multi-core-trace", "trace.json") + trace_description_file_path = os.path.join( + src_dir, "intelpt-multi-core-trace", "trace.json" + ) traceDescriptionFile = lldb.SBFileSpec(trace_description_file_path, True) error = lldb.SBError() @@ -282,7 +409,6 @@ target = self.dbg.GetSelectedTarget() process = target.process - # 1. Test some expected items of thread 1's trace cursor. thread1 = process.threads[1] cursor = trace.CreateNewCursor(error, thread1) @@ -304,15 +430,16 @@ cursor.GoToId(19526) self.assertTrue(cursor.IsError()) - self.assertEqual(cursor.GetError(), "decoding truncated: TSC 40450075478109270 exceeds maximum TSC value 40450075477704372, will skip decoding the remaining data of the PSB (skipping 774 of 825 bytes)") + self.assertEqual( + cursor.GetError(), + "decoding truncated: TSC 40450075478109270 exceeds maximum TSC value 40450075477704372, will skip decoding the remaining data of the PSB (skipping 774 of 825 bytes)", + ) cursor.GoToId(19524) self.assertTrue(cursor.IsInstruction()) self.assertEqual(cursor.GetLoadAddress(), 0x400BA7) - - # Helper function to check equality of the current item of two trace cursors. def assertCurrentTraceCursorItemEqual(lhs, rhs): self.assertTrue(lhs.HasValue() and rhs.HasValue()) @@ -343,8 +470,6 @@ sequentialTraversalCursor.Next() self.assertFalse(sequentialTraversalCursor.HasValue()) - - # 3. Test sequential traversal using sequential access API (ie Next()) # and random access API (ie GoToId()) simultaneously. randomAccessCursor = trace.CreateNewCursor(error, thread) @@ -357,39 +482,53 @@ while sequentialTraversalCursor.HasValue(): itemId = sequentialTraversalCursor.GetId() randomAccessCursor.GoToId(itemId) - assertCurrentTraceCursorItemEqual(sequentialTraversalCursor, randomAccessCursor) + assertCurrentTraceCursorItemEqual( + sequentialTraversalCursor, randomAccessCursor + ) sequentialTraversalCursor.Next() - - # 4. Test a random access with random access API (ie Seek()) and # sequential access API (ie consecutive calls to Next()). TEST_SEEK_ID = 3 - randomAccessCursor.GoToId(TEST_SEEK_ID ) + randomAccessCursor.GoToId(TEST_SEEK_ID) # Reset the sequential cursor sequentialTraversalCursor.Seek(0, lldb.eTraceCursorSeekTypeBeginning) sequentialTraversalCursor.SetForwards(True) - for _ in range(TEST_SEEK_ID): sequentialTraversalCursor.Next() - assertCurrentTraceCursorItemEqual(sequentialTraversalCursor, randomAccessCursor) + for _ in range(TEST_SEEK_ID): + sequentialTraversalCursor.Next() + assertCurrentTraceCursorItemEqual( + sequentialTraversalCursor, randomAccessCursor + ) @testSBAPIAndCommands def testLoadKernelTrace(self): # kernel section without loadAddress (using default loadAddress). src_dir = self.getSourceDir() - trace_description_file_path = os.path.join(src_dir, "intelpt-kernel-trace", "trace.json") - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"]) + trace_description_file_path = os.path.join( + src_dir, "intelpt-kernel-trace", "trace.json" + ) + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"] + ) self.expect("image list", substrs=["0xffffffff81000000", "modules/m.out"]) - self.expect("thread list", substrs=[ - "Process 1 stopped", - "* thread #1: tid = 0x002d", - " thread #2: tid = 0x0033"]) + self.expect( + "thread list", + substrs=[ + "Process 1 stopped", + "* thread #1: tid = 0x002d", + " thread #2: tid = 0x0033", + ], + ) # kernel section with custom loadAddress. - trace_description_file_path = os.path.join(src_dir, "intelpt-kernel-trace", - "trace_with_loadAddress.json") - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"]) + trace_description_file_path = os.path.join( + src_dir, "intelpt-kernel-trace", "trace_with_loadAddress.json" + ) + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, substrs=["intel-pt"] + ) self.expect("image list", substrs=["0x400000", "modules/m.out"]) @@ -398,11 +537,27 @@ src_dir = self.getSourceDir() # Test kernel section with non-empty processeses section. - trace_description_file_path = os.path.join(src_dir, "intelpt-kernel-trace", "trace_kernel_with_process.json") - expected_substrs = ['error: "processes" must be empty when "kernel" is provided when parsing traceBundle'] - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, error=True, substrs=expected_substrs) + trace_description_file_path = os.path.join( + src_dir, "intelpt-kernel-trace", "trace_kernel_with_process.json" + ) + expected_substrs = [ + 'error: "processes" must be empty when "kernel" is provided when parsing traceBundle' + ] + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, + error=True, + substrs=expected_substrs, + ) # Test kernel section without cpus section. - trace_description_file_path = os.path.join(src_dir, "intelpt-kernel-trace", "trace_kernel_wo_cpus.json") - expected_substrs = ['error: "cpus" is required when "kernel" is provided when parsing traceBundle'] - self.traceLoad(traceDescriptionFilePath=trace_description_file_path, error=True, substrs=expected_substrs) + trace_description_file_path = os.path.join( + src_dir, "intelpt-kernel-trace", "trace_kernel_wo_cpus.json" + ) + expected_substrs = [ + 'error: "cpus" is required when "kernel" is provided when parsing traceBundle' + ] + self.traceLoad( + traceDescriptionFilePath=trace_description_file_path, + error=True, + substrs=expected_substrs, + ) diff --git a/lldb/test/API/commands/trace/TestTraceSave.py b/lldb/test/API/commands/trace/TestTraceSave.py --- a/lldb/test/API/commands/trace/TestTraceSave.py +++ b/lldb/test/API/commands/trace/TestTraceSave.py @@ -5,71 +5,92 @@ from lldbsuite.test import lldbutil from lldbsuite.test.decorators import * + def find(predicate, seq): - for item in seq: - if predicate(item): - return item + for item in seq: + if predicate(item): + return item -class TestTraceSave(TraceIntelPTTestCaseBase): +class TestTraceSave(TraceIntelPTTestCaseBase): def testErrorMessages(self): # We first check the output when there are no targets - self.expect("trace save", - substrs=["error: invalid target, create a target using the 'target create' command"], - error=True) + self.expect( + "trace save", + substrs=[ + "error: invalid target, create a target using the 'target create' command" + ], + error=True, + ) # We now check the output when there's a non-running target - self.expect("target create " + - os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "target create " + + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) - self.expect("trace save", + self.expect( + "trace save", substrs=["error: Command requires a current process."], - error=True) + error=True, + ) # Now we check the output when there's a running target without a trace self.expect("b main") self.expect("run") - self.expect("trace save", - substrs=["error: Process is not being traced"], - error=True) + self.expect( + "trace save", substrs=["error: Process is not being traced"], error=True + ) def testSaveToInvalidDir(self): - self.expect("target create " + - os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "target create " + + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) self.expect("b main") self.expect("r") self.expect("thread trace start") self.expect("n") # Check the output when saving without providing the directory argument - self.expect("trace save ", - substrs=["error: a single path to a directory where the trace bundle will be created is required"], - error=True) + self.expect( + "trace save ", + substrs=[ + "error: a single path to a directory where the trace bundle will be created is required" + ], + error=True, + ) # Check the output when saving to an invalid directory - self.expect("trace save /", - substrs=["error: couldn't write to the file"], - error=True) + self.expect( + "trace save /", substrs=["error: couldn't write to the file"], error=True + ) def testSaveWhenNotLiveTrace(self): - self.expect("trace load -v " + - os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), - substrs=["intel-pt"]) + self.expect( + "trace load -v " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json"), + substrs=["intel-pt"], + ) # Check the output when not doing live tracing - self.expect("trace save " + - os.path.join(self.getBuildDir(), "intelpt-trace", "trace_not_live_dir")) + self.expect( + "trace save " + + os.path.join(self.getBuildDir(), "intelpt-trace", "trace_not_live_dir") + ) def testSaveMultiCpuTrace(self): - ''' - This test starts a per-cpu tracing session, then saves the session to disk, and - finally it loads it again. - ''' + """ + This test starts a per-cpu tracing session, then saves the session to disk, and + finally it loads it again. + """ self.skipIfPerCpuTracingIsNotSupported() - self.expect("target create " + - os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "target create " + + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) self.expect("b main") self.expect("r") self.expect("process trace start --per-cpu-tracing") @@ -90,7 +111,9 @@ for cpu in session["cpus"]: cpu_files_prefix = os.path.join(output_dir, "cpus", str(cpu["id"])) self.assertTrue(os.path.exists(cpu_files_prefix + ".intelpt_trace")) - self.assertTrue(os.path.exists(cpu_files_prefix + ".perf_context_switch_trace")) + self.assertTrue( + os.path.exists(cpu_files_prefix + ".perf_context_switch_trace") + ) # We expect at least one one process self.assertGreater(len(session["processes"]), 0) @@ -99,14 +122,18 @@ self.assertGreater(len(process["threads"]), 0) # We don't expect thread traces for thread in process["threads"]: - self.assertTrue(("iptTrace" not in thread) or (thread["iptTrace"] is None)) + self.assertTrue( + ("iptTrace" not in thread) or (thread["iptTrace"] is None) + ) original_trace_session_file = os.path.join(output_dir, "trace.json") checkSessionBundle(original_trace_session_file) output_dir = os.path.join(self.getBuildDir(), "intelpt-trace", "trace_save") self.expect("trace load " + os.path.join(output_dir, "trace.json")) - output_copy_dir = os.path.join(self.getBuildDir(), "intelpt-trace", "copy_trace_save") + output_copy_dir = os.path.join( + self.getBuildDir(), "intelpt-trace", "copy_trace_save" + ) self.expect("trace save " + output_copy_dir) # We now check that the new bundle is correct on its own @@ -122,20 +149,27 @@ self.assertEqual(len(original["processes"]), len(copy["processes"])) for process in original["processes"]: - copied_process = find(lambda proc : proc["pid"] == process["pid"], copy["processes"]) + copied_process = find( + lambda proc: proc["pid"] == process["pid"], copy["processes"] + ) self.assertTrue(copied_process is not None) for thread in process["threads"]: - copied_thread = find(lambda thr : thr["tid"] == thread["tid"], copied_process["threads"]) + copied_thread = find( + lambda thr: thr["tid"] == thread["tid"], + copied_process["threads"], + ) self.assertTrue(copied_thread is not None) for cpu in original["cpus"]: - copied_cpu = find(lambda cor : cor["id"] == cpu["id"], copy["cpus"]) + copied_cpu = find(lambda cor: cor["id"] == cpu["id"], copy["cpus"]) self.assertTrue(copied_cpu is not None) def testSaveTrace(self): - self.expect("target create " + - os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "target create " + + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) self.expect("b main") self.expect("r") self.expect("thread trace start") @@ -153,13 +187,19 @@ last_ten_instructions = res.GetOutput() # Now, save the trace to - self.expect("trace save " + - os.path.join(self.getBuildDir(), "intelpt-trace", "trace_copy_dir")) + self.expect( + "trace save " + + os.path.join(self.getBuildDir(), "intelpt-trace", "trace_copy_dir") + ) # Load the trace just saved - self.expect("trace load -v " + - os.path.join(self.getBuildDir(), "intelpt-trace", "trace_copy_dir", "trace.json"), - substrs=["intel-pt"]) + self.expect( + "trace load -v " + + os.path.join( + self.getBuildDir(), "intelpt-trace", "trace_copy_dir", "trace.json" + ), + substrs=["intel-pt"], + ) # Compare with instructions saved at the first time ci.HandleCommand("thread trace dump instructions -c 10 --forwards", res) @@ -171,8 +211,9 @@ self.assertEqual(res.GetOutput(), last_ten_instructions) def testSaveKernelTrace(self): - original_trace_file = os.path.join(self.getSourceDir(), "intelpt-kernel-trace", - "trace.json") + original_trace_file = os.path.join( + self.getSourceDir(), "intelpt-kernel-trace", "trace.json" + ) copied_trace_dir = os.path.join(self.getBuildDir(), "intelpt-kernel-trace") copied_trace_file = os.path.join(copied_trace_dir, "trace.json") @@ -186,5 +227,7 @@ copy_file = json.load(copy_file) self.assertTrue("kernel" in copy_file) - self.assertEqual(os.path.basename(original_file["kernel"]["file"]), - os.path.basename(copy_file["kernel"]["file"])) + self.assertEqual( + os.path.basename(original_file["kernel"]["file"]), + os.path.basename(copy_file["kernel"]["file"]), + ) diff --git a/lldb/test/API/commands/trace/TestTraceSchema.py b/lldb/test/API/commands/trace/TestTraceSchema.py --- a/lldb/test/API/commands/trace/TestTraceSchema.py +++ b/lldb/test/API/commands/trace/TestTraceSchema.py @@ -4,17 +4,25 @@ from lldbsuite.test import lldbutil from lldbsuite.test.decorators import * -class TestTraceLoad(TraceIntelPTTestCaseBase): +class TestTraceLoad(TraceIntelPTTestCaseBase): def testSchema(self): self.expect("trace schema intel-pt", substrs=["triple", "threads", "iptTrace"]) def testInvalidPluginSchema(self): - self.expect("trace schema invalid-plugin", error=True, - substrs=['error: no trace plug-in matches the specified type: "invalid-plugin"']) + self.expect( + "trace schema invalid-plugin", + error=True, + substrs=[ + 'error: no trace plug-in matches the specified type: "invalid-plugin"' + ], + ) def testAllSchemas(self): - self.expect("trace schema all", substrs=['''{ + self.expect( + "trace schema all", + substrs=[ + """{ "type": "intel-pt", "cpuInfo": { // CPU information gotten from, for example, /proc/cpuinfo. @@ -23,4 +31,6 @@ "family": integer, "model": integer, "stepping": integer - },''']) + },""" + ], + ) diff --git a/lldb/test/API/commands/trace/TestTraceStartStop.py b/lldb/test/API/commands/trace/TestTraceStartStop.py --- a/lldb/test/API/commands/trace/TestTraceStartStop.py +++ b/lldb/test/API/commands/trace/TestTraceStartStop.py @@ -4,16 +4,21 @@ from lldbsuite.test import lldbutil from lldbsuite.test.decorators import * -class TestTraceStartStop(TraceIntelPTTestCaseBase): +class TestTraceStartStop(TraceIntelPTTestCaseBase): def expectGenericHelpMessageForStartCommand(self): - self.expect("help thread trace start", - substrs=["Syntax: thread trace start []"]) + self.expect( + "help thread trace start", + substrs=["Syntax: thread trace start []"], + ) @testSBAPIAndCommands def testStartStopSessionFileThreads(self): # it should fail for processes from json session files - self.expect("trace load -v " + os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json")) + self.expect( + "trace load -v " + + os.path.join(self.getSourceDir(), "intelpt-trace", "trace.json") + ) # the help command should be the generic one, as it's not a live process self.expectGenericHelpMessageForStartCommand() @@ -28,83 +33,133 @@ @testSBAPIAndCommands def testStartSessionWithWrongSize(self): - self.expect("file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) self.expect("b main") self.expect("r") self.traceStartThread( - error=True, iptTraceSize=2000, - substrs=["The intel pt trace size must be a power of 2", "It was 2000"]) + error=True, + iptTraceSize=2000, + substrs=["The intel pt trace size must be a power of 2", "It was 2000"], + ) self.traceStartThread( - error=True, iptTraceSize=5000, - substrs=["The intel pt trace size must be a power of 2", "It was 5000"]) + error=True, + iptTraceSize=5000, + substrs=["The intel pt trace size must be a power of 2", "It was 5000"], + ) self.traceStartThread( - error=True, iptTraceSize=0, - substrs=["The intel pt trace size must be a power of 2", "It was 0"]) + error=True, + iptTraceSize=0, + substrs=["The intel pt trace size must be a power of 2", "It was 0"], + ) self.traceStartThread(iptTraceSize=1048576) @testSBAPIAndCommands def testStartSessionWithSizeDeclarationInUnits(self): - self.expect("file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) self.expect("b main") self.expect("r") self.traceStartThread( - error=True, iptTraceSize="abc", - substrs=["invalid bytes expression for 'abc'"]) + error=True, + iptTraceSize="abc", + substrs=["invalid bytes expression for 'abc'"], + ) self.traceStartThread( - error=True, iptTraceSize="123.12", - substrs=["invalid bytes expression for '123.12'"]) + error=True, + iptTraceSize="123.12", + substrs=["invalid bytes expression for '123.12'"], + ) self.traceStartThread( - error=True, iptTraceSize="\"\"", - substrs=["invalid bytes expression for ''"]) + error=True, iptTraceSize='""', substrs=["invalid bytes expression for ''"] + ) self.traceStartThread( - error=True, iptTraceSize="2000B", - substrs=["The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 2000"]) + error=True, + iptTraceSize="2000B", + substrs=[ + "The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 2000" + ], + ) self.traceStartThread( - error=True, iptTraceSize="3MB", - substrs=["The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3145728"]) + error=True, + iptTraceSize="3MB", + substrs=[ + "The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3145728" + ], + ) self.traceStartThread( - error=True, iptTraceSize="3MiB", - substrs=["The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3145728"]) + error=True, + iptTraceSize="3MiB", + substrs=[ + "The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3145728" + ], + ) self.traceStartThread( - error=True, iptTraceSize="3mib", - substrs=["The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3145728"]) + error=True, + iptTraceSize="3mib", + substrs=[ + "The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3145728" + ], + ) self.traceStartThread( - error=True, iptTraceSize="3M", - substrs=["The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3145728"]) + error=True, + iptTraceSize="3M", + substrs=[ + "The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3145728" + ], + ) self.traceStartThread( - error=True, iptTraceSize="3KB", - substrs=["The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3072"]) + error=True, + iptTraceSize="3KB", + substrs=[ + "The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3072" + ], + ) self.traceStartThread( - error=True, iptTraceSize="3KiB", - substrs=["The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3072"]) + error=True, + iptTraceSize="3KiB", + substrs=[ + "The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3072" + ], + ) self.traceStartThread( - error=True, iptTraceSize="3K", - substrs=["The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3072"]) + error=True, + iptTraceSize="3K", + substrs=[ + "The intel pt trace size must be a power of 2 greater than or equal to 4096 (2^12) bytes. It was 3072" + ], + ) self.traceStartThread( - error=True, iptTraceSize="3MS", - substrs=["invalid bytes expression for '3MS'"]) + error=True, + iptTraceSize="3MS", + substrs=["invalid bytes expression for '3MS'"], + ) self.traceStartThread(iptTraceSize="1048576") - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) def testSBAPIHelp(self): - self.expect("file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) self.expect("b main") self.expect("r") @@ -112,34 +167,46 @@ self.assertIn("iptTraceSize", help) self.assertIn("processBufferSizeLimit", help) - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) def testStoppingAThread(self): - self.expect("file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) self.expect("b main") self.expect("r") self.expect("thread trace start") self.expect("n") - self.expect("thread trace dump instructions", substrs=["""0x0000000000400511 movl $0x0, -0x4(%rbp) - no more data"""]) + self.expect( + "thread trace dump instructions", + substrs=[ + """0x0000000000400511 movl $0x0, -0x4(%rbp) + no more data""" + ], + ) # process stopping should stop the thread self.expect("process trace stop") self.expect("n") - self.expect("thread trace dump instructions", substrs=["not traced"], error=True) - + self.expect( + "thread trace dump instructions", substrs=["not traced"], error=True + ) - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) def testStartStopLiveThreads(self): # The help command should be the generic one if there's no process running self.expectGenericHelpMessageForStartCommand() - self.expect("thread trace start", error=True, - substrs=["error: Process not available"]) + self.expect( + "thread trace start", error=True, substrs=["error: Process not available"] + ) - self.expect("file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) self.expect("b main") - self.expect("thread trace start", error=True, - substrs=["error: Process not available"]) + self.expect( + "thread trace start", error=True, substrs=["error: Process not available"] + ) # The help command should be the generic one if there's still no process running self.expectGenericHelpMessageForStartCommand() @@ -147,79 +214,115 @@ self.expect("r") # This fails because "trace start" hasn't been called yet - self.expect("thread trace stop", error=True, - substrs=["error: Process is not being traced"]) - + self.expect( + "thread trace stop", + error=True, + substrs=["error: Process is not being traced"], + ) # the help command should be the intel-pt one now - self.expect("help thread trace start", - substrs=["Start tracing one or more threads with intel-pt.", - "Syntax: thread trace start [ ...] []"]) + self.expect( + "help thread trace start", + substrs=[ + "Start tracing one or more threads with intel-pt.", + "Syntax: thread trace start [ ...] []", + ], + ) # We start tracing with a small buffer size self.expect("thread trace start 1 --size 4096") # We fail if we try to trace again - self.expect("thread trace start", error=True, - substrs=["error: Thread ", "already traced"]) + self.expect( + "thread trace start", + error=True, + substrs=["error: Thread ", "already traced"], + ) # We can reconstruct the single instruction executed in the first line self.expect("n") - self.expect("thread trace dump instructions -f", - patterns=[f'''thread #1: tid = .* + self.expect( + "thread trace dump instructions -f", + patterns=[ + f"""thread #1: tid = .* a.out`main \+ 4 at main.cpp:2 - 2: {ADDRESS_REGEX} movl''']) + 2: {ADDRESS_REGEX} movl""" + ], + ) # We can reconstruct the instructions up to the second line self.expect("n") - self.expect("thread trace dump instructions -f", - patterns=[f'''thread #1: tid = .* + self.expect( + "thread trace dump instructions -f", + patterns=[ + f"""thread #1: tid = .* a.out`main \+ 4 at main.cpp:2 2: {ADDRESS_REGEX} movl .* a.out`main \+ 11 at main.cpp:4 4: {ADDRESS_REGEX} movl .* 6: {ADDRESS_REGEX} jmp .* ; <\+28> at main.cpp:4 8: {ADDRESS_REGEX} cmpl .* - 10: {ADDRESS_REGEX} jle .* ; <\+20> at main.cpp:5''']) - - self.expect("thread trace dump instructions", - patterns=[f'''thread #1: tid = .* + 10: {ADDRESS_REGEX} jle .* ; <\+20> at main.cpp:5""" + ], + ) + + self.expect( + "thread trace dump instructions", + patterns=[ + f"""thread #1: tid = .* a.out`main \+ 32 at main.cpp:4 10: {ADDRESS_REGEX} jle .* ; <\+20> at main.cpp:5 8: {ADDRESS_REGEX} cmpl .* 6: {ADDRESS_REGEX} jmp .* ; <\+28> at main.cpp:4 4: {ADDRESS_REGEX} movl .* a.out`main \+ 4 at main.cpp:2 - 2: {ADDRESS_REGEX} movl .* ''']) + 2: {ADDRESS_REGEX} movl .* """ + ], + ) # We stop tracing self.expect("thread trace stop") # We can't stop twice - self.expect("thread trace stop", error=True, - substrs=["error: Thread ", "not currently traced"]) + self.expect( + "thread trace stop", + error=True, + substrs=["error: Thread ", "not currently traced"], + ) # We trace again from scratch, this time letting LLDB to pick the current # thread self.expect("thread trace start") self.expect("n") - self.expect("thread trace dump instructions -f", - patterns=[f'''thread #1: tid = .* + self.expect( + "thread trace dump instructions -f", + patterns=[ + f"""thread #1: tid = .* a.out`main \+ 20 at main.cpp:5 - 2: {ADDRESS_REGEX} xorl''']) - - self.expect("thread trace dump instructions", - patterns=[f'''thread #1: tid = .* + 2: {ADDRESS_REGEX} xorl""" + ], + ) + + self.expect( + "thread trace dump instructions", + patterns=[ + f"""thread #1: tid = .* a.out`main \+ 20 at main.cpp:5 - 2: {ADDRESS_REGEX} xorl''']) + 2: {ADDRESS_REGEX} xorl""" + ], + ) self.expect("c") # Now the process has finished, so the commands should fail - self.expect("thread trace start", error=True, - substrs=["error: Process must be launched"]) + self.expect( + "thread trace start", + error=True, + substrs=["error: Process must be launched"], + ) - self.expect("thread trace stop", error=True, - substrs=["error: Process must be launched"]) + self.expect( + "thread trace stop", error=True, substrs=["error: Process must be launched"] + ) # We should be able to trace the program if we relaunch it # For this, we'll trace starting at a different point in the new @@ -230,6 +333,10 @@ self.expect("thread trace start") # We can reconstruct the single instruction executed in the first line self.expect("si") - self.expect("thread trace dump instructions -c 1", - patterns=[f'''thread #1: tid = .* - a.out`main \+ 11 at main.cpp:4''']) + self.expect( + "thread trace dump instructions -c 1", + patterns=[ + f"""thread #1: tid = .* + a.out`main \+ 11 at main.cpp:4""" + ], + ) diff --git a/lldb/test/API/commands/trace/TestTraceTSC.py b/lldb/test/API/commands/trace/TestTraceTSC.py --- a/lldb/test/API/commands/trace/TestTraceTSC.py +++ b/lldb/test/API/commands/trace/TestTraceTSC.py @@ -4,25 +4,31 @@ from lldbsuite.test import lldbutil from lldbsuite.test.decorators import * -class TestTraceTimestampCounters(TraceIntelPTTestCaseBase): +class TestTraceTimestampCounters(TraceIntelPTTestCaseBase): @testSBAPIAndCommands - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) def testTscPerThread(self): - self.expect("file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) self.expect("b main") self.expect("r") self.traceStartThread(enableTsc=True) self.expect("n") - self.expect("thread trace dump instructions -t -c 1", - patterns=[": \[\d+.\d+ ns\] 0x0000000000400511 movl"]) + self.expect( + "thread trace dump instructions -t -c 1", + patterns=[": \[\d+.\d+ ns\] 0x0000000000400511 movl"], + ) @testSBAPIAndCommands - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) def testMultipleTscsPerThread(self): - self.expect("file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) self.expect("b main") self.expect("r") @@ -44,43 +50,57 @@ # We check that the values are right when dumping a specific id for id, timestamp in id_to_timestamp.items(): - self.expect(f"thread trace dump instructions -t --id {id} -c 1", - substrs=[f"{id}: [{timestamp} ns]"]) + self.expect( + f"thread trace dump instructions -t --id {id} -c 1", + substrs=[f"{id}: [{timestamp} ns]"], + ) @testSBAPIAndCommands - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) def testTscPerProcess(self): - self.expect("file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) self.expect("b main") self.expect("r") self.traceStartProcess(enableTsc=True) self.expect("n") - self.expect("thread trace dump instructions -t -c 1", - patterns=[": \[\d+.\d+ ns\] 0x0000000000400511 movl"]) + self.expect( + "thread trace dump instructions -t -c 1", + patterns=[": \[\d+.\d+ ns\] 0x0000000000400511 movl"], + ) - self.expect("thread trace dump instructions -t -c 1 --pretty-json", - patterns=['''"timestamp_ns": "\d+.\d+"''']) + self.expect( + "thread trace dump instructions -t -c 1 --pretty-json", + patterns=['''"timestamp_ns": "\d+.\d+"'''], + ) @testSBAPIAndCommands - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) def testDumpingAfterTracingWithoutTsc(self): - self.expect("file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + self.expect( + "file " + os.path.join(self.getSourceDir(), "intelpt-trace", "a.out") + ) self.expect("b main") self.expect("r") self.traceStartThread(enableTsc=False) self.expect("n") - self.expect("thread trace dump instructions -t -c 1", - patterns=[": \[unavailable\] 0x0000000000400511 movl"]) + self.expect( + "thread trace dump instructions -t -c 1", + patterns=[": \[unavailable\] 0x0000000000400511 movl"], + ) - self.expect("thread trace dump instructions -t -c 1 --json", - substrs=['''"timestamp_ns":null''']) + self.expect( + "thread trace dump instructions -t -c 1 --json", + substrs=[""""timestamp_ns":null"""], + ) @testSBAPIAndCommands - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) def testPSBPeriod(self): def isPSBSupported(): caps_file = "/sys/bus/event_source/devices/intel_pt/caps/psb_cyc" @@ -102,7 +122,6 @@ values.append(i) return values - if not isPSBSupported(): self.skipTest("PSB period unsupported") @@ -110,7 +129,9 @@ # 0 should always be valid, and it's assumed by lldb-server self.assertEqual(valid_psb_values[0], 0) - self.expect("file " + (os.path.join(self.getSourceDir(), "intelpt-trace", "a.out"))) + self.expect( + "file " + (os.path.join(self.getSourceDir(), "intelpt-trace", "a.out")) + ) self.expect("b main") self.expect("r") @@ -125,8 +146,11 @@ self.traceStopProcess() # we now test invalid values - self.traceStartThread(psbPeriod=valid_psb_values[-1] + 1, error=True, - substrs=["Invalid psb_period. Valid values are: 0"]) + self.traceStartThread( + psbPeriod=valid_psb_values[-1] + 1, + error=True, + substrs=["Invalid psb_period. Valid values are: 0"], + ) # TODO: dump the perf_event_attr.config as part of the upcoming "trace dump info" # command and check that the psb period is included there. diff --git a/lldb/test/API/commands/trace/multiple-threads/TestTraceStartStopMultipleThreads.py b/lldb/test/API/commands/trace/multiple-threads/TestTraceStartStopMultipleThreads.py --- a/lldb/test/API/commands/trace/multiple-threads/TestTraceStartStopMultipleThreads.py +++ b/lldb/test/API/commands/trace/multiple-threads/TestTraceStartStopMultipleThreads.py @@ -5,9 +5,9 @@ from lldbsuite.test import lldbutil from lldbsuite.test.decorators import * -class TestTraceStartStopMultipleThreads(TraceIntelPTTestCaseBase): - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) +class TestTraceStartStopMultipleThreads(TraceIntelPTTestCaseBase): + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) @testSBAPIAndCommands def testStartMultipleLiveThreads(self): self.build() @@ -23,15 +23,15 @@ self.traceStartProcess() self.expect("continue") - self.expect("thread trace dump instructions", substrs=['main.cpp:9']) + self.expect("thread trace dump instructions", substrs=["main.cpp:9"]) # We'll see here the second thread self.expect("continue") - self.expect("thread trace dump instructions", substrs=['main.cpp:4']) + self.expect("thread trace dump instructions", substrs=["main.cpp:4"]) self.traceStopProcess() - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) @testSBAPIAndCommands def testStartMultipleLiveThreadsWithStops(self): self.build() @@ -50,25 +50,25 @@ self.expect("continue") # We are in thread 2 - self.expect("thread trace dump instructions", substrs=['main.cpp:9']) - self.expect("thread trace dump instructions 2", substrs=['main.cpp:9']) + self.expect("thread trace dump instructions", substrs=["main.cpp:9"]) + self.expect("thread trace dump instructions 2", substrs=["main.cpp:9"]) # We stop tracing it self.expect("thread trace stop 2") # The trace is still in memory - self.expect("thread trace dump instructions 2", substrs=['main.cpp:9']) + self.expect("thread trace dump instructions 2", substrs=["main.cpp:9"]) # We'll stop at the next breakpoint, thread 2 will be still alive, but not traced. Thread 3 will be traced self.expect("continue") - self.expect("thread trace dump instructions", substrs=['main.cpp:4']) - self.expect("thread trace dump instructions 3", substrs=['main.cpp:4']) + self.expect("thread trace dump instructions", substrs=["main.cpp:4"]) + self.expect("thread trace dump instructions 3", substrs=["main.cpp:4"]) - self.expect("thread trace dump instructions 2", substrs=['not traced']) + self.expect("thread trace dump instructions 2", substrs=["not traced"]) self.traceStopProcess() - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) @testSBAPIAndCommands def testStartMultipleLiveThreadsWithStops(self): self.build() @@ -87,25 +87,29 @@ self.expect("continue") # We are in thread 2 - self.expect("thread trace dump instructions", substrs=['main.cpp:9']) - self.expect("thread trace dump instructions 2", substrs=['main.cpp:9']) + self.expect("thread trace dump instructions", substrs=["main.cpp:9"]) + self.expect("thread trace dump instructions 2", substrs=["main.cpp:9"]) # We stop tracing all self.expect("thread trace stop all") # The trace is still in memory - self.expect("thread trace dump instructions 2", substrs=['main.cpp:9']) + self.expect("thread trace dump instructions 2", substrs=["main.cpp:9"]) # We'll stop at the next breakpoint in thread 3, thread 2 and 3 will be alive, but only 3 traced. self.expect("continue") - self.expect("thread trace dump instructions", substrs=['main.cpp:4']) - self.expect("thread trace dump instructions 3", substrs=['main.cpp:4']) - self.expect("thread trace dump instructions 1", substrs=['not traced'], error=True) - self.expect("thread trace dump instructions 2", substrs=['not traced'], error=True) + self.expect("thread trace dump instructions", substrs=["main.cpp:4"]) + self.expect("thread trace dump instructions 3", substrs=["main.cpp:4"]) + self.expect( + "thread trace dump instructions 1", substrs=["not traced"], error=True + ) + self.expect( + "thread trace dump instructions 2", substrs=["not traced"], error=True + ) self.traceStopProcess() - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) def testStartMultipleLiveThreadsWithThreadStartAll(self): self.build() exe = self.getBuildArtifact("a.out") @@ -123,21 +127,27 @@ # Now we have instructions in thread's 2 trace self.expect("n") - self.expect("thread trace dump instructions 2", substrs=['main.cpp:11']) + self.expect("thread trace dump instructions 2", substrs=["main.cpp:11"]) # We stop tracing all self.runCmd("thread trace stop all") # The trace is still in memory - self.expect("thread trace dump instructions 2", substrs=['main.cpp:11']) + self.expect("thread trace dump instructions 2", substrs=["main.cpp:11"]) # We'll stop at the next breakpoint in thread 3, and nothing should be traced self.expect("continue") - self.expect("thread trace dump instructions 3", substrs=['not traced'], error=True) - self.expect("thread trace dump instructions 1", substrs=['not traced'], error=True) - self.expect("thread trace dump instructions 2", substrs=['not traced'], error=True) - - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + self.expect( + "thread trace dump instructions 3", substrs=["not traced"], error=True + ) + self.expect( + "thread trace dump instructions 1", substrs=["not traced"], error=True + ) + self.expect( + "thread trace dump instructions 2", substrs=["not traced"], error=True + ) + + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) @testSBAPIAndCommands def testStartMultipleLiveThreadsWithSmallTotalLimit(self): self.build() @@ -152,13 +162,13 @@ self.traceStartProcess(processBufferSizeLimit=5000) # we get the stop event when trace 2 appears and can't be traced - self.expect("c", substrs=['Thread', "can't be traced"]) + self.expect("c", substrs=["Thread", "can't be traced"]) # we get the stop event when trace 3 appears and can't be traced - self.expect("c", substrs=['Thread', "can't be traced"]) + self.expect("c", substrs=["Thread", "can't be traced"]) self.traceStopProcess() - @skipIf(oslist=no_match(['linux']), archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=no_match(["linux"]), archs=no_match(["i386", "x86_64"])) @testSBAPIAndCommands def testStartPerCpuSession(self): self.skipIfPerCpuTracingIsNotSupported() @@ -172,27 +182,39 @@ # We should fail if we hit the total buffer limit. Useful if the number # of cpus is huge. - self.traceStartProcess(error="True", processBufferSizeLimit=100, + self.traceStartProcess( + error="True", + processBufferSizeLimit=100, perCpuTracing=True, - substrs=["The process can't be traced because the process trace size " - "limit has been reached. Consider retracing with a higher limit."]) + substrs=[ + "The process can't be traced because the process trace size " + "limit has been reached. Consider retracing with a higher limit." + ], + ) self.traceStartProcess(perCpuTracing=True) self.traceStopProcess() self.traceStartProcess(perCpuTracing=True) # We can't support multiple per-cpu tracing sessions. - self.traceStartProcess(error=True, perCpuTracing=True, - substrs=["Process currently traced. Stop process tracing first"]) + self.traceStartProcess( + error=True, + perCpuTracing=True, + substrs=["Process currently traced. Stop process tracing first"], + ) # We can't support tracing per thread is per cpu is enabled. self.traceStartThread( - error="True", - substrs=["Thread with tid ", "is currently traced"]) + error="True", substrs=["Thread with tid ", "is currently traced"] + ) # We can't stop individual thread when per cpu is enabled. - self.traceStopThread(error="True", - substrs=["Can't stop tracing an individual thread when per-cpu process tracing is enabled"]) + self.traceStopThread( + error="True", + substrs=[ + "Can't stop tracing an individual thread when per-cpu process tracing is enabled" + ], + ) # We move forward a little bit to collect some data self.expect("b 19") @@ -202,12 +224,16 @@ # Besides that, we need to get tsc-to-nanos conversion information. # We first parse the json response from the custom packet - self.runCmd("""process plugin packet send 'jLLDBTraceGetState:{"type":"intel-pt"}]'""") - response_header = 'response: ' + self.runCmd( + """process plugin packet send 'jLLDBTraceGetState:{"type":"intel-pt"}]'""" + ) + response_header = "response: " output = None for line in self.res.GetOutput().splitlines(): if line.find(response_header) != -1: - response = line[line.find(response_header) + len(response_header):].strip() + response = line[ + line.find(response_header) + len(response_header) : + ].strip() output = json.loads(response) self.assertTrue(output is not None) diff --git a/lldb/test/API/commands/version/TestVersion.py b/lldb/test/API/commands/version/TestVersion.py --- a/lldb/test/API/commands/version/TestVersion.py +++ b/lldb/test/API/commands/version/TestVersion.py @@ -2,16 +2,17 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * -class VersionTestCase(TestBase): +class VersionTestCase(TestBase): @no_debug_info_test def test_version(self): # Should work even when people patch the output, # so let's just assume that every vendor at least mentions # 'lldb' in their version string. - self.expect("version", substrs=['lldb']) + self.expect("version", substrs=["lldb"]) @no_debug_info_test def test_version_invalid_invocation(self): - self.expect("version a", error=True, - substrs=["'version' doesn't take any arguments."]) + self.expect( + "version a", error=True, substrs=["'version' doesn't take any arguments."] + ) diff --git a/lldb/test/API/commands/watchpoints/hello_watchlocation/TestWatchLocation.py b/lldb/test/API/commands/watchpoints/hello_watchlocation/TestWatchLocation.py --- a/lldb/test/API/commands/watchpoints/hello_watchlocation/TestWatchLocation.py +++ b/lldb/test/API/commands/watchpoints/hello_watchlocation/TestWatchLocation.py @@ -3,7 +3,6 @@ """ - import re import lldb from lldbsuite.test.decorators import * @@ -18,30 +17,31 @@ # Call super's setUp(). TestBase.setUp(self) # Our simple source filename. - self.source = 'main.cpp' + self.source = "main.cpp" # Find the line number to break inside main(). - self.line = line_number( - self.source, '// Set break point at this line.') + self.line = line_number(self.source, "// Set break point at this line.") # This is for verifying that watch location works. self.violating_func = "do_bad_thing_with_location" # Build dictionary to have unique executable names for each test # method. self.exe_name = self.testMethodName - self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} + self.d = {"CXX_SOURCES": self.source, "EXE": self.exe_name} # on arm64 targets, lldb has incorrect hit-count / ignore-counts # for watchpoints when they are hit with multiple threads at # the same time. Tracked as llvm.org/pr49433 # or rdar://93863107 inside Apple. - def affected_by_radar_93863107(self): - return (self.getArchitecture() in ['arm64', 'arm64e']) and self.platformIsDarwin() + def affected_by_radar_93863107(self): + return ( + self.getArchitecture() in ["arm64", "arm64e"] + ) and self.platformIsDarwin() # Most of the MIPS boards provide only one H/W watchpoints, and S/W # watchpoints are not supported yet - @expectedFailureAll(triple=re.compile('^mips')) + @expectedFailureAll(triple=re.compile("^mips")) # SystemZ and PowerPC also currently supports only one H/W watchpoint - @expectedFailureAll(archs=['powerpc64le', 's390x']) - @skipIfWindows # This test is flaky on Windows + @expectedFailureAll(archs=["powerpc64le", "s390x"]) + @skipIfWindows # This test is flaky on Windows def test_hello_watchlocation(self): """Test watching a location with '-s size' option.""" self.build(dictionary=self.d) @@ -51,69 +51,69 @@ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1, loc_exact=False) + self, None, self.line, num_expected_locations=1, loc_exact=False + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a write-type watchpoint pointed to by 'g_char_ptr'. self.expect( "watchpoint set expression -w write -s 1 -- g_char_ptr", WATCHPOINT_CREATED, - substrs=[ - 'Watchpoint created', - 'size = 1', - 'type = w']) + substrs=["Watchpoint created", "size = 1", "type = w"], + ) # Get a hold of the watchpoint id just created, it is used later on to # match the watchpoint id which is expected to be fired. match = re.match( - "Watchpoint created: Watchpoint (.*):", - self.res.GetOutput().splitlines()[0]) + "Watchpoint created: Watchpoint (.*):", self.res.GetOutput().splitlines()[0] + ) if match: expected_wp_id = int(match.group(1), 0) else: self.fail("Grokking watchpoint id faailed!") self.runCmd("expr unsigned val = *g_char_ptr; val") - self.expect(self.res.GetOutput().splitlines()[0], exe=False, - endstr=' = 0') + self.expect(self.res.GetOutput().splitlines()[0], exe=False, endstr=" = 0") self.runCmd("watchpoint set expression -w write -s 4 -- &threads[0]") # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['hit_count = 0']) + self.expect("watchpoint list -v", substrs=["hit_count = 0"]) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type), but # only once. The stop reason of the thread should be watchpoint. - self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stopped', - 'stop reason = watchpoint %d' % expected_wp_id]) + self.expect( + "thread list", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stopped", "stop reason = watchpoint %d" % expected_wp_id], + ) # Switch to the thread stopped due to watchpoint and issue some # commands. self.switch_to_thread_with_stop_reason(lldb.eStopReasonWatchpoint) self.runCmd("thread backtrace") - self.expect("frame info", - substrs=[self.violating_func]) + self.expect("frame info", substrs=[self.violating_func]) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be the same as the number of threads that # stopped on a watchpoint. threads = lldbutil.get_stopped_threads( - self.process(), lldb.eStopReasonWatchpoint) + self.process(), lldb.eStopReasonWatchpoint + ) if not self.affected_by_radar_93863107(): - self.expect("watchpoint list -v", - substrs=['hit_count = %d' % len(threads)]) + self.expect("watchpoint list -v", substrs=["hit_count = %d" % len(threads)]) self.runCmd("thread backtrace all") diff --git a/lldb/test/API/commands/watchpoints/hello_watchpoint/TestMyFirstWatchpoint.py b/lldb/test/API/commands/watchpoints/hello_watchpoint/TestMyFirstWatchpoint.py --- a/lldb/test/API/commands/watchpoints/hello_watchpoint/TestMyFirstWatchpoint.py +++ b/lldb/test/API/commands/watchpoints/hello_watchpoint/TestMyFirstWatchpoint.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -17,15 +16,13 @@ # Call super's setUp(). TestBase.setUp(self) # Our simple source filename. - self.source = 'main.c' + self.source = "main.c" # Find the line number to break inside main(). - self.line = line_number( - self.source, '// Set break point at this line.') + self.line = line_number(self.source, "// Set break point at this line.") # And the watchpoint variable declaration line number. - self.decl = line_number(self.source, - '// Watchpoint variable declaration.') - self.exe_name = self.getBuildArtifact('a.out') - self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + self.decl = line_number(self.source, "// Watchpoint variable declaration.") + self.exe_name = self.getBuildArtifact("a.out") + self.d = {"C_SOURCES": self.source, "EXE": self.exe_name} @add_test_categories(["basic_process"]) def test_hello_watchpoint_using_watchpoint_set(self): @@ -38,16 +35,19 @@ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1) + self, None, self.line, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a write-type watchpoint for 'global'. # There should be only one watchpoint hit (see main.c). @@ -55,25 +55,26 @@ "watchpoint set variable -w write global", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = w', - '%s:%d' % - (self.source, - self.decl)]) + "Watchpoint created", + "size = 4", + "type = w", + "%s:%d" % (self.source, self.decl), + ], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['hit_count = 0']) + self.expect("watchpoint list -v", substrs=["hit_count = 0"]) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type), but # only once. The stop reason of the thread should be watchpoint. - self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stopped', - 'stop reason = watchpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stopped", "stop reason = watchpoint"], + ) self.runCmd("process continue") @@ -81,10 +82,9 @@ process = self.dbg.GetSelectedTarget().GetProcess() if process.GetState() == lldb.eStateStopped: self.assertFalse( - lldbutil.get_stopped_thread( - process, lldb.eStopReasonWatchpoint)) + lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. - self.expect("watchpoint list -v", - substrs=['hit_count = 1']) + self.expect("watchpoint list -v", substrs=["hit_count = 1"]) diff --git a/lldb/test/API/commands/watchpoints/multi_watchpoint_slots/TestWatchpointMultipleSlots.py b/lldb/test/API/commands/watchpoints/multi_watchpoint_slots/TestWatchpointMultipleSlots.py --- a/lldb/test/API/commands/watchpoints/multi_watchpoint_slots/TestWatchpointMultipleSlots.py +++ b/lldb/test/API/commands/watchpoints/multi_watchpoint_slots/TestWatchpointMultipleSlots.py @@ -19,16 +19,15 @@ TestBase.setUp(self) # Source filename. - self.source = 'main.c' + self.source = "main.c" # Output filename. self.exe_name = self.getBuildArtifact("a.out") - self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + self.d = {"C_SOURCES": self.source, "EXE": self.exe_name} # This is a arm and aarch64 specific test case. No other architectures tested. - @skipIf(archs=no_match(['arm', 'aarch64'])) + @skipIf(archs=no_match(["arm", "aarch64"])) def test_multiple_watchpoints_on_same_word(self): - self.build(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) @@ -36,50 +35,66 @@ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Detect line number after which we are going to increment arrayName. - loc_line = line_number('main.c', '// About to write byteArray') + loc_line = line_number("main.c", "// About to write byteArray") # Set a breakpoint on the line detected above. lldbutil.run_break_set_by_file_and_line( - self, "main.c", loc_line, num_expected_locations=1, loc_exact=True) + self, "main.c", loc_line, num_expected_locations=1, loc_exact=True + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Delete breakpoint we just hit. - self.expect("breakpoint delete 1", substrs=['1 breakpoints deleted']) + self.expect("breakpoint delete 1", substrs=["1 breakpoints deleted"]) # Set a watchpoint at byteArray[0] - self.expect("watchpoint set variable byteArray[0]", WATCHPOINT_CREATED, - substrs=['Watchpoint created','size = 1']) + self.expect( + "watchpoint set variable byteArray[0]", + WATCHPOINT_CREATED, + substrs=["Watchpoint created", "size = 1"], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v 1", substrs=['hit_count = 0']) + self.expect("watchpoint list -v 1", substrs=["hit_count = 0"]) # debugserver on ios doesn't give an error, it creates another watchpoint, # only expect errors on non-darwin platforms. if not self.platformIsDarwin(): # Try setting a watchpoint at byteArray[1] - self.expect("watchpoint set variable byteArray[1]", error=True, - substrs=['Watchpoint creation failed']) + self.expect( + "watchpoint set variable byteArray[1]", + error=True, + substrs=["Watchpoint creation failed"], + ) self.runCmd("process continue") # We should be stopped due to the watchpoint. # The stop reason of the thread should be watchpoint. - self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stopped', 'stop reason = watchpoint 1']) + self.expect( + "thread list", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stopped", "stop reason = watchpoint 1"], + ) # Delete the watchpoint we hit above successfully. - self.expect("watchpoint delete 1", substrs=['1 watchpoints deleted']) + self.expect("watchpoint delete 1", substrs=["1 watchpoints deleted"]) # Set a watchpoint at byteArray[3] - self.expect("watchpoint set variable byteArray[3]", WATCHPOINT_CREATED, - substrs=['Watchpoint created','size = 1']) + self.expect( + "watchpoint set variable byteArray[3]", + WATCHPOINT_CREATED, + substrs=["Watchpoint created", "size = 1"], + ) # Resume inferior. self.runCmd("process continue") @@ -88,11 +103,17 @@ # The stop reason of the thread should be watchpoint. if self.platformIsDarwin(): # On darwin we'll hit byteArray[3] which is watchpoint 2 - self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stopped', 'stop reason = watchpoint 2']) + self.expect( + "thread list", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stopped", "stop reason = watchpoint 2"], + ) else: - self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stopped', 'stop reason = watchpoint 3']) + self.expect( + "thread list", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stopped", "stop reason = watchpoint 3"], + ) # Resume inferior. self.runCmd("process continue") diff --git a/lldb/test/API/commands/watchpoints/multiple_hits/TestMultipleHits.py b/lldb/test/API/commands/watchpoints/multiple_hits/TestMultipleHits.py --- a/lldb/test/API/commands/watchpoints/multiple_hits/TestMultipleHits.py +++ b/lldb/test/API/commands/watchpoints/multiple_hits/TestMultipleHits.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -13,7 +12,11 @@ class MultipleHitsTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True - @skipIf(bugnumber="llvm.org/pr30758", oslist=["linux"], archs=["arm", "aarch64", "powerpc64le"]) + @skipIf( + bugnumber="llvm.org/pr30758", + oslist=["linux"], + archs=["arm", "aarch64", "powerpc64le"], + ) @skipIfwatchOS def test(self): self.build() @@ -22,8 +25,7 @@ bp = target.BreakpointCreateByName("main") self.assertTrue(bp and bp.IsValid(), "Breakpoint is valid") - process = target.LaunchSimple(None, None, - self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertState(process.GetState(), lldb.eStateStopped) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) @@ -43,7 +45,6 @@ watch = member.Watch(True, True, True, error) self.assertSuccess(error) - process.Continue(); + process.Continue() self.assertState(process.GetState(), lldb.eStateStopped) self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonWatchpoint) - diff --git a/lldb/test/API/commands/watchpoints/multiple_threads/TestWatchpointMultipleThreads.py b/lldb/test/API/commands/watchpoints/multiple_threads/TestWatchpointMultipleThreads.py --- a/lldb/test/API/commands/watchpoints/multiple_threads/TestWatchpointMultipleThreads.py +++ b/lldb/test/API/commands/watchpoints/multiple_threads/TestWatchpointMultipleThreads.py @@ -13,12 +13,12 @@ NO_DEBUG_INFO_TESTCASE = True main_spec = lldb.SBFileSpec("main.cpp", False) - @skipIfWindows # This test is flaky on Windows + @skipIfWindows # This test is flaky on Windows def test_watchpoint_before_thread_start(self): """Test that we can hit a watchpoint we set before starting another thread""" self.do_watchpoint_test("Before running the thread") - @skipIfWindows # This test is flaky on Windows + @skipIfWindows # This test is flaky on Windows def test_watchpoint_after_thread_launch(self): """Test that we can hit a watchpoint we set after launching another thread""" self.do_watchpoint_test("After launching the thread") @@ -35,15 +35,12 @@ self.expect( "watchpoint set variable -w write g_val", WATCHPOINT_CREATED, - substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = w']) + substrs=["Watchpoint created", "size = 4", "type = w"], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['hit_count = 0']) + self.expect("watchpoint list -v", substrs=["hit_count = 0"]) self.runCmd("process continue") @@ -56,29 +53,27 @@ # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. - self.expect("watchpoint list -v", - substrs=['hit_count = 1']) + self.expect("watchpoint list -v", substrs=["hit_count = 1"]) def test_watchpoint_multiple_threads_wp_set_and_then_delete(self): """Test that lldb watchpoint works for multiple threads, and after the watchpoint is deleted, the watchpoint event should no longer fires.""" self.build() self.setTearDownCleanup() - lldbutil.run_to_source_breakpoint(self, "After running the thread", self.main_spec) + lldbutil.run_to_source_breakpoint( + self, "After running the thread", self.main_spec + ) # Now let's set a write-type watchpoint for variable 'g_val'. self.expect( "watchpoint set variable -w write g_val", WATCHPOINT_CREATED, - substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = w']) + substrs=["Watchpoint created", "size = 4", "type = w"], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['hit_count = 0']) + self.expect("watchpoint list -v", substrs=["hit_count = 0"]) watchpoint_stops = 0 while True: @@ -93,17 +88,18 @@ self.runCmd("thread backtrace all") watchpoint_stops += 1 if watchpoint_stops > 1: - self.fail( - "Watchpoint hits not supposed to exceed 1 by design!") + self.fail("Watchpoint hits not supposed to exceed 1 by design!") # Good, we verified that the watchpoint works! Now delete the # watchpoint. if self.TraceOn(): print( - "watchpoint_stops=%d at the moment we delete the watchpoint" % - watchpoint_stops) + "watchpoint_stops=%d at the moment we delete the watchpoint" + % watchpoint_stops + ) self.runCmd("watchpoint delete 1") - self.expect("watchpoint list -v", - substrs=['No watchpoints currently set.']) + self.expect( + "watchpoint list -v", substrs=["No watchpoints currently set."] + ) continue else: self.fail("The stop reason should be either break or watchpoint") diff --git a/lldb/test/API/commands/watchpoints/step_over_watchpoint/TestStepOverWatchpoint.py b/lldb/test/API/commands/watchpoints/step_over_watchpoint/TestStepOverWatchpoint.py --- a/lldb/test/API/commands/watchpoints/step_over_watchpoint/TestStepOverWatchpoint.py +++ b/lldb/test/API/commands/watchpoints/step_over_watchpoint/TestStepOverWatchpoint.py @@ -1,7 +1,6 @@ """Test stepping over watchpoints.""" - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -14,13 +13,13 @@ def get_to_start(self, bkpt_text): """Test stepping over watchpoints.""" self.build() - target, process, thread, bkpt = lldbutil.run_to_source_breakpoint(self, bkpt_text, - lldb.SBFileSpec("main.c")) + target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, bkpt_text, lldb.SBFileSpec("main.c") + ) frame = thread.GetFrameAtIndex(0) self.assertTrue(frame.IsValid(), "Failed to get frame.") - read_value = frame.FindValue('g_watch_me_read', - lldb.eValueTypeVariableGlobal) + read_value = frame.FindValue("g_watch_me_read", lldb.eValueTypeVariableGlobal) self.assertTrue(read_value.IsValid(), "Failed to find read value.") error = lldb.SBError() @@ -33,40 +32,44 @@ # Disable the breakpoint we hit so we don't muddy the waters with # stepping off from the breakpoint: bkpt.SetEnabled(False) - + return (target, process, thread, frame, read_watchpoint) - + # Read-write watchpoints not supported on SystemZ - @expectedFailureAll(archs=['s390x']) + @expectedFailureAll(archs=["s390x"]) @add_test_categories(["basic_process"]) def test_step_over(self): target, process, thread, frame, wp = self.get_to_start("Set a breakpoint here") - + thread.StepOver() - self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonWatchpoint, - STOPPED_DUE_TO_WATCHPOINT) - self.assertEquals(thread.GetStopDescription(20), 'watchpoint 1') + self.assertStopReason( + thread.GetStopReason(), + lldb.eStopReasonWatchpoint, + STOPPED_DUE_TO_WATCHPOINT, + ) + self.assertEquals(thread.GetStopDescription(20), "watchpoint 1") @expectedFailureAll( oslist=["freebsd", "linux"], - archs=[ - 'aarch64', - 'arm'], - bugnumber="llvm.org/pr26031") + archs=["aarch64", "arm"], + bugnumber="llvm.org/pr26031", + ) # Read-write watchpoints not supported on SystemZ - @expectedFailureAll(archs=['s390x']) + @expectedFailureAll(archs=["s390x"]) @expectedFailureAll( oslist=["ios", "watchos", "tvos", "bridgeos", "macosx"], - archs=['aarch64', 'arm'], - bugnumber="") + archs=["aarch64", "arm"], + bugnumber="", + ) @add_test_categories(["basic_process"]) def test_step_instruction(self): - target, process, thread, frame, wp = self.get_to_start("Set breakpoint after call") + target, process, thread, frame, wp = self.get_to_start( + "Set breakpoint after call" + ) self.step_inst_for_watchpoint(1) - write_value = frame.FindValue('g_watch_me_write', - lldb.eValueTypeVariableGlobal) + write_value = frame.FindValue("g_watch_me_write", lldb.eValueTypeVariableGlobal) self.assertTrue(write_value, "Failed to find write value.") # Most of the MIPS boards provide only one H/W watchpoints, and S/W @@ -82,14 +85,16 @@ self.assertSuccess(error, "Error while setting watchpoint") thread.StepOver() - self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonWatchpoint, - STOPPED_DUE_TO_WATCHPOINT) - self.assertEquals(thread.GetStopDescription(20), 'watchpoint 2') + self.assertStopReason( + thread.GetStopReason(), + lldb.eStopReasonWatchpoint, + STOPPED_DUE_TO_WATCHPOINT, + ) + self.assertEquals(thread.GetStopDescription(20), "watchpoint 2") process.Continue() - self.assertState(process.GetState(), lldb.eStateStopped, - PROCESS_STOPPED) - self.assertEquals(thread.GetStopDescription(20), 'step over') + self.assertState(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) + self.assertEquals(thread.GetStopDescription(20), "step over") self.step_inst_for_watchpoint(2) @@ -103,10 +108,12 @@ self.assertFalse(watchpoint_hit, "Watchpoint already hit.") expected_stop_desc = "watchpoint %d" % wp_id actual_stop_desc = self.thread().GetStopDescription(20) - self.assertEquals(actual_stop_desc, expected_stop_desc, - "Watchpoint ID didn't match.") + self.assertEquals( + actual_stop_desc, expected_stop_desc, "Watchpoint ID didn't match." + ) watchpoint_hit = True else: - self.assertStopReason(stop_reason, lldb.eStopReasonPlanComplete, - STOPPED_DUE_TO_STEP_IN) + self.assertStopReason( + stop_reason, lldb.eStopReasonPlanComplete, STOPPED_DUE_TO_STEP_IN + ) self.assertTrue(watchpoint_hit, "Watchpoint never hit.") diff --git a/lldb/test/API/commands/watchpoints/unaligned-watchpoint/TestUnalignedWatchpoint.py b/lldb/test/API/commands/watchpoints/unaligned-watchpoint/TestUnalignedWatchpoint.py --- a/lldb/test/API/commands/watchpoints/unaligned-watchpoint/TestUnalignedWatchpoint.py +++ b/lldb/test/API/commands/watchpoints/unaligned-watchpoint/TestUnalignedWatchpoint.py @@ -7,7 +7,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -16,40 +15,44 @@ class UnalignedWatchpointTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True + @skipIfOutOfTreeDebugserver def test_unaligned_watchpoint(self): """Test an unaligned watchpoint triggered by a larger aligned write.""" self.build() self.main_source_file = lldb.SBFileSpec("main.c") - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - "break here", self.main_source_file) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "break here", self.main_source_file + ) frame = thread.GetFrameAtIndex(0) self.expect("watchpoint set variable a.buf[2]") - + self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type), but # only once. The stop reason of the thread should be watchpoint. - self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stopped', - 'stop reason = watchpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stopped", "stop reason = watchpoint"], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. - self.expect("watchpoint list -v", - substrs=['hit_count = 1']) - + self.expect("watchpoint list -v", substrs=["hit_count = 1"]) + self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type), but # only once. The stop reason of the thread should be watchpoint. - self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stopped', - 'stop reason = watchpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stopped", "stop reason = watchpoint"], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. - self.expect("watchpoint list -v", - substrs=['hit_count = 2']) + self.expect("watchpoint list -v", substrs=["hit_count = 2"]) diff --git a/lldb/test/API/commands/watchpoints/variable_out_of_scope/TestWatchedVarHitWhenInScope.py b/lldb/test/API/commands/watchpoints/variable_out_of_scope/TestWatchedVarHitWhenInScope.py --- a/lldb/test/API/commands/watchpoints/variable_out_of_scope/TestWatchedVarHitWhenInScope.py +++ b/lldb/test/API/commands/watchpoints/variable_out_of_scope/TestWatchedVarHitWhenInScope.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil @@ -23,12 +22,12 @@ # Call super's setUp(). TestBase.setUp(self) # Our simple source filename. - self.source = 'main.c' + self.source = "main.c" self.exe_name = self.testMethodName - self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + self.d = {"C_SOURCES": self.source, "EXE": self.exe_name} # Test hangs due to a kernel bug, see fdfeff0f in the linux kernel for details - @skipIfTargetAndroid(api_levels=list(range(25+1)), archs=["aarch64", "arm"]) + @skipIfTargetAndroid(api_levels=list(range(25 + 1)), archs=["aarch64", "arm"]) @skipIf def test_watched_var_should_only_hit_when_in_scope(self): """Test that a variable watchpoint should only hit when in scope.""" @@ -39,43 +38,46 @@ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped in main. - lldbutil.run_break_set_by_symbol( - self, "main", num_expected_locations=-1) + lldbutil.run_break_set_by_symbol(self, "main", num_expected_locations=-1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a watchpoint for 'c.a'. # There should be only one watchpoint hit (see main.c). - self.expect("watchpoint set variable c.a", WATCHPOINT_CREATED, - substrs=['Watchpoint created', 'size = 4', 'type = w']) + self.expect( + "watchpoint set variable c.a", + WATCHPOINT_CREATED, + substrs=["Watchpoint created", "size = 4", "type = w"], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['hit_count = 0']) + self.expect("watchpoint list -v", substrs=["hit_count = 0"]) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type), but # only once. The stop reason of the thread should be watchpoint. - self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stopped', - 'stop reason = watchpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stopped", "stop reason = watchpoint"], + ) self.runCmd("process continue") # Don't expect the read of 'global' to trigger a stop exception. # The process status should be 'exited'. - self.expect("process status", - substrs=['exited']) + self.expect("process status", substrs=["exited"]) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. - self.expect("watchpoint list -v", - substrs=['hit_count = 1']) + self.expect("watchpoint list -v", substrs=["hit_count = 1"]) diff --git a/lldb/test/API/commands/watchpoints/watch_tagged_addr/TestWatchTaggedAddress.py b/lldb/test/API/commands/watchpoints/watch_tagged_addr/TestWatchTaggedAddress.py --- a/lldb/test/API/commands/watchpoints/watch_tagged_addr/TestWatchTaggedAddress.py +++ b/lldb/test/API/commands/watchpoints/watch_tagged_addr/TestWatchTaggedAddress.py @@ -7,6 +7,7 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestWatchTaggedAddresses(TestBase): NO_DEBUG_INFO_TESTCASE = True @@ -16,10 +17,10 @@ # Skip this test if not running on AArch64 target that supports PAC if not self.isAArch64PAuth(): - self.skipTest('Target must support pointer authentication.') + self.skipTest("Target must support pointer authentication.") # Set source filename. - self.source = 'main.c' + self.source = "main.c" # Invoke the default build rule. self.build() @@ -31,7 +32,7 @@ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) @skipIf(archs=no_match(["aarch64"])) - @skipIf(oslist=no_match(['linux'])) + @skipIf(oslist=no_match(["linux"])) def test_watch_hit_tagged_ptr_access(self): """ Test that LLDB hits watchpoint installed on an untagged address with @@ -39,94 +40,101 @@ """ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_symbol(self, 'main') + lldbutil.run_break_set_by_symbol(self, "main") # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped due to the breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Set the watchpoint variable declaration line number. - self.decl = line_number(self.source, - '// Watchpoint variable declaration.') + self.decl = line_number(self.source, "// Watchpoint variable declaration.") # Now let's set a watchpoint on 'global_var'. self.expect( "watchpoint set variable global_var", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = w', - '%s:%d' % - (self.source, - self.decl)]) + "Watchpoint created", + "size = 4", + "type = w", + "%s:%d" % (self.source, self.decl), + ], + ) self.verify_watch_hits() @skipIf(archs=no_match(["aarch64"])) - @skipIf(oslist=no_match(['linux'])) + @skipIf(oslist=no_match(["linux"])) def test_watch_set_on_tagged_ptr(self): """Test that LLDB can install and hit watchpoint on a tagged address""" # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number(self.source, "// Set break point at this line.") # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1) + self, None, self.line, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped due to the breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a expression watchpoint on 'tagged_ptr'. self.expect( "watchpoint set expression -s 4 -- tagged_ptr", WATCHPOINT_CREATED, - substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = w']) + substrs=["Watchpoint created", "size = 4", "type = w"], + ) self.verify_watch_hits() def verify_watch_hits(self): # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['Number of supported hardware watchpoints:', - 'hit_count = 0']) + self.expect( + "watchpoint list -v", + substrs=["Number of supported hardware watchpoints:", "hit_count = 0"], + ) self.runCmd("process continue") # We should be stopped again due to the watchpoint (read_write type). # The stop reason of the thread should be watchpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stop reason = watchpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stop reason = watchpoint"], + ) self.runCmd("process continue") # We should be stopped again due to the watchpoint (read_write type). # The stop reason of the thread should be watchpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stop reason = watchpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stop reason = watchpoint"], + ) self.runCmd("process continue") # There should be no more watchpoint hit and the process status should # be 'exited'. - self.expect("process status", - substrs=['exited']) + self.expect("process status", substrs=["exited"]) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 2. - self.expect("watchpoint list -v", - substrs=['hit_count = 2']) + self.expect("watchpoint list -v", substrs=["hit_count = 2"]) diff --git a/lldb/test/API/commands/watchpoints/watchpoint_commands/TestWatchpointCommands.py b/lldb/test/API/commands/watchpoints/watchpoint_commands/TestWatchpointCommands.py --- a/lldb/test/API/commands/watchpoints/watchpoint_commands/TestWatchpointCommands.py +++ b/lldb/test/API/commands/watchpoints/watchpoint_commands/TestWatchpointCommands.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -17,23 +16,21 @@ # Call super's setUp(). TestBase.setUp(self) # Our simple source filename. - self.source = 'main.c' + self.source = "main.c" # Find the line number to break inside main(). - self.line = line_number( - self.source, '// Set break point at this line.') + self.line = line_number(self.source, "// Set break point at this line.") self.line2 = line_number( - self.source, - '// Set 2nd break point for disable_then_enable test case.') + self.source, "// Set 2nd break point for disable_then_enable test case." + ) # And the watchpoint variable declaration line number. - self.decl = line_number(self.source, - '// Watchpoint variable declaration.') + self.decl = line_number(self.source, "// Watchpoint variable declaration.") # Build dictionary to have unique executable names for each test # method. self.exe_name = self.testMethodName - self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + self.d = {"C_SOURCES": self.source, "EXE": self.exe_name} # Read-write watchpoints not supported on SystemZ - @expectedFailureAll(archs=['s390x']) + @expectedFailureAll(archs=["s390x"]) def test_rw_watchpoint(self): """Test read_write watchpoint and expect to stop two times.""" self.build(dictionary=self.d) @@ -44,16 +41,19 @@ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1) + self, None, self.line, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a read_write-type watchpoint for 'global'. # There should be two watchpoint hits (see main.c). @@ -61,52 +61,56 @@ "watchpoint set variable -w read_write global", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = rw', - '%s:%d' % - (self.source, - self.decl)]) + "Watchpoint created", + "size = 4", + "type = rw", + "%s:%d" % (self.source, self.decl), + ], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['Number of supported hardware watchpoints:', - 'hit_count = 0']) + self.expect( + "watchpoint list -v", + substrs=["Number of supported hardware watchpoints:", "hit_count = 0"], + ) self.runCmd("process continue") # We should be stopped again due to the watchpoint (read_write type). # The stop reason of the thread should be watchpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stop reason = watchpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stop reason = watchpoint"], + ) self.runCmd("process continue") # We should be stopped again due to the watchpoint (read_write type). # The stop reason of the thread should be watchpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stop reason = watchpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stop reason = watchpoint"], + ) self.runCmd("process continue") # There should be no more watchpoint hit and the process status should # be 'exited'. - self.expect("process status", - substrs=['exited']) + self.expect("process status", substrs=["exited"]) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 2. - self.expect("watchpoint list -v", - substrs=['hit_count = 2']) + self.expect("watchpoint list -v", substrs=["hit_count = 2"]) # Read-write watchpoints not supported on SystemZ - @expectedFailureAll(archs=['s390x']) + @expectedFailureAll(archs=["s390x"]) def test_rw_watchpoint_delete(self): """Test delete watchpoint and expect not to stop for watchpoint.""" self.build() - lldbutil.run_to_line_breakpoint(self, lldb.SBFileSpec(self.source), - self.line) + lldbutil.run_to_line_breakpoint(self, lldb.SBFileSpec(self.source), self.line) # Now let's set a read_write-type watchpoint for 'global'. # There should be two watchpoint hits (see main.c). @@ -114,18 +118,17 @@ "watchpoint set variable -w read_write global", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = rw', - '%s:%d' % - (self.source, - self.decl)]) + "Watchpoint created", + "size = 4", + "type = rw", + "%s:%d" % (self.source, self.decl), + ], + ) # Delete the watchpoint immediately, but set auto-confirm to true # first. self.runCmd("settings set auto-confirm true") - self.expect("watchpoint delete", - substrs=['All watchpoints removed.']) + self.expect("watchpoint delete", substrs=["All watchpoints removed."]) # Restore the original setting of auto-confirm. self.runCmd("settings clear auto-confirm") @@ -138,17 +141,15 @@ "watchpoint set variable -w read_write global", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = rw', - '%s:%d' % - (self.source, - self.decl)]) - + "Watchpoint created", + "size = 4", + "type = rw", + "%s:%d" % (self.source, self.decl), + ], + ) # Delete the watchpoint immediately using the force option. - self.expect("watchpoint delete --force", - substrs=['All watchpoints removed.']) + self.expect("watchpoint delete --force", substrs=["All watchpoints removed."]) self.assertTrue(target and not target.GetNumWatchpoints()) @@ -156,11 +157,10 @@ # There should be no more watchpoint hit and the process status should # be 'exited'. - self.expect("process status", - substrs=['exited']) + self.expect("process status", substrs=["exited"]) # Read-write watchpoints not supported on SystemZ - @expectedFailureAll(archs=['s390x']) + @expectedFailureAll(archs=["s390x"]) def test_rw_watchpoint_set_ignore_count(self): """Test watchpoint ignore count and expect to not to stop at all.""" self.build(dictionary=self.d) @@ -171,16 +171,19 @@ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1) + self, None, self.line, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a read_write-type watchpoint for 'global'. # There should be two watchpoint hits (see main.c). @@ -188,36 +191,32 @@ "watchpoint set variable -w read_write global", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = rw', - '%s:%d' % - (self.source, - self.decl)]) + "Watchpoint created", + "size = 4", + "type = rw", + "%s:%d" % (self.source, self.decl), + ], + ) # Set the ignore count of the watchpoint immediately. - self.expect("watchpoint ignore -i 2", - substrs=['All watchpoints ignored.']) + self.expect("watchpoint ignore -i 2", substrs=["All watchpoints ignored."]) # Use the '-v' option to do verbose listing of the watchpoint. # Expect to find an ignore_count of 2. - self.expect("watchpoint list -v", - substrs=['hit_count = 0', 'ignore_count = 2']) + self.expect("watchpoint list -v", substrs=["hit_count = 0", "ignore_count = 2"]) self.runCmd("process continue") # There should be no more watchpoint hit and the process status should # be 'exited'. - self.expect("process status", - substrs=['exited']) + self.expect("process status", substrs=["exited"]) # Use the '-v' option to do verbose listing of the watchpoint. # Expect to find a hit_count of 2 as well. - self.expect("watchpoint list -v", - substrs=['hit_count = 2', 'ignore_count = 2']) + self.expect("watchpoint list -v", substrs=["hit_count = 2", "ignore_count = 2"]) # Read-write watchpoints not supported on SystemZ - @expectedFailureAll(archs=['s390x']) + @expectedFailureAll(archs=["s390x"]) def test_rw_disable_after_first_stop(self): """Test read_write watchpoint but disable it after the first stop.""" self.build(dictionary=self.d) @@ -228,16 +227,19 @@ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1) + self, None, self.line, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a read_write-type watchpoint for 'global'. # There should be two watchpoint hits (see main.c). @@ -245,46 +247,45 @@ "watchpoint set variable -w read_write global", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = rw', - '%s:%d' % - (self.source, - self.decl)]) + "Watchpoint created", + "size = 4", + "type = rw", + "%s:%d" % (self.source, self.decl), + ], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['state = enabled', 'hit_count = 0']) + self.expect("watchpoint list -v", substrs=["state = enabled", "hit_count = 0"]) self.runCmd("process continue") # We should be stopped again due to the watchpoint (read_write type). # The stop reason of the thread should be watchpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stop reason = watchpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stop reason = watchpoint"], + ) # Before continuing, we'll disable the watchpoint, which means we won't # stop again after this. self.runCmd("watchpoint disable") - self.expect("watchpoint list -v", - substrs=['state = disabled', 'hit_count = 1']) + self.expect("watchpoint list -v", substrs=["state = disabled", "hit_count = 1"]) self.runCmd("process continue") # There should be no more watchpoint hit and the process status should # be 'exited'. - self.expect("process status", - substrs=['exited']) + self.expect("process status", substrs=["exited"]) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 1. - self.expect("watchpoint list -v", - substrs=['hit_count = 1']) + self.expect("watchpoint list -v", substrs=["hit_count = 1"]) # Read-write watchpoints not supported on SystemZ - @expectedFailureAll(archs=['s390x']) + @expectedFailureAll(archs=["s390x"]) def test_rw_disable_then_enable(self): """Test read_write watchpoint, disable initially, then enable it.""" self.build(dictionary=self.d) @@ -295,18 +296,22 @@ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1) + self, None, self.line, num_expected_locations=1 + ) lldbutil.run_break_set_by_file_and_line( - self, None, self.line2, num_expected_locations=1) + self, None, self.line2, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a read_write-type watchpoint for 'global'. # There should be two watchpoint hits (see main.c). @@ -314,12 +319,12 @@ "watchpoint set variable -w read_write global", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = rw', - '%s:%d' % - (self.source, - self.decl)]) + "Watchpoint created", + "size = 4", + "type = rw", + "%s:%d" % (self.source, self.decl), + ], + ) # Immediately, we disable the watchpoint. We won't be stopping due to a # watchpoint after this. @@ -327,37 +332,39 @@ # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['state = disabled', 'hit_count = 0']) + self.expect("watchpoint list -v", substrs=["state = disabled", "hit_count = 0"]) self.runCmd("process continue") # We should be stopped again due to the breakpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stop reason = breakpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint"], + ) # Before continuing, we'll enable the watchpoint, which means we will # stop again after this. self.runCmd("watchpoint enable") - self.expect("watchpoint list -v", - substrs=['state = enabled', 'hit_count = 0']) + self.expect("watchpoint list -v", substrs=["state = enabled", "hit_count = 0"]) self.runCmd("process continue") # We should be stopped again due to the watchpoint (read_write type). # The stop reason of the thread should be watchpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stop reason = watchpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stop reason = watchpoint"], + ) self.runCmd("process continue") # There should be no more watchpoint hit and the process status should # be 'exited'. - self.expect("process status", - substrs=['exited']) + self.expect("process status", substrs=["exited"]) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 1. - self.expect("watchpoint list -v", - substrs=['hit_count = 1']) + self.expect("watchpoint list -v", substrs=["hit_count = 1"]) diff --git a/lldb/test/API/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandLLDB.py b/lldb/test/API/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandLLDB.py --- a/lldb/test/API/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandLLDB.py +++ b/lldb/test/API/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandLLDB.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -17,17 +16,15 @@ # Call super's setUp(). TestBase.setUp(self) # Our simple source filename. - self.source = 'main.cpp' + self.source = "main.cpp" # Find the line number to break inside main(). - self.line = line_number( - self.source, '// Set break point at this line.') + self.line = line_number(self.source, "// Set break point at this line.") # And the watchpoint variable declaration line number. - self.decl = line_number(self.source, - '// Watchpoint variable declaration.') + self.decl = line_number(self.source, "// Watchpoint variable declaration.") # Build dictionary to have unique executable names for each test # method. - self.exe_name = 'a%d.out' % self.test_number - self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} + self.exe_name = "a%d.out" % self.test_number + self.d = {"CXX_SOURCES": self.source, "EXE": self.exe_name} def test_watchpoint_command(self): """Test 'watchpoint command'.""" @@ -39,59 +36,68 @@ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1) + self, None, self.line, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a write-type watchpoint for 'global'. self.expect( "watchpoint set variable -w write global", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = w', - '%s:%d' % - (self.source, - self.decl)]) + "Watchpoint created", + "size = 4", + "type = w", + "%s:%d" % (self.source, self.decl), + ], + ) self.runCmd('watchpoint command add 1 -o "expr -- cookie = 777"') # List the watchpoint command we just added. - self.expect("watchpoint command list 1", - substrs=['expr -- cookie = 777']) + self.expect("watchpoint command list 1", substrs=["expr -- cookie = 777"]) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['hit_count = 0']) + self.expect("watchpoint list -v", substrs=["hit_count = 0"]) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type). # The stop reason of the thread should be watchpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stop reason = watchpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stop reason = watchpoint"], + ) # Check that the watchpoint snapshoting mechanism is working. self.expect( "watchpoint list -v", substrs=[ - 'old value: 0', 'new value: 1', 'hit_count = 1', - 'ignore_count = 0' - ]) + "old value: 0", + "new value: 1", + "hit_count = 1", + "ignore_count = 0", + ], + ) # The watchpoint command "forced" our global variable 'cookie' to # become 777. - self.expect("frame variable --show-globals cookie", - substrs=['(int32_t)', 'cookie = 777']) + self.expect( + "frame variable --show-globals cookie", + substrs=["(int32_t)", "cookie = 777"], + ) def test_watchpoint_command_can_disable_a_watchpoint(self): """Test that 'watchpoint command' action can disable a watchpoint after it is triggered.""" @@ -103,54 +109,56 @@ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1) + self, None, self.line, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a write-type watchpoint for 'global'. self.expect( "watchpoint set variable -w write global", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = w', - '%s:%d' % - (self.source, - self.decl)]) + "Watchpoint created", + "size = 4", + "type = w", + "%s:%d" % (self.source, self.decl), + ], + ) self.runCmd('watchpoint command add 1 -o "watchpoint disable 1"') # List the watchpoint command we just added. - self.expect("watchpoint command list 1", - substrs=['watchpoint disable 1']) + self.expect("watchpoint command list 1", substrs=["watchpoint disable 1"]) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['hit_count = 0']) + self.expect("watchpoint list -v", substrs=["hit_count = 0"]) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type). # The stop reason of the thread should be watchpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stop reason = watchpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stop reason = watchpoint"], + ) # Check that the watchpoint has been disabled. - self.expect("watchpoint list -v", - substrs=['disabled']) + self.expect("watchpoint list -v", substrs=["disabled"]) self.runCmd("process continue") # There should be no more watchpoint hit and the process status should # be 'exited'. - self.expect("process status", - substrs=['exited']) + self.expect("process status", substrs=["exited"]) diff --git a/lldb/test/API/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandPython.py b/lldb/test/API/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandPython.py --- a/lldb/test/API/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandPython.py +++ b/lldb/test/API/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandPython.py @@ -3,7 +3,6 @@ """ - import os import lldb from lldbsuite.test.decorators import * @@ -18,19 +17,16 @@ # Call super's setUp(). TestBase.setUp(self) # Our simple source filename. - self.source = 'main.cpp' + self.source = "main.cpp" # Find the line number to break inside main(). - self.line = line_number( - self.source, '// Set break point at this line.') - self.second_line = line_number( - self.source, '// Set another breakpoint here.') + self.line = line_number(self.source, "// Set break point at this line.") + self.second_line = line_number(self.source, "// Set another breakpoint here.") # And the watchpoint variable declaration line number. - self.decl = line_number(self.source, - '// Watchpoint variable declaration.') + self.decl = line_number(self.source, "// Watchpoint variable declaration.") # Build dictionary to have unique executable names for each test # method. self.exe_name = self.testMethodName - self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} + self.d = {"CXX_SOURCES": self.source, "EXE": self.exe_name} def test_watchpoint_command(self): """Test 'watchpoint command'.""" @@ -42,57 +38,65 @@ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1) + self, None, self.line, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a write-type watchpoint for 'global'. self.expect( "watchpoint set variable -w write global", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = w', - '%s:%d' % - (self.source, - self.decl)]) + "Watchpoint created", + "size = 4", + "type = w", + "%s:%d" % (self.source, self.decl), + ], + ) self.runCmd( - 'watchpoint command add -s python 1 -o \'frame.EvaluateExpression("cookie = 777")\'') + "watchpoint command add -s python 1 -o 'frame.EvaluateExpression(\"cookie = 777\")'" + ) # List the watchpoint command we just added. - self.expect("watchpoint command list 1", - substrs=['frame.EvaluateExpression', 'cookie = 777']) + self.expect( + "watchpoint command list 1", + substrs=["frame.EvaluateExpression", "cookie = 777"], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['hit_count = 0']) + self.expect("watchpoint list -v", substrs=["hit_count = 0"]) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type). # The stop reason of the thread should be watchpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stop reason = watchpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stop reason = watchpoint"], + ) # Check that the watchpoint snapshoting mechanism is working. - self.expect("watchpoint list -v", - substrs=['old value: 0', - 'new value: 1']) + self.expect("watchpoint list -v", substrs=["old value: 0", "new value: 1"]) # The watchpoint command "forced" our global variable 'cookie' to # become 777. - self.expect("frame variable --show-globals cookie", - substrs=['(int32_t)', 'cookie = 777']) + self.expect( + "frame variable --show-globals cookie", + substrs=["(int32_t)", "cookie = 777"], + ) def test_continue_in_watchpoint_command(self): """Test continue in a watchpoint command.""" @@ -104,75 +108,93 @@ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1) + self, None, self.line, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a write-type watchpoint for 'global'. self.expect( "watchpoint set variable -w write global", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = w', - '%s:%d' % - (self.source, - self.decl)]) - - cmd_script_file = os.path.join(self.getSourceDir(), - "watchpoint_command.py") + "Watchpoint created", + "size = 4", + "type = w", + "%s:%d" % (self.source, self.decl), + ], + ) + + cmd_script_file = os.path.join(self.getSourceDir(), "watchpoint_command.py") self.runCmd("command script import '%s'" % (cmd_script_file)) - self.runCmd( - 'watchpoint command add -F watchpoint_command.watchpoint_command') + self.runCmd("watchpoint command add -F watchpoint_command.watchpoint_command") # List the watchpoint command we just added. - self.expect("watchpoint command list 1", - substrs=['watchpoint_command.watchpoint_command']) + self.expect( + "watchpoint command list 1", + substrs=["watchpoint_command.watchpoint_command"], + ) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type). # The stop reason of the thread should be watchpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stop reason = watchpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stop reason = watchpoint"], + ) # We should have hit the watchpoint once, set cookie to 888, since the # user callback returned True. - self.expect("frame variable --show-globals cookie", - substrs=['(int32_t)', 'cookie = 888']) + self.expect( + "frame variable --show-globals cookie", + substrs=["(int32_t)", "cookie = 888"], + ) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type). # The stop reason of the thread should be watchpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stop reason = watchpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stop reason = watchpoint"], + ) # We should have hit the watchpoint a second time, set cookie to 666, # even if the user callback didn't return anything and then continue. - self.expect("frame variable --show-globals cookie", - substrs=['(int32_t)', 'cookie = 666']) + self.expect( + "frame variable --show-globals cookie", + substrs=["(int32_t)", "cookie = 666"], + ) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.second_line, num_expected_locations=1) + self, None, self.second_line, num_expected_locations=1 + ) self.runCmd("process continue") - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stop reason = breakpoint']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint"], + ) # We should have hit the watchpoint once, set cookie to 888, then continued to the # second hit and set it to 999 - self.expect("frame variable --show-globals cookie", - substrs=['(int32_t)', 'cookie = 999']) - + self.expect( + "frame variable --show-globals cookie", + substrs=["(int32_t)", "cookie = 999"], + ) diff --git a/lldb/test/API/commands/watchpoints/watchpoint_commands/command/watchpoint_command.py b/lldb/test/API/commands/watchpoints/watchpoint_commands/command/watchpoint_command.py --- a/lldb/test/API/commands/watchpoints/watchpoint_commands/command/watchpoint_command.py +++ b/lldb/test/API/commands/watchpoints/watchpoint_commands/command/watchpoint_command.py @@ -6,15 +6,15 @@ def watchpoint_command(frame, wp, dict): global num_hits if num_hits == 0: - print ("I stopped the first time") + print("I stopped the first time") frame.EvaluateExpression("cookie = 888") num_hits += 1 return True if num_hits == 1: - print ("I stopped the second time, but with no return") + print("I stopped the second time, but with no return") frame.EvaluateExpression("cookie = 666") num_hits += 1 else: - print ("I stopped the %d time" % (num_hits)) + print("I stopped the %d time" % (num_hits)) frame.EvaluateExpression("cookie = 999") - return False # This cause the process to continue. + return False # This cause the process to continue. diff --git a/lldb/test/API/commands/watchpoints/watchpoint_commands/condition/TestWatchpointConditionCmd.py b/lldb/test/API/commands/watchpoints/watchpoint_commands/condition/TestWatchpointConditionCmd.py --- a/lldb/test/API/commands/watchpoints/watchpoint_commands/condition/TestWatchpointConditionCmd.py +++ b/lldb/test/API/commands/watchpoints/watchpoint_commands/condition/TestWatchpointConditionCmd.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -17,17 +16,15 @@ # Call super's setUp(). TestBase.setUp(self) # Our simple source filename. - self.source = 'main.cpp' + self.source = "main.cpp" # Find the line number to break inside main(). - self.line = line_number( - self.source, '// Set break point at this line.') + self.line = line_number(self.source, "// Set break point at this line.") # And the watchpoint variable declaration line number. - self.decl = line_number(self.source, - '// Watchpoint variable declaration.') + self.decl = line_number(self.source, "// Watchpoint variable declaration.") # Build dictionary to have unique executable names for each test # method. self.exe_name = self.testMethodName - self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} + self.d = {"CXX_SOURCES": self.source, "EXE": self.exe_name} def test_watchpoint_cond(self): """Test watchpoint condition.""" @@ -39,16 +36,19 @@ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1) + self, None, self.line, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a write-type watchpoint for 'global'. # With a condition of 'global==5'. @@ -56,30 +56,32 @@ "watchpoint set variable -w write global", WATCHPOINT_CREATED, substrs=[ - 'Watchpoint created', - 'size = 4', - 'type = w', - '%s:%d' % - (self.source, - self.decl)]) + "Watchpoint created", + "size = 4", + "type = w", + "%s:%d" % (self.source, self.decl), + ], + ) self.runCmd("watchpoint modify -c 'global==5'") # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['global==5', 'hit_count = 0']) + self.expect("watchpoint list -v", substrs=["global==5", "hit_count = 0"]) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type). # The stop reason of the thread should be watchpoint. - self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stop reason = watchpoint']) - self.expect("frame variable --show-globals global", - substrs=['(int32_t)', 'global = 5']) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stop reason = watchpoint"], + ) + self.expect( + "frame variable --show-globals global", substrs=["(int32_t)", "global = 5"] + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 2. - self.expect("watchpoint list -v", - substrs=['hit_count = 1']) + self.expect("watchpoint list -v", substrs=["hit_count = 1"]) diff --git a/lldb/test/API/commands/watchpoints/watchpoint_count/TestWatchpointCount.py b/lldb/test/API/commands/watchpoints/watchpoint_count/TestWatchpointCount.py --- a/lldb/test/API/commands/watchpoints/watchpoint_count/TestWatchpointCount.py +++ b/lldb/test/API/commands/watchpoints/watchpoint_count/TestWatchpointCount.py @@ -3,14 +3,20 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestWatchpointCount(TestBase): NO_DEBUG_INFO_TESTCASE = True - @skipIf(oslist=["freebsd", "linux"], archs=["arm", "aarch64"], - bugnumber="llvm.org/pr26031") + @skipIf( + oslist=["freebsd", "linux"], + archs=["arm", "aarch64"], + bugnumber="llvm.org/pr26031", + ) def test_watchpoint_count(self): self.build() - (_, process, thread, _) = lldbutil.run_to_source_breakpoint(self, "patatino", lldb.SBFileSpec("main.c")) + (_, process, thread, _) = lldbutil.run_to_source_breakpoint( + self, "patatino", lldb.SBFileSpec("main.c") + ) frame = thread.GetFrameAtIndex(0) first_var = frame.FindVariable("x1") second_var = frame.FindVariable("x2") @@ -18,24 +24,24 @@ error = lldb.SBError() first_watch = first_var.Watch(True, False, True, error) if not error.Success(): - self.fail( - "Failed to make watchpoint for x1: %s" % - (error.GetCString())) + self.fail("Failed to make watchpoint for x1: %s" % (error.GetCString())) second_watch = second_var.Watch(True, False, True, error) if not error.Success(): - self.fail( - "Failed to make watchpoint for x2: %s" % - (error.GetCString())) + self.fail("Failed to make watchpoint for x2: %s" % (error.GetCString())) process.Continue() stop_reason = thread.GetStopReason() - self.assertStopReason(stop_reason, lldb.eStopReasonWatchpoint, "watchpoint for x1 not hit") + self.assertStopReason( + stop_reason, lldb.eStopReasonWatchpoint, "watchpoint for x1 not hit" + ) stop_reason_descr = thread.GetStopDescription(256) self.assertEqual(stop_reason_descr, "watchpoint 1") process.Continue() stop_reason = thread.GetStopReason() - self.assertStopReason(stop_reason, lldb.eStopReasonWatchpoint, "watchpoint for x2 not hit") + self.assertStopReason( + stop_reason, lldb.eStopReasonWatchpoint, "watchpoint for x2 not hit" + ) stop_reason_descr = thread.GetStopDescription(256) self.assertEqual(stop_reason_descr, "watchpoint 2") diff --git a/lldb/test/API/commands/watchpoints/watchpoint_disable/TestWatchpointDisable.py b/lldb/test/API/commands/watchpoints/watchpoint_disable/TestWatchpointDisable.py --- a/lldb/test/API/commands/watchpoints/watchpoint_disable/TestWatchpointDisable.py +++ b/lldb/test/API/commands/watchpoints/watchpoint_disable/TestWatchpointDisable.py @@ -11,12 +11,12 @@ class TestWatchpointSetEnable(TestBase): NO_DEBUG_INFO_TESTCASE = True - def test_disable_works (self): + def test_disable_works(self): """Set a watchpoint, disable it, and make sure it doesn't get hit.""" self.build() self.do_test(False) - def test_disable_enable_works (self): + def test_disable_enable_works(self): """Set a watchpoint, disable it, and make sure it doesn't get hit.""" self.build() self.do_test(True) @@ -28,26 +28,41 @@ self.target = self.createTestTarget() - bkpt_before = self.target.BreakpointCreateBySourceRegex("Set a breakpoint here", main_file_spec) - self.assertEqual(bkpt_before.GetNumLocations(), 1, "Failed setting the before breakpoint.") + bkpt_before = self.target.BreakpointCreateBySourceRegex( + "Set a breakpoint here", main_file_spec + ) + self.assertEqual( + bkpt_before.GetNumLocations(), 1, "Failed setting the before breakpoint." + ) - bkpt_after = self.target.BreakpointCreateBySourceRegex("We should have stopped", main_file_spec) - self.assertEqual(bkpt_after.GetNumLocations(), 1, "Failed setting the after breakpoint.") + bkpt_after = self.target.BreakpointCreateBySourceRegex( + "We should have stopped", main_file_spec + ) + self.assertEqual( + bkpt_after.GetNumLocations(), 1, "Failed setting the after breakpoint." + ) process = self.target.LaunchSimple( - None, None, self.get_process_working_directory()) + None, None, self.get_process_working_directory() + ) self.assertTrue(process, PROCESS_IS_VALID) thread = lldbutil.get_one_thread_stopped_at_breakpoint(process, bkpt_before) self.assertTrue(thread.IsValid(), "We didn't stop at the before breakpoint.") ret_val = lldb.SBCommandReturnObject() - self.dbg.GetCommandInterpreter().HandleCommand("watchpoint set variable -w write global_var", ret_val) - self.assertTrue(ret_val.Succeeded(), "Watchpoint set variable did not return success.") + self.dbg.GetCommandInterpreter().HandleCommand( + "watchpoint set variable -w write global_var", ret_val + ) + self.assertTrue( + ret_val.Succeeded(), "Watchpoint set variable did not return success." + ) wp = self.target.FindWatchpointByID(1) self.assertTrue(wp.IsValid(), "Didn't make a valid watchpoint.") - self.assertNotEqual(wp.GetWatchAddress(), lldb.LLDB_INVALID_ADDRESS, "Watch address is invalid") + self.assertNotEqual( + wp.GetWatchAddress(), lldb.LLDB_INVALID_ADDRESS, "Watch address is invalid" + ) wp.SetEnabled(False) self.assertTrue(not wp.IsEnabled(), "The watchpoint thinks it is still enabled") @@ -56,12 +71,19 @@ stop_reason = thread.GetStopReason() - self.assertStopReason(stop_reason, lldb.eStopReasonBreakpoint, "We didn't stop at our breakpoint.") + self.assertStopReason( + stop_reason, lldb.eStopReasonBreakpoint, "We didn't stop at our breakpoint." + ) if test_enable: wp.SetEnabled(True) - self.assertTrue(wp.IsEnabled(), "The watchpoint thinks it is still disabled.") + self.assertTrue( + wp.IsEnabled(), "The watchpoint thinks it is still disabled." + ) process.Continue() stop_reason = thread.GetStopReason() - self.assertStopReason(stop_reason, lldb.eStopReasonWatchpoint, "We didn't stop at our watchpoint") - + self.assertStopReason( + stop_reason, + lldb.eStopReasonWatchpoint, + "We didn't stop at our watchpoint", + ) diff --git a/lldb/test/API/commands/watchpoints/watchpoint_events/TestWatchpointEvents.py b/lldb/test/API/commands/watchpoints/watchpoint_events/TestWatchpointEvents.py --- a/lldb/test/API/commands/watchpoints/watchpoint_events/TestWatchpointEvents.py +++ b/lldb/test/API/commands/watchpoints/watchpoint_events/TestWatchpointEvents.py @@ -6,7 +6,7 @@ from lldbsuite.test import lldbutil -class TestWatchpointEvents (TestBase): +class TestWatchpointEvents(TestBase): NO_DEBUG_INFO_TESTCASE = True def setUp(self): @@ -15,7 +15,7 @@ # Find the line numbers that we will step to in main: self.main_source = "main.c" - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) def test_with_python_api(self): """Test that adding, deleting and modifying watchpoints sends the appropriate events.""" self.build() @@ -24,18 +24,17 @@ self.main_source_spec = lldb.SBFileSpec(self.main_source) break_in_main = target.BreakpointCreateBySourceRegex( - '// Put a breakpoint here.', self.main_source_spec) + "// Put a breakpoint here.", self.main_source_spec + ) self.assertTrue(break_in_main, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint( - process, break_in_main) + threads = lldbutil.get_threads_stopped_at_breakpoint(process, break_in_main) if len(threads) != 1: self.fail("Failed to stop at first breakpoint in main.") @@ -48,16 +47,18 @@ self.listener = lldb.SBListener("com.lldb.testsuite_listener") self.target_bcast = target.GetBroadcaster() self.target_bcast.AddListener( - self.listener, lldb.SBTarget.eBroadcastBitWatchpointChanged) + self.listener, lldb.SBTarget.eBroadcastBitWatchpointChanged + ) self.listener.StartListeningForEvents( - self.target_bcast, lldb.SBTarget.eBroadcastBitWatchpointChanged) + self.target_bcast, lldb.SBTarget.eBroadcastBitWatchpointChanged + ) error = lldb.SBError() local_watch = local_var.Watch(True, False, True, error) if not error.Success(): self.fail( - "Failed to make watchpoint for local_var: %s" % - (error.GetCString())) + "Failed to make watchpoint for local_var: %s" % (error.GetCString()) + ) self.GetWatchpointEvent(lldb.eWatchpointEventTypeAdded) # Now change some of the features of this watchpoint and make sure we @@ -75,8 +76,11 @@ local_watch.SetCondition(condition) self.GetWatchpointEvent(lldb.eWatchpointEventTypeConditionChanged) - self.assertEqual(local_watch.GetCondition(), condition, - 'make sure watchpoint condition is "' + condition + '"') + self.assertEqual( + local_watch.GetCondition(), + condition, + 'make sure watchpoint condition is "' + condition + '"', + ) def GetWatchpointEvent(self, event_type): # We added a watchpoint so we should get a watchpoint added event. @@ -85,16 +89,19 @@ self.assertTrue(success, "Successfully got watchpoint event") self.assertTrue( lldb.SBWatchpoint.EventIsWatchpointEvent(event), - "Event is a watchpoint event.") + "Event is a watchpoint event.", + ) found_type = lldb.SBWatchpoint.GetWatchpointEventTypeFromEvent(event) self.assertEqual( - found_type, event_type, - "Event is not correct type, expected: %d, found: %d" % - (event_type, - found_type)) + found_type, + event_type, + "Event is not correct type, expected: %d, found: %d" + % (event_type, found_type), + ) # There shouldn't be another event waiting around: found_event = self.listener.PeekAtNextEventForBroadcasterWithType( - self.target_bcast, lldb.SBTarget.eBroadcastBitBreakpointChanged, event) + self.target_bcast, lldb.SBTarget.eBroadcastBitBreakpointChanged, event + ) if found_event: print("Found an event I didn't expect: ", event) diff --git a/lldb/test/API/commands/watchpoints/watchpoint_on_vectors/TestValueOfVectorVariable.py b/lldb/test/API/commands/watchpoints/watchpoint_on_vectors/TestValueOfVectorVariable.py --- a/lldb/test/API/commands/watchpoints/watchpoint_on_vectors/TestValueOfVectorVariable.py +++ b/lldb/test/API/commands/watchpoints/watchpoint_on_vectors/TestValueOfVectorVariable.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -16,7 +15,7 @@ def test_value_of_vector_variable_using_watchpoint_set(self): """Test verify displayed value of vector variable.""" exe = self.getBuildArtifact("a.out") - d = {'C_SOURCES': self.source, 'EXE': exe} + d = {"C_SOURCES": self.source, "EXE": exe} self.build(dictionary=d) self.setTearDownCleanup(dictionary=d) self.value_of_vector_variable_with_watchpoint_set() @@ -25,7 +24,7 @@ # Call super's setUp(). TestBase.setUp(self) # Our simple source filename. - self.source = 'main.c' + self.source = "main.c" def value_of_vector_variable_with_watchpoint_set(self): """Test verify displayed value of vector variable""" @@ -42,4 +41,5 @@ self.expect( "watchpoint set variable global_vector", WATCHPOINT_CREATED, - substrs=['new value: (1, 2, 3, 4)']) + substrs=["new value: (1, 2, 3, 4)"], + ) diff --git a/lldb/test/API/commands/watchpoints/watchpoint_set_command/TestWatchLocationWithWatchSet.py b/lldb/test/API/commands/watchpoints/watchpoint_set_command/TestWatchLocationWithWatchSet.py --- a/lldb/test/API/commands/watchpoints/watchpoint_set_command/TestWatchLocationWithWatchSet.py +++ b/lldb/test/API/commands/watchpoints/watchpoint_set_command/TestWatchLocationWithWatchSet.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -18,28 +17,24 @@ # the same time. Tracked as llvm.org/pr49433 # or rdar://93863107 inside Apple. def affected_by_radar_93863107(self): - return (self.getArchitecture() in ['arm64', 'arm64e']) and self.platformIsDarwin() + return ( + self.getArchitecture() in ["arm64", "arm64e"] + ) and self.platformIsDarwin() def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Our simple source filename. - self.source = 'main.cpp' + self.source = "main.cpp" # Find the line number to break inside main(). - self.line = line_number( - self.source, '// Set break point at this line.') + self.line = line_number(self.source, "// Set break point at this line.") # This is for verifying that watch location works. self.violating_func = "do_bad_thing_with_location" # Build dictionary to have unique executable names for each test # method. - @skipIf( - oslist=["linux"], - archs=[ - 'aarch64', - 'arm'], - bugnumber="llvm.org/pr26031") - @skipIfWindows # This test is flaky on Windows + @skipIf(oslist=["linux"], archs=["aarch64", "arm"], bugnumber="llvm.org/pr26031") + @skipIfWindows # This test is flaky on Windows def test_watchlocation_using_watchpoint_set(self): """Test watching a location with 'watchpoint set expression -w write -s size' option.""" self.build() @@ -50,16 +45,19 @@ # Add a breakpoint to set a watchpoint when stopped on the breakpoint. lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1) + self, None, self.line, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now let's set a write-type watchpoint pointed to by 'g_char_ptr' and # with offset as 7. @@ -68,18 +66,14 @@ self.expect( "watchpoint set expression -w write -s 1 -- g_char_ptr + 7", WATCHPOINT_CREATED, - substrs=[ - 'Watchpoint created', - 'size = 1', - 'type = w']) + substrs=["Watchpoint created", "size = 1", "type = w"], + ) self.runCmd("expr unsigned val = g_char_ptr[7]; val") - self.expect(self.res.GetOutput().splitlines()[0], exe=False, - endstr=' = 0') + self.expect(self.res.GetOutput().splitlines()[0], exe=False, endstr=" = 0") # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", - substrs=['hit_count = 0']) + self.expect("watchpoint list -v", substrs=["hit_count = 0"]) # Check the underlying SBWatchpoint. watchpoint = target.GetWatchpointAtIndex(0) @@ -95,27 +89,27 @@ "thread list", STOPPED_DUE_TO_WATCHPOINT, substrs=[ - 'stopped', + "stopped", self.violating_func, - 'stop reason = watchpoint', - ]) + "stop reason = watchpoint", + ], + ) # Switch to the thread stopped due to watchpoint and issue some # commands. self.switch_to_thread_with_stop_reason(lldb.eStopReasonWatchpoint) self.runCmd("thread backtrace") self.runCmd("expr unsigned val = g_char_ptr[7]; val") - self.expect(self.res.GetOutput().splitlines()[0], exe=False, - endstr=' = 99') + self.expect(self.res.GetOutput().splitlines()[0], exe=False, endstr=" = 99") # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be the same as the number of threads that # stopped on a watchpoint. threads = lldbutil.get_stopped_threads( - self.process(), lldb.eStopReasonWatchpoint) + self.process(), lldb.eStopReasonWatchpoint + ) if not self.affected_by_radar_93863107(): - self.expect("watchpoint list -v", - substrs=['hit_count = %d' % len(threads)]) + self.expect("watchpoint list -v", substrs=["hit_count = %d" % len(threads)]) self.runCmd("thread backtrace all") diff --git a/lldb/test/API/commands/watchpoints/watchpoint_size/TestWatchpointSizes.py b/lldb/test/API/commands/watchpoints/watchpoint_size/TestWatchpointSizes.py --- a/lldb/test/API/commands/watchpoints/watchpoint_size/TestWatchpointSizes.py +++ b/lldb/test/API/commands/watchpoints/watchpoint_size/TestWatchpointSizes.py @@ -20,29 +20,29 @@ TestBase.setUp(self) # Source filename. - self.source = 'main.c' + self.source = "main.c" # Output filename. self.exe_name = self.getBuildArtifact("a.out") - self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + self.d = {"C_SOURCES": self.source, "EXE": self.exe_name} # Read-write watchpoints not supported on SystemZ - @expectedFailureAll(archs=['s390x']) + @expectedFailureAll(archs=["s390x"]) def test_byte_size_watchpoints_with_byte_selection(self): """Test to selectively watch different bytes in a 8-byte array.""" - self.run_watchpoint_size_test('byteArray', 8, '1') + self.run_watchpoint_size_test("byteArray", 8, "1") # Read-write watchpoints not supported on SystemZ - @expectedFailureAll(archs=['s390x']) + @expectedFailureAll(archs=["s390x"]) def test_two_byte_watchpoints_with_word_selection(self): """Test to selectively watch different words in an 8-byte word array.""" - self.run_watchpoint_size_test('wordArray', 4, '2') + self.run_watchpoint_size_test("wordArray", 4, "2") # Read-write watchpoints not supported on SystemZ - @expectedFailureAll(archs=['s390x']) + @expectedFailureAll(archs=["s390x"]) def test_four_byte_watchpoints_with_dword_selection(self): """Test to selectively watch two double words in an 8-byte dword array.""" - self.run_watchpoint_size_test('dwordArray', 2, '4') + self.run_watchpoint_size_test("dwordArray", 2, "4") def run_watchpoint_size_test(self, arrayName, array_size, watchsize): self.build(dictionary=self.d) @@ -52,11 +52,12 @@ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Detect line number after which we are going to increment arrayName. - loc_line = line_number('main.c', '// About to write ' + arrayName) + loc_line = line_number("main.c", "// About to write " + arrayName) # Set a breakpoint on the line detected above. lldbutil.run_break_set_by_file_and_line( - self, "main.c", loc_line, num_expected_locations=1, loc_exact=True) + self, "main.c", loc_line, num_expected_locations=1, loc_exact=True + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -64,56 +65,57 @@ for i in range(array_size): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Set a read_write type watchpoint arrayName watch_loc = arrayName + "[" + str(i) + "]" self.expect( - "watchpoint set variable -w read_write " + - watch_loc, + "watchpoint set variable -w read_write " + watch_loc, WATCHPOINT_CREATED, - substrs=[ - 'Watchpoint created', - 'size = ' + - watchsize, - 'type = rw']) + substrs=["Watchpoint created", "size = " + watchsize, "type = rw"], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", substrs=['hit_count = 0']) + self.expect("watchpoint list -v", substrs=["hit_count = 0"]) self.runCmd("process continue") # We should be stopped due to the watchpoint. # The stop reason of the thread should be watchpoint. - self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stopped', 'stop reason = watchpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stopped", "stop reason = watchpoint"], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. - self.expect("watchpoint list -v", - substrs=['hit_count = 1']) + self.expect("watchpoint list -v", substrs=["hit_count = 1"]) self.runCmd("process continue") # We should be stopped due to the watchpoint. # The stop reason of the thread should be watchpoint. - self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs=['stopped', 'stop reason = watchpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_WATCHPOINT, + substrs=["stopped", "stop reason = watchpoint"], + ) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. # Verify hit_count has been updated after value has been read. - self.expect("watchpoint list -v", - substrs=['hit_count = 2']) + self.expect("watchpoint list -v", substrs=["hit_count = 2"]) # Delete the watchpoint immediately, but set auto-confirm to true # first. self.runCmd("settings set auto-confirm true") - self.expect( - "watchpoint delete", - substrs=['All watchpoints removed.']) + self.expect("watchpoint delete", substrs=["All watchpoints removed."]) # Restore the original setting of auto-confirm. self.runCmd("settings clear auto-confirm") diff --git a/lldb/test/API/dotest.py b/lldb/test/API/dotest.py --- a/lldb/test/API/dotest.py +++ b/lldb/test/API/dotest.py @@ -4,4 +4,5 @@ import use_lldb_suite import lldbsuite.test + lldbsuite.test.run_suite() diff --git a/lldb/test/API/driver/batch_mode/TestBatchMode.py b/lldb/test/API/driver/batch_mode/TestBatchMode.py --- a/lldb/test/API/driver/batch_mode/TestBatchMode.py +++ b/lldb/test/API/driver/batch_mode/TestBatchMode.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,9 +11,9 @@ class DriverBatchModeTest(PExpectTest): - source = 'main.c' + source = "main.c" - @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot + @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") def test_batch_mode_run_crash(self): """Test that the lldb driver's batch mode works correctly.""" @@ -23,12 +22,18 @@ exe = self.getBuildArtifact("a.out") # Pass CRASH so the process will crash and stop in batch mode. - extra_args = ['-b', - '-o', 'break set -n main', - '-o', 'run', - '-o', 'continue', - '-k', 'frame var touch_me_not', - '--', 'CRASH', + extra_args = [ + "-b", + "-o", + "break set -n main", + "-o", + "run", + "-o", + "continue", + "-k", + "frame var touch_me_not", + "--", + "CRASH", ] self.launch(executable=exe, extra_args=extra_args) child = self.child @@ -40,12 +45,12 @@ # The App should have crashed: child.expect_exact("About to crash") # The -k option should have printed the frame variable once: - child.expect_exact('(char *) touch_me_not') + child.expect_exact("(char *) touch_me_not") # Then we should have a live prompt: self.expect_prompt() - self.expect("frame variable touch_me_not", substrs=['(char *) touch_me_not']) + self.expect("frame variable touch_me_not", substrs=["(char *) touch_me_not"]) - @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot + @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") def test_batch_mode_run_exit(self): """Test that the lldb driver's batch mode works correctly.""" @@ -54,11 +59,16 @@ exe = self.getBuildArtifact("a.out") # Now do it again, and make sure if we don't crash, we quit: - extra_args = ['-b', - '-o', 'break set -n main', - '-o', 'run', - '-o', 'continue', - '--', 'NOCRASH', + extra_args = [ + "-b", + "-o", + "break set -n main", + "-o", + "run", + "-o", + "continue", + "--", + "NOCRASH", ] self.launch(executable=exe, extra_args=extra_args) child = self.child @@ -73,9 +83,10 @@ # Then lldb should exit. child.expect_exact("exited") import pexpect + child.expect(pexpect.EOF) - @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot + @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") def test_batch_mode_launch_stop_at_entry(self): """Test that the lldb driver's batch mode works correctly for process launch.""" @@ -86,9 +97,12 @@ # Launch with the option '--stop-at-entry' stops with a signal (usually SIGSTOP) # that should be suppressed since it doesn't imply a crash and # this is not a reason to exit batch mode. - extra_args = ['-b', - '-o', 'process launch --stop-at-entry', - '-o', 'continue', + extra_args = [ + "-b", + "-o", + "process launch --stop-at-entry", + "-o", + "continue", ] self.launch(executable=exe, extra_args=extra_args) child = self.child @@ -103,6 +117,7 @@ # Then lldb should exit. child.expect_exact("exited") import pexpect + child.expect(pexpect.EOF) def closeVictim(self): @@ -110,7 +125,7 @@ self.victim.close() self.victim = None - @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot + @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) # Randomly fails on buildbot @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") @expectedFailureNetBSD def test_batch_mode_attach_exit(self): @@ -126,7 +141,8 @@ # Start up the process by hand and wait for it to get to the wait loop. import pexpect - self.victim = pexpect.spawn('%s WAIT' % (exe)) + + self.victim = pexpect.spawn("%s WAIT" % (exe)) if self.victim is None: self.fail("Could not spawn ", exe, ".") @@ -138,13 +154,20 @@ self.victim.expect("Waiting") extra_args = [ - '-b', - '-o', 'process attach -p %d'%victim_pid, - '-o', "breakpoint set --file '%s' -p 'Stop here to unset keep_waiting' -N keep_waiting"%self.source, - '-o', 'continue', - '-o', 'break delete keep_waiting', - '-o', 'expr keep_waiting = 0', - '-o', 'continue', + "-b", + "-o", + "process attach -p %d" % victim_pid, + "-o", + "breakpoint set --file '%s' -p 'Stop here to unset keep_waiting' -N keep_waiting" + % self.source, + "-o", + "continue", + "-o", + "break delete keep_waiting", + "-o", + "expr keep_waiting = 0", + "-o", + "continue", ] self.launch(executable=exe, extra_args=extra_args) child = self.child diff --git a/lldb/test/API/driver/job_control/TestJobControl.py b/lldb/test/API/driver/job_control/TestJobControl.py --- a/lldb/test/API/driver/job_control/TestJobControl.py +++ b/lldb/test/API/driver/job_control/TestJobControl.py @@ -8,14 +8,13 @@ class JobControlTest(PExpectTest): - @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) def test_job_control(self): def post_spawn(): self.child.expect("PID=([0-9]+)") self.lldb_pid = int(self.child.match[1]) - run_under = [sys.executable, self.getSourcePath('shell.py')] + run_under = [sys.executable, self.getSourcePath("shell.py")] self.launch(run_under=run_under, post_spawn=post_spawn) os.kill(self.lldb_pid, signal.SIGTSTP) diff --git a/lldb/test/API/functionalities/abbreviation/TestAbbreviations.py b/lldb/test/API/functionalities/abbreviation/TestAbbreviations.py --- a/lldb/test/API/functionalities/abbreviation/TestAbbreviations.py +++ b/lldb/test/API/functionalities/abbreviation/TestAbbreviations.py @@ -9,7 +9,6 @@ class AbbreviationsTestCase(TestBase): - @no_debug_info_test def test_command_abbreviations_and_aliases(self): command_interpreter = self.dbg.GetCommandInterpreter() @@ -42,11 +41,10 @@ # Make sure an unabbreviated command is not mangled. command_interpreter.ResolveCommand( - "breakpoint set --name main --line 123", result) + "breakpoint set --name main --line 123", result + ) self.assertTrue(result.Succeeded()) - self.assertEqual( - "breakpoint set --name main --line 123", - result.GetOutput()) + self.assertEqual("breakpoint set --name main --line 123", result.GetOutput()) # Create some aliases. self.runCmd("com a alias com al") @@ -67,39 +65,34 @@ command_interpreter.ResolveCommand("pltty /dev/tty0", result) self.assertTrue(result.Succeeded()) self.assertEqual( - "process launch -s -o /dev/tty0 -e /dev/tty0", - result.GetOutput()) + "process launch -s -o /dev/tty0 -e /dev/tty0", result.GetOutput() + ) self.runCmd("alias xyzzy breakpoint set -n %1 -l %2") command_interpreter.ResolveCommand("xyzzy main 123", result) self.assertTrue(result.Succeeded()) - self.assertEqual( - "breakpoint set -n main -l 123", - result.GetOutput().strip()) + self.assertEqual("breakpoint set -n main -l 123", result.GetOutput().strip()) # And again, without enough parameters. command_interpreter.ResolveCommand("xyzzy main", result) self.assertFalse(result.Succeeded()) # Check a command that wants the raw input. - command_interpreter.ResolveCommand( - r'''sc print("\n\n\tHello!\n")''', result) + command_interpreter.ResolveCommand(r"""sc print("\n\n\tHello!\n")""", result) self.assertTrue(result.Succeeded()) - self.assertEqual( - r'''script print("\n\n\tHello!\n")''', - result.GetOutput()) + self.assertEqual(r"""script print("\n\n\tHello!\n")""", result.GetOutput()) # Prompt changing stuff should be tested, but this doesn't seem like the # right test to do it in. It has nothing to do with aliases or abbreviations. - #self.runCmd("com sou ./change_prompt.lldb") + # self.runCmd("com sou ./change_prompt.lldb") # self.expect("settings show prompt", # startstr = 'prompt (string) = "[with-three-trailing-spaces] "') - #self.runCmd("settings clear prompt") + # self.runCmd("settings clear prompt") # self.expect("settings show prompt", # startstr = 'prompt (string) = "(lldb) "') - #self.runCmd("se se prompt 'Sycamore> '") + # self.runCmd("se se prompt 'Sycamore> '") # self.expect("se sh prompt", # startstr = 'prompt (string) = "Sycamore> "') - #self.runCmd("se cl prompt") + # self.runCmd("se cl prompt") # self.expect("set sh prompt", # startstr = 'prompt (string) = "(lldb) "') diff --git a/lldb/test/API/functionalities/abbreviation/TestCommonShortSpellings.py b/lldb/test/API/functionalities/abbreviation/TestCommonShortSpellings.py --- a/lldb/test/API/functionalities/abbreviation/TestCommonShortSpellings.py +++ b/lldb/test/API/functionalities/abbreviation/TestCommonShortSpellings.py @@ -4,7 +4,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,7 +11,6 @@ class CommonShortSpellingsTestCase(TestBase): - @no_debug_info_test def test_abbrevs2(self): command_interpreter = self.dbg.GetCommandInterpreter() @@ -20,17 +18,17 @@ result = lldb.SBCommandReturnObject() abbrevs = [ - ('br s', 'breakpoint set'), - ('disp', '_regexp-display'), # a.k.a., 'display' - ('di', 'disassemble'), - ('dis', 'disassemble'), - ('ta st a', 'target stop-hook add'), - ('fr v', 'frame variable'), - ('f 1', 'frame select 1'), - ('ta st li', 'target stop-hook list'), + ("br s", "breakpoint set"), + ("disp", "_regexp-display"), # a.k.a., 'display' + ("di", "disassemble"), + ("dis", "disassemble"), + ("ta st a", "target stop-hook add"), + ("fr v", "frame variable"), + ("f 1", "frame select 1"), + ("ta st li", "target stop-hook list"), ] - for (short_val, long_val) in abbrevs: + for short_val, long_val in abbrevs: command_interpreter.ResolveCommand(short_val, result) self.assertTrue(result.Succeeded()) self.assertEqual(long_val, result.GetOutput()) diff --git a/lldb/test/API/functionalities/archives/TestBSDArchives.py b/lldb/test/API/functionalities/archives/TestBSDArchives.py --- a/lldb/test/API/functionalities/archives/TestBSDArchives.py +++ b/lldb/test/API/functionalities/archives/TestBSDArchives.py @@ -1,7 +1,6 @@ """Test breaking inside functions defined within a BSD archive file libfoo.a.""" - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -9,8 +8,8 @@ import os import time -class BSDArchivesTestCase(TestBase): +class BSDArchivesTestCase(TestBase): # If your test case doesn't stress debug info, then # set this to true. That way it won't be run once for # each debug info format. @@ -20,12 +19,12 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number in a(int) to break at. - self.line = line_number( - 'a.c', '// Set file and line breakpoint inside a().') + self.line = line_number("a.c", "// Set file and line breakpoint inside a().") @expectedFailureAll( oslist=["windows"], - bugnumber="llvm.org/pr24527. Makefile.rules doesn't know how to build static libs on Windows") + bugnumber="llvm.org/pr24527. Makefile.rules doesn't know how to build static libs on Windows", + ) @expectedFailureAll(remote=True) def test(self): """Break inside a() and b() defined within libfoo.a.""" @@ -36,31 +35,39 @@ # Break inside a() by file and line first. lldbutil.run_break_set_by_file_and_line( - self, "a.c", self.line, num_expected_locations=1, loc_exact=True) + self, "a.c", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Break at a(int) first. - self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, - substrs=['(int) arg = 1']) + self.expect( + "frame variable", VARIABLES_DISPLAYED_CORRECTLY, substrs=["(int) arg = 1"] + ) self.expect_var_path("__a_global", type="int", value="1") # Set breakpoint for b() next. lldbutil.run_break_set_by_symbol( - self, "b", num_expected_locations=1, sym_exact=True) + self, "b", num_expected_locations=1, sym_exact=True + ) # Continue the program, we should break at b(int) next. self.runCmd("continue") - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) - self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, - substrs=['(int) arg = 2']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) + self.expect( + "frame variable", VARIABLES_DISPLAYED_CORRECTLY, substrs=["(int) arg = 2"] + ) self.expect_var_path("__b_global", type="int", value="2") # Test loading thin archives @@ -70,13 +77,13 @@ self.assertEqual(num_specs, 1) self.assertEqual(module_specs.GetSpecAtIndex(0).GetObjectName(), "c.o") - def check_frame_variable_errors(self, thread, error_strings): command_result = lldb.SBCommandReturnObject() interp = self.dbg.GetCommandInterpreter() result = interp.HandleCommand("frame variable", command_result) - self.assertEqual(result, lldb.eReturnStatusFailed, - "frame var succeeded unexpectedly") + self.assertEqual( + result, lldb.eReturnStatusFailed, "frame var succeeded unexpectedly" + ) command_error = command_result.GetError() frame = thread.GetFrameAtIndex(0) @@ -85,17 +92,23 @@ api_error = var_list.GetError().GetCString() for s in error_strings: - self.assertTrue(s in command_error, 'Make sure "%s" exists in the command error "%s"' % (s, command_error)) + self.assertTrue( + s in command_error, + 'Make sure "%s" exists in the command error "%s"' % (s, command_error), + ) for s in error_strings: - self.assertTrue(s in api_error, 'Make sure "%s" exists in the API error "%s"' % (s, api_error)) + self.assertTrue( + s in api_error, + 'Make sure "%s" exists in the API error "%s"' % (s, api_error), + ) @skipIfRemote @skipUnlessDarwin def test_frame_var_errors_when_archive_missing(self): """ - Break inside a() and remove libfoo.a to make sure we can't load - the debug information and report an appropriate error when doing - 'frame variable'. + Break inside a() and remove libfoo.a to make sure we can't load + the debug information and report an appropriate error when doing + 'frame variable'. """ self.build() exe = self.getBuildArtifact("a.out") @@ -107,11 +120,12 @@ os.unlink(libfoo_path) (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint( - self, 'a', bkpt_module=exe) + self, "a", bkpt_module=exe + ) error_strings = [ 'debug map object file "', - 'libfoo.a(a.o)" containing debug info does not exist, debug info will not be loaded' + 'libfoo.a(a.o)" containing debug info does not exist, debug info will not be loaded', ] self.check_frame_variable_errors(thread, error_strings) @@ -119,9 +133,9 @@ @skipUnlessDarwin def test_frame_var_errors_when_mtime_mistmatch_for_object_in_archive(self): """ - Break inside a() and modify the modification time for "a.o" within - libfoo.a to make sure we can't load the debug information and - report an appropriate error when doing 'frame variable'. + Break inside a() and modify the modification time for "a.o" within + libfoo.a to make sure we can't load the debug information and + report an appropriate error when doing 'frame variable'. """ self.build() exe = self.getBuildArtifact("a.out") @@ -138,11 +152,12 @@ self.build(make_targets=["libfoo.a"]) (target, process, thread, bkpt) = lldbutil.run_to_name_breakpoint( - self, 'a', bkpt_module=exe) + self, "a", bkpt_module=exe + ) error_strings = [ '"a.o" object from the "', - 'libfoo.a" archive: either the .o file doesn\'t exist in the archive or the modification time (0x', - ') of the .o file doesn\'t match' + "libfoo.a\" archive: either the .o file doesn't exist in the archive or the modification time (0x", + ") of the .o file doesn't match", ] self.check_frame_variable_errors(thread, error_strings) diff --git a/lldb/test/API/functionalities/asan/TestMemoryHistory.py b/lldb/test/API/functionalities/asan/TestMemoryHistory.py --- a/lldb/test/API/functionalities/asan/TestMemoryHistory.py +++ b/lldb/test/API/functionalities/asan/TestMemoryHistory.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,7 +11,6 @@ class AsanTestCase(TestBase): - @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default @expectedFailureNetBSD @skipUnlessAddressSanitizer @@ -23,10 +21,10 @@ def setUp(self): # Call super's setUp(). TestBase.setUp(self) - self.line_malloc = line_number('main.c', '// malloc line') - self.line_malloc2 = line_number('main.c', '// malloc2 line') - self.line_free = line_number('main.c', '// free line') - self.line_breakpoint = line_number('main.c', '// break line') + self.line_malloc = line_number("main.c", "// malloc line") + self.line_malloc2 = line_number("main.c", "// malloc2 line") + self.line_free = line_number("main.c", "// free line") + self.line_breakpoint = line_number("main.c", "// break line") def asan_tests(self): target = self.createTestTarget() @@ -36,72 +34,89 @@ self.runCmd("breakpoint set -f main.c -l %d" % self.line_breakpoint) # "memory history" command should not work without a process - self.expect("memory history 0", - error=True, - substrs=["Command requires a current process"]) + self.expect( + "memory history 0", + error=True, + substrs=["Command requires a current process"], + ) self.runCmd("run") - stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() + stop_reason = ( + self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() + ) if stop_reason == lldb.eStopReasonExec: # On OS X 10.10 and older, we need to re-exec to enable # interceptors. self.runCmd("continue") # the stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # test that the ASan dylib is present self.expect( "image lookup -n __asan_describe_address", "__asan_describe_address should be present", - substrs=['1 match found']) + substrs=["1 match found"], + ) # test the 'memory history' command self.expect( "memory history 'pointer'", substrs=[ - 'Memory deallocated by Thread', - 'a.out`f2', - 'main.c:%d' % self.line_free, - 'Memory allocated by Thread', - 'a.out`f1', - 'main.c:%d' % self.line_malloc, - ]) + "Memory deallocated by Thread", + "a.out`f2", + "main.c:%d" % self.line_free, + "Memory allocated by Thread", + "a.out`f1", + "main.c:%d" % self.line_malloc, + ], + ) # do the same using SB API process = self.dbg.GetSelectedTarget().process - val = process.GetSelectedThread().GetSelectedFrame().EvaluateExpression("pointer") + val = ( + process.GetSelectedThread().GetSelectedFrame().EvaluateExpression("pointer") + ) addr = val.GetValueAsUnsigned() threads = process.GetHistoryThreads(addr) self.assertEqual(threads.GetSize(), 2) history_thread = threads.GetThreadAtIndex(0) self.assertTrue(history_thread.num_frames >= 2) - self.assertEqual(history_thread.frames[1].GetLineEntry( - ).GetFileSpec().GetFilename(), "main.c") self.assertEqual( - history_thread.frames[1].GetLineEntry().GetLine(), - self.line_free) + history_thread.frames[1].GetLineEntry().GetFileSpec().GetFilename(), + "main.c", + ) + self.assertEqual( + history_thread.frames[1].GetLineEntry().GetLine(), self.line_free + ) history_thread = threads.GetThreadAtIndex(1) self.assertTrue(history_thread.num_frames >= 2) - self.assertEqual(history_thread.frames[1].GetLineEntry( - ).GetFileSpec().GetFilename(), "main.c") self.assertEqual( - history_thread.frames[1].GetLineEntry().GetLine(), - self.line_malloc) + history_thread.frames[1].GetLineEntry().GetFileSpec().GetFilename(), + "main.c", + ) + self.assertEqual( + history_thread.frames[1].GetLineEntry().GetLine(), self.line_malloc + ) # let's free the container (SBThreadCollection) and see if the # SBThreads still live threads = None self.assertTrue(history_thread.num_frames >= 2) - self.assertEqual(history_thread.frames[1].GetLineEntry( - ).GetFileSpec().GetFilename(), "main.c") self.assertEqual( - history_thread.frames[1].GetLineEntry().GetLine(), - self.line_malloc) + history_thread.frames[1].GetLineEntry().GetFileSpec().GetFilename(), + "main.c", + ) + self.assertEqual( + history_thread.frames[1].GetLineEntry().GetLine(), self.line_malloc + ) # ASan will break when a report occurs and we'll try the API then self.runCmd("continue") @@ -109,16 +124,16 @@ self.expect( "thread list", "Process should be stopped due to ASan report", - substrs=[ - 'stopped', - 'stop reason = Use of deallocated memory']) + substrs=["stopped", "stop reason = Use of deallocated memory"], + ) # make sure the 'memory history' command still works even when we're # generating a report now self.expect( "memory history 'another_pointer'", substrs=[ - 'Memory allocated by Thread', - 'a.out`f1', - 'main.c:%d' % - self.line_malloc2]) + "Memory allocated by Thread", + "a.out`f1", + "main.c:%d" % self.line_malloc2, + ], + ) diff --git a/lldb/test/API/functionalities/asan/TestReportData.py b/lldb/test/API/functionalities/asan/TestReportData.py --- a/lldb/test/API/functionalities/asan/TestReportData.py +++ b/lldb/test/API/functionalities/asan/TestReportData.py @@ -3,7 +3,6 @@ """ - import json import lldb from lldbsuite.test.decorators import * @@ -12,11 +11,10 @@ class AsanTestReportDataCase(TestBase): - @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default @expectedFailureNetBSD @skipUnlessAddressSanitizer - @skipIf(archs=['i386'], bugnumber="llvm.org/PR36710") + @skipIf(archs=["i386"], bugnumber="llvm.org/PR36710") def test(self): self.build() self.asan_tests() @@ -24,11 +22,11 @@ def setUp(self): # Call super's setUp(). TestBase.setUp(self) - self.line_malloc = line_number('main.c', '// malloc line') - self.line_malloc2 = line_number('main.c', '// malloc2 line') - self.line_free = line_number('main.c', '// free line') - self.line_breakpoint = line_number('main.c', '// break line') - self.line_crash = line_number('main.c', '// BOOM line') + self.line_malloc = line_number("main.c", "// malloc line") + self.line_malloc2 = line_number("main.c", "// malloc2 line") + self.line_free = line_number("main.c", "// free line") + self.line_breakpoint = line_number("main.c", "// break line") + self.line_crash = line_number("main.c", "// BOOM line") self.col_crash = 16 def asan_tests(self): @@ -38,7 +36,9 @@ self.runCmd("run") - stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() + stop_reason = ( + self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() + ) if stop_reason == lldb.eStopReasonExec: # On OS X 10.10 and older, we need to re-exec to enable # interceptors. @@ -47,16 +47,19 @@ self.expect( "thread list", "Process should be stopped due to ASan report", - substrs=[ - 'stopped', - 'stop reason = Use of deallocated memory']) + substrs=["stopped", "stop reason = Use of deallocated memory"], + ) self.assertEqual( self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), - lldb.eStopReasonInstrumentation) + lldb.eStopReasonInstrumentation, + ) - self.expect("bt", "The backtrace should show the crashing line", - substrs=['main.c:%d:%d' % (self.line_crash, self.col_crash)]) + self.expect( + "bt", + "The backtrace should show the crashing line", + substrs=["main.c:%d:%d" % (self.line_crash, self.col_crash)], + ) self.expect( "thread info -s", @@ -68,10 +71,11 @@ "description", "heap-use-after-free", "pc", - ]) + ], + ) - output_lines = self.res.GetOutput().split('\n') - json_line = '\n'.join(output_lines[2:]) + output_lines = self.res.GetOutput().split("\n") + json_line = "\n".join(output_lines[2:]) data = json.loads(json_line) self.assertEqual(data["description"], "heap-use-after-free") self.assertEqual(data["instrumentation_class"], "AddressSanitizer") diff --git a/lldb/test/API/functionalities/avoids-fd-leak/TestFdLeak.py b/lldb/test/API/functionalities/avoids-fd-leak/TestFdLeak.py --- a/lldb/test/API/functionalities/avoids-fd-leak/TestFdLeak.py +++ b/lldb/test/API/functionalities/avoids-fd-leak/TestFdLeak.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test import lldbutil from lldbsuite.test.lldbtest import * @@ -11,14 +10,13 @@ class AvoidsFdLeakTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True # The check for descriptor leakage needs to be implemented differently # here. @skipIfWindows @skipIfTargetAndroid() # Android have some other file descriptors open by the shell - @skipIfDarwinEmbedded # # debugserver on ios has an extra fd open on launch + @skipIfDarwinEmbedded # # debugserver on ios has an extra fd open on launch def test_fd_leak_basic(self): self.do_test([]) @@ -26,7 +24,7 @@ # here. @skipIfWindows @skipIfTargetAndroid() # Android have some other file descriptors open by the shell - @skipIfDarwinEmbedded # # debugserver on ios has an extra fd open on launch + @skipIfDarwinEmbedded # # debugserver on ios has an extra fd open on launch def test_fd_leak_log(self): self.do_test(["log enable -f '/dev/null' lldb commands"]) @@ -39,46 +37,50 @@ target = self.dbg.CreateTarget(exe) - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) self.assertEqual( - process.GetState(), lldb.eStateExited, - "Process should have exited.") + process.GetState(), lldb.eStateExited, "Process should have exited." + ) self.assertEqual( - process.GetExitStatus(), 0, - "Process returned non-zero status. Were incorrect file descriptors passed?") + process.GetExitStatus(), + 0, + "Process returned non-zero status. Were incorrect file descriptors passed?", + ) # The check for descriptor leakage needs to be implemented differently # here. @skipIfWindows @skipIfTargetAndroid() # Android have some other file descriptors open by the shell - @skipIfDarwinEmbedded # # debugserver on ios has an extra fd open on launch + @skipIfDarwinEmbedded # # debugserver on ios has an extra fd open on launch def test_fd_leak_multitarget(self): self.build() exe = self.getBuildArtifact("a.out") target = self.dbg.CreateTarget(exe) breakpoint = target.BreakpointCreateBySourceRegex( - 'Set breakpoint here', lldb.SBFileSpec("main.c", False)) + "Set breakpoint here", lldb.SBFileSpec("main.c", False) + ) self.assertTrue(breakpoint, VALID_BREAKPOINT) - process1 = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process1 = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process1, PROCESS_IS_VALID) self.assertEqual( - process1.GetState(), lldb.eStateStopped, - "Process should have been stopped.") + process1.GetState(), lldb.eStateStopped, "Process should have been stopped." + ) target2 = self.dbg.CreateTarget(exe) process2 = target2.LaunchSimple( - None, None, self.get_process_working_directory()) + None, None, self.get_process_working_directory() + ) self.assertTrue(process2, PROCESS_IS_VALID) self.assertEqual( - process2.GetState(), lldb.eStateExited, - "Process should have exited.") + process2.GetState(), lldb.eStateExited, "Process should have exited." + ) self.assertEqual( - process2.GetExitStatus(), 0, - "Process returned non-zero status. Were incorrect file descriptors passed?") + process2.GetExitStatus(), + 0, + "Process returned non-zero status. Were incorrect file descriptors passed?", + ) diff --git a/lldb/test/API/functionalities/backticks/TestBackticksWithoutATarget.py b/lldb/test/API/functionalities/backticks/TestBackticksWithoutATarget.py --- a/lldb/test/API/functionalities/backticks/TestBackticksWithoutATarget.py +++ b/lldb/test/API/functionalities/backticks/TestBackticksWithoutATarget.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,9 +10,7 @@ class BackticksWithNoTargetTestCase(TestBase): - @no_debug_info_test def test_backticks_no_target(self): """A simple test of backticks without a target.""" - self.expect("expression `1+2-3`", - substrs=[' = 0']) + self.expect("expression `1+2-3`", substrs=[" = 0"]) diff --git a/lldb/test/API/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py b/lldb/test/API/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py --- a/lldb/test/API/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py +++ b/lldb/test/API/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py @@ -3,14 +3,12 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * class AddressBreakpointTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True def test_address_breakpoints(self): @@ -24,17 +22,16 @@ # Now create a breakpoint on main.c by name 'c'. breakpoint = target.BreakpointCreateBySourceRegex( - "Set a breakpoint here", lldb.SBFileSpec("main.c")) - self.assertTrue(breakpoint and - breakpoint.GetNumLocations() >= 1, - VALID_BREAKPOINT) + "Set a breakpoint here", lldb.SBFileSpec("main.c") + ) + self.assertTrue( + breakpoint and breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT + ) # Get the breakpoint location from breakpoint after we verified that, # indeed, it has one location. location = breakpoint.GetLocationAtIndex(0) - self.assertTrue(location and - location.IsEnabled(), - VALID_BREAKPOINT_LOCATION) + self.assertTrue(location and location.IsEnabled(), VALID_BREAKPOINT_LOCATION) # Next get the address from the location, and create an address breakpoint using # that address: @@ -60,10 +57,11 @@ # Did we hit our breakpoint? from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint + threads = get_threads_stopped_at_breakpoint(process, breakpoint) self.assertEqual( - len(threads), 1, - "There should be a thread stopped at our breakpoint") + len(threads), 1, "There should be a thread stopped at our breakpoint" + ) # The hit count for the breakpoint should be 1. self.assertEquals(breakpoint.GetHitCount(), 1) @@ -79,8 +77,8 @@ thread = get_threads_stopped_at_breakpoint(process, breakpoint) self.assertEqual( - len(threads), 1, - "There should be a thread stopped at our breakpoint") + len(threads), 1, "There should be a thread stopped at our breakpoint" + ) # The hit count for the breakpoint should be 1, since we reset counts # for each run. diff --git a/lldb/test/API/functionalities/breakpoint/address_breakpoints/TestBadAddressBreakpoints.py b/lldb/test/API/functionalities/breakpoint/address_breakpoints/TestBadAddressBreakpoints.py --- a/lldb/test/API/functionalities/breakpoint/address_breakpoints/TestBadAddressBreakpoints.py +++ b/lldb/test/API/functionalities/breakpoint/address_breakpoints/TestBadAddressBreakpoints.py @@ -3,14 +3,12 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * class BadAddressBreakpointTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True def test_bad_address_breakpoints(self): @@ -20,12 +18,9 @@ def address_breakpoints(self): """Test that breakpoints set on a bad address say they are bad.""" - target, process, thread, bkpt = \ - lldbutil.run_to_source_breakpoint(self, - "Set a breakpoint here", - lldb.SBFileSpec("main.c")) - - + target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", lldb.SBFileSpec("main.c") + ) # illegal_address will hold (optionally) an address that, if # used as a breakpoint, will generate an unresolved breakpoint. @@ -37,8 +32,7 @@ for region_idx in range(regions.GetSize()): region = lldb.SBMemoryRegionInfo() regions.GetMemoryRegionAtIndex(region_idx, region) - if illegal_address == None or \ - region.GetRegionEnd() > illegal_address: + if illegal_address == None or region.GetRegionEnd() > illegal_address: illegal_address = region.GetRegionEnd() if illegal_address is not None: @@ -49,4 +43,5 @@ self.assertEquals(bp_loc.IsResolved(), False) else: self.fail( - "Could not find an illegal address at which to set a bad breakpoint.") + "Could not find an illegal address at which to set a bad breakpoint." + ) diff --git a/lldb/test/API/functionalities/breakpoint/auto_continue/TestBreakpointAutoContinue.py b/lldb/test/API/functionalities/breakpoint/auto_continue/TestBreakpointAutoContinue.py --- a/lldb/test/API/functionalities/breakpoint/auto_continue/TestBreakpointAutoContinue.py +++ b/lldb/test/API/functionalities/breakpoint/auto_continue/TestBreakpointAutoContinue.py @@ -3,14 +3,12 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * class BreakpointAutoContinue(TestBase): - NO_DEBUG_INFO_TESTCASE = True def test_breakpoint_auto_continue(self): @@ -28,19 +26,26 @@ self.build() self.auto_continue_location() - def make_target_and_bkpt(self, additional_options=None, num_expected_loc=1, - pattern="Set a breakpoint here"): + def make_target_and_bkpt( + self, + additional_options=None, + num_expected_loc=1, + pattern="Set a breakpoint here", + ): self.target = self.createTestTarget() extra_options_txt = "--auto-continue 1 " if additional_options: extra_options_txt += additional_options - bpno = lldbutil.run_break_set_by_source_regexp(self, pattern, - extra_options = extra_options_txt, - num_expected_locations = num_expected_loc) + bpno = lldbutil.run_break_set_by_source_regexp( + self, + pattern, + extra_options=extra_options_txt, + num_expected_locations=num_expected_loc, + ) return bpno - def launch_it (self, expected_state): + def launch_it(self, expected_state): error = lldb.SBError() launch_info = self.target.GetLaunchInfo() launch_info.SetWorkingDirectory(self.get_process_working_directory()) @@ -58,25 +63,33 @@ process = self.launch_it(lldb.eStateExited) bkpt = self.target.FindBreakpointByID(bpno) - self.assertEqual(bkpt.GetHitCount(), 2, "Should have run through the breakpoint twice") + self.assertEqual( + bkpt.GetHitCount(), 2, "Should have run through the breakpoint twice" + ) def auto_continue_with_command(self): - bpno = self.make_target_and_bkpt("-N BKPT -C 'break modify --auto-continue 0 BKPT'") + bpno = self.make_target_and_bkpt( + "-N BKPT -C 'break modify --auto-continue 0 BKPT'" + ) process = self.launch_it(lldb.eStateStopped) state = process.GetState() self.assertState(state, lldb.eStateStopped, "Process should be stopped") bkpt = self.target.FindBreakpointByID(bpno) threads = lldbutil.get_threads_stopped_at_breakpoint(process, bkpt) - self.assertEqual(len(threads), 1, "There was a thread stopped at our breakpoint") + self.assertEqual( + len(threads), 1, "There was a thread stopped at our breakpoint" + ) self.assertEqual(bkpt.GetHitCount(), 2, "Should have hit the breakpoint twice") def auto_continue_location(self): - bpno = self.make_target_and_bkpt(pattern="Set a[^ ]* breakpoint here", num_expected_loc=2) + bpno = self.make_target_and_bkpt( + pattern="Set a[^ ]* breakpoint here", num_expected_loc=2 + ) bkpt = self.target.FindBreakpointByID(bpno) bkpt.SetAutoContinue(False) loc = lldb.SBBreakpointLocation() - for i in range(0,2): + for i in range(0, 2): func_name = bkpt.location[i].GetAddress().function.name if func_name == "main": loc = bkpt.location[i] @@ -87,6 +100,8 @@ process = self.launch_it(lldb.eStateStopped) threads = lldbutil.get_threads_stopped_at_breakpoint(process, bkpt) - self.assertEqual(len(threads), 1, "Didn't get one thread stopped at our breakpoint") + self.assertEqual( + len(threads), 1, "Didn't get one thread stopped at our breakpoint" + ) func_name = threads[0].frame[0].function.name self.assertEqual(func_name, "call_me") diff --git a/lldb/test/API/functionalities/breakpoint/break_in_loaded_dylib/TestBreakInLoadedDylib.py b/lldb/test/API/functionalities/breakpoint/break_in_loaded_dylib/TestBreakInLoadedDylib.py --- a/lldb/test/API/functionalities/breakpoint/break_in_loaded_dylib/TestBreakInLoadedDylib.py +++ b/lldb/test/API/functionalities/breakpoint/break_in_loaded_dylib/TestBreakInLoadedDylib.py @@ -3,9 +3,11 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestBreakInLoadedDylib(TestBase): - """ Test that we can set a source regex breakpoint that will take in + """Test that we can set a source regex breakpoint that will take in a dlopened library that hasn't loaded when we set the breakpoint.""" + NO_DEBUG_INFO_TESTCASE = True @skipIfRemote @@ -14,31 +16,43 @@ ctx = self.platformContext self.main_spec = lldb.SBFileSpec("main.cpp") self.b_spec = lldb.SBFileSpec("b.cpp") - self.lib_shortname = 'lib_b' - self.lib_fullname = ctx.shlib_prefix + self.lib_shortname + '.' + ctx.shlib_extension + self.lib_shortname = "lib_b" + self.lib_fullname = ( + ctx.shlib_prefix + self.lib_shortname + "." + ctx.shlib_extension + ) self.lib_spec = lldb.SBFileSpec(self.lib_fullname) - + def test_break_in_dlopen_dylib_using_lldbutils(self): self.common_setup() - lldbutil.run_to_source_breakpoint(self, "Break here in dylib", self.b_spec, - bkpt_module=self.lib_fullname, - extra_images = [self.lib_shortname], - has_locations_before_run = False) + lldbutil.run_to_source_breakpoint( + self, + "Break here in dylib", + self.b_spec, + bkpt_module=self.lib_fullname, + extra_images=[self.lib_shortname], + has_locations_before_run=False, + ) @skipIfRemote def test_break_in_dlopen_dylib_using_target(self): self.common_setup() - target, process, _, _ = lldbutil.run_to_source_breakpoint(self, "Break here before we dlopen", self.main_spec, - extra_images = [self.lib_shortname]) - + target, process, _, _ = lldbutil.run_to_source_breakpoint( + self, + "Break here before we dlopen", + self.main_spec, + extra_images=[self.lib_shortname], + ) + # Now set some breakpoints that won't take till the library is loaded: # This one is currently how lldbutils does it but test here in case that changes: - bkpt1 = target.BreakpointCreateBySourceRegex("Break here in dylib", self.b_spec, self.lib_fullname) + bkpt1 = target.BreakpointCreateBySourceRegex( + "Break here in dylib", self.b_spec, self.lib_fullname + ) # Try the file list API as well. Put in some bogus entries too, to make sure those # don't trip us up: - + files_list = lldb.SBFileSpecList() files_list.Append(self.b_spec) files_list.Append(self.main_spec) @@ -48,12 +62,10 @@ modules_list.Append(self.lib_spec) modules_list.Append(lldb.SBFileSpec("libI_bet_not_this_one_either.dylib")) - bkpt2 = target.BreakpointCreateBySourceRegex("Break here in dylib", modules_list, files_list) + bkpt2 = target.BreakpointCreateBySourceRegex( + "Break here in dylib", modules_list, files_list + ) lldbutil.continue_to_breakpoint(process, bkpt1) self.assertEqual(bkpt1.GetHitCount(), 1, "Hit breakpoint 1") self.assertEqual(bkpt2.GetHitCount(), 1, "Hit breakpoint 2") - - - - diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_by_file_colon_line/TestBreakpointByFileColonLine.py b/lldb/test/API/functionalities/breakpoint/breakpoint_by_file_colon_line/TestBreakpointByFileColonLine.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_by_file_colon_line/TestBreakpointByFileColonLine.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_by_file_colon_line/TestBreakpointByFileColonLine.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,24 +10,26 @@ class BreakpointByLineAndColumnTestCase(TestBase): - def testBreakpointSpecWithLine(self): self.build() target = self.createTestTarget() - + # This one should work: - lldbutil.run_break_set_by_file_colon_line(self, "main.c:11", "main.c", 11, num_expected_locations = 1) + lldbutil.run_break_set_by_file_colon_line( + self, "main.c:11", "main.c", 11, num_expected_locations=1 + ) # Let's try an illegal specifier to make sure the command fails. I'm not being exhaustive # since the UnitTest has more bad patterns. I'm just testing that if the SetFromString # fails, we propagate the error. self.expect("break set -y 'foo.c'", error=True) - + ## Skip gcc version less 7.1 since it doesn't support -gcolumn-info - @skipIf(compiler="gcc", compiler_version=['<', '7.1']) + @skipIf(compiler="gcc", compiler_version=["<", "7.1"]) def testBreakpointByLine(self): self.build() target = self.createTestTarget() main_c = lldb.SBFileSpec("main.c") - lldbutil.run_break_set_by_file_colon_line(self, "main.c:11:50", "main.c", 11, num_expected_locations = 1) - + lldbutil.run_break_set_by_file_colon_line( + self, "main.c:11:50", "main.c", 11, num_expected_locations=1 + ) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_by_line_and_column/TestBreakpointByLineAndColumn.py b/lldb/test/API/functionalities/breakpoint/breakpoint_by_line_and_column/TestBreakpointByLineAndColumn.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_by_line_and_column/TestBreakpointByLineAndColumn.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_by_line_and_column/TestBreakpointByLineAndColumn.py @@ -10,17 +10,16 @@ class BreakpointByLineAndColumnTestCase(TestBase): - ## Skip gcc version less 7.1 since it doesn't support -gcolumn-info - @skipIf(compiler="gcc", compiler_version=['<', '7.1']) + @skipIf(compiler="gcc", compiler_version=["<", "7.1"]) def testBreakpointByLineAndColumn(self): self.build() src_file = lldb.SBFileSpec("main.cpp") - line = line_number("main.cpp", - "At the beginning of a function name (col:50)") + 1 # Next line after comment - _, _, _, breakpoint = lldbutil.run_to_line_breakpoint(self, - src_file, line, 50) - self.expect("fr v did_call", substrs=['1']) + line = ( + line_number("main.cpp", "At the beginning of a function name (col:50)") + 1 + ) # Next line after comment + _, _, _, breakpoint = lldbutil.run_to_line_breakpoint(self, src_file, line, 50) + self.expect("fr v did_call", substrs=["1"]) in_then = False for i in range(breakpoint.GetNumLocations()): b_loc = breakpoint.GetLocationAtIndex(i).GetAddress().GetLineEntry() @@ -29,15 +28,15 @@ self.assertTrue(in_then) ## Skip gcc version less 7.1 since it doesn't support -gcolumn-info - @skipIf(compiler="gcc", compiler_version=['<', '7.1']) + @skipIf(compiler="gcc", compiler_version=["<", "7.1"]) def testBreakpointByLine(self): self.build() src_file = lldb.SBFileSpec("main.cpp") - line = line_number("main.cpp", - "At the beginning of a function name (col:50)") + 1 # Next line after comment - _, _, _, breakpoint = lldbutil.run_to_line_breakpoint(self, src_file, - line) - self.expect("fr v did_call", substrs=['0']) + line = ( + line_number("main.cpp", "At the beginning of a function name (col:50)") + 1 + ) # Next line after comment + _, _, _, breakpoint = lldbutil.run_to_line_breakpoint(self, src_file, line) + self.expect("fr v did_call", substrs=["0"]) in_condition = False for i in range(breakpoint.GetNumLocations()): b_loc = breakpoint.GetLocationAtIndex(i).GetAddress().GetLineEntry() @@ -47,53 +46,56 @@ @skipIfWindows ## Skip gcc version less 7.1 since it doesn't support -gcolumn-info - @skipIf(compiler="gcc", compiler_version=['<', '7.1']) + @skipIf(compiler="gcc", compiler_version=["<", "7.1"]) def testBreakpointByLineAndColumnNearestCode(self): self.build() patterns = [ "In the middle of a function name (col:42)", "In the middle of the lambda declaration argument (col:23)", - "Inside the lambda (col:26)" + "Inside the lambda (col:26)", ] source_loc = [] for pattern in patterns: line = line_number("main.cpp", pattern) + 1 - column = int(re.search('\(col:([0-9]+)\)', pattern).group(1)) - source_loc.append({'line':line, 'column':column}) + column = int(re.search("\(col:([0-9]+)\)", pattern).group(1)) + source_loc.append({"line": line, "column": column}) target = self.createTestTarget() for loc in source_loc: src_file = lldb.SBFileSpec("main.cpp") - line = loc['line'] - column = loc['column'] + line = loc["line"] + column = loc["column"] indent = 0 module_list = lldb.SBFileSpecList() - valid_bpkt = target.BreakpointCreateByLocation(src_file, line, - column, indent, - module_list, True) + valid_bpkt = target.BreakpointCreateByLocation( + src_file, line, column, indent, module_list, True + ) self.assertTrue(valid_bpkt, VALID_BREAKPOINT) self.assertEqual(valid_bpkt.GetNumLocations(), 1) - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) nearest_column = [7, 17, 26] - for idx,loc in enumerate(source_loc): + for idx, loc in enumerate(source_loc): bpkt = target.GetBreakpointAtIndex(idx) bpkt_loc = bpkt.GetLocationAtIndex(0) self.assertEqual(bpkt_loc.GetHitCount(), 1) self.assertSuccess(process.Continue()) bpkt_loc_desc = lldb.SBStream() - self.assertTrue(bpkt_loc.GetDescription(bpkt_loc_desc, lldb.eDescriptionLevelVerbose)) - self.assertIn("main.cpp:{}:{}".format(loc['line'], nearest_column[idx]), - bpkt_loc_desc.GetData()) + self.assertTrue( + bpkt_loc.GetDescription(bpkt_loc_desc, lldb.eDescriptionLevelVerbose) + ) + self.assertIn( + "main.cpp:{}:{}".format(loc["line"], nearest_column[idx]), + bpkt_loc_desc.GetData(), + ) bpkt_loc_addr = bpkt_loc.GetAddress() self.assertTrue(bpkt_loc_addr) @@ -105,9 +107,8 @@ found = False for line_entry in compile_unit: if line_entry.GetStartAddress() == bpkt_loc_addr: - self.assertEqual(line_entry.GetFileSpec().GetFilename(), - "main.cpp") - self.assertEqual(line_entry.GetLine(), loc['line']) + self.assertEqual(line_entry.GetFileSpec().GetFilename(), "main.cpp") + self.assertEqual(line_entry.GetLine(), loc["line"]) self.assertEqual(line_entry.GetColumn(), nearest_column[idx]) found = True break @@ -117,8 +118,8 @@ line = line_number("main.cpp", "// This is a random comment.") column = len("// This is a random comment.") indent = 2 - invalid_bpkt = target.BreakpointCreateByLocation(src_file, line, column, - indent, module_list, False) + invalid_bpkt = target.BreakpointCreateByLocation( + src_file, line, column, indent, module_list, False + ) self.assertTrue(invalid_bpkt, VALID_BREAKPOINT) self.assertEqual(invalid_bpkt.GetNumLocations(), 0) - diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_callback_command_source/TestBreakpointCallbackCommandSource.py b/lldb/test/API/functionalities/breakpoint/breakpoint_callback_command_source/TestBreakpointCallbackCommandSource.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_callback_command_source/TestBreakpointCallbackCommandSource.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_callback_command_source/TestBreakpointCallbackCommandSource.py @@ -11,7 +11,9 @@ class BreakpointCallbackCommandSource(PExpectTest): - file_to_source = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'source.lldb') + file_to_source = os.path.join( + os.path.abspath(os.path.dirname(__file__)), "source.lldb" + ) # PExpect uses many timeouts internally and doesn't play well # under ASAN on a loaded machine.. @@ -27,8 +29,10 @@ self.expect("b main", substrs=["Breakpoint 1"]) self.child.send("breakpoint command add -s python\n") self.child.send( - "frame.GetThread().GetProcess().GetTarget().GetDebugger().HandleCommand('command source -s true {}')\n" - .format(self.file_to_source)) + "frame.GetThread().GetProcess().GetTarget().GetDebugger().HandleCommand('command source -s true {}')\n".format( + self.file_to_source + ) + ) self.child.send("DONE\n") self.expect_prompt() self.expect("run", substrs=["Process", "stopped"]) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py b/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -13,9 +12,7 @@ import side_effect - class BreakpointCommandTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24528") @@ -38,24 +35,24 @@ @no_debug_info_test def test_breakpoints_with_relative_path_line_tables(self): """ - Test that we can set breakpoints using a full or partial path when - line tables in the debug information has relative paths where the - relative path is either fully contained in the specified path, or if - the specified path also a relative path that is shorter than the - path in the debug info. - - The "relative.yaml" contains a line table that is: - - Line table for a/b/c/main.cpp in `a.out - 0x0000000100003f94: a/b/c/main.cpp:1 - 0x0000000100003fb0: a/b/c/main.cpp:2:3 - 0x0000000100003fb8: a/b/c/main.cpp:2:3 - - So the line table contains relative paths. We should be able to set - breakpoints with any source path that matches this path which - includes paths that are longer than "a/b/c/main.cpp", but also any - relative path that is shorter than this while all specified relative - path components still match. + Test that we can set breakpoints using a full or partial path when + line tables in the debug information has relative paths where the + relative path is either fully contained in the specified path, or if + the specified path also a relative path that is shorter than the + path in the debug info. + + The "relative.yaml" contains a line table that is: + + Line table for a/b/c/main.cpp in `a.out + 0x0000000100003f94: a/b/c/main.cpp:1 + 0x0000000100003fb0: a/b/c/main.cpp:2:3 + 0x0000000100003fb8: a/b/c/main.cpp:2:3 + + So the line table contains relative paths. We should be able to set + breakpoints with any source path that matches this path which + includes paths that are longer than "a/b/c/main.cpp", but also any + relative path that is shorter than this while all specified relative + path components still match. """ src_dir = self.getSourceDir() yaml_path = os.path.join(src_dir, "relative.yaml") @@ -89,9 +86,12 @@ ] for path in valid_paths: bkpt = target.BreakpointCreateByLocation(path, 2) - self.assertTrue(bkpt.GetNumLocations() > 0, + self.assertTrue( + bkpt.GetNumLocations() > 0, 'Couldn\'t resolve breakpoint using full path "%s" in executate "%s" with ' - 'debug info that has relative path with matching suffix' % (path, self.getBuildArtifact("a.out"))) + "debug info that has relative path with matching suffix" + % (path, self.getBuildArtifact("a.out")), + ) invalid_paths = [ "/x/b/c/main.cpp", "/x/c/main.cpp", @@ -102,32 +102,35 @@ self.runCmd("settings clear target.source-map") for path in invalid_paths: bkpt = target.BreakpointCreateByLocation(path, 2) - self.assertEqual(bkpt.GetNumLocations(), 0, + self.assertEqual( + bkpt.GetNumLocations(), + 0, 'Incorrectly resolved a breakpoint using full path "%s" with ' - 'debug info that has relative path with matching suffix' % (path)) + "debug info that has relative path with matching suffix" % (path), + ) @no_debug_info_test def test_breakpoints_with_bad_aranges(self): """ - Test that we can set breakpoints in a file that has an invalid - .debug_aranges. Older versions of LLDB would find a line entry - in the line table and then would use the start address of the line - entry to do an address lookup on the entry from the line table. If - this address to symbol context lookup would fail, due to a bad - .debug_aranges, it would cause the breakpoint to not get resolved. - Verify that even in these conditions we are able to resolve a - breakpoint. - - The "bad_aranges.yaml" contains a line table that is: - - Line table for /tmp/ab/main.cpp in `a.out - 0x0000000100003f94: /tmp/ab/main.cpp:1 - 0x0000000100003fb0: /tmp/ab/main.cpp:2:3 - 0x0000000100003fb8: /tmp/ab/main.cpp:2:3 - - The .debug_aranges has one range for this compile unit that is - invalid: [0x0000000200003f94-0x0000000200003fb8). This will cause - the resolving of the addresses to fail. + Test that we can set breakpoints in a file that has an invalid + .debug_aranges. Older versions of LLDB would find a line entry + in the line table and then would use the start address of the line + entry to do an address lookup on the entry from the line table. If + this address to symbol context lookup would fail, due to a bad + .debug_aranges, it would cause the breakpoint to not get resolved. + Verify that even in these conditions we are able to resolve a + breakpoint. + + The "bad_aranges.yaml" contains a line table that is: + + Line table for /tmp/ab/main.cpp in `a.out + 0x0000000100003f94: /tmp/ab/main.cpp:1 + 0x0000000100003fb0: /tmp/ab/main.cpp:2:3 + 0x0000000100003fb8: /tmp/ab/main.cpp:2:3 + + The .debug_aranges has one range for this compile unit that is + invalid: [0x0000000200003f94-0x0000000200003fb8). This will cause + the resolving of the addresses to fail. """ src_dir = self.getSourceDir() yaml_path = os.path.join(src_dir, "bad_aranges.yaml") @@ -137,22 +140,23 @@ # Create a target with the object file we just created from YAML target = self.dbg.CreateTarget(obj_path) - src_path = '/tmp/ab/main.cpp' + src_path = "/tmp/ab/main.cpp" bkpt = target.BreakpointCreateByLocation(src_path, 2) - self.assertTrue(bkpt.GetNumLocations() > 0, + self.assertTrue( + bkpt.GetNumLocations() > 0, 'Couldn\'t resolve breakpoint using "%s" in executate "%s" with ' - 'debug info that has a bad .debug_aranges section' % (src_path, self.getBuildArtifact("a.out"))) - + "debug info that has a bad .debug_aranges section" + % (src_path, self.getBuildArtifact("a.out")), + ) def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.line = line_number('main.c', '// Set break point at this line.') + self.line = line_number("main.c", "// Set break point at this line.") # disable "There is a running process, kill it and restart?" prompt self.runCmd("settings set auto-confirm true") - self.addTearDownHook( - lambda: self.runCmd("settings clear auto-confirm")) + self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) def test_delete_all_breakpoints(self): """Test that deleting all breakpoints works.""" @@ -162,15 +166,18 @@ lldbutil.run_break_set_by_symbol(self, "main") lldbutil.run_break_set_by_file_and_line( - self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + self, "main.c", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) self.runCmd("breakpoint delete") self.runCmd("process continue") - self.expect("process status", PROCESS_STOPPED, - patterns=['Process .* exited with status = 0']) - + self.expect( + "process status", + PROCESS_STOPPED, + patterns=["Process .* exited with status = 0"], + ) def breakpoint_command_sequence(self): """Test a sequence of breakpoint command add, list, and delete.""" @@ -180,90 +187,137 @@ # Add three breakpoints on the same line. The first time we don't specify the file, # since the default file is the one containing main: lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1, loc_exact=True) + self, None, self.line, num_expected_locations=1, loc_exact=True + ) lldbutil.run_break_set_by_file_and_line( - self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + self, "main.c", self.line, num_expected_locations=1, loc_exact=True + ) lldbutil.run_break_set_by_file_and_line( - self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + self, "main.c", self.line, num_expected_locations=1, loc_exact=True + ) # Breakpoint 4 - set at the same location as breakpoint 1 to test # setting breakpoint commands on two breakpoints at a time lldbutil.run_break_set_by_file_and_line( - self, None, self.line, num_expected_locations=1, loc_exact=True) + self, None, self.line, num_expected_locations=1, loc_exact=True + ) # Make sure relative path source breakpoints work as expected. We test # with partial paths with and without "./" prefixes. lldbutil.run_break_set_by_file_and_line( - self, "./main.c", self.line, - num_expected_locations=1, loc_exact=True) + self, "./main.c", self.line, num_expected_locations=1, loc_exact=True + ) lldbutil.run_break_set_by_file_and_line( - self, "breakpoint_command/main.c", self.line, - num_expected_locations=1, loc_exact=True) + self, + "breakpoint_command/main.c", + self.line, + num_expected_locations=1, + loc_exact=True, + ) lldbutil.run_break_set_by_file_and_line( - self, "./breakpoint_command/main.c", self.line, - num_expected_locations=1, loc_exact=True) + self, + "./breakpoint_command/main.c", + self.line, + num_expected_locations=1, + loc_exact=True, + ) lldbutil.run_break_set_by_file_and_line( - self, "breakpoint/breakpoint_command/main.c", self.line, - num_expected_locations=1, loc_exact=True) + self, + "breakpoint/breakpoint_command/main.c", + self.line, + num_expected_locations=1, + loc_exact=True, + ) lldbutil.run_break_set_by_file_and_line( - self, "./breakpoint/breakpoint_command/main.c", self.line, - num_expected_locations=1, loc_exact=True) + self, + "./breakpoint/breakpoint_command/main.c", + self.line, + num_expected_locations=1, + loc_exact=True, + ) # Test relative breakpoints with incorrect paths and make sure we get # no breakpoint locations lldbutil.run_break_set_by_file_and_line( - self, "invalid/main.c", self.line, - num_expected_locations=0, loc_exact=True) + self, "invalid/main.c", self.line, num_expected_locations=0, loc_exact=True + ) lldbutil.run_break_set_by_file_and_line( - self, "./invalid/main.c", self.line, - num_expected_locations=0, loc_exact=True) + self, + "./invalid/main.c", + self.line, + num_expected_locations=0, + loc_exact=True, + ) # Now add callbacks for the breakpoints just created. self.runCmd( - "breakpoint command add -s command -o 'frame variable --show-types --scope' 1 4") + "breakpoint command add -s command -o 'frame variable --show-types --scope' 1 4" + ) self.runCmd( - "breakpoint command add -s python -o 'import side_effect; side_effect.one_liner = \"one liner was here\"' 2") + "breakpoint command add -s python -o 'import side_effect; side_effect.one_liner = \"one liner was here\"' 2" + ) import side_effect + self.runCmd("command script import --allow-reload ./bktptcmd.py") - self.runCmd( - "breakpoint command add --python-function bktptcmd.function 3") + self.runCmd("breakpoint command add --python-function bktptcmd.function 3") # Check that the breakpoint commands are correctly set. # The breakpoint list now only contains breakpoint 1. self.expect( - "breakpoint list", "Breakpoints 1 & 2 created", substrs=[ - "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % - self.line], patterns=[ - "1: file = '.*main.c', line = %d, exact_match = 0, locations = 1" % - self.line]) + "breakpoint list", + "Breakpoints 1 & 2 created", + substrs=[ + "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" + % self.line + ], + patterns=[ + "1: file = '.*main.c', line = %d, exact_match = 0, locations = 1" + % self.line + ], + ) self.expect( "breakpoint list -f", "Breakpoints 1 & 2 created", substrs=[ - "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % - self.line], + "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" + % self.line + ], patterns=[ - "1: file = '.*main.c', line = %d, exact_match = 0, locations = 1" % - self.line, - "1.1: .+at main.c:%d:?[0-9]*, .+unresolved, hit count = 0" % - self.line, - "2.1: .+at main.c:%d:?[0-9]*, .+unresolved, hit count = 0" % - self.line]) - - self.expect("breakpoint command list 1", "Breakpoint 1 command ok", - substrs=["Breakpoint commands:", - "frame variable --show-types --scope"]) - self.expect("breakpoint command list 2", "Breakpoint 2 command ok", - substrs=["Breakpoint commands (Python):", - "import side_effect", - "side_effect.one_liner"]) - self.expect("breakpoint command list 3", "Breakpoint 3 command ok", - substrs=["Breakpoint commands (Python):", - "bktptcmd.function(frame, bp_loc, internal_dict)"]) - - self.expect("breakpoint command list 4", "Breakpoint 4 command ok", - substrs=["Breakpoint commands:", - "frame variable --show-types --scope"]) + "1: file = '.*main.c', line = %d, exact_match = 0, locations = 1" + % self.line, + "1.1: .+at main.c:%d:?[0-9]*, .+unresolved, hit count = 0" % self.line, + "2.1: .+at main.c:%d:?[0-9]*, .+unresolved, hit count = 0" % self.line, + ], + ) + + self.expect( + "breakpoint command list 1", + "Breakpoint 1 command ok", + substrs=["Breakpoint commands:", "frame variable --show-types --scope"], + ) + self.expect( + "breakpoint command list 2", + "Breakpoint 2 command ok", + substrs=[ + "Breakpoint commands (Python):", + "import side_effect", + "side_effect.one_liner", + ], + ) + self.expect( + "breakpoint command list 3", + "Breakpoint 3 command ok", + substrs=[ + "Breakpoint commands (Python):", + "bktptcmd.function(frame, bp_loc, internal_dict)", + ], + ) + + self.expect( + "breakpoint command list 4", + "Breakpoint 4 command ok", + substrs=["Breakpoint commands:", "frame variable --show-types --scope"], + ) self.runCmd("breakpoint delete 4") @@ -272,32 +326,34 @@ # the second time only one: lldbutil.run_break_set_by_regexp( - self, r"._MyFunction", num_expected_locations=2) + self, r"._MyFunction", num_expected_locations=2 + ) lldbutil.run_break_set_by_regexp( - self, - r"._MyFunction", - extra_options="-f a.c", - num_expected_locations=1) + self, r"._MyFunction", extra_options="-f a.c", num_expected_locations=1 + ) lldbutil.run_break_set_by_regexp( self, r"._MyFunction", extra_options="-f a.c -f b.c", - num_expected_locations=2) + num_expected_locations=2, + ) # Now try a source regex breakpoint: lldbutil.run_break_set_by_source_regexp( self, r"is about to return [12]0", extra_options="-f a.c -f b.c", - num_expected_locations=2) + num_expected_locations=2, + ) lldbutil.run_break_set_by_source_regexp( self, r"is about to return [12]0", extra_options="-f a.c", - num_expected_locations=1) + num_expected_locations=1, + ) # Reset our canary variables and run the program. side_effect.one_liner = None @@ -319,20 +375,24 @@ self.expect( "breakpoint command list 1", - startstr="Breakpoint 1 does not have an associated command.") + startstr="Breakpoint 1 does not have an associated command.", + ) self.expect( "breakpoint command list 2", error=True, - startstr="error: '2' is not a currently valid breakpoint ID.") + startstr="error: '2' is not a currently valid breakpoint ID.", + ) # The breakpoint list now only contains breakpoint 1. self.expect( "breakpoint list -f", "Breakpoint 1 exists", patterns=[ - "1: file = '.*main.c', line = %d, exact_match = 0, locations = 1, resolved = 1" % - self.line, - "hit count = 1"]) + "1: file = '.*main.c', line = %d, exact_match = 0, locations = 1, resolved = 1" + % self.line, + "hit count = 1", + ], + ) # Not breakpoint 2. self.expect( @@ -340,8 +400,10 @@ "No more breakpoint 2", matching=False, substrs=[ - "2: file = 'main.c', line = %d, exact_match = 0, locations = 1, resolved = 1" % - self.line]) + "2: file = 'main.c', line = %d, exact_match = 0, locations = 1, resolved = 1" + % self.line + ], + ) # Run the program again, with breakpoint 1 remaining. self.runCmd("run", RUN_SUCCEEDED) @@ -349,13 +411,15 @@ # We should be stopped again due to breakpoint 1. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # The breakpoint should have a hit count of 1, since we reset counts # for each run. - lldbutil.check_breakpoint(self, bpno = 1, expected_hit_count = 1) + lldbutil.check_breakpoint(self, bpno=1, expected_hit_count=1) def breakpoint_command_script_parameters(self): """Test that the frame and breakpoint location are being properly passed to the script breakpoint command function.""" @@ -364,10 +428,13 @@ # Add a breakpoint. lldbutil.run_break_set_by_file_and_line( - self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + self, "main.c", self.line, num_expected_locations=1, loc_exact=True + ) # Now add callbacks for the breakpoints just created. - self.runCmd("breakpoint command add -s python -o 'import side_effect; side_effect.frame = str(frame); side_effect.bp_loc = str(bp_loc)' 1") + self.runCmd( + "breakpoint command add -s python -o 'import side_effect; side_effect.frame = str(frame); side_effect.bp_loc = str(bp_loc)' 1" + ) # Reset canary variables and run. side_effect.frame = None @@ -375,8 +442,11 @@ self.runCmd("run", RUN_SUCCEEDED) self.expect(side_effect.frame, exe=False, startstr="frame #0:") - self.expect(side_effect.bp_loc, exe=False, - patterns=["1.* where = .*main .* resolved,( hardware,)? hit count = 1"]) + self.expect( + side_effect.bp_loc, + exe=False, + patterns=["1.* where = .*main .* resolved,( hardware,)? hit count = 1"], + ) def breakpoint_commands_on_creation(self): """Test that setting breakpoint commands when creating the breakpoint works""" @@ -384,8 +454,13 @@ # Add a breakpoint. lldbutil.run_break_set_by_file_and_line( - self, "main.c", self.line, num_expected_locations=1, loc_exact=True, - extra_options='-C bt -C "thread list" -C continue') + self, + "main.c", + self.line, + num_expected_locations=1, + loc_exact=True, + extra_options='-C bt -C "thread list" -C continue', + ) bkpt = target.FindBreakpointByID(1) self.assertTrue(bkpt.IsValid(), "Couldn't find breakpoint 1") @@ -393,12 +468,14 @@ bkpt.GetCommandLineCommands(com_list) self.assertEqual(com_list.GetSize(), 3, "Got the wrong number of commands") self.assertEqual(com_list.GetStringAtIndex(0), "bt", "First bt") - self.assertEqual(com_list.GetStringAtIndex(1), "thread list", "Next thread list") + self.assertEqual( + com_list.GetStringAtIndex(1), "thread list", "Next thread list" + ) self.assertEqual(com_list.GetStringAtIndex(2), "continue", "Last continue") def test_add_commands_by_breakpoint_name(self): """Make sure that when you specify a breakpoint name to "break command add" - it gets added to all the breakpoints marked with that name.""" + it gets added to all the breakpoints marked with that name.""" self.build() target = self.createTestTarget() @@ -411,17 +488,21 @@ # First do it with a script one-liner: self.runCmd("breakpoint command add -s py -o 'print(\"some command\")' MyBKPTS") for id in bp_ids: - self.expect("breakpoint command list {0}".format(id), - patterns=["some command"]) + self.expect( + "breakpoint command list {0}".format(id), patterns=["some command"] + ) # Now do the same thing with a python function: import side_effect + self.runCmd("command script import --allow-reload ./bktptcmd.py") - self.runCmd("breakpoint command add --python-function bktptcmd.function MyBKPTS") + self.runCmd( + "breakpoint command add --python-function bktptcmd.function MyBKPTS" + ) for id in bp_ids: - self.expect("breakpoint command list {0}".format(id), - patterns=["bktptcmd.function"]) - + self.expect( + "breakpoint command list {0}".format(id), patterns=["bktptcmd.function"] + ) def test_breakpoint_delete_disabled(self): """Test 'break delete --disabled' works""" @@ -449,7 +530,9 @@ self.assertTrue(bp_2.IsValid(), "Deleted enabled breakpoint 2") bp_3 = target.FindBreakpointByID(bp_id_3) - self.assertTrue(bp_3.IsValid(), "DeleteMeNot didn't protect disabled breakpoint 3") + self.assertTrue( + bp_3.IsValid(), "DeleteMeNot didn't protect disabled breakpoint 3" + ) # Reset the first breakpoint, disable it, and do this again with no protected name: bp_1 = target.BreakpointCreateByName("main") @@ -469,42 +552,45 @@ bp_3 = target.FindBreakpointByID(bp_id_3) self.assertFalse(bp_3.IsValid(), "Didn't delete disabled breakpoint 3") - def get_source_map_json(self): stream = lldb.SBStream() self.dbg.GetSetting("target.source-map").GetAsJSON(stream) return json.loads(stream.GetData()) def verify_source_map_entry_pair(self, entry, original, replacement): - self.assertEquals(entry[0], original, - "source map entry 'original' does not match") - self.assertEquals(entry[1], replacement, - "source map entry 'replacement' does not match") + self.assertEquals( + entry[0], original, "source map entry 'original' does not match" + ) + self.assertEquals( + entry[1], replacement, "source map entry 'replacement' does not match" + ) def verify_source_map_deduce_statistics(self, target, expected_count): stream = lldb.SBStream() res = target.GetStatistics().GetAsJSON(stream) self.assertTrue(res.Success()) debug_stats = json.loads(stream.GetData()) - self.assertEqual('targets' in debug_stats, True, - 'Make sure the "targets" key in in target.GetStatistics()') - target_stats = debug_stats['targets'][0] + self.assertEqual( + "targets" in debug_stats, + True, + 'Make sure the "targets" key in in target.GetStatistics()', + ) + target_stats = debug_stats["targets"][0] self.assertNotEqual(target_stats, None) - self.assertEqual(target_stats['sourceMapDeduceCount'], expected_count) - + self.assertEqual(target_stats["sourceMapDeduceCount"], expected_count) @skipIf(oslist=["windows"]) @no_debug_info_test def test_breakpoints_auto_source_map_relative(self): """ - Test that with target.auto-source-map-relative settings. + Test that with target.auto-source-map-relative settings. - The "relative.yaml" contains a line table that is: + The "relative.yaml" contains a line table that is: - Line table for a/b/c/main.cpp in `a.out - 0x0000000100003f94: a/b/c/main.cpp:1 - 0x0000000100003fb0: a/b/c/main.cpp:2:3 - 0x0000000100003fb8: a/b/c/main.cpp:2:3 + Line table for a/b/c/main.cpp in `a.out + 0x0000000100003f94: a/b/c/main.cpp:1 + 0x0000000100003fb0: a/b/c/main.cpp:2:3 + 0x0000000100003fb8: a/b/c/main.cpp:2:3 """ src_dir = self.getSourceDir() yaml_path = os.path.join(src_dir, "relative.yaml") @@ -518,16 +604,21 @@ # "./a/b/c/main.cpp". source_map_json = self.get_source_map_json() - self.assertEquals(len(source_map_json), 0, "source map should be empty initially") + self.assertEquals( + len(source_map_json), 0, "source map should be empty initially" + ) self.verify_source_map_deduce_statistics(target, 0) # Verify auto deduced source map when file path in debug info # is a suffix of request breakpoint file path path = "/x/y/a/b/c/main.cpp" bp = target.BreakpointCreateByLocation(path, 2) - self.assertTrue(bp.GetNumLocations() > 0, - 'Couldn\'t resolve breakpoint using full path "%s" in executate "%s" with ' - 'debug info that has relative path with matching suffix' % (path, self.getBuildArtifact("a.out"))) + self.assertTrue( + bp.GetNumLocations() > 0, + 'Couldn\'t resolve breakpoint using full path "%s" in executate "%s" with ' + "debug info that has relative path with matching suffix" + % (path, self.getBuildArtifact("a.out")), + ) source_map_json = self.get_source_map_json() self.assertEquals(len(source_map_json), 1, "source map should not be empty") @@ -541,32 +632,38 @@ # equals the file path in debug info. path = "a/b/c/main.cpp" bp = target.BreakpointCreateByLocation(path, 2) - self.assertTrue(bp.GetNumLocations() > 0, - 'Couldn\'t resolve breakpoint using full path "%s" in executate "%s" with ' - 'debug info that has relative path with matching suffix' % (path, self.getBuildArtifact("a.out"))) + self.assertTrue( + bp.GetNumLocations() > 0, + 'Couldn\'t resolve breakpoint using full path "%s" in executate "%s" with ' + "debug info that has relative path with matching suffix" + % (path, self.getBuildArtifact("a.out")), + ) source_map_json = self.get_source_map_json() self.assertEquals(len(source_map_json), 0, "source map should not be deduced") - def test_breakpoint_statistics_hitcount(self): """Test breakpoints statistics have hitCount field.""" self.build() target = self.createTestTarget() lldbutil.run_break_set_by_file_and_line( - self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + self, "main.c", self.line, num_expected_locations=1, loc_exact=True + ) stream = lldb.SBStream() res = target.GetStatistics().GetAsJSON(stream) self.assertTrue(res.Success()) debug_stats = json.loads(stream.GetData()) - self.assertEqual('targets' in debug_stats, True, - 'Make sure the "targets" key in in target.GetStatistics()') - target_stats = debug_stats['targets'][0] + self.assertEqual( + "targets" in debug_stats, + True, + 'Make sure the "targets" key in in target.GetStatistics()', + ) + target_stats = debug_stats["targets"][0] self.assertNotEqual(target_stats, None) - breakpoints_stats = target_stats['breakpoints'] + breakpoints_stats = target_stats["breakpoints"] self.assertNotEqual(breakpoints_stats, None) for breakpoint_stats in breakpoints_stats: self.assertIn("hitCount", breakpoint_stats) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py b/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py @@ -12,7 +12,7 @@ class PythonBreakpointCommandSettingTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) def test_step_out_python(self): """Test stepping out using a python breakpoint command.""" self.build() @@ -34,19 +34,23 @@ self.target = self.createTestTarget() body_bkpt = self.target.BreakpointCreateBySourceRegex( - "Set break point at this line.", self.main_source_spec) + "Set break point at this line.", self.main_source_spec + ) self.assertTrue(body_bkpt, VALID_BREAKPOINT) func_bkpt = self.target.BreakpointCreateBySourceRegex( - "Set break point at this line.", self.main_source_spec) + "Set break point at this line.", self.main_source_spec + ) self.assertTrue(func_bkpt, VALID_BREAKPOINT) fancy_bkpt = self.target.BreakpointCreateBySourceRegex( - "Set break point at this line.", self.main_source_spec) + "Set break point at this line.", self.main_source_spec + ) self.assertTrue(fancy_bkpt, VALID_BREAKPOINT) fancier_bkpt = self.target.BreakpointCreateBySourceRegex( - "Set break point at this line.", self.main_source_spec) + "Set break point at this line.", self.main_source_spec + ) self.assertTrue(fancier_bkpt, VALID_BREAKPOINT) # Also test the list version of this: @@ -54,30 +58,35 @@ file_list.Append(self.main_source_spec) module_list = lldb.SBFileSpecList() module_list.Append(self.target.GetExecutable()) - + list_bkpt = self.target.BreakpointCreateBySourceRegex( - "Set break point at this line.", module_list, file_list) + "Set break point at this line.", module_list, file_list + ) self.assertTrue(list_bkpt, VALID_BREAKPOINT) - not_so_fancy_bkpt = self.target.BreakpointCreateBySourceRegex( - "Set break point at this line.", self.main_source_spec) + "Set break point at this line.", self.main_source_spec + ) self.assertTrue(not_so_fancy_bkpt, VALID_BREAKPOINT) # Also test that setting a source regex breakpoint with an empty file # spec list sets it on all files: no_files_bkpt = self.target.BreakpointCreateBySourceRegex( - "Set a breakpoint here", lldb.SBFileSpecList(), lldb.SBFileSpecList()) + "Set a breakpoint here", lldb.SBFileSpecList(), lldb.SBFileSpecList() + ) self.assertTrue(no_files_bkpt, VALID_BREAKPOINT) num_locations = no_files_bkpt.GetNumLocations() - self.assertTrue( - num_locations >= 2, - "Got at least two breakpoint locations") + self.assertTrue(num_locations >= 2, "Got at least two breakpoint locations") got_one_in_A = False got_one_in_B = False for idx in range(0, num_locations): - comp_unit = no_files_bkpt.GetLocationAtIndex(idx).GetAddress().GetSymbolContext( - lldb.eSymbolContextCompUnit).GetCompileUnit().GetFileSpec() + comp_unit = ( + no_files_bkpt.GetLocationAtIndex(idx) + .GetAddress() + .GetSymbolContext(lldb.eSymbolContextCompUnit) + .GetCompileUnit() + .GetFileSpec() + ) print("Got comp unit: ", comp_unit.GetFilename()) if comp_unit.GetFilename() == "a.c": got_one_in_A = True @@ -90,11 +99,12 @@ error = lldb.SBError() error = body_bkpt.SetScriptCallbackBody( - "import side_effect; side_effect.callback = 'callback was here'") + "import side_effect; side_effect.callback = 'callback was here'" + ) self.assertTrue( error.Success(), - "Failed to set the script callback body: %s." % - (error.GetCString())) + "Failed to set the script callback body: %s." % (error.GetCString()), + ) self.expect("command script import --allow-reload ./bktptcmd.py") @@ -104,7 +114,9 @@ stream = lldb.SBStream() stream.Print('{"side_effect" : "I am fancy"}') extra_args.SetFromJSON(stream) - error = fancy_bkpt.SetScriptCallbackFunction("bktptcmd.another_function", extra_args) + error = fancy_bkpt.SetScriptCallbackFunction( + "bktptcmd.another_function", extra_args + ) self.assertSuccess(error, "Failed to add callback") stream.Clear() @@ -113,41 +125,52 @@ # Fancier's callback is set up from the command line id = fancier_bkpt.GetID() - self.expect("breakpoint command add -F bktptcmd.a_third_function -k side_effect -v 'I am fancier' %d"%(id)) + self.expect( + "breakpoint command add -F bktptcmd.a_third_function -k side_effect -v 'I am fancier' %d" + % (id) + ) # Not so fancy gets an empty extra_args: empty_args = lldb.SBStructuredData() - error = not_so_fancy_bkpt.SetScriptCallbackFunction("bktptcmd.empty_extra_args", empty_args) + error = not_so_fancy_bkpt.SetScriptCallbackFunction( + "bktptcmd.empty_extra_args", empty_args + ) self.assertSuccess(error, "Failed to add callback") # Do list breakpoint like fancy: stream.Clear() stream.Print('{"side_effect" : "I come from list input"}') extra_args.SetFromJSON(stream) - error = list_bkpt.SetScriptCallbackFunction("bktptcmd.a_list_function", extra_args) + error = list_bkpt.SetScriptCallbackFunction( + "bktptcmd.a_list_function", extra_args + ) self.assertSuccess(error, "Failed to add callback") - + # Clear out canary variables side_effect.bktptcmd = None side_effect.callback = None - side_effect.fancy = None - side_effect.fancier = None + side_effect.fancy = None + side_effect.fancier = None side_effect.not_so_fancy = None side_effect.a_list_function = None - + # Now launch the process, and do not stop at entry point. self.process = self.target.LaunchSimple( - None, None, self.get_process_working_directory()) + None, None, self.get_process_working_directory() + ) self.assertTrue(self.process, PROCESS_IS_VALID) # Now finish, and make sure the return value is correct. - threads = lldbutil.get_threads_stopped_at_breakpoint( - self.process, body_bkpt) + threads = lldbutil.get_threads_stopped_at_breakpoint(self.process, body_bkpt) self.assertEquals(len(threads), 1, "Stopped at inner breakpoint.") self.thread = threads[0] - print("* Num Locations: {0} ; Hit Count {1}".format(list_bkpt.GetNumLocations(), list_bkpt.GetHitCount())) + print( + "* Num Locations: {0} ; Hit Count {1}".format( + list_bkpt.GetNumLocations(), list_bkpt.GetHitCount() + ) + ) self.assertEquals("callback was here", side_effect.callback) self.assertEquals("function was here", side_effect.bktptcmd) self.assertEquals("I am fancy", side_effect.fancy) @@ -163,7 +186,8 @@ self.expect("command script import --allow-reload ./bktptcmd.py") bkpt = self.target.BreakpointCreateBySourceRegex( - "Set break point at this line.", self.main_source_spec) + "Set break point at this line.", self.main_source_spec + ) self.assertTrue(bkpt, VALID_BREAKPOINT) # Pass a breakpoint command function that doesn't take extra_args, @@ -175,11 +199,17 @@ extra_args.SetFromJSON(stream) error = bkpt.SetScriptCallbackFunction("bktptcmd.function", extra_args) - self.assertTrue(error.Fail(), "Can't pass extra args if the function doesn't take them") + self.assertTrue( + error.Fail(), "Can't pass extra args if the function doesn't take them" + ) error = bkpt.SetScriptCallbackFunction("bktptcmd.useless_function", extra_args) - self.assertTrue(error.Fail(), "Can't pass extra args if the function has wrong number of args.") + self.assertTrue( + error.Fail(), + "Can't pass extra args if the function has wrong number of args.", + ) error = bkpt.SetScriptCallbackFunction("bktptcmd.nosuch_function", extra_args) - self.assertTrue(error.Fail(), "Can't pass extra args if the function doesn't exist.") - + self.assertTrue( + error.Fail(), "Can't pass extra args if the function doesn't exist." + ) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py b/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py @@ -3,7 +3,6 @@ """ - import os import lldb from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class RegexpBreakCommandTestCase(TestBase): - def test(self): """Test _regexp-break command.""" self.build() @@ -21,48 +19,52 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.source = 'main.c' - self.line = line_number( - self.source, '// Set break point at this line.') + self.source = "main.c" + self.line = line_number(self.source, "// Set break point at this line.") def regexp_break_command(self): """Test the super consie "b" command, which is analias for _regexp-break.""" exe = self.getBuildArtifact("a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - break_results = lldbutil.run_break_set_command( - self, "b %d" % - self.line) + break_results = lldbutil.run_break_set_command(self, "b %d" % self.line) lldbutil.check_breakpoint_result( self, break_results, - file_name='main.c', + file_name="main.c", line_number=self.line, - num_locations=1) + num_locations=1, + ) break_results = lldbutil.run_break_set_command( - self, "b %s:%d" % (self.source, self.line)) + self, "b %s:%d" % (self.source, self.line) + ) lldbutil.check_breakpoint_result( self, break_results, - file_name='main.c', + file_name="main.c", line_number=self.line, - num_locations=1) + num_locations=1, + ) # Check breakpoint with full file path. full_path = os.path.join(self.getSourceDir(), self.source) break_results = lldbutil.run_break_set_command( - self, "b %s:%d" % (full_path, self.line)) + self, "b %s:%d" % (full_path, self.line) + ) lldbutil.check_breakpoint_result( self, break_results, - file_name='main.c', + file_name="main.c", line_number=self.line, - num_locations=1) + num_locations=1, + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_command/bktptcmd.py b/lldb/test/API/functionalities/breakpoint/breakpoint_command/bktptcmd.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_command/bktptcmd.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_command/bktptcmd.py @@ -1,27 +1,32 @@ import side_effect + def useless_function(first, second): print("I have the wrong number of arguments.") + def function(frame, bp_loc, dict): side_effect.bktptcmd = "function was here" + def another_function(frame, bp_loc, extra_args, dict): se_value = extra_args.GetValueForKey("side_effect") se_string = se_value.GetStringValue(100) side_effect.fancy = se_string + def a_third_function(frame, bp_loc, extra_args, dict): se_value = extra_args.GetValueForKey("side_effect") se_string = se_value.GetStringValue(100) side_effect.fancier = se_string + def a_list_function(frame, bp_loc, extra_args, dict): se_value = extra_args.GetValueForKey("side_effect") se_string = se_value.GetStringValue(100) side_effect.from_list = se_string - + def empty_extra_args(frame, bp_loc, extra_args, dict): if extra_args.IsValid(): side_effect.not_so_fancy = "Extra args should not be valid" diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py b/lldb/test/API/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py @@ -9,7 +9,6 @@ class BreakpointConditionsTestCase(TestBase): - def test_breakpoint_condition_and_run_command(self): """Exercise breakpoint condition with 'breakpoint modify -c id'.""" self.build() @@ -20,13 +19,13 @@ self.build() self.breakpoint_conditions(inline=True) - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) def test_breakpoint_condition_and_python_api(self): """Use Python APIs to set breakpoint conditions.""" self.build() self.breakpoint_conditions_python() - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) def test_breakpoint_invalid_condition_and_python_api(self): """Use Python APIs to set breakpoint conditions.""" self.build() @@ -37,9 +36,11 @@ TestBase.setUp(self) # Find the line number to of function 'c'. self.line1 = line_number( - 'main.c', '// Find the line number of function "c" here.') + "main.c", '// Find the line number of function "c" here.' + ) self.line2 = line_number( - 'main.c', "// Find the line number of c's parent call here.") + "main.c", "// Find the line number of c's parent call here." + ) def breakpoint_conditions(self, inline=False): """Exercise breakpoint condition with 'breakpoint modify -c id'.""" @@ -53,11 +54,13 @@ "c", extra_options="-c 'val == 3'", num_expected_locations=1, - sym_exact=True) + sym_exact=True, + ) else: # Create a breakpoint by function name 'c'. lldbutil.run_break_set_by_symbol( - self, "c", num_expected_locations=1, sym_exact=True) + self, "c", num_expected_locations=1, sym_exact=True + ) # And set a condition on the breakpoint to stop on when 'val == 3'. self.runCmd("breakpoint modify -c 'val == 3' 1") @@ -66,28 +69,34 @@ self.runCmd("run", RUN_SUCCEEDED) # The process should be stopped at this point. - self.expect("process status", PROCESS_STOPPED, - patterns=['Process .* stopped']) + self.expect("process status", PROCESS_STOPPED, patterns=["Process .* stopped"]) # 'frame variable --show-types val' should return 3 due to breakpoint condition. self.expect( "frame variable --show-types val", VARIABLES_DISPLAYED_CORRECTLY, - startstr='(int) val = 3') + startstr="(int) val = 3", + ) # Also check the hit count, which should be 3, by design. - self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs=["resolved = 1", - "Condition: val == 3", - "hit count = 1"]) + self.expect( + "breakpoint list -f", + BREAKPOINT_HIT_ONCE, + substrs=["resolved = 1", "Condition: val == 3", "hit count = 1"], + ) # The frame #0 should correspond to main.c:36, the executable statement # in function name 'c'. And the parent frame should point to # main.c:24. - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT_CONDITION, - #substrs = ["stop reason = breakpoint"], - patterns=["frame #0.*main.c:%d" % self.line1, - "frame #1.*main.c:%d" % self.line2]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT_CONDITION, + # substrs = ["stop reason = breakpoint"], + patterns=[ + "frame #0.*main.c:%d" % self.line1, + "frame #1.*main.c:%d" % self.line2, + ], + ) # Test that "breakpoint modify -c ''" clears the condition for the last # created breakpoint, so that when the breakpoint hits, val == 1. @@ -97,20 +106,21 @@ "breakpoint list -f", BREAKPOINT_STATE_CORRECT, matching=False, - substrs=["Condition:"]) + substrs=["Condition:"], + ) # Now run the program again. self.runCmd("run", RUN_SUCCEEDED) # The process should be stopped at this point. - self.expect("process status", PROCESS_STOPPED, - patterns=['Process .* stopped']) + self.expect("process status", PROCESS_STOPPED, patterns=["Process .* stopped"]) # 'frame variable --show-types val' should return 1 since it is the first breakpoint hit. self.expect( "frame variable --show-types val", VARIABLES_DISPLAYED_CORRECTLY, - startstr='(int) val = 1') + startstr="(int) val = 1", + ) self.runCmd("process kill") @@ -119,54 +129,58 @@ target = self.createTestTarget() # Now create a breakpoint on main.c by name 'c'. - breakpoint = target.BreakpointCreateByName('c', 'a.out') + breakpoint = target.BreakpointCreateByName("c", "a.out") self.trace("breakpoint:", breakpoint) - self.assertTrue(breakpoint and - breakpoint.GetNumLocations() == 1, - VALID_BREAKPOINT) + self.assertTrue( + breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT + ) # We didn't associate a thread index with the breakpoint, so it should # be invalid. - self.assertEqual(breakpoint.GetThreadIndex(), lldb.UINT32_MAX, - "The thread index should be invalid") + self.assertEqual( + breakpoint.GetThreadIndex(), + lldb.UINT32_MAX, + "The thread index should be invalid", + ) # The thread name should be invalid, too. - self.assertTrue(breakpoint.GetThreadName() is None, - "The thread name should be invalid") + self.assertTrue( + breakpoint.GetThreadName() is None, "The thread name should be invalid" + ) # Let's set the thread index for this breakpoint and verify that it is, # indeed, being set correctly. # There's only one thread for the process. breakpoint.SetThreadIndex(1) - self.assertEqual(breakpoint.GetThreadIndex(), 1, - "The thread index has been set correctly") + self.assertEqual( + breakpoint.GetThreadIndex(), 1, "The thread index has been set correctly" + ) # Get the breakpoint location from breakpoint after we verified that, # indeed, it has one location. location = breakpoint.GetLocationAtIndex(0) - self.assertTrue(location and - location.IsEnabled(), - VALID_BREAKPOINT_LOCATION) + self.assertTrue(location and location.IsEnabled(), VALID_BREAKPOINT_LOCATION) # Set the condition on the breakpoint location. - location.SetCondition('val == 3') - self.expect(location.GetCondition(), exe=False, - startstr='val == 3') + location.SetCondition("val == 3") + self.expect(location.GetCondition(), exe=False, startstr="val == 3") # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.line1 and the break condition should hold. from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( thread.IsValid(), - "There should be a thread stopped due to breakpoint condition") + "There should be a thread stopped due to breakpoint condition", + ) frame0 = thread.GetFrameAtIndex(0) - var = frame0.FindValue('val', lldb.eValueTypeVariableArgument) - self.assertTrue(frame0.GetLineEntry().GetLine() == self.line1 and - var.GetValue() == '3') + var = frame0.FindValue("val", lldb.eValueTypeVariableArgument) + self.assertTrue( + frame0.GetLineEntry().GetLine() == self.line1 and var.GetValue() == "3" + ) # The hit count for the breakpoint should be 1. self.assertEqual(breakpoint.GetHitCount(), 1) @@ -174,8 +188,9 @@ # Test that the condition expression didn't create a result variable: options = lldb.SBExpressionOptions() value = frame0.EvaluateExpression("$0", options) - self.assertTrue(value.GetError().Fail(), - "Conditions should not make result variables.") + self.assertTrue( + value.GetError().Fail(), "Conditions should not make result variables." + ) process.Continue() def breakpoint_invalid_conditions_python(self): @@ -187,30 +202,34 @@ self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c by name 'c'. - breakpoint = target.BreakpointCreateByName('c', 'a.out') + breakpoint = target.BreakpointCreateByName("c", "a.out") self.trace("breakpoint:", breakpoint) - self.assertTrue(breakpoint and - breakpoint.GetNumLocations() == 1, - VALID_BREAKPOINT) + self.assertTrue( + breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT + ) # Set the condition on the breakpoint. - breakpoint.SetCondition('no_such_variable == not_this_one_either') - self.expect(breakpoint.GetCondition(), exe=False, - startstr='no_such_variable == not_this_one_either') + breakpoint.SetCondition("no_such_variable == not_this_one_either") + self.expect( + breakpoint.GetCondition(), + exe=False, + startstr="no_such_variable == not_this_one_either", + ) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.line1 and the break condition should hold. from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( thread.IsValid(), - "There should be a thread stopped due to breakpoint condition") + "There should be a thread stopped due to breakpoint condition", + ) frame0 = thread.GetFrameAtIndex(0) - var = frame0.FindValue('val', lldb.eValueTypeVariableArgument) + var = frame0.FindValue("val", lldb.eValueTypeVariableArgument) self.assertEqual(frame0.GetLineEntry().GetLine(), self.line1) # The hit count for the breakpoint should be 1. diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_hit_count/TestBreakpointHitCount.py b/lldb/test/API/functionalities/breakpoint/breakpoint_hit_count/TestBreakpointHitCount.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_hit_count/TestBreakpointHitCount.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_hit_count/TestBreakpointHitCount.py @@ -10,10 +10,9 @@ class BreakpointHitCountTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) def test_breakpoint_location_hit_count(self): """Use Python APIs to check breakpoint hit count.""" self.build() @@ -25,18 +24,21 @@ target = self.createTestTarget() self.runCmd("tb a") - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( - thread.IsValid(), - "There should be a thread stopped due to breakpoint") + thread.IsValid(), "There should be a thread stopped due to breakpoint" + ) frame0 = thread.GetFrameAtIndex(0) - self.assertTrue(frame0.GetFunctionName() == "a(int)" or frame0.GetFunctionName() == "int a(int)"); + self.assertTrue( + frame0.GetFunctionName() == "a(int)" + or frame0.GetFunctionName() == "int a(int)" + ) process.Continue() self.assertState(process.GetState(), lldb.eStateExited) @@ -44,10 +46,8 @@ def setUp(self): # Call super's setUp(). TestBase.setUp(self) - self.a_int_body_line_no = line_number( - 'main.cpp', '// Breakpoint Location 1') - self.a_float_body_line_no = line_number( - 'main.cpp', '// Breakpoint Location 2') + self.a_int_body_line_no = line_number("main.cpp", "// Breakpoint Location 1") + self.a_float_body_line_no = line_number("main.cpp", "// Breakpoint Location 2") def do_test_breakpoint_location_hit_count(self): """Use Python APIs to check breakpoint hit count.""" @@ -55,39 +55,37 @@ # Create a breakpoint in main.cpp by name 'a', # there should be two locations. - breakpoint = target.BreakpointCreateByName('a', 'a.out') - self.assertTrue(breakpoint and - breakpoint.GetNumLocations() == 2, - VALID_BREAKPOINT) + breakpoint = target.BreakpointCreateByName("a", "a.out") + self.assertTrue( + breakpoint and breakpoint.GetNumLocations() == 2, VALID_BREAKPOINT + ) # Verify all breakpoint locations are enabled. location1 = breakpoint.GetLocationAtIndex(0) - self.assertTrue(location1 and - location1.IsEnabled(), - VALID_BREAKPOINT_LOCATION) + self.assertTrue(location1 and location1.IsEnabled(), VALID_BREAKPOINT_LOCATION) location2 = breakpoint.GetLocationAtIndex(1) - self.assertTrue(location2 and - location2.IsEnabled(), - VALID_BREAKPOINT_LOCATION) + self.assertTrue(location2 and location2.IsEnabled(), VALID_BREAKPOINT_LOCATION) # Launch the process, and do not stop at entry point. - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Verify 1st breakpoint location is hit. from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( - thread.IsValid(), - "There should be a thread stopped due to breakpoint") + thread.IsValid(), "There should be a thread stopped due to breakpoint" + ) frame0 = thread.GetFrameAtIndex(0) location1 = breakpoint.FindLocationByAddress(frame0.GetPC()) self.assertEqual( - frame0.GetLineEntry().GetLine(), self.a_int_body_line_no, - "Stopped in int a(int)") + frame0.GetLineEntry().GetLine(), + self.a_int_body_line_no, + "Stopped in int a(int)", + ) self.assertTrue(location1) self.assertEqual(location1.GetHitCount(), 1) self.assertEqual(breakpoint.GetHitCount(), 1) @@ -97,14 +95,16 @@ # Verify 2nd breakpoint location is hit. thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( - thread.IsValid(), - "There should be a thread stopped due to breakpoint") + thread.IsValid(), "There should be a thread stopped due to breakpoint" + ) frame0 = thread.GetFrameAtIndex(0) location2 = breakpoint.FindLocationByAddress(frame0.GetPC()) self.assertEqual( - frame0.GetLineEntry().GetLine(), self.a_float_body_line_no, - "Stopped in float a(float)") + frame0.GetLineEntry().GetLine(), + self.a_float_body_line_no, + "Stopped in float a(float)", + ) self.assertTrue(location2) self.assertEqual(location2.GetHitCount(), 1) self.assertEqual(location1.GetHitCount(), 1) @@ -115,8 +115,8 @@ # Verify 2nd breakpoint location is hit again. thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( - thread.IsValid(), - "There should be a thread stopped due to breakpoint") + thread.IsValid(), "There should be a thread stopped due to breakpoint" + ) self.assertEqual(location2.GetHitCount(), 2) self.assertEqual(location1.GetHitCount(), 1) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py b/lldb/test/API/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py @@ -3,53 +3,54 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class BreakpointIDTestCase(TestBase): - def test(self): self.build() exe = self.getBuildArtifact("a.out") - self.expect("file " + exe, - patterns=["Current executable set to .*a.out"]) + self.expect("file " + exe, patterns=["Current executable set to .*a.out"]) bpno = lldbutil.run_break_set_by_symbol( - self, 'product', num_expected_locations=-1, sym_exact=False) + self, "product", num_expected_locations=-1, sym_exact=False + ) self.assertEquals(bpno, 1, "First breakpoint number is 1.") bpno = lldbutil.run_break_set_by_symbol( - self, 'sum', num_expected_locations=-1, sym_exact=False) + self, "sum", num_expected_locations=-1, sym_exact=False + ) self.assertEquals(bpno, 2, "Second breakpoint number is 2.") bpno = lldbutil.run_break_set_by_symbol( - self, 'junk', num_expected_locations=0, sym_exact=False) + self, "junk", num_expected_locations=0, sym_exact=False + ) self.assertEquals(bpno, 3, "Third breakpoint number is 3.") self.expect( "breakpoint disable 1.1 - 2.2 ", COMMAND_FAILED_AS_EXPECTED, error=True, - startstr="error: Invalid range: Ranges that specify particular breakpoint locations must be within the same major breakpoint; you specified two different major breakpoints, 1 and 2.") + startstr="error: Invalid range: Ranges that specify particular breakpoint locations must be within the same major breakpoint; you specified two different major breakpoints, 1 and 2.", + ) self.expect( "breakpoint disable 2 - 2.2", COMMAND_FAILED_AS_EXPECTED, error=True, - startstr="error: Invalid breakpoint id range: Either both ends of range must specify a breakpoint location, or neither can specify a breakpoint location.") + startstr="error: Invalid breakpoint id range: Either both ends of range must specify a breakpoint location, or neither can specify a breakpoint location.", + ) self.expect( "breakpoint disable 2.1 - 2", COMMAND_FAILED_AS_EXPECTED, error=True, - startstr="error: Invalid breakpoint id range: Either both ends of range must specify a breakpoint location, or neither can specify a breakpoint location.") + startstr="error: Invalid breakpoint id range: Either both ends of range must specify a breakpoint location, or neither can specify a breakpoint location.", + ) - self.expect("breakpoint disable 2.1 - 2.2", - startstr="2 breakpoints disabled.") + self.expect("breakpoint disable 2.1 - 2.2", startstr="2 breakpoints disabled.") - self.expect("breakpoint enable 2.*", - patterns=[".* breakpoints enabled."]) + self.expect("breakpoint enable 2.*", patterns=[".* breakpoints enabled."]) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py b/lldb/test/API/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,45 +10,47 @@ class BreakpointIgnoreCountTestCase(TestBase): - - @skipIfWindows # This test will hang on windows llvm.org/pr21753 + @skipIfWindows # This test will hang on windows llvm.org/pr21753 def test_with_run_command(self): """Exercise breakpoint ignore count with 'breakpoint set -i '.""" self.build() self.breakpoint_ignore_count() - @add_test_categories(['pyapi']) - @skipIfWindows # This test will hang on windows llvm.org/pr21753 + @add_test_categories(["pyapi"]) + @skipIfWindows # This test will hang on windows llvm.org/pr21753 def test_with_python_api(self): """Use Python APIs to set breakpoint ignore count.""" self.build() self.breakpoint_ignore_count_python() - @skipIfWindows # This test will hang on windows llvm.org/pr21753 + @skipIfWindows # This test will hang on windows llvm.org/pr21753 def test_ignore_vrs_condition_bkpt(self): self.build() self.ignore_vrs_condition(False) - - @skipIfWindows # This test will hang on windows llvm.org/pr21753 + + @skipIfWindows # This test will hang on windows llvm.org/pr21753 def test_ignore_vrs_condition_loc(self): self.build() self.ignore_vrs_condition(True) - + def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to of function 'c'. self.stop_in_main = "Stop here at start of main" self.line1 = line_number( - 'main.c', '// Find the line number of function "c" here.') + "main.c", '// Find the line number of function "c" here.' + ) self.line2 = line_number( - 'main.c', '// b(2) -> c(2) Find the call site of b(2).') + "main.c", "// b(2) -> c(2) Find the call site of b(2)." + ) self.line3 = line_number( - 'main.c', '// a(3) -> c(3) Find the call site of c(3).') + "main.c", "// a(3) -> c(3) Find the call site of c(3)." + ) self.line4 = line_number( - 'main.c', '// a(3) -> c(3) Find the call site of a(3).') - self.line5 = line_number( - 'main.c', '// Find the call site of c in main.') + "main.c", "// a(3) -> c(3) Find the call site of a(3)." + ) + self.line5 = line_number("main.c", "// Find the call site of c in main.") def breakpoint_ignore_count(self): """Exercise breakpoint ignore count with 'breakpoint set -i '.""" @@ -59,71 +60,79 @@ # Create a breakpoint in main.c at line1. lldbutil.run_break_set_by_file_and_line( self, - 'main.c', + "main.c", self.line1, - extra_options='-i 1', + extra_options="-i 1", num_expected_locations=1, - loc_exact=True) + loc_exact=True, + ) # Now run the program. self.runCmd("run", RUN_SUCCEEDED) # The process should be stopped at this point. - self.expect("process status", PROCESS_STOPPED, - patterns=['Process .* stopped']) + self.expect("process status", PROCESS_STOPPED, patterns=["Process .* stopped"]) # Also check the hit count, which should be 2, due to ignore count of # 1. - lldbutil.check_breakpoint(self, bpno = 1, expected_hit_count = 2) + lldbutil.check_breakpoint(self, bpno=1, expected_hit_count=2) # The frame #0 should correspond to main.c:37, the executable statement # in function name 'c'. And frame #2 should point to main.c:45. - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT, - #substrs = ["stop reason = breakpoint"], - patterns=["frame #0.*main.c:%d" % self.line1, - "frame #2.*main.c:%d" % self.line2]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT, + # substrs = ["stop reason = breakpoint"], + patterns=[ + "frame #0.*main.c:%d" % self.line1, + "frame #2.*main.c:%d" % self.line2, + ], + ) # continue -i 1 is the same as setting the ignore count to 1 again, try that: # Now run the program. self.runCmd("process continue -i 1", RUN_SUCCEEDED) # The process should be stopped at this point. - self.expect("process status", PROCESS_STOPPED, - patterns=['Process .* stopped']) + self.expect("process status", PROCESS_STOPPED, patterns=["Process .* stopped"]) # Also check the hit count, which should be 2, due to ignore count of # 1. - lldbutil.check_breakpoint(self, bpno = 1, expected_hit_count = 4) + lldbutil.check_breakpoint(self, bpno=1, expected_hit_count=4) # The frame #0 should correspond to main.c:37, the executable statement # in function name 'c'. And frame #2 should point to main.c:45. - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT, - #substrs = ["stop reason = breakpoint"], - patterns=["frame #0.*main.c:%d" % self.line1, - "frame #1.*main.c:%d" % self.line5]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT, + # substrs = ["stop reason = breakpoint"], + patterns=[ + "frame #0.*main.c:%d" % self.line1, + "frame #1.*main.c:%d" % self.line5, + ], + ) def breakpoint_ignore_count_python(self): """Use Python APIs to set breakpoint ignore count.""" - target, process, thread, bkpt = lldbutil.run_to_source_breakpoint(self, - self.stop_in_main, - lldb.SBFileSpec("main.c")) + target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, self.stop_in_main, lldb.SBFileSpec("main.c") + ) # Now create a breakpoint on main.c by name 'c'. - breakpoint = target.BreakpointCreateByName('c', 'a.out') - self.assertTrue(breakpoint and - breakpoint.GetNumLocations() == 1, - VALID_BREAKPOINT) + breakpoint = target.BreakpointCreateByName("c", "a.out") + self.assertTrue( + breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT + ) # Get the breakpoint location from breakpoint after we verified that, # indeed, it has one location. location = breakpoint.GetLocationAtIndex(0) - self.assertTrue(location and - location.IsEnabled(), - VALID_BREAKPOINT_LOCATION) + self.assertTrue(location and location.IsEnabled(), VALID_BREAKPOINT_LOCATION) # Set the ignore count on the breakpoint location. location.SetIgnoreCount(2) - self.assertEqual(location.GetIgnoreCount(), 2, - "SetIgnoreCount() works correctly") + self.assertEqual( + location.GetIgnoreCount(), 2, "SetIgnoreCount() works correctly" + ) # Now continue and hit our breakpoint on c: process.Continue() @@ -132,30 +141,35 @@ # frame#2 should be on main.c:48. # lldbutil.print_stacktraces(process) from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( - thread.IsValid(), - "There should be a thread stopped due to breakpoint") + thread.IsValid(), "There should be a thread stopped due to breakpoint" + ) frame0 = thread.GetFrameAtIndex(0) frame1 = thread.GetFrameAtIndex(1) frame2 = thread.GetFrameAtIndex(2) - self.assertTrue(frame0.GetLineEntry().GetLine() == self.line1 and - frame1.GetLineEntry().GetLine() == self.line3 and - frame2.GetLineEntry().GetLine() == self.line4, - STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT) + self.assertTrue( + frame0.GetLineEntry().GetLine() == self.line1 + and frame1.GetLineEntry().GetLine() == self.line3 + and frame2.GetLineEntry().GetLine() == self.line4, + STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT, + ) # The hit count for the breakpoint should be 3. self.assertEqual(breakpoint.GetHitCount(), 3) def ignore_vrs_condition(self, use_location): main_spec = lldb.SBFileSpec("main.c") - target, process, _ , _ = lldbutil.run_to_source_breakpoint(self, - self.stop_in_main, - main_spec) - + target, process, _, _ = lldbutil.run_to_source_breakpoint( + self, self.stop_in_main, main_spec + ) + # Now make a breakpoint on the loop, and set a condition and ignore count. # Make sure that the condition fails don't count against the ignore count. - bkpt = target.BreakpointCreateBySourceRegex("Set a breakpoint here, with i", main_spec) + bkpt = target.BreakpointCreateBySourceRegex( + "Set a breakpoint here, with i", main_spec + ) self.assertEqual(bkpt.GetNumLocations(), 1, "Wrong number of locations") if use_location: diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_in_delayslot/TestAvoidBreakpointInDelaySlot.py b/lldb/test/API/functionalities/breakpoint/breakpoint_in_delayslot/TestAvoidBreakpointInDelaySlot.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_in_delayslot/TestAvoidBreakpointInDelaySlot.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_in_delayslot/TestAvoidBreakpointInDelaySlot.py @@ -10,29 +10,26 @@ class AvoidBreakpointInDelaySlotAPITestCase(TestBase): - - @skipIf(archs=no_match(re.compile('mips*'))) + @skipIf(archs=no_match(re.compile("mips*"))) def test(self): self.build() exe = self.getBuildArtifact("a.out") - self.expect("file " + exe, - patterns=["Current executable set to .*a.out.*"]) + self.expect("file " + exe, patterns=["Current executable set to .*a.out.*"]) # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - breakpoint = target.BreakpointCreateByName('main', 'a.out') - self.assertTrue(breakpoint and - breakpoint.GetNumLocations() == 1, - VALID_BREAKPOINT) + breakpoint = target.BreakpointCreateByName("main", "a.out") + self.assertTrue( + breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT + ) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - list = target.FindFunctions('foo', lldb.eFunctionNameTypeAuto) + list = target.FindFunctions("foo", lldb.eFunctionNameTypeAuto) self.assertEqual(list.GetSize(), 1) sc = list.GetContextAtIndex(0) self.assertEqual(sc.GetSymbol().GetName(), "foo") @@ -47,7 +44,7 @@ print(insts) i = 0 for inst in insts: - if (inst.HasDelaySlot()): + if inst.HasDelaySlot(): # Remember the address of branch instruction. branchinstaddress = inst.GetAddress().GetLoadAddress(target) @@ -59,9 +56,9 @@ breakpoint = target.BreakpointCreateByAddress(delayinstaddr) # Verify the breakpoint. - self.assertTrue(breakpoint and - breakpoint.GetNumLocations() == 1, - VALID_BREAKPOINT) + self.assertTrue( + breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT + ) # Get the location from breakpoint location = breakpoint.GetLocationAtIndex(0) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py b/lldb/test/API/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py @@ -4,14 +4,12 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class TestBreakpointLanguage(TestBase): - def check_location_file(self, bp, loc, test_name): bp_loc = bp.GetLocationAtIndex(loc) addr = bp_loc.GetAddress() @@ -35,30 +33,27 @@ "func_from", lldb.eLanguageTypeC_plus_plus, lldb.SBFileSpecList(), - lldb.SBFileSpecList()) - self.assertEqual( - cpp_bp.GetNumLocations(), 1, - "Only one C++ symbol matches") + lldb.SBFileSpecList(), + ) + self.assertEqual(cpp_bp.GetNumLocations(), 1, "Only one C++ symbol matches") self.assertTrue(self.check_location_file(cpp_bp, 0, "b.cpp")) c_bp = self.target.BreakpointCreateByRegex( "func_from", lldb.eLanguageTypeC, lldb.SBFileSpecList(), - lldb.SBFileSpecList()) - self.assertEqual( - c_bp.GetNumLocations(), 1, - "Only one C symbol matches") + lldb.SBFileSpecList(), + ) + self.assertEqual(c_bp.GetNumLocations(), 1, "Only one C symbol matches") self.assertTrue(self.check_location_file(c_bp, 0, "a.c")) objc_bp = self.target.BreakpointCreateByRegex( "func_from", lldb.eLanguageTypeObjC, lldb.SBFileSpecList(), - lldb.SBFileSpecList()) - self.assertEqual( - objc_bp.GetNumLocations(), 0, - "No ObjC symbol matches") + lldb.SBFileSpecList(), + ) + self.assertEqual(objc_bp.GetNumLocations(), 0, "No ObjC symbol matches") def test_by_name_breakpoint_language(self): """Test that the name regex breakpoint commands obey the language filter.""" @@ -77,10 +72,9 @@ lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeC_plus_plus, lldb.SBFileSpecList(), - lldb.SBFileSpecList()) - self.assertEqual( - cpp_bp.GetNumLocations(), 1, - "Only one C++ symbol matches") + lldb.SBFileSpecList(), + ) + self.assertEqual(cpp_bp.GetNumLocations(), 1, "Only one C++ symbol matches") self.assertTrue(self.check_location_file(cpp_bp, 0, "b.cpp")) no_cpp_bp = self.target.BreakpointCreateByName( @@ -88,20 +82,18 @@ lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeC_plus_plus, lldb.SBFileSpecList(), - lldb.SBFileSpecList()) - self.assertEqual( - no_cpp_bp.GetNumLocations(), 0, - "And the C one doesn't match") + lldb.SBFileSpecList(), + ) + self.assertEqual(no_cpp_bp.GetNumLocations(), 0, "And the C one doesn't match") c_bp = self.target.BreakpointCreateByName( "func_from_c", lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeC, lldb.SBFileSpecList(), - lldb.SBFileSpecList()) - self.assertEqual( - c_bp.GetNumLocations(), 1, - "Only one C symbol matches") + lldb.SBFileSpecList(), + ) + self.assertEqual(c_bp.GetNumLocations(), 1, "Only one C symbol matches") self.assertTrue(self.check_location_file(c_bp, 0, "a.c")) no_c_bp = self.target.BreakpointCreateByName( @@ -109,17 +101,15 @@ lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeC, lldb.SBFileSpecList(), - lldb.SBFileSpecList()) - self.assertEqual( - no_c_bp.GetNumLocations(), 0, - "And the C++ one doesn't match") + lldb.SBFileSpecList(), + ) + self.assertEqual(no_c_bp.GetNumLocations(), 0, "And the C++ one doesn't match") objc_bp = self.target.BreakpointCreateByName( "func_from_cpp", lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeObjC, lldb.SBFileSpecList(), - lldb.SBFileSpecList()) - self.assertEqual( - objc_bp.GetNumLocations(), 0, - "No ObjC symbol matches") + lldb.SBFileSpecList(), + ) + self.assertEqual(objc_bp.GetNumLocations(), 0, "No ObjC symbol matches") diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py b/lldb/test/API/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class BreakpointLocationsTestCase(TestBase): - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24528") def test_enable(self): """Test breakpoint enable/disable for a breakpoint ID with multiple locations.""" @@ -32,12 +30,12 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.line = line_number('main.c', '// Set break point at this line.') + self.line = line_number("main.c", "// Set break point at this line.") - def set_breakpoint (self): + def set_breakpoint(self): exe = self.getBuildArtifact("a.out") target = self.dbg.CreateTarget(exe) - self.assertTrue(target, "Target %s is not valid"%(exe)) + self.assertTrue(target, "Target %s is not valid" % (exe)) # This should create a breakpoint with 3 locations. @@ -50,11 +48,14 @@ "breakpoint list -f", "Breakpoint locations shown correctly", substrs=[ - "1: file = 'main.c', line = %d, exact_match = 0, locations = 3" % - self.line], + "1: file = 'main.c', line = %d, exact_match = 0, locations = 3" + % self.line + ], patterns=[ "where = a.out`func_inlined .+unresolved, hit count = 0", - "where = a.out`main .+\[inlined\].+unresolved, hit count = 0"]) + "where = a.out`main .+\[inlined\].+unresolved, hit count = 0", + ], + ) return bkpt @@ -68,61 +69,111 @@ bkpt = self.set_breakpoint() bkpt_cond = "1 == 0" bkpt.SetCondition(bkpt_cond) - self.assertEqual(bkpt.GetCondition(), bkpt_cond,"Successfully set condition") - self.assertEquals(bkpt.location[0].GetCondition(), bkpt.GetCondition(), "Conditions are the same") + self.assertEqual(bkpt.GetCondition(), bkpt_cond, "Successfully set condition") + self.assertEquals( + bkpt.location[0].GetCondition(), + bkpt.GetCondition(), + "Conditions are the same", + ) # Now set a condition on the locations, make sure that this doesn't effect the bkpt: bkpt_loc_1_cond = "1 == 1" bkpt.location[0].SetCondition(bkpt_loc_1_cond) - self.assertEqual(bkpt.location[0].GetCondition(), bkpt_loc_1_cond, "Successfully changed location condition") - self.assertNotEqual(bkpt.GetCondition(), bkpt_loc_1_cond, "Changed location changed Breakpoint condition") - self.assertEqual(bkpt.location[1].GetCondition(), bkpt_cond, "Changed another location's condition") + self.assertEqual( + bkpt.location[0].GetCondition(), + bkpt_loc_1_cond, + "Successfully changed location condition", + ) + self.assertNotEqual( + bkpt.GetCondition(), + bkpt_loc_1_cond, + "Changed location changed Breakpoint condition", + ) + self.assertEqual( + bkpt.location[1].GetCondition(), + bkpt_cond, + "Changed another location's condition", + ) # Now make sure that setting one options doesn't fix the value of another: bkpt.SetIgnoreCount(10) self.assertEqual(bkpt.GetIgnoreCount(), 10, "Set the ignore count successfully") - self.assertEqual(bkpt.location[0].GetIgnoreCount(), 10, "Location doesn't track top-level bkpt.") + self.assertEqual( + bkpt.location[0].GetIgnoreCount(), + 10, + "Location doesn't track top-level bkpt.", + ) # Now make sure resetting the condition to "" resets the tracking: bkpt.location[0].SetCondition("") bkpt_new_cond = "1 == 3" bkpt.SetCondition(bkpt_new_cond) - self.assertEqual(bkpt.location[0].GetCondition(), bkpt_new_cond, "Didn't go back to tracking condition") + self.assertEqual( + bkpt.location[0].GetCondition(), + bkpt_new_cond, + "Didn't go back to tracking condition", + ) # Test that set/get accessor methods on BreakpointLocation behave correctly. bkpt_loc = bkpt.GetLocationAtIndex(0) value = "MyQueue" bkpt_loc.SetQueueName(value) - self.assertEqual(bkpt_loc.GetQueueName(), value,"Successfully set/get bp location QueueName") + self.assertEqual( + bkpt_loc.GetQueueName(), value, "Successfully set/get bp location QueueName" + ) value = 5 bkpt_loc.SetThreadID(value) - self.assertEqual(bkpt_loc.GetThreadID(), value,"Successfully set/get bp location ThreadID") + self.assertEqual( + bkpt_loc.GetThreadID(), value, "Successfully set/get bp location ThreadID" + ) value = "1 == 0" bkpt_loc.SetCondition(value) - self.assertEqual(bkpt_loc.GetCondition(), value,"Successfully set/get bp location Condition") + self.assertEqual( + bkpt_loc.GetCondition(), value, "Successfully set/get bp location Condition" + ) value = 6 bkpt_loc.SetThreadIndex(value) - self.assertEqual(bkpt_loc.GetThreadIndex(), value,"Successfully set/get bp location ThreadIndex") + self.assertEqual( + bkpt_loc.GetThreadIndex(), + value, + "Successfully set/get bp location ThreadIndex", + ) value = "MyThread" bkpt_loc.SetThreadName(value) - self.assertEqual(bkpt_loc.GetThreadName(), value,"Successfully set/get bp location ThreadName") + self.assertEqual( + bkpt_loc.GetThreadName(), + value, + "Successfully set/get bp location ThreadName", + ) value = 5 bkpt_loc.SetIgnoreCount(value) - self.assertEqual(bkpt_loc.GetIgnoreCount(), value,"Successfully set/get bp location IgnoreCount") + self.assertEqual( + bkpt_loc.GetIgnoreCount(), + value, + "Successfully set/get bp location IgnoreCount", + ) - for value in [True,False]: + for value in [True, False]: bkpt_loc.SetAutoContinue(value) - self.assertEqual(bkpt_loc.GetAutoContinue(), value,"Successfully set/get bp location AutoContinue") + self.assertEqual( + bkpt_loc.GetAutoContinue(), + value, + "Successfully set/get bp location AutoContinue", + ) - for value in [True,False]: + for value in [True, False]: bkpt_loc.SetEnabled(value) - self.assertEqual(bkpt_loc.IsEnabled(), value,"Successfully set/get bp location SetEnabled") + self.assertEqual( + bkpt_loc.IsEnabled(), + value, + "Successfully set/get bp location SetEnabled", + ) # test set/get CommandLineCommands set_cmds = lldb.SBStringList() @@ -132,9 +183,15 @@ get_cmds = lldb.SBStringList() bkpt_loc.GetCommandLineCommands(get_cmds) - self.assertEqual(set_cmds.GetSize(), get_cmds.GetSize(), "Size of command line commands") - for idx, _ in enumerate(set_cmds): - self.assertEqual(set_cmds.GetStringAtIndex(idx), get_cmds.GetStringAtIndex(idx), "Command %d"%(idx)) + self.assertEqual( + set_cmds.GetSize(), get_cmds.GetSize(), "Size of command line commands" + ) + for idx, _ in enumerate(set_cmds): + self.assertEqual( + set_cmds.GetStringAtIndex(idx), + get_cmds.GetStringAtIndex(idx), + "Command %d" % (idx), + ) def shadowed_bkpt_command_test(self): """Test that options set on the breakpoint and location behave correctly.""" @@ -152,9 +209,15 @@ cmd_list = lldb.SBStringList() bkpt.GetCommandLineCommands(cmd_list) list_size = str_list.GetSize() - self.assertEqual(cmd_list.GetSize() , list_size, "Added the right number of commands") - for i in range(0,list_size): - self.assertEqual(str_list.GetStringAtIndex(i), cmd_list.GetStringAtIndex(i), "Mismatched commands.") + self.assertEqual( + cmd_list.GetSize(), list_size, "Added the right number of commands" + ) + for i in range(0, list_size): + self.assertEqual( + str_list.GetStringAtIndex(i), + cmd_list.GetStringAtIndex(i), + "Mismatched commands.", + ) commands = ["DDDDDD", "EEEEEE", "FFFFFF", "GGGGGG"] loc_list = lldb.SBStringList() @@ -166,73 +229,125 @@ loc_list_size = loc_list.GetSize() # Check that the location has the right commands: - self.assertEqual(loc_cmd_list.GetSize() , loc_list_size, "Added the right number of commands to location") - for i in range(0,loc_list_size): - self.assertEqual(loc_list.GetStringAtIndex(i), loc_cmd_list.GetStringAtIndex(i), "Mismatched commands.") + self.assertEqual( + loc_cmd_list.GetSize(), + loc_list_size, + "Added the right number of commands to location", + ) + for i in range(0, loc_list_size): + self.assertEqual( + loc_list.GetStringAtIndex(i), + loc_cmd_list.GetStringAtIndex(i), + "Mismatched commands.", + ) # Check that we didn't mess up the breakpoint level commands: - self.assertEqual(cmd_list.GetSize() , list_size, "Added the right number of commands") - for i in range(0,list_size): - self.assertEqual(str_list.GetStringAtIndex(i), cmd_list.GetStringAtIndex(i), "Mismatched commands.") + self.assertEqual( + cmd_list.GetSize(), list_size, "Added the right number of commands" + ) + for i in range(0, list_size): + self.assertEqual( + str_list.GetStringAtIndex(i), + cmd_list.GetStringAtIndex(i), + "Mismatched commands.", + ) # And check we didn't mess up another location: untouched_loc_cmds = lldb.SBStringList() bkpt.location[0].GetCommandLineCommands(untouched_loc_cmds) - self.assertEqual(untouched_loc_cmds.GetSize() , 0, "Changed the wrong location") + self.assertEqual(untouched_loc_cmds.GetSize(), 0, "Changed the wrong location") def breakpoint_locations_test(self): """Test breakpoint enable/disable for a breakpoint ID with multiple locations.""" self.set_breakpoint() # The 'breakpoint disable 3.*' command should fail gracefully. - self.expect("breakpoint disable 3.*", - "Disabling an invalid breakpoint should fail gracefully", - error=True, - startstr="error: '3' is not a valid breakpoint ID.") + self.expect( + "breakpoint disable 3.*", + "Disabling an invalid breakpoint should fail gracefully", + error=True, + startstr="error: '3' is not a valid breakpoint ID.", + ) # The 'breakpoint disable 1.*' command should disable all 3 locations. self.expect( "breakpoint disable 1.*", "All 3 breakpoint locatons disabled correctly", - startstr="3 breakpoints disabled.") + startstr="3 breakpoints disabled.", + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should not stopped on any breakpoint at all. - self.expect("process status", "No stopping on any disabled breakpoint", - patterns=["^Process [0-9]+ exited with status = 0"]) + self.expect( + "process status", + "No stopping on any disabled breakpoint", + patterns=["^Process [0-9]+ exited with status = 0"], + ) # The 'breakpoint enable 1.*' command should enable all 3 breakpoints. self.expect( "breakpoint enable 1.*", "All 3 breakpoint locatons enabled correctly", - startstr="3 breakpoints enabled.") + startstr="3 breakpoints enabled.", + ) # The 'breakpoint disable 1.1' command should disable 1 location. self.expect( "breakpoint disable 1.1", "1 breakpoint locatons disabled correctly", - startstr="1 breakpoints disabled.") + startstr="1 breakpoints disabled.", + ) # Run the program again. We should stop on the two breakpoint # locations. self.runCmd("run", RUN_SUCCEEDED) # Stopped once. - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=["stop reason = breakpoint 1."]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."], + ) # Continue the program, there should be another stop. self.runCmd("process continue") # Stopped again. - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=["stop reason = breakpoint 1."]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."], + ) # At this point, 1.1 has a hit count of 0 and the other a hit count of # 1". - lldbutil.check_breakpoint(self, bpno = 1, expected_locations = 3, expected_resolved_count = 2, expected_hit_count = 2) - lldbutil.check_breakpoint(self, bpno = 1, location_id = 1, expected_location_resolved = False, expected_location_hit_count = 0) - lldbutil.check_breakpoint(self, bpno = 1, location_id = 2, expected_location_resolved = True, expected_location_hit_count = 1) - lldbutil.check_breakpoint(self, bpno = 1, location_id = 3, expected_location_resolved = True, expected_location_hit_count = 1) + lldbutil.check_breakpoint( + self, + bpno=1, + expected_locations=3, + expected_resolved_count=2, + expected_hit_count=2, + ) + lldbutil.check_breakpoint( + self, + bpno=1, + location_id=1, + expected_location_resolved=False, + expected_location_hit_count=0, + ) + lldbutil.check_breakpoint( + self, + bpno=1, + location_id=2, + expected_location_resolved=True, + expected_location_hit_count=1, + ) + lldbutil.check_breakpoint( + self, + bpno=1, + location_id=3, + expected_location_resolved=True, + expected_location_hit_count=1, + ) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_names/TestBreakpointNames.py b/lldb/test/API/functionalities/breakpoint/breakpoint_names/TestBreakpointNames.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_names/TestBreakpointNames.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_names/TestBreakpointNames.py @@ -3,7 +3,6 @@ """ - import os import lldb from lldbsuite.test.decorators import * @@ -14,7 +13,7 @@ class BreakpointNames(TestBase): NO_DEBUG_INFO_TESTCASE = True - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) def test_setting_names(self): """Use Python APIs to test that we can set breakpoint names.""" self.build() @@ -58,7 +57,9 @@ # Create a targets we are making breakpoint in and copying to: self.target = self.dbg.CreateTarget(exe) self.assertTrue(self.target, VALID_TARGET) - self.main_file_spec = lldb.SBFileSpec(os.path.join(self.getSourceDir(), "main.c")) + self.main_file_spec = lldb.SBFileSpec( + os.path.join(self.getSourceDir(), "main.c") + ) def check_name_in_target(self, bkpt_name): name_list = lldb.SBStringList() @@ -68,7 +69,9 @@ if name == bkpt_name: found_it = True break - self.assertTrue(found_it, "Didn't find the name %s in the target's name list:"%(bkpt_name)) + self.assertTrue( + found_it, "Didn't find the name %s in the target's name list:" % (bkpt_name) + ) def setUp(self): # Call super's setUp(). @@ -80,7 +83,7 @@ self.ignore_count = 1000 self.condition = "1 == 2" self.auto_continue = True - self.tid = 0xaaaa + self.tid = 0xAAAA self.tidx = 10 self.thread_name = "Fooey" self.queue_name = "Blooey" @@ -89,7 +92,6 @@ self.cmd_list.AppendString("bt") self.help_string = "I do something interesting" - def do_check_names(self): """Use Python APIs to check that we can set & retrieve breakpoint names""" bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) @@ -114,40 +116,60 @@ bkpt.AddNameWithErrorHandling(other_bkpt_name) matches = bkpt.MatchesName(bkpt_name) - self.assertTrue(matches, "Adding a name means we didn't match the name we just set") + self.assertTrue( + matches, "Adding a name means we didn't match the name we just set" + ) self.check_name_in_target(other_bkpt_name) # Remove the name and make sure we no longer match it: bkpt.RemoveName(bkpt_name) matches = bkpt.MatchesName(bkpt_name) - self.assertTrue(not matches,"We still match a name after removing it.") + self.assertTrue(not matches, "We still match a name after removing it.") # Make sure the name list has the remaining name: name_list = lldb.SBStringList() bkpt.GetNames(name_list) num_names = name_list.GetSize() - self.assertEquals(num_names, 1, "Name list has %d items, expected 1."%(num_names)) + self.assertEquals( + num_names, 1, "Name list has %d items, expected 1." % (num_names) + ) name = name_list.GetStringAtIndex(0) - self.assertEquals(name, other_bkpt_name, "Remaining name was: %s expected %s."%(name, other_bkpt_name)) + self.assertEquals( + name, + other_bkpt_name, + "Remaining name was: %s expected %s." % (name, other_bkpt_name), + ) def do_check_illegal_names(self): """Use Python APIs to check that we reject illegal names.""" bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) - bad_names = ["-CantStartWithADash", - "1CantStartWithANumber", - "^CantStartWithNonAlpha", - "CantHave-ADash", - "Cant Have Spaces"] + bad_names = [ + "-CantStartWithADash", + "1CantStartWithANumber", + "^CantStartWithNonAlpha", + "CantHave-ADash", + "Cant Have Spaces", + ] for bad_name in bad_names: success = bkpt.AddNameWithErrorHandling(bad_name) - self.assertTrue(success.Fail(), "We allowed an illegal name: %s"%(bad_name)) + self.assertTrue( + success.Fail(), "We allowed an illegal name: %s" % (bad_name) + ) bp_name = lldb.SBBreakpointName(self.target, bad_name) - self.assertFalse(bp_name.IsValid(), "We made a breakpoint name with an illegal name: %s"%(bad_name)); - - retval =lldb.SBCommandReturnObject() - self.dbg.GetCommandInterpreter().HandleCommand("break set -n whatever -N '%s'"%(bad_name), retval) - self.assertTrue(not retval.Succeeded(), "break set succeeded with: illegal name: %s"%(bad_name)) + self.assertFalse( + bp_name.IsValid(), + "We made a breakpoint name with an illegal name: %s" % (bad_name), + ) + + retval = lldb.SBCommandReturnObject() + self.dbg.GetCommandInterpreter().HandleCommand( + "break set -n whatever -N '%s'" % (bad_name), retval + ) + self.assertTrue( + not retval.Succeeded(), + "break set succeeded with: illegal name: %s" % (bad_name), + ) def do_check_using_names(self): """Use Python APIs to check names work in place of breakpoint ID's.""" @@ -159,7 +181,7 @@ bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) bkpt_name = "ABreakpoint" bkpt_id = bkpt.GetID() - other_bkpt_name= "_AnotherBreakpoint" + other_bkpt_name = "_AnotherBreakpoint" # Add a name and make sure we match it: success = bkpt.AddNameWithErrorHandling(bkpt_name) @@ -170,33 +192,51 @@ self.assertEquals(bkpts.GetSize(), 1, "One breakpoint matched.") found_bkpt = bkpts.GetBreakpointAtIndex(0) - self.assertEquals(bkpt.GetID(), found_bkpt.GetID(),"The right breakpoint.") - self.assertEquals(bkpt.GetID(), bkpt_id,"With the same ID as before.") + self.assertEquals(bkpt.GetID(), found_bkpt.GetID(), "The right breakpoint.") + self.assertEquals(bkpt.GetID(), bkpt_id, "With the same ID as before.") retval = lldb.SBCommandReturnObject() - self.dbg.GetCommandInterpreter().HandleCommand("break disable %s"%(bkpt_name), retval) - self.assertTrue(retval.Succeeded(), "break disable failed with: %s."%(retval.GetError())) + self.dbg.GetCommandInterpreter().HandleCommand( + "break disable %s" % (bkpt_name), retval + ) + self.assertTrue( + retval.Succeeded(), "break disable failed with: %s." % (retval.GetError()) + ) self.assertTrue(not bkpt.IsEnabled(), "We didn't disable the breakpoint.") # Also make sure we don't apply commands to non-matching names: - self.dbg.GetCommandInterpreter().HandleCommand("break modify --one-shot 1 %s"%(other_bkpt_name), retval) - self.assertTrue(retval.Succeeded(), "break modify failed with: %s."%(retval.GetError())) - self.assertTrue(not bkpt.IsOneShot(), "We applied one-shot to the wrong breakpoint.") + self.dbg.GetCommandInterpreter().HandleCommand( + "break modify --one-shot 1 %s" % (other_bkpt_name), retval + ) + self.assertTrue( + retval.Succeeded(), "break modify failed with: %s." % (retval.GetError()) + ) + self.assertTrue( + not bkpt.IsOneShot(), "We applied one-shot to the wrong breakpoint." + ) def check_option_values(self, bp_object): self.assertEqual(bp_object.IsOneShot(), self.is_one_shot, "IsOneShot") self.assertEqual(bp_object.GetIgnoreCount(), self.ignore_count, "IgnoreCount") self.assertEqual(bp_object.GetCondition(), self.condition, "Condition") - self.assertEqual(bp_object.GetAutoContinue(), self.auto_continue, "AutoContinue") + self.assertEqual( + bp_object.GetAutoContinue(), self.auto_continue, "AutoContinue" + ) self.assertEqual(bp_object.GetThreadID(), self.tid, "Thread ID") self.assertEqual(bp_object.GetThreadIndex(), self.tidx, "Thread Index") self.assertEqual(bp_object.GetThreadName(), self.thread_name, "Thread Name") self.assertEqual(bp_object.GetQueueName(), self.queue_name, "Queue Name") set_cmds = lldb.SBStringList() bp_object.GetCommandLineCommands(set_cmds) - self.assertEqual(set_cmds.GetSize(), self.cmd_list.GetSize(), "Size of command line commands") + self.assertEqual( + set_cmds.GetSize(), self.cmd_list.GetSize(), "Size of command line commands" + ) for idx in range(0, set_cmds.GetSize()): - self.assertEqual(self.cmd_list.GetStringAtIndex(idx), set_cmds.GetStringAtIndex(idx), "Command %d"%(idx)) + self.assertEqual( + self.cmd_list.GetStringAtIndex(idx), + set_cmds.GetStringAtIndex(idx), + "Command %d" % (idx), + ) def make_a_dummy_name(self): "This makes a breakpoint name in the dummy target to make sure it gets copied over" @@ -204,7 +244,7 @@ dummy_target = self.dbg.GetDummyTarget() self.assertTrue(dummy_target.IsValid(), "Dummy target was not valid.") - def cleanup (): + def cleanup(): self.dbg.GetDummyTarget().DeleteBreakpointName(self.bp_name_string) # Execute the cleanup function during test case tear down. @@ -213,7 +253,11 @@ # Now find it in the dummy target, and make sure these settings took: bp_name = lldb.SBBreakpointName(dummy_target, self.bp_name_string) # Make sure the name is right: - self.assertEqual(bp_name.GetName(), self.bp_name_string, "Wrong bp_name: %s"%(bp_name.GetName())) + self.assertEqual( + bp_name.GetName(), + self.bp_name_string, + "Wrong bp_name: %s" % (bp_name.GetName()), + ) bp_name.SetOneShot(self.is_one_shot) bp_name.SetIgnoreCount(self.ignore_count) bp_name.SetCondition(self.condition) @@ -247,36 +291,53 @@ # Now make a name from this breakpoint, and make sure the new name is properly configured: new_name = lldb.SBBreakpointName(bkpt, other_bp_name_string) - self.assertTrue(new_name.IsValid(), "Couldn't make a valid bp_name from a breakpoint.") + self.assertTrue( + new_name.IsValid(), "Couldn't make a valid bp_name from a breakpoint." + ) self.check_option_values(bkpt) # Now change the name's option and make sure it gets propagated to # the breakpoint: new_auto_continue = not self.auto_continue bp_name.SetAutoContinue(new_auto_continue) - self.assertEqual(bp_name.GetAutoContinue(), new_auto_continue, "Couldn't change auto-continue on the name") - self.assertEqual(bkpt.GetAutoContinue(), new_auto_continue, "Option didn't propagate to the breakpoint.") + self.assertEqual( + bp_name.GetAutoContinue(), + new_auto_continue, + "Couldn't change auto-continue on the name", + ) + self.assertEqual( + bkpt.GetAutoContinue(), + new_auto_continue, + "Option didn't propagate to the breakpoint.", + ) # Now make this same breakpoint name - but from the command line - cmd_str = "breakpoint name configure %s -o %d -i %d -c '%s' -G %d -t %d -x %d -T '%s' -q '%s' -H '%s'"%(cl_bp_name_string, - self.is_one_shot, - self.ignore_count, - self.condition, - self.auto_continue, - self.tid, - self.tidx, - self.thread_name, - self.queue_name, - self.help_string) + cmd_str = ( + "breakpoint name configure %s -o %d -i %d -c '%s' -G %d -t %d -x %d -T '%s' -q '%s' -H '%s'" + % ( + cl_bp_name_string, + self.is_one_shot, + self.ignore_count, + self.condition, + self.auto_continue, + self.tid, + self.tidx, + self.thread_name, + self.queue_name, + self.help_string, + ) + ) for cmd in self.cmd_list: - cmd_str += " -C '%s'"%(cmd) + cmd_str += " -C '%s'" % (cmd) self.runCmd(cmd_str, check=True) # Now look up this name again and check its options: cl_name = lldb.SBBreakpointName(self.target, cl_bp_name_string) self.check_option_values(cl_name) # Also check the help string: - self.assertEqual(self.help_string, cl_name.GetHelpString(), "Help string didn't match") + self.assertEqual( + self.help_string, cl_name.GetHelpString(), "Help string didn't match" + ) # Change the name and make sure that works: new_help = "I do something even more interesting" cl_name.SetHelpString(new_help) @@ -285,17 +346,30 @@ # We should have three names now, make sure the target can list them: name_list = lldb.SBStringList() self.target.GetBreakpointNames(name_list) - for name_string in [self.bp_name_string, other_bp_name_string, cl_bp_name_string]: - self.assertIn(name_string, name_list, "Didn't find %s in names"%(name_string)) + for name_string in [ + self.bp_name_string, + other_bp_name_string, + cl_bp_name_string, + ]: + self.assertIn( + name_string, name_list, "Didn't find %s in names" % (name_string) + ) # Delete the name from the current target. Make sure that works and deletes the # name from the breakpoint as well: self.target.DeleteBreakpointName(self.bp_name_string) name_list.Clear() self.target.GetBreakpointNames(name_list) - self.assertNotIn(self.bp_name_string, name_list, "Didn't delete %s from a real target"%(self.bp_name_string)) + self.assertNotIn( + self.bp_name_string, + name_list, + "Didn't delete %s from a real target" % (self.bp_name_string), + ) # Also make sure the name got removed from breakpoints holding it: - self.assertFalse(bkpt.MatchesName(self.bp_name_string), "Didn't remove the name from the breakpoint.") + self.assertFalse( + bkpt.MatchesName(self.bp_name_string), + "Didn't remove the name from the breakpoint.", + ) # Test that deleting the name we injected into the dummy target works (there's also a # cleanup that will do this, but that won't test the result... @@ -303,56 +377,93 @@ dummy_target.DeleteBreakpointName(self.bp_name_string) name_list.Clear() dummy_target.GetBreakpointNames(name_list) - self.assertNotIn(self.bp_name_string, name_list, "Didn't delete %s from the dummy target"%(self.bp_name_string)) + self.assertNotIn( + self.bp_name_string, + name_list, + "Didn't delete %s from the dummy target" % (self.bp_name_string), + ) # Also make sure the name got removed from breakpoints holding it: - self.assertFalse(bkpt.MatchesName(self.bp_name_string), "Didn't remove the name from the breakpoint.") + self.assertFalse( + bkpt.MatchesName(self.bp_name_string), + "Didn't remove the name from the breakpoint.", + ) def check_permission_results(self, bp_name): self.assertEqual(bp_name.GetAllowDelete(), False, "Didn't set allow delete.") protected_bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) protected_id = protected_bkpt.GetID() - unprotected_bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) + unprotected_bkpt = self.target.BreakpointCreateByLocation( + self.main_file_spec, 10 + ) unprotected_id = unprotected_bkpt.GetID() success = protected_bkpt.AddNameWithErrorHandling(self.bp_name_string) self.assertSuccess(success, "Couldn't add this name to the breakpoint") self.target.DisableAllBreakpoints() - self.assertEqual(protected_bkpt.IsEnabled(), True, "Didnt' keep breakpoint from being disabled") - self.assertEqual(unprotected_bkpt.IsEnabled(), False, "Protected too many breakpoints from disabling.") + self.assertEqual( + protected_bkpt.IsEnabled(), + True, + "Didnt' keep breakpoint from being disabled", + ) + self.assertEqual( + unprotected_bkpt.IsEnabled(), + False, + "Protected too many breakpoints from disabling.", + ) # Try from the command line too: unprotected_bkpt.SetEnabled(True) result = lldb.SBCommandReturnObject() self.dbg.GetCommandInterpreter().HandleCommand("break disable", result) self.assertTrue(result.Succeeded()) - self.assertEqual(protected_bkpt.IsEnabled(), True, "Didnt' keep breakpoint from being disabled") - self.assertEqual(unprotected_bkpt.IsEnabled(), False, "Protected too many breakpoints from disabling.") + self.assertEqual( + protected_bkpt.IsEnabled(), + True, + "Didnt' keep breakpoint from being disabled", + ) + self.assertEqual( + unprotected_bkpt.IsEnabled(), + False, + "Protected too many breakpoints from disabling.", + ) self.target.DeleteAllBreakpoints() bkpt = self.target.FindBreakpointByID(protected_id) - self.assertTrue(bkpt.IsValid(), "Didn't keep the breakpoint from being deleted.") + self.assertTrue( + bkpt.IsValid(), "Didn't keep the breakpoint from being deleted." + ) bkpt = self.target.FindBreakpointByID(unprotected_id) - self.assertFalse(bkpt.IsValid(), "Protected too many breakpoints from deletion.") + self.assertFalse( + bkpt.IsValid(), "Protected too many breakpoints from deletion." + ) # Remake the unprotected breakpoint and try again from the command line: - unprotected_bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) + unprotected_bkpt = self.target.BreakpointCreateByLocation( + self.main_file_spec, 10 + ) unprotected_id = unprotected_bkpt.GetID() self.dbg.GetCommandInterpreter().HandleCommand("break delete -f", result) self.assertTrue(result.Succeeded()) bkpt = self.target.FindBreakpointByID(protected_id) - self.assertTrue(bkpt.IsValid(), "Didn't keep the breakpoint from being deleted.") + self.assertTrue( + bkpt.IsValid(), "Didn't keep the breakpoint from being deleted." + ) bkpt = self.target.FindBreakpointByID(unprotected_id) - self.assertFalse(bkpt.IsValid(), "Protected too many breakpoints from deletion.") + self.assertFalse( + bkpt.IsValid(), "Protected too many breakpoints from deletion." + ) def do_check_configuring_permissions_sb(self): bp_name = lldb.SBBreakpointName(self.target, self.bp_name_string) # Make a breakpoint name with delete disallowed: bp_name = lldb.SBBreakpointName(self.target, self.bp_name_string) - self.assertTrue(bp_name.IsValid(), "Failed to make breakpoint name for valid name.") + self.assertTrue( + bp_name.IsValid(), "Failed to make breakpoint name for valid name." + ) bp_name.SetAllowDelete(False) bp_name.SetAllowDisable(False) @@ -361,8 +472,13 @@ def do_check_configuring_permissions_cli(self): # Make the name with the right options using the command line: - self.runCmd("breakpoint name configure -L 0 -D 0 -A 0 %s"%(self.bp_name_string), check=True) + self.runCmd( + "breakpoint name configure -L 0 -D 0 -A 0 %s" % (self.bp_name_string), + check=True, + ) # Now look up the breakpoint we made, and check that it works. bp_name = lldb.SBBreakpointName(self.target, self.bp_name_string) - self.assertTrue(bp_name.IsValid(), "Didn't make a breakpoint name we could find.") + self.assertTrue( + bp_name.IsValid(), "Didn't make a breakpoint name we could find." + ) self.check_permission_results(bp_name) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_on_lambda_capture/TestBreakOnLambdaCapture.py b/lldb/test/API/functionalities/breakpoint/breakpoint_on_lambda_capture/TestBreakOnLambdaCapture.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_on_lambda_capture/TestBreakOnLambdaCapture.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_on_lambda_capture/TestBreakOnLambdaCapture.py @@ -11,15 +11,15 @@ class TestBreakOnLambdaCapture(TestBase): - NO_DEBUG_INFO_TESTCASE = True def test_break_on_lambda_capture(self): self.build() self.main_source_file = lldb.SBFileSpec("main.cpp") - (target, process, main_thread, _) = lldbutil.run_to_source_breakpoint(self, - "First break", self.main_source_file) + (target, process, main_thread, _) = lldbutil.run_to_source_breakpoint( + self, "First break", self.main_source_file + ) # FIXME: This is working around a separate bug. If you hit a breakpoint and # run an expression and it is the first expression you've ever run, on @@ -31,8 +31,9 @@ self.assertSuccess(val_obj.GetError(), "Ran our expression successfully") self.assertEqual(val_obj.value, "true", "Value was true.") - bkpt = target.BreakpointCreateBySourceRegex("Break here in the helper", - self.main_source_file); + bkpt = target.BreakpointCreateBySourceRegex( + "Break here in the helper", self.main_source_file + ) bkpt.SetCondition("enable && usec == 1") process.Continue() @@ -49,6 +50,8 @@ process.Continue() for thread in process.threads: if thread.id == main_thread.id: - self.assertStopReason(thread.stop_reason, lldb.eStopReasonBreakpoint) + self.assertStopReason( + thread.stop_reason, lldb.eStopReasonBreakpoint + ) else: self.assertStopReason(thread.stop_reason, lldb.eStopReasonNone) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_on_overload/TestBreakOnOverload.py b/lldb/test/API/functionalities/breakpoint/breakpoint_on_overload/TestBreakOnOverload.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_on_overload/TestBreakOnOverload.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_on_overload/TestBreakOnOverload.py @@ -10,7 +10,6 @@ class TestBreakpointOnOverload(TestBase): - def check_breakpoint(self, name): bkpt = self.target.BreakpointCreateByName(name) self.assertEqual(bkpt.num_locations, 1, "Got one location") @@ -22,7 +21,7 @@ # So just look for the name we used for the breakpoint in the # function name, rather than doing an equality check. self.assertIn(name, addr.function.name, "Got the right name") - + def test_break_on_overload(self): self.build() self.target = lldbutil.run_to_breakpoint_make_target(self) @@ -30,6 +29,3 @@ self.check_breakpoint("a_function(double)") self.check_breakpoint("a_function(int, double)") self.check_breakpoint("a_function(double, int)") - - - diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py b/lldb/test/API/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py @@ -3,14 +3,12 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class BreakpointOptionsTestCase(TestBase): - def test(self): """Test breakpoint command for different options.""" self.build() @@ -20,7 +18,7 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def breakpoint_options_test(self): """Test breakpoint command for different options.""" @@ -29,48 +27,53 @@ # This should create a breakpoint with 1 locations. lldbutil.run_break_set_by_file_and_line( - self, - "main.cpp", - self.line, - extra_options="-K 1", - num_expected_locations=1) + self, "main.cpp", self.line, extra_options="-K 1", num_expected_locations=1 + ) lldbutil.run_break_set_by_file_and_line( - self, - "main.cpp", - self.line, - extra_options="-K 0", - num_expected_locations=1) + self, "main.cpp", self.line, extra_options="-K 0", num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # Stopped once. - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=["stop reason = breakpoint 2."]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 2."], + ) # Check the list of breakpoint. self.expect( "breakpoint list -f", "Breakpoint locations shown correctly", substrs=[ - "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % - self.line, - "2: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % - self.line]) + "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" + % self.line, + "2: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" + % self.line, + ], + ) # Continue the program, there should be another stop. self.runCmd("process continue") # Stopped again. - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=["stop reason = breakpoint 1."]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."], + ) # Continue the program, we should exit. self.runCmd("process continue") # We should exit. - self.expect("process status", "Process exited successfully", - patterns=["^Process [0-9]+ exited with status = 0"]) + self.expect( + "process status", + "Process exited successfully", + patterns=["^Process [0-9]+ exited with status = 0"], + ) def breakpoint_options_language_test(self): """Test breakpoint command for language option.""" @@ -80,32 +83,41 @@ # This should create a breakpoint with 1 locations. lldbutil.run_break_set_by_symbol( self, - 'ns::func', + "ns::func", sym_exact=False, extra_options="-L c++", - num_expected_locations=1) + num_expected_locations=1, + ) # This should create a breakpoint with 0 locations. lldbutil.run_break_set_by_symbol( self, - 'ns::func', + "ns::func", sym_exact=False, extra_options="-L c", - num_expected_locations=0) + num_expected_locations=0, + ) self.runCmd("settings set target.language c") lldbutil.run_break_set_by_symbol( - self, 'ns::func', sym_exact=False, num_expected_locations=0) + self, "ns::func", sym_exact=False, num_expected_locations=0 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # Stopped once. - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=["stop reason = breakpoint 1."]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."], + ) # Continue the program, we should exit. self.runCmd("process continue") # We should exit. - self.expect("process status", "Process exited successfully", - patterns=["^Process [0-9]+ exited with status = 0"]) + self.expect( + "process status", + "Process exited successfully", + patterns=["^Process [0-9]+ exited with status = 0"], + ) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_reset_upon_run/TestBreakpointResetUponRun.py b/lldb/test/API/functionalities/breakpoint/breakpoint_reset_upon_run/TestBreakpointResetUponRun.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_reset_upon_run/TestBreakpointResetUponRun.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_reset_upon_run/TestBreakpointResetUponRun.py @@ -8,7 +8,7 @@ class HitcountResetUponRun(TestBase): - BREAKPOINT_TEXT = 'Set a breakpoint here' + BREAKPOINT_TEXT = "Set a breakpoint here" def check_stopped_at_breakpoint_and_hit_once(self, thread, breakpoint): frame0 = thread.GetFrameAtIndex(0) @@ -26,13 +26,13 @@ self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateBySourceRegex( - self.BREAKPOINT_TEXT, lldb.SBFileSpec('main.cpp')) + self.BREAKPOINT_TEXT, lldb.SBFileSpec("main.cpp") + ) self.assertTrue( - breakpoint.IsValid() and breakpoint.GetNumLocations() == 1, - VALID_BREAKPOINT) + breakpoint.IsValid() and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT + ) - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) from lldbsuite.test.lldbutil import get_stopped_thread @@ -40,19 +40,18 @@ # Verify 1st breakpoint location is hit. thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( - thread.IsValid(), - "There should be a thread stopped due to breakpoint") + thread.IsValid(), "There should be a thread stopped due to breakpoint" + ) self.check_stopped_at_breakpoint_and_hit_once(thread, breakpoint) # Relaunch process.Kill() - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Verify the hit counts are still one. thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( - thread.IsValid(), - "There should be a thread stopped due to breakpoint") + thread.IsValid(), "There should be a thread stopped due to breakpoint" + ) self.check_stopped_at_breakpoint_and_hit_once(thread, breakpoint) diff --git a/lldb/test/API/functionalities/breakpoint/breakpoint_set_restart/TestBreakpointSetRestart.py b/lldb/test/API/functionalities/breakpoint/breakpoint_set_restart/TestBreakpointSetRestart.py --- a/lldb/test/API/functionalities/breakpoint/breakpoint_set_restart/TestBreakpointSetRestart.py +++ b/lldb/test/API/functionalities/breakpoint/breakpoint_set_restart/TestBreakpointSetRestart.py @@ -8,11 +8,10 @@ class BreakpointSetRestart(TestBase): - BREAKPOINT_TEXT = 'Set a breakpoint here' + BREAKPOINT_TEXT = "Set a breakpoint here" @skipIfNetBSD - @skipIf(oslist=["freebsd"], - bugnumber="github.com/llvm/llvm-project/issues/56082") + @skipIf(oslist=["freebsd"], bugnumber="github.com/llvm/llvm-project/issues/56082") def test_breakpoint_set_restart(self): self.build() @@ -22,8 +21,7 @@ self.assertTrue(target, VALID_TARGET) self.dbg.SetAsync(True) - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) event = lldb.SBEvent() @@ -33,18 +31,20 @@ break bp = target.BreakpointCreateBySourceRegex( - self.BREAKPOINT_TEXT, lldb.SBFileSpec('main.cpp')) - self.assertTrue( - bp.IsValid() and bp.GetNumLocations() == 1, - VALID_BREAKPOINT) + self.BREAKPOINT_TEXT, lldb.SBFileSpec("main.cpp") + ) + self.assertTrue(bp.IsValid() and bp.GetNumLocations() == 1, VALID_BREAKPOINT) while self.dbg.GetListener().WaitForEvent(2, event): if lldb.SBProcess.GetStateFromEvent( - event) == lldb.eStateStopped and lldb.SBProcess.GetRestartedFromEvent(event): + event + ) == lldb.eStateStopped and lldb.SBProcess.GetRestartedFromEvent(event): continue if lldb.SBProcess.GetStateFromEvent(event) == lldb.eStateRunning: continue self.fail( - "Setting a breakpoint generated an unexpected event: %s" % - lldb.SBDebugger.StateAsCString( - lldb.SBProcess.GetStateFromEvent(event))) + "Setting a breakpoint generated an unexpected event: %s" + % lldb.SBDebugger.StateAsCString( + lldb.SBProcess.GetStateFromEvent(event) + ) + ) diff --git a/lldb/test/API/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py b/lldb/test/API/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py --- a/lldb/test/API/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py +++ b/lldb/test/API/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py @@ -10,20 +10,20 @@ from lldbsuite.test import lldbutil -_EXE_NAME = 'CompDirSymLink' # Must match Makefile -_SRC_FILE = 'relative.cpp' -_COMP_DIR_SYM_LINK_PROP = 'symbols.debug-info-symlink-paths' +_EXE_NAME = "CompDirSymLink" # Must match Makefile +_SRC_FILE = "relative.cpp" +_COMP_DIR_SYM_LINK_PROP = "symbols.debug-info-symlink-paths" class CompDirSymLinkTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number( os.path.join(self.getSourceDir(), "main.cpp"), - '// Set break point at this line.') + "// Set break point at this line.", + ) @skipIf(hostoslist=["windows"]) def test_symlink_paths_set(self): @@ -35,7 +35,7 @@ @skipIf(hostoslist=no_match(["linux"])) def test_symlink_paths_set_procselfcwd(self): os.chdir(self.getBuildDir()) - pwd_symlink = '/proc/self/cwd' + pwd_symlink = "/proc/self/cwd" self.doBuild(pwd_symlink, pwd_symlink) src_path = self.getBuildArtifact(_SRC_FILE) # /proc/self/cwd points to a realpath form of current directory. @@ -52,7 +52,8 @@ lldbutil.run_break_set_by_file_and_line, self, src_path, - self.line) + self.line, + ) @skipIf(hostoslist=["windows"]) def test_symlink_paths_empty(self): @@ -64,10 +65,11 @@ lldbutil.run_break_set_by_file_and_line, self, src_path, - self.line) + self.line, + ) def create_src_symlink(self): - pwd_symlink = self.getBuildArtifact('pwd_symlink') + pwd_symlink = self.getBuildArtifact("pwd_symlink") if os.path.exists(pwd_symlink): os.unlink(pwd_symlink) os.symlink(self.getBuildDir(), pwd_symlink) @@ -75,13 +77,13 @@ return pwd_symlink def doBuild(self, pwd_symlink, setting_value): - self.build(dictionary={'PWD': pwd_symlink}) + self.build(dictionary={"PWD": pwd_symlink}) if setting_value: cmd = "settings set %s '%s'" % (_COMP_DIR_SYM_LINK_PROP, setting_value) else: - cmd = "settings clear %s"%_COMP_DIR_SYM_LINK_PROP + cmd = "settings clear %s" % _COMP_DIR_SYM_LINK_PROP self.runCmd(cmd) exe = self.getBuildArtifact(_EXE_NAME) - self.runCmd('file ' + exe, CURRENT_EXECUTABLE_SET) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) diff --git a/lldb/test/API/functionalities/breakpoint/consecutive_breakpoints/TestConsecutiveBreakpoints.py b/lldb/test/API/functionalities/breakpoint/consecutive_breakpoints/TestConsecutiveBreakpoints.py --- a/lldb/test/API/functionalities/breakpoint/consecutive_breakpoints/TestConsecutiveBreakpoints.py +++ b/lldb/test/API/functionalities/breakpoint/consecutive_breakpoints/TestConsecutiveBreakpoints.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,17 @@ class ConsecutiveBreakpointsTestCase(TestBase): - def prepare_test(self): self.build() - (self.target, self.process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, "Set breakpoint here", lldb.SBFileSpec("main.cpp")) + ( + self.target, + self.process, + self.thread, + bkpt, + ) = lldbutil.run_to_source_breakpoint( + self, "Set breakpoint here", lldb.SBFileSpec("main.cpp") + ) # Set breakpoint to the next instruction frame = self.thread.GetFrameAtIndex(0) @@ -26,10 +30,12 @@ self.assertEquals(len(instructions), 2) self.bkpt_address = instructions[1].GetAddress() self.breakpoint2 = self.target.BreakpointCreateByAddress( - self.bkpt_address.GetLoadAddress(self.target)) + self.bkpt_address.GetLoadAddress(self.target) + ) self.assertTrue( self.breakpoint2 and self.breakpoint2.GetNumLocations() == 1, - VALID_BREAKPOINT) + VALID_BREAKPOINT, + ) def finish_test(self): # Run the process until termination @@ -45,10 +51,11 @@ self.assertState(self.process.GetState(), lldb.eStateStopped) # We should be stopped at the second breakpoint self.thread = lldbutil.get_one_thread_stopped_at_breakpoint( - self.process, self.breakpoint2) + self.process, self.breakpoint2 + ) self.assertIsNotNone( - self.thread, - "Expected one thread to be stopped at breakpoint 2") + self.thread, "Expected one thread to be stopped at breakpoint 2" + ) self.finish_test() @@ -62,14 +69,15 @@ self.assertState(self.process.GetState(), lldb.eStateStopped) self.assertEquals( - self.thread.GetFrameAtIndex(0).GetPCAddress().GetLoadAddress( - self.target), self.bkpt_address.GetLoadAddress( - self.target)) + self.thread.GetFrameAtIndex(0).GetPCAddress().GetLoadAddress(self.target), + self.bkpt_address.GetLoadAddress(self.target), + ) self.thread = lldbutil.get_one_thread_stopped_at_breakpoint( - self.process, self.breakpoint2) + self.process, self.breakpoint2 + ) self.assertIsNotNone( - self.thread, - "Expected one thread to be stopped at breakpoint 2") + self.thread, "Expected one thread to be stopped at breakpoint 2" + ) self.finish_test() @@ -89,12 +97,13 @@ self.assertState(self.process.GetState(), lldb.eStateStopped) self.assertEquals( - self.thread.GetFrameAtIndex(0).GetPCAddress().GetLoadAddress( - self.target), self.bkpt_address.GetLoadAddress( - self.target)) + self.thread.GetFrameAtIndex(0).GetPCAddress().GetLoadAddress(self.target), + self.bkpt_address.GetLoadAddress(self.target), + ) self.assertEquals( self.thread.GetStopReason(), lldb.eStopReasonPlanComplete, - "Stop reason should be 'plan complete'") + "Stop reason should be 'plan complete'", + ) self.finish_test() diff --git a/lldb/test/API/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py b/lldb/test/API/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py --- a/lldb/test/API/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py +++ b/lldb/test/API/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py @@ -9,7 +9,6 @@ class TestCPPBreakpointLocations(TestBase): - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") def test(self): self.do_test(dict()) @@ -25,14 +24,16 @@ self.breakpoint_id_tests() def verify_breakpoint_locations(self, target, bp_dict): - - name = bp_dict['name'] - names = bp_dict['loc_names'] + name = bp_dict["name"] + names = bp_dict["loc_names"] bp = target.BreakpointCreateByName(name) self.assertEquals( bp.GetNumLocations(), len(names), - "Make sure we find the right number of breakpoint locations for {}".format(name)) + "Make sure we find the right number of breakpoint locations for {}".format( + name + ), + ) bp_loc_names = list() for bp_loc in bp: @@ -45,54 +46,90 @@ self.assertTrue(found, "Make sure we find all required locations") def breakpoint_id_tests(self): - # Create a target by the debugger. exe = self.getBuildArtifact("a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) bp_dicts = [ - {'name': 'func1', 'loc_names': ['a::c::func1()', 'aa::cc::func1()', 'b::c::func1()']}, - {'name': 'func2', 'loc_names': ['a::c::func2()', 'aa::cc::func2()', 'c::d::func2()']}, - {'name': 'func3', 'loc_names': ['a::c::func3()', 'aa::cc::func3()', 'b::c::func3()', 'c::d::func3()']}, - {'name': 'c::func1', 'loc_names': ['a::c::func1()', 'b::c::func1()']}, - {'name': 'c::func2', 'loc_names': ['a::c::func2()']}, - {'name': 'c::func3', 'loc_names': ['a::c::func3()', 'b::c::func3()']}, - {'name': 'a::c::func1', 'loc_names': ['a::c::func1()']}, - {'name': 'b::c::func1', 'loc_names': ['b::c::func1()']}, - {'name': 'c::d::func2', 'loc_names': ['c::d::func2()']}, - {'name': 'a::c::func1()', 'loc_names': ['a::c::func1()']}, - {'name': 'b::c::func1()', 'loc_names': ['b::c::func1()']}, - {'name': 'c::d::func2()', 'loc_names': ['c::d::func2()']}, - + { + "name": "func1", + "loc_names": ["a::c::func1()", "aa::cc::func1()", "b::c::func1()"], + }, + { + "name": "func2", + "loc_names": ["a::c::func2()", "aa::cc::func2()", "c::d::func2()"], + }, + { + "name": "func3", + "loc_names": [ + "a::c::func3()", + "aa::cc::func3()", + "b::c::func3()", + "c::d::func3()", + ], + }, + {"name": "c::func1", "loc_names": ["a::c::func1()", "b::c::func1()"]}, + {"name": "c::func2", "loc_names": ["a::c::func2()"]}, + {"name": "c::func3", "loc_names": ["a::c::func3()", "b::c::func3()"]}, + {"name": "a::c::func1", "loc_names": ["a::c::func1()"]}, + {"name": "b::c::func1", "loc_names": ["b::c::func1()"]}, + {"name": "c::d::func2", "loc_names": ["c::d::func2()"]}, + {"name": "a::c::func1()", "loc_names": ["a::c::func1()"]}, + {"name": "b::c::func1()", "loc_names": ["b::c::func1()"]}, + {"name": "c::d::func2()", "loc_names": ["c::d::func2()"]}, # Template cases - {'name': 'func', 'loc_names': []}, - {'name': 'Foo::func', 'loc_names': []}, - {'name': 'ns::Foo::func', 'loc_names': []}, - {'name': 'func', 'loc_names': ['auto ns::Foo::func()']}, - {'name': 'Foo::func', 'loc_names': ['auto ns::Foo::func()']}, - {'name': 'ns::Foo::func', 'loc_names': ['auto ns::Foo::func()']}, - {'name': 'func', 'loc_names': ['auto ns::Foo::func()', - 'auto ns::Foo::func>()']}, - - {'name': 'operator', 'loc_names': []}, - {'name': 'ns::Foo::operator bool', 'loc_names': ['ns::Foo::operator bool()']}, - - {'name': 'operator a::c', 'loc_names': ['ns::Foo::operator a::c()']}, - {'name': 'operator ns::Foo', 'loc_names': ['ns::Foo::operator ns::Foo>()']}, - - {'name': 'operator<<', 'loc_names': []}, - {'name': 'operator<<', 'loc_names': ['void ns::Foo::operator<<(int)']}, - {'name': 'ns::Foo::operator<<', 'loc_names': ['void ns::Foo::operator<<(int)', - 'void ns::Foo::operator<<>(ns::Foo)']}, - - {'name': 'g', 'loc_names': []}, - {'name': 'g', 'loc_names': ['void ns::g()']}, - {'name': 'g', 'loc_names': ['void ns::g()']}, - {'name': 'g', 'loc_names': ['void ns::g()', 'void ns::g()']}, - {'name': 'ns::g', 'loc_names': []}, - {'name': 'ns::g', 'loc_names': ['void ns::g()']}, - {'name': 'ns::g', 'loc_names': ['void ns::g()']}, - {'name': 'ns::g', 'loc_names': ['void ns::g()', 'void ns::g()']}, + {"name": "func", "loc_names": []}, + {"name": "Foo::func", "loc_names": []}, + {"name": "ns::Foo::func", "loc_names": []}, + {"name": "func", "loc_names": ["auto ns::Foo::func()"]}, + { + "name": "Foo::func", + "loc_names": ["auto ns::Foo::func()"], + }, + { + "name": "ns::Foo::func", + "loc_names": ["auto ns::Foo::func()"], + }, + { + "name": "func", + "loc_names": [ + "auto ns::Foo::func()", + "auto ns::Foo::func>()", + ], + }, + {"name": "operator", "loc_names": []}, + { + "name": "ns::Foo::operator bool", + "loc_names": ["ns::Foo::operator bool()"], + }, + { + "name": "operator a::c", + "loc_names": ["ns::Foo::operator a::c()"], + }, + { + "name": "operator ns::Foo", + "loc_names": ["ns::Foo::operator ns::Foo>()"], + }, + {"name": "operator<<", "loc_names": []}, + { + "name": "operator<<", + "loc_names": ["void ns::Foo::operator<<(int)"], + }, + { + "name": "ns::Foo::operator<<", + "loc_names": [ + "void ns::Foo::operator<<(int)", + "void ns::Foo::operator<<>(ns::Foo)", + ], + }, + {"name": "g", "loc_names": []}, + {"name": "g", "loc_names": ["void ns::g()"]}, + {"name": "g", "loc_names": ["void ns::g()"]}, + {"name": "g", "loc_names": ["void ns::g()", "void ns::g()"]}, + {"name": "ns::g", "loc_names": []}, + {"name": "ns::g", "loc_names": ["void ns::g()"]}, + {"name": "ns::g", "loc_names": ["void ns::g()"]}, + {"name": "ns::g", "loc_names": ["void ns::g()", "void ns::g()"]}, ] for bp_dict in bp_dicts: @@ -108,39 +145,34 @@ # easily self.runCmd("settings set target.skip-prologue false") try: - names = ['~c', 'c::~c', 'c::~c()'] - loc_names = {'a::c::~c()', 'b::c::~c()'} + names = ["~c", "c::~c", "c::~c()"] + loc_names = {"a::c::~c()", "b::c::~c()"} # TODO: For windows targets we should put windows mangled names # here - symbols = [ - '_ZN1a1cD1Ev', - '_ZN1a1cD2Ev', - '_ZN1b1cD1Ev', - '_ZN1b1cD2Ev'] + symbols = ["_ZN1a1cD1Ev", "_ZN1a1cD2Ev", "_ZN1b1cD1Ev", "_ZN1b1cD2Ev"] for name in names: bp = target.BreakpointCreateByName(name) - bp_loc_names = {bp_loc.GetAddress().GetFunction().GetName() - for bp_loc in bp} + bp_loc_names = { + bp_loc.GetAddress().GetFunction().GetName() for bp_loc in bp + } self.assertEquals( - bp_loc_names, - loc_names, - "Breakpoint set on the correct symbol") + bp_loc_names, loc_names, "Breakpoint set on the correct symbol" + ) bp_addresses = {bp_loc.GetLoadAddress() for bp_loc in bp} symbol_addresses = set() for symbol in symbols: sc_list = target.FindSymbols(symbol, lldb.eSymbolTypeCode) - self.assertEquals( - sc_list.GetSize(), 1, "Found symbol " + symbol) + self.assertEquals(sc_list.GetSize(), 1, "Found symbol " + symbol) symbol = sc_list.GetContextAtIndex(0).GetSymbol() symbol_addresses.add( - symbol.GetStartAddress().GetLoadAddress(target)) + symbol.GetStartAddress().GetLoadAddress(target) + ) self.assertEquals( - symbol_addresses, - bp_addresses, - "Breakpoint set on correct address") + symbol_addresses, bp_addresses, "Breakpoint set on correct address" + ) finally: self.runCmd("settings clear target.skip-prologue") diff --git a/lldb/test/API/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py b/lldb/test/API/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py --- a/lldb/test/API/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py +++ b/lldb/test/API/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py @@ -3,24 +3,23 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCPPExceptionBreakpoint (TestBase): +class TestCPPExceptionBreakpoint(TestBase): my_var = 10 - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24538") def test_cpp_exception_breakpoint(self): """Test setting and hitting the C++ exception breakpoint.""" self.build() self.do_cpp_exception_bkpt() - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24538") def test_dummy_target_cpp_exception_breakpoint(self): """Test setting and hitting the C++ exception breakpoint from dummy target.""" @@ -40,29 +39,33 @@ self.assertTrue(self.target, VALID_TARGET) exception_bkpt = self.target.BreakpointCreateForException( - lldb.eLanguageTypeC_plus_plus, False, True) - self.assertTrue( - exception_bkpt.IsValid(), - "Created exception breakpoint.") + lldb.eLanguageTypeC_plus_plus, False, True + ) + self.assertTrue(exception_bkpt.IsValid(), "Created exception breakpoint.") process = self.target.LaunchSimple( - None, None, self.get_process_working_directory()) + None, None, self.get_process_working_directory() + ) self.assertTrue(process, PROCESS_IS_VALID) thread_list = lldbutil.get_threads_stopped_at_breakpoint( - process, exception_bkpt) - self.assertEquals(len(thread_list), 1, - "One thread stopped at the exception breakpoint.") + process, exception_bkpt + ) + self.assertEquals( + len(thread_list), 1, "One thread stopped at the exception breakpoint." + ) def do_dummy_target_cpp_exception_bkpt(self): exe = self.getBuildArtifact("a.out") error = lldb.SBError() dummy_exception_bkpt = self.dbg.GetDummyTarget().BreakpointCreateForException( - lldb.eLanguageTypeC_plus_plus, False, True) + lldb.eLanguageTypeC_plus_plus, False, True + ) self.assertTrue( dummy_exception_bkpt.IsValid(), - "Created exception breakpoint in dummy target.") + "Created exception breakpoint in dummy target.", + ) self.target = self.dbg.CreateTarget(exe) self.assertTrue(self.target, VALID_TARGET) @@ -70,13 +73,17 @@ exception_bkpt = self.target.GetBreakpointAtIndex(0) self.assertTrue( exception_bkpt.IsValid(), - "Target primed with exception breakpoint from dummy target.") + "Target primed with exception breakpoint from dummy target.", + ) process = self.target.LaunchSimple( - None, None, self.get_process_working_directory()) + None, None, self.get_process_working_directory() + ) self.assertTrue(process, PROCESS_IS_VALID) thread_list = lldbutil.get_threads_stopped_at_breakpoint( - process, exception_bkpt) - self.assertEquals(len(thread_list), 1, - "One thread stopped at the exception breakpoint.") + process, exception_bkpt + ) + self.assertEquals( + len(thread_list), 1, "One thread stopped at the exception breakpoint." + ) diff --git a/lldb/test/API/functionalities/breakpoint/debugbreak/TestDebugBreak.py b/lldb/test/API/functionalities/breakpoint/debugbreak/TestDebugBreak.py --- a/lldb/test/API/functionalities/breakpoint/debugbreak/TestDebugBreak.py +++ b/lldb/test/API/functionalities/breakpoint/debugbreak/TestDebugBreak.py @@ -10,7 +10,6 @@ class DebugBreakTestCase(TestBase): - @skipIf(archs=no_match(["i386", "i686", "x86_64"])) @no_debug_info_test def test_asm_int_3(self): @@ -20,33 +19,40 @@ # Run the program. target = self.dbg.CreateTarget(exe) - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) # We've hit the first stop, so grab the frame. self.assertState(process.GetState(), lldb.eStateStopped) - stop_reason = lldb.eStopReasonException if (lldbplatformutil.getPlatform( - ) == "windows" or lldbplatformutil.getPlatform() == "macosx") else lldb.eStopReasonSignal + stop_reason = ( + lldb.eStopReasonException + if ( + lldbplatformutil.getPlatform() == "windows" + or lldbplatformutil.getPlatform() == "macosx" + ) + else lldb.eStopReasonSignal + ) thread = lldbutil.get_stopped_thread(process, stop_reason) self.assertIsNotNone( - thread, "Unable to find thread stopped at the __debugbreak()") + thread, "Unable to find thread stopped at the __debugbreak()" + ) frame = thread.GetFrameAtIndex(0) # We should be in function 'bar'. self.assertTrue(frame.IsValid()) function_name = frame.GetFunctionName() - self.assertIn('bar', function_name, - "Unexpected function name {}".format(function_name)) + self.assertIn( + "bar", function_name, "Unexpected function name {}".format(function_name) + ) # We should be able to evaluate the parameter foo. - value = frame.EvaluateExpression('*foo') + value = frame.EvaluateExpression("*foo") self.assertEqual(value.GetValueAsSigned(), 42) # The counter should be 1 at the first stop and increase by 2 for each # subsequent stop. counter = 1 while counter < 20: - value = frame.EvaluateExpression('count') + value = frame.EvaluateExpression("count") self.assertEqual(value.GetValueAsSigned(), counter) counter += 2 process.Continue() diff --git a/lldb/test/API/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py b/lldb/test/API/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py --- a/lldb/test/API/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py +++ b/lldb/test/API/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py @@ -3,16 +3,14 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil -class BreakpointInDummyTarget (TestBase): - +class BreakpointInDummyTarget(TestBase): def test(self): - """Test breakpoint set before we have a target. """ + """Test breakpoint set before we have a target.""" self.build() self.dummy_breakpoint_test() @@ -20,23 +18,25 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.line = line_number('main.c', 'Set a breakpoint on this line.') - self.line2 = line_number('main.c', 'Set another on this line.') + self.line = line_number("main.c", "Set a breakpoint on this line.") + self.line2 = line_number("main.c", "Set another on this line.") def dummy_breakpoint_test(self): - """Test breakpoint set before we have a target. """ + """Test breakpoint set before we have a target.""" # This should create a breakpoint with 3 locations. lldbutil.run_break_set_by_file_and_line( - self, "main.c", self.line, num_expected_locations=0) + self, "main.c", self.line, num_expected_locations=0 + ) lldbutil.run_break_set_by_file_and_line( - self, "main.c", self.line2, num_expected_locations=0) + self, "main.c", self.line2, num_expected_locations=0 + ) # This is the function to remove breakpoints from the dummy target # to get a clean slate for the next test case. def cleanup(): - self.runCmd('breakpoint delete -D -f', check=False) - self.runCmd('breakpoint list', check=False) + self.runCmd("breakpoint delete -D -f", check=False) + self.runCmd("breakpoint list", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -49,21 +49,29 @@ "breakpoint list -f", "Breakpoint locations shown correctly", substrs=[ - "1: file = 'main.c', line = %d, exact_match = 0, locations = 1" % - self.line, - "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % - self.line2]) + "1: file = 'main.c', line = %d, exact_match = 0, locations = 1" + % self.line, + "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" + % self.line2, + ], + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # Stopped once. - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=["stop reason = breakpoint 1."]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."], + ) # Continue the program, there should be another stop. self.runCmd("process continue") # Stopped again. - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs=["stop reason = breakpoint 2."]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 2."], + ) diff --git a/lldb/test/API/functionalities/breakpoint/global_constructor/TestBreakpointInGlobalConstructor.py b/lldb/test/API/functionalities/breakpoint/global_constructor/TestBreakpointInGlobalConstructor.py --- a/lldb/test/API/functionalities/breakpoint/global_constructor/TestBreakpointInGlobalConstructor.py +++ b/lldb/test/API/functionalities/breakpoint/global_constructor/TestBreakpointInGlobalConstructor.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -15,29 +14,30 @@ def test(self): self.build() - self.line_foo = line_number('foo.cpp', '// !BR_foo') - self.line_main = line_number('main.cpp', '// !BR_main') + self.line_foo = line_number("foo.cpp", "// !BR_foo") + self.line_main = line_number("main.cpp", "// !BR_main") target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) self.assertTrue(target, VALID_TARGET) - env= self.registerSharedLibrariesWithTarget(target, ["foo"]) + env = self.registerSharedLibrariesWithTarget(target, ["foo"]) bp_main = lldbutil.run_break_set_by_file_and_line( - self, 'main.cpp', self.line_main) + self, "main.cpp", self.line_main + ) bp_foo = lldbutil.run_break_set_by_file_and_line( - self, 'foo.cpp', self.line_foo, num_expected_locations=-2) + self, "foo.cpp", self.line_foo, num_expected_locations=-2 + ) - process = target.LaunchSimple( - None, env, self.get_process_working_directory()) + process = target.LaunchSimple(None, env, self.get_process_working_directory()) self.assertIsNotNone( - lldbutil.get_one_thread_stopped_at_breakpoint_id( - self.process(), bp_foo)) + lldbutil.get_one_thread_stopped_at_breakpoint_id(self.process(), bp_foo) + ) self.runCmd("continue") self.assertIsNotNone( - lldbutil.get_one_thread_stopped_at_breakpoint_id( - self.process(), bp_main)) + lldbutil.get_one_thread_stopped_at_breakpoint_id(self.process(), bp_main) + ) diff --git a/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/base.py b/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/base.py --- a/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/base.py +++ b/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/base.py @@ -4,16 +4,15 @@ from lldbsuite.test.lldbtest import * + class HardwareBreakpointTestBase(TestBase): NO_DEBUG_INFO_TESTCASE = True - def supports_hw_breakpoints(self): self.build() - self.runCmd("file " + self.getBuildArtifact("a.out"), - CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) self.runCmd("breakpoint set -b main --hardware") self.runCmd("run") - if 'stopped' in self.res.GetOutput(): - return 'Hardware breakpoints are supported' + if "stopped" in self.res.GetOutput(): + return "Hardware breakpoints are supported" return None diff --git a/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/TestHWBreakMultiThread.py b/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/TestHWBreakMultiThread.py --- a/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/TestHWBreakMultiThread.py +++ b/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/TestHWBreakMultiThread.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,8 +10,8 @@ from functionalities.breakpoint.hardware_breakpoints.base import * -class HardwareBreakpointMultiThreadTestCase(HardwareBreakpointTestBase): +class HardwareBreakpointMultiThreadTestCase(HardwareBreakpointTestBase): def does_not_support_hw_breakpoints(self): return not super().supports_hw_breakpoints() @@ -21,53 +20,55 @@ def test_hw_break_set_delete_multi_thread_macos(self): self.build() self.setTearDownCleanup() - self.break_multi_thread('delete') + self.break_multi_thread("delete") @skipIfOutOfTreeDebugserver @skipTestIfFn(does_not_support_hw_breakpoints) def test_hw_break_set_disable_multi_thread_macos(self): self.build() self.setTearDownCleanup() - self.break_multi_thread('disable') + self.break_multi_thread("disable") def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Our simple source filename. - self.source = 'main.cpp' + self.source = "main.cpp" # Find the line number to break inside main(). self.first_stop = line_number( - self.source, 'Starting thread creation with hardware breakpoint set') + self.source, "Starting thread creation with hardware breakpoint set" + ) def break_multi_thread(self, removal_type): """Test that lldb hardware breakpoints work for multiple threads.""" - self.runCmd("file " + self.getBuildArtifact("a.out"), - CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) # Stop in main before creating any threads. lldbutil.run_break_set_by_file_and_line( - self, None, self.first_stop, num_expected_locations=1) + self, None, self.first_stop, num_expected_locations=1 + ) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # Now set a hardware breakpoint in thread function. - self.expect("breakpoint set -b hw_break_function --hardware", - substrs=[ - 'Breakpoint', - 'hw_break_function', - 'address = 0x']) + self.expect( + "breakpoint set -b hw_break_function --hardware", + substrs=["Breakpoint", "hw_break_function", "address = 0x"], + ) # We should stop in hw_break_function function for 4 threads. count = 0 - while count < 2 : - + while count < 2: self.runCmd("process continue") # We should be stopped in hw_break_function @@ -76,35 +77,40 @@ "thread list", STOPPED_DUE_TO_BREAKPOINT, substrs=[ - 'hw_break_function', - 'stop reason = breakpoint', - ]) + "hw_break_function", + "stop reason = breakpoint", + ], + ) # Continue the loop and test that we are stopped 4 times. count += 1 # Check the breakpoint list. - self.expect("breakpoint list", substrs=['hw_break_function', 'hardware']) - self.expect("breakpoint list -v", substrs=['function = hw_break_function', 'hardware = true']) + self.expect("breakpoint list", substrs=["hw_break_function", "hardware"]) + self.expect( + "breakpoint list -v", + substrs=["function = hw_break_function", "hardware = true"], + ) - if removal_type == 'delete': + if removal_type == "delete": self.runCmd("settings set auto-confirm true") # Now 'breakpoint delete' should just work fine without confirmation # prompt from the command interpreter. - self.expect("breakpoint delete", - startstr="All breakpoints removed") + self.expect("breakpoint delete", startstr="All breakpoints removed") # Restore the original setting of auto-confirm. self.runCmd("settings clear auto-confirm") - elif removal_type == 'disable': - self.expect("breakpoint disable", - startstr="All breakpoints disabled.") + elif removal_type == "disable": + self.expect("breakpoint disable", startstr="All breakpoints disabled.") # Continue. Program should exit without stopping anywhere. self.runCmd("process continue") # Process should have stopped and exited with status = 0 - self.expect("process status", PROCESS_STOPPED, - patterns=['Process .* exited with status = 0']) + self.expect( + "process status", + PROCESS_STOPPED, + patterns=["Process .* exited with status = 0"], + ) diff --git a/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/require_hw_breakpoints/TestRequireHWBreakpoints.py b/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/require_hw_breakpoints/TestRequireHWBreakpoints.py --- a/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/require_hw_breakpoints/TestRequireHWBreakpoints.py +++ b/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/require_hw_breakpoints/TestRequireHWBreakpoints.py @@ -10,8 +10,8 @@ from functionalities.breakpoint.hardware_breakpoints.base import * -class BreakpointLocationsTestCase(HardwareBreakpointTestBase): +class BreakpointLocationsTestCase(HardwareBreakpointTestBase): @skipIf(oslist=["linux"], archs=["arm"]) def supports_hw_breakpoints(self): return super().supports_hw_breakpoints() @@ -33,7 +33,8 @@ self.build() _, _, thread, _ = lldbutil.run_to_line_breakpoint( - self, lldb.SBFileSpec("main.c"), 1) + self, lldb.SBFileSpec("main.c"), 1 + ) self.runCmd("settings set target.require-hardware-breakpoint true") @@ -43,10 +44,11 @@ # Ensure we fail when stepping through the API. error = lldb.SBError() - thread.StepInto('', 4, error) + thread.StepInto("", 4, error) self.assertTrue(error.Fail()) - self.assertTrue("Could not create hardware breakpoint for thread plan" - in error.GetCString()) + self.assertTrue( + "Could not create hardware breakpoint for thread plan" in error.GetCString() + ) @expectedFailureIfFn(supports_hw_breakpoints) def test_step_out(self): @@ -54,7 +56,8 @@ self.build() _, _, thread, _ = lldbutil.run_to_line_breakpoint( - self, lldb.SBFileSpec("main.c"), 1) + self, lldb.SBFileSpec("main.c"), 1 + ) self.runCmd("settings set target.require-hardware-breakpoint true") @@ -65,8 +68,9 @@ error = lldb.SBError() thread.StepOut(error) self.assertTrue(error.Fail()) - self.assertTrue("Could not create hardware breakpoint for thread plan" - in error.GetCString()) + self.assertTrue( + "Could not create hardware breakpoint for thread plan" in error.GetCString() + ) @expectedFailureIfFn(supports_hw_breakpoints) def test_step_over(self): @@ -74,7 +78,8 @@ self.build() _, _, thread, _ = lldbutil.run_to_line_breakpoint( - self, lldb.SBFileSpec("main.c"), 7) + self, lldb.SBFileSpec("main.c"), 7 + ) self.runCmd("settings set target.require-hardware-breakpoint true") @@ -82,9 +87,8 @@ self.expect( "thread step-over", error=True, - substrs=[ - 'error: Could not create hardware breakpoint for thread plan.' - ]) + substrs=["error: Could not create hardware breakpoint for thread plan."], + ) @expectedFailureIfFn(supports_hw_breakpoints) def test_step_until(self): @@ -92,7 +96,8 @@ self.build() _, _, thread, _ = lldbutil.run_to_line_breakpoint( - self, lldb.SBFileSpec("main.c"), 7) + self, lldb.SBFileSpec("main.c"), 7 + ) self.runCmd("settings set target.require-hardware-breakpoint true") @@ -101,5 +106,6 @@ # Ensure we fail when stepping through the API. error = thread.StepOverUntil(lldb.SBFrame(), lldb.SBFileSpec(), 5) self.assertTrue(error.Fail()) - self.assertTrue("Could not create hardware breakpoint for thread plan" - in error.GetCString()) + self.assertTrue( + "Could not create hardware breakpoint for thread plan" in error.GetCString() + ) diff --git a/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/write_memory_with_hw_breakpoint/TestWriteMemoryWithHWBreakpoint.py b/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/write_memory_with_hw_breakpoint/TestWriteMemoryWithHWBreakpoint.py --- a/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/write_memory_with_hw_breakpoint/TestWriteMemoryWithHWBreakpoint.py +++ b/lldb/test/API/functionalities/breakpoint/hardware_breakpoints/write_memory_with_hw_breakpoint/TestWriteMemoryWithHWBreakpoint.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,8 +10,8 @@ from functionalities.breakpoint.hardware_breakpoints.base import * -class WriteMemoryWithHWBreakpoint(HardwareBreakpointTestBase): +class WriteMemoryWithHWBreakpoint(HardwareBreakpointTestBase): def does_not_support_hw_breakpoints(self): return not super().supports_hw_breakpoints() @@ -26,20 +25,21 @@ self.assertTrue(target, VALID_TARGET) # Run the program and stop at entry. - self.expect("process launch --stop-at-entry", - patterns=["Process .* launched: .*a.out"]) + self.expect( + "process launch --stop-at-entry", patterns=["Process .* launched: .*a.out"] + ) process = target.GetProcess() self.assertTrue(process, PROCESS_IS_VALID) # Set a hardware breakpoint. - bp_id = lldbutil.run_break_set_by_symbol(self, "hw_break_function", - extra_options="--hardware") + bp_id = lldbutil.run_break_set_by_symbol( + self, "hw_break_function", extra_options="--hardware" + ) # Get breakpoint location from the breakpoint. location = target.FindBreakpointByID(bp_id).GetLocationAtIndex(0) - self.assertTrue(location and location.IsResolved(), - VALID_BREAKPOINT_LOCATION) + self.assertTrue(location and location.IsResolved(), VALID_BREAKPOINT_LOCATION) # Check that writing overlapping memory doesn't crash. address = location.GetLoadAddress() diff --git a/lldb/test/API/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py b/lldb/test/API/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py --- a/lldb/test/API/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py +++ b/lldb/test/API/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py @@ -4,7 +4,6 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil @@ -22,9 +21,7 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside basic_type.cpp. - self.line = line_number( - 'basic_type.cpp', - '// Set break point at this line.') + self.line = line_number("basic_type.cpp", "// Set break point at this line.") def inlined_breakpoints(self): """Test 'b basic_types.cpp:176' does break (where int.cpp includes basic_type.cpp).""" @@ -33,32 +30,36 @@ # With the inline-breakpoint-strategy, our file+line breakpoint should # not resolve to a location. - self.runCmd('settings set target.inline-breakpoint-strategy headers') + self.runCmd("settings set target.inline-breakpoint-strategy headers") # Set a breakpoint and fail because it is in an inlined source # implemenation file lldbutil.run_break_set_by_file_and_line( - self, "basic_type.cpp", self.line, num_expected_locations=0) + self, "basic_type.cpp", self.line, num_expected_locations=0 + ) # Now enable breakpoints in implementation files and see the breakpoint # set succeed - self.runCmd('settings set target.inline-breakpoint-strategy always') + self.runCmd("settings set target.inline-breakpoint-strategy always") # And add hooks to restore the settings during tearDown(). - self.addTearDownHook(lambda: self.runCmd( - "settings set target.inline-breakpoint-strategy always")) + self.addTearDownHook( + lambda: self.runCmd("settings set target.inline-breakpoint-strategy always") + ) lldbutil.run_break_set_by_file_and_line( - self, - "basic_type.cpp", - self.line, - num_expected_locations=1, - loc_exact=True) + self, "basic_type.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. # And it should break at basic_type.cpp:176. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'basic_type.cpp:%d' % self.line, - 'stop reason = breakpoint',]) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=[ + "stopped", + "basic_type.cpp:%d" % self.line, + "stop reason = breakpoint", + ], + ) diff --git a/lldb/test/API/functionalities/breakpoint/move_nearest/TestMoveNearest.py b/lldb/test/API/functionalities/breakpoint/move_nearest/TestMoveNearest.py --- a/lldb/test/API/functionalities/breakpoint/move_nearest/TestMoveNearest.py +++ b/lldb/test/API/functionalities/breakpoint/move_nearest/TestMoveNearest.py @@ -10,11 +10,11 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.line1 = line_number('foo.h', '// !BR1') - self.line2 = line_number('foo.h', '// !BR2') - self.line_between = line_number('main.cpp', "// BR_Between") + self.line1 = line_number("foo.h", "// !BR1") + self.line2 = line_number("foo.h", "// !BR2") + self.line_between = line_number("main.cpp", "// BR_Between") print("BR_Between found at", self.line_between) - self.line_main = line_number('main.cpp', '// !BR_main') + self.line_main = line_number("main.cpp", "// !BR_main") def test(self): """Test target.move-to-nearest logic""" @@ -23,41 +23,55 @@ target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) self.assertTrue(target, VALID_TARGET) - lldbutil.run_break_set_by_symbol(self, 'main', sym_exact=True) + lldbutil.run_break_set_by_symbol(self, "main", sym_exact=True) environment = self.registerSharedLibrariesWithTarget(target, ["foo"]) - process = target.LaunchSimple(None, environment, self.get_process_working_directory()) + process = target.LaunchSimple( + None, environment, self.get_process_working_directory() + ) self.assertState(process.GetState(), lldb.eStateStopped) # Regardless of the -m value the breakpoint should have exactly one # location on the foo functions self.runCmd("settings set target.move-to-nearest-code true") - lldbutil.run_break_set_by_file_and_line(self, 'foo.h', self.line1, - loc_exact=True, extra_options="-m 1") - lldbutil.run_break_set_by_file_and_line(self, 'foo.h', self.line2, - loc_exact=True, extra_options="-m 1") + lldbutil.run_break_set_by_file_and_line( + self, "foo.h", self.line1, loc_exact=True, extra_options="-m 1" + ) + lldbutil.run_break_set_by_file_and_line( + self, "foo.h", self.line2, loc_exact=True, extra_options="-m 1" + ) self.runCmd("settings set target.move-to-nearest-code false") - lldbutil.run_break_set_by_file_and_line(self, 'foo.h', self.line1, - loc_exact=True, extra_options="-m 0") - lldbutil.run_break_set_by_file_and_line(self, 'foo.h', self.line2, - loc_exact=True, extra_options="-m 0") - + lldbutil.run_break_set_by_file_and_line( + self, "foo.h", self.line1, loc_exact=True, extra_options="-m 0" + ) + lldbutil.run_break_set_by_file_and_line( + self, "foo.h", self.line2, loc_exact=True, extra_options="-m 0" + ) # Make sure we set a breakpoint in main with -m 1 for various lines in # the function declaration # "int" - lldbutil.run_break_set_by_file_and_line(self, 'main.cpp', - self.line_main-1, extra_options="-m 1") + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line_main - 1, extra_options="-m 1" + ) # "main()" - lldbutil.run_break_set_by_file_and_line(self, 'main.cpp', - self.line_main, extra_options="-m 1") + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line_main, extra_options="-m 1" + ) # "{" - lldbutil.run_break_set_by_file_and_line(self, 'main.cpp', - self.line_main+1, extra_options="-m 1") + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line_main + 1, extra_options="-m 1" + ) # "return .." - lldbutil.run_break_set_by_file_and_line(self, 'main.cpp', - self.line_main+2, extra_options="-m 1") + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line_main + 2, extra_options="-m 1" + ) # Make sure we don't put move the breakpoint if it is set between two functions: - lldbutil.run_break_set_by_file_and_line(self, 'main.cpp', - self.line_between, extra_options="-m 1", num_expected_locations=0) + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line_between, + extra_options="-m 1", + num_expected_locations=0, + ) diff --git a/lldb/test/API/functionalities/breakpoint/objc/TestObjCBreakpoints.py b/lldb/test/API/functionalities/breakpoint/objc/TestObjCBreakpoints.py --- a/lldb/test/API/functionalities/breakpoint/objc/TestObjCBreakpoints.py +++ b/lldb/test/API/functionalities/breakpoint/objc/TestObjCBreakpoints.py @@ -4,7 +4,6 @@ """ - import shutil import subprocess import lldb @@ -14,7 +13,6 @@ class TestObjCBreakpoints(TestBase): - @add_test_categories(["objc"]) def test_break(self): """Test setting Objective-C specific breakpoints (DWARF in .o files).""" @@ -27,7 +25,7 @@ TestBase.setUp(self) # Find the line number to break inside main(). self.main_source = "main.m" - self.line = line_number(self.main_source, '// Set breakpoint here') + self.line = line_number(self.main_source, "// Set breakpoint here") def check_category_breakpoints(self): name_bp = self.target.BreakpointCreateByName("myCategoryFunction") @@ -35,31 +33,44 @@ "myCategoryFunction", lldb.eFunctionNameTypeSelector, lldb.SBFileSpecList(), - lldb.SBFileSpecList()) + lldb.SBFileSpecList(), + ) self.assertEqual( - name_bp.GetNumLocations(), selector_bp.GetNumLocations(), - 'Make sure setting a breakpoint by name "myCategoryFunction" sets a breakpoint even though it is in a category') + name_bp.GetNumLocations(), + selector_bp.GetNumLocations(), + 'Make sure setting a breakpoint by name "myCategoryFunction" sets a breakpoint even though it is in a category', + ) for bp_loc in selector_bp: function_name = bp_loc.GetAddress().GetSymbol().GetName() self.assertTrue( " myCategoryFunction]" in function_name, - 'Make sure all function names have " myCategoryFunction]" in their names') + 'Make sure all function names have " myCategoryFunction]" in their names', + ) category_bp = self.target.BreakpointCreateByName( - "-[MyClass(MyCategory) myCategoryFunction]") + "-[MyClass(MyCategory) myCategoryFunction]" + ) stripped_bp = self.target.BreakpointCreateByName( - "-[MyClass myCategoryFunction]") + "-[MyClass myCategoryFunction]" + ) stripped2_bp = self.target.BreakpointCreateByName( - "[MyClass myCategoryFunction]") + "[MyClass myCategoryFunction]" + ) self.assertEqual( - category_bp.GetNumLocations(), 1, - "Make sure we can set a breakpoint using a full objective C function name with the category included (-[MyClass(MyCategory) myCategoryFunction])") + category_bp.GetNumLocations(), + 1, + "Make sure we can set a breakpoint using a full objective C function name with the category included (-[MyClass(MyCategory) myCategoryFunction])", + ) self.assertEqual( - stripped_bp.GetNumLocations(), 1, - "Make sure we can set a breakpoint using a full objective C function name without the category included (-[MyClass myCategoryFunction])") + stripped_bp.GetNumLocations(), + 1, + "Make sure we can set a breakpoint using a full objective C function name without the category included (-[MyClass myCategoryFunction])", + ) self.assertEqual( - stripped2_bp.GetNumLocations(), 1, - "Make sure we can set a breakpoint using a full objective C function name without the category included ([MyClass myCategoryFunction])") + stripped2_bp.GetNumLocations(), + 1, + "Make sure we can set a breakpoint using a full objective C function name without the category included ([MyClass myCategoryFunction])", + ) def check_objc_breakpoints(self, have_dsym): """Test constant string generation amd comparison by the expression parser.""" @@ -72,56 +83,69 @@ self.target = self.dbg.CreateTarget(exe) self.assertTrue(self.target, VALID_TARGET) - #---------------------------------------------------------------------- + # ---------------------------------------------------------------------- # Set breakpoints on all selectors whose name is "count". This should # catch breakpoints that are both C functions _and_ anything whose # selector is "count" because just looking at "count" we can't tell # definitively if the name is a selector or a C function - #---------------------------------------------------------------------- + # ---------------------------------------------------------------------- name_bp = self.target.BreakpointCreateByName("count") selector_bp = self.target.BreakpointCreateByName( "count", lldb.eFunctionNameTypeSelector, lldb.SBFileSpecList(), - lldb.SBFileSpecList()) + lldb.SBFileSpecList(), + ) self.assertGreaterEqual( - name_bp.GetNumLocations(), selector_bp.GetNumLocations(), - 'Make sure we get at least the same amount of breakpoints if not more when setting by name "count"') + name_bp.GetNumLocations(), + selector_bp.GetNumLocations(), + 'Make sure we get at least the same amount of breakpoints if not more when setting by name "count"', + ) self.assertGreater( - selector_bp.GetNumLocations(), 50, - 'Make sure we find a lot of "count" selectors') # There are 93 on the latest MacOSX + selector_bp.GetNumLocations(), + 50, + 'Make sure we find a lot of "count" selectors', + ) # There are 93 on the latest MacOSX for bp_loc in selector_bp: function_name = bp_loc.GetAddress().GetSymbol().GetName() self.assertTrue( " count]" in function_name, - 'Make sure all function names have " count]" in their names') + 'Make sure all function names have " count]" in their names', + ) - #---------------------------------------------------------------------- + # ---------------------------------------------------------------------- # Set breakpoints on all selectors whose name is "isEqual:". This should # catch breakpoints that are only ObjC selectors because no C function # can end with a : - #---------------------------------------------------------------------- + # ---------------------------------------------------------------------- name_bp = self.target.BreakpointCreateByName("isEqual:") selector_bp = self.target.BreakpointCreateByName( "isEqual:", lldb.eFunctionNameTypeSelector, lldb.SBFileSpecList(), - lldb.SBFileSpecList()) + lldb.SBFileSpecList(), + ) self.assertEqual( - name_bp.GetNumLocations(), selector_bp.GetNumLocations(), - 'Make sure setting a breakpoint by name "isEqual:" only sets selector breakpoints') + name_bp.GetNumLocations(), + selector_bp.GetNumLocations(), + 'Make sure setting a breakpoint by name "isEqual:" only sets selector breakpoints', + ) for bp_loc in selector_bp: function_name = bp_loc.GetAddress().GetSymbol().GetName() self.assertTrue( " isEqual:]" in function_name, - 'Make sure all function names have " isEqual:]" in their names') + 'Make sure all function names have " isEqual:]" in their names', + ) self.check_category_breakpoints() if have_dsym: shutil.rmtree(exe + ".dSYM") - self.assertEqual(subprocess.call( - ['/usr/bin/strip', '-Sx', exe]), 0, 'stripping dylib succeeded') + self.assertEqual( + subprocess.call(["/usr/bin/strip", "-Sx", exe]), + 0, + "stripping dylib succeeded", + ) # Check breakpoints again, this time using the symbol table only self.check_category_breakpoints() diff --git a/lldb/test/API/functionalities/breakpoint/scripted_bkpt/TestScriptedResolver.py b/lldb/test/API/functionalities/breakpoint/scripted_bkpt/TestScriptedResolver.py --- a/lldb/test/API/functionalities/breakpoint/scripted_bkpt/TestScriptedResolver.py +++ b/lldb/test/API/functionalities/breakpoint/scripted_bkpt/TestScriptedResolver.py @@ -10,7 +10,6 @@ class TestScriptedResolver(TestBase): - NO_DEBUG_INFO_TESTCASE = True def test_scripted_resolver(self): @@ -19,19 +18,19 @@ self.do_test() def test_search_depths(self): - """ Make sure we are called at the right depths depending on what we return - from __get_depth__""" + """Make sure we are called at the right depths depending on what we return + from __get_depth__""" self.build() self.do_test_depths() def test_command_line(self): - """ Test setting a resolver breakpoint from the command line """ + """Test setting a resolver breakpoint from the command line""" self.build() self.do_test_cli() def test_bad_command_lines(self): """Make sure we get appropriate errors when we give invalid key/value - options""" + options""" self.build() self.do_test_bad_options() @@ -58,7 +57,9 @@ command = "command script import " + script_name result = lldb.SBCommandReturnObject() interp.HandleCommand(command, result) - self.assertTrue(result.Succeeded(), "com scr imp failed: %s"%(result.GetError())) + self.assertTrue( + result.Succeeded(), "com scr imp failed: %s" % (result.GetError()) + ) def make_extra_args(self): json_string = '{"symbol":"break_on_me", "test1": "value1"}' @@ -81,25 +82,47 @@ # Make breakpoints with this resolver using different filters, first ones that will take: right = [] # one with no file or module spec - this one should fire: - right.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)) + right.append( + target.BreakpointCreateFromScript( + "resolver.Resolver", extra_args, module_list, file_list + ) + ) # one with the right source file and no module - should also fire: file_list.Append(lldb.SBFileSpec("main.c")) - right.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)) + right.append( + target.BreakpointCreateFromScript( + "resolver.Resolver", extra_args, module_list, file_list + ) + ) # Make sure the help text shows up in the "break list" output: - self.expect("break list", substrs=["I am a python breakpoint resolver"], msg="Help is listed in break list") + self.expect( + "break list", + substrs=["I am a python breakpoint resolver"], + msg="Help is listed in break list", + ) # one with the right source file and right module - should also fire: module_list.Append(lldb.SBFileSpec("a.out")) - right.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)) + right.append( + target.BreakpointCreateFromScript( + "resolver.Resolver", extra_args, module_list, file_list + ) + ) # And one with no source file but the right module: file_list.Clear() - right.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)) + right.append( + target.BreakpointCreateFromScript( + "resolver.Resolver", extra_args, module_list, file_list + ) + ) # Make sure these all got locations: - for i in range (0, len(right)): - self.assertTrue(right[i].GetNumLocations() >= 1, "Breakpoint %d has no locations."%(i)) + for i in range(0, len(right)): + self.assertTrue( + right[i].GetNumLocations() >= 1, "Breakpoint %d has no locations." % (i) + ) # Now some ones that won't take: @@ -109,41 +132,67 @@ # one with the wrong module - should not fire: module_list.Append(lldb.SBFileSpec("noSuchModule")) - wrong.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)) + wrong.append( + target.BreakpointCreateFromScript( + "resolver.Resolver", extra_args, module_list, file_list + ) + ) # one with the wrong file - also should not fire: file_list.Clear() module_list.Clear() file_list.Append(lldb.SBFileSpec("noFileOfThisName.xxx")) - wrong.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)) + wrong.append( + target.BreakpointCreateFromScript( + "resolver.Resolver", extra_args, module_list, file_list + ) + ) # Now make sure the CU level iteration obeys the file filters: file_list.Clear() module_list.Clear() file_list.Append(lldb.SBFileSpec("no_such_file.xxx")) - wrong.append(target.BreakpointCreateFromScript("resolver.ResolverCUDepth", extra_args, module_list, file_list)) + wrong.append( + target.BreakpointCreateFromScript( + "resolver.ResolverCUDepth", extra_args, module_list, file_list + ) + ) # And the Module filters: file_list.Clear() module_list.Clear() module_list.Append(lldb.SBFileSpec("NoSuchModule.dylib")) - wrong.append(target.BreakpointCreateFromScript("resolver.ResolverCUDepth", extra_args, module_list, file_list)) + wrong.append( + target.BreakpointCreateFromScript( + "resolver.ResolverCUDepth", extra_args, module_list, file_list + ) + ) # Now make sure the Function level iteration obeys the file filters: file_list.Clear() module_list.Clear() file_list.Append(lldb.SBFileSpec("no_such_file.xxx")) - wrong.append(target.BreakpointCreateFromScript("resolver.ResolverFuncDepth", extra_args, module_list, file_list)) + wrong.append( + target.BreakpointCreateFromScript( + "resolver.ResolverFuncDepth", extra_args, module_list, file_list + ) + ) # And the Module filters: file_list.Clear() module_list.Clear() module_list.Append(lldb.SBFileSpec("NoSuchModule.dylib")) - wrong.append(target.BreakpointCreateFromScript("resolver.ResolverFuncDepth", extra_args, module_list, file_list)) + wrong.append( + target.BreakpointCreateFromScript( + "resolver.ResolverFuncDepth", extra_args, module_list, file_list + ) + ) # Make sure these didn't get locations: for i in range(0, len(wrong)): - self.assertEqual(wrong[i].GetNumLocations(), 0, "Breakpoint %d has locations."%(i)) + self.assertEqual( + wrong[i].GetNumLocations(), 0, "Breakpoint %d has locations." % (i) + ) # Now run to main and ensure we hit the breakpoints we should have: @@ -151,16 +200,20 @@ # Test the hit counts: for i in range(0, len(right)): - self.assertEqual(right[i].GetHitCount(), 1, "Breakpoint %d has the wrong hit count"%(i)) + self.assertEqual( + right[i].GetHitCount(), 1, "Breakpoint %d has the wrong hit count" % (i) + ) for i in range(0, len(wrong)): - self.assertEqual(wrong[i].GetHitCount(), 0, "Breakpoint %d has the wrong hit count"%(i)) + self.assertEqual( + wrong[i].GetHitCount(), 0, "Breakpoint %d has the wrong hit count" % (i) + ) def do_test_depths(self): """This test uses a class variable in resolver.Resolver which gets set to 1 if we saw - compile unit and 2 if we only saw modules. If the search depth is module, you get passed just - the modules with no comp_unit. If the depth is comp_unit you get comp_units. So we can use - this to test that our callback gets called at the right depth.""" + compile unit and 2 if we only saw modules. If the search depth is module, you get passed just + the modules with no comp_unit. If the depth is comp_unit you get comp_units. So we can use + this to test that our callback gets called at the right depth.""" target = self.make_target_and_import() extra_args = self.make_extra_args() @@ -170,35 +223,77 @@ module_list.Append(lldb.SBFileSpec("a.out")) # Make a breakpoint that has no __get_depth__, check that that is converted to eSearchDepthModule: - bkpt = target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list) + bkpt = target.BreakpointCreateFromScript( + "resolver.Resolver", extra_args, module_list, file_list + ) self.assertTrue(bkpt.GetNumLocations() > 0, "Resolver got no locations.") - self.expect("script print(resolver.Resolver.got_files)", substrs=["2"], msg="Was only passed modules") + self.expect( + "script print(resolver.Resolver.got_files)", + substrs=["2"], + msg="Was only passed modules", + ) # Make a breakpoint that asks for modules, check that we didn't get any files: - bkpt = target.BreakpointCreateFromScript("resolver.ResolverModuleDepth", extra_args, module_list, file_list) - self.assertTrue(bkpt.GetNumLocations() > 0, "ResolverModuleDepth got no locations.") - self.expect("script print(resolver.Resolver.got_files)", substrs=["2"], msg="Was only passed modules") + bkpt = target.BreakpointCreateFromScript( + "resolver.ResolverModuleDepth", extra_args, module_list, file_list + ) + self.assertTrue( + bkpt.GetNumLocations() > 0, "ResolverModuleDepth got no locations." + ) + self.expect( + "script print(resolver.Resolver.got_files)", + substrs=["2"], + msg="Was only passed modules", + ) # Make a breakpoint that asks for compile units, check that we didn't get any files: - bkpt = target.BreakpointCreateFromScript("resolver.ResolverCUDepth", extra_args, module_list, file_list) + bkpt = target.BreakpointCreateFromScript( + "resolver.ResolverCUDepth", extra_args, module_list, file_list + ) self.assertTrue(bkpt.GetNumLocations() > 0, "ResolverCUDepth got no locations.") - self.expect("script print(resolver.Resolver.got_files)", substrs=["1"], msg="Was passed compile units") + self.expect( + "script print(resolver.Resolver.got_files)", + substrs=["1"], + msg="Was passed compile units", + ) # Make a breakpoint that returns a bad value - we should convert that to "modules" so check that: - bkpt = target.BreakpointCreateFromScript("resolver.ResolverBadDepth", extra_args, module_list, file_list) - self.assertTrue(bkpt.GetNumLocations() > 0, "ResolverBadDepth got no locations.") - self.expect("script print(resolver.Resolver.got_files)", substrs=["2"], msg="Was only passed modules") + bkpt = target.BreakpointCreateFromScript( + "resolver.ResolverBadDepth", extra_args, module_list, file_list + ) + self.assertTrue( + bkpt.GetNumLocations() > 0, "ResolverBadDepth got no locations." + ) + self.expect( + "script print(resolver.Resolver.got_files)", + substrs=["2"], + msg="Was only passed modules", + ) # Make a breakpoint that searches at function depth: - bkpt = target.BreakpointCreateFromScript("resolver.ResolverFuncDepth", extra_args, module_list, file_list) - self.assertTrue(bkpt.GetNumLocations() > 0, "ResolverFuncDepth got no locations.") - self.expect("script print(resolver.Resolver.got_files)", substrs=["3"], msg="Was only passed modules") - self.expect("script print(resolver.Resolver.func_list)", substrs=['test_func', 'break_on_me', 'main'], msg="Saw all the functions") + bkpt = target.BreakpointCreateFromScript( + "resolver.ResolverFuncDepth", extra_args, module_list, file_list + ) + self.assertTrue( + bkpt.GetNumLocations() > 0, "ResolverFuncDepth got no locations." + ) + self.expect( + "script print(resolver.Resolver.got_files)", + substrs=["3"], + msg="Was only passed modules", + ) + self.expect( + "script print(resolver.Resolver.func_list)", + substrs=["test_func", "break_on_me", "main"], + msg="Saw all the functions", + ) def do_test_cli(self): target = self.make_target_and_import() - lldbutil.run_break_set_by_script(self, "resolver.Resolver", extra_options="-k symbol -v break_on_me") + lldbutil.run_break_set_by_script( + self, "resolver.Resolver", extra_options="-k symbol -v break_on_me" + ) # Make sure setting a resolver breakpoint doesn't pollute further breakpoint setting # by checking the description of a regular file & line breakpoint to make sure it @@ -208,40 +303,63 @@ strm = lldb.SBStream() bkpt.GetDescription(strm, False) used_resolver = "I am a python breakpoint resolver" in strm.GetData() - self.assertFalse(used_resolver, "Found the resolver description in the file & line breakpoint description.") + self.assertFalse( + used_resolver, + "Found the resolver description in the file & line breakpoint description.", + ) # Also make sure the breakpoint was where we expected: bp_loc = bkpt.GetLocationAtIndex(0) bp_sc = bp_loc.GetAddress().GetSymbolContext(lldb.eSymbolContextEverything) bp_se = bp_sc.GetLineEntry() self.assertEqual(bp_se.GetLine(), 12, "Got the right line number") - self.assertEqual(bp_se.GetFileSpec().GetFilename(), "main.c", "Got the right filename") + self.assertEqual( + bp_se.GetFileSpec().GetFilename(), "main.c", "Got the right filename" + ) def do_test_bad_options(self): target = self.make_target_and_import() - self.expect("break set -P resolver.Resolver -k a_key", error = True, msg="Missing value at end", - substrs=['Key: "a_key" missing value']) - self.expect("break set -P resolver.Resolver -v a_value", error = True, msg="Missing key at end", - substrs=['Value: "a_value" missing matching key']) - self.expect("break set -P resolver.Resolver -v a_value -k a_key -v another_value", error = True, msg="Missing key among args", - substrs=['Value: "a_value" missing matching key']) - self.expect("break set -P resolver.Resolver -k a_key -k a_key -v another_value", error = True, msg="Missing value among args", - substrs=['Key: "a_key" missing value']) + self.expect( + "break set -P resolver.Resolver -k a_key", + error=True, + msg="Missing value at end", + substrs=['Key: "a_key" missing value'], + ) + self.expect( + "break set -P resolver.Resolver -v a_value", + error=True, + msg="Missing key at end", + substrs=['Value: "a_value" missing matching key'], + ) + self.expect( + "break set -P resolver.Resolver -v a_value -k a_key -v another_value", + error=True, + msg="Missing key among args", + substrs=['Value: "a_value" missing matching key'], + ) + self.expect( + "break set -P resolver.Resolver -k a_key -k a_key -v another_value", + error=True, + msg="Missing value among args", + substrs=['Key: "a_key" missing value'], + ) def do_test_copy_from_dummy_target(self): # Import breakpoint scripted resolver. self.import_resolver_script() # Create a scripted breakpoint. - self.runCmd("breakpoint set -P resolver.Resolver -k symbol -v break_on_me", - BREAKPOINT_CREATED) + self.runCmd( + "breakpoint set -P resolver.Resolver -k symbol -v break_on_me", + BREAKPOINT_CREATED, + ) # This is the function to remove breakpoints from the dummy target # to get a clean state for the next test case. def cleanup(): - self.runCmd('breakpoint delete -D -f', check=False) - self.runCmd('breakpoint list', check=False) + self.runCmd("breakpoint delete -D -f", check=False) + self.runCmd("breakpoint list", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) diff --git a/lldb/test/API/functionalities/breakpoint/scripted_bkpt/resolver.py b/lldb/test/API/functionalities/breakpoint/scripted_bkpt/resolver.py --- a/lldb/test/API/functionalities/breakpoint/scripted_bkpt/resolver.py +++ b/lldb/test/API/functionalities/breakpoint/scripted_bkpt/resolver.py @@ -1,57 +1,62 @@ import lldb + class Resolver: - got_files = 0 - func_list = [] - - def __init__(self, bkpt, extra_args, dict): - self.bkpt = bkpt - self.extra_args = extra_args - - Resolver.func_list = [] - Resolver.got_files = 0 - - def __callback__(self, sym_ctx): - sym_name = "not_a_real_function_name" - sym_item = self.extra_args.GetValueForKey("symbol") - if sym_item.IsValid(): - sym_name = sym_item.GetStringValue(1000) - else: - print("Didn't have a value for key 'symbol'") - - if sym_ctx.compile_unit.IsValid(): - Resolver.got_files = 1 - else: - Resolver.got_files = 2 - - if sym_ctx.function.IsValid(): - Resolver.got_files = 3 - func_name = sym_ctx.function.GetName() - Resolver.func_list.append(func_name) - if sym_name == func_name: - self.bkpt.AddLocation(sym_ctx.function.GetStartAddress()) - return - - if sym_ctx.module.IsValid(): - sym = sym_ctx.module.FindSymbol(sym_name, lldb.eSymbolTypeCode) - if sym.IsValid(): - self.bkpt.AddLocation(sym.GetStartAddress()) - - def get_short_help(self): - return "I am a python breakpoint resolver" + got_files = 0 + func_list = [] + + def __init__(self, bkpt, extra_args, dict): + self.bkpt = bkpt + self.extra_args = extra_args + + Resolver.func_list = [] + Resolver.got_files = 0 + + def __callback__(self, sym_ctx): + sym_name = "not_a_real_function_name" + sym_item = self.extra_args.GetValueForKey("symbol") + if sym_item.IsValid(): + sym_name = sym_item.GetStringValue(1000) + else: + print("Didn't have a value for key 'symbol'") + + if sym_ctx.compile_unit.IsValid(): + Resolver.got_files = 1 + else: + Resolver.got_files = 2 + + if sym_ctx.function.IsValid(): + Resolver.got_files = 3 + func_name = sym_ctx.function.GetName() + Resolver.func_list.append(func_name) + if sym_name == func_name: + self.bkpt.AddLocation(sym_ctx.function.GetStartAddress()) + return + + if sym_ctx.module.IsValid(): + sym = sym_ctx.module.FindSymbol(sym_name, lldb.eSymbolTypeCode) + if sym.IsValid(): + self.bkpt.AddLocation(sym.GetStartAddress()) + + def get_short_help(self): + return "I am a python breakpoint resolver" + class ResolverModuleDepth(Resolver): - def __get_depth__ (self): + def __get_depth__(self): return lldb.eSearchDepthModule + class ResolverCUDepth(Resolver): - def __get_depth__ (self): + def __get_depth__(self): return lldb.eSearchDepthCompUnit + class ResolverFuncDepth(Resolver): - def __get_depth__ (self): + def __get_depth__(self): return lldb.eSearchDepthFunction + class ResolverBadDepth(Resolver): - def __get_depth__ (self): + def __get_depth__(self): return lldb.kLastSearchDepthKind + 1 diff --git a/lldb/test/API/functionalities/breakpoint/serialize/TestBreakpointSerialization.py b/lldb/test/API/functionalities/breakpoint/serialize/TestBreakpointSerialization.py --- a/lldb/test/API/functionalities/breakpoint/serialize/TestBreakpointSerialization.py +++ b/lldb/test/API/functionalities/breakpoint/serialize/TestBreakpointSerialization.py @@ -13,7 +13,7 @@ class BreakpointSerialization(TestBase): NO_DEBUG_INFO_TESTCASE = True - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) def test_resolvers(self): """Use Python APIs to test that we serialize resolvers.""" self.build() @@ -59,33 +59,44 @@ result = lldb.SBCommandReturnObject() interpreter.HandleCommand("br set -c 'argc == 1' -n main", result) - bkp1 = target.GetBreakpointAtIndex(0) + bkp1 = target.GetBreakpointAtIndex(0) self.assertTrue(bkp1.IsValid(), VALID_BREAKPOINT) stream = lldb.SBStream() sd = bkp1.SerializeToStructuredData() sd.GetAsJSON(stream) serialized_data = json.loads(stream.GetData()) - self.assertEqual(serialized_data["Breakpoint"]["BKPTResolver"]["Options"]["FileName"], "foo") - self.assertEqual(serialized_data["Breakpoint"]["BKPTResolver"]["Options"]["LineNumber"], 42) - - bkp2 = target.GetBreakpointAtIndex(1) + self.assertEqual( + serialized_data["Breakpoint"]["BKPTResolver"]["Options"]["FileName"], "foo" + ) + self.assertEqual( + serialized_data["Breakpoint"]["BKPTResolver"]["Options"]["LineNumber"], 42 + ) + + bkp2 = target.GetBreakpointAtIndex(1) self.assertTrue(bkp2.IsValid(), VALID_BREAKPOINT) stream = lldb.SBStream() sd = bkp2.SerializeToStructuredData() sd.GetAsJSON(stream) serialized_data = json.loads(stream.GetData()) - self.assertIn("main", serialized_data["Breakpoint"]["BKPTResolver"]["Options"]["SymbolNames"]) - self.assertEqual(serialized_data["Breakpoint"]["BKPTOptions"]["ConditionText"],"argc == 1") + self.assertIn( + "main", + serialized_data["Breakpoint"]["BKPTResolver"]["Options"]["SymbolNames"], + ) + self.assertEqual( + serialized_data["Breakpoint"]["BKPTOptions"]["ConditionText"], "argc == 1" + ) invalid_bkp = lldb.SBBreakpoint() self.assertFalse(invalid_bkp.IsValid(), "Breakpoint should not be valid.") stream = lldb.SBStream() sd = invalid_bkp.SerializeToStructuredData() sd.GetAsJSON(stream) - self.assertFalse(stream.GetData(), "Invalid breakpoint should have an empty structured data") + self.assertFalse( + stream.GetData(), "Invalid breakpoint should have an empty structured data" + ) def setup_targets_and_cleanup(self): - def cleanup (): + def cleanup(): self.RemoveTempFile(self.bkpts_file_path) if self.orig_target.IsValid(): @@ -111,21 +122,29 @@ self.bkpts_file_path = self.getBuildArtifact("breakpoints.json") self.bkpts_file_spec = lldb.SBFileSpec(self.bkpts_file_path) - def check_equivalence(self, source_bps, do_write = True): - + def check_equivalence(self, source_bps, do_write=True): error = lldb.SBError() - if (do_write): - error = self.orig_target.BreakpointsWriteToFile(self.bkpts_file_spec, source_bps) + if do_write: + error = self.orig_target.BreakpointsWriteToFile( + self.bkpts_file_spec, source_bps + ) self.assertSuccess(error, "Failed writing breakpoints to file") copy_bps = lldb.SBBreakpointList(self.copy_target) - error = self.copy_target.BreakpointsCreateFromFile(self.bkpts_file_spec, copy_bps) + error = self.copy_target.BreakpointsCreateFromFile( + self.bkpts_file_spec, copy_bps + ) self.assertSuccess(error, "Failed reading breakpoints from file") num_source_bps = source_bps.GetSize() num_copy_bps = copy_bps.GetSize() - self.assertEqual(num_source_bps, num_copy_bps, "Didn't get same number of input and output breakpoints - orig: %d copy: %d"%(num_source_bps, num_copy_bps)) + self.assertEqual( + num_source_bps, + num_copy_bps, + "Didn't get same number of input and output breakpoints - orig: %d copy: %d" + % (num_source_bps, num_copy_bps), + ) for i in range(0, num_source_bps): source_bp = source_bps.GetBreakpointAtIndex(i) @@ -139,22 +158,31 @@ # see which one is which. copy_id = source_bp.GetID() copy_bp = copy_bps.FindBreakpointByID(copy_id) - self.assertTrue(copy_bp.IsValid(), "Could not find copy breakpoint %d."%(copy_id)) + self.assertTrue( + copy_bp.IsValid(), "Could not find copy breakpoint %d." % (copy_id) + ) copy_desc = lldb.SBStream() copy_bp.GetDescription(copy_desc, False) copy_text = copy_desc.GetData() # These two should be identical. - self.trace("Source text for %d is %s."%(i, source_text)) - self.assertEqual(source_text, copy_text, "Source and dest breakpoints are not identical: \nsource: %s\ndest: %s"%(source_text, copy_text)) + self.trace("Source text for %d is %s." % (i, source_text)) + self.assertEqual( + source_text, + copy_text, + "Source and dest breakpoints are not identical: \nsource: %s\ndest: %s" + % (source_text, copy_text), + ) def do_check_resolvers(self): """Use Python APIs to check serialization of breakpoint resolvers""" empty_module_list = lldb.SBFileSpecList() empty_cu_list = lldb.SBFileSpecList() - blubby_file_spec = lldb.SBFileSpec(os.path.join(self.getSourceDir(), "blubby.c")) + blubby_file_spec = lldb.SBFileSpec( + os.path.join(self.getSourceDir(), "blubby.c") + ) # It isn't actually important for these purposes that these breakpoint # actually have locations. @@ -164,9 +192,21 @@ self.check_equivalence(source_bps) source_bps.Clear() - source_bps.Append(self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeAuto, empty_module_list, empty_cu_list)) - source_bps.Append(self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeFull, empty_module_list,empty_cu_list)) - source_bps.Append(self.orig_target.BreakpointCreateBySourceRegex("dont really care", blubby_file_spec)) + source_bps.Append( + self.orig_target.BreakpointCreateByName( + "blubby", lldb.eFunctionNameTypeAuto, empty_module_list, empty_cu_list + ) + ) + source_bps.Append( + self.orig_target.BreakpointCreateByName( + "blubby", lldb.eFunctionNameTypeFull, empty_module_list, empty_cu_list + ) + ) + source_bps.Append( + self.orig_target.BreakpointCreateBySourceRegex( + "dont really care", blubby_file_spec + ) + ) # And some number greater than one: self.check_equivalence(source_bps) @@ -182,23 +222,33 @@ cu_list.Append(lldb.SBFileSpec("AnotherCU.c")) cu_list.Append(lldb.SBFileSpec("ThirdCU.c")) - blubby_file_spec = lldb.SBFileSpec(os.path.join(self.getSourceDir(), "blubby.c")) + blubby_file_spec = lldb.SBFileSpec( + os.path.join(self.getSourceDir(), "blubby.c") + ) # It isn't actually important for these purposes that these breakpoint # actually have locations. source_bps = lldb.SBBreakpointList(self.orig_target) - bkpt = self.orig_target.BreakpointCreateByLocation(blubby_file_spec, 666, 0, module_list) + bkpt = self.orig_target.BreakpointCreateByLocation( + blubby_file_spec, 666, 0, module_list + ) source_bps.Append(bkpt) # Make sure we do one right: self.check_equivalence(source_bps) source_bps.Clear() - bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeAuto, module_list, cu_list) + bkpt = self.orig_target.BreakpointCreateByName( + "blubby", lldb.eFunctionNameTypeAuto, module_list, cu_list + ) source_bps.Append(bkpt) - bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeFull, module_list, cu_list) + bkpt = self.orig_target.BreakpointCreateByName( + "blubby", lldb.eFunctionNameTypeFull, module_list, cu_list + ) source_bps.Append(bkpt) - bkpt = self.orig_target.BreakpointCreateBySourceRegex("dont really care", blubby_file_spec) + bkpt = self.orig_target.BreakpointCreateBySourceRegex( + "dont really care", blubby_file_spec + ) source_bps.Append(bkpt) # And some number greater than one: @@ -209,14 +259,17 @@ empty_module_list = lldb.SBFileSpecList() empty_cu_list = lldb.SBFileSpecList() - blubby_file_spec = lldb.SBFileSpec(os.path.join(self.getSourceDir(), "blubby.c")) + blubby_file_spec = lldb.SBFileSpec( + os.path.join(self.getSourceDir(), "blubby.c") + ) # It isn't actually important for these purposes that these breakpoint # actually have locations. source_bps = lldb.SBBreakpointList(self.orig_target) bkpt = self.orig_target.BreakpointCreateByLocation( - lldb.SBFileSpec("blubby.c"), 666, 333, 0, lldb.SBFileSpecList()) + lldb.SBFileSpec("blubby.c"), 666, 333, 0, lldb.SBFileSpecList() + ) bkpt.SetEnabled(False) bkpt.SetOneShot(True) bkpt.SetThreadID(10) @@ -226,25 +279,35 @@ self.check_equivalence(source_bps) source_bps.Clear() - bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeAuto, empty_module_list, empty_cu_list) + bkpt = self.orig_target.BreakpointCreateByName( + "blubby", lldb.eFunctionNameTypeAuto, empty_module_list, empty_cu_list + ) bkpt.SetIgnoreCount(10) bkpt.SetThreadName("grubby") source_bps.Append(bkpt) - bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeAuto, empty_module_list, empty_cu_list) + bkpt = self.orig_target.BreakpointCreateByName( + "blubby", lldb.eFunctionNameTypeAuto, empty_module_list, empty_cu_list + ) bkpt.SetCondition("gonna remove this") bkpt.SetCondition("") source_bps.Append(bkpt) - bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeFull, empty_module_list,empty_cu_list) + bkpt = self.orig_target.BreakpointCreateByName( + "blubby", lldb.eFunctionNameTypeFull, empty_module_list, empty_cu_list + ) bkpt.SetCondition("something != something_else") bkpt.SetQueueName("grubby") bkpt.AddName("FirstName") bkpt.AddName("SecondName") - bkpt.SetScriptCallbackBody('\tprint("I am a function that prints.")\n\tprint("I don\'t do anything else")\n') + bkpt.SetScriptCallbackBody( + '\tprint("I am a function that prints.")\n\tprint("I don\'t do anything else")\n' + ) source_bps.Append(bkpt) - bkpt = self.orig_target.BreakpointCreateBySourceRegex("dont really care", blubby_file_spec) + bkpt = self.orig_target.BreakpointCreateBySourceRegex( + "dont really care", blubby_file_spec + ) cmd_list = lldb.SBStringList() cmd_list.AppendString("frame var") cmd_list.AppendString("thread backtrace") @@ -259,7 +322,9 @@ empty_module_list = lldb.SBFileSpecList() empty_cu_list = lldb.SBFileSpecList() - blubby_file_spec = lldb.SBFileSpec(os.path.join(self.getSourceDir(), "blubby.c")) + blubby_file_spec = lldb.SBFileSpec( + os.path.join(self.getSourceDir(), "blubby.c") + ) # It isn't actually important for these purposes that these breakpoint # actually have locations. @@ -268,7 +333,8 @@ source_bps = lldb.SBBreakpointList(self.orig_target) bkpt = self.orig_target.BreakpointCreateByLocation( - lldb.SBFileSpec("blubby.c"), 666, 333, 0, lldb.SBFileSpecList()) + lldb.SBFileSpec("blubby.c"), 666, 333, 0, lldb.SBFileSpecList() + ) bkpt.SetEnabled(False) bkpt.SetOneShot(True) bkpt.SetThreadID(10) @@ -276,18 +342,24 @@ all_bps.Append(bkpt) error = lldb.SBError() - error = self.orig_target.BreakpointsWriteToFile(self.bkpts_file_spec, source_bps) + error = self.orig_target.BreakpointsWriteToFile( + self.bkpts_file_spec, source_bps + ) self.assertSuccess(error, "Failed writing breakpoints to file") source_bps.Clear() - bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeAuto, empty_module_list, empty_cu_list) + bkpt = self.orig_target.BreakpointCreateByName( + "blubby", lldb.eFunctionNameTypeAuto, empty_module_list, empty_cu_list + ) bkpt.SetIgnoreCount(10) bkpt.SetThreadName("grubby") source_bps.Append(bkpt) all_bps.Append(bkpt) - bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeFull, empty_module_list,empty_cu_list) + bkpt = self.orig_target.BreakpointCreateByName( + "blubby", lldb.eFunctionNameTypeFull, empty_module_list, empty_cu_list + ) bkpt.SetCondition("something != something_else") bkpt.SetQueueName("grubby") bkpt.AddName("FirstName") @@ -296,14 +368,17 @@ source_bps.Append(bkpt) all_bps.Append(bkpt) - error = self.orig_target.BreakpointsWriteToFile(self.bkpts_file_spec, source_bps, True) + error = self.orig_target.BreakpointsWriteToFile( + self.bkpts_file_spec, source_bps, True + ) self.assertSuccess(error, "Failed appending breakpoints to file") self.check_equivalence(all_bps) def do_check_names(self): bkpt = self.orig_target.BreakpointCreateByLocation( - lldb.SBFileSpec("blubby.c"), 666, 333, 0, lldb.SBFileSpecList()) + lldb.SBFileSpec("blubby.c"), 666, 333, 0, lldb.SBFileSpecList() + ) good_bkpt_name = "GoodBreakpoint" write_bps = lldb.SBBreakpointList(self.orig_target) bkpt.AddName(good_bkpt_name) @@ -317,18 +392,24 @@ names_list = lldb.SBStringList() names_list.AppendString("NoSuchName") - error = self.copy_target.BreakpointsCreateFromFile(self.bkpts_file_spec, names_list, copy_bps) + error = self.copy_target.BreakpointsCreateFromFile( + self.bkpts_file_spec, names_list, copy_bps + ) self.assertSuccess(error, "Failed reading breakpoints from file") - self.assertEqual(copy_bps.GetSize(), 0, "Found breakpoints with a nonexistent name.") + self.assertEqual( + copy_bps.GetSize(), 0, "Found breakpoints with a nonexistent name." + ) names_list.AppendString(good_bkpt_name) - error = self.copy_target.BreakpointsCreateFromFile(self.bkpts_file_spec, names_list, copy_bps) + error = self.copy_target.BreakpointsCreateFromFile( + self.bkpts_file_spec, names_list, copy_bps + ) self.assertSuccess(error, "Failed reading breakpoints from file") self.assertEqual(copy_bps.GetSize(), 1, "Found the matching breakpoint.") def do_check_extra_args(self): - import side_effect + interp = self.dbg.GetCommandInterpreter() error = lldb.SBError() @@ -337,11 +418,17 @@ command = "command script import " + script_name result = lldb.SBCommandReturnObject() interp.HandleCommand(command, result) - self.assertTrue(result.Succeeded(), "com scr imp failed: %s"%(result.GetError())) + self.assertTrue( + result.Succeeded(), "com scr imp failed: %s" % (result.GetError()) + ) # First make sure a scripted breakpoint with no args works: - bkpt = self.orig_target.BreakpointCreateFromScript("resolver.Resolver", lldb.SBStructuredData(), - lldb.SBFileSpecList(), lldb.SBFileSpecList()) + bkpt = self.orig_target.BreakpointCreateFromScript( + "resolver.Resolver", + lldb.SBStructuredData(), + lldb.SBFileSpecList(), + lldb.SBFileSpecList(), + ) self.assertTrue(bkpt.IsValid(), "Bkpt is valid") write_bps = lldb.SBBreakpointList(self.orig_target) @@ -350,7 +437,9 @@ side_effect.g_extra_args = None copy_bps = lldb.SBBreakpointList(self.copy_target) - error = self.copy_target.BreakpointsCreateFromFile(self.bkpts_file_spec, copy_bps) + error = self.copy_target.BreakpointsCreateFromFile( + self.bkpts_file_spec, copy_bps + ) self.assertSuccess(error, "Failed reading breakpoints") self.assertEqual(copy_bps.GetSize(), 1, "Got one breakpoint from file.") @@ -369,8 +458,12 @@ extra_args.SetFromJSON(stream) self.assertTrue(extra_args.IsValid(), "SBStructuredData is valid.") - bkpt = self.orig_target.BreakpointCreateFromScript("resolver.Resolver", - extra_args, lldb.SBFileSpecList(), lldb.SBFileSpecList()) + bkpt = self.orig_target.BreakpointCreateFromScript( + "resolver.Resolver", + extra_args, + lldb.SBFileSpecList(), + lldb.SBFileSpecList(), + ) self.assertTrue(bkpt.IsValid(), "Bkpt is valid") write_bps = lldb.SBBreakpointList(self.orig_target) @@ -387,7 +480,9 @@ side_effect.g_extra_args = None copy_bps = lldb.SBBreakpointList(self.copy_target) - error = self.copy_target.BreakpointsCreateFromFile(self.bkpts_file_spec, copy_bps) + error = self.copy_target.BreakpointsCreateFromFile( + self.bkpts_file_spec, copy_bps + ) self.assertSuccess(error, "Failed reading breakpoints") self.assertEqual(copy_bps.GetSize(), 1, "Got one breakpoint from file.") @@ -406,4 +501,4 @@ elif key == "second_arg": self.assertEqual(copy_value, "second_value") else: - self.Fail("Unknown key: %s"%(key)) + self.Fail("Unknown key: %s" % (key)) diff --git a/lldb/test/API/functionalities/breakpoint/serialize/resolver.py b/lldb/test/API/functionalities/breakpoint/serialize/resolver.py --- a/lldb/test/API/functionalities/breakpoint/serialize/resolver.py +++ b/lldb/test/API/functionalities/breakpoint/serialize/resolver.py @@ -1,17 +1,17 @@ import lldb import side_effect + class Resolver: - """This resolver class is just so I can read out the extra_args.""" - - def __init__(self, bkpt, extra_args, dict): - self.bkpt = bkpt - side_effect.g_extra_args = extra_args - - def __callback__(self, sym_ctx): - """Doesn't actually do anything.""" - return + """This resolver class is just so I can read out the extra_args.""" + + def __init__(self, bkpt, extra_args, dict): + self.bkpt = bkpt + side_effect.g_extra_args = extra_args - def get_short_help(self): - return "I am a python breakpoint resolver that does nothing" + def __callback__(self, sym_ctx): + """Doesn't actually do anything.""" + return + def get_short_help(self): + return "I am a python breakpoint resolver that does nothing" diff --git a/lldb/test/API/functionalities/breakpoint/source_regexp/TestSourceRegexBreakpoints.py b/lldb/test/API/functionalities/breakpoint/source_regexp/TestSourceRegexBreakpoints.py --- a/lldb/test/API/functionalities/breakpoint/source_regexp/TestSourceRegexBreakpoints.py +++ b/lldb/test/API/functionalities/breakpoint/source_regexp/TestSourceRegexBreakpoints.py @@ -11,7 +11,6 @@ class TestSourceRegexBreakpoints(TestBase): - def test_location(self): self.build() self.source_regex_locations() @@ -21,7 +20,7 @@ self.source_regex_restrictions() def source_regex_locations(self): - """ Test that restricting source expressions to files & to functions. """ + """Test that restricting source expressions to files & to functions.""" # Create a target by the debugger. exe = self.getBuildArtifact("a.out") target = self.dbg.CreateTarget(exe) @@ -36,28 +35,31 @@ source_regex = "Set . breakpoint here" main_break = target.BreakpointCreateBySourceRegex( - source_regex, lldb.SBFileSpecList(), target_files, func_names) + source_regex, lldb.SBFileSpecList(), target_files, func_names + ) num_locations = main_break.GetNumLocations() self.assertEqual( - num_locations, 1, - "a.c in a_func should give one breakpoint, got %d." % - (num_locations)) + num_locations, + 1, + "a.c in a_func should give one breakpoint, got %d." % (num_locations), + ) loc = main_break.GetLocationAtIndex(0) self.assertTrue(loc.IsValid(), "Got a valid location.") address = loc.GetAddress() - self.assertTrue( - address.IsValid(), - "Got a valid address from the location.") + self.assertTrue(address.IsValid(), "Got a valid address from the location.") a_func_line = line_number("a.c", "Set A breakpoint here") line_entry = address.GetLineEntry() self.assertTrue(line_entry.IsValid(), "Got a valid line entry.") - self.assertEquals(line_entry.line, a_func_line, - "Our line number matches the one lldbtest found.") + self.assertEquals( + line_entry.line, + a_func_line, + "Our line number matches the one lldbtest found.", + ) def source_regex_restrictions(self): - """ Test that restricting source expressions to files & to functions. """ + """Test that restricting source expressions to files & to functions.""" # Create a target by the debugger. exe = self.getBuildArtifact("a.out") target = self.dbg.CreateTarget(exe) @@ -68,34 +70,39 @@ target_files.Append(lldb.SBFileSpec("main.c")) source_regex = "Set . breakpoint here" main_break = target.BreakpointCreateBySourceRegex( - source_regex, lldb.SBFileSpecList(), target_files, lldb.SBStringList()) + source_regex, lldb.SBFileSpecList(), target_files, lldb.SBStringList() + ) num_locations = main_break.GetNumLocations() self.assertEqual( - num_locations, 2, - "main.c should have 2 matches, got %d." % - (num_locations)) + num_locations, 2, "main.c should have 2 matches, got %d." % (num_locations) + ) # Now look in both files: target_files.Append(lldb.SBFileSpec("a.c")) main_break = target.BreakpointCreateBySourceRegex( - source_regex, lldb.SBFileSpecList(), target_files, lldb.SBStringList()) + source_regex, lldb.SBFileSpecList(), target_files, lldb.SBStringList() + ) num_locations = main_break.GetNumLocations() self.assertEqual( - num_locations, 4, - "main.c and a.c should have 4 matches, got %d." % - (num_locations)) + num_locations, + 4, + "main.c and a.c should have 4 matches, got %d." % (num_locations), + ) # Now restrict it to functions: func_names = lldb.SBStringList() func_names.AppendString("main_func") main_break = target.BreakpointCreateBySourceRegex( - source_regex, lldb.SBFileSpecList(), target_files, func_names) + source_regex, lldb.SBFileSpecList(), target_files, func_names + ) num_locations = main_break.GetNumLocations() self.assertEqual( - num_locations, 2, - "main_func in main.c and a.c should have 2 matches, got %d." % - (num_locations)) + num_locations, + 2, + "main_func in main.c and a.c should have 2 matches, got %d." + % (num_locations), + ) diff --git a/lldb/test/API/functionalities/breakpoint/step_over_breakpoint/TestStepOverBreakpoint.py b/lldb/test/API/functionalities/breakpoint/step_over_breakpoint/TestStepOverBreakpoint.py --- a/lldb/test/API/functionalities/breakpoint/step_over_breakpoint/TestStepOverBreakpoint.py +++ b/lldb/test/API/functionalities/breakpoint/step_over_breakpoint/TestStepOverBreakpoint.py @@ -11,8 +11,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class StepOverBreakpointsTestCase(TestBase): +class StepOverBreakpointsTestCase(TestBase): def setUp(self): TestBase.setUp(self) @@ -25,32 +25,40 @@ self.assertTrue(self.target, VALID_TARGET) # Setup four breakpoints, two of them with false condition - self.line1 = line_number('main.cpp', "breakpoint_1") - self.line4 = line_number('main.cpp', "breakpoint_4") + self.line1 = line_number("main.cpp", "breakpoint_1") + self.line4 = line_number("main.cpp", "breakpoint_4") self.breakpoint1 = self.target.BreakpointCreateByLocation(src, self.line1) self.assertTrue( self.breakpoint1 and self.breakpoint1.GetNumLocations() == 1, - VALID_BREAKPOINT) + VALID_BREAKPOINT, + ) - self.breakpoint2 = self.target.BreakpointCreateBySourceRegex("breakpoint_2", src) - self.breakpoint2.GetLocationAtIndex(0).SetCondition('false') + self.breakpoint2 = self.target.BreakpointCreateBySourceRegex( + "breakpoint_2", src + ) + self.breakpoint2.GetLocationAtIndex(0).SetCondition("false") - self.breakpoint3 = self.target.BreakpointCreateBySourceRegex("breakpoint_3", src) - self.breakpoint3.GetLocationAtIndex(0).SetCondition('false') + self.breakpoint3 = self.target.BreakpointCreateBySourceRegex( + "breakpoint_3", src + ) + self.breakpoint3.GetLocationAtIndex(0).SetCondition("false") self.breakpoint4 = self.target.BreakpointCreateByLocation(src, self.line4) # Start debugging self.process = self.target.LaunchSimple( - None, None, self.get_process_working_directory()) + None, None, self.get_process_working_directory() + ) self.assertIsNotNone(self.process, PROCESS_IS_VALID) - self.thread = lldbutil.get_one_thread_stopped_at_breakpoint(self.process, self.breakpoint1) + self.thread = lldbutil.get_one_thread_stopped_at_breakpoint( + self.process, self.breakpoint1 + ) self.assertIsNotNone(self.thread, "Didn't stop at breakpoint 1.") def test_step_instruction(self): # Count instructions between breakpoint_1 and breakpoint_4 - contextList = self.target.FindFunctions('main', lldb.eFunctionNameTypeAuto) + contextList = self.target.FindFunctions("main", lldb.eFunctionNameTypeAuto) self.assertEquals(contextList.GetSize(), 1) symbolContext = contextList.GetContextAtIndex(0) function = symbolContext.GetFunction() @@ -69,11 +77,15 @@ self.thread.StepInstruction(True) step_count = step_count + 1 self.assertState(self.process.GetState(), lldb.eStateStopped) - self.assertTrue(self.thread.GetStopReason() == lldb.eStopReasonPlanComplete or - self.thread.GetStopReason() == lldb.eStopReasonBreakpoint) - if (self.thread.GetStopReason() == lldb.eStopReasonBreakpoint) : + self.assertTrue( + self.thread.GetStopReason() == lldb.eStopReasonPlanComplete + or self.thread.GetStopReason() == lldb.eStopReasonBreakpoint + ) + if self.thread.GetStopReason() == lldb.eStopReasonBreakpoint: # we should not stop on breakpoint_2 and _3 because they have false condition - self.assertEquals(self.thread.GetFrameAtIndex(0).GetLineEntry().GetLine(), self.line4) + self.assertEquals( + self.thread.GetFrameAtIndex(0).GetLineEntry().GetLine(), self.line4 + ) # breakpoint_2 and _3 should not affect step count self.assertTrue(step_count >= steps_expected) break @@ -84,7 +96,6 @@ @skipIf(bugnumber="llvm.org/pr31972", hostoslist=["windows"]) def test_step_over(self): - self.thread.StepOver() # We should be stopped at the breakpoint_2 line with stop plan complete reason self.assertState(self.process.GetState(), lldb.eStateStopped) @@ -99,7 +110,9 @@ # We should be stopped at the breakpoint_4 self.assertState(self.process.GetState(), lldb.eStateStopped) self.assertStopReason(self.thread.GetStopReason(), lldb.eStopReasonBreakpoint) - thread1 = lldbutil.get_one_thread_stopped_at_breakpoint(self.process, self.breakpoint4) + thread1 = lldbutil.get_one_thread_stopped_at_breakpoint( + self.process, self.breakpoint4 + ) self.assertEquals(self.thread, thread1, "Didn't stop at breakpoint 4.") # Check that stepping does not affect breakpoint's hit count @@ -111,4 +124,3 @@ # Run the process until termination self.process.Continue() self.assertState(self.process.GetState(), lldb.eStateExited) - diff --git a/lldb/test/API/functionalities/breakpoint/thread_plan_user_breakpoint/TestThreadPlanUserBreakpoint.py b/lldb/test/API/functionalities/breakpoint/thread_plan_user_breakpoint/TestThreadPlanUserBreakpoint.py --- a/lldb/test/API/functionalities/breakpoint/thread_plan_user_breakpoint/TestThreadPlanUserBreakpoint.py +++ b/lldb/test/API/functionalities/breakpoint/thread_plan_user_breakpoint/TestThreadPlanUserBreakpoint.py @@ -14,34 +14,46 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class ThreadPlanUserBreakpointsTestCase(TestBase): +class ThreadPlanUserBreakpointsTestCase(TestBase): def setUp(self): TestBase.setUp(self) # Build and run to starting breakpoint self.build() - src = lldb.SBFileSpec('main.cpp') - (self.target, self.process, self.thread, _) = \ - lldbutil.run_to_source_breakpoint(self, '// Start from here', src) + src = lldb.SBFileSpec("main.cpp") + (self.target, self.process, self.thread, _) = lldbutil.run_to_source_breakpoint( + self, "// Start from here", src + ) # Setup two more breakpoints - self.breakpoints = [self.target.BreakpointCreateBySourceRegex('breakpoint_%i' % i, src) - for i in range(2)] + self.breakpoints = [ + self.target.BreakpointCreateBySourceRegex("breakpoint_%i" % i, src) + for i in range(2) + ] self.assertTrue( all(bp and bp.GetNumLocations() == 1 for bp in self.breakpoints), - VALID_BREAKPOINT) + VALID_BREAKPOINT, + ) def check_correct_stop_reason(self, breakpoint_idx, condition): self.assertState(self.process.GetState(), lldb.eStateStopped) if condition: # All breakpoints active, stop reason is breakpoint - thread1 = lldbutil.get_one_thread_stopped_at_breakpoint(self.process, self.breakpoints[breakpoint_idx]) - self.assertEquals(self.thread, thread1, "Didn't stop at breakpoint %i." % breakpoint_idx) + thread1 = lldbutil.get_one_thread_stopped_at_breakpoint( + self.process, self.breakpoints[breakpoint_idx] + ) + self.assertEquals( + self.thread, thread1, "Didn't stop at breakpoint %i." % breakpoint_idx + ) else: # Breakpoints are inactive, stop reason is plan complete - self.assertEquals(self.thread.GetStopReason(), lldb.eStopReasonPlanComplete, - 'Expected stop reason to be step into/over/out for inactive breakpoint %i line.' % breakpoint_idx) + self.assertEquals( + self.thread.GetStopReason(), + lldb.eStopReasonPlanComplete, + "Expected stop reason to be step into/over/out for inactive breakpoint %i line." + % breakpoint_idx, + ) def change_breakpoints(self, action): for bp in self.breakpoints: @@ -79,7 +91,7 @@ def set_up_breakpoints_condition(self, condition, bp): # Set breakpoint condition to true/false - conditionStr = 'true' if condition else 'false' + conditionStr = "true" if condition else "false" bp.SetCondition(conditionStr) def set_up_breakpoints_enable(self, condition, bp): @@ -88,34 +100,40 @@ def set_up_breakpoints_callback(self, condition, bp): # Set breakpoint callback to return True/False - bp.SetScriptCallbackBody('return %s' % condition) + bp.SetScriptCallbackBody("return %s" % condition) def test_thread_plan_user_breakpoint_conditional_active(self): # Test with breakpoints having true condition - self.check_thread_plan_user_breakpoint(condition=True, - set_up_breakpoint_func=self.set_up_breakpoints_condition) + self.check_thread_plan_user_breakpoint( + condition=True, set_up_breakpoint_func=self.set_up_breakpoints_condition + ) def test_thread_plan_user_breakpoint_conditional_inactive(self): # Test with breakpoints having false condition - self.check_thread_plan_user_breakpoint(condition=False, - set_up_breakpoint_func=self.set_up_breakpoints_condition) + self.check_thread_plan_user_breakpoint( + condition=False, set_up_breakpoint_func=self.set_up_breakpoints_condition + ) def test_thread_plan_user_breakpoint_unconditional_active(self): # Test with breakpoints enabled unconditionally - self.check_thread_plan_user_breakpoint(condition=True, - set_up_breakpoint_func=self.set_up_breakpoints_enable) + self.check_thread_plan_user_breakpoint( + condition=True, set_up_breakpoint_func=self.set_up_breakpoints_enable + ) def test_thread_plan_user_breakpoint_unconditional_inactive(self): # Test with breakpoints disabled unconditionally - self.check_thread_plan_user_breakpoint(condition=False, - set_up_breakpoint_func=self.set_up_breakpoints_enable) + self.check_thread_plan_user_breakpoint( + condition=False, set_up_breakpoint_func=self.set_up_breakpoints_enable + ) def test_thread_plan_user_breakpoint_callback_active(self): # Test with breakpoints with callback that returns 'True' - self.check_thread_plan_user_breakpoint(condition=True, - set_up_breakpoint_func=self.set_up_breakpoints_callback) + self.check_thread_plan_user_breakpoint( + condition=True, set_up_breakpoint_func=self.set_up_breakpoints_callback + ) def test_thread_plan_user_breakpoint_callback_inactive(self): # Test with breakpoints with callback that returns 'False' - self.check_thread_plan_user_breakpoint(condition=False, - set_up_breakpoint_func=self.set_up_breakpoints_callback) + self.check_thread_plan_user_breakpoint( + condition=False, set_up_breakpoint_func=self.set_up_breakpoints_callback + ) diff --git a/lldb/test/API/functionalities/breakpoint/two_hits_one_actual/TestTwoHitsOneActual.py b/lldb/test/API/functionalities/breakpoint/two_hits_one_actual/TestTwoHitsOneActual.py --- a/lldb/test/API/functionalities/breakpoint/two_hits_one_actual/TestTwoHitsOneActual.py +++ b/lldb/test/API/functionalities/breakpoint/two_hits_one_actual/TestTwoHitsOneActual.py @@ -12,7 +12,6 @@ class TestTwoHitsOneActual(TestBase): - NO_DEBUG_INFO_TESTCASE = True @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) @@ -25,8 +24,9 @@ def sample_test(self): """You might use the test implementation in several ways, say so here.""" - (target, process, main_thread, _) = lldbutil.run_to_source_breakpoint(self, - "Set bkpt here to get started", self.main_source_file) + (target, process, main_thread, _) = lldbutil.run_to_source_breakpoint( + self, "Set bkpt here to get started", self.main_source_file + ) # This is working around a separate bug. If you hit a breakpoint and # run an expression and it is the first expression you've ever run, on # Darwin that will involve running the ObjC runtime parsing code, and we'll @@ -37,8 +37,12 @@ self.assertSuccess(val_obj.GetError(), "Ran our expression successfully") self.assertEqual(val_obj.value, "true", "Value was true.") # Set two breakpoints just to test the multiple location logic: - bkpt1 = target.BreakpointCreateBySourceRegex("Break here in the helper", self.main_source_file); - bkpt2 = target.BreakpointCreateBySourceRegex("Break here in the helper", self.main_source_file); + bkpt1 = target.BreakpointCreateBySourceRegex( + "Break here in the helper", self.main_source_file + ) + bkpt2 = target.BreakpointCreateBySourceRegex( + "Break here in the helper", self.main_source_file + ) # This one will never be hit: bkpt1.SetCondition("usec == 100") @@ -57,8 +61,8 @@ process.Continue() for thread in process.threads: if thread.id == main_thread.id: - self.assertStopReason(thread.stop_reason, lldb.eStopReasonBreakpoint) + self.assertStopReason( + thread.stop_reason, lldb.eStopReasonBreakpoint + ) else: self.assertStopReason(thread.stop_reason, lldb.eStopReasonNone) - - diff --git a/lldb/test/API/functionalities/bt-interrupt/TestInterruptBacktrace.py b/lldb/test/API/functionalities/bt-interrupt/TestInterruptBacktrace.py --- a/lldb/test/API/functionalities/bt-interrupt/TestInterruptBacktrace.py +++ b/lldb/test/API/functionalities/bt-interrupt/TestInterruptBacktrace.py @@ -8,32 +8,34 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * -class TestInterruptingBacktrace(TestBase): +class TestInterruptingBacktrace(TestBase): NO_DEBUG_INFO_TESTCASE = True @skipIf(oslist=["linux"], archs=["arm"]) def test_backtrace_interrupt(self): """Use RequestInterrupt followed by stack operations - to ensure correct interrupt behavior for stacks.""" + to ensure correct interrupt behavior for stacks.""" self.build() self.main_source_file = lldb.SBFileSpec("main.c") self.bt_interrupt_test() def bt_interrupt_test(self): - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - "Set a breakpoint here", self.main_source_file) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", self.main_source_file + ) # Now continue, and when we stop we will have crashed. process.Continue() self.dbg.RequestInterrupt() # Be sure to turn this off again: - def cleanup (): + def cleanup(): if self.dbg.InterruptRequested(): self.dbg.CancelInterruptRequest() + self.addTearDownHook(cleanup) - + frame_0 = thread.GetFrameAtIndex(0) self.assertTrue(frame_0.IsValid(), "Got a good 0th frame") # The interrupt flag is up already, so any attempt to backtrace @@ -44,7 +46,5 @@ num_frames = thread.GetNumFrames() print(f"Number of frames: {num_frames}") self.assertGreater(num_frames, 1, "Got many frames") - - self.dbg.CancelInterruptRequest() - + self.dbg.CancelInterruptRequest() diff --git a/lldb/test/API/functionalities/completion/TestCompletion.py b/lldb/test/API/functionalities/completion/TestCompletion.py --- a/lldb/test/API/functionalities/completion/TestCompletion.py +++ b/lldb/test/API/functionalities/completion/TestCompletion.py @@ -3,7 +3,6 @@ """ - import os from multiprocessing import Process import lldb @@ -14,7 +13,6 @@ class CommandLineCompletionTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True @classmethod @@ -28,106 +26,103 @@ def test_at(self): """Test that 'at' completes to 'attach '.""" - self.complete_from_to('at', 'attach ') + self.complete_from_to("at", "attach ") def test_de(self): """Test that 'de' completes to 'detach '.""" - self.complete_from_to('de', 'detach ') + self.complete_from_to("de", "detach ") def test_frame_variable(self): self.build() _, process, _, _ = lldbutil.run_to_source_breakpoint( - self, '// Break here', lldb.SBFileSpec("main.cpp")) + self, "// Break here", lldb.SBFileSpec("main.cpp") + ) self.assertState(process.GetState(), lldb.eStateStopped) # Since CommandInterpreter has been corrected to update the current execution # context at the beginning of HandleCompletion, we're here explicitly testing # the scenario where "frame var" is completed without any preceding commands. - self.do_test_variable_completion('frame variable') + self.do_test_variable_completion("frame variable") def test_dwim_print(self): self.build() _, process, _, _ = lldbutil.run_to_source_breakpoint( - self, '// Break here', lldb.SBFileSpec("main.cpp")) + self, "// Break here", lldb.SBFileSpec("main.cpp") + ) self.assertState(process.GetState(), lldb.eStateStopped) # Since CommandInterpreter has been corrected to update the current execution # context at the beginning of HandleCompletion, we're here explicitly testing # the scenario where "frame var" is completed without any preceding commands. - self.do_test_variable_completion('dwim-print') - + self.do_test_variable_completion("dwim-print") def do_test_variable_completion(self, command): - self.complete_from_to(f'{command} fo', - f'{command} fooo') - self.complete_from_to(f'{command} fooo.', - f'{command} fooo.') - self.complete_from_to(f'{command} fooo.dd', - f'{command} fooo.dd') - - self.complete_from_to(f'{command} ptr_fooo->', - f'{command} ptr_fooo->') - self.complete_from_to(f'{command} ptr_fooo->dd', - f'{command} ptr_fooo->dd') - - self.complete_from_to(f'{command} cont', - f'{command} container') - self.complete_from_to(f'{command} container.', - f'{command} container.MemberVar') - self.complete_from_to(f'{command} container.Mem', - f'{command} container.MemberVar') - - self.complete_from_to(f'{command} ptr_cont', - f'{command} ptr_container') - self.complete_from_to(f'{command} ptr_container->', - f'{command} ptr_container->MemberVar') - self.complete_from_to(f'{command} ptr_container->Mem', - f'{command} ptr_container->MemberVar') + self.complete_from_to(f"{command} fo", f"{command} fooo") + self.complete_from_to(f"{command} fooo.", f"{command} fooo.") + self.complete_from_to(f"{command} fooo.dd", f"{command} fooo.dd") + + self.complete_from_to(f"{command} ptr_fooo->", f"{command} ptr_fooo->") + self.complete_from_to(f"{command} ptr_fooo->dd", f"{command} ptr_fooo->dd") + + self.complete_from_to(f"{command} cont", f"{command} container") + self.complete_from_to(f"{command} container.", f"{command} container.MemberVar") + self.complete_from_to( + f"{command} container.Mem", f"{command} container.MemberVar" + ) + + self.complete_from_to(f"{command} ptr_cont", f"{command} ptr_container") + self.complete_from_to( + f"{command} ptr_container->", f"{command} ptr_container->MemberVar" + ) + self.complete_from_to( + f"{command} ptr_container->Mem", f"{command} ptr_container->MemberVar" + ) def test_process_attach_dash_dash_con(self): """Test that 'process attach --con' completes to 'process attach --continue '.""" - self.complete_from_to( - 'process attach --con', - 'process attach --continue ') + self.complete_from_to("process attach --con", "process attach --continue ") def test_process_launch_arch(self): - self.complete_from_to('process launch --arch ', - ['mips', - 'arm64']) + self.complete_from_to("process launch --arch ", ["mips", "arm64"]) def test_process_load(self): self.build() - lldbutil.run_to_source_breakpoint(self, '// Break here', lldb.SBFileSpec("main.cpp")) - self.complete_from_to('process load Makef', 'process load Makefile') + lldbutil.run_to_source_breakpoint( + self, "// Break here", lldb.SBFileSpec("main.cpp") + ) + self.complete_from_to("process load Makef", "process load Makefile") @skipUnlessPlatform(["linux"]) def test_process_unload(self): """Test the completion for "process unload " """ # This tab completion should not work without a running process. - self.complete_from_to('process unload ', - 'process unload ') + self.complete_from_to("process unload ", "process unload ") self.build() - lldbutil.run_to_source_breakpoint(self, '// Break here', lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Break here", lldb.SBFileSpec("main.cpp") + ) err = lldb.SBError() - self.process().LoadImage(lldb.SBFileSpec(self.getBuildArtifact("libshared.so")), err) + self.process().LoadImage( + lldb.SBFileSpec(self.getBuildArtifact("libshared.so")), err + ) self.assertSuccess(err) - self.complete_from_to('process unload ', - 'process unload 0') + self.complete_from_to("process unload ", "process unload 0") self.process().UnloadImage(0) - self.complete_from_to('process unload ', - 'process unload ') + self.complete_from_to("process unload ", "process unload ") def test_process_plugin_completion(self): - subcommands = ['attach -P', 'connect -p', 'launch -p'] + subcommands = ["attach -P", "connect -p", "launch -p"] for subcommand in subcommands: - self.complete_from_to('process ' + subcommand + ' mac', - 'process ' + subcommand + ' mach-o-core') + self.complete_from_to( + "process " + subcommand + " mac", + "process " + subcommand + " mach-o-core", + ) def completions_contain_str(self, input, needle): interp = self.dbg.GetCommandInterpreter() @@ -135,11 +130,12 @@ num_matches = interp.HandleCompletion(input, len(input), 0, -1, match_strings) found_needle = False for match in match_strings: - if needle in match: - found_needle = True - break - self.assertTrue(found_needle, "Returned completions: " + "\n".join(match_strings)) - + if needle in match: + found_needle = True + break + self.assertTrue( + found_needle, "Returned completions: " + "\n".join(match_strings) + ) @skipIfRemote def test_common_completion_process_pid_and_name(self): @@ -149,85 +145,75 @@ self.build() server = self.spawnSubprocess( self.getBuildArtifact("a.out"), - ["-x"], # Arg "-x" makes the subprocess wait for input thus it won't be terminated too early - install_remote=False) + [ + "-x" + ], # Arg "-x" makes the subprocess wait for input thus it won't be terminated too early + install_remote=False, + ) self.assertIsNotNone(server) pid = server.pid - self.completions_contain('process attach -p ', [str(pid)]) - self.completions_contain('platform process attach -p ', [str(pid)]) - self.completions_contain('platform process info ', [str(pid)]) + self.completions_contain("process attach -p ", [str(pid)]) + self.completions_contain("platform process attach -p ", [str(pid)]) + self.completions_contain("platform process info ", [str(pid)]) - self.completions_contain_str('process attach -n ', "a.out") - self.completions_contain_str('platform process attach -n ', "a.out") + self.completions_contain_str("process attach -n ", "a.out") + self.completions_contain_str("platform process attach -n ", "a.out") def test_process_signal(self): # The tab completion for "process signal" won't work without a running process. - self.complete_from_to('process signal ', - 'process signal ') + self.complete_from_to("process signal ", "process signal ") # Test with a running process. self.build() self.main_source = "main.cpp" self.main_source_spec = lldb.SBFileSpec(self.main_source) - lldbutil.run_to_source_breakpoint(self, '// Break here', self.main_source_spec) + lldbutil.run_to_source_breakpoint(self, "// Break here", self.main_source_spec) - self.complete_from_to('process signal ', - 'process signal SIG') - self.complete_from_to('process signal SIGPIP', - 'process signal SIGPIPE') - self.complete_from_to('process signal SIGA', - ['SIGABRT', - 'SIGALRM']) + self.complete_from_to("process signal ", "process signal SIG") + self.complete_from_to("process signal SIGPIP", "process signal SIGPIPE") + self.complete_from_to("process signal SIGA", ["SIGABRT", "SIGALRM"]) def test_ambiguous_long_opt(self): - self.completions_match('breakpoint modify --th', - ['--thread-id', - '--thread-index', - '--thread-name']) + self.completions_match( + "breakpoint modify --th", ["--thread-id", "--thread-index", "--thread-name"] + ) def test_disassemble_dash_f(self): - self.completions_match('disassemble -F ', - ['default', - 'intel', - 'att']) + self.completions_match("disassemble -F ", ["default", "intel", "att"]) def test_plugin_load(self): - self.complete_from_to('plugin load ', []) + self.complete_from_to("plugin load ", []) def test_log_enable(self): - self.complete_from_to('log enable ll', ['lldb']) - self.complete_from_to('log enable dw', ['dwarf']) - self.complete_from_to('log enable lldb al', ['all']) - self.complete_from_to('log enable lldb sym', ['symbol']) + self.complete_from_to("log enable ll", ["lldb"]) + self.complete_from_to("log enable dw", ["dwarf"]) + self.complete_from_to("log enable lldb al", ["all"]) + self.complete_from_to("log enable lldb sym", ["symbol"]) def test_log_enable(self): - self.complete_from_to('log disable ll', ['lldb']) - self.complete_from_to('log disable dw', ['dwarf']) - self.complete_from_to('log disable lldb al', ['all']) - self.complete_from_to('log disable lldb sym', ['symbol']) + self.complete_from_to("log disable ll", ["lldb"]) + self.complete_from_to("log disable dw", ["dwarf"]) + self.complete_from_to("log disable lldb al", ["all"]) + self.complete_from_to("log disable lldb sym", ["symbol"]) def test_log_list(self): - self.complete_from_to('log list ll', ['lldb']) - self.complete_from_to('log list dw', ['dwarf']) - self.complete_from_to('log list ll', ['lldb']) - self.complete_from_to('log list lldb dwa', ['dwarf']) + self.complete_from_to("log list ll", ["lldb"]) + self.complete_from_to("log list dw", ["dwarf"]) + self.complete_from_to("log list ll", ["lldb"]) + self.complete_from_to("log list lldb dwa", ["dwarf"]) def test_quoted_command(self): - self.complete_from_to('"set', - ['"settings" ']) + self.complete_from_to('"set', ['"settings" ']) def test_quoted_arg_with_quoted_command(self): - self.complete_from_to('"settings" "repl', - ['"replace" ']) + self.complete_from_to('"settings" "repl', ['"replace" ']) def test_quoted_arg_without_quoted_command(self): - self.complete_from_to('settings "repl', - ['"replace" ']) + self.complete_from_to('settings "repl', ['"replace" ']) def test_single_quote_command(self): - self.complete_from_to("'set", - ["'settings' "]) + self.complete_from_to("'set", ["'settings' "]) def test_terminated_quote_command(self): # This should not crash, but we don't get any @@ -235,318 +221,372 @@ self.complete_from_to("'settings'", []) def test_process_launch_arch_arm(self): - self.complete_from_to('process launch --arch arm', - ['arm64']) + self.complete_from_to("process launch --arch arm", ["arm64"]) def test_target_symbols_add_shlib(self): # Doesn't seem to work, but at least it shouldn't crash. - self.complete_from_to('target symbols add --shlib ', []) + self.complete_from_to("target symbols add --shlib ", []) def test_log_file(self): # Complete in our source directory which contains a 'main.cpp' file. - src_dir = self.getSourceDir() + '/' - self.complete_from_to('log enable lldb expr -f ' + src_dir, - ['main.cpp']) + src_dir = self.getSourceDir() + "/" + self.complete_from_to("log enable lldb expr -f " + src_dir, ["main.cpp"]) def test_log_dir(self): # Complete our source directory. - src_dir = os.path.dirname(os.path.realpath(__file__)) - self.complete_from_to('log enable lldb expr -f ' + src_dir, - [src_dir + os.sep], turn_off_re_match=True) + src_dir = os.path.dirname(os.path.realpath(__file__)) + self.complete_from_to( + "log enable lldb expr -f " + src_dir, + [src_dir + os.sep], + turn_off_re_match=True, + ) # def test_infinite_loop_while_completing(self): """Test that 'process print hello\' completes to itself and does not infinite loop.""" - self.complete_from_to('process print hello\\', 'process print hello\\', - turn_off_re_match=True) + self.complete_from_to( + "process print hello\\", "process print hello\\", turn_off_re_match=True + ) def test_watchpoint_co(self): """Test that 'watchpoint co' completes to 'watchpoint command '.""" - self.complete_from_to('watchpoint co', 'watchpoint command ') + self.complete_from_to("watchpoint co", "watchpoint command ") def test_watchpoint_command_space(self): """Test that 'watchpoint command ' completes to ['add', 'delete', 'list'].""" - self.complete_from_to( - 'watchpoint command ', [ - 'add', 'delete', 'list']) + self.complete_from_to("watchpoint command ", ["add", "delete", "list"]) def test_watchpoint_command_a(self): """Test that 'watchpoint command a' completes to 'watchpoint command add '.""" - self.complete_from_to( - 'watchpoint command a', - 'watchpoint command add ') + self.complete_from_to("watchpoint command a", "watchpoint command add ") def test_watchpoint_set_ex(self): """Test that 'watchpoint set ex' completes to 'watchpoint set expression '.""" - self.complete_from_to( - 'watchpoint set ex', - 'watchpoint set expression ') + self.complete_from_to("watchpoint set ex", "watchpoint set expression ") def test_watchpoint_set_var(self): """Test that 'watchpoint set var' completes to 'watchpoint set variable '.""" - self.complete_from_to('watchpoint set var', 'watchpoint set variable ') + self.complete_from_to("watchpoint set var", "watchpoint set variable ") def test_watchpoint_set_variable_foo(self): self.build() - lldbutil.run_to_source_breakpoint(self, '// Break here', lldb.SBFileSpec("main.cpp")) - self.complete_from_to('watchpoint set variable fo', 'watchpoint set variable fooo') + lldbutil.run_to_source_breakpoint( + self, "// Break here", lldb.SBFileSpec("main.cpp") + ) + self.complete_from_to( + "watchpoint set variable fo", "watchpoint set variable fooo" + ) # Only complete the first argument. - self.complete_from_to('watchpoint set variable fooo ', 'watchpoint set variable fooo ') + self.complete_from_to( + "watchpoint set variable fooo ", "watchpoint set variable fooo " + ) def test_help_fi(self): """Test that 'help fi' completes to ['file', 'finish'].""" - self.complete_from_to( - 'help fi', [ - 'file', 'finish']) + self.complete_from_to("help fi", ["file", "finish"]) def test_help_watchpoint_s(self): """Test that 'help watchpoint s' completes to 'help watchpoint set '.""" - self.complete_from_to('help watchpoint s', 'help watchpoint set ') + self.complete_from_to("help watchpoint s", "help watchpoint set ") @expectedFailureNetBSD @add_test_categories(["watchpoint"]) def test_common_complete_watchpoint_ids(self): - subcommands = ['enable', 'disable', 'delete', 'modify', 'ignore'] + subcommands = ["enable", "disable", "delete", "modify", "ignore"] # Completion should not work without a target. for subcommand in subcommands: - self.complete_from_to('watchpoint ' + subcommand + ' ', - 'watchpoint ' + subcommand + ' ') + self.complete_from_to( + "watchpoint " + subcommand + " ", "watchpoint " + subcommand + " " + ) # Create a process to provide a target and enable watchpoint setting. self.build() - lldbutil.run_to_source_breakpoint(self, '// Break here', lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Break here", lldb.SBFileSpec("main.cpp") + ) - self.runCmd('watchpoint set variable ptr_fooo') + self.runCmd("watchpoint set variable ptr_fooo") for subcommand in subcommands: - self.complete_from_to('watchpoint ' + subcommand + ' ', ['1']) + self.complete_from_to("watchpoint " + subcommand + " ", ["1"]) def test_settings_append_target_er(self): """Test that 'settings append target.er' completes to 'settings append target.error-path'.""" self.complete_from_to( - 'settings append target.er', - 'settings append target.error-path') + "settings append target.er", "settings append target.error-path" + ) def test_settings_insert_after_target_en(self): """Test that 'settings insert-after target.env' completes to 'settings insert-after target.env-vars'.""" self.complete_from_to( - 'settings insert-after target.env', - 'settings insert-after target.env-vars') + "settings insert-after target.env", "settings insert-after target.env-vars" + ) def test_settings_insert_before_target_en(self): """Test that 'settings insert-before target.env' completes to 'settings insert-before target.env-vars'.""" self.complete_from_to( - 'settings insert-before target.env', - 'settings insert-before target.env-vars') + "settings insert-before target.env", + "settings insert-before target.env-vars", + ) def test_settings_replace_target_ru(self): """Test that 'settings replace target.ru' completes to 'settings replace target.run-args'.""" self.complete_from_to( - 'settings replace target.ru', - 'settings replace target.run-args') + "settings replace target.ru", "settings replace target.run-args" + ) def test_settings_show_term(self): - self.complete_from_to( - 'settings show term-', - 'settings show term-width') + self.complete_from_to("settings show term-", "settings show term-width") def test_settings_list_term(self): - self.complete_from_to( - 'settings list term-', - 'settings list term-width') + self.complete_from_to("settings list term-", "settings list term-width") def test_settings_remove_term(self): - self.complete_from_to( - 'settings remove term-', - 'settings remove term-width') + self.complete_from_to("settings remove term-", "settings remove term-width") def test_settings_s(self): """Test that 'settings s' completes to ['set', 'show'].""" - self.complete_from_to( - 'settings s', [ - 'set', 'show']) + self.complete_from_to("settings s", ["set", "show"]) def test_settings_set_th(self): """Test that 'settings set thread-f' completes to 'settings set thread-format'.""" - self.complete_from_to('settings set thread-f', 'settings set thread-format') + self.complete_from_to("settings set thread-f", "settings set thread-format") def test_settings_s_dash(self): """Test that 'settings set --g' completes to 'settings set --global'.""" - self.complete_from_to('settings set --g', 'settings set --global') + self.complete_from_to("settings set --g", "settings set --global") def test_settings_clear_th(self): """Test that 'settings clear thread-f' completes to 'settings clear thread-format'.""" - self.complete_from_to( - 'settings clear thread-f', - 'settings clear thread-format') + self.complete_from_to("settings clear thread-f", "settings clear thread-format") def test_settings_set_ta(self): """Test that 'settings set ta' completes to 'settings set target.'.""" - self.complete_from_to( - 'settings set target.ma', - 'settings set target.max-') + self.complete_from_to("settings set target.ma", "settings set target.max-") def test_settings_set_target_exec(self): """Test that 'settings set target.exec' completes to 'settings set target.exec-search-paths '.""" self.complete_from_to( - 'settings set target.exec', - 'settings set target.exec-search-paths') + "settings set target.exec", "settings set target.exec-search-paths" + ) def test_settings_set_target_pr(self): """Test that 'settings set target.pr' completes to [ 'target.prefer-dynamic-value', 'target.process.'].""" - self.complete_from_to('settings set target.pr', - ['target.prefer-dynamic-value', - 'target.process.']) + self.complete_from_to( + "settings set target.pr", ["target.prefer-dynamic-value", "target.process."] + ) def test_settings_set_target_process(self): """Test that 'settings set target.process' completes to 'settings set target.process.'.""" self.complete_from_to( - 'settings set target.process', - 'settings set target.process.') + "settings set target.process", "settings set target.process." + ) def test_settings_set_target_process_dot(self): """Test that 'settings set target.process.t' completes to 'settings set target.process.thread.'.""" self.complete_from_to( - 'settings set target.process.thr', - 'settings set target.process.thread.') + "settings set target.process.thr", "settings set target.process.thread." + ) def test_settings_set_target_process_thread_dot(self): """Test that 'settings set target.process.thread.' completes to [ - 'target.process.thread.step-avoid-regexp', 'target.process.thread.trace-thread'].""" - self.complete_from_to('settings set target.process.thread.', - ['target.process.thread.step-avoid-regexp', - 'target.process.thread.trace-thread']) + 'target.process.thread.step-avoid-regexp', 'target.process.thread.trace-thread']. + """ + self.complete_from_to( + "settings set target.process.thread.", + [ + "target.process.thread.step-avoid-regexp", + "target.process.thread.trace-thread", + ], + ) def test_settings_set_can_complete_setting_enum_values(self): """Checks that we can complete the values of an enum setting.""" - self.complete_from_to('settings set stop-disassembly-display ', - ['never', 'always', 'no-debuginfo', 'no-source']) + self.complete_from_to( + "settings set stop-disassembly-display ", + ["never", "always", "no-debuginfo", "no-source"], + ) def test_thread_plan_discard(self): self.build() - (_, _, thread, _) = lldbutil.run_to_source_breakpoint(self, - 'ptr_foo', lldb.SBFileSpec("main.cpp")) + (_, _, thread, _) = lldbutil.run_to_source_breakpoint( + self, "ptr_foo", lldb.SBFileSpec("main.cpp") + ) self.assertTrue(thread) - self.complete_from_to('thread plan discard ', 'thread plan discard ') + self.complete_from_to("thread plan discard ", "thread plan discard ") source_path = os.path.join(self.getSourceDir(), "thread_plan_script.py") - self.runCmd("command script import '%s'"%(source_path)) + self.runCmd("command script import '%s'" % (source_path)) self.runCmd("thread step-scripted -C thread_plan_script.PushPlanStack") - self.complete_from_to('thread plan discard ', 'thread plan discard 1') - self.runCmd('thread plan discard 1') + self.complete_from_to("thread plan discard ", "thread plan discard 1") + self.runCmd("thread plan discard 1") def test_target_space(self): """Test that 'target ' completes to ['create', 'delete', 'list', 'modules', 'select', 'stop-hook', 'variable'].""" - self.complete_from_to('target ', - ['create', - 'delete', - 'list', - 'modules', - 'select', - 'stop-hook', - 'variable']) + self.complete_from_to( + "target ", + ["create", "delete", "list", "modules", "select", "stop-hook", "variable"], + ) def test_target_modules_dump_line_table(self): """Tests source file completion by completing the line-table argument.""" self.build() self.dbg.CreateTarget(self.getBuildArtifact("a.out")) - self.complete_from_to('target modules dump line-table main.cp', - ['main.cpp']) + self.complete_from_to("target modules dump line-table main.cp", ["main.cpp"]) def test_target_modules_load_aout(self): """Tests modules completion by completing the target modules load argument.""" self.build() self.dbg.CreateTarget(self.getBuildArtifact("a.out")) - self.complete_from_to('target modules load a.ou', - ['a.out']) + self.complete_from_to("target modules load a.ou", ["a.out"]) def test_target_modules_search_paths_insert(self): # Completion won't work without a valid target. - self.complete_from_to("target modules search-paths insert ", "target modules search-paths insert ") + self.complete_from_to( + "target modules search-paths insert ", "target modules search-paths insert " + ) self.build() - target = self.dbg.CreateTarget(self.getBuildArtifact('a.out')) + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) self.assertTrue(target, VALID_TARGET) - self.complete_from_to("target modules search-paths insert ", "target modules search-paths insert ") + self.complete_from_to( + "target modules search-paths insert ", "target modules search-paths insert " + ) self.runCmd("target modules search-paths add a b") - self.complete_from_to("target modules search-paths insert ", "target modules search-paths insert 0") + self.complete_from_to( + "target modules search-paths insert ", + "target modules search-paths insert 0", + ) # Completion only works for the first arg. - self.complete_from_to("target modules search-paths insert 0 ", "target modules search-paths insert 0 ") + self.complete_from_to( + "target modules search-paths insert 0 ", + "target modules search-paths insert 0 ", + ) def test_target_create_dash_co(self): """Test that 'target create --co' completes to 'target variable --core '.""" - self.complete_from_to('target create --co', 'target create --core ') + self.complete_from_to("target create --co", "target create --core ") def test_target_va(self): """Test that 'target va' completes to 'target variable '.""" - self.complete_from_to('target va', 'target variable ') + self.complete_from_to("target va", "target variable ") def test_common_completion_thread_index(self): - subcommands = ['continue', 'info', 'exception', 'select', - 'step-in', 'step-inst', 'step-inst-over', 'step-out', 'step-over', 'step-script'] + subcommands = [ + "continue", + "info", + "exception", + "select", + "step-in", + "step-inst", + "step-inst-over", + "step-out", + "step-over", + "step-script", + ] # Completion should do nothing without threads. for subcommand in subcommands: - self.complete_from_to('thread ' + subcommand + ' ', - 'thread ' + subcommand + ' ') + self.complete_from_to( + "thread " + subcommand + " ", "thread " + subcommand + " " + ) self.build() - lldbutil.run_to_source_breakpoint(self, '// Break here', lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Break here", lldb.SBFileSpec("main.cpp") + ) # At least we have the thread at the index of 1 now. for subcommand in subcommands: - self.complete_from_to('thread ' + subcommand + ' ', ['1']) + self.complete_from_to("thread " + subcommand + " ", ["1"]) def test_common_completion_type_category_name(self): - subcommands = ['delete', 'list', 'enable', 'disable', 'define'] + subcommands = ["delete", "list", "enable", "disable", "define"] for subcommand in subcommands: - self.complete_from_to('type category ' + subcommand + ' ', ['default']) - self.complete_from_to('type filter add -w ', ['default']) + self.complete_from_to("type category " + subcommand + " ", ["default"]) + self.complete_from_to("type filter add -w ", ["default"]) def test_command_argument_completion(self): """Test completion of command arguments""" self.complete_from_to("watchpoint set variable -", ["-w", "-s"]) - self.complete_from_to('watchpoint set variable -w', 'watchpoint set variable -w ') + self.complete_from_to( + "watchpoint set variable -w", "watchpoint set variable -w " + ) self.complete_from_to("watchpoint set variable --", ["--watch", "--size"]) - self.complete_from_to("watchpoint set variable --w", "watchpoint set variable --watch") - self.complete_from_to('watchpoint set variable -w ', ['read', 'write', 'read_write']) - self.complete_from_to("watchpoint set variable --watch ", ["read", "write", "read_write"]) - self.complete_from_to("watchpoint set variable --watch w", "watchpoint set variable --watch write") - self.complete_from_to('watchpoint set variable -w read_', 'watchpoint set variable -w read_write') + self.complete_from_to( + "watchpoint set variable --w", "watchpoint set variable --watch" + ) + self.complete_from_to( + "watchpoint set variable -w ", ["read", "write", "read_write"] + ) + self.complete_from_to( + "watchpoint set variable --watch ", ["read", "write", "read_write"] + ) + self.complete_from_to( + "watchpoint set variable --watch w", "watchpoint set variable --watch write" + ) + self.complete_from_to( + "watchpoint set variable -w read_", "watchpoint set variable -w read_write" + ) # Now try the same thing with a variable name (non-option argument) to # test that getopts arg reshuffling doesn't confuse us. self.complete_from_to("watchpoint set variable foo -", ["-w", "-s"]) - self.complete_from_to('watchpoint set variable foo -w', 'watchpoint set variable foo -w ') + self.complete_from_to( + "watchpoint set variable foo -w", "watchpoint set variable foo -w " + ) self.complete_from_to("watchpoint set variable foo --", ["--watch", "--size"]) - self.complete_from_to("watchpoint set variable foo --w", "watchpoint set variable foo --watch") - self.complete_from_to('watchpoint set variable foo -w ', ['read', 'write', 'read_write']) - self.complete_from_to("watchpoint set variable foo --watch ", ["read", "write", "read_write"]) - self.complete_from_to("watchpoint set variable foo --watch w", "watchpoint set variable foo --watch write") - self.complete_from_to('watchpoint set variable foo -w read_', 'watchpoint set variable foo -w read_write') + self.complete_from_to( + "watchpoint set variable foo --w", "watchpoint set variable foo --watch" + ) + self.complete_from_to( + "watchpoint set variable foo -w ", ["read", "write", "read_write"] + ) + self.complete_from_to( + "watchpoint set variable foo --watch ", ["read", "write", "read_write"] + ) + self.complete_from_to( + "watchpoint set variable foo --watch w", + "watchpoint set variable foo --watch write", + ) + self.complete_from_to( + "watchpoint set variable foo -w read_", + "watchpoint set variable foo -w read_write", + ) def test_command_script_delete(self): self.runCmd("command script add -h test_desc -f none -s current usercmd1") - self.check_completion_with_desc('command script delete ', [['usercmd1', '']]) + self.check_completion_with_desc("command script delete ", [["usercmd1", ""]]) def test_command_delete(self): - self.runCmd(r"command regex test_command s/^$/finish/ 's/([0-9]+)/frame select %1/'") - self.complete_from_to('command delete test_c', 'command delete test_command') + self.runCmd( + r"command regex test_command s/^$/finish/ 's/([0-9]+)/frame select %1/'" + ) + self.complete_from_to("command delete test_c", "command delete test_command") def test_command_unalias(self): - self.complete_from_to('command unalias ima', 'command unalias image') + self.complete_from_to("command unalias ima", "command unalias image") def test_completion_description_commands(self): """Test descriptions of top-level command completions""" - self.check_completion_with_desc("", [ - ["command", "Commands for managing custom LLDB commands."], - ["breakpoint", "Commands for operating on breakpoints (see 'help b' for shorthand.)"] - ]) - - self.check_completion_with_desc("pl", [ - ["platform", "Commands to manage and create platforms."], - ["plugin", "Commands for managing LLDB plugins."] - ]) + self.check_completion_with_desc( + "", + [ + ["command", "Commands for managing custom LLDB commands."], + [ + "breakpoint", + "Commands for operating on breakpoints (see 'help b' for shorthand.)", + ], + ], + ) + + self.check_completion_with_desc( + "pl", + [ + ["platform", "Commands to manage and create platforms."], + ["plugin", "Commands for managing LLDB plugins."], + ], + ) # Just check that this doesn't crash. self.check_completion_with_desc("comman", []) @@ -555,215 +595,221 @@ def test_completion_description_command_options(self): """Test descriptions of command options""" # Short options - self.check_completion_with_desc("breakpoint set -", [ - ["-h", "Set the breakpoint on exception catcH."], - ["-w", "Set the breakpoint on exception throW."] - ]) + self.check_completion_with_desc( + "breakpoint set -", + [ + ["-h", "Set the breakpoint on exception catcH."], + ["-w", "Set the breakpoint on exception throW."], + ], + ) # Long options. - self.check_completion_with_desc("breakpoint set --", [ - ["--on-catch", "Set the breakpoint on exception catcH."], - ["--on-throw", "Set the breakpoint on exception throW."] - ]) + self.check_completion_with_desc( + "breakpoint set --", + [ + ["--on-catch", "Set the breakpoint on exception catcH."], + ["--on-throw", "Set the breakpoint on exception throW."], + ], + ) # Ambiguous long options. - self.check_completion_with_desc("breakpoint set --on-", [ - ["--on-catch", "Set the breakpoint on exception catcH."], - ["--on-throw", "Set the breakpoint on exception throW."] - ]) + self.check_completion_with_desc( + "breakpoint set --on-", + [ + ["--on-catch", "Set the breakpoint on exception catcH."], + ["--on-throw", "Set the breakpoint on exception throW."], + ], + ) # Unknown long option. - self.check_completion_with_desc("breakpoint set --Z", [ - ]) + self.check_completion_with_desc("breakpoint set --Z", []) def test_common_completion_frame_index(self): self.build() - lldbutil.run_to_source_breakpoint(self, '// Break here', lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Break here", lldb.SBFileSpec("main.cpp") + ) - self.complete_from_to('frame select ', ['0']) - self.complete_from_to('thread backtrace -s ', ['0']) + self.complete_from_to("frame select ", ["0"]) + self.complete_from_to("thread backtrace -s ", ["0"]) def test_frame_recognizer_delete(self): - self.runCmd("frame recognizer add -l py_class -s module_name -n recognizer_name") - self.check_completion_with_desc('frame recognizer delete ', [['0', 'py_class, module module_name, symbol recognizer_name']]) + self.runCmd( + "frame recognizer add -l py_class -s module_name -n recognizer_name" + ) + self.check_completion_with_desc( + "frame recognizer delete ", + [["0", "py_class, module module_name, symbol recognizer_name"]], + ) def test_platform_install_local_file(self): - self.complete_from_to('platform target-install main.cp', 'platform target-install main.cpp') + self.complete_from_to( + "platform target-install main.cp", "platform target-install main.cpp" + ) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489") def test_symbol_name(self): self.build() self.dbg.CreateTarget(self.getBuildArtifact("a.out")) - self.complete_from_to('breakpoint set -n Fo', - 'breakpoint set -n Foo::Bar(int,\\ int)', - turn_off_re_match=True) + self.complete_from_to( + "breakpoint set -n Fo", + "breakpoint set -n Foo::Bar(int,\\ int)", + turn_off_re_match=True, + ) # No completion for Qu because the candidate is # (anonymous namespace)::Quux(). - self.complete_from_to('breakpoint set -n Qu', '') + self.complete_from_to("breakpoint set -n Qu", "") def test_completion_type_formatter_delete(self): - self.runCmd('type filter add --child a Aoo') - self.complete_from_to('type filter delete ', ['Aoo']) - self.runCmd('type filter add --child b -x Boo') - self.complete_from_to('type filter delete ', ['Boo']) - - self.runCmd('type format add -f hex Coo') - self.complete_from_to('type format delete ', ['Coo']) - self.runCmd('type format add -f hex -x Doo') - self.complete_from_to('type format delete ', ['Doo']) - - self.runCmd('type summary add -c Eoo') - self.complete_from_to('type summary delete ', ['Eoo']) - self.runCmd('type summary add -x -c Foo') - self.complete_from_to('type summary delete ', ['Foo']) - - self.runCmd('type synthetic add Goo -l test') - self.complete_from_to('type synthetic delete ', ['Goo']) - self.runCmd('type synthetic add -x Hoo -l test') - self.complete_from_to('type synthetic delete ', ['Hoo']) - - @skipIf(archs=no_match(['x86_64'])) + self.runCmd("type filter add --child a Aoo") + self.complete_from_to("type filter delete ", ["Aoo"]) + self.runCmd("type filter add --child b -x Boo") + self.complete_from_to("type filter delete ", ["Boo"]) + + self.runCmd("type format add -f hex Coo") + self.complete_from_to("type format delete ", ["Coo"]) + self.runCmd("type format add -f hex -x Doo") + self.complete_from_to("type format delete ", ["Doo"]) + + self.runCmd("type summary add -c Eoo") + self.complete_from_to("type summary delete ", ["Eoo"]) + self.runCmd("type summary add -x -c Foo") + self.complete_from_to("type summary delete ", ["Foo"]) + + self.runCmd("type synthetic add Goo -l test") + self.complete_from_to("type synthetic delete ", ["Goo"]) + self.runCmd("type synthetic add -x Hoo -l test") + self.complete_from_to("type synthetic delete ", ["Hoo"]) + + @skipIf(archs=no_match(["x86_64"])) def test_register_read_and_write_on_x86(self): """Test the completion of the commands register read and write on x86""" # The tab completion for "register read/write" won't work without a running process. - self.complete_from_to('register read ', - 'register read ') - self.complete_from_to('register write ', - 'register write ') + self.complete_from_to("register read ", "register read ") + self.complete_from_to("register write ", "register write ") self.build() self.main_source_spec = lldb.SBFileSpec("main.cpp") - lldbutil.run_to_source_breakpoint(self, '// Break here', self.main_source_spec) + lldbutil.run_to_source_breakpoint(self, "// Break here", self.main_source_spec) # test cases for register read - self.complete_from_to('register read ', - ['rax', - 'rbx', - 'rcx']) - self.complete_from_to('register read r', - ['rax', - 'rbx', - 'rcx']) - self.complete_from_to('register read ra', - 'register read rax') + self.complete_from_to("register read ", ["rax", "rbx", "rcx"]) + self.complete_from_to("register read r", ["rax", "rbx", "rcx"]) + self.complete_from_to("register read ra", "register read rax") # register read can take multiple register names as arguments - self.complete_from_to('register read rax ', - ['rax', - 'rbx', - 'rcx']) + self.complete_from_to("register read rax ", ["rax", "rbx", "rcx"]) # complete with prefix '$' - self.completions_match('register read $rb', - ['$rbx', - '$rbp']) - self.completions_match('register read $ra', - ['$rax']) - self.complete_from_to('register read rax $', - ['\$rax', - '\$rbx', - '\$rcx']) - self.complete_from_to('register read $rax ', - ['rax', - 'rbx', - 'rcx']) + self.completions_match("register read $rb", ["$rbx", "$rbp"]) + self.completions_match("register read $ra", ["$rax"]) + self.complete_from_to("register read rax $", ["\$rax", "\$rbx", "\$rcx"]) + self.complete_from_to("register read $rax ", ["rax", "rbx", "rcx"]) # test cases for register write - self.complete_from_to('register write ', - ['rax', - 'rbx', - 'rcx']) - self.complete_from_to('register write r', - ['rax', - 'rbx', - 'rcx']) - self.complete_from_to('register write ra', - 'register write rax') - self.complete_from_to('register write rb', - ['rbx', - 'rbp']) + self.complete_from_to("register write ", ["rax", "rbx", "rcx"]) + self.complete_from_to("register write r", ["rax", "rbx", "rcx"]) + self.complete_from_to("register write ra", "register write rax") + self.complete_from_to("register write rb", ["rbx", "rbp"]) # register write can only take exact one register name as argument - self.complete_from_to('register write rbx ', - []) + self.complete_from_to("register write rbx ", []) def test_common_completion_target_stophook_ids(self): - subcommands = ['delete', 'enable', 'disable'] + subcommands = ["delete", "enable", "disable"] for subcommand in subcommands: - self.complete_from_to('target stop-hook ' + subcommand + ' ', - 'target stop-hook ' + subcommand + ' ') + self.complete_from_to( + "target stop-hook " + subcommand + " ", + "target stop-hook " + subcommand + " ", + ) self.build() self.dbg.CreateTarget(self.getBuildArtifact("a.out")) - self.runCmd('target stop-hook add -o test') + self.runCmd("target stop-hook add -o test") for subcommand in subcommands: - self.complete_from_to('target stop-hook ' + subcommand + ' ', - 'target stop-hook ' + subcommand + ' 1') + self.complete_from_to( + "target stop-hook " + subcommand + " ", + "target stop-hook " + subcommand + " 1", + ) # Completion should work only on the first argument. for subcommand in subcommands: - self.complete_from_to('target stop-hook ' + subcommand + ' 1 ', - 'target stop-hook ' + subcommand + ' 1 ') + self.complete_from_to( + "target stop-hook " + subcommand + " 1 ", + "target stop-hook " + subcommand + " 1 ", + ) def test_common_completion_type_language(self): - self.complete_from_to('type category -l ', ['c']) + self.complete_from_to("type category -l ", ["c"]) def test_target_modules_load_dash_u(self): self.build() target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) - self.complete_from_to('target modules load -u ', [target.GetModuleAtIndex(0).GetUUIDString()]) + self.complete_from_to( + "target modules load -u ", [target.GetModuleAtIndex(0).GetUUIDString()] + ) def test_complete_breakpoint_with_ids(self): """These breakpoint subcommands should be completed with a list of breakpoint ids""" - subcommands = ['enable', 'disable', 'delete', 'modify', 'name add', 'name delete', 'write'] + subcommands = [ + "enable", + "disable", + "delete", + "modify", + "name add", + "name delete", + "write", + ] # The tab completion here is unavailable without a target for subcommand in subcommands: - self.complete_from_to('breakpoint ' + subcommand + ' ', - 'breakpoint ' + subcommand + ' ') + self.complete_from_to( + "breakpoint " + subcommand + " ", "breakpoint " + subcommand + " " + ) self.build() - target = self.dbg.CreateTarget(self.getBuildArtifact('a.out')) + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) self.assertTrue(target, VALID_TARGET) - bp = target.BreakpointCreateByName('main', 'a.out') + bp = target.BreakpointCreateByName("main", "a.out") self.assertTrue(bp) self.assertEqual(bp.GetNumLocations(), 1) for subcommand in subcommands: - self.complete_from_to('breakpoint ' + subcommand + ' ', - ['1']) + self.complete_from_to("breakpoint " + subcommand + " ", ["1"]) - bp2 = target.BreakpointCreateByName('Bar', 'a.out') + bp2 = target.BreakpointCreateByName("Bar", "a.out") self.assertTrue(bp2) self.assertEqual(bp2.GetNumLocations(), 1) for subcommand in subcommands: - self.complete_from_to('breakpoint ' + subcommand + ' ', - ['1', - '2']) + self.complete_from_to("breakpoint " + subcommand + " ", ["1", "2"]) for subcommand in subcommands: - self.complete_from_to('breakpoint ' + subcommand + ' 1 ', - ['1', - '2']) + self.complete_from_to("breakpoint " + subcommand + " 1 ", ["1", "2"]) def test_complete_breakpoint_with_names(self): self.build() - target = self.dbg.CreateTarget(self.getBuildArtifact('a.out')) + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) self.assertTrue(target, VALID_TARGET) # test breakpoint read dedicated - self.complete_from_to('breakpoint read -N ', 'breakpoint read -N ') - self.complete_from_to('breakpoint read -f breakpoints.json -N ', ['mm']) - self.complete_from_to('breakpoint read -f breakpoints.json -N n', 'breakpoint read -f breakpoints.json -N n') - self.complete_from_to('breakpoint read -f breakpoints_invalid.json -N ', 'breakpoint read -f breakpoints_invalid.json -N ') + self.complete_from_to("breakpoint read -N ", "breakpoint read -N ") + self.complete_from_to("breakpoint read -f breakpoints.json -N ", ["mm"]) + self.complete_from_to( + "breakpoint read -f breakpoints.json -N n", + "breakpoint read -f breakpoints.json -N n", + ) + self.complete_from_to( + "breakpoint read -f breakpoints_invalid.json -N ", + "breakpoint read -f breakpoints_invalid.json -N ", + ) # test common breapoint name completion - bp1 = target.BreakpointCreateByName('main', 'a.out') + bp1 = target.BreakpointCreateByName("main", "a.out") self.assertTrue(bp1) self.assertEqual(bp1.GetNumLocations(), 1) - self.complete_from_to('breakpoint set -N n', 'breakpoint set -N n') + self.complete_from_to("breakpoint set -N n", "breakpoint set -N n") self.assertTrue(bp1.AddNameWithErrorHandling("nn")) - self.complete_from_to('breakpoint set -N ', 'breakpoint set -N nn') + self.complete_from_to("breakpoint set -N ", "breakpoint set -N nn") diff --git a/lldb/test/API/functionalities/completion/thread_plan_script.py b/lldb/test/API/functionalities/completion/thread_plan_script.py --- a/lldb/test/API/functionalities/completion/thread_plan_script.py +++ b/lldb/test/API/functionalities/completion/thread_plan_script.py @@ -5,8 +5,8 @@ import lldb -class PushPlanStack: +class PushPlanStack: def __init__(self, thread_plan, dict): pass diff --git a/lldb/test/API/functionalities/conditional_break/TestConditionalBreak.py b/lldb/test/API/functionalities/conditional_break/TestConditionalBreak.py --- a/lldb/test/API/functionalities/conditional_break/TestConditionalBreak.py +++ b/lldb/test/API/functionalities/conditional_break/TestConditionalBreak.py @@ -14,8 +14,7 @@ class ConditionalBreakTestCase(TestBase): - - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) def test_with_python(self): """Exercise some thread and frame APIs to break if c() is called by a().""" self.build() @@ -37,19 +36,19 @@ self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - self.assertState(process.GetState(), lldb.eStateStopped, - STOPPED_DUE_TO_BREAKPOINT) + self.assertState( + process.GetState(), lldb.eStateStopped, STOPPED_DUE_TO_BREAKPOINT + ) # Find the line number where a's parent frame function is c. line = line_number( - 'main.c', - "// Find the line number where c's parent frame is a here.") + "main.c", "// Find the line number where c's parent frame is a here." + ) # Suppose we are only interested in the call scenario where c()'s # immediate caller is a() and we want to find out the value passed from @@ -60,10 +59,10 @@ for j in range(10): if self.TraceOn(): print("j is: ", j) - thread = lldbutil.get_one_thread_stopped_at_breakpoint( - process, breakpoint) + thread = lldbutil.get_one_thread_stopped_at_breakpoint(process, breakpoint) self.assertIsNotNone( - thread, "Expected one thread to be stopped at the breakpoint") + thread, "Expected one thread to be stopped at the breakpoint" + ) if thread.GetNumFrames() >= 2: frame0 = thread.GetFrameAtIndex(0) @@ -72,12 +71,15 @@ name1 = frame1.GetFunction().GetName() # lldbutil.print_stacktrace(thread) self.assertEqual(name0, "c", "Break on function c()") - if (name1 == "a"): + if name1 == "a": # By design, we know that a() calls c() only from main.c:27. # In reality, similar logic can be used to find out the call # site. - self.assertEqual(frame1.GetLineEntry().GetLine(), line, - "Immediate caller a() at main.c:%d" % line) + self.assertEqual( + frame1.GetLineEntry().GetLine(), + line, + "Immediate caller a() at main.c:%d" % line, + ) # And the local variable 'val' should have a value of (int) # 3. @@ -118,16 +120,19 @@ print("Done running") # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # The frame info for frame #0 points to a.out`c and its immediate caller # (frame #1) points to a.out`a. - self.expect("frame info", "We should stop at c()", - substrs=["a.out`c"]) + self.expect("frame info", "We should stop at c()", substrs=["a.out`c"]) # Select our parent frame as the current frame. self.runCmd("frame select 1") - self.expect("frame info", "The immediate caller should be a()", - substrs=["a.out`a"]) + self.expect( + "frame info", "The immediate caller should be a()", substrs=["a.out`a"] + ) diff --git a/lldb/test/API/functionalities/conditional_break/conditional_break.py b/lldb/test/API/functionalities/conditional_break/conditional_break.py --- a/lldb/test/API/functionalities/conditional_break/conditional_break.py +++ b/lldb/test/API/functionalities/conditional_break/conditional_break.py @@ -2,7 +2,6 @@ def stop_if_called_from_a(frame, bp_loc, dict): - thread = frame.GetThread() process = thread.GetProcess() target = process.GetTarget() @@ -18,9 +17,10 @@ should_stop = True if thread.GetNumFrames() >= 2: - - if (thread.frames[0].function.name == - 'c' and thread.frames[1].function.name == 'a'): + if ( + thread.frames[0].function.name == "c" + and thread.frames[1].function.name == "a" + ): should_stop = True else: should_stop = False diff --git a/lldb/test/API/functionalities/data-formatter/array_typedef/TestArrayTypedef.py b/lldb/test/API/functionalities/data-formatter/array_typedef/TestArrayTypedef.py --- a/lldb/test/API/functionalities/data-formatter/array_typedef/TestArrayTypedef.py +++ b/lldb/test/API/functionalities/data-formatter/array_typedef/TestArrayTypedef.py @@ -8,6 +8,7 @@ def test_array_typedef(self): self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", - lldb.SBFileSpec("main.cpp", False)) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) self.expect("expr str", substrs=['"abcd"']) diff --git a/lldb/test/API/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py b/lldb/test/API/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py --- a/lldb/test/API/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py +++ b/lldb/test/API/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class DataFormatterBoolRefPtr(TestBase): - @skipUnlessDarwin def test_boolrefptr_with_run_command(self): """Test the formatters we use for BOOL& and BOOL* in Objective-C.""" @@ -22,66 +20,66 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.mm', '// Set break point at this line.') + self.line = line_number("main.mm", "// Set break point at this line.") def boolrefptr_data_formatter_commands(self): """Test the formatters we use for BOOL& and BOOL* in Objective-C.""" self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) + self, "main.mm", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - isArm = 'arm' in self.getArchitecture() + isArm = "arm" in self.getArchitecture() # Now check that we use the right summary for BOOL& - self.expect('frame variable yes_ref', - substrs=['YES']) - self.expect('frame variable no_ref', - substrs=['NO']) - if not(isArm): - self.expect('frame variable unset_ref', substrs=['12']) + self.expect("frame variable yes_ref", substrs=["YES"]) + self.expect("frame variable no_ref", substrs=["NO"]) + if not (isArm): + self.expect("frame variable unset_ref", substrs=["12"]) # Now check that we use the right summary for BOOL* - self.expect('frame variable yes_ptr', - substrs=['YES']) - self.expect('frame variable no_ptr', - substrs=['NO']) - if not(isArm): - self.expect('frame variable unset_ptr', substrs=['12']) + self.expect("frame variable yes_ptr", substrs=["YES"]) + self.expect("frame variable no_ptr", substrs=["NO"]) + if not (isArm): + self.expect("frame variable unset_ptr", substrs=["12"]) # Now check that we use the right summary for BOOL - self.expect('frame variable yes', - substrs=['YES']) - self.expect('frame variable no', - substrs=['NO']) - if not(isArm): - self.expect('frame variable unset', substrs=['12']) + self.expect("frame variable yes", substrs=["YES"]) + self.expect("frame variable no", substrs=["NO"]) + if not (isArm): + self.expect("frame variable unset", substrs=["12"]) # BOOL is bool instead of signed char on ARM. converted_YES = "-1" if not isArm else "YES" - self.expect_expr('myField', result_type="BoolBitFields", - result_children=[ - ValueCheck(name="fieldOne", summary="NO"), - ValueCheck(name="fieldTwo", summary=converted_YES), - ValueCheck(name="fieldThree", summary="NO"), - ValueCheck(name="fieldFour", summary="NO"), - ValueCheck(name="fieldFive", summary=converted_YES) - ]) + self.expect_expr( + "myField", + result_type="BoolBitFields", + result_children=[ + ValueCheck(name="fieldOne", summary="NO"), + ValueCheck(name="fieldTwo", summary=converted_YES), + ValueCheck(name="fieldThree", summary="NO"), + ValueCheck(name="fieldFour", summary="NO"), + ValueCheck(name="fieldFive", summary=converted_YES), + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/builtin-formats/TestBuiltinFormats.py b/lldb/test/API/functionalities/data-formatter/builtin-formats/TestBuiltinFormats.py --- a/lldb/test/API/functionalities/data-formatter/builtin-formats/TestBuiltinFormats.py +++ b/lldb/test/API/functionalities/data-formatter/builtin-formats/TestBuiltinFormats.py @@ -7,8 +7,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): def getFormatted(self, format, expr): """ Evaluates the expression and formats the result with the given format. @@ -22,10 +22,12 @@ @no_debug_info_test @skipIfWindows # uint128_t not available on arm. - @skipIf(archs=['arm']) + @skipIf(archs=["arm"]) def test(self): self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) # void self.assertEqual("", self.getFormatted("void", "1")) @@ -34,7 +36,10 @@ self.assertIn("= false\n", self.getFormatted("boolean", "0")) self.assertIn("= true\n", self.getFormatted("boolean", "1")) self.assertIn("= true\n", self.getFormatted("boolean", "2")) - self.assertIn("= error: unsupported byte size (16) for boolean format\n", self.getFormatted("boolean", "(__uint128_t)0")) + self.assertIn( + "= error: unsupported byte size (16) for boolean format\n", + self.getFormatted("boolean", "(__uint128_t)0"), + ) # float self.assertIn("= 0\n", self.getFormatted("float", "0")) @@ -42,7 +47,10 @@ self.assertIn("= NaN\n", self.getFormatted("float", "-1")) # Checks the float16 code. self.assertIn("= 2\n", self.getFormatted("float", "(__UINT16_TYPE__)0x4000")) - self.assertIn("= error: unsupported byte size (1) for float format\n", self.getFormatted("float", "'a'")) + self.assertIn( + "= error: unsupported byte size (1) for float format\n", + self.getFormatted("float", "'a'"), + ) # enumeration self.assertIn("= 0\n", self.getFormatted("enumeration", "0")) @@ -51,48 +59,83 @@ # dec self.assertIn("= 1234567\n", self.getFormatted("dec", "1234567")) - self.assertIn("= 123456789\n", self.getFormatted("dec", "(__uint128_t)123456789")) + self.assertIn( + "= 123456789\n", self.getFormatted("dec", "(__uint128_t)123456789") + ) # unsigned decimal self.assertIn("= 1234567\n", self.getFormatted("unsigned decimal", "1234567")) - self.assertIn("= 4293732729\n", self.getFormatted("unsigned decimal", "-1234567")) - self.assertIn("= 123456789\n", self.getFormatted("unsigned decimal", "(__uint128_t)123456789")) + self.assertIn( + "= 4293732729\n", self.getFormatted("unsigned decimal", "-1234567") + ) + self.assertIn( + "= 123456789\n", + self.getFormatted("unsigned decimal", "(__uint128_t)123456789"), + ) # octal self.assertIn("= 04553207\n", self.getFormatted("octal", "1234567")) - self.assertIn("= 0221505317046536757\n", self.getFormatted("octal", "(__uint128_t)0x123456789ABDEFull")) + self.assertIn( + "= 0221505317046536757\n", + self.getFormatted("octal", "(__uint128_t)0x123456789ABDEFull"), + ) # complex float - self.assertIn("= error: unsupported byte size (1) for complex float format\n", self.getFormatted("complex float", "'a'")) + self.assertIn( + "= error: unsupported byte size (1) for complex float format\n", + self.getFormatted("complex float", "'a'"), + ) # complex integer - self.assertIn("= error: unsupported byte size (1) for complex integer format\n", self.getFormatted("complex integer", "'a'")) + self.assertIn( + "= error: unsupported byte size (1) for complex integer format\n", + self.getFormatted("complex integer", "'a'"), + ) # hex self.assertIn("= 0x00abc123\n", self.getFormatted("hex", "0xABC123")) - self.assertIn("= 0x000000000000000000123456789abdef\n", self.getFormatted("hex", "(__uint128_t)0x123456789ABDEFull")) + self.assertIn( + "= 0x000000000000000000123456789abdef\n", + self.getFormatted("hex", "(__uint128_t)0x123456789ABDEFull"), + ) # hex float self.assertIn("= 0x1p1\n", self.getFormatted("hex float", "2.0f")) self.assertIn("= 0x1p1\n", self.getFormatted("hex float", "2.0")) # FIXME: long double not supported. - self.assertIn("= error: unsupported byte size (16) for hex float format\n", self.getFormatted("hex float", "2.0l")) + self.assertIn( + "= error: unsupported byte size (16) for hex float format\n", + self.getFormatted("hex float", "2.0l"), + ) # uppercase hex self.assertIn("= 0x00ABC123\n", self.getFormatted("uppercase hex", "0xABC123")) # binary - self.assertIn("= 0b00000000000000000000000000000010\n", self.getFormatted("binary", "2")) + self.assertIn( + "= 0b00000000000000000000000000000010\n", self.getFormatted("binary", "2") + ) self.assertIn("= 0b01100001\n", self.getFormatted("binary", "'a'")) - self.assertIn(" = 0b10010001101000101011001111000\n", self.getFormatted("binary", "(__uint128_t)0x12345678ll")) + self.assertIn( + " = 0b10010001101000101011001111000\n", + self.getFormatted("binary", "(__uint128_t)0x12345678ll"), + ) # Different character arrays. # FIXME: Passing a 'const char *' will ignore any given format, - self.assertIn(r'= " \U0000001b\a\b\f\n\r\t\vaA09"', self.getFormatted("character array", "cstring")) - self.assertIn(r'= " \U0000001b\a\b\f\n\r\t\vaA09"', self.getFormatted("c-string", "cstring")) - self.assertIn(' = " \\e\\a\\b\\f\\n\\r\\t\\vaA09" " \\U0000001b\\a\\b\\f\\n\\r\\t\\vaA09"\n', - self.getFormatted("c-string", "(char *)cstring")) - self.assertIn('=\n', self.getFormatted("c-string", "(__UINT64_TYPE__)0")) + self.assertIn( + r'= " \U0000001b\a\b\f\n\r\t\vaA09"', + self.getFormatted("character array", "cstring"), + ) + self.assertIn( + r'= " \U0000001b\a\b\f\n\r\t\vaA09"', + self.getFormatted("c-string", "cstring"), + ) + self.assertIn( + ' = " \\e\\a\\b\\f\\n\\r\\t\\vaA09" " \\U0000001b\\a\\b\\f\\n\\r\\t\\vaA09"\n', + self.getFormatted("c-string", "(char *)cstring"), + ) + self.assertIn("=\n", self.getFormatted("c-string", "(__UINT64_TYPE__)0")) # Build a uint128_t that contains a series of characters in each byte. # First 8 byte of the uint128_t. @@ -103,80 +146,140 @@ # Build a uint128_t value with the hex encoded characters. string_expr = "((__uint128_t)0x" for c in cstring_chars1: - string_expr += format(ord(c), "x").zfill(2) + string_expr += format(ord(c), "x").zfill(2) string_expr += "ull << 64) | (__uint128_t)0x" for c in cstring_chars2: - string_expr += format(ord(c), "x").zfill(2) + string_expr += format(ord(c), "x").zfill(2) string_expr += "ull" # Try to print that uint128_t with the different char formatters. - self.assertIn('= \\0\\e90zaZA\\v\\t\\r\\n\\f\\b\\a \n', self.getFormatted("character array", string_expr)) - self.assertIn('= \\0\\e90zaZA\\v\\t\\r\\n\\f\\b\\a \n', self.getFormatted("character", string_expr)) - self.assertIn('= ..90zaZA....... \n', self.getFormatted("printable character", string_expr)) - self.assertIn('= 0x00 0x1b 0x39 0x30 0x7a 0x61 0x5a 0x41 0x0b 0x09 0x0d 0x0a 0x0c 0x08 0x07 0x20\n', self.getFormatted("unicode8", string_expr)) + self.assertIn( + "= \\0\\e90zaZA\\v\\t\\r\\n\\f\\b\\a \n", + self.getFormatted("character array", string_expr), + ) + self.assertIn( + "= \\0\\e90zaZA\\v\\t\\r\\n\\f\\b\\a \n", + self.getFormatted("character", string_expr), + ) + self.assertIn( + "= ..90zaZA....... \n", + self.getFormatted("printable character", string_expr), + ) + self.assertIn( + "= 0x00 0x1b 0x39 0x30 0x7a 0x61 0x5a 0x41 0x0b 0x09 0x0d 0x0a 0x0c 0x08 0x07 0x20\n", + self.getFormatted("unicode8", string_expr), + ) # OSType ostype_expr = "(__UINT64_TYPE__)0x" for c in cstring_chars1: - ostype_expr += format(ord(c), "x").zfill(2) - self.assertIn("= ' \\a\\b\\f\\n\\r\\t\\v'\n", self.getFormatted("OSType", ostype_expr)) + ostype_expr += format(ord(c), "x").zfill(2) + self.assertIn( + "= ' \\a\\b\\f\\n\\r\\t\\v'\n", self.getFormatted("OSType", ostype_expr) + ) ostype_expr = "(__UINT64_TYPE__)0x" for c in cstring_chars2: - ostype_expr += format(ord(c), "x").zfill(2) + ostype_expr += format(ord(c), "x").zfill(2) self.assertIn("= 'AZaz09\\e\\0'\n", self.getFormatted("OSType", ostype_expr)) - self.assertIn('= 0x2007080c0a0d090b415a617a30391b00\n', self.getFormatted("OSType", string_expr)) + self.assertIn( + "= 0x2007080c0a0d090b415a617a30391b00\n", + self.getFormatted("OSType", string_expr), + ) # bytes - self.assertIn(r'= " \U0000001b\a\b\f\n\r\t\vaA09"', self.getFormatted("bytes", "cstring")) + self.assertIn( + r'= " \U0000001b\a\b\f\n\r\t\vaA09"', self.getFormatted("bytes", "cstring") + ) # bytes with ASCII - self.assertIn(r'= " \U0000001b\a\b\f\n\r\t\vaA09"', self.getFormatted("bytes with ASCII", "cstring")) + self.assertIn( + r'= " \U0000001b\a\b\f\n\r\t\vaA09"', + self.getFormatted("bytes with ASCII", "cstring"), + ) # unicode8 - self.assertIn('= 0x78 0x56 0x34 0x12\n', self.getFormatted("unicode8", "0x12345678")) + self.assertIn( + "= 0x78 0x56 0x34 0x12\n", self.getFormatted("unicode8", "0x12345678") + ) # unicode16 - self.assertIn('= U+5678 U+1234\n', self.getFormatted("unicode16", "0x12345678")) + self.assertIn("= U+5678 U+1234\n", self.getFormatted("unicode16", "0x12345678")) # unicode32 - self.assertIn('= U+0x89abcdef U+0x01234567\n', self.getFormatted("unicode32", "(__UINT64_TYPE__)0x123456789ABCDEFll")) + self.assertIn( + "= U+0x89abcdef U+0x01234567\n", + self.getFormatted("unicode32", "(__UINT64_TYPE__)0x123456789ABCDEFll"), + ) # address self.assertIn("= 0x00000012\n", self.getFormatted("address", "0x12")) self.assertIn("= 0x00000000\n", self.getFormatted("address", "0")) # Different fixed-width integer type arrays (e.g. 'uint8_t[]'). - self.assertIn("= {0xf8 0x56 0x34 0x12}\n", self.getFormatted("uint8_t[]", "0x123456f8")) + self.assertIn( + "= {0xf8 0x56 0x34 0x12}\n", self.getFormatted("uint8_t[]", "0x123456f8") + ) self.assertIn("= {-8 86 52 18}\n", self.getFormatted("int8_t[]", "0x123456f8")) - self.assertIn("= {0x56f8 0x1234}\n", self.getFormatted("uint16_t[]", "0x123456f8")) + self.assertIn( + "= {0x56f8 0x1234}\n", self.getFormatted("uint16_t[]", "0x123456f8") + ) self.assertIn("= {-2312 4660}\n", self.getFormatted("int16_t[]", "0x1234F6f8")) - self.assertIn("= {0x89abcdef 0x01234567}\n", self.getFormatted("uint32_t[]", "(__UINT64_TYPE__)0x123456789ABCDEFll")) - self.assertIn("= {-1985229329 19088743}\n", self.getFormatted("int32_t[]", "(__UINT64_TYPE__)0x123456789ABCDEFll")) - - self.assertIn("= {0x89abcdef 0x01234567 0x00000000 0x00000000}\n", self.getFormatted("uint32_t[]", "__uint128_t i = 0x123456789ABCDEF; i")) - self.assertIn("= {-1985229329 19088743 0 0}\n", self.getFormatted("int32_t[]", "__uint128_t i = 0x123456789ABCDEF; i")) - - self.assertIn("= {0x0123456789abcdef 0x0000000000000000}\n", self.getFormatted("uint64_t[]", "__uint128_t i = 0x123456789ABCDEF; i")) - self.assertIn("= {-994074541749903617 0}\n", self.getFormatted("int64_t[]", "__uint128_t i = 0xF23456789ABCDEFFll; i")) + self.assertIn( + "= {0x89abcdef 0x01234567}\n", + self.getFormatted("uint32_t[]", "(__UINT64_TYPE__)0x123456789ABCDEFll"), + ) + self.assertIn( + "= {-1985229329 19088743}\n", + self.getFormatted("int32_t[]", "(__UINT64_TYPE__)0x123456789ABCDEFll"), + ) + + self.assertIn( + "= {0x89abcdef 0x01234567 0x00000000 0x00000000}\n", + self.getFormatted("uint32_t[]", "__uint128_t i = 0x123456789ABCDEF; i"), + ) + self.assertIn( + "= {-1985229329 19088743 0 0}\n", + self.getFormatted("int32_t[]", "__uint128_t i = 0x123456789ABCDEF; i"), + ) + + self.assertIn( + "= {0x0123456789abcdef 0x0000000000000000}\n", + self.getFormatted("uint64_t[]", "__uint128_t i = 0x123456789ABCDEF; i"), + ) + self.assertIn( + "= {-994074541749903617 0}\n", + self.getFormatted("int64_t[]", "__uint128_t i = 0xF23456789ABCDEFFll; i"), + ) # There is not int128_t[] style, so this only tests uint128_t[]. - self.assertIn("= {0x00000000000000000123456789abcdef}\n", self.getFormatted("uint128_t[]", "__uint128_t i = 0x123456789ABCDEF; i")) + self.assertIn( + "= {0x00000000000000000123456789abcdef}\n", + self.getFormatted("uint128_t[]", "__uint128_t i = 0x123456789ABCDEF; i"), + ) # Different fixed-width float type arrays. self.assertIn("{2 2}\n", self.getFormatted("float16[]", "0x40004000")) self.assertIn("{2 2}\n", self.getFormatted("float32[]", "0x4000000040000000ll")) - self.assertIn("{2 0}\n", self.getFormatted("float64[]", "__uint128_t i = 0x4000000000000000ll; i")) + self.assertIn( + "{2 0}\n", + self.getFormatted("float64[]", "__uint128_t i = 0x4000000000000000ll; i"), + ) # Invalid format string - self.expect("expr --format invalid_format_string -- 1", error=True, - substrs=["error: Invalid format character or name 'invalid_format_string'. Valid values are:"]) + self.expect( + "expr --format invalid_format_string -- 1", + error=True, + substrs=[ + "error: Invalid format character or name 'invalid_format_string'. Valid values are:" + ], + ) # Extends to host target pointer width. - @skipIf(archs=no_match(['x86_64'])) + @skipIf(archs=no_match(["x86_64"])) @no_debug_info_test def test_pointer(self): # pointer @@ -186,7 +289,9 @@ self.assertIn("= 0x0000000000000000\n", self.getFormatted("pointer", "'a'")) # Depends on the host target for decoding. - @skipIf(archs=no_match(['x86_64'])) + @skipIf(archs=no_match(["x86_64"])) @no_debug_info_test def test_instruction(self): - self.assertIn(" addq 0xa(%rdi), %r8\n", self.getFormatted("instruction", "0x0a47034c")) + self.assertIn( + " addq 0xa(%rdi), %r8\n", self.getFormatted("instruction", "0x0a47034c") + ) diff --git a/lldb/test/API/functionalities/data-formatter/callback-matching/TestDataFormatterCallbackMatching.py b/lldb/test/API/functionalities/data-formatter/callback-matching/TestDataFormatterCallbackMatching.py --- a/lldb/test/API/functionalities/data-formatter/callback-matching/TestDataFormatterCallbackMatching.py +++ b/lldb/test/API/functionalities/data-formatter/callback-matching/TestDataFormatterCallbackMatching.py @@ -9,79 +9,91 @@ class PythonSynthDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_callback_matchers_api_registration(self): """Test data formatter commands.""" self.build() _, process, thread, _ = lldbutil.run_to_line_breakpoint( - self, lldb.SBFileSpec("main.cpp"), self.line) + self, lldb.SBFileSpec("main.cpp"), self.line + ) # Print derived without a formatter. - self.expect("frame variable derived", - substrs=['x = 2222', - 'y = 3333']) + self.expect("frame variable derived", substrs=["x = 2222", "y = 3333"]) # now set up a summary function that uses a python callback to match # classes that derive from `Base`. - self.runCmd("command script import --allow-reload ./formatters_with_callback.py") - self.runCmd("script formatters_with_callback.register_formatters(lldb.debugger)") + self.runCmd( + "command script import --allow-reload ./formatters_with_callback.py" + ) + self.runCmd( + "script formatters_with_callback.register_formatters(lldb.debugger)" + ) # Now `derived` should use our callback summary + synthetic children. - self.expect("frame variable derived", - substrs=['hello from callback summary', - 'synthetic_child = 9999']) + self.expect( + "frame variable derived", + substrs=["hello from callback summary", "synthetic_child = 9999"], + ) # But not other classes. - self.expect("frame variable base", matching=False, - substrs=['hello from callback summary']) - self.expect("frame variable base", - substrs=['x = 1111']) - - self.expect("frame variable nd", matching=False, - substrs=['hello from callback summary']) - self.expect("frame variable nd", - substrs=['z = 4444']) + self.expect( + "frame variable base", + matching=False, + substrs=["hello from callback summary"], + ) + self.expect("frame variable base", substrs=["x = 1111"]) + + self.expect( + "frame variable nd", matching=False, substrs=["hello from callback summary"] + ) + self.expect("frame variable nd", substrs=["z = 4444"]) def test_callback_matchers_cli_registration(self): """Test data formatter commands.""" self.build() _, process, thread, _ = lldbutil.run_to_line_breakpoint( - self, lldb.SBFileSpec("main.cpp"), self.line) + self, lldb.SBFileSpec("main.cpp"), self.line + ) # Print derived without a formatter. - self.expect("frame variable derived", - substrs=['x = 2222', - 'y = 3333']) + self.expect("frame variable derived", substrs=["x = 2222", "y = 3333"]) # now set up a summary function that uses a python callback to match # classes that derive from `Base`. - self.runCmd("command script import --allow-reload ./formatters_with_callback.py") - self.runCmd("type summary add -e -s 'hello from callback summary' " - "--recognizer-function formatters_with_callback.derives_from_base") - self.runCmd("type synth add -l formatters_with_callback.SynthProvider " - "--recognizer-function formatters_with_callback.derives_from_base") + self.runCmd( + "command script import --allow-reload ./formatters_with_callback.py" + ) + self.runCmd( + "type summary add -e -s 'hello from callback summary' " + "--recognizer-function formatters_with_callback.derives_from_base" + ) + self.runCmd( + "type synth add -l formatters_with_callback.SynthProvider " + "--recognizer-function formatters_with_callback.derives_from_base" + ) # Now `derived` should use our callback summary + synthetic children. - self.expect("frame variable derived", - substrs=['hello from callback summary', - 'synthetic_child = 9999']) + self.expect( + "frame variable derived", + substrs=["hello from callback summary", "synthetic_child = 9999"], + ) # But not other classes. - self.expect("frame variable base", matching=False, - substrs=['hello from callback summary']) - self.expect("frame variable base", - substrs=['x = 1111']) - - self.expect("frame variable nd", matching=False, - substrs=['hello from callback summary']) - self.expect("frame variable nd", - substrs=['z = 4444']) - + self.expect( + "frame variable base", + matching=False, + substrs=["hello from callback summary"], + ) + self.expect("frame variable base", substrs=["x = 1111"]) + + self.expect( + "frame variable nd", matching=False, substrs=["hello from callback summary"] + ) + self.expect("frame variable nd", substrs=["z = 4444"]) diff --git a/lldb/test/API/functionalities/data-formatter/callback-matching/formatters_with_callback.py b/lldb/test/API/functionalities/data-formatter/callback-matching/formatters_with_callback.py --- a/lldb/test/API/functionalities/data-formatter/callback-matching/formatters_with_callback.py +++ b/lldb/test/API/functionalities/data-formatter/callback-matching/formatters_with_callback.py @@ -1,5 +1,6 @@ import lldb + def derives_from_base(sbtype, internal_dict): for base in sbtype.get_bases_array(): if base.GetName() == "Base": @@ -19,21 +20,24 @@ def get_child_at_index(self, index): if index == 0: - return self.valobj.CreateValueFromExpression("synthetic_child", - "9999") + return self.valobj.CreateValueFromExpression("synthetic_child", "9999") return None def register_formatters(debugger): cat = debugger.CreateCategory("callback_formatters") cat.AddTypeSummary( - lldb.SBTypeNameSpecifier("formatters_with_callback.derives_from_base", - lldb.eFormatterMatchCallback), - lldb.SBTypeSummary.CreateWithScriptCode( - "return 'hello from callback summary'")) + lldb.SBTypeNameSpecifier( + "formatters_with_callback.derives_from_base", lldb.eFormatterMatchCallback + ), + lldb.SBTypeSummary.CreateWithScriptCode("return 'hello from callback summary'"), + ) cat.AddTypeSynthetic( - lldb.SBTypeNameSpecifier('formatters_with_callback.derives_from_base', - lldb.eFormatterMatchCallback), + lldb.SBTypeNameSpecifier( + "formatters_with_callback.derives_from_base", lldb.eFormatterMatchCallback + ), lldb.SBTypeSynthetic.CreateWithClassName( - 'formatters_with_callback.SynthProvider')) + "formatters_with_callback.SynthProvider" + ), + ) cat.SetEnabled(True) diff --git a/lldb/test/API/functionalities/data-formatter/compactvectors/TestCompactVectors.py b/lldb/test/API/functionalities/data-formatter/compactvectors/TestCompactVectors.py --- a/lldb/test/API/functionalities/data-formatter/compactvectors/TestCompactVectors.py +++ b/lldb/test/API/functionalities/data-formatter/compactvectors/TestCompactVectors.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class CompactVectorsFormattingTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") @skipUnlessDarwin def test_with_run_command(self): @@ -25,35 +23,39 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type summary clear', check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.expect( - 'frame variable', + "frame variable", substrs=[ - '(vFloat) valueFL = (1.25, 0, 0.25, 0)', - '(vDouble) valueDL = (1.25, 2.25)', - '(int16_t[8]) valueI16 = (1, 0, 4, 0, 0, 1, 0, 4)', - '(int32_t[4]) valueI32 = (1, 0, 4, 0)', - '(vUInt8) valueU8 = (0x01, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)', - '(vUInt16) valueU16 = (1, 0, 4, 0, 0, 1, 0, 4)', - '(vUInt32) valueU32 = (1, 2, 3, 4)', - '(vSInt8) valueS8 = (1, 0, 4, 0, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0)', - '(vSInt16) valueS16 = (1, 0, 4, 0, 0, 1, 0, 4)', - '(vSInt32) valueS32 = (4, 3, 2, 1)', - '(vBool32) valueBool32 = (0, 1, 0, 1)', - ]) + "(vFloat) valueFL = (1.25, 0, 0.25, 0)", + "(vDouble) valueDL = (1.25, 2.25)", + "(int16_t[8]) valueI16 = (1, 0, 4, 0, 0, 1, 0, 4)", + "(int32_t[4]) valueI32 = (1, 0, 4, 0)", + "(vUInt8) valueU8 = (0x01, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)", + "(vUInt16) valueU16 = (1, 0, 4, 0, 0, 1, 0, 4)", + "(vUInt32) valueU32 = (1, 2, 3, 4)", + "(vSInt8) valueS8 = (1, 0, 4, 0, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0)", + "(vSInt16) valueS16 = (1, 0, 4, 0, 0, 1, 0, 4)", + "(vSInt32) valueS32 = (4, 3, 2, 1)", + "(vBool32) valueBool32 = (0, 1, 0, 1)", + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/cstring-utf8-summary/TestCstringUnicode.py b/lldb/test/API/functionalities/data-formatter/cstring-utf8-summary/TestCstringUnicode.py --- a/lldb/test/API/functionalities/data-formatter/cstring-utf8-summary/TestCstringUnicode.py +++ b/lldb/test/API/functionalities/data-formatter/cstring-utf8-summary/TestCstringUnicode.py @@ -10,7 +10,8 @@ def test_cstring_unicode(self): self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", - lldb.SBFileSpec("main.cpp", False)) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) self.expect_expr("s", result_summary='"🔥"') self.expect_expr("(const char*)s", result_summary='"🔥"') diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py b/lldb/test/API/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py @@ -3,19 +3,17 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class AdvDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" @@ -23,326 +21,311 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.runCmd("type summary add --summary-string \"pippo\" \"i_am_cool\"") + self.runCmd('type summary add --summary-string "pippo" "i_am_cool"') - self.runCmd( - "type summary add --summary-string \"pluto\" -x \"i_am_cool[a-z]*\"") + self.runCmd('type summary add --summary-string "pluto" -x "i_am_cool[a-z]*"') - self.expect("frame variable cool_boy", - substrs=['pippo']) + self.expect("frame variable cool_boy", substrs=["pippo"]) - self.expect("frame variable cooler_boy", - substrs=['pluto']) + self.expect("frame variable cooler_boy", substrs=["pluto"]) self.runCmd("type summary delete i_am_cool") - self.expect("frame variable cool_boy", - substrs=['pluto']) + self.expect("frame variable cool_boy", substrs=["pluto"]) self.runCmd("type summary clear") - self.runCmd( - "type summary add --summary-string \"${var[]}\" -x \"^int\\[[0-9]\\]") + self.runCmd('type summary add --summary-string "${var[]}" -x "^int\\[[0-9]\\]') - self.expect("frame variable int_array", - substrs=['1,2,3,4,5']) - self.expect("frame variable const_int_array", - substrs=['11,12,13,14,15']) + self.expect("frame variable int_array", substrs=["1,2,3,4,5"]) + self.expect("frame variable const_int_array", substrs=["11,12,13,14,15"]) # this will fail if we don't do [] as regex correctly - self.runCmd( - 'type summary add --summary-string "${var[].integer}" "i_am_cool[]') + self.runCmd('type summary add --summary-string "${var[].integer}" "i_am_cool[]') - self.expect("frame variable cool_array", - substrs=['1,1,1,1,6']) + self.expect("frame variable cool_array", substrs=["1,1,1,1,6"]) self.runCmd("type summary clear") - self.runCmd( - "type summary add --summary-string \"${var[1-0]%x}\" \"int\"") + self.runCmd('type summary add --summary-string "${var[1-0]%x}" "int"') - self.expect("frame variable iAmInt", - substrs=['01']) + self.expect("frame variable iAmInt", substrs=["01"]) - self.runCmd( - "type summary add --summary-string \"${var[0-1]%x}\" \"int\"") + self.runCmd('type summary add --summary-string "${var[0-1]%x}" "int"') - self.expect("frame variable iAmInt", - substrs=['01']) + self.expect("frame variable iAmInt", substrs=["01"]) self.runCmd("type summary clear") - self.runCmd("type summary add --summary-string \"${var[0-1]%x}\" int") - self.runCmd( - "type summary add --summary-string \"${var[0-31]%x}\" float") + self.runCmd('type summary add --summary-string "${var[0-1]%x}" int') + self.runCmd('type summary add --summary-string "${var[0-31]%x}" float') - self.expect("frame variable *pointer", - substrs=['0x', - '2']) + self.expect("frame variable *pointer", substrs=["0x", "2"]) # check fix for LLDB crashes when using a # "type summary" that uses bitfields with no format - self.runCmd("type summary add --summary-string \"${var[0-1]}\" int") - self.expect("frame variable iAmInt", - substrs=['9 1']) + self.runCmd('type summary add --summary-string "${var[0-1]}" int') + self.expect("frame variable iAmInt", substrs=["9 1"]) - self.expect("frame variable cool_array[3].floating", - substrs=['0x']) + self.expect("frame variable cool_array[3].floating", substrs=["0x"]) self.runCmd( - "type summary add --summary-string \"low bits are ${*var[0-1]} tgt is ${*var}\" \"int *\"") + 'type summary add --summary-string "low bits are ${*var[0-1]} tgt is ${*var}" "int *"' + ) - self.expect("frame variable pointer", - substrs=['low bits are', - 'tgt is 6']) + self.expect("frame variable pointer", substrs=["low bits are", "tgt is 6"]) self.expect( - "frame variable int_array --summary-string \"${*var[0-1]}\"", - substrs=['3']) + 'frame variable int_array --summary-string "${*var[0-1]}"', substrs=["3"] + ) self.runCmd("type summary clear") - self.runCmd( - 'type summary add --summary-string \"${var[0-1]}\" -x \"int\[[0-9]\]\"') + self.runCmd('type summary add --summary-string "${var[0-1]}" -x "int\[[0-9]\]"') - self.expect("frame variable int_array", - substrs=['1,2']) + self.expect("frame variable int_array", substrs=["1,2"]) - self.runCmd( - 'type summary add --summary-string \"${var[0-1]}\" "int[]"') + self.runCmd('type summary add --summary-string "${var[0-1]}" "int[]"') - self.expect("frame variable int_array", - substrs=['1,2']) + self.expect("frame variable int_array", substrs=["1,2"]) # Test the patterns are matched in reverse-chronological order. - self.runCmd( - 'type summary add --summary-string \"${var[2-3]}\" "int[]"') + self.runCmd('type summary add --summary-string "${var[2-3]}" "int[]"') - self.expect("frame variable int_array", - substrs=['3,4']) + self.expect("frame variable int_array", substrs=["3,4"]) self.runCmd("type summary clear") - self.runCmd("type summary add -c -x \"i_am_cool\[[0-9]\]\"") + self.runCmd('type summary add -c -x "i_am_cool\[[0-9]\]"') self.runCmd("type summary add -c i_am_cool") self.expect( "frame variable cool_array", substrs=[ - '[0]', - 'integer', - 'floating', - 'character', - '[1]', - 'integer', - 'floating', - 'character', - '[2]', - 'integer', - 'floating', - 'character', - '[3]', - 'integer', - 'floating', - 'character', - '[4]', - 'integer', - 'floating', - 'character', - ]) + "[0]", + "integer", + "floating", + "character", + "[1]", + "integer", + "floating", + "character", + "[2]", + "integer", + "floating", + "character", + "[3]", + "integer", + "floating", + "character", + "[4]", + "integer", + "floating", + "character", + ], + ) self.runCmd( - "type summary add --summary-string \"int = ${*var.int_pointer}, float = ${*var.float_pointer}\" IWrapPointers") + 'type summary add --summary-string "int = ${*var.int_pointer}, float = ${*var.float_pointer}" IWrapPointers' + ) - self.expect("frame variable wrapper", - substrs=['int = 4', - 'float = 1.1']) + self.expect("frame variable wrapper", substrs=["int = 4", "float = 1.1"]) self.runCmd( - "type summary add --summary-string \"low bits = ${*var.int_pointer[2]}\" IWrapPointers -p") + 'type summary add --summary-string "low bits = ${*var.int_pointer[2]}" IWrapPointers -p' + ) - self.expect("frame variable wrapper", - substrs=['low bits = 1']) + self.expect("frame variable wrapper", substrs=["low bits = 1"]) - self.expect("frame variable *wrap_pointer", - substrs=['low bits = 1']) + self.expect("frame variable *wrap_pointer", substrs=["low bits = 1"]) self.runCmd("type summary clear") self.expect( - "frame variable int_array --summary-string \"${var[0][0-2]%hex}\"", - substrs=[ - '0x', - '7']) + 'frame variable int_array --summary-string "${var[0][0-2]%hex}"', + substrs=["0x", "7"], + ) self.runCmd("type summary clear") self.runCmd( - "type summary add --summary-string \"${*var[].x[0-3]%hex} is a bitfield on a set of integers\" -x \"SimpleWithPointers\[[0-9]\]\"") + 'type summary add --summary-string "${*var[].x[0-3]%hex} is a bitfield on a set of integers" -x "SimpleWithPointers\[[0-9]\]"' + ) self.expect( - "frame variable couple --summary-string \"${*var.sp.x[0-2]} are low bits of integer ${*var.sp.x}. If I pretend it is an array I get ${var.sp.x[0-5]}\"", + 'frame variable couple --summary-string "${*var.sp.x[0-2]} are low bits of integer ${*var.sp.x}. If I pretend it is an array I get ${var.sp.x[0-5]}"', substrs=[ - '1 are low bits of integer 9.', - 'If I pretend it is an array I get [9,']) + "1 are low bits of integer 9.", + "If I pretend it is an array I get [9,", + ], + ) # if the summary has an error, we still display the value self.expect( - "frame variable couple --summary-string \"${*var.sp.foo[0-2]\"", - substrs=[ - '(Couple) couple = {', - 'x = 0x', - 'y = 0x', - 'z = 0x', - 's = 0x']) + 'frame variable couple --summary-string "${*var.sp.foo[0-2]"', + substrs=["(Couple) couple = {", "x = 0x", "y = 0x", "z = 0x", "s = 0x"], + ) self.runCmd( - "type summary add --summary-string \"${*var.sp.x[0-2]} are low bits of integer ${*var.sp.x}. If I pretend it is an array I get ${var.sp.x[0-5]}\" Couple") + 'type summary add --summary-string "${*var.sp.x[0-2]} are low bits of integer ${*var.sp.x}. If I pretend it is an array I get ${var.sp.x[0-5]}" Couple' + ) - self.expect("frame variable sparray", - substrs=['[0x0000000f,0x0000000c,0x00000009]']) + self.expect( + "frame variable sparray", substrs=["[0x0000000f,0x0000000c,0x00000009]"] + ) # check that we can format a variable in a summary even if a format is # defined for its datatype self.runCmd("type format add -f hex int") - self.runCmd( - "type summary add --summary-string \"x=${var.x%d}\" Simple") + self.runCmd('type summary add --summary-string "x=${var.x%d}" Simple') - self.expect("frame variable a_simple_object", - substrs=['x=3']) + self.expect("frame variable a_simple_object", substrs=["x=3"]) - self.expect("frame variable a_simple_object", matching=False, - substrs=['0x0']) + self.expect("frame variable a_simple_object", matching=False, substrs=["0x0"]) # now check that the default is applied if we do not hand out a format - self.runCmd("type summary add --summary-string \"x=${var.x}\" Simple") + self.runCmd('type summary add --summary-string "x=${var.x}" Simple') - self.expect("frame variable a_simple_object", matching=False, - substrs=['x=3']) + self.expect("frame variable a_simple_object", matching=False, substrs=["x=3"]) - self.expect("frame variable a_simple_object", matching=True, - substrs=['x=0x00000003']) + self.expect( + "frame variable a_simple_object", matching=True, substrs=["x=0x00000003"] + ) - self.expect_var_path("constInt", value='0x0000002a') + self.expect_var_path("constInt", value="0x0000002a") - self.expect_var_path("volatileInt", value='0x0000002b') + self.expect_var_path("volatileInt", value="0x0000002b") - self.expect_var_path("constVolatileInt", value='0x0000002c') + self.expect_var_path("constVolatileInt", value="0x0000002c") # check that we can correctly cap the number of children shown self.runCmd("settings set target.max-children-count 5") - self.expect('frame variable a_long_guy', matching=True, - substrs=['a_1', - 'b_1', - 'c_1', - 'd_1', - 'e_1', - '...']) + self.expect( + "frame variable a_long_guy", + matching=True, + substrs=["a_1", "b_1", "c_1", "d_1", "e_1", "..."], + ) # check that no further stuff is printed (not ALL values are checked!) - self.expect('frame variable a_long_guy', matching=False, - substrs=['f_1', - 'g_1', - 'h_1', - 'i_1', - 'j_1', - 'q_1', - 'a_2', - 'f_2', - 't_2', - 'w_2']) + self.expect( + "frame variable a_long_guy", + matching=False, + substrs=[ + "f_1", + "g_1", + "h_1", + "i_1", + "j_1", + "q_1", + "a_2", + "f_2", + "t_2", + "w_2", + ], + ) self.runCmd("settings set target.max-children-count 1") - self.expect('frame variable a_long_guy', matching=True, - substrs=['a_1', - '...']) - self.expect('frame variable a_long_guy', matching=False, - substrs=['b_1', - 'c_1', - 'd_1', - 'e_1']) - self.expect('frame variable a_long_guy', matching=False, - substrs=['f_1', - 'g_1', - 'h_1', - 'i_1', - 'j_1', - 'q_1', - 'a_2', - 'f_2', - 't_2', - 'w_2']) + self.expect("frame variable a_long_guy", matching=True, substrs=["a_1", "..."]) + self.expect( + "frame variable a_long_guy", + matching=False, + substrs=["b_1", "c_1", "d_1", "e_1"], + ) + self.expect( + "frame variable a_long_guy", + matching=False, + substrs=[ + "f_1", + "g_1", + "h_1", + "i_1", + "j_1", + "q_1", + "a_2", + "f_2", + "t_2", + "w_2", + ], + ) self.runCmd("settings set target.max-children-count 30") - self.expect('frame variable a_long_guy', matching=True, - substrs=['a_1', - 'b_1', - 'c_1', - 'd_1', - 'e_1', - 'z_1', - 'a_2', - 'b_2', - 'c_2', - 'd_2', - '...']) - self.expect('frame variable a_long_guy', matching=False, - substrs=['e_2', - 'n_2', - 'r_2', - 'i_2', - 'k_2', - 'o_2']) + self.expect( + "frame variable a_long_guy", + matching=True, + substrs=[ + "a_1", + "b_1", + "c_1", + "d_1", + "e_1", + "z_1", + "a_2", + "b_2", + "c_2", + "d_2", + "...", + ], + ) + self.expect( + "frame variable a_long_guy", + matching=False, + substrs=["e_2", "n_2", "r_2", "i_2", "k_2", "o_2"], + ) # override the cap self.expect( - 'frame variable a_long_guy --show-all-children', + "frame variable a_long_guy --show-all-children", matching=True, substrs=[ - 'a_1', - 'b_1', - 'c_1', - 'd_1', - 'e_1', - 'z_1', - 'a_2', - 'b_2', - 'c_2', - 'd_2']) + "a_1", + "b_1", + "c_1", + "d_1", + "e_1", + "z_1", + "a_2", + "b_2", + "c_2", + "d_2", + ], + ) self.expect( - 'frame variable a_long_guy --show-all-children', + "frame variable a_long_guy --show-all-children", matching=True, substrs=[ - 'e_2', - 'i_2', - 'k_2', - 'n_2', - 'o_2', - 'r_2', - ]) + "e_2", + "i_2", + "k_2", + "n_2", + "o_2", + "r_2", + ], + ) self.expect( - 'frame variable a_long_guy --show-all-children', + "frame variable a_long_guy --show-all-children", matching=False, - substrs=['...']) + substrs=["..."], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-caching/TestDataFormatterCaching.py b/lldb/test/API/functionalities/data-formatter/data-formatter-caching/TestDataFormatterCaching.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-caching/TestDataFormatterCaching.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-caching/TestDataFormatterCaching.py @@ -5,18 +5,19 @@ class TestDataFormatterCaching(TestBase): - def test_with_run_command(self): """ Test that hardcoded summary formatter matches aren't improperly cached. """ self.build() target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( - self, 'break here', lldb.SBFileSpec('a.c')) - valobj = self.frame().FindVariable('f') - self.assertEqual(valobj.GetValue(), '4') - bkpt_b = target.BreakpointCreateBySourceRegex('break here', - lldb.SBFileSpec('b.c')) + self, "break here", lldb.SBFileSpec("a.c") + ) + valobj = self.frame().FindVariable("f") + self.assertEqual(valobj.GetValue(), "4") + bkpt_b = target.BreakpointCreateBySourceRegex( + "break here", lldb.SBFileSpec("b.c") + ) lldbutil.continue_to_breakpoint(process, bkpt_b) - valobj = self.frame().FindVariable('f4') - self.assertEqual(valobj.GetSummary(), '(1, 2, 3, 4)') + valobj = self.frame().FindVariable("f4") + self.assertEqual(valobj.GetSummary(), "(1, 2, 3, 4)") diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py b/lldb/test/API/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py @@ -9,12 +9,11 @@ class CategoriesDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") @expectedFlakeyNetBSD @expectedFailureAll(oslist=["windows"]) @@ -24,28 +23,29 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case (most of these categories do not # exist anymore, but we just make sure we delete all of them) def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type category delete Category1', check=False) - self.runCmd('type category delete Category2', check=False) - self.runCmd('type category delete NewCategory', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type category delete Category1", check=False) + self.runCmd("type category delete Category2", check=False) + self.runCmd("type category delete NewCategory", check=False) self.runCmd("type category delete CircleCategory", check=False) - self.runCmd( - "type category delete RectangleStarCategory", - check=False) + self.runCmd("type category delete RectangleStarCategory", check=False) self.runCmd("type category delete BaseCategory", check=False) # Execute the cleanup function during test case tear down. @@ -53,302 +53,288 @@ # Add a summary to a new category and check that it works self.runCmd( - "type summary add Rectangle --summary-string \"ARectangle\" -w NewCategory") + 'type summary add Rectangle --summary-string "ARectangle" -w NewCategory' + ) - self.expect("frame variable r1 r2 r3", matching=False, - substrs=['r1 = ARectangle', - 'r2 = ARectangle', - 'r3 = ARectangle']) + self.expect( + "frame variable r1 r2 r3", + matching=False, + substrs=["r1 = ARectangle", "r2 = ARectangle", "r3 = ARectangle"], + ) self.runCmd("type category enable NewCategory") - self.expect("frame variable r1 r2 r3", matching=True, - substrs=['r1 = ARectangle', - 'r2 = ARectangle', - 'r3 = ARectangle']) + self.expect( + "frame variable r1 r2 r3", + matching=True, + substrs=["r1 = ARectangle", "r2 = ARectangle", "r3 = ARectangle"], + ) # Disable the category and check that the old stuff is there self.runCmd("type category disable NewCategory") - self.expect("frame variable r1 r2 r3", - substrs=['r1 = {', - 'r2 = {', - 'r3 = {']) + self.expect("frame variable r1 r2 r3", substrs=["r1 = {", "r2 = {", "r3 = {"]) # Re-enable the category and check that it works self.runCmd("type category enable NewCategory") - self.expect("frame variable r1 r2 r3", - substrs=['r1 = ARectangle', - 'r2 = ARectangle', - 'r3 = ARectangle']) + self.expect( + "frame variable r1 r2 r3", + substrs=["r1 = ARectangle", "r2 = ARectangle", "r3 = ARectangle"], + ) # Delete the category and the old stuff should be there self.runCmd("type category delete NewCategory") - self.expect("frame variable r1 r2 r3", - substrs=['r1 = {', - 'r2 = {', - 'r3 = {']) + self.expect("frame variable r1 r2 r3", substrs=["r1 = {", "r2 = {", "r3 = {"]) # Add summaries to two different categories and check that we can # switch self.runCmd( - "type summary add --summary-string \"Width = ${var.w}, Height = ${var.h}\" Rectangle -w Category1") - self.runCmd("type summary add --python-script \"return 'Area = ' + str( int(valobj.GetChildMemberWithName('w').GetValue()) * int(valobj.GetChildMemberWithName('h').GetValue()) );\" Rectangle -w Category2") + 'type summary add --summary-string "Width = ${var.w}, Height = ${var.h}" Rectangle -w Category1' + ) + self.runCmd( + "type summary add --python-script \"return 'Area = ' + str( int(valobj.GetChildMemberWithName('w').GetValue()) * int(valobj.GetChildMemberWithName('h').GetValue()) );\" Rectangle -w Category2" + ) # check that enable A B is the same as enable B enable A self.runCmd("type category enable Category1 Category2") - self.expect("frame variable r1 r2 r3", - substrs=['r1 = Width = ', - 'r2 = Width = ', - 'r3 = Width = ']) + self.expect( + "frame variable r1 r2 r3", + substrs=["r1 = Width = ", "r2 = Width = ", "r3 = Width = "], + ) self.runCmd("type category disable Category1") - self.expect("frame variable r1 r2 r3", - substrs=['r1 = Area = ', - 'r2 = Area = ', - 'r3 = Area = ']) + self.expect( + "frame variable r1 r2 r3", + substrs=["r1 = Area = ", "r2 = Area = ", "r3 = Area = "], + ) # switch again self.runCmd("type category enable Category1") - self.expect("frame variable r1 r2 r3", - substrs=['r1 = Width = ', - 'r2 = Width = ', - 'r3 = Width = ']) + self.expect( + "frame variable r1 r2 r3", + substrs=["r1 = Width = ", "r2 = Width = ", "r3 = Width = "], + ) # Re-enable the category and show that the preference is persisted self.runCmd("type category disable Category2") self.runCmd("type category enable Category2") - self.expect("frame variable r1 r2 r3", - substrs=['r1 = Area = ', - 'r2 = Area = ', - 'r3 = Area = ']) + self.expect( + "frame variable r1 r2 r3", + substrs=["r1 = Area = ", "r2 = Area = ", "r3 = Area = "], + ) # Now delete the favorite summary self.runCmd("type summary delete Rectangle -w Category2") - self.expect("frame variable r1 r2 r3", - substrs=['r1 = Width = ', - 'r2 = Width = ', - 'r3 = Width = ']) + self.expect( + "frame variable r1 r2 r3", + substrs=["r1 = Width = ", "r2 = Width = ", "r3 = Width = "], + ) # Delete the summary from the default category (that does not have it) self.runCmd("type summary delete Rectangle", check=False) - self.expect("frame variable r1 r2 r3", - substrs=['r1 = Width = ', - 'r2 = Width = ', - 'r3 = Width = ']) + self.expect( + "frame variable r1 r2 r3", + substrs=["r1 = Width = ", "r2 = Width = ", "r3 = Width = "], + ) # Now add another summary to another category and switch back and forth self.runCmd("type category delete Category1 Category2") self.runCmd( - "type summary add Rectangle -w Category1 --summary-string \"Category1\"") + 'type summary add Rectangle -w Category1 --summary-string "Category1"' + ) self.runCmd( - "type summary add Rectangle -w Category2 --summary-string \"Category2\"") + 'type summary add Rectangle -w Category2 --summary-string "Category2"' + ) self.runCmd("type category enable Category2") self.runCmd("type category enable Category1") self.runCmd("type summary list -w Category1") - self.expect("type summary list -w NoSuchCategoryHere", - substrs=['no matching results found']) + self.expect( + "type summary list -w NoSuchCategoryHere", + substrs=["no matching results found"], + ) - self.expect("frame variable r1 r2 r3", - substrs=['r1 = Category1', - 'r2 = Category1', - 'r3 = Category1']) + self.expect( + "frame variable r1 r2 r3", + substrs=["r1 = Category1", "r2 = Category1", "r3 = Category1"], + ) self.runCmd("type category disable Category1") - self.expect("frame variable r1 r2 r3", - substrs=['r1 = Category2', - 'r2 = Category2', - 'r3 = Category2']) + self.expect( + "frame variable r1 r2 r3", + substrs=["r1 = Category2", "r2 = Category2", "r3 = Category2"], + ) # Check that re-enabling an enabled category works self.runCmd("type category enable Category1") - self.expect("frame variable r1 r2 r3", - substrs=['r1 = Category1', - 'r2 = Category1', - 'r3 = Category1']) + self.expect( + "frame variable r1 r2 r3", + substrs=["r1 = Category1", "r2 = Category1", "r3 = Category1"], + ) self.runCmd("type category delete Category1") self.runCmd("type category delete Category2") - self.expect("frame variable r1 r2 r3", - substrs=['r1 = {', - 'r2 = {', - 'r3 = {']) + self.expect("frame variable r1 r2 r3", substrs=["r1 = {", "r2 = {", "r3 = {"]) # Check that multiple summaries can go into one category self.runCmd( - "type summary add -w Category1 --summary-string \"Width = ${var.w}, Height = ${var.h}\" Rectangle") + 'type summary add -w Category1 --summary-string "Width = ${var.w}, Height = ${var.h}" Rectangle' + ) self.runCmd( - "type summary add -w Category1 --summary-string \"Radius = ${var.r}\" Circle") + 'type summary add -w Category1 --summary-string "Radius = ${var.r}" Circle' + ) self.runCmd("type category enable Category1") - self.expect("frame variable r1 r2 r3", - substrs=['r1 = Width = ', - 'r2 = Width = ', - 'r3 = Width = ']) + self.expect( + "frame variable r1 r2 r3", + substrs=["r1 = Width = ", "r2 = Width = ", "r3 = Width = "], + ) - self.expect("frame variable c1 c2 c3", - substrs=['c1 = Radius = ', - 'c2 = Radius = ', - 'c3 = Radius = ']) + self.expect( + "frame variable c1 c2 c3", + substrs=["c1 = Radius = ", "c2 = Radius = ", "c3 = Radius = "], + ) self.runCmd("type summary delete Circle -w Category1") - self.expect("frame variable c1 c2 c3", - substrs=['c1 = {', - 'c2 = {', - 'c3 = {']) + self.expect("frame variable c1 c2 c3", substrs=["c1 = {", "c2 = {", "c3 = {"]) # Add a regex based summary to a category self.runCmd( - "type summary add -w Category1 --summary-string \"Radius = ${var.r}\" -x Circle") + 'type summary add -w Category1 --summary-string "Radius = ${var.r}" -x Circle' + ) - self.expect("frame variable r1 r2 r3", - substrs=['r1 = Width = ', - 'r2 = Width = ', - 'r3 = Width = ']) + self.expect( + "frame variable r1 r2 r3", + substrs=["r1 = Width = ", "r2 = Width = ", "r3 = Width = "], + ) - self.expect("frame variable c1 c2 c3", - substrs=['c1 = Radius = ', - 'c2 = Radius = ', - 'c3 = Radius = ']) + self.expect( + "frame variable c1 c2 c3", + substrs=["c1 = Radius = ", "c2 = Radius = ", "c3 = Radius = "], + ) # Delete it self.runCmd("type summary delete Circle -w Category1") - self.expect("frame variable c1 c2 c3", - substrs=['c1 = {', - 'c2 = {', - 'c3 = {']) + self.expect("frame variable c1 c2 c3", substrs=["c1 = {", "c2 = {", "c3 = {"]) # Change a summary inside a category and check that the change is # reflected - self.runCmd( - "type summary add Circle -w Category1 --summary-string \"summary1\"") + self.runCmd('type summary add Circle -w Category1 --summary-string "summary1"') - self.expect("frame variable c1 c2 c3", - substrs=['c1 = summary1', - 'c2 = summary1', - 'c3 = summary1']) + self.expect( + "frame variable c1 c2 c3", + substrs=["c1 = summary1", "c2 = summary1", "c3 = summary1"], + ) - self.runCmd( - "type summary add Circle -w Category1 --summary-string \"summary2\"") + self.runCmd('type summary add Circle -w Category1 --summary-string "summary2"') - self.expect("frame variable c1 c2 c3", - substrs=['c1 = summary2', - 'c2 = summary2', - 'c3 = summary2']) + self.expect( + "frame variable c1 c2 c3", + substrs=["c1 = summary2", "c2 = summary2", "c3 = summary2"], + ) # Check that our order of priority works. Start by clearing categories self.runCmd("type category delete Category1") - self.runCmd( - "type summary add Shape -w BaseCategory --summary-string \"AShape\"") + self.runCmd('type summary add Shape -w BaseCategory --summary-string "AShape"') self.runCmd("type category enable BaseCategory") - self.expect("expression (Shape*)&c1", - substrs=['AShape']) - self.expect("expression (Shape*)&r1", - substrs=['AShape']) - self.expect("expression (Shape*)c_ptr", - substrs=['AShape']) - self.expect("expression (Shape*)r_ptr", - substrs=['AShape']) + self.expect("expression (Shape*)&c1", substrs=["AShape"]) + self.expect("expression (Shape*)&r1", substrs=["AShape"]) + self.expect("expression (Shape*)c_ptr", substrs=["AShape"]) + self.expect("expression (Shape*)r_ptr", substrs=["AShape"]) self.runCmd( - "type summary add Circle -w CircleCategory --summary-string \"ACircle\"") + 'type summary add Circle -w CircleCategory --summary-string "ACircle"' + ) self.runCmd( - "type summary add Rectangle -w RectangleCategory --summary-string \"ARectangle\"") + 'type summary add Rectangle -w RectangleCategory --summary-string "ARectangle"' + ) self.runCmd("type category enable CircleCategory") - self.expect("frame variable c1", - substrs=['ACircle']) - self.expect("frame variable c_ptr", - substrs=['ACircle']) + self.expect("frame variable c1", substrs=["ACircle"]) + self.expect("frame variable c_ptr", substrs=["ACircle"]) self.runCmd( - "type summary add \"Rectangle *\" -w RectangleStarCategory --summary-string \"ARectangleStar\"") + 'type summary add "Rectangle *" -w RectangleStarCategory --summary-string "ARectangleStar"' + ) self.runCmd("type category enable RectangleStarCategory") - self.expect("frame variable c1 r1 c_ptr r_ptr", - substrs=['ACircle', - 'ARectangleStar']) + self.expect( + "frame variable c1 r1 c_ptr r_ptr", substrs=["ACircle", "ARectangleStar"] + ) self.runCmd("type category enable RectangleCategory") - self.expect("frame variable c1 r1 c_ptr r_ptr", - substrs=['ACircle', - 'ACircle', - 'ARectangle']) + self.expect( + "frame variable c1 r1 c_ptr r_ptr", + substrs=["ACircle", "ACircle", "ARectangle"], + ) # Check that abruptly deleting an enabled category does not crash us self.runCmd("type category delete RectangleCategory") - self.expect("frame variable c1 r1 c_ptr r_ptr", - substrs=['ACircle', - '(Rectangle) r1 = ', 'w = 5', 'h = 6', - 'ACircle', - 'ARectangleStar']) + self.expect( + "frame variable c1 r1 c_ptr r_ptr", + substrs=[ + "ACircle", + "(Rectangle) r1 = ", + "w = 5", + "h = 6", + "ACircle", + "ARectangleStar", + ], + ) # check that list commands work - self.expect("type category list", - substrs=['RectangleStarCategory (enabled)']) + self.expect("type category list", substrs=["RectangleStarCategory (enabled)"]) - self.expect("type summary list", - substrs=['ARectangleStar']) + self.expect("type summary list", substrs=["ARectangleStar"]) # Disable a category and check that it fallsback self.runCmd("type category disable CircleCategory") # check that list commands work - self.expect("type category list", - substrs=['CircleCategory (disabled']) + self.expect("type category list", substrs=["CircleCategory (disabled"]) - self.expect("frame variable c1 r_ptr", - substrs=['AShape', - 'ARectangleStar']) + self.expect("frame variable c1 r_ptr", substrs=["AShape", "ARectangleStar"]) # check that filters work into categories - self.runCmd( - "type filter add Rectangle --child w --category RectangleCategory") + self.runCmd("type filter add Rectangle --child w --category RectangleCategory") self.runCmd("type category enable RectangleCategory") self.runCmd( - "type summary add Rectangle --category RectangleCategory --summary-string \" \" -e") - self.expect('frame variable r2', - substrs=['w = 9']) - self.runCmd("type summary add Rectangle --summary-string \" \" -e") - self.expect('frame variable r2', matching=False, - substrs=['h = 16']) + 'type summary add Rectangle --category RectangleCategory --summary-string " " -e' + ) + self.expect("frame variable r2", substrs=["w = 9"]) + self.runCmd('type summary add Rectangle --summary-string " " -e') + self.expect("frame variable r2", matching=False, substrs=["h = 16"]) # Now delete all categories self.runCmd( - "type category delete CircleCategory RectangleStarCategory BaseCategory RectangleCategory") + "type category delete CircleCategory RectangleStarCategory BaseCategory RectangleCategory" + ) # check that a deleted category with filter does not blow us up - self.expect('frame variable r2', - substrs=['w = 9', - 'h = 16']) + self.expect("frame variable r2", substrs=["w = 9", "h = 16"]) # and also validate that one can print formatters for a language self.expect( - 'type summary list -l c++', - substrs=[ - 'vector', - 'map', - 'list', - 'string']) + "type summary list -l c++", substrs=["vector", "map", "list", "string"] + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py b/lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -15,7 +14,7 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" @@ -23,24 +22,28 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) - self.expect("frame variable", - substrs=['(Speed) SPILookHex = 5.55' # Speed by default is 5.55. - ]) + self.expect( + "frame variable", + substrs=["(Speed) SPILookHex = 5.55"], # Speed by default is 5.55. + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -53,255 +56,275 @@ # The type format list should show our custom formats. self.expect( "type format list", - substrs=['Speed', 'BitField', 'RealNumber', 'Type2', 'Type1']) + substrs=["Speed", "BitField", "RealNumber", "Type2", "Type1"], + ) - self.expect("frame variable", - patterns=['\(Speed\) SPILookHex = 0x[0-9a-f]+' # Speed should look hex-ish now. - ]) + self.expect( + "frame variable", + patterns=[ + "\(Speed\) SPILookHex = 0x[0-9a-f]+" # Speed should look hex-ish now. + ], + ) # gcc4.2 on Mac OS X skips typedef chains in the DWARF output - if self.getCompiler() in ['clang', 'llvm-gcc']: - self.expect("frame variable", - patterns=['\(SignalMask\) SMILookHex = 0x[0-9a-f]+' # SignalMask should look hex-ish now. - ]) - self.expect("frame variable", matching=False, - patterns=['\(Type4\) T4ILookChar = 0x[0-9a-f]+' # Type4 should NOT look hex-ish now. - ]) + if self.getCompiler() in ["clang", "llvm-gcc"]: + self.expect( + "frame variable", + patterns=[ + "\(SignalMask\) SMILookHex = 0x[0-9a-f]+" # SignalMask should look hex-ish now. + ], + ) + self.expect( + "frame variable", + matching=False, + patterns=[ + "\(Type4\) T4ILookChar = 0x[0-9a-f]+" # Type4 should NOT look hex-ish now. + ], + ) # Now let's delete the 'Speed' custom format. self.runCmd("type format delete Speed") # The type format list should not show 'Speed' at this point. - self.expect("type format list", matching=False, - substrs=['Speed']) + self.expect("type format list", matching=False, substrs=["Speed"]) # Delete type format for 'Speed', we should expect an error message. - self.expect("type format delete Speed", error=True, - substrs=['no custom formatter for Speed']) + self.expect( + "type format delete Speed", + error=True, + substrs=["no custom formatter for Speed"], + ) self.runCmd( - "type summary add --summary-string \"arr = ${var%s}\" -x \"char\\[[0-9]+\\]\" -v") + 'type summary add --summary-string "arr = ${var%s}" -x "char\\[[0-9]+\\]" -v' + ) - self.expect("frame variable strarr", - substrs=['arr = "Hello world!"']) + self.expect("frame variable strarr", substrs=['arr = "Hello world!"']) self.runCmd("type summary clear") - self.runCmd( - "type summary add --summary-string \"ptr = ${var%s}\" \"char *\" -v") + self.runCmd('type summary add --summary-string "ptr = ${var%s}" "char *" -v') - self.expect("frame variable strptr", - substrs=['ptr = "Hello world!"']) + self.expect("frame variable strptr", substrs=['ptr = "Hello world!"']) self.runCmd( - "type summary add --summary-string \"arr = ${var%s}\" -x \"char\\[[0-9]+\\]\" -v") + 'type summary add --summary-string "arr = ${var%s}" -x "char\\[[0-9]+\\]" -v' + ) - self.expect("frame variable strarr", - substrs=['arr = "Hello world!']) + self.expect("frame variable strarr", substrs=['arr = "Hello world!']) # check that rdar://problem/10011145 (Standard summary format for # char[] doesn't work as the result of "expr".) is solved - self.expect("expression strarr", - substrs=['arr = "Hello world!']) + self.expect("expression strarr", substrs=['arr = "Hello world!']) - self.expect("frame variable strptr", - substrs=['ptr = "Hello world!"']) + self.expect("frame variable strptr", substrs=['ptr = "Hello world!"']) - self.expect("expression strptr", - substrs=['ptr = "Hello world!"']) + self.expect("expression strptr", substrs=['ptr = "Hello world!"']) self.expect( - "expression (char*)\"1234567890123456789012345678901234567890123456789012345678901234ABC\"", + 'expression (char*)"1234567890123456789012345678901234567890123456789012345678901234ABC"', substrs=[ - '(char *) $', - ' = ptr = ', - '"1234567890123456789012345678901234567890123456789012345678901234ABC"']) + "(char *) $", + " = ptr = ", + '"1234567890123456789012345678901234567890123456789012345678901234ABC"', + ], + ) self.runCmd("type summary add -c TestPoint") - self.expect("frame variable iAmSomewhere", - substrs=['x = 4', - 'y = 6']) + self.expect("frame variable iAmSomewhere", substrs=["x = 4", "y = 6"]) - self.expect("type summary list", - substrs=['TestPoint', - 'one-line']) + self.expect("type summary list", substrs=["TestPoint", "one-line"]) - self.runCmd("type summary add --summary-string \"y=${var.y%x}\" TestPoint") + self.runCmd('type summary add --summary-string "y=${var.y%x}" TestPoint') - self.expect("frame variable iAmSomewhere", - substrs=['y=0x']) + self.expect("frame variable iAmSomewhere", substrs=["y=0x"]) self.runCmd( - "type summary add --summary-string \"y=${var.y},x=${var.x}\" TestPoint") + 'type summary add --summary-string "y=${var.y},x=${var.x}" TestPoint' + ) - self.expect("frame variable iAmSomewhere", - substrs=['y=6', - 'x=4']) + self.expect("frame variable iAmSomewhere", substrs=["y=6", "x=4"]) - self.runCmd("type summary add --summary-string \"hello\" TestPoint -e") + self.runCmd('type summary add --summary-string "hello" TestPoint -e') - self.expect("type summary list", - substrs=['TestPoint', - 'show children']) + self.expect("type summary list", substrs=["TestPoint", "show children"]) - self.expect("frame variable iAmSomewhere", - substrs=['hello', - 'x = 4', - '}']) + self.expect("frame variable iAmSomewhere", substrs=["hello", "x = 4", "}"]) self.runCmd( - "type summary add --summary-string \"Sign: ${var[31]%B} Exponent: ${var[23-30]%x} Mantissa: ${var[0-22]%u}\" ShowMyGuts") + 'type summary add --summary-string "Sign: ${var[31]%B} Exponent: ${var[23-30]%x} Mantissa: ${var[0-22]%u}" ShowMyGuts' + ) - self.expect("frame variable cool_pointer->floating", - substrs=['Sign: true', - 'Exponent: 0x', - '80']) + self.expect( + "frame variable cool_pointer->floating", + substrs=["Sign: true", "Exponent: 0x", "80"], + ) - self.runCmd("type summary add --summary-string \"a test\" i_am_cool") + self.runCmd('type summary add --summary-string "a test" i_am_cool') - self.expect("frame variable cool_pointer", - substrs=['a test']) + self.expect("frame variable cool_pointer", substrs=["a test"]) self.runCmd( - "type summary add --summary-string \"a test\" i_am_cool --skip-pointers") + 'type summary add --summary-string "a test" i_am_cool --skip-pointers' + ) - self.expect("frame variable cool_pointer", - substrs=['a test'], - matching=False) + self.expect("frame variable cool_pointer", substrs=["a test"], matching=False) - self.runCmd( - "type summary add --summary-string \"${var[1-3]}\" \"int[5]\"") + self.runCmd('type summary add --summary-string "${var[1-3]}" "int[5]"') - self.expect("frame variable int_array", - substrs=['2', - '3', - '4']) + self.expect("frame variable int_array", substrs=["2", "3", "4"]) self.runCmd("type summary clear") self.runCmd( - "type summary add --summary-string \"${var[0-2].integer}\" \"i_am_cool *\"") + 'type summary add --summary-string "${var[0-2].integer}" "i_am_cool *"' + ) self.runCmd( - "type summary add --summary-string \"${var[2-4].integer}\" \"i_am_cool[5]\"") + 'type summary add --summary-string "${var[2-4].integer}" "i_am_cool[5]"' + ) - self.expect("frame variable cool_array", - substrs=['1,1,6']) + self.expect("frame variable cool_array", substrs=["1,1,6"]) - self.expect("frame variable cool_pointer", - substrs=['3,0,0']) + self.expect("frame variable cool_pointer", substrs=["3,0,0"]) # test special symbols for formatting variables into summaries self.runCmd( - "type summary add --summary-string \"cool object @ ${var%L}\" i_am_cool") - self.runCmd("type summary delete \"i_am_cool[5]\"") + 'type summary add --summary-string "cool object @ ${var%L}" i_am_cool' + ) + self.runCmd('type summary delete "i_am_cool[5]"') # this test might fail if the compiler tries to store # these values into registers.. hopefully this is not # going to be the case - self.expect("frame variable cool_array", - substrs=['[0] = cool object @ 0x', - '[1] = cool object @ 0x', - '[2] = cool object @ 0x', - '[3] = cool object @ 0x', - '[4] = cool object @ 0x']) + self.expect( + "frame variable cool_array", + substrs=[ + "[0] = cool object @ 0x", + "[1] = cool object @ 0x", + "[2] = cool object @ 0x", + "[3] = cool object @ 0x", + "[4] = cool object @ 0x", + ], + ) # test getting similar output by exploiting ${var} = 'type @ location' # for aggregates - self.runCmd("type summary add --summary-string \"${var}\" i_am_cool") + self.runCmd('type summary add --summary-string "${var}" i_am_cool') # this test might fail if the compiler tries to store # these values into registers.. hopefully this is not # going to be the case - self.expect("frame variable cool_array", - substrs=['[0] = i_am_cool @ 0x', - '[1] = i_am_cool @ 0x', - '[2] = i_am_cool @ 0x', - '[3] = i_am_cool @ 0x', - '[4] = i_am_cool @ 0x']) + self.expect( + "frame variable cool_array", + substrs=[ + "[0] = i_am_cool @ 0x", + "[1] = i_am_cool @ 0x", + "[2] = i_am_cool @ 0x", + "[3] = i_am_cool @ 0x", + "[4] = i_am_cool @ 0x", + ], + ) # test getting same output by exploiting %T and %L together for # aggregates - self.runCmd( - "type summary add --summary-string \"${var%T} @ ${var%L}\" i_am_cool") + self.runCmd('type summary add --summary-string "${var%T} @ ${var%L}" i_am_cool') # this test might fail if the compiler tries to store # these values into registers.. hopefully this is not # going to be the case - self.expect("frame variable cool_array", - substrs=['[0] = i_am_cool @ 0x', - '[1] = i_am_cool @ 0x', - '[2] = i_am_cool @ 0x', - '[3] = i_am_cool @ 0x', - '[4] = i_am_cool @ 0x']) - - self.runCmd("type summary add --summary-string \"goofy\" i_am_cool") + self.expect( + "frame variable cool_array", + substrs=[ + "[0] = i_am_cool @ 0x", + "[1] = i_am_cool @ 0x", + "[2] = i_am_cool @ 0x", + "[3] = i_am_cool @ 0x", + "[4] = i_am_cool @ 0x", + ], + ) + + self.runCmd('type summary add --summary-string "goofy" i_am_cool') self.runCmd( - "type summary add --summary-string \"${var.second_cool%S}\" i_am_cooler") + 'type summary add --summary-string "${var.second_cool%S}" i_am_cooler' + ) - self.expect("frame variable the_coolest_guy", - substrs=['(i_am_cooler) the_coolest_guy = goofy']) + self.expect( + "frame variable the_coolest_guy", + substrs=["(i_am_cooler) the_coolest_guy = goofy"], + ) # check that unwanted type specifiers are removed self.runCmd("type summary delete i_am_cool") - self.runCmd( - "type summary add --summary-string \"goofy\" \"class i_am_cool\"") - self.expect("frame variable the_coolest_guy", - substrs=['(i_am_cooler) the_coolest_guy = goofy']) + self.runCmd('type summary add --summary-string "goofy" "class i_am_cool"') + self.expect( + "frame variable the_coolest_guy", + substrs=["(i_am_cooler) the_coolest_guy = goofy"], + ) self.runCmd("type summary delete i_am_cool") - self.runCmd( - "type summary add --summary-string \"goofy\" \"enum i_am_cool\"") - self.expect("frame variable the_coolest_guy", - substrs=['(i_am_cooler) the_coolest_guy = goofy']) + self.runCmd('type summary add --summary-string "goofy" "enum i_am_cool"') + self.expect( + "frame variable the_coolest_guy", + substrs=["(i_am_cooler) the_coolest_guy = goofy"], + ) self.runCmd("type summary delete i_am_cool") - self.runCmd( - "type summary add --summary-string \"goofy\" \"struct i_am_cool\"") - self.expect("frame variable the_coolest_guy", - substrs=['(i_am_cooler) the_coolest_guy = goofy']) + self.runCmd('type summary add --summary-string "goofy" "struct i_am_cool"') + self.expect( + "frame variable the_coolest_guy", + substrs=["(i_am_cooler) the_coolest_guy = goofy"], + ) # many spaces, but we still do the right thing self.runCmd("type summary delete i_am_cool") - self.runCmd( - "type summary add --summary-string \"goofy\" \"union i_am_cool\"") - self.expect("frame variable the_coolest_guy", - substrs=['(i_am_cooler) the_coolest_guy = goofy']) + self.runCmd('type summary add --summary-string "goofy" "union i_am_cool"') + self.expect( + "frame variable the_coolest_guy", + substrs=["(i_am_cooler) the_coolest_guy = goofy"], + ) # but that not *every* specifier is removed self.runCmd("type summary delete i_am_cool") - self.runCmd( - "type summary add --summary-string \"goofy\" \"wrong i_am_cool\"") - self.expect("frame variable the_coolest_guy", matching=False, - substrs=['(i_am_cooler) the_coolest_guy = goofy']) + self.runCmd('type summary add --summary-string "goofy" "wrong i_am_cool"') + self.expect( + "frame variable the_coolest_guy", + matching=False, + substrs=["(i_am_cooler) the_coolest_guy = goofy"], + ) # check that formats are not sticking since that is the behavior we # want - self.expect("frame variable iAmInt --format hex", - substrs=['(int) iAmInt = 0x00000001']) + self.expect( + "frame variable iAmInt --format hex", substrs=["(int) iAmInt = 0x00000001"] + ) self.expect( "frame variable iAmInt", matching=False, - substrs=['(int) iAmInt = 0x00000001']) - self.expect("frame variable iAmInt", substrs=['(int) iAmInt = 1']) + substrs=["(int) iAmInt = 0x00000001"], + ) + self.expect("frame variable iAmInt", substrs=["(int) iAmInt = 1"]) @skipIfWindows def test_mem_func_ptr_formats(self): self.build() - lldbutil.run_to_source_breakpoint(self, "Break in has_local_mem_func_pointers", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "Break in has_local_mem_func_pointers", lldb.SBFileSpec("main.cpp") + ) - self.expect( - "frame variable member_ptr", - patterns=['member_ptr = 0x[0-9a-z]+']) + self.expect("frame variable member_ptr", patterns=["member_ptr = 0x[0-9a-z]+"]) self.expect( "frame variable member_func_ptr", - patterns=['member_func_ptr = 0x[0-9a-z]+'], - substrs=['(a.out`IUseCharStar::member_func(int) at main.cpp:61)']) + patterns=["member_func_ptr = 0x[0-9a-z]+"], + substrs=["(a.out`IUseCharStar::member_func(int) at main.cpp:61)"], + ) self.expect( "frame variable ref_to_member_func_ptr", - patterns=['ref_to_member_func_ptr = 0x[0-9a-z]+'], - substrs=['(a.out`IUseCharStar::member_func(int) at main.cpp:61)']) + patterns=["ref_to_member_func_ptr = 0x[0-9a-z]+"], + substrs=["(a.out`IUseCharStar::member_func(int) at main.cpp:61)"], + ) self.expect( "frame variable virt_member_func_ptr", - patterns=['virt_member_func_ptr = 0x[0-9a-z]+$']) + patterns=["virt_member_func_ptr = 0x[0-9a-z]+$"], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py b/lldb/test/API/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,76 +10,86 @@ class DataFormatterDisablingTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") @expectedFailureAll( oslist=["windows"], - bugnumber="llvm.org/pr24462, Data formatters have problems on Windows") + bugnumber="llvm.org/pr24462, Data formatters have problems on Windows", + ) def test_with_run_command(self): """Check that we can properly disable all data formatter categories.""" self.build() self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type category enable *', check=False) + self.runCmd("type category enable *", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - #self.runCmd('type category enable system VectorTypes libcxx gnu-libstdc++ CoreGraphics CoreServices AppKit CoreFoundation objc default', check=False) + # self.runCmd('type category enable system VectorTypes libcxx gnu-libstdc++ CoreGraphics CoreServices AppKit CoreFoundation objc default', check=False) - self.expect('type category list', substrs=['system', 'enabled', ]) + self.expect( + "type category list", + substrs=[ + "system", + "enabled", + ], + ) - self.expect("frame variable numbers", - substrs=['[0] = 1', '[3] = 1234']) + self.expect("frame variable numbers", substrs=["[0] = 1", "[3] = 1234"]) - self.expect('frame variable string1', substrs=['hello world']) + self.expect("frame variable string1", substrs=["hello world"]) # now disable them all and check that nothing is formatted - self.runCmd('type category disable *') - - self.expect("frame variable numbers", matching=False, - substrs=['[0] = 1', '[3] = 1234']) + self.runCmd("type category disable *") self.expect( - 'frame variable string1', - matching=False, - substrs=['hello world']) + "frame variable numbers", matching=False, substrs=["[0] = 1", "[3] = 1234"] + ) + + self.expect("frame variable string1", matching=False, substrs=["hello world"]) - self.expect('type summary list', substrs=[ - 'Category: system (disabled)']) + self.expect("type summary list", substrs=["Category: system (disabled)"]) - self.expect('type category list', substrs=['system', 'disabled', ]) + self.expect( + "type category list", + substrs=[ + "system", + "disabled", + ], + ) # now enable and check that we are back to normal self.runCmd("type category enable *") - self.expect('type category list', substrs=['system', 'enabled']) + self.expect("type category list", substrs=["system", "enabled"]) - self.expect("frame variable numbers", - substrs=['[0] = 1', '[3] = 1234']) + self.expect("frame variable numbers", substrs=["[0] = 1", "[3] = 1234"]) - self.expect('frame variable string1', substrs=['hello world']) + self.expect("frame variable string1", substrs=["hello world"]) - self.expect('type category list', substrs=['system', 'enabled']) + self.expect("type category list", substrs=["system", "enabled"]) # last check - our cleanup will re-enable everything - self.runCmd('type category disable *') - self.expect('type category list', substrs=['system', 'disabled']) + self.runCmd("type category disable *") + self.expect("type category list", substrs=["system", "disabled"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py b/lldb/test/API/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py @@ -3,19 +3,17 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class EnumFormatTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" @@ -23,27 +21,28 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) - self.expect("frame variable", - substrs=['(Foo) f = Case45', - '(int) x = 1', - '(int) y = 45', - '(int) z = 43' - ]) + self.expect( + "frame variable", + substrs=["(Foo) f = Case45", "(int) x = 1", "(int) y = 45", "(int) z = 43"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -51,12 +50,14 @@ self.runCmd("type format add --type Foo int") # The type format list should show our custom formats. - self.expect("type format list -w default", - substrs=['int: as type Foo']) - - self.expect("frame variable", - substrs=['(Foo) f = Case45', - '(int) x = Case1', - '(int) y = Case45', - '(int) z = 43' - ]) + self.expect("type format list -w default", substrs=["int: as type Foo"]) + + self.expect( + "frame variable", + substrs=[ + "(Foo) f = Case45", + "(int) x = Case1", + "(int) y = Case45", + "(int) z = 43", + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py b/lldb/test/API/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * @@ -11,12 +10,11 @@ class GlobalsDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" @@ -24,44 +22,44 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.runCmd("type summary add --summary-string \"JustATest\" Point") + self.runCmd('type summary add --summary-string "JustATest" Point') # Simply check we can get at global variables - self.expect("target variable g_point", - substrs=['JustATest']) + self.expect("target variable g_point", substrs=["JustATest"]) - self.expect("target variable g_point_pointer", - substrs=['(Point *) g_point_pointer =']) + self.expect( + "target variable g_point_pointer", substrs=["(Point *) g_point_pointer ="] + ) # Print some information about the variables # (we ignore the actual values) - self.runCmd( - "type summary add --summary-string \"(x=${var.x},y=${var.y})\" Point") + self.runCmd('type summary add --summary-string "(x=${var.x},y=${var.y})" Point') - self.expect("target variable g_point", - substrs=['x=', - 'y=']) + self.expect("target variable g_point", substrs=["x=", "y="]) - self.expect("target variable g_point_pointer", - substrs=['(Point *) g_point_pointer =']) + self.expect( + "target variable g_point_pointer", substrs=["(Point *) g_point_pointer ="] + ) # Test Python code on resulting SBValue self.runCmd( - "type summary add --python-script \"return 'x=' + str(valobj.GetChildMemberWithName('x').GetValue());\" Point") + "type summary add --python-script \"return 'x=' + str(valobj.GetChildMemberWithName('x').GetValue());\" Point" + ) - self.expect("target variable g_point", - substrs=['x=']) + self.expect("target variable g_point", substrs=["x="]) - self.expect("target variable g_point_pointer", - substrs=['(Point *) g_point_pointer =']) + self.expect( + "target variable g_point_pointer", substrs=["(Point *) g_point_pointer ="] + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py b/lldb/test/API/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py @@ -3,19 +3,17 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class NamedSummariesDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" @@ -23,106 +21,110 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.runCmd( - "type summary add --summary-string \"AllUseIt: x=${var.x} {y=${var.y}} {z=${var.z}}\" --name AllUseIt") + 'type summary add --summary-string "AllUseIt: x=${var.x} {y=${var.y}} {z=${var.z}}" --name AllUseIt' + ) self.runCmd( - "type summary add --summary-string \"First: x=${var.x} y=${var.y} dummy=${var.dummy}\" First") + 'type summary add --summary-string "First: x=${var.x} y=${var.y} dummy=${var.dummy}" First' + ) self.runCmd( - "type summary add --summary-string \"Second: x=${var.x} y=${var.y%hex}\" Second") + 'type summary add --summary-string "Second: x=${var.x} y=${var.y%hex}" Second' + ) self.runCmd( - "type summary add --summary-string \"Third: x=${var.x} z=${var.z}\" Third") + 'type summary add --summary-string "Third: x=${var.x} z=${var.z}" Third' + ) - self.expect('type summary list', substrs=['AllUseIt']) + self.expect("type summary list", substrs=["AllUseIt"]) - self.expect("frame variable first", - substrs=['First: x=12']) + self.expect("frame variable first", substrs=["First: x=12"]) - self.expect("frame variable first --summary AllUseIt", - substrs=['AllUseIt: x=12']) + self.expect( + "frame variable first --summary AllUseIt", substrs=["AllUseIt: x=12"] + ) # We *DO NOT* remember the summary choice anymore - self.expect("frame variable first", matching=False, - substrs=['AllUseIt: x=12']) - self.expect("frame variable first", - substrs=['First: x=12']) + self.expect("frame variable first", matching=False, substrs=["AllUseIt: x=12"]) + self.expect("frame variable first", substrs=["First: x=12"]) self.runCmd("thread step-over") # 2 - self.expect("frame variable first", - substrs=['First: x=12']) + self.expect("frame variable first", substrs=["First: x=12"]) - self.expect("frame variable first --summary AllUseIt", - substrs=['AllUseIt: x=12', - 'y=34']) + self.expect( + "frame variable first --summary AllUseIt", + substrs=["AllUseIt: x=12", "y=34"], + ) - self.expect("frame variable second --summary AllUseIt", - substrs=['AllUseIt: x=65', - 'y=43.25']) + self.expect( + "frame variable second --summary AllUseIt", + substrs=["AllUseIt: x=65", "y=43.25"], + ) - self.expect("frame variable third --summary AllUseIt", - substrs=['AllUseIt: x=96', - 'z=', - 'E']) + self.expect( + "frame variable third --summary AllUseIt", + substrs=["AllUseIt: x=96", "z=", "E"], + ) self.runCmd("thread step-over") # 3 - self.expect("frame variable second", - substrs=['Second: x=65', - 'y=0x']) + self.expect("frame variable second", substrs=["Second: x=65", "y=0x"]) # decided that invalid summaries will raise an error # instead of just defaulting to the base summary self.expect( "frame variable second --summary NoSuchSummary", error=True, - substrs=['must specify a valid named summary']) + substrs=["must specify a valid named summary"], + ) self.runCmd("thread step-over") self.runCmd( - "type summary add --summary-string \"FirstAndFriends: x=${var.x} {y=${var.y}} {z=${var.z}}\" First --name FirstAndFriends") + 'type summary add --summary-string "FirstAndFriends: x=${var.x} {y=${var.y}} {z=${var.z}}" First --name FirstAndFriends' + ) - self.expect("frame variable first", - substrs=['FirstAndFriends: x=12', - 'y=34']) + self.expect("frame variable first", substrs=["FirstAndFriends: x=12", "y=34"]) self.runCmd("type summary delete First") - self.expect("frame variable first --summary FirstAndFriends", - substrs=['FirstAndFriends: x=12', - 'y=34']) + self.expect( + "frame variable first --summary FirstAndFriends", + substrs=["FirstAndFriends: x=12", "y=34"], + ) - self.expect("frame variable first", matching=True, - substrs=['x = 12', - 'y = 34']) + self.expect("frame variable first", matching=True, substrs=["x = 12", "y = 34"]) self.runCmd("type summary delete FirstAndFriends") self.expect("type summary delete NoSuchSummary", error=True) self.runCmd("type summary delete AllUseIt") - self.expect("frame variable first", matching=False, - substrs=['FirstAndFriends']) + self.expect("frame variable first", matching=False, substrs=["FirstAndFriends"]) self.runCmd("thread step-over") # 4 - self.expect("frame variable first", matching=False, - substrs=['FirstAndFriends: x=12', - 'y=34']) + self.expect( + "frame variable first", + matching=False, + substrs=["FirstAndFriends: x=12", "y=34"], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/ObjCDataFormatterTestCase.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/ObjCDataFormatterTestCase.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/ObjCDataFormatterTestCase.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/ObjCDataFormatterTestCase.py @@ -11,41 +11,39 @@ class ObjCDataFormatterTestCase(TestBase): - - def appkit_tester_impl(self, commands, use_constant_classes): - if use_constant_classes: - self.build() - else: - disable_constant_classes = { - 'CC': - 'xcrun clang', # FIXME: Remove when flags are available upstream. - 'CFLAGS_EXTRAS': - '-fno-constant-nsnumber-literals ' + - '-fno-constant-nsarray-literals ' + - '-fno-constant-nsdictionary-literals' - } - self.build(dictionary=disable_constant_classes) - self.appkit_common_data_formatters_command() - commands() - - def appkit_common_data_formatters_command(self): - """Test formatters for AppKit classes.""" - self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( - self, '// Set break point at this line.', - lldb.SBFileSpec('main.m', False)) - - # The stop reason of the thread should be breakpoint. - self.expect( - "thread list", - STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) - - # This is the function to remove the custom formats in order to have a - # clean slate for the next test case. - def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) - - # Execute the cleanup function during test case tear down. - self.addTearDownHook(cleanup) + def appkit_tester_impl(self, commands, use_constant_classes): + if use_constant_classes: + self.build() + else: + disable_constant_classes = { + "CC": "xcrun clang", # FIXME: Remove when flags are available upstream. + "CFLAGS_EXTRAS": "-fno-constant-nsnumber-literals " + + "-fno-constant-nsarray-literals " + + "-fno-constant-nsdictionary-literals", + } + self.build(dictionary=disable_constant_classes) + self.appkit_common_data_formatters_command() + commands() + + def appkit_common_data_formatters_command(self): + """Test formatters for AppKit classes.""" + self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", lldb.SBFileSpec("main.m", False) + ) + + # The stop reason of the thread should be breakpoint. + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCCF.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCCF.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCCF.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCCF.py @@ -13,72 +13,71 @@ class ObjCDataFormatterCF(ObjCDataFormatterTestCase): - def test_coreframeworks_and_run_command(self): """Test formatters for Core OSX frameworks.""" self.build() self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( - self, '// Set break point at this line.', - lldb.SBFileSpec('main.m', False)) + self, "// Set break point at this line.", lldb.SBFileSpec("main.m", False) + ) # The stop reason of the thread should be breakpoint. self.expect( "thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + substrs=["stopped", "stop reason = breakpoint"], + ) - self.runCmd('settings set target.prefer-dynamic-value no-dynamic-values') + self.runCmd("settings set target.prefer-dynamic-value no-dynamic-values") # check formatters for common Objective-C types expect_strings = [ - '(CFGregorianUnits) cf_greg_units = 1 years, 3 months, 5 days, 12 hours, 5 minutes 7 seconds', + "(CFGregorianUnits) cf_greg_units = 1 years, 3 months, 5 days, 12 hours, 5 minutes 7 seconds", '(CFGregorianDate) cf_greg_date = @"4/10/1985 18:0:0"', - '(CFRange) cf_range = location=4 length=4', - '(NSPoint) ns_point = (x = 4, y = 4)', - '(NSRange) ns_range = location=4, length=4', - '(NSRect) ns_rect = (origin = (x = 1, y = 1), size = (width = 5, height = 5))', - '(NSRectArray) ns_rect_arr = ((x = 1, y = 1), (width = 5, height = 5)), ...', - '(NSSize) ns_size = (width = 5, height = 7)', - '(CGSize) cg_size = (width = 1, height = 6)', - '(CGPoint) cg_point = (x = 2, y = 7)', - '(CGRect) cg_rect = (origin = (x = 1, y = 2), size = (width = 7, height = 7))', - '(Rect) rect = (t=4, l=8, b=4, r=7)', - '(Rect *) rect_ptr = (t=4, l=8, b=4, r=7)', - '(Point) point = (v=7, h=12)', '(Point *) point_ptr = (v=7, h=12)', - '(SEL) foo_selector = "foo_selector_impl"' + "(CFRange) cf_range = location=4 length=4", + "(NSPoint) ns_point = (x = 4, y = 4)", + "(NSRange) ns_range = location=4, length=4", + "(NSRect) ns_rect = (origin = (x = 1, y = 1), size = (width = 5, height = 5))", + "(NSRectArray) ns_rect_arr = ((x = 1, y = 1), (width = 5, height = 5)), ...", + "(NSSize) ns_size = (width = 5, height = 7)", + "(CGSize) cg_size = (width = 1, height = 6)", + "(CGPoint) cg_point = (x = 2, y = 7)", + "(CGRect) cg_rect = (origin = (x = 1, y = 2), size = (width = 7, height = 7))", + "(Rect) rect = (t=4, l=8, b=4, r=7)", + "(Rect *) rect_ptr = (t=4, l=8, b=4, r=7)", + "(Point) point = (v=7, h=12)", + "(Point *) point_ptr = (v=7, h=12)", + '(SEL) foo_selector = "foo_selector_impl"', ] self.expect("frame variable", substrs=expect_strings) - if self.getArchitecture() in ['i386', 'x86_64']: + if self.getArchitecture() in ["i386", "x86_64"]: extra_string = [ - '(RGBColor) rgb_color = red=3 green=56 blue=35', - '(RGBColor *) rgb_color_ptr = red=3 green=56 blue=35', - '(HIPoint) hi_point = (x=7, y=12)', - '(HIRect) hi_rect = origin=(x = 3, y = 5) size=(width = 4, height = 6)', + "(RGBColor) rgb_color = red=3 green=56 blue=35", + "(RGBColor *) rgb_color_ptr = red=3 green=56 blue=35", + "(HIPoint) hi_point = (x=7, y=12)", + "(HIRect) hi_rect = origin=(x = 3, y = 5) size=(width = 4, height = 6)", ] self.expect("frame variable", substrs=extra_string) # The original tests left out testing the NSNumber values, so do that here. # This set is all pointers, with summaries, so we only check the summary. var_list_pointer = [ - ['NSNumber *', 'num1', '(int)5'], - ['NSNumber *', 'num2', '(float)3.140000'], - ['NSNumber *', 'num3', '(double)3.14'], - ['NSNumber *', 'num4', '(int128_t)18446744073709551614'], - ['NSNumber *', 'num5', '(char)65'], - ['NSNumber *', 'num6', '(long)255'], - ['NSNumber *', 'num7', '(long)2000000'], - ['NSNumber *', 'num8_Y', 'YES'], - ['NSNumber *', 'num8_N', 'NO'], - ['NSNumber *', 'num9', '(short)-31616'], - ['NSNumber *', 'num_at1', '(int)12'], - ['NSNumber *', 'num_at2', '(int)-12'], - ['NSNumber *', 'num_at3', '(double)12.5'], - ['NSNumber *', 'num_at4', '(double)-12.5'], - ['NSDecimalNumber *', 'decimal_number', '123456 x 10^-10'], - ['NSDecimalNumber *', 'decimal_number_neg', '-123456 x 10^10'] + ["NSNumber *", "num1", "(int)5"], + ["NSNumber *", "num2", "(float)3.140000"], + ["NSNumber *", "num3", "(double)3.14"], + ["NSNumber *", "num4", "(int128_t)18446744073709551614"], + ["NSNumber *", "num5", "(char)65"], + ["NSNumber *", "num6", "(long)255"], + ["NSNumber *", "num7", "(long)2000000"], + ["NSNumber *", "num8_Y", "YES"], + ["NSNumber *", "num8_N", "NO"], + ["NSNumber *", "num9", "(short)-31616"], + ["NSNumber *", "num_at1", "(int)12"], + ["NSNumber *", "num_at2", "(int)-12"], + ["NSNumber *", "num_at3", "(double)12.5"], + ["NSNumber *", "num_at4", "(double)-12.5"], + ["NSDecimalNumber *", "decimal_number", "123456 x 10^-10"], + ["NSDecimalNumber *", "decimal_number_neg", "-123456 x 10^10"], ] for type, var_path, summary in var_list_pointer: self.expect_var_path(var_path, summary, None, type) - - diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCExpr.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCExpr.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCExpr.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCExpr.py @@ -13,28 +13,28 @@ class ObjCDataFormatterExpr(ObjCDataFormatterTestCase): - def test_expr_with_run_command(self): """Test common cases of expression parser <--> formatters interaction.""" self.build() self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( - self, '// Set break point at this line.', - lldb.SBFileSpec('main.m', False)) + self, "// Set break point at this line.", lldb.SBFileSpec("main.m", False) + ) # The stop reason of the thread should be breakpoint. self.expect( "thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + substrs=["stopped", "stop reason = breakpoint"], + ) - self.runCmd('settings set target.prefer-dynamic-value no-dynamic-values') + self.runCmd("settings set target.prefer-dynamic-value no-dynamic-values") # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -44,22 +44,27 @@ self.expect( 'expression ((id)@"Hello for long enough to avoid short string types")', matching=False, - substrs=['Hello for long enough to avoid short string types']) + substrs=["Hello for long enough to avoid short string types"], + ) self.expect( 'expression -d run -- ((id)@"Hello for long enough to avoid short string types")', - substrs=['Hello for long enough to avoid short string types']) + substrs=["Hello for long enough to avoid short string types"], + ) - self.expect('expr -d run -- label1', substrs=['Process Name']) + self.expect("expr -d run -- label1", substrs=["Process Name"]) self.expect( 'expr -d run -- @"Hello for long enough to avoid short string types"', - substrs=['Hello for long enough to avoid short string types']) + substrs=["Hello for long enough to avoid short string types"], + ) self.expect( 'expr -d run --object-description -- @"Hello for long enough to avoid short string types"', - substrs=['Hello for long enough to avoid short string types']) + substrs=["Hello for long enough to avoid short string types"], + ) self.expect( 'expr -d run --object-description -- @"Hello"', matching=False, - substrs=['@"Hello" Hello']) + substrs=['@"Hello" Hello'], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCKVO.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCKVO.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCKVO.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCKVO.py @@ -13,28 +13,28 @@ class ObjCDataFormatterKVO(ObjCDataFormatterTestCase): - def test_kvo_with_run_command(self): """Test the behavior of formatters when KVO is in use.""" self.build() self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( - self, '// Set break point at this line.', - lldb.SBFileSpec('main.m', False)) + self, "// Set break point at this line.", lldb.SBFileSpec("main.m", False) + ) - self.runCmd('settings set target.prefer-dynamic-value no-dynamic-values') + self.runCmd("settings set target.prefer-dynamic-value no-dynamic-values") # The stop reason of the thread should be breakpoint. self.expect( "thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -43,22 +43,20 @@ # we should be able to dynamically figure out that the KVO implementor class # is a subclass of Molecule, and use the appropriate summary for it self.runCmd("type summary add -s JustAMoleculeHere Molecule") - self.expect('frame variable molecule', substrs=['JustAMoleculeHere']) + self.expect("frame variable molecule", substrs=["JustAMoleculeHere"]) self.runCmd("next") - self.expect("thread list", substrs=['stopped', 'step over']) - self.expect('frame variable molecule', substrs=['JustAMoleculeHere']) + self.expect("thread list", substrs=["stopped", "step over"]) + self.expect("frame variable molecule", substrs=["JustAMoleculeHere"]) self.runCmd("next") # check that NSMutableDictionary's formatter is not confused when # dealing with a KVO'd dictionary self.expect( - 'frame variable newMutableDictionary', - substrs=[ - '(NSDictionary *) newMutableDictionary = ', - ' 21 key/value pairs' - ]) + "frame variable newMutableDictionary", + substrs=["(NSDictionary *) newMutableDictionary = ", " 21 key/value pairs"], + ) - lldbutil.run_break_set_by_symbol(self, '-[Molecule setAtoms:]') + lldbutil.run_break_set_by_symbol(self, "-[Molecule setAtoms:]") self.runCmd("continue") - self.expect("frame variable _cmd", substrs=['setAtoms:']) + self.expect("frame variable _cmd", substrs=["setAtoms:"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSBundle.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSBundle.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSBundle.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSBundle.py @@ -13,7 +13,6 @@ class ObjCDataFormatterNSBundle(ObjCDataFormatterTestCase): - def test_nsbundle_with_run_command(self): """Test formatters for NSBundle.""" self.appkit_tester_impl(self.nsbundle_data_formatter_commands, True) @@ -25,11 +24,13 @@ def nsbundle_data_formatter_commands(self): self.expect( - 'frame variable bundle_string bundle_url main_bundle', + "frame variable bundle_string bundle_url main_bundle", substrs=[ - '(NSBundle *) bundle_string = ', + "(NSBundle *) bundle_string = ", ' @"/System/Library/Frameworks/Accelerate.framework"', - '(NSBundle *) bundle_url = ', + "(NSBundle *) bundle_url = ", ' @"/System/Library/Frameworks/Foundation.framework"', - '(NSBundle *) main_bundle = ', 'data-formatter-objc' - ]) + "(NSBundle *) main_bundle = ", + "data-formatter-objc", + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSContainer.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSContainer.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSContainer.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSContainer.py @@ -13,46 +13,47 @@ class ObjCDataFormatterNSContainer(ObjCDataFormatterTestCase): - def test_nscontainers_with_run_command(self): """Test formatters for NS container classes.""" self.appkit_tester_impl(self.nscontainers_data_formatter_commands, False) def nscontainers_data_formatter_commands(self): - self.runCmd('settings set target.prefer-dynamic-value no-dynamic-values') + self.runCmd("settings set target.prefer-dynamic-value no-dynamic-values") self.expect( - 'frame variable newArray nsDictionary newDictionary nscfDictionary cfDictionaryRef newMutableDictionary copyDictionary newMutableDictionaryRef cfarray_ref mutable_array_ref', + "frame variable newArray nsDictionary newDictionary nscfDictionary cfDictionaryRef newMutableDictionary copyDictionary newMutableDictionaryRef cfarray_ref mutable_array_ref", substrs=[ - '(NSArray *) newArray = ', + "(NSArray *) newArray = ", ' @"50 elements"', - '(NSDictionary *) nsDictionary = ', - ' 2 key/value pairs', - '(NSDictionary *) newDictionary = ', - ' 12 key/value pairs', - '(NSDictionary *) nscfDictionary = ', - ' 4 key/value pairs', - '(CFDictionaryRef) cfDictionaryRef = ', - ' 2 key/value pairs', - '(NSDictionary *) newMutableDictionary = ', - ' 21 key/value pairs', - '(NSMutableDictionary *) copyDictionary = ', - ' 21 key/value pairs', - '(CFMutableDictionaryRef) newMutableDictionaryRef = ', - ' 21 key/value pairs', - '(CFArrayRef) cfarray_ref = ', + "(NSDictionary *) nsDictionary = ", + " 2 key/value pairs", + "(NSDictionary *) newDictionary = ", + " 12 key/value pairs", + "(NSDictionary *) nscfDictionary = ", + " 4 key/value pairs", + "(CFDictionaryRef) cfDictionaryRef = ", + " 2 key/value pairs", + "(NSDictionary *) newMutableDictionary = ", + " 21 key/value pairs", + "(NSMutableDictionary *) copyDictionary = ", + " 21 key/value pairs", + "(CFMutableDictionaryRef) newMutableDictionaryRef = ", + " 21 key/value pairs", + "(CFArrayRef) cfarray_ref = ", ' @"3 elements"', - '(CFMutableArrayRef) mutable_array_ref = ', + "(CFMutableArrayRef) mutable_array_ref = ", ' @"11 elements"', - ]) + ], + ) + + self.expect( + "frame var -d run-target copyDictionary[10]", substrs=['@"bar9"', '@"foo"'] + ) - self.expect('frame var -d run-target copyDictionary[10]', - substrs=['@"bar9"', '@"foo"']) - self.expect( - 'frame variable -d run-target *nscfDictionary', + "frame variable -d run-target *nscfDictionary", patterns=[ - '\(__NSCFDictionary\) \*nscfDictionary =', + "\(__NSCFDictionary\) \*nscfDictionary =", 'key = 0x.* @"foo"', 'value = 0x.* @"foo"', 'key = 0x.* @"bar"', @@ -61,53 +62,58 @@ 'value = 0x.* @"baz"', 'key = 0x.* @"quux"', 'value = 0x.* @"quux"', - ]) - + ], + ) self.expect( - 'frame variable -d run-target *cfDictionaryRef', + "frame variable -d run-target *cfDictionaryRef", patterns=[ - '\(const __CFDictionary\) \*cfDictionaryRef =', + "\(const __CFDictionary\) \*cfDictionaryRef =", 'key = 0x.* @"foo"', 'value = 0x.* @"foo"', 'key = 0x.* @"bar"', 'value = 0x.* @"bar"', - ]) - + ], + ) self.expect( - 'frame var nscfSet cfSetRef', - substrs=[ - '(NSSet *) nscfSet = ', - '2 elements', - '(CFSetRef) cfSetRef = ', - '2 elements', - ]) + "frame var nscfSet cfSetRef", + substrs=[ + "(NSSet *) nscfSet = ", + "2 elements", + "(CFSetRef) cfSetRef = ", + "2 elements", + ], + ) self.expect( - 'frame variable -d run-target *nscfSet', - patterns=[ - '\(__NSCFSet\) \*nscfSet =', - '\[0\] = 0x.* @".*"', - '\[1\] = 0x.* @".*"', - ]) + "frame variable -d run-target *nscfSet", + patterns=[ + "\(__NSCFSet\) \*nscfSet =", + '\[0\] = 0x.* @".*"', + '\[1\] = 0x.* @".*"', + ], + ) self.expect( - 'frame variable -d run-target *cfSetRef', - patterns=[ - '\(const __CFSet\) \*cfSetRef =', - '\[0\] = 0x.* @".*"', - '\[1\] = 0x.* @".*"', - ]) + "frame variable -d run-target *cfSetRef", + patterns=[ + "\(const __CFSet\) \*cfSetRef =", + '\[0\] = 0x.* @".*"', + '\[1\] = 0x.* @".*"', + ], + ) self.expect( - 'frame variable iset1 iset2 imset', - substrs=['4 indexes', '512 indexes', '10 indexes']) + "frame variable iset1 iset2 imset", + substrs=["4 indexes", "512 indexes", "10 indexes"], + ) self.expect( - 'frame variable binheap_ref', - substrs=['(CFBinaryHeapRef) binheap_ref = ', '@"21 items"']) + "frame variable binheap_ref", + substrs=["(CFBinaryHeapRef) binheap_ref = ", '@"21 items"'], + ) self.expect( - 'expression -d run -- (NSArray*)[NSArray new]', - substrs=['@"0 elements"']) + "expression -d run -- (NSArray*)[NSArray new]", substrs=['@"0 elements"'] + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSData.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSData.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSData.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSData.py @@ -13,7 +13,6 @@ class ObjCDataFormatterNSData(ObjCDataFormatterTestCase): - def test_nsdata_with_run_command(self): """Test formatters for NSData.""" self.appkit_tester_impl(self.nsdata_data_formatter_commands, True) @@ -24,17 +23,24 @@ self.appkit_tester_impl(self.nsdata_data_formatter_commands, False) def nsdata_data_formatter_commands(self): - self.runCmd('settings set target.prefer-dynamic-value no-dynamic-values') + self.runCmd("settings set target.prefer-dynamic-value no-dynamic-values") self.expect( - 'frame variable immutableData mutableData data_ref mutable_data_ref mutable_string_ref concreteData concreteMutableData', + "frame variable immutableData mutableData data_ref mutable_data_ref mutable_string_ref concreteData concreteMutableData", substrs=[ - '(NSData *) immutableData = ', ' 5 bytes', - '(NSData *) mutableData = ', ' 14 bytes', - '(CFDataRef) data_ref = ', '@"5 bytes"', - '(CFMutableDataRef) mutable_data_ref = ', '@"5 bytes"', - '(CFMutableStringRef) mutable_string_ref = ', - ' @"Wish ya knew"', '(NSData *) concreteData = ', - ' 100000 bytes', '(NSMutableData *) concreteMutableData = ', - ' 100000 bytes' - ]) + "(NSData *) immutableData = ", + " 5 bytes", + "(NSData *) mutableData = ", + " 14 bytes", + "(CFDataRef) data_ref = ", + '@"5 bytes"', + "(CFMutableDataRef) mutable_data_ref = ", + '@"5 bytes"', + "(CFMutableStringRef) mutable_string_ref = ", + ' @"Wish ya knew"', + "(NSData *) concreteData = ", + " 100000 bytes", + "(NSMutableData *) concreteMutableData = ", + " 100000 bytes", + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSDate.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSDate.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSDate.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSDate.py @@ -13,34 +13,34 @@ import datetime -class ObjCDataFormatterNSDate(ObjCDataFormatterTestCase): +class ObjCDataFormatterNSDate(ObjCDataFormatterTestCase): def test_nsdate_with_run_command(self): """Test formatters for NSDate.""" self.appkit_tester_impl(self.nsdate_data_formatter_commands, False) def nsdate_data_formatter_commands(self): self.expect( - 'frame variable date1 date2', - patterns=[ - '(1985-04-10|1985-04-11)', - '(2011-01-01|2010-12-31)']) + "frame variable date1 date2", + patterns=["(1985-04-10|1985-04-11)", "(2011-01-01|2010-12-31)"], + ) # this test might fail if we hit the breakpoint late on December 31st of some given year # and midnight comes between hitting the breakpoint and running this line of code # hopefully the output will be revealing enough in that case :-) - now_year = '%s-' % str(datetime.datetime.now().year) + now_year = "%s-" % str(datetime.datetime.now().year) - self.expect('frame variable date3', substrs=[now_year]) - self.expect('frame variable date4', substrs=['1970']) - self.expect('frame variable date5', substrs=[now_year]) + self.expect("frame variable date3", substrs=[now_year]) + self.expect("frame variable date4", substrs=["1970"]) + self.expect("frame variable date5", substrs=[now_year]) - self.expect('frame variable date1_abs date2_abs', - substrs=['1985-04', '2011-01']) + self.expect( + "frame variable date1_abs date2_abs", substrs=["1985-04", "2011-01"] + ) - self.expect('frame variable date3_abs', substrs=[now_year]) - self.expect('frame variable date4_abs', substrs=['1970']) - self.expect('frame variable date5_abs', substrs=[now_year]) + self.expect("frame variable date3_abs", substrs=[now_year]) + self.expect("frame variable date4_abs", substrs=["1970"]) + self.expect("frame variable date5_abs", substrs=[now_year]) # Check that LLDB always follow's NSDate's rounding behavior (which # is always rounding down). @@ -51,21 +51,23 @@ self.expect_expr("date_1970_plus_05", result_summary="1970-01-01 00:00:00 UTC") self.expect_expr("date_1970_plus_04", result_summary="1970-01-01 00:00:00 UTC") - self.expect('frame variable cupertino home europe', - substrs=['@"America/Los_Angeles"', - '@"Europe/Rome"', - '@"Europe/Paris"']) + self.expect( + "frame variable cupertino home europe", + substrs=['@"America/Los_Angeles"', '@"Europe/Rome"', '@"Europe/Paris"'], + ) - self.expect('frame variable cupertino_ns home_ns europe_ns', - substrs=['@"America/Los_Angeles"', - '@"Europe/Rome"', - '@"Europe/Paris"']) + self.expect( + "frame variable cupertino_ns home_ns europe_ns", + substrs=['@"America/Los_Angeles"', '@"Europe/Rome"', '@"Europe/Paris"'], + ) self.expect( - 'frame variable mut_bv', + "frame variable mut_bv", substrs=[ - '(CFMutableBitVectorRef) mut_bv = ', - '1110 0110 1011 0000 1101 1010 1000 1111 0011 0101 1101 0001 00']) + "(CFMutableBitVectorRef) mut_bv = ", + "1110 0110 1011 0000 1101 1010 1000 1111 0011 0101 1101 0001 00", + ], + ) self.expect_expr("distant_past", result_summary="0001-01-01 00:00:00 UTC") self.expect_expr("distant_future", result_summary="4001-01-01 00:00:00 UTC") diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSError.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSError.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSError.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSError.py @@ -13,7 +13,6 @@ class ObjCDataFormatterNSError(ObjCDataFormatterTestCase): - def test_nserror_with_run_command(self): """Test formatters for NSError.""" self.appkit_tester_impl(self.nserror_data_formatter_commands, True) @@ -24,16 +23,15 @@ self.appkit_tester_impl(self.nserror_data_formatter_commands, False) def nserror_data_formatter_commands(self): - self.expect( - 'frame variable nserror', substrs=['domain: @"Foobar" - code: 12']) + self.expect("frame variable nserror", substrs=['domain: @"Foobar" - code: 12']) self.expect( - 'frame variable nserrorptr', - substrs=['domain: @"Foobar" - code: 12']) + "frame variable nserrorptr", substrs=['domain: @"Foobar" - code: 12'] + ) - self.expect( - 'frame variable nserror->_userInfo', substrs=['2 key/value pairs']) + self.expect("frame variable nserror->_userInfo", substrs=["2 key/value pairs"]) self.expect( - 'frame variable nserror->_userInfo --ptr-depth 1 -d run-target', - substrs=['@"a"', "1", '@"b"', "2"]) + "frame variable nserror->_userInfo --ptr-depth 1 -d run-target", + substrs=['@"a"', "1", '@"b"', "2"], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSNumber.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSNumber.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSNumber.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSNumber.py @@ -12,7 +12,6 @@ class ObjCDataFormatterNSNumber(ObjCDataFormatterTestCase): - @skipUnlessDarwin def test_nsnumber_with_run_command(self): """Test formatters for NS container classes.""" @@ -24,44 +23,52 @@ self.appkit_tester_impl(self.nscontainers_data_formatter_commands, False) def nscontainers_data_formatter_commands(self): - self.runCmd('settings set target.prefer-dynamic-value no-dynamic-values') + self.runCmd("settings set target.prefer-dynamic-value no-dynamic-values") self.expect( - 'frame variable newArray nsDictionary newDictionary nscfDictionary cfDictionaryRef newMutableDictionary cfarray_ref mutable_array_ref', + "frame variable newArray nsDictionary newDictionary nscfDictionary cfDictionaryRef newMutableDictionary cfarray_ref mutable_array_ref", substrs=[ - '(NSArray *) newArray = ', '@"50 elements"', - '(NSDictionary *) nsDictionary = ', ' 2 key/value pairs', - '(NSDictionary *) newDictionary = ', ' 12 key/value pairs', - '(CFDictionaryRef) cfDictionaryRef = ', ' 2 key/value pairs', - '(NSDictionary *) newMutableDictionary = ', ' 21 key/value pairs', - '(CFArrayRef) cfarray_ref = ', '@"3 elements"', - '(CFMutableArrayRef) mutable_array_ref = ', '@"11 elements"' - ]) + "(NSArray *) newArray = ", + '@"50 elements"', + "(NSDictionary *) nsDictionary = ", + " 2 key/value pairs", + "(NSDictionary *) newDictionary = ", + " 12 key/value pairs", + "(CFDictionaryRef) cfDictionaryRef = ", + " 2 key/value pairs", + "(NSDictionary *) newMutableDictionary = ", + " 21 key/value pairs", + "(CFArrayRef) cfarray_ref = ", + '@"3 elements"', + "(CFMutableArrayRef) mutable_array_ref = ", + '@"11 elements"', + ], + ) - numbers = [ ("num1", "(int)5"), - ("num2", "(float)3.140000"), - ("num3", "(double)3.14"), - ("num4", "(int128_t)18446744073709551614"), - ("num5", "(char)65"), - ("num6", "(long)255"), - ("num7", "(long)2000000"), - ("num8_Y", "YES"), - ("num8_N", "NO"), - ("num9", "(short)-31616"), - ("num_at1", "(int)12"), - ("num_at2", "(int)-12"), - ("num_at3", "(double)12.5"), - ("num_at4", "(double)-12.5"), - ("num_at5", "(char)97"), - ("num_at6", "(float)42.123"), - ("num_at7", "(double)43.123"), - ("num_at8", "(long)12345"), - ("num_at9", "17375808098308635870"), - ("num_at9b", "-1070935975400915746"), - ("num_at10", "YES"), - ("num_at11", "NO"), + numbers = [ + ("num1", "(int)5"), + ("num2", "(float)3.140000"), + ("num3", "(double)3.14"), + ("num4", "(int128_t)18446744073709551614"), + ("num5", "(char)65"), + ("num6", "(long)255"), + ("num7", "(long)2000000"), + ("num8_Y", "YES"), + ("num8_N", "NO"), + ("num9", "(short)-31616"), + ("num_at1", "(int)12"), + ("num_at2", "(int)-12"), + ("num_at3", "(double)12.5"), + ("num_at4", "(double)-12.5"), + ("num_at5", "(char)97"), + ("num_at6", "(float)42.123"), + ("num_at7", "(double)43.123"), + ("num_at8", "(long)12345"), + ("num_at9", "17375808098308635870"), + ("num_at9b", "-1070935975400915746"), + ("num_at10", "YES"), + ("num_at11", "NO"), ] for var, res in numbers: - self.expect('frame variable ' + var, substrs=[res]) - + self.expect("frame variable " + var, substrs=[res]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSURL.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSURL.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSURL.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSURL.py @@ -13,7 +13,6 @@ class ObjCDataFormatterNSURL(ObjCDataFormatterTestCase): - def test_nsurl_with_run_command(self): """Test formatters for NSURL.""" self.appkit_tester_impl(self.nsurl_data_formatter_commands, True) @@ -25,19 +24,25 @@ def nsurl_data_formatter_commands(self): self.expect( - 'frame variable cfurl_ref cfchildurl_ref cfgchildurl_ref', + "frame variable cfurl_ref cfchildurl_ref cfgchildurl_ref", substrs=[ - '(CFURLRef) cfurl_ref = ', '@"http://www.foo.bar', - 'cfchildurl_ref = ', '@"page.html -- http://www.foo.bar', - '(CFURLRef) cfgchildurl_ref = ', - '@"?whatever -- http://www.foo.bar/page.html"' - ]) + "(CFURLRef) cfurl_ref = ", + '@"http://www.foo.bar', + "cfchildurl_ref = ", + '@"page.html -- http://www.foo.bar', + "(CFURLRef) cfgchildurl_ref = ", + '@"?whatever -- http://www.foo.bar/page.html"', + ], + ) self.expect( - 'frame variable nsurl nsurl2 nsurl3', + "frame variable nsurl nsurl2 nsurl3", substrs=[ - '(NSURL *) nsurl = ', '@"http://www.foo.bar', - '(NSURL *) nsurl2 =', '@"page.html -- http://www.foo.bar', - '(NSURL *) nsurl3 = ', - '@"?whatever -- http://www.foo.bar/page.html"' - ]) + "(NSURL *) nsurl = ", + '@"http://www.foo.bar', + "(NSURL *) nsurl2 =", + '@"page.html -- http://www.foo.bar', + "(NSURL *) nsurl3 = ", + '@"?whatever -- http://www.foo.bar/page.html"', + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCPlain.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCPlain.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCPlain.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCPlain.py @@ -13,64 +13,61 @@ class ObjCDataFormatterNSPlain(ObjCDataFormatterTestCase): - def test_plain_objc_with_run_command(self): """Test basic ObjC formatting behavior.""" self.build() self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( - self, '// Set break point at this line.', - lldb.SBFileSpec('main.m', False)) + self, "// Set break point at this line.", lldb.SBFileSpec("main.m", False) + ) # The stop reason of the thread should be breakpoint. self.expect( "thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.runCmd("type summary add --summary-string \"${var%@}\" MyClass") + self.runCmd('type summary add --summary-string "${var%@}" MyClass') - self.expect("frame variable object2", substrs=['MyOtherClass']) + self.expect("frame variable object2", substrs=["MyOtherClass"]) - self.expect("frame variable *object2", substrs=['MyOtherClass']) + self.expect("frame variable *object2", substrs=["MyOtherClass"]) # Now let's delete the 'MyClass' custom summary. self.runCmd("type summary delete MyClass") # The type format list should not show 'MyClass' at this point. - self.expect("type summary list", matching=False, substrs=['MyClass']) + self.expect("type summary list", matching=False, substrs=["MyClass"]) - self.runCmd("type summary add --summary-string \"a test\" MyClass") + self.runCmd('type summary add --summary-string "a test" MyClass') self.expect( "frame variable *object2", - substrs=['*object2 =', 'MyClass = a test', 'backup = ']) + substrs=["*object2 =", "MyClass = a test", "backup = "], + ) - self.expect( - "frame variable object2", matching=False, substrs=['a test']) + self.expect("frame variable object2", matching=False, substrs=["a test"]) - self.expect("frame variable object", substrs=['a test']) + self.expect("frame variable object", substrs=["a test"]) - self.expect("frame variable *object", substrs=['a test']) + self.expect("frame variable *object", substrs=["a test"]) + self.expect("frame variable myclass", substrs=["(Class) myclass = NSValue"]) self.expect( - 'frame variable myclass', substrs=['(Class) myclass = NSValue']) - self.expect( - 'frame variable myclass2', - substrs=['(Class) myclass2 = ', 'NS', 'String']) - self.expect( - 'frame variable myclass3', substrs=['(Class) myclass3 = Molecule']) - self.expect( - 'frame variable myclass4', - substrs=['(Class) myclass4 = NSMutableArray']) + "frame variable myclass2", substrs=["(Class) myclass2 = ", "NS", "String"] + ) + self.expect("frame variable myclass3", substrs=["(Class) myclass3 = Molecule"]) self.expect( - 'frame variable myclass5', substrs=['(Class) myclass5 = nil']) + "frame variable myclass4", substrs=["(Class) myclass4 = NSMutableArray"] + ) + self.expect("frame variable myclass5", substrs=["(Class) myclass5 = nil"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjNSException.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjNSException.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjNSException.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjNSException.py @@ -13,7 +13,6 @@ class ObjCDataFormatterNSException(ObjCDataFormatterTestCase): - def test_nsexception_with_run_command(self): """Test formatters for NSException.""" self.appkit_tester_impl(self.nsexception_data_formatter_commands, True) @@ -25,14 +24,15 @@ def nsexception_data_formatter_commands(self): self.expect( - 'frame variable except0 except1 except2 except3', + "frame variable except0 except1 except2 except3", substrs=[ - '(NSException *) except0 = ', + "(NSException *) except0 = ", '@"First"', - '(NSException *) except1 = ', + "(NSException *) except1 = ", '@"Second"', - '(NSException *) except2 = ', + "(NSException *) except2 = ", ' @"Third"', - '(NSException *) except3 = ', - ' @"Fourth"' - ]) + "(NSException *) except3 = ", + ' @"Fourth"', + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/cmtime/TestDataFormatterCMTime.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/cmtime/TestDataFormatterCMTime.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/cmtime/TestDataFormatterCMTime.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/cmtime/TestDataFormatterCMTime.py @@ -7,45 +7,41 @@ class CMTimeDataFormatterTestCase(TestBase): - @skipUnlessDarwin def test_nsindexpath_with_run_command(self): """Test formatters for CMTime.""" self.build() - self.runCmd("file " + self.getBuildArtifact("a.out"), - CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) - line = line_number('main.m', '// break here') + line = line_number("main.m", "// break here") lldbutil.run_break_set_by_file_and_line( - self, "main.m", line, num_expected_locations=1, loc_exact=True) + self, "main.m", line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) self.expect( "thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + substrs=["stopped", "stop reason = breakpoint"], + ) self.expect( - 'frame variable t1', - substrs=[ - '1 half seconds', 'value = 1', 'timescale = 2', 'epoch = 0' - ]) + "frame variable t1", + substrs=["1 half seconds", "value = 1", "timescale = 2", "epoch = 0"], + ) self.expect( - 'frame variable t2', - substrs=[ - '1 third of a second', 'value = 1', 'timescale = 3', - 'epoch = 0' - ]) + "frame variable t2", + substrs=["1 third of a second", "value = 1", "timescale = 3", "epoch = 0"], + ) self.expect( - 'frame variable t3', - substrs=[ - '1 10th of a second', 'value = 1', 'timescale = 10', - 'epoch = 0' - ]) + "frame variable t3", + substrs=["1 10th of a second", "value = 1", "timescale = 10", "epoch = 0"], + ) self.expect( - 'frame variable t4', - substrs=['10 seconds', 'value = 10', 'timescale = 1', 'epoch = 0']) - self.expect('frame variable t5', substrs=['+oo']) - self.expect('frame variable t6', substrs=['-oo']) - self.expect('frame variable t7', substrs=['indefinite']) + "frame variable t4", + substrs=["10 seconds", "value = 10", "timescale = 1", "epoch = 0"], + ) + self.expect("frame variable t5", substrs=["+oo"]) + self.expect("frame variable t6", substrs=["-oo"]) + self.expect("frame variable t7", substrs=["indefinite"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/nsindexpath/TestDataFormatterNSIndexPath.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/nsindexpath/TestDataFormatterNSIndexPath.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/nsindexpath/TestDataFormatterNSIndexPath.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/nsindexpath/TestDataFormatterNSIndexPath.py @@ -4,7 +4,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,35 +11,39 @@ class NSIndexPathDataFormatterTestCase(TestBase): - def appkit_tester_impl(self, commands): self.build() self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + self, "main.m", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) commands() @skipUnlessDarwin - @expectedFailureAll(archs=['i386'], bugnumber="rdar://28656605") - @expectedFailureAll(archs=['armv7', 'armv7k', 'arm64_32'], bugnumber="rdar://problem/34561607") # NSIndexPath formatter isn't working for 32-bit arm + @expectedFailureAll(archs=["i386"], bugnumber="rdar://28656605") + @expectedFailureAll( + archs=["armv7", "armv7k", "arm64_32"], bugnumber="rdar://problem/34561607" + ) # NSIndexPath formatter isn't working for 32-bit arm def test_nsindexpath_with_run_command(self): """Test formatters for NSIndexPath.""" self.appkit_tester_impl(self.nsindexpath_data_formatter_commands) @@ -49,62 +52,47 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.m', '// break here') + self.line = line_number("main.m", "// break here") def nsindexpath_data_formatter_commands(self): # check 'frame variable' self.expect( - 'frame variable --ptr-depth=1 -d run -- indexPath1', - substrs=['[0] = 1']) + "frame variable --ptr-depth=1 -d run -- indexPath1", substrs=["[0] = 1"] + ) self.expect( - 'frame variable --ptr-depth=1 -d run -- indexPath2', - substrs=[ - '[0] = 1', - '[1] = 2']) + "frame variable --ptr-depth=1 -d run -- indexPath2", + substrs=["[0] = 1", "[1] = 2"], + ) self.expect( - 'frame variable --ptr-depth=1 -d run -- indexPath3', - substrs=[ - '[0] = 1', - '[1] = 2', - '[2] = 3']) + "frame variable --ptr-depth=1 -d run -- indexPath3", + substrs=["[0] = 1", "[1] = 2", "[2] = 3"], + ) self.expect( - 'frame variable --ptr-depth=1 -d run -- indexPath4', - substrs=[ - '[0] = 1', - '[1] = 2', - '[2] = 3', - '[3] = 4']) + "frame variable --ptr-depth=1 -d run -- indexPath4", + substrs=["[0] = 1", "[1] = 2", "[2] = 3", "[3] = 4"], + ) self.expect( - 'frame variable --ptr-depth=1 -d run -- indexPath5', - substrs=[ - '[0] = 1', - '[1] = 2', - '[2] = 3', - '[3] = 4', - '[4] = 5']) + "frame variable --ptr-depth=1 -d run -- indexPath5", + substrs=["[0] = 1", "[1] = 2", "[2] = 3", "[3] = 4", "[4] = 5"], + ) # and 'expression' self.expect( - 'expression --ptr-depth=1 -d run -- indexPath1', - substrs=['[0] = 1']) + "expression --ptr-depth=1 -d run -- indexPath1", substrs=["[0] = 1"] + ) + self.expect( + "expression --ptr-depth=1 -d run -- indexPath2", + substrs=["[0] = 1", "[1] = 2"], + ) self.expect( - 'expression --ptr-depth=1 -d run -- indexPath2', - substrs=[ - '[0] = 1', - '[1] = 2']) + "expression --ptr-depth=1 -d run -- indexPath3", + substrs=["[0] = 1", "[1] = 2", "[2] = 3"], + ) self.expect( - 'expression --ptr-depth=1 -d run -- indexPath3', - substrs=[ - '[0] = 1', - '[1] = 2', - '[2] = 3']) - self.expect('expression --ptr-depth=1 -d run -- indexPath4', - substrs=['[0] = 1', '[1] = 2', '[2] = 3', '[3] = 4']) + "expression --ptr-depth=1 -d run -- indexPath4", + substrs=["[0] = 1", "[1] = 2", "[2] = 3", "[3] = 4"], + ) self.expect( - 'expression --ptr-depth=1 -d run -- indexPath5', - substrs=[ - '[0] = 1', - '[1] = 2', - '[2] = 3', - '[3] = 4', - '[4] = 5']) + "expression --ptr-depth=1 -d run -- indexPath5", + substrs=["[0] = 1", "[1] = 2", "[2] = 3", "[3] = 4", "[4] = 5"], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py @@ -4,7 +4,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,29 +11,31 @@ class NSStringDataFormatterTestCase(TestBase): - def appkit_tester_impl(self, commands): self.build() self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + self, "main.m", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) self.runCmd("settings set target.prefer-dynamic-value no-dynamic-values") # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -62,61 +63,90 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.m', '// break here') + self.line = line_number("main.m", "// break here") def rdar11106605_commands(self): """Check that Unicode characters come out of CFString summary correctly.""" - self.expect('frame variable italian', substrs=[ - 'L\'Italia è una Repubblica democratica, fondata sul lavoro. La sovranità appartiene al popolo, che la esercita nelle forme e nei limiti della Costituzione.']) - self.expect('frame variable french', substrs=[ - 'Que veut cette horde d\'esclaves, De traîtres, de rois conjurés?']) - self.expect('frame variable german', substrs=[ - 'Über-Ich und aus den Ansprüchen der sozialen Umwelt']) - self.expect('frame variable japanese', substrs=['色は匂へど散りぬるを']) - self.expect('frame variable hebrew', substrs=['לילה טוב']) + self.expect( + "frame variable italian", + substrs=[ + "L'Italia è una Repubblica democratica, fondata sul lavoro. La sovranità appartiene al popolo, che la esercita nelle forme e nei limiti della Costituzione." + ], + ) + self.expect( + "frame variable french", + substrs=["Que veut cette horde d'esclaves, De traîtres, de rois conjurés?"], + ) + self.expect( + "frame variable german", + substrs=["Über-Ich und aus den Ansprüchen der sozialen Umwelt"], + ) + self.expect("frame variable japanese", substrs=["色は匂へど散りぬるを"]) + self.expect("frame variable hebrew", substrs=["לילה טוב"]) def nsstring_data_formatter_commands(self): - self.expect('frame variable empty str0 str1 str2 str3 str4 str5 str6 str8 str9 str10 str11 label1 label2 processName str12', - substrs=['(NSString *) empty = ', ' @""', - # '(NSString *) str0 = ',' @"255"', - '(NSString *) str1 = ', ' @"A rather short ASCII NSString object is here"', - '(NSString *) str2 = ', ' @"A rather short UTF8 NSString object is here"', - '(NSString *) str3 = ', ' @"A string made with the at sign is here"', - '(NSString *) str4 = ', ' @"This is string number 4 right here"', - '(NSString *) str5 = ', ' @"{{1, 1}, {5, 5}}"', - '(NSString *) str6 = ', ' @"1ST"', - '(NSString *) str8 = ', ' @"hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime', - '(NSString *) str9 = ', ' @"a very much boring task to write a string this way!!', - '(NSString *) str10 = ', ' @"This is a Unicode string σ number 4 right here"', - '(NSString *) str11 = ', ' @"__NSCFString"', - '(NSString *) label1 = ', ' @"Process Name: "', - '(NSString *) label2 = ', ' @"Process Id: "', - '(NSString *) str12 = ', ' @"Process Name: a.out Process Id:']) self.expect( - 'frame variable attrString mutableAttrString mutableGetConst', + "frame variable empty str0 str1 str2 str3 str4 str5 str6 str8 str9 str10 str11 label1 label2 processName str12", substrs=[ - '(NSAttributedString *) attrString = ', + "(NSString *) empty = ", + ' @""', + # '(NSString *) str0 = ',' @"255"', + "(NSString *) str1 = ", + ' @"A rather short ASCII NSString object is here"', + "(NSString *) str2 = ", + ' @"A rather short UTF8 NSString object is here"', + "(NSString *) str3 = ", + ' @"A string made with the at sign is here"', + "(NSString *) str4 = ", + ' @"This is string number 4 right here"', + "(NSString *) str5 = ", + ' @"{{1, 1}, {5, 5}}"', + "(NSString *) str6 = ", + ' @"1ST"', + "(NSString *) str8 = ", + ' @"hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime', + "(NSString *) str9 = ", + ' @"a very much boring task to write a string this way!!', + "(NSString *) str10 = ", + ' @"This is a Unicode string σ number 4 right here"', + "(NSString *) str11 = ", + ' @"__NSCFString"', + "(NSString *) label1 = ", + ' @"Process Name: "', + "(NSString *) label2 = ", + ' @"Process Id: "', + "(NSString *) str12 = ", + ' @"Process Name: a.out Process Id:', + ], + ) + self.expect( + "frame variable attrString mutableAttrString mutableGetConst", + substrs=[ + "(NSAttributedString *) attrString = ", ' @"hello world from foo"', - '(NSAttributedString *) mutableAttrString = ', + "(NSAttributedString *) mutableAttrString = ", ' @"hello world from foo"', - '(NSString *) mutableGetConst = ', - ' @"foo said this string needs to be very long so much longer than whatever other string has been seen ever before by anyone of the mankind that of course this is still not long enough given what foo our friend foo our lovely dearly friend foo desired of us so i am adding more stuff here for the sake of it and for the joy of our friend who is named guess what just foo. hence, dear friend foo, stay safe, your string is now long enough to accommodate your testing need and I will make sure that if not we extend it with even more fuzzy random meaningless words pasted one after the other from a long tiresome friday evening spent working in my office. my office mate went home but I am still randomly typing just for the fun of seeing what happens of the length of a Mutable String in Cocoa if it goes beyond one byte.. so be it, dear foo"']) + "(NSString *) mutableGetConst = ", + ' @"foo said this string needs to be very long so much longer than whatever other string has been seen ever before by anyone of the mankind that of course this is still not long enough given what foo our friend foo our lovely dearly friend foo desired of us so i am adding more stuff here for the sake of it and for the joy of our friend who is named guess what just foo. hence, dear friend foo, stay safe, your string is now long enough to accommodate your testing need and I will make sure that if not we extend it with even more fuzzy random meaningless words pasted one after the other from a long tiresome friday evening spent working in my office. my office mate went home but I am still randomly typing just for the fun of seeing what happens of the length of a Mutable String in Cocoa if it goes beyond one byte.. so be it, dear foo"', + ], + ) - self.expect('expr -d run-target -- path', substrs=['usr/blah/stuff']) - self.expect('frame variable path', substrs=['usr/blah/stuff']) - self.expect('expr -d run-target -- empty_path', substrs=['@""']) - self.expect('frame variable empty_path', substrs=['@""']) + self.expect("expr -d run-target -- path", substrs=["usr/blah/stuff"]) + self.expect("frame variable path", substrs=["usr/blah/stuff"]) + self.expect("expr -d run-target -- empty_path", substrs=['@""']) + self.expect("frame variable empty_path", substrs=['@""']) def nsstring_withNULs_commands(self): """Check that the NSString formatter supports embedded NULs in the text""" + self.expect("po strwithNULs", substrs=["a very much boring task to write"]) + self.expect("expr [strwithNULs length]", substrs=["54"]) + self.expect( + "frame variable strwithNULs", + substrs=['@"a very much boring task to write\\0a string this way!!'], + ) + self.expect("po strwithNULs2", substrs=["a very much boring task to write"]) + self.expect("expr [strwithNULs2 length]", substrs=["52"]) self.expect( - 'po strwithNULs', - substrs=['a very much boring task to write']) - self.expect('expr [strwithNULs length]', substrs=['54']) - self.expect('frame variable strwithNULs', substrs=[ - '@"a very much boring task to write\\0a string this way!!']) - self.expect('po strwithNULs2', substrs=[ - 'a very much boring task to write']) - self.expect('expr [strwithNULs2 length]', substrs=['52']) - self.expect('frame variable strwithNULs2', substrs=[ - '@"a very much boring task to write\\0a string this way!!']) + "frame variable strwithNULs2", + substrs=['@"a very much boring task to write\\0a string this way!!'], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py b/lldb/test/API/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class DataFormatterOneIsSingularTestCase(TestBase): - @skipUnlessDarwin def test_one_is_singular_with_run_command(self): """Test that 1 item is not as reported as 1 items.""" @@ -22,54 +20,47 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.m', '// Set break point at this line.') + self.line = line_number("main.m", "// Set break point at this line.") def oneness_data_formatter_commands(self): """Test that 1 item is not as reported as 1 items.""" self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + self, "main.m", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # Now check that we are displaying Cocoa classes correctly - self.expect('frame variable key', - substrs=['@"1 element"']) - self.expect('frame variable key', matching=False, - substrs=['1 elements']) - self.expect('frame variable value', - substrs=['@"1 element"']) - self.expect('frame variable value', matching=False, - substrs=['1 elements']) - self.expect('frame variable dict', - substrs=['1 key/value pair']) - self.expect('frame variable dict', matching=False, - substrs=['1 key/value pairs']) - self.expect('frame variable imset', - substrs=['1 index']) - self.expect('frame variable imset', matching=False, - substrs=['1 indexes']) - self.expect('frame variable binheap_ref', - substrs=['@"1 item"']) - self.expect('frame variable binheap_ref', matching=False, - substrs=['1 items']) - self.expect('frame variable immutableData', - substrs=['1 byte']) - self.expect('frame variable immutableData', matching=False, - substrs=['1 bytes']) + self.expect("frame variable key", substrs=['@"1 element"']) + self.expect("frame variable key", matching=False, substrs=["1 elements"]) + self.expect("frame variable value", substrs=['@"1 element"']) + self.expect("frame variable value", matching=False, substrs=["1 elements"]) + self.expect("frame variable dict", substrs=["1 key/value pair"]) + self.expect( + "frame variable dict", matching=False, substrs=["1 key/value pairs"] + ) + self.expect("frame variable imset", substrs=["1 index"]) + self.expect("frame variable imset", matching=False, substrs=["1 indexes"]) + self.expect("frame variable binheap_ref", substrs=['@"1 item"']) + self.expect("frame variable binheap_ref", matching=False, substrs=["1 items"]) + self.expect("frame variable immutableData", substrs=["1 byte"]) + self.expect("frame variable immutableData", matching=False, substrs=["1 bytes"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py b/lldb/test/API/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py @@ -3,14 +3,12 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class PtrToArrayDataFormatterTestCase(TestBase): - def test_with_run_command(self): """Test that LLDB handles the clang typeclass Paren correctly.""" self.build() @@ -20,35 +18,46 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def data_formatter_commands(self): """Test that LLDB handles the clang typeclass Paren correctly.""" self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format delete hex', check=False) - self.runCmd('type summary clear', check=False) + self.runCmd("type format delete hex", check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect('expression *(int (*)[3])foo', - substrs=['(int[3]) $', '[0] = 1', '[1] = 2', '[2] = 3']) - - self.expect('expression *(int (*)[3])foo', matching=False, - substrs=['01 00 00 00 02 00 00 00 03 00 00 00']) - self.expect('expression *(int (*)[3])foo', matching=False, - substrs=['0x000000030000000200000001']) + self.expect( + "expression *(int (*)[3])foo", + substrs=["(int[3]) $", "[0] = 1", "[1] = 2", "[2] = 3"], + ) + + self.expect( + "expression *(int (*)[3])foo", + matching=False, + substrs=["01 00 00 00 02 00 00 00 03 00 00 00"], + ) + self.expect( + "expression *(int (*)[3])foo", + matching=False, + substrs=["0x000000030000000200000001"], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py b/lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py @@ -9,7 +9,6 @@ class PythonSynthDataFormatterTestCase(TestBase): - def test_with_run_command(self): """Test data formatter commands.""" self.build() @@ -24,40 +23,38 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') - self.line2 = line_number('main.cpp', - '// Set cast break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") + self.line2 = line_number("main.cpp", "// Set cast break point at this line.") self.line3 = line_number( - 'main.cpp', '// Set second cast break point at this line.') + "main.cpp", "// Set second cast break point at this line." + ) def data_formatter_commands(self): """Test using Python synthetic children provider.""" _, process, thread, _ = lldbutil.run_to_line_breakpoint( - self, lldb.SBFileSpec("main.cpp"), self.line) + self, lldb.SBFileSpec("main.cpp"), self.line + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # print the f00_1 variable without a synth - self.expect("frame variable f00_1", - substrs=['a = 1', - 'b = 2', - 'r = 34']) + self.expect("frame variable f00_1", substrs=["a = 1", "b = 2", "r = 34"]) # now set up the synth self.runCmd("script from fooSynthProvider import *") self.runCmd("type synth add -l fooSynthProvider foo") self.runCmd("type synth add -l wrapfooSynthProvider wrapfoo") - self.expect("type synthetic list foo", substrs=['fooSynthProvider']) + self.expect("type synthetic list foo", substrs=["fooSynthProvider"]) # note that the value of fake_a depends on target byte order if process.GetByteOrder() == lldb.eByteOrderLittle: @@ -69,32 +66,26 @@ self.expect( "frame variable f00_1", substrs=[ - 'a = 1', - 'fake_a = %d' % fake_a_val, - 'r = 34', - ]) + "a = 1", + "fake_a = %d" % fake_a_val, + "r = 34", + ], + ) # check that we do not get the extra vars - self.expect("frame variable f00_1", matching=False, - substrs=['b = 2']) + self.expect("frame variable f00_1", matching=False, substrs=["b = 2"]) # check access to members by name - self.expect('frame variable f00_1.fake_a', - substrs=['%d' % fake_a_val]) + self.expect("frame variable f00_1.fake_a", substrs=["%d" % fake_a_val]) # check access to members by index - self.expect('frame variable f00_1[1]', - substrs=['%d' % fake_a_val]) + self.expect("frame variable f00_1[1]", substrs=["%d" % fake_a_val]) # put synthetic children in summary in several combinations - self.runCmd( - "type summary add --summary-string \"fake_a=${svar.fake_a}\" foo") - self.expect('frame variable f00_1', - substrs=['fake_a=%d' % fake_a_val]) - self.runCmd( - "type summary add --summary-string \"fake_a=${svar[1]}\" foo") - self.expect('frame variable f00_1', - substrs=['fake_a=%d' % fake_a_val]) + self.runCmd('type summary add --summary-string "fake_a=${svar.fake_a}" foo') + self.expect("frame variable f00_1", substrs=["fake_a=%d" % fake_a_val]) + self.runCmd('type summary add --summary-string "fake_a=${svar[1]}" foo') + self.expect("frame variable f00_1", substrs=["fake_a=%d" % fake_a_val]) # clear the summary self.runCmd("type summary delete foo") @@ -110,10 +101,11 @@ self.expect( "frame variable f00_1", substrs=[ - 'a = 2', - 'fake_a = %d' % fake_a_val, - 'r = 34', - ]) + "a = 2", + "fake_a = %d" % fake_a_val, + "r = 34", + ], + ) # check that altering the object also alters fake_a self.runCmd("expr f00_1.a = 280") @@ -126,136 +118,133 @@ self.expect( "frame variable f00_1", substrs=[ - 'a = 280', - 'fake_a = %d' % fake_a_val, - 'r = 34', - ]) + "a = 280", + "fake_a = %d" % fake_a_val, + "r = 34", + ], + ) # check that expanding a pointer does the right thing if process.GetByteOrder() == lldb.eByteOrderLittle: - fake_a_val = 0x0d000000 + fake_a_val = 0x0D000000 else: - fake_a_val = 0x00000c00 + fake_a_val = 0x00000C00 self.expect( "frame variable --ptr-depth 1 f00_ptr", substrs=[ - 'a = 12', - 'fake_a = %d' % fake_a_val, - 'r = 45', - ]) + "a = 12", + "fake_a = %d" % fake_a_val, + "r = 45", + ], + ) self.expect( "frame variable --ptr-depth 1 wrapper", substrs=[ - 'a = 12', - 'fake_a = %d' % fake_a_val, - 'r = 45', - ]) + "a = 12", + "fake_a = %d" % fake_a_val, + "r = 45", + ], + ) # now add a filter.. it should fail - self.expect("type filter add foo --child b --child j", error=True, - substrs=['cannot add']) + self.expect( + "type filter add foo --child b --child j", + error=True, + substrs=["cannot add"], + ) # we get the synth again.. - self.expect('frame variable f00_1', matching=False, - substrs=['b = 1', - 'j = 17']) + self.expect("frame variable f00_1", matching=False, substrs=["b = 1", "j = 17"]) self.expect( "frame variable --ptr-depth 1 f00_ptr", substrs=[ - 'a = 12', - 'fake_a = %d' % fake_a_val, - 'r = 45', - ]) + "a = 12", + "fake_a = %d" % fake_a_val, + "r = 45", + ], + ) self.expect( "frame variable --ptr-depth 1 wrapper", substrs=[ - 'a = 12', - 'fake_a = %d' % fake_a_val, - 'r = 45', - ]) + "a = 12", + "fake_a = %d" % fake_a_val, + "r = 45", + ], + ) # Test that the custom dereference operator for `wrapfoo` works through # the Python API. The synthetic children provider gets queried at # slightly different times in this case. - wrapper_var = thread.GetSelectedFrame().FindVariable('wrapper') + wrapper_var = thread.GetSelectedFrame().FindVariable("wrapper") foo_var = wrapper_var.Dereference() self.assertEqual(foo_var.GetNumChildren(), 3) - self.assertEqual(foo_var.GetChildAtIndex(0).GetName(), 'a') - self.assertEqual(foo_var.GetChildAtIndex(1).GetName(), 'fake_a') - self.assertEqual(foo_var.GetChildAtIndex(2).GetName(), 'r') + self.assertEqual(foo_var.GetChildAtIndex(0).GetName(), "a") + self.assertEqual(foo_var.GetChildAtIndex(1).GetName(), "fake_a") + self.assertEqual(foo_var.GetChildAtIndex(2).GetName(), "r") # now delete the synth and add the filter self.runCmd("type synth delete foo") self.runCmd("type synth delete wrapfoo") self.runCmd("type filter add foo --child b --child j") - self.expect('frame variable f00_1', - substrs=['b = 2', - 'j = 18']) - self.expect("frame variable --ptr-depth 1 f00_ptr", matching=False, - substrs=['r = 45', - 'fake_a = %d' % fake_a_val, - 'a = 12']) - self.expect("frame variable --ptr-depth 1 wrapper", matching=False, - substrs=['r = 45', - 'fake_a = %d' % fake_a_val, - 'a = 12']) + self.expect("frame variable f00_1", substrs=["b = 2", "j = 18"]) + self.expect( + "frame variable --ptr-depth 1 f00_ptr", + matching=False, + substrs=["r = 45", "fake_a = %d" % fake_a_val, "a = 12"], + ) + self.expect( + "frame variable --ptr-depth 1 wrapper", + matching=False, + substrs=["r = 45", "fake_a = %d" % fake_a_val, "a = 12"], + ) # now add the synth and it should fail - self.expect("type synth add -l fooSynthProvider foo", error=True, - substrs=['cannot add']) + self.expect( + "type synth add -l fooSynthProvider foo", error=True, substrs=["cannot add"] + ) # check the listing - self.expect('type synth list', matching=False, - substrs=['foo', - 'Python class fooSynthProvider']) - self.expect('type filter list', - substrs=['foo', - '.b', - '.j']) + self.expect( + "type synth list", + matching=False, + substrs=["foo", "Python class fooSynthProvider"], + ) + self.expect("type filter list", substrs=["foo", ".b", ".j"]) # delete the filter, add the synth self.runCmd("type filter delete foo") self.runCmd("type synth add -l fooSynthProvider foo") - self.expect('frame variable f00_1', matching=False, - substrs=['b = 2', - 'j = 18']) + self.expect("frame variable f00_1", matching=False, substrs=["b = 2", "j = 18"]) self.expect( "frame variable --ptr-depth 1 f00_ptr", substrs=[ - 'a = 12', - 'fake_a = %d' % fake_a_val, - 'r = 45', - ]) + "a = 12", + "fake_a = %d" % fake_a_val, + "r = 45", + ], + ) self.expect( "frame variable --ptr-depth 1 wrapper", substrs=[ - 'a = 12', - 'fake_a = %d' % fake_a_val, - 'r = 45', - ]) + "a = 12", + "fake_a = %d" % fake_a_val, + "r = 45", + ], + ) # check the listing - self.expect('type synth list', - substrs=['foo', - 'Python class fooSynthProvider']) - self.expect('type filter list', matching=False, - substrs=['foo', - '.b', - '.j']) + self.expect("type synth list", substrs=["foo", "Python class fooSynthProvider"]) + self.expect("type filter list", matching=False, substrs=["foo", ".b", ".j"]) # delete the synth and check that we get good output self.runCmd("type synth delete foo") - self.expect("frame variable f00_1", - substrs=['a = 280', - 'b = 2', - 'j = 18']) + self.expect("frame variable f00_1", substrs=["a = 280", "b = 2", "j = 18"]) - self.expect("frame variable f00_1", matching=False, - substrs=['fake_a = ']) + self.expect("frame variable f00_1", matching=False, substrs=["fake_a = "]) # check that we don't feed a regex into another regex when checking for # existing conflicting synth/filters. The two following expressions @@ -280,24 +269,28 @@ # The second breakpoint is on a multi-line expression, so the comment # can't be on the right line... lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line2, num_expected_locations=1, loc_exact=False) + self, "main.cpp", self.line2, num_expected_locations=1, loc_exact=False + ) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line3, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line3, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -309,21 +302,24 @@ # but their values change correctly across stop-points - in order to do this, self.runCmd("next") # does not work because it forces a wipe of the stack frame - this is why we are using this more contrived # mechanism to achieve our goal of preserving test_cast as a VO - test_cast = self.dbg.GetSelectedTarget().GetProcess( - ).GetSelectedThread().GetSelectedFrame().FindVariable('test_cast') + test_cast = ( + self.dbg.GetSelectedTarget() + .GetProcess() + .GetSelectedThread() + .GetSelectedFrame() + .FindVariable("test_cast") + ) str_cast = str(test_cast) if self.TraceOn(): print(str_cast) - self.assertTrue(str_cast.find('A') != -1, 'could not find A in output') - self.assertTrue(str_cast.find('B') != -1, 'could not find B in output') - self.assertTrue(str_cast.find('C') != -1, 'could not find C in output') - self.assertTrue(str_cast.find('D') != -1, 'could not find D in output') - self.assertTrue( - str_cast.find("4 = '\\0'") != -1, - 'could not find item 4 == 0') + self.assertTrue(str_cast.find("A") != -1, "could not find A in output") + self.assertTrue(str_cast.find("B") != -1, "could not find B in output") + self.assertTrue(str_cast.find("C") != -1, "could not find C in output") + self.assertTrue(str_cast.find("D") != -1, "could not find D in output") + self.assertTrue(str_cast.find("4 = '\\0'") != -1, "could not find item 4 == 0") self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().StepOver() @@ -335,10 +331,8 @@ # we detect that all the values of the child objects have changed - but the counter-generated item # is still fixed at 0 because it is cached - this would fail if update(self): in ftsp returned False # or if synthetic children were not being preserved - self.assertTrue(str_cast.find('Q') != -1, 'could not find Q in output') - self.assertTrue(str_cast.find('X') != -1, 'could not find X in output') - self.assertTrue(str_cast.find('T') != -1, 'could not find T in output') - self.assertTrue(str_cast.find('F') != -1, 'could not find F in output') - self.assertTrue( - str_cast.find("4 = '\\0'") != -1, - 'could not find item 4 == 0') + self.assertTrue(str_cast.find("Q") != -1, "could not find Q in output") + self.assertTrue(str_cast.find("X") != -1, "could not find X in output") + self.assertTrue(str_cast.find("T") != -1, "could not find T in output") + self.assertTrue(str_cast.find("F") != -1, "could not find F in output") + self.assertTrue(str_cast.find("4 = '\\0'") != -1, "could not find item 4 == 0") diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py b/lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py @@ -2,7 +2,6 @@ class fooSynthProvider: - def __init__(self, valobj, dict): self.valobj = valobj self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) @@ -12,17 +11,17 @@ def get_child_at_index(self, index): if index == 0: - child = self.valobj.GetChildMemberWithName('a') + child = self.valobj.GetChildMemberWithName("a") if index == 1: - child = self.valobj.CreateChildAtOffset('fake_a', 1, self.int_type) + child = self.valobj.CreateChildAtOffset("fake_a", 1, self.int_type) if index == 2: - child = self.valobj.GetChildMemberWithName('r') + child = self.valobj.GetChildMemberWithName("r") return child def get_child_index(self, name): - if name == 'a': + if name == "a": return 0 - if name == 'fake_a': + if name == "fake_a": return 1 return 2 @@ -31,7 +30,6 @@ class wrapfooSynthProvider: - def __init__(self, valobj, dict): self.valobj = valobj @@ -40,15 +38,15 @@ def get_child_at_index(self, index): if index == 0: - return self.valobj.GetChildMemberWithName('ptr') + return self.valobj.GetChildMemberWithName("ptr") if index == 1: - return self.valobj.GetChildMemberWithName('ptr').Dereference() + return self.valobj.GetChildMemberWithName("ptr").Dereference() return None def get_child_index(self, name): - if name == 'ptr': + if name == "ptr": return 0 - if name == '$$dereference$$': + if name == "$$dereference$$": return 1 return -1 diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/ftsp.py b/lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/ftsp.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/ftsp.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/ftsp.py @@ -4,7 +4,6 @@ class ftsp: - def __init__(self, valobj, dict): self.valobj = valobj @@ -21,13 +20,12 @@ return self.x.Cast(self.char) if index == 4: return self.valobj.CreateValueFromExpression( - str(index), '(char)(' + str(self.count) + ')') - return self.x.CreateChildAtOffset(str(index), - index, - self.char) + str(index), "(char)(" + str(self.count) + ")" + ) + return self.x.CreateChildAtOffset(str(index), index, self.char) def update(self): - self.x = self.valobj.GetChildMemberWithName('x') + self.x = self.valobj.GetChildMemberWithName("x") self.char = self.valobj.GetType().GetBasicType(lldb.eBasicTypeChar) global counter self.count = counter diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py b/lldb/test/API/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py @@ -3,14 +3,12 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class ScriptDataFormatterTestCase(TestBase): - def test_with_run_command(self): """Test data formatter commands.""" self.build() @@ -20,161 +18,135 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def data_formatter_commands(self): """Test that that file and class static variables display correctly.""" self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # Set the script here to ease the formatting - script = 'a = valobj.GetChildMemberWithName(\'integer\'); a_val = a.GetValue(); str = \'Hello from Python, \' + a_val + \' time\'; return str + (\'!\' if a_val == \'1\' else \'s!\');' + script = "a = valobj.GetChildMemberWithName('integer'); a_val = a.GetValue(); str = 'Hello from Python, ' + a_val + ' time'; return str + ('!' if a_val == '1' else 's!');" - self.runCmd( - "type summary add i_am_cool --python-script \"%s\"" % - script) - self.expect('type summary list i_am_cool', substrs=[script]) + self.runCmd('type summary add i_am_cool --python-script "%s"' % script) + self.expect("type summary list i_am_cool", substrs=[script]) - self.expect("frame variable one", - substrs=['Hello from Python', - '1 time!']) + self.expect("frame variable one", substrs=["Hello from Python", "1 time!"]) - self.expect("frame variable two", - substrs=['Hello from Python', - '4 times!']) + self.expect("frame variable two", substrs=["Hello from Python", "4 times!"]) self.runCmd("n") # skip ahead to make values change - self.expect("frame variable three", - substrs=['Hello from Python, 10 times!', - 'Hello from Python, 4 times!']) + self.expect( + "frame variable three", + substrs=["Hello from Python, 10 times!", "Hello from Python, 4 times!"], + ) self.runCmd("n") # skip ahead to make values change - self.expect("frame variable two", - substrs=['Hello from Python', - '1 time!']) + self.expect("frame variable two", substrs=["Hello from Python", "1 time!"]) - script = 'a = valobj.GetChildMemberWithName(\'integer\'); a_val = a.GetValue(); str = \'int says \' + a_val; return str;' + script = "a = valobj.GetChildMemberWithName('integer'); a_val = a.GetValue(); str = 'int says ' + a_val; return str;" # Check that changes in the script are immediately reflected - self.runCmd( - "type summary add i_am_cool --python-script \"%s\"" % - script) + self.runCmd('type summary add i_am_cool --python-script "%s"' % script) - self.expect("frame variable two", - substrs=['int says 1']) + self.expect("frame variable two", substrs=["int says 1"]) - self.expect("frame variable twoptr", - substrs=['int says 1']) + self.expect("frame variable twoptr", substrs=["int says 1"]) # Change the summary self.runCmd( - "type summary add --summary-string \"int says ${var.integer}, and float says ${var.floating}\" i_am_cool") + 'type summary add --summary-string "int says ${var.integer}, and float says ${var.floating}" i_am_cool' + ) - self.expect("frame variable two", - substrs=['int says 1', - 'and float says 2.71']) + self.expect("frame variable two", substrs=["int says 1", "and float says 2.71"]) # Try it for pointers - self.expect("frame variable twoptr", - substrs=['int says 1', - 'and float says 2.71']) + self.expect( + "frame variable twoptr", substrs=["int says 1", "and float says 2.71"] + ) # Force a failure for pointers - self.runCmd( - "type summary add i_am_cool -p --python-script \"%s\"" % - script) + self.runCmd('type summary add i_am_cool -p --python-script "%s"' % script) - self.expect("frame variable twoptr", matching=False, - substrs=['and float says 2.71']) + self.expect( + "frame variable twoptr", matching=False, substrs=["and float says 2.71"] + ) - script = 'return \'Python summary\'' + script = "return 'Python summary'" self.runCmd( - "type summary add --name test_summary --python-script \"%s\"" % - script) + 'type summary add --name test_summary --python-script "%s"' % script + ) # attach the Python named summary to someone - self.expect("frame variable one --summary test_summary", - substrs=['Python summary']) + self.expect( + "frame variable one --summary test_summary", substrs=["Python summary"] + ) # should not bind to the type - self.expect("frame variable two", matching=False, - substrs=['Python summary']) + self.expect("frame variable two", matching=False, substrs=["Python summary"]) # and should not stick to the variable - self.expect("frame variable one", matching=False, - substrs=['Python summary']) + self.expect("frame variable one", matching=False, substrs=["Python summary"]) - self.runCmd( - "type summary add i_am_cool --summary-string \"Text summary\"") + self.runCmd('type summary add i_am_cool --summary-string "Text summary"') # should be temporary only - self.expect("frame variable one", matching=False, - substrs=['Python summary']) + self.expect("frame variable one", matching=False, substrs=["Python summary"]) # use the type summary - self.expect("frame variable two", - substrs=['Text summary']) + self.expect("frame variable two", substrs=["Text summary"]) self.runCmd("n") # skip ahead to make values change # both should use the type summary now - self.expect("frame variable one", - substrs=['Text summary']) + self.expect("frame variable one", substrs=["Text summary"]) - self.expect("frame variable two", - substrs=['Text summary']) + self.expect("frame variable two", substrs=["Text summary"]) # disable type summary for pointers, and make a Python regex summary - self.runCmd( - "type summary add i_am_cool -p --summary-string \"Text summary\"") - self.runCmd("type summary add -x cool --python-script \"%s\"" % script) + self.runCmd('type summary add i_am_cool -p --summary-string "Text summary"') + self.runCmd('type summary add -x cool --python-script "%s"' % script) # variables should stick to the type summary - self.expect("frame variable one", - substrs=['Text summary']) + self.expect("frame variable one", substrs=["Text summary"]) - self.expect("frame variable two", - substrs=['Text summary']) + self.expect("frame variable two", substrs=["Text summary"]) # array and pointer should match the Python one - self.expect("frame variable twoptr", - substrs=['Python summary']) + self.expect("frame variable twoptr", substrs=["Python summary"]) - self.expect("frame variable array", - substrs=['Python summary']) + self.expect("frame variable array", substrs=["Python summary"]) # return pointers to the type summary - self.runCmd( - "type summary add i_am_cool --summary-string \"Text summary\"") + self.runCmd('type summary add i_am_cool --summary-string "Text summary"') - self.expect("frame variable one", - substrs=['Text summary']) + self.expect("frame variable one", substrs=["Text summary"]) - self.expect("frame variable two", - substrs=['Text summary']) + self.expect("frame variable two", substrs=["Text summary"]) - self.expect("frame variable twoptr", - substrs=['Text summary']) + self.expect("frame variable twoptr", substrs=["Text summary"]) - self.expect("frame variable array", - substrs=['Python summary']) + self.expect("frame variable array", substrs=["Python summary"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py b/lldb/test/API/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py @@ -10,10 +10,10 @@ class SkipSummaryDataFormatterTestCase(TestBase): - @expectedFailureAll( oslist=["windows"], - bugnumber="llvm.org/pr24462, Data formatters have problems on Windows") + bugnumber="llvm.org/pr24462, Data formatters have problems on Windows", + ) def test_with_run_command(self): """Test data formatter commands.""" self.build() @@ -23,128 +23,151 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def data_formatter_commands(self): """Test that that file and class static variables display correctly.""" self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) - #import lldbsuite.test.lldbutil as lldbutil + # import lldbsuite.test.lldbutil as lldbutil lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # Setup the summaries for this scenario - #self.runCmd("type summary add --summary-string \"${var._M_dataplus._M_p}\" std::string") - self.runCmd( - "type summary add --summary-string \"Level 1\" \"DeepData_1\"") - self.runCmd( - "type summary add --summary-string \"Level 2\" \"DeepData_2\" -e") - self.runCmd( - "type summary add --summary-string \"Level 3\" \"DeepData_3\"") - self.runCmd( - "type summary add --summary-string \"Level 4\" \"DeepData_4\"") - self.runCmd( - "type summary add --summary-string \"Level 5\" \"DeepData_5\"") + # self.runCmd("type summary add --summary-string \"${var._M_dataplus._M_p}\" std::string") + self.runCmd('type summary add --summary-string "Level 1" "DeepData_1"') + self.runCmd('type summary add --summary-string "Level 2" "DeepData_2" -e') + self.runCmd('type summary add --summary-string "Level 3" "DeepData_3"') + self.runCmd('type summary add --summary-string "Level 4" "DeepData_4"') + self.runCmd('type summary add --summary-string "Level 5" "DeepData_5"') # Default case, just print out summaries - self.expect('frame variable', - substrs=['(DeepData_1) data1 = Level 1', - '(DeepData_2) data2 = Level 2 {', - 'm_child1 = Level 3', - 'm_child2 = Level 3', - 'm_child3 = Level 3', - 'm_child4 = Level 3', - '}']) + self.expect( + "frame variable", + substrs=[ + "(DeepData_1) data1 = Level 1", + "(DeepData_2) data2 = Level 2 {", + "m_child1 = Level 3", + "m_child2 = Level 3", + "m_child3 = Level 3", + "m_child4 = Level 3", + "}", + ], + ) # Skip the default (should be 1) levels of summaries - self.expect('frame variable --no-summary-depth', - substrs=['(DeepData_1) data1 = {', - 'm_child1 = 0x', - '}', - '(DeepData_2) data2 = {', - 'm_child1 = Level 3', - 'm_child2 = Level 3', - 'm_child3 = Level 3', - 'm_child4 = Level 3', - '}']) + self.expect( + "frame variable --no-summary-depth", + substrs=[ + "(DeepData_1) data1 = {", + "m_child1 = 0x", + "}", + "(DeepData_2) data2 = {", + "m_child1 = Level 3", + "m_child2 = Level 3", + "m_child3 = Level 3", + "m_child4 = Level 3", + "}", + ], + ) # Now skip 2 levels of summaries - self.expect('frame variable --no-summary-depth=2', - substrs=['(DeepData_1) data1 = {', - 'm_child1 = 0x', - '}', - '(DeepData_2) data2 = {', - 'm_child1 = {', - 'm_child1 = 0x', - 'Level 4', - 'm_child2 = {', - 'm_child3 = {', - '}']) + self.expect( + "frame variable --no-summary-depth=2", + substrs=[ + "(DeepData_1) data1 = {", + "m_child1 = 0x", + "}", + "(DeepData_2) data2 = {", + "m_child1 = {", + "m_child1 = 0x", + "Level 4", + "m_child2 = {", + "m_child3 = {", + "}", + ], + ) # Check that no "Level 3" comes out self.expect( - 'frame variable data1.m_child1 --no-summary-depth=2', + "frame variable data1.m_child1 --no-summary-depth=2", matching=False, - substrs=['Level 3']) + substrs=["Level 3"], + ) # Now expand a pointer with 2 level of skipped summaries - self.expect('frame variable data1.m_child1 --no-summary-depth=2', - substrs=['(DeepData_2 *) data1.m_child1 = 0x']) + self.expect( + "frame variable data1.m_child1 --no-summary-depth=2", + substrs=["(DeepData_2 *) data1.m_child1 = 0x"], + ) # Deref and expand said pointer - self.expect('frame variable *data1.m_child1 --no-summary-depth=2', - substrs=['(DeepData_2) *data1.m_child1 = {', - 'm_child2 = {', - 'm_child1 = 0x', - 'Level 4', - '}']) + self.expect( + "frame variable *data1.m_child1 --no-summary-depth=2", + substrs=[ + "(DeepData_2) *data1.m_child1 = {", + "m_child2 = {", + "m_child1 = 0x", + "Level 4", + "}", + ], + ) # Expand an expression, skipping 2 layers of summaries self.expect( - 'frame variable data1.m_child1->m_child2 --no-summary-depth=2', + "frame variable data1.m_child1->m_child2 --no-summary-depth=2", substrs=[ - '(DeepData_3) data1.m_child1->m_child2 = {', - 'm_child2 = {', - 'm_child1 = Level 5', - 'm_child2 = Level 5', - 'm_child3 = Level 5', - '}']) + "(DeepData_3) data1.m_child1->m_child2 = {", + "m_child2 = {", + "m_child1 = Level 5", + "m_child2 = Level 5", + "m_child3 = Level 5", + "}", + ], + ) # Expand same expression, skipping only 1 layer of summaries self.expect( - 'frame variable data1.m_child1->m_child2 --no-summary-depth=1', + "frame variable data1.m_child1->m_child2 --no-summary-depth=1", substrs=[ - '(DeepData_3) data1.m_child1->m_child2 = {', - 'm_child1 = 0x', - 'Level 4', - 'm_child2 = Level 4', - '}']) + "(DeepData_3) data1.m_child1->m_child2 = {", + "m_child1 = 0x", + "Level 4", + "m_child2 = Level 4", + "}", + ], + ) # Bad debugging info on SnowLeopard gcc (Apple Inc. build 5666). # Skip the following tests if the condition is met. - if self.getCompiler().endswith('gcc') and not self.getCompiler().endswith('llvm-gcc'): + if self.getCompiler().endswith("gcc") and not self.getCompiler().endswith( + "llvm-gcc" + ): import re - gcc_version_output = system( - [[lldbutil.which(self.getCompiler()), "-v"]]) + + gcc_version_output = system([[lldbutil.which(self.getCompiler()), "-v"]]) self.trace("my output:", gcc_version_output) for line in gcc_version_output.split(os.linesep): - m = re.search('\(Apple Inc\. build ([0-9]+)\)', line) + m = re.search("\(Apple Inc\. build ([0-9]+)\)", line) self.trace("line:", line) if m: gcc_build = int(m.group(1)) @@ -152,28 +175,34 @@ if gcc_build >= 5666: # rdar://problem/9804600" self.skipTest( - "rdar://problem/9804600 wrong namespace for std::string in debug info") + "rdar://problem/9804600 wrong namespace for std::string in debug info" + ) # Expand same expression, skipping 3 layers of summaries self.expect( - 'frame variable data1.m_child1->m_child2 --show-types --no-summary-depth=3', + "frame variable data1.m_child1->m_child2 --show-types --no-summary-depth=3", substrs=[ - '(DeepData_3) data1.m_child1->m_child2 = {', + "(DeepData_3) data1.m_child1->m_child2 = {", + 'm_some_text = "Just a test"', + "m_child2 = {", 'm_some_text = "Just a test"', - 'm_child2 = {', - 'm_some_text = "Just a test"']) + ], + ) # Change summary and expand, first without --no-summary-depth then with # --no-summary-depth - self.runCmd( - "type summary add --summary-string \"${var.m_some_text}\" DeepData_5") + self.runCmd('type summary add --summary-string "${var.m_some_text}" DeepData_5') - self.expect('fr var data2.m_child4.m_child2.m_child2', substrs=[ - '(DeepData_5) data2.m_child4.m_child2.m_child2 = "Just a test"']) + self.expect( + "fr var data2.m_child4.m_child2.m_child2", + substrs=['(DeepData_5) data2.m_child4.m_child2.m_child2 = "Just a test"'], + ) self.expect( - 'fr var data2.m_child4.m_child2.m_child2 --no-summary-depth', + "fr var data2.m_child4.m_child2.m_child2 --no-summary-depth", substrs=[ - '(DeepData_5) data2.m_child4.m_child2.m_child2 = {', + "(DeepData_5) data2.m_child4.m_child2.m_child2 = {", 'm_some_text = "Just a test"', - '}']) + "}", + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py b/lldb/test/API/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class SmartArrayDataFormatterTestCase(TestBase): - def test_with_run_command(self): """Test data formatter commands.""" self.build() @@ -21,431 +19,475 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def data_formatter_commands(self): """Test that that file and class static variables display correctly.""" self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) process = self.dbg.GetSelectedTarget().GetProcess() # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) -# check that we are not looping here - self.runCmd("type summary add --summary-string \"${var%V}\" SomeData") + # check that we are not looping here + self.runCmd('type summary add --summary-string "${var%V}" SomeData') - self.expect("frame variable data", - substrs=['SomeData @ 0x']) -# ${var%s} - self.runCmd( - "type summary add --summary-string \"ptr = ${var%s}\" \"char *\"") + self.expect("frame variable data", substrs=["SomeData @ 0x"]) + # ${var%s} + self.runCmd('type summary add --summary-string "ptr = ${var%s}" "char *"') - self.expect("frame variable strptr", - substrs=['ptr = \"', - 'Hello world!']) + self.expect("frame variable strptr", substrs=['ptr = "', "Hello world!"]) - self.expect("frame variable other.strptr", - substrs=['ptr = \"', - 'Nested Hello world!']) + self.expect( + "frame variable other.strptr", substrs=['ptr = "', "Nested Hello world!"] + ) self.runCmd( - "type summary add --summary-string \"arr = ${var%s}\" -x \"char\\[[0-9]+\\]\"") + 'type summary add --summary-string "arr = ${var%s}" -x "char\\[[0-9]+\\]"' + ) - self.expect("frame variable strarr", - substrs=['arr = \"', - 'Hello world!']) + self.expect("frame variable strarr", substrs=['arr = "', "Hello world!"]) - self.expect("frame variable other.strarr", - substrs=['arr = \"', - 'Nested Hello world!']) + self.expect( + "frame variable other.strarr", substrs=['arr = "', "Nested Hello world!"] + ) - self.expect("expression strarr", - substrs=['arr = \"', - 'Hello world!']) + self.expect("expression strarr", substrs=['arr = "', "Hello world!"]) - self.expect("expression other.strarr", - substrs=['arr = \"', - 'Nested Hello world!']) + self.expect( + "expression other.strarr", substrs=['arr = "', "Nested Hello world!"] + ) -# ${var%c} - self.runCmd( - "type summary add --summary-string \"ptr = ${var%c}\" \"char *\"") + # ${var%c} + self.runCmd('type summary add --summary-string "ptr = ${var%c}" "char *"') - self.expect("frame variable strptr", - substrs=['ptr = \"', - 'Hello world!']) + self.expect("frame variable strptr", substrs=['ptr = "', "Hello world!"]) - self.expect("frame variable other.strptr", - substrs=['ptr = \"', - 'Nested Hello world!']) + self.expect( + "frame variable other.strptr", substrs=['ptr = "', "Nested Hello world!"] + ) - self.expect("expression strptr", - substrs=['ptr = \"', - 'Hello world!']) + self.expect("expression strptr", substrs=['ptr = "', "Hello world!"]) - self.expect("expression other.strptr", - substrs=['ptr = \"', - 'Nested Hello world!']) + self.expect( + "expression other.strptr", substrs=['ptr = "', "Nested Hello world!"] + ) self.runCmd( - "type summary add --summary-string \"arr = ${var%c}\" -x \"char\\[[0-9]+\\]\"") + 'type summary add --summary-string "arr = ${var%c}" -x "char\\[[0-9]+\\]"' + ) - self.expect("frame variable strarr", - substrs=['arr = \"', - 'Hello world!']) + self.expect("frame variable strarr", substrs=['arr = "', "Hello world!"]) - self.expect("frame variable other.strarr", - substrs=['arr = \"', - 'Nested Hello world!']) + self.expect( + "frame variable other.strarr", substrs=['arr = "', "Nested Hello world!"] + ) - self.expect("expression strarr", - substrs=['arr = \"', - 'Hello world!']) + self.expect("expression strarr", substrs=['arr = "', "Hello world!"]) - self.expect("expression other.strarr", - substrs=['arr = \"', - 'Nested Hello world!']) + self.expect( + "expression other.strarr", substrs=['arr = "', "Nested Hello world!"] + ) -# ${var%char[]} + # ${var%char[]} self.runCmd( - "type summary add --summary-string \"arr = ${var%char[]}\" -x \"char\\[[0-9]+\\]\"") + 'type summary add --summary-string "arr = ${var%char[]}" -x "char\\[[0-9]+\\]"' + ) - self.expect("frame variable strarr", - substrs=['arr = \"', - 'Hello world!']) + self.expect("frame variable strarr", substrs=['arr = "', "Hello world!"]) - self.expect("frame variable other.strarr", - substrs=['arr = ', - 'Nested Hello world!']) + self.expect( + "frame variable other.strarr", substrs=["arr = ", "Nested Hello world!"] + ) - self.expect("expression strarr", - substrs=['arr = \"', - 'Hello world!']) + self.expect("expression strarr", substrs=['arr = "', "Hello world!"]) - self.expect("expression other.strarr", - substrs=['arr = ', - 'Nested Hello world!']) + self.expect( + "expression other.strarr", substrs=["arr = ", "Nested Hello world!"] + ) - self.runCmd( - "type summary add --summary-string \"ptr = ${var%char[]}\" \"char *\"") + self.runCmd('type summary add --summary-string "ptr = ${var%char[]}" "char *"') - self.expect("frame variable strptr", - substrs=['ptr = \"', - 'Hello world!']) + self.expect("frame variable strptr", substrs=['ptr = "', "Hello world!"]) - self.expect("frame variable other.strptr", - substrs=['ptr = \"', - 'Nested Hello world!']) + self.expect( + "frame variable other.strptr", substrs=['ptr = "', "Nested Hello world!"] + ) - self.expect("expression strptr", - substrs=['ptr = \"', - 'Hello world!']) + self.expect("expression strptr", substrs=['ptr = "', "Hello world!"]) - self.expect("expression other.strptr", - substrs=['ptr = \"', - 'Nested Hello world!']) + self.expect( + "expression other.strptr", substrs=['ptr = "', "Nested Hello world!"] + ) -# ${var%a} + # ${var%a} self.runCmd( - "type summary add --summary-string \"arr = ${var%a}\" -x \"char\\[[0-9]+\\]\"") + 'type summary add --summary-string "arr = ${var%a}" -x "char\\[[0-9]+\\]"' + ) - self.expect("frame variable strarr", - substrs=['arr = \"', - 'Hello world!']) + self.expect("frame variable strarr", substrs=['arr = "', "Hello world!"]) - self.expect("frame variable other.strarr", - substrs=['arr = ', - 'Nested Hello world!']) + self.expect( + "frame variable other.strarr", substrs=["arr = ", "Nested Hello world!"] + ) - self.expect("expression strarr", - substrs=['arr = \"', - 'Hello world!']) + self.expect("expression strarr", substrs=['arr = "', "Hello world!"]) - self.expect("expression other.strarr", - substrs=['arr = ', - 'Nested Hello world!']) + self.expect( + "expression other.strarr", substrs=["arr = ", "Nested Hello world!"] + ) - self.runCmd( - "type summary add --summary-string \"ptr = ${var%a}\" \"char *\"") + self.runCmd('type summary add --summary-string "ptr = ${var%a}" "char *"') - self.expect("frame variable strptr", - substrs=['ptr = \"', - 'Hello world!']) + self.expect("frame variable strptr", substrs=['ptr = "', "Hello world!"]) - self.expect("frame variable other.strptr", - substrs=['ptr = \"', - 'Nested Hello world!']) + self.expect( + "frame variable other.strptr", substrs=['ptr = "', "Nested Hello world!"] + ) - self.expect("expression strptr", - substrs=['ptr = \"', - 'Hello world!']) + self.expect("expression strptr", substrs=['ptr = "', "Hello world!"]) - self.expect("expression other.strptr", - substrs=['ptr = \"', - 'Nested Hello world!']) + self.expect( + "expression other.strptr", substrs=['ptr = "', "Nested Hello world!"] + ) self.runCmd( - "type summary add --summary-string \"ptr = ${var[]%char[]}\" \"char *\"") + 'type summary add --summary-string "ptr = ${var[]%char[]}" "char *"' + ) -# I do not know the size of the data, but you are asking for a full array slice.. -# use the ${var%char[]} to obtain a string as result - self.expect("frame variable strptr", matching=False, - substrs=['ptr = \"', - 'Hello world!']) + # I do not know the size of the data, but you are asking for a full array slice.. + # use the ${var%char[]} to obtain a string as result + self.expect( + "frame variable strptr", matching=False, substrs=['ptr = "', "Hello world!"] + ) - self.expect("frame variable other.strptr", matching=False, - substrs=['ptr = \"', - 'Nested Hello world!']) + self.expect( + "frame variable other.strptr", + matching=False, + substrs=['ptr = "', "Nested Hello world!"], + ) - self.expect("expression strptr", matching=False, - substrs=['ptr = \"', - 'Hello world!']) + self.expect( + "expression strptr", matching=False, substrs=['ptr = "', "Hello world!"] + ) - self.expect("expression other.strptr", matching=False, - substrs=['ptr = \"', - 'Nested Hello world!']) + self.expect( + "expression other.strptr", + matching=False, + substrs=['ptr = "', "Nested Hello world!"], + ) -# You asked an array-style printout... + # You asked an array-style printout... self.runCmd( - "type summary add --summary-string \"ptr = ${var[0-1]%char[]}\" \"char *\"") + 'type summary add --summary-string "ptr = ${var[0-1]%char[]}" "char *"' + ) - self.expect("frame variable strptr", - substrs=['ptr = ', - '[{H},{e}]']) + self.expect("frame variable strptr", substrs=["ptr = ", "[{H},{e}]"]) - self.expect("frame variable other.strptr", - substrs=['ptr = ', - '[{N},{e}]']) + self.expect("frame variable other.strptr", substrs=["ptr = ", "[{N},{e}]"]) - self.expect("expression strptr", - substrs=['ptr = ', - '[{H},{e}]']) + self.expect("expression strptr", substrs=["ptr = ", "[{H},{e}]"]) - self.expect("expression other.strptr", - substrs=['ptr = ', - '[{N},{e}]']) + self.expect("expression other.strptr", substrs=["ptr = ", "[{N},{e}]"]) -# using [] is required here - self.runCmd( - "type summary add --summary-string \"arr = ${var%x}\" \"int [5]\"") + # using [] is required here + self.runCmd('type summary add --summary-string "arr = ${var%x}" "int [5]"') - self.expect("frame variable intarr", matching=False, substrs=[ - '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005']) + self.expect( + "frame variable intarr", + matching=False, + substrs=["0x00000001,0x00000001,0x00000002,0x00000003,0x00000005"], + ) - self.expect("frame variable other.intarr", matching=False, substrs=[ - '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005']) + self.expect( + "frame variable other.intarr", + matching=False, + substrs=["0x00000009,0x00000008,0x00000007,0x00000006,0x00000005"], + ) - self.runCmd( - "type summary add --summary-string \"arr = ${var[]%x}\" \"int[5]\"") + self.runCmd('type summary add --summary-string "arr = ${var[]%x}" "int[5]"') self.expect( "frame variable intarr", substrs=[ - 'intarr = arr =', - '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005']) + "intarr = arr =", + "0x00000001,0x00000001,0x00000002,0x00000003,0x00000005", + ], + ) self.expect( "frame variable other.intarr", substrs=[ - 'intarr = arr =', - '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005']) + "intarr = arr =", + "0x00000009,0x00000008,0x00000007,0x00000006,0x00000005", + ], + ) -# printing each array item as an array + # printing each array item as an array self.runCmd( - "type summary add --summary-string \"arr = ${var[]%uint32_t[]}\" \"int[5]\"") + 'type summary add --summary-string "arr = ${var[]%uint32_t[]}" "int[5]"' + ) self.expect( "frame variable intarr", substrs=[ - 'intarr = arr =', - '{0x00000001},{0x00000001},{0x00000002},{0x00000003},{0x00000005}']) + "intarr = arr =", + "{0x00000001},{0x00000001},{0x00000002},{0x00000003},{0x00000005}", + ], + ) self.expect( "frame variable other.intarr", substrs=[ - 'intarr = arr = ', - '{0x00000009},{0x00000008},{0x00000007},{0x00000006},{0x00000005}']) + "intarr = arr = ", + "{0x00000009},{0x00000008},{0x00000007},{0x00000006},{0x00000005}", + ], + ) -# printing full array as an array + # printing full array as an array self.runCmd( - "type summary add --summary-string \"arr = ${var%uint32_t[]}\" \"int[5]\"") + 'type summary add --summary-string "arr = ${var%uint32_t[]}" "int[5]"' + ) self.expect( "frame variable intarr", substrs=[ - 'intarr = arr =', - '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005']) + "intarr = arr =", + "0x00000001,0x00000001,0x00000002,0x00000003,0x00000005", + ], + ) self.expect( "frame variable other.intarr", substrs=[ - 'intarr = arr =', - '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005']) + "intarr = arr =", + "0x00000009,0x00000008,0x00000007,0x00000006,0x00000005", + ], + ) -# printing each array item as an array + # printing each array item as an array self.runCmd( - "type summary add --summary-string \"arr = ${var[]%float32[]}\" \"float[7]\"") + 'type summary add --summary-string "arr = ${var[]%float32[]}" "float[7]"' + ) self.expect( "frame variable flarr", substrs=[ - 'flarr = arr =', - '{78.5},{77.25},{78},{76.125},{76.75},{76.875},{77}']) + "flarr = arr =", + "{78.5},{77.25},{78},{76.125},{76.75},{76.875},{77}", + ], + ) self.expect( "frame variable other.flarr", substrs=[ - 'flarr = arr = ', - '{25.5},{25.25},{25.125},{26.75},{27.375},{27.5},{26.125}']) + "flarr = arr = ", + "{25.5},{25.25},{25.125},{26.75},{27.375},{27.5},{26.125}", + ], + ) -# printing full array as an array + # printing full array as an array self.runCmd( - "type summary add --summary-string \"arr = ${var%float32[]}\" \"float[7]\"") + 'type summary add --summary-string "arr = ${var%float32[]}" "float[7]"' + ) - self.expect("frame variable flarr", - substrs=['flarr = arr =', - '78.5,77.25,78,76.125,76.75,76.875,77']) + self.expect( + "frame variable flarr", + substrs=["flarr = arr =", "78.5,77.25,78,76.125,76.75,76.875,77"], + ) - self.expect("frame variable other.flarr", - substrs=['flarr = arr =', - '25.5,25.25,25.125,26.75,27.375,27.5,26.125']) + self.expect( + "frame variable other.flarr", + substrs=["flarr = arr =", "25.5,25.25,25.125,26.75,27.375,27.5,26.125"], + ) -# using array smart summary strings for pointers should make no sense + # using array smart summary strings for pointers should make no sense self.runCmd( - "type summary add --summary-string \"arr = ${var%float32[]}\" \"float *\"") + 'type summary add --summary-string "arr = ${var%float32[]}" "float *"' + ) self.runCmd( - "type summary add --summary-string \"arr = ${var%int32_t[]}\" \"int *\"") + 'type summary add --summary-string "arr = ${var%int32_t[]}" "int *"' + ) - self.expect("frame variable flptr", matching=False, - substrs=['78.5,77.25,78,76.125,76.75,76.875,77']) + self.expect( + "frame variable flptr", + matching=False, + substrs=["78.5,77.25,78,76.125,76.75,76.875,77"], + ) - self.expect("frame variable intptr", matching=False, - substrs=['1,1,2,3,5']) + self.expect("frame variable intptr", matching=False, substrs=["1,1,2,3,5"]) -# use y and Y - self.runCmd( - "type summary add --summary-string \"arr = ${var%y}\" \"float[7]\"") - self.runCmd( - "type summary add --summary-string \"arr = ${var%y}\" \"int[5]\"") + # use y and Y + self.runCmd('type summary add --summary-string "arr = ${var%y}" "float[7]"') + self.runCmd('type summary add --summary-string "arr = ${var%y}" "int[5]"') if process.GetByteOrder() == lldb.eByteOrderLittle: self.expect( "frame variable flarr", substrs=[ - 'flarr = arr =', - '00 00 9d 42,00 80 9a 42,00 00 9c 42,00 40 98 42,00 80 99 42,00 c0 99 42,00 00 9a 42']) + "flarr = arr =", + "00 00 9d 42,00 80 9a 42,00 00 9c 42,00 40 98 42,00 80 99 42,00 c0 99 42,00 00 9a 42", + ], + ) else: self.expect( "frame variable flarr", substrs=[ - 'flarr = arr =', - '42 9d 00 00,42 9a 80 00,42 9c 00 00,42 98 40 00,42 99 80 00,42 99 c0 00,42 9a 00 00']) + "flarr = arr =", + "42 9d 00 00,42 9a 80 00,42 9c 00 00,42 98 40 00,42 99 80 00,42 99 c0 00,42 9a 00 00", + ], + ) if process.GetByteOrder() == lldb.eByteOrderLittle: self.expect( "frame variable other.flarr", substrs=[ - 'flarr = arr =', - '00 00 cc 41,00 00 ca 41,00 00 c9 41,00 00 d6 41,00 00 db 41,00 00 dc 41,00 00 d1 41']) + "flarr = arr =", + "00 00 cc 41,00 00 ca 41,00 00 c9 41,00 00 d6 41,00 00 db 41,00 00 dc 41,00 00 d1 41", + ], + ) else: self.expect( "frame variable other.flarr", substrs=[ - 'flarr = arr =', - '41 cc 00 00,41 ca 00 00,41 c9 00 00,41 d6 00 00,41 db 00 00,41 dc 00 00,41 d1 00 00']) + "flarr = arr =", + "41 cc 00 00,41 ca 00 00,41 c9 00 00,41 d6 00 00,41 db 00 00,41 dc 00 00,41 d1 00 00", + ], + ) if process.GetByteOrder() == lldb.eByteOrderLittle: self.expect( "frame variable intarr", substrs=[ - 'intarr = arr =', - '01 00 00 00,01 00 00 00,02 00 00 00,03 00 00 00,05 00 00 00']) + "intarr = arr =", + "01 00 00 00,01 00 00 00,02 00 00 00,03 00 00 00,05 00 00 00", + ], + ) else: self.expect( "frame variable intarr", substrs=[ - 'intarr = arr =', - '00 00 00 01,00 00 00 01,00 00 00 02,00 00 00 03,00 00 00 05']) + "intarr = arr =", + "00 00 00 01,00 00 00 01,00 00 00 02,00 00 00 03,00 00 00 05", + ], + ) if process.GetByteOrder() == lldb.eByteOrderLittle: self.expect( "frame variable other.intarr", substrs=[ - 'intarr = arr = ', - '09 00 00 00,08 00 00 00,07 00 00 00,06 00 00 00,05 00 00 00']) + "intarr = arr = ", + "09 00 00 00,08 00 00 00,07 00 00 00,06 00 00 00,05 00 00 00", + ], + ) else: self.expect( "frame variable other.intarr", substrs=[ - 'intarr = arr = ', - '00 00 00 09,00 00 00 08,00 00 00 07,00 00 00 06,00 00 00 05']) + "intarr = arr = ", + "00 00 00 09,00 00 00 08,00 00 00 07,00 00 00 06,00 00 00 05", + ], + ) - self.runCmd( - "type summary add --summary-string \"arr = ${var%Y}\" \"float[7]\"") - self.runCmd( - "type summary add --summary-string \"arr = ${var%Y}\" \"int[5]\"") + self.runCmd('type summary add --summary-string "arr = ${var%Y}" "float[7]"') + self.runCmd('type summary add --summary-string "arr = ${var%Y}" "int[5]"') if process.GetByteOrder() == lldb.eByteOrderLittle: self.expect( "frame variable flarr", substrs=[ - 'flarr = arr =', - '00 00 9d 42', '00 80 9a 42', '00 00 9c 42', '00 40 98 42', '00 80 99 42', '00 c0 99 42', '00 00 9a 42']) + "flarr = arr =", + "00 00 9d 42", + "00 80 9a 42", + "00 00 9c 42", + "00 40 98 42", + "00 80 99 42", + "00 c0 99 42", + "00 00 9a 42", + ], + ) else: self.expect( "frame variable flarr", substrs=[ - 'flarr = arr =', - '42 9d 00 00', '42 9a 80 00', '42 9c 00 00', '42 98 40 00', '42 99 80 00', '42 99 c0 00', '42 9a 00 00']) + "flarr = arr =", + "42 9d 00 00", + "42 9a 80 00", + "42 9c 00 00", + "42 98 40 00", + "42 99 80 00", + "42 99 c0 00", + "42 9a 00 00", + ], + ) if process.GetByteOrder() == lldb.eByteOrderLittle: self.expect( "frame variable other.flarr", substrs=[ - 'flarr = arr =', - '00 00 cc 41', '00 00 ca 41', '00 00 c9 41', '00 00 d6 41', '00 00 db 41', '00 00 dc 41', '00 00 d1 41']) + "flarr = arr =", + "00 00 cc 41", + "00 00 ca 41", + "00 00 c9 41", + "00 00 d6 41", + "00 00 db 41", + "00 00 dc 41", + "00 00 d1 41", + ], + ) else: self.expect( "frame variable other.flarr", substrs=[ - 'flarr = arr =', - '41 cc 00 00', '41 ca 00 00', '41 c9 00 00', '41 d6 00 00', '41 db 00 00', '41 dc 00 00', '41 d1 00 00']) + "flarr = arr =", + "41 cc 00 00", + "41 ca 00 00", + "41 c9 00 00", + "41 d6 00 00", + "41 db 00 00", + "41 dc 00 00", + "41 d1 00 00", + ], + ) if process.GetByteOrder() == lldb.eByteOrderLittle: - self.expect("frame variable intarr", - substrs=['intarr = arr =', - '....,01 00 00 00', - '....,05 00 00 00']) + self.expect( + "frame variable intarr", + substrs=["intarr = arr =", "....,01 00 00 00", "....,05 00 00 00"], + ) else: - self.expect("frame variable intarr", - substrs=['intarr = arr =', - '....,00 00 00 01', - '....,00 00 00 05']) + self.expect( + "frame variable intarr", + substrs=["intarr = arr =", "....,00 00 00 01", "....,00 00 00 05"], + ) if process.GetByteOrder() == lldb.eByteOrderLittle: - self.expect("frame variable other.intarr", - substrs=['intarr = arr = ', - '09 00 00 00', - '....,07 00 00 00']) + self.expect( + "frame variable other.intarr", + substrs=["intarr = arr = ", "09 00 00 00", "....,07 00 00 00"], + ) else: - self.expect("frame variable other.intarr", - substrs=['intarr = arr = ', - '00 00 00 09', - '....,00 00 00 07']) + self.expect( + "frame variable other.intarr", + substrs=["intarr = arr = ", "00 00 00 09", "....,00 00 00 07"], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/bitset/TestDataFormatterGenericBitset.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/bitset/TestDataFormatterGenericBitset.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/bitset/TestDataFormatterGenericBitset.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/bitset/TestDataFormatterGenericBitset.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -15,14 +14,14 @@ REFERENCE = "REFERENCE" POINTER = "POINTER" -class GenericBitsetDataFormatterTestCase(TestBase): +class GenericBitsetDataFormatterTestCase(TestBase): def setUp(self): TestBase.setUp(self) - primes = [1]*1000 + primes = [1] * 1000 primes[0] = primes[1] = 0 for i in range(2, len(primes)): - for j in range(2*i, len(primes), i): + for j in range(2 * i, len(primes), i): primes[j] = 0 self.primes = primes @@ -42,17 +41,25 @@ children = [] for i in range(size): child = var.GetChildAtIndex(i) - children.append(ValueCheck(value=str(bool(child.GetValueAsUnsigned())).lower())) - self.assertEqual(child.GetValueAsUnsigned(), self.primes[i], - "variable: %s, index: %d"%(name, size)) - self.expect_var_path(name,type=self.getBitsetVariant(size,variant),children=children) + children.append( + ValueCheck(value=str(bool(child.GetValueAsUnsigned())).lower()) + ) + self.assertEqual( + child.GetValueAsUnsigned(), + self.primes[i], + "variable: %s, index: %d" % (name, size), + ) + self.expect_var_path( + name, type=self.getBitsetVariant(size, variant), children=children + ) def do_test_value(self, stdlib_type): """Test that std::bitset is displayed correctly""" self.build(dictionary={stdlib_type: "1"}) - lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp", False)) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) self.check("empty", 0, VALUE) self.check("small", 13, VALUE) @@ -71,9 +78,9 @@ """Test that ref and ptr to std::bitset is displayed correctly""" self.build(dictionary={stdlib_type: "1"}) - (_, process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, - 'Check ref and ptr', - lldb.SBFileSpec("main.cpp", False)) + (_, process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Check ref and ptr", lldb.SBFileSpec("main.cpp", False) + ) self.check("ref", 13, REFERENCE) self.check("ptr", 13, POINTER) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/TestCoroutineHandle.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/TestCoroutineHandle.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/TestCoroutineHandle.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/TestCoroutineHandle.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,6 +11,7 @@ USE_LIBSTDCPP = "USE_LIBSTDCPP" USE_LIBCPP = "USE_LIBCPP" + class TestCoroutineHandle(TestBase): def do_test(self, stdlib_type): """Test std::coroutine_handle is displayed correctly.""" @@ -19,96 +19,130 @@ is_clang = self.expectedCompiler(["clang"]) test_generator_func_ptr_re = re.compile( - r"^\(a.out`my_generator_func\(\) at main.cpp:[0-9]*\)$") + r"^\(a.out`my_generator_func\(\) at main.cpp:[0-9]*\)$" + ) # Run until the initial suspension point - lldbutil.run_to_source_breakpoint(self, '// Break at initial_suspend', - lldb.SBFileSpec("main.cpp", False)) + lldbutil.run_to_source_breakpoint( + self, "// Break at initial_suspend", lldb.SBFileSpec("main.cpp", False) + ) if self.frame().FindVariable("is_supported").GetValueAsUnsigned(1) == 0: self.skipTest("c++ library not supported") - # Check that we show the correct function pointers and the `promise`. - self.expect_expr("gen.hdl", + # Check that we show the correct function pointers and the `promise`. + self.expect_expr( + "gen.hdl", result_summary=re.compile("^coro frame = 0x[0-9a-f]*$"), result_children=[ - ValueCheck(name="resume", summary = test_generator_func_ptr_re), - ValueCheck(name="destroy", summary = test_generator_func_ptr_re), - ValueCheck(name="promise", children=[ - ValueCheck(name="current_value", value = "-1"), - ]) - ]) + ValueCheck(name="resume", summary=test_generator_func_ptr_re), + ValueCheck(name="destroy", summary=test_generator_func_ptr_re), + ValueCheck( + name="promise", + children=[ + ValueCheck(name="current_value", value="-1"), + ], + ), + ], + ) if is_clang: # For a type-erased `coroutine_handle<>`, we can still devirtualize # the promise call and display the correctly typed promise. - self.expect_expr("type_erased_hdl", + self.expect_expr( + "type_erased_hdl", result_summary=re.compile("^coro frame = 0x[0-9a-f]*$"), result_children=[ - ValueCheck(name="resume", summary = test_generator_func_ptr_re), - ValueCheck(name="destroy", summary = test_generator_func_ptr_re), - ValueCheck(name="promise", children=[ - ValueCheck(name="current_value", value = "-1"), - ]) - ]) + ValueCheck(name="resume", summary=test_generator_func_ptr_re), + ValueCheck(name="destroy", summary=test_generator_func_ptr_re), + ValueCheck( + name="promise", + children=[ + ValueCheck(name="current_value", value="-1"), + ], + ), + ], + ) # For an incorrectly typed `coroutine_handle`, we use the user-supplied # incorrect type instead of inferring the correct type. Strictly speaking, # incorrectly typed coroutine handles are undefined behavior. However, # it provides probably a better debugging experience if we display the # promise as seen by the program instead of fixing this bug based on # the available debug info. - self.expect_expr("incorrectly_typed_hdl", + self.expect_expr( + "incorrectly_typed_hdl", result_summary=re.compile("^coro frame = 0x[0-9a-f]*$"), result_children=[ - ValueCheck(name="resume", summary = test_generator_func_ptr_re), - ValueCheck(name="destroy", summary = test_generator_func_ptr_re), - ValueCheck(name="promise", dereference=ValueCheck(value="-1")) - ]) + ValueCheck(name="resume", summary=test_generator_func_ptr_re), + ValueCheck(name="destroy", summary=test_generator_func_ptr_re), + ValueCheck(name="promise", dereference=ValueCheck(value="-1")), + ], + ) # Run until after the `co_yield` process = self.process() - lldbutil.continue_to_source_breakpoint(self, process, - '// Break after co_yield', lldb.SBFileSpec("main.cpp", False)) + lldbutil.continue_to_source_breakpoint( + self, process, "// Break after co_yield", lldb.SBFileSpec("main.cpp", False) + ) # We correctly show the updated value inside `prommise.current_value`. - self.expect_expr("gen.hdl", + self.expect_expr( + "gen.hdl", result_children=[ - ValueCheck(name="resume", summary = test_generator_func_ptr_re), - ValueCheck(name="destroy", summary = test_generator_func_ptr_re), - ValueCheck(name="promise", children=[ - ValueCheck(name="current_value", value = "42"), - ]) - ]) - + ValueCheck(name="resume", summary=test_generator_func_ptr_re), + ValueCheck(name="destroy", summary=test_generator_func_ptr_re), + ValueCheck( + name="promise", + children=[ + ValueCheck(name="current_value", value="42"), + ], + ), + ], + ) + # Run until the `final_suspend` - lldbutil.continue_to_source_breakpoint(self, process, - '// Break at final_suspend', lldb.SBFileSpec("main.cpp", False)) + lldbutil.continue_to_source_breakpoint( + self, + process, + "// Break at final_suspend", + lldb.SBFileSpec("main.cpp", False), + ) # At the final suspension point, `resume` is set to a nullptr. # Check that we still show the remaining data correctly. - self.expect_expr("gen.hdl", + self.expect_expr( + "gen.hdl", result_children=[ - ValueCheck(name="resume", value = re.compile("^0x0+$")), - ValueCheck(name="destroy", summary = test_generator_func_ptr_re), - ValueCheck(name="promise", children=[ - ValueCheck(name="current_value", value = "42"), - ]) - ]) + ValueCheck(name="resume", value=re.compile("^0x0+$")), + ValueCheck(name="destroy", summary=test_generator_func_ptr_re), + ValueCheck( + name="promise", + children=[ + ValueCheck(name="current_value", value="42"), + ], + ), + ], + ) if is_clang: # Devirtualization still works, also at the final suspension point, despite # the `resume` pointer being reset to a nullptr - self.expect_expr("type_erased_hdl", + self.expect_expr( + "type_erased_hdl", result_summary=re.compile("^coro frame = 0x[0-9a-f]*$"), result_children=[ - ValueCheck(name="resume", value = re.compile("^0x0+$")), - ValueCheck(name="destroy", summary = test_generator_func_ptr_re), - ValueCheck(name="promise", children=[ - ValueCheck(name="current_value", value = "42"), - ]) - ]) + ValueCheck(name="resume", value=re.compile("^0x0+$")), + ValueCheck(name="destroy", summary=test_generator_func_ptr_re), + ValueCheck( + name="promise", + children=[ + ValueCheck(name="current_value", value="42"), + ], + ), + ], + ) @add_test_categories(["libstdcxx"]) def test_libstdcpp(self): self.do_test(USE_LIBSTDCPP) @add_test_categories(["libc++"]) - @skipIf(compiler="clang", compiler_version=['<', '15.0']) + @skipIf(compiler="clang", compiler_version=["<", "15.0"]) def test_libcpp(self): self.do_test(USE_LIBCPP) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/deque/TestDataFormatterGenericDeque.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/deque/TestDataFormatterGenericDeque.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/deque/TestDataFormatterGenericDeque.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/deque/TestDataFormatterGenericDeque.py @@ -6,8 +6,8 @@ USE_LIBSTDCPP = "USE_LIBSTDCPP" USE_LIBCPP = "USE_LIBCPP" -class GenericDequeDataFormatterTestCase(TestBase): +class GenericDequeDataFormatterTestCase(TestBase): def findVariable(self, name): var = self.frame().FindVariable(name) self.assertTrue(var.IsValid()) @@ -21,49 +21,67 @@ var = self.findVariable(var_name) self.assertEqual(var.GetNumChildren(), size) - def do_test(self, stdlib_type): - self.build(dictionary={stdlib_type: '1'}) - lldbutil.run_to_source_breakpoint(self, "break here", - lldb.SBFileSpec("main.cpp")) + self.build(dictionary={stdlib_type: "1"}) + lldbutil.run_to_source_breakpoint( + self, "break here", lldb.SBFileSpec("main.cpp") + ) self.expect_expr("empty", result_children=[]) - self.expect_expr("deque_1", result_children=[ - ValueCheck(name="[0]", value="1"), - ]) - self.expect_expr("deque_3", result_children=[ - ValueCheck(name="[0]", value="3"), - ValueCheck(name="[1]", value="1"), - ValueCheck(name="[2]", value="2") - ]) + self.expect_expr( + "deque_1", + result_children=[ + ValueCheck(name="[0]", value="1"), + ], + ) + self.expect_expr( + "deque_3", + result_children=[ + ValueCheck(name="[0]", value="3"), + ValueCheck(name="[1]", value="1"), + ValueCheck(name="[2]", value="2"), + ], + ) self.check_size("deque_200_small", 200) for i in range(0, 100): - self.expect_var_path("deque_200_small[%d]"%(i), children=[ - ValueCheck(name="a", value=str(-99 + i)), - ValueCheck(name="b", value=str(-100 + i)), - ValueCheck(name="c", value=str(-101 + i)), - ]) - self.expect_var_path("deque_200_small[%d]"%(i + 100), children=[ - ValueCheck(name="a", value=str(i)), - ValueCheck(name="b", value=str(1 + i)), - ValueCheck(name="c", value=str(2 + i)), - ]) + self.expect_var_path( + "deque_200_small[%d]" % (i), + children=[ + ValueCheck(name="a", value=str(-99 + i)), + ValueCheck(name="b", value=str(-100 + i)), + ValueCheck(name="c", value=str(-101 + i)), + ], + ) + self.expect_var_path( + "deque_200_small[%d]" % (i + 100), + children=[ + ValueCheck(name="a", value=str(i)), + ValueCheck(name="b", value=str(1 + i)), + ValueCheck(name="c", value=str(2 + i)), + ], + ) self.check_size("deque_200_large", 200) for i in range(0, 100): - self.expect_var_path("deque_200_large[%d]"%(i), children=[ - ValueCheck(name="a", value=str(-99 + i)), - ValueCheck(name="b", value=str(-100 + i)), - ValueCheck(name="c", value=str(-101 + i)), - ValueCheck(name="d") - ]) - self.expect_var_path("deque_200_large[%d]"%(i + 100), children=[ - ValueCheck(name="a", value=str(i)), - ValueCheck(name="b", value=str(1 + i)), - ValueCheck(name="c", value=str(2 + i)), - ValueCheck(name="d") - ]) + self.expect_var_path( + "deque_200_large[%d]" % (i), + children=[ + ValueCheck(name="a", value=str(-99 + i)), + ValueCheck(name="b", value=str(-100 + i)), + ValueCheck(name="c", value=str(-101 + i)), + ValueCheck(name="d"), + ], + ) + self.expect_var_path( + "deque_200_large[%d]" % (i + 100), + children=[ + ValueCheck(name="a", value=str(i)), + ValueCheck(name="b", value=str(1 + i)), + ValueCheck(name="c", value=str(2 + i)), + ValueCheck(name="d"), + ], + ) @add_test_categories(["libstdcxx"]) def test_libstdcpp(self): @@ -71,4 +89,4 @@ @add_test_categories(["libc++"]) def test_libcpp(self): - self.do_test(USE_LIBCPP) + self.do_test(USE_LIBCPP) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/forward_list/TestDataFormatterGenericForwardList.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/forward_list/TestDataFormatterGenericForwardList.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/forward_list/TestDataFormatterGenericForwardList.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/forward_list/TestDataFormatterGenericForwardList.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,157 +11,151 @@ USE_LIBSTDCPP = "USE_LIBSTDCPP" USE_LIBCPP = "USE_LIBCPP" -class TestDataFormatterGenericForwardList(TestBase): +class TestDataFormatterGenericForwardList(TestBase): def setUp(self): TestBase.setUp(self) - self.line = line_number('main.cpp', '// break here') - self.namespace = 'std' - + self.line = line_number("main.cpp", "// break here") + self.namespace = "std" def do_test(self, stdlib_type): """Test that std::forward_list is displayed correctly""" self.build(dictionary={stdlib_type: "1"}) - lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp", False)) - - forward_list = self.namespace + '::forward_list' - self.expect("frame variable empty", - substrs=[forward_list, - 'size=0', - '{}']) - - self.expect("frame variable one_elt", - substrs=[forward_list, - 'size=1', - '{', - '[0] = 47', - '}']) - - self.expect("frame variable five_elts", - substrs=[forward_list, - 'size=5', - '{', - '[0] = 1', - '[1] = 22', - '[2] = 333', - '[3] = 4444', - '[4] = 55555', - '}']) - - self.expect("settings show target.max-children-count", matching=True, - substrs=['target.max-children-count (int) = 256']) - - self.expect("frame variable thousand_elts",matching=False, - substrs=[ - '[256]', - '[333]', - '[444]', - '[555]', - '[666]', - '...' - ]) - self.runCmd( - "settings set target.max-children-count 3", - check=False) - - self.expect("frame variable thousand_elts",matching=False, - substrs=[ - '[3]', - '[4]', - '[5]', - ]) - - self.expect("frame variable thousand_elts",matching=True, - substrs=[ - 'size=256', - '[0]', - '[1]', - '[2]', - '...' - ]) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) + + forward_list = self.namespace + "::forward_list" + self.expect("frame variable empty", substrs=[forward_list, "size=0", "{}"]) + + self.expect( + "frame variable one_elt", + substrs=[forward_list, "size=1", "{", "[0] = 47", "}"], + ) + + self.expect( + "frame variable five_elts", + substrs=[ + forward_list, + "size=5", + "{", + "[0] = 1", + "[1] = 22", + "[2] = 333", + "[3] = 4444", + "[4] = 55555", + "}", + ], + ) + + self.expect( + "settings show target.max-children-count", + matching=True, + substrs=["target.max-children-count (int) = 256"], + ) + + self.expect( + "frame variable thousand_elts", + matching=False, + substrs=["[256]", "[333]", "[444]", "[555]", "[666]", "..."], + ) + self.runCmd("settings set target.max-children-count 3", check=False) + + self.expect( + "frame variable thousand_elts", + matching=False, + substrs=[ + "[3]", + "[4]", + "[5]", + ], + ) + + self.expect( + "frame variable thousand_elts", + matching=True, + substrs=["size=256", "[0]", "[1]", "[2]", "..."], + ) def do_test_ptr_and_ref(self, stdlib_type): """Test that ref and ptr to std::forward_list is displayed correctly""" self.build(dictionary={stdlib_type: "1"}) - (_, process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, - 'Check ref and ptr', - lldb.SBFileSpec("main.cpp", False)) + (_, process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Check ref and ptr", lldb.SBFileSpec("main.cpp", False) + ) - self.expect("frame variable ref", - substrs=[ - 'size=0', - '{}']) + self.expect("frame variable ref", substrs=["size=0", "{}"]) - self.expect("frame variable *ptr", - substrs=[ - 'size=0', - '{}']) + self.expect("frame variable *ptr", substrs=["size=0", "{}"]) lldbutil.continue_to_breakpoint(process, bkpt) - self.expect("frame variable ref", - substrs=[ - '{', - '[0] = 47', - '}']) + self.expect("frame variable ref", substrs=["{", "[0] = 47", "}"]) - self.expect("frame variable *ptr", - substrs=[ - '{', - '[0] = 47', - '}']) + self.expect("frame variable *ptr", substrs=["{", "[0] = 47", "}"]) lldbutil.continue_to_breakpoint(process, bkpt) - self.expect("frame variable ref", - substrs=[ - 'size=5', - '{', - '[0] = 1', - '[1] = 22', - '[2] = 333', - '[3] = 4444', - '[4] = 55555', - '}']) - - self.expect("frame variable *ptr", - substrs=[ - 'size=5', - '{', - '[0] = 1', - '[1] = 22', - '[2] = 333', - '[3] = 4444', - '[4] = 55555', - '}']) + self.expect( + "frame variable ref", + substrs=[ + "size=5", + "{", + "[0] = 1", + "[1] = 22", + "[2] = 333", + "[3] = 4444", + "[4] = 55555", + "}", + ], + ) + + self.expect( + "frame variable *ptr", + substrs=[ + "size=5", + "{", + "[0] = 1", + "[1] = 22", + "[2] = 333", + "[3] = 4444", + "[4] = 55555", + "}", + ], + ) lldbutil.continue_to_breakpoint(process, bkpt) - self.runCmd( - "settings set target.max-children-count 256", - check=False) - - self.expect("settings show target.max-children-count", matching=True, - substrs=['target.max-children-count (int) = 256']) - - - self.expect("frame variable ref",matching=True, - substrs=[ - 'size=256', - '[0] = 999', - '[1] = 998', - '[2] = 997', - ]) - - self.expect("frame variable *ptr",matching=True, - substrs=[ - 'size=256', - '[0] = 999', - '[1] = 998', - '[2] = 997', - ]) + self.runCmd("settings set target.max-children-count 256", check=False) + + self.expect( + "settings show target.max-children-count", + matching=True, + substrs=["target.max-children-count (int) = 256"], + ) + + self.expect( + "frame variable ref", + matching=True, + substrs=[ + "size=256", + "[0] = 999", + "[1] = 998", + "[2] = 997", + ], + ) + + self.expect( + "frame variable *ptr", + matching=True, + substrs=[ + "size=256", + "[0] = 999", + "[1] = 998", + "[2] = 997", + ], + ) @add_test_categories(["libstdcxx"]) def test_libstdcpp(self): @@ -174,8 +167,8 @@ @add_test_categories(["libc++"]) def test_libcpp(self): - self.do_test(USE_LIBCPP) + self.do_test(USE_LIBCPP) @add_test_categories(["libc++"]) def test_ptr_and_ref_libcpp(self): - self.do_test_ptr_and_ref(USE_LIBCPP) + self.do_test_ptr_and_ref(USE_LIBCPP) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/list/TestDataFormatterGenericList.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/list/TestDataFormatterGenericList.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/list/TestDataFormatterGenericList.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/list/TestDataFormatterGenericList.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,17 +11,19 @@ USE_LIBSTDCPP = "USE_LIBSTDCPP" USE_LIBCPP = "USE_LIBCPP" -class GenericListDataFormatterTestCase(TestBase): +class GenericListDataFormatterTestCase(TestBase): def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line numbers to break at for the different tests. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") self.optional_line = line_number( - 'main.cpp', '// Optional break point at this line.') + "main.cpp", "// Optional break point at this line." + ) self.final_line = line_number( - 'main.cpp', '// Set final break point at this line.') + "main.cpp", "// Set final break point at this line." + ) def do_test_with_run_command(self, stdlib_type): """Test that that file and class static variables display correctly.""" @@ -30,25 +31,26 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=-1) + self, "main.cpp", self.line, num_expected_locations=-1 + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -57,196 +59,250 @@ self.runCmd("type format add -f hex int") - self.expect("frame variable numbers_list --raw", matching=False, - substrs=['size=0', - '{}']) + self.expect( + "frame variable numbers_list --raw", + matching=False, + substrs=["size=0", "{}"], + ) if stdlib_type == USE_LIBSTDCPP: self.expect( "frame variable &numbers_list._M_impl._M_node --raw", matching=False, - substrs=[ - 'size=0', - '{}']) + substrs=["size=0", "{}"], + ) - self.expect("frame variable numbers_list", - substrs=['size=0', - '{}']) + self.expect("frame variable numbers_list", substrs=["size=0", "{}"]) - self.expect("expression numbers_list", - substrs=['size=0', - '{}']) + self.expect("expression numbers_list", substrs=["size=0", "{}"]) self.runCmd("n") - self.expect("frame variable numbers_list", - substrs=['size=1', - '[0] = ', - '0x12345678']) + self.expect( + "frame variable numbers_list", substrs=["size=1", "[0] = ", "0x12345678"] + ) self.runCmd("n") self.runCmd("n") self.runCmd("n") - self.expect("frame variable numbers_list", - substrs=['size=4', - '[0] = ', - '0x12345678', - '[1] =', - '0x11223344', - '[2] =', - '0xbeeffeed', - '[3] =', - '0x00abba00']) + self.expect( + "frame variable numbers_list", + substrs=[ + "size=4", + "[0] = ", + "0x12345678", + "[1] =", + "0x11223344", + "[2] =", + "0xbeeffeed", + "[3] =", + "0x00abba00", + ], + ) self.runCmd("n") self.runCmd("n") - self.expect("frame variable numbers_list", - substrs=['size=6', - '[0] = ', - '0x12345678', - '0x11223344', - '0xbeeffeed', - '0x00abba00', - '[4] =', - '0x0abcdef0', - '[5] =', - '0x0cab0cab']) - - self.expect("expression numbers_list", - substrs=['size=6', - '[0] = ', - '0x12345678', - '0x11223344', - '0xbeeffeed', - '0x00abba00', - '[4] =', - '0x0abcdef0', - '[5] =', - '0x0cab0cab']) + self.expect( + "frame variable numbers_list", + substrs=[ + "size=6", + "[0] = ", + "0x12345678", + "0x11223344", + "0xbeeffeed", + "0x00abba00", + "[4] =", + "0x0abcdef0", + "[5] =", + "0x0cab0cab", + ], + ) + + self.expect( + "expression numbers_list", + substrs=[ + "size=6", + "[0] = ", + "0x12345678", + "0x11223344", + "0xbeeffeed", + "0x00abba00", + "[4] =", + "0x0abcdef0", + "[5] =", + "0x0cab0cab", + ], + ) # check access-by-index - self.expect("frame variable numbers_list[0]", - substrs=['0x12345678']) - self.expect("frame variable numbers_list[1]", - substrs=['0x11223344']) + self.expect("frame variable numbers_list[0]", substrs=["0x12345678"]) + self.expect("frame variable numbers_list[1]", substrs=["0x11223344"]) # but check that expression does not rely on us - self.expect("expression numbers_list[0]", matching=False, error=True, - substrs=['0x12345678']) + self.expect( + "expression numbers_list[0]", + matching=False, + error=True, + substrs=["0x12345678"], + ) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("numbers_list").MightHaveChildren(), - "numbers_list.MightHaveChildren() says False for non empty!") + "numbers_list.MightHaveChildren() says False for non empty!", + ) self.runCmd("n") - self.expect("frame variable numbers_list", - substrs=['size=0', - '{}']) + self.expect("frame variable numbers_list", substrs=["size=0", "{}"]) self.runCmd("n") self.runCmd("n") self.runCmd("n") self.runCmd("n") - self.expect("frame variable numbers_list", - substrs=['size=4', - '[0] = ', '1', - '[1] = ', '2', - '[2] = ', '3', - '[3] = ', '4']) + self.expect( + "frame variable numbers_list", + substrs=[ + "size=4", + "[0] = ", + "1", + "[1] = ", + "2", + "[2] = ", + "3", + "[3] = ", + "4", + ], + ) self.runCmd("type format delete int") - lldbutil.run_break_set_by_file_and_line(self, "main.cpp", - self.optional_line) + lldbutil.run_break_set_by_file_and_line(self, "main.cpp", self.optional_line) self.runCmd("continue") - self.expect("frame variable text_list", - substrs=['size=0', - '{}']) + self.expect("frame variable text_list", substrs=["size=0", "{}"]) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.final_line, num_expected_locations=-1) + self, "main.cpp", self.final_line, num_expected_locations=-1 + ) self.runCmd("c", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) - - self.expect("frame variable text_list", - substrs=['size=4', - '[0]', 'goofy', - '[1]', 'is', - '[2]', 'smart', - '[3]', '!!!']) - - self.expect("expression text_list", - substrs=['size=4', - '\"goofy\"', - '\"is\"', - '\"smart\"', - '\"!!!\"']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) + + self.expect( + "frame variable text_list", + substrs=[ + "size=4", + "[0]", + "goofy", + "[1]", + "is", + "[2]", + "smart", + "[3]", + "!!!", + ], + ) + + self.expect( + "expression text_list", + substrs=["size=4", '"goofy"', '"is"', '"smart"', '"!!!"'], + ) # check access-by-index - self.expect("frame variable text_list[0]", - substrs=['goofy']) - self.expect("frame variable text_list[3]", - substrs=['!!!']) + self.expect("frame variable text_list[0]", substrs=["goofy"]) + self.expect("frame variable text_list[3]", substrs=["!!!"]) # but check that expression does not rely on us - self.expect("expression text_list[0]", matching=False, error=True, - substrs=['goofy']) + self.expect( + "expression text_list[0]", matching=False, error=True, substrs=["goofy"] + ) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("text_list").MightHaveChildren(), - "text_list.MightHaveChildren() says False for non empty!") + "text_list.MightHaveChildren() says False for non empty!", + ) def do_test_ptr_and_ref(self, stdlib_type): """Test that ref and ptr to std::list is displayed correctly""" self.build(dictionary={stdlib_type: "1"}) - (_, process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, - 'Check ref and ptr', - lldb.SBFileSpec("main.cpp", False)) - - self.expect("frame variable ref", - substrs=['size=4', - '[0] = ', '1', - '[1] = ', '2', - '[2] = ', '3', - '[3] = ', '4']) - - - self.expect("frame variable *ptr", - substrs=['size=4', - '[0] = ', '1', - '[1] = ', '2', - '[2] = ', '3', - '[3] = ', '4']) + (_, process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Check ref and ptr", lldb.SBFileSpec("main.cpp", False) + ) + + self.expect( + "frame variable ref", + substrs=[ + "size=4", + "[0] = ", + "1", + "[1] = ", + "2", + "[2] = ", + "3", + "[3] = ", + "4", + ], + ) + + self.expect( + "frame variable *ptr", + substrs=[ + "size=4", + "[0] = ", + "1", + "[1] = ", + "2", + "[2] = ", + "3", + "[3] = ", + "4", + ], + ) lldbutil.continue_to_breakpoint(process, bkpt) - self.expect("frame variable ref", - substrs=['size=4', - '[0]', 'goofy', - '[1]', 'is', - '[2]', 'smart', - '[3]', '!!!']) - - self.expect("frame variable *ptr", - substrs=['size=4', - '[0]', 'goofy', - '[1]', 'is', - '[2]', 'smart', - '[3]', '!!!']) - + self.expect( + "frame variable ref", + substrs=[ + "size=4", + "[0]", + "goofy", + "[1]", + "is", + "[2]", + "smart", + "[3]", + "!!!", + ], + ) + + self.expect( + "frame variable *ptr", + substrs=[ + "size=4", + "[0]", + "goofy", + "[1]", + "is", + "[2]", + "smart", + "[3]", + "!!!", + ], + ) + @add_test_categories(["libstdcxx"]) def test_with_run_command_libstdcpp(self): self.do_test_with_run_command(USE_LIBSTDCPP) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/list/loop/TestDataFormatterGenericListLoop.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/list/loop/TestDataFormatterGenericListLoop.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/list/loop/TestDataFormatterGenericListLoop.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/list/loop/TestDataFormatterGenericListLoop.py @@ -4,7 +4,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -13,6 +12,7 @@ USE_LIBSTDCPP = "USE_LIBSTDCPP" USE_LIBCPP = "USE_LIBCPP" + class GenericListDataFormatterTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True @@ -24,43 +24,39 @@ file_spec = lldb.SBFileSpec("main.cpp", False) breakpoint1 = target.BreakpointCreateBySourceRegex( - '// Set break point at this line.', file_spec) + "// Set break point at this line.", file_spec + ) self.assertTrue(breakpoint1 and breakpoint1.IsValid()) breakpoint2 = target.BreakpointCreateBySourceRegex( - '// Set second break point at this line.', file_spec) + "// Set second break point at this line.", file_spec + ) self.assertTrue(breakpoint2 and breakpoint2.IsValid()) # Run the program, it should stop at breakpoint 1. - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) self.assertEqual( - len(lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint1)), 1) + len(lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint1)), 1 + ) # verify our list is displayed correctly self.expect( "frame variable numbers_list", - substrs=[ - '[0] = 1', - '[1] = 2', - '[2] = 3', - '[3] = 4', - '[5] = 6']) + substrs=["[0] = 1", "[1] = 2", "[2] = 3", "[3] = 4", "[5] = 6"], + ) # Continue to breakpoint 2. process.Continue() self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) self.assertEqual( - len(lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint2)), 1) + len(lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint2)), 1 + ) # The list is now inconsistent. However, we should be able to get the first three # elements at least (and most importantly, not crash). self.expect( - "frame variable numbers_list", - substrs=[ - '[0] = 1', - '[1] = 2', - '[2] = 3']) + "frame variable numbers_list", substrs=["[0] = 1", "[1] = 2", "[2] = 3"] + ) # Run to completion. process.Continue() @@ -72,4 +68,4 @@ @add_test_categories(["libc++"]) def test_with_run_command_libcpp(self): - self.do_test_with_run_command(USE_LIBCPP) \ No newline at end of file + self.do_test_with_run_command(USE_LIBCPP) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/multimap/TestDataFormatterGenericMultiMap.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/multimap/TestDataFormatterGenericMultiMap.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/multimap/TestDataFormatterGenericMultiMap.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/multimap/TestDataFormatterGenericMultiMap.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * @@ -13,11 +12,11 @@ USE_LIBSTDCPP = "USE_LIBSTDCPP" USE_LIBCPP = "USE_LIBCPP" -class GenericMultiMapDataFormatterTestCase(TestBase): +class GenericMultiMapDataFormatterTestCase(TestBase): def setUp(self): TestBase.setUp(self) - self.namespace = 'std' + self.namespace = "std" def findVariable(self, name): var = self.frame().FindVariable(name) @@ -35,7 +34,9 @@ for i in range(size): child = var.GetChildAtIndex(i) children.append(ValueCheck(value=child.GetValue())) - self.expect_var_path(var_name, type=self.getVariableType(var_name), children=children) + self.expect_var_path( + var_name, type=self.getVariableType(var_name), children=children + ) def do_test_with_run_command(self, stdlib_type): """Test that that file and class static variables display correctly.""" @@ -44,25 +45,27 @@ bkpt = self.target().FindBreakpointByID( lldbutil.run_break_set_by_source_regexp( - self, "Set break point at this line.")) + self, "Set break point at this line." + ) + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -70,76 +73,85 @@ multimap = self.namespace + "::multimap" # We expect that in some malformed cases the map shows size 0 - self.expect('frame variable corrupt_map', - substrs=[multimap, 'size=0', - '{}']) + self.expect("frame variable corrupt_map", substrs=[multimap, "size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable ii', - substrs=[multimap, 'size=0', - '{}']) + self.expect("frame variable ii", substrs=[multimap, "size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect( - 'frame variable ii', + "frame variable ii", substrs=[ multimap, - 'size=2', - '[0] = (first = 0, second = 0)', - '[1] = (first = 1, second = 1)', - ]) + "size=2", + "[0] = (first = 0, second = 0)", + "[1] = (first = 1, second = 1)", + ], + ) self.check("ii", 2) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable ii', - substrs=[multimap, 'size=4', - '[2] = ', - 'first = 2', - 'second = 0', - '[3] = ', - 'first = 3', - 'second = 1']) + self.expect( + "frame variable ii", + substrs=[ + multimap, + "size=4", + "[2] = ", + "first = 2", + "second = 0", + "[3] = ", + "first = 3", + "second = 1", + ], + ) self.check("ii", 4) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect("frame variable ii", - substrs=[multimap, 'size=8', - '[5] = ', - 'first = 5', - 'second = 0', - '[7] = ', - 'first = 7', - 'second = 1']) + self.expect( + "frame variable ii", + substrs=[ + multimap, + "size=8", + "[5] = ", + "first = 5", + "second = 0", + "[7] = ", + "first = 7", + "second = 1", + ], + ) self.check("ii", 8) - self.expect("expression ii", - substrs=[multimap, 'size=8', - '[5] = ', - 'first = 5', - 'second = 0', - '[7] = ', - 'first = 7', - 'second = 1']) + self.expect( + "expression ii", + substrs=[ + multimap, + "size=8", + "[5] = ", + "first = 5", + "second = 0", + "[7] = ", + "first = 7", + "second = 1", + ], + ) # check access-by-index - self.expect("frame variable ii[0]", - substrs=['first = 0', - 'second = 0']) - self.expect("frame variable ii[3]", - substrs=['first =', - 'second =']) + self.expect("frame variable ii[0]", substrs=["first = 0", "second = 0"]) + self.expect("frame variable ii[3]", substrs=["first =", "second ="]) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("ii").MightHaveChildren(), - "ii.MightHaveChildren() says False for non empty!") + "ii.MightHaveChildren() says False for non empty!", + ) # check that the expression parser does not make use of # synthetic children instead of running code @@ -151,21 +163,16 @@ lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable ii', - substrs=[multimap, 'size=0', - '{}']) + self.expect("frame variable ii", substrs=[multimap, "size=0", "{}"]) - self.expect('frame variable si', - substrs=[multimap, 'size=0', - '{}']) + self.expect("frame variable si", substrs=[multimap, "size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable si', - substrs=[multimap, 'size=1', - '[0] = ', - 'first = \"zero\"', - 'second = 0']) + self.expect( + "frame variable si", + substrs=[multimap, "size=1", "[0] = ", 'first = "zero"', "second = 0"], + ) lldbutil.continue_to_breakpoint(self.process(), bkpt) @@ -173,30 +180,34 @@ "frame variable si", substrs=[ multimap, - 'size=4', + "size=4", '[0] = (first = "one", second = 1)', '[1] = (first = "three", second = 3)', '[2] = (first = "two", second = 2)', '[3] = (first = "zero", second = 0)', - ]) + ], + ) - self.expect("expression si", - substrs=[multimap, 'size=4', + self.expect( + "expression si", + substrs=[ + multimap, + "size=4", '[0] = (first = "one", second = 1)', '[1] = (first = "three", second = 3)', '[2] = (first = "two", second = 2)', '[3] = (first = "zero", second = 0)', - ]) + ], + ) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("si").MightHaveChildren(), - "si.MightHaveChildren() says False for non empty!") + "si.MightHaveChildren() says False for non empty!", + ) # check access-by-index - self.expect("frame variable si[0]", - substrs=['first = ', 'one', - 'second = 1']) + self.expect("frame variable si[0]", substrs=["first = ", "one", "second = 1"]) # check that the expression parser does not make use of # synthetic children instead of running code @@ -208,15 +219,11 @@ lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable si', - substrs=[multimap, 'size=0', - '{}']) + self.expect("frame variable si", substrs=[multimap, "size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable is', - substrs=[multimap, 'size=0', - '{}']) + self.expect("frame variable is", substrs=[multimap, "size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) @@ -224,33 +231,34 @@ "frame variable is", substrs=[ multimap, - 'size=4', + "size=4", '[0] = (first = 1, second = "is")', '[1] = (first = 2, second = "smart")', '[2] = (first = 3, second = "!!!")', '[3] = (first = 85, second = "goofy")', - ]) + ], + ) self.expect( "expression is", substrs=[ multimap, - 'size=4', + "size=4", '[0] = (first = 1, second = "is")', '[1] = (first = 2, second = "smart")', '[2] = (first = 3, second = "!!!")', '[3] = (first = 85, second = "goofy")', - ]) + ], + ) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("is").MightHaveChildren(), - "is.MightHaveChildren() says False for non empty!") + "is.MightHaveChildren() says False for non empty!", + ) # check access-by-index - self.expect("frame variable is[0]", - substrs=['first = ', - 'second =']) + self.expect("frame variable is[0]", substrs=["first = ", "second ="]) # check that the expression parser does not make use of # synthetic children instead of running code @@ -262,17 +270,13 @@ lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable is', - substrs=[multimap, 'size=0', - '{}']) + self.expect("frame variable is", substrs=[multimap, "size=0", "{}"]) self.check("is", 0) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable ss', - substrs=[multimap, 'size=0', - '{}']) + self.expect("frame variable ss", substrs=[multimap, "size=0", "{}"]) self.check("ss", 0) @@ -282,11 +286,12 @@ "frame variable ss", substrs=[ multimap, - 'size=3', + "size=3", '[0] = (first = "casa", second = "house")', '[1] = (first = "ciao", second = "hello")', '[2] = (first = "gatto", second = "cat")', - ]) + ], + ) self.check("ss", 3) @@ -294,20 +299,21 @@ "expression ss", substrs=[ multimap, - 'size=3', + "size=3", '[0] = (first = "casa", second = "house")', '[1] = (first = "ciao", second = "hello")', '[2] = (first = "gatto", second = "cat")', - ]) + ], + ) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("ss").MightHaveChildren(), - "ss.MightHaveChildren() says False for non empty!") + "ss.MightHaveChildren() says False for non empty!", + ) # check access-by-index - self.expect("frame variable ss[2]", - substrs=['gatto', 'cat']) + self.expect("frame variable ss[2]", substrs=["gatto", "cat"]) # check that the expression parser does not make use of # synthetic children instead of running code @@ -319,18 +325,16 @@ lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable ss', - substrs=[multimap, 'size=0', - '{}']) + self.expect("frame variable ss", substrs=[multimap, "size=0", "{}"]) self.check("ss", 0) @add_test_categories(["libstdcxx"]) - @skipIf(compiler="clang", compiler_version=['<', '9.0']) + @skipIf(compiler="clang", compiler_version=["<", "9.0"]) def test_with_run_command_libstdcpp(self): self.do_test_with_run_command(USE_LIBSTDCPP) - @skipIf(compiler="clang", compiler_version=['<', '9.0']) + @skipIf(compiler="clang", compiler_version=["<", "9.0"]) @add_test_categories(["libc++"]) def test_with_run_command_libcpp(self): self.do_test_with_run_command(USE_LIBCPP) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/multiset/TestDataFormatterGenericMultiSet.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/multiset/TestDataFormatterGenericMultiSet.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/multiset/TestDataFormatterGenericMultiSet.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/multiset/TestDataFormatterGenericMultiSet.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,11 +11,11 @@ USE_LIBSTDCPP = "USE_LIBSTDCPP" USE_LIBCPP = "USE_LIBCPP" -class GenericMultiSetDataFormatterTestCase(TestBase): +class GenericMultiSetDataFormatterTestCase(TestBase): def setUp(self): TestBase.setUp(self) - self.namespace = 'std' + self.namespace = "std" def findVariable(self, name): var = self.frame().FindVariable(name) @@ -27,7 +26,6 @@ var = self.findVariable(name) return var.GetType().GetDisplayTypeName() - def check(self, var_name, size): var = self.findVariable(var_name) self.assertEqual(var.GetNumChildren(), size) @@ -35,31 +33,33 @@ for i in range(size): child = var.GetChildAtIndex(i) children.append(ValueCheck(value=child.GetValue())) - self.expect_var_path(var_name, type=self.getVariableType(var_name), children=children) + self.expect_var_path( + var_name, type=self.getVariableType(var_name), children=children + ) def do_test_with_run_command(self, stdlib_type): """Test that that file and class static variables display correctly.""" self.build(dictionary={stdlib_type: "1"}) (self.target, process, _, bkpt) = lldbutil.run_to_source_breakpoint( - self, "Set break point at this line.", lldb.SBFileSpec("main.cpp", False)) + self, "Set break point at this line.", lldb.SBFileSpec("main.cpp", False) + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) ii_type = self.getVariableType("ii") - self.assertTrue(ii_type.startswith(self.namespace + "::multiset"), - "Type: " + ii_type) + self.assertTrue( + ii_type.startswith(self.namespace + "::multiset"), "Type: " + ii_type + ) self.expect("frame variable ii", substrs=["size=0", "{}"]) lldbutil.continue_to_breakpoint(process, bkpt) @@ -72,7 +72,9 @@ "[2] = 2", "[3] = 3", "[4] = 4", - "[5] = 5"]) + "[5] = 5", + ], + ) lldbutil.continue_to_breakpoint(process, bkpt) self.check("ii", 7) @@ -83,17 +85,16 @@ lldbutil.continue_to_breakpoint(process, bkpt) self.expect("frame variable ii", substrs=["size=0", "{}"]) ss_type = self.getVariableType("ss") - self.assertTrue(ss_type.startswith(self.namespace + "::multiset"), - "Type: " + ss_type) + self.assertTrue( + ss_type.startswith(self.namespace + "::multiset"), "Type: " + ss_type + ) self.expect("frame variable ss", substrs=["size=0", "{}"]) self.check("ss", 0) lldbutil.continue_to_breakpoint(process, bkpt) self.expect( "frame variable ss", - substrs=[ - "size=2", - '[0] = "a"', - '[1] = "a very long string is right here"']) + substrs=["size=2", '[0] = "a"', '[1] = "a very long string is right here"'], + ) self.check("ss", 2) lldbutil.continue_to_breakpoint(process, bkpt) self.expect( @@ -104,7 +105,8 @@ '[1] = "a very long string is right here"', '[2] = "b"', '[3] = "c"', - ]) + ], + ) self.check("ss", 4) self.expect( "expression ss", @@ -114,7 +116,8 @@ '[1] = "a very long string is right here"', '[2] = "b"', '[3] = "c"', - ]) + ], + ) self.expect("frame variable ss[2]", substrs=[' = "b"']) lldbutil.continue_to_breakpoint(process, bkpt) self.expect( @@ -123,22 +126,24 @@ "size=3", '[0] = "a"', '[1] = "a very long string is right here"', - '[2] = "c"']) + '[2] = "c"', + ], + ) def do_test_ref_and_ptr(self, stdlib_type): """Test that the data formatters work on ref and ptr.""" self.build(dictionary={stdlib_type: "1"}) (self.target, process, _, bkpt) = lldbutil.run_to_source_breakpoint( - self, "Stop here to check by ref and ptr.", - lldb.SBFileSpec("main.cpp", False)) + self, + "Stop here to check by ref and ptr.", + lldb.SBFileSpec("main.cpp", False), + ) # The reference should print just like the value: self.check("ref", 7) - self.expect("frame variable ptr", - substrs=["ptr =", "size=7"]) - self.expect("expr ptr", - substrs=["size=7"]) - + self.expect("frame variable ptr", substrs=["ptr =", "size=7"]) + self.expect("expr ptr", substrs=["size=7"]) + @add_test_categories(["libstdcxx"]) def test_with_run_command_libstdcpp(self): self.do_test_with_run_command(USE_LIBSTDCPP) @@ -146,7 +151,7 @@ @add_test_categories(["libc++"]) def test_with_run_command_libcpp(self): self.do_test_with_run_command(USE_LIBCPP) - + @add_test_categories(["libstdcxx"]) def test_ref_and_ptr_libstdcpp(self): self.do_test_ref_and_ptr(USE_LIBSTDCPP) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/optional/TestDataFormatterGenericOptional.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/optional/TestDataFormatterGenericOptional.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/optional/TestDataFormatterGenericOptional.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/optional/TestDataFormatterGenericOptional.py @@ -6,82 +6,95 @@ USE_LIBSTDCPP = "USE_LIBSTDCPP" USE_LIBCPP = "USE_LIBCPP" -class GenericOptionalDataFormatterTestCase(TestBase): +class GenericOptionalDataFormatterTestCase(TestBase): def do_test_with_run_command(self, stdlib_type): """Test that that file and class static variables display correctly.""" + # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.addTearDownHook(cleanup) self.build(dictionary={stdlib_type: "1"}) self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) bkpt = self.target().FindBreakpointByID( - lldbutil.run_break_set_by_source_regexp( - self, "break here")) + lldbutil.run_break_set_by_source_regexp(self, "break here") + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) - self.runCmd( "frame variable has_optional" ) + self.runCmd("frame variable has_optional") output = self.res.GetOutput() ## The variable has_optional tells us if the test program ## detected we have a sufficient libc++ version to support optional ## false means we do not and therefore should skip the test - if output.find("(bool) has_optional = false") != -1 : - self.skipTest( "Optional not supported" ) + if output.find("(bool) has_optional = false") != -1: + self.skipTest("Optional not supported") lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect("frame variable number_not_engaged", - substrs=['Has Value=false']) - - self.expect("frame variable number_engaged", - substrs=['Has Value=true', - 'Value = 42', - '}']) - - self.expect("frame var numbers", - substrs=['(optional_int_vect) numbers = Has Value=true {', - 'Value = size=4 {', - '[0] = 1', - '[1] = 2', - '[2] = 3', - '[3] = 4', - '}', - '}']) - - self.expect("frame var ostring", - substrs=['(optional_string) ostring = Has Value=true {', - 'Value = "hello"', - '}']) + self.expect("frame variable number_not_engaged", substrs=["Has Value=false"]) + + self.expect( + "frame variable number_engaged", + substrs=["Has Value=true", "Value = 42", "}"], + ) + + self.expect( + "frame var numbers", + substrs=[ + "(optional_int_vect) numbers = Has Value=true {", + "Value = size=4 {", + "[0] = 1", + "[1] = 2", + "[2] = 3", + "[3] = 4", + "}", + "}", + ], + ) + + self.expect( + "frame var ostring", + substrs=[ + "(optional_string) ostring = Has Value=true {", + 'Value = "hello"', + "}", + ], + ) @add_test_categories(["libc++"]) ## Clang 7.0 is the oldest Clang that can reliably parse newer libc++ versions ## with -std=c++17. - @skipIf(oslist=no_match(["macosx"]), compiler="clang", compiler_version=['<', '7.0']) + @skipIf( + oslist=no_match(["macosx"]), compiler="clang", compiler_version=["<", "7.0"] + ) ## We are skipping gcc version less that 5.1 since this test requires -std=c++17 - @skipIf(compiler="gcc", compiler_version=['<', '5.1']) + @skipIf(compiler="gcc", compiler_version=["<", "5.1"]) def test_with_run_command_libcpp(self): self.do_test_with_run_command(USE_LIBCPP) @add_test_categories(["libstdcxx"]) ## Clang 7.0 is the oldest Clang that can reliably parse newer libc++ versions ## with -std=c++17. - @skipIf(compiler="clang", compiler_version=['<', '7.0']) + @skipIf(compiler="clang", compiler_version=["<", "7.0"]) ## We are skipping gcc version less that 5.1 since this test requires -std=c++17 - @skipIf(compiler="gcc", compiler_version=['<', '5.1']) + @skipIf(compiler="gcc", compiler_version=["<", "5.1"]) def test_with_run_command_libstdcpp(self): self.do_test_with_run_command(USE_LIBSTDCPP) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/set/TestDataFormatterGenericSet.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/set/TestDataFormatterGenericSet.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/set/TestDataFormatterGenericSet.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/set/TestDataFormatterGenericSet.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,11 +11,11 @@ USE_LIBSTDCPP = "USE_LIBSTDCPP" USE_LIBCPP = "USE_LIBCPP" -class GenericSetDataFormatterTestCase(TestBase): +class GenericSetDataFormatterTestCase(TestBase): def setUp(self): TestBase.setUp(self) - self.namespace = 'std' + self.namespace = "std" def findVariable(self, name): var = self.frame().FindVariable(name) @@ -34,47 +33,50 @@ for i in range(size): child = var.GetChildAtIndex(i) children.append(ValueCheck(value=child.GetValue())) - self.expect_var_path(var_name, type=self.getVariableType(var_name), children=children) - + self.expect_var_path( + var_name, type=self.getVariableType(var_name), children=children + ) - - def do_test_with_run_command(self,stdlib_type): + def do_test_with_run_command(self, stdlib_type): """Test that that file and class static variables display correctly.""" self.build(dictionary={stdlib_type: "1"}) (self.target, process, _, bkpt) = lldbutil.run_to_source_breakpoint( - self, "Set break point at this line.", lldb.SBFileSpec("main.cpp", False)) + self, "Set break point at this line.", lldb.SBFileSpec("main.cpp", False) + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) ii_type = self.getVariableType("ii") - self.assertTrue(ii_type.startswith(self.namespace + "::set"), - "Type: " + ii_type) + self.assertTrue( + ii_type.startswith(self.namespace + "::set"), "Type: " + ii_type + ) self.expect("frame variable ii", substrs=["size=0", "{}"]) lldbutil.continue_to_breakpoint(process, bkpt) self.expect( "frame variable ii", - substrs=["size=6", - "[0] = 0", - "[1] = 1", - "[2] = 2", - "[3] = 3", - "[4] = 4", - "[5] = 5"]) + substrs=[ + "size=6", + "[0] = 0", + "[1] = 1", + "[2] = 2", + "[3] = 3", + "[4] = 4", + "[5] = 5", + ], + ) lldbutil.continue_to_breakpoint(process, bkpt) - self.check("ii",7) + self.check("ii", 7) lldbutil.continue_to_breakpoint(process, bkpt) self.expect("frame variable ii", substrs=["size=0", "{}"]) @@ -82,42 +84,51 @@ self.expect("frame variable ii", substrs=["size=0", "{}"]) ss_type = self.getVariableType("ss") - self.assertTrue(ii_type.startswith(self.namespace + "::set"), - "Type: " + ss_type) + self.assertTrue( + ii_type.startswith(self.namespace + "::set"), "Type: " + ss_type + ) self.expect("frame variable ss", substrs=["size=0", "{}"]) lldbutil.continue_to_breakpoint(process, bkpt) self.expect( "frame variable ss", - substrs=["size=2", - '[0] = "a"', - '[1] = "a very long string is right here"']) + substrs=["size=2", '[0] = "a"', '[1] = "a very long string is right here"'], + ) lldbutil.continue_to_breakpoint(process, bkpt) self.expect( "frame variable ss", - substrs=["size=4", - '[0] = "a"', - '[1] = "a very long string is right here"', - '[2] = "b"', - '[3] = "c"']) + substrs=[ + "size=4", + '[0] = "a"', + '[1] = "a very long string is right here"', + '[2] = "b"', + '[3] = "c"', + ], + ) self.expect( "expression ss", - substrs=["size=4", - '[0] = "a"', - '[1] = "a very long string is right here"', - '[2] = "b"', - '[3] = "c"']) + substrs=[ + "size=4", + '[0] = "a"', + '[1] = "a very long string is right here"', + '[2] = "b"', + '[3] = "c"', + ], + ) self.expect("frame variable ss[2]", substrs=[' = "b"']) lldbutil.continue_to_breakpoint(process, bkpt) self.expect( "frame variable ss", - substrs=["size=3", - '[0] = "a"', - '[1] = "a very long string is right here"', - '[2] = "c"']) - self.check("ss",3) - - @add_test_categories(["libstdcxx"]) + substrs=[ + "size=3", + '[0] = "a"', + '[1] = "a very long string is right here"', + '[2] = "c"', + ], + ) + self.check("ss", 3) + + @add_test_categories(["libstdcxx"]) def test_with_run_command_libstdcpp(self): self.do_test_with_run_command(USE_LIBSTDCPP) @@ -125,26 +136,25 @@ def test_with_run_command_libcpp(self): self.do_test_with_run_command(USE_LIBCPP) - - def do_test_ref_and_ptr(self,stdlib_type): + def do_test_ref_and_ptr(self, stdlib_type): """Test that the data formatters work on ref and ptr.""" self.build() (self.target, process, _, bkpt) = lldbutil.run_to_source_breakpoint( - self, "Stop here to check by ref and ptr.", - lldb.SBFileSpec("main.cpp", False)) + self, + "Stop here to check by ref and ptr.", + lldb.SBFileSpec("main.cpp", False), + ) # The reference should print just like the value: self.check("ref", 7) self.check("ptr", 7) - self.expect("frame variable ptr", - substrs=["ptr =", "size=7"]) - self.expect("expr ptr", - substrs=["size=7"]) + self.expect("frame variable ptr", substrs=["ptr =", "size=7"]) + self.expect("expr ptr", substrs=["size=7"]) - @add_test_categories(["libstdcxx"]) + @add_test_categories(["libstdcxx"]) def test_ref_and_ptr_libstdcpp(self): self.do_test_ref_and_ptr(USE_LIBSTDCPP) - + @add_test_categories(["libc++"]) def test_ref_and_ptr_libcpp(self): self.do_test_ref_and_ptr(USE_LIBCPP) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/unordered/TestDataFormatterGenericUnordered.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/unordered/TestDataFormatterGenericUnordered.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/unordered/TestDataFormatterGenericUnordered.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/unordered/TestDataFormatterGenericUnordered.py @@ -5,40 +5,36 @@ USE_LIBSTDCPP = "USE_LIBSTDCPP" USE_LIBCPP = "USE_LIBCPP" -class GenericUnorderedDataFormatterTestCase(TestBase): +class GenericUnorderedDataFormatterTestCase(TestBase): def setUp(self): TestBase.setUp(self) - self.namespace = 'std' - + self.namespace = "std" def do_test_with_run_command(self, stdlib_type): self.build(dictionary={stdlib_type: "1"}) self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp( - self, "Set break point at this line.") + lldbutil.run_break_set_by_source_regexp(self, "Set break point at this line.") self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) - self.runCmd( - 'settings set auto-one-line-summaries true', - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd("settings set auto-one-line-summaries true", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -47,40 +43,83 @@ # We check here that the map shows 0 children even with corrupt data. self.look_for_content_and_continue( - "corrupt_map", ['%s::unordered_map' % - ns, 'size=0 {}']) + "corrupt_map", ["%s::unordered_map" % ns, "size=0 {}"] + ) # Ensure key/value children, not wrapped in a layer. # This regex depends on auto-one-line-summaries. - self.runCmd('settings set auto-one-line-summaries false') - children_are_key_value = r'\[0\] = \{\s*first = ' + self.runCmd("settings set auto-one-line-summaries false") + children_are_key_value = r"\[0\] = \{\s*first = " self.look_for_content_and_continue( - "map", ['%s::unordered_map' % ns, - children_are_key_value, - 'size=5 {', 'hello', 'world', 'this', 'is', 'me']) + "map", + [ + "%s::unordered_map" % ns, + children_are_key_value, + "size=5 {", + "hello", + "world", + "this", + "is", + "me", + ], + ) self.look_for_content_and_continue( - "mmap", ['%s::unordered_multimap' % ns, - children_are_key_value, - 'size=6 {', 'first = 3', 'second = "this"', - 'first = 2', 'second = "hello"']) + "mmap", + [ + "%s::unordered_multimap" % ns, + children_are_key_value, + "size=6 {", + "first = 3", + 'second = "this"', + "first = 2", + 'second = "hello"', + ], + ) self.look_for_content_and_continue( - "iset", ['%s::unordered_set' % - ns, 'size=5 {', '\[\d\] = 5', '\[\d\] = 3', '\[\d\] = 2']) + "iset", + [ + "%s::unordered_set" % ns, + "size=5 {", + "\[\d\] = 5", + "\[\d\] = 3", + "\[\d\] = 2", + ], + ) self.look_for_content_and_continue( - "sset", ['%s::unordered_set' % ns, 'size=5 {', '\[\d\] = "is"', '\[\d\] = "world"', - '\[\d\] = "hello"']) + "sset", + [ + "%s::unordered_set" % ns, + "size=5 {", + '\[\d\] = "is"', + '\[\d\] = "world"', + '\[\d\] = "hello"', + ], + ) self.look_for_content_and_continue( - "imset", ['%s::unordered_multiset' % ns, 'size=6 {', '(\[\d\] = 3(\\n|.)+){3}', - '\[\d\] = 2', '\[\d\] = 1']) + "imset", + [ + "%s::unordered_multiset" % ns, + "size=6 {", + "(\[\d\] = 3(\\n|.)+){3}", + "\[\d\] = 2", + "\[\d\] = 1", + ], + ) self.look_for_content_and_continue( - "smset", ['%s::unordered_multiset' % ns, 'size=5 {', '(\[\d\] = "is"(\\n|.)+){2}', - '(\[\d\] = "world"(\\n|.)+){2}']) + "smset", + [ + "%s::unordered_multiset" % ns, + "size=5 {", + '(\[\d\] = "is"(\\n|.)+){2}', + '(\[\d\] = "world"(\\n|.)+){2}', + ], + ) def look_for_content_and_continue(self, var_name, patterns): self.expect(("frame variable %s" % var_name), patterns=patterns) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/TestLibCxxAtomic.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/TestLibCxxAtomic.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/TestLibCxxAtomic.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/TestLibCxxAtomic.py @@ -9,7 +9,6 @@ class LibCxxAtomicTestCase(TestBase): - def get_variable(self, name): var = self.frame().FindVariable(name) var.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) @@ -25,20 +24,25 @@ bkpt = self.target().FindBreakpointByID( lldbutil.run_break_set_by_source_regexp( - self, "Set break point at this line.")) + self, "Set break point at this line." + ) + ) self.runCmd("run", RUN_SUCCEEDED) lldbutil.skip_if_library_missing( - self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + self, self.target(), lldbutil.PrintableRegex("libc\+\+") + ) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) - s_atomic = self.get_variable('s') - i_atomic = self.get_variable('i') + s_atomic = self.get_variable("s") + i_atomic = self.get_variable("i") if self.TraceOn(): print(s_atomic) @@ -53,15 +57,13 @@ self.assertEqual(i.GetValueAsUnsigned(0), 5, "i == 5") self.assertEqual(s.GetNumChildren(), 2, "s has two children") - self.assertEqual( - s.GetChildAtIndex(0).GetValueAsUnsigned(0), 1, - "s.x == 1") - self.assertEqual( - s.GetChildAtIndex(1).GetValueAsUnsigned(0), 2, - "s.y == 2") + self.assertEqual(s.GetChildAtIndex(0).GetValueAsUnsigned(0), 1, "s.x == 1") + self.assertEqual(s.GetChildAtIndex(1).GetValueAsUnsigned(0), 2, "s.y == 2") # Try printing the child that points to its own parent object. # This should just treat the atomic pointer as a normal pointer. self.expect("frame var p.child", substrs=["Value = 0x"]) self.expect("frame var p", substrs=["parent = {", "Value = 0x", "}"]) - self.expect("frame var p.child.parent", substrs=["p.child.parent = {\n Value = 0x"]) + self.expect( + "frame var p.child.parent", substrs=["p.child.parent = {\n Value = 0x"] + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/deque/TestDataFormatterLibcxxDeque.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/deque/TestDataFormatterLibcxxDeque.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/deque/TestDataFormatterLibcxxDeque.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/deque/TestDataFormatterLibcxxDeque.py @@ -7,47 +7,54 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class LibcxxDequeDataFormatterTestCase(TestBase): +class LibcxxDequeDataFormatterTestCase(TestBase): def check_numbers(self, var_name): - self.expect("frame variable " + var_name, - substrs=[var_name + ' = size=7', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '[4] = 12345', - '[5] = 123456', - '[6] = 1234567', - '}']) + self.expect( + "frame variable " + var_name, + substrs=[ + var_name + " = size=7", + "[0] = 1", + "[1] = 12", + "[2] = 123", + "[3] = 1234", + "[4] = 12345", + "[5] = 123456", + "[6] = 1234567", + "}", + ], + ) - self.expect_expr(var_name, result_summary="size=7", result_children=[ - ValueCheck(value="1"), - ValueCheck(value="12"), - ValueCheck(value="123"), - ValueCheck(value="1234"), - ValueCheck(value="12345"), - ValueCheck(value="123456"), - ValueCheck(value="1234567"), - ]) + self.expect_expr( + var_name, + result_summary="size=7", + result_children=[ + ValueCheck(value="1"), + ValueCheck(value="12"), + ValueCheck(value="123"), + ValueCheck(value="1234"), + ValueCheck(value="12345"), + ValueCheck(value="123456"), + ValueCheck(value="1234567"), + ], + ) @add_test_categories(["libc++"]) def test_with_run_command(self): """Test basic formatting of std::deque""" self.build() (self.target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, "break here", lldb.SBFileSpec("main.cpp", False)) + self, "break here", lldb.SBFileSpec("main.cpp", False) + ) - self.expect("frame variable numbers", - substrs=['numbers = size=0']) + self.expect("frame variable numbers", substrs=["numbers = size=0"]) lldbutil.continue_to_breakpoint(process, bkpt) # first value added - self.expect("frame variable numbers", - substrs=['numbers = size=1', - '[0] = 1', - '}']) + self.expect( + "frame variable numbers", substrs=["numbers = size=1", "[0] = 1", "}"] + ) # add remaining values lldbutil.continue_to_breakpoint(process, bkpt) @@ -57,19 +64,19 @@ # clear out the deque lldbutil.continue_to_breakpoint(process, bkpt) - self.expect("frame variable numbers", - substrs=['numbers = size=0']) + self.expect("frame variable numbers", substrs=["numbers = size=0"]) @add_test_categories(["libc++"]) def test_ref_and_ptr(self): """Test formatting of std::deque& and std::deque*""" self.build() (self.target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, "stop here", lldb.SBFileSpec("main.cpp", False)) + self, "stop here", lldb.SBFileSpec("main.cpp", False) + ) # The reference should display the same was as the value did self.check_numbers("ref") # The pointer should just show the right number of elements: - self.expect("frame variable ptr", substrs=['ptr =', ' size=7']) - self.expect("expression ptr", substrs=['$', 'size=7']) + self.expect("frame variable ptr", substrs=["ptr =", " size=7"]) + self.expect("expression ptr", substrs=["$", "size=7"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/function/TestLibCxxFunction.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/function/TestLibCxxFunction.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/function/TestLibCxxFunction.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/function/TestLibCxxFunction.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,24 +10,29 @@ class LibCxxFunctionTestCase(TestBase): - # Run frame var for a variable twice. Verify we do not hit the cache # the first time but do the second time. - def run_frame_var_check_cache_use(self, variable, result_to_match, skip_find_function=False): + def run_frame_var_check_cache_use( + self, variable, result_to_match, skip_find_function=False + ): self.runCmd("log timers reset") - self.expect("frame variable " + variable, - substrs=[variable + " = " + result_to_match]) + self.expect( + "frame variable " + variable, substrs=[variable + " = " + result_to_match] + ) if not skip_find_function: - self.expect("log timers dump", - substrs=["lldb_private::CompileUnit::FindFunction"]) + self.expect( + "log timers dump", substrs=["lldb_private::CompileUnit::FindFunction"] + ) self.runCmd("log timers reset") - self.expect("frame variable " + variable, - substrs=[variable + " = " + result_to_match]) - self.expect("log timers dump", - matching=False, - substrs=["lldb_private::CompileUnit::FindFunction"]) - + self.expect( + "frame variable " + variable, substrs=[variable + " = " + result_to_match] + ) + self.expect( + "log timers dump", + matching=False, + substrs=["lldb_private::CompileUnit::FindFunction"], + ) @add_test_categories(["libc++"]) def test(self): @@ -38,33 +42,43 @@ bkpt = self.target().FindBreakpointByID( lldbutil.run_break_set_by_source_regexp( - self, "Set break point at this line.")) + self, "Set break point at this line." + ) + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) - self.run_frame_var_check_cache_use("foo2_f", "Lambda in File main.cpp at Line 22") + self.run_frame_var_check_cache_use( + "foo2_f", "Lambda in File main.cpp at Line 22" + ) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.run_frame_var_check_cache_use("add_num2_f", "Lambda in File main.cpp at Line 13") + self.run_frame_var_check_cache_use( + "add_num2_f", "Lambda in File main.cpp at Line 13" + ) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.run_frame_var_check_cache_use("f2", "Lambda in File main.cpp at Line 35") - self.run_frame_var_check_cache_use("f3", "Lambda in File main.cpp at Line 39", True) + self.run_frame_var_check_cache_use( + "f3", "Lambda in File main.cpp at Line 39", True + ) # TODO reenable this case when std::function formatter supports # general callable object case. - #self.run_frame_var_check_cache_use("f4", "Function in File main.cpp at Line 8") + # self.run_frame_var_check_cache_use("f4", "Function in File main.cpp at Line 8") # These cases won't hit the cache at all but also don't require # an expensive lookup. - self.expect("frame variable f1", - substrs=['f1 = Function = foo(int, int)']) + self.expect("frame variable f1", substrs=["f1 = Function = foo(int, int)"]) - self.expect("frame variable f5", - substrs=['f5 = Function = Bar::add_num(int) const']) + self.expect( + "frame variable f5", substrs=["f5 = Function = Bar::add_num(int) const"] + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class InitializerListTestCase(TestBase): - @add_test_categories(["libc++"]) def test(self): """Test that that file and class static variables display correctly.""" @@ -20,20 +18,27 @@ bkpt = self.target().FindBreakpointByID( lldbutil.run_break_set_by_source_regexp( - self, "Set break point at this line.")) + self, "Set break point at this line." + ) + ) self.runCmd("run", RUN_SUCCEEDED) lldbutil.skip_if_library_missing( - self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + self, self.target(), lldbutil.PrintableRegex("libc\+\+") + ) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) - - self.expect("frame variable ili", substrs=['[1] = 2', '[4] = 5']) - self.expect("frame variable ils", substrs=[ - '[4] = "surprise it is a long string!! yay!!"']) - - self.expect('image list', substrs=self.getLibcPlusPlusLibs()) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) + + self.expect("frame variable ili", substrs=["[1] = 2", "[4] = 5"]) + self.expect( + "frame variable ils", + substrs=['[4] = "surprise it is a long string!! yay!!"'], + ) + + self.expect("image list", substrs=self.getLibcPlusPlusLibs()) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,13 +10,12 @@ class LibcxxIteratorDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') - self.namespace = 'std' + self.line = line_number("main.cpp", "// Set break point at this line.") + self.namespace = "std" @add_test_categories(["libc++"]) def test_with_run_command(self): @@ -26,45 +24,38 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=-1) + self, "main.cpp", self.line, num_expected_locations=-1 + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect('frame variable ivI', substrs=['item = 3']) - self.expect('expr ivI', substrs=['item = 3']) + self.expect("frame variable ivI", substrs=["item = 3"]) + self.expect("expr ivI", substrs=["item = 3"]) - self.expect( - 'frame variable iimI', - substrs=[ - 'first = 43981', - 'second = 61681']) - self.expect('expr iimI', substrs=['first = 43981', 'second = 61681']) + self.expect("frame variable iimI", substrs=["first = 43981", "second = 61681"]) + self.expect("expr iimI", substrs=["first = 43981", "second = 61681"]) - self.expect( - 'frame variable simI', - substrs=[ - 'first = "world"', - 'second = 42']) - self.expect('expr simI', substrs=['first = "world"', 'second = 42']) + self.expect("frame variable simI", substrs=['first = "world"', "second = 42"]) + self.expect("expr simI", substrs=['first = "world"', "second = 42"]) - self.expect('frame variable svI', substrs=['item = "hello"']) - self.expect('expr svI', substrs=['item = "hello"']) + self.expect("frame variable svI", substrs=['item = "hello"']) + self.expect("expr svI", substrs=['item = "hello"']) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,15 +10,16 @@ class LibcxxMapDataFormatterTestCase(TestBase): - def setUp(self): TestBase.setUp(self) - ns = 'ndk' if lldbplatformutil.target_is_android() else '' - self.namespace = 'std' + ns = "ndk" if lldbplatformutil.target_is_android() else "" + self.namespace = "std" def check_pair(self, first_value, second_value): - pair_children = [ValueCheck(name="first", value=first_value), - ValueCheck(name="second", value=second_value)] + pair_children = [ + ValueCheck(name="first", value=first_value), + ValueCheck(name="second", value=second_value), + ] return ValueCheck(children=pair_children) @add_test_categories(["libc++"]) @@ -30,25 +30,27 @@ bkpt = self.target().FindBreakpointByID( lldbutil.run_break_set_by_source_regexp( - self, "Set break point at this line.")) + self, "Set break point at this line." + ) + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -56,80 +58,101 @@ ns = self.namespace self.expect_expr("ii", result_summary="size=0", result_children=[]) - self.expect('frame var ii', - substrs=['%s::map' % ns, - 'size=0', - '{}']) + self.expect("frame var ii", substrs=["%s::map" % ns, "size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect_expr("ii", result_summary="size=2", result_children=[ - self.check_pair("0", "0"), - self.check_pair("1", "1") - ]) + self.expect_expr( + "ii", + result_summary="size=2", + result_children=[self.check_pair("0", "0"), self.check_pair("1", "1")], + ) - self.expect('frame variable ii', - substrs=['%s::map' % ns, 'size=2', - '[0] = ', - 'first = 0', - 'second = 0', - '[1] = ', - 'first = 1', - 'second = 1']) + self.expect( + "frame variable ii", + substrs=[ + "%s::map" % ns, + "size=2", + "[0] = ", + "first = 0", + "second = 0", + "[1] = ", + "first = 1", + "second = 1", + ], + ) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable ii', - substrs=['%s::map' % ns, 'size=4', - '[2] = ', - 'first = 2', - 'second = 0', - '[3] = ', - 'first = 3', - 'second = 1']) + self.expect( + "frame variable ii", + substrs=[ + "%s::map" % ns, + "size=4", + "[2] = ", + "first = 2", + "second = 0", + "[3] = ", + "first = 3", + "second = 1", + ], + ) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect("expression ii", - substrs=['%s::map' % ns, 'size=8', - '[5] = ', - 'first = 5', - 'second = 0', - '[7] = ', - 'first = 7', - 'second = 1']) - - self.expect("frame var ii", - substrs=['%s::map' % ns, 'size=8', - '[5] = ', - 'first = 5', - 'second = 0', - '[7] = ', - 'first = 7', - 'second = 1']) + self.expect( + "expression ii", + substrs=[ + "%s::map" % ns, + "size=8", + "[5] = ", + "first = 5", + "second = 0", + "[7] = ", + "first = 7", + "second = 1", + ], + ) + + self.expect( + "frame var ii", + substrs=[ + "%s::map" % ns, + "size=8", + "[5] = ", + "first = 5", + "second = 0", + "[7] = ", + "first = 7", + "second = 1", + ], + ) # check access-by-index - self.expect("frame variable ii[0]", - substrs=['first = 0', - 'second = 0']) - self.expect("frame variable ii[3]", - substrs=['first =', - 'second =']) + self.expect("frame variable ii[0]", substrs=["first = 0", "second = 0"]) + self.expect("frame variable ii[3]", substrs=["first =", "second ="]) # (Non-)const key/val iterators - self.expect_expr("it", result_children=[ - ValueCheck(name="first", value="0"), - ValueCheck(name="second", value="0") - ]) - self.expect_expr("const_it", result_children=[ - ValueCheck(name="first", value="0"), - ValueCheck(name="second", value="0") - ]) + self.expect_expr( + "it", + result_children=[ + ValueCheck(name="first", value="0"), + ValueCheck(name="second", value="0"), + ], + ) + self.expect_expr( + "const_it", + result_children=[ + ValueCheck(name="first", value="0"), + ValueCheck(name="second", value="0"), + ], + ) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("ii").MightHaveChildren(), - "ii.MightHaveChildren() says False for non empty!") + "ii.MightHaveChildren() says False for non empty!", + ) # check that the expression parser does not make use of # synthetic children instead of running code @@ -141,55 +164,57 @@ self.runCmd("continue") - self.expect('frame variable ii', - substrs=['%s::map' % ns, 'size=0', - '{}']) + self.expect("frame variable ii", substrs=["%s::map" % ns, "size=0", "{}"]) - self.expect('frame variable si', - substrs=['%s::map' % ns, 'size=0', - '{}']) + self.expect("frame variable si", substrs=["%s::map" % ns, "size=0", "{}"]) self.runCmd("continue") - self.expect('frame variable si', - substrs=['%s::map' % ns, 'size=1', - '[0] = ', - 'first = \"zero\"', - 'second = 0']) + self.expect( + "frame variable si", + substrs=[ + "%s::map" % ns, + "size=1", + "[0] = ", + 'first = "zero"', + "second = 0", + ], + ) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect( "frame variable si", substrs=[ - '%s::map' % ns, - 'size=4', + "%s::map" % ns, + "size=4", '[0] = (first = "one", second = 1)', '[1] = (first = "three", second = 3)', '[2] = (first = "two", second = 2)', '[3] = (first = "zero", second = 0)', - ]) + ], + ) self.expect( "expression si", substrs=[ - '%s::map' % ns, - 'size=4', + "%s::map" % ns, + "size=4", '[0] = (first = "one", second = 1)', '[1] = (first = "three", second = 3)', '[2] = (first = "two", second = 2)', '[3] = (first = "zero", second = 0)', - ]) + ], + ) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("si").MightHaveChildren(), - "si.MightHaveChildren() says False for non empty!") + "si.MightHaveChildren() says False for non empty!", + ) # check access-by-index - self.expect("frame variable si[0]", - substrs=['first = ', 'one', - 'second = 1']) + self.expect("frame variable si[0]", substrs=["first = ", "one", "second = 1"]) # check that the expression parser does not make use of # synthetic children instead of running code @@ -201,49 +226,46 @@ lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable si', - substrs=['%s::map' % ns, 'size=0', - '{}']) + self.expect("frame variable si", substrs=["%s::map" % ns, "size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable is', - substrs=['%s::map' % ns, 'size=0', - '{}']) + self.expect("frame variable is", substrs=["%s::map" % ns, "size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect( "frame variable is", substrs=[ - '%s::map' % ns, - 'size=4', + "%s::map" % ns, + "size=4", '[0] = (first = 1, second = "is")', '[1] = (first = 2, second = "smart")', '[2] = (first = 3, second = "!!!")', '[3] = (first = 85, second = "goofy")', - ]) + ], + ) self.expect( "expression is", substrs=[ - '%s::map' % ns, - 'size=4', + "%s::map" % ns, + "size=4", '[0] = (first = 1, second = "is")', '[1] = (first = 2, second = "smart")', '[2] = (first = 3, second = "!!!")', '[3] = (first = 85, second = "goofy")', - ]) + ], + ) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("is").MightHaveChildren(), - "is.MightHaveChildren() says False for non empty!") + "is.MightHaveChildren() says False for non empty!", + ) # check access-by-index - self.expect("frame variable is[0]", - substrs=['first = ', - 'second =']) + self.expect("frame variable is[0]", substrs=["first = ", "second ="]) # check that the expression parser does not make use of # synthetic children instead of running code @@ -255,46 +277,44 @@ lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable is', - substrs=['%s::map' % ns, 'size=0', - '{}']) + self.expect("frame variable is", substrs=["%s::map" % ns, "size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable ss', - substrs=['%s::map' % ns, 'size=0', - '{}']) + self.expect("frame variable ss", substrs=["%s::map" % ns, "size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect( "frame variable ss", substrs=[ - '%s::map' % ns, - 'size=3', + "%s::map" % ns, + "size=3", '[0] = (first = "casa", second = "house")', '[1] = (first = "ciao", second = "hello")', '[2] = (first = "gatto", second = "cat")', - ]) + ], + ) self.expect( "expression ss", substrs=[ - '%s::map' % ns, - 'size=3', + "%s::map" % ns, + "size=3", '[0] = (first = "casa", second = "house")', '[1] = (first = "ciao", second = "hello")', '[2] = (first = "gatto", second = "cat")', - ]) + ], + ) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("ss").MightHaveChildren(), - "ss.MightHaveChildren() says False for non empty!") + "ss.MightHaveChildren() says False for non empty!", + ) # check access-by-index - self.expect("frame variable ss[2]", - substrs=['gatto', 'cat']) + self.expect("frame variable ss[2]", substrs=["gatto", "cat"]) # check that the expression parser does not make use of # synthetic children instead of running code @@ -306,6 +326,4 @@ lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect('frame variable ss', - substrs=['%s::map' % ns, 'size=0', - '{}']) + self.expect("frame variable ss", substrs=["%s::map" % ns, "size=0", "{}"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/queue/TestDataFormatterLibcxxQueue.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/queue/TestDataFormatterLibcxxQueue.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/queue/TestDataFormatterLibcxxQueue.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/queue/TestDataFormatterLibcxxQueue.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,30 +10,32 @@ class TestDataFormatterLibcxxQueue(TestBase): - def setUp(self): TestBase.setUp(self) - self.namespace = 'std' + self.namespace = "std" def check_variable(self, name): var = self.frame().FindVariable(name) self.assertTrue(var.IsValid()) - queue = self.namespace + '::queue' + queue = self.namespace + "::queue" self.assertIn(queue, var.GetDisplayTypeName()) self.assertEqual(var.GetNumChildren(), 5) for i in range(5): ch = var.GetChildAtIndex(i) self.assertTrue(ch.IsValid()) - self.assertEqual(ch.GetValueAsSigned(), i+1) + self.assertEqual(ch.GetValueAsSigned(), i + 1) - @expectedFailureAll(bugnumber="llvm.org/pr36109", debug_info="gmodules", triple=".*-android") + @expectedFailureAll( + bugnumber="llvm.org/pr36109", debug_info="gmodules", triple=".*-android" + ) @add_test_categories(["libc++"]) def test(self): """Test that std::queue is displayed correctly""" self.build() - lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp", False)) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) - self.check_variable('q1') - self.check_variable('q2') + self.check_variable("q1") + self.check_variable("q2") diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/ranges/ref_view/TestDataFormatterLibcxxRangesRefView.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/ranges/ref_view/TestDataFormatterLibcxxRangesRefView.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/ranges/ref_view/TestDataFormatterLibcxxRangesRefView.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/ranges/ref_view/TestDataFormatterLibcxxRangesRefView.py @@ -9,59 +9,63 @@ class LibcxxRangesRefViewDataFormatterTestCase(TestBase): - def check_string_vec_children(self): - return [ValueCheck(name='[0]', summary='"First"'), - ValueCheck(name='[1]', summary='"Second"'), - ValueCheck(name='[2]', summary='"Third"'), - ValueCheck(name='[3]', summary='"Fourth"')] + return [ + ValueCheck(name="[0]", summary='"First"'), + ValueCheck(name="[1]", summary='"Second"'), + ValueCheck(name="[2]", summary='"Third"'), + ValueCheck(name="[3]", summary='"Fourth"'), + ] def check_string_vec_ref_view(self): return ValueCheck( - name='*__range_', - summary='size=4', - children=self.check_string_vec_children()) + name="*__range_", + summary="size=4", + children=self.check_string_vec_children(), + ) def check_foo(self): - return ValueCheck( - name='vec', - children=self.check_string_vec_children()) + return ValueCheck(name="vec", children=self.check_string_vec_children()) @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) - @skipIf(compiler="clang", compiler_version=['<', '16.0']) + @skipIf(compiler="clang", compiler_version=["<", "16.0"]) def test_with_run_command(self): - """Test that std::ranges::ref_view is formatted correctly when printed. - """ + """Test that std::ranges::ref_view is formatted correctly when printed.""" self.build() (self.target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, 'Break here', lldb.SBFileSpec('main.cpp', False)) + self, "Break here", lldb.SBFileSpec("main.cpp", False) + ) # Check ref_view over a std::string - self.expect_var_path('single', - children=[ValueCheck( - name='*__range_', - summary='"First"')]) + self.expect_var_path( + "single", children=[ValueCheck(name="*__range_", summary='"First"')] + ) # Check all_view, which is a ref_view in this case - self.expect_var_path('all', - children=[self.check_string_vec_ref_view()]) + self.expect_var_path("all", children=[self.check_string_vec_ref_view()]) # Check take_view format. Embeds a ref_view - self.expect_var_path('subset', - children=[ - ValueCheck(children=[self.check_string_vec_ref_view()]), - ValueCheck(name='__count_', value='2') - ]) + self.expect_var_path( + "subset", + children=[ + ValueCheck(children=[self.check_string_vec_ref_view()]), + ValueCheck(name="__count_", value="2"), + ], + ) lldbutil.continue_to_breakpoint(self.process(), bkpt) # Check ref_view over custom type 'struct Foo' - self.expect_var_path('view', - children=[ValueCheck( - name='*__range_', - children=[ - ValueCheck(name='[0]', type='Foo', children=[self.check_foo()]), - ValueCheck(name='[1]', type='Foo', children=[self.check_foo()]) - ]) - ]) + self.expect_var_path( + "view", + children=[ + ValueCheck( + name="*__range_", + children=[ + ValueCheck(name="[0]", type="Foo", children=[self.check_foo()]), + ValueCheck(name="[1]", type="Foo", children=[self.check_foo()]), + ], + ) + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/TestDataFormatterLibcxxSharedPtr.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/TestDataFormatterLibcxxSharedPtr.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/TestDataFormatterLibcxxSharedPtr.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/TestDataFormatterLibcxxSharedPtr.py @@ -10,7 +10,6 @@ class TestCase(TestBase): - @add_test_categories(["libc++"]) def test_shared_ptr_variables(self): """Test `frame variable` output for `std::shared_ptr` types.""" @@ -58,7 +57,9 @@ self.assertRegex(valobj.summary, r"^10( strong=1)? weak=1$") self.assertNotEqual(valobj.child[0].unsigned, 0) - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): string_type = "std::string" else: string_type = "std::basic_string, std::allocator > " diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/span/TestDataFormatterLibcxxSpan.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/span/TestDataFormatterLibcxxSpan.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/span/TestDataFormatterLibcxxSpan.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/span/TestDataFormatterLibcxxSpan.py @@ -7,8 +7,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class LibcxxSpanDataFormatterTestCase(TestBase): +class LibcxxSpanDataFormatterTestCase(TestBase): def findVariable(self, name): var = self.frame().FindVariable(name) self.assertTrue(var.IsValid()) @@ -25,127 +25,154 @@ self.check_size(var_name, expectedSize) self.expect_expr( - var_name, result_type=f'std::span', - result_summary=f'size={expectedSize}', - result_children=[ - ValueCheck(name='[0]', value='1'), - ValueCheck(name='[1]', value='12'), - ValueCheck(name='[2]', value='123'), - ValueCheck(name='[3]', value='1234'), - ValueCheck(name='[4]', value='12345') - ]) + var_name, + result_type=f"std::span", + result_summary=f"size={expectedSize}", + result_children=[ + ValueCheck(name="[0]", value="1"), + ValueCheck(name="[1]", value="12"), + ValueCheck(name="[2]", value="123"), + ValueCheck(name="[3]", value="1234"), + ValueCheck(name="[4]", value="12345"), + ], + ) # check access-by-index - self.expect_var_path(f'{var_name}[0]', type='int', value='1') - self.expect_var_path(f'{var_name}[1]', type='int', value='12') - self.expect_var_path(f'{var_name}[2]', type='int', value='123') - self.expect_var_path(f'{var_name}[3]', type='int', value='1234') - self.expect_var_path(f'{var_name}[4]', type='int', value='12345') - - @add_test_categories(['libc++']) - @skipIf(compiler='clang', compiler_version=['<', '11.0']) + self.expect_var_path(f"{var_name}[0]", type="int", value="1") + self.expect_var_path(f"{var_name}[1]", type="int", value="12") + self.expect_var_path(f"{var_name}[2]", type="int", value="123") + self.expect_var_path(f"{var_name}[3]", type="int", value="1234") + self.expect_var_path(f"{var_name}[4]", type="int", value="12345") + + @add_test_categories(["libc++"]) + @skipIf(compiler="clang", compiler_version=["<", "11.0"]) def test_with_run_command(self): """Test that std::span variables are formatted correctly when printed.""" self.build() (self.target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, 'break here', lldb.SBFileSpec('main.cpp', False)) + self, "break here", lldb.SBFileSpec("main.cpp", False) + ) lldbutil.continue_to_breakpoint(process, bkpt) # std::span of std::array with extents known at compile-time - self.check_numbers('numbers_span') + self.check_numbers("numbers_span") # check access to synthetic children for static spans - self.runCmd('type summary add --summary-string "item 0 is ${var[0]}" -x "std::span<" span') - self.expect_expr('numbers_span', - result_type='std::span', - result_summary='item 0 is 1') + self.runCmd( + 'type summary add --summary-string "item 0 is ${var[0]}" -x "std::span<" span' + ) + self.expect_expr( + "numbers_span", + result_type="std::span", + result_summary="item 0 is 1", + ) - self.runCmd('type summary add --summary-string "item 0 is ${svar[0]}" -x "std::span<" span') - self.expect_expr('numbers_span', - result_type='std::span', - result_summary='item 0 is 1') + self.runCmd( + 'type summary add --summary-string "item 0 is ${svar[0]}" -x "std::span<" span' + ) + self.expect_expr( + "numbers_span", + result_type="std::span", + result_summary="item 0 is 1", + ) - self.runCmd('type summary delete span') + self.runCmd("type summary delete span") # New span with strings lldbutil.continue_to_breakpoint(process, bkpt) - expectedStringSpanChildren = [ ValueCheck(name='[0]', summary='"smart"'), - ValueCheck(name='[1]', summary='"!!!"') ] + expectedStringSpanChildren = [ + ValueCheck(name="[0]", summary='"smart"'), + ValueCheck(name="[1]", summary='"!!!"'), + ] - self.expect_var_path('strings_span', - summary='size=2', - children=expectedStringSpanChildren) + self.expect_var_path( + "strings_span", summary="size=2", children=expectedStringSpanChildren + ) # check access to synthetic children for dynamic spans - self.runCmd('type summary add --summary-string "item 0 is ${var[0]}" dynamic_string_span') - self.expect_var_path('strings_span', summary='item 0 is "smart"') + self.runCmd( + 'type summary add --summary-string "item 0 is ${var[0]}" dynamic_string_span' + ) + self.expect_var_path("strings_span", summary='item 0 is "smart"') - self.runCmd('type summary add --summary-string "item 0 is ${svar[0]}" dynamic_string_span') - self.expect_var_path('strings_span', summary='item 0 is "smart"') + self.runCmd( + 'type summary add --summary-string "item 0 is ${svar[0]}" dynamic_string_span' + ) + self.expect_var_path("strings_span", summary='item 0 is "smart"') - self.runCmd('type summary delete dynamic_string_span') + self.runCmd("type summary delete dynamic_string_span") # test summaries based on synthetic children self.runCmd( - 'type summary add --summary-string "span has ${svar%#} items" -e dynamic_string_span') + 'type summary add --summary-string "span has ${svar%#} items" -e dynamic_string_span' + ) - self.expect_var_path('strings_span', summary='span has 2 items') + self.expect_var_path("strings_span", summary="span has 2 items") - self.expect_var_path('strings_span', - summary='span has 2 items', - children=expectedStringSpanChildren) + self.expect_var_path( + "strings_span", + summary="span has 2 items", + children=expectedStringSpanChildren, + ) # check access-by-index - self.expect_var_path('strings_span[0]', summary='"smart"'); - self.expect_var_path('strings_span[1]', summary='"!!!"'); + self.expect_var_path("strings_span[0]", summary='"smart"') + self.expect_var_path("strings_span[1]", summary='"!!!"') # Newly inserted value not visible to span lldbutil.continue_to_breakpoint(process, bkpt) - self.expect_expr('strings_span', - result_summary='span has 2 items', - result_children=expectedStringSpanChildren) + self.expect_expr( + "strings_span", + result_summary="span has 2 items", + result_children=expectedStringSpanChildren, + ) - self.runCmd('type summary delete dynamic_string_span') + self.runCmd("type summary delete dynamic_string_span") lldbutil.continue_to_breakpoint(process, bkpt) # Empty spans - self.expect_expr('static_zero_span', - result_type='std::span', - result_summary='size=0') - self.check_size('static_zero_span', 0) + self.expect_expr( + "static_zero_span", result_type="std::span", result_summary="size=0" + ) + self.check_size("static_zero_span", 0) - self.expect_expr('dynamic_zero_span', - result_summary='size=0') - self.check_size('dynamic_zero_span', 0) + self.expect_expr("dynamic_zero_span", result_summary="size=0") + self.check_size("dynamic_zero_span", 0) # Nested spans - self.expect_expr('nested', - result_summary='size=2', - result_children=[ - ValueCheck(name='[0]', summary='size=2', - children=expectedStringSpanChildren), - ValueCheck(name='[1]', summary='size=2', - children=expectedStringSpanChildren) - ]) - self.check_size('nested', 2) - - @add_test_categories(['libc++']) - @skipIf(compiler='clang', compiler_version=['<', '11.0']) + self.expect_expr( + "nested", + result_summary="size=2", + result_children=[ + ValueCheck( + name="[0]", summary="size=2", children=expectedStringSpanChildren + ), + ValueCheck( + name="[1]", summary="size=2", children=expectedStringSpanChildren + ), + ], + ) + self.check_size("nested", 2) + + @add_test_categories(["libc++"]) + @skipIf(compiler="clang", compiler_version=["<", "11.0"]) def test_ref_and_ptr(self): """Test that std::span is correctly formatted when passed by ref and ptr""" self.build() (self.target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, 'Stop here to check by ref', lldb.SBFileSpec('main.cpp', False)) + self, "Stop here to check by ref", lldb.SBFileSpec("main.cpp", False) + ) # The reference should display the same was as the value did - self.check_numbers('ref') + self.check_numbers("ref") # The pointer should just show the right number of elements: - ptrAddr = self.findVariable('ptr').GetValue() - self.expect_expr('ptr', result_type='std::span *', - result_summary=f'{ptrAddr} size=5') + ptrAddr = self.findVariable("ptr").GetValue() + self.expect_expr( + "ptr", result_type="std::span *", result_summary=f"{ptrAddr} size=5" + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py @@ -4,7 +4,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,16 +11,17 @@ class LibcxxStringDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. self.main_spec = lldb.SBFileSpec("main.cpp") - self.namespace = 'std' + self.namespace = "std" @add_test_categories(["libc++"]) - @expectedFailureAll(bugnumber="llvm.org/pr36109", debug_info="gmodules", triple=".*-android") + @expectedFailureAll( + bugnumber="llvm.org/pr36109", debug_info="gmodules", triple=".*-android" + ) # Inline namespace is randomly ignored as Clang due to broken lookup inside # the std namespace. @expectedFailureAll(debug_info="gmodules") @@ -29,21 +29,19 @@ """Test that that file and class static variables display correctly.""" self.build() - (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, - "Set break point at this line.", - self.main_spec) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set break point at this line.", self.main_spec + ) frame = thread.frames[0] # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) is_64_bit = self.process().GetAddressByteSize() == 8 @@ -52,34 +50,41 @@ ns = self.namespace - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): - expected_basic_string = '%s::basic_string'%ns + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): + expected_basic_string = "%s::basic_string" % ns else: - expected_basic_string = '%s::basic_string, ' \ - '%s::allocator >'%(ns,ns,ns) + expected_basic_string = ( + "%s::basic_string, " + "%s::allocator >" % (ns, ns, ns) + ) self.expect( "frame variable", substrs=[ - '(%s::wstring) wempty = L""'%ns, - '(%s::wstring) s = L"hello world! מזל טוב!"'%ns, - '(%s::wstring) S = L"!!!!"'%ns, - '(const wchar_t *) mazeltov = 0x', + '(%s::wstring) wempty = L""' % ns, + '(%s::wstring) s = L"hello world! מזל טוב!"' % ns, + '(%s::wstring) S = L"!!!!"' % ns, + "(const wchar_t *) mazeltov = 0x", 'L"מזל טוב"', - '(%s::string) empty = ""'%ns, - '(%s::string) q = "hello world"'%ns, - '(%s::string) Q = "quite a long std::strin with lots of info inside it"'%ns, - '(%s::string) IHaveEmbeddedZeros = "a\\0b\\0c\\0d"'%ns, - '(%s::wstring) IHaveEmbeddedZerosToo = L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"'%ns, - '(%s::u16string) u16_string = u"ß水氶"'%ns, + '(%s::string) empty = ""' % ns, + '(%s::string) q = "hello world"' % ns, + '(%s::string) Q = "quite a long std::strin with lots of info inside it"' + % ns, + '(%s::string) IHaveEmbeddedZeros = "a\\0b\\0c\\0d"' % ns, + '(%s::wstring) IHaveEmbeddedZerosToo = L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"' + % ns, + '(%s::u16string) u16_string = u"ß水氶"' % ns, # FIXME: This should have a 'u' prefix. - '(%s::u16string) u16_empty = ""'%ns, - '(%s::u32string) u32_string = U"🍄🍅🍆🍌"'%ns, + '(%s::u16string) u16_empty = ""' % ns, + '(%s::u32string) u32_string = U"🍄🍅🍆🍌"' % ns, # FIXME: This should have a 'U' prefix. - '(%s::u32string) u32_empty = ""'%ns, - '(%s) uchar = "aaaaa"'%expected_basic_string, - '(%s::string *) null_str = nullptr'%ns, - ]) + '(%s::u32string) u32_empty = ""' % ns, + '(%s) uchar = "aaaaa"' % expected_basic_string, + "(%s::string *) null_str = nullptr" % ns, + ], + ) thread.StepOver() @@ -89,46 +94,66 @@ uncappedSummaryStream = lldb.SBStream() TheVeryLongOne.GetSummary(uncappedSummaryStream, summaryOptions) uncappedSummary = uncappedSummaryStream.GetData() - self.assertTrue(uncappedSummary.find("someText") > 0, - "uncappedSummary does not include the full string") + self.assertTrue( + uncappedSummary.find("someText") > 0, + "uncappedSummary does not include the full string", + ) summaryOptions.SetCapping(lldb.eTypeSummaryCapped) cappedSummaryStream = lldb.SBStream() TheVeryLongOne.GetSummary(cappedSummaryStream, summaryOptions) cappedSummary = cappedSummaryStream.GetData() self.assertTrue( cappedSummary.find("someText") <= 0, - "cappedSummary includes the full string") + "cappedSummary includes the full string", + ) - self.expect_expr("s", result_type=ns+"::wstring", result_summary='L"hello world! מזל טוב!"') + self.expect_expr( + "s", result_type=ns + "::wstring", result_summary='L"hello world! מזל טוב!"' + ) self.expect( "frame variable", substrs=[ - '(%s::wstring) S = L"!!!!!"'%ns, - '(const wchar_t *) mazeltov = 0x', + '(%s::wstring) S = L"!!!!!"' % ns, + "(const wchar_t *) mazeltov = 0x", 'L"מזל טוב"', - '(%s::string) q = "hello world"'%ns, - '(%s::string) Q = "quite a long std::strin with lots of info inside it"'%ns, - '(%s::string) IHaveEmbeddedZeros = "a\\0b\\0c\\0d"'%ns, - '(%s::wstring) IHaveEmbeddedZerosToo = L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"'%ns, - '(%s::u16string) u16_string = u"ß水氶"'%ns, - '(%s::u32string) u32_string = U"🍄🍅🍆🍌"'%ns, - '(%s::u32string) u32_empty = ""'%ns, - '(%s) uchar = "aaaaa"'%expected_basic_string, - '(%s::string *) null_str = nullptr'%ns, - ]) + '(%s::string) q = "hello world"' % ns, + '(%s::string) Q = "quite a long std::strin with lots of info inside it"' + % ns, + '(%s::string) IHaveEmbeddedZeros = "a\\0b\\0c\\0d"' % ns, + '(%s::wstring) IHaveEmbeddedZerosToo = L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"' + % ns, + '(%s::u16string) u16_string = u"ß水氶"' % ns, + '(%s::u32string) u32_string = U"🍄🍅🍆🍌"' % ns, + '(%s::u32string) u32_empty = ""' % ns, + '(%s) uchar = "aaaaa"' % expected_basic_string, + "(%s::string *) null_str = nullptr" % ns, + ], + ) # The test assumes that std::string is in its cap-size-data layout. - is_alternate_layout = ('arm' in self.getArchitecture()) and self.platformIsDarwin() + is_alternate_layout = ( + "arm" in self.getArchitecture() + ) and self.platformIsDarwin() if is_64_bit and not is_alternate_layout: - self.expect("frame variable garbage1", substrs=['garbage1 = Summary Unavailable']) - self.expect("frame variable garbage2", substrs=[r'garbage2 = "\xfa\xfa\xfa\xfa"']) + self.expect( + "frame variable garbage1", substrs=["garbage1 = Summary Unavailable"] + ) + self.expect( + "frame variable garbage2", substrs=[r'garbage2 = "\xfa\xfa\xfa\xfa"'] + ) self.expect("frame variable garbage3", substrs=[r'garbage3 = "\xf0\xf0"']) - self.expect("frame variable garbage4", substrs=['garbage4 = Summary Unavailable']) - self.expect("frame variable garbage5", substrs=['garbage5 = Summary Unavailable']) + self.expect( + "frame variable garbage4", substrs=["garbage4 = Summary Unavailable"] + ) + self.expect( + "frame variable garbage5", substrs=["garbage5 = Summary Unavailable"] + ) # Finally, make sure that if the string is not readable, we give an error: - bkpt_2 = target.BreakpointCreateBySourceRegex("Break here to look at bad string", self.main_spec) + bkpt_2 = target.BreakpointCreateBySourceRegex( + "Break here to look at bad string", self.main_spec + ) self.assertEqual(bkpt_2.GetNumLocations(), 1, "Got one location") threads = lldbutil.continue_to_breakpoint(process, bkpt_2) self.assertEqual(len(threads), 1, "Stopped at second breakpoint") @@ -137,4 +162,3 @@ self.assertTrue(var.GetError().Success(), "Made variable") summary = var.GetSummary() self.assertEqual(summary, "Summary Unavailable", "No summary for bad value") - diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/string/simulator/TestDataFormatterLibcxxStringSimulator.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/string/simulator/TestDataFormatterLibcxxStringSimulator.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/string/simulator/TestDataFormatterLibcxxStringSimulator.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/string/simulator/TestDataFormatterLibcxxStringSimulator.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,24 +11,26 @@ class LibcxxStringDataFormatterSimulatorTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True def _run_test(self, defines): cxxflags_extras = " ".join(["-D%s" % d for d in defines]) self.build(dictionary=dict(CXXFLAGS_EXTRAS=cxxflags_extras)) - lldbutil.run_to_source_breakpoint(self, '// Break here', - lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// Break here", lldb.SBFileSpec("main.cpp") + ) self.expect_var_path("shortstring", summary='"short"') self.expect_var_path("longstring", summary='"I am a very long string"') + for v in [None, "ALTERNATE_LAYOUT"]: for r in range(5): - name = "test_r%d"%r - defines = ["REVISION=%d"%r] + name = "test_r%d" % r + defines = ["REVISION=%d" % r] if v: name += "_" + v defines += [v] f = functools.partialmethod( - LibcxxStringDataFormatterSimulatorTestCase._run_test, defines) + LibcxxStringDataFormatterSimulatorTestCase._run_test, defines + ) setattr(LibcxxStringDataFormatterSimulatorTestCase, name, f) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/string_view/TestDataFormatterLibcxxStringView.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/string_view/TestDataFormatterLibcxxStringView.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/string_view/TestDataFormatterLibcxxStringView.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/string_view/TestDataFormatterLibcxxStringView.py @@ -4,7 +4,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,16 +11,19 @@ class LibcxxStringViewDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line1 = line_number('main.cpp', '// Set break point at this line.') - self.line2 = line_number('main.cpp', '// Break here to look at bad string view.' ) + self.line1 = line_number("main.cpp", "// Set break point at this line.") + self.line2 = line_number( + "main.cpp", "// Break here to look at bad string view." + ) @add_test_categories(["libc++"]) - @expectedFailureAll(bugnumber="llvm.org/pr36109", debug_info="gmodules", triple=".*-android") + @expectedFailureAll( + bugnumber="llvm.org/pr36109", debug_info="gmodules", triple=".*-android" + ) # Inline namespace is randomly ignored as Clang due to broken lookup inside # the std namespace. @expectedFailureAll(debug_info="gmodules") @@ -31,93 +33,84 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line1, num_expected_locations=-1) + self, "main.cpp", self.line1, num_expected_locations=-1 + ) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line2, num_expected_locations=-1) + self, "main.cpp", self.line2, num_expected_locations=-1 + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): - expected_basic_string = 'std::basic_string' - expected_basic_string_view = 'std::basic_string_view' + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): + expected_basic_string = "std::basic_string" + expected_basic_string_view = "std::basic_string_view" else: - expected_basic_string = 'std::basic_string, std::allocator >' - expected_basic_string_view = 'std::basic_string_view >' - - self.expect_var_path('wempty', - type='std::wstring_view', - summary='L""') - self.expect_var_path('s', - type='std::wstring_view', - summary='L"hello world! מזל טוב!"') - self.expect_var_path('S', - type='std::wstring_view', - summary='L"!!!!"') - self.expect_var_path('empty', - type='std::string_view', - summary='""') - self.expect_var_path('q_source', - type='std::string', - summary='"hello world"') - self.expect_var_path('q', - type='std::string_view', - summary='"hello world"') - self.expect_var_path('Q', - type='std::string_view', - summary='"quite a long std::strin with lots of info inside it"') - self.expect_var_path('IHaveEmbeddedZeros', - type='std::string_view', - summary='"a\\0b\\0c\\0d"') - self.expect_var_path('IHaveEmbeddedZerosToo', - type='std::wstring_view', - summary='L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"') - self.expect_var_path('u16_string', - type='std::u16string_view', - summary='u"ß水氶"') - self.expect_var_path('u16_empty', - type='std::u16string_view', - summary='""') - self.expect_var_path('u32_string', - type='std::u32string_view', - summary='U"🍄🍅🍆🍌"') - self.expect_var_path('u32_empty', - type='std::u32string_view', - summary='""') - self.expect_var_path('uchar_source', - type=expected_basic_string, - summary='"aaaaaaaaaa"') - self.expect_var_path('uchar', - type=expected_basic_string_view, - summary='"aaaaa"') - self.expect_var_path('oops', - type='std::string_view', - summary='"Hellooo World\\n"') + expected_basic_string = "std::basic_string, std::allocator >" + expected_basic_string_view = "std::basic_string_view >" + + self.expect_var_path("wempty", type="std::wstring_view", summary='L""') + self.expect_var_path( + "s", type="std::wstring_view", summary='L"hello world! מזל טוב!"' + ) + self.expect_var_path("S", type="std::wstring_view", summary='L"!!!!"') + self.expect_var_path("empty", type="std::string_view", summary='""') + self.expect_var_path("q_source", type="std::string", summary='"hello world"') + self.expect_var_path("q", type="std::string_view", summary='"hello world"') + self.expect_var_path( + "Q", + type="std::string_view", + summary='"quite a long std::strin with lots of info inside it"', + ) + self.expect_var_path( + "IHaveEmbeddedZeros", type="std::string_view", summary='"a\\0b\\0c\\0d"' + ) + self.expect_var_path( + "IHaveEmbeddedZerosToo", + type="std::wstring_view", + summary='L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"', + ) + self.expect_var_path("u16_string", type="std::u16string_view", summary='u"ß水氶"') + self.expect_var_path("u16_empty", type="std::u16string_view", summary='""') + self.expect_var_path( + "u32_string", type="std::u32string_view", summary='U"🍄🍅🍆🍌"' + ) + self.expect_var_path("u32_empty", type="std::u32string_view", summary='""') + self.expect_var_path( + "uchar_source", type=expected_basic_string, summary='"aaaaaaaaaa"' + ) + self.expect_var_path( + "uchar", type=expected_basic_string_view, summary='"aaaaa"' + ) + self.expect_var_path( + "oops", type="std::string_view", summary='"Hellooo World\\n"' + ) # GetSummary returns None so can't be checked by expect_var_path, so we # use the str representation instead - null_obj = self.frame().GetValueForVariablePath('null_str') + null_obj = self.frame().GetValueForVariablePath("null_str") self.assertEqual(null_obj.GetSummary(), "Summary Unavailable") - self.assertEqual(str(null_obj), - '(std::string_view *) null_str = nullptr'); + self.assertEqual(str(null_obj), "(std::string_view *) null_str = nullptr") self.runCmd("n") @@ -127,68 +120,65 @@ uncappedSummaryStream = lldb.SBStream() TheVeryLongOne.GetSummary(uncappedSummaryStream, summaryOptions) uncappedSummary = uncappedSummaryStream.GetData() - self.assertTrue(uncappedSummary.find("someText") > 0, - "uncappedSummary does not include the full string") + self.assertTrue( + uncappedSummary.find("someText") > 0, + "uncappedSummary does not include the full string", + ) summaryOptions.SetCapping(lldb.eTypeSummaryCapped) cappedSummaryStream = lldb.SBStream() TheVeryLongOne.GetSummary(cappedSummaryStream, summaryOptions) cappedSummary = cappedSummaryStream.GetData() self.assertTrue( cappedSummary.find("someText") <= 0, - "cappedSummary includes the full string") - - self.expect_expr("s", result_type="std::wstring_view", result_summary='L"hello world! מזל טוב!"') - - self.expect_var_path('wempty', - type='std::wstring_view', - summary='L""') - self.expect_var_path('s', - type='std::wstring_view', - summary='L"hello world! מזל טוב!"') - self.expect_var_path('S', - type='std::wstring_view', - summary='L"!!!!"') - self.expect_var_path('empty', - type='std::string_view', - summary='""') - self.expect_var_path('q_source', - type='std::string', - summary='"Hello world"') - self.expect_var_path('q', - type='std::string_view', - summary='"Hello world"') - self.expect_var_path('Q', - type='std::string_view', - summary='"quite a long std::strin with lots of info inside it"') - self.expect_var_path('IHaveEmbeddedZeros', - type='std::string_view', - summary='"a\\0b\\0c\\0d"') - self.expect_var_path('IHaveEmbeddedZerosToo', - type='std::wstring_view', - summary='L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"') - self.expect_var_path('u16_string', - type='std::u16string_view', - summary='u"ß水氶"') - self.expect_var_path('u16_empty', - type='std::u16string_view', - summary='""') - self.expect_var_path('u32_string', - type='std::u32string_view', - summary='U"🍄🍅🍆🍌"') - self.expect_var_path('u32_empty', - type='std::u32string_view', - summary='""') - self.expect_var_path('uchar_source', - type=expected_basic_string, - summary='"aaaaaaaaaa"') - self.expect_var_path('uchar', - type=expected_basic_string_view, - summary='"aaaaa"') - - self.runCmd('cont') - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) - - broken_obj = self.frame().GetValueForVariablePath('in_str_view') - self.assertEqual( broken_obj.GetSummary(), "Summary Unavailable" ) + "cappedSummary includes the full string", + ) + + self.expect_expr( + "s", + result_type="std::wstring_view", + result_summary='L"hello world! מזל טוב!"', + ) + + self.expect_var_path("wempty", type="std::wstring_view", summary='L""') + self.expect_var_path( + "s", type="std::wstring_view", summary='L"hello world! מזל טוב!"' + ) + self.expect_var_path("S", type="std::wstring_view", summary='L"!!!!"') + self.expect_var_path("empty", type="std::string_view", summary='""') + self.expect_var_path("q_source", type="std::string", summary='"Hello world"') + self.expect_var_path("q", type="std::string_view", summary='"Hello world"') + self.expect_var_path( + "Q", + type="std::string_view", + summary='"quite a long std::strin with lots of info inside it"', + ) + self.expect_var_path( + "IHaveEmbeddedZeros", type="std::string_view", summary='"a\\0b\\0c\\0d"' + ) + self.expect_var_path( + "IHaveEmbeddedZerosToo", + type="std::wstring_view", + summary='L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"', + ) + self.expect_var_path("u16_string", type="std::u16string_view", summary='u"ß水氶"') + self.expect_var_path("u16_empty", type="std::u16string_view", summary='""') + self.expect_var_path( + "u32_string", type="std::u32string_view", summary='U"🍄🍅🍆🍌"' + ) + self.expect_var_path("u32_empty", type="std::u32string_view", summary='""') + self.expect_var_path( + "uchar_source", type=expected_basic_string, summary='"aaaaaaaaaa"' + ) + self.expect_var_path( + "uchar", type=expected_basic_string_view, summary='"aaaaa"' + ) + + self.runCmd("cont") + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) + + broken_obj = self.frame().GetValueForVariablePath("in_str_view") + self.assertEqual(broken_obj.GetSummary(), "Summary Unavailable") diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/TestDataFormatterLibcxxTuple.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/TestDataFormatterLibcxxTuple.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/TestDataFormatterLibcxxTuple.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/TestDataFormatterLibcxxTuple.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,37 +10,36 @@ class TestDataFormatterLibcxxTuple(TestBase): - def setUp(self): TestBase.setUp(self) - self.line = line_number('main.cpp', '// break here') - self.namespace = 'std' + self.line = line_number("main.cpp", "// break here") + self.namespace = "std" @add_test_categories(["libc++"]) def test(self): """Test that std::tuple is displayed correctly""" self.build() - lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp", False)) - - tuple_name = self.namespace + '::tuple' - self.expect("frame variable empty", - substrs=[tuple_name, - 'size=0', - '{}']) - - self.expect("frame variable one_elt", - substrs=[tuple_name, - 'size=1', - '{', - '[0] = 47', - '}']) - - self.expect("frame variable three_elts", - substrs=[tuple_name, - 'size=3', - '{', - '[0] = 1', - '[1] = 47', - '[2] = "foo"', - '}']) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) + + tuple_name = self.namespace + "::tuple" + self.expect("frame variable empty", substrs=[tuple_name, "size=0", "{}"]) + + self.expect( + "frame variable one_elt", + substrs=[tuple_name, "size=1", "{", "[0] = 47", "}"], + ) + + self.expect( + "frame variable three_elts", + substrs=[ + tuple_name, + "size=3", + "{", + "[0] = 1", + "[1] = 47", + '[2] = "foo"', + "}", + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py @@ -10,22 +10,27 @@ class TestCase(TestBase): - def make_expected_type(self, pointee_type: str, qualifiers: str = "") -> str: if qualifiers: - qualifiers = ' ' + qualifiers + qualifiers = " " + qualifiers - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): - return f'std::unique_ptr<{pointee_type}>{qualifiers}' + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): + return f"std::unique_ptr<{pointee_type}>{qualifiers}" else: - return f'std::unique_ptr<{pointee_type}, std::default_delete<{pointee_type}> >{qualifiers}' + return f"std::unique_ptr<{pointee_type}, std::default_delete<{pointee_type}> >{qualifiers}" def make_expected_basic_string_ptr(self) -> str: - if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion(['>', '16.0']): - return f'std::unique_ptr' + if self.expectedCompiler(["clang"]) and self.expectedCompilerVersion( + [">", "16.0"] + ): + return f"std::unique_ptr" else: - return 'std::unique_ptr, std::allocator >, ' \ - 'std::default_delete, std::allocator > > >' + return ( + "std::unique_ptr, std::allocator >, " + "std::default_delete, std::allocator > > >" + ) @add_test_categories(["libc++"]) def test_unique_ptr_variables(self): @@ -81,9 +86,7 @@ children=[ValueCheck(name="pointer", summary='"hello"')], ) - valobj = self.expect_var_path( - "up_user", type=self.make_expected_type("User") - ) + valobj = self.expect_var_path("up_user", type=self.make_expected_type("User")) self.assertRegex(valobj.summary, "^User @ 0x0*[1-9a-f][0-9a-f]+$") self.assertNotEqual(valobj.child[0].unsigned, 0) @@ -103,9 +106,9 @@ summary="1234", children=[ ValueCheck(name="pointer"), - ValueCheck(name="deleter", children=[ - ValueCheck(name="dummy_", value="9999") - ]), + ValueCheck( + name="deleter", children=[ValueCheck(name="dummy_", value="9999")] + ), ], ) self.assertNotEqual(valobj.child[0].unsigned, 0) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unordered_map/TestDataFormatterLibccUnorderedMap.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unordered_map/TestDataFormatterLibccUnorderedMap.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unordered_map/TestDataFormatterLibccUnorderedMap.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unordered_map/TestDataFormatterLibccUnorderedMap.py @@ -7,47 +7,60 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class LibcxxUnorderedMapDataFormatterTestCase(TestBase): - @add_test_categories(['libc++']) +class LibcxxUnorderedMapDataFormatterTestCase(TestBase): + @add_test_categories(["libc++"]) def test_iterator_formatters(self): """Test that std::unordered_map related structures are formatted correctly when printed. - Currently only tests format of std::unordered_map iterators. + Currently only tests format of std::unordered_map iterators. """ self.build() (self.target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, 'Break here', lldb.SBFileSpec('main.cpp', False)) + self, "Break here", lldb.SBFileSpec("main.cpp", False) + ) # Test empty iterators - self.expect_expr('empty_iter', '') - self.expect_expr('const_empty_iter', '') + self.expect_expr("empty_iter", "") + self.expect_expr("const_empty_iter", "") lldbutil.continue_to_breakpoint(process, bkpt) # Check that key/value is correctly formatted - self.expect_expr('foo', result_children=[ - ValueCheck(name='first', summary='"Foo"'), - ValueCheck(name='second', summary='"Bar"') - ]) + self.expect_expr( + "foo", + result_children=[ + ValueCheck(name="first", summary='"Foo"'), + ValueCheck(name="second", summary='"Bar"'), + ], + ) # Check invalid iterator is empty - self.expect_expr('invalid', '') + self.expect_expr("invalid", "") # Const key/val iterator - self.expect_expr('const_baz', result_children=[ - ValueCheck(name='first', summary='"Baz"'), - ValueCheck(name='second', summary='"Qux"') - ]) + self.expect_expr( + "const_baz", + result_children=[ + ValueCheck(name="first", summary='"Baz"'), + ValueCheck(name="second", summary='"Qux"'), + ], + ) # Bucket iterators # I.e., std::__hash_map_const_iterator> # and std::__hash_map_iterator> - self.expect_expr('bucket_it', result_children=[ - ValueCheck(name='first', summary='"Baz"'), - ValueCheck(name='second', summary='"Qux"') - ]) - - self.expect_expr('const_bucket_it', result_children=[ - ValueCheck(name='first', summary='"Baz"'), - ValueCheck(name='second', summary='"Qux"') - ]) + self.expect_expr( + "bucket_it", + result_children=[ + ValueCheck(name="first", summary='"Baz"'), + ValueCheck(name="second", summary='"Qux"'), + ], + ) + + self.expect_expr( + "const_bucket_it", + result_children=[ + ValueCheck(name="first", summary='"Baz"'), + ValueCheck(name="second", summary='"Qux"'), + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/variant/TestDataFormatterLibcxxVariant.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/variant/TestDataFormatterLibcxxVariant.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/variant/TestDataFormatterLibcxxVariant.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/variant/TestDataFormatterLibcxxVariant.py @@ -3,79 +3,86 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class LibcxxVariantDataFormatterTestCase(TestBase): +class LibcxxVariantDataFormatterTestCase(TestBase): @add_test_categories(["libc++"]) ## Clang 7.0 is the oldest Clang that can reliably parse newer libc++ versions ## with -std=c++17. - @skipIf(oslist=no_match(["macosx"]), compiler="clang", compiler_version=['<', '7.0']) + @skipIf( + oslist=no_match(["macosx"]), compiler="clang", compiler_version=["<", "7.0"] + ) ## We are skipping gcc version less that 5.1 since this test requires -std=c++17 - @skipIf(compiler="gcc", compiler_version=['<', '5.1']) + @skipIf(compiler="gcc", compiler_version=["<", "5.1"]) ## std::get is unavailable for std::variant before macOS 10.14 @skipIf(macos_version=["<", "10.14"]) def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() - (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', - lldb.SBFileSpec("main.cpp", False)) + (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp", False) + ) - self.runCmd( "frame variable has_variant" ) + self.runCmd("frame variable has_variant") output = self.res.GetOutput() ## The variable has_variant tells us if the test program ## detected we have a sufficient libc++ version to support variant ## false means we do not and therefore should skip the test - if output.find("(bool) has_variant = false") != -1 : - self.skipTest( "std::variant not supported" ) + if output.find("(bool) has_variant = false") != -1: + self.skipTest("std::variant not supported") lldbutil.continue_to_breakpoint(self.process, bkpt) - self.expect("frame variable v1", - substrs=['v1 = Active Type = int {', - 'Value = 12', - '}']) - - self.expect("frame variable v1_ref", - substrs=['v1_ref = Active Type = int : {', - 'Value = 12', - '}']) - - self.expect("frame variable v_v1", - substrs=['v_v1 = Active Type = std::variant {', - 'Value = Active Type = int {', - 'Value = 12', - '}', - '}']) + self.expect( + "frame variable v1", + substrs=["v1 = Active Type = int {", "Value = 12", "}"], + ) + + self.expect( + "frame variable v1_ref", + substrs=["v1_ref = Active Type = int : {", "Value = 12", "}"], + ) + + self.expect( + "frame variable v_v1", + substrs=[ + "v_v1 = Active Type = std::variant {", + "Value = Active Type = int {", + "Value = 12", + "}", + "}", + ], + ) lldbutil.continue_to_breakpoint(self.process, bkpt) - self.expect("frame variable v1", - substrs=['v1 = Active Type = double {', - 'Value = 2', - '}']) + self.expect( + "frame variable v1", + substrs=["v1 = Active Type = double {", "Value = 2", "}"], + ) lldbutil.continue_to_breakpoint(self.process, bkpt) - self.expect("frame variable v2", - substrs=['v2 = Active Type = double {', - 'Value = 2', - '}']) + self.expect( + "frame variable v2", + substrs=["v2 = Active Type = double {", "Value = 2", "}"], + ) - self.expect("frame variable v3", - substrs=['v3 = Active Type = char {', - 'Value = \'A\'', - '}']) + self.expect( + "frame variable v3", + substrs=["v3 = Active Type = char {", "Value = 'A'", "}"], + ) - self.expect("frame variable v_no_value", - substrs=['v_no_value = No Value']) + self.expect("frame variable v_no_value", substrs=["v_no_value = No Value"]) - self.expect("frame variable v_300_types_no_value", - substrs=['v_300_types_no_value = No Value']) + self.expect( + "frame variable v_300_types_no_value", + substrs=["v_300_types_no_value = No Value"], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class LibcxxVBoolDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") @add_test_categories(["libc++"]) def test_with_run_command(self): @@ -25,25 +23,26 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=-1) + self, "main.cpp", self.line, num_expected_locations=-1 + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -51,23 +50,27 @@ self.expect( "frame variable vBool", substrs=[ - 'size=49', - '[0] = false', - '[1] = true', - '[18] = false', - '[27] = true', - '[36] = false', - '[47] = true', - '[48] = true']) + "size=49", + "[0] = false", + "[1] = true", + "[18] = false", + "[27] = true", + "[36] = false", + "[47] = true", + "[48] = true", + ], + ) self.expect( "expr vBool", substrs=[ - 'size=49', - '[0] = false', - '[1] = true', - '[18] = false', - '[27] = true', - '[36] = false', - '[47] = true', - '[48] = true']) + "size=49", + "[0] = false", + "[1] = true", + "[18] = false", + "[27] = true", + "[36] = false", + "[47] = true", + "[48] = true", + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,101 +10,110 @@ class LibcxxVectorDataFormatterTestCase(TestBase): - def check_numbers(self, var_name): - self.expect("frame variable " + var_name, - substrs=[var_name + ' = size=7', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '[4] = 12345', - '[5] = 123456', - '[6] = 1234567', - '}']) - - self.expect_expr(var_name, result_summary="size=7", result_children=[ - ValueCheck(value="1"), - ValueCheck(value="12"), - ValueCheck(value="123"), - ValueCheck(value="1234"), - ValueCheck(value="12345"), - ValueCheck(value="123456"), - ValueCheck(value="1234567"), - ]) + self.expect( + "frame variable " + var_name, + substrs=[ + var_name + " = size=7", + "[0] = 1", + "[1] = 12", + "[2] = 123", + "[3] = 1234", + "[4] = 12345", + "[5] = 123456", + "[6] = 1234567", + "}", + ], + ) + + self.expect_expr( + var_name, + result_summary="size=7", + result_children=[ + ValueCheck(value="1"), + ValueCheck(value="12"), + ValueCheck(value="123"), + ValueCheck(value="1234"), + ValueCheck(value="12345"), + ValueCheck(value="123456"), + ValueCheck(value="1234567"), + ], + ) # check access-by-index - self.expect("frame variable " + var_name + "[0]", - substrs=['1']) - self.expect("frame variable " + var_name + "[1]", - substrs=['12']) - self.expect("frame variable " + var_name + "[2]", - substrs=['123']) - self.expect("frame variable " + var_name + "[3]", - substrs=['1234']) + self.expect("frame variable " + var_name + "[0]", substrs=["1"]) + self.expect("frame variable " + var_name + "[1]", substrs=["12"]) + self.expect("frame variable " + var_name + "[2]", substrs=["123"]) + self.expect("frame variable " + var_name + "[3]", substrs=["1234"]) @add_test_categories(["libc++"]) def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() (self.target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, "break here", lldb.SBFileSpec("main.cpp", False)) + self, "break here", lldb.SBFileSpec("main.cpp", False) + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # empty vectors (and storage pointers SHOULD BOTH BE NULL..) - self.expect("frame variable numbers", - substrs=['numbers = size=0']) + self.expect("frame variable numbers", substrs=["numbers = size=0"]) lldbutil.continue_to_breakpoint(process, bkpt) # first value added - self.expect("frame variable numbers", - substrs=['numbers = size=1', - '[0] = 1', - '}']) + self.expect( + "frame variable numbers", substrs=["numbers = size=1", "[0] = 1", "}"] + ) # add some more data lldbutil.continue_to_breakpoint(process, bkpt) - self.expect("frame variable numbers", - substrs=['numbers = size=4', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '}']) - - self.expect("expression numbers", - substrs=['$', 'size=4', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '}']) + self.expect( + "frame variable numbers", + substrs=[ + "numbers = size=4", + "[0] = 1", + "[1] = 12", + "[2] = 123", + "[3] = 1234", + "}", + ], + ) + + self.expect( + "expression numbers", + substrs=[ + "$", + "size=4", + "[0] = 1", + "[1] = 12", + "[2] = 123", + "[3] = 1234", + "}", + ], + ) # check access to synthetic children self.runCmd( - "type summary add --summary-string \"item 0 is ${var[0]}\" std::int_vect int_vect") - self.expect('frame variable numbers', - substrs=['item 0 is 1']) + 'type summary add --summary-string "item 0 is ${var[0]}" std::int_vect int_vect' + ) + self.expect("frame variable numbers", substrs=["item 0 is 1"]) self.runCmd( - "type summary add --summary-string \"item 0 is ${svar[0]}\" std::int_vect int_vect") - self.expect('frame variable numbers', - substrs=['item 0 is 1']) + 'type summary add --summary-string "item 0 is ${svar[0]}" std::int_vect int_vect' + ) + self.expect("frame variable numbers", substrs=["item 0 is 1"]) # move on with synths self.runCmd("type summary delete std::int_vect") self.runCmd("type summary delete int_vect") @@ -118,71 +126,58 @@ # clear out the vector and see that we do the right thing once again lldbutil.continue_to_breakpoint(process, bkpt) - self.expect("frame variable numbers", - substrs=['numbers = size=0']) + self.expect("frame variable numbers", substrs=["numbers = size=0"]) lldbutil.continue_to_breakpoint(process, bkpt) # first value added - self.expect("frame variable numbers", - substrs=['numbers = size=1', - '[0] = 7', - '}']) + self.expect( + "frame variable numbers", substrs=["numbers = size=1", "[0] = 7", "}"] + ) # check if we can display strings - self.expect("frame variable strings", - substrs=['goofy', - 'is', - 'smart']) + self.expect("frame variable strings", substrs=["goofy", "is", "smart"]) - self.expect("expression strings", - substrs=['goofy', - 'is', - 'smart']) + self.expect("expression strings", substrs=["goofy", "is", "smart"]) # test summaries based on synthetic children self.runCmd( - "type summary add std::string_vect string_vect --summary-string \"vector has ${svar%#} items\" -e") - self.expect("frame variable strings", - substrs=['vector has 3 items', - 'goofy', - 'is', - 'smart']) - - self.expect("expression strings", - substrs=['vector has 3 items', - 'goofy', - 'is', - 'smart']) + 'type summary add std::string_vect string_vect --summary-string "vector has ${svar%#} items" -e' + ) + self.expect( + "frame variable strings", + substrs=["vector has 3 items", "goofy", "is", "smart"], + ) + + self.expect( + "expression strings", substrs=["vector has 3 items", "goofy", "is", "smart"] + ) lldbutil.continue_to_breakpoint(process, bkpt) - self.expect("frame variable strings", - substrs=['vector has 4 items']) + self.expect("frame variable strings", substrs=["vector has 4 items"]) # check access-by-index - self.expect("frame variable strings[0]", - substrs=['goofy']) - self.expect("frame variable strings[1]", - substrs=['is']) + self.expect("frame variable strings[0]", substrs=["goofy"]) + self.expect("frame variable strings[1]", substrs=["is"]) lldbutil.continue_to_breakpoint(process, bkpt) - self.expect("frame variable strings", - substrs=['vector has 0 items']) + self.expect("frame variable strings", substrs=["vector has 0 items"]) @add_test_categories(["libc++"]) def test_ref_and_ptr(self): """Test that that file and class static variables display correctly.""" self.build() (self.target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( - self, "Stop here to check by ref", lldb.SBFileSpec("main.cpp", False)) + self, "Stop here to check by ref", lldb.SBFileSpec("main.cpp", False) + ) # The reference should display the same was as the value did self.check_numbers("ref") # The pointer should just show the right number of elements: - self.expect("frame variable ptr", substrs=['ptr =', ' size=7']) + self.expect("frame variable ptr", substrs=["ptr =", " size=7"]) - self.expect("expression ptr", substrs=['$', 'size=7']) + self.expect("expression ptr", substrs=["$", "size=7"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class StdIteratorDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") @add_test_categories(["libstdcxx"]) @expectedFailureAll(bugnumber="llvm.org/pr50861", compiler="gcc") @@ -26,45 +24,38 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=-1) + self, "main.cpp", self.line, num_expected_locations=-1 + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect('frame variable ivI', substrs=['item = 3']) - self.expect('expr ivI', substrs=['item = 3']) + self.expect("frame variable ivI", substrs=["item = 3"]) + self.expect("expr ivI", substrs=["item = 3"]) - self.expect( - 'frame variable iimI', - substrs=[ - 'first = 0', - 'second = 12']) - self.expect('expr iimI', substrs=['first = 0', 'second = 12']) + self.expect("frame variable iimI", substrs=["first = 0", "second = 12"]) + self.expect("expr iimI", substrs=["first = 0", "second = 12"]) - self.expect( - 'frame variable simI', - substrs=[ - 'first = "world"', - 'second = 42']) - self.expect('expr simI', substrs=['first = "world"', 'second = 42']) + self.expect("frame variable simI", substrs=['first = "world"', "second = 42"]) + self.expect("expr simI", substrs=['first = "world"', "second = 42"]) - self.expect('frame variable svI', substrs=['item = "hello"']) - self.expect('expr svI', substrs=['item = "hello"']) + self.expect("frame variable svI", substrs=['item = "hello"']) + self.expect("expr svI", substrs=['item = "hello"']) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class StdMapDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") @add_test_categories(["libstdcxx"]) @expectedFailureAll(bugnumber="llvm.org/pr50861", compiler="gcc") @@ -25,26 +23,25 @@ self.build() self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp( - self, "Set break point at this line.") + lldbutil.run_break_set_by_source_regexp(self, "Set break point at this line.") self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -52,69 +49,80 @@ self.runCmd("frame variable ii --show-types") self.runCmd( - "type summary add -x \"std::map<\" --summary-string \"map has ${svar%#} items\" -e") + 'type summary add -x "std::map<" --summary-string "map has ${svar%#} items" -e' + ) - self.expect('frame variable ii', - substrs=['map has 0 items', - '{}']) + self.expect("frame variable ii", substrs=["map has 0 items", "{}"]) self.runCmd("c") - self.expect('frame variable ii', - substrs=['map has 2 items', - '[0] = ', - 'first = 0', - 'second = 0', - '[1] = ', - 'first = 1', - 'second = 1']) + self.expect( + "frame variable ii", + substrs=[ + "map has 2 items", + "[0] = ", + "first = 0", + "second = 0", + "[1] = ", + "first = 1", + "second = 1", + ], + ) self.runCmd("c") - self.expect('frame variable ii', - substrs=['map has 4 items', - '[2] = ', - 'first = 2', - 'second = 0', - '[3] = ', - 'first = 3', - 'second = 1']) + self.expect( + "frame variable ii", + substrs=[ + "map has 4 items", + "[2] = ", + "first = 2", + "second = 0", + "[3] = ", + "first = 3", + "second = 1", + ], + ) self.runCmd("c") - self.expect("frame variable ii", - substrs=['map has 9 items', - '[5] = ', - 'first = 5', - 'second = 0', - '[7] = ', - 'first = 7', - 'second = 1']) - - self.expect("expression ii", - substrs=['map has 9 items', - '[5] = ', - 'first = 5', - 'second = 0', - '[7] = ', - 'first = 7', - 'second = 1']) + self.expect( + "frame variable ii", + substrs=[ + "map has 9 items", + "[5] = ", + "first = 5", + "second = 0", + "[7] = ", + "first = 7", + "second = 1", + ], + ) + + self.expect( + "expression ii", + substrs=[ + "map has 9 items", + "[5] = ", + "first = 5", + "second = 0", + "[7] = ", + "first = 7", + "second = 1", + ], + ) # check access-by-index - self.expect("frame variable ii[0]", - substrs=['first = 0', - 'second = 0']) - self.expect("frame variable ii[3]", - substrs=['first =', - 'second =']) + self.expect("frame variable ii[0]", substrs=["first = 0", "second = 0"]) + self.expect("frame variable ii[3]", substrs=["first =", "second ="]) - self.expect("frame variable ii[8]", matching=True, - substrs=['1234567']) + self.expect("frame variable ii[8]", matching=True, substrs=["1234567"]) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("ii").MightHaveChildren(), - "ii.MightHaveChildren() says False for non empty!") + "ii.MightHaveChildren() says False for non empty!", + ) # check that the expression parser does not make use of # synthetic children instead of running code @@ -126,57 +134,53 @@ self.runCmd("c") - self.expect('frame variable ii', - substrs=['map has 0 items', - '{}']) + self.expect("frame variable ii", substrs=["map has 0 items", "{}"]) self.runCmd("frame variable si --show-types") - self.expect('frame variable si', - substrs=['map has 0 items', - '{}']) + self.expect("frame variable si", substrs=["map has 0 items", "{}"]) self.runCmd("c") - self.expect('frame variable si', - substrs=['map has 1 items', - '[0] = ', - 'first = \"zero\"', - 'second = 0']) + self.expect( + "frame variable si", + substrs=["map has 1 items", "[0] = ", 'first = "zero"', "second = 0"], + ) self.runCmd("c") self.expect( "frame variable si", substrs=[ - 'map has 5 items', + "map has 5 items", '[0] = (first = "four", second = 4)', '[1] = (first = "one", second = 1)', '[2] = (first = "three", second = 3)', '[3] = (first = "two", second = 2)', '[4] = (first = "zero", second = 0)', - ]) + ], + ) self.expect( "expression si", substrs=[ - 'map has 5 items', + "map has 5 items", '[0] = (first = "four", second = 4)', '[1] = (first = "one", second = 1)', '[2] = (first = "three", second = 3)', '[3] = (first = "two", second = 2)', '[4] = (first = "zero", second = 0)', - ]) + ], + ) # check access-by-index - self.expect("frame variable si[0]", - substrs=['first = ', 'four', - 'second = 4']) + self.expect("frame variable si[0]", substrs=["first = ", "four", "second = 4"]) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("si").MightHaveChildren(), - "si.MightHaveChildren() says False for non empty!") + "si.MightHaveChildren() says False for non empty!", + ) # check that the expression parser does not make use of # synthetic children instead of running code @@ -188,45 +192,44 @@ self.runCmd("c") - self.expect('frame variable si', - substrs=['map has 0 items', - '{}']) + self.expect("frame variable si", substrs=["map has 0 items", "{}"]) self.runCmd("frame variable is --show-types") - self.expect('frame variable is', - substrs=['map has 0 items', - '{}']) + self.expect("frame variable is", substrs=["map has 0 items", "{}"]) self.runCmd("c") self.expect( "frame variable is", substrs=[ - 'map has 4 items', '[0] = (first = 1, second = "is")', + "map has 4 items", + '[0] = (first = 1, second = "is")', '[1] = (first = 2, second = "smart")', '[2] = (first = 3, second = "!!!")', - '[3] = (first = 85, second = "goofy")' - ]) + '[3] = (first = 85, second = "goofy")', + ], + ) self.expect( "expression is", substrs=[ - 'map has 4 items', '[0] = (first = 1, second = "is")', + "map has 4 items", + '[0] = (first = 1, second = "is")', '[1] = (first = 2, second = "smart")', '[2] = (first = 3, second = "!!!")', - '[3] = (first = 85, second = "goofy")' - ]) + '[3] = (first = 85, second = "goofy")', + ], + ) # check access-by-index - self.expect("frame variable is[0]", - substrs=['first = ', - 'second =']) + self.expect("frame variable is[0]", substrs=["first = ", "second ="]) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("is").MightHaveChildren(), - "is.MightHaveChildren() says False for non empty!") + "is.MightHaveChildren() says False for non empty!", + ) # check that the expression parser does not make use of # synthetic children instead of running code @@ -238,46 +241,44 @@ self.runCmd("c") - self.expect('frame variable is', - substrs=['map has 0 items', - '{}']) + self.expect("frame variable is", substrs=["map has 0 items", "{}"]) self.runCmd("frame variable ss --show-types") - self.expect('frame variable ss', - substrs=['map has 0 items', - '{}']) + self.expect("frame variable ss", substrs=["map has 0 items", "{}"]) self.runCmd("c") self.expect( "frame variable ss", substrs=[ - 'map has 4 items', + "map has 4 items", '[0] = (first = "a Mac..", second = "..is always a Mac!")', '[1] = (first = "casa", second = "house")', '[2] = (first = "ciao", second = "hello")', - '[3] = (first = "gatto", second = "cat")' - ]) + '[3] = (first = "gatto", second = "cat")', + ], + ) self.expect( "expression ss", substrs=[ - 'map has 4 items', + "map has 4 items", '[0] = (first = "a Mac..", second = "..is always a Mac!")', '[1] = (first = "casa", second = "house")', '[2] = (first = "ciao", second = "hello")', - '[3] = (first = "gatto", second = "cat")' - ]) + '[3] = (first = "gatto", second = "cat")', + ], + ) # check access-by-index - self.expect("frame variable ss[3]", - substrs=['gatto', 'cat']) + self.expect("frame variable ss[3]", substrs=["gatto", "cat"]) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("ss").MightHaveChildren(), - "ss.MightHaveChildren() says False for non empty!") + "ss.MightHaveChildren() says False for non empty!", + ) # check that the expression parser does not make use of # synthetic children instead of running code @@ -289,6 +290,4 @@ self.runCmd("c") - self.expect('frame variable ss', - substrs=['map has 0 items', - '{}']) + self.expect("frame variable ss", substrs=["map has 0 items", "{}"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/TestDataFormatterStdSmartPtr.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/TestDataFormatterStdSmartPtr.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/TestDataFormatterStdSmartPtr.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/TestDataFormatterStdSmartPtr.py @@ -10,42 +10,43 @@ class StdSmartPtrDataFormatterTestCase(TestBase): - @add_test_categories(["libstdcxx"]) @expectedFailureAll(bugnumber="llvm.org/pr50861", compiler="gcc") def test_with_run_command(self): self.build() self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp( - self, "Set break point at this line.") + lldbutil.run_break_set_by_source_regexp(self, "Set break point at this line.") self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) - - self.expect("frame variable nsp", substrs=['nsp = nullptr']) - self.expect("frame variable isp", substrs=['isp = 123']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) + + self.expect("frame variable nsp", substrs=["nsp = nullptr"]) + self.expect("frame variable isp", substrs=["isp = 123"]) self.expect("frame variable ssp", substrs=['ssp = "foobar"']) - self.expect("frame variable nwp", substrs=['nwp = nullptr']) - self.expect("frame variable iwp", substrs=['iwp = 123']) + self.expect("frame variable nwp", substrs=["nwp = nullptr"]) + self.expect("frame variable iwp", substrs=["iwp = 123"]) self.expect("frame variable swp", substrs=['swp = "foobar"']) - self.expect("frame variable *nsp", substrs=['*nsp = ']) - self.expect("frame variable *isp", substrs=['*isp = 123']) + self.expect("frame variable *nsp", substrs=["*nsp = "]) + self.expect("frame variable *isp", substrs=["*isp = 123"]) self.expect("frame variable *ssp", substrs=['*ssp = "foobar"']) - self.expect("frame variable *fsp", substrs=['*fsp = (mem = 5)']) + self.expect("frame variable *fsp", substrs=["*fsp = (mem = 5)"]) - self.expect("frame variable fsp->mem", substrs=['(int) fsp->mem = 5']) + self.expect("frame variable fsp->mem", substrs=["(int) fsp->mem = 5"]) self.runCmd("continue") - self.expect("frame variable nsp", substrs=['nsp = nullptr']) - self.expect("frame variable isp", substrs=['isp = nullptr']) - self.expect("frame variable ssp", substrs=['ssp = nullptr']) + self.expect("frame variable nsp", substrs=["nsp = nullptr"]) + self.expect("frame variable isp", substrs=["isp = nullptr"]) + self.expect("frame variable ssp", substrs=["ssp = nullptr"]) - self.expect("frame variable nwp", substrs=['nwp = nullptr']) - self.expect("frame variable iwp", substrs=['iwp = nullptr']) - self.expect("frame variable swp", substrs=['swp = nullptr']) + self.expect("frame variable nwp", substrs=["nwp = nullptr"]) + self.expect("frame variable iwp", substrs=["iwp = nullptr"]) + self.expect("frame variable swp", substrs=["swp = nullptr"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py @@ -4,7 +4,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -12,12 +11,11 @@ class StdStringDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") @add_test_categories(["libstdcxx"]) @expectedFailureAll(bugnumber="llvm.org/pr50861", compiler="gcc") @@ -27,74 +25,73 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=-1) + self, "main.cpp", self.line, num_expected_locations=-1 + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - var_wempty = self.frame().FindVariable('wempty') - var_s = self.frame().FindVariable('s') - var_S = self.frame().FindVariable('S') - var_mazeltov = self.frame().FindVariable('mazeltov') - var_empty = self.frame().FindVariable('empty') - var_q = self.frame().FindVariable('q') - var_Q = self.frame().FindVariable('Q') - var_rq = self.frame().FindVariable('rq') - var_rQ = self.frame().FindVariable('rQ') - var_pq = self.frame().FindVariable('pq') - var_pQ = self.frame().FindVariable('pQ') + var_wempty = self.frame().FindVariable("wempty") + var_s = self.frame().FindVariable("s") + var_S = self.frame().FindVariable("S") + var_mazeltov = self.frame().FindVariable("mazeltov") + var_empty = self.frame().FindVariable("empty") + var_q = self.frame().FindVariable("q") + var_Q = self.frame().FindVariable("Q") + var_rq = self.frame().FindVariable("rq") + var_rQ = self.frame().FindVariable("rQ") + var_pq = self.frame().FindVariable("pq") + var_pQ = self.frame().FindVariable("pQ") - var_uchar = self.frame().FindVariable('uchar') + var_uchar = self.frame().FindVariable("uchar") self.assertEqual(var_wempty.GetSummary(), 'L""', "wempty summary wrong") self.assertEqual( - var_s.GetSummary(), 'L"hello world! מזל טוב!"', - "s summary wrong") + var_s.GetSummary(), 'L"hello world! מזל טוב!"', "s summary wrong" + ) self.assertEqual(var_S.GetSummary(), 'L"!!!!"', "S summary wrong") self.assertEqual( - var_mazeltov.GetSummary(), 'L"מזל טוב"', - "mazeltov summary wrong") + var_mazeltov.GetSummary(), 'L"מזל טוב"', "mazeltov summary wrong" + ) self.assertEqual(var_empty.GetSummary(), '""', "empty summary wrong") + self.assertEqual(var_q.GetSummary(), '"hello world"', "q summary wrong") self.assertEqual( - var_q.GetSummary(), '"hello world"', - "q summary wrong") - self.assertEqual( - var_Q.GetSummary(), '"quite a long std::strin with lots of info inside it"', - "Q summary wrong") + var_Q.GetSummary(), + '"quite a long std::strin with lots of info inside it"', + "Q summary wrong", + ) self.assertEqual(var_uchar.GetSummary(), '"aaaaa"', "u summary wrong") + self.assertEqual(var_rq.GetSummary(), '"hello world"', "rq summary wrong") self.assertEqual( - var_rq.GetSummary(), '"hello world"', - "rq summary wrong") + var_rQ.GetSummary(), + '"quite a long std::strin with lots of info inside it"', + "rQ summary wrong", + ) + self.assertEqual(var_pq.GetSummary(), '"hello world"', "pq summary wrong") self.assertEqual( - var_rQ.GetSummary(), '"quite a long std::strin with lots of info inside it"', - "rQ summary wrong") - self.assertEqual( - var_pq.GetSummary(), '"hello world"', - "pq summary wrong") - self.assertEqual( - var_pQ.GetSummary(), '"quite a long std::strin with lots of info inside it"', - "pQ summary wrong") + var_pQ.GetSummary(), + '"quite a long std::strin with lots of info inside it"', + "pQ summary wrong", + ) self.runCmd("next") - self.assertEqual( - var_S.GetSummary(), 'L"!!!!!"', - "new S summary wrong") + self.assertEqual(var_S.GetSummary(), 'L"!!!!!"', "new S summary wrong") diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/TestDataFormatterStdTuple.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/TestDataFormatterStdTuple.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/TestDataFormatterStdTuple.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/TestDataFormatterStdTuple.py @@ -10,32 +10,35 @@ class StdTupleDataFormatterTestCase(TestBase): - @add_test_categories(["libstdcxx"]) @expectedFailureAll(bugnumber="llvm.org/pr50861", compiler="gcc") def test_with_run_command(self): self.build() self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp( - self, "Set break point at this line.") + lldbutil.run_break_set_by_source_regexp(self, "Set break point at this line.") self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) frame = self.frame() self.assertTrue(frame.IsValid()) - self.expect("frame variable ti", substrs=['[0] = 1']) + self.expect("frame variable ti", substrs=["[0] = 1"]) self.expect("frame variable ts", substrs=['[0] = "foobar"']) - self.expect("frame variable tt", substrs=['[0] = 1', '[1] = "baz"', '[2] = 2']) + self.expect("frame variable tt", substrs=["[0] = 1", '[1] = "baz"', "[2] = 2"]) self.assertEqual(1, frame.GetValueForVariablePath("ti[0]").GetValueAsUnsigned()) self.assertFalse(frame.GetValueForVariablePath("ti[1]").IsValid()) - self.assertEqual('"foobar"', frame.GetValueForVariablePath("ts[0]").GetSummary()) + self.assertEqual( + '"foobar"', frame.GetValueForVariablePath("ts[0]").GetSummary() + ) self.assertFalse(frame.GetValueForVariablePath("ts[1]").IsValid()) self.assertEqual(1, frame.GetValueForVariablePath("tt[0]").GetValueAsUnsigned()) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/TestDataFormatterStdUniquePtr.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/TestDataFormatterStdUniquePtr.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/TestDataFormatterStdUniquePtr.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/TestDataFormatterStdUniquePtr.py @@ -10,7 +10,6 @@ class StdUniquePtrDataFormatterTestCase(TestBase): - @add_test_categories(["libstdcxx"]) @expectedFailureAll(bugnumber="llvm.org/pr50861", compiler="gcc") @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) @@ -18,47 +17,73 @@ self.build() self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp( - self, "Set break point at this line.") + lldbutil.run_break_set_by_source_regexp(self, "Set break point at this line.") self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) frame = self.frame() self.assertTrue(frame.IsValid()) - self.expect("frame variable nup", substrs=['nup = nullptr']) - self.expect("frame variable iup", substrs=['iup = 0x']) - self.expect("frame variable sup", substrs=['sup = 0x']) - - self.expect("frame variable ndp", substrs=['ndp = nullptr']) - self.expect("frame variable idp", substrs=['idp = 0x', 'deleter = ', 'a = 1', 'b = 2']) - self.expect("frame variable sdp", substrs=['sdp = 0x', 'deleter = ', 'a = 3', 'b = 4']) - - self.assertEqual(123, frame.GetValueForVariablePath("iup.object").GetValueAsUnsigned()) - self.assertEqual(123, frame.GetValueForVariablePath("*iup").GetValueAsUnsigned()) + self.expect("frame variable nup", substrs=["nup = nullptr"]) + self.expect("frame variable iup", substrs=["iup = 0x"]) + self.expect("frame variable sup", substrs=["sup = 0x"]) + + self.expect("frame variable ndp", substrs=["ndp = nullptr"]) + self.expect( + "frame variable idp", substrs=["idp = 0x", "deleter = ", "a = 1", "b = 2"] + ) + self.expect( + "frame variable sdp", substrs=["sdp = 0x", "deleter = ", "a = 3", "b = 4"] + ) + + self.assertEqual( + 123, frame.GetValueForVariablePath("iup.object").GetValueAsUnsigned() + ) + self.assertEqual( + 123, frame.GetValueForVariablePath("*iup").GetValueAsUnsigned() + ) self.assertFalse(frame.GetValueForVariablePath("iup.deleter").IsValid()) - self.assertEqual('"foobar"', frame.GetValueForVariablePath("sup.object").GetSummary()) + self.assertEqual( + '"foobar"', frame.GetValueForVariablePath("sup.object").GetSummary() + ) self.assertEqual('"foobar"', frame.GetValueForVariablePath("*sup").GetSummary()) self.assertFalse(frame.GetValueForVariablePath("sup.deleter").IsValid()) - self.assertEqual(456, frame.GetValueForVariablePath("idp.object").GetValueAsUnsigned()) - self.assertEqual(456, frame.GetValueForVariablePath("*idp").GetValueAsUnsigned()) - self.assertEqual('"baz"', frame.GetValueForVariablePath("sdp.object").GetSummary()) + self.assertEqual( + 456, frame.GetValueForVariablePath("idp.object").GetValueAsUnsigned() + ) + self.assertEqual( + 456, frame.GetValueForVariablePath("*idp").GetValueAsUnsigned() + ) + self.assertEqual( + '"baz"', frame.GetValueForVariablePath("sdp.object").GetSummary() + ) self.assertEqual('"baz"', frame.GetValueForVariablePath("*sdp").GetSummary()) idp_deleter = frame.GetValueForVariablePath("idp.deleter") self.assertTrue(idp_deleter.IsValid()) - self.assertEqual(1, idp_deleter.GetChildMemberWithName("a").GetValueAsUnsigned()) - self.assertEqual(2, idp_deleter.GetChildMemberWithName("b").GetValueAsUnsigned()) + self.assertEqual( + 1, idp_deleter.GetChildMemberWithName("a").GetValueAsUnsigned() + ) + self.assertEqual( + 2, idp_deleter.GetChildMemberWithName("b").GetValueAsUnsigned() + ) sdp_deleter = frame.GetValueForVariablePath("sdp.deleter") self.assertTrue(sdp_deleter.IsValid()) - self.assertEqual(3, sdp_deleter.GetChildMemberWithName("a").GetValueAsUnsigned()) - self.assertEqual(4, sdp_deleter.GetChildMemberWithName("b").GetValueAsUnsigned()) + self.assertEqual( + 3, sdp_deleter.GetChildMemberWithName("a").GetValueAsUnsigned() + ) + self.assertEqual( + 4, sdp_deleter.GetChildMemberWithName("b").GetValueAsUnsigned() + ) @skipIfFreeBSD @skipIfWindows # libstdcpp not ported to Windows @@ -73,22 +98,37 @@ self.build() self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp( - self, "Set break point at this line.") + lldbutil.run_break_set_by_source_regexp(self, "Set break point at this line.") self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', 'stop reason = breakpoint']) - - self.expect("frame variable f1->fp", - substrs=['fp = 0x']) - self.expect("frame variable --ptr-depth=1 f1->fp", - substrs=['data = 2', 'fp = 0x']) - self.expect("frame variable --ptr-depth=2 f1->fp", - substrs=['data = 2', 'fp = 0x', 'data = 1']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) + + self.expect("frame variable f1->fp", substrs=["fp = 0x"]) + self.expect( + "frame variable --ptr-depth=1 f1->fp", substrs=["data = 2", "fp = 0x"] + ) + self.expect( + "frame variable --ptr-depth=2 f1->fp", + substrs=["data = 2", "fp = 0x", "data = 1"], + ) frame = self.frame() self.assertTrue(frame.IsValid()) - self.assertEqual(2, frame.GetValueForVariablePath("f1->fp.object.data").GetValueAsUnsigned()) - self.assertEqual(2, frame.GetValueForVariablePath("f1->fp->data").GetValueAsUnsigned()) - self.assertEqual(1, frame.GetValueForVariablePath("f1->fp.object.fp.object.data").GetValueAsUnsigned()) - self.assertEqual(1, frame.GetValueForVariablePath("f1->fp->fp->data").GetValueAsUnsigned()) + self.assertEqual( + 2, frame.GetValueForVariablePath("f1->fp.object.data").GetValueAsUnsigned() + ) + self.assertEqual( + 2, frame.GetValueForVariablePath("f1->fp->data").GetValueAsUnsigned() + ) + self.assertEqual( + 1, + frame.GetValueForVariablePath( + "f1->fp.object.fp.object.data" + ).GetValueAsUnsigned(), + ) + self.assertEqual( + 1, frame.GetValueForVariablePath("f1->fp->fp->data").GetValueAsUnsigned() + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/invalid/TestDataFormatterInvalidStdUniquePtr.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/invalid/TestDataFormatterInvalidStdUniquePtr.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/invalid/TestDataFormatterInvalidStdUniquePtr.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/invalid/TestDataFormatterInvalidStdUniquePtr.py @@ -2,4 +2,3 @@ from lldbsuite.test.decorators import * lldbinline.MakeInlineTest(__file__, globals(), [no_debug_info_test]) - diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class StdVBoolDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") @add_test_categories(["libstdcxx"]) def test_with_run_command(self): @@ -25,25 +23,26 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=-1) + self, "main.cpp", self.line, num_expected_locations=-1 + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -51,23 +50,27 @@ self.expect( "frame variable vBool", substrs=[ - 'size=49', - '[0] = false', - '[1] = true', - '[18] = false', - '[27] = true', - '[36] = false', - '[47] = true', - '[48] = true']) + "size=49", + "[0] = false", + "[1] = true", + "[18] = false", + "[27] = true", + "[36] = false", + "[47] = true", + "[48] = true", + ], + ) self.expect( "expr vBool", substrs=[ - 'size=49', - '[0] = false', - '[1] = true', - '[18] = false', - '[27] = true', - '[36] = false', - '[47] = true', - '[48] = true']) + "size=49", + "[0] = false", + "[1] = true", + "[18] = false", + "[27] = true", + "[36] = false", + "[47] = true", + "[48] = true", + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class StdVectorDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") @add_test_categories(["libstdcxx"]) @expectedFailureAll(bugnumber="llvm.org/pr50861", compiler="gcc") @@ -25,73 +23,79 @@ self.build() self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp( - self, "Set break point at this line.") + lldbutil.run_break_set_by_source_regexp(self, "Set break point at this line.") self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # empty vectors (and storage pointers SHOULD BOTH BE NULL..) - self.expect("frame variable numbers", - substrs=['numbers = size=0']) + self.expect("frame variable numbers", substrs=["numbers = size=0"]) self.runCmd("c") # first value added - self.expect("frame variable numbers", - substrs=['numbers = size=1', - '[0] = 1', - '}']) + self.expect( + "frame variable numbers", substrs=["numbers = size=1", "[0] = 1", "}"] + ) # add some more data self.runCmd("c") - self.expect("frame variable numbers", - substrs=['numbers = size=4', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '}']) - - self.expect("expression numbers", - substrs=['$', 'size=4', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '}']) + self.expect( + "frame variable numbers", + substrs=[ + "numbers = size=4", + "[0] = 1", + "[1] = 12", + "[2] = 123", + "[3] = 1234", + "}", + ], + ) + + self.expect( + "expression numbers", + substrs=[ + "$", + "size=4", + "[0] = 1", + "[1] = 12", + "[2] = 123", + "[3] = 1234", + "}", + ], + ) # check access to synthetic children self.runCmd( - "type summary add --summary-string \"item 0 is ${var[0]}\" std::int_vect int_vect") - self.expect('frame variable numbers', - substrs=['item 0 is 1']) + 'type summary add --summary-string "item 0 is ${var[0]}" std::int_vect int_vect' + ) + self.expect("frame variable numbers", substrs=["item 0 is 1"]) self.runCmd( - "type summary add --summary-string \"item 0 is ${svar[0]}\" std::int_vect int_vect") - #import time + 'type summary add --summary-string "item 0 is ${svar[0]}" std::int_vect int_vect' + ) + # import time # time.sleep(19) - self.expect('frame variable numbers', - substrs=['item 0 is 1']) + self.expect("frame variable numbers", substrs=["item 0 is 1"]) # move on with synths self.runCmd("type summary delete std::int_vect") self.runCmd("type summary delete int_vect") @@ -99,114 +103,109 @@ # add some more data self.runCmd("c") - self.expect("frame variable numbers", - substrs=['numbers = size=7', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '[4] = 12345', - '[5] = 123456', - '[6] = 1234567', - '}']) - - self.expect("expression numbers", - substrs=['$', 'size=7', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '[4] = 12345', - '[5] = 123456', - '[6] = 1234567', - '}']) + self.expect( + "frame variable numbers", + substrs=[ + "numbers = size=7", + "[0] = 1", + "[1] = 12", + "[2] = 123", + "[3] = 1234", + "[4] = 12345", + "[5] = 123456", + "[6] = 1234567", + "}", + ], + ) + + self.expect( + "expression numbers", + substrs=[ + "$", + "size=7", + "[0] = 1", + "[1] = 12", + "[2] = 123", + "[3] = 1234", + "[4] = 12345", + "[5] = 123456", + "[6] = 1234567", + "}", + ], + ) # check access-by-index - self.expect("frame variable numbers[0]", - substrs=['1']) - self.expect("frame variable numbers[1]", - substrs=['12']) - self.expect("frame variable numbers[2]", - substrs=['123']) - self.expect("frame variable numbers[3]", - substrs=['1234']) + self.expect("frame variable numbers[0]", substrs=["1"]) + self.expect("frame variable numbers[1]", substrs=["12"]) + self.expect("frame variable numbers[2]", substrs=["123"]) + self.expect("frame variable numbers[3]", substrs=["1234"]) # but check that expression does not rely on us # (when expression gets to call into STL code correctly, we will have to find # another way to check this) - self.expect("expression numbers[6]", matching=False, error=True, - substrs=['1234567']) + self.expect( + "expression numbers[6]", matching=False, error=True, substrs=["1234567"] + ) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("numbers").MightHaveChildren(), - "numbers.MightHaveChildren() says False for non empty!") + "numbers.MightHaveChildren() says False for non empty!", + ) # clear out the vector and see that we do the right thing once again self.runCmd("c") - self.expect("frame variable numbers", - substrs=['numbers = size=0']) + self.expect("frame variable numbers", substrs=["numbers = size=0"]) self.runCmd("c") # first value added - self.expect("frame variable numbers", - substrs=['numbers = size=1', - '[0] = 7', - '}']) + self.expect( + "frame variable numbers", substrs=["numbers = size=1", "[0] = 7", "}"] + ) # check if we can display strings self.runCmd("c") - self.expect("frame variable strings", - substrs=['goofy', - 'is', - 'smart']) + self.expect("frame variable strings", substrs=["goofy", "is", "smart"]) - self.expect("expression strings", - substrs=['goofy', - 'is', - 'smart']) + self.expect("expression strings", substrs=["goofy", "is", "smart"]) # test summaries based on synthetic children self.runCmd( - "type summary add std::string_vect string_vect --summary-string \"vector has ${svar%#} items\" -e") - self.expect("frame variable strings", - substrs=['vector has 3 items', - 'goofy', - 'is', - 'smart']) - - self.expect("expression strings", - substrs=['vector has 3 items', - 'goofy', - 'is', - 'smart']) + 'type summary add std::string_vect string_vect --summary-string "vector has ${svar%#} items" -e' + ) + self.expect( + "frame variable strings", + substrs=["vector has 3 items", "goofy", "is", "smart"], + ) + + self.expect( + "expression strings", substrs=["vector has 3 items", "goofy", "is", "smart"] + ) self.runCmd("c") - self.expect("frame variable strings", - substrs=['vector has 4 items']) + self.expect("frame variable strings", substrs=["vector has 4 items"]) # check access-by-index - self.expect("frame variable strings[0]", - substrs=['goofy']) - self.expect("frame variable strings[1]", - substrs=['is']) + self.expect("frame variable strings[0]", substrs=["goofy"]) + self.expect("frame variable strings[1]", substrs=["is"]) # but check that expression does not rely on us # (when expression gets to call into STL code correctly, we will have to find # another way to check this) - self.expect("expression strings[0]", matching=False, error=True, - substrs=['goofy']) + self.expect( + "expression strings[0]", matching=False, error=True, substrs=["goofy"] + ) # check that MightHaveChildren() gets it right self.assertTrue( self.frame().FindVariable("strings").MightHaveChildren(), - "strings.MightHaveChildren() says False for non empty!") + "strings.MightHaveChildren() says False for non empty!", + ) self.runCmd("c") - self.expect("frame variable strings", - substrs=['vector has 0 items']) + self.expect("frame variable strings", substrs=["vector has 0 items"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py b/lldb/test/API/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py @@ -3,19 +3,17 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class SynthDataFormatterTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" @@ -23,193 +21,187 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # Pick some values and check that the basics work self.runCmd("type filter add BagOfInts --child x --child z") - self.expect("frame variable int_bag", - substrs=['x = 6', - 'z = 8']) + self.expect("frame variable int_bag", substrs=["x = 6", "z = 8"]) # Check we can still access the missing child by summary - self.runCmd( - "type summary add BagOfInts --summary-string \"y=${var.y}\"") - self.expect('frame variable int_bag', - substrs=['y=7']) + self.runCmd('type summary add BagOfInts --summary-string "y=${var.y}"') + self.expect("frame variable int_bag", substrs=["y=7"]) # Even if we have synth children, the summary prevails - self.expect("frame variable int_bag", matching=False, - substrs=['x = 6', - 'z = 8']) + self.expect( + "frame variable int_bag", matching=False, substrs=["x = 6", "z = 8"] + ) # if we skip synth and summary show y self.expect( "frame variable int_bag --synthetic-type false --no-summary-depth=1", - substrs=[ - 'x = 6', - 'y = 7', - 'z = 8']) + substrs=["x = 6", "y = 7", "z = 8"], + ) # if we ask for raw output same happens - self.expect("frame variable int_bag --raw-output", - substrs=['x = 6', - 'y = 7', - 'z = 8']) + self.expect( + "frame variable int_bag --raw-output", substrs=["x = 6", "y = 7", "z = 8"] + ) # Summary+Synth must work together - self.runCmd( - "type summary add BagOfInts --summary-string \"x=${var.x}\" -e") - self.expect('frame variable int_bag', - substrs=['x=6', - 'x = 6', - 'z = 8']) + self.runCmd('type summary add BagOfInts --summary-string "x=${var.x}" -e') + self.expect("frame variable int_bag", substrs=["x=6", "x = 6", "z = 8"]) # Same output, but using Python self.runCmd( - "type summary add BagOfInts --python-script \"return 'x=%s' % valobj.GetChildMemberWithName('x').GetValue()\" -e") - self.expect('frame variable int_bag', - substrs=['x=6', - 'x = 6', - 'z = 8']) + "type summary add BagOfInts --python-script \"return 'x=%s' % valobj.GetChildMemberWithName('x').GetValue()\" -e" + ) + self.expect("frame variable int_bag", substrs=["x=6", "x = 6", "z = 8"]) # If I skip summaries, still give me the artificial children - self.expect("frame variable int_bag --no-summary-depth=1", - substrs=['x = 6', - 'z = 8']) + self.expect( + "frame variable int_bag --no-summary-depth=1", substrs=["x = 6", "z = 8"] + ) # Delete synth and check that the view reflects it immediately self.runCmd("type filter delete BagOfInts") - self.expect("frame variable int_bag", - substrs=['x = 6', - 'y = 7', - 'z = 8']) + self.expect("frame variable int_bag", substrs=["x = 6", "y = 7", "z = 8"]) # Add the synth again and check that it's honored deeper in the # hierarchy self.runCmd("type filter add BagOfInts --child x --child z") - self.expect('frame variable bag_bag', - substrs=['x = x=69 {', - 'x = 69', - 'z = 71', - 'y = x=66 {', - 'x = 66', - 'z = 68']) - self.expect('frame variable bag_bag', matching=False, - substrs=['y = 70', - 'y = 67']) + self.expect( + "frame variable bag_bag", + substrs=[ + "x = x=69 {", + "x = 69", + "z = 71", + "y = x=66 {", + "x = 66", + "z = 68", + ], + ) + self.expect( + "frame variable bag_bag", matching=False, substrs=["y = 70", "y = 67"] + ) # Check that a synth can expand nested stuff self.runCmd("type filter add BagOfBags --child x.y --child y.z") - self.expect('frame variable bag_bag', - substrs=['x.y = 70', - 'y.z = 68']) + self.expect("frame variable bag_bag", substrs=["x.y = 70", "y.z = 68"]) # ...even if we get -> and . wrong - self.runCmd("type filter add BagOfBags --child x.y --child \"y->z\"") - self.expect('frame variable bag_bag', - substrs=['x.y = 70', - 'y->z = 68']) + self.runCmd('type filter add BagOfBags --child x.y --child "y->z"') + self.expect("frame variable bag_bag", substrs=["x.y = 70", "y->z = 68"]) # ...even bitfields - self.runCmd( - "type filter add BagOfBags --child x.y --child \"y->z[1-2]\"") - self.expect('frame variable bag_bag --show-types', - substrs=['x.y = 70', - '(int:2) y->z[1-2] = 2']) + self.runCmd('type filter add BagOfBags --child x.y --child "y->z[1-2]"') + self.expect( + "frame variable bag_bag --show-types", + substrs=["x.y = 70", "(int:2) y->z[1-2] = 2"], + ) # ...even if we format the bitfields - self.runCmd( - "type filter add BagOfBags --child x.y --child \"y->y[0-0]\"") - self.runCmd("type format add \"int:1\" -f bool") - self.expect('frame variable bag_bag --show-types', - substrs=['x.y = 70', - '(int:1) y->y[0-0] = true']) + self.runCmd('type filter add BagOfBags --child x.y --child "y->y[0-0]"') + self.runCmd('type format add "int:1" -f bool') + self.expect( + "frame variable bag_bag --show-types", + substrs=["x.y = 70", "(int:1) y->y[0-0] = true"], + ) # ...even if we use one-liner summaries self.runCmd("type summary add -c BagOfBags") - self.expect('frame variable bag_bag', substrs=[ - '(BagOfBags) bag_bag = (x.y = 70, y->y[0-0] = true)']) + self.expect( + "frame variable bag_bag", + substrs=["(BagOfBags) bag_bag = (x.y = 70, y->y[0-0] = true)"], + ) self.runCmd("type summary delete BagOfBags") # now check we are dynamic (and arrays work) self.runCmd( - "type filter add Plenty --child bitfield --child array[0] --child array[2]") - self.expect('frame variable plenty_of_stuff', - substrs=['bitfield = 1', - 'array[0] = 5', - 'array[2] = 3']) + "type filter add Plenty --child bitfield --child array[0] --child array[2]" + ) + self.expect( + "frame variable plenty_of_stuff", + substrs=["bitfield = 1", "array[0] = 5", "array[2] = 3"], + ) self.runCmd("n") - self.expect('frame variable plenty_of_stuff', - substrs=['bitfield = 17', - 'array[0] = 5', - 'array[2] = 3']) + self.expect( + "frame variable plenty_of_stuff", + substrs=["bitfield = 17", "array[0] = 5", "array[2] = 3"], + ) # skip synthetic children - self.expect('frame variable plenty_of_stuff --synthetic-type no', - substrs=['some_values = 0x', - 'array = 0x', - 'array_size = 5']) + self.expect( + "frame variable plenty_of_stuff --synthetic-type no", + substrs=["some_values = 0x", "array = 0x", "array_size = 5"], + ) # check flat printing with synthetic children - self.expect('frame variable plenty_of_stuff --flat', - substrs=['plenty_of_stuff.bitfield = 17', - '*(plenty_of_stuff.array) = 5', - '*(plenty_of_stuff.array) = 3']) + self.expect( + "frame variable plenty_of_stuff --flat", + substrs=[ + "plenty_of_stuff.bitfield = 17", + "*(plenty_of_stuff.array) = 5", + "*(plenty_of_stuff.array) = 3", + ], + ) # check that we do not lose location information for our children - self.expect('frame variable plenty_of_stuff --location', - substrs=['0x', - ': bitfield = 17']) + self.expect( + "frame variable plenty_of_stuff --location", + substrs=["0x", ": bitfield = 17"], + ) # check we work across pointer boundaries - self.expect('frame variable plenty_of_stuff.some_values --ptr-depth=1', - substrs=['(BagOfInts *) plenty_of_stuff.some_values', - 'x = 5', - 'z = 7']) + self.expect( + "frame variable plenty_of_stuff.some_values --ptr-depth=1", + substrs=["(BagOfInts *) plenty_of_stuff.some_values", "x = 5", "z = 7"], + ) # but not if we don't want to self.runCmd("type filter add BagOfInts --child x --child z -p") - self.expect('frame variable plenty_of_stuff.some_values --ptr-depth=1', - substrs=['(BagOfInts *) plenty_of_stuff.some_values', - 'x = 5', - 'y = 6', - 'z = 7']) + self.expect( + "frame variable plenty_of_stuff.some_values --ptr-depth=1", + substrs=[ + "(BagOfInts *) plenty_of_stuff.some_values", + "x = 5", + "y = 6", + "z = 7", + ], + ) # check we're dynamic even if nested self.runCmd("type filter add BagOfBags --child x.z") - self.expect('frame variable bag_bag', - substrs=['x.z = 71']) + self.expect("frame variable bag_bag", substrs=["x.z = 71"]) self.runCmd("n") - self.expect('frame variable bag_bag', - substrs=['x.z = 12']) + self.expect("frame variable bag_bag", substrs=["x.z = 12"]) - self.runCmd( - 'type summary add -e -s "I am always empty but have" EmptyStruct') - self.expect('frame variable es', substrs=[ - "I am always empty but have {}"]) + self.runCmd('type summary add -e -s "I am always empty but have" EmptyStruct') + self.expect("frame variable es", substrs=["I am always empty but have {}"]) self.runCmd('type summary add -e -h -s "I am really empty" EmptyStruct') - self.expect('frame variable es', substrs=["I am really empty"]) + self.expect("frame variable es", substrs=["I am really empty"]) self.expect( - 'frame variable es', - substrs=["I am really empty {}"], - matching=False) + "frame variable es", substrs=["I am really empty {}"], matching=False + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-synthtype/TestDataFormatterSynthType.py b/lldb/test/API/functionalities/data-formatter/data-formatter-synthtype/TestDataFormatterSynthType.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-synthtype/TestDataFormatterSynthType.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-synthtype/TestDataFormatterSynthType.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class DataFormatterSynthTypeTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', 'break here') + self.line = line_number("main.cpp", "break here") def test_with_run_command(self): """Test using Python synthetic children provider to provide a typename.""" @@ -24,22 +22,25 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -47,6 +48,6 @@ self.runCmd("script from myIntSynthProvider import *") self.runCmd("type synth add -l myIntSynthProvider myInt") - self.expect('frame variable x', substrs=['ThisTestPasses']) - self.expect('frame variable y', substrs=['ThisTestPasses']) - self.expect('frame variable z', substrs=['ThisTestPasses']) + self.expect("frame variable x", substrs=["ThisTestPasses"]) + self.expect("frame variable y", substrs=["ThisTestPasses"]) + self.expect("frame variable z", substrs=["ThisTestPasses"]) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-synthtype/myIntSynthProvider.py b/lldb/test/API/functionalities/data-formatter/data-formatter-synthtype/myIntSynthProvider.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-synthtype/myIntSynthProvider.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-synthtype/myIntSynthProvider.py @@ -1,5 +1,4 @@ class myIntSynthProvider(object): - def __init__(self, valobj, dict): self.valobj = valobj self.val = self.valobj.GetChildMemberWithName("theValue") @@ -24,7 +23,6 @@ class myArraySynthProvider(object): - def __init__(self, valobj, dict): self.valobj = valobj self.array = self.valobj.GetChildMemberWithName("array") diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py b/lldb/test/API/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py @@ -9,12 +9,11 @@ class DataFormatterSynthValueTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', 'break here') + self.line = line_number("main.cpp", "break here") @expectedFailureAll(bugnumber="llvm.org/pr50814", compiler="gcc") def test_with_run_command(self): @@ -23,22 +22,25 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -59,8 +61,9 @@ if self.TraceOn(): print( - "x_val = %s; y_val = %s; z_val = %s; q_val = %s" % - (x_val(), y_val(), z_val(), q_val())) + "x_val = %s; y_val = %s; z_val = %s; q_val = %s" + % (x_val(), y_val(), z_val(), q_val()) + ) self.assertNotEqual(x_val(), 3, "x == 3 before synthetics") self.assertNotEqual(y_val(), 4, "y == 4 before synthetics") @@ -75,31 +78,27 @@ if self.TraceOn(): print( - "x_val = %s; y_val = %s; z_val = %s; q_val = %s" % - (x_val(), y_val(), z_val(), q_val())) + "x_val = %s; y_val = %s; z_val = %s; q_val = %s" + % (x_val(), y_val(), z_val(), q_val()) + ) self.assertEqual(x_val(), 3, "x != 3 after synthetics") self.assertEqual(y_val(), 4, "y != 4 after synthetics") self.assertEqual(z_val(), 7, "z != 7 after synthetics") self.assertEqual(q_val(), 8, "q != 8 after synthetics") - self.expect("frame variable x", substrs=['3']) - self.expect( - "frame variable x", - substrs=['theValue = 3'], - matching=False) - self.expect("frame variable q", substrs=['8']) - self.expect( - "frame variable q", - substrs=['theValue = 8'], - matching=False) + self.expect("frame variable x", substrs=["3"]) + self.expect("frame variable x", substrs=["theValue = 3"], matching=False) + self.expect("frame variable q", substrs=["8"]) + self.expect("frame variable q", substrs=["theValue = 8"], matching=False) # check that an aptly defined synthetic provider does not affect # one-lining if not self.isAArch64Windows(): self.expect( "expression struct Struct { myInt theInt{12}; }; Struct()", - substrs=['(theInt = 12)']) + substrs=["(theInt = 12)"], + ) # check that we can use a synthetic value in a summary self.runCmd("type summary add hasAnInt -s ${var.theInt}") diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py b/lldb/test/API/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py --- a/lldb/test/API/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py @@ -1,5 +1,4 @@ class myIntSynthProvider(object): - def __init__(self, valobj, dict): self.valobj = valobj self.val = self.valobj.GetChildMemberWithName("theValue") @@ -24,7 +23,6 @@ class myArraySynthProvider(object): - def __init__(self, valobj, dict): self.valobj = valobj self.array = self.valobj.GetChildMemberWithName("array") diff --git a/lldb/test/API/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py b/lldb/test/API/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py --- a/lldb/test/API/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py +++ b/lldb/test/API/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py @@ -1,6 +1,7 @@ from lldbsuite.test import lldbinline lldbinline.MakeInlineTest( - __file__, globals(), [ - lldbinline.expectedFailureAll( - oslist=["windows"], bugnumber="llvm.org/pr24663")]) + __file__, + globals(), + [lldbinline.expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24663")], +) diff --git a/lldb/test/API/functionalities/data-formatter/format-propagation/TestFormatPropagation.py b/lldb/test/API/functionalities/data-formatter/format-propagation/TestFormatPropagation.py --- a/lldb/test/API/functionalities/data-formatter/format-propagation/TestFormatPropagation.py +++ b/lldb/test/API/functionalities/data-formatter/format-propagation/TestFormatPropagation.py @@ -3,19 +3,17 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class FormatPropagationTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") # rdar://problem/14035604 def test_with_run_command(self): @@ -24,14 +22,17 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -44,9 +45,7 @@ # extract the parent and the children frame = self.frame() parent = self.frame().FindVariable("f") - self.assertTrue( - parent is not None and parent.IsValid(), - "could not find f") + self.assertTrue(parent is not None and parent.IsValid(), "could not find f") X = parent.GetChildMemberWithName("X") self.assertTrue(X is not None and X.IsValid(), "could not find X") Y = parent.GetChildMemberWithName("Y") @@ -56,12 +55,8 @@ self.assertEquals(Y.GetValue(), "2", "Y has an invalid value") # set the format on the parent parent.SetFormat(lldb.eFormatHex) - self.assertEqual( - X.GetValue(), "0x00000001", - "X has not changed format") - self.assertEqual( - Y.GetValue(), "0x00000002", - "Y has not changed format") + self.assertEqual(X.GetValue(), "0x00000001", "X has not changed format") + self.assertEqual(Y.GetValue(), "0x00000002", "Y has not changed format") # Step and check if the values make sense still self.runCmd("next") self.assertEquals(X.GetValue(), "0x00000004", "X has not become 4") @@ -74,7 +69,5 @@ parent.SetFormat(lldb.eFormatDefault) X.SetFormat(lldb.eFormatHex) Y.SetFormat(lldb.eFormatDefault) - self.assertEqual( - X.GetValue(), "0x00000004", - "X is not hex as it asked") + self.assertEqual(X.GetValue(), "0x00000004", "X is not hex as it asked") self.assertEquals(Y.GetValue(), "2", "Y is not defaulted") diff --git a/lldb/test/API/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py b/lldb/test/API/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py --- a/lldb/test/API/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py +++ b/lldb/test/API/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py @@ -3,19 +3,17 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class FrameFormatSmallStructTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Test that the user can input a format but it will not prevail over summary format's choices.""" @@ -23,13 +21,16 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) - self.expect("thread list", substrs=['addPair(p=(x = 3, y = -3))']) + self.expect("thread list", substrs=["addPair(p=(x = 3, y = -3))"]) diff --git a/lldb/test/API/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py b/lldb/test/API/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py --- a/lldb/test/API/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py +++ b/lldb/test/API/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py @@ -3,19 +3,17 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class DataFormatterHexCapsTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" @@ -23,62 +21,67 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format delete hex', check=False) - self.runCmd('type summary clear', check=False) + self.runCmd("type format delete hex", check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.runCmd("type format add -f uppercase int") - self.expect('frame variable mine', - substrs=['mine = ', - 'first = 0x001122AA', 'second = 0x1122BB44']) + self.expect( + "frame variable mine", + substrs=["mine = ", "first = 0x001122AA", "second = 0x1122BB44"], + ) self.runCmd("type format add -f hex int") - self.expect('frame variable mine', - substrs=['mine = ', - 'first = 0x001122aa', 'second = 0x1122bb44']) + self.expect( + "frame variable mine", + substrs=["mine = ", "first = 0x001122aa", "second = 0x1122bb44"], + ) self.runCmd("type format delete int") - self.runCmd( - "type summary add -s \"${var.first%X} and ${var.second%x}\" foo") + self.runCmd('type summary add -s "${var.first%X} and ${var.second%x}" foo') - self.expect('frame variable mine', - substrs=['(foo) mine = 0x001122AA and 0x1122bb44']) + self.expect( + "frame variable mine", substrs=["(foo) mine = 0x001122AA and 0x1122bb44"] + ) - self.runCmd( - "type summary add -s \"${var.first%X} and ${var.second%X}\" foo") + self.runCmd('type summary add -s "${var.first%X} and ${var.second%X}" foo') self.runCmd("next") self.runCmd("next") - self.expect('frame variable mine', - substrs=['(foo) mine = 0xAABBCCDD and 0x1122BB44']) - - self.runCmd( - "type summary add -s \"${var.first%x} and ${var.second%X}\" foo") - self.expect('frame variable mine', - substrs=['(foo) mine = 0xaabbccdd and 0x1122BB44']) + self.expect( + "frame variable mine", substrs=["(foo) mine = 0xAABBCCDD and 0x1122BB44"] + ) + + self.runCmd('type summary add -s "${var.first%x} and ${var.second%X}" foo') + self.expect( + "frame variable mine", substrs=["(foo) mine = 0xaabbccdd and 0x1122BB44"] + ) self.runCmd("next") self.runCmd("next") - self.runCmd( - "type summary add -s \"${var.first%x} and ${var.second%x}\" foo") - self.expect('frame variable mine', - substrs=['(foo) mine = 0xaabbccdd and 0xff00ff00']) - self.runCmd( - "type summary add -s \"${var.first%X} and ${var.second%X}\" foo") - self.expect('frame variable mine', - substrs=['(foo) mine = 0xAABBCCDD and 0xFF00FF00']) + self.runCmd('type summary add -s "${var.first%x} and ${var.second%x}" foo') + self.expect( + "frame variable mine", substrs=["(foo) mine = 0xaabbccdd and 0xff00ff00"] + ) + self.runCmd('type summary add -s "${var.first%X} and ${var.second%X}" foo') + self.expect( + "frame variable mine", substrs=["(foo) mine = 0xAABBCCDD and 0xFF00FF00"] + ) diff --git a/lldb/test/API/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py b/lldb/test/API/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py --- a/lldb/test/API/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py +++ b/lldb/test/API/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py @@ -3,30 +3,25 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class LanguageCategoryUpdatesTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// break here') + self.line = line_number("main.cpp", "// break here") def test_with_run_command(self): """Test that LLDB correctly cleans caches when language categories change.""" + # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - if hasattr( - self, - 'type_category') and hasattr( - self, - 'type_specifier'): + if hasattr(self, "type_category") and hasattr(self, "type_specifier"): self.type_category.DeleteTypeSummary(self.type_specifier) # Execute the cleanup function during test case tear down. @@ -36,46 +31,37 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) self.expect( - "frame variable", - substrs=[ - '(S)', - 'object', - '123', - '456'], - matching=True) + "frame variable", substrs=["(S)", "object", "123", "456"], matching=True + ) - self.type_category = self.dbg.GetCategory( - lldb.eLanguageTypeC_plus_plus) + self.type_category = self.dbg.GetCategory(lldb.eLanguageTypeC_plus_plus) type_summary = lldb.SBTypeSummary.CreateWithSummaryString( - "this is an object of type S") - self.type_specifier = lldb.SBTypeNameSpecifier('S') + "this is an object of type S" + ) + self.type_specifier = lldb.SBTypeNameSpecifier("S") self.type_category.AddTypeSummary(self.type_specifier, type_summary) self.expect( - "frame variable", - substrs=['this is an object of type S'], - matching=True) + "frame variable", substrs=["this is an object of type S"], matching=True + ) self.type_category.DeleteTypeSummary(self.type_specifier) self.expect( - "frame variable", - substrs=['this is an object of type S'], - matching=False) + "frame variable", substrs=["this is an object of type S"], matching=False + ) self.expect( - "frame variable", - substrs=[ - '(S)', - 'object', - '123', - '456'], - matching=True) + "frame variable", substrs=["(S)", "object", "123", "456"], matching=True + ) diff --git a/lldb/test/API/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py b/lldb/test/API/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py --- a/lldb/test/API/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py +++ b/lldb/test/API/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class NSArraySyntheticTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.m', '// Set break point at this line.') + self.line = line_number("main.m", "// Set break point at this line.") @skipUnlessDarwin def test_rdar11086338_with_run_command(self): @@ -25,56 +23,51 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + self, "main.m", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # Now check that we are displaying Cocoa classes correctly - self.expect('frame variable arr', - substrs=['@"6 elements"']) - self.expect('frame variable other_arr', - substrs=['@"4 elements"']) - self.expect('frame variable empty_arr', - substrs=['@"0 elements"']) + self.expect("frame variable arr", substrs=['@"6 elements"']) + self.expect("frame variable other_arr", substrs=['@"4 elements"']) + self.expect("frame variable empty_arr", substrs=['@"0 elements"']) self.expect( - 'frame variable arr --ptr-depth 1', + "frame variable arr --ptr-depth 1", substrs=[ '@"6 elements"', - '[0] = 0x', - '[1] = 0x', - '[2] = 0x', - '[3] = 0x', - '[4] = 0x', - '[5] = 0x']) + "[0] = 0x", + "[1] = 0x", + "[2] = 0x", + "[3] = 0x", + "[4] = 0x", + "[5] = 0x", + ], + ) self.expect( - 'frame variable other_arr --ptr-depth 1', - substrs=[ - '@"4 elements"', - '[0] = 0x', - '[1] = 0x', - '[2] = 0x', - '[3] = 0x']) + "frame variable other_arr --ptr-depth 1", + substrs=['@"4 elements"', "[0] = 0x", "[1] = 0x", "[2] = 0x", "[3] = 0x"], + ) + self.expect("frame variable empty_arr --ptr-depth 1", substrs=['@"0 elements"']) self.expect( - 'frame variable empty_arr --ptr-depth 1', - substrs=[ - '@"0 elements"']) - self.expect( - 'frame variable arr --ptr-depth 1', + "frame variable arr --ptr-depth 1", substrs=[ '@"6 elements"', '@"hello"', @@ -82,16 +75,15 @@ '@"this"', '@"is"', '@"me"', - '@"http://www.apple.com']) + '@"http://www.apple.com', + ], + ) self.expect( - 'frame variable other_arr --ptr-depth 1', - substrs=[ - '@"4 elements"', - '(int)5', - '@"a string"', - '@"6 elements"']) + "frame variable other_arr --ptr-depth 1", + substrs=['@"4 elements"', "(int)5", '@"a string"', '@"6 elements"'], + ) self.expect( - 'frame variable other_arr --ptr-depth 2', + "frame variable other_arr --ptr-depth 2", substrs=[ '@"4 elements"', '@"6 elements" {', @@ -100,14 +92,19 @@ '@"this"', '@"is"', '@"me"', - '@"http://www.apple.com']) + '@"http://www.apple.com', + ], + ) self.assertTrue( self.frame().FindVariable("arr").MightHaveChildren(), - "arr says it does not have children!") + "arr says it does not have children!", + ) self.assertTrue( self.frame().FindVariable("other_arr").MightHaveChildren(), - "arr says it does not have children!") + "arr says it does not have children!", + ) self.assertFalse( self.frame().FindVariable("empty_arr").MightHaveChildren(), - "arr says it does have children!") + "arr says it does have children!", + ) diff --git a/lldb/test/API/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py b/lldb/test/API/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py --- a/lldb/test/API/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py +++ b/lldb/test/API/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class NSDictionarySyntheticTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.m', '// Set break point at this line.') + self.line = line_number("main.m", "// Set break point at this line.") @skipUnlessDarwin def test_rdar11988289_with_run_command(self): @@ -28,12 +26,10 @@ def test_rdar11988289_with_run_command_no_const(self): """Test that NSDictionary reports its synthetic children properly.""" disable_constant_classes = { - 'CC': - 'xcrun clang', # FIXME: Remove when flags are available upstream. - 'CFLAGS_EXTRAS': - '-fno-constant-nsnumber-literals ' + - '-fno-constant-nsarray-literals ' + - '-fno-constant-nsdictionary-literals' + "CC": "xcrun clang", # FIXME: Remove when flags are available upstream. + "CFLAGS_EXTRAS": "-fno-constant-nsnumber-literals " + + "-fno-constant-nsarray-literals " + + "-fno-constant-nsdictionary-literals", } self.build(dictionary=disable_constant_classes) self.run_tests() @@ -42,94 +38,109 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + self, "main.m", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # Now check that we are displaying Cocoa classes correctly - self.expect('frame variable dictionary', - substrs=['3 key/value pairs']) - self.expect('frame variable mutabledict', - substrs=['4 key/value pairs']) + self.expect("frame variable dictionary", substrs=["3 key/value pairs"]) + self.expect("frame variable mutabledict", substrs=["4 key/value pairs"]) self.expect( - 'frame variable dictionary --ptr-depth 1', + "frame variable dictionary --ptr-depth 1", substrs=[ - '3 key/value pairs', - '[0] = ', - 'key = 0x', - 'value = 0x', - '[1] = ', - '[2] = ']) + "3 key/value pairs", + "[0] = ", + "key = 0x", + "value = 0x", + "[1] = ", + "[2] = ", + ], + ) self.expect( - 'frame variable mutabledict --ptr-depth 1', + "frame variable mutabledict --ptr-depth 1", substrs=[ - '4 key/value pairs', - '[0] = ', - 'key = 0x', - 'value = 0x', - '[1] = ', - '[2] = ', - '[3] = ']) + "4 key/value pairs", + "[0] = ", + "key = 0x", + "value = 0x", + "[1] = ", + "[2] = ", + "[3] = ", + ], + ) self.expect( - 'frame variable dictionary --ptr-depth 1', + "frame variable dictionary --ptr-depth 1", substrs=[ - '3 key/value pairs', + "3 key/value pairs", '@"bar"', '@"2 elements"', '@"baz"', - '2 key/value pairs']) + "2 key/value pairs", + ], + ) self.expect( - 'frame variable mutabledict --ptr-depth 1', + "frame variable mutabledict --ptr-depth 1", substrs=[ - '4 key/value pairs', - '(int)23', + "4 key/value pairs", + "(int)23", '@"123"', '@"http://www.apple.com"', '@"sourceofstuff"', - '3 key/value pairs']) + "3 key/value pairs", + ], + ) self.expect( - 'frame variable mutabledict --ptr-depth 2', + "frame variable mutabledict --ptr-depth 2", substrs=[ - '4 key/value pairs', - '(int)23', + "4 key/value pairs", + "(int)23", '@"123"', '@"http://www.apple.com"', '@"sourceofstuff"', - '3 key/value pairs', + "3 key/value pairs", '@"bar"', - '@"2 elements"']) + '@"2 elements"', + ], + ) self.expect( - 'frame variable mutabledict --ptr-depth 3', + "frame variable mutabledict --ptr-depth 3", substrs=[ - '4 key/value pairs', - '(int)23', + "4 key/value pairs", + "(int)23", '@"123"', '@"http://www.apple.com"', '@"sourceofstuff"', - '3 key/value pairs', + "3 key/value pairs", '@"bar"', '@"2 elements"', - '(int)1', - '@"two"']) + "(int)1", + '@"two"', + ], + ) self.assertTrue( self.frame().FindVariable("dictionary").MightHaveChildren(), - "dictionary says it does not have children!") + "dictionary says it does not have children!", + ) self.assertTrue( self.frame().FindVariable("mutabledict").MightHaveChildren(), - "mutable says it does not have children!") + "mutable says it does not have children!", + ) diff --git a/lldb/test/API/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py b/lldb/test/API/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py --- a/lldb/test/API/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py +++ b/lldb/test/API/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class NSSetSyntheticTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.m', '// Set break point at this line.') + self.line = line_number("main.m", "// Set break point at this line.") @skipUnlessDarwin def test_rdar12529957_with_run_command(self): @@ -28,12 +26,10 @@ def test_rdar12529957_with_run_command_no_const(self): """Test that NSSet reports its synthetic children properly.""" disable_constant_classes = { - 'CC': - 'xcrun clang', # FIXME: Remove when flags are available upstream. - 'CFLAGS_EXTRAS': - '-fno-constant-nsnumber-literals ' + - '-fno-constant-nsarray-literals ' + - '-fno-constant-nsdictionary-literals' + "CC": "xcrun clang", # FIXME: Remove when flags are available upstream. + "CFLAGS_EXTRAS": "-fno-constant-nsnumber-literals " + + "-fno-constant-nsarray-literals " + + "-fno-constant-nsdictionary-literals", } self.build(dictionary=disable_constant_classes) self.run_tests() @@ -42,87 +38,91 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + self, "main.m", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # Now check that we are displaying Cocoa classes correctly - self.expect('frame variable set', - substrs=['4 elements']) - self.expect('frame variable mutable', - substrs=['9 elements']) + self.expect("frame variable set", substrs=["4 elements"]) + self.expect("frame variable mutable", substrs=["9 elements"]) self.expect( - 'frame variable set --ptr-depth 1 -d run -T', + "frame variable set --ptr-depth 1 -d run -T", substrs=[ - '4 elements', - '[0]', - 'hello', - '[1]', - '(int)2', - '[2]', - '(int)1', - '[3]', - 'world', - ]) + "4 elements", + "[0]", + "hello", + "[1]", + "(int)2", + "[2]", + "(int)1", + "[3]", + "world", + ], + ) self.expect( - 'frame variable mutable --ptr-depth 1 -d run -T', + "frame variable mutable --ptr-depth 1 -d run -T", substrs=[ - '9 elements', - '(int)5', + "9 elements", + "(int)5", '@"3 elements"', '@"www.apple.com"', - '(int)3', + "(int)3", '@"world"', - '(int)4']) + "(int)4", + ], + ) self.runCmd("next") - self.expect('frame variable mutable', - substrs=['0 elements']) + self.expect("frame variable mutable", substrs=["0 elements"]) self.runCmd("next") - self.expect('frame variable mutable', - substrs=['4 elements']) + self.expect("frame variable mutable", substrs=["4 elements"]) self.expect( - 'frame variable mutable --ptr-depth 1 -d run -T', + "frame variable mutable --ptr-depth 1 -d run -T", substrs=[ - '4 elements', - '[0]', - '(int)1', - '[1]', - '(int)2', - '[2]', - 'hello', - '[3]', - 'world', - ]) + "4 elements", + "[0]", + "(int)1", + "[1]", + "(int)2", + "[2]", + "hello", + "[3]", + "world", + ], + ) self.runCmd("next") - self.expect('frame variable mutable', substrs=['4 elements']) + self.expect("frame variable mutable", substrs=["4 elements"]) self.expect( - 'frame variable mutable --ptr-depth 1 -d run -T', + "frame variable mutable --ptr-depth 1 -d run -T", substrs=[ - '4 elements', - '[0]', - '(int)1', - '[1]', - '(int)2', - '[2]', - 'hello', - '[3]', - 'world', - ]) + "4 elements", + "[0]", + "(int)1", + "[1]", + "(int)2", + "[2]", + "hello", + "[3]", + "world", + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py b/lldb/test/API/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py --- a/lldb/test/API/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py +++ b/lldb/test/API/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class DataFormatterOSTypeTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.mm', '// Set break point at this line.') + self.line = line_number("main.mm", "// Set break point at this line.") @skipUnlessDarwin def test_ostype_with_run_command(self): @@ -25,25 +23,27 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) + self, "main.mm", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # Now check that we use the right summary for OSType - self.expect('frame variable', - substrs=["'test'", "'best'"]) + self.expect("frame variable", substrs=["'test'", "'best'"]) diff --git a/lldb/test/API/functionalities/data-formatter/parray/TestPrintArray.py b/lldb/test/API/functionalities/data-formatter/parray/TestPrintArray.py --- a/lldb/test/API/functionalities/data-formatter/parray/TestPrintArray.py +++ b/lldb/test/API/functionalities/data-formatter/parray/TestPrintArray.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class PrintArrayTestCase(TestBase): - def test_print_array(self): """Test that expr -Z works""" self.build() @@ -21,110 +19,81 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', 'break here') + self.line = line_number("main.cpp", "break here") def printarray_data_formatter_commands(self): """Test that expr -Z works""" self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.expect( - 'expr --element-count 3 -- data', - substrs=[ - '[0] = 1', - '[1] = 3', - '[2] = 5']) - self.expect('expr data', substrs=['int *', '$', '0x']) + "expr --element-count 3 -- data", substrs=["[0] = 1", "[1] = 3", "[2] = 5"] + ) + self.expect("expr data", substrs=["int *", "$", "0x"]) self.expect( - 'expr -f binary --element-count 0 -- data', - substrs=[ - 'int *', - '$', - '0b']) + "expr -f binary --element-count 0 -- data", substrs=["int *", "$", "0b"] + ) self.expect( - 'expr -f hex --element-count 3 -- data', - substrs=[ - '[0] = 0x', - '1', - '[1] = 0x', - '3', - '[2] = 0x', - '5']) + "expr -f hex --element-count 3 -- data", + substrs=["[0] = 0x", "1", "[1] = 0x", "3", "[2] = 0x", "5"], + ) self.expect( - 'expr -f binary --element-count 2 -- data', - substrs=[ - 'int *', - '$', - '0x', - '[0] = 0b', - '1', - '[1] = 0b', - '11']) - self.expect('parray 3 data', substrs=['[0] = 1', '[1] = 3', '[2] = 5']) + "expr -f binary --element-count 2 -- data", + substrs=["int *", "$", "0x", "[0] = 0b", "1", "[1] = 0b", "11"], + ) + self.expect("parray 3 data", substrs=["[0] = 1", "[1] = 3", "[2] = 5"]) self.expect( - 'parray `1 + 1 + 1` data', - substrs=[ - '[0] = 1', - '[1] = 3', - '[2] = 5']) + "parray `1 + 1 + 1` data", substrs=["[0] = 1", "[1] = 3", "[2] = 5"] + ) + self.expect("parray `data[1]` data", substrs=["[0] = 1", "[1] = 3", "[2] = 5"]) self.expect( - 'parray `data[1]` data', - substrs=[ - '[0] = 1', - '[1] = 3', - '[2] = 5']) - self.expect( - 'parray/x 3 data', - substrs=[ - '[0] = 0x', - '1', - '[1] = 0x', - '3', - '[2] = 0x', - '5']) + "parray/x 3 data", + substrs=["[0] = 0x", "1", "[1] = 0x", "3", "[2] = 0x", "5"], + ) self.expect( - 'parray/x `data[1]` data', - substrs=[ - '[0] = 0x', - '1', - '[1] = 0x', - '3', - '[2] = 0x', - '5']) + "parray/x `data[1]` data", + substrs=["[0] = 0x", "1", "[1] = 0x", "3", "[2] = 0x", "5"], + ) # check error conditions self.expect( - 'expr --element-count 10 -- 123', + "expr --element-count 10 -- 123", error=True, - substrs=['expression cannot be used with --element-count as it does not refer to a pointer']) + substrs=[ + "expression cannot be used with --element-count as it does not refer to a pointer" + ], + ) self.expect( - 'expr --element-count 10 -- (void*)123', + "expr --element-count 10 -- (void*)123", error=True, - substrs=['expression cannot be used with --element-count as it refers to a pointer to void']) - self.expect('parray data', error=True, substrs=[ - "invalid element count 'data'"]) + substrs=[ + "expression cannot be used with --element-count as it refers to a pointer to void" + ], + ) + self.expect("parray data", error=True, substrs=["invalid element count 'data'"]) self.expect( - 'parray data data', - error=True, - substrs=["invalid element count 'data'"]) - self.expect('parray', error=True, substrs=[ - 'Not enough arguments provided']) + "parray data data", error=True, substrs=["invalid element count 'data'"] + ) + self.expect("parray", error=True, substrs=["Not enough arguments provided"]) diff --git a/lldb/test/API/functionalities/data-formatter/poarray/TestPrintObjectArray.py b/lldb/test/API/functionalities/data-formatter/poarray/TestPrintObjectArray.py --- a/lldb/test/API/functionalities/data-formatter/poarray/TestPrintObjectArray.py +++ b/lldb/test/API/functionalities/data-formatter/poarray/TestPrintObjectArray.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class PrintObjectArrayTestCase(TestBase): - @skipUnlessDarwin def test_print_array(self): """Test that expr -O -Z works""" @@ -22,14 +20,11 @@ def test_print_array_no_const(self): """Test that expr -O -Z works""" disable_constant_classes = { - 'CC': - 'xcrun clang', # FIXME: Remove when flags are available upstream. - 'USE_SYSTEM_STDLIB': - '1', # See above. - 'CFLAGS_EXTRAS': - '-fno-constant-nsnumber-literals ' + - '-fno-constant-nsarray-literals ' + - '-fno-constant-nsdictionary-literals' + "CC": "xcrun clang", # FIXME: Remove when flags are available upstream. + "USE_SYSTEM_STDLIB": "1", # See above. + "CFLAGS_EXTRAS": "-fno-constant-nsnumber-literals " + + "-fno-constant-nsarray-literals " + + "-fno-constant-nsdictionary-literals", } self.build(dictionary=disable_constant_classes) self.printarray_data_formatter_commands() @@ -38,86 +33,89 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.mm', 'break here') + self.line = line_number("main.mm", "break here") def printarray_data_formatter_commands(self): """Test that expr -O -Z works""" self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) + self, "main.mm", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.expect( - 'expr --element-count 3 --object-description -- objects', + "expr --element-count 3 --object-description -- objects", substrs=[ - '3735928559', - '4276993775', - '3203398366', - 'Hello', - 'World', - 'Two =', - '1 =']) + "3735928559", + "4276993775", + "3203398366", + "Hello", + "World", + "Two =", + "1 =", + ], + ) self.expect( - 'poarray 3 objects', + "poarray 3 objects", substrs=[ - '3735928559', - '4276993775', - '3203398366', - 'Hello', - 'World', - 'Two =', - '1 =']) + "3735928559", + "4276993775", + "3203398366", + "Hello", + "World", + "Two =", + "1 =", + ], + ) self.expect( - 'expr --element-count 3 --object-description --description-verbosity=full -- objects', + "expr --element-count 3 --object-description --description-verbosity=full -- objects", substrs=[ - '[0] =', - '3735928559', - '4276993775', - '3203398366', - '[1] =', - 'Hello', - 'World', - '[2] =', - 'Two =', - '1 =']) + "[0] =", + "3735928559", + "4276993775", + "3203398366", + "[1] =", + "Hello", + "World", + "[2] =", + "Two =", + "1 =", + ], + ) + self.expect("parray 3 objects", substrs=["[0] = 0x", "[1] = 0x", "[2] = 0x"]) self.expect( - 'parray 3 objects', - substrs=[ - '[0] = 0x', - '[1] = 0x', - '[2] = 0x']) - self.expect( - 'expr --element-count 3 -d run -- objects', - substrs=[ - '3 elements', - '2 elements', - '2 key/value pairs']) + "expr --element-count 3 -d run -- objects", + substrs=["3 elements", "2 elements", "2 key/value pairs"], + ) self.expect( - 'expr --element-count 3 -d run --ptr-depth=1 -- objects', + "expr --element-count 3 -d run --ptr-depth=1 -- objects", substrs=[ - '3 elements', - '3735928559', - '4276993775', - '3203398366', - '2 elements', + "3 elements", + "3735928559", + "4276993775", + "3203398366", + "2 elements", '"Hello"', '"World"', - '2 key/value pairs', - ]) + "2 key/value pairs", + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py b/lldb/test/API/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py --- a/lldb/test/API/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py +++ b/lldb/test/API/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py @@ -3,19 +3,17 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class PtrRef2TypedefTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set breakpoint here') + self.line = line_number("main.cpp", "// Set breakpoint here") def test_with_run_command(self): """Test that a pointer/reference to a typedef is formatted as we want.""" @@ -23,20 +21,23 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -45,18 +46,10 @@ self.runCmd('type summary add --cascade true -s "IntLRef" "int &"') self.runCmd('type summary add --cascade true -s "IntRRef" "int &&"') - self.expect( - "frame variable x", - substrs=[ - '(Foo *) x = 0x', - 'IntPointer']) + self.expect("frame variable x", substrs=["(Foo *) x = 0x", "IntPointer"]) # note: Ubuntu 12.04 x86_64 build with gcc 4.8.2 is getting a # const after the ref that isn't showing up on FreeBSD. This # tweak changes the behavior so that the const is not part of # the match. - self.expect( - "frame variable y", substrs=[ - '(Foo &', ') y = 0x', 'IntLRef']) - self.expect( - "frame variable z", substrs=[ - '(Foo &&', ') z = 0x', 'IntRRef']) + self.expect("frame variable y", substrs=["(Foo &", ") y = 0x", "IntLRef"]) + self.expect("frame variable z", substrs=["(Foo &&", ") z = 0x", "IntRRef"]) diff --git a/lldb/test/API/functionalities/data-formatter/pyobjsynthprovider/TestPyObjSynthProvider.py b/lldb/test/API/functionalities/data-formatter/pyobjsynthprovider/TestPyObjSynthProvider.py --- a/lldb/test/API/functionalities/data-formatter/pyobjsynthprovider/TestPyObjSynthProvider.py +++ b/lldb/test/API/functionalities/data-formatter/pyobjsynthprovider/TestPyObjSynthProvider.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -22,45 +21,44 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', 'break here') + self.line = line_number("main.cpp", "break here") def provider_data_formatter_commands(self): """Test that the PythonObjectSyntheticChildProvider helper class works""" self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.runCmd('command script import provider.py') + self.runCmd("command script import provider.py") self.runCmd( - 'type synthetic add Foo --python-class provider.SyntheticChildrenProvider') - self.expect('frame variable f.Name', substrs=['"Enrico"']) + "type synthetic add Foo --python-class provider.SyntheticChildrenProvider" + ) + self.expect("frame variable f.Name", substrs=['"Enrico"']) self.expect( - 'frame variable f', - substrs=[ - 'ID = 123456', - 'Name = "Enrico"', - 'Rate = 1.25']) + "frame variable f", + substrs=["ID = 123456", 'Name = "Enrico"', "Rate = 1.25"], + ) self.expect( - 'expression f', - substrs=[ - 'ID = 123456', - 'Name = "Enrico"', - 'Rate = 1.25']) + "expression f", substrs=["ID = 123456", 'Name = "Enrico"', "Rate = 1.25"] + ) diff --git a/lldb/test/API/functionalities/data-formatter/pyobjsynthprovider/provider.py b/lldb/test/API/functionalities/data-formatter/pyobjsynthprovider/provider.py --- a/lldb/test/API/functionalities/data-formatter/pyobjsynthprovider/provider.py +++ b/lldb/test/API/functionalities/data-formatter/pyobjsynthprovider/provider.py @@ -4,13 +4,12 @@ class SyntheticChildrenProvider( - lldb.formatters.synth.PythonObjectSyntheticChildProvider): - + lldb.formatters.synth.PythonObjectSyntheticChildProvider +): def __init__(self, value, internal_dict): lldb.formatters.synth.PythonObjectSyntheticChildProvider.__init__( - self, value, internal_dict) + self, value, internal_dict + ) def make_children(self): - return [("ID", 123456), - ("Name", "Enrico"), - ("Rate", 1.25)] + return [("ID", 123456), ("Name", "Enrico"), ("Rate", 1.25)] diff --git a/lldb/test/API/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py b/lldb/test/API/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py --- a/lldb/test/API/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py +++ b/lldb/test/API/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py @@ -3,19 +3,17 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class DataFormatterRefPtrRecursionTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Test that ValueObjectPrinter does not cause an infinite loop when a reference to a struct that contains a pointer to itself is printed.""" @@ -23,16 +21,19 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) self.expect("frame variable foo", substrs=[]) - self.expect("frame variable foo --ptr-depth=1", substrs=['ID = 1']) - self.expect("frame variable foo --ptr-depth=2", substrs=['ID = 1']) - self.expect("frame variable foo --ptr-depth=3", substrs=['ID = 1']) + self.expect("frame variable foo --ptr-depth=1", substrs=["ID = 1"]) + self.expect("frame variable foo --ptr-depth=2", substrs=["ID = 1"]) + self.expect("frame variable foo --ptr-depth=3", substrs=["ID = 1"]) diff --git a/lldb/test/API/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py b/lldb/test/API/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py --- a/lldb/test/API/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py +++ b/lldb/test/API/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py @@ -1,5 +1,4 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest( - __file__, globals(), [decorators.skipUnlessDarwin]) +lldbinline.MakeInlineTest(__file__, globals(), [decorators.skipUnlessDarwin]) diff --git a/lldb/test/API/functionalities/data-formatter/stringprinter/TestStringPrinter.py b/lldb/test/API/functionalities/data-formatter/stringprinter/TestStringPrinter.py --- a/lldb/test/API/functionalities/data-formatter/stringprinter/TestStringPrinter.py +++ b/lldb/test/API/functionalities/data-formatter/stringprinter/TestStringPrinter.py @@ -2,6 +2,7 @@ from lldbsuite.test import decorators lldbinline.MakeInlineTest( - __file__, globals(), [ - decorators.expectedFailureAll( - oslist=["windows"], bugnumber="llvm.org/pr24772")]) + __file__, + globals(), + [decorators.expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24772")], +) diff --git a/lldb/test/API/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py b/lldb/test/API/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py --- a/lldb/test/API/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py +++ b/lldb/test/API/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py @@ -3,141 +3,118 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class Radar9974002DataFormatterTestCase(TestBase): - # test for rdar://problem/9974002 () def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion(): self.skipTest( - "llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") + "llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef" + ) self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type summary clear', check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.runCmd( - "type summary add -s \"${var.scalar} and ${var.pointer.first}\" container") + 'type summary add -s "${var.scalar} and ${var.pointer.first}" container' + ) - self.expect('frame variable mine', - substrs=['mine = ', - '1', '']) + self.expect("frame variable mine", substrs=["mine = ", "1", ""]) - self.runCmd( - "type summary add -s \"${var.scalar} and ${var.pointer}\" container") + self.runCmd('type summary add -s "${var.scalar} and ${var.pointer}" container') - self.expect('frame variable mine', - substrs=['mine = ', - '1', '0x000000']) + self.expect("frame variable mine", substrs=["mine = ", "1", "0x000000"]) self.runCmd( - "type summary add -s \"${var.scalar} and ${var.pointer%S}\" container") + 'type summary add -s "${var.scalar} and ${var.pointer%S}" container' + ) - self.expect('frame variable mine', - substrs=['mine = ', - '1', '0x000000']) + self.expect("frame variable mine", substrs=["mine = ", "1", "0x000000"]) self.runCmd("type summary add -s foo contained") - self.expect('frame variable mine', - substrs=['mine = ', - '1', 'foo']) + self.expect("frame variable mine", substrs=["mine = ", "1", "foo"]) - self.runCmd( - "type summary add -s \"${var.scalar} and ${var.pointer}\" container") + self.runCmd('type summary add -s "${var.scalar} and ${var.pointer}" container') - self.expect('frame variable mine', - substrs=['mine = ', - '1', 'foo']) + self.expect("frame variable mine", substrs=["mine = ", "1", "foo"]) self.runCmd( - "type summary add -s \"${var.scalar} and ${var.pointer%V}\" container") + 'type summary add -s "${var.scalar} and ${var.pointer%V}" container' + ) - self.expect('frame variable mine', - substrs=['mine = ', - '1', '0x000000']) + self.expect("frame variable mine", substrs=["mine = ", "1", "0x000000"]) self.runCmd( - "type summary add -s \"${var.scalar} and ${var.pointer.first}\" container") + 'type summary add -s "${var.scalar} and ${var.pointer.first}" container' + ) - self.expect('frame variable mine', - substrs=['mine = ', - '1', '']) + self.expect("frame variable mine", substrs=["mine = ", "1", ""]) self.runCmd("type summary delete contained") self.runCmd("n") - self.expect('frame variable mine', - substrs=['mine = ', - '1', '']) + self.expect("frame variable mine", substrs=["mine = ", "1", ""]) - self.runCmd( - "type summary add -s \"${var.scalar} and ${var.pointer}\" container") + self.runCmd('type summary add -s "${var.scalar} and ${var.pointer}" container') - self.expect('frame variable mine', - substrs=['mine = ', - '1', '0x000000']) + self.expect("frame variable mine", substrs=["mine = ", "1", "0x000000"]) self.runCmd( - "type summary add -s \"${var.scalar} and ${var.pointer%S}\" container") + 'type summary add -s "${var.scalar} and ${var.pointer%S}" container' + ) - self.expect('frame variable mine', - substrs=['mine = ', - '1', '0x000000']) + self.expect("frame variable mine", substrs=["mine = ", "1", "0x000000"]) self.runCmd("type summary add -s foo contained") - self.expect('frame variable mine', - substrs=['mine = ', - '1', 'foo']) + self.expect("frame variable mine", substrs=["mine = ", "1", "foo"]) - self.runCmd( - "type summary add -s \"${var.scalar} and ${var.pointer}\" container") + self.runCmd('type summary add -s "${var.scalar} and ${var.pointer}" container') - self.expect('frame variable mine', - substrs=['mine = ', - '1', 'foo']) + self.expect("frame variable mine", substrs=["mine = ", "1", "foo"]) self.runCmd( - "type summary add -s \"${var.scalar} and ${var.pointer%V}\" container") + 'type summary add -s "${var.scalar} and ${var.pointer%V}" container' + ) - self.expect('frame variable mine', - substrs=['mine = ', - '1', '0x000000']) + self.expect("frame variable mine", substrs=["mine = ", "1", "0x000000"]) self.runCmd( - "type summary add -s \"${var.scalar} and ${var.pointer.first}\" container") + 'type summary add -s "${var.scalar} and ${var.pointer.first}" container' + ) - self.expect('frame variable mine', - substrs=['mine = ', - '1', '']) + self.expect("frame variable mine", substrs=["mine = ", "1", ""]) diff --git a/lldb/test/API/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py b/lldb/test/API/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py --- a/lldb/test/API/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py +++ b/lldb/test/API/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class SyntheticCappingTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Check for an issue where capping does not work because the Target pointer appears to be changing behind our backs.""" @@ -24,27 +22,28 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) process = self.dbg.GetSelectedTarget().GetProcess() # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) - self.runCmd( - "settings set target.max-children-count 256", - check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) + self.runCmd("settings set target.max-children-count 256", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -64,25 +63,26 @@ self.expect( "frame variable f00_1", substrs=[ - 'a = 1', - 'fake_a = %d' % fake_a_val, - 'r = 34', - ]) + "a = 1", + "fake_a = %d" % fake_a_val, + "r = 34", + ], + ) # check that capping works self.runCmd("settings set target.max-children-count 2", check=False) - self.expect("frame variable f00_1", - substrs=[ - 'a = 1', - 'fake_a = %d' % fake_a_val, - '...', - ]) + self.expect( + "frame variable f00_1", + substrs=[ + "a = 1", + "fake_a = %d" % fake_a_val, + "...", + ], + ) - self.expect("frame variable f00_1", matching=False, - substrs=['r = 34']) + self.expect("frame variable f00_1", matching=False, substrs=["r = 34"]) self.runCmd("settings set target.max-children-count 256", check=False) - self.expect("frame variable f00_1", matching=True, - substrs=['r = 34']) + self.expect("frame variable f00_1", matching=True, substrs=["r = 34"]) diff --git a/lldb/test/API/functionalities/data-formatter/synthcapping/fooSynthProvider.py b/lldb/test/API/functionalities/data-formatter/synthcapping/fooSynthProvider.py --- a/lldb/test/API/functionalities/data-formatter/synthcapping/fooSynthProvider.py +++ b/lldb/test/API/functionalities/data-formatter/synthcapping/fooSynthProvider.py @@ -2,7 +2,6 @@ class fooSynthProvider: - def __init__(self, valobj, dict): self.valobj = valobj self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) @@ -12,16 +11,16 @@ def get_child_at_index(self, index): if index == 0: - child = self.valobj.GetChildMemberWithName('a') + child = self.valobj.GetChildMemberWithName("a") if index == 1: - child = self.valobj.CreateChildAtOffset('fake_a', 1, self.int_type) + child = self.valobj.CreateChildAtOffset("fake_a", 1, self.int_type) if index == 2: - child = self.valobj.GetChildMemberWithName('r') + child = self.valobj.GetChildMemberWithName("r") return child def get_child_index(self, name): - if name == 'a': + if name == "a": return 0 - if name == 'fake_a': + if name == "fake_a": return 1 return 2 diff --git a/lldb/test/API/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py b/lldb/test/API/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py --- a/lldb/test/API/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py +++ b/lldb/test/API/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class SyntheticFilterRecomputingTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.m', '// Set break point at this line.') + self.line = line_number("main.m", "// Set break point at this line.") @skipUnlessDarwin def test_rdar12437442_with_run_command(self): @@ -25,28 +23,36 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + self, "main.m", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # Now run the bulk of the test - id_x = self.dbg.GetSelectedTarget().GetProcess( - ).GetSelectedThread().GetSelectedFrame().FindVariable("x") + id_x = ( + self.dbg.GetSelectedTarget() + .GetProcess() + .GetSelectedThread() + .GetSelectedFrame() + .FindVariable("x") + ) id_x.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) id_x.SetPreferSyntheticValue(True) @@ -54,14 +60,19 @@ self.runCmd("expr --dynamic-type run-target --ptr-depth 1 -- x") self.assertEqual( - id_x.GetSummary(), '@"5 elements"', - "array does not get correct summary") + id_x.GetSummary(), '@"5 elements"', "array does not get correct summary" + ) self.runCmd("next") self.runCmd("frame select 0") - id_x = self.dbg.GetSelectedTarget().GetProcess( - ).GetSelectedThread().GetSelectedFrame().FindVariable("x") + id_x = ( + self.dbg.GetSelectedTarget() + .GetProcess() + .GetSelectedThread() + .GetSelectedFrame() + .FindVariable("x") + ) id_x.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) id_x.SetPreferSyntheticValue(True) @@ -69,13 +80,15 @@ self.runCmd("expr --dynamic-type run-target --ptr-depth 1 -- x") self.assertEqual( - id_x.GetNumChildren(), 7, - "dictionary does not have 7 children") + id_x.GetNumChildren(), 7, "dictionary does not have 7 children" + ) id_x.SetPreferSyntheticValue(False) self.assertNotEqual( - id_x.GetNumChildren(), 7, - "dictionary still looks synthetic") + id_x.GetNumChildren(), 7, "dictionary still looks synthetic" + ) id_x.SetPreferSyntheticValue(True) self.assertEqual( - id_x.GetSummary(), "7 key/value pairs", - "dictionary does not get correct summary") + id_x.GetSummary(), + "7 key/value pairs", + "dictionary does not get correct summary", + ) diff --git a/lldb/test/API/functionalities/data-formatter/type_summary_list_arg/TestTypeSummaryListArg.py b/lldb/test/API/functionalities/data-formatter/type_summary_list_arg/TestTypeSummaryListArg.py --- a/lldb/test/API/functionalities/data-formatter/type_summary_list_arg/TestTypeSummaryListArg.py +++ b/lldb/test/API/functionalities/data-formatter/type_summary_list_arg/TestTypeSummaryListArg.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,34 +10,24 @@ class TypeSummaryListArgumentTestCase(TestBase): - @no_debug_info_test def test_type_summary_list_with_arg(self): """Test that the 'type summary list' command handles command line arguments properly""" self.expect( - 'type summary list Foo', - substrs=[ - 'Category: default', - 'Category: system']) + "type summary list Foo", substrs=["Category: default", "Category: system"] + ) self.expect( - 'type summary list char', - substrs=[ - 'char ?(\*|\[\])', - 'char ?\[[0-9]+\]']) + "type summary list char", substrs=["char ?(\*|\[\])", "char ?\[[0-9]+\]"] + ) + self.expect("type summary list -w default", substrs=["system"], matching=False) self.expect( - 'type summary list -w default', - substrs=['system'], - matching=False) - self.expect( - 'type summary list -w system unsigned', - substrs=[ - 'default', - '0-9'], - matching=False) + "type summary list -w system unsigned", + substrs=["default", "0-9"], + matching=False, + ) self.expect( - 'type summary list -w system char', - substrs=[ - 'char ?(\*|\[\])', - 'char ?\[[0-9]+\]'], - matching=True) + "type summary list -w system char", + substrs=["char ?(\*|\[\])", "char ?\[[0-9]+\]"], + matching=True, + ) diff --git a/lldb/test/API/functionalities/data-formatter/type_summary_list_script/TestTypeSummaryListScript.py b/lldb/test/API/functionalities/data-formatter/type_summary_list_script/TestTypeSummaryListScript.py --- a/lldb/test/API/functionalities/data-formatter/type_summary_list_script/TestTypeSummaryListScript.py +++ b/lldb/test/API/functionalities/data-formatter/type_summary_list_script/TestTypeSummaryListScript.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class TypeSummaryListScriptTestCase(TestBase): - def test_typesummarylist_script(self): """Test data formatter commands.""" self.build() @@ -21,40 +19,39 @@ # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', 'Break here') + self.line = line_number("main.cpp", "Break here") def data_formatter_commands(self): """Test printing out Python summary formatters.""" self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type category delete TSLSFormatters', check=False) - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type category delete TSLSFormatters", check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) self.addTearDownHook(cleanup) self.runCmd("command script import tslsformatters.py") - self.expect( - "frame variable myStruct", - substrs=['A data formatter at work']) + self.expect("frame variable myStruct", substrs=["A data formatter at work"]) - self.expect('type summary list', substrs=['Struct_SummaryFormatter']) - self.expect( - 'type summary list Struct', - substrs=['Struct_SummaryFormatter']) + self.expect("type summary list", substrs=["Struct_SummaryFormatter"]) + self.expect("type summary list Struct", substrs=["Struct_SummaryFormatter"]) diff --git a/lldb/test/API/functionalities/data-formatter/type_summary_list_script/tslsformatters.py b/lldb/test/API/functionalities/data-formatter/type_summary_list_script/tslsformatters.py --- a/lldb/test/API/functionalities/data-formatter/type_summary_list_script/tslsformatters.py +++ b/lldb/test/API/functionalities/data-formatter/type_summary_list_script/tslsformatters.py @@ -2,11 +2,13 @@ def Struct_SummaryFormatter(valobj, internal_dict): - return 'A data formatter at work' + return "A data formatter at work" + category = lldb.debugger.CreateCategory("TSLSFormatters") category.SetEnabled(True) summary = lldb.SBTypeSummary.CreateWithFunctionName( - "tslsformatters.Struct_SummaryFormatter", lldb.eTypeOptionCascade) + "tslsformatters.Struct_SummaryFormatter", lldb.eTypeOptionCascade +) spec = lldb.SBTypeNameSpecifier("Struct", False) category.AddTypeSummary(spec, summary) diff --git a/lldb/test/API/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py b/lldb/test/API/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py --- a/lldb/test/API/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py +++ b/lldb/test/API/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py @@ -3,19 +3,17 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class UserFormatVSSummaryTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Test that the user can input a format but it will not prevail over summary format's choices.""" @@ -23,47 +21,47 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) - self.expect("frame variable p1", substrs=[ - '(Pair) p1 = (x = 3, y = -3)']) + self.expect("frame variable p1", substrs=["(Pair) p1 = (x = 3, y = -3)"]) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.runCmd('type summary add Pair -s "x=${var.x%d},y=${var.y%u}"') - self.expect("frame variable p1", substrs=[ - '(Pair) p1 = x=3,y=4294967293']) + self.expect("frame variable p1", substrs=["(Pair) p1 = x=3,y=4294967293"]) self.expect( "frame variable -f x p1", - substrs=['(Pair) p1 = x=0x00000003,y=0xfffffffd'], - matching=False) + substrs=["(Pair) p1 = x=0x00000003,y=0xfffffffd"], + matching=False, + ) self.expect( - "frame variable -f d p1", - substrs=['(Pair) p1 = x=3,y=-3'], - matching=False) - self.expect("frame variable p1", substrs=[ - '(Pair) p1 = x=3,y=4294967293']) + "frame variable -f d p1", substrs=["(Pair) p1 = x=3,y=-3"], matching=False + ) + self.expect("frame variable p1", substrs=["(Pair) p1 = x=3,y=4294967293"]) self.runCmd('type summary add Pair -s "x=${var.x%x},y=${var.y%u}"') - self.expect("frame variable p1", substrs=[ - '(Pair) p1 = x=0x00000003,y=4294967293']) self.expect( - "frame variable -f d p1", - substrs=['(Pair) p1 = x=3,y=-3'], - matching=False) + "frame variable p1", substrs=["(Pair) p1 = x=0x00000003,y=4294967293"] + ) + self.expect( + "frame variable -f d p1", substrs=["(Pair) p1 = x=3,y=-3"], matching=False + ) diff --git a/lldb/test/API/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py b/lldb/test/API/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py --- a/lldb/test/API/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py +++ b/lldb/test/API/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py @@ -3,19 +3,17 @@ """ - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil class VarInAggregateMisuseTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// Set break point at this line.') + self.line = line_number("main.cpp", "// Set break point at this line.") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" @@ -23,53 +21,66 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type summary clear', check=False) + self.runCmd("type summary clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.runCmd( - "type summary add --summary-string \"SUMMARY SUCCESS ${var}\" Summarize") + 'type summary add --summary-string "SUMMARY SUCCESS ${var}" Summarize' + ) - self.expect('frame variable mine_ptr', - substrs=['SUMMARY SUCCESS summarize_ptr_t @ ']) + self.expect( + "frame variable mine_ptr", substrs=["SUMMARY SUCCESS summarize_ptr_t @ "] + ) - self.expect('frame variable *mine_ptr', - substrs=['SUMMARY SUCCESS summarize_t @']) + self.expect( + "frame variable *mine_ptr", substrs=["SUMMARY SUCCESS summarize_t @"] + ) self.runCmd( - "type summary add --summary-string \"SUMMARY SUCCESS ${var.first}\" Summarize") + 'type summary add --summary-string "SUMMARY SUCCESS ${var.first}" Summarize' + ) - self.expect('frame variable mine_ptr', - substrs=['SUMMARY SUCCESS 10']) + self.expect("frame variable mine_ptr", substrs=["SUMMARY SUCCESS 10"]) - self.expect('frame variable *mine_ptr', - substrs=['SUMMARY SUCCESS 10']) + self.expect("frame variable *mine_ptr", substrs=["SUMMARY SUCCESS 10"]) - self.runCmd("type summary add --summary-string \"${var}\" Summarize") - self.runCmd( - "type summary add --summary-string \"${var}\" -e TwoSummarizes") + self.runCmd('type summary add --summary-string "${var}" Summarize') + self.runCmd('type summary add --summary-string "${var}" -e TwoSummarizes') - self.expect('frame variable', - substrs=['(TwoSummarizes) twos = TwoSummarizes @ ', - 'first = summarize_t @ ', - 'second = summarize_t @ ']) + self.expect( + "frame variable", + substrs=[ + "(TwoSummarizes) twos = TwoSummarizes @ ", + "first = summarize_t @ ", + "second = summarize_t @ ", + ], + ) self.runCmd( - "type summary add --summary-string \"SUMMARY SUCCESS ${var.first}\" Summarize") - self.expect('frame variable', - substrs=['(TwoSummarizes) twos = TwoSummarizes @ ', - 'first = SUMMARY SUCCESS 1', - 'second = SUMMARY SUCCESS 3']) + 'type summary add --summary-string "SUMMARY SUCCESS ${var.first}" Summarize' + ) + self.expect( + "frame variable", + substrs=[ + "(TwoSummarizes) twos = TwoSummarizes @ ", + "first = SUMMARY SUCCESS 1", + "second = SUMMARY SUCCESS 3", + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py b/lldb/test/API/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py --- a/lldb/test/API/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py +++ b/lldb/test/API/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,12 +10,11 @@ class DataFormatterVarScriptFormatting(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', ' // Set breakpoint here.') + self.line = line_number("main.cpp", " // Set breakpoint here.") def test_with_run_command(self): """Test using Python synthetic children provider.""" @@ -24,30 +22,34 @@ self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type format clear', check=False) - self.runCmd('type summary clear', check=False) - self.runCmd('type filter clear', check=False) - self.runCmd('type synth clear', check=False) + self.runCmd("type format clear", check=False) + self.runCmd("type summary clear", check=False) + self.runCmd("type filter clear", check=False) + self.runCmd("type synth clear", check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.runCmd("command script import helperfunc.py") self.runCmd( - 'type summary add -x "^something<.*>$" -s "T is a ${script.var:helperfunc.f}"') + 'type summary add -x "^something<.*>$" -s "T is a ${script.var:helperfunc.f}"' + ) - self.expect("frame variable x", substrs=['T is a non-pointer type']) + self.expect("frame variable x", substrs=["T is a non-pointer type"]) - self.expect("frame variable y", substrs=['T is a pointer type']) + self.expect("frame variable y", substrs=["T is a pointer type"]) diff --git a/lldb/test/API/functionalities/data-formatter/varscript_formatting/helperfunc.py b/lldb/test/API/functionalities/data-formatter/varscript_formatting/helperfunc.py --- a/lldb/test/API/functionalities/data-formatter/varscript_formatting/helperfunc.py +++ b/lldb/test/API/functionalities/data-formatter/varscript_formatting/helperfunc.py @@ -2,5 +2,8 @@ def f(value, d): - return "pointer type" if value.GetType().GetTemplateArgumentType( - 0).IsPointerType() else "non-pointer type" + return ( + "pointer type" + if value.GetType().GetTemplateArgumentType(0).IsPointerType() + else "non-pointer type" + ) diff --git a/lldb/test/API/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py b/lldb/test/API/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py --- a/lldb/test/API/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py +++ b/lldb/test/API/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py @@ -9,29 +9,31 @@ class VectorTypesFormattingTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. - self.line = line_number('main.cpp', '// break here') + self.line = line_number("main.cpp", "// break here") # rdar://problem/14035604 - @skipIf(compiler='gcc') # gcc don't have ext_vector_type extension + @skipIf(compiler="gcc") # gcc don't have ext_vector_type extension def test_with_run_command(self): """Check that vector types format properly""" self.build() self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( - self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "stop reason = breakpoint"], + ) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -50,34 +52,37 @@ if self.TraceOn(): print(v) + self.assertEqual(v.GetNumChildren(), 4, "v as float32[] has 4 children") + self.assertEqual( + v.GetChildAtIndex(0).GetData().float[0], 1.25, "child 0 == 1.25" + ) + self.assertEqual( + v.GetChildAtIndex(1).GetData().float[0], 1.25, "child 1 == 1.25" + ) self.assertEqual( - v.GetNumChildren(), 4, - "v as float32[] has 4 children") - self.assertEqual(v.GetChildAtIndex(0).GetData().float[0], 1.25, - "child 0 == 1.25") - self.assertEqual(v.GetChildAtIndex(1).GetData().float[0], 1.25, - "child 1 == 1.25") - self.assertEqual(v.GetChildAtIndex(2).GetData().float[0], 2.50, - "child 2 == 2.50") - self.assertEqual(v.GetChildAtIndex(3).GetData().float[0], 2.50, - "child 3 == 2.50") - - self.expect("expr -f int16_t[] -- v", - substrs=['(0, 16288, 0, 16288, 0, 16416, 0, 16416)']) - self.expect("expr -f uint128_t[] -- v", - substrs=['(85236745249553456609335044694184296448)']) + v.GetChildAtIndex(2).GetData().float[0], 2.50, "child 2 == 2.50" + ) + self.assertEqual( + v.GetChildAtIndex(3).GetData().float[0], 2.50, "child 3 == 2.50" + ) + self.expect( - "expr -f float32[] -- v", - substrs=['(1.25, 1.25, 2.5, 2.5)']) + "expr -f int16_t[] -- v", + substrs=["(0, 16288, 0, 16288, 0, 16416, 0, 16416)"], + ) + self.expect( + "expr -f uint128_t[] -- v", + substrs=["(85236745249553456609335044694184296448)"], + ) + self.expect("expr -f float32[] -- v", substrs=["(1.25, 1.25, 2.5, 2.5)"]) oldValue = v.GetChildAtIndex(0).GetValue() v.SetFormat(lldb.eFormatHex) newValue = v.GetChildAtIndex(0).GetValue() - self.assertNotEqual(oldValue, newValue, - "values did not change along with format") + self.assertNotEqual( + oldValue, newValue, "values did not change along with format" + ) v.SetFormat(lldb.eFormatVectorOfFloat32) oldValueAgain = v.GetChildAtIndex(0).GetValue() - self.assertEqual( - oldValue, oldValueAgain, - "same format but different values") + self.assertEqual(oldValue, oldValueAgain, "same format but different values") diff --git a/lldb/test/API/functionalities/dead-strip/TestDeadStrip.py b/lldb/test/API/functionalities/dead-strip/TestDeadStrip.py --- a/lldb/test/API/functionalities/dead-strip/TestDeadStrip.py +++ b/lldb/test/API/functionalities/dead-strip/TestDeadStrip.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class DeadStripTestCase(TestBase): - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr44429") def test(self): """Test breakpoint works correctly with dead-code stripping.""" @@ -21,34 +19,39 @@ # Break by function name f1 (live code). lldbutil.run_break_set_by_symbol( - self, "f1", num_expected_locations=1, module_name="a.out") + self, "f1", num_expected_locations=1, module_name="a.out" + ) # Break by function name f2 (dead code). lldbutil.run_break_set_by_symbol( - self, "f2", num_expected_locations=0, module_name="a.out") + self, "f2", num_expected_locations=0, module_name="a.out" + ) # Break by function name f3 (live code). lldbutil.run_break_set_by_symbol( - self, "f3", num_expected_locations=1, module_name="a.out") + self, "f3", num_expected_locations=1, module_name="a.out" + ) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint (breakpoint #1). - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'a.out`f1', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "a.out`f1", "stop reason = breakpoint"], + ) # The breakpoint should have a hit count of 1. - lldbutil.check_breakpoint(self, bpno = 1, expected_hit_count = 1) + lldbutil.check_breakpoint(self, bpno=1, expected_hit_count=1) self.runCmd("continue") # The stop reason of the thread should be breakpoint (breakpoint #3). - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs=['stopped', - 'a.out`f3', - 'stop reason = breakpoint']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stopped", "a.out`f3", "stop reason = breakpoint"], + ) # The breakpoint should have a hit count of 1. - lldbutil.check_breakpoint(self, bpno = 3, expected_hit_count = 1) + lldbutil.check_breakpoint(self, bpno=3, expected_hit_count=1) diff --git a/lldb/test/API/functionalities/deleted-executable/TestDeletedExecutable.py b/lldb/test/API/functionalities/deleted-executable/TestDeletedExecutable.py --- a/lldb/test/API/functionalities/deleted-executable/TestDeletedExecutable.py +++ b/lldb/test/API/functionalities/deleted-executable/TestDeletedExecutable.py @@ -3,28 +3,28 @@ """ - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestDeletedExecutable(TestBase): NO_DEBUG_INFO_TESTCASE = True - @skipIfWindows # cannot delete a running executable + @skipIfWindows # cannot delete a running executable def test(self): self.build() exe = self.getBuildArtifact("a.out") # Use a file as a synchronization point between test and inferior. - pid_file_path = lldbutil.append_to_process_working_directory(self, - "token_pid_%d" % (int(os.getpid()))) + pid_file_path = lldbutil.append_to_process_working_directory( + self, "token_pid_%d" % (int(os.getpid())) + ) self.addTearDownHook( - lambda: self.run_platform_command( - "rm %s" % - (pid_file_path))) + lambda: self.run_platform_command("rm %s" % (pid_file_path)) + ) # Spawn a new process popen = self.spawnSubprocess(exe, [pid_file_path]) diff --git a/lldb/test/API/functionalities/diagnostic_reporting/TestDiagnosticReporting.py b/lldb/test/API/functionalities/diagnostic_reporting/TestDiagnosticReporting.py --- a/lldb/test/API/functionalities/diagnostic_reporting/TestDiagnosticReporting.py +++ b/lldb/test/API/functionalities/diagnostic_reporting/TestDiagnosticReporting.py @@ -7,15 +7,16 @@ from lldbsuite.test.lldbtest import * -class TestDiagnosticReporting(TestBase): +class TestDiagnosticReporting(TestBase): def setUp(self): TestBase.setUp(self) self.broadcaster = self.dbg.GetBroadcaster() - self.listener = lldbutil.start_listening_from(self.broadcaster, - lldb.SBDebugger.eBroadcastBitWarning | - lldb.SBDebugger.eBroadcastBitError) + self.listener = lldbutil.start_listening_from( + self.broadcaster, + lldb.SBDebugger.eBroadcastBitWarning | lldb.SBDebugger.eBroadcastBitError, + ) def test_dwarf_symbol_loading_diagnostic_report(self): """Test that we are able to fetch diagnostic events""" @@ -24,15 +25,14 @@ self.dbg.CreateTarget(None) self.target = self.dbg.GetSelectedTarget() - self.process = self.target.LoadCore( - self.getBuildArtifact("minidump.core")) + self.process = self.target.LoadCore(self.getBuildArtifact("minidump.core")) event = lldbutil.fetch_next_event(self, self.listener, self.broadcaster) diagnostic_data = lldb.SBDebugger.GetDiagnosticFromEvent(event) self.assertEquals( - diagnostic_data.GetValueForKey("type").GetStringValue(100), - "warning") + diagnostic_data.GetValueForKey("type").GetStringValue(100), "warning" + ) self.assertEquals( diagnostic_data.GetValueForKey("message").GetStringValue(100), - "unable to retrieve process ID from minidump file, setting process ID to 1" + "unable to retrieve process ID from minidump file, setting process ID to 1", ) diff --git a/lldb/test/API/functionalities/disassemble/aarch64-adrp-add/TestAArch64AdrpAdd.py b/lldb/test/API/functionalities/disassemble/aarch64-adrp-add/TestAArch64AdrpAdd.py --- a/lldb/test/API/functionalities/disassemble/aarch64-adrp-add/TestAArch64AdrpAdd.py +++ b/lldb/test/API/functionalities/disassemble/aarch64-adrp-add/TestAArch64AdrpAdd.py @@ -6,8 +6,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestAArch64AdrpAdd(TestBase): +class TestAArch64AdrpAdd(TestBase): @no_debug_info_test @skipIfLLVMTargetMissing("AArch64") def test_arm64(self): @@ -47,10 +47,10 @@ found_hi_string = False found_foo = False - # The binary has an ADRP + ADD instruction pair which load + # The binary has an ADRP + ADD instruction pair which load # the pc-relative address of a c-string, and loads the address - # of a function into a function pointer. lldb should show - # that c-string and the name of that function in the disassembly + # of a function into a function pointer. lldb should show + # that c-string and the name of that function in the disassembly # comment field. for i in insns: if "HI" in i.GetComment(target): @@ -58,11 +58,14 @@ if "foo" in i.GetComment(target): found_foo = True if found_hi_string == False or found_foo == False: - print('Did not find "HI" string or "foo" in disassembly symbolication in %s' % binaryname) + print( + 'Did not find "HI" string or "foo" in disassembly symbolication in %s' + % binaryname + ) if self.TraceOn(): - strm = lldb.SBStream() - insns.GetDescription(strm) - print('Disassembly of main(), looking for "HI" and "foo" in comments:') - print(strm.GetData()) + strm = lldb.SBStream() + insns.GetDescription(strm) + print('Disassembly of main(), looking for "HI" and "foo" in comments:') + print(strm.GetData()) self.assertTrue(found_hi_string) self.assertTrue(found_foo) diff --git a/lldb/test/API/functionalities/dlopen_other_executable/TestDlopenOtherExecutable.py b/lldb/test/API/functionalities/dlopen_other_executable/TestDlopenOtherExecutable.py --- a/lldb/test/API/functionalities/dlopen_other_executable/TestDlopenOtherExecutable.py +++ b/lldb/test/API/functionalities/dlopen_other_executable/TestDlopenOtherExecutable.py @@ -3,8 +3,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestCase(TestBase): +class TestCase(TestBase): @skipIfRemote @skipIfWindows # glibc's dlopen doesn't support opening executables. @@ -17,7 +17,9 @@ def test(self): self.build() # Launch and stop before the dlopen call. - lldbutil.run_to_source_breakpoint(self, "// break here", lldb.SBFileSpec("main.c")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.c") + ) # Delete the breakpoint we no longer need. self.target().DeleteAllBreakpoints() @@ -27,7 +29,8 @@ # Continue so that dlopen is called. breakpoint = self.target().BreakpointCreateBySourceRegex( - "// break after dlopen", lldb.SBFileSpec("main.c")) + "// break after dlopen", lldb.SBFileSpec("main.c") + ) self.assertNotEqual(breakpoint.GetNumResolvedLocations(), 0) stopped_threads = lldbutil.continue_to_breakpoint(self.process(), breakpoint) self.assertEqual(len(stopped_threads), 1) diff --git a/lldb/test/API/functionalities/dwo/TestZeroDwoId.py b/lldb/test/API/functionalities/dwo/TestZeroDwoId.py --- a/lldb/test/API/functionalities/dwo/TestZeroDwoId.py +++ b/lldb/test/API/functionalities/dwo/TestZeroDwoId.py @@ -9,19 +9,19 @@ from lldbsuite.test import lldbutil import os -class ExecTestCase(TestBase): +class ExecTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True - def test_zero_dwo_id (self): - ''' - Test that we can load a .o file that has a skeleton compile unit - with a DWO ID of zero. We do this by hacking up the yaml to emit - zero as a DWO ID is both the .o file and .dwo file. Then we make - sure we can resolve something in the debug information to verify - that we were able to load the .dwo file corrrectly since that is - the only place that has this information. - ''' + def test_zero_dwo_id(self): + """ + Test that we can load a .o file that has a skeleton compile unit + with a DWO ID of zero. We do this by hacking up the yaml to emit + zero as a DWO ID is both the .o file and .dwo file. Then we make + sure we can resolve something in the debug information to verify + that we were able to load the .dwo file corrrectly since that is + the only place that has this information. + """ src_dir = self.getSourceDir() dwo_yaml_path = os.path.join(src_dir, "main.dwo.yaml") obj_yaml_path = os.path.join(src_dir, "main.o.yaml") @@ -38,7 +38,7 @@ # Set a breakpoint by file and line, this doesn't require anything from # the .dwo file. - bp = target.BreakpointCreateByLocation('main.cpp', 6) + bp = target.BreakpointCreateByLocation("main.cpp", 6) self.assertEqual(bp.GetNumLocations(), 1) bp_loc = bp.GetLocationAtIndex(0) self.assertTrue(bp_loc.IsValid()) diff --git a/lldb/test/API/functionalities/dyld-exec-linux/TestDyldExecLinux.py b/lldb/test/API/functionalities/dyld-exec-linux/TestDyldExecLinux.py --- a/lldb/test/API/functionalities/dyld-exec-linux/TestDyldExecLinux.py +++ b/lldb/test/API/functionalities/dyld-exec-linux/TestDyldExecLinux.py @@ -10,16 +10,17 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestLinux64ExecViaDynamicLoader(TestBase): NO_DEBUG_INFO_TESTCASE = True @skipIfXmlSupportMissing - @skipIf(oslist=no_match(['linux'])) + @skipIf(oslist=no_match(["linux"])) def test_with_svr4(self): self.runCmd("settings set plugin.process.gdb-remote.use-libraries-svr4 true") self._test() - @skipIf(oslist=no_match(['linux'])) + @skipIf(oslist=no_match(["linux"])) def test_without_svr4(self): self.runCmd("settings set plugin.process.gdb-remote.use-libraries-svr4 false") self._test() @@ -34,12 +35,12 @@ spec.SetFileSpec(lldb.SBFileSpec(exe)) interp_section = lldb.SBModule(spec).FindSection(".interp") if not interp_section: - return + return section_data = interp_section.GetSectionData() error = lldb.SBError() - dyld_path = section_data.GetString(error,0) + dyld_path = section_data.GetString(error, 0) if error.Fail(): - return + return target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) @@ -48,7 +49,9 @@ # program exec's via the dynamic loader. The breakpoint will only get # hit if we can successfully read the shared library lists in the # DynamicLoaderPOSIXDYLD.cpp when we exec into the dynamic loader. - breakpoint_main = target.BreakpointCreateBySourceRegex("// Break here", lldb.SBFileSpec("main.cpp")) + breakpoint_main = target.BreakpointCreateBySourceRegex( + "// Break here", lldb.SBFileSpec("main.cpp") + ) # Setup our launch info to supply the dynamic loader path to the # program so it gets two args: # - path to a.out @@ -61,7 +64,7 @@ threads = lldbutil.get_stopped_threads(process, lldb.eStopReasonExec) self.assertEqual(len(threads), 1, "We got a thread stopped for exec.") - process.Continue(); + process.Continue() # Stopped on main here. self.assertState(process.GetState(), lldb.eStateStopped) diff --git a/lldb/test/API/functionalities/dyld-launch-linux/TestDyldLaunchLinux.py b/lldb/test/API/functionalities/dyld-launch-linux/TestDyldLaunchLinux.py --- a/lldb/test/API/functionalities/dyld-launch-linux/TestDyldLaunchLinux.py +++ b/lldb/test/API/functionalities/dyld-launch-linux/TestDyldLaunchLinux.py @@ -8,9 +8,9 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * -class TestLinux64LaunchingViaDynamicLoader(TestBase): - @skipIf(oslist=no_match(['linux'])) +class TestLinux64LaunchingViaDynamicLoader(TestBase): + @skipIf(oslist=no_match(["linux"])) @no_debug_info_test @skipIf(oslist=["linux"], archs=["arm"]) def test(self): @@ -21,21 +21,31 @@ spec.SetFileSpec(lldb.SBFileSpec(self.getBuildArtifact("a.out"))) interp_section = lldb.SBModule(spec).FindSection(".interp") if not interp_section: - return + return section_data = interp_section.GetSectionData() error = lldb.SBError() - exe = section_data.GetString(error,0) + exe = section_data.GetString(error, 0) if error.Fail(): - return + return target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Set breakpoints both on shared library function as well as on # main. Both of them will be pending breakpoints. - breakpoint_main = target.BreakpointCreateBySourceRegex("// Break here", lldb.SBFileSpec("main.cpp")) - breakpoint_shared_library = target.BreakpointCreateBySourceRegex("get_signal_crash", lldb.SBFileSpec("signal_file.cpp")) - launch_info = lldb.SBLaunchInfo([ "--library-path", self.get_process_working_directory(), self.getBuildArtifact("a.out")]) + breakpoint_main = target.BreakpointCreateBySourceRegex( + "// Break here", lldb.SBFileSpec("main.cpp") + ) + breakpoint_shared_library = target.BreakpointCreateBySourceRegex( + "get_signal_crash", lldb.SBFileSpec("signal_file.cpp") + ) + launch_info = lldb.SBLaunchInfo( + [ + "--library-path", + self.get_process_working_directory(), + self.getBuildArtifact("a.out"), + ] + ) launch_info.SetWorkingDirectory(self.get_process_working_directory()) error = lldb.SBError() process = target.Launch(launch_info, error) @@ -49,7 +59,9 @@ # Stopped on get_signal_crash function here. self.assertState(process.GetState(), lldb.eStateStopped) - self.assertIn("get_signal_crash", thread.GetFrameAtIndex(0).GetDisplayFunctionName()) + self.assertIn( + "get_signal_crash", thread.GetFrameAtIndex(0).GetDisplayFunctionName() + ) process.Continue() # Stopped because of generated signal. diff --git a/lldb/test/API/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py b/lldb/test/API/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py --- a/lldb/test/API/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py +++ b/lldb/test/API/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py @@ -3,7 +3,6 @@ """ - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -11,7 +10,6 @@ class DynamicValueChildCountTestCase(TestBase): - def setUp(self): # Call super's setUp(). TestBase.setUp(self) @@ -19,15 +17,19 @@ # Find the line number to break for main.c. self.main_third_call_line = line_number( - 'pass-to-base.cpp', '// Break here and check b has 0 children') + "pass-to-base.cpp", "// Break here and check b has 0 children" + ) self.main_fourth_call_line = line_number( - 'pass-to-base.cpp', '// Break here and check b still has 0 children') + "pass-to-base.cpp", "// Break here and check b still has 0 children" + ) self.main_fifth_call_line = line_number( - 'pass-to-base.cpp', '// Break here and check b has one child now') + "pass-to-base.cpp", "// Break here and check b has one child now" + ) self.main_sixth_call_line = line_number( - 'pass-to-base.cpp', '// Break here and check b has 0 children again') + "pass-to-base.cpp", "// Break here and check b has 0 children again" + ) - @add_test_categories(['pyapi']) + @add_test_categories(["pyapi"]) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24663") def test_get_dynamic_vals(self): """Test fetching C++ dynamic values from pointers & references.""" @@ -43,28 +45,26 @@ # Set up our breakpoints: third_call_bpt = target.BreakpointCreateByLocation( - 'pass-to-base.cpp', self.main_third_call_line) - self.assertTrue(third_call_bpt, - VALID_BREAKPOINT) + "pass-to-base.cpp", self.main_third_call_line + ) + self.assertTrue(third_call_bpt, VALID_BREAKPOINT) fourth_call_bpt = target.BreakpointCreateByLocation( - 'pass-to-base.cpp', self.main_fourth_call_line) - self.assertTrue(fourth_call_bpt, - VALID_BREAKPOINT) + "pass-to-base.cpp", self.main_fourth_call_line + ) + self.assertTrue(fourth_call_bpt, VALID_BREAKPOINT) fifth_call_bpt = target.BreakpointCreateByLocation( - 'pass-to-base.cpp', self.main_fifth_call_line) - self.assertTrue(fifth_call_bpt, - VALID_BREAKPOINT) + "pass-to-base.cpp", self.main_fifth_call_line + ) + self.assertTrue(fifth_call_bpt, VALID_BREAKPOINT) sixth_call_bpt = target.BreakpointCreateByLocation( - 'pass-to-base.cpp', self.main_sixth_call_line) - self.assertTrue(sixth_call_bpt, - VALID_BREAKPOINT) + "pass-to-base.cpp", self.main_sixth_call_line + ) + self.assertTrue(sixth_call_bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) - self.assertState(process.GetState(), lldb.eStateStopped, - PROCESS_STOPPED) + self.assertState(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) b = self.frame().FindVariable("b").GetDynamicValue(lldb.eDynamicCanRunTarget) self.assertEquals(b.GetNumChildren(), 0, "b has 0 children") @@ -73,6 +73,4 @@ self.runCmd("continue") self.assertNotEqual(b.GetNumChildren(), 0, "b now has 1 child") self.runCmd("continue") - self.assertEqual( - b.GetNumChildren(), 0, - "b didn't go back to 0 children") + self.assertEqual(b.GetNumChildren(), 0, "b didn't go back to 0 children") diff --git a/lldb/test/API/functionalities/exec/TestExec.py b/lldb/test/API/functionalities/exec/TestExec.py --- a/lldb/test/API/functionalities/exec/TestExec.py +++ b/lldb/test/API/functionalities/exec/TestExec.py @@ -9,27 +9,32 @@ class ExecTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True - @expectedFailureAll(archs=['i386'], - oslist=no_match(["freebsd"]), - bugnumber="rdar://28656532") - @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://problem/34559552") # this exec test has problems on ios systems + @expectedFailureAll( + archs=["i386"], oslist=no_match(["freebsd"]), bugnumber="rdar://28656532" + ) + @expectedFailureAll( + oslist=["ios", "tvos", "watchos", "bridgeos"], + bugnumber="rdar://problem/34559552", + ) # this exec test has problems on ios systems @expectedFailureNetBSD - @skipIfAsan # rdar://problem/43756823 + @skipIfAsan # rdar://problem/43756823 @skipIfWindows - def test_hitting_exec (self): + def test_hitting_exec(self): self.do_test(False) - @expectedFailureAll(archs=['i386'], - oslist=no_match(["freebsd"]), - bugnumber="rdar://28656532") - @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://problem/34559552") # this exec test has problems on ios systems + @expectedFailureAll( + archs=["i386"], oslist=no_match(["freebsd"]), bugnumber="rdar://28656532" + ) + @expectedFailureAll( + oslist=["ios", "tvos", "watchos", "bridgeos"], + bugnumber="rdar://problem/34559552", + ) # this exec test has problems on ios systems @expectedFailureNetBSD - @skipIfAsan # rdar://problem/43756823 + @skipIfAsan # rdar://problem/43756823 @skipIfWindows - def test_skipping_exec (self): + def test_skipping_exec(self): self.do_test(True) def do_test(self, skip_exec): @@ -42,34 +47,37 @@ # Create any breakpoints we need breakpoint1 = target.BreakpointCreateBySourceRegex( - 'Set breakpoint 1 here', lldb.SBFileSpec("main.c", False)) + "Set breakpoint 1 here", lldb.SBFileSpec("main.c", False) + ) self.assertTrue(breakpoint1, VALID_BREAKPOINT) breakpoint2 = target.BreakpointCreateBySourceRegex( - 'Set breakpoint 2 here', lldb.SBFileSpec("secondprog.cpp", False)) + "Set breakpoint 2 here", lldb.SBFileSpec("secondprog.cpp", False) + ) self.assertTrue(breakpoint2, VALID_BREAKPOINT) # Launch the process - process = target.LaunchSimple( - None, None, self.get_process_working_directory()) + process = target.LaunchSimple(None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) if self.TraceOn(): self.runCmd("settings show target.process.stop-on-exec", check=False) if skip_exec: self.dbg.HandleCommand("settings set target.process.stop-on-exec false") + def cleanup(): - self.runCmd("settings set target.process.stop-on-exec false", - check=False) + self.runCmd( + "settings set target.process.stop-on-exec false", check=False + ) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # The stop reason of the thread should be breakpoint. - self.assertState(process.GetState(), lldb.eStateStopped, - STOPPED_DUE_TO_BREAKPOINT) + self.assertState( + process.GetState(), lldb.eStateStopped, STOPPED_DUE_TO_BREAKPOINT + ) - threads = lldbutil.get_threads_stopped_at_breakpoint( - process, breakpoint1) + threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint1) self.assertEqual(len(threads), 1) # We had a deadlock tearing down the TypeSystemMap on exec, but only if some @@ -78,9 +86,7 @@ thread = threads[0] value = thread.frames[0].EvaluateExpression("1 + 2") - self.assertTrue( - value.IsValid(), - "Expression evaluated successfully") + self.assertTrue(value.IsValid(), "Expression evaluated successfully") int_value = value.GetValueAsSigned() self.assertEqual(int_value, 3, "Expression got the right result.") @@ -88,16 +94,17 @@ process.Continue() if not skip_exec: - self.assertNotEqual(process.GetState(), lldb.eStateExited, - "Process should not have exited!") - self.assertState(process.GetState(), lldb.eStateStopped, - "Process should be stopped at __dyld_start") - - threads = lldbutil.get_stopped_threads( - process, lldb.eStopReasonExec) - self.assertEqual( - len(threads), 1, - "We got a thread stopped for exec.") + self.assertNotEqual( + process.GetState(), lldb.eStateExited, "Process should not have exited!" + ) + self.assertState( + process.GetState(), + lldb.eStateStopped, + "Process should be stopped at __dyld_start", + ) + + threads = lldbutil.get_stopped_threads(process, lldb.eStopReasonExec) + self.assertEqual(len(threads), 1, "We got a thread stopped for exec.") # Run and we should stop at breakpoint in main after exec process.Continue() @@ -105,41 +112,45 @@ self.assertState(process.GetState(), lldb.eStateStopped) for t in process.threads: if t.stop_reason != lldb.eStopReasonNone: - self.assertStopReason(t.stop_reason, lldb.eStopReasonBreakpoint, - "Unexpected stop reason") + self.assertStopReason( + t.stop_reason, lldb.eStopReasonBreakpoint, "Unexpected stop reason" + ) if self.TraceOn(): print(t) if t.stop_reason != lldb.eStopReasonBreakpoint: self.runCmd("bt") - threads = lldbutil.get_threads_stopped_at_breakpoint( - process, breakpoint2) - self.assertEqual(len(threads), 1, - "Stopped at breakpoint in exec'ed process.") + threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint2) + self.assertEqual(len(threads), 1, "Stopped at breakpoint in exec'ed process.") - @expectedFailureAll(archs=['i386'], - oslist=no_match(["freebsd"]), - bugnumber="rdar://28656532") - @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://problem/34559552") # this exec test has problems on ios systems + @expectedFailureAll( + archs=["i386"], oslist=no_match(["freebsd"]), bugnumber="rdar://28656532" + ) + @expectedFailureAll( + oslist=["ios", "tvos", "watchos", "bridgeos"], + bugnumber="rdar://problem/34559552", + ) # this exec test has problems on ios systems @expectedFailureNetBSD - @skipIfAsan # rdar://problem/43756823 + @skipIfAsan # rdar://problem/43756823 @skipIfWindows def test_correct_thread_plan_state_before_exec(self): - ''' + """ In this test we make sure that the Thread* cache in the ThreadPlans is cleared correctly when performing exec - ''' + """ self.build() exe = self.getBuildArtifact("a.out") target = self.dbg.CreateTarget(exe) (target, process, thread, breakpoint1) = lldbutil.run_to_source_breakpoint( - self, 'Set breakpoint 1 here', lldb.SBFileSpec('main.c', False)) + self, "Set breakpoint 1 here", lldb.SBFileSpec("main.c", False) + ) # The stop reason of the thread should be breakpoint. - self.assertState(process.GetState(), lldb.eStateStopped, - STOPPED_DUE_TO_BREAKPOINT) + self.assertState( + process.GetState(), lldb.eStateStopped, STOPPED_DUE_TO_BREAKPOINT + ) threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint1) self.assertEqual(len(threads), 1) @@ -159,25 +170,25 @@ # Run and we should stop due to exec breakpoint2 = target.BreakpointCreateBySourceRegex( - 'Set breakpoint 2 here', lldb.SBFileSpec("secondprog.cpp", False)) + "Set breakpoint 2 here", lldb.SBFileSpec("secondprog.cpp", False) + ) process.Continue() - self.assertNotEqual(process.GetState(), lldb.eStateExited, - "Process should not have exited!") - self.assertState(process.GetState(), lldb.eStateStopped, - "Process should be stopped at __dyld_start") + self.assertNotEqual( + process.GetState(), lldb.eStateExited, "Process should not have exited!" + ) + self.assertState( + process.GetState(), + lldb.eStateStopped, + "Process should be stopped at __dyld_start", + ) - threads = lldbutil.get_stopped_threads( - process, lldb.eStopReasonExec) - self.assertEqual( - len(threads), 1, - "We got a thread stopped for exec.") + threads = lldbutil.get_stopped_threads(process, lldb.eStopReasonExec) + self.assertEqual(len(threads), 1, "We got a thread stopped for exec.") # Run and we should stop at breakpoint in main after exec process.Continue() - threads = lldbutil.get_threads_stopped_at_breakpoint( - process, breakpoint2) - self.assertEqual(len(threads), 1, - "Stopped at breakpoint in exec'ed process.") + threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint2) + self.assertEqual(len(threads), 1, "Stopped at breakpoint in exec'ed process.") diff --git a/lldb/test/API/functionalities/fat_archives/TestFatArchives.py b/lldb/test/API/functionalities/fat_archives/TestFatArchives.py --- a/lldb/test/API/functionalities/fat_archives/TestFatArchives.py +++ b/lldb/test/API/functionalities/fat_archives/TestFatArchives.py @@ -10,31 +10,31 @@ class FatArchiveTestCase(TestBase): - NO_DEBUG_INFO_TESTCASE = True @skipUnlessDarwin def test_breakpoint_resolution_dwarf(self): - if self.getArchitecture() == 'x86_64': + if self.getArchitecture() == "x86_64": self.build() self.main() else: self.skipTest( - "This test requires x86_64 as the architecture for the inferior") + "This test requires x86_64 as the architecture for the inferior" + ) def main(self): - '''This test compiles a quick example by making a fat file (universal) full of + """This test compiles a quick example by making a fat file (universal) full of skinny .o files and makes sure we can use them to resolve breakpoints when doing DWARF in .o file debugging. The only thing this test needs to do is to compile and set a breakpoint in the target and verify any breakpoint locations have valid debug - info for the function, and source file and line.''' + info for the function, and source file and line.""" exe = self.getBuildArtifact("a.out") # Create the target target = self.dbg.CreateTarget(exe) # Create a breakpoint by name - breakpoint = target.BreakpointCreateByName('foo', exe) + breakpoint = target.BreakpointCreateByName("foo", exe) self.assertTrue(breakpoint, VALID_BREAKPOINT) # Make sure the breakpoint resolves to a function, file and line @@ -46,10 +46,14 @@ function = bp_loc_addr.GetFunction() self.assertTrue( function.IsValid(), - "Verify breakpoint in fat BSD archive has valid function debug info") + "Verify breakpoint in fat BSD archive has valid function debug info", + ) self.assertTrue( line_entry.GetFileSpec(), - "Verify breakpoint in fat BSD archive has source file information") + "Verify breakpoint in fat BSD archive has source file information", + ) self.assertNotEqual( - line_entry.GetLine(), 0, - "Verify breakpoint in fat BSD archive has source line information") + line_entry.GetLine(), + 0, + "Verify breakpoint in fat BSD archive has source line information", + ) diff --git a/lldb/test/API/functionalities/find-line-entry/TestFindLineEntry.py b/lldb/test/API/functionalities/find-line-entry/TestFindLineEntry.py --- a/lldb/test/API/functionalities/find-line-entry/TestFindLineEntry.py +++ b/lldb/test/API/functionalities/find-line-entry/TestFindLineEntry.py @@ -6,10 +6,10 @@ import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * -class FindLineEntry(TestBase): +class FindLineEntry(TestBase): def test_compile_unit_find_line_entry_index(self): - """ Test the CompileUnit LineEntryIndex lookup API """ + """Test the CompileUnit LineEntryIndex lookup API""" self.build() exe = self.getBuildArtifact("a.out") self.target = self.dbg.CreateTarget(exe) @@ -23,9 +23,12 @@ # First look for valid line self.line = line_number("main.c", "int change_me") - self.assertNotEqual(cu.FindLineEntryIndex(0, self.line, self.file), - lldb.LLDB_INVALID_LINE_NUMBER) + self.assertNotEqual( + cu.FindLineEntryIndex(0, self.line, self.file), + lldb.LLDB_INVALID_LINE_NUMBER, + ) # Then look for a line out of bound - self.assertEqual(cu.FindLineEntryIndex(0, 42, self.file), - lldb.LLDB_INVALID_LINE_NUMBER) + self.assertEqual( + cu.FindLineEntryIndex(0, 42, self.file), lldb.LLDB_INVALID_LINE_NUMBER + ) diff --git a/lldb/test/API/functionalities/float-display/TestFloatDisplay.py b/lldb/test/API/functionalities/float-display/TestFloatDisplay.py --- a/lldb/test/API/functionalities/float-display/TestFloatDisplay.py +++ b/lldb/test/API/functionalities/float-display/TestFloatDisplay.py @@ -1,5 +1,4 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest( - __file__, globals(), []) +lldbinline.MakeInlineTest(__file__, globals(), []) diff --git a/lldb/test/API/functionalities/fork/resumes-child/TestForkResumesChild.py b/lldb/test/API/functionalities/fork/resumes-child/TestForkResumesChild.py --- a/lldb/test/API/functionalities/fork/resumes-child/TestForkResumesChild.py +++ b/lldb/test/API/functionalities/fork/resumes-child/TestForkResumesChild.py @@ -3,7 +3,6 @@ """ - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * @@ -11,12 +10,13 @@ class TestForkResumesChild(TestBase): - NO_DEBUG_INFO_TESTCASE = True @skipIfWindows def test_step_over_fork(self): self.build() - lldbutil.run_to_source_breakpoint(self, "// break here", lldb.SBFileSpec("main.cpp")) + lldbutil.run_to_source_breakpoint( + self, "// break here", lldb.SBFileSpec("main.cpp") + ) self.runCmd("next") - self.expect("continue", substrs = ["exited with status = 0"]) + self.expect("continue", substrs=["exited with status = 0"]) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestAArch64XMLRegOffsets.py b/lldb/test/API/functionalities/gdb_remote_client/TestAArch64XMLRegOffsets.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestAArch64XMLRegOffsets.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestAArch64XMLRegOffsets.py @@ -9,7 +9,9 @@ class MyResponder(MockGDBServerResponder): def qXferRead(self, obj, annex, offset, length): if annex == "target.xml": - return dedent("""\ + return ( + dedent( + """\ aarch64 @@ -79,9 +81,12 @@ - """), False + """ + ), + False, + ) else: - return None, + return (None,) def readRegister(self, regnum): return "E01" @@ -91,7 +96,6 @@ class TestAArch64XMLRegOffsets(GDBRemoteTestBase): - @skipIfXmlSupportMissing @skipIfRemote @skipIfLLVMTargetMissing("AArch64") @@ -106,46 +110,85 @@ if self.TraceOn(): self.runCmd("log enable gdb-remote packets") - self.addTearDownHook( - lambda: self.runCmd("log disable gdb-remote packets")) + self.addTearDownHook(lambda: self.runCmd("log disable gdb-remote packets")) process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) - registerSet = process.GetThreadAtIndex( - 0).GetFrameAtIndex(0).GetRegisters().GetValueAtIndex(0) + registerSet = ( + process.GetThreadAtIndex(0) + .GetFrameAtIndex(0) + .GetRegisters() + .GetValueAtIndex(0) + ) reg_val_dict = { - "x0": 0x0000000000000020, "x1": 0x0000000000000020, - "x2": 0x0000ffffbf54c1f0, "x3": 0x480bea8f5a98aa5d, - "x4": 0x0000ffffbf54b9f0, "x5": 0x480b1570e5cc13ad, - "x6": 0x0000000000000038, "x7": 0x0000ffffbf6a4570, - "x8": 0x00000000000000a7, "x9": 0x0000000000000000, - "x10": 0x0101010101010101, "x11": 0x0000000000000000, - "x12": 0x0000ffffbf54c1f0, "x13": 0x000000000000270f, - "x14": 0x0000ffffbf55e308, "x15": 0x0000ffffbf550e08, - "x16": 0x0000000000411028, "x17": 0x0000ffffbf61de10, - "x18": 0x000000000000055c, "x19": 0x0000ffffbf54c1f0, - "x20": 0x0000fffffffffc90, "x21": 0x0000fffffffffc8e, - "x22": 0x0000fffffffffc8f, "x23": 0x0000000000000000, - "x24": 0x0000000000001000, "x25": 0x0000fffffffffc90, - "x26": 0x0000ffffbf6cd000, "x27": 0x0000ffffbf54c1f0, - "x28": 0x0000000000000001, "x29": 0x0000ffffbf54b9d0, - "x30": 0x00000000004007e4, "sp": 0x0000ffffbf54b9d0, - "pc": 0x00000000004007e4, "cpsr": 0x00001000, "w0": 0x00000020, - "w1": 0x00000020, "w2": 0xbf54c1f0, "w3": 0x5a98aa5d, - "w4": 0xbf54b9f0, "w5": 0xe5cc13ad, "w6": 0x00000038, - "w7": 0xbf6a4570, "w8": 0x000000a7, "w9": 0x00000000, - "w10": 0x01010101, "w11": 0x00000000, "w12": 0xbf54c1f0, - "w13": 0x0000270f, "w14": 0xbf55e308, "w15": 0xbf550e08, - "w16": 0x00411028, "w17": 0xbf61de10, "w18": 0x0000055c, - "w19": 0xbf54c1f0, "w20": 0xfffffc90, "w21": 0xfffffc8e, - "w22": 0xfffffc8f, "w23": 0x00000000, "w24": 0x00001000, - "w25": 0xfffffc90, "w26": 0xbf6cd000, "w27": 0xbf54c1f0, - "w28": 0x00000001 + "x0": 0x0000000000000020, + "x1": 0x0000000000000020, + "x2": 0x0000FFFFBF54C1F0, + "x3": 0x480BEA8F5A98AA5D, + "x4": 0x0000FFFFBF54B9F0, + "x5": 0x480B1570E5CC13AD, + "x6": 0x0000000000000038, + "x7": 0x0000FFFFBF6A4570, + "x8": 0x00000000000000A7, + "x9": 0x0000000000000000, + "x10": 0x0101010101010101, + "x11": 0x0000000000000000, + "x12": 0x0000FFFFBF54C1F0, + "x13": 0x000000000000270F, + "x14": 0x0000FFFFBF55E308, + "x15": 0x0000FFFFBF550E08, + "x16": 0x0000000000411028, + "x17": 0x0000FFFFBF61DE10, + "x18": 0x000000000000055C, + "x19": 0x0000FFFFBF54C1F0, + "x20": 0x0000FFFFFFFFFC90, + "x21": 0x0000FFFFFFFFFC8E, + "x22": 0x0000FFFFFFFFFC8F, + "x23": 0x0000000000000000, + "x24": 0x0000000000001000, + "x25": 0x0000FFFFFFFFFC90, + "x26": 0x0000FFFFBF6CD000, + "x27": 0x0000FFFFBF54C1F0, + "x28": 0x0000000000000001, + "x29": 0x0000FFFFBF54B9D0, + "x30": 0x00000000004007E4, + "sp": 0x0000FFFFBF54B9D0, + "pc": 0x00000000004007E4, + "cpsr": 0x00001000, + "w0": 0x00000020, + "w1": 0x00000020, + "w2": 0xBF54C1F0, + "w3": 0x5A98AA5D, + "w4": 0xBF54B9F0, + "w5": 0xE5CC13AD, + "w6": 0x00000038, + "w7": 0xBF6A4570, + "w8": 0x000000A7, + "w9": 0x00000000, + "w10": 0x01010101, + "w11": 0x00000000, + "w12": 0xBF54C1F0, + "w13": 0x0000270F, + "w14": 0xBF55E308, + "w15": 0xBF550E08, + "w16": 0x00411028, + "w17": 0xBF61DE10, + "w18": 0x0000055C, + "w19": 0xBF54C1F0, + "w20": 0xFFFFFC90, + "w21": 0xFFFFFC8E, + "w22": 0xFFFFFC8F, + "w23": 0x00000000, + "w24": 0x00001000, + "w25": 0xFFFFFC90, + "w26": 0xBF6CD000, + "w27": 0xBF54C1F0, + "w28": 0x00000001, } for reg in registerSet: - self.assertEqual(reg.GetValueAsUnsigned(), - reg_val_dict[reg.GetName()]) + self.assertEqual(reg.GetValueAsUnsigned(), reg_val_dict[reg.GetName()]) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestArmRegisterDefinition.py b/lldb/test/API/functionalities/gdb_remote_client/TestArmRegisterDefinition.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestArmRegisterDefinition.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestArmRegisterDefinition.py @@ -4,8 +4,8 @@ from lldbsuite.test.gdbclientutils import * from lldbsuite.test.lldbgdbclient import GDBRemoteTestBase -class TestArmRegisterDefinition(GDBRemoteTestBase): +class TestArmRegisterDefinition(GDBRemoteTestBase): @skipIfXmlSupportMissing @skipIfRemote def test(self): @@ -13,11 +13,12 @@ Test lldb's parsing of the tag in the target.xml register description packet. """ - class MyResponder(MockGDBServerResponder): + class MyResponder(MockGDBServerResponder): def qXferRead(self, obj, annex, offset, length): if annex == "target.xml": - return """ + return ( + """ arm @@ -83,7 +84,9 @@ - """, False + """, + False, + ) else: return None, False @@ -98,7 +101,7 @@ def qfThreadInfo(self): return "mdead" - + def qC(self): return "" @@ -114,8 +117,7 @@ self.server.responder = MyResponder() if self.TraceOn(): self.runCmd("log enable gdb-remote packets") - self.addTearDownHook( - lambda: self.runCmd("log disable gdb-remote packets")) + self.addTearDownHook(lambda: self.runCmd("log disable gdb-remote packets")) self.dbg.SetDefaultArchitecture("armv7em") target = self.dbg.CreateTargetWithFileAndArch(None, None) @@ -132,16 +134,16 @@ self.assertEqual(r0_valobj.GetValueAsUnsigned(), 0x20) pc_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("pc") - self.assertEqual(pc_valobj.GetValueAsUnsigned(), 0x0800d22e) + self.assertEqual(pc_valobj.GetValueAsUnsigned(), 0x0800D22E) sys_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("SYS0") - self.assertEqual(sys_valobj.GetValueAsUnsigned(), 0xdead) + self.assertEqual(sys_valobj.GetValueAsUnsigned(), 0xDEAD) sys_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("SYS1") - self.assertEqual(sys_valobj.GetValueAsUnsigned(), 0xbe) + self.assertEqual(sys_valobj.GetValueAsUnsigned(), 0xBE) sys_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("SYS2") - self.assertEqual(sys_valobj.GetValueAsUnsigned(), 0xaf) + self.assertEqual(sys_valobj.GetValueAsUnsigned(), 0xAF) sys_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("SYS3") - self.assertEqual(sys_valobj.GetValueAsUnsigned(), 0xbc) + self.assertEqual(sys_valobj.GetValueAsUnsigned(), 0xBC) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestContinue.py b/lldb/test/API/functionalities/gdb_remote_client/TestContinue.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestContinue.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestContinue.py @@ -38,8 +38,9 @@ self.runCmd("platform select remote-linux") target = self.createTarget("a.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateExited]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateExited] + ) self.assertPacketLogContains(["vCont;C13:401"]) def test_continue_no_vCont(self): @@ -57,8 +58,9 @@ self.runCmd("platform select remote-linux") target = self.createTarget("a.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateExited]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateExited] + ) self.assertPacketLogContains(["Hc401", "C13"]) def test_continue_multiprocess(self): @@ -69,6 +71,7 @@ self.runCmd("platform select remote-linux") target = self.createTarget("a.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateExited]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateExited] + ) self.assertPacketLogContains(["vCont;C13:p400.401"]) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestDynamicLoaderDarwin.py b/lldb/test/API/functionalities/gdb_remote_client/TestDynamicLoaderDarwin.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestDynamicLoaderDarwin.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestDynamicLoaderDarwin.py @@ -90,11 +90,11 @@ arm64_binary = "cffaedfe0c000001000000000200000010000000e8020000850020000000000019000000480000005f5f504147455a45524f00000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000019000000e80000005f5f54455854000000000000000000000000000001000000004000000000000000000000000000000040000000000000050000000500000002000000000000005f5f74657874000000000000000000005f5f5445585400000000000000000000b03f0000010000000800000000000000b03f0000020000000000000000000000000400800000000000000000000000005f5f756e77696e645f696e666f0000005f5f5445585400000000000000000000b83f0000010000004800000000000000b83f00000200000000000000000000000000000000000000000000000000000019000000480000005f5f4c494e4b45444954000000000000004000000100000000400000000000000040000000000000b8010000000000000100000001000000000000000000000034000080100000000040000038000000330000801000000038400000300000000200000018000000704000000100000080400000180000000b000000500000000000000000000000000000000100000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e000000200000000c0000002f7573722f6c69622f64796c64000000000000001b00000018000000a9981092eb3632f4afd9957e769160d932000000200000000100000000000c0000050c000100000003000000000633032a0000001000000000000000000000002800008018000000b03f00000000000000000000000000000c00000038000000180000000200000001781f05000001002f7573722f6c69622f6c696253797374656d2e422e64796c696200000000000026000000100000006840000008000000290000001000000070400000000000001d00000010000000a04000001801" -class TestDynamicLoaderDarwin(GDBRemoteTestBase): +class TestDynamicLoaderDarwin(GDBRemoteTestBase): NO_DEBUG_INFO_TESTCASE = True - class MyResponder(MockGDBServerResponder): + class MyResponder(MockGDBServerResponder): def __init__(self, cpusubtype): self.cpusubtype = cpusubtype MockGDBServerResponder.__init__(self) @@ -111,8 +111,8 @@ return "pid:a860;parent-pid:d2a0;real-uid:1f5;real-gid:14;effective-uid:1f5;effective-gid:14;cputype:100000c;cpusubtype:2;ptrsize:8;ostype:macosx;vendor:apple;endian:little;" def jGetLoadedDynamicLibrariesInfos(self, packet): - if 'fetch_all_solibs' in packet: - return escape_binary(images%self.cpusubtype) + if "fetch_all_solibs" in packet: + return escape_binary(images % self.cpusubtype) return "OK" def vCont(self): @@ -126,8 +126,8 @@ # arm64_binary is just a hex-encoded (hence the 2*) Mach-O # header, pad out the rest with NUL characters, it doesn't # matter for this test. - memory = arm64_binary + '00'*(length-len(arm64_binary)<<1) - return memory[2*file_offset:] + memory = arm64_binary + "00" * (length - len(arm64_binary) << 1) + return memory[2 * file_offset :] def setBreakpoint(self, packet): return "" @@ -142,8 +142,7 @@ self.server.responder = self.MyResponder(subtype_arm64e) if self.TraceOn(): self.runCmd("log enable gdb-remote packets") - self.addTearDownHook( - lambda: self.runCmd("log disable gdb-remote packets")) + self.addTearDownHook(lambda: self.runCmd("log disable gdb-remote packets")) target = self.dbg.CreateTargetWithFileAndArch(None, None) process = self.connect(target) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestFork.py b/lldb/test/API/functionalities/gdb_remote_client/TestFork.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestFork.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestFork.py @@ -7,7 +7,6 @@ class TestMultiprocess(GDBRemoteTestBase): - def base_test(self, variant, follow_child=False): class MyResponder(MockGDBServerResponder): def __init__(self): @@ -20,7 +19,8 @@ assert "multiprocess+" in client_supported assert self.property in client_supported return "{};multiprocess+;{}".format( - super().qSupported(client_supported), self.property) + super().qSupported(client_supported), self.property + ) def qfThreadInfo(self): return "mp400.10200" @@ -28,8 +28,9 @@ def cont(self): if self.first: self.first = False - return ("T0fthread:p400.10200;reason:{0};{0}:p401.10400;" - .format(variant)) + return "T0fthread:p400.10200;reason:{0};{0}:p401.10400;".format( + variant + ) return "W00" def D(self, packet): @@ -37,20 +38,19 @@ return "OK" self.server.responder = MyResponder() - target = self.dbg.CreateTarget('') + target = self.dbg.CreateTarget("") if self.TraceOn(): - self.runCmd("log enable gdb-remote packets") - self.addTearDownHook( - lambda: self.runCmd("log disable gdb-remote packets")) + self.runCmd("log enable gdb-remote packets") + self.addTearDownHook(lambda: self.runCmd("log disable gdb-remote packets")) if follow_child: self.runCmd("settings set target.process.follow-fork-mode child") process = self.connect(target) self.assertEqual(process.GetProcessID(), 1024) process.Continue() - self.assertRegex(self.server.responder.detached, - r"D;0*400" if follow_child else r"D;0*401") - self.assertEqual(process.GetProcessID(), - 1025 if follow_child else 1024) + self.assertRegex( + self.server.responder.detached, r"D;0*400" if follow_child else r"D;0*401" + ) + self.assertEqual(process.GetProcessID(), 1025 if follow_child else 1024) def test_fork(self): self.base_test("fork") diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemoteClient.py b/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemoteClient.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemoteClient.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemoteClient.py @@ -8,7 +8,6 @@ class TestGDBRemoteClient(GDBRemoteTestBase): - class gPacketResponder(MockGDBServerResponder): registers = [ "name:rax;bitsize:64;offset:0;encoding:uint;format:hex;set:General Purpose Registers;ehframe:0;dwarf:0;", @@ -28,7 +27,7 @@ return "E45" def readRegisters(self): - return len(self.registers) * 16 * '0' + return len(self.registers) * 16 * "0" def readRegister(self, register): return "0000000000000000" @@ -48,7 +47,7 @@ return "E42" def qfThreadInfo(self): - return "OK" # No threads. + return "OK" # No threads. # Then, when we are asked to attach, error out. def vAttach(self, pid): @@ -58,7 +57,9 @@ target = self.dbg.CreateTarget("") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, [lldb.eStateConnected]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateConnected] + ) error = lldb.SBError() target.AttachToProcessWithID(lldb.SBListener(), 47, error) @@ -71,7 +72,7 @@ return "E42" def qfThreadInfo(self): - return "OK" # No threads. + return "OK" # No threads. # Then, when we are asked to attach, error out. def A(self, packet): @@ -81,11 +82,14 @@ target = self.createTarget("a.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, [lldb.eStateConnected]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateConnected] + ) error = lldb.SBError() - target.Launch(lldb.SBListener(), None, None, None, None, None, - None, 0, True, error) + target.Launch( + lldb.SBListener(), None, None, None, None, None, None, 0, True, error + ) self.assertRegex(error.GetCString(), "Cannot launch '.*a': Error 71") def test_launch_rich_error(self): @@ -94,7 +98,7 @@ return "E42" def qfThreadInfo(self): - return "OK" # No threads. + return "OK" # No threads. # Then, when we are asked to attach, error out. def vRun(self, packet): @@ -104,19 +108,26 @@ target = self.createTarget("a.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, [lldb.eStateConnected]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateConnected] + ) error = lldb.SBError() - target.Launch(lldb.SBListener(), None, None, None, None, None, - None, 0, True, error) + target.Launch( + lldb.SBListener(), None, None, None, None, None, None, 0, True, error + ) self.assertRegex(error.GetCString(), "Cannot launch '.*a': I'm a teapot") def test_read_registers_using_g_packets(self): """Test reading registers using 'g' packets (default behavior)""" self.dbg.HandleCommand( - "settings set plugin.process.gdb-remote.use-g-packet-for-reading true") - self.addTearDownHook(lambda: - self.runCmd("settings set plugin.process.gdb-remote.use-g-packet-for-reading false")) + "settings set plugin.process.gdb-remote.use-g-packet-for-reading true" + ) + self.addTearDownHook( + lambda: self.runCmd( + "settings set plugin.process.gdb-remote.use-g-packet-for-reading false" + ) + ) self.server.responder = self.gPacketResponder() target = self.createTarget("a.yaml") process = self.connect(target) @@ -126,12 +137,14 @@ self.read_registers(process) # Reading registers should not cause any 'p' packets to be exchanged. self.assertEquals( - 0, len([p for p in self.server.responder.packetLog if p.startswith("p")])) + 0, len([p for p in self.server.responder.packetLog if p.startswith("p")]) + ) def test_read_registers_using_p_packets(self): """Test reading registers using 'p' packets""" self.dbg.HandleCommand( - "settings set plugin.process.gdb-remote.use-g-packet-for-reading false") + "settings set plugin.process.gdb-remote.use-g-packet-for-reading false" + ) self.server.responder = self.gPacketResponder() target = self.createTarget("a.yaml") process = self.connect(target) @@ -139,7 +152,8 @@ self.read_registers(process) self.assertNotIn("g", self.server.responder.packetLog) self.assertGreater( - len([p for p in self.server.responder.packetLog if p.startswith("p")]), 0) + len([p for p in self.server.responder.packetLog if p.startswith("p")]), 0 + ) def test_write_registers_using_P_packets(self): """Test writing registers using 'P' packets (default behavior)""" @@ -148,10 +162,12 @@ process = self.connect(target) self.write_registers(process) - self.assertEquals(0, len( - [p for p in self.server.responder.packetLog if p.startswith("G")])) + self.assertEquals( + 0, len([p for p in self.server.responder.packetLog if p.startswith("G")]) + ) self.assertGreater( - len([p for p in self.server.responder.packetLog if p.startswith("P")]), 0) + len([p for p in self.server.responder.packetLog if p.startswith("P")]), 0 + ) def test_write_registers_using_G_packets(self): """Test writing registers using 'G' packets""" @@ -166,18 +182,22 @@ process = self.connect(target) self.write_registers(process) - self.assertEquals(0, len( - [p for p in self.server.responder.packetLog if p.startswith("P")])) - self.assertGreater(len( - [p for p in self.server.responder.packetLog if p.startswith("G")]), 0) + self.assertEquals( + 0, len([p for p in self.server.responder.packetLog if p.startswith("P")]) + ) + self.assertGreater( + len([p for p in self.server.responder.packetLog if p.startswith("G")]), 0 + ) def read_registers(self, process): self.for_each_gpr( - process, lambda r: self.assertEquals("0x0000000000000000", r.GetValue())) + process, lambda r: self.assertEquals("0x0000000000000000", r.GetValue()) + ) def write_registers(self, process): self.for_each_gpr( - process, lambda r: r.SetValueFromCString("0x0000000000000000")) + process, lambda r: r.SetValueFromCString("0x0000000000000000") + ) def for_each_gpr(self, process, operation): registers = process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetRegisters() @@ -204,7 +224,7 @@ if self.started: return "mp10.10" else: - return "E42" + return "E42" def qsThreadInfo(self): return "l" @@ -222,29 +242,34 @@ target = self.createTarget("a.yaml") # NB: apparently GDB packets are using "/" on Windows too - exe_path = self.getBuildArtifact("a").replace(os.path.sep, '/') + exe_path = self.getBuildArtifact("a").replace(os.path.sep, "/") exe_hex = binascii.b2a_hex(exe_path.encode()).decode() process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateConnected]) - - target.Launch(lldb.SBListener(), - ["arg1", "arg2", "arg3"], # argv - [], # envp - None, # stdin_path - None, # stdout_path - None, # stderr_path - None, # working_directory - 0, # launch_flags - True, # stop_at_entry - lldb.SBError()) # error + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateConnected] + ) + + target.Launch( + lldb.SBListener(), + ["arg1", "arg2", "arg3"], # argv + [], # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working_directory + 0, # launch_flags + True, # stop_at_entry + lldb.SBError(), + ) # error self.assertTrue(process, PROCESS_IS_VALID) self.assertEqual(process.GetProcessID(), 16) - self.assertPacketLogContains([ - "A%d,0,%s,8,1,61726731,8,2,61726732,8,3,61726733" % ( - len(exe_hex), exe_hex), - ]) + self.assertPacketLogContains( + [ + "A%d,0,%s,8,1,61726731,8,2,61726732,8,3,61726733" + % (len(exe_hex), exe_hex), + ] + ) def test_launch_vRun(self): class MyResponder(MockGDBServerResponder): @@ -262,7 +287,7 @@ if self.started: return "mp10.10" else: - return "E42" + return "E42" def qsThreadInfo(self): return "l" @@ -278,28 +303,31 @@ target = self.createTarget("a.yaml") # NB: apparently GDB packets are using "/" on Windows too - exe_path = self.getBuildArtifact("a").replace(os.path.sep, '/') + exe_path = self.getBuildArtifact("a").replace(os.path.sep, "/") exe_hex = binascii.b2a_hex(exe_path.encode()).decode() process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateConnected]) - - process = target.Launch(lldb.SBListener(), - ["arg1", "arg2", "arg3"], # argv - [], # envp - None, # stdin_path - None, # stdout_path - None, # stderr_path - None, # working_directory - 0, # launch_flags - True, # stop_at_entry - lldb.SBError()) # error + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateConnected] + ) + + process = target.Launch( + lldb.SBListener(), + ["arg1", "arg2", "arg3"], # argv + [], # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working_directory + 0, # launch_flags + True, # stop_at_entry + lldb.SBError(), + ) # error self.assertTrue(process, PROCESS_IS_VALID) self.assertEqual(process.GetProcessID(), 16) - self.assertPacketLogContains([ - "vRun;%s;61726731;61726732;61726733" % (exe_hex,) - ]) + self.assertPacketLogContains( + ["vRun;%s;61726731;61726732;61726733" % (exe_hex,)] + ) def test_launch_QEnvironment(self): class MyResponder(MockGDBServerResponder): @@ -307,7 +335,7 @@ return "E42" def qfThreadInfo(self): - return "E42" + return "E42" def vRun(self, packet): self.started = True @@ -317,34 +345,40 @@ target = self.createTarget("a.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateConnected]) - - target.Launch(lldb.SBListener(), - [], # argv - ["PLAIN=foo", - "NEEDSENC=frob$", - "NEEDSENC2=fr*ob", - "NEEDSENC3=fro}b", - "NEEDSENC4=f#rob", - "EQUALS=foo=bar", - ], # envp - None, # stdin_path - None, # stdout_path - None, # stderr_path - None, # working_directory - 0, # launch_flags - True, # stop_at_entry - lldb.SBError()) # error - - self.assertPacketLogContains([ - "QEnvironmentHexEncoded:4e45454453454e43333d66726f7d62", - "QEnvironmentHexEncoded:4e45454453454e43343d6623726f62", - "QEnvironment:PLAIN=foo", - "QEnvironmentHexEncoded:4e45454453454e43323d66722a6f62", - "QEnvironmentHexEncoded:4e45454453454e433d66726f6224", - "QEnvironment:EQUALS=foo=bar", - ]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateConnected] + ) + + target.Launch( + lldb.SBListener(), + [], # argv + [ + "PLAIN=foo", + "NEEDSENC=frob$", + "NEEDSENC2=fr*ob", + "NEEDSENC3=fro}b", + "NEEDSENC4=f#rob", + "EQUALS=foo=bar", + ], # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working_directory + 0, # launch_flags + True, # stop_at_entry + lldb.SBError(), + ) # error + + self.assertPacketLogContains( + [ + "QEnvironmentHexEncoded:4e45454453454e43333d66726f7d62", + "QEnvironmentHexEncoded:4e45454453454e43343d6623726f62", + "QEnvironment:PLAIN=foo", + "QEnvironmentHexEncoded:4e45454453454e43323d66722a6f62", + "QEnvironmentHexEncoded:4e45454453454e433d66726f6224", + "QEnvironment:EQUALS=foo=bar", + ] + ) def test_launch_QEnvironmentHexEncoded_only(self): class MyResponder(MockGDBServerResponder): @@ -352,7 +386,7 @@ return "E42" def qfThreadInfo(self): - return "E42" + return "E42" def vRun(self, packet): self.started = True @@ -365,34 +399,40 @@ target = self.createTarget("a.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateConnected]) - - target.Launch(lldb.SBListener(), - [], # argv - ["PLAIN=foo", - "NEEDSENC=frob$", - "NEEDSENC2=fr*ob", - "NEEDSENC3=fro}b", - "NEEDSENC4=f#rob", - "EQUALS=foo=bar", - ], # envp - None, # stdin_path - None, # stdout_path - None, # stderr_path - None, # working_directory - 0, # launch_flags - True, # stop_at_entry - lldb.SBError()) # error - - self.assertPacketLogContains([ - "QEnvironmentHexEncoded:4e45454453454e43333d66726f7d62", - "QEnvironmentHexEncoded:4e45454453454e43343d6623726f62", - "QEnvironmentHexEncoded:504c41494e3d666f6f", - "QEnvironmentHexEncoded:4e45454453454e43323d66722a6f62", - "QEnvironmentHexEncoded:4e45454453454e433d66726f6224", - "QEnvironmentHexEncoded:455155414c533d666f6f3d626172", - ]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateConnected] + ) + + target.Launch( + lldb.SBListener(), + [], # argv + [ + "PLAIN=foo", + "NEEDSENC=frob$", + "NEEDSENC2=fr*ob", + "NEEDSENC3=fro}b", + "NEEDSENC4=f#rob", + "EQUALS=foo=bar", + ], # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working_directory + 0, # launch_flags + True, # stop_at_entry + lldb.SBError(), + ) # error + + self.assertPacketLogContains( + [ + "QEnvironmentHexEncoded:4e45454453454e43333d66726f7d62", + "QEnvironmentHexEncoded:4e45454453454e43343d6623726f62", + "QEnvironmentHexEncoded:504c41494e3d666f6f", + "QEnvironmentHexEncoded:4e45454453454e43323d66722a6f62", + "QEnvironmentHexEncoded:4e45454453454e433d66726f6224", + "QEnvironmentHexEncoded:455155414c533d666f6f3d626172", + ] + ) def test_detach_no_multiprocess(self): class MyResponder(MockGDBServerResponder): @@ -408,7 +448,7 @@ return "OK" self.server.responder = MyResponder() - target = self.dbg.CreateTarget('') + target = self.dbg.CreateTarget("") process = self.connect(target) process.Detach() self.assertEqual(self.server.responder.detached, "D") @@ -432,7 +472,7 @@ return "OK" self.server.responder = MyResponder(self) - target = self.dbg.CreateTarget('') + target = self.dbg.CreateTarget("") process = self.connect(target) process.Detach() self.assertRegex(self.server.responder.detached, r"D;0*400") @@ -454,10 +494,8 @@ target = self.createTarget("a.yaml") process = self.connect(target) - self.assertEqual(process.threads[0].GetStopReason(), - lldb.eStopReasonSignal) - self.assertEqual(process.threads[0].GetStopDescription(100), - 'signal SIGBUS') + self.assertEqual(process.threads[0].GetStopReason(), lldb.eStopReasonSignal) + self.assertEqual(process.threads[0].GetStopDescription(100), "signal SIGBUS") def test_signal_lldb_old(self): class MyResponder(MockGDBServerResponder): @@ -482,10 +520,8 @@ target = self.createTarget("a.yaml") process = self.connect(target) - self.assertEqual(process.threads[0].GetStopReason(), - lldb.eStopReasonSignal) - self.assertEqual(process.threads[0].GetStopDescription(100), - 'signal SIGUSR1') + self.assertEqual(process.threads[0].GetStopReason(), lldb.eStopReasonSignal) + self.assertEqual(process.threads[0].GetStopDescription(100), "signal SIGUSR1") def test_signal_lldb(self): class MyResponder(MockGDBServerResponder): @@ -507,10 +543,8 @@ target = self.createTarget("a.yaml") process = self.connect(target) - self.assertEqual(process.threads[0].GetStopReason(), - lldb.eStopReasonSignal) - self.assertEqual(process.threads[0].GetStopDescription(100), - 'signal SIGUSR1') + self.assertEqual(process.threads[0].GetStopReason(), lldb.eStopReasonSignal) + self.assertEqual(process.threads[0].GetStopDescription(100), "signal SIGUSR1") def do_siginfo_test(self, platform, target_yaml, raw_data, expected): class MyResponder(MockGDBServerResponder): @@ -539,19 +573,20 @@ self.assertSuccess(siginfo.GetError()) for key, value in expected.items(): - self.assertEqual(siginfo.GetValueForExpressionPath("." + key) - .GetValueAsUnsigned(), - value) - + self.assertEqual( + siginfo.GetValueForExpressionPath("." + key).GetValueAsUnsigned(), value + ) def test_siginfo_linux_amd64(self): data = ( - # si_signo si_errno si_code + # si_signo si_errno si_code "\x11\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00" - # __pad0 si_pid si_uid + # __pad0 si_pid si_uid "\x00\x00\x00\x00\xbf\xf7\x0b\x00\xe8\x03\x00\x00" - # si_status - "\x0c\x00\x00\x00" + "\x00" * 100) + # si_status + "\x0c\x00\x00\x00" + + "\x00" * 100 + ) expected = { "si_signo": 17, # SIGCHLD "si_errno": 0, @@ -562,16 +597,16 @@ "_sifields._sigchld.si_utime": 0, "_sifields._sigchld.si_stime": 0, } - self.do_siginfo_test("remote-linux", "basic_eh_frame.yaml", - data, expected) + self.do_siginfo_test("remote-linux", "basic_eh_frame.yaml", data, expected) def test_siginfo_linux_i386(self): data = ( - # si_signo si_errno si_code + # si_signo si_errno si_code "\x11\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00" - # si_pid si_uid si_status + # si_pid si_uid si_status "\x49\x43\x07\x00\xe8\x03\x00\x00\x0c\x00\x00\x00" - + "\x00" * 104) + + "\x00" * 104 + ) expected = { "si_signo": 17, # SIGCHLD "si_errno": 0, @@ -582,27 +617,26 @@ "_sifields._sigchld.si_utime": 0, "_sifields._sigchld.si_stime": 0, } - self.do_siginfo_test("remote-linux", "basic_eh_frame-i386.yaml", - data, expected) + self.do_siginfo_test("remote-linux", "basic_eh_frame-i386.yaml", data, expected) def test_siginfo_freebsd_amd64(self): data = ( - # si_signo si_errno si_code + # si_signo si_errno si_code "\x0b\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00" - # si_pid si_uid si_status + # si_pid si_uid si_status "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - # si_addr + # si_addr "\x76\x98\xba\xdc\xfe\x00\x00\x00" - # si_status si_trapno + # si_status si_trapno "\x00\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00" - + "\x00" * 36) + + "\x00" * 36 + ) expected = { "si_signo": 11, # SIGSEGV "si_errno": 0, "si_code": 1, # SEGV_MAPERR - "si_addr": 0xfedcba9876, + "si_addr": 0xFEDCBA9876, "_reason._fault._trapno": 12, } - self.do_siginfo_test("remote-freebsd", "basic_eh_frame.yaml", - data, expected) + self.do_siginfo_test("remote-freebsd", "basic_eh_frame.yaml", data, expected) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemoteDiskFileCompletion.py b/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemoteDiskFileCompletion.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemoteDiskFileCompletion.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemoteDiskFileCompletion.py @@ -1,22 +1,19 @@ from lldbsuite.test.gdbclientutils import * from lldbsuite.test.lldbgdbclient import GDBPlatformClientTestBase -class TestGDBRemoteDiskFileCompletion(GDBPlatformClientTestBase): +class TestGDBRemoteDiskFileCompletion(GDBPlatformClientTestBase): def test_autocomplete_request(self): """Test remote disk completion on remote-gdb-server plugin""" class Responder(MockGDBServerResponder): def qPathComplete(self): - return "M{},{}".format( - "test".encode().hex(), - "123".encode().hex() - ) + return "M{},{}".format("test".encode().hex(), "123".encode().hex()) self.server.responder = Responder() - self.complete_from_to('platform get-size ', ['test', '123']) - self.complete_from_to('platform get-file ', ['test', '123']) - self.complete_from_to('platform put-file foo ', ['test', '123']) - self.complete_from_to('platform file open ', ['test', '123']) - self.complete_from_to('platform settings -w ', ['test', '123']) + self.complete_from_to("platform get-size ", ["test", "123"]) + self.complete_from_to("platform get-file ", ["test", "123"]) + self.complete_from_to("platform put-file foo ", ["test", "123"]) + self.complete_from_to("platform file open ", ["test", "123"]) + self.complete_from_to("platform settings -w ", ["test", "123"]) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemoteLoad.py b/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemoteLoad.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemoteLoad.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemoteLoad.py @@ -6,9 +6,9 @@ class TestGDBRemoteLoad(GDBRemoteTestBase): - - @expectedFailureAll(archs=["aarch64"], oslist=["freebsd"], - bugnumber="llvm.org/pr49414") + @expectedFailureAll( + archs=["aarch64"], oslist=["freebsd"], bugnumber="llvm.org/pr49414" + ) def test_module_load_address(self): """Test that setting the load address of a module uses virtual addresses""" target = self.createTarget("a.yaml") @@ -20,21 +20,20 @@ self.assertTrue(address.IsValid()) self.assertEqual(".data", address.GetSection().GetName()) - @expectedFailureAll(archs=["aarch64"], oslist=["freebsd"], - bugnumber="llvm.org/pr49414") + @expectedFailureAll( + archs=["aarch64"], oslist=["freebsd"], bugnumber="llvm.org/pr49414" + ) def test_ram_load(self): """Test loading an object file to a target's ram""" target = self.createTarget("a.yaml") process = self.connect(target) self.dbg.HandleCommand("target modules load -l -s0") - self.assertPacketLogContains([ - "M1000,4:c3c3c3c3", - "M1004,2:3232" - ]) + self.assertPacketLogContains(["M1000,4:c3c3c3c3", "M1004,2:3232"]) @skipIfXmlSupportMissing - @expectedFailureAll(archs=["aarch64"], oslist=["freebsd"], - bugnumber="llvm.org/pr49414") + @expectedFailureAll( + archs=["aarch64"], oslist=["freebsd"], bugnumber="llvm.org/pr49414" + ) def test_flash_load(self): """Test loading an object file to a target's flash memory""" @@ -44,8 +43,10 @@ def qXferRead(self, obj, annex, offset, length): if obj == "memory-map": - return (self.MEMORY_MAP[offset:offset + length], - offset + length < len(self.MEMORY_MAP)) + return ( + self.MEMORY_MAP[offset : offset + length], + offset + length < len(self.MEMORY_MAP), + ) return None, False def other(self, packet): @@ -71,9 +72,11 @@ target = self.createTarget("a.yaml") process = self.connect(target) self.dbg.HandleCommand("target modules load -l -s0") - self.assertPacketLogContains([ + self.assertPacketLogContains( + [ "vFlashErase:1000,100", "vFlashWrite:1000:\xc3\xc3\xc3\xc3", "vFlashWrite:1004:\x32\x32", - "vFlashDone" - ]) + "vFlashDone", + ] + ) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemotePlatformFile.py b/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemotePlatformFile.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemotePlatformFile.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestGDBRemotePlatformFile.py @@ -2,8 +2,8 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbgdbclient import GDBPlatformClientTestBase -class TestGDBRemotePlatformFile(GDBPlatformClientTestBase): +class TestGDBRemotePlatformFile(GDBPlatformClientTestBase): def test_file(self): """Test mock operations on a remote file""" @@ -21,20 +21,23 @@ self.server.responder = Responder() - self.match("platform file open /some/file.txt -v 0755", - [r"File Descriptor = 16"]) - self.match("platform file read 16 -o 11 -c 13", - [r"Return = 11\nData = \"frobnicator\""]) - self.match("platform file write 16 -o 11 -d teststring", - [r"Return = 10"]) - self.match("platform file close 16", - [r"file 16 closed."]) - self.assertPacketLogContains([ - "vFile:open:2f736f6d652f66696c652e747874,00000202,000001ed", - "vFile:pread:10,d,b", - "vFile:pwrite:10,b,teststring", - "vFile:close:10", - ]) + self.match( + "platform file open /some/file.txt -v 0755", [r"File Descriptor = 16"] + ) + self.match( + "platform file read 16 -o 11 -c 13", + [r"Return = 11\nData = \"frobnicator\""], + ) + self.match("platform file write 16 -o 11 -d teststring", [r"Return = 10"]) + self.match("platform file close 16", [r"file 16 closed."]) + self.assertPacketLogContains( + [ + "vFile:open:2f736f6d652f66696c652e747874,00000202,000001ed", + "vFile:pread:10,d,b", + "vFile:pwrite:10,b,teststring", + "vFile:close:10", + ] + ) def test_file_fail(self): """Test mocked failures of remote operations""" @@ -47,24 +50,32 @@ self.server.responder = Responder() - self.match("platform file open /some/file.txt -v 0755", - [r"error: Function not implemented"], - error=True) - self.match("platform file read 16 -o 11 -c 13", - [r"error: Function not implemented"], - error=True) - self.match("platform file write 16 -o 11 -d teststring", - [r"error: Function not implemented"], - error=True) - self.match("platform file close 16", - [r"error: Function not implemented"], - error=True) - self.assertPacketLogContains([ - "vFile:open:2f736f6d652f66696c652e747874,00000202,000001ed", - "vFile:pread:10,d,b", - "vFile:pwrite:10,b,teststring", - "vFile:close:10", - ]) + self.match( + "platform file open /some/file.txt -v 0755", + [r"error: Function not implemented"], + error=True, + ) + self.match( + "platform file read 16 -o 11 -c 13", + [r"error: Function not implemented"], + error=True, + ) + self.match( + "platform file write 16 -o 11 -d teststring", + [r"error: Function not implemented"], + error=True, + ) + self.match( + "platform file close 16", [r"error: Function not implemented"], error=True + ) + self.assertPacketLogContains( + [ + "vFile:open:2f736f6d652f66696c652e747874,00000202,000001ed", + "vFile:pread:10,d,b", + "vFile:pwrite:10,b,teststring", + "vFile:close:10", + ] + ) def test_file_size(self): """Test 'platform get-size'""" @@ -75,11 +86,15 @@ self.server.responder = Responder() - self.match("platform get-size /some/file.txt", - [r"File size of /some/file\.txt \(remote\): 4096"]) - self.assertPacketLogContains([ - "vFile:size:2f736f6d652f66696c652e747874", - ]) + self.match( + "platform get-size /some/file.txt", + [r"File size of /some/file\.txt \(remote\): 4096"], + ) + self.assertPacketLogContains( + [ + "vFile:size:2f736f6d652f66696c652e747874", + ] + ) def test_file_size_fallback(self): """Test 'platform get-size fallback to vFile:fstat'""" @@ -96,14 +111,18 @@ self.server.responder = Responder() - self.match("platform get-size /some/file.txt", - [r"File size of /some/file\.txt \(remote\): 66051"]) - self.assertPacketLogContains([ - "vFile:size:2f736f6d652f66696c652e747874", - "vFile:open:2f736f6d652f66696c652e747874,00000000,00000000", - "vFile:fstat:5", - "vFile:close:5", - ]) + self.match( + "platform get-size /some/file.txt", + [r"File size of /some/file\.txt \(remote\): 66051"], + ) + self.assertPacketLogContains( + [ + "vFile:size:2f736f6d652f66696c652e747874", + "vFile:open:2f736f6d652f66696c652e747874,00000000,00000000", + "vFile:fstat:5", + "vFile:close:5", + ] + ) self.runCmd("platform disconnect") @@ -111,18 +130,22 @@ server2 = MockGDBServer(self.server_socket_class()) server2.responder = Responder() server2.start() - self.addTearDownHook(lambda:server2.stop()) + self.addTearDownHook(lambda: server2.stop()) self.runCmd("platform connect " + server2.get_connect_url()) - self.match("platform get-size /other/file.txt", - [r"File size of /other/file\.txt \(remote\): 66051"]) - - self.assertPacketLogContains([ - "vFile:size:2f6f746865722f66696c652e747874", - "vFile:open:2f6f746865722f66696c652e747874,00000000,00000000", - "vFile:fstat:5", - "vFile:close:5", + self.match( + "platform get-size /other/file.txt", + [r"File size of /other/file\.txt \(remote\): 66051"], + ) + + self.assertPacketLogContains( + [ + "vFile:size:2f6f746865722f66696c652e747874", + "vFile:open:2f6f746865722f66696c652e747874,00000000,00000000", + "vFile:fstat:5", + "vFile:close:5", ], - log=server2.responder.packetLog) + log=server2.responder.packetLog, + ) @skipIfWindows def test_file_permissions(self): @@ -134,11 +157,15 @@ self.server.responder = Responder() - self.match("platform get-permissions /some/file.txt", - [r"File permissions of /some/file\.txt \(remote\): 0o0644"]) - self.assertPacketLogContains([ - "vFile:mode:2f736f6d652f66696c652e747874", - ]) + self.match( + "platform get-permissions /some/file.txt", + [r"File permissions of /some/file\.txt \(remote\): 0o0644"], + ) + self.assertPacketLogContains( + [ + "vFile:mode:2f736f6d652f66696c652e747874", + ] + ) @skipIfWindows def test_file_permissions_fallback(self): @@ -157,14 +184,18 @@ self.server.responder = Responder() try: - self.match("platform get-permissions /some/file.txt", - [r"File permissions of /some/file\.txt \(remote\): 0o0644"]) - self.assertPacketLogContains([ - "vFile:mode:2f736f6d652f66696c652e747874", - "vFile:open:2f736f6d652f66696c652e747874,00000000,00000000", - "vFile:fstat:5", - "vFile:close:5", - ]) + self.match( + "platform get-permissions /some/file.txt", + [r"File permissions of /some/file\.txt \(remote\): 0o0644"], + ) + self.assertPacketLogContains( + [ + "vFile:mode:2f736f6d652f66696c652e747874", + "vFile:open:2f736f6d652f66696c652e747874,00000000,00000000", + "vFile:fstat:5", + "vFile:close:5", + ] + ) finally: self.dbg.GetSelectedPlatform().DisconnectRemote() @@ -177,11 +208,15 @@ self.server.responder = Responder() - self.match("platform file-exists /some/file.txt", - [r"File /some/file\.txt \(remote\) exists"]) - self.assertPacketLogContains([ - "vFile:exists:2f736f6d652f66696c652e747874", - ]) + self.match( + "platform file-exists /some/file.txt", + [r"File /some/file\.txt \(remote\) exists"], + ) + self.assertPacketLogContains( + [ + "vFile:exists:2f736f6d652f66696c652e747874", + ] + ) def test_file_exists_not(self): """Test 'platform file-exists' with non-existing file""" @@ -192,11 +227,15 @@ self.server.responder = Responder() - self.match("platform file-exists /some/file.txt", - [r"File /some/file\.txt \(remote\) does not exist"]) - self.assertPacketLogContains([ - "vFile:exists:2f736f6d652f66696c652e747874", - ]) + self.match( + "platform file-exists /some/file.txt", + [r"File /some/file\.txt \(remote\) does not exist"], + ) + self.assertPacketLogContains( + [ + "vFile:exists:2f736f6d652f66696c652e747874", + ] + ) def test_file_exists_fallback(self): """Test 'platform file-exists' fallback to open""" @@ -211,13 +250,17 @@ self.server.responder = Responder() - self.match("platform file-exists /some/file.txt", - [r"File /some/file\.txt \(remote\) exists"]) - self.assertPacketLogContains([ - "vFile:exists:2f736f6d652f66696c652e747874", - "vFile:open:2f736f6d652f66696c652e747874,00000000,00000000", - "vFile:close:5", - ]) + self.match( + "platform file-exists /some/file.txt", + [r"File /some/file\.txt \(remote\) exists"], + ) + self.assertPacketLogContains( + [ + "vFile:exists:2f736f6d652f66696c652e747874", + "vFile:open:2f736f6d652f66696c652e747874,00000000,00000000", + "vFile:close:5", + ] + ) def test_file_exists_not_fallback(self): """Test 'platform file-exists' fallback to open with non-existing file""" @@ -230,9 +273,13 @@ self.server.responder = Responder() - self.match("platform file-exists /some/file.txt", - [r"File /some/file\.txt \(remote\) does not exist"]) - self.assertPacketLogContains([ - "vFile:exists:2f736f6d652f66696c652e747874", - "vFile:open:2f736f6d652f66696c652e747874,00000000,00000000", - ]) + self.match( + "platform file-exists /some/file.txt", + [r"File /some/file\.txt \(remote\) does not exist"], + ) + self.assertPacketLogContains( + [ + "vFile:exists:2f736f6d652f66696c652e747874", + "vFile:open:2f736f6d652f66696c652e747874,00000000,00000000", + ] + ) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestGDBServerNoTargetXML.py b/lldb/test/API/functionalities/gdb_remote_client/TestGDBServerNoTargetXML.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestGDBServerNoTargetXML.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestGDBServerNoTargetXML.py @@ -8,11 +8,10 @@ class TestGDBServerTargetXML(GDBRemoteTestBase): - @staticmethod def filecheck_to_blob(fc): for l in fc.strip().splitlines(): - val = l.split('0x')[1] + val = l.split("0x")[1] yield binascii.b2a_hex(bytes(reversed(binascii.a2b_hex(val)))).decode() @skipIfRemote @@ -20,7 +19,7 @@ def test_x86_64_regs(self): """Test grabbing various x86_64 registers from gdbserver.""" - GPRS = ''' + GPRS = """ CHECK-AMD64-DAG: rax = 0x0807060504030201 CHECK-AMD64-DAG: rbx = 0x1817161514131211 CHECK-AMD64-DAG: rcx = 0x2827262524232221 @@ -41,9 +40,9 @@ CHECK-AMD64-DAG: eflags = 0x1c1b1a19 CHECK-AMD64-DAG: cs = 0x2c2b2a29 CHECK-AMD64-DAG: ss = 0x3c3b3a39 -''' +""" - SUPPL = ''' + SUPPL = """ CHECK-AMD64-DAG: eax = 0x04030201 CHECK-AMD64-DAG: ebx = 0x14131211 CHECK-AMD64-DAG: ecx = 0x24232221 @@ -99,10 +98,10 @@ CHECK-AMD64-DAG: r13l = 0xd1 CHECK-AMD64-DAG: r14l = 0xe1 CHECK-AMD64-DAG: r15l = 0xf1 -''' +""" class MyResponder(MockGDBServerResponder): - reg_data = ''.join(self.filecheck_to_blob(GPRS)) + reg_data = "".join(self.filecheck_to_blob(GPRS)) def readRegister(self, regnum): return "" @@ -117,41 +116,35 @@ target = self.createTarget("basic_eh_frame.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) # test all registers - self.filecheck("register read --all", __file__, - filecheck_options='--check-prefix=CHECK-AMD64') + self.filecheck( + "register read --all", + __file__, + filecheck_options="--check-prefix=CHECK-AMD64", + ) # test generic aliases - self.match("register read arg4", - ["rcx = 0x2827262524232221"]) - self.match("register read arg3", - ["rdx = 0x3837363534333231"]) - self.match("register read arg2", - ["rsi = 0x4847464544434241"]) - self.match("register read arg1", - ["rdi = 0x5857565554535251"]) - self.match("register read fp", - ["rbp = 0x6867666564636261"]) - self.match("register read sp", - ["rsp = 0x7877767574737271"]) - self.match("register read arg5", - ["r8 = 0x8887868584838281"]) - self.match("register read arg6", - ["r9 = 0x9897969594939291"]) - self.match("register read pc", - ["rip = 0x100f0e0d0c0b0a09"]) - self.match("register read flags", - ["eflags = 0x1c1b1a19"]) + self.match("register read arg4", ["rcx = 0x2827262524232221"]) + self.match("register read arg3", ["rdx = 0x3837363534333231"]) + self.match("register read arg2", ["rsi = 0x4847464544434241"]) + self.match("register read arg1", ["rdi = 0x5857565554535251"]) + self.match("register read fp", ["rbp = 0x6867666564636261"]) + self.match("register read sp", ["rsp = 0x7877767574737271"]) + self.match("register read arg5", ["r8 = 0x8887868584838281"]) + self.match("register read arg6", ["r9 = 0x9897969594939291"]) + self.match("register read pc", ["rip = 0x100f0e0d0c0b0a09"]) + self.match("register read flags", ["eflags = 0x1c1b1a19"]) @skipIfRemote @skipIfLLVMTargetMissing("AArch64") def test_aarch64_regs(self): """Test grabbing various aarch64 registers from gdbserver.""" - GPRS = ''' + GPRS = """ CHECK-AARCH64-DAG: x0 = 0x0001020304050607 CHECK-AARCH64-DAG: x1 = 0x0102030405060708 CHECK-AARCH64-DAG: x2 = 0x0203040506070809 @@ -186,9 +179,9 @@ CHECK-AARCH64-DAG: sp = 0x1f20212223242526 CHECK-AARCH64-DAG: pc = 0x2021222324252627 CHECK-AARCH64-DAG: cpsr = 0x21222324 -''' +""" - SUPPL = ''' + SUPPL = """ CHECK-AARCH64-DAG: w0 = 0x04050607 CHECK-AARCH64-DAG: w1 = 0x05060708 CHECK-AARCH64-DAG: w2 = 0x06070809 @@ -221,10 +214,10 @@ CHECK-AARCH64-DAG: w29 = 0x21222324 CHECK-AARCH64-DAG: w30 = 0x22232425 CHECK-AARCH64-DAG: w31 = 0x23242526 -''' +""" class MyResponder(MockGDBServerResponder): - reg_data = ''.join(self.filecheck_to_blob(GPRS)) + reg_data = "".join(self.filecheck_to_blob(GPRS)) def readRegister(self, regnum): return "" @@ -239,33 +232,31 @@ target = self.createTarget("basic_eh_frame-aarch64.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) # test all registers - self.filecheck("register read --all", __file__, - filecheck_options='--check-prefix=CHECK-AARCH64') + self.filecheck( + "register read --all", + __file__, + filecheck_options="--check-prefix=CHECK-AARCH64", + ) # test generic aliases - self.match("register read arg1", - ["x0 = 0x0001020304050607"]) - self.match("register read arg2", - ["x1 = 0x0102030405060708"]) - self.match("register read fp", - ["x29 = 0x1d1e1f2021222324"]) - self.match("register read lr", - ["x30 = 0x1e1f202122232425"]) - self.match("register read ra", - ["x30 = 0x1e1f202122232425"]) - self.match("register read flags", - ["cpsr = 0x21222324"]) + self.match("register read arg1", ["x0 = 0x0001020304050607"]) + self.match("register read arg2", ["x1 = 0x0102030405060708"]) + self.match("register read fp", ["x29 = 0x1d1e1f2021222324"]) + self.match("register read lr", ["x30 = 0x1e1f202122232425"]) + self.match("register read ra", ["x30 = 0x1e1f202122232425"]) + self.match("register read flags", ["cpsr = 0x21222324"]) @skipIfRemote @skipIfLLVMTargetMissing("X86") def test_i386_regs(self): """Test grabbing various i386 registers from gdbserver.""" - GPRS = ''' + GPRS = """ CHECK-I386-DAG: eax = 0x04030201 CHECK-I386-DAG: ecx = 0x14131211 CHECK-I386-DAG: edx = 0x24232221 @@ -282,9 +273,9 @@ CHECK-I386-DAG: es = 0xd4d3d2d1 CHECK-I386-DAG: fs = 0xe4e3e2e1 CHECK-I386-DAG: gs = 0xf4f3f2f1 -''' +""" - SUPPL = ''' + SUPPL = """ CHECK-I386-DAG: ax = 0x0201 CHECK-I386-DAG: cx = 0x1211 CHECK-I386-DAG: dx = 0x2221 @@ -307,10 +298,10 @@ CHECK-I386-DAG: bpl = 0x51 CHECK-I386-DAG: sil = 0x61 CHECK-I386-DAG: dil = 0x71 -''' +""" class MyResponder(MockGDBServerResponder): - reg_data = ''.join(self.filecheck_to_blob(GPRS)) + reg_data = "".join(self.filecheck_to_blob(GPRS)) def readRegister(self, regnum): return "" @@ -325,19 +316,19 @@ target = self.createTarget("basic_eh_frame-i386.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) # test all registers - self.filecheck("register read --all", __file__, - filecheck_options='--check-prefix=CHECK-I386') + self.filecheck( + "register read --all", + __file__, + filecheck_options="--check-prefix=CHECK-I386", + ) # test generic aliases - self.match("register read fp", - ["ebp = 0x54535251"]) - self.match("register read sp", - ["esp = 0x44434241"]) - self.match("register read pc", - ["eip = 0x84838281"]) - self.match("register read flags", - ["eflags = 0x94939291"]) + self.match("register read fp", ["ebp = 0x54535251"]) + self.match("register read sp", ["esp = 0x44434241"]) + self.match("register read pc", ["eip = 0x84838281"]) + self.match("register read flags", ["eflags = 0x94939291"]) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestGDBServerTargetXML.py b/lldb/test/API/functionalities/gdb_remote_client/TestGDBServerTargetXML.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestGDBServerTargetXML.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestGDBServerTargetXML.py @@ -6,45 +6,46 @@ class TestGDBServerTargetXML(GDBRemoteTestBase): - @skipIfXmlSupportMissing @skipIfRemote @skipIfLLVMTargetMissing("X86") def test_x86_64_regs(self): """Test grabbing various x86_64 registers from gdbserver.""" + class MyResponder(MockGDBServerResponder): reg_data = ( - "0102030405060708" # rcx - "1112131415161718" # rdx - "2122232425262728" # rsi - "3132333435363738" # rdi - "4142434445464748" # rbp - "5152535455565758" # rsp - "6162636465666768" # r8 - "7172737475767778" # r9 - "8182838485868788" # rip - "91929394" # eflags - "0102030405060708090a" # st0 - "1112131415161718191a" # st1 - ) + 6 * ( - "2122232425262728292a" # st2..st7 - ) + ( - "8182838485868788898a8b8c8d8e8f90" # xmm0 - "9192939495969798999a9b9c9d9e9fa0" # xmm1 - ) + 14 * ( - "a1a2a3a4a5a6a7a8a9aaabacadaeafb0" # xmm2..xmm15 - ) + ( - "00000000" # mxcsr - ) + ( - "b1b2b3b4b5b6b7b8b9babbbcbdbebfc0" # ymm0h - "c1c2c3c4c5c6c7c8c9cacbcccdcecfd0" # ymm1h - ) + 14 * ( - "d1d2d3d4d5d6d7d8d9dadbdcdddedfe0" # ymm2h..ymm15h + ( + "0102030405060708" # rcx + "1112131415161718" # rdx + "2122232425262728" # rsi + "3132333435363738" # rdi + "4142434445464748" # rbp + "5152535455565758" # rsp + "6162636465666768" # r8 + "7172737475767778" # r9 + "8182838485868788" # rip + "91929394" # eflags + "0102030405060708090a" # st0 + "1112131415161718191a" # st1 + ) + + 6 * ("2122232425262728292a") # st2..st7 + + ( + "8182838485868788898a8b8c8d8e8f90" # xmm0 + "9192939495969798999a9b9c9d9e9fa0" # xmm1 + ) + + 14 * ("a1a2a3a4a5a6a7a8a9aaabacadaeafb0") # xmm2..xmm15 + + ("00000000") # mxcsr + + ( + "b1b2b3b4b5b6b7b8b9babbbcbdbebfc0" # ymm0h + "c1c2c3c4c5c6c7c8c9cacbcccdcecfd0" # ymm1h + ) + + 14 * ("d1d2d3d4d5d6d7d8d9dadbdcdddedfe0") # ymm2h..ymm15h ) def qXferRead(self, obj, annex, offset, length): if annex == "target.xml": - return """ + return ( + """ i386:x86-64 @@ -106,7 +107,9 @@ - """, False + """, + False, + ) else: return None, False @@ -127,140 +130,157 @@ target = self.createTarget("basic_eh_frame.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) # test generic aliases - self.match("register read arg4", - ["rcx = 0x0807060504030201"]) - self.match("register read arg3", - ["rdx = 0x1817161514131211"]) - self.match("register read arg2", - ["rsi = 0x2827262524232221"]) - self.match("register read arg1", - ["rdi = 0x3837363534333231"]) - self.match("register read fp", - ["rbp = 0x4847464544434241"]) - self.match("register read sp", - ["rsp = 0x5857565554535251"]) - self.match("register read arg5", - ["r8 = 0x6867666564636261"]) - self.match("register read arg6", - ["r9 = 0x7877767574737271"]) - self.match("register read pc", - ["rip = 0x8887868584838281"]) - self.match("register read flags", - ["eflags = 0x94939291"]) + self.match("register read arg4", ["rcx = 0x0807060504030201"]) + self.match("register read arg3", ["rdx = 0x1817161514131211"]) + self.match("register read arg2", ["rsi = 0x2827262524232221"]) + self.match("register read arg1", ["rdi = 0x3837363534333231"]) + self.match("register read fp", ["rbp = 0x4847464544434241"]) + self.match("register read sp", ["rsp = 0x5857565554535251"]) + self.match("register read arg5", ["r8 = 0x6867666564636261"]) + self.match("register read arg6", ["r9 = 0x7877767574737271"]) + self.match("register read pc", ["rip = 0x8887868584838281"]) + self.match("register read flags", ["eflags = 0x94939291"]) # both stX and xmmX should be displayed as vectors - self.match("register read st0", - ["st0 = {0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a}"]) - self.match("register read st1", - ["st1 = {0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a}"]) - self.match("register read xmm0", - ["xmm0 = {0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 " - "0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f 0x90}"]) - self.match("register read xmm1", - ["xmm1 = {0x91 0x92 0x93 0x94 0x95 0x96 0x97 0x98 " - "0x99 0x9a 0x9b 0x9c 0x9d 0x9e 0x9f 0xa0}"]) + self.match( + "register read st0", + ["st0 = {0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a}"], + ) + self.match( + "register read st1", + ["st1 = {0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a}"], + ) + self.match( + "register read xmm0", + [ + "xmm0 = {0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 " + "0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f 0x90}" + ], + ) + self.match( + "register read xmm1", + [ + "xmm1 = {0x91 0x92 0x93 0x94 0x95 0x96 0x97 0x98 " + "0x99 0x9a 0x9b 0x9c 0x9d 0x9e 0x9f 0xa0}" + ], + ) # test pseudo-registers - self.filecheck("register read --all", - os.path.join(os.path.dirname(__file__), - "amd64-partial-regs.FileCheck")) + self.filecheck( + "register read --all", + os.path.join(os.path.dirname(__file__), "amd64-partial-regs.FileCheck"), + ) # test writing into pseudo-registers self.runCmd("register write ecx 0xfffefdfc") - self.match("register read rcx", - ["rcx = 0x08070605fffefdfc"]) + self.match("register read rcx", ["rcx = 0x08070605fffefdfc"]) self.runCmd("register write cx 0xfbfa") - self.match("register read ecx", - ["ecx = 0xfffefbfa"]) - self.match("register read rcx", - ["rcx = 0x08070605fffefbfa"]) + self.match("register read ecx", ["ecx = 0xfffefbfa"]) + self.match("register read rcx", ["rcx = 0x08070605fffefbfa"]) self.runCmd("register write ch 0xf9") - self.match("register read cx", - ["cx = 0xf9fa"]) - self.match("register read ecx", - ["ecx = 0xfffef9fa"]) - self.match("register read rcx", - ["rcx = 0x08070605fffef9fa"]) + self.match("register read cx", ["cx = 0xf9fa"]) + self.match("register read ecx", ["ecx = 0xfffef9fa"]) + self.match("register read rcx", ["rcx = 0x08070605fffef9fa"]) self.runCmd("register write cl 0xf8") - self.match("register read cx", - ["cx = 0xf9f8"]) - self.match("register read ecx", - ["ecx = 0xfffef9f8"]) - self.match("register read rcx", - ["rcx = 0x08070605fffef9f8"]) + self.match("register read cx", ["cx = 0xf9f8"]) + self.match("register read ecx", ["ecx = 0xfffef9f8"]) + self.match("register read rcx", ["rcx = 0x08070605fffef9f8"]) self.runCmd("register write mm0 0xfffefdfcfbfaf9f8") - self.match("register read st0", - ["st0 = {0xf8 0xf9 0xfa 0xfb 0xfc 0xfd 0xfe 0xff 0x09 0x0a}"]) - - self.runCmd("register write xmm0 \"{0xff 0xfe 0xfd 0xfc 0xfb 0xfa 0xf9 " - "0xf8 0xf7 0xf6 0xf5 0xf4 0xf3 0xf2 0xf1 0xf0}\"") - self.match("register read ymm0", - ["ymm0 = {0xff 0xfe 0xfd 0xfc 0xfb 0xfa 0xf9 0xf8 0xf7 0xf6 " - "0xf5 0xf4 0xf3 0xf2 0xf1 0xf0 0xb1 0xb2 0xb3 0xb4 0xb5 " - "0xb6 0xb7 0xb8 0xb9 0xba 0xbb 0xbc 0xbd 0xbe 0xbf 0xc0}"]) - - self.runCmd("register write ymm0h \"{0xef 0xee 0xed 0xec 0xeb 0xea 0xe9 " - "0xe8 0xe7 0xe6 0xe5 0xe4 0xe3 0xe2 0xe1 0xe0}\"") - self.match("register read ymm0", - ["ymm0 = {0xff 0xfe 0xfd 0xfc 0xfb 0xfa 0xf9 0xf8 0xf7 0xf6 " - "0xf5 0xf4 0xf3 0xf2 0xf1 0xf0 0xef 0xee 0xed 0xec 0xeb " - "0xea 0xe9 0xe8 0xe7 0xe6 0xe5 0xe4 0xe3 0xe2 0xe1 0xe0}"]) - - self.runCmd("register write ymm0 \"{0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 " - "0xd7 0xd8 0xd9 0xda 0xdb 0xdc 0xdd 0xde 0xdf 0xe0 0xe1 " - "0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec " - "0xed 0xee 0xef}\"") - self.match("register read ymm0", - ["ymm0 = {0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 0xd7 0xd8 0xd9 " - "0xda 0xdb 0xdc 0xdd 0xde 0xdf 0xe0 0xe1 0xe2 0xe3 0xe4 " - "0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec 0xed 0xee 0xef}"]) + self.match( + "register read st0", + ["st0 = {0xf8 0xf9 0xfa 0xfb 0xfc 0xfd 0xfe 0xff 0x09 0x0a}"], + ) + + self.runCmd( + 'register write xmm0 "{0xff 0xfe 0xfd 0xfc 0xfb 0xfa 0xf9 ' + '0xf8 0xf7 0xf6 0xf5 0xf4 0xf3 0xf2 0xf1 0xf0}"' + ) + self.match( + "register read ymm0", + [ + "ymm0 = {0xff 0xfe 0xfd 0xfc 0xfb 0xfa 0xf9 0xf8 0xf7 0xf6 " + "0xf5 0xf4 0xf3 0xf2 0xf1 0xf0 0xb1 0xb2 0xb3 0xb4 0xb5 " + "0xb6 0xb7 0xb8 0xb9 0xba 0xbb 0xbc 0xbd 0xbe 0xbf 0xc0}" + ], + ) + + self.runCmd( + 'register write ymm0h "{0xef 0xee 0xed 0xec 0xeb 0xea 0xe9 ' + '0xe8 0xe7 0xe6 0xe5 0xe4 0xe3 0xe2 0xe1 0xe0}"' + ) + self.match( + "register read ymm0", + [ + "ymm0 = {0xff 0xfe 0xfd 0xfc 0xfb 0xfa 0xf9 0xf8 0xf7 0xf6 " + "0xf5 0xf4 0xf3 0xf2 0xf1 0xf0 0xef 0xee 0xed 0xec 0xeb " + "0xea 0xe9 0xe8 0xe7 0xe6 0xe5 0xe4 0xe3 0xe2 0xe1 0xe0}" + ], + ) + + self.runCmd( + 'register write ymm0 "{0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 ' + "0xd7 0xd8 0xd9 0xda 0xdb 0xdc 0xdd 0xde 0xdf 0xe0 0xe1 " + "0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec " + '0xed 0xee 0xef}"' + ) + self.match( + "register read ymm0", + [ + "ymm0 = {0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 0xd7 0xd8 0xd9 " + "0xda 0xdb 0xdc 0xdd 0xde 0xdf 0xe0 0xe1 0xe2 0xe3 0xe4 " + "0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec 0xed 0xee 0xef}" + ], + ) @skipIfXmlSupportMissing @skipIfRemote @skipIfLLVMTargetMissing("X86") def test_i386_regs(self): """Test grabbing various i386 registers from gdbserver.""" + class MyResponder(MockGDBServerResponder): reg_data = ( - "01020304" # eax - "11121314" # ecx - "21222324" # edx - "31323334" # ebx - "41424344" # esp - "51525354" # ebp - "61626364" # esi - "71727374" # edi - "81828384" # eip - "91929394" # eflags - "0102030405060708090a" # st0 - "1112131415161718191a" # st1 - ) + 6 * ( - "2122232425262728292a" # st2..st7 - ) + ( - "8182838485868788898a8b8c8d8e8f90" # xmm0 - "9192939495969798999a9b9c9d9e9fa0" # xmm1 - ) + 6 * ( - "a1a2a3a4a5a6a7a8a9aaabacadaeafb0" # xmm2..xmm7 - ) + ( - "00000000" # mxcsr - ) + ( - "b1b2b3b4b5b6b7b8b9babbbcbdbebfc0" # ymm0h - "c1c2c3c4c5c6c7c8c9cacbcccdcecfd0" # ymm1h - ) + 6 * ( - "d1d2d3d4d5d6d7d8d9dadbdcdddedfe0" # ymm2h..ymm7h + ( + "01020304" # eax + "11121314" # ecx + "21222324" # edx + "31323334" # ebx + "41424344" # esp + "51525354" # ebp + "61626364" # esi + "71727374" # edi + "81828384" # eip + "91929394" # eflags + "0102030405060708090a" # st0 + "1112131415161718191a" # st1 + ) + + 6 * ("2122232425262728292a") # st2..st7 + + ( + "8182838485868788898a8b8c8d8e8f90" # xmm0 + "9192939495969798999a9b9c9d9e9fa0" # xmm1 + ) + + 6 * ("a1a2a3a4a5a6a7a8a9aaabacadaeafb0") # xmm2..xmm7 + + ("00000000") # mxcsr + + ( + "b1b2b3b4b5b6b7b8b9babbbcbdbebfc0" # ymm0h + "c1c2c3c4c5c6c7c8c9cacbcccdcecfd0" # ymm1h + ) + + 6 * ("d1d2d3d4d5d6d7d8d9dadbdcdddedfe0") # ymm2h..ymm7h ) def qXferRead(self, obj, annex, offset, length): if annex == "target.xml": - return """ + return ( + """ i386 @@ -306,7 +326,9 @@ - """, False + """, + False, + ) else: return None, False @@ -327,116 +349,133 @@ target = self.createTarget("basic_eh_frame-i386.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) # test generic aliases - self.match("register read fp", - ["ebp = 0x54535251"]) - self.match("register read sp", - ["esp = 0x44434241"]) - self.match("register read pc", - ["eip = 0x84838281"]) - self.match("register read flags", - ["eflags = 0x94939291"]) + self.match("register read fp", ["ebp = 0x54535251"]) + self.match("register read sp", ["esp = 0x44434241"]) + self.match("register read pc", ["eip = 0x84838281"]) + self.match("register read flags", ["eflags = 0x94939291"]) # test pseudo-registers - self.match("register read cx", - ["cx = 0x1211"]) - self.match("register read ch", - ["ch = 0x12"]) - self.match("register read cl", - ["cl = 0x11"]) - self.match("register read mm0", - ["mm0 = 0x0807060504030201"]) - self.match("register read mm1", - ["mm1 = 0x1817161514131211"]) + self.match("register read cx", ["cx = 0x1211"]) + self.match("register read ch", ["ch = 0x12"]) + self.match("register read cl", ["cl = 0x11"]) + self.match("register read mm0", ["mm0 = 0x0807060504030201"]) + self.match("register read mm1", ["mm1 = 0x1817161514131211"]) # both stX and xmmX should be displayed as vectors - self.match("register read st0", - ["st0 = {0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a}"]) - self.match("register read st1", - ["st1 = {0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a}"]) - self.match("register read xmm0", - ["xmm0 = {0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 " - "0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f 0x90}"]) - self.match("register read xmm1", - ["xmm1 = {0x91 0x92 0x93 0x94 0x95 0x96 0x97 0x98 " - "0x99 0x9a 0x9b 0x9c 0x9d 0x9e 0x9f 0xa0}"]) + self.match( + "register read st0", + ["st0 = {0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a}"], + ) + self.match( + "register read st1", + ["st1 = {0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a}"], + ) + self.match( + "register read xmm0", + [ + "xmm0 = {0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 " + "0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f 0x90}" + ], + ) + self.match( + "register read xmm1", + [ + "xmm1 = {0x91 0x92 0x93 0x94 0x95 0x96 0x97 0x98 " + "0x99 0x9a 0x9b 0x9c 0x9d 0x9e 0x9f 0xa0}" + ], + ) # test writing into pseudo-registers self.runCmd("register write cx 0xfbfa") - self.match("register read ecx", - ["ecx = 0x1413fbfa"]) + self.match("register read ecx", ["ecx = 0x1413fbfa"]) self.runCmd("register write ch 0xf9") - self.match("register read cx", - ["cx = 0xf9fa"]) - self.match("register read ecx", - ["ecx = 0x1413f9fa"]) + self.match("register read cx", ["cx = 0xf9fa"]) + self.match("register read ecx", ["ecx = 0x1413f9fa"]) self.runCmd("register write cl 0xf8") - self.match("register read cx", - ["cx = 0xf9f8"]) - self.match("register read ecx", - ["ecx = 0x1413f9f8"]) + self.match("register read cx", ["cx = 0xf9f8"]) + self.match("register read ecx", ["ecx = 0x1413f9f8"]) self.runCmd("register write mm0 0xfffefdfcfbfaf9f8") - self.match("register read st0", - ["st0 = {0xf8 0xf9 0xfa 0xfb 0xfc 0xfd 0xfe 0xff 0x09 0x0a}"]) - - self.runCmd("register write xmm0 \"{0xff 0xfe 0xfd 0xfc 0xfb 0xfa 0xf9 " - "0xf8 0xf7 0xf6 0xf5 0xf4 0xf3 0xf2 0xf1 0xf0}\"") - self.match("register read ymm0", - ["ymm0 = {0xff 0xfe 0xfd 0xfc 0xfb 0xfa 0xf9 0xf8 0xf7 0xf6 " - "0xf5 0xf4 0xf3 0xf2 0xf1 0xf0 0xb1 0xb2 0xb3 0xb4 0xb5 " - "0xb6 0xb7 0xb8 0xb9 0xba 0xbb 0xbc 0xbd 0xbe 0xbf 0xc0}"]) - - self.runCmd("register write ymm0h \"{0xef 0xee 0xed 0xec 0xeb 0xea 0xe9 " - "0xe8 0xe7 0xe6 0xe5 0xe4 0xe3 0xe2 0xe1 0xe0}\"") - self.match("register read ymm0", - ["ymm0 = {0xff 0xfe 0xfd 0xfc 0xfb 0xfa 0xf9 0xf8 0xf7 0xf6 " - "0xf5 0xf4 0xf3 0xf2 0xf1 0xf0 0xef 0xee 0xed 0xec 0xeb " - "0xea 0xe9 0xe8 0xe7 0xe6 0xe5 0xe4 0xe3 0xe2 0xe1 0xe0}"]) - - self.runCmd("register write ymm0 \"{0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 " - "0xd7 0xd8 0xd9 0xda 0xdb 0xdc 0xdd 0xde 0xdf 0xe0 0xe1 " - "0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec " - "0xed 0xee 0xef}\"") - self.match("register read ymm0", - ["ymm0 = {0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 0xd7 0xd8 0xd9 " - "0xda 0xdb 0xdc 0xdd 0xde 0xdf 0xe0 0xe1 0xe2 0xe3 0xe4 " - "0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec 0xed 0xee 0xef}"]) + self.match( + "register read st0", + ["st0 = {0xf8 0xf9 0xfa 0xfb 0xfc 0xfd 0xfe 0xff 0x09 0x0a}"], + ) + + self.runCmd( + 'register write xmm0 "{0xff 0xfe 0xfd 0xfc 0xfb 0xfa 0xf9 ' + '0xf8 0xf7 0xf6 0xf5 0xf4 0xf3 0xf2 0xf1 0xf0}"' + ) + self.match( + "register read ymm0", + [ + "ymm0 = {0xff 0xfe 0xfd 0xfc 0xfb 0xfa 0xf9 0xf8 0xf7 0xf6 " + "0xf5 0xf4 0xf3 0xf2 0xf1 0xf0 0xb1 0xb2 0xb3 0xb4 0xb5 " + "0xb6 0xb7 0xb8 0xb9 0xba 0xbb 0xbc 0xbd 0xbe 0xbf 0xc0}" + ], + ) + + self.runCmd( + 'register write ymm0h "{0xef 0xee 0xed 0xec 0xeb 0xea 0xe9 ' + '0xe8 0xe7 0xe6 0xe5 0xe4 0xe3 0xe2 0xe1 0xe0}"' + ) + self.match( + "register read ymm0", + [ + "ymm0 = {0xff 0xfe 0xfd 0xfc 0xfb 0xfa 0xf9 0xf8 0xf7 0xf6 " + "0xf5 0xf4 0xf3 0xf2 0xf1 0xf0 0xef 0xee 0xed 0xec 0xeb " + "0xea 0xe9 0xe8 0xe7 0xe6 0xe5 0xe4 0xe3 0xe2 0xe1 0xe0}" + ], + ) + + self.runCmd( + 'register write ymm0 "{0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 ' + "0xd7 0xd8 0xd9 0xda 0xdb 0xdc 0xdd 0xde 0xdf 0xe0 0xe1 " + "0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec " + '0xed 0xee 0xef}"' + ) + self.match( + "register read ymm0", + [ + "ymm0 = {0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 0xd7 0xd8 0xd9 " + "0xda 0xdb 0xdc 0xdd 0xde 0xdf 0xe0 0xe1 0xe2 0xe3 0xe4 " + "0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec 0xed 0xee 0xef}" + ], + ) @skipIfXmlSupportMissing @skipIfRemote @skipIfLLVMTargetMissing("AArch64") def test_aarch64_regs(self): """Test grabbing various aarch64 registers from gdbserver.""" + class MyResponder(MockGDBServerResponder): reg_data = ( - "0102030405060708" # x0 - "1112131415161718" # x1 - ) + 27 * ( - "2122232425262728" # x2..x28 - ) + ( - "3132333435363738" # x29 (fp) - "4142434445464748" # x30 (lr) - "5152535455565758" # x31 (sp) - "6162636465666768" # pc - "71727374" # cpsr - "8182838485868788898a8b8c8d8e8f90" # v0 - "9192939495969798999a9b9c9d9e9fa0" # v1 - ) + 30 * ( - "a1a2a3a4a5a6a7a8a9aaabacadaeafb0" # v2..v31 - ) + ( - "00000000" # fpsr - "00000000" # fpcr + ("0102030405060708" "1112131415161718") # x0 # x1 + + 27 * ("2122232425262728") # x2..x28 + + ( + "3132333435363738" # x29 (fp) + "4142434445464748" # x30 (lr) + "5152535455565758" # x31 (sp) + "6162636465666768" # pc + "71727374" # cpsr + "8182838485868788898a8b8c8d8e8f90" # v0 + "9192939495969798999a9b9c9d9e9fa0" # v1 + ) + + 30 * ("a1a2a3a4a5a6a7a8a9aaabacadaeafb0") # v2..v31 + + ("00000000" "00000000") # fpsr # fpcr ) def qXferRead(self, obj, annex, offset, length): if annex == "target.xml": - return """ + return ( + """ aarch64 @@ -512,7 +551,9 @@ - """, False + """, + False, + ) else: return None, False @@ -533,92 +574,90 @@ target = self.createTarget("basic_eh_frame-aarch64.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) # test GPRs - self.match("register read x0", - ["x0 = 0x0807060504030201"]) - self.match("register read x1", - ["x1 = 0x1817161514131211"]) - self.match("register read x29", - ["x29 = 0x3837363534333231"]) - self.match("register read x30", - ["x30 = 0x4847464544434241"]) - self.match("register read x31", - ["sp = 0x5857565554535251"]) - self.match("register read sp", - ["sp = 0x5857565554535251"]) - self.match("register read pc", - ["pc = 0x6867666564636261"]) - self.match("register read cpsr", - ["cpsr = 0x74737271"]) + self.match("register read x0", ["x0 = 0x0807060504030201"]) + self.match("register read x1", ["x1 = 0x1817161514131211"]) + self.match("register read x29", ["x29 = 0x3837363534333231"]) + self.match("register read x30", ["x30 = 0x4847464544434241"]) + self.match("register read x31", ["sp = 0x5857565554535251"]) + self.match("register read sp", ["sp = 0x5857565554535251"]) + self.match("register read pc", ["pc = 0x6867666564636261"]) + self.match("register read cpsr", ["cpsr = 0x74737271"]) # test generic aliases - self.match("register read arg1", - ["x0 = 0x0807060504030201"]) - self.match("register read arg2", - ["x1 = 0x1817161514131211"]) - self.match("register read fp", - ["x29 = 0x3837363534333231"]) - self.match("register read lr", - ["x30 = 0x4847464544434241"]) - self.match("register read ra", - ["x30 = 0x4847464544434241"]) - self.match("register read flags", - ["cpsr = 0x74737271"]) + self.match("register read arg1", ["x0 = 0x0807060504030201"]) + self.match("register read arg2", ["x1 = 0x1817161514131211"]) + self.match("register read fp", ["x29 = 0x3837363534333231"]) + self.match("register read lr", ["x30 = 0x4847464544434241"]) + self.match("register read ra", ["x30 = 0x4847464544434241"]) + self.match("register read flags", ["cpsr = 0x74737271"]) # test vector registers - self.match("register read v0", - ["v0 = {0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f 0x90}"]) - self.match("register read v31", - ["v31 = {0xa1 0xa2 0xa3 0xa4 0xa5 0xa6 0xa7 0xa8 0xa9 0xaa 0xab 0xac 0xad 0xae 0xaf 0xb0}"]) + self.match( + "register read v0", + [ + "v0 = {0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f 0x90}" + ], + ) + self.match( + "register read v31", + [ + "v31 = {0xa1 0xa2 0xa3 0xa4 0xa5 0xa6 0xa7 0xa8 0xa9 0xaa 0xab 0xac 0xad 0xae 0xaf 0xb0}" + ], + ) # test partial registers - self.match("register read w0", - ["w0 = 0x04030201"]) + self.match("register read w0", ["w0 = 0x04030201"]) self.runCmd("register write w0 0xfffefdfc") - self.match("register read x0", - ["x0 = 0x08070605fffefdfc"]) + self.match("register read x0", ["x0 = 0x08070605fffefdfc"]) - self.match("register read w1", - ["w1 = 0x14131211"]) + self.match("register read w1", ["w1 = 0x14131211"]) self.runCmd("register write w1 0xefeeedec") - self.match("register read x1", - ["x1 = 0x18171615efeeedec"]) + self.match("register read x1", ["x1 = 0x18171615efeeedec"]) - self.match("register read w30", - ["w30 = 0x44434241"]) + self.match("register read w30", ["w30 = 0x44434241"]) self.runCmd("register write w30 0xdfdedddc") - self.match("register read x30", - ["x30 = 0x48474645dfdedddc"]) + self.match("register read x30", ["x30 = 0x48474645dfdedddc"]) - self.match("register read w31", - ["w31 = 0x54535251"]) + self.match("register read w31", ["w31 = 0x54535251"]) self.runCmd("register write w31 0xcfcecdcc") - self.match("register read x31", - ["sp = 0x58575655cfcecdcc"]) + self.match("register read x31", ["sp = 0x58575655cfcecdcc"]) # test FPU registers (overlapping with vector registers) self.runCmd("register write d0 16") - self.match("register read v0", - ["v0 = {0x00 0x00 0x00 0x00 0x00 0x00 0x30 0x40 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f 0x90}"]) - self.runCmd("register write v31 '{0x00 0x00 0x00 0x00 0x00 0x00 0x50 0x40 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff}'") - self.match("register read d31", - ["d31 = 64"]) + self.match( + "register read v0", + [ + "v0 = {0x00 0x00 0x00 0x00 0x00 0x00 0x30 0x40 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f 0x90}" + ], + ) + self.runCmd( + "register write v31 '{0x00 0x00 0x00 0x00 0x00 0x00 0x50 0x40 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff}'" + ) + self.match("register read d31", ["d31 = 64"]) self.runCmd("register write s0 32") - self.match("register read v0", - ["v0 = {0x00 0x00 0x00 0x42 0x00 0x00 0x30 0x40 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f 0x90}"]) - self.runCmd("register write v31 '{0x00 0x00 0x00 0x43 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff}'") - self.match("register read s31", - ["s31 = 128"]) + self.match( + "register read v0", + [ + "v0 = {0x00 0x00 0x00 0x42 0x00 0x00 0x30 0x40 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f 0x90}" + ], + ) + self.runCmd( + "register write v31 '{0x00 0x00 0x00 0x43 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff}'" + ) + self.match("register read s31", ["s31 = 128"]) @skipIfXmlSupportMissing @skipIfRemote @skipIfLLVMTargetMissing("X86") def test_x86_64_no_duplicate_subregs(self): """Test that duplicate subregisters are not added (on x86_64).""" + class MyResponder(MockGDBServerResponder): reg_data = ( "0102030405060708" # rcx @@ -635,7 +674,8 @@ def qXferRead(self, obj, annex, offset, length): if annex == "target.xml": - return """ + return ( + """ i386:x86-64 @@ -653,7 +693,9 @@ - """, False + """, + False, + ) else: return None, False @@ -670,26 +712,25 @@ target = self.createTarget("basic_eh_frame.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) - self.match("register read rcx", - ["rcx = 0x0807060504030201"]) + self.match("register read rcx", ["rcx = 0x0807060504030201"]) # ecx is supplied via target.xml - self.match("register read ecx", - ["ecx = 0x04030201"]) - self.match("register read rdx", - ["rdx = 0x1817161514131211"]) + self.match("register read ecx", ["ecx = 0x04030201"]) + self.match("register read rdx", ["rdx = 0x1817161514131211"]) # edx should not be added - self.match("register read edx", - ["error: Invalid register name 'edx'."], - error=True) + self.match( + "register read edx", ["error: Invalid register name 'edx'."], error=True + ) @skipIfXmlSupportMissing @skipIfRemote @skipIfLLVMTargetMissing("X86") def test_i386_no_duplicate_subregs(self): """Test that duplicate subregisters are not added (on i386).""" + class MyResponder(MockGDBServerResponder): reg_data = ( "01020304" # eax @@ -706,7 +747,8 @@ def qXferRead(self, obj, annex, offset, length): if annex == "target.xml": - return """ + return ( + """ i386 @@ -724,7 +766,9 @@ - """, False + """, + False, + ) else: return None, False @@ -741,43 +785,42 @@ target = self.createTarget("basic_eh_frame-i386.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) - self.match("register read eax", - ["eax = 0x04030201"]) + self.match("register read eax", ["eax = 0x04030201"]) # cx is supplied via target.xml - self.match("register read ax", - ["ax = 0x0201"]) - self.match("register read ecx", - ["ecx = 0x14131211"]) + self.match("register read ax", ["ax = 0x0201"]) + self.match("register read ecx", ["ecx = 0x14131211"]) # dx should not be added - self.match("register read cx", - ["error: Invalid register name 'cx'."], - error=True) + self.match( + "register read cx", ["error: Invalid register name 'cx'."], error=True + ) @skipIfXmlSupportMissing @skipIfRemote @skipIfLLVMTargetMissing("AArch64") def test_aarch64_no_duplicate_subregs(self): """Test that duplicate subregisters are not added.""" + class MyResponder(MockGDBServerResponder): reg_data = ( - "0102030405060708" # x0 - "1112131415161718" # x1 - ) + 27 * ( - "2122232425262728" # x2..x28 - ) + ( - "3132333435363738" # x29 (fp) - "4142434445464748" # x30 (lr) - "5152535455565758" # x31 (sp) - "6162636465666768" # pc - "71727374" # cpsr + ("0102030405060708" "1112131415161718") # x0 # x1 + + 27 * ("2122232425262728") # x2..x28 + + ( + "3132333435363738" # x29 (fp) + "4142434445464748" # x30 (lr) + "5152535455565758" # x31 (sp) + "6162636465666768" # pc + "71727374" # cpsr + ) ) def qXferRead(self, obj, annex, offset, length): if annex == "target.xml": - return """ + return ( + """ aarch64 @@ -818,7 +861,9 @@ - """, False + """, + False, + ) else: return None, False @@ -835,17 +880,15 @@ target = self.createTarget("basic_eh_frame-aarch64.yaml") process = self.connect(target) - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) - self.match("register read x0", - ["x0 = 0x0807060504030201"]) + self.match("register read x0", ["x0 = 0x0807060504030201"]) # w0 comes from target.xml - self.match("register read w0", - ["w0 = 0x04030201"]) - self.match("register read x1", - ["x1 = 0x1817161514131211"]) + self.match("register read w0", ["w0 = 0x04030201"]) + self.match("register read x1", ["x1 = 0x1817161514131211"]) # w1 should not be added - self.match("register read w1", - ["error: Invalid register name 'w1'."], - error=True) + self.match( + "register read w1", ["error: Invalid register name 'w1'."], error=True + ) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestGdbClientMemoryRegions.py b/lldb/test/API/functionalities/gdb_remote_client/TestGdbClientMemoryRegions.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestGdbClientMemoryRegions.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestGdbClientMemoryRegions.py @@ -6,14 +6,13 @@ class TestGdbClientMemoryRegions(GDBRemoteTestBase): - def test(self): """ Test handling of overflowing memory regions. In particular, make sure they don't trigger an infinite loop. """ - class MyResponder(MockGDBServerResponder): + class MyResponder(MockGDBServerResponder): def qHostInfo(self): return "ptrsize:8;endian:little;" @@ -26,7 +25,7 @@ self.runCmd("log enable gdb-remote packets") self.runCmd("log enable lldb temp") self.server.responder = MyResponder() - target = self.dbg.CreateTarget('') + target = self.dbg.CreateTarget("") process = self.connect(target) regions = process.GetMemoryRegions() @@ -40,5 +39,5 @@ self.assertTrue(regions.GetMemoryRegionAtIndex(1, region)) self.assertEqual(region.GetRegionBase(), 0x8000000000000000) - self.assertEqual(region.GetRegionEnd(), 0xffffffffffffffff) + self.assertEqual(region.GetRegionEnd(), 0xFFFFFFFFFFFFFFFF) self.assertFalse(region.IsWritable()) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestGdbClientModuleLoad.py b/lldb/test/API/functionalities/gdb_remote_client/TestGdbClientModuleLoad.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestGdbClientModuleLoad.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestGdbClientModuleLoad.py @@ -4,6 +4,7 @@ from lldbsuite.test.gdbclientutils import * from lldbsuite.test.lldbgdbclient import GDBRemoteTestBase + class MyResponder(MockGDBServerResponder): """ A responder which simulates a process with a single shared library loaded. @@ -19,28 +20,42 @@ self._region_info = region_info def qSupported(self, client_supported): - return (super().qSupported(client_supported) + - ";qXfer:auxv:read+;qXfer:libraries-svr4:read+") + return ( + super().qSupported(client_supported) + + ";qXfer:auxv:read+;qXfer:libraries-svr4:read+" + ) def qXferRead(self, obj, annex, offset, length): if obj == "features" and annex == "target.xml": - return """ + return ( + """ i386:x86-64 - """, False + """, + False, + ) elif obj == "auxv": # 0x09 = AT_ENTRY, which lldb uses to compute the load bias of the # main binary. - return hex_decode_bytes(self._auxv_entry + - "09000000000000000000ee000000000000000000000000000000000000000000"), False + return ( + hex_decode_bytes( + self._auxv_entry + + "09000000000000000000ee000000000000000000000000000000000000000000" + ), + False, + ) elif obj == "libraries-svr4": - return """ + return ( + """ - """ % self._library_name, False + """ + % self._library_name, + False, + ) else: return None, False @@ -51,34 +66,36 @@ return "l" def qProcessInfo(self): - return "pid:47;ptrsize:8;endian:little;triple:%s;" % hex_encode_bytes(self._triple) + return "pid:47;ptrsize:8;endian:little;triple:%s;" % hex_encode_bytes( + self._triple + ) def setBreakpoint(self, packet): return "OK" def readMemory(self, addr, length): - if addr == 0xee1000: - return "00"*0x30 + "0020ee0000000000" - elif addr == 0xee2000: + if addr == 0xEE1000: + return "00" * 0x30 + "0020ee0000000000" + elif addr == 0xEE2000: return "01000000000000000030ee0000000000dead00000000000000000000000000000000000000000000" - elif addr == 0xef0000: + elif addr == 0xEF0000: with open(self.testcase.getBuildArtifact("libmodule_load.so"), "rb") as f: contents = f.read(-1) return hex_encode_bytes(seven.bitcast_to_string(contents)) - return ("baadf00d00"*1000)[0:length*2] + return ("baadf00d00" * 1000)[0 : length * 2] def qMemoryRegionInfo(self, addr): - if addr < 0xee0000: + if addr < 0xEE0000: return "start:0;size:ee0000;" - elif addr < 0xef0000: + elif addr < 0xEF0000: return "start:ee0000;size:10000;" - elif addr < 0xf00000: + elif addr < 0xF00000: return "start:ef0000;size:1000;permissions:rx;" + self._region_info else: return "start:ef1000;size:ffffffffff10f000" -class TestGdbClientModuleLoad(GDBRemoteTestBase): +class TestGdbClientModuleLoad(GDBRemoteTestBase): @skipIfXmlSupportMissing def test_android_app_process(self): """ @@ -87,21 +104,25 @@ qMemoryRegionInfo to get the correct value. """ region_info = "name:%s;" % ( - hex_encode_bytes(self.getBuildArtifact("libmodule_load.so"))) - self.server.responder = MyResponder(self, "x86_64-pc-linux-android", - "bogus-name", "", region_info) + hex_encode_bytes(self.getBuildArtifact("libmodule_load.so")) + ) + self.server.responder = MyResponder( + self, "x86_64-pc-linux-android", "bogus-name", "", region_info + ) self.yaml2obj("module_load.yaml", self.getBuildArtifact("libmodule_load.so")) target = self.createTarget("module_load.yaml") process = self.connect(target) self.assertTrue(process.IsValid(), "Process is valid") - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) self.filecheck("image list", __file__, "-check-prefix=ANDROID") -# ANDROID: [ 0] {{.*}} 0x0000000000ee0000 {{.*}}module_load -# ANDROID: [ 1] {{.*}} 0x0000000000ef0000 {{.*}}libmodule_load.so + + # ANDROID: [ 0] {{.*}} 0x0000000000ee0000 {{.*}}module_load + # ANDROID: [ 1] {{.*}} 0x0000000000ef0000 {{.*}}libmodule_load.so @skipIfXmlSupportMissing def test_vdso(self): @@ -113,18 +134,20 @@ """ # vdso address AT_SYSINFO_EHDR = "21000000000000000000ef0000000000" - self.server.responder = MyResponder(self, "x86_64-pc-linux", - "linux-vdso.so.1", AT_SYSINFO_EHDR, "") + self.server.responder = MyResponder( + self, "x86_64-pc-linux", "linux-vdso.so.1", AT_SYSINFO_EHDR, "" + ) self.yaml2obj("module_load.yaml", self.getBuildArtifact("libmodule_load.so")) target = self.createTarget("module_load.yaml") process = self.connect(target) self.assertTrue(process.IsValid(), "Process is valid") - lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, - [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, self.dbg.GetListener(), process, [lldb.eStateStopped] + ) self.filecheck("image list", __file__, "-check-prefix=VDSO") -# VDSO: [ 0] {{.*}} 0x0000000000ee0000 {{.*}}module_load -# VDSO: [ 1] {{.*}} 0x0000000000ef0000 {{.*}}[vdso] + # VDSO: [ 0] {{.*}} 0x0000000000ee0000 {{.*}}module_load + # VDSO: [ 1] {{.*}} 0x0000000000ef0000 {{.*}}[vdso] self.assertEquals(self.target().GetNumModules(), 2) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestIOSSimulator.py b/lldb/test/API/functionalities/gdb_remote_client/TestIOSSimulator.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestIOSSimulator.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestIOSSimulator.py @@ -4,6 +4,7 @@ from lldbsuite.test.gdbclientutils import * from lldbsuite.test.lldbgdbclient import GDBRemoteTestBase + class TestIOSSimulator(GDBRemoteTestBase): """ @@ -22,9 +23,17 @@ return MockGDBServerResponder.respond(self, packet) def qHostInfo(self): - return "cputype:16777223;cpusubtype:8;ostype:%s;vendor:apple;os_version:10.15.4;maccatalyst_version:13.4;endian:little;ptrsize:8;"%self.host_ostype + return ( + "cputype:16777223;cpusubtype:8;ostype:%s;vendor:apple;os_version:10.15.4;maccatalyst_version:13.4;endian:little;ptrsize:8;" + % self.host_ostype + ) + def qProcessInfo(self): - return "pid:a860;parent-pid:d2a0;real-uid:1f5;real-gid:14;effective-uid:1f5;effective-gid:14;cputype:1000007;cpusubtype:8;ptrsize:8;ostype:%s;vendor:apple;endian:little;"%self.process_ostype + return ( + "pid:a860;parent-pid:d2a0;real-uid:1f5;real-gid:14;effective-uid:1f5;effective-gid:14;cputype:1000007;cpusubtype:8;ptrsize:8;ostype:%s;vendor:apple;endian:little;" + % self.process_ostype + ) + def vCont(self): return "vCont;" @@ -41,25 +50,38 @@ @skipIfRemote def test_macos(self): - self.platform_test(host="macosx", process="macosx", - expected_triple="x86_64h-apple-macosx-") + self.platform_test( + host="macosx", process="macosx", expected_triple="x86_64h-apple-macosx-" + ) @skipIfRemote def test_ios_sim(self): - self.platform_test(host="macosx", process="iossimulator", - expected_triple="x86_64h-apple-ios-simulator") + self.platform_test( + host="macosx", + process="iossimulator", + expected_triple="x86_64h-apple-ios-simulator", + ) @skipIfRemote def test_catalyst(self): - self.platform_test(host="macosx", process="maccatalyst", - expected_triple="x86_64h-apple-ios-macabi") + self.platform_test( + host="macosx", + process="maccatalyst", + expected_triple="x86_64h-apple-ios-macabi", + ) @skipIfRemote def test_tvos_sim(self): - self.platform_test(host="macosx", process="tvossimulator", - expected_triple="x86_64h-apple-tvos-simulator") + self.platform_test( + host="macosx", + process="tvossimulator", + expected_triple="x86_64h-apple-tvos-simulator", + ) @skipIfRemote def test_tvos_sim(self): - self.platform_test(host="macosx", process="watchossimulator", - expected_triple="x86_64h-apple-watchos-simulator") + self.platform_test( + host="macosx", + process="watchossimulator", + expected_triple="x86_64h-apple-watchos-simulator", + ) diff --git a/lldb/test/API/functionalities/gdb_remote_client/TestJLink6Armv7RegisterDefinition.py b/lldb/test/API/functionalities/gdb_remote_client/TestJLink6Armv7RegisterDefinition.py --- a/lldb/test/API/functionalities/gdb_remote_client/TestJLink6Armv7RegisterDefinition.py +++ b/lldb/test/API/functionalities/gdb_remote_client/TestJLink6Armv7RegisterDefinition.py @@ -4,8 +4,8 @@ from lldbsuite.test.gdbclientutils import * from lldbsuite.test.lldbgdbclient import GDBRemoteTestBase -class TestJLink6Armv7RegisterDefinition(GDBRemoteTestBase): +class TestJLink6Armv7RegisterDefinition(GDBRemoteTestBase): @skipIfXmlSupportMissing @skipIfRemote def test(self): @@ -15,11 +15,12 @@ that the J-Link only supports g/G for reading/writing register AND the J-Link v6.54 doesn't provide anything but the general purpose registers.""" - class MyResponder(MockGDBServerResponder): + class MyResponder(MockGDBServerResponder): def qXferRead(self, obj, annex, offset, length): if annex == "target.xml": - return """ + return ( + """