1 @c Copyright (C) 2008--2024 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 * Architectures In Python:: Python representation of architectures.
229 * Registers In Python:: Python representation of registers.
230 * Connections In Python:: Python representation of connections.
231 * TUI Windows In Python:: Implementing new TUI windows.
232 * Disassembly In Python:: Instruction Disassembly In Python
233 * Missing Debug Info In Python:: Handle missing debug info from Python.
237 @subsubsection Basic Python
239 @cindex python stdout
240 @cindex python pagination
241 At startup, @value{GDBN} overrides Python's @code{sys.stdout} and
242 @code{sys.stderr} to print using @value{GDBN}'s output-paging streams.
243 A Python program which outputs to one of these streams may have its
244 output interrupted by the user (@pxref{Screen Size}). In this
245 situation, a Python @code{KeyboardInterrupt} exception is thrown.
247 Some care must be taken when writing Python code to run in
248 @value{GDBN}. Two things worth noting in particular:
252 @value{GDBN} installs handlers for @code{SIGCHLD} and @code{SIGINT}.
253 Python code must not override these, or even change the options using
254 @code{sigaction}. If your program changes the handling of these
255 signals, @value{GDBN} will most likely stop working correctly. Note
256 that it is unfortunately common for GUI toolkits to install a
257 @code{SIGCHLD} handler. When creating a new Python thread, you can
258 use @code{gdb.block_signals} or @code{gdb.Thread} to handle this
259 correctly; see @ref{Threading in GDB}.
262 @value{GDBN} takes care to mark its internal file descriptors as
263 close-on-exec. However, this cannot be done in a thread-safe way on
264 all platforms. Your Python programs should be aware of this and
265 should both create new file descriptors with the close-on-exec flag
266 set and arrange to close unneeded file descriptors before starting a
270 @cindex python functions
271 @cindex python module
273 @value{GDBN} introduces a new Python module, named @code{gdb}. All
274 methods and classes added by @value{GDBN} are placed in this module.
275 @value{GDBN} automatically @code{import}s the @code{gdb} module for
276 use in all scripts evaluated by the @code{python} command.
278 Some types of the @code{gdb} module come with a textual representation
279 (accessible through the @code{repr} or @code{str} functions). These are
280 offered for debugging purposes only, expect them to change over time.
282 @defvar gdb.PYTHONDIR
283 A string containing the python directory (@pxref{Python}).
286 @defun gdb.execute (command @r{[}, from_tty @r{[}, to_string@r{]]})
287 Evaluate @var{command}, a string, as a @value{GDBN} CLI command.
288 If a GDB exception happens while @var{command} runs, it is
289 translated as described in @ref{Exception Handling,,Exception Handling}.
291 The @var{from_tty} flag specifies whether @value{GDBN} ought to consider this
292 command as having originated from the user invoking it interactively.
293 It must be a boolean value. If omitted, it defaults to @code{False}.
295 By default, any output produced by @var{command} is sent to
296 @value{GDBN}'s standard output (and to the log output if logging is
297 turned on). If the @var{to_string} parameter is
298 @code{True}, then output will be collected by @code{gdb.execute} and
299 returned as a string. The default is @code{False}, in which case the
300 return value is @code{None}. If @var{to_string} is @code{True}, the
301 @value{GDBN} virtual terminal will be temporarily set to unlimited width
302 and height, and its pagination will be disabled; @pxref{Screen Size}.
305 @defun gdb.breakpoints ()
306 Return a sequence holding all of @value{GDBN}'s breakpoints.
307 @xref{Breakpoints In Python}, for more information. In @value{GDBN}
308 version 7.11 and earlier, this function returned @code{None} if there
309 were no breakpoints. This peculiarity was subsequently fixed, and now
310 @code{gdb.breakpoints} returns an empty sequence in this case.
313 @defun gdb.rbreak (regex @r{[}, minsyms @r{[}, throttle, @r{[}, symtabs @r{]]]})
314 Return a Python list holding a collection of newly set
315 @code{gdb.Breakpoint} objects matching function names defined by the
316 @var{regex} pattern. If the @var{minsyms} keyword is @code{True}, all
317 system functions (those not explicitly defined in the inferior) will
318 also be included in the match. The @var{throttle} keyword takes an
319 integer that defines the maximum number of pattern matches for
320 functions matched by the @var{regex} pattern. If the number of
321 matches exceeds the integer value of @var{throttle}, a
322 @code{RuntimeError} will be raised and no breakpoints will be created.
323 If @var{throttle} is not defined then there is no imposed limit on the
324 maximum number of matches and breakpoints to be created. The
325 @var{symtabs} keyword takes a Python iterable that yields a collection
326 of @code{gdb.Symtab} objects and will restrict the search to those
327 functions only contained within the @code{gdb.Symtab} objects.
330 @defun gdb.parameter (parameter)
331 Return the value of a @value{GDBN} @var{parameter} given by its name,
332 a string; the parameter name string may contain spaces if the parameter has a
333 multi-part name. For example, @samp{print object} is a valid
336 If the named parameter does not exist, this function throws a
337 @code{gdb.error} (@pxref{Exception Handling}). Otherwise, the
338 parameter's value is converted to a Python value of the appropriate
342 @defun gdb.set_parameter (name, value)
343 Sets the gdb parameter @var{name} to @var{value}. As with
344 @code{gdb.parameter}, the parameter name string may contain spaces if
345 the parameter has a multi-part name.
348 @defun gdb.with_parameter (name, value)
349 Create a Python context manager (for use with the Python
350 @command{with} statement) that temporarily sets the gdb parameter
351 @var{name} to @var{value}. On exit from the context, the previous
352 value will be restored.
354 This uses @code{gdb.parameter} in its implementation, so it can throw
355 the same exceptions as that function.
357 For example, it's sometimes useful to evaluate some Python code with a
358 particular gdb language:
361 with gdb.with_parameter('language', 'pascal'):
362 ... language-specific operations
366 @defun gdb.history (number)
367 Return a value from @value{GDBN}'s value history (@pxref{Value
368 History}). The @var{number} argument indicates which history element to return.
369 If @var{number} is negative, then @value{GDBN} will take its absolute value
370 and count backward from the last element (i.e., the most recent element) to
371 find the value to return. If @var{number} is zero, then @value{GDBN} will
372 return the most recent element. If the element specified by @var{number}
373 doesn't exist in the value history, a @code{gdb.error} exception will be
376 If no exception is raised, the return value is always an instance of
377 @code{gdb.Value} (@pxref{Values From Inferior}).
380 @defun gdb.add_history (value)
381 Takes @var{value}, an instance of @code{gdb.Value} (@pxref{Values From
382 Inferior}), and appends the value this object represents to
383 @value{GDBN}'s value history (@pxref{Value History}), and return an
384 integer, its history number. If @var{value} is not a
385 @code{gdb.Value}, it is is converted using the @code{gdb.Value}
386 constructor. If @var{value} can't be converted to a @code{gdb.Value}
387 then a @code{TypeError} is raised.
389 When a command implemented in Python prints a single @code{gdb.Value}
390 as its result, then placing the value into the history will allow the
391 user convenient access to those values via CLI history facilities.
394 @defun gdb.history_count ()
395 Return an integer indicating the number of values in @value{GDBN}'s
396 value history (@pxref{Value History}).
399 @defun gdb.convenience_variable (name)
400 Return the value of the convenience variable (@pxref{Convenience
401 Vars}) named @var{name}. @var{name} must be a string. The name
402 should not include the @samp{$} that is used to mark a convenience
403 variable in an expression. If the convenience variable does not
404 exist, then @code{None} is returned.
407 @defun gdb.set_convenience_variable (name, value)
408 Set the value of the convenience variable (@pxref{Convenience Vars})
409 named @var{name}. @var{name} must be a string. The name should not
410 include the @samp{$} that is used to mark a convenience variable in an
411 expression. If @var{value} is @code{None}, then the convenience
412 variable is removed. Otherwise, if @var{value} is not a
413 @code{gdb.Value} (@pxref{Values From Inferior}), it is is converted
414 using the @code{gdb.Value} constructor.
417 @defun gdb.parse_and_eval (expression @r{[}, global_context@r{]})
418 Parse @var{expression}, which must be a string, as an expression in
419 the current language, evaluate it, and return the result as a
422 @var{global_context}, if provided, is a boolean indicating whether the
423 parsing should be done in the global context. The default is
424 @samp{False}, meaning that the current frame or current static context
427 This function can be useful when implementing a new command
428 (@pxref{CLI Commands In Python}, @pxref{GDB/MI Commands In Python}),
429 as it provides a way to parse the
430 command's argument as an expression. It is also useful simply to
434 @defun gdb.find_pc_line (pc)
435 Return the @code{gdb.Symtab_and_line} object corresponding to the
436 @var{pc} value. @xref{Symbol Tables In Python}. If an invalid
437 value of @var{pc} is passed as an argument, then the @code{symtab} and
438 @code{line} attributes of the returned @code{gdb.Symtab_and_line} object
439 will be @code{None} and 0 respectively. This is identical to
440 @code{gdb.current_progspace().find_pc_line(pc)} and is included for
441 historical compatibility.
444 @defun gdb.write (string @r{[}, stream@r{]})
445 Print a string to @value{GDBN}'s paginated output stream. The
446 optional @var{stream} determines the stream to print to. The default
447 stream is @value{GDBN}'s standard output stream. Possible stream
454 @value{GDBN}'s standard output stream.
459 @value{GDBN}'s standard error stream.
464 @value{GDBN}'s log stream (@pxref{Logging Output}).
467 Writing to @code{sys.stdout} or @code{sys.stderr} will automatically
468 call this function and will automatically direct the output to the
472 @defun gdb.flush (@r{[}, stream@r{]})
473 Flush the buffer of a @value{GDBN} paginated stream so that the
474 contents are displayed immediately. @value{GDBN} will flush the
475 contents of a stream automatically when it encounters a newline in the
476 buffer. The optional @var{stream} determines the stream to flush. The
477 default stream is @value{GDBN}'s standard output stream. Possible
484 @value{GDBN}'s standard output stream.
489 @value{GDBN}'s standard error stream.
494 @value{GDBN}'s log stream (@pxref{Logging Output}).
498 Flushing @code{sys.stdout} or @code{sys.stderr} will automatically
499 call this function for the relevant stream.
502 @defun gdb.target_charset ()
503 Return the name of the current target character set (@pxref{Character
504 Sets}). This differs from @code{gdb.parameter('target-charset')} in
505 that @samp{auto} is never returned.
508 @defun gdb.target_wide_charset ()
509 Return the name of the current target wide character set
510 (@pxref{Character Sets}). This differs from
511 @code{gdb.parameter('target-wide-charset')} in that @samp{auto} is
515 @defun gdb.host_charset ()
516 Return a string, the name of the current host character set
517 (@pxref{Character Sets}). This differs from
518 @code{gdb.parameter('host-charset')} in that @samp{auto} is never
522 @defun gdb.solib_name (address)
523 Return the name of the shared library holding the given @var{address}
524 as a string, or @code{None}. This is identical to
525 @code{gdb.current_progspace().solib_name(address)} and is included for
526 historical compatibility.
529 @defun gdb.decode_line (@r{[}expression@r{]})
530 Return locations of the line specified by @var{expression}, or of the
531 current line if no argument was given. This function returns a Python
532 tuple containing two elements. The first element contains a string
533 holding any unparsed section of @var{expression} (or @code{None} if
534 the expression has been fully parsed). The second element contains
535 either @code{None} or another tuple that contains all the locations
536 that match the expression represented as @code{gdb.Symtab_and_line}
537 objects (@pxref{Symbol Tables In Python}). If @var{expression} is
538 provided, it is decoded the way that @value{GDBN}'s inbuilt
539 @code{break} or @code{edit} commands do (@pxref{Location
543 @defun gdb.prompt_hook (current_prompt)
546 If @var{prompt_hook} is callable, @value{GDBN} will call the method
547 assigned to this operation before a prompt is displayed by
550 The parameter @code{current_prompt} contains the current @value{GDBN}
551 prompt. This method must return a Python string, or @code{None}. If
552 a string is returned, the @value{GDBN} prompt will be set to that
553 string. If @code{None} is returned, @value{GDBN} will continue to use
556 Some prompts cannot be substituted in @value{GDBN}. Secondary prompts
557 such as those used by readline for command input, and annotation
558 related prompts are prohibited from being changed.
561 @anchor{gdb_architecture_names}
562 @defun gdb.architecture_names ()
563 Return a list containing all of the architecture names that the
564 current build of @value{GDBN} supports. Each architecture name is a
565 string. The names returned in this list are the same names as are
566 returned from @code{gdb.Architecture.name}
567 (@pxref{gdbpy_architecture_name,,Architecture.name}).
570 @anchor{gdbpy_connections}
571 @defun gdb.connections
572 Return a list of @code{gdb.TargetConnection} objects, one for each
573 currently active connection (@pxref{Connections In Python}). The
574 connection objects are in no particular order in the returned list.
577 @defun gdb.format_address (address @r{[}, progspace, architecture@r{]})
578 Return a string in the format @samp{@var{addr}
579 <@var{symbol}+@var{offset}>}, where @var{addr} is @var{address}
580 formatted in hexadecimal, @var{symbol} is the symbol whose address is
581 the nearest to @var{address} and below it in memory, and @var{offset}
582 is the offset from @var{symbol} to @var{address} in decimal.
584 If no suitable @var{symbol} was found, then the
585 <@var{symbol}+@var{offset}> part is not included in the returned
586 string, instead the returned string will just contain the
587 @var{address} formatted as hexadecimal. How far @value{GDBN} looks
588 back for a suitable symbol can be controlled with @kbd{set print
589 max-symbolic-offset} (@pxref{Print Settings}).
591 Additionally, the returned string can include file name and line
592 number information when @kbd{set print symbol-filename on}
593 (@pxref{Print Settings}), in this case the format of the returned
594 string is @samp{@var{addr} <@var{symbol}+@var{offset}> at
595 @var{filename}:@var{line-number}}.
598 The @var{progspace} is the gdb.Progspace in which @var{symbol} is
599 looked up, and @var{architecture} is used when formatting @var{addr},
600 e.g.@: in order to determine the size of an address in bytes.
602 If neither @var{progspace} or @var{architecture} are passed, then by
603 default @value{GDBN} will use the program space and architecture of
604 the currently selected inferior, thus, the following two calls are
608 gdb.format_address(address)
609 gdb.format_address(address,
610 gdb.selected_inferior().progspace,
611 gdb.selected_inferior().architecture())
614 It is not valid to only pass one of @var{progspace} or
615 @var{architecture}, either they must both be provided, or neither must
616 be provided (and the defaults will be used).
618 This method uses the same mechanism for formatting address, symbol,
619 and offset information as core @value{GDBN} does in commands such as
622 Here are some examples of the possible string formats:
626 0x00001042 <symbol+16>
627 0x00001042 <symbol+16 at file.c:123>
631 @defun gdb.current_language ()
632 Return the name of the current language as a string. Unlike
633 @code{gdb.parameter('language')}, this function will never return
634 @samp{auto}. If a @code{gdb.Frame} object is available (@pxref{Frames
635 In Python}), the @code{language} method might be preferable in some
636 cases, as that is not affected by the user's language setting.
639 @node Threading in GDB
640 @subsubsection Threading in GDB
642 @value{GDBN} is not thread-safe. If your Python program uses multiple
643 threads, you must be careful to only call @value{GDBN}-specific
644 functions in the @value{GDBN} thread. @value{GDBN} provides some
645 functions to help with this.
647 @defun gdb.block_signals ()
648 As mentioned earlier (@pxref{Basic Python}), certain signals must be
649 delivered to the @value{GDBN} main thread. The @code{block_signals}
650 function returns a context manager that will block these signals on
651 entry. This can be used when starting a new thread to ensure that the
652 signals are blocked there, like:
655 with gdb.block_signals():
660 @deftp {class} gdb.Thread
661 This is a subclass of Python's @code{threading.Thread} class. It
662 overrides the @code{start} method to call @code{block_signals}, making
663 this an easy-to-use drop-in replacement for creating threads that will
664 work well in @value{GDBN}.
667 @defun gdb.interrupt ()
668 This causes @value{GDBN} to react as if the user had typed a control-C
669 character at the terminal. That is, if the inferior is running, it is
670 interrupted; if a @value{GDBN} command is executing, it is stopped;
671 and if a Python command is running, @code{KeyboardInterrupt} will be
674 Unlike most Python APIs in @value{GDBN}, @code{interrupt} is
678 @defun gdb.post_event (event)
679 Put @var{event}, a callable object taking no arguments, into
680 @value{GDBN}'s internal event queue. This callable will be invoked at
681 some later point, during @value{GDBN}'s event processing. Events
682 posted using @code{post_event} will be run in the order in which they
683 were posted; however, there is no way to know when they will be
684 processed relative to other events inside @value{GDBN}.
686 Unlike most Python APIs in @value{GDBN}, @code{post_event} is
687 thread-safe. For example:
690 (@value{GDBP}) python
694 > def __init__(self, message):
695 > self.message = message;
696 > def __call__(self):
697 > gdb.write(self.message)
699 >class MyThread1 (threading.Thread):
701 > gdb.post_event(Writer("Hello "))
703 >class MyThread2 (threading.Thread):
705 > gdb.post_event(Writer("World\n"))
710 (@value{GDBP}) Hello World
715 @node Exception Handling
716 @subsubsection Exception Handling
717 @cindex python exceptions
718 @cindex exceptions, python
720 When executing the @code{python} command, Python exceptions
721 uncaught within the Python code are translated to calls to
722 @value{GDBN} error-reporting mechanism. If the command that called
723 @code{python} does not handle the error, @value{GDBN} will
724 terminate it and print an error message. Exactly what will be printed
725 depends on @code{set python print-stack} (@pxref{Python Commands}).
729 (@value{GDBP}) python print foo
730 Traceback (most recent call last):
731 File "<string>", line 1, in <module>
732 NameError: name 'foo' is not defined
735 @value{GDBN} errors that happen in @value{GDBN} commands invoked by
736 Python code are converted to Python exceptions. The type of the
737 Python exception depends on the error.
741 This is the base class for most exceptions generated by @value{GDBN}.
742 It is derived from @code{RuntimeError}, for compatibility with earlier
743 versions of @value{GDBN}.
745 If an error occurring in @value{GDBN} does not fit into some more
746 specific category, then the generated exception will have this type.
748 @item gdb.MemoryError
749 This is a subclass of @code{gdb.error} which is thrown when an
750 operation tried to access invalid memory in the inferior.
752 @item KeyboardInterrupt
753 User interrupt (via @kbd{C-c} or by typing @kbd{q} at a pagination
754 prompt) is translated to a Python @code{KeyboardInterrupt} exception.
757 In all cases, your exception handler will see the @value{GDBN} error
758 message as its value and the Python call stack backtrace at the Python
759 statement closest to where the @value{GDBN} error occurred as the
763 When implementing @value{GDBN} commands in Python via
764 @code{gdb.Command}, or functions via @code{gdb.Function}, it is useful
765 to be able to throw an exception that doesn't cause a traceback to be
766 printed. For example, the user may have invoked the command
767 incorrectly. @value{GDBN} provides a special exception class that can
768 be used for this purpose.
772 When thrown from a command or function, this exception will cause the
773 command or function to fail, but the Python stack will not be
774 displayed. @value{GDBN} does not throw this exception itself, but
775 rather recognizes it when thrown from user Python code. Example:
779 >class HelloWorld (gdb.Command):
780 > """Greet the whole world."""
781 > def __init__ (self):
782 > super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
783 > def invoke (self, args, from_tty):
784 > argv = gdb.string_to_argv (args)
785 > if len (argv) != 0:
786 > raise gdb.GdbError ("hello-world takes no arguments")
787 > print ("Hello, World!")
791 hello-world takes no arguments
795 @node Values From Inferior
796 @subsubsection Values From Inferior
797 @cindex values from inferior, with Python
798 @cindex python, working with values from inferior
800 @cindex @code{gdb.Value}
801 @value{GDBN} provides values it obtains from the inferior program in
802 an object of type @code{gdb.Value}. @value{GDBN} uses this object
803 for its internal bookkeeping of the inferior's values, and for
804 fetching values when necessary.
806 Inferior values that are simple scalars can be used directly in
807 Python expressions that are valid for the value's data type. Here's
808 an example for an integer or floating-point value @code{some_val}:
815 As result of this, @code{bar} will also be a @code{gdb.Value} object
816 whose values are of the same type as those of @code{some_val}. Valid
817 Python operations can also be performed on @code{gdb.Value} objects
818 representing a @code{struct} or @code{class} object. For such cases,
819 the overloaded operator (if present), is used to perform the operation.
820 For example, if @code{val1} and @code{val2} are @code{gdb.Value} objects
821 representing instances of a @code{class} which overloads the @code{+}
822 operator, then one can use the @code{+} operator in their Python script
830 The result of the operation @code{val3} is also a @code{gdb.Value}
831 object corresponding to the value returned by the overloaded @code{+}
832 operator. In general, overloaded operators are invoked for the
833 following operations: @code{+} (binary addition), @code{-} (binary
834 subtraction), @code{*} (multiplication), @code{/}, @code{%}, @code{<<},
835 @code{>>}, @code{|}, @code{&}, @code{^}.
837 Inferior values that are structures or instances of some class can
838 be accessed using the Python @dfn{dictionary syntax}. For example, if
839 @code{some_val} is a @code{gdb.Value} instance holding a structure, you
840 can access its @code{foo} element with:
843 bar = some_val['foo']
846 @cindex getting structure elements using gdb.Field objects as subscripts
847 Again, @code{bar} will also be a @code{gdb.Value} object. Structure
848 elements can also be accessed by using @code{gdb.Field} objects as
849 subscripts (@pxref{Types In Python}, for more information on
850 @code{gdb.Field} objects). For example, if @code{foo_field} is a
851 @code{gdb.Field} object corresponding to element @code{foo} of the above
852 structure, then @code{bar} can also be accessed as follows:
855 bar = some_val[foo_field]
858 If a @code{gdb.Value} has array or pointer type, an integer index can
859 be used to access elements.
862 result = some_array[23]
865 A @code{gdb.Value} that represents a function can be executed via
866 inferior function call. Any arguments provided to the call must match
867 the function's prototype, and must be provided in the order specified
870 For example, @code{some_val} is a @code{gdb.Value} instance
871 representing a function that takes two integers as arguments. To
872 execute this function, call it like so:
875 result = some_val (10,20)
878 Any values returned from a function call will be stored as a
881 The following attributes are provided:
883 @defvar Value.address
884 If this object is addressable, this read-only attribute holds a
885 @code{gdb.Value} object representing the address. Otherwise,
886 this attribute holds @code{None}.
889 @cindex optimized out value in Python
890 @defvar Value.is_optimized_out
891 This read-only boolean attribute is true if the compiler optimized out
892 this value, thus it is not available for fetching from the inferior.
896 The type of this @code{gdb.Value}. The value of this attribute is a
897 @code{gdb.Type} object (@pxref{Types In Python}).
900 @defvar Value.dynamic_type
901 The dynamic type of this @code{gdb.Value}. This uses the object's
902 virtual table and the C@t{++} run-time type information
903 (@acronym{RTTI}) to determine the dynamic type of the value. If this
904 value is of class type, it will return the class in which the value is
905 embedded, if any. If this value is of pointer or reference to a class
906 type, it will compute the dynamic type of the referenced object, and
907 return a pointer or reference to that type, respectively. In all
908 other cases, it will return the value's static type.
910 Note that this feature will only work when debugging a C@t{++} program
911 that includes @acronym{RTTI} for the object in question. Otherwise,
912 it will just return the static type of the value as in @kbd{ptype foo}
913 (@pxref{Symbols, ptype}).
916 @defvar Value.is_lazy
917 The value of this read-only boolean attribute is @code{True} if this
918 @code{gdb.Value} has not yet been fetched from the inferior.
919 @value{GDBN} does not fetch values until necessary, for efficiency.
923 myval = gdb.parse_and_eval ('somevar')
926 The value of @code{somevar} is not fetched at this time. It will be
927 fetched when the value is needed, or when the @code{fetch_lazy}
932 The value of this attribute is a @code{bytes} object containing the
933 bytes that make up this @code{Value}'s complete value in little endian
934 order. If the complete contents of this value are not available then
935 accessing this attribute will raise an exception.
937 This attribute can also be assigned to. The new value should be a
938 buffer object (e.g.@: a @code{bytes} object), the length of the new
939 buffer must exactly match the length of this @code{Value}'s type. The
940 bytes values in the new buffer should be in little endian order.
942 As with @code{Value.assign} (@pxref{Value.assign}), if this value
943 cannot be assigned to, then an exception will be thrown.
946 The following methods are provided:
948 @defun Value.__init__ (val)
949 Many Python values can be converted directly to a @code{gdb.Value} via
950 this object initializer. Specifically:
954 A Python boolean is converted to the boolean type from the current
958 A Python integer is converted to the C @code{long} type for the
959 current architecture.
962 A Python long is converted to the C @code{long long} type for the
963 current architecture.
966 A Python float is converted to the C @code{double} type for the
967 current architecture.
970 A Python string is converted to a target string in the current target
971 language using the current target encoding.
972 If a character cannot be represented in the current target encoding,
973 then an exception is thrown.
975 @item @code{gdb.Value}
976 If @code{val} is a @code{gdb.Value}, then a copy of the value is made.
978 @item @code{gdb.LazyString}
979 If @code{val} is a @code{gdb.LazyString} (@pxref{Lazy Strings In
980 Python}), then the lazy string's @code{value} method is called, and
985 @defun Value.__init__ (val, type)
986 This second form of the @code{gdb.Value} constructor returns a
987 @code{gdb.Value} of type @var{type} where the value contents are taken
988 from the Python buffer object specified by @var{val}. The number of
989 bytes in the Python buffer object must be greater than or equal to the
992 If @var{type} is @code{None} then this version of @code{__init__}
993 behaves as though @var{type} was not passed at all.
996 @anchor{Value.assign}
997 @defun Value.assign (rhs)
998 Assign @var{rhs} to this value, and return @code{None}. If this value
999 cannot be assigned to, or if the assignment is invalid for some reason
1000 (for example a type-checking failure), an exception will be thrown.
1003 @defun Value.cast (type)
1004 Return a new instance of @code{gdb.Value} that is the result of
1005 casting this instance to the type described by @var{type}, which must
1006 be a @code{gdb.Type} object. If the cast cannot be performed for some
1007 reason, this method throws an exception.
1010 @defun Value.dereference ()
1011 For pointer data types, this method returns a new @code{gdb.Value} object
1012 whose contents is the object pointed to by the pointer. For example, if
1013 @code{foo} is a C pointer to an @code{int}, declared in your C program as
1020 then you can use the corresponding @code{gdb.Value} to access what
1021 @code{foo} points to like this:
1024 bar = foo.dereference ()
1027 The result @code{bar} will be a @code{gdb.Value} object holding the
1028 value pointed to by @code{foo}.
1030 A similar function @code{Value.referenced_value} exists which also
1031 returns @code{gdb.Value} objects corresponding to the values pointed to
1032 by pointer values (and additionally, values referenced by reference
1033 values). However, the behavior of @code{Value.dereference}
1034 differs from @code{Value.referenced_value} by the fact that the
1035 behavior of @code{Value.dereference} is identical to applying the C
1036 unary operator @code{*} on a given value. For example, consider a
1037 reference to a pointer @code{ptrref}, declared in your C@t{++} program
1041 typedef int *intptr;
1045 intptr &ptrref = ptr;
1048 Though @code{ptrref} is a reference value, one can apply the method
1049 @code{Value.dereference} to the @code{gdb.Value} object corresponding
1050 to it and obtain a @code{gdb.Value} which is identical to that
1051 corresponding to @code{val}. However, if you apply the method
1052 @code{Value.referenced_value}, the result would be a @code{gdb.Value}
1053 object identical to that corresponding to @code{ptr}.
1056 py_ptrref = gdb.parse_and_eval ("ptrref")
1057 py_val = py_ptrref.dereference ()
1058 py_ptr = py_ptrref.referenced_value ()
1061 The @code{gdb.Value} object @code{py_val} is identical to that
1062 corresponding to @code{val}, and @code{py_ptr} is identical to that
1063 corresponding to @code{ptr}. In general, @code{Value.dereference} can
1064 be applied whenever the C unary operator @code{*} can be applied
1065 to the corresponding C value. For those cases where applying both
1066 @code{Value.dereference} and @code{Value.referenced_value} is allowed,
1067 the results obtained need not be identical (as we have seen in the above
1068 example). The results are however identical when applied on
1069 @code{gdb.Value} objects corresponding to pointers (@code{gdb.Value}
1070 objects with type code @code{TYPE_CODE_PTR}) in a C/C@t{++} program.
1073 @defun Value.referenced_value ()
1074 For pointer or reference data types, this method returns a new
1075 @code{gdb.Value} object corresponding to the value referenced by the
1076 pointer/reference value. For pointer data types,
1077 @code{Value.dereference} and @code{Value.referenced_value} produce
1078 identical results. The difference between these methods is that
1079 @code{Value.dereference} cannot get the values referenced by reference
1080 values. For example, consider a reference to an @code{int}, declared
1081 in your C@t{++} program as
1089 then applying @code{Value.dereference} to the @code{gdb.Value} object
1090 corresponding to @code{ref} will result in an error, while applying
1091 @code{Value.referenced_value} will result in a @code{gdb.Value} object
1092 identical to that corresponding to @code{val}.
1095 py_ref = gdb.parse_and_eval ("ref")
1096 er_ref = py_ref.dereference () # Results in error
1097 py_val = py_ref.referenced_value () # Returns the referenced value
1100 The @code{gdb.Value} object @code{py_val} is identical to that
1101 corresponding to @code{val}.
1104 @defun Value.reference_value ()
1105 Return a @code{gdb.Value} object which is a reference to the value
1106 encapsulated by this instance.
1109 @defun Value.const_value ()
1110 Return a @code{gdb.Value} object which is a @code{const} version of the
1111 value encapsulated by this instance.
1114 @defun Value.dynamic_cast (type)
1115 Like @code{Value.cast}, but works as if the C@t{++} @code{dynamic_cast}
1116 operator were used. Consult a C@t{++} reference for details.
1119 @defun Value.reinterpret_cast (type)
1120 Like @code{Value.cast}, but works as if the C@t{++} @code{reinterpret_cast}
1121 operator were used. Consult a C@t{++} reference for details.
1124 @defun Value.format_string (...)
1125 Convert a @code{gdb.Value} to a string, similarly to what the @code{print}
1126 command does. Invoked with no arguments, this is equivalent to calling
1127 the @code{str} function on the @code{gdb.Value}. The representation of
1128 the same value may change across different versions of @value{GDBN}, so
1129 you shouldn't, for instance, parse the strings returned by this method.
1131 All the arguments are keyword only. If an argument is not specified, the
1132 current global default setting is used.
1136 @code{True} if pretty-printers (@pxref{Pretty Printing}) should not be
1137 used to format the value. @code{False} if enabled pretty-printers
1138 matching the type represented by the @code{gdb.Value} should be used to
1142 @code{True} if arrays should be pretty printed to be more convenient to
1143 read, @code{False} if they shouldn't (see @code{set print array} in
1144 @ref{Print Settings}).
1146 @item pretty_structs
1147 @code{True} if structs should be pretty printed to be more convenient to
1148 read, @code{False} if they shouldn't (see @code{set print pretty} in
1149 @ref{Print Settings}).
1152 @code{True} if array indexes should be included in the string
1153 representation of arrays, @code{False} if they shouldn't (see @code{set
1154 print array-indexes} in @ref{Print Settings}).
1157 @code{True} if the string representation of a pointer should include the
1158 corresponding symbol name (if one exists), @code{False} if it shouldn't
1159 (see @code{set print symbol} in @ref{Print Settings}).
1162 @code{True} if unions which are contained in other structures or unions
1163 should be expanded, @code{False} if they shouldn't (see @code{set print
1164 union} in @ref{Print Settings}).
1167 @code{True} if the string representation of a pointer should include the
1168 address, @code{False} if it shouldn't (see @code{set print address} in
1169 @ref{Print Settings}).
1172 @code{True} if binary values should be displayed in groups of four bits,
1173 known as nibbles. @code{False} if it shouldn't (@pxref{Print Settings,
1174 set print nibbles}).
1177 @code{True} if C@t{++} references should be resolved to the value they
1178 refer to, @code{False} (the default) if they shouldn't. Note that, unlike
1179 for the @code{print} command, references are not automatically expanded
1180 when using the @code{format_string} method or the @code{str}
1181 function. There is no global @code{print} setting to change the default
1184 @item actual_objects
1185 @code{True} if the representation of a pointer to an object should
1186 identify the @emph{actual} (derived) type of the object rather than the
1187 @emph{declared} type, using the virtual function table. @code{False} if
1188 the @emph{declared} type should be used. (See @code{set print object} in
1189 @ref{Print Settings}).
1191 @item static_members
1192 @code{True} if static members should be included in the string
1193 representation of a C@t{++} object, @code{False} if they shouldn't (see
1194 @code{set print static-members} in @ref{Print Settings}).
1196 @item max_characters
1197 Number of string characters to print, @code{0} to follow
1198 @code{max_elements}, or @code{UINT_MAX} to print an unlimited number
1199 of characters (see @code{set print characters} in @ref{Print Settings}).
1202 Number of array elements to print, or @code{0} to print an unlimited
1203 number of elements (see @code{set print elements} in @ref{Print
1207 The maximum depth to print for nested structs and unions, or @code{-1}
1208 to print an unlimited number of elements (see @code{set print
1209 max-depth} in @ref{Print Settings}).
1211 @item repeat_threshold
1212 Set the threshold for suppressing display of repeated array elements, or
1213 @code{0} to represent all elements, even if repeated. (See @code{set
1214 print repeats} in @ref{Print Settings}).
1217 A string containing a single character representing the format to use for
1218 the returned string. For instance, @code{'x'} is equivalent to using the
1219 @value{GDBN} command @code{print} with the @code{/x} option and formats
1220 the value as a hexadecimal number.
1223 @code{True} if @value{GDBN} should apply styling to the returned
1224 string. When styling is applied, the returned string might contain
1225 ANSI terminal escape sequences. Escape sequences will only be
1226 included if styling is turned on, see @ref{Output Styling}.
1227 Additionally, @value{GDBN} only styles some value contents, so not
1228 every output string will contain escape sequences.
1230 When @code{False}, which is the default, no output styling is applied.
1233 @code{True} when just a summary should be printed. In this mode,
1234 scalar values are printed in their entirety, but aggregates such as
1235 structures or unions are omitted. This mode is used by @code{set
1236 print frame-arguments scalars} (@pxref{Print Settings}).
1240 @defun Value.to_array ()
1241 If this value is array-like (@pxref{Type.is_array_like}), then this
1242 method converts it to an array, which is returned. If this value is
1243 already an array, it is simply returned. Otherwise, an exception is
1247 @defun Value.string (@r{[}encoding@r{[}, errors@r{[}, length@r{]]]})
1248 If this @code{gdb.Value} represents a string, then this method
1249 converts the contents to a Python string. Otherwise, this method will
1252 Values are interpreted as strings according to the rules of the
1253 current language. If the optional length argument is given, the
1254 string will be converted to that length, and will include any embedded
1255 zeroes that the string may contain. Otherwise, for languages
1256 where the string is zero-terminated, the entire string will be
1259 For example, in C-like languages, a value is a string if it is a pointer
1260 to or an array of characters or ints of type @code{wchar_t}, @code{char16_t},
1263 If the optional @var{encoding} argument is given, it must be a string
1264 naming the encoding of the string in the @code{gdb.Value}, such as
1265 @code{"ascii"}, @code{"iso-8859-6"} or @code{"utf-8"}. It accepts
1266 the same encodings as the corresponding argument to Python's
1267 @code{string.decode} method, and the Python codec machinery will be used
1268 to convert the string. If @var{encoding} is not given, or if
1269 @var{encoding} is the empty string, then either the @code{target-charset}
1270 (@pxref{Character Sets}) will be used, or a language-specific encoding
1271 will be used, if the current language is able to supply one.
1273 The optional @var{errors} argument is the same as the corresponding
1274 argument to Python's @code{string.decode} method.
1276 If the optional @var{length} argument is given, the string will be
1277 fetched and converted to the given length.
1280 @defun Value.lazy_string (@r{[}encoding @r{[}, length@r{]]})
1281 If this @code{gdb.Value} represents a string, then this method
1282 converts the contents to a @code{gdb.LazyString} (@pxref{Lazy Strings
1283 In Python}). Otherwise, this method will throw an exception.
1285 If the optional @var{encoding} argument is given, it must be a string
1286 naming the encoding of the @code{gdb.LazyString}. Some examples are:
1287 @samp{ascii}, @samp{iso-8859-6} or @samp{utf-8}. If the
1288 @var{encoding} argument is an encoding that @value{GDBN} does
1289 recognize, @value{GDBN} will raise an error.
1291 When a lazy string is printed, the @value{GDBN} encoding machinery is
1292 used to convert the string during printing. If the optional
1293 @var{encoding} argument is not provided, or is an empty string,
1294 @value{GDBN} will automatically select the encoding most suitable for
1295 the string type. For further information on encoding in @value{GDBN}
1296 please see @ref{Character Sets}.
1298 If the optional @var{length} argument is given, the string will be
1299 fetched and encoded to the length of characters specified. If
1300 the @var{length} argument is not provided, the string will be fetched
1301 and encoded until a null of appropriate width is found.
1304 @defun Value.fetch_lazy ()
1305 If the @code{gdb.Value} object is currently a lazy value
1306 (@code{gdb.Value.is_lazy} is @code{True}), then the value is
1307 fetched from the inferior. Any errors that occur in the process
1308 will produce a Python exception.
1310 If the @code{gdb.Value} object is not a lazy value, this method
1313 This method does not return a value.
1317 @node Types In Python
1318 @subsubsection Types In Python
1319 @cindex types in Python
1320 @cindex Python, working with types
1323 @value{GDBN} represents types from the inferior using the class
1326 The following type-related functions are available in the @code{gdb}
1329 @defun gdb.lookup_type (name @r{[}, block@r{]})
1330 This function looks up a type by its @var{name}, which must be a string.
1332 If @var{block} is given, then @var{name} is looked up in that scope.
1333 Otherwise, it is searched for globally.
1335 Ordinarily, this function will return an instance of @code{gdb.Type}.
1336 If the named type cannot be found, it will throw an exception.
1339 Integer types can be found without looking them up by name.
1340 @xref{Architectures In Python}, for the @code{integer_type} method.
1342 If the type is a structure or class type, or an enum type, the fields
1343 of that type can be accessed using the Python @dfn{dictionary syntax}.
1344 For example, if @code{some_type} is a @code{gdb.Type} instance holding
1345 a structure type, you can access its @code{foo} field with:
1348 bar = some_type['foo']
1351 @code{bar} will be a @code{gdb.Field} object; see below under the
1352 description of the @code{Type.fields} method for a description of the
1353 @code{gdb.Field} class.
1355 An instance of @code{Type} has the following attributes:
1357 @defvar Type.alignof
1358 The alignment of this type, in bytes. Type alignment comes from the
1359 debugging information; if it was not specified, then @value{GDBN} will
1360 use the relevant ABI to try to determine the alignment. In some
1361 cases, even this is not possible, and zero will be returned.
1365 The type code for this type. The type code will be one of the
1366 @code{TYPE_CODE_} constants defined below.
1369 @defvar Type.dynamic
1370 A boolean indicating whether this type is dynamic. In some
1371 situations, such as Rust @code{enum} types or Ada variant records, the
1372 concrete type of a value may vary depending on its contents. That is,
1373 the declared type of a variable, or the type returned by
1374 @code{gdb.lookup_type} may be dynamic; while the type of the
1375 variable's value will be a concrete instance of that dynamic type.
1377 For example, consider this code:
1383 Here, at least conceptually (whether your compiler actually does this
1384 is a separate issue), examining @w{@code{gdb.lookup_symbol("array", ...).type}}
1385 could yield a @code{gdb.Type} which reports a size of @code{None}.
1386 This is the dynamic type.
1388 However, examining @code{gdb.parse_and_eval("array").type} would yield
1389 a concrete type, whose length would be known.
1393 The name of this type. If this type has no name, then @code{None}
1398 The size of this type, in target @code{char} units. Usually, a
1399 target's @code{char} type will be an 8-bit byte. However, on some
1400 unusual platforms, this type may have a different size. A dynamic
1401 type may not have a fixed size; in this case, this attribute's value
1402 will be @code{None}.
1406 The tag name for this type. The tag name is the name after
1407 @code{struct}, @code{union}, or @code{enum} in C and C@t{++}; not all
1408 languages have this concept. If this type has no tag name, then
1409 @code{None} is returned.
1412 @defvar Type.objfile
1413 The @code{gdb.Objfile} that this type was defined in, or @code{None} if
1414 there is no associated objfile.
1417 @defvar Type.is_scalar
1418 This property is @code{True} if the type is a scalar type, otherwise,
1419 this property is @code{False}. Examples of non-scalar types include
1420 structures, unions, and classes.
1423 @defvar Type.is_signed
1424 For scalar types (those for which @code{Type.is_scalar} is
1425 @code{True}), this property is @code{True} if the type is signed,
1426 otherwise this property is @code{False}.
1428 Attempting to read this property for a non-scalar type (a type for
1429 which @code{Type.is_scalar} is @code{False}), will raise a
1433 @defvar Type.is_array_like
1434 @anchor{Type.is_array_like}
1435 A boolean indicating whether this type is array-like.
1437 Some languages have array-like objects that are represented internally
1438 as structures. For example, this is true for a Rust slice type, or
1439 for an Ada unconstrained array. @value{GDBN} may know about these
1440 types. This determination is done based on the language from which
1441 the type originated.
1444 @defvar Type.is_string_like
1445 A boolean indicating whether this type is string-like. Like
1446 @code{Type.is_array_like}, this is determined based on the originating
1447 language of the type.
1450 The following methods are provided:
1452 @defun Type.fields ()
1454 Return the fields of this type. The behavior depends on the type code:
1459 For structure and union types, this method returns the fields.
1462 Enum types have one field per enum constant.
1465 Function and method types have one field per parameter. The base types of
1466 C@t{++} classes are also represented as fields.
1469 Array types have one field representing the array's range.
1472 If the type does not fit into one of these categories, a @code{TypeError}
1477 Each field is a @code{gdb.Field} object, with some pre-defined attributes:
1480 This attribute is not available for @code{enum} or @code{static}
1481 (as in C@t{++}) fields. The value is the position, counting
1482 in bits, from the start of the containing type. Note that, in a
1483 dynamic type, the position of a field may not be constant. In this
1484 case, the value will be @code{None}. Also, a dynamic type may have
1485 fields that do not appear in a corresponding concrete type.
1488 This attribute is only available for @code{enum} fields, and its value
1489 is the enumeration member's integer representation.
1492 The name of the field, or @code{None} for anonymous fields.
1495 This is @code{True} if the field is artificial, usually meaning that
1496 it was provided by the compiler and not the user. This attribute is
1497 always provided, and is @code{False} if the field is not artificial.
1500 This is @code{True} if the field represents a base class of a C@t{++}
1501 structure. This attribute is always provided, and is @code{False}
1502 if the field is not a base class of the type that is the argument of
1503 @code{fields}, or if that type was not a C@t{++} class.
1506 If the field is packed, or is a bitfield, then this will have a
1507 non-zero value, which is the size of the field in bits. Otherwise,
1508 this will be zero; in this case the field's size is given by its type.
1511 The type of the field. This is usually an instance of @code{Type},
1512 but it can be @code{None} in some situations.
1515 The type which contains this field. This is an instance of
1520 @defun Type.array (n1 @r{[}, n2@r{]})
1521 Return a new @code{gdb.Type} object which represents an array of this
1522 type. If one argument is given, it is the inclusive upper bound of
1523 the array; in this case the lower bound is zero. If two arguments are
1524 given, the first argument is the lower bound of the array, and the
1525 second argument is the upper bound of the array. An array's length
1526 must not be negative, but the bounds can be.
1529 @defun Type.vector (n1 @r{[}, n2@r{]})
1530 Return a new @code{gdb.Type} object which represents a vector of this
1531 type. If one argument is given, it is the inclusive upper bound of
1532 the vector; in this case the lower bound is zero. If two arguments are
1533 given, the first argument is the lower bound of the vector, and the
1534 second argument is the upper bound of the vector. A vector's length
1535 must not be negative, but the bounds can be.
1537 The difference between an @code{array} and a @code{vector} is that
1538 arrays behave like in C: when used in expressions they decay to a pointer
1539 to the first element whereas vectors are treated as first class values.
1542 @defun Type.const ()
1543 Return a new @code{gdb.Type} object which represents a
1544 @code{const}-qualified variant of this type.
1547 @defun Type.volatile ()
1548 Return a new @code{gdb.Type} object which represents a
1549 @code{volatile}-qualified variant of this type.
1552 @defun Type.unqualified ()
1553 Return a new @code{gdb.Type} object which represents an unqualified
1554 variant of this type. That is, the result is neither @code{const} nor
1558 @defun Type.range ()
1559 Return a Python @code{Tuple} object that contains two elements: the
1560 low bound of the argument type and the high bound of that type. If
1561 the type does not have a range, @value{GDBN} will raise a
1562 @code{gdb.error} exception (@pxref{Exception Handling}).
1565 @defun Type.reference ()
1566 Return a new @code{gdb.Type} object which represents a reference to this
1570 @defun Type.pointer ()
1571 Return a new @code{gdb.Type} object which represents a pointer to this
1575 @defun Type.strip_typedefs ()
1576 Return a new @code{gdb.Type} that represents the real type,
1577 after removing all layers of typedefs.
1580 @defun Type.target ()
1581 Return a new @code{gdb.Type} object which represents the target type
1584 For a pointer type, the target type is the type of the pointed-to
1585 object. For an array type (meaning C-like arrays), the target type is
1586 the type of the elements of the array. For a function or method type,
1587 the target type is the type of the return value. For a complex type,
1588 the target type is the type of the elements. For a typedef, the
1589 target type is the aliased type.
1591 If the type does not have a target, this method will throw an
1595 @defun Type.template_argument (n @r{[}, block@r{]})
1596 If this @code{gdb.Type} is an instantiation of a template, this will
1597 return a new @code{gdb.Value} or @code{gdb.Type} which represents the
1598 value of the @var{n}th template argument (indexed starting at 0).
1600 If this @code{gdb.Type} is not a template type, or if the type has fewer
1601 than @var{n} template arguments, this will throw an exception.
1602 Ordinarily, only C@t{++} code will have template types.
1604 If @var{block} is given, then @var{name} is looked up in that scope.
1605 Otherwise, it is searched for globally.
1608 @defun Type.optimized_out ()
1609 Return @code{gdb.Value} instance of this type whose value is optimized
1610 out. This allows a frame decorator to indicate that the value of an
1611 argument or a local variable is not known.
1614 Each type has a code, which indicates what category this type falls
1615 into. The available type categories are represented by constants
1616 defined in the @code{gdb} module:
1619 @vindex TYPE_CODE_PTR
1620 @item gdb.TYPE_CODE_PTR
1621 The type is a pointer.
1623 @vindex TYPE_CODE_ARRAY
1624 @item gdb.TYPE_CODE_ARRAY
1625 The type is an array.
1627 @vindex TYPE_CODE_STRUCT
1628 @item gdb.TYPE_CODE_STRUCT
1629 The type is a structure.
1631 @vindex TYPE_CODE_UNION
1632 @item gdb.TYPE_CODE_UNION
1633 The type is a union.
1635 @vindex TYPE_CODE_ENUM
1636 @item gdb.TYPE_CODE_ENUM
1637 The type is an enum.
1639 @vindex TYPE_CODE_FLAGS
1640 @item gdb.TYPE_CODE_FLAGS
1641 A bit flags type, used for things such as status registers.
1643 @vindex TYPE_CODE_FUNC
1644 @item gdb.TYPE_CODE_FUNC
1645 The type is a function.
1647 @vindex TYPE_CODE_INT
1648 @item gdb.TYPE_CODE_INT
1649 The type is an integer type.
1651 @vindex TYPE_CODE_FLT
1652 @item gdb.TYPE_CODE_FLT
1653 A floating point type.
1655 @vindex TYPE_CODE_VOID
1656 @item gdb.TYPE_CODE_VOID
1657 The special type @code{void}.
1659 @vindex TYPE_CODE_SET
1660 @item gdb.TYPE_CODE_SET
1663 @vindex TYPE_CODE_RANGE
1664 @item gdb.TYPE_CODE_RANGE
1665 A range type, that is, an integer type with bounds.
1667 @vindex TYPE_CODE_STRING
1668 @item gdb.TYPE_CODE_STRING
1669 A string type. Note that this is only used for certain languages with
1670 language-defined string types; C strings are not represented this way.
1672 @vindex TYPE_CODE_BITSTRING
1673 @item gdb.TYPE_CODE_BITSTRING
1674 A string of bits. It is deprecated.
1676 @vindex TYPE_CODE_ERROR
1677 @item gdb.TYPE_CODE_ERROR
1678 An unknown or erroneous type.
1680 @vindex TYPE_CODE_METHOD
1681 @item gdb.TYPE_CODE_METHOD
1682 A method type, as found in C@t{++}.
1684 @vindex TYPE_CODE_METHODPTR
1685 @item gdb.TYPE_CODE_METHODPTR
1686 A pointer-to-member-function.
1688 @vindex TYPE_CODE_MEMBERPTR
1689 @item gdb.TYPE_CODE_MEMBERPTR
1690 A pointer-to-member.
1692 @vindex TYPE_CODE_REF
1693 @item gdb.TYPE_CODE_REF
1696 @vindex TYPE_CODE_RVALUE_REF
1697 @item gdb.TYPE_CODE_RVALUE_REF
1698 A C@t{++}11 rvalue reference type.
1700 @vindex TYPE_CODE_CHAR
1701 @item gdb.TYPE_CODE_CHAR
1704 @vindex TYPE_CODE_BOOL
1705 @item gdb.TYPE_CODE_BOOL
1708 @vindex TYPE_CODE_COMPLEX
1709 @item gdb.TYPE_CODE_COMPLEX
1710 A complex float type.
1712 @vindex TYPE_CODE_TYPEDEF
1713 @item gdb.TYPE_CODE_TYPEDEF
1714 A typedef to some other type.
1716 @vindex TYPE_CODE_NAMESPACE
1717 @item gdb.TYPE_CODE_NAMESPACE
1718 A C@t{++} namespace.
1720 @vindex TYPE_CODE_DECFLOAT
1721 @item gdb.TYPE_CODE_DECFLOAT
1722 A decimal floating point type.
1724 @vindex TYPE_CODE_INTERNAL_FUNCTION
1725 @item gdb.TYPE_CODE_INTERNAL_FUNCTION
1726 A function internal to @value{GDBN}. This is the type used to represent
1727 convenience functions.
1729 @vindex TYPE_CODE_XMETHOD
1730 @item gdb.TYPE_CODE_XMETHOD
1731 A method internal to @value{GDBN}. This is the type used to represent
1732 xmethods (@pxref{Writing an Xmethod}).
1734 @vindex TYPE_CODE_FIXED_POINT
1735 @item gdb.TYPE_CODE_FIXED_POINT
1736 A fixed-point number.
1738 @vindex TYPE_CODE_NAMESPACE
1739 @item gdb.TYPE_CODE_NAMESPACE
1743 Further support for types is provided in the @code{gdb.types}
1744 Python module (@pxref{gdb.types}).
1746 @node Pretty Printing API
1747 @subsubsection Pretty Printing API
1748 @cindex python pretty printing api
1750 A pretty-printer is just an object that holds a value and implements a
1751 specific interface, defined here. An example output is provided
1752 (@pxref{Pretty Printing}).
1754 Because @value{GDBN} did not document extensibility for
1755 pretty-printers, by default @value{GDBN} will assume that only the
1756 basic pretty-printer methods may be available. The basic methods are
1757 marked as such, below.
1759 To allow extensibility, @value{GDBN} provides the
1760 @code{gdb.ValuePrinter} base class. This class does not provide any
1761 attributes or behavior, but instead serves as a tag that can be
1762 recognized by @value{GDBN}. For such printers, @value{GDBN} reserves
1763 all attributes starting with a lower-case letter. That is, in the
1764 future, @value{GDBN} may add a new method or attribute to the
1765 pretty-printer protocol, and @code{gdb.ValuePrinter}-based printers
1766 are expected to handle this gracefully. A simple way to do this would
1767 be to use a leading underscore (or two, following the Python
1768 name-mangling scheme) to any attributes local to the implementation.
1770 @defun pretty_printer.children (self)
1771 @value{GDBN} will call this method on a pretty-printer to compute the
1772 children of the pretty-printer's value.
1774 This method must return an object conforming to the Python iterator
1775 protocol. Each item returned by the iterator must be a tuple holding
1776 two elements. The first element is the ``name'' of the child; the
1777 second element is the child's value. The value can be any Python
1778 object which is convertible to a @value{GDBN} value.
1780 This is a basic method, and is optional. If it does not exist,
1781 @value{GDBN} will act as though the value has no children.
1783 For efficiency, the @code{children} method should lazily compute its
1784 results. This will let @value{GDBN} read as few elements as
1785 necessary, for example when various print settings (@pxref{Print
1786 Settings}) or @code{-var-list-children} (@pxref{GDB/MI Variable
1787 Objects}) limit the number of elements to be displayed.
1789 Children may be hidden from display based on the value of @samp{set
1790 print max-depth} (@pxref{Print Settings}).
1793 @defun pretty_printer.display_hint (self)
1794 The CLI may call this method and use its result to change the
1795 formatting of a value. The result will also be supplied to an MI
1796 consumer as a @samp{displayhint} attribute of the variable being
1799 This is a basic method, and is optional. If it does exist, this
1800 method must return a string or the special value @code{None}.
1802 Some display hints are predefined by @value{GDBN}:
1806 Indicate that the object being printed is ``array-like''. The CLI
1807 uses this to respect parameters such as @code{set print elements} and
1808 @code{set print array}.
1811 Indicate that the object being printed is ``map-like'', and that the
1812 children of this value can be assumed to alternate between keys and
1816 Indicate that the object being printed is ``string-like''. If the
1817 printer's @code{to_string} method returns a Python string of some
1818 kind, then @value{GDBN} will call its internal language-specific
1819 string-printing function to format the string. For the CLI this means
1820 adding quotation marks, possibly escaping some characters, respecting
1821 @code{set print elements}, and the like.
1824 The special value @code{None} causes @value{GDBN} to apply the default
1828 @defun pretty_printer.to_string (self)
1829 @value{GDBN} will call this method to display the string
1830 representation of the value passed to the object's constructor.
1832 This is a basic method, and is optional.
1834 When printing from the CLI, if the @code{to_string} method exists,
1835 then @value{GDBN} will prepend its result to the values returned by
1836 @code{children}. Exactly how this formatting is done is dependent on
1837 the display hint, and may change as more hints are added. Also,
1838 depending on the print settings (@pxref{Print Settings}), the CLI may
1839 print just the result of @code{to_string} in a stack trace, omitting
1840 the result of @code{children}.
1842 If this method returns a string, it is printed verbatim.
1844 Otherwise, if this method returns an instance of @code{gdb.Value},
1845 then @value{GDBN} prints this value. This may result in a call to
1846 another pretty-printer.
1848 If instead the method returns a Python value which is convertible to a
1849 @code{gdb.Value}, then @value{GDBN} performs the conversion and prints
1850 the resulting value. Again, this may result in a call to another
1851 pretty-printer. Python scalars (integers, floats, and booleans) and
1852 strings are convertible to @code{gdb.Value}; other types are not.
1854 Finally, if this method returns @code{None} then no further operations
1855 are performed in this method and nothing is printed.
1857 If the result is not one of these types, an exception is raised.
1860 @defun pretty_printer.num_children ()
1861 This is not a basic method, so @value{GDBN} will only ever call it for
1862 objects derived from @code{gdb.ValuePrinter}.
1864 If available, this method should return the number of children.
1865 @code{None} may be returned if the number can't readily be computed.
1868 @defun pretty_printer.child (n)
1869 This is not a basic method, so @value{GDBN} will only ever call it for
1870 objects derived from @code{gdb.ValuePrinter}.
1872 If available, this method should return the child item (that is, a
1873 tuple holding the name and value of this child) indicated by @var{n}.
1874 Indices start at zero.
1877 @value{GDBN} provides a function which can be used to look up the
1878 default pretty-printer for a @code{gdb.Value}:
1880 @defun gdb.default_visualizer (value)
1881 This function takes a @code{gdb.Value} object as an argument. If a
1882 pretty-printer for this value exists, then it is returned. If no such
1883 printer exists, then this returns @code{None}.
1886 Normally, a pretty-printer can respect the user's print settings
1887 (including temporarily applied settings, such as @samp{/x}) simply by
1888 calling @code{Value.format_string} (@pxref{Values From Inferior}).
1889 However, these settings can also be queried directly:
1891 @defun gdb.print_options ()
1892 Return a dictionary whose keys are the valid keywords that can be
1893 given to @code{Value.format_string}, and whose values are the user's
1894 settings. During a @code{print} or other operation, the values will
1895 reflect any flags that are temporarily in effect.
1898 (gdb) python print (gdb.print_options ()['max_elements'])
1903 @node Selecting Pretty-Printers
1904 @subsubsection Selecting Pretty-Printers
1905 @cindex selecting python pretty-printers
1907 @value{GDBN} provides several ways to register a pretty-printer:
1908 globally, per program space, and per objfile. When choosing how to
1909 register your pretty-printer, a good rule is to register it with the
1910 smallest scope possible: that is prefer a specific objfile first, then
1911 a program space, and only register a printer globally as a last
1914 @defvar gdb.pretty_printers
1915 The Python list @code{gdb.pretty_printers} contains an array of
1916 functions or callable objects that have been registered via addition
1917 as a pretty-printer. Printers in this list are called @code{global}
1918 printers, they're available when debugging all inferiors.
1921 Each @code{gdb.Progspace} contains a @code{pretty_printers} attribute.
1922 Each @code{gdb.Objfile} also contains a @code{pretty_printers}
1925 Each function on these lists is passed a single @code{gdb.Value}
1926 argument and should return a pretty-printer object conforming to the
1927 interface definition above (@pxref{Pretty Printing API}). If a function
1928 cannot create a pretty-printer for the value, it should return
1931 @value{GDBN} first checks the @code{pretty_printers} attribute of each
1932 @code{gdb.Objfile} in the current program space and iteratively calls
1933 each enabled lookup routine in the list for that @code{gdb.Objfile}
1934 until it receives a pretty-printer object.
1935 If no pretty-printer is found in the objfile lists, @value{GDBN} then
1936 searches the pretty-printer list of the current program space,
1937 calling each enabled function until an object is returned.
1938 After these lists have been exhausted, it tries the global
1939 @code{gdb.pretty_printers} list, again calling each enabled function until an
1942 The order in which the objfiles are searched is not specified. For a
1943 given list, functions are always invoked from the head of the list,
1944 and iterated over sequentially until the end of the list, or a printer
1947 For various reasons a pretty-printer may not work.
1948 For example, the underlying data structure may have changed and
1949 the pretty-printer is out of date.
1951 The consequences of a broken pretty-printer are severe enough that
1952 @value{GDBN} provides support for enabling and disabling individual
1953 printers. For example, if @code{print frame-arguments} is on,
1954 a backtrace can become highly illegible if any argument is printed
1955 with a broken printer.
1957 Pretty-printers are enabled and disabled by attaching an @code{enabled}
1958 attribute to the registered function or callable object. If this attribute
1959 is present and its value is @code{False}, the printer is disabled, otherwise
1960 the printer is enabled.
1962 @node Writing a Pretty-Printer
1963 @subsubsection Writing a Pretty-Printer
1964 @cindex writing a pretty-printer
1966 A pretty-printer consists of two parts: a lookup function to detect
1967 if the type is supported, and the printer itself.
1969 Here is an example showing how a @code{std::string} printer might be
1970 written. @xref{Pretty Printing API}, for details on the API this class
1971 must provide. Note that this example uses the @code{gdb.ValuePrinter}
1972 base class, and is careful to use a leading underscore for its local
1976 class StdStringPrinter(gdb.ValuePrinter):
1977 "Print a std::string"
1979 def __init__(self, val):
1982 def to_string(self):
1983 return self.__val['_M_dataplus']['_M_p']
1985 def display_hint(self):
1989 And here is an example showing how a lookup function for the printer
1990 example above might be written.
1993 def str_lookup_function(val):
1994 lookup_tag = val.type.tag
1995 if lookup_tag is None:
1997 regex = re.compile("^std::basic_string<char,.*>$")
1998 if regex.match(lookup_tag):
1999 return StdStringPrinter(val)
2003 The example lookup function extracts the value's type, and attempts to
2004 match it to a type that it can pretty-print. If it is a type the
2005 printer can pretty-print, it will return a printer object. If not, it
2006 returns @code{None}.
2008 We recommend that you put your core pretty-printers into a Python
2009 package. If your pretty-printers are for use with a library, we
2010 further recommend embedding a version number into the package name.
2011 This practice will enable @value{GDBN} to load multiple versions of
2012 your pretty-printers at the same time, because they will have
2015 You should write auto-loaded code (@pxref{Python Auto-loading}) such that it
2016 can be evaluated multiple times without changing its meaning. An
2017 ideal auto-load file will consist solely of @code{import}s of your
2018 printer modules, followed by a call to a register pretty-printers with
2019 the current objfile.
2021 Taken as a whole, this approach will scale nicely to multiple
2022 inferiors, each potentially using a different library version.
2023 Embedding a version number in the Python package name will ensure that
2024 @value{GDBN} is able to load both sets of printers simultaneously.
2025 Then, because the search for pretty-printers is done by objfile, and
2026 because your auto-loaded code took care to register your library's
2027 printers with a specific objfile, @value{GDBN} will find the correct
2028 printers for the specific version of the library used by each
2031 To continue the @code{std::string} example (@pxref{Pretty Printing API}),
2032 this code might appear in @code{gdb.libstdcxx.v6}:
2035 def register_printers(objfile):
2036 objfile.pretty_printers.append(str_lookup_function)
2040 And then the corresponding contents of the auto-load file would be:
2043 import gdb.libstdcxx.v6
2044 gdb.libstdcxx.v6.register_printers(gdb.current_objfile())
2047 The previous example illustrates a basic pretty-printer.
2048 There are a few things that can be improved on.
2049 The printer doesn't have a name, making it hard to identify in a
2050 list of installed printers. The lookup function has a name, but
2051 lookup functions can have arbitrary, even identical, names.
2053 Second, the printer only handles one type, whereas a library typically has
2054 several types. One could install a lookup function for each desired type
2055 in the library, but one could also have a single lookup function recognize
2056 several types. The latter is the conventional way this is handled.
2057 If a pretty-printer can handle multiple data types, then its
2058 @dfn{subprinters} are the printers for the individual data types.
2060 The @code{gdb.printing} module provides a formal way of solving these
2061 problems (@pxref{gdb.printing}).
2062 Here is another example that handles multiple types.
2064 These are the types we are going to pretty-print:
2067 struct foo @{ int a, b; @};
2068 struct bar @{ struct foo x, y; @};
2071 Here are the printers:
2074 class fooPrinter(gdb.ValuePrinter):
2075 """Print a foo object."""
2077 def __init__(self, val):
2080 def to_string(self):
2081 return ("a=<" + str(self.__val["a"]) +
2082 "> b=<" + str(self.__val["b"]) + ">")
2084 class barPrinter(gdb.ValuePrinter):
2085 """Print a bar object."""
2087 def __init__(self, val):
2090 def to_string(self):
2091 return ("x=<" + str(self.__val["x"]) +
2092 "> y=<" + str(self.__val["y"]) + ">")
2095 This example doesn't need a lookup function, that is handled by the
2096 @code{gdb.printing} module. Instead a function is provided to build up
2097 the object that handles the lookup.
2102 def build_pretty_printer():
2103 pp = gdb.printing.RegexpCollectionPrettyPrinter(
2105 pp.add_printer('foo', '^foo$', fooPrinter)
2106 pp.add_printer('bar', '^bar$', barPrinter)
2110 And here is the autoload support:
2115 gdb.printing.register_pretty_printer(
2116 gdb.current_objfile(),
2117 my_library.build_pretty_printer())
2120 Finally, when this printer is loaded into @value{GDBN}, here is the
2121 corresponding output of @samp{info pretty-printer}:
2124 (gdb) info pretty-printer
2131 @node Type Printing API
2132 @subsubsection Type Printing API
2133 @cindex type printing API for Python
2135 @value{GDBN} provides a way for Python code to customize type display.
2136 This is mainly useful for substituting canonical typedef names for
2139 @cindex type printer
2140 A @dfn{type printer} is just a Python object conforming to a certain
2141 protocol. A simple base class implementing the protocol is provided;
2142 see @ref{gdb.types}. A type printer must supply at least:
2144 @defivar type_printer enabled
2145 A boolean which is True if the printer is enabled, and False
2146 otherwise. This is manipulated by the @code{enable type-printer}
2147 and @code{disable type-printer} commands.
2150 @defivar type_printer name
2151 The name of the type printer. This must be a string. This is used by
2152 the @code{enable type-printer} and @code{disable type-printer}
2156 @defmethod type_printer instantiate (self)
2157 This is called by @value{GDBN} at the start of type-printing. It is
2158 only called if the type printer is enabled. This method must return a
2159 new object that supplies a @code{recognize} method, as described below.
2163 When displaying a type, say via the @code{ptype} command, @value{GDBN}
2164 will compute a list of type recognizers. This is done by iterating
2165 first over the per-objfile type printers (@pxref{Objfiles In Python}),
2166 followed by the per-progspace type printers (@pxref{Progspaces In
2167 Python}), and finally the global type printers.
2169 @value{GDBN} will call the @code{instantiate} method of each enabled
2170 type printer. If this method returns @code{None}, then the result is
2171 ignored; otherwise, it is appended to the list of recognizers.
2173 Then, when @value{GDBN} is going to display a type name, it iterates
2174 over the list of recognizers. For each one, it calls the recognition
2175 function, stopping if the function returns a non-@code{None} value.
2176 The recognition function is defined as:
2178 @defmethod type_recognizer recognize (self, type)
2179 If @var{type} is not recognized, return @code{None}. Otherwise,
2180 return a string which is to be printed as the name of @var{type}.
2181 The @var{type} argument will be an instance of @code{gdb.Type}
2182 (@pxref{Types In Python}).
2185 @value{GDBN} uses this two-pass approach so that type printers can
2186 efficiently cache information without holding on to it too long. For
2187 example, it can be convenient to look up type information in a type
2188 printer and hold it for a recognizer's lifetime; if a single pass were
2189 done then type printers would have to make use of the event system in
2190 order to avoid holding information that could become stale as the
2193 @node Frame Filter API
2194 @subsubsection Filtering Frames
2195 @cindex frame filters api
2197 Frame filters are Python objects that manipulate the visibility of a
2198 frame or frames when a backtrace (@pxref{Backtrace}) is printed by
2201 Only commands that print a backtrace, or, in the case of @sc{gdb/mi}
2202 commands (@pxref{GDB/MI}), those that return a collection of frames
2203 are affected. The commands that work with frame filters are:
2205 @code{backtrace} (@pxref{backtrace-command,, The backtrace command}),
2206 @code{-stack-list-frames}
2207 (@pxref{-stack-list-frames,, The -stack-list-frames command}),
2208 @code{-stack-list-variables} (@pxref{-stack-list-variables,, The
2209 -stack-list-variables command}), @code{-stack-list-arguments}
2210 @pxref{-stack-list-arguments,, The -stack-list-arguments command}) and
2211 @code{-stack-list-locals} (@pxref{-stack-list-locals,, The
2212 -stack-list-locals command}).
2214 A frame filter works by taking an iterator as an argument, applying
2215 actions to the contents of that iterator, and returning another
2216 iterator (or, possibly, the same iterator it was provided in the case
2217 where the filter does not perform any operations). Typically, frame
2218 filters utilize tools such as the Python's @code{itertools} module to
2219 work with and create new iterators from the source iterator.
2220 Regardless of how a filter chooses to apply actions, it must not alter
2221 the underlying @value{GDBN} frame or frames, or attempt to alter the
2222 call-stack within @value{GDBN}. This preserves data integrity within
2223 @value{GDBN}. Frame filters are executed on a priority basis and care
2224 should be taken that some frame filters may have been executed before,
2225 and that some frame filters will be executed after.
2227 An important consideration when designing frame filters, and well
2228 worth reflecting upon, is that frame filters should avoid unwinding
2229 the call stack if possible. Some stacks can run very deep, into the
2230 tens of thousands in some cases. To search every frame when a frame
2231 filter executes may be too expensive at that step. The frame filter
2232 cannot know how many frames it has to iterate over, and it may have to
2233 iterate through them all. This ends up duplicating effort as
2234 @value{GDBN} performs this iteration when it prints the frames. If
2235 the filter can defer unwinding frames until frame decorators are
2236 executed, after the last filter has executed, it should. @xref{Frame
2237 Decorator API}, for more information on decorators. Also, there are
2238 examples for both frame decorators and filters in later chapters.
2239 @xref{Writing a Frame Filter}, for more information.
2241 The Python dictionary @code{gdb.frame_filters} contains key/object
2242 pairings that comprise a frame filter. Frame filters in this
2243 dictionary are called @code{global} frame filters, and they are
2244 available when debugging all inferiors. These frame filters must
2245 register with the dictionary directly. In addition to the
2246 @code{global} dictionary, there are other dictionaries that are loaded
2247 with different inferiors via auto-loading (@pxref{Python
2248 Auto-loading}). The two other areas where frame filter dictionaries
2249 can be found are: @code{gdb.Progspace} which contains a
2250 @code{frame_filters} dictionary attribute, and each @code{gdb.Objfile}
2251 object which also contains a @code{frame_filters} dictionary
2254 When a command is executed from @value{GDBN} that is compatible with
2255 frame filters, @value{GDBN} combines the @code{global},
2256 @code{gdb.Progspace} and all @code{gdb.Objfile} dictionaries currently
2257 loaded. All of the @code{gdb.Objfile} dictionaries are combined, as
2258 several frames, and thus several object files, might be in use.
2259 @value{GDBN} then prunes any frame filter whose @code{enabled}
2260 attribute is @code{False}. This pruned list is then sorted according
2261 to the @code{priority} attribute in each filter.
2263 Once the dictionaries are combined, pruned and sorted, @value{GDBN}
2264 creates an iterator which wraps each frame in the call stack in a
2265 @code{FrameDecorator} object, and calls each filter in order. The
2266 output from the previous filter will always be the input to the next
2269 Frame filters have a mandatory interface which each frame filter must
2270 implement, defined here:
2272 @defun FrameFilter.filter (iterator)
2273 @value{GDBN} will call this method on a frame filter when it has
2274 reached the order in the priority list for that filter.
2276 For example, if there are four frame filters:
2287 The order that the frame filters will be called is:
2290 Filter3 -> Filter2 -> Filter1 -> Filter4
2293 Note that the output from @code{Filter3} is passed to the input of
2294 @code{Filter2}, and so on.
2296 This @code{filter} method is passed a Python iterator. This iterator
2297 contains a sequence of frame decorators that wrap each
2298 @code{gdb.Frame}, or a frame decorator that wraps another frame
2299 decorator. The first filter that is executed in the sequence of frame
2300 filters will receive an iterator entirely comprised of default
2301 @code{FrameDecorator} objects. However, after each frame filter is
2302 executed, the previous frame filter may have wrapped some or all of
2303 the frame decorators with their own frame decorator. As frame
2304 decorators must also conform to a mandatory interface, these
2305 decorators can be assumed to act in a uniform manner (@pxref{Frame
2308 This method must return an object conforming to the Python iterator
2309 protocol. Each item in the iterator must be an object conforming to
2310 the frame decorator interface. If a frame filter does not wish to
2311 perform any operations on this iterator, it should return that
2314 This method is not optional. If it does not exist, @value{GDBN} will
2315 raise and print an error.
2318 @defvar FrameFilter.name
2319 The @code{name} attribute must be Python string which contains the
2320 name of the filter displayed by @value{GDBN} (@pxref{Frame Filter
2321 Management}). This attribute may contain any combination of letters
2322 or numbers. Care should be taken to ensure that it is unique. This
2323 attribute is mandatory.
2326 @defvar FrameFilter.enabled
2327 The @code{enabled} attribute must be Python boolean. This attribute
2328 indicates to @value{GDBN} whether the frame filter is enabled, and
2329 should be considered when frame filters are executed. If
2330 @code{enabled} is @code{True}, then the frame filter will be executed
2331 when any of the backtrace commands detailed earlier in this chapter
2332 are executed. If @code{enabled} is @code{False}, then the frame
2333 filter will not be executed. This attribute is mandatory.
2336 @defvar FrameFilter.priority
2337 The @code{priority} attribute must be Python integer. This attribute
2338 controls the order of execution in relation to other frame filters.
2339 There are no imposed limits on the range of @code{priority} other than
2340 it must be a valid integer. The higher the @code{priority} attribute,
2341 the sooner the frame filter will be executed in relation to other
2342 frame filters. Although @code{priority} can be negative, it is
2343 recommended practice to assume zero is the lowest priority that a
2344 frame filter can be assigned. Frame filters that have the same
2345 priority are executed in unsorted order in that priority slot. This
2346 attribute is mandatory. 100 is a good default priority.
2349 @node Frame Decorator API
2350 @subsubsection Decorating Frames
2351 @cindex frame decorator api
2353 Frame decorators are sister objects to frame filters (@pxref{Frame
2354 Filter API}). Frame decorators are applied by a frame filter and can
2355 only be used in conjunction with frame filters.
2357 The purpose of a frame decorator is to customize the printed content
2358 of each @code{gdb.Frame} in commands where frame filters are executed.
2359 This concept is called decorating a frame. Frame decorators decorate
2360 a @code{gdb.Frame} with Python code contained within each API call.
2361 This separates the actual data contained in a @code{gdb.Frame} from
2362 the decorated data produced by a frame decorator. This abstraction is
2363 necessary to maintain integrity of the data contained in each
2366 Frame decorators have a mandatory interface, defined below.
2368 @value{GDBN} already contains a frame decorator called
2369 @code{FrameDecorator}. This contains substantial amounts of
2370 boilerplate code to decorate the content of a @code{gdb.Frame}. It is
2371 recommended that other frame decorators inherit and extend this
2372 object, and only to override the methods needed.
2374 @tindex gdb.FrameDecorator
2375 @code{FrameDecorator} is defined in the Python module
2376 @code{gdb.FrameDecorator}, so your code can import it like:
2378 from gdb.FrameDecorator import FrameDecorator
2381 @defun FrameDecorator.elided (self)
2383 The @code{elided} method groups frames together in a hierarchical
2384 system. An example would be an interpreter, where multiple low-level
2385 frames make up a single call in the interpreted language. In this
2386 example, the frame filter would elide the low-level frames and present
2387 a single high-level frame, representing the call in the interpreted
2388 language, to the user.
2390 The @code{elided} function must return an iterable and this iterable
2391 must contain the frames that are being elided wrapped in a suitable
2392 frame decorator. If no frames are being elided this function may
2393 return an empty iterable, or @code{None}. Elided frames are indented
2394 from normal frames in a @code{CLI} backtrace, or in the case of
2395 @sc{gdb/mi}, are placed in the @code{children} field of the eliding
2398 It is the frame filter's task to also filter out the elided frames from
2399 the source iterator. This will avoid printing the frame twice.
2402 @defun FrameDecorator.function (self)
2404 This method returns the name of the function in the frame that is to
2407 This method must return a Python string describing the function, or
2410 If this function returns @code{None}, @value{GDBN} will not print any
2411 data for this field.
2414 @defun FrameDecorator.address (self)
2416 This method returns the address of the frame that is to be printed.
2418 This method must return a Python numeric integer type of sufficient
2419 size to describe the address of the frame, or @code{None}.
2421 If this function returns a @code{None}, @value{GDBN} will not print
2422 any data for this field.
2425 @defun FrameDecorator.filename (self)
2427 This method returns the filename and path associated with this frame.
2429 This method must return a Python string containing the filename and
2430 the path to the object file backing the frame, or @code{None}.
2432 If this function returns a @code{None}, @value{GDBN} will not print
2433 any data for this field.
2436 @defun FrameDecorator.line (self):
2438 This method returns the line number associated with the current
2439 position within the function addressed by this frame.
2441 This method must return a Python integer type, 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.frame_args (self)
2450 This method must return an iterable, or @code{None}. Returning an
2451 empty iterable, or @code{None} means frame arguments will not be
2452 printed for this frame. This iterable must contain objects that
2453 implement two methods, described here.
2455 This object must implement a @code{symbol} method which takes a
2456 single @code{self} parameter and must return a @code{gdb.Symbol}
2457 (@pxref{Symbols In Python}), or a Python string. The object must also
2458 implement a @code{value} method which takes a single @code{self}
2459 parameter and must return a @code{gdb.Value} (@pxref{Values From
2460 Inferior}), a Python value, or @code{None}. If the @code{value}
2461 method returns @code{None}, and the @code{argument} method returns a
2462 @code{gdb.Symbol}, @value{GDBN} will look-up and print the value of
2463 the @code{gdb.Symbol} automatically.
2468 class SymValueWrapper():
2470 def __init__(self, symbol, value):
2480 class SomeFrameDecorator()
2483 def frame_args(self):
2486 block = self.inferior_frame.block()
2490 # Iterate over all symbols in a block. Only add
2491 # symbols that are arguments.
2493 if not sym.is_argument:
2495 args.append(SymValueWrapper(sym,None))
2497 # Add example synthetic argument.
2498 args.append(SymValueWrapper(``foo'', 42))
2504 @defun FrameDecorator.frame_locals (self)
2506 This method must return an iterable or @code{None}. Returning an
2507 empty iterable, or @code{None} means frame local arguments will not be
2508 printed for this frame.
2510 The object interface, the description of the various strategies for
2511 reading frame locals, and the example are largely similar to those
2512 described in the @code{frame_args} function, (@pxref{frame_args,,The
2513 frame filter frame_args function}). Below is a modified example:
2516 class SomeFrameDecorator()
2519 def frame_locals(self):
2522 block = self.inferior_frame.block()
2526 # Iterate over all symbols in a block. Add all
2527 # symbols, except arguments.
2531 vars.append(SymValueWrapper(sym,None))
2533 # Add an example of a synthetic local variable.
2534 vars.append(SymValueWrapper(``bar'', 99))
2540 @defun FrameDecorator.inferior_frame (self):
2542 This method must return the underlying @code{gdb.Frame} that this
2543 frame decorator is decorating. @value{GDBN} requires the underlying
2544 frame for internal frame information to determine how to print certain
2545 values when printing a frame.
2548 @node Writing a Frame Filter
2549 @subsubsection Writing a Frame Filter
2550 @cindex writing a frame filter
2552 There are three basic elements that a frame filter must implement: it
2553 must correctly implement the documented interface (@pxref{Frame Filter
2554 API}), it must register itself with @value{GDBN}, and finally, it must
2555 decide if it is to work on the data provided by @value{GDBN}. In all
2556 cases, whether it works on the iterator or not, each frame filter must
2557 return an iterator. A bare-bones frame filter follows the pattern in
2558 the following example.
2563 class FrameFilter():
2566 # Frame filter attribute creation.
2568 # 'name' is the name of the filter that GDB will display.
2570 # 'priority' is the priority of the filter relative to other
2573 # 'enabled' is a boolean that indicates whether this filter is
2574 # enabled and should be executed.
2580 # Register this frame filter with the global frame_filters
2582 gdb.frame_filters[self.name] = self
2584 def filter(self, frame_iter):
2585 # Just return the iterator.
2589 The frame filter in the example above implements the three
2590 requirements for all frame filters. It implements the API, self
2591 registers, and makes a decision on the iterator (in this case, it just
2592 returns the iterator untouched).
2594 The first step is attribute creation and assignment, and as shown in
2595 the comments the filter assigns the following attributes: @code{name},
2596 @code{priority} and whether the filter should be enabled with the
2597 @code{enabled} attribute.
2599 The second step is registering the frame filter with the dictionary or
2600 dictionaries that the frame filter has interest in. As shown in the
2601 comments, this filter just registers itself with the global dictionary
2602 @code{gdb.frame_filters}. As noted earlier, @code{gdb.frame_filters}
2603 is a dictionary that is initialized in the @code{gdb} module when
2604 @value{GDBN} starts. What dictionary a filter registers with is an
2605 important consideration. Generally, if a filter is specific to a set
2606 of code, it should be registered either in the @code{objfile} or
2607 @code{progspace} dictionaries as they are specific to the program
2608 currently loaded in @value{GDBN}. The global dictionary is always
2609 present in @value{GDBN} and is never unloaded. Any filters registered
2610 with the global dictionary will exist until @value{GDBN} exits. To
2611 avoid filters that may conflict, it is generally better to register
2612 frame filters against the dictionaries that more closely align with
2613 the usage of the filter currently in question. @xref{Python
2614 Auto-loading}, for further information on auto-loading Python scripts.
2616 @value{GDBN} takes a hands-off approach to frame filter registration,
2617 therefore it is the frame filter's responsibility to ensure
2618 registration has occurred, and that any exceptions are handled
2619 appropriately. In particular, you may wish to handle exceptions
2620 relating to Python dictionary key uniqueness. It is mandatory that
2621 the dictionary key is the same as frame filter's @code{name}
2622 attribute. When a user manages frame filters (@pxref{Frame Filter
2623 Management}), the names @value{GDBN} will display are those contained
2624 in the @code{name} attribute.
2626 The final step of this example is the implementation of the
2627 @code{filter} method. As shown in the example comments, we define the
2628 @code{filter} method and note that the method must take an iterator,
2629 and also must return an iterator. In this bare-bones example, the
2630 frame filter is not very useful as it just returns the iterator
2631 untouched. However this is a valid operation for frame filters that
2632 have the @code{enabled} attribute set, but decide not to operate on
2635 In the next example, the frame filter operates on all frames and
2636 utilizes a frame decorator to perform some work on the frames.
2637 @xref{Frame Decorator API}, for further information on the frame
2638 decorator interface.
2640 This example works on inlined frames. It highlights frames which are
2641 inlined by tagging them with an ``[inlined]'' tag. By applying a
2642 frame decorator to all frames with the Python @code{itertools imap}
2643 method, the example defers actions to the frame decorator. Frame
2644 decorators are only processed when @value{GDBN} prints the backtrace.
2646 This introduces a new decision making topic: whether to perform
2647 decision making operations at the filtering step, or at the printing
2648 step. In this example's approach, it does not perform any filtering
2649 decisions at the filtering step beyond mapping a frame decorator to
2650 each frame. This allows the actual decision making to be performed
2651 when each frame is printed. This is an important consideration, and
2652 well worth reflecting upon when designing a frame filter. An issue
2653 that frame filters should avoid is unwinding the stack if possible.
2654 Some stacks can run very deep, into the tens of thousands in some
2655 cases. To search every frame to determine if it is inlined ahead of
2656 time may be too expensive at the filtering step. The frame filter
2657 cannot know how many frames it has to iterate over, and it would have
2658 to iterate through them all. This ends up duplicating effort as
2659 @value{GDBN} performs this iteration when it prints the frames.
2661 In this example decision making can be deferred to the printing step.
2662 As each frame is printed, the frame decorator can examine each frame
2663 in turn when @value{GDBN} iterates. From a performance viewpoint,
2664 this is the most appropriate decision to make as it avoids duplicating
2665 the effort that the printing step would undertake anyway. Also, if
2666 there are many frame filters unwinding the stack during filtering, it
2667 can substantially delay the printing of the backtrace which will
2668 result in large memory usage, and a poor user experience.
2671 class InlineFilter():
2674 self.name = "InlinedFrameFilter"
2677 gdb.frame_filters[self.name] = self
2679 def filter(self, frame_iter):
2680 frame_iter = itertools.imap(InlinedFrameDecorator,
2685 This frame filter is somewhat similar to the earlier example, except
2686 that the @code{filter} method applies a frame decorator object called
2687 @code{InlinedFrameDecorator} to each element in the iterator. The
2688 @code{imap} Python method is light-weight. It does not proactively
2689 iterate over the iterator, but rather creates a new iterator which
2690 wraps the existing one.
2692 Below is the frame decorator for this example.
2695 class InlinedFrameDecorator(FrameDecorator):
2697 def __init__(self, fobj):
2698 super(InlinedFrameDecorator, self).__init__(fobj)
2701 frame = self.inferior_frame()
2702 name = str(frame.name())
2704 if frame.type() == gdb.INLINE_FRAME:
2705 name = name + " [inlined]"
2710 This frame decorator only defines and overrides the @code{function}
2711 method. It lets the supplied @code{FrameDecorator}, which is shipped
2712 with @value{GDBN}, perform the other work associated with printing
2715 The combination of these two objects create this output from a
2719 #0 0x004004e0 in bar () at inline.c:11
2720 #1 0x00400566 in max [inlined] (b=6, a=12) at inline.c:21
2721 #2 0x00400566 in main () at inline.c:31
2724 So in the case of this example, a frame decorator is applied to all
2725 frames, regardless of whether they may be inlined or not. As
2726 @value{GDBN} iterates over the iterator produced by the frame filters,
2727 @value{GDBN} executes each frame decorator which then makes a decision
2728 on what to print in the @code{function} callback. Using a strategy
2729 like this is a way to defer decisions on the frame content to printing
2732 @subheading Eliding Frames
2734 It might be that the above example is not desirable for representing
2735 inlined frames, and a hierarchical approach may be preferred. If we
2736 want to hierarchically represent frames, the @code{elided} frame
2737 decorator interface might be preferable.
2739 This example approaches the issue with the @code{elided} method. This
2740 example is quite long, but very simplistic. It is out-of-scope for
2741 this section to write a complete example that comprehensively covers
2742 all approaches of finding and printing inlined frames. However, this
2743 example illustrates the approach an author might use.
2745 This example comprises of three sections.
2748 class InlineFrameFilter():
2751 self.name = "InlinedFrameFilter"
2754 gdb.frame_filters[self.name] = self
2756 def filter(self, frame_iter):
2757 return ElidingInlineIterator(frame_iter)
2760 This frame filter is very similar to the other examples. The only
2761 difference is this frame filter is wrapping the iterator provided to
2762 it (@code{frame_iter}) with a custom iterator called
2763 @code{ElidingInlineIterator}. This again defers actions to when
2764 @value{GDBN} prints the backtrace, as the iterator is not traversed
2767 The iterator for this example is as follows. It is in this section of
2768 the example where decisions are made on the content of the backtrace.
2771 class ElidingInlineIterator:
2772 def __init__(self, ii):
2773 self.input_iterator = ii
2779 frame = next(self.input_iterator)
2781 if frame.inferior_frame().type() != gdb.INLINE_FRAME:
2785 eliding_frame = next(self.input_iterator)
2786 except StopIteration:
2788 return ElidingFrameDecorator(eliding_frame, [frame])
2791 This iterator implements the Python iterator protocol. When the
2792 @code{next} function is called (when @value{GDBN} prints each frame),
2793 the iterator checks if this frame decorator, @code{frame}, is wrapping
2794 an inlined frame. If it is not, it returns the existing frame decorator
2795 untouched. If it is wrapping an inlined frame, it assumes that the
2796 inlined frame was contained within the next oldest frame,
2797 @code{eliding_frame}, which it fetches. It then creates and returns a
2798 frame decorator, @code{ElidingFrameDecorator}, which contains both the
2799 elided frame, and the eliding frame.
2802 class ElidingInlineDecorator(FrameDecorator):
2804 def __init__(self, frame, elided_frames):
2805 super(ElidingInlineDecorator, self).__init__(frame)
2807 self.elided_frames = elided_frames
2810 return iter(self.elided_frames)
2813 This frame decorator overrides one function and returns the inlined
2814 frame in the @code{elided} method. As before it lets
2815 @code{FrameDecorator} do the rest of the work involved in printing
2816 this frame. This produces the following output.
2819 #0 0x004004e0 in bar () at inline.c:11
2820 #2 0x00400529 in main () at inline.c:25
2821 #1 0x00400529 in max (b=6, a=12) at inline.c:15
2824 In that output, @code{max} which has been inlined into @code{main} is
2825 printed hierarchically. Another approach would be to combine the
2826 @code{function} method, and the @code{elided} method to both print a
2827 marker in the inlined frame, and also show the hierarchical
2830 @node Unwinding Frames in Python
2831 @subsubsection Unwinding Frames in Python
2832 @cindex unwinding frames in Python
2834 In @value{GDBN} terminology ``unwinding'' is the process of finding
2835 the previous frame (that is, caller's) from the current one. An
2836 unwinder has three methods. The first one checks if it can handle
2837 given frame (``sniff'' it). For the frames it can sniff an unwinder
2838 provides two additional methods: it can return frame's ID, and it can
2839 fetch registers from the previous frame. A running @value{GDBN}
2840 maintains a list of the unwinders and calls each unwinder's sniffer in
2841 turn until it finds the one that recognizes the current frame. There
2842 is an API to register an unwinder.
2844 The unwinders that come with @value{GDBN} handle standard frames.
2845 However, mixed language applications (for example, an application
2846 running Java Virtual Machine) sometimes use frame layouts that cannot
2847 be handled by the @value{GDBN} unwinders. You can write Python code
2848 that can handle such custom frames.
2850 You implement a frame unwinder in Python as a class with which has two
2851 attributes, @code{name} and @code{enabled}, with obvious meanings, and
2852 a single method @code{__call__}, which examines a given frame and
2853 returns an object (an instance of @code{gdb.UnwindInfo class)}
2854 describing it. If an unwinder does not recognize a frame, it should
2855 return @code{None}. The code in @value{GDBN} that enables writing
2856 unwinders in Python uses this object to return frame's ID and previous
2857 frame registers when @value{GDBN} core asks for them.
2859 An unwinder should do as little work as possible. Some otherwise
2860 innocuous operations can cause problems (even crashes, as this code is
2861 not well-hardened yet). For example, making an inferior call from
2862 an unwinder is unadvisable, as an inferior call will reset
2863 @value{GDBN}'s stack unwinding process, potentially causing re-entrant
2866 @subheading Unwinder Input
2868 An object passed to an unwinder (a @code{gdb.PendingFrame} instance)
2869 provides a method to read frame's registers:
2871 @defun PendingFrame.read_register (register)
2872 This method returns the contents of @var{register} in the
2873 frame as a @code{gdb.Value} object. For a description of the
2874 acceptable values of @var{register} see
2875 @ref{gdbpy_frame_read_register,,Frame.read_register}. If @var{register}
2876 does not name a register for the current architecture, this method
2877 will throw an exception.
2879 Note that this method will always return a @code{gdb.Value} for a
2880 valid register name. This does not mean that the value will be valid.
2881 For example, you may request a register that an earlier unwinder could
2882 not unwind---the value will be unavailable. Instead, the
2883 @code{gdb.Value} returned from this method will be lazy; that is, its
2884 underlying bits will not be fetched until it is first used. So,
2885 attempting to use such a value will cause an exception at the point of
2888 The type of the returned @code{gdb.Value} depends on the register and
2889 the architecture. It is common for registers to have a scalar type,
2890 like @code{long long}; but many other types are possible, such as
2891 pointer, pointer-to-function, floating point or vector types.
2894 It also provides a factory method to create a @code{gdb.UnwindInfo}
2895 instance to be returned to @value{GDBN}:
2897 @anchor{gdb.PendingFrame.create_unwind_info}
2898 @defun PendingFrame.create_unwind_info (frame_id)
2899 Returns a new @code{gdb.UnwindInfo} instance identified by given
2900 @var{frame_id}. The @var{frame_id} is used internally by @value{GDBN}
2901 to identify the frames within the current thread's stack. The
2902 attributes of @var{frame_id} determine what type of frame is
2903 created within @value{GDBN}:
2907 The frame is identified by the given stack address and PC. The stack
2908 address must be chosen so that it is constant throughout the lifetime
2909 of the frame, so a typical choice is the value of the stack pointer at
2910 the start of the function---in the DWARF standard, this would be the
2911 ``Call Frame Address''.
2913 This is the most common case by far. The other cases are documented
2914 for completeness but are only useful in specialized situations.
2916 @item sp, pc, special
2917 The frame is identified by the stack address, the PC, and a
2918 ``special'' address. The special address is used on architectures
2919 that can have frames that do not change the stack, but which are still
2920 distinct, for example the IA-64, which has a second stack for
2921 registers. Both @var{sp} and @var{special} must be constant
2922 throughout the lifetime of the frame.
2925 The frame is identified by the stack address only. Any other stack
2926 frame with a matching @var{sp} will be considered to match this frame.
2927 Inside gdb, this is called a ``wild frame''. You will never need
2931 Each attribute value should either be an instance of @code{gdb.Value}
2934 A helper class is provided in the @code{gdb.unwinder} module that can
2935 be used to represent a frame-id
2936 (@pxref{gdb.unwinder.FrameId}).
2940 @defun PendingFrame.architecture ()
2941 Return the @code{gdb.Architecture} (@pxref{Architectures In Python})
2942 for this @code{gdb.PendingFrame}. This represents the architecture of
2943 the particular frame being unwound.
2946 @defun PendingFrame.level ()
2947 Return an integer, the stack frame level for this frame.
2948 @xref{Frames, ,Stack Frames}.
2951 @defun PendingFrame.name ()
2952 Returns the function name of this pending frame, or @code{None} if it
2956 @defun PendingFrame.is_valid ()
2957 Returns true if the @code{gdb.PendingFrame} object is valid, false if
2958 not. A pending frame object becomes invalid when the call to the
2959 unwinder, for which the pending frame was created, returns.
2961 All @code{gdb.PendingFrame} methods, except this one, will raise an
2962 exception if the pending frame object is invalid at the time the
2966 @defun PendingFrame.pc ()
2967 Returns the pending frame's resume address.
2970 @defun PendingFrame.block ()
2971 Return the pending frame's code block (@pxref{Blocks In Python}). If
2972 the frame does not have a block -- for example, if there is no
2973 debugging information for the code in question -- then this will raise
2974 a @code{RuntimeError} exception.
2977 @defun PendingFrame.function ()
2978 Return the symbol for the function corresponding to this pending frame.
2979 @xref{Symbols In Python}.
2982 @defun PendingFrame.find_sal ()
2983 Return the pending frame's symtab and line object (@pxref{Symbol
2987 @defun PendingFrame.language ()
2988 Return the language of this frame, as a string, or None.
2991 @subheading Unwinder Output: UnwindInfo
2993 Use @code{PendingFrame.create_unwind_info} method described above to
2994 create a @code{gdb.UnwindInfo} instance. Use the following method to
2995 specify caller registers that have been saved in this frame:
2997 @defun gdb.UnwindInfo.add_saved_register (register, value)
2998 @var{register} identifies the register, for a description of the acceptable
2999 values see @ref{gdbpy_frame_read_register,,Frame.read_register}.
3000 @var{value} is a register value (a @code{gdb.Value} object).
3003 @subheading The @code{gdb.unwinder} Module
3005 @value{GDBN} comes with a @code{gdb.unwinder} module which contains
3006 the following classes:
3008 @deftp {class} gdb.unwinder.Unwinder
3009 The @code{Unwinder} class is a base class from which user created
3010 unwinders can derive, though it is not required that unwinders derive
3011 from this class, so long as any user created unwinder has the required
3012 @code{name} and @code{enabled} attributes.
3014 @defun gdb.unwinder.Unwinder.__init__(name)
3015 The @var{name} is a string used to reference this unwinder within some
3016 @value{GDBN} commands (@pxref{Managing Registered Unwinders}).
3019 @defvar gdb.unwinder.name
3020 A read-only attribute which is a string, the name of this unwinder.
3023 @defvar gdb.unwinder.enabled
3024 A modifiable attribute containing a boolean; when @code{True}, the
3025 unwinder is enabled, and will be used by @value{GDBN}. When
3026 @code{False}, the unwinder has been disabled, and will not be used.
3030 @anchor{gdb.unwinder.FrameId}
3031 @deftp {class} gdb.unwinder.FrameId
3032 This is a class suitable for being used as the frame-id when calling
3033 @code{gdb.PendingFrame.create_unwind_info}. It is not required to use
3034 this class, any class with the required attribute
3035 (@pxref{gdb.PendingFrame.create_unwind_info}) will be accepted, but in
3036 most cases this class will be sufficient.
3038 @code{gdb.unwinder.FrameId} has the following method:
3040 @defun gdb.unwinder.FrameId.__init__(sp, pc, special = @code{None})
3041 The @var{sp} and @var{pc} arguments are required and should be either
3042 a @code{gdb.Value} object, or an integer.
3044 The @var{special} argument is optional; if specified, it should be a
3045 @code{gdb.Value} object, or an integer.
3048 @code{gdb.unwinder.FrameId} has the following read-only attributes:
3050 @defvar gdb.unwinder.sp
3051 The @var{sp} value passed to the constructor.
3054 @defvar gdb.unwinder.pc
3055 The @var{pc} value passed to the constructor.
3058 @defvar gdb.unwinder.special
3059 The @var{special} value passed to the constructor, or @code{None} if
3060 no such value was passed.
3064 @subheading Registering an Unwinder
3066 Object files and program spaces can have unwinders registered with
3067 them. In addition, you can register unwinders globally.
3069 The @code{gdb.unwinders} module provides the function to register an
3072 @defun gdb.unwinder.register_unwinder (locus, unwinder, replace=False)
3073 @var{locus} specifies to which unwinder list to prepend the
3074 @var{unwinder}. It can be either an object file (@pxref{Objfiles In
3075 Python}), a program space (@pxref{Progspaces In Python}), or
3076 @code{None}, in which case the unwinder is registered globally. The
3077 newly added @var{unwinder} will be called before any other unwinder
3078 from the same locus. Two unwinders in the same locus cannot have the
3079 same name. An attempt to add an unwinder with an already existing
3080 name raises an exception unless @var{replace} is @code{True}, in which
3081 case the old unwinder is deleted and the new unwinder is registered in
3084 @value{GDBN} first calls the unwinders from all the object files in no
3085 particular order, then the unwinders from the current program space,
3086 then the globally registered unwinders, and finally the unwinders
3087 builtin to @value{GDBN}.
3090 @subheading Unwinder Skeleton Code
3092 Here is an example of how to structure a user created unwinder:
3095 from gdb.unwinder import Unwinder, FrameId
3097 class MyUnwinder(Unwinder):
3099 super().__init___("MyUnwinder_Name")
3101 def __call__(self, pending_frame):
3102 if not <we recognize frame>:
3105 # Create a FrameID. Usually the frame is identified by a
3106 # stack pointer and the function address.
3107 sp = ... compute a stack address ...
3108 pc = ... compute function address ...
3109 unwind_info = pending_frame.create_unwind_info(FrameId(sp, pc))
3111 # Find the values of the registers in the caller's frame and
3112 # save them in the result:
3113 unwind_info.add_saved_register(<register-number>, <register-value>)
3116 # Return the result:
3119 gdb.unwinder.register_unwinder(<locus>, MyUnwinder(), <replace>)
3122 @anchor{Managing Registered Unwinders}
3123 @subheading Managing Registered Unwinders
3124 @value{GDBN} defines 3 commands to manage registered unwinders. These
3128 @item info unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
3129 Lists all registered unwinders. Arguments @var{locus} and
3130 @var{name-regexp} are both optional and can be used to filter which
3131 unwinders are listed.
3133 The @var{locus} argument should be either @kbd{global},
3134 @kbd{progspace}, or the name of an object file. Only unwinders
3135 registered for the specified locus will be listed.
3137 The @var{name-regexp} is a regular expression used to match against
3138 unwinder names. When trying to match against unwinder names that
3139 include a string enclose @var{name-regexp} in quotes.
3140 @item disable unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
3141 The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
3142 unwinder} above, but instead of listing the matching unwinders, all of
3143 the matching unwinders are disabled. The @code{enabled} field of each
3144 matching unwinder is set to @code{False}.
3145 @item enable unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
3146 The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
3147 unwinder} above, but instead of listing the matching unwinders, all of
3148 the matching unwinders are enabled. The @code{enabled} field of each
3149 matching unwinder is set to @code{True}.
3152 @node Xmethods In Python
3153 @subsubsection Xmethods In Python
3154 @cindex xmethods in Python
3156 @dfn{Xmethods} are additional methods or replacements for existing
3157 methods of a C@t{++} class. This feature is useful for those cases
3158 where a method defined in C@t{++} source code could be inlined or
3159 optimized out by the compiler, making it unavailable to @value{GDBN}.
3160 For such cases, one can define an xmethod to serve as a replacement
3161 for the method defined in the C@t{++} source code. @value{GDBN} will
3162 then invoke the xmethod, instead of the C@t{++} method, to
3163 evaluate expressions. One can also use xmethods when debugging
3164 with core files. Moreover, when debugging live programs, invoking an
3165 xmethod need not involve running the inferior (which can potentially
3166 perturb its state). Hence, even if the C@t{++} method is available, it
3167 is better to use its replacement xmethod if one is defined.
3169 The xmethods feature in Python is available via the concepts of an
3170 @dfn{xmethod matcher} and an @dfn{xmethod worker}. To
3171 implement an xmethod, one has to implement a matcher and a
3172 corresponding worker for it (more than one worker can be
3173 implemented, each catering to a different overloaded instance of the
3174 method). Internally, @value{GDBN} invokes the @code{match} method of a
3175 matcher to match the class type and method name. On a match, the
3176 @code{match} method returns a list of matching @emph{worker} objects.
3177 Each worker object typically corresponds to an overloaded instance of
3178 the xmethod. They implement a @code{get_arg_types} method which
3179 returns a sequence of types corresponding to the arguments the xmethod
3180 requires. @value{GDBN} uses this sequence of types to perform
3181 overload resolution and picks a winning xmethod worker. A winner
3182 is also selected from among the methods @value{GDBN} finds in the
3183 C@t{++} source code. Next, the winning xmethod worker and the
3184 winning C@t{++} method are compared to select an overall winner. In
3185 case of a tie between a xmethod worker and a C@t{++} method, the
3186 xmethod worker is selected as the winner. That is, if a winning
3187 xmethod worker is found to be equivalent to the winning C@t{++}
3188 method, then the xmethod worker is treated as a replacement for
3189 the C@t{++} method. @value{GDBN} uses the overall winner to invoke the
3190 method. If the winning xmethod worker is the overall winner, then
3191 the corresponding xmethod is invoked via the @code{__call__} method
3192 of the worker object.
3194 If one wants to implement an xmethod as a replacement for an
3195 existing C@t{++} method, then they have to implement an equivalent
3196 xmethod which has exactly the same name and takes arguments of
3197 exactly the same type as the C@t{++} method. If the user wants to
3198 invoke the C@t{++} method even though a replacement xmethod is
3199 available for that method, then they can disable the xmethod.
3201 @xref{Xmethod API}, for API to implement xmethods in Python.
3202 @xref{Writing an Xmethod}, for implementing xmethods in Python.
3205 @subsubsection Xmethod API
3208 The @value{GDBN} Python API provides classes, interfaces and functions
3209 to implement, register and manipulate xmethods.
3210 @xref{Xmethods In Python}.
3212 An xmethod matcher should be an instance of a class derived from
3213 @code{XMethodMatcher} defined in the module @code{gdb.xmethod}, or an
3214 object with similar interface and attributes. An instance of
3215 @code{XMethodMatcher} has the following attributes:
3218 The name of the matcher.
3222 A boolean value indicating whether the matcher is enabled or disabled.
3226 A list of named methods managed by the matcher. Each object in the list
3227 is an instance of the class @code{XMethod} defined in the module
3228 @code{gdb.xmethod}, or any object with the following attributes:
3233 Name of the xmethod which should be unique for each xmethod
3234 managed by the matcher.
3237 A boolean value indicating whether the xmethod is enabled or
3242 The class @code{XMethod} is a convenience class with same
3243 attributes as above along with the following constructor:
3245 @defun XMethod.__init__ (self, name)
3246 Constructs an enabled xmethod with name @var{name}.
3251 The @code{XMethodMatcher} class has the following methods:
3253 @defun XMethodMatcher.__init__ (self, name)
3254 Constructs an enabled xmethod matcher with name @var{name}. The
3255 @code{methods} attribute is initialized to @code{None}.
3258 @defun XMethodMatcher.match (self, class_type, method_name)
3259 Derived classes should override this method. It should return a
3260 xmethod worker object (or a sequence of xmethod worker
3261 objects) matching the @var{class_type} and @var{method_name}.
3262 @var{class_type} is a @code{gdb.Type} object, and @var{method_name}
3263 is a string value. If the matcher manages named methods as listed in
3264 its @code{methods} attribute, then only those worker objects whose
3265 corresponding entries in the @code{methods} list are enabled should be
3269 An xmethod worker should be an instance of a class derived from
3270 @code{XMethodWorker} defined in the module @code{gdb.xmethod},
3271 or support the following interface:
3273 @defun XMethodWorker.get_arg_types (self)
3274 This method returns a sequence of @code{gdb.Type} objects corresponding
3275 to the arguments that the xmethod takes. It can return an empty
3276 sequence or @code{None} if the xmethod does not take any arguments.
3277 If the xmethod takes a single argument, then a single
3278 @code{gdb.Type} object corresponding to it can be returned.
3281 @defun XMethodWorker.get_result_type (self, *args)
3282 This method returns a @code{gdb.Type} object representing the type
3283 of the result of invoking this xmethod.
3284 The @var{args} argument is the same tuple of arguments that would be
3285 passed to the @code{__call__} method of this worker.
3288 @defun XMethodWorker.__call__ (self, *args)
3289 This is the method which does the @emph{work} of the xmethod. The
3290 @var{args} arguments is the tuple of arguments to the xmethod. Each
3291 element in this tuple is a gdb.Value object. The first element is
3292 always the @code{this} pointer value.
3295 For @value{GDBN} to lookup xmethods, the xmethod matchers
3296 should be registered using the following function defined in the module
3299 @defun register_xmethod_matcher (locus, matcher, replace=False)
3300 The @code{matcher} is registered with @code{locus}, replacing an
3301 existing matcher with the same name as @code{matcher} if
3302 @code{replace} is @code{True}. @code{locus} can be a
3303 @code{gdb.Objfile} object (@pxref{Objfiles In Python}), or a
3304 @code{gdb.Progspace} object (@pxref{Progspaces In Python}), or
3305 @code{None}. If it is @code{None}, then @code{matcher} is registered
3309 @node Writing an Xmethod
3310 @subsubsection Writing an Xmethod
3311 @cindex writing xmethods in Python
3313 Implementing xmethods in Python will require implementing xmethod
3314 matchers and xmethod workers (@pxref{Xmethods In Python}). Consider
3315 the following C@t{++} class:
3321 MyClass (int a) : a_(a) @{ @}
3323 int geta (void) @{ return a_; @}
3324 int operator+ (int b);
3331 MyClass::operator+ (int b)
3338 Let us define two xmethods for the class @code{MyClass}, one
3339 replacing the method @code{geta}, and another adding an overloaded
3340 flavor of @code{operator+} which takes a @code{MyClass} argument (the
3341 C@t{++} code above already has an overloaded @code{operator+}
3342 which takes an @code{int} argument). The xmethod matcher can be
3346 class MyClass_geta(gdb.xmethod.XMethod):
3348 gdb.xmethod.XMethod.__init__(self, 'geta')
3350 def get_worker(self, method_name):
3351 if method_name == 'geta':
3352 return MyClassWorker_geta()
3355 class MyClass_sum(gdb.xmethod.XMethod):
3357 gdb.xmethod.XMethod.__init__(self, 'sum')
3359 def get_worker(self, method_name):
3360 if method_name == 'operator+':
3361 return MyClassWorker_plus()
3364 class MyClassMatcher(gdb.xmethod.XMethodMatcher):
3366 gdb.xmethod.XMethodMatcher.__init__(self, 'MyClassMatcher')
3367 # List of methods 'managed' by this matcher
3368 self.methods = [MyClass_geta(), MyClass_sum()]
3370 def match(self, class_type, method_name):
3371 if class_type.tag != 'MyClass':
3374 for method in self.methods:
3376 worker = method.get_worker(method_name)
3378 workers.append(worker)
3384 Notice that the @code{match} method of @code{MyClassMatcher} returns
3385 a worker object of type @code{MyClassWorker_geta} for the @code{geta}
3386 method, and a worker object of type @code{MyClassWorker_plus} for the
3387 @code{operator+} method. This is done indirectly via helper classes
3388 derived from @code{gdb.xmethod.XMethod}. One does not need to use the
3389 @code{methods} attribute in a matcher as it is optional. However, if a
3390 matcher manages more than one xmethod, it is a good practice to list the
3391 xmethods in the @code{methods} attribute of the matcher. This will then
3392 facilitate enabling and disabling individual xmethods via the
3393 @code{enable/disable} commands. Notice also that a worker object is
3394 returned only if the corresponding entry in the @code{methods} attribute
3395 of the matcher is enabled.
3397 The implementation of the worker classes returned by the matcher setup
3398 above is as follows:
3401 class MyClassWorker_geta(gdb.xmethod.XMethodWorker):
3402 def get_arg_types(self):
3405 def get_result_type(self, obj):
3406 return gdb.lookup_type('int')
3408 def __call__(self, obj):
3412 class MyClassWorker_plus(gdb.xmethod.XMethodWorker):
3413 def get_arg_types(self):
3414 return gdb.lookup_type('MyClass')
3416 def get_result_type(self, obj):
3417 return gdb.lookup_type('int')
3419 def __call__(self, obj, other):
3420 return obj['a_'] + other['a_']
3423 For @value{GDBN} to actually lookup a xmethod, it has to be
3424 registered with it. The matcher defined above is registered with
3425 @value{GDBN} globally as follows:
3428 gdb.xmethod.register_xmethod_matcher(None, MyClassMatcher())
3431 If an object @code{obj} of type @code{MyClass} is initialized in C@t{++}
3439 then, after loading the Python script defining the xmethod matchers
3440 and workers into @value{GDBN}, invoking the method @code{geta} or using
3441 the operator @code{+} on @code{obj} will invoke the xmethods
3452 Consider another example with a C++ template class:
3459 MyTemplate () : dsize_(10), data_ (new T [10]) @{ @}
3460 ~MyTemplate () @{ delete [] data_; @}
3462 int footprint (void)
3464 return sizeof (T) * dsize_ + sizeof (MyTemplate<T>);
3473 Let us implement an xmethod for the above class which serves as a
3474 replacement for the @code{footprint} method. The full code listing
3475 of the xmethod workers and xmethod matchers is as follows:
3478 class MyTemplateWorker_footprint(gdb.xmethod.XMethodWorker):
3479 def __init__(self, class_type):
3480 self.class_type = class_type
3482 def get_arg_types(self):
3485 def get_result_type(self):
3486 return gdb.lookup_type('int')
3488 def __call__(self, obj):
3489 return (self.class_type.sizeof +
3491 self.class_type.template_argument(0).sizeof)
3494 class MyTemplateMatcher_footprint(gdb.xmethod.XMethodMatcher):
3496 gdb.xmethod.XMethodMatcher.__init__(self, 'MyTemplateMatcher')
3498 def match(self, class_type, method_name):
3499 if (re.match('MyTemplate<[ \t\n]*[_a-zA-Z][ _a-zA-Z0-9]*>',
3501 method_name == 'footprint'):
3502 return MyTemplateWorker_footprint(class_type)
3505 Notice that, in this example, we have not used the @code{methods}
3506 attribute of the matcher as the matcher manages only one xmethod. The
3507 user can enable/disable this xmethod by enabling/disabling the matcher
3510 @node Inferiors In Python
3511 @subsubsection Inferiors In Python
3512 @cindex inferiors in Python
3514 @findex gdb.Inferior
3515 Programs which are being run under @value{GDBN} are called inferiors
3516 (@pxref{Inferiors Connections and Programs}). Python scripts can access
3517 information about and manipulate inferiors controlled by @value{GDBN}
3518 via objects of the @code{gdb.Inferior} class.
3520 The following inferior-related functions are available in the @code{gdb}
3523 @defun gdb.inferiors ()
3524 Return a tuple containing all inferior objects.
3527 @defun gdb.selected_inferior ()
3528 Return an object representing the current inferior.
3531 A @code{gdb.Inferior} object has the following attributes:
3533 @defvar Inferior.num
3534 ID of inferior, as assigned by @value{GDBN}. You can use this to make
3535 Python breakpoints inferior-specific, for example
3536 (@pxref{python_breakpoint_inferior,,The Breakpoint.inferior
3540 @anchor{gdbpy_inferior_connection}
3541 @defvar Inferior.connection
3542 The @code{gdb.TargetConnection} for this inferior (@pxref{Connections
3543 In Python}), or @code{None} if this inferior has no connection.
3546 @defvar Inferior.connection_num
3547 ID of inferior's connection as assigned by @value{GDBN}, or None if
3548 the inferior is not connected to a target. @xref{Inferiors Connections
3549 and Programs}. This is equivalent to
3550 @code{gdb.Inferior.connection.num} in the case where
3551 @code{gdb.Inferior.connection} is not @code{None}.
3554 @defvar Inferior.pid
3555 Process ID of the inferior, as assigned by the underlying operating
3559 @defvar Inferior.was_attached
3560 Boolean signaling whether the inferior was created using `attach', or
3561 started by @value{GDBN} itself.
3564 @defvar Inferior.main_name
3565 A string holding the name of this inferior's ``main'' function, if it
3566 can be determined. If the name of main is not known, this is
3570 @defvar Inferior.progspace
3571 The inferior's program space. @xref{Progspaces In Python}.
3574 @defvar Inferior.arguments
3575 The inferior's command line arguments, if known. This corresponds to
3576 the @code{set args} and @code{show args} commands. @xref{Arguments}.
3578 When accessed, the value is a string holding all the arguments. The
3579 contents are quoted as they would be when passed to the shell. If
3580 there are no arguments, the value is @code{None}.
3582 Either a string or a sequence of strings can be assigned to this
3583 attribute. When a string is assigned, it is assumed to have any
3584 necessary quoting for the shell; when a sequence is assigned, the
3585 quoting is applied by @value{GDBN}.
3588 A @code{gdb.Inferior} object has the following methods:
3590 @defun Inferior.is_valid ()
3591 Returns @code{True} if the @code{gdb.Inferior} object is valid,
3592 @code{False} if not. A @code{gdb.Inferior} object will become invalid
3593 if the inferior no longer exists within @value{GDBN}. All other
3594 @code{gdb.Inferior} methods will throw an exception if it is invalid
3595 at the time the method is called.
3598 @defun Inferior.threads ()
3599 This method returns a tuple holding all the threads which are valid
3600 when it is called. If there are no valid threads, the method will
3601 return an empty tuple.
3604 @defun Inferior.architecture ()
3605 Return the @code{gdb.Architecture} (@pxref{Architectures In Python})
3606 for this inferior. This represents the architecture of the inferior
3607 as a whole. Some platforms can have multiple architectures in a
3608 single address space, so this may not match the architecture of a
3609 particular frame (@pxref{Frames In Python}).
3612 @anchor{gdbpy_inferior_read_memory}
3613 @defun Inferior.read_memory (address, length)
3614 Read @var{length} addressable memory units from the inferior, starting
3615 at @var{address}. Returns a @code{memoryview} object, which behaves
3616 much like an array or a string. It can be modified and given to the
3617 @code{Inferior.write_memory} function.
3620 @defun Inferior.write_memory (address, buffer @r{[}, length@r{]})
3621 Write the contents of @var{buffer} to the inferior, starting at
3622 @var{address}. The @var{buffer} parameter must be a Python object
3623 which supports the buffer protocol, i.e., a string, an array or the
3624 object returned from @code{Inferior.read_memory}. If given, @var{length}
3625 determines the number of addressable memory units from @var{buffer} to be
3629 @defun Inferior.search_memory (address, length, pattern)
3630 Search a region of the inferior memory starting at @var{address} with
3631 the given @var{length} using the search pattern supplied in
3632 @var{pattern}. The @var{pattern} parameter must be a Python object
3633 which supports the buffer protocol, i.e., a string, an array or the
3634 object returned from @code{gdb.read_memory}. Returns a Python @code{Long}
3635 containing the address where the pattern was found, or @code{None} if
3636 the pattern could not be found.
3639 @findex Inferior.thread_from_thread_handle
3640 @defun Inferior.thread_from_handle (handle)
3641 Return the thread object corresponding to @var{handle}, a thread
3642 library specific data structure such as @code{pthread_t} for pthreads
3643 library implementations.
3645 The function @code{Inferior.thread_from_thread_handle} provides
3646 the same functionality, but use of @code{Inferior.thread_from_thread_handle}
3651 The environment that will be passed to the inferior can be changed
3652 from Python by using the following methods. These methods only take
3653 effect when the inferior is started -- they will not affect an
3654 inferior that is already executing.
3656 @defun Inferior.clear_env ()
3657 Clear the current environment variables that will be passed to this
3661 @defun Inferior.set_env (name, value)
3662 Set the environment variable @var{name} to have the indicated value.
3663 Both parameters must be strings.
3666 @defun Inferior.unset_env (name)
3667 Unset the environment variable @var{name}. @var{name} must be a
3671 One may add arbitrary attributes to @code{gdb.Inferior} objects in the
3672 usual Python way. This is useful if, for example, one needs to do
3673 some extra record keeping associated with the inferior.
3675 @anchor{choosing attribute names}
3676 When selecting a name for a new attribute, avoid starting the new
3677 attribute name with a lower case letter; future attributes added by
3678 @value{GDBN} will start with a lower case letter. Additionally, avoid
3679 starting attribute names with two underscore characters, as these
3680 could clash with Python builtin attribute names.
3682 In this contrived example we record the time when an inferior last
3687 (@value{GDBP}) python
3690 def thread_stopped(event):
3691 if event.inferior_thread is not None:
3692 thread = event.inferior_thread
3694 thread = gdb.selected_thread()
3695 inferior = thread.inferior
3696 inferior._last_stop_time = datetime.datetime.today()
3698 gdb.events.stop.connect(thread_stopped)
3701 (@value{GDBP}) file /tmp/hello
3702 Reading symbols from /tmp/hello...
3703 (@value{GDBP}) start
3704 Temporary breakpoint 1 at 0x401198: file /tmp/hello.c, line 18.
3705 Starting program: /tmp/hello
3707 Temporary breakpoint 1, main () at /tmp/hello.c:18
3708 18 printf ("Hello World\n");
3709 (@value{GDBP}) python print(gdb.selected_inferior()._last_stop_time)
3710 2024-01-04 14:48:41.347036
3714 @node Events In Python
3715 @subsubsection Events In Python
3716 @cindex inferior events in Python
3718 @value{GDBN} provides a general event facility so that Python code can be
3719 notified of various state changes, particularly changes that occur in
3722 An @dfn{event} is just an object that describes some state change. The
3723 type of the object and its attributes will vary depending on the details
3724 of the change. All the existing events are described below.
3726 In order to be notified of an event, you must register an event handler
3727 with an @dfn{event registry}. An event registry is an object in the
3728 @code{gdb.events} module which dispatches particular events. A registry
3729 provides methods to register and unregister event handlers:
3731 @defun EventRegistry.connect (object)
3732 Add the given callable @var{object} to the registry. This object will be
3733 called when an event corresponding to this registry occurs.
3736 @defun EventRegistry.disconnect (object)
3737 Remove the given @var{object} from the registry. Once removed, the object
3738 will no longer receive notifications of events.
3744 def exit_handler (event):
3745 print ("event type: exit")
3746 if hasattr (event, 'exit_code'):
3747 print ("exit code: %d" % (event.exit_code))
3749 print ("exit code not available")
3751 gdb.events.exited.connect (exit_handler)
3754 In the above example we connect our handler @code{exit_handler} to the
3755 registry @code{events.exited}. Once connected, @code{exit_handler} gets
3756 called when the inferior exits. The argument @dfn{event} in this example is
3757 of type @code{gdb.ExitedEvent}. As you can see in the example the
3758 @code{ExitedEvent} object has an attribute which indicates the exit code of
3761 Some events can be thread specific when @value{GDBN} is running in
3762 non-stop mode. When represented in Python, these events all extend
3763 @code{gdb.ThreadEvent}. This event is a base class and is never
3764 emitted directly; instead, events which are emitted by this or other
3765 modules might extend this event. Examples of these events are
3766 @code{gdb.BreakpointEvent} and @code{gdb.ContinueEvent}.
3767 @code{gdb.ThreadEvent} holds the following attributes:
3769 @defvar ThreadEvent.inferior_thread
3770 In non-stop mode this attribute will be set to the specific thread which was
3771 involved in the emitted event. Otherwise, it will be set to @code{None}.
3774 The following is a listing of the event registries that are available and
3775 details of the events they emit:
3780 Emits @code{gdb.ContinueEvent}, which extends @code{gdb.ThreadEvent}.
3781 This event indicates that the inferior has been continued after a
3782 stop. For inherited attribute refer to @code{gdb.ThreadEvent} above.
3785 Emits @code{events.ExitedEvent}, which indicates that the inferior has
3786 exited. @code{events.ExitedEvent} has two attributes:
3788 @defvar ExitedEvent.exit_code
3789 An integer representing the exit code, if available, which the inferior
3790 has returned. (The exit code could be unavailable if, for example,
3791 @value{GDBN} detaches from the inferior.) If the exit code is unavailable,
3792 the attribute does not exist.
3795 @defvar ExitedEvent.inferior
3796 A reference to the inferior which triggered the @code{exited} event.
3800 Emits @code{gdb.StopEvent}, which extends @code{gdb.ThreadEvent}.
3802 Indicates that the inferior has stopped. All events emitted by this
3803 registry extend @code{gdb.StopEvent}. As a child of
3804 @code{gdb.ThreadEvent}, @code{gdb.StopEvent} will indicate the stopped
3805 thread when @value{GDBN} is running in non-stop mode. Refer to
3806 @code{gdb.ThreadEvent} above for more details.
3808 @code{gdb.StopEvent} has the following additional attributes:
3810 @defvar StopEvent.details
3811 A dictionary holding any details relevant to the stop. The exact keys
3812 and values depend on the type of stop, but are identical to the
3813 corresponding MI output (@pxref{GDB/MI Async Records}).
3815 A dictionary was used for this (rather than adding attributes directly
3816 to the event object) so that the MI keys could be used unchanged.
3818 When a @code{StopEvent} results from a @code{finish} command, it will
3819 also hold the return value from the function, if that is available.
3820 This will be an entry named @samp{return-value} in the @code{details}
3821 dictionary. The value of this entry will be a @code{gdb.Value}
3825 Emits @code{gdb.SignalEvent}, which extends @code{gdb.StopEvent}.
3827 This event indicates that the inferior or one of its threads has
3828 received a signal. @code{gdb.SignalEvent} has the following
3831 @defvar SignalEvent.stop_signal
3832 A string representing the signal received by the inferior. A list of possible
3833 signal values can be obtained by running the command @code{info signals} in
3834 the @value{GDBN} command prompt.
3837 Also emits @code{gdb.BreakpointEvent}, which extends
3838 @code{gdb.StopEvent}.
3840 @code{gdb.BreakpointEvent} event indicates that one or more breakpoints have
3841 been hit, and has the following attributes:
3843 @defvar BreakpointEvent.breakpoints
3844 A sequence containing references to all the breakpoints (type
3845 @code{gdb.Breakpoint}) that were hit.
3846 @xref{Breakpoints In Python}, for details of the @code{gdb.Breakpoint} object.
3849 @defvar BreakpointEvent.breakpoint
3850 A reference to the first breakpoint that was hit. This attribute is
3851 maintained for backward compatibility and is now deprecated in favor
3852 of the @code{gdb.BreakpointEvent.breakpoints} attribute.
3855 @item events.new_objfile
3856 Emits @code{gdb.NewObjFileEvent} which indicates that a new object file has
3857 been loaded by @value{GDBN}. @code{gdb.NewObjFileEvent} has one attribute:
3859 @defvar NewObjFileEvent.new_objfile
3860 A reference to the object file (@code{gdb.Objfile}) which has been loaded.
3861 @xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
3864 @item events.free_objfile
3865 Emits @code{gdb.FreeObjFileEvent} which indicates that an object file
3866 is about to be removed from @value{GDBN}. One reason this can happen
3867 is when the inferior calls @code{dlclose}.
3868 @code{gdb.FreeObjFileEvent} has one attribute:
3870 @defvar FreeObjFileEvent.objfile
3871 A reference to the object file (@code{gdb.Objfile}) which will be unloaded.
3872 @xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
3875 @item events.clear_objfiles
3876 Emits @code{gdb.ClearObjFilesEvent} which indicates that the list of object
3877 files for a program space has been reset.
3878 @code{gdb.ClearObjFilesEvent} has one attribute:
3880 @defvar ClearObjFilesEvent.progspace
3881 A reference to the program space (@code{gdb.Progspace}) whose objfile list has
3882 been cleared. @xref{Progspaces In Python}.
3885 @item events.inferior_call
3886 Emits events just before and after a function in the inferior is
3887 called by @value{GDBN}. Before an inferior call, this emits an event
3888 of type @code{gdb.InferiorCallPreEvent}, and after an inferior call,
3889 this emits an event of type @code{gdb.InferiorCallPostEvent}.
3892 @tindex gdb.InferiorCallPreEvent
3893 @item @code{gdb.InferiorCallPreEvent}
3894 Indicates that a function in the inferior is about to be called.
3896 @defvar InferiorCallPreEvent.ptid
3897 The thread in which the call will be run.
3900 @defvar InferiorCallPreEvent.address
3901 The location of the function to be called.
3904 @tindex gdb.InferiorCallPostEvent
3905 @item @code{gdb.InferiorCallPostEvent}
3906 Indicates that a function in the inferior has just been called.
3908 @defvar InferiorCallPostEvent.ptid
3909 The thread in which the call was run.
3912 @defvar InferiorCallPostEvent.address
3913 The location of the function that was called.
3917 @item events.memory_changed
3918 Emits @code{gdb.MemoryChangedEvent} which indicates that the memory of the
3919 inferior has been modified by the @value{GDBN} user, for instance via a
3920 command like @w{@code{set *addr = value}}. The event has the following
3923 @defvar MemoryChangedEvent.address
3924 The start address of the changed region.
3927 @defvar MemoryChangedEvent.length
3928 Length in bytes of the changed region.
3931 @item events.register_changed
3932 Emits @code{gdb.RegisterChangedEvent} which indicates that a register in the
3933 inferior has been modified by the @value{GDBN} user.
3935 @defvar RegisterChangedEvent.frame
3936 A gdb.Frame object representing the frame in which the register was modified.
3938 @defvar RegisterChangedEvent.regnum
3939 Denotes which register was modified.
3942 @item events.breakpoint_created
3943 This is emitted when a new breakpoint has been created. The argument
3944 that is passed is the new @code{gdb.Breakpoint} object.
3946 @item events.breakpoint_modified
3947 This is emitted when a breakpoint has been modified in some way. The
3948 argument that is passed is the new @code{gdb.Breakpoint} object.
3950 @item events.breakpoint_deleted
3951 This is emitted when a breakpoint has been deleted. The argument that
3952 is passed is the @code{gdb.Breakpoint} object. When this event is
3953 emitted, the @code{gdb.Breakpoint} object will already be in its
3954 invalid state; that is, the @code{is_valid} method will return
3957 @item events.before_prompt
3958 This event carries no payload. It is emitted each time @value{GDBN}
3959 presents a prompt to the user.
3961 @item events.new_inferior
3962 This is emitted when a new inferior is created. Note that the
3963 inferior is not necessarily running; in fact, it may not even have an
3964 associated executable.
3966 The event is of type @code{gdb.NewInferiorEvent}. This has a single
3969 @defvar NewInferiorEvent.inferior
3970 The new inferior, a @code{gdb.Inferior} object.
3973 @item events.inferior_deleted
3974 This is emitted when an inferior has been deleted. Note that this is
3975 not the same as process exit; it is notified when the inferior itself
3976 is removed, say via @code{remove-inferiors}.
3978 The event is of type @code{gdb.InferiorDeletedEvent}. This has a single
3981 @defvar InferiorDeletedEvent.inferior
3982 The inferior that is being removed, a @code{gdb.Inferior} object.
3985 @item events.new_thread
3986 This is emitted when @value{GDBN} notices a new thread. The event is of
3987 type @code{gdb.NewThreadEvent}, which extends @code{gdb.ThreadEvent}.
3988 This has a single attribute:
3990 @defvar NewThreadEvent.inferior_thread
3994 @item events.thread_exited
3995 This is emitted when @value{GDBN} notices a thread has exited. The event
3996 is of type @code{gdb.ThreadExitedEvent} which extends @code{gdb.ThreadEvent}.
3997 This has a single attribute:
3999 @defvar ThreadExitedEvent.inferior_thread
4003 @item events.gdb_exiting
4004 This is emitted when @value{GDBN} exits. This event is not emitted if
4005 @value{GDBN} exits as a result of an internal error, or after an
4006 unexpected signal. The event is of type @code{gdb.GdbExitingEvent},
4007 which has a single attribute:
4009 @defvar GdbExitingEvent.exit_code
4010 An integer, the value of the exit code @value{GDBN} will return.
4013 @item events.connection_removed
4014 This is emitted when @value{GDBN} removes a connection
4015 (@pxref{Connections In Python}). The event is of type
4016 @code{gdb.ConnectionEvent}. This has a single read-only attribute:
4018 @defvar ConnectionEvent.connection
4019 The @code{gdb.TargetConnection} that is being removed.
4022 @item events.executable_changed
4023 Emits @code{gdb.ExecutableChangedEvent} which indicates that the
4024 @code{gdb.Progspace.executable_filename} has changed.
4026 This event is emitted when either the value of
4027 @code{gdb.Progspace.executable_filename } has changed to name a
4028 different file, or the executable file named by
4029 @code{gdb.Progspace.executable_filename} has changed on disk, and
4030 @value{GDBN} has therefore reloaded it.
4032 @defvar ExecutableChangedEvent.progspace
4033 The @code{gdb.Progspace} in which the current executable has changed.
4034 The file name of the updated executable will be visible in
4035 @code{gdb.Progspace.executable_filename} (@pxref{Progspaces In Python}).
4037 @defvar ExecutableChangedEvent.reload
4038 This attribute will be @code{True} if the value of
4039 @code{gdb.Progspace.executable_filename} didn't change, but the file
4040 it names changed on disk instead, and @value{GDBN} reloaded it.
4042 When this attribute is @code{False}, the value in
4043 @code{gdb.Progspace.executable_filename} was changed to name a
4047 Remember that @value{GDBN} tracks the executable file and the symbol
4048 file separately, these are visible as
4049 @code{gdb.Progspace.executable_filename} and
4050 @code{gdb.Progspace.filename} respectively. When using the @kbd{file}
4051 command, @value{GDBN} updates both of these fields, but the executable
4052 file is updated first, so when this event is emitted, the executable
4053 filename will have changed, but the symbol filename might still hold
4056 @item events.new_progspace
4057 This is emitted when @value{GDBN} adds a new program space
4058 (@pxref{Progspaces In Python,,Program Spaces In Python}). The event
4059 is of type @code{gdb.NewProgspaceEvent}, and has a single read-only
4062 @defvar NewProgspaceEvent.progspace
4063 The @code{gdb.Progspace} that was added to @value{GDBN}.
4066 No @code{NewProgspaceEvent} is emitted for the very first program
4067 space, which is assigned to the first inferior. This first program
4068 space is created within @value{GDBN} before any Python scripts are
4071 @item events.free_progspace
4072 This is emitted when @value{GDBN} removes a program space
4073 (@pxref{Progspaces In Python,,Program Spaces In Python}), for example
4074 as a result of the @kbd{remove-inferiors} command
4075 (@pxref{remove_inferiors_cli,,@kbd{remove-inferiors}}). The event is
4076 of type @code{gdb.FreeProgspaceEvent}, and has a single read-only
4079 @defvar FreeProgspaceEvent.progspace
4080 The @code{gdb.Progspace} that is about to be removed from
4084 @item events.tui_enabled
4085 This is emitted when the TUI is enabled or disabled. The event is of
4086 type @code{gdb.TuiEnabledEvent}, which has a single read-only
4089 @defvar TuiStatusEvent.enabled
4090 If the TUI has just been enabled, this is @code{True}; otherwise it is
4096 @node Threads In Python
4097 @subsubsection Threads In Python
4098 @cindex threads in python
4100 @findex gdb.InferiorThread
4101 Python scripts can access information about, and manipulate inferior threads
4102 controlled by @value{GDBN}, via objects of the @code{gdb.InferiorThread} class.
4104 The following thread-related functions are available in the @code{gdb}
4107 @defun gdb.selected_thread ()
4108 This function returns the thread object for the selected thread. If there
4109 is no selected thread, this will return @code{None}.
4112 To get the list of threads for an inferior, use the @code{Inferior.threads()}
4113 method. @xref{Inferiors In Python}.
4115 A @code{gdb.InferiorThread} object has the following attributes:
4117 @defvar InferiorThread.name
4118 The name of the thread. If the user specified a name using
4119 @code{thread name}, then this returns that name. Otherwise, if an
4120 OS-supplied name is available, then it is returned. Otherwise, this
4121 returns @code{None}.
4123 This attribute can be assigned to. The new value must be a string
4124 object, which sets the new name, or @code{None}, which removes any
4125 user-specified thread name.
4128 @defvar InferiorThread.num
4129 The per-inferior number of the thread, as assigned by GDB.
4132 @defvar InferiorThread.global_num
4133 The global ID of the thread, as assigned by GDB. You can use this to
4134 make Python breakpoints thread-specific, for example
4135 (@pxref{python_breakpoint_thread,,The Breakpoint.thread attribute}).
4138 @anchor{inferior_thread_ptid}
4139 @defvar InferiorThread.ptid
4140 ID of the thread, as assigned by the operating system. This attribute is a
4141 tuple containing three integers. The first is the Process ID (PID); the second
4142 is the Lightweight Process ID (LWPID), and the third is the Thread ID (TID).
4143 Either the LWPID or TID may be 0, which indicates that the operating system
4144 does not use that identifier.
4147 @defvar InferiorThread.ptid_string
4148 This read-only attribute contains a string representing
4149 @code{InferiorThread.ptid}. This is the string that @value{GDBN} uses
4150 in the @samp{Target Id} column in the @kbd{info threads} output
4151 (@pxref{info_threads,,@samp{info threads}}).
4154 @defvar InferiorThread.inferior
4155 The inferior this thread belongs to. This attribute is represented as
4156 a @code{gdb.Inferior} object. This attribute is not writable.
4159 @defvar InferiorThread.details
4160 A string containing target specific thread state information. The
4161 format of this string varies by target. If there is no additional
4162 state information for this thread, then this attribute contains
4165 For example, on a @sc{gnu}/Linux system, a thread that is in the
4166 process of exiting will return the string @samp{Exiting}. For remote
4167 targets the @code{details} string will be obtained with the
4168 @samp{qThreadExtraInfo} remote packet, if the target supports it
4169 (@pxref{qThreadExtraInfo,,@samp{qThreadExtraInfo}}).
4171 @value{GDBN} displays the @code{details} string as part of the
4172 @samp{Target Id} column, in the @code{info threads} output
4173 (@pxref{info_threads,,@samp{info threads}}).
4176 A @code{gdb.InferiorThread} object has the following methods:
4178 @defun InferiorThread.is_valid ()
4179 Returns @code{True} if the @code{gdb.InferiorThread} object is valid,
4180 @code{False} if not. A @code{gdb.InferiorThread} object will become
4181 invalid if the thread exits, or the inferior that the thread belongs
4182 is deleted. All other @code{gdb.InferiorThread} methods will throw an
4183 exception if it is invalid at the time the method is called.
4186 @defun InferiorThread.switch ()
4187 This changes @value{GDBN}'s currently selected thread to the one represented
4191 @defun InferiorThread.is_stopped ()
4192 Return a Boolean indicating whether the thread is stopped.
4195 @defun InferiorThread.is_running ()
4196 Return a Boolean indicating whether the thread is running.
4199 @defun InferiorThread.is_exited ()
4200 Return a Boolean indicating whether the thread is exited.
4203 @defun InferiorThread.handle ()
4204 Return the thread object's handle, represented as a Python @code{bytes}
4205 object. A @code{gdb.Value} representation of the handle may be
4206 constructed via @code{gdb.Value(bufobj, type)} where @var{bufobj} is
4207 the Python @code{bytes} representation of the handle and @var{type} is
4208 a @code{gdb.Type} for the handle type.
4211 One may add arbitrary attributes to @code{gdb.InferiorThread} objects
4212 in the usual Python way. This is useful if, for example, one needs to
4213 do some extra record keeping associated with the thread.
4215 @xref{choosing attribute names}, for guidance on selecting a suitable
4216 name for new attributes.
4218 In this contrived example we record the time when a thread last
4223 (@value{GDBP}) python
4226 def thread_stopped(event):
4227 if event.inferior_thread is not None:
4228 thread = event.inferior_thread
4230 thread = gdb.selected_thread()
4231 thread._last_stop_time = datetime.datetime.today()
4233 gdb.events.stop.connect(thread_stopped)
4236 (@value{GDBP}) file /tmp/hello
4237 Reading symbols from /tmp/hello...
4238 (@value{GDBP}) start
4239 Temporary breakpoint 1 at 0x401198: file /tmp/hello.c, line 18.
4240 Starting program: /tmp/hello
4242 Temporary breakpoint 1, main () at /tmp/hello.c:18
4243 18 printf ("Hello World\n");
4244 (@value{GDBP}) python print(gdb.selected_thread()._last_stop_time)
4245 2024-01-04 14:48:41.347036
4249 @node Recordings In Python
4250 @subsubsection Recordings In Python
4251 @cindex recordings in python
4253 The following recordings-related functions
4254 (@pxref{Process Record and Replay}) are available in the @code{gdb}
4257 @defun gdb.start_recording (@r{[}method@r{]}, @r{[}format@r{]})
4258 Start a recording using the given @var{method} and @var{format}. If
4259 no @var{format} is given, the default format for the recording method
4260 is used. If no @var{method} is given, the default method will be used.
4261 Returns a @code{gdb.Record} object on success. Throw an exception on
4264 The following strings can be passed as @var{method}:
4270 @code{"btrace"}: Possible values for @var{format}: @code{"pt"},
4271 @code{"bts"} or leave out for default format.
4275 @defun gdb.current_recording ()
4276 Access a currently running recording. Return a @code{gdb.Record}
4277 object on success. Return @code{None} if no recording is currently
4281 @defun gdb.stop_recording ()
4282 Stop the current recording. Throw an exception if no recording is
4283 currently active. All record objects become invalid after this call.
4286 A @code{gdb.Record} object has the following attributes:
4288 @defvar Record.method
4289 A string with the current recording method, e.g.@: @code{full} or
4293 @defvar Record.format
4294 A string with the current recording format, e.g.@: @code{bt}, @code{pts} or
4298 @defvar Record.begin
4299 A method specific instruction object representing the first instruction
4304 A method specific instruction object representing the current
4305 instruction, that is not actually part of the recording.
4308 @defvar Record.replay_position
4309 The instruction representing the current replay position. If there is
4310 no replay active, this will be @code{None}.
4313 @defvar Record.instruction_history
4314 A list with all recorded instructions.
4317 @defvar Record.function_call_history
4318 A list with all recorded function call segments.
4321 A @code{gdb.Record} object has the following methods:
4323 @defun Record.goto (instruction)
4324 Move the replay position to the given @var{instruction}.
4327 @defun Record.clear ()
4328 Clear the trace data of the current recording. This forces re-decoding of the
4329 trace for successive commands.
4332 The common @code{gdb.Instruction} class that recording method specific
4333 instruction objects inherit from, has the following attributes:
4335 @defvar Instruction.pc
4336 An integer representing this instruction's address.
4339 @defvar Instruction.data
4340 A @code{memoryview} object holding the raw instruction data.
4343 @defvar Instruction.decoded
4344 A human readable string with the disassembled instruction.
4347 @defvar Instruction.size
4348 The size of the instruction in bytes.
4351 Additionally @code{gdb.RecordInstruction} has the following attributes:
4353 @defvar RecordInstruction.number
4354 An integer identifying this instruction. @code{number} corresponds to
4355 the numbers seen in @code{record instruction-history}
4356 (@pxref{Process Record and Replay}).
4359 @defvar RecordInstruction.sal
4360 A @code{gdb.Symtab_and_line} object representing the associated symtab
4361 and line of this instruction. May be @code{None} if no debug information is
4365 @defvar RecordInstruction.is_speculative
4366 A boolean indicating whether the instruction was executed speculatively.
4369 If an error occurred during recording or decoding a recording, this error is
4370 represented by a @code{gdb.RecordGap} object in the instruction list. It has
4371 the following attributes:
4373 @defvar RecordGap.number
4374 An integer identifying this gap. @code{number} corresponds to the numbers seen
4375 in @code{record instruction-history} (@pxref{Process Record and Replay}).
4378 @defvar RecordGap.error_code
4379 A numerical representation of the reason for the gap. The value is specific to
4380 the current recording method.
4383 @defvar RecordGap.error_string
4384 A human readable string with the reason for the gap.
4387 Some @value{GDBN} features write auxiliary information into the execution
4388 history. This information is represented by a @code{gdb.RecordAuxiliary} object
4389 in the instruction list. It has the following attributes:
4391 @defvar RecordAuxiliary.@var{number}
4392 An integer identifying this auxiliary. @var{number} corresponds to the numbers
4393 seen in @code{record instruction-history} (@pxref{Process Record and Replay}).
4396 @defvar RecordAuxiliary.data
4397 A string representation of the auxiliary data.
4400 A @code{gdb.RecordFunctionSegment} object has the following attributes:
4402 @defvar RecordFunctionSegment.number
4403 An integer identifying this function segment. @code{number} corresponds to
4404 the numbers seen in @code{record function-call-history}
4405 (@pxref{Process Record and Replay}).
4408 @defvar RecordFunctionSegment.symbol
4409 A @code{gdb.Symbol} object representing the associated symbol. May be
4410 @code{None} if no debug information is available.
4413 @defvar RecordFunctionSegment.level
4414 An integer representing the function call's stack level. May be
4415 @code{None} if the function call is a gap.
4418 @defvar RecordFunctionSegment.instructions
4419 A list of @code{gdb.RecordInstruction} or @code{gdb.RecordGap} objects
4420 associated with this function call.
4423 @defvar RecordFunctionSegment.up
4424 A @code{gdb.RecordFunctionSegment} object representing the caller's
4425 function segment. If the call has not been recorded, this will be the
4426 function segment to which control returns. If neither the call nor the
4427 return have been recorded, this will be @code{None}.
4430 @defvar RecordFunctionSegment.prev
4431 A @code{gdb.RecordFunctionSegment} object representing the previous
4432 segment of this function call. May be @code{None}.
4435 @defvar RecordFunctionSegment.next
4436 A @code{gdb.RecordFunctionSegment} object representing the next segment of
4437 this function call. May be @code{None}.
4440 The following example demonstrates the usage of these objects and
4441 functions to create a function that will rewind a record to the last
4442 time a function in a different file was executed. This would typically
4443 be used to track the execution of user provided callback functions in a
4444 library which typically are not visible in a back trace.
4448 rec = gdb.current_recording ()
4452 insn = rec.instruction_history
4457 position = insn.index (rec.replay_position)
4461 filename = insn[position].sal.symtab.fullname ()
4465 for i in reversed (insn[:position]):
4467 current = i.sal.symtab.fullname ()
4471 if filename == current:
4478 Another possible application is to write a function that counts the
4479 number of code executions in a given line range. This line range can
4480 contain parts of functions or span across several functions and is not
4481 limited to be contiguous.
4484 def countrange (filename, linerange):
4487 def filter_only (file_name):
4488 for call in gdb.current_recording ().function_call_history:
4490 if file_name in call.symbol.symtab.fullname ():
4495 for c in filter_only (filename):
4496 for i in c.instructions:
4498 if i.sal.line in linerange:
4507 @node CLI Commands In Python
4508 @subsubsection CLI Commands In Python
4510 @cindex CLI commands in python
4511 @cindex commands in python, CLI
4512 @cindex python commands, CLI
4513 You can implement new @value{GDBN} CLI commands in Python. A CLI
4514 command is implemented using an instance of the @code{gdb.Command}
4515 class, most commonly using a subclass.
4517 @defun Command.__init__ (name, command_class @r{[}, completer_class @r{[}, prefix@r{]]})
4518 The object initializer for @code{Command} registers the new command
4519 with @value{GDBN}. This initializer is normally invoked from the
4520 subclass' own @code{__init__} method.
4522 @var{name} is the name of the command. If @var{name} consists of
4523 multiple words, then the initial words are looked for as prefix
4524 commands. In this case, if one of the prefix commands does not exist,
4525 an exception is raised.
4527 There is no support for multi-line commands.
4529 @var{command_class} should be one of the @samp{COMMAND_} constants
4530 defined below. This argument tells @value{GDBN} how to categorize the
4531 new command in the help system.
4533 @var{completer_class} is an optional argument. If given, it should be
4534 one of the @samp{COMPLETE_} constants defined below. This argument
4535 tells @value{GDBN} how to perform completion for this command. If not
4536 given, @value{GDBN} will attempt to complete using the object's
4537 @code{complete} method (see below); if no such method is found, an
4538 error will occur when completion is attempted.
4540 @var{prefix} is an optional argument. If @code{True}, then the new
4541 command is a prefix command; sub-commands of this command may be
4544 The help text for the new command is taken from the Python
4545 documentation string for the command's class, if there is one. If no
4546 documentation string is provided, the default value ``This command is
4547 not documented.'' is used.
4550 @cindex don't repeat Python command
4551 @defun Command.dont_repeat ()
4552 By default, a @value{GDBN} command is repeated when the user enters a
4553 blank line at the command prompt. A command can suppress this
4554 behavior by invoking the @code{dont_repeat} method at some point in
4555 its @code{invoke} method (normally this is done early in case of
4556 exception). This is similar to the user command @code{dont-repeat},
4557 see @ref{Define, dont-repeat}.
4560 @defun Command.invoke (argument, from_tty)
4561 This method is called by @value{GDBN} when this command is invoked.
4563 @var{argument} is a string. It is the argument to the command, after
4564 leading and trailing whitespace has been stripped.
4566 @var{from_tty} is a boolean argument. When true, this means that the
4567 command was entered by the user at the terminal; when false it means
4568 that the command came from elsewhere.
4570 If this method throws an exception, it is turned into a @value{GDBN}
4571 @code{error} call. Otherwise, the return value is ignored.
4573 @findex gdb.string_to_argv
4574 To break @var{argument} up into an argv-like string use
4575 @code{gdb.string_to_argv}. This function behaves identically to
4576 @value{GDBN}'s internal argument lexer @code{buildargv}.
4577 It is recommended to use this for consistency.
4578 Arguments are separated by spaces and may be quoted.
4582 print gdb.string_to_argv ("1 2\ \\\"3 '4 \"5' \"6 '7\"")
4583 ['1', '2 "3', '4 "5', "6 '7"]
4588 @cindex completion of Python commands
4589 @defun Command.complete (text, word)
4590 This method is called by @value{GDBN} when the user attempts
4591 completion on this command. All forms of completion are handled by
4592 this method, that is, the @key{TAB} and @key{M-?} key bindings
4593 (@pxref{Completion}), and the @code{complete} command (@pxref{Help,
4596 The arguments @var{text} and @var{word} are both strings; @var{text}
4597 holds the complete command line up to the cursor's location, while
4598 @var{word} holds the last word of the command line; this is computed
4599 using a word-breaking heuristic.
4601 The @code{complete} method can return several values:
4604 If the return value is a sequence, the contents of the sequence are
4605 used as the completions. It is up to @code{complete} to ensure that the
4606 contents actually do complete the word. A zero-length sequence is
4607 allowed, it means that there were no completions available. Only
4608 string elements of the sequence are used; other elements in the
4609 sequence are ignored.
4612 If the return value is one of the @samp{COMPLETE_} constants defined
4613 below, then the corresponding @value{GDBN}-internal completion
4614 function is invoked, and its result is used.
4617 All other results are treated as though there were no available
4622 When a new command is registered, it must be declared as a member of
4623 some general class of commands. This is used to classify top-level
4624 commands in the on-line help system; note that prefix commands are not
4625 listed under their own category but rather that of their top-level
4626 command. The available classifications are represented by constants
4627 defined in the @code{gdb} module:
4630 @findex COMMAND_NONE
4631 @findex gdb.COMMAND_NONE
4632 @item gdb.COMMAND_NONE
4633 The command does not belong to any particular class. A command in
4634 this category will not be displayed in any of the help categories.
4636 @findex COMMAND_RUNNING
4637 @findex gdb.COMMAND_RUNNING
4638 @item gdb.COMMAND_RUNNING
4639 The command is related to running the inferior. For example,
4640 @code{start}, @code{step}, and @code{continue} are in this category.
4641 Type @kbd{help running} at the @value{GDBN} prompt to see a list of
4642 commands in this category.
4644 @findex COMMAND_DATA
4645 @findex gdb.COMMAND_DATA
4646 @item gdb.COMMAND_DATA
4647 The command is related to data or variables. For example,
4648 @code{call}, @code{find}, and @code{print} are in this category. Type
4649 @kbd{help data} at the @value{GDBN} prompt to see a list of commands
4652 @findex COMMAND_STACK
4653 @findex gdb.COMMAND_STACK
4654 @item gdb.COMMAND_STACK
4655 The command has to do with manipulation of the stack. For example,
4656 @code{backtrace}, @code{frame}, and @code{return} are in this
4657 category. Type @kbd{help stack} at the @value{GDBN} prompt to see a
4658 list of commands in this category.
4660 @findex COMMAND_FILES
4661 @findex gdb.COMMAND_FILES
4662 @item gdb.COMMAND_FILES
4663 This class is used for file-related commands. For example,
4664 @code{file}, @code{list} and @code{section} are in this category.
4665 Type @kbd{help files} at the @value{GDBN} prompt to see a list of
4666 commands in this category.
4668 @findex COMMAND_SUPPORT
4669 @findex gdb.COMMAND_SUPPORT
4670 @item gdb.COMMAND_SUPPORT
4671 This should be used for ``support facilities'', generally meaning
4672 things that are useful to the user when interacting with @value{GDBN},
4673 but not related to the state of the inferior. For example,
4674 @code{help}, @code{make}, and @code{shell} are in this category. Type
4675 @kbd{help support} at the @value{GDBN} prompt to see a list of
4676 commands in this category.
4678 @findex COMMAND_STATUS
4679 @findex gdb.COMMAND_STATUS
4680 @item gdb.COMMAND_STATUS
4681 The command is an @samp{info}-related command, that is, related to the
4682 state of @value{GDBN} itself. For example, @code{info}, @code{macro},
4683 and @code{show} are in this category. Type @kbd{help status} at the
4684 @value{GDBN} prompt to see a list of commands in this category.
4686 @findex COMMAND_BREAKPOINTS
4687 @findex gdb.COMMAND_BREAKPOINTS
4688 @item gdb.COMMAND_BREAKPOINTS
4689 The command has to do with breakpoints. For example, @code{break},
4690 @code{clear}, and @code{delete} are in this category. Type @kbd{help
4691 breakpoints} at the @value{GDBN} prompt to see a list of commands in
4694 @findex COMMAND_TRACEPOINTS
4695 @findex gdb.COMMAND_TRACEPOINTS
4696 @item gdb.COMMAND_TRACEPOINTS
4697 The command has to do with tracepoints. For example, @code{trace},
4698 @code{actions}, and @code{tfind} are in this category. Type
4699 @kbd{help tracepoints} at the @value{GDBN} prompt to see a list of
4700 commands in this category.
4703 @findex gdb.COMMAND_TUI
4704 @item gdb.COMMAND_TUI
4705 The command has to do with the text user interface (@pxref{TUI}).
4706 Type @kbd{help tui} at the @value{GDBN} prompt to see a list of
4707 commands in this category.
4709 @findex COMMAND_USER
4710 @findex gdb.COMMAND_USER
4711 @item gdb.COMMAND_USER
4712 The command is a general purpose command for the user, and typically
4713 does not fit in one of the other categories.
4714 Type @kbd{help user-defined} at the @value{GDBN} prompt to see
4715 a list of commands in this category, as well as the list of gdb macros
4716 (@pxref{Sequences}).
4718 @findex COMMAND_OBSCURE
4719 @findex gdb.COMMAND_OBSCURE
4720 @item gdb.COMMAND_OBSCURE
4721 The command is only used in unusual circumstances, or is not of
4722 general interest to users. For example, @code{checkpoint},
4723 @code{fork}, and @code{stop} are in this category. Type @kbd{help
4724 obscure} at the @value{GDBN} prompt to see a list of commands in this
4727 @findex COMMAND_MAINTENANCE
4728 @findex gdb.COMMAND_MAINTENANCE
4729 @item gdb.COMMAND_MAINTENANCE
4730 The command is only useful to @value{GDBN} maintainers. The
4731 @code{maintenance} and @code{flushregs} commands are in this category.
4732 Type @kbd{help internals} at the @value{GDBN} prompt to see a list of
4733 commands in this category.
4736 A new command can use a predefined completion function, either by
4737 specifying it via an argument at initialization, or by returning it
4738 from the @code{complete} method. These predefined completion
4739 constants are all defined in the @code{gdb} module:
4742 @vindex COMPLETE_NONE
4743 @item gdb.COMPLETE_NONE
4744 This constant means that no completion should be done.
4746 @vindex COMPLETE_FILENAME
4747 @item gdb.COMPLETE_FILENAME
4748 This constant means that filename completion should be performed.
4750 @vindex COMPLETE_LOCATION
4751 @item gdb.COMPLETE_LOCATION
4752 This constant means that location completion should be done.
4753 @xref{Location Specifications}.
4755 @vindex COMPLETE_COMMAND
4756 @item gdb.COMPLETE_COMMAND
4757 This constant means that completion should examine @value{GDBN}
4760 @vindex COMPLETE_SYMBOL
4761 @item gdb.COMPLETE_SYMBOL
4762 This constant means that completion should be done using symbol names
4765 @vindex COMPLETE_EXPRESSION
4766 @item gdb.COMPLETE_EXPRESSION
4767 This constant means that completion should be done on expressions.
4768 Often this means completing on symbol names, but some language
4769 parsers also have support for completing on field names.
4772 The following code snippet shows how a trivial CLI command can be
4773 implemented in Python:
4776 class HelloWorld (gdb.Command):
4777 """Greet the whole world."""
4779 def __init__ (self):
4780 super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
4782 def invoke (self, arg, from_tty):
4783 print ("Hello, World!")
4788 The last line instantiates the class, and is necessary to trigger the
4789 registration of the command with @value{GDBN}. Depending on how the
4790 Python code is read into @value{GDBN}, you may need to import the
4791 @code{gdb} module explicitly.
4793 @node GDB/MI Commands In Python
4794 @subsubsection @sc{gdb/mi} Commands In Python
4796 @cindex MI commands in python
4797 @cindex commands in python, GDB/MI
4798 @cindex python commands, GDB/MI
4799 It is possible to add @sc{gdb/mi} (@pxref{GDB/MI}) commands
4800 implemented in Python. A @sc{gdb/mi} command is implemented using an
4801 instance of the @code{gdb.MICommand} class, most commonly using a
4804 @defun MICommand.__init__ (name)
4805 The object initializer for @code{MICommand} registers the new command
4806 with @value{GDBN}. This initializer is normally invoked from the
4807 subclass' own @code{__init__} method.
4809 @var{name} is the name of the command. It must be a valid name of a
4810 @sc{gdb/mi} command, and in particular must start with a hyphen
4811 (@code{-}). Reusing the name of a built-in @sc{gdb/mi} is not
4812 allowed, and a @code{RuntimeError} will be raised. Using the name
4813 of an @sc{gdb/mi} command previously defined in Python is allowed, the
4814 previous command will be replaced with the new command.
4817 @defun MICommand.invoke (arguments)
4818 This method is called by @value{GDBN} when the new MI command is
4821 @var{arguments} is a list of strings. Note, that @code{--thread}
4822 and @code{--frame} arguments are handled by @value{GDBN} itself therefore
4823 they do not show up in @code{arguments}.
4825 If this method raises an exception, then it is turned into a
4826 @sc{gdb/mi} @code{^error} response. Only @code{gdb.GdbError}
4827 exceptions (or its sub-classes) should be used for reporting errors to
4828 users, any other exception type is treated as a failure of the
4829 @code{invoke} method, and the exception will be printed to the error
4830 stream according to the @kbd{set python print-stack} setting
4831 (@pxref{set_python_print_stack,,@kbd{set python print-stack}}).
4833 If this method returns @code{None}, then the @sc{gdb/mi} command will
4834 return a @code{^done} response with no additional values.
4836 Otherwise, the return value must be a dictionary, which is converted
4837 to a @sc{gdb/mi} @var{result-record} (@pxref{GDB/MI Output Syntax}).
4838 The keys of this dictionary must be strings, and are used as
4839 @var{variable} names in the @var{result-record}, these strings must
4840 comply with the naming rules detailed below. The values of this
4841 dictionary are recursively handled as follows:
4845 If the value is Python sequence or iterator, it is converted to
4846 @sc{gdb/mi} @var{list} with elements converted recursively.
4849 If the value is Python dictionary, it is converted to
4850 @sc{gdb/mi} @var{tuple}. Keys in that dictionary must be strings,
4851 which comply with the @var{variable} naming rules detailed below.
4852 Values are converted recursively.
4855 Otherwise, value is first converted to a Python string using
4856 @code{str ()} and then converted to @sc{gdb/mi} @var{const}.
4859 The strings used for @var{variable} names in the @sc{gdb/mi} output
4860 must follow the following rules; the string must be at least one
4861 character long, the first character must be in the set
4862 @code{[a-zA-Z]}, while every subsequent character must be in the set
4863 @code{[-_a-zA-Z0-9]}.
4866 An instance of @code{MICommand} has the following attributes:
4868 @defvar MICommand.name
4869 A string, the name of this @sc{gdb/mi} command, as was passed to the
4870 @code{__init__} method. This attribute is read-only.
4873 @defvar MICommand.installed
4874 A boolean value indicating if this command is installed ready for a
4875 user to call from the command line. Commands are automatically
4876 installed when they are instantiated, after which this attribute will
4879 If later, a new command is created with the same name, then the
4880 original command will become uninstalled, and this attribute will be
4883 This attribute is read-write, setting this attribute to @code{False}
4884 will uninstall the command, removing it from the set of available
4885 commands. Setting this attribute to @code{True} will install the
4886 command for use. If there is already a Python command with this name
4887 installed, the currently installed command will be uninstalled, and
4888 this command installed in its stead.
4891 The following code snippet shows how some trivial MI commands can be
4892 implemented in Python:
4895 class MIEcho(gdb.MICommand):
4896 """Echo arguments passed to the command."""
4898 def __init__(self, name, mode):
4900 super(MIEcho, self).__init__(name)
4902 def invoke(self, argv):
4903 if self._mode == 'dict':
4904 return @{ 'dict': @{ 'argv' : argv @} @}
4905 elif self._mode == 'list':
4906 return @{ 'list': argv @}
4908 return @{ 'string': ", ".join(argv) @}
4911 MIEcho("-echo-dict", "dict")
4912 MIEcho("-echo-list", "list")
4913 MIEcho("-echo-string", "string")
4916 The last three lines instantiate the class three times, creating three
4917 new @sc{gdb/mi} commands @code{-echo-dict}, @code{-echo-list}, and
4918 @code{-echo-string}. Each time a subclass of @code{gdb.MICommand} is
4919 instantiated, the new command is automatically registered with
4922 Depending on how the Python code is read into @value{GDBN}, you may
4923 need to import the @code{gdb} module explicitly.
4925 The following example shows a @value{GDBN} session in which the above
4926 commands have been added:
4930 -echo-dict abc def ghi
4931 ^done,dict=@{argv=["abc","def","ghi"]@}
4933 -echo-list abc def ghi
4934 ^done,list=["abc","def","ghi"]
4936 -echo-string abc def ghi
4937 ^done,string="abc, def, ghi"
4941 Conversely, it is possible to execute @sc{gdb/mi} commands from
4942 Python, with the results being a Python object and not a
4943 specially-formatted string. This is done with the
4944 @code{gdb.execute_mi} function.
4946 @defun gdb.execute_mi (command @r{[}, arg @r{]}@dots{})
4947 Invoke a @sc{gdb/mi} command. @var{command} is the name of the
4948 command, a string. The arguments, @var{arg}, are passed to the
4949 command. Each argument must also be a string.
4951 This function returns a Python dictionary whose contents reflect the
4952 corresponding @sc{GDB/MI} command's output. Refer to the
4953 documentation for these commands for details. Lists are represented
4954 as Python lists, and tuples are represented as Python dictionaries.
4956 If the command fails, it will raise a Python exception.
4959 Here is how this works using the commands from the example above:
4962 (@value{GDBP}) python print(gdb.execute_mi("-echo-dict", "abc", "def", "ghi"))
4963 @{'dict': @{'argv': ['abc', 'def', 'ghi']@}@}
4964 (@value{GDBP}) python print(gdb.execute_mi("-echo-list", "abc", "def", "ghi"))
4965 @{'list': ['abc', 'def', 'ghi']@}
4966 (@value{GDBP}) python print(gdb.execute_mi("-echo-string", "abc", "def", "ghi"))
4967 @{'string': 'abc, def, ghi'@}
4970 @node GDB/MI Notifications In Python
4971 @subsubsection @sc{gdb/mi} Notifications In Python
4973 @cindex MI notifications in python
4974 @cindex notifications in python, GDB/MI
4975 @cindex python notifications, GDB/MI
4977 It is possible to emit @sc{gdb/mi} notifications from
4978 Python. Use the @code{gdb.notify_mi} function to do that.
4980 @defun gdb.notify_mi (name @r{[}, data@r{]})
4981 Emit a @sc{gdb/mi} asynchronous notification. @var{name} is the name of the
4982 notification, consisting of alphanumeric characters and a hyphen (@code{-}).
4983 @var{data} is any additional data to be emitted with the notification, passed
4984 as a Python dictionary. This argument is optional. The dictionary is converted
4985 to a @sc{gdb/mi} @var{result} records (@pxref{GDB/MI Output Syntax}) the same way
4986 as result of Python MI command (@pxref{GDB/MI Commands In Python}).
4988 If @var{data} is @code{None} then no additional values are emitted.
4991 While using existing notification names (@pxref{GDB/MI Async Records}) with
4992 @code{gdb.notify_mi} is allowed, users are encouraged to prefix user-defined
4993 notification with a hyphen (@code{-}) to avoid possible conflict.
4994 @value{GDBN} will never introduce notification starting with hyphen.
4996 Here is how to emit @code{=-connection-removed} whenever a connection to remote
4997 GDB server is closed (@pxref{Connections In Python}):
5000 def notify_connection_removed(event):
5001 data = @{"id": event.connection.num, "type": event.connection.type@}
5002 gdb.notify_mi("-connection-removed", data)
5005 gdb.events.connection_removed.connect(notify_connection_removed)
5008 Then, each time a connection is closed, there will be a notification on MI channel:
5011 =-connection-removed,id="1",type="remote"
5014 @node Parameters In Python
5015 @subsubsection Parameters In Python
5017 @cindex parameters in python
5018 @cindex python parameters
5019 @tindex gdb.Parameter
5021 You can implement new @value{GDBN} parameters using Python. A new
5022 parameter is implemented as an instance of the @code{gdb.Parameter}
5025 Parameters are exposed to the user via the @code{set} and
5026 @code{show} commands. @xref{Help}.
5028 There are many parameters that already exist and can be set in
5029 @value{GDBN}. Two examples are: @code{set follow fork} and
5030 @code{set charset}. Setting these parameters influences certain
5031 behavior in @value{GDBN}. Similarly, you can define parameters that
5032 can be used to influence behavior in custom Python scripts and commands.
5034 @defun Parameter.__init__ (name, command_class, parameter_class @r{[}, enum_sequence@r{]})
5035 The object initializer for @code{Parameter} registers the new
5036 parameter with @value{GDBN}. This initializer is normally invoked
5037 from the subclass' own @code{__init__} method.
5039 @var{name} is the name of the new parameter. If @var{name} consists
5040 of multiple words, then the initial words are looked for as prefix
5041 parameters. An example of this can be illustrated with the
5042 @code{set print} set of parameters. If @var{name} is
5043 @code{print foo}, then @code{print} will be searched as the prefix
5044 parameter. In this case the parameter can subsequently be accessed in
5045 @value{GDBN} as @code{set print foo}.
5047 If @var{name} consists of multiple words, and no prefix parameter group
5048 can be found, an exception is raised.
5050 @var{command_class} should be one of the @samp{COMMAND_} constants
5051 (@pxref{CLI Commands In Python}). This argument tells @value{GDBN} how to
5052 categorize the new parameter in the help system.
5054 @var{parameter_class} should be one of the @samp{PARAM_} constants
5055 defined below. This argument tells @value{GDBN} the type of the new
5056 parameter; this information is used for input validation and
5059 If @var{parameter_class} is @code{PARAM_ENUM}, then
5060 @var{enum_sequence} must be a sequence of strings. These strings
5061 represent the possible values for the parameter.
5063 If @var{parameter_class} is not @code{PARAM_ENUM}, then the presence
5064 of a fourth argument will cause an exception to be thrown.
5066 The help text for the new parameter includes the Python documentation
5067 string from the parameter's class, if there is one. If there is no
5068 documentation string, a default value is used. The documentation
5069 string is included in the output of the parameters @code{help set} and
5070 @code{help show} commands, and should be written taking this into
5074 @defvar Parameter.set_doc
5075 If this attribute exists, and is a string, then its value is used as
5076 the first part of the help text for this parameter's @code{set}
5077 command. The second part of the help text is taken from the
5078 documentation string for the parameter's class, if there is one.
5080 The value of @code{set_doc} should give a brief summary specific to
5081 the set action, this text is only displayed when the user runs the
5082 @code{help set} command for this parameter. The class documentation
5083 should be used to give a fuller description of what the parameter
5084 does, this text is displayed for both the @code{help set} and
5085 @code{help show} commands.
5087 The @code{set_doc} value is examined when @code{Parameter.__init__} is
5088 invoked; subsequent changes have no effect.
5091 @defvar Parameter.show_doc
5092 If this attribute exists, and is a string, then its value is used as
5093 the first part of the help text for this parameter's @code{show}
5094 command. The second part of the help text is taken from the
5095 documentation string for the parameter's class, if there is one.
5097 The value of @code{show_doc} should give a brief summary specific to
5098 the show action, this text is only displayed when the user runs the
5099 @code{help show} command for this parameter. The class documentation
5100 should be used to give a fuller description of what the parameter
5101 does, this text is displayed for both the @code{help set} and
5102 @code{help show} commands.
5104 The @code{show_doc} value is examined when @code{Parameter.__init__}
5105 is invoked; subsequent changes have no effect.
5108 @defvar Parameter.value
5109 The @code{value} attribute holds the underlying value of the
5110 parameter. It can be read and assigned to just as any other
5111 attribute. @value{GDBN} does validation when assignments are made.
5114 There are two methods that may be implemented in any @code{Parameter}
5117 @defun Parameter.get_set_string (self)
5118 If this method exists, @value{GDBN} will call it when a
5119 @var{parameter}'s value has been changed via the @code{set} API (for
5120 example, @kbd{set foo off}). The @code{value} attribute has already
5121 been populated with the new value and may be used in output. This
5122 method must return a string. If the returned string is not empty,
5123 @value{GDBN} will present it to the user.
5125 If this method raises the @code{gdb.GdbError} exception
5126 (@pxref{Exception Handling}), then @value{GDBN} will print the
5127 exception's string and the @code{set} command will fail. Note,
5128 however, that the @code{value} attribute will not be reset in this
5129 case. So, if your parameter must validate values, it should store the
5130 old value internally and reset the exposed value, like so:
5133 class ExampleParam (gdb.Parameter):
5134 def __init__ (self, name):
5135 super (ExampleParam, self).__init__ (name,
5139 self.saved_value = True
5142 def get_set_string (self):
5143 if not self.validate():
5144 self.value = self.saved_value
5145 raise gdb.GdbError('Failed to validate')
5146 self.saved_value = self.value
5151 @defun Parameter.get_show_string (self, svalue)
5152 @value{GDBN} will call this method when a @var{parameter}'s
5153 @code{show} API has been invoked (for example, @kbd{show foo}). The
5154 argument @code{svalue} receives the string representation of the
5155 current value. This method must return a string.
5158 When a new parameter is defined, its type must be specified. The
5159 available types are represented by constants defined in the @code{gdb}
5163 @findex PARAM_BOOLEAN
5164 @findex gdb.PARAM_BOOLEAN
5165 @item gdb.PARAM_BOOLEAN
5166 The value is a plain boolean. The Python boolean values, @code{True}
5167 and @code{False} are the only valid values.
5169 @findex PARAM_AUTO_BOOLEAN
5170 @findex gdb.PARAM_AUTO_BOOLEAN
5171 @item gdb.PARAM_AUTO_BOOLEAN
5172 The value has three possible states: true, false, and @samp{auto}. In
5173 Python, true and false are represented using boolean constants, and
5174 @samp{auto} is represented using @code{None}.
5176 @findex PARAM_UINTEGER
5177 @findex gdb.PARAM_UINTEGER
5178 @item gdb.PARAM_UINTEGER
5179 The value is an unsigned integer. The value of @code{None} should be
5180 interpreted to mean ``unlimited'' (literal @code{'unlimited'} can also
5181 be used to set that value), and the value of 0 is reserved and should
5184 @findex PARAM_INTEGER
5185 @findex gdb.PARAM_INTEGER
5186 @item gdb.PARAM_INTEGER
5187 The value is a signed integer. The value of @code{None} should be
5188 interpreted to mean ``unlimited'' (literal @code{'unlimited'} can also
5189 be used to set that value), and the value of 0 is reserved and should
5192 @findex PARAM_STRING
5193 @findex gdb.PARAM_STRING
5194 @item gdb.PARAM_STRING
5195 The value is a string. When the user modifies the string, any escape
5196 sequences, such as @samp{\t}, @samp{\f}, and octal escapes, are
5197 translated into corresponding characters and encoded into the current
5200 @findex PARAM_STRING_NOESCAPE
5201 @findex gdb.PARAM_STRING_NOESCAPE
5202 @item gdb.PARAM_STRING_NOESCAPE
5203 The value is a string. When the user modifies the string, escapes are
5204 passed through untranslated.
5206 @findex PARAM_OPTIONAL_FILENAME
5207 @findex gdb.PARAM_OPTIONAL_FILENAME
5208 @item gdb.PARAM_OPTIONAL_FILENAME
5209 The value is a either a filename (a string), or @code{None}.
5211 @findex PARAM_FILENAME
5212 @findex gdb.PARAM_FILENAME
5213 @item gdb.PARAM_FILENAME
5214 The value is a filename. This is just like
5215 @code{PARAM_STRING_NOESCAPE}, but uses file names for completion.
5217 @findex PARAM_ZINTEGER
5218 @findex gdb.PARAM_ZINTEGER
5219 @item gdb.PARAM_ZINTEGER
5220 The value is a signed integer. This is like @code{PARAM_INTEGER},
5221 except that 0 is allowed and the value of @code{None} is not supported.
5223 @findex PARAM_ZUINTEGER
5224 @findex gdb.PARAM_ZUINTEGER
5225 @item gdb.PARAM_ZUINTEGER
5226 The value is an unsigned integer. This is like @code{PARAM_UINTEGER},
5227 except that 0 is allowed and the value of @code{None} is not supported.
5229 @findex PARAM_ZUINTEGER_UNLIMITED
5230 @findex gdb.PARAM_ZUINTEGER_UNLIMITED
5231 @item gdb.PARAM_ZUINTEGER_UNLIMITED
5232 The value is a signed integer. This is like @code{PARAM_INTEGER}
5233 including that the value of @code{None} should be interpreted to mean
5234 ``unlimited'' (literal @code{'unlimited'} can also be used to set that
5235 value), except that 0 is allowed, and the value cannot be negative,
5236 except the special value -1 is returned for the setting of ``unlimited''.
5239 @findex gdb.PARAM_ENUM
5240 @item gdb.PARAM_ENUM
5241 The value is a string, which must be one of a collection string
5242 constants provided when the parameter is created.
5245 @node Functions In Python
5246 @subsubsection Writing new convenience functions
5248 @cindex writing convenience functions
5249 @cindex convenience functions in python
5250 @cindex python convenience functions
5251 @tindex gdb.Function
5253 You can implement new convenience functions (@pxref{Convenience Vars})
5254 in Python. A convenience function is an instance of a subclass of the
5255 class @code{gdb.Function}.
5257 @defun Function.__init__ (name)
5258 The initializer for @code{Function} registers the new function with
5259 @value{GDBN}. The argument @var{name} is the name of the function,
5260 a string. The function will be visible to the user as a convenience
5261 variable of type @code{internal function}, whose name is the same as
5262 the given @var{name}.
5264 The documentation for the new function is taken from the documentation
5265 string for the new class.
5268 @defun Function.invoke (*args)
5269 When a convenience function is evaluated, its arguments are converted
5270 to instances of @code{gdb.Value}, and then the function's
5271 @code{invoke} method is called. Note that @value{GDBN} does not
5272 predetermine the arity of convenience functions. Instead, all
5273 available arguments are passed to @code{invoke}, following the
5274 standard Python calling convention. In particular, a convenience
5275 function can have default values for parameters without ill effect.
5277 The return value of this method is used as its value in the enclosing
5278 expression. If an ordinary Python value is returned, it is converted
5279 to a @code{gdb.Value} following the usual rules.
5282 The following code snippet shows how a trivial convenience function can
5283 be implemented in Python:
5286 class Greet (gdb.Function):
5287 """Return string to greet someone.
5288 Takes a name as argument."""
5290 def __init__ (self):
5291 super (Greet, self).__init__ ("greet")
5293 def invoke (self, name):
5294 return "Hello, %s!" % name.string ()
5299 The last line instantiates the class, and is necessary to trigger the
5300 registration of the function with @value{GDBN}. Depending on how the
5301 Python code is read into @value{GDBN}, you may need to import the
5302 @code{gdb} module explicitly.
5304 Now you can use the function in an expression:
5307 (gdb) print $greet("Bob")
5311 @node Progspaces In Python
5312 @subsubsection Program Spaces In Python
5314 @cindex progspaces in python
5315 @tindex gdb.Progspace
5317 A program space, or @dfn{progspace}, represents a symbolic view
5318 of an address space.
5319 It consists of all of the objfiles of the program.
5320 @xref{Objfiles In Python}.
5321 @xref{Inferiors Connections and Programs, program spaces}, for more details
5322 about program spaces.
5324 The following progspace-related functions are available in the
5327 @defun gdb.current_progspace ()
5328 This function returns the program space of the currently selected inferior.
5329 @xref{Inferiors Connections and Programs}. This is identical to
5330 @code{gdb.selected_inferior().progspace} (@pxref{Inferiors In Python}) and is
5331 included for historical compatibility.
5334 @defun gdb.progspaces ()
5335 Return a sequence of all the progspaces currently known to @value{GDBN}.
5338 Each progspace is represented by an instance of the @code{gdb.Progspace}
5341 @defvar Progspace.filename
5342 The file name, as a string, of the main symbol file (from which debug
5343 symbols have been loaded) for the progspace, e.g.@: the argument to
5344 the @kbd{symbol-file} or @kbd{file} commands.
5346 If there is no main symbol table currently loaded, then this attribute
5347 will be @code{None}.
5350 @defvar Progspace.symbol_file
5351 The @code{gdb.Objfile} representing the main symbol file (from which
5352 debug symbols have been loaded) for the @code{gdb.Progspace}. This is
5353 the symbol file set by the @kbd{symbol-file} or @kbd{file} commands.
5355 This will be the @code{gdb.Objfile} representing
5356 @code{Progspace.filename} when @code{Progspace.filename} is not
5359 If there is no main symbol table currently loaded, then this attribute
5360 will be @code{None}.
5362 If the @code{Progspace} is invalid, i.e.@:, when
5363 @code{Progspace.is_valid()} returns @code{False}, then attempting to
5364 access this attribute will raise a @code{RuntimeError} exception.
5367 @defvar Progspace.executable_filename
5368 The file name, as a string, of the executable file in use by this
5369 program space. The executable file is the file that @value{GDBN} will
5370 invoke in order to start an inferior when using a native target. The
5371 file name within this attribute is updated by the @kbd{exec-file} and
5372 @kbd{file} commands.
5374 If no executable is currently set within this @code{Progspace} then
5375 this attribute contains @code{None}.
5377 If the @code{Progspace} is invalid, i.e.@:, when
5378 @code{Progspace.is_valid()} returns @code{False}, then attempting to
5379 access this attribute will raise a @code{RuntimeError} exception.
5382 @defvar Progspace.pretty_printers
5383 The @code{pretty_printers} attribute is a list of functions. It is
5384 used to look up pretty-printers. A @code{Value} is passed to each
5385 function in order; if the function returns @code{None}, then the
5386 search continues. Otherwise, the return value should be an object
5387 which is used to format the value. @xref{Pretty Printing API}, for more
5391 @defvar Progspace.type_printers
5392 The @code{type_printers} attribute is a list of type printer objects.
5393 @xref{Type Printing API}, for more information.
5396 @defvar Progspace.frame_filters
5397 The @code{frame_filters} attribute is a dictionary of frame filter
5398 objects. @xref{Frame Filter API}, for more information.
5401 @defvar Progspace.missing_debug_handlers
5402 The @code{missing_debug_handlers} attribute is a list of the missing
5403 debug handler objects for this program space. @xref{Missing Debug
5404 Info In Python}, for more information.
5407 A program space has the following methods:
5409 @defun Progspace.block_for_pc (pc)
5410 Return the innermost @code{gdb.Block} containing the given @var{pc}
5411 value. If the block cannot be found for the @var{pc} value specified,
5412 the function will return @code{None}.
5415 @defun Progspace.find_pc_line (pc)
5416 Return the @code{gdb.Symtab_and_line} object corresponding to the
5417 @var{pc} value. @xref{Symbol Tables In Python}. If an invalid value
5418 of @var{pc} is passed as an argument, then the @code{symtab} and
5419 @code{line} attributes of the returned @code{gdb.Symtab_and_line}
5420 object will be @code{None} and 0 respectively.
5423 @defun Progspace.is_valid ()
5424 Returns @code{True} if the @code{gdb.Progspace} object is valid,
5425 @code{False} if not. A @code{gdb.Progspace} object can become invalid
5426 if the program space file it refers to is not referenced by any
5427 inferior. All other @code{gdb.Progspace} methods will throw an
5428 exception if it is invalid at the time the method is called.
5431 @defun Progspace.objfiles ()
5432 Return a sequence of all the objfiles referenced by this program
5433 space. @xref{Objfiles In Python}.
5436 @defun Progspace.solib_name (address)
5437 Return the name of the shared library holding the given @var{address}
5438 as a string, or @code{None}.
5441 @defun Progspace.objfile_for_address (address)
5442 Return the @code{gdb.Objfile} holding the given address, or
5443 @code{None} if no objfile covers it.
5446 One may add arbitrary attributes to @code{gdb.Progspace} objects
5447 in the usual Python way.
5448 This is useful if, for example, one needs to do some extra record keeping
5449 associated with the program space.
5451 @xref{choosing attribute names}, for guidance on selecting a suitable
5452 name for new attributes.
5454 In this contrived example, we want to perform some processing when
5455 an objfile with a certain symbol is loaded, but we only want to do
5456 this once because it is expensive. To achieve this we record the results
5457 with the program space because we can't predict when the desired objfile
5461 (@value{GDBP}) python
5463 def clear_objfiles_handler(event):
5464 event.progspace.expensive_computation = None
5465 def expensive(symbol):
5466 """A mock routine to perform an "expensive" computation on symbol."""
5467 print ("Computing the answer to the ultimate question ...")
5471 def new_objfile_handler(event):
5472 objfile = event.new_objfile
5473 progspace = objfile.progspace
5474 if not hasattr(progspace, 'expensive_computation') or \
5475 progspace.expensive_computation is None:
5476 # We use 'main' for the symbol to keep the example simple.
5477 # Note: There's no current way to constrain the lookup
5479 symbol = gdb.lookup_global_symbol('main')
5480 if symbol is not None:
5481 progspace.expensive_computation = expensive(symbol)
5482 gdb.events.clear_objfiles.connect(clear_objfiles_handler)
5483 gdb.events.new_objfile.connect(new_objfile_handler)
5487 (@value{GDBP}) file /tmp/hello
5488 Reading symbols from /tmp/hello...
5489 Computing the answer to the ultimate question ...
5490 (@value{GDBP}) python print(gdb.current_progspace().expensive_computation)
5493 Starting program: /tmp/hello
5495 [Inferior 1 (process 4242) exited normally]
5499 @node Objfiles In Python
5500 @subsubsection Objfiles In Python
5502 @cindex objfiles in python
5505 @value{GDBN} loads symbols for an inferior from various
5506 symbol-containing files (@pxref{Files}). These include the primary
5507 executable file, any shared libraries used by the inferior, and any
5508 separate debug info files (@pxref{Separate Debug Files}).
5509 @value{GDBN} calls these symbol-containing files @dfn{objfiles}.
5511 The following objfile-related functions are available in the
5514 @defun gdb.current_objfile ()
5515 When auto-loading a Python script (@pxref{Python Auto-loading}), @value{GDBN}
5516 sets the ``current objfile'' to the corresponding objfile. This
5517 function returns the current objfile. If there is no current objfile,
5518 this function returns @code{None}.
5521 @defun gdb.objfiles ()
5522 Return a sequence of objfiles referenced by the current program space.
5523 @xref{Objfiles In Python}, and @ref{Progspaces In Python}. This is identical
5524 to @code{gdb.selected_inferior().progspace.objfiles()} and is included for
5525 historical compatibility.
5528 @defun gdb.lookup_objfile (name @r{[}, by_build_id@r{]})
5529 Look up @var{name}, a file name or build ID, in the list of objfiles
5530 for the current program space (@pxref{Progspaces In Python}).
5531 If the objfile is not found throw the Python @code{ValueError} exception.
5533 If @var{name} is a relative file name, then it will match any
5534 source file name with the same trailing components. For example, if
5535 @var{name} is @samp{gcc/expr.c}, then it will match source file
5536 name of @file{/build/trunk/gcc/expr.c}, but not
5537 @file{/build/trunk/libcpp/expr.c} or @file{/build/trunk/gcc/x-expr.c}.
5539 If @var{by_build_id} is provided and is @code{True} then @var{name}
5540 is the build ID of the objfile. Otherwise, @var{name} is a file name.
5541 This is supported only on some operating systems, notably those which use
5542 the ELF format for binary files and the @sc{gnu} Binutils. For more details
5543 about this feature, see the description of the @option{--build-id}
5544 command-line option in @ref{Options, , Command Line Options, ld,
5548 Each objfile is represented by an instance of the @code{gdb.Objfile}
5551 @defvar Objfile.filename
5552 The file name of the objfile as a string, with symbolic links resolved.
5554 The value is @code{None} if the objfile is no longer valid.
5555 See the @code{gdb.Objfile.is_valid} method, described below.
5558 @defvar Objfile.username
5559 The file name of the objfile as specified by the user as a string.
5561 The value is @code{None} if the objfile is no longer valid.
5562 See the @code{gdb.Objfile.is_valid} method, described below.
5565 @defvar Objfile.is_file
5566 An objfile often comes from an ordinary file, but in some cases it may
5567 be constructed from the contents of memory. This attribute is
5568 @code{True} for file-backed objfiles, and @code{False} for other
5572 @defvar Objfile.owner
5573 For separate debug info objfiles this is the corresponding @code{gdb.Objfile}
5574 object that debug info is being provided for.
5575 Otherwise this is @code{None}.
5576 Separate debug info objfiles are added with the
5577 @code{gdb.Objfile.add_separate_debug_file} method, described below.
5580 @defvar Objfile.build_id
5581 The build ID of the objfile as a string.
5582 If the objfile does not have a build ID then the value is @code{None}.
5584 This is supported only on some operating systems, notably those which use
5585 the ELF format for binary files and the @sc{gnu} Binutils. For more details
5586 about this feature, see the description of the @option{--build-id}
5587 command-line option in @ref{Options, , Command Line Options, ld,
5591 @defvar Objfile.progspace
5592 The containing program space of the objfile as a @code{gdb.Progspace}
5593 object. @xref{Progspaces In Python}.
5596 @defvar Objfile.pretty_printers
5597 The @code{pretty_printers} attribute is a list of functions. It is
5598 used to look up pretty-printers. A @code{Value} is passed to each
5599 function in order; if the function returns @code{None}, then the
5600 search continues. Otherwise, the return value should be an object
5601 which is used to format the value. @xref{Pretty Printing API}, for more
5605 @defvar Objfile.type_printers
5606 The @code{type_printers} attribute is a list of type printer objects.
5607 @xref{Type Printing API}, for more information.
5610 @defvar Objfile.frame_filters
5611 The @code{frame_filters} attribute is a dictionary of frame filter
5612 objects. @xref{Frame Filter API}, for more information.
5615 One may add arbitrary attributes to @code{gdb.Objfile} objects
5616 in the usual Python way.
5617 This is useful if, for example, one needs to do some extra record keeping
5618 associated with the objfile.
5620 @xref{choosing attribute names}, for guidance on selecting a suitable
5621 name for new attributes.
5623 In this contrived example we record the time when @value{GDBN}
5628 (@value{GDBP}) python
5630 def new_objfile_handler(event):
5631 # Set the time_loaded attribute of the new objfile.
5632 event.new_objfile.time_loaded = datetime.datetime.today()
5633 gdb.events.new_objfile.connect(new_objfile_handler)
5637 (@value{GDBP}) file ./hello
5638 Reading symbols from ./hello...
5639 (@value{GDBP}) python print(gdb.objfiles()[0].time_loaded)
5640 2014-10-09 11:41:36.770345
5644 A @code{gdb.Objfile} object has the following methods:
5646 @defun Objfile.is_valid ()
5647 Returns @code{True} if the @code{gdb.Objfile} object is valid,
5648 @code{False} if not. A @code{gdb.Objfile} object can become invalid
5649 if the object file it refers to is not loaded in @value{GDBN} any
5650 longer. All other @code{gdb.Objfile} methods will throw an exception
5651 if it is invalid at the time the method is called.
5654 @defun Objfile.add_separate_debug_file (file)
5655 Add @var{file} to the list of files that @value{GDBN} will search for
5656 debug information for the objfile.
5657 This is useful when the debug info has been removed from the program
5658 and stored in a separate file. @value{GDBN} has built-in support for
5659 finding separate debug info files (@pxref{Separate Debug Files}), but if
5660 the file doesn't live in one of the standard places that @value{GDBN}
5661 searches then this function can be used to add a debug info file
5662 from a different place.
5665 @defun Objfile.lookup_global_symbol (name @r{[}, domain@r{]})
5666 Search for a global symbol named @var{name} in this objfile. Optionally, the
5667 search scope can be restricted with the @var{domain} argument.
5668 The @var{domain} argument must be a domain constant defined in the @code{gdb}
5669 module and described in @ref{Symbols In Python}. This function is similar to
5670 @code{gdb.lookup_global_symbol}, except that the search is limited to this
5673 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
5677 @defun Objfile.lookup_static_symbol (name @r{[}, domain@r{]})
5678 Like @code{Objfile.lookup_global_symbol}, but searches for a global
5679 symbol with static linkage named @var{name} in this objfile.
5682 @node Frames In Python
5683 @subsubsection Accessing inferior stack frames from Python
5685 @cindex frames in python
5686 When the debugged program stops, @value{GDBN} is able to analyze its call
5687 stack (@pxref{Frames,,Stack frames}). The @code{gdb.Frame} class
5688 represents a frame in the stack. A @code{gdb.Frame} object is only valid
5689 while its corresponding frame exists in the inferior's stack. If you try
5690 to use an invalid frame object, @value{GDBN} will throw a @code{gdb.error}
5691 exception (@pxref{Exception Handling}).
5693 Two @code{gdb.Frame} objects can be compared for equality with the @code{==}
5697 (@value{GDBP}) python print gdb.newest_frame() == gdb.selected_frame ()
5701 The following frame-related functions are available in the @code{gdb} module:
5703 @defun gdb.selected_frame ()
5704 Return the selected frame object. (@pxref{Selection,,Selecting a Frame}).
5707 @defun gdb.newest_frame ()
5708 Return the newest frame object for the selected thread.
5711 @defun gdb.frame_stop_reason_string (reason)
5712 Return a string explaining the reason why @value{GDBN} stopped unwinding
5713 frames, as expressed by the given @var{reason} code (an integer, see the
5714 @code{unwind_stop_reason} method further down in this section).
5717 @defun gdb.invalidate_cached_frames
5718 @value{GDBN} internally keeps a cache of the frames that have been
5719 unwound. This function invalidates this cache.
5721 This function should not generally be called by ordinary Python code.
5722 It is documented for the sake of completeness.
5725 A @code{gdb.Frame} object has the following methods:
5727 @defun Frame.is_valid ()
5728 Returns true if the @code{gdb.Frame} object is valid, false if not.
5729 A frame object can become invalid if the frame it refers to doesn't
5730 exist anymore in the inferior. All @code{gdb.Frame} methods will throw
5731 an exception if it is invalid at the time the method is called.
5734 @defun Frame.name ()
5735 Returns the function name of the frame, or @code{None} if it can't be
5739 @defun Frame.architecture ()
5740 Returns the @code{gdb.Architecture} object corresponding to the frame's
5741 architecture. @xref{Architectures In Python}.
5744 @defun Frame.type ()
5745 Returns the type of the frame. The value can be one of:
5747 @item gdb.NORMAL_FRAME
5748 An ordinary stack frame.
5750 @item gdb.DUMMY_FRAME
5751 A fake stack frame that was created by @value{GDBN} when performing an
5752 inferior function call.
5754 @item gdb.INLINE_FRAME
5755 A frame representing an inlined function. The function was inlined
5756 into a @code{gdb.NORMAL_FRAME} that is older than this one.
5758 @item gdb.TAILCALL_FRAME
5759 A frame representing a tail call. @xref{Tail Call Frames}.
5761 @item gdb.SIGTRAMP_FRAME
5762 A signal trampoline frame. This is the frame created by the OS when
5763 it calls into a signal handler.
5765 @item gdb.ARCH_FRAME
5766 A fake stack frame representing a cross-architecture call.
5768 @item gdb.SENTINEL_FRAME
5769 This is like @code{gdb.NORMAL_FRAME}, but it is only used for the
5774 @defun Frame.unwind_stop_reason ()
5775 Return an integer representing the reason why it's not possible to find
5776 more frames toward the outermost frame. Use
5777 @code{gdb.frame_stop_reason_string} to convert the value returned by this
5778 function to a string. The value can be one of:
5781 @item gdb.FRAME_UNWIND_NO_REASON
5782 No particular reason (older frames should be available).
5784 @item gdb.FRAME_UNWIND_NULL_ID
5785 The previous frame's analyzer returns an invalid result. This is no
5786 longer used by @value{GDBN}, and is kept only for backward
5789 @item gdb.FRAME_UNWIND_OUTERMOST
5790 This frame is the outermost.
5792 @item gdb.FRAME_UNWIND_UNAVAILABLE
5793 Cannot unwind further, because that would require knowing the
5794 values of registers or memory that have not been collected.
5796 @item gdb.FRAME_UNWIND_INNER_ID
5797 This frame ID looks like it ought to belong to a NEXT frame,
5798 but we got it for a PREV frame. Normally, this is a sign of
5799 unwinder failure. It could also indicate stack corruption.
5801 @item gdb.FRAME_UNWIND_SAME_ID
5802 This frame has the same ID as the previous one. That means
5803 that unwinding further would almost certainly give us another
5804 frame with exactly the same ID, so break the chain. Normally,
5805 this is a sign of unwinder failure. It could also indicate
5808 @item gdb.FRAME_UNWIND_NO_SAVED_PC
5809 The frame unwinder did not find any saved PC, but we needed
5810 one to unwind further.
5812 @item gdb.FRAME_UNWIND_MEMORY_ERROR
5813 The frame unwinder caused an error while trying to access memory.
5815 @item gdb.FRAME_UNWIND_FIRST_ERROR
5816 Any stop reason greater or equal to this value indicates some kind
5817 of error. This special value facilitates writing code that tests
5818 for errors in unwinding in a way that will work correctly even if
5819 the list of the other values is modified in future @value{GDBN}
5820 versions. Using it, you could write:
5822 reason = gdb.selected_frame().unwind_stop_reason ()
5823 reason_str = gdb.frame_stop_reason_string (reason)
5824 if reason >= gdb.FRAME_UNWIND_FIRST_ERROR:
5825 print ("An error occurred: %s" % reason_str)
5832 Returns the frame's resume address.
5835 @defun Frame.block ()
5836 Return the frame's code block. @xref{Blocks In Python}. If the frame
5837 does not have a block -- for example, if there is no debugging
5838 information for the code in question -- then this will throw an
5842 @defun Frame.function ()
5843 Return the symbol for the function corresponding to this frame.
5844 @xref{Symbols In Python}.
5847 @defun Frame.older ()
5848 Return the frame that called this frame. If this is the oldest frame,
5852 @defun Frame.newer ()
5853 Return the frame called by this frame. If this is the newest frame,
5857 @defun Frame.find_sal ()
5858 Return the frame's symtab and line object.
5859 @xref{Symbol Tables In Python}.
5862 @anchor{gdbpy_frame_read_register}
5863 @defun Frame.read_register (register)
5864 Return the value of @var{register} in this frame. Returns a
5865 @code{Gdb.Value} object. Throws an exception if @var{register} does
5866 not exist. The @var{register} argument must be one of the following:
5869 A string that is the name of a valid register (e.g., @code{'sp'} or
5872 A @code{gdb.RegisterDescriptor} object (@pxref{Registers In Python}).
5874 A @value{GDBN} internal, platform specific number. Using these
5875 numbers is supported for historic reasons, but is not recommended as
5876 future changes to @value{GDBN} could change the mapping between
5877 numbers and the registers they represent, breaking any Python code
5878 that uses the platform-specific numbers. The numbers are usually
5879 found in the corresponding @file{@var{platform}-tdep.h} file in the
5880 @value{GDBN} source tree.
5882 Using a string to access registers will be slightly slower than the
5883 other two methods as @value{GDBN} must look up the mapping between
5884 name and internal register number. If performance is critical
5885 consider looking up and caching a @code{gdb.RegisterDescriptor}
5889 @defun Frame.read_var (variable @r{[}, block@r{]})
5890 Return the value of @var{variable} in this frame. If the optional
5891 argument @var{block} is provided, search for the variable from that
5892 block; otherwise start at the frame's current block (which is
5893 determined by the frame's current program counter). The @var{variable}
5894 argument must be a string or a @code{gdb.Symbol} object; @var{block} must be a
5895 @code{gdb.Block} object.
5898 @defun Frame.select ()
5899 Set this frame to be the selected frame. @xref{Stack, ,Examining the
5903 @defun Frame.static_link ()
5904 In some languages (e.g., Ada, but also a GNU C extension), a nested
5905 function can access the variables in the outer scope. This is done
5906 via a ``static link'', which is a reference from the nested frame to
5907 the appropriate outer frame.
5909 This method returns this frame's static link frame, if one exists. If
5910 there is no static link, this method returns @code{None}.
5913 @defun Frame.level ()
5914 Return an integer, the stack frame level for this frame. @xref{Frames, ,Stack Frames}.
5917 @defun Frame.language ()
5918 Return a string, the source language for this frame.
5921 @node Blocks In Python
5922 @subsubsection Accessing blocks from Python
5924 @cindex blocks in python
5927 In @value{GDBN}, symbols are stored in blocks. A block corresponds
5928 roughly to a scope in the source code. Blocks are organized
5929 hierarchically, and are represented individually in Python as a
5930 @code{gdb.Block}. Blocks rely on debugging information being
5933 A frame has a block. Please see @ref{Frames In Python}, for a more
5934 in-depth discussion of frames.
5936 The outermost block is known as the @dfn{global block}. The global
5937 block typically holds public global variables and functions.
5939 The block nested just inside the global block is the @dfn{static
5940 block}. The static block typically holds file-scoped variables and
5943 @value{GDBN} provides a method to get a block's superblock, but there
5944 is currently no way to examine the sub-blocks of a block, or to
5945 iterate over all the blocks in a symbol table (@pxref{Symbol Tables In
5948 Here is a short example that should help explain blocks:
5951 /* This is in the global block. */
5954 /* This is in the static block. */
5955 static int file_scope;
5957 /* 'function' is in the global block, and 'argument' is
5958 in a block nested inside of 'function'. */
5959 int function (int argument)
5961 /* 'local' is in a block inside 'function'. It may or may
5962 not be in the same block as 'argument'. */
5966 /* 'inner' is in a block whose superblock is the one holding
5970 /* If this call is expanded by the compiler, you may see
5971 a nested block here whose function is 'inline_function'
5972 and whose superblock is the one holding 'inner'. */
5978 A @code{gdb.Block} is iterable. The iterator returns the symbols
5979 (@pxref{Symbols In Python}) local to the block. Python programs
5980 should not assume that a specific block object will always contain a
5981 given symbol, since changes in @value{GDBN} features and
5982 infrastructure may cause symbols move across blocks in a symbol
5983 table. You can also use Python's @dfn{dictionary syntax} to access
5984 variables in this block, e.g.:
5987 symbol = some_block['variable'] # symbol is of type gdb.Symbol
5990 The following block-related functions are available in the @code{gdb}
5993 @defun gdb.block_for_pc (pc)
5994 Return the innermost @code{gdb.Block} containing the given @var{pc}
5995 value. If the block cannot be found for the @var{pc} value specified,
5996 the function will return @code{None}. This is identical to
5997 @code{gdb.current_progspace().block_for_pc(pc)} and is included for
5998 historical compatibility.
6001 A @code{gdb.Block} object has the following methods:
6003 @defun Block.is_valid ()
6004 Returns @code{True} if the @code{gdb.Block} object is valid,
6005 @code{False} if not. A block object can become invalid if the block it
6006 refers to doesn't exist anymore in the inferior. All other
6007 @code{gdb.Block} methods will throw an exception if it is invalid at
6008 the time the method is called. The block's validity is also checked
6009 during iteration over symbols of the block.
6012 A @code{gdb.Block} object has the following attributes:
6015 The start address of the block. This attribute is not writable.
6019 One past the last address that appears in the block. This attribute
6023 @defvar Block.function
6024 The name of the block represented as a @code{gdb.Symbol}. If the
6025 block is not named, then this attribute holds @code{None}. This
6026 attribute is not writable.
6028 For ordinary function blocks, the superblock is the static block.
6029 However, you should note that it is possible for a function block to
6030 have a superblock that is not the static block -- for instance this
6031 happens for an inlined function.
6034 @defvar Block.superblock
6035 The block containing this block. If this parent block does not exist,
6036 this attribute holds @code{None}. This attribute is not writable.
6039 @defvar Block.global_block
6040 The global block associated with this block. This attribute is not
6044 @defvar Block.static_block
6045 The static block associated with this block. This attribute is not
6049 @defvar Block.is_global
6050 @code{True} if the @code{gdb.Block} object is a global block,
6051 @code{False} if not. This attribute is not
6055 @defvar Block.is_static
6056 @code{True} if the @code{gdb.Block} object is a static block,
6057 @code{False} if not. This attribute is not writable.
6060 @node Symbols In Python
6061 @subsubsection Python representation of Symbols
6063 @cindex symbols in python
6066 @value{GDBN} represents every variable, function and type as an
6067 entry in a symbol table. @xref{Symbols, ,Examining the Symbol Table}.
6068 Similarly, Python represents these symbols in @value{GDBN} with the
6069 @code{gdb.Symbol} object.
6071 The following symbol-related functions are available in the @code{gdb}
6074 @defun gdb.lookup_symbol (name @r{[}, block @r{[}, domain@r{]]})
6075 This function searches for a symbol by name. The search scope can be
6076 restricted to the parameters defined in the optional domain and block
6079 @var{name} is the name of the symbol. It must be a string. The
6080 optional @var{block} argument restricts the search to symbols visible
6081 in that @var{block}. The @var{block} argument must be a
6082 @code{gdb.Block} object. If omitted, the block for the current frame
6083 is used. The optional @var{domain} argument restricts
6084 the search to the domain type. The @var{domain} argument must be a
6085 domain constant defined in the @code{gdb} module and described later
6088 The result is a tuple of two elements.
6089 The first element is a @code{gdb.Symbol} object or @code{None} if the symbol
6091 If the symbol is found, the second element is @code{True} if the symbol
6092 is a field of a method's object (e.g., @code{this} in C@t{++}),
6093 otherwise it is @code{False}.
6094 If the symbol is not found, the second element is @code{False}.
6097 @defun gdb.lookup_global_symbol (name @r{[}, domain@r{]})
6098 This function searches for a global symbol by name.
6099 The search scope can be restricted to by the domain argument.
6101 @var{name} is the name of the symbol. It must be a string.
6102 The optional @var{domain} argument restricts the search to the domain type.
6103 The @var{domain} argument must be a domain constant defined in the @code{gdb}
6104 module and described later in this chapter.
6106 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
6110 @defun gdb.lookup_static_symbol (name @r{[}, domain@r{]})
6111 This function searches for a global symbol with static linkage by name.
6112 The search scope can be restricted to by the domain argument.
6114 @var{name} is the name of the symbol. It must be a string.
6115 The optional @var{domain} argument restricts the search to the domain type.
6116 The @var{domain} argument must be a domain constant defined in the @code{gdb}
6117 module and described later in this chapter.
6119 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
6122 Note that this function will not find function-scoped static variables. To look
6123 up such variables, iterate over the variables of the function's
6124 @code{gdb.Block} and check that @code{block.addr_class} is
6125 @code{gdb.SYMBOL_LOC_STATIC}.
6127 There can be multiple global symbols with static linkage with the same
6128 name. This function will only return the first matching symbol that
6129 it finds. Which symbol is found depends on where @value{GDBN} is
6130 currently stopped, as @value{GDBN} will first search for matching
6131 symbols in the current object file, and then search all other object
6132 files. If the application is not yet running then @value{GDBN} will
6133 search all object files in the order they appear in the debug
6137 @defun gdb.lookup_static_symbols (name @r{[}, domain@r{]})
6138 Similar to @code{gdb.lookup_static_symbol}, this function searches for
6139 global symbols with static linkage by name, and optionally restricted
6140 by the domain argument. However, this function returns a list of all
6141 matching symbols found, not just the first one.
6143 @var{name} is the name of the symbol. It must be a string.
6144 The optional @var{domain} argument restricts the search to the domain type.
6145 The @var{domain} argument must be a domain constant defined in the @code{gdb}
6146 module and described later in this chapter.
6148 The result is a list of @code{gdb.Symbol} objects which could be empty
6149 if no matching symbols were found.
6151 Note that this function will not find function-scoped static variables. To look
6152 up such variables, iterate over the variables of the function's
6153 @code{gdb.Block} and check that @code{block.addr_class} is
6154 @code{gdb.SYMBOL_LOC_STATIC}.
6157 A @code{gdb.Symbol} object has the following attributes:
6160 The type of the symbol or @code{None} if no type is recorded.
6161 This attribute is represented as a @code{gdb.Type} object.
6162 @xref{Types In Python}. This attribute is not writable.
6165 @defvar Symbol.symtab
6166 The symbol table in which the symbol appears. This attribute is
6167 represented as a @code{gdb.Symtab} object. @xref{Symbol Tables In
6168 Python}. This attribute is not writable.
6172 The line number in the source code at which the symbol was defined.
6177 The name of the symbol as a string. This attribute is not writable.
6180 @defvar Symbol.linkage_name
6181 The name of the symbol, as used by the linker (i.e., may be mangled).
6182 This attribute is not writable.
6185 @defvar Symbol.print_name
6186 The name of the symbol in a form suitable for output. This is either
6187 @code{name} or @code{linkage_name}, depending on whether the user
6188 asked @value{GDBN} to display demangled or mangled names.
6191 @defvar Symbol.addr_class
6192 The address class of the symbol. This classifies how to find the value
6193 of a symbol. Each address class is a constant defined in the
6194 @code{gdb} module and described later in this chapter.
6197 @defvar Symbol.needs_frame
6198 This is @code{True} if evaluating this symbol's value requires a frame
6199 (@pxref{Frames In Python}) and @code{False} otherwise. Typically,
6200 local variables will require a frame, but other symbols will not.
6203 @defvar Symbol.is_argument
6204 @code{True} if the symbol is an argument of a function.
6207 @defvar Symbol.is_constant
6208 @code{True} if the symbol is a constant.
6211 @defvar Symbol.is_function
6212 @code{True} if the symbol is a function or a method.
6215 @defvar Symbol.is_variable
6216 @code{True} if the symbol is a variable, as opposed to something like
6217 a function or type. Note that this also returns @code{False} for
6221 A @code{gdb.Symbol} object has the following methods:
6223 @defun Symbol.is_valid ()
6224 Returns @code{True} if the @code{gdb.Symbol} object is valid,
6225 @code{False} if not. A @code{gdb.Symbol} object can become invalid if
6226 the symbol it refers to does not exist in @value{GDBN} any longer.
6227 All other @code{gdb.Symbol} methods will throw an exception if it is
6228 invalid at the time the method is called.
6231 @defun Symbol.value (@r{[}frame@r{]})
6232 Compute the value of the symbol, as a @code{gdb.Value}. For
6233 functions, this computes the address of the function, cast to the
6234 appropriate type. If the symbol requires a frame in order to compute
6235 its value, then @var{frame} must be given. If @var{frame} is not
6236 given, or if @var{frame} is invalid, then this method will throw an
6240 The available domain categories in @code{gdb.Symbol} are represented
6241 as constants in the @code{gdb} module:
6244 @vindex SYMBOL_UNDEF_DOMAIN
6245 @item gdb.SYMBOL_UNDEF_DOMAIN
6246 This is used when a domain has not been discovered or none of the
6247 following domains apply. This usually indicates an error either
6248 in the symbol information or in @value{GDBN}'s handling of symbols.
6250 @vindex SYMBOL_VAR_DOMAIN
6251 @item gdb.SYMBOL_VAR_DOMAIN
6252 This domain contains variables.
6254 @vindex SYMBOL_FUNCTION_DOMAIN
6255 @item gdb.SYMBOL_FUNCTION_DOMAIN
6256 This domain contains functions.
6258 @vindex SYMBOL_TYPE_DOMAIN
6259 @item gdb.SYMBOL_TYPE_DOMAIN
6260 This domain contains types. In a C-like language, types using a tag
6261 (the name appearing after a @code{struct}, @code{union}, or
6262 @code{enum} keyword) will not appear here; in other languages, all
6263 types are in this domain.
6265 @vindex SYMBOL_STRUCT_DOMAIN
6266 @item gdb.SYMBOL_STRUCT_DOMAIN
6267 This domain holds struct, union and enum tag names. This domain is
6268 only used for C-like languages. For example, in this code:
6270 struct type_one @{ int x; @};
6271 typedef struct type_one type_two;
6273 Here @code{type_one} will be in @code{SYMBOL_STRUCT_DOMAIN}, but
6274 @code{type_two} will be in @code{SYMBOL_TYPE_DOMAIN}.
6276 @vindex SYMBOL_LABEL_DOMAIN
6277 @item gdb.SYMBOL_LABEL_DOMAIN
6278 This domain contains names of labels (for gotos).
6280 @vindex SYMBOL_MODULE_DOMAIN
6281 @item gdb.SYMBOL_MODULE_DOMAIN
6282 This domain contains names of Fortran module types.
6284 @vindex SYMBOL_COMMON_BLOCK_DOMAIN
6285 @item gdb.SYMBOL_COMMON_BLOCK_DOMAIN
6286 This domain contains names of Fortran common blocks.
6289 When searching for a symbol, the desired domain constant can be passed
6290 verbatim to the lookup function. For example:
6292 symbol = gdb.lookup_symbol ("name", domain=gdb.SYMBOL_VAR_DOMAIN)
6295 For more complex searches, there is a corresponding set of constants,
6296 each named after one of the preceding constants, but with the
6297 @samp{SEARCH} prefix replacing the @samp{SYMBOL} prefix; for example,
6298 @code{SEARCH_LABEL_DOMAIN}. These may be or'd together to form a
6299 search constant, e.g.:
6301 symbol = gdb.lookup_symbol ("name",
6302 domain=gdb.SEARCH_VAR_DOMAIN | gdb.SEARCH_TYPE_DOMAIN)
6305 The available address class categories in @code{gdb.Symbol} are represented
6306 as constants in the @code{gdb} module:
6309 @vindex SYMBOL_LOC_UNDEF
6310 @item gdb.SYMBOL_LOC_UNDEF
6311 If this is returned by address class, it indicates an error either in
6312 the symbol information or in @value{GDBN}'s handling of symbols.
6314 @vindex SYMBOL_LOC_CONST
6315 @item gdb.SYMBOL_LOC_CONST
6316 Value is constant int.
6318 @vindex SYMBOL_LOC_STATIC
6319 @item gdb.SYMBOL_LOC_STATIC
6320 Value is at a fixed address.
6322 @vindex SYMBOL_LOC_REGISTER
6323 @item gdb.SYMBOL_LOC_REGISTER
6324 Value is in a register.
6326 @vindex SYMBOL_LOC_ARG
6327 @item gdb.SYMBOL_LOC_ARG
6328 Value is an argument. This value is at the offset stored within the
6329 symbol inside the frame's argument list.
6331 @vindex SYMBOL_LOC_REF_ARG
6332 @item gdb.SYMBOL_LOC_REF_ARG
6333 Value address is stored in the frame's argument list. Just like
6334 @code{LOC_ARG} except that the value's address is stored at the
6335 offset, not the value itself.
6337 @vindex SYMBOL_LOC_REGPARM_ADDR
6338 @item gdb.SYMBOL_LOC_REGPARM_ADDR
6339 Value is a specified register. Just like @code{LOC_REGISTER} except
6340 the register holds the address of the argument instead of the argument
6343 @vindex SYMBOL_LOC_LOCAL
6344 @item gdb.SYMBOL_LOC_LOCAL
6345 Value is a local variable.
6347 @vindex SYMBOL_LOC_TYPEDEF
6348 @item gdb.SYMBOL_LOC_TYPEDEF
6349 Value not used. Symbols in the domain @code{SYMBOL_STRUCT_DOMAIN} all
6352 @vindex SYMBOL_LOC_LABEL
6353 @item gdb.SYMBOL_LOC_LABEL
6356 @vindex SYMBOL_LOC_BLOCK
6357 @item gdb.SYMBOL_LOC_BLOCK
6360 @vindex SYMBOL_LOC_CONST_BYTES
6361 @item gdb.SYMBOL_LOC_CONST_BYTES
6362 Value is a byte-sequence.
6364 @vindex SYMBOL_LOC_UNRESOLVED
6365 @item gdb.SYMBOL_LOC_UNRESOLVED
6366 Value is at a fixed address, but the address of the variable has to be
6367 determined from the minimal symbol table whenever the variable is
6370 @vindex SYMBOL_LOC_OPTIMIZED_OUT
6371 @item gdb.SYMBOL_LOC_OPTIMIZED_OUT
6372 The value does not actually exist in the program.
6374 @vindex SYMBOL_LOC_COMPUTED
6375 @item gdb.SYMBOL_LOC_COMPUTED
6376 The value's address is a computed location.
6378 @vindex SYMBOL_LOC_COMMON_BLOCK
6379 @item gdb.SYMBOL_LOC_COMMON_BLOCK
6380 The value's address is a symbol. This is only used for Fortran common
6384 @node Symbol Tables In Python
6385 @subsubsection Symbol table representation in Python
6387 @cindex symbol tables in python
6389 @tindex gdb.Symtab_and_line
6391 Access to symbol table data maintained by @value{GDBN} on the inferior
6392 is exposed to Python via two objects: @code{gdb.Symtab_and_line} and
6393 @code{gdb.Symtab}. Symbol table and line data for a frame is returned
6394 from the @code{find_sal} method in @code{gdb.Frame} object.
6395 @xref{Frames In Python}.
6397 For more information on @value{GDBN}'s symbol table management, see
6398 @ref{Symbols, ,Examining the Symbol Table}, for more information.
6400 A @code{gdb.Symtab_and_line} object has the following attributes:
6402 @defvar Symtab_and_line.symtab
6403 The symbol table object (@code{gdb.Symtab}) for this frame.
6404 This attribute is not writable.
6407 @defvar Symtab_and_line.pc
6408 Indicates the start of the address range occupied by code for the
6409 current source line. This attribute is not writable.
6412 @defvar Symtab_and_line.last
6413 Indicates the end of the address range occupied by code for the current
6414 source line. This attribute is not writable.
6417 @defvar Symtab_and_line.line
6418 Indicates the current line number for this object. This
6419 attribute is not writable.
6422 A @code{gdb.Symtab_and_line} object has the following methods:
6424 @defun Symtab_and_line.is_valid ()
6425 Returns @code{True} if the @code{gdb.Symtab_and_line} object is valid,
6426 @code{False} if not. A @code{gdb.Symtab_and_line} object can become
6427 invalid if the Symbol table and line object it refers to does not
6428 exist in @value{GDBN} any longer. All other
6429 @code{gdb.Symtab_and_line} methods will throw an exception if it is
6430 invalid at the time the method is called.
6433 A @code{gdb.Symtab} object has the following attributes:
6435 @defvar Symtab.filename
6436 The symbol table's source filename. This attribute is not writable.
6439 @defvar Symtab.objfile
6440 The symbol table's backing object file. @xref{Objfiles In Python}.
6441 This attribute is not writable.
6444 @defvar Symtab.producer
6445 The name and possibly version number of the program that
6446 compiled the code in the symbol table.
6447 The contents of this string is up to the compiler.
6448 If no producer information is available then @code{None} is returned.
6449 This attribute is not writable.
6452 A @code{gdb.Symtab} object has the following methods:
6454 @defun Symtab.is_valid ()
6455 Returns @code{True} if the @code{gdb.Symtab} object is valid,
6456 @code{False} if not. A @code{gdb.Symtab} object can become invalid if
6457 the symbol table it refers to does not exist in @value{GDBN} any
6458 longer. All other @code{gdb.Symtab} methods will throw an exception
6459 if it is invalid at the time the method is called.
6462 @defun Symtab.fullname ()
6463 Return the symbol table's source absolute file name.
6466 @defun Symtab.global_block ()
6467 Return the global block of the underlying symbol table.
6468 @xref{Blocks In Python}.
6471 @defun Symtab.static_block ()
6472 Return the static block of the underlying symbol table.
6473 @xref{Blocks In Python}.
6476 @defun Symtab.linetable ()
6477 Return the line table associated with the symbol table.
6478 @xref{Line Tables In Python}.
6481 @node Line Tables In Python
6482 @subsubsection Manipulating line tables using Python
6484 @cindex line tables in python
6485 @tindex gdb.LineTable
6487 Python code can request and inspect line table information from a
6488 symbol table that is loaded in @value{GDBN}. A line table is a
6489 mapping of source lines to their executable locations in memory. To
6490 acquire the line table information for a particular symbol table, use
6491 the @code{linetable} function (@pxref{Symbol Tables In Python}).
6493 A @code{gdb.LineTable} is iterable. The iterator returns
6494 @code{LineTableEntry} objects that correspond to the source line and
6495 address for each line table entry. @code{LineTableEntry} objects have
6496 the following attributes:
6498 @defvar LineTableEntry.line
6499 The source line number for this line table entry. This number
6500 corresponds to the actual line of source. This attribute is not
6504 @defvar LineTableEntry.pc
6505 The address that is associated with the line table entry where the
6506 executable code for that source line resides in memory. This
6507 attribute is not writable.
6510 As there can be multiple addresses for a single source line, you may
6511 receive multiple @code{LineTableEntry} objects with matching
6512 @code{line} attributes, but with different @code{pc} attributes. The
6513 iterator is sorted in ascending @code{pc} order. Here is a small
6514 example illustrating iterating over a line table.
6517 symtab = gdb.selected_frame().find_sal().symtab
6518 linetable = symtab.linetable()
6519 for line in linetable:
6520 print ("Line: "+str(line.line)+" Address: "+hex(line.pc))
6523 This will have the following output:
6526 Line: 33 Address: 0x4005c8L
6527 Line: 37 Address: 0x4005caL
6528 Line: 39 Address: 0x4005d2L
6529 Line: 40 Address: 0x4005f8L
6530 Line: 42 Address: 0x4005ffL
6531 Line: 44 Address: 0x400608L
6532 Line: 42 Address: 0x40060cL
6533 Line: 45 Address: 0x400615L
6536 In addition to being able to iterate over a @code{LineTable}, it also
6537 has the following direct access methods:
6539 @defun LineTable.line (line)
6540 Return a Python @code{Tuple} of @code{LineTableEntry} objects for any
6541 entries in the line table for the given @var{line}, which specifies
6542 the source code line. If there are no entries for that source code
6543 @var{line}, the Python @code{None} is returned.
6546 @defun LineTable.has_line (line)
6547 Return a Python @code{Boolean} indicating whether there is an entry in
6548 the line table for this source line. Return @code{True} if an entry
6549 is found, or @code{False} if not.
6552 @defun LineTable.source_lines ()
6553 Return a Python @code{List} of the source line numbers in the symbol
6554 table. Only lines with executable code locations are returned. The
6555 contents of the @code{List} will just be the source line entries
6556 represented as Python @code{Long} values.
6559 @node Breakpoints In Python
6560 @subsubsection Manipulating breakpoints using Python
6562 @cindex breakpoints in python
6563 @tindex gdb.Breakpoint
6565 Python code can manipulate breakpoints via the @code{gdb.Breakpoint}
6568 A breakpoint can be created using one of the two forms of the
6569 @code{gdb.Breakpoint} constructor. The first one accepts a string
6570 like one would pass to the @code{break}
6571 (@pxref{Set Breaks,,Setting Breakpoints}) and @code{watch}
6572 (@pxref{Set Watchpoints, , Setting Watchpoints}) commands, and can be used to
6573 create both breakpoints and watchpoints. The second accepts separate Python
6574 arguments similar to @ref{Explicit Locations}, and can only be used to create
6577 @defun Breakpoint.__init__ (spec @r{[}, type @r{][}, wp_class @r{][}, internal @r{][}, temporary @r{][}, qualified @r{]})
6578 Create a new breakpoint according to @var{spec}, which is a string naming the
6579 location of a breakpoint, or an expression that defines a watchpoint. The
6580 string should describe a location in a format recognized by the @code{break}
6581 command (@pxref{Set Breaks,,Setting Breakpoints}) or, in the case of a
6582 watchpoint, by the @code{watch} command
6583 (@pxref{Set Watchpoints, , Setting Watchpoints}).
6585 The optional @var{type} argument specifies the type of the breakpoint to create,
6588 The optional @var{wp_class} argument defines the class of watchpoint to create,
6589 if @var{type} is @code{gdb.BP_WATCHPOINT}. If @var{wp_class} is omitted, it
6590 defaults to @code{gdb.WP_WRITE}.
6592 The optional @var{internal} argument allows the breakpoint to become invisible
6593 to the user. The breakpoint will neither be reported when created, nor will it
6594 be listed in the output from @code{info breakpoints} (but will be listed with
6595 the @code{maint info breakpoints} command).
6597 The optional @var{temporary} argument makes the breakpoint a temporary
6598 breakpoint. Temporary breakpoints are deleted after they have been hit. Any
6599 further access to the Python breakpoint after it has been hit will result in a
6600 runtime error (as that breakpoint has now been automatically deleted).
6602 The optional @var{qualified} argument is a boolean that allows interpreting
6603 the function passed in @code{spec} as a fully-qualified name. It is equivalent
6604 to @code{break}'s @code{-qualified} flag (@pxref{Linespec Locations} and
6605 @ref{Explicit Locations}).
6609 @defun Breakpoint.__init__ (@r{[} source @r{][}, function @r{][}, label @r{][}, line @r{]}, @r{][} internal @r{][}, temporary @r{][}, qualified @r{]})
6610 This second form of creating a new breakpoint specifies the explicit
6611 location (@pxref{Explicit Locations}) using keywords. The new breakpoint will
6612 be created in the specified source file @var{source}, at the specified
6613 @var{function}, @var{label} and @var{line}.
6615 @var{internal}, @var{temporary} and @var{qualified} have the same usage as
6616 explained previously.
6619 The available types are represented by constants defined in the @code{gdb}
6623 @vindex BP_BREAKPOINT
6624 @item gdb.BP_BREAKPOINT
6625 Normal code breakpoint.
6627 @vindex BP_HARDWARE_BREAKPOINT
6628 @item gdb.BP_HARDWARE_BREAKPOINT
6629 Hardware assisted code breakpoint.
6631 @vindex BP_WATCHPOINT
6632 @item gdb.BP_WATCHPOINT
6633 Watchpoint breakpoint.
6635 @vindex BP_HARDWARE_WATCHPOINT
6636 @item gdb.BP_HARDWARE_WATCHPOINT
6637 Hardware assisted watchpoint.
6639 @vindex BP_READ_WATCHPOINT
6640 @item gdb.BP_READ_WATCHPOINT
6641 Hardware assisted read watchpoint.
6643 @vindex BP_ACCESS_WATCHPOINT
6644 @item gdb.BP_ACCESS_WATCHPOINT
6645 Hardware assisted access watchpoint.
6647 @vindex BP_CATCHPOINT
6648 @item gdb.BP_CATCHPOINT
6649 Catchpoint. Currently, this type can't be used when creating
6650 @code{gdb.Breakpoint} objects, but will be present in
6651 @code{gdb.Breakpoint} objects reported from
6652 @code{gdb.BreakpointEvent}s (@pxref{Events In Python}).
6655 The available watchpoint types are represented by constants defined in the
6661 Read only watchpoint.
6665 Write only watchpoint.
6669 Read/Write watchpoint.
6672 @defun Breakpoint.stop (self)
6673 The @code{gdb.Breakpoint} class can be sub-classed and, in
6674 particular, you may choose to implement the @code{stop} method.
6675 If this method is defined in a sub-class of @code{gdb.Breakpoint},
6676 it will be called when the inferior reaches any location of a
6677 breakpoint which instantiates that sub-class. If the method returns
6678 @code{True}, the inferior will be stopped at the location of the
6679 breakpoint, otherwise the inferior will continue.
6681 If there are multiple breakpoints at the same location with a
6682 @code{stop} method, each one will be called regardless of the
6683 return status of the previous. This ensures that all @code{stop}
6684 methods have a chance to execute at that location. In this scenario
6685 if one of the methods returns @code{True} but the others return
6686 @code{False}, the inferior will still be stopped.
6688 You should not alter the execution state of the inferior (i.e.@:, step,
6689 next, etc.), alter the current frame context (i.e.@:, change the current
6690 active frame), or alter, add or delete any breakpoint. As a general
6691 rule, you should not alter any data within @value{GDBN} or the inferior
6694 Example @code{stop} implementation:
6697 class MyBreakpoint (gdb.Breakpoint):
6699 inf_val = gdb.parse_and_eval("foo")
6706 @defun Breakpoint.is_valid ()
6707 Return @code{True} if this @code{Breakpoint} object is valid,
6708 @code{False} otherwise. A @code{Breakpoint} object can become invalid
6709 if the user deletes the breakpoint. In this case, the object still
6710 exists, but the underlying breakpoint does not. In the cases of
6711 watchpoint scope, the watchpoint remains valid even if execution of the
6712 inferior leaves the scope of that watchpoint.
6715 @defun Breakpoint.delete ()
6716 Permanently deletes the @value{GDBN} breakpoint. This also
6717 invalidates the Python @code{Breakpoint} object. Any further access
6718 to this object's attributes or methods will raise an error.
6721 @defvar Breakpoint.enabled
6722 This attribute is @code{True} if the breakpoint is enabled, and
6723 @code{False} otherwise. This attribute is writable. You can use it to enable
6724 or disable the breakpoint.
6727 @defvar Breakpoint.silent
6728 This attribute is @code{True} if the breakpoint is silent, and
6729 @code{False} otherwise. This attribute is writable.
6731 Note that a breakpoint can also be silent if it has commands and the
6732 first command is @code{silent}. This is not reported by the
6733 @code{silent} attribute.
6736 @defvar Breakpoint.pending
6737 This attribute is @code{True} if the breakpoint is pending, and
6738 @code{False} otherwise. @xref{Set Breaks}. This attribute is
6742 @anchor{python_breakpoint_thread}
6743 @defvar Breakpoint.thread
6744 If the breakpoint is thread-specific (@pxref{Thread-Specific
6745 Breakpoints}), this attribute holds the thread's global id. If the
6746 breakpoint is not thread-specific, this attribute is @code{None}.
6747 This attribute is writable.
6749 Only one of @code{Breakpoint.thread} or @code{Breakpoint.inferior} can
6750 be set to a valid id at any time, that is, a breakpoint can be thread
6751 specific, or inferior specific, but not both.
6754 @anchor{python_breakpoint_inferior}
6755 @defvar Breakpoint.inferior
6756 If the breakpoint is inferior-specific (@pxref{Inferior-Specific
6757 Breakpoints}), this attribute holds the inferior's id. If the
6758 breakpoint is not inferior-specific, this attribute is @code{None}.
6760 This attribute can be written for breakpoints of type
6761 @code{gdb.BP_BREAKPOINT} and @code{gdb.BP_HARDWARE_BREAKPOINT}.
6764 @defvar Breakpoint.task
6765 If the breakpoint is Ada task-specific, this attribute holds the Ada task
6766 id. If the breakpoint is not task-specific (or the underlying
6767 language is not Ada), this attribute is @code{None}. This attribute
6771 @defvar Breakpoint.ignore_count
6772 This attribute holds the ignore count for the breakpoint, an integer.
6773 This attribute is writable.
6776 @defvar Breakpoint.number
6777 This attribute holds the breakpoint's number --- the identifier used by
6778 the user to manipulate the breakpoint. This attribute is not writable.
6781 @defvar Breakpoint.type
6782 This attribute holds the breakpoint's type --- the identifier used to
6783 determine the actual breakpoint type or use-case. This attribute is not
6787 @defvar Breakpoint.visible
6788 This attribute tells whether the breakpoint is visible to the user
6789 when set, or when the @samp{info breakpoints} command is run. This
6790 attribute is not writable.
6793 @defvar Breakpoint.temporary
6794 This attribute indicates whether the breakpoint was created as a
6795 temporary breakpoint. Temporary breakpoints are automatically deleted
6796 after that breakpoint has been hit. Access to this attribute, and all
6797 other attributes and functions other than the @code{is_valid}
6798 function, will result in an error after the breakpoint has been hit
6799 (as it has been automatically deleted). This attribute is not
6803 @defvar Breakpoint.hit_count
6804 This attribute holds the hit count for the breakpoint, an integer.
6805 This attribute is writable, but currently it can only be set to zero.
6808 @defvar Breakpoint.location
6809 This attribute holds the location of the breakpoint, as specified by
6810 the user. It is a string. If the breakpoint does not have a location
6811 (that is, it is a watchpoint) the attribute's value is @code{None}. This
6812 attribute is not writable.
6815 @defvar Breakpoint.locations
6816 Get the most current list of breakpoint locations that are inserted for this
6817 breakpoint, with elements of type @code{gdb.BreakpointLocation}
6818 (described below). This functionality matches that of the
6819 @code{info breakpoint} command (@pxref{Set Breaks}), in that it only retrieves
6820 the most current list of locations, thus the list itself when returned is
6821 not updated behind the scenes. This attribute is not writable.
6824 @defvar Breakpoint.expression
6825 This attribute holds a breakpoint expression, as specified by
6826 the user. It is a string. If the breakpoint does not have an
6827 expression (the breakpoint is not a watchpoint) the attribute's value
6828 is @code{None}. This attribute is not writable.
6831 @defvar Breakpoint.condition
6832 This attribute holds the condition of the breakpoint, as specified by
6833 the user. It is a string. If there is no condition, this attribute's
6834 value is @code{None}. This attribute is writable.
6837 @defvar Breakpoint.commands
6838 This attribute holds the commands attached to the breakpoint. If
6839 there are commands, this attribute's value is a string holding all the
6840 commands, separated by newlines. If there are no commands, this
6841 attribute is @code{None}. This attribute is writable.
6844 @subheading Breakpoint Locations
6846 A breakpoint location is one of the actual places where a breakpoint has been
6847 set, represented in the Python API by the @code{gdb.BreakpointLocation}
6848 type. This type is never instantiated by the user directly, but is retrieved
6849 from @code{Breakpoint.locations} which returns a list of breakpoint
6850 locations where it is currently set. Breakpoint locations can become
6851 invalid if new symbol files are loaded or dynamically loaded libraries are
6852 closed. Accessing the attributes of an invalidated breakpoint location will
6853 throw a @code{RuntimeError} exception. Access the @code{Breakpoint.locations}
6854 attribute again to retrieve the new and valid breakpoints location list.
6856 @defvar BreakpointLocation.source
6857 This attribute returns the source file path and line number where this location
6858 was set. The type of the attribute is a tuple of @var{string} and
6859 @var{long}. If the breakpoint location doesn't have a source location,
6860 it returns None, which is the case for watchpoints and catchpoints.
6861 This will throw a @code{RuntimeError} exception if the location
6862 has been invalidated. This attribute is not writable.
6865 @defvar BreakpointLocation.address
6866 This attribute returns the address where this location was set.
6867 This attribute is of type long. This will throw a @code{RuntimeError}
6868 exception if the location has been invalidated. This attribute is
6872 @defvar BreakpointLocation.enabled
6873 This attribute holds the value for whether or not this location is enabled.
6874 This attribute is writable (boolean). This will throw a @code{RuntimeError}
6875 exception if the location has been invalidated.
6878 @defvar BreakpointLocation.owner
6879 This attribute holds a reference to the @code{gdb.Breakpoint} owner object,
6880 from which this @code{gdb.BreakpointLocation} was retrieved from.
6881 This will throw a @code{RuntimeError} exception if the location has been
6882 invalidated. This attribute is not writable.
6885 @defvar BreakpointLocation.function
6886 This attribute gets the name of the function where this location was set.
6887 If no function could be found this attribute returns @code{None}.
6888 This will throw a @code{RuntimeError} exception if the location has
6889 been invalidated. This attribute is not writable.
6892 @defvar BreakpointLocation.fullname
6893 This attribute gets the full name of where this location was set. If no
6894 full name could be found, this attribute returns @code{None}.
6895 This will throw a @code{RuntimeError} exception if the location has
6896 been invalidated. This attribute is not writable.
6899 @defvar BreakpointLocation.thread_groups
6900 This attribute gets the thread groups it was set in. It returns a @code{List}
6901 of the thread group ID's. This will throw a @code{RuntimeError}
6902 exception if the location has been invalidated. This attribute
6906 @node Finish Breakpoints in Python
6907 @subsubsection Finish Breakpoints
6909 @cindex python finish breakpoints
6910 @tindex gdb.FinishBreakpoint
6912 A finish breakpoint is a temporary breakpoint set at the return address of
6913 a frame, based on the @code{finish} command. @code{gdb.FinishBreakpoint}
6914 extends @code{gdb.Breakpoint}. The underlying breakpoint will be disabled
6915 and deleted when the execution will run out of the breakpoint scope (i.e.@:
6916 @code{Breakpoint.stop} or @code{FinishBreakpoint.out_of_scope} triggered).
6917 Finish breakpoints are thread specific and must be create with the right
6920 @defun FinishBreakpoint.__init__ (@r{[}frame@r{]} @r{[}, internal@r{]})
6921 Create a finish breakpoint at the return address of the @code{gdb.Frame}
6922 object @var{frame}. If @var{frame} is not provided, this defaults to the
6923 newest frame. The optional @var{internal} argument allows the breakpoint to
6924 become invisible to the user. @xref{Breakpoints In Python}, for further
6925 details about this argument.
6928 @defun FinishBreakpoint.out_of_scope (self)
6929 In some circumstances (e.g.@: @code{longjmp}, C@t{++} exceptions, @value{GDBN}
6930 @code{return} command, @dots{}), a function may not properly terminate, and
6931 thus never hit the finish breakpoint. When @value{GDBN} notices such a
6932 situation, the @code{out_of_scope} callback will be triggered.
6934 You may want to sub-class @code{gdb.FinishBreakpoint} and override this
6938 class MyFinishBreakpoint (gdb.FinishBreakpoint)
6940 print ("normal finish")
6943 def out_of_scope ():
6944 print ("abnormal finish")
6948 @defvar FinishBreakpoint.return_value
6949 When @value{GDBN} is stopped at a finish breakpoint and the frame
6950 used to build the @code{gdb.FinishBreakpoint} object had debug symbols, this
6951 attribute will contain a @code{gdb.Value} object corresponding to the return
6952 value of the function. The value will be @code{None} if the function return
6953 type is @code{void} or if the return value was not computable. This attribute
6957 @node Lazy Strings In Python
6958 @subsubsection Python representation of lazy strings
6960 @cindex lazy strings in python
6961 @tindex gdb.LazyString
6963 A @dfn{lazy string} is a string whose contents is not retrieved or
6964 encoded until it is needed.
6966 A @code{gdb.LazyString} is represented in @value{GDBN} as an
6967 @code{address} that points to a region of memory, an @code{encoding}
6968 that will be used to encode that region of memory, and a @code{length}
6969 to delimit the region of memory that represents the string. The
6970 difference between a @code{gdb.LazyString} and a string wrapped within
6971 a @code{gdb.Value} is that a @code{gdb.LazyString} will be treated
6972 differently by @value{GDBN} when printing. A @code{gdb.LazyString} is
6973 retrieved and encoded during printing, while a @code{gdb.Value}
6974 wrapping a string is immediately retrieved and encoded on creation.
6976 A @code{gdb.LazyString} object has the following functions:
6978 @defun LazyString.value ()
6979 Convert the @code{gdb.LazyString} to a @code{gdb.Value}. This value
6980 will point to the string in memory, but will lose all the delayed
6981 retrieval, encoding and handling that @value{GDBN} applies to a
6982 @code{gdb.LazyString}.
6985 @defvar LazyString.address
6986 This attribute holds the address of the string. This attribute is not
6990 @defvar LazyString.length
6991 This attribute holds the length of the string in characters. If the
6992 length is -1, then the string will be fetched and encoded up to the
6993 first null of appropriate width. This attribute is not writable.
6996 @defvar LazyString.encoding
6997 This attribute holds the encoding that will be applied to the string
6998 when the string is printed by @value{GDBN}. If the encoding is not
6999 set, or contains an empty string, then @value{GDBN} will select the
7000 most appropriate encoding when the string is printed. This attribute
7004 @defvar LazyString.type
7005 This attribute holds the type that is represented by the lazy string's
7006 type. For a lazy string this is a pointer or array type. To
7007 resolve this to the lazy string's character type, use the type's
7008 @code{target} method. @xref{Types In Python}. This attribute is not
7012 @node Architectures In Python
7013 @subsubsection Python representation of architectures
7014 @cindex Python architectures
7016 @value{GDBN} uses architecture specific parameters and artifacts in a
7017 number of its various computations. An architecture is represented
7018 by an instance of the @code{gdb.Architecture} class.
7020 A @code{gdb.Architecture} class has the following methods:
7022 @anchor{gdbpy_architecture_name}
7023 @defun Architecture.name ()
7024 Return the name (string value) of the architecture.
7027 @defun Architecture.disassemble (start_pc @r{[}, end_pc @r{[}, count@r{]]})
7028 Return a list of disassembled instructions starting from the memory
7029 address @var{start_pc}. The optional arguments @var{end_pc} and
7030 @var{count} determine the number of instructions in the returned list.
7031 If both the optional arguments @var{end_pc} and @var{count} are
7032 specified, then a list of at most @var{count} disassembled instructions
7033 whose start address falls in the closed memory address interval from
7034 @var{start_pc} to @var{end_pc} are returned. If @var{end_pc} is not
7035 specified, but @var{count} is specified, then @var{count} number of
7036 instructions starting from the address @var{start_pc} are returned. If
7037 @var{count} is not specified but @var{end_pc} is specified, then all
7038 instructions whose start address falls in the closed memory address
7039 interval from @var{start_pc} to @var{end_pc} are returned. If neither
7040 @var{end_pc} nor @var{count} are specified, then a single instruction at
7041 @var{start_pc} is returned. For all of these cases, each element of the
7042 returned list is a Python @code{dict} with the following string keys:
7047 The value corresponding to this key is a Python long integer capturing
7048 the memory address of the instruction.
7051 The value corresponding to this key is a string value which represents
7052 the instruction with assembly language mnemonics. The assembly
7053 language flavor used is the same as that specified by the current CLI
7054 variable @code{disassembly-flavor}. @xref{Machine Code}.
7057 The value corresponding to this key is the length (integer value) of the
7058 instruction in bytes.
7063 @defun Architecture.integer_type (size @r{[}, signed@r{]})
7064 This function looks up an integer type by its @var{size}, and
7065 optionally whether or not it is signed.
7067 @var{size} is the size, in bits, of the desired integer type. Only
7068 certain sizes are currently supported: 0, 8, 16, 24, 32, 64, and 128.
7070 If @var{signed} is not specified, it defaults to @code{True}. If
7071 @var{signed} is @code{False}, the returned type will be unsigned.
7073 If the indicated type cannot be found, this function will throw a
7074 @code{ValueError} exception.
7077 @anchor{gdbpy_architecture_registers}
7078 @defun Architecture.registers (@r{[} reggroup @r{]})
7079 Return a @code{gdb.RegisterDescriptorIterator} (@pxref{Registers In
7080 Python}) for all of the registers in @var{reggroup}, a string that is
7081 the name of a register group. If @var{reggroup} is omitted, or is the
7082 empty string, then the register group @samp{all} is assumed.
7085 @anchor{gdbpy_architecture_reggroups}
7086 @defun Architecture.register_groups ()
7087 Return a @code{gdb.RegisterGroupsIterator} (@pxref{Registers In
7088 Python}) for all of the register groups available for the
7089 @code{gdb.Architecture}.
7092 @node Registers In Python
7093 @subsubsection Registers In Python
7094 @cindex Registers In Python
7096 Python code can request from a @code{gdb.Architecture} information
7097 about the set of registers available
7098 (@pxref{gdbpy_architecture_registers,,@code{Architecture.registers}}).
7099 The register information is returned as a
7100 @code{gdb.RegisterDescriptorIterator}, which is an iterator that in
7101 turn returns @code{gdb.RegisterDescriptor} objects.
7103 A @code{gdb.RegisterDescriptor} does not provide the value of a
7104 register (@pxref{gdbpy_frame_read_register,,@code{Frame.read_register}}
7105 for reading a register's value), instead the @code{RegisterDescriptor}
7106 is a way to discover which registers are available for a particular
7109 A @code{gdb.RegisterDescriptor} has the following read-only properties:
7111 @defvar RegisterDescriptor.name
7112 The name of this register.
7115 It is also possible to lookup a register descriptor based on its name
7116 using the following @code{gdb.RegisterDescriptorIterator} function:
7118 @defun RegisterDescriptorIterator.find (name)
7119 Takes @var{name} as an argument, which must be a string, and returns a
7120 @code{gdb.RegisterDescriptor} for the register with that name, or
7121 @code{None} if there is no register with that name.
7124 Python code can also request from a @code{gdb.Architecture}
7125 information about the set of register groups available on a given
7127 (@pxref{gdbpy_architecture_reggroups,,@code{Architecture.register_groups}}).
7129 Every register can be a member of zero or more register groups. Some
7130 register groups are used internally within @value{GDBN} to control
7131 things like which registers must be saved when calling into the
7132 program being debugged (@pxref{Calling,,Calling Program Functions}).
7133 Other register groups exist to allow users to easily see related sets
7134 of registers in commands like @code{info registers}
7135 (@pxref{info_registers_reggroup,,@code{info registers
7138 The register groups information is returned as a
7139 @code{gdb.RegisterGroupsIterator}, which is an iterator that in turn
7140 returns @code{gdb.RegisterGroup} objects.
7142 A @code{gdb.RegisterGroup} object has the following read-only
7145 @defvar RegisterGroup.name
7146 A string that is the name of this register group.
7149 @node Connections In Python
7150 @subsubsection Connections In Python
7151 @cindex connections in python
7152 @value{GDBN} lets you run and debug multiple programs in a single
7153 session. Each program being debugged has a connection, the connection
7154 describes how @value{GDBN} controls the program being debugged.
7155 Examples of different connection types are @samp{native} and
7156 @samp{remote}. @xref{Inferiors Connections and Programs}.
7158 Connections in @value{GDBN} are represented as instances of
7159 @code{gdb.TargetConnection}, or as one of its sub-classes. To get a
7160 list of all connections use @code{gdb.connections}
7161 (@pxref{gdbpy_connections,,gdb.connections}).
7163 To get the connection for a single @code{gdb.Inferior} read its
7164 @code{gdb.Inferior.connection} attribute
7165 (@pxref{gdbpy_inferior_connection,,gdb.Inferior.connection}).
7167 Currently there is only a single sub-class of
7168 @code{gdb.TargetConnection}, @code{gdb.RemoteTargetConnection},
7169 however, additional sub-classes may be added in future releases of
7170 @value{GDBN}. As a result you should avoid writing code like:
7173 conn = gdb.selected_inferior().connection
7174 if type(conn) is gdb.RemoteTargetConnection:
7175 print("This is a remote target connection")
7179 as this may fail when more connection types are added. Instead, you
7183 conn = gdb.selected_inferior().connection
7184 if isinstance(conn, gdb.RemoteTargetConnection):
7185 print("This is a remote target connection")
7188 A @code{gdb.TargetConnection} has the following method:
7190 @defun TargetConnection.is_valid ()
7191 Return @code{True} if the @code{gdb.TargetConnection} object is valid,
7192 @code{False} if not. A @code{gdb.TargetConnection} will become
7193 invalid if the connection no longer exists within @value{GDBN}, this
7194 might happen when no inferiors are using the connection, but could be
7195 delayed until the user replaces the current target.
7197 Reading any of the @code{gdb.TargetConnection} properties will throw
7198 an exception if the connection is invalid.
7201 A @code{gdb.TargetConnection} has the following read-only properties:
7203 @defvar TargetConnection.num
7204 An integer assigned by @value{GDBN} to uniquely identify this
7205 connection. This is the same value as displayed in the @samp{Num}
7206 column of the @code{info connections} command output (@pxref{Inferiors
7207 Connections and Programs,,info connections}).
7210 @defvar TargetConnection.type
7211 A string that describes what type of connection this is. This string
7212 will be one of the valid names that can be passed to the @code{target}
7213 command (@pxref{Target Commands,,target command}).
7216 @defvar TargetConnection.description
7217 A string that gives a short description of this target type. This is
7218 the same string that is displayed in the @samp{Description} column of
7219 the @code{info connection} command output (@pxref{Inferiors
7220 Connections and Programs,,info connections}).
7223 @defvar TargetConnection.details
7224 An optional string that gives additional information about this
7225 connection. This attribute can be @code{None} if there are no
7226 additional details for this connection.
7228 An example of a connection type that might have additional details is
7229 the @samp{remote} connection, in this case the details string can
7230 contain the @samp{@var{hostname}:@var{port}} that was used to connect
7231 to the remote target.
7234 The @code{gdb.RemoteTargetConnection} class is a sub-class of
7235 @code{gdb.TargetConnection}, and is used to represent @samp{remote}
7236 and @samp{extended-remote} connections. In addition to the attributes
7237 and methods available from the @code{gdb.TargetConnection} base class,
7238 a @code{gdb.RemoteTargetConnection} has the following method:
7240 @kindex maint packet
7241 @defun RemoteTargetConnection.send_packet (packet)
7242 This method sends @var{packet} to the remote target and returns the
7243 response. The @var{packet} should either be a @code{bytes} object, or
7244 a @code{Unicode} string.
7246 If @var{packet} is a @code{Unicode} string, then the string is encoded
7247 to a @code{bytes} object using the @sc{ascii} codec. If the string
7248 can't be encoded then an @code{UnicodeError} is raised.
7250 If @var{packet} is not a @code{bytes} object, or a @code{Unicode}
7251 string, then a @code{TypeError} is raised. If @var{packet} is empty
7252 then a @code{ValueError} is raised.
7254 The response is returned as a @code{bytes} object. If it is known
7255 that the response can be represented as a string then this can be
7256 decoded from the buffer. For example, if it is known that the
7257 response is an @sc{ascii} string:
7260 remote_connection.send_packet("some_packet").decode("ascii")
7263 The prefix, suffix, and checksum (as required by the remote serial
7264 protocol) are automatically added to the outgoing packet, and removed
7265 from the incoming packet before the contents of the reply are
7268 This is equivalent to the @code{maintenance packet} command
7269 (@pxref{maint packet}).
7272 @node TUI Windows In Python
7273 @subsubsection Implementing new TUI windows
7274 @cindex Python TUI Windows
7276 New TUI (@pxref{TUI}) windows can be implemented in Python.
7278 @defun gdb.register_window_type (name, factory)
7279 Because TUI windows are created and destroyed depending on the layout
7280 the user chooses, new window types are implemented by registering a
7281 factory function with @value{GDBN}.
7283 @var{name} is the name of the new window. It's an error to try to
7284 replace one of the built-in windows, but other window types can be
7285 replaced. The @var{name} should match the regular expression
7286 @code{[a-zA-Z][-_.a-zA-Z0-9]*}, it is an error to try and create a
7287 window with an invalid name.
7289 @var{function} is a factory function that is called to create the TUI
7290 window. This is called with a single argument of type
7291 @code{gdb.TuiWindow}, described below. It should return an object
7292 that implements the TUI window protocol, also described below.
7295 As mentioned above, when a factory function is called, it is passed
7296 an object of type @code{gdb.TuiWindow}. This object has these
7297 methods and attributes:
7299 @defun TuiWindow.is_valid ()
7300 This method returns @code{True} when this window is valid. When the
7301 user changes the TUI layout, windows no longer visible in the new
7302 layout will be destroyed. At this point, the @code{gdb.TuiWindow}
7303 will no longer be valid, and methods (and attributes) other than
7304 @code{is_valid} will throw an exception.
7306 When the TUI is disabled using @code{tui disable} (@pxref{TUI
7307 Commands,,tui disable}) the window is hidden rather than destroyed,
7308 but @code{is_valid} will still return @code{False} and other methods
7309 (and attributes) will still throw an exception.
7312 @defvar TuiWindow.width
7313 This attribute holds the width of the window. It is not writable.
7316 @defvar TuiWindow.height
7317 This attribute holds the height of the window. It is not writable.
7320 @defvar TuiWindow.title
7321 This attribute holds the window's title, a string. This is normally
7322 displayed above the window. This attribute can be modified.
7325 @defun TuiWindow.erase ()
7326 Remove all the contents of the window.
7329 @defun TuiWindow.write (string @r{[}, full_window@r{]})
7330 Write @var{string} to the window. @var{string} can contain ANSI
7331 terminal escape styling sequences; @value{GDBN} will translate these
7332 as appropriate for the terminal.
7334 If the @var{full_window} parameter is @code{True}, then @var{string}
7335 contains the full contents of the window. This is similar to calling
7336 @code{erase} before @code{write}, but avoids the flickering.
7339 The factory function that you supply should return an object
7340 conforming to the TUI window protocol. These are the methods that can
7341 be called on this object, which is referred to below as the ``window
7342 object''. The methods documented below are optional; if the object
7343 does not implement one of these methods, @value{GDBN} will not attempt
7344 to call it. Additional new methods may be added to the window
7345 protocol in the future. @value{GDBN} guarantees that they will begin
7346 with a lower-case letter, so you can start implementation methods with
7347 upper-case letters or underscore to avoid any future conflicts.
7349 @defun Window.close ()
7350 When the TUI window is closed, the @code{gdb.TuiWindow} object will be
7351 put into an invalid state. At this time, @value{GDBN} will call
7352 @code{close} method on the window object.
7354 After this method is called, @value{GDBN} will discard any references
7355 it holds on this window object, and will no longer call methods on
7359 @defun Window.render ()
7360 In some situations, a TUI window can change size. For example, this
7361 can happen if the user resizes the terminal, or changes the layout.
7362 When this happens, @value{GDBN} will call the @code{render} method on
7365 If your window is intended to update in response to changes in the
7366 inferior, you will probably also want to register event listeners and
7367 send output to the @code{gdb.TuiWindow}.
7370 @defun Window.hscroll (num)
7371 This is a request to scroll the window horizontally. @var{num} is the
7372 amount by which to scroll, with negative numbers meaning to scroll
7373 right. In the TUI model, it is the viewport that moves, not the
7374 contents. A positive argument should cause the viewport to move
7375 right, and so the content should appear to move to the left.
7378 @defun Window.vscroll (num)
7379 This is a request to scroll the window vertically. @var{num} is the
7380 amount by which to scroll, with negative numbers meaning to scroll
7381 backward. In the TUI model, it is the viewport that moves, not the
7382 contents. A positive argument should cause the viewport to move down,
7383 and so the content should appear to move up.
7386 @anchor{python-window-click}
7387 @defun Window.click (x, y, button)
7388 This is called on a mouse click in this window. @var{x} and @var{y} are
7389 the mouse coordinates inside the window (0-based, from the top left
7390 corner), and @var{button} specifies which mouse button was used, whose
7391 values can be 1 (left), 2 (middle), or 3 (right).
7393 When TUI mouse events are disabled by turning off the @code{tui mouse-events}
7394 setting (@pxref{tui-mouse-events,,set tui mouse-events}), then @code{click} will
7398 @node Disassembly In Python
7399 @subsubsection Instruction Disassembly In Python
7400 @cindex python instruction disassembly
7402 @value{GDBN}'s builtin disassembler can be extended, or even replaced,
7403 using the Python API. The disassembler related features are contained
7404 within the @code{gdb.disassembler} module:
7406 @anchor{DisassembleInfo Class}
7407 @deftp {class} gdb.disassembler.DisassembleInfo
7408 Disassembly is driven by instances of this class. Each time
7409 @value{GDBN} needs to disassemble an instruction, an instance of this
7410 class is created and passed to a registered disassembler. The
7411 disassembler is then responsible for disassembling an instruction and
7414 Instances of this type are usually created within @value{GDBN},
7415 however, it is possible to create a copy of an instance of this type,
7416 see the description of @code{__init__} for more details.
7418 This class has the following properties and methods:
7420 @defvar DisassembleInfo.address
7421 A read-only integer containing the address at which @value{GDBN}
7422 wishes to disassemble a single instruction.
7425 @defvar DisassembleInfo.architecture
7426 The @code{gdb.Architecture} (@pxref{Architectures In Python}) for
7427 which @value{GDBN} is currently disassembling, this property is
7431 @defvar DisassembleInfo.progspace
7432 The @code{gdb.Progspace} (@pxref{Progspaces In Python,,Program Spaces
7433 In Python}) for which @value{GDBN} is currently disassembling, this
7434 property is read-only.
7437 @defun DisassembleInfo.is_valid ()
7438 Returns @code{True} if the @code{DisassembleInfo} object is valid,
7439 @code{False} if not. A @code{DisassembleInfo} object will become
7440 invalid once the disassembly call for which the @code{DisassembleInfo}
7441 was created, has returned. Calling other @code{DisassembleInfo}
7442 methods, or accessing @code{DisassembleInfo} properties, will raise a
7443 @code{RuntimeError} exception if it is invalid.
7446 @defun DisassembleInfo.__init__ (info)
7447 This can be used to create a new @code{DisassembleInfo} object that is
7448 a copy of @var{info}. The copy will have the same @code{address},
7449 @code{architecture}, and @code{progspace} values as @var{info}, and
7450 will become invalid at the same time as @var{info}.
7452 This method exists so that sub-classes of @code{DisassembleInfo} can
7453 be created, these sub-classes must be initialized as copies of an
7454 existing @code{DisassembleInfo} object, but sub-classes might choose
7455 to override the @code{read_memory} method, and so control what
7456 @value{GDBN} sees when reading from memory
7457 (@pxref{builtin_disassemble}).
7460 @defun DisassembleInfo.read_memory (length, offset)
7461 This method allows the disassembler to read the bytes of the
7462 instruction to be disassembled. The method reads @var{length} bytes,
7463 starting at @var{offset} from
7464 @code{DisassembleInfo.address}.
7466 It is important that the disassembler read the instruction bytes using
7467 this method, rather than reading inferior memory directly, as in some
7468 cases @value{GDBN} disassembles from an internal buffer rather than
7469 directly from inferior memory, calling this method handles this
7472 Returns a buffer object, which behaves much like an array or a string,
7473 just as @code{Inferior.read_memory} does
7474 (@pxref{gdbpy_inferior_read_memory,,Inferior.read_memory}). The
7475 length of the returned buffer will always be exactly @var{length}.
7477 If @value{GDBN} is unable to read the required memory then a
7478 @code{gdb.MemoryError} exception is raised (@pxref{Exception
7481 This method can be overridden by a sub-class in order to control what
7482 @value{GDBN} sees when reading from memory
7483 (@pxref{builtin_disassemble}). When overriding this method it is
7484 important to understand how @code{builtin_disassemble} makes use of
7487 While disassembling a single instruction there could be multiple calls
7488 to this method, and the same bytes might be read multiple times. Any
7489 single call might only read a subset of the total instruction bytes.
7491 If an implementation of @code{read_memory} is unable to read the
7492 requested memory contents, for example, if there's a request to read
7493 from an invalid memory address, then a @code{gdb.MemoryError} should
7496 Raising a @code{MemoryError} inside @code{read_memory} does not
7497 automatically mean a @code{MemoryError} will be raised by
7498 @code{builtin_disassemble}. It is possible the @value{GDBN}'s builtin
7499 disassembler is probing to see how many bytes are available. When
7500 @code{read_memory} raises the @code{MemoryError} the builtin
7501 disassembler might be able to perform a complete disassembly with the
7502 bytes it has available, in this case @code{builtin_disassemble} will
7503 not itself raise a @code{MemoryError}.
7505 Any other exception type raised in @code{read_memory} will propagate
7506 back and be re-raised by @code{builtin_disassemble}.
7509 @defun DisassembleInfo.text_part (style, string)
7510 Create a new @code{DisassemblerTextPart} representing a piece of a
7511 disassembled instruction. @var{string} should be a non-empty string,
7512 and @var{style} should be an appropriate style constant
7513 (@pxref{Disassembler Style Constants}).
7515 Disassembler parts are used when creating a @code{DisassemblerResult}
7516 in order to represent the styling within an instruction
7517 (@pxref{DisassemblerResult Class}).
7520 @defun DisassembleInfo.address_part (address)
7521 Create a new @code{DisassemblerAddressPart}. @var{address} is the
7522 value of the absolute address this part represents. A
7523 @code{DisassemblerAddressPart} is displayed as an absolute address and
7524 an associated symbol, the address and symbol are styled appropriately.
7529 @anchor{Disassembler Class}
7530 @deftp {class} gdb.disassembler.Disassembler
7531 This is a base class from which all user implemented disassemblers
7534 @defun Disassembler.__init__ (name)
7535 The constructor takes @var{name}, a string, which should be a short
7536 name for this disassembler.
7539 @defun Disassembler.__call__ (info)
7540 The @code{__call__} method must be overridden by sub-classes to
7541 perform disassembly. Calling @code{__call__} on this base class will
7542 raise a @code{NotImplementedError} exception.
7544 The @var{info} argument is an instance of @code{DisassembleInfo}, and
7545 describes the instruction that @value{GDBN} wants disassembling.
7547 If this function returns @code{None}, this indicates to @value{GDBN}
7548 that this sub-class doesn't wish to disassemble the requested
7549 instruction. @value{GDBN} will then use its builtin disassembler to
7550 perform the disassembly.
7552 Alternatively, this function can return a @code{DisassemblerResult}
7553 that represents the disassembled instruction, this type is described
7554 in more detail below.
7556 The @code{__call__} method can raise a @code{gdb.MemoryError}
7557 exception (@pxref{Exception Handling}) to indicate to @value{GDBN}
7558 that there was a problem accessing the required memory, this will then
7559 be displayed by @value{GDBN} within the disassembler output.
7561 Ideally, the only three outcomes from invoking @code{__call__} would
7562 be a return of @code{None}, a successful disassembly returned in a
7563 @code{DisassemblerResult}, or a @code{MemoryError} indicating that
7564 there was a problem reading memory.
7566 However, as an implementation of @code{__call__} could fail due to
7567 other reasons, e.g.@: some external resource required to perform
7568 disassembly is temporarily unavailable, then, if @code{__call__}
7569 raises a @code{GdbError}, the exception will be converted to a string
7570 and printed at the end of the disassembly output, the disassembly
7571 request will then stop.
7573 Any other exception type raised by the @code{__call__} method is
7574 considered an error in the user code, the exception will be printed to
7575 the error stream according to the @kbd{set python print-stack} setting
7576 (@pxref{set_python_print_stack,,@kbd{set python print-stack}}).
7580 @anchor{DisassemblerResult Class}
7581 @deftp {class} gdb.disassembler.DisassemblerResult
7582 This class represents the result of disassembling a single
7583 instruction. An instance of this class will be returned from
7584 @code{builtin_disassemble} (@pxref{builtin_disassemble}), and an
7585 instance of this class should be returned from
7586 @w{@code{Disassembler.__call__}} (@pxref{Disassembler Class}) if an
7587 instruction was successfully disassembled.
7589 It is not possible to sub-class the @code{DisassemblerResult} class.
7591 The @code{DisassemblerResult} class has the following properties and
7594 @defun DisassemblerResult.__init__ (length, string, parts)
7595 Initialize an instance of this class, @var{length} is the length of
7596 the disassembled instruction in bytes, which must be greater than
7599 Only one of @var{string} or @var{parts} should be used to initialize a
7600 new @code{DisassemblerResult}; the other one should be passed the
7601 value @code{None}. Alternatively, the arguments can be passed by
7602 name, and the unused argument can be ignored.
7604 The @var{string} argument, if not @code{None}, is a non-empty string
7605 that represents the entire disassembled instruction. Building a result
7606 object using the @var{string} argument does not allow for any styling
7607 information to be included in the result. @value{GDBN} will style the
7608 result as a single @code{DisassemblerTextPart} with @code{STYLE_TEXT}
7609 style (@pxref{Disassembler Styling Parts}).
7611 The @var{parts} argument, if not @code{None}, is a non-empty sequence
7612 of @code{DisassemblerPart} objects. Each part represents a small part
7613 of the disassembled instruction along with associated styling
7614 information. A result object built using @var{parts} can be displayed
7615 by @value{GDBN} with full styling information
7616 (@pxref{style_disassembler_enabled,,@kbd{set style disassembler
7620 @defvar DisassemblerResult.length
7621 A read-only property containing the length of the disassembled
7622 instruction in bytes, this will always be greater than zero.
7625 @defvar DisassemblerResult.string
7626 A read-only property containing a non-empty string representing the
7627 disassembled instruction. The @var{string} is a representation of the
7628 disassembled instruction without any styling information. To see how
7629 the instruction will be styled use the @var{parts} property.
7631 If this instance was initialized using separate
7632 @code{DisassemblerPart} objects, the @var{string} property will still
7633 be valid. The @var{string} value is created by concatenating the
7634 @code{DisassemblerPart.string} values of each component part
7635 (@pxref{Disassembler Styling Parts}).
7638 @defvar DisassemblerResult.parts
7639 A read-only property containing a non-empty sequence of
7640 @code{DisassemblerPart} objects. Each @code{DisassemblerPart} object
7641 contains a small part of the instruction along with information about
7642 how that part should be styled. @value{GDBN} uses this information to
7643 create styled disassembler output
7644 (@pxref{style_disassembler_enabled,,@kbd{set style disassembler
7647 If this instance was initialized using a single string rather than
7648 with a sequence of @code{DisassemblerPart} objects, the @var{parts}
7649 property will still be valid. In this case the @var{parts} property
7650 will hold a sequence containing a single @code{DisassemblerTextPart}
7651 object, the string of which will represent the entire instruction, and
7652 the style of which will be @code{STYLE_TEXT}.
7656 @anchor{Disassembler Styling Parts}
7657 @deftp {class} gdb.disassembler.DisassemblerPart
7658 This is a parent class from which the different part sub-classes
7659 inherit. Only instances of the sub-classes detailed below will be
7660 returned by the Python API.
7662 It is not possible to directly create instances of either this parent
7663 class, or any of the sub-classes listed below. Instances of the
7664 sub-classes listed below are created by calling
7665 @code{builtin_disassemble} (@pxref{builtin_disassemble}) and are
7666 returned within the @code{DisassemblerResult} object, or can be
7667 created by calling the @code{text_part} and @code{address_part}
7668 methods on the @code{DisassembleInfo} class (@pxref{DisassembleInfo
7671 The @code{DisassemblerPart} class has a single property:
7673 @defvar DisassemblerPart.string
7674 A read-only property that contains a non-empty string representing
7675 this part of the disassembled instruction. The string within this
7676 property doesn't include any styling information.
7680 @deftp {class} gdb.disassembler.DisassemblerTextPart
7681 The @code{DisassemblerTextPart} class represents a piece of the
7682 disassembled instruction and the associated style for that piece.
7683 Instances of this class can't be created directly, instead call
7684 @code{DisassembleInfo.text_part} to create a new instance of this
7685 class (@pxref{DisassembleInfo Class}).
7687 As well as the properties of its parent class, the
7688 @code{DisassemblerTextPart} has the following additional property:
7690 @defvar DisassemblerTextPart.style
7691 A read-only property that contains one of the defined style constants.
7692 @value{GDBN} will use this style when styling this part of the
7693 disassembled instruction (@pxref{Disassembler Style Constants}).
7697 @deftp {class} gdb.disassembler.DisassemblerAddressPart
7698 The @code{DisassemblerAddressPart} class represents an absolute
7699 address within a disassembled instruction. Using a
7700 @code{DisassemblerAddressPart} instead of a
7701 @code{DisassemblerTextPart} with @code{STYLE_ADDRESS} is preferred,
7702 @value{GDBN} will display the address as both an absolute address, and
7703 will look up a suitable symbol to display next to the address. Using
7704 @code{DisassemblerAddressPart} also ensures that user settings such as
7705 @code{set print max-symbolic-offset} are respected.
7707 Here is an example of an x86-64 instruction:
7714 In this instruction the @code{0x401136 <foo>} was generated from a
7715 single @code{DisassemblerAddressPart}. The @code{0x401136} will be
7716 styled with @code{STYLE_ADDRESS}, and @code{foo} will be styled with
7717 @code{STYLE_SYMBOL}. The @code{<} and @code{>} will be styled as
7720 If the inclusion of the symbol name is not required then a
7721 @code{DisassemblerTextPart} with style @code{STYLE_ADDRESS} can be
7724 Instances of this class can't be created directly, instead call
7725 @code{DisassembleInfo.address_part} to create a new instance of this
7726 class (@pxref{DisassembleInfo Class}).
7728 As well as the properties of its parent class, the
7729 @code{DisassemblerAddressPart} has the following additional property:
7731 @defvar DisassemblerAddressPart.address
7732 A read-only property that contains the @var{address} passed to this
7733 object's @code{__init__} method.
7737 @anchor{Disassembler Style Constants}
7739 The following table lists all of the disassembler styles that are
7740 available. @value{GDBN} maps these style constants onto its style
7741 settings (@pxref{Output Styling}). In some cases, several style
7742 constants produce the same style settings, and thus will produce the
7743 same visual effect on the screen. This could change in future
7744 releases of @value{GDBN}, so care should be taken to select the
7745 correct style constant to ensure correct output styling in future
7746 releases of @value{GDBN}.
7750 @item gdb.disassembler.STYLE_TEXT
7751 This is the default style used by @value{GDBN} when styling
7752 disassembler output. This style should be used for any parts of the
7753 instruction that don't fit any of the other styles listed below.
7754 @value{GDBN} styles text with this style using its default style.
7756 @vindex STYLE_MNEMONIC
7757 @item gdb.disassembler.STYLE_MNEMONIC
7758 This style is used for styling the primary instruction mnemonic, which
7759 usually appears at, or near, the start of the disassembled instruction
7762 @value{GDBN} styles text with this style using the @code{disassembler
7763 mnemonic} style setting.
7765 @vindex STYLE_SUB_MNEMONIC
7766 @item gdb.disassembler.STYLE_SUB_MNEMONIC
7767 This style is used for styling any sub-mnemonics within a disassembled
7768 instruction. A sub-mnemonic is any text within the instruction that
7769 controls the function of the instruction, but which is disjoint from
7770 the primary mnemonic (which will have styled @code{STYLE_MNEMONIC}).
7772 As an example, consider this AArch64 instruction:
7775 add w16, w7, w1, lsl #1
7779 The @code{add} is the primary instruction mnemonic, and would be given
7780 style @code{STYLE_MNEMONIC}, while @code{lsl} is the sub-mnemonic, and
7781 would be given the style @code{STYLE_SUB_MNEMONIC}.
7783 @value{GDBN} styles text with this style using the @code{disassembler
7784 mnemonic} style setting.
7786 @vindex STYLE_ASSEMBLER_DIRECTIVE
7787 @item gdb.disassembler.STYLE_ASSEMBLER_DIRECTIVE
7788 Sometimes a series of bytes doesn't decode to a valid instruction. In
7789 this case the disassembler may choose to represent the result of
7790 disassembling using an assembler directive, for example:
7797 In this case, the @code{.word} would be give the
7798 @code{STYLE_ASSEMBLER_DIRECTIVE} style. An assembler directive is
7799 similar to a mnemonic in many ways but is something that is not part
7800 of the architecture's instruction set.
7802 @value{GDBN} styles text with this style using the @code{disassembler
7803 mnemonic} style setting.
7805 @vindex STYLE_REGISTER
7806 @item gdb.disassembler.STYLE_REGISTER
7807 This style is used for styling any text that represents a register
7808 name, or register number, within a disassembled instruction.
7810 @value{GDBN} styles text with this style using the @code{disassembler
7811 register} style setting.
7813 @vindex STYLE_ADDRESS
7814 @item gdb.disassembler.STYLE_ADDRESS
7815 This style is used for styling numerical values that represent
7816 absolute addresses within the disassembled instruction.
7818 When creating a @code{DisassemblerTextPart} with this style, you
7819 should consider if a @code{DisassemblerAddressPart} would be more
7820 appropriate. See @ref{Disassembler Styling Parts} for a description
7821 of what each part offers.
7823 @value{GDBN} styles text with this style using the @code{disassembler
7824 address} style setting.
7826 @vindex STYLE_ADDRESS_OFFSET
7827 @item gdb.disassembler.STYLE_ADDRESS_OFFSET
7828 This style is used for styling numerical values that represent offsets
7829 to addresses within the disassembled instruction. A value is
7830 considered an address offset when the instruction itself is going to
7831 access memory, and the value is being used to offset which address is
7834 For example, an architecture might have an instruction that loads from
7835 memory using an address within a register. If that instruction also
7836 allowed for an immediate offset to be encoded into the instruction,
7837 this would be an address offset. Similarly, a branch instruction
7838 might jump to an address in a register plus an address offset that is
7839 encoded into the instruction.
7841 @value{GDBN} styles text with this style using the @code{disassembler
7842 immediate} style setting.
7844 @vindex STYLE_IMMEDIATE
7845 @item gdb.disassembler.STYLE_IMMEDIATE
7846 Use @code{STYLE_IMMEDIATE} for any numerical values within a
7847 disassembled instruction when those values are not addresses, address
7848 offsets, or register numbers (The styles @code{STYLE_ADDRESS},
7849 @code{STYLE_ADDRESS_OFFSET}, or @code{STYLE_REGISTER} can be used in
7852 @value{GDBN} styles text with this style using the @code{disassembler
7853 immediate} style setting.
7855 @vindex STYLE_SYMBOL
7856 @item gdb.disassembler.STYLE_SYMBOL
7857 This style is used for styling the textual name of a symbol that is
7858 included within a disassembled instruction. A symbol name is often
7859 included next to an absolute address within a disassembled instruction
7860 to make it easier for the user to understand what the address is
7861 referring too. For example:
7868 Here @code{foo} is the name of a symbol, and should be given the
7869 @code{STYLE_SYMBOL} style.
7871 Adding symbols next to absolute addresses like this is handled
7872 automatically by the @code{DisassemblerAddressPart} class
7873 (@pxref{Disassembler Styling Parts}).
7875 @value{GDBN} styles text with this style using the @code{disassembler
7876 symbol} style setting.
7878 @vindex STYLE_COMMENT_START
7879 @item gdb.disassembler.STYLE_COMMENT_START
7880 This style is used to start a line comment in the disassembly output.
7881 Unlike other styles, which only apply to the single
7882 @code{DisassemblerTextPiece} to which they are applied, the comment
7883 style is sticky, and overrides the style of any further pieces within
7886 This means that, after a @code{STYLE_COMMENT_START} piece has been
7887 seen, @value{GDBN} will apply the comment style until the end of the
7888 line, ignoring the specific style within a piece.
7890 @value{GDBN} styles text with this style using the @code{disassembler
7891 comment} style setting.
7894 The following functions are also contained in the
7895 @code{gdb.disassembler} module:
7897 @defun register_disassembler (disassembler, architecture)
7898 The @var{disassembler} must be a sub-class of
7899 @code{gdb.disassembler.Disassembler} or @code{None}.
7901 The optional @var{architecture} is either a string, or the value
7902 @code{None}. If it is a string, then it should be the name of an
7903 architecture known to @value{GDBN}, as returned either from
7904 @code{gdb.Architecture.name}
7905 (@pxref{gdbpy_architecture_name,,gdb.Architecture.name}), or from
7906 @code{gdb.architecture_names}
7907 (@pxref{gdb_architecture_names,,gdb.architecture_names}).
7909 The @var{disassembler} will be installed for the architecture named by
7910 @var{architecture}, or if @var{architecture} is @code{None}, then
7911 @var{disassembler} will be installed as a global disassembler for use
7912 by all architectures.
7914 @cindex disassembler in Python, global vs.@: specific
7915 @cindex search order for disassembler in Python
7916 @cindex look up of disassembler in Python
7917 @value{GDBN} only records a single disassembler for each architecture,
7918 and a single global disassembler. Calling
7919 @code{register_disassembler} for an architecture, or for the global
7920 disassembler, will replace any existing disassembler registered for
7921 that @var{architecture} value. The previous disassembler is returned.
7923 If @var{disassembler} is @code{None} then any disassembler currently
7924 registered for @var{architecture} is deregistered and returned.
7926 When @value{GDBN} is looking for a disassembler to use, @value{GDBN}
7927 first looks for an architecture specific disassembler. If none has
7928 been registered then @value{GDBN} looks for a global disassembler (one
7929 registered with @var{architecture} set to @code{None}). Only one
7930 disassembler is called to perform disassembly, so, if there is both an
7931 architecture specific disassembler, and a global disassembler
7932 registered, it is the architecture specific disassembler that will be
7935 @value{GDBN} tracks the architecture specific, and global
7936 disassemblers separately, so it doesn't matter in which order
7937 disassemblers are created or registered; an architecture specific
7938 disassembler, if present, will always be used in preference to a
7939 global disassembler.
7941 You can use the @kbd{maint info python-disassemblers} command
7942 (@pxref{maint info python-disassemblers}) to see which disassemblers
7943 have been registered.
7946 @anchor{builtin_disassemble}
7947 @defun builtin_disassemble (info)
7948 This function calls back into @value{GDBN}'s builtin disassembler to
7949 disassemble the instruction identified by @var{info}, an instance, or
7950 sub-class, of @code{DisassembleInfo}.
7952 When the builtin disassembler needs to read memory the
7953 @code{read_memory} method on @var{info} will be called. By
7954 sub-classing @code{DisassembleInfo} and overriding the
7955 @code{read_memory} method, it is possible to intercept calls to
7956 @code{read_memory} from the builtin disassembler, and to modify the
7959 It is important to understand that, even when
7960 @code{DisassembleInfo.read_memory} raises a @code{gdb.MemoryError}, it
7961 is the internal disassembler itself that reports the memory error to
7962 @value{GDBN}. The reason for this is that the disassembler might
7963 probe memory to see if a byte is readable or not; if the byte can't be
7964 read then the disassembler may choose not to report an error, but
7965 instead to disassemble the bytes that it does have available.
7967 If the builtin disassembler is successful then an instance of
7968 @code{DisassemblerResult} is returned from @code{builtin_disassemble},
7969 alternatively, if something goes wrong, an exception will be raised.
7971 A @code{MemoryError} will be raised if @code{builtin_disassemble} is
7972 unable to read some memory that is required in order to perform
7973 disassembly correctly.
7975 Any exception that is not a @code{MemoryError}, that is raised in a
7976 call to @code{read_memory}, will pass through
7977 @code{builtin_disassemble}, and be visible to the caller.
7979 Finally, there are a few cases where @value{GDBN}'s builtin
7980 disassembler can fail for reasons that are not covered by
7981 @code{MemoryError}. In these cases, a @code{GdbError} will be raised.
7982 The contents of the exception will be a string describing the problem
7983 the disassembler encountered.
7986 Here is an example that registers a global disassembler. The new
7987 disassembler invokes the builtin disassembler, and then adds a
7988 comment, @code{## Comment}, to each line of disassembly output:
7991 class ExampleDisassembler(gdb.disassembler.Disassembler):
7993 super().__init__("ExampleDisassembler")
7995 def __call__(self, info):
7996 result = gdb.disassembler.builtin_disassemble(info)
7997 length = result.length
7998 text = result.string + "\t## Comment"
7999 return gdb.disassembler.DisassemblerResult(length, text)
8001 gdb.disassembler.register_disassembler(ExampleDisassembler())
8004 The following example creates a sub-class of @code{DisassembleInfo} in
8005 order to intercept the @code{read_memory} calls, within
8006 @code{read_memory} any bytes read from memory have the two 4-bit
8007 nibbles swapped around. This isn't a very useful adjustment, but
8008 serves as an example.
8011 class MyInfo(gdb.disassembler.DisassembleInfo):
8012 def __init__(self, info):
8013 super().__init__(info)
8015 def read_memory(self, length, offset):
8016 buffer = super().read_memory(length, offset)
8017 result = bytearray()
8019 v = int.from_bytes(b, 'little')
8020 v = (v << 4) & 0xf0 | (v >> 4)
8022 return memoryview(result)
8024 class NibbleSwapDisassembler(gdb.disassembler.Disassembler):
8026 super().__init__("NibbleSwapDisassembler")
8028 def __call__(self, info):
8030 return gdb.disassembler.builtin_disassemble(info)
8032 gdb.disassembler.register_disassembler(NibbleSwapDisassembler())
8035 @node Missing Debug Info In Python
8036 @subsubsection Missing Debug Info In Python
8037 @cindex python, handle missing debug information
8039 When @value{GDBN} encounters a new objfile (@pxref{Objfiles In
8040 Python}), e.g.@: the primary executable, or any shared libraries used
8041 by the inferior, @value{GDBN} will attempt to load the corresponding
8042 debug information for that objfile. The debug information might be
8043 found within the objfile itself, or within a separate objfile which
8044 @value{GDBN} will automatically locate and load.
8046 Sometimes though, @value{GDBN} might not find any debug information
8047 for an objfile, in this case the debugging experience will be
8050 If @value{GDBN} fails to locate any debug information for a particular
8051 objfile, there is an opportunity for a Python extension to step in. A
8052 Python extension can potentially locate the missing debug information
8053 using some platform- or project-specific steps, and inform
8054 @value{GDBN} of its location. Or a Python extension might provide
8055 some platform- or project-specific advice to the user about how to
8056 obtain the missing debug information.
8058 A missing debug information Python extension consists of a handler
8059 object which has the @code{name} and @code{enabled} attributes, and
8060 implements the @code{__call__} method. When @value{GDBN} encounters
8061 an objfile for which it is unable to find any debug information, it
8062 invokes the @code{__call__} method. Full details of how handlers are
8063 written can be found below.
8065 @subheading The @code{gdb.missing_debug} Module
8067 @value{GDBN} comes with a @code{gdb.missing_debug} module which
8068 contains the following class and global function:
8070 @deftp{class} gdb.missing_debug.MissingDebugHandler
8072 @code{MissingDebugHandler} is a base class from which user-created
8073 handlers can derive, though it is not required that handlers derive
8074 from this class, so long as any user created handler has the
8075 @code{name} and @code{enabled} attributes, and implements the
8076 @code{__call__} method.
8078 @defun MissingDebugHandler.__init__ (name)
8079 The @var{name} is a string used to reference this missing debug
8080 handler within some @value{GDBN} commands. Valid names consist of the
8081 characters @code{[-_a-zA-Z0-9]}, creating a handler with an invalid
8082 name raises a @code{ValueError} exception.
8085 @defun MissingDebugHandler.__call__ (objfile)
8086 Sub-classes must override the @code{__call__} method. The
8087 @var{objfile} argument will be a @code{gdb.Objfile}, this is the
8088 objfile for which @value{GDBN} was unable to find any debug
8091 The return value from the @code{__call__} method indicates what
8092 @value{GDBN} should do next. The possible return values are:
8097 This indicates that this handler could not help with @var{objfile},
8098 @value{GDBN} should call any other registered handlers.
8102 This indicates that this handler has installed the debug information
8103 into a location where @value{GDBN} would normally expect to find it
8104 when looking for separate debug information files (@pxref{Separate
8105 Debug Files}). @value{GDBN} will repeat the normal lookup process,
8106 which should now find the separate debug file.
8108 If @value{GDBN} still doesn't find the separate debug information file
8109 after this second attempt, then the Python missing debug information
8110 handlers are not invoked a second time, this prevents a badly behaved
8111 handler causing @value{GDBN} to get stuck in a loop. @value{GDBN}
8112 will continue without any debug information for @var{objfile}.
8116 This indicates that this handler has done everything that it intends
8117 to do with @var{objfile}, but no separate debug information can be
8118 found. @value{GDBN} will not call any other registered handlers for
8119 @var{objfile}. @value{GDBN} will continue without debugging
8120 information for @var{objfile}.
8124 The returned string should contain a filename. @value{GDBN} will not
8125 call any further registered handlers, and will instead load the debug
8126 information from the file identified by the returned filename.
8129 Invoking the @code{__call__} method from this base class will raise a
8130 @code{NotImplementedError} exception.
8133 @defvar MissingDebugHandler.name
8134 A read-only attribute which is a string, the name of this handler
8135 passed to the @code{__init__} method.
8138 @defvar MissingDebugHandler.enabled
8139 A modifiable attribute containing a boolean; when @code{True}, the
8140 handler is enabled, and will be used by @value{GDBN}. When
8141 @code{False}, the handler has been disabled, and will not be used.
8145 @defun gdb.missing_debug.register_handler (locus, handler, replace=@code{False})
8146 Register a new missing debug handler with @value{GDBN}.
8148 @var{handler} is an instance of a sub-class of
8149 @code{MissingDebugHandler}, or at least an instance of an object that
8150 has the same attributes and methods as @code{MissingDebugHandler}.
8152 @var{locus} specifies to which handler list to prepend @var{handler}.
8153 It can be either a @code{gdb.Progspace} (@pxref{Progspaces In Python})
8154 or @code{None}, in which case the handler is registered globally. The
8155 newly registered @var{handler} will be called before any other handler
8156 from the same locus. Two handlers in the same locus cannot have the
8157 same name, an attempt to add a handler with an already existing name
8158 raises an exception unless @var{replace} is @code{True}, in which case
8159 the old handler is deleted and the new handler is prepended to the
8160 selected handler list.
8162 @value{GDBN} first calls the handlers for the current program space,
8163 and then the globally registered handlers. As soon as a handler
8164 returns a value other than @code{None}, no further handlers are called
8168 @node Python Auto-loading
8169 @subsection Python Auto-loading
8170 @cindex Python auto-loading
8172 When a new object file is read (for example, due to the @code{file}
8173 command, or because the inferior has loaded a shared library),
8174 @value{GDBN} will look for Python support scripts in several ways:
8175 @file{@var{objfile}-gdb.py} and @code{.debug_gdb_scripts} section.
8176 @xref{Auto-loading extensions}.
8178 The auto-loading feature is useful for supplying application-specific
8179 debugging commands and scripts.
8181 Auto-loading can be enabled or disabled,
8182 and the list of auto-loaded scripts can be printed.
8185 @anchor{set auto-load python-scripts}
8186 @kindex set auto-load python-scripts
8187 @item set auto-load python-scripts [on|off]
8188 Enable or disable the auto-loading of Python scripts.
8190 @anchor{show auto-load python-scripts}
8191 @kindex show auto-load python-scripts
8192 @item show auto-load python-scripts
8193 Show whether auto-loading of Python scripts is enabled or disabled.
8195 @anchor{info auto-load python-scripts}
8196 @kindex info auto-load python-scripts
8197 @cindex print list of auto-loaded Python scripts
8198 @item info auto-load python-scripts [@var{regexp}]
8199 Print the list of all Python scripts that @value{GDBN} auto-loaded.
8201 Also printed is the list of Python scripts that were mentioned in
8202 the @code{.debug_gdb_scripts} section and were either not found
8203 (@pxref{dotdebug_gdb_scripts section}) or were not auto-loaded due to
8204 @code{auto-load safe-path} rejection (@pxref{Auto-loading}).
8205 This is useful because their names are not printed when @value{GDBN}
8206 tries to load them and fails. There may be many of them, and printing
8207 an error message for each one is problematic.
8209 If @var{regexp} is supplied only Python scripts with matching names are printed.
8214 (gdb) info auto-load python-scripts
8216 Yes py-section-script.py
8217 full name: /tmp/py-section-script.py
8218 No my-foo-pretty-printers.py
8222 When reading an auto-loaded file or script, @value{GDBN} sets the
8223 @dfn{current objfile}. This is available via the @code{gdb.current_objfile}
8224 function (@pxref{Objfiles In Python}). This can be useful for
8225 registering objfile-specific pretty-printers and frame-filters.
8227 @node Python modules
8228 @subsection Python modules
8229 @cindex python modules
8231 @value{GDBN} comes with several modules to assist writing Python code.
8234 * gdb.printing:: Building and registering pretty-printers.
8235 * gdb.types:: Utilities for working with types.
8236 * gdb.prompt:: Utilities for prompt value substitution.
8237 * gdb.ptwrite:: Utilities for PTWRITE filter registration.
8241 @subsubsection gdb.printing
8242 @cindex gdb.printing
8244 This module provides a collection of utilities for working with
8248 @item PrettyPrinter (@var{name}, @var{subprinters}=None)
8249 This class specifies the API that makes @samp{info pretty-printer},
8250 @samp{enable pretty-printer} and @samp{disable pretty-printer} work.
8251 Pretty-printers should generally inherit from this class.
8253 @item SubPrettyPrinter (@var{name})
8254 For printers that handle multiple types, this class specifies the
8255 corresponding API for the subprinters.
8257 @item RegexpCollectionPrettyPrinter (@var{name})
8258 Utility class for handling multiple printers, all recognized via
8259 regular expressions.
8260 @xref{Writing a Pretty-Printer}, for an example.
8262 @item FlagEnumerationPrinter (@var{name})
8263 A pretty-printer which handles printing of @code{enum} values. Unlike
8264 @value{GDBN}'s built-in @code{enum} printing, this printer attempts to
8265 work properly when there is some overlap between the enumeration
8266 constants. The argument @var{name} is the name of the printer and
8267 also the name of the @code{enum} type to look up.
8269 @item register_pretty_printer (@var{obj}, @var{printer}, @var{replace}=False)
8270 Register @var{printer} with the pretty-printer list of @var{obj}.
8271 If @var{replace} is @code{True} then any existing copy of the printer
8272 is replaced. Otherwise a @code{RuntimeError} exception is raised
8273 if a printer with the same name already exists.
8277 @subsubsection gdb.types
8280 This module provides a collection of utilities for working with
8281 @code{gdb.Type} objects.
8284 @item get_basic_type (@var{type})
8285 Return @var{type} with const and volatile qualifiers stripped,
8286 and with typedefs and C@t{++} references converted to the underlying type.
8291 typedef const int const_int;
8293 const_int& foo_ref (foo);
8294 int main () @{ return 0; @}
8301 (gdb) python import gdb.types
8302 (gdb) python foo_ref = gdb.parse_and_eval("foo_ref")
8303 (gdb) python print gdb.types.get_basic_type(foo_ref.type)
8307 @item has_field (@var{type}, @var{field})
8308 Return @code{True} if @var{type}, assumed to be a type with fields
8309 (e.g., a structure or union), has field @var{field}.
8311 @item make_enum_dict (@var{enum_type})
8312 Return a Python @code{dictionary} type produced from @var{enum_type}.
8314 @item deep_items (@var{type})
8315 Returns a Python iterator similar to the standard
8316 @code{gdb.Type.iteritems} method, except that the iterator returned
8317 by @code{deep_items} will recursively traverse anonymous struct or
8318 union fields. For example:
8332 Then in @value{GDBN}:
8334 (@value{GDBP}) python import gdb.types
8335 (@value{GDBP}) python struct_a = gdb.lookup_type("struct A")
8336 (@value{GDBP}) python print struct_a.keys ()
8338 (@value{GDBP}) python print [k for k,v in gdb.types.deep_items(struct_a)]
8339 @{['a', 'b0', 'b1']@}
8342 @item get_type_recognizers ()
8343 Return a list of the enabled type recognizers for the current context.
8344 This is called by @value{GDBN} during the type-printing process
8345 (@pxref{Type Printing API}).
8347 @item apply_type_recognizers (recognizers, type_obj)
8348 Apply the type recognizers, @var{recognizers}, to the type object
8349 @var{type_obj}. If any recognizer returns a string, return that
8350 string. Otherwise, return @code{None}. This is called by
8351 @value{GDBN} during the type-printing process (@pxref{Type Printing
8354 @item register_type_printer (locus, printer)
8355 This is a convenience function to register a type printer
8356 @var{printer}. The printer must implement the type printer protocol.
8357 The @var{locus} argument is either a @code{gdb.Objfile}, in which case
8358 the printer is registered with that objfile; a @code{gdb.Progspace},
8359 in which case the printer is registered with that progspace; or
8360 @code{None}, in which case the printer is registered globally.
8363 This is a base class that implements the type printer protocol. Type
8364 printers are encouraged, but not required, to derive from this class.
8365 It defines a constructor:
8367 @defmethod TypePrinter __init__ (self, name)
8368 Initialize the type printer with the given name. The new printer
8369 starts in the enabled state.
8375 @subsubsection gdb.prompt
8378 This module provides a method for prompt value-substitution.
8381 @item substitute_prompt (@var{string})
8382 Return @var{string} with escape sequences substituted by values. Some
8383 escape sequences take arguments. You can specify arguments inside
8384 ``@{@}'' immediately following the escape sequence.
8386 The escape sequences you can pass to this function are:
8390 Substitute a backslash.
8392 Substitute an ESC character.
8394 Substitute the selected frame; an argument names a frame parameter.
8396 Substitute a newline.
8398 Substitute a parameter's value; the argument names the parameter.
8400 Substitute a carriage return.
8402 Substitute the selected thread; an argument names a thread parameter.
8404 Substitute the version of GDB.
8406 Substitute the current working directory.
8408 Begin a sequence of non-printing characters. These sequences are
8409 typically used with the ESC character, and are not counted in the string
8410 length. Example: ``\[\e[0;34m\](gdb)\[\e[0m\]'' will return a
8411 blue-colored ``(gdb)'' prompt where the length is five.
8413 End a sequence of non-printing characters.
8419 substitute_prompt ("frame: \f, args: \p@{print frame-arguments@}")
8422 @exdent will return the string:
8425 "frame: main, args: scalars"
8430 @subsubsection gdb.ptwrite
8433 This module provides additional functionality for recording programs that
8434 make use of the @code{PTWRITE} instruction. @code{PTWRITE} is a x86
8435 instruction that allows to write values into the Intel Processor Trace
8436 (@pxref{Process Record and Replay}).
8437 The @value{NGCC} intrinsics for it are:
8439 void _ptwrite32 (unsigned int a)
8440 void _ptwrite64 (unsigned __int64 a)
8443 If an inferior uses the instruction, @value{GDBN} by default inserts the
8444 raw payload value as auxiliary information into the execution history.
8445 Auxiliary information is by default printed during
8446 @code{record instruction-history}, @code{record function-call-history},
8447 and all stepping commands, and is accessible in Python as a
8448 @code{RecordAuxiliary} object (@pxref{Recordings In Python}).
8450 @exdent Sample program:
8453 #include <immintrin.h>
8456 ptwrite64 (unsigned long long value)
8467 return 0; /* break here. */
8473 @exdent @value{GDBN} output after recording the sample program in pt format:
8476 (gdb) record instruction-history 12,14
8477 12 0x0040074c <ptwrite64+16>: ptwrite %rbx
8479 14 0x00400751 <ptwrite64+21>: mov -0x8(%rbp),%rbx
8480 (gdb) record function-call-history
8488 The @code{gdb.ptwrite} module allows customizing the default output of
8489 @code{PTWRITE} auxiliary information. A custom Python function can be
8490 registered as the @code{PTWRITE} filter function. This function will be
8491 called with the @code{PTWRITE} payload and PC as arguments during trace
8492 decoding. The function can return a string, which will be printed by
8493 @value{GDBN} during the aforementioned commands, or @code{None}, resulting
8494 in no output. To register such a filter function, the user needs to
8495 provide a filter factory function, which returns a new filter function
8496 object to be called by @value{GDBN}.
8498 @findex gdb.ptwrite.register_filter_factory
8499 @defun register_filter_factory (filter_factory)
8500 Used to register the @code{PTWRITE} filter factory. This filter factory can
8501 be any callable object that accepts one argument, the current thread as
8502 a @code{gdb.InferiorThread}.
8503 It can return None or a callable. This callable is the @code{PTWRITE} filter
8504 function for the specified thread. If @code{None} is returned by the factory
8505 function, the default auxiliary information will be printed.
8508 @findex gdb.ptwrite.get_filter
8509 @defun get_filter ()
8510 Return the currently active @code{PTWRITE} filter function.
8517 (gdb) python-interactive
8518 >>> class my_filter():
8519 ... def __init__(self):
8521 ... def __call__(self, payload, ip):
8523 ... return f"counter: @{self.var@}, ip: @{ip:#x@}"
8525 >>> def my_filter_factory(thread):
8526 ... if thread.global_num == 1:
8527 ... return my_filter()
8531 >>> import gdb.ptwrite
8532 >>> gdb.ptwrite.register_filter_factory(my_filter_factory)
8537 (gdb) record function-call-history 59,64
8538 59 pthread_create@@GLIBC_2.2.5
8541 62 ptwrite64(unsigned long)
8542 [counter: 1, ip: 0x401156]
8544 64 ptwrite32(unsigned int)
8545 [counter: 2, ip: 0x40116c]
8550 * 1 Thread 0x7ffff7fd8740 (LWP 25796) "ptw_threads" task ()
8551 at bin/ptwrite/ptw_threads.c:45
8552 2 Thread 0x7ffff6eb8700 (LWP 25797) "ptw_threads" task ()
8553 at bin/ptwrite/ptw_threads.c:45
8558 [Switching to thread 2 (Thread 0x7ffff6eb8700 (LWP 25797))]
8559 #0 task (arg=0x0) at ptwrite_threads.c:45
8564 (gdb) record function-call-history 10,14
8567 12 ptwrite64(unsigned long)
8570 14 ptwrite32(unsigned int)
8575 This @value{GDBN} feature is dependent on hardware and operating system
8576 support and requires the Intel Processor Trace decoder library in version