This is gdb.info, produced by makeinfo version 7.1 from gdb.texinfo.

Copyright © 1988-2025 Free Software Foundation, Inc.

   Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "Free Software" and "Free Software Needs Free
Documentation", with the Front-Cover Texts being "A GNU Manual," and
with the Back-Cover Texts as in (a) below.

   (a) The FSF's Back-Cover Text is: "You are free to copy and modify
this GNU Manual.  Buying copies from GNU Press supports the FSF in
developing GNU and promoting software freedom."
INFO-DIR-SECTION Software development
START-INFO-DIR-ENTRY
* Gdb: (gdb).                     The GNU debugger.
* gdbserver: (gdb) Server.        The GNU debugging server.
END-INFO-DIR-ENTRY

   This file documents the GNU debugger GDB.

   This is the Tenth Edition, of ‘Debugging with GDB: the GNU
Source-Level Debugger’ for GDB (GDB) Version 17.2.

   Copyright © 1988-2025 Free Software Foundation, Inc.

   Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "Free Software" and "Free Software Needs Free
Documentation", with the Front-Cover Texts being "A GNU Manual," and
with the Back-Cover Texts as in (a) below.

   (a) The FSF's Back-Cover Text is: "You are free to copy and modify
this GNU Manual.  Buying copies from GNU Press supports the FSF in
developing GNU and promoting software freedom."


File: gdb.info,  Node: Frame Decorator API,  Next: Writing a Frame Filter,  Prev: Frame Filter API,  Up: Python API

23.3.2.11 Decorating Frames
...........................

Frame decorators are sister objects to frame filters (*note Frame Filter
API::).  Frame decorators are applied by a frame filter and can only be
used in conjunction with frame filters.

   The purpose of a frame decorator is to customize the printed content
of each ‘gdb.Frame’ in commands where frame filters are executed.  This
concept is called decorating a frame.  Frame decorators decorate a
‘gdb.Frame’ with Python code contained within each API call.  This
separates the actual data contained in a ‘gdb.Frame’ from the decorated
data produced by a frame decorator.  This abstraction is necessary to
maintain integrity of the data contained in each ‘gdb.Frame’.

   Frame decorators have a mandatory interface, defined below.

   GDB already contains a frame decorator called ‘FrameDecorator’.  This
contains substantial amounts of boilerplate code to decorate the content
of a ‘gdb.Frame’.  It is recommended that other frame decorators inherit
and extend this object, and only to override the methods needed.

   ‘FrameDecorator’ is defined in the Python module
‘gdb.FrameDecorator’, so your code can import it like:
     from gdb.FrameDecorator import FrameDecorator

 -- Function: FrameDecorator.elided (self)

     The ‘elided’ method groups frames together in a hierarchical
     system.  An example would be an interpreter, where multiple
     low-level frames make up a single call in the interpreted language.
     In this example, the frame filter would elide the low-level frames
     and present a single high-level frame, representing the call in the
     interpreted language, to the user.

     The ‘elided’ function must return an iterable and this iterable
     must contain the frames that are being elided wrapped in a suitable
     frame decorator.  If no frames are being elided this function may
     return an empty iterable, or ‘None’.  Elided frames are indented
     from normal frames in a ‘CLI’ backtrace, or in the case of GDB/MI,
     are placed in the ‘children’ field of the eliding frame.

     It is the frame filter's task to also filter out the elided frames
     from the source iterator.  This will avoid printing the frame
     twice.

 -- Function: FrameDecorator.function (self)

     This method returns the name of the function in the frame that is
     to be printed.

     This method must return a Python string describing the function, or
     ‘None’.

     If this function returns ‘None’, GDB will not print any data for
     this field.

 -- Function: FrameDecorator.address (self)

     This method returns the address of the frame that is to be printed.

     This method must return a Python numeric integer type of sufficient
     size to describe the address of the frame, or ‘None’.

     If this function returns a ‘None’, GDB will not print any data for
     this field.

 -- Function: FrameDecorator.filename (self)

     This method returns the filename and path associated with this
     frame.

     This method must return a Python string containing the filename and
     the path to the object file backing the frame, or ‘None’.

     If this function returns a ‘None’, GDB will not print any data for
     this field.

 -- Function: FrameDecorator.line (self):

     This method returns the line number associated with the current
     position within the function addressed by this frame.

     This method must return a Python integer type, or ‘None’.

     If this function returns a ‘None’, GDB will not print any data for
     this field.

 -- Function: FrameDecorator.frame_args (self)

     This method must return an iterable, or ‘None’.  Returning an empty
     iterable, or ‘None’ means frame arguments will not be printed for
     this frame.  This iterable must contain objects that implement two
     methods, described here.

     This object must implement a ‘symbol’ method which takes a single
     ‘self’ parameter and must return a ‘gdb.Symbol’ (*note Symbols In
     Python::), or a Python string.  The object must also implement a
     ‘value’ method which takes a single ‘self’ parameter and must
     return a ‘gdb.Value’ (*note Values From Inferior::), a Python
     value, or ‘None’.  If the ‘value’ method returns ‘None’, and the
     ‘argument’ method returns a ‘gdb.Symbol’, GDB will look-up and
     print the value of the ‘gdb.Symbol’ automatically.

     A brief example:

          class SymValueWrapper():

              def __init__(self, symbol, value):
                  self.sym = symbol
                  self.val = value

              def value(self):
                  return self.val

              def symbol(self):
                  return self.sym

          class SomeFrameDecorator()
          ...
          ...
              def frame_args(self):
                  args = []
                  try:
                      block = self.inferior_frame.block()
                  except:
                      return None

                  # Iterate over all symbols in a block.  Only add
                  # symbols that are arguments.
                  for sym in block:
                      if not sym.is_argument:
                          continue
                      args.append(SymValueWrapper(sym,None))

                  # Add example synthetic argument.
                  args.append(SymValueWrapper(``foo'', 42))

                  return args

 -- Function: FrameDecorator.frame_locals (self)

     This method must return an iterable or ‘None’.  Returning an empty
     iterable, or ‘None’ means frame local arguments will not be printed
     for this frame.

     The object interface, the description of the various strategies for
     reading frame locals, and the example are largely similar to those
     described in the ‘frame_args’ function, (*note The frame filter
     frame_args function: frame_args.).  Below is a modified example:

          class SomeFrameDecorator()
          ...
          ...
              def frame_locals(self):
                  vars = []
                  try:
                      block = self.inferior_frame.block()
                  except:
                      return None

                  # Iterate over all symbols in a block.  Add all
                  # symbols, except arguments.
                  for sym in block:
                      if sym.is_argument:
                          continue
                      vars.append(SymValueWrapper(sym,None))

                  # Add an example of a synthetic local variable.
                  vars.append(SymValueWrapper(``bar'', 99))

                  return vars

 -- Function: FrameDecorator.inferior_frame (self):

     This method must return the underlying ‘gdb.Frame’ that this frame
     decorator is decorating.  GDB requires the underlying frame for
     internal frame information to determine how to print certain values
     when printing a frame.


File: gdb.info,  Node: Writing a Frame Filter,  Next: Unwinding Frames in Python,  Prev: Frame Decorator API,  Up: Python API

23.3.2.12 Writing a Frame Filter
................................

There are three basic elements that a frame filter must implement: it
must correctly implement the documented interface (*note Frame Filter
API::), it must register itself with GDB, and finally, it must decide if
it is to work on the data provided by GDB.  In all cases, whether it
works on the iterator or not, each frame filter must return an iterator.
A bare-bones frame filter follows the pattern in the following example.

     import gdb

     class FrameFilter():

         def __init__(self):
             # Frame filter attribute creation.
             #
             # 'name' is the name of the filter that GDB will display.
             #
             # 'priority' is the priority of the filter relative to other
             # filters.
             #
             # 'enabled' is a boolean that indicates whether this filter is
             # enabled and should be executed.

             self.name = "Foo"
             self.priority = 100
             self.enabled = True

             # Register this frame filter with the global frame_filters
             # dictionary.
             gdb.frame_filters[self.name] = self

         def filter(self, frame_iter):
             # Just return the iterator.
             return frame_iter

   The frame filter in the example above implements the three
requirements for all frame filters.  It implements the API, self
registers, and makes a decision on the iterator (in this case, it just
returns the iterator untouched).

   The first step is attribute creation and assignment, and as shown in
the comments the filter assigns the following attributes: ‘name’,
‘priority’ and whether the filter should be enabled with the ‘enabled’
attribute.

   The second step is registering the frame filter with the dictionary
or dictionaries that the frame filter has interest in.  As shown in the
comments, this filter just registers itself with the global dictionary
‘gdb.frame_filters’.  As noted earlier, ‘gdb.frame_filters’ is a
dictionary that is initialized in the ‘gdb’ module when GDB starts.
What dictionary a filter registers with is an important consideration.
Generally, if a filter is specific to a set of code, it should be
registered either in the ‘objfile’ or ‘progspace’ dictionaries as they
are specific to the program currently loaded in GDB.  The global
dictionary is always present in GDB and is never unloaded.  Any filters
registered with the global dictionary will exist until GDB exits.  To
avoid filters that may conflict, it is generally better to register
frame filters against the dictionaries that more closely align with the
usage of the filter currently in question.  *Note Python Auto-loading::,
for further information on auto-loading Python scripts.

   GDB takes a hands-off approach to frame filter registration,
therefore it is the frame filter's responsibility to ensure registration
has occurred, and that any exceptions are handled appropriately.  In
particular, you may wish to handle exceptions relating to Python
dictionary key uniqueness.  It is mandatory that the dictionary key is
the same as frame filter's ‘name’ attribute.  When a user manages frame
filters (*note Frame Filter Management::), the names GDB will display
are those contained in the ‘name’ attribute.

   The final step of this example is the implementation of the ‘filter’
method.  As shown in the example comments, we define the ‘filter’ method
and note that the method must take an iterator, and also must return an
iterator.  In this bare-bones example, the frame filter is not very
useful as it just returns the iterator untouched.  However this is a
valid operation for frame filters that have the ‘enabled’ attribute set,
but decide not to operate on any frames.

   In the next example, the frame filter operates on all frames and
utilizes a frame decorator to perform some work on the frames.  *Note
Frame Decorator API::, for further information on the frame decorator
interface.

   This example works on inlined frames.  It highlights frames which are
inlined by tagging them with an "[inlined]" tag.  By applying a frame
decorator to all frames with the Python ‘itertools imap’ method, the
example defers actions to the frame decorator.  Frame decorators are
only processed when GDB prints the backtrace.

   This introduces a new decision making topic: whether to perform
decision making operations at the filtering step, or at the printing
step.  In this example's approach, it does not perform any filtering
decisions at the filtering step beyond mapping a frame decorator to each
frame.  This allows the actual decision making to be performed when each
frame is printed.  This is an important consideration, and well worth
reflecting upon when designing a frame filter.  An issue that frame
filters should avoid is unwinding the stack if possible.  Some stacks
can run very deep, into the tens of thousands in some cases.  To search
every frame to determine if it is inlined ahead of time may be too
expensive at the filtering step.  The frame filter cannot know how many
frames it has to iterate over, and it would have to iterate through them
all.  This ends up duplicating effort as GDB performs this iteration
when it prints the frames.

   In this example decision making can be deferred to the printing step.
As each frame is printed, the frame decorator can examine each frame in
turn when GDB iterates.  From a performance viewpoint, this is the most
appropriate decision to make as it avoids duplicating the effort that
the printing step would undertake anyway.  Also, if there are many frame
filters unwinding the stack during filtering, it can substantially delay
the printing of the backtrace which will result in large memory usage,
and a poor user experience.

     class InlineFilter():

         def __init__(self):
             self.name = "InlinedFrameFilter"
             self.priority = 100
             self.enabled = True
             gdb.frame_filters[self.name] = self

         def filter(self, frame_iter):
             frame_iter = itertools.imap(InlinedFrameDecorator,
                                         frame_iter)
             return frame_iter

   This frame filter is somewhat similar to the earlier example, except
that the ‘filter’ method applies a frame decorator object called
‘InlinedFrameDecorator’ to each element in the iterator.  The ‘imap’
Python method is light-weight.  It does not proactively iterate over the
iterator, but rather creates a new iterator which wraps the existing
one.

   Below is the frame decorator for this example.

     class InlinedFrameDecorator(FrameDecorator):

         def __init__(self, fobj):
             super(InlinedFrameDecorator, self).__init__(fobj)

         def function(self):
             frame = self.inferior_frame()
             name = str(frame.name())

             if frame.type() == gdb.INLINE_FRAME:
                 name = name + " [inlined]"

             return name

   This frame decorator only defines and overrides the ‘function’
method.  It lets the supplied ‘FrameDecorator’, which is shipped with
GDB, perform the other work associated with printing this frame.

   The combination of these two objects create this output from a
backtrace:

     #0  0x004004e0 in bar () at inline.c:11
     #1  0x00400566 in max [inlined] (b=6, a=12) at inline.c:21
     #2  0x00400566 in main () at inline.c:31

   So in the case of this example, a frame decorator is applied to all
frames, regardless of whether they may be inlined or not.  As GDB
iterates over the iterator produced by the frame filters, GDB executes
each frame decorator which then makes a decision on what to print in the
‘function’ callback.  Using a strategy like this is a way to defer
decisions on the frame content to printing time.

Eliding Frames
--------------

It might be that the above example is not desirable for representing
inlined frames, and a hierarchical approach may be preferred.  If we
want to hierarchically represent frames, the ‘elided’ frame decorator
interface might be preferable.

   This example approaches the issue with the ‘elided’ method.  This
example is quite long, but very simplistic.  It is out-of-scope for this
section to write a complete example that comprehensively covers all
approaches of finding and printing inlined frames.  However, this
example illustrates the approach an author might use.

   This example comprises of three sections.

     class InlineFrameFilter():

         def __init__(self):
             self.name = "InlinedFrameFilter"
             self.priority = 100
             self.enabled = True
             gdb.frame_filters[self.name] = self

         def filter(self, frame_iter):
             return ElidingInlineIterator(frame_iter)

   This frame filter is very similar to the other examples.  The only
difference is this frame filter is wrapping the iterator provided to it
(‘frame_iter’) with a custom iterator called ‘ElidingInlineIterator’.
This again defers actions to when GDB prints the backtrace, as the
iterator is not traversed until printing.

   The iterator for this example is as follows.  It is in this section
of the example where decisions are made on the content of the backtrace.

     class ElidingInlineIterator:
         def __init__(self, ii):
             self.input_iterator = ii

         def __iter__(self):
             return self

         def next(self):
             frame = next(self.input_iterator)

             if frame.inferior_frame().type() != gdb.INLINE_FRAME:
                 return frame

             try:
                 eliding_frame = next(self.input_iterator)
             except StopIteration:
                 return frame
             return ElidingFrameDecorator(eliding_frame, [frame])

   This iterator implements the Python iterator protocol.  When the
‘next’ function is called (when GDB prints each frame), the iterator
checks if this frame decorator, ‘frame’, is wrapping an inlined frame.
If it is not, it returns the existing frame decorator untouched.  If it
is wrapping an inlined frame, it assumes that the inlined frame was
contained within the next oldest frame, ‘eliding_frame’, which it
fetches.  It then creates and returns a frame decorator,
‘ElidingFrameDecorator’, which contains both the elided frame, and the
eliding frame.

     class ElidingInlineDecorator(FrameDecorator):

         def __init__(self, frame, elided_frames):
             super(ElidingInlineDecorator, self).__init__(frame)
             self.frame = frame
             self.elided_frames = elided_frames

         def elided(self):
             return iter(self.elided_frames)

   This frame decorator overrides one function and returns the inlined
frame in the ‘elided’ method.  As before it lets ‘FrameDecorator’ do the
rest of the work involved in printing this frame.  This produces the
following output.

     #0  0x004004e0 in bar () at inline.c:11
     #2  0x00400529 in main () at inline.c:25
         #1  0x00400529 in max (b=6, a=12) at inline.c:15

   In that output, ‘max’ which has been inlined into ‘main’ is printed
hierarchically.  Another approach would be to combine the ‘function’
method, and the ‘elided’ method to both print a marker in the inlined
frame, and also show the hierarchical relationship.


File: gdb.info,  Node: Unwinding Frames in Python,  Next: Xmethods In Python,  Prev: Writing a Frame Filter,  Up: Python API

23.3.2.13 Unwinding Frames in Python
....................................

In GDB terminology "unwinding" is the process of finding the previous
frame (that is, caller's) from the current one.  An unwinder has three
methods.  The first one checks if it can handle given frame ("sniff"
it).  For the frames it can sniff an unwinder provides two additional
methods: it can return frame's ID, and it can fetch registers from the
previous frame.  A running GDB maintains a list of the unwinders and
calls each unwinder's sniffer in turn until it finds the one that
recognizes the current frame.  There is an API to register an unwinder.

   The unwinders that come with GDB handle standard frames.  However,
mixed language applications (for example, an application running Java
Virtual Machine) sometimes use frame layouts that cannot be handled by
the GDB unwinders.  You can write Python code that can handle such
custom frames.

   You implement a frame unwinder in Python as a class with which has
two attributes, ‘name’ and ‘enabled’, with obvious meanings, and a
single method ‘__call__’, which examines a given frame and returns an
object (an instance of ‘gdb.UnwindInfo class)’ describing it.  If an
unwinder does not recognize a frame, it should return ‘None’.  The code
in GDB that enables writing unwinders in Python uses this object to
return frame's ID and previous frame registers when GDB core asks for
them.

   An unwinder should do as little work as possible.  Some otherwise
innocuous operations can cause problems (even crashes, as this code is
not well-hardened yet).  For example, making an inferior call from an
unwinder is unadvisable, as an inferior call will reset GDB's stack
unwinding process, potentially causing re-entrant unwinding.

Unwinder Input
--------------

An object passed to an unwinder (a ‘gdb.PendingFrame’ instance) provides
a method to read frame's registers:

 -- Function: PendingFrame.read_register (register)
     This method returns the contents of REGISTER in the frame as a
     ‘gdb.Value’ object.  For a description of the acceptable values of
     REGISTER see *note Frame.read_register: gdbpy_frame_read_register.
     If REGISTER does not name a register for the current architecture,
     this method will throw an exception.

     Note that this method will always return a ‘gdb.Value’ for a valid
     register name.  This does not mean that the value will be valid.
     For example, you may request a register that an earlier unwinder
     could not unwind--the value will be unavailable.  Instead, the
     ‘gdb.Value’ returned from this method will be lazy; that is, its
     underlying bits will not be fetched until it is first used.  So,
     attempting to use such a value will cause an exception at the point
     of use.

     The type of the returned ‘gdb.Value’ depends on the register and
     the architecture.  It is common for registers to have a scalar
     type, like ‘long long’; but many other types are possible, such as
     pointer, pointer-to-function, floating point or vector types.

   It also provides a factory method to create a ‘gdb.UnwindInfo’
instance to be returned to GDB:

 -- Function: PendingFrame.create_unwind_info (frame_id)
     Returns a new ‘gdb.UnwindInfo’ instance identified by given
     FRAME_ID.  The FRAME_ID is used internally by GDB to identify the
     frames within the current thread's stack.  The attributes of
     FRAME_ID determine what type of frame is created within GDB:

     ‘sp, pc’
          The frame is identified by the given stack address and PC. The
          stack address must be chosen so that it is constant throughout
          the lifetime of the frame, so a typical choice is the value of
          the stack pointer at the start of the function--in the DWARF
          standard, this would be the "Call Frame Address".

          This is the most common case by far.  The other cases are
          documented for completeness but are only useful in specialized
          situations.

     ‘sp, pc, special’
          The frame is identified by the stack address, the PC, and a
          "special" address.  The special address is used on
          architectures that can have frames that do not change the
          stack, but which are still distinct, for example the IA-64,
          which has a second stack for registers.  Both SP and SPECIAL
          must be constant throughout the lifetime of the frame.

     ‘sp’
          The frame is identified by the stack address only.  Any other
          stack frame with a matching SP will be considered to match
          this frame.  Inside gdb, this is called a "wild frame".  You
          will never need this.

     Each attribute value should either be an instance of ‘gdb.Value’ or
     an integer.

     A helper class is provided in the ‘gdb.unwinder’ module that can be
     used to represent a frame-id (*note gdb.unwinder.FrameId::).

 -- Function: PendingFrame.architecture ()
     Return the ‘gdb.Architecture’ (*note Architectures In Python::) for
     this ‘gdb.PendingFrame’.  This represents the architecture of the
     particular frame being unwound.

 -- Function: PendingFrame.level ()
     Return an integer, the stack frame level for this frame.  *Note
     Stack Frames: Frames.

 -- Function: PendingFrame.name ()
     Returns the function name of this pending frame, or ‘None’ if it
     can't be obtained.

 -- Function: PendingFrame.is_valid ()
     Returns true if the ‘gdb.PendingFrame’ object is valid, false if
     not.  A pending frame object becomes invalid when the call to the
     unwinder, for which the pending frame was created, returns.

     All ‘gdb.PendingFrame’ methods, except this one, will raise an
     exception if the pending frame object is invalid at the time the
     method is called.

 -- Function: PendingFrame.pc ()
     Returns the pending frame's resume address.

 -- Function: PendingFrame.block ()
     Return the pending frame's code block (*note Blocks In Python::).
     If the frame does not have a block - for example, if there is no
     debugging information for the code in question - then this will
     raise a ‘RuntimeError’ exception.

 -- Function: PendingFrame.function ()
     Return the symbol for the function corresponding to this pending
     frame.  *Note Symbols In Python::.

 -- Function: PendingFrame.find_sal ()
     Return the pending frame's symtab and line object (*note Symbol
     Tables In Python::).

 -- Function: PendingFrame.language ()
     Return the language of this frame, as a string, or None.

Unwinder Output: UnwindInfo
---------------------------

Use ‘PendingFrame.create_unwind_info’ method described above to create a
‘gdb.UnwindInfo’ instance.  Use the following method to specify caller
registers that have been saved in this frame:

 -- Function: gdb.UnwindInfo.add_saved_register (register, value)
     REGISTER identifies the register, for a description of the
     acceptable values see *note Frame.read_register:
     gdbpy_frame_read_register.  VALUE is a register value (a
     ‘gdb.Value’ object).

The ‘gdb.unwinder’ Module
-------------------------

GDB comes with a ‘gdb.unwinder’ module which contains the following
classes:

 -- class: gdb.unwinder.Unwinder
     The ‘Unwinder’ class is a base class from which user created
     unwinders can derive, though it is not required that unwinders
     derive from this class, so long as any user created unwinder has
     the required ‘name’ and ‘enabled’ attributes.

      -- Function: gdb.unwinder.Unwinder.__init__ (name)
          The NAME is a string used to reference this unwinder within
          some GDB commands (*note Managing Registered Unwinders::).

      -- Variable: gdb.unwinder.name
          A read-only attribute which is a string, the name of this
          unwinder.

      -- Variable: gdb.unwinder.enabled
          A modifiable attribute containing a boolean; when ‘True’, the
          unwinder is enabled, and will be used by GDB.  When ‘False’,
          the unwinder has been disabled, and will not be used.

 -- class: gdb.unwinder.FrameId
     This is a class suitable for being used as the frame-id when
     calling ‘gdb.PendingFrame.create_unwind_info’.  It is not required
     to use this class, any class with the required attribute (*note
     gdb.PendingFrame.create_unwind_info::) will be accepted, but in
     most cases this class will be sufficient.

     ‘gdb.unwinder.FrameId’ has the following method:

      -- Function: gdb.unwinder.FrameId.__init__ (sp, pc, special =
               None)
          The SP and PC arguments are required and should be either a
          ‘gdb.Value’ object, or an integer.

          The SPECIAL argument is optional; if specified, it should be a
          ‘gdb.Value’ object, or an integer.

     ‘gdb.unwinder.FrameId’ has the following read-only attributes:

      -- Variable: gdb.unwinder.sp
          The SP value passed to the constructor.

      -- Variable: gdb.unwinder.pc
          The PC value passed to the constructor.

      -- Variable: gdb.unwinder.special
          The SPECIAL value passed to the constructor, or ‘None’ if no
          such value was passed.

Registering an Unwinder
-----------------------

Object files and program spaces can have unwinders registered with them.
In addition, you can register unwinders globally.

   The ‘gdb.unwinders’ module provides the function to register an
unwinder:

 -- Function: gdb.unwinder.register_unwinder (locus, unwinder,
          replace=False)
     LOCUS specifies to which unwinder list to prepend the UNWINDER.  It
     can be either an object file (*note Objfiles In Python::), a
     program space (*note Progspaces In Python::), or ‘None’, in which
     case the unwinder is registered globally.  The newly added UNWINDER
     will be called before any other unwinder from the same locus.  Two
     unwinders in the same locus cannot have the same name.  An attempt
     to add an unwinder with an already existing name raises an
     exception unless REPLACE is ‘True’, in which case the old unwinder
     is deleted and the new unwinder is registered in its place.

     GDB first calls the unwinders from all the object files in no
     particular order, then the unwinders from the current program
     space, then the globally registered unwinders, and finally the
     unwinders builtin to GDB.

Unwinder Skeleton Code
----------------------

Here is an example of how to structure a user created unwinder:

     from gdb.unwinder import Unwinder, FrameId

     class MyUnwinder(Unwinder):
         def __init__(self):
             super().__init___("MyUnwinder_Name")

         def __call__(self, pending_frame):
             if not <we recognize frame>:
                 return None

             # Create a FrameID.  Usually the frame is identified by a
             # stack pointer and the function address.
             sp = ... compute a stack address ...
             pc = ... compute function address ...
             unwind_info = pending_frame.create_unwind_info(FrameId(sp, pc))

             # Find the values of the registers in the caller's frame and
             # save them in the result:
             unwind_info.add_saved_register(<register-number>, <register-value>)
             ....

             # Return the result:
             return unwind_info

     gdb.unwinder.register_unwinder(<locus>, MyUnwinder(), <replace>)

Managing Registered Unwinders
-----------------------------

GDB defines 3 commands to manage registered unwinders.  These are:

‘info unwinder [ LOCUS [ NAME-REGEXP ] ]’
     Lists all registered unwinders.  Arguments LOCUS and NAME-REGEXP
     are both optional and can be used to filter which unwinders are
     listed.

     The LOCUS argument should be either ‘global’, ‘progspace’, or the
     name of an object file.  Only unwinders registered for the
     specified locus will be listed.

     The NAME-REGEXP is a regular expression used to match against
     unwinder names.  When trying to match against unwinder names that
     include a string enclose NAME-REGEXP in quotes.
‘disable unwinder [ LOCUS [ NAME-REGEXP ] ]’
     The LOCUS and NAME-REGEXP are interpreted as in ‘info unwinder’
     above, but instead of listing the matching unwinders, all of the
     matching unwinders are disabled.  The ‘enabled’ field of each
     matching unwinder is set to ‘False’.
‘enable unwinder [ LOCUS [ NAME-REGEXP ] ]’
     The LOCUS and NAME-REGEXP are interpreted as in ‘info unwinder’
     above, but instead of listing the matching unwinders, all of the
     matching unwinders are enabled.  The ‘enabled’ field of each
     matching unwinder is set to ‘True’.


File: gdb.info,  Node: Xmethods In Python,  Next: Xmethod API,  Prev: Unwinding Frames in Python,  Up: Python API

23.3.2.14 Xmethods In Python
............................

“Xmethods” are additional methods or replacements for existing methods
of a C++ class.  This feature is useful for those cases where a method
defined in C++ source code could be inlined or optimized out by the
compiler, making it unavailable to GDB.  For such cases, one can define
an xmethod to serve as a replacement for the method defined in the C++
source code.  GDB will then invoke the xmethod, instead of the C++
method, to evaluate expressions.  One can also use xmethods when
debugging with core files.  Moreover, when debugging live programs,
invoking an xmethod need not involve running the inferior (which can
potentially perturb its state).  Hence, even if the C++ method is
available, it is better to use its replacement xmethod if one is
defined.

   The xmethods feature in Python is available via the concepts of an
“xmethod matcher” and an “xmethod worker”.  To implement an xmethod, one
has to implement a matcher and a corresponding worker for it (more than
one worker can be implemented, each catering to a different overloaded
instance of the method).  Internally, GDB invokes the ‘match’ method of
a matcher to match the class type and method name.  On a match, the
‘match’ method returns a list of matching _worker_ objects.  Each worker
object typically corresponds to an overloaded instance of the xmethod.
They implement a ‘get_arg_types’ method which returns a sequence of
types corresponding to the arguments the xmethod requires.  GDB uses
this sequence of types to perform overload resolution and picks a
winning xmethod worker.  A winner is also selected from among the
methods GDB finds in the C++ source code.  Next, the winning xmethod
worker and the winning C++ method are compared to select an overall
winner.  In case of a tie between a xmethod worker and a C++ method, the
xmethod worker is selected as the winner.  That is, if a winning xmethod
worker is found to be equivalent to the winning C++ method, then the
xmethod worker is treated as a replacement for the C++ method.  GDB uses
the overall winner to invoke the method.  If the winning xmethod worker
is the overall winner, then the corresponding xmethod is invoked via the
‘__call__’ method of the worker object.

   If one wants to implement an xmethod as a replacement for an existing
C++ method, then they have to implement an equivalent xmethod which has
exactly the same name and takes arguments of exactly the same type as
the C++ method.  If the user wants to invoke the C++ method even though
a replacement xmethod is available for that method, then they can
disable the xmethod.

   *Note Xmethod API::, for API to implement xmethods in Python.  *Note
Writing an Xmethod::, for implementing xmethods in Python.


File: gdb.info,  Node: Xmethod API,  Next: Writing an Xmethod,  Prev: Xmethods In Python,  Up: Python API

23.3.2.15 Xmethod API
.....................

The GDB Python API provides classes, interfaces and functions to
implement, register and manipulate xmethods.  *Note Xmethods In
Python::.

   An xmethod matcher should be an instance of a class derived from
‘XMethodMatcher’ defined in the module ‘gdb.xmethod’, or an object with
similar interface and attributes.  An instance of ‘XMethodMatcher’ has
the following attributes:

 -- Variable: name
     The name of the matcher.

 -- Variable: enabled
     A boolean value indicating whether the matcher is enabled or
     disabled.

 -- Variable: methods
     A list of named methods managed by the matcher.  Each object in the
     list is an instance of the class ‘XMethod’ defined in the module
     ‘gdb.xmethod’, or any object with the following attributes:

     ‘name’
          Name of the xmethod which should be unique for each xmethod
          managed by the matcher.

     ‘enabled’
          A boolean value indicating whether the xmethod is enabled or
          disabled.

     The class ‘XMethod’ is a convenience class with same attributes as
     above along with the following constructor:

      -- Function: XMethod.__init__ (self, name)
          Constructs an enabled xmethod with name NAME.

The ‘XMethodMatcher’ class has the following methods:

 -- Function: XMethodMatcher.__init__ (self, name)
     Constructs an enabled xmethod matcher with name NAME.  The
     ‘methods’ attribute is initialized to ‘None’.

 -- Function: XMethodMatcher.match (self, class_type, method_name)
     Derived classes should override this method.  It should return a
     xmethod worker object (or a sequence of xmethod worker objects)
     matching the CLASS_TYPE and METHOD_NAME.  CLASS_TYPE is a
     ‘gdb.Type’ object, and METHOD_NAME is a string value.  If the
     matcher manages named methods as listed in its ‘methods’ attribute,
     then only those worker objects whose corresponding entries in the
     ‘methods’ list are enabled should be returned.

   An xmethod worker should be an instance of a class derived from
‘XMethodWorker’ defined in the module ‘gdb.xmethod’, or support the
following interface:

 -- Function: XMethodWorker.get_arg_types (self)
     This method returns a sequence of ‘gdb.Type’ objects corresponding
     to the arguments that the xmethod takes.  It can return an empty
     sequence or ‘None’ if the xmethod does not take any arguments.  If
     the xmethod takes a single argument, then a single ‘gdb.Type’
     object corresponding to it can be returned.

 -- Function: XMethodWorker.get_result_type (self, *args)
     This method returns a ‘gdb.Type’ object representing the type of
     the result of invoking this xmethod.  The ARGS argument is the same
     tuple of arguments that would be passed to the ‘__call__’ method of
     this worker.

 -- Function: XMethodWorker.__call__ (self, *args)
     This is the method which does the _work_ of the xmethod.  The ARGS
     arguments is the tuple of arguments to the xmethod.  Each element
     in this tuple is a gdb.Value object.  The first element is always
     the ‘this’ pointer value.

   For GDB to lookup xmethods, the xmethod matchers should be registered
