[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GDB provides several mechanisms for extension. GDB also provides the ability to automatically load extensions when it reads a file for debugging. This allows the user to automatically customize GDB for the program being debugged.
23.1 Canned Sequences of Commands Canned Sequences of GDB Commands 23.2 Extending GDB using Python 23.3 Auto-loading extensions Automatically loading extensions 23.4 Creating new spellings of existing commands
To facilitate the use of extension languages, GDB is capable of evaluating the contents of a file. When doing so, GDB can recognize which extension language is being used by looking at the filename extension. Files with an unrecognized filename extension are always treated as a GDB Command Files. See section Command files.
You can control how GDB evaluates these files with the following setting:
set script-extension off
set script-extension soft
set script-extension strict
show script-extension
script-extension
option.
[ < ] | [ > ] | [ << ] | [ 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 23.1.5 Controlling auto-loading native GDB scripts Controlling auto-loaded command files
[ < ] | [ > ] | [ << ] | [ 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.
This does not apply to user-defined python commands.
In addition to the above commands, user-defined commands frequently use control flow commands, described in 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. Note that the source
command is also used to evaluate
scripts that are not Command Files. The exact behavior can be configured
using the script-extension
setting.
See section Extending GDB.
source [-s] [-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 first searches for filename in the current directory. If the file is not found there, and filename does not specify a directory, then GDB also looks for the file on the source search path (specified with the `directory' command); except that `$cdir' is not searched because the compilation directory is not relevant to scripts.
If -s
is specified, then GDB searches for filename
on the search path even if filename specifies a directory.
The search is done by appending filename to each element of the
search path. So, for example, if filename is `mylib/myscript'
and the search path contains `/home/user' then GDB will
look for the script `/home/user/mylib/myscript'.
The search is also done if filename is an absolute path.
For example, if filename is `/tmp/myscript' and
the search path contains `/home/user' then GDB will
look for the script `/home/user/tmp/myscript'.
For DOS-like systems, if filename contains a drive specification,
it is stripped before concatenation. For example, if filename is
`d:myscript' and the search path contains `c:/tmp' then GDB
will look for the script `c:/tmp/myscript'.
If -v
, for verbose mode, is given then GDB displays
each command as it is executed. The option must be given before
filename, and is interpreted as part of the filename anywhere else.
Commands that would ask for confirmation if used interactively proceed without asking when used in a command file. Many GDB commands that normally print messages to say what they are doing omit the messages when called from command files.
GDB also accepts command input from standard input. In this mode, normal output goes to standard output and error output goes to standard error. Errors in a command file supplied on standard input do not terminate execution of the command file--execution continues with the next command.
gdb < cmds > log 2>&1 |
(The syntax above will vary depending on the shell used.) This example will execute commands from the file `cmds'. All output and errors would be directed to `log'.
Since commands stored on command files tend to be more general than commands typed interactively, they frequently need to deal with complicated situations, such as different or unexpected values of variables and symbols, changes in how the program being debugged is built, etc. GDB provides a set of flow-control commands to deal with these complexities. Using these commands, you can write complex scripts that loop over data structures, execute commands conditionally, etc.
if
else
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 while
s 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 |
eval template, expressions...
[ < ] | [ > ] | [ << ] | [ 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 the command file `objfile-gdb.gdb'.
See section 23.3 Auto-loading extensions.
Auto-loading can be enabled or disabled, and the list of auto-loaded scripts can be printed.
set auto-load gdb-scripts [on|off]
show auto-load gdb-scripts
info auto-load gdb-scripts [regexp]
If regexp is supplied only canned sequences of commands scripts with matching names are printed.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can extend GDB using the Python programming language. This feature is available only if GDB was configured using `--with-python'.
Python scripts used by GDB should be installed in `data-directory/python', where data-directory is the data directory as determined at GDB startup (see section 18.6 GDB Data Files). This directory, known as the python directory, is automatically added to the Python Search Path in order to allow the Python interpreter to locate all scripts installed at this location.
Additionally, GDB commands and convenience functions which are written in Python and are located in the `data-directory/python/gdb/command' or `data-directory/python/gdb/function' directories are automatically imported when GDB starts.
23.2.1 Python Commands Accessing Python from GDB. 23.2.2 Python API Accessing GDB from Python. 23.2.3 Python Auto-loading Automatically loading Python code. 23.2.4 Python modules Python modules provided by GDB.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GDB provides two commands for accessing the Python interpreter, and one related setting:
python-interactive [command]
pi [command]
python-interactive
command can be used
to start an interactive Python prompt. To return to GDB,
type the EOF
character (e.g., Ctrl-D on an empty prompt).
Alternatively, a single-line Python command can be given as an argument and evaluated. If the command is an expression, the result will be printed; otherwise, nothing will be printed. For example:
(gdb) python-interactive 2 + 3 5 |
python [command]
py [command]
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 |
set python print-stack
set python print-stack
: if full
, then
full Python stack printing is enabled; if none
, then Python stack
and message printing is disabled; if message
, the default, only
the message component of the error is printed.
It is also possible to execute a Python script from the GDB interpreter:
source `script-name'
script-extension
setting. See section Extending GDB.
python execfile ("script-name")
execfile
Python built-in function,
and thus is always available.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can get quick online help for GDB's Python API by issuing the command python help (gdb).
Functions and methods which have two or more optional arguments allow
them to be specified using keyword syntax. This allows passing some
optional arguments while skipping others. Example:
gdb.some_function ('foo', bar = 1, baz = 2)
.
[ < ] | [ > ] | [ << ] | [ 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.
Some care must be taken when writing Python code to run in GDB. Two things worth noting in particular:
SIGCHLD
and SIGINT
.
Python code must not override these, or even change the options using
sigaction
. If your program changes the handling of these
signals, GDB will most likely stop working correctly. Note
that it is unfortunately common for GUI toolkits to install a
SIGCHLD
handler.
GDB introduces a new Python module, named gdb
. All
methods and classes added by GDB are placed in this module.
GDB automatically import
s the gdb
module for
use in all scripts evaluated by the python
command.
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
.
By default, any output produced by command is sent to
GDB's standard output. If the to_string parameter is
True
, then output will be collected by gdb.execute
and
returned as a string. The default is False
, in which case the
return value is None
. If to_string is True
, the
GDB virtual terminal will be temporarily set to unlimited width
and height, and its pagination will be disabled; see section 22.4 Screen Size.
If the named parameter does not exist, this function throws a
gdb.error
(see section 23.2.2.2 Exception Handling). Otherwise, the
parameter's value is converted to a Python value of the appropriate
type, and returned.
gdb.error
exception will be
raised.
If no exception is raised, the return value is always an instance of
gdb.Value
(see section 23.2.2.3 Values From Inferior).
gdb.Value
.
expression must be a string.
This function can be useful when implementing a new command
(see section 23.2.2.15 Commands In Python), as it provides a way to parse the
command's argument as an expression. It is also useful simply to
compute values, for example, it is the only way to get the value of a
convenience variable (see section 10.11 Convenience Variables) as a gdb.Value
.
gdb.Symtab_and_line
object corresponding to the
pc value. See section 23.2.2.23 Symbol table representation in Python.. If an invalid
value of pc is passed as an argument, then the symtab
and
line
attributes of the returned gdb.Symtab_and_line
object
will be None
and 0 respectively.
post_event
will be run in the order in which they
were posted; however, there is no way to know when they will be
processed relative to other events inside GDB.
GDB is not thread-safe. If your Python program uses multiple
threads, you must be careful to only call GDB-specific
functions in the main GDB thread. post_event
ensures
this. For example:
(gdb) python >import threading > >class Writer(): > def __init__(self, message): > self.message = message; > def __call__(self): > gdb.write(self.message) > >class MyThread1 (threading.Thread): > def run (self): > gdb.post_event(Writer("Hello ")) > >class MyThread2 (threading.Thread): > def run (self): > gdb.post_event(Writer("World\n")) > >MyThread1().start() >MyThread2().start() >end (gdb) Hello World |
gdb.STDOUT
gdb.STDERR
gdb.STDLOG
Writing to sys.stdout
or sys.stderr
will automatically
call this function and will automatically direct the output to the
relevant stream.
gdb.STDOUT
gdb.STDERR
gdb.STDLOG
Flushing sys.stdout
or sys.stderr
will automatically
call this function for the relevant stream.
gdb.parameter('target-charset')
in
that `auto' is never returned.
gdb.parameter('target-wide-charset')
in that `auto' is
never returned.
None
.
None
if
the expression has been fully parsed). The second element contains
either None
or another tuple that contains all the locations
that match the expression represented as gdb.Symtab_and_line
objects (see section 23.2.2.23 Symbol table representation in Python.). If expression is
provided, it is decoded the way that GDB's inbuilt
break
or edit
commands do (see section 9.2 Specifying a Location).
If prompt_hook is callable, GDB will call the method assigned to this operation before a prompt is displayed by GDB.
The parameter current_prompt
contains the current GDB
prompt. This method must return a Python string, or None
. If
a string is returned, the GDB prompt will be set to that
string. If None
is returned, GDB will continue to use
the current prompt.
Some prompts cannot be substituted in GDB. Secondary prompts such as those used by readline for command input, and annotation related prompts are prohibited from being changed.
[ < ] | [ > ] | [ << ] | [ 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 exceptions. The type of the Python exception depends on the error.
gdb.error
RuntimeError
, for compatibility with earlier
versions of GDB.
If an error occurring in GDB does not fit into some more specific category, then the generated exception will have this type.
gdb.MemoryError
gdb.error
which is thrown when an
operation tried to access invalid memory in the inferior.
KeyboardInterrupt
KeyboardInterrupt
exception.
In all cases, your exception handler will see the GDB error message as its value and the Python call stack backtrace at the Python statement closest to where the GDB error occured as the traceback.
When implementing GDB commands in Python via gdb.Command
,
it is useful to be able to throw an exception that doesn't cause a
traceback to be printed. For example, the user may have invoked the
command incorrectly. Use the gdb.GdbError
exception
to handle this case. Example:
(gdb) python >class HelloWorld (gdb.Command): > """Greet the whole world.""" > def __init__ (self): > super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER) > def invoke (self, args, from_tty): > argv = gdb.string_to_argv (args) > if len (argv) != 0: > raise gdb.GdbError ("hello-world takes no arguments") > print "Hello, World!" >HelloWorld () >end (gdb) hello-world 42 hello-world takes no arguments |
[ < ] | [ > ] | [ << ] | [ 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. Structure
elements can also be accessed by using gdb.Field
objects as
subscripts (see section 23.2.2.4 Types In Python, for more information on
gdb.Field
objects). For example, if foo_field
is a
gdb.Field
object corresponding to element foo
of the above
structure, then bar
can also be accessed as follows:
bar = some_val[foo_field] |
A gdb.Value
that represents a function can be executed via
inferior function call. Any arguments provided to the call must match
the function's prototype, and must be provided in the order specified
by that prototype.
For example, some_val
is a gdb.Value
instance
representing a function that takes two integers as arguments. To
execute this function, call it like so:
result = some_val (10,20) |
Any values returned from a function call will be stored as a
gdb.Value
.
The following attributes are provided:
gdb.Value
object representing the address. Otherwise,
this attribute holds None
.
gdb.Value
. The value of this attribute is a
gdb.Type
object (see section 23.2.2.4 Types In Python).
gdb.Value
. This uses C++ run-time
type information (RTTI) to determine the dynamic type of the
value. If this value is of class type, it will return the class in
which the value is embedded, if any. If this value is of pointer or
reference to a class type, it will compute the dynamic type of the
referenced object, and return a pointer or reference to that type,
respectively. In all other cases, it will return the value's static
type.
Note that this feature will only work when debugging a C++ program that includes RTTI for the object in question. Otherwise, it will just return the static type of the value as in ptype foo (see section ptype).
True
if this
gdb.Value
has not yet been fetched from the inferior.
GDB does not fetch values until necessary, for efficiency.
For example:
myval = gdb.parse_and_eval ('somevar') |
The value of somevar
is not fetched at this time. It will be
fetched when the value is needed, or when the fetch_lazy
method is invoked.
The following methods are provided:
gdb.Value
via
this object initializer. Specifically:
long
type for the
current architecture.
long long
type for the
current architecture.
double
type for the
current architecture.
gdb.Value
val
is a gdb.Value
, then a copy of the value is made.
gdb.LazyString
val
is a gdb.LazyString
(see section 23.2.2.27 Python representation of lazy strings.), then the lazy string's value
method is called, and
its result is used.
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; |
then you can use the corresponding gdb.Value
to access what
foo
points to like this:
bar = foo.dereference () |
The result bar
will be a gdb.Value
object holding the
value pointed to by foo
.
A similar function Value.referenced_value
exists which also
returns gdb.Value
objects corresonding to the values pointed to
by pointer values (and additionally, values referenced by reference
values). However, the behavior of Value.dereference
differs from Value.referenced_value
by the fact that the
behavior of Value.dereference
is identical to applying the C
unary operator *
on a given value. For example, consider a
reference to a pointer ptrref
, declared in your C++ program
as
typedef int *intptr; ... int val = 10; intptr ptr = &val; intptr &ptrref = ptr; |
Though ptrref
is a reference value, one can apply the method
Value.dereference
to the gdb.Value
object corresponding
to it and obtain a gdb.Value
which is identical to that
corresponding to val
. However, if you apply the method
Value.referenced_value
, the result would be a gdb.Value
object identical to that corresponding to ptr
.
py_ptrref = gdb.parse_and_eval ("ptrref") py_val = py_ptrref.dereference () py_ptr = py_ptrref.referenced_value () |
The gdb.Value
object py_val
is identical to that
corresponding to val
, and py_ptr
is identical to that
corresponding to ptr
. In general, Value.dereference
can
be applied whenever the C unary operator *
can be applied
to the corresponding C value. For those cases where applying both
Value.dereference
and Value.referenced_value
is allowed,
the results obtained need not be identical (as we have seen in the above
example). The results are however identical when applied on
gdb.Value
objects corresponding to pointers (gdb.Value
objects with type code TYPE_CODE_PTR
) in a C/C++ program.
gdb.Value
object corresponding to the value referenced by the
pointer/reference value. For pointer data types,
Value.dereference
and Value.referenced_value
produce
identical results. The difference between these methods is that
Value.dereference
cannot get the values referenced by reference
values. For example, consider a reference to an int
, declared
in your C++ program as
int val = 10; int &ref = val; |
then applying Value.dereference
to the gdb.Value
object
corresponding to ref
will result in an error, while applying
Value.referenced_value
will result in a gdb.Value
object
identical to that corresponding to val
.
py_ref = gdb.parse_and_eval ("ref") er_ref = py_ref.dereference () # Results in error py_val = py_ref.referenced_value () # Returns the referenced value |
The gdb.Value
object py_val
is identical to that
corresponding to val
.
Value.cast
, but works as if the C++ dynamic_cast
operator were used. Consult a C++ reference for details.
Value.cast
, but works as if the C++ reinterpret_cast
operator were used. Consult a C++ reference for details.
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.20 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.
gdb.Value
represents a string, then this method
converts the contents to a gdb.LazyString
(see section 23.2.2.27 Python representation of lazy strings.). Otherwise, this method will throw an exception.
If the optional encoding argument is given, it must be a string
naming the encoding of the gdb.LazyString
. Some examples are:
`ascii', `iso-8859-6' or `utf-8'. If the
encoding argument is an encoding that GDB does
recognize, GDB will raise an error.
When a lazy string is printed, the GDB encoding machinery is used to convert the string during printing. If the optional encoding argument is not provided, or is an empty string, GDB will automatically select the encoding most suitable for the string type. For further information on encoding in GDB please see 10.20 Character Sets.
If the optional length argument is given, the string will be fetched and encoded to the length of characters specified. If the length argument is not provided, the string will be fetched and encoded until a null of appropriate width is found.
gdb.Value
object is currently a lazy value
(gdb.Value.is_lazy
is True
), then the value is
fetched from the inferior. Any errors that occur in the process
will produce a Python exception.
If the gdb.Value
object is not a lazy value, this method
has no effect.
This method does not return a value.
[ < ] | [ > ] | [ << ] | [ 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:
If block is given, then name is looked up in that scope. Otherwise, it is searched for globally.
Ordinarily, this function will return an instance of gdb.Type
.
If the named type cannot be found, it will throw an exception.
If the type is a structure or class type, or an enum type, the fields
of that type can be accessed using the Python dictionary syntax.
For example, if some_type
is a gdb.Type
instance holding
a structure type, you can access its foo
field with:
bar = some_type['foo'] |
bar
will be a gdb.Field
object; see below under the
description of the Type.fields
method for a description of the
gdb.Field
class.
An instance of Type
has the following attributes:
TYPE_CODE_
constants defined below.
None
is returned.
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:
Each field is a gdb.Field
object, with some pre-defined attributes:
bitpos
enum
or static
(as in C++ or Java) fields. The value is the position, counting
in bits, from the start of the containing type.
enumval
enum
fields, and its value
is the enumeration member's integer representation.
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.
is_base_class
True
if the field represents a base class of a C++
structure. This attribute is always provided, and is False
if the field is not a base class of the type that is the argument of
fields
, or if that type was not a C++ class.
bitsize
type
Type
,
but it can be None
in some situations.
parent_type
gdb.Type
.
gdb.Type
object which represents an array of this
type. If one argument is given, it is the inclusive upper bound of
the array; in this case the lower bound is zero. If two arguments are
given, the first argument is the lower bound of the array, and the
second argument is the upper bound of the array. An array's length
must not be negative, but the bounds can be.
gdb.Type
object which represents a vector of this
type. If one argument is given, it is the inclusive upper bound of
the vector; in this case the lower bound is zero. If two arguments are
given, the first argument is the lower bound of the vector, and the
second argument is the upper bound of the vector. A vector's length
must not be negative, but the bounds can be.
The difference between an array
and a vector
is that
arrays behave like in C: when used in expressions they decay to a pointer
to the first element whereas vectors are treated as first class values.
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
.
Tuple
object that contains two elements: the
low bound of the argument type and the high bound of that type. If
the type does not have a range, GDB will raise a
gdb.error
exception (see section 23.2.2.2 Exception Handling).
gdb.Type
object which represents a reference to this
type.
gdb.Type
object which represents a pointer 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.
If block is given, then name is looked up in that scope. Otherwise, it 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:
gdb.TYPE_CODE_PTR
gdb.TYPE_CODE_ARRAY
gdb.TYPE_CODE_STRUCT
gdb.TYPE_CODE_UNION
gdb.TYPE_CODE_ENUM
gdb.TYPE_CODE_FLAGS
gdb.TYPE_CODE_FUNC
gdb.TYPE_CODE_INT
gdb.TYPE_CODE_FLT
gdb.TYPE_CODE_VOID
void
.
gdb.TYPE_CODE_SET
gdb.TYPE_CODE_RANGE
gdb.TYPE_CODE_STRING
gdb.TYPE_CODE_BITSTRING
gdb.TYPE_CODE_ERROR
gdb.TYPE_CODE_METHOD
gdb.TYPE_CODE_METHODPTR
gdb.TYPE_CODE_MEMBERPTR
gdb.TYPE_CODE_REF
gdb.TYPE_CODE_CHAR
gdb.TYPE_CODE_BOOL
gdb.TYPE_CODE_COMPLEX
gdb.TYPE_CODE_TYPEDEF
gdb.TYPE_CODE_NAMESPACE
gdb.TYPE_CODE_DECFLOAT
gdb.TYPE_CODE_INTERNAL_FUNCTION
Further support for types is provided in the gdb.types
Python module (see section 23.2.4.2 gdb.types).
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
An example output is provided (see section 10.9 Pretty Printing).
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.
Finally, if this method returns None
then no further operations
are peformed in this method and nothing is printed.
If the result is not one of these types, an exception is raised.
GDB provides a function which can be used to look up the
default pretty-printer for a gdb.Value
:
gdb.Value
object as an argument. If a
pretty-printer for this value exists, then it is returned. If no such
printer exists, then this returns None
.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The Python list gdb.pretty_printers
contains an array of
functions or callable objects that have been registered via addition
as a pretty-printer. Printers in this list are called global
printers, they're available when debugging all inferiors.
Each gdb.Progspace
contains a pretty_printers
attribute.
Each gdb.Objfile
also contains a pretty_printers
attribute.
Each function on these lists is passed a single gdb.Value
argument and should return a pretty-printer object conforming to the
interface definition above (see section 23.2.2.5 Pretty Printing API). If a function
cannot create a pretty-printer for the value, it should return
None
.
GDB first checks the pretty_printers
attribute of each
gdb.Objfile
in the current program space and iteratively calls
each enabled lookup routine in the list for that gdb.Objfile
until it receives a pretty-printer object.
If no pretty-printer is found in the objfile lists, GDB then
searches the pretty-printer list of the current program space,
calling each enabled function until an object is returned.
After these lists have been exhausted, it tries the global
gdb.pretty_printers
list, again calling each enabled function until an
object is returned.
The order in which the objfiles are searched is not specified. For a given list, functions are always invoked from the head of the list, and iterated over sequentially until the end of the list, or a printer object is returned.
For various reasons a pretty-printer may not work. For example, the underlying data structure may have changed and the pretty-printer is out of date.
The consequences of a broken pretty-printer are severe enough that
GDB provides support for enabling and disabling individual
printers. For example, if print frame-arguments
is on,
a backtrace can become highly illegible if any argument is printed
with a broken printer.
Pretty-printers are enabled and disabled by attaching an enabled
attribute to the registered function or callable object. If this attribute
is present and its value is False
, the printer is disabled, otherwise
the printer is enabled.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A pretty-printer consists of two parts: a lookup function to detect if the type is supported, and the printer itself.
Here is an example showing how a std::string
printer might be
written. See section 23.2.2.5 Pretty Printing API, for details on the API this class
must provide.
class StdStringPrinter(object): "Print a std::string" def __init__(self, val): self.val = val def to_string(self): return self.val['_M_dataplus']['_M_p'] def display_hint(self): return 'string' |
And here is an example showing how a lookup function for the printer example above might be written.
def str_lookup_function(val): lookup_tag = val.type.tag if lookup_tag == None: return None 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.3 Python Auto-loading) such that it
can be evaluated multiple times without changing its meaning. An
ideal auto-load file will consist solely of import
s of your
printer modules, followed by a call to a register pretty-printers with
the current objfile.
Taken as a whole, this approach will scale nicely to multiple inferiors, each potentially using a different library version. Embedding a version number in the Python package name will ensure that GDB is able to load both sets of printers simultaneously. Then, because the search for pretty-printers is done by objfile, and because your auto-loaded code took care to register your library's printers with a specific objfile, GDB will find the correct printers for the specific version of the library used by each inferior.
To continue the std::string
example (see section 23.2.2.5 Pretty Printing API),
this code might appear in gdb.libstdcxx.v6
:
def register_printers(objfile): objfile.pretty_printers.append(str_lookup_function) |
And then the corresponding contents of the auto-load file would be:
import gdb.libstdcxx.v6 gdb.libstdcxx.v6.register_printers(gdb.current_objfile()) |
The previous example illustrates a basic pretty-printer. There are a few things that can be improved on. The printer doesn't have a name, making it hard to identify in a list of installed printers. The lookup function has a name, but lookup functions can have arbitrary, even identical, names.
Second, the printer only handles one type, whereas a library typically has several types. One could install a lookup function for each desired type in the library, but one could also have a single lookup function recognize several types. The latter is the conventional way this is handled. If a pretty-printer can handle multiple data types, then its subprinters are the printers for the individual data types.
The gdb.printing
module provides a formal way of solving these
problems (see section 23.2.4.1 gdb.printing).
Here is another example that handles multiple types.
These are the types we are going to pretty-print:
struct foo { int a, b; }; struct bar { struct foo x, y; }; |
Here are the printers:
class fooPrinter: """Print a foo object.""" def __init__(self, val): self.val = val def to_string(self): return ("a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">") class barPrinter: """Print a bar object.""" def __init__(self, val): self.val = val def to_string(self): return ("x=<" + str(self.val["x"]) + "> y=<" + str(self.val["y"]) + ">") |
This example doesn't need a lookup function, that is handled by the
gdb.printing
module. Instead a function is provided to build up
the object that handles the lookup.
import gdb.printing def build_pretty_printer(): pp = gdb.printing.RegexpCollectionPrettyPrinter( "my_library") pp.add_printer('foo', '^foo$', fooPrinter) pp.add_printer('bar', '^bar$', barPrinter) return pp |
And here is the autoload support:
import gdb.printing import my_library gdb.printing.register_pretty_printer( gdb.current_objfile(), my_library.build_pretty_printer()) |
Finally, when this printer is loaded into GDB, here is the corresponding output of `info pretty-printer':
(gdb) info pretty-printer my_library.so: my_library foo bar |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GDB provides a way for Python code to customize type display. This is mainly useful for substituting canonical typedef names for types.
A type printer is just a Python object conforming to a certain protocol. A simple base class implementing the protocol is provided; see 23.2.4.2 gdb.types. A type printer must supply at least:
enable type-printer
and disable type-printer
commands.
enable type-printer
and disable type-printer
commands.
recognize
method, as described below.
When displaying a type, say via the ptype
command, GDB
will compute a list of type recognizers. This is done by iterating
first over the per-objfile type printers (see section 23.2.2.19 Objfiles In Python),
followed by the per-progspace type printers (see section 23.2.2.18 Program Spaces In Python), and finally the global type printers.
GDB will call the instantiate
method of each enabled
type printer. If this method returns None
, then the result is
ignored; otherwise, it is appended to the list of recognizers.
Then, when GDB is going to display a type name, it iterates
over the list of recognizers. For each one, it calls the recognition
function, stopping if the function returns a non-None
value.
The recognition function is defined as:
None
. Otherwise,
return a string which is to be printed as the name of type.
type will be an instance of gdb.Type
(see section 23.2.2.4 Types In Python).
GDB uses this two-pass approach so that type printers can efficiently cache information without holding on to it too long. For example, it can be convenient to look up type information in a type printer and hold it for a recognizer's lifetime; if a single pass were done then type printers would have to make use of the event system in order to avoid holding information that could become stale as the inferior changed.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Frame filters are Python objects that manipulate the visibility of a frame or frames when a backtrace (see section 8.2 Backtraces) is printed by GDB.
Only commands that print a backtrace, or, in the case of GDB/MI commands (see section 27. The GDB/MI Interface), those that return a collection of frames are affected. The commands that work with frame filters are:
backtrace
(see section The backtrace command),
-stack-list-frames
(see section The -stack-list-frames command),
-stack-list-variables
(see section The -stack-list-variables command), -stack-list-arguments
see section The -stack-list-arguments command) and
-stack-list-locals
(see section The -stack-list-locals command).
A frame filter works by taking an iterator as an argument, applying
actions to the contents of that iterator, and returning another
iterator (or, possibly, the same iterator it was provided in the case
where the filter does not perform any operations). Typically, frame
filters utilize tools such as the Python's itertools
module to
work with and create new iterators from the source iterator.
Regardless of how a filter chooses to apply actions, it must not alter
the underlying GDB frame or frames, or attempt to alter the
call-stack within GDB. This preserves data integrity within
GDB. Frame filters are executed on a priority basis and care
should be taken that some frame filters may have been executed before,
and that some frame filters will be executed after.
An important consideration when designing frame filters, and well worth reflecting upon, is that frame filters should avoid unwinding the call stack if possible. Some stacks can run very deep, into the tens of thousands in some cases. To search every frame when a frame filter executes may be too expensive at that step. The frame filter cannot know how many frames it has to iterate over, and it may have to iterate through them all. This ends up duplicating effort as GDB performs this iteration when it prints the frames. If the filter can defer unwinding frames until frame decorators are executed, after the last filter has executed, it should. See section 23.2.2.10 Decorating Frames., for more information on decorators. Also, there are examples for both frame decorators and filters in later chapters. See section 23.2.2.11 Writing a Frame Filter, for more information.
The Python dictionary gdb.frame_filters
contains key/object
pairings that comprise a frame filter. Frame filters in this
dictionary are called global
frame filters, and they are
available when debugging all inferiors. These frame filters must
register with the dictionary directly. In addition to the
global
dictionary, there are other dictionaries that are loaded
with different inferiors via auto-loading (see section 23.2.3 Python Auto-loading). The two other areas where frame filter dictionaries
can be found are: gdb.Progspace
which contains a
frame_filters
dictionary attribute, and each gdb.Objfile
object which also contains a frame_filters
dictionary
attribute.
When a command is executed from GDB that is compatible with
frame filters, GDB combines the global
,
gdb.Progspace
and all gdb.Objfile
dictionaries currently
loaded. All of the gdb.Objfile
dictionaries are combined, as
several frames, and thus several object files, might be in use.
GDB then prunes any frame filter whose enabled
attribute is False
. This pruned list is then sorted according
to the priority
attribute in each filter.
Once the dictionaries are combined, pruned and sorted, GDB
creates an iterator which wraps each frame in the call stack in a
FrameDecorator
object, and calls each filter in order. The
output from the previous filter will always be the input to the next
filter, and so on.
Frame filters have a mandatory interface which each frame filter must implement, defined here:
For example, if there are four frame filters:
Name Priority Filter1 5 Filter2 10 Filter3 100 Filter4 1 |
The order that the frame filters will be called is:
Filter3 -> Filter2 -> Filter1 -> Filter4 |
Note that the output from Filter3
is passed to the input of
Filter2
, and so on.
This filter
method is passed a Python iterator. This iterator
contains a sequence of frame decorators that wrap each
gdb.Frame
, or a frame decorator that wraps another frame
decorator. The first filter that is executed in the sequence of frame
filters will receive an iterator entirely comprised of default
FrameDecorator
objects. However, after each frame filter is
executed, the previous frame filter may have wrapped some or all of
the frame decorators with their own frame decorator. As frame
decorators must also conform to a mandatory interface, these
decorators can be assumed to act in a uniform manner (see section 23.2.2.10 Decorating Frames.).
This method must return an object conforming to the Python iterator protocol. Each item in the iterator must be an object conforming to the frame decorator interface. If a frame filter does not wish to perform any operations on this iterator, it should return that iterator untouched.
This method is not optional. If it does not exist, GDB will raise and print an error.
name
attribute must be Python string which contains the
name of the filter displayed by GDB (see section 8.3 Management of Frame Filters.). This attribute may contain any combination of letters
or numbers. Care should be taken to ensure that it is unique. This
attribute is mandatory.
enabled
attribute must be Python boolean. This attribute
indicates to GDB whether the frame filter is enabled, and
should be considered when frame filters are executed. If
enabled
is True
, then the frame filter will be executed
when any of the backtrace commands detailed earlier in this chapter
are executed. If enabled
is False
, then the frame
filter will not be executed. This attribute is mandatory.
priority
attribute must be Python integer. This attribute
controls the order of execution in relation to other frame filters.
There are no imposed limits on the range of priority
other than
it must be a valid integer. The higher the priority
attribute,
the sooner the frame filter will be executed in relation to other
frame filters. Although priority
can be negative, it is
recommended practice to assume zero is the lowest priority that a
frame filter can be assigned. Frame filters that have the same
priority are executed in unsorted order in that priority slot. This
attribute is mandatory.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Frame decorators are sister objects to frame filters (see section 23.2.2.9 Filtering Frames.). Frame decorators are applied by a frame filter and can only be used in conjunction with frame filters.
The purpose of a frame decorator is to customize the printed content
of each gdb.Frame
in commands where frame filters are executed.
This concept is called decorating a frame. Frame decorators decorate
a gdb.Frame
with Python code contained within each API call.
This separates the actual data contained in a gdb.Frame
from
the decorated data produced by a frame decorator. This abstraction is
necessary to maintain integrity of the data contained in each
gdb.Frame
.
Frame decorators have a mandatory interface, defined below.
GDB already contains a frame decorator called
FrameDecorator
. This contains substantial amounts of
boilerplate code to decorate the content of a gdb.Frame
. It is
recommended that other frame decorators inherit and extend this
object, and only to override the methods needed.
The elided
method groups frames together in a hierarchical
system. An example would be an interpreter, where multiple low-level
frames make up a single call in the interpreted language. In this
example, the frame filter would elide the low-level frames and present
a single high-level frame, representing the call in the interpreted
language, to the user.
The elided
function must return an iterable and this iterable
must contain the frames that are being elided wrapped in a suitable
frame decorator. If no frames are being elided this function may
return an empty iterable, or None
. Elided frames are indented
from normal frames in a CLI
backtrace, or in the case of
GDB/MI
, are placed in the children
field of the eliding
frame.
It is the frame filter's task to also filter out the elided frames from the source iterator. This will avoid printing the frame twice.
This method returns the name of the function in the frame that is to be printed.
This method must return a Python string describing the function, or
None
.
If this function returns None
, GDB will not print any
data for this field.
This method returns the address of the frame that is to be printed.
This method must return a Python numeric integer type of sufficient
size to describe the address of the frame, or None
.
If this function returns a None
, GDB will not print
any data for this field.
This method returns the filename and path associated with this frame.
This method must return a Python string containing the filename and
the path to the object file backing the frame, or None
.
If this function returns a None
, GDB will not print
any data for this field.
This method returns the line number associated with the current position within the function addressed by this frame.
This method must return a Python integer type, or None
.
If this function returns a None
, GDB will not print
any data for this field.
This method must return an iterable, or None
. Returning an
empty iterable, or None
means frame arguments will not be
printed for this frame. This iterable must contain objects that
implement two methods, described here.
This object must implement a argument
method which takes a
single self
parameter and must return a gdb.Symbol
(see section 23.2.2.22 Python representation of Symbols.), or a Python string. The object must also
implement a value
method which takes a single self
parameter and must return a gdb.Value
(see section 23.2.2.3 Values From Inferior), a Python value, or None
. If the value
method returns None
, and the argument
method returns a
gdb.Symbol
, GDB will look-up and print the value of
the gdb.Symbol
automatically.
A brief example:
class SymValueWrapper(): def __init__(self, symbol, value): self.sym = symbol self.val = value def value(self): return self.val def symbol(self): return self.sym class SomeFrameDecorator() ... ... def frame_args(self): args = [] try: block = self.inferior_frame.block() except: return None # Iterate over all symbols in a block. Only add # symbols that are arguments. for sym in block: if not sym.is_argument: continue args.append(SymValueWrapper(sym,None)) # Add example synthetic argument. args.append(SymValueWrapper(``foo'', 42)) return args |
This method must return an iterable or None
. Returning an
empty iterable, or None
means frame local arguments will not be
printed for this frame.
The object interface, the description of the various strategies for
reading frame locals, and the example are largely similar to those
described in the frame_args
function, (see section The frame filter frame_args function). Below is a modified example:
class SomeFrameDecorator() ... ... def frame_locals(self): vars = [] try: block = self.inferior_frame.block() except: return None # Iterate over all symbols in a block. Add all # symbols, except arguments. for sym in block: if sym.is_argument: continue vars.append(SymValueWrapper(sym,None)) # Add an example of a synthetic local variable. vars.append(SymValueWrapper(``bar'', 99)) return vars |
This method must return the underlying gdb.Frame
that this
frame decorator is decorating. GDB requires the underlying
frame for internal frame information to determine how to print certain
values when printing a frame.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There are three basic elements that a frame filter must implement: it must correctly implement the documented interface (see section 23.2.2.9 Filtering Frames.), it must register itself with GDB, and finally, it must decide if it is to work on the data provided by GDB. In all cases, whether it works on the iterator or not, each frame filter must return an iterator. A bare-bones frame filter follows the pattern in the following example.
import gdb class FrameFilter(): def __init__(self): # Frame filter attribute creation. # # 'name' is the name of the filter that GDB will display. # # 'priority' is the priority of the filter relative to other # filters. # # 'enabled' is a boolean that indicates whether this filter is # enabled and should be executed. self.name = "Foo" self.priority = 100 self.enabled = True # Register this frame filter with the global frame_filters # dictionary. gdb.frame_filters[self.name] = self def filter(self, frame_iter): # Just return the iterator. return frame_iter |
The frame filter in the example above implements the three requirements for all frame filters. It implements the API, self registers, and makes a decision on the iterator (in this case, it just returns the iterator untouched).
The first step is attribute creation and assignment, and as shown in
the comments the filter assigns the following attributes: name
,
priority
and whether the filter should be enabled with the
enabled
attribute.
The second step is registering the frame filter with the dictionary or
dictionaries that the frame filter has interest in. As shown in the
comments, this filter just registers itself with the global dictionary
gdb.frame_filters
. As noted earlier, gdb.frame_filters
is a dictionary that is initialized in the gdb
module when
GDB starts. What dictionary a filter registers with is an
important consideration. Generally, if a filter is specific to a set
of code, it should be registered either in the objfile
or
progspace
dictionaries as they are specific to the program
currently loaded in GDB. The global dictionary is always
present in GDB and is never unloaded. Any filters registered
with the global dictionary will exist until GDB exits. To
avoid filters that may conflict, it is generally better to register
frame filters against the dictionaries that more closely align with
the usage of the filter currently in question. See section 23.2.3 Python Auto-loading, for further information on auto-loading Python scripts.
GDB takes a hands-off approach to frame filter registration,
therefore it is the frame filter's responsibility to ensure
registration has occurred, and that any exceptions are handled
appropriately. In particular, you may wish to handle exceptions
relating to Python dictionary key uniqueness. It is mandatory that
the dictionary key is the same as frame filter's name
attribute. When a user manages frame filters (see section 8.3 Management of Frame Filters.), the names GDB will display are those contained
in the name
attribute.
The final step of this example is the implementation of the
filter
method. As shown in the example comments, we define the
filter
method and note that the method must take an iterator,
and also must return an iterator. In this bare-bones example, the
frame filter is not very useful as it just returns the iterator
untouched. However this is a valid operation for frame filters that
have the enabled
attribute set, but decide not to operate on
any frames.
In the next example, the frame filter operates on all frames and utilizes a frame decorator to perform some work on the frames. See section 23.2.2.10 Decorating Frames., for further information on the frame decorator interface.
This example works on inlined frames. It highlights frames which are
inlined by tagging them with an "[inlined]" tag. By applying a
frame decorator to all frames with the Python itertools imap
method, the example defers actions to the frame decorator. Frame
decorators are only processed when GDB prints the backtrace.
This introduces a new decision making topic: whether to perform decision making operations at the filtering step, or at the printing step. In this example's approach, it does not perform any filtering decisions at the filtering step beyond mapping a frame decorator to each frame. This allows the actual decision making to be performed when each frame is printed. This is an important consideration, and well worth reflecting upon when designing a frame filter. An issue that frame filters should avoid is unwinding the stack if possible. Some stacks can run very deep, into the tens of thousands in some cases. To search every frame to determine if it is inlined ahead of time may be too expensive at the filtering step. The frame filter cannot know how many frames it has to iterate over, and it would have to iterate through them all. This ends up duplicating effort as GDB performs this iteration when it prints the frames.
In this example decision making can be deferred to the printing step. As each frame is printed, the frame decorator can examine each frame in turn when GDB iterates. From a performance viewpoint, this is the most appropriate decision to make as it avoids duplicating the effort that the printing step would undertake anyway. Also, if there are many frame filters unwinding the stack during filtering, it can substantially delay the printing of the backtrace which will result in large memory usage, and a poor user experience.
class InlineFilter(): def __init__(self): self.name = "InlinedFrameFilter" self.priority = 100 self.enabled = True gdb.frame_filters[self.name] = self def filter(self, frame_iter): frame_iter = itertools.imap(InlinedFrameDecorator, frame_iter) return frame_iter |
This frame filter is somewhat similar to the earlier example, except
that the filter
method applies a frame decorator object called
InlinedFrameDecorator
to each element in the iterator. The
imap
Python method is light-weight. It does not proactively
iterate over the iterator, but rather creates a new iterator which
wraps the existing one.
Below is the frame decorator for this example.
class InlinedFrameDecorator(FrameDecorator): def __init__(self, fobj): super(InlinedFrameDecorator, self).__init__(fobj) def function(self): frame = fobj.inferior_frame() name = str(frame.name()) if frame.type() == gdb.INLINE_FRAME: name = name + " [inlined]" return name |
This frame decorator only defines and overrides the function
method. It lets the supplied FrameDecorator
, which is shipped
with GDB, perform the other work associated with printing
this frame.
The combination of these two objects create this output from a backtrace:
#0 0x004004e0 in bar () at inline.c:11 #1 0x00400566 in max [inlined] (b=6, a=12) at inline.c:21 #2 0x00400566 in main () at inline.c:31 |
So in the case of this example, a frame decorator is applied to all
frames, regardless of whether they may be inlined or not. As
GDB iterates over the iterator produced by the frame filters,
GDB executes each frame decorator which then makes a decision
on what to print in the function
callback. Using a strategy
like this is a way to defer decisions on the frame content to printing
time.
It might be that the above example is not desirable for representing
inlined frames, and a hierarchical approach may be preferred. If we
want to hierarchically represent frames, the elided
frame
decorator interface might be preferable.
This example approaches the issue with the elided
method. This
example is quite long, but very simplistic. It is out-of-scope for
this section to write a complete example that comprehensively covers
all approaches of finding and printing inlined frames. However, this
example illustrates the approach an author might use.
This example comprises of three sections.
class InlineFrameFilter(): def __init__(self): self.name = "InlinedFrameFilter" self.priority = 100 self.enabled = True gdb.frame_filters[self.name] = self def filter(self, frame_iter): return ElidingInlineIterator(frame_iter) |
This frame filter is very similar to the other examples. The only
difference is this frame filter is wrapping the iterator provided to
it (frame_iter
) with a custom iterator called
ElidingInlineIterator
. This again defers actions to when
GDB prints the backtrace, as the iterator is not traversed
until printing.
The iterator for this example is as follows. It is in this section of the example where decisions are made on the content of the backtrace.
class ElidingInlineIterator: def __init__(self, ii): self.input_iterator = ii def __iter__(self): return self def next(self): frame = next(self.input_iterator) if frame.inferior_frame().type() != gdb.INLINE_FRAME: return frame try: eliding_frame = next(self.input_iterator) except StopIteration: return frame return ElidingFrameDecorator(eliding_frame, [frame]) |
This iterator implements the Python iterator protocol. When the
next
function is called (when GDB prints each frame),
the iterator checks if this frame decorator, frame
, is wrapping
an inlined frame. If it is not, it returns the existing frame decorator
untouched. If it is wrapping an inlined frame, it assumes that the
inlined frame was contained within the next oldest frame,
eliding_frame
, which it fetches. It then creates and returns a
frame decorator, ElidingFrameDecorator
, which contains both the
elided frame, and the eliding frame.
class ElidingInlineDecorator(FrameDecorator): def __init__(self, frame, elided_frames): super(ElidingInlineDecorator, self).__init__(frame) self.frame = frame self.elided_frames = elided_frames def elided(self): return iter(self.elided_frames) |
This frame decorator overrides one function and returns the inlined
frame in the elided
method. As before it lets
FrameDecorator
do the rest of the work involved in printing
this frame. This produces the following output.
#0 0x004004e0 in bar () at inline.c:11 #2 0x00400529 in main () at inline.c:25 #1 0x00400529 in max (b=6, a=12) at inline.c:15 |
In that output, max
which has been inlined into main
is
printed hierarchically. Another approach would be to combine the
function
method, and the elided
method to both print a
marker in the inlined frame, and also show the hierarchical
relationship.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Programs which are being run under GDB are called inferiors
(see section 4.9 Debugging Multiple Inferiors and Programs). Python scripts can access
information about and manipulate inferiors controlled by GDB
via objects of the gdb.Inferior
class.
The following inferior-related functions are available in the gdb
module:
A gdb.Inferior
object has the following attributes:
A gdb.Inferior
object has the following methods:
True
if the gdb.Inferior
object is valid,
False
if not. A gdb.Inferior
object will become invalid
if the inferior no longer exists within GDB. All other
gdb.Inferior
methods will throw an exception if it is invalid
at the time the method is called.
Inferior.write_memory
function. In Python
3, the return
value is a memoryview
object.
Inferior.read_memory
. If given, length
determines the number of bytes from buffer to be written.
gdb.read_memory
. Returns a Python Long
containing the address where the pattern was found, or None
if
the pattern could not be found.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GDB provides a general event facility so that Python code can be notified of various state changes, particularly changes that occur in the inferior.
An event is just an object that describes some state change. The type of the object and its attributes will vary depending on the details of the change. All the existing events are described below.
In order to be notified of an event, you must register an event handler
with an event registry. An event registry is an object in the
gdb.events
module which dispatches particular events. A registry
provides methods to register and unregister event handlers:
Here is an example:
def exit_handler (event): print "event type: exit" print "exit code: %d" % (event.exit_code) gdb.events.exited.connect (exit_handler) |
In the above example we connect our handler exit_handler
to the
registry events.exited
. Once connected, exit_handler
gets
called when the inferior exits. The argument event in this example is
of type gdb.ExitedEvent
. As you can see in the example the
ExitedEvent
object has an attribute which indicates the exit code of
the inferior.
The following is a listing of the event registries that are available and details of the events they emit:
events.cont
gdb.ThreadEvent
.
Some events can be thread specific when GDB is running in non-stop
mode. When represented in Python, these events all extend
gdb.ThreadEvent
. Note, this event is not emitted directly; instead,
events which are emitted by this or other modules might extend this event.
Examples of these events are gdb.BreakpointEvent
and
gdb.ContinueEvent
.
None
.
Emits gdb.ContinueEvent
which extends gdb.ThreadEvent
.
This event indicates that the inferior has been continued after a stop. For
inherited attribute refer to gdb.ThreadEvent
above.
events.exited
events.ExitedEvent
which indicates that the inferior has exited.
events.ExitedEvent
has two attributes:
exited
event.
events.stop
gdb.StopEvent
which extends gdb.ThreadEvent
.
Indicates that the inferior has stopped. All events emitted by this registry
extend StopEvent. As a child of gdb.ThreadEvent
, gdb.StopEvent
will indicate the stopped thread when GDB is running in non-stop
mode. Refer to gdb.ThreadEvent
above for more details.
Emits gdb.SignalEvent
which extends gdb.StopEvent
.
This event indicates that the inferior or one of its threads has received as
signal. gdb.SignalEvent
has the following attributes:
info signals
in
the GDB command prompt.
Also emits gdb.BreakpointEvent
which extends gdb.StopEvent
.
gdb.BreakpointEvent
event indicates that one or more breakpoints have
been hit, and has the following attributes:
gdb.Breakpoint
) that were hit.
See section 23.2.2.25 Manipulating breakpoints using Python, for details of the gdb.Breakpoint
object.
gdb.BreakpointEvent.breakpoints
attribute.
events.new_objfile
gdb.NewObjFileEvent
which indicates that a new object file has
been loaded by GDB. gdb.NewObjFileEvent
has one attribute:
gdb.Objfile
) which has been loaded.
See section 23.2.2.19 Objfiles In Python, for details of the gdb.Objfile
object.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Python scripts can access information about, and manipulate inferior threads
controlled by GDB, via objects of the gdb.InferiorThread
class.
The following thread-related functions are available in the gdb
module:
None
.
A gdb.InferiorThread
object has the following attributes:
thread name
, then this returns that name. Otherwise, if an
OS-supplied name is available, then it is returned. Otherwise, this
returns None
.
This attribute can be assigned to. The new value must be a string
object, which sets the new name, or None
, which removes any
user-specified thread name.
A gdb.InferiorThread
object has the following methods:
True
if the gdb.InferiorThread
object is valid,
False
if not. A gdb.InferiorThread
object will become
invalid if the thread exits, or the inferior that the thread belongs
is deleted. All other gdb.InferiorThread
methods will throw an
exception if it is invalid at the time the method is called.
[ < ] | [ > ] | [ << ] | [ 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.
To break argument up into an argv-like string use
gdb.string_to_argv
. This function behaves identically to
GDB's internal argument lexer buildargv
.
It is recommended to use this for consistency.
Arguments are separated by spaces and may be quoted.
Example:
print gdb.string_to_argv ("1 2\ \\\"3 '4 \"5' \"6 '7\"") ['1', '2 "3', '4 "5', "6 '7"] |
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:
gdb.COMMAND_NONE
gdb.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.
gdb.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.
gdb.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.
gdb.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.
gdb.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.
gdb.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.
gdb.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.
gdb.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.
gdb.COMMAND_USER
gdb.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.
gdb.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:
gdb.COMPLETE_NONE
gdb.COMPLETE_FILENAME
gdb.COMPLETE_LOCATION
gdb.COMPLETE_COMMAND
gdb.COMPLETE_SYMBOL
gdb.COMPLETE_EXPRESSION
The following code snippet shows how a trivial CLI command can be implemented in Python:
class HelloWorld (gdb.Command): """Greet the whole world.""" def __init__ (self): super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER) def invoke (self, arg, from_tty): print "Hello, World!" HelloWorld () |
The last line instantiates the class, and is necessary to trigger the
registration of the command with GDB. Depending on how the
Python code is read into GDB, you may need to import the
gdb
module explicitly.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can implement new GDB parameters using Python. A new
parameter is implemented as an instance of the gdb.Parameter
class.
Parameters are exposed to the user via the set
and
show
commands. See section 3.3 Getting Help.
There are many parameters that already exist and can be set in
GDB. Two examples are: set follow fork
and
set charset
. Setting these parameters influences certain
behavior in GDB. Similarly, you can define parameters that
can be used to influence behavior in custom Python scripts and commands.
Parameter
registers the new
parameter with GDB. This initializer is normally invoked
from the subclass' own __init__
method.
name is the name of the new parameter. If name consists
of multiple words, then the initial words are looked for as prefix
parameters. An example of this can be illustrated with the
set print
set of parameters. If name is
print foo
, then print
will be searched as the prefix
parameter. In this case the parameter can subsequently be accessed in
GDB as set print foo
.
If name consists of multiple words, and no prefix parameter group can be found, an exception is raised.
command-class should be one of the `COMMAND_' constants (see section 23.2.2.15 Commands In Python). This argument tells GDB how to categorize the new parameter in the help system.
parameter-class should be one of the `PARAM_' constants defined below. This argument tells GDB the type of the new parameter; this information is used for input validation and completion.
If parameter-class is PARAM_ENUM
, then
enum-sequence must be a sequence of strings. These strings
represent the possible values for the parameter.
If parameter-class is not PARAM_ENUM
, then the presence
of a fourth argument will cause an exception to be thrown.
The help text for the new parameter is taken from the Python documentation string for the parameter's class, if there is one. If there is no documentation string, a default value is used.
set
command. The value is
examined when Parameter.__init__
is invoked; subsequent changes
have no effect.
show
command. The value is
examined when Parameter.__init__
is invoked; subsequent changes
have no effect.
value
attribute holds the underlying value of the
parameter. It can be read and assigned to just as any other
attribute. GDB does validation when assignments are made.
There are two methods that should be implemented in any
Parameter
class. These are:
set
API (for example, set foo off).
The value
attribute has already been populated with the new
value and may be used in output. This method must return a string.
show
API has been invoked (for example, show foo). The
argument svalue
receives the string representation of the
current value. This method must return a string.
When a new parameter is defined, its type must be specified. The
available types are represented by constants defined in the gdb
module:
gdb.PARAM_BOOLEAN
True
and False
are the only valid values.
gdb.PARAM_AUTO_BOOLEAN
None
.
gdb.PARAM_UINTEGER
gdb.PARAM_INTEGER
gdb.PARAM_STRING
gdb.PARAM_STRING_NOESCAPE
gdb.PARAM_OPTIONAL_FILENAME
None
.
gdb.PARAM_FILENAME
PARAM_STRING_NOESCAPE
, but uses file names for completion.
gdb.PARAM_ZINTEGER
PARAM_INTEGER
, except 0
is interpreted as itself.
gdb.PARAM_ENUM
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can implement new convenience functions (see section 10.11 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.
Now you can use the function in an expression:
(gdb) print $greet("Bob") $1 = "Hello, Bob!" |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A program space, or progspace, represents a symbolic view of an address space. It consists of all of the objfiles of the program. See section 23.2.2.19 Objfiles In Python. See section program spaces, for more details about program spaces.
The following progspace-related functions are available in the
gdb
module:
Each progspace is represented by an instance of the gdb.Progspace
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.5 Pretty Printing API, for more
information.
type_printers
attribute is a list of type printer objects.
See section 23.2.2.8 Type Printing API, for more information.
frame_filters
attribute is a dictionary of frame filter
objects. See section 23.2.2.9 Filtering Frames., for more information.
[ < ] | [ > ] | [ << ] | [ 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.5 Pretty Printing API, for more
information.
type_printers
attribute is a list of type printer objects.
See section 23.2.2.8 Type Printing API, for more information.
frame_filters
attribute is a dictionary of frame filter
objects. See section 23.2.2.9 Filtering Frames., for more information.
A gdb.Objfile
object has the following methods:
True
if the gdb.Objfile
object is valid,
False
if not. A gdb.Objfile
object can become invalid
if the object file it refers to is not loaded in GDB any
longer. All other gdb.Objfile
methods will throw an exception
if it is invalid at the time the method is called.
[ < ] | [ > ] | [ << ] | [ 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 gdb.error
exception (see section 23.2.2.2 Exception Handling).
Two gdb.Frame
objects can be compared for equality with the ==
operator, like:
(gdb) python print gdb.newest_frame() == gdb.selected_frame () True |
The following frame-related functions are available in the gdb
module:
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.Architecture
object corresponding to the frame's
architecture. See section 23.2.2.28 Python representation of architectures.
gdb.NORMAL_FRAME
gdb.DUMMY_FRAME
gdb.INLINE_FRAME
gdb.NORMAL_FRAME
that is older than this one.
gdb.TAILCALL_FRAME
gdb.SIGTRAMP_FRAME
gdb.ARCH_FRAME
gdb.SENTINEL_FRAME
gdb.NORMAL_FRAME
, but it is only used for the
newest frame.
gdb.frame_stop_reason_string
to convert the value returned by this
function to a string. The value can be one of:
gdb.FRAME_UNWIND_NO_REASON
gdb.FRAME_UNWIND_NULL_ID
gdb.FRAME_UNWIND_OUTERMOST
gdb.FRAME_UNWIND_UNAVAILABLE
gdb.FRAME_UNWIND_INNER_ID
gdb.FRAME_UNWIND_SAME_ID
gdb.FRAME_UNWIND_NO_SAVED_PC
gdb.FRAME_UNWIND_FIRST_ERROR
reason = gdb.selected_frame().unwind_stop_reason () reason_str = gdb.frame_stop_reason_string (reason) if reason >= gdb.FRAME_UNWIND_FIRST_ERROR: print "An error occured: %s" % reason_str |
gdb.Symbol
object. block must be a
gdb.Block
object.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In GDB, symbols are stored in blocks. A block corresponds
roughly to a scope in the source code. Blocks are organized
hierarchically, and are represented individually in Python as a
gdb.Block
. Blocks rely on debugging information being
available.
A frame has a block. Please see 23.2.2.20 Accessing inferior stack frames from Python., for a more in-depth discussion of frames.
The outermost block is known as the global block. The global block typically holds public global variables and functions.
The block nested just inside the global block is the static block. The static block typically holds file-scoped variables and functions.
GDB provides a method to get a block's superblock, but there is currently no way to examine the sub-blocks of a block, or to iterate over all the blocks in a symbol table (see section 23.2.2.23 Symbol table representation in Python.).
Here is a short example that should help explain blocks:
/* This is in the global block. */ int global; /* This is in the static block. */ static int file_scope; /* 'function' is in the global block, and 'argument' is in a block nested inside of 'function'. */ int function (int argument) { /* 'local' is in a block inside 'function'. It may or may not be in the same block as 'argument'. */ int local; { /* 'inner' is in a block whose superblock is the one holding 'local'. */ int inner; /* If this call is expanded by the compiler, you may see a nested block here whose function is 'inline_function' and whose superblock is the one holding 'inner'. */ inline_function (); } } |
A gdb.Block
is iterable. The iterator returns the symbols
(see section 23.2.2.22 Python representation of Symbols.) local to the block. Python programs
should not assume that a specific block object will always contain a
given symbol, since changes in GDB features and
infrastructure may cause symbols move across blocks in a symbol
table.
The following block-related functions are available in the gdb
module:
gdb.Block
containing the given pc
value. If the block cannot be found for the pc value specified,
the function will return None
.
A gdb.Block
object has the following methods:
True
if the gdb.Block
object is valid,
False
if not. A block object can become invalid if the block it
refers to doesn't exist anymore in the inferior. All other
gdb.Block
methods will throw an exception if it is invalid at
the time the method is called. The block's validity is also checked
during iteration over symbols of the block.
A gdb.Block
object has the following attributes:
gdb.Symbol
. If the
block is not named, then this attribute holds None
. This
attribute is not writable.
For ordinary function blocks, the superblock is the static block. However, you should note that it is possible for a function block to have a superblock that is not the static block -- for instance this happens for an inlined function.
None
. This attribute is not writable.
True
if the gdb.Block
object is a global block,
False
if not. This attribute is not
writable.
True
if the gdb.Block
object is a static block,
False
if not. This attribute is not writable.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GDB represents every variable, function and type as an
entry in a symbol table. See section Examining the Symbol Table.
Similarly, Python represents these symbols in GDB with the
gdb.Symbol
object.
The following symbol-related functions are available in the gdb
module:
name is the name of the symbol. It must be a string. The
optional block argument restricts the search to symbols visible
in that block. The block argument must be a
gdb.Block
object. If omitted, the block for the current frame
is used. The optional domain argument restricts
the search to the domain type. The domain argument must be a
domain constant defined in the gdb
module and described later
in this chapter.
The result is a tuple of two elements.
The first element is a gdb.Symbol
object or None
if the symbol
is not found.
If the symbol is found, the second element is True
if the symbol
is a field of a method's object (e.g., this
in C++),
otherwise it is False
.
If the symbol is not found, the second element is False
.
name is the name of the symbol. It must be a string.
The optional domain argument restricts the search to the domain type.
The domain argument must be a domain constant defined in the gdb
module and described later in this chapter.
The result is a gdb.Symbol
object or None
if the symbol
is not found.
A gdb.Symbol
object has the following attributes:
None
if no type is recorded.
This attribute is represented as a gdb.Type
object.
See section 23.2.2.4 Types In Python. This attribute is not writable.
gdb.Symtab
object. See section 23.2.2.23 Symbol table representation in Python.. This attribute is not writable.
name
or linkage_name
, depending on whether the user
asked GDB to display demangled or mangled names.
gdb
module and described later in this chapter.
True
if evaluating this symbol's value requires a frame
(see section 23.2.2.20 Accessing inferior stack frames from Python.) and False
otherwise. Typically,
local variables will require a frame, but other symbols will not.
True
if the symbol is an argument of a function.
True
if the symbol is a constant.
True
if the symbol is a function or a method.
True
if the symbol is a variable.
A gdb.Symbol
object has the following methods:
True
if the gdb.Symbol
object is valid,
False
if not. A gdb.Symbol
object can become invalid if
the symbol it refers to does not exist in GDB any longer.
All other gdb.Symbol
methods will throw an exception if it is
invalid at the time the method is called.
gdb.Value
. For
functions, this computes the address of the function, cast to the
appropriate type. If the symbol requires a frame in order to compute
its value, then frame must be given. If frame is not
given, or if frame is invalid, then this method will throw an
exception.
The available domain categories in gdb.Symbol
are represented
as constants in the gdb
module:
gdb.SYMBOL_UNDEF_DOMAIN
gdb.SYMBOL_VAR_DOMAIN
gdb.SYMBOL_STRUCT_DOMAIN
gdb.SYMBOL_LABEL_DOMAIN
gdb.SYMBOL_VARIABLES_DOMAIN
SYMBOLS_VAR_DOMAIN
; it
contains everything minus functions and types.
gdb.SYMBOL_FUNCTION_DOMAIN
gdb.SYMBOL_TYPES_DOMAIN
The available address class categories in gdb.Symbol
are represented
as constants in the gdb
module:
gdb.SYMBOL_LOC_UNDEF
gdb.SYMBOL_LOC_CONST
gdb.SYMBOL_LOC_STATIC
gdb.SYMBOL_LOC_REGISTER
gdb.SYMBOL_LOC_ARG
gdb.SYMBOL_LOC_REF_ARG
LOC_ARG
except that the value's address is stored at the
offset, not the value itself.
gdb.SYMBOL_LOC_REGPARM_ADDR
LOC_REGISTER
except
the register holds the address of the argument instead of the argument
itself.
gdb.SYMBOL_LOC_LOCAL
gdb.SYMBOL_LOC_TYPEDEF
SYMBOL_STRUCT_DOMAIN
all
have this class.
gdb.SYMBOL_LOC_BLOCK
gdb.SYMBOL_LOC_CONST_BYTES
gdb.SYMBOL_LOC_UNRESOLVED
gdb.SYMBOL_LOC_OPTIMIZED_OUT
gdb.SYMBOL_LOC_COMPUTED
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Access to symbol table data maintained by GDB on the inferior
is exposed to Python via two objects: gdb.Symtab_and_line
and
gdb.Symtab
. Symbol table and line data for a frame is returned
from the find_sal
method in gdb.Frame
object.
See section 23.2.2.20 Accessing inferior stack frames from Python..
For more information on GDB's symbol table management, see Examining the Symbol Table, for more information.
A gdb.Symtab_and_line
object has the following attributes:
gdb.Symtab
) for this frame.
This attribute is not writable.
A gdb.Symtab_and_line
object has the following methods:
True
if the gdb.Symtab_and_line
object is valid,
False
if not. A gdb.Symtab_and_line
object can become
invalid if the Symbol table and line object it refers to does not
exist in GDB any longer. All other
gdb.Symtab_and_line
methods will throw an exception if it is
invalid at the time the method is called.
A gdb.Symtab
object has the following attributes:
A gdb.Symtab
object has the following methods:
True
if the gdb.Symtab
object is valid,
False
if not. A gdb.Symtab
object can become invalid if
the symbol table it refers to does not exist in GDB any
longer. All other gdb.Symtab
methods will throw an exception
if it is invalid at the time the method is called.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Python code can request and inspect line table information from a
symbol table that is loaded in GDB. A line table is a
mapping of source lines to their executable locations in memory. To
acquire the line table information for a particular symbol table, use
the linetable
function (see section 23.2.2.23 Symbol table representation in Python.).
A gdb.LineTable
is iterable. The iterator returns
LineTableEntry
objects that correspond to the source line and
address for each line table entry. LineTableEntry
objects have
the following attributes:
As there can be multiple addresses for a single source line, you may
receive multiple LineTableEntry
objects with matching
line
attributes, but with different pc
attributes. The
iterator is sorted in ascending pc
order. Here is a small
example illustrating iterating over a line table.
symtab = gdb.selected_frame().find_sal().symtab linetable = symtab.linetable() for line in linetable: print "Line: "+str(line.line)+" Address: "+hex(line.pc) |
This will have the following output:
Line: 33 Address: 0x4005c8L Line: 37 Address: 0x4005caL Line: 39 Address: 0x4005d2L Line: 40 Address: 0x4005f8L Line: 42 Address: 0x4005ffL Line: 44 Address: 0x400608L Line: 42 Address: 0x40060cL Line: 45 Address: 0x400615L |
In addition to being able to iterate over a LineTable
, it also
has the following direct access methods:
Tuple
of LineTableEntry
objects for any
entries in the line table for the given line. line refers
to the source code line. If there are no entries for that source code
line, the Python None
is returned.
Boolean
indicating whether there is an entry in
the line table for this source line. Return True
if an entry
is found, or False
if not.
List
of the source line numbers in the symbol
table. Only lines with executable code locations are returned. The
contents of the List
will just be the source line entries
represented as Python Long
values.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Python code can manipulate breakpoints via the gdb.Breakpoint
class.
break
command,
or in the case of a watchpoint, by the watch
command. The
optional type denotes the breakpoint to create from the types
defined later in this chapter. This argument can be either:
gdb.BP_BREAKPOINT
or gdb.BP_WATCHPOINT
. type
defaults to gdb.BP_BREAKPOINT
. The optional internal
argument allows the breakpoint to become invisible to the user. The
breakpoint will neither be reported when created, nor will it be
listed in the output from info breakpoints
(but will be listed
with the maint info breakpoints
command). The optional
temporary argument makes the breakpoint a temporary breakpoint.
Temporary breakpoints are deleted after they have been hit. Any
further access to the Python breakpoint after it has been hit will
result in a runtime error (as that breakpoint has now been
automatically deleted). The optional wp_class argument defines
the class of watchpoint to create, if type is
gdb.BP_WATCHPOINT
. If a watchpoint class is not provided, it
is assumed to be a gdb.WP_WRITE
class.
gdb.Breakpoint
class can be sub-classed and, in
particular, you may choose to implement the stop
method.
If this method is defined in a sub-class of gdb.Breakpoint
,
it will be called when the inferior reaches any location of a
breakpoint which instantiates that sub-class. If the method returns
True
, the inferior will be stopped at the location of the
breakpoint, otherwise the inferior will continue.
If there are multiple breakpoints at the same location with a
stop
method, each one will be called regardless of the
return status of the previous. This ensures that all stop
methods have a chance to execute at that location. In this scenario
if one of the methods returns True
but the others return
False
, the inferior will still be stopped.
You should not alter the execution state of the inferior (i.e., step, next, etc.), alter the current frame context (i.e., change the current active frame), or alter, add or delete any breakpoint. As a general rule, you should not alter any data within GDB or the inferior at this time.
Example stop
implementation:
class MyBreakpoint (gdb.Breakpoint): def stop (self): inf_val = gdb.parse_and_eval("foo") if inf_val == 3: return True return False |
The available watchpoint types represented by constants are defined in the
gdb
module:
gdb.WP_READ
gdb.WP_WRITE
gdb.WP_ACCESS
True
if this Breakpoint
object is valid,
False
otherwise. A Breakpoint
object can become invalid
if the user deletes the breakpoint. In this case, the object still
exists, but the underlying breakpoint does not. In the cases of
watchpoint scope, the watchpoint remains valid even if execution of the
inferior leaves the scope of that watchpoint.
Breakpoint
object. Any further access
to this object's attributes or methods will raise an error.
True
if the breakpoint is enabled, and
False
otherwise. This attribute is writable.
True
if the breakpoint is silent, and
False
otherwise. This attribute is writable.
Note that a breakpoint can also be silent if it has commands and the
first command is silent
. This is not reported by the
silent
attribute.
None
. This attribute is writable.
None
. This attribute
is writable.
is_valid
function, will result in an error after the breakpoint has been hit
(as it has been automatically deleted). This attribute is not
writable.
The available types are represented by constants defined in the gdb
module:
gdb.BP_BREAKPOINT
gdb.BP_WATCHPOINT
gdb.BP_HARDWARE_WATCHPOINT
gdb.BP_READ_WATCHPOINT
gdb.BP_ACCESS_WATCHPOINT
None
. This
attribute is not writable.
None
. This attribute is not writable.
None
. This attribute is writable.
None
. This attribute is not writable.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A finish breakpoint is a temporary breakpoint set at the return address of
a frame, based on the finish
command. gdb.FinishBreakpoint
extends gdb.Breakpoint
. The underlying breakpoint will be disabled
and deleted when the execution will run out of the breakpoint scope (i.e.
Breakpoint.stop
or FinishBreakpoint.out_of_scope
triggered).
Finish breakpoints are thread specific and must be create with the right
thread selected.
gdb.Frame
object frame. If frame is not provided, this defaults to the
newest frame. The optional internal argument allows the breakpoint to
become invisible to the user. See section 23.2.2.25 Manipulating breakpoints using Python, for further
details about this argument.
longjmp
, C++ exceptions, GDB
return
command, ...), a function may not properly terminate, and
thus never hit the finish breakpoint. When GDB notices such a
situation, the out_of_scope
callback will be triggered.
You may want to sub-class gdb.FinishBreakpoint
and override this
method:
class MyFinishBreakpoint (gdb.FinishBreakpoint) def stop (self): print "normal finish" return True def out_of_scope (): print "abnormal finish" |
gdb.FinishBreakpoint
object had debug symbols, this
attribute will contain a gdb.Value
object corresponding to the return
value of the function. The value will be None
if the function return
type is void
or if the return value was not computable. This attribute
is not writable.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A lazy string is a string whose contents is not retrieved or encoded until it is needed.
A gdb.LazyString
is represented in GDB as an
address
that points to a region of memory, an encoding
that will be used to encode that region of memory, and a length
to delimit the region of memory that represents the string. The
difference between a gdb.LazyString
and a string wrapped within
a gdb.Value
is that a gdb.LazyString
will be treated
differently by GDB when printing. A gdb.LazyString
is
retrieved and encoded during printing, while a gdb.Value
wrapping a string is immediately retrieved and encoded on creation.
A gdb.LazyString
object has the following functions:
gdb.LazyString
to a gdb.Value
. This value
will point to the string in memory, but will lose all the delayed
retrieval, encoding and handling that GDB applies to a
gdb.LazyString
.
target
method. See section 23.2.2.4 Types In Python. This attribute is not
writable.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GDB uses architecture specific parameters and artifacts in a
number of its various computations. An architecture is represented
by an instance of the gdb.Architecture
class.
A gdb.Architecture
class has the following methods:
dict
with the following string keys:
addr
asm
disassembly-flavor
. See section 9.6 Source and Machine Code.
length
[ < ] | [ > ] | [ << ] | [ 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 Python support scripts in several ways:
`objfile-gdb.py' and .debug_gdb_scripts
section.
See section 23.3 Auto-loading extensions.
The auto-loading feature is useful for supplying application-specific debugging commands and scripts.
Auto-loading can be enabled or disabled, and the list of auto-loaded scripts can be printed.
set auto-load python-scripts [on|off]
show auto-load python-scripts
info auto-load python-scripts [regexp]
Also printed is the list of Python scripts that were mentioned in
the .debug_gdb_scripts
section and were not found
(see section 23.3.2 The .debug_gdb_scripts
section).
This is useful because their names are not printed when GDB
tries to load them and fails. There may be many of them, and printing
an error message for each one is problematic.
If regexp is supplied only Python scripts with matching names are printed.
Example:
(gdb) info auto-load python-scripts Loaded Script Yes py-section-script.py full name: /tmp/py-section-script.py No my-foo-pretty-printers.py |
When reading an auto-loaded file, GDB sets the
current objfile. This is available via the gdb.current_objfile
function (see section 23.2.2.19 Objfiles In Python). This can be useful for
registering objfile-specific pretty-printers and frame-filters.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GDB comes with several modules to assist writing Python code.
23.2.4.1 gdb.printing Building and registering pretty-printers. 23.2.4.2 gdb.types Utilities for working with types. 23.2.4.3 gdb.prompt Utilities for prompt value substitution.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This module provides a collection of utilities for working with pretty-printers.
PrettyPrinter (name, subprinters=None)
SubPrettyPrinter (name)
RegexpCollectionPrettyPrinter (name)
FlagEnumerationPrinter (name)
enum
values. Unlike
GDB's built-in enum
printing, this printer attempts to
work properly when there is some overlap between the enumeration
constants. name is the name of the printer and also the name of
the enum
type to look up.
register_pretty_printer (obj, printer, replace=False)
True
then any existing copy of the printer
is replaced. Otherwise a RuntimeError
exception is raised
if a printer with the same name already exists.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This module provides a collection of utilities for working with
gdb.Type
objects.
get_basic_type (type)
C++ example:
typedef const int const_int; const_int foo (3); const_int& foo_ref (foo); int main () { return 0; } |
Then in gdb:
(gdb) start (gdb) python import gdb.types (gdb) python foo_ref = gdb.parse_and_eval("foo_ref") (gdb) python print gdb.types.get_basic_type(foo_ref.type) int |
has_field (type, field)
True
if type, assumed to be a type with fields
(e.g., a structure or union), has field field.
make_enum_dict (enum_type)
dictionary
type produced from enum_type.
deep_items (type)
gdb.Type.iteritems
method, except that the iterator returned
by deep_items
will recursively traverse anonymous struct or
union fields. For example:
struct A { int a; union { int b0; int b1; }; }; |
Then in GDB:
(gdb) python import gdb.types (gdb) python struct_a = gdb.lookup_type("struct A") (gdb) python print struct_a.keys () {['a', '']} (gdb) python print [k for k,v in gdb.types.deep_items(struct_a)] {['a', 'b0', 'b1']} |
get_type_recognizers ()
apply_type_recognizers (recognizers, type_obj)
None
. This is called by
GDB during the type-printing process (see section 23.2.2.8 Type Printing API).
register_type_printer (locus, printer)
gdb.Objfile
, in
which case the printer is registered with that objfile; a
gdb.Progspace
, in which case the printer is registered with
that progspace; or None
, in which case the printer is
registered globally.
TypePrinter
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This module provides a method for prompt value-substitution.
substitute_prompt (string)
The escape sequences you can pass to this function are:
\\
\e
\f
\n
\p
\r
\t
\v
\w
\[
\]
For example:
substitute_prompt (``frame: \f, print arguments: \p{print frame-arguments}'') |
will return the string:
"frame: main, print arguments: scalars" |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GDB provides two mechanisms for automatically loading extensions
when a new object file is read (for example, due to the file
command, or because the inferior has loaded a shared library):
`objfile-gdb.ext' and the .debug_gdb_scripts
section of modern file formats like ELF.
23.3.1 The `objfile-gdb.ext' file 23.3.2 The .debug_gdb_scripts
section23.3.3 Which flavor to choose?
The auto-loading feature is useful for supplying application-specific debugging commands and features.
Auto-loading can be enabled or disabled, and the list of auto-loaded scripts can be printed. See the `auto-loading' section of each extension language for more information. For GDB command files see 23.1.5 Controlling auto-loading native GDB scripts. For Python files see 23.2.3 Python Auto-loading.
Note that loading of this script file also requires accordingly configured
auto-load safe-path
(see section 22.7.3 Security restriction for auto-loading).
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
When a new object file is read, GDB looks for a file named `objfile-gdb.ext' (we call it script-name below), where objfile is the object file's name and where ext is the file extension for the extension language:
`objfile-gdb.gdb'
`objfile-gdb.py'
script-name is formed by ensuring that the file name of objfile
is absolute, following all symlinks, and resolving .
and ..
components, and appending the `-gdb.ext' suffix.
If this file exists and is readable, GDB will evaluate it as a
script in the specified extension language.
If this file does not exist, then GDB will look for script-name file in all of the directories as specified below.
Note that loading of these files requires an accordingly configured
auto-load safe-path
(see section 22.7.3 Security restriction for auto-loading).
For object files using `.exe' suffix GDB tries to load first the scripts normally according to its `.exe' filename. But if no scripts are found GDB also tries script filenames matching the object file without its `.exe' suffix. This `.exe' stripping is case insensitive and it is attempted on any platform. This makes the script filenames compatible between Unix and MS-Windows hosts.
set auto-load scripts-directory [directories]
Each entry here needs to be covered also by the security setting
set auto-load safe-path
(see set auto-load safe-path).
This variable defaults to `$debugdir:$datadir/auto-load'. The default
set auto-load safe-path
value can be also overriden by GDB
configuration option `--with-auto-load-dir'.
Any reference to `$debugdir' will get replaced by debug-file-directory value (see section 18.2 Debugging Information in Separate Files) and any reference to `$datadir' will get replaced by data-directory which is determined at GDB startup (see section 18.6 GDB Data Files). `$debugdir' and `$datadir' must be placed as a directory component -- either alone or delimited by `/' or `\' directory separators, depending on the host platform.
The list of directories uses path separator (`:' on GNU and Unix
systems, `;' on MS-Windows and MS-DOS) to separate directories, similarly
to the PATH
environment variable.
show auto-load scripts-directory
GDB does not track which files it has already auto-loaded this way. GDB will load the associated script every time the corresponding objfile is opened. So your `-gdb.ext' file should be careful to avoid errors if it is evaluated more than once.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
.debug_gdb_scripts
section
For systems using file formats like ELF and COFF,
when GDB loads a new object file
it will look for a special section named .debug_gdb_scripts
.
If this section exists, its contents is a list of NUL-terminated names
of scripts to load. Each entry begins with a non-NULL prefix byte that
specifies the kind of entry, typically the extension language.
GDB will look for each specified script file first in the current directory and then along the source search path (see section Specifying Source Directories), except that `$cdir' is not searched, since the compilation directory is not relevant to scripts.
Entries can be placed in section .debug_gdb_scripts
with,
for example, this GCC macro for Python scripts.
/* Note: The "MS" section flags are to remove duplicates. */ #define DEFINE_GDB_PY_SCRIPT(script_name) \ asm("\ .pushsection \".debug_gdb_scripts\", \"MS\",@progbits,1\n\ .byte 1 /* Python */\n\ .asciz \"" script_name "\"\n\ .popsection \n\ "); |
Then one can reference the macro in a header or source file like this:
DEFINE_GDB_PY_SCRIPT ("my-app-scripts.py") |
The script name may include directories if desired.
Note that loading of this script file also requires accordingly configured
auto-load safe-path
(see section 22.7.3 Security restriction for auto-loading).
If the macro invocation is put in a header, any application or library
using this header will get a reference to the specified script,
and with the use of "MS"
attributes on the section, the linker
will remove duplicates.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Given the multiple ways of auto-loading extensions, it might not always be clear which one to choose. This section provides some guidance.
Benefits of the `-gdb.ext' way:
Scripts specified in the .debug_gdb_scripts
section are searched for
in the source search path.
For publicly installed libraries, e.g., `libstdc++', there typically
isn't a source directory in which to find the script.
Benefits of the .debug_gdb_scripts
way:
Scripts for libraries done the `-gdb.ext' way require an objfile to trigger their loading. When an application is statically linked the only objfile available is the executable, and it is cumbersome to attach all the scripts from all the input libraries to the executable's `-gdb.ext' script.
Some classes can be entirely inlined, and thus there may not be an associated shared library to attach a `-gdb.ext' script to.
In some circumstances, apps can be built out of large collections of internal
libraries, and the build infrastructure necessary to install the
`-gdb.ext' scripts in a place where GDB can find them is
cumbersome. It may be easier to specify the scripts in the
.debug_gdb_scripts
section as relative paths, and add a path to the
top of the source tree to the source search path.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
It is often useful to define alternate spellings of existing commands. For example, if a new GDB command defined in Python has a long name to type, it is handy to have an abbreviated version of it that involves less typing.
GDB itself uses aliases. For example `s' is an alias of the `step' command even though it is otherwise an ambiguous abbreviation of other commands like `set' and `show'.
Aliases are also used to provide shortened or more common versions of multi-word commands. For example, GDB provides the `tty' alias of the `set inferior-tty' command.
You can define a new alias with the `alias' command.
alias [-a] [--] ALIAS = COMMAND
ALIAS specifies the name of the new alias. Each word of ALIAS must consist of letters, numbers, dashes and underscores.
COMMAND specifies the name of an existing command that is being aliased.
The `-a' option specifies that the new alias is an abbreviation of the command. Abbreviations are not shown in command lists displayed by the `help' command.
The `--' option specifies the end of options, and is useful when ALIAS begins with a dash.
Here is a simple example showing how to make an abbreviation of a command so that there is less to type. Suppose you were tired of typing `disas', the current shortest unambiguous abbreviation of the `disassemble' command and you wanted an even shorter version named `di'. The following will accomplish this.
(gdb) alias -a di = disas |
Note that aliases are different from user-defined commands. With a user-defined command, you also need to write documentation for it with the `document' command. An alias automatically picks up the documentation of the existing command.
Here is an example where we make `elms' an abbreviation of `elements' in the `set print elements' command. This is to show that you can make an abbreviation of any part of a command.
(gdb) alias -a set print elms = set print elements (gdb) alias -a show print elms = show print elements (gdb) set p elms 20 (gdb) show p elms Limit on string chars or array elements to print is 200. |
Note that if you are defining an alias of a `set' command, and you want to have an alias for the corresponding `show' command, then you need to define the latter separately.
Unambiguously abbreviated commands are allowed in COMMAND and ALIAS, just as they are normally.
(gdb) alias -a set pr elms = set p ele |
Finally, here is an example showing the creation of a one word alias for a more complex command. This creates alias `spe' of the command `set print elements'.
(gdb) alias spe = set print elements (gdb) spe 20 |
[ << ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |