]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/gdbhooks.py
Add pretty print for const_tree.
[thirdparty/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 val_tree_code_type = gdb.parse_and_eval('tree_code_type')
226 val_tclass = val_tree_code_type[val_TREE_CODE]
227
228 val_tree_code_name = gdb.parse_and_eval('tree_code_name')
229 val_code_name = val_tree_code_name[intptr(val_TREE_CODE)]
230 #print(val_code_name.string())
231
232 try:
233 result = '<%s 0x%x' % (val_code_name.string(), intptr(self.gdbval))
234 except:
235 return '<tree 0x%x>' % intptr(self.gdbval)
236 if intptr(val_tclass) == tcc_declaration:
237 tree_DECL_NAME = self.node.DECL_NAME()
238 if tree_DECL_NAME.is_nonnull():
239 result += ' %s' % tree_DECL_NAME.IDENTIFIER_POINTER()
240 else:
241 pass # TODO: labels etc
242 elif intptr(val_tclass) == tcc_type:
243 tree_TYPE_NAME = Tree(self.gdbval['type_common']['name'])
244 if tree_TYPE_NAME.is_nonnull():
245 if tree_TYPE_NAME.TREE_CODE() == IDENTIFIER_NODE:
246 result += ' %s' % tree_TYPE_NAME.IDENTIFIER_POINTER()
247 elif tree_TYPE_NAME.TREE_CODE() == TYPE_DECL:
248 if tree_TYPE_NAME.DECL_NAME().is_nonnull():
249 result += ' %s' % tree_TYPE_NAME.DECL_NAME().IDENTIFIER_POINTER()
250 if self.node.TREE_CODE() == IDENTIFIER_NODE:
251 result += ' %s' % self.node.IDENTIFIER_POINTER()
252 # etc
253 result += '>'
254 return result
255
256 ######################################################################
257 # Callgraph pretty-printers
258 ######################################################################
259
260 class SymtabNodePrinter:
261 def __init__(self, gdbval):
262 self.gdbval = gdbval
263
264 def to_string (self):
265 t = str(self.gdbval.type)
266 result = '<%s 0x%x' % (t, intptr(self.gdbval))
267 if intptr(self.gdbval):
268 # symtab_node::name calls lang_hooks.decl_printable_name
269 # default implementation (lhd_decl_printable_name) is:
270 # return IDENTIFIER_POINTER (DECL_NAME (decl));
271 tree_decl = Tree(self.gdbval['decl'])
272 result += ' "%s"/%d' % (tree_decl.DECL_NAME().IDENTIFIER_POINTER(), self.gdbval['order'])
273 result += '>'
274 return result
275
276 class CgraphEdgePrinter:
277 def __init__(self, gdbval):
278 self.gdbval = gdbval
279
280 def to_string (self):
281 result = '<cgraph_edge* 0x%x' % intptr(self.gdbval)
282 if intptr(self.gdbval):
283 src = SymtabNodePrinter(self.gdbval['caller']).to_string()
284 dest = SymtabNodePrinter(self.gdbval['callee']).to_string()
285 result += ' (%s -> %s)' % (src, dest)
286 result += '>'
287 return result
288
289 class IpaReferencePrinter:
290 def __init__(self, gdbval):
291 self.gdbval = gdbval
292
293 def to_string (self):
294 result = '<ipa_ref* 0x%x' % intptr(self.gdbval)
295 if intptr(self.gdbval):
296 src = SymtabNodePrinter(self.gdbval['referring']).to_string()
297 dest = SymtabNodePrinter(self.gdbval['referred']).to_string()
298 result += ' (%s -> %s:%s)' % (src, dest, str(self.gdbval['use']))
299 result += '>'
300 return result
301
302 ######################################################################
303 # Dwarf DIE pretty-printers
304 ######################################################################
305
306 class DWDieRefPrinter:
307 def __init__(self, gdbval):
308 self.gdbval = gdbval
309
310 def to_string (self):
311 if intptr(self.gdbval) == 0:
312 return '<dw_die_ref 0x0>'
313 result = '<dw_die_ref 0x%x' % intptr(self.gdbval)
314 result += ' %s' % self.gdbval['die_tag']
315 if intptr(self.gdbval['die_parent']) != 0:
316 result += ' <parent=0x%x %s>' % (intptr(self.gdbval['die_parent']),
317 self.gdbval['die_parent']['die_tag'])
318
319 result += '>'
320 return result
321
322 ######################################################################
323
324 class GimplePrinter:
325 def __init__(self, gdbval):
326 self.gdbval = gdbval
327
328 def to_string (self):
329 if intptr(self.gdbval) == 0:
330 return '<gimple 0x0>'
331 val_gimple_code = self.gdbval['code']
332 val_gimple_code_name = gdb.parse_and_eval('gimple_code_name')
333 val_code_name = val_gimple_code_name[intptr(val_gimple_code)]
334 result = '<%s 0x%x' % (val_code_name.string(),
335 intptr(self.gdbval))
336 result += '>'
337 return result
338
339 ######################################################################
340 # CFG pretty-printers
341 ######################################################################
342
343 def bb_index_to_str(index):
344 if index == 0:
345 return 'ENTRY'
346 elif index == 1:
347 return 'EXIT'
348 else:
349 return '%i' % index
350
351 class BasicBlockPrinter:
352 def __init__(self, gdbval):
353 self.gdbval = gdbval
354
355 def to_string (self):
356 result = '<basic_block 0x%x' % intptr(self.gdbval)
357 if intptr(self.gdbval):
358 result += ' (%s)' % bb_index_to_str(intptr(self.gdbval['index']))
359 result += '>'
360 return result
361
362 class CfgEdgePrinter:
363 def __init__(self, gdbval):
364 self.gdbval = gdbval
365
366 def to_string (self):
367 result = '<edge 0x%x' % intptr(self.gdbval)
368 if intptr(self.gdbval):
369 src = bb_index_to_str(intptr(self.gdbval['src']['index']))
370 dest = bb_index_to_str(intptr(self.gdbval['dest']['index']))
371 result += ' (%s -> %s)' % (src, dest)
372 result += '>'
373 return result
374
375 ######################################################################
376
377 class Rtx:
378 def __init__(self, gdbval):
379 self.gdbval = gdbval
380
381 def GET_CODE(self):
382 return self.gdbval['code']
383
384 def GET_RTX_LENGTH(code):
385 val_rtx_length = gdb.parse_and_eval('rtx_length')
386 return intptr(val_rtx_length[code])
387
388 def GET_RTX_NAME(code):
389 val_rtx_name = gdb.parse_and_eval('rtx_name')
390 return val_rtx_name[code].string()
391
392 def GET_RTX_FORMAT(code):
393 val_rtx_format = gdb.parse_and_eval('rtx_format')
394 return val_rtx_format[code].string()
395
396 class RtxPrinter:
397 def __init__(self, gdbval):
398 self.gdbval = gdbval
399 self.rtx = Rtx(gdbval)
400
401 def to_string (self):
402 """
403 For now, a cheap kludge: invoke the inferior's print
404 function to get a string to use the user, and return an empty
405 string for gdb
406 """
407 # We use print_inline_rtx to avoid a trailing newline
408 gdb.execute('call print_inline_rtx (stderr, (const_rtx) %s, 0)'
409 % intptr(self.gdbval))
410 return ''
411
412 # or by hand; based on gcc/print-rtl.c:print_rtx
413 result = ('<rtx_def 0x%x'
414 % (intptr(self.gdbval)))
415 code = self.rtx.GET_CODE()
416 result += ' (%s' % GET_RTX_NAME(code)
417 format_ = GET_RTX_FORMAT(code)
418 for i in range(GET_RTX_LENGTH(code)):
419 print(format_[i])
420 result += ')>'
421 return result
422
423 ######################################################################
424
425 class PassPrinter:
426 def __init__(self, gdbval):
427 self.gdbval = gdbval
428
429 def to_string (self):
430 result = '<opt_pass* 0x%x' % intptr(self.gdbval)
431 if intptr(self.gdbval):
432 result += (' "%s"(%i)'
433 % (self.gdbval['name'].string(),
434 intptr(self.gdbval['static_pass_number'])))
435 result += '>'
436 return result
437
438 ######################################################################
439
440 class VecPrinter:
441 # -ex "up" -ex "p bb->preds"
442 def __init__(self, gdbval):
443 self.gdbval = gdbval
444
445 def display_hint (self):
446 return 'array'
447
448 def to_string (self):
449 # A trivial implementation; prettyprinting the contents is done
450 # by gdb calling the "children" method below.
451 return '0x%x' % intptr(self.gdbval)
452
453 def children (self):
454 if intptr(self.gdbval) == 0:
455 return
456 m_vecpfx = self.gdbval['m_vecpfx']
457 m_num = m_vecpfx['m_num']
458 m_vecdata = self.gdbval['m_vecdata']
459 for i in range(m_num):
460 yield ('[%d]' % i, m_vecdata[i])
461
462 ######################################################################
463
464 class MachineModePrinter:
465 def __init__(self, gdbval):
466 self.gdbval = gdbval
467
468 def to_string (self):
469 name = str(self.gdbval['m_mode'])
470 return name[2:] if name.startswith('E_') else name
471
472 ######################################################################
473
474 class OptMachineModePrinter:
475 def __init__(self, gdbval):
476 self.gdbval = gdbval
477
478 def to_string (self):
479 name = str(self.gdbval['m_mode'])
480 if name == 'E_VOIDmode':
481 return '<None>'
482 return name[2:] if name.startswith('E_') else name
483
484 ######################################################################
485
486 # TODO:
487 # * hashtab
488 # * location_t
489
490 class GdbSubprinter(gdb.printing.SubPrettyPrinter):
491 def __init__(self, name, class_):
492 super(GdbSubprinter, self).__init__(name)
493 self.class_ = class_
494
495 def handles_type(self, str_type):
496 raise NotImplementedError
497
498 class GdbSubprinterTypeList(GdbSubprinter):
499 """
500 A GdbSubprinter that handles a specific set of types
501 """
502 def __init__(self, str_types, name, class_):
503 super(GdbSubprinterTypeList, self).__init__(name, class_)
504 self.str_types = frozenset(str_types)
505
506 def handles_type(self, str_type):
507 return str_type in self.str_types
508
509 class GdbSubprinterRegex(GdbSubprinter):
510 """
511 A GdbSubprinter that handles types that match a regex
512 """
513 def __init__(self, regex, name, class_):
514 super(GdbSubprinterRegex, self).__init__(name, class_)
515 self.regex = re.compile(regex)
516
517 def handles_type(self, str_type):
518 return self.regex.match(str_type)
519
520 class GdbPrettyPrinters(gdb.printing.PrettyPrinter):
521 def __init__(self, name):
522 super(GdbPrettyPrinters, self).__init__(name, [])
523
524 def add_printer_for_types(self, name, class_, types):
525 self.subprinters.append(GdbSubprinterTypeList(name, class_, types))
526
527 def add_printer_for_regex(self, name, class_, regex):
528 self.subprinters.append(GdbSubprinterRegex(name, class_, regex))
529
530 def __call__(self, gdbval):
531 type_ = gdbval.type.unqualified()
532 str_type = str(type_)
533 for printer in self.subprinters:
534 if printer.enabled and printer.handles_type(str_type):
535 return printer.class_(gdbval)
536
537 # Couldn't find a pretty printer (or it was disabled):
538 return None
539
540
541 def build_pretty_printer():
542 pp = GdbPrettyPrinters('gcc')
543 pp.add_printer_for_types(['tree', 'const_tree'],
544 'tree', TreePrinter)
545 pp.add_printer_for_types(['cgraph_node *', 'varpool_node *', 'symtab_node *'],
546 'symtab_node', SymtabNodePrinter)
547 pp.add_printer_for_types(['cgraph_edge *'],
548 'cgraph_edge', CgraphEdgePrinter)
549 pp.add_printer_for_types(['ipa_ref *'],
550 'ipa_ref', IpaReferencePrinter)
551 pp.add_printer_for_types(['dw_die_ref'],
552 'dw_die_ref', DWDieRefPrinter)
553 pp.add_printer_for_types(['gimple', 'gimple *',
554
555 # Keep this in the same order as gimple.def:
556 'gimple_cond', 'const_gimple_cond',
557 'gimple_statement_cond *',
558 'gimple_debug', 'const_gimple_debug',
559 'gimple_statement_debug *',
560 'gimple_label', 'const_gimple_label',
561 'gimple_statement_label *',
562 'gimple_switch', 'const_gimple_switch',
563 'gimple_statement_switch *',
564 'gimple_assign', 'const_gimple_assign',
565 'gimple_statement_assign *',
566 'gimple_bind', 'const_gimple_bind',
567 'gimple_statement_bind *',
568 'gimple_phi', 'const_gimple_phi',
569 'gimple_statement_phi *'],
570
571 'gimple',
572 GimplePrinter)
573 pp.add_printer_for_types(['basic_block', 'basic_block_def *'],
574 'basic_block',
575 BasicBlockPrinter)
576 pp.add_printer_for_types(['edge', 'edge_def *'],
577 'edge',
578 CfgEdgePrinter)
579 pp.add_printer_for_types(['rtx_def *'], 'rtx_def', RtxPrinter)
580 pp.add_printer_for_types(['opt_pass *'], 'opt_pass', PassPrinter)
581
582 pp.add_printer_for_regex(r'vec<(\S+), (\S+), (\S+)> \*',
583 'vec',
584 VecPrinter)
585
586 pp.add_printer_for_regex(r'opt_mode<(\S+)>',
587 'opt_mode', OptMachineModePrinter)
588 pp.add_printer_for_types(['opt_scalar_int_mode',
589 'opt_scalar_float_mode',
590 'opt_scalar_mode'],
591 'opt_mode', OptMachineModePrinter)
592 pp.add_printer_for_regex(r'pod_mode<(\S+)>',
593 'pod_mode', MachineModePrinter)
594 pp.add_printer_for_types(['scalar_int_mode_pod',
595 'scalar_mode_pod'],
596 'pod_mode', MachineModePrinter)
597 for mode in ('scalar_mode', 'scalar_int_mode', 'scalar_float_mode',
598 'complex_mode'):
599 pp.add_printer_for_types([mode], mode, MachineModePrinter)
600
601 return pp
602
603 gdb.printing.register_pretty_printer(
604 gdb.current_objfile(),
605 build_pretty_printer())
606
607 def find_gcc_source_dir():
608 # Use location of global "g" to locate the source tree
609 sym_g = gdb.lookup_global_symbol('g')
610 path = sym_g.symtab.filename # e.g. '../../src/gcc/context.h'
611 srcdir = os.path.split(path)[0] # e.g. '../../src/gcc'
612 return srcdir
613
614 class PassNames:
615 """Parse passes.def, gathering a list of pass class names"""
616 def __init__(self):
617 srcdir = find_gcc_source_dir()
618 self.names = []
619 with open(os.path.join(srcdir, 'passes.def')) as f:
620 for line in f:
621 m = re.match('\s*NEXT_PASS \(([^,]+).*\);', line)
622 if m:
623 self.names.append(m.group(1))
624
625 class BreakOnPass(gdb.Command):
626 """
627 A custom command for putting breakpoints on the execute hook of passes.
628 This is largely a workaround for issues with tab-completion in gdb when
629 setting breakpoints on methods on classes within anonymous namespaces.
630
631 Example of use: putting a breakpoint on "final"
632 (gdb) break-on-pass
633 Press <TAB>; it autocompletes to "pass_":
634 (gdb) break-on-pass pass_
635 Press <TAB>:
636 Display all 219 possibilities? (y or n)
637 Press "n"; then type "f":
638 (gdb) break-on-pass pass_f
639 Press <TAB> to autocomplete to pass classnames beginning with "pass_f":
640 pass_fast_rtl_dce pass_fold_builtins
641 pass_feedback_split_functions pass_forwprop
642 pass_final pass_fre
643 pass_fixup_cfg pass_free_cfg
644 Type "in<TAB>" to complete to "pass_final":
645 (gdb) break-on-pass pass_final
646 ...and hit <RETURN>:
647 Breakpoint 6 at 0x8396ba: file ../../src/gcc/final.c, line 4526.
648 ...and we have a breakpoint set; continue execution:
649 (gdb) cont
650 Continuing.
651 Breakpoint 6, (anonymous namespace)::pass_final::execute (this=0x17fb990) at ../../src/gcc/final.c:4526
652 4526 virtual unsigned int execute (function *) { return rest_of_handle_final (); }
653 """
654 def __init__(self):
655 gdb.Command.__init__(self, 'break-on-pass', gdb.COMMAND_BREAKPOINTS)
656 self.pass_names = None
657
658 def complete(self, text, word):
659 # Lazily load pass names:
660 if not self.pass_names:
661 self.pass_names = PassNames()
662
663 return [name
664 for name in sorted(self.pass_names.names)
665 if name.startswith(text)]
666
667 def invoke(self, arg, from_tty):
668 sym = '(anonymous namespace)::%s::execute' % arg
669 breakpoint = gdb.Breakpoint(sym)
670
671 BreakOnPass()
672
673 class DumpFn(gdb.Command):
674 """
675 A custom command to dump a gimple/rtl function to file. By default, it
676 dumps the current function using 0 as dump_flags, but the function and flags
677 can also be specified. If /f <file> are passed as the first two arguments,
678 the dump is written to that file. Otherwise, a temporary file is created
679 and opened in the text editor specified in the EDITOR environment variable.
680
681 Examples of use:
682 (gdb) dump-fn
683 (gdb) dump-fn /f foo.1.txt
684 (gdb) dump-fn cfun->decl
685 (gdb) dump-fn /f foo.1.txt cfun->decl
686 (gdb) dump-fn cfun->decl 0
687 (gdb) dump-fn cfun->decl dump_flags
688 """
689
690 def __init__(self):
691 gdb.Command.__init__(self, 'dump-fn', gdb.COMMAND_USER)
692
693 def invoke(self, arg, from_tty):
694 # Parse args, check number of args
695 args = gdb.string_to_argv(arg)
696 if len(args) >= 1 and args[0] == "/f":
697 if len(args) == 1:
698 print ("Missing file argument")
699 return
700 filename = args[1]
701 editor_mode = False
702 base_arg = 2
703 else:
704 editor = os.getenv("EDITOR", "")
705 if editor == "":
706 print ("EDITOR environment variable not defined")
707 return
708 editor_mode = True
709 base_arg = 0
710 if len(args) - base_arg > 2:
711 print ("Too many arguments")
712 return
713
714 # Set func
715 if len(args) - base_arg >= 1:
716 funcname = args[base_arg]
717 printfuncname = "function %s" % funcname
718 else:
719 funcname = "cfun ? cfun->decl : current_function_decl"
720 printfuncname = "current function"
721 func = gdb.parse_and_eval(funcname)
722 if func == 0:
723 print ("Could not find %s" % printfuncname)
724 return
725 func = "(tree)%u" % func
726
727 # Set flags
728 if len(args) - base_arg >= 2:
729 flags = gdb.parse_and_eval(args[base_arg + 1])
730 else:
731 flags = 0
732
733 # Get tempory file, if necessary
734 if editor_mode:
735 f = tempfile.NamedTemporaryFile(delete=False, suffix=".txt")
736 filename = f.name
737 f.close()
738
739 # Open file
740 fp = gdb.parse_and_eval("fopen (\"%s\", \"w\")" % filename)
741 if fp == 0:
742 print ("Could not open file: %s" % filename)
743 return
744 fp = "(FILE *)%u" % fp
745
746 # Dump function to file
747 _ = gdb.parse_and_eval("dump_function_to_file (%s, %s, %u)" %
748 (func, fp, flags))
749
750 # Close file
751 ret = gdb.parse_and_eval("fclose (%s)" % fp)
752 if ret != 0:
753 print ("Could not close file: %s" % filename)
754 return
755
756 # Open file in editor, if necessary
757 if editor_mode:
758 os.system("( %s \"%s\"; rm \"%s\" ) &" %
759 (editor, filename, filename))
760
761 DumpFn()
762
763 class DotFn(gdb.Command):
764 """
765 A custom command to show a gimple/rtl function control flow graph.
766 By default, it show the current function, but the function can also be
767 specified.
768
769 Examples of use:
770 (gdb) dot-fn
771 (gdb) dot-fn cfun
772 (gdb) dot-fn cfun 0
773 (gdb) dot-fn cfun dump_flags
774 """
775 def __init__(self):
776 gdb.Command.__init__(self, 'dot-fn', gdb.COMMAND_USER)
777
778 def invoke(self, arg, from_tty):
779 # Parse args, check number of args
780 args = gdb.string_to_argv(arg)
781 if len(args) > 2:
782 print("Too many arguments")
783 return
784
785 # Set func
786 if len(args) >= 1:
787 funcname = args[0]
788 printfuncname = "function %s" % funcname
789 else:
790 funcname = "cfun"
791 printfuncname = "current function"
792 func = gdb.parse_and_eval(funcname)
793 if func == 0:
794 print("Could not find %s" % printfuncname)
795 return
796 func = "(struct function *)%s" % func
797
798 # Set flags
799 if len(args) >= 2:
800 flags = gdb.parse_and_eval(args[1])
801 else:
802 flags = 0
803
804 # Get temp file
805 f = tempfile.NamedTemporaryFile(delete=False)
806 filename = f.name
807
808 # Close and reopen temp file to get C FILE*
809 f.close()
810 fp = gdb.parse_and_eval("fopen (\"%s\", \"w\")" % filename)
811 if fp == 0:
812 print("Cannot open temp file")
813 return
814 fp = "(FILE *)%u" % fp
815
816 # Write graph to temp file
817 _ = gdb.parse_and_eval("start_graph_dump (%s, \"<debug>\")" % fp)
818 _ = gdb.parse_and_eval("print_graph_cfg (%s, %s, %u)"
819 % (fp, func, flags))
820 _ = gdb.parse_and_eval("end_graph_dump (%s)" % fp)
821
822 # Close temp file
823 ret = gdb.parse_and_eval("fclose (%s)" % fp)
824 if ret != 0:
825 print("Could not close temp file: %s" % filename)
826 return
827
828 # Show graph in temp file
829 os.system("( dot -Tx11 \"%s\"; rm \"%s\" ) &" % (filename, filename))
830
831 DotFn()
832
833 print('Successfully loaded GDB hooks for GCC')