| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
23.1 Canned Sequences of Commands 23.2 Scripting GDB using Python
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
23.1.1 User-defined Commands How to define your own commands 23.1.2 User-defined Command Hooks Hooks for user-defined commands 23.1.3 Command Files How to write scripts of commands to be stored in a file 23.1.4 Commands for Controlled Output Commands for controlled output
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 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. This expands to a number in the range 0...10.
define adder
if $argc == 2
print $arg0 + $arg1
end
if $argc == 3
print $arg0 + $arg1 + $arg2
end
end
|
define commandname
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
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.
dont-repeat
help user-defined
show user
show user commandname
show max-user-call-depth
set max-user-call-depth
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 23.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] | [ ? ] |
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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
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.
if
else
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
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
while loop in whose body it is included.
Execution of the script continues after that whiles end
line.
loop_continue
while loop in whose body it is included. Execution
branches to the beginning of the while loop, where it evaluates
the controlling expression.
end
if,
else, or while flow-control commands.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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
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
output/fmt expression
print. See section Output Formats, for more information.
printf template, expressions...
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:
LC_NUMERIC') is 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:
Decimal32 types.
Decimal64 types.
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 |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can script GDB using the Python programming language. This feature is available only if GDB was configured using `--with-python'.
23.2.1 Python Commands Accessing Python from GDB. 23.2.2 Python API Accessing GDB from Python.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GDB provides one command for accessing the Python interpreter, and one related setting:
python [code]
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 Type python script End with a line saying just "end". >print 23 >end 23 |
maint set python print-stack
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] | [ ? ] |
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 22.4 Screen Size). In this
situation, a Python KeyboardInterrupt exception is thrown.
23.2.2.1 Basic Python Basic Python Functions. 23.2.2.2 Exception Handling 23.2.2.3 Auto-loading Automatically loading Python code. 23.2.2.4 Values From Inferior 23.2.2.5 Types In Python Python representation of types. 23.2.2.6 Pretty Printing Pretty-printing values. 23.2.2.7 Selecting Pretty-Printers How GDB chooses a pretty-printer. 23.2.2.8 Commands In Python Implementing new commands in Python. 23.2.2.9 Writing new convenience functions 23.2.2.10 Objfiles In Python Object files. 23.2.2.11 Acessing inferior stack frames from Python.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
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.
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.
RuntimeError exception will be
raised.
If no exception is raised, the return value is always an instance of
gdb.Value (see section 23.2.2.4 Values From Inferior).
sys.stdout or sys.stderr will automatically
call this function.
sys.stdout or sys.stderr will automatically call this
function.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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] | [ ? ] |
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 18.2 Debugging Information in Separate Files),
then GDB will use for its each separated directory component
component the file named `component/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 18.4 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 23.2.2.10 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]
show python auto-load
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] | [ ? ] |
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:
gdb.Value object representing the address. Otherwise,
this attribute holds None.
gdb.Value. The value of this attribute is a
gdb.Type object.
The following methods are provided:
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.
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; |
gdb.Value to access what
foo points to like this:
bar = foo.dereference () |
bar will be a gdb.Value object holding the
value pointed to by foo.
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 10.18 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] | [ ? ] |
GDB represents types from the inferior using the class
gdb.Type.
The following type-related functions are available in the gdb
module:
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:
TYPE_CODE_ constants defined below.
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.
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:
bitpos
static fields (as in
C++ or Java). For non-static fields, the value is the bit
position of the field.
name
None for anonymous fields.
artificial
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.
bitsize
type
Type,
but it can be None in some situations.
gdb.Type object which represents a
const-qualified variant of this type.
gdb.Type object which represents a
volatile-qualified variant of this type.
gdb.Type object which represents an unqualified
variant of this type. That is, the result is neither const nor
volatile.
gdb.Type object which represents a reference to this
type.
gdb.Type that represents the real type,
after removing all layers of typedefs.
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.
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:
TYPE_CODE_PTR
TYPE_CODE_ARRAY
TYPE_CODE_STRUCT
TYPE_CODE_UNION
TYPE_CODE_ENUM
TYPE_CODE_FLAGS
TYPE_CODE_FUNC
TYPE_CODE_INT
TYPE_CODE_FLT
TYPE_CODE_VOID
void.
TYPE_CODE_SET
TYPE_CODE_RANGE
TYPE_CODE_STRING
TYPE_CODE_BITSTRING
TYPE_CODE_ERROR
TYPE_CODE_METHOD
TYPE_CODE_METHODPTR
TYPE_CODE_MEMBERPTR
TYPE_CODE_REF
TYPE_CODE_CHAR
TYPE_CODE_BOOL
TYPE_CODE_COMPLEX
TYPE_CODE_TYPEDEF
TYPE_CODE_NAMESPACE
TYPE_CODE_DECFLOAT
TYPE_CODE_INTERNAL_FUNCTION
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
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.
This method is optional. If it does exist, this method must return a string.
Some display hints are predefined by GDB:
set print elements and
set print array.
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.
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 10.8 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] | [ ? ] |
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 23.2.2.6 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 |
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 23.2.2.3 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 23.2.2.6 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] | [ ? ] |
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.
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.
dont_repeat method. This is similar
to the user command dont-repeat, see dont-repeat.
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.
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:
complete to ensure that the
contents actually do complete the word. A zero-length sequence is
allowed, it means that there were no completions available. Only
string elements of the sequence are used; other elements in the
sequence are ignored.
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:
COMMAND_NONE
COMMAND_RUNNING
start, step, and continue are in this category.
Type help running at the GDB prompt to see a list of
commands in this category.
COMMAND_DATA
call, find, and print are in this category. Type
help data at the GDB prompt to see a list of commands
in this category.
COMMAND_STACK
backtrace, frame, and return are in this
category. Type help stack at the GDB prompt to see a
list of commands in this category.
COMMAND_FILES
file, list and section are in this category.
Type help files at the GDB prompt to see a list of
commands in this category.
COMMAND_SUPPORT
help, make, and shell are in this category. Type
help support at the GDB prompt to see a list of
commands in this category.
COMMAND_STATUS
info, macro,
and show are in this category. Type help status at the
GDB prompt to see a list of commands in this category.
COMMAND_BREAKPOINTS
break,
clear, and delete are in this category. Type help
breakpoints at the GDB prompt to see a list of commands in
this category.
COMMAND_TRACEPOINTS
trace,
actions, and tfind are in this category. Type
help tracepoints at the GDB prompt to see a list of
commands in this category.
COMMAND_OBSCURE
checkpoint,
fork, and stop are in this category. Type help
obscure at the GDB prompt to see a list of commands in this
category.
COMMAND_MAINTENANCE
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:
COMPLETE_NONE
COMPLETE_FILENAME
COMPLETE_LOCATION
COMPLETE_COMMAND
COMPLETE_SYMBOL
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] | [ ? ] |
You can implement new convenience functions (see section 10.10 Convenience Variables)
in Python. A convenience function is an instance of a subclass of the
class gdb.Function.
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.
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] | [ ? ] |
GDB loads symbols for an inferior from various symbol-containing files (see section 18.1 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 18.2 Debugging Information in Separate Files). GDB calls these symbol-containing files objfiles.
The following objfile-related functions are available in the
gdb module:
None.
Each objfile is represented by an instance of the gdb.Objfile
class.
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 23.2.2.6 Pretty Printing, for more
information.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 () True |
The following frame-related functions are available in the gdb module:
unwind_stop_reason method further down in this section).
A gdb.Frame object has the following methods:
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.
None if it can't be
obtained.
gdb.NORMAL_FRAME, gdb.DUMMY_FRAME, gdb.SIGTRAMP_FRAME
or gdb.SENTINEL_FRAME.
gdb.frame_stop_reason_string to convert the value returned by this
function to a string.
| [ << ] | [ >> ] | [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 November, 3 2009 using texi2html