summaryrefslogtreecommitdiff
path: root/gdb/python
diff options
context:
space:
mode:
Diffstat (limited to 'gdb/python')
-rw-r--r--gdb/python/lib/gdb/FrameDecorator.py43
-rw-r--r--gdb/python/lib/gdb/FrameIterator.py1
-rw-r--r--gdb/python/lib/gdb/__init__.py60
-rw-r--r--gdb/python/lib/gdb/command/__init__.py2
-rw-r--r--gdb/python/lib/gdb/command/explore.py342
-rw-r--r--gdb/python/lib/gdb/command/frame_filters.py205
-rw-r--r--gdb/python/lib/gdb/command/pretty_printers.py186
-rw-r--r--gdb/python/lib/gdb/command/prompt.py30
-rw-r--r--gdb/python/lib/gdb/command/type_printers.py41
-rw-r--r--gdb/python/lib/gdb/command/unwinders.py94
-rw-r--r--gdb/python/lib/gdb/command/xmethods.py133
-rw-r--r--gdb/python/lib/gdb/frames.py33
-rw-r--r--gdb/python/lib/gdb/function/as_string.py11
-rw-r--r--gdb/python/lib/gdb/function/caller_is.py87
-rw-r--r--gdb/python/lib/gdb/function/strfns.py100
-rw-r--r--gdb/python/lib/gdb/printer/bound_registers.py16
-rw-r--r--gdb/python/lib/gdb/printing.py27
-rw-r--r--gdb/python/lib/gdb/prompt.py75
-rw-r--r--gdb/python/lib/gdb/types.py25
-rw-r--r--gdb/python/lib/gdb/unwinder.py8
-rw-r--r--gdb/python/lib/gdb/xmethod.py25
-rw-r--r--gdb/python/python-config.py83
22 files changed, 903 insertions, 724 deletions
diff --git a/gdb/python/lib/gdb/FrameDecorator.py b/gdb/python/lib/gdb/FrameDecorator.py
index 25d58952f96..1f4b2cab6ec 100644
--- a/gdb/python/lib/gdb/FrameDecorator.py
+++ b/gdb/python/lib/gdb/FrameDecorator.py
@@ -24,6 +24,7 @@ try:
except NameError:
basestring = str
+
class FrameDecorator(object):
"""Basic implementation of a Frame Decorator"""
@@ -66,9 +67,12 @@ class FrameDecorator(object):
limited."""
sal = frame.find_sal()
- if (not sal.symtab or not sal.symtab.filename
+ if (
+ not sal.symtab
+ or not sal.symtab.filename
or frame.type() == gdb.DUMMY_FRAME
- or frame.type() == gdb.SIGTRAMP_FRAME):
+ or frame.type() == gdb.SIGTRAMP_FRAME
+ ):
return True
@@ -83,7 +87,7 @@ class FrameDecorator(object):
return None
def function(self):
- """ Return the name of the frame's function or an address of
+ """Return the name of the frame's function or an address of
the function of the frame. First determine if this is a
special frame. If not, try to determine filename from GDB's
frame internal function API. Finally, if a name cannot be
@@ -120,7 +124,7 @@ class FrameDecorator(object):
return str(func)
def address(self):
- """ Return the address of the frame's pc"""
+ """Return the address of the frame's pc"""
if hasattr(self._base, "address"):
return self._base.address()
@@ -129,7 +133,7 @@ class FrameDecorator(object):
return frame.pc()
def filename(self):
- """ Return the filename associated with this frame, detecting
+ """Return the filename associated with this frame, detecting
and returning the appropriate library name is this is a shared
library."""
@@ -145,7 +149,7 @@ class FrameDecorator(object):
return sal.symtab.filename
def frame_args(self):
- """ Return an iterable of frame arguments for this frame, if
+ """Return an iterable of frame arguments for this frame, if
any. The iterable object contains objects conforming with the
Symbol/Value interface. If there are no frame arguments, or
if this frame is deemed to be a special case, return None."""
@@ -161,7 +165,7 @@ class FrameDecorator(object):
return args.fetch_frame_args()
def frame_locals(self):
- """ Return an iterable of local variables for this frame, if
+ """Return an iterable of local variables for this frame, if
any. The iterable object contains objects conforming with the
Symbol/Value interface. If there are no frame locals, or if
this frame is deemed to be a special case, return None."""
@@ -177,7 +181,7 @@ class FrameDecorator(object):
return args.fetch_frame_locals()
def line(self):
- """ Return line number information associated with the frame's
+ """Return line number information associated with the frame's
pc. If symbol table/line information does not exist, or if
this frame is deemed to be a special case, return None"""
@@ -189,13 +193,13 @@ class FrameDecorator(object):
return None
sal = frame.find_sal()
- if (sal):
+ if sal:
return sal.line
else:
return None
def inferior_frame(self):
- """ Return the gdb.Frame underpinning this frame decorator."""
+ """Return the gdb.Frame underpinning this frame decorator."""
# If 'base' is a frame decorator, we want to call its inferior
# frame method. If '_base' is a gdb.Frame, just return that.
@@ -203,22 +207,25 @@ class FrameDecorator(object):
return self._base.inferior_frame()
return self._base
+
class SymValueWrapper(object):
"""A container class conforming to the Symbol/Value interface
which holds frame locals or frame arguments."""
+
def __init__(self, symbol, value):
self.sym = symbol
self.val = value
def value(self):
- """ Return the value associated with this symbol, or None"""
+ """Return the value associated with this symbol, or None"""
return self.val
def symbol(self):
- """ Return the symbol, or Python text, associated with this
+ """Return the symbol, or Python text, associated with this
symbol, or None"""
return self.sym
+
class FrameVars(object):
"""Utility class to fetch and store frame local variables, or
@@ -232,12 +239,12 @@ class FrameVars(object):
gdb.SYMBOL_LOC_ARG: True,
gdb.SYMBOL_LOC_REF_ARG: True,
gdb.SYMBOL_LOC_LOCAL: True,
- gdb.SYMBOL_LOC_REGPARM_ADDR: True,
- gdb.SYMBOL_LOC_COMPUTED: True
- }
+ gdb.SYMBOL_LOC_REGPARM_ADDR: True,
+ gdb.SYMBOL_LOC_COMPUTED: True,
+ }
def fetch_b(self, sym):
- """ Local utility method to determine if according to Symbol
+ """Local utility method to determine if according to Symbol
type whether it should be included in the iterator. Not all
symbols are fetched, and only symbols that return
True from this method should be fetched."""
@@ -268,7 +275,7 @@ class FrameVars(object):
break
for sym in block:
if sym.is_argument:
- continue;
+ continue
if self.fetch_b(sym):
lvars.append(SymValueWrapper(sym, None))
@@ -296,7 +303,7 @@ class FrameVars(object):
if block != None:
for sym in block:
if not sym.is_argument:
- continue;
+ continue
args.append(SymValueWrapper(sym, None))
return args
diff --git a/gdb/python/lib/gdb/FrameIterator.py b/gdb/python/lib/gdb/FrameIterator.py
index b9e44be0aff..fccb5886d1a 100644
--- a/gdb/python/lib/gdb/FrameIterator.py
+++ b/gdb/python/lib/gdb/FrameIterator.py
@@ -16,6 +16,7 @@
import gdb
import itertools
+
class FrameIterator(object):
"""A gdb.Frame iterator. Iterates over gdb.Frames or objects that
conform to that interface."""
diff --git a/gdb/python/lib/gdb/__init__.py b/gdb/python/lib/gdb/__init__.py
index 9a0e9891cc5..d748b3a5827 100644
--- a/gdb/python/lib/gdb/__init__.py
+++ b/gdb/python/lib/gdb/__init__.py
@@ -26,7 +26,8 @@ elif sys.version_info[0] > 2:
from _gdb import *
-class _GdbFile (object):
+
+class _GdbFile(object):
# These two are needed in Python 3
encoding = "UTF-8"
errors = "strict"
@@ -45,16 +46,20 @@ class _GdbFile (object):
def flush(self):
flush()
-class _GdbOutputFile (_GdbFile):
+
+class _GdbOutputFile(_GdbFile):
def write(self, s):
write(s, stream=STDOUT)
+
sys.stdout = _GdbOutputFile()
-class _GdbOutputErrorFile (_GdbFile):
+
+class _GdbOutputErrorFile(_GdbFile):
def write(self, s):
write(s, stream=STDERR)
+
sys.stderr = _GdbOutputErrorFile()
# Default prompt hook does nothing.
@@ -62,7 +67,7 @@ prompt_hook = None
# Ensure that sys.argv is set to something.
# We do not use PySys_SetArgvEx because it did not appear until 2.6.6.
-sys.argv = ['']
+sys.argv = [""]
# Initial pretty printers.
pretty_printers = []
@@ -76,6 +81,7 @@ frame_filters = {}
# Initial frame unwinders.
frame_unwinders = []
+
def _execute_unwinders(pending_frame):
"""Internal function called from GDB to execute all unwinders.
@@ -108,6 +114,7 @@ def _execute_unwinders(pending_frame):
return None
+
def _execute_file(filepath):
"""This function is used to replace Python 2's PyRun_SimpleFile.
@@ -117,22 +124,22 @@ def _execute_file(filepath):
"Furthermore, any functions and classes defined by the executed code are
not guaranteed to work correctly after a runpy function has returned."
"""
- globals = sys.modules['__main__'].__dict__
+ globals = sys.modules["__main__"].__dict__
set_file = False
# Set file (if not set) so that the imported file can use it (e.g. to
# access file-relative paths). This matches what PyRun_SimpleFile does.
- if not hasattr(globals, '__file__'):
- globals['__file__'] = filepath
+ if not hasattr(globals, "__file__"):
+ globals["__file__"] = filepath
set_file = True
try:
- with open(filepath, 'rb') as file:
+ with open(filepath, "rb") as file:
# We pass globals also as locals to match what Python does
# in PyRun_SimpleFile.
- compiled = compile(file.read(), filepath, 'exec')
+ compiled = compile(file.read(), filepath, "exec")
exec(compiled, globals, globals)
finally:
if set_file:
- del globals['__file__']
+ del globals["__file__"]
# Convenience variable to GDB's python directory
@@ -142,27 +149,24 @@ PYTHONDIR = os.path.dirname(os.path.dirname(__file__))
# Packages to auto-load.
-packages = [
- 'function',
- 'command',
- 'printer'
-]
+packages = ["function", "command", "printer"]
# pkgutil.iter_modules is not available prior to Python 2.6. Instead,
# manually iterate the list, collating the Python files in each module
# path. Construct the module name, and import.
+
def _auto_load_packages():
for package in packages:
location = os.path.join(os.path.dirname(__file__), package)
if os.path.exists(location):
- py_files = filter(lambda x: x.endswith('.py')
- and x != '__init__.py',
- os.listdir(location))
+ py_files = filter(
+ lambda x: x.endswith(".py") and x != "__init__.py", os.listdir(location)
+ )
for py_file in py_files:
# Construct from foo.py, gdb.module.foo
- modname = "%s.%s.%s" % ( __name__, package, py_file[:-3] )
+ modname = "%s.%s.%s" % (__name__, package, py_file[:-3])
try:
if modname in sys.modules:
# reload modules with duplicate names
@@ -170,10 +174,12 @@ def _auto_load_packages():
else:
__import__(modname)
except:
- sys.stderr.write (traceback.format_exc() + "\n")
+ sys.stderr.write(traceback.format_exc() + "\n")
+
_auto_load_packages()
+
def GdbSetPythonDirectory(dir):
"""Update sys.path, reload gdb and auto-load packages."""
global PYTHONDIR
@@ -191,30 +197,37 @@ def GdbSetPythonDirectory(dir):
reload(__import__(__name__))
_auto_load_packages()
+
def current_progspace():
"Return the current Progspace."
return selected_inferior().progspace
+
def objfiles():
"Return a sequence of the current program space's objfiles."
return current_progspace().objfiles()
-def solib_name (addr):
+
+def solib_name(addr):
"""solib_name (Long) -> String.\n\
Return the name of the shared library holding a given address, or None."""
return current_progspace().solib_name(addr)
+
def block_for_pc(pc):
"Return the block containing the given pc value, or None."
return current_progspace().block_for_pc(pc)
+
def find_pc_line(pc):
"""find_pc_line (pc) -> Symtab_and_line.
-Return the gdb.Symtab_and_line object corresponding to the pc value."""
+ Return the gdb.Symtab_and_line object corresponding to the pc value."""
return current_progspace().find_pc_line(pc)
+
try:
from pygments import formatters, lexers, highlight
+
def colorize(filename, contents):
# Don't want any errors.
try:
@@ -223,6 +236,9 @@ try:
return highlight(contents, lexer, formatter)
except:
return None
+
+
except:
+
def colorize(filename, contents):
return None
diff --git a/gdb/python/lib/gdb/command/__init__.py b/gdb/python/lib/gdb/command/__init__.py
index 5ba92a8c2e1..ac45a0da815 100644
--- a/gdb/python/lib/gdb/command/__init__.py
+++ b/gdb/python/lib/gdb/command/__init__.py
@@ -12,5 +12,3 @@
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-
diff --git a/gdb/python/lib/gdb/command/explore.py b/gdb/python/lib/gdb/command/explore.py
index 3a265be5baf..3b76d36cfb4 100644
--- a/gdb/python/lib/gdb/command/explore.py
+++ b/gdb/python/lib/gdb/command/explore.py
@@ -22,12 +22,13 @@ import sys
if sys.version_info[0] > 2:
# Python 3 renamed raw_input to input
raw_input = input
-
+
+
class Explorer(object):
"""Internal class which invokes other explorers."""
# This map is filled by the Explorer.init_env() function
- type_code_to_explorer_map = { }
+ type_code_to_explorer_map = {}
_SCALAR_TYPE_LIST = (
gdb.TYPE_CODE_CHAR,
@@ -43,14 +44,18 @@ class Explorer(object):
length = len(expr)
guard = False
- if expr[0] == '(' and expr[length-1] == ')':
+ if expr[0] == "(" and expr[length - 1] == ")":
pass
else:
i = 0
while i < length:
c = expr[i]
- if (c == '_' or ('a' <= c and c <= 'z') or
- ('A' <= c and c <= 'Z') or ('0' <= c and c <= '9')):
+ if (
+ c == "_"
+ or ("a" <= c and c <= "z")
+ or ("A" <= c and c <= "Z")
+ or ("0" <= c and c <= "9")
+ ):
pass
else:
guard = True
@@ -85,8 +90,7 @@ class Explorer(object):
while explorer_class.explore_expr(expr, value, is_child):
pass
else:
- print ("Explorer for type '%s' not yet available.\n" %
- str(value.type))
+ print("Explorer for type '%s' not yet available.\n" % str(value.type))
@staticmethod
def explore_type(name, datatype, is_child):
@@ -111,8 +115,7 @@ class Explorer(object):
while explorer_class.explore_type(name, datatype, is_child):
pass
else:
- print ("Explorer for type '%s' not yet available.\n" %
- str(datatype))
+ print("Explorer for type '%s' not yet available.\n" % str(datatype))
@staticmethod
def init_env():
@@ -122,19 +125,19 @@ class Explorer(object):
explorations.
"""
Explorer.type_code_to_explorer_map = {
- gdb.TYPE_CODE_CHAR : ScalarExplorer,
- gdb.TYPE_CODE_INT : ScalarExplorer,
- gdb.TYPE_CODE_BOOL : ScalarExplorer,
- gdb.TYPE_CODE_FLT : ScalarExplorer,
- gdb.TYPE_CODE_VOID : ScalarExplorer,
- gdb.TYPE_CODE_ENUM : ScalarExplorer,
- gdb.TYPE_CODE_STRUCT : CompoundExplorer,
- gdb.TYPE_CODE_UNION : CompoundExplorer,
- gdb.TYPE_CODE_PTR : PointerExplorer,
- gdb.TYPE_CODE_REF : ReferenceExplorer,
- gdb.TYPE_CODE_RVALUE_REF : ReferenceExplorer,
- gdb.TYPE_CODE_TYPEDEF : TypedefExplorer,
- gdb.TYPE_CODE_ARRAY : ArrayExplorer
+ gdb.TYPE_CODE_CHAR: ScalarExplorer,
+ gdb.TYPE_CODE_INT: ScalarExplorer,
+ gdb.TYPE_CODE_BOOL: ScalarExplorer,
+ gdb.TYPE_CODE_FLT: ScalarExplorer,
+ gdb.TYPE_CODE_VOID: ScalarExplorer,
+ gdb.TYPE_CODE_ENUM: ScalarExplorer,
+ gdb.TYPE_CODE_STRUCT: CompoundExplorer,
+ gdb.TYPE_CODE_UNION: CompoundExplorer,
+ gdb.TYPE_CODE_PTR: PointerExplorer,
+ gdb.TYPE_CODE_REF: ReferenceExplorer,
+ gdb.TYPE_CODE_RVALUE_REF: ReferenceExplorer,
+ gdb.TYPE_CODE_TYPEDEF: TypedefExplorer,
+ gdb.TYPE_CODE_ARRAY: ArrayExplorer,
}
@staticmethod
@@ -161,8 +164,8 @@ class Explorer(object):
"""A utility function which prints that the current exploration session
is returning to the parent value. Useful when exploring values.
"""
- print ("\nReturning to parent value...\n")
-
+ print("\nReturning to parent value...\n")
+
@staticmethod
def return_to_parent_value_prompt():
"""A utility function which prompts the user to press the 'enter' key
@@ -170,14 +173,14 @@ class Explorer(object):
Useful when exploring values.
"""
raw_input("\nPress enter to return to parent value: ")
-
+
@staticmethod
def return_to_enclosing_type():
"""A utility function which prints that the current exploration session
is returning to the enclosing type. Useful when exploring types.
"""
- print ("\nReturning to enclosing type...\n")
-
+ print("\nReturning to enclosing type...\n")
+
@staticmethod
def return_to_enclosing_type_prompt():
"""A utility function which prompts the user to press the 'enter' key
@@ -196,9 +199,8 @@ class ScalarExplorer(object):
See Explorer.explore_expr and Explorer.is_scalar_type for more
information.
"""
- print ("'%s' is a scalar value of type '%s'." %
- (expr, value.type))
- print ("%s = %s" % (expr, str(value)))
+ print("'%s' is a scalar value of type '%s'." % (expr, value.type))
+ print("%s = %s" % (expr, str(value)))
if is_child:
Explorer.return_to_parent_value_prompt()
@@ -214,16 +216,14 @@ class ScalarExplorer(object):
"""
if datatype.code == gdb.TYPE_CODE_ENUM:
if is_child:
- print ("%s is of an enumerated type '%s'." %
- (name, str(datatype)))
+ print("%s is of an enumerated type '%s'." % (name, str(datatype)))
else:
- print ("'%s' is an enumerated type." % name)
+ print("'%s' is an enumerated type." % name)
else:
if is_child:
- print ("%s is of a scalar type '%s'." %
- (name, str(datatype)))
+ print("%s is of a scalar type '%s'." % (name, str(datatype)))
else:
- print ("'%s' is a scalar type." % name)
+ print("'%s' is a scalar type." % name)
if is_child:
Explorer.return_to_enclosing_type_prompt()
@@ -240,33 +240,41 @@ class PointerExplorer(object):
"""Function to explore pointer values.
See Explorer.explore_expr for more information.
"""
- print ("'%s' is a pointer to a value of type '%s'" %
- (expr, str(value.type.target())))
- option = raw_input("Continue exploring it as a pointer to a single "
- "value [y/n]: ")
+ print(
+ "'%s' is a pointer to a value of type '%s'"
+ % (expr, str(value.type.target()))
+ )
+ option = raw_input(
+ "Continue exploring it as a pointer to a single " "value [y/n]: "
+ )
if option == "y":
deref_value = None
try:
deref_value = value.dereference()
str(deref_value)
except gdb.MemoryError:
- print ("'%s' a pointer pointing to an invalid memory "
- "location." % expr)
+ print(
+ "'%s' a pointer pointing to an invalid memory " "location." % expr
+ )
if is_child:
Explorer.return_to_parent_value_prompt()
return False
- Explorer.explore_expr("*%s" % Explorer.guard_expr(expr),
- deref_value, is_child)
+ Explorer.explore_expr(
+ "*%s" % Explorer.guard_expr(expr), deref_value, is_child
+ )
return False
-
- option = raw_input("Continue exploring it as a pointer to an "
- "array [y/n]: ")
+
+ option = raw_input("Continue exploring it as a pointer to an " "array [y/n]: ")
if option == "y":
while True:
index = 0
try:
- index = int(raw_input("Enter the index of the element you "
- "want to explore in '%s': " % expr))
+ index = int(
+ raw_input(
+ "Enter the index of the element you "
+ "want to explore in '%s': " % expr
+ )
+ )
except ValueError:
break
element_expr = "%s[%d]" % (Explorer.guard_expr(expr), index)
@@ -274,7 +282,7 @@ class PointerExplorer(object):
try:
str(element)
except gdb.MemoryError:
- print ("Cannot read value at index %d." % index)
+ print("Cannot read value at index %d." % index)
continue
Explorer.explore_expr(element_expr, element, True)
return False
@@ -289,12 +297,9 @@ class PointerExplorer(object):
See Explorer.explore_type for more information.
"""
target_type = datatype.target()
- print ("\n%s is a pointer to a value of type '%s'." %
- (name, str(target_type)))
+ print("\n%s is a pointer to a value of type '%s'." % (name, str(target_type)))
- Explorer.explore_type("the pointee type of %s" % name,
- target_type,
- is_child)
+ Explorer.explore_type("the pointee type of %s" % name, target_type, is_child)
return False
@@ -319,6 +324,7 @@ class ReferenceExplorer(object):
Explorer.explore_type(name, target_type, is_child)
return False
+
class ArrayExplorer(object):
"""Internal class used to explore arrays."""
@@ -328,11 +334,15 @@ class ArrayExplorer(object):
See Explorer.explore_expr for more information.
"""
target_type = value.type.target()
- print ("'%s' is an array of '%s'." % (expr, str(target_type)))
+ print("'%s' is an array of '%s'." % (expr, str(target_type)))
index = 0
try:
- index = int(raw_input("Enter the index of the element you want to "
- "explore in '%s': " % expr))
+ index = int(
+ raw_input(
+ "Enter the index of the element you want to "
+ "explore in '%s': " % expr
+ )
+ )
except ValueError:
if is_child:
Explorer.return_to_parent_value()
@@ -343,12 +353,13 @@ class ArrayExplorer(object):
element = value[index]
str(element)
except gdb.MemoryError:
- print ("Cannot read value at index %d." % index)
+ print("Cannot read value at index %d." % index)
raw_input("Press enter to continue... ")
return True
-
- Explorer.explore_expr("%s[%d]" % (Explorer.guard_expr(expr), index),
- element, True)
+
+ Explorer.explore_expr(
+ "%s[%d]" % (Explorer.guard_expr(expr), index), element, True
+ )
return True
@staticmethod
@@ -357,10 +368,9 @@ class ArrayExplorer(object):
See Explorer.explore_type for more information.
"""
target_type = datatype.target()
- print ("%s is an array of '%s'." % (name, str(target_type)))
+ print("%s is an array of '%s'." % (name, str(target_type)))
- Explorer.explore_type("the array element of %s" % name, target_type,
- is_child)
+ Explorer.explore_type("the array element of %s" % name, target_type, is_child)
return False
@@ -369,19 +379,18 @@ class CompoundExplorer(object):
@staticmethod
def _print_fields(print_list):
- """Internal function which prints the fields of a struct/class/union.
- """
+ """Internal function which prints the fields of a struct/class/union."""
max_field_name_length = 0
for pair in print_list:
if max_field_name_length < len(pair[0]):
max_field_name_length = len(pair[0])
for pair in print_list:
- print (" %*s = %s" % (max_field_name_length, pair[0], pair[1]))
+ print(" %*s = %s" % (max_field_name_length, pair[0], pair[1]))
@staticmethod
def _get_real_field_count(fields):
- real_field_count = 0;
+ real_field_count = 0
for field in fields:
if not field.artificial:
real_field_count = real_field_count + 1
@@ -403,19 +412,23 @@ class CompoundExplorer(object):
type_desc = "union"
if CompoundExplorer._get_real_field_count(fields) == 0:
- print ("The value of '%s' is a %s of type '%s' with no fields." %
- (expr, type_desc, str(value.type)))
+ print(
+ "The value of '%s' is a %s of type '%s' with no fields."
+ % (expr, type_desc, str(value.type))
+ )
if is_child:
Explorer.return_to_parent_value_prompt()
return False
- print ("The value of '%s' is a %s of type '%s' with the following "
- "fields:\n" % (expr, type_desc, str(value.type)))
+ print(
+ "The value of '%s' is a %s of type '%s' with the following "
+ "fields:\n" % (expr, type_desc, str(value.type))
+ )
has_explorable_fields = False
- choice_to_compound_field_map = { }
+ choice_to_compound_field_map = {}
current_choice = 0
- print_list = [ ]
+ print_list = []
for field in fields:
if field.artificial:
continue
@@ -426,39 +439,48 @@ class CompoundExplorer(object):
field_value = value[field.name]
literal_value = ""
if type_code == gdb.TYPE_CODE_UNION:
- literal_value = ("<Enter %d to explore this field of type "
- "'%s'>" % (current_choice, str(field.type)))
+ literal_value = "<Enter %d to explore this field of type " "'%s'>" % (
+ current_choice,
+ str(field.type),
+ )
has_explorable_fields = True
else:
if Explorer.is_scalar_type(field.type):
- literal_value = ("%s .. (Value of type '%s')" %
- (str(field_value), str(field.type)))
+ literal_value = "%s .. (Value of type '%s')" % (
+ str(field_value),
+ str(field.type),
+ )
else:
if field.is_base_class:
field_desc = "base class"
else:
field_desc = "field"
- literal_value = ("<Enter %d to explore this %s of type "
- "'%s'>" %
- (current_choice, field_desc,
- str(field.type)))
+ literal_value = "<Enter %d to explore this %s of type " "'%s'>" % (
+ current_choice,
+ field_desc,
+ str(field.type),
+ )
has_explorable_fields = True
choice_to_compound_field_map[str(current_choice)] = (
- field_full_name, field_value)
+ field_full_name,
+ field_value,
+ )
current_choice = current_choice + 1
print_list.append((field.name, literal_value))
CompoundExplorer._print_fields(print_list)
- print ("")
+ print("")
if has_explorable_fields:
choice = raw_input("Enter the field number of choice: ")
if choice in choice_to_compound_field_map:
- Explorer.explore_expr(choice_to_compound_field_map[choice][0],
- choice_to_compound_field_map[choice][1],
- True)
+ Explorer.explore_expr(
+ choice_to_compound_field_map[choice][0],
+ choice_to_compound_field_map[choice][1],
+ True,
+ )
return True
else:
if is_child:
@@ -484,26 +506,27 @@ class CompoundExplorer(object):
fields = datatype.fields()
if CompoundExplorer._get_real_field_count(fields) == 0:
if is_child:
- print ("%s is a %s of type '%s' with no fields." %
- (name, type_desc, str(datatype)))
+ print(
+ "%s is a %s of type '%s' with no fields."
+ % (name, type_desc, str(datatype))
+ )
Explorer.return_to_enclosing_type_prompt()
else:
- print ("'%s' is a %s with no fields." % (name, type_desc))
+ print("'%s' is a %s with no fields." % (name, type_desc))
return False
if is_child:
- print ("%s is a %s of type '%s' "
- "with the following fields:\n" %
- (name, type_desc, str(datatype)))
+ print(
+ "%s is a %s of type '%s' "
+ "with the following fields:\n" % (name, type_desc, str(datatype))
+ )
else:
- print ("'%s' is a %s with the following "
- "fields:\n" %
- (name, type_desc))
+ print("'%s' is a %s with the following " "fields:\n" % (name, type_desc))
has_explorable_fields = False
current_choice = 0
- choice_to_compound_field_map = { }
- print_list = [ ]
+ choice_to_compound_field_map = {}
+ print_list = []
for field in fields:
if field.artificial:
continue
@@ -511,31 +534,40 @@ class CompoundExplorer(object):
field_desc = "base class"
else:
field_desc = "field"
- rhs = ("<Enter %d to explore this %s of type '%s'>" %
- (current_choice, field_desc, str(field.type)))
+ rhs = "<Enter %d to explore this %s of type '%s'>" % (
+ current_choice,
+ field_desc,
+ str(field.type),
+ )
print_list.append((field.name, rhs))
choice_to_compound_field_map[str(current_choice)] = (
- field.name, field.type, field_desc)
+ field.name,
+ field.type,
+ field_desc,
+ )
current_choice = current_choice + 1
CompoundExplorer._print_fields(print_list)
- print ("")
+ print("")
if len(choice_to_compound_field_map) > 0:
choice = raw_input("Enter the field number of choice: ")
if choice in choice_to_compound_field_map:
if is_child:
- new_name = ("%s '%s' of %s" %
- (choice_to_compound_field_map[choice][2],
- choice_to_compound_field_map[choice][0],
- name))
+ new_name = "%s '%s' of %s" % (
+ choice_to_compound_field_map[choice][2],
+ choice_to_compound_field_map[choice][0],
+ name,
+ )
else:
- new_name = ("%s '%s' of '%s'" %
- (choice_to_compound_field_map[choice][2],
- choice_to_compound_field_map[choice][0],
- name))
- Explorer.explore_type(new_name,
- choice_to_compound_field_map[choice][1], True)
+ new_name = "%s '%s' of '%s'" % (
+ choice_to_compound_field_map[choice][2],
+ choice_to_compound_field_map[choice][0],
+ name,
+ )
+ Explorer.explore_type(
+ new_name, choice_to_compound_field_map[choice][1], True
+ )
return True
else:
if is_child:
@@ -545,7 +577,7 @@ class CompoundExplorer(object):
Explorer.return_to_enclosing_type_prompt()
return False
-
+
class TypedefExplorer(object):
"""Internal class used to explore values whose type is a typedef."""
@@ -556,9 +588,11 @@ class TypedefExplorer(object):
See Explorer.explore_expr for more information.
"""
actual_type = value.type.strip_typedefs()
- print ("The value of '%s' is of type '%s' "
- "which is a typedef of type '%s'" %
- (expr, str(value.type), str(actual_type)))
+ print(
+ "The value of '%s' is of type '%s' "
+ "which is a typedef of type '%s'"
+ % (expr, str(value.type), str(actual_type))
+ )
Explorer.explore_expr(expr, value.cast(actual_type), is_child)
return False
@@ -570,11 +604,11 @@ class TypedefExplorer(object):
"""
actual_type = datatype.strip_typedefs()
if is_child:
- print ("The type of %s is a typedef of type '%s'." %
- (name, str(actual_type)))
+ print(
+ "The type of %s is a typedef of type '%s'." % (name, str(actual_type))
+ )
else:
- print ("The type '%s' is a typedef of type '%s'." %
- (name, str(actual_type)))
+ print("The type '%s' is a typedef of type '%s'." % (name, str(actual_type)))
Explorer.explore_type(name, actual_type, is_child)
return False
@@ -599,8 +633,7 @@ class ExploreUtils(object):
gdb.GdbError if adequate arguments are not passed.
"""
if len(arg_str) < 1:
- raise gdb.GdbError("ERROR: '%s' requires an argument."
- % name)
+ raise gdb.GdbError("ERROR: '%s' requires an argument." % name)
return False
else:
return True
@@ -649,16 +682,16 @@ class ExploreUtils(object):
class ExploreCommand(gdb.Command):
"""Explore a value or a type valid in the current context.
-Usage: explore ARG
+ Usage: explore ARG
-- ARG is either a valid expression or a type name.
-- At any stage of exploration, hit the return key (instead of a
-choice, if any) to return to the enclosing type or value."""
+ - ARG is either a valid expression or a type name.
+ - At any stage of exploration, hit the return key (instead of a
+ choice, if any) to return to the enclosing type or value."""
def __init__(self):
- super(ExploreCommand, self).__init__(name = "explore",
- command_class = gdb.COMMAND_DATA,
- prefix = True)
+ super(ExploreCommand, self).__init__(
+ name="explore", command_class=gdb.COMMAND_DATA, prefix=True
+ )
def invoke(self, arg_str, from_tty):
if ExploreUtils.check_args("explore", arg_str) == False:
@@ -678,23 +711,26 @@ choice, if any) to return to the enclosing type or value."""
# If it is neither a value nor a type, raise an error.
raise gdb.GdbError(
- ("'%s' neither evaluates to a value nor is a type "
- "in the current context." %
- arg_str))
+ (
+ "'%s' neither evaluates to a value nor is a type "
+ "in the current context." % arg_str
+ )
+ )
class ExploreValueCommand(gdb.Command):
"""Explore value of an expression valid in the current context.
-Usage: explore value ARG
+ Usage: explore value ARG
+
+ - ARG is a valid expression.
+ - At any stage of exploration, hit the return key (instead of a
+ choice, if any) to return to the enclosing value."""
-- ARG is a valid expression.
-- At any stage of exploration, hit the return key (instead of a
-choice, if any) to return to the enclosing value."""
-
def __init__(self):
super(ExploreValueCommand, self).__init__(
- name = "explore value", command_class = gdb.COMMAND_DATA)
+ name="explore value", command_class=gdb.COMMAND_DATA
+ )
def invoke(self, arg_str, from_tty):
if ExploreUtils.check_args("explore value", arg_str) == False:
@@ -703,26 +739,29 @@ choice, if any) to return to the enclosing value."""
value = ExploreUtils.get_value_from_str(arg_str)
if value is None:
raise gdb.GdbError(
- (" '%s' does not evaluate to a value in the current "
- "context." %
- arg_str))
+ (
+ " '%s' does not evaluate to a value in the current "
+ "context." % arg_str
+ )
+ )
return
Explorer.explore_expr(arg_str, value, False)
-class ExploreTypeCommand(gdb.Command):
+class ExploreTypeCommand(gdb.Command):
"""Explore a type or the type of an expression.
-Usage: explore type ARG
+ Usage: explore type ARG
-- ARG is a valid expression or a type name.
-- At any stage of exploration, hit the return key (instead of a
-choice, if any) to return to the enclosing type."""
+ - ARG is a valid expression or a type name.
+ - At any stage of exploration, hit the return key (instead of a
+ choice, if any) to return to the enclosing type."""
def __init__(self):
super(ExploreTypeCommand, self).__init__(
- name = "explore type", command_class = gdb.COMMAND_DATA)
+ name="explore type", command_class=gdb.COMMAND_DATA
+ )
def invoke(self, arg_str, from_tty):
if ExploreUtils.check_args("explore type", arg_str) == False:
@@ -735,12 +774,13 @@ choice, if any) to return to the enclosing type."""
value = ExploreUtils.get_value_from_str(arg_str)
if value is not None:
- print ("'%s' is of type '%s'." % (arg_str, str(value.type)))
+ print("'%s' is of type '%s'." % (arg_str, str(value.type)))
Explorer.explore_type(str(value.type), value.type, False)
return
- raise gdb.GdbError(("'%s' is not a type or value in the current "
- "context." % arg_str))
+ raise gdb.GdbError(
+ ("'%s' is not a type or value in the current " "context." % arg_str)
+ )
Explorer.init_env()
diff --git a/gdb/python/lib/gdb/command/frame_filters.py b/gdb/python/lib/gdb/command/frame_filters.py
index 09e1f9aa5ad..91e8ca2d43c 100644
--- a/gdb/python/lib/gdb/command/frame_filters.py
+++ b/gdb/python/lib/gdb/command/frame_filters.py
@@ -29,24 +29,28 @@ class SetFilterPrefixCmd(gdb.Command):
"""Prefix command for 'set' frame-filter related operations."""
def __init__(self):
- super(SetFilterPrefixCmd, self).__init__("set frame-filter",
- gdb.COMMAND_OBSCURE,
- gdb.COMPLETE_NONE, True)
+ super(SetFilterPrefixCmd, self).__init__(
+ "set frame-filter", gdb.COMMAND_OBSCURE, gdb.COMPLETE_NONE, True
+ )
+
class ShowFilterPrefixCmd(gdb.Command):
"""Prefix command for 'show' frame-filter related operations."""
+
def __init__(self):
- super(ShowFilterPrefixCmd, self).__init__("show frame-filter",
- gdb.COMMAND_OBSCURE,
- gdb.COMPLETE_NONE, True)
+ super(ShowFilterPrefixCmd, self).__init__(
+ "show frame-filter", gdb.COMMAND_OBSCURE, gdb.COMPLETE_NONE, True
+ )
+
+
class InfoFrameFilter(gdb.Command):
"""List all registered Python frame-filters.
-Usage: info frame-filters"""
+ Usage: info frame-filters"""
def __init__(self):
- super(InfoFrameFilter, self).__init__("info frame-filter",
- gdb.COMMAND_DATA)
+ super(InfoFrameFilter, self).__init__("info frame-filter", gdb.COMMAND_DATA)
+
@staticmethod
def enabled_string(state):
"""Return "Yes" if filter is enabled, otherwise "No"."""
@@ -56,9 +60,11 @@ Usage: info frame-filters"""
return "No"
def print_list(self, title, frame_filters, blank_line):
- sorted_frame_filters = sorted(frame_filters.items(),
- key=lambda i: gdb.frames.get_priority(i[1]),
- reverse=True)
+ sorted_frame_filters = sorted(
+ frame_filters.items(),
+ key=lambda i: gdb.frames.get_priority(i[1]),
+ reverse=True,
+ )
if len(sorted_frame_filters) == 0:
return 0
@@ -68,14 +74,14 @@ Usage: info frame-filters"""
for frame_filter in sorted_frame_filters:
name = frame_filter[0]
try:
- priority = '{:<8}'.format(
- str(gdb.frames.get_priority(frame_filter[1])))
- enabled = '{:<7}'.format(
- self.enabled_string(gdb.frames.get_enabled(frame_filter[1])))
+ priority = "{:<8}".format(str(gdb.frames.get_priority(frame_filter[1])))
+ enabled = "{:<7}".format(
+ self.enabled_string(gdb.frames.get_enabled(frame_filter[1]))
+ )
print(" %s %s %s" % (priority, enabled, name))
except Exception:
e = sys.exc_info()[1]
- print(" Error printing filter '"+name+"': "+str(e))
+ print(" Error printing filter '" + name + "': " + str(e))
if blank_line:
print("")
return 1
@@ -84,20 +90,26 @@ Usage: info frame-filters"""
any_printed = self.print_list("global frame-filters:", gdb.frame_filters, True)
cp = gdb.current_progspace()
- any_printed += self.print_list("progspace %s frame-filters:" % cp.filename,
- cp.frame_filters, True)
+ any_printed += self.print_list(
+ "progspace %s frame-filters:" % cp.filename, cp.frame_filters, True
+ )
for objfile in gdb.objfiles():
- any_printed += self.print_list("objfile %s frame-filters:" % objfile.filename,
- objfile.frame_filters, False)
+ any_printed += self.print_list(
+ "objfile %s frame-filters:" % objfile.filename,
+ objfile.frame_filters,
+ False,
+ )
if any_printed == 0:
- print ("No frame filters.")
+ print("No frame filters.")
+
# Internal enable/disable functions.
+
def _enable_parse_arg(cmd_name, arg):
- """ Internal worker function to take an argument from
+ """Internal worker function to take an argument from
enable/disable and return a tuple of arguments.
Arguments:
@@ -109,19 +121,21 @@ def _enable_parse_arg(cmd_name, arg):
the dictionary in the case of "all".
"""
- argv = gdb.string_to_argv(arg);
+ argv = gdb.string_to_argv(arg)
argc = len(argv)
if argc == 0:
raise gdb.GdbError(cmd_name + " requires an argument")
if argv[0] == "all":
if argc > 1:
- raise gdb.GdbError(cmd_name + ": with 'all' " \
- "you may not specify a filter.")
+ raise gdb.GdbError(
+ cmd_name + ": with 'all' " "you may not specify a filter."
+ )
elif argc != 2:
- raise gdb.GdbError(cmd_name + " takes exactly two arguments.")
+ raise gdb.GdbError(cmd_name + " takes exactly two arguments.")
return argv
+
def _do_enable_frame_filter(command_tuple, flag):
"""Worker for enabling/disabling frame_filters.
@@ -148,6 +162,7 @@ def _do_enable_frame_filter(command_tuple, flag):
gdb.frames.set_enabled(ff, flag)
+
def _complete_frame_filter_list(text, word, all_flag):
"""Worker for frame filter dictionary name completion.
@@ -160,7 +175,7 @@ def _complete_frame_filter_list(text, word, all_flag):
A list of suggested frame filter dictionary name completions
from text/word analysis. This list can be empty when there
are no suggestions for completion.
- """
+ """
if all_flag == True:
filter_locations = ["all", "global", "progspace"]
else:
@@ -171,20 +186,21 @@ def _complete_frame_filter_list(text, word, all_flag):
# If the user just asked for completions with no completion
# hints, just return all the frame filter dictionaries we know
# about.
- if (text == ""):
+ if text == "":
return filter_locations
# Otherwise filter on what we know.
- flist = filter(lambda x,y=text:x.startswith(y), filter_locations)
+ flist = filter(lambda x, y=text: x.startswith(y), filter_locations)
# If we only have one completion, complete it and return it.
if len(flist) == 1:
- flist[0] = flist[0][len(text)-len(word):]
+ flist[0] = flist[0][len(text) - len(word) :]
# Otherwise, return an empty list, or a list of frame filter
# dictionaries that the previous filter operation returned.
return flist
+
def _complete_frame_filter_name(word, printer_dict):
"""Worker for frame filter name completion.
@@ -201,29 +217,31 @@ def _complete_frame_filter_name(word, printer_dict):
"""
printer_keys = printer_dict.keys()
- if (word == ""):
+ if word == "":
return printer_keys
- flist = filter(lambda x,y=word:x.startswith(y), printer_keys)
+ flist = filter(lambda x, y=word: x.startswith(y), printer_keys)
return flist
+
class EnableFrameFilter(gdb.Command):
"""GDB command to enable the specified frame-filter.
-Usage: enable frame-filter DICTIONARY [NAME]
+ Usage: enable frame-filter DICTIONARY [NAME]
-DICTIONARY is the name of the frame filter dictionary on which to
-operate. If dictionary is set to "all", perform operations on all
-dictionaries. Named dictionaries are: "global" for the global
-frame filter dictionary, "progspace" for the program space's frame
-filter dictionary. If either all, or the two named dictionaries
-are not specified, the dictionary name is assumed to be the name
-of an "objfile" -- a shared library or an executable.
+ DICTIONARY is the name of the frame filter dictionary on which to
+ operate. If dictionary is set to "all", perform operations on all
+ dictionaries. Named dictionaries are: "global" for the global
+ frame filter dictionary, "progspace" for the program space's frame
+ filter dictionary. If either all, or the two named dictionaries
+ are not specified, the dictionary name is assumed to be the name
+ of an "objfile" -- a shared library or an executable.
+
+ NAME matches the name of the frame-filter to operate on."""
-NAME matches the name of the frame-filter to operate on."""
def __init__(self):
- super(EnableFrameFilter, self).__init__("enable frame-filter",
- gdb.COMMAND_DATA)
+ super(EnableFrameFilter, self).__init__("enable frame-filter", gdb.COMMAND_DATA)
+
def complete(self, text, word):
"""Completion function for both frame filter dictionary, and
frame filter name."""
@@ -241,20 +259,22 @@ NAME matches the name of the frame-filter to operate on."""
class DisableFrameFilter(gdb.Command):
"""GDB command to disable the specified frame-filter.
-Usage: disable frame-filter DICTIONARY [NAME]
+ Usage: disable frame-filter DICTIONARY [NAME]
-DICTIONARY is the name of the frame filter dictionary on which to
-operate. If dictionary is set to "all", perform operations on all
-dictionaries. Named dictionaries are: "global" for the global
-frame filter dictionary, "progspace" for the program space's frame
-filter dictionary. If either all, or the two named dictionaries
-are not specified, the dictionary name is assumed to be the name
-of an "objfile" -- a shared library or an executable.
+ DICTIONARY is the name of the frame filter dictionary on which to
+ operate. If dictionary is set to "all", perform operations on all
+ dictionaries. Named dictionaries are: "global" for the global
+ frame filter dictionary, "progspace" for the program space's frame
+ filter dictionary. If either all, or the two named dictionaries
+ are not specified, the dictionary name is assumed to be the name
+ of an "objfile" -- a shared library or an executable.
+
+ NAME matches the name of the frame-filter to operate on."""
-NAME matches the name of the frame-filter to operate on."""
def __init__(self):
- super(DisableFrameFilter, self).__init__("disable frame-filter",
- gdb.COMMAND_DATA)
+ super(DisableFrameFilter, self).__init__(
+ "disable frame-filter", gdb.COMMAND_DATA
+ )
def complete(self, text, word):
"""Completion function for both frame filter dictionary, and
@@ -269,27 +289,28 @@ NAME matches the name of the frame-filter to operate on."""
command_tuple = _enable_parse_arg("disable frame-filter", arg)
_do_enable_frame_filter(command_tuple, False)
+
class SetFrameFilterPriority(gdb.Command):
"""GDB command to set the priority of the specified frame-filter.
-Usage: set frame-filter priority DICTIONARY NAME PRIORITY
+ Usage: set frame-filter priority DICTIONARY NAME PRIORITY
-DICTIONARY is the name of the frame filter dictionary on which to
-operate. Named dictionaries are: "global" for the global frame
-filter dictionary, "progspace" for the program space's framefilter
-dictionary. If either of these two are not specified, the
-dictionary name is assumed to be the name of an "objfile" -- a
-shared library or an executable.
+ DICTIONARY is the name of the frame filter dictionary on which to
+ operate. Named dictionaries are: "global" for the global frame
+ filter dictionary, "progspace" for the program space's framefilter
+ dictionary. If either of these two are not specified, the
+ dictionary name is assumed to be the name of an "objfile" -- a
+ shared library or an executable.
-NAME matches the name of the frame filter to operate on.
+ NAME matches the name of the frame filter to operate on.
-PRIORITY is the an integer to assign the new priority to the frame
-filter."""
+ PRIORITY is the an integer to assign the new priority to the frame
+ filter."""
def __init__(self):
- super(SetFrameFilterPriority, self).__init__("set frame-filter " \
- "priority",
- gdb.COMMAND_DATA)
+ super(SetFrameFilterPriority, self).__init__(
+ "set frame-filter " "priority", gdb.COMMAND_DATA
+ )
def _parse_pri_arg(self, arg):
"""Internal worker to parse a priority from a tuple.
@@ -305,11 +326,10 @@ filter."""
gdb.GdbError: An error parsing the arguments.
"""
- argv = gdb.string_to_argv(arg);
+ argv = gdb.string_to_argv(arg)
argc = len(argv)
if argc != 3:
- print("set frame-filter priority " \
- "takes exactly three arguments.")
+ print("set frame-filter priority " "takes exactly three arguments.")
return None
return argv
@@ -355,24 +375,25 @@ filter."""
if command_tuple != None:
self._set_filter_priority(command_tuple)
+
class ShowFrameFilterPriority(gdb.Command):
"""GDB command to show the priority of the specified frame-filter.
-Usage: show frame-filter priority DICTIONARY NAME
+ Usage: show frame-filter priority DICTIONARY NAME
-DICTIONARY is the name of the frame filter dictionary on which to
-operate. Named dictionaries are: "global" for the global frame
-filter dictionary, "progspace" for the program space's framefilter
-dictionary. If either of these two are not specified, the
-dictionary name is assumed to be the name of an "objfile" -- a
-shared library or an executable.
+ DICTIONARY is the name of the frame filter dictionary on which to
+ operate. Named dictionaries are: "global" for the global frame
+ filter dictionary, "progspace" for the program space's framefilter
+ dictionary. If either of these two are not specified, the
+ dictionary name is assumed to be the name of an "objfile" -- a
+ shared library or an executable.
-NAME matches the name of the frame-filter to operate on."""
+ NAME matches the name of the frame-filter to operate on."""
def __init__(self):
- super(ShowFrameFilterPriority, self).__init__("show frame-filter " \
- "priority",
- gdb.COMMAND_DATA)
+ super(ShowFrameFilterPriority, self).__init__(
+ "show frame-filter " "priority", gdb.COMMAND_DATA
+ )
def _parse_pri_arg(self, arg):
"""Internal worker to parse a dictionary and name from a
@@ -388,11 +409,10 @@ NAME matches the name of the frame-filter to operate on."""
gdb.GdbError: An error parsing the arguments.
"""
- argv = gdb.string_to_argv(arg);
+ argv = gdb.string_to_argv(arg)
argc = len(argv)
if argc != 2:
- print("show frame-filter priority " \
- "takes exactly two arguments.")
+ print("show frame-filter priority " "takes exactly two arguments.")
return None
return argv
@@ -438,13 +458,20 @@ NAME matches the name of the frame-filter to operate on."""
filter_name = command_tuple[1]
list_name = command_tuple[0]
try:
- priority = self.get_filter_priority(list_name, filter_name);
+ priority = self.get_filter_priority(list_name, filter_name)
except Exception:
e = sys.exc_info()[1]
- print("Error printing filter priority for '"+name+"':"+str(e))
+ print("Error printing filter priority for '" + name + "':" + str(e))
else:
- print("Priority of filter '" + filter_name + "' in list '" \
- + list_name + "' is: " + str(priority))
+ print(
+ "Priority of filter '"
+ + filter_name
+ + "' in list '"
+ + list_name
+ + "' is: "
+ + str(priority)
+ )
+
# Register commands
SetFilterPrefixCmd()
diff --git a/gdb/python/lib/gdb/command/pretty_printers.py b/gdb/python/lib/gdb/command/pretty_printers.py
index 57953236c93..9d579bcf0bd 100644
--- a/gdb/python/lib/gdb/command/pretty_printers.py
+++ b/gdb/python/lib/gdb/command/pretty_printers.py
@@ -38,7 +38,7 @@ def parse_printer_regexps(arg):
SyntaxError: an error processing ARG
"""
- argv = gdb.string_to_argv(arg);
+ argv = gdb.string_to_argv(arg)
argc = len(argv)
object_regexp = "" # match everything
name_regexp = "" # match everything
@@ -60,7 +60,7 @@ def parse_printer_regexps(arg):
except SyntaxError:
raise SyntaxError("invalid object regexp: %s" % object_regexp)
try:
- name_re = re.compile (name_regexp)
+ name_re = re.compile(name_regexp)
except SyntaxError:
raise SyntaxError("invalid name regexp: %s" % name_regexp)
if subname_regexp is not None:
@@ -70,7 +70,7 @@ def parse_printer_regexps(arg):
raise SyntaxError("invalid subname regexp: %s" % subname_regexp)
else:
subname_re = None
- return(object_re, name_re, subname_re)
+ return (object_re, name_re, subname_re)
def printer_enabled_p(printer):
@@ -84,19 +84,18 @@ def printer_enabled_p(printer):
class InfoPrettyPrinter(gdb.Command):
"""GDB command to list all registered pretty-printers.
-Usage: info pretty-printer [OBJECT-REGEXP [NAME-REGEXP]]
+ Usage: info pretty-printer [OBJECT-REGEXP [NAME-REGEXP]]
-OBJECT-REGEXP is a regular expression matching the objects to list.
-Objects are "global", the program space's file, and the objfiles within
-that program space.
+ OBJECT-REGEXP is a regular expression matching the objects to list.
+ Objects are "global", the program space's file, and the objfiles within
+ that program space.
-NAME-REGEXP matches the name of the pretty-printer.
-Individual printers in a collection are named as
-printer-name;subprinter-name."""
+ NAME-REGEXP matches the name of the pretty-printer.
+ Individual printers in a collection are named as
+ printer-name;subprinter-name."""
- def __init__ (self):
- super(InfoPrettyPrinter, self).__init__("info pretty-printer",
- gdb.COMMAND_DATA)
+ def __init__(self):
+ super(InfoPrettyPrinter, self).__init__("info pretty-printer", gdb.COMMAND_DATA)
@staticmethod
def enabled_string(printer):
@@ -123,44 +122,62 @@ printer-name;subprinter-name."""
"""Print a list of pretty-printers."""
# A potential enhancement is to provide an option to list printers in
# "lookup order" (i.e. unsorted).
- sorted_pretty_printers = sorted (copy.copy(pretty_printers),
- key = self.printer_name)
+ sorted_pretty_printers = sorted(
+ copy.copy(pretty_printers), key=self.printer_name
+ )
for printer in sorted_pretty_printers:
name = self.printer_name(printer)
enabled = self.enabled_string(printer)
if name_re.match(name):
- print (" %s%s" % (name, enabled))
- if (hasattr(printer, "subprinters") and
- printer.subprinters is not None):
- sorted_subprinters = sorted (copy.copy(printer.subprinters),
- key = self.printer_name)
+ print(" %s%s" % (name, enabled))
+ if hasattr(printer, "subprinters") and printer.subprinters is not None:
+ sorted_subprinters = sorted(
+ copy.copy(printer.subprinters), key=self.printer_name
+ )
for subprinter in sorted_subprinters:
- if (not subname_re or
- subname_re.match(subprinter.name)):
- print (" %s%s" %
- (subprinter.name,
- self.enabled_string(subprinter)))
-
- def invoke1(self, title, printer_list,
- obj_name_to_match, object_re, name_re, subname_re):
+ if not subname_re or subname_re.match(subprinter.name):
+ print(
+ " %s%s"
+ % (subprinter.name, self.enabled_string(subprinter))
+ )
+
+ def invoke1(
+ self, title, printer_list, obj_name_to_match, object_re, name_re, subname_re
+ ):
"""Subroutine of invoke to simplify it."""
if printer_list and object_re.match(obj_name_to_match):
- print (title)
+ print(title)
self.list_pretty_printers(printer_list, name_re, subname_re)
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
(object_re, name_re, subname_re) = parse_printer_regexps(arg)
- self.invoke1("global pretty-printers:", gdb.pretty_printers,
- "global", object_re, name_re, subname_re)
+ self.invoke1(
+ "global pretty-printers:",
+ gdb.pretty_printers,
+ "global",
+ object_re,
+ name_re,
+ subname_re,
+ )
cp = gdb.current_progspace()
- self.invoke1("progspace %s pretty-printers:" % cp.filename,
- cp.pretty_printers, "progspace",
- object_re, name_re, subname_re)
+ self.invoke1(
+ "progspace %s pretty-printers:" % cp.filename,
+ cp.pretty_printers,
+ "progspace",
+ object_re,
+ name_re,
+ subname_re,
+ )
for objfile in gdb.objfiles():
- self.invoke1("objfile %s pretty-printers:" % objfile.filename,
- objfile.pretty_printers, objfile.filename,
- object_re, name_re, subname_re)
+ self.invoke1(
+ "objfile %s pretty-printers:" % objfile.filename,
+ objfile.pretty_printers,
+ objfile.filename,
+ object_re,
+ name_re,
+ subname_re,
+ )
def count_enabled_printers(pretty_printers):
@@ -168,8 +185,7 @@ def count_enabled_printers(pretty_printers):
enabled = 0
total = 0
for printer in pretty_printers:
- if (hasattr(printer, "subprinters")
- and printer.subprinters is not None):
+ if hasattr(printer, "subprinters") and printer.subprinters is not None:
if printer_enabled_p(printer):
for subprinter in printer.subprinters:
if printer_enabled_p(subprinter):
@@ -191,7 +207,9 @@ def count_all_enabled_printers():
(t_enabled, t_total) = count_enabled_printers(gdb.pretty_printers)
enabled_count += t_enabled
total_count += t_total
- (t_enabled, t_total) = count_enabled_printers(gdb.current_progspace().pretty_printers)
+ (t_enabled, t_total) = count_enabled_printers(
+ gdb.current_progspace().pretty_printers
+ )
enabled_count += t_enabled
total_count += t_total
for objfile in gdb.objfiles():
@@ -214,10 +232,10 @@ def show_pretty_printer_enabled_summary():
We count subprinters individually.
"""
(enabled_count, total_count) = count_all_enabled_printers()
- print ("%d of %d printers enabled" % (enabled_count, total_count))
+ print("%d of %d printers enabled" % (enabled_count, total_count))
-def do_enable_pretty_printer_1 (pretty_printers, name_re, subname_re, flag):
+def do_enable_pretty_printer_1(pretty_printers, name_re, subname_re, flag):
"""Worker for enabling/disabling pretty-printers.
Arguments:
@@ -233,10 +251,13 @@ def do_enable_pretty_printer_1 (pretty_printers, name_re, subname_re, flag):
"""
total = 0
for printer in pretty_printers:
- if (hasattr(printer, "name") and name_re.match(printer.name) or
- hasattr(printer, "__name__") and name_re.match(printer.__name__)):
- if (hasattr(printer, "subprinters") and
- printer.subprinters is not None):
+ if (
+ hasattr(printer, "name")
+ and name_re.match(printer.name)
+ or hasattr(printer, "__name__")
+ and name_re.match(printer.__name__)
+ ):
+ if hasattr(printer, "subprinters") and printer.subprinters is not None:
if not subname_re:
# Only record printers that change state.
if printer_enabled_p(printer) != flag:
@@ -252,10 +273,12 @@ def do_enable_pretty_printer_1 (pretty_printers, name_re, subname_re, flag):
for subprinter in printer.subprinters:
if subname_re.match(subprinter.name):
# Only record printers that change state.
- if (printer_enabled_p(printer) and
- printer_enabled_p(subprinter) != flag):
- total += 1
- subprinter.enabled = flag
+ if (
+ printer_enabled_p(printer)
+ and printer_enabled_p(subprinter) != flag
+ ):
+ total += 1
+ subprinter.enabled = flag
else:
# This printer has no subprinters.
# If the user does "disable pretty-printer .* .* foo"
@@ -275,28 +298,31 @@ def do_enable_pretty_printer_1 (pretty_printers, name_re, subname_re, flag):
return total
-def do_enable_pretty_printer (arg, flag):
+def do_enable_pretty_printer(arg, flag):
"""Internal worker for enabling/disabling pretty-printers."""
(object_re, name_re, subname_re) = parse_printer_regexps(arg)
total = 0
if object_re.match("global"):
- total += do_enable_pretty_printer_1(gdb.pretty_printers,
- name_re, subname_re, flag)
+ total += do_enable_pretty_printer_1(
+ gdb.pretty_printers, name_re, subname_re, flag
+ )
cp = gdb.current_progspace()
if object_re.match("progspace"):
- total += do_enable_pretty_printer_1(cp.pretty_printers,
- name_re, subname_re, flag)
+ total += do_enable_pretty_printer_1(
+ cp.pretty_printers, name_re, subname_re, flag
+ )
for objfile in gdb.objfiles():
if object_re.match(objfile.filename):
- total += do_enable_pretty_printer_1(objfile.pretty_printers,
- name_re, subname_re, flag)
+ total += do_enable_pretty_printer_1(
+ objfile.pretty_printers, name_re, subname_re, flag
+ )
if flag:
state = "enabled"
else:
state = "disabled"
- print ("%d %s %s" % (total, pluralize("printer", total), state))
+ print("%d %s %s" % (total, pluralize("printer", total), state))
# Print the total list of printers currently enabled/disabled.
# This is to further assist the user in determining whether the result
@@ -312,44 +338,47 @@ def do_enable_pretty_printer (arg, flag):
#
# A useful addition would be -v (verbose) to show each printer affected.
-class EnablePrettyPrinter (gdb.Command):
+
+class EnablePrettyPrinter(gdb.Command):
"""GDB command to enable the specified pretty-printer.
-Usage: enable pretty-printer [OBJECT-REGEXP [NAME-REGEXP]]
+ Usage: enable pretty-printer [OBJECT-REGEXP [NAME-REGEXP]]
-OBJECT-REGEXP is a regular expression matching the objects to examine.
-Objects are "global", the program space's file, and the objfiles within
-that program space.
+ OBJECT-REGEXP is a regular expression matching the objects to examine.
+ Objects are "global", the program space's file, and the objfiles within
+ that program space.
-NAME-REGEXP matches the name of the pretty-printer.
-Individual printers in a collection are named as
-printer-name;subprinter-name."""
+ NAME-REGEXP matches the name of the pretty-printer.
+ Individual printers in a collection are named as
+ printer-name;subprinter-name."""
def __init__(self):
- super(EnablePrettyPrinter, self).__init__("enable pretty-printer",
- gdb.COMMAND_DATA)
+ super(EnablePrettyPrinter, self).__init__(
+ "enable pretty-printer", gdb.COMMAND_DATA
+ )
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
do_enable_pretty_printer(arg, True)
-class DisablePrettyPrinter (gdb.Command):
+class DisablePrettyPrinter(gdb.Command):
"""GDB command to disable the specified pretty-printer.
-Usage: disable pretty-printer [OBJECT-REGEXP [NAME-REGEXP]]
+ Usage: disable pretty-printer [OBJECT-REGEXP [NAME-REGEXP]]
-OBJECT-REGEXP is a regular expression matching the objects to examine.
-Objects are "global", the program space's file, and the objfiles within
-that program space.
+ OBJECT-REGEXP is a regular expression matching the objects to examine.
+ Objects are "global", the program space's file, and the objfiles within
+ that program space.
-NAME-REGEXP matches the name of the pretty-printer.
-Individual printers in a collection are named as
-printer-name;subprinter-name."""
+ NAME-REGEXP matches the name of the pretty-printer.
+ Individual printers in a collection are named as
+ printer-name;subprinter-name."""
def __init__(self):
- super(DisablePrettyPrinter, self).__init__("disable pretty-printer",
- gdb.COMMAND_DATA)
+ super(DisablePrettyPrinter, self).__init__(
+ "disable pretty-printer", gdb.COMMAND_DATA
+ )
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
@@ -362,4 +391,5 @@ def register_pretty_printer_commands():
EnablePrettyPrinter()
DisablePrettyPrinter()
+
register_pretty_printer_commands()
diff --git a/gdb/python/lib/gdb/command/prompt.py b/gdb/python/lib/gdb/command/prompt.py
index 45ac1bc7346..6e105a39973 100644
--- a/gdb/python/lib/gdb/command/prompt.py
+++ b/gdb/python/lib/gdb/command/prompt.py
@@ -19,17 +19,18 @@
import gdb
import gdb.prompt
+
class _ExtendedPrompt(gdb.Parameter):
"""Set the extended prompt.
-Usage: set extended-prompt VALUE
+ Usage: set extended-prompt VALUE
-Substitutions are applied to VALUE to compute the real prompt.
+ Substitutions are applied to VALUE to compute the real prompt.
-The currently defined substitutions are:
+ The currently defined substitutions are:
+ """
-"""
# Add the prompt library's dynamically generated help to the
# __doc__ string.
__doc__ = __doc__ + gdb.prompt.prompt_help()
@@ -38,22 +39,22 @@ The currently defined substitutions are:
show_doc = "Show the extended prompt."
def __init__(self):
- super(_ExtendedPrompt, self).__init__("extended-prompt",
- gdb.COMMAND_SUPPORT,
- gdb.PARAM_STRING_NOESCAPE)
- self.value = ''
+ super(_ExtendedPrompt, self).__init__(
+ "extended-prompt", gdb.COMMAND_SUPPORT, gdb.PARAM_STRING_NOESCAPE
+ )
+ self.value = ""
self.hook_set = False
- def get_show_string (self, pvalue):
+ def get_show_string(self, pvalue):
if self.value:
- return "The extended prompt is: " + self.value
+ return "The extended prompt is: " + self.value
else:
- return "The extended prompt is not set."
+ return "The extended prompt is not set."
- def get_set_string (self):
+ def get_set_string(self):
if self.hook_set == False:
- gdb.prompt_hook = self.before_prompt_hook
- self.hook_set = True
+ gdb.prompt_hook = self.before_prompt_hook
+ self.hook_set = True
return ""
def before_prompt_hook(self, current):
@@ -62,4 +63,5 @@ The currently defined substitutions are:
else:
return None
+
_ExtendedPrompt()
diff --git a/gdb/python/lib/gdb/command/type_printers.py b/gdb/python/lib/gdb/command/type_printers.py
index 84fe8b61f97..560ec04e26b 100644
--- a/gdb/python/lib/gdb/command/type_printers.py
+++ b/gdb/python/lib/gdb/command/type_printers.py
@@ -19,44 +19,44 @@ import gdb
"""GDB commands for working with type-printers."""
+
class InfoTypePrinter(gdb.Command):
"""GDB command to list all registered type-printers.
-Usage: info type-printers"""
+ Usage: info type-printers"""
- def __init__ (self):
- super(InfoTypePrinter, self).__init__("info type-printers",
- gdb.COMMAND_DATA)
+ def __init__(self):
+ super(InfoTypePrinter, self).__init__("info type-printers", gdb.COMMAND_DATA)
def list_type_printers(self, type_printers):
"""Print a list of type printers."""
# A potential enhancement is to provide an option to list printers in
# "lookup order" (i.e. unsorted).
- sorted_type_printers = sorted (copy.copy(type_printers),
- key = lambda x: x.name)
+ sorted_type_printers = sorted(copy.copy(type_printers), key=lambda x: x.name)
for printer in sorted_type_printers:
if printer.enabled:
- enabled = ''
+ enabled = ""
else:
enabled = " [disabled]"
- print (" %s%s" % (printer.name, enabled))
+ print(" %s%s" % (printer.name, enabled))
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
- sep = ''
+ sep = ""
for objfile in gdb.objfiles():
if objfile.type_printers:
- print ("%sType printers for %s:" % (sep, objfile.filename))
+ print("%sType printers for %s:" % (sep, objfile.filename))
self.list_type_printers(objfile.type_printers)
- sep = '\n'
+ sep = "\n"
if gdb.current_progspace().type_printers:
- print ("%sType printers for program space:" % sep)
+ print("%sType printers for program space:" % sep)
self.list_type_printers(gdb.current_progspace().type_printers)
- sep = '\n'
+ sep = "\n"
if gdb.type_printers:
- print ("%sGlobal type printers:" % sep)
+ print("%sGlobal type printers:" % sep)
self.list_type_printers(gdb.type_printers)
+
class _EnableOrDisableCommand(gdb.Command):
def __init__(self, setting, name):
super(_EnableOrDisableCommand, self).__init__(name, gdb.COMMAND_DATA)
@@ -82,7 +82,7 @@ class _EnableOrDisableCommand(gdb.Command):
if self.set_some(name, gdb.type_printers):
ok = True
if not ok:
- print ("No type printer named '%s'" % name)
+ print("No type printer named '%s'" % name)
def add_some(self, result, word, printers):
for p in printers:
@@ -97,26 +97,29 @@ class _EnableOrDisableCommand(gdb.Command):
self.add_some(result, word, gdb.type_printers)
return result
+
class EnableTypePrinter(_EnableOrDisableCommand):
"""GDB command to enable the specified type printer.
-Usage: enable type-printer NAME
+ Usage: enable type-printer NAME
-NAME is the name of the type-printer."""
+ NAME is the name of the type-printer."""
def __init__(self):
super(EnableTypePrinter, self).__init__(True, "enable type-printer")
+
class DisableTypePrinter(_EnableOrDisableCommand):
"""GDB command to disable the specified type-printer.
-Usage: disable type-printer NAME
+ Usage: disable type-printer NAME
-NAME is the name of the type-printer."""
+ NAME is the name of the type-printer."""
def __init__(self):
super(DisableTypePrinter, self).__init__(False, "disable type-printer")
+
InfoTypePrinter()
EnableTypePrinter()
DisableTypePrinter()
diff --git a/gdb/python/lib/gdb/command/unwinders.py b/gdb/python/lib/gdb/command/unwinders.py
index 0af469846dc..59ee67cc7b3 100644
--- a/gdb/python/lib/gdb/command/unwinders.py
+++ b/gdb/python/lib/gdb/command/unwinders.py
@@ -49,28 +49,29 @@ def parse_unwinder_command_args(arg):
locus_regexp = argv[0]
if argc >= 2:
name_regexp = argv[1]
- return (validate_regexp(locus_regexp, "locus"),
- validate_regexp(name_regexp, "unwinder"))
+ return (
+ validate_regexp(locus_regexp, "locus"),
+ validate_regexp(name_regexp, "unwinder"),
+ )
class InfoUnwinder(gdb.Command):
"""GDB command to list unwinders.
-Usage: info unwinder [LOCUS-REGEXP [NAME-REGEXP]]
+ Usage: info unwinder [LOCUS-REGEXP [NAME-REGEXP]]
-LOCUS-REGEXP is a regular expression matching the location of the
-unwinder. If it is omitted, all registered unwinders from all
-loci are listed. A locus can be 'global', 'progspace' to list
-the unwinders from the current progspace, or a regular expression
-matching filenames of objfiles.
+ LOCUS-REGEXP is a regular expression matching the location of the
+ unwinder. If it is omitted, all registered unwinders from all
+ loci are listed. A locus can be 'global', 'progspace' to list
+ the unwinders from the current progspace, or a regular expression
+ matching filenames of objfiles.
-NAME-REGEXP is a regular expression to filter unwinder names. If
-this omitted for a specified locus, then all registered unwinders
-in the locus are listed."""
+ NAME-REGEXP is a regular expression to filter unwinder names. If
+ this omitted for a specified locus, then all registered unwinders
+ in the locus are listed."""
def __init__(self):
- super(InfoUnwinder, self).__init__("info unwinder",
- gdb.COMMAND_STACK)
+ super(InfoUnwinder, self).__init__("info unwinder", gdb.COMMAND_STACK)
def list_unwinders(self, title, unwinders, name_re):
"""Lists the unwinders whose name matches regexp.
@@ -85,22 +86,25 @@ in the locus are listed."""
print(title)
for unwinder in unwinders:
if name_re.match(unwinder.name):
- print(" %s%s" % (unwinder.name,
- "" if unwinder.enabled else " [disabled]"))
+ print(
+ " %s%s"
+ % (unwinder.name, "" if unwinder.enabled else " [disabled]")
+ )
def invoke(self, arg, from_tty):
locus_re, name_re = parse_unwinder_command_args(arg)
if locus_re.match("global"):
- self.list_unwinders("Global:", gdb.frame_unwinders,
- name_re)
+ self.list_unwinders("Global:", gdb.frame_unwinders, name_re)
if locus_re.match("progspace"):
cp = gdb.current_progspace()
- self.list_unwinders("Progspace %s:" % cp.filename,
- cp.frame_unwinders, name_re)
+ self.list_unwinders(
+ "Progspace %s:" % cp.filename, cp.frame_unwinders, name_re
+ )
for objfile in gdb.objfiles():
if locus_re.match(objfile.filename):
- self.list_unwinders("Objfile %s:" % objfile.filename,
- objfile.frame_unwinders, name_re)
+ self.list_unwinders(
+ "Objfile %s:" % objfile.filename, objfile.frame_unwinders, name_re
+ )
def do_enable_unwinder1(unwinders, name_re, flag):
@@ -129,34 +133,35 @@ def do_enable_unwinder(arg, flag):
if locus_re.match("global"):
total += do_enable_unwinder1(gdb.frame_unwinders, name_re, flag)
if locus_re.match("progspace"):
- total += do_enable_unwinder1(gdb.current_progspace().frame_unwinders,
- name_re, flag)
+ total += do_enable_unwinder1(
+ gdb.current_progspace().frame_unwinders, name_re, flag
+ )
for objfile in gdb.objfiles():
if locus_re.match(objfile.filename):
- total += do_enable_unwinder1(objfile.frame_unwinders, name_re,
- flag)
+ total += do_enable_unwinder1(objfile.frame_unwinders, name_re, flag)
if total > 0:
gdb.invalidate_cached_frames()
- print("%d unwinder%s %s" % (total, "" if total == 1 else "s",
- "enabled" if flag else "disabled"))
+ print(
+ "%d unwinder%s %s"
+ % (total, "" if total == 1 else "s", "enabled" if flag else "disabled")
+ )
class EnableUnwinder(gdb.Command):
"""GDB command to enable unwinders.
-Usage: enable unwinder [LOCUS-REGEXP [NAME-REGEXP]]
+ Usage: enable unwinder [LOCUS-REGEXP [NAME-REGEXP]]
-LOCUS-REGEXP is a regular expression specifying the unwinders to
-enable. It can 'global', 'progspace', or the name of an objfile
-within that progspace.
+ LOCUS-REGEXP is a regular expression specifying the unwinders to
+ enable. It can 'global', 'progspace', or the name of an objfile
+ within that progspace.
-NAME_REGEXP is a regular expression to filter unwinder names. If
-this omitted for a specified locus, then all registered unwinders
-in the locus are affected."""
+ NAME_REGEXP is a regular expression to filter unwinder names. If
+ this omitted for a specified locus, then all registered unwinders
+ in the locus are affected."""
def __init__(self):
- super(EnableUnwinder, self).__init__("enable unwinder",
- gdb.COMMAND_STACK)
+ super(EnableUnwinder, self).__init__("enable unwinder", gdb.COMMAND_STACK)
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
@@ -166,19 +171,18 @@ in the locus are affected."""
class DisableUnwinder(gdb.Command):
"""GDB command to disable the specified unwinder.
-Usage: disable unwinder [LOCUS-REGEXP [NAME-REGEXP]]
+ Usage: disable unwinder [LOCUS-REGEXP [NAME-REGEXP]]
-LOCUS-REGEXP is a regular expression specifying the unwinders to
-disable. It can 'global', 'progspace', or the name of an objfile
-within that progspace.
+ LOCUS-REGEXP is a regular expression specifying the unwinders to
+ disable. It can 'global', 'progspace', or the name of an objfile
+ within that progspace.
-NAME_REGEXP is a regular expression to filter unwinder names. If
-this omitted for a specified locus, then all registered unwinders
-in the locus are affected."""
+ NAME_REGEXP is a regular expression to filter unwinder names. If
+ this omitted for a specified locus, then all registered unwinders
+ in the locus are affected."""
def __init__(self):
- super(DisableUnwinder, self).__init__("disable unwinder",
- gdb.COMMAND_STACK)
+ super(DisableUnwinder, self).__init__("disable unwinder", gdb.COMMAND_STACK)
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
diff --git a/gdb/python/lib/gdb/command/xmethods.py b/gdb/python/lib/gdb/command/xmethods.py
index b8ac4cac0f1..cda234f9ce1 100644
--- a/gdb/python/lib/gdb/command/xmethods.py
+++ b/gdb/python/lib/gdb/command/xmethods.py
@@ -56,9 +56,11 @@ def parse_xm_command_args(arg):
name_re = validate_xm_regexp("xmethod name", xm_name_regexp)
else:
name_re = None
- return (validate_xm_regexp("locus", locus_regexp),
- validate_xm_regexp("matcher name", matcher_name_regexp),
- name_re)
+ return (
+ validate_xm_regexp("locus", locus_regexp),
+ validate_xm_regexp("matcher name", matcher_name_regexp),
+ name_re,
+ )
def get_global_method_matchers(locus_re, matcher_re):
@@ -75,10 +77,9 @@ def get_global_method_matchers(locus_re, matcher_re):
key in the dict will be 'global'.
"""
locus_str = "global"
- xm_dict = { locus_str: [] }
+ xm_dict = {locus_str: []}
if locus_re.match("global"):
- xm_dict[locus_str].extend(
- [m for m in gdb.xmethods if matcher_re.match(m.name)])
+ xm_dict[locus_str].extend([m for m in gdb.xmethods if matcher_re.match(m.name)])
return xm_dict
@@ -102,7 +103,7 @@ def get_method_matchers_in_loci(loci, locus_re, matcher_re):
xm_dict = {}
for locus in loci:
if isinstance(locus, gdb.Progspace):
- if not locus_re.match('progspace'):
+ if not locus_re.match("progspace"):
continue
locus_type = "progspace"
else:
@@ -110,32 +111,32 @@ def get_method_matchers_in_loci(loci, locus_re, matcher_re):
continue
locus_type = "objfile"
locus_str = "%s %s" % (locus_type, locus.filename)
- xm_dict[locus_str] = [
- m for m in locus.xmethods if matcher_re.match(m.name)]
+ xm_dict[locus_str] = [m for m in locus.xmethods if matcher_re.match(m.name)]
return xm_dict
def print_xm_info(xm_dict, name_re):
"""Print a dictionary of xmethods."""
+
def get_status_string(m):
if not m.enabled:
return " [disabled]"
else:
- return ""
+ return ""
if not xm_dict:
return
for locus_str in xm_dict:
if not xm_dict[locus_str]:
continue
- print ("Xmethods in %s:" % locus_str)
+ print("Xmethods in %s:" % locus_str)
for matcher in xm_dict[locus_str]:
- print (" %s%s" % (matcher.name, get_status_string(matcher)))
+ print(" %s%s" % (matcher.name, get_status_string(matcher)))
if not matcher.methods:
continue
for m in matcher.methods:
if name_re is None or name_re.match(m.name):
- print (" %s%s" % (m.name, get_status_string(m)))
+ print(" %s%s" % (m.name, get_status_string(m)))
def set_xm_status1(xm_dict, name_re, status):
@@ -161,75 +162,74 @@ def set_xm_status(arg, status):
argument string passed to the commands.
"""
locus_re, matcher_re, name_re = parse_xm_command_args(arg)
- set_xm_status1(get_global_method_matchers(locus_re, matcher_re), name_re,
- status)
+ set_xm_status1(get_global_method_matchers(locus_re, matcher_re), name_re, status)
set_xm_status1(
- get_method_matchers_in_loci(
- [gdb.current_progspace()], locus_re, matcher_re),
+ get_method_matchers_in_loci([gdb.current_progspace()], locus_re, matcher_re),
name_re,
- status)
+ status,
+ )
set_xm_status1(
get_method_matchers_in_loci(gdb.objfiles(), locus_re, matcher_re),
name_re,
- status)
+ status,
+ )
class InfoXMethod(gdb.Command):
"""GDB command to list registered xmethod matchers.
-Usage: info xmethod [LOCUS-REGEXP [NAME-REGEXP]]
+ Usage: info xmethod [LOCUS-REGEXP [NAME-REGEXP]]
-LOCUS-REGEXP is a regular expression matching the location of the
-xmethod matchers. If it is omitted, all registered xmethod matchers
-from all loci are listed. A locus could be 'global', a regular expression
-matching the current program space's filename, or a regular expression
-matching filenames of objfiles. Locus could be 'progspace' to specify that
-only xmethods from the current progspace should be listed.
+ LOCUS-REGEXP is a regular expression matching the location of the
+ xmethod matchers. If it is omitted, all registered xmethod matchers
+ from all loci are listed. A locus could be 'global', a regular expression
+ matching the current program space's filename, or a regular expression
+ matching filenames of objfiles. Locus could be 'progspace' to specify that
+ only xmethods from the current progspace should be listed.
-NAME-REGEXP is a regular expression matching the names of xmethod
-matchers. If this omitted for a specified locus, then all registered
-xmethods in the locus are listed. To list only a certain xmethods
-managed by a single matcher, the name regexp can be specified as
-matcher-name-regexp;xmethod-name-regexp."""
+ NAME-REGEXP is a regular expression matching the names of xmethod
+ matchers. If this omitted for a specified locus, then all registered
+ xmethods in the locus are listed. To list only a certain xmethods
+ managed by a single matcher, the name regexp can be specified as
+ matcher-name-regexp;xmethod-name-regexp."""
def __init__(self):
- super(InfoXMethod, self).__init__("info xmethod",
- gdb.COMMAND_DATA)
+ super(InfoXMethod, self).__init__("info xmethod", gdb.COMMAND_DATA)
def invoke(self, arg, from_tty):
locus_re, matcher_re, name_re = parse_xm_command_args(arg)
- print_xm_info(get_global_method_matchers(locus_re, matcher_re),
- name_re)
+ print_xm_info(get_global_method_matchers(locus_re, matcher_re), name_re)
print_xm_info(
get_method_matchers_in_loci(
- [gdb.current_progspace()], locus_re, matcher_re),
- name_re)
+ [gdb.current_progspace()], locus_re, matcher_re
+ ),
+ name_re,
+ )
print_xm_info(
- get_method_matchers_in_loci(gdb.objfiles(), locus_re, matcher_re),
- name_re)
+ get_method_matchers_in_loci(gdb.objfiles(), locus_re, matcher_re), name_re
+ )
class EnableXMethod(gdb.Command):
"""GDB command to enable a specified (group of) xmethod(s).
-Usage: enable xmethod [LOCUS-REGEXP [NAME-REGEXP]]
+ Usage: enable xmethod [LOCUS-REGEXP [NAME-REGEXP]]
-LOCUS-REGEXP is a regular expression matching the location of the
-xmethod matchers. If it is omitted, all registered xmethods matchers
-from all loci are enabled. A locus could be 'global', a regular expression
-matching the current program space's filename, or a regular expression
-matching filenames of objfiles. Locus could be 'progspace' to specify that
-only xmethods from the current progspace should be enabled.
+ LOCUS-REGEXP is a regular expression matching the location of the
+ xmethod matchers. If it is omitted, all registered xmethods matchers
+ from all loci are enabled. A locus could be 'global', a regular expression
+ matching the current program space's filename, or a regular expression
+ matching filenames of objfiles. Locus could be 'progspace' to specify that
+ only xmethods from the current progspace should be enabled.
-NAME-REGEXP is a regular expression matching the names of xmethods
-within a given locus. If this omitted for a specified locus, then all
-registered xmethod matchers in the locus are enabled. To enable only
-a certain xmethods managed by a single matcher, the name regexp can be
-specified as matcher-name-regexp;xmethod-name-regexp."""
+ NAME-REGEXP is a regular expression matching the names of xmethods
+ within a given locus. If this omitted for a specified locus, then all
+ registered xmethod matchers in the locus are enabled. To enable only
+ a certain xmethods managed by a single matcher, the name regexp can be
+ specified as matcher-name-regexp;xmethod-name-regexp."""
def __init__(self):
- super(EnableXMethod, self).__init__("enable xmethod",
- gdb.COMMAND_DATA)
+ super(EnableXMethod, self).__init__("enable xmethod", gdb.COMMAND_DATA)
def invoke(self, arg, from_tty):
set_xm_status(arg, True)
@@ -238,24 +238,23 @@ specified as matcher-name-regexp;xmethod-name-regexp."""
class DisableXMethod(gdb.Command):
"""GDB command to disable a specified (group of) xmethod(s).
-Usage: disable xmethod [LOCUS-REGEXP [NAME-REGEXP]]
+ Usage: disable xmethod [LOCUS-REGEXP [NAME-REGEXP]]
-LOCUS-REGEXP is a regular expression matching the location of the
-xmethod matchers. If it is omitted, all registered xmethod matchers
-from all loci are disabled. A locus could be 'global', a regular
-expression matching the current program space's filename, or a regular
-expression filenames of objfiles. Locus could be 'progspace' to specify
-that only xmethods from the current progspace should be disabled.
+ LOCUS-REGEXP is a regular expression matching the location of the
+ xmethod matchers. If it is omitted, all registered xmethod matchers
+ from all loci are disabled. A locus could be 'global', a regular
+ expression matching the current program space's filename, or a regular
+ expression filenames of objfiles. Locus could be 'progspace' to specify
+ that only xmethods from the current progspace should be disabled.
-NAME-REGEXP is a regular expression matching the names of xmethods
-within a given locus. If this omitted for a specified locus, then all
-registered xmethod matchers in the locus are disabled. To disable
-only a certain xmethods managed by a single matcher, the name regexp
-can be specified as matcher-name-regexp;xmethod-name-regexp."""
+ NAME-REGEXP is a regular expression matching the names of xmethods
+ within a given locus. If this omitted for a specified locus, then all
+ registered xmethod matchers in the locus are disabled. To disable
+ only a certain xmethods managed by a single matcher, the name regexp
+ can be specified as matcher-name-regexp;xmethod-name-regexp."""
def __init__(self):
- super(DisableXMethod, self).__init__("disable xmethod",
- gdb.COMMAND_DATA)
+ super(DisableXMethod, self).__init__("disable xmethod", gdb.COMMAND_DATA)
def invoke(self, arg, from_tty):
set_xm_status(arg, False)
diff --git a/gdb/python/lib/gdb/frames.py b/gdb/python/lib/gdb/frames.py
index 40a5c343cb7..a9397a881fe 100644
--- a/gdb/python/lib/gdb/frames.py
+++ b/gdb/python/lib/gdb/frames.py
@@ -22,8 +22,9 @@ from gdb.FrameDecorator import FrameDecorator
import itertools
import collections
+
def get_priority(filter_item):
- """ Internal worker function to return the frame-filter's priority
+ """Internal worker function to return the frame-filter's priority
from a frame filter object. This is a fail free function as it is
used in sorting and filtering. If a badly implemented frame
filter does not implement the priority attribute, return zero
@@ -42,8 +43,9 @@ def get_priority(filter_item):
# (incorrectly) set a priority, set it to zero.
return getattr(filter_item, "priority", 0)
+
def set_priority(filter_item, priority):
- """ Internal worker function to set the frame-filter's priority.
+ """Internal worker function to set the frame-filter's priority.
Arguments:
filter_item: An object conforming to the frame filter
@@ -53,8 +55,9 @@ def set_priority(filter_item, priority):
filter_item.priority = priority
+
def get_enabled(filter_item):
- """ Internal worker function to return a filter's enabled state
+ """Internal worker function to return a filter's enabled state
from a frame filter object. This is a fail free function as it is
used in sorting and filtering. If a badly implemented frame
filter does not implement the enabled attribute, return False
@@ -75,8 +78,9 @@ def get_enabled(filter_item):
# enabled to False.
return getattr(filter_item, "enabled", False)
+
def set_enabled(filter_item, state):
- """ Internal Worker function to set the frame-filter's enabled
+ """Internal Worker function to set the frame-filter's enabled
state.
Arguments:
@@ -87,8 +91,9 @@ def set_enabled(filter_item, state):
filter_item.enabled = state
+
def return_list(name):
- """ Internal Worker function to return the frame filter
+ """Internal Worker function to return the frame filter
dictionary, depending on the name supplied as an argument. If the
name is not "all", "global" or "progspace", it is assumed to name
an object-file.
@@ -132,8 +137,9 @@ def return_list(name):
msg = "Cannot find frame-filter dictionary for '" + name + "'"
raise gdb.GdbError(msg)
+
def _sort_list():
- """ Internal Worker function to merge all known frame-filter
+ """Internal Worker function to merge all known frame-filter
lists, prune any filters with the state set to "disabled", and
sort the list on the frame-filter's "priority" attribute.
@@ -143,16 +149,15 @@ def _sort_list():
"""
all_filters = return_list("all")
- sorted_frame_filters = sorted(all_filters, key = get_priority,
- reverse = True)
+ sorted_frame_filters = sorted(all_filters, key=get_priority, reverse=True)
- sorted_frame_filters = filter(get_enabled,
- sorted_frame_filters)
+ sorted_frame_filters = filter(get_enabled, sorted_frame_filters)
return sorted_frame_filters
+
def execute_frame_filters(frame, frame_low, frame_high):
- """ Internal function called from GDB that will execute the chain
+ """Internal function called from GDB that will execute the chain
of frame filters. Each filter is executed in priority order.
After the execution completes, slice the iterator to frame_low -
frame_high range.
@@ -187,7 +192,7 @@ def execute_frame_filters(frame, frame_low, frame_high):
# Apply a basic frame decorator to all gdb.Frames. This unifies
# the interface. Python 3.x moved the itertools.imap
# functionality to map(), so check if it is available.
- if hasattr(itertools,"imap"):
+ if hasattr(itertools, "imap"):
frame_iterator = itertools.imap(FrameDecorator, frame_iterator)
else:
frame_iterator = map(FrameDecorator, frame_iterator)
@@ -207,7 +212,7 @@ def execute_frame_filters(frame, frame_low, frame_high):
for frame_item in frame_iterator:
if count >= slice_length:
- sliced.popleft();
+ sliced.popleft()
count = count + 1
sliced.append(frame_item)
@@ -221,7 +226,7 @@ def execute_frame_filters(frame, frame_low, frame_high):
else:
# As frames start from 0, add one to frame_high so islice
# correctly finds the end
- frame_high = frame_high + 1;
+ frame_high = frame_high + 1
sliced = itertools.islice(frame_iterator, frame_low, frame_high)
diff --git a/gdb/python/lib/gdb/function/as_string.py b/gdb/python/lib/gdb/function/as_string.py
index 68396a5d687..b0a996ee799 100644
--- a/gdb/python/lib/gdb/function/as_string.py
+++ b/gdb/python/lib/gdb/function/as_string.py
@@ -19,14 +19,14 @@ import gdb
class _AsString(gdb.Function):
"""Return the string representation of a value.
-Usage: $_as_string (VALUE)
+ Usage: $_as_string (VALUE)
-Arguments:
+ Arguments:
- VALUE: any value
+ VALUE: any value
-Returns:
- The string representation of the value."""
+ Returns:
+ The string representation of the value."""
def __init__(self):
super(_AsString, self).__init__("_as_string")
@@ -34,4 +34,5 @@ Returns:
def invoke(self, val):
return str(val)
+
_AsString()
diff --git a/gdb/python/lib/gdb/function/caller_is.py b/gdb/python/lib/gdb/function/caller_is.py
index 3f7625890b2..922e2f4b6aa 100644
--- a/gdb/python/lib/gdb/function/caller_is.py
+++ b/gdb/python/lib/gdb/function/caller_is.py
@@ -17,27 +17,28 @@
import gdb
import re
+
class CallerIs(gdb.Function):
"""Check the calling function's name.
-Usage: $_caller_is (NAME [, NUMBER-OF-FRAMES])
+ Usage: $_caller_is (NAME [, NUMBER-OF-FRAMES])
-Arguments:
+ Arguments:
- NAME: The name of the function to search for.
+ NAME: The name of the function to search for.
- NUMBER-OF-FRAMES: How many stack frames to traverse back from the currently
- selected frame to compare with. If the value is greater than the depth of
- the stack from that point then the result is False.
- The default is 1.
+ NUMBER-OF-FRAMES: How many stack frames to traverse back from the currently
+ selected frame to compare with. If the value is greater than the depth of
+ the stack from that point then the result is False.
+ The default is 1.
-Returns:
- True if the function's name at the specified frame is equal to NAME."""
+ Returns:
+ True if the function's name at the specified frame is equal to NAME."""
def __init__(self):
super(CallerIs, self).__init__("_caller_is")
- def invoke(self, name, nframes = 1):
+ def invoke(self, name, nframes=1):
if nframes < 0:
raise ValueError("nframes must be >= 0")
frame = gdb.selected_frame()
@@ -48,27 +49,28 @@ Returns:
nframes = nframes - 1
return frame.name() == name.string()
+
class CallerMatches(gdb.Function):
"""Compare the calling function's name with a regexp.
-Usage: $_caller_matches (REGEX [, NUMBER-OF-FRAMES])
+ Usage: $_caller_matches (REGEX [, NUMBER-OF-FRAMES])
-Arguments:
+ Arguments:
- REGEX: The regular expression to compare the function's name with.
+ REGEX: The regular expression to compare the function's name with.
- NUMBER-OF-FRAMES: How many stack frames to traverse back from the currently
- selected frame to compare with. If the value is greater than the depth of
- the stack from that point then the result is False.
- The default is 1.
+ NUMBER-OF-FRAMES: How many stack frames to traverse back from the currently
+ selected frame to compare with. If the value is greater than the depth of
+ the stack from that point then the result is False.
+ The default is 1.
-Returns:
- True if the function's name at the specified frame matches REGEX."""
+ Returns:
+ True if the function's name at the specified frame matches REGEX."""
def __init__(self):
super(CallerMatches, self).__init__("_caller_matches")
- def invoke(self, name, nframes = 1):
+ def invoke(self, name, nframes=1):
if nframes < 0:
raise ValueError("nframes must be >= 0")
frame = gdb.selected_frame()
@@ -79,60 +81,62 @@ Returns:
nframes = nframes - 1
return re.match(name.string(), frame.name()) is not None
+
class AnyCallerIs(gdb.Function):
"""Check all calling function's names.
-Usage: $_any_caller_is (NAME [, NUMBER-OF-FRAMES])
+ Usage: $_any_caller_is (NAME [, NUMBER-OF-FRAMES])
-Arguments:
+ Arguments:
- NAME: The name of the function to search for.
+ NAME: The name of the function to search for.
- NUMBER-OF-FRAMES: How many stack frames to traverse back from the currently
- selected frame to compare with. If the value is greater than the depth of
- the stack from that point then the result is False.
- The default is 1.
+ NUMBER-OF-FRAMES: How many stack frames to traverse back from the currently
+ selected frame to compare with. If the value is greater than the depth of
+ the stack from that point then the result is False.
+ The default is 1.
-Returns:
- True if any function's name is equal to NAME."""
+ Returns:
+ True if any function's name is equal to NAME."""
def __init__(self):
super(AnyCallerIs, self).__init__("_any_caller_is")
- def invoke(self, name, nframes = 1):
+ def invoke(self, name, nframes=1):
if nframes < 0:
raise ValueError("nframes must be >= 0")
frame = gdb.selected_frame()
while nframes >= 0:
if frame.name() == name.string():
- return True
+ return True
frame = frame.older()
if frame is None:
return False
nframes = nframes - 1
return False
+
class AnyCallerMatches(gdb.Function):
"""Compare all calling function's names with a regexp.
-Usage: $_any_caller_matches (REGEX [, NUMBER-OF-FRAMES])
+ Usage: $_any_caller_matches (REGEX [, NUMBER-OF-FRAMES])
-Arguments:
+ Arguments:
- REGEX: The regular expression to compare the function's name with.
+ REGEX: The regular expression to compare the function's name with.
- NUMBER-OF-FRAMES: How many stack frames to traverse back from the currently
- selected frame to compare with. If the value is greater than the depth of
- the stack from that point then the result is False.
- The default is 1.
+ NUMBER-OF-FRAMES: How many stack frames to traverse back from the currently
+ selected frame to compare with. If the value is greater than the depth of
+ the stack from that point then the result is False.
+ The default is 1.
-Returns:
- True if any function's name matches REGEX."""
+ Returns:
+ True if any function's name matches REGEX."""
def __init__(self):
super(AnyCallerMatches, self).__init__("_any_caller_matches")
- def invoke(self, name, nframes = 1):
+ def invoke(self, name, nframes=1):
if nframes < 0:
raise ValueError("nframes must be >= 0")
frame = gdb.selected_frame()
@@ -146,6 +150,7 @@ Returns:
nframes = nframes - 1
return False
+
CallerIs()
CallerMatches()
AnyCallerIs()
diff --git a/gdb/python/lib/gdb/function/strfns.py b/gdb/python/lib/gdb/function/strfns.py
index 8ffc111195f..596f4d1bfc7 100644
--- a/gdb/python/lib/gdb/function/strfns.py
+++ b/gdb/python/lib/gdb/function/strfns.py
@@ -21,76 +21,80 @@ import re
class _MemEq(gdb.Function):
- """$_memeq - compare bytes of memory.
+ """$_memeq - compare bytes of memory.
-Usage: $_memeq (A, B, LEN)
+ Usage: $_memeq (A, B, LEN)
-Returns:
- True if LEN bytes at A and B compare equally."""
- def __init__(self):
- super(_MemEq, self).__init__("_memeq")
+ Returns:
+ True if LEN bytes at A and B compare equally."""
- def invoke(self, a, b, length):
- if length < 0:
- raise ValueError("length must be non-negative")
- if length == 0:
- return True
- # The argument(s) to vector are [low_bound,]high_bound.
- byte_vector = gdb.lookup_type("char").vector(length - 1)
- ptr_byte_vector = byte_vector.pointer()
- a_ptr = a.reinterpret_cast(ptr_byte_vector)
- b_ptr = b.reinterpret_cast(ptr_byte_vector)
- return a_ptr.dereference() == b_ptr.dereference()
+ def __init__(self):
+ super(_MemEq, self).__init__("_memeq")
+
+ def invoke(self, a, b, length):
+ if length < 0:
+ raise ValueError("length must be non-negative")
+ if length == 0:
+ return True
+ # The argument(s) to vector are [low_bound,]high_bound.
+ byte_vector = gdb.lookup_type("char").vector(length - 1)
+ ptr_byte_vector = byte_vector.pointer()
+ a_ptr = a.reinterpret_cast(ptr_byte_vector)
+ b_ptr = b.reinterpret_cast(ptr_byte_vector)
+ return a_ptr.dereference() == b_ptr.dereference()
class _StrLen(gdb.Function):
- """$_strlen - compute string length.
+ """$_strlen - compute string length.
+
+ Usage: $_strlen (A)
-Usage: $_strlen (A)
+ Returns:
+ Length of string A, assumed to be a string in the current language."""
-Returns:
- Length of string A, assumed to be a string in the current language."""
- def __init__(self):
- super(_StrLen, self).__init__("_strlen")
+ def __init__(self):
+ super(_StrLen, self).__init__("_strlen")
- def invoke(self, a):
- s = a.string()
- return len(s)
+ def invoke(self, a):
+ s = a.string()
+ return len(s)
class _StrEq(gdb.Function):
- """$_streq - check string equality.
+ """$_streq - check string equality.
-Usage: $_streq (A, B)
+ Usage: $_streq (A, B)
-Returns:
- True if A and B are identical strings in the current language.
+ Returns:
+ True if A and B are identical strings in the current language.
-Example (amd64-linux):
- catch syscall open
- cond $bpnum $_streq((char*) $rdi, "foo")"""
- def __init__(self):
- super(_StrEq, self).__init__("_streq")
+ Example (amd64-linux):
+ catch syscall open
+ cond $bpnum $_streq((char*) $rdi, "foo")"""
- def invoke(self, a, b):
- return a.string() == b.string()
+ def __init__(self):
+ super(_StrEq, self).__init__("_streq")
+
+ def invoke(self, a, b):
+ return a.string() == b.string()
class _RegEx(gdb.Function):
- """$_regex - check if a string matches a regular expression.
+ """$_regex - check if a string matches a regular expression.
+
+ Usage: $_regex (STRING, REGEX)
-Usage: $_regex (STRING, REGEX)
+ Returns:
+ True if string STRING (in the current language) matches the
+ regular expression REGEX."""
-Returns:
- True if string STRING (in the current language) matches the
- regular expression REGEX."""
- def __init__(self):
- super(_RegEx, self).__init__("_regex")
+ def __init__(self):
+ super(_RegEx, self).__init__("_regex")
- def invoke(self, string, regex):
- s = string.string()
- r = re.compile(regex.string())
- return bool(r.match(s))
+ def invoke(self, string, regex):
+ s = string.string()
+ r = re.compile(regex.string())
+ return bool(r.match(s))
# GDB will import us automagically via gdb/__init__.py.
diff --git a/gdb/python/lib/gdb/printer/bound_registers.py b/gdb/python/lib/gdb/printer/bound_registers.py
index 88fc463a380..f0d0a3eab2f 100644
--- a/gdb/python/lib/gdb/printer/bound_registers.py
+++ b/gdb/python/lib/gdb/printer/bound_registers.py
@@ -23,21 +23,23 @@ if sys.version_info[0] > 2:
basestring = str
long = int
+
class MpxBound128Printer:
"""Adds size field to a mpx __gdb_builtin_type_bound128 type."""
- def __init__ (self, val):
+ def __init__(self, val):
self.val = val
- def to_string (self):
+ def to_string(self):
upper = self.val["ubound"]
lower = self.val["lbound"]
- size = (long) ((upper) - (lower))
+ size = (long)((upper) - (lower))
if size > -1:
size = size + 1
- result = '{lbound = %s, ubound = %s} : size %s' % (lower, upper, size)
+ result = "{lbound = %s, ubound = %s} : size %s" % (lower, upper, size)
return result
-gdb.printing.add_builtin_pretty_printer ('mpx_bound128',
- '^builtin_type_bound128',
- MpxBound128Printer)
+
+gdb.printing.add_builtin_pretty_printer(
+ "mpx_bound128", "^builtin_type_bound128", MpxBound128Printer
+)
diff --git a/gdb/python/lib/gdb/printing.py b/gdb/python/lib/gdb/printing.py
index 0fecb3d538f..aaa0115224f 100644
--- a/gdb/python/lib/gdb/printing.py
+++ b/gdb/python/lib/gdb/printing.py
@@ -26,6 +26,7 @@ if sys.version_info[0] > 2:
basestring = str
long = int
+
class PrettyPrinter(object):
"""A basic pretty-printer.
@@ -110,22 +111,23 @@ def register_pretty_printer(obj, printer, replace=False):
if not hasattr(printer, "__name__") and not hasattr(printer, "name"):
raise TypeError("printer missing attribute: name")
if hasattr(printer, "name") and not hasattr(printer, "enabled"):
- raise TypeError("printer missing attribute: enabled")
+ raise TypeError("printer missing attribute: enabled")
if not hasattr(printer, "__call__"):
raise TypeError("printer missing attribute: __call__")
if hasattr(printer, "name"):
- name = printer.name
+ name = printer.name
else:
- name = printer.__name__
+ name = printer.__name__
if obj is None or obj is gdb:
if gdb.parameter("verbose"):
gdb.write("Registering global %s pretty-printer ...\n" % name)
obj = gdb
else:
if gdb.parameter("verbose"):
- gdb.write("Registering %s pretty-printer for %s ...\n" % (
- name, obj.filename))
+ gdb.write(
+ "Registering %s pretty-printer for %s ...\n" % (name, obj.filename)
+ )
# Printers implemented as functions are old-style. In order to not risk
# breaking anything we do not check __name__ here.
@@ -148,8 +150,9 @@ def register_pretty_printer(obj, printer, replace=False):
del obj.pretty_printers[i]
break
else:
- raise RuntimeError("pretty-printer already registered: %s" %
- printer.name)
+ raise RuntimeError(
+ "pretty-printer already registered: %s" % printer.name
+ )
i = i + 1
obj.pretty_printers.insert(0, printer)
@@ -197,8 +200,7 @@ class RegexpCollectionPrettyPrinter(PrettyPrinter):
# cumbersome to make a regexp of a regexp). So now the name is a
# separate parameter.
- self.subprinters.append(self.RegexpSubprinter(name, regexp,
- gen_printer))
+ self.subprinters.append(self.RegexpSubprinter(name, regexp, gen_printer))
def __call__(self, val):
"""Lookup the pretty-printer for the provided value."""
@@ -220,6 +222,7 @@ class RegexpCollectionPrettyPrinter(PrettyPrinter):
# Cannot find a pretty printer. Return None.
return None
+
# A helper class for printing enum types. This class is instantiated
# with a list of enumerators to print a particular Value.
class _EnumInstance:
@@ -238,9 +241,10 @@ class _EnumInstance:
any_found = True
if not any_found or v != 0:
# Leftover value.
- flag_list.append('<unknown: 0x%x>' % v)
+ flag_list.append("<unknown: 0x%x>" % v)
return "0x%x [%s]" % (int(self.val), " | ".join(flag_list))
+
class FlagEnumerationPrinter(PrettyPrinter):
"""A pretty-printer which can be used to print a flag-style enumeration.
A flag-style enumeration is one where the enumerators are or'd
@@ -263,7 +267,7 @@ class FlagEnumerationPrinter(PrettyPrinter):
self.enumerators.append((field.name, field.enumval))
# Sorting the enumerators by value usually does the right
# thing.
- self.enumerators.sort(key = lambda x: x[1])
+ self.enumerators.sort(key=lambda x: x[1])
if self.enabled:
return _EnumInstance(self.enumerators, val)
@@ -281,5 +285,6 @@ register_pretty_printer(None, _builtin_pretty_printers)
# Add a builtin pretty-printer.
+
def add_builtin_pretty_printer(name, regexp, printer):
_builtin_pretty_printers.add_printer(name, regexp, printer)
diff --git a/gdb/python/lib/gdb/prompt.py b/gdb/python/lib/gdb/prompt.py
index 3da063bba5b..9b6c322e61e 100644
--- a/gdb/python/lib/gdb/prompt.py
+++ b/gdb/python/lib/gdb/prompt.py
@@ -19,10 +19,12 @@
import gdb
import os
+
def _prompt_pwd(ignore):
"The current working directory."
return os.getcwd()
+
def _prompt_object_attr(func, what, attr, nattr):
"""Internal worker for fetching GDB attributes."""
if attr is None:
@@ -30,91 +32,104 @@ def _prompt_object_attr(func, what, attr, nattr):
try:
obj = func()
except gdb.error:
- return '<no %s>' % what
+ return "<no %s>" % what
if hasattr(obj, attr):
result = getattr(obj, attr)
if callable(result):
result = result()
return result
else:
- return '<no attribute %s on current %s>' % (attr, what)
+ return "<no attribute %s on current %s>" % (attr, what)
+
def _prompt_frame(attr):
"The selected frame; an argument names a frame parameter."
- return _prompt_object_attr(gdb.selected_frame, 'frame', attr, 'name')
+ return _prompt_object_attr(gdb.selected_frame, "frame", attr, "name")
+
def _prompt_thread(attr):
"The selected thread; an argument names a thread parameter."
- return _prompt_object_attr(gdb.selected_thread, 'thread', attr, 'num')
+ return _prompt_object_attr(gdb.selected_thread, "thread", attr, "num")
+
def _prompt_version(attr):
"The version of GDB."
return gdb.VERSION
+
def _prompt_esc(attr):
"The ESC character."
- return '\033'
+ return "\033"
+
def _prompt_bs(attr):
"A backslash."
- return '\\'
+ return "\\"
+
def _prompt_n(attr):
"A newline."
- return '\n'
+ return "\n"
+
def _prompt_r(attr):
"A carriage return."
- return '\r'
+ return "\r"
+
def _prompt_param(attr):
"A parameter's value; the argument names the parameter."
return gdb.parameter(attr)
+
def _prompt_noprint_begin(attr):
"Begins a sequence of non-printing characters."
- return '\001'
+ return "\001"
+
def _prompt_noprint_end(attr):
- "Ends a sequence of non-printing characters."
- return '\002'
+ "Ends a sequence of non-printing characters."
+ return "\002"
+
prompt_substitutions = {
- 'e': _prompt_esc,
- '\\': _prompt_bs,
- 'n': _prompt_n,
- 'r': _prompt_r,
- 'v': _prompt_version,
- 'w': _prompt_pwd,
- 'f': _prompt_frame,
- 't': _prompt_thread,
- 'p': _prompt_param,
- '[': _prompt_noprint_begin,
- ']': _prompt_noprint_end
+ "e": _prompt_esc,
+ "\\": _prompt_bs,
+ "n": _prompt_n,
+ "r": _prompt_r,
+ "v": _prompt_version,
+ "w": _prompt_pwd,
+ "f": _prompt_frame,
+ "t": _prompt_thread,
+ "p": _prompt_param,
+ "[": _prompt_noprint_begin,
+ "]": _prompt_noprint_end,
}
+
def prompt_help():
"""Generate help dynamically from the __doc__ strings of attribute
functions."""
- result = ''
- keys = sorted (prompt_substitutions.keys())
+ result = ""
+ keys = sorted(prompt_substitutions.keys())
for key in keys:
- result += ' \\%s\t%s\n' % (key, prompt_substitutions[key].__doc__)
+ result += " \\%s\t%s\n" % (key, prompt_substitutions[key].__doc__)
result += """
A substitution can be used in a simple form, like "\\f".
An argument can also be passed to it, like "\\f{name}".
The meaning of the argument depends on the particular substitution."""
return result
+
def substitute_prompt(prompt):
"Perform substitutions on PROMPT."
- result = ''
+ result = ""
plen = len(prompt)
i = 0
while i < plen:
- if prompt[i] == '\\':
+ if prompt[i] == "\\":
i = i + 1
if i >= plen:
break
@@ -123,12 +138,12 @@ def substitute_prompt(prompt):
if cmdch in prompt_substitutions:
cmd = prompt_substitutions[cmdch]
- if i + 1 < plen and prompt[i + 1] == '{':
+ if i + 1 < plen and prompt[i + 1] == "{":
j = i + 1
- while j < plen and prompt[j] != '}':
+ while j < plen and prompt[j] != "}":
j = j + 1
# Just ignore formatting errors.
- if j >= plen or prompt[j] != '}':
+ if j >= plen or prompt[j] != "}":
arg = None
else:
arg = prompt[i + 2 : j]
diff --git a/gdb/python/lib/gdb/types.py b/gdb/python/lib/gdb/types.py
index edb3c58f605..c7de68adb4c 100644
--- a/gdb/python/lib/gdb/types.py
+++ b/gdb/python/lib/gdb/types.py
@@ -30,11 +30,12 @@ def get_basic_type(type_):
and typedefs/references converted to the underlying type.
"""
- while (type_.code == gdb.TYPE_CODE_REF or
- type_.code == gdb.TYPE_CODE_RVALUE_REF or
- type_.code == gdb.TYPE_CODE_TYPEDEF):
- if (type_.code == gdb.TYPE_CODE_REF or
- type_.code == gdb.TYPE_CODE_RVALUE_REF):
+ while (
+ type_.code == gdb.TYPE_CODE_REF
+ or type_.code == gdb.TYPE_CODE_RVALUE_REF
+ or type_.code == gdb.TYPE_CODE_TYPEDEF
+ ):
+ if type_.code == gdb.TYPE_CODE_REF or type_.code == gdb.TYPE_CODE_RVALUE_REF:
type_ = type_.target()
else:
type_ = type_.strip_typedefs()
@@ -57,8 +58,7 @@ def has_field(type_, field):
"""
type_ = get_basic_type(type_)
- if (type_.code != gdb.TYPE_CODE_STRUCT and
- type_.code != gdb.TYPE_CODE_UNION):
+ if type_.code != gdb.TYPE_CODE_STRUCT and type_.code != gdb.TYPE_CODE_UNION:
raise TypeError("not a struct or union")
for f in type_.fields():
if f.is_base_class:
@@ -93,7 +93,7 @@ def make_enum_dict(enum_type):
return enum_dict
-def deep_items (type_):
+def deep_items(type_):
"""Return an iterator that recursively traverses anonymous fields.
Arguments:
@@ -105,13 +105,14 @@ def deep_items (type_):
pairs of key, value, but for any anonymous struct or union
field that field is traversed recursively, depth-first.
"""
- for k, v in type_.iteritems ():
+ for k, v in type_.iteritems():
if k:
yield k, v
else:
- for i in deep_items (v.type):
+ for i in deep_items(v.type):
yield i
+
class TypePrinter(object):
"""The base class for type printers.
@@ -134,6 +135,7 @@ class TypePrinter(object):
def instantiate(self):
return None
+
# Helper function for computing the list of type recognizers.
def _get_some_type_recognizers(result, plist):
for printer in plist:
@@ -143,6 +145,7 @@ def _get_some_type_recognizers(result, plist):
result.append(inst)
return None
+
def get_type_recognizers():
"Return a list of the enabled type recognizers for the current context."
result = []
@@ -157,6 +160,7 @@ def get_type_recognizers():
return result
+
def apply_type_recognizers(recognizers, type_obj):
"""Apply the given list of type recognizers to the type TYPE_OBJ.
If any recognizer in the list recognizes TYPE_OBJ, returns the name
@@ -167,6 +171,7 @@ def apply_type_recognizers(recognizers, type_obj):
return result
return None
+
def register_type_printer(locus, printer):
"""Register a type printer.
PRINTER is the type printer instance.
diff --git a/gdb/python/lib/gdb/unwinder.py b/gdb/python/lib/gdb/unwinder.py
index 8cdcf0c1a7c..ef2aa5bdf6c 100644
--- a/gdb/python/lib/gdb/unwinder.py
+++ b/gdb/python/lib/gdb/unwinder.py
@@ -77,8 +77,9 @@ def register_unwinder(locus, unwinder, replace=False):
locus = gdb
elif isinstance(locus, gdb.Objfile) or isinstance(locus, gdb.Progspace):
if gdb.parameter("verbose"):
- gdb.write("Registering %s unwinder for %s ...\n" %
- (unwinder.name, locus.filename))
+ gdb.write(
+ "Registering %s unwinder for %s ...\n" % (unwinder.name, locus.filename)
+ )
else:
raise TypeError("locus should be gdb.Objfile or gdb.Progspace or None")
@@ -88,8 +89,7 @@ def register_unwinder(locus, unwinder, replace=False):
if replace:
del locus.frame_unwinders[i]
else:
- raise RuntimeError("Unwinder %s already exists." %
- unwinder.name)
+ raise RuntimeError("Unwinder %s already exists." % unwinder.name)
i += 1
locus.frame_unwinders.insert(0, unwinder)
gdb.invalidate_cached_frames()
diff --git a/gdb/python/lib/gdb/xmethod.py b/gdb/python/lib/gdb/xmethod.py
index b6bfbb019cc..44eb4dd88c1 100644
--- a/gdb/python/lib/gdb/xmethod.py
+++ b/gdb/python/lib/gdb/xmethod.py
@@ -172,9 +172,9 @@ class SimpleXMethodMatcher(XMethodMatcher):
def __call__(self, *args):
return self._method_function(*args)
-
- def __init__(self, name, class_matcher, method_matcher, method_function,
- *arg_types):
+ def __init__(
+ self, name, class_matcher, method_matcher, method_function, *arg_types
+ ):
"""
Args:
name: Name of the xmethod matcher.
@@ -195,7 +195,8 @@ class SimpleXMethodMatcher(XMethodMatcher):
XMethodMatcher.__init__(self, name)
assert callable(method_function), (
"The 'method_function' argument to 'SimpleXMethodMatcher' "
- "__init__ method should be a callable.")
+ "__init__ method should be a callable."
+ )
self._method_function = method_function
self._class_matcher = class_matcher
self._method_matcher = method_matcher
@@ -206,13 +207,15 @@ class SimpleXMethodMatcher(XMethodMatcher):
mm = re.match(self._method_matcher, method_name)
if cm and mm:
return SimpleXMethodMatcher.SimpleXMethodWorker(
- self._method_function, self._arg_types)
+ self._method_function, self._arg_types
+ )
# A helper function for register_xmethod_matcher which returns an error
# object if MATCHER is not having the requisite attributes in the proper
# format.
+
def _validate_xmethod_matcher(matcher):
if not hasattr(matcher, "match"):
return TypeError("Xmethod matcher is missing method: match")
@@ -221,17 +224,17 @@ def _validate_xmethod_matcher(matcher):
if not hasattr(matcher, "enabled"):
return TypeError("Xmethod matcher is missing attribute: enabled")
if not isinstance(matcher.name, basestring):
- return TypeError("Attribute 'name' of xmethod matcher is not a "
- "string")
+ return TypeError("Attribute 'name' of xmethod matcher is not a " "string")
if matcher.name.find(";") >= 0:
return ValueError("Xmethod matcher name cannot contain ';' in it")
-# A helper function for register_xmethod_matcher which looks up an
+# A helper function for register_xmethod_matcher which looks up an
# xmethod matcher with NAME in LOCUS. Returns the index of the xmethod
# matcher in 'xmethods' sequence attribute of the LOCUS. If NAME is not
# found in LOCUS, then -1 is returned.
+
def _lookup_xmethod_matcher(locus, name):
for i in range(0, len(locus.xmethods)):
if locus.xmethods[i].name == name:
@@ -268,8 +271,10 @@ def register_xmethod_matcher(locus, matcher, replace=False):
if replace:
del locus.xmethods[index]
else:
- raise RuntimeError("Xmethod matcher already registered with "
- "%s: %s" % (locus_name, matcher.name))
+ raise RuntimeError(
+ "Xmethod matcher already registered with "
+ "%s: %s" % (locus_name, matcher.name)
+ )
if gdb.parameter("verbose"):
gdb.write("Registering xmethod matcher '%s' with %s' ...\n")
locus.xmethods.insert(0, matcher)
diff --git a/gdb/python/python-config.py b/gdb/python/python-config.py
index 3e60b86a6fc..027d80dcc86 100644
--- a/gdb/python/python-config.py
+++ b/gdb/python/python-config.py
@@ -6,31 +6,34 @@ import os
import getopt
from distutils import sysconfig
-valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags',
- 'ldflags', 'help']
+valid_opts = ["prefix", "exec-prefix", "includes", "libs", "cflags", "ldflags", "help"]
+
def exit_with_usage(code=1):
- sys.stderr.write ("Usage: %s [%s]\n" % (sys.argv[0],
- '|'.join('--'+opt for opt in valid_opts)))
+ sys.stderr.write(
+ "Usage: %s [%s]\n" % (sys.argv[0], "|".join("--" + opt for opt in valid_opts))
+ )
sys.exit(code)
+
try:
- opts, args = getopt.getopt(sys.argv[1:], '', valid_opts)
+ opts, args = getopt.getopt(sys.argv[1:], "", valid_opts)
except getopt.error:
exit_with_usage()
if not opts:
exit_with_usage()
-pyver = sysconfig.get_config_var('VERSION')
+pyver = sysconfig.get_config_var("VERSION")
getvar = sysconfig.get_config_var
-abiflags = getattr (sys, "abiflags", "")
+abiflags = getattr(sys, "abiflags", "")
opt_flags = [flag for (flag, val) in opts]
-if '--help' in opt_flags:
+if "--help" in opt_flags:
exit_with_usage(code=0)
+
def to_unix_path(path):
"""On Windows, returns the given path with all backslashes
converted into forward slashes. This is to help prevent problems
@@ -39,39 +42,41 @@ def to_unix_path(path):
On Unix systems, returns the path unchanged.
"""
- if os.name == 'nt':
- path = path.replace('\\', '/')
+ if os.name == "nt":
+ path = path.replace("\\", "/")
return path
+
for opt in opt_flags:
- if opt == '--prefix':
- print (to_unix_path(sysconfig.PREFIX))
-
- elif opt == '--exec-prefix':
- print (to_unix_path(sysconfig.EXEC_PREFIX))
-
- elif opt in ('--includes', '--cflags'):
- flags = ['-I' + sysconfig.get_python_inc(),
- '-I' + sysconfig.get_python_inc(plat_specific=True)]
- if opt == '--cflags':
- flags.extend(getvar('CFLAGS').split())
- print (to_unix_path(' '.join(flags)))
-
- elif opt in ('--libs', '--ldflags'):
- libs = ['-lpython' + pyver + abiflags]
- if getvar('LIBS') is not None:
- libs.extend(getvar('LIBS').split())
- if getvar('SYSLIBS') is not None:
- libs.extend(getvar('SYSLIBS').split())
+ if opt == "--prefix":
+ print(to_unix_path(sysconfig.PREFIX))
+
+ elif opt == "--exec-prefix":
+ print(to_unix_path(sysconfig.EXEC_PREFIX))
+
+ elif opt in ("--includes", "--cflags"):
+ flags = [
+ "-I" + sysconfig.get_python_inc(),
+ "-I" + sysconfig.get_python_inc(plat_specific=True),
+ ]
+ if opt == "--cflags":
+ flags.extend(getvar("CFLAGS").split())
+ print(to_unix_path(" ".join(flags)))
+
+ elif opt in ("--libs", "--ldflags"):
+ libs = ["-lpython" + pyver + abiflags]
+ if getvar("LIBS") is not None:
+ libs.extend(getvar("LIBS").split())
+ if getvar("SYSLIBS") is not None:
+ libs.extend(getvar("SYSLIBS").split())
# add the prefix/lib/pythonX.Y/config dir, but only if there is no
# shared library in prefix/lib/.
- if opt == '--ldflags':
- if not getvar('Py_ENABLE_SHARED'):
- if getvar('LIBPL') is not None:
- libs.insert(0, '-L' + getvar('LIBPL'))
- elif os.name == 'nt':
- libs.insert(0, '-L' + sysconfig.PREFIX + '/libs')
- if getvar('LINKFORSHARED') is not None:
- libs.extend(getvar('LINKFORSHARED').split())
- print (to_unix_path(' '.join(libs)))
-
+ if opt == "--ldflags":
+ if not getvar("Py_ENABLE_SHARED"):
+ if getvar("LIBPL") is not None:
+ libs.insert(0, "-L" + getvar("LIBPL"))
+ elif os.name == "nt":
+ libs.insert(0, "-L" + sysconfig.PREFIX + "/libs")
+ if getvar("LINKFORSHARED") is not None:
+ libs.extend(getvar("LINKFORSHARED").split())
+ print(to_unix_path(" ".join(libs)))