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

Copyright (C) 1988-2024 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 15.1.

   Copyright (C) 1988-2024 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: Configurations,  Next: Controlling GDB,  Prev: Remote Debugging,  Up: Top

21 Configuration-Specific Information
*************************************

While nearly all GDB commands are available for all native and cross
versions of the debugger, there are some exceptions.  This chapter
describes things that are only available in certain configurations.

   There are three major categories of configurations: native
configurations, where the host and target are the same, embedded
operating system configurations, which are usually the same for several
different processor architectures, and bare embedded processors, which
are quite different from each other.

* Menu:

* Native::
* Embedded OS::
* Embedded Processors::
* Architectures::


File: gdb.info,  Node: Native,  Next: Embedded OS,  Up: Configurations

21.1 Native
===========

This section describes details specific to particular native
configurations.

* Menu:

* BSD libkvm Interface::        Debugging BSD kernel memory images
* Process Information::         Process information
* DJGPP Native::                Features specific to the DJGPP port
* Cygwin Native::               Features specific to the Cygwin port
* Hurd Native::                 Features specific to GNU Hurd
* Darwin::                      Features specific to Darwin
* FreeBSD::                     Features specific to FreeBSD


File: gdb.info,  Node: BSD libkvm Interface,  Next: Process Information,  Up: Native

21.1.1 BSD libkvm Interface
---------------------------

BSD-derived systems (FreeBSD/NetBSD/OpenBSD) have a kernel memory
interface that provides a uniform interface for accessing kernel virtual
memory images, including live systems and crash dumps.  GDB uses this
interface to allow you to debug live kernels and kernel crash dumps on
many native BSD configurations.  This is implemented as a special 'kvm'
debugging target.  For debugging a live system, load the currently
running kernel into GDB and connect to the 'kvm' target:

     (gdb) target kvm

   For debugging crash dumps, provide the file name of the crash dump as
an argument:

     (gdb) target kvm /var/crash/bsd.0

   Once connected to the 'kvm' target, the following commands are
available:

'kvm pcb'
     Set current context from the "Process Control Block" (PCB) address.

'kvm proc'
     Set current context from proc address.  This command isn't
     available on modern FreeBSD systems.


File: gdb.info,  Node: Process Information,  Next: DJGPP Native,  Prev: BSD libkvm Interface,  Up: Native

21.1.2 Process Information
--------------------------

Some operating systems provide interfaces to fetch additional
information about running processes beyond memory and per-thread
register state.  If GDB is configured for an operating system with a
supported interface, the command 'info proc' is available to report
information about the process running your program, or about any process
running on your system.

   One supported interface is a facility called '/proc' that can be used
to examine the image of a running process using file-system subroutines.
This facility is supported on GNU/Linux and Solaris systems.

   On FreeBSD and NetBSD systems, system control nodes are used to query
process information.

   In addition, some systems may provide additional process information
in core files.  Note that a core file may include a subset of the
information available from a live process.  Process information is
currently available from cores created on GNU/Linux and FreeBSD systems.

'info proc'
'info proc PROCESS-ID'
     Summarize available information about a process.  If a process ID
     is specified by PROCESS-ID, display information about that process;
     otherwise display information about the program being debugged.
     The summary includes the debugged process ID, the command line used
     to invoke it, its current working directory, and its executable
     file's absolute file name.

     On some systems, PROCESS-ID can be of the form '[PID]/TID' which
     specifies a certain thread ID within a process.  If the optional
     PID part is missing, it means a thread from the process being
     debugged (the leading '/' still needs to be present, or else GDB
     will interpret the number as a process ID rather than a thread ID).

'info proc cmdline'
     Show the original command line of the process.  This command is
     supported on GNU/Linux, FreeBSD and NetBSD.

'info proc cwd'
     Show the current working directory of the process.  This command is
     supported on GNU/Linux, FreeBSD and NetBSD.

'info proc exe'
     Show the name of executable of the process.  This command is
     supported on GNU/Linux, FreeBSD and NetBSD.

'info proc files'
     Show the file descriptors open by the process.  For each open file
     descriptor, GDB shows its number, type (file, directory, character
     device, socket), file pointer offset, and the name of the resource
     open on the descriptor.  The resource name can be a file name (for
     files, directories, and devices) or a protocol followed by socket
     address (for network connections).  This command is supported on
     FreeBSD.

     This example shows the open file descriptors for a process using a
     tty for standard input and output as well as two network sockets:

          (gdb) info proc files 22136
          process 22136
          Open files:

                FD   Type     Offset   Flags   Name
              text   file          - r-------- /usr/bin/ssh
              ctty    chr          - rw------- /dev/pts/20
               cwd    dir          - r-------- /usr/home/john
              root    dir          - r-------- /
                 0    chr  0x32933a4 rw------- /dev/pts/20
                 1    chr  0x32933a4 rw------- /dev/pts/20
                 2    chr  0x32933a4 rw------- /dev/pts/20
                 3 socket        0x0 rw----n-- tcp4 10.0.1.2:53014 -> 10.0.1.10:22
                 4 socket        0x0 rw------- unix stream:/tmp/ssh-FIt89oAzOn5f/agent.2456

'info proc mappings'
     Report the memory address space ranges accessible in a process.  On
     Solaris, FreeBSD and NetBSD systems, each memory range includes
     information on whether the process has read, write, or execute
     access rights to each range.  On GNU/Linux, FreeBSD and NetBSD
     systems, each memory range includes the object file which is mapped
     to that range.

'info proc stat'
'info proc status'
     Show additional process-related information, including the user ID
     and group ID; virtual memory usage; the signals that are pending,
     blocked, and ignored; its TTY; its consumption of system and user
     time; its stack size; its 'nice' value; etc.  These commands are
     supported on GNU/Linux, FreeBSD and NetBSD.

     For GNU/Linux systems, see the 'proc' man page for more information
     (type 'man 5 proc' from your shell prompt).

     For FreeBSD and NetBSD systems, 'info proc stat' is an alias for
     'info proc status'.

'info proc all'
     Show all the information about the process described under all of
     the above 'info proc' subcommands.

'set procfs-trace'
     This command enables and disables tracing of 'procfs' API calls.

'show procfs-trace'
     Show the current state of 'procfs' API call tracing.

'set procfs-file FILE'
     Tell GDB to write 'procfs' API trace to the named FILE.  GDB
     appends the trace info to the previous contents of the file.  The
     default is to display the trace on the standard output.

'show procfs-file'
     Show the file to which 'procfs' API trace is written.

'proc-trace-entry'
'proc-trace-exit'
'proc-untrace-entry'
'proc-untrace-exit'
     These commands enable and disable tracing of entries into and exits
     from the 'syscall' interface.

'info pidlist'
     For QNX Neutrino only, this command displays the list of all the
     processes and all the threads within each process.

'info meminfo'
     For QNX Neutrino only, this command displays the list of all
     mapinfos.


File: gdb.info,  Node: DJGPP Native,  Next: Cygwin Native,  Prev: Process Information,  Up: Native

21.1.3 Features for Debugging DJGPP Programs
--------------------------------------------

DJGPP is a port of the GNU development tools to MS-DOS and MS-Windows.
DJGPP programs are 32-bit protected-mode programs that use the "DPMI"
(DOS Protected-Mode Interface) API to run on top of real-mode DOS
systems and their emulations.

   GDB supports native debugging of DJGPP programs, and defines a few
commands specific to the DJGPP port.  This subsection describes those
commands.

'info dos'
     This is a prefix of DJGPP-specific commands which print information
     about the target system and important OS structures.

'info dos sysinfo'
     This command displays assorted information about the underlying
     platform: the CPU type and features, the OS version and flavor, the
     DPMI version, and the available conventional and DPMI memory.

'info dos gdt'
'info dos ldt'
'info dos idt'
     These 3 commands display entries from, respectively, Global, Local,
     and Interrupt Descriptor Tables (GDT, LDT, and IDT). The descriptor
     tables are data structures which store a descriptor for each
     segment that is currently in use.  The segment's selector is an
     index into a descriptor table; the table entry for that index holds
     the descriptor's base address and limit, and its attributes and
     access rights.

     A typical DJGPP program uses 3 segments: a code segment, a data
     segment (used for both data and the stack), and a DOS segment
     (which allows access to DOS/BIOS data structures and absolute
     addresses in conventional memory).  However, the DPMI host will
     usually define additional segments in order to support the DPMI
     environment.

     These commands allow to display entries from the descriptor tables.
     Without an argument, all entries from the specified table are
     displayed.  An argument, which should be an integer expression,
     means display a single entry whose index is given by the argument.
     For example, here's a convenient way to display information about
     the debugged program's data segment:

     (gdb) info dos ldt $ds
     0x13f: base=0x11970000 limit=0x0009ffff 32-Bit Data (Read/Write, Exp-up)

     This comes in handy when you want to see whether a pointer is
     outside the data segment's limit (i.e. "garbled").

'info dos pde'
'info dos pte'
     These two commands display entries from, respectively, the Page
     Directory and the Page Tables.  Page Directories and Page Tables
     are data structures which control how virtual memory addresses are
     mapped into physical addresses.  A Page Table includes an entry for
     every page of memory that is mapped into the program's address
     space; there may be several Page Tables, each one holding up to
     4096 entries.  A Page Directory has up to 4096 entries, one each
     for every Page Table that is currently in use.

     Without an argument, 'info dos pde' displays the entire Page
     Directory, and 'info dos pte' displays all the entries in all of
     the Page Tables.  An argument, an integer expression, given to the
     'info dos pde' command means display only that entry from the Page
     Directory table.  An argument given to the 'info dos pte' command
     means display entries from a single Page Table, the one pointed to
     by the specified entry in the Page Directory.

     These commands are useful when your program uses "DMA" (Direct
     Memory Access), which needs physical addresses to program the DMA
     controller.

     These commands are supported only with some DPMI servers.

'info dos address-pte ADDR'
     This command displays the Page Table entry for a specified linear
     address.  The argument ADDR is a linear address which should
     already have the appropriate segment's base address added to it,
     because this command accepts addresses which may belong to _any_
     segment.  For example, here's how to display the Page Table entry
     for the page where a variable 'i' is stored:

     (gdb) info dos address-pte __djgpp_base_address + (char *)&i
     Page Table entry for address 0x11a00d30:
     Base=0x02698000 Dirty Acc. Not-Cached Write-Back Usr Read-Write +0xd30

     This says that 'i' is stored at offset '0xd30' from the page whose
     physical base address is '0x02698000', and shows all the attributes
     of that page.

     Note that you must cast the addresses of variables to a 'char *',
     since otherwise the value of '__djgpp_base_address', the base
     address of all variables and functions in a DJGPP program, will be
     added using the rules of C pointer arithmetic: if 'i' is declared
     an 'int', GDB will add 4 times the value of '__djgpp_base_address'
     to the address of 'i'.

     Here's another example, it displays the Page Table entry for the
     transfer buffer:

     (gdb) info dos address-pte *((unsigned *)&_go32_info_block + 3)
     Page Table entry for address 0x29110:
     Base=0x00029000 Dirty Acc. Not-Cached Write-Back Usr Read-Write +0x110

     (The '+ 3' offset is because the transfer buffer's address is the
     3rd member of the '_go32_info_block' structure.)  The output
     clearly shows that this DPMI server maps the addresses in
     conventional memory 1:1, i.e. the physical ('0x00029000' + '0x110')
     and linear ('0x29110') addresses are identical.

     This command is supported only with some DPMI servers.

   In addition to native debugging, the DJGPP port supports remote
debugging via a serial data link.  The following commands are specific
to remote serial debugging in the DJGPP port of GDB.

'set com1base ADDR'
     This command sets the base I/O port address of the 'COM1' serial
     port.

'set com1irq IRQ'
     This command sets the "Interrupt Request" ('IRQ') line to use for
     the 'COM1' serial port.

     There are similar commands 'set com2base', 'set com3irq', etc. for
     setting the port address and the 'IRQ' lines for the other 3 COM
     ports.

     The related commands 'show com1base', 'show com1irq' etc. display
     the current settings of the base address and the 'IRQ' lines used
     by the COM ports.

'info serial'
     This command prints the status of the 4 DOS serial ports.  For each
     port, it prints whether it's active or not, its I/O base address
     and IRQ number, whether it uses a 16550-style FIFO, its baudrate,
     and the counts of various errors encountered so far.


File: gdb.info,  Node: Cygwin Native,  Next: Hurd Native,  Prev: DJGPP Native,  Up: Native

21.1.4 Features for Debugging MS Windows PE Executables
-------------------------------------------------------

GDB supports native debugging of MS Windows programs, including DLLs
with and without symbolic debugging information.

   MS-Windows programs that call 'SetConsoleMode' to switch off the
special meaning of the 'Ctrl-C' keystroke cannot be interrupted by
typing 'C-c'.  For this reason, GDB on MS-Windows supports 'C-<BREAK>'
as an alternative interrupt key sequence, which can be used to interrupt
the debuggee even if it ignores 'C-c'.

   There are various additional Cygwin-specific commands, described in
this section.  Working with DLLs that have no debugging symbols is
described in *note Non-debug DLL Symbols::.

'info w32'
     This is a prefix of MS Windows-specific commands which print
     information about the target system and important OS structures.

'info w32 selector'
     This command displays information returned by the Win32 API
     'GetThreadSelectorEntry' function.  It takes an optional argument
     that is evaluated to a long value to give the information about
     this given selector.  Without argument, this command displays
     information about the six segment registers.

'info w32 thread-information-block'
     This command displays thread specific information stored in the
     Thread Information Block (readable on the X86 CPU family using
     '$fs' selector for 32-bit programs and '$gs' for 64-bit programs).

'signal-event ID'
     This command signals an event with user-provided ID.  Used to
     resume crashing process when attached to it using MS-Windows JIT
     debugging (AeDebug).

     To use it, create or edit the following keys in
     'HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug' and/or
     'HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows
     NT\CurrentVersion\AeDebug' (for x86_64 versions):

        - 'Debugger' (REG_SZ) -- a command to launch the debugger.
          Suggested command is: 'FULLY-QUALIFIED-PATH-TO-GDB.EXE -ex
          "attach %ld" -ex "signal-event %ld" -ex "continue"'.

          The first '%ld' will be replaced by the process ID of the
          crashing process, the second '%ld' will be replaced by the ID
          of the event that blocks the crashing process, waiting for GDB
          to attach.

        - 'Auto' (REG_SZ) -- either '1' or '0'.  '1' will make the
          system run debugger specified by the Debugger key
          automatically, '0' will cause a dialog box with "OK" and
          "Cancel" buttons to appear, which allows the user to either
          terminate the crashing process (OK) or debug it (Cancel).

'set cygwin-exceptions MODE'
     If MODE is 'on', GDB will break on exceptions that happen inside
     the Cygwin DLL. If MODE is 'off', GDB will delay recognition of
     exceptions, and may ignore some exceptions which seem to be caused
     by internal Cygwin DLL "bookkeeping".  This option is meant
     primarily for debugging the Cygwin DLL itself; the default value is
     'off' to avoid annoying GDB users with false 'SIGSEGV' signals.

'show cygwin-exceptions'
     Displays whether GDB will break on exceptions that happen inside
     the Cygwin DLL itself.

'set new-console MODE'
     If MODE is 'on' the debuggee will be started in a new console on
     next start.  If MODE is 'off', the debuggee will be started in the
     same console as the debugger.

'show new-console'
     Displays whether a new console is used when the debuggee is
     started.

'set new-group MODE'
     This boolean value controls whether the debuggee should start a new
     group or stay in the same group as the debugger.  This affects the
     way the Windows OS handles 'Ctrl-C'.

'show new-group'
     Displays current value of new-group boolean.

'set debugevents'
     This boolean value adds debug output concerning kernel events
     related to the debuggee seen by the debugger.  This includes events
     that signal thread and process creation and exit, DLL loading and
     unloading, console interrupts, and debugging messages produced by
     the Windows 'OutputDebugString' API call.

'set debugexec'
     This boolean value adds debug output concerning execute events
     (such as resume thread) seen by the debugger.

'set debugexceptions'
     This boolean value adds debug output concerning exceptions in the
     debuggee seen by the debugger.

'set debugmemory'
     This boolean value adds debug output concerning debuggee memory
     reads and writes by the debugger.

'set shell'
     This boolean values specifies whether the debuggee is called via a
     shell or directly (default value is on).

'show shell'
     Displays if the debuggee will be started with a shell.

* Menu:

* Non-debug DLL Symbols::  Support for DLLs without debugging symbols


File: gdb.info,  Node: Non-debug DLL Symbols,  Up: Cygwin Native

21.1.4.1 Support for DLLs without Debugging Symbols
...................................................

Very often on windows, some of the DLLs that your program relies on do
not include symbolic debugging information (for example,
'kernel32.dll').  When GDB doesn't recognize any debugging symbols in a
DLL, it relies on the minimal amount of symbolic information contained
in the DLL's export table.  This section describes working with such
symbols, known internally to GDB as "minimal symbols".

   Note that before the debugged program has started execution, no DLLs
will have been loaded.  The easiest way around this problem is simply to
start the program -- either by setting a breakpoint or letting the
program run once to completion.

21.1.4.2 DLL Name Prefixes
..........................

In keeping with the naming conventions used by the Microsoft debugging
tools, DLL export symbols are made available with a prefix based on the
DLL name, for instance 'KERNEL32!CreateFileA'.  The plain name is also
entered into the symbol table, so 'CreateFileA' is often sufficient.  In
some cases there will be name clashes within a program (particularly if
the executable itself includes full debugging symbols) necessitating the
use of the fully qualified name when referring to the contents of the
DLL. Use single-quotes around the name to avoid the exclamation mark
("!")  being interpreted as a language operator.

   Note that the internal name of the DLL may be all upper-case, even
though the file name of the DLL is lower-case, or vice-versa.  Since
symbols within GDB are _case-sensitive_ this may cause some confusion.
If in doubt, try the 'info functions' and 'info variables' commands or
even 'maint print msymbols' (*note Symbols::).  Here's an example:

     (gdb) info function CreateFileA
     All functions matching regular expression "CreateFileA":

     Non-debugging symbols:
     0x77e885f4  CreateFileA
     0x77e885f4  KERNEL32!CreateFileA

     (gdb) info function !
     All functions matching regular expression "!":

     Non-debugging symbols:
     0x6100114c  cygwin1!__assert
     0x61004034  cygwin1!_dll_crt0@0
     0x61004240  cygwin1!dll_crt0(per_process *)
     [etc...]

21.1.4.3 Working with Minimal Symbols
.....................................

Symbols extracted from a DLL's export table do not contain very much
type information.  All that GDB can do is guess whether a symbol refers
to a function or variable depending on the linker section that contains
the symbol.  Also note that the actual contents of the memory contained
in a DLL are not available unless the program is running.  This means
that you cannot examine the contents of a variable or disassemble a
function within a DLL without a running program.

   Variables are generally treated as pointers and dereferenced
automatically.  For this reason, it is often necessary to prefix a
variable name with the address-of operator ("&") and provide explicit
type information in the command.  Here's an example of the type of
problem:

     (gdb) print 'cygwin1!__argv'
     'cygwin1!__argv' has unknown type; cast it to its declared type

     (gdb) x 'cygwin1!__argv'
     'cygwin1!__argv' has unknown type; cast it to its declared type

   And two possible solutions:

     (gdb) print ((char **)'cygwin1!__argv')[0]
     $2 = 0x22fd98 "/cygdrive/c/mydirectory/myprogram"

     (gdb) x/2x &'cygwin1!__argv'
     0x610c0aa8 <cygwin1!__argv>:    0x10021608      0x00000000
     (gdb) x/x 0x10021608
     0x10021608:     0x0022fd98
     (gdb) x/s 0x0022fd98
     0x22fd98:        "/cygdrive/c/mydirectory/myprogram"

   Setting a break point within a DLL is possible even before the
program starts execution.  However, under these circumstances, GDB can't
examine the initial instructions of the function in order to skip the
function's frame set-up code.  You can work around this by using "*&" to
set the breakpoint at a raw memory address:

     (gdb) break *&'python22!PyOS_Readline'
     Breakpoint 1 at 0x1e04eff0

   The author of these extensions is not entirely convinced that setting
a break point within a shared DLL like 'kernel32.dll' is completely
safe.


File: gdb.info,  Node: Hurd Native,  Next: Darwin,  Prev: Cygwin Native,  Up: Native

21.1.5 Commands Specific to GNU Hurd Systems
--------------------------------------------

This subsection describes GDB commands specific to the GNU Hurd native
debugging.

'set signals'
'set sigs'
     This command toggles the state of inferior signal interception by
     GDB.  Mach exceptions, such as breakpoint traps, are not affected
     by this command.  'sigs' is a shorthand alias for 'signals'.

'show signals'
'show sigs'
     Show the current state of intercepting inferior's signals.

'set signal-thread'
'set sigthread'
     This command tells GDB which thread is the 'libc' signal thread.
     That thread is run when a signal is delivered to a running process.
     'set sigthread' is the shorthand alias of 'set signal-thread'.

'show signal-thread'
'show sigthread'
     These two commands show which thread will run when the inferior is
     delivered a signal.

'set stopped'
     This commands tells GDB that the inferior process is stopped, as
     with the 'SIGSTOP' signal.  The stopped process can be continued by
     delivering a signal to it.

'show stopped'
     This command shows whether GDB thinks the debuggee is stopped.

'set exceptions'
     Use this command to turn off trapping of exceptions in the
     inferior.  When exception trapping is off, neither breakpoints nor
     single-stepping will work.  To restore the default, set exception
     trapping on.

'show exceptions'
     Show the current state of trapping exceptions in the inferior.

'set task pause'
     This command toggles task suspension when GDB has control.  Setting
     it to on takes effect immediately, and the task is suspended
     whenever GDB gets control.  Setting it to off will take effect the
     next time the inferior is continued.  If this option is set to off,
     you can use 'set thread default pause on' or 'set thread pause on'
     (see below) to pause individual threads.

'show task pause'
     Show the current state of task suspension.

'set task detach-suspend-count'
     This command sets the suspend count the task will be left with when
     GDB detaches from it.

'show task detach-suspend-count'
     Show the suspend count the task will be left with when detaching.

'set task exception-port'
'set task excp'
     This command sets the task exception port to which GDB will forward
     exceptions.  The argument should be the value of the "send rights"
     of the task.  'set task excp' is a shorthand alias.

'set noninvasive'
     This command switches GDB to a mode that is the least invasive as
     far as interfering with the inferior is concerned.  This is the
     same as using 'set task pause', 'set exceptions', and 'set signals'
     to values opposite to the defaults.

'info send-rights'
'info receive-rights'
'info port-rights'
'info port-sets'
'info dead-names'
'info ports'
'info psets'
     These commands display information about, respectively, send
     rights, receive rights, port rights, port sets, and dead names of a
     task.  There are also shorthand aliases: 'info ports' for 'info
     port-rights' and 'info psets' for 'info port-sets'.

'set thread pause'
     This command toggles current thread suspension when GDB has
     control.  Setting it to on takes effect immediately, and the
     current thread is suspended whenever GDB gets control.  Setting it
     to off will take effect the next time the inferior is continued.
     Normally, this command has no effect, since when GDB has control,
     the whole task is suspended.  However, if you used 'set task pause
     off' (see above), this command comes in handy to suspend only the
     current thread.

'show thread pause'
     This command shows the state of current thread suspension.

'set thread run'
     This command sets whether the current thread is allowed to run.

'show thread run'
     Show whether the current thread is allowed to run.

'set thread detach-suspend-count'
     This command sets the suspend count GDB will leave on a thread when
     detaching.  This number is relative to the suspend count found by
     GDB when it notices the thread; use 'set thread
     takeover-suspend-count' to force it to an absolute value.

'show thread detach-suspend-count'
     Show the suspend count GDB will leave on the thread when detaching.

'set thread exception-port'
'set thread excp'
     Set the thread exception port to which to forward exceptions.  This
     overrides the port set by 'set task exception-port' (see above).
     'set thread excp' is the shorthand alias.

'set thread takeover-suspend-count'
     Normally, GDB's thread suspend counts are relative to the value GDB
     finds when it notices each thread.  This command changes the
     suspend counts to be absolute instead.