using the following function defined in the module ‘gdb.xmethod’:

 -- Function: register_xmethod_matcher (locus, matcher, replace=False)
     The ‘matcher’ is registered with ‘locus’, replacing an existing
     matcher with the same name as ‘matcher’ if ‘replace’ is ‘True’.
     ‘locus’ can be a ‘gdb.Objfile’ object (*note Objfiles In Python::),
     or a ‘gdb.Progspace’ object (*note Progspaces In Python::), or
     ‘None’.  If it is ‘None’, then ‘matcher’ is registered globally.


File: gdb.info,  Node: Writing an Xmethod,  Next: Inferiors In Python,  Prev: Xmethod API,  Up: Python API

23.3.2.16 Writing an Xmethod
............................

Implementing xmethods in Python will require implementing xmethod
matchers and xmethod workers (*note Xmethods In Python::).  Consider the
following C++ class:

     class MyClass
     {
     public:
       MyClass (int a) : a_(a) { }

       int geta (void) { return a_; }
       int operator+ (int b);

     private:
       int a_;
     };

     int
     MyClass::operator+ (int b)
     {
       return a_ + b;
     }

Let us define two xmethods for the class ‘MyClass’, one replacing the
method ‘geta’, and another adding an overloaded flavor of ‘operator+’
which takes a ‘MyClass’ argument (the C++ code above already has an
overloaded ‘operator+’ which takes an ‘int’ argument).  The xmethod
matcher can be defined as follows:

     class MyClass_geta(gdb.xmethod.XMethod):
         def __init__(self):
             gdb.xmethod.XMethod.__init__(self, 'geta')

         def get_worker(self, method_name):
             if method_name == 'geta':
                 return MyClassWorker_geta()


     class MyClass_sum(gdb.xmethod.XMethod):
         def __init__(self):
             gdb.xmethod.XMethod.__init__(self, 'sum')

         def get_worker(self, method_name):
             if method_name == 'operator+':
                 return MyClassWorker_plus()


     class MyClassMatcher(gdb.xmethod.XMethodMatcher):
         def __init__(self):
             gdb.xmethod.XMethodMatcher.__init__(self, 'MyClassMatcher')
             # List of methods 'managed' by this matcher
             self.methods = [MyClass_geta(), MyClass_sum()]

         def match(self, class_type, method_name):
             if class_type.tag != 'MyClass':
                 return None
             workers = []
             for method in self.methods:
                 if method.enabled:
                     worker = method.get_worker(method_name)
                     if worker:
                         workers.append(worker)

             return workers

Notice that the ‘match’ method of ‘MyClassMatcher’ returns a worker
object of type ‘MyClassWorker_geta’ for the ‘geta’ method, and a worker
object of type ‘MyClassWorker_plus’ for the ‘operator+’ method.  This is
done indirectly via helper classes derived from ‘gdb.xmethod.XMethod’.
One does not need to use the ‘methods’ attribute in a matcher as it is
optional.  However, if a matcher manages more than one xmethod, it is a
good practice to list the xmethods in the ‘methods’ attribute of the
matcher.  This will then facilitate enabling and disabling individual
xmethods via the ‘enable/disable’ commands.  Notice also that a worker
object is returned only if the corresponding entry in the ‘methods’
attribute of the matcher is enabled.

   The implementation of the worker classes returned by the matcher
setup above is as follows:

     class MyClassWorker_geta(gdb.xmethod.XMethodWorker):
         def get_arg_types(self):
             return None

         def get_result_type(self, obj):
             return gdb.lookup_type('int')

         def __call__(self, obj):
             return obj['a_']


     class MyClassWorker_plus(gdb.xmethod.XMethodWorker):
         def get_arg_types(self):
             return gdb.lookup_type('MyClass')

         def get_result_type(self, obj):
             return gdb.lookup_type('int')

         def __call__(self, obj, other):
             return obj['a_'] + other['a_']

   For GDB to actually lookup a xmethod, it has to be registered with
it.  The matcher defined above is registered with GDB globally as
follows:

     gdb.xmethod.register_xmethod_matcher(None, MyClassMatcher())

   If an object ‘obj’ of type ‘MyClass’ is initialized in C++ code as
follows:

     MyClass obj(5);

then, after loading the Python script defining the xmethod matchers and
workers into GDB, invoking the method ‘geta’ or using the operator ‘+’
on ‘obj’ will invoke the xmethods defined above:

     (gdb) p obj.geta()
     $1 = 5

     (gdb) p obj + obj
     $2 = 10

   Consider another example with a C++ template class:

     template <class T>
     class MyTemplate
     {
     public:
       MyTemplate () : dsize_(10), data_ (new T [10]) { }
       ~MyTemplate () { delete [] data_; }

       int footprint (void)
       {
         return sizeof (T) * dsize_ + sizeof (MyTemplate<T>);
       }

     private:
       int dsize_;
       T *data_;
     };

   Let us implement an xmethod for the above class which serves as a
replacement for the ‘footprint’ method.  The full code listing of the
xmethod workers and xmethod matchers is as follows:

     class MyTemplateWorker_footprint(gdb.xmethod.XMethodWorker):
         def __init__(self, class_type):
             self.class_type = class_type

         def get_arg_types(self):
             return None

         def get_result_type(self):
             return gdb.lookup_type('int')

         def __call__(self, obj):
             return (self.class_type.sizeof +
                     obj['dsize_'] *
                     self.class_type.template_argument(0).sizeof)


     class MyTemplateMatcher_footprint(gdb.xmethod.XMethodMatcher):
         def __init__(self):
             gdb.xmethod.XMethodMatcher.__init__(self, 'MyTemplateMatcher')

         def match(self, class_type, method_name):
             if (re.match('MyTemplate<[ \t\n]*[_a-zA-Z][ _a-zA-Z0-9]*>',
                          class_type.tag) and
                 method_name == 'footprint'):
                 return MyTemplateWorker_footprint(class_type)

   Notice that, in this example, we have not used the ‘methods’
attribute of the matcher as the matcher manages only one xmethod.  The
user can enable/disable this xmethod by enabling/disabling the matcher
itself.


File: gdb.info,  Node: Inferiors In Python,  Next: Events In Python,  Prev: Writing an Xmethod,  Up: Python API

23.3.2.17 Inferiors In Python
.............................

Programs which are being run under GDB are called inferiors (*note
Inferiors Connections and Programs::).  Python scripts can access
information about and manipulate inferiors controlled by GDB via objects
of the ‘gdb.Inferior’ class.

   The following inferior-related functions are available in the ‘gdb’
module:

 -- Function: gdb.inferiors ()
     Return a tuple containing all inferior objects.

 -- Function: gdb.selected_inferior ()
     Return an object representing the current inferior.

   A ‘gdb.Inferior’ object has the following attributes:

 -- Variable: Inferior.num
     ID of inferior, as assigned by GDB.  You can use this to make
     Python breakpoints inferior-specific, for example (*note The
     Breakpoint.inferior attribute: python_breakpoint_inferior.).

 -- Variable: Inferior.connection
     The ‘gdb.TargetConnection’ for this inferior (*note Connections In
     Python::), or ‘None’ if this inferior has no connection.

 -- Variable: Inferior.connection_num
     ID of inferior's connection as assigned by GDB, or None if the
     inferior is not connected to a target.  *Note Inferiors Connections
     and Programs::.  This is equivalent to
     ‘gdb.Inferior.connection.num’ in the case where
     ‘gdb.Inferior.connection’ is not ‘None’.

 -- Variable: Inferior.pid
     Process ID of the inferior, as assigned by the underlying operating
     system.

 -- Variable: Inferior.was_attached
     Boolean signaling whether the inferior was created using 'attach',
     or started by GDB itself.

 -- Variable: Inferior.main_name
     A string holding the name of this inferior's "main" function, if it
     can be determined.  If the name of main is not known, this is
     ‘None’.

 -- Variable: Inferior.progspace
     The inferior's program space.  *Note Progspaces In Python::.

 -- Variable: Inferior.arguments
     The inferior's command line arguments, if known.  This corresponds
     to the ‘set args’ and ‘show args’ commands.  *Note Arguments::.

     When accessed, the value is a string holding all the arguments.
     The contents are quoted as they would be when passed to the shell.
     If there are no arguments, the value is ‘None’.

     Either a string or a sequence of strings can be assigned to this
     attribute.  When a string is assigned, it is assumed to have any
     necessary quoting for the shell; when a sequence is assigned, the
     quoting is applied by GDB.

   A ‘gdb.Inferior’ object has the following methods:

 -- Function: Inferior.is_valid ()
     Returns ‘True’ if the ‘gdb.Inferior’ object is valid, ‘False’ if
     not.  A ‘gdb.Inferior’ object will become invalid if the inferior
     no longer exists within GDB.  All other ‘gdb.Inferior’ methods will
     throw an exception if it is invalid at the time the method is
     called.

 -- Function: Inferior.threads ()
     This method returns a tuple holding all the threads which are valid
     when it is called.  If there are no valid threads, the method will
     return an empty tuple.

 -- Function: Inferior.architecture ()
     Return the ‘gdb.Architecture’ (*note Architectures In Python::) for
     this inferior.  This represents the architecture of the inferior as
     a whole.  Some platforms can have multiple architectures in a
     single address space, so this may not match the architecture of a
     particular frame (*note Frames In Python::).

 -- Function: Inferior.read_memory (address, length)
     Read LENGTH addressable memory units from the inferior, starting at
     ADDRESS.  Returns a ‘memoryview’ object, which behaves much like an
     array or a string.  It can be modified and given to the
     ‘Inferior.write_memory’ function.

 -- Function: Inferior.write_memory (address, buffer [, length])
     Write the contents of BUFFER to the inferior, starting at ADDRESS.
     The BUFFER parameter must be a Python object which supports the
     buffer protocol, i.e., a string, an array or the object returned
     from ‘Inferior.read_memory’.  If given, LENGTH determines the
     number of addressable memory units from BUFFER to be written.

 -- Function: Inferior.search_memory (address, length, pattern)
     Search a region of the inferior memory starting at ADDRESS with the
     given LENGTH using the search pattern supplied in PATTERN.  The
     PATTERN parameter must be a Python object which supports the buffer
     protocol, i.e., a string, an array or the object returned from
     ‘gdb.read_memory’.  Returns a Python ‘Long’ containing the address
     where the pattern was found, or ‘None’ if the pattern could not be
     found.

 -- Function: Inferior.thread_from_handle (handle)
     Return the thread object corresponding to HANDLE, a thread library
     specific data structure such as ‘pthread_t’ for pthreads library
     implementations.

     The function ‘Inferior.thread_from_thread_handle’ provides the same
     functionality, but use of ‘Inferior.thread_from_thread_handle’ is
     deprecated.

   The environment that will be passed to the inferior can be changed
from Python by using the following methods.  These methods only take
effect when the inferior is started - they will not affect an inferior
that is already executing.

 -- Function: Inferior.clear_env ()
     Clear the current environment variables that will be passed to this
     inferior.

 -- Function: Inferior.set_env (name, value)
     Set the environment variable NAME to have the indicated value.
     Both parameters must be strings.

 -- Function: Inferior.unset_env (name)
     Unset the environment variable NAME.  NAME must be a string.

   One may add arbitrary attributes to ‘gdb.Inferior’ objects in the
usual Python way.  This is useful if, for example, one needs to do some
extra record keeping associated with the inferior.

   When selecting a name for a new attribute, avoid starting the new
attribute name with a lower case letter; future attributes added by GDB
will start with a lower case letter.  Additionally, avoid starting
attribute names with two underscore characters, as these could clash
with Python builtin attribute names.

   In this contrived example we record the time when an inferior last
stopped:

     (gdb) python
     import datetime

     def thread_stopped(event):
         if event.inferior_thread is not None:
             thread = event.inferior_thread
         else:
             thread = gdb.selected_thread()
         inferior = thread.inferior
         inferior._last_stop_time = datetime.datetime.today()

     gdb.events.stop.connect(thread_stopped)
     (gdb) file /tmp/hello
     Reading symbols from /tmp/hello...
     (gdb) start
     Temporary breakpoint 1 at 0x401198: file /tmp/hello.c, line 18.
     Starting program: /tmp/hello

     Temporary breakpoint 1, main () at /tmp/hello.c:18
     18	  printf ("Hello World\n");
     (gdb) python print(gdb.selected_inferior()._last_stop_time)
     2024-01-04 14:48:41.347036


File: gdb.info,  Node: Events In Python,  Next: Threads In Python,  Prev: Inferiors In Python,  Up: Python API

23.3.2.18 Events In Python
..........................

GDB provides a general event facility so that Python code can be
notified of various state changes, particularly changes that occur in
the inferior.

   An “event” is just an object that describes some state change.  The
type of the object and its attributes will vary depending on the details
of the change.  All the existing events are described below.

   In order to be notified of an event, you must register an event
handler with an “event registry”.  An event registry is an object in the
‘gdb.events’ module which dispatches particular events.  A registry
provides methods to register and unregister event handlers:

 -- Function: EventRegistry.connect (object)
     Add the given callable OBJECT to the registry.  This object will be
     called when an event corresponding to this registry occurs.

 -- Function: EventRegistry.disconnect (object)
     Remove the given OBJECT from the registry.  Once removed, the
     object will no longer receive notifications of events.

   Here is an example:

     def exit_handler (event):
         print ("event type: exit")
         if hasattr (event, 'exit_code'):
             print ("exit code: %d" % (event.exit_code))
         else:
             print ("exit code not available")

     gdb.events.exited.connect (exit_handler)

   In the above example we connect our handler ‘exit_handler’ to the
registry ‘events.exited’.  Once connected, ‘exit_handler’ gets called
when the inferior exits.  The argument “event” in this example is of
type ‘gdb.ExitedEvent’.  As you can see in the example the ‘ExitedEvent’
object has an attribute which indicates the exit code of the inferior.

   Some events can be thread specific when GDB is running in non-stop
mode.  When represented in Python, these events all extend
‘gdb.ThreadEvent’.  This event is a base class and is never emitted
directly; instead, events which are emitted by this or other modules
might extend this event.  Examples of these events are
‘gdb.BreakpointEvent’ and ‘gdb.ContinueEvent’.  ‘gdb.ThreadEvent’ holds
the following attributes:

 -- Variable: ThreadEvent.inferior_thread
     In non-stop mode this attribute will be set to the specific thread
     which was involved in the emitted event.  Otherwise, it will be set
     to ‘None’.

   The following is a listing of the event registries that are available
and details of the events they emit:

‘events.cont’
     Emits ‘gdb.ContinueEvent’, which extends ‘gdb.ThreadEvent’.  This
     event indicates that the inferior has been continued after a stop.
     For inherited attribute refer to ‘gdb.ThreadEvent’ above.

‘events.exited’
     Emits ‘events.ExitedEvent’, which indicates that the inferior has
     exited.  ‘events.ExitedEvent’ has two attributes:

      -- Variable: ExitedEvent.exit_code
          An integer representing the exit code, if available, which the
          inferior has returned.  (The exit code could be unavailable
          if, for example, GDB detaches from the inferior.)  If the exit
          code is unavailable, the attribute does not exist.

      -- Variable: ExitedEvent.inferior
          A reference to the inferior which triggered the ‘exited’
          event.

‘events.stop’
     Emits ‘gdb.StopEvent’, which extends ‘gdb.ThreadEvent’.

     Indicates that the inferior has stopped.  All events emitted by
     this registry extend ‘gdb.StopEvent’.  As a child of
     ‘gdb.ThreadEvent’, ‘gdb.StopEvent’ will indicate the stopped thread
     when GDB is running in non-stop mode.  Refer to ‘gdb.ThreadEvent’
     above for more details.

     ‘gdb.StopEvent’ has the following additional attributes:

      -- Variable: StopEvent.details
          A dictionary holding any details relevant to the stop.  The
          exact keys and values depend on the type of stop, but are
          identical to the corresponding MI output (*note GDB/MI Async
          Records::).

          A dictionary was used for this (rather than adding attributes
          directly to the event object) so that the MI keys could be
          used unchanged.

          When a ‘StopEvent’ results from a ‘finish’ command, it will
          also hold the return value from the function, if that is
          available.  This will be an entry named ‘return-value’ in the
          ‘details’ dictionary.  The value of this entry will be a
          ‘gdb.Value’ object.

     Emits ‘gdb.SignalEvent’, which extends ‘gdb.StopEvent’.

     This event indicates that the inferior or one of its threads has
     received a signal.  ‘gdb.SignalEvent’ has the following attributes:

      -- Variable: SignalEvent.stop_signal
          A string representing the signal received by the inferior.  A
          list of possible signal values can be obtained by running the
          command ‘info signals’ in the GDB command prompt.

     Also emits ‘gdb.BreakpointEvent’, which extends ‘gdb.StopEvent’.

     ‘gdb.BreakpointEvent’ event indicates that one or more breakpoints
     have been hit, and has the following attributes:

      -- Variable: BreakpointEvent.breakpoints
          A sequence containing references to all the breakpoints (type
          ‘gdb.Breakpoint’) that were hit.  *Note Breakpoints In
          Python::, for details of the ‘gdb.Breakpoint’ object.

      -- Variable: BreakpointEvent.breakpoint
          A reference to the first breakpoint that was hit.  This
          attribute is maintained for backward compatibility and is now
          deprecated in favor of the ‘gdb.BreakpointEvent.breakpoints’
          attribute.

‘events.new_objfile’
     Emits ‘gdb.NewObjFileEvent’ which indicates that a new object file
     has been loaded by GDB.  ‘gdb.NewObjFileEvent’ has one attribute:

      -- Variable: NewObjFileEvent.new_objfile
          A reference to the object file (‘gdb.Objfile’) which has been
          loaded.  *Note Objfiles In Python::, for details of the
          ‘gdb.Objfile’ object.

‘events.free_objfile’
     Emits ‘gdb.FreeObjFileEvent’ which indicates that an object file is
     about to be removed from GDB.  One reason this can happen is when
     the inferior calls ‘dlclose’.  ‘gdb.FreeObjFileEvent’ has one
     attribute:

      -- Variable: FreeObjFileEvent.objfile
          A reference to the object file (‘gdb.Objfile’) which will be
          unloaded.  *Note Objfiles In Python::, for details of the
          ‘gdb.Objfile’ object.

‘events.clear_objfiles’
     Emits ‘gdb.ClearObjFilesEvent’ which indicates that the list of
     object files for a program space has been reset.
     ‘gdb.ClearObjFilesEvent’ has one attribute:

      -- Variable: ClearObjFilesEvent.progspace
          A reference to the program space (‘gdb.Progspace’) whose
          objfile list has been cleared.  *Note Progspaces In Python::.

‘events.inferior_call’
     Emits events just before and after a function in the inferior is
     called by GDB.  Before an inferior call, this emits an event of
     type ‘gdb.InferiorCallPreEvent’, and after an inferior call, this
     emits an event of type ‘gdb.InferiorCallPostEvent’.

     ‘gdb.InferiorCallPreEvent’
          Indicates that a function in the inferior is about to be
          called.

           -- Variable: InferiorCallPreEvent.ptid
               The thread in which the call will be run.

           -- Variable: InferiorCallPreEvent.address
               The location of the function to be called.

     ‘gdb.InferiorCallPostEvent’
          Indicates that a function in the inferior has just been
          called.

           -- Variable: InferiorCallPostEvent.ptid
               The thread in which the call was run.

           -- Variable: InferiorCallPostEvent.address
               The location of the function that was called.

‘events.memory_changed’
     Emits ‘gdb.MemoryChangedEvent’ which indicates that the memory of
     the inferior has been modified by the GDB user, for instance via a
     command like ‘set *addr = value’.  The event has the following
     attributes:

      -- Variable: MemoryChangedEvent.address
          The start address of the changed region.

      -- Variable: MemoryChangedEvent.length
          Length in bytes of the changed region.

‘events.register_changed’
     Emits ‘gdb.RegisterChangedEvent’ which indicates that a register in
     the inferior has been modified by the GDB user.

      -- Variable: RegisterChangedEvent.frame
          A gdb.Frame object representing the frame in which the
          register was modified.
      -- Variable: RegisterChangedEvent.regnum
          Denotes which register was modified.

‘events.breakpoint_created’
     This is emitted when a new breakpoint has been created.  The
     argument that is passed is the new ‘gdb.Breakpoint’ object.

‘events.breakpoint_modified’
     This is emitted when a breakpoint has been modified in some way.
     The argument that is passed is the new ‘gdb.Breakpoint’ object.

‘events.breakpoint_deleted’
     This is emitted when a breakpoint has been deleted.  The argument
     that is passed is the ‘gdb.Breakpoint’ object.  When this event is
     emitted, the ‘gdb.Breakpoint’ object will already be in its invalid
     state; that is, the ‘is_valid’ method will return ‘False’.

‘events.before_prompt’
     This event carries no payload.  It is emitted each time GDB
     presents a prompt to the user.

‘events.new_inferior’
     This is emitted when a new inferior is created.  Note that the
     inferior is not necessarily running; in fact, it may not even have
     an associated executable.

     The event is of type ‘gdb.NewInferiorEvent’.  This has a single
     attribute:

      -- Variable: NewInferiorEvent.inferior
          The new inferior, a ‘gdb.Inferior’ object.

‘events.inferior_deleted’
     This is emitted when an inferior has been deleted.  Note that this
     is not the same as process exit; it is notified when the inferior
     itself is removed, say via ‘remove-inferiors’.

     The event is of type ‘gdb.InferiorDeletedEvent’.  This has a single
     attribute:

      -- Variable: InferiorDeletedEvent.inferior
          The inferior that is being removed, a ‘gdb.Inferior’ object.

‘events.new_thread’
     This is emitted when GDB notices a new thread.  The event is of
     type ‘gdb.NewThreadEvent’, which extends ‘gdb.ThreadEvent’.  This
     has a single attribute:

      -- Variable: NewThreadEvent.inferior_thread
          The new thread.

‘events.thread_exited’
     This is emitted when GDB notices a thread has exited.  The event is
     of type ‘gdb.ThreadExitedEvent’ which extends ‘gdb.ThreadEvent’.
     This has a single attribute:

      -- Variable: ThreadExitedEvent.inferior_thread
          The exiting thread.

‘events.gdb_exiting’
     This is emitted when GDB exits.  This event is not emitted if GDB
     exits as a result of an internal error, or after an unexpected
     signal.  The event is of type ‘gdb.GdbExitingEvent’, which has a
     single attribute:

      -- Variable: GdbExitingEvent.exit_code
          An integer, the value of the exit code GDB will return.

‘events.connection_removed’
     This is emitted when GDB removes a connection (*note Connections In
     Python::).  The event is of type ‘gdb.ConnectionEvent’.  This has a
     single read-only attribute:

      -- Variable: ConnectionEvent.connection
          The ‘gdb.TargetConnection’ that is being removed.

‘events.executable_changed’
     Emits ‘gdb.ExecutableChangedEvent’ which indicates that the
     ‘gdb.Progspace.executable_filename’ has changed.

     This event is emitted when either the value of
     ‘gdb.Progspace.executable_filename ’ has changed to name a
     different file, or the executable file named by
     ‘gdb.Progspace.executable_filename’ has changed on disk, and GDB
     has therefore reloaded it.

      -- Variable: ExecutableChangedEvent.progspace
          The ‘gdb.Progspace’ in which the current executable has
          changed.  The file name of the updated executable will be
          visible in ‘gdb.Progspace.executable_filename’ (*note
          Progspaces In Python::).
      -- Variable: ExecutableChangedEvent.reload
          This attribute will be ‘True’ if the value of
          ‘gdb.Progspace.executable_filename’ didn't change, but the
          file it names changed on disk instead, and GDB reloaded it.

          When this attribute is ‘False’, the value in
          ‘gdb.Progspace.executable_filename’ was changed to name a
          different file.

     Remember that GDB tracks the executable file and the symbol file
     separately, these are visible as
     ‘gdb.Progspace.executable_filename’ and ‘gdb.Progspace.filename’
     respectively.  When using the ‘file’ command, GDB updates both of
     these fields, but the executable file is updated first, so when
     this event is emitted, the executable filename will have changed,
     but the symbol filename might still hold its previous value.

‘events.new_progspace’
     This is emitted when GDB adds a new program space (*note Program
     Spaces In Python: Progspaces In Python.).  The event is of type
     ‘gdb.NewProgspaceEvent’, and has a single read-only attribute:

      -- Variable: NewProgspaceEvent.progspace
          The ‘gdb.Progspace’ that was added to GDB.

     No ‘NewProgspaceEvent’ is emitted for the very first program space,
     which is assigned to the first inferior.  This first program space
     is created within GDB before any Python scripts are sourced.

‘events.free_progspace’
     This is emitted when GDB removes a program space (*note Program
     Spaces In Python: Progspaces In Python.), for example as a result
     of the ‘remove-inferiors’ command (*note ‘remove-inferiors’:
     remove_inferiors_cli.).  The event is of type
     ‘gdb.FreeProgspaceEvent’, and has a single read-only attribute:

      -- Variable: FreeProgspaceEvent.progspace
          The ‘gdb.Progspace’ that is about to be removed from GDB.

‘events.tui_enabled’
     This is emitted when the TUI is enabled or disabled.  The event is
     of type ‘gdb.TuiEnabledEvent’, which has a single read-only
     attribute:

      -- Variable: TuiEnabledEvent.enabled
          If the TUI has just been enabled, this is ‘True’; otherwise it
          is ‘False’.


File: gdb.info,  Node: Threads In Python,  Next: Recordings In Python,  Prev: Events In Python,  Up: Python API

23.3.2.19 Threads In Python
...........................

Python scripts can access information about, and manipulate inferior
threads controlled by GDB, via objects of the ‘gdb.InferiorThread’
class.

   The following thread-related functions are available in the ‘gdb’
module:

 -- Function: gdb.selected_thread ()
     This function returns the thread object for the selected thread.
     If there is no selected thread, this will return ‘None’.

   To get the list of threads for an inferior, use the
‘Inferior.threads()’ method.  *Note Inferiors In Python::.

   A ‘gdb.InferiorThread’ object has the following attributes:

 -- Variable: InferiorThread.name
     The name of the thread.  If the user specified a name using ‘thread
     name’, then this returns that name.  Otherwise, if an OS-supplied
     name is available, then it is returned.  Otherwise, this returns
     ‘None’.

     This attribute can be assigned to.  The new value must be a string
     object, which sets the new name, or ‘None’, which removes any
     user-specified thread name.

 -- Variable: InferiorThread.num
     The per-inferior number of the thread, as assigned by GDB.

 -- Variable: InferiorThread.global_num
     The global ID of the thread, as assigned by GDB. You can use this
     to make Python breakpoints thread-specific, for example (*note The
     Breakpoint.thread attribute: python_breakpoint_thread.).

 -- Variable: InferiorThread.ptid
     ID of the thread, as assigned by the operating system.  This
     attribute is a tuple containing three integers.  The first is the
     Process ID (PID); the second is the Lightweight Process ID (LWPID),
     and the third is the Thread ID (TID). Either the LWPID or TID may
     be 0, which indicates that the operating system does not use that
     identifier.

 -- Variable: InferiorThread.ptid_string
     This read-only attribute contains a string representing
     ‘InferiorThread.ptid’.  This is the string that GDB uses in the
     ‘Target Id’ column in the ‘info threads’ output (*note ‘info
     threads’: info_threads.).

 -- Variable: InferiorThread.inferior
     The inferior this thread belongs to.  This attribute is represented
     as a ‘gdb.Inferior’ object.  This attribute is not writable.

 -- Variable: InferiorThread.details
     A string containing target specific thread state information.  The
     format of this string varies by target.  If there is no additional
     state information for this thread, then this attribute contains
     ‘None’.

     For example, on a GNU/Linux system, a thread that is in the process
     of exiting will return the string ‘Exiting’.  For remote targets
     the ‘details’ string will be obtained with the ‘qThreadExtraInfo’
     remote packet, if the target supports it (*note ‘qThreadExtraInfo’:
     qThreadExtraInfo.).

     GDB displays the ‘details’ string as part of the ‘Target Id’
     column, in the ‘info threads’ output (*note ‘info threads’:
     info_threads.).

   A ‘gdb.InferiorThread’ object has the following methods:

 -- Function: InferiorThread.is_valid ()
     Returns ‘True’ if the ‘gdb.InferiorThread’ object is valid, ‘False’
     if not.  A ‘gdb.InferiorThread’ object will become invalid if the
     thread exits, or the inferior that the thread belongs is deleted.
     All other ‘gdb.InferiorThread’ methods will throw an exception if
     it is invalid at the time the method is called.

 -- Function: InferiorThread.switch ()
     This changes GDB's currently selected thread to the one represented
     by this object.

 -- Function: InferiorThread.is_stopped ()
     Return a Boolean indicating whether the thread is stopped.

 -- Function: InferiorThread.is_running ()
     Return a Boolean indicating whether the thread is running.

 -- Function: InferiorThread.is_exited ()
     Return a Boolean indicating whether the thread is exited.

 -- Function: InferiorThread.handle ()
     Return the thread object's handle, represented as a Python ‘bytes’
     object.  A ‘gdb.Value’ representation of the handle may be
     constructed via ‘gdb.Value(bufobj, type)’ where BUFOBJ is the
     Python ‘bytes’ representation of the handle and TYPE is a
     ‘gdb.Type’ for the handle type.

   One may add arbitrary attributes to ‘gdb.InferiorThread’ objects in
the usual Python way.  This is useful if, for example, one needs to do
some extra record keeping associated with the thread.

   *Note choosing attribute names::, for guidance on selecting a
suitable name for new attributes.

   In this contrived example we record the time when a thread last
stopped:

     (gdb) python
     import datetime

     def thread_stopped(event):
         if event.inferior_thread is not None:
             thread = event.inferior_thread
         else:
             thread = gdb.selected_thread()
         thread._last_stop_time = datetime.datetime.today()

     gdb.events.stop.connect(thread_stopped)
     (gdb) file /tmp/hello
     Reading symbols from /tmp/hello...
     (gdb) start
     Temporary breakpoint 1 at 0x401198: file /tmp/hello.c, line 18.
     Starting program: /tmp/hello

     Temporary breakpoint 1, main () at /tmp/hello.c:18
     18	  printf ("Hello World\n");
     (gdb) python print(gdb.selected_thread()._last_stop_time)
     2024-01-04 14:48:41.347036


File: gdb.info,  Node: Recordings In Python,  Next: CLI Commands In Python,  Prev: Threads In Python,  Up: Python API

23.3.2.20 Recordings In Python
..............................

The following recordings-related functions (*note Process Record and
Replay::) are available in the ‘gdb’ module:

 -- Function: gdb.start_recording ([method], [format])
     Start a recording using the given METHOD and FORMAT.  If no FORMAT
     is given, the default format for the recording method is used.  If
     no METHOD is given, the default method will be used.  Returns a
     ‘gdb.Record’ object on success.  Throw an exception on failure.

     The following strings can be passed as METHOD:

        • ‘"full"’
        • ‘"btrace"’: Possible values for FORMAT: ‘"pt"’, ‘"bts"’ or
          leave out for default format.

 -- Function: gdb.current_recording ()
     Access a currently running recording.  Return a ‘gdb.Record’ object
     on success.  Return ‘None’ if no recording is currently active.

 -- Function: gdb.stop_recording ()
     Stop the current recording.  Throw an exception if no recording is
     currently active.  All record objects become invalid after this
     call.

   A ‘gdb.Record’ object has the following attributes:

 -- Variable: Record.method
     A string with the current recording method, e.g. ‘full’ or
     ‘btrace’.

 -- Variable: Record.format
     A string with the current recording format, e.g. ‘bt’, ‘pts’ or
     ‘None’.

 -- Variable: Record.begin
     A method specific instruction object representing the first
     instruction in this recording.

 -- Variable: Record.end
     A method specific instruction object representing the current
     instruction, that is not actually part of the recording.

 -- Variable: Record.replay_position
     The instruction representing the current replay position.  If there
     is no replay active, this will be ‘None’.

 -- Variable: Record.instruction_history
     A list with all recorded instructions.

 -- Variable: Record.function_call_history
     A list with all recorded function call segments.

   A ‘gdb.Record’ object has the following methods:

 -- Function: Record.goto (instruction)
     Move the replay position to the given INSTRUCTION.

 -- Function: Record.clear ()
     Clear the trace data of the current recording.  This forces
     re-decoding of the trace for successive commands.

   The common ‘gdb.Instruction’ class that recording method specific
