Home | History | Annotate | Line # | Download | only in doc
      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.
      8 @c 
      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.''
     12 
     13 @node Python
     14 @section Extending @value{GDBN} using Python
     15 @cindex python scripting
     16 @cindex scripting with python
     17 
     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}.
     21 
     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.
     29 
     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.
     35 
     36 @menu
     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}.
     41 @end menu
     42 
     43 @node Python Commands
     44 @subsection Python Commands
     45 @cindex python commands
     46 @cindex commands to access python
     47 
     48 @value{GDBN} provides two commands for accessing the Python interpreter,
     49 and one related setting:
     50 
     51 @table @code
     52 @kindex python-interactive
     53 @kindex pi
     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).
     59 
     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:
     63 
     64 @smallexample
     65 (@value{GDBP}) python-interactive 2 + 3
     66 5
     67 @end smallexample
     68 
     69 @kindex python
     70 @kindex py
     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.
     74 
     75 If given an argument, the @code{python} command will evaluate the
     76 argument as a Python command.  For example:
     77 
     78 @smallexample
     79 (@value{GDBP}) python print 23
     80 23
     81 @end smallexample
     82 
     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:
     88 
     89 @smallexample
     90 (@value{GDBP}) python
     91 >print 23
     92 >end
     93 23
     94 @end smallexample
     95 
     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.
    105 
    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.}.
    114 
    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.
    120 
    121 This option is equivalent to passing @option{-E} to the real
    122 @command{python} executable.
    123 
    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
    129 @file{.pyc} files.
    130 
    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.
    136 
    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.
    145 
    146 This option is equivalent to passing @option{-B} to the real
    147 @command{python} executable.
    148 @end table
    149 
    150 It is also possible to execute a Python script from the @value{GDBN}
    151 interpreter:
    152 
    153 @table @code
    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}.
    158 @end table
    159 
    160 The following commands are intended to help debug @value{GDBN} itself:
    161 
    162 @table @code
    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.
    169 
    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.
    176 @end table
    177 
    178 @node Python API
    179 @subsection Python API
    180 @cindex python api
    181 @cindex programming in python
    182 
    183 You can get quick online help for @value{GDBN}'s Python API by issuing
    184 the command @w{@kbd{python help (gdb)}}.
    185 
    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)}}.
    190 
    191 @menu
    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
    226                                 using Python.
    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.
    234 * Missing Objfiles In Python::  Handle objfiles from Python.
    235 @end menu
    236 
    237 @node Basic Python
    238 @subsubsection Basic Python
    239 
    240 @cindex python stdout
    241 @cindex python pagination
    242 At startup, @value{GDBN} overrides Python's @code{sys.stdout} and
    243 @code{sys.stderr} to print using @value{GDBN}'s output-paging streams.
    244 A Python program which outputs to one of these streams may have its
    245 output interrupted by the user (@pxref{Screen Size}).  In this
    246 situation, a Python @code{KeyboardInterrupt} exception is thrown.
    247 
    248 Some care must be taken when writing Python code to run in
    249 @value{GDBN}.  Two things worth noting in particular:
    250 
    251 @itemize @bullet
    252 @item
    253 @value{GDBN} installs handlers for @code{SIGCHLD} and @code{SIGINT}.
    254 Python code must not override these, or even change the options using
    255 @code{sigaction}.  If your program changes the handling of these
    256 signals, @value{GDBN} will most likely stop working correctly.  Note
    257 that it is unfortunately common for GUI toolkits to install a
    258 @code{SIGCHLD} handler.  When creating a new Python thread, you can
    259 use @code{gdb.block_signals} or @code{gdb.Thread} to handle this
    260 correctly; see @ref{Threading in GDB}.
    261 
    262 @item
    263 @value{GDBN} takes care to mark its internal file descriptors as
    264 close-on-exec.  However, this cannot be done in a thread-safe way on
    265 all platforms.  Your Python programs should be aware of this and
    266 should both create new file descriptors with the close-on-exec flag
    267 set and arrange to close unneeded file descriptors before starting a
    268 child process.
    269 @end itemize
    270 
    271 @cindex python functions
    272 @cindex python module
    273 @cindex gdb module
    274 @value{GDBN} introduces a new Python module, named @code{gdb}.  All
    275 methods and classes added by @value{GDBN} are placed in this module.
    276 @value{GDBN} automatically @code{import}s the @code{gdb} module for
    277 use in all scripts evaluated by the @code{python} command.
    278 
    279 Some types of the @code{gdb} module come with a textual representation
    280 (accessible through the @code{repr} or @code{str} functions).  These are
    281 offered for debugging purposes only, expect them to change over time.
    282 
    283 @defvar gdb.PYTHONDIR
    284 A string containing the python directory (@pxref{Python}).
    285 @end defvar
    286 
    287 @defun gdb.execute (command @r{[}, from_tty @r{[}, to_string@r{]]})
    288 Evaluate @var{command}, a string, as a @value{GDBN} CLI command.
    289 If a GDB exception happens while @var{command} runs, it is
    290 translated as described in @ref{Exception Handling,,Exception Handling}.
    291 
    292 The @var{from_tty} flag specifies whether @value{GDBN} ought to consider this
    293 command as having originated from the user invoking it interactively.
    294 It must be a boolean value.  If omitted, it defaults to @code{False}.
    295 
    296 By default, any output produced by @var{command} is sent to
    297 @value{GDBN}'s standard output (and to the log output if logging is
    298 turned on).  If the @var{to_string} parameter is
    299 @code{True}, then output will be collected by @code{gdb.execute} and
    300 returned as a string.  The default is @code{False}, in which case the
    301 return value is @code{None}.  If @var{to_string} is @code{True}, the
    302 @value{GDBN} virtual terminal will be temporarily set to unlimited width
    303 and height, and its pagination will be disabled; @pxref{Screen Size}.
    304 @end defun
    305 
    306 @defun gdb.breakpoints ()
    307 Return a sequence holding all of @value{GDBN}'s breakpoints.
    308 @xref{Breakpoints In Python}, for more information.  In @value{GDBN}
    309 version 7.11 and earlier, this function returned @code{None} if there
    310 were no breakpoints.  This peculiarity was subsequently fixed, and now
    311 @code{gdb.breakpoints} returns an empty sequence in this case.
    312 @end defun
    313 
    314 @defun gdb.rbreak (regex @r{[}, minsyms @r{[}, throttle, @r{[}, symtabs @r{]]]})
    315 Return a Python list holding a collection of newly set
    316 @code{gdb.Breakpoint} objects matching function names defined by the
    317 @var{regex} pattern.  If the @var{minsyms} keyword is @code{True}, all
    318 system functions (those not explicitly defined in the inferior) will
    319 also be included in the match.  The @var{throttle} keyword takes an
    320 integer that defines the maximum number of pattern matches for
    321 functions matched by the @var{regex} pattern.  If the number of
    322 matches exceeds the integer value of @var{throttle}, a
    323 @code{RuntimeError} will be raised and no breakpoints will be created.
    324 If @var{throttle} is not defined then there is no imposed limit on the
    325 maximum number of matches and breakpoints to be created.  The
    326 @var{symtabs} keyword takes a Python iterable that yields a collection
    327 of @code{gdb.Symtab} objects and will restrict the search to those
    328 functions only contained within the @code{gdb.Symtab} objects.
    329 @end defun
    330 
    331 @defun gdb.parameter (parameter)
    332 Return the value of a @value{GDBN} @var{parameter} given by its name,
    333 a string; the parameter name string may contain spaces if the parameter has a
    334 multi-part name.  For example, @samp{print object} is a valid
    335 parameter name.
    336 
    337 If the named parameter does not exist, this function throws a
    338 @code{gdb.error} (@pxref{Exception Handling}).  Otherwise, the
    339 parameter's value is converted to a Python value of the appropriate
    340 type, and returned.
    341 @end defun
    342 
    343 @defun gdb.set_parameter (name, value)
    344 Sets the gdb parameter @var{name} to @var{value}.  As with
    345 @code{gdb.parameter}, the parameter name string may contain spaces if
    346 the parameter has a multi-part name.
    347 @end defun
    348 
    349 @defun gdb.with_parameter (name, value)
    350 Create a Python context manager (for use with the Python
    351 @command{with} statement) that temporarily sets the gdb parameter
    352 @var{name} to @var{value}.  On exit from the context, the previous
    353 value will be restored.
    354 
    355 This uses @code{gdb.parameter} in its implementation, so it can throw
    356 the same exceptions as that function.
    357 
    358 For example, it's sometimes useful to evaluate some Python code with a
    359 particular gdb language:
    360 
    361 @smallexample
    362 with gdb.with_parameter('language', 'pascal'):
    363   ... language-specific operations
    364 @end smallexample
    365 @end defun
    366 
    367 @defun gdb.history (number)
    368 Return a value from @value{GDBN}'s value history (@pxref{Value
    369 History}).  The @var{number} argument indicates which history element to return.
    370 If @var{number} is negative, then @value{GDBN} will take its absolute value
    371 and count backward from the last element (i.e., the most recent element) to
    372 find the value to return.  If @var{number} is zero, then @value{GDBN} will
    373 return the most recent element.  If the element specified by @var{number}
    374 doesn't exist in the value history, a @code{gdb.error} exception will be
    375 raised.
    376 
    377 If no exception is raised, the return value is always an instance of
    378 @code{gdb.Value} (@pxref{Values From Inferior}).
    379 @end defun
    380 
    381 @defun gdb.add_history (value)
    382 Takes @var{value}, an instance of @code{gdb.Value} (@pxref{Values From
    383 Inferior}), and appends the value this object represents to
    384 @value{GDBN}'s value history (@pxref{Value History}), and return an
    385 integer, its history number.  If @var{value} is not a
    386 @code{gdb.Value}, it is is converted using the @code{gdb.Value}
    387 constructor.  If @var{value} can't be converted to a @code{gdb.Value}
    388 then a @code{TypeError} is raised.
    389 
    390 When a command implemented in Python prints a single @code{gdb.Value}
    391 as its result, then placing the value into the history will allow the
    392 user convenient access to those values via CLI history facilities.
    393 @end defun
    394 
    395 @defun gdb.history_count ()
    396 Return an integer indicating the number of values in @value{GDBN}'s
    397 value history (@pxref{Value History}).
    398 @end defun
    399 
    400 @defun gdb.convenience_variable (name)
    401 Return the value of the convenience variable (@pxref{Convenience
    402 Vars}) named @var{name}.  @var{name} must be a string.  The name
    403 should not include the @samp{$} that is used to mark a convenience
    404 variable in an expression.  If the convenience variable does not
    405 exist, then @code{None} is returned.
    406 @end defun
    407 
    408 @defun gdb.set_convenience_variable (name, value)
    409 Set the value of the convenience variable (@pxref{Convenience Vars})
    410 named @var{name}.  @var{name} must be a string.  The name should not
    411 include the @samp{$} that is used to mark a convenience variable in an
    412 expression.  If @var{value} is @code{None}, then the convenience
    413 variable is removed.  Otherwise, if @var{value} is not a
    414 @code{gdb.Value} (@pxref{Values From Inferior}), it is is converted
    415 using the @code{gdb.Value} constructor.
    416 @end defun
    417 
    418 @defun gdb.parse_and_eval (expression @r{[}, global_context@r{]})
    419 Parse @var{expression}, which must be a string, as an expression in
    420 the current language, evaluate it, and return the result as a
    421 @code{gdb.Value}.
    422 
    423 @var{global_context}, if provided, is a boolean indicating whether the
    424 parsing should be done in the global context.  The default is
    425 @samp{False}, meaning that the current frame or current static context
    426 should be used.
    427 
    428 This function can be useful when implementing a new command
    429 (@pxref{CLI Commands In Python}, @pxref{GDB/MI Commands In Python}),
    430 as it provides a way to parse the
    431 command's argument as an expression.  It is also useful simply to
    432 compute values.
    433 @end defun
    434 
    435 @defun gdb.find_pc_line (pc)
    436 Return the @code{gdb.Symtab_and_line} object corresponding to the
    437 @var{pc} value.  @xref{Symbol Tables In Python}.  If an invalid
    438 value of @var{pc} is passed as an argument, then the @code{symtab} and
    439 @code{line} attributes of the returned @code{gdb.Symtab_and_line} object
    440 will be @code{None} and 0 respectively.  This is identical to
    441 @code{gdb.current_progspace().find_pc_line(pc)} and is included for
    442 historical compatibility.
    443 @end defun
    444 
    445 @defun gdb.write (string @r{[}, stream@r{]})
    446 Print a string to @value{GDBN}'s paginated output stream.  The
    447 optional @var{stream} determines the stream to print to.  The default
    448 stream is @value{GDBN}'s standard output stream.  Possible stream
    449 values are:
    450 
    451 @table @code
    452 @findex STDOUT
    453 @findex gdb.STDOUT
    454 @item gdb.STDOUT
    455 @value{GDBN}'s standard output stream.
    456 
    457 @findex STDERR
    458 @findex gdb.STDERR
    459 @item gdb.STDERR
    460 @value{GDBN}'s standard error stream.
    461 
    462 @findex STDLOG
    463 @findex gdb.STDLOG
    464 @item gdb.STDLOG
    465 @value{GDBN}'s log stream (@pxref{Logging Output}).
    466 @end table
    467 
    468 Writing to @code{sys.stdout} or @code{sys.stderr} will automatically
    469 call this function and will automatically direct the output to the
    470 relevant stream.
    471 @end defun
    472 
    473 @defun gdb.flush (@r{[}, stream@r{]})
    474 Flush the buffer of a @value{GDBN} paginated stream so that the
    475 contents are displayed immediately.  @value{GDBN} will flush the
    476 contents of a stream automatically when it encounters a newline in the
    477 buffer.  The optional @var{stream} determines the stream to flush.  The
    478 default stream is @value{GDBN}'s standard output stream.  Possible
    479 stream values are: 
    480 
    481 @table @code
    482 @findex STDOUT
    483 @findex gdb.STDOUT
    484 @item gdb.STDOUT
    485 @value{GDBN}'s standard output stream.
    486 
    487 @findex STDERR
    488 @findex gdb.STDERR
    489 @item gdb.STDERR
    490 @value{GDBN}'s standard error stream.
    491 
    492 @findex STDLOG
    493 @findex gdb.STDLOG
    494 @item gdb.STDLOG
    495 @value{GDBN}'s log stream (@pxref{Logging Output}).
    496 
    497 @end table
    498 
    499 Flushing @code{sys.stdout} or @code{sys.stderr} will automatically
    500 call this function for the relevant stream.
    501 @end defun
    502 
    503 @defun gdb.target_charset ()
    504 Return the name of the current target character set (@pxref{Character
    505 Sets}).  This differs from @code{gdb.parameter('target-charset')} in
    506 that @samp{auto} is never returned.
    507 @end defun
    508 
    509 @defun gdb.target_wide_charset ()
    510 Return the name of the current target wide character set
    511 (@pxref{Character Sets}).  This differs from
    512 @code{gdb.parameter('target-wide-charset')} in that @samp{auto} is
    513 never returned.
    514 @end defun
    515 
    516 @defun gdb.host_charset ()
    517 Return a string, the name of the current host character set
    518 (@pxref{Character Sets}).  This differs from
    519 @code{gdb.parameter('host-charset')} in that @samp{auto} is never
    520 returned.
    521 @end defun
    522 
    523 @defun gdb.solib_name (address)
    524 Return the name of the shared library holding the given @var{address}
    525 as a string, or @code{None}.  This is identical to
    526 @code{gdb.current_progspace().solib_name(address)} and is included for
    527 historical compatibility.
    528 @end defun
    529 
    530 @defun gdb.decode_line (@r{[}expression@r{]})
    531 Return locations of the line specified by @var{expression}, or of the
    532 current line if no argument was given.  This function returns a Python
    533 tuple containing two elements.  The first element contains a string
    534 holding any unparsed section of @var{expression} (or @code{None} if
    535 the expression has been fully parsed).  The second element contains
    536 either @code{None} or another tuple that contains all the locations
    537 that match the expression represented as @code{gdb.Symtab_and_line}
    538 objects (@pxref{Symbol Tables In Python}).  If @var{expression} is
    539 provided, it is decoded the way that @value{GDBN}'s inbuilt
    540 @code{break} or @code{edit} commands do (@pxref{Location
    541 Specifications}).
    542 @end defun
    543 
    544 @defun gdb.prompt_hook (current_prompt)
    545 @anchor{prompt_hook}
    546 
    547 If @var{prompt_hook} is callable, @value{GDBN} will call the method
    548 assigned to this operation before a prompt is displayed by
    549 @value{GDBN}.
    550 
    551 The parameter @code{current_prompt} contains the current @value{GDBN} 
    552 prompt.  This method must return a Python string, or @code{None}.  If
    553 a string is returned, the @value{GDBN} prompt will be set to that
    554 string.  If @code{None} is returned, @value{GDBN} will continue to use
    555 the current prompt.
    556 
    557 Some prompts cannot be substituted in @value{GDBN}.  Secondary prompts
    558 such as those used by readline for command input, and annotation
    559 related prompts are prohibited from being changed.
    560 @end defun
    561 
    562 @anchor{gdb_architecture_names}
    563 @defun gdb.architecture_names ()
    564 Return a list containing all of the architecture names that the
    565 current build of @value{GDBN} supports.  Each architecture name is a
    566 string.  The names returned in this list are the same names as are
    567 returned from @code{gdb.Architecture.name}
    568 (@pxref{gdbpy_architecture_name,,Architecture.name}).
    569 @end defun
    570 
    571 @anchor{gdbpy_connections}
    572 @defun gdb.connections
    573 Return a list of @code{gdb.TargetConnection} objects, one for each
    574 currently active connection (@pxref{Connections In Python}).  The
    575 connection objects are in no particular order in the returned list.
    576 @end defun
    577 
    578 @defun gdb.format_address (address @r{[}, progspace, architecture@r{]})
    579 Return a string in the format @samp{@var{addr}
    580 <@var{symbol}+@var{offset}>}, where @var{addr} is @var{address}
    581 formatted in hexadecimal, @var{symbol} is the symbol whose address is
    582 the nearest to @var{address} and below it in memory, and @var{offset}
    583 is the offset from @var{symbol} to @var{address} in decimal.
    584 
    585 If no suitable @var{symbol} was found, then the
    586 <@var{symbol}+@var{offset}> part is not included in the returned
    587 string, instead the returned string will just contain the
    588 @var{address} formatted as hexadecimal.  How far @value{GDBN} looks
    589 back for a suitable symbol can be controlled with @kbd{set print
    590 max-symbolic-offset} (@pxref{Print Settings}).
    591 
    592 Additionally, the returned string can include file name and line
    593 number information when @kbd{set print symbol-filename on}
    594 (@pxref{Print Settings}), in this case the format of the returned
    595 string is @samp{@var{addr} <@var{symbol}+@var{offset}> at
    596 @var{filename}:@var{line-number}}.
    597 
    598 
    599 The @var{progspace} is the gdb.Progspace in which @var{symbol} is
    600 looked up, and @var{architecture} is used when formatting @var{addr},
    601 e.g.@: in order to determine the size of an address in bytes.
    602 
    603 If neither @var{progspace} or @var{architecture} are passed, then by
    604 default @value{GDBN} will use the program space and architecture of
    605 the currently selected inferior, thus, the following two calls are
    606 equivalent:
    607 
    608 @smallexample
    609 gdb.format_address(address)
    610 gdb.format_address(address,
    611                    gdb.selected_inferior().progspace,
    612                    gdb.selected_inferior().architecture())
    613 @end smallexample
    614 
    615 It is not valid to only pass one of @var{progspace} or
    616 @var{architecture}, either they must both be provided, or neither must
    617 be provided (and the defaults will be used).
    618 
    619 This method uses the same mechanism for formatting address, symbol,
    620 and offset information as core @value{GDBN} does in commands such as
    621 @kbd{disassemble}.
    622 
    623 Here are some examples of the possible string formats:
    624 
    625 @smallexample
    626 0x00001042
    627 0x00001042 <symbol+16>
    628 0x00001042 <symbol+16 at file.c:123>
    629 @end smallexample
    630 @end defun
    631 
    632 @defun gdb.current_language ()
    633 Return the name of the current language as a string.  Unlike
    634 @code{gdb.parameter('language')}, this function will never return
    635 @samp{auto}.  If a @code{gdb.Frame} object is available (@pxref{Frames
    636 In Python}), the @code{language} method might be preferable in some
    637 cases, as that is not affected by the user's language setting.
    638 @end defun
    639 
    640 @node Threading in GDB
    641 @subsubsection Threading in GDB
    642 
    643 @value{GDBN} is not thread-safe.  If your Python program uses multiple
    644 threads, you must be careful to only call @value{GDBN}-specific
    645 functions in the @value{GDBN} thread.  @value{GDBN} provides some
    646 functions to help with this.
    647 
    648 @defun gdb.block_signals ()
    649 As mentioned earlier (@pxref{Basic Python}), certain signals must be
    650 delivered to the @value{GDBN} main thread.  The @code{block_signals}
    651 function returns a context manager that will block these signals on
    652 entry.  This can be used when starting a new thread to ensure that the
    653 signals are blocked there, like:
    654 
    655 @smallexample
    656 with gdb.block_signals():
    657    start_new_thread()
    658 @end smallexample
    659 @end defun
    660 
    661 @deftp {class} gdb.Thread
    662 This is a subclass of Python's @code{threading.Thread} class.  It
    663 overrides the @code{start} method to call @code{block_signals}, making
    664 this an easy-to-use drop-in replacement for creating threads that will
    665 work well in @value{GDBN}.
    666 @end deftp
    667 
    668 @defun gdb.interrupt ()
    669 This causes @value{GDBN} to react as if the user had typed a control-C
    670 character at the terminal.  That is, if the inferior is running, it is
    671 interrupted; if a @value{GDBN} command is executing, it is stopped;
    672 and if a Python command is running, @code{KeyboardInterrupt} will be
    673 raised.
    674 
    675 Unlike most Python APIs in @value{GDBN}, @code{interrupt} is
    676 thread-safe.
    677 @end defun
    678 
    679 @defun gdb.post_event (event)
    680 Put @var{event}, a callable object taking no arguments, into
    681 @value{GDBN}'s internal event queue.  This callable will be invoked at
    682 some later point, during @value{GDBN}'s event processing.  Events
    683 posted using @code{post_event} will be run in the order in which they
    684 were posted; however, there is no way to know when they will be
    685 processed relative to other events inside @value{GDBN}.
    686 
    687 Unlike most Python APIs in @value{GDBN}, @code{post_event} is
    688 thread-safe.  For example:
    689 
    690 @smallexample
    691 (@value{GDBP}) python
    692 >import threading
    693 >
    694 >class Writer():
    695 > def __init__(self, message):
    696 >        self.message = message;
    697 > def __call__(self):
    698 >        gdb.write(self.message)
    699 >
    700 >class MyThread1 (threading.Thread):
    701 > def run (self):
    702 >        gdb.post_event(Writer("Hello "))
    703 >
    704 >class MyThread2 (threading.Thread):
    705 > def run (self):
    706 >        gdb.post_event(Writer("World\n"))
    707 >
    708 >MyThread1().start()
    709 >MyThread2().start()
    710 >end
    711 (@value{GDBP}) Hello World
    712 @end smallexample
    713 @end defun
    714 
    715 
    716 @node Exception Handling
    717 @subsubsection Exception Handling
    718 @cindex python exceptions
    719 @cindex exceptions, python
    720 
    721 When executing the @code{python} command, Python exceptions
    722 uncaught within the Python code are translated to calls to
    723 @value{GDBN} error-reporting mechanism.  If the command that called
    724 @code{python} does not handle the error, @value{GDBN} will
    725 terminate it and print an error message.  Exactly what will be printed
    726 depends on @code{set python print-stack} (@pxref{Python Commands}).
    727 Example:
    728 
    729 @smallexample
    730 (@value{GDBP}) python print foo
    731 Traceback (most recent call last):
    732   File "<string>", line 1, in <module>
    733 NameError: name 'foo' is not defined
    734 @end smallexample
    735 
    736 @value{GDBN} errors that happen in @value{GDBN} commands invoked by
    737 Python code are converted to Python exceptions.  The type of the
    738 Python exception depends on the error.
    739 
    740 @ftable @code
    741 @item gdb.error
    742 This is the base class for most exceptions generated by @value{GDBN}.
    743 It is derived from @code{RuntimeError}, for compatibility with earlier
    744 versions of @value{GDBN}.
    745 
    746 If an error occurring in @value{GDBN} does not fit into some more
    747 specific category, then the generated exception will have this type.
    748 
    749 @item gdb.MemoryError
    750 This is a subclass of @code{gdb.error} which is thrown when an
    751 operation tried to access invalid memory in the inferior.
    752 
    753 @item KeyboardInterrupt
    754 User interrupt (via @kbd{C-c} or by typing @kbd{q} at a pagination
    755 prompt) is translated to a Python @code{KeyboardInterrupt} exception.
    756 @end ftable
    757 
    758 In all cases, your exception handler will see the @value{GDBN} error
    759 message as its value and the Python call stack backtrace at the Python
    760 statement closest to where the @value{GDBN} error occurred as the
    761 traceback.
    762 
    763 
    764 When implementing @value{GDBN} commands in Python via
    765 @code{gdb.Command}, or functions via @code{gdb.Function}, it is useful
    766 to be able to throw an exception that doesn't cause a traceback to be
    767 printed.  For example, the user may have invoked the command
    768 incorrectly.  @value{GDBN} provides a special exception class that can
    769 be used for this purpose.
    770 
    771 @ftable @code
    772 @item gdb.GdbError
    773 When thrown from a command or function, this exception will cause the
    774 command or function to fail, but the Python stack will not be
    775 displayed.  @value{GDBN} does not throw this exception itself, but
    776 rather recognizes it when thrown from user Python code.  Example:
    777 
    778 @smallexample
    779 (gdb) python
    780 >class HelloWorld (gdb.Command):
    781 >  """Greet the whole world."""
    782 >  def __init__ (self):
    783 >    super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
    784 >  def invoke (self, args, from_tty):
    785 >    argv = gdb.string_to_argv (args)
    786 >    if len (argv) != 0:
    787 >      raise gdb.GdbError ("hello-world takes no arguments")
    788 >    print ("Hello, World!")
    789 >HelloWorld ()
    790 >end
    791 (gdb) hello-world 42
    792 hello-world takes no arguments
    793 @end smallexample
    794 @end ftable
    795 
    796 @node Values From Inferior
    797 @subsubsection Values From Inferior
    798 @cindex values from inferior, with Python
    799 @cindex python, working with values from inferior
    800 
    801 @cindex @code{gdb.Value}
    802 @value{GDBN} provides values it obtains from the inferior program in
    803 an object of type @code{gdb.Value}.  @value{GDBN} uses this object
    804 for its internal bookkeeping of the inferior's values, and for
    805 fetching values when necessary.
    806 
    807 Inferior values that are simple scalars can be used directly in
    808 Python expressions that are valid for the value's data type.  Here's
    809 an example for an integer or floating-point value @code{some_val}:
    810 
    811 @smallexample
    812 bar = some_val + 2
    813 @end smallexample
    814 
    815 @noindent
    816 As result of this, @code{bar} will also be a @code{gdb.Value} object
    817 whose values are of the same type as those of @code{some_val}.  Valid
    818 Python operations can also be performed on @code{gdb.Value} objects
    819 representing a @code{struct} or @code{class} object.  For such cases,
    820 the overloaded operator (if present), is used to perform the operation.
    821 For example, if @code{val1} and @code{val2} are @code{gdb.Value} objects
    822 representing instances of a @code{class} which overloads the @code{+}
    823 operator, then one can use the @code{+} operator in their Python script
    824 as follows:
    825 
    826 @smallexample
    827 val3 = val1 + val2
    828 @end smallexample
    829 
    830 @noindent
    831 The result of the operation @code{val3} is also a @code{gdb.Value}
    832 object corresponding to the value returned by the overloaded @code{+}
    833 operator.  In general, overloaded operators are invoked for the
    834 following operations: @code{+} (binary addition), @code{-} (binary
    835 subtraction), @code{*} (multiplication), @code{/}, @code{%}, @code{<<},
    836 @code{>>}, @code{|}, @code{&}, @code{^}.
    837 
    838 Inferior values that are structures or instances of some class can
    839 be accessed using the Python @dfn{dictionary syntax}.  For example, if
    840 @code{some_val} is a @code{gdb.Value} instance holding a structure, you
    841 can access its @code{foo} element with:
    842 
    843 @smallexample
    844 bar = some_val['foo']
    845 @end smallexample
    846 
    847 @cindex getting structure elements using gdb.Field objects as subscripts
    848 Again, @code{bar} will also be a @code{gdb.Value} object.  Structure
    849 elements can also be accessed by using @code{gdb.Field} objects as
    850 subscripts (@pxref{Types In Python}, for more information on
    851 @code{gdb.Field} objects).  For example, if @code{foo_field} is a
    852 @code{gdb.Field} object corresponding to element @code{foo} of the above
    853 structure, then @code{bar} can also be accessed as follows:
    854 
    855 @smallexample
    856 bar = some_val[foo_field]
    857 @end smallexample
    858 
    859 If a @code{gdb.Value} has array or pointer type, an integer index can
    860 be used to access elements.
    861 
    862 @smallexample
    863 result = some_array[23]
    864 @end smallexample
    865 
    866 A @code{gdb.Value} that represents a function can be executed via
    867 inferior function call.  Any arguments provided to the call must match
    868 the function's prototype, and must be provided in the order specified
    869 by that prototype.
    870 
    871 For example, @code{some_val} is a @code{gdb.Value} instance
    872 representing a function that takes two integers as arguments.  To
    873 execute this function, call it like so:
    874 
    875 @smallexample
    876 result = some_val (10,20)
    877 @end smallexample
    878 
    879 Any values returned from a function call will be stored as a
    880 @code{gdb.Value}.
    881 
    882 The following attributes are provided:
    883 
    884 @defvar Value.address
    885 If this object is addressable, this read-only attribute holds a
    886 @code{gdb.Value} object representing the address.  Otherwise,
    887 this attribute holds @code{None}.
    888 @end defvar
    889 
    890 @cindex optimized out value in Python
    891 @defvar Value.is_optimized_out
    892 This read-only boolean attribute is true if the compiler optimized out
    893 this value, thus it is not available for fetching from the inferior.
    894 @end defvar
    895 
    896 @defvar Value.type
    897 The type of this @code{gdb.Value}.  The value of this attribute is a
    898 @code{gdb.Type} object (@pxref{Types In Python}).
    899 @end defvar
    900 
    901 @defvar Value.dynamic_type
    902 The dynamic type of this @code{gdb.Value}.  This uses the object's
    903 virtual table and the C@t{++} run-time type information
    904 (@acronym{RTTI}) to determine the dynamic type of the value.  If this
    905 value is of class type, it will return the class in which the value is
    906 embedded, if any.  If this value is of pointer or reference to a class
    907 type, it will compute the dynamic type of the referenced object, and
    908 return a pointer or reference to that type, respectively.  In all
    909 other cases, it will return the value's static type.
    910 
    911 Note that this feature will only work when debugging a C@t{++} program
    912 that includes @acronym{RTTI} for the object in question.  Otherwise,
    913 it will just return the static type of the value as in @kbd{ptype foo}
    914 (@pxref{Symbols, ptype}).
    915 @end defvar
    916 
    917 @defvar Value.is_lazy
    918 The value of this read-only boolean attribute is @code{True} if this
    919 @code{gdb.Value} has not yet been fetched from the inferior.  
    920 @value{GDBN} does not fetch values until necessary, for efficiency.  
    921 For example:
    922 
    923 @smallexample
    924 myval = gdb.parse_and_eval ('somevar')
    925 @end smallexample
    926 
    927 The value of @code{somevar} is not fetched at this time.  It will be 
    928 fetched when the value is needed, or when the @code{fetch_lazy}
    929 method is invoked.  
    930 @end defvar
    931 
    932 @defvar Value.bytes
    933 The value of this attribute is a @code{bytes} object containing the
    934 bytes that make up this @code{Value}'s complete value in little endian
    935 order.  If the complete contents of this value are not available then
    936 accessing this attribute will raise an exception.
    937 
    938 This attribute can also be assigned to.  The new value should be a
    939 buffer object (e.g.@: a @code{bytes} object), the length of the new
    940 buffer must exactly match the length of this @code{Value}'s type.  The
    941 bytes values in the new buffer should be in little endian order.
    942 
    943 As with @code{Value.assign} (@pxref{Value.assign}), if this value
    944 cannot be assigned to, then an exception will be thrown.
    945 @end defvar
    946 
    947 The following methods are provided:
    948 
    949 @defun Value.__init__ (val)
    950 Many Python values can be converted directly to a @code{gdb.Value} via
    951 this object initializer.  Specifically:
    952 
    953 @table @asis
    954 @item Python boolean
    955 A Python boolean is converted to the boolean type from the current
    956 language.
    957 
    958 @item Python integer
    959 A Python integer is converted to the C @code{long} type for the
    960 current architecture.
    961 
    962 @item Python long
    963 A Python long is converted to the C @code{long long} type for the
    964 current architecture.
    965 
    966 @item Python float
    967 A Python float is converted to the C @code{double} type for the
    968 current architecture.
    969 
    970 @item Python string
    971 A Python string is converted to a target string in the current target
    972 language using the current target encoding.
    973 If a character cannot be represented in the current target encoding,
    974 then an exception is thrown.
    975 
    976 @item @code{gdb.Value}
    977 If @code{val} is a @code{gdb.Value}, then a copy of the value is made.
    978 
    979 @item @code{gdb.LazyString}
    980 If @code{val} is a @code{gdb.LazyString} (@pxref{Lazy Strings In
    981 Python}), then the lazy string's @code{value} method is called, and
    982 its result is used.
    983 @end table
    984 @end defun
    985 
    986 @defun Value.__init__ (val, type)
    987 This second form of the @code{gdb.Value} constructor returns a
    988 @code{gdb.Value} of type @var{type} where the value contents are taken
    989 from the Python buffer object specified by @var{val}.  The number of
    990 bytes in the Python buffer object must be greater than or equal to the
    991 size of @var{type}.
    992 
    993 If @var{type} is @code{None} then this version of @code{__init__}
    994 behaves as though @var{type} was not passed at all.
    995 @end defun
    996 
    997 @anchor{Value.assign}
    998 @defun Value.assign (rhs)
    999 Assign @var{rhs} to this value, and return @code{None}.  If this value
   1000 cannot be assigned to, or if the assignment is invalid for some reason
   1001 (for example a type-checking failure), an exception will be thrown.
   1002 @end defun
   1003 
   1004 @defun Value.cast (type)
   1005 Return a new instance of @code{gdb.Value} that is the result of
   1006 casting this instance to the type described by @var{type}, which must
   1007 be a @code{gdb.Type} object.  If the cast cannot be performed for some
   1008 reason, this method throws an exception.
   1009 @end defun
   1010 
   1011 @defun Value.dereference ()
   1012 For pointer data types, this method returns a new @code{gdb.Value} object
   1013 whose contents is the object pointed to by the pointer.  For example, if
   1014 @code{foo} is a C pointer to an @code{int}, declared in your C program as
   1015 
   1016 @smallexample
   1017 int *foo;
   1018 @end smallexample
   1019 
   1020 @noindent
   1021 then you can use the corresponding @code{gdb.Value} to access what
   1022 @code{foo} points to like this:
   1023 
   1024 @smallexample
   1025 bar = foo.dereference ()
   1026 @end smallexample
   1027 
   1028 The result @code{bar} will be a @code{gdb.Value} object holding the
   1029 value pointed to by @code{foo}.
   1030 
   1031 A similar function @code{Value.referenced_value} exists which also
   1032 returns @code{gdb.Value} objects corresponding to the values pointed to
   1033 by pointer values (and additionally, values referenced by reference
   1034 values).  However, the behavior of @code{Value.dereference}
   1035 differs from @code{Value.referenced_value} by the fact that the
   1036 behavior of @code{Value.dereference} is identical to applying the C
   1037 unary operator @code{*} on a given value.  For example, consider a
   1038 reference to a pointer @code{ptrref}, declared in your C@t{++} program
   1039 as
   1040 
   1041 @smallexample
   1042 typedef int *intptr;
   1043 ...
   1044 int val = 10;
   1045 intptr ptr = &val;
   1046 intptr &ptrref = ptr;
   1047 @end smallexample
   1048 
   1049 Though @code{ptrref} is a reference value, one can apply the method
   1050 @code{Value.dereference} to the @code{gdb.Value} object corresponding
   1051 to it and obtain a @code{gdb.Value} which is identical to that
   1052 corresponding to @code{val}.  However, if you apply the method
   1053 @code{Value.referenced_value}, the result would be a @code{gdb.Value}
   1054 object identical to that corresponding to @code{ptr}.
   1055 
   1056 @smallexample
   1057 py_ptrref = gdb.parse_and_eval ("ptrref")
   1058 py_val = py_ptrref.dereference ()
   1059 py_ptr = py_ptrref.referenced_value ()
   1060 @end smallexample
   1061 
   1062 The @code{gdb.Value} object @code{py_val} is identical to that
   1063 corresponding to @code{val}, and @code{py_ptr} is identical to that
   1064 corresponding to @code{ptr}.  In general, @code{Value.dereference} can
   1065 be applied whenever the C unary operator @code{*} can be applied
   1066 to the corresponding C value.  For those cases where applying both
   1067 @code{Value.dereference} and @code{Value.referenced_value} is allowed,
   1068 the results obtained need not be identical (as we have seen in the above
   1069 example).  The results are however identical when applied on
   1070 @code{gdb.Value} objects corresponding to pointers (@code{gdb.Value}
   1071 objects with type code @code{TYPE_CODE_PTR}) in a C/C@t{++} program.
   1072 @end defun
   1073 
   1074 @defun Value.referenced_value ()
   1075 For pointer or reference data types, this method returns a new
   1076 @code{gdb.Value} object corresponding to the value referenced by the
   1077 pointer/reference value.  For pointer data types,
   1078 @code{Value.dereference} and @code{Value.referenced_value} produce
   1079 identical results.  The difference between these methods is that
   1080 @code{Value.dereference} cannot get the values referenced by reference
   1081 values.  For example, consider a reference to an @code{int}, declared
   1082 in your C@t{++} program as
   1083 
   1084 @smallexample
   1085 int val = 10;
   1086 int &ref = val;
   1087 @end smallexample
   1088 
   1089 @noindent
   1090 then applying @code{Value.dereference} to the @code{gdb.Value} object
   1091 corresponding to @code{ref} will result in an error, while applying
   1092 @code{Value.referenced_value} will result in a @code{gdb.Value} object
   1093 identical to that corresponding to @code{val}.
   1094 
   1095 @smallexample
   1096 py_ref = gdb.parse_and_eval ("ref")
   1097 er_ref = py_ref.dereference ()       # Results in error
   1098 py_val = py_ref.referenced_value ()  # Returns the referenced value
   1099 @end smallexample
   1100 
   1101 The @code{gdb.Value} object @code{py_val} is identical to that
   1102 corresponding to @code{val}.
   1103 @end defun
   1104 
   1105 @defun Value.reference_value ()
   1106 Return a @code{gdb.Value} object which is a reference to the value
   1107 encapsulated by this instance.
   1108 @end defun
   1109 
   1110 @defun Value.const_value ()
   1111 Return a @code{gdb.Value} object which is a @code{const} version of the
   1112 value encapsulated by this instance.
   1113 @end defun
   1114 
   1115 @defun Value.dynamic_cast (type)
   1116 Like @code{Value.cast}, but works as if the C@t{++} @code{dynamic_cast}
   1117 operator were used.  Consult a C@t{++} reference for details.
   1118 @end defun
   1119 
   1120 @defun Value.reinterpret_cast (type)
   1121 Like @code{Value.cast}, but works as if the C@t{++} @code{reinterpret_cast}
   1122 operator were used.  Consult a C@t{++} reference for details.
   1123 @end defun
   1124 
   1125 @defun Value.format_string (...)
   1126 Convert a @code{gdb.Value} to a string, similarly to what the @code{print}
   1127 command does.  Invoked with no arguments, this is equivalent to calling
   1128 the @code{str} function on the @code{gdb.Value}.  The representation of
   1129 the same value may change across different versions of @value{GDBN}, so
   1130 you shouldn't, for instance, parse the strings returned by this method.
   1131 
   1132 All the arguments are keyword only.  If an argument is not specified, the
   1133 current global default setting is used.
   1134 
   1135 @table @code
   1136 @item raw
   1137 @code{True} if pretty-printers (@pxref{Pretty Printing}) should not be
   1138 used to format the value.  @code{False} if enabled pretty-printers
   1139 matching the type represented by the @code{gdb.Value} should be used to
   1140 format it.
   1141 
   1142 @item pretty_arrays
   1143 @code{True} if arrays should be pretty printed to be more convenient to
   1144 read, @code{False} if they shouldn't (see @code{set print array} in
   1145 @ref{Print Settings}).
   1146 
   1147 @item pretty_structs
   1148 @code{True} if structs should be pretty printed to be more convenient to
   1149 read, @code{False} if they shouldn't (see @code{set print pretty} in
   1150 @ref{Print Settings}).
   1151 
   1152 @item array_indexes
   1153 @code{True} if array indexes should be included in the string
   1154 representation of arrays, @code{False} if they shouldn't (see @code{set
   1155 print array-indexes} in @ref{Print Settings}).
   1156 
   1157 @item symbols
   1158 @code{True} if the string representation of a pointer should include the
   1159 corresponding symbol name (if one exists), @code{False} if it shouldn't
   1160 (see @code{set print symbol} in @ref{Print Settings}).
   1161 
   1162 @item unions
   1163 @code{True} if unions which are contained in other structures or unions
   1164 should be expanded, @code{False} if they shouldn't (see @code{set print
   1165 union} in @ref{Print Settings}).
   1166 
   1167 @item address
   1168 @code{True} if the string representation of a pointer should include the
   1169 address, @code{False} if it shouldn't (see @code{set print address} in
   1170 @ref{Print Settings}).
   1171 
   1172 @item nibbles
   1173 @code{True} if binary values should be displayed in groups of four bits,
   1174 known as nibbles.  @code{False} if it shouldn't (@pxref{Print Settings,
   1175 set print nibbles}).
   1176 
   1177 @item deref_refs
   1178 @code{True} if C@t{++} references should be resolved to the value they
   1179 refer to, @code{False} (the default) if they shouldn't.  Note that, unlike
   1180 for the @code{print} command, references are not automatically expanded
   1181 when using the @code{format_string} method or the @code{str}
   1182 function.  There is no global @code{print} setting to change the default
   1183 behavior.
   1184 
   1185 @item actual_objects
   1186 @code{True} if the representation of a pointer to an object should
   1187 identify the @emph{actual} (derived) type of the object rather than the
   1188 @emph{declared} type, using the virtual function table.  @code{False} if
   1189 the @emph{declared} type should be used.  (See @code{set print object} in
   1190 @ref{Print Settings}).
   1191 
   1192 @item static_members
   1193 @code{True} if static members should be included in the string
   1194 representation of a C@t{++} object, @code{False} if they shouldn't (see
   1195 @code{set print static-members} in @ref{Print Settings}).
   1196 
   1197 @item max_characters
   1198 Number of string characters to print, @code{0} to follow
   1199 @code{max_elements}, or @code{UINT_MAX} to print an unlimited number
   1200 of characters (see @code{set print characters} in @ref{Print Settings}).
   1201 
   1202 @item max_elements
   1203 Number of array elements to print, or @code{0} to print an unlimited
   1204 number of elements (see @code{set print elements} in @ref{Print
   1205 Settings}).
   1206 
   1207 @item max_depth
   1208 The maximum depth to print for nested structs and unions, or @code{-1}
   1209 to print an unlimited number of elements (see @code{set print
   1210 max-depth} in @ref{Print Settings}).
   1211 
   1212 @item repeat_threshold
   1213 Set the threshold for suppressing display of repeated array elements, or
   1214 @code{0} to represent all elements, even if repeated.  (See @code{set
   1215 print repeats} in @ref{Print Settings}).
   1216 
   1217 @item format
   1218 A string containing a single character representing the format to use for
   1219 the returned string.  For instance, @code{'x'} is equivalent to using the
   1220 @value{GDBN} command @code{print} with the @code{/x} option and formats
   1221 the value as a hexadecimal number.
   1222 
   1223 @item styling
   1224 @code{True} if @value{GDBN} should apply styling to the returned
   1225 string.  When styling is applied, the returned string might contain
   1226 ANSI terminal escape sequences.  Escape sequences will only be
   1227 included if styling is turned on, see @ref{Output Styling}.
   1228 Additionally, @value{GDBN} only styles some value contents, so not
   1229 every output string will contain escape sequences.
   1230 
   1231 When @code{False}, which is the default, no output styling is applied.
   1232 
   1233 @item summary
   1234 @code{True} when just a summary should be printed.  In this mode,
   1235 scalar values are printed in their entirety, but aggregates such as
   1236 structures or unions are omitted.  This mode is used by @code{set
   1237 print frame-arguments scalars} (@pxref{Print Settings}).
   1238 @end table
   1239 @end defun
   1240 
   1241 @defun Value.to_array ()
   1242 If this value is array-like (@pxref{Type.is_array_like}), then this
   1243 method converts it to an array, which is returned.  If this value is
   1244 already an array, it is simply returned.  Otherwise, an exception is
   1245 throw.
   1246 @end defun
   1247 
   1248 @defun Value.string (@r{[}encoding@r{[}, errors@r{[}, length@r{]]]})
   1249 If this @code{gdb.Value} represents a string, then this method
   1250 converts the contents to a Python string.  Otherwise, this method will
   1251 throw an exception.
   1252 
   1253 Values are interpreted as strings according to the rules of the
   1254 current language.  If the optional length argument is given, the
   1255 string will be converted to that length, and will include any embedded
   1256 zeroes that the string may contain.  Otherwise, for languages
   1257 where the string is zero-terminated, the entire string will be
   1258 converted.
   1259 
   1260 For example, in C-like languages, a value is a string if it is a pointer
   1261 to or an array of characters or ints of type @code{wchar_t}, @code{char16_t},
   1262 or @code{char32_t}.
   1263 
   1264 If the optional @var{encoding} argument is given, it must be a string
   1265 naming the encoding of the string in the @code{gdb.Value}, such as
   1266 @code{"ascii"}, @code{"iso-8859-6"} or @code{"utf-8"}.  It accepts
   1267 the same encodings as the corresponding argument to Python's
   1268 @code{string.decode} method, and the Python codec machinery will be used
   1269 to convert the string.  If @var{encoding} is not given, or if
   1270 @var{encoding} is the empty string, then either the @code{target-charset}
   1271 (@pxref{Character Sets}) will be used, or a language-specific encoding
   1272 will be used, if the current language is able to supply one.
   1273 
   1274 The optional @var{errors} argument is the same as the corresponding
   1275 argument to Python's @code{string.decode} method.
   1276 
   1277 If the optional @var{length} argument is given, the string will be
   1278 fetched and converted to the given length.
   1279 @end defun
   1280 
   1281 @defun Value.lazy_string (@r{[}encoding @r{[}, length@r{]]})
   1282 This method attempts to convert this @code{gdb.Value} to a
   1283 @code{gdb.LazyString} (@pxref{Lazy Strings In Python}).  Values of
   1284 array or pointer type can be converted; for other types, this method
   1285 will throw an exception.
   1286 
   1287 If the optional @var{encoding} argument is given, it must be a string
   1288 naming the encoding of the @code{gdb.LazyString}.  Some examples are:
   1289 @samp{ascii}, @samp{iso-8859-6} or @samp{utf-8}.  If the
   1290 @var{encoding} argument is an encoding that @value{GDBN} does
   1291 recognize, @value{GDBN} will raise an error.
   1292 
   1293 When a lazy string is printed, the @value{GDBN} encoding machinery is
   1294 used to convert the string during printing.  If the optional
   1295 @var{encoding} argument is not provided, or is an empty string,
   1296 @value{GDBN} will automatically select the encoding most suitable for
   1297 the string type.  For further information on encoding in @value{GDBN}
   1298 please see @ref{Character Sets}.
   1299 
   1300 If the optional @var{length} argument is given, the string will be
   1301 fetched and encoded to the length of characters specified.  If
   1302 the @var{length} argument is not provided, the string will be fetched
   1303 and encoded until a null of appropriate width is found.
   1304 @end defun
   1305 
   1306 @defun Value.fetch_lazy ()
   1307 If the @code{gdb.Value} object is currently a lazy value 
   1308 (@code{gdb.Value.is_lazy} is @code{True}), then the value is
   1309 fetched from the inferior.  Any errors that occur in the process
   1310 will produce a Python exception.
   1311 
   1312 If the @code{gdb.Value} object is not a lazy value, this method
   1313 has no effect.
   1314 
   1315 This method does not return a value.
   1316 @end defun
   1317 
   1318 
   1319 @node Types In Python
   1320 @subsubsection Types In Python
   1321 @cindex types in Python
   1322 @cindex Python, working with types
   1323 
   1324 @tindex gdb.Type
   1325 @value{GDBN} represents types from the inferior using the class
   1326 @code{gdb.Type}.
   1327 
   1328 The following type-related functions are available in the @code{gdb}
   1329 module:
   1330 
   1331 @defun gdb.lookup_type (name @r{[}, block@r{]})
   1332 This function looks up a type by its @var{name}, which must be a string.
   1333 
   1334 If @var{block} is given, then @var{name} is looked up in that scope.
   1335 Otherwise, it is searched for globally.
   1336 
   1337 Ordinarily, this function will return an instance of @code{gdb.Type}.
   1338 If the named type cannot be found, it will throw an exception.
   1339 @end defun
   1340 
   1341 Integer types can be found without looking them up by name.
   1342 @xref{Architectures In Python}, for the @code{integer_type} method.
   1343 
   1344 If the type is a structure or class type, or an enum type, the fields
   1345 of that type can be accessed using the Python @dfn{dictionary syntax}.
   1346 For example, if @code{some_type} is a @code{gdb.Type} instance holding
   1347 a structure type, you can access its @code{foo} field with:
   1348 
   1349 @smallexample
   1350 bar = some_type['foo']
   1351 @end smallexample
   1352 
   1353 @code{bar} will be a @code{gdb.Field} object; see below under the
   1354 description of the @code{Type.fields} method for a description of the
   1355 @code{gdb.Field} class.
   1356 
   1357 An instance of @code{Type} has the following attributes:
   1358 
   1359 @defvar Type.alignof
   1360 The alignment of this type, in bytes.  Type alignment comes from the
   1361 debugging information; if it was not specified, then @value{GDBN} will
   1362 use the relevant ABI to try to determine the alignment.  In some
   1363 cases, even this is not possible, and zero will be returned.
   1364 @end defvar
   1365 
   1366 @defvar Type.code
   1367 The type code for this type.  The type code will be one of the
   1368 @code{TYPE_CODE_} constants defined below.
   1369 @end defvar
   1370 
   1371 @defvar Type.dynamic
   1372 A boolean indicating whether this type is dynamic.  In some
   1373 situations, such as Rust @code{enum} types or Ada variant records, the
   1374 concrete type of a value may vary depending on its contents.  That is,
   1375 the declared type of a variable, or the type returned by
   1376 @code{gdb.lookup_type} may be dynamic; while the type of the
   1377 variable's value will be a concrete instance of that dynamic type.
   1378 
   1379 For example, consider this code:
   1380 @smallexample
   1381 int n;
   1382 int array[n];
   1383 @end smallexample
   1384 
   1385 Here, at least conceptually (whether your compiler actually does this
   1386 is a separate issue), examining @w{@code{gdb.lookup_symbol("array", ...).type}}
   1387 could yield a @code{gdb.Type} which reports a size of @code{None}.
   1388 This is the dynamic type.
   1389 
   1390 However, examining @code{gdb.parse_and_eval("array").type} would yield
   1391 a concrete type, whose length would be known.
   1392 @end defvar
   1393 
   1394 @defvar Type.name
   1395 The name of this type.  If this type has no name, then @code{None}
   1396 is returned.
   1397 @end defvar
   1398 
   1399 @defvar Type.sizeof
   1400 The size of this type, in target @code{char} units.  Usually, a
   1401 target's @code{char} type will be an 8-bit byte.  However, on some
   1402 unusual platforms, this type may have a different size.  A dynamic
   1403 type may not have a fixed size; in this case, this attribute's value
   1404 will be @code{None}.
   1405 @end defvar
   1406 
   1407 @defvar Type.tag
   1408 The tag name for this type.  The tag name is the name after
   1409 @code{struct}, @code{union}, or @code{enum} in C and C@t{++}; not all
   1410 languages have this concept.  If this type has no tag name, then
   1411 @code{None} is returned.
   1412 @end defvar
   1413 
   1414 @defvar Type.objfile
   1415 The @code{gdb.Objfile} that this type was defined in, or @code{None} if
   1416 there is no associated objfile.
   1417 @end defvar
   1418 
   1419 @defvar Type.is_scalar
   1420 This property is @code{True} if the type is a scalar type, otherwise,
   1421 this property is @code{False}.  Examples of non-scalar types include
   1422 structures, unions, and classes.
   1423 @end defvar
   1424 
   1425 @defvar Type.is_signed
   1426 For scalar types (those for which @code{Type.is_scalar} is
   1427 @code{True}), this property is @code{True} if the type is signed,
   1428 otherwise this property is @code{False}.
   1429 
   1430 Attempting to read this property for a non-scalar type (a type for
   1431 which @code{Type.is_scalar} is @code{False}), will raise a
   1432 @code{ValueError}.
   1433 @end defvar
   1434 
   1435 @defvar Type.is_array_like
   1436 @anchor{Type.is_array_like}
   1437 A boolean indicating whether this type is array-like.
   1438 
   1439 Some languages have array-like objects that are represented internally
   1440 as structures.  For example, this is true for a Rust slice type, or
   1441 for an Ada unconstrained array.  @value{GDBN} may know about these
   1442 types.  This determination is done based on the language from which
   1443 the type originated.
   1444 @end defvar
   1445 
   1446 @defvar Type.is_string_like
   1447 A boolean indicating whether this type is string-like.  Like
   1448 @code{Type.is_array_like}, this is determined based on the originating
   1449 language of the type.
   1450 @end defvar
   1451 
   1452 The following methods are provided:
   1453 
   1454 @defun Type.fields ()
   1455 
   1456 Return the fields of this type.  The behavior depends on the type code:
   1457 
   1458 @itemize @bullet
   1459 
   1460 @item
   1461 For structure and union types, this method returns the fields.
   1462 
   1463 @item
   1464 Enum types have one field per enum constant.
   1465 
   1466 @item
   1467 Function and method types have one field per parameter.  The base types of
   1468 C@t{++} classes are also represented as fields.
   1469 
   1470 @item
   1471 Array types have one field representing the array's range.
   1472 
   1473 @item
   1474 If the type does not fit into one of these categories, a @code{TypeError}
   1475 is raised.
   1476 
   1477 @end itemize
   1478 
   1479 Each field is a @code{gdb.Field} object, with some pre-defined attributes:
   1480 @table @code
   1481 @item bitpos
   1482 This attribute is not available for @code{enum} or @code{static}
   1483 (as in C@t{++}) fields.  The value is the position, counting
   1484 in bits, from the start of the containing type.  Note that, in a
   1485 dynamic type, the position of a field may not be constant.  In this
   1486 case, the value will be @code{None}.  Also, a dynamic type may have
   1487 fields that do not appear in a corresponding concrete type.
   1488 
   1489 @item enumval
   1490 This attribute is only available for @code{enum} fields, and its value
   1491 is the enumeration member's integer representation.
   1492 
   1493 @item name
   1494 The name of the field, or @code{None} for anonymous fields.
   1495 
   1496 @item artificial
   1497 This is @code{True} if the field is artificial, usually meaning that
   1498 it was provided by the compiler and not the user.  This attribute is
   1499 always provided, and is @code{False} if the field is not artificial.
   1500 
   1501 @item is_base_class
   1502 This is @code{True} if the field represents a base class of a C@t{++}
   1503 structure.  This attribute is always provided, and is @code{False}
   1504 if the field is not a base class of the type that is the argument of
   1505 @code{fields}, or if that type was not a C@t{++} class.
   1506 
   1507 @item bitsize
   1508 If the field is packed, or is a bitfield, then this will have a
   1509 non-zero value, which is the size of the field in bits.  Otherwise,
   1510 this will be zero; in this case the field's size is given by its type.
   1511 
   1512 @item type
   1513 The type of the field.  This is usually an instance of @code{Type},
   1514 but it can be @code{None} in some situations.
   1515 
   1516 @item parent_type
   1517 The type which contains this field.  This is an instance of
   1518 @code{gdb.Type}.
   1519 @end table
   1520 @end defun
   1521 
   1522 @defun Type.array (n1 @r{[}, n2@r{]})
   1523 Return a new @code{gdb.Type} object which represents an array of this
   1524 type.  If one argument is given, it is the inclusive upper bound of
   1525 the array; in this case the lower bound is zero.  If two arguments are
   1526 given, the first argument is the lower bound of the array, and the
   1527 second argument is the upper bound of the array.  An array's length
   1528 must not be negative, but the bounds can be.
   1529 @end defun
   1530 
   1531 @defun Type.vector (n1 @r{[}, n2@r{]})
   1532 Return a new @code{gdb.Type} object which represents a vector of this
   1533 type.  If one argument is given, it is the inclusive upper bound of
   1534 the vector; in this case the lower bound is zero.  If two arguments are
   1535 given, the first argument is the lower bound of the vector, and the
   1536 second argument is the upper bound of the vector.  A vector's length
   1537 must not be negative, but the bounds can be.
   1538 
   1539 The difference between an @code{array} and a @code{vector} is that
   1540 arrays behave like in C: when used in expressions they decay to a pointer
   1541 to the first element whereas vectors are treated as first class values.
   1542 @end defun
   1543 
   1544 @defun Type.const ()
   1545 Return a new @code{gdb.Type} object which represents a
   1546 @code{const}-qualified variant of this type.
   1547 @end defun
   1548 
   1549 @defun Type.volatile ()
   1550 Return a new @code{gdb.Type} object which represents a
   1551 @code{volatile}-qualified variant of this type.
   1552 @end defun
   1553 
   1554 @defun Type.unqualified ()
   1555 Return a new @code{gdb.Type} object which represents an unqualified
   1556 variant of this type.  That is, the result is neither @code{const} nor
   1557 @code{volatile}.
   1558 @end defun
   1559 
   1560 @defun Type.range ()
   1561 Return a Python @code{Tuple} object that contains two elements: the
   1562 low bound of the argument type and the high bound of that type.  If
   1563 the type does not have a range, @value{GDBN} will raise a
   1564 @code{gdb.error} exception (@pxref{Exception Handling}).
   1565 @end defun
   1566 
   1567 @defun Type.reference ()
   1568 Return a new @code{gdb.Type} object which represents a reference to this
   1569 type.
   1570 @end defun
   1571 
   1572 @defun Type.pointer ()
   1573 Return a new @code{gdb.Type} object which represents a pointer to this
   1574 type.
   1575 @end defun
   1576 
   1577 @defun Type.strip_typedefs ()
   1578 Return a new @code{gdb.Type} that represents the real type,
   1579 after removing all layers of typedefs.
   1580 @end defun
   1581 
   1582 @defun Type.target ()
   1583 Return a new @code{gdb.Type} object which represents the target type
   1584 of this type.
   1585 
   1586 For a pointer type, the target type is the type of the pointed-to
   1587 object.  For an array type (meaning C-like arrays), the target type is
   1588 the type of the elements of the array.  For a function or method type,
   1589 the target type is the type of the return value.  For a complex type,
   1590 the target type is the type of the elements.  For a typedef, the
   1591 target type is the aliased type.
   1592 
   1593 If the type does not have a target, this method will throw an
   1594 exception.
   1595 @end defun
   1596 
   1597 @defun Type.template_argument (n @r{[}, block@r{]})
   1598 If this @code{gdb.Type} is an instantiation of a template, this will
   1599 return a new @code{gdb.Value} or @code{gdb.Type} which represents the
   1600 value of the @var{n}th template argument (indexed starting at 0).
   1601 
   1602 If this @code{gdb.Type} is not a template type, or if the type has fewer
   1603 than @var{n} template arguments, this will throw an exception.
   1604 Ordinarily, only C@t{++} code will have template types.
   1605 
   1606 If @var{block} is given, then @var{name} is looked up in that scope.
   1607 Otherwise, it is searched for globally.
   1608 @end defun
   1609 
   1610 @defun Type.optimized_out ()
   1611 Return @code{gdb.Value} instance of this type whose value is optimized
   1612 out.  This allows a frame decorator to indicate that the value of an
   1613 argument or a local variable is not known.
   1614 @end defun
   1615 
   1616 Each type has a code, which indicates what category this type falls
   1617 into.  The available type categories are represented by constants
   1618 defined in the @code{gdb} module:
   1619 
   1620 @vtable @code
   1621 @vindex TYPE_CODE_PTR
   1622 @item gdb.TYPE_CODE_PTR
   1623 The type is a pointer.
   1624 
   1625 @vindex TYPE_CODE_ARRAY
   1626 @item gdb.TYPE_CODE_ARRAY
   1627 The type is an array.
   1628 
   1629 @vindex TYPE_CODE_STRUCT
   1630 @item gdb.TYPE_CODE_STRUCT
   1631 The type is a structure.
   1632 
   1633 @vindex TYPE_CODE_UNION
   1634 @item gdb.TYPE_CODE_UNION
   1635 The type is a union.
   1636 
   1637 @vindex TYPE_CODE_ENUM
   1638 @item gdb.TYPE_CODE_ENUM
   1639 The type is an enum.
   1640 
   1641 @vindex TYPE_CODE_FLAGS
   1642 @item gdb.TYPE_CODE_FLAGS
   1643 A bit flags type, used for things such as status registers.
   1644 
   1645 @vindex TYPE_CODE_FUNC
   1646 @item gdb.TYPE_CODE_FUNC
   1647 The type is a function.
   1648 
   1649 @vindex TYPE_CODE_INT
   1650 @item gdb.TYPE_CODE_INT
   1651 The type is an integer type.
   1652 
   1653 @vindex TYPE_CODE_FLT
   1654 @item gdb.TYPE_CODE_FLT
   1655 A floating point type.
   1656 
   1657 @vindex TYPE_CODE_VOID
   1658 @item gdb.TYPE_CODE_VOID
   1659 The special type @code{void}.
   1660 
   1661 @vindex TYPE_CODE_SET
   1662 @item gdb.TYPE_CODE_SET
   1663 A Pascal set type.
   1664 
   1665 @vindex TYPE_CODE_RANGE
   1666 @item gdb.TYPE_CODE_RANGE
   1667 A range type, that is, an integer type with bounds.
   1668 
   1669 @vindex TYPE_CODE_STRING
   1670 @item gdb.TYPE_CODE_STRING
   1671 A string type.  Note that this is only used for certain languages with
   1672 language-defined string types; C strings are not represented this way.
   1673 
   1674 @vindex TYPE_CODE_BITSTRING
   1675 @item gdb.TYPE_CODE_BITSTRING
   1676 A string of bits.  It is deprecated.
   1677 
   1678 @vindex TYPE_CODE_ERROR
   1679 @item gdb.TYPE_CODE_ERROR
   1680 An unknown or erroneous type.
   1681 
   1682 @vindex TYPE_CODE_METHOD
   1683 @item gdb.TYPE_CODE_METHOD
   1684 A method type, as found in C@t{++}.
   1685 
   1686 @vindex TYPE_CODE_METHODPTR
   1687 @item gdb.TYPE_CODE_METHODPTR
   1688 A pointer-to-member-function.
   1689 
   1690 @vindex TYPE_CODE_MEMBERPTR
   1691 @item gdb.TYPE_CODE_MEMBERPTR
   1692 A pointer-to-member.
   1693 
   1694 @vindex TYPE_CODE_REF
   1695 @item gdb.TYPE_CODE_REF
   1696 A reference type.
   1697 
   1698 @vindex TYPE_CODE_RVALUE_REF
   1699 @item gdb.TYPE_CODE_RVALUE_REF
   1700 A C@t{++}11 rvalue reference type.
   1701 
   1702 @vindex TYPE_CODE_CHAR
   1703 @item gdb.TYPE_CODE_CHAR
   1704 A character type.
   1705 
   1706 @vindex TYPE_CODE_BOOL
   1707 @item gdb.TYPE_CODE_BOOL
   1708 A boolean type.
   1709 
   1710 @vindex TYPE_CODE_COMPLEX
   1711 @item gdb.TYPE_CODE_COMPLEX
   1712 A complex float type.
   1713 
   1714 @vindex TYPE_CODE_TYPEDEF
   1715 @item gdb.TYPE_CODE_TYPEDEF
   1716 A typedef to some other type.
   1717 
   1718 @vindex TYPE_CODE_NAMESPACE
   1719 @item gdb.TYPE_CODE_NAMESPACE
   1720 A C@t{++} namespace.
   1721 
   1722 @vindex TYPE_CODE_DECFLOAT
   1723 @item gdb.TYPE_CODE_DECFLOAT
   1724 A decimal floating point type.
   1725 
   1726 @vindex TYPE_CODE_INTERNAL_FUNCTION
   1727 @item gdb.TYPE_CODE_INTERNAL_FUNCTION
   1728 A function internal to @value{GDBN}.  This is the type used to represent
   1729 convenience functions.
   1730 
   1731 @vindex TYPE_CODE_XMETHOD
   1732 @item gdb.TYPE_CODE_XMETHOD
   1733 A method internal to @value{GDBN}.  This is the type used to represent
   1734 xmethods (@pxref{Writing an Xmethod}).
   1735 
   1736 @vindex TYPE_CODE_FIXED_POINT
   1737 @item gdb.TYPE_CODE_FIXED_POINT
   1738 A fixed-point number.
   1739 
   1740 @vindex TYPE_CODE_NAMESPACE
   1741 @item gdb.TYPE_CODE_NAMESPACE
   1742 A Fortran namelist.
   1743 @end vtable
   1744 
   1745 Further support for types is provided in the @code{gdb.types}
   1746 Python module (@pxref{gdb.types}).
   1747 
   1748 @node Pretty Printing API
   1749 @subsubsection Pretty Printing API
   1750 @cindex python pretty printing api
   1751 
   1752 A pretty-printer is just an object that holds a value and implements a
   1753 specific interface, defined here.  An example output is provided
   1754 (@pxref{Pretty Printing}).
   1755 
   1756 Because @value{GDBN} did not document extensibility for
   1757 pretty-printers, by default @value{GDBN} will assume that only the
   1758 basic pretty-printer methods may be available.  The basic methods are
   1759 marked as such, below.
   1760 
   1761 To allow extensibility, @value{GDBN} provides the
   1762 @code{gdb.ValuePrinter} base class.  This class does not provide any
   1763 attributes or behavior, but instead serves as a tag that can be
   1764 recognized by @value{GDBN}.  For such printers, @value{GDBN} reserves
   1765 all attributes starting with a lower-case letter.  That is, in the
   1766 future, @value{GDBN} may add a new method or attribute to the
   1767 pretty-printer protocol, and @code{gdb.ValuePrinter}-based printers
   1768 are expected to handle this gracefully.  A simple way to do this would
   1769 be to use a leading underscore (or two, following the Python
   1770 name-mangling scheme) to any attributes local to the implementation.
   1771 
   1772 @defun pretty_printer.children (self)
   1773 @value{GDBN} will call this method on a pretty-printer to compute the
   1774 children of the pretty-printer's value.
   1775 
   1776 This method must return an object conforming to the Python iterator
   1777 protocol.  Each item returned by the iterator must be a tuple holding
   1778 two elements.  The first element is the ``name'' of the child; the
   1779 second element is the child's value.  The value can be any Python
   1780 object which is convertible to a @value{GDBN} value.
   1781 
   1782 This is a basic method, and is optional.  If it does not exist,
   1783 @value{GDBN} will act as though the value has no children.
   1784 
   1785 For efficiency, the @code{children} method should lazily compute its
   1786 results.  This will let @value{GDBN} read as few elements as
   1787 necessary, for example when various print settings (@pxref{Print
   1788 Settings}) or @code{-var-list-children} (@pxref{GDB/MI Variable
   1789 Objects}) limit the number of elements to be displayed.
   1790 
   1791 Children may be hidden from display based on the value of @samp{set
   1792 print max-depth} (@pxref{Print Settings}).
   1793 @end defun
   1794 
   1795 @defun pretty_printer.display_hint (self)
   1796 The CLI may call this method and use its result to change the
   1797 formatting of a value.  The result will also be supplied to an MI
   1798 consumer as a @samp{displayhint} attribute of the variable being
   1799 printed.
   1800 
   1801 This is a basic method, and is optional.  If it does exist, this
   1802 method must return a string or the special value @code{None}.
   1803 
   1804 Some display hints are predefined by @value{GDBN}:
   1805 
   1806 @table @samp
   1807 @item array
   1808 Indicate that the object being printed is ``array-like''.  The CLI
   1809 uses this to respect parameters such as @code{set print elements} and
   1810 @code{set print array}.
   1811 
   1812 @item map
   1813 Indicate that the object being printed is ``map-like'', and that the
   1814 children of this value can be assumed to alternate between keys and
   1815 values.
   1816 
   1817 @item string
   1818 Indicate that the object being printed is ``string-like''.  If the
   1819 printer's @code{to_string} method returns a Python string of some
   1820 kind, then @value{GDBN} will call its internal language-specific
   1821 string-printing function to format the string.  For the CLI this means
   1822 adding quotation marks, possibly escaping some characters, respecting
   1823 @code{set print elements}, and the like.
   1824 @end table
   1825 
   1826 The special value @code{None} causes @value{GDBN} to apply the default
   1827 display rules.
   1828 @end defun
   1829 
   1830 @defun pretty_printer.to_string (self)
   1831 @value{GDBN} will call this method to display the string
   1832 representation of the value passed to the object's constructor.
   1833 
   1834 This is a basic method, and is optional.
   1835 
   1836 When printing from the CLI, if the @code{to_string} method exists,
   1837 then @value{GDBN} will prepend its result to the values returned by
   1838 @code{children}.  Exactly how this formatting is done is dependent on
   1839 the display hint, and may change as more hints are added.  Also,
   1840 depending on the print settings (@pxref{Print Settings}), the CLI may
   1841 print just the result of @code{to_string} in a stack trace, omitting
   1842 the result of @code{children}.
   1843 
   1844 If this method returns a string, it is printed verbatim.
   1845 
   1846 Otherwise, if this method returns an instance of @code{gdb.Value},
   1847 then @value{GDBN} prints this value.  This may result in a call to
   1848 another pretty-printer.
   1849 
   1850 If instead the method returns a Python value which is convertible to a
   1851 @code{gdb.Value}, then @value{GDBN} performs the conversion and prints
   1852 the resulting value.  Again, this may result in a call to another
   1853 pretty-printer.  Python scalars (integers, floats, and booleans) and
   1854 strings are convertible to @code{gdb.Value}; other types are not.
   1855 
   1856 Finally, if this method returns @code{None} then no further operations
   1857 are performed in this method and nothing is printed.
   1858 
   1859 If the result is not one of these types, an exception is raised.
   1860 @end defun
   1861 
   1862 @defun pretty_printer.num_children ()
   1863 This is not a basic method, so @value{GDBN} will only ever call it for
   1864 objects derived from @code{gdb.ValuePrinter}.
   1865 
   1866 If available, this method should return the number of children.
   1867 @code{None} may be returned if the number can't readily be computed.
   1868 @end defun
   1869 
   1870 @defun pretty_printer.child (n)
   1871 This is not a basic method, so @value{GDBN} will only ever call it for
   1872 objects derived from @code{gdb.ValuePrinter}.
   1873 
   1874 If available, this method should return the child item (that is, a
   1875 tuple holding the name and value of this child) indicated by @var{n}.
   1876 Indices start at zero.
   1877 @end defun
   1878 
   1879 @value{GDBN} provides a function which can be used to look up the
   1880 default pretty-printer for a @code{gdb.Value}:
   1881 
   1882 @defun gdb.default_visualizer (value)
   1883 This function takes a @code{gdb.Value} object as an argument.  If a
   1884 pretty-printer for this value exists, then it is returned.  If no such
   1885 printer exists, then this returns @code{None}.
   1886 @end defun
   1887 
   1888 Normally, a pretty-printer can respect the user's print settings
   1889 (including temporarily applied settings, such as @samp{/x}) simply by
   1890 calling @code{Value.format_string} (@pxref{Values From Inferior}).
   1891 However, these settings can also be queried directly:
   1892 
   1893 @defun gdb.print_options ()
   1894 Return a dictionary whose keys are the valid keywords that can be
   1895 given to @code{Value.format_string}, and whose values are the user's
   1896 settings.  During a @code{print} or other operation, the values will
   1897 reflect any flags that are temporarily in effect.
   1898 
   1899 @smallexample
   1900 (gdb) python print (gdb.print_options ()['max_elements'])
   1901 200
   1902 @end smallexample
   1903 @end defun
   1904 
   1905 @node Selecting Pretty-Printers
   1906 @subsubsection Selecting Pretty-Printers
   1907 @cindex selecting python pretty-printers
   1908 
   1909 @value{GDBN} provides several ways to register a pretty-printer:
   1910 globally, per program space, and per objfile.  When choosing how to
   1911 register your pretty-printer, a good rule is to register it with the
   1912 smallest scope possible: that is prefer a specific objfile first, then
   1913 a program space, and only register a printer globally as a last
   1914 resort.
   1915 
   1916 @defvar gdb.pretty_printers
   1917 The Python list @code{gdb.pretty_printers} contains an array of
   1918 functions or callable objects that have been registered via addition
   1919 as a pretty-printer.  Printers in this list are called @code{global}
   1920 printers, they're available when debugging all inferiors.
   1921 @end defvar
   1922 
   1923 Each @code{gdb.Progspace} contains a @code{pretty_printers} attribute.
   1924 Each @code{gdb.Objfile} also contains a @code{pretty_printers}
   1925 attribute.
   1926 
   1927 Each function on these lists is passed a single @code{gdb.Value}
   1928 argument and should return a pretty-printer object conforming to the
   1929 interface definition above (@pxref{Pretty Printing API}).  If a function
   1930 cannot create a pretty-printer for the value, it should return
   1931 @code{None}.
   1932 
   1933 @value{GDBN} first checks the @code{pretty_printers} attribute of each
   1934 @code{gdb.Objfile} in the current program space and iteratively calls
   1935 each enabled lookup routine in the list for that @code{gdb.Objfile}
   1936 until it receives a pretty-printer object.
   1937 If no pretty-printer is found in the objfile lists, @value{GDBN} then
   1938 searches the pretty-printer list of the current program space,
   1939 calling each enabled function until an object is returned.
   1940 After these lists have been exhausted, it tries the global
   1941 @code{gdb.pretty_printers} list, again calling each enabled function until an
   1942 object is returned.
   1943 
   1944 The order in which the objfiles are searched is not specified.  For a
   1945 given list, functions are always invoked from the head of the list,
   1946 and iterated over sequentially until the end of the list, or a printer
   1947 object is returned.
   1948 
   1949 For various reasons a pretty-printer may not work.
   1950 For example, the underlying data structure may have changed and
   1951 the pretty-printer is out of date.
   1952 
   1953 The consequences of a broken pretty-printer are severe enough that
   1954 @value{GDBN} provides support for enabling and disabling individual
   1955 printers.  For example, if @code{print frame-arguments} is on,
   1956 a backtrace can become highly illegible if any argument is printed
   1957 with a broken printer.
   1958 
   1959 Pretty-printers are enabled and disabled by attaching an @code{enabled}
   1960 attribute to the registered function or callable object.  If this attribute
   1961 is present and its value is @code{False}, the printer is disabled, otherwise
   1962 the printer is enabled.
   1963 
   1964 @node Writing a Pretty-Printer
   1965 @subsubsection Writing a Pretty-Printer
   1966 @cindex writing a pretty-printer
   1967 
   1968 A pretty-printer consists of two parts: a lookup function to detect
   1969 if the type is supported, and the printer itself.
   1970 
   1971 Here is an example showing how a @code{std::string} printer might be
   1972 written.  @xref{Pretty Printing API}, for details on the API this class
   1973 must provide.  Note that this example uses the @code{gdb.ValuePrinter}
   1974 base class, and is careful to use a leading underscore for its local
   1975 state.
   1976 
   1977 @smallexample
   1978 class StdStringPrinter(gdb.ValuePrinter):
   1979     "Print a std::string"
   1980 
   1981     def __init__(self, val):
   1982         self.__val = val
   1983 
   1984     def to_string(self):
   1985         return self.__val['_M_dataplus']['_M_p']
   1986 
   1987     def display_hint(self):
   1988         return 'string'
   1989 @end smallexample
   1990 
   1991 And here is an example showing how a lookup function for the printer
   1992 example above might be written.
   1993 
   1994 @smallexample
   1995 def str_lookup_function(val):
   1996     lookup_tag = val.type.tag
   1997     if lookup_tag is None:
   1998         return None
   1999     regex = re.compile("^std::basic_string<char,.*>$")
   2000     if regex.match(lookup_tag):
   2001         return StdStringPrinter(val)
   2002     return None
   2003 @end smallexample
   2004 
   2005 The example lookup function extracts the value's type, and attempts to
   2006 match it to a type that it can pretty-print.  If it is a type the
   2007 printer can pretty-print, it will return a printer object.  If not, it
   2008 returns @code{None}.
   2009 
   2010 We recommend that you put your core pretty-printers into a Python
   2011 package.  If your pretty-printers are for use with a library, we
   2012 further recommend embedding a version number into the package name.
   2013 This practice will enable @value{GDBN} to load multiple versions of
   2014 your pretty-printers at the same time, because they will have
   2015 different names.
   2016 
   2017 You should write auto-loaded code (@pxref{Python Auto-loading}) such that it
   2018 can be evaluated multiple times without changing its meaning.  An
   2019 ideal auto-load file will consist solely of @code{import}s of your
   2020 printer modules, followed by a call to a register pretty-printers with
   2021 the current objfile.
   2022 
   2023 Taken as a whole, this approach will scale nicely to multiple
   2024 inferiors, each potentially using a different library version.
   2025 Embedding a version number in the Python package name will ensure that
   2026 @value{GDBN} is able to load both sets of printers simultaneously.
   2027 Then, because the search for pretty-printers is done by objfile, and
   2028 because your auto-loaded code took care to register your library's
   2029 printers with a specific objfile, @value{GDBN} will find the correct
   2030 printers for the specific version of the library used by each
   2031 inferior.
   2032 
   2033 To continue the @code{std::string} example (@pxref{Pretty Printing API}),
   2034 this code might appear in @code{gdb.libstdcxx.v6}:
   2035 
   2036 @smallexample
   2037 def register_printers(objfile):
   2038     objfile.pretty_printers.append(str_lookup_function)
   2039 @end smallexample
   2040 
   2041 @noindent
   2042 And then the corresponding contents of the auto-load file would be:
   2043 
   2044 @smallexample
   2045 import gdb.libstdcxx.v6
   2046 gdb.libstdcxx.v6.register_printers(gdb.current_objfile())
   2047 @end smallexample
   2048 
   2049 The previous example illustrates a basic pretty-printer.
   2050 There are a few things that can be improved on.
   2051 The printer doesn't have a name, making it hard to identify in a
   2052 list of installed printers.  The lookup function has a name, but
   2053 lookup functions can have arbitrary, even identical, names.
   2054 
   2055 Second, the printer only handles one type, whereas a library typically has
   2056 several types.  One could install a lookup function for each desired type
   2057 in the library, but one could also have a single lookup function recognize
   2058 several types.  The latter is the conventional way this is handled.
   2059 If a pretty-printer can handle multiple data types, then its
   2060 @dfn{subprinters} are the printers for the individual data types.
   2061 
   2062 The @code{gdb.printing} module provides a formal way of solving these
   2063 problems (@pxref{gdb.printing}).
   2064 Here is another example that handles multiple types.
   2065 
   2066 These are the types we are going to pretty-print:
   2067 
   2068 @smallexample
   2069 struct foo @{ int a, b; @};
   2070 struct bar @{ struct foo x, y; @};
   2071 @end smallexample
   2072 
   2073 Here are the printers:
   2074 
   2075 @smallexample
   2076 class fooPrinter(gdb.ValuePrinter):
   2077     """Print a foo object."""
   2078 
   2079     def __init__(self, val):
   2080         self.__val = val
   2081 
   2082     def to_string(self):
   2083         return ("a=<" + str(self.__val["a"]) +
   2084                 "> b=<" + str(self.__val["b"]) + ">")
   2085 
   2086 class barPrinter(gdb.ValuePrinter):
   2087     """Print a bar object."""
   2088 
   2089     def __init__(self, val):
   2090         self.__val = val
   2091 
   2092     def to_string(self):
   2093         return ("x=<" + str(self.__val["x"]) +
   2094                 "> y=<" + str(self.__val["y"]) + ">")
   2095 @end smallexample
   2096 
   2097 This example doesn't need a lookup function, that is handled by the
   2098 @code{gdb.printing} module.  Instead a function is provided to build up
   2099 the object that handles the lookup.
   2100 
   2101 @smallexample
   2102 import gdb.printing
   2103 
   2104 def build_pretty_printer():
   2105     pp = gdb.printing.RegexpCollectionPrettyPrinter(
   2106         "my_library")
   2107     pp.add_printer('foo', '^foo$', fooPrinter)
   2108     pp.add_printer('bar', '^bar$', barPrinter)
   2109     return pp
   2110 @end smallexample
   2111 
   2112 And here is the autoload support:
   2113 
   2114 @smallexample
   2115 import gdb.printing
   2116 import my_library
   2117 gdb.printing.register_pretty_printer(
   2118     gdb.current_objfile(),
   2119     my_library.build_pretty_printer())
   2120 @end smallexample
   2121 
   2122 Finally, when this printer is loaded into @value{GDBN}, here is the
   2123 corresponding output of @samp{info pretty-printer}:
   2124 
   2125 @smallexample
   2126 (gdb) info pretty-printer
   2127 my_library.so:
   2128   my_library
   2129     foo
   2130     bar
   2131 @end smallexample
   2132 
   2133 @node Type Printing API
   2134 @subsubsection Type Printing API
   2135 @cindex type printing API for Python
   2136 
   2137 @value{GDBN} provides a way for Python code to customize type display.
   2138 This is mainly useful for substituting canonical typedef names for
   2139 types.
   2140 
   2141 @cindex type printer
   2142 A @dfn{type printer} is just a Python object conforming to a certain
   2143 protocol.  A simple base class implementing the protocol is provided;
   2144 see @ref{gdb.types}.  A type printer must supply at least:
   2145 
   2146 @defivar type_printer enabled
   2147 A boolean which is True if the printer is enabled, and False
   2148 otherwise.  This is manipulated by the @code{enable type-printer}
   2149 and @code{disable type-printer} commands.
   2150 @end defivar
   2151 
   2152 @defivar type_printer name
   2153 The name of the type printer.  This must be a string.  This is used by
   2154 the @code{enable type-printer} and @code{disable type-printer}
   2155 commands.
   2156 @end defivar
   2157 
   2158 @defmethod type_printer instantiate (self)
   2159 This is called by @value{GDBN} at the start of type-printing.  It is
   2160 only called if the type printer is enabled.  This method must return a
   2161 new object that supplies a @code{recognize} method, as described below.
   2162 @end defmethod
   2163 
   2164 
   2165 When displaying a type, say via the @code{ptype} command, @value{GDBN}
   2166 will compute a list of type recognizers.  This is done by iterating
   2167 first over the per-objfile type printers (@pxref{Objfiles In Python}),
   2168 followed by the per-progspace type printers (@pxref{Progspaces In
   2169 Python}), and finally the global type printers.
   2170 
   2171 @value{GDBN} will call the @code{instantiate} method of each enabled
   2172 type printer.  If this method returns @code{None}, then the result is
   2173 ignored; otherwise, it is appended to the list of recognizers.
   2174 
   2175 Then, when @value{GDBN} is going to display a type name, it iterates
   2176 over the list of recognizers.  For each one, it calls the recognition
   2177 function, stopping if the function returns a non-@code{None} value.
   2178 The recognition function is defined as:
   2179 
   2180 @defmethod type_recognizer recognize (self, type)
   2181 If @var{type} is not recognized, return @code{None}.  Otherwise,
   2182 return a string which is to be printed as the name of @var{type}.
   2183 The @var{type} argument will be an instance of @code{gdb.Type}
   2184 (@pxref{Types In Python}).
   2185 @end defmethod
   2186 
   2187 @value{GDBN} uses this two-pass approach so that type printers can
   2188 efficiently cache information without holding on to it too long.  For
   2189 example, it can be convenient to look up type information in a type
   2190 printer and hold it for a recognizer's lifetime; if a single pass were
   2191 done then type printers would have to make use of the event system in
   2192 order to avoid holding information that could become stale as the
   2193 inferior changed.
   2194 
   2195 @node Frame Filter API
   2196 @subsubsection Filtering Frames
   2197 @cindex frame filters api
   2198 
   2199 Frame filters are Python objects that manipulate the visibility of a
   2200 frame or frames when a backtrace (@pxref{Backtrace}) is printed by
   2201 @value{GDBN}.
   2202 
   2203 Only commands that print a backtrace, or, in the case of @sc{gdb/mi}
   2204 commands (@pxref{GDB/MI}), those that return a collection of frames
   2205 are affected.  The commands that work with frame filters are:
   2206 
   2207 @code{backtrace} (@pxref{backtrace-command,, The backtrace command}),
   2208 @code{-stack-list-frames}
   2209 (@pxref{-stack-list-frames,, The -stack-list-frames command}),
   2210 @code{-stack-list-variables} (@pxref{-stack-list-variables,, The
   2211 -stack-list-variables command}), @code{-stack-list-arguments}
   2212 @pxref{-stack-list-arguments,, The -stack-list-arguments command}) and
   2213 @code{-stack-list-locals} (@pxref{-stack-list-locals,, The
   2214 -stack-list-locals command}).
   2215 
   2216 A frame filter works by taking an iterator as an argument, applying
   2217 actions to the contents of that iterator, and returning another
   2218 iterator (or, possibly, the same iterator it was provided in the case
   2219 where the filter does not perform any operations).  Typically, frame
   2220 filters utilize tools such as the Python's @code{itertools} module to
   2221 work with and create new iterators from the source iterator.
   2222 Regardless of how a filter chooses to apply actions, it must not alter
   2223 the underlying @value{GDBN} frame or frames, or attempt to alter the
   2224 call-stack within @value{GDBN}.  This preserves data integrity within
   2225 @value{GDBN}.  Frame filters are executed on a priority basis and care
   2226 should be taken that some frame filters may have been executed before,
   2227 and that some frame filters will be executed after.
   2228 
   2229 An important consideration when designing frame filters, and well
   2230 worth reflecting upon, is that frame filters should avoid unwinding
   2231 the call stack if possible.  Some stacks can run very deep, into the
   2232 tens of thousands in some cases.  To search every frame when a frame
   2233 filter executes may be too expensive at that step.  The frame filter
   2234 cannot know how many frames it has to iterate over, and it may have to
   2235 iterate through them all.  This ends up duplicating effort as
   2236 @value{GDBN} performs this iteration when it prints the frames.  If
   2237 the filter can defer unwinding frames until frame decorators are
   2238 executed, after the last filter has executed, it should.  @xref{Frame
   2239 Decorator API}, for more information on decorators.  Also, there are
   2240 examples for both frame decorators and filters in later chapters.
   2241 @xref{Writing a Frame Filter}, for more information.
   2242 
   2243 The Python dictionary @code{gdb.frame_filters} contains key/object
   2244 pairings that comprise a frame filter.  Frame filters in this
   2245 dictionary are called @code{global} frame filters, and they are
   2246 available when debugging all inferiors.  These frame filters must
   2247 register with the dictionary directly.  In addition to the
   2248 @code{global} dictionary, there are other dictionaries that are loaded
   2249 with different inferiors via auto-loading (@pxref{Python
   2250 Auto-loading}).  The two other areas where frame filter dictionaries
   2251 can be found are: @code{gdb.Progspace} which contains a
   2252 @code{frame_filters} dictionary attribute, and each @code{gdb.Objfile}
   2253 object which also contains a @code{frame_filters} dictionary
   2254 attribute.
   2255 
   2256 When a command is executed from @value{GDBN} that is compatible with
   2257 frame filters, @value{GDBN} combines the @code{global},
   2258 @code{gdb.Progspace} and all @code{gdb.Objfile} dictionaries currently
   2259 loaded.  All of the @code{gdb.Objfile} dictionaries are combined, as
   2260 several frames, and thus several object files, might be in use.
   2261 @value{GDBN} then prunes any frame filter whose @code{enabled}
   2262 attribute is @code{False}.  This pruned list is then sorted according
   2263 to the @code{priority} attribute in each filter.
   2264 
   2265 Once the dictionaries are combined, pruned and sorted, @value{GDBN}
   2266 creates an iterator which wraps each frame in the call stack in a
   2267 @code{FrameDecorator} object, and calls each filter in order.  The
   2268 output from the previous filter will always be the input to the next
   2269 filter, and so on.
   2270 
   2271 Frame filters have a mandatory interface which each frame filter must
   2272 implement, defined here:
   2273 
   2274 @defun FrameFilter.filter (iterator)
   2275 @value{GDBN} will call this method on a frame filter when it has
   2276 reached the order in the priority list for that filter.
   2277 
   2278 For example, if there are four frame filters:
   2279 
   2280 @smallexample
   2281 Name         Priority
   2282 
   2283 Filter1      5
   2284 Filter2      10
   2285 Filter3      100
   2286 Filter4      1
   2287 @end smallexample
   2288 
   2289 The order that the frame filters will be called is:
   2290 
   2291 @smallexample
   2292 Filter3 -> Filter2 -> Filter1 -> Filter4
   2293 @end smallexample
   2294 
   2295 Note that the output from @code{Filter3} is passed to the input of
   2296 @code{Filter2}, and so on.
   2297 
   2298 This @code{filter} method is passed a Python iterator.  This iterator
   2299 contains a sequence of frame decorators that wrap each
   2300 @code{gdb.Frame}, or a frame decorator that wraps another frame
   2301 decorator.  The first filter that is executed in the sequence of frame
   2302 filters will receive an iterator entirely comprised of default
   2303 @code{FrameDecorator} objects.  However, after each frame filter is
   2304 executed, the previous frame filter may have wrapped some or all of
   2305 the frame decorators with their own frame decorator.  As frame
   2306 decorators must also conform to a mandatory interface, these
   2307 decorators can be assumed to act in a uniform manner (@pxref{Frame
   2308 Decorator API}).
   2309 
   2310 This method must return an object conforming to the Python iterator
   2311 protocol.  Each item in the iterator must be an object conforming to
   2312 the frame decorator interface.  If a frame filter does not wish to
   2313 perform any operations on this iterator, it should return that
   2314 iterator untouched.
   2315 
   2316 This method is not optional.  If it does not exist, @value{GDBN} will
   2317 raise and print an error.
   2318 @end defun
   2319 
   2320 @defvar FrameFilter.name
   2321 The @code{name} attribute must be Python string which contains the
   2322 name of the filter displayed by @value{GDBN} (@pxref{Frame Filter
   2323 Management}).  This attribute may contain any combination of letters
   2324 or numbers.  Care should be taken to ensure that it is unique.  This
   2325 attribute is mandatory.
   2326 @end defvar
   2327 
   2328 @defvar FrameFilter.enabled
   2329 The @code{enabled} attribute must be Python boolean.  This attribute
   2330 indicates to @value{GDBN} whether the frame filter is enabled, and
   2331 should be considered when frame filters are executed.  If
   2332 @code{enabled} is @code{True}, then the frame filter will be executed
   2333 when any of the backtrace commands detailed earlier in this chapter
   2334 are executed.  If @code{enabled} is @code{False}, then the frame
   2335 filter will not be executed.  This attribute is mandatory.
   2336 @end defvar
   2337 
   2338 @defvar FrameFilter.priority
   2339 The @code{priority} attribute must be Python integer.  This attribute
   2340 controls the order of execution in relation to other frame filters.
   2341 There are no imposed limits on the range of @code{priority} other than
   2342 it must be a valid integer.  The higher the @code{priority} attribute,
   2343 the sooner the frame filter will be executed in relation to other
   2344 frame filters.  Although @code{priority} can be negative, it is
   2345 recommended practice to assume zero is the lowest priority that a
   2346 frame filter can be assigned.  Frame filters that have the same
   2347 priority are executed in unsorted order in that priority slot.  This
   2348 attribute is mandatory.  100 is a good default priority.
   2349 @end defvar
   2350 
   2351 @node Frame Decorator API
   2352 @subsubsection Decorating Frames
   2353 @cindex frame decorator api
   2354 
   2355 Frame decorators are sister objects to frame filters (@pxref{Frame
   2356 Filter API}).  Frame decorators are applied by a frame filter and can
   2357 only be used in conjunction with frame filters.
   2358 
   2359 The purpose of a frame decorator is to customize the printed content
   2360 of each @code{gdb.Frame} in commands where frame filters are executed.
   2361 This concept is called decorating a frame.  Frame decorators decorate
   2362 a @code{gdb.Frame} with Python code contained within each API call.
   2363 This separates the actual data contained in a @code{gdb.Frame} from
   2364 the decorated data produced by a frame decorator.  This abstraction is
   2365 necessary to maintain integrity of the data contained in each
   2366 @code{gdb.Frame}.
   2367 
   2368 Frame decorators have a mandatory interface, defined below.
   2369 
   2370 @value{GDBN} already contains a frame decorator called
   2371 @code{FrameDecorator}.  This contains substantial amounts of
   2372 boilerplate code to decorate the content of a @code{gdb.Frame}.  It is
   2373 recommended that other frame decorators inherit and extend this
   2374 object, and only to override the methods needed.
   2375 
   2376 @tindex gdb.FrameDecorator
   2377 @code{FrameDecorator} is defined in the Python module
   2378 @code{gdb.FrameDecorator}, so your code can import it like:
   2379 @smallexample
   2380 from gdb.FrameDecorator import FrameDecorator
   2381 @end smallexample
   2382 
   2383 @defun FrameDecorator.elided (self)
   2384 
   2385 The @code{elided} method groups frames together in a hierarchical
   2386 system.  An example would be an interpreter, where multiple low-level
   2387 frames make up a single call in the interpreted language.  In this
   2388 example, the frame filter would elide the low-level frames and present
   2389 a single high-level frame, representing the call in the interpreted
   2390 language, to the user.
   2391 
   2392 The @code{elided} function must return an iterable and this iterable
   2393 must contain the frames that are being elided wrapped in a suitable
   2394 frame decorator.  If no frames are being elided this function may
   2395 return an empty iterable, or @code{None}.  Elided frames are indented
   2396 from normal frames in a @code{CLI} backtrace, or in the case of
   2397 @sc{gdb/mi}, are placed in the @code{children} field of the eliding
   2398 frame.
   2399 
   2400 It is the frame filter's task to also filter out the elided frames from
   2401 the source iterator.  This will avoid printing the frame twice.
   2402 @end defun
   2403 
   2404 @defun FrameDecorator.function (self)
   2405 
   2406 This method returns the name of the function in the frame that is to
   2407 be printed.
   2408 
   2409 This method must return a Python string describing the function, or
   2410 @code{None}.
   2411 
   2412 If this function returns @code{None}, @value{GDBN} will not print any
   2413 data for this field.
   2414 @end defun
   2415 
   2416 @defun FrameDecorator.address (self)
   2417 
   2418 This method returns the address of the frame that is to be printed.
   2419 
   2420 This method must return a Python numeric integer type of sufficient
   2421 size to describe the address of the frame, or @code{None}.
   2422 
   2423 If this function returns a @code{None}, @value{GDBN} will not print
   2424 any data for this field.
   2425 @end defun
   2426 
   2427 @defun FrameDecorator.filename (self)
   2428 
   2429 This method returns the filename and path associated with this frame.
   2430 
   2431 This method must return a Python string containing the filename and
   2432 the path to the object file backing the frame, or @code{None}.
   2433 
   2434 If this function returns a @code{None}, @value{GDBN} will not print
   2435 any data for this field.
   2436 @end defun
   2437 
   2438 @defun FrameDecorator.line (self):
   2439 
   2440 This method returns the line number associated with the current
   2441 position within the function addressed by this frame.
   2442 
   2443 This method must return a Python integer type, or @code{None}.
   2444 
   2445 If this function returns a @code{None}, @value{GDBN} will not print
   2446 any data for this field.
   2447 @end defun
   2448 
   2449 @defun FrameDecorator.frame_args (self)
   2450 @anchor{frame_args}
   2451 
   2452 This method must return an iterable, or @code{None}.  Returning an
   2453 empty iterable, or @code{None} means frame arguments will not be
   2454 printed for this frame.  This iterable must contain objects that
   2455 implement two methods, described here.
   2456 
   2457 This object must implement a @code{symbol} method which takes a
   2458 single @code{self} parameter and must return a @code{gdb.Symbol}
   2459 (@pxref{Symbols In Python}), or a Python string.  The object must also
   2460 implement a @code{value} method which takes a single @code{self}
   2461 parameter and must return a @code{gdb.Value} (@pxref{Values From
   2462 Inferior}), a Python value, or @code{None}.  If the @code{value}
   2463 method returns @code{None}, and the @code{argument} method returns a
   2464 @code{gdb.Symbol}, @value{GDBN} will look-up and print the value of
   2465 the @code{gdb.Symbol} automatically.
   2466 
   2467 A brief example:
   2468 
   2469 @smallexample
   2470 class SymValueWrapper():
   2471 
   2472     def __init__(self, symbol, value):
   2473         self.sym = symbol
   2474         self.val = value
   2475 
   2476     def value(self):
   2477         return self.val
   2478 
   2479     def symbol(self):
   2480         return self.sym
   2481 
   2482 class SomeFrameDecorator()
   2483 ...
   2484 ...
   2485     def frame_args(self):
   2486         args = []
   2487         try:
   2488             block = self.inferior_frame.block()
   2489         except:
   2490             return None
   2491 
   2492         # Iterate over all symbols in a block.  Only add
   2493         # symbols that are arguments.
   2494         for sym in block:
   2495             if not sym.is_argument:
   2496                 continue
   2497             args.append(SymValueWrapper(sym,None))
   2498 
   2499         # Add example synthetic argument.
   2500         args.append(SymValueWrapper(``foo'', 42))
   2501 
   2502         return args
   2503 @end smallexample
   2504 @end defun
   2505 
   2506 @defun FrameDecorator.frame_locals (self)
   2507 
   2508 This method must return an iterable or @code{None}.  Returning an
   2509 empty iterable, or @code{None} means frame local arguments will not be
   2510 printed for this frame.
   2511 
   2512 The object interface, the description of the various strategies for
   2513 reading frame locals, and the example are largely similar to those
   2514 described in the @code{frame_args} function, (@pxref{frame_args,,The
   2515 frame filter frame_args function}).  Below is a modified example:
   2516 
   2517 @smallexample
   2518 class SomeFrameDecorator()
   2519 ...
   2520 ...
   2521     def frame_locals(self):
   2522         vars = []
   2523         try:
   2524             block = self.inferior_frame.block()
   2525         except:
   2526             return None
   2527 
   2528         # Iterate over all symbols in a block.  Add all
   2529         # symbols, except arguments.
   2530         for sym in block:
   2531             if sym.is_argument:
   2532                 continue
   2533             vars.append(SymValueWrapper(sym,None))
   2534 
   2535         # Add an example of a synthetic local variable.
   2536         vars.append(SymValueWrapper(``bar'', 99))
   2537 
   2538         return vars
   2539 @end smallexample
   2540 @end defun
   2541 
   2542 @defun FrameDecorator.inferior_frame (self):
   2543 
   2544 This method must return the underlying @code{gdb.Frame} that this
   2545 frame decorator is decorating.  @value{GDBN} requires the underlying
   2546 frame for internal frame information to determine how to print certain
   2547 values when printing a frame.
   2548 @end defun
   2549 
   2550 @node Writing a Frame Filter
   2551 @subsubsection Writing a Frame Filter
   2552 @cindex writing a frame filter
   2553 
   2554 There are three basic elements that a frame filter must implement: it
   2555 must correctly implement the documented interface (@pxref{Frame Filter
   2556 API}), it must register itself with @value{GDBN}, and finally, it must
   2557 decide if it is to work on the data provided by @value{GDBN}.  In all
   2558 cases, whether it works on the iterator or not, each frame filter must
   2559 return an iterator.  A bare-bones frame filter follows the pattern in
   2560 the following example.
   2561 
   2562 @smallexample
   2563 import gdb
   2564 
   2565 class FrameFilter():
   2566 
   2567     def __init__(self):
   2568         # Frame filter attribute creation.
   2569         #
   2570         # 'name' is the name of the filter that GDB will display.
   2571         #
   2572         # 'priority' is the priority of the filter relative to other
   2573         # filters.
   2574         #
   2575         # 'enabled' is a boolean that indicates whether this filter is
   2576         # enabled and should be executed.
   2577 
   2578         self.name = "Foo"
   2579         self.priority = 100
   2580         self.enabled = True
   2581 
   2582         # Register this frame filter with the global frame_filters
   2583         # dictionary.
   2584         gdb.frame_filters[self.name] = self
   2585 
   2586     def filter(self, frame_iter):
   2587         # Just return the iterator.
   2588         return frame_iter
   2589 @end smallexample
   2590 
   2591 The frame filter in the example above implements the three
   2592 requirements for all frame filters.  It implements the API, self
   2593 registers, and makes a decision on the iterator (in this case, it just
   2594 returns the iterator untouched).
   2595 
   2596 The first step is attribute creation and assignment, and as shown in
   2597 the comments the filter assigns the following attributes:  @code{name},
   2598 @code{priority} and whether the filter should be enabled with the
   2599 @code{enabled} attribute.
   2600 
   2601 The second step is registering the frame filter with the dictionary or
   2602 dictionaries that the frame filter has interest in.  As shown in the
   2603 comments, this filter just registers itself with the global dictionary
   2604 @code{gdb.frame_filters}.  As noted earlier, @code{gdb.frame_filters}
   2605 is a dictionary that is initialized in the @code{gdb} module when
   2606 @value{GDBN} starts.  What dictionary a filter registers with is an
   2607 important consideration.  Generally, if a filter is specific to a set
   2608 of code, it should be registered either in the @code{objfile} or
   2609 @code{progspace} dictionaries as they are specific to the program
   2610 currently loaded in @value{GDBN}.  The global dictionary is always
   2611 present in @value{GDBN} and is never unloaded.  Any filters registered
   2612 with the global dictionary will exist until @value{GDBN} exits.  To
   2613 avoid filters that may conflict, it is generally better to register
   2614 frame filters against the dictionaries that more closely align with
   2615 the usage of the filter currently in question.  @xref{Python
   2616 Auto-loading}, for further information on auto-loading Python scripts.
   2617 
   2618 @value{GDBN} takes a hands-off approach to frame filter registration,
   2619 therefore it is the frame filter's responsibility to ensure
   2620 registration has occurred, and that any exceptions are handled
   2621 appropriately.  In particular, you may wish to handle exceptions
   2622 relating to Python dictionary key uniqueness.  It is mandatory that
   2623 the dictionary key is the same as frame filter's @code{name}
   2624 attribute.  When a user manages frame filters (@pxref{Frame Filter
   2625 Management}), the names @value{GDBN} will display are those contained
   2626 in the @code{name} attribute.
   2627 
   2628 The final step of this example is the implementation of the
   2629 @code{filter} method.  As shown in the example comments, we define the
   2630 @code{filter} method and note that the method must take an iterator,
   2631 and also must return an iterator.  In this bare-bones example, the
   2632 frame filter is not very useful as it just returns the iterator
   2633 untouched.  However this is a valid operation for frame filters that
   2634 have the @code{enabled} attribute set, but decide not to operate on
   2635 any frames.
   2636 
   2637 In the next example, the frame filter operates on all frames and
   2638 utilizes a frame decorator to perform some work on the frames.
   2639 @xref{Frame Decorator API}, for further information on the frame
   2640 decorator interface.
   2641 
   2642 This example works on inlined frames.  It highlights frames which are
   2643 inlined by tagging them with an ``[inlined]'' tag.  By applying a
   2644 frame decorator to all frames with the Python @code{itertools imap}
   2645 method, the example defers actions to the frame decorator.  Frame
   2646 decorators are only processed when @value{GDBN} prints the backtrace.
   2647 
   2648 This introduces a new decision making topic: whether to perform
   2649 decision making operations at the filtering step, or at the printing
   2650 step.  In this example's approach, it does not perform any filtering
   2651 decisions at the filtering step beyond mapping a frame decorator to
   2652 each frame.  This allows the actual decision making to be performed
   2653 when each frame is printed.  This is an important consideration, and
   2654 well worth reflecting upon when designing a frame filter.  An issue
   2655 that frame filters should avoid is unwinding the stack if possible.
   2656 Some stacks can run very deep, into the tens of thousands in some
   2657 cases.  To search every frame to determine if it is inlined ahead of
   2658 time may be too expensive at the filtering step.  The frame filter
   2659 cannot know how many frames it has to iterate over, and it would have
   2660 to iterate through them all.  This ends up duplicating effort as
   2661 @value{GDBN} performs this iteration when it prints the frames.
   2662 
   2663 In this example decision making can be deferred to the printing step.
   2664 As each frame is printed, the frame decorator can examine each frame
   2665 in turn when @value{GDBN} iterates.  From a performance viewpoint,
   2666 this is the most appropriate decision to make as it avoids duplicating
   2667 the effort that the printing step would undertake anyway.  Also, if
   2668 there are many frame filters unwinding the stack during filtering, it
   2669 can substantially delay the printing of the backtrace which will
   2670 result in large memory usage, and a poor user experience.
   2671 
   2672 @smallexample
   2673 class InlineFilter():
   2674 
   2675     def __init__(self):
   2676         self.name = "InlinedFrameFilter"
   2677         self.priority = 100
   2678         self.enabled = True
   2679         gdb.frame_filters[self.name] = self
   2680 
   2681     def filter(self, frame_iter):
   2682         frame_iter = itertools.imap(InlinedFrameDecorator,
   2683                                     frame_iter)
   2684         return frame_iter
   2685 @end smallexample
   2686 
   2687 This frame filter is somewhat similar to the earlier example, except
   2688 that the @code{filter} method applies a frame decorator object called
   2689 @code{InlinedFrameDecorator} to each element in the iterator.  The
   2690 @code{imap} Python method is light-weight.  It does not proactively
   2691 iterate over the iterator, but rather creates a new iterator which
   2692 wraps the existing one.
   2693 
   2694 Below is the frame decorator for this example.
   2695 
   2696 @smallexample
   2697 class InlinedFrameDecorator(FrameDecorator):
   2698 
   2699     def __init__(self, fobj):
   2700         super(InlinedFrameDecorator, self).__init__(fobj)
   2701 
   2702     def function(self):
   2703         frame = self.inferior_frame()
   2704         name = str(frame.name())
   2705 
   2706         if frame.type() == gdb.INLINE_FRAME:
   2707             name = name + " [inlined]"
   2708 
   2709         return name
   2710 @end smallexample
   2711 
   2712 This frame decorator only defines and overrides the @code{function}
   2713 method.  It lets the supplied @code{FrameDecorator}, which is shipped
   2714 with @value{GDBN}, perform the other work associated with printing
   2715 this frame.
   2716 
   2717 The combination of these two objects create this output from a
   2718 backtrace:
   2719 
   2720 @smallexample
   2721 #0  0x004004e0 in bar () at inline.c:11
   2722 #1  0x00400566 in max [inlined] (b=6, a=12) at inline.c:21
   2723 #2  0x00400566 in main () at inline.c:31
   2724 @end smallexample
   2725 
   2726 So in the case of this example, a frame decorator is applied to all
   2727 frames, regardless of whether they may be inlined or not.  As
   2728 @value{GDBN} iterates over the iterator produced by the frame filters,
   2729 @value{GDBN} executes each frame decorator which then makes a decision
   2730 on what to print in the @code{function} callback.  Using a strategy
   2731 like this is a way to defer decisions on the frame content to printing
   2732 time.
   2733 
   2734 @subheading Eliding Frames
   2735 
   2736 It might be that the above example is not desirable for representing
   2737 inlined frames, and a hierarchical approach may be preferred.  If we
   2738 want to hierarchically represent frames, the @code{elided} frame
   2739 decorator interface might be preferable.
   2740 
   2741 This example approaches the issue with the @code{elided} method.  This
   2742 example is quite long, but very simplistic.  It is out-of-scope for
   2743 this section to write a complete example that comprehensively covers
   2744 all approaches of finding and printing inlined frames.  However, this
   2745 example illustrates the approach an author might use.
   2746 
   2747 This example comprises of three sections.
   2748 
   2749 @smallexample
   2750 class InlineFrameFilter():
   2751 
   2752     def __init__(self):
   2753         self.name = "InlinedFrameFilter"
   2754         self.priority = 100
   2755         self.enabled = True
   2756         gdb.frame_filters[self.name] = self
   2757 
   2758     def filter(self, frame_iter):
   2759         return ElidingInlineIterator(frame_iter)
   2760 @end smallexample
   2761 
   2762 This frame filter is very similar to the other examples.  The only
   2763 difference is this frame filter is wrapping the iterator provided to
   2764 it (@code{frame_iter}) with a custom iterator called
   2765 @code{ElidingInlineIterator}.  This again defers actions to when
   2766 @value{GDBN} prints the backtrace, as the iterator is not traversed
   2767 until printing.
   2768 
   2769 The iterator for this example is as follows.  It is in this section of
   2770 the example where decisions are made on the content of the backtrace.
   2771 
   2772 @smallexample
   2773 class ElidingInlineIterator:
   2774     def __init__(self, ii):
   2775         self.input_iterator = ii
   2776 
   2777     def __iter__(self):
   2778         return self
   2779 
   2780     def next(self):
   2781         frame = next(self.input_iterator)
   2782 
   2783         if frame.inferior_frame().type() != gdb.INLINE_FRAME:
   2784             return frame
   2785 
   2786         try:
   2787             eliding_frame = next(self.input_iterator)
   2788         except StopIteration:
   2789             return frame
   2790         return ElidingFrameDecorator(eliding_frame, [frame])
   2791 @end smallexample
   2792 
   2793 This iterator implements the Python iterator protocol.  When the
   2794 @code{next} function is called (when @value{GDBN} prints each frame),
   2795 the iterator checks if this frame decorator, @code{frame}, is wrapping
   2796 an inlined frame.  If it is not, it returns the existing frame decorator
   2797 untouched.  If it is wrapping an inlined frame, it assumes that the
   2798 inlined frame was contained within the next oldest frame,
   2799 @code{eliding_frame}, which it fetches.  It then creates and returns a
   2800 frame decorator, @code{ElidingFrameDecorator}, which contains both the
   2801 elided frame, and the eliding frame.
   2802 
   2803 @smallexample
   2804 class ElidingInlineDecorator(FrameDecorator):
   2805 
   2806     def __init__(self, frame, elided_frames):
   2807         super(ElidingInlineDecorator, self).__init__(frame)
   2808         self.frame = frame
   2809         self.elided_frames = elided_frames
   2810 
   2811     def elided(self):
   2812         return iter(self.elided_frames)
   2813 @end smallexample
   2814 
   2815 This frame decorator overrides one function and returns the inlined
   2816 frame in the @code{elided} method.  As before it lets
   2817 @code{FrameDecorator} do the rest of the work involved in printing
   2818 this frame.  This produces the following output.
   2819 
   2820 @smallexample
   2821 #0  0x004004e0 in bar () at inline.c:11
   2822 #2  0x00400529 in main () at inline.c:25
   2823     #1  0x00400529 in max (b=6, a=12) at inline.c:15
   2824 @end smallexample
   2825 
   2826 In that output, @code{max} which has been inlined into @code{main} is
   2827 printed hierarchically.  Another approach would be to combine the
   2828 @code{function} method, and the @code{elided} method to both print a
   2829 marker in the inlined frame, and also show the hierarchical
   2830 relationship.
   2831 
   2832 @node Unwinding Frames in Python
   2833 @subsubsection Unwinding Frames in Python
   2834 @cindex unwinding frames in Python
   2835 
   2836 In @value{GDBN} terminology ``unwinding'' is the process of finding
   2837 the previous frame (that is, caller's) from the current one.  An
   2838 unwinder has three methods.  The first one checks if it can handle
   2839 given frame (``sniff'' it).  For the frames it can sniff an unwinder
   2840 provides two additional methods: it can return frame's ID, and it can
   2841 fetch registers from the previous frame.  A running @value{GDBN}
   2842 maintains a list of the unwinders and calls each unwinder's sniffer in
   2843 turn until it finds the one that recognizes the current frame.  There
   2844 is an API to register an unwinder.
   2845 
   2846 The unwinders that come with @value{GDBN} handle standard frames.
   2847 However, mixed language applications (for example, an application
   2848 running Java Virtual Machine) sometimes use frame layouts that cannot
   2849 be handled by the @value{GDBN} unwinders.  You can write Python code
   2850 that can handle such custom frames.
   2851 
   2852 You implement a frame unwinder in Python as a class with which has two
   2853 attributes, @code{name} and @code{enabled}, with obvious meanings, and
   2854 a single method @code{__call__}, which examines a given frame and
   2855 returns an object (an instance of @code{gdb.UnwindInfo class)}
   2856 describing it.  If an unwinder does not recognize a frame, it should
   2857 return @code{None}.  The code in @value{GDBN} that enables writing
   2858 unwinders in Python uses this object to return frame's ID and previous
   2859 frame registers when @value{GDBN} core asks for them.
   2860 
   2861 An unwinder should do as little work as possible.  Some otherwise
   2862 innocuous operations can cause problems (even crashes, as this code is
   2863 not well-hardened yet).  For example, making an inferior call from
   2864 an unwinder is unadvisable, as an inferior call will reset
   2865 @value{GDBN}'s stack unwinding process, potentially causing re-entrant
   2866 unwinding.
   2867 
   2868 @subheading Unwinder Input
   2869 
   2870 An object passed to an unwinder (a @code{gdb.PendingFrame} instance)
   2871 provides a method to read frame's registers:
   2872 
   2873 @defun PendingFrame.read_register (register)
   2874 This method returns the contents of @var{register} in the
   2875 frame as a @code{gdb.Value} object.  For a description of the
   2876 acceptable values of @var{register} see
   2877 @ref{gdbpy_frame_read_register,,Frame.read_register}.  If @var{register}
   2878 does not name a register for the current architecture, this method
   2879 will throw an exception.
   2880 
   2881 Note that this method will always return a @code{gdb.Value} for a
   2882 valid register name.  This does not mean that the value will be valid.
   2883 For example, you may request a register that an earlier unwinder could
   2884 not unwind---the value will be unavailable.  Instead, the
   2885 @code{gdb.Value} returned from this method will be lazy; that is, its
   2886 underlying bits will not be fetched until it is first used.  So,
   2887 attempting to use such a value will cause an exception at the point of
   2888 use.
   2889 
   2890 The type of the returned @code{gdb.Value} depends on the register and
   2891 the architecture.  It is common for registers to have a scalar type,
   2892 like @code{long long}; but many other types are possible, such as
   2893 pointer, pointer-to-function, floating point or vector types.
   2894 @end defun
   2895 
   2896 It also provides a factory method to create a @code{gdb.UnwindInfo}
   2897 instance to be returned to @value{GDBN}:
   2898 
   2899 @anchor{gdb.PendingFrame.create_unwind_info}
   2900 @defun PendingFrame.create_unwind_info (frame_id)
   2901 Returns a new @code{gdb.UnwindInfo} instance identified by given
   2902 @var{frame_id}.  The @var{frame_id} is used internally by @value{GDBN}
   2903 to identify the frames within the current thread's stack.  The
   2904 attributes of @var{frame_id} determine what type of frame is
   2905 created within @value{GDBN}:
   2906 
   2907 @table @code
   2908 @item sp, pc
   2909 The frame is identified by the given stack address and PC.  The stack
   2910 address must be chosen so that it is constant throughout the lifetime
   2911 of the frame, so a typical choice is the value of the stack pointer at
   2912 the start of the function---in the DWARF standard, this would be the
   2913 ``Call Frame Address''.
   2914 
   2915 This is the most common case by far.  The other cases are documented
   2916 for completeness but are only useful in specialized situations.
   2917 
   2918 @item sp, pc, special
   2919 The frame is identified by the stack address, the PC, and a
   2920 ``special'' address.  The special address is used on architectures
   2921 that can have frames that do not change the stack, but which are still
   2922 distinct, for example the IA-64, which has a second stack for
   2923 registers.  Both @var{sp} and @var{special} must be constant
   2924 throughout the lifetime of the frame.
   2925 
   2926 @item sp
   2927 The frame is identified by the stack address only.  Any other stack
   2928 frame with a matching @var{sp} will be considered to match this frame.
   2929 Inside gdb, this is called a ``wild frame''.  You will never need
   2930 this.
   2931 @end table
   2932 
   2933 Each attribute value should either be an instance of @code{gdb.Value}
   2934 or an integer.
   2935 
   2936 A helper class is provided in the @code{gdb.unwinder} module that can
   2937 be used to represent a frame-id
   2938 (@pxref{gdb.unwinder.FrameId}).
   2939 
   2940 @end defun
   2941 
   2942 @defun PendingFrame.architecture ()
   2943 Return the @code{gdb.Architecture} (@pxref{Architectures In Python})
   2944 for this @code{gdb.PendingFrame}.  This represents the architecture of
   2945 the particular frame being unwound.
   2946 @end defun
   2947 
   2948 @defun PendingFrame.level ()
   2949 Return an integer, the stack frame level for this frame.
   2950 @xref{Frames, ,Stack Frames}.
   2951 @end defun
   2952 
   2953 @defun PendingFrame.name ()
   2954 Returns the function name of this pending frame, or @code{None} if it
   2955 can't be obtained.
   2956 @end defun
   2957 
   2958 @defun PendingFrame.is_valid ()
   2959 Returns true if the @code{gdb.PendingFrame} object is valid, false if
   2960 not.  A pending frame object becomes invalid when the call to the
   2961 unwinder, for which the pending frame was created, returns.
   2962 
   2963 All @code{gdb.PendingFrame} methods, except this one, will raise an
   2964 exception if the pending frame object is invalid at the time the
   2965 method is called.
   2966 @end defun
   2967 
   2968 @defun PendingFrame.pc ()
   2969 Returns the pending frame's resume address.
   2970 @end defun
   2971 
   2972 @defun PendingFrame.block ()
   2973 Return the pending frame's code block (@pxref{Blocks In Python}).  If
   2974 the frame does not have a block -- for example, if there is no
   2975 debugging information for the code in question -- then this will raise
   2976 a @code{RuntimeError} exception.
   2977 @end defun
   2978 
   2979 @defun PendingFrame.function ()
   2980 Return the symbol for the function corresponding to this pending frame.
   2981 @xref{Symbols In Python}.
   2982 @end defun
   2983 
   2984 @defun PendingFrame.find_sal ()
   2985 Return the pending frame's symtab and line object (@pxref{Symbol
   2986 Tables In Python}).
   2987 @end defun
   2988 
   2989 @defun PendingFrame.language ()
   2990 Return the language of this frame, as a string, or None.
   2991 @end defun
   2992 
   2993 @subheading Unwinder Output: UnwindInfo
   2994 
   2995 Use @code{PendingFrame.create_unwind_info} method described above to
   2996 create a @code{gdb.UnwindInfo} instance.  Use the following method to
   2997 specify caller registers that have been saved in this frame:
   2998 
   2999 @defun gdb.UnwindInfo.add_saved_register (register, value)
   3000 @var{register} identifies the register, for a description of the acceptable
   3001 values see @ref{gdbpy_frame_read_register,,Frame.read_register}.
   3002 @var{value} is a register value (a @code{gdb.Value} object).
   3003 @end defun
   3004 
   3005 @subheading The @code{gdb.unwinder} Module
   3006 
   3007 @value{GDBN} comes with a @code{gdb.unwinder} module which contains
   3008 the following classes:
   3009 
   3010 @deftp {class} gdb.unwinder.Unwinder
   3011 The @code{Unwinder} class is a base class from which user created
   3012 unwinders can derive, though it is not required that unwinders derive
   3013 from this class, so long as any user created unwinder has the required
   3014 @code{name} and @code{enabled} attributes.
   3015 
   3016 @defun gdb.unwinder.Unwinder.__init__(name)
   3017 The @var{name} is a string used to reference this unwinder within some
   3018 @value{GDBN} commands (@pxref{Managing Registered Unwinders}).
   3019 @end defun
   3020 
   3021 @defvar gdb.unwinder.name
   3022 A read-only attribute which is a string, the name of this unwinder.
   3023 @end defvar
   3024 
   3025 @defvar gdb.unwinder.enabled
   3026 A modifiable attribute containing a boolean; when @code{True}, the
   3027 unwinder is enabled, and will be used by @value{GDBN}.  When
   3028 @code{False}, the unwinder has been disabled, and will not be used.
   3029 @end defvar
   3030 @end deftp
   3031 
   3032 @anchor{gdb.unwinder.FrameId}
   3033 @deftp {class} gdb.unwinder.FrameId
   3034 This is a class suitable for being used as the frame-id when calling
   3035 @code{gdb.PendingFrame.create_unwind_info}.  It is not required to use
   3036 this class, any class with the required attribute
   3037 (@pxref{gdb.PendingFrame.create_unwind_info}) will be accepted, but in
   3038 most cases this class will be sufficient.
   3039 
   3040 @code{gdb.unwinder.FrameId} has the following method:
   3041 
   3042 @defun gdb.unwinder.FrameId.__init__(sp, pc, special = @code{None})
   3043 The @var{sp} and @var{pc} arguments are required and should be either
   3044 a @code{gdb.Value} object, or an integer.
   3045 
   3046 The @var{special} argument is optional; if specified, it should be a
   3047 @code{gdb.Value} object, or an integer.
   3048 @end defun
   3049 
   3050 @code{gdb.unwinder.FrameId} has the following read-only attributes:
   3051 
   3052 @defvar gdb.unwinder.sp
   3053 The @var{sp} value passed to the constructor.
   3054 @end defvar
   3055 
   3056 @defvar gdb.unwinder.pc
   3057 The @var{pc} value passed to the constructor.
   3058 @end defvar
   3059 
   3060 @defvar gdb.unwinder.special
   3061 The @var{special} value passed to the constructor, or @code{None} if
   3062 no such value was passed.
   3063 @end defvar
   3064 @end deftp
   3065 
   3066 @subheading Registering an Unwinder
   3067 
   3068 Object files and program spaces can have unwinders registered with
   3069 them.  In addition, you can register unwinders globally.
   3070 
   3071 The @code{gdb.unwinders} module provides the function to register an
   3072 unwinder:
   3073 
   3074 @defun gdb.unwinder.register_unwinder (locus, unwinder, replace=False)
   3075 @var{locus} specifies to which unwinder list to prepend the
   3076 @var{unwinder}.  It can be either an object file (@pxref{Objfiles In
   3077 Python}), a program space (@pxref{Progspaces In Python}), or
   3078 @code{None}, in which case the unwinder is registered globally.  The
   3079 newly added @var{unwinder} will be called before any other unwinder
   3080 from the same locus.  Two unwinders in the same locus cannot have the
   3081 same name.  An attempt to add an unwinder with an already existing
   3082 name raises an exception unless @var{replace} is @code{True}, in which
   3083 case the old unwinder is deleted and the new unwinder is registered in
   3084 its place.
   3085 
   3086 @value{GDBN} first calls the unwinders from all the object files in no
   3087 particular order, then the unwinders from the current program space,
   3088 then the globally registered unwinders, and finally the unwinders
   3089 builtin to @value{GDBN}.
   3090 @end defun
   3091 
   3092 @subheading Unwinder Skeleton Code
   3093 
   3094 Here is an example of how to structure a user created unwinder:
   3095 
   3096 @smallexample
   3097 from gdb.unwinder import Unwinder, FrameId
   3098 
   3099 class MyUnwinder(Unwinder):
   3100     def __init__(self):
   3101         super().__init___("MyUnwinder_Name")
   3102 
   3103     def __call__(self, pending_frame):
   3104         if not <we recognize frame>:
   3105             return None
   3106 
   3107         # Create a FrameID.  Usually the frame is identified by a
   3108         # stack pointer and the function address.
   3109         sp = ... compute a stack address ...
   3110         pc = ... compute function address ...
   3111         unwind_info = pending_frame.create_unwind_info(FrameId(sp, pc))
   3112 
   3113         # Find the values of the registers in the caller's frame and
   3114         # save them in the result:
   3115         unwind_info.add_saved_register(<register-number>, <register-value>)
   3116         ....
   3117 
   3118         # Return the result:
   3119         return unwind_info
   3120 
   3121 gdb.unwinder.register_unwinder(<locus>, MyUnwinder(), <replace>)
   3122 @end smallexample
   3123 
   3124 @anchor{Managing Registered Unwinders}
   3125 @subheading Managing Registered Unwinders
   3126 @value{GDBN} defines 3 commands to manage registered unwinders.  These
   3127 are:
   3128 
   3129 @table @code
   3130 @item info unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
   3131 Lists all registered unwinders.  Arguments @var{locus} and
   3132 @var{name-regexp} are both optional and can be used to filter which
   3133 unwinders are listed.
   3134 
   3135 The @var{locus} argument should be either @kbd{global},
   3136 @kbd{progspace}, or the name of an object file.  Only unwinders
   3137 registered for the specified locus will be listed.
   3138 
   3139 The @var{name-regexp} is a regular expression used to match against
   3140 unwinder names.  When trying to match against unwinder names that
   3141 include a string enclose @var{name-regexp} in quotes.
   3142 @item disable unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
   3143 The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
   3144 unwinder} above, but instead of listing the matching unwinders, all of
   3145 the matching unwinders are disabled.  The @code{enabled} field of each
   3146 matching unwinder is set to @code{False}.
   3147 @item enable unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
   3148 The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
   3149 unwinder} above, but instead of listing the matching unwinders, all of
   3150 the matching unwinders are enabled.  The @code{enabled} field of each
   3151 matching unwinder is set to @code{True}.
   3152 @end table
   3153 
   3154 @node Xmethods In Python
   3155 @subsubsection Xmethods In Python
   3156 @cindex xmethods in Python
   3157 
   3158 @dfn{Xmethods} are additional methods or replacements for existing
   3159 methods of a C@t{++} class.  This feature is useful for those cases
   3160 where a method defined in C@t{++} source code could be inlined or
   3161 optimized out by the compiler, making it unavailable to @value{GDBN}.
   3162 For such cases, one can define an xmethod to serve as a replacement
   3163 for the method defined in the C@t{++} source code.  @value{GDBN} will
   3164 then invoke the xmethod, instead of the C@t{++} method, to
   3165 evaluate expressions.  One can also use xmethods when debugging
   3166 with core files.  Moreover, when debugging live programs, invoking an
   3167 xmethod need not involve running the inferior (which can potentially
   3168 perturb its state).  Hence, even if the C@t{++} method is available, it
   3169 is better to use its replacement xmethod if one is defined.
   3170 
   3171 The xmethods feature in Python is available via the concepts of an
   3172 @dfn{xmethod matcher} and an @dfn{xmethod worker}.  To
   3173 implement an xmethod, one has to implement a matcher and a
   3174 corresponding worker for it (more than one worker can be
   3175 implemented, each catering to a different overloaded instance of the
   3176 method).  Internally, @value{GDBN} invokes the @code{match} method of a
   3177 matcher to match the class type and method name.  On a match, the
   3178 @code{match} method returns a list of matching @emph{worker} objects.
   3179 Each worker object typically corresponds to an overloaded instance of
   3180 the xmethod.  They implement a @code{get_arg_types} method which
   3181 returns a sequence of types corresponding to the arguments the xmethod
   3182 requires.  @value{GDBN} uses this sequence of types to perform
   3183 overload resolution and picks a winning xmethod worker.  A winner
   3184 is also selected from among the methods @value{GDBN} finds in the
   3185 C@t{++} source code.  Next, the winning xmethod worker and the
   3186 winning C@t{++} method are compared to select an overall winner.  In
   3187 case of a tie between a xmethod worker and a C@t{++} method, the
   3188 xmethod worker is selected as the winner.  That is, if a winning
   3189 xmethod worker is found to be equivalent to the winning C@t{++}
   3190 method, then the xmethod worker is treated as a replacement for
   3191 the C@t{++} method.  @value{GDBN} uses the overall winner to invoke the
   3192 method.  If the winning xmethod worker is the overall winner, then
   3193 the corresponding xmethod is invoked via the @code{__call__} method
   3194 of the worker object.
   3195 
   3196 If one wants to implement an xmethod as a replacement for an
   3197 existing C@t{++} method, then they have to implement an equivalent
   3198 xmethod which has exactly the same name and takes arguments of
   3199 exactly the same type as the C@t{++} method.  If the user wants to
   3200 invoke the C@t{++} method even though a replacement xmethod is
   3201 available for that method, then they can disable the xmethod.
   3202 
   3203 @xref{Xmethod API}, for API to implement xmethods in Python.
   3204 @xref{Writing an Xmethod}, for implementing xmethods in Python.
   3205 
   3206 @node Xmethod API
   3207 @subsubsection Xmethod API
   3208 @cindex xmethod API
   3209 
   3210 The @value{GDBN} Python API provides classes, interfaces and functions
   3211 to implement, register and manipulate xmethods.
   3212 @xref{Xmethods In Python}.
   3213 
   3214 An xmethod matcher should be an instance of a class derived from
   3215 @code{XMethodMatcher} defined in the module @code{gdb.xmethod}, or an
   3216 object with similar interface and attributes.  An instance of
   3217 @code{XMethodMatcher} has the following attributes:
   3218 
   3219 @defvar name
   3220 The name of the matcher.
   3221 @end defvar
   3222 
   3223 @defvar enabled
   3224 A boolean value indicating whether the matcher is enabled or disabled.
   3225 @end defvar
   3226 
   3227 @defvar methods
   3228 A list of named methods managed by the matcher.  Each object in the list
   3229 is an instance of the class @code{XMethod} defined in the module
   3230 @code{gdb.xmethod}, or any object with the following attributes:
   3231 
   3232 @table @code
   3233 
   3234 @item name
   3235 Name of the xmethod which should be unique for each xmethod
   3236 managed by the matcher.
   3237 
   3238 @item enabled
   3239 A boolean value indicating whether the xmethod is enabled or
   3240 disabled.
   3241 
   3242 @end table
   3243 
   3244 The class @code{XMethod} is a convenience class with same
   3245 attributes as above along with the following constructor:
   3246 
   3247 @defun XMethod.__init__ (self, name)
   3248 Constructs an enabled xmethod with name @var{name}.
   3249 @end defun
   3250 @end defvar
   3251 
   3252 @noindent
   3253 The @code{XMethodMatcher} class has the following methods:
   3254 
   3255 @defun XMethodMatcher.__init__ (self, name)
   3256 Constructs an enabled xmethod matcher with name @var{name}.  The
   3257 @code{methods} attribute is initialized to @code{None}.
   3258 @end defun
   3259 
   3260 @defun XMethodMatcher.match (self, class_type, method_name)
   3261 Derived classes should override this method.  It should return a
   3262 xmethod worker object (or a sequence of xmethod worker
   3263 objects) matching the @var{class_type} and @var{method_name}.
   3264 @var{class_type} is a @code{gdb.Type} object, and @var{method_name}
   3265 is a string value.  If the matcher manages named methods as listed in
   3266 its @code{methods} attribute, then only those worker objects whose
   3267 corresponding entries in the @code{methods} list are enabled should be
   3268 returned.
   3269 @end defun
   3270 
   3271 An xmethod worker should be an instance of a class derived from
   3272 @code{XMethodWorker} defined in the module @code{gdb.xmethod},
   3273 or support the following interface:
   3274 
   3275 @defun XMethodWorker.get_arg_types (self)
   3276 This method returns a sequence of @code{gdb.Type} objects corresponding
   3277 to the arguments that the xmethod takes.  It can return an empty
   3278 sequence or @code{None} if the xmethod does not take any arguments.
   3279 If the xmethod takes a single argument, then a single
   3280 @code{gdb.Type} object corresponding to it can be returned.
   3281 @end defun
   3282 
   3283 @defun XMethodWorker.get_result_type (self, *args)
   3284 This method returns a @code{gdb.Type} object representing the type
   3285 of the result of invoking this xmethod.
   3286 The @var{args} argument is the same tuple of arguments that would be
   3287 passed to the @code{__call__} method of this worker.
   3288 @end defun
   3289 
   3290 @defun XMethodWorker.__call__ (self, *args)
   3291 This is the method which does the @emph{work} of the xmethod.  The
   3292 @var{args} arguments is the tuple of arguments to the xmethod.  Each
   3293 element in this tuple is a gdb.Value object.  The first element is
   3294 always the @code{this} pointer value.
   3295 @end defun
   3296 
   3297 For @value{GDBN} to lookup xmethods, the xmethod matchers
   3298 should be registered using the following function defined in the module
   3299 @code{gdb.xmethod}:
   3300 
   3301 @defun register_xmethod_matcher (locus, matcher, replace=False)
   3302 The @code{matcher} is registered with @code{locus}, replacing an
   3303 existing matcher with the same name as @code{matcher} if
   3304 @code{replace} is @code{True}.  @code{locus} can be a
   3305 @code{gdb.Objfile} object (@pxref{Objfiles In Python}), or a
   3306 @code{gdb.Progspace} object (@pxref{Progspaces In Python}), or
   3307 @code{None}.  If it is @code{None}, then @code{matcher} is registered
   3308 globally.
   3309 @end defun
   3310 
   3311 @node Writing an Xmethod
   3312 @subsubsection Writing an Xmethod
   3313 @cindex writing xmethods in Python
   3314 
   3315 Implementing xmethods in Python will require implementing xmethod
   3316 matchers and xmethod workers (@pxref{Xmethods In Python}).  Consider
   3317 the following C@t{++} class:
   3318 
   3319 @smallexample
   3320 class MyClass
   3321 @{
   3322 public:
   3323   MyClass (int a) : a_(a) @{ @}
   3324 
   3325   int geta (void) @{ return a_; @}
   3326   int operator+ (int b);
   3327 
   3328 private:
   3329   int a_;
   3330 @};
   3331 
   3332 int
   3333 MyClass::operator+ (int b)
   3334 @{
   3335   return a_ + b;
   3336 @}
   3337 @end smallexample
   3338 
   3339 @noindent
   3340 Let us define two xmethods for the class @code{MyClass}, one
   3341 replacing the method @code{geta}, and another adding an overloaded
   3342 flavor of @code{operator+} which takes a @code{MyClass} argument (the
   3343 C@t{++} code above already has an overloaded @code{operator+}
   3344 which takes an @code{int} argument).  The xmethod matcher can be
   3345 defined as follows:
   3346 
   3347 @smallexample
   3348 class MyClass_geta(gdb.xmethod.XMethod):
   3349     def __init__(self):
   3350         gdb.xmethod.XMethod.__init__(self, 'geta')
   3351  
   3352     def get_worker(self, method_name):
   3353         if method_name == 'geta':
   3354             return MyClassWorker_geta()
   3355  
   3356  
   3357 class MyClass_sum(gdb.xmethod.XMethod):
   3358     def __init__(self):
   3359         gdb.xmethod.XMethod.__init__(self, 'sum')
   3360  
   3361     def get_worker(self, method_name):
   3362         if method_name == 'operator+':
   3363             return MyClassWorker_plus()
   3364  
   3365  
   3366 class MyClassMatcher(gdb.xmethod.XMethodMatcher):
   3367     def __init__(self):
   3368         gdb.xmethod.XMethodMatcher.__init__(self, 'MyClassMatcher')
   3369         # List of methods 'managed' by this matcher
   3370         self.methods = [MyClass_geta(), MyClass_sum()]
   3371  
   3372     def match(self, class_type, method_name):
   3373         if class_type.tag != 'MyClass':
   3374             return None
   3375         workers = []
   3376         for method in self.methods:
   3377             if method.enabled:
   3378                 worker = method.get_worker(method_name)
   3379                 if worker:
   3380                     workers.append(worker)
   3381  
   3382         return workers
   3383 @end smallexample
   3384 
   3385 @noindent
   3386 Notice that the @code{match} method of @code{MyClassMatcher} returns
   3387 a worker object of type @code{MyClassWorker_geta} for the @code{geta}
   3388 method, and a worker object of type @code{MyClassWorker_plus} for the
   3389 @code{operator+} method.  This is done indirectly via helper classes
   3390 derived from @code{gdb.xmethod.XMethod}.  One does not need to use the
   3391 @code{methods} attribute in a matcher as it is optional.  However, if a
   3392 matcher manages more than one xmethod, it is a good practice to list the
   3393 xmethods in the @code{methods} attribute of the matcher.  This will then
   3394 facilitate enabling and disabling individual xmethods via the
   3395 @code{enable/disable} commands.  Notice also that a worker object is
   3396 returned only if the corresponding entry in the @code{methods} attribute
   3397 of the matcher is enabled.
   3398 
   3399 The implementation of the worker classes returned by the matcher setup
   3400 above is as follows:
   3401 
   3402 @smallexample
   3403 class MyClassWorker_geta(gdb.xmethod.XMethodWorker):
   3404     def get_arg_types(self):
   3405         return None
   3406 
   3407     def get_result_type(self, obj):
   3408         return gdb.lookup_type('int')
   3409  
   3410     def __call__(self, obj):
   3411         return obj['a_']
   3412  
   3413  
   3414 class MyClassWorker_plus(gdb.xmethod.XMethodWorker):
   3415     def get_arg_types(self):
   3416         return gdb.lookup_type('MyClass')
   3417 
   3418     def get_result_type(self, obj):
   3419         return gdb.lookup_type('int')
   3420  
   3421     def __call__(self, obj, other):
   3422         return obj['a_'] + other['a_']
   3423 @end smallexample
   3424 
   3425 For @value{GDBN} to actually lookup a xmethod, it has to be
   3426 registered with it.  The matcher defined above is registered with
   3427 @value{GDBN} globally as follows:
   3428 
   3429 @smallexample
   3430 gdb.xmethod.register_xmethod_matcher(None, MyClassMatcher())
   3431 @end smallexample
   3432 
   3433 If an object @code{obj} of type @code{MyClass} is initialized in C@t{++}
   3434 code as follows:
   3435 
   3436 @smallexample
   3437 MyClass obj(5);
   3438 @end smallexample
   3439 
   3440 @noindent
   3441 then, after loading the Python script defining the xmethod matchers
   3442 and workers into @value{GDBN}, invoking the method @code{geta} or using
   3443 the operator @code{+} on @code{obj} will invoke the xmethods
   3444 defined above:
   3445 
   3446 @smallexample
   3447 (gdb) p obj.geta()
   3448 $1 = 5
   3449 
   3450 (gdb) p obj + obj
   3451 $2 = 10
   3452 @end smallexample
   3453 
   3454 Consider another example with a C++ template class:
   3455 
   3456 @smallexample
   3457 template <class T>
   3458 class MyTemplate
   3459 @{
   3460 public:
   3461   MyTemplate () : dsize_(10), data_ (new T [10]) @{ @}
   3462   ~MyTemplate () @{ delete [] data_; @}
   3463  
   3464   int footprint (void)
   3465   @{
   3466     return sizeof (T) * dsize_ + sizeof (MyTemplate<T>);
   3467   @}
   3468  
   3469 private:
   3470   int dsize_;
   3471   T *data_;
   3472 @};
   3473 @end smallexample
   3474 
   3475 Let us implement an xmethod for the above class which serves as a
   3476 replacement for the @code{footprint} method.  The full code listing
   3477 of the xmethod workers and xmethod matchers is as follows:
   3478 
   3479 @smallexample
   3480 class MyTemplateWorker_footprint(gdb.xmethod.XMethodWorker):
   3481     def __init__(self, class_type):
   3482         self.class_type = class_type
   3483 
   3484     def get_arg_types(self):
   3485         return None
   3486 
   3487     def get_result_type(self):
   3488         return gdb.lookup_type('int')
   3489 
   3490     def __call__(self, obj):
   3491         return (self.class_type.sizeof +
   3492                 obj['dsize_'] *
   3493                 self.class_type.template_argument(0).sizeof)
   3494  
   3495  
   3496 class MyTemplateMatcher_footprint(gdb.xmethod.XMethodMatcher):
   3497     def __init__(self):
   3498         gdb.xmethod.XMethodMatcher.__init__(self, 'MyTemplateMatcher')
   3499  
   3500     def match(self, class_type, method_name):
   3501         if (re.match('MyTemplate<[ \t\n]*[_a-zA-Z][ _a-zA-Z0-9]*>',
   3502                      class_type.tag) and
   3503             method_name == 'footprint'):
   3504             return MyTemplateWorker_footprint(class_type)
   3505 @end smallexample
   3506 
   3507 Notice that, in this example, we have not used the @code{methods}
   3508 attribute of the matcher as the matcher manages only one xmethod.  The
   3509 user can enable/disable this xmethod by enabling/disabling the matcher
   3510 itself.
   3511 
   3512 @node Inferiors In Python
   3513 @subsubsection Inferiors In Python
   3514 @cindex inferiors in Python
   3515 
   3516 @findex gdb.Inferior
   3517 Programs which are being run under @value{GDBN} are called inferiors
   3518 (@pxref{Inferiors Connections and Programs}).  Python scripts can access
   3519 information about and manipulate inferiors controlled by @value{GDBN}
   3520 via objects of the @code{gdb.Inferior} class.
   3521 
   3522 The following inferior-related functions are available in the @code{gdb}
   3523 module:
   3524 
   3525 @defun gdb.inferiors ()
   3526 Return a tuple containing all inferior objects.
   3527 @end defun
   3528 
   3529 @defun gdb.selected_inferior ()
   3530 Return an object representing the current inferior.
   3531 @end defun
   3532 
   3533 A @code{gdb.Inferior} object has the following attributes:
   3534 
   3535 @defvar Inferior.num
   3536 ID of inferior, as assigned by @value{GDBN}.  You can use this to make
   3537 Python breakpoints inferior-specific, for example
   3538 (@pxref{python_breakpoint_inferior,,The Breakpoint.inferior
   3539 attribute}).
   3540 @end defvar
   3541 
   3542 @anchor{gdbpy_inferior_connection}
   3543 @defvar Inferior.connection
   3544 The @code{gdb.TargetConnection} for this inferior (@pxref{Connections
   3545 In Python}), or @code{None} if this inferior has no connection.
   3546 @end defvar
   3547 
   3548 @defvar Inferior.connection_num
   3549 ID of inferior's connection as assigned by @value{GDBN}, or None if
   3550 the inferior is not connected to a target.  @xref{Inferiors Connections
   3551 and Programs}.  This is equivalent to
   3552 @code{gdb.Inferior.connection.num} in the case where
   3553 @code{gdb.Inferior.connection} is not @code{None}.
   3554 @end defvar
   3555 
   3556 @defvar Inferior.pid
   3557 Process ID of the inferior, as assigned by the underlying operating
   3558 system.
   3559 @end defvar
   3560 
   3561 @defvar Inferior.was_attached
   3562 Boolean signaling whether the inferior was created using `attach', or
   3563 started by @value{GDBN} itself.
   3564 @end defvar
   3565 
   3566 @defvar Inferior.main_name
   3567 A string holding the name of this inferior's ``main'' function, if it
   3568 can be determined.  If the name of main is not known, this is
   3569 @code{None}.
   3570 @end defvar
   3571 
   3572 @defvar Inferior.progspace
   3573 The inferior's program space.  @xref{Progspaces In Python}.
   3574 @end defvar
   3575 
   3576 @defvar Inferior.arguments
   3577 The inferior's command line arguments, if known.  This corresponds to
   3578 the @code{set args} and @code{show args} commands.  @xref{Arguments}.
   3579 
   3580 When accessed, the value is a string holding all the arguments.  The
   3581 contents are quoted as they would be when passed to the shell.  If
   3582 there are no arguments, the value is @code{None}.
   3583 
   3584 Either a string or a sequence of strings can be assigned to this
   3585 attribute.  When a string is assigned, it is assumed to have any
   3586 necessary quoting for the shell; when a sequence is assigned, the
   3587 quoting is applied by @value{GDBN}.
   3588 @end defvar
   3589 
   3590 A @code{gdb.Inferior} object has the following methods:
   3591 
   3592 @defun Inferior.is_valid ()
   3593 Returns @code{True} if the @code{gdb.Inferior} object is valid,
   3594 @code{False} if not.  A @code{gdb.Inferior} object will become invalid
   3595 if the inferior no longer exists within @value{GDBN}.  All other
   3596 @code{gdb.Inferior} methods will throw an exception if it is invalid
   3597 at the time the method is called.
   3598 @end defun
   3599 
   3600 @defun Inferior.threads ()
   3601 This method returns a tuple holding all the threads which are valid
   3602 when it is called.  If there are no valid threads, the method will
   3603 return an empty tuple.
   3604 @end defun
   3605 
   3606 @defun Inferior.architecture ()
   3607 Return the @code{gdb.Architecture} (@pxref{Architectures In Python})
   3608 for this inferior.  This represents the architecture of the inferior
   3609 as a whole.  Some platforms can have multiple architectures in a
   3610 single address space, so this may not match the architecture of a
   3611 particular frame (@pxref{Frames In Python}).
   3612 @end defun
   3613 
   3614 @anchor{gdbpy_inferior_read_memory}
   3615 @defun Inferior.read_memory (address, length)
   3616 Read @var{length} addressable memory units from the inferior, starting
   3617 at @var{address}.  Returns a @code{memoryview} object, which behaves
   3618 much like an array or a string.  It can be modified and given to the
   3619 @code{Inferior.write_memory} function.
   3620 @end defun
   3621 
   3622 @defun Inferior.write_memory (address, buffer @r{[}, length@r{]})
   3623 Write the contents of @var{buffer} to the inferior, starting at
   3624 @var{address}.  The @var{buffer} parameter must be a Python object
   3625 which supports the buffer protocol, i.e., a string, an array or the
   3626 object returned from @code{Inferior.read_memory}.  If given, @var{length}
   3627 determines the number of addressable memory units from @var{buffer} to be
   3628 written.
   3629 @end defun
   3630 
   3631 @defun Inferior.search_memory (address, length, pattern)
   3632 Search a region of the inferior memory starting at @var{address} with
   3633 the given @var{length} using the search pattern supplied in
   3634 @var{pattern}.  The @var{pattern} parameter must be a Python object
   3635 which supports the buffer protocol, i.e., a string, an array or the
   3636 object returned from @code{gdb.read_memory}.  Returns a Python @code{Long}
   3637 containing the address where the pattern was found, or @code{None} if
   3638 the pattern could not be found.
   3639 @end defun
   3640 
   3641 @findex Inferior.thread_from_thread_handle
   3642 @defun Inferior.thread_from_handle (handle)
   3643 Return the thread object corresponding to @var{handle}, a thread
   3644 library specific data structure such as @code{pthread_t} for pthreads
   3645 library implementations.
   3646 
   3647 The function @code{Inferior.thread_from_thread_handle} provides
   3648 the same functionality, but use of @code{Inferior.thread_from_thread_handle}
   3649 is deprecated.
   3650 @end defun
   3651 
   3652 
   3653 The environment that will be passed to the inferior can be changed
   3654 from Python by using the following methods.  These methods only take
   3655 effect when the inferior is started -- they will not affect an
   3656 inferior that is already executing.
   3657 
   3658 @defun Inferior.clear_env ()
   3659 Clear the current environment variables that will be passed to this
   3660 inferior.
   3661 @end defun
   3662 
   3663 @defun Inferior.set_env (name, value)
   3664 Set the environment variable @var{name} to have the indicated value.
   3665 Both parameters must be strings.
   3666 @end defun
   3667 
   3668 @defun Inferior.unset_env (name)
   3669 Unset the environment variable @var{name}.  @var{name} must be a
   3670 string.
   3671 @end defun
   3672 
   3673 One may add arbitrary attributes to @code{gdb.Inferior} objects in the
   3674 usual Python way.  This is useful if, for example, one needs to do
   3675 some extra record keeping associated with the inferior.
   3676 
   3677 @anchor{choosing attribute names}
   3678 When selecting a name for a new attribute, avoid starting the new
   3679 attribute name with a lower case letter; future attributes added by
   3680 @value{GDBN} will start with a lower case letter.  Additionally, avoid
   3681 starting attribute names with two underscore characters, as these
   3682 could clash with Python builtin attribute names.
   3683 
   3684 In this contrived example we record the time when an inferior last
   3685 stopped:
   3686 
   3687 @smallexample
   3688 @group
   3689 (@value{GDBP}) python
   3690 import datetime
   3691 
   3692 def thread_stopped(event):
   3693     if event.inferior_thread is not None:
   3694         thread = event.inferior_thread
   3695     else:
   3696         thread = gdb.selected_thread()
   3697     inferior = thread.inferior
   3698     inferior._last_stop_time = datetime.datetime.today()
   3699 
   3700 gdb.events.stop.connect(thread_stopped)
   3701 @end group
   3702 @group
   3703 (@value{GDBP}) file /tmp/hello
   3704 Reading symbols from /tmp/hello...
   3705 (@value{GDBP}) start
   3706 Temporary breakpoint 1 at 0x401198: file /tmp/hello.c, line 18.
   3707 Starting program: /tmp/hello
   3708 
   3709 Temporary breakpoint 1, main () at /tmp/hello.c:18
   3710 18	  printf ("Hello World\n");
   3711 (@value{GDBP}) python print(gdb.selected_inferior()._last_stop_time)
   3712 2024-01-04 14:48:41.347036
   3713 @end group
   3714 @end smallexample
   3715 
   3716 @node Events In Python
   3717 @subsubsection Events In Python
   3718 @cindex inferior events in Python
   3719 
   3720 @value{GDBN} provides a general event facility so that Python code can be
   3721 notified of various state changes, particularly changes that occur in
   3722 the inferior.
   3723 
   3724 An @dfn{event} is just an object that describes some state change.  The
   3725 type of the object and its attributes will vary depending on the details
   3726 of the change.  All the existing events are described below.
   3727 
   3728 In order to be notified of an event, you must register an event handler
   3729 with an @dfn{event registry}.  An event registry is an object in the
   3730 @code{gdb.events} module which dispatches particular events.  A registry
   3731 provides methods to register and unregister event handlers:
   3732 
   3733 @defun EventRegistry.connect (object)
   3734 Add the given callable @var{object} to the registry.  This object will be
   3735 called when an event corresponding to this registry occurs.
   3736 @end defun
   3737 
   3738 @defun EventRegistry.disconnect (object)
   3739 Remove the given @var{object} from the registry.  Once removed, the object
   3740 will no longer receive notifications of events.
   3741 @end defun
   3742 
   3743 Here is an example:
   3744 
   3745 @smallexample
   3746 def exit_handler (event):
   3747     print ("event type: exit")
   3748     if hasattr (event, 'exit_code'):
   3749         print ("exit code: %d" % (event.exit_code))
   3750     else:
   3751         print ("exit code not available")
   3752 
   3753 gdb.events.exited.connect (exit_handler)
   3754 @end smallexample
   3755 
   3756 In the above example we connect our handler @code{exit_handler} to the
   3757 registry @code{events.exited}.  Once connected, @code{exit_handler} gets
   3758 called when the inferior exits.  The argument @dfn{event} in this example is
   3759 of type @code{gdb.ExitedEvent}.  As you can see in the example the
   3760 @code{ExitedEvent} object has an attribute which indicates the exit code of
   3761 the inferior.
   3762 
   3763 Some events can be thread specific when @value{GDBN} is running in
   3764 non-stop mode.  When represented in Python, these events all extend
   3765 @code{gdb.ThreadEvent}.  This event is a base class and is never
   3766 emitted directly; instead, events which are emitted by this or other
   3767 modules might extend this event.  Examples of these events are
   3768 @code{gdb.BreakpointEvent} and @code{gdb.ContinueEvent}.
   3769 @code{gdb.ThreadEvent} holds the following attributes:
   3770 
   3771 @defvar ThreadEvent.inferior_thread
   3772 In non-stop mode this attribute will be set to the specific thread which was
   3773 involved in the emitted event. Otherwise, it will be set to @code{None}.
   3774 @end defvar
   3775 
   3776 The following is a listing of the event registries that are available and
   3777 details of the events they emit:
   3778 
   3779 @table @code
   3780 
   3781 @item events.cont
   3782 Emits @code{gdb.ContinueEvent}, which extends @code{gdb.ThreadEvent}.
   3783 This event indicates that the inferior has been continued after a
   3784 stop. For inherited attribute refer to @code{gdb.ThreadEvent} above.
   3785 
   3786 @item events.exited
   3787 Emits @code{events.ExitedEvent}, which indicates that the inferior has
   3788 exited.  @code{events.ExitedEvent} has two attributes:
   3789 
   3790 @defvar ExitedEvent.exit_code
   3791 An integer representing the exit code, if available, which the inferior 
   3792 has returned.  (The exit code could be unavailable if, for example,
   3793 @value{GDBN} detaches from the inferior.) If the exit code is unavailable,
   3794 the attribute does not exist.
   3795 @end defvar
   3796 
   3797 @defvar ExitedEvent.inferior
   3798 A reference to the inferior which triggered the @code{exited} event.
   3799 @end defvar
   3800 
   3801 @item events.stop
   3802 Emits @code{gdb.StopEvent}, which extends @code{gdb.ThreadEvent}.
   3803 
   3804 Indicates that the inferior has stopped.  All events emitted by this
   3805 registry extend @code{gdb.StopEvent}.  As a child of
   3806 @code{gdb.ThreadEvent}, @code{gdb.StopEvent} will indicate the stopped
   3807 thread when @value{GDBN} is running in non-stop mode.  Refer to
   3808 @code{gdb.ThreadEvent} above for more details.
   3809 
   3810 @code{gdb.StopEvent} has the following additional attributes:
   3811 
   3812 @defvar StopEvent.details
   3813 A dictionary holding any details relevant to the stop.  The exact keys
   3814 and values depend on the type of stop, but are identical to the
   3815 corresponding MI output (@pxref{GDB/MI Async Records}).
   3816 
   3817 A dictionary was used for this (rather than adding attributes directly
   3818 to the event object) so that the MI keys could be used unchanged.
   3819 
   3820 When a @code{StopEvent} results from a @code{finish} command, it will
   3821 also hold the return value from the function, if that is available.
   3822 This will be an entry named @samp{return-value} in the @code{details}
   3823 dictionary.  The value of this entry will be a @code{gdb.Value}
   3824 object.
   3825 @end defvar
   3826 
   3827 Emits @code{gdb.SignalEvent}, which extends @code{gdb.StopEvent}.
   3828 
   3829 This event indicates that the inferior or one of its threads has
   3830 received a signal.  @code{gdb.SignalEvent} has the following
   3831 attributes:
   3832 
   3833 @defvar SignalEvent.stop_signal
   3834 A string representing the signal received by the inferior.  A list of possible
   3835 signal values can be obtained by running the command @code{info signals} in
   3836 the @value{GDBN} command prompt.
   3837 @end defvar
   3838 
   3839 Also emits @code{gdb.BreakpointEvent}, which extends
   3840 @code{gdb.StopEvent}.
   3841 
   3842 @code{gdb.BreakpointEvent} event indicates that one or more breakpoints have
   3843 been hit, and has the following attributes:
   3844 
   3845 @defvar BreakpointEvent.breakpoints
   3846 A sequence containing references to all the breakpoints (type 
   3847 @code{gdb.Breakpoint}) that were hit.
   3848 @xref{Breakpoints In Python}, for details of the @code{gdb.Breakpoint} object.
   3849 @end defvar
   3850 
   3851 @defvar BreakpointEvent.breakpoint
   3852 A reference to the first breakpoint that was hit.  This attribute is
   3853 maintained for backward compatibility and is now deprecated in favor
   3854 of the @code{gdb.BreakpointEvent.breakpoints} attribute.
   3855 @end defvar
   3856 
   3857 @item events.new_objfile
   3858 Emits @code{gdb.NewObjFileEvent} which indicates that a new object file has
   3859 been loaded by @value{GDBN}.  @code{gdb.NewObjFileEvent} has one attribute:
   3860 
   3861 @defvar NewObjFileEvent.new_objfile
   3862 A reference to the object file (@code{gdb.Objfile}) which has been loaded.
   3863 @xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
   3864 @end defvar
   3865 
   3866 @item events.free_objfile
   3867 Emits @code{gdb.FreeObjFileEvent} which indicates that an object file
   3868 is about to be removed from @value{GDBN}.  One reason this can happen
   3869 is when the inferior calls @code{dlclose}.
   3870 @code{gdb.FreeObjFileEvent} has one attribute:
   3871 
   3872 @defvar FreeObjFileEvent.objfile
   3873 A reference to the object file (@code{gdb.Objfile}) which will be unloaded.
   3874 @xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
   3875 @end defvar
   3876 
   3877 @item events.clear_objfiles
   3878 Emits @code{gdb.ClearObjFilesEvent} which indicates that the list of object
   3879 files for a program space has been reset.
   3880 @code{gdb.ClearObjFilesEvent} has one attribute:
   3881 
   3882 @defvar ClearObjFilesEvent.progspace
   3883 A reference to the program space (@code{gdb.Progspace}) whose objfile list has
   3884 been cleared.  @xref{Progspaces In Python}.
   3885 @end defvar
   3886 
   3887 @item events.inferior_call
   3888 Emits events just before and after a function in the inferior is
   3889 called by @value{GDBN}.  Before an inferior call, this emits an event
   3890 of type @code{gdb.InferiorCallPreEvent}, and after an inferior call,
   3891 this emits an event of type @code{gdb.InferiorCallPostEvent}.
   3892 
   3893 @table @code
   3894 @tindex gdb.InferiorCallPreEvent
   3895 @item @code{gdb.InferiorCallPreEvent}
   3896 Indicates that a function in the inferior is about to be called.
   3897 
   3898 @defvar InferiorCallPreEvent.ptid
   3899 The thread in which the call will be run.
   3900 @end defvar
   3901 
   3902 @defvar InferiorCallPreEvent.address
   3903 The location of the function to be called.
   3904 @end defvar
   3905 
   3906 @tindex gdb.InferiorCallPostEvent
   3907 @item @code{gdb.InferiorCallPostEvent}
   3908 Indicates that a function in the inferior has just been called.
   3909 
   3910 @defvar InferiorCallPostEvent.ptid
   3911 The thread in which the call was run.
   3912 @end defvar
   3913 
   3914 @defvar InferiorCallPostEvent.address
   3915 The location of the function that was called.
   3916 @end defvar
   3917 @end table
   3918 
   3919 @item events.memory_changed
   3920 Emits @code{gdb.MemoryChangedEvent} which indicates that the memory of the
   3921 inferior has been modified by the @value{GDBN} user, for instance via a
   3922 command like @w{@code{set *addr = value}}.  The event has the following
   3923 attributes:
   3924 
   3925 @defvar MemoryChangedEvent.address
   3926 The start address of the changed region.
   3927 @end defvar
   3928 
   3929 @defvar MemoryChangedEvent.length
   3930 Length in bytes of the changed region.
   3931 @end defvar
   3932 
   3933 @item events.register_changed
   3934 Emits @code{gdb.RegisterChangedEvent} which indicates that a register in the
   3935 inferior has been modified by the @value{GDBN} user.
   3936 
   3937 @defvar RegisterChangedEvent.frame
   3938 A gdb.Frame object representing the frame in which the register was modified.
   3939 @end defvar
   3940 @defvar RegisterChangedEvent.regnum
   3941 Denotes which register was modified.
   3942 @end defvar
   3943 
   3944 @item events.breakpoint_created
   3945 This is emitted when a new breakpoint has been created.  The argument
   3946 that is passed is the new @code{gdb.Breakpoint} object.
   3947 
   3948 @item events.breakpoint_modified
   3949 This is emitted when a breakpoint has been modified in some way.  The
   3950 argument that is passed is the new @code{gdb.Breakpoint} object.
   3951 
   3952 @item events.breakpoint_deleted
   3953 This is emitted when a breakpoint has been deleted.  The argument that
   3954 is passed is the @code{gdb.Breakpoint} object.  When this event is
   3955 emitted, the @code{gdb.Breakpoint} object will already be in its
   3956 invalid state; that is, the @code{is_valid} method will return
   3957 @code{False}.
   3958 
   3959 @item events.before_prompt
   3960 This event carries no payload.  It is emitted each time @value{GDBN}
   3961 presents a prompt to the user.
   3962 
   3963 @item events.new_inferior
   3964 This is emitted when a new inferior is created.  Note that the
   3965 inferior is not necessarily running; in fact, it may not even have an
   3966 associated executable.
   3967 
   3968 The event is of type @code{gdb.NewInferiorEvent}.  This has a single
   3969 attribute:
   3970 
   3971 @defvar NewInferiorEvent.inferior
   3972 The new inferior, a @code{gdb.Inferior} object.
   3973 @end defvar
   3974 
   3975 @item events.inferior_deleted
   3976 This is emitted when an inferior has been deleted.  Note that this is
   3977 not the same as process exit; it is notified when the inferior itself
   3978 is removed, say via @code{remove-inferiors}.
   3979 
   3980 The event is of type @code{gdb.InferiorDeletedEvent}.  This has a single
   3981 attribute:
   3982 
   3983 @defvar InferiorDeletedEvent.inferior
   3984 The inferior that is being removed, a @code{gdb.Inferior} object.
   3985 @end defvar
   3986 
   3987 @item events.new_thread
   3988 This is emitted when @value{GDBN} notices a new thread.  The event is of
   3989 type @code{gdb.NewThreadEvent}, which extends @code{gdb.ThreadEvent}.
   3990 This has a single attribute:
   3991 
   3992 @defvar NewThreadEvent.inferior_thread
   3993 The new thread.
   3994 @end defvar
   3995 
   3996 @item events.thread_exited
   3997 This is emitted when @value{GDBN} notices a thread has exited.  The event
   3998 is of type @code{gdb.ThreadExitedEvent} which extends @code{gdb.ThreadEvent}.
   3999 This has a single attribute:
   4000 
   4001 @defvar ThreadExitedEvent.inferior_thread
   4002 The exiting thread.
   4003 @end defvar
   4004 
   4005 @item events.gdb_exiting
   4006 This is emitted when @value{GDBN} exits.  This event is not emitted if
   4007 @value{GDBN} exits as a result of an internal error, or after an
   4008 unexpected signal.  The event is of type @code{gdb.GdbExitingEvent},
   4009 which has a single attribute:
   4010 
   4011 @defvar GdbExitingEvent.exit_code
   4012 An integer, the value of the exit code @value{GDBN} will return.
   4013 @end defvar
   4014 
   4015 @item events.connection_removed
   4016 This is emitted when @value{GDBN} removes a connection
   4017 (@pxref{Connections In Python}).  The event is of type
   4018 @code{gdb.ConnectionEvent}.  This has a single read-only attribute:
   4019 
   4020 @defvar ConnectionEvent.connection
   4021 The @code{gdb.TargetConnection} that is being removed.
   4022 @end defvar
   4023 
   4024 @item events.executable_changed
   4025 Emits @code{gdb.ExecutableChangedEvent} which indicates that the
   4026 @code{gdb.Progspace.executable_filename} has changed.
   4027 
   4028 This event is emitted when either the value of
   4029 @code{gdb.Progspace.executable_filename } has changed to name a
   4030 different file, or the executable file named by
   4031 @code{gdb.Progspace.executable_filename} has changed on disk, and
   4032 @value{GDBN} has therefore reloaded it.
   4033 
   4034 @defvar ExecutableChangedEvent.progspace
   4035 The @code{gdb.Progspace} in which the current executable has changed.
   4036 The file name of the updated executable will be visible in
   4037 @code{gdb.Progspace.executable_filename} (@pxref{Progspaces In Python}).
   4038 @end defvar
   4039 @defvar ExecutableChangedEvent.reload
   4040 This attribute will be @code{True} if the value of
   4041 @code{gdb.Progspace.executable_filename} didn't change, but the file
   4042 it names changed on disk instead, and @value{GDBN} reloaded it.
   4043 
   4044 When this attribute is @code{False}, the value in
   4045 @code{gdb.Progspace.executable_filename} was changed to name a
   4046 different file.
   4047 @end defvar
   4048 
   4049 Remember that @value{GDBN} tracks the executable file and the symbol
   4050 file separately, these are visible as
   4051 @code{gdb.Progspace.executable_filename} and
   4052 @code{gdb.Progspace.filename} respectively.  When using the @kbd{file}
   4053 command, @value{GDBN} updates both of these fields, but the executable
   4054 file is updated first, so when this event is emitted, the executable
   4055 filename will have changed, but the symbol filename might still hold
   4056 its previous value.
   4057 
   4058 @item events.new_progspace
   4059 This is emitted when @value{GDBN} adds a new program space
   4060 (@pxref{Progspaces In Python,,Program Spaces In Python}).  The event
   4061 is of type @code{gdb.NewProgspaceEvent}, and has a single read-only
   4062 attribute:
   4063 
   4064 @defvar NewProgspaceEvent.progspace
   4065 The @code{gdb.Progspace} that was added to @value{GDBN}.
   4066 @end defvar
   4067 
   4068 No @code{NewProgspaceEvent} is emitted for the very first program
   4069 space, which is assigned to the first inferior.  This first program
   4070 space is created within @value{GDBN} before any Python scripts are
   4071 sourced.
   4072 
   4073 @item events.free_progspace
   4074 This is emitted when @value{GDBN} removes a program space
   4075 (@pxref{Progspaces In Python,,Program Spaces In Python}), for example
   4076 as a result of the @kbd{remove-inferiors} command
   4077 (@pxref{remove_inferiors_cli,,@kbd{remove-inferiors}}).  The event is
   4078 of type @code{gdb.FreeProgspaceEvent}, and has a single read-only
   4079 attribute:
   4080 
   4081 @defvar FreeProgspaceEvent.progspace
   4082 The @code{gdb.Progspace} that is about to be removed from
   4083 @value{GDBN}.
   4084 @end defvar
   4085 
   4086 @item events.tui_enabled
   4087 This is emitted when the TUI is enabled or disabled.  The event is of
   4088 type @code{gdb.TuiEnabledEvent}, which has a single read-only
   4089 attribute:
   4090 
   4091 @defvar TuiEnabledEvent.enabled
   4092 If the TUI has just been enabled, this is @code{True}; otherwise it is
   4093 @code{False}.
   4094 @end defvar
   4095 
   4096 @end table
   4097 
   4098 @node Threads In Python
   4099 @subsubsection Threads In Python
   4100 @cindex threads in python
   4101 
   4102 @findex gdb.InferiorThread
   4103 Python scripts can access information about, and manipulate inferior threads
   4104 controlled by @value{GDBN}, via objects of the @code{gdb.InferiorThread} class.
   4105 
   4106 The following thread-related functions are available in the @code{gdb}
   4107 module:
   4108 
   4109 @defun gdb.selected_thread ()
   4110 This function returns the thread object for the selected thread.  If there
   4111 is no selected thread, this will return @code{None}.
   4112 @end defun
   4113 
   4114 To get the list of threads for an inferior, use the @code{Inferior.threads()}
   4115 method.  @xref{Inferiors In Python}.
   4116 
   4117 A @code{gdb.InferiorThread} object has the following attributes:
   4118 
   4119 @defvar InferiorThread.name
   4120 The name of the thread.  If the user specified a name using
   4121 @code{thread name}, then this returns that name.  Otherwise, if an
   4122 OS-supplied name is available, then it is returned.  Otherwise, this
   4123 returns @code{None}.
   4124 
   4125 This attribute can be assigned to.  The new value must be a string
   4126 object, which sets the new name, or @code{None}, which removes any
   4127 user-specified thread name.
   4128 @end defvar
   4129 
   4130 @defvar InferiorThread.num
   4131 The per-inferior number of the thread, as assigned by GDB.
   4132 @end defvar
   4133 
   4134 @defvar InferiorThread.global_num
   4135 The global ID of the thread, as assigned by GDB.  You can use this to
   4136 make Python breakpoints thread-specific, for example
   4137 (@pxref{python_breakpoint_thread,,The Breakpoint.thread attribute}).
   4138 @end defvar
   4139 
   4140 @anchor{inferior_thread_ptid}
   4141 @defvar InferiorThread.ptid
   4142 ID of the thread, as assigned by the operating system.  This attribute is a
   4143 tuple containing three integers.  The first is the Process ID (PID); the second
   4144 is the Lightweight Process ID (LWPID), and the third is the Thread ID (TID).
   4145 Either the LWPID or TID may be 0, which indicates that the operating system
   4146 does not  use that identifier.
   4147 @end defvar
   4148 
   4149 @defvar InferiorThread.ptid_string
   4150 This read-only attribute contains a string representing
   4151 @code{InferiorThread.ptid}.  This is the string that @value{GDBN} uses
   4152 in the @samp{Target Id} column in the @kbd{info threads} output
   4153 (@pxref{info_threads,,@samp{info threads}}).
   4154 @end defvar
   4155 
   4156 @defvar InferiorThread.inferior
   4157 The inferior this thread belongs to.  This attribute is represented as
   4158 a @code{gdb.Inferior} object.  This attribute is not writable.
   4159 @end defvar
   4160 
   4161 @defvar InferiorThread.details
   4162 A string containing target specific thread state information.  The
   4163 format of this string varies by target.  If there is no additional
   4164 state information for this thread, then this attribute contains
   4165 @code{None}.
   4166 
   4167 For example, on a @sc{gnu}/Linux system, a thread that is in the
   4168 process of exiting will return the string @samp{Exiting}.  For remote
   4169 targets the @code{details} string will be obtained with the
   4170 @samp{qThreadExtraInfo} remote packet, if the target supports it
   4171 (@pxref{qThreadExtraInfo,,@samp{qThreadExtraInfo}}).
   4172 
   4173 @value{GDBN} displays the @code{details} string as part of the
   4174 @samp{Target Id} column, in the @code{info threads} output
   4175 (@pxref{info_threads,,@samp{info threads}}).
   4176 @end defvar
   4177 
   4178 A @code{gdb.InferiorThread} object has the following methods:
   4179 
   4180 @defun InferiorThread.is_valid ()
   4181 Returns @code{True} if the @code{gdb.InferiorThread} object is valid,
   4182 @code{False} if not.  A @code{gdb.InferiorThread} object will become
   4183 invalid if the thread exits, or the inferior that the thread belongs
   4184 is deleted.  All other @code{gdb.InferiorThread} methods will throw an
   4185 exception if it is invalid at the time the method is called.
   4186 @end defun
   4187 
   4188 @defun InferiorThread.switch ()
   4189 This changes @value{GDBN}'s currently selected thread to the one represented
   4190 by this object.
   4191 @end defun
   4192 
   4193 @defun InferiorThread.is_stopped ()
   4194 Return a Boolean indicating whether the thread is stopped.
   4195 @end defun
   4196 
   4197 @defun InferiorThread.is_running ()
   4198 Return a Boolean indicating whether the thread is running.
   4199 @end defun
   4200 
   4201 @defun InferiorThread.is_exited ()
   4202 Return a Boolean indicating whether the thread is exited.
   4203 @end defun
   4204 
   4205 @defun InferiorThread.handle ()
   4206 Return the thread object's handle, represented as a Python @code{bytes}
   4207 object.  A @code{gdb.Value} representation of the handle may be
   4208 constructed via @code{gdb.Value(bufobj, type)} where @var{bufobj} is
   4209 the Python @code{bytes} representation of the handle and @var{type} is
   4210 a @code{gdb.Type} for the handle type.
   4211 @end defun
   4212 
   4213 One may add arbitrary attributes to @code{gdb.InferiorThread} objects
   4214 in the usual Python way.  This is useful if, for example, one needs to
   4215 do some extra record keeping associated with the thread.
   4216 
   4217 @xref{choosing attribute names}, for guidance on selecting a suitable
   4218 name for new attributes.
   4219 
   4220 In this contrived example we record the time when a thread last
   4221 stopped:
   4222 
   4223 @smallexample
   4224 @group
   4225 (@value{GDBP}) python
   4226 import datetime
   4227 
   4228 def thread_stopped(event):
   4229     if event.inferior_thread is not None:
   4230         thread = event.inferior_thread
   4231     else:
   4232         thread = gdb.selected_thread()
   4233     thread._last_stop_time = datetime.datetime.today()
   4234 
   4235 gdb.events.stop.connect(thread_stopped)
   4236 @end group
   4237 @group
   4238 (@value{GDBP}) file /tmp/hello
   4239 Reading symbols from /tmp/hello...
   4240 (@value{GDBP}) start
   4241 Temporary breakpoint 1 at 0x401198: file /tmp/hello.c, line 18.
   4242 Starting program: /tmp/hello
   4243 
   4244 Temporary breakpoint 1, main () at /tmp/hello.c:18
   4245 18	  printf ("Hello World\n");
   4246 (@value{GDBP}) python print(gdb.selected_thread()._last_stop_time)
   4247 2024-01-04 14:48:41.347036
   4248 @end group
   4249 @end smallexample
   4250 
   4251 @node Recordings In Python
   4252 @subsubsection Recordings In Python
   4253 @cindex recordings in python
   4254 
   4255 The following recordings-related functions
   4256 (@pxref{Process Record and Replay}) are available in the @code{gdb}
   4257 module:
   4258 
   4259 @defun gdb.start_recording (@r{[}method@r{]}, @r{[}format@r{]})
   4260 Start a recording using the given @var{method} and @var{format}.  If
   4261 no @var{format} is given, the default format for the recording method
   4262 is used.  If no @var{method} is given, the default method will be used.
   4263 Returns a @code{gdb.Record} object on success.  Throw an exception on
   4264 failure.
   4265 
   4266 The following strings can be passed as @var{method}:
   4267 
   4268 @itemize @bullet
   4269 @item
   4270 @code{"full"}
   4271 @item
   4272 @code{"btrace"}: Possible values for @var{format}: @code{"pt"},
   4273 @code{"bts"} or leave out for default format.
   4274 @end itemize
   4275 @end defun
   4276 
   4277 @defun gdb.current_recording ()
   4278 Access a currently running recording.  Return a @code{gdb.Record}
   4279 object on success.  Return @code{None} if no recording is currently
   4280 active.
   4281 @end defun
   4282 
   4283 @defun gdb.stop_recording ()
   4284 Stop the current recording.  Throw an exception if no recording is
   4285 currently active.  All record objects become invalid after this call.
   4286 @end defun
   4287 
   4288 A @code{gdb.Record} object has the following attributes:
   4289 
   4290 @defvar Record.method
   4291 A string with the current recording method, e.g.@: @code{full} or
   4292 @code{btrace}.
   4293 @end defvar
   4294 
   4295 @defvar Record.format
   4296 A string with the current recording format, e.g.@: @code{bt}, @code{pts} or
   4297 @code{None}.
   4298 @end defvar
   4299 
   4300 @defvar Record.begin
   4301 A method specific instruction object representing the first instruction
   4302 in this recording.
   4303 @end defvar
   4304 
   4305 @defvar Record.end
   4306 A method specific instruction object representing the current
   4307 instruction, that is not actually part of the recording.
   4308 @end defvar
   4309 
   4310 @defvar Record.replay_position
   4311 The instruction representing the current replay position.  If there is
   4312 no replay active, this will be @code{None}.
   4313 @end defvar
   4314 
   4315 @defvar Record.instruction_history
   4316 A list with all recorded instructions.
   4317 @end defvar
   4318 
   4319 @defvar Record.function_call_history
   4320 A list with all recorded function call segments.
   4321 @end defvar
   4322 
   4323 A @code{gdb.Record} object has the following methods:
   4324 
   4325 @defun Record.goto (instruction)
   4326 Move the replay position to the given @var{instruction}.
   4327 @end defun
   4328 
   4329 @defun Record.clear ()
   4330 Clear the trace data of the current recording.  This forces re-decoding of the
   4331 trace for successive commands.
   4332 @end defun
   4333 
   4334 The common @code{gdb.Instruction} class that recording method specific
   4335 instruction objects inherit from, has the following attributes:
   4336 
   4337 @defvar Instruction.pc
   4338 An integer representing this instruction's address.
   4339 @end defvar
   4340 
   4341 @defvar Instruction.data
   4342 A @code{memoryview} object holding the raw instruction data.
   4343 @end defvar
   4344 
   4345 @defvar Instruction.decoded
   4346 A human readable string with the disassembled instruction.
   4347 @end defvar
   4348 
   4349 @defvar Instruction.size
   4350 The size of the instruction in bytes.
   4351 @end defvar
   4352 
   4353 Additionally @code{gdb.RecordInstruction} has the following attributes:
   4354 
   4355 @defvar RecordInstruction.number
   4356 An integer identifying this instruction.  @code{number} corresponds to
   4357 the numbers seen in @code{record instruction-history}
   4358 (@pxref{Process Record and Replay}).
   4359 @end defvar
   4360 
   4361 @defvar RecordInstruction.sal
   4362 A @code{gdb.Symtab_and_line} object representing the associated symtab
   4363 and line of this instruction.  May be @code{None} if no debug information is
   4364 available.
   4365 @end defvar
   4366 
   4367 @defvar RecordInstruction.is_speculative
   4368 A boolean indicating whether the instruction was executed speculatively.
   4369 @end defvar
   4370 
   4371 If an error occurred during recording or decoding a recording, this error is
   4372 represented by a @code{gdb.RecordGap} object in the instruction list.  It has
   4373 the following attributes:
   4374 
   4375 @defvar RecordGap.number
   4376 An integer identifying this gap.  @code{number} corresponds to the numbers seen
   4377 in @code{record instruction-history} (@pxref{Process Record and Replay}).
   4378 @end defvar
   4379 
   4380 @defvar RecordGap.error_code
   4381 A numerical representation of the reason for the gap.  The value is specific to
   4382 the current recording method.
   4383 @end defvar
   4384 
   4385 @defvar RecordGap.error_string
   4386 A human readable string with the reason for the gap.
   4387 @end defvar
   4388 
   4389 Some @value{GDBN} features write auxiliary information into the execution
   4390 history.  This information is represented by a @code{gdb.RecordAuxiliary} object
   4391 in the instruction list.  It has the following attributes:
   4392 
   4393 @defvar RecordAuxiliary.@var{number}
   4394 An integer identifying this auxiliary.  @var{number} corresponds to the numbers
   4395 seen in @code{record instruction-history} (@pxref{Process Record and Replay}).
   4396 @end defvar
   4397 
   4398 @defvar RecordAuxiliary.data
   4399 A string representation of the auxiliary data.
   4400 @end defvar
   4401 
   4402 A @code{gdb.RecordFunctionSegment} object has the following attributes:
   4403 
   4404 @defvar RecordFunctionSegment.number
   4405 An integer identifying this function segment.  @code{number} corresponds to
   4406 the numbers seen in @code{record function-call-history}
   4407 (@pxref{Process Record and Replay}).
   4408 @end defvar
   4409 
   4410 @defvar RecordFunctionSegment.symbol
   4411 A @code{gdb.Symbol} object representing the associated symbol.  May be
   4412 @code{None} if no debug information is available.
   4413 @end defvar
   4414 
   4415 @defvar RecordFunctionSegment.level
   4416 An integer representing the function call's stack level.  May be
   4417 @code{None} if the function call is a gap.
   4418 @end defvar
   4419 
   4420 @defvar RecordFunctionSegment.instructions
   4421 A list of @code{gdb.RecordInstruction} or @code{gdb.RecordGap} objects
   4422 associated with this function call.
   4423 @end defvar
   4424 
   4425 @defvar RecordFunctionSegment.up
   4426 A @code{gdb.RecordFunctionSegment} object representing the caller's
   4427 function segment.  If the call has not been recorded, this will be the
   4428 function segment to which control returns.  If neither the call nor the
   4429 return have been recorded, this will be @code{None}.
   4430 @end defvar
   4431 
   4432 @defvar RecordFunctionSegment.prev
   4433 A @code{gdb.RecordFunctionSegment} object representing the previous
   4434 segment of this function call.  May be @code{None}.
   4435 @end defvar
   4436 
   4437 @defvar RecordFunctionSegment.next
   4438 A @code{gdb.RecordFunctionSegment} object representing the next segment of
   4439 this function call.  May be @code{None}.
   4440 @end defvar
   4441 
   4442 The following example demonstrates the usage of these objects and
   4443 functions to create a function that will rewind a record to the last
   4444 time a function in a different file was executed.  This would typically
   4445 be used to track the execution of user provided callback functions in a
   4446 library which typically are not visible in a back trace.
   4447 
   4448 @smallexample
   4449 def bringback ():
   4450     rec = gdb.current_recording ()
   4451     if not rec:
   4452         return
   4453 
   4454     insn = rec.instruction_history
   4455     if len (insn) == 0:
   4456         return
   4457 
   4458     try:
   4459         position = insn.index (rec.replay_position)
   4460     except:
   4461         position = -1
   4462     try:
   4463         filename = insn[position].sal.symtab.fullname ()
   4464     except:
   4465         filename = None
   4466 
   4467     for i in reversed (insn[:position]):
   4468 	try:
   4469             current = i.sal.symtab.fullname ()
   4470 	except:
   4471             current = None
   4472 
   4473         if filename == current:
   4474             continue
   4475 
   4476         rec.goto (i)
   4477         return
   4478 @end smallexample
   4479 
   4480 Another possible application is to write a function that counts the
   4481 number of code executions in a given line range.  This line range can
   4482 contain parts of functions or span across several functions and is not
   4483 limited to be contiguous.
   4484 
   4485 @smallexample
   4486 def countrange (filename, linerange):
   4487     count = 0
   4488 
   4489     def filter_only (file_name):
   4490         for call in gdb.current_recording ().function_call_history:
   4491             try:
   4492                 if file_name in call.symbol.symtab.fullname ():
   4493                     yield call
   4494             except:
   4495                 pass
   4496 
   4497     for c in filter_only (filename):
   4498         for i in c.instructions:
   4499             try:
   4500                 if i.sal.line in linerange:
   4501                     count += 1
   4502                     break;
   4503             except:
   4504                     pass
   4505 
   4506     return count
   4507 @end smallexample
   4508 
   4509 @node CLI Commands In Python
   4510 @subsubsection CLI Commands In Python
   4511 
   4512 @cindex CLI commands in python
   4513 @cindex commands in python, CLI
   4514 @cindex python commands, CLI
   4515 You can implement new @value{GDBN} CLI commands in Python.  A CLI
   4516 command is implemented using an instance of the @code{gdb.Command}
   4517 class, most commonly using a subclass.
   4518 
   4519 @defun Command.__init__ (name, command_class @r{[}, completer_class @r{[}, prefix@r{]]})
   4520 The object initializer for @code{Command} registers the new command
   4521 with @value{GDBN}.  This initializer is normally invoked from the
   4522 subclass' own @code{__init__} method.
   4523 
   4524 @var{name} is the name of the command.  If @var{name} consists of
   4525 multiple words, then the initial words are looked for as prefix
   4526 commands.  In this case, if one of the prefix commands does not exist,
   4527 an exception is raised.
   4528 
   4529 There is no support for multi-line commands.
   4530 
   4531 @var{command_class} should be one of the @samp{COMMAND_} constants
   4532 defined below.  This argument tells @value{GDBN} how to categorize the
   4533 new command in the help system.
   4534 
   4535 @var{completer_class} is an optional argument.  If given, it should be
   4536 one of the @samp{COMPLETE_} constants defined below.  This argument
   4537 tells @value{GDBN} how to perform completion for this command.  If not
   4538 given, @value{GDBN} will attempt to complete using the object's
   4539 @code{complete} method (see below); if no such method is found, an
   4540 error will occur when completion is attempted.
   4541 
   4542 @var{prefix} is an optional argument.  If @code{True}, then the new
   4543 command is a prefix command; sub-commands of this command may be
   4544 registered.
   4545 
   4546 The help text for the new command is taken from the Python
   4547 documentation string for the command's class, if there is one.  If no
   4548 documentation string is provided, the default value ``This command is
   4549 not documented.'' is used.
   4550 @end defun
   4551 
   4552 @cindex don't repeat Python command
   4553 @defun Command.dont_repeat ()
   4554 By default, a @value{GDBN} command is repeated when the user enters a
   4555 blank line at the command prompt.  A command can suppress this
   4556 behavior by invoking the @code{dont_repeat} method at some point in
   4557 its @code{invoke} method (normally this is done early in case of
   4558 exception).  This is similar to the user command @code{dont-repeat},
   4559 see @ref{Define, dont-repeat}.
   4560 @end defun
   4561 
   4562 @defun Command.invoke (argument, from_tty)
   4563 This method is called by @value{GDBN} when this command is invoked.
   4564 
   4565 @var{argument} is a string.  It is the argument to the command, after
   4566 leading and trailing whitespace has been stripped.
   4567 
   4568 @var{from_tty} is a boolean argument.  When true, this means that the
   4569 command was entered by the user at the terminal; when false it means
   4570 that the command came from elsewhere.
   4571 
   4572 If this method throws an exception, it is turned into a @value{GDBN}
   4573 @code{error} call.  Otherwise, the return value is ignored.
   4574 
   4575 @findex gdb.string_to_argv
   4576 To break @var{argument} up into an argv-like string use
   4577 @code{gdb.string_to_argv}.  This function behaves identically to
   4578 @value{GDBN}'s internal argument lexer @code{buildargv}.
   4579 It is recommended to use this for consistency.
   4580 Arguments are separated by spaces and may be quoted.
   4581 Example:
   4582 
   4583 @smallexample
   4584 print gdb.string_to_argv ("1 2\ \\\"3 '4 \"5' \"6 '7\"")
   4585 ['1', '2 "3', '4 "5', "6 '7"]
   4586 @end smallexample
   4587 
   4588 @end defun
   4589 
   4590 @cindex completion of Python commands
   4591 @defun Command.complete (text, word)
   4592 This method is called by @value{GDBN} when the user attempts
   4593 completion on this command.  All forms of completion are handled by
   4594 this method, that is, the @key{TAB} and @key{M-?} key bindings
   4595 (@pxref{Completion}), and the @code{complete} command (@pxref{Help,
   4596 complete}).
   4597 
   4598 The arguments @var{text} and @var{word} are both strings; @var{text}
   4599 holds the complete command line up to the cursor's location, while
   4600 @var{word} holds the last word of the command line; this is computed
   4601 using a word-breaking heuristic.
   4602 
   4603 The @code{complete} method can return several values:
   4604 @itemize @bullet
   4605 @item
   4606 If the return value is a sequence, the contents of the sequence are
   4607 used as the completions.  It is up to @code{complete} to ensure that the
   4608 contents actually do complete the word.  A zero-length sequence is
   4609 allowed, it means that there were no completions available.  Only
   4610 string elements of the sequence are used; other elements in the
   4611 sequence are ignored.
   4612 
   4613 @item
   4614 If the return value is one of the @samp{COMPLETE_} constants defined
   4615 below, then the corresponding @value{GDBN}-internal completion
   4616 function is invoked, and its result is used.
   4617 
   4618 @item
   4619 All other results are treated as though there were no available
   4620 completions.
   4621 @end itemize
   4622 @end defun
   4623 
   4624 When a new command is registered, it must be declared as a member of
   4625 some general class of commands.  This is used to classify top-level
   4626 commands in the on-line help system; note that prefix commands are not
   4627 listed under their own category but rather that of their top-level
   4628 command.  The available classifications are represented by constants
   4629 defined in the @code{gdb} module:
   4630 
   4631 @table @code
   4632 @findex COMMAND_NONE
   4633 @findex gdb.COMMAND_NONE
   4634 @item gdb.COMMAND_NONE
   4635 The command does not belong to any particular class.  A command in
   4636 this category will not be displayed in any of the help categories.
   4637 
   4638 @findex COMMAND_RUNNING
   4639 @findex gdb.COMMAND_RUNNING
   4640 @item gdb.COMMAND_RUNNING
   4641 The command is related to running the inferior.  For example,
   4642 @code{start}, @code{step}, and @code{continue} are in this category.
   4643 Type @kbd{help running} at the @value{GDBN} prompt to see a list of
   4644 commands in this category.
   4645 
   4646 @findex COMMAND_DATA
   4647 @findex gdb.COMMAND_DATA
   4648 @item gdb.COMMAND_DATA
   4649 The command is related to data or variables.  For example,
   4650 @code{call}, @code{find}, and @code{print} are in this category.  Type
   4651 @kbd{help data} at the @value{GDBN} prompt to see a list of commands
   4652 in this category.
   4653 
   4654 @findex COMMAND_STACK
   4655 @findex gdb.COMMAND_STACK
   4656 @item gdb.COMMAND_STACK
   4657 The command has to do with manipulation of the stack.  For example,
   4658 @code{backtrace}, @code{frame}, and @code{return} are in this
   4659 category.  Type @kbd{help stack} at the @value{GDBN} prompt to see a
   4660 list of commands in this category.
   4661 
   4662 @findex COMMAND_FILES
   4663 @findex gdb.COMMAND_FILES
   4664 @item gdb.COMMAND_FILES
   4665 This class is used for file-related commands.  For example,
   4666 @code{file}, @code{list} and @code{section} are in this category.
   4667 Type @kbd{help files} at the @value{GDBN} prompt to see a list of
   4668 commands in this category.
   4669 
   4670 @findex COMMAND_SUPPORT
   4671 @findex gdb.COMMAND_SUPPORT
   4672 @item gdb.COMMAND_SUPPORT
   4673 This should be used for ``support facilities'', generally meaning
   4674 things that are useful to the user when interacting with @value{GDBN},
   4675 but not related to the state of the inferior.  For example,
   4676 @code{help}, @code{make}, and @code{shell} are in this category.  Type
   4677 @kbd{help support} at the @value{GDBN} prompt to see a list of
   4678 commands in this category.
   4679 
   4680 @findex COMMAND_STATUS
   4681 @findex gdb.COMMAND_STATUS
   4682 @item gdb.COMMAND_STATUS
   4683 The command is an @samp{info}-related command, that is, related to the
   4684 state of @value{GDBN} itself.  For example, @code{info}, @code{macro},
   4685 and @code{show} are in this category.  Type @kbd{help status} at the
   4686 @value{GDBN} prompt to see a list of commands in this category.
   4687 
   4688 @findex COMMAND_BREAKPOINTS
   4689 @findex gdb.COMMAND_BREAKPOINTS
   4690 @item gdb.COMMAND_BREAKPOINTS
   4691 The command has to do with breakpoints.  For example, @code{break},
   4692 @code{clear}, and @code{delete} are in this category.  Type @kbd{help
   4693 breakpoints} at the @value{GDBN} prompt to see a list of commands in
   4694 this category.
   4695 
   4696 @findex COMMAND_TRACEPOINTS
   4697 @findex gdb.COMMAND_TRACEPOINTS
   4698 @item gdb.COMMAND_TRACEPOINTS
   4699 The command has to do with tracepoints.  For example, @code{trace},
   4700 @code{actions}, and @code{tfind} are in this category.  Type
   4701 @kbd{help tracepoints} at the @value{GDBN} prompt to see a list of
   4702 commands in this category.
   4703 
   4704 @findex COMMAND_TUI
   4705 @findex gdb.COMMAND_TUI
   4706 @item gdb.COMMAND_TUI
   4707 The command has to do with the text user interface (@pxref{TUI}).
   4708 Type @kbd{help tui} at the @value{GDBN} prompt to see a list of
   4709 commands in this category.
   4710 
   4711 @findex COMMAND_USER
   4712 @findex gdb.COMMAND_USER
   4713 @item gdb.COMMAND_USER
   4714 The command is a general purpose command for the user, and typically
   4715 does not fit in one of the other categories.
   4716 Type @kbd{help user-defined} at the @value{GDBN} prompt to see
   4717 a list of commands in this category, as well as the list of gdb macros
   4718 (@pxref{Sequences}).
   4719 
   4720 @findex COMMAND_OBSCURE
   4721 @findex gdb.COMMAND_OBSCURE
   4722 @item gdb.COMMAND_OBSCURE
   4723 The command is only used in unusual circumstances, or is not of
   4724 general interest to users.  For example, @code{checkpoint},
   4725 @code{fork}, and @code{stop} are in this category.  Type @kbd{help
   4726 obscure} at the @value{GDBN} prompt to see a list of commands in this
   4727 category.
   4728 
   4729 @findex COMMAND_MAINTENANCE
   4730 @findex gdb.COMMAND_MAINTENANCE
   4731 @item gdb.COMMAND_MAINTENANCE
   4732 The command is only useful to @value{GDBN} maintainers.  The
   4733 @code{maintenance} and @code{flushregs} commands are in this category.
   4734 Type @kbd{help internals} at the @value{GDBN} prompt to see a list of
   4735 commands in this category.
   4736 @end table
   4737 
   4738 A new command can use a predefined completion function, either by
   4739 specifying it via an argument at initialization, or by returning it
   4740 from the @code{complete} method.  These predefined completion
   4741 constants are all defined in the @code{gdb} module:
   4742 
   4743 @vtable @code
   4744 @vindex COMPLETE_NONE
   4745 @item gdb.COMPLETE_NONE
   4746 This constant means that no completion should be done.
   4747 
   4748 @vindex COMPLETE_FILENAME
   4749 @item gdb.COMPLETE_FILENAME
   4750 This constant means that filename completion should be performed.
   4751 
   4752 @vindex COMPLETE_LOCATION
   4753 @item gdb.COMPLETE_LOCATION
   4754 This constant means that location completion should be done.
   4755 @xref{Location Specifications}.
   4756 
   4757 @vindex COMPLETE_COMMAND
   4758 @item gdb.COMPLETE_COMMAND
   4759 This constant means that completion should examine @value{GDBN}
   4760 command names.
   4761 
   4762 @vindex COMPLETE_SYMBOL
   4763 @item gdb.COMPLETE_SYMBOL
   4764 This constant means that completion should be done using symbol names
   4765 as the source.
   4766 
   4767 @vindex COMPLETE_EXPRESSION
   4768 @item gdb.COMPLETE_EXPRESSION
   4769 This constant means that completion should be done on expressions.
   4770 Often this means completing on symbol names, but some language
   4771 parsers also have support for completing on field names.
   4772 @end vtable
   4773 
   4774 The following code snippet shows how a trivial CLI command can be
   4775 implemented in Python:
   4776 
   4777 @smallexample
   4778 class HelloWorld (gdb.Command):
   4779   """Greet the whole world."""
   4780 
   4781   def __init__ (self):
   4782     super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
   4783 
   4784   def invoke (self, arg, from_tty):
   4785     print ("Hello, World!")
   4786 
   4787 HelloWorld ()
   4788 @end smallexample
   4789 
   4790 The last line instantiates the class, and is necessary to trigger the
   4791 registration of the command with @value{GDBN}.  Depending on how the
   4792 Python code is read into @value{GDBN}, you may need to import the
   4793 @code{gdb} module explicitly.
   4794 
   4795 @node GDB/MI Commands In Python
   4796 @subsubsection @sc{gdb/mi} Commands In Python
   4797 
   4798 @cindex MI commands in python
   4799 @cindex commands in python, GDB/MI
   4800 @cindex python commands, GDB/MI
   4801 It is possible to add @sc{gdb/mi} (@pxref{GDB/MI}) commands
   4802 implemented in Python.  A @sc{gdb/mi} command is implemented using an
   4803 instance of the @code{gdb.MICommand} class, most commonly using a
   4804 subclass.
   4805 
   4806 @defun MICommand.__init__ (name)
   4807 The object initializer for @code{MICommand} registers the new command
   4808 with @value{GDBN}.  This initializer is normally invoked from the
   4809 subclass' own @code{__init__} method.
   4810 
   4811 @var{name} is the name of the command.  It must be a valid name of a
   4812 @sc{gdb/mi} command, and in particular must start with a hyphen
   4813 (@code{-}).  Reusing the name of a built-in @sc{gdb/mi} is not
   4814 allowed, and a @code{RuntimeError} will be raised.  Using the name
   4815 of an @sc{gdb/mi} command previously defined in Python is allowed, the
   4816 previous command will be replaced with the new command.
   4817 @end defun
   4818 
   4819 @defun MICommand.invoke (arguments)
   4820 This method is called by @value{GDBN} when the new MI command is
   4821 invoked.
   4822 
   4823 @var{arguments} is a list of strings.  Note, that @code{--thread}
   4824 and @code{--frame} arguments are handled by @value{GDBN} itself therefore
   4825 they do not show up in @code{arguments}.
   4826 
   4827 If this method raises an exception, then it is turned into a
   4828 @sc{gdb/mi} @code{^error} response.  Only @code{gdb.GdbError}
   4829 exceptions (or its sub-classes) should be used for reporting errors to
   4830 users, any other exception type is treated as a failure of the
   4831 @code{invoke} method, and the exception will be printed to the error
   4832 stream according to the @kbd{set python print-stack} setting
   4833 (@pxref{set_python_print_stack,,@kbd{set python print-stack}}).
   4834 
   4835 If this method returns @code{None}, then the @sc{gdb/mi} command will
   4836 return a @code{^done} response with no additional values.
   4837 
   4838 Otherwise, the return value must be a dictionary, which is converted
   4839 to a @sc{gdb/mi} @var{result-record} (@pxref{GDB/MI Output Syntax}).
   4840 The keys of this dictionary must be strings, and are used as
   4841 @var{variable} names in the @var{result-record}, these strings must
   4842 comply with the naming rules detailed below.  The values of this
   4843 dictionary are recursively handled as follows:
   4844 
   4845 @itemize
   4846 @item
   4847 If the value is Python sequence or iterator, it is converted to
   4848 @sc{gdb/mi} @var{list} with elements converted recursively.
   4849 
   4850 @item
   4851 If the value is Python dictionary, it is converted to
   4852 @sc{gdb/mi} @var{tuple}.  Keys in that dictionary must be strings,
   4853 which comply with the @var{variable} naming rules detailed below.
   4854 Values are converted recursively.
   4855 
   4856 @item
   4857 Otherwise, value is first converted to a Python string using
   4858 @code{str ()} and then converted to @sc{gdb/mi} @var{const}.
   4859 @end itemize
   4860 
   4861 The strings used for @var{variable} names in the @sc{gdb/mi} output
   4862 must follow the following rules; the string must be at least one
   4863 character long, the first character must be in the set
   4864 @code{[a-zA-Z]}, while every subsequent character must be in the set
   4865 @code{[-_a-zA-Z0-9]}.
   4866 @end defun
   4867 
   4868 An instance of @code{MICommand} has the following attributes:
   4869 
   4870 @defvar MICommand.name
   4871 A string, the name of this @sc{gdb/mi} command, as was passed to the
   4872 @code{__init__} method.  This attribute is read-only.
   4873 @end defvar
   4874 
   4875 @defvar MICommand.installed
   4876 A boolean value indicating if this command is installed ready for a
   4877 user to call from the command line.  Commands are automatically
   4878 installed when they are instantiated, after which this attribute will
   4879 be @code{True}.
   4880 
   4881 If later, a new command is created with the same name, then the
   4882 original command will become uninstalled, and this attribute will be
   4883 @code{False}.
   4884 
   4885 This attribute is read-write, setting this attribute to @code{False}
   4886 will uninstall the command, removing it from the set of available
   4887 commands.  Setting this attribute to @code{True} will install the
   4888 command for use.  If there is already a Python command with this name
   4889 installed, the currently installed command will be uninstalled, and
   4890 this command installed in its stead.
   4891 @end defvar
   4892 
   4893 The following code snippet shows how some trivial MI commands can be
   4894 implemented in Python:
   4895 
   4896 @smallexample
   4897 class MIEcho(gdb.MICommand):
   4898     """Echo arguments passed to the command."""
   4899 
   4900     def __init__(self, name, mode):
   4901         self._mode = mode
   4902         super(MIEcho, self).__init__(name)
   4903 
   4904     def invoke(self, argv):
   4905         if self._mode == 'dict':
   4906             return @{ 'dict': @{ 'argv' : argv @} @}
   4907         elif self._mode == 'list':
   4908             return @{ 'list': argv @}
   4909         else:
   4910             return @{ 'string': ", ".join(argv) @}
   4911 
   4912 
   4913 MIEcho("-echo-dict", "dict")
   4914 MIEcho("-echo-list", "list")
   4915 MIEcho("-echo-string", "string")
   4916 @end smallexample
   4917 
   4918 The last three lines instantiate the class three times, creating three
   4919 new @sc{gdb/mi} commands @code{-echo-dict}, @code{-echo-list}, and
   4920 @code{-echo-string}.  Each time a subclass of @code{gdb.MICommand} is
   4921 instantiated, the new command is automatically registered with
   4922 @value{GDBN}.
   4923 
   4924 Depending on how the Python code is read into @value{GDBN}, you may
   4925 need to import the @code{gdb} module explicitly.
   4926 
   4927 The following example shows a @value{GDBN} session in which the above
   4928 commands have been added:
   4929 
   4930 @smallexample
   4931 (@value{GDBP})
   4932 -echo-dict abc def ghi
   4933 ^done,dict=@{argv=["abc","def","ghi"]@}
   4934 (@value{GDBP})
   4935 -echo-list abc def ghi
   4936 ^done,list=["abc","def","ghi"]
   4937 (@value{GDBP})
   4938 -echo-string abc def ghi
   4939 ^done,string="abc, def, ghi"
   4940 (@value{GDBP})
   4941 @end smallexample
   4942 
   4943 Conversely, it is possible to execute @sc{gdb/mi} commands from
   4944 Python, with the results being a Python object and not a
   4945 specially-formatted string.  This is done with the
   4946 @code{gdb.execute_mi} function.
   4947 
   4948 @defun gdb.execute_mi (command @r{[}, arg @r{]}@dots{})
   4949 Invoke a @sc{gdb/mi} command.  @var{command} is the name of the
   4950 command, a string.  The arguments, @var{arg}, are passed to the
   4951 command.  Each argument must also be a string.
   4952 
   4953 This function returns a Python dictionary whose contents reflect the
   4954 corresponding @sc{GDB/MI} command's output.  Refer to the
   4955 documentation for these commands for details.  Lists are represented
   4956 as Python lists, and tuples are represented as Python dictionaries.
   4957 
   4958 If the command fails, it will raise a Python exception.
   4959 @end defun
   4960 
   4961 Here is how this works using the commands from the example above:
   4962 
   4963 @smallexample
   4964 (@value{GDBP}) python print(gdb.execute_mi("-echo-dict", "abc", "def", "ghi"))
   4965 @{'dict': @{'argv': ['abc', 'def', 'ghi']@}@}
   4966 (@value{GDBP}) python print(gdb.execute_mi("-echo-list", "abc", "def", "ghi"))
   4967 @{'list': ['abc', 'def', 'ghi']@}
   4968 (@value{GDBP}) python print(gdb.execute_mi("-echo-string", "abc", "def", "ghi"))
   4969 @{'string': 'abc, def, ghi'@}
   4970 @end smallexample
   4971 
   4972 @node GDB/MI Notifications In Python
   4973 @subsubsection @sc{gdb/mi} Notifications In Python
   4974 
   4975 @cindex MI notifications in python
   4976 @cindex notifications in python, GDB/MI
   4977 @cindex python notifications, GDB/MI
   4978 
   4979 It is possible to emit @sc{gdb/mi} notifications from
   4980 Python.  Use the @code{gdb.notify_mi} function to do that.
   4981 
   4982 @defun gdb.notify_mi (name @r{[}, data@r{]})
   4983 Emit a @sc{gdb/mi} asynchronous notification.  @var{name} is the name of the
   4984 notification, consisting of alphanumeric characters and a hyphen (@code{-}).
   4985 @var{data} is any additional data to be emitted with the notification, passed
   4986 as a Python dictionary. This argument is optional. The dictionary is converted
   4987 to a @sc{gdb/mi} @var{result} records (@pxref{GDB/MI Output Syntax}) the same way
   4988 as result of Python MI command (@pxref{GDB/MI Commands In Python}).
   4989 
   4990 If @var{data} is @code{None} then no additional values are emitted.
   4991 @end defun
   4992 
   4993 While using existing notification names (@pxref{GDB/MI Async Records}) with
   4994 @code{gdb.notify_mi} is allowed, users are encouraged to prefix user-defined
   4995 notification with a hyphen (@code{-}) to avoid possible conflict.
   4996 @value{GDBN} will never introduce notification starting with hyphen.
   4997 
   4998 Here is how to emit @code{=-connection-removed} whenever a connection to remote
   4999 GDB server is closed (@pxref{Connections In Python}):
   5000 
   5001 @smallexample
   5002 def notify_connection_removed(event):
   5003     data = @{"id": event.connection.num, "type": event.connection.type@}
   5004     gdb.notify_mi("-connection-removed", data)
   5005 
   5006 
   5007 gdb.events.connection_removed.connect(notify_connection_removed)
   5008 @end smallexample
   5009 
   5010 Then, each time a connection is closed, there will be a notification on MI channel:
   5011 
   5012 @smallexample
   5013 =-connection-removed,id="1",type="remote"
   5014 @end smallexample
   5015 
   5016 @node Parameters In Python
   5017 @subsubsection Parameters In Python
   5018 
   5019 @cindex parameters in python
   5020 @cindex python parameters
   5021 @tindex gdb.Parameter
   5022 @tindex Parameter
   5023 You can implement new @value{GDBN} parameters using Python.  A new
   5024 parameter is implemented as an instance of the @code{gdb.Parameter}
   5025 class.
   5026 
   5027 Parameters are exposed to the user via the @code{set} and
   5028 @code{show} commands.  @xref{Help}.
   5029 
   5030 There are many parameters that already exist and can be set in
   5031 @value{GDBN}.  Two examples are: @code{set follow fork} and
   5032 @code{set charset}.  Setting these parameters influences certain
   5033 behavior in @value{GDBN}.  Similarly, you can define parameters that
   5034 can be used to influence behavior in custom Python scripts and commands.
   5035 
   5036 @defun Parameter.__init__ (name, command_class, parameter_class @r{[}, enum_sequence@r{]})
   5037 The object initializer for @code{Parameter} registers the new
   5038 parameter with @value{GDBN}.  This initializer is normally invoked
   5039 from the subclass' own @code{__init__} method.
   5040 
   5041 @var{name} is the name of the new parameter.  If @var{name} consists
   5042 of multiple words, then the initial words are looked for as prefix
   5043 parameters.  An example of this can be illustrated with the
   5044 @code{set print} set of parameters.  If @var{name} is
   5045 @code{print foo}, then @code{print} will be searched as the prefix
   5046 parameter.  In this case the parameter can subsequently be accessed in
   5047 @value{GDBN} as @code{set print foo}.
   5048 
   5049 If @var{name} consists of multiple words, and no prefix parameter group
   5050 can be found, an exception is raised.
   5051 
   5052 @var{command_class} should be one of the @samp{COMMAND_} constants
   5053 (@pxref{CLI Commands In Python}).  This argument tells @value{GDBN} how to
   5054 categorize the new parameter in the help system.
   5055 
   5056 @var{parameter_class} should be one of the @samp{PARAM_} constants
   5057 defined below.  This argument tells @value{GDBN} the type of the new
   5058 parameter; this information is used for input validation and
   5059 completion.
   5060 
   5061 If @var{parameter_class} is @code{PARAM_ENUM}, then
   5062 @var{enum_sequence} must be a sequence of strings.  These strings
   5063 represent the possible values for the parameter.
   5064 
   5065 If @var{parameter_class} is not @code{PARAM_ENUM}, then the presence
   5066 of a fourth argument will cause an exception to be thrown.
   5067 
   5068 The help text for the new parameter includes the Python documentation
   5069 string from the parameter's class, if there is one.  If there is no
   5070 documentation string, a default value is used.  The documentation
   5071 string is included in the output of the parameters @code{help set} and
   5072 @code{help show} commands, and should be written taking this into
   5073 account.
   5074 @end defun
   5075 
   5076 @defvar Parameter.set_doc
   5077 If this attribute exists, and is a string, then its value is used as
   5078 the first part of the help text for this parameter's @code{set}
   5079 command.  The second part of the help text is taken from the
   5080 documentation string for the parameter's class, if there is one.
   5081 
   5082 The value of @code{set_doc} should give a brief summary specific to
   5083 the set action, this text is only displayed when the user runs the
   5084 @code{help set} command for this parameter.  The class documentation
   5085 should be used to give a fuller description of what the parameter
   5086 does, this text is displayed for both the @code{help set} and
   5087 @code{help show} commands.
   5088 
   5089 The @code{set_doc} value is examined when @code{Parameter.__init__} is
   5090 invoked; subsequent changes have no effect.
   5091 @end defvar
   5092 
   5093 @defvar Parameter.show_doc
   5094 If this attribute exists, and is a string, then its value is used as
   5095 the first part of the help text for this parameter's @code{show}
   5096 command.  The second part of the help text is taken from the
   5097 documentation string for the parameter's class, if there is one.
   5098 
   5099 The value of @code{show_doc} should give a brief summary specific to
   5100 the show action, this text is only displayed when the user runs the
   5101 @code{help show} command for this parameter.  The class documentation
   5102 should be used to give a fuller description of what the parameter
   5103 does, this text is displayed for both the @code{help set} and
   5104 @code{help show} commands.
   5105 
   5106 The @code{show_doc} value is examined when @code{Parameter.__init__}
   5107 is invoked; subsequent changes have no effect.
   5108 @end defvar
   5109 
   5110 @defvar Parameter.value
   5111 The @code{value} attribute holds the underlying value of the
   5112 parameter.  It can be read and assigned to just as any other
   5113 attribute.  @value{GDBN} does validation when assignments are made.
   5114 @end defvar
   5115 
   5116 There are two methods that may be implemented in any @code{Parameter}
   5117 class.  These are:
   5118 
   5119 @defun Parameter.get_set_string (self)
   5120 If this method exists, @value{GDBN} will call it when a
   5121 @var{parameter}'s value has been changed via the @code{set} API (for
   5122 example, @kbd{set foo off}).  The @code{value} attribute has already
   5123 been populated with the new value and may be used in output.  This
   5124 method must return a string.  If the returned string is not empty,
   5125 @value{GDBN} will present it to the user.
   5126 
   5127 If this method raises the @code{gdb.GdbError} exception
   5128 (@pxref{Exception Handling}), then @value{GDBN} will print the
   5129 exception's string and the @code{set} command will fail.  Note,
   5130 however, that the @code{value} attribute will not be reset in this
   5131 case.  So, if your parameter must validate values, it should store the
   5132 old value internally and reset the exposed value, like so:
   5133 
   5134 @smallexample
   5135 class ExampleParam (gdb.Parameter):
   5136    def __init__ (self, name):
   5137       super (ExampleParam, self).__init__ (name,
   5138                    gdb.COMMAND_DATA,
   5139                    gdb.PARAM_BOOLEAN)
   5140       self.value = True
   5141       self.saved_value = True
   5142    def validate(self):
   5143       return False
   5144    def get_set_string (self):
   5145       if not self.validate():
   5146         self.value = self.saved_value
   5147         raise gdb.GdbError('Failed to validate')
   5148       self.saved_value = self.value
   5149       return ""
   5150 @end smallexample
   5151 @end defun
   5152 
   5153 @defun Parameter.get_show_string (self, svalue)
   5154 @value{GDBN} will call this method when a @var{parameter}'s
   5155 @code{show} API has been invoked (for example, @kbd{show foo}).  The
   5156 argument @code{svalue} receives the string representation of the
   5157 current value.  This method must return a string.
   5158 @end defun
   5159 
   5160 When a new parameter is defined, its type must be specified.  The
   5161 available types are represented by constants defined in the @code{gdb}
   5162 module:
   5163 
   5164 @table @code
   5165 @findex PARAM_BOOLEAN
   5166 @findex gdb.PARAM_BOOLEAN
   5167 @item gdb.PARAM_BOOLEAN
   5168 The value is a plain boolean.  The Python boolean values, @code{True}
   5169 and @code{False} are the only valid values.
   5170 
   5171 @findex PARAM_AUTO_BOOLEAN
   5172 @findex gdb.PARAM_AUTO_BOOLEAN
   5173 @item gdb.PARAM_AUTO_BOOLEAN
   5174 The value has three possible states: true, false, and @samp{auto}.  In
   5175 Python, true and false are represented using boolean constants, and
   5176 @samp{auto} is represented using @code{None}.
   5177 
   5178 @findex PARAM_UINTEGER
   5179 @findex gdb.PARAM_UINTEGER
   5180 @item gdb.PARAM_UINTEGER
   5181 The value is an unsigned integer.  The value of @code{None} should be
   5182 interpreted to mean ``unlimited'' (literal @code{'unlimited'} can also
   5183 be used to set that value), and the value of 0 is reserved and should
   5184 not be used.
   5185 
   5186 @findex PARAM_INTEGER
   5187 @findex gdb.PARAM_INTEGER
   5188 @item gdb.PARAM_INTEGER
   5189 The value is a signed integer.  The value of @code{None} should be
   5190 interpreted to mean ``unlimited'' (literal @code{'unlimited'} can also
   5191 be used to set that value), and the value of 0 is reserved and should
   5192 not be used.
   5193 
   5194 @findex PARAM_STRING
   5195 @findex gdb.PARAM_STRING
   5196 @item gdb.PARAM_STRING
   5197 The value is a string.  When the user modifies the string, any escape
   5198 sequences, such as @samp{\t}, @samp{\f}, and octal escapes, are
   5199 translated into corresponding characters and encoded into the current
   5200 host charset.
   5201 
   5202 @findex PARAM_STRING_NOESCAPE
   5203 @findex gdb.PARAM_STRING_NOESCAPE
   5204 @item gdb.PARAM_STRING_NOESCAPE
   5205 The value is a string.  When the user modifies the string, escapes are
   5206 passed through untranslated.
   5207 
   5208 @findex PARAM_OPTIONAL_FILENAME
   5209 @findex gdb.PARAM_OPTIONAL_FILENAME
   5210 @item gdb.PARAM_OPTIONAL_FILENAME
   5211 The value is a either a filename (a string), or @code{None}.
   5212 
   5213 @findex PARAM_FILENAME
   5214 @findex gdb.PARAM_FILENAME
   5215 @item gdb.PARAM_FILENAME
   5216 The value is a filename.  This is just like
   5217 @code{PARAM_STRING_NOESCAPE}, but uses file names for completion.
   5218 
   5219 @findex PARAM_ZINTEGER
   5220 @findex gdb.PARAM_ZINTEGER
   5221 @item gdb.PARAM_ZINTEGER
   5222 The value is a signed integer.  This is like @code{PARAM_INTEGER},
   5223 except that 0 is allowed and the value of @code{None} is not supported.
   5224 
   5225 @findex PARAM_ZUINTEGER
   5226 @findex gdb.PARAM_ZUINTEGER
   5227 @item gdb.PARAM_ZUINTEGER
   5228 The value is an unsigned integer.  This is like @code{PARAM_UINTEGER},
   5229 except that 0 is allowed and the value of @code{None} is not supported.
   5230 
   5231 @findex PARAM_ZUINTEGER_UNLIMITED
   5232 @findex gdb.PARAM_ZUINTEGER_UNLIMITED
   5233 @item gdb.PARAM_ZUINTEGER_UNLIMITED
   5234 The value is a signed integer.  This is like @code{PARAM_INTEGER}
   5235 including that the value of @code{None} should be interpreted to mean
   5236 ``unlimited'' (literal @code{'unlimited'} can also be used to set that
   5237 value), except that 0 is allowed, and the value cannot be negative,
   5238 except the special value -1 is returned for the setting of ``unlimited''.
   5239 
   5240 @findex PARAM_ENUM
   5241 @findex gdb.PARAM_ENUM
   5242 @item gdb.PARAM_ENUM
   5243 The value is a string, which must be one of a collection string
   5244 constants provided when the parameter is created.
   5245 @end table
   5246 
   5247 @node Functions In Python
   5248 @subsubsection Writing new convenience functions
   5249 
   5250 @cindex writing convenience functions
   5251 @cindex convenience functions in python
   5252 @cindex python convenience functions
   5253 @tindex gdb.Function
   5254 @tindex Function
   5255 You can implement new convenience functions (@pxref{Convenience Vars})
   5256 in Python.  A convenience function is an instance of a subclass of the
   5257 class @code{gdb.Function}.
   5258 
   5259 @defun Function.__init__ (name)
   5260 The initializer for @code{Function} registers the new function with
   5261 @value{GDBN}.  The argument @var{name} is the name of the function,
   5262 a string.  The function will be visible to the user as a convenience
   5263 variable of type @code{internal function}, whose name is the same as
   5264 the given @var{name}.
   5265 
   5266 The documentation for the new function is taken from the documentation
   5267 string for the new class.
   5268 @end defun
   5269 
   5270 @defun Function.invoke (*args)
   5271 When a convenience function is evaluated, its arguments are converted
   5272 to instances of @code{gdb.Value}, and then the function's
   5273 @code{invoke} method is called.  Note that @value{GDBN} does not
   5274 predetermine the arity of convenience functions.  Instead, all
   5275 available arguments are passed to @code{invoke}, following the
   5276 standard Python calling convention.  In particular, a convenience
   5277 function can have default values for parameters without ill effect.
   5278 
   5279 The return value of this method is used as its value in the enclosing
   5280 expression.  If an ordinary Python value is returned, it is converted
   5281 to a @code{gdb.Value} following the usual rules.
   5282 @end defun
   5283 
   5284 The following code snippet shows how a trivial convenience function can
   5285 be implemented in Python:
   5286 
   5287 @smallexample
   5288 class Greet (gdb.Function):
   5289   """Return string to greet someone.
   5290 Takes a name as argument."""
   5291 
   5292   def __init__ (self):
   5293     super (Greet, self).__init__ ("greet")
   5294 
   5295   def invoke (self, name):
   5296     return "Hello, %s!" % name.string ()
   5297 
   5298 Greet ()
   5299 @end smallexample
   5300 
   5301 The last line instantiates the class, and is necessary to trigger the
   5302 registration of the function with @value{GDBN}.  Depending on how the
   5303 Python code is read into @value{GDBN}, you may need to import the
   5304 @code{gdb} module explicitly.
   5305 
   5306 Now you can use the function in an expression:
   5307 
   5308 @smallexample
   5309 (gdb) print $greet("Bob")
   5310 $1 = "Hello, Bob!"
   5311 @end smallexample
   5312 
   5313 @node Progspaces In Python
   5314 @subsubsection Program Spaces In Python
   5315 
   5316 @cindex progspaces in python
   5317 @tindex gdb.Progspace
   5318 @tindex Progspace
   5319 A program space, or @dfn{progspace}, represents a symbolic view
   5320 of an address space.
   5321 It consists of all of the objfiles of the program.
   5322 @xref{Objfiles In Python}.
   5323 @xref{Inferiors Connections and Programs, program spaces}, for more details
   5324 about program spaces.
   5325 
   5326 The following progspace-related functions are available in the
   5327 @code{gdb} module:
   5328 
   5329 @defun gdb.current_progspace ()
   5330 This function returns the program space of the currently selected inferior.
   5331 @xref{Inferiors Connections and Programs}.  This is identical to
   5332 @code{gdb.selected_inferior().progspace} (@pxref{Inferiors In Python}) and is
   5333 included for historical compatibility.
   5334 @end defun
   5335 
   5336 @defun gdb.progspaces ()
   5337 Return a sequence of all the progspaces currently known to @value{GDBN}.
   5338 @end defun
   5339 
   5340 Each progspace is represented by an instance of the @code{gdb.Progspace}
   5341 class.
   5342 
   5343 @defvar Progspace.filename
   5344 The file name, as a string, of the main symbol file (from which debug
   5345 symbols have been loaded) for the progspace, e.g.@: the argument to
   5346 the @kbd{symbol-file} or @kbd{file} commands.
   5347 
   5348 If there is no main symbol table currently loaded, then this attribute
   5349 will be @code{None}.
   5350 @end defvar
   5351 
   5352 @defvar Progspace.symbol_file
   5353 The @code{gdb.Objfile} representing the main symbol file (from which
   5354 debug symbols have been loaded) for the @code{gdb.Progspace}.  This is
   5355 the symbol file set by the @kbd{symbol-file} or @kbd{file} commands.
   5356 
   5357 This will be the @code{gdb.Objfile} representing
   5358 @code{Progspace.filename} when @code{Progspace.filename} is not
   5359 @code{None}.
   5360 
   5361 If there is no main symbol table currently loaded, then this attribute
   5362 will be @code{None}.
   5363 
   5364 If the @code{Progspace} is invalid, i.e.@:, when
   5365 @code{Progspace.is_valid()} returns @code{False}, then attempting to
   5366 access this attribute will raise a @code{RuntimeError} exception.
   5367 @end defvar
   5368 
   5369 @defvar Progspace.executable_filename
   5370 The file name, as a string, of the executable file in use by this
   5371 program space.  The executable file is the file that @value{GDBN} will
   5372 invoke in order to start an inferior when using a native target.  The
   5373 file name within this attribute is updated by the @kbd{exec-file} and
   5374 @kbd{file} commands.
   5375 
   5376 If no executable is currently set within this @code{Progspace} then
   5377 this attribute contains @code{None}.
   5378 
   5379 If the @code{Progspace} is invalid, i.e.@:, when
   5380 @code{Progspace.is_valid()} returns @code{False}, then attempting to
   5381 access this attribute will raise a @code{RuntimeError} exception.
   5382 @end defvar
   5383 
   5384 @defvar Progspace.pretty_printers
   5385 The @code{pretty_printers} attribute is a list of functions.  It is
   5386 used to look up pretty-printers.  A @code{Value} is passed to each
   5387 function in order; if the function returns @code{None}, then the
   5388 search continues.  Otherwise, the return value should be an object
   5389 which is used to format the value.  @xref{Pretty Printing API}, for more
   5390 information.
   5391 @end defvar
   5392 
   5393 @defvar Progspace.type_printers
   5394 The @code{type_printers} attribute is a list of type printer objects.
   5395 @xref{Type Printing API}, for more information.
   5396 @end defvar
   5397 
   5398 @defvar Progspace.frame_filters
   5399 The @code{frame_filters} attribute is a dictionary of frame filter
   5400 objects.  @xref{Frame Filter API}, for more information.
   5401 @end defvar
   5402 
   5403 @defvar Progspace.missing_file_handlers
   5404 The @code{missing_file_handlers} attribute is a list of tuples.  Each
   5405 tuple holds a missing-file handler object for this program space.  For
   5406 more information, @pxref{Missing Debug Info In Python}, and
   5407 @ref{Missing Objfiles In Python}.
   5408 @end defvar
   5409 
   5410 A program space has the following methods:
   5411 
   5412 @defun Progspace.block_for_pc (pc)
   5413 Return the innermost @code{gdb.Block} containing the given @var{pc}
   5414 value.  If the block cannot be found for the @var{pc} value specified,
   5415 the function will return @code{None}.
   5416 @end defun
   5417 
   5418 @defun Progspace.find_pc_line (pc)
   5419 Return the @code{gdb.Symtab_and_line} object corresponding to the
   5420 @var{pc} value.  @xref{Symbol Tables In Python}.  If an invalid value
   5421 of @var{pc} is passed as an argument, then the @code{symtab} and
   5422 @code{line} attributes of the returned @code{gdb.Symtab_and_line}
   5423 object will be @code{None} and 0 respectively.
   5424 @end defun
   5425 
   5426 @defun Progspace.is_valid ()
   5427 Returns @code{True} if the @code{gdb.Progspace} object is valid,
   5428 @code{False} if not.  A @code{gdb.Progspace} object can become invalid
   5429 if the program space file it refers to is not referenced by any
   5430 inferior.  All other @code{gdb.Progspace} methods will throw an
   5431 exception if it is invalid at the time the method is called.
   5432 @end defun
   5433 
   5434 @defun Progspace.objfiles ()
   5435 Return a sequence of all the objfiles referenced by this program
   5436 space.  @xref{Objfiles In Python}.
   5437 @end defun
   5438 
   5439 @defun Progspace.solib_name (address)
   5440 Return the name of the shared library holding the given @var{address}
   5441 as a string, or @code{None}.
   5442 @end defun
   5443 
   5444 @defun Progspace.objfile_for_address (address)
   5445 Return the @code{gdb.Objfile} holding the given address, or
   5446 @code{None} if no objfile covers it.
   5447 @end defun
   5448 
   5449 One may add arbitrary attributes to @code{gdb.Progspace} objects
   5450 in the usual Python way.
   5451 This is useful if, for example, one needs to do some extra record keeping
   5452 associated with the program space.
   5453 
   5454 @xref{choosing attribute names}, for guidance on selecting a suitable
   5455 name for new attributes.
   5456 
   5457 In this contrived example, we want to perform some processing when
   5458 an objfile with a certain symbol is loaded, but we only want to do
   5459 this once because it is expensive.  To achieve this we record the results
   5460 with the program space because we can't predict when the desired objfile
   5461 will be loaded.
   5462 
   5463 @smallexample
   5464 (@value{GDBP}) python
   5465 @group
   5466 def clear_objfiles_handler(event):
   5467     event.progspace.expensive_computation = None
   5468 def expensive(symbol):
   5469     """A mock routine to perform an "expensive" computation on symbol."""
   5470     print ("Computing the answer to the ultimate question ...")
   5471     return 42
   5472 @end group
   5473 @group
   5474 def new_objfile_handler(event):
   5475     objfile = event.new_objfile
   5476     progspace = objfile.progspace
   5477     if not hasattr(progspace, 'expensive_computation') or \
   5478             progspace.expensive_computation is None:
   5479         # We use 'main' for the symbol to keep the example simple.
   5480         # Note: There's no current way to constrain the lookup
   5481         # to one objfile.
   5482         symbol = gdb.lookup_global_symbol('main')
   5483         if symbol is not None:
   5484             progspace.expensive_computation = expensive(symbol)
   5485 gdb.events.clear_objfiles.connect(clear_objfiles_handler)
   5486 gdb.events.new_objfile.connect(new_objfile_handler)
   5487 end
   5488 @end group
   5489 @group
   5490 (@value{GDBP}) file /tmp/hello
   5491 Reading symbols from /tmp/hello...
   5492 Computing the answer to the ultimate question ...
   5493 (@value{GDBP}) python print(gdb.current_progspace().expensive_computation)
   5494 42
   5495 (@value{GDBP}) run
   5496 Starting program: /tmp/hello
   5497 Hello.
   5498 [Inferior 1 (process 4242) exited normally]
   5499 @end group
   5500 @end smallexample
   5501 
   5502 @node Objfiles In Python
   5503 @subsubsection Objfiles In Python
   5504 
   5505 @cindex objfiles in python
   5506 @tindex gdb.Objfile
   5507 @tindex Objfile
   5508 @value{GDBN} loads symbols for an inferior from various
   5509 symbol-containing files (@pxref{Files}).  These include the primary
   5510 executable file, any shared libraries used by the inferior, and any
   5511 separate debug info files (@pxref{Separate Debug Files}).
   5512 @value{GDBN} calls these symbol-containing files @dfn{objfiles}.
   5513 
   5514 The following objfile-related functions are available in the
   5515 @code{gdb} module:
   5516 
   5517 @defun gdb.current_objfile ()
   5518 When auto-loading a Python script (@pxref{Python Auto-loading}), @value{GDBN}
   5519 sets the ``current objfile'' to the corresponding objfile.  This
   5520 function returns the current objfile.  If there is no current objfile,
   5521 this function returns @code{None}.
   5522 @end defun
   5523 
   5524 @defun gdb.objfiles ()
   5525 Return a sequence of objfiles referenced by the current program space.
   5526 @xref{Objfiles In Python}, and @ref{Progspaces In Python}.  This is identical
   5527 to @code{gdb.selected_inferior().progspace.objfiles()} and is included for
   5528 historical compatibility.
   5529 @end defun
   5530 
   5531 @defun gdb.lookup_objfile (name @r{[}, by_build_id@r{]})
   5532 Look up @var{name}, a file name or build ID, in the list of objfiles
   5533 for the current program space (@pxref{Progspaces In Python}).
   5534 If the objfile is not found throw the Python @code{ValueError} exception.
   5535 
   5536 If @var{name} is a relative file name, then it will match any
   5537 source file name with the same trailing components.  For example, if
   5538 @var{name} is @samp{gcc/expr.c}, then it will match source file
   5539 name of @file{/build/trunk/gcc/expr.c}, but not
   5540 @file{/build/trunk/libcpp/expr.c} or @file{/build/trunk/gcc/x-expr.c}.
   5541 
   5542 If @var{by_build_id} is provided and is @code{True} then @var{name}
   5543 is the build ID of the objfile.  Otherwise, @var{name} is a file name.
   5544 This is supported only on some operating systems, notably those which use
   5545 the ELF format for binary files and the @sc{gnu} Binutils.  For more details
   5546 about this feature, see the description of the @option{--build-id}
   5547 command-line option in @ref{Options, , Command Line Options, ld,
   5548 The GNU Linker}.
   5549 @end defun
   5550 
   5551 Each objfile is represented by an instance of the @code{gdb.Objfile}
   5552 class.
   5553 
   5554 @defvar Objfile.filename
   5555 The file name of the objfile as a string, with symbolic links resolved.
   5556 
   5557 The value is @code{None} if the objfile is no longer valid.
   5558 See the @code{gdb.Objfile.is_valid} method, described below.
   5559 @end defvar
   5560 
   5561 @defvar Objfile.username
   5562 The file name of the objfile as specified by the user as a string.
   5563 
   5564 The value is @code{None} if the objfile is no longer valid.
   5565 See the @code{gdb.Objfile.is_valid} method, described below.
   5566 @end defvar
   5567 
   5568 @defvar Objfile.is_file
   5569 An objfile often comes from an ordinary file, but in some cases it may
   5570 be constructed from the contents of memory.  This attribute is
   5571 @code{True} for file-backed objfiles, and @code{False} for other
   5572 kinds.
   5573 @end defvar
   5574 
   5575 @defvar Objfile.owner
   5576 For separate debug info objfiles this is the corresponding @code{gdb.Objfile}
   5577 object that debug info is being provided for.
   5578 Otherwise this is @code{None}.
   5579 Separate debug info objfiles are added with the
   5580 @code{gdb.Objfile.add_separate_debug_file} method, described below.
   5581 @end defvar
   5582 
   5583 @anchor{Objfile.build_id}
   5584 @defvar Objfile.build_id
   5585 The build ID of the objfile as a string.
   5586 If the objfile does not have a build ID then the value is @code{None}.
   5587 
   5588 This is supported only on some operating systems, notably those which use
   5589 the ELF format for binary files and the @sc{gnu} Binutils.  For more details
   5590 about this feature, see the description of the @option{--build-id}
   5591 command-line option in @ref{Options, , Command Line Options, ld,
   5592 The GNU Linker}.
   5593 @end defvar
   5594 
   5595 @defvar Objfile.progspace
   5596 The containing program space of the objfile as a @code{gdb.Progspace}
   5597 object.  @xref{Progspaces In Python}.
   5598 @end defvar
   5599 
   5600 @defvar Objfile.pretty_printers
   5601 The @code{pretty_printers} attribute is a list of functions.  It is
   5602 used to look up pretty-printers.  A @code{Value} is passed to each
   5603 function in order; if the function returns @code{None}, then the
   5604 search continues.  Otherwise, the return value should be an object
   5605 which is used to format the value.  @xref{Pretty Printing API}, for more
   5606 information.
   5607 @end defvar
   5608 
   5609 @defvar Objfile.type_printers
   5610 The @code{type_printers} attribute is a list of type printer objects.
   5611 @xref{Type Printing API}, for more information.
   5612 @end defvar
   5613 
   5614 @defvar Objfile.frame_filters
   5615 The @code{frame_filters} attribute is a dictionary of frame filter
   5616 objects.  @xref{Frame Filter API}, for more information.
   5617 @end defvar
   5618 
   5619 One may add arbitrary attributes to @code{gdb.Objfile} objects
   5620 in the usual Python way.
   5621 This is useful if, for example, one needs to do some extra record keeping
   5622 associated with the objfile.
   5623 
   5624 @xref{choosing attribute names}, for guidance on selecting a suitable
   5625 name for new attributes.
   5626 
   5627 In this contrived example we record the time when @value{GDBN}
   5628 loaded the objfile.
   5629 
   5630 @smallexample
   5631 @group
   5632 (@value{GDBP}) python
   5633 import datetime
   5634 def new_objfile_handler(event):
   5635     # Set the time_loaded attribute of the new objfile.
   5636     event.new_objfile.time_loaded = datetime.datetime.today()
   5637 gdb.events.new_objfile.connect(new_objfile_handler)
   5638 end
   5639 @end group
   5640 @group
   5641 (@value{GDBP}) file ./hello
   5642 Reading symbols from ./hello...
   5643 (@value{GDBP}) python print(gdb.objfiles()[0].time_loaded)
   5644 2014-10-09 11:41:36.770345
   5645 @end group
   5646 @end smallexample
   5647 
   5648 A @code{gdb.Objfile} object has the following methods:
   5649 
   5650 @defun Objfile.is_valid ()
   5651 Returns @code{True} if the @code{gdb.Objfile} object is valid,
   5652 @code{False} if not.  A @code{gdb.Objfile} object can become invalid
   5653 if the object file it refers to is not loaded in @value{GDBN} any
   5654 longer.  All other @code{gdb.Objfile} methods will throw an exception
   5655 if it is invalid at the time the method is called.
   5656 @end defun
   5657 
   5658 @defun Objfile.add_separate_debug_file (file)
   5659 Add @var{file} to the list of files that @value{GDBN} will search for
   5660 debug information for the objfile.
   5661 This is useful when the debug info has been removed from the program
   5662 and stored in a separate file.  @value{GDBN} has built-in support for
   5663 finding separate debug info files (@pxref{Separate Debug Files}), but if
   5664 the file doesn't live in one of the standard places that @value{GDBN}
   5665 searches then this function can be used to add a debug info file
   5666 from a different place.
   5667 @end defun
   5668 
   5669 @defun Objfile.lookup_global_symbol (name @r{[}, domain@r{]})
   5670 Search for a global symbol named @var{name} in this objfile.  Optionally, the
   5671 search scope can be restricted with the @var{domain} argument.
   5672 The @var{domain} argument must be a domain constant defined in the @code{gdb}
   5673 module and described in @ref{Symbols In Python}.  This function is similar to
   5674 @code{gdb.lookup_global_symbol}, except that the search is limited to this
   5675 objfile.
   5676 
   5677 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
   5678 is not found.
   5679 @end defun
   5680 
   5681 @defun Objfile.lookup_static_symbol (name @r{[}, domain@r{]})
   5682 Like @code{Objfile.lookup_global_symbol}, but searches for a global
   5683 symbol with static linkage named @var{name} in this objfile.
   5684 @end defun
   5685 
   5686 @node Frames In Python
   5687 @subsubsection Accessing inferior stack frames from Python
   5688 
   5689 @cindex frames in python
   5690 When the debugged program stops, @value{GDBN} is able to analyze its call
   5691 stack (@pxref{Frames,,Stack frames}).  The @code{gdb.Frame} class
   5692 represents a frame in the stack.  A @code{gdb.Frame} object is only valid
   5693 while its corresponding frame exists in the inferior's stack.  If you try
   5694 to use an invalid frame object, @value{GDBN} will throw a @code{gdb.error}
   5695 exception (@pxref{Exception Handling}).
   5696 
   5697 Two @code{gdb.Frame} objects can be compared for equality with the @code{==}
   5698 operator, like:
   5699 
   5700 @smallexample
   5701 (@value{GDBP}) python print gdb.newest_frame() == gdb.selected_frame ()
   5702 True
   5703 @end smallexample
   5704 
   5705 The following frame-related functions are available in the @code{gdb} module:
   5706 
   5707 @defun gdb.selected_frame ()
   5708 Return the selected frame object.  (@pxref{Selection,,Selecting a Frame}).
   5709 @end defun
   5710 
   5711 @defun gdb.newest_frame ()
   5712 Return the newest frame object for the selected thread.
   5713 @end defun
   5714 
   5715 @defun gdb.frame_stop_reason_string (reason)
   5716 Return a string explaining the reason why @value{GDBN} stopped unwinding
   5717 frames, as expressed by the given @var{reason} code (an integer, see the
   5718 @code{unwind_stop_reason} method further down in this section).
   5719 @end defun
   5720 
   5721 @defun gdb.invalidate_cached_frames
   5722 @value{GDBN} internally keeps a cache of the frames that have been
   5723 unwound.  This function invalidates this cache.
   5724 
   5725 This function should not generally be called by ordinary Python code.
   5726 It is documented for the sake of completeness.
   5727 @end defun
   5728 
   5729 A @code{gdb.Frame} object has the following methods:
   5730 
   5731 @defun Frame.is_valid ()
   5732 Returns true if the @code{gdb.Frame} object is valid, false if not.
   5733 A frame object can become invalid if the frame it refers to doesn't
   5734 exist anymore in the inferior.  All @code{gdb.Frame} methods will throw
   5735 an exception if it is invalid at the time the method is called.
   5736 @end defun
   5737 
   5738 @defun Frame.name ()
   5739 Returns the function name of the frame, or @code{None} if it can't be
   5740 obtained.
   5741 @end defun
   5742 
   5743 @defun Frame.architecture ()
   5744 Returns the @code{gdb.Architecture} object corresponding to the frame's
   5745 architecture.  @xref{Architectures In Python}.
   5746 @end defun
   5747 
   5748 @defun Frame.type ()
   5749 Returns the type of the frame.  The value can be one of:
   5750 @table @code
   5751 @item gdb.NORMAL_FRAME
   5752 An ordinary stack frame.
   5753 
   5754 @item gdb.DUMMY_FRAME
   5755 A fake stack frame that was created by @value{GDBN} when performing an
   5756 inferior function call.
   5757 
   5758 @item gdb.INLINE_FRAME
   5759 A frame representing an inlined function.  The function was inlined
   5760 into a @code{gdb.NORMAL_FRAME} that is older than this one.
   5761 
   5762 @item gdb.TAILCALL_FRAME
   5763 A frame representing a tail call.  @xref{Tail Call Frames}.
   5764 
   5765 @item gdb.SIGTRAMP_FRAME
   5766 A signal trampoline frame.  This is the frame created by the OS when
   5767 it calls into a signal handler.
   5768 
   5769 @item gdb.ARCH_FRAME
   5770 A fake stack frame representing a cross-architecture call.
   5771 
   5772 @item gdb.SENTINEL_FRAME
   5773 This is like @code{gdb.NORMAL_FRAME}, but it is only used for the
   5774 newest frame.
   5775 @end table
   5776 @end defun
   5777 
   5778 @defun Frame.unwind_stop_reason ()
   5779 Return an integer representing the reason why it's not possible to find
   5780 more frames toward the outermost frame.  Use
   5781 @code{gdb.frame_stop_reason_string} to convert the value returned by this
   5782 function to a string. The value can be one of:
   5783 
   5784 @table @code
   5785 @item gdb.FRAME_UNWIND_NO_REASON
   5786 No particular reason (older frames should be available).
   5787 
   5788 @item gdb.FRAME_UNWIND_NULL_ID
   5789 The previous frame's analyzer returns an invalid result.  This is no
   5790 longer used by @value{GDBN}, and is kept only for backward
   5791 compatibility.
   5792 
   5793 @item gdb.FRAME_UNWIND_OUTERMOST
   5794 This frame is the outermost.
   5795 
   5796 @item gdb.FRAME_UNWIND_UNAVAILABLE
   5797 Cannot unwind further, because that would require knowing the 
   5798 values of registers or memory that have not been collected.
   5799 
   5800 @item gdb.FRAME_UNWIND_INNER_ID
   5801 This frame ID looks like it ought to belong to a NEXT frame,
   5802 but we got it for a PREV frame.  Normally, this is a sign of
   5803 unwinder failure.  It could also indicate stack corruption.
   5804 
   5805 @item gdb.FRAME_UNWIND_SAME_ID
   5806 This frame has the same ID as the previous one.  That means
   5807 that unwinding further would almost certainly give us another
   5808 frame with exactly the same ID, so break the chain.  Normally,
   5809 this is a sign of unwinder failure.  It could also indicate
   5810 stack corruption.
   5811 
   5812 @item gdb.FRAME_UNWIND_NO_SAVED_PC
   5813 The frame unwinder did not find any saved PC, but we needed
   5814 one to unwind further.
   5815 
   5816 @item gdb.FRAME_UNWIND_MEMORY_ERROR
   5817 The frame unwinder caused an error while trying to access memory.
   5818 
   5819 @item gdb.FRAME_UNWIND_FIRST_ERROR
   5820 Any stop reason greater or equal to this value indicates some kind
   5821 of error.  This special value facilitates writing code that tests
   5822 for errors in unwinding in a way that will work correctly even if
   5823 the list of the other values is modified in future @value{GDBN}
   5824 versions.  Using it, you could write:
   5825 @smallexample
   5826 reason = gdb.selected_frame().unwind_stop_reason ()
   5827 reason_str =  gdb.frame_stop_reason_string (reason)
   5828 if reason >=  gdb.FRAME_UNWIND_FIRST_ERROR:
   5829     print ("An error occurred: %s" % reason_str)
   5830 @end smallexample
   5831 @end table
   5832 
   5833 @end defun
   5834 
   5835 @defun Frame.pc ()
   5836 Returns the frame's resume address.
   5837 @end defun
   5838 
   5839 @defun Frame.block ()
   5840 Return the frame's code block.  @xref{Blocks In Python}.  If the frame
   5841 does not have a block -- for example, if there is no debugging
   5842 information for the code in question -- then this will throw an
   5843 exception.
   5844 @end defun
   5845 
   5846 @defun Frame.function ()
   5847 Return the symbol for the function corresponding to this frame.
   5848 @xref{Symbols In Python}.
   5849 @end defun
   5850 
   5851 @defun Frame.older ()
   5852 Return the frame that called this frame.  If this is the oldest frame,
   5853 return @code{None}.
   5854 @end defun
   5855 
   5856 @defun Frame.newer ()
   5857 Return the frame called by this frame.  If this is the newest frame,
   5858 return @code{None}.
   5859 @end defun
   5860 
   5861 @defun Frame.find_sal ()
   5862 Return the frame's symtab and line object.
   5863 @xref{Symbol Tables In Python}.
   5864 @end defun
   5865 
   5866 @anchor{gdbpy_frame_read_register}
   5867 @defun Frame.read_register (register)
   5868 Return the value of @var{register} in this frame.  Returns a
   5869 @code{Gdb.Value} object.  Throws an exception if @var{register} does
   5870 not exist.  The @var{register} argument must be one of the following:
   5871 @enumerate
   5872 @item
   5873 A string that is the name of a valid register (e.g., @code{'sp'} or
   5874 @code{'rax'}).
   5875 @item
   5876 A @code{gdb.RegisterDescriptor} object (@pxref{Registers In Python}).
   5877 @item
   5878 A @value{GDBN} internal, platform specific number.  Using these
   5879 numbers is supported for historic reasons, but is not recommended as
   5880 future changes to @value{GDBN} could change the mapping between
   5881 numbers and the registers they represent, breaking any Python code
   5882 that uses the platform-specific numbers.  The numbers are usually
   5883 found in the corresponding @file{@var{platform}-tdep.h} file in the
   5884 @value{GDBN} source tree.
   5885 @end enumerate
   5886 Using a string to access registers will be slightly slower than the
   5887 other two methods as @value{GDBN} must look up the mapping between
   5888 name and internal register number.  If performance is critical
   5889 consider looking up and caching a @code{gdb.RegisterDescriptor}
   5890 object.
   5891 @end defun
   5892 
   5893 @defun Frame.read_var (variable @r{[}, block@r{]})
   5894 Return the value of @var{variable} in this frame.  If the optional
   5895 argument @var{block} is provided, search for the variable from that
   5896 block; otherwise start at the frame's current block (which is
   5897 determined by the frame's current program counter).  The @var{variable}
   5898 argument must be a string or a @code{gdb.Symbol} object; @var{block} must be a
   5899 @code{gdb.Block} object.
   5900 @end defun
   5901 
   5902 @defun Frame.select ()
   5903 Set this frame to be the selected frame.  @xref{Stack, ,Examining the
   5904 Stack}.
   5905 @end defun
   5906 
   5907 @defun Frame.static_link ()
   5908 In some languages (e.g., Ada, but also a GNU C extension), a nested
   5909 function can access the variables in the outer scope.  This is done
   5910 via a ``static link'', which is a reference from the nested frame to
   5911 the appropriate outer frame.
   5912 
   5913 This method returns this frame's static link frame, if one exists.  If
   5914 there is no static link, this method returns @code{None}.
   5915 @end defun
   5916 
   5917 @defun Frame.level ()
   5918 Return an integer, the stack frame level for this frame.  @xref{Frames, ,Stack Frames}.
   5919 @end defun
   5920 
   5921 @defun Frame.language ()
   5922 Return a string, the source language for this frame.
   5923 @end defun
   5924 
   5925 @node Blocks In Python
   5926 @subsubsection Accessing blocks from Python
   5927 
   5928 @cindex blocks in python
   5929 @tindex gdb.Block
   5930 
   5931 In @value{GDBN}, symbols are stored in blocks.  A block corresponds
   5932 roughly to a scope in the source code.  Blocks are organized
   5933 hierarchically, and are represented individually in Python as a
   5934 @code{gdb.Block}.  Blocks rely on debugging information being
   5935 available.
   5936 
   5937 A frame has a block.  Please see @ref{Frames In Python}, for a more
   5938 in-depth discussion of frames.
   5939 
   5940 The outermost block is known as the @dfn{global block}.  The global
   5941 block typically holds public global variables and functions.
   5942 
   5943 The block nested just inside the global block is the @dfn{static
   5944 block}.  The static block typically holds file-scoped variables and
   5945 functions.
   5946 
   5947 @value{GDBN} provides a method to get a block's superblock, but there
   5948 is currently no way to examine the sub-blocks of a block, or to
   5949 iterate over all the blocks in a symbol table (@pxref{Symbol Tables In
   5950 Python}).
   5951 
   5952 Here is a short example that should help explain blocks:
   5953 
   5954 @smallexample
   5955 /* This is in the global block.  */
   5956 int global;
   5957 
   5958 /* This is in the static block.  */
   5959 static int file_scope;
   5960 
   5961 /* 'function' is in the global block, and 'argument' is
   5962    in a block nested inside of 'function'.  */
   5963 int function (int argument)
   5964 @{
   5965   /* 'local' is in a block inside 'function'.  It may or may
   5966      not be in the same block as 'argument'.  */
   5967   int local;
   5968 
   5969   @{
   5970      /* 'inner' is in a block whose superblock is the one holding
   5971         'local'.  */
   5972      int inner;
   5973 
   5974      /* If this call is expanded by the compiler, you may see
   5975         a nested block here whose function is 'inline_function'
   5976         and whose superblock is the one holding 'inner'.  */
   5977      inline_function ();
   5978   @}
   5979 @}
   5980 @end smallexample
   5981 
   5982 A @code{gdb.Block} is iterable.  The iterator returns the symbols
   5983 (@pxref{Symbols In Python}) local to the block.  Python programs
   5984 should not assume that a specific block object will always contain a
   5985 given symbol, since changes in @value{GDBN} features and
   5986 infrastructure may cause symbols move across blocks in a symbol
   5987 table.  You can also use Python's @dfn{dictionary syntax} to access
   5988 variables in this block, e.g.:
   5989 
   5990 @smallexample
   5991 symbol = some_block['variable']  # symbol is of type gdb.Symbol
   5992 @end smallexample
   5993 
   5994 The following block-related functions are available in the @code{gdb}
   5995 module:
   5996 
   5997 @defun gdb.block_for_pc (pc)
   5998 Return the innermost @code{gdb.Block} containing the given @var{pc}
   5999 value.  If the block cannot be found for the @var{pc} value specified,
   6000 the function will return @code{None}.  This is identical to
   6001 @code{gdb.current_progspace().block_for_pc(pc)} and is included for
   6002 historical compatibility.
   6003 @end defun
   6004 
   6005 A @code{gdb.Block} object has the following methods:
   6006 
   6007 @defun Block.is_valid ()
   6008 Returns @code{True} if the @code{gdb.Block} object is valid,
   6009 @code{False} if not.  A block object can become invalid if the block it
   6010 refers to doesn't exist anymore in the inferior.  All other
   6011 @code{gdb.Block} methods will throw an exception if it is invalid at
   6012 the time the method is called.  The block's validity is also checked
   6013 during iteration over symbols of the block.
   6014 @end defun
   6015 
   6016 A @code{gdb.Block} object has the following attributes:
   6017 
   6018 @defvar Block.start
   6019 The start address of the block.  This attribute is not writable.
   6020 @end defvar
   6021 
   6022 @defvar Block.end
   6023 One past the last address that appears in the block.  This attribute
   6024 is not writable.
   6025 @end defvar
   6026 
   6027 @defvar Block.function
   6028 The name of the block represented as a @code{gdb.Symbol}.  If the
   6029 block is not named, then this attribute holds @code{None}.  This
   6030 attribute is not writable.
   6031 
   6032 For ordinary function blocks, the superblock is the static block.
   6033 However, you should note that it is possible for a function block to
   6034 have a superblock that is not the static block -- for instance this
   6035 happens for an inlined function.
   6036 @end defvar
   6037 
   6038 @defvar Block.superblock
   6039 The block containing this block.  If this parent block does not exist,
   6040 this attribute holds @code{None}.  This attribute is not writable.
   6041 @end defvar
   6042 
   6043 @defvar Block.global_block
   6044 The global block associated with this block.  This attribute is not
   6045 writable.
   6046 @end defvar
   6047 
   6048 @defvar Block.static_block
   6049 The static block associated with this block.  This attribute is not
   6050 writable.
   6051 @end defvar
   6052 
   6053 @defvar Block.is_global
   6054 @code{True} if the @code{gdb.Block} object is a global block,
   6055 @code{False} if not.  This attribute is not
   6056 writable.
   6057 @end defvar
   6058 
   6059 @defvar Block.is_static
   6060 @code{True} if the @code{gdb.Block} object is a static block,
   6061 @code{False} if not.  This attribute is not writable.
   6062 @end defvar
   6063 
   6064 @node Symbols In Python
   6065 @subsubsection Python representation of Symbols
   6066 
   6067 @cindex symbols in python
   6068 @tindex gdb.Symbol
   6069 
   6070 @value{GDBN} represents every variable, function and type as an
   6071 entry in a symbol table.  @xref{Symbols, ,Examining the Symbol Table}.
   6072 Similarly, Python represents these symbols in @value{GDBN} with the
   6073 @code{gdb.Symbol} object.
   6074 
   6075 The following symbol-related functions are available in the @code{gdb}
   6076 module:
   6077 
   6078 @defun gdb.lookup_symbol (name @r{[}, block @r{[}, domain@r{]]})
   6079 This function searches for a symbol by name.  The search scope can be
   6080 restricted to the parameters defined in the optional domain and block
   6081 arguments.
   6082 
   6083 @var{name} is the name of the symbol.  It must be a string.  The
   6084 optional @var{block} argument restricts the search to symbols visible
   6085 in that @var{block}.  The @var{block} argument must be a
   6086 @code{gdb.Block} object.  If omitted, the block for the current frame
   6087 is used.  The optional @var{domain} argument restricts
   6088 the search to the domain type.  The @var{domain} argument must be a
   6089 domain constant defined in the @code{gdb} module and described later
   6090 in this chapter.
   6091 
   6092 The result is a tuple of two elements.
   6093 The first element is a @code{gdb.Symbol} object or @code{None} if the symbol
   6094 is not found.
   6095 If the symbol is found, the second element is @code{True} if the symbol
   6096 is a field of a method's object (e.g., @code{this} in C@t{++}),
   6097 otherwise it is @code{False}.
   6098 If the symbol is not found, the second element is @code{False}.
   6099 @end defun
   6100 
   6101 @defun gdb.lookup_global_symbol (name @r{[}, domain@r{]})
   6102 This function searches for a global symbol by name.
   6103 The search scope can be restricted to by the domain argument.
   6104 
   6105 @var{name} is the name of the symbol.  It must be a string.
   6106 The optional @var{domain} argument restricts the search to the domain type.
   6107 The @var{domain} argument must be a domain constant defined in the @code{gdb}
   6108 module and described later in this chapter.
   6109 
   6110 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
   6111 is not found.
   6112 @end defun
   6113 
   6114 @defun gdb.lookup_static_symbol (name @r{[}, domain@r{]})
   6115 This function searches for a global symbol with static linkage by name.
   6116 The search scope can be restricted to by the domain argument.
   6117 
   6118 @var{name} is the name of the symbol.  It must be a string.
   6119 The optional @var{domain} argument restricts the search to the domain type.
   6120 The @var{domain} argument must be a domain constant defined in the @code{gdb}
   6121 module and described later in this chapter.
   6122 
   6123 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
   6124 is not found.
   6125 
   6126 Note that this function will not find function-scoped static variables. To look
   6127 up such variables, iterate over the variables of the function's
   6128 @code{gdb.Block} and check that @code{block.addr_class} is
   6129 @code{gdb.SYMBOL_LOC_STATIC}.
   6130 
   6131 There can be multiple global symbols with static linkage with the same
   6132 name.  This function will only return the first matching symbol that
   6133 it finds.  Which symbol is found depends on where @value{GDBN} is
   6134 currently stopped, as @value{GDBN} will first search for matching
   6135 symbols in the current object file, and then search all other object
   6136 files.  If the application is not yet running then @value{GDBN} will
   6137 search all object files in the order they appear in the debug
   6138 information.
   6139 @end defun
   6140 
   6141 @defun gdb.lookup_static_symbols (name @r{[}, domain@r{]})
   6142 Similar to @code{gdb.lookup_static_symbol}, this function searches for
   6143 global symbols with static linkage by name, and optionally restricted
   6144 by the domain argument.  However, this function returns a list of all
   6145 matching symbols found, not just the first one.
   6146 
   6147 @var{name} is the name of the symbol.  It must be a string.
   6148 The optional @var{domain} argument restricts the search to the domain type.
   6149 The @var{domain} argument must be a domain constant defined in the @code{gdb}
   6150 module and described later in this chapter.
   6151 
   6152 The result is a list of @code{gdb.Symbol} objects which could be empty
   6153 if no matching symbols were found.
   6154 
   6155 Note that this function will not find function-scoped static variables. To look
   6156 up such variables, iterate over the variables of the function's
   6157 @code{gdb.Block} and check that @code{block.addr_class} is
   6158 @code{gdb.SYMBOL_LOC_STATIC}.
   6159 @end defun
   6160 
   6161 A @code{gdb.Symbol} object has the following attributes:
   6162 
   6163 @defvar Symbol.type
   6164 The type of the symbol or @code{None} if no type is recorded.
   6165 This attribute is represented as a @code{gdb.Type} object.
   6166 @xref{Types In Python}.  This attribute is not writable.
   6167 @end defvar
   6168 
   6169 @defvar Symbol.symtab
   6170 The symbol table in which the symbol appears.  This attribute is
   6171 represented as a @code{gdb.Symtab} object.  @xref{Symbol Tables In
   6172 Python}.  This attribute is not writable.
   6173 @end defvar
   6174 
   6175 @defvar Symbol.line
   6176 The line number in the source code at which the symbol was defined.
   6177 This is an integer.
   6178 @end defvar
   6179 
   6180 @defvar Symbol.name
   6181 The name of the symbol as a string.  This attribute is not writable.
   6182 @end defvar
   6183 
   6184 @defvar Symbol.linkage_name
   6185 The name of the symbol, as used by the linker (i.e., may be mangled).
   6186 This attribute is not writable.
   6187 @end defvar
   6188 
   6189 @defvar Symbol.print_name
   6190 The name of the symbol in a form suitable for output.  This is either
   6191 @code{name} or @code{linkage_name}, depending on whether the user
   6192 asked @value{GDBN} to display demangled or mangled names.
   6193 @end defvar
   6194 
   6195 @defvar Symbol.addr_class
   6196 The address class of the symbol.  This classifies how to find the value
   6197 of a symbol.  Each address class is a constant defined in the
   6198 @code{gdb} module and described later in this chapter.
   6199 @end defvar
   6200 
   6201 @defvar Symbol.needs_frame
   6202 This is @code{True} if evaluating this symbol's value requires a frame
   6203 (@pxref{Frames In Python}) and @code{False} otherwise.  Typically,
   6204 local variables will require a frame, but other symbols will not.
   6205 @end defvar
   6206 
   6207 @defvar Symbol.is_argument
   6208 @code{True} if the symbol is an argument of a function.
   6209 @end defvar
   6210 
   6211 @defvar Symbol.is_artificial
   6212 @code{True} if the symbol is artificial.  An artificial symbol is one
   6213 that is introduced by the compiler.
   6214 @end defvar
   6215 
   6216 @defvar Symbol.is_constant
   6217 @code{True} if the symbol is a constant.
   6218 @end defvar
   6219 
   6220 @defvar Symbol.is_function
   6221 @code{True} if the symbol is a function or a method.
   6222 @end defvar
   6223 
   6224 @defvar Symbol.is_variable
   6225 @code{True} if the symbol is a variable, as opposed to something like
   6226 a function or type.  Note that this also returns @code{False} for
   6227 arguments.
   6228 @end defvar
   6229 
   6230 A @code{gdb.Symbol} object has the following methods:
   6231 
   6232 @defun Symbol.is_valid ()
   6233 Returns @code{True} if the @code{gdb.Symbol} object is valid,
   6234 @code{False} if not.  A @code{gdb.Symbol} object can become invalid if
   6235 the symbol it refers to does not exist in @value{GDBN} any longer.
   6236 All other @code{gdb.Symbol} methods will throw an exception if it is
   6237 invalid at the time the method is called.
   6238 @end defun
   6239 
   6240 @defun Symbol.value (@r{[}frame@r{]})
   6241 Compute the value of the symbol, as a @code{gdb.Value}.  For
   6242 functions, this computes the address of the function, cast to the
   6243 appropriate type.  If the symbol requires a frame in order to compute
   6244 its value, then @var{frame} must be given.  If @var{frame} is not
   6245 given, or if @var{frame} is invalid, then this method will throw an
   6246 exception.
   6247 @end defun
   6248 
   6249 The available domain categories in @code{gdb.Symbol} are represented
   6250 as constants in the @code{gdb} module:
   6251 
   6252 @vtable @code
   6253 @vindex SYMBOL_UNDEF_DOMAIN
   6254 @item gdb.SYMBOL_UNDEF_DOMAIN
   6255 This is used when a domain has not been discovered or none of the
   6256 following domains apply.  This usually indicates an error either
   6257 in the symbol information or in @value{GDBN}'s handling of symbols.
   6258 
   6259 @vindex SYMBOL_VAR_DOMAIN
   6260 @item gdb.SYMBOL_VAR_DOMAIN
   6261 This domain contains variables.
   6262 
   6263 @vindex SYMBOL_FUNCTION_DOMAIN
   6264 @item gdb.SYMBOL_FUNCTION_DOMAIN
   6265 This domain contains functions.
   6266 
   6267 @vindex SYMBOL_TYPE_DOMAIN
   6268 @item gdb.SYMBOL_TYPE_DOMAIN
   6269 This domain contains types.  In a C-like language, types using a tag
   6270 (the name appearing after a @code{struct}, @code{union}, or
   6271 @code{enum} keyword) will not appear here; in other languages, all
   6272 types are in this domain.
   6273 
   6274 @vindex SYMBOL_STRUCT_DOMAIN
   6275 @item gdb.SYMBOL_STRUCT_DOMAIN
   6276 This domain holds struct, union and enum tag names.  This domain is
   6277 only used for C-like languages.  For example, in this code:
   6278 @smallexample
   6279 struct type_one @{ int x; @};
   6280 typedef struct type_one type_two;
   6281 @end smallexample
   6282 Here @code{type_one} will be in @code{SYMBOL_STRUCT_DOMAIN}, but
   6283 @code{type_two} will be in @code{SYMBOL_TYPE_DOMAIN}.
   6284 
   6285 @vindex SYMBOL_LABEL_DOMAIN
   6286 @item gdb.SYMBOL_LABEL_DOMAIN
   6287 This domain contains names of labels (for gotos).
   6288 
   6289 @vindex SYMBOL_MODULE_DOMAIN
   6290 @item gdb.SYMBOL_MODULE_DOMAIN
   6291 This domain contains names of Fortran module types.
   6292 
   6293 @vindex SYMBOL_COMMON_BLOCK_DOMAIN
   6294 @item gdb.SYMBOL_COMMON_BLOCK_DOMAIN
   6295 This domain contains names of Fortran common blocks.
   6296 @end vtable
   6297 
   6298 When searching for a symbol, the desired domain constant can be passed
   6299 verbatim to the lookup function.  For example:
   6300 @smallexample
   6301 symbol = gdb.lookup_symbol ("name", domain=gdb.SYMBOL_VAR_DOMAIN)
   6302 @end smallexample
   6303 
   6304 For more complex searches, there is a corresponding set of constants,
   6305 each named after one of the preceding constants, but with the
   6306 @samp{SEARCH} prefix replacing the @samp{SYMBOL} prefix; for example,
   6307 @code{SEARCH_LABEL_DOMAIN}.  These may be or'd together to form a
   6308 search constant, e.g.:
   6309 @smallexample
   6310 symbol = gdb.lookup_symbol ("name",
   6311                             domain=gdb.SEARCH_VAR_DOMAIN | gdb.SEARCH_TYPE_DOMAIN)
   6312 @end smallexample
   6313 
   6314 The available address class categories in @code{gdb.Symbol} are represented
   6315 as constants in the @code{gdb} module:
   6316 
   6317 @vtable @code
   6318 @vindex SYMBOL_LOC_UNDEF
   6319 @item gdb.SYMBOL_LOC_UNDEF
   6320 If this is returned by address class, it indicates an error either in
   6321 the symbol information or in @value{GDBN}'s handling of symbols.
   6322 
   6323 @vindex SYMBOL_LOC_CONST
   6324 @item gdb.SYMBOL_LOC_CONST
   6325 Value is constant int.
   6326 
   6327 @vindex SYMBOL_LOC_STATIC
   6328 @item gdb.SYMBOL_LOC_STATIC
   6329 Value is at a fixed address.
   6330 
   6331 @vindex SYMBOL_LOC_REGISTER
   6332 @item gdb.SYMBOL_LOC_REGISTER
   6333 Value is in a register.
   6334 
   6335 @vindex SYMBOL_LOC_ARG
   6336 @item gdb.SYMBOL_LOC_ARG
   6337 Value is an argument.  This value is at the offset stored within the
   6338 symbol inside the frame's argument list.
   6339 
   6340 @vindex SYMBOL_LOC_REF_ARG
   6341 @item gdb.SYMBOL_LOC_REF_ARG
   6342 Value address is stored in the frame's argument list.  Just like
   6343 @code{LOC_ARG} except that the value's address is stored at the
   6344 offset, not the value itself.
   6345 
   6346 @vindex SYMBOL_LOC_REGPARM_ADDR
   6347 @item gdb.SYMBOL_LOC_REGPARM_ADDR
   6348 Value is a specified register.  Just like @code{LOC_REGISTER} except
   6349 the register holds the address of the argument instead of the argument
   6350 itself.
   6351 
   6352 @vindex SYMBOL_LOC_LOCAL
   6353 @item gdb.SYMBOL_LOC_LOCAL
   6354 Value is a local variable.
   6355 
   6356 @vindex SYMBOL_LOC_TYPEDEF
   6357 @item gdb.SYMBOL_LOC_TYPEDEF
   6358 Value not used.  Symbols in the domain @code{SYMBOL_STRUCT_DOMAIN} all
   6359 have this class.
   6360 
   6361 @vindex SYMBOL_LOC_LABEL
   6362 @item gdb.SYMBOL_LOC_LABEL
   6363 Value is a label.
   6364 
   6365 @vindex SYMBOL_LOC_BLOCK
   6366 @item gdb.SYMBOL_LOC_BLOCK
   6367 Value is a block.
   6368 
   6369 @vindex SYMBOL_LOC_CONST_BYTES
   6370 @item gdb.SYMBOL_LOC_CONST_BYTES
   6371 Value is a byte-sequence.
   6372 
   6373 @vindex SYMBOL_LOC_UNRESOLVED
   6374 @item gdb.SYMBOL_LOC_UNRESOLVED
   6375 Value is at a fixed address, but the address of the variable has to be
   6376 determined from the minimal symbol table whenever the variable is
   6377 referenced.
   6378 
   6379 @vindex SYMBOL_LOC_OPTIMIZED_OUT
   6380 @item gdb.SYMBOL_LOC_OPTIMIZED_OUT
   6381 The value does not actually exist in the program.
   6382 
   6383 @vindex SYMBOL_LOC_COMPUTED
   6384 @item gdb.SYMBOL_LOC_COMPUTED
   6385 The value's address is a computed location.
   6386 
   6387 @vindex SYMBOL_LOC_COMMON_BLOCK
   6388 @item gdb.SYMBOL_LOC_COMMON_BLOCK
   6389 The value's address is a symbol.  This is only used for Fortran common
   6390 blocks.
   6391 @end vtable
   6392 
   6393 @node Symbol Tables In Python
   6394 @subsubsection Symbol table representation in Python
   6395 
   6396 @cindex symbol tables in python
   6397 @tindex gdb.Symtab
   6398 @tindex gdb.Symtab_and_line
   6399 
   6400 Access to symbol table data maintained by @value{GDBN} on the inferior
   6401 is exposed to Python via two objects: @code{gdb.Symtab_and_line} and
   6402 @code{gdb.Symtab}.  Symbol table and line data for a frame is returned
   6403 from the @code{find_sal} method in @code{gdb.Frame} object.
   6404 @xref{Frames In Python}.
   6405 
   6406 For more information on @value{GDBN}'s symbol table management, see
   6407 @ref{Symbols, ,Examining the Symbol Table}, for more information.
   6408 
   6409 A @code{gdb.Symtab_and_line} object has the following attributes:
   6410 
   6411 @defvar Symtab_and_line.symtab
   6412 The symbol table object (@code{gdb.Symtab}) for this frame.
   6413 This attribute is not writable.
   6414 @end defvar
   6415 
   6416 @defvar Symtab_and_line.pc
   6417 Indicates the start of the address range occupied by code for the
   6418 current source line.  This attribute is not writable.
   6419 @end defvar
   6420 
   6421 @defvar Symtab_and_line.last
   6422 Indicates the end of the address range occupied by code for the current
   6423 source line.  This attribute is not writable.
   6424 @end defvar
   6425 
   6426 @defvar Symtab_and_line.line
   6427 Indicates the current line number for this object.  This
   6428 attribute is not writable.
   6429 @end defvar
   6430 
   6431 A @code{gdb.Symtab_and_line} object has the following methods:
   6432 
   6433 @defun Symtab_and_line.is_valid ()
   6434 Returns @code{True} if the @code{gdb.Symtab_and_line} object is valid,
   6435 @code{False} if not.  A @code{gdb.Symtab_and_line} object can become
   6436 invalid if the Symbol table and line object it refers to does not
   6437 exist in @value{GDBN} any longer.  All other
   6438 @code{gdb.Symtab_and_line} methods will throw an exception if it is
   6439 invalid at the time the method is called.
   6440 @end defun
   6441 
   6442 A @code{gdb.Symtab} object has the following attributes:
   6443 
   6444 @defvar Symtab.filename
   6445 The symbol table's source filename.  This attribute is not writable.
   6446 @end defvar
   6447 
   6448 @defvar Symtab.objfile
   6449 The symbol table's backing object file.  @xref{Objfiles In Python}.
   6450 This attribute is not writable.
   6451 @end defvar
   6452 
   6453 @defvar Symtab.producer
   6454 The name and possibly version number of the program that
   6455 compiled the code in the symbol table.
   6456 The contents of this string is up to the compiler.
   6457 If no producer information is available then @code{None} is returned.
   6458 This attribute is not writable.
   6459 @end defvar
   6460 
   6461 A @code{gdb.Symtab} object has the following methods:
   6462 
   6463 @defun Symtab.is_valid ()
   6464 Returns @code{True} if the @code{gdb.Symtab} object is valid,
   6465 @code{False} if not.  A @code{gdb.Symtab} object can become invalid if
   6466 the symbol table it refers to does not exist in @value{GDBN} any
   6467 longer.  All other @code{gdb.Symtab} methods will throw an exception
   6468 if it is invalid at the time the method is called.
   6469 @end defun
   6470 
   6471 @defun Symtab.fullname ()
   6472 Return the symbol table's source absolute file name.
   6473 @end defun
   6474 
   6475 @defun Symtab.global_block ()
   6476 Return the global block of the underlying symbol table.
   6477 @xref{Blocks In Python}.
   6478 @end defun
   6479 
   6480 @defun Symtab.static_block ()
   6481 Return the static block of the underlying symbol table.
   6482 @xref{Blocks In Python}.
   6483 @end defun
   6484 
   6485 @defun Symtab.linetable ()
   6486 Return the line table associated with the symbol table.
   6487 @xref{Line Tables In Python}.
   6488 @end defun
   6489 
   6490 @node Line Tables In Python
   6491 @subsubsection Manipulating line tables using Python
   6492 
   6493 @cindex line tables in python
   6494 @tindex gdb.LineTable
   6495 
   6496 Python code can request and inspect line table information from a
   6497 symbol table that is loaded in @value{GDBN}.  A line table is a
   6498 mapping of source lines to their executable locations in memory.  To
   6499 acquire the line table information for a particular symbol table, use
   6500 the @code{linetable} function (@pxref{Symbol Tables In Python}).
   6501 
   6502 A @code{gdb.LineTable} is iterable.  The iterator returns
   6503 @code{LineTableEntry} objects that correspond to the source line and
   6504 address for each line table entry.  @code{LineTableEntry} objects have
   6505 the following attributes:
   6506 
   6507 @defvar LineTableEntry.line
   6508 The source line number for this line table entry.  This number
   6509 corresponds to the actual line of source.  This attribute is not
   6510 writable.
   6511 @end defvar
   6512 
   6513 @defvar LineTableEntry.pc
   6514 The address that is associated with the line table entry where the
   6515 executable code for that source line resides in memory.  This
   6516 attribute is not writable.
   6517 @end defvar
   6518 
   6519 As there can be multiple addresses for a single source line, you may
   6520 receive multiple @code{LineTableEntry} objects with matching
   6521 @code{line} attributes, but with different @code{pc} attributes.  The
   6522 iterator is sorted in ascending @code{pc} order.  Here is a small
   6523 example illustrating iterating over a line table.
   6524 
   6525 @smallexample
   6526 symtab = gdb.selected_frame().find_sal().symtab
   6527 linetable = symtab.linetable()
   6528 for line in linetable:
   6529    print ("Line: "+str(line.line)+" Address: "+hex(line.pc))
   6530 @end smallexample
   6531 
   6532 This will have the following output:
   6533 
   6534 @smallexample
   6535 Line: 33 Address: 0x4005c8L
   6536 Line: 37 Address: 0x4005caL
   6537 Line: 39 Address: 0x4005d2L
   6538 Line: 40 Address: 0x4005f8L
   6539 Line: 42 Address: 0x4005ffL
   6540 Line: 44 Address: 0x400608L
   6541 Line: 42 Address: 0x40060cL
   6542 Line: 45 Address: 0x400615L
   6543 @end smallexample
   6544 
   6545 In addition to being able to iterate over a @code{LineTable}, it also
   6546 has the following direct access methods:
   6547 
   6548 @defun LineTable.line (line)
   6549 Return a Python @code{Tuple} of @code{LineTableEntry} objects for any
   6550 entries in the line table for the given @var{line}, which specifies
   6551 the source code line.  If there are no entries for that source code
   6552 @var{line}, the Python @code{None} is returned.
   6553 @end defun
   6554 
   6555 @defun LineTable.has_line (line)
   6556 Return a Python @code{Boolean} indicating whether there is an entry in
   6557 the line table for this source line.  Return @code{True} if an entry
   6558 is found, or @code{False} if not.
   6559 @end defun
   6560 
   6561 @defun LineTable.source_lines ()
   6562 Return a Python @code{List} of the source line numbers in the symbol
   6563 table.  Only lines with executable code locations are returned.  The
   6564 contents of the @code{List} will just be the source line entries
   6565 represented as Python @code{Long} values.
   6566 @end defun
   6567 
   6568 @node Breakpoints In Python
   6569 @subsubsection Manipulating breakpoints using Python
   6570 
   6571 @cindex breakpoints in python
   6572 @tindex gdb.Breakpoint
   6573 
   6574 Python code can manipulate breakpoints via the @code{gdb.Breakpoint}
   6575 class.
   6576 
   6577 A breakpoint can be created using one of the two forms of the
   6578 @code{gdb.Breakpoint} constructor.  The first one accepts a string
   6579 like one would pass to the @code{break}
   6580 (@pxref{Set Breaks,,Setting Breakpoints}) and @code{watch}
   6581 (@pxref{Set Watchpoints, , Setting Watchpoints}) commands, and can be used to
   6582 create both breakpoints and watchpoints.  The second accepts separate Python
   6583 arguments similar to @ref{Explicit Locations}, and can only be used to create
   6584 breakpoints.
   6585 
   6586 @defun Breakpoint.__init__ (spec @r{[}, type @r{][}, wp_class @r{][}, internal @r{][}, temporary @r{][}, qualified @r{]})
   6587 Create a new breakpoint according to @var{spec}, which is a string naming the
   6588 location of a breakpoint, or an expression that defines a watchpoint.  The
   6589 string should describe a location in a format recognized by the @code{break}
   6590 command (@pxref{Set Breaks,,Setting Breakpoints}) or, in the case of a
   6591 watchpoint, by the @code{watch} command
   6592 (@pxref{Set Watchpoints, , Setting Watchpoints}).
   6593 
   6594 The optional @var{type} argument specifies the type of the breakpoint to create,
   6595 as defined below.
   6596 
   6597 The optional @var{wp_class} argument defines the class of watchpoint to create,
   6598 if @var{type} is @code{gdb.BP_WATCHPOINT}.  If @var{wp_class} is omitted, it
   6599 defaults to @code{gdb.WP_WRITE}.
   6600 
   6601 The optional @var{internal} argument allows the breakpoint to become invisible
   6602 to the user.  The breakpoint will neither be reported when created, nor will it
   6603 be listed in the output from @code{info breakpoints} (but will be listed with
   6604 the @code{maint info breakpoints} command).
   6605 
   6606 The optional @var{temporary} argument makes the breakpoint a temporary
   6607 breakpoint.  Temporary breakpoints are deleted after they have been hit.  Any
   6608 further access to the Python breakpoint after it has been hit will result in a
   6609 runtime error (as that breakpoint has now been automatically deleted).
   6610 
   6611 The optional @var{qualified} argument is a boolean that allows interpreting
   6612 the function passed in @code{spec} as a fully-qualified name.  It is equivalent
   6613 to @code{break}'s @code{-qualified} flag (@pxref{Linespec Locations} and
   6614 @ref{Explicit Locations}).
   6615 
   6616 @end defun
   6617 
   6618 @defun Breakpoint.__init__ (@r{[} source @r{][}, function @r{][}, label @r{][}, line @r{]}, @r{][} internal @r{][}, temporary @r{][}, qualified @r{]})
   6619 This second form of creating a new breakpoint specifies the explicit
   6620 location (@pxref{Explicit Locations}) using keywords.  The new breakpoint will
   6621 be created in the specified source file @var{source}, at the specified
   6622 @var{function}, @var{label} and @var{line}.
   6623 
   6624 @var{internal}, @var{temporary} and @var{qualified} have the same usage as
   6625 explained previously.
   6626 @end defun
   6627 
   6628 The available types are represented by constants defined in the @code{gdb}
   6629 module:
   6630 
   6631 @vtable @code
   6632 @vindex BP_BREAKPOINT
   6633 @item gdb.BP_BREAKPOINT
   6634 Normal code breakpoint.
   6635 
   6636 @vindex BP_HARDWARE_BREAKPOINT
   6637 @item gdb.BP_HARDWARE_BREAKPOINT
   6638 Hardware assisted code breakpoint.
   6639 
   6640 @vindex BP_WATCHPOINT
   6641 @item gdb.BP_WATCHPOINT
   6642 Watchpoint breakpoint.
   6643 
   6644 @vindex BP_HARDWARE_WATCHPOINT
   6645 @item gdb.BP_HARDWARE_WATCHPOINT
   6646 Hardware assisted watchpoint.
   6647 
   6648 @vindex BP_READ_WATCHPOINT
   6649 @item gdb.BP_READ_WATCHPOINT
   6650 Hardware assisted read watchpoint.
   6651 
   6652 @vindex BP_ACCESS_WATCHPOINT
   6653 @item gdb.BP_ACCESS_WATCHPOINT
   6654 Hardware assisted access watchpoint.
   6655 
   6656 @vindex BP_CATCHPOINT
   6657 @item gdb.BP_CATCHPOINT
   6658 Catchpoint.  Currently, this type can't be used when creating
   6659 @code{gdb.Breakpoint} objects, but will be present in
   6660 @code{gdb.Breakpoint} objects reported from
   6661 @code{gdb.BreakpointEvent}s (@pxref{Events In Python}).
   6662 @end vtable
   6663 
   6664 The available watchpoint types are represented by constants defined in the
   6665 @code{gdb} module:
   6666 
   6667 @vtable @code
   6668 @vindex WP_READ
   6669 @item gdb.WP_READ
   6670 Read only watchpoint.
   6671 
   6672 @vindex WP_WRITE
   6673 @item gdb.WP_WRITE
   6674 Write only watchpoint.
   6675 
   6676 @vindex WP_ACCESS
   6677 @item gdb.WP_ACCESS
   6678 Read/Write watchpoint.
   6679 @end vtable
   6680 
   6681 @defun Breakpoint.stop (self)
   6682 The @code{gdb.Breakpoint} class can be sub-classed and, in
   6683 particular, you may choose to implement the @code{stop} method.
   6684 If this method is defined in a sub-class of @code{gdb.Breakpoint},
   6685 it will be called when the inferior reaches any location of a
   6686 breakpoint which instantiates that sub-class.  If the method returns
   6687 @code{True}, the inferior will be stopped at the location of the
   6688 breakpoint, otherwise the inferior will continue.
   6689 
   6690 If there are multiple breakpoints at the same location with a
   6691 @code{stop} method, each one will be called regardless of the
   6692 return status of the previous.  This ensures that all @code{stop}
   6693 methods have a chance to execute at that location.  In this scenario
   6694 if one of the methods returns @code{True} but the others return
   6695 @code{False}, the inferior will still be stopped.
   6696 
   6697 You should not alter the execution state of the inferior (i.e.@:, step,
   6698 next, etc.), alter the current frame context (i.e.@:, change the current
   6699 active frame), or alter, add or delete any breakpoint.  As a general
   6700 rule, you should not alter any data within @value{GDBN} or the inferior
   6701 at this time.
   6702 
   6703 Example @code{stop} implementation:
   6704 
   6705 @smallexample
   6706 class MyBreakpoint (gdb.Breakpoint):
   6707       def stop (self):
   6708         inf_val = gdb.parse_and_eval("foo")
   6709         if inf_val == 3:
   6710           return True
   6711         return False
   6712 @end smallexample
   6713 @end defun
   6714 
   6715 @defun Breakpoint.is_valid ()
   6716 Return @code{True} if this @code{Breakpoint} object is valid,
   6717 @code{False} otherwise.  A @code{Breakpoint} object can become invalid
   6718 if the user deletes the breakpoint.  In this case, the object still
   6719 exists, but the underlying breakpoint does not.  In the cases of
   6720 watchpoint scope, the watchpoint remains valid even if execution of the
   6721 inferior leaves the scope of that watchpoint.
   6722 @end defun
   6723 
   6724 @defun Breakpoint.delete ()
   6725 Permanently deletes the @value{GDBN} breakpoint.  This also
   6726 invalidates the Python @code{Breakpoint} object.  Any further access
   6727 to this object's attributes or methods will raise an error.
   6728 @end defun
   6729 
   6730 @defvar Breakpoint.enabled
   6731 This attribute is @code{True} if the breakpoint is enabled, and
   6732 @code{False} otherwise.  This attribute is writable.  You can use it to enable
   6733 or disable the breakpoint.
   6734 @end defvar
   6735 
   6736 @defvar Breakpoint.silent
   6737 This attribute is @code{True} if the breakpoint is silent, and
   6738 @code{False} otherwise.  This attribute is writable.
   6739 
   6740 Note that a breakpoint can also be silent if it has commands and the
   6741 first command is @code{silent}.  This is not reported by the
   6742 @code{silent} attribute.
   6743 @end defvar
   6744 
   6745 @defvar Breakpoint.pending
   6746 This attribute is @code{True} if the breakpoint is pending, and
   6747 @code{False} otherwise.  @xref{Set Breaks}.  This attribute is
   6748 read-only.
   6749 @end defvar
   6750 
   6751 @anchor{python_breakpoint_thread}
   6752 @defvar Breakpoint.thread
   6753 If the breakpoint is thread-specific (@pxref{Thread-Specific
   6754 Breakpoints}), this attribute holds the thread's global id.  If the
   6755 breakpoint is not thread-specific, this attribute is @code{None}.
   6756 This attribute is writable.
   6757 
   6758 Only one of @code{Breakpoint.thread} or @code{Breakpoint.inferior} can
   6759 be set to a valid id at any time, that is, a breakpoint can be thread
   6760 specific, or inferior specific, but not both.
   6761 @end defvar
   6762 
   6763 @anchor{python_breakpoint_inferior}
   6764 @defvar Breakpoint.inferior
   6765 If the breakpoint is inferior-specific (@pxref{Inferior-Specific
   6766 Breakpoints}), this attribute holds the inferior's id.  If the
   6767 breakpoint is not inferior-specific, this attribute is @code{None}.
   6768 
   6769 This attribute can be written for breakpoints of type
   6770 @code{gdb.BP_BREAKPOINT} and @code{gdb.BP_HARDWARE_BREAKPOINT}.
   6771 @end defvar
   6772 
   6773 @defvar Breakpoint.task
   6774 If the breakpoint is Ada task-specific, this attribute holds the Ada task
   6775 id.  If the breakpoint is not task-specific (or the underlying
   6776 language is not Ada), this attribute is @code{None}.  This attribute
   6777 is writable.
   6778 @end defvar
   6779 
   6780 @defvar Breakpoint.ignore_count
   6781 This attribute holds the ignore count for the breakpoint, an integer.
   6782 This attribute is writable.
   6783 @end defvar
   6784 
   6785 @defvar Breakpoint.number
   6786 This attribute holds the breakpoint's number --- the identifier used by
   6787 the user to manipulate the breakpoint.  This attribute is not writable.
   6788 @end defvar
   6789 
   6790 @defvar Breakpoint.type
   6791 This attribute holds the breakpoint's type --- the identifier used to
   6792 determine the actual breakpoint type or use-case.  This attribute is not
   6793 writable.
   6794 @end defvar
   6795 
   6796 @defvar Breakpoint.visible
   6797 This attribute tells whether the breakpoint is visible to the user
   6798 when set, or when the @samp{info breakpoints} command is run.  This
   6799 attribute is not writable.
   6800 @end defvar
   6801 
   6802 @defvar Breakpoint.temporary
   6803 This attribute indicates whether the breakpoint was created as a
   6804 temporary breakpoint.  Temporary breakpoints are automatically deleted
   6805 after that breakpoint has been hit.  Access to this attribute, and all
   6806 other attributes and functions other than the @code{is_valid}
   6807 function, will result in an error after the breakpoint has been hit
   6808 (as it has been automatically deleted).  This attribute is not
   6809 writable.
   6810 @end defvar
   6811 
   6812 @defvar Breakpoint.hit_count
   6813 This attribute holds the hit count for the breakpoint, an integer.
   6814 This attribute is writable, but currently it can only be set to zero.
   6815 @end defvar
   6816 
   6817 @defvar Breakpoint.location
   6818 This attribute holds the location of the breakpoint, as specified by
   6819 the user.  It is a string.  If the breakpoint does not have a location
   6820 (that is, it is a watchpoint) the attribute's value is @code{None}.  This
   6821 attribute is not writable.
   6822 @end defvar
   6823 
   6824 @defvar Breakpoint.locations
   6825 Get the most current list of breakpoint locations that are inserted for this
   6826 breakpoint, with elements of type @code{gdb.BreakpointLocation}
   6827 (described below).  This functionality matches that of the
   6828 @code{info breakpoint} command (@pxref{Set Breaks}), in that it only retrieves
   6829 the most current list of locations, thus the list itself when returned is
   6830 not updated behind the scenes.  This attribute is not writable.
   6831 @end defvar
   6832 
   6833 @defvar Breakpoint.expression
   6834 This attribute holds a breakpoint expression, as specified by
   6835 the user.  It is a string.  If the breakpoint does not have an
   6836 expression (the breakpoint is not a watchpoint) the attribute's value
   6837 is @code{None}.  This attribute is not writable.
   6838 @end defvar
   6839 
   6840 @defvar Breakpoint.condition
   6841 This attribute holds the condition of the breakpoint, as specified by
   6842 the user.  It is a string.  If there is no condition, this attribute's
   6843 value is @code{None}.  This attribute is writable.
   6844 @end defvar
   6845 
   6846 @defvar Breakpoint.commands
   6847 This attribute holds the commands attached to the breakpoint.  If
   6848 there are commands, this attribute's value is a string holding all the
   6849 commands, separated by newlines.  If there are no commands, this
   6850 attribute is @code{None}.  This attribute is writable.
   6851 @end defvar
   6852 
   6853 @subheading Breakpoint Locations
   6854 
   6855 A breakpoint location is one of the actual places where a breakpoint has been
   6856 set, represented in the Python API by the @code{gdb.BreakpointLocation}
   6857 type.  This type is never instantiated by the user directly, but is retrieved
   6858 from @code{Breakpoint.locations} which returns a list of breakpoint
   6859 locations where it is currently set.  Breakpoint locations can become
   6860 invalid if new symbol files are loaded or dynamically loaded libraries are
   6861 closed.  Accessing the attributes of an invalidated breakpoint location will
   6862 throw a @code{RuntimeError} exception.  Access the @code{Breakpoint.locations}
   6863 attribute again to retrieve the new and valid breakpoints location list.
   6864 
   6865 @defvar BreakpointLocation.source
   6866 This attribute returns the source file path and line number where this location
   6867 was set. The type of the attribute is a tuple of @var{string} and
   6868 @var{long}.  If the breakpoint location doesn't have a source location,
   6869 it returns None, which is the case for watchpoints and catchpoints.
   6870 This will throw a @code{RuntimeError} exception if the location
   6871 has been invalidated. This attribute is not writable.
   6872 @end defvar
   6873 
   6874 @defvar BreakpointLocation.address
   6875 This attribute returns the address where this location was set.
   6876 This attribute is of type long.  This will throw a @code{RuntimeError}
   6877 exception if the location has been invalidated.  This attribute is
   6878 not writable.
   6879 @end defvar
   6880 
   6881 @defvar BreakpointLocation.enabled
   6882 This attribute holds the value for whether or not this location is enabled.
   6883 This attribute is writable (boolean).  This will throw a @code{RuntimeError}
   6884 exception if the location has been invalidated.
   6885 @end defvar
   6886 
   6887 @defvar BreakpointLocation.owner
   6888 This attribute holds a reference to the @code{gdb.Breakpoint} owner object,
   6889 from which this @code{gdb.BreakpointLocation} was retrieved from.
   6890 This will throw a @code{RuntimeError} exception if the location has been
   6891 invalidated.  This attribute is not writable.
   6892 @end defvar
   6893 
   6894 @defvar BreakpointLocation.function
   6895 This attribute gets the name of the function where this location was set.
   6896 If no function could be found this attribute returns @code{None}.
   6897 This will throw a @code{RuntimeError} exception if the location has
   6898 been invalidated.  This attribute is not writable.
   6899 @end defvar
   6900 
   6901 @defvar BreakpointLocation.fullname
   6902 This attribute gets the full name of where this location was set.  If no
   6903 full name could be found, this attribute returns @code{None}.
   6904 This will throw a @code{RuntimeError} exception if the location has
   6905 been invalidated.  This attribute is not writable.
   6906 @end defvar
   6907 
   6908 @defvar BreakpointLocation.thread_groups
   6909 This attribute gets the thread groups it was set in.  It returns a @code{List}
   6910 of the thread group ID's.  This will throw a @code{RuntimeError}
   6911 exception if the location has been invalidated.  This attribute
   6912 is not writable.
   6913 @end defvar
   6914 
   6915 @node Finish Breakpoints in Python
   6916 @subsubsection Finish Breakpoints
   6917 
   6918 @cindex python finish breakpoints
   6919 @tindex gdb.FinishBreakpoint
   6920 
   6921 A finish breakpoint is a temporary breakpoint set at the return address of
   6922 a frame, based on the @code{finish} command.  @code{gdb.FinishBreakpoint}
   6923 extends @code{gdb.Breakpoint}.  The underlying breakpoint will be disabled 
   6924 and deleted when the execution will run out of the breakpoint scope (i.e.@: 
   6925 @code{Breakpoint.stop} or @code{FinishBreakpoint.out_of_scope} triggered).
   6926 Finish breakpoints are thread specific and must be create with the right 
   6927 thread selected.  
   6928  
   6929 @defun FinishBreakpoint.__init__ (@r{[}frame@r{]} @r{[}, internal@r{]})
   6930 Create a finish breakpoint at the return address of the @code{gdb.Frame}
   6931 object @var{frame}.  If @var{frame} is not provided, this defaults to the
   6932 newest frame.  The optional @var{internal} argument allows the breakpoint to
   6933 become invisible to the user.  @xref{Breakpoints In Python}, for further 
   6934 details about this argument.
   6935 @end defun
   6936 
   6937 @defun FinishBreakpoint.out_of_scope (self)
   6938 In some circumstances (e.g.@: @code{longjmp}, C@t{++} exceptions, @value{GDBN} 
   6939 @code{return} command, @dots{}), a function may not properly terminate, and
   6940 thus never hit the finish breakpoint.  When @value{GDBN} notices such a
   6941 situation, the @code{out_of_scope} callback will be triggered.
   6942 
   6943 You may want to sub-class @code{gdb.FinishBreakpoint} and override this
   6944 method:
   6945 
   6946 @smallexample
   6947 class MyFinishBreakpoint (gdb.FinishBreakpoint)
   6948     def stop (self):
   6949         print ("normal finish")
   6950         return True
   6951     
   6952     def out_of_scope ():
   6953         print ("abnormal finish")
   6954 @end smallexample 
   6955 @end defun
   6956 
   6957 @defvar FinishBreakpoint.return_value
   6958 When @value{GDBN} is stopped at a finish breakpoint and the frame 
   6959 used to build the @code{gdb.FinishBreakpoint} object had debug symbols, this
   6960 attribute will contain a @code{gdb.Value} object corresponding to the return
   6961 value of the function.  The value will be @code{None} if the function return 
   6962 type is @code{void} or if the return value was not computable.  This attribute
   6963 is not writable.
   6964 @end defvar
   6965 
   6966 @node Lazy Strings In Python
   6967 @subsubsection Python representation of lazy strings
   6968 
   6969 @cindex lazy strings in python
   6970 @tindex gdb.LazyString
   6971 
   6972 A @dfn{lazy string} is a string whose contents is not retrieved or
   6973 encoded until it is needed.
   6974 
   6975 A @code{gdb.LazyString} is represented in @value{GDBN} as an
   6976 @code{address} that points to a region of memory, an @code{encoding}
   6977 that will be used to encode that region of memory, and a @code{length}
   6978 to delimit the region of memory that represents the string.  The
   6979 difference between a @code{gdb.LazyString} and a string wrapped within
   6980 a @code{gdb.Value} is that a @code{gdb.LazyString} will only be
   6981 retrieved and encoded during printing, while a @code{gdb.Value}
   6982 wrapping a string is immediately retrieved and encoded on creation.
   6983 
   6984 A @code{gdb.LazyString} can be created using the
   6985 @code{gdb.Value.lazy_string} method (@pxref{Values From Inferior}).
   6986 
   6987 A @code{gdb.LazyString} object has the following functions:
   6988 
   6989 @defun LazyString.value ()
   6990 Convert the @code{gdb.LazyString} to a @code{gdb.Value}.  This value
   6991 will point to the string in memory, but will lose all the delayed
   6992 retrieval, encoding and handling that @value{GDBN} applies to a
   6993 @code{gdb.LazyString}.
   6994 @end defun
   6995 
   6996 @defvar LazyString.address
   6997 This attribute holds the address of the string.  This attribute is not
   6998 writable.
   6999 @end defvar
   7000 
   7001 @defvar LazyString.length
   7002 This attribute holds the length of the string in characters.  If the
   7003 length is -1, then the string will be fetched and encoded up to the
   7004 first null of appropriate width.  This attribute is not writable.
   7005 @end defvar
   7006 
   7007 @defvar LazyString.encoding
   7008 This attribute holds the encoding that will be applied to the string
   7009 when the string is printed by @value{GDBN}.  If the encoding is not
   7010 set, or contains an empty string,  then @value{GDBN} will select the
   7011 most appropriate encoding when the string is printed.  This attribute
   7012 is not writable.
   7013 @end defvar
   7014 
   7015 @defvar LazyString.type
   7016 This attribute holds the type that is represented by the lazy string's
   7017 type.  For a lazy string this is a pointer or array type.  To
   7018 resolve this to the lazy string's character type, use the type's
   7019 @code{target} method.  @xref{Types In Python}.  This attribute is not
   7020 writable.
   7021 @end defvar
   7022 
   7023 @node Architectures In Python
   7024 @subsubsection Python representation of architectures
   7025 @cindex Python architectures
   7026 
   7027 @value{GDBN} uses architecture specific parameters and artifacts in a
   7028 number of its various computations.  An architecture is represented
   7029 by an instance of the @code{gdb.Architecture} class.
   7030 
   7031 A @code{gdb.Architecture} class has the following methods:
   7032 
   7033 @anchor{gdbpy_architecture_name}
   7034 @defun Architecture.name ()
   7035 Return the name (string value) of the architecture.
   7036 @end defun
   7037 
   7038 @defun Architecture.disassemble (start_pc @r{[}, end_pc @r{[}, count@r{]]})
   7039 Return a list of disassembled instructions starting from the memory
   7040 address @var{start_pc}.  The optional arguments @var{end_pc} and
   7041 @var{count} determine the number of instructions in the returned list.
   7042 If both the optional arguments @var{end_pc} and @var{count} are
   7043 specified, then a list of at most @var{count} disassembled instructions
   7044 whose start address falls in the closed memory address interval from
   7045 @var{start_pc} to @var{end_pc} are returned.  If @var{end_pc} is not
   7046 specified, but @var{count} is specified, then @var{count} number of
   7047 instructions starting from the address @var{start_pc} are returned.  If
   7048 @var{count} is not specified but @var{end_pc} is specified, then all
   7049 instructions whose start address falls in the closed memory address
   7050 interval from @var{start_pc} to @var{end_pc} are returned.  If neither
   7051 @var{end_pc} nor @var{count} are specified, then a single instruction at
   7052 @var{start_pc} is returned.  For all of these cases, each element of the
   7053 returned list is a Python @code{dict} with the following string keys:
   7054 
   7055 @table @code
   7056 
   7057 @item addr
   7058 The value corresponding to this key is a Python long integer capturing
   7059 the memory address of the instruction.
   7060 
   7061 @item asm
   7062 The value corresponding to this key is a string value which represents
   7063 the instruction with assembly language mnemonics.  The assembly
   7064 language flavor used is the same as that specified by the current CLI
   7065 variable @code{disassembly-flavor}.  @xref{Machine Code}.
   7066 
   7067 @item length
   7068 The value corresponding to this key is the length (integer value) of the
   7069 instruction in bytes.
   7070 
   7071 @end table
   7072 @end defun
   7073 
   7074 @defun Architecture.integer_type (size @r{[}, signed@r{]})
   7075 This function looks up an integer type by its @var{size}, and
   7076 optionally whether or not it is signed.
   7077 
   7078 @var{size} is the size, in bits, of the desired integer type.  Only
   7079 certain sizes are currently supported: 0, 8, 16, 24, 32, 64, and 128.
   7080 
   7081 If @var{signed} is not specified, it defaults to @code{True}.  If
   7082 @var{signed} is @code{False}, the returned type will be unsigned.
   7083 
   7084 If the indicated type cannot be found, this function will throw a
   7085 @code{ValueError} exception.
   7086 @end defun
   7087 
   7088 @anchor{gdbpy_architecture_registers}
   7089 @defun Architecture.registers (@r{[} reggroup @r{]})
   7090 Return a @code{gdb.RegisterDescriptorIterator} (@pxref{Registers In
   7091 Python}) for all of the registers in @var{reggroup}, a string that is
   7092 the name of a register group.  If @var{reggroup} is omitted, or is the
   7093 empty string, then the register group @samp{all} is assumed.
   7094 @end defun
   7095 
   7096 @anchor{gdbpy_architecture_reggroups}
   7097 @defun Architecture.register_groups ()
   7098 Return a @code{gdb.RegisterGroupsIterator} (@pxref{Registers In
   7099 Python}) for all of the register groups available for the
   7100 @code{gdb.Architecture}.
   7101 @end defun
   7102 
   7103 @node Registers In Python
   7104 @subsubsection Registers In Python
   7105 @cindex Registers In Python
   7106 
   7107 Python code can request from a @code{gdb.Architecture} information
   7108 about the set of registers available
   7109 (@pxref{gdbpy_architecture_registers,,@code{Architecture.registers}}).
   7110 The register information is returned as a
   7111 @code{gdb.RegisterDescriptorIterator}, which is an iterator that in
   7112 turn returns @code{gdb.RegisterDescriptor} objects.
   7113 
   7114 A @code{gdb.RegisterDescriptor} does not provide the value of a
   7115 register (@pxref{gdbpy_frame_read_register,,@code{Frame.read_register}}
   7116 for reading a register's value), instead the @code{RegisterDescriptor}
   7117 is a way to discover which registers are available for a particular
   7118 architecture.
   7119 
   7120 A @code{gdb.RegisterDescriptor} has the following read-only properties:
   7121 
   7122 @defvar RegisterDescriptor.name
   7123 The name of this register.
   7124 @end defvar
   7125 
   7126 It is also possible to lookup a register descriptor based on its name
   7127 using the following @code{gdb.RegisterDescriptorIterator} function:
   7128 
   7129 @defun RegisterDescriptorIterator.find (name)
   7130 Takes @var{name} as an argument, which must be a string, and returns a
   7131 @code{gdb.RegisterDescriptor} for the register with that name, or
   7132 @code{None} if there is no register with that name.
   7133 @end defun
   7134 
   7135 Python code can also request from a @code{gdb.Architecture}
   7136 information about the set of register groups available on a given
   7137 architecture
   7138 (@pxref{gdbpy_architecture_reggroups,,@code{Architecture.register_groups}}).
   7139 
   7140 Every register can be a member of zero or more register groups.  Some
   7141 register groups are used internally within @value{GDBN} to control
   7142 things like which registers must be saved when calling into the
   7143 program being debugged (@pxref{Calling,,Calling Program Functions}).
   7144 Other register groups exist to allow users to easily see related sets
   7145 of registers in commands like @code{info registers}
   7146 (@pxref{info_registers_reggroup,,@code{info registers
   7147 @var{reggroup}}}).
   7148 
   7149 The register groups information is returned as a
   7150 @code{gdb.RegisterGroupsIterator}, which is an iterator that in turn
   7151 returns @code{gdb.RegisterGroup} objects.
   7152 
   7153 A @code{gdb.RegisterGroup} object has the following read-only
   7154 properties:
   7155 
   7156 @defvar RegisterGroup.name
   7157 A string that is the name of this register group.
   7158 @end defvar
   7159 
   7160 @node Connections In Python
   7161 @subsubsection Connections In Python
   7162 @cindex connections in python
   7163 @value{GDBN} lets you run and debug multiple programs in a single
   7164 session.  Each program being debugged has a connection, the connection
   7165 describes how @value{GDBN} controls the program being debugged.
   7166 Examples of different connection types are @samp{native} and
   7167 @samp{remote}.  @xref{Inferiors Connections and Programs}.
   7168 
   7169 Connections in @value{GDBN} are represented as instances of
   7170 @code{gdb.TargetConnection}, or as one of its sub-classes.  To get a
   7171 list of all connections use @code{gdb.connections}
   7172 (@pxref{gdbpy_connections,,gdb.connections}).
   7173 
   7174 To get the connection for a single @code{gdb.Inferior} read its
   7175 @code{gdb.Inferior.connection} attribute
   7176 (@pxref{gdbpy_inferior_connection,,gdb.Inferior.connection}).
   7177 
   7178 Currently there is only a single sub-class of
   7179 @code{gdb.TargetConnection}, @code{gdb.RemoteTargetConnection},
   7180 however, additional sub-classes may be added in future releases of
   7181 @value{GDBN}.  As a result you should avoid writing code like:
   7182 
   7183 @smallexample
   7184 conn = gdb.selected_inferior().connection
   7185 if type(conn) is gdb.RemoteTargetConnection:
   7186   print("This is a remote target connection")
   7187 @end smallexample
   7188 
   7189 @noindent
   7190 as this may fail when more connection types are added.  Instead, you
   7191 should write:
   7192 
   7193 @smallexample
   7194 conn = gdb.selected_inferior().connection
   7195 if isinstance(conn, gdb.RemoteTargetConnection):
   7196   print("This is a remote target connection")
   7197 @end smallexample
   7198 
   7199 A @code{gdb.TargetConnection} has the following method:
   7200 
   7201 @defun TargetConnection.is_valid ()
   7202 Return @code{True} if the @code{gdb.TargetConnection} object is valid,
   7203 @code{False} if not.  A @code{gdb.TargetConnection} will become
   7204 invalid if the connection no longer exists within @value{GDBN}, this
   7205 might happen when no inferiors are using the connection, but could be
   7206 delayed until the user replaces the current target.
   7207 
   7208 Reading any of the @code{gdb.TargetConnection} properties will throw
   7209 an exception if the connection is invalid.
   7210 @end defun
   7211 
   7212 A @code{gdb.TargetConnection} has the following read-only properties:
   7213 
   7214 @defvar TargetConnection.num
   7215 An integer assigned by @value{GDBN} to uniquely identify this
   7216 connection.  This is the same value as displayed in the @samp{Num}
   7217 column of the @code{info connections} command output (@pxref{Inferiors
   7218 Connections and Programs,,info connections}).
   7219 @end defvar
   7220 
   7221 @defvar TargetConnection.type
   7222 A string that describes what type of connection this is.  This string
   7223 will be one of the valid names that can be passed to the @code{target}
   7224 command (@pxref{Target Commands,,target command}).
   7225 @end defvar
   7226 
   7227 @defvar TargetConnection.description
   7228 A string that gives a short description of this target type.  This is
   7229 the same string that is displayed in the @samp{Description} column of
   7230 the @code{info connection} command output (@pxref{Inferiors
   7231 Connections and Programs,,info connections}).
   7232 @end defvar
   7233 
   7234 @defvar TargetConnection.details
   7235 An optional string that gives additional information about this
   7236 connection.  This attribute can be @code{None} if there are no
   7237 additional details for this connection.
   7238 
   7239 An example of a connection type that might have additional details is
   7240 the @samp{remote} connection, in this case the details string can
   7241 contain the @samp{@var{hostname}:@var{port}} that was used to connect
   7242 to the remote target.
   7243 @end defvar
   7244 
   7245 The @code{gdb.RemoteTargetConnection} class is a sub-class of
   7246 @code{gdb.TargetConnection}, and is used to represent @samp{remote}
   7247 and @samp{extended-remote} connections.  In addition to the attributes
   7248 and methods available from the @code{gdb.TargetConnection} base class,
   7249 a @code{gdb.RemoteTargetConnection} has the following method:
   7250 
   7251 @kindex maint packet
   7252 @defun RemoteTargetConnection.send_packet (packet)
   7253 This method sends @var{packet} to the remote target and returns the
   7254 response.  The @var{packet} should either be a @code{bytes} object, or
   7255 a @code{Unicode} string.
   7256 
   7257 If @var{packet} is a @code{Unicode} string, then the string is encoded
   7258 to a @code{bytes} object using the @sc{ascii} codec.  If the string
   7259 can't be encoded then an @code{UnicodeError} is raised.
   7260 
   7261 If @var{packet} is not a @code{bytes} object, or a @code{Unicode}
   7262 string, then a @code{TypeError} is raised.  If @var{packet} is empty
   7263 then a @code{ValueError} is raised.
   7264 
   7265 The response is returned as a @code{bytes} object.  If it is known
   7266 that the response can be represented as a string then this can be
   7267 decoded from the buffer.  For example, if it is known that the
   7268 response is an @sc{ascii} string:
   7269 
   7270 @smallexample
   7271 remote_connection.send_packet("some_packet").decode("ascii")
   7272 @end smallexample
   7273 
   7274 The prefix, suffix, and checksum (as required by the remote serial
   7275 protocol) are automatically added to the outgoing packet, and removed
   7276 from the incoming packet before the contents of the reply are
   7277 returned.
   7278 
   7279 This is equivalent to the @code{maintenance packet} command
   7280 (@pxref{maint packet}).
   7281 @end defun
   7282 
   7283 @node TUI Windows In Python
   7284 @subsubsection Implementing new TUI windows
   7285 @cindex Python TUI Windows
   7286 
   7287 New TUI (@pxref{TUI}) windows can be implemented in Python.
   7288 
   7289 @defun gdb.register_window_type (name, factory)
   7290 Because TUI windows are created and destroyed depending on the layout
   7291 the user chooses, new window types are implemented by registering a
   7292 factory function with @value{GDBN}.
   7293 
   7294 @var{name} is the name of the new window.  It's an error to try to
   7295 replace one of the built-in windows, but other window types can be
   7296 replaced.  The @var{name} should match the regular expression
   7297 @code{[a-zA-Z][-_.a-zA-Z0-9]*}, it is an error to try and create a
   7298 window with an invalid name.
   7299 
   7300 @var{function} is a factory function that is called to create the TUI
   7301 window.  This is called with a single argument of type
   7302 @code{gdb.TuiWindow}, described below.  It should return an object
   7303 that implements the TUI window protocol, also described below.
   7304 @end defun
   7305 
   7306 As mentioned above, when a factory function is called, it is passed
   7307 an object of type @code{gdb.TuiWindow}.  This object has these
   7308 methods and attributes:
   7309 
   7310 @defun TuiWindow.is_valid ()
   7311 This method returns @code{True} when this window is valid.  When the
   7312 user changes the TUI layout, windows no longer visible in the new
   7313 layout will be destroyed.  At this point, the @code{gdb.TuiWindow}
   7314 will no longer be valid, and methods (and attributes) other than
   7315 @code{is_valid} will throw an exception.
   7316 
   7317 When the TUI is disabled using @code{tui disable} (@pxref{TUI
   7318 Commands,,tui disable}) the window is hidden rather than destroyed,
   7319 but @code{is_valid} will still return @code{False} and other methods
   7320 (and attributes) will still throw an exception.
   7321 @end defun
   7322 
   7323 @defvar TuiWindow.width
   7324 This attribute holds the width of the window.  It is not writable.
   7325 @end defvar
   7326 
   7327 @defvar TuiWindow.height
   7328 This attribute holds the height of the window.  It is not writable.
   7329 @end defvar
   7330 
   7331 @defvar TuiWindow.title
   7332 This attribute holds the window's title, a string.  This is normally
   7333 displayed above the window.  This attribute can be modified.
   7334 @end defvar
   7335 
   7336 @defun TuiWindow.erase ()
   7337 Remove all the contents of the window.
   7338 @end defun
   7339 
   7340 @defun TuiWindow.write (string @r{[}, full_window@r{]})
   7341 Write @var{string} to the window.  @var{string} can contain ANSI
   7342 terminal escape styling sequences; @value{GDBN} will translate these
   7343 as appropriate for the terminal.
   7344 
   7345 If the @var{full_window} parameter is @code{True}, then @var{string}
   7346 contains the full contents of the window.  This is similar to calling
   7347 @code{erase} before @code{write}, but avoids the flickering.
   7348 @end defun
   7349 
   7350 The factory function that you supply should return an object
   7351 conforming to the TUI window protocol.  These are the methods that can
   7352 be called on this object, which is referred to below as the ``window
   7353 object''.  The methods documented below are optional; if the object
   7354 does not implement one of these methods, @value{GDBN} will not attempt
   7355 to call it.  Additional new methods may be added to the window
   7356 protocol in the future.  @value{GDBN} guarantees that they will begin
   7357 with a lower-case letter, so you can start implementation methods with
   7358 upper-case letters or underscore to avoid any future conflicts.
   7359 
   7360 @defun Window.close ()
   7361 When the TUI window is closed, the @code{gdb.TuiWindow} object will be
   7362 put into an invalid state.  At this time, @value{GDBN} will call
   7363 @code{close} method on the window object.
   7364 
   7365 After this method is called, @value{GDBN} will discard any references
   7366 it holds on this window object, and will no longer call methods on
   7367 this object.
   7368 @end defun
   7369 
   7370 @defun Window.render ()
   7371 In some situations, a TUI window can change size.  For example, this
   7372 can happen if the user resizes the terminal, or changes the layout.
   7373 When this happens, @value{GDBN} will call the @code{render} method on
   7374 the window object.
   7375 
   7376 If your window is intended to update in response to changes in the
   7377 inferior, you will probably also want to register event listeners and
   7378 send output to the @code{gdb.TuiWindow}.
   7379 @end defun
   7380 
   7381 @defun Window.hscroll (num)
   7382 This is a request to scroll the window horizontally.  @var{num} is the
   7383 amount by which to scroll, with negative numbers meaning to scroll
   7384 right.  In the TUI model, it is the viewport that moves, not the
   7385 contents.  A positive argument should cause the viewport to move
   7386 right, and so the content should appear to move to the left.
   7387 @end defun
   7388 
   7389 @defun Window.vscroll (num)
   7390 This is a request to scroll the window vertically.  @var{num} is the
   7391 amount by which to scroll, with negative numbers meaning to scroll
   7392 backward.  In the TUI model, it is the viewport that moves, not the
   7393 contents.  A positive argument should cause the viewport to move down,
   7394 and so the content should appear to move up.
   7395 @end defun
   7396 
   7397 @anchor{python-window-click}
   7398 @defun Window.click (x, y, button)
   7399 This is called on a mouse click in this window.  @var{x} and @var{y} are
   7400 the mouse coordinates inside the window (0-based, from the top left
   7401 corner), and @var{button} specifies which mouse button was used, whose
   7402 values can be 1 (left), 2 (middle), or 3 (right).
   7403 
   7404 When TUI mouse events are disabled by turning off the @code{tui mouse-events}
   7405 setting (@pxref{tui-mouse-events,,set tui mouse-events}), then @code{click} will
   7406 not be called.
   7407 @end defun
   7408 
   7409 @node Disassembly In Python
   7410 @subsubsection Instruction Disassembly In Python
   7411 @cindex python instruction disassembly
   7412 
   7413 @value{GDBN}'s builtin disassembler can be extended, or even replaced,
   7414 using the Python API.  The disassembler related features are contained
   7415 within the @code{gdb.disassembler} module:
   7416 
   7417 @anchor{DisassembleInfo Class}
   7418 @deftp {class} gdb.disassembler.DisassembleInfo
   7419 Disassembly is driven by instances of this class.  Each time
   7420 @value{GDBN} needs to disassemble an instruction, an instance of this
   7421 class is created and passed to a registered disassembler.  The
   7422 disassembler is then responsible for disassembling an instruction and
   7423 returning a result.
   7424 
   7425 Instances of this type are usually created within @value{GDBN},
   7426 however, it is possible to create a copy of an instance of this type,
   7427 see the description of @code{__init__} for more details.
   7428 
   7429 This class has the following properties and methods:
   7430 
   7431 @defvar DisassembleInfo.address
   7432 A read-only integer containing the address at which @value{GDBN}
   7433 wishes to disassemble a single instruction.
   7434 @end defvar
   7435 
   7436 @defvar DisassembleInfo.architecture
   7437 The @code{gdb.Architecture} (@pxref{Architectures In Python}) for
   7438 which @value{GDBN} is currently disassembling, this property is
   7439 read-only.
   7440 @end defvar
   7441 
   7442 @defvar DisassembleInfo.progspace
   7443 The @code{gdb.Progspace} (@pxref{Progspaces In Python,,Program Spaces
   7444 In Python}) for which @value{GDBN} is currently disassembling, this
   7445 property is read-only.
   7446 @end defvar
   7447 
   7448 @defun DisassembleInfo.is_valid ()
   7449 Returns @code{True} if the @code{DisassembleInfo} object is valid,
   7450 @code{False} if not.  A @code{DisassembleInfo} object will become
   7451 invalid once the disassembly call for which the @code{DisassembleInfo}
   7452 was created, has returned.  Calling other @code{DisassembleInfo}
   7453 methods, or accessing @code{DisassembleInfo} properties, will raise a
   7454 @code{RuntimeError} exception if it is invalid.
   7455 @end defun
   7456 
   7457 @defun DisassembleInfo.__init__ (info)
   7458 This can be used to create a new @code{DisassembleInfo} object that is
   7459 a copy of @var{info}.  The copy will have the same @code{address},
   7460 @code{architecture}, and @code{progspace} values as @var{info}, and
   7461 will become invalid at the same time as @var{info}.
   7462 
   7463 This method exists so that sub-classes of @code{DisassembleInfo} can
   7464 be created, these sub-classes must be initialized as copies of an
   7465 existing @code{DisassembleInfo} object, but sub-classes might choose
   7466 to override the @code{read_memory} method, and so control what
   7467 @value{GDBN} sees when reading from memory
   7468 (@pxref{builtin_disassemble}).
   7469 @end defun
   7470 
   7471 @defun DisassembleInfo.read_memory (length, offset)
   7472 This method allows the disassembler to read the bytes of the
   7473 instruction to be disassembled.  The method reads @var{length} bytes,
   7474 starting at @var{offset} from
   7475 @code{DisassembleInfo.address}.
   7476 
   7477 It is important that the disassembler read the instruction bytes using
   7478 this method, rather than reading inferior memory directly, as in some
   7479 cases @value{GDBN} disassembles from an internal buffer rather than
   7480 directly from inferior memory, calling this method handles this
   7481 detail.
   7482 
   7483 Returns a buffer object, which behaves much like an array or a string,
   7484 just as @code{Inferior.read_memory} does
   7485 (@pxref{gdbpy_inferior_read_memory,,Inferior.read_memory}).  The
   7486 length of the returned buffer will always be exactly @var{length}.
   7487 
   7488 If @value{GDBN} is unable to read the required memory then a
   7489 @code{gdb.MemoryError} exception is raised (@pxref{Exception
   7490 Handling}).
   7491 
   7492 This method can be overridden by a sub-class in order to control what
   7493 @value{GDBN} sees when reading from memory
   7494 (@pxref{builtin_disassemble}).  When overriding this method it is
   7495 important to understand how @code{builtin_disassemble} makes use of
   7496 this method.
   7497 
   7498 While disassembling a single instruction there could be multiple calls
   7499 to this method, and the same bytes might be read multiple times.  Any
   7500 single call might only read a subset of the total instruction bytes.
   7501 
   7502 If an implementation of @code{read_memory} is unable to read the
   7503 requested memory contents, for example, if there's a request to read
   7504 from an invalid memory address, then a @code{gdb.MemoryError} should
   7505 be raised.
   7506 
   7507 Raising a @code{MemoryError} inside @code{read_memory} does not
   7508 automatically mean a @code{MemoryError} will be raised by
   7509 @code{builtin_disassemble}.  It is possible the @value{GDBN}'s builtin
   7510 disassembler is probing to see how many bytes are available.  When
   7511 @code{read_memory} raises the @code{MemoryError} the builtin
   7512 disassembler might be able to perform a complete disassembly with the
   7513 bytes it has available, in this case @code{builtin_disassemble} will
   7514 not itself raise a @code{MemoryError}.
   7515 
   7516 Any other exception type raised in @code{read_memory} will propagate
   7517 back and be re-raised by @code{builtin_disassemble}.
   7518 @end defun
   7519 
   7520 @defun DisassembleInfo.text_part (style, string)
   7521 Create a new @code{DisassemblerTextPart} representing a piece of a
   7522 disassembled instruction.  @var{string} should be a non-empty string,
   7523 and @var{style} should be an appropriate style constant
   7524 (@pxref{Disassembler Style Constants}).
   7525 
   7526 Disassembler parts are used when creating a @code{DisassemblerResult}
   7527 in order to represent the styling within an instruction
   7528 (@pxref{DisassemblerResult Class}).
   7529 @end defun
   7530 
   7531 @defun DisassembleInfo.address_part (address)
   7532 Create a new @code{DisassemblerAddressPart}.  @var{address} is the
   7533 value of the absolute address this part represents.  A
   7534 @code{DisassemblerAddressPart} is displayed as an absolute address and
   7535 an associated symbol, the address and symbol are styled appropriately.
   7536 @end defun
   7537 
   7538 @end deftp
   7539 
   7540 @anchor{Disassembler Class}
   7541 @deftp {class} gdb.disassembler.Disassembler
   7542 This is a base class from which all user implemented disassemblers
   7543 must inherit.
   7544 
   7545 @defun Disassembler.__init__ (name)
   7546 The constructor takes @var{name}, a string, which should be a short
   7547 name for this disassembler.
   7548 @end defun
   7549 
   7550 @defun Disassembler.__call__ (info)
   7551 The @code{__call__} method must be overridden by sub-classes to
   7552 perform disassembly.  Calling @code{__call__} on this base class will
   7553 raise a @code{NotImplementedError} exception.
   7554 
   7555 The @var{info} argument is an instance of @code{DisassembleInfo}, and
   7556 describes the instruction that @value{GDBN} wants disassembling.
   7557 
   7558 If this function returns @code{None}, this indicates to @value{GDBN}
   7559 that this sub-class doesn't wish to disassemble the requested
   7560 instruction.  @value{GDBN} will then use its builtin disassembler to
   7561 perform the disassembly.
   7562 
   7563 Alternatively, this function can return a @code{DisassemblerResult}
   7564 that represents the disassembled instruction, this type is described
   7565 in more detail below.
   7566 
   7567 The @code{__call__} method can raise a @code{gdb.MemoryError}
   7568 exception (@pxref{Exception Handling}) to indicate to @value{GDBN}
   7569 that there was a problem accessing the required memory, this will then
   7570 be displayed by @value{GDBN} within the disassembler output.
   7571 
   7572 Ideally, the only three outcomes from invoking @code{__call__} would
   7573 be a return of @code{None}, a successful disassembly returned in a
   7574 @code{DisassemblerResult}, or a @code{MemoryError} indicating that
   7575 there was a problem reading memory.
   7576 
   7577 However, as an implementation of @code{__call__} could fail due to
   7578 other reasons, e.g.@: some external resource required to perform
   7579 disassembly is temporarily unavailable, then, if @code{__call__}
   7580 raises a @code{GdbError}, the exception will be converted to a string
   7581 and printed at the end of the disassembly output, the disassembly
   7582 request will then stop.
   7583 
   7584 Any other exception type raised by the @code{__call__} method is
   7585 considered an error in the user code, the exception will be printed to
   7586 the error stream according to the @kbd{set python print-stack} setting
   7587 (@pxref{set_python_print_stack,,@kbd{set python print-stack}}).
   7588 @end defun
   7589 @end deftp
   7590 
   7591 @anchor{DisassemblerResult Class}
   7592 @deftp {class} gdb.disassembler.DisassemblerResult
   7593 This class represents the result of disassembling a single
   7594 instruction.  An instance of this class will be returned from
   7595 @code{builtin_disassemble} (@pxref{builtin_disassemble}), and an
   7596 instance of this class should be returned from
   7597 @w{@code{Disassembler.__call__}} (@pxref{Disassembler Class}) if an
   7598 instruction was successfully disassembled.
   7599 
   7600 It is not possible to sub-class the @code{DisassemblerResult} class.
   7601 
   7602 The @code{DisassemblerResult} class has the following properties and
   7603 methods:
   7604 
   7605 @defun DisassemblerResult.__init__ (length, string, parts)
   7606 Initialize an instance of this class, @var{length} is the length of
   7607 the disassembled instruction in bytes, which must be greater than
   7608 zero.
   7609 
   7610 Only one of @var{string} or @var{parts} should be used to initialize a
   7611 new @code{DisassemblerResult}; the other one should be passed the
   7612 value @code{None}.  Alternatively, the arguments can be passed by
   7613 name, and the unused argument can be ignored.
   7614 
   7615 The @var{string} argument, if not @code{None}, is a non-empty string
   7616 that represents the entire disassembled instruction.  Building a result
   7617 object using the @var{string} argument does not allow for any styling
   7618 information to be included in the result.  @value{GDBN} will style the
   7619 result as a single @code{DisassemblerTextPart} with @code{STYLE_TEXT}
   7620 style (@pxref{Disassembler Styling Parts}).
   7621 
   7622 The @var{parts} argument, if not @code{None}, is a non-empty sequence
   7623 of @code{DisassemblerPart} objects.  Each part represents a small part
   7624 of the disassembled instruction along with associated styling
   7625 information.  A result object built using @var{parts} can be displayed
   7626 by @value{GDBN} with full styling information
   7627 (@pxref{style_disassembler_enabled,,@kbd{set style disassembler
   7628 enabled}}).
   7629 @end defun
   7630 
   7631 @defvar DisassemblerResult.length
   7632 A read-only property containing the length of the disassembled
   7633 instruction in bytes, this will always be greater than zero.
   7634 @end defvar
   7635 
   7636 @defvar DisassemblerResult.string
   7637 A read-only property containing a non-empty string representing the
   7638 disassembled instruction.  The @var{string} is a representation of the
   7639 disassembled instruction without any styling information.  To see how
   7640 the instruction will be styled use the @var{parts} property.
   7641 
   7642 If this instance was initialized using separate
   7643 @code{DisassemblerPart} objects, the @var{string} property will still
   7644 be valid.  The @var{string} value is created by concatenating the
   7645 @code{DisassemblerPart.string} values of each component part
   7646 (@pxref{Disassembler Styling Parts}).
   7647 @end defvar
   7648 
   7649 @defvar DisassemblerResult.parts
   7650 A read-only property containing a non-empty sequence of
   7651 @code{DisassemblerPart} objects.  Each @code{DisassemblerPart} object
   7652 contains a small part of the instruction along with information about
   7653 how that part should be styled.  @value{GDBN} uses this information to
   7654 create styled disassembler output
   7655 (@pxref{style_disassembler_enabled,,@kbd{set style disassembler
   7656 enabled}}).
   7657 
   7658 If this instance was initialized using a single string rather than
   7659 with a sequence of @code{DisassemblerPart} objects, the @var{parts}
   7660 property will still be valid.  In this case the @var{parts} property
   7661 will hold a sequence containing a single @code{DisassemblerTextPart}
   7662 object, the string of which will represent the entire instruction, and
   7663 the style of which will be @code{STYLE_TEXT}.
   7664 @end defvar
   7665 @end deftp
   7666 
   7667 @anchor{Disassembler Styling Parts}
   7668 @deftp {class} gdb.disassembler.DisassemblerPart
   7669 This is a parent class from which the different part sub-classes
   7670 inherit.  Only instances of the sub-classes detailed below will be
   7671 returned by the Python API.
   7672 
   7673 It is not possible to directly create instances of either this parent
   7674 class, or any of the sub-classes listed below.  Instances of the
   7675 sub-classes listed below are created by calling
   7676 @code{builtin_disassemble} (@pxref{builtin_disassemble}) and are
   7677 returned within the @code{DisassemblerResult} object, or can be
   7678 created by calling the @code{text_part} and @code{address_part}
   7679 methods on the @code{DisassembleInfo} class (@pxref{DisassembleInfo
   7680 Class}).
   7681 
   7682 The @code{DisassemblerPart} class has a single property:
   7683 
   7684 @defvar DisassemblerPart.string
   7685 A read-only property that contains a non-empty string representing
   7686 this part of the disassembled instruction.  The string within this
   7687 property doesn't include any styling information.
   7688 @end defvar
   7689 @end deftp
   7690 
   7691 @deftp {class} gdb.disassembler.DisassemblerTextPart
   7692 The @code{DisassemblerTextPart} class represents a piece of the
   7693 disassembled instruction and the associated style for that piece.
   7694 Instances of this class can't be created directly, instead call
   7695 @code{DisassembleInfo.text_part} to create a new instance of this
   7696 class (@pxref{DisassembleInfo Class}).
   7697 
   7698 As well as the properties of its parent class, the
   7699 @code{DisassemblerTextPart} has the following additional property:
   7700 
   7701 @defvar DisassemblerTextPart.style
   7702 A read-only property that contains one of the defined style constants.
   7703 @value{GDBN} will use this style when styling this part of the
   7704 disassembled instruction (@pxref{Disassembler Style Constants}).
   7705 @end defvar
   7706 @end deftp
   7707 
   7708 @deftp {class} gdb.disassembler.DisassemblerAddressPart
   7709 The @code{DisassemblerAddressPart} class represents an absolute
   7710 address within a disassembled instruction.  Using a
   7711 @code{DisassemblerAddressPart} instead of a
   7712 @code{DisassemblerTextPart} with @code{STYLE_ADDRESS} is preferred,
   7713 @value{GDBN} will display the address as both an absolute address, and
   7714 will look up a suitable symbol to display next to the address.  Using
   7715 @code{DisassemblerAddressPart} also ensures that user settings such as
   7716 @code{set print max-symbolic-offset} are respected.
   7717 
   7718 Here is an example of an x86-64 instruction:
   7719 
   7720 @smallexample
   7721 call   0x401136 <foo>
   7722 @end smallexample
   7723 
   7724 @noindent
   7725 In this instruction the @code{0x401136 <foo>} was generated from a
   7726 single @code{DisassemblerAddressPart}.  The @code{0x401136} will be
   7727 styled with @code{STYLE_ADDRESS}, and @code{foo} will be styled with
   7728 @code{STYLE_SYMBOL}.  The @code{<} and @code{>} will be styled as
   7729 @code{STYLE_TEXT}.
   7730 
   7731 If the inclusion of the symbol name is not required then a
   7732 @code{DisassemblerTextPart} with style @code{STYLE_ADDRESS} can be
   7733 used instead.
   7734 
   7735 Instances of this class can't be created directly, instead call
   7736 @code{DisassembleInfo.address_part} to create a new instance of this
   7737 class (@pxref{DisassembleInfo Class}).
   7738 
   7739 As well as the properties of its parent class, the
   7740 @code{DisassemblerAddressPart} has the following additional property:
   7741 
   7742 @defvar DisassemblerAddressPart.address
   7743 A read-only property that contains the @var{address} passed to this
   7744 object's @code{__init__} method.
   7745 @end defvar
   7746 @end deftp
   7747 
   7748 @anchor{Disassembler Style Constants}
   7749 
   7750 The following table lists all of the disassembler styles that are
   7751 available.  @value{GDBN} maps these style constants onto its style
   7752 settings (@pxref{Output Styling}).  In some cases, several style
   7753 constants produce the same style settings, and thus will produce the
   7754 same visual effect on the screen.  This could change in future
   7755 releases of @value{GDBN}, so care should be taken to select the
   7756 correct style constant to ensure correct output styling in future
   7757 releases of @value{GDBN}.
   7758 
   7759 @vtable @code
   7760 @vindex STYLE_TEXT
   7761 @item gdb.disassembler.STYLE_TEXT
   7762 This is the default style used by @value{GDBN} when styling
   7763 disassembler output.  This style should be used for any parts of the
   7764 instruction that don't fit any of the other styles listed below.
   7765 @value{GDBN} styles text with this style using its default style.
   7766 
   7767 @vindex STYLE_MNEMONIC
   7768 @item gdb.disassembler.STYLE_MNEMONIC
   7769 This style is used for styling the primary instruction mnemonic, which
   7770 usually appears at, or near, the start of the disassembled instruction
   7771 string.
   7772 
   7773 @value{GDBN} styles text with this style using the @code{disassembler
   7774 mnemonic} style setting.
   7775 
   7776 @vindex STYLE_SUB_MNEMONIC
   7777 @item gdb.disassembler.STYLE_SUB_MNEMONIC
   7778 This style is used for styling any sub-mnemonics within a disassembled
   7779 instruction.  A sub-mnemonic is any text within the instruction that
   7780 controls the function of the instruction, but which is disjoint from
   7781 the primary mnemonic (which will have styled @code{STYLE_MNEMONIC}).
   7782 
   7783 As an example, consider this AArch64 instruction:
   7784 
   7785 @smallexample
   7786 add	w16, w7, w1, lsl #1
   7787 @end smallexample
   7788 
   7789 @noindent
   7790 The @code{add} is the primary instruction mnemonic, and would be given
   7791 style @code{STYLE_MNEMONIC}, while @code{lsl} is the sub-mnemonic, and
   7792 would be given the style @code{STYLE_SUB_MNEMONIC}.
   7793 
   7794 @value{GDBN} styles text with this style using the @code{disassembler
   7795 mnemonic} style setting.
   7796 
   7797 @vindex STYLE_ASSEMBLER_DIRECTIVE
   7798 @item gdb.disassembler.STYLE_ASSEMBLER_DIRECTIVE
   7799 Sometimes a series of bytes doesn't decode to a valid instruction.  In
   7800 this case the disassembler may choose to represent the result of
   7801 disassembling using an assembler directive, for example:
   7802 
   7803 @smallexample
   7804 .word	0x1234
   7805 @end smallexample
   7806 
   7807 @noindent
   7808 In this case, the @code{.word} would be give the
   7809 @code{STYLE_ASSEMBLER_DIRECTIVE} style.  An assembler directive is
   7810 similar to a mnemonic in many ways but is something that is not part
   7811 of the architecture's instruction set.
   7812 
   7813 @value{GDBN} styles text with this style using the @code{disassembler
   7814 mnemonic} style setting.
   7815 
   7816 @vindex STYLE_REGISTER
   7817 @item gdb.disassembler.STYLE_REGISTER
   7818 This style is used for styling any text that represents a register
   7819 name, or register number, within a disassembled instruction.
   7820 
   7821 @value{GDBN} styles text with this style using the @code{disassembler
   7822 register} style setting.
   7823 
   7824 @vindex STYLE_ADDRESS
   7825 @item gdb.disassembler.STYLE_ADDRESS
   7826 This style is used for styling numerical values that represent
   7827 absolute addresses within the disassembled instruction.
   7828 
   7829 When creating a @code{DisassemblerTextPart} with this style, you
   7830 should consider if a @code{DisassemblerAddressPart} would be more
   7831 appropriate.  See @ref{Disassembler Styling Parts} for a description
   7832 of what each part offers.
   7833 
   7834 @value{GDBN} styles text with this style using the @code{disassembler
   7835 address} style setting.
   7836 
   7837 @vindex STYLE_ADDRESS_OFFSET
   7838 @item gdb.disassembler.STYLE_ADDRESS_OFFSET
   7839 This style is used for styling numerical values that represent offsets
   7840 to addresses within the disassembled instruction.  A value is
   7841 considered an address offset when the instruction itself is going to
   7842 access memory, and the value is being used to offset which address is
   7843 accessed.
   7844 
   7845 For example, an architecture might have an instruction that loads from
   7846 memory using an address within a register.  If that instruction also
   7847 allowed for an immediate offset to be encoded into the instruction,
   7848 this would be an address offset.  Similarly, a branch instruction
   7849 might jump to an address in a register plus an address offset that is
   7850 encoded into the instruction.
   7851 
   7852 @value{GDBN} styles text with this style using the @code{disassembler
   7853 immediate} style setting.
   7854 
   7855 @vindex STYLE_IMMEDIATE
   7856 @item gdb.disassembler.STYLE_IMMEDIATE
   7857 Use @code{STYLE_IMMEDIATE} for any numerical values within a
   7858 disassembled instruction when those values are not addresses, address
   7859 offsets, or register numbers (The styles @code{STYLE_ADDRESS},
   7860 @code{STYLE_ADDRESS_OFFSET}, or @code{STYLE_REGISTER} can be used in
   7861 those cases).
   7862 
   7863 @value{GDBN} styles text with this style using the @code{disassembler
   7864 immediate} style setting.
   7865 
   7866 @vindex STYLE_SYMBOL
   7867 @item gdb.disassembler.STYLE_SYMBOL
   7868 This style is used for styling the textual name of a symbol that is
   7869 included within a disassembled instruction.  A symbol name is often
   7870 included next to an absolute address within a disassembled instruction
   7871 to make it easier for the user to understand what the address is
   7872 referring too.  For example:
   7873 
   7874 @smallexample
   7875 call   0x401136 <foo>
   7876 @end smallexample
   7877 
   7878 @noindent
   7879 Here @code{foo} is the name of a symbol, and should be given the
   7880 @code{STYLE_SYMBOL} style.
   7881 
   7882 Adding symbols next to absolute addresses like this is handled
   7883 automatically by the @code{DisassemblerAddressPart} class
   7884 (@pxref{Disassembler Styling Parts}).
   7885 
   7886 @value{GDBN} styles text with this style using the @code{disassembler
   7887 symbol} style setting.
   7888 
   7889 @vindex STYLE_COMMENT_START
   7890 @item gdb.disassembler.STYLE_COMMENT_START
   7891 This style is used to start a line comment in the disassembly output.
   7892 Unlike other styles, which only apply to the single
   7893 @code{DisassemblerTextPiece} to which they are applied, the comment
   7894 style is sticky, and overrides the style of any further pieces within
   7895 this instruction.
   7896 
   7897 This means that, after a @code{STYLE_COMMENT_START} piece has been
   7898 seen, @value{GDBN} will apply the comment style until the end of the
   7899 line, ignoring the specific style within a piece.
   7900 
   7901 @value{GDBN} styles text with this style using the @code{disassembler
   7902 comment} style setting.
   7903 @end vtable
   7904 
   7905 The following functions are also contained in the
   7906 @code{gdb.disassembler} module:
   7907 
   7908 @defun register_disassembler (disassembler, architecture)
   7909 The @var{disassembler} must be a sub-class of
   7910 @code{gdb.disassembler.Disassembler} or @code{None}.
   7911 
   7912 The optional @var{architecture} is either a string, or the value
   7913 @code{None}.  If it is a string, then it should be the name of an
   7914 architecture known to @value{GDBN}, as returned either from
   7915 @code{gdb.Architecture.name}
   7916 (@pxref{gdbpy_architecture_name,,gdb.Architecture.name}), or from
   7917 @code{gdb.architecture_names}
   7918 (@pxref{gdb_architecture_names,,gdb.architecture_names}).
   7919 
   7920 The @var{disassembler} will be installed for the architecture named by
   7921 @var{architecture}, or if @var{architecture} is @code{None}, then
   7922 @var{disassembler} will be installed as a global disassembler for use
   7923 by all architectures.
   7924 
   7925 @cindex disassembler in Python, global vs.@: specific
   7926 @cindex search order for disassembler in Python
   7927 @cindex look up of disassembler in Python
   7928 @value{GDBN} only records a single disassembler for each architecture,
   7929 and a single global disassembler.  Calling
   7930 @code{register_disassembler} for an architecture, or for the global
   7931 disassembler, will replace any existing disassembler registered for
   7932 that @var{architecture} value.  The previous disassembler is returned.
   7933 
   7934 If @var{disassembler} is @code{None} then any disassembler currently
   7935 registered for @var{architecture} is deregistered and returned.
   7936 
   7937 When @value{GDBN} is looking for a disassembler to use, @value{GDBN}
   7938 first looks for an architecture specific disassembler.  If none has
   7939 been registered then @value{GDBN} looks for a global disassembler (one
   7940 registered with @var{architecture} set to @code{None}).  Only one
   7941 disassembler is called to perform disassembly, so, if there is both an
   7942 architecture specific disassembler, and a global disassembler
   7943 registered, it is the architecture specific disassembler that will be
   7944 used.
   7945 
   7946 @value{GDBN} tracks the architecture specific, and global
   7947 disassemblers separately, so it doesn't matter in which order
   7948 disassemblers are created or registered; an architecture specific
   7949 disassembler, if present, will always be used in preference to a
   7950 global disassembler.
   7951 
   7952 You can use the @kbd{maint info python-disassemblers} command
   7953 (@pxref{maint info python-disassemblers}) to see which disassemblers
   7954 have been registered.
   7955 @end defun
   7956 
   7957 @anchor{builtin_disassemble}
   7958 @defun builtin_disassemble (info)
   7959 This function calls back into @value{GDBN}'s builtin disassembler to
   7960 disassemble the instruction identified by @var{info}, an instance, or
   7961 sub-class, of @code{DisassembleInfo}.
   7962 
   7963 When the builtin disassembler needs to read memory the
   7964 @code{read_memory} method on @var{info} will be called.  By
   7965 sub-classing @code{DisassembleInfo} and overriding the
   7966 @code{read_memory} method, it is possible to intercept calls to
   7967 @code{read_memory} from the builtin disassembler, and to modify the
   7968 values returned.
   7969 
   7970 It is important to understand that, even when
   7971 @code{DisassembleInfo.read_memory} raises a @code{gdb.MemoryError}, it
   7972 is the internal disassembler itself that reports the memory error to
   7973 @value{GDBN}.  The reason for this is that the disassembler might
   7974 probe memory to see if a byte is readable or not; if the byte can't be
   7975 read then the disassembler may choose not to report an error, but
   7976 instead to disassemble the bytes that it does have available.
   7977 
   7978 If the builtin disassembler is successful then an instance of
   7979 @code{DisassemblerResult} is returned from @code{builtin_disassemble},
   7980 alternatively, if something goes wrong, an exception will be raised.
   7981 
   7982 A @code{MemoryError} will be raised if @code{builtin_disassemble} is
   7983 unable to read some memory that is required in order to perform
   7984 disassembly correctly.
   7985 
   7986 Any exception that is not a @code{MemoryError}, that is raised in a
   7987 call to @code{read_memory}, will pass through
   7988 @code{builtin_disassemble}, and be visible to the caller.
   7989 
   7990 Finally, there are a few cases where @value{GDBN}'s builtin
   7991 disassembler can fail for reasons that are not covered by
   7992 @code{MemoryError}.  In these cases, a @code{GdbError} will be raised.
   7993 The contents of the exception will be a string describing the problem
   7994 the disassembler encountered.
   7995 @end defun
   7996 
   7997 Here is an example that registers a global disassembler.  The new
   7998 disassembler invokes the builtin disassembler, and then adds a
   7999 comment, @code{## Comment}, to each line of disassembly output:
   8000 
   8001 @smallexample
   8002 class ExampleDisassembler(gdb.disassembler.Disassembler):
   8003     def __init__(self):
   8004         super().__init__("ExampleDisassembler")
   8005 
   8006     def __call__(self, info):
   8007         result = gdb.disassembler.builtin_disassemble(info)
   8008         length = result.length
   8009         text = result.string + "\t## Comment"
   8010         return gdb.disassembler.DisassemblerResult(length, text)
   8011 
   8012 gdb.disassembler.register_disassembler(ExampleDisassembler())
   8013 @end smallexample
   8014 
   8015 The following example creates a sub-class of @code{DisassembleInfo} in
   8016 order to intercept the @code{read_memory} calls, within
   8017 @code{read_memory} any bytes read from memory have the two 4-bit
   8018 nibbles swapped around.  This isn't a very useful adjustment, but
   8019 serves as an example.
   8020 
   8021 @smallexample
   8022 class MyInfo(gdb.disassembler.DisassembleInfo):
   8023     def __init__(self, info):
   8024         super().__init__(info)
   8025 
   8026     def read_memory(self, length, offset):
   8027         buffer = super().read_memory(length, offset)
   8028         result = bytearray()
   8029         for b in buffer:
   8030             v = int.from_bytes(b, 'little')
   8031             v = (v << 4) & 0xf0 | (v >> 4)
   8032             result.append(v)
   8033         return memoryview(result)
   8034 
   8035 class NibbleSwapDisassembler(gdb.disassembler.Disassembler):
   8036     def __init__(self):
   8037         super().__init__("NibbleSwapDisassembler")
   8038 
   8039     def __call__(self, info):
   8040         info = MyInfo(info)
   8041         return gdb.disassembler.builtin_disassemble(info)
   8042 
   8043 gdb.disassembler.register_disassembler(NibbleSwapDisassembler())
   8044 @end smallexample
   8045 
   8046 @node Missing Debug Info In Python
   8047 @subsubsection Missing Debug Info In Python
   8048 @cindex python, handle missing debug information
   8049 
   8050 When @value{GDBN} encounters a new objfile (@pxref{Objfiles In
   8051 Python}), e.g.@: the primary executable, or any shared libraries used
   8052 by the inferior, @value{GDBN} will attempt to load the corresponding
   8053 debug information for that objfile.  The debug information might be
   8054 found within the objfile itself, or within a separate objfile which
   8055 @value{GDBN} will automatically locate and load.
   8056 
   8057 Sometimes though, @value{GDBN} might not find any debug information
   8058 for an objfile, in this case the debugging experience will be
   8059 restricted.
   8060 
   8061 If @value{GDBN} fails to locate any debug information for a particular
   8062 objfile, there is an opportunity for a Python extension to step in.  A
   8063 Python extension can potentially locate the missing debug information
   8064 using some platform- or project-specific steps, and inform
   8065 @value{GDBN} of its location.  Or a Python extension might provide
   8066 some platform- or project-specific advice to the user about how to
   8067 obtain the missing debug information.
   8068 
   8069 A missing debug information Python extension consists of a handler
   8070 object which has the @code{name} and @code{enabled} attributes, and
   8071 implements the @code{__call__} method.  When @value{GDBN} encounters
   8072 an objfile for which it is unable to find any debug information, it
   8073 invokes the @code{__call__} method.  Full details of how handlers are
   8074 written can be found below.
   8075 
   8076 @subheading The @code{gdb.missing_debug} Module
   8077 
   8078 @value{GDBN} comes with a @code{gdb.missing_debug} module which
   8079 contains the following class and global function:
   8080 
   8081 @deftp{class} gdb.missing_debug.MissingDebugHandler
   8082 
   8083 @code{MissingDebugHandler} is a base class from which user-created
   8084 handlers can derive, though it is not required that handlers derive
   8085 from this class, so long as any user created handler has the
   8086 @code{name} and @code{enabled} attributes, and implements the
   8087 @code{__call__} method.
   8088 
   8089 @defun MissingDebugHandler.__init__ (name)
   8090 The @var{name} is a string used to reference this missing debug
   8091 handler within some @value{GDBN} commands.  Valid names consist of the
   8092 characters @code{[-_a-zA-Z0-9]}, creating a handler with an invalid
   8093 name raises a @code{ValueError} exception.
   8094 @end defun
   8095 
   8096 @defun MissingDebugHandler.__call__ (objfile)
   8097 Sub-classes must override the @code{__call__} method.  The
   8098 @var{objfile} argument will be a @code{gdb.Objfile}, this is the
   8099 objfile for which @value{GDBN} was unable to find any debug
   8100 information.
   8101 
   8102 The return value from the @code{__call__} method indicates what
   8103 @value{GDBN} should do next.  The possible return values are:
   8104 
   8105 @itemize @bullet
   8106 @item @code{None}
   8107 
   8108 This indicates that this handler could not help with @var{objfile},
   8109 @value{GDBN} should call any other registered handlers.
   8110 
   8111 @item @code{True}
   8112 
   8113 This indicates that this handler has installed the debug information
   8114 into a location where @value{GDBN} would normally expect to find it
   8115 when looking for separate debug information files (@pxref{Separate
   8116 Debug Files}).  @value{GDBN} will repeat the normal lookup process,
   8117 which should now find the separate debug file.
   8118 
   8119 If @value{GDBN} still doesn't find the separate debug information file
   8120 after this second attempt, then the Python missing debug information
   8121 handlers are not invoked a second time, this prevents a badly behaved
   8122 handler causing @value{GDBN} to get stuck in a loop.  @value{GDBN}
   8123 will continue without any debug information for @var{objfile}.
   8124 
   8125 @item @code{False}
   8126 
   8127 This indicates that this handler has done everything that it intends
   8128 to do with @var{objfile}, but no separate debug information can be
   8129 found.  @value{GDBN} will not call any other registered handlers for
   8130 @var{objfile}.  @value{GDBN} will continue without debugging
   8131 information for @var{objfile}.
   8132 
   8133 @item A string
   8134 
   8135 The returned string should contain a filename.  @value{GDBN} will not
   8136 call any further registered handlers, and will instead load the debug
   8137 information from the file identified by the returned filename.
   8138 @end itemize
   8139 
   8140 Invoking the @code{__call__} method from this base class will raise a
   8141 @code{NotImplementedError} exception.
   8142 @end defun
   8143 
   8144 @defvar MissingDebugHandler.name
   8145 A read-only attribute which is a string, the name of this handler
   8146 passed to the @code{__init__} method.
   8147 @end defvar
   8148 
   8149 @defvar MissingDebugHandler.enabled
   8150 A modifiable attribute containing a boolean; when @code{True}, the
   8151 handler is enabled, and will be used by @value{GDBN}.  When
   8152 @code{False}, the handler has been disabled, and will not be used.
   8153 @end defvar
   8154 @end deftp
   8155 
   8156 @defun gdb.missing_debug.register_handler (locus, handler, replace=@code{False})
   8157 Register a new missing debug handler with @value{GDBN}.
   8158 
   8159 @var{handler} is an instance of a sub-class of
   8160 @code{MissingDebugHandler}, or at least an instance of an object that
   8161 has the same attributes and methods as @code{MissingDebugHandler}.
   8162 
   8163 @var{locus} specifies to which handler list to prepend @var{handler}.
   8164 It can be either a @code{gdb.Progspace} (@pxref{Progspaces In Python})
   8165 or @code{None}, in which case the handler is registered globally.  The
   8166 newly registered @var{handler} will be called before any other handler
   8167 from the same locus.  Two handlers in the same locus cannot have the
   8168 same name, an attempt to add a handler with an already existing name
   8169 raises an exception unless @var{replace} is @code{True}, in which case
   8170 the old handler is deleted and the new handler is prepended to the
   8171 selected handler list.
   8172 
   8173 @value{GDBN} first calls the handlers for the current program space,
   8174 and then the globally registered handlers.  As soon as a handler
   8175 returns a value other than @code{None}, no further handlers are called
   8176 for this objfile.
   8177 @end defun
   8178 
   8179 @node Missing Objfiles In Python
   8180 @subsubsection Missing Objfiles In Python
   8181 @cindex python, handle missing objfiles
   8182 
   8183 When @value{GDBN} opens a core file, for example with the
   8184 @kbd{core-file} command (@pxref{core-file command}), @value{GDBN} will
   8185 attempt to load the corresponding executable and shared libraries.
   8186 Often these files can be found on the local machine, but sometimes
   8187 these files cannot be found, in which case the debugging experience
   8188 will be restricted.
   8189 
   8190 If @value{GDBN} fails to locate a particular file then there is an
   8191 opportunity for a Python extension to step in.  A Python extension can
   8192 potentially locate the missing file using some platform- or
   8193 project-specific steps, and inform @value{GDBN} of its location.  Or a
   8194 Python extension might provide some platform- or project-specific
   8195 advice to the user about how to obtain the missing file.
   8196 
   8197 A missing-objfile Python extension consists of a handler object which
   8198 has the @code{name} and @code{enabled} attributes, and implements the
   8199 @code{__call__} method.  When @value{GDBN} encounters a situation
   8200 where a file cannot be found, but the build-id (@pxref{build ID}) for
   8201 the missing file is known, then the @code{__call__} method is invoked
   8202 to try and find the file.  Full details of how handlers are written
   8203 can be found below.
   8204 
   8205 @subheading The @code{gdb.missing_objfile} Module
   8206 
   8207 @value{GDBN} comes with a @code{gdb.missing_objfile} module which
   8208 contains the following class and global function:
   8209 
   8210 @deftp{class} gdb.missing_objfile.MissingObjfileHandler
   8211 
   8212 @code{MissingObjfileHandler} is a base class from which user-created
   8213 handlers can derive, though it is not required that handlers derive
   8214 from this class, so long as any user created handler has the
   8215 @code{name} and @code{enabled} attributes, and implements the
   8216 @code{__call__} method.
   8217 
   8218 @defun MissingObjfileHandler.__init__ (name)
   8219 The @var{name} is a string used to reference this missing-objfile
   8220 handler within some @value{GDBN} commands.  Valid names consist of the
   8221 characters @samp{[-_a-zA-Z0-9]}, creating a handler with an invalid
   8222 name raises a @code{ValueError} exception.
   8223 @end defun
   8224 
   8225 @defun MissingObjfileHandler.__call__ (pspace, build_id, filename)
   8226 
   8227 Sub-classes must override the @code{__call__} method.  The
   8228 @var{pspace} argument will be a @code{gdb.Progspace}
   8229 (@pxref{Progspaces In Python}), this is the program space in which
   8230 @value{GDBN} is looking for the missing file.
   8231 
   8232 The @var{build_id} argument is a string containing the build-id of the
   8233 file that is missing, this will be in the same format as returned by
   8234 @code{Objfile.build_id} (@pxref{Objfile.build_id}).
   8235 
   8236 The @var{filename} argument contains the name of the file that
   8237 @value{GDBN} is looking for.  This information is provided to allow
   8238 handlers to generate informative messages for the user.  A handler is
   8239 not required to place the missing file at this location.  There might
   8240 already be a file present at this location, but it might not match the
   8241 required build-id, in which case @value{GDBN} will have ignored it.
   8242 In some limited cases @value{GDBN} might not be able to establish the
   8243 @var{filename} of the file it is searching for, in this case
   8244 @value{GDBN} will use a string @samp{with build-id @var{build_id}} as a
   8245 replacement.
   8246 
   8247 The return value from the @code{__call__} method indicates what
   8248 @value{GDBN} should do next.  The possible return values are:
   8249 
   8250 @itemize @bullet
   8251 @item @code{None}
   8252 
   8253 This indicates that this handler could not locate the missing file and
   8254 @value{GDBN} should call any other registered handlers.
   8255 
   8256 @item @code{True}
   8257 
   8258 This indicates that this handler has installed the missing file into a
   8259 location where @value{GDBN} would normally expect to find it.  The
   8260 only location in which @value{GDBN} will look is within the
   8261 @file{.build-id} sub-directory within the @var{debug-file-directory}
   8262 (@pxref{debug-file-directory}).
   8263 
   8264 @value{GDBN} will repeat the normal lookup process, which should now
   8265 find the previously missing file.
   8266 
   8267 If @value{GDBN} still doesn't find file after this second attempt,
   8268 then the Python missing-objfile handlers are not invoked a second
   8269 time, this prevents a badly behaved handler causing @value{GDBN} to
   8270 get stuck in a loop.  @value{GDBN} will continue without the missing
   8271 file, though this will degrade the debugging experience.
   8272 
   8273 @item @code{False}
   8274 
   8275 This indicates that this handler has done everything that it intends
   8276 to do but the missing file could not be found.  @value{GDBN} will not
   8277 call any other registered handlers to look for the missing file.
   8278 @value{GDBN} will continue without the missing file, though this will
   8279 degrade the debugging experience.
   8280 
   8281 @item A string
   8282 
   8283 The returned string should contain a filename.  @value{GDBN} will not
   8284 call any further registered handlers, and will instead use the
   8285 returned filename as the missing file.
   8286 @end itemize
   8287 
   8288 Invoking the @code{__call__} method from this base class will raise a
   8289 @code{NotImplementedError} exception.
   8290 @end defun
   8291 
   8292 @defvar MissingObjfileHandler.name
   8293 A read-only attribute which is a string, the name of this handler
   8294 passed to the @code{__init__} method.
   8295 @end defvar
   8296 
   8297 @defvar MissingObjfileHandler.enabled
   8298 A modifiable attribute containing a boolean; when @code{True}, the
   8299 handler is enabled, and will be used by @value{GDBN}.  When
   8300 @code{False}, the handler has been disabled, and will not be used.
   8301 @end defvar
   8302 @end deftp
   8303 
   8304 @defun gdb.missing_objfile.register_handler (locus, handler, replace=@code{False})
   8305 Register a new missing-objfile handler with @value{GDBN}.
   8306 
   8307 @var{handler} is an instance of a sub-class of
   8308 @code{MissingObjfileHandler}, or at least an instance of an object that
   8309 has the same attributes and methods as @code{MissingObjfileHandler}.
   8310 
   8311 @var{locus} specifies to which handler list to prepend @var{handler}.
   8312 It can be either a @code{gdb.Progspace} (@pxref{Progspaces In Python})
   8313 or @code{None}, in which case the handler is registered globally.  The
   8314 newly registered @var{handler} will be called before any other handler
   8315 from the same locus.  Two handlers in the same locus cannot have the
   8316 same name, an attempt to add a handler with an already existing name
   8317 raises an exception unless @var{replace} is @code{True}, in which case
   8318 the old handler is deleted and the new handler is prepended to the
   8319 selected handler list.
   8320 
   8321 @value{GDBN} first calls the handlers for the current program space,
   8322 and then the globally registered handlers.  As soon as a handler
   8323 returns a value other than @code{None}, no further handlers are
   8324 called.
   8325 @end defun
   8326 
   8327 @subheading Managing Missing-Objfile Handlers
   8328 
   8329 @value{GDBN} defines the following commands to manage registered
   8330 missing-objfile handlers:
   8331 
   8332 @table @code
   8333 
   8334 @kindex info missing-objfile-handlers
   8335 @item info missing-objfile-handlers @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
   8336 Lists all registered missing-objfile handlers.  Arguments @var{locus}
   8337 and @var{name-regexp} are both optional and can be used to filter
   8338 which handlers are listed.
   8339 
   8340 The @var{locus} argument should be either @kbd{global},
   8341 @kbd{progspace}, or the name of an object file.  Only handlers
   8342 registered for the specified locus will be listed.
   8343 
   8344 The @var{name-regexp} is a regular expression used to match against
   8345 handler names.
   8346 
   8347 @kindex disable missing-objfile-handler
   8348 @item disable missing-objfile-handler @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
   8349 The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
   8350 missing-objfile-handlers} above, but instead of listing the matching
   8351 handlers, all of the matching handlers are disabled.  The
   8352 @code{enabled} field of each matching handler is set to @code{False}.
   8353 
   8354 @kindex enable missing-objfile-handler
   8355 @item enable missing-objfile-handler @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
   8356 The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
   8357 missing-objfile-handlers} above, but instead of listing the matching
   8358 handlers, all of the matching handlers are enabled.  The
   8359 @code{enabled} field of each matching handler is set to @code{True}.
   8360 @end table
   8361 
   8362 @node Python Auto-loading
   8363 @subsection Python Auto-loading
   8364 @cindex Python auto-loading
   8365 
   8366 When a new object file is read (for example, due to the @code{file}
   8367 command, or because the inferior has loaded a shared library),
   8368 @value{GDBN} will look for Python support scripts in several ways:
   8369 @file{@var{objfile}-gdb.py} and @code{.debug_gdb_scripts} section.
   8370 @xref{Auto-loading extensions}.
   8371 
   8372 The auto-loading feature is useful for supplying application-specific
   8373 debugging commands and scripts.
   8374 
   8375 Auto-loading can be enabled or disabled,
   8376 and the list of auto-loaded scripts can be printed.
   8377 
   8378 @table @code
   8379 @anchor{set auto-load python-scripts}
   8380 @kindex set auto-load python-scripts
   8381 @item set auto-load python-scripts [on|off]
   8382 Enable or disable the auto-loading of Python scripts.
   8383 
   8384 @anchor{show auto-load python-scripts}
   8385 @kindex show auto-load python-scripts
   8386 @item show auto-load python-scripts
   8387 Show whether auto-loading of Python scripts is enabled or disabled.
   8388 
   8389 @anchor{info auto-load python-scripts}
   8390 @kindex info auto-load python-scripts
   8391 @cindex print list of auto-loaded Python scripts
   8392 @item info auto-load python-scripts [@var{regexp}]
   8393 Print the list of all Python scripts that @value{GDBN} auto-loaded.
   8394 
   8395 Also printed is the list of Python scripts that were mentioned in
   8396 the @code{.debug_gdb_scripts} section and were either not found
   8397 (@pxref{dotdebug_gdb_scripts section}) or were not auto-loaded due to
   8398 @code{auto-load safe-path} rejection (@pxref{Auto-loading}).
   8399 This is useful because their names are not printed when @value{GDBN}
   8400 tries to load them and fails.  There may be many of them, and printing
   8401 an error message for each one is problematic.
   8402 
   8403 If @var{regexp} is supplied only Python scripts with matching names are printed.
   8404 
   8405 Example:
   8406 
   8407 @smallexample
   8408 (gdb) info auto-load python-scripts
   8409 Loaded Script
   8410 Yes    py-section-script.py
   8411        full name: /tmp/py-section-script.py
   8412 No     my-foo-pretty-printers.py
   8413 @end smallexample
   8414 @end table
   8415 
   8416 When reading an auto-loaded file or script, @value{GDBN} sets the
   8417 @dfn{current objfile}.  This is available via the @code{gdb.current_objfile}
   8418 function (@pxref{Objfiles In Python}).  This can be useful for
   8419 registering objfile-specific pretty-printers and frame-filters.
   8420 
   8421 @node Python modules
   8422 @subsection Python modules
   8423 @cindex python modules
   8424 
   8425 @value{GDBN} comes with several modules to assist writing Python code.
   8426 
   8427 @menu
   8428 * gdb.printing::       Building and registering pretty-printers.
   8429 * gdb.types::          Utilities for working with types.
   8430 * gdb.prompt::         Utilities for prompt value substitution.
   8431 * gdb.ptwrite::        Utilities for PTWRITE filter registration.
   8432 @end menu
   8433 
   8434 @node gdb.printing
   8435 @subsubsection gdb.printing
   8436 @cindex gdb.printing
   8437 
   8438 This module provides a collection of utilities for working with
   8439 pretty-printers.
   8440 
   8441 @table @code
   8442 @item PrettyPrinter (@var{name}, @var{subprinters}=None)
   8443 This class specifies the API that makes @samp{info pretty-printer},
   8444 @samp{enable pretty-printer} and @samp{disable pretty-printer} work.
   8445 Pretty-printers should generally inherit from this class.
   8446 
   8447 @item SubPrettyPrinter (@var{name})
   8448 For printers that handle multiple types, this class specifies the
   8449 corresponding API for the subprinters.
   8450 
   8451 @item RegexpCollectionPrettyPrinter (@var{name})
   8452 Utility class for handling multiple printers, all recognized via
   8453 regular expressions.
   8454 @xref{Writing a Pretty-Printer}, for an example.
   8455 
   8456 @item FlagEnumerationPrinter (@var{name})
   8457 A pretty-printer which handles printing of @code{enum} values.  Unlike
   8458 @value{GDBN}'s built-in @code{enum} printing, this printer attempts to
   8459 work properly when there is some overlap between the enumeration
   8460 constants.  The argument @var{name} is the name of the printer and
   8461 also the name of the @code{enum} type to look up.
   8462 
   8463 @item register_pretty_printer (@var{obj}, @var{printer}, @var{replace}=False)
   8464 Register @var{printer} with the pretty-printer list of @var{obj}.
   8465 If @var{replace} is @code{True} then any existing copy of the printer
   8466 is replaced.  Otherwise a @code{RuntimeError} exception is raised
   8467 if a printer with the same name already exists.
   8468 @end table
   8469 
   8470 @node gdb.types
   8471 @subsubsection gdb.types
   8472 @cindex gdb.types
   8473 
   8474 This module provides a collection of utilities for working with
   8475 @code{gdb.Type} objects.
   8476 
   8477 @table @code
   8478 @item get_basic_type (@var{type})
   8479 Return @var{type} with const and volatile qualifiers stripped,
   8480 and with typedefs and C@t{++} references converted to the underlying type.
   8481 
   8482 C@t{++} example:
   8483 
   8484 @smallexample
   8485 typedef const int const_int;
   8486 const_int foo (3);
   8487 const_int& foo_ref (foo);
   8488 int main () @{ return 0; @}
   8489 @end smallexample
   8490 
   8491 Then in gdb:
   8492 
   8493 @smallexample
   8494 (gdb) start
   8495 (gdb) python import gdb.types
   8496 (gdb) python foo_ref = gdb.parse_and_eval("foo_ref")
   8497 (gdb) python print gdb.types.get_basic_type(foo_ref.type)
   8498 int
   8499 @end smallexample
   8500 
   8501 @item has_field (@var{type}, @var{field})
   8502 Return @code{True} if @var{type}, assumed to be a type with fields
   8503 (e.g., a structure or union), has field @var{field}.
   8504 
   8505 @item make_enum_dict (@var{enum_type})
   8506 Return a Python @code{dictionary} type produced from @var{enum_type}.
   8507 
   8508 @item deep_items (@var{type})
   8509 Returns a Python iterator similar to the standard
   8510 @code{gdb.Type.iteritems} method, except that the iterator returned
   8511 by @code{deep_items} will recursively traverse anonymous struct or
   8512 union fields.  For example:
   8513 
   8514 @smallexample
   8515 struct A
   8516 @{
   8517     int a;
   8518     union @{
   8519         int b0;
   8520         int b1;
   8521     @};
   8522 @};
   8523 @end smallexample
   8524 
   8525 @noindent
   8526 Then in @value{GDBN}:
   8527 @smallexample
   8528 (@value{GDBP}) python import gdb.types
   8529 (@value{GDBP}) python struct_a = gdb.lookup_type("struct A")
   8530 (@value{GDBP}) python print struct_a.keys ()
   8531 @{['a', '']@}
   8532 (@value{GDBP}) python print [k for k,v in gdb.types.deep_items(struct_a)]
   8533 @{['a', 'b0', 'b1']@}
   8534 @end smallexample
   8535 
   8536 @item get_type_recognizers ()
   8537 Return a list of the enabled type recognizers for the current context.
   8538 This is called by @value{GDBN} during the type-printing process
   8539 (@pxref{Type Printing API}).
   8540 
   8541 @item apply_type_recognizers (recognizers, type_obj)
   8542 Apply the type recognizers, @var{recognizers}, to the type object
   8543 @var{type_obj}.  If any recognizer returns a string, return that
   8544 string.  Otherwise, return @code{None}.  This is called by
   8545 @value{GDBN} during the type-printing process (@pxref{Type Printing
   8546 API}).
   8547 
   8548 @item register_type_printer (locus, printer)
   8549 This is a convenience function to register a type printer
   8550 @var{printer}.  The printer must implement the type printer protocol.
   8551 The @var{locus} argument is either a @code{gdb.Objfile}, in which case
   8552 the printer is registered with that objfile; a @code{gdb.Progspace},
   8553 in which case the printer is registered with that progspace; or
   8554 @code{None}, in which case the printer is registered globally.
   8555 
   8556 @item TypePrinter
   8557 This is a base class that implements the type printer protocol.  Type
   8558 printers are encouraged, but not required, to derive from this class.
   8559 It defines a constructor:
   8560 
   8561 @defmethod TypePrinter __init__ (self, name)
   8562 Initialize the type printer with the given name.  The new printer
   8563 starts in the enabled state.
   8564 @end defmethod
   8565 
   8566 @end table
   8567 
   8568 @node gdb.prompt
   8569 @subsubsection gdb.prompt
   8570 @cindex gdb.prompt
   8571 
   8572 This module provides a method for prompt value-substitution.
   8573 
   8574 @table @code
   8575 @item substitute_prompt (@var{string})
   8576 Return @var{string} with escape sequences substituted by values.  Some
   8577 escape sequences take arguments.  You can specify arguments inside
   8578 ``@{@}'' immediately following the escape sequence.
   8579 
   8580 The escape sequences you can pass to this function are:
   8581 
   8582 @table @code
   8583 @item \\
   8584 Substitute a backslash.
   8585 @item \e
   8586 Substitute an ESC character.
   8587 @item \f
   8588 Substitute the selected frame; an argument names a frame parameter.
   8589 @item \n
   8590 Substitute a newline.
   8591 @item \p
   8592 Substitute a parameter's value; the argument names the parameter.
   8593 @item \r
   8594 Substitute a carriage return.
   8595 @item \t
   8596 Substitute the selected thread; an argument names a thread parameter.
   8597 @item \v
   8598 Substitute the version of GDB.
   8599 @item \w
   8600 Substitute the current working directory.
   8601 @item \[
   8602 Begin a sequence of non-printing characters.  These sequences are
   8603 typically used with the ESC character, and are not counted in the string
   8604 length.  Example: ``\[\e[0;34m\](gdb)\[\e[0m\]'' will return a
   8605 blue-colored ``(gdb)'' prompt where the length is five.
   8606 @item \]
   8607 End a sequence of non-printing characters.
   8608 @end table
   8609 
   8610 For example:
   8611 
   8612 @smallexample
   8613 substitute_prompt ("frame: \f, args: \p@{print frame-arguments@}")
   8614 @end smallexample
   8615 
   8616 @exdent will return the string:
   8617 
   8618 @smallexample
   8619 "frame: main, args: scalars"
   8620 @end smallexample
   8621 @end table
   8622 
   8623 @node gdb.ptwrite
   8624 @subsubsection gdb.ptwrite
   8625 @cindex gdb.ptwrite
   8626 
   8627 This module provides additional functionality for recording programs that
   8628 make use of the @code{PTWRITE} instruction.  @code{PTWRITE} is a x86
   8629 instruction that allows to write values into the Intel Processor Trace
   8630 (@pxref{Process Record and Replay}).
   8631 The @value{NGCC} intrinsics for it are:
   8632 @smallexample
   8633 void _ptwrite32 (unsigned int a)
   8634 void _ptwrite64 (unsigned __int64 a)
   8635 @end smallexample
   8636 
   8637 If an inferior uses the instruction, @value{GDBN} by default inserts the
   8638 raw payload value as auxiliary information into the execution history.
   8639 Auxiliary information is by default printed during
   8640 @code{record instruction-history}, @code{record function-call-history},
   8641 and all stepping commands, and is accessible in Python as a
   8642 @code{RecordAuxiliary} object (@pxref{Recordings In Python}).
   8643 
   8644 @exdent Sample program:
   8645 @smallexample
   8646 @group
   8647 #include <immintrin.h>
   8648 
   8649 void
   8650 ptwrite64 (unsigned long long value)
   8651 @{
   8652   _ptwrite64 (value);
   8653 @}
   8654 @end group
   8655 
   8656 @group
   8657 int
   8658 main (void)
   8659 @{
   8660   ptwrite64 (0x42);
   8661   return 0; /* break here.  */
   8662 @}
   8663 @end group
   8664 @end smallexample
   8665 
   8666 
   8667 @exdent @value{GDBN} output after recording the sample program in pt format:
   8668 @smallexample
   8669 @group
   8670 (gdb) record instruction-history 12,14
   8671 12         0x0040074c <ptwrite64+16>:   ptwrite %rbx
   8672 13           [0x42]
   8673 14         0x00400751 <ptwrite64+21>:   mov -0x8(%rbp),%rbx
   8674 (gdb) record function-call-history
   8675 1       main
   8676 2       ptwrite64
   8677           [0x42]
   8678 3       main
   8679 @end group
   8680 @end smallexample
   8681 
   8682 The @code{gdb.ptwrite} module allows customizing the default output of
   8683 @code{PTWRITE} auxiliary information.  A custom Python function can be
   8684 registered as the @code{PTWRITE} filter function.  This function will be
   8685 called with the @code{PTWRITE} payload and PC as arguments during trace
   8686 decoding.  The function can return a string, which will be printed by
   8687 @value{GDBN} during the aforementioned commands, or @code{None}, resulting
   8688 in no output.  To register such a filter function, the user needs to
   8689 provide a filter factory function, which returns a new filter function
   8690 object to be called by @value{GDBN}.
   8691 
   8692 @findex gdb.ptwrite.register_filter_factory
   8693 @defun register_filter_factory (filter_factory)
   8694 Used to register the @code{PTWRITE} filter factory.  This filter factory can
   8695 be any callable object that accepts one argument, the current thread as
   8696 a @code{gdb.InferiorThread}.
   8697 It can return None or a callable.  This callable is the @code{PTWRITE} filter
   8698 function for the specified thread.  If @code{None} is returned by the factory
   8699 function, the default auxiliary information will be printed.
   8700 @end defun
   8701 
   8702 @findex gdb.ptwrite.get_filter
   8703 @defun get_filter ()
   8704 Return the currently active @code{PTWRITE} filter function.
   8705 @end defun
   8706 
   8707 An example:
   8708 
   8709 @smallexample
   8710 @group
   8711 (gdb) python-interactive
   8712 >>> class my_filter():
   8713 ...    def __init__(self):
   8714 ...        self.var = 0
   8715 ...    def __call__(self, payload, ip):
   8716 ...        self.var += 1
   8717 ...        return f"counter: @{self.var@}, ip: @{ip:#x@}"
   8718 ...
   8719 >>> def my_filter_factory(thread):
   8720 ...    if thread.global_num == 1:
   8721 ...        return my_filter()
   8722 ...    else:
   8723 ...        return None
   8724 ...
   8725 >>> import gdb.ptwrite
   8726 >>> gdb.ptwrite.register_filter_factory(my_filter_factory)
   8727 >>>
   8728 @end group
   8729 
   8730 @group
   8731 (gdb) record function-call-history 59,64
   8732 59      pthread_create@@GLIBC_2.2.5
   8733 60      job()
   8734 61      task(void*)
   8735 62      ptwrite64(unsigned long)
   8736           [counter: 1, ip: 0x401156]
   8737 63      task(void*)
   8738 64      ptwrite32(unsigned int)
   8739           [counter: 2, ip: 0x40116c]
   8740 @end group
   8741 
   8742 @group
   8743 (gdb) info threads
   8744 * 1    Thread 0x7ffff7fd8740 (LWP 25796) "ptw_threads" task ()
   8745     at bin/ptwrite/ptw_threads.c:45
   8746   2    Thread 0x7ffff6eb8700 (LWP 25797) "ptw_threads" task ()
   8747     at bin/ptwrite/ptw_threads.c:45
   8748 @end group
   8749 
   8750 @group
   8751 (gdb) thread 2
   8752 [Switching to thread 2 (Thread 0x7ffff6eb8700 (LWP 25797))]
   8753 #0  task (arg=0x0) at ptwrite_threads.c:45
   8754 45        return NULL;
   8755 @end group
   8756 
   8757 @group
   8758 (gdb) record function-call-history 10,14
   8759 10    start_thread
   8760 11    task(void*)
   8761 12    ptwrite64(unsigned long)
   8762         [0x42]
   8763 13    task(void*)
   8764 14    ptwrite32(unsigned int)
   8765         [0x43]
   8766 @end group
   8767 @end smallexample
   8768 
   8769 This @value{GDBN} feature is dependent on hardware and operating system
   8770 support and requires the Intel Processor Trace decoder library in version
   8771 2.0.0 or newer.
   8772