'set thread default'
'show thread default'
     Each of the above 'set thread' commands has a 'set thread default'
     counterpart (e.g., 'set thread default pause', 'set thread default
     exception-port', etc.).  The 'thread default' variety of commands
     sets the default thread properties for all threads; you can then
     change the properties of individual threads with the non-default
     commands.


File: gdb.info,  Node: Darwin,  Next: FreeBSD,  Prev: Hurd Native,  Up: Native

21.1.6 Darwin
-------------

GDB provides the following commands specific to the Darwin target:

'set debug darwin NUM'
     When set to a non zero value, enables debugging messages specific
     to the Darwin support.  Higher values produce more verbose output.

'show debug darwin'
     Show the current state of Darwin messages.

'set debug mach-o NUM'
     When set to a non zero value, enables debugging messages while GDB
     is reading Darwin object files.  ("Mach-O" is the file format used
     on Darwin for object and executable files.)  Higher values produce
     more verbose output.  This is a command to diagnose problems
     internal to GDB and should not be needed in normal usage.

'show debug mach-o'
     Show the current state of Mach-O file messages.

'set mach-exceptions on'
'set mach-exceptions off'
     On Darwin, faults are first reported as a Mach exception and are
     then mapped to a Posix signal.  Use this command to turn on
     trapping of Mach exceptions in the inferior.  This might be
     sometimes useful to better understand the cause of a fault.  The
     default is off.

'show mach-exceptions'
     Show the current state of exceptions trapping.


File: gdb.info,  Node: FreeBSD,  Prev: Darwin,  Up: Native

21.1.7 FreeBSD
--------------

When the ABI of a system call is changed in the FreeBSD kernel, this is
implemented by leaving a compatibility system call using the old ABI at
the existing number and allocating a new system call number for the
version using the new ABI. As a convenience, when a system call is
caught by name (*note catch syscall::), compatibility system calls are
also caught.

   For example, FreeBSD 12 introduced a new variant of the 'kevent'
system call and catching the 'kevent' system call by name catches both
variants:

     (gdb) catch syscall kevent
     Catchpoint 1 (syscalls 'freebsd11_kevent' [363] 'kevent' [560])
     (gdb)


File: gdb.info,  Node: Embedded OS,  Next: Embedded Processors,  Prev: Native,  Up: Configurations

21.2 Embedded Operating Systems
===============================

This section describes configurations involving the debugging of
embedded operating systems that are available for several different
architectures.

   GDB includes the ability to debug programs running on various
real-time operating systems.


File: gdb.info,  Node: Embedded Processors,  Next: Architectures,  Prev: Embedded OS,  Up: Configurations

21.3 Embedded Processors
========================

This section goes into details specific to particular embedded
configurations.

   Whenever a specific embedded processor has a simulator, GDB allows to
send an arbitrary command to the simulator.

'sim COMMAND'
     Send an arbitrary COMMAND string to the simulator.  Consult the
     documentation for the specific simulator in use for information
     about acceptable commands.

* Menu:

* ARC::                         Synopsys ARC
* ARM::                         ARM
* BPF::                         eBPF
* M68K::                        Motorola M68K
* MicroBlaze::                  Xilinx MicroBlaze
* MIPS Embedded::               MIPS Embedded
* OpenRISC 1000::               OpenRISC 1000 (or1k)
* PowerPC Embedded::            PowerPC Embedded
* AVR::                         Atmel AVR
* CRIS::                        CRIS
* Super-H::                     Renesas Super-H


File: gdb.info,  Node: ARC,  Next: ARM,  Up: Embedded Processors

21.3.1 Synopsys ARC
-------------------

GDB provides the following ARC-specific commands:

'set debug arc'
     Control the level of ARC specific debug messages.  Use 0 for no
     messages (the default), 1 for debug messages, and 2 for even more
     debug messages.

'show debug arc'
     Show the level of ARC specific debugging in operation.

'maint print arc arc-instruction ADDRESS'
     Print internal disassembler information about instruction at a
     given address.


File: gdb.info,  Node: ARM,  Next: BPF,  Prev: ARC,  Up: Embedded Processors

21.3.2 ARM
----------

GDB provides the following ARM-specific commands:

'set arm disassembler'
     This commands selects from a list of disassembly styles.  The
     '"std"' style is the standard style.

'show arm disassembler'
     Show the current disassembly style.

'set arm apcs32'
     This command toggles ARM operation mode between 32-bit and 26-bit.

'show arm apcs32'
     Display the current usage of the ARM 32-bit mode.

'set arm fpu FPUTYPE'
     This command sets the ARM floating-point unit (FPU) type.  The
     argument FPUTYPE can be one of these:

     'auto'
          Determine the FPU type by querying the OS ABI.
     'softfpa'
          Software FPU, with mixed-endian doubles on little-endian ARM
          processors.
     'fpa'
          GCC-compiled FPA co-processor.
     'softvfp'
          Software FPU with pure-endian doubles.
     'vfp'
          VFP co-processor.

'show arm fpu'
     Show the current type of the FPU.

'set arm abi'
     This command forces GDB to use the specified ABI.

'show arm abi'
     Show the currently used ABI.

'set arm fallback-mode (arm|thumb|auto)'
     GDB uses the symbol table, when available, to determine whether
     instructions are ARM or Thumb.  This command controls GDB's default
     behavior when the symbol table is not available.  The default is
     'auto', which causes GDB to use the current execution mode (from
     the 'T' bit in the 'CPSR' register).

'show arm fallback-mode'
     Show the current fallback instruction mode.

'set arm force-mode (arm|thumb|auto)'
     This command overrides use of the symbol table to determine whether
     instructions are ARM or Thumb.  The default is 'auto', which causes
     GDB to use the symbol table and then the setting of 'set arm
     fallback-mode'.

'show arm force-mode'
     Show the current forced instruction mode.

'set arm unwind-secure-frames'
     This command enables unwinding from Non-secure to Secure mode on
     Cortex-M with Security extension.  This can trigger security
     exceptions when unwinding the exception stack.  It is enabled by
     default.

'show arm unwind-secure-frames'
     Show whether unwinding from Non-secure to Secure mode is enabled.

'set debug arm'
     Toggle whether to display ARM-specific debugging messages from the
     ARM target support subsystem.

'show debug arm'
     Show whether ARM-specific debugging messages are enabled.

'target sim [SIMARGS] ...'
     The GDB ARM simulator accepts the following optional arguments.

     '--swi-support=TYPE'
          Tell the simulator which SWI interfaces to support.  The
          argument TYPE may be a comma separated list of the following
          values.  The default value is 'all'.

          'none'
          'demon'
          'angel'
          'redboot'
          'all'


File: gdb.info,  Node: BPF,  Next: M68K,  Prev: ARM,  Up: Embedded Processors

21.3.3 BPF
----------

'target sim [SIMARGS] ...'
     The GDB BPF simulator accepts the following optional arguments.

     '--skb-data-offset=OFFSET'
          Tell the simulator the offset, measured in bytes, of the
          'skb_data' field in the kernel 'struct sk_buff' structure.
          This offset is used by some BPF specific-purpose load/store
          instructions.  Defaults to 0.


File: gdb.info,  Node: M68K,  Next: MicroBlaze,  Prev: BPF,  Up: Embedded Processors

21.3.4 M68k
-----------

The Motorola m68k configuration includes ColdFire support.


File: gdb.info,  Node: MicroBlaze,  Next: MIPS Embedded,  Prev: M68K,  Up: Embedded Processors

21.3.5 MicroBlaze
-----------------

The MicroBlaze is a soft-core processor supported on various Xilinx
FPGAs, such as Spartan or Virtex series.  Boards with these processors
usually have JTAG ports which connect to a host system running the
Xilinx Embedded Development Kit (EDK) or Software Development Kit (SDK).
This host system is used to download the configuration bitstream to the
target FPGA. The Xilinx Microprocessor Debugger (XMD) program
communicates with the target board using the JTAG interface and presents
a 'gdbserver' interface to the board.  By default 'xmd' uses port
'1234'.  (While it is possible to change this default port, it requires
the use of undocumented 'xmd' commands.  Contact Xilinx support if you
need to do this.)

   Use these GDB commands to connect to the MicroBlaze target processor.

'target remote :1234'
     Use this command to connect to the target if you are running GDB on
     the same system as 'xmd'.

'target remote XMD-HOST:1234'
     Use this command to connect to the target if it is connected to
     'xmd' running on a different system named XMD-HOST.

'load'
     Use this command to download a program to the MicroBlaze target.

'set debug microblaze N'
     Enable MicroBlaze-specific debugging messages if non-zero.

'show debug microblaze N'
     Show MicroBlaze-specific debugging level.


File: gdb.info,  Node: MIPS Embedded,  Next: OpenRISC 1000,  Prev: MicroBlaze,  Up: Embedded Processors

21.3.6 MIPS Embedded
--------------------

GDB supports these special commands for MIPS targets:

'set mipsfpu double'
'set mipsfpu single'
'set mipsfpu none'
'set mipsfpu auto'
'show mipsfpu'
     If your target board does not support the MIPS floating point
     coprocessor, you should use the command 'set mipsfpu none' (if you
     need this, you may wish to put the command in your GDB init file).
     This tells GDB how to find the return value of functions which
     return floating point values.  It also allows GDB to avoid saving
     the floating point registers when calling functions on the board.
     If you are using a floating point coprocessor with only single
     precision floating point support, as on the R4650 processor, use
     the command 'set mipsfpu single'.  The default double precision
     floating point coprocessor may be selected using 'set mipsfpu
     double'.

     In previous versions the only choices were double precision or no
     floating point, so 'set mipsfpu on' will select double precision
     and 'set mipsfpu off' will select no floating point.

     As usual, you can inquire about the 'mipsfpu' variable with 'show
     mipsfpu'.


File: gdb.info,  Node: OpenRISC 1000,  Next: PowerPC Embedded,  Prev: MIPS Embedded,  Up: Embedded Processors

21.3.7 OpenRISC 1000
--------------------

The OpenRISC 1000 provides a free RISC instruction set architecture.  It
is mainly provided as a soft-core which can run on Xilinx, Altera and
other FPGA's.

   GDB for OpenRISC supports the below commands when connecting to a
target:

'target sim'

     Runs the builtin CPU simulator which can run very basic programs
     but does not support most hardware functions like MMU. For more
     complex use cases the user is advised to run an external target,
     and connect using 'target remote'.

     Example: 'target sim'

'set debug or1k'
     Toggle whether to display OpenRISC-specific debugging messages from
     the OpenRISC target support subsystem.

'show debug or1k'
     Show whether OpenRISC-specific debugging messages are enabled.


File: gdb.info,  Node: PowerPC Embedded,  Next: AVR,  Prev: OpenRISC 1000,  Up: Embedded Processors

21.3.8 PowerPC Embedded
-----------------------

GDB supports using the DVC (Data Value Compare) register to implement in
hardware simple hardware watchpoint conditions of the form:

     (gdb) watch ADDRESS|VARIABLE \
       if  ADDRESS|VARIABLE == CONSTANT EXPRESSION

   The DVC register will be automatically used when GDB detects such
pattern in a condition expression, and the created watchpoint uses one
debug register (either the 'exact-watchpoints' option is on and the
variable is scalar, or the variable has a length of one byte).  This
feature is available in native GDB running on a Linux kernel version
2.6.34 or newer.

   When running on PowerPC embedded processors, GDB automatically uses
ranged hardware watchpoints, unless the 'exact-watchpoints' option is
on, in which case watchpoints using only one debug register are created
when watching variables of scalar types.

   You can create an artificial array to watch an arbitrary memory
region using one of the following commands (*note Expressions::):

     (gdb) watch *((char *) ADDRESS)@LENGTH
     (gdb) watch {char[LENGTH]} ADDRESS

   PowerPC embedded processors support masked watchpoints.  See the
discussion about the 'mask' argument in *note Set Watchpoints::.

   PowerPC embedded processors support hardware accelerated "ranged
breakpoints".  A ranged breakpoint stops execution of the inferior
whenever it executes an instruction at any address within the range it
was set at.  To set a ranged breakpoint in GDB, use the 'break-range'
command.

   GDB provides the following PowerPC-specific commands:

'break-range START-LOCSPEC, END-LOCSPEC'
     Set a breakpoint for an address range given by START-LOCSPEC and
     END-LOCSPEC, which are location specs.  *Note Location
     Specifications::, for a list of all the possible forms of location
     specs.  GDB resolves both START-LOCSPEC and END-LOCSPEC, and uses
     the addresses of the resolved code locations as start and end
     addresses of the range to break at.  The breakpoint will stop
     execution of the inferior whenever it executes an instruction at
     any address between the start and end addresses, inclusive.  If
     either START-LOCSPEC or END-LOCSPEC resolve to multiple code
     locations in the program, then the command aborts with an error
     without creating a breakpoint.

'set powerpc soft-float'
'show powerpc soft-float'
     Force GDB to use (or not use) a software floating point calling
     convention.  By default, GDB selects the calling convention based
     on the selected architecture and the provided executable file.

'set powerpc vector-abi'
'show powerpc vector-abi'
     Force GDB to use the specified calling convention for vector
     arguments and return values.  The valid options are 'auto';
     'generic', to avoid vector registers even if they are present;
     'altivec', to use AltiVec registers; and 'spe' to use SPE
     registers.  By default, GDB selects the calling convention based on
     the selected architecture and the provided executable file.

'set powerpc exact-watchpoints'
'show powerpc exact-watchpoints'
     Allow GDB to use only one debug register when watching a variable
     of scalar type, thus assuming that the variable is accessed through
     the address of its first byte.


File: gdb.info,  Node: AVR,  Next: CRIS,  Prev: PowerPC Embedded,  Up: Embedded Processors

21.3.9 Atmel AVR
----------------

When configured for debugging the Atmel AVR, GDB supports the following
AVR-specific commands:

'info io_registers'
     This command displays information about the AVR I/O registers.  For
     each register, GDB prints its number and value.


File: gdb.info,  Node: CRIS,  Next: Super-H,  Prev: AVR,  Up: Embedded Processors

21.3.10 CRIS
------------

When configured for debugging CRIS, GDB provides the following
CRIS-specific commands:

'set cris-version VER'
     Set the current CRIS version to VER, either '10' or '32'.  The CRIS
     version affects register names and sizes.  This command is useful
     in case autodetection of the CRIS version fails.

'show cris-version'
     Show the current CRIS version.

'set cris-dwarf2-cfi'
     Set the usage of DWARF-2 CFI for CRIS debugging.  The default is
     'on'.  Change to 'off' when using 'gcc-cris' whose version is below
     'R59'.

'show cris-dwarf2-cfi'
     Show the current state of using DWARF-2 CFI.

'set cris-mode MODE'
     Set the current CRIS mode to MODE.  It should only be changed when
     debugging in guru mode, in which case it should be set to 'guru'
     (the default is 'normal').

'show cris-mode'
     Show the current CRIS mode.


File: gdb.info,  Node: Super-H,  Prev: CRIS,  Up: Embedded Processors

21.3.11 Renesas Super-H
-----------------------

For the Renesas Super-H processor, GDB provides these commands:

'set sh calling-convention CONVENTION'
     Set the calling-convention used when calling functions from GDB.
     Allowed values are 'gcc', which is the default setting, and
     'renesas'.  With the 'gcc' setting, functions are called using the
     GCC calling convention.  If the DWARF-2 information of the called
     function specifies that the function follows the Renesas calling
     convention, the function is called using the Renesas calling
     convention.  If the calling convention is set to 'renesas', the
     Renesas calling convention is always used, regardless of the
     DWARF-2 information.  This can be used to override the default of
     'gcc' if debug information is missing, or the compiler does not
     emit the DWARF-2 calling convention entry for a function.

'show sh calling-convention'
     Show the current calling convention setting.


File: gdb.info,  Node: Architectures,  Prev: Embedded Processors,  Up: Configurations

21.4 Architectures
==================

This section describes characteristics of architectures that affect all
uses of GDB with the architecture, both native and cross.

* Menu:

* AArch64::
* x86::
* Alpha::
* MIPS::
* HPPA::               HP PA architecture
* PowerPC::
* Nios II::
* Sparc64::
* S12Z::
* AMD GPU::            AMD GPU architectures


File: gdb.info,  Node: AArch64,  Next: x86,  Up: Architectures

21.4.1 AArch64
--------------

When GDB is debugging the AArch64 architecture, it provides the
following special commands:

'set debug aarch64'
     This command determines whether AArch64 architecture-specific
     debugging messages are to be displayed.

'show debug aarch64'
     Show whether AArch64 debugging messages are displayed.

21.4.1.1 AArch64 SVE.
.....................

When GDB is debugging the AArch64 architecture, if the Scalable Vector
Extension (SVE) is present, then GDB will provide the vector registers
'$z0' through '$z31', vector predicate registers '$p0' through '$p15',
and the '$ffr' register.  In addition, the pseudo register '$vg' will be
provided.  This is the vector granule for the current thread and
represents the number of 64-bit chunks in an SVE 'z' register.

   If the vector length changes, then the '$vg' register will be
updated, but the lengths of the 'z' and 'p' registers will not change.
This is a known limitation of GDB and does not affect the execution of
the target process.

   For SVE, the following definitions are used throughout GDB's source
code and in this document:

   * VL: The vector length, in bytes.  It defines the size of each 'Z'
     register.

   * VQ: The number of 128 bit units in VL.  This is mostly used
     internally by GDB and the Linux Kernel.

   * VG: The number of 64 bit units in VL.  This is mostly used
     internally by GDB and the Linux Kernel.

21.4.1.2 AArch64 SME.
.....................

The Scalable Matrix Extension (SME
(https://community.arm.com/arm-community-blogs/b/architectures-and-processors-blog/posts/scalable-matrix-extension-armv9-a-architecture))
is an AArch64 architecture extension that expands on the concept of the
Scalable Vector Extension (SVE
(https://developer.arm.com/documentation/101726/4-0/Learn-about-the-Scalable-Vector-Extension--SVE-/What-is-the-Scalable-Vector-Extension-))
by providing a 2-dimensional register 'ZA', which is a square matrix of
variable size, just like SVE provides a group of vector registers of
variable size.

   Similarly to SVE, where the size of each 'Z' register is directly
related to the vector length (VL for short), the SME 'ZA' matrix
register's size is directly related to the streaming vector length (SVL
for short).  *Note vl::.  *Note svl::.

   The 'ZA' register state can be either active or inactive, if it is
not in use.

   SME also introduces a new execution mode called streaming SVE mode
(streaming mode for short).  When streaming mode is enabled, the program
supports execution of SVE2 instructions and the SVE registers will have
vector length SVL.  When streaming mode is disabled, the SVE registers
have vector length VL.

   For more information about SME and SVE, please refer to official
architecture documentation
(https://developer.arm.com/documentation/ddi0487/latest).

   The following definitions are used throughout GDB's source code and
in this document:

   * SVL: The streaming vector length, in bytes.  It defines the size of
     each dimension of the 2-dimensional square 'ZA' matrix.  The total
     size of 'ZA' is therefore SVL by SVL.

     When streaming mode is enabled, it defines the size of the SVE
     registers as well.

   * SVQ: The number of 128 bit units in SVL, also known as streaming
     vector granule.  This is mostly used internally by GDB and the
     Linux Kernel.

   * SVG: The number of 64 bit units in SVL.  This is mostly used
     internally by GDB and the Linux Kernel.

   When GDB is debugging the AArch64 architecture, if the Scalable
Matrix Extension (SME) is present, then GDB will make the 'ZA' register
available.  GDB will also make the 'SVG' register and 'SVCR'
pseudo-register available.

   The 'ZA' register is a 2-dimensional square SVL by SVL matrix of
bytes.  To simplify the representation and access to the 'ZA' register
in GDB, it is defined as a vector of SVLxSVL bytes.

   If the user wants to index the 'ZA' register as a matrix, it is
possible to reference 'ZA' as 'ZA[I][J]', where I is the row number and
J is the column number.

   The 'SVG' register always contains the streaming vector granule (SVG)
for the current thread.  From the value of register 'SVG' we can easily
derive the SVL value.

   The 'SVCR' pseudo-register (streaming vector control register) is a
status register that holds two state bits: SM in bit 0 and ZA in bit 1.

   If the SM bit is 1, it means the current thread is in streaming mode,
and the SVE registers will use SVL for their sizes.  If the SM bit is 0,
the current thread is not in streaming mode, and the SVE registers will
use VL for their sizes.  *Note vl::.

   If the ZA bit is 1, it means the 'ZA' register is being used and has
meaningful contents.  If the ZA bit is 0, the 'ZA' register is
unavailable and its contents are undefined.

   For convenience and simplicity, if the ZA bit is 0, the 'ZA' register
and all of its pseudo-registers will read as zero.

   If SVL changes during the execution of a program, then the 'ZA'
register size and the bits in the 'SVCR' pseudo-register will be updated
to reflect it.

   It is possible for users to change SVL during the execution of a
program by modifying the 'SVG' register value.

   Whenever the 'SVG' register is modified with a new value, the
following will be observed:

   * The ZA and SM bits will be cleared in the 'SVCR' pseudo-register.

   * The 'ZA' register will have a new size and its state will be
     cleared, forcing its contents and the contents of all of its
     pseudo-registers back to zero.

   * If the SM bit was 1, the SVE registers will be reset to having
     their sizes based on VL as opposed to SVL.  If the SM bit was 0
     prior to modifying the 'SVG' register, there will be no observable
     effect on the SVE registers.

   The possible values for the 'SVG' register are 2, 4, 8, 16, 32.
These numbers correspond to streaming vector length (SVL) values of 16
bytes, 32 bytes, 64 bytes, 128 bytes and 256 bytes respectively.

   The minimum size of the 'ZA' register is 16 x 16 (256) bytes, and the
maximum size is 256 x 256 (65536) bytes.  In streaming mode, with bit SM
set, the size of the 'ZA' register is the size of all the SVE 'Z'
registers combined.

   The 'ZA' register can also be accessed using tiles and tile slices.

   Tile pseudo-registers are square, 2-dimensional sub-arrays of
elements within the 'ZA' register.

   The tile pseudo-registers have the following naming pattern: 'ZA<TILE
NUMBER><QUALIFIER>'.

   There is a total of 31 'ZA' tile pseudo-registers.  They are 'ZA0B',
'ZA0H' through 'ZA1H', 'ZA0S' through 'ZA3S', 'ZA0D' through 'ZA7D' and
'ZA0Q' through 'ZA15Q'.

   Tile slice pseudo-registers are vectors of horizontally or vertically
contiguous elements within the 'ZA' register.

   The tile slice pseudo-registers have the following naming pattern:
'ZA<TILE NUMBER><DIRECTION><QUALIFIER> <SLICE NUMBER>'.

   There are up to 16 tiles (0 ~ 15), the direction can be either 'v'
(vertical) or 'h' (horizontal), the qualifiers can be 'b' (byte), 'h'
(halfword), 's' (word), 'd' (doubleword) and 'q' (quadword) and there
are up to 256 slices (0 ~ 255) depending on the value of SVL.  The
number of slices is the same as the value of SVL.

   The number of available tile slice pseudo-registers can be large.
For a minimum SVL of 16 bytes, there are 5 (number of qualifiers) x 2
(number of directions) x 16 (SVL) pseudo-registers.  For the maximum SVL
of 256 bytes, there are 5 x 2 x 256 pseudo-registers.

   When listing all the available registers, users will see the
currently-available 'ZA' pseudo-registers.  Pseudo-registers that don't
exist for a given SVL value will not be displayed.

   For more information on SME and its terminology, please refer to the
Arm Architecture Reference Manual Supplement
(https://developer.arm.com/documentation/ddi0616/aa/), The Scalable
Matrix Extension (SME), for Armv9-A.

   Some features are still under development and rely on ACLE
(https://github.com/ARM-software/acle/releases/latest) and ABI
(https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst)
definitions, so there are known limitations to the current SME support
in GDB.

   One such example is calling functions in the program being debugged
by GDB.  Such calls are not SME-aware and thus don't take into account
the 'SVCR' pseudo-register bits nor the 'ZA' register contents.  *Note
Calling::.

   The lazy saving scheme
(https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#the-za-lazy-saving-scheme)
involving the 'TPIDR2' register is not yet supported by GDB, though the
'TPIDR2' register is known and supported by GDB.

   Lastly, an important limitation for 'gdbserver' is its inability to
communicate SVL changes to GDB.  This means 'gdbserver', even though it
is capable of adjusting its internal caches to reflect a change in the
value of SVL mid-execution, will operate with a potentially different
SVL value compared to GDB.  This can lead to GDB showing incorrect
values for the 'ZA' register and incorrect values for SVE registers
(when in streaming mode).

   This is the same limitation we have for the SVE registers, and there
are plans to address this limitation going forward.

21.4.1.3 AArch64 SME2.
......................

The Scalable Matrix Extension 2 is an AArch64 architecture extension
that further expands the SME extension with the following:

   * The ability to address the 'ZA' array through groups of
     one-dimensional 'ZA' array vectors, as opposed to 'ZA' tiles with 2
     dimensions.

   * Instructions to operate on groups of SVE 'Z' registers and 'ZA'
     array vectors.

   * A new 512 bit 'ZT0' lookup table register, for data decompression.

   When GDB is debugging the AArch64 architecture, if the Scalable
Matrix Extension 2 (SME2) is present, then GDB will make the 'ZT0'
register available.

   The 'ZT0' register is only considered active when the 'ZA' register
state is active, therefore when the ZA bit of the 'SVCR' is 1.

   When the ZA bit of 'SVCR' is 0, that means the 'ZA' register state is
not active, which means the 'ZT0' register state is also not active.

   When 'ZT0' is not active, it is comprised of zeroes, just like 'ZA'.

   Similarly to the 'ZA' register, if the 'ZT0' state is not active and
the user attempts to modify its value such that any of its bytes is
non-zero, then GDB will initialize the 'ZA' register state as well,
which means the 'SVCR' ZA bit gets set to 1.

   For more information about SME2, please refer to the official
architecture documentation
(https://developer.arm.com/documentation/ddi0487/latest).

21.4.1.4 AArch64 Pointer Authentication.
........................................

When GDB is debugging the AArch64 architecture, and the program is using
the v8.3-A feature Pointer Authentication (PAC), then whenever the link
register '$lr' is pointing to an PAC function its value will be masked.
When GDB prints a backtrace, any addresses that required unmasking will
be postfixed with the marker [PAC]. When using the MI, this is printed
as part of the 'addr_flags' field.

21.4.1.5 AArch64 Memory Tagging Extension.
..........................................

When GDB is debugging the AArch64 architecture, the program is using the
v8.5-A feature Memory Tagging Extension (MTE) and there is support in
the kernel for MTE, GDB will make memory tagging functionality available
for inspection and editing of logical and allocation tags.  *Note Memory
Tagging::.

   To aid debugging, GDB will output additional information when SIGSEGV
signals are generated as a result of memory tag failures.

   If the tag violation is synchronous, the following will be shown:

     Program received signal SIGSEGV, Segmentation fault
     Memory tag violation while accessing address 0x0500fffff7ff8000
     Allocation tag 0x1
     Logical tag 0x5.

   If the tag violation is asynchronous, the fault address is not
available.  In this case GDB will show the following:

     Program received signal SIGSEGV, Segmentation fault
     Memory tag violation
     Fault address unavailable.

   A special register, 'tag_ctl', is made available through the
'org.gnu.gdb.aarch64.mte' feature.  This register exposes some options
that can be controlled at runtime and emulates the 'prctl' option
'PR_SET_TAGGED_ADDR_CTRL'.  For further information, see the
documentation in the Linux kernel.

   GDB supports dumping memory tag data to core files through the
'gcore' command and reading memory tag data from core files generated by
the 'gcore' command or the Linux kernel.

   When a process uses memory-mapped pages protected by memory tags (for
example, AArch64 MTE), this additional information will be recorded in
the core file in the event of a crash or if GDB generates a core file
from the current process state.

   The memory tag data will be used so developers can display the memory
tags from a particular memory region (using the 'm' modifier to the 'x'
command, using the 'print' command or using the various 'memory-tag'
subcommands.

   In the case of a crash, GDB will attempt to retrieve the memory tag
information automatically from the core file, and will show one of the
above messages depending on whether the synchronous or asynchronous mode
is selected.  *Note Memory Tagging::.  *Note Memory::.


File: gdb.info,  Node: x86,  Next: Alpha,  Prev: AArch64,  Up: Architectures

21.4.2 x86
----------

'set struct-convention MODE'
     Set the convention used by the inferior to return 'struct's and
     'union's from functions to MODE.  Possible values of MODE are
     '"pcc"', '"reg"', and '"default"' (the default).  '"default"' or
     '"pcc"' means that 'struct's are returned on the stack, while
     '"reg"' means that a 'struct' or a 'union' whose size is 1, 2, 4,
     or 8 bytes will be returned in a register.

'show struct-convention'
     Show the current setting of the convention to return 'struct's from
     functions.

21.4.2.1 Intel "Memory Protection Extensions" (MPX).
....................................................

Memory Protection Extension (MPX) adds the bound registers 'BND0' (1)
through 'BND3'.  Bound registers store a pair of 64-bit values which are
the lower bound and upper bound.  Bounds are effective addresses or
memory locations.  The upper bounds are architecturally represented in
1's complement form.  A bound having lower bound = 0, and upper bound =
0 (1's complement of all bits set) will allow access to the entire
address space.

   'BND0' through 'BND3' are represented in GDB as 'bnd0raw' through
'bnd3raw'.  Pseudo registers 'bnd0' through 'bnd3' display the upper
bound performing the complement of one operation on the upper bound
value, i.e. when upper bound in 'bnd0raw' is 0 in the GDB 'bnd0' it will
be '0xfff...'.  In this sense it can also be noted that the upper bounds
are inclusive.

   As an example, assume that the register BND0 holds bounds for a
pointer having access allowed for the range between 0x32 and 0x71.  The
values present on bnd0raw and bnd registers are presented as follows:

     	bnd0raw = {0x32, 0xffffffff8e}
     	bnd0 = {lbound = 0x32, ubound = 0x71} : size 64

   This way the raw value can be accessed via bnd0raw...bnd3raw.  Any
change on bnd0...bnd3 or bnd0raw...bnd3raw is reflect on its
counterpart.  When the bnd0...bnd3 registers are displayed via Python,
the display includes the memory size, in bits, accessible to the
pointer.

   Bounds can also be stored in bounds tables, which are stored in
application memory.  These tables store bounds for pointers by
specifying the bounds pointer's value along with its bounds.  Evaluating
and changing bounds located in bound tables is therefore interesting
while investigating bugs on MPX context.  GDB provides commands for this
purpose:

'show mpx bound POINTER'
     Display bounds of the given POINTER.

'set mpx bound POINTER, LBOUND, UBOUND'
     Set the bounds of a pointer in the bound table.  This command takes
     three parameters: POINTER is the pointers whose bounds are to be
     changed, LBOUND and UBOUND are new values for lower and upper
     bounds respectively.

   Both commands are deprecated and will be removed in future versions
of GDB.  MPX itself was listed as removed by Intel in 2019.

   When you call an inferior function on an Intel MPX enabled program,
GDB sets the inferior's bound registers to the init (disabled) state
before calling the function.  As a consequence, bounds checks for the
pointer arguments passed to the function will always pass.

   This is necessary because when you call an inferior function, the
program is usually in the middle of the execution of other function.
Since at that point bound registers are in an arbitrary state, not
clearing them would lead to random bound violations in the called
function.

   You can still examine the influence of the bound registers on the
execution of the called function by stopping the execution of the called
function at its prologue, setting bound registers, and continuing the
execution.  For example:

     	$ break *upper
     	Breakpoint 2 at 0x4009de: file i386-mpx-call.c, line 47.
     	$ print upper (a, b, c, d, 1)
     	Breakpoint 2, upper (a=0x0, b=0x6e0000005b, c=0x0, d=0x0, len=48)....
     	$ print $bnd0
     	{lbound = 0x0, ubound = ffffffff} : size -1

   At this last step the value of bnd0 can be changed for investigation
of bound violations caused along the execution of the call.  In order to
know how to set the bound registers or bound table for the call consult
the ABI.

21.4.2.2 x87 registers
......................

GDB provides access to the x87 state through the following registers:

   * '$st0' to 'st7': 'ST(0)' to 'ST(7)' floating-point registers
   * '$fctrl': control word register ('FCW')
   * '$fstat': status word register ('FSW')
   * '$ftag': tag word ('FTW')
   * '$fiseg': last instruction pointer segment
   * '$fioff': last instruction pointer
   * '$foseg': last data pointer segment
   * '$fooff': last data pointer
   * '$fop': last opcode

   ---------- Footnotes ----------

   (1) The register named with capital letters represent the
architecture registers.


File: gdb.info,  Node: Alpha,  Next: MIPS,  Prev: x86,  Up: Architectures

21.4.3 Alpha
------------

See the following section.


File: gdb.info,  Node: MIPS,  Next: HPPA,  Prev: Alpha,  Up: Architectures

21.4.4 MIPS
-----------

Alpha- and MIPS-based computers use an unusual stack frame, which
sometimes requires GDB to search backward in the object code to find the
beginning of a function.

   To improve response time (especially for embedded applications, where
GDB may be restricted to a slow serial line for this search) you may
want to limit the size of this search, using one of these commands:

'set heuristic-fence-post LIMIT'
     Restrict GDB to examining at most LIMIT bytes in its search for the
     beginning of a function.  A value of 0 (the default) means there is
     no limit.  However, except for 0, the larger the limit the more
     bytes 'heuristic-fence-post' must search and therefore the longer
     it takes to run.  You should only need to use this command when
     debugging a stripped executable.

'show heuristic-fence-post'
     Display the current limit.

These commands are available _only_ when GDB is configured for debugging
programs on Alpha or MIPS processors.

   Several MIPS-specific commands are available when debugging MIPS
programs:

'set mips abi ARG'
     Tell GDB which MIPS ABI is used by the inferior.  Possible values
     of ARG are:

     'auto'
          The default ABI associated with the current binary (this is
          the default).
     'o32'
     'o64'
     'n32'
     'n64'
     'eabi32'
     'eabi64'

'show mips abi'
     Show the MIPS ABI used by GDB to debug the inferior.

'set mips compression ARG'
     Tell GDB which MIPS compressed ISA (Instruction Set Architecture)
     encoding is used by the inferior.  GDB uses this for code
     disassembly and other internal interpretation purposes.  This
     setting is only referred to when no executable has been associated
     with the debugging session or the executable does not provide
     information about the encoding it uses.  Otherwise this setting is
     automatically updated from information provided by the executable.

     Possible values of ARG are 'mips16' and 'micromips'.  The default
     compressed ISA encoding is 'mips16', as executables containing
     MIPS16 code frequently are not identified as such.

     This setting is "sticky"; that is, it retains its value across
     debugging sessions until reset either explicitly with this command
     or implicitly from an executable.

     The compiler and/or assembler typically add symbol table
     annotations to identify functions compiled for the MIPS16 or
     microMIPS ISAs.  If these function-scope annotations are present,
     GDB uses them in preference to the global compressed ISA encoding
     setting.

'show mips compression'
     Show the MIPS compressed ISA encoding used by GDB to debug the
     inferior.

'set mipsfpu'
'show mipsfpu'
     *Note set mipsfpu: MIPS Embedded.

'set mips mask-address ARG'
     This command determines whether the most-significant 32 bits of
     64-bit MIPS addresses are masked off.  The argument ARG can be
     'on', 'off', or 'auto'.  The latter is the default setting, which
     lets GDB determine the correct value.

'show mips mask-address'
     Show whether the upper 32 bits of MIPS addresses are masked off or
     not.

'set remote-mips64-transfers-32bit-regs'
     This command controls compatibility with 64-bit MIPS targets that
     transfer data in 32-bit quantities.  If you have an old MIPS 64
     target that transfers 32 bits for some registers, like SR and FSR,
     and 64 bits for other registers, set this option to 'on'.

'show remote-mips64-transfers-32bit-regs'
     Show the current setting of compatibility with older MIPS 64
     targets.

'set debug mips'
     This command turns on and off debugging messages for the
     MIPS-specific target code in GDB.

'show debug mips'
     Show the current setting of MIPS debugging messages.


File: gdb.info,  Node: HPPA,  Next: PowerPC,  Prev: MIPS,  Up: Architectures

21.4.5 HPPA
-----------

When GDB is debugging the HP PA architecture, it provides the following
special commands:

'set debug hppa'
     This command determines whether HPPA architecture-specific
     debugging messages are to be displayed.

'show debug hppa'
     Show whether HPPA debugging messages are displayed.

'maint print unwind ADDRESS'
     This command displays the contents of the unwind table entry at the
     given ADDRESS.


File: gdb.info,  Node: PowerPC,  Next: Nios II,  Prev: HPPA,  Up: Architectures

21.4.6 PowerPC
--------------

When GDB is debugging the PowerPC architecture, it provides a set of
pseudo-registers to enable inspection of 128-bit wide Decimal Floating
Point numbers stored in the floating point registers.  These values must
be stored in two consecutive registers, always starting at an even
register like 'f0' or 'f2'.

   The pseudo-registers go from '$dl0' through '$dl15', and are formed
by joining the even/odd register pairs 'f0' and 'f1' for '$dl0', 'f2'
and 'f3' for '$dl1' and so on.

   For POWER7 processors, GDB provides a set of pseudo-registers, the
64-bit wide Extended Floating Point Registers ('f32' through 'f63').


File: gdb.info,  Node: Nios II,  Next: Sparc64,  Prev: PowerPC,  Up: Architectures

21.4.7 Nios II
--------------

When GDB is debugging the Nios II architecture, it provides the
following special commands:

'set debug nios2'
     This command turns on and off debugging messages for the Nios II
     target code in GDB.

'show debug nios2'
     Show the current setting of Nios II debugging messages.


File: gdb.info,  Node: Sparc64,  Next: S12Z,  Prev: Nios II,  Up: Architectures

21.4.8 Sparc64
--------------

21.4.8.1 ADI Support
....................

The M7 processor supports an Application Data Integrity (ADI) feature
that detects invalid data accesses.  When software allocates memory and
enables ADI on the allocated memory, it chooses a 4-bit version number,
sets the version in the upper 4 bits of the 64-bit pointer to that data,
and stores the 4-bit version in every cacheline of that data.  Hardware
saves the latter in spare bits in the cache and memory hierarchy.  On
each load and store, the processor compares the upper 4 VA (virtual
address) bits to the cacheline's version.  If there is a mismatch, the
processor generates a version mismatch trap which can be either precise
or disrupting.  The trap is an error condition which the kernel delivers
to the process as a SIGSEGV signal.

   Note that only 64-bit applications can use ADI and need to be built
with ADI-enabled.

   Values of the ADI version tags, which are in granularity of a
cacheline (64 bytes), can be viewed or modified.

'adi (examine | x) [ / N ] ADDR'

     The 'adi examine' command displays the value of one ADI version tag
     per cacheline.

     N is a decimal integer specifying the number in bytes; the default
     is 1.  It specifies how much ADI version information, at the ratio
     of 1:ADI block size, to display.

     ADDR is the address in user address space where you want GDB to
     begin displaying the ADI version tags.

     Below is an example of displaying ADI versions of variable
     "shmaddr".

          (gdb) adi x/100 shmaddr
             0xfff800010002c000:     0 0

'adi (assign | a) [ / N ] ADDR = TAG'

     The 'adi assign' command is used to assign new ADI version tag to
     an address.

     N is a decimal integer specifying the number in bytes; the default
     is 1.  It specifies how much ADI version information, at the ratio
     of 1:ADI block size, to modify.

     ADDR is the address in user address space where you want GDB to
     begin modifying the ADI version tags.

     TAG is the new ADI version tag.

     For example, do the following to modify then verify ADI versions of
     variable "shmaddr":

          (gdb) adi a/100 shmaddr = 7
          (gdb) adi x/100 shmaddr
             0xfff800010002c000:     7 7


File: gdb.info,  Node: S12Z,  Next: AMD GPU,  Prev: Sparc64,  Up: Architectures

21.4.9 S12Z
-----------

When GDB is debugging the S12Z architecture, it provides the following
special command:

'maint info bdccsr'
     This command displays the current value of the microprocessor's
     BDCCSR register.


File: gdb.info,  Node: AMD GPU,  Prev: S12Z,  Up: Architectures

21.4.10 AMD GPU
---------------

GDB supports debugging programs offloaded to AMD GPU devices using the
AMD ROCm (https://docs.amd.com/) platform.  GDB presents host threads
alongside GPU wavefronts, allowing debugging both the host and device
parts of the program simultaneously.

21.4.10.1 AMD GPU Architectures
...............................

The list of AMD GPU architectures supported by GDB depends on the
version of the AMD Debugger API library used.  See its documentation
(https://docs.amd.com/bundle/ROCDebugger_User_and_API) for more details.

21.4.10.2 AMD GPU Device Driver and AMD ROCm Runtime
....................................................

GDB requires a compatible AMD GPU device driver to be installed.  A
warning message is displayed if either the device driver version or the
version of the debug support it implements is unsupported.  GDB will
continue to function except no AMD GPU debugging will be possible.

   GDB requires each agent to have compatible firmware installed by the
device driver.  A warning message is displayed if unsupported firmware
is detected.  GDB will continue to function except no AMD GPU debugging
will be possible on the agent.

   GDB requires a compatible AMD ROCm runtime to be loaded in order to
detect AMD GPU code objects and wavefronts.  A warning message is
displayed if an unsupported AMD ROCm runtime is detected, or there is an
error or restriction that prevents debugging.  GDB will continue to
function except no AMD GPU debugging will be possible.

21.4.10.3 AMD GPU Wavefronts
............................

An AMD GPU wavefront is represented in GDB as a thread.

   Note that some AMD GPU architectures may have restrictions on
providing information about AMD GPU wavefronts created when GDB is not
attached (*note AMD GPU Attaching Restrictions: AMD GPU Attaching
Restrictions.).

   When scheduler-locking is in effect (*note set scheduler-locking::),
new wavefronts created by the resumed thread (either CPU thread or GPU
wavefront) are held in the halt state.

21.4.10.4 AMD GPU Code Objects
..............................

The 'info sharedlibrary' command will show the AMD GPU code objects as
file or memory URIs, together with the host's shared libraries.  For
example:

     (gdb) info sharedlibrary
     From    To      Syms Read   Shared Object Library
     0x1111  0x2222  Yes (*)     /lib64/ld-linux-x86-64.so.2
     ...
     0x3333  0x4444  Yes (*)     /opt/rocm-4.5.0/.../libamd_comgr.so
     0x5555  0x6666  Yes (*)     /lib/x86_64-linux-gnu/libtinfo.so.5
     0x7777  0x8888  Yes         file:///tmp/a.out#offset=6477&size=10832
     0x9999  0xaaaa  Yes (*)     memory://95557/mem#offset=0x1234&size=100
     (*): Shared library is missing debugging information.
     (gdb)

   For a 'file' URI, the path portion is the file on disk containing the
code object.  The OFFSET parameter is a 0-based offset in this file, to
the start of the code object.  If omitted, it defaults to 0.  The SIZE
parameter is the size of the code object in bytes.  If omitted, it
defaults to the size of the file.

   For a 'memory' URI, the path portion is the process id of the process
owning the memory containing the code object.  The OFFSET parameter is
the memory address where the code object is found, and the SIZE
parameter is its size in bytes.

   AMD GPU code objects are loaded into each AMD GPU device separately.
The 'info sharedlibrary' command may therefore show the same code object
loaded multiple times.  As a consequence, setting a breakpoint in AMD
GPU code will result in multiple breakpoint locations if there are
multiple AMD GPU devices.

21.4.10.5 AMD GPU Entity Target Identifiers and Convenience Variables
.....................................................................

The AMD GPU entities have the following target identifier formats:

Thread Target ID
     The AMD GPU thread target identifier (SYSTAG) string has the
     following format:

          AMDGPU Wave AGENT-ID:QUEUE-ID:DISPATCH-ID:WAVE-ID (WORK-GROUP-X,WORK-GROUP-Y,WORK-GROUP-Z)/WORK-GROUP-THREAD-INDEX

21.4.10.6 AMD GPU Signals
.........................

For AMD GPU wavefronts, GDB maps target conditions to stop signals in
the following way:

'SIGILL'
     Execution of an illegal instruction.

'SIGTRAP'
     Execution of a 'S_TRAP' instruction other than:

        * 'S_TRAP 1' which is used by GDB to insert breakpoints.

        * 'S_TRAP 2' which raises 'SIGABRT'.

'SIGABRT'
     Execution of a 'S_TRAP 2' instruction.

'SIGFPE'
     Execution of a floating point or integer instruction detects a
     condition that is enabled to raise a signal.  The conditions
     include:

        * Floating point operation is invalid.

        * Floating point operation had subnormal input that was rounded
          to zero.

        * Floating point operation performed a division by zero.

        * Floating point operation produced an overflow result.  The
          result was rounded to infinity.

        * Floating point operation produced an underflow result.  A
          subnormal result was rounded to zero.

        * Floating point operation produced an inexact result.

        * Integer operation performed a division by zero.

     By default, these conditions are not enabled to raise signals.  The
     'set $mode' command can be used to change the AMD GPU wavefront's
     register that has bits controlling which conditions are enabled to
     raise signals.  The 'print $trapsts' command can be used to inspect
     which conditions have been detected even if they are not enabled to
     raise a signal.

'SIGBUS'
     Execution of an instruction that accessed global memory using an
     address that is outside the virtual address range.

'SIGSEGV'
     Execution of an instruction that accessed a global memory page that
     is either not mapped or accessed with incompatible permissions.

   If a single instruction raises more than one signal, they will be
reported one at a time each time the wavefront is continued.

21.4.10.7 AMD GPU Memory Violation Reporting
............................................

A wavefront can report memory violation events.  However, the program
location at which they are reported may be after the machine instruction
that caused them.  This can result in the reported source statement
being incorrect.  The following commands can be used to control this
behavior:

'set amdgpu precise-memory MODE'
     Controls how AMD GPU devices detect memory violations, where MODE
     can be:

     'off'
          The program location may not be immediately after the
          instruction that caused the memory violation.  This is the
          default.

     'on'
          Requests that the program location will be immediately after
          the instruction that caused a memory violation.  Enabling this
          mode may make the AMD GPU device execution significantly
          slower as it has to wait for each memory operation to complete
          before executing the next instruction.

     The 'amdgpu precise-memory' parameter is per-inferior.  When an
     inferior forks or execs, or the user uses the 'clone-inferior'
     command, and an inferior is created as a result, the newly created
     inferior inherits the parameter value of the original inferior.

'show amdgpu precise-memory'
     Displays the currently requested AMD GPU precise memory setting.

21.4.10.8 AMD GPU Logging
.........................

The 'set debug amd-dbgapi' command can be used to enable diagnostic
messages in the 'amd-dbgapi' target.  The 'show debug amd-dbgapi'
command displays the current setting.  *Note set debug amd-dbgapi::.

   The 'set debug amd-dbgapi-lib log-level LEVEL' command can be used to
enable diagnostic messages from the 'amd-dbgapi' library (which GDB uses
under the hood).  The 'show debug amd-dbgapi-lib log-level' command
displays the current 'amd-dbgapi' library log level.  *Note set debug
amd-dbgapi-lib::.

21.4.10.9 AMD GPU Restrictions
..............................

  1. When in non-stop mode, wavefronts may not hit breakpoints inserted
     while not stopped, nor see memory updates made while not stopped,
     until the wavefront is next stopped.  Memory updated by non-stopped
     wavefronts may not be visible until the wavefront is next stopped.

  2. The HIP runtime performs deferred code object loading by default.
     AMD GPU code objects are not loaded until the first kernel is
     launched.  Before then, all breakpoints have to be set as pending
     breakpoints.

     If source line positions are used that only correspond to source
     lines in unloaded code objects, then GDB may not set pending
     breakpoints, and instead set breakpoints on the next following
     source line that maps to host code.  This can result in unexpected
     breakpoint hits being reported.  When the code object containing
     the source lines is loaded, the incorrect breakpoints will be
     removed and replaced by the correct ones.  This problem can be
     avoided by only setting breakpoints in unloaded code objects using
     symbol or function names.

     Setting the 'HIP_ENABLE_DEFERRED_LOADING' environment variable to
     '0' can be used to disable deferred code object loading by the HIP
     runtime.  This ensures all code objects will be loaded when the
     inferior reaches the beginning of the 'main' function.

  3. If no CPU thread is running, then 'Ctrl-C' is not able to stop AMD
     GPU threads.  This can happen for example if you enable
     'scheduler-locking' after the whole program stopped, and then
     resume an AMD GPU thread.  The only way to unblock the situation is
     to kill the GDB process.

  4. 
     By default, for some architectures, the AMD GPU device driver
     causes all AMD GPU wavefronts created when GDB is not attached to
     be unable to report the dispatch associated with the wavefront, or
     the wavefront's work-group position.  The 'info threads' command
     will display this missing information with a '?'.

     This does not affect wavefronts created while GDB is attached which
     are always capable of reporting this information.

     If the 'HSA_ENABLE_DEBUG' environment variable is set to '1' when
     the AMD ROCm runtime is initialized, then this information will be
     available for all architectures even for wavefronts created when
     GDB was not attached.


File: gdb.info,  Node: Controlling GDB,  Next: Extending GDB,  Prev: Configurations,  Up: Top

22 Controlling GDB
******************

You can alter the way GDB interacts with you by using the 'set' command.
For commands controlling how GDB displays data, see *note Print
Settings: Print Settings.  Other settings are described here.

* Menu:

* Prompt::                      Prompt
* Editing::                     Command editing
* Command History::             Command history
* Screen Size::                 Screen size
* Output Styling::              Output styling
* Numbers::                     Numbers
* ABI::                         Configuring the current ABI
* Auto-loading::                Automatically loading associated files
* Messages/Warnings::           Optional warnings and messages
* Debugging Output::            Optional messages about internal happenings
* Other Misc Settings::         Other Miscellaneous Settings


File: gdb.info,  Node: Prompt,  Next: Editing,  Up: Controlling GDB

22.1 Prompt
===========

GDB indicates its readiness to read a command by printing a string
called the "prompt".  This string is normally '(gdb)'.  You can change
the prompt string with the 'set prompt' command.  For instance, when
debugging GDB with GDB, it is useful to change the prompt in one of the
GDB sessions so that you can always tell which one you are talking to.

   _Note:_ 'set prompt' does not add a space for you after the prompt
you set.  This allows you to set a prompt which ends in a space or a
prompt that does not.

'set prompt NEWPROMPT'
     Directs GDB to use NEWPROMPT as its prompt string henceforth.

'show prompt'
     Prints a line of the form: 'Gdb's prompt is: YOUR-PROMPT'

   Versions of GDB that ship with Python scripting enabled have prompt
extensions.  The commands for interacting with these extensions are:

'set extended-prompt PROMPT'
     Set an extended prompt that allows for substitutions.  *Note
     gdb.prompt::, for a list of escape sequences that can be used for
     substitution.  Any escape sequences specified as part of the prompt
     string are replaced with the corresponding strings each time the
     prompt is displayed.

     For example:

          set extended-prompt Current working directory: \w (gdb)

     Note that when an extended-prompt is set, it takes control of the
     PROMPT_HOOK hook.  *Note prompt_hook::, for further information.

'show extended-prompt'
     Prints the extended prompt.  Any escape sequences specified as part
     of the prompt string with 'set extended-prompt', are replaced with
     the corresponding strings each time the prompt is displayed.


File: gdb.info,  Node: Editing,  Next: Command History,  Prev: Prompt,  Up: Controlling GDB

22.2 Command Editing
====================

GDB reads its input commands via the "Readline" interface.  This GNU
library provides consistent behavior for programs which provide a
command line interface to the user.  Advantages are GNU Emacs-style or
"vi"-style inline editing of commands, 'csh'-like history substitution,
and a storage and recall of command history across debugging sessions.

   You may control the behavior of command line editing in GDB with the
command 'set'.

'set editing'
'set editing on'
     Enable command line editing (enabled by default).

'set editing off'
     Disable command line editing.

'show editing'
     Show whether command line editing is enabled.

   *Note Command Line Editing::, for more details about the Readline
interface.  Users unfamiliar with GNU Emacs or 'vi' are encouraged to
read that chapter.

   GDB sets the Readline application name to 'gdb'.  This is useful for
conditions in '.inputrc'.

   GDB defines a bindable Readline command, 'operate-and-get-next'.
This is bound to 'C-o' by default.  This command accepts the current
line for execution and fetches the next line relative to the current
line from the history for editing.  Any argument is ignored.


File: gdb.info,  Node: Command History,  Next: Screen Size,  Prev: Editing,  Up: Controlling GDB

22.3 Command History
====================

GDB can keep track of the commands you type during your debugging
sessions, so that you can be certain of precisely what happened.  Use
these commands to manage the GDB command history facility.

   GDB uses the GNU History library, a part of the Readline package, to
provide the history facility.  *Note Using History Interactively::, for
the detailed description of the History library.

   To issue a command to GDB without affecting certain aspects of the
state which is seen by users, prefix it with 'server ' (*note Server
Prefix::).  This means that this command will not affect the command
history, nor will it affect GDB's notion of which command to repeat if
<RET> is pressed on a line by itself.

   The server prefix does not affect the recording of values into the
value history; to print a value without recording it into the value
history, use the 'output' command instead of the 'print' command.

   Here is the description of GDB commands related to command history.

'set history filename [FNAME]'
     Set the name of the GDB command history file to FNAME.  This is the
     file where GDB reads an initial command history list, and where it
     writes the command history from this session when it exits.  You
     can access this list through history expansion or through the
     history command editing characters listed below.  This file
     defaults to the value of the environment variable 'GDBHISTFILE', or
     to './.gdb_history' ('./_gdb_history' on MS-DOS) if this variable
     is not set.

     The 'GDBHISTFILE' environment variable is read after processing any
     GDB initialization files (*note Startup::) and after processing any
     commands passed using command line options (for example, '-ex').

     If the FNAME argument is not given, or if the 'GDBHISTFILE' is the
     empty string then GDB will neither try to load an existing history
     file, nor will it try to save the history on exit.

'set history save'
'set history save on'
     Record command history in a file, whose name may be specified with
     the 'set history filename' command.  By default, this option is
     disabled.  The command history will be recorded when GDB exits.  If
     'set history filename' is set to the empty string then history
     saving is disabled, even when 'set history save' is 'on'.

'set history save off'
     Don't record the command history into the file specified by 'set
     history filename' when GDB exits.

'set history size SIZE'
'set history size unlimited'
     Set the number of commands which GDB keeps in its history list.
     This defaults to the value of the environment variable
     'GDBHISTSIZE', or to 256 if this variable is not set.  Non-numeric
     values of 'GDBHISTSIZE' are ignored.  If SIZE is 'unlimited' or if
     'GDBHISTSIZE' is either a negative number or the empty string, then
     the number of commands GDB keeps in the history list is unlimited.

     The 'GDBHISTSIZE' environment variable is read after processing any
     GDB initialization files (*note Startup::) and after processing any
     commands passed using command line options (for example, '-ex').

'set history remove-duplicates COUNT'
'set history remove-duplicates unlimited'
     Control the removal of duplicate history entries in the command
     history list.  If COUNT is non-zero, GDB will look back at the last
     COUNT history entries and remove the first entry that is a
     duplicate of the current entry being added to the command history
     list.  If COUNT is 'unlimited' then this lookbehind is unbounded.
     If COUNT is 0, then removal of duplicate history entries is
     disabled.

     Only history entries added during the current session are
     considered for removal.  This option is set to 0 by default.

   History expansion assigns special meaning to the character '!'.
*Note Event Designators::, for more details.

   Since '!' is also the logical not operator in C, history expansion is
off by default.  If you decide to enable history expansion with the 'set
history expansion on' command, you may sometimes need to follow '!'
(when it is used as logical not, in an expression) with a space or a tab
to prevent it from being expanded.  The readline history facilities do
not attempt substitution on the strings '!=' and '!(', even when history
expansion is enabled.

   The commands to control history expansion are:

'set history expansion on'
'set history expansion'
     Enable history expansion.  History expansion is off by default.

'set history expansion off'
     Disable history expansion.

'show history'
'show history filename'
'show history save'
'show history size'
'show history expansion'
     These commands display the state of the GDB history parameters.
     'show history' by itself displays all four states.

'show commands'
     Display the last ten commands in the command history.

'show commands N'
     Print ten commands centered on command number N.

'show commands +'
     Print ten commands just after the commands last printed.


File: gdb.info,  Node: Screen Size,  Next: Output Styling,  Prev: Command History,  Up: Controlling GDB

22.4 Screen Size
================

Certain commands to GDB may produce large amounts of information output
to the screen.  To help you read all of it, GDB pauses and asks you for
input at the end of each page of output.  Type <RET> when you want to
see one more page of output, 'q' to discard the remaining output, or 'c'
to continue without paging for the rest of the current command.  Also,
the screen width setting determines when to wrap lines of output.
Depending on what is being printed, GDB tries to break the line at a
readable place, rather than simply letting it overflow onto the
following line.

   Normally GDB knows the size of the screen from the terminal driver
software.  For example, on Unix GDB uses the termcap data base together
with the value of the 'TERM' environment variable and the 'stty rows'
and 'stty cols' settings.  If this is not correct, you can override it
with the 'set height' and 'set width' commands:

'set height LPP'
'set height unlimited'
'show height'
'set width CPL'
'set width unlimited'
'show width'
     These 'set' commands specify a screen height of LPP lines and a
     screen width of CPL characters.  The associated 'show' commands
     display the current settings.

     If you specify a height of either 'unlimited' or zero lines, GDB
     does not pause during output no matter how long the output is.
     This is useful if output is to a file or to an editor buffer.

     Likewise, you can specify 'set width unlimited' or 'set width 0' to
     prevent GDB from wrapping its output.

'set pagination on'
'set pagination off'
     Turn the output pagination on or off; the default is on.  Turning
     pagination off is the alternative to 'set height unlimited'.  Note
     that running GDB with the '--batch' option (*note -batch: Mode
     Options.) also automatically disables pagination.

'show pagination'
     Show the current pagination mode.


File: gdb.info,  Node: Output Styling,  Next: Numbers,  Prev: Screen Size,  Up: Controlling GDB

22.5 Output Styling
===================

GDB can style its output on a capable terminal.  This is enabled by
default on most systems, but disabled by default when in batch mode
(*note Mode Options::).  Various style settings are available; and
styles can also be disabled entirely.

'set style enabled 'on|off''
     Enable or disable all styling.  The default is host-dependent, with
     most hosts defaulting to 'on'.

     If the 'NO_COLOR' environment variable is set to a non-empty value,
     then GDB will change this to 'off' at startup.

'show style enabled'
     Show the current state of styling.

'set style sources 'on|off''
     Enable or disable source code styling.  This affects whether source
     code, such as the output of the 'list' command, is styled.  The
     default is 'on'.  Note that source styling only works if styling in
     general is enabled, and if a source highlighting library is
     available to GDB.

     There are two ways that highlighting can be done.  First, if GDB
     was linked with the GNU Source Highlight library, then it is used.
     Otherwise, if GDB was configured with Python scripting support, and
     if the Python Pygments package is available, then it will be used.

'show style sources'
     Show the current state of source code styling.

'set style tui-current-position 'on|off''
     Enable or disable styling of the source and assembly code
     highlighted by the TUI's current position indicator.  The default
     is 'off'.  *Note GDB Text User Interface: TUI.

'show style tui-current-position'
     Show whether the source and assembly code highlighted by the TUI's
     current position indicator is styled.

'set style disassembler enabled 'on|off''
     Enable or disable disassembler styling.  This affects whether
     disassembler output, such as the output of the 'disassemble'
     command, is styled.  Disassembler styling only works if styling in
     general is enabled (with 'set style enabled on'), and if a source
     highlighting library is available to GDB.

     The two source highlighting libraries that GDB could use to style
     disassembler output are; GDB's builtin disassembler, or the Python
     Pygments package.

     GDB's first choice will be to use the builtin disassembler for
     styling, this usually provides better results, being able to style
     different types of instruction operands differently.  However, the
     builtin disassembler is not able to style all architectures.

     For architectures that the builtin disassembler is unable to style,
     GDB will fall back to use the Python Pygments package where
     possible.  In order to use the Python Pygments package, GDB must be
     built with Python support, and the Pygments package must be
     installed.

     If neither of these options are available then GDB will produce
     unstyled disassembler output, even when this setting is 'on'.

     To discover if the current architecture supports styling using the
     builtin disassembler library see *note 'maint show
     libopcodes-styling enabled': maint_libopcodes_styling.

'show style disassembler enabled'
     Show the current state of disassembler styling.

   Subcommands of 'set style' control specific forms of styling.  These
subcommands all follow the same pattern: each style-able object can be
styled with a foreground color, a background color, and an intensity.

   For example, the style of file names can be controlled using the 'set
style filename' group of commands:

'set style filename background COLOR'
     Set the background to COLOR.  Valid colors are 'none' (meaning the
     terminal's default color), 'black', 'red', 'green', 'yellow',
     'blue', 'magenta', 'cyan', and'white'.

'set style filename foreground COLOR'
     Set the foreground to COLOR.  Valid colors are 'none' (meaning the
     terminal's default color), 'black', 'red', 'green', 'yellow',
     'blue', 'magenta', 'cyan', and'white'.

'set style filename intensity VALUE'
     Set the intensity to VALUE.  Valid intensities are 'normal' (the
     default), 'bold', and 'dim'.

   The 'show style' command and its subcommands are styling a style name
in their output using its own style.  So, use 'show style' to see the
complete list of styles, their characteristics and the visual aspect of
each style.

   The style-able objects are:
'filename'
     Control the styling of file names and URLs.  By default, this
     style's foreground color is green.

'function'
     Control the styling of function names.  These are managed with the
     'set style function' family of commands.  By default, this style's
     foreground color is yellow.

     This style is also used for symbol names in styled disassembler
     output if GDB is using its builtin disassembler library for styling
     (*note 'set style disassembler enabled':
     style_disassembler_enabled.).

'variable'
     Control the styling of variable names.  These are managed with the
     'set style variable' family of commands.  By default, this style's
     foreground color is cyan.

'address'
     Control the styling of addresses.  These are managed with the 'set
     style address' family of commands.  By default, this style's
     foreground color is blue.

     This style is also used for addresses in styled disassembler output
     if GDB is using its builtin disassembler library for styling (*note
     'set style disassembler enabled': style_disassembler_enabled.).

'version'
     Control the styling of GDB's version number text.  By default, this
     style's foreground color is magenta and it has bold intensity.  The
     version number is displayed in two places, the output of 'show
     version', and when GDB starts up.

     In order to control how GDB styles the version number at startup,
     add the 'set style version' family of commands to the early
     initialization command file (*note Initialization Files::).

'title'
     Control the styling of titles.  These are managed with the 'set
     style title' family of commands.  By default, this style's
     intensity is bold.  Commands are using the title style to improve
     the readability of large output.  For example, the commands
     'apropos' and 'help' are using the title style for the command
     names.

'highlight'
     Control the styling of highlightings.  These are managed with the
     'set style highlight' family of commands.  By default, this style's
     foreground color is red.  Commands are using the highlight style to
     draw the user attention to some specific parts of their output.
     For example, the command 'apropos -v REGEXP' uses the highlight
     style to mark the documentation parts matching REGEXP.

'metadata'
     Control the styling of data annotations added by GDB to data it
     displays.  By default, this style's intensity is dim.  Metadata
     annotations include the 'repeats N times' annotation for suppressed
     display of repeated array elements (*note Print Settings::),
     '<unavailable>' and '<error DESCR>' annotations for errors and
     '<optimized-out>' annotations for optimized-out values in
     displaying stack frame information in backtraces (*note
     Backtrace::), etc.

'tui-border'
     Control the styling of the TUI border.  Note that, unlike other
     styling options, only the color of the border can be controlled via
     'set style'.  This was done for compatibility reasons, as TUI
     controls to set the border's intensity predated the addition of
     general styling to GDB.  *Note TUI Configuration::.

'tui-active-border'
     Control the styling of the active TUI border; that is, the TUI
     window that has the focus.

'disassembler comment'
     Control the styling of comments in the disassembler output.  These
     are managed with the 'set style disassembler comment' family of
     commands.  This style is only used when GDB is styling using its
     builtin disassembler library (*note 'set style disassembler
     enabled': style_disassembler_enabled.).  By default, this style's
     intensity is dim, and its foreground color is white.

'disassembler immediate'
     Control the styling of numeric operands in the disassembler output.
     These are managed with the 'set style disassembler immediate'
     family of commands.  This style is not used for instruction
     operands that represent addresses, in that case the 'disassembler
     address' style is used.  This style is only used when GDB is
     styling using its builtin disassembler library.  By default, this
     style's foreground color is blue.

'disassembler address'
     Control the styling of address operands in the disassembler output.
     This is an alias for the 'address' style.

'disassembler symbol'
     Control the styling of symbol names in the disassembler output.
     This is an alias for the 'function' style.

'disassembler mnemonic'
     Control the styling of instruction mnemonics in the disassembler
     output.  These are managed with the 'set style disassembler
     mnemonic' family of commands.  This style is also used for
     assembler directives, e.g. '.byte', '.word', etc.  This style is
     only used when GDB is styling using its builtin disassembler
     library.  By default, this style's foreground color is green.

'disassembler register'
     Control the styling of register operands in the disassembler
     output.  These are managed with the 'set style disassembler
     register' family of commands.  This style is only used when GDB is
     styling using its builtin disassembler library.  By default, this
     style's foreground color is red.


File: gdb.info,  Node: Numbers,  Next: ABI,  Prev: Output Styling,  Up: Controlling GDB

22.6 Numbers
============

You can always enter numbers in octal, decimal, or hexadecimal in GDB by
the usual conventions: octal numbers begin with '0', decimal numbers end
with '.', and hexadecimal numbers begin with '0x'.  Numbers that neither
begin with '0' or '0x', nor end with a '.' are, by default, entered in
base 10; likewise, the default display for numbers--when no particular
format is specified--is base 10.  You can change the default base for
both input and output with the commands described below.

'set input-radix BASE'
     Set the default base for numeric input.  Supported choices for BASE
     are decimal 8, 10, or 16.  The base must itself be specified either
     unambiguously or using the current input radix; for example, any of

          set input-radix 012
          set input-radix 10.
          set input-radix 0xa

     sets the input base to decimal.  On the other hand, 'set
     input-radix 10' leaves the input radix unchanged, no matter what it
     was, since '10', being without any leading or trailing signs of its
     base, is interpreted in the current radix.  Thus, if the current
     radix is 16, '10' is interpreted in hex, i.e. as 16 decimal, which
     doesn't change the radix.

'set output-radix BASE'
     Set the default base for numeric display.  Supported choices for
     BASE are decimal 8, 10, or 16.  The base must itself be specified
     either unambiguously or using the current input radix.

'show input-radix'
     Display the current default base for numeric input.

'show output-radix'
     Display the current default base for numeric display.

'set radix [BASE]'
'show radix'
     These commands set and show the default base for both input and
     output of numbers.  'set radix' sets the radix of input and output
     to the same base; without an argument, it resets the radix back to
     its default value of 10.


File: gdb.info,  Node: ABI,  Next: Auto-loading,  Prev: Numbers,  Up: Controlling GDB

22.7 Configuring the Current ABI
================================

GDB can determine the "ABI" (Application Binary Interface) of your
application automatically.  However, sometimes you need to override its
conclusions.  Use these commands to manage GDB's view of the current
ABI.

   One GDB configuration can debug binaries for multiple operating
system targets, either via remote debugging or native emulation.  GDB
will autodetect the "OS ABI" (Operating System ABI) in use, but you can
override its conclusion using the 'set osabi' command.  One example
where this is useful is in debugging of binaries which use an alternate
C library (e.g. UCLIBC for GNU/Linux) which does not have the same
identifying marks that the standard C library for your platform
provides.

   When GDB is debugging the AArch64 architecture, it provides a
"Newlib" OS ABI. This is useful for handling 'setjmp' and 'longjmp' when
debugging binaries that use the NEWLIB C library.  The "Newlib" OS ABI
can be selected by 'set osabi Newlib'.

'show osabi'
     Show the OS ABI currently in use.

'set osabi'
     With no argument, show the list of registered available OS ABI's.

'set osabi ABI'
     Set the current OS ABI to ABI.

   Generally, the way that an argument of type 'float' is passed to a
function depends on whether the function is prototyped.  For a
prototyped (i.e. ANSI/ISO style) function, 'float' arguments are passed
unchanged, according to the architecture's convention for 'float'.  For
unprototyped (i.e. K&R style) functions, 'float' arguments are first
promoted to type 'double' and then passed.

   Unfortunately, some forms of debug information do not reliably
indicate whether a function is prototyped.  If GDB calls a function that
is not marked as prototyped, it consults 'set coerce-float-to-double'.

'set coerce-float-to-double'
'set coerce-float-to-double on'
     Arguments of type 'float' will be promoted to 'double' when passed
     to an unprototyped function.  This is the default setting.

'set coerce-float-to-double off'
     Arguments of type 'float' will be passed directly to unprototyped
     functions.

'show coerce-float-to-double'
     Show the current setting of promoting 'float' to 'double'.

   GDB needs to know the ABI used for your program's C++ objects.  The
correct C++ ABI depends on which C++ compiler was used to build your
application.  GDB only fully supports programs with a single C++ ABI; if
your program contains code using multiple C++ ABI's or if GDB can not
identify your program's ABI correctly, you can tell GDB which ABI to
use.  Currently supported ABI's include "gnu-v2", for 'g++' versions
before 3.0, "gnu-v3", for 'g++' versions 3.0 and later, and "hpaCC" for
the HP ANSI C++ compiler.  Other C++ compilers may use the "gnu-v2" or
"gnu-v3" ABI's as well.  The default setting is "auto".

'show cp-abi'
     Show the C++ ABI currently in use.

'set cp-abi'
     With no argument, show the list of supported C++ ABI's.

'set cp-abi ABI'
'set cp-abi auto'
     Set the current C++ ABI to ABI, or return to automatic detection.


File: gdb.info,  Node: Auto-loading,  Next: Messages/Warnings,  Prev: ABI,  Up: Controlling GDB

22.8 Automatically loading associated files
===========================================

GDB sometimes reads files with commands and settings automatically,
without being explicitly told so by the user.  We call this feature
"auto-loading".  While auto-loading is useful for automatically adapting
GDB to the needs of your project, it can sometimes produce unexpected
results or introduce security risks (e.g., if the file comes from
untrusted sources).

   There are various kinds of files GDB can automatically load.  In
addition to these files, GDB supports auto-loading code written in
various extension languages.  *Note Auto-loading extensions::.

   Note that loading of these associated files (including the local
'.gdbinit' file) requires accordingly configured 'auto-load safe-path'
(*note Auto-loading safe path::).

   For these reasons, GDB includes commands and options to let you
control when to auto-load files and which files should be auto-loaded.

'set auto-load off'
     Globally disable loading of all auto-loaded files.  You may want to
     use this command with the '-iex' option (*note Option
     -init-eval-command::) such as:
          $ gdb -iex "set auto-load off" untrusted-executable corefile

     Be aware that system init file (*note System-wide configuration::)
     and init files from your home directory (*note Home Directory Init
     File::) still get read (as they come from generally trusted
     directories).  To prevent GDB from auto-loading even those init
     files, use the '-nx' option (*note Mode Options::), in addition to
     'set auto-load no'.

'show auto-load'
     Show whether auto-loading of each specific 'auto-load' file(s) is
     enabled or disabled.

          (gdb) show auto-load
          gdb-scripts:  Auto-loading of canned sequences of commands scripts is on.
          libthread-db:  Auto-loading of inferior specific libthread_db is on.
          local-gdbinit:  Auto-loading of .gdbinit script from current directory
                          is on.
          python-scripts:  Auto-loading of Python scripts is on.
          safe-path:  List of directories from which it is safe to auto-load files
                      is $debugdir:$datadir/auto-load.
          scripts-directory:  List of directories from which to load auto-loaded scripts
                              is $debugdir:$datadir/auto-load.

'info auto-load'
     Print whether each specific 'auto-load' file(s) have been
     auto-loaded or not.

          (gdb) info auto-load
          gdb-scripts:
          Loaded  Script
          Yes     /home/user/gdb/gdb-gdb.gdb
          libthread-db:  No auto-loaded libthread-db.
          local-gdbinit:  Local .gdbinit file "/home/user/gdb/.gdbinit" has been
                          loaded.
          python-scripts:
          Loaded  Script
          Yes     /home/user/gdb/gdb-gdb.py

   These are GDB control commands for the auto-loading:

*Note set auto-load off::.           Disable auto-loading globally.
*Note show auto-load::.              Show setting of all kinds of
                                     files.
*Note info auto-load::.              Show state of all kinds of files.
*Note set auto-load gdb-scripts::.   Control for GDB command scripts.
*Note show auto-load gdb-scripts::.  Show setting of GDB command
                                     scripts.
*Note info auto-load gdb-scripts::.  Show state of GDB command scripts.
*Note set auto-load python-scripts::.Control for GDB Python scripts.
*Note show auto-load python-scripts::.Show setting of GDB Python
                                     scripts.
*Note info auto-load python-scripts::.Show state of GDB Python scripts.
*Note set auto-load guile-scripts::. Control for GDB Guile scripts.
*Note show auto-load guile-scripts::.Show setting of GDB Guile scripts.
*Note info auto-load guile-scripts::.Show state of GDB Guile scripts.
*Note set auto-load scripts-directory::.Control for GDB auto-loaded
                                     scripts location.
*Note show auto-load scripts-directory::.Show GDB auto-loaded scripts
                                     location.
*Note add-auto-load-scripts-directory::.Add directory for auto-loaded
                                     scripts location list.
*Note set auto-load local-gdbinit::. Control for init file in the
                                     current directory.
*Note show auto-load local-gdbinit::.Show setting of init file in the
                                     current directory.
*Note info auto-load local-gdbinit::.Show state of init file in the
                                     current directory.
*Note set auto-load libthread-db::.  Control for thread debugging
                                     library.
*Note show auto-load libthread-db::. Show setting of thread debugging
                                     library.
*Note info auto-load libthread-db::. Show state of thread debugging
                                     library.
*Note set auto-load safe-path::.     Control directories trusted for
                                     automatic loading.
*Note show auto-load safe-path::.    Show directories trusted for
                                     automatic loading.
*Note add-auto-load-safe-path::.     Add directory trusted for
                                     automatic loading.

* Menu:

* Init File in the Current Directory:: 'set/show/info auto-load local-gdbinit'
* libthread_db.so.1 file::             'set/show/info auto-load libthread-db'

* Auto-loading safe path::             'set/show/info auto-load safe-path'
* Auto-loading verbose mode::          'set/show debug auto-load'


File: gdb.info,  Node: Init File in the Current Directory,  Next: libthread_db.so.1 file,  Up: Auto-loading

22.8.1 Automatically loading init file in the current directory
---------------------------------------------------------------

By default, GDB reads and executes the canned sequences of commands from
init file (if any) in the current working directory, see *note Init File
in the Current Directory during Startup::.

   Note that loading of this local '.gdbinit' file also requires
accordingly configured 'auto-load safe-path' (*note Auto-loading safe
path::).

'set auto-load local-gdbinit [on|off]'
     Enable or disable the auto-loading of canned sequences of commands
     (*note Sequences::) found in init file in the current directory.

'show auto-load local-gdbinit'
     Show whether auto-loading of canned sequences of commands from init
     file in the current directory is enabled or disabled.

'info auto-load local-gdbinit'
     Print whether canned sequences of commands from init file in the
     current directory have been auto-loaded.


File: gdb.info,  Node: libthread_db.so.1 file,  Next: Auto-loading safe path,  Prev: Init File in the Current Directory,  Up: Auto-loading

22.8.2 Automatically loading thread debugging library
-----------------------------------------------------

This feature is currently present only on GNU/Linux native hosts.

   GDB reads in some cases thread debugging library from places specific
to the inferior (*note set libthread-db-search-path::).

   The special 'libthread-db-search-path' entry '$sdir' is processed
without checking this 'set auto-load libthread-db' switch as system
libraries have to be trusted in general.  In all other cases of
'libthread-db-search-path' entries GDB checks first if 'set auto-load
libthread-db' is enabled before trying to open such thread debugging
library.

   Note that loading of this debugging library also requires accordingly
configured 'auto-load safe-path' (*note Auto-loading safe path::).

'set auto-load libthread-db [on|off]'
     Enable or disable the auto-loading of inferior specific thread
     debugging library.

'show auto-load libthread-db'
     Show whether auto-loading of inferior specific thread debugging
     library is enabled or disabled.

'info auto-load libthread-db'
     Print the list of all loaded inferior specific thread debugging
     libraries and for each such library print list of inferior PIDs
     using it.


File: gdb.info,  Node: Auto-loading safe path,  Next: Auto-loading verbose mode,  Prev: libthread_db.so.1 file,  Up: Auto-loading

22.8.3 Security restriction for auto-loading
--------------------------------------------

As the files of inferior can come from untrusted source (such as
submitted by an application user) GDB does not always load any files
automatically.  GDB provides the 'set auto-load safe-path' setting to
list directories trusted for loading files not explicitly requested by
user.  Each directory can also be a shell wildcard pattern.

   If the path is not set properly you will see a warning and the file
will not get loaded:

     $ ./gdb -q ./gdb
     Reading symbols from /home/user/gdb/gdb...
     warning: File "/home/user/gdb/gdb-gdb.gdb" auto-loading has been
              declined by your `auto-load safe-path' set
              to "$debugdir:$datadir/auto-load".
     warning: File "/home/user/gdb/gdb-gdb.py" auto-loading has been
              declined by your `auto-load safe-path' set
              to "$debugdir:$datadir/auto-load".

To instruct GDB to go ahead and use the init files anyway, invoke GDB
like this:

     $ gdb -q -iex "set auto-load safe-path /home/user/gdb" ./gdb

   The list of trusted directories is controlled by the following
commands:

'set auto-load safe-path [DIRECTORIES]'
     Set the list of directories (and their subdirectories) trusted for
     automatic loading and execution of scripts.  You can also enter a
     specific trusted file.  Each directory can also be a shell wildcard
     pattern; wildcards do not match directory separator - see
     'FNM_PATHNAME' for system function 'fnmatch' (*note fnmatch:
     (libc)Wildcard Matching.).  If you omit DIRECTORIES, 'auto-load
     safe-path' will be reset to its default value as specified during
     GDB compilation.

     The list of directories uses path separator (':' on GNU and Unix
     systems, ';' on MS-Windows and MS-DOS) to separate directories,
     similarly to the 'PATH' environment variable.

'show auto-load safe-path'
     Show the list of directories trusted for automatic loading and
     execution of scripts.

'add-auto-load-safe-path'
     Add an entry (or list of entries) to the list of directories
     trusted for automatic loading and execution of scripts.  Multiple
     entries may be delimited by the host platform path separator in
     use.

   This variable defaults to what '--with-auto-load-dir' has been
configured to (*note with-auto-load-dir::).  '$debugdir' and '$datadir'
substitution applies the same as for *note set auto-load
scripts-directory::.  The default 'set auto-load safe-path' value can be
also overridden by GDB configuration option
'--with-auto-load-safe-path'.

   Setting this variable to '/' disables this security protection,
corresponding GDB configuration option is
'--without-auto-load-safe-path'.  This variable is supposed to be set to
the system directories writable by the system superuser only.  Users can
add their source directories in init files in their home directories
(*note Home Directory Init File::).  See also deprecated init file in
the current directory (*note Init File in the Current Directory during
Startup::).

   To force GDB to load the files it declined to load in the previous
example, you could use one of the following ways:

'~/.gdbinit': 'add-auto-load-safe-path ~/src/gdb'
     Specify this trusted directory (or a file) as additional component
     of the list.  You have to specify also any existing directories
     displayed by by 'show auto-load safe-path' (such as '/usr:/bin' in
     this example).

'gdb -iex "set auto-load safe-path /usr:/bin:~/src/gdb" ...'
     Specify this directory as in the previous case but just for a
     single GDB session.

'gdb -iex "set auto-load safe-path /" ...'
     Disable auto-loading safety for a single GDB session.  This assumes
     all the files you debug during this GDB session will come from
     trusted sources.

'./configure --without-auto-load-safe-path'
     During compilation of GDB you may disable any auto-loading safety.
     This assumes all the files you will ever debug with this GDB come
     from trusted sources.

   On the other hand you can also explicitly forbid automatic files
loading which also suppresses any such warning messages:

'gdb -iex "set auto-load no" ...'
     You can use GDB command-line option for a single GDB session.

'~/.gdbinit': 'set auto-load no'
     Disable auto-loading globally for the user (*note Home Directory
     Init File::).  While it is improbable, you could also use system
     init file instead (*note System-wide configuration::).

   This setting applies to the file names as entered by user.  If no
entry matches GDB tries as a last resort to also resolve all the file
names into their canonical form (typically resolving symbolic links) and
compare the entries again.  GDB already canonicalizes most of the
filenames on its own before starting the comparison so a canonical form
of directories is recommended to be entered.


File: gdb.info,  Node: Auto-loading verbose mode,  Prev: Auto-loading safe path,  Up: Auto-loading

22.8.4 Displaying files tried for auto-load
-------------------------------------------

For better visibility of all the file locations where you can place
scripts to be auto-loaded with inferior -- or to protect yourself
against accidental execution of untrusted scripts -- GDB provides a
feature for printing all the files attempted to be loaded.  Both
existing and non-existing files may be printed.

   For example the list of directories from which it is safe to
auto-load files (*note Auto-loading safe path::) applies also to
canonicalized filenames which may not be too obvious while setting it
up.

     (gdb) set debug auto-load on
     (gdb) file ~/src/t/true
     auto-load: Loading canned sequences of commands script "/tmp/true-gdb.gdb"
                for objfile "/tmp/true".
     auto-load: Updating directories of "/usr:/opt".
     auto-load: Using directory "/usr".
     auto-load: Using directory "/opt".
     warning: File "/tmp/true-gdb.gdb" auto-loading has been declined
              by your `auto-load safe-path' set to "/usr:/opt".

'set debug auto-load [on|off]'
     Set whether to print the filenames attempted to be auto-loaded.

'show debug auto-load'
     Show whether printing of the filenames attempted to be auto-loaded
     is turned on or off.


File: gdb.info,  Node: Messages/Warnings,  Next: Debugging Output,  Prev: Auto-loading,  Up: Controlling GDB

22.9 Optional Warnings and Messages
===================================

By default, GDB is silent about its inner workings.  If you are running
on a slow machine, you may want to use the 'set verbose' command.  This
makes GDB tell you when it does a lengthy internal operation, so you
will not think it has crashed.

   Currently, the messages controlled by 'set verbose' are those which
announce that the symbol table for a source file is being read; see
'symbol-file' in *note Commands to Specify Files: Files.

'set verbose on'
     Enables GDB output of certain informational messages.

'set verbose off'
     Disables GDB output of certain informational messages.

'show verbose'
     Displays whether 'set verbose' is on or off.

   By default, if GDB encounters bugs in the symbol table of an object
file, it is silent; but if you are debugging a compiler, you may find
this information useful (*note Errors Reading Symbol Files: Symbol
Errors.).

'set complaints LIMIT'
     Permits GDB to output LIMIT complaints about each type of unusual
     symbols before becoming silent about the problem.  Set LIMIT to
     zero to suppress all complaints; set it to a large number to
     prevent complaints from being suppressed.

'show complaints'
     Displays how many symbol complaints GDB is permitted to produce.

   By default, GDB is cautious, and asks what sometimes seems to be a
lot of stupid questions to confirm certain commands.  For example, if
you try to run a program which is already running:

     (gdb) run
     The program being debugged has been started already.
     Start it from the beginning? (y or n)

   If you are willing to unflinchingly face the consequences of your own
commands, you can disable this "feature":

'set confirm off'
     Disables confirmation requests.  Note that running GDB with the
     '--batch' option (*note -batch: Mode Options.) also automatically
     disables confirmation requests.

'set confirm on'
     Enables confirmation requests (the default).

'show confirm'
     Displays state of confirmation requests.

   If you need to debug user-defined commands or sourced files you may
find it useful to enable "command tracing".  In this mode each command
will be printed as it is executed, prefixed with one or more '+'
symbols, the quantity denoting the call depth of each command.

'set trace-commands on'
     Enable command tracing.
'set trace-commands off'
     Disable command tracing.
'show trace-commands'
     Display the current state of command tracing.


File: gdb.info,  Node: Debugging Output,  Next: Other Misc Settings,  Prev: Messages/Warnings,  Up: Controlling GDB

22.10 Optional Messages about Internal Happenings
=================================================

GDB has commands that enable optional debugging messages from various
GDB subsystems; normally these commands are of interest to GDB
maintainers, or when reporting a bug.  This section documents those
commands.

'set exec-done-display'
     Turns on or off the notification of asynchronous commands'
     completion.  When on, GDB will print a message when an asynchronous
     command finishes its execution.  The default is off.
'show exec-done-display'
     Displays the current setting of asynchronous command completion
     notification.

'set debug aarch64'
     Turns on or off display of debugging messages related to ARM
     AArch64.  The default is off.
'show debug aarch64'
     Displays the current state of displaying debugging messages related
     to ARM AArch64.

'set debug arch'
     Turns on or off display of gdbarch debugging info.  The default is
     off
'show debug arch'
     Displays the current state of displaying gdbarch debugging info.

'set debug aix-thread'
     Display debugging messages about inner workings of the AIX thread
     module.
'show debug aix-thread'
     Show the current state of AIX thread debugging info display.

'set debug amd-dbgapi-lib'
'show debug amd-dbgapi-lib'

     The 'set debug amd-dbgapi-lib log-level LEVEL' command can be used
     to enable diagnostic messages from the 'amd-dbgapi' library, where
     LEVEL can be:

     'off'
          no logging is enabled

     'error'
          fatal errors are reported

     'warning'
          fatal errors and warnings are reported

     'info'
          fatal errors, warnings, and info messages are reported

     'verbose'
          all messages are reported

     The 'show debug amd-dbgapi-lib log-level' command displays the
     current amd-dbgapi library log level.

'set debug amd-dbgapi'
'show debug amd-dbgapi'

     The 'set debug amd-dbgapi' command can be used to enable diagnostic
     messages in the 'amd-dbgapi' target.  The 'show debug amd-dbgapi'
     command displays the current setting.  *Note set debug
     amd-dbgapi::.

'set debug check-physname'
     Check the results of the "physname" computation.  When reading
     DWARF debugging information for C++, GDB attempts to compute each
     entity's name.  GDB can do this computation in two different ways,
     depending on exactly what information is present.  When enabled,
     this setting causes GDB to compute the names both ways and display
     any discrepancies.
'show debug check-physname'
     Show the current state of "physname" checking.

'set debug coff-pe-read'
     Control display of debugging messages related to reading of COFF/PE
     exported symbols.  The default is off.
'show debug coff-pe-read'
     Displays the current state of displaying debugging messages related
     to reading of COFF/PE exported symbols.

'set debug dwarf-die'
     Dump DWARF DIEs after they are read in.  The value is the number of
     nesting levels to print.  A value of zero turns off the display.
'show debug dwarf-die'
     Show the current state of DWARF DIE debugging.

'set debug dwarf-line'
     Turns on or off display of debugging messages related to reading
     DWARF line tables.  The default is 0 (off).  A value of 1 provides
     basic information.  A value greater than 1 provides more verbose
     information.
'show debug dwarf-line'
     Show the current state of DWARF line table debugging.

'set debug dwarf-read'
     Turns on or off display of debugging messages related to reading
     DWARF debug info.  The default is 0 (off).  A value of 1 provides
     basic information.  A value greater than 1 provides more verbose
     information.
'show debug dwarf-read'
     Show the current state of DWARF reader debugging.

'set debug displaced'
     Turns on or off display of GDB debugging info for the displaced
     stepping support.  The default is off.
'show debug displaced'
     Displays the current state of displaying GDB debugging info related
     to displaced stepping.

'set debug event'
     Turns on or off display of GDB event debugging info.  The default
     is off.
'show debug event'
     Displays the current state of displaying GDB event debugging info.

'set debug event-loop'
     Controls output of debugging info about the event loop.  The
     possible values are 'off', 'all' (shows all debugging info) and
     'all-except-ui' (shows all debugging info except those about
     UI-related events).
'show debug event-loop'
     Shows the current state of displaying debugging info about the
     event loop.

'set debug expression'
     Turns on or off display of debugging info about GDB expression
     parsing.  The default is off.
'show debug expression'
     Displays the current state of displaying debugging info about GDB
     expression parsing.

'set debug fbsd-lwp'
     Turns on or off debugging messages from the FreeBSD LWP debug
     support.
'show debug fbsd-lwp'
     Show the current state of FreeBSD LWP debugging messages.

'set debug fbsd-nat'
     Turns on or off debugging messages from the FreeBSD native target.
'show debug fbsd-nat'
     Show the current state of FreeBSD native target debugging messages.

'set debug fortran-array-slicing'
     Turns on or off display of GDB Fortran array slicing debugging
     info.  The default is off.

'show debug fortran-array-slicing'
     Displays the current state of displaying GDB Fortran array slicing
     debugging info.

'set debug frame'
     Turns on or off display of GDB frame debugging info.  The default
     is off.
'show debug frame'
     Displays the current state of displaying GDB frame debugging info.

'set debug gnu-nat'
     Turn on or off debugging messages from the GNU/Hurd debug support.
'show debug gnu-nat'
     Show the current state of GNU/Hurd debugging messages.

'set debug infrun'
     Turns on or off display of GDB debugging info for running the
     inferior.  The default is off.  'infrun.c' contains GDB's runtime
     state machine used for implementing operations such as
     single-stepping the inferior.
'show debug infrun'
     Displays the current state of GDB inferior debugging.

'set debug infcall'
     Turns on or off display of debugging info related to inferior
     function calls made by GDB.
'show debug infcall'
     Displays the current state of GDB inferior function call debugging.

'set debug jit'
     Turn on or off debugging messages from JIT debug support.
'show debug jit'
     Displays the current state of GDB JIT debugging.

'set debug linux-nat [on|off]'
     Turn on or off debugging messages from the Linux native target
     debug support.
'show debug linux-nat'
     Show the current state of Linux native target debugging messages.

'set debug linux-namespaces'
     Turn on or off debugging messages from the Linux namespaces debug
     support.
'show debug linux-namespaces'
     Show the current state of Linux namespaces debugging messages.

'set debug mach-o'
     Control display of debugging messages related to Mach-O symbols
     processing.  The default is off.
'show debug mach-o'
     Displays the current state of displaying debugging messages related
     to reading of COFF/PE exported symbols.

'set debug notification'
     Turn on or off debugging messages about remote async notification.
     The default is off.
'show debug notification'
     Displays the current state of remote async notification debugging
     messages.

'set debug observer'
     Turns on or off display of GDB observer debugging.  This includes
     info such as the notification of observable events.
'show debug observer'
     Displays the current state of observer debugging.

'set debug overload'
     Turns on or off display of GDB C++ overload debugging info.  This
     includes info such as ranking of functions, etc.  The default is
     off.
'show debug overload'
     Displays the current state of displaying GDB C++ overload debugging
     info.

'set debug parser'
     Turns on or off the display of expression parser debugging output.
     Internally, this sets the 'yydebug' variable in the expression
     parser.  *Note Tracing Your Parser: (bison)Tracing, for details.
     The default is off.
'show debug parser'
     Show the current state of expression parser debugging.

'set debug remote'
     Turns on or off display of reports on all packets sent back and
     forth across the serial line to the remote machine.  The info is
     printed on the GDB standard output stream.  The default is off.
'show debug remote'
     Displays the state of display of remote packets.

'set debug remote-packet-max-chars'
     Sets the maximum number of characters to display for each remote
     packet when 'set debug remote' is on.  This is useful to prevent
     GDB from displaying lengthy remote packets and polluting the
     console.

     The default value is '512', which means GDB will truncate each
     remote packet after 512 bytes.

     Setting this option to 'unlimited' will disable truncation and will
     output the full length of the remote packets.
'show debug remote-packet-max-chars'
     Displays the number of bytes to output for remote packet debugging.

'set debug separate-debug-file'
     Turns on or off display of debug output about separate debug file
     search.
'show debug separate-debug-file'
     Displays the state of separate debug file search debug output.

'set debug serial'
     Turns on or off display of GDB serial debugging info.  The default
     is off.
'show debug serial'
     Displays the current state of displaying GDB serial debugging info.

'set debug solib'
     Turns on or off display of debugging messages related to shared
     libraries.  The default is off.
'show debug solib'
     Show the current state of solib debugging messages.

'set debug symbol-lookup'
     Turns on or off display of debugging messages related to symbol
     lookup.  The default is 0 (off).  A value of 1 provides basic
     information.  A value greater than 1 provides more verbose
     information.
'show debug symbol-lookup'
     Show the current state of symbol lookup debugging messages.

'set debug symfile'
     Turns on or off display of debugging messages related to symbol
     file functions.  The default is off.  *Note Files::.
'show debug symfile'
     Show the current state of symbol file debugging messages.

'set debug symtab-create'
     Turns on or off display of debugging messages related to symbol
     table creation.  The default is 0 (off).  A value of 1 provides
     basic information.  A value greater than 1 provides more verbose
     information.
'show debug symtab-create'
     Show the current state of symbol table creation debugging.

'set debug target'
     Turns on or off display of GDB target debugging info.  This info
     includes what is going on at the target level of GDB, as it
     happens.  The default is 0.  Set it to 1 to track events, and to 2
     to also track the value of large memory transfers.
'show debug target'
     Displays the current state of displaying GDB target debugging info.

'set debug timestamp'
     Turns on or off display of timestamps with GDB debugging info.
     When enabled, seconds and microseconds are displayed before each
     debugging message.
'show debug timestamp'
     Displays the current state of displaying timestamps with GDB
     debugging info.

'set debug varobj'
     Turns on or off display of GDB variable object debugging info.  The
     default is off.
'show debug varobj'
     Displays the current state of displaying GDB variable object
     debugging info.

'set debug xml'
     Turn on or off debugging messages for built-in XML parsers.
'show debug xml'
     Displays the current state of XML debugging messages.

'set debug breakpoints'
     Turns on or off display of GDB debugging info for breakpoint
     insertion and removal.  The default is off.
'show debug breakpoints'
     Displays the current state of displaying GDB debugging info for
     breakpoint insertion and removal.


File: gdb.info,  Node: Other Misc Settings,  Prev: Debugging Output,  Up: Controlling GDB

22.11 Other Miscellaneous Settings
==================================

'set interactive-mode'
     If 'on', forces GDB to assume that GDB was started in a terminal.
     In practice, this means that GDB should wait for the user to answer
     queries generated by commands entered at the command prompt.  If
     'off', forces GDB to operate in the opposite mode, and it uses the
     default answers to all queries.  If 'auto' (the default), GDB tries
     to determine whether its standard input is a terminal, and works in
     interactive-mode if it is, non-interactively otherwise.

     In the vast majority of cases, the debugger should be able to guess
     correctly which mode should be used.  But this setting can be
     useful in certain specific cases, such as running a MinGW GDB
     inside a cygwin window.

'show interactive-mode'
     Displays whether the debugger is operating in interactive mode or
     not.

'set suppress-cli-notifications'
     If 'on', command-line-interface (CLI) notifications that are
     printed by GDB are suppressed.  If 'off', the notifications are
     printed as usual.  The default value is 'off'.  CLI notifications
     occur when you change the selected context or when the program
     being debugged stops, as detailed below.

     _User-selected context changes:_
          When you change the selected context (i.e. the current
          inferior, thread and/or the frame), GDB prints information
          about the new context.  For example, the default behavior is
          below:

               (gdb) inferior 1
               [Switching to inferior 1 [process 634] (/tmp/test)]
               [Switching to thread 1 (process 634)]
               #0  main () at test.c:3
               3         return 0;
               (gdb)

          When the notifications are suppressed, the new context is not
          printed:

               (gdb) set suppress-cli-notifications on
               (gdb) inferior 1
               (gdb)

     _The program being debugged stops:_
          When the program you are debugging stops (e.g. because of
          hitting a breakpoint, completing source-stepping, an
          interrupt, etc.), GDB prints information about the stop event.
          For example, below is a breakpoint hit:

               (gdb) break test.c:3
               Breakpoint 2 at 0x555555555155: file test.c, line 3.
               (gdb) continue
               Continuing.

               Breakpoint 2, main () at test.c:3
               3         return 0;
               (gdb)

          When the notifications are suppressed, the output becomes:

               (gdb) break test.c:3
               Breakpoint 2 at 0x555555555155: file test.c, line 3.
               (gdb) set suppress-cli-notifications on
               (gdb) continue
               Continuing.
               (gdb)

          Suppressing CLI notifications may be useful in scripts to
          obtain a reduced output from a list of commands.

'show suppress-cli-notifications'
     Displays whether printing CLI notifications is suppressed or not.


File: gdb.info,  Node: Extending GDB,  Next: Interpreters,  Prev: Controlling GDB,  Up: Top

23 Extending GDB
****************

GDB provides several mechanisms for extension.  GDB also provides the
ability to automatically load extensions when it reads a file for
debugging.  This allows the user to automatically customize GDB for the
program being debugged.

   To facilitate the use of extension languages, GDB is capable of
evaluating the contents of a file.  When doing so, GDB can recognize
which extension language is being used by looking at the filename
extension.  Files with an unrecognized filename extension are always
treated as a GDB Command Files.  *Note Command files: Command Files.

   You can control how GDB evaluates these files with the following
setting:

'set script-extension off'
     All scripts are always evaluated as GDB Command Files.

'set script-extension soft'
     The debugger determines the scripting language based on filename
     extension.  If this scripting language is supported, GDB evaluates
     the script using that language.  Otherwise, it evaluates the file
     as a GDB Command File.

'set script-extension strict'
     The debugger determines the scripting language based on filename
     extension, and evaluates the script using that language.  If the
     language is not supported, then the evaluation fails.

'show script-extension'
     Display the current value of the 'script-extension' option.

* Menu:

* Sequences::                Canned Sequences of GDB Commands
* Aliases::                  Command Aliases
* Python::                   Extending GDB using Python
* Guile::                    Extending GDB using Guile
* Auto-loading extensions::  Automatically loading extensions
* Multiple Extension Languages:: Working with multiple extension languages


File: gdb.info,  Node: Sequences,  Next: Aliases,  Up: Extending GDB

23.1 Canned Sequences of Commands
=================================

Aside from breakpoint commands (*note Breakpoint Command Lists: Break
Commands.), GDB provides two ways to store sequences of commands for
execution as a unit: user-defined commands and command files.

* Menu:

* Define::             How to define your own commands
* Hooks::              Hooks for user-defined commands
* Command Files::      How to write scripts of commands to be stored in a file
* Output::             Commands for controlled output
* Auto-loading sequences::  Controlling auto-loaded command files


File: gdb.info,  Node: Define,  Next: Hooks,  Up: Sequences

23.1.1 User-defined Commands
----------------------------

A "user-defined command" is a sequence of GDB commands to which you
assign a new name as a command.  This is done with the 'define' command.
User commands may accept an unlimited number of arguments separated by
whitespace.  Arguments are accessed within the user command via
'$arg0...$argN'.  A trivial example:

     define adder
       print $arg0 + $arg1 + $arg2
     end

To execute the command use:

     adder 1 2 3

This defines the command 'adder', which prints the sum of its three
arguments.  Note the arguments are text substitutions, so they may
reference variables, use complex expressions, or even perform inferior
functions calls.

   In addition, '$argc' may be used to find out how many arguments have
been passed.

     define adder
       if $argc == 2
         print $arg0 + $arg1
       end
       if $argc == 3
         print $arg0 + $arg1 + $arg2
       end
     end

   Combining with the 'eval' command (*note eval::) makes it easier to
process a variable number of arguments:

     define adder
       set $i = 0
       set $sum = 0
       while $i < $argc
         eval "set $sum = $sum + $arg%d", $i
         set $i = $i + 1
       end
       print $sum
     end

'define COMMANDNAME'
     Define a command named COMMANDNAME.  If there is already a command
     by that name, you are asked to confirm that you want to redefine
     it.  The argument COMMANDNAME may be a bare command name consisting
     of letters, numbers, dashes, dots, and underscores.  It may also
     start with any predefined or user-defined prefix command.  For
     example, 'define target my-target' creates a user-defined 'target
     my-target' command.

     The definition of the command is made up of other GDB command
     lines, which are given following the 'define' command.  The end of
     these commands is marked by a line containing 'end'.

'document COMMANDNAME'
     Document the user-defined command COMMANDNAME, so that it can be
     accessed by 'help'.  The command COMMANDNAME must already be
     defined.  This command reads lines of documentation just as
     'define' reads the lines of the command definition, ending with
     'end'.  After the 'document' command is finished, 'help' on command
     COMMANDNAME displays the documentation you have written.

     You may use the 'document' command again to change the
     documentation of a command.  Redefining the command with 'define'
     does not change the documentation.

     It is also possible to document user-defined aliases.  The alias
     documentation will then be used by the 'help' and 'apropos'
     commands instead of the documentation of the aliased command.
     Documenting a user-defined alias is particularly useful when
     defining an alias as a set of nested 'with' commands (*note Command
     aliases default args::).

'define-prefix COMMANDNAME'
     Define or mark the command COMMANDNAME as a user-defined prefix
     command.  Once marked, COMMANDNAME can be used as prefix command by
     the 'define' command.  Note that 'define-prefix' can be used with a
     not yet defined COMMANDNAME.  In such a case, COMMANDNAME is
     defined as an empty user-defined command.  In case you redefine a
     command that was marked as a user-defined prefix command, the
     subcommands of the redefined command are kept (and GDB indicates so
     to the user).

     Example:
          (gdb) define-prefix abc
          (gdb) define-prefix abc def
          (gdb) define abc def
          Type commands for definition of "abc def".
          End with a line saying just "end".
          >echo command initial def\n
          >end
          (gdb) define abc def ghi
          Type commands for definition of "abc def ghi".
          End with a line saying just "end".
          >echo command ghi\n
          >end
          (gdb) define abc def
          Keeping subcommands of prefix command "def".
          Redefine command "def"? (y or n) y
          Type commands for definition of "abc def".
          End with a line saying just "end".
          >echo command def\n
          >end
          (gdb) abc def ghi
          command ghi
          (gdb) abc def
          command def
          (gdb)

'dont-repeat'
     Used inside a user-defined command, this tells GDB that this
     command should not be repeated when the user hits <RET> (*note
     repeat last command: Command Syntax.).

'help user-defined'
     List all user-defined commands and all python commands defined in
     class COMMAND_USER. The first line of the documentation or
     docstring is included (if any).

'show user'
'show user COMMANDNAME'
     Display the GDB commands used to define COMMANDNAME (but not its
     documentation).  If no COMMANDNAME is given, display the
     definitions for all user-defined commands.  This does not work for
     user-defined python commands.

'show max-user-call-depth'
'set max-user-call-depth'
     The value of 'max-user-call-depth' controls how many recursion
     levels are allowed in user-defined commands before GDB suspects an
     infinite recursion and aborts the command.  This does not apply to
     user-defined python commands.

   In addition to the above commands, user-defined commands frequently
use control flow commands, described in *note Command Files::.

   When user-defined commands are executed, the commands of the
definition are not printed.  An error in any command stops execution of
the user-defined command.

   If used interactively, commands that would ask for confirmation
proceed without asking when used inside a user-defined command.  Many
GDB commands that normally print messages to say what they are doing
omit the messages when used in a user-defined command.


File: gdb.info,  Node: Hooks,  Next: Command Files,  Prev: Define,  Up: Sequences

23.1.2 User-defined Command Hooks
---------------------------------

You may define "hooks", which are a special kind of user-defined
command.  Whenever you run the command 'foo', if the user-defined
command 'hook-foo' exists, it is executed (with no arguments) before
that command.

   A hook may also be defined which is run after the command you
executed.  Whenever you run the command 'foo', if the user-defined
command 'hookpost-foo' exists, it is executed (with no arguments) after
that command.  Post-execution hooks may exist simultaneously with
pre-execution hooks, for the same command.

   It is valid for a hook to call the command which it hooks.  If this
occurs, the hook is not re-executed, thereby avoiding infinite
recursion.

   In addition, a pseudo-command, 'stop' exists.  Defining ('hook-stop')
makes the associated commands execute every time execution stops in your
program: before breakpoint commands are run, displays are printed, or
the stack frame is printed.

   For example, to ignore 'SIGALRM' signals while single-stepping, but
treat them normally during normal execution, you could define:

     define hook-stop
     handle SIGALRM nopass
     end

     define hook-run
     handle SIGALRM pass
     end

     define hook-continue
     handle SIGALRM pass
     end

   As a further example, to hook at the beginning and end of the 'echo'
command, and to add extra text to the beginning and end of the message,
you could define:

     define hook-echo
     echo <<<---
     end

     define hookpost-echo
     echo --->>>\n
     end

     (gdb) echo Hello World
     <<<---Hello World--->>>
     (gdb)


   You can define a hook for any single-word command in GDB, but not for
command aliases; you should define a hook for the basic command name,
e.g. 'backtrace' rather than 'bt'.  You can hook a multi-word command by
adding 'hook-' or 'hookpost-' to the last word of the command, e.g.
'define target hook-remote' to add a hook to 'target remote'.

   If an error occurs during the execution of your hook, execution of
GDB commands stops and GDB issues a prompt (before the command that you
actually typed had a chance to run).

   If you try to define a hook which does not match any known command,
you get a warning from the 'define' command.


File: gdb.info,  Node: Command Files,  Next: Output,  Prev: Hooks,  Up: Sequences

23.1.3 Command Files
--------------------

A command file for GDB is a text file made of lines that are GDB
commands.  Comments (lines starting with '#') may also be included.  An
empty line in a command file does nothing; it does not mean to repeat
the last command, as it would from the terminal.

   You can request the execution of a command file with the 'source'
command.  Note that the 'source' command is also used to evaluate
scripts that are not Command Files.  The exact behavior can be
configured using the 'script-extension' setting.  *Note Extending GDB:
Extending GDB.

'source [-s] [-v] FILENAME'
     Execute the command file FILENAME.

   The lines in a command file are generally executed sequentially,
unless the order of execution is changed by one of the _flow-control
commands_ described below.  The commands are not printed as they are
executed.  An error in any command terminates execution of the command
file and control is returned to the console.

   GDB first searches for FILENAME in the current directory.  If the
file is not found there, and FILENAME does not specify a directory, then
GDB also looks for the file on the source search path (specified with
the 'directory' command); except that '$cdir' is not searched because
the compilation directory is not relevant to scripts.

   If '-s' is specified, then GDB searches for FILENAME on the search
path even if FILENAME specifies a directory.  The search is done by
appending FILENAME to each element of the search path.  So, for example,
if FILENAME is 'mylib/myscript' and the search path contains
'/home/user' then GDB will look for the script
'/home/user/mylib/myscript'.  The search is also done if FILENAME is an
absolute path.  For example, if FILENAME is '/tmp/myscript' and the
search path contains '/home/user' then GDB will look for the script
'/home/user/tmp/myscript'.  For DOS-like systems, if FILENAME contains a
drive specification, it is stripped before concatenation.  For example,
if FILENAME is 'd:myscript' and the search path contains 'c:/tmp' then
GDB will look for the script 'c:/tmp/myscript'.

   If '-v', for verbose mode, is given then GDB displays each command as
it is executed.  The option must be given before FILENAME, and is
interpreted as part of the filename anywhere else.

   Commands that would ask for confirmation if used interactively
proceed without asking when used in a command file.  Many GDB commands
that normally print messages to say what they are doing omit the
messages when called from command files.

   GDB also accepts command input from standard input.  In this mode,
normal output goes to standard output and error output goes to standard
error.  Errors in a command file supplied on standard input do not
terminate execution of the command file--execution continues with the
next command.

     gdb < cmds > log 2>&1

   (The syntax above will vary depending on the shell used.)  This
example will execute commands from the file 'cmds'.  All output and
errors would be directed to 'log'.

   Since commands stored on command files tend to be more general than
commands typed interactively, they frequently need to deal with
complicated situations, such as different or unexpected values of
variables and symbols, changes in how the program being debugged is
built, etc.  GDB provides a set of flow-control commands to deal with
these complexities.  Using these commands, you can write complex scripts
that loop over data structures, execute commands conditionally, etc.

'if'
'else'
     This command allows to include in your script conditionally
     executed commands.  The 'if' command takes a single argument, which
     is an expression to evaluate.  It is followed by a series of
     commands that are executed only if the expression is true (its
     value is nonzero).  There can then optionally be an 'else' line,
     followed by a series of commands that are only executed if the
     expression was false.  The end of the list is marked by a line
     containing 'end'.

'while'
     This command allows to write loops.  Its syntax is similar to 'if':
     the command takes a single argument, which is an expression to
     evaluate, and must be followed by the commands to execute, one per
     line, terminated by an 'end'.  These commands are called the "body"
     of the loop.  The commands in the body of 'while' are executed
     repeatedly as long as the expression evaluates to true.

'loop_break'
     This command exits the 'while' loop in whose body it is included.
     Execution of the script continues after that 'while's 'end' line.

'loop_continue'
     This command skips the execution of the rest of the body of
     commands in the 'while' loop in whose body it is included.
     Execution branches to the beginning of the 'while' loop, where it
     evaluates the controlling expression.

'end'
     Terminate the block of commands that are the body of 'if', 'else',
     or 'while' flow-control commands.


File: gdb.info,  Node: Output,  Next: Auto-loading sequences,  Prev: Command Files,  Up: Sequences

23.1.4 Commands for Controlled Output
-------------------------------------

During the execution of a command file or a user-defined command, normal
GDB output is suppressed; the only output that appears is what is
explicitly printed by the commands in the definition.  This section
describes three commands useful for generating exactly the output you
want.

'echo TEXT'
     Print TEXT.  Nonprinting characters can be included in TEXT using C
     escape sequences, such as '\n' to print a newline.  *No newline is
     printed unless you specify one.*  In addition to the standard C
     escape sequences, a backslash followed by a space stands for a
     space.  This is useful for displaying a string with spaces at the
     beginning or the end, since leading and trailing spaces are
     otherwise trimmed from all arguments.  To print ' and foo = ', use
     the command 'echo \ and foo = \ '.

     A backslash at the end of TEXT can be used, as in C, to continue
     the command onto subsequent lines.  For example,

          echo This is some text\n\
          which is continued\n\
          onto several lines.\n

     produces the same output as

          echo This is some text\n
          echo which is continued\n
          echo onto several lines.\n

'output EXPRESSION'
     Print the value of EXPRESSION and nothing but that value: no
     newlines, no '$NN = '.  The value is not entered in the value
     history either.  *Note Expressions: Expressions, for more
     information on expressions.

'output/FMT EXPRESSION'
     Print the value of EXPRESSION in format FMT.  You can use the same
     formats as for 'print'.  *Note Output Formats: Output Formats, for
     more information.

'printf TEMPLATE, EXPRESSIONS...'
     Print the values of one or more EXPRESSIONS under the control of
     the string TEMPLATE.  To print several values, make EXPRESSIONS be
     a comma-separated list of individual expressions, which may be
     either numbers or pointers.  Their values are printed as specified
     by TEMPLATE, exactly as a C program would do by executing the code
     below:

          printf (TEMPLATE, EXPRESSIONS...);

     As in 'C' 'printf', ordinary characters in TEMPLATE are printed
     verbatim, while "conversion specification" introduced by the '%'
     character cause subsequent EXPRESSIONS to be evaluated, their
     values converted and formatted according to type and style
     information encoded in the conversion specifications, and then
     printed.

     For example, you can print two values in hex like this:

          printf "foo, bar-foo = 0x%x, 0x%x\n", foo, bar-foo

     'printf' supports all the standard 'C' conversion specifications,
     including the flags and modifiers between the '%' character and the
     conversion letter, with the following exceptions:

        * The argument-ordering modifiers, such as '2$', are not
          supported.

        * The modifier '*' is not supported for specifying precision or
          width.

        * The ''' flag (for separation of digits into groups according
          to 'LC_NUMERIC'') is not supported.

        * The type modifiers 'hh', 'j', 't', and 'z' are not supported.

        * The conversion letter 'n' (as in '%n') is not supported.

        * The conversion letters 'a' and 'A' are not supported.

     Note that the 'll' type modifier is supported only if the
     underlying 'C' implementation used to build GDB supports the 'long
     long int' type, and the 'L' type modifier is supported only if
     'long double' type is available.

     As in 'C', 'printf' supports simple backslash-escape sequences,
     such as '\n', '\t', '\\', '\"', '\a', and '\f', that consist of
     backslash followed by a single character.  Octal and hexadecimal
     escape sequences are not supported.

     Additionally, 'printf' supports conversion specifications for DFP
     ("Decimal Floating Point") types using the following length
     modifiers together with a floating point specifier.  letters:

        * 'H' for printing 'Decimal32' types.

        * 'D' for printing 'Decimal64' types.

        * 'DD' for printing 'Decimal128' types.

     If the underlying 'C' implementation used to build GDB has support
     for the three length modifiers for DFP types, other modifiers such
     as width and precision will also be available for GDB to use.

     In case there is no such 'C' support, no additional modifiers will
     be available and the value will be printed in the standard way.

     Here's an example of printing DFP types using the above conversion
     letters:
          printf "D32: %Hf - D64: %Df - D128: %DDf\n",1.2345df,1.2E10dd,1.2E1dl

     Additionally, 'printf' supports a special '%V' output format.  This
     format prints the string representation of an expression just as
     GDB would produce with the standard 'print' command (*note
     Examining Data: Data.):

          (gdb) print array
          $1 = {0, 1, 2, 3, 4, 5}
          (gdb) printf "Array is: %V\n", array
          Array is: {0, 1, 2, 3, 4, 5}

     It is possible to include print options with the '%V' format by
     placing them in '[...]' immediately after the '%V', like this:

          (gdb) printf "Array is: %V[-array-indexes on]\n", array
          Array is: {[0] = 0, [1] = 1, [2] = 2, [3] = 3, [4] = 4, [5] = 5}

     If you need to print a literal '[' directly after a '%V', then just
     include an empty print options list:

          (gdb) printf "Array is: %V[][Hello]\n", array
          Array is: {0, 1, 2, 3, 4, 5}[Hello]

'eval TEMPLATE, EXPRESSIONS...'
     Convert the values of one or more EXPRESSIONS under the control of
     the string TEMPLATE to a command line, and call it.


File: gdb.info,  Node: Auto-loading sequences,  Prev: Output,  Up: Sequences

23.1.5 Controlling auto-loading native GDB scripts
--------------------------------------------------

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
the command file 'OBJFILE-gdb.gdb'.  *Note Auto-loading extensions::.

   Auto-loading can be enabled or disabled, and the list of auto-loaded
scripts can be printed.

'set auto-load gdb-scripts [on|off]'
     Enable or disable the auto-loading of canned sequences of commands
     scripts.

'show auto-load gdb-scripts'
     Show whether auto-loading of canned sequences of commands scripts
     is enabled or disabled.

'info auto-load gdb-scripts [REGEXP]'
     Print the list of all canned sequences of commands scripts that GDB
     auto-loaded.

   If REGEXP is supplied only canned sequences of commands scripts with
matching names are printed.


File: gdb.info,  Node: Aliases,  Next: Python,  Prev: Sequences,  Up: Extending GDB

23.2 Command Aliases
====================

Aliases allow you to define alternate spellings for existing commands.
For example, if a new GDB command defined in Python (*note Python::) has
a long name, it is handy to have an abbreviated version of it that
involves less typing.

   GDB itself uses aliases.  For example 's' is an alias of the 'step'
command even though it is otherwise an ambiguous abbreviation of other
commands like 'set' and 'show'.

   Aliases are also used to provide shortened or more common versions of
multi-word commands.  For example, GDB provides the 'tty' alias of the
'set inferior-tty' command.

   You can define a new alias with the 'alias' command.

'alias [-a] [--] ALIAS = COMMAND [DEFAULT-ARGS]'

   ALIAS specifies the name of the new alias.  Each word of ALIAS must
consist of letters, numbers, dashes and underscores.

   COMMAND specifies the name of an existing command that is being
aliased.

   COMMAND can also be the name of an existing alias.  In this case,
COMMAND cannot be an alias that has default arguments.

   The '-a' option specifies that the new alias is an abbreviation of
the command.  Abbreviations are not used in command completion.

   The '--' option specifies the end of options, and is useful when
ALIAS begins with a dash.

   You can specify DEFAULT-ARGS for your alias.  These DEFAULT-ARGS will
be automatically added before the alias arguments typed explicitly on
the command line.

   For example, the below defines an alias 'btfullall' that shows all
local variables and all frame arguments:
     (gdb) alias btfullall = backtrace -full -frame-arguments all

   For more information about DEFAULT-ARGS, see *note Default Arguments:
Command aliases default args.

   Here is a simple example showing how to make an abbreviation of a
command so that there is less to type.  Suppose you were tired of typing
'disas', the current shortest unambiguous abbreviation of the
'disassemble' command and you wanted an even shorter version named 'di'.
The following will accomplish this.

     (gdb) alias -a di = disas

   Note that aliases are different from user-defined commands.  With a
user-defined command, you also need to write documentation for it with
the 'document' command.  An alias automatically picks up the
documentation of the existing command.

   Here is an example where we make 'elms' an abbreviation of 'elements'
in the 'set print elements' command.  This is to show that you can make
an abbreviation of any part of a command.

     (gdb) alias -a set print elms = set print elements
     (gdb) alias -a show print elms = show print elements
     (gdb) set p elms 200
     (gdb) show p elms
     Limit on string chars or array elements to print is 200.

   Note that if you are defining an alias of a 'set' command, and you
want to have an alias for the corresponding 'show' command, then you
need to define the latter separately.

   Unambiguously abbreviated commands are allowed in COMMAND and ALIAS,
just as they are normally.

     (gdb) alias -a set pr elms = set p ele

   Finally, here is an example showing the creation of a one word alias
for a more complex command.  This creates alias 'spe' of the command
'set print elements'.

     (gdb) alias spe = set print elements
     (gdb) spe 20

* Menu:

* Command aliases default args::        Default arguments for aliases


File: gdb.info,  Node: Command aliases default args,  Up: Aliases

23.2.1 Default Arguments
------------------------

You can tell GDB to always prepend some default arguments to the list of
arguments provided explicitly by the user when using a user-defined
alias.

   If you repeatedly use the same arguments or options for a command,
you can define an alias for this command and tell GDB to automatically
prepend these arguments or options to the list of arguments you type
explicitly when using the alias(1).

   For example, if you often use the command 'thread apply all'
specifying to work on the threads in ascending order and to continue in
case it encounters an error, you can tell GDB to automatically preprend
the '-ascending' and '-c' options by using:

     (gdb) alias thread apply asc-all = thread apply all -ascending -c

   Once you have defined this alias with its default args, any time you
type the 'thread apply asc-all' followed by 'some arguments', GDB will
execute 'thread apply all -ascending -c some arguments'.

   To have even less to type, you can also define a one word alias:
     (gdb) alias t_a_c = thread apply all -ascending -c

   As usual, unambiguous abbreviations can be used for ALIAS and
DEFAULT-ARGS.

   The different aliases of a command do not share their default args.
For example, you define a new alias 'bt_ALL' showing all possible
information and another alias 'bt_SMALL' showing very limited
information using:
     (gdb) alias bt_ALL = backtrace -entry-values both -frame-arg all \
        -past-main -past-entry -full
     (gdb) alias bt_SMALL = backtrace -entry-values no -frame-arg none \
        -past-main off -past-entry off

   (For more on using the 'alias' command, see *note Aliases::.)

   Default args are not limited to the arguments and options of COMMAND,
but can specify nested commands if COMMAND accepts such a nested command
as argument.  For example, the below defines 'faalocalsoftype' that
lists the frames having locals of a certain type, together with the
matching local vars:
     (gdb) alias faalocalsoftype = frame apply all info locals -q -t
     (gdb) faalocalsoftype int
     #1  0x55554f5e in sleeper_or_burner (v=0xdf50) at sleepers.c:86
     i = 0
     ret = 21845

   This is also very useful to define an alias for a set of nested
'with' commands to have a particular combination of temporary settings.
For example, the below defines the alias 'pp10' that pretty prints an
expression argument, with a maximum of 10 elements if the expression is
a string or an array:
     (gdb) alias pp10 = with print pretty -- with print elements 10 -- print
   This defines the alias 'pp10' as being a sequence of 3 commands.  The
first part 'with print pretty --' temporarily activates the setting 'set
print pretty', then launches the command that follows the separator
'--'.  The command following the first part is also a 'with' command
that temporarily changes the setting 'set print elements' to 10, then
launches the command that follows the second separator '--'.  The third
part 'print' is the command the 'pp10' alias will launch, using the
temporary values of the settings and the arguments explicitly given by
the user.  For more information about the 'with' command usage, see
*note Command Settings::.

   By default, asking the help for an alias shows the documentation of
the aliased command.  When the alias is a set of nested commands, 'help'
of an alias shows the documentation of the first command.  This help is
not particularly useful for an alias such as 'pp10'.  For such an alias,
it is useful to give a specific documentation using the 'document'
command (*note document: Define.).

   ---------- Footnotes ----------

   (1) GDB could easily accept default arguments for pre-defined
commands and aliases, but it was deemed this would be confusing, and so
is not allowed.


File: gdb.info,  Node: Python,  Next: Guile,  Prev: Aliases,  Up: Extending GDB

23.3 Extending GDB using Python
===============================

You can extend GDB using the Python programming language
(http://www.python.org/).  This feature is available only if GDB was
configured using '--with-python'.

   Python scripts used by GDB should be installed in
'DATA-DIRECTORY/python', where DATA-DIRECTORY is the data directory as
determined at GDB startup (*note Data Files::).  This directory, known
as the "python directory", is automatically added to the Python Search
Path in order to allow the Python interpreter to locate all scripts
installed at this location.

   Additionally, GDB commands and convenience functions which are
written in Python and are located in the
'DATA-DIRECTORY/python/gdb/command' or
'DATA-DIRECTORY/python/gdb/function' directories are automatically
imported when GDB starts.

* Menu:

* Python Commands::             Accessing Python from GDB.
* Python API::                  Accessing GDB from Python.
* Python Auto-loading::         Automatically loading Python code.
* Python modules::              Python modules provided by GDB.


File: gdb.info,  Node: Python Commands,  Next: Python API,  Up: Python

23.3.1 Python Commands
----------------------

GDB provides two commands for accessing the Python interpreter, and one
related setting:

'python-interactive [COMMAND]'
'pi [COMMAND]'
     Without an argument, the 'python-interactive' command can be used
     to start an interactive Python prompt.  To return to GDB, type the
     'EOF' character (e.g., 'Ctrl-D' on an empty prompt).

     Alternatively, a single-line Python command can be given as an
     argument and evaluated.  If the command is an expression, the
     result will be printed; otherwise, nothing will be printed.  For
     example:

          (gdb) python-interactive 2 + 3
          5

'python [COMMAND]'
'py [COMMAND]'
     The 'python' command can be used to evaluate Python code.

     If given an argument, the 'python' command will evaluate the
     argument as a Python command.  For example:

          (gdb) python print 23
          23

     If you do not provide an argument to 'python', it will act as a
     multi-line command, like 'define'.  In this case, the Python script
     is made up of subsequent command lines, given after the 'python'
     command.  This command list is terminated using a line containing
     'end'.  For example:

          (gdb) python
          >print 23
          >end
          23

'set python print-stack'
     By default, GDB will print only the message component of a Python
     exception when an error occurs in a Python script.  This can be
     controlled using 'set python print-stack': if 'full', then full
     Python stack printing is enabled; if 'none', then Python stack and
     message printing is disabled; if 'message', the default, only the
     message component of the error is printed.

'set python ignore-environment [on|off]'
     By default this option is 'off', and, when GDB initializes its
     internal Python interpreter, the Python interpreter will check the
     environment for variables that will effect how it behaves, for
     example 'PYTHONHOME', and 'PYTHONPATH'(1).

     If this option is set to 'on' before Python is initialized then
     Python will ignore all such environment variables.  As Python is
     initialized early during GDB's startup process, then this option
     must be placed into the early initialization file (*note
     Initialization Files::) to have the desired effect.

     This option is equivalent to passing '-E' to the real 'python'
     executable.

'set python dont-write-bytecode [auto|on|off]'
     When this option is 'off', then, once GDB has initialized the
     Python interpreter, the interpreter will byte-compile any Python
     modules that it imports and write the byte code to disk in '.pyc'
     files.

     If this option is set to 'on' before Python is initialized then
     Python will no longer write the byte code to disk.  As Python is
     initialized early during GDB's startup process, then this option
     must be placed into the early initialization file (*note
     Initialization Files::) to have the desired effect.

     By default this option is set to 'auto'.  In this mode, provided
     the 'python ignore-environment' setting is 'off', the environment
     variable 'PYTHONDONTWRITEBYTECODE' is examined to see if it should
     write out byte-code or not.  'PYTHONDONTWRITEBYTECODE' is
     considered to be off/disabled either when set to the empty string
     or when the environment variable doesn't exist.  All other
     settings, including those which don't seem to make sense, indicate
     that it's on/enabled.

     This option is equivalent to passing '-B' to the real 'python'
     executable.

   It is also possible to execute a Python script from the GDB
interpreter:

'source script-name'
     The script name must end with '.py' and GDB must be configured to
     recognize the script language based on filename extension using the
     'script-extension' setting.  *Note Extending GDB: Extending GDB.

   The following commands are intended to help debug GDB itself:

'set debug py-breakpoint on|off'
'show debug py-breakpoint'
     When 'on', GDB prints debug messages related to the Python
     breakpoint API. This is 'off' by default.

'set debug py-unwind on|off'
'show debug py-unwind'
     When 'on', GDB prints debug messages related to the Python unwinder
     API. This is 'off' by default.

   ---------- Footnotes ----------

   (1) See the ENVIRONMENT VARIABLES section of 'man 1 python' for a
comprehensive list.


File: gdb.info,  Node: Python API,  Next: Python Auto-loading,  Prev: Python Commands,  Up: Python

23.3.2 Python API
-----------------

You can get quick online help for GDB's Python API by issuing the
command 'python help (gdb)'.

   Functions and methods which have two or more optional arguments allow
them to be specified using keyword syntax.  This allows passing some
optional arguments while skipping others.  Example:
'gdb.some_function ('foo', bar = 1, baz = 2)'.

* Menu:

* Basic Python::                Basic Python Functions.
* Threading in GDB::		Using Python threads in GDB.
* Exception Handling::          How Python exceptions are translated.
* Values From Inferior::        Python representation of values.
* Types In Python::             Python representation of types.
* Pretty Printing API::         Pretty-printing values.
* Selecting Pretty-Printers::   How GDB chooses a pretty-printer.
* Writing a Pretty-Printer::    Writing a Pretty-Printer.
* Type Printing API::           Pretty-printing types.
* Frame Filter API::            Filtering Frames.
* Frame Decorator API::         Decorating Frames.
* Writing a Frame Filter::      Writing a Frame Filter.
* Unwinding Frames in Python::  Writing frame unwinder.
* Xmethods In Python::          Adding and replacing methods of C++ classes.
* Xmethod API::                 Xmethod types.
* Writing an Xmethod::          Writing an xmethod.
* Inferiors In Python::         Python representation of inferiors (processes)
* Events In Python::            Listening for events from GDB.
* Threads In Python::           Accessing inferior threads from Python.
* Recordings In Python::        Accessing recordings from Python.
* CLI Commands In Python::      Implementing new CLI commands in Python.
* GDB/MI Commands In Python::   Implementing new GDB/MI commands in Python.
* GDB/MI Notifications In Python:: Implementing new GDB/MI notifications in Python.
* Parameters In Python::        Adding new GDB parameters.
* Functions In Python::         Writing new convenience functions.
* Progspaces In Python::        Program spaces.
* Objfiles In Python::          Object files.
* Frames In Python::            Accessing inferior stack frames from Python.
* Blocks In Python::            Accessing blocks from Python.
* Symbols In Python::           Python representation of symbols.
* Symbol Tables In Python::     Python representation of symbol tables.
* Line Tables In Python::       Python representation of line tables.
* Breakpoints In Python::       Manipulating breakpoints using Python.
* Finish Breakpoints in Python:: Setting Breakpoints on function return
                                using Python.
* Lazy Strings In Python::      Python representation of lazy strings.
* Architectures In Python::     Python representation of architectures.
* Registers In Python::         Python representation of registers.
* Connections In Python::       Python representation of connections.
* TUI Windows In Python::       Implementing new TUI windows.
* Disassembly In Python::       Instruction Disassembly In Python
* Missing Debug Info In Python:: Handle missing debug info from Python.


File: gdb.info,  Node: Basic Python,  Next: Threading in GDB,  Up: Python API

23.3.2.1 Basic Python
.....................

At startup, GDB overrides Python's 'sys.stdout' and 'sys.stderr' to
print using GDB's output-paging streams.  A Python program which outputs
to one of these streams may have its output interrupted by the user
(*note Screen Size::).  In this situation, a Python 'KeyboardInterrupt'
exception is thrown.

   Some care must be taken when writing Python code to run in GDB.  Two
things worth noting in particular:

   * GDB installs handlers for 'SIGCHLD' and 'SIGINT'.  Python 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.  When
     creating a new Python thread, you can use 'gdb.block_signals' or
     'gdb.Thread' to handle this correctly; see *note Threading in
     GDB::.

   * 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 Python 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 Python module, named 'gdb'.  All methods and
classes added by GDB are placed in this module.  GDB automatically
'import's the 'gdb' module for use in all scripts evaluated by the
'python' command.

   Some types of the 'gdb' module come with a textual representation
(accessible through the 'repr' or 'str' functions).  These are offered
for debugging purposes only, expect them to change over time.

 -- Variable: gdb.PYTHONDIR
     A string containing the python directory (*note Python::).

 -- Function: gdb.execute (command [, from_tty [, to_string]])
     Evaluate COMMAND, a string, as a GDB CLI command.  If a GDB
     exception happens while COMMAND runs, it is translated as described
     in *note Exception Handling: Exception Handling.

     The FROM_TTY flag 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 'False'.

     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 'True', then output will be collected
     by 'gdb.execute' and returned as a string.  The default is 'False',
     in which case the return value is 'None'.  If TO_STRING is 'True',
     the GDB virtual terminal will be temporarily set to unlimited width
     and height, and its pagination will be disabled; *note Screen
     Size::.

 -- Function: gdb.breakpoints ()
     Return a sequence holding all of GDB's breakpoints.  *Note
     Breakpoints In Python::, for more information.  In GDB version 7.11
     and earlier, this function returned 'None' if there were no
     breakpoints.  This peculiarity was subsequently fixed, and now
     'gdb.breakpoints' returns an empty sequence in this case.

 -- Function: gdb.rbreak (regex [, minsyms [, throttle, [, symtabs ]]])
     Return a Python list holding a collection of newly set
     'gdb.Breakpoint' objects matching function names defined by the
     REGEX pattern.  If the MINSYMS keyword is 'True', all system
     functions (those not explicitly defined in the inferior) will also
     be included in the match.  The THROTTLE keyword takes an integer
     that defines the maximum number of pattern matches for functions
     matched by the REGEX pattern.  If the number of matches exceeds the
     integer value of THROTTLE, a 'RuntimeError' will be raised and no
     breakpoints will be created.  If THROTTLE is not defined then there
     is no imposed limit on the maximum number of matches and
     breakpoints to be created.  The SYMTABS keyword takes a Python
     iterable that yields a collection of 'gdb.Symtab' objects and will
     restrict the search to those functions only contained within the
     'gdb.Symtab' objects.

 -- Function: gdb.parameter (parameter)
     Return the value of a GDB PARAMETER given by its name, a string;
     the parameter name string may contain spaces if the parameter has a
     multi-part name.  For example, 'print object' is a valid parameter
     name.

     If the named parameter does not exist, this function throws a
     'gdb.error' (*note Exception Handling::).  Otherwise, the
     parameter's value is converted to a Python value of the appropriate
     type, and returned.

 -- Function: gdb.set_parameter (name, value)
     Sets the gdb parameter NAME to VALUE.  As with 'gdb.parameter', the
     parameter name string may contain spaces if the parameter has a
     multi-part name.

 -- Function: gdb.with_parameter (name, value)
     Create a Python context manager (for use with the Python 'with'
     statement) that temporarily sets the gdb parameter NAME to VALUE.
     On exit from the context, the previous value will be restored.

     This uses 'gdb.parameter' in its implementation, so it can throw
     the same exceptions as that function.

     For example, it's sometimes useful to evaluate some Python code
     with a particular gdb language:

          with gdb.with_parameter('language', 'pascal'):
            ... language-specific operations

 -- Function: gdb.history (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::).

 -- Function: gdb.add_history (value)
     Takes VALUE, an instance of 'gdb.Value' (*note Values From
     Inferior::), and appends the value this object represents to GDB's
     value history (*note Value History::), and return an integer, its
     history number.  If VALUE is not a 'gdb.Value', it is is converted
     using the 'gdb.Value' constructor.  If VALUE can't be converted to
     a 'gdb.Value' then a 'TypeError' is raised.

     When a command implemented in Python prints a single 'gdb.Value' as
     its result, then placing the value into the history will allow the
     user convenient access to those values via CLI history facilities.

 -- Function: gdb.history_count ()
     Return an integer indicating the number of values in GDB's value
     history (*note Value History::).

 -- Function: gdb.convenience_variable (name)
     Return the value of the convenience variable (*note Convenience
     Vars::) named NAME.  NAME must be a string.  The name should not
     include the '$' that is used to mark a convenience variable in an
     expression.  If the convenience variable does not exist, then
     'None' is returned.

 -- Function: gdb.set_convenience_variable (name, value)
     Set the value of the convenience variable (*note Convenience
     Vars::) named NAME.  NAME must be a string.  The name should not
     include the '$' that is used to mark a convenience variable in an
     expression.  If VALUE is 'None', then the convenience variable is
     removed.  Otherwise, if VALUE is not a 'gdb.Value' (*note Values
     From Inferior::), it is is converted using the 'gdb.Value'
     constructor.

 -- Function: gdb.parse_and_eval (expression [, global_context])
     Parse EXPRESSION, which must be a string, as an expression in the
     current language, evaluate it, and return the result as a
     'gdb.Value'.

     GLOBAL_CONTEXT, if provided, is a boolean indicating whether the
     parsing should be done in the global context.  The default is
     'False', meaning that the current frame or current static context
     should be used.

     This function can be useful when implementing a new command (*note
     CLI Commands In Python::, *note GDB/MI Commands In Python::), as it
     provides a way to parse the command's argument as an expression.
     It is also useful simply to compute values.

 -- Function: gdb.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.  This is identical to
     'gdb.current_progspace().find_pc_line(pc)' and is included for
     historical compatibility.

 -- Function: gdb.write (string [, stream])
     Print a string to GDB's paginated output stream.  The optional
     STREAM determines the stream to print to.  The default stream is
     GDB's standard output stream.  Possible stream values are:

     'gdb.STDOUT'
          GDB's standard output stream.

     'gdb.STDERR'
          GDB's standard error stream.

     'gdb.STDLOG'
          GDB's log stream (*note Logging Output::).

     Writing to 'sys.stdout' or 'sys.stderr' will automatically call
     this function and will automatically direct the output to the
     relevant stream.

 -- Function: gdb.flush ([, stream])
     Flush the buffer of a GDB paginated stream so that the contents are
     displayed immediately.  GDB will flush the contents of a stream
     automatically when it encounters a newline in the buffer.  The
     optional STREAM determines the stream to flush.  The default stream
     is GDB's standard output stream.  Possible stream values are:

     'gdb.STDOUT'
          GDB's standard output stream.

     'gdb.STDERR'
          GDB's standard error stream.

     'gdb.STDLOG'
          GDB's log stream (*note Logging Output::).

     Flushing 'sys.stdout' or 'sys.stderr' will automatically call this
     function for the relevant stream.

 -- Function: gdb.target_charset ()
     Return the name of the current target character set (*note
     Character Sets::).  This differs from
     'gdb.parameter('target-charset')' in that 'auto' is never returned.

 -- Function: gdb.target_wide_charset ()
     Return the name of the current target wide character set (*note
     Character Sets::).  This differs from
     'gdb.parameter('target-wide-charset')' in that 'auto' is never
     returned.

 -- Function: gdb.host_charset ()
     Return a string, the name of the current host character set (*note
     Character Sets::).  This differs from
     'gdb.parameter('host-charset')' in that 'auto' is never returned.

 -- Function: gdb.solib_name (address)
     Return the name of the shared library holding the given ADDRESS as
     a string, or 'None'.  This is identical to
     'gdb.current_progspace().solib_name(address)' and is included for
     historical compatibility.

 -- Function: gdb.decode_line ([expression])
     Return locations of the line specified by EXPRESSION, or of the
     current line if no argument was given.  This function returns a
     Python tuple containing two elements.  The first element contains a
     string holding any unparsed section of EXPRESSION (or 'None' if the
     expression has been fully parsed).  The second element contains
     either 'None' or another tuple that contains all the locations that
     match the expression represented as 'gdb.Symtab_and_line' objects
     (*note Symbol Tables In Python::).  If EXPRESSION is provided, it
     is decoded the way that GDB's inbuilt 'break' or 'edit' commands do
     (*note Location Specifications::).

 -- Function: gdb.prompt_hook (current_prompt)

     If PROMPT_HOOK is callable, GDB will call the method assigned to
     this operation before a prompt is displayed by GDB.

     The parameter 'current_prompt' contains the current GDB prompt.
     This method must return a Python string, or 'None'.  If a string is
     returned, the GDB prompt will be set to that string.  If 'None' is
     returned, GDB will continue to use the current prompt.

     Some prompts cannot be substituted in GDB.  Secondary prompts such
     as those used by readline for command input, and annotation related
     prompts are prohibited from being changed.

 -- Function: gdb.architecture_names ()
     Return a list containing all of the architecture names that the
     current build of GDB supports.  Each architecture name is a string.
     The names returned in this list are the same names as are returned
     from 'gdb.Architecture.name' (*note Architecture.name:
     gdbpy_architecture_name.).

 -- Function: gdb.connections
     Return a list of 'gdb.TargetConnection' objects, one for each
     currently active connection (*note Connections In Python::).  The
     connection objects are in no particular order in the returned list.

 -- Function: gdb.format_address (address [, progspace, architecture])
     Return a string in the format 'ADDR <SYMBOL+OFFSET>', where ADDR is
     ADDRESS formatted in hexadecimal, SYMBOL is the symbol whose
     address is the nearest to ADDRESS and below it in memory, and
     OFFSET is the offset from SYMBOL to ADDRESS in decimal.

     If no suitable SYMBOL was found, then the <SYMBOL+OFFSET> part is
     not included in the returned string, instead the returned string
     will just contain the ADDRESS formatted as hexadecimal.  How far
     GDB looks back for a suitable symbol can be controlled with 'set
     print max-symbolic-offset' (*note Print Settings::).

     Additionally, the returned string can include file name and line
     number information when 'set print symbol-filename on' (*note Print
     Settings::), in this case the format of the returned string is
     'ADDR <SYMBOL+OFFSET> at FILENAME:LINE-NUMBER'.

     The PROGSPACE is the gdb.Progspace in which SYMBOL is looked up,
     and ARCHITECTURE is used when formatting ADDR, e.g. in order to
     determine the size of an address in bytes.

     If neither PROGSPACE or ARCHITECTURE are passed, then by default
     GDB will use the program space and architecture of the currently
     selected inferior, thus, the following two calls are equivalent:

          gdb.format_address(address)
          gdb.format_address(address,
                             gdb.selected_inferior().progspace,
                             gdb.selected_inferior().architecture())

     It is not valid to only pass one of PROGSPACE or ARCHITECTURE,
     either they must both be provided, or neither must be provided (and
     the defaults will be used).

     This method uses the same mechanism for formatting address, symbol,
     and offset information as core GDB does in commands such as
     'disassemble'.

     Here are some examples of the possible string formats:

          0x00001042
          0x00001042 <symbol+16>
          0x00001042 <symbol+16 at file.c:123>

 -- Function: gdb.current_language ()
     Return the name of the current language as a string.  Unlike
     'gdb.parameter('language')', this function will never return
     'auto'.  If a 'gdb.Frame' object is available (*note Frames In
     Python::), the 'language' method might be preferable in some cases,
     as that is not affected by the user's language setting.


File: gdb.info,  Node: Threading in GDB,  Next: Exception Handling,  Prev: Basic Python,  Up: Python API

23.3.2.2 Threading in GDB
.........................

GDB is not thread-safe.  If your Python program uses multiple threads,
you must be careful to only call GDB-specific functions in the GDB
thread.  GDB provides some functions to help with this.

 -- Function: gdb.block_signals ()
     As mentioned earlier (*note Basic Python::), certain signals must
     be delivered to the GDB main thread.  The 'block_signals' function
     returns a context manager that will block these signals on entry.
     This can be used when starting a new thread to ensure that the
     signals are blocked there, like:

          with gdb.block_signals():
             start_new_thread()

 -- class: gdb.Thread
     This is a subclass of Python's 'threading.Thread' class.  It
     overrides the 'start' method to call 'block_signals', making this
     an easy-to-use drop-in replacement for creating threads that will
     work well in GDB.

 -- Function: gdb.interrupt ()
     This causes GDB to react as if the user had typed a control-C
     character at the terminal.  That is, if the inferior is running, it
     is interrupted; if a GDB command is executing, it is stopped; and
     if a Python command is running, 'KeyboardInterrupt' will be raised.

     Unlike most Python APIs in GDB, 'interrupt' is thread-safe.

 -- Function: gdb.post_event (event)
     Put EVENT, a callable object taking no arguments, into GDB's
     internal event queue.  This callable will be invoked at some later
     point, during GDB's event processing.  Events posted using
     'post_event' will be run in the order in which they were posted;
     however, there is no way to know when they will be processed
     relative to other events inside GDB.

     Unlike most Python APIs in GDB, 'post_event' is thread-safe.  For
     example:

          (gdb) python
          >import threading
          >
          >class Writer():
          > def __init__(self, message):
          >        self.message = message;
          > def __call__(self):
          >        gdb.write(self.message)
          >
          >class MyThread1 (threading.Thread):
          > def run (self):
          >        gdb.post_event(Writer("Hello "))
          >
          >class MyThread2 (threading.Thread):
          > def run (self):
          >        gdb.post_event(Writer("World\n"))
          >
          >MyThread1().start()
          >MyThread2().start()
          >end
          (gdb) Hello World


File: gdb.info,  Node: Exception Handling,  Next: Values From Inferior,  Prev: Threading in GDB,  Up: Python API

23.3.2.3 Exception Handling
...........................

When executing the 'python' command, Python exceptions uncaught within
the Python code are translated to calls to GDB error-reporting
mechanism.  If the command that called 'python' does not handle the
error, GDB will terminate it and print an error message.  Exactly what
will be printed depends on 'set python print-stack' (*note Python
Commands::).  Example:

     (gdb) python print foo
     Traceback (most recent call last):
       File "<string>", line 1, in <module>
     NameError: name 'foo' is not defined

   GDB errors that happen in GDB commands invoked by Python code are
converted to Python exceptions.  The type of the Python exception
depends on the error.

'gdb.error'
     This is the base class for most exceptions generated by GDB.  It is
     derived from 'RuntimeError', for compatibility with earlier
     versions of GDB.

     If an error occurring in GDB does not fit into some more specific
     category, then the generated exception will have this type.

'gdb.MemoryError'
     This is a subclass of 'gdb.error' which is thrown when an operation
     tried to access invalid memory in the inferior.

'KeyboardInterrupt'
     User interrupt (via 'C-c' or by typing 'q' at a pagination prompt)
     is translated to a Python 'KeyboardInterrupt' exception.

   In all cases, your exception handler will see the GDB error message
as its value and the Python call stack backtrace at the Python statement
closest to where the GDB error occurred as the traceback.

   When implementing GDB commands in Python via 'gdb.Command', or
functions via 'gdb.Function', it is useful to be able to throw an
exception that doesn't cause a traceback to be printed.  For example,
the user may have invoked the command incorrectly.  GDB provides a
special exception class that can be used for this purpose.

'gdb.GdbError'
     When thrown from a command or function, this exception will cause
     the command or function to fail, but the Python stack will not be
     displayed.  GDB does not throw this exception itself, but rather
     recognizes it when thrown from user Python code.  Example:

          (gdb) python
          >class HelloWorld (gdb.Command):
          >  """Greet the whole world."""
          >  def __init__ (self):
          >    super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
          >  def invoke (self, args, from_tty):
          >    argv = gdb.string_to_argv (args)
          >    if len (argv) != 0:
          >      raise gdb.GdbError ("hello-world takes no arguments")
          >    print ("Hello, World!")
          >HelloWorld ()
          >end
          (gdb) hello-world 42
          hello-world takes no arguments


File: gdb.info,  Node: Values From Inferior,  Next: Types In Python,  Prev: Exception Handling,  Up: Python API

23.3.2.4 Values From Inferior
.............................

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.

   Inferior values that are simple scalars can be used directly in
Python expressions that are valid for the value's data type.  Here's an
example for an integer or floating-point value 'some_val':

     bar = some_val + 2

As result of this, 'bar' will also be a 'gdb.Value' object whose values
are of the same type as those of 'some_val'.  Valid Python operations
can also be performed on 'gdb.Value' objects representing a 'struct' or
'class' object.  For such cases, the overloaded operator (if present),
is used to perform the operation.  For example, if 'val1' and 'val2' are
'gdb.Value' objects representing instances of a 'class' which overloads
the '+' operator, then one can use the '+' operator in their Python
script as follows:

     val3 = val1 + val2

The result of the operation 'val3' is also a 'gdb.Value' object
corresponding to the value returned by the overloaded '+' operator.  In
general, overloaded operators are invoked for the following operations:
'+' (binary addition), '-' (binary subtraction), '*' (multiplication),
'/', '%', '<<', '>>', '|', '&', '^'.

   Inferior values that are structures or instances of some class can be
accessed using the Python "dictionary syntax".  For example, if
'some_val' is a 'gdb.Value' instance holding a structure, you can access
its 'foo' element with:

     bar = some_val['foo']

   Again, 'bar' will also be a 'gdb.Value' object.  Structure elements
can also be accessed by using 'gdb.Field' objects as subscripts (*note
Types In Python::, for more information on 'gdb.Field' objects).  For
example, if 'foo_field' is a 'gdb.Field' object corresponding to element
'foo' of the above structure, then 'bar' can also be accessed as
follows:

     bar = some_val[foo_field]

   If a 'gdb.Value' has array or pointer type, an integer index can be
used to access elements.

     result = some_array[23]

   A 'gdb.Value' that represents a function can be executed via inferior
function 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:

     result = some_val (10,20)

   Any values returned from a function call will be stored as a
'gdb.Value'.

   The following attributes are provided:

 -- Variable: Value.address
     If this object is addressable, this read-only attribute holds a
     'gdb.Value' object representing the address.  Otherwise, this
     attribute holds 'None'.

 -- Variable: Value.is_optimized_out
     This read-only boolean attribute is true if the compiler optimized
     out this value, thus it is not available for fetching from the
     inferior.

 -- Variable: Value.type
     The type of this 'gdb.Value'.  The value of this attribute is a
     'gdb.Type' object (*note Types In Python::).

 -- Variable: Value.dynamic_type
     The dynamic type of this 'gdb.Value'.  This uses the object's
     virtual table and the C++ run-time type information (RTTI) to
     determine the dynamic type of the value.  If this value is of class
     type, it will return the class in which the value is embedded, if
     any.  If this 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.).

 -- Variable: Value.is_lazy
     The value of this read-only boolean attribute is 'True' if this
     'gdb.Value' has not yet been fetched from the inferior.  GDB does
     not fetch values until necessary, for efficiency.  For example:

          myval = gdb.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' method
     is invoked.

 -- Variable: Value.bytes
     The value of this attribute is a 'bytes' object containing the
     bytes that make up this 'Value''s complete value in little endian
     order.  If the complete contents of this value are not available
     then accessing this attribute will raise an exception.

     This attribute can also be assigned to.  The new value should be a
     buffer object (e.g. a 'bytes' object), the length of the new buffer
     must exactly match the length of this 'Value''s type.  The bytes
     values in the new buffer should be in little endian order.

     As with 'Value.assign' (*note Value.assign::), if this value cannot
     be assigned to, then an exception will be thrown.

   The following methods are provided:

 -- Function: Value.__init__ (val)
     Many Python values can be converted directly to a 'gdb.Value' via
     this object initializer.  Specifically:

     Python boolean
          A Python boolean is converted to the boolean type from the
          current language.

     Python integer
          A Python integer is converted to the C 'long' type for the
          current architecture.

     Python long
          A Python long is converted to the C 'long long' type for the
          current architecture.

     Python float
          A Python float is converted to the C 'double' type for the
          current architecture.

     Python string
          A Python string is converted to a target string in the current
          target language using the current target encoding.  If a
          character cannot be represented in the current target
          encoding, then an exception is thrown.

     'gdb.Value'
          If 'val' is a 'gdb.Value', then a copy of the value is made.

     'gdb.LazyString'
          If 'val' is a 'gdb.LazyString' (*note Lazy Strings In
          Python::), then the lazy string's 'value' method is called,
          and its result is used.

 -- Function: Value.__init__ (val, type)
     This second form of the 'gdb.Value' constructor returns a
     'gdb.Value' of type TYPE where the value contents are taken from
     the Python buffer object specified by VAL.  The number of bytes in
     the Python buffer object must be greater than or equal to the size
     of TYPE.

     If TYPE is 'None' then this version of '__init__' behaves as though
     TYPE was not passed at all.

 -- Function: Value.assign (rhs)
     Assign RHS to this value, and return 'None'.  If this value cannot
     be assigned to, or if the assignment is invalid for some reason
     (for example a type-checking failure), an exception will be thrown.

 -- Function: Value.cast (type)
     Return a new instance of 'gdb.Value' that is the result of casting
     this instance 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.

 -- Function: Value.dereference ()
     For pointer data types, this method returns a new 'gdb.Value'
     object whose contents is the object pointed to by the pointer.  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:

          bar = foo.dereference ()

     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'.

          py_ptrref = gdb.parse_and_eval ("ptrref")
          py_val = py_ptrref.dereference ()
          py_ptr = py_ptrref.referenced_value ()

     The 'gdb.Value' object 'py_val' is identical to that corresponding
     to 'val', and 'py_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.

 -- Function: Value.referenced_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'.

          py_ref = gdb.parse_and_eval ("ref")
          er_ref = py_ref.dereference ()       # Results in error
          py_val = py_ref.referenced_value ()  # Returns the referenced value

     The 'gdb.Value' object 'py_val' is identical to that corresponding
     to 'val'.

 -- Function: Value.reference_value ()
     Return a 'gdb.Value' object which is a reference to the value
     encapsulated by this instance.

 -- Function: Value.const_value ()
     Return a 'gdb.Value' object which is a 'const' version of the value
     encapsulated by this instance.

 -- Function: Value.dynamic_cast (type)
     Like 'Value.cast', but works as if the C++ 'dynamic_cast' operator
     were used.  Consult a C++ reference for details.

 -- Function: Value.reinterpret_cast (type)
     Like 'Value.cast', but works as if the C++ 'reinterpret_cast'
     operator were used.  Consult a C++ reference for details.

 -- Function: Value.format_string (...)
     Convert a 'gdb.Value' to a string, similarly to what the 'print'
     command does.  Invoked with no arguments, this is equivalent to
     calling the 'str' function on the 'gdb.Value'.  The representation
     of the same value may change across different versions of GDB, so
     you shouldn't, for instance, parse the strings returned by this
     method.

     All the arguments are keyword only.  If an argument is not
     specified, the current global default setting is used.

     'raw'
          'True' if pretty-printers (*note Pretty Printing::) should not
          be used to format the value.  'False' if enabled
          pretty-printers matching the type represented by the
          'gdb.Value' should be used to format it.

     'pretty_arrays'
          'True' if arrays should be pretty printed to be more
          convenient to read, 'False' if they shouldn't (see 'set print
          array' in *note Print Settings::).

     'pretty_structs'
          'True' if structs should be pretty printed to be more
          convenient to read, 'False' if they shouldn't (see 'set print
          pretty' in *note Print Settings::).

     'array_indexes'
          'True' if array indexes should be included in the string
          representation of arrays, 'False' if they shouldn't (see 'set
          print array-indexes' in *note Print Settings::).

     'symbols'
          'True' if the string representation of a pointer should
          include the corresponding symbol name (if one exists), 'False'
          if it shouldn't (see 'set print symbol' in *note Print
          Settings::).

     'unions'
          'True' if unions which are contained in other structures or
          unions should be expanded, 'False' if they shouldn't (see 'set
          print union' in *note Print Settings::).

     'address'
          'True' if the string representation of a pointer should
          include the address, 'False' if it shouldn't (see 'set print
          address' in *note Print Settings::).

     'nibbles'
          'True' if binary values should be displayed in groups of four
          bits, known as nibbles.  'False' if it shouldn't (*note set
          print nibbles: Print Settings.).

     'deref_refs'
          'True' if C++ references should be resolved to the value they
          refer to, 'False' (the default) if they shouldn't.  Note that,
          unlike for the 'print' command, references are not
          automatically expanded when using the 'format_string' method
          or the 'str' function.  There is no global 'print' setting to
          change the default behaviour.

     'actual_objects'
          'True' if the representation of a pointer to an object should
          identify the _actual_ (derived) type of the object rather than
          the _declared_ type, using the virtual function table.
          'False' if the _declared_ type should be used.  (See 'set
          print object' in *note Print Settings::).

     'static_members'
          'True' if static members should be included in the string
          representation of a C++ object, 'False' if they shouldn't (see
          'set print static-members' in *note Print Settings::).

     'max_characters'
          Number of string characters to print, '0' to follow
          'max_elements', or 'UINT_MAX' to print an unlimited number of
          characters (see 'set print characters' in *note Print
          Settings::).

     'max_elements'
          Number of array elements to print, or '0' to print an
          unlimited number of elements (see 'set print elements' in
          *note Print Settings::).

     'max_depth'
          The maximum depth to print for nested structs and unions, or
          '-1' to print an unlimited number of elements (see 'set print
          max-depth' in *note Print Settings::).

     'repeat_threshold'
          Set the threshold for suppressing display of repeated array
          elements, or '0' to represent all elements, even if repeated.
          (See 'set print repeats' in *note Print Settings::).

     'format'
          A string containing a single character representing the format
          to use for the returned string.  For instance, ''x'' is
          equivalent to using the GDB command 'print' with the '/x'
          option and formats the value as a hexadecimal number.

     'styling'
          'True' if GDB should apply styling to the returned string.
          When styling is applied, the returned string might contain
          ANSI terminal escape sequences.  Escape sequences will only be
          included if styling is turned on, see *note Output Styling::.
          Additionally, GDB only styles some value contents, so not
          every output string will contain escape sequences.

          When 'False', which is the default, no output styling is
          applied.

     'summary'
          'True' when just a summary should be printed.  In this mode,
          scalar values are printed in their entirety, but aggregates
          such as structures or unions are omitted.  This mode is used
          by 'set print frame-arguments scalars' (*note Print
          Settings::).

 -- Function: Value.to_array ()
     If this value is array-like (*note Type.is_array_like::), then this
     method converts it to an array, which is returned.  If this value
     is already an array, it is simply returned.  Otherwise, an
     exception is throw.

 -- Function: Value.string ([encoding[, errors[, length]]])
     If this 'gdb.Value' represents a string, then this method converts
     the contents to a Python 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 Python's 'string.decode'
     method, and the Python 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 the same as the corresponding
     argument to Python's 'string.decode' method.

     If the optional LENGTH argument is given, the string will be
     fetched and converted to the given length.

 -- Function: Value.lazy_string ([encoding [, length]])
     If this 'gdb.Value' represents a string, then this method converts
     the contents to a 'gdb.LazyString' (*note Lazy Strings In
     Python::).  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.LazyString'.  Some examples are:
     'ascii', 'iso-8859-6' or 'utf-8'.  If the ENCODING argument is an
     encoding that GDB does 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.

 -- Function: Value.fetch_lazy ()
     If the 'gdb.Value' object is currently a lazy value
     ('gdb.Value.is_lazy' is 'True'), then the value is fetched from the
     inferior.  Any errors that occur in the process will produce a
     Python exception.

     If the 'gdb.Value' object is not a lazy value, this method has no
     effect.

     This method does not return a value.


File: gdb.info,  Node: Types In Python,  Next: Pretty Printing API,  Prev: Values From Inferior,  Up: Python API

23.3.2.5 Types In Python
........................

GDB represents types from the inferior using the class 'gdb.Type'.

   The following type-related functions are available in the 'gdb'
module:

 -- Function: gdb.lookup_type (name [, block])
     This function looks up a type by its NAME, which must be a string.

     If BLOCK is given, then 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.

   Integer types can be found without looking them up by name.  *Note
Architectures In Python::, for the 'integer_type' method.

   If the type is a structure or class type, or an enum type, the fields
of that type can be accessed using the Python "dictionary syntax".  For
example, if 'some_type' is a 'gdb.Type' instance holding a structure
type, you can access its 'foo' field with:

     bar = some_type['foo']

   'bar' will be a 'gdb.Field' object; see below under the description
of the 'Type.fields' method for a description of the 'gdb.Field' class.

   An instance of 'Type' has the following attributes:

 -- Variable: Type.alignof
     The alignment of this type, in bytes.  Type alignment comes from
     the debugging information; if it was not specified, then GDB will
     use the relevant ABI to try to determine the alignment.  In some
     cases, even this is not possible, and zero will be returned.

 -- Variable: Type.code
     The type code for this type.  The type code will be one of the
     'TYPE_CODE_' constants defined below.

 -- Variable: Type.dynamic
     A boolean indicating whether this type is dynamic.  In some
     situations, such as Rust 'enum' types or Ada variant records, the
     concrete type of a value may vary depending on its contents.  That
     is, the declared type of a variable, or the type returned by
     'gdb.lookup_type' may be dynamic; while the type of the variable's
     value will be a concrete instance of that dynamic type.

     For example, consider this code:
          int n;
          int array[n];

     Here, at least conceptually (whether your compiler actually does
     this is a separate issue), examining
     'gdb.lookup_symbol("array", ...).type' could yield a 'gdb.Type'
     which reports a size of 'None'.  This is the dynamic type.

     However, examining 'gdb.parse_and_eval("array").type' would yield a
     concrete type, whose length would be known.

 -- Variable: Type.name
     The name of this type.  If this type has no name, then 'None' is
     returned.

 -- Variable: Type.sizeof
     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.  A dynamic type may
     not have a fixed size; in this case, this attribute's value will be
     'None'.

 -- Variable: Type.tag
     The tag name for this 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 'None' is
     returned.

 -- Variable: Type.objfile
     The 'gdb.Objfile' that this type was defined in, or 'None' if there
     is no associated objfile.

 -- Variable: Type.is_scalar
     This property is 'True' if the type is a scalar type, otherwise,
     this property is 'False'.  Examples of non-scalar types include
     structures, unions, and classes.

 -- Variable: Type.is_signed
     For scalar types (those for which 'Type.is_scalar' is 'True'), this
     property is 'True' if the type is signed, otherwise this property
     is 'False'.

     Attempting to read this property for a non-scalar type (a type for
     which 'Type.is_scalar' is 'False'), will raise a 'ValueError'.

 -- Variable: Type.is_array_like
     A boolean indicating whether this type is array-like.

     Some languages have array-like objects that are represented
     internally as structures.  For example, this is true for a Rust
     slice type, or for an Ada unconstrained array.  GDB may know about
     these types.  This determination is done based on the language from
     which the type originated.

 -- Variable: Type.is_string_like
     A boolean indicating whether this type is string-like.  Like
     'Type.is_array_like', this is determined based on the originating
     language of the type.

   The following methods are provided:

 -- Function: Type.fields ()

     Return the fields of this type.  The behavior depends on the type
     code:

        * For structure and union types, this method returns the fields.

        * 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.

        * Array types have one field representing the array's range.

        * If the type does not fit into one of these categories, a
          'TypeError' is raised.

     Each field is a 'gdb.Field' object, with some pre-defined
     attributes:
     'bitpos'
          This attribute is not available for 'enum' or 'static' (as in
          C++) fields.  The value is the position, counting in bits,
          from the start of the containing type.  Note that, in a
          dynamic type, the position of a field may not be constant.  In
          this case, the value will be 'None'.  Also, a dynamic type may
          have fields that do not appear in a corresponding concrete
          type.

     'enumval'
          This attribute is only available for 'enum' fields, and its
          value is the enumeration member's integer representation.

     'name'
          The name of the field, or 'None' for anonymous fields.

     'artificial'
          This is 'True' if the field is artificial, usually meaning
          that it was provided by the compiler and not the user.  This
          attribute is always provided, and is 'False' if the field is
          not artificial.

     'is_base_class'
          This is 'True' if the field represents a base class of a C++
          structure.  This attribute is always provided, and is 'False'
          if the field is not a base class of the type that is the
          argument of 'fields', or if that type was not a C++ class.

     'bitsize'
          If the field is packed, or is a bitfield, then this will have
          a non-zero value, which is the size of the field in bits.
          Otherwise, this will be zero; in this case the field's size is
          given by its type.

     'type'
          The type of the field.  This is usually an instance of 'Type',
          but it can be 'None' in some situations.

     'parent_type'
          The type which contains this field.  This is an instance of
          'gdb.Type'.

 -- Function: Type.array (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.

 -- Function: Type.vector (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.

 -- Function: Type.const ()
     Return a new 'gdb.Type' object which represents a 'const'-qualified
     variant of this type.

 -- Function: Type.volatile ()
     Return a new 'gdb.Type' object which represents a
     'volatile'-qualified variant of this type.

 -- Function: Type.unqualified ()
     Return a new 'gdb.Type' object which represents an unqualified
     variant of this type.  That is, the result is neither 'const' nor
     'volatile'.

 -- Function: Type.range ()
     Return a Python 'Tuple' object that contains two elements: the low
     bound of the argument type and the high bound of that type.  If the
     type does not have a range, GDB will raise a 'gdb.error' exception
     (*note Exception Handling::).

 -- Function: Type.reference ()
     Return a new 'gdb.Type' object which represents a reference to this
     type.

 -- Function: Type.pointer ()
     Return a new 'gdb.Type' object which represents a pointer to this
     type.

 -- Function: Type.strip_typedefs ()
     Return a new 'gdb.Type' that represents the real type, after
     removing all layers of typedefs.

 -- Function: Type.target ()
     Return a new 'gdb.Type' object which represents the target type of
     this 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.

 -- Function: Type.template_argument (n [, block])
     If this 'gdb.Type' is an instantiation of a template, this will
     return a new 'gdb.Value' or 'gdb.Type' which represents the value
     of the Nth template argument (indexed starting at 0).

     If this 'gdb.Type' is not a template type, or if the type has fewer
     than N template arguments, this will throw an exception.
     Ordinarily, only C++ code will have template types.

     If BLOCK is given, then NAME is looked up in that scope.
     Otherwise, it is searched for globally.

 -- Function: Type.optimized_out ()
     Return 'gdb.Value' instance of this type whose value is optimized
     out.  This allows a frame decorator to indicate that the value of
     an argument or a local variable is not known.

   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:

'gdb.TYPE_CODE_PTR'
     The type is a pointer.

'gdb.TYPE_CODE_ARRAY'
     The type is an array.

'gdb.TYPE_CODE_STRUCT'
     The type is a structure.

'gdb.TYPE_CODE_UNION'
     The type is a union.

'gdb.TYPE_CODE_ENUM'
     The type is an enum.

'gdb.TYPE_CODE_FLAGS'
     A bit flags type, used for things such as status registers.

'gdb.TYPE_CODE_FUNC'
     The type is a function.

'gdb.TYPE_CODE_INT'
     The type is an integer type.

'gdb.TYPE_CODE_FLT'
     A floating point type.

'gdb.TYPE_CODE_VOID'
     The special type 'void'.

'gdb.TYPE_CODE_SET'
     A Pascal set type.

'gdb.TYPE_CODE_RANGE'
     A range type, that is, an integer type with bounds.

'gdb.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.

'gdb.TYPE_CODE_BITSTRING'
     A string of bits.  It is deprecated.

'gdb.TYPE_CODE_ERROR'
     An unknown or erroneous type.

'gdb.TYPE_CODE_METHOD'
     A method type, as found in C++.

'gdb.TYPE_CODE_METHODPTR'
     A pointer-to-member-function.

'gdb.TYPE_CODE_MEMBERPTR'
     A pointer-to-member.

'gdb.TYPE_CODE_REF'
     A reference type.

'gdb.TYPE_CODE_RVALUE_REF'
     A C++11 rvalue reference type.

'gdb.TYPE_CODE_CHAR'
     A character type.

'gdb.TYPE_CODE_BOOL'
     A boolean type.

'gdb.TYPE_CODE_COMPLEX'
     A complex float type.

'gdb.TYPE_CODE_TYPEDEF'
     A typedef to some other type.

'gdb.TYPE_CODE_NAMESPACE'
     A C++ namespace.

'gdb.TYPE_CODE_DECFLOAT'
     A decimal floating point type.

'gdb.TYPE_CODE_INTERNAL_FUNCTION'
     A function internal to GDB.  This is the type used to represent
     convenience functions.

'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' Python
module (*note gdb.types::).


File: gdb.info,  Node: Pretty Printing API,  Next: Selecting Pretty-Printers,  Prev: Types In Python,  Up: Python API

23.3.2.6 Pretty Printing API
............................

A pretty-printer is just an object that holds a value and implements a
specific interface, defined here.  An example output is provided (*note
Pretty Printing::).

   Because GDB did not document extensibility for pretty-printers, by
default GDB will assume that only the basic pretty-printer methods may
be available.  The basic methods are marked as such, below.

   To allow extensibility, GDB provides the 'gdb.ValuePrinter' base
class.  This class does not provide any attributes or behavior, but
instead serves as a tag that can be recognized by GDB.  For such
printers, GDB reserves all attributes starting with a lower-case letter.
That is, in the future, GDB may add a new method or attribute to the
pretty-printer protocol, and 'gdb.ValuePrinter'-based printers are
expected to handle this gracefully.  A simple way to do this would be to
use a leading underscore (or two, following the Python name-mangling
scheme) to any attributes local to the implementation.

 -- Function: pretty_printer.children (self)
     GDB will call this method on a pretty-printer to compute the
     children of the pretty-printer's value.

     This method must return an object conforming to the Python iterator
     protocol.  Each item returned by the iterator must be a tuple
     holding two elements.  The first element is the "name" of the
     child; the second element is the child's value.  The value can be
     any Python object which is convertible to a GDB value.

     This is a basic method, and is optional.  If it does not exist, GDB
     will act as though the value has no children.

     For efficiency, the 'children' method should lazily compute its
     results.  This will let GDB read as few elements as necessary, for
     example when various print settings (*note Print Settings::) or
     '-var-list-children' (*note GDB/MI Variable Objects::) limit the
     number of elements to be displayed.

     Children may be hidden from display based on the value of 'set
     print max-depth' (*note Print Settings::).

 -- Function: pretty_printer.display_hint (self)
     The CLI may call this method and use its result to change the
     formatting of a value.  The result will also be supplied to an MI
     consumer as a 'displayhint' attribute of the variable being
     printed.

     This is a basic method, and is optional.  If it does exist, this
     method must return a string or the special value 'None'.

     Some display hints are predefined by GDB:

     'array'
          Indicate that the object being printed is "array-like".  The
          CLI uses this to respect parameters such as 'set print
          elements' and 'set print array'.

     'map'
          Indicate that the object being printed is "map-like", and that
          the children of this value can be assumed to alternate between
          keys and values.

     'string'
          Indicate that the object being printed is "string-like".  If
          the printer's 'to_string' method returns a Python string of
          some kind, then GDB will call its internal language-specific
          string-printing function to format the string.  For the CLI
          this means adding quotation marks, possibly escaping some
          characters, respecting 'set print elements', and the like.

     The special value 'None' causes GDB to apply the default display
     rules.

 -- Function: pretty_printer.to_string (self)
     GDB will call this method to display the string representation of
     the value passed to the object's constructor.

     This is a basic method, and is optional.

     When printing from the CLI, if the 'to_string' method exists, then
     GDB will prepend its result to the values returned by 'children'.
     Exactly how this formatting is done is dependent on the display
     hint, and may change as more hints are added.  Also, depending on
     the print settings (*note Print Settings::), the CLI may print just
     the result of 'to_string' in a stack trace, omitting the result of
     'children'.

     If this method returns a string, it is printed verbatim.

     Otherwise, if this method returns an instance of 'gdb.Value', then
     GDB prints this value.  This may result in a call to another
     pretty-printer.

     If instead the method returns a Python value which is convertible
     to a 'gdb.Value', then GDB performs the conversion and prints the
     resulting value.  Again, this may result in a call to another
     pretty-printer.  Python scalars (integers, floats, and booleans)
     and strings are convertible to 'gdb.Value'; other types are not.

     Finally, if this method returns 'None' then no further operations
     are performed in this method and nothing is printed.

     If the result is not one of these types, an exception is raised.

 -- Function: pretty_printer.num_children ()
     This is not a basic method, so GDB will only ever call it for
     objects derived from 'gdb.ValuePrinter'.

     If available, this method should return the number of children.
     'None' may be returned if the number can't readily be computed.

 -- Function: pretty_printer.child (n)
     This is not a basic method, so GDB will only ever call it for
     objects derived from 'gdb.ValuePrinter'.

     If available, this method should return the child item (that is, a
     tuple holding the name and value of this child) indicated by N.
     Indices start at zero.

   GDB provides a function which can be used to look up the default
pretty-printer for a 'gdb.Value':

 -- Function: gdb.default_visualizer (value)
     This function takes a 'gdb.Value' object as an argument.  If a
     pretty-printer for this value exists, then it is returned.  If no
     such printer exists, then this returns 'None'.

   Normally, a pretty-printer can respect the user's print settings
(including temporarily applied settings, such as '/x') simply by calling
'Value.format_string' (*note Values From Inferior::).  However, these
settings can also be queried directly:

 -- Function: gdb.print_options ()
     Return a dictionary whose keys are the valid keywords that can be
     given to 'Value.format_string', and whose values are the user's
     settings.  During a 'print' or other operation, the values will
     reflect any flags that are temporarily in effect.

          (gdb) python print (gdb.print_options ()['max_elements'])
          200


File: gdb.info,  Node: Selecting Pretty-Printers,  Next: Writing a Pretty-Printer,  Prev: Pretty Printing API,  Up: Python API

23.3.2.7 Selecting Pretty-Printers
..................................

GDB provides several ways to register a pretty-printer: globally, per
program space, and per objfile.  When choosing how to register your
pretty-printer, a good rule is to register it with the smallest scope
possible: that is prefer a specific objfile first, then a program space,
and only register a printer globally as a last resort.

 -- Variable: gdb.pretty_printers
     The Python list 'gdb.pretty_printers' contains an array of
     functions or callable objects that have been registered via
     addition as a pretty-printer.  Printers in this list are called
     'global' printers, they're available when debugging all inferiors.

   Each 'gdb.Progspace' contains a 'pretty_printers' attribute.  Each
'gdb.Objfile' also contains a 'pretty_printers' attribute.

   Each function on these lists is passed a single 'gdb.Value' argument
and should return a pretty-printer object conforming to the interface
definition above (*note Pretty Printing API::).  If a function cannot
create a pretty-printer for the value, it should return 'None'.

   GDB first checks the 'pretty_printers' attribute of each
'gdb.Objfile' in the current program space and iteratively calls each
enabled lookup routine in the list for that 'gdb.Objfile' until it
receives a pretty-printer object.  If no pretty-printer is found in the
objfile lists, GDB then searches the pretty-printer list of the current
program space, calling each enabled function until an object is
returned.  After these lists have been exhausted, it tries the global
'gdb.pretty_printers' list, again calling each enabled function until an
object is returned.

   The order in which the objfiles are searched is not specified.  For a
given list, functions are always invoked from the head of the list, and
iterated over sequentially until the end of the list, or a printer
object is returned.

   For various reasons a pretty-printer may not work.  For example, the
underlying data structure may have changed and the pretty-printer is out
of date.

   The consequences of a broken pretty-printer are severe enough that
GDB provides support for enabling and disabling individual printers.
For example, if 'print frame-arguments' is on, a backtrace can become
highly illegible if any argument is printed with a broken printer.

   Pretty-printers are enabled and disabled by attaching an 'enabled'
attribute to the registered function or callable object.  If this
attribute is present and its value is 'False', the printer is disabled,
otherwise the printer is enabled.


File: gdb.info,  Node: Writing a Pretty-Printer,  Next: Type Printing API,  Prev: Selecting Pretty-Printers,  Up: Python API

23.3.2.8 Writing a Pretty-Printer
.................................

A pretty-printer consists of two parts: a lookup function to detect if
the type is supported, and the printer itself.

   Here is an example showing how a 'std::string' printer might be
written.  *Note Pretty Printing API::, for details on the API this class
must provide.  Note that this example uses the 'gdb.ValuePrinter' base
class, and is careful to use a leading underscore for its local state.

     class StdStringPrinter(gdb.ValuePrinter):
         "Print a std::string"

         def __init__(self, val):
             self.__val = val

         def to_string(self):
             return self.__val['_M_dataplus']['_M_p']

         def display_hint(self):
             return 'string'

   And here is an example showing how a lookup function for the printer
example above might be written.

     def str_lookup_function(val):
         lookup_tag = val.type.tag
         if lookup_tag is None:
             return None
         regex = re.compile("^std::basic_string<char,.*>$")
         if regex.match(lookup_tag):
             return StdStringPrinter(val)
         return None

   The example lookup function extracts the value's type, and attempts
to match it to a type that it can pretty-print.  If it is a type the
printer can pretty-print, it will return a printer object.  If not, it
returns 'None'.

   We recommend that you put your core pretty-printers into a Python
package.  If your pretty-printers are for use with a library, we further
recommend embedding a version number into the package name.  This
practice will enable GDB to load multiple versions of your
pretty-printers at the same time, because they will have different
names.

   You should write auto-loaded code (*note Python Auto-loading::) such
that it can be evaluated multiple times without changing its meaning.
An ideal auto-load file will consist solely of 'import's of your printer
modules, followed by a call to a register pretty-printers with the
current objfile.

   Taken as a whole, this approach will scale nicely to multiple
inferiors, each potentially using a different library version.
Embedding a version number in the Python package name will ensure that
GDB is able to load both sets of printers simultaneously.  Then, because
the search for pretty-printers is done by objfile, and because your
auto-loaded code took care to register your library's printers with a
specific objfile, GDB will find the correct printers for the specific
version of the library used by each inferior.

   To continue the 'std::string' example (*note Pretty Printing API::),
this code might appear in 'gdb.libstdcxx.v6':

     def register_printers(objfile):
         objfile.pretty_printers.append(str_lookup_function)

And then the corresponding contents of the auto-load file would be:

     import gdb.libstdcxx.v6
     gdb.libstdcxx.v6.register_printers(gdb.current_objfile())

   The previous example illustrates a basic pretty-printer.  There are a
few things that can be improved on.  The printer doesn't have a name,
making it hard to identify in a list of installed printers.  The lookup
function has a name, but lookup functions can have arbitrary, even
identical, names.

   Second, the printer only handles one type, whereas a library
typically has several types.  One could install a lookup function for
each desired type in the library, but one could also have a single
lookup function recognize several types.  The latter is the conventional
way this is handled.  If a pretty-printer can handle multiple data
types, then its "subprinters" are the printers for the individual data
types.

   The 'gdb.printing' module provides a formal way of solving these
problems (*note gdb.printing::).  Here is another example that handles
multiple types.

   These are the types we are going to pretty-print:

     struct foo { int a, b; };
     struct bar { struct foo x, y; };

   Here are the printers:

     class fooPrinter(gdb.ValuePrinter):
         """Print a foo object."""

         def __init__(self, val):
             self.__val = val

         def to_string(self):
             return ("a=<" + str(self.__val["a"]) +
                     "> b=<" + str(self.__val["b"]) + ">")

     class barPrinter(gdb.ValuePrinter):
         """Print a bar object."""

         def __init__(self, val):
             self.__val = val

         def to_string(self):
             return ("x=<" + str(self.__val["x"]) +
                     "> y=<" + str(self.__val["y"]) + ">")

   This example doesn't need a lookup function, that is handled by the
'gdb.printing' module.  Instead a function is provided to build up the
object that handles the lookup.

     import gdb.printing

     def build_pretty_printer():
         pp = gdb.printing.RegexpCollectionPrettyPrinter(
             "my_library")
         pp.add_printer('foo', '^foo$', fooPrinter)
         pp.add_printer('bar', '^bar$', barPrinter)
         return pp

   And here is the autoload support:

     import gdb.printing
     import my_library
     gdb.printing.register_pretty_printer(
         gdb.current_objfile(),
         my_library.build_pretty_printer())

   Finally, when this printer is loaded into GDB, here is the
corresponding output of 'info pretty-printer':

     (gdb) info pretty-printer
     my_library.so:
       my_library
         foo
         bar


File: gdb.info,  Node: Type Printing API,  Next: Frame Filter API,  Prev: Writing a Pretty-Printer,  Up: Python API

23.3.2.9 Type Printing API
..........................

GDB provides a way for Python code to customize type display.  This is
mainly useful for substituting canonical typedef names for types.

   A "type printer" is just a Python object conforming to a certain
protocol.  A simple base class implementing the protocol is provided;
see *note gdb.types::.  A type printer must supply at least:

 -- Instance Variable of type_printer: enabled
     A boolean which is True if the printer is enabled, and False
     otherwise.  This is manipulated by the 'enable type-printer' and
     'disable type-printer' commands.

 -- Instance Variable of type_printer: name
     The name of the type printer.  This must be a string.  This is used
     by the 'enable type-printer' and 'disable type-printer' commands.

 -- Method on type_printer: instantiate (self)
     This is called by GDB at the start of type-printing.  It is only
     called if the type printer is enabled.  This method must return a
     new object that supplies a 'recognize' method, as described below.

   When displaying a type, say via the 'ptype' command, GDB will compute
a list of type recognizers.  This is done by iterating first over the
per-objfile type printers (*note Objfiles In Python::), followed by the
per-progspace type printers (*note Progspaces In Python::), and finally
the global type printers.

   GDB will call the 'instantiate' method of each enabled type printer.
If this method returns 'None', then the result is ignored; otherwise, it
is appended to the list of recognizers.

   Then, when GDB is going to display a type name, it iterates over the
list of recognizers.  For each one, it calls the recognition function,
stopping if the function returns a non-'None' value.  The recognition
function is defined as:

 -- Method on type_recognizer: recognize (self, type)
     If TYPE is not recognized, return 'None'.  Otherwise, return a
     string which is to be printed as the name of TYPE.  The TYPE
     argument will be an instance of 'gdb.Type' (*note Types In
     Python::).

   GDB uses this two-pass approach so that type printers can efficiently
cache information without holding on to it too long.  For example, it
can be convenient to look up type information in a type printer and hold
it for a recognizer's lifetime; if a single pass were done then type
printers would have to make use of the event system in order to avoid
holding information that could become stale as the inferior changed.


File: gdb.info,  Node: Frame Filter API,  Next: Frame Decorator API,  Prev: Type Printing API,  Up: Python API

23.3.2.10 Filtering Frames
..........................

Frame filters are Python objects that manipulate the visibility of a
frame or frames when a backtrace (*note Backtrace::) is printed by GDB.

   Only commands that print a backtrace, or, in the case of GDB/MI
commands (*note GDB/MI::), those that return a collection of frames are
affected.  The commands that work with frame filters are:

   'backtrace' (*note The backtrace command: backtrace-command.),
'-stack-list-frames' (*note The -stack-list-frames command:
-stack-list-frames.), '-stack-list-variables' (*note The
-stack-list-variables command: -stack-list-variables.),
'-stack-list-arguments' *note The -stack-list-arguments command:
-stack-list-arguments.) and '-stack-list-locals' (*note The
-stack-list-locals command: -stack-list-locals.).

   A frame filter works by taking an iterator as an argument, applying
actions to the contents of that iterator, and returning another iterator
(or, possibly, the same iterator it was provided in the case where the
filter does not perform any operations).  Typically, frame filters
utilize tools such as the Python's 'itertools' module to work with and
create new iterators from the source iterator.  Regardless of how a
filter chooses to apply actions, it must not alter the underlying GDB
frame or frames, or attempt to alter the call-stack within GDB.  This
preserves data integrity within GDB.  Frame filters are executed on a
priority basis and care should be taken that some frame filters may have
been executed before, and that some frame filters will be executed
after.

   An important consideration when designing frame filters, and well
worth reflecting upon, is that frame filters should avoid unwinding the
call stack if possible.  Some stacks can run very deep, into the tens of
thousands in some cases.  To search every frame when a frame filter
executes may be too expensive at that step.  The frame filter cannot
know how many frames it has to iterate over, and it may have to iterate
through them all.  This ends up duplicating effort as GDB performs this
iteration when it prints the frames.  If the filter can defer unwinding
frames until frame decorators are executed, after the last filter has
executed, it should.  *Note Frame Decorator API::, for more information
on decorators.  Also, there are examples for both frame decorators and
filters in later chapters.  *Note Writing a Frame Filter::, for more
information.

   The Python dictionary 'gdb.frame_filters' contains key/object
pairings that comprise a frame filter.  Frame filters in this dictionary
are called 'global' frame filters, and they are available when debugging
all inferiors.  These frame filters must register with the dictionary
directly.  In addition to the 'global' dictionary, there are other
dictionaries that are loaded with different inferiors via auto-loading
(*note Python Auto-loading::).  The two other areas where frame filter
dictionaries can be found are: 'gdb.Progspace' which contains a
'frame_filters' dictionary attribute, and each 'gdb.Objfile' object
which also contains a 'frame_filters' dictionary attribute.

   When a command is executed from GDB that is compatible with frame
filters, GDB combines the 'global', 'gdb.Progspace' and all
'gdb.Objfile' dictionaries currently loaded.  All of the 'gdb.Objfile'
dictionaries are combined, as several frames, and thus several object
files, might be in use.  GDB then prunes any frame filter whose
'enabled' attribute is 'False'.  This pruned list is then sorted
according to the 'priority' attribute in each filter.

   Once the dictionaries are combined, pruned and sorted, GDB creates an
iterator which wraps each frame in the call stack in a 'FrameDecorator'
object, and calls each filter in order.  The output from the previous
filter will always be the input to the next filter, and so on.

   Frame filters have a mandatory interface which each frame filter must
implement, defined here:

 -- Function: FrameFilter.filter (iterator)
     GDB will call this method on a frame filter when it has reached the
     order in the priority list for that filter.

     For example, if there are four frame filters:

          Name         Priority

          Filter1      5
          Filter2      10
          Filter3      100
          Filter4      1

     The order that the frame filters will be called is:

          Filter3 -> Filter2 -> Filter1 -> Filter4

     Note that the output from 'Filter3' is passed to the input of
     'Filter2', and so on.

     This 'filter' method is passed a Python iterator.  This iterator
     contains a sequence of frame decorators that wrap each 'gdb.Frame',
     or a frame decorator that wraps another frame decorator.  The first
     filter that is executed in the sequence of frame filters will
     receive an iterator entirely comprised of default 'FrameDecorator'
     objects.  However, after each frame filter is executed, the
     previous frame filter may have wrapped some or all of the frame
     decorators with their own frame decorator.  As frame decorators
     must also conform to a mandatory interface, these decorators can be
     assumed to act in a uniform manner (*note Frame Decorator API::).

     This method must return an object conforming to the Python iterator
     protocol.  Each item in the iterator must be an object conforming
     to the frame decorator interface.  If a frame filter does not wish
     to perform any operations on this iterator, it should return that
     iterator untouched.

     This method is not optional.  If it does not exist, GDB will raise
     and print an error.

 -- Variable: FrameFilter.name
     The 'name' attribute must be Python string which contains the name
     of the filter displayed by GDB (*note Frame Filter Management::).
     This attribute may contain any combination of letters or numbers.
     Care should be taken to ensure that it is unique.  This attribute
     is mandatory.

 -- Variable: FrameFilter.enabled
     The 'enabled' attribute must be Python boolean.  This attribute
     indicates to GDB whether the frame filter is enabled, and should be
     considered when frame filters are executed.  If 'enabled' is
     'True', then the frame filter will be executed when any of the
     backtrace commands detailed earlier in this chapter are executed.
     If 'enabled' is 'False', then the frame filter will not be
     executed.  This attribute is mandatory.

 -- Variable: FrameFilter.priority
     The 'priority' attribute must be Python integer.  This attribute
     controls the order of execution in relation to other frame filters.
     There are no imposed limits on the range of 'priority' other than
     it must be a valid integer.  The higher the 'priority' attribute,
     the sooner the frame filter will be executed in relation to other
     frame filters.  Although 'priority' can be negative, it is
     recommended practice to assume zero is the lowest priority that a
     frame filter can be assigned.  Frame filters that have the same
     priority are executed in unsorted order in that priority slot.
     This attribute is mandatory.  100 is a good default priority.


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.