instruction objects inherit from, has the following attributes:

 -- Variable: Instruction.pc
     An integer representing this instruction's address.

 -- Variable: Instruction.data
     A ‘memoryview’ object holding the raw instruction data.

 -- Variable: Instruction.decoded
     A human readable string with the disassembled instruction.

 -- Variable: Instruction.size
     The size of the instruction in bytes.

   Additionally ‘gdb.RecordInstruction’ has the following attributes:

 -- Variable: RecordInstruction.number
     An integer identifying this instruction.  ‘number’ corresponds to
     the numbers seen in ‘record instruction-history’ (*note Process
     Record and Replay::).

 -- Variable: RecordInstruction.sal
     A ‘gdb.Symtab_and_line’ object representing the associated symtab
     and line of this instruction.  May be ‘None’ if no debug
     information is available.

 -- Variable: RecordInstruction.is_speculative
     A boolean indicating whether the instruction was executed
     speculatively.

   If an error occurred during recording or decoding a recording, this
error is represented by a ‘gdb.RecordGap’ object in the instruction
list.  It has the following attributes:

 -- Variable: RecordGap.number
     An integer identifying this gap.  ‘number’ corresponds to the
     numbers seen in ‘record instruction-history’ (*note Process Record
     and Replay::).

 -- Variable: RecordGap.error_code
     A numerical representation of the reason for the gap.  The value is
     specific to the current recording method.

 -- Variable: RecordGap.error_string
     A human readable string with the reason for the gap.

   Some GDB features write auxiliary information into the execution
history.  This information is represented by a ‘gdb.RecordAuxiliary’
object in the instruction list.  It has the following attributes:

 -- Variable: RecordAuxiliary.NUMBER
     An integer identifying this auxiliary.  NUMBER corresponds to the
     numbers seen in ‘record instruction-history’ (*note Process Record
     and Replay::).

 -- Variable: RecordAuxiliary.data
     A string representation of the auxiliary data.

   A ‘gdb.RecordFunctionSegment’ object has the following attributes:

 -- Variable: RecordFunctionSegment.number
     An integer identifying this function segment.  ‘number’ corresponds
     to the numbers seen in ‘record function-call-history’ (*note
     Process Record and Replay::).

 -- Variable: RecordFunctionSegment.symbol
     A ‘gdb.Symbol’ object representing the associated symbol.  May be
     ‘None’ if no debug information is available.

 -- Variable: RecordFunctionSegment.level
     An integer representing the function call's stack level.  May be
     ‘None’ if the function call is a gap.

 -- Variable: RecordFunctionSegment.instructions
     A list of ‘gdb.RecordInstruction’ or ‘gdb.RecordGap’ objects
     associated with this function call.

 -- Variable: RecordFunctionSegment.up
     A ‘gdb.RecordFunctionSegment’ object representing the caller's
     function segment.  If the call has not been recorded, this will be
     the function segment to which control returns.  If neither the call
     nor the return have been recorded, this will be ‘None’.

 -- Variable: RecordFunctionSegment.prev
     A ‘gdb.RecordFunctionSegment’ object representing the previous
     segment of this function call.  May be ‘None’.

 -- Variable: RecordFunctionSegment.next
     A ‘gdb.RecordFunctionSegment’ object representing the next segment
     of this function call.  May be ‘None’.

   The following example demonstrates the usage of these objects and
functions to create a function that will rewind a record to the last
time a function in a different file was executed.  This would typically
be used to track the execution of user provided callback functions in a
library which typically are not visible in a back trace.

     def bringback ():
         rec = gdb.current_recording ()
         if not rec:
             return

         insn = rec.instruction_history
         if len (insn) == 0:
             return

         try:
             position = insn.index (rec.replay_position)
         except:
             position = -1
         try:
             filename = insn[position].sal.symtab.fullname ()
         except:
             filename = None

         for i in reversed (insn[:position]):
     	try:
                 current = i.sal.symtab.fullname ()
     	except:
                 current = None

             if filename == current:
                 continue

             rec.goto (i)
             return

   Another possible application is to write a function that counts the
number of code executions in a given line range.  This line range can
contain parts of functions or span across several functions and is not
limited to be contiguous.

     def countrange (filename, linerange):
         count = 0

         def filter_only (file_name):
             for call in gdb.current_recording ().function_call_history:
                 try:
                     if file_name in call.symbol.symtab.fullname ():
                         yield call
                 except:
                     pass

         for c in filter_only (filename):
             for i in c.instructions:
                 try:
                     if i.sal.line in linerange:
                         count += 1
                         break;
                 except:
                         pass

         return count


File: gdb.info,  Node: CLI Commands In Python,  Next: GDB/MI Commands In Python,  Prev: Recordings In Python,  Up: Python API

23.3.2.21 CLI Commands In Python
................................

You can implement new GDB CLI commands in Python.  A CLI command is
implemented using an instance of the ‘gdb.Command’ class, most commonly
using a subclass.

 -- Function: Command.__init__ (name, command_class [, completer_class
          [, prefix]])
     The object initializer for ‘Command’ registers the new command with
     GDB.  This initializer is normally invoked from the subclass' own
     ‘__init__’ method.

     NAME is the name of the command.  If NAME consists of multiple
     words, then the initial words are looked for as prefix commands.
     In this case, if one of the prefix commands does not exist, an
     exception is raised.

     There is no support for multi-line commands.

     COMMAND_CLASS should be one of the ‘COMMAND_’ constants defined
     below.  This argument tells GDB how to categorize the new command
     in the help system.

     COMPLETER_CLASS is an optional argument.  If given, it should be
     one of the ‘COMPLETE_’ constants defined below.  This argument
     tells GDB how to perform completion for this command.  If not
     given, GDB will attempt to complete using the object's ‘complete’
     method (see below); if no such method is found, an error will occur
     when completion is attempted.

     PREFIX is an optional argument.  If ‘True’, then the new command is
     a prefix command; sub-commands of this command may be registered.

     The help text for the new command is taken from the Python
     documentation string for the command's class, if there is one.  If
     no documentation string is provided, the default value ‘This
     command is not documented.’ is used.

 -- Function: Command.dont_repeat ()
     By default, a GDB command is repeated when the user enters a blank
     line at the command prompt.  A command can suppress this behavior
     by invoking the ‘dont_repeat’ method at some point in its ‘invoke’
     method (normally this is done early in case of exception).  This is
     similar to the user command ‘dont-repeat’, see *note dont-repeat:
     Define.

 -- Function: Command.invoke (argument, from_tty)
     This method is called by GDB when this command is invoked.

     ARGUMENT is a string.  It is the argument to the command, after
     leading and trailing whitespace has been stripped.

     FROM_TTY is a boolean argument.  When true, this means that the
     command was entered by the user at the terminal; when false it
     means that the command came from elsewhere.

     If this method throws an exception, it is turned into a GDB ‘error’
     call.  Otherwise, the return value is ignored.

     For non-prefix commands (*note Command.__init__::), the ‘invoke’
     method is required.  For prefix commands the ‘invoke’ method is
     optional.  Only prefix commands that need to handle unknown
     sub-commands should implement the ‘invoke’ method.

     For prefix commands that don't implement ‘invoke’, if the prefix
     command is used without a sub-command name then GDB will display
     the help text for every sub-command, unless the prefix command is a
     ‘show’ sub-command, in which case GDB will list the values of all
     sub-commands.

     To break ARGUMENT up into an argv-like string use
     ‘gdb.string_to_argv’.  This function behaves identically to GDB's
     internal argument lexer ‘buildargv’.  It is recommended to use this
     for consistency.  Arguments are separated by spaces and may be
     quoted.  Example:

          print gdb.string_to_argv ("1 2\ \\\"3 '4 \"5' \"6 '7\"")
          ['1', '2 "3', '4 "5', "6 '7"]

 -- Function: Command.complete (text, word)
     This method is called by GDB when the user attempts completion on
     this command.  All forms of completion are handled by this method,
     that is, the <TAB> and <M-?> key bindings (*note Completion::), and
     the ‘complete’ command (*note complete: Help.).

     The arguments TEXT and WORD are both strings; TEXT holds the
     complete command line up to the cursor's location, while WORD holds
     the last word of the command line; this is computed using a
     word-breaking heuristic.

     The ‘complete’ method can return several values:
        • If the return value is a sequence, the contents of the
          sequence are used as the completions.  It is up to ‘complete’
          to ensure that the contents actually do complete the word.  A
          zero-length sequence is allowed, it means that there were no
          completions available.  Only string elements of the sequence
          are used; other elements in the sequence are ignored.

        • If the return value is one of the ‘COMPLETE_’ constants
          defined below, then the corresponding GDB-internal completion
          function is invoked, and its result is used.

        • All other results are treated as though there were no
          available completions.

   When a new command is registered, it must be declared as a member of
some general class of commands.  This is used to classify top-level
commands in the on-line help system; note that prefix commands are not
listed under their own category but rather that of their top-level
command.  The available classifications are represented by constants
defined in the ‘gdb’ module:

‘gdb.COMMAND_NONE’
     The command does not belong to any particular class.  A command in
     this category will not be displayed in any of the help categories.

‘gdb.COMMAND_RUNNING’
     The command is related to running the inferior.  For example,
     ‘start’, ‘step’, and ‘continue’ are in this category.  Type ‘help
     running’ at the GDB prompt to see a list of commands in this
     category.

‘gdb.COMMAND_DATA’
     The command is related to data or variables.  For example, ‘call’,
     ‘find’, and ‘print’ are in this category.  Type ‘help data’ at the
     GDB prompt to see a list of commands in this category.

‘gdb.COMMAND_STACK’
     The command has to do with manipulation of the stack.  For example,
     ‘backtrace’, ‘frame’, and ‘return’ are in this category.  Type
     ‘help stack’ at the GDB prompt to see a list of commands in this
     category.

‘gdb.COMMAND_FILES’
     This class is used for file-related commands.  For example, ‘file’,
     ‘list’ and ‘section’ are in this category.  Type ‘help files’ at
     the GDB prompt to see a list of commands in this category.

‘gdb.COMMAND_SUPPORT’
     This should be used for "support facilities", generally meaning
     things that are useful to the user when interacting with GDB, but
     not related to the state of the inferior.  For example, ‘help’,
     ‘make’, and ‘shell’ are in this category.  Type ‘help support’ at
     the GDB prompt to see a list of commands in this category.

‘gdb.COMMAND_STATUS’
     The command is an ‘info’-related command, that is, related to the
     state of GDB itself.  For example, ‘info’, ‘macro’, and ‘show’ are
     in this category.  Type ‘help status’ at the GDB prompt to see a
     list of commands in this category.

‘gdb.COMMAND_BREAKPOINTS’
     The command has to do with breakpoints.  For example, ‘break’,
     ‘clear’, and ‘delete’ are in this category.  Type ‘help
     breakpoints’ at the GDB prompt to see a list of commands in this
     category.

‘gdb.COMMAND_TRACEPOINTS’
     The command has to do with tracepoints.  For example, ‘trace’,
     ‘actions’, and ‘tfind’ are in this category.  Type ‘help
     tracepoints’ at the GDB prompt to see a list of commands in this
     category.

‘gdb.COMMAND_TUI’
     The command has to do with the text user interface (*note TUI::).
     Type ‘help tui’ at the GDB prompt to see a list of commands in this
     category.

‘gdb.COMMAND_USER’
     The command is a general purpose command for the user, and
     typically does not fit in one of the other categories.  Type ‘help
     user-defined’ at the GDB prompt to see a list of commands in this
     category, as well as the list of gdb macros (*note Sequences::).

‘gdb.COMMAND_OBSCURE’
     The command is only used in unusual circumstances, or is not of
     general interest to users.  For example, ‘checkpoint’, ‘fork’, and
     ‘stop’ are in this category.  Type ‘help obscure’ at the GDB prompt
     to see a list of commands in this category.

‘gdb.COMMAND_MAINTENANCE’
     The command is only useful to GDB maintainers.  The ‘maintenance’
     and ‘flushregs’ commands are in this category.  Type ‘help
     internals’ at the GDB prompt to see a list of commands in this
     category.

   A new command can use a predefined completion function, either by
specifying it via an argument at initialization, or by returning it from
the ‘complete’ method.  These predefined completion constants are all
defined in the ‘gdb’ module:

‘gdb.COMPLETE_NONE’
     This constant means that no completion should be done.

‘gdb.COMPLETE_FILENAME’
     This constant means that filename completion should be performed.

‘gdb.COMPLETE_LOCATION’
     This constant means that location completion should be done.  *Note
     Location Specifications::.

‘gdb.COMPLETE_COMMAND’
     This constant means that completion should examine GDB command
     names.

‘gdb.COMPLETE_SYMBOL’
     This constant means that completion should be done using symbol
     names as the source.

‘gdb.COMPLETE_EXPRESSION’
     This constant means that completion should be done on expressions.
     Often this means completing on symbol names, but some language
     parsers also have support for completing on field names.

   The following code snippet shows how a trivial CLI command can be
implemented in Python:

     class HelloWorld (gdb.Command):
       """Greet the whole world."""

       def __init__ (self):
         super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)

       def invoke (self, arg, from_tty):
         print ("Hello, World!")

     HelloWorld ()

   The last line instantiates the class, and is necessary to trigger the
registration of the command with GDB.  Depending on how the Python code
is read into GDB, you may need to import the ‘gdb’ module explicitly.


File: gdb.info,  Node: GDB/MI Commands In Python,  Next: GDB/MI Notifications In Python,  Prev: CLI Commands In Python,  Up: Python API

23.3.2.22 GDB/MI Commands In Python
...................................

It is possible to add GDB/MI (*note GDB/MI::) commands implemented in
Python.  A GDB/MI command is implemented using an instance of the
‘gdb.MICommand’ class, most commonly using a subclass.

 -- Function: MICommand.__init__ (name)
     The object initializer for ‘MICommand’ registers the new command
     with GDB.  This initializer is normally invoked from the subclass'
     own ‘__init__’ method.

     NAME is the name of the command.  It must be a valid name of a
     GDB/MI command, and in particular must start with a hyphen (‘-’).
     Reusing the name of a built-in GDB/MI is not allowed, and a
     ‘RuntimeError’ will be raised.  Using the name of an GDB/MI command
     previously defined in Python is allowed, the previous command will
     be replaced with the new command.

 -- Function: MICommand.invoke (arguments)
     This method is called by GDB when the new MI command is invoked.

     ARGUMENTS is a list of strings.  Note, that ‘--thread’ and
     ‘--frame’ arguments are handled by GDB itself therefore they do not
     show up in ‘arguments’.

     If this method raises an exception, then it is turned into a GDB/MI
     ‘^error’ response.  Only ‘gdb.GdbError’ exceptions (or its
     sub-classes) should be used for reporting errors to users, any
     other exception type is treated as a failure of the ‘invoke’
     method, and the exception will be printed to the error stream
     according to the ‘set python print-stack’ setting (*note ‘set
     python print-stack’: set_python_print_stack.).

     If this method returns ‘None’, then the GDB/MI command will return
     a ‘^done’ response with no additional values.

     Otherwise, the return value must be a dictionary, which is
     converted to a GDB/MI RESULT-RECORD (*note GDB/MI Output Syntax::).
     The keys of this dictionary must be strings, and are used as
     VARIABLE names in the RESULT-RECORD, these strings must comply with
     the naming rules detailed below.  The values of this dictionary are
     recursively handled as follows:

        • If the value is Python sequence or iterator, it is converted
          to GDB/MI LIST with elements converted recursively.

        • If the value is Python dictionary, it is converted to GDB/MI
          TUPLE.  Keys in that dictionary must be strings, which comply
          with the VARIABLE naming rules detailed below.  Values are
          converted recursively.

        • Otherwise, value is first converted to a Python string using
          ‘str ()’ and then converted to GDB/MI CONST.

     The strings used for VARIABLE names in the GDB/MI output must
     follow the following rules; the string must be at least one
     character long, the first character must be in the set ‘[a-zA-Z]’,
     while every subsequent character must be in the set
     ‘[-_a-zA-Z0-9]’.

   An instance of ‘MICommand’ has the following attributes:

 -- Variable: MICommand.name
     A string, the name of this GDB/MI command, as was passed to the
     ‘__init__’ method.  This attribute is read-only.

 -- Variable: MICommand.installed
     A boolean value indicating if this command is installed ready for a
     user to call from the command line.  Commands are automatically
     installed when they are instantiated, after which this attribute
     will be ‘True’.

     If later, a new command is created with the same name, then the
     original command will become uninstalled, and this attribute will
     be ‘False’.

     This attribute is read-write, setting this attribute to ‘False’
     will uninstall the command, removing it from the set of available
     commands.  Setting this attribute to ‘True’ will install the
     command for use.  If there is already a Python command with this
     name installed, the currently installed command will be
     uninstalled, and this command installed in its stead.

   The following code snippet shows how some trivial MI commands can be
implemented in Python:

     class MIEcho(gdb.MICommand):
         """Echo arguments passed to the command."""

         def __init__(self, name, mode):
             self._mode = mode
             super(MIEcho, self).__init__(name)

         def invoke(self, argv):
             if self._mode == 'dict':
                 return { 'dict': { 'argv' : argv } }
             elif self._mode == 'list':
                 return { 'list': argv }
             else:
                 return { 'string': ", ".join(argv) }


     MIEcho("-echo-dict", "dict")
     MIEcho("-echo-list", "list")
     MIEcho("-echo-string", "string")

   The last three lines instantiate the class three times, creating
three new GDB/MI commands ‘-echo-dict’, ‘-echo-list’, and
‘-echo-string’.  Each time a subclass of ‘gdb.MICommand’ is
instantiated, the new command is automatically registered with GDB.

   Depending on how the Python code is read into GDB, you may need to
import the ‘gdb’ module explicitly.

   The following example shows a GDB session in which the above commands
have been added:

     (gdb)
     -echo-dict abc def ghi
     ^done,dict={argv=["abc","def","ghi"]}
     (gdb)
     -echo-list abc def ghi
     ^done,list=["abc","def","ghi"]
     (gdb)
     -echo-string abc def ghi
     ^done,string="abc, def, ghi"
     (gdb)

   Conversely, it is possible to execute GDB/MI commands from Python,
with the results being a Python object and not a specially-formatted
string.  This is done with the ‘gdb.execute_mi’ function.

 -- Function: gdb.execute_mi (command [, arg ]...)
     Invoke a GDB/MI command.  COMMAND is the name of the command, a
     string.  The arguments, ARG, are passed to the command.  Each
     argument must also be a string.

     This function returns a Python dictionary whose contents reflect
     the corresponding GDB/MI command's output.  Refer to the
     documentation for these commands for details.  Lists are
     represented as Python lists, and tuples are represented as Python
     dictionaries.

     If the command fails, it will raise a Python exception.

   Here is how this works using the commands from the example above:

     (gdb) python print(gdb.execute_mi("-echo-dict", "abc", "def", "ghi"))
     {'dict': {'argv': ['abc', 'def', 'ghi']}}
     (gdb) python print(gdb.execute_mi("-echo-list", "abc", "def", "ghi"))
     {'list': ['abc', 'def', 'ghi']}
     (gdb) python print(gdb.execute_mi("-echo-string", "abc", "def", "ghi"))
     {'string': 'abc, def, ghi'}


File: gdb.info,  Node: GDB/MI Notifications In Python,  Next: Parameters In Python,  Prev: GDB/MI Commands In Python,  Up: Python API

23.3.2.23 GDB/MI Notifications In Python
........................................

It is possible to emit GDB/MI notifications from Python.  Use the
‘gdb.notify_mi’ function to do that.

 -- Function: gdb.notify_mi (name [, data])
     Emit a GDB/MI asynchronous notification.  NAME is the name of the
     notification, consisting of alphanumeric characters and a hyphen
     (‘-’).  DATA is any additional data to be emitted with the
     notification, passed as a Python dictionary.  This argument is
     optional.  The dictionary is converted to a GDB/MI RESULT records
     (*note GDB/MI Output Syntax::) the same way as result of Python MI
     command (*note GDB/MI Commands In Python::).

     If DATA is ‘None’ then no additional values are emitted.

   While using existing notification names (*note GDB/MI Async
Records::) with ‘gdb.notify_mi’ is allowed, users are encouraged to
prefix user-defined notification with a hyphen (‘-’) to avoid possible
conflict.  GDB will never introduce notification starting with hyphen.

   Here is how to emit ‘=-connection-removed’ whenever a connection to
remote GDB server is closed (*note Connections In Python::):

     def notify_connection_removed(event):
         data = {"id": event.connection.num, "type": event.connection.type}
         gdb.notify_mi("-connection-removed", data)


     gdb.events.connection_removed.connect(notify_connection_removed)

   Then, each time a connection is closed, there will be a notification
on MI channel:

     =-connection-removed,id="1",type="remote"


File: gdb.info,  Node: Parameters In Python,  Next: Functions In Python,  Prev: GDB/MI Notifications In Python,  Up: Python API

23.3.2.24 Parameters In Python
..............................

You can implement new GDB parameters using Python.  A new parameter is
implemented as an instance of the ‘gdb.Parameter’ class.

   Parameters are exposed to the user via the ‘set’ and ‘show’ commands.
*Note Help::.

   There are many parameters that already exist and can be set in GDB.
Two examples are: ‘set follow fork’ and ‘set charset’.  Setting these
parameters influences certain behavior in GDB.  Similarly, you can
define parameters that can be used to influence behavior in custom
Python scripts and commands.

 -- Function: Parameter.__init__ (name, command_class, parameter_class
          [, enum_sequence])
     The object initializer for ‘Parameter’ registers the new parameter
     with GDB.  This initializer is normally invoked from the subclass'
     own ‘__init__’ method.

     NAME is the name of the new parameter.  If NAME consists of
     multiple words, then the initial words are looked for as prefix
     parameters.  An example of this can be illustrated with the ‘set
     print’ set of parameters.  If NAME is ‘print foo’, then ‘print’
     will be searched as the prefix parameter.  In this case the
     parameter can subsequently be accessed in GDB as ‘set print foo’.

     If NAME consists of multiple words, and no prefix parameter group
     can be found, an exception is raised.

     COMMAND_CLASS should be one of the ‘COMMAND_’ constants (*note CLI
     Commands In Python::).  This argument tells GDB how to categorize
     the new parameter in the help system.

     PARAMETER_CLASS should be one of the ‘PARAM_’ constants defined
     below.  This argument tells GDB the type of the new parameter; this
     information is used for input validation and completion.

     If PARAMETER_CLASS is ‘PARAM_ENUM’, then ENUM_SEQUENCE must be a
     sequence of strings.  These strings represent the possible values
     for the parameter.

     If PARAMETER_CLASS is not ‘PARAM_ENUM’, then the presence of a
     fourth argument will cause an exception to be thrown.

     The help text for the new parameter includes the Python
     documentation string from the parameter's class, if there is one.
     If there is no documentation string, a default value is used.  The
     documentation string is included in the output of the parameters
     ‘help set’ and ‘help show’ commands, and should be written taking
     this into account.  If the documentation string for the parameter's
     class is the empty string then GDB will only use
     ‘Parameter.set_doc’ or ‘Parameter.show_doc’ (see below) in the
     ‘help’ output.

 -- Variable: Parameter.set_doc
     If this attribute exists, and is a string, then its value is used
     as the first part of the help text for this parameter's ‘set’
     command.  The second part of the help text is taken from the
     documentation string for the parameter's class, if there is one.

     The value of ‘set_doc’ should give a brief summary specific to the
     set action, this text is only displayed when the user runs the
     ‘help set’ command for this parameter.  The class documentation
     should be used to give a fuller description of what the parameter
     does, this text is displayed for both the ‘help set’ and ‘help
     show’ commands.

     The ‘set_doc’ value is examined when ‘Parameter.__init__’ is
     invoked; subsequent changes have no effect.

 -- Variable: Parameter.show_doc
     If this attribute exists, and is a string, then its value is used
     as the first part of the help text for this parameter's ‘show’
     command.  The second part of the help text is taken from the
     documentation string for the parameter's class, if there is one.

     The value of ‘show_doc’ should give a brief summary specific to the
     show action, this text is only displayed when the user runs the
     ‘help show’ command for this parameter.  The class documentation
     should be used to give a fuller description of what the parameter
     does, this text is displayed for both the ‘help set’ and ‘help
     show’ commands.

     The ‘show_doc’ value is examined when ‘Parameter.__init__’ is
     invoked; subsequent changes have no effect.

 -- Variable: Parameter.value
     The ‘value’ attribute holds the underlying value of the parameter.
     It can be read and assigned to just as any other attribute.  GDB
     does validation when assignments are made.

   There are two methods that may be implemented in any ‘Parameter’
class.  These are:

 -- Function: Parameter.get_set_string (self)
     If this method exists, GDB will call it when a PARAMETER's value
     has been changed via the ‘set’ API (for example, ‘set foo off’).
     The ‘value’ attribute has already been populated with the new value
     and may be used in output.  This method must return a string.  If
     the returned string is not empty, GDB will present it to the user.

     If this method raises the ‘gdb.GdbError’ exception (*note Exception
     Handling::), then GDB will print the exception's string and the
     ‘set’ command will fail.  Note, however, that the ‘value’ attribute
     will not be reset in this case.  So, if your parameter must
     validate values, it should store the old value internally and reset
     the exposed value, like so:

          class ExampleParam (gdb.Parameter):
             def __init__ (self, name):
                super (ExampleParam, self).__init__ (name,
                             gdb.COMMAND_DATA,
                             gdb.PARAM_BOOLEAN)
                self.value = True
                self.saved_value = True
             def validate(self):
                return False
             def get_set_string (self):
                if not self.validate():
                  self.value = self.saved_value
                  raise gdb.GdbError('Failed to validate')
                self.saved_value = self.value
                return ""

 -- Function: Parameter.get_show_string (self, svalue)
     GDB will call this method when a PARAMETER's ‘show’ API has been
     invoked (for example, ‘show foo’).  The argument ‘svalue’ receives
     the string representation of the current value.  This method must
     return a string.

   When a new parameter is defined, its type must be specified.  The
available types are represented by constants defined in the ‘gdb’
module:

‘gdb.PARAM_BOOLEAN’
     The value is a plain boolean.  The Python boolean values, ‘True’
     and ‘False’ are the only valid values.

‘gdb.PARAM_AUTO_BOOLEAN’
     The value has three possible states: true, false, and ‘auto’.  In
     Python, true and false are represented using boolean constants, and
     ‘auto’ is represented using ‘None’.

‘gdb.PARAM_UINTEGER’
     The value is an unsigned integer.  The value of ‘None’ should be
     interpreted to mean "unlimited" (literal ‘'unlimited'’ can also be
     used to set that value), and the value of 0 is reserved and should
     not be used.

‘gdb.PARAM_INTEGER’
     The value is a signed integer.  The value of ‘None’ should be
     interpreted to mean "unlimited" (literal ‘'unlimited'’ can also be
     used to set that value), and the value of 0 is reserved and should
     not be used.

‘gdb.PARAM_STRING’
     The value is a string.  When the user modifies the string, any
     escape sequences, such as ‘\t’, ‘\f’, and octal escapes, are
     translated into corresponding characters and encoded into the
     current host charset.

‘gdb.PARAM_STRING_NOESCAPE’
     The value is a string.  When the user modifies the string, escapes
     are passed through untranslated.

‘gdb.PARAM_OPTIONAL_FILENAME’
     The value is a either a filename (a string), or ‘None’.

‘gdb.PARAM_FILENAME’
     The value is a filename.  This is just like
     ‘PARAM_STRING_NOESCAPE’, but uses file names for completion.

‘gdb.PARAM_ZINTEGER’
     The value is a signed integer.  This is like ‘PARAM_INTEGER’,
     except that 0 is allowed and the value of ‘None’ is not supported.

‘gdb.PARAM_ZUINTEGER’
     The value is an unsigned integer.  This is like ‘PARAM_UINTEGER’,
     except that 0 is allowed and the value of ‘None’ is not supported.

‘gdb.PARAM_ZUINTEGER_UNLIMITED’
     The value is a signed integer.  This is like ‘PARAM_INTEGER’
     including that the value of ‘None’ should be interpreted to mean
     "unlimited" (literal ‘'unlimited'’ can also be used to set that
     value), except that 0 is allowed, and the value cannot be negative,
     except the special value -1 is returned for the setting of
     "unlimited".

‘gdb.PARAM_ENUM’
     The value is a string, which must be one of a collection string
     constants provided when the parameter is created.

‘gdb.PARAM_COLOR’
     The value is ‘gdb.Color’ instance.

   When creating multiple new parameters using ‘gdb.Parameter’, it is
often desirable to create a prefix command that can be used to group
related parameters together, for example, if you wished to add the
parameters ‘plugin-name feature-1’ and ‘plugin-name feature-2’, then the
‘plugin-name’ would need to be a prefix command (*note CLI Commands In
Python::).

   However, when creating parameters, you will almost always need to
create two prefix commands, one as a ‘set’ sub-command, and one as a
‘show’ sub-command.  GDB provides the ‘gdb.ParameterPrefix’ helper class
to make creation of these two prefixes easier.

 -- Function: ParameterPrefix.__init__ (name, command_class, doc = None)
     The object initializer for ‘ParameterPrefix’ registers two new
     ‘gdb.Command’ prefixes, one as a ‘set’ sub-command, and the other
     as a ‘show’ sub-command.

     NAME, a string, is the name of the new prefix, without either ‘set’
     or ‘show’, similar to the NAME passed to ‘gdb.Parameter’ (*note
     Parameters In Python::).  For example, to create the prefixes ‘set
     plugin-name’ and ‘show plugin-name’, you would pass the string
     ‘plugin-name’.

     COMMAND_CLASS should be one of the ‘COMMAND_’ constants (*note CLI
     Commands In Python::).  This argument tells GDB how to categorize
     the new parameter prefixes in the help system.

     There are a number of ways in which the help text for the two new
     prefix commands can be provided.  If the DOC parameter is not
     ‘None’, then this will be used as the documentation string for both
     prefix commands.

     If DOC is ‘None’, but ‘gdb.ParameterPrefix’ has been sub-classed,
     then the prefix command documentation will be taken from
     sub-classes documentation string (i.e., the ‘__doc__’ attribute).

     If DOC is ‘None’, and there is no ‘__doc__’ string, then the
     default value ‘This command is not documented.’ is used.

     When writing the help text, keep in mind that the same text is used
     for both the ‘set’ and ‘show’ prefix commands.

 -- Function: ParameterPrefix.invoke_set (argument, from_tty)
     If a sub-class defines this method, then GDB will call this when
     the prefix command is used with an unknown sub-command.  The
     ARGUMENT and FROM_TTY parameters are the same as for
     ‘gdb.Command.invoke’ (*note Command.invoke::).

     If this method throws an exception, it is turned into a GDB ‘error’
     call.  Otherwise, the return value is ignored.

     It is not required that a ‘ParameterPrefix’ sub-class override this
     method.  Usually, a parameter prefix only exists as a means to
     group related parameters together.  GDB handles this use case
     automatically with no need to implement ‘invoke_set’.

 -- Function: ParameterPrefix.invoke_show (argument, from_tty)
     This is like the ‘invoke_set’ method, but for the ‘show’ prefix
     command.  As with ‘invoke_set’, implementation of this method is
     optional, and usually not required.

 -- Function: ParameterPrefix.dont_repeat ()
     Like ‘Command.dont_repeat’ (*note Command.dont_repeat::), this can
     be called from ‘ParameterPrefix.invoke_set’ or
     ‘ParameterPrefix.invoke_show’ to prevent the prefix commands from
     being repeated.

   Here is a small example that uses ‘gdb.ParameterPrefix’ along with
‘gdb.Parameter’ to create two new parameters ‘plugin-name feature-1’ and
‘plugin-name feature-2’.  As neither ‘invoke_set’ or ‘invoke_show’ is
needed, this example does not sub-class ‘gdb.ParameterPrefix’:

     class ExampleParam(gdb.Parameter):
        def __init__ (self, name):
           super ().__init__ (name, gdb.COMMAND_DATA, gdb.PARAM_BOOLEAN)
           self.value = True

     gdb.ParameterPrefix("plugin-name", gdb.COMMAND_NONE,
                         """An example parameter prefix.

                         This groups together some parameters.""")
     ExampleParam("plugin-name feature-1")
     ExampleParam("plugin-name feature-2")


File: gdb.info,  Node: Functions In Python,  Next: Progspaces In Python,  Prev: Parameters In Python,  Up: Python API

23.3.2.25 Writing new convenience functions
...........................................

