gdbhooks.py (TreePrinter.to_string): Recognize ggc_free'd memory.
[gcc.git] / gcc / gdbhooks.py
1 # Python hooks for gdb for debugging GCC
2 # Copyright (C) 2013-2019 Free Software Foundation, Inc.
3
4 # Contributed by David Malcolm <dmalcolm@redhat.com>
5
6 # This file is part of GCC.
7
8 # GCC is free software; you can redistribute it and/or modify it under
9 # the terms of the GNU General Public License as published by the Free
10 # Software Foundation; either version 3, or (at your option) any later
11 # version.
12
13 # GCC is distributed in the hope that it will be useful, but WITHOUT
14 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 # for more details.
17
18 # You should have received a copy of the GNU General Public License
19 # along with GCC; see the file COPYING3. If not see
20 # <http://www.gnu.org/licenses/>.
21
22 """
23 Enabling the debugging hooks
24 ----------------------------
25 gcc/configure (from configure.ac) generates a .gdbinit within the "gcc"
26 subdirectory of the build directory, and when run by gdb, this imports
27 gcc/gdbhooks.py from the source directory, injecting useful Python code
28 into gdb.
29
30 You may see a message from gdb of the form:
31 "path-to-build/gcc/.gdbinit" auto-loading has been declined by your `auto-load safe-path'
32 as a protection against untrustworthy python scripts. See
33 http://sourceware.org/gdb/onlinedocs/gdb/Auto_002dloading-safe-path.html
34
35 The fix is to mark the paths of the build/gcc directory as trustworthy.
36 An easy way to do so is by adding the following to your ~/.gdbinit script:
37 add-auto-load-safe-path /absolute/path/to/build/gcc
38 for the build directories for your various checkouts of gcc.
39
40 If it's working, you should see the message:
41 Successfully loaded GDB hooks for GCC
42 as gdb starts up.
43
44 During development, I've been manually invoking the code in this way, as a
45 precanned way of printing a variety of different kinds of value:
46
47 gdb \
48 -ex "break expand_gimple_stmt" \
49 -ex "run" \
50 -ex "bt" \
51 --args \
52 ./cc1 foo.c -O3
53
54 Examples of output using the pretty-printers
55 --------------------------------------------
56 Pointer values are generally shown in the form:
57 <type address extra_info>
58
59 For example, an opt_pass* might appear as:
60 (gdb) p pass
61 $2 = <opt_pass* 0x188b600 "expand"(170)>
62
63 The name of the pass is given ("expand"), together with the
64 static_pass_number.
65
66 Note that you can dereference the pointer in the normal way:
67 (gdb) p *pass
68 $4 = {type = RTL_PASS, name = 0x120a312 "expand",
69 [etc, ...snipped...]
70
71 and you can suppress pretty-printers using /r (for "raw"):
72 (gdb) p /r pass
73 $3 = (opt_pass *) 0x188b600
74
75 Basic blocks are shown with their index in parentheses, apart from the
76 CFG's entry and exit blocks, which are given as "ENTRY" and "EXIT":
77 (gdb) p bb
78 $9 = <basic_block 0x7ffff041f1a0 (2)>
79 (gdb) p cfun->cfg->x_entry_block_ptr
80 $10 = <basic_block 0x7ffff041f0d0 (ENTRY)>
81 (gdb) p cfun->cfg->x_exit_block_ptr
82 $11 = <basic_block 0x7ffff041f138 (EXIT)>
83
84 CFG edges are shown with the src and dest blocks given in parentheses:
85 (gdb) p e
86 $1 = <edge 0x7ffff043f118 (ENTRY -> 6)>
87
88 Tree nodes are printed using Python code that emulates print_node_brief,
89 running in gdb, rather than in the inferior:
90 (gdb) p cfun->decl
91 $1 = <function_decl 0x7ffff0420b00 foo>
92 For usability, the type is printed first (e.g. "function_decl"), rather
93 than just "tree".
94
95 RTL expressions use a kludge: they are pretty-printed by injecting
96 calls into print-rtl.c into the inferior:
97 Value returned is $1 = (note 9 8 10 [bb 3] NOTE_INSN_BASIC_BLOCK)
98 (gdb) p $1
99 $2 = (note 9 8 10 [bb 3] NOTE_INSN_BASIC_BLOCK)
100 (gdb) p /r $1
101 $3 = (rtx_def *) 0x7ffff043e140
102 This won't work for coredumps, and probably in other circumstances, but
103 it's a quick way of getting lots of debuggability quickly.
104
105 Callgraph nodes are printed with the name of the function decl, if
106 available:
107 (gdb) frame 5
108 #5 0x00000000006c288a in expand_function (node=<cgraph_node* 0x7ffff0312720 "foo"/12345>) at ../../src/gcc/cgraphunit.c:1594
109 1594 execute_pass_list (g->get_passes ()->all_passes);
110 (gdb) p node
111 $1 = <cgraph_node* 0x7ffff0312720 "foo"/12345>
112
113 Similarly for symtab_node and varpool_node classes.
114
115 Cgraph edges are printed with the name of caller and callee:
116 (gdb) p this->callees
117 $4 = <cgraph_edge* 0x7fffe25aa000 (<cgraph_node * 0x7fffe62b22e0 "_GLOBAL__sub_I__ZN5Pooma5pinfoE"/19660> -> <cgraph_node * 0x7fffe620f730 "__static_initialization_and_destruction_1"/19575>)>
118
119 IPA reference follow very similar format:
120 (gdb) Value returned is $5 = <ipa_ref* 0x7fffefcb80c8 (<symtab_node * 0x7ffff562f000 "__dt_base "/875> -> <symtab_node * 0x7fffe795f000 "_ZTVN6Smarts8RunnableE"/16056>:IPA_REF_ADDR)>
121
122 vec<> pointers are printed as the address followed by the elements in
123 braces. Here's a length 2 vec:
124 (gdb) p bb->preds
125 $18 = 0x7ffff0428b68 = {<edge 0x7ffff044d380 (3 -> 5)>, <edge 0x7ffff044d3b8 (4 -> 5)>}
126
127 and here's a length 1 vec:
128 (gdb) p bb->succs
129 $19 = 0x7ffff0428bb8 = {<edge 0x7ffff044d3f0 (5 -> EXIT)>}
130
131 You cannot yet use array notation [] to access the elements within the
132 vector: attempting to do so instead gives you the vec itself (for vec[0]),
133 or a (probably) invalid cast to vec<> for the memory after the vec (for
134 vec[1] onwards).
135
136 Instead (for now) you must access m_vecdata:
137 (gdb) p bb->preds->m_vecdata[0]
138 $20 = <edge 0x7ffff044d380 (3 -> 5)>
139 (gdb) p bb->preds->m_vecdata[1]
140 $21 = <edge 0x7ffff044d3b8 (4 -> 5)>
141 """
142 import os.path
143 import re
144 import sys
145 import tempfile
146
147 import gdb
148 import gdb.printing
149 import gdb.types
150
151 # Convert "enum tree_code" (tree.def and tree.h) to a dict:
152 tree_code_dict = gdb.types.make_enum_dict(gdb.lookup_type('enum tree_code'))
153
154 # ...and look up specific values for use later:
155 IDENTIFIER_NODE = tree_code_dict['IDENTIFIER_NODE']
156 TYPE_DECL = tree_code_dict['TYPE_DECL']
157
158 # Similarly for "enum tree_code_class" (tree.h):
159 tree_code_class_dict = gdb.types.make_enum_dict(gdb.lookup_type('enum tree_code_class'))
160 tcc_type = tree_code_class_dict['tcc_type']
161 tcc_declaration = tree_code_class_dict['tcc_declaration']
162
163 # Python3 has int() with arbitrary precision (bignum). Python2 int() is 32-bit
164 # on 32-bit hosts but remote targets may have 64-bit pointers there; Python2
165 # long() is always 64-bit but Python3 no longer has anything named long.
166 def intptr(gdbval):
167 return long(gdbval) if sys.version_info.major == 2 else int(gdbval)
168
169 class Tree:
170 """
171 Wrapper around a gdb.Value for a tree, with various methods
172 corresponding to macros in gcc/tree.h
173 """
174 def __init__(self, gdbval):
175 self.gdbval = gdbval
176
177 def is_nonnull(self):
178 return intptr(self.gdbval)
179
180 def TREE_CODE(self):
181 """
182 Get gdb.Value corresponding to TREE_CODE (self)
183 as per:
184 #define TREE_CODE(NODE) ((enum tree_code) (NODE)->base.code)
185 """
186 return self.gdbval['base']['code']
187
188 def DECL_NAME(self):
189 """
190 Get Tree instance corresponding to DECL_NAME (self)
191 """
192 return Tree(self.gdbval['decl_minimal']['name'])
193
194 def TYPE_NAME(self):
195 """
196 Get Tree instance corresponding to result of TYPE_NAME (self)
197 """
198 return Tree(self.gdbval['type_common']['name'])
199
200 def IDENTIFIER_POINTER(self):
201 """
202 Get str correspoinding to result of IDENTIFIER_NODE (self)
203 """
204 return self.gdbval['identifier']['id']['str'].string()
205
206 class TreePrinter:
207 "Prints a tree"
208
209 def __init__ (self, gdbval):
210 self.gdbval = gdbval
211 self.node = Tree(gdbval)
212
213 def to_string (self):
214 # like gcc/print-tree.c:print_node_brief
215 # #define TREE_CODE(NODE) ((enum tree_code) (NODE)->base.code)
216 # tree_code_name[(int) TREE_CODE (node)])
217 if intptr(self.gdbval) == 0:
218 return '<tree 0x0>'
219
220 val_TREE_CODE = self.node.TREE_CODE()
221
222 # extern const enum tree_code_class tree_code_type[];
223 # #define TREE_CODE_CLASS(CODE) tree_code_type[(int) (CODE)]
224
225 if val_TREE_CODE == 0xa5a5:
226 return '<ggc_freed 0x%x>' % intptr(self.gdbval)
227
228 val_tree_code_type = gdb.parse_and_eval('tree_code_type')
229 val_tclass = val_tree_code_type[val_TREE_CODE]
230
231 val_tree_code_name = gdb.parse_and_eval('tree_code_name')
232 val_code_name = val_tree_code_name[intptr(val_TREE_CODE)]
233 #print(val_code_name.string())
234
235 try:
236 result = '<%s 0x%x' % (val_code_name.string(), intptr(self.gdbval))
237 except:
238 return '<tree 0x%x>' % intptr(self.gdbval)
239 if intptr(val_tclass) == tcc_declaration:
240 tree_DECL_NAME = self.node.DECL_NAME()
241 if tree_DECL_NAME.is_nonnull():
242 result += ' %s' % tree_DECL_NAME.IDENTIFIER_POINTER()
243 else:
244 pass # TODO: labels etc
245 elif intptr(val_tclass) == tcc_type:
246 tree_TYPE_NAME = Tree(self.gdbval['type_common']['name'])
247 if tree_TYPE_NAME.is_nonnull():
248 if tree_TYPE_NAME.TREE_CODE() == IDENTIFIER_NODE:
249 result += ' %s' % tree_TYPE_NAME.IDENTIFIER_POINTER()
250 elif tree_TYPE_NAME.TREE_CODE() == TYPE_DECL:
251 if tree_TYPE_NAME.DECL_NAME().is_nonnull():
252 result += ' %s' % tree_TYPE_NAME.DECL_NAME().IDENTIFIER_POINTER()
253 if self.node.TREE_CODE() == IDENTIFIER_NODE:
254 result += ' %s' % self.node.IDENTIFIER_POINTER()
255 # etc
256 result += '>'
257 return result
258
259 ######################################################################
260 # Callgraph pretty-printers
261 ######################################################################
262
263 class SymtabNodePrinter:
264 def __init__(self, gdbval):
265 self.gdbval = gdbval
266
267 def to_string (self):
268 t = str(self.gdbval.type)
269 result = '<%s 0x%x' % (t, intptr(self.gdbval))
270 if intptr(self.gdbval):
271 # symtab_node::name calls lang_hooks.decl_printable_name
272 # default implementation (lhd_decl_printable_name) is:
273 # return IDENTIFIER_POINTER (DECL_NAME (decl));
274 tree_decl = Tree(self.gdbval['decl'])
275 result += ' "%s"/%d' % (tree_decl.DECL_NAME().IDENTIFIER_POINTER(), self.gdbval['order'])
276 result += '>'
277 return result
278
279 class CgraphEdgePrinter:
280 def __init__(self, gdbval):
281 self.gdbval = gdbval
282
283 def to_string (self):
284 result = '<cgraph_edge* 0x%x' % intptr(self.gdbval)
285 if intptr(self.gdbval):
286 src = SymtabNodePrinter(self.gdbval['caller']).to_string()
287 dest = SymtabNodePrinter(self.gdbval['callee']).to_string()
288 result += ' (%s -> %s)' % (src, dest)
289 result += '>'
290 return result
291
292 class IpaReferencePrinter:
293 def __init__(self, gdbval):
294 self.gdbval = gdbval
295
296 def to_string (self):
297 result = '<ipa_ref* 0x%x' % intptr(self.gdbval)
298 if intptr(self.gdbval):
299 src = SymtabNodePrinter(self.gdbval['referring']).to_string()
300 dest = SymtabNodePrinter(self.gdbval['referred']).to_string()
301 result += ' (%s -> %s:%s)' % (src, dest, str(self.gdbval['use']))
302 result += '>'
303 return result
304
305 ######################################################################
306 # Dwarf DIE pretty-printers
307 ######################################################################
308
309 class DWDieRefPrinter:
310 def __init__(self, gdbval):
311 self.gdbval = gdbval
312
313 def to_string (self):
314 if intptr(self.gdbval) == 0:
315 return '<dw_die_ref 0x0>'
316 result = '<dw_die_ref 0x%x' % intptr(self.gdbval)
317 result += ' %s' % self.gdbval['die_tag']
318 if intptr(self.gdbval['die_parent']) != 0:
319 result += ' <parent=0x%x %s>' % (intptr(self.gdbval['die_parent']),
320 self.gdbval['die_parent']['die_tag'])
321
322 result += '>'
323 return result
324
325 ######################################################################
326
327 class GimplePrinter:
328 def __init__(self, gdbval):
329 self.gdbval = gdbval
330
331 def to_string (self):
332 if intptr(self.gdbval) == 0:
333 return '<gimple 0x0>'
334 val_gimple_code = self.gdbval['code']
335 val_gimple_code_name = gdb.parse_and_eval('gimple_code_name')
336 val_code_name = val_gimple_code_name[intptr(val_gimple_code)]
337 result = '<%s 0x%x' % (val_code_name.string(),
338 intptr(self.gdbval))
339 result += '>'
340 return result
341
342 ######################################################################
343 # CFG pretty-printers
344 ######################################################################
345
346 def bb_index_to_str(index):
347 if index == 0:
348 return 'ENTRY'
349 elif index == 1:
350 return 'EXIT'
351 else:
352 return '%i' % index
353
354 class BasicBlockPrinter:
355 def __init__(self, gdbval):
356 self.gdbval = gdbval
357
358 def to_string (self):
359 result = '<basic_block 0x%x' % intptr(self.gdbval)
360 if intptr(self.gdbval):
361 result += ' (%s)' % bb_index_to_str(intptr(self.gdbval['index']))
362 result += '>'
363 return result
364
365 class CfgEdgePrinter:
366 def __init__(self, gdbval):
367 self.gdbval = gdbval
368
369 def to_string (self):
370 result = '<edge 0x%x' % intptr(self.gdbval)
371 if intptr(self.gdbval):
372 src = bb_index_to_str(intptr(self.gdbval['src']['index']))
373 dest = bb_index_to_str(intptr(self.gdbval['dest']['index']))
374 result += ' (%s -> %s)' % (src, dest)
375 result += '>'
376 return result
377
378 ######################################################################
379
380 class Rtx:
381 def __init__(self, gdbval):
382 self.gdbval = gdbval
383
384 def GET_CODE(self):
385 return self.gdbval['code']
386
387 def GET_RTX_LENGTH(code):
388 val_rtx_length = gdb.parse_and_eval('rtx_length')
389 return intptr(val_rtx_length[code])
390
391 def GET_RTX_NAME(code):
392 val_rtx_name = gdb.parse_and_eval('rtx_name')
393 return val_rtx_name[code].string()
394
395 def GET_RTX_FORMAT(code):
396 val_rtx_format = gdb.parse_and_eval('rtx_format')
397 return val_rtx_format[code].string()
398
399 class RtxPrinter:
400 def __init__(self, gdbval):
401 self.gdbval = gdbval
402 self.rtx = Rtx(gdbval)
403
404 def to_string (self):
405 """
406 For now, a cheap kludge: invoke the inferior's print
407 function to get a string to use the user, and return an empty
408 string for gdb
409 """
410 # We use print_inline_rtx to avoid a trailing newline
411 gdb.execute('call print_inline_rtx (stderr, (const_rtx) %s, 0)'
412 % intptr(self.gdbval))
413 return ''
414
415 # or by hand; based on gcc/print-rtl.c:print_rtx
416 result = ('<rtx_def 0x%x'
417 % (intptr(self.gdbval)))
418 code = self.rtx.GET_CODE()
419 result += ' (%s' % GET_RTX_NAME(code)
420 format_ = GET_RTX_FORMAT(code)
421 for i in range(GET_RTX_LENGTH(code)):
422 print(format_[i])
423 result += ')>'
424 return result
425
426 ######################################################################
427
428 class PassPrinter:
429 def __init__(self, gdbval):
430 self.gdbval = gdbval
431
432 def to_string (self):
433 result = '<opt_pass* 0x%x' % intptr(self.gdbval)
434 if intptr(self.gdbval):
435 result += (' "%s"(%i)'
436 % (self.gdbval['name'].string(),
437 intptr(self.gdbval['static_pass_number'])))
438 result += '>'
439 return result
440
441 ######################################################################
442
443 class VecPrinter:
444 # -ex "up" -ex "p bb->preds"
445 def __init__(self, gdbval):
446 self.gdbval = gdbval
447
448 def display_hint (self):
449 return 'array'
450
451 def to_string (self):
452 # A trivial implementation; prettyprinting the contents is done
453 # by gdb calling the "children" method below.
454 return '0x%x' % intptr(self.gdbval)
455
456 def children (self):
457 if intptr(self.gdbval) == 0:
458 return
459 m_vecpfx = self.gdbval['m_vecpfx']
460 m_num = m_vecpfx['m_num']
461 m_vecdata = self.gdbval['m_vecdata']
462 for i in range(m_num):
463 yield ('[%d]' % i, m_vecdata[i])
464
465 ######################################################################
466
467 class MachineModePrinter:
468 def __init__(self, gdbval):
469 self.gdbval = gdbval
470
471 def to_string (self):
472 name = str(self.gdbval['m_mode'])
473 return name[2:] if name.startswith('E_') else name
474
475 ######################################################################
476
477 class OptMachineModePrinter:
478 def __init__(self, gdbval):
479 self.gdbval = gdbval
480
481 def to_string (self):
482 name = str(self.gdbval['m_mode'])
483 if name == 'E_VOIDmode':
484 return '<None>'
485 return name[2:] if name.startswith('E_') else name
486
487 ######################################################################
488
489 # TODO:
490 # * hashtab
491 # * location_t
492
493 class GdbSubprinter(gdb.printing.SubPrettyPrinter):
494 def __init__(self, name, class_):
495 super(GdbSubprinter, self).__init__(name)
496 self.class_ = class_
497
498 def handles_type(self, str_type):
499 raise NotImplementedError
500
501 class GdbSubprinterTypeList(GdbSubprinter):
502 """
503 A GdbSubprinter that handles a specific set of types
504 """
505 def __init__(self, str_types, name, class_):
506 super(GdbSubprinterTypeList, self).__init__(name, class_)
507 self.str_types = frozenset(str_types)
508
509 def handles_type(self, str_type):
510 return str_type in self.str_types
511
512 class GdbSubprinterRegex(GdbSubprinter):
513 """
514 A GdbSubprinter that handles types that match a regex
515 """
516 def __init__(self, regex, name, class_):
517 super(GdbSubprinterRegex, self).__init__(name, class_)
518 self.regex = re.compile(regex)
519
520 def handles_type(self, str_type):
521 return self.regex.match(str_type)
522
523 class GdbPrettyPrinters(gdb.printing.PrettyPrinter):
524 def __init__(self, name):
525 super(GdbPrettyPrinters, self).__init__(name, [])
526
527 def add_printer_for_types(self, name, class_, types):
528 self.subprinters.append(GdbSubprinterTypeList(name, class_, types))
529
530 def add_printer_for_regex(self, name, class_, regex):
531 self.subprinters.append(GdbSubprinterRegex(name, class_, regex))
532
533 def __call__(self, gdbval):
534 type_ = gdbval.type.unqualified()
535 str_type = str(type_)
536 for printer in self.subprinters:
537 if printer.enabled and printer.handles_type(str_type):
538 return printer.class_(gdbval)
539
540 # Couldn't find a pretty printer (or it was disabled):
541 return None
542
543
544 def build_pretty_printer():
545 pp = GdbPrettyPrinters('gcc')
546 pp.add_printer_for_types(['tree', 'const_tree'],
547 'tree', TreePrinter)
548 pp.add_printer_for_types(['cgraph_node *', 'varpool_node *', 'symtab_node *'],
549 'symtab_node', SymtabNodePrinter)
550 pp.add_printer_for_types(['cgraph_edge *'],
551 'cgraph_edge', CgraphEdgePrinter)
552 pp.add_printer_for_types(['ipa_ref *'],
553 'ipa_ref', IpaReferencePrinter)
554 pp.add_printer_for_types(['dw_die_ref'],
555 'dw_die_ref', DWDieRefPrinter)
556 pp.add_printer_for_types(['gimple', 'gimple *',
557
558 # Keep this in the same order as gimple.def:
559 'gimple_cond', 'const_gimple_cond',
560 'gimple_statement_cond *',
561 'gimple_debug', 'const_gimple_debug',
562 'gimple_statement_debug *',
563 'gimple_label', 'const_gimple_label',
564 'gimple_statement_label *',
565 'gimple_switch', 'const_gimple_switch',
566 'gimple_statement_switch *',
567 'gimple_assign', 'const_gimple_assign',
568 'gimple_statement_assign *',
569 'gimple_bind', 'const_gimple_bind',
570 'gimple_statement_bind *',
571 'gimple_phi', 'const_gimple_phi',
572 'gimple_statement_phi *'],
573
574 'gimple',
575 GimplePrinter)
576 pp.add_printer_for_types(['basic_block', 'basic_block_def *'],
577 'basic_block',
578 BasicBlockPrinter)
579 pp.add_printer_for_types(['edge', 'edge_def *'],
580 'edge',
581 CfgEdgePrinter)
582 pp.add_printer_for_types(['rtx_def *'], 'rtx_def', RtxPrinter)
583 pp.add_printer_for_types(['opt_pass *'], 'opt_pass', PassPrinter)
584
585 pp.add_printer_for_regex(r'vec<(\S+), (\S+), (\S+)> \*',
586 'vec',
587 VecPrinter)
588
589 pp.add_printer_for_regex(r'opt_mode<(\S+)>',
590 'opt_mode', OptMachineModePrinter)
591 pp.add_printer_for_types(['opt_scalar_int_mode',
592 'opt_scalar_float_mode',
593 'opt_scalar_mode'],
594 'opt_mode', OptMachineModePrinter)
595 pp.add_printer_for_regex(r'pod_mode<(\S+)>',
596 'pod_mode', MachineModePrinter)
597 pp.add_printer_for_types(['scalar_int_mode_pod',
598 'scalar_mode_pod'],
599 'pod_mode', MachineModePrinter)
600 for mode in ('scalar_mode', 'scalar_int_mode', 'scalar_float_mode',
601 'complex_mode'):
602 pp.add_printer_for_types([mode], mode, MachineModePrinter)
603
604 return pp
605
606 gdb.printing.register_pretty_printer(
607 gdb.current_objfile(),
608 build_pretty_printer())
609
610 def find_gcc_source_dir():
611 # Use location of global "g" to locate the source tree
612 sym_g = gdb.lookup_global_symbol('g')
613 path = sym_g.symtab.filename # e.g. '../../src/gcc/context.h'
614 srcdir = os.path.split(path)[0] # e.g. '../../src/gcc'
615 return srcdir
616
617 class PassNames:
618 """Parse passes.def, gathering a list of pass class names"""
619 def __init__(self):
620 srcdir = find_gcc_source_dir()
621 self.names = []
622 with open(os.path.join(srcdir, 'passes.def')) as f:
623 for line in f:
624 m = re.match('\s*NEXT_PASS \(([^,]+).*\);', line)
625 if m:
626 self.names.append(m.group(1))
627
628 class BreakOnPass(gdb.Command):
629 """
630 A custom command for putting breakpoints on the execute hook of passes.
631 This is largely a workaround for issues with tab-completion in gdb when
632 setting breakpoints on methods on classes within anonymous namespaces.
633
634 Example of use: putting a breakpoint on "final"
635 (gdb) break-on-pass
636 Press <TAB>; it autocompletes to "pass_":
637 (gdb) break-on-pass pass_
638 Press <TAB>:
639 Display all 219 possibilities? (y or n)
640 Press "n"; then type "f":
641 (gdb) break-on-pass pass_f
642 Press <TAB> to autocomplete to pass classnames beginning with "pass_f":
643 pass_fast_rtl_dce pass_fold_builtins
644 pass_feedback_split_functions pass_forwprop
645 pass_final pass_fre
646 pass_fixup_cfg pass_free_cfg
647 Type "in<TAB>" to complete to "pass_final":
648 (gdb) break-on-pass pass_final
649 ...and hit <RETURN>:
650 Breakpoint 6 at 0x8396ba: file ../../src/gcc/final.c, line 4526.
651 ...and we have a breakpoint set; continue execution:
652 (gdb) cont
653 Continuing.
654 Breakpoint 6, (anonymous namespace)::pass_final::execute (this=0x17fb990) at ../../src/gcc/final.c:4526
655 4526 virtual unsigned int execute (function *) { return rest_of_handle_final (); }
656 """
657 def __init__(self):
658 gdb.Command.__init__(self, 'break-on-pass', gdb.COMMAND_BREAKPOINTS)
659 self.pass_names = None
660
661 def complete(self, text, word):
662 # Lazily load pass names:
663 if not self.pass_names:
664 self.pass_names = PassNames()
665
666 return [name
667 for name in sorted(self.pass_names.names)
668 if name.startswith(text)]
669
670 def invoke(self, arg, from_tty):
671 sym = '(anonymous namespace)::%s::execute' % arg
672 breakpoint = gdb.Breakpoint(sym)
673
674 BreakOnPass()
675
676 class DumpFn(gdb.Command):
677 """
678 A custom command to dump a gimple/rtl function to file. By default, it
679 dumps the current function using 0 as dump_flags, but the function and flags
680 can also be specified. If /f <file> are passed as the first two arguments,
681 the dump is written to that file. Otherwise, a temporary file is created
682 and opened in the text editor specified in the EDITOR environment variable.
683
684 Examples of use:
685 (gdb) dump-fn
686 (gdb) dump-fn /f foo.1.txt
687 (gdb) dump-fn cfun->decl
688 (gdb) dump-fn /f foo.1.txt cfun->decl
689 (gdb) dump-fn cfun->decl 0
690 (gdb) dump-fn cfun->decl dump_flags
691 """
692
693 def __init__(self):
694 gdb.Command.__init__(self, 'dump-fn', gdb.COMMAND_USER)
695
696 def invoke(self, arg, from_tty):
697 # Parse args, check number of args
698 args = gdb.string_to_argv(arg)
699 if len(args) >= 1 and args[0] == "/f":
700 if len(args) == 1:
701 print ("Missing file argument")
702 return
703 filename = args[1]
704 editor_mode = False
705 base_arg = 2
706 else:
707 editor = os.getenv("EDITOR", "")
708 if editor == "":
709 print ("EDITOR environment variable not defined")
710 return
711 editor_mode = True
712 base_arg = 0
713 if len(args) - base_arg > 2:
714 print ("Too many arguments")
715 return
716
717 # Set func
718 if len(args) - base_arg >= 1:
719 funcname = args[base_arg]
720 printfuncname = "function %s" % funcname
721 else:
722 funcname = "cfun ? cfun->decl : current_function_decl"
723 printfuncname = "current function"
724 func = gdb.parse_and_eval(funcname)
725 if func == 0:
726 print ("Could not find %s" % printfuncname)
727 return
728 func = "(tree)%u" % func
729
730 # Set flags
731 if len(args) - base_arg >= 2:
732 flags = gdb.parse_and_eval(args[base_arg + 1])
733 else:
734 flags = 0
735
736 # Get tempory file, if necessary
737 if editor_mode:
738 f = tempfile.NamedTemporaryFile(delete=False, suffix=".txt")
739 filename = f.name
740 f.close()
741
742 # Open file
743 fp = gdb.parse_and_eval("fopen (\"%s\", \"w\")" % filename)
744 if fp == 0:
745 print ("Could not open file: %s" % filename)
746 return
747 fp = "(FILE *)%u" % fp
748
749 # Dump function to file
750 _ = gdb.parse_and_eval("dump_function_to_file (%s, %s, %u)" %
751 (func, fp, flags))
752
753 # Close file
754 ret = gdb.parse_and_eval("fclose (%s)" % fp)
755 if ret != 0:
756 print ("Could not close file: %s" % filename)
757 return
758
759 # Open file in editor, if necessary
760 if editor_mode:
761 os.system("( %s \"%s\"; rm \"%s\" ) &" %
762 (editor, filename, filename))
763
764 DumpFn()
765
766 class DotFn(gdb.Command):
767 """
768 A custom command to show a gimple/rtl function control flow graph.
769 By default, it show the current function, but the function can also be
770 specified.
771
772 Examples of use:
773 (gdb) dot-fn
774 (gdb) dot-fn cfun
775 (gdb) dot-fn cfun 0
776 (gdb) dot-fn cfun dump_flags
777 """
778 def __init__(self):
779 gdb.Command.__init__(self, 'dot-fn', gdb.COMMAND_USER)
780
781 def invoke(self, arg, from_tty):
782 # Parse args, check number of args
783 args = gdb.string_to_argv(arg)
784 if len(args) > 2:
785 print("Too many arguments")
786 return
787
788 # Set func
789 if len(args) >= 1:
790 funcname = args[0]
791 printfuncname = "function %s" % funcname
792 else:
793 funcname = "cfun"
794 printfuncname = "current function"
795 func = gdb.parse_and_eval(funcname)
796 if func == 0:
797 print("Could not find %s" % printfuncname)
798 return
799 func = "(struct function *)%s" % func
800
801 # Set flags
802 if len(args) >= 2:
803 flags = gdb.parse_and_eval(args[1])
804 else:
805 flags = 0
806
807 # Get temp file
808 f = tempfile.NamedTemporaryFile(delete=False)
809 filename = f.name
810
811 # Close and reopen temp file to get C FILE*
812 f.close()
813 fp = gdb.parse_and_eval("fopen (\"%s\", \"w\")" % filename)
814 if fp == 0:
815 print("Cannot open temp file")
816 return
817 fp = "(FILE *)%u" % fp
818
819 # Write graph to temp file
820 _ = gdb.parse_and_eval("start_graph_dump (%s, \"<debug>\")" % fp)
821 _ = gdb.parse_and_eval("print_graph_cfg (%s, %s, %u)"
822 % (fp, func, flags))
823 _ = gdb.parse_and_eval("end_graph_dump (%s)" % fp)
824
825 # Close temp file
826 ret = gdb.parse_and_eval("fclose (%s)" % fp)
827 if ret != 0:
828 print("Could not close temp file: %s" % filename)
829 return
830
831 # Show graph in temp file
832 os.system("( dot -Tx11 \"%s\"; rm \"%s\" ) &" % (filename, filename))
833
834 DotFn()
835
836 print('Successfully loaded GDB hooks for GCC')