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

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

20.1 Canned Sequences of Commands  
20.2 Scripting GDB using Python  

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

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

20.1.1 User-defined Commands  How to define your own commands
20.1.2 User-defined Command Hooks  Hooks for user-defined commands
20.1.3 Command Files  How to write scripts of commands to be stored in a file
20.1.4 Commands for Controlled Output  Commands for controlled output

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

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

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 20.1.3 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] [ ? ]

20.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. 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] [ ? ]

20.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] [ ? ]

20.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] [ ? ]

20.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'.

20.2.1 Python Commands  Accessing Python from GDB.
20.2.2 Python API  Accessing GDB from Python.

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

20.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] [ ? ]

20.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 19.4 Screen Size). In this situation, a Python KeyboardInterrupt exception is thrown. Basic Python  Basic Python Functions. Exception Handling  

[ < ] [ > ]   [ << ] [ 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
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.

Function: get_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: 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.

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

Please send FSF & GNU inquiries & questions to gnu@gnu.org. There are also other ways to contact the FSF.

These pages are maintained by the GDB developers.

Copyright Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.

Verbatim copying and distribution of this entire article is permitted in any medium, provided this notice is preserved.

This document was generated by GDB Administrator on August, 20 2008 using texi2html