You can implement new convenience functions (*note Convenience Vars::)
in Python.  A convenience function is an instance of a subclass of the
class ‘gdb.Function’.

 -- Function: Function.__init__ (name)
     The initializer for ‘Function’ registers the new function with GDB.
     The argument NAME is the name of the function, a string.  The
     function will be visible to the user as a convenience variable of
     type ‘internal function’, whose name is the same as the given NAME.

     The documentation for the new function is taken from the
     documentation string for the new class.

 -- Function: Function.invoke (*args)
     When a convenience function is evaluated, its arguments are
     converted to instances of ‘gdb.Value’, and then the function's
     ‘invoke’ method is called.  Note that GDB does not predetermine the
     arity of convenience functions.  Instead, all available arguments
     are passed to ‘invoke’, following the standard Python calling
     convention.  In particular, a convenience function can have default
     values for parameters without ill effect.

     The return value of this method is used as its value in the
     enclosing expression.  If an ordinary Python value is returned, it
     is converted to a ‘gdb.Value’ following the usual rules.

   The following code snippet shows how a trivial convenience function
can be implemented in Python:

     class Greet (gdb.Function):
       """Return string to greet someone.
     Takes a name as argument."""

       def __init__ (self):
         super (Greet, self).__init__ ("greet")

       def invoke (self, name):
         return "Hello, %s!" % name.string ()

     Greet ()

   The last line instantiates the class, and is necessary to trigger the
registration of the function with GDB.  Depending on how the Python code
is read into GDB, you may need to import the ‘gdb’ module explicitly.

   Now you can use the function in an expression:

     (gdb) print $greet("Bob")
     $1 = "Hello, Bob!"


File: gdb.info,  Node: Progspaces In Python,  Next: Objfiles In Python,  Prev: Functions In Python,  Up: Python API

23.3.2.26 Program Spaces In Python
..................................

A program space, or “progspace”, represents a symbolic view of an
address space.  It consists of all of the objfiles of the program.
*Note Objfiles In Python::.  *Note program spaces: Inferiors Connections
and Programs, for more details about program spaces.

   The following progspace-related functions are available in the ‘gdb’
module:

 -- Function: gdb.current_progspace ()
     This function returns the program space of the currently selected
     inferior.  *Note Inferiors Connections and Programs::.  This is
     identical to ‘gdb.selected_inferior().progspace’ (*note Inferiors
     In Python::) and is included for historical compatibility.

 -- Function: gdb.progspaces ()
     Return a sequence of all the progspaces currently known to GDB.

   Each progspace is represented by an instance of the ‘gdb.Progspace’
class.

 -- Variable: Progspace.filename
     The file name, as a string, of the main symbol file (from which
     debug symbols have been loaded) for the progspace, e.g. the
     argument to the ‘symbol-file’ or ‘file’ commands.

     If there is no main symbol table currently loaded, then this
     attribute will be ‘None’.

 -- Variable: Progspace.symbol_file
     The ‘gdb.Objfile’ representing the main symbol file (from which
     debug symbols have been loaded) for the ‘gdb.Progspace’.  This is
     the symbol file set by the ‘symbol-file’ or ‘file’ commands.

     This will be the ‘gdb.Objfile’ representing ‘Progspace.filename’
     when ‘Progspace.filename’ is not ‘None’.

     If there is no main symbol table currently loaded, then this
     attribute will be ‘None’.

     If the ‘Progspace’ is invalid, i.e., when ‘Progspace.is_valid()’
     returns ‘False’, then attempting to access this attribute will
     raise a ‘RuntimeError’ exception.

 -- Variable: Progspace.executable_filename
     The file name, as a string, of the executable file in use by this
     program space.  The executable file is the file that GDB will
     invoke in order to start an inferior when using a native target.
     The file name within this attribute is updated by the ‘exec-file’
     and ‘file’ commands.

     If no executable is currently set within this ‘Progspace’ then this
     attribute contains ‘None’.

     If the ‘Progspace’ is invalid, i.e., when ‘Progspace.is_valid()’
     returns ‘False’, then attempting to access this attribute will
     raise a ‘RuntimeError’ exception.

 -- Variable: Progspace.pretty_printers
     The ‘pretty_printers’ attribute is a list of functions.  It is used
     to look up pretty-printers.  A ‘Value’ is passed to each function
     in order; if the function returns ‘None’, then the search
     continues.  Otherwise, the return value should be an object which
     is used to format the value.  *Note Pretty Printing API::, for more
     information.

 -- Variable: Progspace.type_printers
     The ‘type_printers’ attribute is a list of type printer objects.
     *Note Type Printing API::, for more information.

 -- Variable: Progspace.frame_filters
     The ‘frame_filters’ attribute is a dictionary of frame filter
     objects.  *Note Frame Filter API::, for more information.

 -- Variable: Progspace.missing_file_handlers
     The ‘missing_file_handlers’ attribute is a list of tuples.  Each
     tuple holds a missing-file handler object for this program space.
     For more information, *note Missing Debug Info In Python::, and
     *note Missing Objfiles In Python::.

   A program space has the following methods:

 -- Function: Progspace.block_for_pc (pc)
     Return the innermost ‘gdb.Block’ containing the given PC value.  If
     the block cannot be found for the PC value specified, the function
     will return ‘None’.

 -- Function: Progspace.find_pc_line (pc)
     Return the ‘gdb.Symtab_and_line’ object corresponding to the PC
     value.  *Note Symbol Tables In Python::.  If an invalid value of PC
     is passed as an argument, then the ‘symtab’ and ‘line’ attributes
     of the returned ‘gdb.Symtab_and_line’ object will be ‘None’ and 0
     respectively.

 -- Function: Progspace.is_valid ()
     Returns ‘True’ if the ‘gdb.Progspace’ object is valid, ‘False’ if
     not.  A ‘gdb.Progspace’ object can become invalid if the program
     space file it refers to is not referenced by any inferior.  All
     other ‘gdb.Progspace’ methods will throw an exception if it is
     invalid at the time the method is called.

 -- Function: Progspace.objfiles ()
     Return a sequence of all the objfiles referenced by this program
     space.  *Note Objfiles In Python::.

 -- Function: Progspace.solib_name (address)
     Return the name of the shared library holding the given ADDRESS as
     a string, or ‘None’.

 -- Function: Progspace.objfile_for_address (address)
     Return the ‘gdb.Objfile’ holding the given address, or ‘None’ if no
     objfile covers it.

   One may add arbitrary attributes to ‘gdb.Progspace’ objects in the
usual Python way.  This is useful if, for example, one needs to do some
extra record keeping associated with the program space.

   *Note choosing attribute names::, for guidance on selecting a
suitable name for new attributes.

   In this contrived example, we want to perform some processing when an
objfile with a certain symbol is loaded, but we only want to do this
once because it is expensive.  To achieve this we record the results
with the program space because we can't predict when the desired objfile
will be loaded.

     (gdb) python
     def clear_objfiles_handler(event):
         event.progspace.expensive_computation = None
     def expensive(symbol):
         """A mock routine to perform an "expensive" computation on symbol."""
         print ("Computing the answer to the ultimate question ...")
         return 42
     def new_objfile_handler(event):
         objfile = event.new_objfile
         progspace = objfile.progspace
         if not hasattr(progspace, 'expensive_computation') or \
                 progspace.expensive_computation is None:
             # We use 'main' for the symbol to keep the example simple.
             # Note: There's no current way to constrain the lookup
             # to one objfile.
             symbol = gdb.lookup_global_symbol('main')
             if symbol is not None:
                 progspace.expensive_computation = expensive(symbol)
     gdb.events.clear_objfiles.connect(clear_objfiles_handler)
     gdb.events.new_objfile.connect(new_objfile_handler)
     end
     (gdb) file /tmp/hello
     Reading symbols from /tmp/hello...
     Computing the answer to the ultimate question ...
     (gdb) python print(gdb.current_progspace().expensive_computation)
     42
     (gdb) run
     Starting program: /tmp/hello
     Hello.
     [Inferior 1 (process 4242) exited normally]


File: gdb.info,  Node: Objfiles In Python,  Next: Frames In Python,  Prev: Progspaces In Python,  Up: Python API

23.3.2.27 Objfiles In Python
............................

GDB loads symbols for an inferior from various symbol-containing files
(*note Files::).  These include the primary executable file, any shared
libraries used by the inferior, and any separate debug info files (*note
Separate Debug Files::).  GDB calls these symbol-containing files
“objfiles”.

   The following objfile-related functions are available in the ‘gdb’
module:

 -- Function: gdb.current_objfile ()
     When auto-loading a Python script (*note Python Auto-loading::),
     GDB sets the "current objfile" to the corresponding objfile.  This
     function returns the current objfile.  If there is no current
     objfile, this function returns ‘None’.

 -- Function: gdb.objfiles ()
     Return a sequence of objfiles referenced by the current program
     space.  *Note Objfiles In Python::, and *note Progspaces In
     Python::.  This is identical to
     ‘gdb.selected_inferior().progspace.objfiles()’ and is included for
     historical compatibility.

 -- Function: gdb.lookup_objfile (name [, by_build_id])
     Look up NAME, a file name or build ID, in the list of objfiles for
     the current program space (*note Progspaces In Python::).  If the
     objfile is not found throw the Python ‘ValueError’ exception.

     If NAME is a relative file name, then it will match any source file
     name with the same trailing components.  For example, if NAME is
     ‘gcc/expr.c’, then it will match source file name of
     ‘/build/trunk/gcc/expr.c’, but not ‘/build/trunk/libcpp/expr.c’ or
     ‘/build/trunk/gcc/x-expr.c’.

     If BY_BUILD_ID is provided and is ‘True’ then NAME is the build ID
     of the objfile.  Otherwise, NAME is a file name.  This is supported
     only on some operating systems, notably those which use the ELF
     format for binary files and the GNU Binutils.  For more details
     about this feature, see the description of the ‘--build-id’
     command-line option in *note Command Line Options: (ld)Options.

   Each objfile is represented by an instance of the ‘gdb.Objfile’
class.

 -- Variable: Objfile.filename
     The file name of the objfile as a string, with symbolic links
     resolved.

     The value is ‘None’ if the objfile is no longer valid.  See the
     ‘gdb.Objfile.is_valid’ method, described below.

 -- Variable: Objfile.username
     The file name of the objfile as specified by the user as a string.

     The value is ‘None’ if the objfile is no longer valid.  See the
     ‘gdb.Objfile.is_valid’ method, described below.

 -- Variable: Objfile.is_file
     An objfile often comes from an ordinary file, but in some cases it
     may be constructed from the contents of memory.  This attribute is
     ‘True’ for file-backed objfiles, and ‘False’ for other kinds.

 -- Variable: Objfile.owner
     For separate debug info objfiles this is the corresponding
     ‘gdb.Objfile’ object that debug info is being provided for.
     Otherwise this is ‘None’.  Separate debug info objfiles are added
     with the ‘gdb.Objfile.add_separate_debug_file’ method, described
     below.

 -- Variable: Objfile.build_id
     The build ID of the objfile as a string.  If the objfile does not
     have a build ID then the value is ‘None’.

     This is supported only on some operating systems, notably those
     which use the ELF format for binary files and the GNU Binutils.
     For more details about this feature, see the description of the
     ‘--build-id’ command-line option in *note Command Line Options:
     (ld)Options.

 -- Variable: Objfile.progspace
     The containing program space of the objfile as a ‘gdb.Progspace’
     object.  *Note Progspaces In Python::.

 -- Variable: Objfile.pretty_printers
     The ‘pretty_printers’ attribute is a list of functions.  It is used
     to look up pretty-printers.  A ‘Value’ is passed to each function
     in order; if the function returns ‘None’, then the search
     continues.  Otherwise, the return value should be an object which
     is used to format the value.  *Note Pretty Printing API::, for more
     information.

 -- Variable: Objfile.type_printers
     The ‘type_printers’ attribute is a list of type printer objects.
     *Note Type Printing API::, for more information.

 -- Variable: Objfile.frame_filters
     The ‘frame_filters’ attribute is a dictionary of frame filter
     objects.  *Note Frame Filter API::, for more information.

   One may add arbitrary attributes to ‘gdb.Objfile’ objects in the
usual Python way.  This is useful if, for example, one needs to do some
extra record keeping associated with the objfile.

   *Note choosing attribute names::, for guidance on selecting a
suitable name for new attributes.

   In this contrived example we record the time when GDB loaded the
objfile.

     (gdb) python
     import datetime
     def new_objfile_handler(event):
         # Set the time_loaded attribute of the new objfile.
         event.new_objfile.time_loaded = datetime.datetime.today()
     gdb.events.new_objfile.connect(new_objfile_handler)
     end
     (gdb) file ./hello
     Reading symbols from ./hello...
     (gdb) python print(gdb.objfiles()[0].time_loaded)
     2014-10-09 11:41:36.770345

   A ‘gdb.Objfile’ object has the following methods:

 -- Function: Objfile.is_valid ()
     Returns ‘True’ if the ‘gdb.Objfile’ object is valid, ‘False’ if
     not.  A ‘gdb.Objfile’ object can become invalid if the object file
     it refers to is not loaded in GDB any longer.  All other
     ‘gdb.Objfile’ methods will throw an exception if it is invalid at
     the time the method is called.

 -- Function: Objfile.add_separate_debug_file (file)
     Add FILE to the list of files that GDB will search for debug
     information for the objfile.  This is useful when the debug info
     has been removed from the program and stored in a separate file.
     GDB has built-in support for finding separate debug info files
     (*note Separate Debug Files::), but if the file doesn't live in one
     of the standard places that GDB searches then this function can be
     used to add a debug info file from a different place.

 -- Function: Objfile.lookup_global_symbol (name [, domain])
     Search for a global symbol named NAME in this objfile.  Optionally,
     the search scope can be restricted with the DOMAIN argument.  The
     DOMAIN argument must be a domain constant defined in the ‘gdb’
     module and described in *note Symbols In Python::.  This function
     is similar to ‘gdb.lookup_global_symbol’, except that the search is
     limited to this objfile.

     The result is a ‘gdb.Symbol’ object or ‘None’ if the symbol is not
     found.

 -- Function: Objfile.lookup_static_symbol (name [, domain])
     Like ‘Objfile.lookup_global_symbol’, but searches for a global
     symbol with static linkage named NAME in this objfile.


File: gdb.info,  Node: Frames In Python,  Next: Blocks In Python,  Prev: Objfiles In Python,  Up: Python API

23.3.2.28 Accessing inferior stack frames from Python
.....................................................

When the debugged program stops, GDB is able to analyze its call stack
(*note Stack frames: Frames.).  The ‘gdb.Frame’ class represents a frame
in the stack.  A ‘gdb.Frame’ object is only valid while its
corresponding frame exists in the inferior's stack.  If you try to use
an invalid frame object, GDB will throw a ‘gdb.error’ exception (*note
Exception Handling::).

   Two ‘gdb.Frame’ objects can be compared for equality with the ‘==’
operator, like:

     (gdb) python print gdb.newest_frame() == gdb.selected_frame ()
     True

   The following frame-related functions are available in the ‘gdb’
module:

 -- Function: gdb.selected_frame ()
     Return the selected frame object.  (*note Selecting a Frame:
     Selection.).

 -- Function: gdb.newest_frame ()
     Return the newest frame object for the selected thread.

 -- Function: gdb.frame_stop_reason_string (reason)
     Return a string explaining the reason why GDB stopped unwinding
     frames, as expressed by the given REASON code (an integer, see the
     ‘unwind_stop_reason’ method further down in this section).

 -- Function: gdb.invalidate_cached_frames
     GDB internally keeps a cache of the frames that have been unwound.
     This function invalidates this cache.

     This function should not generally be called by ordinary Python
     code.  It is documented for the sake of completeness.

   A ‘gdb.Frame’ object has the following methods:

 -- Function: Frame.is_valid ()
     Returns true if the ‘gdb.Frame’ object is valid, false if not.  A
     frame object can become invalid if the frame it refers to doesn't
     exist anymore in the inferior.  All ‘gdb.Frame’ methods will throw
     an exception if it is invalid at the time the method is called.

 -- Function: Frame.name ()
     Returns the function name of the frame, or ‘None’ if it can't be
     obtained.

 -- Function: Frame.architecture ()
     Returns the ‘gdb.Architecture’ object corresponding to the frame's
     architecture.  *Note Architectures In Python::.

 -- Function: Frame.type ()
     Returns the type of the frame.  The value can be one of:
     ‘gdb.NORMAL_FRAME’
          An ordinary stack frame.

     ‘gdb.DUMMY_FRAME’
          A fake stack frame that was created by GDB when performing an
          inferior function call.

     ‘gdb.INLINE_FRAME’
          A frame representing an inlined function.  The function was
          inlined into a ‘gdb.NORMAL_FRAME’ that is older than this one.

     ‘gdb.TAILCALL_FRAME’
          A frame representing a tail call.  *Note Tail Call Frames::.

     ‘gdb.SIGTRAMP_FRAME’
          A signal trampoline frame.  This is the frame created by the
          OS when it calls into a signal handler.

     ‘gdb.ARCH_FRAME’
          A fake stack frame representing a cross-architecture call.

     ‘gdb.SENTINEL_FRAME’
          This is like ‘gdb.NORMAL_FRAME’, but it is only used for the
          newest frame.

 -- Function: Frame.unwind_stop_reason ()
     Return an integer representing the reason why it's not possible to
     find more frames toward the outermost frame.  Use
     ‘gdb.frame_stop_reason_string’ to convert the value returned by
     this function to a string.  The value can be one of:

     ‘gdb.FRAME_UNWIND_NO_REASON’
          No particular reason (older frames should be available).

     ‘gdb.FRAME_UNWIND_NULL_ID’
          The previous frame's analyzer returns an invalid result.  This
          is no longer used by GDB, and is kept only for backward
          compatibility.

     ‘gdb.FRAME_UNWIND_OUTERMOST’
          This frame is the outermost.

     ‘gdb.FRAME_UNWIND_UNAVAILABLE’
          Cannot unwind further, because that would require knowing the
          values of registers or memory that have not been collected.

     ‘gdb.FRAME_UNWIND_INNER_ID’
          This frame ID looks like it ought to belong to a NEXT frame,
          but we got it for a PREV frame.  Normally, this is a sign of
          unwinder failure.  It could also indicate stack corruption.

     ‘gdb.FRAME_UNWIND_SAME_ID’
          This frame has the same ID as the previous one.  That means
          that unwinding further would almost certainly give us another
          frame with exactly the same ID, so break the chain.  Normally,
          this is a sign of unwinder failure.  It could also indicate
          stack corruption.

     ‘gdb.FRAME_UNWIND_NO_SAVED_PC’
          The frame unwinder did not find any saved PC, but we needed
          one to unwind further.

     ‘gdb.FRAME_UNWIND_MEMORY_ERROR’
          The frame unwinder caused an error while trying to access
          memory.

     ‘gdb.FRAME_UNWIND_FIRST_ERROR’
          Any stop reason greater or equal to this value indicates some
          kind of error.  This special value facilitates writing code
          that tests for errors in unwinding in a way that will work
          correctly even if the list of the other values is modified in
          future GDB versions.  Using it, you could write:
               reason = gdb.selected_frame().unwind_stop_reason ()
               reason_str =  gdb.frame_stop_reason_string (reason)
               if reason >=  gdb.FRAME_UNWIND_FIRST_ERROR:
                   print ("An error occurred: %s" % reason_str)

 -- Function: Frame.pc ()
     Returns the frame's resume address.

 -- Function: Frame.block ()
     Return the frame's code block.  *Note Blocks In Python::.  If the
     frame does not have a block - for example, if there is no debugging
     information for the code in question - then this will throw an
     exception.

 -- Function: Frame.function ()
     Return the symbol for the function corresponding to this frame.
     *Note Symbols In Python::.

 -- Function: Frame.older ()
     Return the frame that called this frame.  If this is the oldest
     frame, return ‘None’.

 -- Function: Frame.newer ()
     Return the frame called by this frame.  If this is the newest
     frame, return ‘None’.

 -- Function: Frame.find_sal ()
     Return the frame's symtab and line object.  *Note Symbol Tables In
     Python::.

 -- Function: Frame.read_register (register)
     Return the value of REGISTER in this frame.  Returns a ‘Gdb.Value’
     object.  Throws an exception if REGISTER does not exist.  The
     REGISTER argument must be one of the following:
       1. A string that is the name of a valid register (e.g., ‘'sp'’ or
          ‘'rax'’).
       2. A ‘gdb.RegisterDescriptor’ object (*note Registers In
          Python::).
       3. A GDB internal, platform specific number.  Using these numbers
          is supported for historic reasons, but is not recommended as
          future changes to GDB could change the mapping between numbers
          and the registers they represent, breaking any Python code
          that uses the platform-specific numbers.  The numbers are
          usually found in the corresponding ‘PLATFORM-tdep.h’ file in
          the GDB source tree.
     Using a string to access registers will be slightly slower than the
     other two methods as GDB must look up the mapping between name and
     internal register number.  If performance is critical consider
     looking up and caching a ‘gdb.RegisterDescriptor’ object.

 -- Function: Frame.read_var (variable [, block])
     Return the value of VARIABLE in this frame.  If the optional
     argument BLOCK is provided, search for the variable from that
     block; otherwise start at the frame's current block (which is
     determined by the frame's current program counter).  The VARIABLE
     argument must be a string or a ‘gdb.Symbol’ object; BLOCK must be a
     ‘gdb.Block’ object.

 -- Function: Frame.select ()
     Set this frame to be the selected frame.  *Note Examining the
     Stack: Stack.

 -- Function: Frame.static_link ()
     In some languages (e.g., Ada, but also a GNU C extension), a nested
     function can access the variables in the outer scope.  This is done
     via a "static link", which is a reference from the nested frame to
     the appropriate outer frame.

     This method returns this frame's static link frame, if one exists.
     If there is no static link, this method returns ‘None’.

 -- Function: Frame.level ()
     Return an integer, the stack frame level for this frame.  *Note
     Stack Frames: Frames.

 -- Function: Frame.language ()
     Return a string, the source language for this frame.


File: gdb.info,  Node: Blocks In Python,  Next: Symbols In Python,  Prev: Frames In Python,  Up: Python API

23.3.2.29 Accessing blocks from Python
......................................

In GDB, symbols are stored in blocks.  A block corresponds roughly to a
scope in the source code.  Blocks are organized hierarchically, and are
represented individually in Python as a ‘gdb.Block’.  Blocks rely on
debugging information being available.

   A frame has a block.  Please see *note Frames In Python::, for a more
in-depth discussion of frames.

   The outermost block is known as the “global block”.  The global block
typically holds public global variables and functions.

   The block nested just inside the global block is the “static block”.
The static block typically holds file-scoped variables and functions.

   GDB provides a method to get a block's superblock, but there is
currently no way to examine the sub-blocks of a block, or to iterate
over all the blocks in a symbol table (*note Symbol Tables In Python::).

   Here is a short example that should help explain blocks:

     /* This is in the global block.  */
     int global;

     /* This is in the static block.  */
     static int file_scope;

     /* 'function' is in the global block, and 'argument' is
        in a block nested inside of 'function'.  */
     int function (int argument)
     {
       /* 'local' is in a block inside 'function'.  It may or may
          not be in the same block as 'argument'.  */
       int local;

       {
          /* 'inner' is in a block whose superblock is the one holding
             'local'.  */
          int inner;

          /* If this call is expanded by the compiler, you may see
             a nested block here whose function is 'inline_function'
             and whose superblock is the one holding 'inner'.  */
          inline_function ();
       }
     }

   A ‘gdb.Block’ is iterable.  The iterator returns the symbols (*note
Symbols In Python::) local to the block.  Python programs should not
assume that a specific block object will always contain a given symbol,
since changes in GDB features and infrastructure may cause symbols move
across blocks in a symbol table.  You can also use Python's “dictionary
syntax” to access variables in this block, e.g.:

     symbol = some_block['variable']  # symbol is of type gdb.Symbol

   The following block-related functions are available in the ‘gdb’
module:

 -- Function: gdb.block_for_pc (pc)
     Return the innermost ‘gdb.Block’ containing the given PC value.  If
     the block cannot be found for the PC value specified, the function
     will return ‘None’.  This is identical to
     ‘gdb.current_progspace().block_for_pc(pc)’ and is included for
     historical compatibility.

   A ‘gdb.Block’ object has the following methods:

 -- Function: Block.is_valid ()
     Returns ‘True’ if the ‘gdb.Block’ object is valid, ‘False’ if not.
     A block object can become invalid if the block it refers to doesn't
     exist anymore in the inferior.  All other ‘gdb.Block’ methods will
     throw an exception if it is invalid at the time the method is
     called.  The block's validity is also checked during iteration over
     symbols of the block.

   A ‘gdb.Block’ object has the following attributes:

 -- Variable: Block.start
     The start address of the block.  This attribute is not writable.

 -- Variable: Block.end
     One past the last address that appears in the block.  This
     attribute is not writable.

 -- Variable: Block.function
     The name of the block represented as a ‘gdb.Symbol’.  If the block
     is not named, then this attribute holds ‘None’.  This attribute is
     not writable.

     For ordinary function blocks, the superblock is the static block.
     However, you should note that it is possible for a function block
     to have a superblock that is not the static block - for instance
     this happens for an inlined function.

 -- Variable: Block.superblock
     The block containing this block.  If this parent block does not
     exist, this attribute holds ‘None’.  This attribute is not
     writable.

 -- Variable: Block.subblocks
     A list of blocks nested in this block.  If there are no blocks
     nested, this attribute holds an empty list.  This attribute is not
     writable.

 -- Variable: Block.global_block
     The global block associated with this block.  This attribute is not
     writable.

 -- Variable: Block.static_block
     The static block associated with this block.  This attribute is not
     writable.

 -- Variable: Block.is_global
     ‘True’ if the ‘gdb.Block’ object is a global block, ‘False’ if not.
     This attribute is not writable.

 -- Variable: Block.is_static
     ‘True’ if the ‘gdb.Block’ object is a static block, ‘False’ if not.
     This attribute is not writable.


File: gdb.info,  Node: Symbols In Python,  Next: Symbol Tables In Python,  Prev: Blocks In Python,  Up: Python API

23.3.2.30 Python representation of Symbols
..........................................

GDB represents every variable, function and type as an entry in a symbol
table.  *Note Examining the Symbol Table: Symbols.  Similarly, Python
represents these symbols in GDB with the ‘gdb.Symbol’ object.

   The following symbol-related functions are available in the ‘gdb’
module:

 -- Function: gdb.lookup_symbol (name [, block [, domain]])
     This function searches for a symbol by name.  The search scope can
     be restricted to the parameters defined in the optional domain and
     block arguments.

     NAME is the name of the symbol.  It must be a string.  The optional
     BLOCK argument restricts the search to symbols visible in that
     BLOCK.  The BLOCK argument must be a ‘gdb.Block’ object.  If
     omitted, the block for the current frame is used.  The optional
     DOMAIN argument restricts the search to the domain type.  The
     DOMAIN argument must be a domain constant defined in the ‘gdb’
     module and described later in this chapter.

     The result is a tuple of two elements.  The first element is a
     ‘gdb.Symbol’ object or ‘None’ if the symbol is not found.  If the
     symbol is found, the second element is ‘True’ if the symbol is a
     field of a method's object (e.g., ‘this’ in C++), otherwise it is
     ‘False’.  If the symbol is not found, the second element is
     ‘False’.

 -- Function: gdb.lookup_global_symbol (name [, domain])
     This function searches for a global symbol by name.  The search
     scope can be restricted to by the domain argument.

     NAME is the name of the symbol.  It must be a string.  The optional
     DOMAIN argument restricts the search to the domain type.  The
     DOMAIN argument must be a domain constant defined in the ‘gdb’
     module and described later in this chapter.

     The result is a ‘gdb.Symbol’ object or ‘None’ if the symbol is not
     found.

 -- Function: gdb.lookup_static_symbol (name [, domain])
     This function searches for a global symbol with static linkage by
     name.  The search scope can be restricted to by the domain
     argument.

     NAME is the name of the symbol.  It must be a string.  The optional
     DOMAIN argument restricts the search to the domain type.  The
     DOMAIN argument must be a domain constant defined in the ‘gdb’
     module and described later in this chapter.

     The result is a ‘gdb.Symbol’ object or ‘None’ if the symbol is not
     found.

     Note that this function will not find function-scoped static
     variables.  To look up such variables, iterate over the variables
     of the function's ‘gdb.Block’ and check that ‘block.addr_class’ is
     ‘gdb.SYMBOL_LOC_STATIC’.

     There can be multiple global symbols with static linkage with the
     same name.  This function will only return the first matching
     symbol that it finds.  Which symbol is found depends on where GDB
     is currently stopped, as GDB will first search for matching symbols
     in the current object file, and then search all other object files.
     If the application is not yet running then GDB will search all
     object files in the order they appear in the debug information.

 -- Function: gdb.lookup_static_symbols (name [, domain])
     Similar to ‘gdb.lookup_static_symbol’, this function searches for
     global symbols with static linkage by name, and optionally
     restricted by the domain argument.  However, this function returns
     a list of all matching symbols found, not just the first one.

     NAME is the name of the symbol.  It must be a string.  The optional
     DOMAIN argument restricts the search to the domain type.  The
     DOMAIN argument must be a domain constant defined in the ‘gdb’
     module and described later in this chapter.

     The result is a list of ‘gdb.Symbol’ objects which could be empty
     if no matching symbols were found.

     Note that this function will not find function-scoped static
     variables.  To look up such variables, iterate over the variables
     of the function's ‘gdb.Block’ and check that ‘block.addr_class’ is
     ‘gdb.SYMBOL_LOC_STATIC’.

   A ‘gdb.Symbol’ object has the following attributes:

 -- Variable: Symbol.type
     The type of the symbol or ‘None’ if no type is recorded.  This
     attribute is represented as a ‘gdb.Type’ object.  *Note Types In
     Python::.  This attribute is not writable.

 -- Variable: Symbol.symtab
     The symbol table in which the symbol appears.  This attribute is
     represented as a ‘gdb.Symtab’ object.  *Note Symbol Tables In
     Python::.  This attribute is not writable.

 -- Variable: Symbol.line
     The line number in the source code at which the symbol was defined.
     This is an integer.

 -- Variable: Symbol.name
     The name of the symbol as a string.  This attribute is not
     writable.

 -- Variable: Symbol.linkage_name
     The name of the symbol, as used by the linker (i.e., may be
     mangled).  This attribute is not writable.

 -- Variable: Symbol.print_name
     The name of the symbol in a form suitable for output.  This is
     either ‘name’ or ‘linkage_name’, depending on whether the user
     asked GDB to display demangled or mangled names.

 -- Variable: Symbol.addr_class
     The address class of the symbol.  This classifies how to find the
     value of a symbol.  Each address class is a constant defined in the
     ‘gdb’ module and described later in this chapter.

 -- Variable: Symbol.domain
     The domain of the symbol.  Each domain is a constant defined in the
     ‘gdb’ module and described later in this chapter.

 -- Variable: Symbol.needs_frame
     This is ‘True’ if evaluating this symbol's value requires a frame
     (*note Frames In Python::) and ‘False’ otherwise.  Typically, local
     variables will require a frame, but other symbols will not.

 -- Variable: Symbol.is_argument
     ‘True’ if the symbol is an argument of a function.

 -- Variable: Symbol.is_artificial
     ‘True’ if the symbol is artificial.  An artificial symbol is one
     that is introduced by the compiler.

 -- Variable: Symbol.is_constant
     ‘True’ if the symbol is a constant.

 -- Variable: Symbol.is_function
     ‘True’ if the symbol is a function or a method.

 -- Variable: Symbol.is_variable
     ‘True’ if the symbol is a variable, as opposed to something like a
     function or type.  Note that this also returns ‘False’ for
     arguments.

   A ‘gdb.Symbol’ object has the following methods:

 -- Function: Symbol.is_valid ()
     Returns ‘True’ if the ‘gdb.Symbol’ object is valid, ‘False’ if not.
     A ‘gdb.Symbol’ object can become invalid if the symbol it refers to
     does not exist in GDB any longer.  All other ‘gdb.Symbol’ methods
     will throw an exception if it is invalid at the time the method is
     called.

 -- Function: Symbol.value ([frame])
     Compute the value of the symbol, as a ‘gdb.Value’.  For functions,
     this computes the address of the function, cast to the appropriate
     type.  If the symbol requires a frame in order to compute its
     value, then FRAME must be given.  If FRAME is not given, or if
     FRAME is invalid, then this method will throw an exception.

   The available domain categories in ‘gdb.Symbol’ are represented as
constants in the ‘gdb’ module:

‘gdb.SYMBOL_UNDEF_DOMAIN’
     This is used when a domain has not been discovered or none of the
     following domains apply.  This usually indicates an error either in
     the symbol information or in GDB's handling of symbols.

‘gdb.SYMBOL_VAR_DOMAIN’
     This domain contains variables.

‘gdb.SYMBOL_FUNCTION_DOMAIN’
     This domain contains functions.

