[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

23. Extending GDB

GDB provides two mechanisms for extension. The first is based on composition of GDB commands, and the second is based on the Python scripting language.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

23.1 Canned Sequences of Commands

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

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 up to 10 arguments separated by whitespace. Arguments are accessed within the user command via $arg0…$arg9. A trivial example:

define adder
  print $arg0 + $arg1 + $arg2

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. This expands to a number in the range 0…10.

define adder
  if $argc == 2
    print $arg0 + $arg1
  if $argc == 3
    print $arg0 + $arg1 + $arg2
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. commandname may be a bare command name consisting of letters, numbers, dashes, and underscores. It may also start with any predefined 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.


Used inside a user-defined command, this tells GDB that this command should not be repeated when the user hits RET (see section repeat last command).

help user-defined

List all user-defined commands, with the first line of the documentation (if any) for each.

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.

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.

In addition to the above commands, user-defined commands frequently use control flow commands, described in 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.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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

define hook-run
handle SIGALRM pass

define hook-continue
handle SIGALRM pass

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 <<<---

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

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

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.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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:

source [-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 searches for filename in the current directory and then on the search path (specified with the `directory' command).

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.


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.


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.


This command exits the while loop in whose body it is included. Execution of the script continues after that whiles end line.


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.


Terminate the block of commands that are the body of if, else, or while flow-control commands.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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. See section 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. See section 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:

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:

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

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

23.2 Scripting GDB using Python

You can script GDB using the Python programming language. This feature is available only if GDB was configured using `--with-python'.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

23.2.1 Python Commands

GDB provides one command for accessing the Python interpreter, and one related setting:

python [code]

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

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
Type python script
End with a line saying just "end".
>print 23
maint set python print-stack

By default, GDB will print a stack trace when an error occurs in a Python script. This can be controlled using maint set python print-stack: if on, the default, then Python stack printing is enabled; if off, then Python stack printing is disabled.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

23.2.2 Python API

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 (see section Screen Size). In this situation, a Python KeyboardInterrupt exception is thrown.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] Basic Python

GDB introduces a new Python module, named gdb. All methods and classes added by GDB are placed in this module. GDB automatically imports the gdb module for use in all scripts evaluated by the python command.

Function: execute command [from_tty]

Evaluate command, a string, as a GDB CLI command. If a GDB exception happens while command runs, it is translated as described in Exception Handling. If no exceptions occur, this function returns None.

from_tty specifies whether GDB ought to consider this command as having originated from the user invoking it interactively. It must be a boolean value. If omitted, it defaults to False.

Function: parameter parameter

Return the value of a GDB parameter. parameter is a string naming the parameter to look up; parameter 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 RuntimeError. Otherwise, the parameter's value is converted to a Python value of the appropriate type, and returned.

Function: history number

Return a value from GDB's value history (see section Value History). number 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 RuntimeError exception will be raised.

If no exception is raised, the return value is always an instance of gdb.Value (see section Values From Inferior).

Function: write string

Print a string to GDB's paginated standard output stream. Writing to sys.stdout or sys.stderr will automatically call this function.

Function: flush

Flush GDB's paginated standard output stream. Flushing sys.stdout or sys.stderr will automatically call this function.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] 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 containing the Python exception name, the associated value, and the Python call stack backtrace at the point where the exception was raised. 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 RuntimeError exceptions. User interrupt (via C-c or by typing q at a pagination prompt) is translated to a Python KeyboardInterrupt exception. If you catch these exceptions in your Python code, your exception handler will see RuntimeError or KeyboardInterrupt as the exception type, the GDB error message as its value, and the Python call stack backtrace at the Python statement closest to where the GDB error occured as the traceback.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] Auto-loading

When a new object file is read (for example, due to the file command, or because the inferior has loaded a shared library), GDB will look for a file named `objfile-gdb.py', where objfile is the object file's real name, formed by ensuring that the file name is absolute, following all symlinks, and resolving . and .. components. If this file exists and is readable, GDB will evaluate it as a Python script.

If this file does not exist, and if the parameter debug-file-directory is set (see section Debugging Information in Separate Files), then GDB will use the file named `debug-file-directory/real-name', where real-name is the object file's real name, as described above.

Finally, if this file does not exist, then GDB will look for a file named `data-directory/python/auto-load/real-name', where data-directory is GDB's data directory (available via show data-directory, see section GDB Data Files), and real-name is the object file's real name, as described above.

When reading an auto-loaded file, GDB sets the "current objfile". This is available via the gdb.current_objfile function (see section Objfiles In Python). This can be useful for registering objfile-specific pretty-printers.

The auto-loading feature is useful for supplying application-specific debugging commands and scripts. You can enable or disable this feature, and view its current state.

maint set python auto-load [yes|no]

Enable or disable the Python auto-loading feature.

show python auto-load

Show whether Python auto-loading is enabled or disabled.

GDB does not track which files it has already auto-loaded. So, your `-gdb.py' file should take care to ensure that it may be evaluated multiple times without error.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] 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.

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.

The following attributes are provided:

Instance Variable of Value: address

If this object is addressable, this read-only attribute holds a gdb.Value object representing the address. Otherwise, this attribute holds None.

Instance Variable of 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.

Instance Variable of Value: type

The type of this gdb.Value. The value of this attribute is a gdb.Type object.

The following methods are provided:

Method on 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.

Method on 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.

Strings are recognized in a language-specific way; whether a given gdb.Value represents a string is determined by the current language.

For C-like languages, a value is a string if it is a pointer to or an array of characters or ints. The string is assumed to be terminated by a zero of the appropriate width. However if the optional length argument is given, the string will be converted to that given length, ignoring any embedded zeros that the string may contain.

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 (see section 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.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] 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: lookup_type name [block]

This function looks up a type by name. name is the name of the type to look up. It must be a string.

Ordinarily, this function will return an instance of gdb.Type. If the named type cannot be found, it will throw an exception.

An instance of Type has the following attributes:

Instance Variable of Type: code

The type code for this type. The type code will be one of the TYPE_CODE_ constants defined below.

Instance Variable of 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.

Instance Variable of 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.

The following methods are provided:

Method on Type: fields

For structure and union types, this method returns the fields. Range types have two fields, the minimum and maximum values. Enum types have one field per enum constant. Function and method types have one field per parameter. The base types of C++ classes are also represented as fields. If the type has no fields, or does not fit into one of these categories, an empty sequence will be returned.

Each field is an object, with some pre-defined attributes:


This attribute is not available for static fields (as in C++ or Java). For non-static fields, the value is the bit position of the field.


The name of the field, or None for anonymous fields.


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.


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.


The type of the field. This is usually an instance of Type, but it can be None in some situations.

Method on Type: const

Return a new gdb.Type object which represents a const-qualified variant of this type.

Method on Type: volatile

Return a new gdb.Type object which represents a volatile-qualified variant of this type.

Method on 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.

Method on Type: reference

Return a new gdb.Type object which represents a reference to this type.

Method on Type: strip_typedefs

Return a new gdb.Type that represents the real type, after removing all layers of typedefs.

Method on 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.

Method on Type: template_argument n

If this gdb.Type is an instantiation of a template, this will return a new gdb.Type which represents the type of the nth template argument.

If this gdb.Type is not a template type, this will throw an exception. Ordinarily, only C++ code will have template types.

name is searched for globally.

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:


The type is a pointer.


The type is an array.


The type is a structure.


The type is a union.


The type is an enum.


A bit flags type, used for things such as status registers.


The type is a function.


The type is an integer type.


A floating point type.


The special type void.


A Pascal set type.


A range type, that is, an integer type with bounds.


A string type. Note that this is only used for certain languages with language-defined string types; C strings are not represented this way.


A string of bits.


An unknown or erroneous type.


A method type, as found in C++ or Java.


A pointer-to-member-function.


A pointer-to-member.


A reference type.


A character type.


A boolean type.


A complex float type.


A typedef to some other type.


A C++ namespace.


A decimal floating point type.


A function internal to GDB. This is the type used to represent convenience functions.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] Pretty Printing

GDB provides a mechanism to allow pretty-printing of values using Python code. The pretty-printer API allows application-specific code to greatly simplify the display of complex objects. This mechanism works for both MI and the CLI.

For example, here is how a C++ std::string looks without a pretty-printer:

(gdb) print s
$1 = {
  static npos = 4294967295, 
  _M_dataplus = {
    <std::allocator<char>> = {
      <__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, 
    members of std::basic_string<char, std::char_traits<char>, std::allocator<char> >::_Alloc_hider: 
    _M_p = 0x804a014 "abcd"

After a pretty-printer for std::string has been installed, only the contents are printed:

(gdb) print s
$2 = "abcd"

A pretty-printer is just an object that holds a value and implements a specific interface, defined here.

Operation on 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 method is optional. If it does not exist, GDB will act as though the value has no children.

Operation on 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 method is optional. If it does exist, this method must return a string.

Some display hints are predefined by GDB:


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.


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.


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.

Operation on pretty printer: to_string (self)

GDB will call this method to display the string representation of the value passed to the object's constructor.

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 (see section 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.

If the result is not one of these types, an exception is raised.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] Selecting Pretty-Printers

The Python list gdb.pretty_printers contains an array of functions that have been registered via addition as a pretty-printer. Each gdb.Objfile also contains a pretty_printers attribute.

A function on one of these lists is passed a single gdb.Value argument and should return a pretty-printer object conforming to the interface definition above (see section Pretty Printing). 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 and iteratively calls each function in the list for that gdb.Objfile until it receives a pretty-printer object. After these lists have been exhausted, it tries the global gdb.pretty-printers list, again calling each 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.

Here is an example showing how a std::string printer might be written:

class StdStringPrinter:
    "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
    regex = re.compile ("^std::basic_string<char,.*>$")
    if lookup_tag == None:
        return None
    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 (see section Auto-loading) such that it can be evaluated multiple times without changing its meaning. An ideal auto-load file will consist solely of imports 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 (see section Pretty Printing), this code might appear in gdb.libstdcxx.v6:

def register_printers (objfile):
    objfile.pretty_printers.add (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 ())

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] Commands In Python

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

Method on Command: __init__ name command_class [completer_class] [prefix]

The object initializer for Command registers the new command with GDB. This initializer is normally invoked from the subclass' own __init__ method.

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

There is no support for multi-line commands.

command_class should be one of the `COMMAND_' constants defined below. This argument tells GDB how to categorize the new command in the help system.

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

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

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

Method on Command: dont_repeat

By default, a GDB command is repeated when the user enters a blank line at the command prompt. A command can suppress this behavior by invoking the dont_repeat method. This is similar to the user command dont-repeat, see dont-repeat.

Method on Command: invoke argument from_tty

This method is called by GDB when this command is invoked.

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

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

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

Method on Command: complete text word

This method is called by GDB when the user attempts completion on this command. All forms of completion are handled by this method, that is, the TAB and M-? key bindings (see section Command Completion), and the complete command (see section complete).

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

The complete method can return several values:

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


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


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


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


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


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


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


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


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


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


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


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

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


This constant means that no completion should be done.


This constant means that filename completion should be performed.


This constant means that location completion should be done. See section Specifying a Location.


This constant means that completion should examine GDB command names.


This constant means that completion should be done using symbol names as the source.

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

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

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

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

HelloWorld ()

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

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] Writing new convenience functions

You can implement new convenience functions (see section Convenience Variables) in Python. A convenience function is an instance of a subclass of the class gdb.Function.

Method on Function: __init__ name

The initializer for Function registers the new function with GDB. The argument name is the name of the function, a string. The function will be visible to the user as a convenience variable of type internal function, whose name is the same as the given name.

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

Method on Function: invoke *args

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

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

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

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

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

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

Greet ()

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

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] Objfiles In Python

GDB loads symbols for an inferior from various symbol-containing files (see section Commands to Specify Files). These include the primary executable file, any shared libraries used by the inferior, and any separate debug info files (see section Debugging Information in Separate Files). GDB calls these symbol-containing files objfiles.

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

Function: current_objfile

When auto-loading a Python script (see section Auto-loading), GDB sets the "current objfile" to the corresponding objfile. This function returns the current objfile. If there is no current objfile, this function returns None.

Function: objfiles

Return a sequence of all the objfiles current known to GDB. See section Objfiles In Python.

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

Instance Variable of Objfile: filename

The file name of the objfile as a string.

Instance Variable of Objfile: pretty_printers

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

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] Acessing inferior stack frames from Python.

When the debugged program stops, GDB is able to analyze its call stack (see section Stack frames). The gdb.Frame class represents a frame in the stack. A gdb.Frame object is only valid while its corresponding frame exists in the inferior's stack. If you try to use an invalid frame object, GDB will throw a RuntimeError exception.

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

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

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

Function: selected_frame

Return the selected frame object. (see section Selecting a Frame).

Function: frame_stop_reason_string reason

Return a string explaining the reason why GDB stopped unwinding frames, as expressed by the given reason code (an integer, see the unwind_stop_reason method further down in this section).

A gdb.Frame object has the following methods:

Method on Frame: is_valid

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

Method on Frame: name

Returns the function name of the frame, or None if it can't be obtained.

Method on Frame: type

Returns the type of the frame. The value can be one of gdb.NORMAL_FRAME, gdb.DUMMY_FRAME, gdb.SIGTRAMP_FRAME or gdb.SENTINEL_FRAME.

Method on Frame: unwind_stop_reason

Return an integer representing the reason why it's not possible to find more frames toward the outermost frame. Use gdb.frame_stop_reason_string to convert the value returned by this function to a string.

Method on Frame: pc

Returns the frame's resume address.

Method on Frame: older

Return the frame that called this frame.

Method on Frame: newer

Return the frame called by this frame.

Method on Frame: read_var variable

Return the value of the given variable in this frame. variable must be a string.

[ << ] [ >> ]           [Top] [Contents] [Index] [ ? ]

This document was generated on January, 20 2010 using texi2html 1.76.