printers.py 74 KB

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