‘gdb.SYMBOL_TYPE_DOMAIN’
     This domain contains types.  In a C-like language, types using a
     tag (the name appearing after a ‘struct’, ‘union’, or ‘enum’
     keyword) will not appear here; in other languages, all types are in
     this domain.

‘gdb.SYMBOL_STRUCT_DOMAIN’
     This domain holds struct, union and enum tag names.  This domain is
     only used for C-like languages.  For example, in this code:
          struct type_one { int x; };
          typedef struct type_one type_two;
     Here ‘type_one’ will be in ‘SYMBOL_STRUCT_DOMAIN’, but ‘type_two’
     will be in ‘SYMBOL_TYPE_DOMAIN’.

‘gdb.SYMBOL_LABEL_DOMAIN’
     This domain contains names of labels (for gotos).

‘gdb.SYMBOL_MODULE_DOMAIN’
     This domain contains names of Fortran module types.

‘gdb.SYMBOL_COMMON_BLOCK_DOMAIN’
     This domain contains names of Fortran common blocks.

   When searching for a symbol, the desired domain constant can be
passed verbatim to the lookup function.  For example:
     symbol = gdb.lookup_symbol ("name", domain=gdb.SYMBOL_VAR_DOMAIN)

   For more complex searches, there is a corresponding set of constants,
each named after one of the preceding constants, but with the ‘SEARCH’
prefix replacing the ‘SYMBOL’ prefix; for example,
‘SEARCH_LABEL_DOMAIN’.  These may be or'd together to form a search
constant, e.g.:
     symbol = gdb.lookup_symbol ("name",
                                 domain=gdb.SEARCH_VAR_DOMAIN | gdb.SEARCH_TYPE_DOMAIN)

   The available address class categories in ‘gdb.Symbol’ are
represented as constants in the ‘gdb’ module:

‘gdb.SYMBOL_LOC_UNDEF’
     If this is returned by address class, it indicates an error either
     in the symbol information or in GDB's handling of symbols.

‘gdb.SYMBOL_LOC_CONST’
     Value is constant int.

‘gdb.SYMBOL_LOC_STATIC’
     Value is at a fixed address.

‘gdb.SYMBOL_LOC_REGISTER’
     Value is in a register.

‘gdb.SYMBOL_LOC_ARG’
     Value is an argument.  This value is at the offset stored within
     the symbol inside the frame's argument list.

‘gdb.SYMBOL_LOC_REF_ARG’
     Value address is stored in the frame's argument list.  Just like
     ‘LOC_ARG’ except that the value's address is stored at the offset,
     not the value itself.

‘gdb.SYMBOL_LOC_REGPARM_ADDR’
     Value is a specified register.  Just like ‘LOC_REGISTER’ except the
     register holds the address of the argument instead of the argument
     itself.

‘gdb.SYMBOL_LOC_LOCAL’
     Value is a local variable.

‘gdb.SYMBOL_LOC_TYPEDEF’
     Value not used.  Symbols in the domain ‘SYMBOL_STRUCT_DOMAIN’ all
     have this class.

‘gdb.SYMBOL_LOC_LABEL’
     Value is a label.

‘gdb.SYMBOL_LOC_BLOCK’
     Value is a block.

‘gdb.SYMBOL_LOC_CONST_BYTES’
     Value is a byte-sequence.

‘gdb.SYMBOL_LOC_UNRESOLVED’
     Value is at a fixed address, but the address of the variable has to
     be determined from the minimal symbol table whenever the variable
     is referenced.

‘gdb.SYMBOL_LOC_OPTIMIZED_OUT’
     The value does not actually exist in the program.

‘gdb.SYMBOL_LOC_COMPUTED’
     The value's address is a computed location.

‘gdb.SYMBOL_LOC_COMMON_BLOCK’
     The value's address is a symbol.  This is only used for Fortran
     common blocks.


File: gdb.info,  Node: Symbol Tables In Python,  Next: Line Tables In Python,  Prev: Symbols In Python,  Up: Python API

23.3.2.31 Symbol table representation in Python
...............................................

Access to symbol table data maintained by GDB on the inferior is exposed
to Python via two objects: ‘gdb.Symtab_and_line’ and ‘gdb.Symtab’.
Symbol table and line data for a frame is returned from the ‘find_sal’
method in ‘gdb.Frame’ object.  *Note Frames In Python::.

   For more information on GDB's symbol table management, see *note
Examining the Symbol Table: Symbols, for more information.

   A ‘gdb.Symtab_and_line’ object has the following attributes:

 -- Variable: Symtab_and_line.symtab
     The symbol table object (‘gdb.Symtab’) for this frame.  This
     attribute is not writable.

 -- Variable: Symtab_and_line.pc
     Indicates the start of the address range occupied by code for the
     current source line.  This attribute is not writable.

 -- Variable: Symtab_and_line.last
     Indicates the end of the address range occupied by code for the
     current source line.  This attribute is not writable.

 -- Variable: Symtab_and_line.line
     Indicates the current line number for this object.  This attribute
     is not writable.

   A ‘gdb.Symtab_and_line’ object has the following methods:

 -- Function: Symtab_and_line.is_valid ()
     Returns ‘True’ if the ‘gdb.Symtab_and_line’ object is valid,
     ‘False’ if not.  A ‘gdb.Symtab_and_line’ object can become invalid
     if the Symbol table and line object it refers to does not exist in
     GDB any longer.  All other ‘gdb.Symtab_and_line’ methods will throw
     an exception if it is invalid at the time the method is called.

   A ‘gdb.Symtab’ object has the following attributes:

 -- Variable: Symtab.filename
     The symbol table's source filename.  This attribute is not
     writable.

 -- Variable: Symtab.objfile
     The symbol table's backing object file.  *Note Objfiles In
     Python::.  This attribute is not writable.

 -- Variable: Symtab.producer
     The name and possibly version number of the program that compiled
     the code in the symbol table.  The contents of this string is up to
     the compiler.  If no producer information is available then ‘None’
     is returned.  This attribute is not writable.

   A ‘gdb.Symtab’ object has the following methods:

 -- Function: Symtab.is_valid ()
     Returns ‘True’ if the ‘gdb.Symtab’ object is valid, ‘False’ if not.
     A ‘gdb.Symtab’ object can become invalid if the symbol table it
     refers to does not exist in GDB any longer.  All other ‘gdb.Symtab’
     methods will throw an exception if it is invalid at the time the
     method is called.

 -- Function: Symtab.fullname ()
     Return the symbol table's source absolute file name.

 -- Function: Symtab.global_block ()
     Return the global block of the underlying symbol table.  *Note
     Blocks In Python::.

 -- Function: Symtab.static_block ()
     Return the static block of the underlying symbol table.  *Note
     Blocks In Python::.

 -- Function: Symtab.linetable ()
     Return the line table associated with the symbol table.  *Note Line
     Tables In Python::.


File: gdb.info,  Node: Line Tables In Python,  Next: Breakpoints In Python,  Prev: Symbol Tables In Python,  Up: Python API

23.3.2.32 Manipulating line tables using Python
...............................................

Python code can request and inspect line table information from a symbol
table that is loaded in GDB.  A line table is a mapping of source lines
to their executable locations in memory.  To acquire the line table
information for a particular symbol table, use the ‘linetable’ function
(*note Symbol Tables In Python::).

   A ‘gdb.LineTable’ is iterable.  The iterator returns ‘LineTableEntry’
objects that correspond to the source line and address for each line
table entry.  ‘LineTableEntry’ objects have the following attributes:

 -- Variable: LineTableEntry.line
     The source line number for this line table entry.  This number
     corresponds to the actual line of source.  This attribute is not
     writable.

 -- Variable: LineTableEntry.pc
     The address that is associated with the line table entry where the
     executable code for that source line resides in memory.  This
     attribute is not writable.

   As there can be multiple addresses for a single source line, you may
receive multiple ‘LineTableEntry’ objects with matching ‘line’
attributes, but with different ‘pc’ attributes.  The iterator is sorted
in ascending ‘pc’ order.  Here is a small example illustrating iterating
over a line table.

     symtab = gdb.selected_frame().find_sal().symtab
     linetable = symtab.linetable()
     for line in linetable:
        print ("Line: "+str(line.line)+" Address: "+hex(line.pc))

   This will have the following output:

     Line: 33 Address: 0x4005c8L
     Line: 37 Address: 0x4005caL
     Line: 39 Address: 0x4005d2L
     Line: 40 Address: 0x4005f8L
     Line: 42 Address: 0x4005ffL
     Line: 44 Address: 0x400608L
     Line: 42 Address: 0x40060cL
     Line: 45 Address: 0x400615L

   In addition to being able to iterate over a ‘LineTable’, it also has
the following direct access methods:

 -- Function: LineTable.line (line)
     Return a Python ‘Tuple’ of ‘LineTableEntry’ objects for any entries
     in the line table for the given LINE, which specifies the source
     code line.  If there are no entries for that source code LINE, the
     Python ‘None’ is returned.

 -- Function: LineTable.has_line (line)
     Return a Python ‘Boolean’ indicating whether there is an entry in
     the line table for this source line.  Return ‘True’ if an entry is
     found, or ‘False’ if not.

 -- Function: LineTable.source_lines ()
     Return a Python ‘List’ of the source line numbers in the symbol
     table.  Only lines with executable code locations are returned.
     The contents of the ‘List’ will just be the source line entries
     represented as Python ‘Long’ values.


File: gdb.info,  Node: Breakpoints In Python,  Next: Finish Breakpoints in Python,  Prev: Line Tables In Python,  Up: Python API

23.3.2.33 Manipulating breakpoints using Python
...............................................

Python code can manipulate breakpoints via the ‘gdb.Breakpoint’ class.

   A breakpoint can be created using one of the two forms of the
‘gdb.Breakpoint’ constructor.  The first one accepts a string like one
would pass to the ‘break’ (*note Setting Breakpoints: Set Breaks.) and
‘watch’ (*note Setting Watchpoints: Set Watchpoints.) commands, and can
be used to create both breakpoints and watchpoints.  The second accepts
separate Python arguments similar to *note Explicit Locations::, and can
only be used to create breakpoints.

 -- Function: Breakpoint.__init__ (spec [, type ][, wp_class ][,
          internal ][, temporary ][, qualified ])
     Create a new breakpoint according to SPEC, which is a string naming
     the location of a breakpoint, or an expression that defines a
     watchpoint.  The string should describe a location in a format
     recognized by the ‘break’ command (*note Setting Breakpoints: Set
     Breaks.) or, in the case of a watchpoint, by the ‘watch’ command
     (*note Setting Watchpoints: Set Watchpoints.).

     The optional TYPE argument specifies the type of the breakpoint to
     create, as defined below.

     The optional WP_CLASS argument defines the class of watchpoint to
     create, if TYPE is ‘gdb.BP_WATCHPOINT’.  If WP_CLASS is omitted, it
     defaults to ‘gdb.WP_WRITE’.

     The optional INTERNAL argument allows the breakpoint to become
     invisible to the user.  The breakpoint will neither be reported
     when created, nor will it be listed in the output from ‘info
     breakpoints’ (but will be listed with the ‘maint info breakpoints’
     command).

     The optional TEMPORARY argument makes the breakpoint a temporary
     breakpoint.  Temporary breakpoints are deleted after they have been
     hit.  Any further access to the Python breakpoint after it has been
     hit will result in a runtime error (as that breakpoint has now been
     automatically deleted).

     The optional QUALIFIED argument is a boolean that allows
     interpreting the function passed in ‘spec’ as a fully-qualified
     name.  It is equivalent to ‘break’'s ‘-qualified’ flag (*note
     Linespec Locations:: and *note Explicit Locations::).

 -- Function: Breakpoint.__init__ ([ source ][, function ][, label ][,
          line ], ][ internal ][, temporary ][, qualified ])
     This second form of creating a new breakpoint specifies the
     explicit location (*note Explicit Locations::) using keywords.  The
     new breakpoint will be created in the specified source file SOURCE,
     at the specified FUNCTION, LABEL and LINE.

     INTERNAL, TEMPORARY and QUALIFIED have the same usage as explained
     previously.

   The available types are represented by constants defined in the ‘gdb’
module:

‘gdb.BP_BREAKPOINT’
     Normal code breakpoint.

‘gdb.BP_HARDWARE_BREAKPOINT’
     Hardware assisted code breakpoint.

‘gdb.BP_WATCHPOINT’
     Watchpoint breakpoint.

‘gdb.BP_HARDWARE_WATCHPOINT’
     Hardware assisted watchpoint.

‘gdb.BP_READ_WATCHPOINT’
     Hardware assisted read watchpoint.

‘gdb.BP_ACCESS_WATCHPOINT’
     Hardware assisted access watchpoint.

‘gdb.BP_CATCHPOINT’
     Catchpoint.  Currently, this type can't be used when creating
     ‘gdb.Breakpoint’ objects, but will be present in ‘gdb.Breakpoint’
     objects reported from ‘gdb.BreakpointEvent’s (*note Events In
     Python::).

   The available watchpoint types are represented by constants defined
in the ‘gdb’ module:

‘gdb.WP_READ’
     Read only watchpoint.

‘gdb.WP_WRITE’
     Write only watchpoint.

‘gdb.WP_ACCESS’
     Read/Write watchpoint.

 -- Function: Breakpoint.stop (self)
     The ‘gdb.Breakpoint’ class can be sub-classed and, in particular,
     you may choose to implement the ‘stop’ method.  If this method is
     defined in a sub-class of ‘gdb.Breakpoint’, it will be called when
     the inferior reaches any location of a breakpoint which
     instantiates that sub-class.  If the method returns ‘True’, the
     inferior will be stopped at the location of the breakpoint,
     otherwise the inferior will continue.

     If there are multiple breakpoints at the same location with a
     ‘stop’ method, each one will be called regardless of the return
     status of the previous.  This ensures that all ‘stop’ methods have
     a chance to execute at that location.  In this scenario if one of
     the methods returns ‘True’ but the others return ‘False’, the
     inferior will still be stopped.

     You should not alter the execution state of the inferior (i.e.,
     step, next, etc.), alter the current frame context (i.e., change
     the current active frame), or alter, add or delete any breakpoint.
     As a general rule, you should not alter any data within GDB or the
     inferior at this time.

     Example ‘stop’ implementation:

          class MyBreakpoint (gdb.Breakpoint):
                def stop (self):
                  inf_val = gdb.parse_and_eval("foo")
                  if inf_val == 3:
                    return True
                  return False

 -- Function: Breakpoint.is_valid ()
     Return ‘True’ if this ‘Breakpoint’ object is valid, ‘False’
     otherwise.  A ‘Breakpoint’ object can become invalid if the user
     deletes the breakpoint.  In this case, the object still exists, but
     the underlying breakpoint does not.  In the cases of watchpoint
     scope, the watchpoint remains valid even if execution of the
     inferior leaves the scope of that watchpoint.

 -- Function: Breakpoint.delete ()
     Permanently deletes the GDB breakpoint.  This also invalidates the
     Python ‘Breakpoint’ object.  Any further access to this object's
     attributes or methods will raise an error.

 -- Variable: Breakpoint.enabled
     This attribute is ‘True’ if the breakpoint is enabled, and ‘False’
     otherwise.  This attribute is writable.  You can use it to enable
     or disable the breakpoint.

 -- Variable: Breakpoint.silent
     This attribute is ‘True’ if the breakpoint is silent, and ‘False’
     otherwise.  This attribute is writable.

     Note that a breakpoint can also be silent if it has commands and
     the first command is ‘silent’.  This is not reported by the
     ‘silent’ attribute.

 -- Variable: Breakpoint.pending
     This attribute is ‘True’ if the breakpoint is pending, and ‘False’
     otherwise.  *Note Set Breaks::.  This attribute is read-only.

 -- Variable: Breakpoint.thread
     If the breakpoint is thread-specific (*note Thread-Specific
     Breakpoints::), this attribute holds the thread's global id.  If
     the breakpoint is not thread-specific, this attribute is ‘None’.
     This attribute is writable.

     Only one of ‘Breakpoint.thread’ or ‘Breakpoint.inferior’ can be set
     to a valid id at any time, that is, a breakpoint can be thread
     specific, or inferior specific, but not both.

 -- Variable: Breakpoint.inferior
     If the breakpoint is inferior-specific (*note Inferior-Specific
     Breakpoints::), this attribute holds the inferior's id.  If the
     breakpoint is not inferior-specific, this attribute is ‘None’.

     This attribute can be written for breakpoints of type
     ‘gdb.BP_BREAKPOINT’ and ‘gdb.BP_HARDWARE_BREAKPOINT’.

 -- Variable: Breakpoint.task
     If the breakpoint is Ada task-specific, this attribute holds the
     Ada task id.  If the breakpoint is not task-specific (or the
     underlying language is not Ada), this attribute is ‘None’.  This
     attribute is writable.

 -- Variable: Breakpoint.ignore_count
     This attribute holds the ignore count for the breakpoint, an
     integer.  This attribute is writable.

 -- Variable: Breakpoint.number
     This attribute holds the breakpoint's number -- the identifier used
     by the user to manipulate the breakpoint.  This attribute is not
     writable.

 -- Variable: Breakpoint.type
     This attribute holds the breakpoint's type -- the identifier used
     to determine the actual breakpoint type or use-case.  This
     attribute is not writable.

 -- Variable: Breakpoint.visible
     This attribute tells whether the breakpoint is visible to the user
     when set, or when the ‘info breakpoints’ command is run.  This
     attribute is not writable.

 -- Variable: Breakpoint.temporary
     This attribute indicates whether the breakpoint was created as a
     temporary breakpoint.  Temporary breakpoints are automatically
     deleted after that breakpoint has been hit.  Access to this
     attribute, and all other attributes and functions other than the
     ‘is_valid’ function, will result in an error after the breakpoint
     has been hit (as it has been automatically deleted).  This
     attribute is not writable.

 -- Variable: Breakpoint.hit_count
     This attribute holds the hit count for the breakpoint, an integer.
     This attribute is writable, but currently it can only be set to
     zero.

 -- Variable: Breakpoint.location
     This attribute holds the location of the breakpoint, as specified
     by the user.  It is a string.  If the breakpoint does not have a
     location (that is, it is a watchpoint) the attribute's value is
     ‘None’.  This attribute is not writable.

 -- Variable: Breakpoint.locations
     Get the most current list of breakpoint locations that are inserted
     for this breakpoint, with elements of type ‘gdb.BreakpointLocation’
     (described below).  This functionality matches that of the ‘info
     breakpoint’ command (*note Set Breaks::), in that it only retrieves
     the most current list of locations, thus the list itself when
     returned is not updated behind the scenes.  This attribute is not
     writable.

 -- Variable: Breakpoint.expression
     This attribute holds a breakpoint expression, as specified by the
     user.  It is a string.  If the breakpoint does not have an
     expression (the breakpoint is not a watchpoint) the attribute's
     value is ‘None’.  This attribute is not writable.

 -- Variable: Breakpoint.condition
     This attribute holds the condition of the breakpoint, as specified
     by the user.  It is a string.  If there is no condition, this
     attribute's value is ‘None’.  This attribute is writable.

 -- Variable: Breakpoint.commands
     This attribute holds the commands attached to the breakpoint.  If
     there are commands, this attribute's value is a string holding all
     the commands, separated by newlines.  If there are no commands,
     this attribute is ‘None’.  This attribute is writable.

Breakpoint Locations
--------------------

A breakpoint location is one of the actual places where a breakpoint has
been set, represented in the Python API by the ‘gdb.BreakpointLocation’
type.  This type is never instantiated by the user directly, but is
retrieved from ‘Breakpoint.locations’ which returns a list of breakpoint
locations where it is currently set.  Breakpoint locations can become
invalid if new symbol files are loaded or dynamically loaded libraries
are closed.  Accessing the attributes of an invalidated breakpoint
location will throw a ‘RuntimeError’ exception.  Access the
‘Breakpoint.locations’ attribute again to retrieve the new and valid
breakpoints location list.

 -- Variable: BreakpointLocation.source
     This attribute returns the source file path and line number where
     this location was set.  The type of the attribute is a tuple of
     STRING and LONG.  If the breakpoint location doesn't have a source
     location, it returns None, which is the case for watchpoints and
     catchpoints.  This will throw a ‘RuntimeError’ exception if the
     location has been invalidated.  This attribute is not writable.

 -- Variable: BreakpointLocation.address
     This attribute returns the address where this location was set.
     This attribute is of type long.  This will throw a ‘RuntimeError’
     exception if the location has been invalidated.  This attribute is
     not writable.

 -- Variable: BreakpointLocation.enabled
     This attribute holds the value for whether or not this location is
     enabled.  This attribute is writable (boolean).  This will throw a
     ‘RuntimeError’ exception if the location has been invalidated.

 -- Variable: BreakpointLocation.owner
     This attribute holds a reference to the ‘gdb.Breakpoint’ owner
     object, from which this ‘gdb.BreakpointLocation’ was retrieved
     from.  This will throw a ‘RuntimeError’ exception if the location
     has been invalidated.  This attribute is not writable.

 -- Variable: BreakpointLocation.function
     This attribute gets the name of the function where this location
     was set.  If no function could be found this attribute returns
     ‘None’.  This will throw a ‘RuntimeError’ exception if the location
     has been invalidated.  This attribute is not writable.

 -- Variable: BreakpointLocation.fullname
     This attribute gets the full name of where this location was set.
     If no full name could be found, this attribute returns ‘None’.
     This will throw a ‘RuntimeError’ exception if the location has been
     invalidated.  This attribute is not writable.

 -- Variable: BreakpointLocation.thread_groups
     This attribute gets the thread groups it was set in.  It returns a
     ‘List’ of the thread group ID's.  This will throw a ‘RuntimeError’
     exception if the location has been invalidated.  This attribute is
     not writable.


File: gdb.info,  Node: Finish Breakpoints in Python,  Next: Lazy Strings In Python,  Prev: Breakpoints In Python,  Up: Python API

23.3.2.34 Finish Breakpoints
............................

A finish breakpoint is a temporary breakpoint set at the return address
of a frame, based on the ‘finish’ command.  ‘gdb.FinishBreakpoint’
extends ‘gdb.Breakpoint’.  The underlying breakpoint will be disabled
and deleted when the execution will run out of the breakpoint scope
(i.e. ‘Breakpoint.stop’ or ‘FinishBreakpoint.out_of_scope’ triggered).
Finish breakpoints are thread specific and must be create with the right
thread selected.

 -- Function: FinishBreakpoint.__init__ ([frame] [, internal])
     Create a finish breakpoint at the return address of the ‘gdb.Frame’
     object FRAME.  If FRAME is not provided, this defaults to the
     newest frame.  The optional INTERNAL argument allows the breakpoint
     to become invisible to the user.  *Note Breakpoints In Python::,
     for further details about this argument.

 -- Function: FinishBreakpoint.out_of_scope (self)
     In some circumstances (e.g. ‘longjmp’, C++ exceptions, GDB ‘return’
     command, ...), a function may not properly terminate, and thus
     never hit the finish breakpoint.  When GDB notices such a
     situation, the ‘out_of_scope’ callback will be triggered.

     You may want to sub-class ‘gdb.FinishBreakpoint’ and override this
     method:

          class MyFinishBreakpoint (gdb.FinishBreakpoint)
              def stop (self):
                  print ("normal finish")
                  return True

              def out_of_scope ():
                  print ("abnormal finish")

 -- Variable: FinishBreakpoint.return_value
     When GDB is stopped at a finish breakpoint and the frame used to
     build the ‘gdb.FinishBreakpoint’ object had debug symbols, this
     attribute will contain a ‘gdb.Value’ object corresponding to the
     return value of the function.  The value will be ‘None’ if the
     function return type is ‘void’ or if the return value was not
     computable.  This attribute is not writable.


File: gdb.info,  Node: Lazy Strings In Python,  Next: Colors In Python,  Prev: Finish Breakpoints in Python,  Up: Python API

23.3.2.35 Python representation of lazy strings
...............................................

A “lazy string” is a string whose contents is not retrieved or encoded
until it is needed.

   A ‘gdb.LazyString’ is represented in GDB as an ‘address’ that points
to a region of memory, an ‘encoding’ that will be used to encode that
region of memory, and a ‘length’ to delimit the region of memory that
represents the string.  The difference between a ‘gdb.LazyString’ and a
string wrapped within a ‘gdb.Value’ is that a ‘gdb.LazyString’ will only
be retrieved and encoded during printing, while a ‘gdb.Value’ wrapping a
string is immediately retrieved and encoded on creation.

   A ‘gdb.LazyString’ can be created using the ‘gdb.Value.lazy_string’
method (*note Values From Inferior::).

   A ‘gdb.LazyString’ object has the following functions:

 -- Function: LazyString.value ()
     Convert the ‘gdb.LazyString’ to a ‘gdb.Value’.  This value will
     point to the string in memory, but will lose all the delayed
     retrieval, encoding and handling that GDB applies to a
     ‘gdb.LazyString’.

 -- Variable: LazyString.address
     This attribute holds the address of the string.  This attribute is
     not writable.

 -- Variable: LazyString.length
     This attribute holds the length of the string in characters.  If
     the length is -1, then the string will be fetched and encoded up to
     the first null of appropriate width.  This attribute is not
     writable.

 -- Variable: LazyString.encoding
     This attribute holds the encoding that will be applied to the
     string when the string is printed by GDB.  If the encoding is not
     set, or contains an empty string, then GDB will select the most
     appropriate encoding when the string is printed.  This attribute is
     not writable.

 -- Variable: LazyString.type
     This attribute holds the type that is represented by the lazy
     string's type.  For a lazy string this is a pointer or array type.
     To resolve this to the lazy string's character type, use the type's
     ‘target’ method.  *Note Types In Python::.  This attribute is not
     writable.


File: gdb.info,  Node: Colors In Python,  Next: Architectures In Python,  Prev: Lazy Strings In Python,  Up: Python API

23.3.2.36 Python representation of colors
.........................................

You can assign instance of ‘gdb.Color’ to the ‘value’ of a ‘Parameter’
instance created with ‘PARAM_COLOR’.

   ‘gdb.Color’ may refer to an index from a color palette or contain
