1 @c Copyright (C) 2008--2023 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:
96 @anchor{set_python_print_stack}
97 @kindex set python print-stack
98 @item set python print-stack
99 By default, @value{GDBN} will print only the message component of a
100 Python exception when an error occurs in a Python script. This can be
101 controlled using @code{set python print-stack}: if @code{full}, then
102 full Python stack printing is enabled; if @code{none}, then Python stack
103 and message printing is disabled; if @code{message}, the default, only
104 the message component of the error is printed.
106 @kindex set python ignore-environment
107 @item set python ignore-environment @r{[}on@r{|}off@r{]}
108 By default this option is @samp{off}, and, when @value{GDBN}
109 initializes its internal Python interpreter, the Python interpreter
110 will check the environment for variables that will effect how it
111 behaves, for example @env{PYTHONHOME}, and
112 @env{PYTHONPATH}@footnote{See the ENVIRONMENT VARIABLES section of
113 @command{man 1 python} for a comprehensive list.}.
115 If this option is set to @samp{on} before Python is initialized then
116 Python will ignore all such environment variables. As Python is
117 initialized early during @value{GDBN}'s startup process, then this
118 option must be placed into the early initialization file
119 (@pxref{Initialization Files}) to have the desired effect.
121 This option is equivalent to passing @option{-E} to the real
122 @command{python} executable.
124 @kindex set python dont-write-bytecode
125 @item set python dont-write-bytecode @r{[}auto@r{|}on@r{|}off@r{]}
126 When this option is @samp{off}, then, once @value{GDBN} has
127 initialized the Python interpreter, the interpreter will byte-compile
128 any Python modules that it imports and write the byte code to disk in
131 If this option is set to @samp{on} before Python is initialized then
132 Python will no longer write the byte code to disk. As Python is
133 initialized early during @value{GDBN}'s startup process, then this
134 option must be placed into the early initialization file
135 (@pxref{Initialization Files}) to have the desired effect.
137 By default this option is set to @samp{auto}. In this mode, provided
138 the @code{python ignore-environment} setting is @samp{off}, the
139 environment variable @env{PYTHONDONTWRITEBYTECODE} is examined to see
140 if it should write out byte-code or not.
141 @env{PYTHONDONTWRITEBYTECODE} is considered to be off/disabled either
142 when set to the empty string or when the environment variable doesn't
143 exist. All other settings, including those which don't seem to make
144 sense, indicate that it's on/enabled.
146 This option is equivalent to passing @option{-B} to the real
147 @command{python} executable.
150 It is also possible to execute a Python script from the @value{GDBN}
154 @item source @file{script-name}
155 The script name must end with @samp{.py} and @value{GDBN} must be configured
156 to recognize the script language based on filename extension using
157 the @code{script-extension} setting. @xref{Extending GDB, ,Extending GDB}.
160 The following commands are intended to help debug @value{GDBN} itself:
163 @kindex set debug py-breakpoint
164 @kindex show debug py-breakpoint
165 @item set debug py-breakpoint on@r{|}off
166 @itemx show debug py-breakpoint
167 When @samp{on}, @value{GDBN} prints debug messages related to the
168 Python breakpoint API. This is @samp{off} by default.
170 @kindex set debug py-unwind
171 @kindex show debug py-unwind
172 @item set debug py-unwind on@r{|}off
173 @itemx show debug py-unwind
174 When @samp{on}, @value{GDBN} prints debug messages related to the
175 Python unwinder API. This is @samp{off} by default.
179 @subsection Python API
181 @cindex programming in python
183 You can get quick online help for @value{GDBN}'s Python API by issuing
184 the command @w{@kbd{python help (gdb)}}.
186 Functions and methods which have two or more optional arguments allow
187 them to be specified using keyword syntax. This allows passing some
188 optional arguments while skipping others. Example:
189 @w{@code{gdb.some_function ('foo', bar = 1, baz = 2)}}.
192 * Basic Python:: Basic Python Functions.
193 * Exception Handling:: How Python exceptions are translated.
194 * Values From Inferior:: Python representation of values.
195 * Types In Python:: Python representation of types.
196 * Pretty Printing API:: Pretty-printing values.
197 * Selecting Pretty-Printers:: How GDB chooses a pretty-printer.
198 * Writing a Pretty-Printer:: Writing a Pretty-Printer.
199 * Type Printing API:: Pretty-printing types.
200 * Frame Filter API:: Filtering Frames.
201 * Frame Decorator API:: Decorating Frames.
202 * Writing a Frame Filter:: Writing a Frame Filter.
203 * Unwinding Frames in Python:: Writing frame unwinder.
204 * Xmethods In Python:: Adding and replacing methods of C++ classes.
205 * Xmethod API:: Xmethod types.
206 * Writing an Xmethod:: Writing an xmethod.
207 * Inferiors In Python:: Python representation of inferiors (processes)
208 * Events In Python:: Listening for events from @value{GDBN}.
209 * Threads In Python:: Accessing inferior threads from Python.
210 * Recordings In Python:: Accessing recordings from Python.
211 * CLI Commands In Python:: Implementing new CLI commands in Python.
212 * GDB/MI Commands In Python:: Implementing new @sc{gdb/mi} commands in Python.
213 * Parameters In Python:: Adding new @value{GDBN} parameters.
214 * Functions In Python:: Writing new convenience functions.
215 * Progspaces In Python:: Program spaces.
216 * Objfiles In Python:: Object files.
217 * Frames In Python:: Accessing inferior stack frames from Python.
218 * Blocks In Python:: Accessing blocks from Python.
219 * Symbols In Python:: Python representation of symbols.
220 * Symbol Tables In Python:: Python representation of symbol tables.
221 * Line Tables In Python:: Python representation of line tables.
222 * Breakpoints In Python:: Manipulating breakpoints using Python.
223 * Finish Breakpoints in Python:: Setting Breakpoints on function return
225 * Lazy Strings In Python:: Python representation of lazy strings.
226 * Architectures In Python:: Python representation of architectures.
227 * Registers In Python:: Python representation of registers.
228 * Connections In Python:: Python representation of connections.
229 * TUI Windows In Python:: Implementing new TUI windows.
230 * Disassembly In Python:: Instruction Disassembly In Python
234 @subsubsection Basic Python
236 @cindex python stdout
237 @cindex python pagination
238 At startup, @value{GDBN} overrides Python's @code{sys.stdout} and
239 @code{sys.stderr} to print using @value{GDBN}'s output-paging streams.
240 A Python program which outputs to one of these streams may have its
241 output interrupted by the user (@pxref{Screen Size}). In this
242 situation, a Python @code{KeyboardInterrupt} exception is thrown.
244 Some care must be taken when writing Python code to run in
245 @value{GDBN}. Two things worth noting in particular:
249 @value{GDBN} install handlers for @code{SIGCHLD} and @code{SIGINT}.
250 Python code must not override these, or even change the options using
251 @code{sigaction}. If your program changes the handling of these
252 signals, @value{GDBN} will most likely stop working correctly. Note
253 that it is unfortunately common for GUI toolkits to install a
254 @code{SIGCHLD} handler.
257 @value{GDBN} takes care to mark its internal file descriptors as
258 close-on-exec. However, this cannot be done in a thread-safe way on
259 all platforms. Your Python programs should be aware of this and
260 should both create new file descriptors with the close-on-exec flag
261 set and arrange to close unneeded file descriptors before starting a
265 @cindex python functions
266 @cindex python module
268 @value{GDBN} introduces a new Python module, named @code{gdb}. All
269 methods and classes added by @value{GDBN} are placed in this module.
270 @value{GDBN} automatically @code{import}s the @code{gdb} module for
271 use in all scripts evaluated by the @code{python} command.
273 Some types of the @code{gdb} module come with a textual representation
274 (accessible through the @code{repr} or @code{str} functions). These are
275 offered for debugging purposes only, expect them to change over time.
277 @findex gdb.PYTHONDIR
278 @defvar gdb.PYTHONDIR
279 A string containing the python directory (@pxref{Python}).
283 @defun gdb.execute (command @r{[}, from_tty @r{[}, to_string@r{]]})
284 Evaluate @var{command}, a string, as a @value{GDBN} CLI command.
285 If a GDB exception happens while @var{command} runs, it is
286 translated as described in @ref{Exception Handling,,Exception Handling}.
288 The @var{from_tty} flag specifies whether @value{GDBN} ought to consider this
289 command as having originated from the user invoking it interactively.
290 It must be a boolean value. If omitted, it defaults to @code{False}.
292 By default, any output produced by @var{command} is sent to
293 @value{GDBN}'s standard output (and to the log output if logging is
294 turned on). If the @var{to_string} parameter is
295 @code{True}, then output will be collected by @code{gdb.execute} and
296 returned as a string. The default is @code{False}, in which case the
297 return value is @code{None}. If @var{to_string} is @code{True}, the
298 @value{GDBN} virtual terminal will be temporarily set to unlimited width
299 and height, and its pagination will be disabled; @pxref{Screen Size}.
302 @findex gdb.breakpoints
303 @defun gdb.breakpoints ()
304 Return a sequence holding all of @value{GDBN}'s breakpoints.
305 @xref{Breakpoints In Python}, for more information. In @value{GDBN}
306 version 7.11 and earlier, this function returned @code{None} if there
307 were no breakpoints. This peculiarity was subsequently fixed, and now
308 @code{gdb.breakpoints} returns an empty sequence in this case.
311 @defun gdb.rbreak (regex @r{[}, minsyms @r{[}, throttle, @r{[}, symtabs @r{]]]})
312 Return a Python list holding a collection of newly set
313 @code{gdb.Breakpoint} objects matching function names defined by the
314 @var{regex} pattern. If the @var{minsyms} keyword is @code{True}, all
315 system functions (those not explicitly defined in the inferior) will
316 also be included in the match. The @var{throttle} keyword takes an
317 integer that defines the maximum number of pattern matches for
318 functions matched by the @var{regex} pattern. If the number of
319 matches exceeds the integer value of @var{throttle}, a
320 @code{RuntimeError} will be raised and no breakpoints will be created.
321 If @var{throttle} is not defined then there is no imposed limit on the
322 maximum number of matches and breakpoints to be created. The
323 @var{symtabs} keyword takes a Python iterable that yields a collection
324 of @code{gdb.Symtab} objects and will restrict the search to those
325 functions only contained within the @code{gdb.Symtab} objects.
328 @findex gdb.parameter
329 @defun gdb.parameter (parameter)
330 Return the value of a @value{GDBN} @var{parameter} given by its name,
331 a string; the parameter name string may contain spaces if the parameter has a
332 multi-part name. For example, @samp{print object} is a valid
335 If the named parameter does not exist, this function throws a
336 @code{gdb.error} (@pxref{Exception Handling}). Otherwise, the
337 parameter's value is converted to a Python value of the appropriate
341 @findex gdb.set_parameter
342 @defun gdb.set_parameter (name, value)
343 Sets the gdb parameter @var{name} to @var{value}. As with
344 @code{gdb.parameter}, the parameter name string may contain spaces if
345 the parameter has a multi-part name.
348 @findex gdb.with_parameter
349 @defun gdb.with_parameter (name, value)
350 Create a Python context manager (for use with the Python
351 @command{with} statement) that temporarily sets the gdb parameter
352 @var{name} to @var{value}. On exit from the context, the previous
353 value will be restored.
355 This uses @code{gdb.parameter} in its implementation, so it can throw
356 the same exceptions as that function.
358 For example, it's sometimes useful to evaluate some Python code with a
359 particular gdb language:
362 with gdb.with_parameter('language', 'pascal'):
363 ... language-specific operations
368 @defun gdb.history (number)
369 Return a value from @value{GDBN}'s value history (@pxref{Value
370 History}). The @var{number} argument indicates which history element to return.
371 If @var{number} is negative, then @value{GDBN} will take its absolute value
372 and count backward from the last element (i.e., the most recent element) to
373 find the value to return. If @var{number} is zero, then @value{GDBN} will
374 return the most recent element. If the element specified by @var{number}
375 doesn't exist in the value history, a @code{gdb.error} exception will be
378 If no exception is raised, the return value is always an instance of
379 @code{gdb.Value} (@pxref{Values From Inferior}).
382 @defun gdb.add_history (value)
383 Takes @var{value}, an instance of @code{gdb.Value} (@pxref{Values From
384 Inferior}), and appends the value this object represents to
385 @value{GDBN}'s value history (@pxref{Value History}), and return an
386 integer, its history number. If @var{value} is not a
387 @code{gdb.Value}, it is is converted using the @code{gdb.Value}
388 constructor. If @var{value} can't be converted to a @code{gdb.Value}
389 then a @code{TypeError} is raised.
391 When a command implemented in Python prints a single @code{gdb.Value}
392 as its result, then placing the value into the history will allow the
393 user convenient access to those values via CLI history facilities.
396 @defun gdb.history_count ()
397 Return an integer indicating the number of values in @value{GDBN}'s
398 value history (@pxref{Value History}).
401 @findex gdb.convenience_variable
402 @defun gdb.convenience_variable (name)
403 Return the value of the convenience variable (@pxref{Convenience
404 Vars}) named @var{name}. @var{name} must be a string. The name
405 should not include the @samp{$} that is used to mark a convenience
406 variable in an expression. If the convenience variable does not
407 exist, then @code{None} is returned.
410 @findex gdb.set_convenience_variable
411 @defun gdb.set_convenience_variable (name, value)
412 Set the value of the convenience variable (@pxref{Convenience Vars})
413 named @var{name}. @var{name} must be a string. The name should not
414 include the @samp{$} that is used to mark a convenience variable in an
415 expression. If @var{value} is @code{None}, then the convenience
416 variable is removed. Otherwise, if @var{value} is not a
417 @code{gdb.Value} (@pxref{Values From Inferior}), it is is converted
418 using the @code{gdb.Value} constructor.
421 @findex gdb.parse_and_eval
422 @defun gdb.parse_and_eval (expression @r{[}, global_context@r{]})
423 Parse @var{expression}, which must be a string, as an expression in
424 the current language, evaluate it, and return the result as a
427 @var{global_context}, if provided, is a boolean indicating whether the
428 parsing should be done in the global context. The default is
429 @samp{False}, meaning that the current frame or current static context
432 This function can be useful when implementing a new command
433 (@pxref{CLI Commands In Python}, @pxref{GDB/MI Commands In Python}),
434 as it provides a way to parse the
435 command's argument as an expression. It is also useful simply to
439 @findex gdb.find_pc_line
440 @defun gdb.find_pc_line (pc)
441 Return the @code{gdb.Symtab_and_line} object corresponding to the
442 @var{pc} value. @xref{Symbol Tables In Python}. If an invalid
443 value of @var{pc} is passed as an argument, then the @code{symtab} and
444 @code{line} attributes of the returned @code{gdb.Symtab_and_line} object
445 will be @code{None} and 0 respectively. This is identical to
446 @code{gdb.current_progspace().find_pc_line(pc)} and is included for
447 historical compatibility.
450 @findex gdb.post_event
451 @defun gdb.post_event (event)
452 Put @var{event}, a callable object taking no arguments, into
453 @value{GDBN}'s internal event queue. This callable will be invoked at
454 some later point, during @value{GDBN}'s event processing. Events
455 posted using @code{post_event} will be run in the order in which they
456 were posted; however, there is no way to know when they will be
457 processed relative to other events inside @value{GDBN}.
459 @value{GDBN} is not thread-safe. If your Python program uses multiple
460 threads, you must be careful to only call @value{GDBN}-specific
461 functions in the @value{GDBN} thread. @code{post_event} ensures
465 (@value{GDBP}) python
469 > def __init__(self, message):
470 > self.message = message;
471 > def __call__(self):
472 > gdb.write(self.message)
474 >class MyThread1 (threading.Thread):
476 > gdb.post_event(Writer("Hello "))
478 >class MyThread2 (threading.Thread):
480 > gdb.post_event(Writer("World\n"))
485 (@value{GDBP}) Hello World
490 @defun gdb.write (string @r{[}, stream@r{]})
491 Print a string to @value{GDBN}'s paginated output stream. The
492 optional @var{stream} determines the stream to print to. The default
493 stream is @value{GDBN}'s standard output stream. Possible stream
500 @value{GDBN}'s standard output stream.
505 @value{GDBN}'s standard error stream.
510 @value{GDBN}'s log stream (@pxref{Logging Output}).
513 Writing to @code{sys.stdout} or @code{sys.stderr} will automatically
514 call this function and will automatically direct the output to the
519 @defun gdb.flush (@r{[}, stream@r{]})
520 Flush the buffer of a @value{GDBN} paginated stream so that the
521 contents are displayed immediately. @value{GDBN} will flush the
522 contents of a stream automatically when it encounters a newline in the
523 buffer. The optional @var{stream} determines the stream to flush. The
524 default stream is @value{GDBN}'s standard output stream. Possible
531 @value{GDBN}'s standard output stream.
536 @value{GDBN}'s standard error stream.
541 @value{GDBN}'s log stream (@pxref{Logging Output}).
545 Flushing @code{sys.stdout} or @code{sys.stderr} will automatically
546 call this function for the relevant stream.
549 @findex gdb.target_charset
550 @defun gdb.target_charset ()
551 Return the name of the current target character set (@pxref{Character
552 Sets}). This differs from @code{gdb.parameter('target-charset')} in
553 that @samp{auto} is never returned.
556 @findex gdb.target_wide_charset
557 @defun gdb.target_wide_charset ()
558 Return the name of the current target wide character set
559 (@pxref{Character Sets}). This differs from
560 @code{gdb.parameter('target-wide-charset')} in that @samp{auto} is
564 @findex gdb.host_charset
565 @defun gdb.host_charset ()
566 Return a string, the name of the current host character set
567 (@pxref{Character Sets}). This differs from
568 @code{gdb.parameter('host-charset')} in that @samp{auto} is never
572 @findex gdb.solib_name
573 @defun gdb.solib_name (address)
574 Return the name of the shared library holding the given @var{address}
575 as a string, or @code{None}. This is identical to
576 @code{gdb.current_progspace().solib_name(address)} and is included for
577 historical compatibility.
580 @findex gdb.decode_line
581 @defun gdb.decode_line (@r{[}expression@r{]})
582 Return locations of the line specified by @var{expression}, or of the
583 current line if no argument was given. This function returns a Python
584 tuple containing two elements. The first element contains a string
585 holding any unparsed section of @var{expression} (or @code{None} if
586 the expression has been fully parsed). The second element contains
587 either @code{None} or another tuple that contains all the locations
588 that match the expression represented as @code{gdb.Symtab_and_line}
589 objects (@pxref{Symbol Tables In Python}). If @var{expression} is
590 provided, it is decoded the way that @value{GDBN}'s inbuilt
591 @code{break} or @code{edit} commands do (@pxref{Location
595 @defun gdb.prompt_hook (current_prompt)
598 If @var{prompt_hook} is callable, @value{GDBN} will call the method
599 assigned to this operation before a prompt is displayed by
602 The parameter @code{current_prompt} contains the current @value{GDBN}
603 prompt. This method must return a Python string, or @code{None}. If
604 a string is returned, the @value{GDBN} prompt will be set to that
605 string. If @code{None} is returned, @value{GDBN} will continue to use
608 Some prompts cannot be substituted in @value{GDBN}. Secondary prompts
609 such as those used by readline for command input, and annotation
610 related prompts are prohibited from being changed.
613 @anchor{gdb_architecture_names}
614 @defun gdb.architecture_names ()
615 Return a list containing all of the architecture names that the
616 current build of @value{GDBN} supports. Each architecture name is a
617 string. The names returned in this list are the same names as are
618 returned from @code{gdb.Architecture.name}
619 (@pxref{gdbpy_architecture_name,,Architecture.name}).
622 @anchor{gdbpy_connections}
623 @defun gdb.connections
624 Return a list of @code{gdb.TargetConnection} objects, one for each
625 currently active connection (@pxref{Connections In Python}). The
626 connection objects are in no particular order in the returned list.
629 @defun gdb.format_address (address @r{[}, progspace, architecture@r{]})
630 Return a string in the format @samp{@var{addr}
631 <@var{symbol}+@var{offset}>}, where @var{addr} is @var{address}
632 formatted in hexadecimal, @var{symbol} is the symbol whose address is
633 the nearest to @var{address} and below it in memory, and @var{offset}
634 is the offset from @var{symbol} to @var{address} in decimal.
636 If no suitable @var{symbol} was found, then the
637 <@var{symbol}+@var{offset}> part is not included in the returned
638 string, instead the returned string will just contain the
639 @var{address} formatted as hexadecimal. How far @value{GDBN} looks
640 back for a suitable symbol can be controlled with @kbd{set print
641 max-symbolic-offset} (@pxref{Print Settings}).
643 Additionally, the returned string can include file name and line
644 number information when @kbd{set print symbol-filename on}
645 (@pxref{Print Settings}), in this case the format of the returned
646 string is @samp{@var{addr} <@var{symbol}+@var{offset}> at
647 @var{filename}:@var{line-number}}.
650 The @var{progspace} is the gdb.Progspace in which @var{symbol} is
651 looked up, and @var{architecture} is used when formatting @var{addr},
652 e.g.@: in order to determine the size of an address in bytes.
654 If neither @var{progspace} or @var{architecture} are passed, then by
655 default @value{GDBN} will use the program space and architecture of
656 the currently selected inferior, thus, the following two calls are
660 gdb.format_address(address)
661 gdb.format_address(address,
662 gdb.selected_inferior().progspace,
663 gdb.selected_inferior().architecture())
666 It is not valid to only pass one of @var{progspace} or
667 @var{architecture}, either they must both be provided, or neither must
668 be provided (and the defaults will be used).
670 This method uses the same mechanism for formatting address, symbol,
671 and offset information as core @value{GDBN} does in commands such as
674 Here are some examples of the possible string formats:
678 0x00001042 <symbol+16>
679 0x00001042 <symbol+16 at file.c:123>
683 @defun gdb.current_language ()
684 Return the name of the current language as a string. Unlike
685 @code{gdb.parameter('language')}, this function will never return
686 @samp{auto}. If a @code{gdb.Frame} object is available (@pxref{Frames
687 In Python}), the @code{language} method might be preferable in some
688 cases, as that is not affected by the user's language setting.
691 @node Exception Handling
692 @subsubsection Exception Handling
693 @cindex python exceptions
694 @cindex exceptions, python
696 When executing the @code{python} command, Python exceptions
697 uncaught within the Python code are translated to calls to
698 @value{GDBN} error-reporting mechanism. If the command that called
699 @code{python} does not handle the error, @value{GDBN} will
700 terminate it and print an error message containing the Python
701 exception name, the associated value, and the Python call stack
702 backtrace at the point where the exception was raised. Example:
705 (@value{GDBP}) python print foo
706 Traceback (most recent call last):
707 File "<string>", line 1, in <module>
708 NameError: name 'foo' is not defined
711 @value{GDBN} errors that happen in @value{GDBN} commands invoked by
712 Python code are converted to Python exceptions. The type of the
713 Python exception depends on the error.
717 This is the base class for most exceptions generated by @value{GDBN}.
718 It is derived from @code{RuntimeError}, for compatibility with earlier
719 versions of @value{GDBN}.
721 If an error occurring in @value{GDBN} does not fit into some more
722 specific category, then the generated exception will have this type.
724 @item gdb.MemoryError
725 This is a subclass of @code{gdb.error} which is thrown when an
726 operation tried to access invalid memory in the inferior.
728 @item KeyboardInterrupt
729 User interrupt (via @kbd{C-c} or by typing @kbd{q} at a pagination
730 prompt) is translated to a Python @code{KeyboardInterrupt} exception.
733 In all cases, your exception handler will see the @value{GDBN} error
734 message as its value and the Python call stack backtrace at the Python
735 statement closest to where the @value{GDBN} error occured as the
739 When implementing @value{GDBN} commands in Python via
740 @code{gdb.Command}, or functions via @code{gdb.Function}, it is useful
741 to be able to throw an exception that doesn't cause a traceback to be
742 printed. For example, the user may have invoked the command
743 incorrectly. @value{GDBN} provides a special exception class that can
744 be used for this purpose.
748 When thrown from a command or function, this exception will cause the
749 command or function to fail, but the Python stack will not be
750 displayed. @value{GDBN} does not throw this exception itself, but
751 rather recognizes it when thrown from user Python code. Example:
755 >class HelloWorld (gdb.Command):
756 > """Greet the whole world."""
757 > def __init__ (self):
758 > super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
759 > def invoke (self, args, from_tty):
760 > argv = gdb.string_to_argv (args)
761 > if len (argv) != 0:
762 > raise gdb.GdbError ("hello-world takes no arguments")
763 > print ("Hello, World!")
767 hello-world takes no arguments
771 @node Values From Inferior
772 @subsubsection Values From Inferior
773 @cindex values from inferior, with Python
774 @cindex python, working with values from inferior
776 @cindex @code{gdb.Value}
777 @value{GDBN} provides values it obtains from the inferior program in
778 an object of type @code{gdb.Value}. @value{GDBN} uses this object
779 for its internal bookkeeping of the inferior's values, and for
780 fetching values when necessary.
782 Inferior values that are simple scalars can be used directly in
783 Python expressions that are valid for the value's data type. Here's
784 an example for an integer or floating-point value @code{some_val}:
791 As result of this, @code{bar} will also be a @code{gdb.Value} object
792 whose values are of the same type as those of @code{some_val}. Valid
793 Python operations can also be performed on @code{gdb.Value} objects
794 representing a @code{struct} or @code{class} object. For such cases,
795 the overloaded operator (if present), is used to perform the operation.
796 For example, if @code{val1} and @code{val2} are @code{gdb.Value} objects
797 representing instances of a @code{class} which overloads the @code{+}
798 operator, then one can use the @code{+} operator in their Python script
806 The result of the operation @code{val3} is also a @code{gdb.Value}
807 object corresponding to the value returned by the overloaded @code{+}
808 operator. In general, overloaded operators are invoked for the
809 following operations: @code{+} (binary addition), @code{-} (binary
810 subtraction), @code{*} (multiplication), @code{/}, @code{%}, @code{<<},
811 @code{>>}, @code{|}, @code{&}, @code{^}.
813 Inferior values that are structures or instances of some class can
814 be accessed using the Python @dfn{dictionary syntax}. For example, if
815 @code{some_val} is a @code{gdb.Value} instance holding a structure, you
816 can access its @code{foo} element with:
819 bar = some_val['foo']
822 @cindex getting structure elements using gdb.Field objects as subscripts
823 Again, @code{bar} will also be a @code{gdb.Value} object. Structure
824 elements can also be accessed by using @code{gdb.Field} objects as
825 subscripts (@pxref{Types In Python}, for more information on
826 @code{gdb.Field} objects). For example, if @code{foo_field} is a
827 @code{gdb.Field} object corresponding to element @code{foo} of the above
828 structure, then @code{bar} can also be accessed as follows:
831 bar = some_val[foo_field]
834 A @code{gdb.Value} that represents a function can be executed via
835 inferior function call. Any arguments provided to the call must match
836 the function's prototype, and must be provided in the order specified
839 For example, @code{some_val} is a @code{gdb.Value} instance
840 representing a function that takes two integers as arguments. To
841 execute this function, call it like so:
844 result = some_val (10,20)
847 Any values returned from a function call will be stored as a
850 The following attributes are provided:
852 @defvar Value.address
853 If this object is addressable, this read-only attribute holds a
854 @code{gdb.Value} object representing the address. Otherwise,
855 this attribute holds @code{None}.
858 @cindex optimized out value in Python
859 @defvar Value.is_optimized_out
860 This read-only boolean attribute is true if the compiler optimized out
861 this value, thus it is not available for fetching from the inferior.
865 The type of this @code{gdb.Value}. The value of this attribute is a
866 @code{gdb.Type} object (@pxref{Types In Python}).
869 @defvar Value.dynamic_type
870 The dynamic type of this @code{gdb.Value}. This uses the object's
871 virtual table and the C@t{++} run-time type information
872 (@acronym{RTTI}) to determine the dynamic type of the value. If this
873 value is of class type, it will return the class in which the value is
874 embedded, if any. If this value is of pointer or reference to a class
875 type, it will compute the dynamic type of the referenced object, and
876 return a pointer or reference to that type, respectively. In all
877 other cases, it will return the value's static type.
879 Note that this feature will only work when debugging a C@t{++} program
880 that includes @acronym{RTTI} for the object in question. Otherwise,
881 it will just return the static type of the value as in @kbd{ptype foo}
882 (@pxref{Symbols, ptype}).
885 @defvar Value.is_lazy
886 The value of this read-only boolean attribute is @code{True} if this
887 @code{gdb.Value} has not yet been fetched from the inferior.
888 @value{GDBN} does not fetch values until necessary, for efficiency.
892 myval = gdb.parse_and_eval ('somevar')
895 The value of @code{somevar} is not fetched at this time. It will be
896 fetched when the value is needed, or when the @code{fetch_lazy}
900 The following methods are provided:
902 @defun Value.__init__ (val)
903 Many Python values can be converted directly to a @code{gdb.Value} via
904 this object initializer. Specifically:
908 A Python boolean is converted to the boolean type from the current
912 A Python integer is converted to the C @code{long} type for the
913 current architecture.
916 A Python long is converted to the C @code{long long} type for the
917 current architecture.
920 A Python float is converted to the C @code{double} type for the
921 current architecture.
924 A Python string is converted to a target string in the current target
925 language using the current target encoding.
926 If a character cannot be represented in the current target encoding,
927 then an exception is thrown.
929 @item @code{gdb.Value}
930 If @code{val} is a @code{gdb.Value}, then a copy of the value is made.
932 @item @code{gdb.LazyString}
933 If @code{val} is a @code{gdb.LazyString} (@pxref{Lazy Strings In
934 Python}), then the lazy string's @code{value} method is called, and
939 @defun Value.__init__ (val, type)
940 This second form of the @code{gdb.Value} constructor returns a
941 @code{gdb.Value} of type @var{type} where the value contents are taken
942 from the Python buffer object specified by @var{val}. The number of
943 bytes in the Python buffer object must be greater than or equal to the
946 If @var{type} is @code{None} then this version of @code{__init__}
947 behaves as though @var{type} was not passed at all.
950 @defun Value.cast (type)
951 Return a new instance of @code{gdb.Value} that is the result of
952 casting this instance to the type described by @var{type}, which must
953 be a @code{gdb.Type} object. If the cast cannot be performed for some
954 reason, this method throws an exception.
957 @defun Value.dereference ()
958 For pointer data types, this method returns a new @code{gdb.Value} object
959 whose contents is the object pointed to by the pointer. For example, if
960 @code{foo} is a C pointer to an @code{int}, declared in your C program as
967 then you can use the corresponding @code{gdb.Value} to access what
968 @code{foo} points to like this:
971 bar = foo.dereference ()
974 The result @code{bar} will be a @code{gdb.Value} object holding the
975 value pointed to by @code{foo}.
977 A similar function @code{Value.referenced_value} exists which also
978 returns @code{gdb.Value} objects corresponding to the values pointed to
979 by pointer values (and additionally, values referenced by reference
980 values). However, the behavior of @code{Value.dereference}
981 differs from @code{Value.referenced_value} by the fact that the
982 behavior of @code{Value.dereference} is identical to applying the C
983 unary operator @code{*} on a given value. For example, consider a
984 reference to a pointer @code{ptrref}, declared in your C@t{++} program
992 intptr &ptrref = ptr;
995 Though @code{ptrref} is a reference value, one can apply the method
996 @code{Value.dereference} to the @code{gdb.Value} object corresponding
997 to it and obtain a @code{gdb.Value} which is identical to that
998 corresponding to @code{val}. However, if you apply the method
999 @code{Value.referenced_value}, the result would be a @code{gdb.Value}
1000 object identical to that corresponding to @code{ptr}.
1003 py_ptrref = gdb.parse_and_eval ("ptrref")
1004 py_val = py_ptrref.dereference ()
1005 py_ptr = py_ptrref.referenced_value ()
1008 The @code{gdb.Value} object @code{py_val} is identical to that
1009 corresponding to @code{val}, and @code{py_ptr} is identical to that
1010 corresponding to @code{ptr}. In general, @code{Value.dereference} can
1011 be applied whenever the C unary operator @code{*} can be applied
1012 to the corresponding C value. For those cases where applying both
1013 @code{Value.dereference} and @code{Value.referenced_value} is allowed,
1014 the results obtained need not be identical (as we have seen in the above
1015 example). The results are however identical when applied on
1016 @code{gdb.Value} objects corresponding to pointers (@code{gdb.Value}
1017 objects with type code @code{TYPE_CODE_PTR}) in a C/C@t{++} program.
1020 @defun Value.referenced_value ()
1021 For pointer or reference data types, this method returns a new
1022 @code{gdb.Value} object corresponding to the value referenced by the
1023 pointer/reference value. For pointer data types,
1024 @code{Value.dereference} and @code{Value.referenced_value} produce
1025 identical results. The difference between these methods is that
1026 @code{Value.dereference} cannot get the values referenced by reference
1027 values. For example, consider a reference to an @code{int}, declared
1028 in your C@t{++} program as
1036 then applying @code{Value.dereference} to the @code{gdb.Value} object
1037 corresponding to @code{ref} will result in an error, while applying
1038 @code{Value.referenced_value} will result in a @code{gdb.Value} object
1039 identical to that corresponding to @code{val}.
1042 py_ref = gdb.parse_and_eval ("ref")
1043 er_ref = py_ref.dereference () # Results in error
1044 py_val = py_ref.referenced_value () # Returns the referenced value
1047 The @code{gdb.Value} object @code{py_val} is identical to that
1048 corresponding to @code{val}.
1051 @defun Value.reference_value ()
1052 Return a @code{gdb.Value} object which is a reference to the value
1053 encapsulated by this instance.
1056 @defun Value.const_value ()
1057 Return a @code{gdb.Value} object which is a @code{const} version of the
1058 value encapsulated by this instance.
1061 @defun Value.dynamic_cast (type)
1062 Like @code{Value.cast}, but works as if the C@t{++} @code{dynamic_cast}
1063 operator were used. Consult a C@t{++} reference for details.
1066 @defun Value.reinterpret_cast (type)
1067 Like @code{Value.cast}, but works as if the C@t{++} @code{reinterpret_cast}
1068 operator were used. Consult a C@t{++} reference for details.
1071 @defun Value.format_string (...)
1072 Convert a @code{gdb.Value} to a string, similarly to what the @code{print}
1073 command does. Invoked with no arguments, this is equivalent to calling
1074 the @code{str} function on the @code{gdb.Value}. The representation of
1075 the same value may change across different versions of @value{GDBN}, so
1076 you shouldn't, for instance, parse the strings returned by this method.
1078 All the arguments are keyword only. If an argument is not specified, the
1079 current global default setting is used.
1083 @code{True} if pretty-printers (@pxref{Pretty Printing}) should not be
1084 used to format the value. @code{False} if enabled pretty-printers
1085 matching the type represented by the @code{gdb.Value} should be used to
1089 @code{True} if arrays should be pretty printed to be more convenient to
1090 read, @code{False} if they shouldn't (see @code{set print array} in
1091 @ref{Print Settings}).
1093 @item pretty_structs
1094 @code{True} if structs should be pretty printed to be more convenient to
1095 read, @code{False} if they shouldn't (see @code{set print pretty} in
1096 @ref{Print Settings}).
1099 @code{True} if array indexes should be included in the string
1100 representation of arrays, @code{False} if they shouldn't (see @code{set
1101 print array-indexes} in @ref{Print Settings}).
1104 @code{True} if the string representation of a pointer should include the
1105 corresponding symbol name (if one exists), @code{False} if it shouldn't
1106 (see @code{set print symbol} in @ref{Print Settings}).
1109 @code{True} if unions which are contained in other structures or unions
1110 should be expanded, @code{False} if they shouldn't (see @code{set print
1111 union} in @ref{Print Settings}).
1114 @code{True} if the string representation of a pointer should include the
1115 address, @code{False} if it shouldn't (see @code{set print address} in
1116 @ref{Print Settings}).
1119 @code{True} if binary values should be displayed in groups of four bits,
1120 known as nibbles. @code{False} if it shouldn't (@pxref{Print Settings,
1121 set print nibbles}).
1124 @code{True} if C@t{++} references should be resolved to the value they
1125 refer to, @code{False} (the default) if they shouldn't. Note that, unlike
1126 for the @code{print} command, references are not automatically expanded
1127 when using the @code{format_string} method or the @code{str}
1128 function. There is no global @code{print} setting to change the default
1131 @item actual_objects
1132 @code{True} if the representation of a pointer to an object should
1133 identify the @emph{actual} (derived) type of the object rather than the
1134 @emph{declared} type, using the virtual function table. @code{False} if
1135 the @emph{declared} type should be used. (See @code{set print object} in
1136 @ref{Print Settings}).
1138 @item static_members
1139 @code{True} if static members should be included in the string
1140 representation of a C@t{++} object, @code{False} if they shouldn't (see
1141 @code{set print static-members} in @ref{Print Settings}).
1143 @item max_characters
1144 Number of string characters to print, @code{0} to follow
1145 @code{max_elements}, or @code{UINT_MAX} to print an unlimited number
1146 of characters (see @code{set print characters} in @ref{Print Settings}).
1149 Number of array elements to print, or @code{0} to print an unlimited
1150 number of elements (see @code{set print elements} in @ref{Print
1154 The maximum depth to print for nested structs and unions, or @code{-1}
1155 to print an unlimited number of elements (see @code{set print
1156 max-depth} in @ref{Print Settings}).
1158 @item repeat_threshold
1159 Set the threshold for suppressing display of repeated array elements, or
1160 @code{0} to represent all elements, even if repeated. (See @code{set
1161 print repeats} in @ref{Print Settings}).
1164 A string containing a single character representing the format to use for
1165 the returned string. For instance, @code{'x'} is equivalent to using the
1166 @value{GDBN} command @code{print} with the @code{/x} option and formats
1167 the value as a hexadecimal number.
1170 @code{True} if @value{GDBN} should apply styling to the returned
1171 string. When styling is applied, the returned string might contain
1172 ANSI terminal escape sequences. Escape sequences will only be
1173 included if styling is turned on, see @ref{Output Styling}.
1174 Additionally, @value{GDBN} only styles some value contents, so not
1175 every output string will contain escape sequences.
1177 When @code{False}, which is the default, no output styling is applied.
1180 @code{True} when just a summary should be printed. In this mode,
1181 scalar values are printed in their entirety, but aggregates such as
1182 structures or unions are omitted. This mode is used by @code{set
1183 print frame-arguments scalars} (@pxref{Print Settings}).
1187 @defun Value.string (@r{[}encoding@r{[}, errors@r{[}, length@r{]]]})
1188 If this @code{gdb.Value} represents a string, then this method
1189 converts the contents to a Python string. Otherwise, this method will
1192 Values are interpreted as strings according to the rules of the
1193 current language. If the optional length argument is given, the
1194 string will be converted to that length, and will include any embedded
1195 zeroes that the string may contain. Otherwise, for languages
1196 where the string is zero-terminated, the entire string will be
1199 For example, in C-like languages, a value is a string if it is a pointer
1200 to or an array of characters or ints of type @code{wchar_t}, @code{char16_t},
1203 If the optional @var{encoding} argument is given, it must be a string
1204 naming the encoding of the string in the @code{gdb.Value}, such as
1205 @code{"ascii"}, @code{"iso-8859-6"} or @code{"utf-8"}. It accepts
1206 the same encodings as the corresponding argument to Python's
1207 @code{string.decode} method, and the Python codec machinery will be used
1208 to convert the string. If @var{encoding} is not given, or if
1209 @var{encoding} is the empty string, then either the @code{target-charset}
1210 (@pxref{Character Sets}) will be used, or a language-specific encoding
1211 will be used, if the current language is able to supply one.
1213 The optional @var{errors} argument is the same as the corresponding
1214 argument to Python's @code{string.decode} method.
1216 If the optional @var{length} argument is given, the string will be
1217 fetched and converted to the given length.
1220 @defun Value.lazy_string (@r{[}encoding @r{[}, length@r{]]})
1221 If this @code{gdb.Value} represents a string, then this method
1222 converts the contents to a @code{gdb.LazyString} (@pxref{Lazy Strings
1223 In Python}). Otherwise, this method will throw an exception.
1225 If the optional @var{encoding} argument is given, it must be a string
1226 naming the encoding of the @code{gdb.LazyString}. Some examples are:
1227 @samp{ascii}, @samp{iso-8859-6} or @samp{utf-8}. If the
1228 @var{encoding} argument is an encoding that @value{GDBN} does
1229 recognize, @value{GDBN} will raise an error.
1231 When a lazy string is printed, the @value{GDBN} encoding machinery is
1232 used to convert the string during printing. If the optional
1233 @var{encoding} argument is not provided, or is an empty string,
1234 @value{GDBN} will automatically select the encoding most suitable for
1235 the string type. For further information on encoding in @value{GDBN}
1236 please see @ref{Character Sets}.
1238 If the optional @var{length} argument is given, the string will be
1239 fetched and encoded to the length of characters specified. If
1240 the @var{length} argument is not provided, the string will be fetched
1241 and encoded until a null of appropriate width is found.
1244 @defun Value.fetch_lazy ()
1245 If the @code{gdb.Value} object is currently a lazy value
1246 (@code{gdb.Value.is_lazy} is @code{True}), then the value is
1247 fetched from the inferior. Any errors that occur in the process
1248 will produce a Python exception.
1250 If the @code{gdb.Value} object is not a lazy value, this method
1253 This method does not return a value.
1257 @node Types In Python
1258 @subsubsection Types In Python
1259 @cindex types in Python
1260 @cindex Python, working with types
1263 @value{GDBN} represents types from the inferior using the class
1266 The following type-related functions are available in the @code{gdb}
1269 @findex gdb.lookup_type
1270 @defun gdb.lookup_type (name @r{[}, block@r{]})
1271 This function looks up a type by its @var{name}, which must be a string.
1273 If @var{block} is given, then @var{name} is looked up in that scope.
1274 Otherwise, it is searched for globally.
1276 Ordinarily, this function will return an instance of @code{gdb.Type}.
1277 If the named type cannot be found, it will throw an exception.
1280 Integer types can be found without looking them up by name.
1281 @xref{Architectures In Python}, for the @code{integer_type} method.
1283 If the type is a structure or class type, or an enum type, the fields
1284 of that type can be accessed using the Python @dfn{dictionary syntax}.
1285 For example, if @code{some_type} is a @code{gdb.Type} instance holding
1286 a structure type, you can access its @code{foo} field with:
1289 bar = some_type['foo']
1292 @code{bar} will be a @code{gdb.Field} object; see below under the
1293 description of the @code{Type.fields} method for a description of the
1294 @code{gdb.Field} class.
1296 An instance of @code{Type} has the following attributes:
1298 @defvar Type.alignof
1299 The alignment of this type, in bytes. Type alignment comes from the
1300 debugging information; if it was not specified, then @value{GDBN} will
1301 use the relevant ABI to try to determine the alignment. In some
1302 cases, even this is not possible, and zero will be returned.
1306 The type code for this type. The type code will be one of the
1307 @code{TYPE_CODE_} constants defined below.
1310 @defvar Type.dynamic
1311 A boolean indicating whether this type is dynamic. In some
1312 situations, such as Rust @code{enum} types or Ada variant records, the
1313 concrete type of a value may vary depending on its contents. That is,
1314 the declared type of a variable, or the type returned by
1315 @code{gdb.lookup_type} may be dynamic; while the type of the
1316 variable's value will be a concrete instance of that dynamic type.
1318 For example, consider this code:
1324 Here, at least conceptually (whether your compiler actually does this
1325 is a separate issue), examining @w{@code{gdb.lookup_symbol("array", ...).type}}
1326 could yield a @code{gdb.Type} which reports a size of @code{None}.
1327 This is the dynamic type.
1329 However, examining @code{gdb.parse_and_eval("array").type} would yield
1330 a concrete type, whose length would be known.
1334 The name of this type. If this type has no name, then @code{None}
1339 The size of this type, in target @code{char} units. Usually, a
1340 target's @code{char} type will be an 8-bit byte. However, on some
1341 unusual platforms, this type may have a different size. A dynamic
1342 type may not have a fixed size; in this case, this attribute's value
1343 will be @code{None}.
1347 The tag name for this type. The tag name is the name after
1348 @code{struct}, @code{union}, or @code{enum} in C and C@t{++}; not all
1349 languages have this concept. If this type has no tag name, then
1350 @code{None} is returned.
1353 @defvar Type.objfile
1354 The @code{gdb.Objfile} that this type was defined in, or @code{None} if
1355 there is no associated objfile.
1358 @defvar Type.is_scalar
1359 This property is @code{True} if the type is a scalar type, otherwise,
1360 this property is @code{False}. Examples of non-scalar types include
1361 structures, unions, and classes.
1364 @defvar Type.is_signed
1365 For scalar types (those for which @code{Type.is_scalar} is
1366 @code{True}), this property is @code{True} if the type is signed,
1367 otherwise this property is @code{False}.
1369 Attempting to read this property for a non-scalar type (a type for
1370 which @code{Type.is_scalar} is @code{False}), will raise a
1374 The following methods are provided:
1376 @defun Type.fields ()
1378 Return the fields of this type. The behavior depends on the type code:
1383 For structure and union types, this method returns the fields.
1386 Range types have two fields, the minimum and maximum values.
1389 Enum types have one field per enum constant.
1392 Function and method types have one field per parameter. The base types of
1393 C@t{++} classes are also represented as fields.
1396 Array types have one field representing the array's range.
1399 If the type does not fit into one of these categories, a @code{TypeError}
1404 Each field is a @code{gdb.Field} object, with some pre-defined attributes:
1407 This attribute is not available for @code{enum} or @code{static}
1408 (as in C@t{++}) fields. The value is the position, counting
1409 in bits, from the start of the containing type. Note that, in a
1410 dynamic type, the position of a field may not be constant. In this
1411 case, the value will be @code{None}. Also, a dynamic type may have
1412 fields that do not appear in a corresponding concrete type.
1415 This attribute is only available for @code{enum} fields, and its value
1416 is the enumeration member's integer representation.
1419 The name of the field, or @code{None} for anonymous fields.
1422 This is @code{True} if the field is artificial, usually meaning that
1423 it was provided by the compiler and not the user. This attribute is
1424 always provided, and is @code{False} if the field is not artificial.
1427 This is @code{True} if the field represents a base class of a C@t{++}
1428 structure. This attribute is always provided, and is @code{False}
1429 if the field is not a base class of the type that is the argument of
1430 @code{fields}, or if that type was not a C@t{++} class.
1433 If the field is packed, or is a bitfield, then this will have a
1434 non-zero value, which is the size of the field in bits. Otherwise,
1435 this will be zero; in this case the field's size is given by its type.
1438 The type of the field. This is usually an instance of @code{Type},
1439 but it can be @code{None} in some situations.
1442 The type which contains this field. This is an instance of
1447 @defun Type.array (n1 @r{[}, n2@r{]})
1448 Return a new @code{gdb.Type} object which represents an array of this
1449 type. If one argument is given, it is the inclusive upper bound of
1450 the array; in this case the lower bound is zero. If two arguments are
1451 given, the first argument is the lower bound of the array, and the
1452 second argument is the upper bound of the array. An array's length
1453 must not be negative, but the bounds can be.
1456 @defun Type.vector (n1 @r{[}, n2@r{]})
1457 Return a new @code{gdb.Type} object which represents a vector of this
1458 type. If one argument is given, it is the inclusive upper bound of
1459 the vector; in this case the lower bound is zero. If two arguments are
1460 given, the first argument is the lower bound of the vector, and the
1461 second argument is the upper bound of the vector. A vector's length
1462 must not be negative, but the bounds can be.
1464 The difference between an @code{array} and a @code{vector} is that
1465 arrays behave like in C: when used in expressions they decay to a pointer
1466 to the first element whereas vectors are treated as first class values.
1469 @defun Type.const ()
1470 Return a new @code{gdb.Type} object which represents a
1471 @code{const}-qualified variant of this type.
1474 @defun Type.volatile ()
1475 Return a new @code{gdb.Type} object which represents a
1476 @code{volatile}-qualified variant of this type.
1479 @defun Type.unqualified ()
1480 Return a new @code{gdb.Type} object which represents an unqualified
1481 variant of this type. That is, the result is neither @code{const} nor
1485 @defun Type.range ()
1486 Return a Python @code{Tuple} object that contains two elements: the
1487 low bound of the argument type and the high bound of that type. If
1488 the type does not have a range, @value{GDBN} will raise a
1489 @code{gdb.error} exception (@pxref{Exception Handling}).
1492 @defun Type.reference ()
1493 Return a new @code{gdb.Type} object which represents a reference to this
1497 @defun Type.pointer ()
1498 Return a new @code{gdb.Type} object which represents a pointer to this
1502 @defun Type.strip_typedefs ()
1503 Return a new @code{gdb.Type} that represents the real type,
1504 after removing all layers of typedefs.
1507 @defun Type.target ()
1508 Return a new @code{gdb.Type} object which represents the target type
1511 For a pointer type, the target type is the type of the pointed-to
1512 object. For an array type (meaning C-like arrays), the target type is
1513 the type of the elements of the array. For a function or method type,
1514 the target type is the type of the return value. For a complex type,
1515 the target type is the type of the elements. For a typedef, the
1516 target type is the aliased type.
1518 If the type does not have a target, this method will throw an
1522 @defun Type.template_argument (n @r{[}, block@r{]})
1523 If this @code{gdb.Type} is an instantiation of a template, this will
1524 return a new @code{gdb.Value} or @code{gdb.Type} which represents the
1525 value of the @var{n}th template argument (indexed starting at 0).
1527 If this @code{gdb.Type} is not a template type, or if the type has fewer
1528 than @var{n} template arguments, this will throw an exception.
1529 Ordinarily, only C@t{++} code will have template types.
1531 If @var{block} is given, then @var{name} is looked up in that scope.
1532 Otherwise, it is searched for globally.
1535 @defun Type.optimized_out ()
1536 Return @code{gdb.Value} instance of this type whose value is optimized
1537 out. This allows a frame decorator to indicate that the value of an
1538 argument or a local variable is not known.
1541 Each type has a code, which indicates what category this type falls
1542 into. The available type categories are represented by constants
1543 defined in the @code{gdb} module:
1546 @vindex TYPE_CODE_PTR
1547 @item gdb.TYPE_CODE_PTR
1548 The type is a pointer.
1550 @vindex TYPE_CODE_ARRAY
1551 @item gdb.TYPE_CODE_ARRAY
1552 The type is an array.
1554 @vindex TYPE_CODE_STRUCT
1555 @item gdb.TYPE_CODE_STRUCT
1556 The type is a structure.
1558 @vindex TYPE_CODE_UNION
1559 @item gdb.TYPE_CODE_UNION
1560 The type is a union.
1562 @vindex TYPE_CODE_ENUM
1563 @item gdb.TYPE_CODE_ENUM
1564 The type is an enum.
1566 @vindex TYPE_CODE_FLAGS
1567 @item gdb.TYPE_CODE_FLAGS
1568 A bit flags type, used for things such as status registers.
1570 @vindex TYPE_CODE_FUNC
1571 @item gdb.TYPE_CODE_FUNC
1572 The type is a function.
1574 @vindex TYPE_CODE_INT
1575 @item gdb.TYPE_CODE_INT
1576 The type is an integer type.
1578 @vindex TYPE_CODE_FLT
1579 @item gdb.TYPE_CODE_FLT
1580 A floating point type.
1582 @vindex TYPE_CODE_VOID
1583 @item gdb.TYPE_CODE_VOID
1584 The special type @code{void}.
1586 @vindex TYPE_CODE_SET
1587 @item gdb.TYPE_CODE_SET
1590 @vindex TYPE_CODE_RANGE
1591 @item gdb.TYPE_CODE_RANGE
1592 A range type, that is, an integer type with bounds.
1594 @vindex TYPE_CODE_STRING
1595 @item gdb.TYPE_CODE_STRING
1596 A string type. Note that this is only used for certain languages with
1597 language-defined string types; C strings are not represented this way.
1599 @vindex TYPE_CODE_BITSTRING
1600 @item gdb.TYPE_CODE_BITSTRING
1601 A string of bits. It is deprecated.
1603 @vindex TYPE_CODE_ERROR
1604 @item gdb.TYPE_CODE_ERROR
1605 An unknown or erroneous type.
1607 @vindex TYPE_CODE_METHOD
1608 @item gdb.TYPE_CODE_METHOD
1609 A method type, as found in C@t{++}.
1611 @vindex TYPE_CODE_METHODPTR
1612 @item gdb.TYPE_CODE_METHODPTR
1613 A pointer-to-member-function.
1615 @vindex TYPE_CODE_MEMBERPTR
1616 @item gdb.TYPE_CODE_MEMBERPTR
1617 A pointer-to-member.
1619 @vindex TYPE_CODE_REF
1620 @item gdb.TYPE_CODE_REF
1623 @vindex TYPE_CODE_RVALUE_REF
1624 @item gdb.TYPE_CODE_RVALUE_REF
1625 A C@t{++}11 rvalue reference type.
1627 @vindex TYPE_CODE_CHAR
1628 @item gdb.TYPE_CODE_CHAR
1631 @vindex TYPE_CODE_BOOL
1632 @item gdb.TYPE_CODE_BOOL
1635 @vindex TYPE_CODE_COMPLEX
1636 @item gdb.TYPE_CODE_COMPLEX
1637 A complex float type.
1639 @vindex TYPE_CODE_TYPEDEF
1640 @item gdb.TYPE_CODE_TYPEDEF
1641 A typedef to some other type.
1643 @vindex TYPE_CODE_NAMESPACE
1644 @item gdb.TYPE_CODE_NAMESPACE
1645 A C@t{++} namespace.
1647 @vindex TYPE_CODE_DECFLOAT
1648 @item gdb.TYPE_CODE_DECFLOAT
1649 A decimal floating point type.
1651 @vindex TYPE_CODE_INTERNAL_FUNCTION
1652 @item gdb.TYPE_CODE_INTERNAL_FUNCTION
1653 A function internal to @value{GDBN}. This is the type used to represent
1654 convenience functions.
1656 @vindex TYPE_CODE_XMETHOD
1657 @item gdb.TYPE_CODE_XMETHOD
1658 A method internal to @value{GDBN}. This is the type used to represent
1659 xmethods (@pxref{Writing an Xmethod}).
1661 @vindex TYPE_CODE_FIXED_POINT
1662 @item gdb.TYPE_CODE_FIXED_POINT
1663 A fixed-point number.
1665 @vindex TYPE_CODE_NAMESPACE
1666 @item gdb.TYPE_CODE_NAMESPACE
1670 Further support for types is provided in the @code{gdb.types}
1671 Python module (@pxref{gdb.types}).
1673 @node Pretty Printing API
1674 @subsubsection Pretty Printing API
1675 @cindex python pretty printing api
1677 A pretty-printer is just an object that holds a value and implements a
1678 specific interface, defined here. An example output is provided
1679 (@pxref{Pretty Printing}).
1681 @defun pretty_printer.children (self)
1682 @value{GDBN} will call this method on a pretty-printer to compute the
1683 children of the pretty-printer's value.
1685 This method must return an object conforming to the Python iterator
1686 protocol. Each item returned by the iterator must be a tuple holding
1687 two elements. The first element is the ``name'' of the child; the
1688 second element is the child's value. The value can be any Python
1689 object which is convertible to a @value{GDBN} value.
1691 This method is optional. If it does not exist, @value{GDBN} will act
1692 as though the value has no children.
1694 For efficiency, the @code{children} method should lazily compute its
1695 results. This will let @value{GDBN} read as few elements as
1696 necessary, for example when various print settings (@pxref{Print
1697 Settings}) or @code{-var-list-children} (@pxref{GDB/MI Variable
1698 Objects}) limit the number of elements to be displayed.
1700 Children may be hidden from display based on the value of @samp{set
1701 print max-depth} (@pxref{Print Settings}).
1704 @defun pretty_printer.display_hint (self)
1705 The CLI may call this method and use its result to change the
1706 formatting of a value. The result will also be supplied to an MI
1707 consumer as a @samp{displayhint} attribute of the variable being
1710 This method is optional. If it does exist, this method must return a
1711 string or the special value @code{None}.
1713 Some display hints are predefined by @value{GDBN}:
1717 Indicate that the object being printed is ``array-like''. The CLI
1718 uses this to respect parameters such as @code{set print elements} and
1719 @code{set print array}.
1722 Indicate that the object being printed is ``map-like'', and that the
1723 children of this value can be assumed to alternate between keys and
1727 Indicate that the object being printed is ``string-like''. If the
1728 printer's @code{to_string} method returns a Python string of some
1729 kind, then @value{GDBN} will call its internal language-specific
1730 string-printing function to format the string. For the CLI this means
1731 adding quotation marks, possibly escaping some characters, respecting
1732 @code{set print elements}, and the like.
1735 The special value @code{None} causes @value{GDBN} to apply the default
1739 @defun pretty_printer.to_string (self)
1740 @value{GDBN} will call this method to display the string
1741 representation of the value passed to the object's constructor.
1743 When printing from the CLI, if the @code{to_string} method exists,
1744 then @value{GDBN} will prepend its result to the values returned by
1745 @code{children}. Exactly how this formatting is done is dependent on
1746 the display hint, and may change as more hints are added. Also,
1747 depending on the print settings (@pxref{Print Settings}), the CLI may
1748 print just the result of @code{to_string} in a stack trace, omitting
1749 the result of @code{children}.
1751 If this method returns a string, it is printed verbatim.
1753 Otherwise, if this method returns an instance of @code{gdb.Value},
1754 then @value{GDBN} prints this value. This may result in a call to
1755 another pretty-printer.
1757 If instead the method returns a Python value which is convertible to a
1758 @code{gdb.Value}, then @value{GDBN} performs the conversion and prints
1759 the resulting value. Again, this may result in a call to another
1760 pretty-printer. Python scalars (integers, floats, and booleans) and
1761 strings are convertible to @code{gdb.Value}; other types are not.
1763 Finally, if this method returns @code{None} then no further operations
1764 are peformed in this method and nothing is printed.
1766 If the result is not one of these types, an exception is raised.
1769 @value{GDBN} provides a function which can be used to look up the
1770 default pretty-printer for a @code{gdb.Value}:
1772 @findex gdb.default_visualizer
1773 @defun gdb.default_visualizer (value)
1774 This function takes a @code{gdb.Value} object as an argument. If a
1775 pretty-printer for this value exists, then it is returned. If no such
1776 printer exists, then this returns @code{None}.
1779 Normally, a pretty-printer can respect the user's print settings
1780 (including temporarily applied settings, such as @samp{/x}) simply by
1781 calling @code{Value.format_string} (@pxref{Values From Inferior}).
1782 However, these settings can also be queried directly:
1784 @findex gdb.print_options
1785 @defun gdb.print_options ()
1786 Return a dictionary whose keys are the valid keywords that can be
1787 given to @code{Value.format_string}, and whose values are the user's
1788 settings. During a @code{print} or other operation, the values will
1789 reflect any flags that are temporarily in effect.
1792 (gdb) python print (gdb.print_options ()['max_elements'])
1797 @node Selecting Pretty-Printers
1798 @subsubsection Selecting Pretty-Printers
1799 @cindex selecting python pretty-printers
1801 @value{GDBN} provides several ways to register a pretty-printer:
1802 globally, per program space, and per objfile. When choosing how to
1803 register your pretty-printer, a good rule is to register it with the
1804 smallest scope possible: that is prefer a specific objfile first, then
1805 a program space, and only register a printer globally as a last
1808 @findex gdb.pretty_printers
1809 @defvar gdb.pretty_printers
1810 The Python list @code{gdb.pretty_printers} contains an array of
1811 functions or callable objects that have been registered via addition
1812 as a pretty-printer. Printers in this list are called @code{global}
1813 printers, they're available when debugging all inferiors.
1816 Each @code{gdb.Progspace} contains a @code{pretty_printers} attribute.
1817 Each @code{gdb.Objfile} also contains a @code{pretty_printers}
1820 Each function on these lists is passed a single @code{gdb.Value}
1821 argument and should return a pretty-printer object conforming to the
1822 interface definition above (@pxref{Pretty Printing API}). If a function
1823 cannot create a pretty-printer for the value, it should return
1826 @value{GDBN} first checks the @code{pretty_printers} attribute of each
1827 @code{gdb.Objfile} in the current program space and iteratively calls
1828 each enabled lookup routine in the list for that @code{gdb.Objfile}
1829 until it receives a pretty-printer object.
1830 If no pretty-printer is found in the objfile lists, @value{GDBN} then
1831 searches the pretty-printer list of the current program space,
1832 calling each enabled function until an object is returned.
1833 After these lists have been exhausted, it tries the global
1834 @code{gdb.pretty_printers} list, again calling each enabled function until an
1837 The order in which the objfiles are searched is not specified. For a
1838 given list, functions are always invoked from the head of the list,
1839 and iterated over sequentially until the end of the list, or a printer
1842 For various reasons a pretty-printer may not work.
1843 For example, the underlying data structure may have changed and
1844 the pretty-printer is out of date.
1846 The consequences of a broken pretty-printer are severe enough that
1847 @value{GDBN} provides support for enabling and disabling individual
1848 printers. For example, if @code{print frame-arguments} is on,
1849 a backtrace can become highly illegible if any argument is printed
1850 with a broken printer.
1852 Pretty-printers are enabled and disabled by attaching an @code{enabled}
1853 attribute to the registered function or callable object. If this attribute
1854 is present and its value is @code{False}, the printer is disabled, otherwise
1855 the printer is enabled.
1857 @node Writing a Pretty-Printer
1858 @subsubsection Writing a Pretty-Printer
1859 @cindex writing a pretty-printer
1861 A pretty-printer consists of two parts: a lookup function to detect
1862 if the type is supported, and the printer itself.
1864 Here is an example showing how a @code{std::string} printer might be
1865 written. @xref{Pretty Printing API}, for details on the API this class
1869 class StdStringPrinter(object):
1870 "Print a std::string"
1872 def __init__(self, val):
1875 def to_string(self):
1876 return self.val['_M_dataplus']['_M_p']
1878 def display_hint(self):
1882 And here is an example showing how a lookup function for the printer
1883 example above might be written.
1886 def str_lookup_function(val):
1887 lookup_tag = val.type.tag
1888 if lookup_tag is None:
1890 regex = re.compile("^std::basic_string<char,.*>$")
1891 if regex.match(lookup_tag):
1892 return StdStringPrinter(val)
1896 The example lookup function extracts the value's type, and attempts to
1897 match it to a type that it can pretty-print. If it is a type the
1898 printer can pretty-print, it will return a printer object. If not, it
1899 returns @code{None}.
1901 We recommend that you put your core pretty-printers into a Python
1902 package. If your pretty-printers are for use with a library, we
1903 further recommend embedding a version number into the package name.
1904 This practice will enable @value{GDBN} to load multiple versions of
1905 your pretty-printers at the same time, because they will have
1908 You should write auto-loaded code (@pxref{Python Auto-loading}) such that it
1909 can be evaluated multiple times without changing its meaning. An
1910 ideal auto-load file will consist solely of @code{import}s of your
1911 printer modules, followed by a call to a register pretty-printers with
1912 the current objfile.
1914 Taken as a whole, this approach will scale nicely to multiple
1915 inferiors, each potentially using a different library version.
1916 Embedding a version number in the Python package name will ensure that
1917 @value{GDBN} is able to load both sets of printers simultaneously.
1918 Then, because the search for pretty-printers is done by objfile, and
1919 because your auto-loaded code took care to register your library's
1920 printers with a specific objfile, @value{GDBN} will find the correct
1921 printers for the specific version of the library used by each
1924 To continue the @code{std::string} example (@pxref{Pretty Printing API}),
1925 this code might appear in @code{gdb.libstdcxx.v6}:
1928 def register_printers(objfile):
1929 objfile.pretty_printers.append(str_lookup_function)
1933 And then the corresponding contents of the auto-load file would be:
1936 import gdb.libstdcxx.v6
1937 gdb.libstdcxx.v6.register_printers(gdb.current_objfile())
1940 The previous example illustrates a basic pretty-printer.
1941 There are a few things that can be improved on.
1942 The printer doesn't have a name, making it hard to identify in a
1943 list of installed printers. The lookup function has a name, but
1944 lookup functions can have arbitrary, even identical, names.
1946 Second, the printer only handles one type, whereas a library typically has
1947 several types. One could install a lookup function for each desired type
1948 in the library, but one could also have a single lookup function recognize
1949 several types. The latter is the conventional way this is handled.
1950 If a pretty-printer can handle multiple data types, then its
1951 @dfn{subprinters} are the printers for the individual data types.
1953 The @code{gdb.printing} module provides a formal way of solving these
1954 problems (@pxref{gdb.printing}).
1955 Here is another example that handles multiple types.
1957 These are the types we are going to pretty-print:
1960 struct foo @{ int a, b; @};
1961 struct bar @{ struct foo x, y; @};
1964 Here are the printers:
1968 """Print a foo object."""
1970 def __init__(self, val):
1973 def to_string(self):
1974 return ("a=<" + str(self.val["a"]) +
1975 "> b=<" + str(self.val["b"]) + ">")
1978 """Print a bar object."""
1980 def __init__(self, val):
1983 def to_string(self):
1984 return ("x=<" + str(self.val["x"]) +
1985 "> y=<" + str(self.val["y"]) + ">")
1988 This example doesn't need a lookup function, that is handled by the
1989 @code{gdb.printing} module. Instead a function is provided to build up
1990 the object that handles the lookup.
1995 def build_pretty_printer():
1996 pp = gdb.printing.RegexpCollectionPrettyPrinter(
1998 pp.add_printer('foo', '^foo$', fooPrinter)
1999 pp.add_printer('bar', '^bar$', barPrinter)
2003 And here is the autoload support:
2008 gdb.printing.register_pretty_printer(
2009 gdb.current_objfile(),
2010 my_library.build_pretty_printer())
2013 Finally, when this printer is loaded into @value{GDBN}, here is the
2014 corresponding output of @samp{info pretty-printer}:
2017 (gdb) info pretty-printer
2024 @node Type Printing API
2025 @subsubsection Type Printing API
2026 @cindex type printing API for Python
2028 @value{GDBN} provides a way for Python code to customize type display.
2029 This is mainly useful for substituting canonical typedef names for
2032 @cindex type printer
2033 A @dfn{type printer} is just a Python object conforming to a certain
2034 protocol. A simple base class implementing the protocol is provided;
2035 see @ref{gdb.types}. A type printer must supply at least:
2037 @defivar type_printer enabled
2038 A boolean which is True if the printer is enabled, and False
2039 otherwise. This is manipulated by the @code{enable type-printer}
2040 and @code{disable type-printer} commands.
2043 @defivar type_printer name
2044 The name of the type printer. This must be a string. This is used by
2045 the @code{enable type-printer} and @code{disable type-printer}
2049 @defmethod type_printer instantiate (self)
2050 This is called by @value{GDBN} at the start of type-printing. It is
2051 only called if the type printer is enabled. This method must return a
2052 new object that supplies a @code{recognize} method, as described below.
2056 When displaying a type, say via the @code{ptype} command, @value{GDBN}
2057 will compute a list of type recognizers. This is done by iterating
2058 first over the per-objfile type printers (@pxref{Objfiles In Python}),
2059 followed by the per-progspace type printers (@pxref{Progspaces In
2060 Python}), and finally the global type printers.
2062 @value{GDBN} will call the @code{instantiate} method of each enabled
2063 type printer. If this method returns @code{None}, then the result is
2064 ignored; otherwise, it is appended to the list of recognizers.
2066 Then, when @value{GDBN} is going to display a type name, it iterates
2067 over the list of recognizers. For each one, it calls the recognition
2068 function, stopping if the function returns a non-@code{None} value.
2069 The recognition function is defined as:
2071 @defmethod type_recognizer recognize (self, type)
2072 If @var{type} is not recognized, return @code{None}. Otherwise,
2073 return a string which is to be printed as the name of @var{type}.
2074 The @var{type} argument will be an instance of @code{gdb.Type}
2075 (@pxref{Types In Python}).
2078 @value{GDBN} uses this two-pass approach so that type printers can
2079 efficiently cache information without holding on to it too long. For
2080 example, it can be convenient to look up type information in a type
2081 printer and hold it for a recognizer's lifetime; if a single pass were
2082 done then type printers would have to make use of the event system in
2083 order to avoid holding information that could become stale as the
2086 @node Frame Filter API
2087 @subsubsection Filtering Frames
2088 @cindex frame filters api
2090 Frame filters are Python objects that manipulate the visibility of a
2091 frame or frames when a backtrace (@pxref{Backtrace}) is printed by
2094 Only commands that print a backtrace, or, in the case of @sc{gdb/mi}
2095 commands (@pxref{GDB/MI}), those that return a collection of frames
2096 are affected. The commands that work with frame filters are:
2098 @code{backtrace} (@pxref{backtrace-command,, The backtrace command}),
2099 @code{-stack-list-frames}
2100 (@pxref{-stack-list-frames,, The -stack-list-frames command}),
2101 @code{-stack-list-variables} (@pxref{-stack-list-variables,, The
2102 -stack-list-variables command}), @code{-stack-list-arguments}
2103 @pxref{-stack-list-arguments,, The -stack-list-arguments command}) and
2104 @code{-stack-list-locals} (@pxref{-stack-list-locals,, The
2105 -stack-list-locals command}).
2107 A frame filter works by taking an iterator as an argument, applying
2108 actions to the contents of that iterator, and returning another
2109 iterator (or, possibly, the same iterator it was provided in the case
2110 where the filter does not perform any operations). Typically, frame
2111 filters utilize tools such as the Python's @code{itertools} module to
2112 work with and create new iterators from the source iterator.
2113 Regardless of how a filter chooses to apply actions, it must not alter
2114 the underlying @value{GDBN} frame or frames, or attempt to alter the
2115 call-stack within @value{GDBN}. This preserves data integrity within
2116 @value{GDBN}. Frame filters are executed on a priority basis and care
2117 should be taken that some frame filters may have been executed before,
2118 and that some frame filters will be executed after.
2120 An important consideration when designing frame filters, and well
2121 worth reflecting upon, is that frame filters should avoid unwinding
2122 the call stack if possible. Some stacks can run very deep, into the
2123 tens of thousands in some cases. To search every frame when a frame
2124 filter executes may be too expensive at that step. The frame filter
2125 cannot know how many frames it has to iterate over, and it may have to
2126 iterate through them all. This ends up duplicating effort as
2127 @value{GDBN} performs this iteration when it prints the frames. If
2128 the filter can defer unwinding frames until frame decorators are
2129 executed, after the last filter has executed, it should. @xref{Frame
2130 Decorator API}, for more information on decorators. Also, there are
2131 examples for both frame decorators and filters in later chapters.
2132 @xref{Writing a Frame Filter}, for more information.
2134 The Python dictionary @code{gdb.frame_filters} contains key/object
2135 pairings that comprise a frame filter. Frame filters in this
2136 dictionary are called @code{global} frame filters, and they are
2137 available when debugging all inferiors. These frame filters must
2138 register with the dictionary directly. In addition to the
2139 @code{global} dictionary, there are other dictionaries that are loaded
2140 with different inferiors via auto-loading (@pxref{Python
2141 Auto-loading}). The two other areas where frame filter dictionaries
2142 can be found are: @code{gdb.Progspace} which contains a
2143 @code{frame_filters} dictionary attribute, and each @code{gdb.Objfile}
2144 object which also contains a @code{frame_filters} dictionary
2147 When a command is executed from @value{GDBN} that is compatible with
2148 frame filters, @value{GDBN} combines the @code{global},
2149 @code{gdb.Progspace} and all @code{gdb.Objfile} dictionaries currently
2150 loaded. All of the @code{gdb.Objfile} dictionaries are combined, as
2151 several frames, and thus several object files, might be in use.
2152 @value{GDBN} then prunes any frame filter whose @code{enabled}
2153 attribute is @code{False}. This pruned list is then sorted according
2154 to the @code{priority} attribute in each filter.
2156 Once the dictionaries are combined, pruned and sorted, @value{GDBN}
2157 creates an iterator which wraps each frame in the call stack in a
2158 @code{FrameDecorator} object, and calls each filter in order. The
2159 output from the previous filter will always be the input to the next
2162 Frame filters have a mandatory interface which each frame filter must
2163 implement, defined here:
2165 @defun FrameFilter.filter (iterator)
2166 @value{GDBN} will call this method on a frame filter when it has
2167 reached the order in the priority list for that filter.
2169 For example, if there are four frame filters:
2180 The order that the frame filters will be called is:
2183 Filter3 -> Filter2 -> Filter1 -> Filter4
2186 Note that the output from @code{Filter3} is passed to the input of
2187 @code{Filter2}, and so on.
2189 This @code{filter} method is passed a Python iterator. This iterator
2190 contains a sequence of frame decorators that wrap each
2191 @code{gdb.Frame}, or a frame decorator that wraps another frame
2192 decorator. The first filter that is executed in the sequence of frame
2193 filters will receive an iterator entirely comprised of default
2194 @code{FrameDecorator} objects. However, after each frame filter is
2195 executed, the previous frame filter may have wrapped some or all of
2196 the frame decorators with their own frame decorator. As frame
2197 decorators must also conform to a mandatory interface, these
2198 decorators can be assumed to act in a uniform manner (@pxref{Frame
2201 This method must return an object conforming to the Python iterator
2202 protocol. Each item in the iterator must be an object conforming to
2203 the frame decorator interface. If a frame filter does not wish to
2204 perform any operations on this iterator, it should return that
2207 This method is not optional. If it does not exist, @value{GDBN} will
2208 raise and print an error.
2211 @defvar FrameFilter.name
2212 The @code{name} attribute must be Python string which contains the
2213 name of the filter displayed by @value{GDBN} (@pxref{Frame Filter
2214 Management}). This attribute may contain any combination of letters
2215 or numbers. Care should be taken to ensure that it is unique. This
2216 attribute is mandatory.
2219 @defvar FrameFilter.enabled
2220 The @code{enabled} attribute must be Python boolean. This attribute
2221 indicates to @value{GDBN} whether the frame filter is enabled, and
2222 should be considered when frame filters are executed. If
2223 @code{enabled} is @code{True}, then the frame filter will be executed
2224 when any of the backtrace commands detailed earlier in this chapter
2225 are executed. If @code{enabled} is @code{False}, then the frame
2226 filter will not be executed. This attribute is mandatory.
2229 @defvar FrameFilter.priority
2230 The @code{priority} attribute must be Python integer. This attribute
2231 controls the order of execution in relation to other frame filters.
2232 There are no imposed limits on the range of @code{priority} other than
2233 it must be a valid integer. The higher the @code{priority} attribute,
2234 the sooner the frame filter will be executed in relation to other
2235 frame filters. Although @code{priority} can be negative, it is
2236 recommended practice to assume zero is the lowest priority that a
2237 frame filter can be assigned. Frame filters that have the same
2238 priority are executed in unsorted order in that priority slot. This
2239 attribute is mandatory. 100 is a good default priority.
2242 @node Frame Decorator API
2243 @subsubsection Decorating Frames
2244 @cindex frame decorator api
2246 Frame decorators are sister objects to frame filters (@pxref{Frame
2247 Filter API}). Frame decorators are applied by a frame filter and can
2248 only be used in conjunction with frame filters.
2250 The purpose of a frame decorator is to customize the printed content
2251 of each @code{gdb.Frame} in commands where frame filters are executed.
2252 This concept is called decorating a frame. Frame decorators decorate
2253 a @code{gdb.Frame} with Python code contained within each API call.
2254 This separates the actual data contained in a @code{gdb.Frame} from
2255 the decorated data produced by a frame decorator. This abstraction is
2256 necessary to maintain integrity of the data contained in each
2259 Frame decorators have a mandatory interface, defined below.
2261 @value{GDBN} already contains a frame decorator called
2262 @code{FrameDecorator}. This contains substantial amounts of
2263 boilerplate code to decorate the content of a @code{gdb.Frame}. It is
2264 recommended that other frame decorators inherit and extend this
2265 object, and only to override the methods needed.
2267 @tindex gdb.FrameDecorator
2268 @code{FrameDecorator} is defined in the Python module
2269 @code{gdb.FrameDecorator}, so your code can import it like:
2271 from gdb.FrameDecorator import FrameDecorator
2274 @defun FrameDecorator.elided (self)
2276 The @code{elided} method groups frames together in a hierarchical
2277 system. An example would be an interpreter, where multiple low-level
2278 frames make up a single call in the interpreted language. In this
2279 example, the frame filter would elide the low-level frames and present
2280 a single high-level frame, representing the call in the interpreted
2281 language, to the user.
2283 The @code{elided} function must return an iterable and this iterable
2284 must contain the frames that are being elided wrapped in a suitable
2285 frame decorator. If no frames are being elided this function may
2286 return an empty iterable, or @code{None}. Elided frames are indented
2287 from normal frames in a @code{CLI} backtrace, or in the case of
2288 @sc{gdb/mi}, are placed in the @code{children} field of the eliding
2291 It is the frame filter's task to also filter out the elided frames from
2292 the source iterator. This will avoid printing the frame twice.
2295 @defun FrameDecorator.function (self)
2297 This method returns the name of the function in the frame that is to
2300 This method must return a Python string describing the function, or
2303 If this function returns @code{None}, @value{GDBN} will not print any
2304 data for this field.
2307 @defun FrameDecorator.address (self)
2309 This method returns the address of the frame that is to be printed.
2311 This method must return a Python numeric integer type of sufficient
2312 size to describe the address of the frame, or @code{None}.
2314 If this function returns a @code{None}, @value{GDBN} will not print
2315 any data for this field.
2318 @defun FrameDecorator.filename (self)
2320 This method returns the filename and path associated with this frame.
2322 This method must return a Python string containing the filename and
2323 the path to the object file backing the frame, or @code{None}.
2325 If this function returns a @code{None}, @value{GDBN} will not print
2326 any data for this field.
2329 @defun FrameDecorator.line (self):
2331 This method returns the line number associated with the current
2332 position within the function addressed by this frame.
2334 This method must return a Python integer type, or @code{None}.
2336 If this function returns a @code{None}, @value{GDBN} will not print
2337 any data for this field.
2340 @defun FrameDecorator.frame_args (self)
2343 This method must return an iterable, or @code{None}. Returning an
2344 empty iterable, or @code{None} means frame arguments will not be
2345 printed for this frame. This iterable must contain objects that
2346 implement two methods, described here.
2348 This object must implement a @code{symbol} method which takes a
2349 single @code{self} parameter and must return a @code{gdb.Symbol}
2350 (@pxref{Symbols In Python}), or a Python string. The object must also
2351 implement a @code{value} method which takes a single @code{self}
2352 parameter and must return a @code{gdb.Value} (@pxref{Values From
2353 Inferior}), a Python value, or @code{None}. If the @code{value}
2354 method returns @code{None}, and the @code{argument} method returns a
2355 @code{gdb.Symbol}, @value{GDBN} will look-up and print the value of
2356 the @code{gdb.Symbol} automatically.
2361 class SymValueWrapper():
2363 def __init__(self, symbol, value):
2373 class SomeFrameDecorator()
2376 def frame_args(self):
2379 block = self.inferior_frame.block()
2383 # Iterate over all symbols in a block. Only add
2384 # symbols that are arguments.
2386 if not sym.is_argument:
2388 args.append(SymValueWrapper(sym,None))
2390 # Add example synthetic argument.
2391 args.append(SymValueWrapper(``foo'', 42))
2397 @defun FrameDecorator.frame_locals (self)
2399 This method must return an iterable or @code{None}. Returning an
2400 empty iterable, or @code{None} means frame local arguments will not be
2401 printed for this frame.
2403 The object interface, the description of the various strategies for
2404 reading frame locals, and the example are largely similar to those
2405 described in the @code{frame_args} function, (@pxref{frame_args,,The
2406 frame filter frame_args function}). Below is a modified example:
2409 class SomeFrameDecorator()
2412 def frame_locals(self):
2415 block = self.inferior_frame.block()
2419 # Iterate over all symbols in a block. Add all
2420 # symbols, except arguments.
2424 vars.append(SymValueWrapper(sym,None))
2426 # Add an example of a synthetic local variable.
2427 vars.append(SymValueWrapper(``bar'', 99))
2433 @defun FrameDecorator.inferior_frame (self):
2435 This method must return the underlying @code{gdb.Frame} that this
2436 frame decorator is decorating. @value{GDBN} requires the underlying
2437 frame for internal frame information to determine how to print certain
2438 values when printing a frame.
2441 @node Writing a Frame Filter
2442 @subsubsection Writing a Frame Filter
2443 @cindex writing a frame filter
2445 There are three basic elements that a frame filter must implement: it
2446 must correctly implement the documented interface (@pxref{Frame Filter
2447 API}), it must register itself with @value{GDBN}, and finally, it must
2448 decide if it is to work on the data provided by @value{GDBN}. In all
2449 cases, whether it works on the iterator or not, each frame filter must
2450 return an iterator. A bare-bones frame filter follows the pattern in
2451 the following example.
2456 class FrameFilter():
2459 # Frame filter attribute creation.
2461 # 'name' is the name of the filter that GDB will display.
2463 # 'priority' is the priority of the filter relative to other
2466 # 'enabled' is a boolean that indicates whether this filter is
2467 # enabled and should be executed.
2473 # Register this frame filter with the global frame_filters
2475 gdb.frame_filters[self.name] = self
2477 def filter(self, frame_iter):
2478 # Just return the iterator.
2482 The frame filter in the example above implements the three
2483 requirements for all frame filters. It implements the API, self
2484 registers, and makes a decision on the iterator (in this case, it just
2485 returns the iterator untouched).
2487 The first step is attribute creation and assignment, and as shown in
2488 the comments the filter assigns the following attributes: @code{name},
2489 @code{priority} and whether the filter should be enabled with the
2490 @code{enabled} attribute.
2492 The second step is registering the frame filter with the dictionary or
2493 dictionaries that the frame filter has interest in. As shown in the
2494 comments, this filter just registers itself with the global dictionary
2495 @code{gdb.frame_filters}. As noted earlier, @code{gdb.frame_filters}
2496 is a dictionary that is initialized in the @code{gdb} module when
2497 @value{GDBN} starts. What dictionary a filter registers with is an
2498 important consideration. Generally, if a filter is specific to a set
2499 of code, it should be registered either in the @code{objfile} or
2500 @code{progspace} dictionaries as they are specific to the program
2501 currently loaded in @value{GDBN}. The global dictionary is always
2502 present in @value{GDBN} and is never unloaded. Any filters registered
2503 with the global dictionary will exist until @value{GDBN} exits. To
2504 avoid filters that may conflict, it is generally better to register
2505 frame filters against the dictionaries that more closely align with
2506 the usage of the filter currently in question. @xref{Python
2507 Auto-loading}, for further information on auto-loading Python scripts.
2509 @value{GDBN} takes a hands-off approach to frame filter registration,
2510 therefore it is the frame filter's responsibility to ensure
2511 registration has occurred, and that any exceptions are handled
2512 appropriately. In particular, you may wish to handle exceptions
2513 relating to Python dictionary key uniqueness. It is mandatory that
2514 the dictionary key is the same as frame filter's @code{name}
2515 attribute. When a user manages frame filters (@pxref{Frame Filter
2516 Management}), the names @value{GDBN} will display are those contained
2517 in the @code{name} attribute.
2519 The final step of this example is the implementation of the
2520 @code{filter} method. As shown in the example comments, we define the
2521 @code{filter} method and note that the method must take an iterator,
2522 and also must return an iterator. In this bare-bones example, the
2523 frame filter is not very useful as it just returns the iterator
2524 untouched. However this is a valid operation for frame filters that
2525 have the @code{enabled} attribute set, but decide not to operate on
2528 In the next example, the frame filter operates on all frames and
2529 utilizes a frame decorator to perform some work on the frames.
2530 @xref{Frame Decorator API}, for further information on the frame
2531 decorator interface.
2533 This example works on inlined frames. It highlights frames which are
2534 inlined by tagging them with an ``[inlined]'' tag. By applying a
2535 frame decorator to all frames with the Python @code{itertools imap}
2536 method, the example defers actions to the frame decorator. Frame
2537 decorators are only processed when @value{GDBN} prints the backtrace.
2539 This introduces a new decision making topic: whether to perform
2540 decision making operations at the filtering step, or at the printing
2541 step. In this example's approach, it does not perform any filtering
2542 decisions at the filtering step beyond mapping a frame decorator to
2543 each frame. This allows the actual decision making to be performed
2544 when each frame is printed. This is an important consideration, and
2545 well worth reflecting upon when designing a frame filter. An issue
2546 that frame filters should avoid is unwinding the stack if possible.
2547 Some stacks can run very deep, into the tens of thousands in some
2548 cases. To search every frame to determine if it is inlined ahead of
2549 time may be too expensive at the filtering step. The frame filter
2550 cannot know how many frames it has to iterate over, and it would have
2551 to iterate through them all. This ends up duplicating effort as
2552 @value{GDBN} performs this iteration when it prints the frames.
2554 In this example decision making can be deferred to the printing step.
2555 As each frame is printed, the frame decorator can examine each frame
2556 in turn when @value{GDBN} iterates. From a performance viewpoint,
2557 this is the most appropriate decision to make as it avoids duplicating
2558 the effort that the printing step would undertake anyway. Also, if
2559 there are many frame filters unwinding the stack during filtering, it
2560 can substantially delay the printing of the backtrace which will
2561 result in large memory usage, and a poor user experience.
2564 class InlineFilter():
2567 self.name = "InlinedFrameFilter"
2570 gdb.frame_filters[self.name] = self
2572 def filter(self, frame_iter):
2573 frame_iter = itertools.imap(InlinedFrameDecorator,
2578 This frame filter is somewhat similar to the earlier example, except
2579 that the @code{filter} method applies a frame decorator object called
2580 @code{InlinedFrameDecorator} to each element in the iterator. The
2581 @code{imap} Python method is light-weight. It does not proactively
2582 iterate over the iterator, but rather creates a new iterator which
2583 wraps the existing one.
2585 Below is the frame decorator for this example.
2588 class InlinedFrameDecorator(FrameDecorator):
2590 def __init__(self, fobj):
2591 super(InlinedFrameDecorator, self).__init__(fobj)
2594 frame = self.inferior_frame()
2595 name = str(frame.name())
2597 if frame.type() == gdb.INLINE_FRAME:
2598 name = name + " [inlined]"
2603 This frame decorator only defines and overrides the @code{function}
2604 method. It lets the supplied @code{FrameDecorator}, which is shipped
2605 with @value{GDBN}, perform the other work associated with printing
2608 The combination of these two objects create this output from a
2612 #0 0x004004e0 in bar () at inline.c:11
2613 #1 0x00400566 in max [inlined] (b=6, a=12) at inline.c:21
2614 #2 0x00400566 in main () at inline.c:31
2617 So in the case of this example, a frame decorator is applied to all
2618 frames, regardless of whether they may be inlined or not. As
2619 @value{GDBN} iterates over the iterator produced by the frame filters,
2620 @value{GDBN} executes each frame decorator which then makes a decision
2621 on what to print in the @code{function} callback. Using a strategy
2622 like this is a way to defer decisions on the frame content to printing
2625 @subheading Eliding Frames
2627 It might be that the above example is not desirable for representing
2628 inlined frames, and a hierarchical approach may be preferred. If we
2629 want to hierarchically represent frames, the @code{elided} frame
2630 decorator interface might be preferable.
2632 This example approaches the issue with the @code{elided} method. This
2633 example is quite long, but very simplistic. It is out-of-scope for
2634 this section to write a complete example that comprehensively covers
2635 all approaches of finding and printing inlined frames. However, this
2636 example illustrates the approach an author might use.
2638 This example comprises of three sections.
2641 class InlineFrameFilter():
2644 self.name = "InlinedFrameFilter"
2647 gdb.frame_filters[self.name] = self
2649 def filter(self, frame_iter):
2650 return ElidingInlineIterator(frame_iter)
2653 This frame filter is very similar to the other examples. The only
2654 difference is this frame filter is wrapping the iterator provided to
2655 it (@code{frame_iter}) with a custom iterator called
2656 @code{ElidingInlineIterator}. This again defers actions to when
2657 @value{GDBN} prints the backtrace, as the iterator is not traversed
2660 The iterator for this example is as follows. It is in this section of
2661 the example where decisions are made on the content of the backtrace.
2664 class ElidingInlineIterator:
2665 def __init__(self, ii):
2666 self.input_iterator = ii
2672 frame = next(self.input_iterator)
2674 if frame.inferior_frame().type() != gdb.INLINE_FRAME:
2678 eliding_frame = next(self.input_iterator)
2679 except StopIteration:
2681 return ElidingFrameDecorator(eliding_frame, [frame])
2684 This iterator implements the Python iterator protocol. When the
2685 @code{next} function is called (when @value{GDBN} prints each frame),
2686 the iterator checks if this frame decorator, @code{frame}, is wrapping
2687 an inlined frame. If it is not, it returns the existing frame decorator
2688 untouched. If it is wrapping an inlined frame, it assumes that the
2689 inlined frame was contained within the next oldest frame,
2690 @code{eliding_frame}, which it fetches. It then creates and returns a
2691 frame decorator, @code{ElidingFrameDecorator}, which contains both the
2692 elided frame, and the eliding frame.
2695 class ElidingInlineDecorator(FrameDecorator):
2697 def __init__(self, frame, elided_frames):
2698 super(ElidingInlineDecorator, self).__init__(frame)
2700 self.elided_frames = elided_frames
2703 return iter(self.elided_frames)
2706 This frame decorator overrides one function and returns the inlined
2707 frame in the @code{elided} method. As before it lets
2708 @code{FrameDecorator} do the rest of the work involved in printing
2709 this frame. This produces the following output.
2712 #0 0x004004e0 in bar () at inline.c:11
2713 #2 0x00400529 in main () at inline.c:25
2714 #1 0x00400529 in max (b=6, a=12) at inline.c:15
2717 In that output, @code{max} which has been inlined into @code{main} is
2718 printed hierarchically. Another approach would be to combine the
2719 @code{function} method, and the @code{elided} method to both print a
2720 marker in the inlined frame, and also show the hierarchical
2723 @node Unwinding Frames in Python
2724 @subsubsection Unwinding Frames in Python
2725 @cindex unwinding frames in Python
2727 In @value{GDBN} terminology ``unwinding'' is the process of finding
2728 the previous frame (that is, caller's) from the current one. An
2729 unwinder has three methods. The first one checks if it can handle
2730 given frame (``sniff'' it). For the frames it can sniff an unwinder
2731 provides two additional methods: it can return frame's ID, and it can
2732 fetch registers from the previous frame. A running @value{GDBN}
2733 mantains a list of the unwinders and calls each unwinder's sniffer in
2734 turn until it finds the one that recognizes the current frame. There
2735 is an API to register an unwinder.
2737 The unwinders that come with @value{GDBN} handle standard frames.
2738 However, mixed language applications (for example, an application
2739 running Java Virtual Machine) sometimes use frame layouts that cannot
2740 be handled by the @value{GDBN} unwinders. You can write Python code
2741 that can handle such custom frames.
2743 You implement a frame unwinder in Python as a class with which has two
2744 attributes, @code{name} and @code{enabled}, with obvious meanings, and
2745 a single method @code{__call__}, which examines a given frame and
2746 returns an object (an instance of @code{gdb.UnwindInfo class)}
2747 describing it. If an unwinder does not recognize a frame, it should
2748 return @code{None}. The code in @value{GDBN} that enables writing
2749 unwinders in Python uses this object to return frame's ID and previous
2750 frame registers when @value{GDBN} core asks for them.
2752 An unwinder should do as little work as possible. Some otherwise
2753 innocuous operations can cause problems (even crashes, as this code is
2754 not not well-hardened yet). For example, making an inferior call from
2755 an unwinder is unadvisable, as an inferior call will reset
2756 @value{GDBN}'s stack unwinding process, potentially causing re-entrant
2759 @subheading Unwinder Input
2761 An object passed to an unwinder (a @code{gdb.PendingFrame} instance)
2762 provides a method to read frame's registers:
2764 @defun PendingFrame.read_register (register)
2765 This method returns the contents of @var{register} in the
2766 frame as a @code{gdb.Value} object. For a description of the
2767 acceptable values of @var{register} see
2768 @ref{gdbpy_frame_read_register,,Frame.read_register}. If @var{register}
2769 does not name a register for the current architecture, this method
2770 will throw an exception.
2772 Note that this method will always return a @code{gdb.Value} for a
2773 valid register name. This does not mean that the value will be valid.
2774 For example, you may request a register that an earlier unwinder could
2775 not unwind---the value will be unavailable. Instead, the
2776 @code{gdb.Value} returned from this method will be lazy; that is, its
2777 underlying bits will not be fetched until it is first used. So,
2778 attempting to use such a value will cause an exception at the point of
2781 The type of the returned @code{gdb.Value} depends on the register and
2782 the architecture. It is common for registers to have a scalar type,
2783 like @code{long long}; but many other types are possible, such as
2784 pointer, pointer-to-function, floating point or vector types.
2787 It also provides a factory method to create a @code{gdb.UnwindInfo}
2788 instance to be returned to @value{GDBN}:
2790 @anchor{gdb.PendingFrame.create_unwind_info}
2791 @defun PendingFrame.create_unwind_info (frame_id)
2792 Returns a new @code{gdb.UnwindInfo} instance identified by given
2793 @var{frame_id}. The @var{frame_id} is used internally by @value{GDBN}
2794 to identify the frames within the current thread's stack. The
2795 attributes of @var{frame_id} determine what type of frame is
2796 created within @value{GDBN}:
2800 The frame is identified by the given stack address and PC. The stack
2801 address must be chosen so that it is constant throughout the lifetime
2802 of the frame, so a typical choice is the value of the stack pointer at
2803 the start of the function---in the DWARF standard, this would be the
2804 ``Call Frame Address''.
2806 This is the most common case by far. The other cases are documented
2807 for completeness but are only useful in specialized situations.
2809 @item sp, pc, special
2810 The frame is identified by the stack address, the PC, and a
2811 ``special'' address. The special address is used on architectures
2812 that can have frames that do not change the stack, but which are still
2813 distinct, for example the IA-64, which has a second stack for
2814 registers. Both @var{sp} and @var{special} must be constant
2815 throughout the lifetime of the frame.
2818 The frame is identified by the stack address only. Any other stack
2819 frame with a matching @var{sp} will be considered to match this frame.
2820 Inside gdb, this is called a ``wild frame''. You will never need
2824 Each attribute value should either be an instance of @code{gdb.Value}
2827 A helper class is provided in the @code{gdb.unwinder} module that can
2828 be used to represent a frame-id
2829 (@pxref{gdb.unwinder.FrameId}).
2833 @defun PendingFrame.architecture ()
2834 Return the @code{gdb.Architecture} (@pxref{Architectures In Python})
2835 for this @code{gdb.PendingFrame}. This represents the architecture of
2836 the particular frame being unwound.
2839 @defun PendingFrame.level ()
2840 Return an integer, the stack frame level for this frame.
2841 @xref{Frames, ,Stack Frames}.
2844 @defun PendingFrame.name ()
2845 Returns the function name of this pending frame, or @code{None} if it
2849 @defun PendingFrame.is_valid ()
2850 Returns true if the @code{gdb.PendingFrame} object is valid, false if
2851 not. A pending frame object becomes invalid when the call to the
2852 unwinder, for which the pending frame was created, returns.
2854 All @code{gdb.PendingFrame} methods, except this one, will raise an
2855 exception if the pending frame object is invalid at the time the
2859 @defun PendingFrame.pc ()
2860 Returns the pending frame's resume address.
2863 @defun PendingFrame.block ()
2864 Return the pending frame's code block (@pxref{Blocks In Python}). If
2865 the frame does not have a block -- for example, if there is no
2866 debugging information for the code in question -- then this will raise
2867 a @code{RuntimeError} exception.
2870 @defun PendingFrame.function ()
2871 Return the symbol for the function corresponding to this pending frame.
2872 @xref{Symbols In Python}.
2875 @defun PendingFrame.find_sal ()
2876 Return the pending frame's symtab and line object (@pxref{Symbol
2880 @defun PendingFrame.language ()
2881 Return the language of this frame, as a string, or None.
2884 @subheading Unwinder Output: UnwindInfo
2886 Use @code{PendingFrame.create_unwind_info} method described above to
2887 create a @code{gdb.UnwindInfo} instance. Use the following method to
2888 specify caller registers that have been saved in this frame:
2890 @defun gdb.UnwindInfo.add_saved_register (register, value)
2891 @var{register} identifies the register, for a description of the acceptable
2892 values see @ref{gdbpy_frame_read_register,,Frame.read_register}.
2893 @var{value} is a register value (a @code{gdb.Value} object).
2896 @subheading The @code{gdb.unwinder} Module
2898 @value{GDBN} comes with a @code{gdb.unwinder} module which contains
2899 the following classes:
2901 @deftp {class} gdb.unwinder.Unwinder
2902 The @code{Unwinder} class is a base class from which user created
2903 unwinders can derive, though it is not required that unwinders derive
2904 from this class, so long as any user created unwinder has the required
2905 @code{name} and @code{enabled} attributes.
2907 @defun gdb.unwinder.Unwinder.__init__(name)
2908 The @var{name} is a string used to reference this unwinder within some
2909 @value{GDBN} commands (@pxref{Managing Registered Unwinders}).
2912 @defvar gdb.unwinder.name
2913 A read-only attribute which is a string, the name of this unwinder.
2916 @defvar gdb.unwinder.enabled
2917 A modifiable attribute containing a boolean; when @code{True}, the
2918 unwinder is enabled, and will be used by @value{GDBN}. When
2919 @code{False}, the unwinder has been disabled, and will not be used.
2923 @anchor{gdb.unwinder.FrameId}
2924 @deftp {class} gdb.unwinder.FrameId
2925 This is a class suitable for being used as the frame-id when calling
2926 @code{gdb.PendingFrame.create_unwind_info}. It is not required to use
2927 this class, any class with the required attribute
2928 (@pxref{gdb.PendingFrame.create_unwind_info}) will be accepted, but in
2929 most cases this class will be sufficient.
2931 @code{gdb.unwinder.FrameId} has the following method:
2933 @defun gdb.unwinder.FrameId.__init__(sp, pc, special = @code{None})
2934 The @var{sp} and @var{pc} arguments are required and should be either
2935 a @code{gdb.Value} object, or an integer.
2937 The @var{special} argument is optional; if specified, it should be a
2938 @code{gdb.Value} object, or an integer.
2941 @code{gdb.unwinder.FrameId} has the following read-only attributes:
2943 @defvar gdb.unwinder.sp
2944 The @var{sp} value passed to the constructor.
2947 @defvar gdb.unwinder.pc
2948 The @var{pc} value passed to the constructor.
2951 @defvar gdb.unwinder.special
2952 The @var{special} value passed to the constructor, or @code{None} if
2953 no such value was passed.
2957 @subheading Registering an Unwinder
2959 Object files and program spaces can have unwinders registered with
2960 them. In addition, you can register unwinders globally.
2962 The @code{gdb.unwinders} module provides the function to register an
2965 @defun gdb.unwinder.register_unwinder (locus, unwinder, replace=False)
2966 @var{locus} specifies to which unwinder list to prepend the
2967 @var{unwinder}. It can be either an object file (@pxref{Objfiles In
2968 Python}), a program space (@pxref{Progspaces In Python}), or
2969 @code{None}, in which case the unwinder is registered globally. The
2970 newly added @var{unwinder} will be called before any other unwinder
2971 from the same locus. Two unwinders in the same locus cannot have the
2972 same name. An attempt to add an unwinder with an already existing
2973 name raises an exception unless @var{replace} is @code{True}, in which
2974 case the old unwinder is deleted and the new unwinder is registered in
2977 @value{GDBN} first calls the unwinders from all the object files in no
2978 particular order, then the unwinders from the current program space,
2979 then the globally registered unwinders, and finally the unwinders
2980 builtin to @value{GDBN}.
2983 @subheading Unwinder Skeleton Code
2985 Here is an example of how to structure a user created unwinder:
2988 from gdb.unwinder import Unwinder, FrameId
2990 class MyUnwinder(Unwinder):
2992 super().__init___("MyUnwinder_Name")
2994 def __call__(self, pending_frame):
2995 if not <we recognize frame>:
2998 # Create a FrameID. Usually the frame is identified by a
2999 # stack pointer and the function address.
3000 sp = ... compute a stack address ...
3001 pc = ... compute function address ...
3002 unwind_info = pending_frame.create_unwind_info(FrameId(sp, pc))
3004 # Find the values of the registers in the caller's frame and
3005 # save them in the result:
3006 unwind_info.add_saved_register(<register-number>, <register-value>)
3009 # Return the result:
3012 gdb.unwinder.register_unwinder(<locus>, MyUnwinder(), <replace>)
3015 @anchor{Managing Registered Unwinders}
3016 @subheading Managing Registered Unwinders
3017 @value{GDBN} defines 3 commands to manage registered unwinders. These
3021 @item info unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
3022 Lists all registered unwinders. Arguments @var{locus} and
3023 @var{name-regexp} are both optional and can be used to filter which
3024 unwinders are listed.
3026 The @var{locus} argument should be either @kbd{global},
3027 @kbd{progspace}, or the name of an object file. Only unwinders
3028 registered for the specified locus will be listed.
3030 The @var{name-regexp} is a regular expression used to match against
3031 unwinder names. When trying to match against unwinder names that
3032 include a string enclose @var{name-regexp} in quotes.
3033 @item disable unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
3034 The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
3035 unwinder} above, but instead of listing the matching unwinders, all of
3036 the matching unwinders are disabled. The @code{enabled} field of each
3037 matching unwinder is set to @code{False}.
3038 @item enable unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
3039 The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
3040 unwinder} above, but instead of listing the matching unwinders, all of
3041 the matching unwinders are enabled. The @code{enabled} field of each
3042 matching unwinder is set to @code{True}.
3045 @node Xmethods In Python
3046 @subsubsection Xmethods In Python
3047 @cindex xmethods in Python
3049 @dfn{Xmethods} are additional methods or replacements for existing
3050 methods of a C@t{++} class. This feature is useful for those cases
3051 where a method defined in C@t{++} source code could be inlined or
3052 optimized out by the compiler, making it unavailable to @value{GDBN}.
3053 For such cases, one can define an xmethod to serve as a replacement
3054 for the method defined in the C@t{++} source code. @value{GDBN} will
3055 then invoke the xmethod, instead of the C@t{++} method, to
3056 evaluate expressions. One can also use xmethods when debugging
3057 with core files. Moreover, when debugging live programs, invoking an
3058 xmethod need not involve running the inferior (which can potentially
3059 perturb its state). Hence, even if the C@t{++} method is available, it
3060 is better to use its replacement xmethod if one is defined.
3062 The xmethods feature in Python is available via the concepts of an
3063 @dfn{xmethod matcher} and an @dfn{xmethod worker}. To
3064 implement an xmethod, one has to implement a matcher and a
3065 corresponding worker for it (more than one worker can be
3066 implemented, each catering to a different overloaded instance of the
3067 method). Internally, @value{GDBN} invokes the @code{match} method of a
3068 matcher to match the class type and method name. On a match, the
3069 @code{match} method returns a list of matching @emph{worker} objects.
3070 Each worker object typically corresponds to an overloaded instance of
3071 the xmethod. They implement a @code{get_arg_types} method which
3072 returns a sequence of types corresponding to the arguments the xmethod
3073 requires. @value{GDBN} uses this sequence of types to perform
3074 overload resolution and picks a winning xmethod worker. A winner
3075 is also selected from among the methods @value{GDBN} finds in the
3076 C@t{++} source code. Next, the winning xmethod worker and the
3077 winning C@t{++} method are compared to select an overall winner. In
3078 case of a tie between a xmethod worker and a C@t{++} method, the
3079 xmethod worker is selected as the winner. That is, if a winning
3080 xmethod worker is found to be equivalent to the winning C@t{++}
3081 method, then the xmethod worker is treated as a replacement for
3082 the C@t{++} method. @value{GDBN} uses the overall winner to invoke the
3083 method. If the winning xmethod worker is the overall winner, then
3084 the corresponding xmethod is invoked via the @code{__call__} method
3085 of the worker object.
3087 If one wants to implement an xmethod as a replacement for an
3088 existing C@t{++} method, then they have to implement an equivalent
3089 xmethod which has exactly the same name and takes arguments of
3090 exactly the same type as the C@t{++} method. If the user wants to
3091 invoke the C@t{++} method even though a replacement xmethod is
3092 available for that method, then they can disable the xmethod.
3094 @xref{Xmethod API}, for API to implement xmethods in Python.
3095 @xref{Writing an Xmethod}, for implementing xmethods in Python.
3098 @subsubsection Xmethod API
3101 The @value{GDBN} Python API provides classes, interfaces and functions
3102 to implement, register and manipulate xmethods.
3103 @xref{Xmethods In Python}.
3105 An xmethod matcher should be an instance of a class derived from
3106 @code{XMethodMatcher} defined in the module @code{gdb.xmethod}, or an
3107 object with similar interface and attributes. An instance of
3108 @code{XMethodMatcher} has the following attributes:
3111 The name of the matcher.
3115 A boolean value indicating whether the matcher is enabled or disabled.
3119 A list of named methods managed by the matcher. Each object in the list
3120 is an instance of the class @code{XMethod} defined in the module
3121 @code{gdb.xmethod}, or any object with the following attributes:
3126 Name of the xmethod which should be unique for each xmethod
3127 managed by the matcher.
3130 A boolean value indicating whether the xmethod is enabled or
3135 The class @code{XMethod} is a convenience class with same
3136 attributes as above along with the following constructor:
3138 @defun XMethod.__init__ (self, name)
3139 Constructs an enabled xmethod with name @var{name}.
3144 The @code{XMethodMatcher} class has the following methods:
3146 @defun XMethodMatcher.__init__ (self, name)
3147 Constructs an enabled xmethod matcher with name @var{name}. The
3148 @code{methods} attribute is initialized to @code{None}.
3151 @defun XMethodMatcher.match (self, class_type, method_name)
3152 Derived classes should override this method. It should return a
3153 xmethod worker object (or a sequence of xmethod worker
3154 objects) matching the @var{class_type} and @var{method_name}.
3155 @var{class_type} is a @code{gdb.Type} object, and @var{method_name}
3156 is a string value. If the matcher manages named methods as listed in
3157 its @code{methods} attribute, then only those worker objects whose
3158 corresponding entries in the @code{methods} list are enabled should be
3162 An xmethod worker should be an instance of a class derived from
3163 @code{XMethodWorker} defined in the module @code{gdb.xmethod},
3164 or support the following interface:
3166 @defun XMethodWorker.get_arg_types (self)
3167 This method returns a sequence of @code{gdb.Type} objects corresponding
3168 to the arguments that the xmethod takes. It can return an empty
3169 sequence or @code{None} if the xmethod does not take any arguments.
3170 If the xmethod takes a single argument, then a single
3171 @code{gdb.Type} object corresponding to it can be returned.
3174 @defun XMethodWorker.get_result_type (self, *args)
3175 This method returns a @code{gdb.Type} object representing the type
3176 of the result of invoking this xmethod.
3177 The @var{args} argument is the same tuple of arguments that would be
3178 passed to the @code{__call__} method of this worker.
3181 @defun XMethodWorker.__call__ (self, *args)
3182 This is the method which does the @emph{work} of the xmethod. The
3183 @var{args} arguments is the tuple of arguments to the xmethod. Each
3184 element in this tuple is a gdb.Value object. The first element is
3185 always the @code{this} pointer value.
3188 For @value{GDBN} to lookup xmethods, the xmethod matchers
3189 should be registered using the following function defined in the module
3192 @defun register_xmethod_matcher (locus, matcher, replace=False)
3193 The @code{matcher} is registered with @code{locus}, replacing an
3194 existing matcher with the same name as @code{matcher} if
3195 @code{replace} is @code{True}. @code{locus} can be a
3196 @code{gdb.Objfile} object (@pxref{Objfiles In Python}), or a
3197 @code{gdb.Progspace} object (@pxref{Progspaces In Python}), or
3198 @code{None}. If it is @code{None}, then @code{matcher} is registered
3202 @node Writing an Xmethod
3203 @subsubsection Writing an Xmethod
3204 @cindex writing xmethods in Python
3206 Implementing xmethods in Python will require implementing xmethod
3207 matchers and xmethod workers (@pxref{Xmethods In Python}). Consider
3208 the following C@t{++} class:
3214 MyClass (int a) : a_(a) @{ @}
3216 int geta (void) @{ return a_; @}
3217 int operator+ (int b);
3224 MyClass::operator+ (int b)
3231 Let us define two xmethods for the class @code{MyClass}, one
3232 replacing the method @code{geta}, and another adding an overloaded
3233 flavor of @code{operator+} which takes a @code{MyClass} argument (the
3234 C@t{++} code above already has an overloaded @code{operator+}
3235 which takes an @code{int} argument). The xmethod matcher can be
3239 class MyClass_geta(gdb.xmethod.XMethod):
3241 gdb.xmethod.XMethod.__init__(self, 'geta')
3243 def get_worker(self, method_name):
3244 if method_name == 'geta':
3245 return MyClassWorker_geta()
3248 class MyClass_sum(gdb.xmethod.XMethod):
3250 gdb.xmethod.XMethod.__init__(self, 'sum')
3252 def get_worker(self, method_name):
3253 if method_name == 'operator+':
3254 return MyClassWorker_plus()
3257 class MyClassMatcher(gdb.xmethod.XMethodMatcher):
3259 gdb.xmethod.XMethodMatcher.__init__(self, 'MyClassMatcher')
3260 # List of methods 'managed' by this matcher
3261 self.methods = [MyClass_geta(), MyClass_sum()]
3263 def match(self, class_type, method_name):
3264 if class_type.tag != 'MyClass':
3267 for method in self.methods:
3269 worker = method.get_worker(method_name)
3271 workers.append(worker)
3277 Notice that the @code{match} method of @code{MyClassMatcher} returns
3278 a worker object of type @code{MyClassWorker_geta} for the @code{geta}
3279 method, and a worker object of type @code{MyClassWorker_plus} for the
3280 @code{operator+} method. This is done indirectly via helper classes
3281 derived from @code{gdb.xmethod.XMethod}. One does not need to use the
3282 @code{methods} attribute in a matcher as it is optional. However, if a
3283 matcher manages more than one xmethod, it is a good practice to list the
3284 xmethods in the @code{methods} attribute of the matcher. This will then
3285 facilitate enabling and disabling individual xmethods via the
3286 @code{enable/disable} commands. Notice also that a worker object is
3287 returned only if the corresponding entry in the @code{methods} attribute
3288 of the matcher is enabled.
3290 The implementation of the worker classes returned by the matcher setup
3291 above is as follows:
3294 class MyClassWorker_geta(gdb.xmethod.XMethodWorker):
3295 def get_arg_types(self):
3298 def get_result_type(self, obj):
3299 return gdb.lookup_type('int')
3301 def __call__(self, obj):
3305 class MyClassWorker_plus(gdb.xmethod.XMethodWorker):
3306 def get_arg_types(self):
3307 return gdb.lookup_type('MyClass')
3309 def get_result_type(self, obj):
3310 return gdb.lookup_type('int')
3312 def __call__(self, obj, other):
3313 return obj['a_'] + other['a_']
3316 For @value{GDBN} to actually lookup a xmethod, it has to be
3317 registered with it. The matcher defined above is registered with
3318 @value{GDBN} globally as follows:
3321 gdb.xmethod.register_xmethod_matcher(None, MyClassMatcher())
3324 If an object @code{obj} of type @code{MyClass} is initialized in C@t{++}
3332 then, after loading the Python script defining the xmethod matchers
3333 and workers into @value{GDBN}, invoking the method @code{geta} or using
3334 the operator @code{+} on @code{obj} will invoke the xmethods
3345 Consider another example with a C++ template class:
3352 MyTemplate () : dsize_(10), data_ (new T [10]) @{ @}
3353 ~MyTemplate () @{ delete [] data_; @}
3355 int footprint (void)
3357 return sizeof (T) * dsize_ + sizeof (MyTemplate<T>);
3366 Let us implement an xmethod for the above class which serves as a
3367 replacement for the @code{footprint} method. The full code listing
3368 of the xmethod workers and xmethod matchers is as follows:
3371 class MyTemplateWorker_footprint(gdb.xmethod.XMethodWorker):
3372 def __init__(self, class_type):
3373 self.class_type = class_type
3375 def get_arg_types(self):
3378 def get_result_type(self):
3379 return gdb.lookup_type('int')
3381 def __call__(self, obj):
3382 return (self.class_type.sizeof +
3384 self.class_type.template_argument(0).sizeof)
3387 class MyTemplateMatcher_footprint(gdb.xmethod.XMethodMatcher):
3389 gdb.xmethod.XMethodMatcher.__init__(self, 'MyTemplateMatcher')
3391 def match(self, class_type, method_name):
3392 if (re.match('MyTemplate<[ \t\n]*[_a-zA-Z][ _a-zA-Z0-9]*>',
3394 method_name == 'footprint'):
3395 return MyTemplateWorker_footprint(class_type)
3398 Notice that, in this example, we have not used the @code{methods}
3399 attribute of the matcher as the matcher manages only one xmethod. The
3400 user can enable/disable this xmethod by enabling/disabling the matcher
3403 @node Inferiors In Python
3404 @subsubsection Inferiors In Python
3405 @cindex inferiors in Python
3407 @findex gdb.Inferior
3408 Programs which are being run under @value{GDBN} are called inferiors
3409 (@pxref{Inferiors Connections and Programs}). Python scripts can access
3410 information about and manipulate inferiors controlled by @value{GDBN}
3411 via objects of the @code{gdb.Inferior} class.
3413 The following inferior-related functions are available in the @code{gdb}
3416 @defun gdb.inferiors ()
3417 Return a tuple containing all inferior objects.
3420 @defun gdb.selected_inferior ()
3421 Return an object representing the current inferior.
3424 A @code{gdb.Inferior} object has the following attributes:
3426 @defvar Inferior.num
3427 ID of inferior, as assigned by GDB.
3430 @anchor{gdbpy_inferior_connection}
3431 @defvar Inferior.connection
3432 The @code{gdb.TargetConnection} for this inferior (@pxref{Connections
3433 In Python}), or @code{None} if this inferior has no connection.
3436 @defvar Inferior.connection_num
3437 ID of inferior's connection as assigned by @value{GDBN}, or None if
3438 the inferior is not connected to a target. @xref{Inferiors Connections
3439 and Programs}. This is equivalent to
3440 @code{gdb.Inferior.connection.num} in the case where
3441 @code{gdb.Inferior.connection} is not @code{None}.
3444 @defvar Inferior.pid
3445 Process ID of the inferior, as assigned by the underlying operating
3449 @defvar Inferior.was_attached
3450 Boolean signaling whether the inferior was created using `attach', or
3451 started by @value{GDBN} itself.
3454 @defvar Inferior.main_name
3455 A string holding the name of this inferior's ``main'' function, if it
3456 can be determined. If the name of main is not known, this is
3460 @defvar Inferior.progspace
3461 The inferior's program space. @xref{Progspaces In Python}.
3464 @defvar Inferior.arguments
3465 The inferior's command line arguments, if known. This corresponds to
3466 the @code{set args} and @code{show args} commands. @xref{Arguments}.
3468 When accessed, the value is a string holding all the arguments. The
3469 contents are quoted as they would be when passed to the shell. If
3470 there are no arguments, the value is @code{None}.
3472 Either a string or a sequence of strings can be assigned to this
3473 attribute. When a string is assigned, it is assumed to have any
3474 necessary quoting for the shell; when a sequence is assigned, the
3475 quoting is applied by @value{GDBN}.
3478 A @code{gdb.Inferior} object has the following methods:
3480 @defun Inferior.is_valid ()
3481 Returns @code{True} if the @code{gdb.Inferior} object is valid,
3482 @code{False} if not. A @code{gdb.Inferior} object will become invalid
3483 if the inferior no longer exists within @value{GDBN}. All other
3484 @code{gdb.Inferior} methods will throw an exception if it is invalid
3485 at the time the method is called.
3488 @defun Inferior.threads ()
3489 This method returns a tuple holding all the threads which are valid
3490 when it is called. If there are no valid threads, the method will
3491 return an empty tuple.
3494 @defun Inferior.architecture ()
3495 Return the @code{gdb.Architecture} (@pxref{Architectures In Python})
3496 for this inferior. This represents the architecture of the inferior
3497 as a whole. Some platforms can have multiple architectures in a
3498 single address space, so this may not match the architecture of a
3499 particular frame (@pxref{Frames In Python}).
3502 @anchor{gdbpy_inferior_read_memory}
3503 @findex Inferior.read_memory
3504 @defun Inferior.read_memory (address, length)
3505 Read @var{length} addressable memory units from the inferior, starting at
3506 @var{address}. Returns a buffer object, which behaves much like an array
3507 or a string. It can be modified and given to the
3508 @code{Inferior.write_memory} function. In Python 3, the return
3509 value is a @code{memoryview} object.
3512 @findex Inferior.write_memory
3513 @defun Inferior.write_memory (address, buffer @r{[}, length@r{]})
3514 Write the contents of @var{buffer} to the inferior, starting at
3515 @var{address}. The @var{buffer} parameter must be a Python object
3516 which supports the buffer protocol, i.e., a string, an array or the
3517 object returned from @code{Inferior.read_memory}. If given, @var{length}
3518 determines the number of addressable memory units from @var{buffer} to be
3522 @findex gdb.search_memory
3523 @defun Inferior.search_memory (address, length, pattern)
3524 Search a region of the inferior memory starting at @var{address} with
3525 the given @var{length} using the search pattern supplied in
3526 @var{pattern}. The @var{pattern} parameter must be a Python object
3527 which supports the buffer protocol, i.e., a string, an array or the
3528 object returned from @code{gdb.read_memory}. Returns a Python @code{Long}
3529 containing the address where the pattern was found, or @code{None} if
3530 the pattern could not be found.
3533 @findex Inferior.thread_from_handle
3534 @findex Inferior.thread_from_thread_handle
3535 @defun Inferior.thread_from_handle (handle)
3536 Return the thread object corresponding to @var{handle}, a thread
3537 library specific data structure such as @code{pthread_t} for pthreads
3538 library implementations.
3540 The function @code{Inferior.thread_from_thread_handle} provides
3541 the same functionality, but use of @code{Inferior.thread_from_thread_handle}
3546 The environment that will be passed to the inferior can be changed
3547 from Python by using the following methods. These methods only take
3548 effect when the inferior is started -- they will not affect an
3549 inferior that is already executing.
3551 @findex Inferior.clear_env
3552 @defun Inferior.clear_env ()
3553 Clear the current environment variables that will be passed to this
3557 @findex Inferior.set_env
3558 @defun Inferior.set_env (name, value)
3559 Set the environment variable @var{name} to have the indicated value.
3560 Both parameters must be strings.
3563 @findex Inferior.unset_env
3564 @defun Inferior.unset_env (name)
3565 Unset the environment variable @var{name}. @var{name} must be a
3569 @node Events In Python
3570 @subsubsection Events In Python
3571 @cindex inferior events in Python
3573 @value{GDBN} provides a general event facility so that Python code can be
3574 notified of various state changes, particularly changes that occur in
3577 An @dfn{event} is just an object that describes some state change. The
3578 type of the object and its attributes will vary depending on the details
3579 of the change. All the existing events are described below.
3581 In order to be notified of an event, you must register an event handler
3582 with an @dfn{event registry}. An event registry is an object in the
3583 @code{gdb.events} module which dispatches particular events. A registry
3584 provides methods to register and unregister event handlers:
3586 @defun EventRegistry.connect (object)
3587 Add the given callable @var{object} to the registry. This object will be
3588 called when an event corresponding to this registry occurs.
3591 @defun EventRegistry.disconnect (object)
3592 Remove the given @var{object} from the registry. Once removed, the object
3593 will no longer receive notifications of events.
3599 def exit_handler (event):
3600 print ("event type: exit")
3601 if hasattr (event, 'exit_code'):
3602 print ("exit code: %d" % (event.exit_code))
3604 print ("exit code not available")
3606 gdb.events.exited.connect (exit_handler)
3609 In the above example we connect our handler @code{exit_handler} to the
3610 registry @code{events.exited}. Once connected, @code{exit_handler} gets
3611 called when the inferior exits. The argument @dfn{event} in this example is
3612 of type @code{gdb.ExitedEvent}. As you can see in the example the
3613 @code{ExitedEvent} object has an attribute which indicates the exit code of
3616 Some events can be thread specific when @value{GDBN} is running in
3617 non-stop mode. When represented in Python, these events all extend
3618 @code{gdb.ThreadEvent}. This event is a base class and is never
3619 emitted directly; instead, events which are emitted by this or other
3620 modules might extend this event. Examples of these events are
3621 @code{gdb.BreakpointEvent} and @code{gdb.ContinueEvent}.
3622 @code{gdb.ThreadEvent} holds the following attributes:
3624 @defvar ThreadEvent.inferior_thread
3625 In non-stop mode this attribute will be set to the specific thread which was
3626 involved in the emitted event. Otherwise, it will be set to @code{None}.
3629 The following is a listing of the event registries that are available and
3630 details of the events they emit:
3635 Emits @code{gdb.ContinueEvent}, which extends @code{gdb.ThreadEvent}.
3636 This event indicates that the inferior has been continued after a
3637 stop. For inherited attribute refer to @code{gdb.ThreadEvent} above.
3640 Emits @code{events.ExitedEvent}, which indicates that the inferior has
3641 exited. @code{events.ExitedEvent} has two attributes:
3643 @defvar ExitedEvent.exit_code
3644 An integer representing the exit code, if available, which the inferior
3645 has returned. (The exit code could be unavailable if, for example,
3646 @value{GDBN} detaches from the inferior.) If the exit code is unavailable,
3647 the attribute does not exist.
3650 @defvar ExitedEvent.inferior
3651 A reference to the inferior which triggered the @code{exited} event.
3655 Emits @code{gdb.StopEvent}, which extends @code{gdb.ThreadEvent}.
3657 Indicates that the inferior has stopped. All events emitted by this
3658 registry extend @code{gdb.StopEvent}. As a child of
3659 @code{gdb.ThreadEvent}, @code{gdb.StopEvent} will indicate the stopped
3660 thread when @value{GDBN} is running in non-stop mode. Refer to
3661 @code{gdb.ThreadEvent} above for more details.
3663 Emits @code{gdb.SignalEvent}, which extends @code{gdb.StopEvent}.
3665 This event indicates that the inferior or one of its threads has
3666 received a signal. @code{gdb.SignalEvent} has the following
3669 @defvar SignalEvent.stop_signal
3670 A string representing the signal received by the inferior. A list of possible
3671 signal values can be obtained by running the command @code{info signals} in
3672 the @value{GDBN} command prompt.
3675 Also emits @code{gdb.BreakpointEvent}, which extends
3676 @code{gdb.StopEvent}.
3678 @code{gdb.BreakpointEvent} event indicates that one or more breakpoints have
3679 been hit, and has the following attributes:
3681 @defvar BreakpointEvent.breakpoints
3682 A sequence containing references to all the breakpoints (type
3683 @code{gdb.Breakpoint}) that were hit.
3684 @xref{Breakpoints In Python}, for details of the @code{gdb.Breakpoint} object.
3687 @defvar BreakpointEvent.breakpoint
3688 A reference to the first breakpoint that was hit. This attribute is
3689 maintained for backward compatibility and is now deprecated in favor
3690 of the @code{gdb.BreakpointEvent.breakpoints} attribute.
3693 @item events.new_objfile
3694 Emits @code{gdb.NewObjFileEvent} which indicates that a new object file has
3695 been loaded by @value{GDBN}. @code{gdb.NewObjFileEvent} has one attribute:
3697 @defvar NewObjFileEvent.new_objfile
3698 A reference to the object file (@code{gdb.Objfile}) which has been loaded.
3699 @xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
3702 @item events.free_objfile
3703 Emits @code{gdb.FreeObjFileEvent} which indicates that an object file
3704 is about to be removed from @value{GDBN}. One reason this can happen
3705 is when the inferior calls @code{dlclose}.
3706 @code{gdb.FreeObjFileEvent} has one attribute:
3708 @defvar NewObjFileEvent.objfile
3709 A reference to the object file (@code{gdb.Objfile}) which will be unloaded.
3710 @xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
3713 @item events.clear_objfiles
3714 Emits @code{gdb.ClearObjFilesEvent} which indicates that the list of object
3715 files for a program space has been reset.
3716 @code{gdb.ClearObjFilesEvent} has one attribute:
3718 @defvar ClearObjFilesEvent.progspace
3719 A reference to the program space (@code{gdb.Progspace}) whose objfile list has
3720 been cleared. @xref{Progspaces In Python}.
3723 @item events.inferior_call
3724 Emits events just before and after a function in the inferior is
3725 called by @value{GDBN}. Before an inferior call, this emits an event
3726 of type @code{gdb.InferiorCallPreEvent}, and after an inferior call,
3727 this emits an event of type @code{gdb.InferiorCallPostEvent}.
3730 @tindex gdb.InferiorCallPreEvent
3731 @item @code{gdb.InferiorCallPreEvent}
3732 Indicates that a function in the inferior is about to be called.
3734 @defvar InferiorCallPreEvent.ptid
3735 The thread in which the call will be run.
3738 @defvar InferiorCallPreEvent.address
3739 The location of the function to be called.
3742 @tindex gdb.InferiorCallPostEvent
3743 @item @code{gdb.InferiorCallPostEvent}
3744 Indicates that a function in the inferior has just been called.
3746 @defvar InferiorCallPostEvent.ptid
3747 The thread in which the call was run.
3750 @defvar InferiorCallPostEvent.address
3751 The location of the function that was called.
3755 @item events.memory_changed
3756 Emits @code{gdb.MemoryChangedEvent} which indicates that the memory of the
3757 inferior has been modified by the @value{GDBN} user, for instance via a
3758 command like @w{@code{set *addr = value}}. The event has the following
3761 @defvar MemoryChangedEvent.address
3762 The start address of the changed region.
3765 @defvar MemoryChangedEvent.length
3766 Length in bytes of the changed region.
3769 @item events.register_changed
3770 Emits @code{gdb.RegisterChangedEvent} which indicates that a register in the
3771 inferior has been modified by the @value{GDBN} user.
3773 @defvar RegisterChangedEvent.frame
3774 A gdb.Frame object representing the frame in which the register was modified.
3776 @defvar RegisterChangedEvent.regnum
3777 Denotes which register was modified.
3780 @item events.breakpoint_created
3781 This is emitted when a new breakpoint has been created. The argument
3782 that is passed is the new @code{gdb.Breakpoint} object.
3784 @item events.breakpoint_modified
3785 This is emitted when a breakpoint has been modified in some way. The
3786 argument that is passed is the new @code{gdb.Breakpoint} object.
3788 @item events.breakpoint_deleted
3789 This is emitted when a breakpoint has been deleted. The argument that
3790 is passed is the @code{gdb.Breakpoint} object. When this event is
3791 emitted, the @code{gdb.Breakpoint} object will already be in its
3792 invalid state; that is, the @code{is_valid} method will return
3795 @item events.before_prompt
3796 This event carries no payload. It is emitted each time @value{GDBN}
3797 presents a prompt to the user.
3799 @item events.new_inferior
3800 This is emitted when a new inferior is created. Note that the
3801 inferior is not necessarily running; in fact, it may not even have an
3802 associated executable.
3804 The event is of type @code{gdb.NewInferiorEvent}. This has a single
3807 @defvar NewInferiorEvent.inferior
3808 The new inferior, a @code{gdb.Inferior} object.
3811 @item events.inferior_deleted
3812 This is emitted when an inferior has been deleted. Note that this is
3813 not the same as process exit; it is notified when the inferior itself
3814 is removed, say via @code{remove-inferiors}.
3816 The event is of type @code{gdb.InferiorDeletedEvent}. This has a single
3819 @defvar InferiorDeletedEvent.inferior
3820 The inferior that is being removed, a @code{gdb.Inferior} object.
3823 @item events.new_thread
3824 This is emitted when @value{GDBN} notices a new thread. The event is of
3825 type @code{gdb.NewThreadEvent}, which extends @code{gdb.ThreadEvent}.
3826 This has a single attribute:
3828 @defvar NewThreadEvent.inferior_thread
3832 @item events.gdb_exiting
3833 This is emitted when @value{GDBN} exits. This event is not emitted if
3834 @value{GDBN} exits as a result of an internal error, or after an
3835 unexpected signal. The event is of type @code{gdb.GdbExitingEvent},
3836 which has a single attribute:
3838 @defvar GdbExitingEvent.exit_code
3839 An integer, the value of the exit code @value{GDBN} will return.
3842 @item events.connection_removed
3843 This is emitted when @value{GDBN} removes a connection
3844 (@pxref{Connections In Python}). The event is of type
3845 @code{gdb.ConnectionEvent}. This has a single read-only attribute:
3847 @defvar ConnectionEvent.connection
3848 The @code{gdb.TargetConnection} that is being removed.
3853 @node Threads In Python
3854 @subsubsection Threads In Python
3855 @cindex threads in python
3857 @findex gdb.InferiorThread
3858 Python scripts can access information about, and manipulate inferior threads
3859 controlled by @value{GDBN}, via objects of the @code{gdb.InferiorThread} class.
3861 The following thread-related functions are available in the @code{gdb}
3864 @findex gdb.selected_thread
3865 @defun gdb.selected_thread ()
3866 This function returns the thread object for the selected thread. If there
3867 is no selected thread, this will return @code{None}.
3870 To get the list of threads for an inferior, use the @code{Inferior.threads()}
3871 method. @xref{Inferiors In Python}.
3873 A @code{gdb.InferiorThread} object has the following attributes:
3875 @defvar InferiorThread.name
3876 The name of the thread. If the user specified a name using
3877 @code{thread name}, then this returns that name. Otherwise, if an
3878 OS-supplied name is available, then it is returned. Otherwise, this
3879 returns @code{None}.
3881 This attribute can be assigned to. The new value must be a string
3882 object, which sets the new name, or @code{None}, which removes any
3883 user-specified thread name.
3886 @defvar InferiorThread.num
3887 The per-inferior number of the thread, as assigned by GDB.
3890 @defvar InferiorThread.global_num
3891 The global ID of the thread, as assigned by GDB. You can use this to
3892 make Python breakpoints thread-specific, for example
3893 (@pxref{python_breakpoint_thread,,The Breakpoint.thread attribute}).
3896 @defvar InferiorThread.ptid
3897 ID of the thread, as assigned by the operating system. This attribute is a
3898 tuple containing three integers. The first is the Process ID (PID); the second
3899 is the Lightweight Process ID (LWPID), and the third is the Thread ID (TID).
3900 Either the LWPID or TID may be 0, which indicates that the operating system
3901 does not use that identifier.
3904 @defvar InferiorThread.inferior
3905 The inferior this thread belongs to. This attribute is represented as
3906 a @code{gdb.Inferior} object. This attribute is not writable.
3909 @defvar InferiorThread.details
3910 A string containing target specific thread state information. The
3911 format of this string varies by target. If there is no additional
3912 state information for this thread, then this attribute contains
3915 For example, on a @sc{gnu}/Linux system, a thread that is in the
3916 process of exiting will return the string @samp{Exiting}. For remote
3917 targets the @code{details} string will be obtained with the
3918 @samp{qThreadExtraInfo} remote packet, if the target supports it
3919 (@pxref{qThreadExtraInfo,,@samp{qThreadExtraInfo}}).
3921 @value{GDBN} displays the @code{details} string as part of the
3922 @samp{Target Id} column, in the @code{info threads} output
3923 (@pxref{info_threads,,@samp{info threads}}).
3926 A @code{gdb.InferiorThread} object has the following methods:
3928 @defun InferiorThread.is_valid ()
3929 Returns @code{True} if the @code{gdb.InferiorThread} object is valid,
3930 @code{False} if not. A @code{gdb.InferiorThread} object will become
3931 invalid if the thread exits, or the inferior that the thread belongs
3932 is deleted. All other @code{gdb.InferiorThread} methods will throw an
3933 exception if it is invalid at the time the method is called.
3936 @defun InferiorThread.switch ()
3937 This changes @value{GDBN}'s currently selected thread to the one represented
3941 @defun InferiorThread.is_stopped ()
3942 Return a Boolean indicating whether the thread is stopped.
3945 @defun InferiorThread.is_running ()
3946 Return a Boolean indicating whether the thread is running.
3949 @defun InferiorThread.is_exited ()
3950 Return a Boolean indicating whether the thread is exited.
3953 @defun InferiorThread.handle ()
3954 Return the thread object's handle, represented as a Python @code{bytes}
3955 object. A @code{gdb.Value} representation of the handle may be
3956 constructed via @code{gdb.Value(bufobj, type)} where @var{bufobj} is
3957 the Python @code{bytes} representation of the handle and @var{type} is
3958 a @code{gdb.Type} for the handle type.
3961 @node Recordings In Python
3962 @subsubsection Recordings In Python
3963 @cindex recordings in python
3965 The following recordings-related functions
3966 (@pxref{Process Record and Replay}) are available in the @code{gdb}
3969 @defun gdb.start_recording (@r{[}method@r{]}, @r{[}format@r{]})
3970 Start a recording using the given @var{method} and @var{format}. If
3971 no @var{format} is given, the default format for the recording method
3972 is used. If no @var{method} is given, the default method will be used.
3973 Returns a @code{gdb.Record} object on success. Throw an exception on
3976 The following strings can be passed as @var{method}:
3982 @code{"btrace"}: Possible values for @var{format}: @code{"pt"},
3983 @code{"bts"} or leave out for default format.
3987 @defun gdb.current_recording ()
3988 Access a currently running recording. Return a @code{gdb.Record}
3989 object on success. Return @code{None} if no recording is currently
3993 @defun gdb.stop_recording ()
3994 Stop the current recording. Throw an exception if no recording is
3995 currently active. All record objects become invalid after this call.
3998 A @code{gdb.Record} object has the following attributes:
4000 @defvar Record.method
4001 A string with the current recording method, e.g.@: @code{full} or
4005 @defvar Record.format
4006 A string with the current recording format, e.g.@: @code{bt}, @code{pts} or
4010 @defvar Record.begin
4011 A method specific instruction object representing the first instruction
4016 A method specific instruction object representing the current
4017 instruction, that is not actually part of the recording.
4020 @defvar Record.replay_position
4021 The instruction representing the current replay position. If there is
4022 no replay active, this will be @code{None}.
4025 @defvar Record.instruction_history
4026 A list with all recorded instructions.
4029 @defvar Record.function_call_history
4030 A list with all recorded function call segments.
4033 A @code{gdb.Record} object has the following methods:
4035 @defun Record.goto (instruction)
4036 Move the replay position to the given @var{instruction}.
4039 The common @code{gdb.Instruction} class that recording method specific
4040 instruction objects inherit from, has the following attributes:
4042 @defvar Instruction.pc
4043 An integer representing this instruction's address.
4046 @defvar Instruction.data
4047 A buffer with the raw instruction data. In Python 3, the return value is a
4048 @code{memoryview} object.
4051 @defvar Instruction.decoded
4052 A human readable string with the disassembled instruction.
4055 @defvar Instruction.size
4056 The size of the instruction in bytes.
4059 Additionally @code{gdb.RecordInstruction} has the following attributes:
4061 @defvar RecordInstruction.number
4062 An integer identifying this instruction. @code{number} corresponds to
4063 the numbers seen in @code{record instruction-history}
4064 (@pxref{Process Record and Replay}).
4067 @defvar RecordInstruction.sal
4068 A @code{gdb.Symtab_and_line} object representing the associated symtab
4069 and line of this instruction. May be @code{None} if no debug information is
4073 @defvar RecordInstruction.is_speculative
4074 A boolean indicating whether the instruction was executed speculatively.
4077 If an error occured during recording or decoding a recording, this error is
4078 represented by a @code{gdb.RecordGap} object in the instruction list. It has
4079 the following attributes:
4081 @defvar RecordGap.number
4082 An integer identifying this gap. @code{number} corresponds to the numbers seen
4083 in @code{record instruction-history} (@pxref{Process Record and Replay}).
4086 @defvar RecordGap.error_code
4087 A numerical representation of the reason for the gap. The value is specific to
4088 the current recording method.
4091 @defvar RecordGap.error_string
4092 A human readable string with the reason for the gap.
4095 A @code{gdb.RecordFunctionSegment} object has the following attributes:
4097 @defvar RecordFunctionSegment.number
4098 An integer identifying this function segment. @code{number} corresponds to
4099 the numbers seen in @code{record function-call-history}
4100 (@pxref{Process Record and Replay}).
4103 @defvar RecordFunctionSegment.symbol
4104 A @code{gdb.Symbol} object representing the associated symbol. May be
4105 @code{None} if no debug information is available.
4108 @defvar RecordFunctionSegment.level
4109 An integer representing the function call's stack level. May be
4110 @code{None} if the function call is a gap.
4113 @defvar RecordFunctionSegment.instructions
4114 A list of @code{gdb.RecordInstruction} or @code{gdb.RecordGap} objects
4115 associated with this function call.
4118 @defvar RecordFunctionSegment.up
4119 A @code{gdb.RecordFunctionSegment} object representing the caller's
4120 function segment. If the call has not been recorded, this will be the
4121 function segment to which control returns. If neither the call nor the
4122 return have been recorded, this will be @code{None}.
4125 @defvar RecordFunctionSegment.prev
4126 A @code{gdb.RecordFunctionSegment} object representing the previous
4127 segment of this function call. May be @code{None}.
4130 @defvar RecordFunctionSegment.next
4131 A @code{gdb.RecordFunctionSegment} object representing the next segment of
4132 this function call. May be @code{None}.
4135 The following example demonstrates the usage of these objects and
4136 functions to create a function that will rewind a record to the last
4137 time a function in a different file was executed. This would typically
4138 be used to track the execution of user provided callback functions in a
4139 library which typically are not visible in a back trace.
4143 rec = gdb.current_recording ()
4147 insn = rec.instruction_history
4152 position = insn.index (rec.replay_position)
4156 filename = insn[position].sal.symtab.fullname ()
4160 for i in reversed (insn[:position]):
4162 current = i.sal.symtab.fullname ()
4166 if filename == current:
4173 Another possible application is to write a function that counts the
4174 number of code executions in a given line range. This line range can
4175 contain parts of functions or span across several functions and is not
4176 limited to be contiguous.
4179 def countrange (filename, linerange):
4182 def filter_only (file_name):
4183 for call in gdb.current_recording ().function_call_history:
4185 if file_name in call.symbol.symtab.fullname ():
4190 for c in filter_only (filename):
4191 for i in c.instructions:
4193 if i.sal.line in linerange:
4202 @node CLI Commands In Python
4203 @subsubsection CLI Commands In Python
4205 @cindex CLI commands in python
4206 @cindex commands in python, CLI
4207 @cindex python commands, CLI
4208 You can implement new @value{GDBN} CLI commands in Python. A CLI
4209 command is implemented using an instance of the @code{gdb.Command}
4210 class, most commonly using a subclass.
4212 @defun Command.__init__ (name, command_class @r{[}, completer_class @r{[}, prefix@r{]]})
4213 The object initializer for @code{Command} registers the new command
4214 with @value{GDBN}. This initializer is normally invoked from the
4215 subclass' own @code{__init__} method.
4217 @var{name} is the name of the command. If @var{name} consists of
4218 multiple words, then the initial words are looked for as prefix
4219 commands. In this case, if one of the prefix commands does not exist,
4220 an exception is raised.
4222 There is no support for multi-line commands.
4224 @var{command_class} should be one of the @samp{COMMAND_} constants
4225 defined below. This argument tells @value{GDBN} how to categorize the
4226 new command in the help system.
4228 @var{completer_class} is an optional argument. If given, it should be
4229 one of the @samp{COMPLETE_} constants defined below. This argument
4230 tells @value{GDBN} how to perform completion for this command. If not
4231 given, @value{GDBN} will attempt to complete using the object's
4232 @code{complete} method (see below); if no such method is found, an
4233 error will occur when completion is attempted.
4235 @var{prefix} is an optional argument. If @code{True}, then the new
4236 command is a prefix command; sub-commands of this command may be
4239 The help text for the new command is taken from the Python
4240 documentation string for the command's class, if there is one. If no
4241 documentation string is provided, the default value ``This command is
4242 not documented.'' is used.
4245 @cindex don't repeat Python command
4246 @defun Command.dont_repeat ()
4247 By default, a @value{GDBN} command is repeated when the user enters a
4248 blank line at the command prompt. A command can suppress this
4249 behavior by invoking the @code{dont_repeat} method at some point in
4250 its @code{invoke} method (normally this is done early in case of
4251 exception). This is similar to the user command @code{dont-repeat},
4252 see @ref{Define, dont-repeat}.
4255 @defun Command.invoke (argument, from_tty)
4256 This method is called by @value{GDBN} when this command is invoked.
4258 @var{argument} is a string. It is the argument to the command, after
4259 leading and trailing whitespace has been stripped.
4261 @var{from_tty} is a boolean argument. When true, this means that the
4262 command was entered by the user at the terminal; when false it means
4263 that the command came from elsewhere.
4265 If this method throws an exception, it is turned into a @value{GDBN}
4266 @code{error} call. Otherwise, the return value is ignored.
4268 @findex gdb.string_to_argv
4269 To break @var{argument} up into an argv-like string use
4270 @code{gdb.string_to_argv}. This function behaves identically to
4271 @value{GDBN}'s internal argument lexer @code{buildargv}.
4272 It is recommended to use this for consistency.
4273 Arguments are separated by spaces and may be quoted.
4277 print gdb.string_to_argv ("1 2\ \\\"3 '4 \"5' \"6 '7\"")
4278 ['1', '2 "3', '4 "5', "6 '7"]
4283 @cindex completion of Python commands
4284 @defun Command.complete (text, word)
4285 This method is called by @value{GDBN} when the user attempts
4286 completion on this command. All forms of completion are handled by
4287 this method, that is, the @key{TAB} and @key{M-?} key bindings
4288 (@pxref{Completion}), and the @code{complete} command (@pxref{Help,
4291 The arguments @var{text} and @var{word} are both strings; @var{text}
4292 holds the complete command line up to the cursor's location, while
4293 @var{word} holds the last word of the command line; this is computed
4294 using a word-breaking heuristic.
4296 The @code{complete} method can return several values:
4299 If the return value is a sequence, the contents of the sequence are
4300 used as the completions. It is up to @code{complete} to ensure that the
4301 contents actually do complete the word. A zero-length sequence is
4302 allowed, it means that there were no completions available. Only
4303 string elements of the sequence are used; other elements in the
4304 sequence are ignored.
4307 If the return value is one of the @samp{COMPLETE_} constants defined
4308 below, then the corresponding @value{GDBN}-internal completion
4309 function is invoked, and its result is used.
4312 All other results are treated as though there were no available
4317 When a new command is registered, it must be declared as a member of
4318 some general class of commands. This is used to classify top-level
4319 commands in the on-line help system; note that prefix commands are not
4320 listed under their own category but rather that of their top-level
4321 command. The available classifications are represented by constants
4322 defined in the @code{gdb} module:
4325 @findex COMMAND_NONE
4326 @findex gdb.COMMAND_NONE
4327 @item gdb.COMMAND_NONE
4328 The command does not belong to any particular class. A command in
4329 this category will not be displayed in any of the help categories.
4331 @findex COMMAND_RUNNING
4332 @findex gdb.COMMAND_RUNNING
4333 @item gdb.COMMAND_RUNNING
4334 The command is related to running the inferior. For example,
4335 @code{start}, @code{step}, and @code{continue} are in this category.
4336 Type @kbd{help running} at the @value{GDBN} prompt to see a list of
4337 commands in this category.
4339 @findex COMMAND_DATA
4340 @findex gdb.COMMAND_DATA
4341 @item gdb.COMMAND_DATA
4342 The command is related to data or variables. For example,
4343 @code{call}, @code{find}, and @code{print} are in this category. Type
4344 @kbd{help data} at the @value{GDBN} prompt to see a list of commands
4347 @findex COMMAND_STACK
4348 @findex gdb.COMMAND_STACK
4349 @item gdb.COMMAND_STACK
4350 The command has to do with manipulation of the stack. For example,
4351 @code{backtrace}, @code{frame}, and @code{return} are in this
4352 category. Type @kbd{help stack} at the @value{GDBN} prompt to see a
4353 list of commands in this category.
4355 @findex COMMAND_FILES
4356 @findex gdb.COMMAND_FILES
4357 @item gdb.COMMAND_FILES
4358 This class is used for file-related commands. For example,
4359 @code{file}, @code{list} and @code{section} are in this category.
4360 Type @kbd{help files} at the @value{GDBN} prompt to see a list of
4361 commands in this category.
4363 @findex COMMAND_SUPPORT
4364 @findex gdb.COMMAND_SUPPORT
4365 @item gdb.COMMAND_SUPPORT
4366 This should be used for ``support facilities'', generally meaning
4367 things that are useful to the user when interacting with @value{GDBN},
4368 but not related to the state of the inferior. For example,
4369 @code{help}, @code{make}, and @code{shell} are in this category. Type
4370 @kbd{help support} at the @value{GDBN} prompt to see a list of
4371 commands in this category.
4373 @findex COMMAND_STATUS
4374 @findex gdb.COMMAND_STATUS
4375 @item gdb.COMMAND_STATUS
4376 The command is an @samp{info}-related command, that is, related to the
4377 state of @value{GDBN} itself. For example, @code{info}, @code{macro},
4378 and @code{show} are in this category. Type @kbd{help status} at the
4379 @value{GDBN} prompt to see a list of commands in this category.
4381 @findex COMMAND_BREAKPOINTS
4382 @findex gdb.COMMAND_BREAKPOINTS
4383 @item gdb.COMMAND_BREAKPOINTS
4384 The command has to do with breakpoints. For example, @code{break},
4385 @code{clear}, and @code{delete} are in this category. Type @kbd{help
4386 breakpoints} at the @value{GDBN} prompt to see a list of commands in
4389 @findex COMMAND_TRACEPOINTS
4390 @findex gdb.COMMAND_TRACEPOINTS
4391 @item gdb.COMMAND_TRACEPOINTS
4392 The command has to do with tracepoints. For example, @code{trace},
4393 @code{actions}, and @code{tfind} are in this category. Type
4394 @kbd{help tracepoints} at the @value{GDBN} prompt to see a list of
4395 commands in this category.
4398 @findex gdb.COMMAND_TUI
4399 @item gdb.COMMAND_TUI
4400 The command has to do with the text user interface (@pxref{TUI}).
4401 Type @kbd{help tui} at the @value{GDBN} prompt to see a list of
4402 commands in this category.
4404 @findex COMMAND_USER
4405 @findex gdb.COMMAND_USER
4406 @item gdb.COMMAND_USER
4407 The command is a general purpose command for the user, and typically
4408 does not fit in one of the other categories.
4409 Type @kbd{help user-defined} at the @value{GDBN} prompt to see
4410 a list of commands in this category, as well as the list of gdb macros
4411 (@pxref{Sequences}).
4413 @findex COMMAND_OBSCURE
4414 @findex gdb.COMMAND_OBSCURE
4415 @item gdb.COMMAND_OBSCURE
4416 The command is only used in unusual circumstances, or is not of
4417 general interest to users. For example, @code{checkpoint},
4418 @code{fork}, and @code{stop} are in this category. Type @kbd{help
4419 obscure} at the @value{GDBN} prompt to see a list of commands in this
4422 @findex COMMAND_MAINTENANCE
4423 @findex gdb.COMMAND_MAINTENANCE
4424 @item gdb.COMMAND_MAINTENANCE
4425 The command is only useful to @value{GDBN} maintainers. The
4426 @code{maintenance} and @code{flushregs} commands are in this category.
4427 Type @kbd{help internals} at the @value{GDBN} prompt to see a list of
4428 commands in this category.
4431 A new command can use a predefined completion function, either by
4432 specifying it via an argument at initialization, or by returning it
4433 from the @code{complete} method. These predefined completion
4434 constants are all defined in the @code{gdb} module:
4437 @vindex COMPLETE_NONE
4438 @item gdb.COMPLETE_NONE
4439 This constant means that no completion should be done.
4441 @vindex COMPLETE_FILENAME
4442 @item gdb.COMPLETE_FILENAME
4443 This constant means that filename completion should be performed.
4445 @vindex COMPLETE_LOCATION
4446 @item gdb.COMPLETE_LOCATION
4447 This constant means that location completion should be done.
4448 @xref{Location Specifications}.
4450 @vindex COMPLETE_COMMAND
4451 @item gdb.COMPLETE_COMMAND
4452 This constant means that completion should examine @value{GDBN}
4455 @vindex COMPLETE_SYMBOL
4456 @item gdb.COMPLETE_SYMBOL
4457 This constant means that completion should be done using symbol names
4460 @vindex COMPLETE_EXPRESSION
4461 @item gdb.COMPLETE_EXPRESSION
4462 This constant means that completion should be done on expressions.
4463 Often this means completing on symbol names, but some language
4464 parsers also have support for completing on field names.
4467 The following code snippet shows how a trivial CLI command can be
4468 implemented in Python:
4471 class HelloWorld (gdb.Command):
4472 """Greet the whole world."""
4474 def __init__ (self):
4475 super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
4477 def invoke (self, arg, from_tty):
4478 print ("Hello, World!")
4483 The last line instantiates the class, and is necessary to trigger the
4484 registration of the command with @value{GDBN}. Depending on how the
4485 Python code is read into @value{GDBN}, you may need to import the
4486 @code{gdb} module explicitly.
4488 @node GDB/MI Commands In Python
4489 @subsubsection @sc{gdb/mi} Commands In Python
4491 @cindex MI commands in python
4492 @cindex commands in python, GDB/MI
4493 @cindex python commands, GDB/MI
4494 It is possible to add @sc{gdb/mi} (@pxref{GDB/MI}) commands
4495 implemented in Python. A @sc{gdb/mi} command is implemented using an
4496 instance of the @code{gdb.MICommand} class, most commonly using a
4499 @defun MICommand.__init__ (name)
4500 The object initializer for @code{MICommand} registers the new command
4501 with @value{GDBN}. This initializer is normally invoked from the
4502 subclass' own @code{__init__} method.
4504 @var{name} is the name of the command. It must be a valid name of a
4505 @sc{gdb/mi} command, and in particular must start with a hyphen
4506 (@code{-}). Reusing the name of a built-in @sc{gdb/mi} is not
4507 allowed, and a @code{RuntimeError} will be raised. Using the name
4508 of an @sc{gdb/mi} command previously defined in Python is allowed, the
4509 previous command will be replaced with the new command.
4512 @defun MICommand.invoke (arguments)
4513 This method is called by @value{GDBN} when the new MI command is
4516 @var{arguments} is a list of strings. Note, that @code{--thread}
4517 and @code{--frame} arguments are handled by @value{GDBN} itself therefore
4518 they do not show up in @code{arguments}.
4520 If this method raises an exception, then it is turned into a
4521 @sc{gdb/mi} @code{^error} response. Only @code{gdb.GdbError}
4522 exceptions (or its sub-classes) should be used for reporting errors to
4523 users, any other exception type is treated as a failure of the
4524 @code{invoke} method, and the exception will be printed to the error
4525 stream according to the @kbd{set python print-stack} setting
4526 (@pxref{set_python_print_stack,,@kbd{set python print-stack}}).
4528 If this method returns @code{None}, then the @sc{gdb/mi} command will
4529 return a @code{^done} response with no additional values.
4531 Otherwise, the return value must be a dictionary, which is converted
4532 to a @sc{gdb/mi} @var{result-record} (@pxref{GDB/MI Output Syntax}).
4533 The keys of this dictionary must be strings, and are used as
4534 @var{variable} names in the @var{result-record}, these strings must
4535 comply with the naming rules detailed below. The values of this
4536 dictionary are recursively handled as follows:
4540 If the value is Python sequence or iterator, it is converted to
4541 @sc{gdb/mi} @var{list} with elements converted recursively.
4544 If the value is Python dictionary, it is converted to
4545 @sc{gdb/mi} @var{tuple}. Keys in that dictionary must be strings,
4546 which comply with the @var{variable} naming rules detailed below.
4547 Values are converted recursively.
4550 Otherwise, value is first converted to a Python string using
4551 @code{str ()} and then converted to @sc{gdb/mi} @var{const}.
4554 The strings used for @var{variable} names in the @sc{gdb/mi} output
4555 must follow the following rules; the string must be at least one
4556 character long, the first character must be in the set
4557 @code{[a-zA-Z]}, while every subsequent character must be in the set
4558 @code{[-_a-zA-Z0-9]}.
4561 An instance of @code{MICommand} has the following attributes:
4563 @defvar MICommand.name
4564 A string, the name of this @sc{gdb/mi} command, as was passed to the
4565 @code{__init__} method. This attribute is read-only.
4568 @defvar MICommand.installed
4569 A boolean value indicating if this command is installed ready for a
4570 user to call from the command line. Commands are automatically
4571 installed when they are instantiated, after which this attribute will
4574 If later, a new command is created with the same name, then the
4575 original command will become uninstalled, and this attribute will be
4578 This attribute is read-write, setting this attribute to @code{False}
4579 will uninstall the command, removing it from the set of available
4580 commands. Setting this attribute to @code{True} will install the
4581 command for use. If there is already a Python command with this name
4582 installed, the currently installed command will be uninstalled, and
4583 this command installed in its stead.
4586 The following code snippet shows how some trivial MI commands can be
4587 implemented in Python:
4590 class MIEcho(gdb.MICommand):
4591 """Echo arguments passed to the command."""
4593 def __init__(self, name, mode):
4595 super(MIEcho, self).__init__(name)
4597 def invoke(self, argv):
4598 if self._mode == 'dict':
4599 return @{ 'dict': @{ 'argv' : argv @} @}
4600 elif self._mode == 'list':
4601 return @{ 'list': argv @}
4603 return @{ 'string': ", ".join(argv) @}
4606 MIEcho("-echo-dict", "dict")
4607 MIEcho("-echo-list", "list")
4608 MIEcho("-echo-string", "string")
4611 The last three lines instantiate the class three times, creating three
4612 new @sc{gdb/mi} commands @code{-echo-dict}, @code{-echo-list}, and
4613 @code{-echo-string}. Each time a subclass of @code{gdb.MICommand} is
4614 instantiated, the new command is automatically registered with
4617 Depending on how the Python code is read into @value{GDBN}, you may
4618 need to import the @code{gdb} module explicitly.
4620 The following example shows a @value{GDBN} session in which the above
4621 commands have been added:
4625 -echo-dict abc def ghi
4626 ^done,dict=@{argv=["abc","def","ghi"]@}
4628 -echo-list abc def ghi
4629 ^done,list=["abc","def","ghi"]
4631 -echo-string abc def ghi
4632 ^done,string="abc, def, ghi"
4636 Conversely, it is possible to execute @sc{gdb/mi} commands from
4637 Python, with the results being a Python object and not a
4638 specially-formatted string. This is done with the
4639 @code{gdb.execute_mi} function.
4641 @findex gdb.execute_mi
4642 @defun gdb.execute_mi (command @r{[}, arg @r{]}@dots{})
4643 Invoke a @sc{gdb/mi} command. @var{command} is the name of the
4644 command, a string. The arguments, @var{arg}, are passed to the
4645 command. Each argument must also be a string.
4647 This function returns a Python dictionary whose contents reflect the
4648 corresponding @sc{GDB/MI} command's output. Refer to the
4649 documentation for these commands for details. Lists are represented
4650 as Python lists, and tuples are represented as Python dictionaries.
4652 If the command fails, it will raise a Python exception.
4655 Here is how this works using the commands from the example above:
4658 (@value{GDBP}) python print(gdb.execute_mi("-echo-dict", "abc", "def", "ghi"))
4659 @{'dict': @{'argv': ['abc', 'def', 'ghi']@}@}
4660 (@value{GDBP}) python print(gdb.execute_mi("-echo-list", "abc", "def", "ghi"))
4661 @{'list': ['abc', 'def', 'ghi']@}
4662 (@value{GDBP}) python print(gdb.execute_mi("-echo-string", "abc", "def", "ghi"))
4663 @{'string': 'abc, def, ghi'@}
4666 @node Parameters In Python
4667 @subsubsection Parameters In Python
4669 @cindex parameters in python
4670 @cindex python parameters
4671 @tindex gdb.Parameter
4673 You can implement new @value{GDBN} parameters using Python. A new
4674 parameter is implemented as an instance of the @code{gdb.Parameter}
4677 Parameters are exposed to the user via the @code{set} and
4678 @code{show} commands. @xref{Help}.
4680 There are many parameters that already exist and can be set in
4681 @value{GDBN}. Two examples are: @code{set follow fork} and
4682 @code{set charset}. Setting these parameters influences certain
4683 behavior in @value{GDBN}. Similarly, you can define parameters that
4684 can be used to influence behavior in custom Python scripts and commands.
4686 @defun Parameter.__init__ (name, command_class, parameter_class @r{[}, enum_sequence@r{]})
4687 The object initializer for @code{Parameter} registers the new
4688 parameter with @value{GDBN}. This initializer is normally invoked
4689 from the subclass' own @code{__init__} method.
4691 @var{name} is the name of the new parameter. If @var{name} consists
4692 of multiple words, then the initial words are looked for as prefix
4693 parameters. An example of this can be illustrated with the
4694 @code{set print} set of parameters. If @var{name} is
4695 @code{print foo}, then @code{print} will be searched as the prefix
4696 parameter. In this case the parameter can subsequently be accessed in
4697 @value{GDBN} as @code{set print foo}.
4699 If @var{name} consists of multiple words, and no prefix parameter group
4700 can be found, an exception is raised.
4702 @var{command_class} should be one of the @samp{COMMAND_} constants
4703 (@pxref{CLI Commands In Python}). This argument tells @value{GDBN} how to
4704 categorize the new parameter in the help system.
4706 @var{parameter_class} should be one of the @samp{PARAM_} constants
4707 defined below. This argument tells @value{GDBN} the type of the new
4708 parameter; this information is used for input validation and
4711 If @var{parameter_class} is @code{PARAM_ENUM}, then
4712 @var{enum_sequence} must be a sequence of strings. These strings
4713 represent the possible values for the parameter.
4715 If @var{parameter_class} is not @code{PARAM_ENUM}, then the presence
4716 of a fourth argument will cause an exception to be thrown.
4718 The help text for the new parameter includes the Python documentation
4719 string from the parameter's class, if there is one. If there is no
4720 documentation string, a default value is used. The documentation
4721 string is included in the output of the parameters @code{help set} and
4722 @code{help show} commands, and should be written taking this into
4726 @defvar Parameter.set_doc
4727 If this attribute exists, and is a string, then its value is used as
4728 the first part of the help text for this parameter's @code{set}
4729 command. The second part of the help text is taken from the
4730 documentation string for the parameter's class, if there is one.
4732 The value of @code{set_doc} should give a brief summary specific to
4733 the set action, this text is only displayed when the user runs the
4734 @code{help set} command for this parameter. The class documentation
4735 should be used to give a fuller description of what the parameter
4736 does, this text is displayed for both the @code{help set} and
4737 @code{help show} commands.
4739 The @code{set_doc} value is examined when @code{Parameter.__init__} is
4740 invoked; subsequent changes have no effect.
4743 @defvar Parameter.show_doc
4744 If this attribute exists, and is a string, then its value is used as
4745 the first part of the help text for this parameter's @code{show}
4746 command. The second part of the help text is taken from the
4747 documentation string for the parameter's class, if there is one.
4749 The value of @code{show_doc} should give a brief summary specific to
4750 the show action, this text is only displayed when the user runs the
4751 @code{help show} command for this parameter. The class documentation
4752 should be used to give a fuller description of what the parameter
4753 does, this text is displayed for both the @code{help set} and
4754 @code{help show} commands.
4756 The @code{show_doc} value is examined when @code{Parameter.__init__}
4757 is invoked; subsequent changes have no effect.
4760 @defvar Parameter.value
4761 The @code{value} attribute holds the underlying value of the
4762 parameter. It can be read and assigned to just as any other
4763 attribute. @value{GDBN} does validation when assignments are made.
4766 There are two methods that may be implemented in any @code{Parameter}
4769 @defun Parameter.get_set_string (self)
4770 If this method exists, @value{GDBN} will call it when a
4771 @var{parameter}'s value has been changed via the @code{set} API (for
4772 example, @kbd{set foo off}). The @code{value} attribute has already
4773 been populated with the new value and may be used in output. This
4774 method must return a string. If the returned string is not empty,
4775 @value{GDBN} will present it to the user.
4777 If this method raises the @code{gdb.GdbError} exception
4778 (@pxref{Exception Handling}), then @value{GDBN} will print the
4779 exception's string and the @code{set} command will fail. Note,
4780 however, that the @code{value} attribute will not be reset in this
4781 case. So, if your parameter must validate values, it should store the
4782 old value internally and reset the exposed value, like so:
4785 class ExampleParam (gdb.Parameter):
4786 def __init__ (self, name):
4787 super (ExampleParam, self).__init__ (name,
4791 self.saved_value = True
4794 def get_set_string (self):
4795 if not self.validate():
4796 self.value = self.saved_value
4797 raise gdb.GdbError('Failed to validate')
4798 self.saved_value = self.value
4803 @defun Parameter.get_show_string (self, svalue)
4804 @value{GDBN} will call this method when a @var{parameter}'s
4805 @code{show} API has been invoked (for example, @kbd{show foo}). The
4806 argument @code{svalue} receives the string representation of the
4807 current value. This method must return a string.
4810 When a new parameter is defined, its type must be specified. The
4811 available types are represented by constants defined in the @code{gdb}
4815 @findex PARAM_BOOLEAN
4816 @findex gdb.PARAM_BOOLEAN
4817 @item gdb.PARAM_BOOLEAN
4818 The value is a plain boolean. The Python boolean values, @code{True}
4819 and @code{False} are the only valid values.
4821 @findex PARAM_AUTO_BOOLEAN
4822 @findex gdb.PARAM_AUTO_BOOLEAN
4823 @item gdb.PARAM_AUTO_BOOLEAN
4824 The value has three possible states: true, false, and @samp{auto}. In
4825 Python, true and false are represented using boolean constants, and
4826 @samp{auto} is represented using @code{None}.
4828 @findex PARAM_UINTEGER
4829 @findex gdb.PARAM_UINTEGER
4830 @item gdb.PARAM_UINTEGER
4831 The value is an unsigned integer. The value of @code{None} should be
4832 interpreted to mean ``unlimited'' (literal @code{'unlimited'} can also
4833 be used to set that value), and the value of 0 is reserved and should
4836 @findex PARAM_INTEGER
4837 @findex gdb.PARAM_INTEGER
4838 @item gdb.PARAM_INTEGER
4839 The value is a signed integer. The value of @code{None} should be
4840 interpreted to mean ``unlimited'' (literal @code{'unlimited'} can also
4841 be used to set that value), and the value of 0 is reserved and should
4844 @findex PARAM_STRING
4845 @findex gdb.PARAM_STRING
4846 @item gdb.PARAM_STRING
4847 The value is a string. When the user modifies the string, any escape
4848 sequences, such as @samp{\t}, @samp{\f}, and octal escapes, are
4849 translated into corresponding characters and encoded into the current
4852 @findex PARAM_STRING_NOESCAPE
4853 @findex gdb.PARAM_STRING_NOESCAPE
4854 @item gdb.PARAM_STRING_NOESCAPE
4855 The value is a string. When the user modifies the string, escapes are
4856 passed through untranslated.
4858 @findex PARAM_OPTIONAL_FILENAME
4859 @findex gdb.PARAM_OPTIONAL_FILENAME
4860 @item gdb.PARAM_OPTIONAL_FILENAME
4861 The value is a either a filename (a string), or @code{None}.
4863 @findex PARAM_FILENAME
4864 @findex gdb.PARAM_FILENAME
4865 @item gdb.PARAM_FILENAME
4866 The value is a filename. This is just like
4867 @code{PARAM_STRING_NOESCAPE}, but uses file names for completion.
4869 @findex PARAM_ZINTEGER
4870 @findex gdb.PARAM_ZINTEGER
4871 @item gdb.PARAM_ZINTEGER
4872 The value is a signed integer. This is like @code{PARAM_INTEGER},
4873 except that 0 is allowed and the value of @code{None} is not supported.
4875 @findex PARAM_ZUINTEGER
4876 @findex gdb.PARAM_ZUINTEGER
4877 @item gdb.PARAM_ZUINTEGER
4878 The value is an unsigned integer. This is like @code{PARAM_UINTEGER},
4879 except that 0 is allowed and the value of @code{None} is not supported.
4881 @findex PARAM_ZUINTEGER_UNLIMITED
4882 @findex gdb.PARAM_ZUINTEGER_UNLIMITED
4883 @item gdb.PARAM_ZUINTEGER_UNLIMITED
4884 The value is a signed integer. This is like @code{PARAM_INTEGER}
4885 including that the value of @code{None} should be interpreted to mean
4886 ``unlimited'' (literal @code{'unlimited'} can also be used to set that
4887 value), except that 0 is allowed, and the value cannot be negative,
4888 except the special value -1 is returned for the setting of ``unlimited''.
4891 @findex gdb.PARAM_ENUM
4892 @item gdb.PARAM_ENUM
4893 The value is a string, which must be one of a collection string
4894 constants provided when the parameter is created.
4897 @node Functions In Python
4898 @subsubsection Writing new convenience functions
4900 @cindex writing convenience functions
4901 @cindex convenience functions in python
4902 @cindex python convenience functions
4903 @tindex gdb.Function
4905 You can implement new convenience functions (@pxref{Convenience Vars})
4906 in Python. A convenience function is an instance of a subclass of the
4907 class @code{gdb.Function}.
4909 @defun Function.__init__ (name)
4910 The initializer for @code{Function} registers the new function with
4911 @value{GDBN}. The argument @var{name} is the name of the function,
4912 a string. The function will be visible to the user as a convenience
4913 variable of type @code{internal function}, whose name is the same as
4914 the given @var{name}.
4916 The documentation for the new function is taken from the documentation
4917 string for the new class.
4920 @defun Function.invoke (*args)
4921 When a convenience function is evaluated, its arguments are converted
4922 to instances of @code{gdb.Value}, and then the function's
4923 @code{invoke} method is called. Note that @value{GDBN} does not
4924 predetermine the arity of convenience functions. Instead, all
4925 available arguments are passed to @code{invoke}, following the
4926 standard Python calling convention. In particular, a convenience
4927 function can have default values for parameters without ill effect.
4929 The return value of this method is used as its value in the enclosing
4930 expression. If an ordinary Python value is returned, it is converted
4931 to a @code{gdb.Value} following the usual rules.
4934 The following code snippet shows how a trivial convenience function can
4935 be implemented in Python:
4938 class Greet (gdb.Function):
4939 """Return string to greet someone.
4940 Takes a name as argument."""
4942 def __init__ (self):
4943 super (Greet, self).__init__ ("greet")
4945 def invoke (self, name):
4946 return "Hello, %s!" % name.string ()
4951 The last line instantiates the class, and is necessary to trigger the
4952 registration of the function with @value{GDBN}. Depending on how the
4953 Python code is read into @value{GDBN}, you may need to import the
4954 @code{gdb} module explicitly.
4956 Now you can use the function in an expression:
4959 (gdb) print $greet("Bob")
4963 @node Progspaces In Python
4964 @subsubsection Program Spaces In Python
4966 @cindex progspaces in python
4967 @tindex gdb.Progspace
4969 A program space, or @dfn{progspace}, represents a symbolic view
4970 of an address space.
4971 It consists of all of the objfiles of the program.
4972 @xref{Objfiles In Python}.
4973 @xref{Inferiors Connections and Programs, program spaces}, for more details
4974 about program spaces.
4976 The following progspace-related functions are available in the
4979 @findex gdb.current_progspace
4980 @defun gdb.current_progspace ()
4981 This function returns the program space of the currently selected inferior.
4982 @xref{Inferiors Connections and Programs}. This is identical to
4983 @code{gdb.selected_inferior().progspace} (@pxref{Inferiors In Python}) and is
4984 included for historical compatibility.
4987 @findex gdb.progspaces
4988 @defun gdb.progspaces ()
4989 Return a sequence of all the progspaces currently known to @value{GDBN}.
4992 Each progspace is represented by an instance of the @code{gdb.Progspace}
4995 @defvar Progspace.filename
4996 The file name of the progspace as a string.
4999 @defvar Progspace.pretty_printers
5000 The @code{pretty_printers} attribute is a list of functions. It is
5001 used to look up pretty-printers. A @code{Value} is passed to each
5002 function in order; if the function returns @code{None}, then the
5003 search continues. Otherwise, the return value should be an object
5004 which is used to format the value. @xref{Pretty Printing API}, for more
5008 @defvar Progspace.type_printers
5009 The @code{type_printers} attribute is a list of type printer objects.
5010 @xref{Type Printing API}, for more information.
5013 @defvar Progspace.frame_filters
5014 The @code{frame_filters} attribute is a dictionary of frame filter
5015 objects. @xref{Frame Filter API}, for more information.
5018 A program space has the following methods:
5020 @findex Progspace.block_for_pc
5021 @defun Progspace.block_for_pc (pc)
5022 Return the innermost @code{gdb.Block} containing the given @var{pc}
5023 value. If the block cannot be found for the @var{pc} value specified,
5024 the function will return @code{None}.
5027 @findex Progspace.find_pc_line
5028 @defun Progspace.find_pc_line (pc)
5029 Return the @code{gdb.Symtab_and_line} object corresponding to the
5030 @var{pc} value. @xref{Symbol Tables In Python}. If an invalid value
5031 of @var{pc} is passed as an argument, then the @code{symtab} and
5032 @code{line} attributes of the returned @code{gdb.Symtab_and_line}
5033 object will be @code{None} and 0 respectively.
5036 @findex Progspace.is_valid
5037 @defun Progspace.is_valid ()
5038 Returns @code{True} if the @code{gdb.Progspace} object is valid,
5039 @code{False} if not. A @code{gdb.Progspace} object can become invalid
5040 if the program space file it refers to is not referenced by any
5041 inferior. All other @code{gdb.Progspace} methods will throw an
5042 exception if it is invalid at the time the method is called.
5045 @findex Progspace.objfiles
5046 @defun Progspace.objfiles ()
5047 Return a sequence of all the objfiles referenced by this program
5048 space. @xref{Objfiles In Python}.
5051 @findex Progspace.solib_name
5052 @defun Progspace.solib_name (address)
5053 Return the name of the shared library holding the given @var{address}
5054 as a string, or @code{None}.
5057 One may add arbitrary attributes to @code{gdb.Progspace} objects
5058 in the usual Python way.
5059 This is useful if, for example, one needs to do some extra record keeping
5060 associated with the program space.
5062 In this contrived example, we want to perform some processing when
5063 an objfile with a certain symbol is loaded, but we only want to do
5064 this once because it is expensive. To achieve this we record the results
5065 with the program space because we can't predict when the desired objfile
5070 def clear_objfiles_handler(event):
5071 event.progspace.expensive_computation = None
5072 def expensive(symbol):
5073 """A mock routine to perform an "expensive" computation on symbol."""
5074 print ("Computing the answer to the ultimate question ...")
5076 def new_objfile_handler(event):
5077 objfile = event.new_objfile
5078 progspace = objfile.progspace
5079 if not hasattr(progspace, 'expensive_computation') or \
5080 progspace.expensive_computation is None:
5081 # We use 'main' for the symbol to keep the example simple.
5082 # Note: There's no current way to constrain the lookup
5084 symbol = gdb.lookup_global_symbol('main')
5085 if symbol is not None:
5086 progspace.expensive_computation = expensive(symbol)
5087 gdb.events.clear_objfiles.connect(clear_objfiles_handler)
5088 gdb.events.new_objfile.connect(new_objfile_handler)
5090 (gdb) file /tmp/hello
5091 Reading symbols from /tmp/hello...
5092 Computing the answer to the ultimate question ...
5093 (gdb) python print gdb.current_progspace().expensive_computation
5096 Starting program: /tmp/hello
5098 [Inferior 1 (process 4242) exited normally]
5101 @node Objfiles In Python
5102 @subsubsection Objfiles In Python
5104 @cindex objfiles in python
5107 @value{GDBN} loads symbols for an inferior from various
5108 symbol-containing files (@pxref{Files}). These include the primary
5109 executable file, any shared libraries used by the inferior, and any
5110 separate debug info files (@pxref{Separate Debug Files}).
5111 @value{GDBN} calls these symbol-containing files @dfn{objfiles}.
5113 The following objfile-related functions are available in the
5116 @findex gdb.current_objfile
5117 @defun gdb.current_objfile ()
5118 When auto-loading a Python script (@pxref{Python Auto-loading}), @value{GDBN}
5119 sets the ``current objfile'' to the corresponding objfile. This
5120 function returns the current objfile. If there is no current objfile,
5121 this function returns @code{None}.
5124 @findex gdb.objfiles
5125 @defun gdb.objfiles ()
5126 Return a sequence of objfiles referenced by the current program space.
5127 @xref{Objfiles In Python}, and @ref{Progspaces In Python}. This is identical
5128 to @code{gdb.selected_inferior().progspace.objfiles()} and is included for
5129 historical compatibility.
5132 @findex gdb.lookup_objfile
5133 @defun gdb.lookup_objfile (name @r{[}, by_build_id@r{]})
5134 Look up @var{name}, a file name or build ID, in the list of objfiles
5135 for the current program space (@pxref{Progspaces In Python}).
5136 If the objfile is not found throw the Python @code{ValueError} exception.
5138 If @var{name} is a relative file name, then it will match any
5139 source file name with the same trailing components. For example, if
5140 @var{name} is @samp{gcc/expr.c}, then it will match source file
5141 name of @file{/build/trunk/gcc/expr.c}, but not
5142 @file{/build/trunk/libcpp/expr.c} or @file{/build/trunk/gcc/x-expr.c}.
5144 If @var{by_build_id} is provided and is @code{True} then @var{name}
5145 is the build ID of the objfile. Otherwise, @var{name} is a file name.
5146 This is supported only on some operating systems, notably those which use
5147 the ELF format for binary files and the @sc{gnu} Binutils. For more details
5148 about this feature, see the description of the @option{--build-id}
5149 command-line option in @ref{Options, , Command Line Options, ld,
5153 Each objfile is represented by an instance of the @code{gdb.Objfile}
5156 @defvar Objfile.filename
5157 The file name of the objfile as a string, with symbolic links resolved.
5159 The value is @code{None} if the objfile is no longer valid.
5160 See the @code{gdb.Objfile.is_valid} method, described below.
5163 @defvar Objfile.username
5164 The file name of the objfile as specified by the user as a string.
5166 The value is @code{None} if the objfile is no longer valid.
5167 See the @code{gdb.Objfile.is_valid} method, described below.
5170 @defvar Objfile.is_file
5171 An objfile often comes from an ordinary file, but in some cases it may
5172 be constructed from the contents of memory. This attribute is
5173 @code{True} for file-backed objfiles, and @code{False} for other
5177 @defvar Objfile.owner
5178 For separate debug info objfiles this is the corresponding @code{gdb.Objfile}
5179 object that debug info is being provided for.
5180 Otherwise this is @code{None}.
5181 Separate debug info objfiles are added with the
5182 @code{gdb.Objfile.add_separate_debug_file} method, described below.
5185 @defvar Objfile.build_id
5186 The build ID of the objfile as a string.
5187 If the objfile does not have a build ID then the value is @code{None}.
5189 This is supported only on some operating systems, notably those which use
5190 the ELF format for binary files and the @sc{gnu} Binutils. For more details
5191 about this feature, see the description of the @option{--build-id}
5192 command-line option in @ref{Options, , Command Line Options, ld,
5196 @defvar Objfile.progspace
5197 The containing program space of the objfile as a @code{gdb.Progspace}
5198 object. @xref{Progspaces In Python}.
5201 @defvar Objfile.pretty_printers
5202 The @code{pretty_printers} attribute is a list of functions. It is
5203 used to look up pretty-printers. A @code{Value} is passed to each
5204 function in order; if the function returns @code{None}, then the
5205 search continues. Otherwise, the return value should be an object
5206 which is used to format the value. @xref{Pretty Printing API}, for more
5210 @defvar Objfile.type_printers
5211 The @code{type_printers} attribute is a list of type printer objects.
5212 @xref{Type Printing API}, for more information.
5215 @defvar Objfile.frame_filters
5216 The @code{frame_filters} attribute is a dictionary of frame filter
5217 objects. @xref{Frame Filter API}, for more information.
5220 One may add arbitrary attributes to @code{gdb.Objfile} objects
5221 in the usual Python way.
5222 This is useful if, for example, one needs to do some extra record keeping
5223 associated with the objfile.
5225 In this contrived example we record the time when @value{GDBN}
5231 def new_objfile_handler(event):
5232 # Set the time_loaded attribute of the new objfile.
5233 event.new_objfile.time_loaded = datetime.datetime.today()
5234 gdb.events.new_objfile.connect(new_objfile_handler)
5237 Reading symbols from ./hello...
5238 (gdb) python print gdb.objfiles()[0].time_loaded
5239 2014-10-09 11:41:36.770345
5242 A @code{gdb.Objfile} object has the following methods:
5244 @defun Objfile.is_valid ()
5245 Returns @code{True} if the @code{gdb.Objfile} object is valid,
5246 @code{False} if not. A @code{gdb.Objfile} object can become invalid
5247 if the object file it refers to is not loaded in @value{GDBN} any
5248 longer. All other @code{gdb.Objfile} methods will throw an exception
5249 if it is invalid at the time the method is called.
5252 @defun Objfile.add_separate_debug_file (file)
5253 Add @var{file} to the list of files that @value{GDBN} will search for
5254 debug information for the objfile.
5255 This is useful when the debug info has been removed from the program
5256 and stored in a separate file. @value{GDBN} has built-in support for
5257 finding separate debug info files (@pxref{Separate Debug Files}), but if
5258 the file doesn't live in one of the standard places that @value{GDBN}
5259 searches then this function can be used to add a debug info file
5260 from a different place.
5263 @defun Objfile.lookup_global_symbol (name @r{[}, domain@r{]})
5264 Search for a global symbol named @var{name} in this objfile. Optionally, the
5265 search scope can be restricted with the @var{domain} argument.
5266 The @var{domain} argument must be a domain constant defined in the @code{gdb}
5267 module and described in @ref{Symbols In Python}. This function is similar to
5268 @code{gdb.lookup_global_symbol}, except that the search is limited to this
5271 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
5275 @defun Objfile.lookup_static_symbol (name @r{[}, domain@r{]})
5276 Like @code{Objfile.lookup_global_symbol}, but searches for a global
5277 symbol with static linkage named @var{name} in this objfile.
5280 @node Frames In Python
5281 @subsubsection Accessing inferior stack frames from Python
5283 @cindex frames in python
5284 When the debugged program stops, @value{GDBN} is able to analyze its call
5285 stack (@pxref{Frames,,Stack frames}). The @code{gdb.Frame} class
5286 represents a frame in the stack. A @code{gdb.Frame} object is only valid
5287 while its corresponding frame exists in the inferior's stack. If you try
5288 to use an invalid frame object, @value{GDBN} will throw a @code{gdb.error}
5289 exception (@pxref{Exception Handling}).
5291 Two @code{gdb.Frame} objects can be compared for equality with the @code{==}
5295 (@value{GDBP}) python print gdb.newest_frame() == gdb.selected_frame ()
5299 The following frame-related functions are available in the @code{gdb} module:
5301 @findex gdb.selected_frame
5302 @defun gdb.selected_frame ()
5303 Return the selected frame object. (@pxref{Selection,,Selecting a Frame}).
5306 @findex gdb.newest_frame
5307 @defun gdb.newest_frame ()
5308 Return the newest frame object for the selected thread.
5311 @defun gdb.frame_stop_reason_string (reason)
5312 Return a string explaining the reason why @value{GDBN} stopped unwinding
5313 frames, as expressed by the given @var{reason} code (an integer, see the
5314 @code{unwind_stop_reason} method further down in this section).
5317 @findex gdb.invalidate_cached_frames
5318 @defun gdb.invalidate_cached_frames
5319 @value{GDBN} internally keeps a cache of the frames that have been
5320 unwound. This function invalidates this cache.
5322 This function should not generally be called by ordinary Python code.
5323 It is documented for the sake of completeness.
5326 A @code{gdb.Frame} object has the following methods:
5328 @defun Frame.is_valid ()
5329 Returns true if the @code{gdb.Frame} object is valid, false if not.
5330 A frame object can become invalid if the frame it refers to doesn't
5331 exist anymore in the inferior. All @code{gdb.Frame} methods will throw
5332 an exception if it is invalid at the time the method is called.
5335 @defun Frame.name ()
5336 Returns the function name of the frame, or @code{None} if it can't be
5340 @defun Frame.architecture ()
5341 Returns the @code{gdb.Architecture} object corresponding to the frame's
5342 architecture. @xref{Architectures In Python}.
5345 @defun Frame.type ()
5346 Returns the type of the frame. The value can be one of:
5348 @item gdb.NORMAL_FRAME
5349 An ordinary stack frame.
5351 @item gdb.DUMMY_FRAME
5352 A fake stack frame that was created by @value{GDBN} when performing an
5353 inferior function call.
5355 @item gdb.INLINE_FRAME
5356 A frame representing an inlined function. The function was inlined
5357 into a @code{gdb.NORMAL_FRAME} that is older than this one.
5359 @item gdb.TAILCALL_FRAME
5360 A frame representing a tail call. @xref{Tail Call Frames}.
5362 @item gdb.SIGTRAMP_FRAME
5363 A signal trampoline frame. This is the frame created by the OS when
5364 it calls into a signal handler.
5366 @item gdb.ARCH_FRAME
5367 A fake stack frame representing a cross-architecture call.
5369 @item gdb.SENTINEL_FRAME
5370 This is like @code{gdb.NORMAL_FRAME}, but it is only used for the
5375 @defun Frame.unwind_stop_reason ()
5376 Return an integer representing the reason why it's not possible to find
5377 more frames toward the outermost frame. Use
5378 @code{gdb.frame_stop_reason_string} to convert the value returned by this
5379 function to a string. The value can be one of:
5382 @item gdb.FRAME_UNWIND_NO_REASON
5383 No particular reason (older frames should be available).
5385 @item gdb.FRAME_UNWIND_NULL_ID
5386 The previous frame's analyzer returns an invalid result. This is no
5387 longer used by @value{GDBN}, and is kept only for backward
5390 @item gdb.FRAME_UNWIND_OUTERMOST
5391 This frame is the outermost.
5393 @item gdb.FRAME_UNWIND_UNAVAILABLE
5394 Cannot unwind further, because that would require knowing the
5395 values of registers or memory that have not been collected.
5397 @item gdb.FRAME_UNWIND_INNER_ID
5398 This frame ID looks like it ought to belong to a NEXT frame,
5399 but we got it for a PREV frame. Normally, this is a sign of
5400 unwinder failure. It could also indicate stack corruption.
5402 @item gdb.FRAME_UNWIND_SAME_ID
5403 This frame has the same ID as the previous one. That means
5404 that unwinding further would almost certainly give us another
5405 frame with exactly the same ID, so break the chain. Normally,
5406 this is a sign of unwinder failure. It could also indicate
5409 @item gdb.FRAME_UNWIND_NO_SAVED_PC
5410 The frame unwinder did not find any saved PC, but we needed
5411 one to unwind further.
5413 @item gdb.FRAME_UNWIND_MEMORY_ERROR
5414 The frame unwinder caused an error while trying to access memory.
5416 @item gdb.FRAME_UNWIND_FIRST_ERROR
5417 Any stop reason greater or equal to this value indicates some kind
5418 of error. This special value facilitates writing code that tests
5419 for errors in unwinding in a way that will work correctly even if
5420 the list of the other values is modified in future @value{GDBN}
5421 versions. Using it, you could write:
5423 reason = gdb.selected_frame().unwind_stop_reason ()
5424 reason_str = gdb.frame_stop_reason_string (reason)
5425 if reason >= gdb.FRAME_UNWIND_FIRST_ERROR:
5426 print ("An error occured: %s" % reason_str)
5433 Returns the frame's resume address.
5436 @defun Frame.block ()
5437 Return the frame's code block. @xref{Blocks In Python}. If the frame
5438 does not have a block -- for example, if there is no debugging
5439 information for the code in question -- then this will throw an
5443 @defun Frame.function ()
5444 Return the symbol for the function corresponding to this frame.
5445 @xref{Symbols In Python}.
5448 @defun Frame.older ()
5449 Return the frame that called this frame. If this is the oldest frame,
5453 @defun Frame.newer ()
5454 Return the frame called by this frame. If this is the newest frame,
5458 @defun Frame.find_sal ()
5459 Return the frame's symtab and line object.
5460 @xref{Symbol Tables In Python}.
5463 @anchor{gdbpy_frame_read_register}
5464 @defun Frame.read_register (register)
5465 Return the value of @var{register} in this frame. Returns a
5466 @code{Gdb.Value} object. Throws an exception if @var{register} does
5467 not exist. The @var{register} argument must be one of the following:
5470 A string that is the name of a valid register (e.g., @code{'sp'} or
5473 A @code{gdb.RegisterDescriptor} object (@pxref{Registers In Python}).
5475 A @value{GDBN} internal, platform specific number. Using these
5476 numbers is supported for historic reasons, but is not recommended as
5477 future changes to @value{GDBN} could change the mapping between
5478 numbers and the registers they represent, breaking any Python code
5479 that uses the platform-specific numbers. The numbers are usually
5480 found in the corresponding @file{@var{platform}-tdep.h} file in the
5481 @value{GDBN} source tree.
5483 Using a string to access registers will be slightly slower than the
5484 other two methods as @value{GDBN} must look up the mapping between
5485 name and internal register number. If performance is critical
5486 consider looking up and caching a @code{gdb.RegisterDescriptor}
5490 @defun Frame.read_var (variable @r{[}, block@r{]})
5491 Return the value of @var{variable} in this frame. If the optional
5492 argument @var{block} is provided, search for the variable from that
5493 block; otherwise start at the frame's current block (which is
5494 determined by the frame's current program counter). The @var{variable}
5495 argument must be a string or a @code{gdb.Symbol} object; @var{block} must be a
5496 @code{gdb.Block} object.
5499 @defun Frame.select ()
5500 Set this frame to be the selected frame. @xref{Stack, ,Examining the
5504 @defun Frame.level ()
5505 Return an integer, the stack frame level for this frame. @xref{Frames, ,Stack Frames}.
5508 @defun Frame.language ()
5509 Return a string, the source language for this frame.
5512 @node Blocks In Python
5513 @subsubsection Accessing blocks from Python
5515 @cindex blocks in python
5518 In @value{GDBN}, symbols are stored in blocks. A block corresponds
5519 roughly to a scope in the source code. Blocks are organized
5520 hierarchically, and are represented individually in Python as a
5521 @code{gdb.Block}. Blocks rely on debugging information being
5524 A frame has a block. Please see @ref{Frames In Python}, for a more
5525 in-depth discussion of frames.
5527 The outermost block is known as the @dfn{global block}. The global
5528 block typically holds public global variables and functions.
5530 The block nested just inside the global block is the @dfn{static
5531 block}. The static block typically holds file-scoped variables and
5534 @value{GDBN} provides a method to get a block's superblock, but there
5535 is currently no way to examine the sub-blocks of a block, or to
5536 iterate over all the blocks in a symbol table (@pxref{Symbol Tables In
5539 Here is a short example that should help explain blocks:
5542 /* This is in the global block. */
5545 /* This is in the static block. */
5546 static int file_scope;
5548 /* 'function' is in the global block, and 'argument' is
5549 in a block nested inside of 'function'. */
5550 int function (int argument)
5552 /* 'local' is in a block inside 'function'. It may or may
5553 not be in the same block as 'argument'. */
5557 /* 'inner' is in a block whose superblock is the one holding
5561 /* If this call is expanded by the compiler, you may see
5562 a nested block here whose function is 'inline_function'
5563 and whose superblock is the one holding 'inner'. */
5569 A @code{gdb.Block} is iterable. The iterator returns the symbols
5570 (@pxref{Symbols In Python}) local to the block. Python programs
5571 should not assume that a specific block object will always contain a
5572 given symbol, since changes in @value{GDBN} features and
5573 infrastructure may cause symbols move across blocks in a symbol
5574 table. You can also use Python's @dfn{dictionary syntax} to access
5575 variables in this block, e.g.:
5578 symbol = some_block['variable'] # symbol is of type gdb.Symbol
5581 The following block-related functions are available in the @code{gdb}
5584 @findex gdb.block_for_pc
5585 @defun gdb.block_for_pc (pc)
5586 Return the innermost @code{gdb.Block} containing the given @var{pc}
5587 value. If the block cannot be found for the @var{pc} value specified,
5588 the function will return @code{None}. This is identical to
5589 @code{gdb.current_progspace().block_for_pc(pc)} and is included for
5590 historical compatibility.
5593 A @code{gdb.Block} object has the following methods:
5595 @defun Block.is_valid ()
5596 Returns @code{True} if the @code{gdb.Block} object is valid,
5597 @code{False} if not. A block object can become invalid if the block it
5598 refers to doesn't exist anymore in the inferior. All other
5599 @code{gdb.Block} methods will throw an exception if it is invalid at
5600 the time the method is called. The block's validity is also checked
5601 during iteration over symbols of the block.
5604 A @code{gdb.Block} object has the following attributes:
5607 The start address of the block. This attribute is not writable.
5611 One past the last address that appears in the block. This attribute
5615 @defvar Block.function
5616 The name of the block represented as a @code{gdb.Symbol}. If the
5617 block is not named, then this attribute holds @code{None}. This
5618 attribute is not writable.
5620 For ordinary function blocks, the superblock is the static block.
5621 However, you should note that it is possible for a function block to
5622 have a superblock that is not the static block -- for instance this
5623 happens for an inlined function.
5626 @defvar Block.superblock
5627 The block containing this block. If this parent block does not exist,
5628 this attribute holds @code{None}. This attribute is not writable.
5631 @defvar Block.global_block
5632 The global block associated with this block. This attribute is not
5636 @defvar Block.static_block
5637 The static block associated with this block. This attribute is not
5641 @defvar Block.is_global
5642 @code{True} if the @code{gdb.Block} object is a global block,
5643 @code{False} if not. This attribute is not
5647 @defvar Block.is_static
5648 @code{True} if the @code{gdb.Block} object is a static block,
5649 @code{False} if not. This attribute is not writable.
5652 @node Symbols In Python
5653 @subsubsection Python representation of Symbols
5655 @cindex symbols in python
5658 @value{GDBN} represents every variable, function and type as an
5659 entry in a symbol table. @xref{Symbols, ,Examining the Symbol Table}.
5660 Similarly, Python represents these symbols in @value{GDBN} with the
5661 @code{gdb.Symbol} object.
5663 The following symbol-related functions are available in the @code{gdb}
5666 @findex gdb.lookup_symbol
5667 @defun gdb.lookup_symbol (name @r{[}, block @r{[}, domain@r{]]})
5668 This function searches for a symbol by name. The search scope can be
5669 restricted to the parameters defined in the optional domain and block
5672 @var{name} is the name of the symbol. It must be a string. The
5673 optional @var{block} argument restricts the search to symbols visible
5674 in that @var{block}. The @var{block} argument must be a
5675 @code{gdb.Block} object. If omitted, the block for the current frame
5676 is used. The optional @var{domain} argument restricts
5677 the search to the domain type. The @var{domain} argument must be a
5678 domain constant defined in the @code{gdb} module and described later
5681 The result is a tuple of two elements.
5682 The first element is a @code{gdb.Symbol} object or @code{None} if the symbol
5684 If the symbol is found, the second element is @code{True} if the symbol
5685 is a field of a method's object (e.g., @code{this} in C@t{++}),
5686 otherwise it is @code{False}.
5687 If the symbol is not found, the second element is @code{False}.
5690 @findex gdb.lookup_global_symbol
5691 @defun gdb.lookup_global_symbol (name @r{[}, domain@r{]})
5692 This function searches for a global symbol by name.
5693 The search scope can be restricted to by the domain argument.
5695 @var{name} is the name of the symbol. It must be a string.
5696 The optional @var{domain} argument restricts the search to the domain type.
5697 The @var{domain} argument must be a domain constant defined in the @code{gdb}
5698 module and described later in this chapter.
5700 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
5704 @findex gdb.lookup_static_symbol
5705 @defun gdb.lookup_static_symbol (name @r{[}, domain@r{]})
5706 This function searches for a global symbol with static linkage by name.
5707 The search scope can be restricted to by the domain argument.
5709 @var{name} is the name of the symbol. It must be a string.
5710 The optional @var{domain} argument restricts the search to the domain type.
5711 The @var{domain} argument must be a domain constant defined in the @code{gdb}
5712 module and described later in this chapter.
5714 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
5717 Note that this function will not find function-scoped static variables. To look
5718 up such variables, iterate over the variables of the function's
5719 @code{gdb.Block} and check that @code{block.addr_class} is
5720 @code{gdb.SYMBOL_LOC_STATIC}.
5722 There can be multiple global symbols with static linkage with the same
5723 name. This function will only return the first matching symbol that
5724 it finds. Which symbol is found depends on where @value{GDBN} is
5725 currently stopped, as @value{GDBN} will first search for matching
5726 symbols in the current object file, and then search all other object
5727 files. If the application is not yet running then @value{GDBN} will
5728 search all object files in the order they appear in the debug
5732 @findex gdb.lookup_static_symbols
5733 @defun gdb.lookup_static_symbols (name @r{[}, domain@r{]})
5734 Similar to @code{gdb.lookup_static_symbol}, this function searches for
5735 global symbols with static linkage by name, and optionally restricted
5736 by the domain argument. However, this function returns a list of all
5737 matching symbols found, not just the first one.
5739 @var{name} is the name of the symbol. It must be a string.
5740 The optional @var{domain} argument restricts the search to the domain type.
5741 The @var{domain} argument must be a domain constant defined in the @code{gdb}
5742 module and described later in this chapter.
5744 The result is a list of @code{gdb.Symbol} objects which could be empty
5745 if no matching symbols were found.
5747 Note that this function will not find function-scoped static variables. To look
5748 up such variables, iterate over the variables of the function's
5749 @code{gdb.Block} and check that @code{block.addr_class} is
5750 @code{gdb.SYMBOL_LOC_STATIC}.
5753 A @code{gdb.Symbol} object has the following attributes:
5756 The type of the symbol or @code{None} if no type is recorded.
5757 This attribute is represented as a @code{gdb.Type} object.
5758 @xref{Types In Python}. This attribute is not writable.
5761 @defvar Symbol.symtab
5762 The symbol table in which the symbol appears. This attribute is
5763 represented as a @code{gdb.Symtab} object. @xref{Symbol Tables In
5764 Python}. This attribute is not writable.
5768 The line number in the source code at which the symbol was defined.
5773 The name of the symbol as a string. This attribute is not writable.
5776 @defvar Symbol.linkage_name
5777 The name of the symbol, as used by the linker (i.e., may be mangled).
5778 This attribute is not writable.
5781 @defvar Symbol.print_name
5782 The name of the symbol in a form suitable for output. This is either
5783 @code{name} or @code{linkage_name}, depending on whether the user
5784 asked @value{GDBN} to display demangled or mangled names.
5787 @defvar Symbol.addr_class
5788 The address class of the symbol. This classifies how to find the value
5789 of a symbol. Each address class is a constant defined in the
5790 @code{gdb} module and described later in this chapter.
5793 @defvar Symbol.needs_frame
5794 This is @code{True} if evaluating this symbol's value requires a frame
5795 (@pxref{Frames In Python}) and @code{False} otherwise. Typically,
5796 local variables will require a frame, but other symbols will not.
5799 @defvar Symbol.is_argument
5800 @code{True} if the symbol is an argument of a function.
5803 @defvar Symbol.is_constant
5804 @code{True} if the symbol is a constant.
5807 @defvar Symbol.is_function
5808 @code{True} if the symbol is a function or a method.
5811 @defvar Symbol.is_variable
5812 @code{True} if the symbol is a variable.
5815 A @code{gdb.Symbol} object has the following methods:
5817 @defun Symbol.is_valid ()
5818 Returns @code{True} if the @code{gdb.Symbol} object is valid,
5819 @code{False} if not. A @code{gdb.Symbol} object can become invalid if
5820 the symbol it refers to does not exist in @value{GDBN} any longer.
5821 All other @code{gdb.Symbol} methods will throw an exception if it is
5822 invalid at the time the method is called.
5825 @defun Symbol.value (@r{[}frame@r{]})
5826 Compute the value of the symbol, as a @code{gdb.Value}. For
5827 functions, this computes the address of the function, cast to the
5828 appropriate type. If the symbol requires a frame in order to compute
5829 its value, then @var{frame} must be given. If @var{frame} is not
5830 given, or if @var{frame} is invalid, then this method will throw an
5834 The available domain categories in @code{gdb.Symbol} are represented
5835 as constants in the @code{gdb} module:
5838 @vindex SYMBOL_UNDEF_DOMAIN
5839 @item gdb.SYMBOL_UNDEF_DOMAIN
5840 This is used when a domain has not been discovered or none of the
5841 following domains apply. This usually indicates an error either
5842 in the symbol information or in @value{GDBN}'s handling of symbols.
5844 @vindex SYMBOL_VAR_DOMAIN
5845 @item gdb.SYMBOL_VAR_DOMAIN
5846 This domain contains variables, function names, typedef names and enum
5849 @vindex SYMBOL_STRUCT_DOMAIN
5850 @item gdb.SYMBOL_STRUCT_DOMAIN
5851 This domain holds struct, union and enum type names.
5853 @vindex SYMBOL_LABEL_DOMAIN
5854 @item gdb.SYMBOL_LABEL_DOMAIN
5855 This domain contains names of labels (for gotos).
5857 @vindex SYMBOL_MODULE_DOMAIN
5858 @item gdb.SYMBOL_MODULE_DOMAIN
5859 This domain contains names of Fortran module types.
5861 @vindex SYMBOL_COMMON_BLOCK_DOMAIN
5862 @item gdb.SYMBOL_COMMON_BLOCK_DOMAIN
5863 This domain contains names of Fortran common blocks.
5866 The available address class categories in @code{gdb.Symbol} are represented
5867 as constants in the @code{gdb} module:
5870 @vindex SYMBOL_LOC_UNDEF
5871 @item gdb.SYMBOL_LOC_UNDEF
5872 If this is returned by address class, it indicates an error either in
5873 the symbol information or in @value{GDBN}'s handling of symbols.
5875 @vindex SYMBOL_LOC_CONST
5876 @item gdb.SYMBOL_LOC_CONST
5877 Value is constant int.
5879 @vindex SYMBOL_LOC_STATIC
5880 @item gdb.SYMBOL_LOC_STATIC
5881 Value is at a fixed address.
5883 @vindex SYMBOL_LOC_REGISTER
5884 @item gdb.SYMBOL_LOC_REGISTER
5885 Value is in a register.
5887 @vindex SYMBOL_LOC_ARG
5888 @item gdb.SYMBOL_LOC_ARG
5889 Value is an argument. This value is at the offset stored within the
5890 symbol inside the frame's argument list.
5892 @vindex SYMBOL_LOC_REF_ARG
5893 @item gdb.SYMBOL_LOC_REF_ARG
5894 Value address is stored in the frame's argument list. Just like
5895 @code{LOC_ARG} except that the value's address is stored at the
5896 offset, not the value itself.
5898 @vindex SYMBOL_LOC_REGPARM_ADDR
5899 @item gdb.SYMBOL_LOC_REGPARM_ADDR
5900 Value is a specified register. Just like @code{LOC_REGISTER} except
5901 the register holds the address of the argument instead of the argument
5904 @vindex SYMBOL_LOC_LOCAL
5905 @item gdb.SYMBOL_LOC_LOCAL
5906 Value is a local variable.
5908 @vindex SYMBOL_LOC_TYPEDEF
5909 @item gdb.SYMBOL_LOC_TYPEDEF
5910 Value not used. Symbols in the domain @code{SYMBOL_STRUCT_DOMAIN} all
5913 @vindex SYMBOL_LOC_LABEL
5914 @item gdb.SYMBOL_LOC_LABEL
5917 @vindex SYMBOL_LOC_BLOCK
5918 @item gdb.SYMBOL_LOC_BLOCK
5921 @vindex SYMBOL_LOC_CONST_BYTES
5922 @item gdb.SYMBOL_LOC_CONST_BYTES
5923 Value is a byte-sequence.
5925 @vindex SYMBOL_LOC_UNRESOLVED
5926 @item gdb.SYMBOL_LOC_UNRESOLVED
5927 Value is at a fixed address, but the address of the variable has to be
5928 determined from the minimal symbol table whenever the variable is
5931 @vindex SYMBOL_LOC_OPTIMIZED_OUT
5932 @item gdb.SYMBOL_LOC_OPTIMIZED_OUT
5933 The value does not actually exist in the program.
5935 @vindex SYMBOL_LOC_COMPUTED
5936 @item gdb.SYMBOL_LOC_COMPUTED
5937 The value's address is a computed location.
5939 @vindex SYMBOL_LOC_COMMON_BLOCK
5940 @item gdb.SYMBOL_LOC_COMMON_BLOCK
5941 The value's address is a symbol. This is only used for Fortran common
5945 @node Symbol Tables In Python
5946 @subsubsection Symbol table representation in Python
5948 @cindex symbol tables in python
5950 @tindex gdb.Symtab_and_line
5952 Access to symbol table data maintained by @value{GDBN} on the inferior
5953 is exposed to Python via two objects: @code{gdb.Symtab_and_line} and
5954 @code{gdb.Symtab}. Symbol table and line data for a frame is returned
5955 from the @code{find_sal} method in @code{gdb.Frame} object.
5956 @xref{Frames In Python}.
5958 For more information on @value{GDBN}'s symbol table management, see
5959 @ref{Symbols, ,Examining the Symbol Table}, for more information.
5961 A @code{gdb.Symtab_and_line} object has the following attributes:
5963 @defvar Symtab_and_line.symtab
5964 The symbol table object (@code{gdb.Symtab}) for this frame.
5965 This attribute is not writable.
5968 @defvar Symtab_and_line.pc
5969 Indicates the start of the address range occupied by code for the
5970 current source line. This attribute is not writable.
5973 @defvar Symtab_and_line.last
5974 Indicates the end of the address range occupied by code for the current
5975 source line. This attribute is not writable.
5978 @defvar Symtab_and_line.line
5979 Indicates the current line number for this object. This
5980 attribute is not writable.
5983 A @code{gdb.Symtab_and_line} object has the following methods:
5985 @defun Symtab_and_line.is_valid ()
5986 Returns @code{True} if the @code{gdb.Symtab_and_line} object is valid,
5987 @code{False} if not. A @code{gdb.Symtab_and_line} object can become
5988 invalid if the Symbol table and line object it refers to does not
5989 exist in @value{GDBN} any longer. All other
5990 @code{gdb.Symtab_and_line} methods will throw an exception if it is
5991 invalid at the time the method is called.
5994 A @code{gdb.Symtab} object has the following attributes:
5996 @defvar Symtab.filename
5997 The symbol table's source filename. This attribute is not writable.
6000 @defvar Symtab.objfile
6001 The symbol table's backing object file. @xref{Objfiles In Python}.
6002 This attribute is not writable.
6005 @defvar Symtab.producer
6006 The name and possibly version number of the program that
6007 compiled the code in the symbol table.
6008 The contents of this string is up to the compiler.
6009 If no producer information is available then @code{None} is returned.
6010 This attribute is not writable.
6013 A @code{gdb.Symtab} object has the following methods:
6015 @defun Symtab.is_valid ()
6016 Returns @code{True} if the @code{gdb.Symtab} object is valid,
6017 @code{False} if not. A @code{gdb.Symtab} object can become invalid if
6018 the symbol table it refers to does not exist in @value{GDBN} any
6019 longer. All other @code{gdb.Symtab} methods will throw an exception
6020 if it is invalid at the time the method is called.
6023 @defun Symtab.fullname ()
6024 Return the symbol table's source absolute file name.
6027 @defun Symtab.global_block ()
6028 Return the global block of the underlying symbol table.
6029 @xref{Blocks In Python}.
6032 @defun Symtab.static_block ()
6033 Return the static block of the underlying symbol table.
6034 @xref{Blocks In Python}.
6037 @defun Symtab.linetable ()
6038 Return the line table associated with the symbol table.
6039 @xref{Line Tables In Python}.
6042 @node Line Tables In Python
6043 @subsubsection Manipulating line tables using Python
6045 @cindex line tables in python
6046 @tindex gdb.LineTable
6048 Python code can request and inspect line table information from a
6049 symbol table that is loaded in @value{GDBN}. A line table is a
6050 mapping of source lines to their executable locations in memory. To
6051 acquire the line table information for a particular symbol table, use
6052 the @code{linetable} function (@pxref{Symbol Tables In Python}).
6054 A @code{gdb.LineTable} is iterable. The iterator returns
6055 @code{LineTableEntry} objects that correspond to the source line and
6056 address for each line table entry. @code{LineTableEntry} objects have
6057 the following attributes:
6059 @defvar LineTableEntry.line
6060 The source line number for this line table entry. This number
6061 corresponds to the actual line of source. This attribute is not
6065 @defvar LineTableEntry.pc
6066 The address that is associated with the line table entry where the
6067 executable code for that source line resides in memory. This
6068 attribute is not writable.
6071 As there can be multiple addresses for a single source line, you may
6072 receive multiple @code{LineTableEntry} objects with matching
6073 @code{line} attributes, but with different @code{pc} attributes. The
6074 iterator is sorted in ascending @code{pc} order. Here is a small
6075 example illustrating iterating over a line table.
6078 symtab = gdb.selected_frame().find_sal().symtab
6079 linetable = symtab.linetable()
6080 for line in linetable:
6081 print ("Line: "+str(line.line)+" Address: "+hex(line.pc))
6084 This will have the following output:
6087 Line: 33 Address: 0x4005c8L
6088 Line: 37 Address: 0x4005caL
6089 Line: 39 Address: 0x4005d2L
6090 Line: 40 Address: 0x4005f8L
6091 Line: 42 Address: 0x4005ffL
6092 Line: 44 Address: 0x400608L
6093 Line: 42 Address: 0x40060cL
6094 Line: 45 Address: 0x400615L
6097 In addition to being able to iterate over a @code{LineTable}, it also
6098 has the following direct access methods:
6100 @defun LineTable.line (line)
6101 Return a Python @code{Tuple} of @code{LineTableEntry} objects for any
6102 entries in the line table for the given @var{line}, which specifies
6103 the source code line. If there are no entries for that source code
6104 @var{line}, the Python @code{None} is returned.
6107 @defun LineTable.has_line (line)
6108 Return a Python @code{Boolean} indicating whether there is an entry in
6109 the line table for this source line. Return @code{True} if an entry
6110 is found, or @code{False} if not.
6113 @defun LineTable.source_lines ()
6114 Return a Python @code{List} of the source line numbers in the symbol
6115 table. Only lines with executable code locations are returned. The
6116 contents of the @code{List} will just be the source line entries
6117 represented as Python @code{Long} values.
6120 @node Breakpoints In Python
6121 @subsubsection Manipulating breakpoints using Python
6123 @cindex breakpoints in python
6124 @tindex gdb.Breakpoint
6126 Python code can manipulate breakpoints via the @code{gdb.Breakpoint}
6129 A breakpoint can be created using one of the two forms of the
6130 @code{gdb.Breakpoint} constructor. The first one accepts a string
6131 like one would pass to the @code{break}
6132 (@pxref{Set Breaks,,Setting Breakpoints}) and @code{watch}
6133 (@pxref{Set Watchpoints, , Setting Watchpoints}) commands, and can be used to
6134 create both breakpoints and watchpoints. The second accepts separate Python
6135 arguments similar to @ref{Explicit Locations}, and can only be used to create
6138 @defun Breakpoint.__init__ (spec @r{[}, type @r{][}, wp_class @r{][}, internal @r{][}, temporary @r{][}, qualified @r{]})
6139 Create a new breakpoint according to @var{spec}, which is a string naming the
6140 location of a breakpoint, or an expression that defines a watchpoint. The
6141 string should describe a location in a format recognized by the @code{break}
6142 command (@pxref{Set Breaks,,Setting Breakpoints}) or, in the case of a
6143 watchpoint, by the @code{watch} command
6144 (@pxref{Set Watchpoints, , Setting Watchpoints}).
6146 The optional @var{type} argument specifies the type of the breakpoint to create,
6149 The optional @var{wp_class} argument defines the class of watchpoint to create,
6150 if @var{type} is @code{gdb.BP_WATCHPOINT}. If @var{wp_class} is omitted, it
6151 defaults to @code{gdb.WP_WRITE}.
6153 The optional @var{internal} argument allows the breakpoint to become invisible
6154 to the user. The breakpoint will neither be reported when created, nor will it
6155 be listed in the output from @code{info breakpoints} (but will be listed with
6156 the @code{maint info breakpoints} command).
6158 The optional @var{temporary} argument makes the breakpoint a temporary
6159 breakpoint. Temporary breakpoints are deleted after they have been hit. Any
6160 further access to the Python breakpoint after it has been hit will result in a
6161 runtime error (as that breakpoint has now been automatically deleted).
6163 The optional @var{qualified} argument is a boolean that allows interpreting
6164 the function passed in @code{spec} as a fully-qualified name. It is equivalent
6165 to @code{break}'s @code{-qualified} flag (@pxref{Linespec Locations} and
6166 @ref{Explicit Locations}).
6170 @defun Breakpoint.__init__ (@r{[} source @r{][}, function @r{][}, label @r{][}, line @r{]}, @r{][} internal @r{][}, temporary @r{][}, qualified @r{]})
6171 This second form of creating a new breakpoint specifies the explicit
6172 location (@pxref{Explicit Locations}) using keywords. The new breakpoint will
6173 be created in the specified source file @var{source}, at the specified
6174 @var{function}, @var{label} and @var{line}.
6176 @var{internal}, @var{temporary} and @var{qualified} have the same usage as
6177 explained previously.
6180 The available types are represented by constants defined in the @code{gdb}
6184 @vindex BP_BREAKPOINT
6185 @item gdb.BP_BREAKPOINT
6186 Normal code breakpoint.
6188 @vindex BP_HARDWARE_BREAKPOINT
6189 @item gdb.BP_HARDWARE_BREAKPOINT
6190 Hardware assisted code breakpoint.
6192 @vindex BP_WATCHPOINT
6193 @item gdb.BP_WATCHPOINT
6194 Watchpoint breakpoint.
6196 @vindex BP_HARDWARE_WATCHPOINT
6197 @item gdb.BP_HARDWARE_WATCHPOINT
6198 Hardware assisted watchpoint.
6200 @vindex BP_READ_WATCHPOINT
6201 @item gdb.BP_READ_WATCHPOINT
6202 Hardware assisted read watchpoint.
6204 @vindex BP_ACCESS_WATCHPOINT
6205 @item gdb.BP_ACCESS_WATCHPOINT
6206 Hardware assisted access watchpoint.
6208 @vindex BP_CATCHPOINT
6209 @item gdb.BP_CATCHPOINT
6210 Catchpoint. Currently, this type can't be used when creating
6211 @code{gdb.Breakpoint} objects, but will be present in
6212 @code{gdb.Breakpoint} objects reported from
6213 @code{gdb.BreakpointEvent}s (@pxref{Events In Python}).
6216 The available watchpoint types are represented by constants defined in the
6222 Read only watchpoint.
6226 Write only watchpoint.
6230 Read/Write watchpoint.
6233 @defun Breakpoint.stop (self)
6234 The @code{gdb.Breakpoint} class can be sub-classed and, in
6235 particular, you may choose to implement the @code{stop} method.
6236 If this method is defined in a sub-class of @code{gdb.Breakpoint},
6237 it will be called when the inferior reaches any location of a
6238 breakpoint which instantiates that sub-class. If the method returns
6239 @code{True}, the inferior will be stopped at the location of the
6240 breakpoint, otherwise the inferior will continue.
6242 If there are multiple breakpoints at the same location with a
6243 @code{stop} method, each one will be called regardless of the
6244 return status of the previous. This ensures that all @code{stop}
6245 methods have a chance to execute at that location. In this scenario
6246 if one of the methods returns @code{True} but the others return
6247 @code{False}, the inferior will still be stopped.
6249 You should not alter the execution state of the inferior (i.e.@:, step,
6250 next, etc.), alter the current frame context (i.e.@:, change the current
6251 active frame), or alter, add or delete any breakpoint. As a general
6252 rule, you should not alter any data within @value{GDBN} or the inferior
6255 Example @code{stop} implementation:
6258 class MyBreakpoint (gdb.Breakpoint):
6260 inf_val = gdb.parse_and_eval("foo")
6267 @defun Breakpoint.is_valid ()
6268 Return @code{True} if this @code{Breakpoint} object is valid,
6269 @code{False} otherwise. A @code{Breakpoint} object can become invalid
6270 if the user deletes the breakpoint. In this case, the object still
6271 exists, but the underlying breakpoint does not. In the cases of
6272 watchpoint scope, the watchpoint remains valid even if execution of the
6273 inferior leaves the scope of that watchpoint.
6276 @defun Breakpoint.delete ()
6277 Permanently deletes the @value{GDBN} breakpoint. This also
6278 invalidates the Python @code{Breakpoint} object. Any further access
6279 to this object's attributes or methods will raise an error.
6282 @defvar Breakpoint.enabled
6283 This attribute is @code{True} if the breakpoint is enabled, and
6284 @code{False} otherwise. This attribute is writable. You can use it to enable
6285 or disable the breakpoint.
6288 @defvar Breakpoint.silent
6289 This attribute is @code{True} if the breakpoint is silent, and
6290 @code{False} otherwise. This attribute is writable.
6292 Note that a breakpoint can also be silent if it has commands and the
6293 first command is @code{silent}. This is not reported by the
6294 @code{silent} attribute.
6297 @defvar Breakpoint.pending
6298 This attribute is @code{True} if the breakpoint is pending, and
6299 @code{False} otherwise. @xref{Set Breaks}. This attribute is
6303 @anchor{python_breakpoint_thread}
6304 @defvar Breakpoint.thread
6305 If the breakpoint is thread-specific, this attribute holds the
6306 thread's global id. If the breakpoint is not thread-specific, this
6307 attribute is @code{None}. This attribute is writable.
6310 @defvar Breakpoint.task
6311 If the breakpoint is Ada task-specific, this attribute holds the Ada task
6312 id. If the breakpoint is not task-specific (or the underlying
6313 language is not Ada), this attribute is @code{None}. This attribute
6317 @defvar Breakpoint.ignore_count
6318 This attribute holds the ignore count for the breakpoint, an integer.
6319 This attribute is writable.
6322 @defvar Breakpoint.number
6323 This attribute holds the breakpoint's number --- the identifier used by
6324 the user to manipulate the breakpoint. This attribute is not writable.
6327 @defvar Breakpoint.type
6328 This attribute holds the breakpoint's type --- the identifier used to
6329 determine the actual breakpoint type or use-case. This attribute is not
6333 @defvar Breakpoint.visible
6334 This attribute tells whether the breakpoint is visible to the user
6335 when set, or when the @samp{info breakpoints} command is run. This
6336 attribute is not writable.
6339 @defvar Breakpoint.temporary
6340 This attribute indicates whether the breakpoint was created as a
6341 temporary breakpoint. Temporary breakpoints are automatically deleted
6342 after that breakpoint has been hit. Access to this attribute, and all
6343 other attributes and functions other than the @code{is_valid}
6344 function, will result in an error after the breakpoint has been hit
6345 (as it has been automatically deleted). This attribute is not
6349 @defvar Breakpoint.hit_count
6350 This attribute holds the hit count for the breakpoint, an integer.
6351 This attribute is writable, but currently it can only be set to zero.
6354 @defvar Breakpoint.location
6355 This attribute holds the location of the breakpoint, as specified by
6356 the user. It is a string. If the breakpoint does not have a location
6357 (that is, it is a watchpoint) the attribute's value is @code{None}. This
6358 attribute is not writable.
6361 @defvar Breakpoint.locations
6362 Get the most current list of breakpoint locations that are inserted for this
6363 breakpoint, with elements of type @code{gdb.BreakpointLocation}
6364 (described below). This functionality matches that of the
6365 @code{info breakpoint} command (@pxref{Set Breaks}), in that it only retrieves
6366 the most current list of locations, thus the list itself when returned is
6367 not updated behind the scenes. This attribute is not writable.
6370 @defvar Breakpoint.expression
6371 This attribute holds a breakpoint expression, as specified by
6372 the user. It is a string. If the breakpoint does not have an
6373 expression (the breakpoint is not a watchpoint) the attribute's value
6374 is @code{None}. This attribute is not writable.
6377 @defvar Breakpoint.condition
6378 This attribute holds the condition of the breakpoint, as specified by
6379 the user. It is a string. If there is no condition, this attribute's
6380 value is @code{None}. This attribute is writable.
6383 @defvar Breakpoint.commands
6384 This attribute holds the commands attached to the breakpoint. If
6385 there are commands, this attribute's value is a string holding all the
6386 commands, separated by newlines. If there are no commands, this
6387 attribute is @code{None}. This attribute is writable.
6390 @subheading Breakpoint Locations
6392 A breakpoint location is one of the actual places where a breakpoint has been
6393 set, represented in the Python API by the @code{gdb.BreakpointLocation}
6394 type. This type is never instantiated by the user directly, but is retrieved
6395 from @code{Breakpoint.locations} which returns a list of breakpoint
6396 locations where it is currently set. Breakpoint locations can become
6397 invalid if new symbol files are loaded or dynamically loaded libraries are
6398 closed. Accessing the attributes of an invalidated breakpoint location will
6399 throw a @code{RuntimeError} exception. Access the @code{Breakpoint.locations}
6400 attribute again to retrieve the new and valid breakpoints location list.
6402 @defvar BreakpointLocation.source
6403 This attribute returns the source file path and line number where this location
6404 was set. The type of the attribute is a tuple of @var{string} and
6405 @var{long}. If the breakpoint location doesn't have a source location,
6406 it returns None, which is the case for watchpoints and catchpoints.
6407 This will throw a @code{RuntimeError} exception if the location
6408 has been invalidated. This attribute is not writable.
6411 @defvar BreakpointLocation.address
6412 This attribute returns the address where this location was set.
6413 This attribute is of type long. This will throw a @code{RuntimeError}
6414 exception if the location has been invalidated. This attribute is
6418 @defvar BreakpointLocation.enabled
6419 This attribute holds the value for whether or not this location is enabled.
6420 This attribute is writable (boolean). This will throw a @code{RuntimeError}
6421 exception if the location has been invalidated.
6424 @defvar BreakpointLocation.owner
6425 This attribute holds a reference to the @code{gdb.Breakpoint} owner object,
6426 from which this @code{gdb.BreakpointLocation} was retrieved from.
6427 This will throw a @code{RuntimeError} exception if the location has been
6428 invalidated. This attribute is not writable.
6431 @defvar BreakpointLocation.function
6432 This attribute gets the name of the function where this location was set.
6433 If no function could be found this attribute returns @code{None}.
6434 This will throw a @code{RuntimeError} exception if the location has
6435 been invalidated. This attribute is not writable.
6438 @defvar BreakpointLocation.fullname
6439 This attribute gets the full name of where this location was set. If no
6440 full name could be found, this attribute returns @code{None}.
6441 This will throw a @code{RuntimeError} exception if the location has
6442 been invalidated. This attribute is not writable.
6445 @defvar BreakpointLocation.thread_groups
6446 This attribute gets the thread groups it was set in. It returns a @code{List}
6447 of the thread group ID's. This will throw a @code{RuntimeError}
6448 exception if the location has been invalidated. This attribute
6452 @node Finish Breakpoints in Python
6453 @subsubsection Finish Breakpoints
6455 @cindex python finish breakpoints
6456 @tindex gdb.FinishBreakpoint
6458 A finish breakpoint is a temporary breakpoint set at the return address of
6459 a frame, based on the @code{finish} command. @code{gdb.FinishBreakpoint}
6460 extends @code{gdb.Breakpoint}. The underlying breakpoint will be disabled
6461 and deleted when the execution will run out of the breakpoint scope (i.e.@:
6462 @code{Breakpoint.stop} or @code{FinishBreakpoint.out_of_scope} triggered).
6463 Finish breakpoints are thread specific and must be create with the right
6466 @defun FinishBreakpoint.__init__ (@r{[}frame@r{]} @r{[}, internal@r{]})
6467 Create a finish breakpoint at the return address of the @code{gdb.Frame}
6468 object @var{frame}. If @var{frame} is not provided, this defaults to the
6469 newest frame. The optional @var{internal} argument allows the breakpoint to
6470 become invisible to the user. @xref{Breakpoints In Python}, for further
6471 details about this argument.
6474 @defun FinishBreakpoint.out_of_scope (self)
6475 In some circumstances (e.g.@: @code{longjmp}, C@t{++} exceptions, @value{GDBN}
6476 @code{return} command, @dots{}), a function may not properly terminate, and
6477 thus never hit the finish breakpoint. When @value{GDBN} notices such a
6478 situation, the @code{out_of_scope} callback will be triggered.
6480 You may want to sub-class @code{gdb.FinishBreakpoint} and override this
6484 class MyFinishBreakpoint (gdb.FinishBreakpoint)
6486 print ("normal finish")
6489 def out_of_scope ():
6490 print ("abnormal finish")
6494 @defvar FinishBreakpoint.return_value
6495 When @value{GDBN} is stopped at a finish breakpoint and the frame
6496 used to build the @code{gdb.FinishBreakpoint} object had debug symbols, this
6497 attribute will contain a @code{gdb.Value} object corresponding to the return
6498 value of the function. The value will be @code{None} if the function return
6499 type is @code{void} or if the return value was not computable. This attribute
6503 @node Lazy Strings In Python
6504 @subsubsection Python representation of lazy strings
6506 @cindex lazy strings in python
6507 @tindex gdb.LazyString
6509 A @dfn{lazy string} is a string whose contents is not retrieved or
6510 encoded until it is needed.
6512 A @code{gdb.LazyString} is represented in @value{GDBN} as an
6513 @code{address} that points to a region of memory, an @code{encoding}
6514 that will be used to encode that region of memory, and a @code{length}
6515 to delimit the region of memory that represents the string. The
6516 difference between a @code{gdb.LazyString} and a string wrapped within
6517 a @code{gdb.Value} is that a @code{gdb.LazyString} will be treated
6518 differently by @value{GDBN} when printing. A @code{gdb.LazyString} is
6519 retrieved and encoded during printing, while a @code{gdb.Value}
6520 wrapping a string is immediately retrieved and encoded on creation.
6522 A @code{gdb.LazyString} object has the following functions:
6524 @defun LazyString.value ()
6525 Convert the @code{gdb.LazyString} to a @code{gdb.Value}. This value
6526 will point to the string in memory, but will lose all the delayed
6527 retrieval, encoding and handling that @value{GDBN} applies to a
6528 @code{gdb.LazyString}.
6531 @defvar LazyString.address
6532 This attribute holds the address of the string. This attribute is not
6536 @defvar LazyString.length
6537 This attribute holds the length of the string in characters. If the
6538 length is -1, then the string will be fetched and encoded up to the
6539 first null of appropriate width. This attribute is not writable.
6542 @defvar LazyString.encoding
6543 This attribute holds the encoding that will be applied to the string
6544 when the string is printed by @value{GDBN}. If the encoding is not
6545 set, or contains an empty string, then @value{GDBN} will select the
6546 most appropriate encoding when the string is printed. This attribute
6550 @defvar LazyString.type
6551 This attribute holds the type that is represented by the lazy string's
6552 type. For a lazy string this is a pointer or array type. To
6553 resolve this to the lazy string's character type, use the type's
6554 @code{target} method. @xref{Types In Python}. This attribute is not
6558 @node Architectures In Python
6559 @subsubsection Python representation of architectures
6560 @cindex Python architectures
6562 @value{GDBN} uses architecture specific parameters and artifacts in a
6563 number of its various computations. An architecture is represented
6564 by an instance of the @code{gdb.Architecture} class.
6566 A @code{gdb.Architecture} class has the following methods:
6568 @anchor{gdbpy_architecture_name}
6569 @defun Architecture.name ()
6570 Return the name (string value) of the architecture.
6573 @defun Architecture.disassemble (start_pc @r{[}, end_pc @r{[}, count@r{]]})
6574 Return a list of disassembled instructions starting from the memory
6575 address @var{start_pc}. The optional arguments @var{end_pc} and
6576 @var{count} determine the number of instructions in the returned list.
6577 If both the optional arguments @var{end_pc} and @var{count} are
6578 specified, then a list of at most @var{count} disassembled instructions
6579 whose start address falls in the closed memory address interval from
6580 @var{start_pc} to @var{end_pc} are returned. If @var{end_pc} is not
6581 specified, but @var{count} is specified, then @var{count} number of
6582 instructions starting from the address @var{start_pc} are returned. If
6583 @var{count} is not specified but @var{end_pc} is specified, then all
6584 instructions whose start address falls in the closed memory address
6585 interval from @var{start_pc} to @var{end_pc} are returned. If neither
6586 @var{end_pc} nor @var{count} are specified, then a single instruction at
6587 @var{start_pc} is returned. For all of these cases, each element of the
6588 returned list is a Python @code{dict} with the following string keys:
6593 The value corresponding to this key is a Python long integer capturing
6594 the memory address of the instruction.
6597 The value corresponding to this key is a string value which represents
6598 the instruction with assembly language mnemonics. The assembly
6599 language flavor used is the same as that specified by the current CLI
6600 variable @code{disassembly-flavor}. @xref{Machine Code}.
6603 The value corresponding to this key is the length (integer value) of the
6604 instruction in bytes.
6609 @findex Architecture.integer_type
6610 @defun Architecture.integer_type (size @r{[}, signed@r{]})
6611 This function looks up an integer type by its @var{size}, and
6612 optionally whether or not it is signed.
6614 @var{size} is the size, in bits, of the desired integer type. Only
6615 certain sizes are currently supported: 0, 8, 16, 24, 32, 64, and 128.
6617 If @var{signed} is not specified, it defaults to @code{True}. If
6618 @var{signed} is @code{False}, the returned type will be unsigned.
6620 If the indicated type cannot be found, this function will throw a
6621 @code{ValueError} exception.
6624 @anchor{gdbpy_architecture_registers}
6625 @defun Architecture.registers (@r{[} reggroup @r{]})
6626 Return a @code{gdb.RegisterDescriptorIterator} (@pxref{Registers In
6627 Python}) for all of the registers in @var{reggroup}, a string that is
6628 the name of a register group. If @var{reggroup} is omitted, or is the
6629 empty string, then the register group @samp{all} is assumed.
6632 @anchor{gdbpy_architecture_reggroups}
6633 @defun Architecture.register_groups ()
6634 Return a @code{gdb.RegisterGroupsIterator} (@pxref{Registers In
6635 Python}) for all of the register groups available for the
6636 @code{gdb.Architecture}.
6639 @node Registers In Python
6640 @subsubsection Registers In Python
6641 @cindex Registers In Python
6643 Python code can request from a @code{gdb.Architecture} information
6644 about the set of registers available
6645 (@pxref{gdbpy_architecture_registers,,@code{Architecture.registers}}).
6646 The register information is returned as a
6647 @code{gdb.RegisterDescriptorIterator}, which is an iterator that in
6648 turn returns @code{gdb.RegisterDescriptor} objects.
6650 A @code{gdb.RegisterDescriptor} does not provide the value of a
6651 register (@pxref{gdbpy_frame_read_register,,@code{Frame.read_register}}
6652 for reading a register's value), instead the @code{RegisterDescriptor}
6653 is a way to discover which registers are available for a particular
6656 A @code{gdb.RegisterDescriptor} has the following read-only properties:
6658 @defvar RegisterDescriptor.name
6659 The name of this register.
6662 It is also possible to lookup a register descriptor based on its name
6663 using the following @code{gdb.RegisterDescriptorIterator} function:
6665 @defun RegisterDescriptorIterator.find (name)
6666 Takes @var{name} as an argument, which must be a string, and returns a
6667 @code{gdb.RegisterDescriptor} for the register with that name, or
6668 @code{None} if there is no register with that name.
6671 Python code can also request from a @code{gdb.Architecture}
6672 information about the set of register groups available on a given
6674 (@pxref{gdbpy_architecture_reggroups,,@code{Architecture.register_groups}}).
6676 Every register can be a member of zero or more register groups. Some
6677 register groups are used internally within @value{GDBN} to control
6678 things like which registers must be saved when calling into the
6679 program being debugged (@pxref{Calling,,Calling Program Functions}).
6680 Other register groups exist to allow users to easily see related sets
6681 of registers in commands like @code{info registers}
6682 (@pxref{info_registers_reggroup,,@code{info registers
6685 The register groups information is returned as a
6686 @code{gdb.RegisterGroupsIterator}, which is an iterator that in turn
6687 returns @code{gdb.RegisterGroup} objects.
6689 A @code{gdb.RegisterGroup} object has the following read-only
6692 @defvar RegisterGroup.name
6693 A string that is the name of this register group.
6696 @node Connections In Python
6697 @subsubsection Connections In Python
6698 @cindex connections in python
6699 @value{GDBN} lets you run and debug multiple programs in a single
6700 session. Each program being debugged has a connection, the connection
6701 describes how @value{GDBN} controls the program being debugged.
6702 Examples of different connection types are @samp{native} and
6703 @samp{remote}. @xref{Inferiors Connections and Programs}.
6705 Connections in @value{GDBN} are represented as instances of
6706 @code{gdb.TargetConnection}, or as one of its sub-classes. To get a
6707 list of all connections use @code{gdb.connections}
6708 (@pxref{gdbpy_connections,,gdb.connections}).
6710 To get the connection for a single @code{gdb.Inferior} read its
6711 @code{gdb.Inferior.connection} attribute
6712 (@pxref{gdbpy_inferior_connection,,gdb.Inferior.connection}).
6714 Currently there is only a single sub-class of
6715 @code{gdb.TargetConnection}, @code{gdb.RemoteTargetConnection},
6716 however, additional sub-classes may be added in future releases of
6717 @value{GDBN}. As a result you should avoid writing code like:
6720 conn = gdb.selected_inferior().connection
6721 if type(conn) is gdb.RemoteTargetConnection:
6722 print("This is a remote target connection")
6726 as this may fail when more connection types are added. Instead, you
6730 conn = gdb.selected_inferior().connection
6731 if isinstance(conn, gdb.RemoteTargetConnection):
6732 print("This is a remote target connection")
6735 A @code{gdb.TargetConnection} has the following method:
6737 @defun TargetConnection.is_valid ()
6738 Return @code{True} if the @code{gdb.TargetConnection} object is valid,
6739 @code{False} if not. A @code{gdb.TargetConnection} will become
6740 invalid if the connection no longer exists within @value{GDBN}, this
6741 might happen when no inferiors are using the connection, but could be
6742 delayed until the user replaces the current target.
6744 Reading any of the @code{gdb.TargetConnection} properties will throw
6745 an exception if the connection is invalid.
6748 A @code{gdb.TargetConnection} has the following read-only properties:
6750 @defvar TargetConnection.num
6751 An integer assigned by @value{GDBN} to uniquely identify this
6752 connection. This is the same value as displayed in the @samp{Num}
6753 column of the @code{info connections} command output (@pxref{Inferiors
6754 Connections and Programs,,info connections}).
6757 @defvar TargetConnection.type
6758 A string that describes what type of connection this is. This string
6759 will be one of the valid names that can be passed to the @code{target}
6760 command (@pxref{Target Commands,,target command}).
6763 @defvar TargetConnection.description
6764 A string that gives a short description of this target type. This is
6765 the same string that is displayed in the @samp{Description} column of
6766 the @code{info connection} command output (@pxref{Inferiors
6767 Connections and Programs,,info connections}).
6770 @defvar TargetConnection.details
6771 An optional string that gives additional information about this
6772 connection. This attribute can be @code{None} if there are no
6773 additional details for this connection.
6775 An example of a connection type that might have additional details is
6776 the @samp{remote} connection, in this case the details string can
6777 contain the @samp{@var{hostname}:@var{port}} that was used to connect
6778 to the remote target.
6781 The @code{gdb.RemoteTargetConnection} class is a sub-class of
6782 @code{gdb.TargetConnection}, and is used to represent @samp{remote}
6783 and @samp{extended-remote} connections. In addition to the attributes
6784 and methods available from the @code{gdb.TargetConnection} base class,
6785 a @code{gdb.RemoteTargetConnection} has the following method:
6787 @kindex maint packet
6788 @defun RemoteTargetConnection.send_packet (packet)
6789 This method sends @var{packet} to the remote target and returns the
6790 response. The @var{packet} should either be a @code{bytes} object, or
6791 a @code{Unicode} string.
6793 If @var{packet} is a @code{Unicode} string, then the string is encoded
6794 to a @code{bytes} object using the @sc{ascii} codec. If the string
6795 can't be encoded then an @code{UnicodeError} is raised.
6797 If @var{packet} is not a @code{bytes} object, or a @code{Unicode}
6798 string, then a @code{TypeError} is raised. If @var{packet} is empty
6799 then a @code{ValueError} is raised.
6801 The response is returned as a @code{bytes} object. For Python 3 if it
6802 is known that the response can be represented as a string then this
6803 can be decoded from the buffer. For example, if it is known that the
6804 response is an @sc{ascii} string:
6807 remote_connection.send_packet("some_packet").decode("ascii")
6810 In Python 2 @code{bytes} and @code{str} are aliases, so the result is
6811 already a string, if the response includes non-printable characters,
6812 or null characters, then these will be present in the result, care
6813 should be taken when processing the result to handle this case.
6815 The prefix, suffix, and checksum (as required by the remote serial
6816 protocol) are automatically added to the outgoing packet, and removed
6817 from the incoming packet before the contents of the reply are
6820 This is equivalent to the @code{maintenance packet} command
6821 (@pxref{maint packet}).
6824 @node TUI Windows In Python
6825 @subsubsection Implementing new TUI windows
6826 @cindex Python TUI Windows
6828 New TUI (@pxref{TUI}) windows can be implemented in Python.
6830 @findex gdb.register_window_type
6831 @defun gdb.register_window_type (name, factory)
6832 Because TUI windows are created and destroyed depending on the layout
6833 the user chooses, new window types are implemented by registering a
6834 factory function with @value{GDBN}.
6836 @var{name} is the name of the new window. It's an error to try to
6837 replace one of the built-in windows, but other window types can be
6838 replaced. The @var{name} should match the regular expression
6839 @code{[a-zA-Z][-_.a-zA-Z0-9]*}, it is an error to try and create a
6840 window with an invalid name.
6842 @var{function} is a factory function that is called to create the TUI
6843 window. This is called with a single argument of type
6844 @code{gdb.TuiWindow}, described below. It should return an object
6845 that implements the TUI window protocol, also described below.
6848 As mentioned above, when a factory function is called, it is passed
6849 an object of type @code{gdb.TuiWindow}. This object has these
6850 methods and attributes:
6852 @defun TuiWindow.is_valid ()
6853 This method returns @code{True} when this window is valid. When the
6854 user changes the TUI layout, windows no longer visible in the new
6855 layout will be destroyed. At this point, the @code{gdb.TuiWindow}
6856 will no longer be valid, and methods (and attributes) other than
6857 @code{is_valid} will throw an exception.
6859 When the TUI is disabled using @code{tui disable} (@pxref{TUI
6860 Commands,,tui disable}) the window is hidden rather than destroyed,
6861 but @code{is_valid} will still return @code{False} and other methods
6862 (and attributes) will still throw an exception.
6865 @defvar TuiWindow.width
6866 This attribute holds the width of the window. It is not writable.
6869 @defvar TuiWindow.height
6870 This attribute holds the height of the window. It is not writable.
6873 @defvar TuiWindow.title
6874 This attribute holds the window's title, a string. This is normally
6875 displayed above the window. This attribute can be modified.
6878 @defun TuiWindow.erase ()
6879 Remove all the contents of the window.
6882 @defun TuiWindow.write (string @r{[}, full_window@r{]})
6883 Write @var{string} to the window. @var{string} can contain ANSI
6884 terminal escape styling sequences; @value{GDBN} will translate these
6885 as appropriate for the terminal.
6887 If the @var{full_window} parameter is @code{True}, then @var{string}
6888 contains the full contents of the window. This is similar to calling
6889 @code{erase} before @code{write}, but avoids the flickering.
6892 The factory function that you supply should return an object
6893 conforming to the TUI window protocol. These are the method that can
6894 be called on this object, which is referred to below as the ``window
6895 object''. The methods documented below are optional; if the object
6896 does not implement one of these methods, @value{GDBN} will not attempt
6897 to call it. Additional new methods may be added to the window
6898 protocol in the future. @value{GDBN} guarantees that they will begin
6899 with a lower-case letter, so you can start implementation methods with
6900 upper-case letters or underscore to avoid any future conflicts.
6902 @defun Window.close ()
6903 When the TUI window is closed, the @code{gdb.TuiWindow} object will be
6904 put into an invalid state. At this time, @value{GDBN} will call
6905 @code{close} method on the window object.
6907 After this method is called, @value{GDBN} will discard any references
6908 it holds on this window object, and will no longer call methods on
6912 @defun Window.render ()
6913 In some situations, a TUI window can change size. For example, this
6914 can happen if the user resizes the terminal, or changes the layout.
6915 When this happens, @value{GDBN} will call the @code{render} method on
6918 If your window is intended to update in response to changes in the
6919 inferior, you will probably also want to register event listeners and
6920 send output to the @code{gdb.TuiWindow}.
6923 @defun Window.hscroll (num)
6924 This is a request to scroll the window horizontally. @var{num} is the
6925 amount by which to scroll, with negative numbers meaning to scroll
6926 right. In the TUI model, it is the viewport that moves, not the
6927 contents. A positive argument should cause the viewport to move
6928 right, and so the content should appear to move to the left.
6931 @defun Window.vscroll (num)
6932 This is a request to scroll the window vertically. @var{num} is the
6933 amount by which to scroll, with negative numbers meaning to scroll
6934 backward. In the TUI model, it is the viewport that moves, not the
6935 contents. A positive argument should cause the viewport to move down,
6936 and so the content should appear to move up.
6939 @defun Window.click (x, y, button)
6940 This is called on a mouse click in this window. @var{x} and @var{y} are
6941 the mouse coordinates inside the window (0-based, from the top left
6942 corner), and @var{button} specifies which mouse button was used, whose
6943 values can be 1 (left), 2 (middle), or 3 (right).
6946 @node Disassembly In Python
6947 @subsubsection Instruction Disassembly In Python
6948 @cindex python instruction disassembly
6950 @value{GDBN}'s builtin disassembler can be extended, or even replaced,
6951 using the Python API. The disassembler related features are contained
6952 within the @code{gdb.disassembler} module:
6954 @anchor{DisassembleInfo Class}
6955 @deftp {class} gdb.disassembler.DisassembleInfo
6956 Disassembly is driven by instances of this class. Each time
6957 @value{GDBN} needs to disassemble an instruction, an instance of this
6958 class is created and passed to a registered disassembler. The
6959 disassembler is then responsible for disassembling an instruction and
6962 Instances of this type are usually created within @value{GDBN},
6963 however, it is possible to create a copy of an instance of this type,
6964 see the description of @code{__init__} for more details.
6966 This class has the following properties and methods:
6968 @defvar DisassembleInfo.address
6969 A read-only integer containing the address at which @value{GDBN}
6970 wishes to disassemble a single instruction.
6973 @defvar DisassembleInfo.architecture
6974 The @code{gdb.Architecture} (@pxref{Architectures In Python}) for
6975 which @value{GDBN} is currently disassembling, this property is
6979 @defvar DisassembleInfo.progspace
6980 The @code{gdb.Progspace} (@pxref{Progspaces In Python,,Program Spaces
6981 In Python}) for which @value{GDBN} is currently disassembling, this
6982 property is read-only.
6985 @defun DisassembleInfo.is_valid ()
6986 Returns @code{True} if the @code{DisassembleInfo} object is valid,
6987 @code{False} if not. A @code{DisassembleInfo} object will become
6988 invalid once the disassembly call for which the @code{DisassembleInfo}
6989 was created, has returned. Calling other @code{DisassembleInfo}
6990 methods, or accessing @code{DisassembleInfo} properties, will raise a
6991 @code{RuntimeError} exception if it is invalid.
6994 @defun DisassembleInfo.__init__ (info)
6995 This can be used to create a new @code{DisassembleInfo} object that is
6996 a copy of @var{info}. The copy will have the same @code{address},
6997 @code{architecture}, and @code{progspace} values as @var{info}, and
6998 will become invalid at the same time as @var{info}.
7000 This method exists so that sub-classes of @code{DisassembleInfo} can
7001 be created, these sub-classes must be initialized as copies of an
7002 existing @code{DisassembleInfo} object, but sub-classes might choose
7003 to override the @code{read_memory} method, and so control what
7004 @value{GDBN} sees when reading from memory
7005 (@pxref{builtin_disassemble}).
7008 @defun DisassembleInfo.read_memory (length, offset)
7009 This method allows the disassembler to read the bytes of the
7010 instruction to be disassembled. The method reads @var{length} bytes,
7011 starting at @var{offset} from
7012 @code{DisassembleInfo.address}.
7014 It is important that the disassembler read the instruction bytes using
7015 this method, rather than reading inferior memory directly, as in some
7016 cases @value{GDBN} disassembles from an internal buffer rather than
7017 directly from inferior memory, calling this method handles this
7020 Returns a buffer object, which behaves much like an array or a string,
7021 just as @code{Inferior.read_memory} does
7022 (@pxref{gdbpy_inferior_read_memory,,Inferior.read_memory}). The
7023 length of the returned buffer will always be exactly @var{length}.
7025 If @value{GDBN} is unable to read the required memory then a
7026 @code{gdb.MemoryError} exception is raised (@pxref{Exception
7029 This method can be overridden by a sub-class in order to control what
7030 @value{GDBN} sees when reading from memory
7031 (@pxref{builtin_disassemble}). When overriding this method it is
7032 important to understand how @code{builtin_disassemble} makes use of
7035 While disassembling a single instruction there could be multiple calls
7036 to this method, and the same bytes might be read multiple times. Any
7037 single call might only read a subset of the total instruction bytes.
7039 If an implementation of @code{read_memory} is unable to read the
7040 requested memory contents, for example, if there's a request to read
7041 from an invalid memory address, then a @code{gdb.MemoryError} should
7044 Raising a @code{MemoryError} inside @code{read_memory} does not
7045 automatically mean a @code{MemoryError} will be raised by
7046 @code{builtin_disassemble}. It is possible the @value{GDBN}'s builtin
7047 disassembler is probing to see how many bytes are available. When
7048 @code{read_memory} raises the @code{MemoryError} the builtin
7049 disassembler might be able to perform a complete disassembly with the
7050 bytes it has available, in this case @code{builtin_disassemble} will
7051 not itself raise a @code{MemoryError}.
7053 Any other exception type raised in @code{read_memory} will propagate
7054 back and be re-raised by @code{builtin_disassemble}.
7057 @defun DisassembleInfo.text_part (style, string)
7058 Create a new @code{DisassemblerTextPart} representing a piece of a
7059 disassembled instruction. @var{string} should be a non-empty string,
7060 and @var{style} should be an appropriate style constant
7061 (@pxref{Disassembler Style Constants}).
7063 Disassembler parts are used when creating a @code{DisassemblerResult}
7064 in order to represent the styling within an instruction
7065 (@pxref{DisassemblerResult Class}).
7068 @defun DisassembleInfo.address_part (address)
7069 Create a new @code{DisassemblerAddressPart}. @var{address} is the
7070 value of the absolute address this part represents. A
7071 @code{DisassemblerAddressPart} is displayed as an absolute address and
7072 an associated symbol, the address and symbol are styled appropriately.
7077 @anchor{Disassembler Class}
7078 @deftp {class} gdb.disassembler.Disassembler
7079 This is a base class from which all user implemented disassemblers
7082 @defun Disassembler.__init__ (name)
7083 The constructor takes @var{name}, a string, which should be a short
7084 name for this disassembler.
7087 @defun Disassembler.__call__ (info)
7088 The @code{__call__} method must be overridden by sub-classes to
7089 perform disassembly. Calling @code{__call__} on this base class will
7090 raise a @code{NotImplementedError} exception.
7092 The @var{info} argument is an instance of @code{DisassembleInfo}, and
7093 describes the instruction that @value{GDBN} wants disassembling.
7095 If this function returns @code{None}, this indicates to @value{GDBN}
7096 that this sub-class doesn't wish to disassemble the requested
7097 instruction. @value{GDBN} will then use its builtin disassembler to
7098 perform the disassembly.
7100 Alternatively, this function can return a @code{DisassemblerResult}
7101 that represents the disassembled instruction, this type is described
7102 in more detail below.
7104 The @code{__call__} method can raise a @code{gdb.MemoryError}
7105 exception (@pxref{Exception Handling}) to indicate to @value{GDBN}
7106 that there was a problem accessing the required memory, this will then
7107 be displayed by @value{GDBN} within the disassembler output.
7109 Ideally, the only three outcomes from invoking @code{__call__} would
7110 be a return of @code{None}, a successful disassembly returned in a
7111 @code{DisassemblerResult}, or a @code{MemoryError} indicating that
7112 there was a problem reading memory.
7114 However, as an implementation of @code{__call__} could fail due to
7115 other reasons, e.g.@: some external resource required to perform
7116 disassembly is temporarily unavailable, then, if @code{__call__}
7117 raises a @code{GdbError}, the exception will be converted to a string
7118 and printed at the end of the disassembly output, the disassembly
7119 request will then stop.
7121 Any other exception type raised by the @code{__call__} method is
7122 considered an error in the user code, the exception will be printed to
7123 the error stream according to the @kbd{set python print-stack} setting
7124 (@pxref{set_python_print_stack,,@kbd{set python print-stack}}).
7128 @anchor{DisassemblerResult Class}
7129 @deftp {class} gdb.disassembler.DisassemblerResult
7130 This class represents the result of disassembling a single
7131 instruction. An instance of this class will be returned from
7132 @code{builtin_disassemble} (@pxref{builtin_disassemble}), and an
7133 instance of this class should be returned from
7134 @w{@code{Disassembler.__call__}} (@pxref{Disassembler Class}) if an
7135 instruction was successfully disassembled.
7137 It is not possible to sub-class the @code{DisassemblerResult} class.
7139 The @code{DisassemblerResult} class has the following properties and
7142 @defun DisassemblerResult.__init__ (length, string, parts)
7143 Initialize an instance of this class, @var{length} is the length of
7144 the disassembled instruction in bytes, which must be greater than
7147 Only one of @var{string} or @var{parts} should be used to initialize a
7148 new @code{DisassemblerResult}; the other one should be passed the
7149 value @code{None}. Alternatively, the arguments can be passed by
7150 name, and the unused argument can be ignored.
7152 The @var{string} argument, if not @code{None}, is a non-empty string
7153 that represents the entire disassembled instruction. Building a result
7154 object using the @var{string} argument does not allow for any styling
7155 information to be included in the result. @value{GDBN} will style the
7156 result as a single @code{DisassemblerTextPart} with @code{STYLE_TEXT}
7157 style (@pxref{Disassembler Styling Parts}).
7159 The @var{parts} argument, if not @code{None}, is a non-empty sequence
7160 of @code{DisassemblerPart} objects. Each part represents a small part
7161 of the disassembled instruction along with associated styling
7162 information. A result object built using @var{parts} can be displayed
7163 by @value{GDBN} with full styling information
7164 (@pxref{style_disassembler_enabled,,@kbd{set style disassembler
7168 @defvar DisassemblerResult.length
7169 A read-only property containing the length of the disassembled
7170 instruction in bytes, this will always be greater than zero.
7173 @defvar DisassemblerResult.string
7174 A read-only property containing a non-empty string representing the
7175 disassembled instruction. The @var{string} is a representation of the
7176 disassembled instruction without any styling information. To see how
7177 the instruction will be styled use the @var{parts} property.
7179 If this instance was initialized using separate
7180 @code{DisassemblerPart} objects, the @var{string} property will still
7181 be valid. The @var{string} value is created by concatenating the
7182 @code{DisassemblerPart.string} values of each component part
7183 (@pxref{Disassembler Styling Parts}).
7186 @defvar DisassemblerResult.parts
7187 A read-only property containing a non-empty sequence of
7188 @code{DisassemblerPart} objects. Each @code{DisassemblerPart} object
7189 contains a small part of the instruction along with information about
7190 how that part should be styled. @value{GDBN} uses this information to
7191 create styled disassembler output
7192 (@pxref{style_disassembler_enabled,,@kbd{set style disassembler
7195 If this instance was initialized using a single string rather than
7196 with a sequence of @code{DisassemblerPart} objects, the @var{parts}
7197 property will still be valid. In this case the @var{parts} property
7198 will hold a sequence containing a single @code{DisassemblerTextPart}
7199 object, the string of which will represent the entire instruction, and
7200 the style of which will be @code{STYLE_TEXT}.
7204 @anchor{Disassembler Styling Parts}
7205 @deftp {class} gdb.disassembler.DisassemblerPart
7206 This is a parent class from which the different part sub-classes
7207 inherit. Only instances of the sub-classes detailed below will be
7208 returned by the Python API.
7210 It is not possible to directly create instances of either this parent
7211 class, or any of the sub-classes listed below. Instances of the
7212 sub-classes listed below are created by calling
7213 @code{builtin_disassemble} (@pxref{builtin_disassemble}) and are
7214 returned within the @code{DisassemblerResult} object, or can be
7215 created by calling the @code{text_part} and @code{address_part}
7216 methods on the @code{DisassembleInfo} class (@pxref{DisassembleInfo
7219 The @code{DisassemblerPart} class has a single property:
7221 @defvar DisassemblerPart.string
7222 A read-only property that contains a non-empty string representing
7223 this part of the disassembled instruction. The string within this
7224 property doesn't include any styling information.
7228 @deftp {class} gdb.disassembler.DisassemblerTextPart
7229 The @code{DisassemblerTextPart} class represents a piece of the
7230 disassembled instruction and the associated style for that piece.
7231 Instances of this class can't be created directly, instead call
7232 @code{DisassembleInfo.text_part} to create a new instance of this
7233 class (@pxref{DisassembleInfo Class}).
7235 As well as the properties of its parent class, the
7236 @code{DisassemblerTextPart} has the following additional property:
7238 @defvar DisassemblerTextPart.style
7239 A read-only property that contains one of the defined style constants.
7240 @value{GDBN} will use this style when styling this part of the
7241 disassembled instruction (@pxref{Disassembler Style Constants}).
7245 @deftp {class} gdb.disassembler.DisassemblerAddressPart
7246 The @code{DisassemblerAddressPart} class represents an absolute
7247 address within a disassembled instruction. Using a
7248 @code{DisassemblerAddressPart} instead of a
7249 @code{DisassemblerTextPart} with @code{STYLE_ADDRESS} is preferred,
7250 @value{GDBN} will display the address as both an absolute address, and
7251 will look up a suitable symbol to display next to the address. Using
7252 @code{DisassemblerAddressPart} also ensures that user settings such as
7253 @code{set print max-symbolic-offset} are respected.
7255 Here is an example of an x86-64 instruction:
7262 In this instruction the @code{0x401136 <foo>} was generated from a
7263 single @code{DisassemblerAddressPart}. The @code{0x401136} will be
7264 styled with @code{STYLE_ADDRESS}, and @code{foo} will be styled with
7265 @code{STYLE_SYMBOL}. The @code{<} and @code{>} will be styled as
7268 If the inclusion of the symbol name is not required then a
7269 @code{DisassemblerTextPart} with style @code{STYLE_ADDRESS} can be
7272 Instances of this class can't be created directly, instead call
7273 @code{DisassembleInfo.address_part} to create a new instance of this
7274 class (@pxref{DisassembleInfo Class}).
7276 As well as the properties of its parent class, the
7277 @code{DisassemblerAddressPart} has the following additional property:
7279 @defvar DisassemblerAddressPart.address
7280 A read-only property that contains the @var{address} passed to this
7281 object's @code{__init__} method.
7285 @anchor{Disassembler Style Constants}
7287 The following table lists all of the disassembler styles that are
7288 available. @value{GDBN} maps these style constants onto its style
7289 settings (@pxref{Output Styling}). In some cases, several style
7290 constants produce the same style settings, and thus will produce the
7291 same visual effect on the screen. This could change in future
7292 releases of @value{GDBN}, so care should be taken to select the
7293 correct style constant to ensure correct output styling in future
7294 releases of @value{GDBN}.
7298 @item gdb.disassembler.STYLE_TEXT
7299 This is the default style used by @value{GDBN} when styling
7300 disassembler output. This style should be used for any parts of the
7301 instruction that don't fit any of the other styles listed below.
7302 @value{GDBN} styles text with this style using its default style.
7304 @vindex STYLE_MNEMONIC
7305 @item gdb.disassembler.STYLE_MNEMONIC
7306 This style is used for styling the primary instruction mnemonic, which
7307 usually appears at, or near, the start of the disassembled instruction
7310 @value{GDBN} styles text with this style using the @code{disassembler
7311 mnemonic} style setting.
7313 @vindex STYLE_SUB_MNEMONIC
7314 @item gdb.disassembler.STYLE_SUB_MNEMONIC
7315 This style is used for styling any sub-mnemonics within a disassembled
7316 instruction. A sub-mnemonic is any text within the instruction that
7317 controls the function of the instruction, but which is disjoint from
7318 the primary mnemonic (which will have styled @code{STYLE_MNEMONIC}).
7320 As an example, consider this AArch64 instruction:
7323 add w16, w7, w1, lsl #1
7327 The @code{add} is the primary instruction mnemonic, and would be given
7328 style @code{STYLE_MNEMONIC}, while @code{lsl} is the sub-mnemonic, and
7329 would be given the style @code{STYLE_SUB_MNEMONIC}.
7331 @value{GDBN} styles text with this style using the @code{disassembler
7332 mnemonic} style setting.
7334 @vindex STYLE_ASSEMBLER_DIRECTIVE
7335 @item gdb.disassembler.STYLE_ASSEMBLER_DIRECTIVE
7336 Sometimes a series of bytes doesn't decode to a valid instruction. In
7337 this case the disassembler may choose to represent the result of
7338 disassembling using an assembler directive, for example:
7345 In this case, the @code{.word} would be give the
7346 @code{STYLE_ASSEMBLER_DIRECTIVE} style. An assembler directive is
7347 similar to a mnemonic in many ways but is something that is not part
7348 of the architecture's instruction set.
7350 @value{GDBN} styles text with this style using the @code{disassembler
7351 mnemonic} style setting.
7353 @vindex STYLE_REGISTER
7354 @item gdb.disassembler.STYLE_REGISTER
7355 This style is used for styling any text that represents a register
7356 name, or register number, within a disassembled instruction.
7358 @value{GDBN} styles text with this style using the @code{disassembler
7359 register} style setting.
7361 @vindex STYLE_ADDRESS
7362 @item gdb.disassembler.STYLE_ADDRESS
7363 This style is used for styling numerical values that represent
7364 absolute addresses within the disassembled instruction.
7366 When creating a @code{DisassemblerTextPart} with this style, you
7367 should consider if a @code{DisassemblerAddressPart} would be more
7368 appropriate. See @ref{Disassembler Styling Parts} for a description
7369 of what each part offers.
7371 @value{GDBN} styles text with this style using the @code{disassembler
7372 address} style setting.
7374 @vindex STYLE_ADDRESS_OFFSET
7375 @item gdb.disassembler.STYLE_ADDRESS_OFFSET
7376 This style is used for styling numerical values that represent offsets
7377 to addresses within the disassembled instruction. A value is
7378 considered an address offset when the instruction itself is going to
7379 access memory, and the value is being used to offset which address is
7382 For example, an architecture might have an instruction that loads from
7383 memory using an address within a register. If that instruction also
7384 allowed for an immediate offset to be encoded into the instruction,
7385 this would be an address offset. Similarly, a branch instruction
7386 might jump to an address in a register plus an address offset that is
7387 encoded into the instruction.
7389 @value{GDBN} styles text with this style using the @code{disassembler
7390 immediate} style setting.
7392 @vindex STYLE_IMMEDIATE
7393 @item gdb.disassembler.STYLE_IMMEDIATE
7394 Use @code{STYLE_IMMEDIATE} for any numerical values within a
7395 disassembled instruction when those values are not addresses, address
7396 offsets, or register numbers (The styles @code{STYLE_ADDRESS},
7397 @code{STYLE_ADDRESS_OFFSET}, or @code{STYLE_REGISTER} can be used in
7400 @value{GDBN} styles text with this style using the @code{disassembler
7401 immediate} style setting.
7403 @vindex STYLE_SYMBOL
7404 @item gdb.disassembler.STYLE_SYMBOL
7405 This style is used for styling the textual name of a symbol that is
7406 included within a disassembled instruction. A symbol name is often
7407 included next to an absolute address within a disassembled instruction
7408 to make it easier for the user to understand what the address is
7409 referring too. For example:
7416 Here @code{foo} is the name of a symbol, and should be given the
7417 @code{STYLE_SYMBOL} style.
7419 Adding symbols next to absolute addresses like this is handled
7420 automatically by the @code{DisassemblerAddressPart} class
7421 (@pxref{Disassembler Styling Parts}).
7423 @value{GDBN} styles text with this style using the @code{disassembler
7424 symbol} style setting.
7426 @vindex STYLE_COMMENT_START
7427 @item gdb.disassembler.STYLE_COMMENT_START
7428 This style is used to start a line comment in the disassembly output.
7429 Unlike other styles, which only apply to the single
7430 @code{DisassemblerTextPiece} to which they are applied, the comment
7431 style is sticky, and overrides the style of any further pieces within
7434 This means that, after a @code{STYLE_COMMENT_START} piece has been
7435 seen, @value{GDBN} will apply the comment style until the end of the
7436 line, ignoring the specific style within a piece.
7438 @value{GDBN} styles text with this style using the @code{disassembler
7439 comment} style setting.
7442 The following functions are also contained in the
7443 @code{gdb.disassembler} module:
7445 @defun register_disassembler (disassembler, architecture)
7446 The @var{disassembler} must be a sub-class of
7447 @code{gdb.disassembler.Disassembler} or @code{None}.
7449 The optional @var{architecture} is either a string, or the value
7450 @code{None}. If it is a string, then it should be the name of an
7451 architecture known to @value{GDBN}, as returned either from
7452 @code{gdb.Architecture.name}
7453 (@pxref{gdbpy_architecture_name,,gdb.Architecture.name}), or from
7454 @code{gdb.architecture_names}
7455 (@pxref{gdb_architecture_names,,gdb.architecture_names}).
7457 The @var{disassembler} will be installed for the architecture named by
7458 @var{architecture}, or if @var{architecture} is @code{None}, then
7459 @var{disassembler} will be installed as a global disassembler for use
7460 by all architectures.
7462 @cindex disassembler in Python, global vs.@: specific
7463 @cindex search order for disassembler in Python
7464 @cindex look up of disassembler in Python
7465 @value{GDBN} only records a single disassembler for each architecture,
7466 and a single global disassembler. Calling
7467 @code{register_disassembler} for an architecture, or for the global
7468 disassembler, will replace any existing disassembler registered for
7469 that @var{architecture} value. The previous disassembler is returned.
7471 If @var{disassembler} is @code{None} then any disassembler currently
7472 registered for @var{architecture} is deregistered and returned.
7474 When @value{GDBN} is looking for a disassembler to use, @value{GDBN}
7475 first looks for an architecture specific disassembler. If none has
7476 been registered then @value{GDBN} looks for a global disassembler (one
7477 registered with @var{architecture} set to @code{None}). Only one
7478 disassembler is called to perform disassembly, so, if there is both an
7479 architecture specific disassembler, and a global disassembler
7480 registered, it is the architecture specific disassembler that will be
7483 @value{GDBN} tracks the architecture specific, and global
7484 disassemblers separately, so it doesn't matter in which order
7485 disassemblers are created or registered; an architecture specific
7486 disassembler, if present, will always be used in preference to a
7487 global disassembler.
7489 You can use the @kbd{maint info python-disassemblers} command
7490 (@pxref{maint info python-disassemblers}) to see which disassemblers
7491 have been registered.
7494 @anchor{builtin_disassemble}
7495 @defun builtin_disassemble (info)
7496 This function calls back into @value{GDBN}'s builtin disassembler to
7497 disassemble the instruction identified by @var{info}, an instance, or
7498 sub-class, of @code{DisassembleInfo}.
7500 When the builtin disassembler needs to read memory the
7501 @code{read_memory} method on @var{info} will be called. By
7502 sub-classing @code{DisassembleInfo} and overriding the
7503 @code{read_memory} method, it is possible to intercept calls to
7504 @code{read_memory} from the builtin disassembler, and to modify the
7507 It is important to understand that, even when
7508 @code{DisassembleInfo.read_memory} raises a @code{gdb.MemoryError}, it
7509 is the internal disassembler itself that reports the memory error to
7510 @value{GDBN}. The reason for this is that the disassembler might
7511 probe memory to see if a byte is readable or not; if the byte can't be
7512 read then the disassembler may choose not to report an error, but
7513 instead to disassemble the bytes that it does have available.
7515 If the builtin disassembler is successful then an instance of
7516 @code{DisassemblerResult} is returned from @code{builtin_disassemble},
7517 alternatively, if something goes wrong, an exception will be raised.
7519 A @code{MemoryError} will be raised if @code{builtin_disassemble} is
7520 unable to read some memory that is required in order to perform
7521 disassembly correctly.
7523 Any exception that is not a @code{MemoryError}, that is raised in a
7524 call to @code{read_memory}, will pass through
7525 @code{builtin_disassemble}, and be visible to the caller.
7527 Finally, there are a few cases where @value{GDBN}'s builtin
7528 disassembler can fail for reasons that are not covered by
7529 @code{MemoryError}. In these cases, a @code{GdbError} will be raised.
7530 The contents of the exception will be a string describing the problem
7531 the disassembler encountered.
7534 Here is an example that registers a global disassembler. The new
7535 disassembler invokes the builtin disassembler, and then adds a
7536 comment, @code{## Comment}, to each line of disassembly output:
7539 class ExampleDisassembler(gdb.disassembler.Disassembler):
7541 super().__init__("ExampleDisassembler")
7543 def __call__(self, info):
7544 result = gdb.disassembler.builtin_disassemble(info)
7545 length = result.length
7546 text = result.string + "\t## Comment"
7547 return gdb.disassembler.DisassemblerResult(length, text)
7549 gdb.disassembler.register_disassembler(ExampleDisassembler())
7552 The following example creates a sub-class of @code{DisassembleInfo} in
7553 order to intercept the @code{read_memory} calls, within
7554 @code{read_memory} any bytes read from memory have the two 4-bit
7555 nibbles swapped around. This isn't a very useful adjustment, but
7556 serves as an example.
7559 class MyInfo(gdb.disassembler.DisassembleInfo):
7560 def __init__(self, info):
7561 super().__init__(info)
7563 def read_memory(self, length, offset):
7564 buffer = super().read_memory(length, offset)
7565 result = bytearray()
7567 v = int.from_bytes(b, 'little')
7568 v = (v << 4) & 0xf0 | (v >> 4)
7570 return memoryview(result)
7572 class NibbleSwapDisassembler(gdb.disassembler.Disassembler):
7574 super().__init__("NibbleSwapDisassembler")
7576 def __call__(self, info):
7578 return gdb.disassembler.builtin_disassemble(info)
7580 gdb.disassembler.register_disassembler(NibbleSwapDisassembler())
7583 @node Python Auto-loading
7584 @subsection Python Auto-loading
7585 @cindex Python auto-loading
7587 When a new object file is read (for example, due to the @code{file}
7588 command, or because the inferior has loaded a shared library),
7589 @value{GDBN} will look for Python support scripts in several ways:
7590 @file{@var{objfile}-gdb.py} and @code{.debug_gdb_scripts} section.
7591 @xref{Auto-loading extensions}.
7593 The auto-loading feature is useful for supplying application-specific
7594 debugging commands and scripts.
7596 Auto-loading can be enabled or disabled,
7597 and the list of auto-loaded scripts can be printed.
7600 @anchor{set auto-load python-scripts}
7601 @kindex set auto-load python-scripts
7602 @item set auto-load python-scripts [on|off]
7603 Enable or disable the auto-loading of Python scripts.
7605 @anchor{show auto-load python-scripts}
7606 @kindex show auto-load python-scripts
7607 @item show auto-load python-scripts
7608 Show whether auto-loading of Python scripts is enabled or disabled.
7610 @anchor{info auto-load python-scripts}
7611 @kindex info auto-load python-scripts
7612 @cindex print list of auto-loaded Python scripts
7613 @item info auto-load python-scripts [@var{regexp}]
7614 Print the list of all Python scripts that @value{GDBN} auto-loaded.
7616 Also printed is the list of Python scripts that were mentioned in
7617 the @code{.debug_gdb_scripts} section and were either not found
7618 (@pxref{dotdebug_gdb_scripts section}) or were not auto-loaded due to
7619 @code{auto-load safe-path} rejection (@pxref{Auto-loading}).
7620 This is useful because their names are not printed when @value{GDBN}
7621 tries to load them and fails. There may be many of them, and printing
7622 an error message for each one is problematic.
7624 If @var{regexp} is supplied only Python scripts with matching names are printed.
7629 (gdb) info auto-load python-scripts
7631 Yes py-section-script.py
7632 full name: /tmp/py-section-script.py
7633 No my-foo-pretty-printers.py
7637 When reading an auto-loaded file or script, @value{GDBN} sets the
7638 @dfn{current objfile}. This is available via the @code{gdb.current_objfile}
7639 function (@pxref{Objfiles In Python}). This can be useful for
7640 registering objfile-specific pretty-printers and frame-filters.
7642 @node Python modules
7643 @subsection Python modules
7644 @cindex python modules
7646 @value{GDBN} comes with several modules to assist writing Python code.
7649 * gdb.printing:: Building and registering pretty-printers.
7650 * gdb.types:: Utilities for working with types.
7651 * gdb.prompt:: Utilities for prompt value substitution.
7655 @subsubsection gdb.printing
7656 @cindex gdb.printing
7658 This module provides a collection of utilities for working with
7662 @item PrettyPrinter (@var{name}, @var{subprinters}=None)
7663 This class specifies the API that makes @samp{info pretty-printer},
7664 @samp{enable pretty-printer} and @samp{disable pretty-printer} work.
7665 Pretty-printers should generally inherit from this class.
7667 @item SubPrettyPrinter (@var{name})
7668 For printers that handle multiple types, this class specifies the
7669 corresponding API for the subprinters.
7671 @item RegexpCollectionPrettyPrinter (@var{name})
7672 Utility class for handling multiple printers, all recognized via
7673 regular expressions.
7674 @xref{Writing a Pretty-Printer}, for an example.
7676 @item FlagEnumerationPrinter (@var{name})
7677 A pretty-printer which handles printing of @code{enum} values. Unlike
7678 @value{GDBN}'s built-in @code{enum} printing, this printer attempts to
7679 work properly when there is some overlap between the enumeration
7680 constants. The argument @var{name} is the name of the printer and
7681 also the name of the @code{enum} type to look up.
7683 @item register_pretty_printer (@var{obj}, @var{printer}, @var{replace}=False)
7684 Register @var{printer} with the pretty-printer list of @var{obj}.
7685 If @var{replace} is @code{True} then any existing copy of the printer
7686 is replaced. Otherwise a @code{RuntimeError} exception is raised
7687 if a printer with the same name already exists.
7691 @subsubsection gdb.types
7694 This module provides a collection of utilities for working with
7695 @code{gdb.Type} objects.
7698 @item get_basic_type (@var{type})
7699 Return @var{type} with const and volatile qualifiers stripped,
7700 and with typedefs and C@t{++} references converted to the underlying type.
7705 typedef const int const_int;
7707 const_int& foo_ref (foo);
7708 int main () @{ return 0; @}
7715 (gdb) python import gdb.types
7716 (gdb) python foo_ref = gdb.parse_and_eval("foo_ref")
7717 (gdb) python print gdb.types.get_basic_type(foo_ref.type)
7721 @item has_field (@var{type}, @var{field})
7722 Return @code{True} if @var{type}, assumed to be a type with fields
7723 (e.g., a structure or union), has field @var{field}.
7725 @item make_enum_dict (@var{enum_type})
7726 Return a Python @code{dictionary} type produced from @var{enum_type}.
7728 @item deep_items (@var{type})
7729 Returns a Python iterator similar to the standard
7730 @code{gdb.Type.iteritems} method, except that the iterator returned
7731 by @code{deep_items} will recursively traverse anonymous struct or
7732 union fields. For example:
7746 Then in @value{GDBN}:
7748 (@value{GDBP}) python import gdb.types
7749 (@value{GDBP}) python struct_a = gdb.lookup_type("struct A")
7750 (@value{GDBP}) python print struct_a.keys ()
7752 (@value{GDBP}) python print [k for k,v in gdb.types.deep_items(struct_a)]
7753 @{['a', 'b0', 'b1']@}
7756 @item get_type_recognizers ()
7757 Return a list of the enabled type recognizers for the current context.
7758 This is called by @value{GDBN} during the type-printing process
7759 (@pxref{Type Printing API}).
7761 @item apply_type_recognizers (recognizers, type_obj)
7762 Apply the type recognizers, @var{recognizers}, to the type object
7763 @var{type_obj}. If any recognizer returns a string, return that
7764 string. Otherwise, return @code{None}. This is called by
7765 @value{GDBN} during the type-printing process (@pxref{Type Printing
7768 @item register_type_printer (locus, printer)
7769 This is a convenience function to register a type printer
7770 @var{printer}. The printer must implement the type printer protocol.
7771 The @var{locus} argument is either a @code{gdb.Objfile}, in which case
7772 the printer is registered with that objfile; a @code{gdb.Progspace},
7773 in which case the printer is registered with that progspace; or
7774 @code{None}, in which case the printer is registered globally.
7777 This is a base class that implements the type printer protocol. Type
7778 printers are encouraged, but not required, to derive from this class.
7779 It defines a constructor:
7781 @defmethod TypePrinter __init__ (self, name)
7782 Initialize the type printer with the given name. The new printer
7783 starts in the enabled state.
7789 @subsubsection gdb.prompt
7792 This module provides a method for prompt value-substitution.
7795 @item substitute_prompt (@var{string})
7796 Return @var{string} with escape sequences substituted by values. Some
7797 escape sequences take arguments. You can specify arguments inside
7798 ``@{@}'' immediately following the escape sequence.
7800 The escape sequences you can pass to this function are:
7804 Substitute a backslash.
7806 Substitute an ESC character.
7808 Substitute the selected frame; an argument names a frame parameter.
7810 Substitute a newline.
7812 Substitute a parameter's value; the argument names the parameter.
7814 Substitute a carriage return.
7816 Substitute the selected thread; an argument names a thread parameter.
7818 Substitute the version of GDB.
7820 Substitute the current working directory.
7822 Begin a sequence of non-printing characters. These sequences are
7823 typically used with the ESC character, and are not counted in the string
7824 length. Example: ``\[\e[0;34m\](gdb)\[\e[0m\]'' will return a
7825 blue-colored ``(gdb)'' prompt where the length is five.
7827 End a sequence of non-printing characters.
7833 substitute_prompt ("frame: \f, args: \p@{print frame-arguments@}")
7836 @exdent will return the string:
7839 "frame: main, args: scalars"