PageRenderTime 41ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/share/gdb/python/gdb/printing.py

https://gitlab.com/UBERTC/arm-eabi-5.3-old
Python | 285 lines | 258 code | 5 blank | 22 comment | 2 complexity | 41ade58509f109d7dc8e0b261d369aa9 MD5 | raw file
  1. # Pretty-printer utilities.
  2. # Copyright (C) 2010-2016 Free Software Foundation, Inc.
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 3 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. """Utilities for working with pretty-printers."""
  16. import gdb
  17. import gdb.types
  18. import re
  19. import sys
  20. if sys.version_info[0] > 2:
  21. # Python 3 removed basestring and long
  22. basestring = str
  23. long = int
  24. class PrettyPrinter(object):
  25. """A basic pretty-printer.
  26. Attributes:
  27. name: A unique string among all printers for the context in which
  28. it is defined (objfile, progspace, or global(gdb)), and should
  29. meaningfully describe what can be pretty-printed.
  30. E.g., "StringPiece" or "protobufs".
  31. subprinters: An iterable object with each element having a `name'
  32. attribute, and, potentially, "enabled" attribute.
  33. Or this is None if there are no subprinters.
  34. enabled: A boolean indicating if the printer is enabled.
  35. Subprinters are for situations where "one" pretty-printer is actually a
  36. collection of several printers. E.g., The libstdc++ pretty-printer has
  37. a pretty-printer for each of several different types, based on regexps.
  38. """
  39. # While one might want to push subprinters into the subclass, it's
  40. # present here to formalize such support to simplify
  41. # commands/pretty_printers.py.
  42. def __init__(self, name, subprinters=None):
  43. self.name = name
  44. self.subprinters = subprinters
  45. self.enabled = True
  46. def __call__(self, val):
  47. # The subclass must define this.
  48. raise NotImplementedError("PrettyPrinter __call__")
  49. class SubPrettyPrinter(object):
  50. """Baseclass for sub-pretty-printers.
  51. Sub-pretty-printers needn't use this, but it formalizes what's needed.
  52. Attributes:
  53. name: The name of the subprinter.
  54. enabled: A boolean indicating if the subprinter is enabled.
  55. """
  56. def __init__(self, name):
  57. self.name = name
  58. self.enabled = True
  59. def register_pretty_printer(obj, printer, replace=False):
  60. """Register pretty-printer PRINTER with OBJ.
  61. The printer is added to the front of the search list, thus one can override
  62. an existing printer if one needs to. Use a different name when overriding
  63. an existing printer, otherwise an exception will be raised; multiple
  64. printers with the same name are disallowed.
  65. Arguments:
  66. obj: Either an objfile, progspace, or None (in which case the printer
  67. is registered globally).
  68. printer: Either a function of one argument (old way) or any object
  69. which has attributes: name, enabled, __call__.
  70. replace: If True replace any existing copy of the printer.
  71. Otherwise if the printer already exists raise an exception.
  72. Returns:
  73. Nothing.
  74. Raises:
  75. TypeError: A problem with the type of the printer.
  76. ValueError: The printer's name contains a semicolon ";".
  77. RuntimeError: A printer with the same name is already registered.
  78. If the caller wants the printer to be listable and disableable, it must
  79. follow the PrettyPrinter API. This applies to the old way (functions) too.
  80. If printer is an object, __call__ is a method of two arguments:
  81. self, and the value to be pretty-printed. See PrettyPrinter.
  82. """
  83. # Watch for both __name__ and name.
  84. # Functions get the former for free, but we don't want to use an
  85. # attribute named __foo__ for pretty-printers-as-objects.
  86. # If printer has both, we use `name'.
  87. if not hasattr(printer, "__name__") and not hasattr(printer, "name"):
  88. raise TypeError("printer missing attribute: name")
  89. if hasattr(printer, "name") and not hasattr(printer, "enabled"):
  90. raise TypeError("printer missing attribute: enabled")
  91. if not hasattr(printer, "__call__"):
  92. raise TypeError("printer missing attribute: __call__")
  93. if hasattr(printer, "name"):
  94. name = printer.name
  95. else:
  96. name = printer.__name__
  97. if obj is None or obj is gdb:
  98. if gdb.parameter("verbose"):
  99. gdb.write("Registering global %s pretty-printer ...\n" % name)
  100. obj = gdb
  101. else:
  102. if gdb.parameter("verbose"):
  103. gdb.write("Registering %s pretty-printer for %s ...\n" % (
  104. name, obj.filename))
  105. # Printers implemented as functions are old-style. In order to not risk
  106. # breaking anything we do not check __name__ here.
  107. if hasattr(printer, "name"):
  108. if not isinstance(printer.name, basestring):
  109. raise TypeError("printer name is not a string")
  110. # If printer provides a name, make sure it doesn't contain ";".
  111. # Semicolon is used by the info/enable/disable pretty-printer commands
  112. # to delimit subprinters.
  113. if printer.name.find(";") >= 0:
  114. raise ValueError("semicolon ';' in printer name")
  115. # Also make sure the name is unique.
  116. # Alas, we can't do the same for functions and __name__, they could
  117. # all have a canonical name like "lookup_function".
  118. # PERF: gdb records printers in a list, making this inefficient.
  119. i = 0
  120. for p in obj.pretty_printers:
  121. if hasattr(p, "name") and p.name == printer.name:
  122. if replace:
  123. del obj.pretty_printers[i]
  124. break
  125. else:
  126. raise RuntimeError("pretty-printer already registered: %s" %
  127. printer.name)
  128. i = i + 1
  129. obj.pretty_printers.insert(0, printer)
  130. class RegexpCollectionPrettyPrinter(PrettyPrinter):
  131. """Class for implementing a collection of regular-expression based pretty-printers.
  132. Intended usage:
  133. pretty_printer = RegexpCollectionPrettyPrinter("my_library")
  134. pretty_printer.add_printer("myclass1", "^myclass1$", MyClass1Printer)
  135. ...
  136. pretty_printer.add_printer("myclassN", "^myclassN$", MyClassNPrinter)
  137. register_pretty_printer(obj, pretty_printer)
  138. """
  139. class RegexpSubprinter(SubPrettyPrinter):
  140. def __init__(self, name, regexp, gen_printer):
  141. super(RegexpCollectionPrettyPrinter.RegexpSubprinter, self).__init__(name)
  142. self.regexp = regexp
  143. self.gen_printer = gen_printer
  144. self.compiled_re = re.compile(regexp)
  145. def __init__(self, name):
  146. super(RegexpCollectionPrettyPrinter, self).__init__(name, [])
  147. def add_printer(self, name, regexp, gen_printer):
  148. """Add a printer to the list.
  149. The printer is added to the end of the list.
  150. Arguments:
  151. name: The name of the subprinter.
  152. regexp: The regular expression, as a string.
  153. gen_printer: A function/method that given a value returns an
  154. object to pretty-print it.
  155. Returns:
  156. Nothing.
  157. """
  158. # NOTE: A previous version made the name of each printer the regexp.
  159. # That makes it awkward to pass to the enable/disable commands (it's
  160. # cumbersome to make a regexp of a regexp). So now the name is a
  161. # separate parameter.
  162. self.subprinters.append(self.RegexpSubprinter(name, regexp,
  163. gen_printer))
  164. def __call__(self, val):
  165. """Lookup the pretty-printer for the provided value."""
  166. # Get the type name.
  167. typename = gdb.types.get_basic_type(val.type).tag
  168. if not typename:
  169. typename = val.type.name
  170. if not typename:
  171. return None
  172. # Iterate over table of type regexps to determine
  173. # if a printer is registered for that type.
  174. # Return an instantiation of the printer if found.
  175. for printer in self.subprinters:
  176. if printer.enabled and printer.compiled_re.search(typename):
  177. return printer.gen_printer(val)
  178. # Cannot find a pretty printer. Return None.
  179. return None
  180. # A helper class for printing enum types. This class is instantiated
  181. # with a list of enumerators to print a particular Value.
  182. class _EnumInstance:
  183. def __init__(self, enumerators, val):
  184. self.enumerators = enumerators
  185. self.val = val
  186. def to_string(self):
  187. flag_list = []
  188. v = long(self.val)
  189. any_found = False
  190. for (e_name, e_value) in self.enumerators:
  191. if v & e_value != 0:
  192. flag_list.append(e_name)
  193. v = v & ~e_value
  194. any_found = True
  195. if not any_found or v != 0:
  196. # Leftover value.
  197. flag_list.append('<unknown: 0x%x>' % v)
  198. return "0x%x [%s]" % (int(self.val), " | ".join(flag_list))
  199. class FlagEnumerationPrinter(PrettyPrinter):
  200. """A pretty-printer which can be used to print a flag-style enumeration.
  201. A flag-style enumeration is one where the enumerators are or'd
  202. together to create values. The new printer will print these
  203. symbolically using '|' notation. The printer must be registered
  204. manually. This printer is most useful when an enum is flag-like,
  205. but has some overlap. GDB's built-in printing will not handle
  206. this case, but this printer will attempt to."""
  207. def __init__(self, enum_type):
  208. super(FlagEnumerationPrinter, self).__init__(enum_type)
  209. self.initialized = False
  210. def __call__(self, val):
  211. if not self.initialized:
  212. self.initialized = True
  213. flags = gdb.lookup_type(self.name)
  214. self.enumerators = []
  215. for field in flags.fields():
  216. self.enumerators.append((field.name, field.enumval))
  217. # Sorting the enumerators by value usually does the right
  218. # thing.
  219. self.enumerators.sort(key = lambda x: x[1])
  220. if self.enabled:
  221. return _EnumInstance(self.enumerators, val)
  222. else:
  223. return None
  224. # Builtin pretty-printers.
  225. # The set is defined as empty, and files in printing/*.py add their printers
  226. # to this with add_builtin_pretty_printer.
  227. _builtin_pretty_printers = RegexpCollectionPrettyPrinter("builtin")
  228. register_pretty_printer(None, _builtin_pretty_printers)
  229. # Add a builtin pretty-printer.
  230. def add_builtin_pretty_printer(name, regexp, printer):
  231. _builtin_pretty_printers.add_printer(name, regexp, printer)