components of a color from some color space.

 -- Function: Color.__init__ ([value [, color_space]])

     VALUE is ‘None’ (meaning the terminal's default color), an integer
     index of a color in palette, tuple with color components or a
     string.  String can be a hex RGB triplet in ‘#RRGGBB’ format or one
     of the following color names: ‘none’ (meaning the terminal's
     default color), ‘black’, ‘red’, ‘green’, ‘yellow’, ‘blue’,
     ‘magenta’, ‘cyan’, or ‘white’.

     COLOR_SPACE should be one of the ‘COLORSPACE_’ constants listed
     below.  This argument tells GDB which color space VALUE belongs.

 -- Variable: Color.is_none
     This attribute is boolean.  If its value is ‘True’ then color is
     terminal's default.

 -- Variable: Color.is_indexed
     This attribute is boolean.  If its value is ‘True’ then color is
     indexed, i.e.  belongs to some palette.

 -- Variable: Color.is_direct
     This attribute is boolean.  If its value is ‘True’ then this object
     describes direct colour in the sense of ISO/IEC 8613-6.

 -- Variable: Color.index
     This attribute exist if ‘is_indexed’ is ‘True’.  Its integer value
     is index of a color in a palette.

 -- Variable: Color.components
     This attribute exist if ‘is_direct’ is ‘True’.  Its value is tuple
     with integer components of a color.

 -- Function: Color.escape_sequence (is_foreground)
     Returns string to change terminal's color to this.

     If IS_FOREGROUND is ‘True’, then the returned sequence will change
     foreground color.  Otherwise, the returned sequence will change
     background color.

     If styling is currently disabled (*note ‘set style enabled’: Output
     Styling.), then this method will return an empty string.

   When color is initialized, its color space must be specified.  The
available color spaces are represented by constants defined in the ‘gdb’
module:

‘gdb.COLORSPACE_MONOCHROME’
     Palette with only terminal's default color.

‘gdb.COLORSPACE_ANSI_8COLOR’
     Palette with eight standard colors of ISO/IEC 6429 "black", "red",
     "green", etc.

‘gdb.COLORSPACE_AIXTERM_16COLOR’
     Palette with 16 colors.  First eight are standard colors of ISO/IEC
     6429 "black", "red", "green", etc.  Next eight are their bright
     version.

‘gdb.COLORSPACE_XTERM_256COLOR’
     Palette with 256 colors.  First 16 are from
     COLORSPACE_AIXTERM_16COLOR. Next 216 colors are 6x6x6 RGB cube.
     And last 24 colors form grayscale ramp.

‘gdb.COLORSPACE_RGB_24BIT’
     Direct 24-bit RGB colors.

   It is not possible to sub-class the ‘Color’ class.


File: gdb.info,  Node: Architectures In Python,  Next: Registers In Python,  Prev: Colors In Python,  Up: Python API

23.3.2.37 Python representation of architectures
................................................

GDB uses architecture specific parameters and artifacts in a number of
its various computations.  An architecture is represented by an instance
of the ‘gdb.Architecture’ class.

   A ‘gdb.Architecture’ class has the following methods:

 -- Function: Architecture.name ()
     Return the name (string value) of the architecture.

 -- Function: Architecture.disassemble (start_pc [, end_pc [, count]])
     Return a list of disassembled instructions starting from the memory
     address START_PC.  The optional arguments END_PC and COUNT
     determine the number of instructions in the returned list.  If both
     the optional arguments END_PC and COUNT are specified, then a list
     of at most COUNT disassembled instructions whose start address
     falls in the closed memory address interval from START_PC to END_PC
     are returned.  If END_PC is not specified, but COUNT is specified,
     then COUNT number of instructions starting from the address
     START_PC are returned.  If COUNT is not specified but END_PC is
     specified, then all instructions whose start address falls in the
     closed memory address interval from START_PC to END_PC are
     returned.  If neither END_PC nor COUNT are specified, then a single
     instruction at START_PC is returned.  For all of these cases, each
     element of the returned list is a Python ‘dict’ with the following
     string keys:

     ‘addr’
          The value corresponding to this key is a Python long integer
          capturing the memory address of the instruction.

     ‘asm’
          The value corresponding to this key is a string value which
          represents the instruction with assembly language mnemonics.
          The assembly language flavor used is the same as that
          specified by the current CLI variable ‘disassembly-flavor’.
          *Note Machine Code::.

     ‘length’
          The value corresponding to this key is the length (integer
          value) of the instruction in bytes.

 -- Function: Architecture.integer_type (size [, signed])
     This function looks up an integer type by its SIZE, and optionally
     whether or not it is signed.

     SIZE is the size, in bits, of the desired integer type.  Only
     certain sizes are currently supported: 0, 8, 16, 24, 32, 64, and
     128.

     If SIGNED is not specified, it defaults to ‘True’.  If SIGNED is
     ‘False’, the returned type will be unsigned.

     If the indicated type cannot be found, this function will throw a
     ‘ValueError’ exception.

 -- Function: Architecture.void_type ()
     This function returns a void type.

 -- Function: Architecture.registers ([ reggroup ])
     Return a ‘gdb.RegisterDescriptorIterator’ (*note Registers In
     Python::) for all of the registers in REGGROUP, a string that is
     the name of a register group.  If REGGROUP is omitted, or is the
     empty string, then the register group ‘all’ is assumed.

 -- Function: Architecture.register_groups ()
     Return a ‘gdb.RegisterGroupsIterator’ (*note Registers In Python::)
     for all of the register groups available for the
     ‘gdb.Architecture’.


File: gdb.info,  Node: Registers In Python,  Next: Connections In Python,  Prev: Architectures In Python,  Up: Python API

23.3.2.38 Registers In Python
.............................

Python code can request from a ‘gdb.Architecture’ information about the
set of registers available (*note ‘Architecture.registers’:
gdbpy_architecture_registers.).  The register information is returned as
a ‘gdb.RegisterDescriptorIterator’, which is an iterator that in turn
returns ‘gdb.RegisterDescriptor’ objects.

   A ‘gdb.RegisterDescriptor’ does not provide the value of a register
(*note ‘Frame.read_register’: gdbpy_frame_read_register. for reading a
register's value), instead the ‘RegisterDescriptor’ is a way to discover
which registers are available for a particular architecture.

   A ‘gdb.RegisterDescriptor’ has the following read-only properties:

 -- Variable: RegisterDescriptor.name
     The name of this register.

   It is also possible to lookup a register descriptor based on its name
using the following ‘gdb.RegisterDescriptorIterator’ function:

 -- Function: RegisterDescriptorIterator.find (name)
     Takes NAME as an argument, which must be a string, and returns a
     ‘gdb.RegisterDescriptor’ for the register with that name, or ‘None’
     if there is no register with that name.

   Python code can also request from a ‘gdb.Architecture’ information
about the set of register groups available on a given architecture
(*note ‘Architecture.register_groups’: gdbpy_architecture_reggroups.).

   Every register can be a member of zero or more register groups.  Some
register groups are used internally within GDB to control things like
which registers must be saved when calling into the program being
debugged (*note Calling Program Functions: Calling.).  Other register
groups exist to allow users to easily see related sets of registers in
commands like ‘info registers’ (*note ‘info registers REGGROUP’:
info_registers_reggroup.).

   The register groups information is returned as a
‘gdb.RegisterGroupsIterator’, which is an iterator that in turn returns
‘gdb.RegisterGroup’ objects.

   A ‘gdb.RegisterGroup’ object has the following read-only properties:

 -- Variable: RegisterGroup.name
     A string that is the name of this register group.


File: gdb.info,  Node: Connections In Python,  Next: TUI Windows In Python,  Prev: Registers In Python,  Up: Python API

23.3.2.39 Connections In Python
...............................

GDB lets you run and debug multiple programs in a single session.  Each
program being debugged has a connection, the connection describes how
GDB controls the program being debugged.  Examples of different
connection types are ‘native’ and ‘remote’.  *Note Inferiors Connections
and Programs::.

   Connections in GDB are represented as instances of
‘gdb.TargetConnection’, or as one of its sub-classes.  To get a list of
all connections use ‘gdb.connections’ (*note gdb.connections:
gdbpy_connections.).

   To get the connection for a single ‘gdb.Inferior’ read its
‘gdb.Inferior.connection’ attribute (*note gdb.Inferior.connection:
gdbpy_inferior_connection.).

   Currently there is only a single sub-class of ‘gdb.TargetConnection’,
‘gdb.RemoteTargetConnection’, however, additional sub-classes may be
added in future releases of GDB.  As a result you should avoid writing
code like:

     conn = gdb.selected_inferior().connection
     if type(conn) is gdb.RemoteTargetConnection:
       print("This is a remote target connection")

as this may fail when more connection types are added.  Instead, you
should write:

     conn = gdb.selected_inferior().connection
     if isinstance(conn, gdb.RemoteTargetConnection):
       print("This is a remote target connection")

   A ‘gdb.TargetConnection’ has the following method:

 -- Function: TargetConnection.is_valid ()
     Return ‘True’ if the ‘gdb.TargetConnection’ object is valid,
     ‘False’ if not.  A ‘gdb.TargetConnection’ will become invalid if
     the connection no longer exists within GDB, this might happen when
     no inferiors are using the connection, but could be delayed until
     the user replaces the current target.

     Reading any of the ‘gdb.TargetConnection’ properties will throw an
     exception if the connection is invalid.

   A ‘gdb.TargetConnection’ has the following read-only properties:

 -- Variable: TargetConnection.num
     An integer assigned by GDB to uniquely identify this connection.
     This is the same value as displayed in the ‘Num’ column of the
     ‘info connections’ command output (*note info connections:
     Inferiors Connections and Programs.).

 -- Variable: TargetConnection.type
     A string that describes what type of connection this is.  This
     string will be one of the valid names that can be passed to the
     ‘target’ command (*note target command: Target Commands.).

 -- Variable: TargetConnection.description
     A string that gives a short description of this target type.  This
     is the same string that is displayed in the ‘Description’ column of
     the ‘info connection’ command output (*note info connections:
     Inferiors Connections and Programs.).

 -- Variable: TargetConnection.details
     An optional string that gives additional information about this
     connection.  This attribute can be ‘None’ if there are no
     additional details for this connection.

     An example of a connection type that might have additional details
     is the ‘remote’ connection, in this case the details string can
     contain the ‘HOSTNAME:PORT’ that was used to connect to the remote
     target.

   The ‘gdb.RemoteTargetConnection’ class is a sub-class of
‘gdb.TargetConnection’, and is used to represent ‘remote’ and
‘extended-remote’ connections.  In addition to the attributes and
methods available from the ‘gdb.TargetConnection’ base class, a
‘gdb.RemoteTargetConnection’ has the following method:

 -- Function: RemoteTargetConnection.send_packet (packet)
     This method sends PACKET to the remote target and returns the
     response.  The PACKET should either be a ‘bytes’ object, or a
     ‘Unicode’ string.

     If PACKET is a ‘Unicode’ string, then the string is encoded to a
     ‘bytes’ object using the ASCII codec.  If the string can't be
     encoded then an ‘UnicodeError’ is raised.

     If PACKET is not a ‘bytes’ object, or a ‘Unicode’ string, then a
     ‘TypeError’ is raised.  If PACKET is empty then a ‘ValueError’ is
     raised.

     The response is returned as a ‘bytes’ object.  If it is known that
     the response can be represented as a string then this can be
     decoded from the buffer.  For example, if it is known that the
     response is an ASCII string:

          remote_connection.send_packet("some_packet").decode("ascii")

     The prefix, suffix, and checksum (as required by the remote serial
     protocol) are automatically added to the outgoing packet, and
     removed from the incoming packet before the contents of the reply
     are returned.

     This is equivalent to the ‘maintenance packet’ command (*note maint
     packet::).


File: gdb.info,  Node: TUI Windows In Python,  Next: Disassembly In Python,  Prev: Connections In Python,  Up: Python API

23.3.2.40 Implementing new TUI windows
......................................

New TUI (*note TUI::) windows can be implemented in Python.

 -- Function: gdb.register_window_type (name, factory)
     Because TUI windows are created and destroyed depending on the
     layout the user chooses, new window types are implemented by
     registering a factory function with GDB.

     NAME is the name of the new window.  It's an error to try to
     replace one of the built-in windows, but other window types can be
     replaced.  The NAME should match the regular expression
     ‘[a-zA-Z][-_.a-zA-Z0-9]*’, it is an error to try and create a
     window with an invalid name.

     FUNCTION is a factory function that is called to create the TUI
     window.  This is called with a single argument of type
     ‘gdb.TuiWindow’, described below.  It should return an object that
     implements the TUI window protocol, also described below.

   As mentioned above, when a factory function is called, it is passed
an object of type ‘gdb.TuiWindow’.  This object has these methods and
attributes:

 -- Function: TuiWindow.is_valid ()
     This method returns ‘True’ when this window is valid.  When the
     user changes the TUI layout, windows no longer visible in the new
     layout will be destroyed.  At this point, the ‘gdb.TuiWindow’ will
     no longer be valid, and methods (and attributes) other than
     ‘is_valid’ will throw an exception.

     When the TUI is disabled using ‘tui disable’ (*note tui disable:
     TUI Commands.) the window is hidden rather than destroyed, but
     ‘is_valid’ will still return ‘False’ and other methods (and
     attributes) will still throw an exception.

 -- Variable: TuiWindow.width
     This attribute holds the width of the window.  It is not writable.

 -- Variable: TuiWindow.height
     This attribute holds the height of the window.  It is not writable.

 -- Variable: TuiWindow.title
     This attribute holds the window's title, a string.  This is
     normally displayed above the window.  This attribute can be
     modified.

 -- Function: TuiWindow.erase ()
     Remove all the contents of the window.

 -- Function: TuiWindow.write (string [, full_window])
     Write STRING to the window.  STRING can contain ANSI terminal
     escape styling sequences; GDB will translate these as appropriate
     for the terminal.

     If the FULL_WINDOW parameter is ‘True’, then STRING contains the
     full contents of the window.  This is similar to calling ‘erase’
     before ‘write’, but avoids the flickering.

   The factory function that you supply should return an object
conforming to the TUI window protocol.  These are the methods that can
be called on this object, which is referred to below as the "window
object".  The methods documented below are optional; if the object does
not implement one of these methods, GDB will not attempt to call it.
Additional new methods may be added to the window protocol in the
future.  GDB guarantees that they will begin with a lower-case letter,
so you can start implementation methods with upper-case letters or
underscore to avoid any future conflicts.

 -- Function: Window.close ()
     When the TUI window is closed, the ‘gdb.TuiWindow’ object will be
     put into an invalid state.  At this time, GDB will call ‘close’
     method on the window object.

     After this method is called, GDB will discard any references it
     holds on this window object, and will no longer call methods on
     this object.

 -- Function: Window.render ()
     In some situations, a TUI window can change size.  For example,
     this can happen if the user resizes the terminal, or changes the
     layout.  When this happens, GDB will call the ‘render’ method on
     the window object.

     If your window is intended to update in response to changes in the
     inferior, you will probably also want to register event listeners
     and send output to the ‘gdb.TuiWindow’.

 -- Function: Window.hscroll (num)
     This is a request to scroll the window horizontally.  NUM is the
     amount by which to scroll, with negative numbers meaning to scroll
     right.  In the TUI model, it is the viewport that moves, not the
     contents.  A positive argument should cause the viewport to move
     right, and so the content should appear to move to the left.

 -- Function: Window.vscroll (num)
     This is a request to scroll the window vertically.  NUM is the
     amount by which to scroll, with negative numbers meaning to scroll
     backward.  In the TUI model, it is the viewport that moves, not the
     contents.  A positive argument should cause the viewport to move
     down, and so the content should appear to move up.

 -- Function: Window.click (x, y, button)
     This is called on a mouse click in this window.  X and Y are the
     mouse coordinates inside the window (0-based, from the top left
     corner), and BUTTON specifies which mouse button was used, whose
     values can be 1 (left), 2 (middle), or 3 (right).

     When TUI mouse events are disabled by turning off the ‘tui
     mouse-events’ setting (*note set tui mouse-events:
     tui-mouse-events.), then ‘click’ will not be called.


File: gdb.info,  Node: Disassembly In Python,  Next: Missing Debug Info In Python,  Prev: TUI Windows In Python,  Up: Python API

23.3.2.41 Instruction Disassembly In Python
...........................................

GDB's builtin disassembler can be extended, or even replaced, using the
Python API. The disassembler related features are contained within the
‘gdb.disassembler’ module:

 -- class: gdb.disassembler.DisassembleInfo
     Disassembly is driven by instances of this class.  Each time GDB
     needs to disassemble an instruction, an instance of this class is
     created and passed to a registered disassembler.  The disassembler
     is then responsible for disassembling an instruction and returning
     a result.

     Instances of this type are usually created within GDB, however, it
     is possible to create a copy of an instance of this type, see the
     description of ‘__init__’ for more details.

     This class has the following properties and methods:

      -- Variable: DisassembleInfo.address
          A read-only integer containing the address at which GDB wishes
          to disassemble a single instruction.

      -- Variable: DisassembleInfo.architecture
          The ‘gdb.Architecture’ (*note Architectures In Python::) for
          which GDB is currently disassembling, this property is
          read-only.

      -- Variable: DisassembleInfo.progspace
          The ‘gdb.Progspace’ (*note Program Spaces In Python:
          Progspaces In Python.) for which GDB is currently
          disassembling, this property is read-only.

      -- Function: DisassembleInfo.is_valid ()
          Returns ‘True’ if the ‘DisassembleInfo’ object is valid,
          ‘False’ if not.  A ‘DisassembleInfo’ object will become
          invalid once the disassembly call for which the
          ‘DisassembleInfo’ was created, has returned.  Calling other
          ‘DisassembleInfo’ methods, or accessing ‘DisassembleInfo’
          properties, will raise a ‘RuntimeError’ exception if it is
          invalid.

      -- Function: DisassembleInfo.__init__ (info)
          This can be used to create a new ‘DisassembleInfo’ object that
          is a copy of INFO.  The copy will have the same ‘address’,
          ‘architecture’, and ‘progspace’ values as INFO, and will
          become invalid at the same time as INFO.

          This method exists so that sub-classes of ‘DisassembleInfo’
          can be created, these sub-classes must be initialized as
          copies of an existing ‘DisassembleInfo’ object, but
          sub-classes might choose to override the ‘read_memory’ method,
          and so control what GDB sees when reading from memory (*note
          builtin_disassemble::).

      -- Function: DisassembleInfo.read_memory (length, offset)
          This method allows the disassembler to read the bytes of the
          instruction to be disassembled.  The method reads LENGTH
          bytes, starting at OFFSET from ‘DisassembleInfo.address’.

          It is important that the disassembler read the instruction
          bytes using this method, rather than reading inferior memory
          directly, as in some cases GDB disassembles from an internal
          buffer rather than directly from inferior memory, calling this
          method handles this detail.

          Returns a buffer object, which behaves much like an array or a
          string, just as ‘Inferior.read_memory’ does (*note
          Inferior.read_memory: gdbpy_inferior_read_memory.).  The
          length of the returned buffer will always be exactly LENGTH.

          If GDB is unable to read the required memory then a
          ‘gdb.MemoryError’ exception is raised (*note Exception
          Handling::).

          This method can be overridden by a sub-class in order to
          control what GDB sees when reading from memory (*note
          builtin_disassemble::).  When overriding this method it is
          important to understand how ‘builtin_disassemble’ makes use of
          this method.

          While disassembling a single instruction there could be
          multiple calls to this method, and the same bytes might be
          read multiple times.  Any single call might only read a subset
          of the total instruction bytes.

          If an implementation of ‘read_memory’ is unable to read the
          requested memory contents, for example, if there's a request
          to read from an invalid memory address, then a
          ‘gdb.MemoryError’ should be raised.

          Raising a ‘MemoryError’ inside ‘read_memory’ does not
          automatically mean a ‘MemoryError’ will be raised by
          ‘builtin_disassemble’.  It is possible the GDB's builtin
          disassembler is probing to see how many bytes are available.
          When ‘read_memory’ raises the ‘MemoryError’ the builtin
          disassembler might be able to perform a complete disassembly
          with the bytes it has available, in this case
          ‘builtin_disassemble’ will not itself raise a ‘MemoryError’.

          Any other exception type raised in ‘read_memory’ will
          propagate back and be re-raised by ‘builtin_disassemble’.

      -- Function: DisassembleInfo.text_part (style, string)
          Create a new ‘DisassemblerTextPart’ representing a piece of a
          disassembled instruction.  STRING should be a non-empty
          string, and STYLE should be an appropriate style constant
          (*note Disassembler Style Constants::).

          Disassembler parts are used when creating a
          ‘DisassemblerResult’ in order to represent the styling within
          an instruction (*note DisassemblerResult Class::).

      -- Function: DisassembleInfo.address_part (address)
          Create a new ‘DisassemblerAddressPart’.  ADDRESS is the value
          of the absolute address this part represents.  A
          ‘DisassemblerAddressPart’ is displayed as an absolute address
          and an associated symbol, the address and symbol are styled
          appropriately.

 -- class: gdb.disassembler.Disassembler
     This is a base class from which all user implemented disassemblers
     must inherit.

      -- Function: Disassembler.__init__ (name)
          The constructor takes NAME, a string, which should be a short
          name for this disassembler.

      -- Function: Disassembler.__call__ (info)
          The ‘__call__’ method must be overridden by sub-classes to
          perform disassembly.  Calling ‘__call__’ on this base class
          will raise a ‘NotImplementedError’ exception.

          The INFO argument is an instance of ‘DisassembleInfo’, and
          describes the instruction that GDB wants disassembling.

          If this function returns ‘None’, this indicates to GDB that
          this sub-class doesn't wish to disassemble the requested
          instruction.  GDB will then use its builtin disassembler to
          perform the disassembly.

          Alternatively, this function can return a ‘DisassemblerResult’
          that represents the disassembled instruction, this type is
          described in more detail below.

          The ‘__call__’ method can raise a ‘gdb.MemoryError’ exception
          (*note Exception Handling::) to indicate to GDB that there was
          a problem accessing the required memory, this will then be
          displayed by GDB within the disassembler output.

          Ideally, the only three outcomes from invoking ‘__call__’
          would be a return of ‘None’, a successful disassembly returned
          in a ‘DisassemblerResult’, or a ‘MemoryError’ indicating that
          there was a problem reading memory.

          However, as an implementation of ‘__call__’ could fail due to
          other reasons, e.g. some external resource required to perform
          disassembly is temporarily unavailable, then, if ‘__call__’
          raises a ‘GdbError’, the exception will be converted to a
          string and printed at the end of the disassembly output, the
          disassembly request will then stop.

          Any other exception type raised by the ‘__call__’ method is
          considered an error in the user code, the exception will be
          printed to the error stream according to the ‘set python
          print-stack’ setting (*note ‘set python print-stack’:
          set_python_print_stack.).

 -- class: gdb.disassembler.DisassemblerResult
     This class represents the result of disassembling a single
     instruction.  An instance of this class will be returned from
     ‘builtin_disassemble’ (*note builtin_disassemble::), and an
     instance of this class should be returned from
     ‘Disassembler.__call__’ (*note Disassembler Class::) if an
     instruction was successfully disassembled.

     It is not possible to sub-class the ‘DisassemblerResult’ class.

     The ‘DisassemblerResult’ class has the following properties and
     methods:

      -- Function: DisassemblerResult.__init__ (length, string, parts)
          Initialize an instance of this class, LENGTH is the length of
          the disassembled instruction in bytes, which must be greater
          than zero.

          Only one of STRING or PARTS should be used to initialize a new
          ‘DisassemblerResult’; the other one should be passed the value
          ‘None’.  Alternatively, the arguments can be passed by name,
          and the unused argument can be ignored.

          The STRING argument, if not ‘None’, is a non-empty string that
          represents the entire disassembled instruction.  Building a
          result object using the STRING argument does not allow for any
          styling information to be included in the result.  GDB will
          style the result as a single ‘DisassemblerTextPart’ with
          ‘STYLE_TEXT’ style (*note Disassembler Styling Parts::).

          The PARTS argument, if not ‘None’, is a non-empty sequence of
          ‘DisassemblerPart’ objects.  Each part represents a small part
          of the disassembled instruction along with associated styling
          information.  A result object built using PARTS can be
          displayed by GDB with full styling information (*note ‘set
          style disassembler enabled’: style_disassembler_enabled.).

      -- Variable: DisassemblerResult.length
          A read-only property containing the length of the disassembled
          instruction in bytes, this will always be greater than zero.

      -- Variable: DisassemblerResult.string
          A read-only property containing a non-empty string
          representing the disassembled instruction.  The STRING is a
          representation of the disassembled instruction without any
          styling information.  To see how the instruction will be
          styled use the PARTS property.

          If this instance was initialized using separate
          ‘DisassemblerPart’ objects, the STRING property will still be
          valid.  The STRING value is created by concatenating the
          ‘DisassemblerPart.string’ values of each component part (*note
          Disassembler Styling Parts::).

      -- Variable: DisassemblerResult.parts
          A read-only property containing a non-empty sequence of
          ‘DisassemblerPart’ objects.  Each ‘DisassemblerPart’ object
          contains a small part of the instruction along with
          information about how that part should be styled.  GDB uses
          this information to create styled disassembler output (*note
          ‘set style disassembler enabled’:
          style_disassembler_enabled.).

          If this instance was initialized using a single string rather
          than with a sequence of ‘DisassemblerPart’ objects, the PARTS
          property will still be valid.  In this case the PARTS property
          will hold a sequence containing a single
          ‘DisassemblerTextPart’ object, the string of which will
          represent the entire instruction, and the style of which will
          be ‘STYLE_TEXT’.

 -- class: gdb.disassembler.DisassemblerPart
     This is a parent class from which the different part sub-classes
     inherit.  Only instances of the sub-classes detailed below will be
     returned by the Python API.

     It is not possible to directly create instances of either this
     parent class, or any of the sub-classes listed below.  Instances of
     the sub-classes listed below are created by calling
     ‘builtin_disassemble’ (*note builtin_disassemble::) and are
     returned within the ‘DisassemblerResult’ object, or can be created
     by calling the ‘text_part’ and ‘address_part’ methods on the
     ‘DisassembleInfo’ class (*note DisassembleInfo Class::).

     The ‘DisassemblerPart’ class has a single property:

      -- Variable: DisassemblerPart.string
          A read-only property that contains a non-empty string
          representing this part of the disassembled instruction.  The
          string within this property doesn't include any styling
          information.

 -- class: gdb.disassembler.DisassemblerTextPart
     The ‘DisassemblerTextPart’ class represents a piece of the
     disassembled instruction and the associated style for that piece.
     Instances of this class can't be created directly, instead call
     ‘DisassembleInfo.text_part’ to create a new instance of this class
     (*note DisassembleInfo Class::).

     As well as the properties of its parent class, the
     ‘DisassemblerTextPart’ has the following additional property:

      -- Variable: DisassemblerTextPart.style
          A read-only property that contains one of the defined style
          constants.  GDB will use this style when styling this part of
          the disassembled instruction (*note Disassembler Style
          Constants::).

 -- class: gdb.disassembler.DisassemblerAddressPart
     The ‘DisassemblerAddressPart’ class represents an absolute address
     within a disassembled instruction.  Using a
     ‘DisassemblerAddressPart’ instead of a ‘DisassemblerTextPart’ with
     ‘STYLE_ADDRESS’ is preferred, GDB will display the address as both
     an absolute address, and will look up a suitable symbol to display
     next to the address.  Using ‘DisassemblerAddressPart’ also ensures
     that user settings such as ‘set print max-symbolic-offset’ are
     respected.

     Here is an example of an x86-64 instruction:

          call   0x401136 <foo>

     In this instruction the ‘0x401136 <foo>’ was generated from a
     single ‘DisassemblerAddressPart’.  The ‘0x401136’ will be styled
     with ‘STYLE_ADDRESS’, and ‘foo’ will be styled with ‘STYLE_SYMBOL’.
     The ‘<’ and ‘>’ will be styled as ‘STYLE_TEXT’.

     If the inclusion of the symbol name is not required then a
     ‘DisassemblerTextPart’ with style ‘STYLE_ADDRESS’ can be used
     instead.

     Instances of this class can't be created directly, instead call
     ‘DisassembleInfo.address_part’ to create a new instance of this
     class (*note DisassembleInfo Class::).

     As well as the properties of its parent class, the
     ‘DisassemblerAddressPart’ has the following additional property:

      -- Variable: DisassemblerAddressPart.address
          A read-only property that contains the ADDRESS passed to this
          object's ‘__init__’ method.

   The following table lists all of the disassembler styles that are
available.  GDB maps these style constants onto its style settings
(*note Output Styling::).  In some cases, several style constants
produce the same style settings, and thus will produce the same visual
effect on the screen.  This could change in future releases of GDB, so
care should be taken to select the correct style constant to ensure
correct output styling in future releases of GDB.

‘gdb.disassembler.STYLE_TEXT’
     This is the default style used by GDB when styling disassembler
     output.  This style should be used for any parts of the instruction
     that don't fit any of the other styles listed below.  GDB styles
     text with this style using its default style.

‘gdb.disassembler.STYLE_MNEMONIC’
     This style is used for styling the primary instruction mnemonic,
     which usually appears at, or near, the start of the disassembled
     instruction string.

     GDB styles text with this style using the ‘disassembler mnemonic’
     style setting.

‘gdb.disassembler.STYLE_SUB_MNEMONIC’
     This style is used for styling any sub-mnemonics within a
     disassembled instruction.  A sub-mnemonic is any text within the
     instruction that controls the function of the instruction, but
     which is disjoint from the primary mnemonic (which will have styled
     ‘STYLE_MNEMONIC’).

     As an example, consider this AArch64 instruction:

          add	w16, w7, w1, lsl #1

     The ‘add’ is the primary instruction mnemonic, and would be given
     style ‘STYLE_MNEMONIC’, while ‘lsl’ is the sub-mnemonic, and would
     be given the style ‘STYLE_SUB_MNEMONIC’.

     GDB styles text with this style using the ‘disassembler mnemonic’
     style setting.

‘gdb.disassembler.STYLE_ASSEMBLER_DIRECTIVE’
     Sometimes a series of bytes doesn't decode to a valid instruction.
     In this case the disassembler may choose to represent the result of
     disassembling using an assembler directive, for example:

          .word	0x1234

     In this case, the ‘.word’ would be give the
     ‘STYLE_ASSEMBLER_DIRECTIVE’ style.  An assembler directive is
     similar to a mnemonic in many ways but is something that is not
     part of the architecture's instruction set.

     GDB styles text with this style using the ‘disassembler mnemonic’
     style setting.

‘gdb.disassembler.STYLE_REGISTER’
     This style is used for styling any text that represents a register
     name, or register number, within a disassembled instruction.

     GDB styles text with this style using the ‘disassembler register’
     style setting.

‘gdb.disassembler.STYLE_ADDRESS’
     This style is used for styling numerical values that represent
     absolute addresses within the disassembled instruction.

     When creating a ‘DisassemblerTextPart’ with this style, you should
     consider if a ‘DisassemblerAddressPart’ would be more appropriate.
     See *note Disassembler Styling Parts:: for a description of what
     each part offers.

     GDB styles text with this style using the ‘disassembler address’
     style setting.

‘gdb.disassembler.STYLE_ADDRESS_OFFSET’
     This style is used for styling numerical values that represent
     offsets to addresses within the disassembled instruction.  A value
     is considered an address offset when the instruction itself is
     going to access memory, and the value is being used to offset which
     address is accessed.

     For example, an architecture might have an instruction that loads
     from memory using an address within a register.  If that
     instruction also allowed for an immediate offset to be encoded into
     the instruction, this would be an address offset.  Similarly, a
     branch instruction might jump to an address in a register plus an
     address offset that is encoded into the instruction.

     GDB styles text with this style using the ‘disassembler immediate’
     style setting.

‘gdb.disassembler.STYLE_IMMEDIATE’
     Use ‘STYLE_IMMEDIATE’ for any numerical values within a
     disassembled instruction when those values are not addresses,
     address offsets, or register numbers (The styles ‘STYLE_ADDRESS’,
     ‘STYLE_ADDRESS_OFFSET’, or ‘STYLE_REGISTER’ can be used in those
     cases).

     GDB styles text with this style using the ‘disassembler immediate’
     style setting.

‘gdb.disassembler.STYLE_SYMBOL’
     This style is used for styling the textual name of a symbol that is
     included within a disassembled instruction.  A symbol name is often
     included next to an absolute address within a disassembled
     instruction to make it easier for the user to understand what the
     address is referring too.  For example:

          call   0x401136 <foo>

     Here ‘foo’ is the name of a symbol, and should be given the
     ‘STYLE_SYMBOL’ style.

     Adding symbols next to absolute addresses like this is handled
     automatically by the ‘DisassemblerAddressPart’ class (*note
     Disassembler Styling Parts::).

     GDB styles text with this style using the ‘disassembler symbol’
     style setting.

‘gdb.disassembler.STYLE_COMMENT_START’
     This style is used to start a line comment in the disassembly
     output.  Unlike other styles, which only apply to the single
     ‘DisassemblerTextPiece’ to which they are applied, the comment
     style is sticky, and overrides the style of any further pieces
     within this instruction.

     This means that, after a ‘STYLE_COMMENT_START’ piece has been seen,
     GDB will apply the comment style until the end of the line,
     ignoring the specific style within a piece.

     GDB styles text with this style using the ‘disassembler comment’
     style setting.

   The following functions are also contained in the ‘gdb.disassembler’
module:

 -- Function: register_disassembler (disassembler, architecture)
     The DISASSEMBLER must be a sub-class of
     ‘gdb.disassembler.Disassembler’ or ‘None’.

     The optional ARCHITECTURE is either a string, or the value ‘None’.
     If it is a string, then it should be the name of an architecture
     known to GDB, as returned either from ‘gdb.Architecture.name’
     (*note gdb.Architecture.name: gdbpy_architecture_name.), or from
     ‘gdb.architecture_names’ (*note gdb.architecture_names:
     gdb_architecture_names.).

     The DISASSEMBLER will be installed for the architecture named by
     ARCHITECTURE, or if ARCHITECTURE is ‘None’, then DISASSEMBLER will
     be installed as a global disassembler for use by all architectures.

     GDB only records a single disassembler for each architecture, and a
     single global disassembler.  Calling ‘register_disassembler’ for an
     architecture, or for the global disassembler, will replace any
     existing disassembler registered for that ARCHITECTURE value.  The
     previous disassembler is returned.

     If DISASSEMBLER is ‘None’ then any disassembler currently
     registered for ARCHITECTURE is deregistered and returned.

     When GDB is looking for a disassembler to use, GDB first looks for
     an architecture specific disassembler.  If none has been registered
     then GDB looks for a global disassembler (one registered with
     ARCHITECTURE set to ‘None’).  Only one disassembler is called to
     perform disassembly, so, if there is both an architecture specific
     disassembler, and a global disassembler registered, it is the
     architecture specific disassembler that will be used.

     GDB tracks the architecture specific, and global disassemblers
     separately, so it doesn't matter in which order disassemblers are
     created or registered; an architecture specific disassembler, if
     present, will always be used in preference to a global
     disassembler.

     You can use the ‘maint info python-disassemblers’ command (*note
     maint info python-disassemblers::) to see which disassemblers have
     been registered.

 -- Function: builtin_disassemble (info)
     This function calls back into GDB's builtin disassembler to
     disassemble the instruction identified by INFO, an instance, or
     sub-class, of ‘DisassembleInfo’.

     When the builtin disassembler needs to read memory the
     ‘read_memory’ method on INFO will be called.  By sub-classing
     ‘DisassembleInfo’ and overriding the ‘read_memory’ method, it is
     possible to intercept calls to ‘read_memory’ from the builtin
     disassembler, and to modify the values returned.

     It is important to understand that, even when
     ‘DisassembleInfo.read_memory’ raises a ‘gdb.MemoryError’, it is the
     internal disassembler itself that reports the memory error to GDB.
     The reason for this is that the disassembler might probe memory to
     see if a byte is readable or not; if the byte can't be read then
     the disassembler may choose not to report an error, but instead to
     disassemble the bytes that it does have available.

     If the builtin disassembler is successful then an instance of
     ‘DisassemblerResult’ is returned from ‘builtin_disassemble’,
     alternatively, if something goes wrong, an exception will be
     raised.

     A ‘MemoryError’ will be raised if ‘builtin_disassemble’ is unable
     to read some memory that is required in order to perform
     disassembly correctly.

     Any exception that is not a ‘MemoryError’, that is raised in a call
     to ‘read_memory’, will pass through ‘builtin_disassemble’, and be
     visible to the caller.

     Finally, there are a few cases where GDB's builtin disassembler can
     fail for reasons that are not covered by ‘MemoryError’.  In these
     cases, a ‘GdbError’ will be raised.  The contents of the exception
     will be a string describing the problem the disassembler
     encountered.

   Here is an example that registers a global disassembler.  The new
disassembler invokes the builtin disassembler, and then adds a comment,
‘## Comment’, to each line of disassembly output:

     class ExampleDisassembler(gdb.disassembler.Disassembler):
         def __init__(self):
             super().__init__("ExampleDisassembler")

         def __call__(self, info):
             result = gdb.disassembler.builtin_disassemble(info)
             length = result.length
             text = result.string + "\t## Comment"
             return gdb.disassembler.DisassemblerResult(length, text)

     gdb.disassembler.register_disassembler(ExampleDisassembler())

   The following example creates a sub-class of ‘DisassembleInfo’ in
order to intercept the ‘read_memory’ calls, within ‘read_memory’ any
bytes read from memory have the two 4-bit nibbles swapped around.  This
isn't a very useful adjustment, but serves as an example.

     class MyInfo(gdb.disassembler.DisassembleInfo):
         def __init__(self, info):
             super().__init__(info)

         def read_memory(self, length, offset):
             buffer = super().read_memory(length, offset)
             result = bytearray()
             for b in buffer:
                 v = int.from_bytes(b, 'little')
                 v = (v << 4) & 0xf0 | (v >> 4)
                 result.append(v)
             return memoryview(result)

     class NibbleSwapDisassembler(gdb.disassembler.Disassembler):
         def __init__(self):
             super().__init__("NibbleSwapDisassembler")

         def __call__(self, info):
             info = MyInfo(info)
             return gdb.disassembler.builtin_disassemble(info)

     gdb.disassembler.register_disassembler(NibbleSwapDisassembler())


File: gdb.info,  Node: Missing Debug Info In Python,  Next: Missing Objfiles In Python,  Prev: Disassembly In Python,  Up: Python API

23.3.2.42 Missing Debug Info In Python
......................................

When GDB encounters a new objfile (*note Objfiles In Python::), e.g. the
primary executable, or any shared libraries used by the inferior, GDB
will attempt to load the corresponding debug information for that
objfile.  The debug information might be found within the objfile
itself, or within a separate objfile which GDB will automatically locate
and load.

   Sometimes though, GDB might not find any debug information for an
objfile, in this case the debugging experience will be restricted.

   If GDB fails to locate any debug information for a particular
objfile, there is an opportunity for a Python extension to step in.  A
Python extension can potentially locate the missing debug information
using some platform- or project-specific steps, and inform GDB of its
location.  Or a Python extension might provide some platform- or
project-specific advice to the user about how to obtain the missing
debug information.

   A missing debug information Python extension consists of a handler
object which has the ‘name’ and ‘enabled’ attributes, and implements the
‘__call__’ method.  When GDB encounters an objfile for which it is
unable to find any debug information, it invokes the ‘__call__’ method.
Full details of how handlers are written can be found below.

The ‘gdb.missing_debug’ Module
------------------------------

GDB comes with a ‘gdb.missing_debug’ module which contains the following
class and global function:

 -- class: gdb.missing_debug.MissingDebugHandler

     ‘MissingDebugHandler’ is a base class from which user-created
     handlers can derive, though it is not required that handlers derive
     from this class, so long as any user created handler has the ‘name’
     and ‘enabled’ attributes, and implements the ‘__call__’ method.

      -- Function: MissingDebugHandler.__init__ (name)
          The NAME is a string used to reference this missing debug
          handler within some GDB commands.  Valid names consist of the
          characters ‘[-_a-zA-Z0-9]’, creating a handler with an invalid
          name raises a ‘ValueError’ exception.

      -- Function: MissingDebugHandler.__call__ (objfile)
          Sub-classes must override the ‘__call__’ method.  The OBJFILE
          argument will be a ‘gdb.Objfile’, this is the objfile for
          which GDB was unable to find any debug information.

          The return value from the ‘__call__’ method indicates what GDB
          should do next.  The possible return values are:

             • ‘None’

               This indicates that this handler could not help with
               OBJFILE, GDB should call any other registered handlers.

             • ‘True’

               This indicates that this handler has installed the debug
               information into a location where GDB would normally
               expect to find it when looking for separate debug
               information files (*note Separate Debug Files::).  GDB
               will repeat the normal lookup process, which should now
               find the separate debug file.

               If GDB still doesn't find the separate debug information
               file after this second attempt, then the Python missing
               debug information handlers are not invoked a second time,
               this prevents a badly behaved handler causing GDB to get
               stuck in a loop.  GDB will continue without any debug
               information for OBJFILE.

             • ‘False’

               This indicates that this handler has done everything that
               it intends to do with OBJFILE, but no separate debug
               information can be found.  GDB will not call any other
               registered handlers for OBJFILE.  GDB will continue
               without debugging information for OBJFILE.

             • A string

               The returned string should contain a filename.  GDB will
               not call any further registered handlers, and will
               instead load the debug information from the file
               identified by the returned filename.

          Invoking the ‘__call__’ method from this base class will raise
          a ‘NotImplementedError’ exception.

      -- Variable: MissingDebugHandler.name
          A read-only attribute which is a string, the name of this
          handler passed to the ‘__init__’ method.

      -- Variable: MissingDebugHandler.enabled
          A modifiable attribute containing a boolean; when ‘True’, the
          handler is enabled, and will be used by GDB.  When ‘False’,
          the handler has been disabled, and will not be used.

 -- Function: gdb.missing_debug.register_handler (locus, handler,
          replace=False)
     Register a new missing debug handler with GDB.

     HANDLER is an instance of a sub-class of ‘MissingDebugHandler’, or
     at least an instance of an object that has the same attributes and
     methods as ‘MissingDebugHandler’.

     LOCUS specifies to which handler list to prepend HANDLER.  It can
     be either a ‘gdb.Progspace’ (*note Progspaces In Python::) or
     ‘None’, in which case the handler is registered globally.  The
     newly registered HANDLER will be called before any other handler
     from the same locus.  Two handlers in the same locus cannot have
     the same name, an attempt to add a handler with an already existing
     name raises an exception unless REPLACE is ‘True’, in which case
     the old handler is deleted and the new handler is prepended to the
     selected handler list.

     GDB first calls the handlers for the current program space, and
     then the globally registered handlers.  As soon as a handler
     returns a value other than ‘None’, no further handlers are called
     for this objfile.


File: gdb.info,  Node: Missing Objfiles In Python,  Prev: Missing Debug Info In Python,  Up: Python API

23.3.2.43 Missing Objfiles In Python
....................................

When GDB opens a core file, for example with the ‘core-file’ command
(*note core-file command::), GDB will attempt to load the corresponding
executable and shared libraries.  Often these files can be found on the
local machine, but sometimes these files cannot be found, in which case
the debugging experience will be restricted.

   If GDB fails to locate a particular file then there is an opportunity
for a Python extension to step in.  A Python extension can potentially
locate the missing file using some platform- or project-specific steps,
and inform GDB of its location.  Or a Python extension might provide
some platform- or project-specific advice to the user about how to
obtain the missing file.

   A missing-objfile Python extension consists of a handler object which
has the ‘name’ and ‘enabled’ attributes, and implements the ‘__call__’
method.  When GDB encounters a situation where a file cannot be found,
but the build-id (*note build ID::) for the missing file is known, then
the ‘__call__’ method is invoked to try and find the file.  Full details
of how handlers are written can be found below.

The ‘gdb.missing_objfile’ Module
--------------------------------

GDB comes with a ‘gdb.missing_objfile’ module which contains the
following class and global function:

 -- class: gdb.missing_objfile.MissingObjfileHandler

     ‘MissingObjfileHandler’ is a base class from which user-created
     handlers can derive, though it is not required that handlers derive
     from this class, so long as any user created handler has the ‘name’
     and ‘enabled’ attributes, and implements the ‘__call__’ method.

      -- Function: MissingObjfileHandler.__init__ (name)
          The NAME is a string used to reference this missing-objfile
          handler within some GDB commands.  Valid names consist of the
          characters ‘[-_a-zA-Z0-9]’, creating a handler with an invalid
          name raises a ‘ValueError’ exception.

      -- Function: MissingObjfileHandler.__call__ (pspace, build_id,
               filename)

          Sub-classes must override the ‘__call__’ method.  The PSPACE
          argument will be a ‘gdb.Progspace’ (*note Progspaces In
          Python::), this is the program space in which GDB is looking
          for the missing file.

          The BUILD_ID argument is a string containing the build-id of
          the file that is missing, this will be in the same format as
          returned by ‘Objfile.build_id’ (*note Objfile.build_id::).

          The FILENAME argument contains the name of the file that GDB
          is looking for.  This information is provided to allow
          handlers to generate informative messages for the user.  A
          handler is not required to place the missing file at this
          location.  There might already be a file present at this
          location, but it might not match the required build-id, in
          which case GDB will have ignored it.  In some limited cases
          GDB might not be able to establish the FILENAME of the file it
          is searching for, in this case GDB will use a string ‘with
          build-id BUILD_ID’ as a replacement.

          The return value from the ‘__call__’ method indicates what GDB
          should do next.  The possible return values are:

             • ‘None’

               This indicates that this handler could not locate the
               missing file and GDB should call any other registered
               handlers.

             • ‘True’

               This indicates that this handler has installed the
               missing file into a location where GDB would normally
               expect to find it.  The only location in which GDB will
               look is within the ‘.build-id’ sub-directory within the
               DEBUG-FILE-DIRECTORY (*note debug-file-directory::).

               GDB will repeat the normal lookup process, which should
               now find the previously missing file.

               If GDB still doesn't find file after this second attempt,
               then the Python missing-objfile handlers are not invoked
               a second time, this prevents a badly behaved handler
               causing GDB to get stuck in a loop.  GDB will continue
               without the missing file, though this will degrade the
               debugging experience.

             • ‘False’

               This indicates that this handler has done everything that
               it intends to do but the missing file could not be found.
               GDB will not call any other registered handlers to look
               for the missing file.  GDB will continue without the
               missing file, though this will degrade the debugging
               experience.

             • A string

               The returned string should contain a filename.  GDB will
               not call any further registered handlers, and will
               instead use the returned filename as the missing file.

          Invoking the ‘__call__’ method from this base class will raise
          a ‘NotImplementedError’ exception.

      -- Variable: MissingObjfileHandler.name
          A read-only attribute which is a string, the name of this
          handler passed to the ‘__init__’ method.

      -- Variable: MissingObjfileHandler.enabled
          A modifiable attribute containing a boolean; when ‘True’, the
          handler is enabled, and will be used by GDB.  When ‘False’,
          the handler has been disabled, and will not be used.

 -- Function: gdb.missing_objfile.register_handler (locus, handler,
          replace=False)
     Register a new missing-objfile handler with GDB.

     HANDLER is an instance of a sub-class of ‘MissingObjfileHandler’,
     or at least an instance of an object that has the same attributes
     and methods as ‘MissingObjfileHandler’.

     LOCUS specifies to which handler list to prepend HANDLER.  It can
     be either a ‘gdb.Progspace’ (*note Progspaces In Python::) or
     ‘None’, in which case the handler is registered globally.  The
     newly registered HANDLER will be called before any other handler
     from the same locus.  Two handlers in the same locus cannot have
     the same name, an attempt to add a handler with an already existing
     name raises an exception unless REPLACE is ‘True’, in which case
     the old handler is deleted and the new handler is prepended to the
     selected handler list.

     GDB first calls the handlers for the current program space, and
     then the globally registered handlers.  As soon as a handler
     returns a value other than ‘None’, no further handlers are called.

Managing Missing-Objfile Handlers
---------------------------------

GDB defines the following commands to manage registered missing-objfile
handlers:

‘info missing-objfile-handlers [ LOCUS [ NAME-REGEXP ] ]’
     Lists all registered missing-objfile handlers.  Arguments LOCUS and
     NAME-REGEXP are both optional and can be used to filter which
     handlers are listed.

     The LOCUS argument should be either ‘global’, ‘progspace’, or the
     name of an object file.  Only handlers registered for the specified
     locus will be listed.

     The NAME-REGEXP is a regular expression used to match against
     handler names.

‘disable missing-objfile-handler [ LOCUS [ NAME-REGEXP ] ]’
     The LOCUS and NAME-REGEXP are interpreted as in ‘info
     missing-objfile-handlers’ above, but instead of listing the
     matching handlers, all of the matching handlers are disabled.  The
     ‘enabled’ field of each matching handler is set to ‘False’.

‘enable missing-objfile-handler [ LOCUS [ NAME-REGEXP ] ]’
     The LOCUS and NAME-REGEXP are interpreted as in ‘info
     missing-objfile-handlers’ above, but instead of listing the
     matching handlers, all of the matching handlers are enabled.  The
     ‘enabled’ field of each matching handler is set to ‘True’.


File: gdb.info,  Node: Python Auto-loading,  Next: Python modules,  Prev: Python API,  Up: Python

23.3.3 Python Auto-loading
--------------------------

When a new object file is read (for example, due to the ‘file’ command,
or because the inferior has loaded a shared library), GDB will look for
Python support scripts in several ways: ‘OBJFILE-gdb.py’ and
‘.debug_gdb_scripts’ section.  *Note Auto-loading extensions::.

   The auto-loading feature is useful for supplying application-specific
debugging commands and scripts.

   Auto-loading can be enabled or disabled, and the list of auto-loaded
scripts can be printed.

‘set auto-load python-scripts [on|off]’
     Enable or disable the auto-loading of Python scripts.

‘show auto-load python-scripts’
     Show whether auto-loading of Python scripts is enabled or disabled.

‘info auto-load python-scripts [REGEXP]’
     Print the list of all Python scripts that GDB auto-loaded.

     Also printed is the list of Python scripts that were mentioned in
     the ‘.debug_gdb_scripts’ section and were either not found (*note
     dotdebug_gdb_scripts section::) or were not auto-loaded due to
     ‘auto-load safe-path’ rejection (*note Auto-loading::).  This is
     useful because their names are not printed when GDB tries to load
     them and fails.  There may be many of them, and printing an error
     message for each one is problematic.

     If REGEXP is supplied only Python scripts with matching names are
     printed.

     Example:

          (gdb) info auto-load python-scripts
          Loaded Script
          Yes    py-section-script.py
                 full name: /tmp/py-section-script.py
          No     my-foo-pretty-printers.py

   When reading an auto-loaded file or script, GDB sets the “current
objfile”.  This is available via the ‘gdb.current_objfile’ function
(*note Objfiles In Python::).  This can be useful for registering
objfile-specific pretty-printers and frame-filters.


File: gdb.info,  Node: Python modules,  Prev: Python Auto-loading,  Up: Python

23.3.4 Python modules
---------------------

GDB comes with several modules to assist writing Python code.

* Menu:

* gdb.printing::       Building and registering pretty-printers.
* gdb.types::          Utilities for working with types.
* gdb.prompt::         Utilities for prompt value substitution.
* gdb.ptwrite::        Utilities for PTWRITE filter registration.


File: gdb.info,  Node: gdb.printing,  Next: gdb.types,  Up: Python modules

23.3.4.1 gdb.printing
.....................

This module provides a collection of utilities for working with
pretty-printers.

‘PrettyPrinter (NAME, SUBPRINTERS=None)’
     This class specifies the API that makes ‘info pretty-printer’,
     ‘enable pretty-printer’ and ‘disable pretty-printer’ work.
     Pretty-printers should generally inherit from this class.

‘SubPrettyPrinter (NAME)’
     For printers that handle multiple types, this class specifies the
     corresponding API for the subprinters.

‘RegexpCollectionPrettyPrinter (NAME)’
     Utility class for handling multiple printers, all recognized via
     regular expressions.  *Note Writing a Pretty-Printer::, for an
     example.

‘FlagEnumerationPrinter (NAME)’
     A pretty-printer which handles printing of ‘enum’ values.  Unlike
     GDB's built-in ‘enum’ printing, this printer attempts to work
     properly when there is some overlap between the enumeration
     constants.  The argument NAME is the name of the printer and also
     the name of the ‘enum’ type to look up.

‘register_pretty_printer (OBJ, PRINTER, REPLACE=False)’
     Register PRINTER with the pretty-printer list of OBJ.  If REPLACE
     is ‘True’ then any existing copy of the printer is replaced.
     Otherwise a ‘RuntimeError’ exception is raised if a printer with
     the same name already exists.


File: gdb.info,  Node: gdb.types,  Next: gdb.prompt,  Prev: gdb.printing,  Up: Python modules

23.3.4.2 gdb.types
..................

This module provides a collection of utilities for working with
‘gdb.Type’ objects.

‘get_basic_type (TYPE)’
     Return TYPE with const and volatile qualifiers stripped, and with
     typedefs and C++ references converted to the underlying type.

     C++ example:

          typedef const int const_int;
          const_int foo (3);
          const_int& foo_ref (foo);
          int main () { return 0; }

     Then in gdb:

          (gdb) start
          (gdb) python import gdb.types
          (gdb) python foo_ref = gdb.parse_and_eval("foo_ref")
          (gdb) python print gdb.types.get_basic_type(foo_ref.type)
          int

‘has_field (TYPE, FIELD)’
     Return ‘True’ if TYPE, assumed to be a type with fields (e.g., a
     structure or union), has field FIELD.

‘make_enum_dict (ENUM_TYPE)’
     Return a Python ‘dictionary’ type produced from ENUM_TYPE.

‘deep_items (TYPE)’
     Returns a Python iterator similar to the standard
     ‘gdb.Type.iteritems’ method, except that the iterator returned by
     ‘deep_items’ will recursively traverse anonymous struct or union
     fields.  For example:

          struct A
          {
              int a;
              union {
                  int b0;
                  int b1;
              };
          };

     Then in GDB:
          (gdb) python import gdb.types
          (gdb) python struct_a = gdb.lookup_type("struct A")
          (gdb) python print struct_a.keys ()
          {['a', '']}
          (gdb) python print [k for k,v in gdb.types.deep_items(struct_a)]
          {['a', 'b0', 'b1']}

‘get_type_recognizers ()’
     Return a list of the enabled type recognizers for the current
     context.  This is called by GDB during the type-printing process
     (*note Type Printing API::).

‘apply_type_recognizers (recognizers, type_obj)’
     Apply the type recognizers, RECOGNIZERS, to the type object
     TYPE_OBJ.  If any recognizer returns a string, return that string.
     Otherwise, return ‘None’.  This is called by GDB during the
     type-printing process (*note Type Printing API::).

‘register_type_printer (locus, printer)’
     This is a convenience function to register a type printer PRINTER.
     The printer must implement the type printer protocol.  The LOCUS
     argument is either a ‘gdb.Objfile’, in which case the printer is
     registered with that objfile; a ‘gdb.Progspace’, in which case the
     printer is registered with that progspace; or ‘None’, in which case
     the printer is registered globally.

‘TypePrinter’
     This is a base class that implements the type printer protocol.
     Type printers are encouraged, but not required, to derive from this
     class.  It defines a constructor:

      -- Method on TypePrinter: __init__ (self, name)
          Initialize the type printer with the given name.  The new
          printer starts in the enabled state.


File: gdb.info,  Node: gdb.prompt,  Next: gdb.ptwrite,  Prev: gdb.types,  Up: Python modules

23.3.4.3 gdb.prompt
...................

This module provides a method for prompt value-substitution.

‘substitute_prompt (STRING)’
     Return STRING with escape sequences substituted by values.  Some
     escape sequences take arguments.  You can specify arguments inside
     "{}" immediately following the escape sequence.

     The escape sequences you can pass to this function are:

     ‘\\’
          Substitute a backslash.
     ‘\e’
          Substitute an ESC character.
     ‘\f’
          Substitute the selected frame; an argument names a frame
          parameter.
     ‘\n’
          Substitute a newline.
     ‘\p’
          Substitute a parameter's value; the argument names the
          parameter.
     ‘\r’
          Substitute a carriage return.
     ‘\t’
          Substitute the selected thread; an argument names a thread
          parameter.
     ‘\v’
          Substitute the version of GDB.
     ‘\w’
          Substitute the current working directory.
     ‘\[’
          Begin a sequence of non-printing characters.  These sequences
          are typically used with the ESC character, and are not counted
          in the string length.  Example: "\[\e[0;34m\](gdb)\[\e[0m\]"
          will return a blue-colored "(gdb)" prompt where the length is
          five.
     ‘\]’
          End a sequence of non-printing characters.

     For example:

          substitute_prompt ("frame: \f, args: \p{print frame-arguments}")

will return the string:

          "frame: main, args: scalars"


File: gdb.info,  Node: gdb.ptwrite,  Prev: gdb.prompt,  Up: Python modules

23.3.4.4 gdb.ptwrite
....................

This module provides additional functionality for recording programs
that make use of the ‘PTWRITE’ instruction.  ‘PTWRITE’ is a x86
instruction that allows to write values into the Intel Processor Trace
(*note Process Record and Replay::).  The GCC intrinsics for it are:
     void _ptwrite32 (unsigned int a)
     void _ptwrite64 (unsigned __int64 a)

   If an inferior uses the instruction, GDB by default inserts the raw
payload value as auxiliary information into the execution history.
Auxiliary information is by default printed during ‘record
instruction-history’, ‘record function-call-history’, and all stepping
commands, and is accessible in Python as a ‘RecordAuxiliary’ object
(*note Recordings In Python::).

Sample program:
     #include <immintrin.h>

     void
     ptwrite64 (unsigned long long value)
     {
       _ptwrite64 (value);
     }

     int
     main (void)
     {
       ptwrite64 (0x42);
       return 0; /* break here.  */
     }

GDB output after recording the sample program in pt format:
     (gdb) record instruction-history 12,14
     12         0x0040074c <ptwrite64+16>:   ptwrite %rbx
     13           [0x42]
     14         0x00400751 <ptwrite64+21>:   mov -0x8(%rbp),%rbx
     (gdb) record function-call-history
     1       main
     2       ptwrite64
               [0x42]
     3       main

   The ‘gdb.ptwrite’ module allows customizing the default output of
‘PTWRITE’ auxiliary information.  A custom Python function can be
registered as the ‘PTWRITE’ filter function.  This function will be
called with the ‘PTWRITE’ payload and PC as arguments during trace
decoding.  The function can return a string, which will be printed by
GDB during the aforementioned commands, or ‘None’, resulting in no
output.  To register such a filter function, the user needs to provide a
filter factory function, which returns a new filter function object to
be called by GDB.

 -- Function: register_filter_factory (filter_factory)
     Used to register the ‘PTWRITE’ filter factory.  This filter factory
     can be any callable object that accepts one argument, the current
     thread as a ‘gdb.InferiorThread’.  It can return None or a
     callable.  This callable is the ‘PTWRITE’ filter function for the
     specified thread.  If ‘None’ is returned by the factory function,
     the default auxiliary information will be printed.

 -- Function: get_filter ()
     Return the currently active ‘PTWRITE’ filter function.

   An example:

     (gdb) python-interactive
     >>> class my_filter():
     ...    def __init__(self):
     ...        self.var = 0
     ...    def __call__(self, payload, ip):
     ...        self.var += 1
     ...        return f"counter: {self.var}, ip: {ip:#x}"
     ...
     >>> def my_filter_factory(thread):
     ...    if thread.global_num == 1:
     ...        return my_filter()
     ...    else:
     ...        return None
     ...
     >>> import gdb.ptwrite
     >>> gdb.ptwrite.register_filter_factory(my_filter_factory)
     >>>

     (gdb) record function-call-history 59,64
     59      pthread_create@GLIBC_2.2.5
     60      job()
     61      task(void*)
     62      ptwrite64(unsigned long)
               [counter: 1, ip: 0x401156]
     63      task(void*)
     64      ptwrite32(unsigned int)
               [counter: 2, ip: 0x40116c]

     (gdb) info threads
     * 1    Thread 0x7ffff7fd8740 (LWP 25796) "ptw_threads" task ()
         at bin/ptwrite/ptw_threads.c:45
       2    Thread 0x7ffff6eb8700 (LWP 25797) "ptw_threads" task ()
         at bin/ptwrite/ptw_threads.c:45

     (gdb) thread 2
     [Switching to thread 2 (Thread 0x7ffff6eb8700 (LWP 25797))]
     #0  task (arg=0x0) at ptwrite_threads.c:45
     45        return NULL;

     (gdb) record function-call-history 10,14
     10    start_thread
     11    task(void*)
     12    ptwrite64(unsigned long)
             [0x42]
     13    task(void*)
     14    ptwrite32(unsigned int)
             [0x43]

   This GDB feature is dependent on hardware and operating system
support and requires the Intel Processor Trace decoder library in
version 2.0.0 or newer.


File: gdb.info,  Node: Guile,  Next: Auto-loading extensions,  Prev: Python,  Up: Extending GDB

23.4 Extending GDB using Guile
==============================

You can extend GDB using the Guile implementation of the Scheme
programming language (http://www.gnu.org/software/guile/).  This feature
is available only if GDB was configured using ‘--with-guile’.

* Menu:

* Guile Introduction::     Introduction to Guile scripting in GDB
* Guile Commands::         Accessing Guile from GDB
* Guile API::              Accessing GDB from Guile
* Guile Auto-loading::     Automatically loading Guile code
* Guile Modules::          Guile modules provided by GDB


File: gdb.info,  Node: Guile Introduction,  Next: Guile Commands,  Up: Guile

23.4.1 Guile Introduction
-------------------------

Guile is an implementation of the Scheme programming language and is the
GNU project's official extension language.

   Guile support in GDB follows the Python support in GDB reasonably
closely, so concepts there should carry over.  However, some things are
done differently where it makes sense.

   GDB requires Guile version 3.0, 2.2, or 2.0.

   Guile scripts used by GDB should be installed in
‘DATA-DIRECTORY/guile’, where DATA-DIRECTORY is the data directory as
determined at GDB startup (*note Data Files::).  This directory, known
as the “guile directory”, is automatically added to the Guile Search
Path in order to allow the Guile interpreter to locate all scripts
installed at this location.


File: gdb.info,  Node: Guile Commands,  Next: Guile API,  Prev: Guile Introduction,  Up: Guile

23.4.2 Guile Commands
---------------------

GDB provides two commands for accessing the Guile interpreter:

‘guile-repl’
‘gr’
     The ‘guile-repl’ command can be used to start an interactive Guile
     prompt or “repl”.  To return to GDB, type ‘,q’ or the ‘EOF’
     character (e.g., ‘Ctrl-D’ on an empty prompt).  These commands do
     not take any arguments.

‘guile [SCHEME-EXPRESSION]’
‘gu [SCHEME-EXPRESSION]’
     The ‘guile’ command can be used to evaluate a Scheme expression.

     If given an argument, GDB will pass the argument to the Guile
     interpreter for evaluation.

          (gdb) guile (display (+ 20 3)) (newline)
          23

     The result of the Scheme expression is displayed using normal Guile
     rules.

          (gdb) guile (+ 20 3)
          23

     If you do not provide an argument to ‘guile’, it will act as a
     multi-line command, like ‘define’.  In this case, the Guile script
     is made up of subsequent command lines, given after the ‘guile’
     command.  This command list is terminated using a line containing
     ‘end’.  For example:

          (gdb) guile
          >(display 23)
          >(newline)
          >end
          23

   It is also possible to execute a Guile script from the GDB
interpreter:

‘source script-name’
     The script name must end with ‘.scm’ and GDB must be configured to
     recognize the script language based on filename extension using the
     ‘script-extension’ setting.  *Note Extending GDB: Extending GDB.

‘guile (load "script-name")’
     This method uses the ‘load’ Guile function.  It takes a string
     argument that is the name of the script to load.  See the Guile
     documentation for a description of this function.  (*note
     (guile)Loading::).


File: gdb.info,  Node: Guile API,  Next: Guile Auto-loading,  Prev: Guile Commands,  Up: Guile

23.4.3 Guile API
----------------

You can get quick online help for GDB's Guile API by issuing the command
‘help guile’, or by issuing the command ‘,help’ from an interactive
Guile session.  Furthermore, most Guile procedures provided by GDB have
doc strings which can be obtained with ‘,describe PROCEDURE-NAME’ or ‘,d
PROCEDURE-NAME’ from the Guile interactive prompt.

* Menu:

* Basic Guile::              Basic Guile Functions
* Guile Configuration::      Guile configuration variables
* GDB Scheme Data Types::    Scheme representations of GDB objects
* Guile Exception Handling:: How Guile exceptions are translated
* Values From Inferior In Guile:: Guile representation of values
* Arithmetic In Guile::      Arithmetic in Guile
* Types In Guile::           Guile representation of types
* Guile Pretty Printing API:: Pretty-printing values with Guile
* Selecting Guile Pretty-Printers:: How GDB chooses a pretty-printer
* Writing a Guile Pretty-Printer:: Writing a pretty-printer
* Commands In Guile::        Implementing new commands in Guile
* Parameters In Guile::      Adding new GDB parameters
* Progspaces In Guile::      Program spaces
* Objfiles In Guile::        Object files in Guile
* Frames In Guile::          Accessing inferior stack frames from Guile
* Blocks In Guile::          Accessing blocks from Guile
* Symbols In Guile::         Guile representation of symbols
* Symbol Tables In Guile::   Guile representation of symbol tables
* Breakpoints In Guile::     Manipulating breakpoints using Guile
* Lazy Strings In Guile::    Guile representation of lazy strings
* Architectures In Guile::   Guile representation of architectures
* Disassembly In Guile::     Disassembling instructions from Guile
* I/O Ports in Guile::       GDB I/O ports
* Memory Ports in Guile::    Accessing memory through ports and bytevectors
* Iterators In Guile::       Basic iterator support
* Colors In Guile::          Colorize output with Guile


File: gdb.info,  Node: Basic Guile,  Next: Guile Configuration,  Up: Guile API

23.4.3.1 Basic Guile
....................

At startup, GDB overrides Guile's ‘current-output-port’ and
‘current-error-port’ to print using GDB's output-paging streams.  A
Guile program which outputs to one of these streams may have its output
interrupted by the user (*note Screen Size::).  In this situation, a
Guile ‘signal’ exception is thrown with value ‘SIGINT’.

   Guile's history mechanism uses the same naming as GDB's, namely the
user of dollar-variables (e.g., $1, $2, etc.).  The results of
evaluations in Guile and in GDB are counted separately, ‘$1’ in Guile is
not the same value as ‘$1’ in GDB.

   GDB is not thread-safe.  If your Guile program uses multiple threads,
you must be careful to only call GDB-specific functions in the GDB
thread.

   Some care must be taken when writing Guile code to run in GDB.  Two
things are worth noting in particular:

   • GDB installs handlers for ‘SIGCHLD’ and ‘SIGINT’.  Guile code must
     not override these, or even change the options using ‘sigaction’.
     If your program changes the handling of these signals, GDB will
     most likely stop working correctly.  Note that it is unfortunately
     common for GUI toolkits to install a ‘SIGCHLD’ handler.

   • GDB takes care to mark its internal file descriptors as
     close-on-exec.  However, this cannot be done in a thread-safe way
     on all platforms.  Your Guile programs should be aware of this and
     should both create new file descriptors with the close-on-exec flag
     set and arrange to close unneeded file descriptors before starting
     a child process.

   GDB introduces a new Guile module, named ‘gdb’.  All methods and
classes added by GDB are placed in this module.  GDB does not
automatically ‘import’ the ‘gdb’ module, scripts must do this
themselves.  There are various options for how to import a module, so
GDB leaves the choice of how the ‘gdb’ module is imported to the user.
To simplify interactive use, it is recommended to add one of the
following to your ~/.gdbinit.

     guile (use-modules (gdb))

     guile (use-modules ((gdb) #:renamer (symbol-prefix-proc 'gdb:)))

   Which one to choose depends on your preference.  The second one adds
‘gdb:’ as a prefix to all module functions and variables.

   The rest of this manual assumes the ‘gdb’ module has been imported
without any prefix.  See the Guile documentation for ‘use-modules’ for
more information (*note (guile)Using Guile Modules::).

   Example:

     (gdb) guile (value-type (make-value 1))
     ERROR: Unbound variable: value-type
     Error while executing Scheme code.
     (gdb) guile (use-modules (gdb))
     (gdb) guile (value-type (make-value 1))
     int
     (gdb)

   The ‘(gdb)’ module provides these basic Guile functions.

 -- Scheme Procedure: execute command [#:from-tty boolean]
          [#:to-string boolean]
     Evaluate COMMAND, a string, as a GDB CLI command.  If a GDB
     exception happens while COMMAND runs, it is translated as described
     in *note Guile Exception Handling: Guile Exception Handling.

     FROM-TTY specifies whether GDB ought to consider this command as
     having originated from the user invoking it interactively.  It must
     be a boolean value.  If omitted, it defaults to ‘#f’.

     By default, any output produced by COMMAND is sent to GDB's
     standard output (and to the log output if logging is turned on).
     If the TO-STRING parameter is ‘#t’, then output will be collected
     by ‘execute’ and returned as a string.  The default is ‘#f’, in
     which case the return value is unspecified.  If TO-STRING is ‘#t’,
     the GDB virtual terminal will be temporarily set to unlimited width
     and height, and its pagination will be disabled; *note Screen
     Size::.

 -- Scheme Procedure: history-ref number
     Return a value from GDB's value history (*note Value History::).
     The NUMBER argument indicates which history element to return.  If
     NUMBER is negative, then GDB will take its absolute value and count
     backward from the last element (i.e., the most recent element) to
     find the value to return.  If NUMBER is zero, then GDB will return
     the most recent element.  If the element specified by NUMBER
     doesn't exist in the value history, a ‘gdb:error’ exception will be
     raised.

     If no exception is raised, the return value is always an instance
     of ‘<gdb:value>’ (*note Values From Inferior In Guile::).

     _Note:_ GDB's value history is independent of Guile's.  ‘$1’ in
     GDB's value history contains the result of evaluating an expression
     from GDB's command line and ‘$1’ from Guile's history contains the
     result of evaluating an expression from Guile's command line.

 -- Scheme Procedure: history-append! value
     Append VALUE, an instance of ‘<gdb:value>’, to GDB's value history.
     Return its index in the history.

     Putting into history values returned by Guile extensions will allow
     the user convenient access to those values via CLI history
     facilities.

 -- Scheme Procedure: parse-and-eval expression
     Parse EXPRESSION as an expression in the current language, evaluate
     it, and return the result as a ‘<gdb:value>’.  The EXPRESSION must
     be a string.

     This function can be useful when implementing a new command (*note
     Commands In Guile::), as it provides a way to parse the command's
     arguments as an expression.  It is also is useful when computing
     values.  For example, it is the only way to get the value of a
     convenience variable (*note Convenience Vars::) as a ‘<gdb:value>’.


File: gdb.info,  Node: Guile Configuration,  Next: GDB Scheme Data Types,  Prev: Basic Guile,  Up: Guile API

23.4.3.2 Guile Configuration
............................

GDB provides these Scheme functions to access various configuration
parameters.

 -- Scheme Procedure: data-directory
     Return a string containing GDB's data directory.  This directory
     contains GDB's ancillary files.

 -- Scheme Procedure: guile-data-directory
     Return a string containing GDB's Guile data directory.  This
     directory contains the Guile modules provided by GDB.

 -- Scheme Procedure: gdb-version
     Return a string containing the GDB version.

 -- Scheme Procedure: host-config
     Return a string containing the host configuration.  This is the
     string passed to ‘--host’ when GDB was configured.

 -- Scheme Procedure: target-config
     Return a string containing the target configuration.  This is the
     string passed to ‘--target’ when GDB was configured.


File: gdb.info,  Node: GDB Scheme Data Types,  Next: Guile Exception Handling,  Prev: Guile Configuration,  Up: Guile API

23.4.3.3 GDB Scheme Data Types
..............................

The values exposed by GDB to Guile are known as “GDB objects”.  There
are several kinds of GDB object, and each is disjoint from all other
types known to Guile.

 -- Scheme Procedure: gdb-object-kind object
     Return the kind of the GDB object, e.g., ‘<gdb:breakpoint>’, as a
     symbol.

   GDB defines the following object types:

‘<gdb:arch>’
     *Note Architectures In Guile::.

‘<gdb:block>’
     *Note Blocks In Guile::.

‘<gdb:block-symbols-iterator>’
     *Note Blocks In Guile::.

‘<gdb:breakpoint>’
     *Note Breakpoints In Guile::.

‘<gdb:command>’
     *Note Commands In Guile::.

‘<gdb:exception>’
     *Note Guile Exception Handling::.

‘<gdb:frame>’
     *Note Frames In Guile::.

‘<gdb:iterator>’
     *Note Iterators In Guile::.

‘<gdb:lazy-string>’
     *Note Lazy Strings In Guile::.

‘<gdb:objfile>’
     *Note Objfiles In Guile::.

‘<gdb:parameter>’
     *Note Parameters In Guile::.

‘<gdb:pretty-printer>’
     *Note Guile Pretty Printing API::.

‘<gdb:pretty-printer-worker>’
     *Note Guile Pretty Printing API::.

‘<gdb:progspace>’
     *Note Progspaces In Guile::.

‘<gdb:symbol>’
     *Note Symbols In Guile::.

‘<gdb:symtab>’
     *Note Symbol Tables In Guile::.

‘<gdb:sal>’
     *Note Symbol Tables In Guile::.

‘<gdb:type>’
     *Note Types In Guile::.

‘<gdb:field>’
     *Note Types In Guile::.

‘<gdb:value>’
     *Note Values From Inferior In Guile::.

‘<gdb:color>’
     *Note Colors In Guile::.

   The following GDB objects are managed internally so that the Scheme
function ‘eq?’ may be applied to them.

‘<gdb:arch>’
‘<gdb:block>’
‘<gdb:breakpoint>’
‘<gdb:frame>’
‘<gdb:objfile>’
‘<gdb:progspace>’
‘<gdb:symbol>’
‘<gdb:symtab>’
‘<gdb:type>’


File: gdb.info,  Node: Guile Exception Handling,  Next: Values From Inferior In Guile,  Prev: GDB Scheme Data Types,  Up: Guile API

23.4.3.4 Guile Exception Handling
.................................

When executing the ‘guile’ command, Guile exceptions uncaught within the
Guile code are translated to calls to the GDB error-reporting mechanism.
If the command that called ‘guile’ does not handle the error, GDB will
terminate it and report the error according to the setting of the ‘guile
print-stack’ parameter.

   The ‘guile print-stack’ parameter has three settings:

‘none’
     Nothing is printed.

‘message’
     An error message is printed containing the Guile exception name,
     the associated value, and the Guile call stack backtrace at the
     point where the exception was raised.  Example:

          (gdb) guile (display foo)
          ERROR: In procedure memoize-variable-access!:
          ERROR: Unbound variable: foo
          Error while executing Scheme code.

‘full’
     In addition to an error message a full backtrace is printed.

          (gdb) set guile print-stack full
          (gdb) guile (display foo)
          Guile Backtrace:
          In ice-9/boot-9.scm:
           157: 10 [catch #t #<catch-closure 2c76e20> ...]
          In unknown file:
             ?: 9 [apply-smob/1 #<catch-closure 2c76e20>]
          In ice-9/boot-9.scm:
           157: 8 [catch #t #<catch-closure 2c76d20> ...]
          In unknown file:
             ?: 7 [apply-smob/1 #<catch-closure 2c76d20>]
             ?: 6 [call-with-input-string "(display foo)" ...]
          In ice-9/boot-9.scm:
          2320: 5 [save-module-excursion #<procedure 2c2dc30 ... ()>]
          In ice-9/eval-string.scm:
            44: 4 [read-and-eval #<input: string 27cb410> #:lang ...]
            37: 3 [lp (display foo)]
          In ice-9/eval.scm:
           387: 2 [eval # ()]
           393: 1 [eval #<memoized foo> ()]
          In unknown file:
             ?: 0 [memoize-variable-access! #<memoized foo> ...]

          ERROR: In procedure memoize-variable-access!:
          ERROR: Unbound variable: foo
          Error while executing Scheme code.

   GDB errors that happen in GDB commands invoked by Guile code are
converted to Guile exceptions.  The type of the Guile exception depends
on the error.

   Guile procedures provided by GDB can throw the standard Guile
exceptions like ‘wrong-type-arg’ and ‘out-of-range’.

   User interrupt (via ‘C-c’ or by typing ‘q’ at a pagination prompt) is
translated to a Guile ‘signal’ exception with value ‘SIGINT’.

   GDB Guile procedures can also throw these exceptions:

‘gdb:error’
     This exception is a catch-all for errors generated from within GDB.

‘gdb:invalid-object’
     This exception is thrown when accessing Guile objects that wrap
     underlying GDB objects have become invalid.  For example, a
     ‘<gdb:breakpoint>’ object becomes invalid if the user deletes it
     from the command line.  The object still exists in Guile, but the
     object it represents is gone.  Further operations on this
     breakpoint will throw this exception.

‘gdb:memory-error’
     This exception is thrown when an operation tried to access invalid
     memory in the inferior.

‘gdb:pp-type-error’
     This exception is thrown when a Guile pretty-printer passes a bad
     object to GDB.

   The following exception-related procedures are provided by the
‘(gdb)’ module.

 -- Scheme Procedure: make-exception key args
     Return a ‘<gdb:exception>’ object given by its KEY and ARGS, which
     are the standard Guile parameters of an exception.  See the Guile
     documentation for more information (*note (guile)Exceptions::).

 -- Scheme Procedure: exception? object
     Return ‘#t’ if OBJECT is a ‘<gdb:exception>’ object.  Otherwise
     return ‘#f’.

 -- Scheme Procedure: exception-key exception
     Return the ARGS field of a ‘<gdb:exception>’ object.

 -- Scheme Procedure: exception-args exception
     Return the ARGS field of a ‘<gdb:exception>’ object.


File: gdb.info,  Node: Values From Inferior In Guile,  Next: Arithmetic In Guile,  Prev: Guile Exception Handling,  Up: Guile API

23.4.3.5 Values From Inferior In Guile
......................................

GDB provides values it obtains from the inferior program in an object of
type ‘<gdb:value>’.  GDB uses this object for its internal bookkeeping
of the inferior's values, and for fetching values when necessary.

   GDB does not memoize ‘<gdb:value>’ objects.  ‘make-value’ always
returns a fresh object.

     (gdb) guile (eq? (make-value 1) (make-value 1))
     $1 = #f
     (gdb) guile (equal? (make-value 1) (make-value 1))
     $1 = #t

   A ‘<gdb:value>’ that represents a function can be executed via
inferior function call with ‘value-call’.  Any arguments provided to the
call must match the function's prototype, and must be provided in the
order specified by that prototype.

   For example, ‘some-val’ is a ‘<gdb:value>’ instance representing a
function that takes two integers as arguments.  To execute this
function, call it like so:

     (define result (value-call some-val 10 20))

   Any values returned from a function call are ‘<gdb:value>’ objects.

   Note: Unlike Python scripting in GDB, inferior values that are simple
scalars cannot be used directly in Scheme expressions that are valid for
the value's data type.  For example, ‘(+ (parse-and-eval "int_variable")
2)’ does not work.  And inferior values that are structures or instances
of some class cannot be accessed using any special syntax, instead
‘value-field’ must be used.

   The following value-related procedures are provided by the ‘(gdb)’
module.

 -- Scheme Procedure: value? object
     Return ‘#t’ if OBJECT is a ‘<gdb:value>’ object.  Otherwise return
     ‘#f’.

 -- Scheme Procedure: make-value value [#:type type]
     Many Scheme values can be converted directly to a ‘<gdb:value>’
     with this procedure.  If TYPE is specified, the result is a value
     of this type, and if VALUE can't be represented with this type an
     exception is thrown.  Otherwise the type of the result is
     determined from VALUE as described below.

     *Note Architectures In Guile::, for a list of the builtin types for
     an architecture.

     Here's how Scheme values are converted when TYPE argument to
     ‘make-value’ is not specified:

     Scheme boolean
          A Scheme boolean is converted the boolean type for the current
          language.

     Scheme integer
          A Scheme integer is converted to the first of a C ‘int’,
          ‘unsigned int’, ‘long’, ‘unsigned long’, ‘long long’ or
          ‘unsigned long long’ type for the current architecture that
          can represent the value.

          If the Scheme integer cannot be represented as a target
          integer an ‘out-of-range’ exception is thrown.

     Scheme real
          A Scheme real is converted to the C ‘double’ type for the
          current architecture.

     Scheme string
          A Scheme string is converted to a string in the current target
          language using the current target encoding.  Characters that
          cannot be represented in the current target encoding are
          replaced with the corresponding escape sequence.  This is
          Guile's ‘SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE’ conversion
          strategy (*note (guile)Strings::).

          Passing TYPE is not supported in this case, if it is provided
          a ‘wrong-type-arg’ exception is thrown.

     ‘<gdb:lazy-string>’
          If VALUE is a ‘<gdb:lazy-string>’ object (*note Lazy Strings
          In Guile::), then the ‘lazy-string->value’ procedure is
          called, and its result is used.

          Passing TYPE is not supported in this case, if it is provided
          a ‘wrong-type-arg’ exception is thrown.

     Scheme bytevector
          If VALUE is a Scheme bytevector and TYPE is provided, VALUE
          must be the same size, in bytes, of values of type TYPE, and
          the result is essentially created by using ‘memcpy’.

          If VALUE is a Scheme bytevector and TYPE is not provided, the
          result is an array of type ‘uint8’ of the same length.

 -- Scheme Procedure: value-optimized-out? value
     Return ‘#t’ if the compiler optimized out VALUE, thus it is not
     available for fetching from the inferior.  Otherwise return ‘#f’.

 -- Scheme Procedure: value-address value
     If VALUE is addressable, returns a ‘<gdb:value>’ object
     representing the address.  Otherwise, ‘#f’ is returned.

 -- Scheme Procedure: value-type value
     Return the type of VALUE as a ‘<gdb:type>’ object (*note Types In
     Guile::).

 -- Scheme Procedure: value-dynamic-type value
     Return the dynamic type of VALUE.  This uses C++ run-time type
     information (RTTI) to determine the dynamic type of the value.  If
     the value is of class type, it will return the class in which the
     value is embedded, if any.  If the value is of pointer or reference
     to a class type, it will compute the dynamic type of the referenced
     object, and return a pointer or reference to that type,
     respectively.  In all other cases, it will return the value's
     static type.

     Note that this feature will only work when debugging a C++ program
     that includes RTTI for the object in question.  Otherwise, it will
     just return the static type of the value as in ‘ptype foo’.  *Note
     ptype: Symbols.

 -- Scheme Procedure: value-cast value type
     Return a new instance of ‘<gdb:value>’ that is the result of
     casting VALUE to the type described by TYPE, which must be a
     ‘<gdb:type>’ object.  If the cast cannot be performed for some
     reason, this method throws an exception.

 -- Scheme Procedure: value-dynamic-cast value type
     Like ‘value-cast’, but works as if the C++ ‘dynamic_cast’ operator
     were used.  Consult a C++ reference for details.

 -- Scheme Procedure: value-reinterpret-cast value type
     Like ‘value-cast’, but works as if the C++ ‘reinterpret_cast’
     operator were used.  Consult a C++ reference for details.

 -- Scheme Procedure: value-dereference value
     For pointer data types, this method returns a new ‘<gdb:value>’
     object whose contents is the object pointed to by VALUE.  For
     example, if ‘foo’ is a C pointer to an ‘int’, declared in your C
     program as

          int *foo;

     then you can use the corresponding ‘<gdb:value>’ to access what
     ‘foo’ points to like this:

          (define bar (value-dereference foo))

     The result ‘bar’ will be a ‘<gdb:value>’ object holding the value
     pointed to by ‘foo’.

     A similar function ‘value-referenced-value’ exists which also
     returns ‘<gdb:value>’ objects corresponding to the values pointed
     to by pointer values (and additionally, values referenced by
     reference values).  However, the behavior of ‘value-dereference’
     differs from ‘value-referenced-value’ by the fact that the behavior
     of ‘value-dereference’ is identical to applying the C unary
     operator ‘*’ on a given value.  For example, consider a reference
     to a pointer ‘ptrref’, declared in your C++ program as

          typedef int *intptr;
          ...
          int val = 10;
          intptr ptr = &val;
          intptr &ptrref = ptr;

     Though ‘ptrref’ is a reference value, one can apply the method
     ‘value-dereference’ to the ‘<gdb:value>’ object corresponding to it
     and obtain a ‘<gdb:value>’ which is identical to that corresponding
     to ‘val’.  However, if you apply the method
     ‘value-referenced-value’, the result would be a ‘<gdb:value>’
     object identical to that corresponding to ‘ptr’.

          (define scm-ptrref (parse-and-eval "ptrref"))
          (define scm-val (value-dereference scm-ptrref))
          (define scm-ptr (value-referenced-value scm-ptrref))

     The ‘<gdb:value>’ object ‘scm-val’ is identical to that
     corresponding to ‘val’, and ‘scm-ptr’ is identical to that
     corresponding to ‘ptr’.  In general, ‘value-dereference’ can be
     applied whenever the C unary operator ‘*’ can be applied to the
     corresponding C value.  For those cases where applying both
     ‘value-dereference’ and ‘value-referenced-value’ is allowed, the
     results obtained need not be identical (as we have seen in the
     above example).  The results are however identical when applied on
     ‘<gdb:value>’ objects corresponding to pointers (‘<gdb:value>’
     objects with type code ‘TYPE_CODE_PTR’) in a C/C++ program.

 -- Scheme Procedure: value-referenced-value value
     For pointer or reference data types, this method returns a new
     ‘<gdb:value>’ object corresponding to the value referenced by the
     pointer/reference value.  For pointer data types,
     ‘value-dereference’ and ‘value-referenced-value’ produce identical
     results.  The difference between these methods is that
     ‘value-dereference’ cannot get the values referenced by reference
     values.  For example, consider a reference to an ‘int’, declared in
     your C++ program as

          int val = 10;
          int &ref = val;

     then applying ‘value-dereference’ to the ‘<gdb:value>’ object
     corresponding to ‘ref’ will result in an error, while applying
     ‘value-referenced-value’ will result in a ‘<gdb:value>’ object
     identical to that corresponding to ‘val’.

          (define scm-ref (parse-and-eval "ref"))
          (define err-ref (value-dereference scm-ref))      ;; error
          (define scm-val (value-referenced-value scm-ref)) ;; ok

     The ‘<gdb:value>’ object ‘scm-val’ is identical to that
     corresponding to ‘val’.

 -- Scheme Procedure: value-reference-value value
     Return a new ‘<gdb:value>’ object which is a reference to the value
     encapsulated by ‘<gdb:value>’ object VALUE.

 -- Scheme Procedure: value-rvalue-reference-value value
     Return a new ‘<gdb:value>’ object which is an rvalue reference to
     the value encapsulated by ‘<gdb:value>’ object VALUE.

 -- Scheme Procedure: value-const-value value
     Return a new ‘<gdb:value>’ object which is a ‘const’ version of
     ‘<gdb:value>’ object VALUE.

 -- Scheme Procedure: value-field value field-name
     Return field FIELD-NAME from ‘<gdb:value>’ object VALUE.

 -- Scheme Procedure: value-subscript value index
     Return the value of array VALUE at index INDEX.  The VALUE argument
     must be a subscriptable ‘<gdb:value>’ object.

 -- Scheme Procedure: value-call value arg-list
     Perform an inferior function call, taking VALUE as a pointer to the
     function to call.  Each element of list ARG-LIST must be a
     <gdb:value> object or an object that can be converted to a value.
     The result is the value returned by the function.

 -- Scheme Procedure: value->bool value
     Return the Scheme boolean representing ‘<gdb:value>’ VALUE.  The
     value must be "integer like".  Pointers are ok.

 -- Scheme Procedure: value->integer
     Return the Scheme integer representing ‘<gdb:value>’ VALUE.  The
     value must be "integer like".  Pointers are ok.

 -- Scheme Procedure: value->real
     Return the Scheme real number representing ‘<gdb:value>’ VALUE.
     The value must be a number.

 -- Scheme Procedure: value->bytevector
     Return a Scheme bytevector with the raw contents of ‘<gdb:value>’
     VALUE.  No transformation, endian or otherwise, is performed.

 -- Scheme Procedure: value->string value [#:encoding encoding]
          [#:errors errors] [#:length length]
     If VALUE> represents a string, then this method converts the
     contents to a Guile string.  Otherwise, this method will throw an
     exception.

     Values are interpreted as strings according to the rules of the
     current language.  If the optional length argument is given, the
     string will be converted to that length, and will include any
     embedded zeroes that the string may contain.  Otherwise, for
     languages where the string is zero-terminated, the entire string
     will be converted.

     For example, in C-like languages, a value is a string if it is a
     pointer to or an array of characters or ints of type ‘wchar_t’,
     ‘char16_t’, or ‘char32_t’.

     If the optional ENCODING argument is given, it must be a string
     naming the encoding of the string in the ‘<gdb:value>’, such as
     ‘"ascii"’, ‘"iso-8859-6"’ or ‘"utf-8"’.  It accepts the same
     encodings as the corresponding argument to Guile's
     ‘scm_from_stringn’ function, and the Guile codec machinery will be
     used to convert the string.  If ENCODING is not given, or if
     ENCODING is the empty string, then either the ‘target-charset’
     (*note Character Sets::) will be used, or a language-specific
     encoding will be used, if the current language is able to supply
     one.

     The optional ERRORS argument is one of ‘#f’, ‘error’ or
     ‘substitute’.  ‘error’ and ‘substitute’ must be symbols.  If ERRORS
     is not specified, or if its value is ‘#f’, then the default
     conversion strategy is used, which is set with the Scheme function
     ‘set-port-conversion-strategy!’.  If the value is ‘'error’ then an
     exception is thrown if there is any conversion error.  If the value
     is ‘'substitute’ then any conversion error is replaced with
     question marks.  *Note (guile)Strings::.

     If the optional LENGTH argument is given, the string will be
     fetched and converted to the given length.  The length must be a
     Scheme integer and not a ‘<gdb:value>’ integer.

 -- Scheme Procedure: value->lazy-string value [#:encoding encoding]
          [#:length length]
     If this ‘<gdb:value>’ represents a string, then this method
     converts VALUE to a ‘<gdb:lazy-string’ (*note Lazy Strings In
     Guile::).  Otherwise, this method will throw an exception.

     If the optional ENCODING argument is given, it must be a string
     naming the encoding of the ‘<gdb:lazy-string’.  Some examples are:
     ‘"ascii"’, ‘"iso-8859-6"’ or ‘"utf-8"’.  If the ENCODING argument
     is an encoding that GDB does not recognize, GDB will raise an
     error.

     When a lazy string is printed, the GDB encoding machinery is used
     to convert the string during printing.  If the optional ENCODING
     argument is not provided, or is an empty string, GDB will
     automatically select the encoding most suitable for the string
     type.  For further information on encoding in GDB please see *note
     Character Sets::.

     If the optional LENGTH argument is given, the string will be
     fetched and encoded to the length of characters specified.  If the
     LENGTH argument is not provided, the string will be fetched and
     encoded until a null of appropriate width is found.  The length
     must be a Scheme integer and not a ‘<gdb:value>’ integer.

 -- Scheme Procedure: value-lazy? value
     Return ‘#t’ if VALUE has not yet been fetched from the inferior.
     Otherwise return ‘#f’.  GDB does not fetch values until necessary,
     for efficiency.  For example:

          (define myval (parse-and-eval "somevar"))

     The value of ‘somevar’ is not fetched at this time.  It will be
     fetched when the value is needed, or when the ‘fetch-lazy’
     procedure is invoked.

 -- Scheme Procedure: make-lazy-value type address
     Return a ‘<gdb:value>’ that will be lazily fetched from the target.
     The object of type ‘<gdb:type>’ whose value to fetch is specified
     by its TYPE and its target memory ADDRESS, which is a Scheme
     integer.

 -- Scheme Procedure: value-fetch-lazy! value
     If VALUE is a lazy value (‘(value-lazy? value)’ is ‘#t’), then the
     value is fetched from the inferior.  Any errors that occur in the
     process will produce a Guile exception.

     If VALUE is not a lazy value, this method has no effect.

     The result of this function is unspecified.

 -- Scheme Procedure: value-print value
     Return the string representation (print form) of ‘<gdb:value>’
     VALUE.


File: gdb.info,  Node: Arithmetic In Guile,  Next: Types In Guile,  Prev: Values From Inferior In Guile,  Up: Guile API

23.4.3.6 Arithmetic In Guile
............................

The ‘(gdb)’ module provides several functions for performing arithmetic
on ‘<gdb:value>’ objects.  The arithmetic is performed as if it were
done by the target, and therefore has target semantics which are not
necessarily those of Scheme.  For example operations work with a fixed
precision, not the arbitrary precision of Scheme.

   Wherever a function takes an integer or pointer as an operand, GDB
will convert appropriate Scheme values to perform the operation.

 -- Scheme Procedure: value-add a b

 -- Scheme Procedure: value-sub a b

 -- Scheme Procedure: value-mul a b

 -- Scheme Procedure: value-div a b

 -- Scheme Procedure: value-rem a b

 -- Scheme Procedure: value-mod a b

 -- Scheme Procedure: value-pow a b

 -- Scheme Procedure: value-not a

 -- Scheme Procedure: value-neg a

 -- Scheme Procedure: value-pos a

 -- Scheme Procedure: value-abs a

 -- Scheme Procedure: value-lsh a b

 -- Scheme Procedure: value-rsh a b

 -- Scheme Procedure: value-min a b

 -- Scheme Procedure: value-max a b

 -- Scheme Procedure: value-lognot a

 -- Scheme Procedure: value-logand a b

 -- Scheme Procedure: value-logior a b

 -- Scheme Procedure: value-logxor a b

 -- Scheme Procedure: value=? a b

 -- Scheme Procedure: value<? a b

 -- Scheme Procedure: value<=? a b

 -- Scheme Procedure: value>? a b

 -- Scheme Procedure: value>=? a b

   Scheme does not provide a ‘not-equal’ function, and thus Guile
support in GDB does not either.


File: gdb.info,  Node: Types In Guile,  Next: Guile Pretty Printing API,  Prev: Arithmetic In Guile,  Up: Guile API

23.4.3.7 Types In Guile
.......................

GDB represents types from the inferior in objects of type ‘<gdb:type>’.

   The following type-related procedures are provided by the ‘(gdb)’
module.

 -- Scheme Procedure: type? object
     Return ‘#t’ if OBJECT is an object of type ‘<gdb:type>’.  Otherwise
     return ‘#f’.

 -- Scheme Procedure: lookup-type name [#:block block]
     This function looks up a type by its NAME, which must be a string.

     If BLOCK is given, it is an object of type ‘<gdb:block>’, and NAME
     is looked up in that scope.  Otherwise, it is searched for
     globally.

     Ordinarily, this function will return an instance of ‘<gdb:type>’.
     If the named type cannot be found, it will throw an exception.

 -- Scheme Procedure: type-code type
     Return the type code of TYPE.  The type code will be one of the
     ‘TYPE_CODE_’ constants defined below.

 -- Scheme Procedure: type-tag type
     Return the tag name of TYPE.  The tag name is the name after
     ‘struct’, ‘union’, or ‘enum’ in C and C++; not all languages have
     this concept.  If this type has no tag name, then ‘#f’ is returned.

 -- Scheme Procedure: type-name type
     Return the name of TYPE.  If this type has no name, then ‘#f’ is
     returned.

 -- Scheme Procedure: type-print-name type
     Return the print name of TYPE.  This returns something even for
     anonymous types.  For example, for an anonymous C struct ‘"struct
     {...}"’ is returned.

 -- Scheme Procedure: type-sizeof type
     Return the size of this type, in target ‘char’ units.  Usually, a
     target's ‘char’ type will be an 8-bit byte.  However, on some
     unusual platforms, this type may have a different size.

 -- Scheme Procedure: type-strip-typedefs type
     Return a new ‘<gdb:type>’ that represents the real type of TYPE,
     after removing all layers of typedefs.

 -- Scheme Procedure: type-array type n1 [n2]
     Return a new ‘<gdb:type>’ object which represents an array of this
     type.  If one argument is given, it is the inclusive upper bound of
     the array; in this case the lower bound is zero.  If two arguments
     are given, the first argument is the lower bound of the array, and
     the second argument is the upper bound of the array.  An array's
     length must not be negative, but the bounds can be.

 -- Scheme Procedure: type-vector type n1 [n2]
     Return a new ‘<gdb:type>’ object which represents a vector of this
     type.  If one argument is given, it is the inclusive upper bound of
     the vector; in this case the lower bound is zero.  If two arguments
     are given, the first argument is the lower bound of the vector, and
     the second argument is the upper bound of the vector.  A vector's
     length must not be negative, but the bounds can be.

     The difference between an ‘array’ and a ‘vector’ is that arrays
     behave like in C: when used in expressions they decay to a pointer
     to the first element whereas vectors are treated as first class
     values.

 -- Scheme Procedure: type-pointer type
     Return a new ‘<gdb:type>’ object which represents a pointer to
     TYPE.

 -- Scheme Procedure: type-range type
     Return a list of two elements: the low bound and high bound of
     TYPE.  If TYPE does not have a range, an exception is thrown.

 -- Scheme Procedure: type-reference type
     Return a new ‘<gdb:type>’ object which represents a reference to
     TYPE.

 -- Scheme Procedure: type-target type
     Return a new ‘<gdb:type>’ object which represents the target type
     of TYPE.

     For a pointer type, the target type is the type of the pointed-to
     object.  For an array type (meaning C-like arrays), the target type
     is the type of the elements of the array.  For a function or method
     type, the target type is the type of the return value.  For a
     complex type, the target type is the type of the elements.  For a
     typedef, the target type is the aliased type.

     If the type does not have a target, this method will throw an
     exception.

 -- Scheme Procedure: type-const type
     Return a new ‘<gdb:type>’ object which represents a
     ‘const’-qualified variant of TYPE.

 -- Scheme Procedure: type-volatile type
     Return a new ‘<gdb:type>’ object which represents a
     ‘volatile’-qualified variant of TYPE.

 -- Scheme Procedure: type-unqualified type
     Return a new ‘<gdb:type>’ object which represents an unqualified
     variant of TYPE.  That is, the result is neither ‘const’ nor
     ‘volatile’.

 -- Scheme Procedure: type-num-fields
     Return the number of fields of ‘<gdb:type>’ TYPE.

 -- Scheme Procedure: type-fields type
     Return the fields of TYPE as a list.  For structure and union
     types, ‘fields’ has the usual meaning.  Range types have two
     fields, the minimum and maximum values.  Enum types have one field
     per enum constant.  Function and method types have one field per
     parameter.  The base types of C++ classes are also represented as
     fields.  If the type has no fields, or does not fit into one of
     these categories, an empty list will be returned.  *Note Fields of
     a type in Guile::.

 -- Scheme Procedure: make-field-iterator type
     Return the fields of TYPE as a <gdb:iterator> object.  *Note
     Iterators In Guile::.

 -- Scheme Procedure: type-field type field-name
     Return field named FIELD-NAME in TYPE.  The result is an object of
     type ‘<gdb:field>’.  *Note Fields of a type in Guile::.  If the
     type does not have fields, or FIELD-NAME is not a field of TYPE, an
     exception is thrown.

     For example, if ‘some-type’ is a ‘<gdb:type>’ instance holding a
     structure type, you can access its ‘foo’ field with:

          (define bar (type-field some-type "foo"))

     ‘bar’ will be a ‘<gdb:field>’ object.

 -- Scheme Procedure: type-has-field? type name
     Return ‘#t’ if ‘<gdb:type>’ TYPE has field named NAME.  Otherwise
     return ‘#f’.

   Each type has a code, which indicates what category this type falls
into.  The available type categories are represented by constants
defined in the ‘(gdb)’ module:

‘TYPE_CODE_PTR’
     The type is a pointer.

‘TYPE_CODE_ARRAY’
     The type is an array.

‘TYPE_CODE_STRUCT’
     The type is a structure.

‘TYPE_CODE_UNION’
     The type is a union.

‘TYPE_CODE_ENUM’
     The type is an enum.

‘TYPE_CODE_FLAGS’
     A bit flags type, used for things such as status registers.

‘TYPE_CODE_FUNC’
     The type is a function.

‘TYPE_CODE_INT’
     The type is an integer type.

‘TYPE_CODE_FLT’
     A floating point type.

‘TYPE_CODE_VOID’
     The special type ‘void’.

‘TYPE_CODE_SET’
     A Pascal set type.

‘TYPE_CODE_RANGE’
     A range type, that is, an integer type with bounds.

‘TYPE_CODE_STRING’
     A string type.  Note that this is only used for certain languages
     with language-defined string types; C strings are not represented
     this way.

‘TYPE_CODE_BITSTRING’
     A string of bits.  It is deprecated.

‘TYPE_CODE_ERROR’
     An unknown or erroneous type.

‘TYPE_CODE_METHOD’
     A method type, as found in C++.

‘TYPE_CODE_METHODPTR’
     A pointer-to-member-function.

‘TYPE_CODE_MEMBERPTR’
     A pointer-to-member.

‘TYPE_CODE_REF’
     A reference type.

‘TYPE_CODE_RVALUE_REF’
     A C++11 rvalue reference type.

‘TYPE_CODE_CHAR’
     A character type.

‘TYPE_CODE_BOOL’
     A boolean type.

‘TYPE_CODE_COMPLEX’
     A complex float type.

‘TYPE_CODE_TYPEDEF’
     A typedef to some other type.

‘TYPE_CODE_NAMESPACE’
     A C++ namespace.

‘TYPE_CODE_DECFLOAT’
     A decimal floating point type.

‘TYPE_CODE_INTERNAL_FUNCTION’
     A function internal to GDB.  This is the type used to represent
     convenience functions (*note Convenience Funs::).

‘gdb.TYPE_CODE_XMETHOD’
     A method internal to GDB.  This is the type used to represent
     xmethods (*note Writing an Xmethod::).

‘gdb.TYPE_CODE_FIXED_POINT’
     A fixed-point number.

‘gdb.TYPE_CODE_NAMESPACE’
     A Fortran namelist.

   Further support for types is provided in the ‘(gdb types)’ Guile
module (*note Guile Types Module::).

   Each field is represented as an object of type ‘<gdb:field>’.

   The following field-related procedures are provided by the ‘(gdb)’
module:

 -- Scheme Procedure: field? object
     Return ‘#t’ if OBJECT is an object of type ‘<gdb:field>’.
     Otherwise return ‘#f’.

 -- Scheme Procedure: field-name field
     Return the name of the field, or ‘#f’ for anonymous fields.

 -- Scheme Procedure: field-type field
     Return the type of the field.  This is usually an instance of
     ‘<gdb:type>’, but it can be ‘#f’ in some situations.

 -- Scheme Procedure: field-enumval field
     Return the enum value represented by ‘<gdb:field>’ FIELD.

 -- Scheme Procedure: field-bitpos field
     Return the bit position of ‘<gdb:field>’ FIELD.  This attribute is
     not available for ‘static’ fields (as in C++).

 -- Scheme Procedure: field-bitsize field
     If the field is packed, or is a bitfield, return the size of
     ‘<gdb:field>’ FIELD in bits.  Otherwise, zero is returned; in which
     case the field's size is given by its type.

 -- Scheme Procedure: field-artificial? field
     Return ‘#t’ if the field is artificial, usually meaning that it was
     provided by the compiler and not the user.  Otherwise return ‘#f’.

 -- Scheme Procedure: field-base-class? field
     Return ‘#t’ if the field represents a base class of a C++
     structure.  Otherwise return ‘#f’.

