1 @c Copyright (C) 2008--2025 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 * Threading in GDB:: Using Python threads in GDB.
194 * Exception Handling:: How Python exceptions are translated.
195 * Values From Inferior:: Python representation of values.
196 * Types In Python:: Python representation of types.
197 * Pretty Printing API:: Pretty-printing values.
198 * Selecting Pretty-Printers:: How GDB chooses a pretty-printer.
199 * Writing a Pretty-Printer:: Writing a Pretty-Printer.
200 * Type Printing API:: Pretty-printing types.
201 * Frame Filter API:: Filtering Frames.
202 * Frame Decorator API:: Decorating Frames.
203 * Writing a Frame Filter:: Writing a Frame Filter.
204 * Unwinding Frames in Python:: Writing frame unwinder.
205 * Xmethods In Python:: Adding and replacing methods of C++ classes.
206 * Xmethod API:: Xmethod types.
207 * Writing an Xmethod:: Writing an xmethod.
208 * Inferiors In Python:: Python representation of inferiors (processes)
209 * Events In Python:: Listening for events from @value{GDBN}.
210 * Threads In Python:: Accessing inferior threads from Python.
211 * Recordings In Python:: Accessing recordings from Python.
212 * CLI Commands In Python:: Implementing new CLI commands in Python.
213 * GDB/MI Commands In Python:: Implementing new @sc{gdb/mi} commands in Python.
214 * GDB/MI Notifications In Python:: Implementing new @sc{gdb/mi} notifications in Python.
215 * Parameters In Python:: Adding new @value{GDBN} parameters.
216 * Functions In Python:: Writing new convenience functions.
217 * Progspaces In Python:: Program spaces.
218 * Objfiles In Python:: Object files.
219 * Frames In Python:: Accessing inferior stack frames from Python.
220 * Blocks In Python:: Accessing blocks from Python.
221 * Symbols In Python:: Python representation of symbols.
222 * Symbol Tables In Python:: Python representation of symbol tables.
223 * Line Tables In Python:: Python representation of line tables.
224 * Breakpoints In Python:: Manipulating breakpoints using Python.
225 * Finish Breakpoints in Python:: Setting Breakpoints on function return
227 * Lazy Strings In Python:: Python representation of lazy strings.
228 * Colors In Python:: Python representation of colors.
229 * Architectures In Python:: Python representation of architectures.
230 * Registers In Python:: Python representation of registers.
231 * Connections In Python:: Python representation of connections.
232 * TUI Windows In Python:: Implementing new TUI windows.
233 * Disassembly In Python:: Instruction Disassembly In Python
234 * Missing Debug Info In Python:: Handle missing debug info from Python.
235 * Missing Objfiles In Python:: Handle objfiles from Python.
239 @subsubsection Basic Python
241 @cindex python stdout
242 @cindex python pagination
243 At startup, @value{GDBN} overrides Python's @code{sys.stdout} and
244 @code{sys.stderr} to print using @value{GDBN}'s output-paging streams.
245 A Python program which outputs to one of these streams may have its
246 output interrupted by the user (@pxref{Screen Size}). In this
247 situation, a Python @code{KeyboardInterrupt} exception is thrown.
249 Some care must be taken when writing Python code to run in
250 @value{GDBN}. Two things worth noting in particular:
254 @value{GDBN} installs handlers for @code{SIGCHLD} and @code{SIGINT}.
255 Python code must not override these, or even change the options using
256 @code{sigaction}. If your program changes the handling of these
257 signals, @value{GDBN} will most likely stop working correctly. Note
258 that it is unfortunately common for GUI toolkits to install a
259 @code{SIGCHLD} handler. When creating a new Python thread, you can
260 use @code{gdb.blocked_signals} or @code{gdb.Thread} to handle this
261 correctly; see @ref{Threading in GDB}.
264 @value{GDBN} takes care to mark its internal file descriptors as
265 close-on-exec. However, this cannot be done in a thread-safe way on
266 all platforms. Your Python programs should be aware of this and
267 should both create new file descriptors with the close-on-exec flag
268 set and arrange to close unneeded file descriptors before starting a
272 @cindex python functions
273 @cindex python module
275 @value{GDBN} introduces a new Python module, named @code{gdb}. All
276 methods and classes added by @value{GDBN} are placed in this module.
277 @value{GDBN} automatically @code{import}s the @code{gdb} module for
278 use in all scripts evaluated by the @code{python} command.
280 Some types of the @code{gdb} module come with a textual representation
281 (accessible through the @code{repr} or @code{str} functions). These are
282 offered for debugging purposes only, expect them to change over time.
284 @defvar gdb.PYTHONDIR
285 A string containing the python directory (@pxref{Python}).
288 @defun gdb.execute (command @r{[}, from_tty @r{[}, to_string @w{@r{[}, styling @r{]]]}})
289 Evaluate @var{command}, a string, as a @value{GDBN} CLI command.
290 If a GDB exception happens while @var{command} runs, it is
291 translated as described in @ref{Exception Handling,,Exception Handling}.
293 The @var{from_tty} flag specifies whether @value{GDBN} ought to consider this
294 command as having originated from the user invoking it interactively.
295 It must be a boolean value. If omitted, it defaults to @code{False}.
297 By default, any output produced by @var{command} is sent to
298 @value{GDBN}'s standard output (and to the log output if logging is
299 turned on). If the @var{to_string} parameter is
300 @code{True}, then output will be collected by @code{gdb.execute} and
301 returned as a string. The default is @code{False}, in which case the
302 return value is @code{None}. If @var{to_string} is @code{True}, the
303 @value{GDBN} virtual terminal will be temporarily set to unlimited width
304 and height, and its pagination will be disabled; @pxref{Screen Size}.
306 When @var{styling} is @code{True}, the output, whether sent to
307 standard output, or to a string, will have styling applied, if
308 @value{GDBN}'s standard output supports styling, and @kbd{show style
309 enabled} is @kbd{on}. When @var{styling} is @code{False} then no
310 styling is applied. The default for @var{styling} is @code{True} when
311 @var{to_string} is @code{False}, and @code{False} when @var{to_string}
315 @defun gdb.breakpoints ()
316 Return a sequence holding all of @value{GDBN}'s breakpoints.
317 @xref{Breakpoints In Python}, for more information. In @value{GDBN}
318 version 7.11 and earlier, this function returned @code{None} if there
319 were no breakpoints. This peculiarity was subsequently fixed, and now
320 @code{gdb.breakpoints} returns an empty sequence in this case.
323 @defun gdb.rbreak (regex @r{[}, minsyms @r{[}, throttle, @r{[}, symtabs @r{]]]})
324 Return a Python list holding a collection of newly set
325 @code{gdb.Breakpoint} objects matching function names defined by the
326 @var{regex} pattern. If the @var{minsyms} keyword is @code{True}, all
327 system functions (those not explicitly defined in the inferior) will
328 also be included in the match. The @var{throttle} keyword takes an
329 integer that defines the maximum number of pattern matches for
330 functions matched by the @var{regex} pattern. If the number of
331 matches exceeds the integer value of @var{throttle}, a
332 @code{RuntimeError} will be raised and no breakpoints will be created.
333 If @var{throttle} is not defined then there is no imposed limit on the
334 maximum number of matches and breakpoints to be created. The
335 @var{symtabs} keyword takes a Python iterable that yields a collection
336 of @code{gdb.Symtab} objects and will restrict the search to those
337 functions only contained within the @code{gdb.Symtab} objects.
340 @defun gdb.parameter (parameter)
341 Return the value of a @value{GDBN} @var{parameter} given by its name,
342 a string; the parameter name string may contain spaces if the parameter has a
343 multi-part name. For example, @samp{print object} is a valid
346 If the named parameter does not exist, this function throws a
347 @code{gdb.error} (@pxref{Exception Handling}). Otherwise, the
348 parameter's value is converted to a Python value of the appropriate
352 @defun gdb.set_parameter (name, value)
353 Sets the gdb parameter @var{name} to @var{value}. As with
354 @code{gdb.parameter}, the parameter name string may contain spaces if
355 the parameter has a multi-part name.
358 @defun gdb.with_parameter (name, value)
359 Create a Python context manager (for use with the Python
360 @command{with} statement) that temporarily sets the gdb parameter
361 @var{name} to @var{value}. On exit from the context, the previous
362 value will be restored.
364 This uses @code{gdb.parameter} in its implementation, so it can throw
365 the same exceptions as that function.
367 For example, it's sometimes useful to evaluate some Python code with a
368 particular gdb language:
371 with gdb.with_parameter('language', 'pascal'):
372 ... language-specific operations
376 @defun gdb.history (number)
377 Return a value from @value{GDBN}'s value history (@pxref{Value
378 History}). The @var{number} argument indicates which history element to return.
379 If @var{number} is negative, then @value{GDBN} will take its absolute value
380 and count backward from the last element (i.e., the most recent element) to
381 find the value to return. If @var{number} is zero, then @value{GDBN} will
382 return the most recent element. If the element specified by @var{number}
383 doesn't exist in the value history, a @code{gdb.error} exception will be
386 If no exception is raised, the return value is always an instance of
387 @code{gdb.Value} (@pxref{Values From Inferior}).
390 @defun gdb.add_history (value)
391 Takes @var{value}, an instance of @code{gdb.Value} (@pxref{Values From
392 Inferior}), and appends the value this object represents to
393 @value{GDBN}'s value history (@pxref{Value History}), and return an
394 integer, its history number. If @var{value} is not a
395 @code{gdb.Value}, it is is converted using the @code{gdb.Value}
396 constructor. If @var{value} can't be converted to a @code{gdb.Value}
397 then a @code{TypeError} is raised.
399 When a command implemented in Python prints a single @code{gdb.Value}
400 as its result, then placing the value into the history will allow the
401 user convenient access to those values via CLI history facilities.
404 @defun gdb.history_count ()
405 Return an integer indicating the number of values in @value{GDBN}'s
406 value history (@pxref{Value History}).
409 @defun gdb.convenience_variable (name)
410 Return the value of the convenience variable (@pxref{Convenience
411 Vars}) named @var{name}. @var{name} must be a string. The name
412 should not include the @samp{$} that is used to mark a convenience
413 variable in an expression. If the convenience variable does not
414 exist, then @code{None} is returned.
417 @defun gdb.set_convenience_variable (name, value)
418 Set the value of the convenience variable (@pxref{Convenience Vars})
419 named @var{name}. @var{name} must be a string. The name should not
420 include the @samp{$} that is used to mark a convenience variable in an
421 expression. If @var{value} is @code{None}, then the convenience
422 variable is removed. Otherwise, if @var{value} is not a
423 @code{gdb.Value} (@pxref{Values From Inferior}), it is is converted
424 using the @code{gdb.Value} constructor.
427 @defun gdb.parse_and_eval (expression @r{[}, global_context@r{]})
428 Parse @var{expression}, which must be a string, as an expression in
429 the current language, evaluate it, and return the result as a
432 @var{global_context}, if provided, is a boolean indicating whether the
433 parsing should be done in the global context. The default is
434 @samp{False}, meaning that the current frame or current static context
437 This function can be useful when implementing a new command
438 (@pxref{CLI Commands In Python}, @pxref{GDB/MI Commands In Python}),
439 as it provides a way to parse the
440 command's argument as an expression. It is also useful simply to
444 @defun gdb.find_pc_line (pc)
445 Return the @code{gdb.Symtab_and_line} object corresponding to the
446 @var{pc} value. @xref{Symbol Tables In Python}. If an invalid
447 value of @var{pc} is passed as an argument, then the @code{symtab} and
448 @code{line} attributes of the returned @code{gdb.Symtab_and_line} object
449 will be @code{None} and 0 respectively. This is identical to
450 @code{gdb.current_progspace().find_pc_line(pc)} and is included for
451 historical compatibility.
454 @defun gdb.write (string @r{[}, stream@r{]})
455 Print a string to @value{GDBN}'s paginated output stream. The
456 optional @var{stream} determines the stream to print to. The default
457 stream is @value{GDBN}'s standard output stream. Possible stream
464 @value{GDBN}'s standard output stream.
469 @value{GDBN}'s standard error stream.
474 @value{GDBN}'s log stream (@pxref{Logging Output}).
477 Writing to @code{sys.stdout} or @code{sys.stderr} will automatically
478 call this function and will automatically direct the output to the
482 @defun gdb.flush (@r{[}stream@r{]})
483 Flush the buffer of a @value{GDBN} paginated stream so that the
484 contents are displayed immediately. @value{GDBN} will flush the
485 contents of a stream automatically when it encounters a newline in the
486 buffer. The optional @var{stream} determines the stream to flush. The
487 default stream is @value{GDBN}'s standard output stream. Possible
494 @value{GDBN}'s standard output stream.
499 @value{GDBN}'s standard error stream.
504 @value{GDBN}'s log stream (@pxref{Logging Output}).
508 Flushing @code{sys.stdout} or @code{sys.stderr} will automatically
509 call this function for the relevant stream.
512 @defun gdb.warning (text)
513 Print a warning message to @value{GDBN}'s standard output stream. The
514 warning message is the warning prefix (@pxref{warning-prefix}), the
515 string @w{@samp{warning: }}, and then @var{text}, which must be a
518 Due to the warning prefix, @var{text} should not begin with a capital
519 letter (except for proper nouns), and @var{text} should end with a
523 @defun gdb.target_charset ()
524 Return the name of the current target character set (@pxref{Character
525 Sets}). This differs from @code{gdb.parameter('target-charset')} in
526 that @samp{auto} is never returned.
529 @defun gdb.target_wide_charset ()
530 Return the name of the current target wide character set
531 (@pxref{Character Sets}). This differs from
532 @code{gdb.parameter('target-wide-charset')} in that @samp{auto} is
536 @defun gdb.host_charset ()
537 Return a string, the name of the current host character set
538 (@pxref{Character Sets}). This differs from
539 @code{gdb.parameter('host-charset')} in that @samp{auto} is never
543 @defun gdb.solib_name (address)
544 Return the name of the shared library holding the given @var{address}
545 as a string, or @code{None}. This is identical to
546 @code{gdb.current_progspace().solib_name(address)} and is included for
547 historical compatibility.
550 @defun gdb.decode_line (@r{[}expression@r{]})
551 Return locations of the line specified by @var{expression}, or of the
552 current line if no argument was given. This function returns a Python
553 tuple containing two elements. The first element contains a string
554 holding any unparsed section of @var{expression} (or @code{None} if
555 the expression has been fully parsed). The second element contains
556 either @code{None} or another tuple that contains all the locations
557 that match the expression represented as @code{gdb.Symtab_and_line}
558 objects (@pxref{Symbol Tables In Python}). If @var{expression} is
559 provided, it is decoded the way that @value{GDBN}'s inbuilt
560 @code{break} or @code{edit} commands do (@pxref{Location
564 @defun gdb.prompt_hook (current_prompt)
567 If @var{prompt_hook} is callable, @value{GDBN} will call the method
568 assigned to this operation before a prompt is displayed by
571 The parameter @code{current_prompt} contains the current @value{GDBN}
572 prompt. This method must return a Python string, or @code{None}. If
573 a string is returned, the @value{GDBN} prompt will be set to that
574 string. If @code{None} is returned, @value{GDBN} will continue to use
577 Some prompts cannot be substituted in @value{GDBN}. Secondary prompts
578 such as those used by readline for command input, and annotation
579 related prompts are prohibited from being changed.
582 @anchor{gdb_architecture_names}
583 @defun gdb.architecture_names ()
584 Return a list containing all of the architecture names that the
585 current build of @value{GDBN} supports. Each architecture name is a
586 string. The names returned in this list are the same names as are
587 returned from @code{gdb.Architecture.name}
588 (@pxref{gdbpy_architecture_name,,Architecture.name}).
591 @anchor{gdbpy_connections}
592 @defun gdb.connections
593 Return a list of @code{gdb.TargetConnection} objects, one for each
594 currently active connection (@pxref{Connections In Python}). The
595 connection objects are in no particular order in the returned list.
598 @defun gdb.format_address (address @r{[}, progspace, architecture@r{]})
599 Return a string in the format @samp{@var{addr}
600 <@var{symbol}+@var{offset}>}, where @var{addr} is @var{address}
601 formatted in hexadecimal, @var{symbol} is the symbol whose address is
602 the nearest to @var{address} and below it in memory, and @var{offset}
603 is the offset from @var{symbol} to @var{address} in decimal.
605 If no suitable @var{symbol} was found, then the
606 <@var{symbol}+@var{offset}> part is not included in the returned
607 string, instead the returned string will just contain the
608 @var{address} formatted as hexadecimal. How far @value{GDBN} looks
609 back for a suitable symbol can be controlled with @kbd{set print
610 max-symbolic-offset} (@pxref{Print Settings}).
612 Additionally, the returned string can include file name and line
613 number information when @kbd{set print symbol-filename on}
614 (@pxref{Print Settings}), in this case the format of the returned
615 string is @samp{@var{addr} <@var{symbol}+@var{offset}> at
616 @var{filename}:@var{line-number}}.
619 The @var{progspace} is the gdb.Progspace in which @var{symbol} is
620 looked up, and @var{architecture} is used when formatting @var{addr},
621 e.g.@: in order to determine the size of an address in bytes.
623 If neither @var{progspace} or @var{architecture} are passed, then by
624 default @value{GDBN} will use the program space and architecture of
625 the currently selected inferior, thus, the following two calls are
629 gdb.format_address(address)
630 gdb.format_address(address,
631 gdb.selected_inferior().progspace,
632 gdb.selected_inferior().architecture())
635 It is not valid to only pass one of @var{progspace} or
636 @var{architecture}, either they must both be provided, or neither must
637 be provided (and the defaults will be used).
639 This method uses the same mechanism for formatting address, symbol,
640 and offset information as core @value{GDBN} does in commands such as
643 Here are some examples of the possible string formats:
647 0x00001042 <symbol+16>
648 0x00001042 <symbol+16 at file.c:123>
652 @defun gdb.current_language ()
653 Return the name of the current language as a string. Unlike
654 @code{gdb.parameter('language')}, this function will never return
655 @samp{auto}. If a @code{gdb.Frame} object is available (@pxref{Frames
656 In Python}), the @code{language} method might be preferable in some
657 cases, as that is not affected by the user's language setting.
660 @node Threading in GDB
661 @subsubsection Threading in GDB
663 @value{GDBN} is not thread-safe. If your Python program uses multiple
664 threads, you must be careful to only call @value{GDBN}-specific
665 functions in the @value{GDBN} thread. @value{GDBN} provides some
666 functions to help with this.
668 @defun gdb.blocked_signals ()
669 As mentioned earlier (@pxref{Basic Python}), certain signals must be
670 delivered to the @value{GDBN} main thread. The @code{blocked_signals}
671 function returns a context manager that will block these signals on
672 entry. This can be used when starting a new thread to ensure that the
673 signals are blocked there, like:
676 with gdb.blocked_signals():
681 @deftp {class} gdb.Thread
682 This is a subclass of Python's @code{threading.Thread} class. It
683 overrides the @code{start} method to call @code{blocked_signals}, making
684 this an easy-to-use drop-in replacement for creating threads that will
685 work well in @value{GDBN}.
688 @defun gdb.interrupt ()
689 This causes @value{GDBN} to react as if the user had typed a control-C
690 character at the terminal. That is, if the inferior is running, it is
691 interrupted; if a @value{GDBN} command is executing, it is stopped;
692 and if a Python command is running, @code{KeyboardInterrupt} will be
695 Unlike most Python APIs in @value{GDBN}, @code{interrupt} is
699 @defun gdb.post_event (event)
700 Put @var{event}, a callable object taking no arguments, into
701 @value{GDBN}'s internal event queue. This callable will be invoked at
702 some later point, during @value{GDBN}'s event processing. Events
703 posted using @code{post_event} will be run in the order in which they
704 were posted; however, there is no way to know when they will be
705 processed relative to other events inside @value{GDBN}.
707 Unlike most Python APIs in @value{GDBN}, @code{post_event} is
708 thread-safe. For example:
711 (@value{GDBP}) python
715 > def __init__(self, message):
716 > self.message = message;
717 > def __call__(self):
718 > gdb.write(self.message)
720 >class MyThread1 (threading.Thread):
722 > gdb.post_event(Writer("Hello "))
724 >class MyThread2 (threading.Thread):
726 > gdb.post_event(Writer("World\n"))
731 (@value{GDBP}) Hello World
736 @node Exception Handling
737 @subsubsection Exception Handling
738 @cindex python exceptions
739 @cindex exceptions, python
741 When executing the @code{python} command, Python exceptions
742 uncaught within the Python code are translated to calls to
743 @value{GDBN} error-reporting mechanism. If the command that called
744 @code{python} does not handle the error, @value{GDBN} will
745 terminate it and print an error message. Exactly what will be printed
746 depends on @code{set python print-stack} (@pxref{Python Commands}).
750 (@value{GDBP}) python print foo
751 Traceback (most recent call last):
752 File "<string>", line 1, in <module>
753 NameError: name 'foo' is not defined
756 @value{GDBN} errors that happen in @value{GDBN} commands invoked by
757 Python code are converted to Python exceptions. The type of the
758 Python exception depends on the error.
762 This is the base class for most exceptions generated by @value{GDBN}.
763 It is derived from @code{RuntimeError}, for compatibility with earlier
764 versions of @value{GDBN}.
766 If an error occurring in @value{GDBN} does not fit into some more
767 specific category, then the generated exception will have this type.
769 @item gdb.MemoryError
770 This is a subclass of @code{gdb.error} which is thrown when an
771 operation tried to access invalid memory in the inferior.
773 @item KeyboardInterrupt
774 User interrupt (via @kbd{C-c} or by typing @kbd{q} at a pagination
775 prompt) is translated to a Python @code{KeyboardInterrupt} exception.
778 In all cases, your exception handler will see the @value{GDBN} error
779 message as its value and the Python call stack backtrace at the Python
780 statement closest to where the @value{GDBN} error occurred as the
784 When implementing @value{GDBN} commands in Python via
785 @code{gdb.Command}, or functions via @code{gdb.Function}, it is useful
786 to be able to throw an exception that doesn't cause a traceback to be
787 printed. For example, the user may have invoked the command
788 incorrectly. @value{GDBN} provides a special exception class that can
789 be used for this purpose.
793 When thrown from a command or function, this exception will cause the
794 command or function to fail, but the Python stack will not be
795 displayed. @value{GDBN} does not throw this exception itself, but
796 rather recognizes it when thrown from user Python code. Example:
800 >class HelloWorld (gdb.Command):
801 > """Greet the whole world."""
802 > def __init__ (self):
803 > super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
804 > def invoke (self, args, from_tty):
805 > argv = gdb.string_to_argv (args)
806 > if len (argv) != 0:
807 > raise gdb.GdbError ("hello-world takes no arguments")
808 > print ("Hello, World!")
812 hello-world takes no arguments
816 @node Values From Inferior
817 @subsubsection Values From Inferior
818 @cindex values from inferior, with Python
819 @cindex python, working with values from inferior
821 @cindex @code{gdb.Value}
822 @value{GDBN} provides values it obtains from the inferior program in
823 an object of type @code{gdb.Value}. @value{GDBN} uses this object
824 for its internal bookkeeping of the inferior's values, and for
825 fetching values when necessary.
827 Inferior values that are simple scalars can be used directly in
828 Python expressions that are valid for the value's data type. Here's
829 an example for an integer or floating-point value @code{some_val}:
836 As result of this, @code{bar} will also be a @code{gdb.Value} object
837 whose values are of the same type as those of @code{some_val}. Valid
838 Python operations can also be performed on @code{gdb.Value} objects
839 representing a @code{struct} or @code{class} object. For such cases,
840 the overloaded operator (if present), is used to perform the operation.
841 For example, if @code{val1} and @code{val2} are @code{gdb.Value} objects
842 representing instances of a @code{class} which overloads the @code{+}
843 operator, then one can use the @code{+} operator in their Python script
851 The result of the operation @code{val3} is also a @code{gdb.Value}
852 object corresponding to the value returned by the overloaded @code{+}
853 operator. In general, overloaded operators are invoked for the
854 following operations: @code{+} (binary addition), @code{-} (binary
855 subtraction), @code{*} (multiplication), @code{/}, @code{%}, @code{<<},
856 @code{>>}, @code{|}, @code{&}, @code{^}.
858 Inferior values that are structures or instances of some class can
859 be accessed using the Python @dfn{dictionary syntax}. For example, if
860 @code{some_val} is a @code{gdb.Value} instance holding a structure, you
861 can access its @code{foo} element with:
864 bar = some_val['foo']
867 @cindex getting structure elements using gdb.Field objects as subscripts
868 Again, @code{bar} will also be a @code{gdb.Value} object. Structure
869 elements can also be accessed by using @code{gdb.Field} objects as
870 subscripts (@pxref{Types In Python}, for more information on
871 @code{gdb.Field} objects). For example, if @code{foo_field} is a
872 @code{gdb.Field} object corresponding to element @code{foo} of the above
873 structure, then @code{bar} can also be accessed as follows:
876 bar = some_val[foo_field]
879 If a @code{gdb.Value} has array or pointer type, an integer index can
880 be used to access elements.
883 result = some_array[23]
886 A @code{gdb.Value} that represents a function can be executed via
887 inferior function call. Any arguments provided to the call must match
888 the function's prototype, and must be provided in the order specified
891 For example, @code{some_val} is a @code{gdb.Value} instance
892 representing a function that takes two integers as arguments. To
893 execute this function, call it like so:
896 result = some_val (10,20)
899 Any values returned from a function call will be stored as a
902 The following attributes are provided:
904 @defvar Value.address
905 If this object is addressable, this read-only attribute holds a
906 @code{gdb.Value} object representing the address. Otherwise,
907 this attribute holds @code{None}.
910 @cindex optimized out value in Python
911 @defvar Value.is_optimized_out
912 This read-only boolean attribute is true if the compiler optimized out
913 this value, thus it is not available for fetching from the inferior.
917 The type of this @code{gdb.Value}. The value of this attribute is a
918 @code{gdb.Type} object (@pxref{Types In Python}).
921 @defvar Value.dynamic_type
922 The dynamic type of this @code{gdb.Value}. This uses the object's
923 virtual table and the C@t{++} run-time type information
924 (@acronym{RTTI}) to determine the dynamic type of the value. If this
925 value is of class type, it will return the class in which the value is
926 embedded, if any. If this value is of pointer or reference to a class
927 type, it will compute the dynamic type of the referenced object, and
928 return a pointer or reference to that type, respectively. In all
929 other cases, it will return the value's static type.
931 Note that this feature will only work when debugging a C@t{++} program
932 that includes @acronym{RTTI} for the object in question. Otherwise,
933 it will just return the static type of the value as in @kbd{ptype foo}
934 (@pxref{Symbols, ptype}).
937 @defvar Value.is_lazy
938 The value of this read-only boolean attribute is @code{True} if this
939 @code{gdb.Value} has not yet been fetched from the inferior.
940 @value{GDBN} does not fetch values until necessary, for efficiency.
944 myval = gdb.parse_and_eval ('somevar')
947 The value of @code{somevar} is not fetched at this time. It will be
948 fetched when the value is needed, or when the @code{fetch_lazy}
953 The value of this attribute is a @code{bytes} object containing the
954 bytes that make up this @code{Value}'s complete value in little endian
955 order. If the complete contents of this value are not available then
956 accessing this attribute will raise an exception.
958 This attribute can also be assigned to. The new value should be a
959 buffer object (e.g.@: a @code{bytes} object), the length of the new
960 buffer must exactly match the length of this @code{Value}'s type. The
961 bytes values in the new buffer should be in little endian order.
963 As with @code{Value.assign} (@pxref{Value.assign}), if this value
964 cannot be assigned to, then an exception will be thrown.
967 The following methods are provided:
969 @defun Value.__init__ (val)
970 Many Python values can be converted directly to a @code{gdb.Value} via
971 this object initializer. Specifically:
975 A Python boolean is converted to the boolean type from the current
979 A Python integer is converted to the C @code{long} type for the
980 current architecture.
983 A Python long is converted to the C @code{long long} type for the
984 current architecture.
987 A Python float is converted to the C @code{double} type for the
988 current architecture.
991 A Python string is converted to a target string in the current target
992 language using the current target encoding.
993 If a character cannot be represented in the current target encoding,
994 then an exception is thrown.
996 @item @code{gdb.Value}
997 If @code{val} is a @code{gdb.Value}, then a copy of the value is made.
999 @item @code{gdb.LazyString}
1000 If @code{val} is a @code{gdb.LazyString} (@pxref{Lazy Strings In
1001 Python}), then the lazy string's @code{value} method is called, and
1006 @defun Value.__init__ (val, type)
1007 This second form of the @code{gdb.Value} constructor returns a
1008 @code{gdb.Value} of type @var{type} where the value contents are taken
1009 from the Python buffer object specified by @var{val}. The number of
1010 bytes in the Python buffer object must be greater than or equal to the
1013 If @var{type} is @code{None} then this version of @code{__init__}
1014 behaves as though @var{type} was not passed at all.
1017 @anchor{Value.assign}
1018 @defun Value.assign (rhs)
1019 Assign @var{rhs} to this value, and return @code{None}. If this value
1020 cannot be assigned to, or if the assignment is invalid for some reason
1021 (for example a type-checking failure), an exception will be thrown.
1024 @defun Value.cast (type)
1025 Return a new instance of @code{gdb.Value} that is the result of
1026 casting this instance to the type described by @var{type}, which must
1027 be a @code{gdb.Type} object. If the cast cannot be performed for some
1028 reason, this method throws an exception.
1031 @defun Value.dereference ()
1032 For pointer data types, this method returns a new @code{gdb.Value} object
1033 whose contents is the object pointed to by the pointer. For example, if
1034 @code{foo} is a C pointer to an @code{int}, declared in your C program as
1041 then you can use the corresponding @code{gdb.Value} to access what
1042 @code{foo} points to like this:
1045 bar = foo.dereference ()
1048 The result @code{bar} will be a @code{gdb.Value} object holding the
1049 value pointed to by @code{foo}.
1051 A similar function @code{Value.referenced_value} exists which also
1052 returns @code{gdb.Value} objects corresponding to the values pointed to
1053 by pointer values (and additionally, values referenced by reference
1054 values). However, the behavior of @code{Value.dereference}
1055 differs from @code{Value.referenced_value} by the fact that the
1056 behavior of @code{Value.dereference} is identical to applying the C
1057 unary operator @code{*} on a given value. For example, consider a
1058 reference to a pointer @code{ptrref}, declared in your C@t{++} program
1062 typedef int *intptr;
1066 intptr &ptrref = ptr;
1069 Though @code{ptrref} is a reference value, one can apply the method
1070 @code{Value.dereference} to the @code{gdb.Value} object corresponding
1071 to it and obtain a @code{gdb.Value} which is identical to that
1072 corresponding to @code{val}. However, if you apply the method
1073 @code{Value.referenced_value}, the result would be a @code{gdb.Value}
1074 object identical to that corresponding to @code{ptr}.
1077 py_ptrref = gdb.parse_and_eval ("ptrref")
1078 py_val = py_ptrref.dereference ()
1079 py_ptr = py_ptrref.referenced_value ()
1082 The @code{gdb.Value} object @code{py_val} is identical to that
1083 corresponding to @code{val}, and @code{py_ptr} is identical to that
1084 corresponding to @code{ptr}. In general, @code{Value.dereference} can
1085 be applied whenever the C unary operator @code{*} can be applied
1086 to the corresponding C value. For those cases where applying both
1087 @code{Value.dereference} and @code{Value.referenced_value} is allowed,
1088 the results obtained need not be identical (as we have seen in the above
1089 example). The results are however identical when applied on
1090 @code{gdb.Value} objects corresponding to pointers (@code{gdb.Value}
1091 objects with type code @code{TYPE_CODE_PTR}) in a C/C@t{++} program.
1094 @defun Value.referenced_value ()
1095 For pointer or reference data types, this method returns a new
1096 @code{gdb.Value} object corresponding to the value referenced by the
1097 pointer/reference value. For pointer data types,
1098 @code{Value.dereference} and @code{Value.referenced_value} produce
1099 identical results. The difference between these methods is that
1100 @code{Value.dereference} cannot get the values referenced by reference
1101 values. For example, consider a reference to an @code{int}, declared
1102 in your C@t{++} program as
1110 then applying @code{Value.dereference} to the @code{gdb.Value} object
1111 corresponding to @code{ref} will result in an error, while applying
1112 @code{Value.referenced_value} will result in a @code{gdb.Value} object
1113 identical to that corresponding to @code{val}.
1116 py_ref = gdb.parse_and_eval ("ref")
1117 er_ref = py_ref.dereference () # Results in error
1118 py_val = py_ref.referenced_value () # Returns the referenced value
1121 The @code{gdb.Value} object @code{py_val} is identical to that
1122 corresponding to @code{val}.
1125 @defun Value.reference_value ()
1126 Return a @code{gdb.Value} object which is a reference to the value
1127 encapsulated by this instance.
1130 @defun Value.const_value ()
1131 Return a @code{gdb.Value} object which is a @code{const} version of the
1132 value encapsulated by this instance.
1135 @defun Value.dynamic_cast (type)
1136 Like @code{Value.cast}, but works as if the C@t{++} @code{dynamic_cast}
1137 operator were used. Consult a C@t{++} reference for details.
1140 @defun Value.reinterpret_cast (type)
1141 Like @code{Value.cast}, but works as if the C@t{++} @code{reinterpret_cast}
1142 operator were used. Consult a C@t{++} reference for details.
1145 @defun Value.format_string (...)
1146 Convert a @code{gdb.Value} to a string, similarly to what the @code{print}
1147 command does. Invoked with no arguments, this is equivalent to calling
1148 the @code{str} function on the @code{gdb.Value}. The representation of
1149 the same value may change across different versions of @value{GDBN}, so
1150 you shouldn't, for instance, parse the strings returned by this method.
1152 All the arguments are keyword only. If an argument is not specified, the
1153 current global default setting is used.
1157 @code{True} if pretty-printers (@pxref{Pretty Printing}) should not be
1158 used to format the value. @code{False} if enabled pretty-printers
1159 matching the type represented by the @code{gdb.Value} should be used to
1163 @code{True} if arrays should be pretty printed to be more convenient to
1164 read, @code{False} if they shouldn't (see @code{set print array} in
1165 @ref{Print Settings}).
1167 @item pretty_structs
1168 @code{True} if structs should be pretty printed to be more convenient to
1169 read, @code{False} if they shouldn't (see @code{set print pretty} in
1170 @ref{Print Settings}).
1173 @code{True} if array indexes should be included in the string
1174 representation of arrays, @code{False} if they shouldn't (see @code{set
1175 print array-indexes} in @ref{Print Settings}).
1178 @code{True} if the string representation of a pointer should include the
1179 corresponding symbol name (if one exists), @code{False} if it shouldn't
1180 (see @code{set print symbol} in @ref{Print Settings}).
1183 @code{True} if unions which are contained in other structures or unions
1184 should be expanded, @code{False} if they shouldn't (see @code{set print
1185 union} in @ref{Print Settings}).
1188 @code{True} if the string representation of a pointer should include the
1189 address, @code{False} if it shouldn't (see @code{set print address} in
1190 @ref{Print Settings}).
1193 @code{True} if binary values should be displayed in groups of four bits,
1194 known as nibbles. @code{False} if it shouldn't (@pxref{Print Settings,
1195 set print nibbles}).
1198 @code{True} if C@t{++} references should be resolved to the value they
1199 refer to, @code{False} (the default) if they shouldn't. Note that, unlike
1200 for the @code{print} command, references are not automatically expanded
1201 when using the @code{format_string} method or the @code{str}
1202 function. There is no global @code{print} setting to change the default
1205 @item actual_objects
1206 @code{True} if the representation of a pointer to an object should
1207 identify the @emph{actual} (derived) type of the object rather than the
1208 @emph{declared} type, using the virtual function table. @code{False} if
1209 the @emph{declared} type should be used. (See @code{set print object} in
1210 @ref{Print Settings}).
1212 @item static_members
1213 @code{True} if static members should be included in the string
1214 representation of a C@t{++} object, @code{False} if they shouldn't (see
1215 @code{set print static-members} in @ref{Print Settings}).
1217 @item max_characters
1218 Number of string characters to print, @code{0} to follow
1219 @code{max_elements}, or @code{UINT_MAX} to print an unlimited number
1220 of characters (see @code{set print characters} in @ref{Print Settings}).
1223 Number of array elements to print, or @code{0} to print an unlimited
1224 number of elements (see @code{set print elements} in @ref{Print
1228 The maximum depth to print for nested structs and unions, or @code{-1}
1229 to print an unlimited number of elements (see @code{set print
1230 max-depth} in @ref{Print Settings}).
1232 @item repeat_threshold
1233 Set the threshold for suppressing display of repeated array elements, or
1234 @code{0} to represent all elements, even if repeated. (See @code{set
1235 print repeats} in @ref{Print Settings}).
1238 A string containing a single character representing the format to use for
1239 the returned string. For instance, @code{'x'} is equivalent to using the
1240 @value{GDBN} command @code{print} with the @code{/x} option and formats
1241 the value as a hexadecimal number.
1244 @code{True} if @value{GDBN} should apply styling to the returned
1245 string. When styling is applied, the returned string might contain
1246 ANSI terminal escape sequences. Escape sequences will only be
1247 included if styling is turned on, see @ref{Output Styling}.
1248 Additionally, @value{GDBN} only styles some value contents, so not
1249 every output string will contain escape sequences.
1251 When @code{False}, which is the default, no output styling is applied.
1254 @code{True} when just a summary should be printed. In this mode,
1255 scalar values are printed in their entirety, but aggregates such as
1256 structures or unions are omitted. This mode is used by @code{set
1257 print frame-arguments scalars} (@pxref{Print Settings}).
1261 @defun Value.to_array ()
1262 If this value is array-like (@pxref{Type.is_array_like}), then this
1263 method converts it to an array, which is returned. If this value is
1264 already an array, it is simply returned. Otherwise, an exception is
1268 @defun Value.string (@r{[}encoding@r{[}, errors@r{[}, length@r{]]]})
1269 If this @code{gdb.Value} represents a string, then this method
1270 converts the contents to a Python string. Otherwise, this method will
1273 Values are interpreted as strings according to the rules of the
1274 current language. If the optional length argument is given, the
1275 string will be converted to that length, and will include any embedded
1276 zeroes that the string may contain. Otherwise, for languages
1277 where the string is zero-terminated, the entire string will be
1280 For example, in C-like languages, a value is a string if it is a pointer
1281 to or an array of characters or ints of type @code{wchar_t}, @code{char16_t},
1284 If the optional @var{encoding} argument is given, it must be a string
1285 naming the encoding of the string in the @code{gdb.Value}, such as
1286 @code{"ascii"}, @code{"iso-8859-6"} or @code{"utf-8"}. It accepts
1287 the same encodings as the corresponding argument to Python's
1288 @code{string.decode} method, and the Python codec machinery will be used
1289 to convert the string. If @var{encoding} is not given, or if
1290 @var{encoding} is the empty string, then either the @code{target-charset}
1291 (@pxref{Character Sets}) will be used, or a language-specific encoding
1292 will be used, if the current language is able to supply one.
1294 The optional @var{errors} argument is the same as the corresponding
1295 argument to Python's @code{string.decode} method.
1297 If the optional @var{length} argument is given, the string will be
1298 fetched and converted to the given length.
1301 @defun Value.lazy_string (@r{[}encoding @r{[}, length@r{]]})
1302 This method attempts to convert this @code{gdb.Value} to a
1303 @code{gdb.LazyString} (@pxref{Lazy Strings In Python}). Values of
1304 array or pointer type can be converted; for other types, this method
1305 will throw an exception.
1307 If the optional @var{encoding} argument is given, it must be a string
1308 naming the encoding of the @code{gdb.LazyString}. Some examples are:
1309 @samp{ascii}, @samp{iso-8859-6} or @samp{utf-8}. If the
1310 @var{encoding} argument is an encoding that @value{GDBN} does
1311 recognize, @value{GDBN} will raise an error.
1313 When a lazy string is printed, the @value{GDBN} encoding machinery is
1314 used to convert the string during printing. If the optional
1315 @var{encoding} argument is not provided, or is an empty string,
1316 @value{GDBN} will automatically select the encoding most suitable for
1317 the string type. For further information on encoding in @value{GDBN}
1318 please see @ref{Character Sets}.
1320 If the optional @var{length} argument is given, the string will be
1321 fetched and encoded to the length of characters specified. If
1322 the @var{length} argument is not provided, the string will be fetched
1323 and encoded until a null of appropriate width is found.
1326 @defun Value.fetch_lazy ()
1327 If the @code{gdb.Value} object is currently a lazy value
1328 (@code{gdb.Value.is_lazy} is @code{True}), then the value is
1329 fetched from the inferior. Any errors that occur in the process
1330 will produce a Python exception.
1332 If the @code{gdb.Value} object is not a lazy value, this method
1335 This method does not return a value.
1339 @node Types In Python
1340 @subsubsection Types In Python
1341 @cindex types in Python
1342 @cindex Python, working with types
1345 @value{GDBN} represents types from the inferior using the class
1348 The following type-related functions are available in the @code{gdb}
1351 @defun gdb.lookup_type (name @r{[}, block@r{]})
1352 This function looks up a type by its @var{name}, which must be a string.
1354 If @var{block} is given, then @var{name} is looked up in that scope.
1355 Otherwise, it is searched for globally.
1357 Ordinarily, this function will return an instance of @code{gdb.Type}.
1358 If the named type cannot be found, it will throw an exception.
1361 Integer types can be found without looking them up by name.
1362 @xref{Architectures In Python}, for the @code{integer_type} method.
1364 If the type is a structure or class type, or an enum type, the fields
1365 of that type can be accessed using the Python @dfn{dictionary syntax}.
1366 For example, if @code{some_type} is a @code{gdb.Type} instance holding
1367 a structure type, you can access its @code{foo} field with:
1370 bar = some_type['foo']
1373 @code{bar} will be a @code{gdb.Field} object; see below under the
1374 description of the @code{Type.fields} method for a description of the
1375 @code{gdb.Field} class.
1377 An instance of @code{Type} has the following attributes:
1379 @defvar Type.alignof
1380 The alignment of this type, in bytes. Type alignment comes from the
1381 debugging information; if it was not specified, then @value{GDBN} will
1382 use the relevant ABI to try to determine the alignment. In some
1383 cases, even this is not possible, and zero will be returned.
1387 The type code for this type. The type code will be one of the
1388 @code{TYPE_CODE_} constants defined below.
1391 @defvar Type.dynamic
1392 A boolean indicating whether this type is dynamic. In some
1393 situations, such as Rust @code{enum} types or Ada variant records, the
1394 concrete type of a value may vary depending on its contents. That is,
1395 the declared type of a variable, or the type returned by
1396 @code{gdb.lookup_type} may be dynamic; while the type of the
1397 variable's value will be a concrete instance of that dynamic type.
1399 For example, consider this code:
1405 Here, at least conceptually (whether your compiler actually does this
1406 is a separate issue), examining @w{@code{gdb.lookup_symbol("array", ...).type}}
1407 could yield a @code{gdb.Type} which reports a size of @code{None}.
1408 This is the dynamic type.
1410 However, examining @code{gdb.parse_and_eval("array").type} would yield
1411 a concrete type, whose length would be known.
1415 The name of this type. If this type has no name, then @code{None}
1420 The size of this type, in target @code{char} units. Usually, a
1421 target's @code{char} type will be an 8-bit byte. However, on some
1422 unusual platforms, this type may have a different size. A dynamic
1423 type may not have a fixed size; in this case, this attribute's value
1424 will be @code{None}.
1428 The tag name for this type. The tag name is the name after
1429 @code{struct}, @code{union}, or @code{enum} in C and C@t{++}; not all
1430 languages have this concept. If this type has no tag name, then
1431 @code{None} is returned.
1434 @defvar Type.objfile
1435 The @code{gdb.Objfile} that this type was defined in, or @code{None} if
1436 there is no associated objfile.
1439 @defvar Type.is_scalar
1440 This property is @code{True} if the type is a scalar type, otherwise,
1441 this property is @code{False}. Examples of non-scalar types include
1442 structures, unions, and classes.
1445 @defvar Type.is_signed
1446 For scalar types (those for which @code{Type.is_scalar} is
1447 @code{True}), this property is @code{True} if the type is signed,
1448 otherwise this property is @code{False}.
1450 Attempting to read this property for a non-scalar type (a type for
1451 which @code{Type.is_scalar} is @code{False}), will raise a
1455 @defvar Type.is_array_like
1456 @anchor{Type.is_array_like}
1457 A boolean indicating whether this type is array-like.
1459 Some languages have array-like objects that are represented internally
1460 as structures. For example, this is true for a Rust slice type, or
1461 for an Ada unconstrained array. @value{GDBN} may know about these
1462 types. This determination is done based on the language from which
1463 the type originated.
1466 @defvar Type.is_string_like
1467 A boolean indicating whether this type is string-like. Like
1468 @code{Type.is_array_like}, this is determined based on the originating
1469 language of the type.
1472 The following methods are provided:
1474 @defun Type.fields ()
1476 Return the fields of this type. The behavior depends on the type code:
1481 For structure and union types, this method returns the fields.
1484 Enum types have one field per enum constant.
1487 Function and method types have one field per parameter. The base types of
1488 C@t{++} classes are also represented as fields.
1491 Array types have one field representing the array's range.
1494 If the type does not fit into one of these categories, a @code{TypeError}
1499 Each field is a @code{gdb.Field} object, with some pre-defined attributes:
1502 This attribute is not available for @code{enum} or @code{static}
1503 (as in C@t{++}) fields. The value is the position, counting
1504 in bits, from the start of the containing type. Note that, in a
1505 dynamic type, the position of a field may not be constant. In this
1506 case, the value will be @code{None}. Also, a dynamic type may have
1507 fields that do not appear in a corresponding concrete type.
1510 This attribute is only available for @code{enum} fields, and its value
1511 is the enumeration member's integer representation.
1514 The name of the field, or @code{None} for anonymous fields.
1517 This is @code{True} if the field is artificial, usually meaning that
1518 it was provided by the compiler and not the user. This attribute is
1519 always provided, and is @code{False} if the field is not artificial.
1522 This is @code{True} if the field represents a base class of a C@t{++}
1523 structure. This attribute is always provided, and is @code{False}
1524 if the field is not a base class of the type that is the argument of
1525 @code{fields}, or if that type was not a C@t{++} class.
1528 If the field is packed, or is a bitfield, then this will have a
1529 non-zero value, which is the size of the field in bits. Otherwise,
1530 this will be zero; in this case the field's size is given by its type.
1533 The type of the field. This is usually an instance of @code{Type},
1534 but it can be @code{None} in some situations.
1537 The type which contains this field. This is an instance of
1542 @defun Type.array (n1 @r{[}, n2@r{]})
1543 Return a new @code{gdb.Type} object which represents an array of this
1544 type. If one argument is given, it is the inclusive upper bound of
1545 the array; in this case the lower bound is zero. If two arguments are
1546 given, the first argument is the lower bound of the array, and the
1547 second argument is the upper bound of the array. An array's length
1548 must not be negative, but the bounds can be.
1551 @defun Type.vector (n1 @r{[}, n2@r{]})
1552 Return a new @code{gdb.Type} object which represents a vector of this
1553 type. If one argument is given, it is the inclusive upper bound of
1554 the vector; in this case the lower bound is zero. If two arguments are
1555 given, the first argument is the lower bound of the vector, and the
1556 second argument is the upper bound of the vector. A vector's length
1557 must not be negative, but the bounds can be.
1559 The difference between an @code{array} and a @code{vector} is that
1560 arrays behave like in C: when used in expressions they decay to a pointer
1561 to the first element whereas vectors are treated as first class values.
1564 @defun Type.const ()
1565 Return a new @code{gdb.Type} object which represents a
1566 @code{const}-qualified variant of this type.
1569 @defun Type.volatile ()
1570 Return a new @code{gdb.Type} object which represents a
1571 @code{volatile}-qualified variant of this type.
1574 @defun Type.unqualified ()
1575 Return a new @code{gdb.Type} object which represents an unqualified
1576 variant of this type. That is, the result is neither @code{const} nor
1580 @defun Type.range ()
1581 Return a Python @code{Tuple} object that contains two elements: the
1582 low bound of the argument type and the high bound of that type. If
1583 the type does not have a range, @value{GDBN} will raise a
1584 @code{gdb.error} exception (@pxref{Exception Handling}).
1587 @defun Type.reference ()
1588 Return a new @code{gdb.Type} object which represents a reference to this
1592 @defun Type.pointer ()
1593 Return a new @code{gdb.Type} object which represents a pointer to this
1597 @defun Type.strip_typedefs ()
1598 Return a new @code{gdb.Type} that represents the real type,
1599 after removing all layers of typedefs.
1602 @defun Type.target ()
1603 Return a new @code{gdb.Type} object which represents the target type
1606 For a pointer type, the target type is the type of the pointed-to
1607 object. For an array type (meaning C-like arrays), the target type is
1608 the type of the elements of the array. For a function or method type,
1609 the target type is the type of the return value. For a complex type,
1610 the target type is the type of the elements. For a typedef, the
1611 target type is the aliased type.
1613 If the type does not have a target, this method will throw an
1617 @defun Type.template_argument (n @r{[}, block@r{]})
1618 If this @code{gdb.Type} is an instantiation of a template, this will
1619 return a new @code{gdb.Value} or @code{gdb.Type} which represents the
1620 value of the @var{n}th template argument (indexed starting at 0).
1622 If this @code{gdb.Type} is not a template type, or if the type has fewer
1623 than @var{n} template arguments, this will throw an exception.
1624 Ordinarily, only C@t{++} code will have template types.
1626 If @var{block} is given, then @var{name} is looked up in that scope.
1627 Otherwise, it is searched for globally.
1630 @defun Type.optimized_out ()
1631 Return @code{gdb.Value} instance of this type whose value is optimized
1632 out. This allows a frame decorator to indicate that the value of an
1633 argument or a local variable is not known.
1636 Each type has a code, which indicates what category this type falls
1637 into. The available type categories are represented by constants
1638 defined in the @code{gdb} module:
1641 @vindex TYPE_CODE_PTR
1642 @item gdb.TYPE_CODE_PTR
1643 The type is a pointer.
1645 @vindex TYPE_CODE_ARRAY
1646 @item gdb.TYPE_CODE_ARRAY
1647 The type is an array.
1649 @vindex TYPE_CODE_STRUCT
1650 @item gdb.TYPE_CODE_STRUCT
1651 The type is a structure.
1653 @vindex TYPE_CODE_UNION
1654 @item gdb.TYPE_CODE_UNION
1655 The type is a union.
1657 @vindex TYPE_CODE_ENUM
1658 @item gdb.TYPE_CODE_ENUM
1659 The type is an enum.
1661 @vindex TYPE_CODE_FLAGS
1662 @item gdb.TYPE_CODE_FLAGS
1663 A bit flags type, used for things such as status registers.
1665 @vindex TYPE_CODE_FUNC
1666 @item gdb.TYPE_CODE_FUNC
1667 The type is a function.
1669 @vindex TYPE_CODE_INT
1670 @item gdb.TYPE_CODE_INT
1671 The type is an integer type.
1673 @vindex TYPE_CODE_FLT
1674 @item gdb.TYPE_CODE_FLT
1675 A floating point type.
1677 @vindex TYPE_CODE_VOID
1678 @item gdb.TYPE_CODE_VOID
1679 The special type @code{void}.
1681 @vindex TYPE_CODE_SET
1682 @item gdb.TYPE_CODE_SET
1685 @vindex TYPE_CODE_RANGE
1686 @item gdb.TYPE_CODE_RANGE
1687 A range type, that is, an integer type with bounds.
1689 @vindex TYPE_CODE_STRING
1690 @item gdb.TYPE_CODE_STRING
1691 A string type. Note that this is only used for certain languages with
1692 language-defined string types; C strings are not represented this way.
1694 @vindex TYPE_CODE_BITSTRING
1695 @item gdb.TYPE_CODE_BITSTRING
1696 A string of bits. It is deprecated.
1698 @vindex TYPE_CODE_ERROR
1699 @item gdb.TYPE_CODE_ERROR
1700 An unknown or erroneous type.
1702 @vindex TYPE_CODE_METHOD
1703 @item gdb.TYPE_CODE_METHOD
1704 A method type, as found in C@t{++}.
1706 @vindex TYPE_CODE_METHODPTR
1707 @item gdb.TYPE_CODE_METHODPTR
1708 A pointer-to-member-function.
1710 @vindex TYPE_CODE_MEMBERPTR
1711 @item gdb.TYPE_CODE_MEMBERPTR
1712 A pointer-to-member.
1714 @vindex TYPE_CODE_REF
1715 @item gdb.TYPE_CODE_REF
1718 @vindex TYPE_CODE_RVALUE_REF
1719 @item gdb.TYPE_CODE_RVALUE_REF
1720 A C@t{++}11 rvalue reference type.
1722 @vindex TYPE_CODE_CHAR
1723 @item gdb.TYPE_CODE_CHAR
1726 @vindex TYPE_CODE_BOOL
1727 @item gdb.TYPE_CODE_BOOL
1730 @vindex TYPE_CODE_COMPLEX
1731 @item gdb.TYPE_CODE_COMPLEX
1732 A complex float type.
1734 @vindex TYPE_CODE_TYPEDEF
1735 @item gdb.TYPE_CODE_TYPEDEF
1736 A typedef to some other type.
1738 @vindex TYPE_CODE_NAMESPACE
1739 @item gdb.TYPE_CODE_NAMESPACE
1740 A C@t{++} namespace.
1742 @vindex TYPE_CODE_DECFLOAT
1743 @item gdb.TYPE_CODE_DECFLOAT
1744 A decimal floating point type.
1746 @vindex TYPE_CODE_INTERNAL_FUNCTION
1747 @item gdb.TYPE_CODE_INTERNAL_FUNCTION
1748 A function internal to @value{GDBN}. This is the type used to represent
1749 convenience functions.
1751 @vindex TYPE_CODE_XMETHOD
1752 @item gdb.TYPE_CODE_XMETHOD
1753 A method internal to @value{GDBN}. This is the type used to represent
1754 xmethods (@pxref{Writing an Xmethod}).
1756 @vindex TYPE_CODE_FIXED_POINT
1757 @item gdb.TYPE_CODE_FIXED_POINT
1758 A fixed-point number.
1760 @vindex TYPE_CODE_NAMESPACE
1761 @item gdb.TYPE_CODE_NAMESPACE
1765 Further support for types is provided in the @code{gdb.types}
1766 Python module (@pxref{gdb.types}).
1768 @node Pretty Printing API
1769 @subsubsection Pretty Printing API
1770 @cindex python pretty printing api
1772 A pretty-printer is just an object that holds a value and implements a
1773 specific interface, defined here. An example output is provided
1774 (@pxref{Pretty Printing}).
1776 Because @value{GDBN} did not document extensibility for
1777 pretty-printers, by default @value{GDBN} will assume that only the
1778 basic pretty-printer methods may be available. The basic methods are
1779 marked as such, below.
1781 To allow extensibility, @value{GDBN} provides the
1782 @code{gdb.ValuePrinter} base class. This class does not provide any
1783 attributes or behavior, but instead serves as a tag that can be
1784 recognized by @value{GDBN}. For such printers, @value{GDBN} reserves
1785 all attributes starting with a lower-case letter. That is, in the
1786 future, @value{GDBN} may add a new method or attribute to the
1787 pretty-printer protocol, and @code{gdb.ValuePrinter}-based printers
1788 are expected to handle this gracefully. A simple way to do this would
1789 be to use a leading underscore (or two, following the Python
1790 name-mangling scheme) to any attributes local to the implementation.
1792 @defun pretty_printer.children (self)
1793 @value{GDBN} will call this method on a pretty-printer to compute the
1794 children of the pretty-printer's value.
1796 This method must return an object conforming to the Python iterator
1797 protocol. Each item returned by the iterator must be a tuple holding
1798 two elements. The first element is the ``name'' of the child; the
1799 second element is the child's value. The value can be any Python
1800 object which is convertible to a @value{GDBN} value.
1802 This is a basic method, and is optional. If it does not exist,
1803 @value{GDBN} will act as though the value has no children.
1805 For efficiency, the @code{children} method should lazily compute its
1806 results. This will let @value{GDBN} read as few elements as
1807 necessary, for example when various print settings (@pxref{Print
1808 Settings}) or @code{-var-list-children} (@pxref{GDB/MI Variable
1809 Objects}) limit the number of elements to be displayed.
1811 Children may be hidden from display based on the value of @samp{set
1812 print max-depth} (@pxref{Print Settings}).
1815 @defun pretty_printer.display_hint (self)
1816 The CLI may call this method and use its result to change the
1817 formatting of a value. The result will also be supplied to an MI
1818 consumer as a @samp{displayhint} attribute of the variable being
1821 This is a basic method, and is optional. If it does exist, this
1822 method must return a string or the special value @code{None}.
1824 Some display hints are predefined by @value{GDBN}:
1828 Indicate that the object being printed is ``array-like''. The CLI
1829 uses this to respect parameters such as @code{set print elements} and
1830 @code{set print array}.
1833 Indicate that the object being printed is ``map-like'', and that the
1834 children of this value can be assumed to alternate between keys and
1838 Indicate that the object being printed is ``string-like''. If the
1839 printer's @code{to_string} method returns a Python string of some
1840 kind, then @value{GDBN} will call its internal language-specific
1841 string-printing function to format the string. For the CLI this means
1842 adding quotation marks, possibly escaping some characters, respecting
1843 @code{set print elements}, and the like.
1846 The special value @code{None} causes @value{GDBN} to apply the default
1850 @defun pretty_printer.to_string (self)
1851 @value{GDBN} will call this method to display the string
1852 representation of the value passed to the object's constructor.
1854 This is a basic method, and is optional.
1856 When printing from the CLI, if the @code{to_string} method exists,
1857 then @value{GDBN} will prepend its result to the values returned by
1858 @code{children}. Exactly how this formatting is done is dependent on
1859 the display hint, and may change as more hints are added. Also,
1860 depending on the print settings (@pxref{Print Settings}), the CLI may
1861 print just the result of @code{to_string} in a stack trace, omitting
1862 the result of @code{children}.
1864 If this method returns a string, it is printed verbatim.
1866 Otherwise, if this method returns an instance of @code{gdb.Value},
1867 then @value{GDBN} prints this value. This may result in a call to
1868 another pretty-printer.
1870 If instead the method returns a Python value which is convertible to a
1871 @code{gdb.Value}, then @value{GDBN} performs the conversion and prints
1872 the resulting value. Again, this may result in a call to another
1873 pretty-printer. Python scalars (integers, floats, and booleans) and
1874 strings are convertible to @code{gdb.Value}; other types are not.
1876 Finally, if this method returns @code{None} then no further operations
1877 are performed in this method and nothing is printed.
1879 If the result is not one of these types, an exception is raised.
1882 @defun pretty_printer.num_children ()
1883 This is not a basic method, so @value{GDBN} will only ever call it for
1884 objects derived from @code{gdb.ValuePrinter}.
1886 If available, this method should return the number of children.
1887 @code{None} may be returned if the number can't readily be computed.
1890 @defun pretty_printer.child (n)
1891 This is not a basic method, so @value{GDBN} will only ever call it for
1892 objects derived from @code{gdb.ValuePrinter}.
1894 If available, this method should return the child item (that is, a
1895 tuple holding the name and value of this child) indicated by @var{n}.
1896 Indices start at zero.
1899 @value{GDBN} provides a function which can be used to look up the
1900 default pretty-printer for a @code{gdb.Value}:
1902 @defun gdb.default_visualizer (value)
1903 This function takes a @code{gdb.Value} object as an argument. If a
1904 pretty-printer for this value exists, then it is returned. If no such
1905 printer exists, then this returns @code{None}.
1908 Normally, a pretty-printer can respect the user's print settings
1909 (including temporarily applied settings, such as @samp{/x}) simply by
1910 calling @code{Value.format_string} (@pxref{Values From Inferior}).
1911 However, these settings can also be queried directly:
1913 @defun gdb.print_options ()
1914 Return a dictionary whose keys are the valid keywords that can be
1915 given to @code{Value.format_string}, and whose values are the user's
1916 settings. During a @code{print} or other operation, the values will
1917 reflect any flags that are temporarily in effect.
1920 (gdb) python print (gdb.print_options ()['max_elements'])
1925 @node Selecting Pretty-Printers
1926 @subsubsection Selecting Pretty-Printers
1927 @cindex selecting python pretty-printers
1929 @value{GDBN} provides several ways to register a pretty-printer:
1930 globally, per program space, and per objfile. When choosing how to
1931 register your pretty-printer, a good rule is to register it with the
1932 smallest scope possible: that is prefer a specific objfile first, then
1933 a program space, and only register a printer globally as a last
1936 @defvar gdb.pretty_printers
1937 The Python list @code{gdb.pretty_printers} contains an array of
1938 functions or callable objects that have been registered via addition
1939 as a pretty-printer. Printers in this list are called @code{global}
1940 printers, they're available when debugging all inferiors.
1943 Each @code{gdb.Progspace} contains a @code{pretty_printers} attribute.
1944 Each @code{gdb.Objfile} also contains a @code{pretty_printers}
1947 Each function on these lists is passed a single @code{gdb.Value}
1948 argument and should return a pretty-printer object conforming to the
1949 interface definition above (@pxref{Pretty Printing API}). If a function
1950 cannot create a pretty-printer for the value, it should return
1953 @value{GDBN} first checks the @code{pretty_printers} attribute of each
1954 @code{gdb.Objfile} in the current program space and iteratively calls
1955 each enabled lookup routine in the list for that @code{gdb.Objfile}
1956 until it receives a pretty-printer object.
1957 If no pretty-printer is found in the objfile lists, @value{GDBN} then
1958 searches the pretty-printer list of the current program space,
1959 calling each enabled function until an object is returned.
1960 After these lists have been exhausted, it tries the global
1961 @code{gdb.pretty_printers} list, again calling each enabled function until an
1964 The order in which the objfiles are searched is not specified. For a
1965 given list, functions are always invoked from the head of the list,
1966 and iterated over sequentially until the end of the list, or a printer
1969 For various reasons a pretty-printer may not work.
1970 For example, the underlying data structure may have changed and
1971 the pretty-printer is out of date.
1973 The consequences of a broken pretty-printer are severe enough that
1974 @value{GDBN} provides support for enabling and disabling individual
1975 printers. For example, if @code{print frame-arguments} is on,
1976 a backtrace can become highly illegible if any argument is printed
1977 with a broken printer.
1979 Pretty-printers are enabled and disabled by attaching an @code{enabled}
1980 attribute to the registered function or callable object. If this attribute
1981 is present and its value is @code{False}, the printer is disabled, otherwise
1982 the printer is enabled.
1984 @node Writing a Pretty-Printer
1985 @subsubsection Writing a Pretty-Printer
1986 @cindex writing a pretty-printer
1988 A pretty-printer consists of two parts: a lookup function to detect
1989 if the type is supported, and the printer itself.
1991 Here is an example showing how a @code{std::string} printer might be
1992 written. @xref{Pretty Printing API}, for details on the API this class
1993 must provide. Note that this example uses the @code{gdb.ValuePrinter}
1994 base class, and is careful to use a leading underscore for its local
1998 class StdStringPrinter(gdb.ValuePrinter):
1999 "Print a std::string"
2001 def __init__(self, val):
2004 def to_string(self):
2005 return self.__val['_M_dataplus']['_M_p']
2007 def display_hint(self):
2011 And here is an example showing how a lookup function for the printer
2012 example above might be written.
2015 def str_lookup_function(val):
2016 lookup_tag = val.type.tag
2017 if lookup_tag is None:
2019 regex = re.compile("^std::basic_string<char,.*>$")
2020 if regex.match(lookup_tag):
2021 return StdStringPrinter(val)
2025 The example lookup function extracts the value's type, and attempts to
2026 match it to a type that it can pretty-print. If it is a type the
2027 printer can pretty-print, it will return a printer object. If not, it
2028 returns @code{None}.
2030 We recommend that you put your core pretty-printers into a Python
2031 package. If your pretty-printers are for use with a library, we
2032 further recommend embedding a version number into the package name.
2033 This practice will enable @value{GDBN} to load multiple versions of
2034 your pretty-printers at the same time, because they will have
2037 You should write auto-loaded code (@pxref{Python Auto-loading}) such that it
2038 can be evaluated multiple times without changing its meaning. An
2039 ideal auto-load file will consist solely of @code{import}s of your
2040 printer modules, followed by a call to a register pretty-printers with
2041 the current objfile.
2043 Taken as a whole, this approach will scale nicely to multiple
2044 inferiors, each potentially using a different library version.
2045 Embedding a version number in the Python package name will ensure that
2046 @value{GDBN} is able to load both sets of printers simultaneously.
2047 Then, because the search for pretty-printers is done by objfile, and
2048 because your auto-loaded code took care to register your library's
2049 printers with a specific objfile, @value{GDBN} will find the correct
2050 printers for the specific version of the library used by each
2053 To continue the @code{std::string} example (@pxref{Pretty Printing API}),
2054 this code might appear in @code{gdb.libstdcxx.v6}:
2057 def register_printers(objfile):
2058 objfile.pretty_printers.append(str_lookup_function)
2062 And then the corresponding contents of the auto-load file would be:
2065 import gdb.libstdcxx.v6
2066 gdb.libstdcxx.v6.register_printers(gdb.current_objfile())
2069 The previous example illustrates a basic pretty-printer.
2070 There are a few things that can be improved on.
2071 The printer doesn't have a name, making it hard to identify in a
2072 list of installed printers. The lookup function has a name, but
2073 lookup functions can have arbitrary, even identical, names.
2075 Second, the printer only handles one type, whereas a library typically has
2076 several types. One could install a lookup function for each desired type
2077 in the library, but one could also have a single lookup function recognize
2078 several types. The latter is the conventional way this is handled.
2079 If a pretty-printer can handle multiple data types, then its
2080 @dfn{subprinters} are the printers for the individual data types.
2082 The @code{gdb.printing} module provides a formal way of solving these
2083 problems (@pxref{gdb.printing}).
2084 Here is another example that handles multiple types.
2086 These are the types we are going to pretty-print:
2089 struct foo @{ int a, b; @};
2090 struct bar @{ struct foo x, y; @};
2093 Here are the printers:
2096 class fooPrinter(gdb.ValuePrinter):
2097 """Print a foo object."""
2099 def __init__(self, val):
2102 def to_string(self):
2103 return ("a=<" + str(self.__val["a"]) +
2104 "> b=<" + str(self.__val["b"]) + ">")
2106 class barPrinter(gdb.ValuePrinter):
2107 """Print a bar object."""
2109 def __init__(self, val):
2112 def to_string(self):
2113 return ("x=<" + str(self.__val["x"]) +
2114 "> y=<" + str(self.__val["y"]) + ">")
2117 This example doesn't need a lookup function, that is handled by the
2118 @code{gdb.printing} module. Instead a function is provided to build up
2119 the object that handles the lookup.
2124 def build_pretty_printer():
2125 pp = gdb.printing.RegexpCollectionPrettyPrinter(
2127 pp.add_printer('foo', '^foo$', fooPrinter)
2128 pp.add_printer('bar', '^bar$', barPrinter)
2132 And here is the autoload support:
2137 gdb.printing.register_pretty_printer(
2138 gdb.current_objfile(),
2139 my_library.build_pretty_printer())
2142 Finally, when this printer is loaded into @value{GDBN}, here is the
2143 corresponding output of @samp{info pretty-printer}:
2146 (gdb) info pretty-printer
2153 @node Type Printing API
2154 @subsubsection Type Printing API
2155 @cindex type printing API for Python
2157 @value{GDBN} provides a way for Python code to customize type display.
2158 This is mainly useful for substituting canonical typedef names for
2161 @cindex type printer
2162 A @dfn{type printer} is just a Python object conforming to a certain
2163 protocol. A simple base class implementing the protocol is provided;
2164 see @ref{gdb.types}. A type printer must supply at least:
2166 @defivar type_printer enabled
2167 A boolean which is True if the printer is enabled, and False
2168 otherwise. This is manipulated by the @code{enable type-printer}
2169 and @code{disable type-printer} commands.
2172 @defivar type_printer name
2173 The name of the type printer. This must be a string. This is used by
2174 the @code{enable type-printer} and @code{disable type-printer}
2178 @defmethod type_printer instantiate (self)
2179 This is called by @value{GDBN} at the start of type-printing. It is
2180 only called if the type printer is enabled. This method must return a
2181 new object that supplies a @code{recognize} method, as described below.
2185 When displaying a type, say via the @code{ptype} command, @value{GDBN}
2186 will compute a list of type recognizers. This is done by iterating
2187 first over the per-objfile type printers (@pxref{Objfiles In Python}),
2188 followed by the per-progspace type printers (@pxref{Progspaces In
2189 Python}), and finally the global type printers.
2191 @value{GDBN} will call the @code{instantiate} method of each enabled
2192 type printer. If this method returns @code{None}, then the result is
2193 ignored; otherwise, it is appended to the list of recognizers.
2195 Then, when @value{GDBN} is going to display a type name, it iterates
2196 over the list of recognizers. For each one, it calls the recognition
2197 function, stopping if the function returns a non-@code{None} value.
2198 The recognition function is defined as:
2200 @defmethod type_recognizer recognize (self, type)
2201 If @var{type} is not recognized, return @code{None}. Otherwise,
2202 return a string which is to be printed as the name of @var{type}.
2203 The @var{type} argument will be an instance of @code{gdb.Type}
2204 (@pxref{Types In Python}).
2207 @value{GDBN} uses this two-pass approach so that type printers can
2208 efficiently cache information without holding on to it too long. For
2209 example, it can be convenient to look up type information in a type
2210 printer and hold it for a recognizer's lifetime; if a single pass were
2211 done then type printers would have to make use of the event system in
2212 order to avoid holding information that could become stale as the
2215 @node Frame Filter API
2216 @subsubsection Filtering Frames
2217 @cindex frame filters api
2219 Frame filters are Python objects that manipulate the visibility of a
2220 frame or frames when a backtrace (@pxref{Backtrace}) is printed by
2223 Only commands that print a backtrace, or, in the case of @sc{gdb/mi}
2224 commands (@pxref{GDB/MI}), those that return a collection of frames
2225 are affected. The commands that work with frame filters are:
2227 @code{backtrace} (@pxref{backtrace-command,, The backtrace command}),
2228 @code{-stack-list-frames}
2229 (@pxref{-stack-list-frames,, The -stack-list-frames command}),
2230 @code{-stack-list-variables} (@pxref{-stack-list-variables,, The
2231 -stack-list-variables command}), @code{-stack-list-arguments}
2232 @pxref{-stack-list-arguments,, The -stack-list-arguments command}) and
2233 @code{-stack-list-locals} (@pxref{-stack-list-locals,, The
2234 -stack-list-locals command}).
2236 A frame filter works by taking an iterator as an argument, applying
2237 actions to the contents of that iterator, and returning another
2238 iterator (or, possibly, the same iterator it was provided in the case
2239 where the filter does not perform any operations). Typically, frame
2240 filters utilize tools such as the Python's @code{itertools} module to
2241 work with and create new iterators from the source iterator.
2242 Regardless of how a filter chooses to apply actions, it must not alter
2243 the underlying @value{GDBN} frame or frames, or attempt to alter the
2244 call-stack within @value{GDBN}. This preserves data integrity within
2245 @value{GDBN}. Frame filters are executed on a priority basis and care
2246 should be taken that some frame filters may have been executed before,
2247 and that some frame filters will be executed after.
2249 An important consideration when designing frame filters, and well
2250 worth reflecting upon, is that frame filters should avoid unwinding
2251 the call stack if possible. Some stacks can run very deep, into the
2252 tens of thousands in some cases. To search every frame when a frame
2253 filter executes may be too expensive at that step. The frame filter
2254 cannot know how many frames it has to iterate over, and it may have to
2255 iterate through them all. This ends up duplicating effort as
2256 @value{GDBN} performs this iteration when it prints the frames. If
2257 the filter can defer unwinding frames until frame decorators are
2258 executed, after the last filter has executed, it should. @xref{Frame
2259 Decorator API}, for more information on decorators. Also, there are
2260 examples for both frame decorators and filters in later chapters.
2261 @xref{Writing a Frame Filter}, for more information.
2263 The Python dictionary @code{gdb.frame_filters} contains key/object
2264 pairings that comprise a frame filter. Frame filters in this
2265 dictionary are called @code{global} frame filters, and they are
2266 available when debugging all inferiors. These frame filters must
2267 register with the dictionary directly. In addition to the
2268 @code{global} dictionary, there are other dictionaries that are loaded
2269 with different inferiors via auto-loading (@pxref{Python
2270 Auto-loading}). The two other areas where frame filter dictionaries
2271 can be found are: @code{gdb.Progspace} which contains a
2272 @code{frame_filters} dictionary attribute, and each @code{gdb.Objfile}
2273 object which also contains a @code{frame_filters} dictionary
2276 When a command is executed from @value{GDBN} that is compatible with
2277 frame filters, @value{GDBN} combines the @code{global},
2278 @code{gdb.Progspace} and all @code{gdb.Objfile} dictionaries currently
2279 loaded. All of the @code{gdb.Objfile} dictionaries are combined, as
2280 several frames, and thus several object files, might be in use.
2281 @value{GDBN} then prunes any frame filter whose @code{enabled}
2282 attribute is @code{False}. This pruned list is then sorted according
2283 to the @code{priority} attribute in each filter.
2285 Once the dictionaries are combined, pruned and sorted, @value{GDBN}
2286 creates an iterator which wraps each frame in the call stack in a
2287 @code{FrameDecorator} object, and calls each filter in order. The
2288 output from the previous filter will always be the input to the next
2291 Frame filters have a mandatory interface which each frame filter must
2292 implement, defined here:
2294 @defun FrameFilter.filter (iterator)
2295 @value{GDBN} will call this method on a frame filter when it has
2296 reached the order in the priority list for that filter.
2298 For example, if there are four frame filters:
2309 The order that the frame filters will be called is:
2312 Filter3 -> Filter2 -> Filter1 -> Filter4
2315 Note that the output from @code{Filter3} is passed to the input of
2316 @code{Filter2}, and so on.
2318 This @code{filter} method is passed a Python iterator. This iterator
2319 contains a sequence of frame decorators that wrap each
2320 @code{gdb.Frame}, or a frame decorator that wraps another frame
2321 decorator. The first filter that is executed in the sequence of frame
2322 filters will receive an iterator entirely comprised of default
2323 @code{FrameDecorator} objects. However, after each frame filter is
2324 executed, the previous frame filter may have wrapped some or all of
2325 the frame decorators with their own frame decorator. As frame
2326 decorators must also conform to a mandatory interface, these
2327 decorators can be assumed to act in a uniform manner (@pxref{Frame
2330 This method must return an object conforming to the Python iterator
2331 protocol. Each item in the iterator must be an object conforming to
2332 the frame decorator interface. If a frame filter does not wish to
2333 perform any operations on this iterator, it should return that
2336 This method is not optional. If it does not exist, @value{GDBN} will
2337 raise and print an error.
2340 @defvar FrameFilter.name
2341 The @code{name} attribute must be Python string which contains the
2342 name of the filter displayed by @value{GDBN} (@pxref{Frame Filter
2343 Management}). This attribute may contain any combination of letters
2344 or numbers. Care should be taken to ensure that it is unique. This
2345 attribute is mandatory.
2348 @defvar FrameFilter.enabled
2349 The @code{enabled} attribute must be Python boolean. This attribute
2350 indicates to @value{GDBN} whether the frame filter is enabled, and
2351 should be considered when frame filters are executed. If
2352 @code{enabled} is @code{True}, then the frame filter will be executed
2353 when any of the backtrace commands detailed earlier in this chapter
2354 are executed. If @code{enabled} is @code{False}, then the frame
2355 filter will not be executed. This attribute is mandatory.
2358 @defvar FrameFilter.priority
2359 The @code{priority} attribute must be Python integer. This attribute
2360 controls the order of execution in relation to other frame filters.
2361 There are no imposed limits on the range of @code{priority} other than
2362 it must be a valid integer. The higher the @code{priority} attribute,
2363 the sooner the frame filter will be executed in relation to other
2364 frame filters. Although @code{priority} can be negative, it is
2365 recommended practice to assume zero is the lowest priority that a
2366 frame filter can be assigned. Frame filters that have the same
2367 priority are executed in unsorted order in that priority slot. This
2368 attribute is mandatory. 100 is a good default priority.
2371 @node Frame Decorator API
2372 @subsubsection Decorating Frames
2373 @cindex frame decorator api
2375 Frame decorators are sister objects to frame filters (@pxref{Frame
2376 Filter API}). Frame decorators are applied by a frame filter and can
2377 only be used in conjunction with frame filters.
2379 The purpose of a frame decorator is to customize the printed content
2380 of each @code{gdb.Frame} in commands where frame filters are executed.
2381 This concept is called decorating a frame. Frame decorators decorate
2382 a @code{gdb.Frame} with Python code contained within each API call.
2383 This separates the actual data contained in a @code{gdb.Frame} from
2384 the decorated data produced by a frame decorator. This abstraction is
2385 necessary to maintain integrity of the data contained in each
2388 Frame decorators have a mandatory interface, defined below.
2390 @value{GDBN} already contains a frame decorator called
2391 @code{FrameDecorator}. This contains substantial amounts of
2392 boilerplate code to decorate the content of a @code{gdb.Frame}. It is
2393 recommended that other frame decorators inherit and extend this
2394 object, and only to override the methods needed.
2396 @tindex gdb.FrameDecorator
2397 @code{FrameDecorator} is defined in the Python module
2398 @code{gdb.FrameDecorator}, so your code can import it like:
2400 from gdb.FrameDecorator import FrameDecorator
2403 @defun FrameDecorator.elided (self)
2405 The @code{elided} method groups frames together in a hierarchical
2406 system. An example would be an interpreter, where multiple low-level
2407 frames make up a single call in the interpreted language. In this
2408 example, the frame filter would elide the low-level frames and present
2409 a single high-level frame, representing the call in the interpreted
2410 language, to the user.
2412 The @code{elided} function must return an iterable and this iterable
2413 must contain the frames that are being elided wrapped in a suitable
2414 frame decorator. If no frames are being elided this function may
2415 return an empty iterable, or @code{None}. Elided frames are indented
2416 from normal frames in a @code{CLI} backtrace, or in the case of
2417 @sc{gdb/mi}, are placed in the @code{children} field of the eliding
2420 It is the frame filter's task to also filter out the elided frames from
2421 the source iterator. This will avoid printing the frame twice.
2424 @defun FrameDecorator.function (self)
2426 This method returns the name of the function in the frame that is to
2429 This method must return a Python string describing the function, or
2432 If this function returns @code{None}, @value{GDBN} will not print any
2433 data for this field.
2436 @defun FrameDecorator.address (self)
2438 This method returns the address of the frame that is to be printed.
2440 This method must return a Python numeric integer type of sufficient
2441 size to describe the address of the frame, or @code{None}.
2443 If this function returns a @code{None}, @value{GDBN} will not print
2444 any data for this field.
2447 @defun FrameDecorator.filename (self)
2449 This method returns the filename and path associated with this frame.
2451 This method must return a Python string containing the filename and
2452 the path to the object file backing the frame, or @code{None}.
2454 If this function returns a @code{None}, @value{GDBN} will not print
2455 any data for this field.
2458 @defun FrameDecorator.line (self):
2460 This method returns the line number associated with the current
2461 position within the function addressed by this frame.
2463 This method must return a Python integer type, or @code{None}.
2465 If this function returns a @code{None}, @value{GDBN} will not print
2466 any data for this field.
2469 @defun FrameDecorator.frame_args (self)
2472 This method must return an iterable, or @code{None}. Returning an
2473 empty iterable, or @code{None} means frame arguments will not be
2474 printed for this frame. This iterable must contain objects that
2475 implement two methods, described here.
2477 This object must implement a @code{symbol} method which takes a
2478 single @code{self} parameter and must return a @code{gdb.Symbol}
2479 (@pxref{Symbols In Python}), or a Python string. The object must also
2480 implement a @code{value} method which takes a single @code{self}
2481 parameter and must return a @code{gdb.Value} (@pxref{Values From
2482 Inferior}), a Python value, or @code{None}. If the @code{value}
2483 method returns @code{None}, and the @code{argument} method returns a
2484 @code{gdb.Symbol}, @value{GDBN} will look-up and print the value of
2485 the @code{gdb.Symbol} automatically.
2490 class SymValueWrapper():
2492 def __init__(self, symbol, value):
2502 class SomeFrameDecorator()
2505 def frame_args(self):
2508 block = self.inferior_frame.block()
2512 # Iterate over all symbols in a block. Only add
2513 # symbols that are arguments.
2515 if not sym.is_argument:
2517 args.append(SymValueWrapper(sym,None))
2519 # Add example synthetic argument.
2520 args.append(SymValueWrapper(``foo'', 42))
2526 @defun FrameDecorator.frame_locals (self)
2528 This method must return an iterable or @code{None}. Returning an
2529 empty iterable, or @code{None} means frame local arguments will not be
2530 printed for this frame.
2532 The object interface, the description of the various strategies for
2533 reading frame locals, and the example are largely similar to those
2534 described in the @code{frame_args} function, (@pxref{frame_args,,The
2535 frame filter frame_args function}). Below is a modified example:
2538 class SomeFrameDecorator()
2541 def frame_locals(self):
2544 block = self.inferior_frame.block()
2548 # Iterate over all symbols in a block. Add all
2549 # symbols, except arguments.
2553 vars.append(SymValueWrapper(sym,None))
2555 # Add an example of a synthetic local variable.
2556 vars.append(SymValueWrapper(``bar'', 99))
2562 @defun FrameDecorator.inferior_frame (self):
2564 This method must return the underlying @code{gdb.Frame} that this
2565 frame decorator is decorating. @value{GDBN} requires the underlying
2566 frame for internal frame information to determine how to print certain
2567 values when printing a frame.
2570 @node Writing a Frame Filter
2571 @subsubsection Writing a Frame Filter
2572 @cindex writing a frame filter
2574 There are three basic elements that a frame filter must implement: it
2575 must correctly implement the documented interface (@pxref{Frame Filter
2576 API}), it must register itself with @value{GDBN}, and finally, it must
2577 decide if it is to work on the data provided by @value{GDBN}. In all
2578 cases, whether it works on the iterator or not, each frame filter must
2579 return an iterator. A bare-bones frame filter follows the pattern in
2580 the following example.
2585 class FrameFilter():
2588 # Frame filter attribute creation.
2590 # 'name' is the name of the filter that GDB will display.
2592 # 'priority' is the priority of the filter relative to other
2595 # 'enabled' is a boolean that indicates whether this filter is
2596 # enabled and should be executed.
2602 # Register this frame filter with the global frame_filters
2604 gdb.frame_filters[self.name] = self
2606 def filter(self, frame_iter):
2607 # Just return the iterator.
2611 The frame filter in the example above implements the three
2612 requirements for all frame filters. It implements the API, self
2613 registers, and makes a decision on the iterator (in this case, it just
2614 returns the iterator untouched).
2616 The first step is attribute creation and assignment, and as shown in
2617 the comments the filter assigns the following attributes: @code{name},
2618 @code{priority} and whether the filter should be enabled with the
2619 @code{enabled} attribute.
2621 The second step is registering the frame filter with the dictionary or
2622 dictionaries that the frame filter has interest in. As shown in the
2623 comments, this filter just registers itself with the global dictionary
2624 @code{gdb.frame_filters}. As noted earlier, @code{gdb.frame_filters}
2625 is a dictionary that is initialized in the @code{gdb} module when
2626 @value{GDBN} starts. What dictionary a filter registers with is an
2627 important consideration. Generally, if a filter is specific to a set
2628 of code, it should be registered either in the @code{objfile} or
2629 @code{progspace} dictionaries as they are specific to the program
2630 currently loaded in @value{GDBN}. The global dictionary is always
2631 present in @value{GDBN} and is never unloaded. Any filters registered
2632 with the global dictionary will exist until @value{GDBN} exits. To
2633 avoid filters that may conflict, it is generally better to register
2634 frame filters against the dictionaries that more closely align with
2635 the usage of the filter currently in question. @xref{Python
2636 Auto-loading}, for further information on auto-loading Python scripts.
2638 @value{GDBN} takes a hands-off approach to frame filter registration,
2639 therefore it is the frame filter's responsibility to ensure
2640 registration has occurred, and that any exceptions are handled
2641 appropriately. In particular, you may wish to handle exceptions
2642 relating to Python dictionary key uniqueness. It is mandatory that
2643 the dictionary key is the same as frame filter's @code{name}
2644 attribute. When a user manages frame filters (@pxref{Frame Filter
2645 Management}), the names @value{GDBN} will display are those contained
2646 in the @code{name} attribute.
2648 The final step of this example is the implementation of the
2649 @code{filter} method. As shown in the example comments, we define the
2650 @code{filter} method and note that the method must take an iterator,
2651 and also must return an iterator. In this bare-bones example, the
2652 frame filter is not very useful as it just returns the iterator
2653 untouched. However this is a valid operation for frame filters that
2654 have the @code{enabled} attribute set, but decide not to operate on
2657 In the next example, the frame filter operates on all frames and
2658 utilizes a frame decorator to perform some work on the frames.
2659 @xref{Frame Decorator API}, for further information on the frame
2660 decorator interface.
2662 This example works on inlined frames. It highlights frames which are
2663 inlined by tagging them with an ``[inlined]'' tag. By applying a
2664 frame decorator to all frames with the Python @code{itertools imap}
2665 method, the example defers actions to the frame decorator. Frame
2666 decorators are only processed when @value{GDBN} prints the backtrace.
2668 This introduces a new decision making topic: whether to perform
2669 decision making operations at the filtering step, or at the printing
2670 step. In this example's approach, it does not perform any filtering
2671 decisions at the filtering step beyond mapping a frame decorator to
2672 each frame. This allows the actual decision making to be performed
2673 when each frame is printed. This is an important consideration, and
2674 well worth reflecting upon when designing a frame filter. An issue
2675 that frame filters should avoid is unwinding the stack if possible.
2676 Some stacks can run very deep, into the tens of thousands in some
2677 cases. To search every frame to determine if it is inlined ahead of
2678 time may be too expensive at the filtering step. The frame filter
2679 cannot know how many frames it has to iterate over, and it would have
2680 to iterate through them all. This ends up duplicating effort as
2681 @value{GDBN} performs this iteration when it prints the frames.
2683 In this example decision making can be deferred to the printing step.
2684 As each frame is printed, the frame decorator can examine each frame
2685 in turn when @value{GDBN} iterates. From a performance viewpoint,
2686 this is the most appropriate decision to make as it avoids duplicating
2687 the effort that the printing step would undertake anyway. Also, if
2688 there are many frame filters unwinding the stack during filtering, it
2689 can substantially delay the printing of the backtrace which will
2690 result in large memory usage, and a poor user experience.
2693 class InlineFilter():
2696 self.name = "InlinedFrameFilter"
2699 gdb.frame_filters[self.name] = self
2701 def filter(self, frame_iter):
2702 frame_iter = itertools.imap(InlinedFrameDecorator,
2707 This frame filter is somewhat similar to the earlier example, except
2708 that the @code{filter} method applies a frame decorator object called
2709 @code{InlinedFrameDecorator} to each element in the iterator. The
2710 @code{imap} Python method is light-weight. It does not proactively
2711 iterate over the iterator, but rather creates a new iterator which
2712 wraps the existing one.
2714 Below is the frame decorator for this example.
2717 class InlinedFrameDecorator(FrameDecorator):
2719 def __init__(self, fobj):
2720 super(InlinedFrameDecorator, self).__init__(fobj)
2723 frame = self.inferior_frame()
2724 name = str(frame.name())
2726 if frame.type() == gdb.INLINE_FRAME:
2727 name = name + " [inlined]"
2732 This frame decorator only defines and overrides the @code{function}
2733 method. It lets the supplied @code{FrameDecorator}, which is shipped
2734 with @value{GDBN}, perform the other work associated with printing
2737 The combination of these two objects create this output from a
2741 #0 0x004004e0 in bar () at inline.c:11
2742 #1 0x00400566 in max [inlined] (b=6, a=12) at inline.c:21
2743 #2 0x00400566 in main () at inline.c:31
2746 So in the case of this example, a frame decorator is applied to all
2747 frames, regardless of whether they may be inlined or not. As
2748 @value{GDBN} iterates over the iterator produced by the frame filters,
2749 @value{GDBN} executes each frame decorator which then makes a decision
2750 on what to print in the @code{function} callback. Using a strategy
2751 like this is a way to defer decisions on the frame content to printing
2754 @subheading Eliding Frames
2756 It might be that the above example is not desirable for representing
2757 inlined frames, and a hierarchical approach may be preferred. If we
2758 want to hierarchically represent frames, the @code{elided} frame
2759 decorator interface might be preferable.
2761 This example approaches the issue with the @code{elided} method. This
2762 example is quite long, but very simplistic. It is out-of-scope for
2763 this section to write a complete example that comprehensively covers
2764 all approaches of finding and printing inlined frames. However, this
2765 example illustrates the approach an author might use.
2767 This example comprises of three sections.
2770 class InlineFrameFilter():
2773 self.name = "InlinedFrameFilter"
2776 gdb.frame_filters[self.name] = self
2778 def filter(self, frame_iter):
2779 return ElidingInlineIterator(frame_iter)
2782 This frame filter is very similar to the other examples. The only
2783 difference is this frame filter is wrapping the iterator provided to
2784 it (@code{frame_iter}) with a custom iterator called
2785 @code{ElidingInlineIterator}. This again defers actions to when
2786 @value{GDBN} prints the backtrace, as the iterator is not traversed
2789 The iterator for this example is as follows. It is in this section of
2790 the example where decisions are made on the content of the backtrace.
2793 class ElidingInlineIterator:
2794 def __init__(self, ii):
2795 self.input_iterator = ii
2801 frame = next(self.input_iterator)
2803 if frame.inferior_frame().type() != gdb.INLINE_FRAME:
2807 eliding_frame = next(self.input_iterator)
2808 except StopIteration:
2810 return ElidingFrameDecorator(eliding_frame, [frame])
2813 This iterator implements the Python iterator protocol. When the
2814 @code{next} function is called (when @value{GDBN} prints each frame),
2815 the iterator checks if this frame decorator, @code{frame}, is wrapping
2816 an inlined frame. If it is not, it returns the existing frame decorator
2817 untouched. If it is wrapping an inlined frame, it assumes that the
2818 inlined frame was contained within the next oldest frame,
2819 @code{eliding_frame}, which it fetches. It then creates and returns a
2820 frame decorator, @code{ElidingFrameDecorator}, which contains both the
2821 elided frame, and the eliding frame.
2824 class ElidingInlineDecorator(FrameDecorator):
2826 def __init__(self, frame, elided_frames):
2827 super(ElidingInlineDecorator, self).__init__(frame)
2829 self.elided_frames = elided_frames
2832 return iter(self.elided_frames)
2835 This frame decorator overrides one function and returns the inlined
2836 frame in the @code{elided} method. As before it lets
2837 @code{FrameDecorator} do the rest of the work involved in printing
2838 this frame. This produces the following output.
2841 #0 0x004004e0 in bar () at inline.c:11
2842 #2 0x00400529 in main () at inline.c:25
2843 #1 0x00400529 in max (b=6, a=12) at inline.c:15
2846 In that output, @code{max} which has been inlined into @code{main} is
2847 printed hierarchically. Another approach would be to combine the
2848 @code{function} method, and the @code{elided} method to both print a
2849 marker in the inlined frame, and also show the hierarchical
2852 @node Unwinding Frames in Python
2853 @subsubsection Unwinding Frames in Python
2854 @cindex unwinding frames in Python
2856 In @value{GDBN} terminology ``unwinding'' is the process of finding
2857 the previous frame (that is, caller's) from the current one. An
2858 unwinder has three methods. The first one checks if it can handle
2859 given frame (``sniff'' it). For the frames it can sniff an unwinder
2860 provides two additional methods: it can return frame's ID, and it can
2861 fetch registers from the previous frame. A running @value{GDBN}
2862 maintains a list of the unwinders and calls each unwinder's sniffer in
2863 turn until it finds the one that recognizes the current frame. There
2864 is an API to register an unwinder.
2866 The unwinders that come with @value{GDBN} handle standard frames.
2867 However, mixed language applications (for example, an application
2868 running Java Virtual Machine) sometimes use frame layouts that cannot
2869 be handled by the @value{GDBN} unwinders. You can write Python code
2870 that can handle such custom frames.
2872 You implement a frame unwinder in Python as a class with which has two
2873 attributes, @code{name} and @code{enabled}, with obvious meanings, and
2874 a single method @code{__call__}, which examines a given frame and
2875 returns an object (an instance of @code{gdb.UnwindInfo class)}
2876 describing it. If an unwinder does not recognize a frame, it should
2877 return @code{None}. The code in @value{GDBN} that enables writing
2878 unwinders in Python uses this object to return frame's ID and previous
2879 frame registers when @value{GDBN} core asks for them.
2881 An unwinder should do as little work as possible. Some otherwise
2882 innocuous operations can cause problems (even crashes, as this code is
2883 not well-hardened yet). For example, making an inferior call from
2884 an unwinder is unadvisable, as an inferior call will reset
2885 @value{GDBN}'s stack unwinding process, potentially causing re-entrant
2888 @subheading Unwinder Input
2890 An object passed to an unwinder (a @code{gdb.PendingFrame} instance)
2891 provides a method to read frame's registers:
2893 @defun PendingFrame.read_register (register)
2894 This method returns the contents of @var{register} in the
2895 frame as a @code{gdb.Value} object. For a description of the
2896 acceptable values of @var{register} see
2897 @ref{gdbpy_frame_read_register,,Frame.read_register}. If @var{register}
2898 does not name a register for the current architecture, this method
2899 will throw an exception.
2901 Note that this method will always return a @code{gdb.Value} for a
2902 valid register name. This does not mean that the value will be valid.
2903 For example, you may request a register that an earlier unwinder could
2904 not unwind---the value will be unavailable. Instead, the
2905 @code{gdb.Value} returned from this method will be lazy; that is, its
2906 underlying bits will not be fetched until it is first used. So,
2907 attempting to use such a value will cause an exception at the point of
2910 The type of the returned @code{gdb.Value} depends on the register and
2911 the architecture. It is common for registers to have a scalar type,
2912 like @code{long long}; but many other types are possible, such as
2913 pointer, pointer-to-function, floating point or vector types.
2916 It also provides a factory method to create a @code{gdb.UnwindInfo}
2917 instance to be returned to @value{GDBN}:
2919 @anchor{gdb.PendingFrame.create_unwind_info}
2920 @defun PendingFrame.create_unwind_info (frame_id)
2921 Returns a new @code{gdb.UnwindInfo} instance identified by given
2922 @var{frame_id}. The @var{frame_id} is used internally by @value{GDBN}
2923 to identify the frames within the current thread's stack. The
2924 attributes of @var{frame_id} determine what type of frame is
2925 created within @value{GDBN}:
2929 The frame is identified by the given stack address and PC. The stack
2930 address must be chosen so that it is constant throughout the lifetime
2931 of the frame, so a typical choice is the value of the stack pointer at
2932 the start of the function---in the DWARF standard, this would be the
2933 ``Call Frame Address''.
2935 This is the most common case by far. The other cases are documented
2936 for completeness but are only useful in specialized situations.
2938 @item sp, pc, special
2939 The frame is identified by the stack address, the PC, and a
2940 ``special'' address. The special address is used on architectures
2941 that can have frames that do not change the stack, but which are still
2942 distinct, for example the IA-64, which has a second stack for
2943 registers. Both @var{sp} and @var{special} must be constant
2944 throughout the lifetime of the frame.
2947 The frame is identified by the stack address only. Any other stack
2948 frame with a matching @var{sp} will be considered to match this frame.
2949 Inside gdb, this is called a ``wild frame''. You will never need
2953 Each attribute value should either be an instance of @code{gdb.Value}
2956 A helper class is provided in the @code{gdb.unwinder} module that can
2957 be used to represent a frame-id
2958 (@pxref{gdb.unwinder.FrameId}).
2962 @defun PendingFrame.architecture ()
2963 Return the @code{gdb.Architecture} (@pxref{Architectures In Python})
2964 for this @code{gdb.PendingFrame}. This represents the architecture of
2965 the particular frame being unwound.
2968 @defun PendingFrame.level ()
2969 Return an integer, the stack frame level for this frame.
2970 @xref{Frames, ,Stack Frames}.
2973 @defun PendingFrame.name ()
2974 Returns the function name of this pending frame, or @code{None} if it
2978 @defun PendingFrame.is_valid ()
2979 Returns true if the @code{gdb.PendingFrame} object is valid, false if
2980 not. A pending frame object becomes invalid when the call to the
2981 unwinder, for which the pending frame was created, returns.
2983 All @code{gdb.PendingFrame} methods, except this one, will raise an
2984 exception if the pending frame object is invalid at the time the
2988 @defun PendingFrame.pc ()
2989 Returns the pending frame's resume address.
2992 @defun PendingFrame.block ()
2993 Return the pending frame's code block (@pxref{Blocks In Python}). If
2994 the frame does not have a block -- for example, if there is no
2995 debugging information for the code in question -- then this will raise
2996 a @code{RuntimeError} exception.
2999 @defun PendingFrame.function ()
3000 Return the symbol for the function corresponding to this pending frame.
3001 @xref{Symbols In Python}.
3004 @defun PendingFrame.find_sal ()
3005 Return the pending frame's symtab and line object (@pxref{Symbol
3009 @defun PendingFrame.language ()
3010 Return the language of this frame, as a string, or None.
3013 @subheading Unwinder Output: UnwindInfo
3015 Use @code{PendingFrame.create_unwind_info} method described above to
3016 create a @code{gdb.UnwindInfo} instance. Use the following method to
3017 specify caller registers that have been saved in this frame:
3019 @defun gdb.UnwindInfo.add_saved_register (register, value)
3020 @var{register} identifies the register, for a description of the acceptable
3021 values see @ref{gdbpy_frame_read_register,,Frame.read_register}.
3022 @var{value} is a register value (a @code{gdb.Value} object).
3025 @subheading The @code{gdb.unwinder} Module
3027 @value{GDBN} comes with a @code{gdb.unwinder} module which contains
3028 the following classes:
3030 @deftp {class} gdb.unwinder.Unwinder
3031 The @code{Unwinder} class is a base class from which user created
3032 unwinders can derive, though it is not required that unwinders derive
3033 from this class, so long as any user created unwinder has the required
3034 @code{name} and @code{enabled} attributes.
3036 @defun gdb.unwinder.Unwinder.__init__ (name)
3037 The @var{name} is a string used to reference this unwinder within some
3038 @value{GDBN} commands (@pxref{Managing Registered Unwinders}).
3041 @defvar gdb.unwinder.name
3042 A read-only attribute which is a string, the name of this unwinder.
3045 @defvar gdb.unwinder.enabled
3046 A modifiable attribute containing a boolean; when @code{True}, the
3047 unwinder is enabled, and will be used by @value{GDBN}. When
3048 @code{False}, the unwinder has been disabled, and will not be used.
3052 @anchor{gdb.unwinder.FrameId}
3053 @deftp {class} gdb.unwinder.FrameId
3054 This is a class suitable for being used as the frame-id when calling
3055 @code{gdb.PendingFrame.create_unwind_info}. It is not required to use
3056 this class, any class with the required attribute
3057 (@pxref{gdb.PendingFrame.create_unwind_info}) will be accepted, but in
3058 most cases this class will be sufficient.
3060 @code{gdb.unwinder.FrameId} has the following method:
3062 @defun gdb.unwinder.FrameId.__init__ (sp, pc, special = @code{None})
3063 The @var{sp} and @var{pc} arguments are required and should be either
3064 a @code{gdb.Value} object, or an integer.
3066 The @var{special} argument is optional; if specified, it should be a
3067 @code{gdb.Value} object, or an integer.
3070 @code{gdb.unwinder.FrameId} has the following read-only attributes:
3072 @defvar gdb.unwinder.sp
3073 The @var{sp} value passed to the constructor.
3076 @defvar gdb.unwinder.pc
3077 The @var{pc} value passed to the constructor.
3080 @defvar gdb.unwinder.special
3081 The @var{special} value passed to the constructor, or @code{None} if
3082 no such value was passed.
3086 @subheading Registering an Unwinder
3088 Object files and program spaces can have unwinders registered with
3089 them. In addition, you can register unwinders globally.
3091 The @code{gdb.unwinders} module provides the function to register an
3094 @defun gdb.unwinder.register_unwinder (locus, unwinder, replace=False)
3095 @var{locus} specifies to which unwinder list to prepend the
3096 @var{unwinder}. It can be either an object file (@pxref{Objfiles In
3097 Python}), a program space (@pxref{Progspaces In Python}), or
3098 @code{None}, in which case the unwinder is registered globally. The
3099 newly added @var{unwinder} will be called before any other unwinder
3100 from the same locus. Two unwinders in the same locus cannot have the
3101 same name. An attempt to add an unwinder with an already existing
3102 name raises an exception unless @var{replace} is @code{True}, in which
3103 case the old unwinder is deleted and the new unwinder is registered in
3106 @value{GDBN} first calls the unwinders from all the object files in no
3107 particular order, then the unwinders from the current program space,
3108 then the globally registered unwinders, and finally the unwinders
3109 builtin to @value{GDBN}.
3112 @subheading Unwinder Skeleton Code
3114 Here is an example of how to structure a user created unwinder:
3117 from gdb.unwinder import Unwinder, FrameId
3119 class MyUnwinder(Unwinder):
3121 super().__init___("MyUnwinder_Name")
3123 def __call__(self, pending_frame):
3124 if not <we recognize frame>:
3127 # Create a FrameID. Usually the frame is identified by a
3128 # stack pointer and the function address.
3129 sp = ... compute a stack address ...
3130 pc = ... compute function address ...
3131 unwind_info = pending_frame.create_unwind_info(FrameId(sp, pc))
3133 # Find the values of the registers in the caller's frame and
3134 # save them in the result:
3135 unwind_info.add_saved_register(<register-number>, <register-value>)
3138 # Return the result:
3141 gdb.unwinder.register_unwinder(<locus>, MyUnwinder(), <replace>)
3144 @anchor{Managing Registered Unwinders}
3145 @subheading Managing Registered Unwinders
3146 @value{GDBN} defines 3 commands to manage registered unwinders. These
3150 @item info unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
3151 Lists all registered unwinders. Arguments @var{locus} and
3152 @var{name-regexp} are both optional and can be used to filter which
3153 unwinders are listed.
3155 The @var{locus} argument should be either @kbd{global},
3156 @kbd{progspace}, or the name of an object file. Only unwinders
3157 registered for the specified locus will be listed.
3159 The @var{name-regexp} is a regular expression used to match against
3160 unwinder names. When trying to match against unwinder names that
3161 include a string enclose @var{name-regexp} in quotes.
3162 @item disable unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
3163 The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
3164 unwinder} above, but instead of listing the matching unwinders, all of
3165 the matching unwinders are disabled. The @code{enabled} field of each
3166 matching unwinder is set to @code{False}.
3167 @item enable unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
3168 The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
3169 unwinder} above, but instead of listing the matching unwinders, all of
3170 the matching unwinders are enabled. The @code{enabled} field of each
3171 matching unwinder is set to @code{True}.
3174 @node Xmethods In Python
3175 @subsubsection Xmethods In Python
3176 @cindex xmethods in Python
3178 @dfn{Xmethods} are additional methods or replacements for existing
3179 methods of a C@t{++} class. This feature is useful for those cases
3180 where a method defined in C@t{++} source code could be inlined or
3181 optimized out by the compiler, making it unavailable to @value{GDBN}.
3182 For such cases, one can define an xmethod to serve as a replacement
3183 for the method defined in the C@t{++} source code. @value{GDBN} will
3184 then invoke the xmethod, instead of the C@t{++} method, to
3185 evaluate expressions. One can also use xmethods when debugging
3186 with core files. Moreover, when debugging live programs, invoking an
3187 xmethod need not involve running the inferior (which can potentially
3188 perturb its state). Hence, even if the C@t{++} method is available, it
3189 is better to use its replacement xmethod if one is defined.
3191 The xmethods feature in Python is available via the concepts of an
3192 @dfn{xmethod matcher} and an @dfn{xmethod worker}. To
3193 implement an xmethod, one has to implement a matcher and a
3194 corresponding worker for it (more than one worker can be
3195 implemented, each catering to a different overloaded instance of the
3196 method). Internally, @value{GDBN} invokes the @code{match} method of a
3197 matcher to match the class type and method name. On a match, the
3198 @code{match} method returns a list of matching @emph{worker} objects.
3199 Each worker object typically corresponds to an overloaded instance of
3200 the xmethod. They implement a @code{get_arg_types} method which
3201 returns a sequence of types corresponding to the arguments the xmethod
3202 requires. @value{GDBN} uses this sequence of types to perform
3203 overload resolution and picks a winning xmethod worker. A winner
3204 is also selected from among the methods @value{GDBN} finds in the
3205 C@t{++} source code. Next, the winning xmethod worker and the
3206 winning C@t{++} method are compared to select an overall winner. In
3207 case of a tie between a xmethod worker and a C@t{++} method, the
3208 xmethod worker is selected as the winner. That is, if a winning
3209 xmethod worker is found to be equivalent to the winning C@t{++}
3210 method, then the xmethod worker is treated as a replacement for
3211 the C@t{++} method. @value{GDBN} uses the overall winner to invoke the
3212 method. If the winning xmethod worker is the overall winner, then
3213 the corresponding xmethod is invoked via the @code{__call__} method
3214 of the worker object.
3216 If one wants to implement an xmethod as a replacement for an
3217 existing C@t{++} method, then they have to implement an equivalent
3218 xmethod which has exactly the same name and takes arguments of
3219 exactly the same type as the C@t{++} method. If the user wants to
3220 invoke the C@t{++} method even though a replacement xmethod is
3221 available for that method, then they can disable the xmethod.
3223 @xref{Xmethod API}, for API to implement xmethods in Python.
3224 @xref{Writing an Xmethod}, for implementing xmethods in Python.
3227 @subsubsection Xmethod API
3230 The @value{GDBN} Python API provides classes, interfaces and functions
3231 to implement, register and manipulate xmethods.
3232 @xref{Xmethods In Python}.
3234 An xmethod matcher should be an instance of a class derived from
3235 @code{XMethodMatcher} defined in the module @code{gdb.xmethod}, or an
3236 object with similar interface and attributes. An instance of
3237 @code{XMethodMatcher} has the following attributes:
3240 The name of the matcher.
3244 A boolean value indicating whether the matcher is enabled or disabled.
3248 A list of named methods managed by the matcher. Each object in the list
3249 is an instance of the class @code{XMethod} defined in the module
3250 @code{gdb.xmethod}, or any object with the following attributes:
3255 Name of the xmethod which should be unique for each xmethod
3256 managed by the matcher.
3259 A boolean value indicating whether the xmethod is enabled or
3264 The class @code{XMethod} is a convenience class with same
3265 attributes as above along with the following constructor:
3267 @defun XMethod.__init__ (self, name)
3268 Constructs an enabled xmethod with name @var{name}.
3273 The @code{XMethodMatcher} class has the following methods:
3275 @defun XMethodMatcher.__init__ (self, name)
3276 Constructs an enabled xmethod matcher with name @var{name}. The
3277 @code{methods} attribute is initialized to @code{None}.
3280 @defun XMethodMatcher.match (self, class_type, method_name)
3281 Derived classes should override this method. It should return a
3282 xmethod worker object (or a sequence of xmethod worker
3283 objects) matching the @var{class_type} and @var{method_name}.
3284 @var{class_type} is a @code{gdb.Type} object, and @var{method_name}
3285 is a string value. If the matcher manages named methods as listed in
3286 its @code{methods} attribute, then only those worker objects whose
3287 corresponding entries in the @code{methods} list are enabled should be
3291 An xmethod worker should be an instance of a class derived from
3292 @code{XMethodWorker} defined in the module @code{gdb.xmethod},
3293 or support the following interface:
3295 @defun XMethodWorker.get_arg_types (self)
3296 This method returns a sequence of @code{gdb.Type} objects corresponding
3297 to the arguments that the xmethod takes. It can return an empty
3298 sequence or @code{None} if the xmethod does not take any arguments.
3299 If the xmethod takes a single argument, then a single
3300 @code{gdb.Type} object corresponding to it can be returned.
3303 @defun XMethodWorker.get_result_type (self, *args)
3304 This method returns a @code{gdb.Type} object representing the type
3305 of the result of invoking this xmethod.
3306 The @var{args} argument is the same tuple of arguments that would be
3307 passed to the @code{__call__} method of this worker.
3310 @defun XMethodWorker.__call__ (self, *args)
3311 This is the method which does the @emph{work} of the xmethod. The
3312 @var{args} arguments is the tuple of arguments to the xmethod. Each
3313 element in this tuple is a gdb.Value object. The first element is
3314 always the @code{this} pointer value.
3317 For @value{GDBN} to lookup xmethods, the xmethod matchers
3318 should be registered using the following function defined in the module
3321 @defun register_xmethod_matcher (locus, matcher, replace=False)
3322 The @code{matcher} is registered with @code{locus}, replacing an
3323 existing matcher with the same name as @code{matcher} if
3324 @code{replace} is @code{True}. @code{locus} can be a
3325 @code{gdb.Objfile} object (@pxref{Objfiles In Python}), or a
3326 @code{gdb.Progspace} object (@pxref{Progspaces In Python}), or
3327 @code{None}. If it is @code{None}, then @code{matcher} is registered
3331 @node Writing an Xmethod
3332 @subsubsection Writing an Xmethod
3333 @cindex writing xmethods in Python
3335 Implementing xmethods in Python will require implementing xmethod
3336 matchers and xmethod workers (@pxref{Xmethods In Python}). Consider
3337 the following C@t{++} class:
3343 MyClass (int a) : a_(a) @{ @}
3345 int geta (void) @{ return a_; @}
3346 int operator+ (int b);
3353 MyClass::operator+ (int b)
3360 Let us define two xmethods for the class @code{MyClass}, one
3361 replacing the method @code{geta}, and another adding an overloaded
3362 flavor of @code{operator+} which takes a @code{MyClass} argument (the
3363 C@t{++} code above already has an overloaded @code{operator+}
3364 which takes an @code{int} argument). The xmethod matcher can be
3368 class MyClass_geta(gdb.xmethod.XMethod):
3370 gdb.xmethod.XMethod.__init__(self, 'geta')
3372 def get_worker(self, method_name):
3373 if method_name == 'geta':
3374 return MyClassWorker_geta()
3377 class MyClass_sum(gdb.xmethod.XMethod):
3379 gdb.xmethod.XMethod.__init__(self, 'sum')
3381 def get_worker(self, method_name):
3382 if method_name == 'operator+':
3383 return MyClassWorker_plus()
3386 class MyClassMatcher(gdb.xmethod.XMethodMatcher):
3388 gdb.xmethod.XMethodMatcher.__init__(self, 'MyClassMatcher')
3389 # List of methods 'managed' by this matcher
3390 self.methods = [MyClass_geta(), MyClass_sum()]
3392 def match(self, class_type, method_name):
3393 if class_type.tag != 'MyClass':
3396 for method in self.methods:
3398 worker = method.get_worker(method_name)
3400 workers.append(worker)
3406 Notice that the @code{match} method of @code{MyClassMatcher} returns
3407 a worker object of type @code{MyClassWorker_geta} for the @code{geta}
3408 method, and a worker object of type @code{MyClassWorker_plus} for the
3409 @code{operator+} method. This is done indirectly via helper classes
3410 derived from @code{gdb.xmethod.XMethod}. One does not need to use the
3411 @code{methods} attribute in a matcher as it is optional. However, if a
3412 matcher manages more than one xmethod, it is a good practice to list the
3413 xmethods in the @code{methods} attribute of the matcher. This will then
3414 facilitate enabling and disabling individual xmethods via the
3415 @code{enable/disable} commands. Notice also that a worker object is
3416 returned only if the corresponding entry in the @code{methods} attribute
3417 of the matcher is enabled.
3419 The implementation of the worker classes returned by the matcher setup
3420 above is as follows:
3423 class MyClassWorker_geta(gdb.xmethod.XMethodWorker):
3424 def get_arg_types(self):
3427 def get_result_type(self, obj):
3428 return gdb.lookup_type('int')
3430 def __call__(self, obj):
3434 class MyClassWorker_plus(gdb.xmethod.XMethodWorker):
3435 def get_arg_types(self):
3436 return gdb.lookup_type('MyClass')
3438 def get_result_type(self, obj):
3439 return gdb.lookup_type('int')
3441 def __call__(self, obj, other):
3442 return obj['a_'] + other['a_']
3445 For @value{GDBN} to actually lookup a xmethod, it has to be
3446 registered with it. The matcher defined above is registered with
3447 @value{GDBN} globally as follows:
3450 gdb.xmethod.register_xmethod_matcher(None, MyClassMatcher())
3453 If an object @code{obj} of type @code{MyClass} is initialized in C@t{++}
3461 then, after loading the Python script defining the xmethod matchers
3462 and workers into @value{GDBN}, invoking the method @code{geta} or using
3463 the operator @code{+} on @code{obj} will invoke the xmethods
3474 Consider another example with a C++ template class:
3481 MyTemplate () : dsize_(10), data_ (new T [10]) @{ @}
3482 ~MyTemplate () @{ delete [] data_; @}
3484 int footprint (void)
3486 return sizeof (T) * dsize_ + sizeof (MyTemplate<T>);
3495 Let us implement an xmethod for the above class which serves as a
3496 replacement for the @code{footprint} method. The full code listing
3497 of the xmethod workers and xmethod matchers is as follows:
3500 class MyTemplateWorker_footprint(gdb.xmethod.XMethodWorker):
3501 def __init__(self, class_type):
3502 self.class_type = class_type
3504 def get_arg_types(self):
3507 def get_result_type(self):
3508 return gdb.lookup_type('int')
3510 def __call__(self, obj):
3511 return (self.class_type.sizeof +
3513 self.class_type.template_argument(0).sizeof)
3516 class MyTemplateMatcher_footprint(gdb.xmethod.XMethodMatcher):
3518 gdb.xmethod.XMethodMatcher.__init__(self, 'MyTemplateMatcher')
3520 def match(self, class_type, method_name):
3521 if (re.match('MyTemplate<[ \t\n]*[_a-zA-Z][ _a-zA-Z0-9]*>',
3523 method_name == 'footprint'):
3524 return MyTemplateWorker_footprint(class_type)
3527 Notice that, in this example, we have not used the @code{methods}
3528 attribute of the matcher as the matcher manages only one xmethod. The
3529 user can enable/disable this xmethod by enabling/disabling the matcher
3532 @node Inferiors In Python
3533 @subsubsection Inferiors In Python
3534 @cindex inferiors in Python
3536 @findex gdb.Inferior
3537 Programs which are being run under @value{GDBN} are called inferiors
3538 (@pxref{Inferiors Connections and Programs}). Python scripts can access
3539 information about and manipulate inferiors controlled by @value{GDBN}
3540 via objects of the @code{gdb.Inferior} class.
3542 The following inferior-related functions are available in the @code{gdb}
3545 @defun gdb.inferiors ()
3546 Return a tuple containing all inferior objects.
3549 @defun gdb.selected_inferior ()
3550 Return an object representing the current inferior.
3553 A @code{gdb.Inferior} object has the following attributes:
3555 @defvar Inferior.num
3556 ID of inferior, as assigned by @value{GDBN}. You can use this to make
3557 Python breakpoints inferior-specific, for example
3558 (@pxref{python_breakpoint_inferior,,The Breakpoint.inferior
3562 @anchor{gdbpy_inferior_connection}
3563 @defvar Inferior.connection
3564 The @code{gdb.TargetConnection} for this inferior (@pxref{Connections
3565 In Python}), or @code{None} if this inferior has no connection.
3568 @defvar Inferior.connection_num
3569 ID of inferior's connection as assigned by @value{GDBN}, or None if
3570 the inferior is not connected to a target. @xref{Inferiors Connections
3571 and Programs}. This is equivalent to
3572 @code{gdb.Inferior.connection.num} in the case where
3573 @code{gdb.Inferior.connection} is not @code{None}.
3576 @defvar Inferior.pid
3577 Process ID of the inferior, as assigned by the underlying operating
3581 @defvar Inferior.was_attached
3582 Boolean signaling whether the inferior was created using `attach', or
3583 started by @value{GDBN} itself.
3586 @defvar Inferior.main_name
3587 A string holding the name of this inferior's ``main'' function, if it
3588 can be determined. If the name of main is not known, this is
3592 @defvar Inferior.progspace
3593 The inferior's program space. @xref{Progspaces In Python}.
3596 @defvar Inferior.arguments
3597 The inferior's command line arguments, if known. This corresponds to
3598 the @code{set args} and @code{show args} commands. @xref{Arguments}.
3600 When accessed, the value is a string holding all the arguments. The
3601 contents are quoted as they would be when passed to the shell. If
3602 there are no arguments, the value is @code{None}.
3604 Either a string or a sequence of strings can be assigned to this
3605 attribute. When a string is assigned, it is assumed to have any
3606 necessary quoting for the shell; when a sequence is assigned, the
3607 quoting is applied by @value{GDBN}.
3610 A @code{gdb.Inferior} object has the following methods:
3612 @defun Inferior.is_valid ()
3613 Returns @code{True} if the @code{gdb.Inferior} object is valid,
3614 @code{False} if not. A @code{gdb.Inferior} object will become invalid
3615 if the inferior no longer exists within @value{GDBN}. All other
3616 @code{gdb.Inferior} methods will throw an exception if it is invalid
3617 at the time the method is called.
3620 @defun Inferior.threads ()
3621 This method returns a tuple holding all the threads which are valid
3622 when it is called. If there are no valid threads, the method will
3623 return an empty tuple.
3626 @defun Inferior.architecture ()
3627 Return the @code{gdb.Architecture} (@pxref{Architectures In Python})
3628 for this inferior. This represents the architecture of the inferior
3629 as a whole. Some platforms can have multiple architectures in a
3630 single address space, so this may not match the architecture of a
3631 particular frame (@pxref{Frames In Python}).
3634 @anchor{gdbpy_inferior_read_memory}
3635 @defun Inferior.read_memory (address, length)
3636 Read @var{length} addressable memory units from the inferior, starting
3637 at @var{address}. Returns a @code{memoryview} object, which behaves
3638 much like an array or a string. It can be modified and given to the
3639 @code{Inferior.write_memory} function.
3642 @defun Inferior.write_memory (address, buffer @r{[}, length@r{]})
3643 Write the contents of @var{buffer} to the inferior, starting at
3644 @var{address}. The @var{buffer} parameter must be a Python object
3645 which supports the buffer protocol, i.e., a string, an array or the
3646 object returned from @code{Inferior.read_memory}. If given, @var{length}
3647 determines the number of addressable memory units from @var{buffer} to be
3651 @defun Inferior.search_memory (address, length, pattern)
3652 Search a region of the inferior memory starting at @var{address} with
3653 the given @var{length} using the search pattern supplied in
3654 @var{pattern}. The @var{pattern} parameter must be a Python object
3655 which supports the buffer protocol, i.e., a string, an array or the
3656 object returned from @code{gdb.read_memory}. Returns a Python @code{Long}
3657 containing the address where the pattern was found, or @code{None} if
3658 the pattern could not be found.
3661 @findex Inferior.thread_from_thread_handle
3662 @defun Inferior.thread_from_handle (handle)
3663 Return the thread object corresponding to @var{handle}, a thread
3664 library specific data structure such as @code{pthread_t} for pthreads
3665 library implementations.
3667 The function @code{Inferior.thread_from_thread_handle} provides
3668 the same functionality, but use of @code{Inferior.thread_from_thread_handle}
3673 The environment that will be passed to the inferior can be changed
3674 from Python by using the following methods. These methods only take
3675 effect when the inferior is started -- they will not affect an
3676 inferior that is already executing.
3678 @defun Inferior.clear_env ()
3679 Clear the current environment variables that will be passed to this
3683 @defun Inferior.set_env (name, value)
3684 Set the environment variable @var{name} to have the indicated value.
3685 Both parameters must be strings.
3688 @defun Inferior.unset_env (name)
3689 Unset the environment variable @var{name}. @var{name} must be a
3693 One may add arbitrary attributes to @code{gdb.Inferior} objects in the
3694 usual Python way. This is useful if, for example, one needs to do
3695 some extra record keeping associated with the inferior.
3697 @anchor{choosing attribute names}
3698 When selecting a name for a new attribute, avoid starting the new
3699 attribute name with a lower case letter; future attributes added by
3700 @value{GDBN} will start with a lower case letter. Additionally, avoid
3701 starting attribute names with two underscore characters, as these
3702 could clash with Python builtin attribute names.
3704 In this contrived example we record the time when an inferior last
3709 (@value{GDBP}) python
3712 def thread_stopped(event):
3713 if event.inferior_thread is not None:
3714 thread = event.inferior_thread
3716 thread = gdb.selected_thread()
3717 inferior = thread.inferior
3718 inferior._last_stop_time = datetime.datetime.today()
3720 gdb.events.stop.connect(thread_stopped)
3723 (@value{GDBP}) file /tmp/hello
3724 Reading symbols from /tmp/hello...
3725 (@value{GDBP}) start
3726 Temporary breakpoint 1 at 0x401198: file /tmp/hello.c, line 18.
3727 Starting program: /tmp/hello
3729 Temporary breakpoint 1, main () at /tmp/hello.c:18
3730 18 printf ("Hello World\n");
3731 (@value{GDBP}) python print(gdb.selected_inferior()._last_stop_time)
3732 2024-01-04 14:48:41.347036
3736 @node Events In Python
3737 @subsubsection Events In Python
3738 @cindex inferior events in Python
3740 @value{GDBN} provides a general event facility so that Python code can be
3741 notified of various state changes, particularly changes that occur in
3744 An @dfn{event} is just an object that describes some state change. The
3745 type of the object and its attributes will vary depending on the details
3746 of the change. All the existing events are described below.
3748 In order to be notified of an event, you must register an event handler
3749 with an @dfn{event registry}. An event registry is an object in the
3750 @code{gdb.events} module which dispatches particular events. A registry
3751 provides methods to register and unregister event handlers:
3753 @defun EventRegistry.connect (object)
3754 Add the given callable @var{object} to the registry. This object will be
3755 called when an event corresponding to this registry occurs.
3758 @defun EventRegistry.disconnect (object)
3759 Remove the given @var{object} from the registry. Once removed, the object
3760 will no longer receive notifications of events.
3766 def exit_handler (event):
3767 print ("event type: exit")
3768 if hasattr (event, 'exit_code'):
3769 print ("exit code: %d" % (event.exit_code))
3771 print ("exit code not available")
3773 gdb.events.exited.connect (exit_handler)
3776 In the above example we connect our handler @code{exit_handler} to the
3777 registry @code{events.exited}. Once connected, @code{exit_handler} gets
3778 called when the inferior exits. The argument @dfn{event} in this example is
3779 of type @code{gdb.ExitedEvent}. As you can see in the example the
3780 @code{ExitedEvent} object has an attribute which indicates the exit code of
3783 Some events can be thread specific when @value{GDBN} is running in
3784 non-stop mode. When represented in Python, these events all extend
3785 @code{gdb.ThreadEvent}. This event is a base class and is never
3786 emitted directly; instead, events which are emitted by this or other
3787 modules might extend this event. Examples of these events are
3788 @code{gdb.BreakpointEvent} and @code{gdb.ContinueEvent}.
3789 @code{gdb.ThreadEvent} holds the following attributes:
3791 @defvar ThreadEvent.inferior_thread
3792 In non-stop mode this attribute will be set to the specific thread which was
3793 involved in the emitted event. Otherwise, it will be set to @code{None}.
3796 The following is a listing of the event registries that are available and
3797 details of the events they emit:
3802 Emits @code{gdb.ContinueEvent}, which extends @code{gdb.ThreadEvent}.
3803 This event indicates that the inferior has been continued after a
3804 stop. For inherited attribute refer to @code{gdb.ThreadEvent} above.
3807 Emits @code{events.ExitedEvent}, which indicates that the inferior has
3808 exited. @code{events.ExitedEvent} has two attributes:
3810 @defvar ExitedEvent.exit_code
3811 An integer representing the exit code, if available, which the inferior
3812 has returned. (The exit code could be unavailable if, for example,
3813 @value{GDBN} detaches from the inferior.) If the exit code is unavailable,
3814 the attribute does not exist.
3817 @defvar ExitedEvent.inferior
3818 A reference to the inferior which triggered the @code{exited} event.
3822 Emits @code{gdb.StopEvent}, which extends @code{gdb.ThreadEvent}.
3824 Indicates that the inferior has stopped. All events emitted by this
3825 registry extend @code{gdb.StopEvent}. As a child of
3826 @code{gdb.ThreadEvent}, @code{gdb.StopEvent} will indicate the stopped
3827 thread when @value{GDBN} is running in non-stop mode. Refer to
3828 @code{gdb.ThreadEvent} above for more details.
3830 @code{gdb.StopEvent} has the following additional attributes:
3832 @defvar StopEvent.details
3833 A dictionary holding any details relevant to the stop. The exact keys
3834 and values depend on the type of stop, but are identical to the
3835 corresponding MI output (@pxref{GDB/MI Async Records}).
3837 A dictionary was used for this (rather than adding attributes directly
3838 to the event object) so that the MI keys could be used unchanged.
3840 When a @code{StopEvent} results from a @code{finish} command, it will
3841 also hold the return value from the function, if that is available.
3842 This will be an entry named @samp{return-value} in the @code{details}
3843 dictionary. The value of this entry will be a @code{gdb.Value}
3847 Emits @code{gdb.SignalEvent}, which extends @code{gdb.StopEvent}.
3849 This event indicates that the inferior or one of its threads has
3850 received a signal. @code{gdb.SignalEvent} has the following
3853 @defvar SignalEvent.stop_signal
3854 A string representing the signal received by the inferior. A list of possible
3855 signal values can be obtained by running the command @code{info signals} in
3856 the @value{GDBN} command prompt.
3859 Also emits @code{gdb.BreakpointEvent}, which extends
3860 @code{gdb.StopEvent}.
3862 @code{gdb.BreakpointEvent} event indicates that one or more breakpoints have
3863 been hit, and has the following attributes:
3865 @defvar BreakpointEvent.breakpoints
3866 A sequence containing references to all the breakpoints (type
3867 @code{gdb.Breakpoint}) that were hit.
3868 @xref{Breakpoints In Python}, for details of the @code{gdb.Breakpoint} object.
3871 @defvar BreakpointEvent.breakpoint
3872 A reference to the first breakpoint that was hit. This attribute is
3873 maintained for backward compatibility and is now deprecated in favor
3874 of the @code{gdb.BreakpointEvent.breakpoints} attribute.
3877 @item events.new_objfile
3878 Emits @code{gdb.NewObjFileEvent} which indicates that a new object file has
3879 been loaded by @value{GDBN}. @code{gdb.NewObjFileEvent} has one attribute:
3881 @defvar NewObjFileEvent.new_objfile
3882 A reference to the object file (@code{gdb.Objfile}) which has been loaded.
3883 @xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
3886 @item events.free_objfile
3887 Emits @code{gdb.FreeObjFileEvent} which indicates that an object file
3888 is about to be removed from @value{GDBN}. One reason this can happen
3889 is when the inferior calls @code{dlclose}.
3890 @code{gdb.FreeObjFileEvent} has one attribute:
3892 @defvar FreeObjFileEvent.objfile
3893 A reference to the object file (@code{gdb.Objfile}) which will be unloaded.
3894 @xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
3897 @item events.clear_objfiles
3898 Emits @code{gdb.ClearObjFilesEvent} which indicates that the list of object
3899 files for a program space has been reset.
3900 @code{gdb.ClearObjFilesEvent} has one attribute:
3902 @defvar ClearObjFilesEvent.progspace
3903 A reference to the program space (@code{gdb.Progspace}) whose objfile list has
3904 been cleared. @xref{Progspaces In Python}.
3907 @item events.inferior_call
3908 Emits events just before and after a function in the inferior is
3909 called by @value{GDBN}. Before an inferior call, this emits an event
3910 of type @code{gdb.InferiorCallPreEvent}, and after an inferior call,
3911 this emits an event of type @code{gdb.InferiorCallPostEvent}.
3914 @tindex gdb.InferiorCallPreEvent
3915 @item @code{gdb.InferiorCallPreEvent}
3916 Indicates that a function in the inferior is about to be called.
3918 @defvar InferiorCallPreEvent.ptid
3919 The thread in which the call will be run.
3922 @defvar InferiorCallPreEvent.address
3923 The location of the function to be called.
3926 @tindex gdb.InferiorCallPostEvent
3927 @item @code{gdb.InferiorCallPostEvent}
3928 Indicates that a function in the inferior has just been called.
3930 @defvar InferiorCallPostEvent.ptid
3931 The thread in which the call was run.
3934 @defvar InferiorCallPostEvent.address
3935 The location of the function that was called.
3939 @item events.memory_changed
3940 Emits @code{gdb.MemoryChangedEvent} which indicates that the memory of the
3941 inferior has been modified by the @value{GDBN} user, for instance via a
3942 command like @w{@code{set *addr = value}}. The event has the following
3945 @defvar MemoryChangedEvent.address
3946 The start address of the changed region.
3949 @defvar MemoryChangedEvent.length
3950 Length in bytes of the changed region.
3953 @item events.register_changed
3954 Emits @code{gdb.RegisterChangedEvent} which indicates that a register in the
3955 inferior has been modified by the @value{GDBN} user.
3957 @defvar RegisterChangedEvent.frame
3958 A gdb.Frame object representing the frame in which the register was modified.
3960 @defvar RegisterChangedEvent.regnum
3961 Denotes which register was modified.
3964 @item events.breakpoint_created
3965 This is emitted when a new breakpoint has been created. The argument
3966 that is passed is the new @code{gdb.Breakpoint} object.
3968 @item events.breakpoint_modified
3969 This is emitted when a breakpoint has been modified in some way. The
3970 argument that is passed is the new @code{gdb.Breakpoint} object.
3972 @item events.breakpoint_deleted
3973 This is emitted when a breakpoint has been deleted. The argument that
3974 is passed is the @code{gdb.Breakpoint} object. When this event is
3975 emitted, the @code{gdb.Breakpoint} object will already be in its
3976 invalid state; that is, the @code{is_valid} method will return
3979 @item events.before_prompt
3980 This event carries no payload. It is emitted each time @value{GDBN}
3981 presents a prompt to the user.
3983 @item events.new_inferior
3984 This is emitted when a new inferior is created. Note that the
3985 inferior is not necessarily running; in fact, it may not even have an
3986 associated executable.
3988 The event is of type @code{gdb.NewInferiorEvent}. This has a single
3991 @defvar NewInferiorEvent.inferior
3992 The new inferior, a @code{gdb.Inferior} object.
3995 @item events.inferior_deleted
3996 This is emitted when an inferior has been deleted. Note that this is
3997 not the same as process exit; it is notified when the inferior itself
3998 is removed, say via @code{remove-inferiors}.
4000 The event is of type @code{gdb.InferiorDeletedEvent}. This has a single
4003 @defvar InferiorDeletedEvent.inferior
4004 The inferior that is being removed, a @code{gdb.Inferior} object.
4007 @item events.new_thread
4008 This is emitted when @value{GDBN} notices a new thread. The event is of
4009 type @code{gdb.NewThreadEvent}, which extends @code{gdb.ThreadEvent}.
4010 This has a single attribute:
4012 @defvar NewThreadEvent.inferior_thread
4016 @item events.thread_exited
4017 This is emitted when @value{GDBN} notices a thread has exited. The event
4018 is of type @code{gdb.ThreadExitedEvent} which extends @code{gdb.ThreadEvent}.
4019 This has a single attribute:
4021 @defvar ThreadExitedEvent.inferior_thread
4025 @item events.gdb_exiting
4026 This is emitted when @value{GDBN} exits. This event is not emitted if
4027 @value{GDBN} exits as a result of an internal error, or after an
4028 unexpected signal. The event is of type @code{gdb.GdbExitingEvent},
4029 which has a single attribute:
4031 @defvar GdbExitingEvent.exit_code
4032 An integer, the value of the exit code @value{GDBN} will return.
4035 @item events.connection_removed
4036 This is emitted when @value{GDBN} removes a connection
4037 (@pxref{Connections In Python}). The event is of type
4038 @code{gdb.ConnectionEvent}. This has a single read-only attribute:
4040 @defvar ConnectionEvent.connection
4041 The @code{gdb.TargetConnection} that is being removed.
4044 @item events.executable_changed
4045 Emits @code{gdb.ExecutableChangedEvent} which indicates that the
4046 @code{gdb.Progspace.executable_filename} has changed.
4048 This event is emitted when either the value of
4049 @code{gdb.Progspace.executable_filename } has changed to name a
4050 different file, or the executable file named by
4051 @code{gdb.Progspace.executable_filename} has changed on disk, and
4052 @value{GDBN} has therefore reloaded it.
4054 @defvar ExecutableChangedEvent.progspace
4055 The @code{gdb.Progspace} in which the current executable has changed.
4056 The file name of the updated executable will be visible in
4057 @code{gdb.Progspace.executable_filename} (@pxref{Progspaces In Python}).
4059 @defvar ExecutableChangedEvent.reload
4060 This attribute will be @code{True} if the value of
4061 @code{gdb.Progspace.executable_filename} didn't change, but the file
4062 it names changed on disk instead, and @value{GDBN} reloaded it.
4064 When this attribute is @code{False}, the value in
4065 @code{gdb.Progspace.executable_filename} was changed to name a
4069 Remember that @value{GDBN} tracks the executable file and the symbol
4070 file separately, these are visible as
4071 @code{gdb.Progspace.executable_filename} and
4072 @code{gdb.Progspace.filename} respectively. When using the @kbd{file}
4073 command, @value{GDBN} updates both of these fields, but the executable
4074 file is updated first, so when this event is emitted, the executable
4075 filename will have changed, but the symbol filename might still hold
4078 @item events.new_progspace
4079 This is emitted when @value{GDBN} adds a new program space
4080 (@pxref{Progspaces In Python,,Program Spaces In Python}). The event
4081 is of type @code{gdb.NewProgspaceEvent}, and has a single read-only
4084 @defvar NewProgspaceEvent.progspace
4085 The @code{gdb.Progspace} that was added to @value{GDBN}.
4088 No @code{NewProgspaceEvent} is emitted for the very first program
4089 space, which is assigned to the first inferior. This first program
4090 space is created within @value{GDBN} before any Python scripts are
4093 @item events.free_progspace
4094 This is emitted when @value{GDBN} removes a program space
4095 (@pxref{Progspaces In Python,,Program Spaces In Python}), for example
4096 as a result of the @kbd{remove-inferiors} command
4097 (@pxref{remove_inferiors_cli,,@kbd{remove-inferiors}}). The event is
4098 of type @code{gdb.FreeProgspaceEvent}, and has a single read-only
4101 @defvar FreeProgspaceEvent.progspace
4102 The @code{gdb.Progspace} that is about to be removed from
4106 @item events.tui_enabled
4107 This is emitted when the TUI is enabled or disabled. The event is of
4108 type @code{gdb.TuiEnabledEvent}, which has a single read-only
4111 @defvar TuiEnabledEvent.enabled
4112 If the TUI has just been enabled, this is @code{True}; otherwise it is
4118 @node Threads In Python
4119 @subsubsection Threads In Python
4120 @cindex threads in python
4122 @findex gdb.InferiorThread
4123 Python scripts can access information about, and manipulate inferior threads
4124 controlled by @value{GDBN}, via objects of the @code{gdb.InferiorThread} class.
4126 The following thread-related functions are available in the @code{gdb}
4129 @defun gdb.selected_thread ()
4130 This function returns the thread object for the selected thread. If there
4131 is no selected thread, this will return @code{None}.
4134 To get the list of threads for an inferior, use the @code{Inferior.threads()}
4135 method. @xref{Inferiors In Python}.
4137 A @code{gdb.InferiorThread} object has the following attributes:
4139 @defvar InferiorThread.name
4140 The name of the thread. If the user specified a name using
4141 @code{thread name}, then this returns that name. Otherwise, if an
4142 OS-supplied name is available, then it is returned. Otherwise, this
4143 returns @code{None}.
4145 This attribute can be assigned to. The new value must be a string
4146 object, which sets the new name, or @code{None}, which removes any
4147 user-specified thread name.
4150 @defvar InferiorThread.num
4151 The per-inferior number of the thread, as assigned by GDB.
4154 @defvar InferiorThread.global_num
4155 The global ID of the thread, as assigned by GDB. You can use this to
4156 make Python breakpoints thread-specific, for example
4157 (@pxref{python_breakpoint_thread,,The Breakpoint.thread attribute}).
4160 @anchor{inferior_thread_ptid}
4161 @defvar InferiorThread.ptid
4162 ID of the thread, as assigned by the operating system. This attribute is a
4163 tuple containing three integers. The first is the Process ID (PID); the second
4164 is the Lightweight Process ID (LWPID), and the third is the Thread ID (TID).
4165 Either the LWPID or TID may be 0, which indicates that the operating system
4166 does not use that identifier.
4169 @defvar InferiorThread.ptid_string
4170 This read-only attribute contains a string representing
4171 @code{InferiorThread.ptid}. This is the string that @value{GDBN} uses
4172 in the @samp{Target Id} column in the @kbd{info threads} output
4173 (@pxref{info_threads,,@samp{info threads}}).
4176 @defvar InferiorThread.inferior
4177 The inferior this thread belongs to. This attribute is represented as
4178 a @code{gdb.Inferior} object. This attribute is not writable.
4181 @defvar InferiorThread.details
4182 A string containing target specific thread state information. The
4183 format of this string varies by target. If there is no additional
4184 state information for this thread, then this attribute contains
4187 For example, on a @sc{gnu}/Linux system, a thread that is in the
4188 process of exiting will return the string @samp{Exiting}. For remote
4189 targets the @code{details} string will be obtained with the
4190 @samp{qThreadExtraInfo} remote packet, if the target supports it
4191 (@pxref{qThreadExtraInfo,,@samp{qThreadExtraInfo}}).
4193 @value{GDBN} displays the @code{details} string as part of the
4194 @samp{Target Id} column, in the @code{info threads} output
4195 (@pxref{info_threads,,@samp{info threads}}).
4198 A @code{gdb.InferiorThread} object has the following methods:
4200 @defun InferiorThread.is_valid ()
4201 Returns @code{True} if the @code{gdb.InferiorThread} object is valid,
4202 @code{False} if not. A @code{gdb.InferiorThread} object will become
4203 invalid if the thread exits, or the inferior that the thread belongs
4204 is deleted. All other @code{gdb.InferiorThread} methods will throw an
4205 exception if it is invalid at the time the method is called.
4208 @defun InferiorThread.switch ()
4209 This changes @value{GDBN}'s currently selected thread to the one represented
4213 @defun InferiorThread.is_stopped ()
4214 Return a Boolean indicating whether the thread is stopped.
4217 @defun InferiorThread.is_running ()
4218 Return a Boolean indicating whether the thread is running.
4221 @defun InferiorThread.is_exited ()
4222 Return a Boolean indicating whether the thread is exited.
4225 @defun InferiorThread.handle ()
4226 Return the thread object's handle, represented as a Python @code{bytes}
4227 object. A @code{gdb.Value} representation of the handle may be
4228 constructed via @code{gdb.Value(bufobj, type)} where @var{bufobj} is
4229 the Python @code{bytes} representation of the handle and @var{type} is
4230 a @code{gdb.Type} for the handle type.
4233 One may add arbitrary attributes to @code{gdb.InferiorThread} objects
4234 in the usual Python way. This is useful if, for example, one needs to
4235 do some extra record keeping associated with the thread.
4237 @xref{choosing attribute names}, for guidance on selecting a suitable
4238 name for new attributes.
4240 In this contrived example we record the time when a thread last
4245 (@value{GDBP}) python
4248 def thread_stopped(event):
4249 if event.inferior_thread is not None:
4250 thread = event.inferior_thread
4252 thread = gdb.selected_thread()
4253 thread._last_stop_time = datetime.datetime.today()
4255 gdb.events.stop.connect(thread_stopped)
4258 (@value{GDBP}) file /tmp/hello
4259 Reading symbols from /tmp/hello...
4260 (@value{GDBP}) start
4261 Temporary breakpoint 1 at 0x401198: file /tmp/hello.c, line 18.
4262 Starting program: /tmp/hello
4264 Temporary breakpoint 1, main () at /tmp/hello.c:18
4265 18 printf ("Hello World\n");
4266 (@value{GDBP}) python print(gdb.selected_thread()._last_stop_time)
4267 2024-01-04 14:48:41.347036
4271 @node Recordings In Python
4272 @subsubsection Recordings In Python
4273 @cindex recordings in python
4275 The following recordings-related functions
4276 (@pxref{Process Record and Replay}) are available in the @code{gdb}
4279 @defun gdb.start_recording (@r{[}method@r{]}, @r{[}format@r{]})
4280 Start a recording using the given @var{method} and @var{format}. If
4281 no @var{format} is given, the default format for the recording method
4282 is used. If no @var{method} is given, the default method will be used.
4283 Returns a @code{gdb.Record} object on success. Throw an exception on
4286 The following strings can be passed as @var{method}:
4292 @code{"btrace"}: Possible values for @var{format}: @code{"pt"},
4293 @code{"bts"} or leave out for default format.
4297 @defun gdb.current_recording ()
4298 Access a currently running recording. Return a @code{gdb.Record}
4299 object on success. Return @code{None} if no recording is currently
4303 @defun gdb.stop_recording ()
4304 Stop the current recording. Throw an exception if no recording is
4305 currently active. All record objects become invalid after this call.
4308 A @code{gdb.Record} object has the following attributes:
4310 @defvar Record.method
4311 A string with the current recording method, e.g.@: @code{full} or
4315 @defvar Record.format
4316 A string with the current recording format, e.g.@: @code{bt}, @code{pts} or
4320 @defvar Record.begin
4321 A method specific instruction object representing the first instruction
4326 A method specific instruction object representing the current
4327 instruction, that is not actually part of the recording.
4330 @defvar Record.replay_position
4331 The instruction representing the current replay position. If there is
4332 no replay active, this will be @code{None}.
4335 @defvar Record.instruction_history
4336 A list with all recorded instructions.
4339 @defvar Record.function_call_history
4340 A list with all recorded function call segments.
4343 A @code{gdb.Record} object has the following methods:
4345 @defun Record.goto (instruction)
4346 Move the replay position to the given @var{instruction}.
4349 @defun Record.clear ()
4350 Clear the trace data of the current recording. This forces re-decoding of the
4351 trace for successive commands.
4354 The common @code{gdb.Instruction} class that recording method specific
4355 instruction objects inherit from, has the following attributes:
4357 @defvar Instruction.pc
4358 An integer representing this instruction's address.
4361 @defvar Instruction.data
4362 A @code{memoryview} object holding the raw instruction data.
4365 @defvar Instruction.decoded
4366 A human readable string with the disassembled instruction.
4369 @defvar Instruction.size
4370 The size of the instruction in bytes.
4373 Additionally @code{gdb.RecordInstruction} has the following attributes:
4375 @defvar RecordInstruction.number
4376 An integer identifying this instruction. @code{number} corresponds to
4377 the numbers seen in @code{record instruction-history}
4378 (@pxref{Process Record and Replay}).
4381 @defvar RecordInstruction.sal
4382 A @code{gdb.Symtab_and_line} object representing the associated symtab
4383 and line of this instruction. May be @code{None} if no debug information is
4387 @defvar RecordInstruction.is_speculative
4388 A boolean indicating whether the instruction was executed speculatively.
4391 If an error occurred during recording or decoding a recording, this error is
4392 represented by a @code{gdb.RecordGap} object in the instruction list. It has
4393 the following attributes:
4395 @defvar RecordGap.number
4396 An integer identifying this gap. @code{number} corresponds to the numbers seen
4397 in @code{record instruction-history} (@pxref{Process Record and Replay}).
4400 @defvar RecordGap.error_code
4401 A numerical representation of the reason for the gap. The value is specific to
4402 the current recording method.
4405 @defvar RecordGap.error_string
4406 A human readable string with the reason for the gap.
4409 Some @value{GDBN} features write auxiliary information into the execution
4410 history. This information is represented by a @code{gdb.RecordAuxiliary} object
4411 in the instruction list. It has the following attributes:
4413 @defvar RecordAuxiliary.@var{number}
4414 An integer identifying this auxiliary. @var{number} corresponds to the numbers
4415 seen in @code{record instruction-history} (@pxref{Process Record and Replay}).
4418 @defvar RecordAuxiliary.data
4419 A string representation of the auxiliary data.
4422 A @code{gdb.RecordFunctionSegment} object has the following attributes:
4424 @defvar RecordFunctionSegment.number
4425 An integer identifying this function segment. @code{number} corresponds to
4426 the numbers seen in @code{record function-call-history}
4427 (@pxref{Process Record and Replay}).
4430 @defvar RecordFunctionSegment.symbol
4431 A @code{gdb.Symbol} object representing the associated symbol. May be
4432 @code{None} if no debug information is available.
4435 @defvar RecordFunctionSegment.level
4436 An integer representing the function call's stack level. May be
4437 @code{None} if the function call is a gap.
4440 @defvar RecordFunctionSegment.instructions
4441 A list of @code{gdb.RecordInstruction} or @code{gdb.RecordGap} objects
4442 associated with this function call.
4445 @defvar RecordFunctionSegment.up
4446 A @code{gdb.RecordFunctionSegment} object representing the caller's
4447 function segment. If the call has not been recorded, this will be the
4448 function segment to which control returns. If neither the call nor the
4449 return have been recorded, this will be @code{None}.
4452 @defvar RecordFunctionSegment.prev
4453 A @code{gdb.RecordFunctionSegment} object representing the previous
4454 segment of this function call. May be @code{None}.
4457 @defvar RecordFunctionSegment.next
4458 A @code{gdb.RecordFunctionSegment} object representing the next segment of
4459 this function call. May be @code{None}.
4462 The following example demonstrates the usage of these objects and
4463 functions to create a function that will rewind a record to the last
4464 time a function in a different file was executed. This would typically
4465 be used to track the execution of user provided callback functions in a
4466 library which typically are not visible in a back trace.
4470 rec = gdb.current_recording ()
4474 insn = rec.instruction_history
4479 position = insn.index (rec.replay_position)
4483 filename = insn[position].sal.symtab.fullname ()
4487 for i in reversed (insn[:position]):
4489 current = i.sal.symtab.fullname ()
4493 if filename == current:
4500 Another possible application is to write a function that counts the
4501 number of code executions in a given line range. This line range can
4502 contain parts of functions or span across several functions and is not
4503 limited to be contiguous.
4506 def countrange (filename, linerange):
4509 def filter_only (file_name):
4510 for call in gdb.current_recording ().function_call_history:
4512 if file_name in call.symbol.symtab.fullname ():
4517 for c in filter_only (filename):
4518 for i in c.instructions:
4520 if i.sal.line in linerange:
4529 @node CLI Commands In Python
4530 @subsubsection CLI Commands In Python
4532 @cindex CLI commands in python
4533 @cindex commands in python, CLI
4534 @cindex python commands, CLI
4535 You can implement new @value{GDBN} CLI commands in Python. A CLI
4536 command is implemented using an instance of the @code{gdb.Command}
4537 class, most commonly using a subclass.
4539 @anchor{Command.__init__}
4540 @defun Command.__init__ (name, command_class @r{[}, completer_class @r{[}, prefix@r{]]})
4541 The object initializer for @code{Command} registers the new command
4542 with @value{GDBN}. This initializer is normally invoked from the
4543 subclass' own @code{__init__} method.
4545 @var{name} is the name of the command. If @var{name} consists of
4546 multiple words, then the initial words are looked for as prefix
4547 commands. In this case, if one of the prefix commands does not exist,
4548 an exception is raised.
4550 There is no support for multi-line commands.
4552 @var{command_class} should be one of the @samp{COMMAND_} constants
4553 defined below. This argument tells @value{GDBN} how to categorize the
4554 new command in the help system.
4556 @var{completer_class} is an optional argument. If given, it should be
4557 one of the @samp{COMPLETE_} constants defined below. This argument
4558 tells @value{GDBN} how to perform completion for this command. If not
4559 given, @value{GDBN} will attempt to complete using the object's
4560 @code{complete} method (see below); if no such method is found, an
4561 error will occur when completion is attempted.
4563 @var{prefix} is an optional argument. If @code{True}, then the new
4564 command is a prefix command; sub-commands of this command may be
4567 The help text for the new command is taken from the Python
4568 documentation string for the command's class, if there is one. If no
4569 documentation string is provided, the default value @samp{This command
4570 is not documented.} is used.
4573 @anchor{Command.dont_repeat}
4574 @cindex don't repeat Python command
4575 @defun Command.dont_repeat ()
4576 By default, a @value{GDBN} command is repeated when the user enters a
4577 blank line at the command prompt. A command can suppress this
4578 behavior by invoking the @code{dont_repeat} method at some point in
4579 its @code{invoke} method (normally this is done early in case of
4580 exception). This is similar to the user command @code{dont-repeat},
4581 see @ref{Define, dont-repeat}.
4584 @anchor{Command.invoke}
4585 @defun Command.invoke (argument, from_tty)
4586 This method is called by @value{GDBN} when this command is invoked.
4588 @var{argument} is a string. It is the argument to the command, after
4589 leading and trailing whitespace has been stripped.
4591 @var{from_tty} is a boolean argument. When true, this means that the
4592 command was entered by the user at the terminal; when false it means
4593 that the command came from elsewhere.
4595 If this method throws an exception, it is turned into a @value{GDBN}
4596 @code{error} call. Otherwise, the return value is ignored.
4598 For non-prefix commands (@pxref{Command.__init__}), the @code{invoke}
4599 method is required. For prefix commands the @code{invoke} method is
4600 optional. Only prefix commands that need to handle unknown
4601 sub-commands should implement the @code{invoke} method.
4603 For prefix commands that don't implement @code{invoke}, if the prefix
4604 command is used without a sub-command name then @value{GDBN} will
4605 display the help text for every sub-command, unless the prefix command
4606 is a @kbd{show} sub-command, in which case @value{GDBN} will list the
4607 values of all sub-commands.
4609 @findex gdb.string_to_argv
4610 To break @var{argument} up into an argv-like string use
4611 @code{gdb.string_to_argv}. This function behaves identically to
4612 @value{GDBN}'s internal argument lexer @code{buildargv}.
4613 It is recommended to use this for consistency.
4614 Arguments are separated by spaces and may be quoted.
4618 print gdb.string_to_argv ("1 2\ \\\"3 '4 \"5' \"6 '7\"")
4619 ['1', '2 "3', '4 "5', "6 '7"]
4624 @cindex completion of Python commands
4625 @defun Command.complete (text, word)
4626 This method is called by @value{GDBN} when the user attempts
4627 completion on this command. All forms of completion are handled by
4628 this method, that is, the @key{TAB} and @key{M-?} key bindings
4629 (@pxref{Completion}), and the @code{complete} command (@pxref{Help,
4632 The arguments @var{text} and @var{word} are both strings; @var{text}
4633 holds the complete command line up to the cursor's location, while
4634 @var{word} holds the last word of the command line; this is computed
4635 using a word-breaking heuristic.
4637 The @code{complete} method can return several values:
4640 If the return value is a sequence, the contents of the sequence are
4641 used as the completions. It is up to @code{complete} to ensure that the
4642 contents actually do complete the word. A zero-length sequence is
4643 allowed, it means that there were no completions available. Only
4644 string elements of the sequence are used; other elements in the
4645 sequence are ignored.
4648 If the return value is one of the @samp{COMPLETE_} constants defined
4649 below, then the corresponding @value{GDBN}-internal completion
4650 function is invoked, and its result is used.
4653 All other results are treated as though there were no available
4658 When a new command is registered, it must be declared as a member of
4659 some general class of commands. This is used to classify top-level
4660 commands in the on-line help system; note that prefix commands are not
4661 listed under their own category but rather that of their top-level
4662 command. The available classifications are represented by constants
4663 defined in the @code{gdb} module:
4666 @findex COMMAND_NONE
4667 @findex gdb.COMMAND_NONE
4668 @item gdb.COMMAND_NONE
4669 The command does not belong to any particular class. A command in
4670 this category will not be displayed in any of the help categories.
4672 @findex COMMAND_RUNNING
4673 @findex gdb.COMMAND_RUNNING
4674 @item gdb.COMMAND_RUNNING
4675 The command is related to running the inferior. For example,
4676 @code{start}, @code{step}, and @code{continue} are in this category.
4677 Type @kbd{help running} at the @value{GDBN} prompt to see a list of
4678 commands in this category.
4680 @findex COMMAND_DATA
4681 @findex gdb.COMMAND_DATA
4682 @item gdb.COMMAND_DATA
4683 The command is related to data or variables. For example,
4684 @code{call}, @code{find}, and @code{print} are in this category. Type
4685 @kbd{help data} at the @value{GDBN} prompt to see a list of commands
4688 @findex COMMAND_STACK
4689 @findex gdb.COMMAND_STACK
4690 @item gdb.COMMAND_STACK
4691 The command has to do with manipulation of the stack. For example,
4692 @code{backtrace}, @code{frame}, and @code{return} are in this
4693 category. Type @kbd{help stack} at the @value{GDBN} prompt to see a
4694 list of commands in this category.
4696 @findex COMMAND_FILES
4697 @findex gdb.COMMAND_FILES
4698 @item gdb.COMMAND_FILES
4699 This class is used for file-related commands. For example,
4700 @code{file}, @code{list} and @code{section} are in this category.
4701 Type @kbd{help files} at the @value{GDBN} prompt to see a list of
4702 commands in this category.
4704 @findex COMMAND_SUPPORT
4705 @findex gdb.COMMAND_SUPPORT
4706 @item gdb.COMMAND_SUPPORT
4707 This should be used for ``support facilities'', generally meaning
4708 things that are useful to the user when interacting with @value{GDBN},
4709 but not related to the state of the inferior. For example,
4710 @code{help}, @code{make}, and @code{shell} are in this category. Type
4711 @kbd{help support} at the @value{GDBN} prompt to see a list of
4712 commands in this category.
4714 @findex COMMAND_STATUS
4715 @findex gdb.COMMAND_STATUS
4716 @item gdb.COMMAND_STATUS
4717 The command is an @samp{info}-related command, that is, related to the
4718 state of @value{GDBN} itself. For example, @code{info}, @code{macro},
4719 and @code{show} are in this category. Type @kbd{help status} at the
4720 @value{GDBN} prompt to see a list of commands in this category.
4722 @findex COMMAND_BREAKPOINTS
4723 @findex gdb.COMMAND_BREAKPOINTS
4724 @item gdb.COMMAND_BREAKPOINTS
4725 The command has to do with breakpoints. For example, @code{break},
4726 @code{clear}, and @code{delete} are in this category. Type @kbd{help
4727 breakpoints} at the @value{GDBN} prompt to see a list of commands in
4730 @findex COMMAND_TRACEPOINTS
4731 @findex gdb.COMMAND_TRACEPOINTS
4732 @item gdb.COMMAND_TRACEPOINTS
4733 The command has to do with tracepoints. For example, @code{trace},
4734 @code{actions}, and @code{tfind} are in this category. Type
4735 @kbd{help tracepoints} at the @value{GDBN} prompt to see a list of
4736 commands in this category.
4739 @findex gdb.COMMAND_TUI
4740 @item gdb.COMMAND_TUI
4741 The command has to do with the text user interface (@pxref{TUI}).
4742 Type @kbd{help tui} at the @value{GDBN} prompt to see a list of
4743 commands in this category.
4745 @findex COMMAND_USER
4746 @findex gdb.COMMAND_USER
4747 @item gdb.COMMAND_USER
4748 The command is a general purpose command for the user, and typically
4749 does not fit in one of the other categories.
4750 Type @kbd{help user-defined} at the @value{GDBN} prompt to see
4751 a list of commands in this category, as well as the list of gdb macros
4752 (@pxref{Sequences}).
4754 @findex COMMAND_OBSCURE
4755 @findex gdb.COMMAND_OBSCURE
4756 @item gdb.COMMAND_OBSCURE
4757 The command is only used in unusual circumstances, or is not of
4758 general interest to users. For example, @code{checkpoint},
4759 @code{fork}, and @code{stop} are in this category. Type @kbd{help
4760 obscure} at the @value{GDBN} prompt to see a list of commands in this
4763 @findex COMMAND_MAINTENANCE
4764 @findex gdb.COMMAND_MAINTENANCE
4765 @item gdb.COMMAND_MAINTENANCE
4766 The command is only useful to @value{GDBN} maintainers. The
4767 @code{maintenance} and @code{flushregs} commands are in this category.
4768 Type @kbd{help internals} at the @value{GDBN} prompt to see a list of
4769 commands in this category.
4772 A new command can use a predefined completion function, either by
4773 specifying it via an argument at initialization, or by returning it
4774 from the @code{complete} method. These predefined completion
4775 constants are all defined in the @code{gdb} module:
4778 @vindex COMPLETE_NONE
4779 @item gdb.COMPLETE_NONE
4780 This constant means that no completion should be done.
4782 @vindex COMPLETE_FILENAME
4783 @item gdb.COMPLETE_FILENAME
4784 This constant means that filename completion should be performed.
4786 @vindex COMPLETE_LOCATION
4787 @item gdb.COMPLETE_LOCATION
4788 This constant means that location completion should be done.
4789 @xref{Location Specifications}.
4791 @vindex COMPLETE_COMMAND
4792 @item gdb.COMPLETE_COMMAND
4793 This constant means that completion should examine @value{GDBN}
4796 @vindex COMPLETE_SYMBOL
4797 @item gdb.COMPLETE_SYMBOL
4798 This constant means that completion should be done using symbol names
4801 @vindex COMPLETE_EXPRESSION
4802 @item gdb.COMPLETE_EXPRESSION
4803 This constant means that completion should be done on expressions.
4804 Often this means completing on symbol names, but some language
4805 parsers also have support for completing on field names.
4808 The following code snippet shows how a trivial CLI command can be
4809 implemented in Python:
4812 class HelloWorld (gdb.Command):
4813 """Greet the whole world."""
4815 def __init__ (self):
4816 super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
4818 def invoke (self, arg, from_tty):
4819 print ("Hello, World!")
4824 The last line instantiates the class, and is necessary to trigger the
4825 registration of the command with @value{GDBN}. Depending on how the
4826 Python code is read into @value{GDBN}, you may need to import the
4827 @code{gdb} module explicitly.
4829 @node GDB/MI Commands In Python
4830 @subsubsection @sc{gdb/mi} Commands In Python
4832 @cindex MI commands in python
4833 @cindex commands in python, GDB/MI
4834 @cindex python commands, GDB/MI
4835 It is possible to add @sc{gdb/mi} (@pxref{GDB/MI}) commands
4836 implemented in Python. A @sc{gdb/mi} command is implemented using an
4837 instance of the @code{gdb.MICommand} class, most commonly using a
4840 @defun MICommand.__init__ (name)
4841 The object initializer for @code{MICommand} registers the new command
4842 with @value{GDBN}. This initializer is normally invoked from the
4843 subclass' own @code{__init__} method.
4845 @var{name} is the name of the command. It must be a valid name of a
4846 @sc{gdb/mi} command, and in particular must start with a hyphen
4847 (@code{-}). Reusing the name of a built-in @sc{gdb/mi} is not
4848 allowed, and a @code{RuntimeError} will be raised. Using the name
4849 of an @sc{gdb/mi} command previously defined in Python is allowed, the
4850 previous command will be replaced with the new command.
4853 @defun MICommand.invoke (arguments)
4854 This method is called by @value{GDBN} when the new MI command is
4857 @var{arguments} is a list of strings. Note, that @code{--thread}
4858 and @code{--frame} arguments are handled by @value{GDBN} itself therefore
4859 they do not show up in @code{arguments}.
4861 If this method raises an exception, then it is turned into a
4862 @sc{gdb/mi} @code{^error} response. Only @code{gdb.GdbError}
4863 exceptions (or its sub-classes) should be used for reporting errors to
4864 users, any other exception type is treated as a failure of the
4865 @code{invoke} method, and the exception will be printed to the error
4866 stream according to the @kbd{set python print-stack} setting
4867 (@pxref{set_python_print_stack,,@kbd{set python print-stack}}).
4869 If this method returns @code{None}, then the @sc{gdb/mi} command will
4870 return a @code{^done} response with no additional values.
4872 Otherwise, the return value must be a dictionary, which is converted
4873 to a @sc{gdb/mi} @var{result-record} (@pxref{GDB/MI Output Syntax}).
4874 The keys of this dictionary must be strings, and are used as
4875 @var{variable} names in the @var{result-record}, these strings must
4876 comply with the naming rules detailed below. The values of this
4877 dictionary are recursively handled as follows:
4881 If the value is Python sequence or iterator, it is converted to
4882 @sc{gdb/mi} @var{list} with elements converted recursively.
4885 If the value is Python dictionary, it is converted to
4886 @sc{gdb/mi} @var{tuple}. Keys in that dictionary must be strings,
4887 which comply with the @var{variable} naming rules detailed below.
4888 Values are converted recursively.
4891 Otherwise, value is first converted to a Python string using
4892 @code{str ()} and then converted to @sc{gdb/mi} @var{const}.
4895 The strings used for @var{variable} names in the @sc{gdb/mi} output
4896 must follow the following rules; the string must be at least one
4897 character long, the first character must be in the set
4898 @code{[a-zA-Z]}, while every subsequent character must be in the set
4899 @code{[-_a-zA-Z0-9]}.
4902 An instance of @code{MICommand} has the following attributes:
4904 @defvar MICommand.name
4905 A string, the name of this @sc{gdb/mi} command, as was passed to the
4906 @code{__init__} method. This attribute is read-only.
4909 @defvar MICommand.installed
4910 A boolean value indicating if this command is installed ready for a
4911 user to call from the command line. Commands are automatically
4912 installed when they are instantiated, after which this attribute will
4915 If later, a new command is created with the same name, then the
4916 original command will become uninstalled, and this attribute will be
4919 This attribute is read-write, setting this attribute to @code{False}
4920 will uninstall the command, removing it from the set of available
4921 commands. Setting this attribute to @code{True} will install the
4922 command for use. If there is already a Python command with this name
4923 installed, the currently installed command will be uninstalled, and
4924 this command installed in its stead.
4927 The following code snippet shows how some trivial MI commands can be
4928 implemented in Python:
4931 class MIEcho(gdb.MICommand):
4932 """Echo arguments passed to the command."""
4934 def __init__(self, name, mode):
4936 super(MIEcho, self).__init__(name)
4938 def invoke(self, argv):
4939 if self._mode == 'dict':
4940 return @{ 'dict': @{ 'argv' : argv @} @}
4941 elif self._mode == 'list':
4942 return @{ 'list': argv @}
4944 return @{ 'string': ", ".join(argv) @}
4947 MIEcho("-echo-dict", "dict")
4948 MIEcho("-echo-list", "list")
4949 MIEcho("-echo-string", "string")
4952 The last three lines instantiate the class three times, creating three
4953 new @sc{gdb/mi} commands @code{-echo-dict}, @code{-echo-list}, and
4954 @code{-echo-string}. Each time a subclass of @code{gdb.MICommand} is
4955 instantiated, the new command is automatically registered with
4958 Depending on how the Python code is read into @value{GDBN}, you may
4959 need to import the @code{gdb} module explicitly.
4961 The following example shows a @value{GDBN} session in which the above
4962 commands have been added:
4966 -echo-dict abc def ghi
4967 ^done,dict=@{argv=["abc","def","ghi"]@}
4969 -echo-list abc def ghi
4970 ^done,list=["abc","def","ghi"]
4972 -echo-string abc def ghi
4973 ^done,string="abc, def, ghi"
4977 Conversely, it is possible to execute @sc{gdb/mi} commands from
4978 Python, with the results being a Python object and not a
4979 specially-formatted string. This is done with the
4980 @code{gdb.execute_mi} function.
4982 @defun gdb.execute_mi (command @r{[}, arg @r{]}@dots{})
4983 Invoke a @sc{gdb/mi} command. @var{command} is the name of the
4984 command, a string. The arguments, @var{arg}, are passed to the
4985 command. Each argument must also be a string.
4987 This function returns a Python dictionary whose contents reflect the
4988 corresponding @sc{gdb/mi} command's output. Refer to the
4989 documentation for these commands for details. Lists are represented
4990 as Python lists, and tuples are represented as Python dictionaries.
4992 If the command fails, it will raise a Python exception.
4995 Here is how this works using the commands from the example above:
4998 (@value{GDBP}) python print(gdb.execute_mi("-echo-dict", "abc", "def", "ghi"))
4999 @{'dict': @{'argv': ['abc', 'def', 'ghi']@}@}
5000 (@value{GDBP}) python print(gdb.execute_mi("-echo-list", "abc", "def", "ghi"))
5001 @{'list': ['abc', 'def', 'ghi']@}
5002 (@value{GDBP}) python print(gdb.execute_mi("-echo-string", "abc", "def", "ghi"))
5003 @{'string': 'abc, def, ghi'@}
5006 @node GDB/MI Notifications In Python
5007 @subsubsection @sc{gdb/mi} Notifications In Python
5009 @cindex MI notifications in python
5010 @cindex notifications in python, GDB/MI
5011 @cindex python notifications, GDB/MI
5013 It is possible to emit @sc{gdb/mi} notifications from
5014 Python. Use the @code{gdb.notify_mi} function to do that.
5016 @defun gdb.notify_mi (name @r{[}, data@r{]})
5017 Emit a @sc{gdb/mi} asynchronous notification. @var{name} is the name of the
5018 notification, consisting of alphanumeric characters and a hyphen (@code{-}).
5019 @var{data} is any additional data to be emitted with the notification, passed
5020 as a Python dictionary. This argument is optional. The dictionary is converted
5021 to a @sc{gdb/mi} @var{result} records (@pxref{GDB/MI Output Syntax}) the same way
5022 as result of Python MI command (@pxref{GDB/MI Commands In Python}).
5024 If @var{data} is @code{None} then no additional values are emitted.
5027 While using existing notification names (@pxref{GDB/MI Async Records}) with
5028 @code{gdb.notify_mi} is allowed, users are encouraged to prefix user-defined
5029 notification with a hyphen (@code{-}) to avoid possible conflict.
5030 @value{GDBN} will never introduce notification starting with hyphen.
5032 Here is how to emit @code{=-connection-removed} whenever a connection to remote
5033 GDB server is closed (@pxref{Connections In Python}):
5036 def notify_connection_removed(event):
5037 data = @{"id": event.connection.num, "type": event.connection.type@}
5038 gdb.notify_mi("-connection-removed", data)
5041 gdb.events.connection_removed.connect(notify_connection_removed)
5044 Then, each time a connection is closed, there will be a notification on MI channel:
5047 =-connection-removed,id="1",type="remote"
5050 @node Parameters In Python
5051 @subsubsection Parameters In Python
5053 @cindex parameters in python
5054 @cindex python parameters
5055 @tindex gdb.Parameter
5057 You can implement new @value{GDBN} parameters using Python. A new
5058 parameter is implemented as an instance of the @code{gdb.Parameter}
5061 Parameters are exposed to the user via the @code{set} and
5062 @code{show} commands. @xref{Help}.
5064 There are many parameters that already exist and can be set in
5065 @value{GDBN}. Two examples are: @code{set follow fork} and
5066 @code{set charset}. Setting these parameters influences certain
5067 behavior in @value{GDBN}. Similarly, you can define parameters that
5068 can be used to influence behavior in custom Python scripts and commands.
5070 @defun Parameter.__init__ (name, command_class, parameter_class @r{[}, enum_sequence@r{]})
5071 The object initializer for @code{Parameter} registers the new
5072 parameter with @value{GDBN}. This initializer is normally invoked
5073 from the subclass' own @code{__init__} method.
5075 @var{name} is the name of the new parameter. If @var{name} consists
5076 of multiple words, then the initial words are looked for as prefix
5077 parameters. An example of this can be illustrated with the
5078 @code{set print} set of parameters. If @var{name} is
5079 @code{print foo}, then @code{print} will be searched as the prefix
5080 parameter. In this case the parameter can subsequently be accessed in
5081 @value{GDBN} as @code{set print foo}.
5083 If @var{name} consists of multiple words, and no prefix parameter group
5084 can be found, an exception is raised.
5086 @var{command_class} should be one of the @samp{COMMAND_} constants
5087 (@pxref{CLI Commands In Python}). This argument tells @value{GDBN} how to
5088 categorize the new parameter in the help system.
5090 @var{parameter_class} should be one of the @samp{PARAM_} constants
5091 defined below. This argument tells @value{GDBN} the type of the new
5092 parameter; this information is used for input validation and
5095 If @var{parameter_class} is @code{PARAM_ENUM}, then
5096 @var{enum_sequence} must be a sequence of strings. These strings
5097 represent the possible values for the parameter.
5099 If @var{parameter_class} is not @code{PARAM_ENUM}, then the presence
5100 of a fourth argument will cause an exception to be thrown.
5102 The help text for the new parameter includes the Python documentation
5103 string from the parameter's class, if there is one. If there is no
5104 documentation string, a default value is used. The documentation
5105 string is included in the output of the parameters @code{help set} and
5106 @code{help show} commands, and should be written taking this into
5107 account. If the documentation string for the parameter's class is the
5108 empty string then @value{GDBN} will only use @code{Parameter.set_doc}
5109 or @code{Parameter.show_doc} (see below) in the @kbd{help} output.
5112 @defvar Parameter.set_doc
5113 If this attribute exists, and is a string, then its value is used as
5114 the first part of the help text for this parameter's @code{set}
5115 command. The second part of the help text is taken from the
5116 documentation string for the parameter's class, if there is one.
5118 The value of @code{set_doc} should give a brief summary specific to
5119 the set action, this text is only displayed when the user runs the
5120 @code{help set} command for this parameter. The class documentation
5121 should be used to give a fuller description of what the parameter
5122 does, this text is displayed for both the @code{help set} and
5123 @code{help show} commands.
5125 The @code{set_doc} value is examined when @code{Parameter.__init__} is
5126 invoked; subsequent changes have no effect.
5129 @defvar Parameter.show_doc
5130 If this attribute exists, and is a string, then its value is used as
5131 the first part of the help text for this parameter's @code{show}
5132 command. The second part of the help text is taken from the
5133 documentation string for the parameter's class, if there is one.
5135 The value of @code{show_doc} should give a brief summary specific to
5136 the show action, this text is only displayed when the user runs the
5137 @code{help show} command for this parameter. The class documentation
5138 should be used to give a fuller description of what the parameter
5139 does, this text is displayed for both the @code{help set} and
5140 @code{help show} commands.
5142 The @code{show_doc} value is examined when @code{Parameter.__init__}
5143 is invoked; subsequent changes have no effect.
5146 @defvar Parameter.value
5147 The @code{value} attribute holds the underlying value of the
5148 parameter. It can be read and assigned to just as any other
5149 attribute. @value{GDBN} does validation when assignments are made.
5152 There are two methods that may be implemented in any @code{Parameter}
5155 @defun Parameter.get_set_string (self)
5156 If this method exists, @value{GDBN} will call it when a
5157 @var{parameter}'s value has been changed via the @code{set} API (for
5158 example, @kbd{set foo off}). The @code{value} attribute has already
5159 been populated with the new value and may be used in output. This
5160 method must return a string. If the returned string is not empty,
5161 @value{GDBN} will present it to the user.
5163 If this method raises the @code{gdb.GdbError} exception
5164 (@pxref{Exception Handling}), then @value{GDBN} will print the
5165 exception's string and the @code{set} command will fail. Note,
5166 however, that the @code{value} attribute will not be reset in this
5167 case. So, if your parameter must validate values, it should store the
5168 old value internally and reset the exposed value, like so:
5171 class ExampleParam (gdb.Parameter):
5172 def __init__ (self, name):
5173 super (ExampleParam, self).__init__ (name,
5177 self.saved_value = True
5180 def get_set_string (self):
5181 if not self.validate():
5182 self.value = self.saved_value
5183 raise gdb.GdbError('Failed to validate')
5184 self.saved_value = self.value
5189 @defun Parameter.get_show_string (self, svalue)
5190 @value{GDBN} will call this method when a @var{parameter}'s
5191 @code{show} API has been invoked (for example, @kbd{show foo}). The
5192 argument @code{svalue} receives the string representation of the
5193 current value. This method must return a string.
5196 When a new parameter is defined, its type must be specified. The
5197 available types are represented by constants defined in the @code{gdb}
5201 @findex PARAM_BOOLEAN
5202 @findex gdb.PARAM_BOOLEAN
5203 @item gdb.PARAM_BOOLEAN
5204 The value is a plain boolean. The Python boolean values, @code{True}
5205 and @code{False} are the only valid values.
5207 @findex PARAM_AUTO_BOOLEAN
5208 @findex gdb.PARAM_AUTO_BOOLEAN
5209 @item gdb.PARAM_AUTO_BOOLEAN
5210 The value has three possible states: true, false, and @samp{auto}. In
5211 Python, true and false are represented using boolean constants, and
5212 @samp{auto} is represented using @code{None}.
5214 @findex PARAM_UINTEGER
5215 @findex gdb.PARAM_UINTEGER
5216 @item gdb.PARAM_UINTEGER
5217 The value is an unsigned integer. The value of @code{None} should be
5218 interpreted to mean ``unlimited'' (literal @code{'unlimited'} can also
5219 be used to set that value), and the value of 0 is reserved and should
5222 @findex PARAM_INTEGER
5223 @findex gdb.PARAM_INTEGER
5224 @item gdb.PARAM_INTEGER
5225 The value is a signed integer. The value of @code{None} should be
5226 interpreted to mean ``unlimited'' (literal @code{'unlimited'} can also
5227 be used to set that value), and the value of 0 is reserved and should
5230 @findex PARAM_STRING
5231 @findex gdb.PARAM_STRING
5232 @item gdb.PARAM_STRING
5233 The value is a string. When the user modifies the string, any escape
5234 sequences, such as @samp{\t}, @samp{\f}, and octal escapes, are
5235 translated into corresponding characters and encoded into the current
5238 @findex PARAM_STRING_NOESCAPE
5239 @findex gdb.PARAM_STRING_NOESCAPE
5240 @item gdb.PARAM_STRING_NOESCAPE
5241 The value is a string. When the user modifies the string, escapes are
5242 passed through untranslated.
5244 @findex PARAM_OPTIONAL_FILENAME
5245 @findex gdb.PARAM_OPTIONAL_FILENAME
5246 @item gdb.PARAM_OPTIONAL_FILENAME
5247 The value is a either a filename (a string), or @code{None}.
5249 @findex PARAM_FILENAME
5250 @findex gdb.PARAM_FILENAME
5251 @item gdb.PARAM_FILENAME
5252 The value is a filename. This is just like
5253 @code{PARAM_STRING_NOESCAPE}, but uses file names for completion.
5255 @findex PARAM_ZINTEGER
5256 @findex gdb.PARAM_ZINTEGER
5257 @item gdb.PARAM_ZINTEGER
5258 The value is a signed integer. This is like @code{PARAM_INTEGER},
5259 except that 0 is allowed and the value of @code{None} is not supported.
5261 @findex PARAM_ZUINTEGER
5262 @findex gdb.PARAM_ZUINTEGER
5263 @item gdb.PARAM_ZUINTEGER
5264 The value is an unsigned integer. This is like @code{PARAM_UINTEGER},
5265 except that 0 is allowed and the value of @code{None} is not supported.
5267 @findex PARAM_ZUINTEGER_UNLIMITED
5268 @findex gdb.PARAM_ZUINTEGER_UNLIMITED
5269 @item gdb.PARAM_ZUINTEGER_UNLIMITED
5270 The value is a signed integer. This is like @code{PARAM_INTEGER}
5271 including that the value of @code{None} should be interpreted to mean
5272 ``unlimited'' (literal @code{'unlimited'} can also be used to set that
5273 value), except that 0 is allowed, and the value cannot be negative,
5274 except the special value -1 is returned for the setting of ``unlimited''.
5277 @findex gdb.PARAM_ENUM
5278 @item gdb.PARAM_ENUM
5279 The value is a string, which must be one of a collection string
5280 constants provided when the parameter is created.
5283 @findex gdb.PARAM_COLOR
5284 @item gdb.PARAM_COLOR
5285 The value is @code{gdb.Color} instance.
5288 When creating multiple new parameters using @code{gdb.Parameter}, it
5289 is often desirable to create a prefix command that can be used to
5290 group related parameters together, for example, if you wished to add
5291 the parameters @kbd{plugin-name feature-1} and @kbd{plugin-name
5292 feature-2}, then the @kbd{plugin-name} would need to be a prefix
5293 command (@pxref{CLI Commands In Python}).
5295 However, when creating parameters, you will almost always need to
5296 create two prefix commands, one as a @kbd{set} sub-command, and one as
5297 a @kbd{show} sub-command. @value{GDBN} provides the
5298 @code{gdb.ParameterPrefix} helper class to make creation of these two
5301 @defun ParameterPrefix.__init__ (name, command_class, doc = @code{None})
5302 The object initializer for @code{ParameterPrefix} registers two new
5303 @code{gdb.Command} prefixes, one as a @kbd{set} sub-command, and the
5304 other as a @kbd{show} sub-command.
5306 @var{name}, a string, is the name of the new prefix, without either
5307 @kbd{set} or @kbd{show}, similar to the @var{name} passed to
5308 @code{gdb.Parameter} (@pxref{Parameters In Python}). For example, to
5309 create the prefixes @kbd{set plugin-name} and @kbd{show plugin-name},
5310 you would pass the string @kbd{plugin-name}.
5312 @var{command_class} should be one of the @samp{COMMAND_} constants
5313 (@pxref{CLI Commands In Python}). This argument tells @value{GDBN} how to
5314 categorize the new parameter prefixes in the help system.
5316 There are a number of ways in which the help text for the two new
5317 prefix commands can be provided. If the @var{doc} parameter is not
5318 @code{None}, then this will be used as the documentation string for
5319 both prefix commands.
5321 If @var{doc} is @code{None}, but @code{gdb.ParameterPrefix} has been
5322 sub-classed, then the prefix command documentation will be taken from
5323 sub-classes documentation string (i.e., the @code{__doc__} attribute).
5325 If @var{doc} is @code{None}, and there is no @code{__doc__} string,
5326 then the default value @samp{This command is not documented.} is used.
5328 When writing the help text, keep in mind that the same text is used
5329 for both the @kbd{set} and @kbd{show} prefix commands.
5332 @defun ParameterPrefix.invoke_set (argument, from_tty)
5333 If a sub-class defines this method, then @value{GDBN} will call this
5334 when the prefix command is used with an unknown sub-command. The
5335 @var{argument} and @var{from_tty} parameters are the same as for
5336 @code{gdb.Command.invoke} (@pxref{Command.invoke}).
5338 If this method throws an exception, it is turned into a @value{GDBN}
5339 @code{error} call. Otherwise, the return value is ignored.
5341 It is not required that a @code{ParameterPrefix} sub-class override
5342 this method. Usually, a parameter prefix only exists as a means to
5343 group related parameters together. @value{GDBN} handles this use case
5344 automatically with no need to implement @code{invoke_set}.
5347 @defun ParameterPrefix.invoke_show (argument, from_tty)
5348 This is like the @code{invoke_set} method, but for the @kbd{show}
5349 prefix command. As with @code{invoke_set}, implementation of this
5350 method is optional, and usually not required.
5353 @cindex don't repeat Python command
5354 @defun ParameterPrefix.dont_repeat ()
5355 Like @code{Command.dont_repeat} (@pxref{Command.dont_repeat}), this
5356 can be called from @code{ParameterPrefix.invoke_set} or
5357 @code{ParameterPrefix.invoke_show} to prevent the prefix commands from
5361 Here is a small example that uses @code{gdb.ParameterPrefix} along
5362 with @code{gdb.Parameter} to create two new parameters
5363 @kbd{plugin-name feature-1} and @kbd{plugin-name feature-2}. As
5364 neither @code{invoke_set} or @code{invoke_show} is needed, this
5365 example does not sub-class @code{gdb.ParameterPrefix}:
5368 class ExampleParam(gdb.Parameter):
5369 def __init__ (self, name):
5370 super ().__init__ (name, gdb.COMMAND_DATA, gdb.PARAM_BOOLEAN)
5373 gdb.ParameterPrefix("plugin-name", gdb.COMMAND_NONE,
5374 """An example parameter prefix.
5376 This groups together some parameters.""")
5377 ExampleParam("plugin-name feature-1")
5378 ExampleParam("plugin-name feature-2")
5381 @node Functions In Python
5382 @subsubsection Writing new convenience functions
5384 @cindex writing convenience functions
5385 @cindex convenience functions in python
5386 @cindex python convenience functions
5387 @tindex gdb.Function
5389 You can implement new convenience functions (@pxref{Convenience Vars})
5390 in Python. A convenience function is an instance of a subclass of the
5391 class @code{gdb.Function}.
5393 @defun Function.__init__ (name)
5394 The initializer for @code{Function} registers the new function with
5395 @value{GDBN}. The argument @var{name} is the name of the function,
5396 a string. The function will be visible to the user as a convenience
5397 variable of type @code{internal function}, whose name is the same as
5398 the given @var{name}.
5400 The documentation for the new function is taken from the documentation
5401 string for the new class.
5404 @defun Function.invoke (*args)
5405 When a convenience function is evaluated, its arguments are converted
5406 to instances of @code{gdb.Value}, and then the function's
5407 @code{invoke} method is called. Note that @value{GDBN} does not
5408 predetermine the arity of convenience functions. Instead, all
5409 available arguments are passed to @code{invoke}, following the
5410 standard Python calling convention. In particular, a convenience
5411 function can have default values for parameters without ill effect.
5413 The return value of this method is used as its value in the enclosing
5414 expression. If an ordinary Python value is returned, it is converted
5415 to a @code{gdb.Value} following the usual rules.
5418 The following code snippet shows how a trivial convenience function can
5419 be implemented in Python:
5422 class Greet (gdb.Function):
5423 """Return string to greet someone.
5424 Takes a name as argument."""
5426 def __init__ (self):
5427 super (Greet, self).__init__ ("greet")
5429 def invoke (self, name):
5430 return "Hello, %s!" % name.string ()
5435 The last line instantiates the class, and is necessary to trigger the
5436 registration of the function with @value{GDBN}. Depending on how the
5437 Python code is read into @value{GDBN}, you may need to import the
5438 @code{gdb} module explicitly.
5440 Now you can use the function in an expression:
5443 (gdb) print $greet("Bob")
5447 @node Progspaces In Python
5448 @subsubsection Program Spaces In Python
5450 @cindex progspaces in python
5451 @tindex gdb.Progspace
5453 A program space, or @dfn{progspace}, represents a symbolic view
5454 of an address space.
5455 It consists of all of the objfiles of the program.
5456 @xref{Objfiles In Python}.
5457 @xref{Inferiors Connections and Programs, program spaces}, for more details
5458 about program spaces.
5460 The following progspace-related functions are available in the
5463 @defun gdb.current_progspace ()
5464 This function returns the program space of the currently selected inferior.
5465 @xref{Inferiors Connections and Programs}. This is identical to
5466 @code{gdb.selected_inferior().progspace} (@pxref{Inferiors In Python}) and is
5467 included for historical compatibility.
5470 @defun gdb.progspaces ()
5471 Return a sequence of all the progspaces currently known to @value{GDBN}.
5474 Each progspace is represented by an instance of the @code{gdb.Progspace}
5477 @defvar Progspace.filename
5478 The file name, as a string, of the main symbol file (from which debug
5479 symbols have been loaded) for the progspace, e.g.@: the argument to
5480 the @kbd{symbol-file} or @kbd{file} commands.
5482 If there is no main symbol table currently loaded, then this attribute
5483 will be @code{None}.
5486 @defvar Progspace.symbol_file
5487 The @code{gdb.Objfile} representing the main symbol file (from which
5488 debug symbols have been loaded) for the @code{gdb.Progspace}. This is
5489 the symbol file set by the @kbd{symbol-file} or @kbd{file} commands.
5491 This will be the @code{gdb.Objfile} representing
5492 @code{Progspace.filename} when @code{Progspace.filename} is not
5495 If there is no main symbol table currently loaded, then this attribute
5496 will be @code{None}.
5498 If the @code{Progspace} is invalid, i.e.@:, when
5499 @code{Progspace.is_valid()} returns @code{False}, then attempting to
5500 access this attribute will raise a @code{RuntimeError} exception.
5503 @defvar Progspace.executable_filename
5504 The file name, as a string, of the executable file in use by this
5505 program space. The executable file is the file that @value{GDBN} will
5506 invoke in order to start an inferior when using a native target. The
5507 file name within this attribute is updated by the @kbd{exec-file} and
5508 @kbd{file} commands.
5510 If no executable is currently set within this @code{Progspace} then
5511 this attribute contains @code{None}.
5513 If the @code{Progspace} is invalid, i.e.@:, when
5514 @code{Progspace.is_valid()} returns @code{False}, then attempting to
5515 access this attribute will raise a @code{RuntimeError} exception.
5518 @defvar Progspace.pretty_printers
5519 The @code{pretty_printers} attribute is a list of functions. It is
5520 used to look up pretty-printers. A @code{Value} is passed to each
5521 function in order; if the function returns @code{None}, then the
5522 search continues. Otherwise, the return value should be an object
5523 which is used to format the value. @xref{Pretty Printing API}, for more
5527 @defvar Progspace.type_printers
5528 The @code{type_printers} attribute is a list of type printer objects.
5529 @xref{Type Printing API}, for more information.
5532 @defvar Progspace.frame_filters
5533 The @code{frame_filters} attribute is a dictionary of frame filter
5534 objects. @xref{Frame Filter API}, for more information.
5537 @defvar Progspace.missing_file_handlers
5538 The @code{missing_file_handlers} attribute is a list of tuples. Each
5539 tuple holds a missing-file handler object for this program space. For
5540 more information, @pxref{Missing Debug Info In Python}, and
5541 @ref{Missing Objfiles In Python}.
5544 A program space has the following methods:
5546 @defun Progspace.block_for_pc (pc)
5547 Return the innermost @code{gdb.Block} containing the given @var{pc}
5548 value. If the block cannot be found for the @var{pc} value specified,
5549 the function will return @code{None}.
5552 @defun Progspace.find_pc_line (pc)
5553 Return the @code{gdb.Symtab_and_line} object corresponding to the
5554 @var{pc} value. @xref{Symbol Tables In Python}. If an invalid value
5555 of @var{pc} is passed as an argument, then the @code{symtab} and
5556 @code{line} attributes of the returned @code{gdb.Symtab_and_line}
5557 object will be @code{None} and 0 respectively.
5560 @defun Progspace.is_valid ()
5561 Returns @code{True} if the @code{gdb.Progspace} object is valid,
5562 @code{False} if not. A @code{gdb.Progspace} object can become invalid
5563 if the program space file it refers to is not referenced by any
5564 inferior. All other @code{gdb.Progspace} methods will throw an
5565 exception if it is invalid at the time the method is called.
5568 @defun Progspace.objfiles ()
5569 Return a sequence of all the objfiles referenced by this program
5570 space. @xref{Objfiles In Python}.
5573 @defun Progspace.solib_name (address)
5574 Return the name of the shared library holding the given @var{address}
5575 as a string, or @code{None}.
5578 @defun Progspace.objfile_for_address (address)
5579 Return the @code{gdb.Objfile} holding the given address, or
5580 @code{None} if no objfile covers it.
5583 One may add arbitrary attributes to @code{gdb.Progspace} objects
5584 in the usual Python way.
5585 This is useful if, for example, one needs to do some extra record keeping
5586 associated with the program space.
5588 @xref{choosing attribute names}, for guidance on selecting a suitable
5589 name for new attributes.
5591 In this contrived example, we want to perform some processing when
5592 an objfile with a certain symbol is loaded, but we only want to do
5593 this once because it is expensive. To achieve this we record the results
5594 with the program space because we can't predict when the desired objfile
5598 (@value{GDBP}) python
5600 def clear_objfiles_handler(event):
5601 event.progspace.expensive_computation = None
5602 def expensive(symbol):
5603 """A mock routine to perform an "expensive" computation on symbol."""
5604 print ("Computing the answer to the ultimate question ...")
5608 def new_objfile_handler(event):
5609 objfile = event.new_objfile
5610 progspace = objfile.progspace
5611 if not hasattr(progspace, 'expensive_computation') or \
5612 progspace.expensive_computation is None:
5613 # We use 'main' for the symbol to keep the example simple.
5614 # Note: There's no current way to constrain the lookup
5616 symbol = gdb.lookup_global_symbol('main')
5617 if symbol is not None:
5618 progspace.expensive_computation = expensive(symbol)
5619 gdb.events.clear_objfiles.connect(clear_objfiles_handler)
5620 gdb.events.new_objfile.connect(new_objfile_handler)
5624 (@value{GDBP}) file /tmp/hello
5625 Reading symbols from /tmp/hello...
5626 Computing the answer to the ultimate question ...
5627 (@value{GDBP}) python print(gdb.current_progspace().expensive_computation)
5630 Starting program: /tmp/hello
5632 [Inferior 1 (process 4242) exited normally]
5636 @node Objfiles In Python
5637 @subsubsection Objfiles In Python
5639 @cindex objfiles in python
5642 @value{GDBN} loads symbols for an inferior from various
5643 symbol-containing files (@pxref{Files}). These include the primary
5644 executable file, any shared libraries used by the inferior, and any
5645 separate debug info files (@pxref{Separate Debug Files}).
5646 @value{GDBN} calls these symbol-containing files @dfn{objfiles}.
5648 The following objfile-related functions are available in the
5651 @defun gdb.current_objfile ()
5652 When auto-loading a Python script (@pxref{Python Auto-loading}), @value{GDBN}
5653 sets the ``current objfile'' to the corresponding objfile. This
5654 function returns the current objfile. If there is no current objfile,
5655 this function returns @code{None}.
5658 @defun gdb.objfiles ()
5659 Return a sequence of objfiles referenced by the current program space.
5660 @xref{Objfiles In Python}, and @ref{Progspaces In Python}. This is identical
5661 to @code{gdb.selected_inferior().progspace.objfiles()} and is included for
5662 historical compatibility.
5665 @defun gdb.lookup_objfile (name @r{[}, by_build_id@r{]})
5666 Look up @var{name}, a file name or build ID, in the list of objfiles
5667 for the current program space (@pxref{Progspaces In Python}).
5668 If the objfile is not found throw the Python @code{ValueError} exception.
5670 If @var{name} is a relative file name, then it will match any
5671 source file name with the same trailing components. For example, if
5672 @var{name} is @samp{gcc/expr.c}, then it will match source file
5673 name of @file{/build/trunk/gcc/expr.c}, but not
5674 @file{/build/trunk/libcpp/expr.c} or @file{/build/trunk/gcc/x-expr.c}.
5676 If @var{by_build_id} is provided and is @code{True} then @var{name}
5677 is the build ID of the objfile. Otherwise, @var{name} is a file name.
5678 This is supported only on some operating systems, notably those which use
5679 the ELF format for binary files and the @sc{gnu} Binutils. For more details
5680 about this feature, see the description of the @option{--build-id}
5681 command-line option in @ref{Options, , Command Line Options, ld,
5685 Each objfile is represented by an instance of the @code{gdb.Objfile}
5688 @defvar Objfile.filename
5689 The file name of the objfile as a string, with symbolic links resolved.
5691 The value is @code{None} if the objfile is no longer valid.
5692 See the @code{gdb.Objfile.is_valid} method, described below.
5695 @defvar Objfile.username
5696 The file name of the objfile as specified by the user as a string.
5698 The value is @code{None} if the objfile is no longer valid.
5699 See the @code{gdb.Objfile.is_valid} method, described below.
5702 @defvar Objfile.is_file
5703 An objfile often comes from an ordinary file, but in some cases it may
5704 be constructed from the contents of memory. This attribute is
5705 @code{True} for file-backed objfiles, and @code{False} for other
5709 @defvar Objfile.owner
5710 For separate debug info objfiles this is the corresponding @code{gdb.Objfile}
5711 object that debug info is being provided for.
5712 Otherwise this is @code{None}.
5713 Separate debug info objfiles are added with the
5714 @code{gdb.Objfile.add_separate_debug_file} method, described below.
5717 @anchor{Objfile.build_id}
5718 @defvar Objfile.build_id
5719 The build ID of the objfile as a string.
5720 If the objfile does not have a build ID then the value is @code{None}.
5722 This is supported only on some operating systems, notably those which use
5723 the ELF format for binary files and the @sc{gnu} Binutils. For more details
5724 about this feature, see the description of the @option{--build-id}
5725 command-line option in @ref{Options, , Command Line Options, ld,
5729 @defvar Objfile.progspace
5730 The containing program space of the objfile as a @code{gdb.Progspace}
5731 object. @xref{Progspaces In Python}.
5734 @defvar Objfile.pretty_printers
5735 The @code{pretty_printers} attribute is a list of functions. It is
5736 used to look up pretty-printers. A @code{Value} is passed to each
5737 function in order; if the function returns @code{None}, then the
5738 search continues. Otherwise, the return value should be an object
5739 which is used to format the value. @xref{Pretty Printing API}, for more
5743 @defvar Objfile.type_printers
5744 The @code{type_printers} attribute is a list of type printer objects.
5745 @xref{Type Printing API}, for more information.
5748 @defvar Objfile.frame_filters
5749 The @code{frame_filters} attribute is a dictionary of frame filter
5750 objects. @xref{Frame Filter API}, for more information.
5753 One may add arbitrary attributes to @code{gdb.Objfile} objects
5754 in the usual Python way.
5755 This is useful if, for example, one needs to do some extra record keeping
5756 associated with the objfile.
5758 @xref{choosing attribute names}, for guidance on selecting a suitable
5759 name for new attributes.
5761 In this contrived example we record the time when @value{GDBN}
5766 (@value{GDBP}) python
5768 def new_objfile_handler(event):
5769 # Set the time_loaded attribute of the new objfile.
5770 event.new_objfile.time_loaded = datetime.datetime.today()
5771 gdb.events.new_objfile.connect(new_objfile_handler)
5775 (@value{GDBP}) file ./hello
5776 Reading symbols from ./hello...
5777 (@value{GDBP}) python print(gdb.objfiles()[0].time_loaded)
5778 2014-10-09 11:41:36.770345
5782 A @code{gdb.Objfile} object has the following methods:
5784 @defun Objfile.is_valid ()
5785 Returns @code{True} if the @code{gdb.Objfile} object is valid,
5786 @code{False} if not. A @code{gdb.Objfile} object can become invalid
5787 if the object file it refers to is not loaded in @value{GDBN} any
5788 longer. All other @code{gdb.Objfile} methods will throw an exception
5789 if it is invalid at the time the method is called.
5792 @defun Objfile.add_separate_debug_file (file)
5793 Add @var{file} to the list of files that @value{GDBN} will search for
5794 debug information for the objfile.
5795 This is useful when the debug info has been removed from the program
5796 and stored in a separate file. @value{GDBN} has built-in support for
5797 finding separate debug info files (@pxref{Separate Debug Files}), but if
5798 the file doesn't live in one of the standard places that @value{GDBN}
5799 searches then this function can be used to add a debug info file
5800 from a different place.
5803 @defun Objfile.lookup_global_symbol (name @r{[}, domain@r{]})
5804 Search for a global symbol named @var{name} in this objfile. Optionally, the
5805 search scope can be restricted with the @var{domain} argument.
5806 The @var{domain} argument must be a domain constant defined in the @code{gdb}
5807 module and described in @ref{Symbols In Python}. This function is similar to
5808 @code{gdb.lookup_global_symbol}, except that the search is limited to this
5811 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
5815 @defun Objfile.lookup_static_symbol (name @r{[}, domain@r{]})
5816 Like @code{Objfile.lookup_global_symbol}, but searches for a global
5817 symbol with static linkage named @var{name} in this objfile.
5820 @node Frames In Python
5821 @subsubsection Accessing inferior stack frames from Python
5823 @cindex frames in python
5824 When the debugged program stops, @value{GDBN} is able to analyze its call
5825 stack (@pxref{Frames,,Stack frames}). The @code{gdb.Frame} class
5826 represents a frame in the stack. A @code{gdb.Frame} object is only valid
5827 while its corresponding frame exists in the inferior's stack. If you try
5828 to use an invalid frame object, @value{GDBN} will throw a @code{gdb.error}
5829 exception (@pxref{Exception Handling}).
5831 Two @code{gdb.Frame} objects can be compared for equality with the @code{==}
5835 (@value{GDBP}) python print gdb.newest_frame() == gdb.selected_frame ()
5839 The following frame-related functions are available in the @code{gdb} module:
5841 @defun gdb.selected_frame ()
5842 Return the selected frame object. (@pxref{Selection,,Selecting a Frame}).
5845 @defun gdb.newest_frame ()
5846 Return the newest frame object for the selected thread.
5849 @defun gdb.frame_stop_reason_string (reason)
5850 Return a string explaining the reason why @value{GDBN} stopped unwinding
5851 frames, as expressed by the given @var{reason} code (an integer, see the
5852 @code{unwind_stop_reason} method further down in this section).
5855 @defun gdb.invalidate_cached_frames
5856 @value{GDBN} internally keeps a cache of the frames that have been
5857 unwound. This function invalidates this cache.
5859 This function should not generally be called by ordinary Python code.
5860 It is documented for the sake of completeness.
5863 A @code{gdb.Frame} object has the following methods:
5865 @defun Frame.is_valid ()
5866 Returns true if the @code{gdb.Frame} object is valid, false if not.
5867 A frame object can become invalid if the frame it refers to doesn't
5868 exist anymore in the inferior. All @code{gdb.Frame} methods will throw
5869 an exception if it is invalid at the time the method is called.
5872 @defun Frame.name ()
5873 Returns the function name of the frame, or @code{None} if it can't be
5877 @defun Frame.architecture ()
5878 Returns the @code{gdb.Architecture} object corresponding to the frame's
5879 architecture. @xref{Architectures In Python}.
5882 @defun Frame.type ()
5883 Returns the type of the frame. The value can be one of:
5885 @item gdb.NORMAL_FRAME
5886 An ordinary stack frame.
5888 @item gdb.DUMMY_FRAME
5889 A fake stack frame that was created by @value{GDBN} when performing an
5890 inferior function call.
5892 @item gdb.INLINE_FRAME
5893 A frame representing an inlined function. The function was inlined
5894 into a @code{gdb.NORMAL_FRAME} that is older than this one.
5896 @item gdb.TAILCALL_FRAME
5897 A frame representing a tail call. @xref{Tail Call Frames}.
5899 @item gdb.SIGTRAMP_FRAME
5900 A signal trampoline frame. This is the frame created by the OS when
5901 it calls into a signal handler.
5903 @item gdb.ARCH_FRAME
5904 A fake stack frame representing a cross-architecture call.
5906 @item gdb.SENTINEL_FRAME
5907 This is like @code{gdb.NORMAL_FRAME}, but it is only used for the
5912 @defun Frame.unwind_stop_reason ()
5913 Return an integer representing the reason why it's not possible to find
5914 more frames toward the outermost frame. Use
5915 @code{gdb.frame_stop_reason_string} to convert the value returned by this
5916 function to a string. The value can be one of:
5919 @item gdb.FRAME_UNWIND_NO_REASON
5920 No particular reason (older frames should be available).
5922 @item gdb.FRAME_UNWIND_NULL_ID
5923 The previous frame's analyzer returns an invalid result. This is no
5924 longer used by @value{GDBN}, and is kept only for backward
5927 @item gdb.FRAME_UNWIND_OUTERMOST
5928 This frame is the outermost.
5930 @item gdb.FRAME_UNWIND_UNAVAILABLE
5931 Cannot unwind further, because that would require knowing the
5932 values of registers or memory that have not been collected.
5934 @item gdb.FRAME_UNWIND_INNER_ID
5935 This frame ID looks like it ought to belong to a NEXT frame,
5936 but we got it for a PREV frame. Normally, this is a sign of
5937 unwinder failure. It could also indicate stack corruption.
5939 @item gdb.FRAME_UNWIND_SAME_ID
5940 This frame has the same ID as the previous one. That means
5941 that unwinding further would almost certainly give us another
5942 frame with exactly the same ID, so break the chain. Normally,
5943 this is a sign of unwinder failure. It could also indicate
5946 @item gdb.FRAME_UNWIND_NO_SAVED_PC
5947 The frame unwinder did not find any saved PC, but we needed
5948 one to unwind further.
5950 @item gdb.FRAME_UNWIND_MEMORY_ERROR
5951 The frame unwinder caused an error while trying to access memory.
5953 @item gdb.FRAME_UNWIND_FIRST_ERROR
5954 Any stop reason greater or equal to this value indicates some kind
5955 of error. This special value facilitates writing code that tests
5956 for errors in unwinding in a way that will work correctly even if
5957 the list of the other values is modified in future @value{GDBN}
5958 versions. Using it, you could write:
5960 reason = gdb.selected_frame().unwind_stop_reason ()
5961 reason_str = gdb.frame_stop_reason_string (reason)
5962 if reason >= gdb.FRAME_UNWIND_FIRST_ERROR:
5963 print ("An error occurred: %s" % reason_str)
5970 Returns the frame's resume address.
5973 @defun Frame.block ()
5974 Return the frame's code block. @xref{Blocks In Python}. If the frame
5975 does not have a block -- for example, if there is no debugging
5976 information for the code in question -- then this will throw an
5980 @defun Frame.function ()
5981 Return the symbol for the function corresponding to this frame.
5982 @xref{Symbols In Python}.
5985 @defun Frame.older ()
5986 Return the frame that called this frame. If this is the oldest frame,
5990 @defun Frame.newer ()
5991 Return the frame called by this frame. If this is the newest frame,
5995 @defun Frame.find_sal ()
5996 Return the frame's symtab and line object.
5997 @xref{Symbol Tables In Python}.
6000 @anchor{gdbpy_frame_read_register}
6001 @defun Frame.read_register (register)
6002 Return the value of @var{register} in this frame. Returns a
6003 @code{Gdb.Value} object. Throws an exception if @var{register} does
6004 not exist. The @var{register} argument must be one of the following:
6007 A string that is the name of a valid register (e.g., @code{'sp'} or
6010 A @code{gdb.RegisterDescriptor} object (@pxref{Registers In Python}).
6012 A @value{GDBN} internal, platform specific number. Using these
6013 numbers is supported for historic reasons, but is not recommended as
6014 future changes to @value{GDBN} could change the mapping between
6015 numbers and the registers they represent, breaking any Python code
6016 that uses the platform-specific numbers. The numbers are usually
6017 found in the corresponding @file{@var{platform}-tdep.h} file in the
6018 @value{GDBN} source tree.
6020 Using a string to access registers will be slightly slower than the
6021 other two methods as @value{GDBN} must look up the mapping between
6022 name and internal register number. If performance is critical
6023 consider looking up and caching a @code{gdb.RegisterDescriptor}
6027 @defun Frame.read_var (variable @r{[}, block@r{]})
6028 Return the value of @var{variable} in this frame. If the optional
6029 argument @var{block} is provided, search for the variable from that
6030 block; otherwise start at the frame's current block (which is
6031 determined by the frame's current program counter). The @var{variable}
6032 argument must be a string or a @code{gdb.Symbol} object; @var{block} must be a
6033 @code{gdb.Block} object.
6036 @defun Frame.select ()
6037 Set this frame to be the selected frame. @xref{Stack, ,Examining the
6041 @defun Frame.static_link ()
6042 In some languages (e.g., Ada, but also a GNU C extension), a nested
6043 function can access the variables in the outer scope. This is done
6044 via a ``static link'', which is a reference from the nested frame to
6045 the appropriate outer frame.
6047 This method returns this frame's static link frame, if one exists. If
6048 there is no static link, this method returns @code{None}.
6051 @defun Frame.level ()
6052 Return an integer, the stack frame level for this frame. @xref{Frames, ,Stack Frames}.
6055 @defun Frame.language ()
6056 Return a string, the source language for this frame.
6059 @node Blocks In Python
6060 @subsubsection Accessing blocks from Python
6062 @cindex blocks in python
6065 In @value{GDBN}, symbols are stored in blocks. A block corresponds
6066 roughly to a scope in the source code. Blocks are organized
6067 hierarchically, and are represented individually in Python as a
6068 @code{gdb.Block}. Blocks rely on debugging information being
6071 A frame has a block. Please see @ref{Frames In Python}, for a more
6072 in-depth discussion of frames.
6074 The outermost block is known as the @dfn{global block}. The global
6075 block typically holds public global variables and functions.
6077 The block nested just inside the global block is the @dfn{static
6078 block}. The static block typically holds file-scoped variables and
6081 @value{GDBN} provides a method to get a block's superblock, but there
6082 is currently no way to examine the sub-blocks of a block, or to
6083 iterate over all the blocks in a symbol table (@pxref{Symbol Tables In
6086 Here is a short example that should help explain blocks:
6089 /* This is in the global block. */
6092 /* This is in the static block. */
6093 static int file_scope;
6095 /* 'function' is in the global block, and 'argument' is
6096 in a block nested inside of 'function'. */
6097 int function (int argument)
6099 /* 'local' is in a block inside 'function'. It may or may
6100 not be in the same block as 'argument'. */
6104 /* 'inner' is in a block whose superblock is the one holding
6108 /* If this call is expanded by the compiler, you may see
6109 a nested block here whose function is 'inline_function'
6110 and whose superblock is the one holding 'inner'. */
6116 A @code{gdb.Block} is iterable. The iterator returns the symbols
6117 (@pxref{Symbols In Python}) local to the block. Python programs
6118 should not assume that a specific block object will always contain a
6119 given symbol, since changes in @value{GDBN} features and
6120 infrastructure may cause symbols move across blocks in a symbol
6121 table. You can also use Python's @dfn{dictionary syntax} to access
6122 variables in this block, e.g.:
6125 symbol = some_block['variable'] # symbol is of type gdb.Symbol
6128 The following block-related functions are available in the @code{gdb}
6131 @defun gdb.block_for_pc (pc)
6132 Return the innermost @code{gdb.Block} containing the given @var{pc}
6133 value. If the block cannot be found for the @var{pc} value specified,
6134 the function will return @code{None}. This is identical to
6135 @code{gdb.current_progspace().block_for_pc(pc)} and is included for
6136 historical compatibility.
6139 A @code{gdb.Block} object has the following methods:
6141 @defun Block.is_valid ()
6142 Returns @code{True} if the @code{gdb.Block} object is valid,
6143 @code{False} if not. A block object can become invalid if the block it
6144 refers to doesn't exist anymore in the inferior. All other
6145 @code{gdb.Block} methods will throw an exception if it is invalid at
6146 the time the method is called. The block's validity is also checked
6147 during iteration over symbols of the block.
6150 A @code{gdb.Block} object has the following attributes:
6153 The start address of the block. This attribute is not writable.
6157 One past the last address that appears in the block. This attribute
6161 @defvar Block.function
6162 The name of the block represented as a @code{gdb.Symbol}. If the
6163 block is not named, then this attribute holds @code{None}. This
6164 attribute is not writable.
6166 For ordinary function blocks, the superblock is the static block.
6167 However, you should note that it is possible for a function block to
6168 have a superblock that is not the static block -- for instance this
6169 happens for an inlined function.
6172 @defvar Block.superblock
6173 The block containing this block. If this parent block does not exist,
6174 this attribute holds @code{None}. This attribute is not writable.
6177 @defvar Block.subblocks
6178 A list of blocks nested in this block. If there are no blocks nested,
6179 this attribute holds an empty list. This attribute is not writable.
6182 @defvar Block.global_block
6183 The global block associated with this block. This attribute is not
6187 @defvar Block.static_block
6188 The static block associated with this block. This attribute is not
6192 @defvar Block.is_global
6193 @code{True} if the @code{gdb.Block} object is a global block,
6194 @code{False} if not. This attribute is not
6198 @defvar Block.is_static
6199 @code{True} if the @code{gdb.Block} object is a static block,
6200 @code{False} if not. This attribute is not writable.
6203 @node Symbols In Python
6204 @subsubsection Python representation of Symbols
6206 @cindex symbols in python
6209 @value{GDBN} represents every variable, function and type as an
6210 entry in a symbol table. @xref{Symbols, ,Examining the Symbol Table}.
6211 Similarly, Python represents these symbols in @value{GDBN} with the
6212 @code{gdb.Symbol} object.
6214 The following symbol-related functions are available in the @code{gdb}
6217 @defun gdb.lookup_symbol (name @r{[}, block @r{[}, domain@r{]]})
6218 This function searches for a symbol by name. The search scope can be
6219 restricted to the parameters defined in the optional domain and block
6222 @var{name} is the name of the symbol. It must be a string. The
6223 optional @var{block} argument restricts the search to symbols visible
6224 in that @var{block}. The @var{block} argument must be a
6225 @code{gdb.Block} object. If omitted, the block for the current frame
6226 is used. The optional @var{domain} argument restricts
6227 the search to the domain type. The @var{domain} argument must be a
6228 domain constant defined in the @code{gdb} module and described later
6231 The result is a tuple of two elements.
6232 The first element is a @code{gdb.Symbol} object or @code{None} if the symbol
6234 If the symbol is found, the second element is @code{True} if the symbol
6235 is a field of a method's object (e.g., @code{this} in C@t{++}),
6236 otherwise it is @code{False}.
6237 If the symbol is not found, the second element is @code{False}.
6240 @defun gdb.lookup_global_symbol (name @r{[}, domain@r{]})
6241 This function searches for a global symbol by name.
6242 The search scope can be restricted to by the domain argument.
6244 @var{name} is the name of the symbol. It must be a string.
6245 The optional @var{domain} argument restricts the search to the domain type.
6246 The @var{domain} argument must be a domain constant defined in the @code{gdb}
6247 module and described later in this chapter.
6249 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
6253 @defun gdb.lookup_static_symbol (name @r{[}, domain@r{]})
6254 This function searches for a global symbol with static linkage by name.
6255 The search scope can be restricted to by the domain argument.
6257 @var{name} is the name of the symbol. It must be a string.
6258 The optional @var{domain} argument restricts the search to the domain type.
6259 The @var{domain} argument must be a domain constant defined in the @code{gdb}
6260 module and described later in this chapter.
6262 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
6265 Note that this function will not find function-scoped static variables. To look
6266 up such variables, iterate over the variables of the function's
6267 @code{gdb.Block} and check that @code{block.addr_class} is
6268 @code{gdb.SYMBOL_LOC_STATIC}.
6270 There can be multiple global symbols with static linkage with the same
6271 name. This function will only return the first matching symbol that
6272 it finds. Which symbol is found depends on where @value{GDBN} is
6273 currently stopped, as @value{GDBN} will first search for matching
6274 symbols in the current object file, and then search all other object
6275 files. If the application is not yet running then @value{GDBN} will
6276 search all object files in the order they appear in the debug
6280 @defun gdb.lookup_static_symbols (name @r{[}, domain@r{]})
6281 Similar to @code{gdb.lookup_static_symbol}, this function searches for
6282 global symbols with static linkage by name, and optionally restricted
6283 by the domain argument. However, this function returns a list of all
6284 matching symbols found, not just the first one.
6286 @var{name} is the name of the symbol. It must be a string.
6287 The optional @var{domain} argument restricts the search to the domain type.
6288 The @var{domain} argument must be a domain constant defined in the @code{gdb}
6289 module and described later in this chapter.
6291 The result is a list of @code{gdb.Symbol} objects which could be empty
6292 if no matching symbols were found.
6294 Note that this function will not find function-scoped static variables. To look
6295 up such variables, iterate over the variables of the function's
6296 @code{gdb.Block} and check that @code{block.addr_class} is
6297 @code{gdb.SYMBOL_LOC_STATIC}.
6300 A @code{gdb.Symbol} object has the following attributes:
6303 The type of the symbol or @code{None} if no type is recorded.
6304 This attribute is represented as a @code{gdb.Type} object.
6305 @xref{Types In Python}. This attribute is not writable.
6308 @defvar Symbol.symtab
6309 The symbol table in which the symbol appears. This attribute is
6310 represented as a @code{gdb.Symtab} object. @xref{Symbol Tables In
6311 Python}. This attribute is not writable.
6315 The line number in the source code at which the symbol was defined.
6320 The name of the symbol as a string. This attribute is not writable.
6323 @defvar Symbol.linkage_name
6324 The name of the symbol, as used by the linker (i.e., may be mangled).
6325 This attribute is not writable.
6328 @defvar Symbol.print_name
6329 The name of the symbol in a form suitable for output. This is either
6330 @code{name} or @code{linkage_name}, depending on whether the user
6331 asked @value{GDBN} to display demangled or mangled names.
6334 @defvar Symbol.addr_class
6335 The address class of the symbol. This classifies how to find the value
6336 of a symbol. Each address class is a constant defined in the
6337 @code{gdb} module and described later in this chapter.
6340 @defvar Symbol.domain
6341 The domain of the symbol. Each domain is a constant defined in the
6342 @code{gdb} module and described later in this chapter.
6345 @defvar Symbol.needs_frame
6346 This is @code{True} if evaluating this symbol's value requires a frame
6347 (@pxref{Frames In Python}) and @code{False} otherwise. Typically,
6348 local variables will require a frame, but other symbols will not.
6351 @defvar Symbol.is_argument
6352 @code{True} if the symbol is an argument of a function.
6355 @defvar Symbol.is_artificial
6356 @code{True} if the symbol is artificial. An artificial symbol is one
6357 that is introduced by the compiler.
6360 @defvar Symbol.is_constant
6361 @code{True} if the symbol is a constant.
6364 @defvar Symbol.is_function
6365 @code{True} if the symbol is a function or a method.
6368 @defvar Symbol.is_variable
6369 @code{True} if the symbol is a variable, as opposed to something like
6370 a function or type. Note that this also returns @code{False} for
6374 A @code{gdb.Symbol} object has the following methods:
6376 @defun Symbol.is_valid ()
6377 Returns @code{True} if the @code{gdb.Symbol} object is valid,
6378 @code{False} if not. A @code{gdb.Symbol} object can become invalid if
6379 the symbol it refers to does not exist in @value{GDBN} any longer.
6380 All other @code{gdb.Symbol} methods will throw an exception if it is
6381 invalid at the time the method is called.
6384 @defun Symbol.value (@r{[}frame@r{]})
6385 Compute the value of the symbol, as a @code{gdb.Value}. For
6386 functions, this computes the address of the function, cast to the
6387 appropriate type. If the symbol requires a frame in order to compute
6388 its value, then @var{frame} must be given. If @var{frame} is not
6389 given, or if @var{frame} is invalid, then this method will throw an
6393 The available domain categories in @code{gdb.Symbol} are represented
6394 as constants in the @code{gdb} module:
6397 @vindex SYMBOL_UNDEF_DOMAIN
6398 @item gdb.SYMBOL_UNDEF_DOMAIN
6399 This is used when a domain has not been discovered or none of the
6400 following domains apply. This usually indicates an error either
6401 in the symbol information or in @value{GDBN}'s handling of symbols.
6403 @vindex SYMBOL_VAR_DOMAIN
6404 @item gdb.SYMBOL_VAR_DOMAIN
6405 This domain contains variables.
6407 @vindex SYMBOL_FUNCTION_DOMAIN
6408 @item gdb.SYMBOL_FUNCTION_DOMAIN
6409 This domain contains functions.
6411 @vindex SYMBOL_TYPE_DOMAIN
6412 @item gdb.SYMBOL_TYPE_DOMAIN
6413 This domain contains types. In a C-like language, types using a tag
6414 (the name appearing after a @code{struct}, @code{union}, or
6415 @code{enum} keyword) will not appear here; in other languages, all
6416 types are in this domain.
6418 @vindex SYMBOL_STRUCT_DOMAIN
6419 @item gdb.SYMBOL_STRUCT_DOMAIN
6420 This domain holds struct, union and enum tag names. This domain is
6421 only used for C-like languages. For example, in this code:
6423 struct type_one @{ int x; @};
6424 typedef struct type_one type_two;
6426 Here @code{type_one} will be in @code{SYMBOL_STRUCT_DOMAIN}, but
6427 @code{type_two} will be in @code{SYMBOL_TYPE_DOMAIN}.
6429 @vindex SYMBOL_LABEL_DOMAIN
6430 @item gdb.SYMBOL_LABEL_DOMAIN
6431 This domain contains names of labels (for gotos).
6433 @vindex SYMBOL_MODULE_DOMAIN
6434 @item gdb.SYMBOL_MODULE_DOMAIN
6435 This domain contains names of Fortran module types.
6437 @vindex SYMBOL_COMMON_BLOCK_DOMAIN
6438 @item gdb.SYMBOL_COMMON_BLOCK_DOMAIN
6439 This domain contains names of Fortran common blocks.
6442 When searching for a symbol, the desired domain constant can be passed
6443 verbatim to the lookup function. For example:
6445 symbol = gdb.lookup_symbol ("name", domain=gdb.SYMBOL_VAR_DOMAIN)
6448 For more complex searches, there is a corresponding set of constants,
6449 each named after one of the preceding constants, but with the
6450 @samp{SEARCH} prefix replacing the @samp{SYMBOL} prefix; for example,
6451 @code{SEARCH_LABEL_DOMAIN}. These may be or'd together to form a
6452 search constant, e.g.:
6454 symbol = gdb.lookup_symbol ("name",
6455 domain=gdb.SEARCH_VAR_DOMAIN | gdb.SEARCH_TYPE_DOMAIN)
6458 The available address class categories in @code{gdb.Symbol} are represented
6459 as constants in the @code{gdb} module:
6462 @vindex SYMBOL_LOC_UNDEF
6463 @item gdb.SYMBOL_LOC_UNDEF
6464 If this is returned by address class, it indicates an error either in
6465 the symbol information or in @value{GDBN}'s handling of symbols.
6467 @vindex SYMBOL_LOC_CONST
6468 @item gdb.SYMBOL_LOC_CONST
6469 Value is constant int.
6471 @vindex SYMBOL_LOC_STATIC
6472 @item gdb.SYMBOL_LOC_STATIC
6473 Value is at a fixed address.
6475 @vindex SYMBOL_LOC_REGISTER
6476 @item gdb.SYMBOL_LOC_REGISTER
6477 Value is in a register.
6479 @vindex SYMBOL_LOC_ARG
6480 @item gdb.SYMBOL_LOC_ARG
6481 Value is an argument. This value is at the offset stored within the
6482 symbol inside the frame's argument list.
6484 @vindex SYMBOL_LOC_REF_ARG
6485 @item gdb.SYMBOL_LOC_REF_ARG
6486 Value address is stored in the frame's argument list. Just like
6487 @code{LOC_ARG} except that the value's address is stored at the
6488 offset, not the value itself.
6490 @vindex SYMBOL_LOC_REGPARM_ADDR
6491 @item gdb.SYMBOL_LOC_REGPARM_ADDR
6492 Value is a specified register. Just like @code{LOC_REGISTER} except
6493 the register holds the address of the argument instead of the argument
6496 @vindex SYMBOL_LOC_LOCAL
6497 @item gdb.SYMBOL_LOC_LOCAL
6498 Value is a local variable.
6500 @vindex SYMBOL_LOC_TYPEDEF
6501 @item gdb.SYMBOL_LOC_TYPEDEF
6502 Value not used. Symbols in the domain @code{SYMBOL_STRUCT_DOMAIN} all
6505 @vindex SYMBOL_LOC_LABEL
6506 @item gdb.SYMBOL_LOC_LABEL
6509 @vindex SYMBOL_LOC_BLOCK
6510 @item gdb.SYMBOL_LOC_BLOCK
6513 @vindex SYMBOL_LOC_CONST_BYTES
6514 @item gdb.SYMBOL_LOC_CONST_BYTES
6515 Value is a byte-sequence.
6517 @vindex SYMBOL_LOC_UNRESOLVED
6518 @item gdb.SYMBOL_LOC_UNRESOLVED
6519 Value is at a fixed address, but the address of the variable has to be
6520 determined from the minimal symbol table whenever the variable is
6523 @vindex SYMBOL_LOC_OPTIMIZED_OUT
6524 @item gdb.SYMBOL_LOC_OPTIMIZED_OUT
6525 The value does not actually exist in the program.
6527 @vindex SYMBOL_LOC_COMPUTED
6528 @item gdb.SYMBOL_LOC_COMPUTED
6529 The value's address is a computed location.
6531 @vindex SYMBOL_LOC_COMMON_BLOCK
6532 @item gdb.SYMBOL_LOC_COMMON_BLOCK
6533 The value's address is a symbol. This is only used for Fortran common
6537 @node Symbol Tables In Python
6538 @subsubsection Symbol table representation in Python
6540 @cindex symbol tables in python
6542 @tindex gdb.Symtab_and_line
6544 Access to symbol table data maintained by @value{GDBN} on the inferior
6545 is exposed to Python via two objects: @code{gdb.Symtab_and_line} and
6546 @code{gdb.Symtab}. Symbol table and line data for a frame is returned
6547 from the @code{find_sal} method in @code{gdb.Frame} object.
6548 @xref{Frames In Python}.
6550 For more information on @value{GDBN}'s symbol table management, see
6551 @ref{Symbols, ,Examining the Symbol Table}, for more information.
6553 A @code{gdb.Symtab_and_line} object has the following attributes:
6555 @defvar Symtab_and_line.symtab
6556 The symbol table object (@code{gdb.Symtab}) for this frame.
6557 This attribute is not writable.
6560 @defvar Symtab_and_line.pc
6561 Indicates the start of the address range occupied by code for the
6562 current source line. This attribute is not writable.
6565 @defvar Symtab_and_line.last
6566 Indicates the end of the address range occupied by code for the current
6567 source line. This attribute is not writable.
6570 @defvar Symtab_and_line.line
6571 Indicates the current line number for this object. This
6572 attribute is not writable.
6575 A @code{gdb.Symtab_and_line} object has the following methods:
6577 @defun Symtab_and_line.is_valid ()
6578 Returns @code{True} if the @code{gdb.Symtab_and_line} object is valid,
6579 @code{False} if not. A @code{gdb.Symtab_and_line} object can become
6580 invalid if the Symbol table and line object it refers to does not
6581 exist in @value{GDBN} any longer. All other
6582 @code{gdb.Symtab_and_line} methods will throw an exception if it is
6583 invalid at the time the method is called.
6586 A @code{gdb.Symtab} object has the following attributes:
6588 @defvar Symtab.filename
6589 The symbol table's source filename. This attribute is not writable.
6592 @defvar Symtab.objfile
6593 The symbol table's backing object file. @xref{Objfiles In Python}.
6594 This attribute is not writable.
6597 @defvar Symtab.producer
6598 The name and possibly version number of the program that
6599 compiled the code in the symbol table.
6600 The contents of this string is up to the compiler.
6601 If no producer information is available then @code{None} is returned.
6602 This attribute is not writable.
6605 A @code{gdb.Symtab} object has the following methods:
6607 @defun Symtab.is_valid ()
6608 Returns @code{True} if the @code{gdb.Symtab} object is valid,
6609 @code{False} if not. A @code{gdb.Symtab} object can become invalid if
6610 the symbol table it refers to does not exist in @value{GDBN} any
6611 longer. All other @code{gdb.Symtab} methods will throw an exception
6612 if it is invalid at the time the method is called.
6615 @defun Symtab.fullname ()
6616 Return the symbol table's source absolute file name.
6619 @defun Symtab.global_block ()
6620 Return the global block of the underlying symbol table.
6621 @xref{Blocks In Python}.
6624 @defun Symtab.static_block ()
6625 Return the static block of the underlying symbol table.
6626 @xref{Blocks In Python}.
6629 @defun Symtab.linetable ()
6630 Return the line table associated with the symbol table.
6631 @xref{Line Tables In Python}.
6634 @node Line Tables In Python
6635 @subsubsection Manipulating line tables using Python
6637 @cindex line tables in python
6638 @tindex gdb.LineTable
6640 Python code can request and inspect line table information from a
6641 symbol table that is loaded in @value{GDBN}. A line table is a
6642 mapping of source lines to their executable locations in memory. To
6643 acquire the line table information for a particular symbol table, use
6644 the @code{linetable} function (@pxref{Symbol Tables In Python}).
6646 A @code{gdb.LineTable} is iterable. The iterator returns
6647 @code{LineTableEntry} objects that correspond to the source line and
6648 address for each line table entry. @code{LineTableEntry} objects have
6649 the following attributes:
6651 @defvar LineTableEntry.line
6652 The source line number for this line table entry. This number
6653 corresponds to the actual line of source. This attribute is not
6657 @defvar LineTableEntry.pc
6658 The address that is associated with the line table entry where the
6659 executable code for that source line resides in memory. This
6660 attribute is not writable.
6663 As there can be multiple addresses for a single source line, you may
6664 receive multiple @code{LineTableEntry} objects with matching
6665 @code{line} attributes, but with different @code{pc} attributes. The
6666 iterator is sorted in ascending @code{pc} order. Here is a small
6667 example illustrating iterating over a line table.
6670 symtab = gdb.selected_frame().find_sal().symtab
6671 linetable = symtab.linetable()
6672 for line in linetable:
6673 print ("Line: "+str(line.line)+" Address: "+hex(line.pc))
6676 This will have the following output:
6679 Line: 33 Address: 0x4005c8L
6680 Line: 37 Address: 0x4005caL
6681 Line: 39 Address: 0x4005d2L
6682 Line: 40 Address: 0x4005f8L
6683 Line: 42 Address: 0x4005ffL
6684 Line: 44 Address: 0x400608L
6685 Line: 42 Address: 0x40060cL
6686 Line: 45 Address: 0x400615L
6689 In addition to being able to iterate over a @code{LineTable}, it also
6690 has the following direct access methods:
6692 @defun LineTable.line (line)
6693 Return a Python @code{Tuple} of @code{LineTableEntry} objects for any
6694 entries in the line table for the given @var{line}, which specifies
6695 the source code line. If there are no entries for that source code
6696 @var{line}, the Python @code{None} is returned.
6699 @defun LineTable.has_line (line)
6700 Return a Python @code{Boolean} indicating whether there is an entry in
6701 the line table for this source line. Return @code{True} if an entry
6702 is found, or @code{False} if not.
6705 @defun LineTable.source_lines ()
6706 Return a Python @code{List} of the source line numbers in the symbol
6707 table. Only lines with executable code locations are returned. The
6708 contents of the @code{List} will just be the source line entries
6709 represented as Python @code{Long} values.
6712 @node Breakpoints In Python
6713 @subsubsection Manipulating breakpoints using Python
6715 @cindex breakpoints in python
6716 @tindex gdb.Breakpoint
6718 Python code can manipulate breakpoints via the @code{gdb.Breakpoint}
6721 A breakpoint can be created using one of the two forms of the
6722 @code{gdb.Breakpoint} constructor. The first one accepts a string
6723 like one would pass to the @code{break}
6724 (@pxref{Set Breaks,,Setting Breakpoints}) and @code{watch}
6725 (@pxref{Set Watchpoints, , Setting Watchpoints}) commands, and can be used to
6726 create both breakpoints and watchpoints. The second accepts separate Python
6727 arguments similar to @ref{Explicit Locations}, and can only be used to create
6730 @defun Breakpoint.__init__ (spec @r{[}, type @r{][}, wp_class @r{][}, internal @r{][}, temporary @r{][}, qualified @r{]})
6731 Create a new breakpoint according to @var{spec}, which is a string naming the
6732 location of a breakpoint, or an expression that defines a watchpoint. The
6733 string should describe a location in a format recognized by the @code{break}
6734 command (@pxref{Set Breaks,,Setting Breakpoints}) or, in the case of a
6735 watchpoint, by the @code{watch} command
6736 (@pxref{Set Watchpoints, , Setting Watchpoints}).
6738 The optional @var{type} argument specifies the type of the breakpoint to create,
6741 The optional @var{wp_class} argument defines the class of watchpoint to create,
6742 if @var{type} is @code{gdb.BP_WATCHPOINT}. If @var{wp_class} is omitted, it
6743 defaults to @code{gdb.WP_WRITE}.
6745 The optional @var{internal} argument allows the breakpoint to become invisible
6746 to the user. The breakpoint will neither be reported when created, nor will it
6747 be listed in the output from @code{info breakpoints} (but will be listed with
6748 the @code{maint info breakpoints} command).
6750 The optional @var{temporary} argument makes the breakpoint a temporary
6751 breakpoint. Temporary breakpoints are deleted after they have been hit. Any
6752 further access to the Python breakpoint after it has been hit will result in a
6753 runtime error (as that breakpoint has now been automatically deleted).
6755 The optional @var{qualified} argument is a boolean that allows interpreting
6756 the function passed in @code{spec} as a fully-qualified name. It is equivalent
6757 to @code{break}'s @code{-qualified} flag (@pxref{Linespec Locations} and
6758 @ref{Explicit Locations}).
6762 @defun Breakpoint.__init__ (@r{[} source @r{][}, function @r{][}, label @r{][}, line @r{]}, @r{][} internal @r{][}, temporary @r{][}, qualified @r{]})
6763 This second form of creating a new breakpoint specifies the explicit
6764 location (@pxref{Explicit Locations}) using keywords. The new breakpoint will
6765 be created in the specified source file @var{source}, at the specified
6766 @var{function}, @var{label} and @var{line}.
6768 @var{internal}, @var{temporary} and @var{qualified} have the same usage as
6769 explained previously.
6772 The available types are represented by constants defined in the @code{gdb}
6776 @vindex BP_BREAKPOINT
6777 @item gdb.BP_BREAKPOINT
6778 Normal code breakpoint.
6780 @vindex BP_HARDWARE_BREAKPOINT
6781 @item gdb.BP_HARDWARE_BREAKPOINT
6782 Hardware assisted code breakpoint.
6784 @vindex BP_WATCHPOINT
6785 @item gdb.BP_WATCHPOINT
6786 Watchpoint breakpoint.
6788 @vindex BP_HARDWARE_WATCHPOINT
6789 @item gdb.BP_HARDWARE_WATCHPOINT
6790 Hardware assisted watchpoint.
6792 @vindex BP_READ_WATCHPOINT
6793 @item gdb.BP_READ_WATCHPOINT
6794 Hardware assisted read watchpoint.
6796 @vindex BP_ACCESS_WATCHPOINT
6797 @item gdb.BP_ACCESS_WATCHPOINT
6798 Hardware assisted access watchpoint.
6800 @vindex BP_CATCHPOINT
6801 @item gdb.BP_CATCHPOINT
6802 Catchpoint. Currently, this type can't be used when creating
6803 @code{gdb.Breakpoint} objects, but will be present in
6804 @code{gdb.Breakpoint} objects reported from
6805 @code{gdb.BreakpointEvent}s (@pxref{Events In Python}).
6808 The available watchpoint types are represented by constants defined in the
6814 Read only watchpoint.
6818 Write only watchpoint.
6822 Read/Write watchpoint.
6825 @defun Breakpoint.stop (self)
6826 The @code{gdb.Breakpoint} class can be sub-classed and, in
6827 particular, you may choose to implement the @code{stop} method.
6828 If this method is defined in a sub-class of @code{gdb.Breakpoint},
6829 it will be called when the inferior reaches any location of a
6830 breakpoint which instantiates that sub-class. If the method returns
6831 @code{True}, the inferior will be stopped at the location of the
6832 breakpoint, otherwise the inferior will continue.
6834 If there are multiple breakpoints at the same location with a
6835 @code{stop} method, each one will be called regardless of the
6836 return status of the previous. This ensures that all @code{stop}
6837 methods have a chance to execute at that location. In this scenario
6838 if one of the methods returns @code{True} but the others return
6839 @code{False}, the inferior will still be stopped.
6841 You should not alter the execution state of the inferior (i.e.@:, step,
6842 next, etc.), alter the current frame context (i.e.@:, change the current
6843 active frame), or alter, add or delete any breakpoint. As a general
6844 rule, you should not alter any data within @value{GDBN} or the inferior
6847 Example @code{stop} implementation:
6850 class MyBreakpoint (gdb.Breakpoint):
6852 inf_val = gdb.parse_and_eval("foo")
6859 @defun Breakpoint.is_valid ()
6860 Return @code{True} if this @code{Breakpoint} object is valid,
6861 @code{False} otherwise. A @code{Breakpoint} object can become invalid
6862 if the user deletes the breakpoint. In this case, the object still
6863 exists, but the underlying breakpoint does not. In the cases of
6864 watchpoint scope, the watchpoint remains valid even if execution of the
6865 inferior leaves the scope of that watchpoint.
6868 @defun Breakpoint.delete ()
6869 Permanently deletes the @value{GDBN} breakpoint. This also
6870 invalidates the Python @code{Breakpoint} object. Any further access
6871 to this object's attributes or methods will raise an error.
6874 @defvar Breakpoint.enabled
6875 This attribute is @code{True} if the breakpoint is enabled, and
6876 @code{False} otherwise. This attribute is writable. You can use it to enable
6877 or disable the breakpoint.
6880 @defvar Breakpoint.silent
6881 This attribute is @code{True} if the breakpoint is silent, and
6882 @code{False} otherwise. This attribute is writable.
6884 Note that a breakpoint can also be silent if it has commands and the
6885 first command is @code{silent}. This is not reported by the
6886 @code{silent} attribute.
6889 @defvar Breakpoint.pending
6890 This attribute is @code{True} if the breakpoint is pending, and
6891 @code{False} otherwise. @xref{Set Breaks}. This attribute is
6895 @anchor{python_breakpoint_thread}
6896 @defvar Breakpoint.thread
6897 If the breakpoint is thread-specific (@pxref{Thread-Specific
6898 Breakpoints}), this attribute holds the thread's global id. If the
6899 breakpoint is not thread-specific, this attribute is @code{None}.
6900 This attribute is writable.
6902 Only one of @code{Breakpoint.thread} or @code{Breakpoint.inferior} can
6903 be set to a valid id at any time, that is, a breakpoint can be thread
6904 specific, or inferior specific, but not both.
6907 @anchor{python_breakpoint_inferior}
6908 @defvar Breakpoint.inferior
6909 If the breakpoint is inferior-specific (@pxref{Inferior-Specific
6910 Breakpoints}), this attribute holds the inferior's id. If the
6911 breakpoint is not inferior-specific, this attribute is @code{None}.
6913 This attribute can be written for breakpoints of type
6914 @code{gdb.BP_BREAKPOINT} and @code{gdb.BP_HARDWARE_BREAKPOINT}.
6917 @defvar Breakpoint.task
6918 If the breakpoint is Ada task-specific, this attribute holds the Ada task
6919 id. If the breakpoint is not task-specific (or the underlying
6920 language is not Ada), this attribute is @code{None}. This attribute
6924 @defvar Breakpoint.ignore_count
6925 This attribute holds the ignore count for the breakpoint, an integer.
6926 This attribute is writable.
6929 @defvar Breakpoint.number
6930 This attribute holds the breakpoint's number --- the identifier used by
6931 the user to manipulate the breakpoint. This attribute is not writable.
6934 @defvar Breakpoint.type
6935 This attribute holds the breakpoint's type --- the identifier used to
6936 determine the actual breakpoint type or use-case. This attribute is not
6940 @defvar Breakpoint.visible
6941 This attribute tells whether the breakpoint is visible to the user
6942 when set, or when the @samp{info breakpoints} command is run. This
6943 attribute is not writable.
6946 @defvar Breakpoint.temporary
6947 This attribute indicates whether the breakpoint was created as a
6948 temporary breakpoint. Temporary breakpoints are automatically deleted
6949 after that breakpoint has been hit. Access to this attribute, and all
6950 other attributes and functions other than the @code{is_valid}
6951 function, will result in an error after the breakpoint has been hit
6952 (as it has been automatically deleted). This attribute is not
6956 @defvar Breakpoint.hit_count
6957 This attribute holds the hit count for the breakpoint, an integer.
6958 This attribute is writable, but currently it can only be set to zero.
6961 @defvar Breakpoint.location
6962 This attribute holds the location of the breakpoint, as specified by
6963 the user. It is a string. If the breakpoint does not have a location
6964 (that is, it is a watchpoint) the attribute's value is @code{None}. This
6965 attribute is not writable.
6968 @defvar Breakpoint.locations
6969 Get the most current list of breakpoint locations that are inserted for this
6970 breakpoint, with elements of type @code{gdb.BreakpointLocation}
6971 (described below). This functionality matches that of the
6972 @code{info breakpoint} command (@pxref{Set Breaks}), in that it only retrieves
6973 the most current list of locations, thus the list itself when returned is
6974 not updated behind the scenes. This attribute is not writable.
6977 @defvar Breakpoint.expression
6978 This attribute holds a breakpoint expression, as specified by
6979 the user. It is a string. If the breakpoint does not have an
6980 expression (the breakpoint is not a watchpoint) the attribute's value
6981 is @code{None}. This attribute is not writable.
6984 @defvar Breakpoint.condition
6985 This attribute holds the condition of the breakpoint, as specified by
6986 the user. It is a string. If there is no condition, this attribute's
6987 value is @code{None}. This attribute is writable.
6990 @defvar Breakpoint.commands
6991 This attribute holds the commands attached to the breakpoint. If
6992 there are commands, this attribute's value is a string holding all the
6993 commands, separated by newlines. If there are no commands, this
6994 attribute is @code{None}. This attribute is writable.
6997 @subheading Breakpoint Locations
6999 A breakpoint location is one of the actual places where a breakpoint has been
7000 set, represented in the Python API by the @code{gdb.BreakpointLocation}
7001 type. This type is never instantiated by the user directly, but is retrieved
7002 from @code{Breakpoint.locations} which returns a list of breakpoint
7003 locations where it is currently set. Breakpoint locations can become
7004 invalid if new symbol files are loaded or dynamically loaded libraries are
7005 closed. Accessing the attributes of an invalidated breakpoint location will
7006 throw a @code{RuntimeError} exception. Access the @code{Breakpoint.locations}
7007 attribute again to retrieve the new and valid breakpoints location list.
7009 @defvar BreakpointLocation.source
7010 This attribute returns the source file path and line number where this location
7011 was set. The type of the attribute is a tuple of @var{string} and
7012 @var{long}. If the breakpoint location doesn't have a source location,
7013 it returns None, which is the case for watchpoints and catchpoints.
7014 This will throw a @code{RuntimeError} exception if the location
7015 has been invalidated. This attribute is not writable.
7018 @defvar BreakpointLocation.address
7019 This attribute returns the address where this location was set.
7020 This attribute is of type long. This will throw a @code{RuntimeError}
7021 exception if the location has been invalidated. This attribute is
7025 @defvar BreakpointLocation.enabled
7026 This attribute holds the value for whether or not this location is enabled.
7027 This attribute is writable (boolean). This will throw a @code{RuntimeError}
7028 exception if the location has been invalidated.
7031 @defvar BreakpointLocation.owner
7032 This attribute holds a reference to the @code{gdb.Breakpoint} owner object,
7033 from which this @code{gdb.BreakpointLocation} was retrieved from.
7034 This will throw a @code{RuntimeError} exception if the location has been
7035 invalidated. This attribute is not writable.
7038 @defvar BreakpointLocation.function
7039 This attribute gets the name of the function where this location was set.
7040 If no function could be found this attribute returns @code{None}.
7041 This will throw a @code{RuntimeError} exception if the location has
7042 been invalidated. This attribute is not writable.
7045 @defvar BreakpointLocation.fullname
7046 This attribute gets the full name of where this location was set. If no
7047 full name could be found, this attribute returns @code{None}.
7048 This will throw a @code{RuntimeError} exception if the location has
7049 been invalidated. This attribute is not writable.
7052 @defvar BreakpointLocation.thread_groups
7053 This attribute gets the thread groups it was set in. It returns a @code{List}
7054 of the thread group ID's. This will throw a @code{RuntimeError}
7055 exception if the location has been invalidated. This attribute
7059 @node Finish Breakpoints in Python
7060 @subsubsection Finish Breakpoints
7062 @cindex python finish breakpoints
7063 @tindex gdb.FinishBreakpoint
7065 A finish breakpoint is a temporary breakpoint set at the return address of
7066 a frame, based on the @code{finish} command. @code{gdb.FinishBreakpoint}
7067 extends @code{gdb.Breakpoint}. The underlying breakpoint will be disabled
7068 and deleted when the execution will run out of the breakpoint scope (i.e.@:
7069 @code{Breakpoint.stop} or @code{FinishBreakpoint.out_of_scope} triggered).
7070 Finish breakpoints are thread specific and must be create with the right
7073 @defun FinishBreakpoint.__init__ (@r{[}frame@r{]} @r{[}, internal@r{]})
7074 Create a finish breakpoint at the return address of the @code{gdb.Frame}
7075 object @var{frame}. If @var{frame} is not provided, this defaults to the
7076 newest frame. The optional @var{internal} argument allows the breakpoint to
7077 become invisible to the user. @xref{Breakpoints In Python}, for further
7078 details about this argument.
7081 @defun FinishBreakpoint.out_of_scope (self)
7082 In some circumstances (e.g.@: @code{longjmp}, C@t{++} exceptions, @value{GDBN}
7083 @code{return} command, @dots{}), a function may not properly terminate, and
7084 thus never hit the finish breakpoint. When @value{GDBN} notices such a
7085 situation, the @code{out_of_scope} callback will be triggered.
7087 You may want to sub-class @code{gdb.FinishBreakpoint} and override this
7091 class MyFinishBreakpoint (gdb.FinishBreakpoint)
7093 print ("normal finish")
7096 def out_of_scope ():
7097 print ("abnormal finish")
7101 @defvar FinishBreakpoint.return_value
7102 When @value{GDBN} is stopped at a finish breakpoint and the frame
7103 used to build the @code{gdb.FinishBreakpoint} object had debug symbols, this
7104 attribute will contain a @code{gdb.Value} object corresponding to the return
7105 value of the function. The value will be @code{None} if the function return
7106 type is @code{void} or if the return value was not computable. This attribute
7110 @node Lazy Strings In Python
7111 @subsubsection Python representation of lazy strings
7113 @cindex lazy strings in python
7114 @tindex gdb.LazyString
7116 A @dfn{lazy string} is a string whose contents is not retrieved or
7117 encoded until it is needed.
7119 A @code{gdb.LazyString} is represented in @value{GDBN} as an
7120 @code{address} that points to a region of memory, an @code{encoding}
7121 that will be used to encode that region of memory, and a @code{length}
7122 to delimit the region of memory that represents the string. The
7123 difference between a @code{gdb.LazyString} and a string wrapped within
7124 a @code{gdb.Value} is that a @code{gdb.LazyString} will only be
7125 retrieved and encoded during printing, while a @code{gdb.Value}
7126 wrapping a string is immediately retrieved and encoded on creation.
7128 A @code{gdb.LazyString} can be created using the
7129 @code{gdb.Value.lazy_string} method (@pxref{Values From Inferior}).
7131 A @code{gdb.LazyString} object has the following functions:
7133 @defun LazyString.value ()
7134 Convert the @code{gdb.LazyString} to a @code{gdb.Value}. This value
7135 will point to the string in memory, but will lose all the delayed
7136 retrieval, encoding and handling that @value{GDBN} applies to a
7137 @code{gdb.LazyString}.
7140 @defvar LazyString.address
7141 This attribute holds the address of the string. This attribute is not
7145 @defvar LazyString.length
7146 This attribute holds the length of the string in characters. If the
7147 length is -1, then the string will be fetched and encoded up to the
7148 first null of appropriate width. This attribute is not writable.
7151 @defvar LazyString.encoding
7152 This attribute holds the encoding that will be applied to the string
7153 when the string is printed by @value{GDBN}. If the encoding is not
7154 set, or contains an empty string, then @value{GDBN} will select the
7155 most appropriate encoding when the string is printed. This attribute
7159 @defvar LazyString.type
7160 This attribute holds the type that is represented by the lazy string's
7161 type. For a lazy string this is a pointer or array type. To
7162 resolve this to the lazy string's character type, use the type's
7163 @code{target} method. @xref{Types In Python}. This attribute is not
7167 @node Colors In Python
7168 @subsubsection Python representation of colors
7170 @cindex colors in python
7172 You can assign instance of @code{gdb.Color} to the @code{value} of
7173 a @code{Parameter} instance created with @code{PARAM_COLOR}.
7175 @code{gdb.Color} may refer to an index from a color palette or contain
7176 components of a color from some color space.
7178 @defun Color.__init__ (@r{[}value @r{[}, color_space@r{]}@r{]})
7180 @var{value} is @code{None} (meaning the terminal's default color),
7181 an integer index of a color in palette, tuple with color components
7182 or a string. String can be a hex RGB triplet in @samp{#RRGGBB} format
7183 or one of the following color names:
7184 @samp{none} (meaning the terminal's default color), @samp{black}, @samp{red},
7185 @samp{green}, @samp{yellow}, @samp{blue}, @samp{magenta}, @samp{cyan},
7188 @var{color_space} should be one of the @samp{COLORSPACE_} constants
7189 listed below. This argument tells @value{GDBN} which color space
7190 @var{value} belongs.
7193 @defvar Color.is_none
7194 This attribute is boolean. If its value is @code{True} then color is terminal's
7198 @defvar Color.is_indexed
7199 This attribute is boolean. If its value is @code{True} then color is indexed,
7200 i.e. belongs to some palette.
7203 @defvar Color.is_direct
7204 This attribute is boolean. If its value is @code{True} then this object
7205 describes direct colour in the sense of ISO/IEC 8613-6.
7209 This attribute exist if @code{is_indexed} is @code{True}. Its integer value is
7210 index of a color in a palette.
7213 @defvar Color.components
7214 This attribute exist if @code{is_direct} is @code{True}. Its value is tuple
7215 with integer components of a color.
7218 @defun Color.escape_sequence (is_foreground)
7219 Returns string to change terminal's color to this.
7221 If @var{is_foreground} is @code{True}, then the returned sequence will change
7222 foreground color. Otherwise, the returned sequence will change background
7225 If styling is currently disabled (@pxref{Output Styling,,@kbd{set style
7226 enabled}}), then this method will return an empty string.
7229 When color is initialized, its color space must be specified. The
7230 available color spaces are represented by constants defined in the @code{gdb}
7234 @findex COLORSPACE_MONOCHROME
7235 @findex gdb.COLORSPACE_MONOCHROME
7236 @item gdb.COLORSPACE_MONOCHROME
7237 Palette with only terminal's default color.
7239 @findex COLORSPACE_ANSI_8COLOR
7240 @findex gdb.COLORSPACE_ANSI_8COLOR
7241 @item gdb.COLORSPACE_ANSI_8COLOR
7242 Palette with eight standard colors of ISO/IEC 6429 "black", "red", "green", etc.
7244 @findex COLORSPACE_AIXTERM_16COLOR
7245 @findex gdb.COLORSPACE_AIXTERM_16COLOR
7246 @item gdb.COLORSPACE_AIXTERM_16COLOR
7247 Palette with 16 colors. First eight are standard colors of ISO/IEC 6429
7248 "black", "red", "green", etc. Next eight are their bright version.
7250 @findex COLORSPACE_XTERM_256COLOR
7251 @findex gdb.COLORSPACE_XTERM_256COLOR
7252 @item gdb.COLORSPACE_XTERM_256COLOR
7253 Palette with 256 colors. First 16 are from COLORSPACE_AIXTERM_16COLOR. Next
7254 216 colors are 6x6x6 RGB cube. And last 24 colors form grayscale ramp.
7256 @findex COLORSPACE_RGB_24BIT
7257 @findex gdb.COLORSPACE_RGB_24BIT
7258 @item gdb.COLORSPACE_RGB_24BIT
7259 Direct 24-bit RGB colors.
7263 It is not possible to sub-class the @code{Color} class.
7265 @node Architectures In Python
7266 @subsubsection Python representation of architectures
7267 @cindex Python architectures
7269 @value{GDBN} uses architecture specific parameters and artifacts in a
7270 number of its various computations. An architecture is represented
7271 by an instance of the @code{gdb.Architecture} class.
7273 A @code{gdb.Architecture} class has the following methods:
7275 @anchor{gdbpy_architecture_name}
7276 @defun Architecture.name ()
7277 Return the name (string value) of the architecture.
7280 @defun Architecture.disassemble (start_pc @r{[}, end_pc @r{[}, count@r{]]})
7281 Return a list of disassembled instructions starting from the memory
7282 address @var{start_pc}. The optional arguments @var{end_pc} and
7283 @var{count} determine the number of instructions in the returned list.
7284 If both the optional arguments @var{end_pc} and @var{count} are
7285 specified, then a list of at most @var{count} disassembled instructions
7286 whose start address falls in the closed memory address interval from
7287 @var{start_pc} to @var{end_pc} are returned. If @var{end_pc} is not
7288 specified, but @var{count} is specified, then @var{count} number of
7289 instructions starting from the address @var{start_pc} are returned. If
7290 @var{count} is not specified but @var{end_pc} is specified, then all
7291 instructions whose start address falls in the closed memory address
7292 interval from @var{start_pc} to @var{end_pc} are returned. If neither
7293 @var{end_pc} nor @var{count} are specified, then a single instruction at
7294 @var{start_pc} is returned. For all of these cases, each element of the
7295 returned list is a Python @code{dict} with the following string keys:
7300 The value corresponding to this key is a Python long integer capturing
7301 the memory address of the instruction.
7304 The value corresponding to this key is a string value which represents
7305 the instruction with assembly language mnemonics. The assembly
7306 language flavor used is the same as that specified by the current CLI
7307 variable @code{disassembly-flavor}. @xref{Machine Code}.
7310 The value corresponding to this key is the length (integer value) of the
7311 instruction in bytes.
7316 @defun Architecture.integer_type (size @r{[}, signed@r{]})
7317 This function looks up an integer type by its @var{size}, and
7318 optionally whether or not it is signed.
7320 @var{size} is the size, in bits, of the desired integer type. Only
7321 certain sizes are currently supported: 0, 8, 16, 24, 32, 64, and 128.
7323 If @var{signed} is not specified, it defaults to @code{True}. If
7324 @var{signed} is @code{False}, the returned type will be unsigned.
7326 If the indicated type cannot be found, this function will throw a
7327 @code{ValueError} exception.
7330 @defun Architecture.void_type ()
7331 This function returns a void type.
7334 @anchor{gdbpy_architecture_registers}
7335 @defun Architecture.registers (@r{[} reggroup @r{]})
7336 Return a @code{gdb.RegisterDescriptorIterator} (@pxref{Registers In
7337 Python}) for all of the registers in @var{reggroup}, a string that is
7338 the name of a register group. If @var{reggroup} is omitted, or is the
7339 empty string, then the register group @samp{all} is assumed.
7342 @anchor{gdbpy_architecture_reggroups}
7343 @defun Architecture.register_groups ()
7344 Return a @code{gdb.RegisterGroupsIterator} (@pxref{Registers In
7345 Python}) for all of the register groups available for the
7346 @code{gdb.Architecture}.
7349 @node Registers In Python
7350 @subsubsection Registers In Python
7351 @cindex Registers In Python
7353 Python code can request from a @code{gdb.Architecture} information
7354 about the set of registers available
7355 (@pxref{gdbpy_architecture_registers,,@code{Architecture.registers}}).
7356 The register information is returned as a
7357 @code{gdb.RegisterDescriptorIterator}, which is an iterator that in
7358 turn returns @code{gdb.RegisterDescriptor} objects.
7360 A @code{gdb.RegisterDescriptor} does not provide the value of a
7361 register (@pxref{gdbpy_frame_read_register,,@code{Frame.read_register}}
7362 for reading a register's value), instead the @code{RegisterDescriptor}
7363 is a way to discover which registers are available for a particular
7366 A @code{gdb.RegisterDescriptor} has the following read-only properties:
7368 @defvar RegisterDescriptor.name
7369 The name of this register.
7372 It is also possible to lookup a register descriptor based on its name
7373 using the following @code{gdb.RegisterDescriptorIterator} function:
7375 @defun RegisterDescriptorIterator.find (name)
7376 Takes @var{name} as an argument, which must be a string, and returns a
7377 @code{gdb.RegisterDescriptor} for the register with that name, or
7378 @code{None} if there is no register with that name.
7381 Python code can also request from a @code{gdb.Architecture}
7382 information about the set of register groups available on a given
7384 (@pxref{gdbpy_architecture_reggroups,,@code{Architecture.register_groups}}).
7386 Every register can be a member of zero or more register groups. Some
7387 register groups are used internally within @value{GDBN} to control
7388 things like which registers must be saved when calling into the
7389 program being debugged (@pxref{Calling,,Calling Program Functions}).
7390 Other register groups exist to allow users to easily see related sets
7391 of registers in commands like @code{info registers}
7392 (@pxref{info_registers_reggroup,,@code{info registers
7395 The register groups information is returned as a
7396 @code{gdb.RegisterGroupsIterator}, which is an iterator that in turn
7397 returns @code{gdb.RegisterGroup} objects.
7399 A @code{gdb.RegisterGroup} object has the following read-only
7402 @defvar RegisterGroup.name
7403 A string that is the name of this register group.
7406 @node Connections In Python
7407 @subsubsection Connections In Python
7408 @cindex connections in python
7409 @value{GDBN} lets you run and debug multiple programs in a single
7410 session. Each program being debugged has a connection, the connection
7411 describes how @value{GDBN} controls the program being debugged.
7412 Examples of different connection types are @samp{native} and
7413 @samp{remote}. @xref{Inferiors Connections and Programs}.
7415 Connections in @value{GDBN} are represented as instances of
7416 @code{gdb.TargetConnection}, or as one of its sub-classes. To get a
7417 list of all connections use @code{gdb.connections}
7418 (@pxref{gdbpy_connections,,gdb.connections}).
7420 To get the connection for a single @code{gdb.Inferior} read its
7421 @code{gdb.Inferior.connection} attribute
7422 (@pxref{gdbpy_inferior_connection,,gdb.Inferior.connection}).
7424 Currently there is only a single sub-class of
7425 @code{gdb.TargetConnection}, @code{gdb.RemoteTargetConnection},
7426 however, additional sub-classes may be added in future releases of
7427 @value{GDBN}. As a result you should avoid writing code like:
7430 conn = gdb.selected_inferior().connection
7431 if type(conn) is gdb.RemoteTargetConnection:
7432 print("This is a remote target connection")
7436 as this may fail when more connection types are added. Instead, you
7440 conn = gdb.selected_inferior().connection
7441 if isinstance(conn, gdb.RemoteTargetConnection):
7442 print("This is a remote target connection")
7445 A @code{gdb.TargetConnection} has the following method:
7447 @defun TargetConnection.is_valid ()
7448 Return @code{True} if the @code{gdb.TargetConnection} object is valid,
7449 @code{False} if not. A @code{gdb.TargetConnection} will become
7450 invalid if the connection no longer exists within @value{GDBN}, this
7451 might happen when no inferiors are using the connection, but could be
7452 delayed until the user replaces the current target.
7454 Reading any of the @code{gdb.TargetConnection} properties will throw
7455 an exception if the connection is invalid.
7458 A @code{gdb.TargetConnection} has the following read-only properties:
7460 @defvar TargetConnection.num
7461 An integer assigned by @value{GDBN} to uniquely identify this
7462 connection. This is the same value as displayed in the @samp{Num}
7463 column of the @code{info connections} command output (@pxref{Inferiors
7464 Connections and Programs,,info connections}).
7467 @defvar TargetConnection.type
7468 A string that describes what type of connection this is. This string
7469 will be one of the valid names that can be passed to the @code{target}
7470 command (@pxref{Target Commands,,target command}).
7473 @defvar TargetConnection.description
7474 A string that gives a short description of this target type. This is
7475 the same string that is displayed in the @samp{Description} column of
7476 the @code{info connection} command output (@pxref{Inferiors
7477 Connections and Programs,,info connections}).
7480 @defvar TargetConnection.details
7481 An optional string that gives additional information about this
7482 connection. This attribute can be @code{None} if there are no
7483 additional details for this connection.
7485 An example of a connection type that might have additional details is
7486 the @samp{remote} connection, in this case the details string can
7487 contain the @samp{@var{hostname}:@var{port}} that was used to connect
7488 to the remote target.
7491 The @code{gdb.RemoteTargetConnection} class is a sub-class of
7492 @code{gdb.TargetConnection}, and is used to represent @samp{remote}
7493 and @samp{extended-remote} connections. In addition to the attributes
7494 and methods available from the @code{gdb.TargetConnection} base class,
7495 a @code{gdb.RemoteTargetConnection} has the following method:
7497 @kindex maint packet
7498 @defun RemoteTargetConnection.send_packet (packet)
7499 This method sends @var{packet} to the remote target and returns the
7500 response. The @var{packet} should either be a @code{bytes} object, or
7501 a @code{Unicode} string.
7503 If @var{packet} is a @code{Unicode} string, then the string is encoded
7504 to a @code{bytes} object using the @sc{ascii} codec. If the string
7505 can't be encoded then an @code{UnicodeError} is raised.
7507 If @var{packet} is not a @code{bytes} object, or a @code{Unicode}
7508 string, then a @code{TypeError} is raised. If @var{packet} is empty
7509 then a @code{ValueError} is raised.
7511 The response is returned as a @code{bytes} object. If it is known
7512 that the response can be represented as a string then this can be
7513 decoded from the buffer. For example, if it is known that the
7514 response is an @sc{ascii} string:
7517 remote_connection.send_packet("some_packet").decode("ascii")
7520 The prefix, suffix, and checksum (as required by the remote serial
7521 protocol) are automatically added to the outgoing packet, and removed
7522 from the incoming packet before the contents of the reply are
7525 This is equivalent to the @code{maintenance packet} command
7526 (@pxref{maint packet}).
7529 @node TUI Windows In Python
7530 @subsubsection Implementing new TUI windows
7531 @cindex Python TUI Windows
7533 New TUI (@pxref{TUI}) windows can be implemented in Python.
7535 @defun gdb.register_window_type (name, factory)
7536 Because TUI windows are created and destroyed depending on the layout
7537 the user chooses, new window types are implemented by registering a
7538 factory function with @value{GDBN}.
7540 @var{name} is the name of the new window. It's an error to try to
7541 replace one of the built-in windows, but other window types can be
7542 replaced. The @var{name} should match the regular expression
7543 @code{[a-zA-Z][-_.a-zA-Z0-9]*}, it is an error to try and create a
7544 window with an invalid name.
7546 @var{function} is a factory function that is called to create the TUI
7547 window. This is called with a single argument of type
7548 @code{gdb.TuiWindow}, described below. It should return an object
7549 that implements the TUI window protocol, also described below.
7552 As mentioned above, when a factory function is called, it is passed
7553 an object of type @code{gdb.TuiWindow}. This object has these
7554 methods and attributes:
7556 @defun TuiWindow.is_valid ()
7557 This method returns @code{True} when this window is valid. When the
7558 user changes the TUI layout, windows no longer visible in the new
7559 layout will be destroyed. At this point, the @code{gdb.TuiWindow}
7560 will no longer be valid, and methods (and attributes) other than
7561 @code{is_valid} will throw an exception.
7563 When the TUI is disabled using @code{tui disable} (@pxref{TUI
7564 Commands,,tui disable}) the window is hidden rather than destroyed,
7565 but @code{is_valid} will still return @code{False} and other methods
7566 (and attributes) will still throw an exception.
7569 @defvar TuiWindow.width
7570 This attribute holds the width of the window. It is not writable.
7573 @defvar TuiWindow.height
7574 This attribute holds the height of the window. It is not writable.
7577 @defvar TuiWindow.title
7578 This attribute holds the window's title, a string. This is normally
7579 displayed above the window. This attribute can be modified.
7582 @defun TuiWindow.erase ()
7583 Remove all the contents of the window.
7586 @defun TuiWindow.write (string @r{[}, full_window@r{]})
7587 Write @var{string} to the window. @var{string} can contain ANSI
7588 terminal escape styling sequences; @value{GDBN} will translate these
7589 as appropriate for the terminal.
7591 If the @var{full_window} parameter is @code{True}, then @var{string}
7592 contains the full contents of the window. This is similar to calling
7593 @code{erase} before @code{write}, but avoids the flickering.
7596 The factory function that you supply should return an object
7597 conforming to the TUI window protocol. These are the methods that can
7598 be called on this object, which is referred to below as the ``window
7599 object''. The methods documented below are optional; if the object
7600 does not implement one of these methods, @value{GDBN} will not attempt
7601 to call it. Additional new methods may be added to the window
7602 protocol in the future. @value{GDBN} guarantees that they will begin
7603 with a lower-case letter, so you can start implementation methods with
7604 upper-case letters or underscore to avoid any future conflicts.
7606 @defun Window.close ()
7607 When the TUI window is closed, the @code{gdb.TuiWindow} object will be
7608 put into an invalid state. At this time, @value{GDBN} will call
7609 @code{close} method on the window object.
7611 After this method is called, @value{GDBN} will discard any references
7612 it holds on this window object, and will no longer call methods on
7616 @defun Window.render ()
7617 In some situations, a TUI window can change size. For example, this
7618 can happen if the user resizes the terminal, or changes the layout.
7619 When this happens, @value{GDBN} will call the @code{render} method on
7622 If your window is intended to update in response to changes in the
7623 inferior, you will probably also want to register event listeners and
7624 send output to the @code{gdb.TuiWindow}.
7627 @defun Window.hscroll (num)
7628 This is a request to scroll the window horizontally. @var{num} is the
7629 amount by which to scroll, with negative numbers meaning to scroll
7630 right. In the TUI model, it is the viewport that moves, not the
7631 contents. A positive argument should cause the viewport to move
7632 right, and so the content should appear to move to the left.
7635 @defun Window.vscroll (num)
7636 This is a request to scroll the window vertically. @var{num} is the
7637 amount by which to scroll, with negative numbers meaning to scroll
7638 backward. In the TUI model, it is the viewport that moves, not the
7639 contents. A positive argument should cause the viewport to move down,
7640 and so the content should appear to move up.
7643 @anchor{python-window-click}
7644 @defun Window.click (x, y, button)
7645 This is called on a mouse click in this window. @var{x} and @var{y} are
7646 the mouse coordinates inside the window (0-based, from the top left
7647 corner), and @var{button} specifies which mouse button was used, whose
7648 values can be 1 (left), 2 (middle), or 3 (right).
7650 When TUI mouse events are disabled by turning off the @code{tui mouse-events}
7651 setting (@pxref{tui-mouse-events,,set tui mouse-events}), then @code{click} will
7655 @node Disassembly In Python
7656 @subsubsection Instruction Disassembly In Python
7657 @cindex python instruction disassembly
7659 @value{GDBN}'s builtin disassembler can be extended, or even replaced,
7660 using the Python API. The disassembler related features are contained
7661 within the @code{gdb.disassembler} module:
7663 @anchor{DisassembleInfo Class}
7664 @deftp {class} gdb.disassembler.DisassembleInfo
7665 Disassembly is driven by instances of this class. Each time
7666 @value{GDBN} needs to disassemble an instruction, an instance of this
7667 class is created and passed to a registered disassembler. The
7668 disassembler is then responsible for disassembling an instruction and
7671 Instances of this type are usually created within @value{GDBN},
7672 however, it is possible to create a copy of an instance of this type,
7673 see the description of @code{__init__} for more details.
7675 This class has the following properties and methods:
7677 @defvar DisassembleInfo.address
7678 A read-only integer containing the address at which @value{GDBN}
7679 wishes to disassemble a single instruction.
7682 @defvar DisassembleInfo.architecture
7683 The @code{gdb.Architecture} (@pxref{Architectures In Python}) for
7684 which @value{GDBN} is currently disassembling, this property is
7688 @defvar DisassembleInfo.progspace
7689 The @code{gdb.Progspace} (@pxref{Progspaces In Python,,Program Spaces
7690 In Python}) for which @value{GDBN} is currently disassembling, this
7691 property is read-only.
7694 @defun DisassembleInfo.is_valid ()
7695 Returns @code{True} if the @code{DisassembleInfo} object is valid,
7696 @code{False} if not. A @code{DisassembleInfo} object will become
7697 invalid once the disassembly call for which the @code{DisassembleInfo}
7698 was created, has returned. Calling other @code{DisassembleInfo}
7699 methods, or accessing @code{DisassembleInfo} properties, will raise a
7700 @code{RuntimeError} exception if it is invalid.
7703 @defun DisassembleInfo.__init__ (info)
7704 This can be used to create a new @code{DisassembleInfo} object that is
7705 a copy of @var{info}. The copy will have the same @code{address},
7706 @code{architecture}, and @code{progspace} values as @var{info}, and
7707 will become invalid at the same time as @var{info}.
7709 This method exists so that sub-classes of @code{DisassembleInfo} can
7710 be created, these sub-classes must be initialized as copies of an
7711 existing @code{DisassembleInfo} object, but sub-classes might choose
7712 to override the @code{read_memory} method, and so control what
7713 @value{GDBN} sees when reading from memory
7714 (@pxref{builtin_disassemble}).
7717 @defun DisassembleInfo.read_memory (length, offset)
7718 This method allows the disassembler to read the bytes of the
7719 instruction to be disassembled. The method reads @var{length} bytes,
7720 starting at @var{offset} from
7721 @code{DisassembleInfo.address}.
7723 It is important that the disassembler read the instruction bytes using
7724 this method, rather than reading inferior memory directly, as in some
7725 cases @value{GDBN} disassembles from an internal buffer rather than
7726 directly from inferior memory, calling this method handles this
7729 Returns a buffer object, which behaves much like an array or a string,
7730 just as @code{Inferior.read_memory} does
7731 (@pxref{gdbpy_inferior_read_memory,,Inferior.read_memory}). The
7732 length of the returned buffer will always be exactly @var{length}.
7734 If @value{GDBN} is unable to read the required memory then a
7735 @code{gdb.MemoryError} exception is raised (@pxref{Exception
7738 This method can be overridden by a sub-class in order to control what
7739 @value{GDBN} sees when reading from memory
7740 (@pxref{builtin_disassemble}). When overriding this method it is
7741 important to understand how @code{builtin_disassemble} makes use of
7744 While disassembling a single instruction there could be multiple calls
7745 to this method, and the same bytes might be read multiple times. Any
7746 single call might only read a subset of the total instruction bytes.
7748 If an implementation of @code{read_memory} is unable to read the
7749 requested memory contents, for example, if there's a request to read
7750 from an invalid memory address, then a @code{gdb.MemoryError} should
7753 Raising a @code{MemoryError} inside @code{read_memory} does not
7754 automatically mean a @code{MemoryError} will be raised by
7755 @code{builtin_disassemble}. It is possible the @value{GDBN}'s builtin
7756 disassembler is probing to see how many bytes are available. When
7757 @code{read_memory} raises the @code{MemoryError} the builtin
7758 disassembler might be able to perform a complete disassembly with the
7759 bytes it has available, in this case @code{builtin_disassemble} will
7760 not itself raise a @code{MemoryError}.
7762 Any other exception type raised in @code{read_memory} will propagate
7763 back and be re-raised by @code{builtin_disassemble}.
7766 @defun DisassembleInfo.text_part (style, string)
7767 Create a new @code{DisassemblerTextPart} representing a piece of a
7768 disassembled instruction. @var{string} should be a non-empty string,
7769 and @var{style} should be an appropriate style constant
7770 (@pxref{Disassembler Style Constants}).
7772 Disassembler parts are used when creating a @code{DisassemblerResult}
7773 in order to represent the styling within an instruction
7774 (@pxref{DisassemblerResult Class}).
7777 @defun DisassembleInfo.address_part (address)
7778 Create a new @code{DisassemblerAddressPart}. @var{address} is the
7779 value of the absolute address this part represents. A
7780 @code{DisassemblerAddressPart} is displayed as an absolute address and
7781 an associated symbol, the address and symbol are styled appropriately.
7786 @anchor{Disassembler Class}
7787 @deftp {class} gdb.disassembler.Disassembler
7788 This is a base class from which all user implemented disassemblers
7791 @defun Disassembler.__init__ (name)
7792 The constructor takes @var{name}, a string, which should be a short
7793 name for this disassembler.
7796 @defun Disassembler.__call__ (info)
7797 The @code{__call__} method must be overridden by sub-classes to
7798 perform disassembly. Calling @code{__call__} on this base class will
7799 raise a @code{NotImplementedError} exception.
7801 The @var{info} argument is an instance of @code{DisassembleInfo}, and
7802 describes the instruction that @value{GDBN} wants disassembling.
7804 If this function returns @code{None}, this indicates to @value{GDBN}
7805 that this sub-class doesn't wish to disassemble the requested
7806 instruction. @value{GDBN} will then use its builtin disassembler to
7807 perform the disassembly.
7809 Alternatively, this function can return a @code{DisassemblerResult}
7810 that represents the disassembled instruction, this type is described
7811 in more detail below.
7813 The @code{__call__} method can raise a @code{gdb.MemoryError}
7814 exception (@pxref{Exception Handling}) to indicate to @value{GDBN}
7815 that there was a problem accessing the required memory, this will then
7816 be displayed by @value{GDBN} within the disassembler output.
7818 Ideally, the only three outcomes from invoking @code{__call__} would
7819 be a return of @code{None}, a successful disassembly returned in a
7820 @code{DisassemblerResult}, or a @code{MemoryError} indicating that
7821 there was a problem reading memory.
7823 However, as an implementation of @code{__call__} could fail due to
7824 other reasons, e.g.@: some external resource required to perform
7825 disassembly is temporarily unavailable, then, if @code{__call__}
7826 raises a @code{GdbError}, the exception will be converted to a string
7827 and printed at the end of the disassembly output, the disassembly
7828 request will then stop.
7830 Any other exception type raised by the @code{__call__} method is
7831 considered an error in the user code, the exception will be printed to
7832 the error stream according to the @kbd{set python print-stack} setting
7833 (@pxref{set_python_print_stack,,@kbd{set python print-stack}}).
7837 @anchor{DisassemblerResult Class}
7838 @deftp {class} gdb.disassembler.DisassemblerResult
7839 This class represents the result of disassembling a single
7840 instruction. An instance of this class will be returned from
7841 @code{builtin_disassemble} (@pxref{builtin_disassemble}), and an
7842 instance of this class should be returned from
7843 @w{@code{Disassembler.__call__}} (@pxref{Disassembler Class}) if an
7844 instruction was successfully disassembled.
7846 It is not possible to sub-class the @code{DisassemblerResult} class.
7848 The @code{DisassemblerResult} class has the following properties and
7851 @defun DisassemblerResult.__init__ (length, string, parts)
7852 Initialize an instance of this class, @var{length} is the length of
7853 the disassembled instruction in bytes, which must be greater than
7856 Only one of @var{string} or @var{parts} should be used to initialize a
7857 new @code{DisassemblerResult}; the other one should be passed the
7858 value @code{None}. Alternatively, the arguments can be passed by
7859 name, and the unused argument can be ignored.
7861 The @var{string} argument, if not @code{None}, is a non-empty string
7862 that represents the entire disassembled instruction. Building a result
7863 object using the @var{string} argument does not allow for any styling
7864 information to be included in the result. @value{GDBN} will style the
7865 result as a single @code{DisassemblerTextPart} with @code{STYLE_TEXT}
7866 style (@pxref{Disassembler Styling Parts}).
7868 The @var{parts} argument, if not @code{None}, is a non-empty sequence
7869 of @code{DisassemblerPart} objects. Each part represents a small part
7870 of the disassembled instruction along with associated styling
7871 information. A result object built using @var{parts} can be displayed
7872 by @value{GDBN} with full styling information
7873 (@pxref{style_disassembler_enabled,,@kbd{set style disassembler
7877 @defvar DisassemblerResult.length
7878 A read-only property containing the length of the disassembled
7879 instruction in bytes, this will always be greater than zero.
7882 @defvar DisassemblerResult.string
7883 A read-only property containing a non-empty string representing the
7884 disassembled instruction. The @var{string} is a representation of the
7885 disassembled instruction without any styling information. To see how
7886 the instruction will be styled use the @var{parts} property.
7888 If this instance was initialized using separate
7889 @code{DisassemblerPart} objects, the @var{string} property will still
7890 be valid. The @var{string} value is created by concatenating the
7891 @code{DisassemblerPart.string} values of each component part
7892 (@pxref{Disassembler Styling Parts}).
7895 @defvar DisassemblerResult.parts
7896 A read-only property containing a non-empty sequence of
7897 @code{DisassemblerPart} objects. Each @code{DisassemblerPart} object
7898 contains a small part of the instruction along with information about
7899 how that part should be styled. @value{GDBN} uses this information to
7900 create styled disassembler output
7901 (@pxref{style_disassembler_enabled,,@kbd{set style disassembler
7904 If this instance was initialized using a single string rather than
7905 with a sequence of @code{DisassemblerPart} objects, the @var{parts}
7906 property will still be valid. In this case the @var{parts} property
7907 will hold a sequence containing a single @code{DisassemblerTextPart}
7908 object, the string of which will represent the entire instruction, and
7909 the style of which will be @code{STYLE_TEXT}.
7913 @anchor{Disassembler Styling Parts}
7914 @deftp {class} gdb.disassembler.DisassemblerPart
7915 This is a parent class from which the different part sub-classes
7916 inherit. Only instances of the sub-classes detailed below will be
7917 returned by the Python API.
7919 It is not possible to directly create instances of either this parent
7920 class, or any of the sub-classes listed below. Instances of the
7921 sub-classes listed below are created by calling
7922 @code{builtin_disassemble} (@pxref{builtin_disassemble}) and are
7923 returned within the @code{DisassemblerResult} object, or can be
7924 created by calling the @code{text_part} and @code{address_part}
7925 methods on the @code{DisassembleInfo} class (@pxref{DisassembleInfo
7928 The @code{DisassemblerPart} class has a single property:
7930 @defvar DisassemblerPart.string
7931 A read-only property that contains a non-empty string representing
7932 this part of the disassembled instruction. The string within this
7933 property doesn't include any styling information.
7937 @deftp {class} gdb.disassembler.DisassemblerTextPart
7938 The @code{DisassemblerTextPart} class represents a piece of the
7939 disassembled instruction and the associated style for that piece.
7940 Instances of this class can't be created directly, instead call
7941 @code{DisassembleInfo.text_part} to create a new instance of this
7942 class (@pxref{DisassembleInfo Class}).
7944 As well as the properties of its parent class, the
7945 @code{DisassemblerTextPart} has the following additional property:
7947 @defvar DisassemblerTextPart.style
7948 A read-only property that contains one of the defined style constants.
7949 @value{GDBN} will use this style when styling this part of the
7950 disassembled instruction (@pxref{Disassembler Style Constants}).
7954 @deftp {class} gdb.disassembler.DisassemblerAddressPart
7955 The @code{DisassemblerAddressPart} class represents an absolute
7956 address within a disassembled instruction. Using a
7957 @code{DisassemblerAddressPart} instead of a
7958 @code{DisassemblerTextPart} with @code{STYLE_ADDRESS} is preferred,
7959 @value{GDBN} will display the address as both an absolute address, and
7960 will look up a suitable symbol to display next to the address. Using
7961 @code{DisassemblerAddressPart} also ensures that user settings such as
7962 @code{set print max-symbolic-offset} are respected.
7964 Here is an example of an x86-64 instruction:
7971 In this instruction the @code{0x401136 <foo>} was generated from a
7972 single @code{DisassemblerAddressPart}. The @code{0x401136} will be
7973 styled with @code{STYLE_ADDRESS}, and @code{foo} will be styled with
7974 @code{STYLE_SYMBOL}. The @code{<} and @code{>} will be styled as
7977 If the inclusion of the symbol name is not required then a
7978 @code{DisassemblerTextPart} with style @code{STYLE_ADDRESS} can be
7981 Instances of this class can't be created directly, instead call
7982 @code{DisassembleInfo.address_part} to create a new instance of this
7983 class (@pxref{DisassembleInfo Class}).
7985 As well as the properties of its parent class, the
7986 @code{DisassemblerAddressPart} has the following additional property:
7988 @defvar DisassemblerAddressPart.address
7989 A read-only property that contains the @var{address} passed to this
7990 object's @code{__init__} method.
7994 @anchor{Disassembler Style Constants}
7996 The following table lists all of the disassembler styles that are
7997 available. @value{GDBN} maps these style constants onto its style
7998 settings (@pxref{Output Styling}). In some cases, several style
7999 constants produce the same style settings, and thus will produce the
8000 same visual effect on the screen. This could change in future
8001 releases of @value{GDBN}, so care should be taken to select the
8002 correct style constant to ensure correct output styling in future
8003 releases of @value{GDBN}.
8007 @item gdb.disassembler.STYLE_TEXT
8008 This is the default style used by @value{GDBN} when styling
8009 disassembler output. This style should be used for any parts of the
8010 instruction that don't fit any of the other styles listed below.
8011 @value{GDBN} styles text with this style using its default style.
8013 @vindex STYLE_MNEMONIC
8014 @item gdb.disassembler.STYLE_MNEMONIC
8015 This style is used for styling the primary instruction mnemonic, which
8016 usually appears at, or near, the start of the disassembled instruction
8019 @value{GDBN} styles text with this style using the @code{disassembler
8020 mnemonic} style setting.
8022 @vindex STYLE_SUB_MNEMONIC
8023 @item gdb.disassembler.STYLE_SUB_MNEMONIC
8024 This style is used for styling any sub-mnemonics within a disassembled
8025 instruction. A sub-mnemonic is any text within the instruction that
8026 controls the function of the instruction, but which is disjoint from
8027 the primary mnemonic (which will have styled @code{STYLE_MNEMONIC}).
8029 As an example, consider this AArch64 instruction:
8032 add w16, w7, w1, lsl #1
8036 The @code{add} is the primary instruction mnemonic, and would be given
8037 style @code{STYLE_MNEMONIC}, while @code{lsl} is the sub-mnemonic, and
8038 would be given the style @code{STYLE_SUB_MNEMONIC}.
8040 @value{GDBN} styles text with this style using the @code{disassembler
8041 mnemonic} style setting.
8043 @vindex STYLE_ASSEMBLER_DIRECTIVE
8044 @item gdb.disassembler.STYLE_ASSEMBLER_DIRECTIVE
8045 Sometimes a series of bytes doesn't decode to a valid instruction. In
8046 this case the disassembler may choose to represent the result of
8047 disassembling using an assembler directive, for example:
8054 In this case, the @code{.word} would be give the
8055 @code{STYLE_ASSEMBLER_DIRECTIVE} style. An assembler directive is
8056 similar to a mnemonic in many ways but is something that is not part
8057 of the architecture's instruction set.
8059 @value{GDBN} styles text with this style using the @code{disassembler
8060 mnemonic} style setting.
8062 @vindex STYLE_REGISTER
8063 @item gdb.disassembler.STYLE_REGISTER
8064 This style is used for styling any text that represents a register
8065 name, or register number, within a disassembled instruction.
8067 @value{GDBN} styles text with this style using the @code{disassembler
8068 register} style setting.
8070 @vindex STYLE_ADDRESS
8071 @item gdb.disassembler.STYLE_ADDRESS
8072 This style is used for styling numerical values that represent
8073 absolute addresses within the disassembled instruction.
8075 When creating a @code{DisassemblerTextPart} with this style, you
8076 should consider if a @code{DisassemblerAddressPart} would be more
8077 appropriate. See @ref{Disassembler Styling Parts} for a description
8078 of what each part offers.
8080 @value{GDBN} styles text with this style using the @code{disassembler
8081 address} style setting.
8083 @vindex STYLE_ADDRESS_OFFSET
8084 @item gdb.disassembler.STYLE_ADDRESS_OFFSET
8085 This style is used for styling numerical values that represent offsets
8086 to addresses within the disassembled instruction. A value is
8087 considered an address offset when the instruction itself is going to
8088 access memory, and the value is being used to offset which address is
8091 For example, an architecture might have an instruction that loads from
8092 memory using an address within a register. If that instruction also
8093 allowed for an immediate offset to be encoded into the instruction,
8094 this would be an address offset. Similarly, a branch instruction
8095 might jump to an address in a register plus an address offset that is
8096 encoded into the instruction.
8098 @value{GDBN} styles text with this style using the @code{disassembler
8099 immediate} style setting.
8101 @vindex STYLE_IMMEDIATE
8102 @item gdb.disassembler.STYLE_IMMEDIATE
8103 Use @code{STYLE_IMMEDIATE} for any numerical values within a
8104 disassembled instruction when those values are not addresses, address
8105 offsets, or register numbers (The styles @code{STYLE_ADDRESS},
8106 @code{STYLE_ADDRESS_OFFSET}, or @code{STYLE_REGISTER} can be used in
8109 @value{GDBN} styles text with this style using the @code{disassembler
8110 immediate} style setting.
8112 @vindex STYLE_SYMBOL
8113 @item gdb.disassembler.STYLE_SYMBOL
8114 This style is used for styling the textual name of a symbol that is
8115 included within a disassembled instruction. A symbol name is often
8116 included next to an absolute address within a disassembled instruction
8117 to make it easier for the user to understand what the address is
8118 referring too. For example:
8125 Here @code{foo} is the name of a symbol, and should be given the
8126 @code{STYLE_SYMBOL} style.
8128 Adding symbols next to absolute addresses like this is handled
8129 automatically by the @code{DisassemblerAddressPart} class
8130 (@pxref{Disassembler Styling Parts}).
8132 @value{GDBN} styles text with this style using the @code{disassembler
8133 symbol} style setting.
8135 @vindex STYLE_COMMENT_START
8136 @item gdb.disassembler.STYLE_COMMENT_START
8137 This style is used to start a line comment in the disassembly output.
8138 Unlike other styles, which only apply to the single
8139 @code{DisassemblerTextPiece} to which they are applied, the comment
8140 style is sticky, and overrides the style of any further pieces within
8143 This means that, after a @code{STYLE_COMMENT_START} piece has been
8144 seen, @value{GDBN} will apply the comment style until the end of the
8145 line, ignoring the specific style within a piece.
8147 @value{GDBN} styles text with this style using the @code{disassembler
8148 comment} style setting.
8151 The following functions are also contained in the
8152 @code{gdb.disassembler} module:
8154 @defun register_disassembler (disassembler, architecture)
8155 The @var{disassembler} must be a sub-class of
8156 @code{gdb.disassembler.Disassembler} or @code{None}.
8158 The optional @var{architecture} is either a string, or the value
8159 @code{None}. If it is a string, then it should be the name of an
8160 architecture known to @value{GDBN}, as returned either from
8161 @code{gdb.Architecture.name}
8162 (@pxref{gdbpy_architecture_name,,gdb.Architecture.name}), or from
8163 @code{gdb.architecture_names}
8164 (@pxref{gdb_architecture_names,,gdb.architecture_names}).
8166 The @var{disassembler} will be installed for the architecture named by
8167 @var{architecture}, or if @var{architecture} is @code{None}, then
8168 @var{disassembler} will be installed as a global disassembler for use
8169 by all architectures.
8171 @cindex disassembler in Python, global vs.@: specific
8172 @cindex search order for disassembler in Python
8173 @cindex look up of disassembler in Python
8174 @value{GDBN} only records a single disassembler for each architecture,
8175 and a single global disassembler. Calling
8176 @code{register_disassembler} for an architecture, or for the global
8177 disassembler, will replace any existing disassembler registered for
8178 that @var{architecture} value. The previous disassembler is returned.
8180 If @var{disassembler} is @code{None} then any disassembler currently
8181 registered for @var{architecture} is deregistered and returned.
8183 When @value{GDBN} is looking for a disassembler to use, @value{GDBN}
8184 first looks for an architecture specific disassembler. If none has
8185 been registered then @value{GDBN} looks for a global disassembler (one
8186 registered with @var{architecture} set to @code{None}). Only one
8187 disassembler is called to perform disassembly, so, if there is both an
8188 architecture specific disassembler, and a global disassembler
8189 registered, it is the architecture specific disassembler that will be
8192 @value{GDBN} tracks the architecture specific, and global
8193 disassemblers separately, so it doesn't matter in which order
8194 disassemblers are created or registered; an architecture specific
8195 disassembler, if present, will always be used in preference to a
8196 global disassembler.
8198 You can use the @kbd{maint info python-disassemblers} command
8199 (@pxref{maint info python-disassemblers}) to see which disassemblers
8200 have been registered.
8203 @anchor{builtin_disassemble}
8204 @defun builtin_disassemble (info)
8205 This function calls back into @value{GDBN}'s builtin disassembler to
8206 disassemble the instruction identified by @var{info}, an instance, or
8207 sub-class, of @code{DisassembleInfo}.
8209 When the builtin disassembler needs to read memory the
8210 @code{read_memory} method on @var{info} will be called. By
8211 sub-classing @code{DisassembleInfo} and overriding the
8212 @code{read_memory} method, it is possible to intercept calls to
8213 @code{read_memory} from the builtin disassembler, and to modify the
8216 It is important to understand that, even when
8217 @code{DisassembleInfo.read_memory} raises a @code{gdb.MemoryError}, it
8218 is the internal disassembler itself that reports the memory error to
8219 @value{GDBN}. The reason for this is that the disassembler might
8220 probe memory to see if a byte is readable or not; if the byte can't be
8221 read then the disassembler may choose not to report an error, but
8222 instead to disassemble the bytes that it does have available.
8224 If the builtin disassembler is successful then an instance of
8225 @code{DisassemblerResult} is returned from @code{builtin_disassemble},
8226 alternatively, if something goes wrong, an exception will be raised.
8228 A @code{MemoryError} will be raised if @code{builtin_disassemble} is
8229 unable to read some memory that is required in order to perform
8230 disassembly correctly.
8232 Any exception that is not a @code{MemoryError}, that is raised in a
8233 call to @code{read_memory}, will pass through
8234 @code{builtin_disassemble}, and be visible to the caller.
8236 Finally, there are a few cases where @value{GDBN}'s builtin
8237 disassembler can fail for reasons that are not covered by
8238 @code{MemoryError}. In these cases, a @code{GdbError} will be raised.
8239 The contents of the exception will be a string describing the problem
8240 the disassembler encountered.
8243 Here is an example that registers a global disassembler. The new
8244 disassembler invokes the builtin disassembler, and then adds a
8245 comment, @code{## Comment}, to each line of disassembly output:
8248 class ExampleDisassembler(gdb.disassembler.Disassembler):
8250 super().__init__("ExampleDisassembler")
8252 def __call__(self, info):
8253 result = gdb.disassembler.builtin_disassemble(info)
8254 length = result.length
8255 text = result.string + "\t## Comment"
8256 return gdb.disassembler.DisassemblerResult(length, text)
8258 gdb.disassembler.register_disassembler(ExampleDisassembler())
8261 The following example creates a sub-class of @code{DisassembleInfo} in
8262 order to intercept the @code{read_memory} calls, within
8263 @code{read_memory} any bytes read from memory have the two 4-bit
8264 nibbles swapped around. This isn't a very useful adjustment, but
8265 serves as an example.
8268 class MyInfo(gdb.disassembler.DisassembleInfo):
8269 def __init__(self, info):
8270 super().__init__(info)
8272 def read_memory(self, length, offset):
8273 buffer = super().read_memory(length, offset)
8274 result = bytearray()
8276 v = int.from_bytes(b, 'little')
8277 v = (v << 4) & 0xf0 | (v >> 4)
8279 return memoryview(result)
8281 class NibbleSwapDisassembler(gdb.disassembler.Disassembler):
8283 super().__init__("NibbleSwapDisassembler")
8285 def __call__(self, info):
8287 return gdb.disassembler.builtin_disassemble(info)
8289 gdb.disassembler.register_disassembler(NibbleSwapDisassembler())
8292 @node Missing Debug Info In Python
8293 @subsubsection Missing Debug Info In Python
8294 @cindex python, handle missing debug information
8296 When @value{GDBN} encounters a new objfile (@pxref{Objfiles In
8297 Python}), e.g.@: the primary executable, or any shared libraries used
8298 by the inferior, @value{GDBN} will attempt to load the corresponding
8299 debug information for that objfile. The debug information might be
8300 found within the objfile itself, or within a separate objfile which
8301 @value{GDBN} will automatically locate and load.
8303 Sometimes though, @value{GDBN} might not find any debug information
8304 for an objfile, in this case the debugging experience will be
8307 If @value{GDBN} fails to locate any debug information for a particular
8308 objfile, there is an opportunity for a Python extension to step in. A
8309 Python extension can potentially locate the missing debug information
8310 using some platform- or project-specific steps, and inform
8311 @value{GDBN} of its location. Or a Python extension might provide
8312 some platform- or project-specific advice to the user about how to
8313 obtain the missing debug information.
8315 A missing debug information Python extension consists of a handler
8316 object which has the @code{name} and @code{enabled} attributes, and
8317 implements the @code{__call__} method. When @value{GDBN} encounters
8318 an objfile for which it is unable to find any debug information, it
8319 invokes the @code{__call__} method. Full details of how handlers are
8320 written can be found below.
8322 @subheading The @code{gdb.missing_debug} Module
8324 @value{GDBN} comes with a @code{gdb.missing_debug} module which
8325 contains the following class and global function:
8327 @deftp{class} gdb.missing_debug.MissingDebugHandler
8329 @code{MissingDebugHandler} is a base class from which user-created
8330 handlers can derive, though it is not required that handlers derive
8331 from this class, so long as any user created handler has the
8332 @code{name} and @code{enabled} attributes, and implements the
8333 @code{__call__} method.
8335 @defun MissingDebugHandler.__init__ (name)
8336 The @var{name} is a string used to reference this missing debug
8337 handler within some @value{GDBN} commands. Valid names consist of the
8338 characters @code{[-_a-zA-Z0-9]}, creating a handler with an invalid
8339 name raises a @code{ValueError} exception.
8342 @defun MissingDebugHandler.__call__ (objfile)
8343 Sub-classes must override the @code{__call__} method. The
8344 @var{objfile} argument will be a @code{gdb.Objfile}, this is the
8345 objfile for which @value{GDBN} was unable to find any debug
8348 The return value from the @code{__call__} method indicates what
8349 @value{GDBN} should do next. The possible return values are:
8354 This indicates that this handler could not help with @var{objfile},
8355 @value{GDBN} should call any other registered handlers.
8359 This indicates that this handler has installed the debug information
8360 into a location where @value{GDBN} would normally expect to find it
8361 when looking for separate debug information files (@pxref{Separate
8362 Debug Files}). @value{GDBN} will repeat the normal lookup process,
8363 which should now find the separate debug file.
8365 If @value{GDBN} still doesn't find the separate debug information file
8366 after this second attempt, then the Python missing debug information
8367 handlers are not invoked a second time, this prevents a badly behaved
8368 handler causing @value{GDBN} to get stuck in a loop. @value{GDBN}
8369 will continue without any debug information for @var{objfile}.
8373 This indicates that this handler has done everything that it intends
8374 to do with @var{objfile}, but no separate debug information can be
8375 found. @value{GDBN} will not call any other registered handlers for
8376 @var{objfile}. @value{GDBN} will continue without debugging
8377 information for @var{objfile}.
8381 The returned string should contain a filename. @value{GDBN} will not
8382 call any further registered handlers, and will instead load the debug
8383 information from the file identified by the returned filename.
8386 Invoking the @code{__call__} method from this base class will raise a
8387 @code{NotImplementedError} exception.
8390 @defvar MissingDebugHandler.name
8391 A read-only attribute which is a string, the name of this handler
8392 passed to the @code{__init__} method.
8395 @defvar MissingDebugHandler.enabled
8396 A modifiable attribute containing a boolean; when @code{True}, the
8397 handler is enabled, and will be used by @value{GDBN}. When
8398 @code{False}, the handler has been disabled, and will not be used.
8402 @defun gdb.missing_debug.register_handler (locus, handler, replace=@code{False})
8403 Register a new missing debug handler with @value{GDBN}.
8405 @var{handler} is an instance of a sub-class of
8406 @code{MissingDebugHandler}, or at least an instance of an object that
8407 has the same attributes and methods as @code{MissingDebugHandler}.
8409 @var{locus} specifies to which handler list to prepend @var{handler}.
8410 It can be either a @code{gdb.Progspace} (@pxref{Progspaces In Python})
8411 or @code{None}, in which case the handler is registered globally. The
8412 newly registered @var{handler} will be called before any other handler
8413 from the same locus. Two handlers in the same locus cannot have the
8414 same name, an attempt to add a handler with an already existing name
8415 raises an exception unless @var{replace} is @code{True}, in which case
8416 the old handler is deleted and the new handler is prepended to the
8417 selected handler list.
8419 @value{GDBN} first calls the handlers for the current program space,
8420 and then the globally registered handlers. As soon as a handler
8421 returns a value other than @code{None}, no further handlers are called
8425 @node Missing Objfiles In Python
8426 @subsubsection Missing Objfiles In Python
8427 @cindex python, handle missing objfiles
8429 When @value{GDBN} opens a core file, for example with the
8430 @kbd{core-file} command (@pxref{core-file command}), @value{GDBN} will
8431 attempt to load the corresponding executable and shared libraries.
8432 Often these files can be found on the local machine, but sometimes
8433 these files cannot be found, in which case the debugging experience
8436 If @value{GDBN} fails to locate a particular file then there is an
8437 opportunity for a Python extension to step in. A Python extension can
8438 potentially locate the missing file using some platform- or
8439 project-specific steps, and inform @value{GDBN} of its location. Or a
8440 Python extension might provide some platform- or project-specific
8441 advice to the user about how to obtain the missing file.
8443 A missing-objfile Python extension consists of a handler object which
8444 has the @code{name} and @code{enabled} attributes, and implements the
8445 @code{__call__} method. When @value{GDBN} encounters a situation
8446 where a file cannot be found, but the build-id (@pxref{build ID}) for
8447 the missing file is known, then the @code{__call__} method is invoked
8448 to try and find the file. Full details of how handlers are written
8451 @subheading The @code{gdb.missing_objfile} Module
8453 @value{GDBN} comes with a @code{gdb.missing_objfile} module which
8454 contains the following class and global function:
8456 @deftp{class} gdb.missing_objfile.MissingObjfileHandler
8458 @code{MissingObjfileHandler} is a base class from which user-created
8459 handlers can derive, though it is not required that handlers derive
8460 from this class, so long as any user created handler has the
8461 @code{name} and @code{enabled} attributes, and implements the
8462 @code{__call__} method.
8464 @defun MissingObjfileHandler.__init__ (name)
8465 The @var{name} is a string used to reference this missing-objfile
8466 handler within some @value{GDBN} commands. Valid names consist of the
8467 characters @samp{[-_a-zA-Z0-9]}, creating a handler with an invalid
8468 name raises a @code{ValueError} exception.
8471 @defun MissingObjfileHandler.__call__ (pspace, build_id, filename)
8473 Sub-classes must override the @code{__call__} method. The
8474 @var{pspace} argument will be a @code{gdb.Progspace}
8475 (@pxref{Progspaces In Python}), this is the program space in which
8476 @value{GDBN} is looking for the missing file.
8478 The @var{build_id} argument is a string containing the build-id of the
8479 file that is missing, this will be in the same format as returned by
8480 @code{Objfile.build_id} (@pxref{Objfile.build_id}).
8482 The @var{filename} argument contains the name of the file that
8483 @value{GDBN} is looking for. This information is provided to allow
8484 handlers to generate informative messages for the user. A handler is
8485 not required to place the missing file at this location. There might
8486 already be a file present at this location, but it might not match the
8487 required build-id, in which case @value{GDBN} will have ignored it.
8488 In some limited cases @value{GDBN} might not be able to establish the
8489 @var{filename} of the file it is searching for, in this case
8490 @value{GDBN} will use a string @samp{with build-id @var{build_id}} as a
8493 The return value from the @code{__call__} method indicates what
8494 @value{GDBN} should do next. The possible return values are:
8499 This indicates that this handler could not locate the missing file and
8500 @value{GDBN} should call any other registered handlers.
8504 This indicates that this handler has installed the missing file into a
8505 location where @value{GDBN} would normally expect to find it. The
8506 only location in which @value{GDBN} will look is within the
8507 @file{.build-id} sub-directory within the @var{debug-file-directory}
8508 (@pxref{debug-file-directory}).
8510 @value{GDBN} will repeat the normal lookup process, which should now
8511 find the previously missing file.
8513 If @value{GDBN} still doesn't find file after this second attempt,
8514 then the Python missing-objfile handlers are not invoked a second
8515 time, this prevents a badly behaved handler causing @value{GDBN} to
8516 get stuck in a loop. @value{GDBN} will continue without the missing
8517 file, though this will degrade the debugging experience.
8521 This indicates that this handler has done everything that it intends
8522 to do but the missing file could not be found. @value{GDBN} will not
8523 call any other registered handlers to look for the missing file.
8524 @value{GDBN} will continue without the missing file, though this will
8525 degrade the debugging experience.
8529 The returned string should contain a filename. @value{GDBN} will not
8530 call any further registered handlers, and will instead use the
8531 returned filename as the missing file.
8534 Invoking the @code{__call__} method from this base class will raise a
8535 @code{NotImplementedError} exception.
8538 @defvar MissingObjfileHandler.name
8539 A read-only attribute which is a string, the name of this handler
8540 passed to the @code{__init__} method.
8543 @defvar MissingObjfileHandler.enabled
8544 A modifiable attribute containing a boolean; when @code{True}, the
8545 handler is enabled, and will be used by @value{GDBN}. When
8546 @code{False}, the handler has been disabled, and will not be used.
8550 @defun gdb.missing_objfile.register_handler (locus, handler, replace=@code{False})
8551 Register a new missing-objfile handler with @value{GDBN}.
8553 @var{handler} is an instance of a sub-class of
8554 @code{MissingObjfileHandler}, or at least an instance of an object that
8555 has the same attributes and methods as @code{MissingObjfileHandler}.
8557 @var{locus} specifies to which handler list to prepend @var{handler}.
8558 It can be either a @code{gdb.Progspace} (@pxref{Progspaces In Python})
8559 or @code{None}, in which case the handler is registered globally. The
8560 newly registered @var{handler} will be called before any other handler
8561 from the same locus. Two handlers in the same locus cannot have the
8562 same name, an attempt to add a handler with an already existing name
8563 raises an exception unless @var{replace} is @code{True}, in which case
8564 the old handler is deleted and the new handler is prepended to the
8565 selected handler list.
8567 @value{GDBN} first calls the handlers for the current program space,
8568 and then the globally registered handlers. As soon as a handler
8569 returns a value other than @code{None}, no further handlers are
8573 @subheading Managing Missing-Objfile Handlers
8575 @value{GDBN} defines the following commands to manage registered
8576 missing-objfile handlers:
8580 @kindex info missing-objfile-handlers
8581 @item info missing-objfile-handlers @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
8582 Lists all registered missing-objfile handlers. Arguments @var{locus}
8583 and @var{name-regexp} are both optional and can be used to filter
8584 which handlers are listed.
8586 The @var{locus} argument should be either @kbd{global},
8587 @kbd{progspace}, or the name of an object file. Only handlers
8588 registered for the specified locus will be listed.
8590 The @var{name-regexp} is a regular expression used to match against
8593 @kindex disable missing-objfile-handler
8594 @item disable missing-objfile-handler @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
8595 The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
8596 missing-objfile-handlers} above, but instead of listing the matching
8597 handlers, all of the matching handlers are disabled. The
8598 @code{enabled} field of each matching handler is set to @code{False}.
8600 @kindex enable missing-objfile-handler
8601 @item enable missing-objfile-handler @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
8602 The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
8603 missing-objfile-handlers} above, but instead of listing the matching
8604 handlers, all of the matching handlers are enabled. The
8605 @code{enabled} field of each matching handler is set to @code{True}.
8608 @node Python Auto-loading
8609 @subsection Python Auto-loading
8610 @cindex Python auto-loading
8612 When a new object file is read (for example, due to the @code{file}
8613 command, or because the inferior has loaded a shared library),
8614 @value{GDBN} will look for Python support scripts in several ways:
8615 @file{@var{objfile}-gdb.py} and @code{.debug_gdb_scripts} section.
8616 @xref{Auto-loading extensions}.
8618 The auto-loading feature is useful for supplying application-specific
8619 debugging commands and scripts.
8621 Auto-loading can be enabled or disabled,
8622 and the list of auto-loaded scripts can be printed.
8625 @anchor{set auto-load python-scripts}
8626 @kindex set auto-load python-scripts
8627 @item set auto-load python-scripts [on|off]
8628 Enable or disable the auto-loading of Python scripts.
8630 @anchor{show auto-load python-scripts}
8631 @kindex show auto-load python-scripts
8632 @item show auto-load python-scripts
8633 Show whether auto-loading of Python scripts is enabled or disabled.
8635 @anchor{info auto-load python-scripts}
8636 @kindex info auto-load python-scripts
8637 @cindex print list of auto-loaded Python scripts
8638 @item info auto-load python-scripts [@var{regexp}]
8639 Print the list of all Python scripts that @value{GDBN} auto-loaded.
8641 Also printed is the list of Python scripts that were mentioned in
8642 the @code{.debug_gdb_scripts} section and were either not found
8643 (@pxref{dotdebug_gdb_scripts section}) or were not auto-loaded due to
8644 @code{auto-load safe-path} rejection (@pxref{Auto-loading}).
8645 This is useful because their names are not printed when @value{GDBN}
8646 tries to load them and fails. There may be many of them, and printing
8647 an error message for each one is problematic.
8649 If @var{regexp} is supplied only Python scripts with matching names are printed.
8654 (gdb) info auto-load python-scripts
8656 Yes py-section-script.py
8657 full name: /tmp/py-section-script.py
8658 No my-foo-pretty-printers.py
8662 When reading an auto-loaded file or script, @value{GDBN} sets the
8663 @dfn{current objfile}. This is available via the @code{gdb.current_objfile}
8664 function (@pxref{Objfiles In Python}). This can be useful for
8665 registering objfile-specific pretty-printers and frame-filters.
8667 @node Python modules
8668 @subsection Python modules
8669 @cindex python modules
8671 @value{GDBN} comes with several modules to assist writing Python code.
8674 * gdb.printing:: Building and registering pretty-printers.
8675 * gdb.types:: Utilities for working with types.
8676 * gdb.prompt:: Utilities for prompt value substitution.
8677 * gdb.ptwrite:: Utilities for PTWRITE filter registration.
8681 @subsubsection gdb.printing
8682 @cindex gdb.printing
8684 This module provides a collection of utilities for working with
8688 @item PrettyPrinter (@var{name}, @var{subprinters}=None)
8689 This class specifies the API that makes @samp{info pretty-printer},
8690 @samp{enable pretty-printer} and @samp{disable pretty-printer} work.
8691 Pretty-printers should generally inherit from this class.
8693 @item SubPrettyPrinter (@var{name})
8694 For printers that handle multiple types, this class specifies the
8695 corresponding API for the subprinters.
8697 @item RegexpCollectionPrettyPrinter (@var{name})
8698 Utility class for handling multiple printers, all recognized via
8699 regular expressions.
8700 @xref{Writing a Pretty-Printer}, for an example.
8702 @item FlagEnumerationPrinter (@var{name})
8703 A pretty-printer which handles printing of @code{enum} values. Unlike
8704 @value{GDBN}'s built-in @code{enum} printing, this printer attempts to
8705 work properly when there is some overlap between the enumeration
8706 constants. The argument @var{name} is the name of the printer and
8707 also the name of the @code{enum} type to look up.
8709 @item register_pretty_printer (@var{obj}, @var{printer}, @var{replace}=False)
8710 Register @var{printer} with the pretty-printer list of @var{obj}.
8711 If @var{replace} is @code{True} then any existing copy of the printer
8712 is replaced. Otherwise a @code{RuntimeError} exception is raised
8713 if a printer with the same name already exists.
8717 @subsubsection gdb.types
8720 This module provides a collection of utilities for working with
8721 @code{gdb.Type} objects.
8724 @item get_basic_type (@var{type})
8725 Return @var{type} with const and volatile qualifiers stripped,
8726 and with typedefs and C@t{++} references converted to the underlying type.
8731 typedef const int const_int;
8733 const_int& foo_ref (foo);
8734 int main () @{ return 0; @}
8741 (gdb) python import gdb.types
8742 (gdb) python foo_ref = gdb.parse_and_eval("foo_ref")
8743 (gdb) python print gdb.types.get_basic_type(foo_ref.type)
8747 @item has_field (@var{type}, @var{field})
8748 Return @code{True} if @var{type}, assumed to be a type with fields
8749 (e.g., a structure or union), has field @var{field}.
8751 @item make_enum_dict (@var{enum_type})
8752 Return a Python @code{dictionary} type produced from @var{enum_type}.
8754 @item deep_items (@var{type})
8755 Returns a Python iterator similar to the standard
8756 @code{gdb.Type.iteritems} method, except that the iterator returned
8757 by @code{deep_items} will recursively traverse anonymous struct or
8758 union fields. For example:
8772 Then in @value{GDBN}:
8774 (@value{GDBP}) python import gdb.types
8775 (@value{GDBP}) python struct_a = gdb.lookup_type("struct A")
8776 (@value{GDBP}) python print struct_a.keys ()
8778 (@value{GDBP}) python print [k for k,v in gdb.types.deep_items(struct_a)]
8779 @{['a', 'b0', 'b1']@}
8782 @item get_type_recognizers ()
8783 Return a list of the enabled type recognizers for the current context.
8784 This is called by @value{GDBN} during the type-printing process
8785 (@pxref{Type Printing API}).
8787 @item apply_type_recognizers (recognizers, type_obj)
8788 Apply the type recognizers, @var{recognizers}, to the type object
8789 @var{type_obj}. If any recognizer returns a string, return that
8790 string. Otherwise, return @code{None}. This is called by
8791 @value{GDBN} during the type-printing process (@pxref{Type Printing
8794 @item register_type_printer (locus, printer)
8795 This is a convenience function to register a type printer
8796 @var{printer}. The printer must implement the type printer protocol.
8797 The @var{locus} argument is either a @code{gdb.Objfile}, in which case
8798 the printer is registered with that objfile; a @code{gdb.Progspace},
8799 in which case the printer is registered with that progspace; or
8800 @code{None}, in which case the printer is registered globally.
8803 This is a base class that implements the type printer protocol. Type
8804 printers are encouraged, but not required, to derive from this class.
8805 It defines a constructor:
8807 @defmethod TypePrinter __init__ (self, name)
8808 Initialize the type printer with the given name. The new printer
8809 starts in the enabled state.
8815 @subsubsection gdb.prompt
8818 This module provides a method for prompt value-substitution.
8821 @item substitute_prompt (@var{string})
8822 Return @var{string} with escape sequences substituted by values. Some
8823 escape sequences take arguments. You can specify arguments inside
8824 ``@{@}'' immediately following the escape sequence.
8826 The escape sequences you can pass to this function are:
8830 Substitute a backslash.
8832 Substitute an ESC character.
8834 Substitute the selected frame; an argument names a frame parameter.
8836 Substitute a newline.
8838 Substitute a parameter's value; the argument names the parameter.
8840 Substitute a carriage return.
8842 Substitute the selected thread; an argument names a thread parameter.
8844 Substitute the version of GDB.
8846 Substitute the current working directory.
8848 Begin a sequence of non-printing characters. These sequences are
8849 typically used with the ESC character, and are not counted in the string
8850 length. Example: ``\[\e[0;34m\](gdb)\[\e[0m\]'' will return a
8851 blue-colored ``(gdb)'' prompt where the length is five.
8853 End a sequence of non-printing characters.
8859 substitute_prompt ("frame: \f, args: \p@{print frame-arguments@}")
8862 @exdent will return the string:
8865 "frame: main, args: scalars"
8870 @subsubsection gdb.ptwrite
8873 This module provides additional functionality for recording programs that
8874 make use of the @code{PTWRITE} instruction. @code{PTWRITE} is a x86
8875 instruction that allows to write values into the Intel Processor Trace
8876 (@pxref{Process Record and Replay}).
8877 The @value{NGCC} intrinsics for it are:
8879 void _ptwrite32 (unsigned int a)
8880 void _ptwrite64 (unsigned __int64 a)
8883 If an inferior uses the instruction, @value{GDBN} by default inserts the
8884 raw payload value as auxiliary information into the execution history.
8885 Auxiliary information is by default printed during
8886 @code{record instruction-history}, @code{record function-call-history},
8887 and all stepping commands, and is accessible in Python as a
8888 @code{RecordAuxiliary} object (@pxref{Recordings In Python}).
8890 @exdent Sample program:
8893 #include <immintrin.h>
8896 ptwrite64 (unsigned long long value)
8907 return 0; /* break here. */
8913 @exdent @value{GDBN} output after recording the sample program in pt format:
8916 (gdb) record instruction-history 12,14
8917 12 0x0040074c <ptwrite64+16>: ptwrite %rbx
8919 14 0x00400751 <ptwrite64+21>: mov -0x8(%rbp),%rbx
8920 (gdb) record function-call-history
8928 The @code{gdb.ptwrite} module allows customizing the default output of
8929 @code{PTWRITE} auxiliary information. A custom Python function can be
8930 registered as the @code{PTWRITE} filter function. This function will be
8931 called with the @code{PTWRITE} payload and PC as arguments during trace
8932 decoding. The function can return a string, which will be printed by
8933 @value{GDBN} during the aforementioned commands, or @code{None}, resulting
8934 in no output. To register such a filter function, the user needs to
8935 provide a filter factory function, which returns a new filter function
8936 object to be called by @value{GDBN}.
8938 @findex gdb.ptwrite.register_filter_factory
8939 @defun register_filter_factory (filter_factory)
8940 Used to register the @code{PTWRITE} filter factory. This filter factory can
8941 be any callable object that accepts one argument, the current thread as
8942 a @code{gdb.InferiorThread}.
8943 It can return None or a callable. This callable is the @code{PTWRITE} filter
8944 function for the specified thread. If @code{None} is returned by the factory
8945 function, the default auxiliary information will be printed.
8948 @findex gdb.ptwrite.get_filter
8949 @defun get_filter ()
8950 Return the currently active @code{PTWRITE} filter function.
8957 (gdb) python-interactive
8958 >>> class my_filter():
8959 ... def __init__(self):
8961 ... def __call__(self, payload, ip):
8963 ... return f"counter: @{self.var@}, ip: @{ip:#x@}"
8965 >>> def my_filter_factory(thread):
8966 ... if thread.global_num == 1:
8967 ... return my_filter()
8971 >>> import gdb.ptwrite
8972 >>> gdb.ptwrite.register_filter_factory(my_filter_factory)
8977 (gdb) record function-call-history 59,64
8978 59 pthread_create@@GLIBC_2.2.5
8981 62 ptwrite64(unsigned long)
8982 [counter: 1, ip: 0x401156]
8984 64 ptwrite32(unsigned int)
8985 [counter: 2, ip: 0x40116c]
8990 * 1 Thread 0x7ffff7fd8740 (LWP 25796) "ptw_threads" task ()
8991 at bin/ptwrite/ptw_threads.c:45
8992 2 Thread 0x7ffff6eb8700 (LWP 25797) "ptw_threads" task ()
8993 at bin/ptwrite/ptw_threads.c:45
8998 [Switching to thread 2 (Thread 0x7ffff6eb8700 (LWP 25797))]
8999 #0 task (arg=0x0) at ptwrite_threads.c:45
9004 (gdb) record function-call-history 10,14
9007 12 ptwrite64(unsigned long)
9010 14 ptwrite32(unsigned int)
9015 This @value{GDBN} feature is dependent on hardware and operating system
9016 support and requires the Intel Processor Trace decoder library in version