1 @c Copyright (C) 2008-2014 Free Software Foundation, Inc.
2 @c Permission is granted to copy, distribute and/or modify this document
3 @c under the terms of the GNU Free Documentation License, Version 1.3 or
4 @c any later version published by the Free Software Foundation; with the
5 @c Invariant Sections being ``Free Software'' and ``Free Software Needs
6 @c Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,''
7 @c and with the Back-Cover Texts as in (a) below.
9 @c (a) The FSF's Back-Cover Text is: ``You are free to copy and modify
10 @c this GNU Manual. Buying copies from GNU Press supports the FSF in
11 @c developing GNU and promoting software freedom.''
14 @section Extending @value{GDBN} using Python
15 @cindex python scripting
16 @cindex scripting with python
18 You can extend @value{GDBN} using the @uref{http://www.python.org/,
19 Python programming language}. This feature is available only if
20 @value{GDBN} was configured using @option{--with-python}.
22 @cindex python directory
23 Python scripts used by @value{GDBN} should be installed in
24 @file{@var{data-directory}/python}, where @var{data-directory} is
25 the data directory as determined at @value{GDBN} startup (@pxref{Data Files}).
26 This directory, known as the @dfn{python directory},
27 is automatically added to the Python Search Path in order to allow
28 the Python interpreter to locate all scripts installed at this location.
30 Additionally, @value{GDBN} commands and convenience functions which
31 are written in Python and are located in the
32 @file{@var{data-directory}/python/gdb/command} or
33 @file{@var{data-directory}/python/gdb/function} directories are
34 automatically imported when @value{GDBN} starts.
37 * Python Commands:: Accessing Python from @value{GDBN}.
38 * Python API:: Accessing @value{GDBN} from Python.
39 * Python Auto-loading:: Automatically loading Python code.
40 * Python modules:: Python modules provided by @value{GDBN}.
44 @subsection Python Commands
45 @cindex python commands
46 @cindex commands to access python
48 @value{GDBN} provides two commands for accessing the Python interpreter,
49 and one related setting:
52 @kindex python-interactive
54 @item python-interactive @r{[}@var{command}@r{]}
55 @itemx pi @r{[}@var{command}@r{]}
56 Without an argument, the @code{python-interactive} command can be used
57 to start an interactive Python prompt. To return to @value{GDBN},
58 type the @code{EOF} character (e.g., @kbd{Ctrl-D} on an empty prompt).
60 Alternatively, a single-line Python command can be given as an
61 argument and evaluated. If the command is an expression, the result
62 will be printed; otherwise, nothing will be printed. For example:
65 (@value{GDBP}) python-interactive 2 + 3
71 @item python @r{[}@var{command}@r{]}
72 @itemx py @r{[}@var{command}@r{]}
73 The @code{python} command can be used to evaluate Python code.
75 If given an argument, the @code{python} command will evaluate the
76 argument as a Python command. For example:
79 (@value{GDBP}) python print 23
83 If you do not provide an argument to @code{python}, it will act as a
84 multi-line command, like @code{define}. In this case, the Python
85 script is made up of subsequent command lines, given after the
86 @code{python} command. This command list is terminated using a line
87 containing @code{end}. For example:
92 End with a line saying just "end".
98 @kindex set python print-stack
99 @item set python print-stack
100 By default, @value{GDBN} will print only the message component of a
101 Python exception when an error occurs in a Python script. This can be
102 controlled using @code{set python print-stack}: if @code{full}, then
103 full Python stack printing is enabled; if @code{none}, then Python stack
104 and message printing is disabled; if @code{message}, the default, only
105 the message component of the error is printed.
108 It is also possible to execute a Python script from the @value{GDBN}
112 @item source @file{script-name}
113 The script name must end with @samp{.py} and @value{GDBN} must be configured
114 to recognize the script language based on filename extension using
115 the @code{script-extension} setting. @xref{Extending GDB, ,Extending GDB}.
117 @item python execfile ("script-name")
118 This method is based on the @code{execfile} Python built-in function,
119 and thus is always available.
123 @subsection Python API
125 @cindex programming in python
127 You can get quick online help for @value{GDBN}'s Python API by issuing
128 the command @w{@kbd{python help (gdb)}}.
130 Functions and methods which have two or more optional arguments allow
131 them to be specified using keyword syntax. This allows passing some
132 optional arguments while skipping others. Example:
133 @w{@code{gdb.some_function ('foo', bar = 1, baz = 2)}}.
136 * Basic Python:: Basic Python Functions.
137 * Exception Handling:: How Python exceptions are translated.
138 * Values From Inferior:: Python representation of values.
139 * Types In Python:: Python representation of types.
140 * Pretty Printing API:: Pretty-printing values.
141 * Selecting Pretty-Printers:: How GDB chooses a pretty-printer.
142 * Writing a Pretty-Printer:: Writing a Pretty-Printer.
143 * Type Printing API:: Pretty-printing types.
144 * Frame Filter API:: Filtering Frames.
145 * Frame Decorator API:: Decorating Frames.
146 * Writing a Frame Filter:: Writing a Frame Filter.
147 * Inferiors In Python:: Python representation of inferiors (processes)
148 * Events In Python:: Listening for events from @value{GDBN}.
149 * Threads In Python:: Accessing inferior threads from Python.
150 * Commands In Python:: Implementing new commands in Python.
151 * Parameters In Python:: Adding new @value{GDBN} parameters.
152 * Functions In Python:: Writing new convenience functions.
153 * Progspaces In Python:: Program spaces.
154 * Objfiles In Python:: Object files.
155 * Frames In Python:: Accessing inferior stack frames from Python.
156 * Blocks In Python:: Accessing blocks from Python.
157 * Symbols In Python:: Python representation of symbols.
158 * Symbol Tables In Python:: Python representation of symbol tables.
159 * Line Tables In Python:: Python representation of line tables.
160 * Breakpoints In Python:: Manipulating breakpoints using Python.
161 * Finish Breakpoints in Python:: Setting Breakpoints on function return
163 * Lazy Strings In Python:: Python representation of lazy strings.
164 * Architectures In Python:: Python representation of architectures.
168 @subsubsection Basic Python
170 @cindex python stdout
171 @cindex python pagination
172 At startup, @value{GDBN} overrides Python's @code{sys.stdout} and
173 @code{sys.stderr} to print using @value{GDBN}'s output-paging streams.
174 A Python program which outputs to one of these streams may have its
175 output interrupted by the user (@pxref{Screen Size}). In this
176 situation, a Python @code{KeyboardInterrupt} exception is thrown.
178 Some care must be taken when writing Python code to run in
179 @value{GDBN}. Two things worth noting in particular:
183 @value{GDBN} install handlers for @code{SIGCHLD} and @code{SIGINT}.
184 Python code must not override these, or even change the options using
185 @code{sigaction}. If your program changes the handling of these
186 signals, @value{GDBN} will most likely stop working correctly. Note
187 that it is unfortunately common for GUI toolkits to install a
188 @code{SIGCHLD} handler.
191 @value{GDBN} takes care to mark its internal file descriptors as
192 close-on-exec. However, this cannot be done in a thread-safe way on
193 all platforms. Your Python programs should be aware of this and
194 should both create new file descriptors with the close-on-exec flag
195 set and arrange to close unneeded file descriptors before starting a
199 @cindex python functions
200 @cindex python module
202 @value{GDBN} introduces a new Python module, named @code{gdb}. All
203 methods and classes added by @value{GDBN} are placed in this module.
204 @value{GDBN} automatically @code{import}s the @code{gdb} module for
205 use in all scripts evaluated by the @code{python} command.
207 @findex gdb.PYTHONDIR
208 @defvar gdb.PYTHONDIR
209 A string containing the python directory (@pxref{Python}).
213 @defun gdb.execute (command @r{[}, from_tty @r{[}, to_string@r{]]})
214 Evaluate @var{command}, a string, as a @value{GDBN} CLI command.
215 If a GDB exception happens while @var{command} runs, it is
216 translated as described in @ref{Exception Handling,,Exception Handling}.
218 @var{from_tty} specifies whether @value{GDBN} ought to consider this
219 command as having originated from the user invoking it interactively.
220 It must be a boolean value. If omitted, it defaults to @code{False}.
222 By default, any output produced by @var{command} is sent to
223 @value{GDBN}'s standard output (and to the log output if logging is
224 turned on). If the @var{to_string} parameter is
225 @code{True}, then output will be collected by @code{gdb.execute} and
226 returned as a string. The default is @code{False}, in which case the
227 return value is @code{None}. If @var{to_string} is @code{True}, the
228 @value{GDBN} virtual terminal will be temporarily set to unlimited width
229 and height, and its pagination will be disabled; @pxref{Screen Size}.
232 @findex gdb.breakpoints
233 @defun gdb.breakpoints ()
234 Return a sequence holding all of @value{GDBN}'s breakpoints.
235 @xref{Breakpoints In Python}, for more information.
238 @findex gdb.parameter
239 @defun gdb.parameter (parameter)
240 Return the value of a @value{GDBN} parameter. @var{parameter} is a
241 string naming the parameter to look up; @var{parameter} may contain
242 spaces if the parameter has a multi-part name. For example,
243 @samp{print object} is a valid parameter name.
245 If the named parameter does not exist, this function throws a
246 @code{gdb.error} (@pxref{Exception Handling}). Otherwise, the
247 parameter's value is converted to a Python value of the appropriate
252 @defun gdb.history (number)
253 Return a value from @value{GDBN}'s value history (@pxref{Value
254 History}). @var{number} indicates which history element to return.
255 If @var{number} is negative, then @value{GDBN} will take its absolute value
256 and count backward from the last element (i.e., the most recent element) to
257 find the value to return. If @var{number} is zero, then @value{GDBN} will
258 return the most recent element. If the element specified by @var{number}
259 doesn't exist in the value history, a @code{gdb.error} exception will be
262 If no exception is raised, the return value is always an instance of
263 @code{gdb.Value} (@pxref{Values From Inferior}).
266 @findex gdb.parse_and_eval
267 @defun gdb.parse_and_eval (expression)
268 Parse @var{expression} as an expression in the current language,
269 evaluate it, and return the result as a @code{gdb.Value}.
270 @var{expression} must be a string.
272 This function can be useful when implementing a new command
273 (@pxref{Commands In Python}), as it provides a way to parse the
274 command's argument as an expression. It is also useful simply to
275 compute values, for example, it is the only way to get the value of a
276 convenience variable (@pxref{Convenience Vars}) as a @code{gdb.Value}.
279 @findex gdb.find_pc_line
280 @defun gdb.find_pc_line (pc)
281 Return the @code{gdb.Symtab_and_line} object corresponding to the
282 @var{pc} value. @xref{Symbol Tables In Python}. If an invalid
283 value of @var{pc} is passed as an argument, then the @code{symtab} and
284 @code{line} attributes of the returned @code{gdb.Symtab_and_line} object
285 will be @code{None} and 0 respectively.
288 @findex gdb.post_event
289 @defun gdb.post_event (event)
290 Put @var{event}, a callable object taking no arguments, into
291 @value{GDBN}'s internal event queue. This callable will be invoked at
292 some later point, during @value{GDBN}'s event processing. Events
293 posted using @code{post_event} will be run in the order in which they
294 were posted; however, there is no way to know when they will be
295 processed relative to other events inside @value{GDBN}.
297 @value{GDBN} is not thread-safe. If your Python program uses multiple
298 threads, you must be careful to only call @value{GDBN}-specific
299 functions in the @value{GDBN} thread. @code{post_event} ensures
303 (@value{GDBP}) python
307 > def __init__(self, message):
308 > self.message = message;
309 > def __call__(self):
310 > gdb.write(self.message)
312 >class MyThread1 (threading.Thread):
314 > gdb.post_event(Writer("Hello "))
316 >class MyThread2 (threading.Thread):
318 > gdb.post_event(Writer("World\n"))
323 (@value{GDBP}) Hello World
328 @defun gdb.write (string @r{[}, stream{]})
329 Print a string to @value{GDBN}'s paginated output stream. The
330 optional @var{stream} determines the stream to print to. The default
331 stream is @value{GDBN}'s standard output stream. Possible stream
338 @value{GDBN}'s standard output stream.
343 @value{GDBN}'s standard error stream.
348 @value{GDBN}'s log stream (@pxref{Logging Output}).
351 Writing to @code{sys.stdout} or @code{sys.stderr} will automatically
352 call this function and will automatically direct the output to the
358 Flush the buffer of a @value{GDBN} paginated stream so that the
359 contents are displayed immediately. @value{GDBN} will flush the
360 contents of a stream automatically when it encounters a newline in the
361 buffer. The optional @var{stream} determines the stream to flush. The
362 default stream is @value{GDBN}'s standard output stream. Possible
369 @value{GDBN}'s standard output stream.
374 @value{GDBN}'s standard error stream.
379 @value{GDBN}'s log stream (@pxref{Logging Output}).
383 Flushing @code{sys.stdout} or @code{sys.stderr} will automatically
384 call this function for the relevant stream.
387 @findex gdb.target_charset
388 @defun gdb.target_charset ()
389 Return the name of the current target character set (@pxref{Character
390 Sets}). This differs from @code{gdb.parameter('target-charset')} in
391 that @samp{auto} is never returned.
394 @findex gdb.target_wide_charset
395 @defun gdb.target_wide_charset ()
396 Return the name of the current target wide character set
397 (@pxref{Character Sets}). This differs from
398 @code{gdb.parameter('target-wide-charset')} in that @samp{auto} is
402 @findex gdb.solib_name
403 @defun gdb.solib_name (address)
404 Return the name of the shared library holding the given @var{address}
405 as a string, or @code{None}.
408 @findex gdb.decode_line
409 @defun gdb.decode_line @r{[}expression@r{]}
410 Return locations of the line specified by @var{expression}, or of the
411 current line if no argument was given. This function returns a Python
412 tuple containing two elements. The first element contains a string
413 holding any unparsed section of @var{expression} (or @code{None} if
414 the expression has been fully parsed). The second element contains
415 either @code{None} or another tuple that contains all the locations
416 that match the expression represented as @code{gdb.Symtab_and_line}
417 objects (@pxref{Symbol Tables In Python}). If @var{expression} is
418 provided, it is decoded the way that @value{GDBN}'s inbuilt
419 @code{break} or @code{edit} commands do (@pxref{Specify Location}).
422 @defun gdb.prompt_hook (current_prompt)
425 If @var{prompt_hook} is callable, @value{GDBN} will call the method
426 assigned to this operation before a prompt is displayed by
429 The parameter @code{current_prompt} contains the current @value{GDBN}
430 prompt. This method must return a Python string, or @code{None}. If
431 a string is returned, the @value{GDBN} prompt will be set to that
432 string. If @code{None} is returned, @value{GDBN} will continue to use
435 Some prompts cannot be substituted in @value{GDBN}. Secondary prompts
436 such as those used by readline for command input, and annotation
437 related prompts are prohibited from being changed.
440 @node Exception Handling
441 @subsubsection Exception Handling
442 @cindex python exceptions
443 @cindex exceptions, python
445 When executing the @code{python} command, Python exceptions
446 uncaught within the Python code are translated to calls to
447 @value{GDBN} error-reporting mechanism. If the command that called
448 @code{python} does not handle the error, @value{GDBN} will
449 terminate it and print an error message containing the Python
450 exception name, the associated value, and the Python call stack
451 backtrace at the point where the exception was raised. Example:
454 (@value{GDBP}) python print foo
455 Traceback (most recent call last):
456 File "<string>", line 1, in <module>
457 NameError: name 'foo' is not defined
460 @value{GDBN} errors that happen in @value{GDBN} commands invoked by
461 Python code are converted to Python exceptions. The type of the
462 Python exception depends on the error.
466 This is the base class for most exceptions generated by @value{GDBN}.
467 It is derived from @code{RuntimeError}, for compatibility with earlier
468 versions of @value{GDBN}.
470 If an error occurring in @value{GDBN} does not fit into some more
471 specific category, then the generated exception will have this type.
473 @item gdb.MemoryError
474 This is a subclass of @code{gdb.error} which is thrown when an
475 operation tried to access invalid memory in the inferior.
477 @item KeyboardInterrupt
478 User interrupt (via @kbd{C-c} or by typing @kbd{q} at a pagination
479 prompt) is translated to a Python @code{KeyboardInterrupt} exception.
482 In all cases, your exception handler will see the @value{GDBN} error
483 message as its value and the Python call stack backtrace at the Python
484 statement closest to where the @value{GDBN} error occured as the
488 When implementing @value{GDBN} commands in Python via @code{gdb.Command},
489 it is useful to be able to throw an exception that doesn't cause a
490 traceback to be printed. For example, the user may have invoked the
491 command incorrectly. Use the @code{gdb.GdbError} exception
492 to handle this case. Example:
496 >class HelloWorld (gdb.Command):
497 > """Greet the whole world."""
498 > def __init__ (self):
499 > super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
500 > def invoke (self, args, from_tty):
501 > argv = gdb.string_to_argv (args)
502 > if len (argv) != 0:
503 > raise gdb.GdbError ("hello-world takes no arguments")
504 > print "Hello, World!"
508 hello-world takes no arguments
511 @node Values From Inferior
512 @subsubsection Values From Inferior
513 @cindex values from inferior, with Python
514 @cindex python, working with values from inferior
516 @cindex @code{gdb.Value}
517 @value{GDBN} provides values it obtains from the inferior program in
518 an object of type @code{gdb.Value}. @value{GDBN} uses this object
519 for its internal bookkeeping of the inferior's values, and for
520 fetching values when necessary.
522 Inferior values that are simple scalars can be used directly in
523 Python expressions that are valid for the value's data type. Here's
524 an example for an integer or floating-point value @code{some_val}:
531 As result of this, @code{bar} will also be a @code{gdb.Value} object
532 whose values are of the same type as those of @code{some_val}. Valid
533 Python operations can also be performed on @code{gdb.Value} objects
534 representing a @code{struct} or @code{class} object. For such cases,
535 the overloaded operator (if present), is used to perform the operation.
536 For example, if @code{val1} and @code{val2} are @code{gdb.Value} objects
537 representing instances of a @code{class} which overloads the @code{+}
538 operator, then one can use the @code{+} operator in their Python script
546 The result of the operation @code{val3} is also a @code{gdb.Value}
547 object corresponding to the value returned by the overloaded @code{+}
548 operator. In general, overloaded operators are invoked for the
549 following operations: @code{+} (binary addition), @code{-} (binary
550 subtraction), @code{*} (multiplication), @code{/}, @code{%}, @code{<<},
551 @code{>>}, @code{|}, @code{&}, @code{^}.
553 Inferior values that are structures or instances of some class can
554 be accessed using the Python @dfn{dictionary syntax}. For example, if
555 @code{some_val} is a @code{gdb.Value} instance holding a structure, you
556 can access its @code{foo} element with:
559 bar = some_val['foo']
562 @cindex getting structure elements using gdb.Field objects as subscripts
563 Again, @code{bar} will also be a @code{gdb.Value} object. Structure
564 elements can also be accessed by using @code{gdb.Field} objects as
565 subscripts (@pxref{Types In Python}, for more information on
566 @code{gdb.Field} objects). For example, if @code{foo_field} is a
567 @code{gdb.Field} object corresponding to element @code{foo} of the above
568 structure, then @code{bar} can also be accessed as follows:
571 bar = some_val[foo_field]
574 A @code{gdb.Value} that represents a function can be executed via
575 inferior function call. Any arguments provided to the call must match
576 the function's prototype, and must be provided in the order specified
579 For example, @code{some_val} is a @code{gdb.Value} instance
580 representing a function that takes two integers as arguments. To
581 execute this function, call it like so:
584 result = some_val (10,20)
587 Any values returned from a function call will be stored as a
590 The following attributes are provided:
592 @defvar Value.address
593 If this object is addressable, this read-only attribute holds a
594 @code{gdb.Value} object representing the address. Otherwise,
595 this attribute holds @code{None}.
598 @cindex optimized out value in Python
599 @defvar Value.is_optimized_out
600 This read-only boolean attribute is true if the compiler optimized out
601 this value, thus it is not available for fetching from the inferior.
605 The type of this @code{gdb.Value}. The value of this attribute is a
606 @code{gdb.Type} object (@pxref{Types In Python}).
609 @defvar Value.dynamic_type
610 The dynamic type of this @code{gdb.Value}. This uses C@t{++} run-time
611 type information (@acronym{RTTI}) to determine the dynamic type of the
612 value. If this value is of class type, it will return the class in
613 which the value is embedded, if any. If this value is of pointer or
614 reference to a class type, it will compute the dynamic type of the
615 referenced object, and return a pointer or reference to that type,
616 respectively. In all other cases, it will return the value's static
619 Note that this feature will only work when debugging a C@t{++} program
620 that includes @acronym{RTTI} for the object in question. Otherwise,
621 it will just return the static type of the value as in @kbd{ptype foo}
622 (@pxref{Symbols, ptype}).
625 @defvar Value.is_lazy
626 The value of this read-only boolean attribute is @code{True} if this
627 @code{gdb.Value} has not yet been fetched from the inferior.
628 @value{GDBN} does not fetch values until necessary, for efficiency.
632 myval = gdb.parse_and_eval ('somevar')
635 The value of @code{somevar} is not fetched at this time. It will be
636 fetched when the value is needed, or when the @code{fetch_lazy}
640 The following methods are provided:
642 @defun Value.__init__ (@var{val})
643 Many Python values can be converted directly to a @code{gdb.Value} via
644 this object initializer. Specifically:
648 A Python boolean is converted to the boolean type from the current
652 A Python integer is converted to the C @code{long} type for the
653 current architecture.
656 A Python long is converted to the C @code{long long} type for the
657 current architecture.
660 A Python float is converted to the C @code{double} type for the
661 current architecture.
664 A Python string is converted to a target string in the current target
665 language using the current target encoding.
666 If a character cannot be represented in the current target encoding,
667 then an exception is thrown.
669 @item @code{gdb.Value}
670 If @code{val} is a @code{gdb.Value}, then a copy of the value is made.
672 @item @code{gdb.LazyString}
673 If @code{val} is a @code{gdb.LazyString} (@pxref{Lazy Strings In
674 Python}), then the lazy string's @code{value} method is called, and
679 @defun Value.cast (type)
680 Return a new instance of @code{gdb.Value} that is the result of
681 casting this instance to the type described by @var{type}, which must
682 be a @code{gdb.Type} object. If the cast cannot be performed for some
683 reason, this method throws an exception.
686 @defun Value.dereference ()
687 For pointer data types, this method returns a new @code{gdb.Value} object
688 whose contents is the object pointed to by the pointer. For example, if
689 @code{foo} is a C pointer to an @code{int}, declared in your C program as
696 then you can use the corresponding @code{gdb.Value} to access what
697 @code{foo} points to like this:
700 bar = foo.dereference ()
703 The result @code{bar} will be a @code{gdb.Value} object holding the
704 value pointed to by @code{foo}.
706 A similar function @code{Value.referenced_value} exists which also
707 returns @code{gdb.Value} objects corresonding to the values pointed to
708 by pointer values (and additionally, values referenced by reference
709 values). However, the behavior of @code{Value.dereference}
710 differs from @code{Value.referenced_value} by the fact that the
711 behavior of @code{Value.dereference} is identical to applying the C
712 unary operator @code{*} on a given value. For example, consider a
713 reference to a pointer @code{ptrref}, declared in your C@t{++} program
721 intptr &ptrref = ptr;
724 Though @code{ptrref} is a reference value, one can apply the method
725 @code{Value.dereference} to the @code{gdb.Value} object corresponding
726 to it and obtain a @code{gdb.Value} which is identical to that
727 corresponding to @code{val}. However, if you apply the method
728 @code{Value.referenced_value}, the result would be a @code{gdb.Value}
729 object identical to that corresponding to @code{ptr}.
732 py_ptrref = gdb.parse_and_eval ("ptrref")
733 py_val = py_ptrref.dereference ()
734 py_ptr = py_ptrref.referenced_value ()
737 The @code{gdb.Value} object @code{py_val} is identical to that
738 corresponding to @code{val}, and @code{py_ptr} is identical to that
739 corresponding to @code{ptr}. In general, @code{Value.dereference} can
740 be applied whenever the C unary operator @code{*} can be applied
741 to the corresponding C value. For those cases where applying both
742 @code{Value.dereference} and @code{Value.referenced_value} is allowed,
743 the results obtained need not be identical (as we have seen in the above
744 example). The results are however identical when applied on
745 @code{gdb.Value} objects corresponding to pointers (@code{gdb.Value}
746 objects with type code @code{TYPE_CODE_PTR}) in a C/C@t{++} program.
749 @defun Value.referenced_value ()
750 For pointer or reference data types, this method returns a new
751 @code{gdb.Value} object corresponding to the value referenced by the
752 pointer/reference value. For pointer data types,
753 @code{Value.dereference} and @code{Value.referenced_value} produce
754 identical results. The difference between these methods is that
755 @code{Value.dereference} cannot get the values referenced by reference
756 values. For example, consider a reference to an @code{int}, declared
757 in your C@t{++} program as
765 then applying @code{Value.dereference} to the @code{gdb.Value} object
766 corresponding to @code{ref} will result in an error, while applying
767 @code{Value.referenced_value} will result in a @code{gdb.Value} object
768 identical to that corresponding to @code{val}.
771 py_ref = gdb.parse_and_eval ("ref")
772 er_ref = py_ref.dereference () # Results in error
773 py_val = py_ref.referenced_value () # Returns the referenced value
776 The @code{gdb.Value} object @code{py_val} is identical to that
777 corresponding to @code{val}.
780 @defun Value.dynamic_cast (type)
781 Like @code{Value.cast}, but works as if the C@t{++} @code{dynamic_cast}
782 operator were used. Consult a C@t{++} reference for details.
785 @defun Value.reinterpret_cast (type)
786 Like @code{Value.cast}, but works as if the C@t{++} @code{reinterpret_cast}
787 operator were used. Consult a C@t{++} reference for details.
790 @defun Value.string (@r{[}encoding@r{[}, errors@r{[}, length@r{]]]})
791 If this @code{gdb.Value} represents a string, then this method
792 converts the contents to a Python string. Otherwise, this method will
795 Values are interpreted as strings according to the rules of the
796 current language. If the optional length argument is given, the
797 string will be converted to that length, and will include any embedded
798 zeroes that the string may contain. Otherwise, for languages
799 where the string is zero-terminated, the entire string will be
802 For example, in C-like languages, a value is a string if it is a pointer
803 to or an array of characters or ints of type @code{wchar_t}, @code{char16_t},
806 If the optional @var{encoding} argument is given, it must be a string
807 naming the encoding of the string in the @code{gdb.Value}, such as
808 @code{"ascii"}, @code{"iso-8859-6"} or @code{"utf-8"}. It accepts
809 the same encodings as the corresponding argument to Python's
810 @code{string.decode} method, and the Python codec machinery will be used
811 to convert the string. If @var{encoding} is not given, or if
812 @var{encoding} is the empty string, then either the @code{target-charset}
813 (@pxref{Character Sets}) will be used, or a language-specific encoding
814 will be used, if the current language is able to supply one.
816 The optional @var{errors} argument is the same as the corresponding
817 argument to Python's @code{string.decode} method.
819 If the optional @var{length} argument is given, the string will be
820 fetched and converted to the given length.
823 @defun Value.lazy_string (@r{[}encoding @r{[}, length@r{]]})
824 If this @code{gdb.Value} represents a string, then this method
825 converts the contents to a @code{gdb.LazyString} (@pxref{Lazy Strings
826 In Python}). Otherwise, this method will throw an exception.
828 If the optional @var{encoding} argument is given, it must be a string
829 naming the encoding of the @code{gdb.LazyString}. Some examples are:
830 @samp{ascii}, @samp{iso-8859-6} or @samp{utf-8}. If the
831 @var{encoding} argument is an encoding that @value{GDBN} does
832 recognize, @value{GDBN} will raise an error.
834 When a lazy string is printed, the @value{GDBN} encoding machinery is
835 used to convert the string during printing. If the optional
836 @var{encoding} argument is not provided, or is an empty string,
837 @value{GDBN} will automatically select the encoding most suitable for
838 the string type. For further information on encoding in @value{GDBN}
839 please see @ref{Character Sets}.
841 If the optional @var{length} argument is given, the string will be
842 fetched and encoded to the length of characters specified. If
843 the @var{length} argument is not provided, the string will be fetched
844 and encoded until a null of appropriate width is found.
847 @defun Value.fetch_lazy ()
848 If the @code{gdb.Value} object is currently a lazy value
849 (@code{gdb.Value.is_lazy} is @code{True}), then the value is
850 fetched from the inferior. Any errors that occur in the process
851 will produce a Python exception.
853 If the @code{gdb.Value} object is not a lazy value, this method
856 This method does not return a value.
860 @node Types In Python
861 @subsubsection Types In Python
862 @cindex types in Python
863 @cindex Python, working with types
866 @value{GDBN} represents types from the inferior using the class
869 The following type-related functions are available in the @code{gdb}
872 @findex gdb.lookup_type
873 @defun gdb.lookup_type (name @r{[}, block@r{]})
874 This function looks up a type by name. @var{name} is the name of the
875 type to look up. It must be a string.
877 If @var{block} is given, then @var{name} is looked up in that scope.
878 Otherwise, it is searched for globally.
880 Ordinarily, this function will return an instance of @code{gdb.Type}.
881 If the named type cannot be found, it will throw an exception.
884 If the type is a structure or class type, or an enum type, the fields
885 of that type can be accessed using the Python @dfn{dictionary syntax}.
886 For example, if @code{some_type} is a @code{gdb.Type} instance holding
887 a structure type, you can access its @code{foo} field with:
890 bar = some_type['foo']
893 @code{bar} will be a @code{gdb.Field} object; see below under the
894 description of the @code{Type.fields} method for a description of the
895 @code{gdb.Field} class.
897 An instance of @code{Type} has the following attributes:
900 The type code for this type. The type code will be one of the
901 @code{TYPE_CODE_} constants defined below.
905 The name of this type. If this type has no name, then @code{None}
910 The size of this type, in target @code{char} units. Usually, a
911 target's @code{char} type will be an 8-bit byte. However, on some
912 unusual platforms, this type may have a different size.
916 The tag name for this type. The tag name is the name after
917 @code{struct}, @code{union}, or @code{enum} in C and C@t{++}; not all
918 languages have this concept. If this type has no tag name, then
919 @code{None} is returned.
922 The following methods are provided:
924 @defun Type.fields ()
925 For structure and union types, this method returns the fields. Range
926 types have two fields, the minimum and maximum values. Enum types
927 have one field per enum constant. Function and method types have one
928 field per parameter. The base types of C@t{++} classes are also
929 represented as fields. If the type has no fields, or does not fit
930 into one of these categories, an empty sequence will be returned.
932 Each field is a @code{gdb.Field} object, with some pre-defined attributes:
935 This attribute is not available for @code{enum} or @code{static}
936 (as in C@t{++} or Java) fields. The value is the position, counting
937 in bits, from the start of the containing type.
940 This attribute is only available for @code{enum} fields, and its value
941 is the enumeration member's integer representation.
944 The name of the field, or @code{None} for anonymous fields.
947 This is @code{True} if the field is artificial, usually meaning that
948 it was provided by the compiler and not the user. This attribute is
949 always provided, and is @code{False} if the field is not artificial.
952 This is @code{True} if the field represents a base class of a C@t{++}
953 structure. This attribute is always provided, and is @code{False}
954 if the field is not a base class of the type that is the argument of
955 @code{fields}, or if that type was not a C@t{++} class.
958 If the field is packed, or is a bitfield, then this will have a
959 non-zero value, which is the size of the field in bits. Otherwise,
960 this will be zero; in this case the field's size is given by its type.
963 The type of the field. This is usually an instance of @code{Type},
964 but it can be @code{None} in some situations.
967 The type which contains this field. This is an instance of
972 @defun Type.array (@var{n1} @r{[}, @var{n2}@r{]})
973 Return a new @code{gdb.Type} object which represents an array of this
974 type. If one argument is given, it is the inclusive upper bound of
975 the array; in this case the lower bound is zero. If two arguments are
976 given, the first argument is the lower bound of the array, and the
977 second argument is the upper bound of the array. An array's length
978 must not be negative, but the bounds can be.
981 @defun Type.vector (@var{n1} @r{[}, @var{n2}@r{]})
982 Return a new @code{gdb.Type} object which represents a vector of this
983 type. If one argument is given, it is the inclusive upper bound of
984 the vector; in this case the lower bound is zero. If two arguments are
985 given, the first argument is the lower bound of the vector, and the
986 second argument is the upper bound of the vector. A vector's length
987 must not be negative, but the bounds can be.
989 The difference between an @code{array} and a @code{vector} is that
990 arrays behave like in C: when used in expressions they decay to a pointer
991 to the first element whereas vectors are treated as first class values.
995 Return a new @code{gdb.Type} object which represents a
996 @code{const}-qualified variant of this type.
999 @defun Type.volatile ()
1000 Return a new @code{gdb.Type} object which represents a
1001 @code{volatile}-qualified variant of this type.
1004 @defun Type.unqualified ()
1005 Return a new @code{gdb.Type} object which represents an unqualified
1006 variant of this type. That is, the result is neither @code{const} nor
1010 @defun Type.range ()
1011 Return a Python @code{Tuple} object that contains two elements: the
1012 low bound of the argument type and the high bound of that type. If
1013 the type does not have a range, @value{GDBN} will raise a
1014 @code{gdb.error} exception (@pxref{Exception Handling}).
1017 @defun Type.reference ()
1018 Return a new @code{gdb.Type} object which represents a reference to this
1022 @defun Type.pointer ()
1023 Return a new @code{gdb.Type} object which represents a pointer to this
1027 @defun Type.strip_typedefs ()
1028 Return a new @code{gdb.Type} that represents the real type,
1029 after removing all layers of typedefs.
1032 @defun Type.target ()
1033 Return a new @code{gdb.Type} object which represents the target type
1036 For a pointer type, the target type is the type of the pointed-to
1037 object. For an array type (meaning C-like arrays), the target type is
1038 the type of the elements of the array. For a function or method type,
1039 the target type is the type of the return value. For a complex type,
1040 the target type is the type of the elements. For a typedef, the
1041 target type is the aliased type.
1043 If the type does not have a target, this method will throw an
1047 @defun Type.template_argument (n @r{[}, block@r{]})
1048 If this @code{gdb.Type} is an instantiation of a template, this will
1049 return a new @code{gdb.Type} which represents the type of the
1050 @var{n}th template argument.
1052 If this @code{gdb.Type} is not a template type, this will throw an
1053 exception. Ordinarily, only C@t{++} code will have template types.
1055 If @var{block} is given, then @var{name} is looked up in that scope.
1056 Otherwise, it is searched for globally.
1060 Each type has a code, which indicates what category this type falls
1061 into. The available type categories are represented by constants
1062 defined in the @code{gdb} module:
1065 @vindex TYPE_CODE_PTR
1066 @item gdb.TYPE_CODE_PTR
1067 The type is a pointer.
1069 @vindex TYPE_CODE_ARRAY
1070 @item gdb.TYPE_CODE_ARRAY
1071 The type is an array.
1073 @vindex TYPE_CODE_STRUCT
1074 @item gdb.TYPE_CODE_STRUCT
1075 The type is a structure.
1077 @vindex TYPE_CODE_UNION
1078 @item gdb.TYPE_CODE_UNION
1079 The type is a union.
1081 @vindex TYPE_CODE_ENUM
1082 @item gdb.TYPE_CODE_ENUM
1083 The type is an enum.
1085 @vindex TYPE_CODE_FLAGS
1086 @item gdb.TYPE_CODE_FLAGS
1087 A bit flags type, used for things such as status registers.
1089 @vindex TYPE_CODE_FUNC
1090 @item gdb.TYPE_CODE_FUNC
1091 The type is a function.
1093 @vindex TYPE_CODE_INT
1094 @item gdb.TYPE_CODE_INT
1095 The type is an integer type.
1097 @vindex TYPE_CODE_FLT
1098 @item gdb.TYPE_CODE_FLT
1099 A floating point type.
1101 @vindex TYPE_CODE_VOID
1102 @item gdb.TYPE_CODE_VOID
1103 The special type @code{void}.
1105 @vindex TYPE_CODE_SET
1106 @item gdb.TYPE_CODE_SET
1109 @vindex TYPE_CODE_RANGE
1110 @item gdb.TYPE_CODE_RANGE
1111 A range type, that is, an integer type with bounds.
1113 @vindex TYPE_CODE_STRING
1114 @item gdb.TYPE_CODE_STRING
1115 A string type. Note that this is only used for certain languages with
1116 language-defined string types; C strings are not represented this way.
1118 @vindex TYPE_CODE_BITSTRING
1119 @item gdb.TYPE_CODE_BITSTRING
1120 A string of bits. It is deprecated.
1122 @vindex TYPE_CODE_ERROR
1123 @item gdb.TYPE_CODE_ERROR
1124 An unknown or erroneous type.
1126 @vindex TYPE_CODE_METHOD
1127 @item gdb.TYPE_CODE_METHOD
1128 A method type, as found in C@t{++} or Java.
1130 @vindex TYPE_CODE_METHODPTR
1131 @item gdb.TYPE_CODE_METHODPTR
1132 A pointer-to-member-function.
1134 @vindex TYPE_CODE_MEMBERPTR
1135 @item gdb.TYPE_CODE_MEMBERPTR
1136 A pointer-to-member.
1138 @vindex TYPE_CODE_REF
1139 @item gdb.TYPE_CODE_REF
1142 @vindex TYPE_CODE_CHAR
1143 @item gdb.TYPE_CODE_CHAR
1146 @vindex TYPE_CODE_BOOL
1147 @item gdb.TYPE_CODE_BOOL
1150 @vindex TYPE_CODE_COMPLEX
1151 @item gdb.TYPE_CODE_COMPLEX
1152 A complex float type.
1154 @vindex TYPE_CODE_TYPEDEF
1155 @item gdb.TYPE_CODE_TYPEDEF
1156 A typedef to some other type.
1158 @vindex TYPE_CODE_NAMESPACE
1159 @item gdb.TYPE_CODE_NAMESPACE
1160 A C@t{++} namespace.
1162 @vindex TYPE_CODE_DECFLOAT
1163 @item gdb.TYPE_CODE_DECFLOAT
1164 A decimal floating point type.
1166 @vindex TYPE_CODE_INTERNAL_FUNCTION
1167 @item gdb.TYPE_CODE_INTERNAL_FUNCTION
1168 A function internal to @value{GDBN}. This is the type used to represent
1169 convenience functions.
1172 Further support for types is provided in the @code{gdb.types}
1173 Python module (@pxref{gdb.types}).
1175 @node Pretty Printing API
1176 @subsubsection Pretty Printing API
1177 @cindex python pretty printing api
1179 An example output is provided (@pxref{Pretty Printing}).
1181 A pretty-printer is just an object that holds a value and implements a
1182 specific interface, defined here.
1184 @defun pretty_printer.children (self)
1185 @value{GDBN} will call this method on a pretty-printer to compute the
1186 children of the pretty-printer's value.
1188 This method must return an object conforming to the Python iterator
1189 protocol. Each item returned by the iterator must be a tuple holding
1190 two elements. The first element is the ``name'' of the child; the
1191 second element is the child's value. The value can be any Python
1192 object which is convertible to a @value{GDBN} value.
1194 This method is optional. If it does not exist, @value{GDBN} will act
1195 as though the value has no children.
1198 @defun pretty_printer.display_hint (self)
1199 The CLI may call this method and use its result to change the
1200 formatting of a value. The result will also be supplied to an MI
1201 consumer as a @samp{displayhint} attribute of the variable being
1204 This method is optional. If it does exist, this method must return a
1207 Some display hints are predefined by @value{GDBN}:
1211 Indicate that the object being printed is ``array-like''. The CLI
1212 uses this to respect parameters such as @code{set print elements} and
1213 @code{set print array}.
1216 Indicate that the object being printed is ``map-like'', and that the
1217 children of this value can be assumed to alternate between keys and
1221 Indicate that the object being printed is ``string-like''. If the
1222 printer's @code{to_string} method returns a Python string of some
1223 kind, then @value{GDBN} will call its internal language-specific
1224 string-printing function to format the string. For the CLI this means
1225 adding quotation marks, possibly escaping some characters, respecting
1226 @code{set print elements}, and the like.
1230 @defun pretty_printer.to_string (self)
1231 @value{GDBN} will call this method to display the string
1232 representation of the value passed to the object's constructor.
1234 When printing from the CLI, if the @code{to_string} method exists,
1235 then @value{GDBN} will prepend its result to the values returned by
1236 @code{children}. Exactly how this formatting is done is dependent on
1237 the display hint, and may change as more hints are added. Also,
1238 depending on the print settings (@pxref{Print Settings}), the CLI may
1239 print just the result of @code{to_string} in a stack trace, omitting
1240 the result of @code{children}.
1242 If this method returns a string, it is printed verbatim.
1244 Otherwise, if this method returns an instance of @code{gdb.Value},
1245 then @value{GDBN} prints this value. This may result in a call to
1246 another pretty-printer.
1248 If instead the method returns a Python value which is convertible to a
1249 @code{gdb.Value}, then @value{GDBN} performs the conversion and prints
1250 the resulting value. Again, this may result in a call to another
1251 pretty-printer. Python scalars (integers, floats, and booleans) and
1252 strings are convertible to @code{gdb.Value}; other types are not.
1254 Finally, if this method returns @code{None} then no further operations
1255 are peformed in this method and nothing is printed.
1257 If the result is not one of these types, an exception is raised.
1260 @value{GDBN} provides a function which can be used to look up the
1261 default pretty-printer for a @code{gdb.Value}:
1263 @findex gdb.default_visualizer
1264 @defun gdb.default_visualizer (value)
1265 This function takes a @code{gdb.Value} object as an argument. If a
1266 pretty-printer for this value exists, then it is returned. If no such
1267 printer exists, then this returns @code{None}.
1270 @node Selecting Pretty-Printers
1271 @subsubsection Selecting Pretty-Printers
1272 @cindex selecting python pretty-printers
1274 The Python list @code{gdb.pretty_printers} contains an array of
1275 functions or callable objects that have been registered via addition
1276 as a pretty-printer. Printers in this list are called @code{global}
1277 printers, they're available when debugging all inferiors.
1278 Each @code{gdb.Progspace} contains a @code{pretty_printers} attribute.
1279 Each @code{gdb.Objfile} also contains a @code{pretty_printers}
1282 Each function on these lists is passed a single @code{gdb.Value}
1283 argument and should return a pretty-printer object conforming to the
1284 interface definition above (@pxref{Pretty Printing API}). If a function
1285 cannot create a pretty-printer for the value, it should return
1288 @value{GDBN} first checks the @code{pretty_printers} attribute of each
1289 @code{gdb.Objfile} in the current program space and iteratively calls
1290 each enabled lookup routine in the list for that @code{gdb.Objfile}
1291 until it receives a pretty-printer object.
1292 If no pretty-printer is found in the objfile lists, @value{GDBN} then
1293 searches the pretty-printer list of the current program space,
1294 calling each enabled function until an object is returned.
1295 After these lists have been exhausted, it tries the global
1296 @code{gdb.pretty_printers} list, again calling each enabled function until an
1299 The order in which the objfiles are searched is not specified. For a
1300 given list, functions are always invoked from the head of the list,
1301 and iterated over sequentially until the end of the list, or a printer
1304 For various reasons a pretty-printer may not work.
1305 For example, the underlying data structure may have changed and
1306 the pretty-printer is out of date.
1308 The consequences of a broken pretty-printer are severe enough that
1309 @value{GDBN} provides support for enabling and disabling individual
1310 printers. For example, if @code{print frame-arguments} is on,
1311 a backtrace can become highly illegible if any argument is printed
1312 with a broken printer.
1314 Pretty-printers are enabled and disabled by attaching an @code{enabled}
1315 attribute to the registered function or callable object. If this attribute
1316 is present and its value is @code{False}, the printer is disabled, otherwise
1317 the printer is enabled.
1319 @node Writing a Pretty-Printer
1320 @subsubsection Writing a Pretty-Printer
1321 @cindex writing a pretty-printer
1323 A pretty-printer consists of two parts: a lookup function to detect
1324 if the type is supported, and the printer itself.
1326 Here is an example showing how a @code{std::string} printer might be
1327 written. @xref{Pretty Printing API}, for details on the API this class
1331 class StdStringPrinter(object):
1332 "Print a std::string"
1334 def __init__(self, val):
1337 def to_string(self):
1338 return self.val['_M_dataplus']['_M_p']
1340 def display_hint(self):
1344 And here is an example showing how a lookup function for the printer
1345 example above might be written.
1348 def str_lookup_function(val):
1349 lookup_tag = val.type.tag
1350 if lookup_tag == None:
1352 regex = re.compile("^std::basic_string<char,.*>$")
1353 if regex.match(lookup_tag):
1354 return StdStringPrinter(val)
1358 The example lookup function extracts the value's type, and attempts to
1359 match it to a type that it can pretty-print. If it is a type the
1360 printer can pretty-print, it will return a printer object. If not, it
1361 returns @code{None}.
1363 We recommend that you put your core pretty-printers into a Python
1364 package. If your pretty-printers are for use with a library, we
1365 further recommend embedding a version number into the package name.
1366 This practice will enable @value{GDBN} to load multiple versions of
1367 your pretty-printers at the same time, because they will have
1370 You should write auto-loaded code (@pxref{Python Auto-loading}) such that it
1371 can be evaluated multiple times without changing its meaning. An
1372 ideal auto-load file will consist solely of @code{import}s of your
1373 printer modules, followed by a call to a register pretty-printers with
1374 the current objfile.
1376 Taken as a whole, this approach will scale nicely to multiple
1377 inferiors, each potentially using a different library version.
1378 Embedding a version number in the Python package name will ensure that
1379 @value{GDBN} is able to load both sets of printers simultaneously.
1380 Then, because the search for pretty-printers is done by objfile, and
1381 because your auto-loaded code took care to register your library's
1382 printers with a specific objfile, @value{GDBN} will find the correct
1383 printers for the specific version of the library used by each
1386 To continue the @code{std::string} example (@pxref{Pretty Printing API}),
1387 this code might appear in @code{gdb.libstdcxx.v6}:
1390 def register_printers(objfile):
1391 objfile.pretty_printers.append(str_lookup_function)
1395 And then the corresponding contents of the auto-load file would be:
1398 import gdb.libstdcxx.v6
1399 gdb.libstdcxx.v6.register_printers(gdb.current_objfile())
1402 The previous example illustrates a basic pretty-printer.
1403 There are a few things that can be improved on.
1404 The printer doesn't have a name, making it hard to identify in a
1405 list of installed printers. The lookup function has a name, but
1406 lookup functions can have arbitrary, even identical, names.
1408 Second, the printer only handles one type, whereas a library typically has
1409 several types. One could install a lookup function for each desired type
1410 in the library, but one could also have a single lookup function recognize
1411 several types. The latter is the conventional way this is handled.
1412 If a pretty-printer can handle multiple data types, then its
1413 @dfn{subprinters} are the printers for the individual data types.
1415 The @code{gdb.printing} module provides a formal way of solving these
1416 problems (@pxref{gdb.printing}).
1417 Here is another example that handles multiple types.
1419 These are the types we are going to pretty-print:
1422 struct foo @{ int a, b; @};
1423 struct bar @{ struct foo x, y; @};
1426 Here are the printers:
1430 """Print a foo object."""
1432 def __init__(self, val):
1435 def to_string(self):
1436 return ("a=<" + str(self.val["a"]) +
1437 "> b=<" + str(self.val["b"]) + ">")
1440 """Print a bar object."""
1442 def __init__(self, val):
1445 def to_string(self):
1446 return ("x=<" + str(self.val["x"]) +
1447 "> y=<" + str(self.val["y"]) + ">")
1450 This example doesn't need a lookup function, that is handled by the
1451 @code{gdb.printing} module. Instead a function is provided to build up
1452 the object that handles the lookup.
1457 def build_pretty_printer():
1458 pp = gdb.printing.RegexpCollectionPrettyPrinter(
1460 pp.add_printer('foo', '^foo$', fooPrinter)
1461 pp.add_printer('bar', '^bar$', barPrinter)
1465 And here is the autoload support:
1470 gdb.printing.register_pretty_printer(
1471 gdb.current_objfile(),
1472 my_library.build_pretty_printer())
1475 Finally, when this printer is loaded into @value{GDBN}, here is the
1476 corresponding output of @samp{info pretty-printer}:
1479 (gdb) info pretty-printer
1486 @node Type Printing API
1487 @subsubsection Type Printing API
1488 @cindex type printing API for Python
1490 @value{GDBN} provides a way for Python code to customize type display.
1491 This is mainly useful for substituting canonical typedef names for
1494 @cindex type printer
1495 A @dfn{type printer} is just a Python object conforming to a certain
1496 protocol. A simple base class implementing the protocol is provided;
1497 see @ref{gdb.types}. A type printer must supply at least:
1499 @defivar type_printer enabled
1500 A boolean which is True if the printer is enabled, and False
1501 otherwise. This is manipulated by the @code{enable type-printer}
1502 and @code{disable type-printer} commands.
1505 @defivar type_printer name
1506 The name of the type printer. This must be a string. This is used by
1507 the @code{enable type-printer} and @code{disable type-printer}
1511 @defmethod type_printer instantiate (self)
1512 This is called by @value{GDBN} at the start of type-printing. It is
1513 only called if the type printer is enabled. This method must return a
1514 new object that supplies a @code{recognize} method, as described below.
1518 When displaying a type, say via the @code{ptype} command, @value{GDBN}
1519 will compute a list of type recognizers. This is done by iterating
1520 first over the per-objfile type printers (@pxref{Objfiles In Python}),
1521 followed by the per-progspace type printers (@pxref{Progspaces In
1522 Python}), and finally the global type printers.
1524 @value{GDBN} will call the @code{instantiate} method of each enabled
1525 type printer. If this method returns @code{None}, then the result is
1526 ignored; otherwise, it is appended to the list of recognizers.
1528 Then, when @value{GDBN} is going to display a type name, it iterates
1529 over the list of recognizers. For each one, it calls the recognition
1530 function, stopping if the function returns a non-@code{None} value.
1531 The recognition function is defined as:
1533 @defmethod type_recognizer recognize (self, type)
1534 If @var{type} is not recognized, return @code{None}. Otherwise,
1535 return a string which is to be printed as the name of @var{type}.
1536 @var{type} will be an instance of @code{gdb.Type} (@pxref{Types In
1540 @value{GDBN} uses this two-pass approach so that type printers can
1541 efficiently cache information without holding on to it too long. For
1542 example, it can be convenient to look up type information in a type
1543 printer and hold it for a recognizer's lifetime; if a single pass were
1544 done then type printers would have to make use of the event system in
1545 order to avoid holding information that could become stale as the
1548 @node Frame Filter API
1549 @subsubsection Filtering Frames.
1550 @cindex frame filters api
1552 Frame filters are Python objects that manipulate the visibility of a
1553 frame or frames when a backtrace (@pxref{Backtrace}) is printed by
1556 Only commands that print a backtrace, or, in the case of @sc{gdb/mi}
1557 commands (@pxref{GDB/MI}), those that return a collection of frames
1558 are affected. The commands that work with frame filters are:
1560 @code{backtrace} (@pxref{backtrace-command,, The backtrace command}),
1561 @code{-stack-list-frames}
1562 (@pxref{-stack-list-frames,, The -stack-list-frames command}),
1563 @code{-stack-list-variables} (@pxref{-stack-list-variables,, The
1564 -stack-list-variables command}), @code{-stack-list-arguments}
1565 @pxref{-stack-list-arguments,, The -stack-list-arguments command}) and
1566 @code{-stack-list-locals} (@pxref{-stack-list-locals,, The
1567 -stack-list-locals command}).
1569 A frame filter works by taking an iterator as an argument, applying
1570 actions to the contents of that iterator, and returning another
1571 iterator (or, possibly, the same iterator it was provided in the case
1572 where the filter does not perform any operations). Typically, frame
1573 filters utilize tools such as the Python's @code{itertools} module to
1574 work with and create new iterators from the source iterator.
1575 Regardless of how a filter chooses to apply actions, it must not alter
1576 the underlying @value{GDBN} frame or frames, or attempt to alter the
1577 call-stack within @value{GDBN}. This preserves data integrity within
1578 @value{GDBN}. Frame filters are executed on a priority basis and care
1579 should be taken that some frame filters may have been executed before,
1580 and that some frame filters will be executed after.
1582 An important consideration when designing frame filters, and well
1583 worth reflecting upon, is that frame filters should avoid unwinding
1584 the call stack if possible. Some stacks can run very deep, into the
1585 tens of thousands in some cases. To search every frame when a frame
1586 filter executes may be too expensive at that step. The frame filter
1587 cannot know how many frames it has to iterate over, and it may have to
1588 iterate through them all. This ends up duplicating effort as
1589 @value{GDBN} performs this iteration when it prints the frames. If
1590 the filter can defer unwinding frames until frame decorators are
1591 executed, after the last filter has executed, it should. @xref{Frame
1592 Decorator API}, for more information on decorators. Also, there are
1593 examples for both frame decorators and filters in later chapters.
1594 @xref{Writing a Frame Filter}, for more information.
1596 The Python dictionary @code{gdb.frame_filters} contains key/object
1597 pairings that comprise a frame filter. Frame filters in this
1598 dictionary are called @code{global} frame filters, and they are
1599 available when debugging all inferiors. These frame filters must
1600 register with the dictionary directly. In addition to the
1601 @code{global} dictionary, there are other dictionaries that are loaded
1602 with different inferiors via auto-loading (@pxref{Python
1603 Auto-loading}). The two other areas where frame filter dictionaries
1604 can be found are: @code{gdb.Progspace} which contains a
1605 @code{frame_filters} dictionary attribute, and each @code{gdb.Objfile}
1606 object which also contains a @code{frame_filters} dictionary
1609 When a command is executed from @value{GDBN} that is compatible with
1610 frame filters, @value{GDBN} combines the @code{global},
1611 @code{gdb.Progspace} and all @code{gdb.Objfile} dictionaries currently
1612 loaded. All of the @code{gdb.Objfile} dictionaries are combined, as
1613 several frames, and thus several object files, might be in use.
1614 @value{GDBN} then prunes any frame filter whose @code{enabled}
1615 attribute is @code{False}. This pruned list is then sorted according
1616 to the @code{priority} attribute in each filter.
1618 Once the dictionaries are combined, pruned and sorted, @value{GDBN}
1619 creates an iterator which wraps each frame in the call stack in a
1620 @code{FrameDecorator} object, and calls each filter in order. The
1621 output from the previous filter will always be the input to the next
1624 Frame filters have a mandatory interface which each frame filter must
1625 implement, defined here:
1627 @defun FrameFilter.filter (iterator)
1628 @value{GDBN} will call this method on a frame filter when it has
1629 reached the order in the priority list for that filter.
1631 For example, if there are four frame filters:
1642 The order that the frame filters will be called is:
1645 Filter3 -> Filter2 -> Filter1 -> Filter4
1648 Note that the output from @code{Filter3} is passed to the input of
1649 @code{Filter2}, and so on.
1651 This @code{filter} method is passed a Python iterator. This iterator
1652 contains a sequence of frame decorators that wrap each
1653 @code{gdb.Frame}, or a frame decorator that wraps another frame
1654 decorator. The first filter that is executed in the sequence of frame
1655 filters will receive an iterator entirely comprised of default
1656 @code{FrameDecorator} objects. However, after each frame filter is
1657 executed, the previous frame filter may have wrapped some or all of
1658 the frame decorators with their own frame decorator. As frame
1659 decorators must also conform to a mandatory interface, these
1660 decorators can be assumed to act in a uniform manner (@pxref{Frame
1663 This method must return an object conforming to the Python iterator
1664 protocol. Each item in the iterator must be an object conforming to
1665 the frame decorator interface. If a frame filter does not wish to
1666 perform any operations on this iterator, it should return that
1669 This method is not optional. If it does not exist, @value{GDBN} will
1670 raise and print an error.
1673 @defvar FrameFilter.name
1674 The @code{name} attribute must be Python string which contains the
1675 name of the filter displayed by @value{GDBN} (@pxref{Frame Filter
1676 Management}). This attribute may contain any combination of letters
1677 or numbers. Care should be taken to ensure that it is unique. This
1678 attribute is mandatory.
1681 @defvar FrameFilter.enabled
1682 The @code{enabled} attribute must be Python boolean. This attribute
1683 indicates to @value{GDBN} whether the frame filter is enabled, and
1684 should be considered when frame filters are executed. If
1685 @code{enabled} is @code{True}, then the frame filter will be executed
1686 when any of the backtrace commands detailed earlier in this chapter
1687 are executed. If @code{enabled} is @code{False}, then the frame
1688 filter will not be executed. This attribute is mandatory.
1691 @defvar FrameFilter.priority
1692 The @code{priority} attribute must be Python integer. This attribute
1693 controls the order of execution in relation to other frame filters.
1694 There are no imposed limits on the range of @code{priority} other than
1695 it must be a valid integer. The higher the @code{priority} attribute,
1696 the sooner the frame filter will be executed in relation to other
1697 frame filters. Although @code{priority} can be negative, it is
1698 recommended practice to assume zero is the lowest priority that a
1699 frame filter can be assigned. Frame filters that have the same
1700 priority are executed in unsorted order in that priority slot. This
1701 attribute is mandatory.
1704 @node Frame Decorator API
1705 @subsubsection Decorating Frames.
1706 @cindex frame decorator api
1708 Frame decorators are sister objects to frame filters (@pxref{Frame
1709 Filter API}). Frame decorators are applied by a frame filter and can
1710 only be used in conjunction with frame filters.
1712 The purpose of a frame decorator is to customize the printed content
1713 of each @code{gdb.Frame} in commands where frame filters are executed.
1714 This concept is called decorating a frame. Frame decorators decorate
1715 a @code{gdb.Frame} with Python code contained within each API call.
1716 This separates the actual data contained in a @code{gdb.Frame} from
1717 the decorated data produced by a frame decorator. This abstraction is
1718 necessary to maintain integrity of the data contained in each
1721 Frame decorators have a mandatory interface, defined below.
1723 @value{GDBN} already contains a frame decorator called
1724 @code{FrameDecorator}. This contains substantial amounts of
1725 boilerplate code to decorate the content of a @code{gdb.Frame}. It is
1726 recommended that other frame decorators inherit and extend this
1727 object, and only to override the methods needed.
1729 @defun FrameDecorator.elided (self)
1731 The @code{elided} method groups frames together in a hierarchical
1732 system. An example would be an interpreter, where multiple low-level
1733 frames make up a single call in the interpreted language. In this
1734 example, the frame filter would elide the low-level frames and present
1735 a single high-level frame, representing the call in the interpreted
1736 language, to the user.
1738 The @code{elided} function must return an iterable and this iterable
1739 must contain the frames that are being elided wrapped in a suitable
1740 frame decorator. If no frames are being elided this function may
1741 return an empty iterable, or @code{None}. Elided frames are indented
1742 from normal frames in a @code{CLI} backtrace, or in the case of
1743 @code{GDB/MI}, are placed in the @code{children} field of the eliding
1746 It is the frame filter's task to also filter out the elided frames from
1747 the source iterator. This will avoid printing the frame twice.
1750 @defun FrameDecorator.function (self)
1752 This method returns the name of the function in the frame that is to
1755 This method must return a Python string describing the function, or
1758 If this function returns @code{None}, @value{GDBN} will not print any
1759 data for this field.
1762 @defun FrameDecorator.address (self)
1764 This method returns the address of the frame that is to be printed.
1766 This method must return a Python numeric integer type of sufficient
1767 size to describe the address of the frame, or @code{None}.
1769 If this function returns a @code{None}, @value{GDBN} will not print
1770 any data for this field.
1773 @defun FrameDecorator.filename (self)
1775 This method returns the filename and path associated with this frame.
1777 This method must return a Python string containing the filename and
1778 the path to the object file backing the frame, or @code{None}.
1780 If this function returns a @code{None}, @value{GDBN} will not print
1781 any data for this field.
1784 @defun FrameDecorator.line (self):
1786 This method returns the line number associated with the current
1787 position within the function addressed by this frame.
1789 This method must return a Python integer type, or @code{None}.
1791 If this function returns a @code{None}, @value{GDBN} will not print
1792 any data for this field.
1795 @defun FrameDecorator.frame_args (self)
1798 This method must return an iterable, or @code{None}. Returning an
1799 empty iterable, or @code{None} means frame arguments will not be
1800 printed for this frame. This iterable must contain objects that
1801 implement two methods, described here.
1803 This object must implement a @code{argument} method which takes a
1804 single @code{self} parameter and must return a @code{gdb.Symbol}
1805 (@pxref{Symbols In Python}), or a Python string. The object must also
1806 implement a @code{value} method which takes a single @code{self}
1807 parameter and must return a @code{gdb.Value} (@pxref{Values From
1808 Inferior}), a Python value, or @code{None}. If the @code{value}
1809 method returns @code{None}, and the @code{argument} method returns a
1810 @code{gdb.Symbol}, @value{GDBN} will look-up and print the value of
1811 the @code{gdb.Symbol} automatically.
1816 class SymValueWrapper():
1818 def __init__(self, symbol, value):
1828 class SomeFrameDecorator()
1831 def frame_args(self):
1834 block = self.inferior_frame.block()
1838 # Iterate over all symbols in a block. Only add
1839 # symbols that are arguments.
1841 if not sym.is_argument:
1843 args.append(SymValueWrapper(sym,None))
1845 # Add example synthetic argument.
1846 args.append(SymValueWrapper(``foo'', 42))
1852 @defun FrameDecorator.frame_locals (self)
1854 This method must return an iterable or @code{None}. Returning an
1855 empty iterable, or @code{None} means frame local arguments will not be
1856 printed for this frame.
1858 The object interface, the description of the various strategies for
1859 reading frame locals, and the example are largely similar to those
1860 described in the @code{frame_args} function, (@pxref{frame_args,,The
1861 frame filter frame_args function}). Below is a modified example:
1864 class SomeFrameDecorator()
1867 def frame_locals(self):
1870 block = self.inferior_frame.block()
1874 # Iterate over all symbols in a block. Add all
1875 # symbols, except arguments.
1879 vars.append(SymValueWrapper(sym,None))
1881 # Add an example of a synthetic local variable.
1882 vars.append(SymValueWrapper(``bar'', 99))
1888 @defun FrameDecorator.inferior_frame (self):
1890 This method must return the underlying @code{gdb.Frame} that this
1891 frame decorator is decorating. @value{GDBN} requires the underlying
1892 frame for internal frame information to determine how to print certain
1893 values when printing a frame.
1896 @node Writing a Frame Filter
1897 @subsubsection Writing a Frame Filter
1898 @cindex writing a frame filter
1900 There are three basic elements that a frame filter must implement: it
1901 must correctly implement the documented interface (@pxref{Frame Filter
1902 API}), it must register itself with @value{GDBN}, and finally, it must
1903 decide if it is to work on the data provided by @value{GDBN}. In all
1904 cases, whether it works on the iterator or not, each frame filter must
1905 return an iterator. A bare-bones frame filter follows the pattern in
1906 the following example.
1911 class FrameFilter():
1914 # Frame filter attribute creation.
1916 # 'name' is the name of the filter that GDB will display.
1918 # 'priority' is the priority of the filter relative to other
1921 # 'enabled' is a boolean that indicates whether this filter is
1922 # enabled and should be executed.
1928 # Register this frame filter with the global frame_filters
1930 gdb.frame_filters[self.name] = self
1932 def filter(self, frame_iter):
1933 # Just return the iterator.
1937 The frame filter in the example above implements the three
1938 requirements for all frame filters. It implements the API, self
1939 registers, and makes a decision on the iterator (in this case, it just
1940 returns the iterator untouched).
1942 The first step is attribute creation and assignment, and as shown in
1943 the comments the filter assigns the following attributes: @code{name},
1944 @code{priority} and whether the filter should be enabled with the
1945 @code{enabled} attribute.
1947 The second step is registering the frame filter with the dictionary or
1948 dictionaries that the frame filter has interest in. As shown in the
1949 comments, this filter just registers itself with the global dictionary
1950 @code{gdb.frame_filters}. As noted earlier, @code{gdb.frame_filters}
1951 is a dictionary that is initialized in the @code{gdb} module when
1952 @value{GDBN} starts. What dictionary a filter registers with is an
1953 important consideration. Generally, if a filter is specific to a set
1954 of code, it should be registered either in the @code{objfile} or
1955 @code{progspace} dictionaries as they are specific to the program
1956 currently loaded in @value{GDBN}. The global dictionary is always
1957 present in @value{GDBN} and is never unloaded. Any filters registered
1958 with the global dictionary will exist until @value{GDBN} exits. To
1959 avoid filters that may conflict, it is generally better to register
1960 frame filters against the dictionaries that more closely align with
1961 the usage of the filter currently in question. @xref{Python
1962 Auto-loading}, for further information on auto-loading Python scripts.
1964 @value{GDBN} takes a hands-off approach to frame filter registration,
1965 therefore it is the frame filter's responsibility to ensure
1966 registration has occurred, and that any exceptions are handled
1967 appropriately. In particular, you may wish to handle exceptions
1968 relating to Python dictionary key uniqueness. It is mandatory that
1969 the dictionary key is the same as frame filter's @code{name}
1970 attribute. When a user manages frame filters (@pxref{Frame Filter
1971 Management}), the names @value{GDBN} will display are those contained
1972 in the @code{name} attribute.
1974 The final step of this example is the implementation of the
1975 @code{filter} method. As shown in the example comments, we define the
1976 @code{filter} method and note that the method must take an iterator,
1977 and also must return an iterator. In this bare-bones example, the
1978 frame filter is not very useful as it just returns the iterator
1979 untouched. However this is a valid operation for frame filters that
1980 have the @code{enabled} attribute set, but decide not to operate on
1983 In the next example, the frame filter operates on all frames and
1984 utilizes a frame decorator to perform some work on the frames.
1985 @xref{Frame Decorator API}, for further information on the frame
1986 decorator interface.
1988 This example works on inlined frames. It highlights frames which are
1989 inlined by tagging them with an ``[inlined]'' tag. By applying a
1990 frame decorator to all frames with the Python @code{itertools imap}
1991 method, the example defers actions to the frame decorator. Frame
1992 decorators are only processed when @value{GDBN} prints the backtrace.
1994 This introduces a new decision making topic: whether to perform
1995 decision making operations at the filtering step, or at the printing
1996 step. In this example's approach, it does not perform any filtering
1997 decisions at the filtering step beyond mapping a frame decorator to
1998 each frame. This allows the actual decision making to be performed
1999 when each frame is printed. This is an important consideration, and
2000 well worth reflecting upon when designing a frame filter. An issue
2001 that frame filters should avoid is unwinding the stack if possible.
2002 Some stacks can run very deep, into the tens of thousands in some
2003 cases. To search every frame to determine if it is inlined ahead of
2004 time may be too expensive at the filtering step. The frame filter
2005 cannot know how many frames it has to iterate over, and it would have
2006 to iterate through them all. This ends up duplicating effort as
2007 @value{GDBN} performs this iteration when it prints the frames.
2009 In this example decision making can be deferred to the printing step.
2010 As each frame is printed, the frame decorator can examine each frame
2011 in turn when @value{GDBN} iterates. From a performance viewpoint,
2012 this is the most appropriate decision to make as it avoids duplicating
2013 the effort that the printing step would undertake anyway. Also, if
2014 there are many frame filters unwinding the stack during filtering, it
2015 can substantially delay the printing of the backtrace which will
2016 result in large memory usage, and a poor user experience.
2019 class InlineFilter():
2022 self.name = "InlinedFrameFilter"
2025 gdb.frame_filters[self.name] = self
2027 def filter(self, frame_iter):
2028 frame_iter = itertools.imap(InlinedFrameDecorator,
2033 This frame filter is somewhat similar to the earlier example, except
2034 that the @code{filter} method applies a frame decorator object called
2035 @code{InlinedFrameDecorator} to each element in the iterator. The
2036 @code{imap} Python method is light-weight. It does not proactively
2037 iterate over the iterator, but rather creates a new iterator which
2038 wraps the existing one.
2040 Below is the frame decorator for this example.
2043 class InlinedFrameDecorator(FrameDecorator):
2045 def __init__(self, fobj):
2046 super(InlinedFrameDecorator, self).__init__(fobj)
2049 frame = fobj.inferior_frame()
2050 name = str(frame.name())
2052 if frame.type() == gdb.INLINE_FRAME:
2053 name = name + " [inlined]"
2058 This frame decorator only defines and overrides the @code{function}
2059 method. It lets the supplied @code{FrameDecorator}, which is shipped
2060 with @value{GDBN}, perform the other work associated with printing
2063 The combination of these two objects create this output from a
2067 #0 0x004004e0 in bar () at inline.c:11
2068 #1 0x00400566 in max [inlined] (b=6, a=12) at inline.c:21
2069 #2 0x00400566 in main () at inline.c:31
2072 So in the case of this example, a frame decorator is applied to all
2073 frames, regardless of whether they may be inlined or not. As
2074 @value{GDBN} iterates over the iterator produced by the frame filters,
2075 @value{GDBN} executes each frame decorator which then makes a decision
2076 on what to print in the @code{function} callback. Using a strategy
2077 like this is a way to defer decisions on the frame content to printing
2080 @subheading Eliding Frames
2082 It might be that the above example is not desirable for representing
2083 inlined frames, and a hierarchical approach may be preferred. If we
2084 want to hierarchically represent frames, the @code{elided} frame
2085 decorator interface might be preferable.
2087 This example approaches the issue with the @code{elided} method. This
2088 example is quite long, but very simplistic. It is out-of-scope for
2089 this section to write a complete example that comprehensively covers
2090 all approaches of finding and printing inlined frames. However, this
2091 example illustrates the approach an author might use.
2093 This example comprises of three sections.
2096 class InlineFrameFilter():
2099 self.name = "InlinedFrameFilter"
2102 gdb.frame_filters[self.name] = self
2104 def filter(self, frame_iter):
2105 return ElidingInlineIterator(frame_iter)
2108 This frame filter is very similar to the other examples. The only
2109 difference is this frame filter is wrapping the iterator provided to
2110 it (@code{frame_iter}) with a custom iterator called
2111 @code{ElidingInlineIterator}. This again defers actions to when
2112 @value{GDBN} prints the backtrace, as the iterator is not traversed
2115 The iterator for this example is as follows. It is in this section of
2116 the example where decisions are made on the content of the backtrace.
2119 class ElidingInlineIterator:
2120 def __init__(self, ii):
2121 self.input_iterator = ii
2127 frame = next(self.input_iterator)
2129 if frame.inferior_frame().type() != gdb.INLINE_FRAME:
2133 eliding_frame = next(self.input_iterator)
2134 except StopIteration:
2136 return ElidingFrameDecorator(eliding_frame, [frame])
2139 This iterator implements the Python iterator protocol. When the
2140 @code{next} function is called (when @value{GDBN} prints each frame),
2141 the iterator checks if this frame decorator, @code{frame}, is wrapping
2142 an inlined frame. If it is not, it returns the existing frame decorator
2143 untouched. If it is wrapping an inlined frame, it assumes that the
2144 inlined frame was contained within the next oldest frame,
2145 @code{eliding_frame}, which it fetches. It then creates and returns a
2146 frame decorator, @code{ElidingFrameDecorator}, which contains both the
2147 elided frame, and the eliding frame.
2150 class ElidingInlineDecorator(FrameDecorator):
2152 def __init__(self, frame, elided_frames):
2153 super(ElidingInlineDecorator, self).__init__(frame)
2155 self.elided_frames = elided_frames
2158 return iter(self.elided_frames)
2161 This frame decorator overrides one function and returns the inlined
2162 frame in the @code{elided} method. As before it lets
2163 @code{FrameDecorator} do the rest of the work involved in printing
2164 this frame. This produces the following output.
2167 #0 0x004004e0 in bar () at inline.c:11
2168 #2 0x00400529 in main () at inline.c:25
2169 #1 0x00400529 in max (b=6, a=12) at inline.c:15
2172 In that output, @code{max} which has been inlined into @code{main} is
2173 printed hierarchically. Another approach would be to combine the
2174 @code{function} method, and the @code{elided} method to both print a
2175 marker in the inlined frame, and also show the hierarchical
2178 @node Inferiors In Python
2179 @subsubsection Inferiors In Python
2180 @cindex inferiors in Python
2182 @findex gdb.Inferior
2183 Programs which are being run under @value{GDBN} are called inferiors
2184 (@pxref{Inferiors and Programs}). Python scripts can access
2185 information about and manipulate inferiors controlled by @value{GDBN}
2186 via objects of the @code{gdb.Inferior} class.
2188 The following inferior-related functions are available in the @code{gdb}
2191 @defun gdb.inferiors ()
2192 Return a tuple containing all inferior objects.
2195 @defun gdb.selected_inferior ()
2196 Return an object representing the current inferior.
2199 A @code{gdb.Inferior} object has the following attributes:
2201 @defvar Inferior.num
2202 ID of inferior, as assigned by GDB.
2205 @defvar Inferior.pid
2206 Process ID of the inferior, as assigned by the underlying operating
2210 @defvar Inferior.was_attached
2211 Boolean signaling whether the inferior was created using `attach', or
2212 started by @value{GDBN} itself.
2215 A @code{gdb.Inferior} object has the following methods:
2217 @defun Inferior.is_valid ()
2218 Returns @code{True} if the @code{gdb.Inferior} object is valid,
2219 @code{False} if not. A @code{gdb.Inferior} object will become invalid
2220 if the inferior no longer exists within @value{GDBN}. All other
2221 @code{gdb.Inferior} methods will throw an exception if it is invalid
2222 at the time the method is called.
2225 @defun Inferior.threads ()
2226 This method returns a tuple holding all the threads which are valid
2227 when it is called. If there are no valid threads, the method will
2228 return an empty tuple.
2231 @findex Inferior.read_memory
2232 @defun Inferior.read_memory (address, length)
2233 Read @var{length} bytes of memory from the inferior, starting at
2234 @var{address}. Returns a buffer object, which behaves much like an array
2235 or a string. It can be modified and given to the
2236 @code{Inferior.write_memory} function. In @code{Python} 3, the return
2237 value is a @code{memoryview} object.
2240 @findex Inferior.write_memory
2241 @defun Inferior.write_memory (address, buffer @r{[}, length@r{]})
2242 Write the contents of @var{buffer} to the inferior, starting at
2243 @var{address}. The @var{buffer} parameter must be a Python object
2244 which supports the buffer protocol, i.e., a string, an array or the
2245 object returned from @code{Inferior.read_memory}. If given, @var{length}
2246 determines the number of bytes from @var{buffer} to be written.
2249 @findex gdb.search_memory
2250 @defun Inferior.search_memory (address, length, pattern)
2251 Search a region of the inferior memory starting at @var{address} with
2252 the given @var{length} using the search pattern supplied in
2253 @var{pattern}. The @var{pattern} parameter must be a Python object
2254 which supports the buffer protocol, i.e., a string, an array or the
2255 object returned from @code{gdb.read_memory}. Returns a Python @code{Long}
2256 containing the address where the pattern was found, or @code{None} if
2257 the pattern could not be found.
2260 @node Events In Python
2261 @subsubsection Events In Python
2262 @cindex inferior events in Python
2264 @value{GDBN} provides a general event facility so that Python code can be
2265 notified of various state changes, particularly changes that occur in
2268 An @dfn{event} is just an object that describes some state change. The
2269 type of the object and its attributes will vary depending on the details
2270 of the change. All the existing events are described below.
2272 In order to be notified of an event, you must register an event handler
2273 with an @dfn{event registry}. An event registry is an object in the
2274 @code{gdb.events} module which dispatches particular events. A registry
2275 provides methods to register and unregister event handlers:
2277 @defun EventRegistry.connect (object)
2278 Add the given callable @var{object} to the registry. This object will be
2279 called when an event corresponding to this registry occurs.
2282 @defun EventRegistry.disconnect (object)
2283 Remove the given @var{object} from the registry. Once removed, the object
2284 will no longer receive notifications of events.
2290 def exit_handler (event):
2291 print "event type: exit"
2292 print "exit code: %d" % (event.exit_code)
2294 gdb.events.exited.connect (exit_handler)
2297 In the above example we connect our handler @code{exit_handler} to the
2298 registry @code{events.exited}. Once connected, @code{exit_handler} gets
2299 called when the inferior exits. The argument @dfn{event} in this example is
2300 of type @code{gdb.ExitedEvent}. As you can see in the example the
2301 @code{ExitedEvent} object has an attribute which indicates the exit code of
2304 The following is a listing of the event registries that are available and
2305 details of the events they emit:
2310 Emits @code{gdb.ThreadEvent}.
2312 Some events can be thread specific when @value{GDBN} is running in non-stop
2313 mode. When represented in Python, these events all extend
2314 @code{gdb.ThreadEvent}. Note, this event is not emitted directly; instead,
2315 events which are emitted by this or other modules might extend this event.
2316 Examples of these events are @code{gdb.BreakpointEvent} and
2317 @code{gdb.ContinueEvent}.
2319 @defvar ThreadEvent.inferior_thread
2320 In non-stop mode this attribute will be set to the specific thread which was
2321 involved in the emitted event. Otherwise, it will be set to @code{None}.
2324 Emits @code{gdb.ContinueEvent} which extends @code{gdb.ThreadEvent}.
2326 This event indicates that the inferior has been continued after a stop. For
2327 inherited attribute refer to @code{gdb.ThreadEvent} above.
2330 Emits @code{events.ExitedEvent} which indicates that the inferior has exited.
2331 @code{events.ExitedEvent} has two attributes:
2332 @defvar ExitedEvent.exit_code
2333 An integer representing the exit code, if available, which the inferior
2334 has returned. (The exit code could be unavailable if, for example,
2335 @value{GDBN} detaches from the inferior.) If the exit code is unavailable,
2336 the attribute does not exist.
2338 @defvar ExitedEvent inferior
2339 A reference to the inferior which triggered the @code{exited} event.
2343 Emits @code{gdb.StopEvent} which extends @code{gdb.ThreadEvent}.
2345 Indicates that the inferior has stopped. All events emitted by this registry
2346 extend StopEvent. As a child of @code{gdb.ThreadEvent}, @code{gdb.StopEvent}
2347 will indicate the stopped thread when @value{GDBN} is running in non-stop
2348 mode. Refer to @code{gdb.ThreadEvent} above for more details.
2350 Emits @code{gdb.SignalEvent} which extends @code{gdb.StopEvent}.
2352 This event indicates that the inferior or one of its threads has received as
2353 signal. @code{gdb.SignalEvent} has the following attributes:
2355 @defvar SignalEvent.stop_signal
2356 A string representing the signal received by the inferior. A list of possible
2357 signal values can be obtained by running the command @code{info signals} in
2358 the @value{GDBN} command prompt.
2361 Also emits @code{gdb.BreakpointEvent} which extends @code{gdb.StopEvent}.
2363 @code{gdb.BreakpointEvent} event indicates that one or more breakpoints have
2364 been hit, and has the following attributes:
2366 @defvar BreakpointEvent.breakpoints
2367 A sequence containing references to all the breakpoints (type
2368 @code{gdb.Breakpoint}) that were hit.
2369 @xref{Breakpoints In Python}, for details of the @code{gdb.Breakpoint} object.
2371 @defvar BreakpointEvent.breakpoint
2372 A reference to the first breakpoint that was hit.
2373 This function is maintained for backward compatibility and is now deprecated
2374 in favor of the @code{gdb.BreakpointEvent.breakpoints} attribute.
2377 @item events.new_objfile
2378 Emits @code{gdb.NewObjFileEvent} which indicates that a new object file has
2379 been loaded by @value{GDBN}. @code{gdb.NewObjFileEvent} has one attribute:
2381 @defvar NewObjFileEvent.new_objfile
2382 A reference to the object file (@code{gdb.Objfile}) which has been loaded.
2383 @xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
2388 @node Threads In Python
2389 @subsubsection Threads In Python
2390 @cindex threads in python
2392 @findex gdb.InferiorThread
2393 Python scripts can access information about, and manipulate inferior threads
2394 controlled by @value{GDBN}, via objects of the @code{gdb.InferiorThread} class.
2396 The following thread-related functions are available in the @code{gdb}
2399 @findex gdb.selected_thread
2400 @defun gdb.selected_thread ()
2401 This function returns the thread object for the selected thread. If there
2402 is no selected thread, this will return @code{None}.
2405 A @code{gdb.InferiorThread} object has the following attributes:
2407 @defvar InferiorThread.name
2408 The name of the thread. If the user specified a name using
2409 @code{thread name}, then this returns that name. Otherwise, if an
2410 OS-supplied name is available, then it is returned. Otherwise, this
2411 returns @code{None}.
2413 This attribute can be assigned to. The new value must be a string
2414 object, which sets the new name, or @code{None}, which removes any
2415 user-specified thread name.
2418 @defvar InferiorThread.num
2419 ID of the thread, as assigned by GDB.
2422 @defvar InferiorThread.ptid
2423 ID of the thread, as assigned by the operating system. This attribute is a
2424 tuple containing three integers. The first is the Process ID (PID); the second
2425 is the Lightweight Process ID (LWPID), and the third is the Thread ID (TID).
2426 Either the LWPID or TID may be 0, which indicates that the operating system
2427 does not use that identifier.
2430 A @code{gdb.InferiorThread} object has the following methods:
2432 @defun InferiorThread.is_valid ()
2433 Returns @code{True} if the @code{gdb.InferiorThread} object is valid,
2434 @code{False} if not. A @code{gdb.InferiorThread} object will become
2435 invalid if the thread exits, or the inferior that the thread belongs
2436 is deleted. All other @code{gdb.InferiorThread} methods will throw an
2437 exception if it is invalid at the time the method is called.
2440 @defun InferiorThread.switch ()
2441 This changes @value{GDBN}'s currently selected thread to the one represented
2445 @defun InferiorThread.is_stopped ()
2446 Return a Boolean indicating whether the thread is stopped.
2449 @defun InferiorThread.is_running ()
2450 Return a Boolean indicating whether the thread is running.
2453 @defun InferiorThread.is_exited ()
2454 Return a Boolean indicating whether the thread is exited.
2457 @node Commands In Python
2458 @subsubsection Commands In Python
2460 @cindex commands in python
2461 @cindex python commands
2462 You can implement new @value{GDBN} CLI commands in Python. A CLI
2463 command is implemented using an instance of the @code{gdb.Command}
2464 class, most commonly using a subclass.
2466 @defun Command.__init__ (name, @var{command_class} @r{[}, @var{completer_class} @r{[}, @var{prefix}@r{]]})
2467 The object initializer for @code{Command} registers the new command
2468 with @value{GDBN}. This initializer is normally invoked from the
2469 subclass' own @code{__init__} method.
2471 @var{name} is the name of the command. If @var{name} consists of
2472 multiple words, then the initial words are looked for as prefix
2473 commands. In this case, if one of the prefix commands does not exist,
2474 an exception is raised.
2476 There is no support for multi-line commands.
2478 @var{command_class} should be one of the @samp{COMMAND_} constants
2479 defined below. This argument tells @value{GDBN} how to categorize the
2480 new command in the help system.
2482 @var{completer_class} is an optional argument. If given, it should be
2483 one of the @samp{COMPLETE_} constants defined below. This argument
2484 tells @value{GDBN} how to perform completion for this command. If not
2485 given, @value{GDBN} will attempt to complete using the object's
2486 @code{complete} method (see below); if no such method is found, an
2487 error will occur when completion is attempted.
2489 @var{prefix} is an optional argument. If @code{True}, then the new
2490 command is a prefix command; sub-commands of this command may be
2493 The help text for the new command is taken from the Python
2494 documentation string for the command's class, if there is one. If no
2495 documentation string is provided, the default value ``This command is
2496 not documented.'' is used.
2499 @cindex don't repeat Python command
2500 @defun Command.dont_repeat ()
2501 By default, a @value{GDBN} command is repeated when the user enters a
2502 blank line at the command prompt. A command can suppress this
2503 behavior by invoking the @code{dont_repeat} method. This is similar
2504 to the user command @code{dont-repeat}, see @ref{Define, dont-repeat}.
2507 @defun Command.invoke (argument, from_tty)
2508 This method is called by @value{GDBN} when this command is invoked.
2510 @var{argument} is a string. It is the argument to the command, after
2511 leading and trailing whitespace has been stripped.
2513 @var{from_tty} is a boolean argument. When true, this means that the
2514 command was entered by the user at the terminal; when false it means
2515 that the command came from elsewhere.
2517 If this method throws an exception, it is turned into a @value{GDBN}
2518 @code{error} call. Otherwise, the return value is ignored.
2520 @findex gdb.string_to_argv
2521 To break @var{argument} up into an argv-like string use
2522 @code{gdb.string_to_argv}. This function behaves identically to
2523 @value{GDBN}'s internal argument lexer @code{buildargv}.
2524 It is recommended to use this for consistency.
2525 Arguments are separated by spaces and may be quoted.
2529 print gdb.string_to_argv ("1 2\ \\\"3 '4 \"5' \"6 '7\"")
2530 ['1', '2 "3', '4 "5', "6 '7"]
2535 @cindex completion of Python commands
2536 @defun Command.complete (text, word)
2537 This method is called by @value{GDBN} when the user attempts
2538 completion on this command. All forms of completion are handled by
2539 this method, that is, the @key{TAB} and @key{M-?} key bindings
2540 (@pxref{Completion}), and the @code{complete} command (@pxref{Help,
2543 The arguments @var{text} and @var{word} are both strings. @var{text}
2544 holds the complete command line up to the cursor's location.
2545 @var{word} holds the last word of the command line; this is computed
2546 using a word-breaking heuristic.
2548 The @code{complete} method can return several values:
2551 If the return value is a sequence, the contents of the sequence are
2552 used as the completions. It is up to @code{complete} to ensure that the
2553 contents actually do complete the word. A zero-length sequence is
2554 allowed, it means that there were no completions available. Only
2555 string elements of the sequence are used; other elements in the
2556 sequence are ignored.
2559 If the return value is one of the @samp{COMPLETE_} constants defined
2560 below, then the corresponding @value{GDBN}-internal completion
2561 function is invoked, and its result is used.
2564 All other results are treated as though there were no available
2569 When a new command is registered, it must be declared as a member of
2570 some general class of commands. This is used to classify top-level
2571 commands in the on-line help system; note that prefix commands are not
2572 listed under their own category but rather that of their top-level
2573 command. The available classifications are represented by constants
2574 defined in the @code{gdb} module:
2577 @findex COMMAND_NONE
2578 @findex gdb.COMMAND_NONE
2579 @item gdb.COMMAND_NONE
2580 The command does not belong to any particular class. A command in
2581 this category will not be displayed in any of the help categories.
2583 @findex COMMAND_RUNNING
2584 @findex gdb.COMMAND_RUNNING
2585 @item gdb.COMMAND_RUNNING
2586 The command is related to running the inferior. For example,
2587 @code{start}, @code{step}, and @code{continue} are in this category.
2588 Type @kbd{help running} at the @value{GDBN} prompt to see a list of
2589 commands in this category.
2591 @findex COMMAND_DATA
2592 @findex gdb.COMMAND_DATA
2593 @item gdb.COMMAND_DATA
2594 The command is related to data or variables. For example,
2595 @code{call}, @code{find}, and @code{print} are in this category. Type
2596 @kbd{help data} at the @value{GDBN} prompt to see a list of commands
2599 @findex COMMAND_STACK
2600 @findex gdb.COMMAND_STACK
2601 @item gdb.COMMAND_STACK
2602 The command has to do with manipulation of the stack. For example,
2603 @code{backtrace}, @code{frame}, and @code{return} are in this
2604 category. Type @kbd{help stack} at the @value{GDBN} prompt to see a
2605 list of commands in this category.
2607 @findex COMMAND_FILES
2608 @findex gdb.COMMAND_FILES
2609 @item gdb.COMMAND_FILES
2610 This class is used for file-related commands. For example,
2611 @code{file}, @code{list} and @code{section} are in this category.
2612 Type @kbd{help files} at the @value{GDBN} prompt to see a list of
2613 commands in this category.
2615 @findex COMMAND_SUPPORT
2616 @findex gdb.COMMAND_SUPPORT
2617 @item gdb.COMMAND_SUPPORT
2618 This should be used for ``support facilities'', generally meaning
2619 things that are useful to the user when interacting with @value{GDBN},
2620 but not related to the state of the inferior. For example,
2621 @code{help}, @code{make}, and @code{shell} are in this category. Type
2622 @kbd{help support} at the @value{GDBN} prompt to see a list of
2623 commands in this category.
2625 @findex COMMAND_STATUS
2626 @findex gdb.COMMAND_STATUS
2627 @item gdb.COMMAND_STATUS
2628 The command is an @samp{info}-related command, that is, related to the
2629 state of @value{GDBN} itself. For example, @code{info}, @code{macro},
2630 and @code{show} are in this category. Type @kbd{help status} at the
2631 @value{GDBN} prompt to see a list of commands in this category.
2633 @findex COMMAND_BREAKPOINTS
2634 @findex gdb.COMMAND_BREAKPOINTS
2635 @item gdb.COMMAND_BREAKPOINTS
2636 The command has to do with breakpoints. For example, @code{break},
2637 @code{clear}, and @code{delete} are in this category. Type @kbd{help
2638 breakpoints} at the @value{GDBN} prompt to see a list of commands in
2641 @findex COMMAND_TRACEPOINTS
2642 @findex gdb.COMMAND_TRACEPOINTS
2643 @item gdb.COMMAND_TRACEPOINTS
2644 The command has to do with tracepoints. For example, @code{trace},
2645 @code{actions}, and @code{tfind} are in this category. Type
2646 @kbd{help tracepoints} at the @value{GDBN} prompt to see a list of
2647 commands in this category.
2649 @findex COMMAND_USER
2650 @findex gdb.COMMAND_USER
2651 @item gdb.COMMAND_USER
2652 The command is a general purpose command for the user, and typically
2653 does not fit in one of the other categories.
2654 Type @kbd{help user-defined} at the @value{GDBN} prompt to see
2655 a list of commands in this category, as well as the list of gdb macros
2656 (@pxref{Sequences}).
2658 @findex COMMAND_OBSCURE
2659 @findex gdb.COMMAND_OBSCURE
2660 @item gdb.COMMAND_OBSCURE
2661 The command is only used in unusual circumstances, or is not of
2662 general interest to users. For example, @code{checkpoint},
2663 @code{fork}, and @code{stop} are in this category. Type @kbd{help
2664 obscure} at the @value{GDBN} prompt to see a list of commands in this
2667 @findex COMMAND_MAINTENANCE
2668 @findex gdb.COMMAND_MAINTENANCE
2669 @item gdb.COMMAND_MAINTENANCE
2670 The command is only useful to @value{GDBN} maintainers. The
2671 @code{maintenance} and @code{flushregs} commands are in this category.
2672 Type @kbd{help internals} at the @value{GDBN} prompt to see a list of
2673 commands in this category.
2676 A new command can use a predefined completion function, either by
2677 specifying it via an argument at initialization, or by returning it
2678 from the @code{complete} method. These predefined completion
2679 constants are all defined in the @code{gdb} module:
2682 @vindex COMPLETE_NONE
2683 @item gdb.COMPLETE_NONE
2684 This constant means that no completion should be done.
2686 @vindex COMPLETE_FILENAME
2687 @item gdb.COMPLETE_FILENAME
2688 This constant means that filename completion should be performed.
2690 @vindex COMPLETE_LOCATION
2691 @item gdb.COMPLETE_LOCATION
2692 This constant means that location completion should be done.
2693 @xref{Specify Location}.
2695 @vindex COMPLETE_COMMAND
2696 @item gdb.COMPLETE_COMMAND
2697 This constant means that completion should examine @value{GDBN}
2700 @vindex COMPLETE_SYMBOL
2701 @item gdb.COMPLETE_SYMBOL
2702 This constant means that completion should be done using symbol names
2705 @vindex COMPLETE_EXPRESSION
2706 @item gdb.COMPLETE_EXPRESSION
2707 This constant means that completion should be done on expressions.
2708 Often this means completing on symbol names, but some language
2709 parsers also have support for completing on field names.
2712 The following code snippet shows how a trivial CLI command can be
2713 implemented in Python:
2716 class HelloWorld (gdb.Command):
2717 """Greet the whole world."""
2719 def __init__ (self):
2720 super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
2722 def invoke (self, arg, from_tty):
2723 print "Hello, World!"
2728 The last line instantiates the class, and is necessary to trigger the
2729 registration of the command with @value{GDBN}. Depending on how the
2730 Python code is read into @value{GDBN}, you may need to import the
2731 @code{gdb} module explicitly.
2733 @node Parameters In Python
2734 @subsubsection Parameters In Python
2736 @cindex parameters in python
2737 @cindex python parameters
2738 @tindex gdb.Parameter
2740 You can implement new @value{GDBN} parameters using Python. A new
2741 parameter is implemented as an instance of the @code{gdb.Parameter}
2744 Parameters are exposed to the user via the @code{set} and
2745 @code{show} commands. @xref{Help}.
2747 There are many parameters that already exist and can be set in
2748 @value{GDBN}. Two examples are: @code{set follow fork} and
2749 @code{set charset}. Setting these parameters influences certain
2750 behavior in @value{GDBN}. Similarly, you can define parameters that
2751 can be used to influence behavior in custom Python scripts and commands.
2753 @defun Parameter.__init__ (name, @var{command-class}, @var{parameter-class} @r{[}, @var{enum-sequence}@r{]})
2754 The object initializer for @code{Parameter} registers the new
2755 parameter with @value{GDBN}. This initializer is normally invoked
2756 from the subclass' own @code{__init__} method.
2758 @var{name} is the name of the new parameter. If @var{name} consists
2759 of multiple words, then the initial words are looked for as prefix
2760 parameters. An example of this can be illustrated with the
2761 @code{set print} set of parameters. If @var{name} is
2762 @code{print foo}, then @code{print} will be searched as the prefix
2763 parameter. In this case the parameter can subsequently be accessed in
2764 @value{GDBN} as @code{set print foo}.
2766 If @var{name} consists of multiple words, and no prefix parameter group
2767 can be found, an exception is raised.
2769 @var{command-class} should be one of the @samp{COMMAND_} constants
2770 (@pxref{Commands In Python}). This argument tells @value{GDBN} how to
2771 categorize the new parameter in the help system.
2773 @var{parameter-class} should be one of the @samp{PARAM_} constants
2774 defined below. This argument tells @value{GDBN} the type of the new
2775 parameter; this information is used for input validation and
2778 If @var{parameter-class} is @code{PARAM_ENUM}, then
2779 @var{enum-sequence} must be a sequence of strings. These strings
2780 represent the possible values for the parameter.
2782 If @var{parameter-class} is not @code{PARAM_ENUM}, then the presence
2783 of a fourth argument will cause an exception to be thrown.
2785 The help text for the new parameter is taken from the Python
2786 documentation string for the parameter's class, if there is one. If
2787 there is no documentation string, a default value is used.
2790 @defvar Parameter.set_doc
2791 If this attribute exists, and is a string, then its value is used as
2792 the help text for this parameter's @code{set} command. The value is
2793 examined when @code{Parameter.__init__} is invoked; subsequent changes
2797 @defvar Parameter.show_doc
2798 If this attribute exists, and is a string, then its value is used as
2799 the help text for this parameter's @code{show} command. The value is
2800 examined when @code{Parameter.__init__} is invoked; subsequent changes
2804 @defvar Parameter.value
2805 The @code{value} attribute holds the underlying value of the
2806 parameter. It can be read and assigned to just as any other
2807 attribute. @value{GDBN} does validation when assignments are made.
2810 There are two methods that should be implemented in any
2811 @code{Parameter} class. These are:
2813 @defun Parameter.get_set_string (self)
2814 @value{GDBN} will call this method when a @var{parameter}'s value has
2815 been changed via the @code{set} API (for example, @kbd{set foo off}).
2816 The @code{value} attribute has already been populated with the new
2817 value and may be used in output. This method must return a string.
2820 @defun Parameter.get_show_string (self, svalue)
2821 @value{GDBN} will call this method when a @var{parameter}'s
2822 @code{show} API has been invoked (for example, @kbd{show foo}). The
2823 argument @code{svalue} receives the string representation of the
2824 current value. This method must return a string.
2827 When a new parameter is defined, its type must be specified. The
2828 available types are represented by constants defined in the @code{gdb}
2832 @findex PARAM_BOOLEAN
2833 @findex gdb.PARAM_BOOLEAN
2834 @item gdb.PARAM_BOOLEAN
2835 The value is a plain boolean. The Python boolean values, @code{True}
2836 and @code{False} are the only valid values.
2838 @findex PARAM_AUTO_BOOLEAN
2839 @findex gdb.PARAM_AUTO_BOOLEAN
2840 @item gdb.PARAM_AUTO_BOOLEAN
2841 The value has three possible states: true, false, and @samp{auto}. In
2842 Python, true and false are represented using boolean constants, and
2843 @samp{auto} is represented using @code{None}.
2845 @findex PARAM_UINTEGER
2846 @findex gdb.PARAM_UINTEGER
2847 @item gdb.PARAM_UINTEGER
2848 The value is an unsigned integer. The value of 0 should be
2849 interpreted to mean ``unlimited''.
2851 @findex PARAM_INTEGER
2852 @findex gdb.PARAM_INTEGER
2853 @item gdb.PARAM_INTEGER
2854 The value is a signed integer. The value of 0 should be interpreted
2855 to mean ``unlimited''.
2857 @findex PARAM_STRING
2858 @findex gdb.PARAM_STRING
2859 @item gdb.PARAM_STRING
2860 The value is a string. When the user modifies the string, any escape
2861 sequences, such as @samp{\t}, @samp{\f}, and octal escapes, are
2862 translated into corresponding characters and encoded into the current
2865 @findex PARAM_STRING_NOESCAPE
2866 @findex gdb.PARAM_STRING_NOESCAPE
2867 @item gdb.PARAM_STRING_NOESCAPE
2868 The value is a string. When the user modifies the string, escapes are
2869 passed through untranslated.
2871 @findex PARAM_OPTIONAL_FILENAME
2872 @findex gdb.PARAM_OPTIONAL_FILENAME
2873 @item gdb.PARAM_OPTIONAL_FILENAME
2874 The value is a either a filename (a string), or @code{None}.
2876 @findex PARAM_FILENAME
2877 @findex gdb.PARAM_FILENAME
2878 @item gdb.PARAM_FILENAME
2879 The value is a filename. This is just like
2880 @code{PARAM_STRING_NOESCAPE}, but uses file names for completion.
2882 @findex PARAM_ZINTEGER
2883 @findex gdb.PARAM_ZINTEGER
2884 @item gdb.PARAM_ZINTEGER
2885 The value is an integer. This is like @code{PARAM_INTEGER}, except 0
2886 is interpreted as itself.
2889 @findex gdb.PARAM_ENUM
2890 @item gdb.PARAM_ENUM
2891 The value is a string, which must be one of a collection string
2892 constants provided when the parameter is created.
2895 @node Functions In Python
2896 @subsubsection Writing new convenience functions
2898 @cindex writing convenience functions
2899 @cindex convenience functions in python
2900 @cindex python convenience functions
2901 @tindex gdb.Function
2903 You can implement new convenience functions (@pxref{Convenience Vars})
2904 in Python. A convenience function is an instance of a subclass of the
2905 class @code{gdb.Function}.
2907 @defun Function.__init__ (name)
2908 The initializer for @code{Function} registers the new function with
2909 @value{GDBN}. The argument @var{name} is the name of the function,
2910 a string. The function will be visible to the user as a convenience
2911 variable of type @code{internal function}, whose name is the same as
2912 the given @var{name}.
2914 The documentation for the new function is taken from the documentation
2915 string for the new class.
2918 @defun Function.invoke (@var{*args})
2919 When a convenience function is evaluated, its arguments are converted
2920 to instances of @code{gdb.Value}, and then the function's
2921 @code{invoke} method is called. Note that @value{GDBN} does not
2922 predetermine the arity of convenience functions. Instead, all
2923 available arguments are passed to @code{invoke}, following the
2924 standard Python calling convention. In particular, a convenience
2925 function can have default values for parameters without ill effect.
2927 The return value of this method is used as its value in the enclosing
2928 expression. If an ordinary Python value is returned, it is converted
2929 to a @code{gdb.Value} following the usual rules.
2932 The following code snippet shows how a trivial convenience function can
2933 be implemented in Python:
2936 class Greet (gdb.Function):
2937 """Return string to greet someone.
2938 Takes a name as argument."""
2940 def __init__ (self):
2941 super (Greet, self).__init__ ("greet")
2943 def invoke (self, name):
2944 return "Hello, %s!" % name.string ()
2949 The last line instantiates the class, and is necessary to trigger the
2950 registration of the function with @value{GDBN}. Depending on how the
2951 Python code is read into @value{GDBN}, you may need to import the
2952 @code{gdb} module explicitly.
2954 Now you can use the function in an expression:
2957 (gdb) print $greet("Bob")
2961 @node Progspaces In Python
2962 @subsubsection Program Spaces In Python
2964 @cindex progspaces in python
2965 @tindex gdb.Progspace
2967 A program space, or @dfn{progspace}, represents a symbolic view
2968 of an address space.
2969 It consists of all of the objfiles of the program.
2970 @xref{Objfiles In Python}.
2971 @xref{Inferiors and Programs, program spaces}, for more details
2972 about program spaces.
2974 The following progspace-related functions are available in the
2977 @findex gdb.current_progspace
2978 @defun gdb.current_progspace ()
2979 This function returns the program space of the currently selected inferior.
2980 @xref{Inferiors and Programs}.
2983 @findex gdb.progspaces
2984 @defun gdb.progspaces ()
2985 Return a sequence of all the progspaces currently known to @value{GDBN}.
2988 Each progspace is represented by an instance of the @code{gdb.Progspace}
2991 @defvar Progspace.filename
2992 The file name of the progspace as a string.
2995 @defvar Progspace.pretty_printers
2996 The @code{pretty_printers} attribute is a list of functions. It is
2997 used to look up pretty-printers. A @code{Value} is passed to each
2998 function in order; if the function returns @code{None}, then the
2999 search continues. Otherwise, the return value should be an object
3000 which is used to format the value. @xref{Pretty Printing API}, for more
3004 @defvar Progspace.type_printers
3005 The @code{type_printers} attribute is a list of type printer objects.
3006 @xref{Type Printing API}, for more information.
3009 @defvar Progspace.frame_filters
3010 The @code{frame_filters} attribute is a dictionary of frame filter
3011 objects. @xref{Frame Filter API}, for more information.
3014 @node Objfiles In Python
3015 @subsubsection Objfiles In Python
3017 @cindex objfiles in python
3020 @value{GDBN} loads symbols for an inferior from various
3021 symbol-containing files (@pxref{Files}). These include the primary
3022 executable file, any shared libraries used by the inferior, and any
3023 separate debug info files (@pxref{Separate Debug Files}).
3024 @value{GDBN} calls these symbol-containing files @dfn{objfiles}.
3026 The following objfile-related functions are available in the
3029 @findex gdb.current_objfile
3030 @defun gdb.current_objfile ()
3031 When auto-loading a Python script (@pxref{Python Auto-loading}), @value{GDBN}
3032 sets the ``current objfile'' to the corresponding objfile. This
3033 function returns the current objfile. If there is no current objfile,
3034 this function returns @code{None}.
3037 @findex gdb.objfiles
3038 @defun gdb.objfiles ()
3039 Return a sequence of all the objfiles current known to @value{GDBN}.
3040 @xref{Objfiles In Python}.
3043 Each objfile is represented by an instance of the @code{gdb.Objfile}
3046 @defvar Objfile.filename
3047 The file name of the objfile as a string.
3050 @defvar Objfile.pretty_printers
3051 The @code{pretty_printers} attribute is a list of functions. It is
3052 used to look up pretty-printers. A @code{Value} is passed to each
3053 function in order; if the function returns @code{None}, then the
3054 search continues. Otherwise, the return value should be an object
3055 which is used to format the value. @xref{Pretty Printing API}, for more
3059 @defvar Objfile.type_printers
3060 The @code{type_printers} attribute is a list of type printer objects.
3061 @xref{Type Printing API}, for more information.
3064 @defvar Objfile.frame_filters
3065 The @code{frame_filters} attribute is a dictionary of frame filter
3066 objects. @xref{Frame Filter API}, for more information.
3069 A @code{gdb.Objfile} object has the following methods:
3071 @defun Objfile.is_valid ()
3072 Returns @code{True} if the @code{gdb.Objfile} object is valid,
3073 @code{False} if not. A @code{gdb.Objfile} object can become invalid
3074 if the object file it refers to is not loaded in @value{GDBN} any
3075 longer. All other @code{gdb.Objfile} methods will throw an exception
3076 if it is invalid at the time the method is called.
3079 @node Frames In Python
3080 @subsubsection Accessing inferior stack frames from Python.
3082 @cindex frames in python
3083 When the debugged program stops, @value{GDBN} is able to analyze its call
3084 stack (@pxref{Frames,,Stack frames}). The @code{gdb.Frame} class
3085 represents a frame in the stack. A @code{gdb.Frame} object is only valid
3086 while its corresponding frame exists in the inferior's stack. If you try
3087 to use an invalid frame object, @value{GDBN} will throw a @code{gdb.error}
3088 exception (@pxref{Exception Handling}).
3090 Two @code{gdb.Frame} objects can be compared for equality with the @code{==}
3094 (@value{GDBP}) python print gdb.newest_frame() == gdb.selected_frame ()
3098 The following frame-related functions are available in the @code{gdb} module:
3100 @findex gdb.selected_frame
3101 @defun gdb.selected_frame ()
3102 Return the selected frame object. (@pxref{Selection,,Selecting a Frame}).
3105 @findex gdb.newest_frame
3106 @defun gdb.newest_frame ()
3107 Return the newest frame object for the selected thread.
3110 @defun gdb.frame_stop_reason_string (reason)
3111 Return a string explaining the reason why @value{GDBN} stopped unwinding
3112 frames, as expressed by the given @var{reason} code (an integer, see the
3113 @code{unwind_stop_reason} method further down in this section).
3116 A @code{gdb.Frame} object has the following methods:
3118 @defun Frame.is_valid ()
3119 Returns true if the @code{gdb.Frame} object is valid, false if not.
3120 A frame object can become invalid if the frame it refers to doesn't
3121 exist anymore in the inferior. All @code{gdb.Frame} methods will throw
3122 an exception if it is invalid at the time the method is called.
3125 @defun Frame.name ()
3126 Returns the function name of the frame, or @code{None} if it can't be
3130 @defun Frame.architecture ()
3131 Returns the @code{gdb.Architecture} object corresponding to the frame's
3132 architecture. @xref{Architectures In Python}.
3135 @defun Frame.type ()
3136 Returns the type of the frame. The value can be one of:
3138 @item gdb.NORMAL_FRAME
3139 An ordinary stack frame.
3141 @item gdb.DUMMY_FRAME
3142 A fake stack frame that was created by @value{GDBN} when performing an
3143 inferior function call.
3145 @item gdb.INLINE_FRAME
3146 A frame representing an inlined function. The function was inlined
3147 into a @code{gdb.NORMAL_FRAME} that is older than this one.
3149 @item gdb.TAILCALL_FRAME
3150 A frame representing a tail call. @xref{Tail Call Frames}.
3152 @item gdb.SIGTRAMP_FRAME
3153 A signal trampoline frame. This is the frame created by the OS when
3154 it calls into a signal handler.
3156 @item gdb.ARCH_FRAME
3157 A fake stack frame representing a cross-architecture call.
3159 @item gdb.SENTINEL_FRAME
3160 This is like @code{gdb.NORMAL_FRAME}, but it is only used for the
3165 @defun Frame.unwind_stop_reason ()
3166 Return an integer representing the reason why it's not possible to find
3167 more frames toward the outermost frame. Use
3168 @code{gdb.frame_stop_reason_string} to convert the value returned by this
3169 function to a string. The value can be one of:
3172 @item gdb.FRAME_UNWIND_NO_REASON
3173 No particular reason (older frames should be available).
3175 @item gdb.FRAME_UNWIND_NULL_ID
3176 The previous frame's analyzer returns an invalid result. This is no
3177 longer used by @value{GDBN}, and is kept only for backward
3180 @item gdb.FRAME_UNWIND_OUTERMOST
3181 This frame is the outermost.
3183 @item gdb.FRAME_UNWIND_UNAVAILABLE
3184 Cannot unwind further, because that would require knowing the
3185 values of registers or memory that have not been collected.
3187 @item gdb.FRAME_UNWIND_INNER_ID
3188 This frame ID looks like it ought to belong to a NEXT frame,
3189 but we got it for a PREV frame. Normally, this is a sign of
3190 unwinder failure. It could also indicate stack corruption.
3192 @item gdb.FRAME_UNWIND_SAME_ID
3193 This frame has the same ID as the previous one. That means
3194 that unwinding further would almost certainly give us another
3195 frame with exactly the same ID, so break the chain. Normally,
3196 this is a sign of unwinder failure. It could also indicate
3199 @item gdb.FRAME_UNWIND_NO_SAVED_PC
3200 The frame unwinder did not find any saved PC, but we needed
3201 one to unwind further.
3203 @item gdb.FRAME_UNWIND_FIRST_ERROR
3204 Any stop reason greater or equal to this value indicates some kind
3205 of error. This special value facilitates writing code that tests
3206 for errors in unwinding in a way that will work correctly even if
3207 the list of the other values is modified in future @value{GDBN}
3208 versions. Using it, you could write:
3210 reason = gdb.selected_frame().unwind_stop_reason ()
3211 reason_str = gdb.frame_stop_reason_string (reason)
3212 if reason >= gdb.FRAME_UNWIND_FIRST_ERROR:
3213 print "An error occured: %s" % reason_str
3220 Returns the frame's resume address.
3223 @defun Frame.block ()
3224 Return the frame's code block. @xref{Blocks In Python}.
3227 @defun Frame.function ()
3228 Return the symbol for the function corresponding to this frame.
3229 @xref{Symbols In Python}.
3232 @defun Frame.older ()
3233 Return the frame that called this frame.
3236 @defun Frame.newer ()
3237 Return the frame called by this frame.
3240 @defun Frame.find_sal ()
3241 Return the frame's symtab and line object.
3242 @xref{Symbol Tables In Python}.
3245 @defun Frame.read_var (variable @r{[}, block@r{]})
3246 Return the value of @var{variable} in this frame. If the optional
3247 argument @var{block} is provided, search for the variable from that
3248 block; otherwise start at the frame's current block (which is
3249 determined by the frame's current program counter). @var{variable}
3250 must be a string or a @code{gdb.Symbol} object. @var{block} must be a
3251 @code{gdb.Block} object.
3254 @defun Frame.select ()
3255 Set this frame to be the selected frame. @xref{Stack, ,Examining the
3259 @node Blocks In Python
3260 @subsubsection Accessing blocks from Python.
3262 @cindex blocks in python
3265 In @value{GDBN}, symbols are stored in blocks. A block corresponds
3266 roughly to a scope in the source code. Blocks are organized
3267 hierarchically, and are represented individually in Python as a
3268 @code{gdb.Block}. Blocks rely on debugging information being
3271 A frame has a block. Please see @ref{Frames In Python}, for a more
3272 in-depth discussion of frames.
3274 The outermost block is known as the @dfn{global block}. The global
3275 block typically holds public global variables and functions.
3277 The block nested just inside the global block is the @dfn{static
3278 block}. The static block typically holds file-scoped variables and
3281 @value{GDBN} provides a method to get a block's superblock, but there
3282 is currently no way to examine the sub-blocks of a block, or to
3283 iterate over all the blocks in a symbol table (@pxref{Symbol Tables In
3286 Here is a short example that should help explain blocks:
3289 /* This is in the global block. */
3292 /* This is in the static block. */
3293 static int file_scope;
3295 /* 'function' is in the global block, and 'argument' is
3296 in a block nested inside of 'function'. */
3297 int function (int argument)
3299 /* 'local' is in a block inside 'function'. It may or may
3300 not be in the same block as 'argument'. */
3304 /* 'inner' is in a block whose superblock is the one holding
3308 /* If this call is expanded by the compiler, you may see
3309 a nested block here whose function is 'inline_function'
3310 and whose superblock is the one holding 'inner'. */
3316 A @code{gdb.Block} is iterable. The iterator returns the symbols
3317 (@pxref{Symbols In Python}) local to the block. Python programs
3318 should not assume that a specific block object will always contain a
3319 given symbol, since changes in @value{GDBN} features and
3320 infrastructure may cause symbols move across blocks in a symbol
3323 The following block-related functions are available in the @code{gdb}
3326 @findex gdb.block_for_pc
3327 @defun gdb.block_for_pc (pc)
3328 Return the innermost @code{gdb.Block} containing the given @var{pc}
3329 value. If the block cannot be found for the @var{pc} value specified,
3330 the function will return @code{None}.
3333 A @code{gdb.Block} object has the following methods:
3335 @defun Block.is_valid ()
3336 Returns @code{True} if the @code{gdb.Block} object is valid,
3337 @code{False} if not. A block object can become invalid if the block it
3338 refers to doesn't exist anymore in the inferior. All other
3339 @code{gdb.Block} methods will throw an exception if it is invalid at
3340 the time the method is called. The block's validity is also checked
3341 during iteration over symbols of the block.
3344 A @code{gdb.Block} object has the following attributes:
3347 The start address of the block. This attribute is not writable.
3351 The end address of the block. This attribute is not writable.
3354 @defvar Block.function
3355 The name of the block represented as a @code{gdb.Symbol}. If the
3356 block is not named, then this attribute holds @code{None}. This
3357 attribute is not writable.
3359 For ordinary function blocks, the superblock is the static block.
3360 However, you should note that it is possible for a function block to
3361 have a superblock that is not the static block -- for instance this
3362 happens for an inlined function.
3365 @defvar Block.superblock
3366 The block containing this block. If this parent block does not exist,
3367 this attribute holds @code{None}. This attribute is not writable.
3370 @defvar Block.global_block
3371 The global block associated with this block. This attribute is not
3375 @defvar Block.static_block
3376 The static block associated with this block. This attribute is not
3380 @defvar Block.is_global
3381 @code{True} if the @code{gdb.Block} object is a global block,
3382 @code{False} if not. This attribute is not
3386 @defvar Block.is_static
3387 @code{True} if the @code{gdb.Block} object is a static block,
3388 @code{False} if not. This attribute is not writable.
3391 @node Symbols In Python
3392 @subsubsection Python representation of Symbols.
3394 @cindex symbols in python
3397 @value{GDBN} represents every variable, function and type as an
3398 entry in a symbol table. @xref{Symbols, ,Examining the Symbol Table}.
3399 Similarly, Python represents these symbols in @value{GDBN} with the
3400 @code{gdb.Symbol} object.
3402 The following symbol-related functions are available in the @code{gdb}
3405 @findex gdb.lookup_symbol
3406 @defun gdb.lookup_symbol (name @r{[}, block @r{[}, domain@r{]]})
3407 This function searches for a symbol by name. The search scope can be
3408 restricted to the parameters defined in the optional domain and block
3411 @var{name} is the name of the symbol. It must be a string. The
3412 optional @var{block} argument restricts the search to symbols visible
3413 in that @var{block}. The @var{block} argument must be a
3414 @code{gdb.Block} object. If omitted, the block for the current frame
3415 is used. The optional @var{domain} argument restricts
3416 the search to the domain type. The @var{domain} argument must be a
3417 domain constant defined in the @code{gdb} module and described later
3420 The result is a tuple of two elements.
3421 The first element is a @code{gdb.Symbol} object or @code{None} if the symbol
3423 If the symbol is found, the second element is @code{True} if the symbol
3424 is a field of a method's object (e.g., @code{this} in C@t{++}),
3425 otherwise it is @code{False}.
3426 If the symbol is not found, the second element is @code{False}.
3429 @findex gdb.lookup_global_symbol
3430 @defun gdb.lookup_global_symbol (name @r{[}, domain@r{]})
3431 This function searches for a global symbol by name.
3432 The search scope can be restricted to by the domain argument.
3434 @var{name} is the name of the symbol. It must be a string.
3435 The optional @var{domain} argument restricts the search to the domain type.
3436 The @var{domain} argument must be a domain constant defined in the @code{gdb}
3437 module and described later in this chapter.
3439 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
3443 A @code{gdb.Symbol} object has the following attributes:
3446 The type of the symbol or @code{None} if no type is recorded.
3447 This attribute is represented as a @code{gdb.Type} object.
3448 @xref{Types In Python}. This attribute is not writable.
3451 @defvar Symbol.symtab
3452 The symbol table in which the symbol appears. This attribute is
3453 represented as a @code{gdb.Symtab} object. @xref{Symbol Tables In
3454 Python}. This attribute is not writable.
3458 The line number in the source code at which the symbol was defined.
3463 The name of the symbol as a string. This attribute is not writable.
3466 @defvar Symbol.linkage_name
3467 The name of the symbol, as used by the linker (i.e., may be mangled).
3468 This attribute is not writable.
3471 @defvar Symbol.print_name
3472 The name of the symbol in a form suitable for output. This is either
3473 @code{name} or @code{linkage_name}, depending on whether the user
3474 asked @value{GDBN} to display demangled or mangled names.
3477 @defvar Symbol.addr_class
3478 The address class of the symbol. This classifies how to find the value
3479 of a symbol. Each address class is a constant defined in the
3480 @code{gdb} module and described later in this chapter.
3483 @defvar Symbol.needs_frame
3484 This is @code{True} if evaluating this symbol's value requires a frame
3485 (@pxref{Frames In Python}) and @code{False} otherwise. Typically,
3486 local variables will require a frame, but other symbols will not.
3489 @defvar Symbol.is_argument
3490 @code{True} if the symbol is an argument of a function.
3493 @defvar Symbol.is_constant
3494 @code{True} if the symbol is a constant.
3497 @defvar Symbol.is_function
3498 @code{True} if the symbol is a function or a method.
3501 @defvar Symbol.is_variable
3502 @code{True} if the symbol is a variable.
3505 A @code{gdb.Symbol} object has the following methods:
3507 @defun Symbol.is_valid ()
3508 Returns @code{True} if the @code{gdb.Symbol} object is valid,
3509 @code{False} if not. A @code{gdb.Symbol} object can become invalid if
3510 the symbol it refers to does not exist in @value{GDBN} any longer.
3511 All other @code{gdb.Symbol} methods will throw an exception if it is
3512 invalid at the time the method is called.
3515 @defun Symbol.value (@r{[}frame@r{]})
3516 Compute the value of the symbol, as a @code{gdb.Value}. For
3517 functions, this computes the address of the function, cast to the
3518 appropriate type. If the symbol requires a frame in order to compute
3519 its value, then @var{frame} must be given. If @var{frame} is not
3520 given, or if @var{frame} is invalid, then this method will throw an
3524 The available domain categories in @code{gdb.Symbol} are represented
3525 as constants in the @code{gdb} module:
3528 @vindex SYMBOL_UNDEF_DOMAIN
3529 @item gdb.SYMBOL_UNDEF_DOMAIN
3530 This is used when a domain has not been discovered or none of the
3531 following domains apply. This usually indicates an error either
3532 in the symbol information or in @value{GDBN}'s handling of symbols.
3534 @vindex SYMBOL_VAR_DOMAIN
3535 @item gdb.SYMBOL_VAR_DOMAIN
3536 This domain contains variables, function names, typedef names and enum
3539 @vindex SYMBOL_STRUCT_DOMAIN
3540 @item gdb.SYMBOL_STRUCT_DOMAIN
3541 This domain holds struct, union and enum type names.
3543 @vindex SYMBOL_LABEL_DOMAIN
3544 @item gdb.SYMBOL_LABEL_DOMAIN
3545 This domain contains names of labels (for gotos).
3547 @vindex SYMBOL_VARIABLES_DOMAIN
3548 @item gdb.SYMBOL_VARIABLES_DOMAIN
3549 This domain holds a subset of the @code{SYMBOLS_VAR_DOMAIN}; it
3550 contains everything minus functions and types.
3552 @vindex SYMBOL_FUNCTIONS_DOMAIN
3553 @item gdb.SYMBOL_FUNCTION_DOMAIN
3554 This domain contains all functions.
3556 @vindex SYMBOL_TYPES_DOMAIN
3557 @item gdb.SYMBOL_TYPES_DOMAIN
3558 This domain contains all types.
3561 The available address class categories in @code{gdb.Symbol} are represented
3562 as constants in the @code{gdb} module:
3565 @vindex SYMBOL_LOC_UNDEF
3566 @item gdb.SYMBOL_LOC_UNDEF
3567 If this is returned by address class, it indicates an error either in
3568 the symbol information or in @value{GDBN}'s handling of symbols.
3570 @vindex SYMBOL_LOC_CONST
3571 @item gdb.SYMBOL_LOC_CONST
3572 Value is constant int.
3574 @vindex SYMBOL_LOC_STATIC
3575 @item gdb.SYMBOL_LOC_STATIC
3576 Value is at a fixed address.
3578 @vindex SYMBOL_LOC_REGISTER
3579 @item gdb.SYMBOL_LOC_REGISTER
3580 Value is in a register.
3582 @vindex SYMBOL_LOC_ARG
3583 @item gdb.SYMBOL_LOC_ARG
3584 Value is an argument. This value is at the offset stored within the
3585 symbol inside the frame's argument list.
3587 @vindex SYMBOL_LOC_REF_ARG
3588 @item gdb.SYMBOL_LOC_REF_ARG
3589 Value address is stored in the frame's argument list. Just like
3590 @code{LOC_ARG} except that the value's address is stored at the
3591 offset, not the value itself.
3593 @vindex SYMBOL_LOC_REGPARM_ADDR
3594 @item gdb.SYMBOL_LOC_REGPARM_ADDR
3595 Value is a specified register. Just like @code{LOC_REGISTER} except
3596 the register holds the address of the argument instead of the argument
3599 @vindex SYMBOL_LOC_LOCAL
3600 @item gdb.SYMBOL_LOC_LOCAL
3601 Value is a local variable.
3603 @vindex SYMBOL_LOC_TYPEDEF
3604 @item gdb.SYMBOL_LOC_TYPEDEF
3605 Value not used. Symbols in the domain @code{SYMBOL_STRUCT_DOMAIN} all
3608 @vindex SYMBOL_LOC_BLOCK
3609 @item gdb.SYMBOL_LOC_BLOCK
3612 @vindex SYMBOL_LOC_CONST_BYTES
3613 @item gdb.SYMBOL_LOC_CONST_BYTES
3614 Value is a byte-sequence.
3616 @vindex SYMBOL_LOC_UNRESOLVED
3617 @item gdb.SYMBOL_LOC_UNRESOLVED
3618 Value is at a fixed address, but the address of the variable has to be
3619 determined from the minimal symbol table whenever the variable is
3622 @vindex SYMBOL_LOC_OPTIMIZED_OUT
3623 @item gdb.SYMBOL_LOC_OPTIMIZED_OUT
3624 The value does not actually exist in the program.
3626 @vindex SYMBOL_LOC_COMPUTED
3627 @item gdb.SYMBOL_LOC_COMPUTED
3628 The value's address is a computed location.
3631 @node Symbol Tables In Python
3632 @subsubsection Symbol table representation in Python.
3634 @cindex symbol tables in python
3636 @tindex gdb.Symtab_and_line
3638 Access to symbol table data maintained by @value{GDBN} on the inferior
3639 is exposed to Python via two objects: @code{gdb.Symtab_and_line} and
3640 @code{gdb.Symtab}. Symbol table and line data for a frame is returned
3641 from the @code{find_sal} method in @code{gdb.Frame} object.
3642 @xref{Frames In Python}.
3644 For more information on @value{GDBN}'s symbol table management, see
3645 @ref{Symbols, ,Examining the Symbol Table}, for more information.
3647 A @code{gdb.Symtab_and_line} object has the following attributes:
3649 @defvar Symtab_and_line.symtab
3650 The symbol table object (@code{gdb.Symtab}) for this frame.
3651 This attribute is not writable.
3654 @defvar Symtab_and_line.pc
3655 Indicates the start of the address range occupied by code for the
3656 current source line. This attribute is not writable.
3659 @defvar Symtab_and_line.last
3660 Indicates the end of the address range occupied by code for the current
3661 source line. This attribute is not writable.
3664 @defvar Symtab_and_line.line
3665 Indicates the current line number for this object. This
3666 attribute is not writable.
3669 A @code{gdb.Symtab_and_line} object has the following methods:
3671 @defun Symtab_and_line.is_valid ()
3672 Returns @code{True} if the @code{gdb.Symtab_and_line} object is valid,
3673 @code{False} if not. A @code{gdb.Symtab_and_line} object can become
3674 invalid if the Symbol table and line object it refers to does not
3675 exist in @value{GDBN} any longer. All other
3676 @code{gdb.Symtab_and_line} methods will throw an exception if it is
3677 invalid at the time the method is called.
3680 A @code{gdb.Symtab} object has the following attributes:
3682 @defvar Symtab.filename
3683 The symbol table's source filename. This attribute is not writable.
3686 @defvar Symtab.objfile
3687 The symbol table's backing object file. @xref{Objfiles In Python}.
3688 This attribute is not writable.
3691 A @code{gdb.Symtab} object has the following methods:
3693 @defun Symtab.is_valid ()
3694 Returns @code{True} if the @code{gdb.Symtab} object is valid,
3695 @code{False} if not. A @code{gdb.Symtab} object can become invalid if
3696 the symbol table it refers to does not exist in @value{GDBN} any
3697 longer. All other @code{gdb.Symtab} methods will throw an exception
3698 if it is invalid at the time the method is called.
3701 @defun Symtab.fullname ()
3702 Return the symbol table's source absolute file name.
3705 @defun Symtab.global_block ()
3706 Return the global block of the underlying symbol table.
3707 @xref{Blocks In Python}.
3710 @defun Symtab.static_block ()
3711 Return the static block of the underlying symbol table.
3712 @xref{Blocks In Python}.
3715 @defun Symtab.linetable ()
3716 Return the line table associated with the symbol table.
3717 @xref{Line Tables In Python}.
3720 @node Line Tables In Python
3721 @subsubsection Manipulating line tables using Python
3723 @cindex line tables in python
3724 @tindex gdb.LineTable
3726 Python code can request and inspect line table information from a
3727 symbol table that is loaded in @value{GDBN}. A line table is a
3728 mapping of source lines to their executable locations in memory. To
3729 acquire the line table information for a particular symbol table, use
3730 the @code{linetable} function (@pxref{Symbol Tables In Python}).
3732 A @code{gdb.LineTable} is iterable. The iterator returns
3733 @code{LineTableEntry} objects that correspond to the source line and
3734 address for each line table entry. @code{LineTableEntry} objects have
3735 the following attributes:
3737 @defvar LineTableEntry.line
3738 The source line number for this line table entry. This number
3739 corresponds to the actual line of source. This attribute is not
3743 @defvar LineTableEntry.pc
3744 The address that is associated with the line table entry where the
3745 executable code for that source line resides in memory. This
3746 attribute is not writable.
3749 As there can be multiple addresses for a single source line, you may
3750 receive multiple @code{LineTableEntry} objects with matching
3751 @code{line} attributes, but with different @code{pc} attributes. The
3752 iterator is sorted in ascending @code{pc} order. Here is a small
3753 example illustrating iterating over a line table.
3756 symtab = gdb.selected_frame().find_sal().symtab
3757 linetable = symtab.linetable()
3758 for line in linetable:
3759 print "Line: "+str(line.line)+" Address: "+hex(line.pc)
3762 This will have the following output:
3765 Line: 33 Address: 0x4005c8L
3766 Line: 37 Address: 0x4005caL
3767 Line: 39 Address: 0x4005d2L
3768 Line: 40 Address: 0x4005f8L
3769 Line: 42 Address: 0x4005ffL
3770 Line: 44 Address: 0x400608L
3771 Line: 42 Address: 0x40060cL
3772 Line: 45 Address: 0x400615L
3775 In addition to being able to iterate over a @code{LineTable}, it also
3776 has the following direct access methods:
3778 @defun LineTable.line (line)
3779 Return a Python @code{Tuple} of @code{LineTableEntry} objects for any
3780 entries in the line table for the given @var{line}. @var{line} refers
3781 to the source code line. If there are no entries for that source code
3782 @var{line}, the Python @code{None} is returned.
3785 @defun LineTable.has_line (line)
3786 Return a Python @code{Boolean} indicating whether there is an entry in
3787 the line table for this source line. Return @code{True} if an entry
3788 is found, or @code{False} if not.
3791 @defun LineTable.source_lines ()
3792 Return a Python @code{List} of the source line numbers in the symbol
3793 table. Only lines with executable code locations are returned. The
3794 contents of the @code{List} will just be the source line entries
3795 represented as Python @code{Long} values.
3798 @node Breakpoints In Python
3799 @subsubsection Manipulating breakpoints using Python
3801 @cindex breakpoints in python
3802 @tindex gdb.Breakpoint
3804 Python code can manipulate breakpoints via the @code{gdb.Breakpoint}
3807 @defun Breakpoint.__init__ (spec @r{[}, type @r{[}, wp_class @r{[},internal @r{[},temporary@r{]]]]})
3808 Create a new breakpoint. @var{spec} is a string naming the location
3809 of the breakpoint, or an expression that defines a watchpoint. The
3810 contents can be any location recognized by the @code{break} command,
3811 or in the case of a watchpoint, by the @code{watch} command. The
3812 optional @var{type} denotes the breakpoint to create from the types
3813 defined later in this chapter. This argument can be either:
3814 @code{gdb.BP_BREAKPOINT} or @code{gdb.BP_WATCHPOINT}. @var{type}
3815 defaults to @code{gdb.BP_BREAKPOINT}. The optional @var{internal}
3816 argument allows the breakpoint to become invisible to the user. The
3817 breakpoint will neither be reported when created, nor will it be
3818 listed in the output from @code{info breakpoints} (but will be listed
3819 with the @code{maint info breakpoints} command). The optional
3820 @var{temporary} argument makes the breakpoint a temporary breakpoint.
3821 Temporary breakpoints are deleted after they have been hit. Any
3822 further access to the Python breakpoint after it has been hit will
3823 result in a runtime error (as that breakpoint has now been
3824 automatically deleted). The optional @var{wp_class} argument defines
3825 the class of watchpoint to create, if @var{type} is
3826 @code{gdb.BP_WATCHPOINT}. If a watchpoint class is not provided, it
3827 is assumed to be a @code{gdb.WP_WRITE} class.
3830 @defun Breakpoint.stop (self)
3831 The @code{gdb.Breakpoint} class can be sub-classed and, in
3832 particular, you may choose to implement the @code{stop} method.
3833 If this method is defined in a sub-class of @code{gdb.Breakpoint},
3834 it will be called when the inferior reaches any location of a
3835 breakpoint which instantiates that sub-class. If the method returns
3836 @code{True}, the inferior will be stopped at the location of the
3837 breakpoint, otherwise the inferior will continue.
3839 If there are multiple breakpoints at the same location with a
3840 @code{stop} method, each one will be called regardless of the
3841 return status of the previous. This ensures that all @code{stop}
3842 methods have a chance to execute at that location. In this scenario
3843 if one of the methods returns @code{True} but the others return
3844 @code{False}, the inferior will still be stopped.
3846 You should not alter the execution state of the inferior (i.e.@:, step,
3847 next, etc.), alter the current frame context (i.e.@:, change the current
3848 active frame), or alter, add or delete any breakpoint. As a general
3849 rule, you should not alter any data within @value{GDBN} or the inferior
3852 Example @code{stop} implementation:
3855 class MyBreakpoint (gdb.Breakpoint):
3857 inf_val = gdb.parse_and_eval("foo")
3864 The available watchpoint types represented by constants are defined in the
3870 Read only watchpoint.
3874 Write only watchpoint.
3878 Read/Write watchpoint.
3881 @defun Breakpoint.is_valid ()
3882 Return @code{True} if this @code{Breakpoint} object is valid,
3883 @code{False} otherwise. A @code{Breakpoint} object can become invalid
3884 if the user deletes the breakpoint. In this case, the object still
3885 exists, but the underlying breakpoint does not. In the cases of
3886 watchpoint scope, the watchpoint remains valid even if execution of the
3887 inferior leaves the scope of that watchpoint.
3890 @defun Breakpoint.delete
3891 Permanently deletes the @value{GDBN} breakpoint. This also
3892 invalidates the Python @code{Breakpoint} object. Any further access
3893 to this object's attributes or methods will raise an error.
3896 @defvar Breakpoint.enabled
3897 This attribute is @code{True} if the breakpoint is enabled, and
3898 @code{False} otherwise. This attribute is writable.
3901 @defvar Breakpoint.silent
3902 This attribute is @code{True} if the breakpoint is silent, and
3903 @code{False} otherwise. This attribute is writable.
3905 Note that a breakpoint can also be silent if it has commands and the
3906 first command is @code{silent}. This is not reported by the
3907 @code{silent} attribute.
3910 @defvar Breakpoint.thread
3911 If the breakpoint is thread-specific, this attribute holds the thread
3912 id. If the breakpoint is not thread-specific, this attribute is
3913 @code{None}. This attribute is writable.
3916 @defvar Breakpoint.task
3917 If the breakpoint is Ada task-specific, this attribute holds the Ada task
3918 id. If the breakpoint is not task-specific (or the underlying
3919 language is not Ada), this attribute is @code{None}. This attribute
3923 @defvar Breakpoint.ignore_count
3924 This attribute holds the ignore count for the breakpoint, an integer.
3925 This attribute is writable.
3928 @defvar Breakpoint.number
3929 This attribute holds the breakpoint's number --- the identifier used by
3930 the user to manipulate the breakpoint. This attribute is not writable.
3933 @defvar Breakpoint.type
3934 This attribute holds the breakpoint's type --- the identifier used to
3935 determine the actual breakpoint type or use-case. This attribute is not
3939 @defvar Breakpoint.visible
3940 This attribute tells whether the breakpoint is visible to the user
3941 when set, or when the @samp{info breakpoints} command is run. This
3942 attribute is not writable.
3945 @defvar Breakpoint.temporary
3946 This attribute indicates whether the breakpoint was created as a
3947 temporary breakpoint. Temporary breakpoints are automatically deleted
3948 after that breakpoint has been hit. Access to this attribute, and all
3949 other attributes and functions other than the @code{is_valid}
3950 function, will result in an error after the breakpoint has been hit
3951 (as it has been automatically deleted). This attribute is not
3955 The available types are represented by constants defined in the @code{gdb}
3959 @vindex BP_BREAKPOINT
3960 @item gdb.BP_BREAKPOINT
3961 Normal code breakpoint.
3963 @vindex BP_WATCHPOINT
3964 @item gdb.BP_WATCHPOINT
3965 Watchpoint breakpoint.
3967 @vindex BP_HARDWARE_WATCHPOINT
3968 @item gdb.BP_HARDWARE_WATCHPOINT
3969 Hardware assisted watchpoint.
3971 @vindex BP_READ_WATCHPOINT
3972 @item gdb.BP_READ_WATCHPOINT
3973 Hardware assisted read watchpoint.
3975 @vindex BP_ACCESS_WATCHPOINT
3976 @item gdb.BP_ACCESS_WATCHPOINT
3977 Hardware assisted access watchpoint.
3980 @defvar Breakpoint.hit_count
3981 This attribute holds the hit count for the breakpoint, an integer.
3982 This attribute is writable, but currently it can only be set to zero.
3985 @defvar Breakpoint.location
3986 This attribute holds the location of the breakpoint, as specified by
3987 the user. It is a string. If the breakpoint does not have a location
3988 (that is, it is a watchpoint) the attribute's value is @code{None}. This
3989 attribute is not writable.
3992 @defvar Breakpoint.expression
3993 This attribute holds a breakpoint expression, as specified by
3994 the user. It is a string. If the breakpoint does not have an
3995 expression (the breakpoint is not a watchpoint) the attribute's value
3996 is @code{None}. This attribute is not writable.
3999 @defvar Breakpoint.condition
4000 This attribute holds the condition of the breakpoint, as specified by
4001 the user. It is a string. If there is no condition, this attribute's
4002 value is @code{None}. This attribute is writable.
4005 @defvar Breakpoint.commands
4006 This attribute holds the commands attached to the breakpoint. If
4007 there are commands, this attribute's value is a string holding all the
4008 commands, separated by newlines. If there are no commands, this
4009 attribute is @code{None}. This attribute is not writable.
4012 @node Finish Breakpoints in Python
4013 @subsubsection Finish Breakpoints
4015 @cindex python finish breakpoints
4016 @tindex gdb.FinishBreakpoint
4018 A finish breakpoint is a temporary breakpoint set at the return address of
4019 a frame, based on the @code{finish} command. @code{gdb.FinishBreakpoint}
4020 extends @code{gdb.Breakpoint}. The underlying breakpoint will be disabled
4021 and deleted when the execution will run out of the breakpoint scope (i.e.@:
4022 @code{Breakpoint.stop} or @code{FinishBreakpoint.out_of_scope} triggered).
4023 Finish breakpoints are thread specific and must be create with the right
4026 @defun FinishBreakpoint.__init__ (@r{[}frame@r{]} @r{[}, internal@r{]})
4027 Create a finish breakpoint at the return address of the @code{gdb.Frame}
4028 object @var{frame}. If @var{frame} is not provided, this defaults to the
4029 newest frame. The optional @var{internal} argument allows the breakpoint to
4030 become invisible to the user. @xref{Breakpoints In Python}, for further
4031 details about this argument.
4034 @defun FinishBreakpoint.out_of_scope (self)
4035 In some circumstances (e.g.@: @code{longjmp}, C@t{++} exceptions, @value{GDBN}
4036 @code{return} command, @dots{}), a function may not properly terminate, and
4037 thus never hit the finish breakpoint. When @value{GDBN} notices such a
4038 situation, the @code{out_of_scope} callback will be triggered.
4040 You may want to sub-class @code{gdb.FinishBreakpoint} and override this
4044 class MyFinishBreakpoint (gdb.FinishBreakpoint)
4046 print "normal finish"
4049 def out_of_scope ():
4050 print "abnormal finish"
4054 @defvar FinishBreakpoint.return_value
4055 When @value{GDBN} is stopped at a finish breakpoint and the frame
4056 used to build the @code{gdb.FinishBreakpoint} object had debug symbols, this
4057 attribute will contain a @code{gdb.Value} object corresponding to the return
4058 value of the function. The value will be @code{None} if the function return
4059 type is @code{void} or if the return value was not computable. This attribute
4063 @node Lazy Strings In Python
4064 @subsubsection Python representation of lazy strings.
4066 @cindex lazy strings in python
4067 @tindex gdb.LazyString
4069 A @dfn{lazy string} is a string whose contents is not retrieved or
4070 encoded until it is needed.
4072 A @code{gdb.LazyString} is represented in @value{GDBN} as an
4073 @code{address} that points to a region of memory, an @code{encoding}
4074 that will be used to encode that region of memory, and a @code{length}
4075 to delimit the region of memory that represents the string. The
4076 difference between a @code{gdb.LazyString} and a string wrapped within
4077 a @code{gdb.Value} is that a @code{gdb.LazyString} will be treated
4078 differently by @value{GDBN} when printing. A @code{gdb.LazyString} is
4079 retrieved and encoded during printing, while a @code{gdb.Value}
4080 wrapping a string is immediately retrieved and encoded on creation.
4082 A @code{gdb.LazyString} object has the following functions:
4084 @defun LazyString.value ()
4085 Convert the @code{gdb.LazyString} to a @code{gdb.Value}. This value
4086 will point to the string in memory, but will lose all the delayed
4087 retrieval, encoding and handling that @value{GDBN} applies to a
4088 @code{gdb.LazyString}.
4091 @defvar LazyString.address
4092 This attribute holds the address of the string. This attribute is not
4096 @defvar LazyString.length
4097 This attribute holds the length of the string in characters. If the
4098 length is -1, then the string will be fetched and encoded up to the
4099 first null of appropriate width. This attribute is not writable.
4102 @defvar LazyString.encoding
4103 This attribute holds the encoding that will be applied to the string
4104 when the string is printed by @value{GDBN}. If the encoding is not
4105 set, or contains an empty string, then @value{GDBN} will select the
4106 most appropriate encoding when the string is printed. This attribute
4110 @defvar LazyString.type
4111 This attribute holds the type that is represented by the lazy string's
4112 type. For a lazy string this will always be a pointer type. To
4113 resolve this to the lazy string's character type, use the type's
4114 @code{target} method. @xref{Types In Python}. This attribute is not
4118 @node Architectures In Python
4119 @subsubsection Python representation of architectures
4120 @cindex Python architectures
4122 @value{GDBN} uses architecture specific parameters and artifacts in a
4123 number of its various computations. An architecture is represented
4124 by an instance of the @code{gdb.Architecture} class.
4126 A @code{gdb.Architecture} class has the following methods:
4128 @defun Architecture.name ()
4129 Return the name (string value) of the architecture.
4132 @defun Architecture.disassemble (@var{start_pc} @r{[}, @var{end_pc} @r{[}, @var{count}@r{]]})
4133 Return a list of disassembled instructions starting from the memory
4134 address @var{start_pc}. The optional arguments @var{end_pc} and
4135 @var{count} determine the number of instructions in the returned list.
4136 If both the optional arguments @var{end_pc} and @var{count} are
4137 specified, then a list of at most @var{count} disassembled instructions
4138 whose start address falls in the closed memory address interval from
4139 @var{start_pc} to @var{end_pc} are returned. If @var{end_pc} is not
4140 specified, but @var{count} is specified, then @var{count} number of
4141 instructions starting from the address @var{start_pc} are returned. If
4142 @var{count} is not specified but @var{end_pc} is specified, then all
4143 instructions whose start address falls in the closed memory address
4144 interval from @var{start_pc} to @var{end_pc} are returned. If neither
4145 @var{end_pc} nor @var{count} are specified, then a single instruction at
4146 @var{start_pc} is returned. For all of these cases, each element of the
4147 returned list is a Python @code{dict} with the following string keys:
4152 The value corresponding to this key is a Python long integer capturing
4153 the memory address of the instruction.
4156 The value corresponding to this key is a string value which represents
4157 the instruction with assembly language mnemonics. The assembly
4158 language flavor used is the same as that specified by the current CLI
4159 variable @code{disassembly-flavor}. @xref{Machine Code}.
4162 The value corresponding to this key is the length (integer value) of the
4163 instruction in bytes.
4168 @node Python Auto-loading
4169 @subsection Python Auto-loading
4170 @cindex Python auto-loading
4172 When a new object file is read (for example, due to the @code{file}
4173 command, or because the inferior has loaded a shared library),
4174 @value{GDBN} will look for Python support scripts in several ways:
4175 @file{@var{objfile}-gdb.py} and @code{.debug_gdb_scripts} section.
4176 @xref{Auto-loading extensions}.
4178 The auto-loading feature is useful for supplying application-specific
4179 debugging commands and scripts.
4181 Auto-loading can be enabled or disabled,
4182 and the list of auto-loaded scripts can be printed.
4185 @anchor{set auto-load python-scripts}
4186 @kindex set auto-load python-scripts
4187 @item set auto-load python-scripts [on|off]
4188 Enable or disable the auto-loading of Python scripts.
4190 @anchor{show auto-load python-scripts}
4191 @kindex show auto-load python-scripts
4192 @item show auto-load python-scripts
4193 Show whether auto-loading of Python scripts is enabled or disabled.
4195 @anchor{info auto-load python-scripts}
4196 @kindex info auto-load python-scripts
4197 @cindex print list of auto-loaded Python scripts
4198 @item info auto-load python-scripts [@var{regexp}]
4199 Print the list of all Python scripts that @value{GDBN} auto-loaded.
4201 Also printed is the list of Python scripts that were mentioned in
4202 the @code{.debug_gdb_scripts} section and were not found
4203 (@pxref{dotdebug_gdb_scripts section}).
4204 This is useful because their names are not printed when @value{GDBN}
4205 tries to load them and fails. There may be many of them, and printing
4206 an error message for each one is problematic.
4208 If @var{regexp} is supplied only Python scripts with matching names are printed.
4213 (gdb) info auto-load python-scripts
4215 Yes py-section-script.py
4216 full name: /tmp/py-section-script.py
4217 No my-foo-pretty-printers.py
4221 When reading an auto-loaded file, @value{GDBN} sets the
4222 @dfn{current objfile}. This is available via the @code{gdb.current_objfile}
4223 function (@pxref{Objfiles In Python}). This can be useful for
4224 registering objfile-specific pretty-printers and frame-filters.
4226 @node Python modules
4227 @subsection Python modules
4228 @cindex python modules
4230 @value{GDBN} comes with several modules to assist writing Python code.
4233 * gdb.printing:: Building and registering pretty-printers.
4234 * gdb.types:: Utilities for working with types.
4235 * gdb.prompt:: Utilities for prompt value substitution.
4239 @subsubsection gdb.printing
4240 @cindex gdb.printing
4242 This module provides a collection of utilities for working with
4246 @item PrettyPrinter (@var{name}, @var{subprinters}=None)
4247 This class specifies the API that makes @samp{info pretty-printer},
4248 @samp{enable pretty-printer} and @samp{disable pretty-printer} work.
4249 Pretty-printers should generally inherit from this class.
4251 @item SubPrettyPrinter (@var{name})
4252 For printers that handle multiple types, this class specifies the
4253 corresponding API for the subprinters.
4255 @item RegexpCollectionPrettyPrinter (@var{name})
4256 Utility class for handling multiple printers, all recognized via
4257 regular expressions.
4258 @xref{Writing a Pretty-Printer}, for an example.
4260 @item FlagEnumerationPrinter (@var{name})
4261 A pretty-printer which handles printing of @code{enum} values. Unlike
4262 @value{GDBN}'s built-in @code{enum} printing, this printer attempts to
4263 work properly when there is some overlap between the enumeration
4264 constants. @var{name} is the name of the printer and also the name of
4265 the @code{enum} type to look up.
4267 @item register_pretty_printer (@var{obj}, @var{printer}, @var{replace}=False)
4268 Register @var{printer} with the pretty-printer list of @var{obj}.
4269 If @var{replace} is @code{True} then any existing copy of the printer
4270 is replaced. Otherwise a @code{RuntimeError} exception is raised
4271 if a printer with the same name already exists.
4275 @subsubsection gdb.types
4278 This module provides a collection of utilities for working with
4279 @code{gdb.Type} objects.
4282 @item get_basic_type (@var{type})
4283 Return @var{type} with const and volatile qualifiers stripped,
4284 and with typedefs and C@t{++} references converted to the underlying type.
4289 typedef const int const_int;
4291 const_int& foo_ref (foo);
4292 int main () @{ return 0; @}
4299 (gdb) python import gdb.types
4300 (gdb) python foo_ref = gdb.parse_and_eval("foo_ref")
4301 (gdb) python print gdb.types.get_basic_type(foo_ref.type)
4305 @item has_field (@var{type}, @var{field})
4306 Return @code{True} if @var{type}, assumed to be a type with fields
4307 (e.g., a structure or union), has field @var{field}.
4309 @item make_enum_dict (@var{enum_type})
4310 Return a Python @code{dictionary} type produced from @var{enum_type}.
4312 @item deep_items (@var{type})
4313 Returns a Python iterator similar to the standard
4314 @code{gdb.Type.iteritems} method, except that the iterator returned
4315 by @code{deep_items} will recursively traverse anonymous struct or
4316 union fields. For example:
4330 Then in @value{GDBN}:
4332 (@value{GDBP}) python import gdb.types
4333 (@value{GDBP}) python struct_a = gdb.lookup_type("struct A")
4334 (@value{GDBP}) python print struct_a.keys ()
4336 (@value{GDBP}) python print [k for k,v in gdb.types.deep_items(struct_a)]
4337 @{['a', 'b0', 'b1']@}
4340 @item get_type_recognizers ()
4341 Return a list of the enabled type recognizers for the current context.
4342 This is called by @value{GDBN} during the type-printing process
4343 (@pxref{Type Printing API}).
4345 @item apply_type_recognizers (recognizers, type_obj)
4346 Apply the type recognizers, @var{recognizers}, to the type object
4347 @var{type_obj}. If any recognizer returns a string, return that
4348 string. Otherwise, return @code{None}. This is called by
4349 @value{GDBN} during the type-printing process (@pxref{Type Printing
4352 @item register_type_printer (locus, printer)
4353 This is a convenience function to register a type printer.
4354 @var{printer} is the type printer to register. It must implement the
4355 type printer protocol. @var{locus} is either a @code{gdb.Objfile}, in
4356 which case the printer is registered with that objfile; a
4357 @code{gdb.Progspace}, in which case the printer is registered with
4358 that progspace; or @code{None}, in which case the printer is
4359 registered globally.
4362 This is a base class that implements the type printer protocol. Type
4363 printers are encouraged, but not required, to derive from this class.
4364 It defines a constructor:
4366 @defmethod TypePrinter __init__ (self, name)
4367 Initialize the type printer with the given name. The new printer
4368 starts in the enabled state.
4374 @subsubsection gdb.prompt
4377 This module provides a method for prompt value-substitution.
4380 @item substitute_prompt (@var{string})
4381 Return @var{string} with escape sequences substituted by values. Some
4382 escape sequences take arguments. You can specify arguments inside
4383 ``@{@}'' immediately following the escape sequence.
4385 The escape sequences you can pass to this function are:
4389 Substitute a backslash.
4391 Substitute an ESC character.
4393 Substitute the selected frame; an argument names a frame parameter.
4395 Substitute a newline.
4397 Substitute a parameter's value; the argument names the parameter.
4399 Substitute a carriage return.
4401 Substitute the selected thread; an argument names a thread parameter.
4403 Substitute the version of GDB.
4405 Substitute the current working directory.
4407 Begin a sequence of non-printing characters. These sequences are
4408 typically used with the ESC character, and are not counted in the string
4409 length. Example: ``\[\e[0;34m\](gdb)\[\e[0m\]'' will return a
4410 blue-colored ``(gdb)'' prompt where the length is five.
4412 End a sequence of non-printing characters.
4418 substitute_prompt (``frame: \f,
4419 print arguments: \p@{print frame-arguments@}'')
4422 @exdent will return the string:
4425 "frame: main, print arguments: scalars"