printers.py 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032
  1. # Pretty-printers for libstdc++.
  2. # Copyright (C) 2008-2021 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. import gdb
  16. import itertools
  17. import re
  18. import sys
  19. ### Python 2 + Python 3 compatibility code
  20. # Resources about compatibility:
  21. #
  22. # * <http://pythonhosted.org/six/>: Documentation of the "six" module
  23. # FIXME: The handling of e.g. std::basic_string (at least on char)
  24. # probably needs updating to work with Python 3's new string rules.
  25. #
  26. # In particular, Python 3 has a separate type (called byte) for
  27. # bytestrings, and a special b"" syntax for the byte literals; the old
  28. # str() type has been redefined to always store Unicode text.
  29. #
  30. # We probably can't do much about this until this GDB PR is addressed:
  31. # <https://sourceware.org/bugzilla/show_bug.cgi?id=17138>
  32. if sys.version_info[0] > 2:
  33. ### Python 3 stuff
  34. Iterator = object
  35. # Python 3 folds these into the normal functions.
  36. imap = map
  37. izip = zip
  38. # Also, int subsumes long
  39. long = int
  40. else:
  41. ### Python 2 stuff
  42. class Iterator:
  43. """Compatibility mixin for iterators
  44. Instead of writing next() methods for iterators, write
  45. __next__() methods and use this mixin to make them work in
  46. Python 2 as well as Python 3.
  47. Idea stolen from the "six" documentation:
  48. <http://pythonhosted.org/six/#six.Iterator>
  49. """
  50. def next(self):
  51. return self.__next__()
  52. # In Python 2, we still need these from itertools
  53. from itertools import imap, izip
  54. # Try to use the new-style pretty-printing if available.
  55. _use_gdb_pp = True
  56. try:
  57. import gdb.printing
  58. except ImportError:
  59. _use_gdb_pp = False
  60. # Try to install type-printers.
  61. _use_type_printing = False
  62. try:
  63. import gdb.types
  64. if hasattr(gdb.types, 'TypePrinter'):
  65. _use_type_printing = True
  66. except ImportError:
  67. pass
  68. # Starting with the type ORIG, search for the member type NAME. This
  69. # handles searching upward through superclasses. This is needed to
  70. # work around http://sourceware.org/bugzilla/show_bug.cgi?id=13615.
  71. def find_type(orig, name):
  72. typ = orig.strip_typedefs()
  73. while True:
  74. # Use Type.tag to ignore cv-qualifiers. PR 67440.
  75. search = '%s::%s' % (typ.tag, name)
  76. try:
  77. return gdb.lookup_type(search)
  78. except RuntimeError:
  79. pass
  80. # The type was not found, so try the superclass. We only need
  81. # to check the first superclass, so we don't bother with
  82. # anything fancier here.
  83. fields = typ.fields()
  84. if len(fields) and fields[0].is_base_class:
  85. typ = fields[0].type
  86. else:
  87. raise ValueError("Cannot find type %s::%s" % (str(orig), name))
  88. _versioned_namespace = '__8::'
  89. def lookup_templ_spec(templ, *args):
  90. """
  91. Lookup template specialization templ<args...>
  92. """
  93. t = '{}<{}>'.format(templ, ', '.join([str(a) for a in args]))
  94. try:
  95. return gdb.lookup_type(t)
  96. except gdb.error as e:
  97. # Type not found, try again in versioned namespace.
  98. global _versioned_namespace
  99. if _versioned_namespace and _versioned_namespace not in templ:
  100. t = t.replace('::', '::' + _versioned_namespace, 1)
  101. try:
  102. return gdb.lookup_type(t)
  103. except gdb.error:
  104. # If that also fails, rethrow the original exception
  105. pass
  106. raise e
  107. # Use this to find container node types instead of find_type,
  108. # see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91997 for details.
  109. def lookup_node_type(nodename, containertype):
  110. """
  111. Lookup specialization of template NODENAME corresponding to CONTAINERTYPE.
  112. e.g. if NODENAME is '_List_node' and CONTAINERTYPE is std::list<int>
  113. then return the type std::_List_node<int>.
  114. Returns None if not found.
  115. """
  116. # If nodename is unqualified, assume it's in namespace std.
  117. if '::' not in nodename:
  118. nodename = 'std::' + nodename
  119. try:
  120. valtype = find_type(containertype, 'value_type')
  121. except:
  122. valtype = containertype.template_argument(0)
  123. valtype = valtype.strip_typedefs()
  124. try:
  125. return lookup_templ_spec(nodename, valtype)
  126. except gdb.error as e:
  127. # For debug mode containers the node is in std::__cxx1998.
  128. if is_member_of_namespace(nodename, 'std'):
  129. if is_member_of_namespace(containertype, 'std::__cxx1998',
  130. 'std::__debug', '__gnu_debug'):
  131. nodename = nodename.replace('::', '::__cxx1998::', 1)
  132. try:
  133. return lookup_templ_spec(nodename, valtype)
  134. except gdb.error:
  135. pass
  136. return None
  137. def is_member_of_namespace(typ, *namespaces):
  138. """
  139. Test whether a type is a member of one of the specified namespaces.
  140. The type can be specified as a string or a gdb.Type object.
  141. """
  142. if type(typ) is gdb.Type:
  143. typ = str(typ)
  144. typ = strip_versioned_namespace(typ)
  145. for namespace in namespaces:
  146. if typ.startswith(namespace + '::'):
  147. return True
  148. return False
  149. def is_specialization_of(x, template_name):
  150. "Test if a type is a given template instantiation."
  151. global _versioned_namespace
  152. if type(x) is gdb.Type:
  153. x = x.tag
  154. if _versioned_namespace:
  155. return re.match('^std::(%s)?%s<.*>$' % (_versioned_namespace, template_name), x) is not None
  156. return re.match('^std::%s<.*>$' % template_name, x) is not None
  157. def strip_versioned_namespace(typename):
  158. global _versioned_namespace
  159. if _versioned_namespace:
  160. return typename.replace(_versioned_namespace, '')
  161. return typename
  162. def strip_inline_namespaces(type_str):
  163. "Remove known inline namespaces from the canonical name of a type."
  164. type_str = strip_versioned_namespace(type_str)
  165. type_str = type_str.replace('std::__cxx11::', 'std::')
  166. expt_ns = 'std::experimental::'
  167. for lfts_ns in ('fundamentals_v1', 'fundamentals_v2'):
  168. type_str = type_str.replace(expt_ns+lfts_ns+'::', expt_ns)
  169. fs_ns = expt_ns + 'filesystem::'
  170. type_str = type_str.replace(fs_ns+'v1::', fs_ns)
  171. return type_str
  172. def get_template_arg_list(type_obj):
  173. "Return a type's template arguments as a list"
  174. n = 0
  175. template_args = []
  176. while True:
  177. try:
  178. template_args.append(type_obj.template_argument(n))
  179. except:
  180. return template_args
  181. n += 1
  182. class SmartPtrIterator(Iterator):
  183. "An iterator for smart pointer types with a single 'child' value"
  184. def __init__(self, val):
  185. self.val = val
  186. def __iter__(self):
  187. return self
  188. def __next__(self):
  189. if self.val is None:
  190. raise StopIteration
  191. self.val, val = None, self.val
  192. return ('get()', val)
  193. class SharedPointerPrinter:
  194. "Print a shared_ptr or weak_ptr"
  195. def __init__ (self, typename, val):
  196. self.typename = strip_versioned_namespace(typename)
  197. self.val = val
  198. self.pointer = val['_M_ptr']
  199. def children (self):
  200. return SmartPtrIterator(self.pointer)
  201. def to_string (self):
  202. state = 'empty'
  203. refcounts = self.val['_M_refcount']['_M_pi']
  204. if refcounts != 0:
  205. usecount = refcounts['_M_use_count']
  206. weakcount = refcounts['_M_weak_count']
  207. if usecount == 0:
  208. state = 'expired, weak count %d' % weakcount
  209. else:
  210. state = 'use count %d, weak count %d' % (usecount, weakcount - 1)
  211. return '%s<%s> (%s)' % (self.typename, str(self.val.type.template_argument(0)), state)
  212. class UniquePointerPrinter:
  213. "Print a unique_ptr"
  214. def __init__ (self, typename, val):
  215. self.val = val
  216. impl_type = val.type.fields()[0].type.strip_typedefs()
  217. # Check for new implementations first:
  218. if is_specialization_of(impl_type, '__uniq_ptr_data') \
  219. or is_specialization_of(impl_type, '__uniq_ptr_impl'):
  220. tuple_member = val['_M_t']['_M_t']
  221. elif is_specialization_of(impl_type, 'tuple'):
  222. tuple_member = val['_M_t']
  223. else:
  224. raise ValueError("Unsupported implementation for unique_ptr: %s" % str(impl_type))
  225. tuple_impl_type = tuple_member.type.fields()[0].type # _Tuple_impl
  226. tuple_head_type = tuple_impl_type.fields()[1].type # _Head_base
  227. head_field = tuple_head_type.fields()[0]
  228. if head_field.name == '_M_head_impl':
  229. self.pointer = tuple_member['_M_head_impl']
  230. elif head_field.is_base_class:
  231. self.pointer = tuple_member.cast(head_field.type)
  232. else:
  233. raise ValueError("Unsupported implementation for tuple in unique_ptr: %s" % str(impl_type))
  234. def children (self):
  235. return SmartPtrIterator(self.pointer)
  236. def to_string (self):
  237. return ('std::unique_ptr<%s>' % (str(self.val.type.template_argument(0))))
  238. def get_value_from_aligned_membuf(buf, valtype):
  239. """Returns the value held in a __gnu_cxx::__aligned_membuf."""
  240. return buf['_M_storage'].address.cast(valtype.pointer()).dereference()
  241. def get_value_from_list_node(node):
  242. """Returns the value held in an _List_node<_Val>"""
  243. try:
  244. member = node.type.fields()[1].name
  245. if member == '_M_data':
  246. # C++03 implementation, node contains the value as a member
  247. return node['_M_data']
  248. elif member == '_M_storage':
  249. # C++11 implementation, node stores value in __aligned_membuf
  250. valtype = node.type.template_argument(0)
  251. return get_value_from_aligned_membuf(node['_M_storage'], valtype)
  252. except:
  253. pass
  254. raise ValueError("Unsupported implementation for %s" % str(node.type))
  255. class StdListPrinter:
  256. "Print a std::list"
  257. class _iterator(Iterator):
  258. def __init__(self, nodetype, head):
  259. self.nodetype = nodetype
  260. self.base = head['_M_next']
  261. self.head = head.address
  262. self.count = 0
  263. def __iter__(self):
  264. return self
  265. def __next__(self):
  266. if self.base == self.head:
  267. raise StopIteration
  268. elt = self.base.cast(self.nodetype).dereference()
  269. self.base = elt['_M_next']
  270. count = self.count
  271. self.count = self.count + 1
  272. val = get_value_from_list_node(elt)
  273. return ('[%d]' % count, val)
  274. def __init__(self, typename, val):
  275. self.typename = strip_versioned_namespace(typename)
  276. self.val = val
  277. def children(self):
  278. nodetype = lookup_node_type('_List_node', self.val.type).pointer()
  279. return self._iterator(nodetype, self.val['_M_impl']['_M_node'])
  280. def to_string(self):
  281. headnode = self.val['_M_impl']['_M_node']
  282. if headnode['_M_next'] == headnode.address:
  283. return 'empty %s' % (self.typename)
  284. return '%s' % (self.typename)
  285. class NodeIteratorPrinter:
  286. def __init__(self, typename, val, contname, nodename):
  287. self.val = val
  288. self.typename = typename
  289. self.contname = contname
  290. self.nodetype = lookup_node_type(nodename, val.type)
  291. def to_string(self):
  292. if not self.val['_M_node']:
  293. return 'non-dereferenceable iterator for std::%s' % (self.contname)
  294. node = self.val['_M_node'].cast(self.nodetype.pointer()).dereference()
  295. return str(get_value_from_list_node(node))
  296. class StdListIteratorPrinter(NodeIteratorPrinter):
  297. "Print std::list::iterator"
  298. def __init__(self, typename, val):
  299. NodeIteratorPrinter.__init__(self, typename, val, 'list', '_List_node')
  300. class StdFwdListIteratorPrinter(NodeIteratorPrinter):
  301. "Print std::forward_list::iterator"
  302. def __init__(self, typename, val):
  303. NodeIteratorPrinter.__init__(self, typename, val, 'forward_list',
  304. '_Fwd_list_node')
  305. class StdSlistPrinter:
  306. "Print a __gnu_cxx::slist"
  307. class _iterator(Iterator):
  308. def __init__(self, nodetype, head):
  309. self.nodetype = nodetype
  310. self.base = head['_M_head']['_M_next']
  311. self.count = 0
  312. def __iter__(self):
  313. return self
  314. def __next__(self):
  315. if self.base == 0:
  316. raise StopIteration
  317. elt = self.base.cast(self.nodetype).dereference()
  318. self.base = elt['_M_next']
  319. count = self.count
  320. self.count = self.count + 1
  321. return ('[%d]' % count, elt['_M_data'])
  322. def __init__(self, typename, val):
  323. self.val = val
  324. def children(self):
  325. nodetype = lookup_node_type('__gnu_cxx::_Slist_node', self.val.type)
  326. return self._iterator(nodetype.pointer(), self.val)
  327. def to_string(self):
  328. if self.val['_M_head']['_M_next'] == 0:
  329. return 'empty __gnu_cxx::slist'
  330. return '__gnu_cxx::slist'
  331. class StdSlistIteratorPrinter:
  332. "Print __gnu_cxx::slist::iterator"
  333. def __init__(self, typename, val):
  334. self.val = val
  335. def to_string(self):
  336. if not self.val['_M_node']:
  337. return 'non-dereferenceable iterator for __gnu_cxx::slist'
  338. nodetype = lookup_node_type('__gnu_cxx::_Slist_node', self.val.type).pointer()
  339. return str(self.val['_M_node'].cast(nodetype).dereference()['_M_data'])
  340. class StdVectorPrinter:
  341. "Print a std::vector"
  342. class _iterator(Iterator):
  343. def __init__ (self, start, finish, bitvec):
  344. self.bitvec = bitvec
  345. if bitvec:
  346. self.item = start['_M_p']
  347. self.so = 0
  348. self.finish = finish['_M_p']
  349. self.fo = finish['_M_offset']
  350. itype = self.item.dereference().type
  351. self.isize = 8 * itype.sizeof
  352. else:
  353. self.item = start
  354. self.finish = finish
  355. self.count = 0
  356. def __iter__(self):
  357. return self
  358. def __next__(self):
  359. count = self.count
  360. self.count = self.count + 1
  361. if self.bitvec:
  362. if self.item == self.finish and self.so >= self.fo:
  363. raise StopIteration
  364. elt = bool(self.item.dereference() & (1 << self.so))
  365. self.so = self.so + 1
  366. if self.so >= self.isize:
  367. self.item = self.item + 1
  368. self.so = 0
  369. return ('[%d]' % count, elt)
  370. else:
  371. if self.item == self.finish:
  372. raise StopIteration
  373. elt = self.item.dereference()
  374. self.item = self.item + 1
  375. return ('[%d]' % count, elt)
  376. def __init__(self, typename, val):
  377. self.typename = strip_versioned_namespace(typename)
  378. self.val = val
  379. self.is_bool = val.type.template_argument(0).code == gdb.TYPE_CODE_BOOL
  380. def children(self):
  381. return self._iterator(self.val['_M_impl']['_M_start'],
  382. self.val['_M_impl']['_M_finish'],
  383. self.is_bool)
  384. def to_string(self):
  385. start = self.val['_M_impl']['_M_start']
  386. finish = self.val['_M_impl']['_M_finish']
  387. end = self.val['_M_impl']['_M_end_of_storage']
  388. if self.is_bool:
  389. start = self.val['_M_impl']['_M_start']['_M_p']
  390. finish = self.val['_M_impl']['_M_finish']['_M_p']
  391. fo = self.val['_M_impl']['_M_finish']['_M_offset']
  392. itype = start.dereference().type
  393. bl = 8 * itype.sizeof
  394. length = bl * (finish - start) + fo
  395. capacity = bl * (end - start)
  396. return ('%s<bool> of length %d, capacity %d'
  397. % (self.typename, int (length), int (capacity)))
  398. else:
  399. return ('%s of length %d, capacity %d'
  400. % (self.typename, int (finish - start), int (end - start)))
  401. def display_hint(self):
  402. return 'array'
  403. class StdVectorIteratorPrinter:
  404. "Print std::vector::iterator"
  405. def __init__(self, typename, val):
  406. self.val = val
  407. def to_string(self):
  408. if not self.val['_M_current']:
  409. return 'non-dereferenceable iterator for std::vector'
  410. return str(self.val['_M_current'].dereference())
  411. class StdBitIteratorPrinter:
  412. "Print std::vector<bool>'s _Bit_iterator and _Bit_const_iterator"
  413. def __init__(self, typename, val):
  414. self.val = val
  415. def to_string(self):
  416. if not self.val['_M_p']:
  417. return 'non-dereferenceable iterator for std::vector<bool>'
  418. return bool(self.val['_M_p'].dereference() & (1 << self.val['_M_offset']))
  419. class StdBitReferencePrinter:
  420. "Print std::_Bit_reference"
  421. def __init__(self, typename, val):
  422. self.val = val
  423. def to_string(self):
  424. if not self.val['_M_p']:
  425. return 'invalid std::_Bit_reference'
  426. return bool(self.val['_M_p'].dereference() & (self.val['_M_mask']))
  427. class StdTuplePrinter:
  428. "Print a std::tuple"
  429. class _iterator(Iterator):
  430. @staticmethod
  431. def _is_nonempty_tuple (nodes):
  432. if len (nodes) == 2:
  433. if is_specialization_of (nodes[1].type, '__tuple_base'):
  434. return True
  435. elif len (nodes) == 1:
  436. return True
  437. elif len (nodes) == 0:
  438. return False
  439. raise ValueError("Top of tuple tree does not consist of a single node.")
  440. def __init__ (self, head):
  441. self.head = head
  442. # Set the base class as the initial head of the
  443. # tuple.
  444. nodes = self.head.type.fields ()
  445. if self._is_nonempty_tuple (nodes):
  446. # Set the actual head to the first pair.
  447. self.head = self.head.cast (nodes[0].type)
  448. self.count = 0
  449. def __iter__ (self):
  450. return self
  451. def __next__ (self):
  452. # Check for further recursions in the inheritance tree.
  453. # For a GCC 5+ tuple self.head is None after visiting all nodes:
  454. if not self.head:
  455. raise StopIteration
  456. nodes = self.head.type.fields ()
  457. # For a GCC 4.x tuple there is a final node with no fields:
  458. if len (nodes) == 0:
  459. raise StopIteration
  460. # Check that this iteration has an expected structure.
  461. if len (nodes) > 2:
  462. raise ValueError("Cannot parse more than 2 nodes in a tuple tree.")
  463. if len (nodes) == 1:
  464. # This is the last node of a GCC 5+ std::tuple.
  465. impl = self.head.cast (nodes[0].type)
  466. self.head = None
  467. else:
  468. # Either a node before the last node, or the last node of
  469. # a GCC 4.x tuple (which has an empty parent).
  470. # - Left node is the next recursion parent.
  471. # - Right node is the actual class contained in the tuple.
  472. # Process right node.
  473. impl = self.head.cast (nodes[1].type)
  474. # Process left node and set it as head.
  475. self.head = self.head.cast (nodes[0].type)
  476. self.count = self.count + 1
  477. # Finally, check the implementation. If it is
  478. # wrapped in _M_head_impl return that, otherwise return
  479. # the value "as is".
  480. fields = impl.type.fields ()
  481. if len (fields) < 1 or fields[0].name != "_M_head_impl":
  482. return ('[%d]' % self.count, impl)
  483. else:
  484. return ('[%d]' % self.count, impl['_M_head_impl'])
  485. def __init__ (self, typename, val):
  486. self.typename = strip_versioned_namespace(typename)
  487. self.val = val;
  488. def children (self):
  489. return self._iterator (self.val)
  490. def to_string (self):
  491. if len (self.val.type.fields ()) == 0:
  492. return 'empty %s' % (self.typename)
  493. return '%s containing' % (self.typename)
  494. class StdStackOrQueuePrinter:
  495. "Print a std::stack or std::queue"
  496. def __init__ (self, typename, val):
  497. self.typename = strip_versioned_namespace(typename)
  498. self.visualizer = gdb.default_visualizer(val['c'])
  499. def children (self):
  500. return self.visualizer.children()
  501. def to_string (self):
  502. return '%s wrapping: %s' % (self.typename,
  503. self.visualizer.to_string())
  504. def display_hint (self):
  505. if hasattr (self.visualizer, 'display_hint'):
  506. return self.visualizer.display_hint ()
  507. return None
  508. class RbtreeIterator(Iterator):
  509. """
  510. Turn an RB-tree-based container (std::map, std::set etc.) into
  511. a Python iterable object.
  512. """
  513. def __init__(self, rbtree):
  514. self.size = rbtree['_M_t']['_M_impl']['_M_node_count']
  515. self.node = rbtree['_M_t']['_M_impl']['_M_header']['_M_left']
  516. self.count = 0
  517. def __iter__(self):
  518. return self
  519. def __len__(self):
  520. return int (self.size)
  521. def __next__(self):
  522. if self.count == self.size:
  523. raise StopIteration
  524. result = self.node
  525. self.count = self.count + 1
  526. if self.count < self.size:
  527. # Compute the next node.
  528. node = self.node
  529. if node.dereference()['_M_right']:
  530. node = node.dereference()['_M_right']
  531. while node.dereference()['_M_left']:
  532. node = node.dereference()['_M_left']
  533. else:
  534. parent = node.dereference()['_M_parent']
  535. while node == parent.dereference()['_M_right']:
  536. node = parent
  537. parent = parent.dereference()['_M_parent']
  538. if node.dereference()['_M_right'] != parent:
  539. node = parent
  540. self.node = node
  541. return result
  542. def get_value_from_Rb_tree_node(node):
  543. """Returns the value held in an _Rb_tree_node<_Val>"""
  544. try:
  545. member = node.type.fields()[1].name
  546. if member == '_M_value_field':
  547. # C++03 implementation, node contains the value as a member
  548. return node['_M_value_field']
  549. elif member == '_M_storage':
  550. # C++11 implementation, node stores value in __aligned_membuf
  551. valtype = node.type.template_argument(0)
  552. return get_value_from_aligned_membuf(node['_M_storage'], valtype)
  553. except:
  554. pass
  555. raise ValueError("Unsupported implementation for %s" % str(node.type))
  556. # This is a pretty printer for std::_Rb_tree_iterator (which is
  557. # std::map::iterator), and has nothing to do with the RbtreeIterator
  558. # class above.
  559. class StdRbtreeIteratorPrinter:
  560. "Print std::map::iterator, std::set::iterator, etc."
  561. def __init__ (self, typename, val):
  562. self.val = val
  563. nodetype = lookup_node_type('_Rb_tree_node', self.val.type)
  564. self.link_type = nodetype.pointer()
  565. def to_string (self):
  566. if not self.val['_M_node']:
  567. return 'non-dereferenceable iterator for associative container'
  568. node = self.val['_M_node'].cast(self.link_type).dereference()
  569. return str(get_value_from_Rb_tree_node(node))
  570. class StdDebugIteratorPrinter:
  571. "Print a debug enabled version of an iterator"
  572. def __init__ (self, typename, val):
  573. self.val = val
  574. # Just strip away the encapsulating __gnu_debug::_Safe_iterator
  575. # and return the wrapped iterator value.
  576. def to_string (self):
  577. base_type = gdb.lookup_type('__gnu_debug::_Safe_iterator_base')
  578. itype = self.val.type.template_argument(0)
  579. safe_seq = self.val.cast(base_type)['_M_sequence']
  580. if not safe_seq:
  581. return str(self.val.cast(itype))
  582. if self.val['_M_version'] != safe_seq['_M_version']:
  583. return "invalid iterator"
  584. return str(self.val.cast(itype))
  585. def num_elements(num):
  586. """Return either "1 element" or "N elements" depending on the argument."""
  587. return '1 element' if num == 1 else '%d elements' % num
  588. class StdMapPrinter:
  589. "Print a std::map or std::multimap"
  590. # Turn an RbtreeIterator into a pretty-print iterator.
  591. class _iter(Iterator):
  592. def __init__(self, rbiter, type):
  593. self.rbiter = rbiter
  594. self.count = 0
  595. self.type = type
  596. def __iter__(self):
  597. return self
  598. def __next__(self):
  599. if self.count % 2 == 0:
  600. n = next(self.rbiter)
  601. n = n.cast(self.type).dereference()
  602. n = get_value_from_Rb_tree_node(n)
  603. self.pair = n
  604. item = n['first']
  605. else:
  606. item = self.pair['second']
  607. result = ('[%d]' % self.count, item)
  608. self.count = self.count + 1
  609. return result
  610. def __init__ (self, typename, val):
  611. self.typename = strip_versioned_namespace(typename)
  612. self.val = val
  613. def to_string (self):
  614. return '%s with %s' % (self.typename,
  615. num_elements(len(RbtreeIterator (self.val))))
  616. def children (self):
  617. node = lookup_node_type('_Rb_tree_node', self.val.type).pointer()
  618. return self._iter (RbtreeIterator (self.val), node)
  619. def display_hint (self):
  620. return 'map'
  621. class StdSetPrinter:
  622. "Print a std::set or std::multiset"
  623. # Turn an RbtreeIterator into a pretty-print iterator.
  624. class _iter(Iterator):
  625. def __init__(self, rbiter, type):
  626. self.rbiter = rbiter
  627. self.count = 0
  628. self.type = type
  629. def __iter__(self):
  630. return self
  631. def __next__(self):
  632. item = next(self.rbiter)
  633. item = item.cast(self.type).dereference()
  634. item = get_value_from_Rb_tree_node(item)
  635. # FIXME: this is weird ... what to do?
  636. # Maybe a 'set' display hint?
  637. result = ('[%d]' % self.count, item)
  638. self.count = self.count + 1
  639. return result
  640. def __init__ (self, typename, val):
  641. self.typename = strip_versioned_namespace(typename)
  642. self.val = val
  643. def to_string (self):
  644. return '%s with %s' % (self.typename,
  645. num_elements(len(RbtreeIterator (self.val))))
  646. def children (self):
  647. node = lookup_node_type('_Rb_tree_node', self.val.type).pointer()
  648. return self._iter (RbtreeIterator (self.val), node)
  649. class StdBitsetPrinter:
  650. "Print a std::bitset"
  651. def __init__(self, typename, val):
  652. self.typename = strip_versioned_namespace(typename)
  653. self.val = val
  654. def to_string (self):
  655. # If template_argument handled values, we could print the
  656. # size. Or we could use a regexp on the type.
  657. return '%s' % (self.typename)
  658. def children (self):
  659. try:
  660. # An empty bitset may not have any members which will
  661. # result in an exception being thrown.
  662. words = self.val['_M_w']
  663. except:
  664. return []
  665. wtype = words.type
  666. # The _M_w member can be either an unsigned long, or an
  667. # array. This depends on the template specialization used.
  668. # If it is a single long, convert to a single element list.
  669. if wtype.code == gdb.TYPE_CODE_ARRAY:
  670. tsize = wtype.target ().sizeof
  671. else:
  672. words = [words]
  673. tsize = wtype.sizeof
  674. nwords = wtype.sizeof / tsize
  675. result = []
  676. byte = 0
  677. while byte < nwords:
  678. w = words[byte]
  679. bit = 0
  680. while w != 0:
  681. if (w & 1) != 0:
  682. # Another spot where we could use 'set'?
  683. result.append(('[%d]' % (byte * tsize * 8 + bit), 1))
  684. bit = bit + 1
  685. w = w >> 1
  686. byte = byte + 1
  687. return result
  688. class StdDequePrinter:
  689. "Print a std::deque"
  690. class _iter(Iterator):
  691. def __init__(self, node, start, end, last, buffer_size):
  692. self.node = node
  693. self.p = start
  694. self.end = end
  695. self.last = last
  696. self.buffer_size = buffer_size
  697. self.count = 0
  698. def __iter__(self):
  699. return self
  700. def __next__(self):
  701. if self.p == self.last:
  702. raise StopIteration
  703. result = ('[%d]' % self.count, self.p.dereference())
  704. self.count = self.count + 1
  705. # Advance the 'cur' pointer.
  706. self.p = self.p + 1
  707. if self.p == self.end:
  708. # If we got to the end of this bucket, move to the
  709. # next bucket.
  710. self.node = self.node + 1
  711. self.p = self.node[0]
  712. self.end = self.p + self.buffer_size
  713. return result
  714. def __init__(self, typename, val):
  715. self.typename = strip_versioned_namespace(typename)
  716. self.val = val
  717. self.elttype = val.type.template_argument(0)
  718. size = self.elttype.sizeof
  719. if size < 512:
  720. self.buffer_size = int (512 / size)
  721. else:
  722. self.buffer_size = 1
  723. def to_string(self):
  724. start = self.val['_M_impl']['_M_start']
  725. end = self.val['_M_impl']['_M_finish']
  726. delta_n = end['_M_node'] - start['_M_node'] - 1
  727. delta_s = start['_M_last'] - start['_M_cur']
  728. delta_e = end['_M_cur'] - end['_M_first']
  729. size = self.buffer_size * delta_n + delta_s + delta_e
  730. return '%s with %s' % (self.typename, num_elements(long(size)))
  731. def children(self):
  732. start = self.val['_M_impl']['_M_start']
  733. end = self.val['_M_impl']['_M_finish']
  734. return self._iter(start['_M_node'], start['_M_cur'], start['_M_last'],
  735. end['_M_cur'], self.buffer_size)
  736. def display_hint (self):
  737. return 'array'
  738. class StdDequeIteratorPrinter:
  739. "Print std::deque::iterator"
  740. def __init__(self, typename, val):
  741. self.val = val
  742. def to_string(self):
  743. if not self.val['_M_cur']:
  744. return 'non-dereferenceable iterator for std::deque'
  745. return str(self.val['_M_cur'].dereference())
  746. class StdStringPrinter:
  747. "Print a std::basic_string of some kind"
  748. def __init__(self, typename, val):
  749. self.val = val
  750. self.new_string = typename.find("::__cxx11::basic_string") != -1
  751. def to_string(self):
  752. # Make sure &string works, too.
  753. type = self.val.type
  754. if type.code == gdb.TYPE_CODE_REF:
  755. type = type.target ()
  756. # Calculate the length of the string so that to_string returns
  757. # the string according to length, not according to first null
  758. # encountered.
  759. ptr = self.val ['_M_dataplus']['_M_p']
  760. if self.new_string:
  761. length = self.val['_M_string_length']
  762. # https://sourceware.org/bugzilla/show_bug.cgi?id=17728
  763. ptr = ptr.cast(ptr.type.strip_typedefs())
  764. else:
  765. realtype = type.unqualified ().strip_typedefs ()
  766. reptype = gdb.lookup_type (str (realtype) + '::_Rep').pointer ()
  767. header = ptr.cast(reptype) - 1
  768. length = header.dereference ()['_M_length']
  769. if hasattr(ptr, "lazy_string"):
  770. return ptr.lazy_string (length = length)
  771. return ptr.string (length = length)
  772. def display_hint (self):
  773. return 'string'
  774. class Tr1HashtableIterator(Iterator):
  775. def __init__ (self, hashtable):
  776. self.buckets = hashtable['_M_buckets']
  777. self.bucket = 0
  778. self.bucket_count = hashtable['_M_bucket_count']
  779. self.node_type = find_type(hashtable.type, '_Node').pointer()
  780. self.node = 0
  781. while self.bucket != self.bucket_count:
  782. self.node = self.buckets[self.bucket]
  783. if self.node:
  784. break
  785. self.bucket = self.bucket + 1
  786. def __iter__ (self):
  787. return self
  788. def __next__ (self):
  789. if self.node == 0:
  790. raise StopIteration
  791. node = self.node.cast(self.node_type)
  792. result = node.dereference()['_M_v']
  793. self.node = node.dereference()['_M_next'];
  794. if self.node == 0:
  795. self.bucket = self.bucket + 1
  796. while self.bucket != self.bucket_count:
  797. self.node = self.buckets[self.bucket]
  798. if self.node:
  799. break
  800. self.bucket = self.bucket + 1
  801. return result
  802. class StdHashtableIterator(Iterator):
  803. def __init__(self, hashtable):
  804. self.node = hashtable['_M_before_begin']['_M_nxt']
  805. valtype = hashtable.type.template_argument(1)
  806. cached = hashtable.type.template_argument(9).template_argument(0)
  807. node_type = lookup_templ_spec('std::__detail::_Hash_node', str(valtype),
  808. 'true' if cached else 'false')
  809. self.node_type = node_type.pointer()
  810. def __iter__(self):
  811. return self
  812. def __next__(self):
  813. if self.node == 0:
  814. raise StopIteration
  815. elt = self.node.cast(self.node_type).dereference()
  816. self.node = elt['_M_nxt']
  817. valptr = elt['_M_storage'].address
  818. valptr = valptr.cast(elt.type.template_argument(0).pointer())
  819. return valptr.dereference()
  820. class Tr1UnorderedSetPrinter:
  821. "Print a std::unordered_set or tr1::unordered_set"
  822. def __init__ (self, typename, val):
  823. self.typename = strip_versioned_namespace(typename)
  824. self.val = val
  825. def hashtable (self):
  826. if self.typename.startswith('std::tr1'):
  827. return self.val
  828. return self.val['_M_h']
  829. def to_string (self):
  830. count = self.hashtable()['_M_element_count']
  831. return '%s with %s' % (self.typename, num_elements(count))
  832. @staticmethod
  833. def format_count (i):
  834. return '[%d]' % i
  835. def children (self):
  836. counter = imap (self.format_count, itertools.count())
  837. if self.typename.startswith('std::tr1'):
  838. return izip (counter, Tr1HashtableIterator (self.hashtable()))
  839. return izip (counter, StdHashtableIterator (self.hashtable()))
  840. class Tr1UnorderedMapPrinter:
  841. "Print a std::unordered_map or tr1::unordered_map"
  842. def __init__ (self, typename, val):
  843. self.typename = strip_versioned_namespace(typename)
  844. self.val = val
  845. def hashtable (self):
  846. if self.typename.startswith('std::tr1'):
  847. return self.val
  848. return self.val['_M_h']
  849. def to_string (self):
  850. count = self.hashtable()['_M_element_count']
  851. return '%s with %s' % (self.typename, num_elements(count))
  852. @staticmethod
  853. def flatten (list):
  854. for elt in list:
  855. for i in elt:
  856. yield i
  857. @staticmethod
  858. def format_one (elt):
  859. return (elt['first'], elt['second'])
  860. @staticmethod
  861. def format_count (i):
  862. return '[%d]' % i
  863. def children (self):
  864. counter = imap (self.format_count, itertools.count())
  865. # Map over the hash table and flatten the result.
  866. if self.typename.startswith('std::tr1'):
  867. data = self.flatten (imap (self.format_one, Tr1HashtableIterator (self.hashtable())))
  868. # Zip the two iterators together.
  869. return izip (counter, data)
  870. data = self.flatten (imap (self.format_one, StdHashtableIterator (self.hashtable())))
  871. # Zip the two iterators together.
  872. return izip (counter, data)
  873. def display_hint (self):
  874. return 'map'
  875. class StdForwardListPrinter:
  876. "Print a std::forward_list"
  877. class _iterator(Iterator):
  878. def __init__(self, nodetype, head):
  879. self.nodetype = nodetype
  880. self.base = head['_M_next']
  881. self.count = 0
  882. def __iter__(self):
  883. return self
  884. def __next__(self):
  885. if self.base == 0:
  886. raise StopIteration
  887. elt = self.base.cast(self.nodetype).dereference()
  888. self.base = elt['_M_next']
  889. count = self.count
  890. self.count = self.count + 1
  891. valptr = elt['_M_storage'].address
  892. valptr = valptr.cast(elt.type.template_argument(0).pointer())
  893. return ('[%d]' % count, valptr.dereference())
  894. def __init__(self, typename, val):
  895. self.val = val
  896. self.typename = strip_versioned_namespace(typename)
  897. def children(self):
  898. nodetype = lookup_node_type('_Fwd_list_node', self.val.type).pointer()
  899. return self._iterator(nodetype, self.val['_M_impl']['_M_head'])
  900. def to_string(self):
  901. if self.val['_M_impl']['_M_head']['_M_next'] == 0:
  902. return 'empty %s' % self.typename
  903. return '%s' % self.typename
  904. class SingleObjContainerPrinter(object):
  905. "Base class for printers of containers of single objects"
  906. def __init__ (self, val, viz, hint = None):
  907. self.contained_value = val
  908. self.visualizer = viz
  909. self.hint = hint
  910. def _recognize(self, type):
  911. """Return TYPE as a string after applying type printers"""
  912. global _use_type_printing
  913. if not _use_type_printing:
  914. return str(type)
  915. return gdb.types.apply_type_recognizers(gdb.types.get_type_recognizers(),
  916. type) or str(type)
  917. class _contained(Iterator):
  918. def __init__ (self, val):
  919. self.val = val
  920. def __iter__ (self):
  921. return self
  922. def __next__(self):
  923. if self.val is None:
  924. raise StopIteration
  925. retval = self.val
  926. self.val = None
  927. return ('[contained value]', retval)
  928. def children (self):
  929. if self.contained_value is None:
  930. return self._contained (None)
  931. if hasattr (self.visualizer, 'children'):
  932. return self.visualizer.children ()
  933. return self._contained (self.contained_value)
  934. def display_hint (self):
  935. # if contained value is a map we want to display in the same way
  936. if hasattr (self.visualizer, 'children') and hasattr (self.visualizer, 'display_hint'):
  937. return self.visualizer.display_hint ()
  938. return self.hint
  939. def function_pointer_to_name(f):
  940. "Find the name of the function referred to by the gdb.Value f, "
  941. " which should contain a function pointer from the program."
  942. # Turn the function pointer into an actual address.
  943. # This is needed to unpack ppc64 function descriptors.
  944. f = f.dereference().address
  945. if sys.version_info[0] == 2:
  946. # Older versions of GDB need to use long for Python 2,
  947. # because int(f) on 64-bit big-endian values raises a
  948. # gdb.error saying "Cannot convert value to int."
  949. f = long(f)
  950. else:
  951. f = int(f)
  952. try:
  953. # If the function can't be found older versions of GDB raise a
  954. # RuntimeError saying "Cannot locate object file for block."
  955. return gdb.block_for_pc(f).function.name
  956. except:
  957. return None
  958. class StdExpAnyPrinter(SingleObjContainerPrinter):
  959. "Print a std::any or std::experimental::any"
  960. def __init__ (self, typename, val):
  961. self.typename = strip_versioned_namespace(typename)
  962. self.typename = re.sub('^std::experimental::fundamentals_v\d::', 'std::experimental::', self.typename, 1)
  963. self.val = val
  964. self.contained_type = None
  965. contained_value = None
  966. visualizer = None
  967. mgr = self.val['_M_manager']
  968. if mgr != 0:
  969. func = function_pointer_to_name(mgr)
  970. if not func:
  971. raise ValueError("Invalid function pointer in %s" % (self.typename))
  972. rx = r"""({0}::_Manager_\w+<.*>)::_S_manage\((enum )?{0}::_Op, (const {0}|{0} const) ?\*, (union )?{0}::_Arg ?\*\)""".format(typename)
  973. m = re.match(rx, func)
  974. if not m:
  975. raise ValueError("Unknown manager function in %s" % self.typename)
  976. mgrname = m.group(1)
  977. # FIXME need to expand 'std::string' so that gdb.lookup_type works
  978. if 'std::string' in mgrname:
  979. mgrname = re.sub("std::string(?!\w)", str(gdb.lookup_type('std::string').strip_typedefs()), m.group(1))
  980. mgrtype = gdb.lookup_type(mgrname)
  981. self.contained_type = mgrtype.template_argument(0)
  982. valptr = None
  983. if '::_Manager_internal' in mgrname:
  984. valptr = self.val['_M_storage']['_M_buffer'].address
  985. elif '::_Manager_external' in mgrname:
  986. valptr = self.val['_M_storage']['_M_ptr']
  987. else:
  988. raise ValueError("Unknown manager function in %s" % self.typename)
  989. contained_value = valptr.cast(self.contained_type.pointer()).dereference()
  990. visualizer = gdb.default_visualizer(contained_value)
  991. super(StdExpAnyPrinter, self).__init__ (contained_value, visualizer)
  992. def to_string (self):
  993. if self.contained_type is None:
  994. return '%s [no contained value]' % self.typename
  995. desc = "%s containing " % self.typename
  996. if hasattr (self.visualizer, 'children'):
  997. return desc + self.visualizer.to_string ()
  998. valtype = self._recognize (self.contained_type)
  999. return desc + strip_versioned_namespace(str(valtype))
  1000. class StdExpOptionalPrinter(SingleObjContainerPrinter):
  1001. "Print a std::optional or std::experimental::optional"
  1002. def __init__ (self, typename, val):
  1003. valtype = self._recognize (val.type.template_argument(0))
  1004. typename = strip_versioned_namespace(typename)
  1005. self.typename = re.sub('^std::(experimental::|)(fundamentals_v\d::|)(.*)', r'std::\1\3<%s>' % valtype, typename, 1)
  1006. payload = val['_M_payload']
  1007. if self.typename.startswith('std::experimental'):
  1008. engaged = val['_M_engaged']
  1009. contained_value = payload
  1010. else:
  1011. engaged = payload['_M_engaged']
  1012. contained_value = payload['_M_payload']
  1013. try:
  1014. # Since GCC 9
  1015. contained_value = contained_value['_M_value']
  1016. except:
  1017. pass
  1018. visualizer = gdb.default_visualizer (contained_value)
  1019. if not engaged:
  1020. contained_value = None
  1021. super (StdExpOptionalPrinter, self).__init__ (contained_value, visualizer)
  1022. def to_string (self):
  1023. if self.contained_value is None:
  1024. return "%s [no contained value]" % self.typename
  1025. if hasattr (self.visualizer, 'children'):
  1026. return "%s containing %s" % (self.typename,
  1027. self.visualizer.to_string())
  1028. return self.typename
  1029. class StdVariantPrinter(SingleObjContainerPrinter):
  1030. "Print a std::variant"
  1031. def __init__(self, typename, val):
  1032. alternatives = get_template_arg_list(val.type)
  1033. self.typename = strip_versioned_namespace(typename)
  1034. self.typename = "%s<%s>" % (self.typename, ', '.join([self._recognize(alt) for alt in alternatives]))
  1035. self.index = val['_M_index']
  1036. if self.index >= len(alternatives):
  1037. self.contained_type = None
  1038. contained_value = None
  1039. visualizer = None
  1040. else:
  1041. self.contained_type = alternatives[int(self.index)]
  1042. addr = val['_M_u']['_M_first']['_M_storage'].address
  1043. contained_value = addr.cast(self.contained_type.pointer()).dereference()
  1044. visualizer = gdb.default_visualizer(contained_value)
  1045. super (StdVariantPrinter, self).__init__(contained_value, visualizer, 'array')
  1046. def to_string(self):
  1047. if self.contained_value is None:
  1048. return "%s [no contained value]" % self.typename
  1049. if hasattr(self.visualizer, 'children'):
  1050. return "%s [index %d] containing %s" % (self.typename, self.index,
  1051. self.visualizer.to_string())
  1052. return "%s [index %d]" % (self.typename, self.index)
  1053. class StdNodeHandlePrinter(SingleObjContainerPrinter):
  1054. "Print a container node handle"
  1055. def __init__(self, typename, val):
  1056. self.value_type = val.type.template_argument(1)
  1057. nodetype = val.type.template_argument(2).template_argument(0)
  1058. self.is_rb_tree_node = is_specialization_of(nodetype.name, '_Rb_tree_node')
  1059. self.is_map_node = val.type.template_argument(0) != self.value_type
  1060. nodeptr = val['_M_ptr']
  1061. if nodeptr:
  1062. if self.is_rb_tree_node:
  1063. contained_value = get_value_from_Rb_tree_node(nodeptr.dereference())
  1064. else:
  1065. contained_value = get_value_from_aligned_membuf(nodeptr['_M_storage'],
  1066. self.value_type)
  1067. visualizer = gdb.default_visualizer(contained_value)
  1068. else:
  1069. contained_value = None
  1070. visualizer = None
  1071. optalloc = val['_M_alloc']
  1072. self.alloc = optalloc['_M_payload'] if optalloc['_M_engaged'] else None
  1073. super(StdNodeHandlePrinter, self).__init__(contained_value, visualizer,
  1074. 'array')
  1075. def to_string(self):
  1076. desc = 'node handle for '
  1077. if not self.is_rb_tree_node:
  1078. desc += 'unordered '
  1079. if self.is_map_node:
  1080. desc += 'map';
  1081. else:
  1082. desc += 'set';
  1083. if self.contained_value:
  1084. desc += ' with element'
  1085. if hasattr(self.visualizer, 'children'):
  1086. return "%s = %s" % (desc, self.visualizer.to_string())
  1087. return desc
  1088. else:
  1089. return 'empty %s' % desc
  1090. class StdExpStringViewPrinter:
  1091. "Print a std::basic_string_view or std::experimental::basic_string_view"
  1092. def __init__ (self, typename, val):
  1093. self.val = val
  1094. def to_string (self):
  1095. ptr = self.val['_M_str']
  1096. len = self.val['_M_len']
  1097. if hasattr (ptr, "lazy_string"):
  1098. return ptr.lazy_string (length = len)
  1099. return ptr.string (length = len)
  1100. def display_hint (self):
  1101. return 'string'
  1102. class StdExpPathPrinter:
  1103. "Print a std::experimental::filesystem::path"
  1104. def __init__ (self, typename, val):
  1105. self.val = val
  1106. self.typename = typename
  1107. start = self.val['_M_cmpts']['_M_impl']['_M_start']
  1108. finish = self.val['_M_cmpts']['_M_impl']['_M_finish']
  1109. self.num_cmpts = int (finish - start)
  1110. def _path_type(self):
  1111. t = str(self.val['_M_type'])
  1112. if t[-9:] == '_Root_dir':
  1113. return "root-directory"
  1114. if t[-10:] == '_Root_name':
  1115. return "root-name"
  1116. return None
  1117. def to_string (self):
  1118. path = "%s" % self.val ['_M_pathname']
  1119. if self.num_cmpts == 0:
  1120. t = self._path_type()
  1121. if t:
  1122. path = '%s [%s]' % (path, t)
  1123. return "experimental::filesystem::path %s" % path
  1124. class _iterator(Iterator):
  1125. def __init__(self, cmpts, pathtype):
  1126. self.pathtype = pathtype
  1127. self.item = cmpts['_M_impl']['_M_start']
  1128. self.finish = cmpts['_M_impl']['_M_finish']
  1129. self.count = 0
  1130. def __iter__(self):
  1131. return self
  1132. def __next__(self):
  1133. if self.item == self.finish:
  1134. raise StopIteration
  1135. item = self.item.dereference()
  1136. count = self.count
  1137. self.count = self.count + 1
  1138. self.item = self.item + 1
  1139. path = item['_M_pathname']
  1140. t = StdExpPathPrinter(self.pathtype, item)._path_type()
  1141. if not t:
  1142. t = count
  1143. return ('[%s]' % t, path)
  1144. def children(self):
  1145. return self._iterator(self.val['_M_cmpts'], self.typename)
  1146. class StdPathPrinter:
  1147. "Print a std::filesystem::path"
  1148. def __init__ (self, typename, val):
  1149. self.val = val
  1150. self.typename = typename
  1151. impl = self.val['_M_cmpts']['_M_impl']['_M_t']['_M_t']['_M_head_impl']
  1152. self.type = impl.cast(gdb.lookup_type('uintptr_t')) & 3
  1153. if self.type == 0:
  1154. self.impl = impl
  1155. else:
  1156. self.impl = None
  1157. def _path_type(self):
  1158. t = str(self.type.cast(gdb.lookup_type(self.typename + '::_Type')))
  1159. if t[-9:] == '_Root_dir':
  1160. return "root-directory"
  1161. if t[-10:] == '_Root_name':
  1162. return "root-name"
  1163. return None
  1164. def to_string (self):
  1165. path = "%s" % self.val ['_M_pathname']
  1166. if self.type != 0:
  1167. t = self._path_type()
  1168. if t:
  1169. path = '%s [%s]' % (path, t)
  1170. return "filesystem::path %s" % path
  1171. class _iterator(Iterator):
  1172. def __init__(self, impl, pathtype):
  1173. self.pathtype = pathtype
  1174. if impl:
  1175. # We can't access _Impl::_M_size because _Impl is incomplete
  1176. # so cast to int* to access the _M_size member at offset zero,
  1177. int_type = gdb.lookup_type('int')
  1178. cmpt_type = gdb.lookup_type(pathtype+'::_Cmpt')
  1179. char_type = gdb.lookup_type('char')
  1180. impl = impl.cast(int_type.pointer())
  1181. size = impl.dereference()
  1182. #self.capacity = (impl + 1).dereference()
  1183. if hasattr(gdb.Type, 'alignof'):
  1184. sizeof_Impl = max(2 * int_type.sizeof, cmpt_type.alignof)
  1185. else:
  1186. sizeof_Impl = 2 * int_type.sizeof
  1187. begin = impl.cast(char_type.pointer()) + sizeof_Impl
  1188. self.item = begin.cast(cmpt_type.pointer())
  1189. self.finish = self.item + size
  1190. self.count = 0
  1191. else:
  1192. self.item = None
  1193. self.finish = None
  1194. def __iter__(self):
  1195. return self
  1196. def __next__(self):
  1197. if self.item == self.finish:
  1198. raise StopIteration
  1199. item = self.item.dereference()
  1200. count = self.count
  1201. self.count = self.count + 1
  1202. self.item = self.item + 1
  1203. path = item['_M_pathname']
  1204. t = StdPathPrinter(self.pathtype, item)._path_type()
  1205. if not t:
  1206. t = count
  1207. return ('[%s]' % t, path)
  1208. def children(self):
  1209. return self._iterator(self.impl, self.typename)
  1210. class StdPairPrinter:
  1211. "Print a std::pair object, with 'first' and 'second' as children"
  1212. def __init__(self, typename, val):
  1213. self.val = val
  1214. class _iter(Iterator):
  1215. "An iterator for std::pair types. Returns 'first' then 'second'."
  1216. def __init__(self, val):
  1217. self.val = val
  1218. self.which = 'first'
  1219. def __iter__(self):
  1220. return self
  1221. def __next__(self):
  1222. if self.which is None:
  1223. raise StopIteration
  1224. which = self.which
  1225. if which == 'first':
  1226. self.which = 'second'
  1227. else:
  1228. self.which = None
  1229. return (which, self.val[which])
  1230. def children(self):
  1231. return self._iter(self.val)
  1232. def to_string(self):
  1233. return None
  1234. class StdCmpCatPrinter:
  1235. "Print a comparison category object"
  1236. def __init__ (self, typename, val):
  1237. self.typename = typename[typename.rfind(':')+1:]
  1238. self.val = val['_M_value']
  1239. def to_string (self):
  1240. if self.typename == 'strong_ordering' and self.val == 0:
  1241. name = 'equal'
  1242. else:
  1243. names = {2:'unordered', -1:'less', 0:'equivalent', 1:'greater'}
  1244. name = names[int(self.val)]
  1245. return 'std::{}::{}'.format(self.typename, name)
  1246. # A "regular expression" printer which conforms to the
  1247. # "SubPrettyPrinter" protocol from gdb.printing.
  1248. class RxPrinter(object):
  1249. def __init__(self, name, function):
  1250. super(RxPrinter, self).__init__()
  1251. self.name = name
  1252. self.function = function
  1253. self.enabled = True
  1254. def invoke(self, value):
  1255. if not self.enabled:
  1256. return None
  1257. if value.type.code == gdb.TYPE_CODE_REF:
  1258. if hasattr(gdb.Value,"referenced_value"):
  1259. value = value.referenced_value()
  1260. return self.function(self.name, value)
  1261. # A pretty-printer that conforms to the "PrettyPrinter" protocol from
  1262. # gdb.printing. It can also be used directly as an old-style printer.
  1263. class Printer(object):
  1264. def __init__(self, name):
  1265. super(Printer, self).__init__()
  1266. self.name = name
  1267. self.subprinters = []
  1268. self.lookup = {}
  1269. self.enabled = True
  1270. self.compiled_rx = re.compile('^([a-zA-Z0-9_:]+)(<.*>)?$')
  1271. def add(self, name, function):
  1272. # A small sanity check.
  1273. # FIXME
  1274. if not self.compiled_rx.match(name):
  1275. raise ValueError('libstdc++ programming error: "%s" does not match' % name)
  1276. printer = RxPrinter(name, function)
  1277. self.subprinters.append(printer)
  1278. self.lookup[name] = printer
  1279. # Add a name using _GLIBCXX_BEGIN_NAMESPACE_VERSION.
  1280. def add_version(self, base, name, function):
  1281. self.add(base + name, function)
  1282. if _versioned_namespace:
  1283. vbase = re.sub('^(std|__gnu_cxx)::', r'\g<0>%s' % _versioned_namespace, base)
  1284. self.add(vbase + name, function)
  1285. # Add a name using _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
  1286. def add_container(self, base, name, function):
  1287. self.add_version(base, name, function)
  1288. self.add_version(base + '__cxx1998::', name, function)
  1289. @staticmethod
  1290. def get_basic_type(type):
  1291. # If it points to a reference, get the reference.
  1292. if type.code == gdb.TYPE_CODE_REF:
  1293. type = type.target ()
  1294. # Get the unqualified type, stripped of typedefs.
  1295. type = type.unqualified ().strip_typedefs ()
  1296. return type.tag
  1297. def __call__(self, val):
  1298. typename = self.get_basic_type(val.type)
  1299. if not typename:
  1300. return None
  1301. # All the types we match are template types, so we can use a
  1302. # dictionary.
  1303. match = self.compiled_rx.match(typename)
  1304. if not match:
  1305. return None
  1306. basename = match.group(1)
  1307. if val.type.code == gdb.TYPE_CODE_REF:
  1308. if hasattr(gdb.Value,"referenced_value"):
  1309. val = val.referenced_value()
  1310. if basename in self.lookup:
  1311. return self.lookup[basename].invoke(val)
  1312. # Cannot find a pretty printer. Return None.
  1313. return None
  1314. libstdcxx_printer = None
  1315. class TemplateTypePrinter(object):
  1316. r"""
  1317. A type printer for class templates with default template arguments.
  1318. Recognizes specializations of class templates and prints them without
  1319. any template arguments that use a default template argument.
  1320. Type printers are recursively applied to the template arguments.
  1321. e.g. replace "std::vector<T, std::allocator<T> >" with "std::vector<T>".
  1322. """
  1323. def __init__(self, name, defargs):
  1324. self.name = name
  1325. self.defargs = defargs
  1326. self.enabled = True
  1327. class _recognizer(object):
  1328. "The recognizer class for TemplateTypePrinter."
  1329. def __init__(self, name, defargs):
  1330. self.name = name
  1331. self.defargs = defargs
  1332. # self.type_obj = None
  1333. def recognize(self, type_obj):
  1334. """
  1335. If type_obj is a specialization of self.name that uses all the
  1336. default template arguments for the class template, then return
  1337. a string representation of the type without default arguments.
  1338. Otherwise, return None.
  1339. """
  1340. if type_obj.tag is None:
  1341. return None
  1342. if not type_obj.tag.startswith(self.name):
  1343. return None
  1344. template_args = get_template_arg_list(type_obj)
  1345. displayed_args = []
  1346. require_defaulted = False
  1347. for n in range(len(template_args)):
  1348. # The actual template argument in the type:
  1349. targ = template_args[n]
  1350. # The default template argument for the class template:
  1351. defarg = self.defargs.get(n)
  1352. if defarg is not None:
  1353. # Substitute other template arguments into the default:
  1354. defarg = defarg.format(*template_args)
  1355. # Fail to recognize the type (by returning None)
  1356. # unless the actual argument is the same as the default.
  1357. try:
  1358. if targ != gdb.lookup_type(defarg):
  1359. return None
  1360. except gdb.error:
  1361. # Type lookup failed, just use string comparison:
  1362. if targ.tag != defarg:
  1363. return None
  1364. # All subsequent args must have defaults:
  1365. require_defaulted = True
  1366. elif require_defaulted:
  1367. return None
  1368. else:
  1369. # Recursively apply recognizers to the template argument
  1370. # and add it to the arguments that will be displayed:
  1371. displayed_args.append(self._recognize_subtype(targ))
  1372. # This assumes no class templates in the nested-name-specifier:
  1373. template_name = type_obj.tag[0:type_obj.tag.find('<')]
  1374. template_name = strip_inline_namespaces(template_name)
  1375. return template_name + '<' + ', '.join(displayed_args) + '>'
  1376. def _recognize_subtype(self, type_obj):
  1377. """Convert a gdb.Type to a string by applying recognizers,
  1378. or if that fails then simply converting to a string."""
  1379. if type_obj.code == gdb.TYPE_CODE_PTR:
  1380. return self._recognize_subtype(type_obj.target()) + '*'
  1381. if type_obj.code == gdb.TYPE_CODE_ARRAY:
  1382. type_str = self._recognize_subtype(type_obj.target())
  1383. if str(type_obj.strip_typedefs()).endswith('[]'):
  1384. return type_str + '[]' # array of unknown bound
  1385. return "%s[%d]" % (type_str, type_obj.range()[1] + 1)
  1386. if type_obj.code == gdb.TYPE_CODE_REF:
  1387. return self._recognize_subtype(type_obj.target()) + '&'
  1388. if hasattr(gdb, 'TYPE_CODE_RVALUE_REF'):
  1389. if type_obj.code == gdb.TYPE_CODE_RVALUE_REF:
  1390. return self._recognize_subtype(type_obj.target()) + '&&'
  1391. type_str = gdb.types.apply_type_recognizers(
  1392. gdb.types.get_type_recognizers(), type_obj)
  1393. if type_str:
  1394. return type_str
  1395. return str(type_obj)
  1396. def instantiate(self):
  1397. "Return a recognizer object for this type printer."
  1398. return self._recognizer(self.name, self.defargs)
  1399. def add_one_template_type_printer(obj, name, defargs):
  1400. r"""
  1401. Add a type printer for a class template with default template arguments.
  1402. Args:
  1403. name (str): The template-name of the class template.
  1404. defargs (dict int:string) The default template arguments.
  1405. Types in defargs can refer to the Nth template-argument using {N}
  1406. (with zero-based indices).
  1407. e.g. 'unordered_map' has these defargs:
  1408. { 2: 'std::hash<{0}>',
  1409. 3: 'std::equal_to<{0}>',
  1410. 4: 'std::allocator<std::pair<const {0}, {1}> >' }
  1411. """
  1412. printer = TemplateTypePrinter('std::'+name, defargs)
  1413. gdb.types.register_type_printer(obj, printer)
  1414. # Add type printer for same type in debug namespace:
  1415. printer = TemplateTypePrinter('std::__debug::'+name, defargs)
  1416. gdb.types.register_type_printer(obj, printer)
  1417. if _versioned_namespace:
  1418. # Add second type printer for same type in versioned namespace:
  1419. ns = 'std::' + _versioned_namespace
  1420. # PR 86112 Cannot use dict comprehension here:
  1421. defargs = dict((n, d.replace('std::', ns)) for (n,d) in defargs.items())
  1422. printer = TemplateTypePrinter(ns+name, defargs)
  1423. gdb.types.register_type_printer(obj, printer)
  1424. class FilteringTypePrinter(object):
  1425. r"""
  1426. A type printer that uses typedef names for common template specializations.
  1427. Args:
  1428. match (str): The class template to recognize.
  1429. name (str): The typedef-name that will be used instead.
  1430. Checks if a specialization of the class template 'match' is the same type
  1431. as the typedef 'name', and prints it as 'name' instead.
  1432. e.g. if an instantiation of std::basic_istream<C, T> is the same type as
  1433. std::istream then print it as std::istream.
  1434. """
  1435. def __init__(self, match, name):
  1436. self.match = match
  1437. self.name = name
  1438. self.enabled = True
  1439. class _recognizer(object):
  1440. "The recognizer class for TemplateTypePrinter."
  1441. def __init__(self, match, name):
  1442. self.match = match
  1443. self.name = name
  1444. self.type_obj = None
  1445. def recognize(self, type_obj):
  1446. """
  1447. If type_obj starts with self.match and is the same type as
  1448. self.name then return self.name, otherwise None.
  1449. """
  1450. if type_obj.tag is None:
  1451. return None
  1452. if self.type_obj is None:
  1453. if not type_obj.tag.startswith(self.match):
  1454. # Filter didn't match.
  1455. return None
  1456. try:
  1457. self.type_obj = gdb.lookup_type(self.name).strip_typedefs()
  1458. except:
  1459. pass
  1460. if self.type_obj == type_obj:
  1461. return strip_inline_namespaces(self.name)
  1462. return None
  1463. def instantiate(self):
  1464. "Return a recognizer object for this type printer."
  1465. return self._recognizer(self.match, self.name)
  1466. def add_one_type_printer(obj, match, name):
  1467. printer = FilteringTypePrinter('std::' + match, 'std::' + name)
  1468. gdb.types.register_type_printer(obj, printer)
  1469. if _versioned_namespace:
  1470. ns = 'std::' + _versioned_namespace
  1471. printer = FilteringTypePrinter(ns + match, ns + name)
  1472. gdb.types.register_type_printer(obj, printer)
  1473. def register_type_printers(obj):
  1474. global _use_type_printing
  1475. if not _use_type_printing:
  1476. return
  1477. # Add type printers for typedefs std::string, std::wstring etc.
  1478. for ch in ('', 'w', 'u8', 'u16', 'u32'):
  1479. add_one_type_printer(obj, 'basic_string', ch + 'string')
  1480. add_one_type_printer(obj, '__cxx11::basic_string', ch + 'string')
  1481. # Typedefs for __cxx11::basic_string used to be in namespace __cxx11:
  1482. add_one_type_printer(obj, '__cxx11::basic_string',
  1483. '__cxx11::' + ch + 'string')
  1484. add_one_type_printer(obj, 'basic_string_view', ch + 'string_view')
  1485. # Add type printers for typedefs std::istream, std::wistream etc.
  1486. for ch in ('', 'w'):
  1487. for x in ('ios', 'streambuf', 'istream', 'ostream', 'iostream',
  1488. 'filebuf', 'ifstream', 'ofstream', 'fstream'):
  1489. add_one_type_printer(obj, 'basic_' + x, ch + x)
  1490. for x in ('stringbuf', 'istringstream', 'ostringstream',
  1491. 'stringstream'):
  1492. add_one_type_printer(obj, 'basic_' + x, ch + x)
  1493. # <sstream> types are in __cxx11 namespace, but typedefs aren't:
  1494. add_one_type_printer(obj, '__cxx11::basic_' + x, ch + x)
  1495. # Add type printers for typedefs regex, wregex, cmatch, wcmatch etc.
  1496. for abi in ('', '__cxx11::'):
  1497. for ch in ('', 'w'):
  1498. add_one_type_printer(obj, abi + 'basic_regex', abi + ch + 'regex')
  1499. for ch in ('c', 's', 'wc', 'ws'):
  1500. add_one_type_printer(obj, abi + 'match_results', abi + ch + 'match')
  1501. for x in ('sub_match', 'regex_iterator', 'regex_token_iterator'):
  1502. add_one_type_printer(obj, abi + x, abi + ch + x)
  1503. # Note that we can't have a printer for std::wstreampos, because
  1504. # it is the same type as std::streampos.
  1505. add_one_type_printer(obj, 'fpos', 'streampos')
  1506. # Add type printers for <chrono> typedefs.
  1507. for dur in ('nanoseconds', 'microseconds', 'milliseconds',
  1508. 'seconds', 'minutes', 'hours'):
  1509. add_one_type_printer(obj, 'duration', dur)
  1510. # Add type printers for <random> typedefs.
  1511. add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand0')
  1512. add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand')
  1513. add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937')
  1514. add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937_64')
  1515. add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux24_base')
  1516. add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux48_base')
  1517. add_one_type_printer(obj, 'discard_block_engine', 'ranlux24')
  1518. add_one_type_printer(obj, 'discard_block_engine', 'ranlux48')
  1519. add_one_type_printer(obj, 'shuffle_order_engine', 'knuth_b')
  1520. # Add type printers for experimental::basic_string_view typedefs.
  1521. ns = 'experimental::fundamentals_v1::'
  1522. for ch in ('', 'w', 'u8', 'u16', 'u32'):
  1523. add_one_type_printer(obj, ns + 'basic_string_view',
  1524. ns + ch + 'string_view')
  1525. # Do not show defaulted template arguments in class templates.
  1526. add_one_template_type_printer(obj, 'unique_ptr',
  1527. { 1: 'std::default_delete<{0}>' })
  1528. add_one_template_type_printer(obj, 'deque', { 1: 'std::allocator<{0}>'})
  1529. add_one_template_type_printer(obj, 'forward_list', { 1: 'std::allocator<{0}>'})
  1530. add_one_template_type_printer(obj, 'list', { 1: 'std::allocator<{0}>'})
  1531. add_one_template_type_printer(obj, '__cxx11::list', { 1: 'std::allocator<{0}>'})
  1532. add_one_template_type_printer(obj, 'vector', { 1: 'std::allocator<{0}>'})
  1533. add_one_template_type_printer(obj, 'map',
  1534. { 2: 'std::less<{0}>',
  1535. 3: 'std::allocator<std::pair<{0} const, {1}>>' })
  1536. add_one_template_type_printer(obj, 'multimap',
  1537. { 2: 'std::less<{0}>',
  1538. 3: 'std::allocator<std::pair<{0} const, {1}>>' })
  1539. add_one_template_type_printer(obj, 'set',
  1540. { 1: 'std::less<{0}>', 2: 'std::allocator<{0}>' })
  1541. add_one_template_type_printer(obj, 'multiset',
  1542. { 1: 'std::less<{0}>', 2: 'std::allocator<{0}>' })
  1543. add_one_template_type_printer(obj, 'unordered_map',
  1544. { 2: 'std::hash<{0}>',
  1545. 3: 'std::equal_to<{0}>',
  1546. 4: 'std::allocator<std::pair<{0} const, {1}>>'})
  1547. add_one_template_type_printer(obj, 'unordered_multimap',
  1548. { 2: 'std::hash<{0}>',
  1549. 3: 'std::equal_to<{0}>',
  1550. 4: 'std::allocator<std::pair<{0} const, {1}>>'})
  1551. add_one_template_type_printer(obj, 'unordered_set',
  1552. { 1: 'std::hash<{0}>',
  1553. 2: 'std::equal_to<{0}>',
  1554. 3: 'std::allocator<{0}>'})
  1555. add_one_template_type_printer(obj, 'unordered_multiset',
  1556. { 1: 'std::hash<{0}>',
  1557. 2: 'std::equal_to<{0}>',
  1558. 3: 'std::allocator<{0}>'})
  1559. def register_libstdcxx_printers (obj):
  1560. "Register libstdc++ pretty-printers with objfile Obj."
  1561. global _use_gdb_pp
  1562. global libstdcxx_printer
  1563. if _use_gdb_pp:
  1564. gdb.printing.register_pretty_printer(obj, libstdcxx_printer)
  1565. else:
  1566. if obj is None:
  1567. obj = gdb
  1568. obj.pretty_printers.append(libstdcxx_printer)
  1569. register_type_printers(obj)
  1570. def build_libstdcxx_dictionary ():
  1571. global libstdcxx_printer
  1572. libstdcxx_printer = Printer("libstdc++-v6")
  1573. # libstdc++ objects requiring pretty-printing.
  1574. # In order from:
  1575. # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
  1576. libstdcxx_printer.add_version('std::', 'basic_string', StdStringPrinter)
  1577. libstdcxx_printer.add_version('std::__cxx11::', 'basic_string', StdStringPrinter)
  1578. libstdcxx_printer.add_container('std::', 'bitset', StdBitsetPrinter)
  1579. libstdcxx_printer.add_container('std::', 'deque', StdDequePrinter)
  1580. libstdcxx_printer.add_container('std::', 'list', StdListPrinter)
  1581. libstdcxx_printer.add_container('std::__cxx11::', 'list', StdListPrinter)
  1582. libstdcxx_printer.add_container('std::', 'map', StdMapPrinter)
  1583. libstdcxx_printer.add_container('std::', 'multimap', StdMapPrinter)
  1584. libstdcxx_printer.add_container('std::', 'multiset', StdSetPrinter)
  1585. libstdcxx_printer.add_version('std::', 'pair', StdPairPrinter)
  1586. libstdcxx_printer.add_version('std::', 'priority_queue',
  1587. StdStackOrQueuePrinter)
  1588. libstdcxx_printer.add_version('std::', 'queue', StdStackOrQueuePrinter)
  1589. libstdcxx_printer.add_version('std::', 'tuple', StdTuplePrinter)
  1590. libstdcxx_printer.add_container('std::', 'set', StdSetPrinter)
  1591. libstdcxx_printer.add_version('std::', 'stack', StdStackOrQueuePrinter)
  1592. libstdcxx_printer.add_version('std::', 'unique_ptr', UniquePointerPrinter)
  1593. libstdcxx_printer.add_container('std::', 'vector', StdVectorPrinter)
  1594. # vector<bool>
  1595. # Printer registrations for classes compiled with -D_GLIBCXX_DEBUG.
  1596. libstdcxx_printer.add('std::__debug::bitset', StdBitsetPrinter)
  1597. libstdcxx_printer.add('std::__debug::deque', StdDequePrinter)
  1598. libstdcxx_printer.add('std::__debug::list', StdListPrinter)
  1599. libstdcxx_printer.add('std::__debug::map', StdMapPrinter)
  1600. libstdcxx_printer.add('std::__debug::multimap', StdMapPrinter)
  1601. libstdcxx_printer.add('std::__debug::multiset', StdSetPrinter)
  1602. libstdcxx_printer.add('std::__debug::priority_queue',
  1603. StdStackOrQueuePrinter)
  1604. libstdcxx_printer.add('std::__debug::queue', StdStackOrQueuePrinter)
  1605. libstdcxx_printer.add('std::__debug::set', StdSetPrinter)
  1606. libstdcxx_printer.add('std::__debug::stack', StdStackOrQueuePrinter)
  1607. libstdcxx_printer.add('std::__debug::unique_ptr', UniquePointerPrinter)
  1608. libstdcxx_printer.add('std::__debug::vector', StdVectorPrinter)
  1609. # These are the TR1 and C++11 printers.
  1610. # For array - the default GDB pretty-printer seems reasonable.
  1611. libstdcxx_printer.add_version('std::', 'shared_ptr', SharedPointerPrinter)
  1612. libstdcxx_printer.add_version('std::', 'weak_ptr', SharedPointerPrinter)
  1613. libstdcxx_printer.add_container('std::', 'unordered_map',
  1614. Tr1UnorderedMapPrinter)
  1615. libstdcxx_printer.add_container('std::', 'unordered_set',
  1616. Tr1UnorderedSetPrinter)
  1617. libstdcxx_printer.add_container('std::', 'unordered_multimap',
  1618. Tr1UnorderedMapPrinter)
  1619. libstdcxx_printer.add_container('std::', 'unordered_multiset',
  1620. Tr1UnorderedSetPrinter)
  1621. libstdcxx_printer.add_container('std::', 'forward_list',
  1622. StdForwardListPrinter)
  1623. libstdcxx_printer.add_version('std::tr1::', 'shared_ptr', SharedPointerPrinter)
  1624. libstdcxx_printer.add_version('std::tr1::', 'weak_ptr', SharedPointerPrinter)
  1625. libstdcxx_printer.add_version('std::tr1::', 'unordered_map',
  1626. Tr1UnorderedMapPrinter)
  1627. libstdcxx_printer.add_version('std::tr1::', 'unordered_set',
  1628. Tr1UnorderedSetPrinter)
  1629. libstdcxx_printer.add_version('std::tr1::', 'unordered_multimap',
  1630. Tr1UnorderedMapPrinter)
  1631. libstdcxx_printer.add_version('std::tr1::', 'unordered_multiset',
  1632. Tr1UnorderedSetPrinter)
  1633. # These are the C++11 printer registrations for -D_GLIBCXX_DEBUG cases.
  1634. # The tr1 namespace containers do not have any debug equivalents,
  1635. # so do not register printers for them.
  1636. libstdcxx_printer.add('std::__debug::unordered_map',
  1637. Tr1UnorderedMapPrinter)
  1638. libstdcxx_printer.add('std::__debug::unordered_set',
  1639. Tr1UnorderedSetPrinter)
  1640. libstdcxx_printer.add('std::__debug::unordered_multimap',
  1641. Tr1UnorderedMapPrinter)
  1642. libstdcxx_printer.add('std::__debug::unordered_multiset',
  1643. Tr1UnorderedSetPrinter)
  1644. libstdcxx_printer.add('std::__debug::forward_list',
  1645. StdForwardListPrinter)
  1646. # Library Fundamentals TS components
  1647. libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
  1648. 'any', StdExpAnyPrinter)
  1649. libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
  1650. 'optional', StdExpOptionalPrinter)
  1651. libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
  1652. 'basic_string_view', StdExpStringViewPrinter)
  1653. # Filesystem TS components
  1654. libstdcxx_printer.add_version('std::experimental::filesystem::v1::',
  1655. 'path', StdExpPathPrinter)
  1656. libstdcxx_printer.add_version('std::experimental::filesystem::v1::__cxx11::',
  1657. 'path', StdExpPathPrinter)
  1658. libstdcxx_printer.add_version('std::filesystem::',
  1659. 'path', StdPathPrinter)
  1660. libstdcxx_printer.add_version('std::filesystem::__cxx11::',
  1661. 'path', StdPathPrinter)
  1662. # C++17 components
  1663. libstdcxx_printer.add_version('std::',
  1664. 'any', StdExpAnyPrinter)
  1665. libstdcxx_printer.add_version('std::',
  1666. 'optional', StdExpOptionalPrinter)
  1667. libstdcxx_printer.add_version('std::',
  1668. 'basic_string_view', StdExpStringViewPrinter)
  1669. libstdcxx_printer.add_version('std::',
  1670. 'variant', StdVariantPrinter)
  1671. libstdcxx_printer.add_version('std::',
  1672. '_Node_handle', StdNodeHandlePrinter)
  1673. # C++20 components
  1674. libstdcxx_printer.add_version('std::', 'partial_ordering', StdCmpCatPrinter)
  1675. libstdcxx_printer.add_version('std::', 'weak_ordering', StdCmpCatPrinter)
  1676. libstdcxx_printer.add_version('std::', 'strong_ordering', StdCmpCatPrinter)
  1677. # Extensions.
  1678. libstdcxx_printer.add_version('__gnu_cxx::', 'slist', StdSlistPrinter)
  1679. if True:
  1680. # These shouldn't be necessary, if GDB "print *i" worked.
  1681. # But it often doesn't, so here they are.
  1682. libstdcxx_printer.add_container('std::', '_List_iterator',
  1683. StdListIteratorPrinter)
  1684. libstdcxx_printer.add_container('std::', '_List_const_iterator',
  1685. StdListIteratorPrinter)
  1686. libstdcxx_printer.add_version('std::', '_Rb_tree_iterator',
  1687. StdRbtreeIteratorPrinter)
  1688. libstdcxx_printer.add_version('std::', '_Rb_tree_const_iterator',
  1689. StdRbtreeIteratorPrinter)
  1690. libstdcxx_printer.add_container('std::', '_Deque_iterator',
  1691. StdDequeIteratorPrinter)
  1692. libstdcxx_printer.add_container('std::', '_Deque_const_iterator',
  1693. StdDequeIteratorPrinter)
  1694. libstdcxx_printer.add_version('__gnu_cxx::', '__normal_iterator',
  1695. StdVectorIteratorPrinter)
  1696. libstdcxx_printer.add_version('std::', '_Bit_iterator',
  1697. StdBitIteratorPrinter)
  1698. libstdcxx_printer.add_version('std::', '_Bit_const_iterator',
  1699. StdBitIteratorPrinter)
  1700. libstdcxx_printer.add_version('std::', '_Bit_reference',
  1701. StdBitReferencePrinter)
  1702. libstdcxx_printer.add_version('__gnu_cxx::', '_Slist_iterator',
  1703. StdSlistIteratorPrinter)
  1704. libstdcxx_printer.add_container('std::', '_Fwd_list_iterator',
  1705. StdFwdListIteratorPrinter)
  1706. libstdcxx_printer.add_container('std::', '_Fwd_list_const_iterator',
  1707. StdFwdListIteratorPrinter)
  1708. # Debug (compiled with -D_GLIBCXX_DEBUG) printer
  1709. # registrations.
  1710. libstdcxx_printer.add('__gnu_debug::_Safe_iterator',
  1711. StdDebugIteratorPrinter)
  1712. build_libstdcxx_dictionary ()