-@c Copyright (C) 2008--2020 Free Software Foundation, Inc.
+@c Copyright (C) 2008--2022 Free Software Foundation, Inc.
@c Permission is granted to copy, distribute and/or modify this document
@c under the terms of the GNU Free Documentation License, Version 1.3 or
@c any later version published by the Free Software Foundation; with the
full Python stack printing is enabled; if @code{none}, then Python stack
and message printing is disabled; if @code{message}, the default, only
the message component of the error is printed.
+
+@kindex set python ignore-environment
+@item set python ignore-environment @r{[}on@r{|}off@r{]}
+By default this option is @samp{off}, and, when @value{GDBN}
+initializes its internal Python interpreter, the Python interpreter
+will check the environment for variables that will effect how it
+behaves, for example @env{PYTHONHOME}, and
+@env{PYTHONPATH}@footnote{See the ENVIRONMENT VARIABLES section of
+@command{man 1 python} for a comprehensive list.}.
+
+If this option is set to @samp{on} before Python is initialized then
+Python will ignore all such environment variables. As Python is
+initialized early during @value{GDBN}'s startup process, then this
+option must be placed into the early initialization file
+(@pxref{Initialization Files}) to have the desired effect.
+
+This option is equivalent to passing @option{-E} to the real
+@command{python} executable.
+
+@kindex set python dont-write-bytecode
+@item set python dont-write-bytecode @r{[}auto@r{|}on@r{|}off@r{]}
+When this option is @samp{off}, then, once @value{GDBN} has
+initialized the Python interpreter, the interpreter will byte-compile
+any Python modules that it imports and write the byte code to disk in
+@file{.pyc} files.
+
+If this option is set to @samp{on} before Python is initialized then
+Python will no longer write the byte code to disk. As Python is
+initialized early during @value{GDBN}'s startup process, then this
+option must be placed into the early initialization file
+(@pxref{Initialization Files}) to have the desired effect.
+
+By default this option is set to @samp{auto}, in this mode Python will
+check the environment variable @env{PYTHONDONTWRITEBYTECODE} to see
+if it should write out byte-code or not.
+
+This option is equivalent to passing @option{-B} to the real
+@command{python} executable.
@end table
It is also possible to execute a Python script from the @value{GDBN}
the @code{script-extension} setting. @xref{Extending GDB, ,Extending GDB}.
@end table
+The following commands are intended to help debug @value{GDBN} itself:
+
+@table @code
+@kindex set debug py-breakpoint
+@kindex show debug py-breakpoint
+@item set debug py-breakpoint on@r{|}off
+@itemx show debug py-breakpoint
+When @samp{on}, @value{GDBN} prints debug messages related to the
+Python breakpoint API. This is @samp{off} by default.
+
+@kindex set debug py-unwind
+@kindex show debug py-unwind
+@item set debug py-unwind on@r{|}off
+@itemx show debug py-unwind
+When @samp{on}, @value{GDBN} prints debug messages related to the
+Python unwinder API. This is @samp{off} by default.
+@end table
+
@node Python API
@subsection Python API
@cindex python api
using Python.
* Lazy Strings In Python:: Python representation of lazy strings.
* Architectures In Python:: Python representation of architectures.
+* Registers In Python:: Python representation of registers.
+* TUI Windows In Python:: Implementing new TUI windows.
@end menu
@node Basic Python
> argv = gdb.string_to_argv (args)
> if len (argv) != 0:
> raise gdb.GdbError ("hello-world takes no arguments")
-> print "Hello, World!"
+> print ("Hello, World!")
>HelloWorld ()
>end
(gdb) hello-world 42
should be expanded, @code{False} if they shouldn't (see @code{set print
union} in @ref{Print Settings}).
+@item address
+@code{True} if the string representation of a pointer should include the
+address, @code{False} if it shouldn't (see @code{set print address} in
+@ref{Print Settings}).
+
@item deref_refs
@code{True} if C@t{++} references should be resolved to the value they
refer to, @code{False} (the default) if they shouldn't. Note that, unlike
the @emph{declared} type should be used. (See @code{set print object} in
@ref{Print Settings}).
-@item static_fields
+@item static_members
@code{True} if static members should be included in the string
representation of a C@t{++} object, @code{False} if they shouldn't (see
@code{set print static-members} in @ref{Print Settings}).
@code{TYPE_CODE_} constants defined below.
@end defvar
+@defvar Type.dynamic
+A boolean indicating whether this type is dynamic. In some
+situations, such as Rust @code{enum} types or Ada variant records, the
+concrete type of a value may vary depending on its contents. That is,
+the declared type of a variable, or the type returned by
+@code{gdb.lookup_type} may be dynamic; while the type of the
+variable's value will be a concrete instance of that dynamic type.
+
+For example, consider this code:
+@smallexample
+int n;
+int array[n];
+@end smallexample
+
+Here, at least conceptually (whether your compiler actually does this
+is a separate issue), examining @w{@code{gdb.lookup_symbol("array", ...).type}}
+could yield a @code{gdb.Type} which reports a size of @code{None}.
+This is the dynamic type.
+
+However, examining @code{gdb.parse_and_eval("array").type} would yield
+a concrete type, whose length would be known.
+@end defvar
+
@defvar Type.name
The name of this type. If this type has no name, then @code{None}
is returned.
@defvar Type.sizeof
The size of this type, in target @code{char} units. Usually, a
target's @code{char} type will be an 8-bit byte. However, on some
-unusual platforms, this type may have a different size.
+unusual platforms, this type may have a different size. A dynamic
+type may not have a fixed size; in this case, this attribute's value
+will be @code{None}.
@end defvar
@defvar Type.tag
The following methods are provided:
@defun Type.fields ()
-For structure and union types, this method returns the fields. Range
-types have two fields, the minimum and maximum values. Enum types
-have one field per enum constant. Function and method types have one
-field per parameter. The base types of C@t{++} classes are also
-represented as fields. If the type has no fields, or does not fit
-into one of these categories, an empty sequence will be returned.
+
+Return the fields of this type. The behavior depends on the type code:
+
+@itemize @bullet
+
+@item
+For structure and union types, this method returns the fields.
+
+@item
+Range types have two fields, the minimum and maximum values.
+
+@item
+Enum types have one field per enum constant.
+
+@item
+Function and method types have one field per parameter. The base types of
+C@t{++} classes are also represented as fields.
+
+@item
+Array types have one field representing the array's range.
+
+@item
+If the type does not fit into one of these categories, a @code{TypeError}
+is raised.
+
+@end itemize
Each field is a @code{gdb.Field} object, with some pre-defined attributes:
@table @code
@item bitpos
This attribute is not available for @code{enum} or @code{static}
(as in C@t{++}) fields. The value is the position, counting
-in bits, from the start of the containing type.
+in bits, from the start of the containing type. Note that, in a
+dynamic type, the position of a field may not be constant. In this
+case, the value will be @code{None}. Also, a dynamic type may have
+fields that do not appear in a corresponding concrete type.
@item enumval
This attribute is only available for @code{enum} fields, and its value
@smallexample
def str_lookup_function(val):
lookup_tag = val.type.tag
- if lookup_tag == None:
+ if lookup_tag is None:
return None
regex = re.compile("^std::basic_string<char,.*>$")
if regex.match(lookup_tag):
printed for this frame. This iterable must contain objects that
implement two methods, described here.
-This object must implement a @code{argument} method which takes a
+This object must implement a @code{symbol} method which takes a
single @code{self} parameter and must return a @code{gdb.Symbol}
(@pxref{Symbols In Python}), or a Python string. The object must also
implement a @code{value} method which takes a single @code{self}
super(InlinedFrameDecorator, self).__init__(fobj)
def function(self):
- frame = fobj.inferior_frame()
+ frame = self.inferior_frame()
name = str(frame.name())
if frame.type() == gdb.INLINE_FRAME:
@defun PendingFrame.read_register (reg)
This method returns the contents of the register @var{reg} in the
-frame as a @code{gdb.Value} object. @var{reg} can be either a
-register number or a register name; the values are platform-specific.
-They are usually found in the corresponding
-@file{@var{platform}-tdep.h} file in the @value{GDBN} source tree. If
-@var{reg} does not name a register for the current architecture, this
-method will throw an exception.
+frame as a @code{gdb.Value} object. For a description of the
+acceptable values of @var{reg} see
+@ref{gdbpy_frame_read_register,,Frame.read_register}. If @var{reg}
+does not name a register for the current architecture, this method
+will throw an exception.
Note that this method will always return a @code{gdb.Value} for a
valid register name. This does not mean that the value will be valid.
@end defun
+@defun PendingFrame.architecture ()
+Return the @code{gdb.Architecture} (@pxref{Architectures In Python})
+for this @code{gdb.PendingFrame}. This represents the architecture of
+the particular frame being unwound.
+@end defun
+
+@defun PendingFrame.level ()
+Return an integer, the stack frame level for this frame.
+@xref{Frames, ,Stack Frames}.
+@end defun
+
@subheading Unwinder Output: UnwindInfo
Use @code{PendingFrame.create_unwind_info} method described above to
specify caller registers that have been saved in this frame:
@defun gdb.UnwindInfo.add_saved_register (reg, value)
-@var{reg} identifies the register. It can be a number or a name, just
-as for the @code{PendingFrame.read_register} method above.
+@var{reg} identifies the register, for a description of the acceptable
+values see @ref{gdbpy_frame_read_register,,Frame.read_register}.
@var{value} is a register value (a @code{gdb.Value} object).
@end defun
@findex gdb.Inferior
Programs which are being run under @value{GDBN} are called inferiors
-(@pxref{Inferiors and Programs}). Python scripts can access
+(@pxref{Inferiors Connections and Programs}). Python scripts can access
information about and manipulate inferiors controlled by @value{GDBN}
via objects of the @code{gdb.Inferior} class.
ID of inferior, as assigned by GDB.
@end defvar
+@defvar Inferior.connection_num
+ID of inferior's connection as assigned by @value{GDBN}, or None if
+the inferior is not connected to a target.
+@xref{Inferiors Connections and Programs}.
+@end defvar
+
@defvar Inferior.pid
Process ID of the inferior, as assigned by the underlying operating
system.
@smallexample
def exit_handler (event):
- print "event type: exit"
- print "exit code: %d" % (event.exit_code)
+ print ("event type: exit")
+ print ("exit code: %d" % (event.exit_code))
gdb.events.exited.connect (exit_handler)
@end smallexample
@end defun
To get the list of threads for an inferior, use the @code{Inferior.threads()}
-method. @xref{Inferiors In Python}
+method. @xref{Inferiors In Python}.
A @code{gdb.InferiorThread} object has the following attributes:
@kbd{help tracepoints} at the @value{GDBN} prompt to see a list of
commands in this category.
+@findex COMMAND_TUI
+@findex gdb.COMMAND_TUI
+@item gdb.COMMAND_TUI
+The command has to do with the text user interface (@pxref{TUI}).
+Type @kbd{help tui} at the @value{GDBN} prompt to see a list of
+commands in this category.
+
@findex COMMAND_USER
@findex gdb.COMMAND_USER
@item gdb.COMMAND_USER
super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
def invoke (self, arg, from_tty):
- print "Hello, World!"
+ print ("Hello, World!")
HelloWorld ()
@end smallexample
self.value = self.saved_value
raise gdb.GdbError('Failed to validate')
self.saved_value = self.value
+ return ""
@end smallexample
@end defun
of an address space.
It consists of all of the objfiles of the program.
@xref{Objfiles In Python}.
-@xref{Inferiors and Programs, program spaces}, for more details
+@xref{Inferiors Connections and Programs, program spaces}, for more details
about program spaces.
The following progspace-related functions are available in the
@findex gdb.current_progspace
@defun gdb.current_progspace ()
This function returns the program space of the currently selected inferior.
-@xref{Inferiors and Programs}. This is identical to
+@xref{Inferiors Connections and Programs}. This is identical to
@code{gdb.selected_inferior().progspace} (@pxref{Inferiors In Python}) and is
included for historical compatibility.
@end defun
event.progspace.expensive_computation = None
def expensive(symbol):
"""A mock routine to perform an "expensive" computation on symbol."""
- print "Computing the answer to the ultimate question ..."
+ print ("Computing the answer to the ultimate question ...")
return 42
def new_objfile_handler(event):
objfile = event.new_objfile
gdb.events.new_objfile.connect(new_objfile_handler)
end
(gdb) file /tmp/hello
-Reading symbols from /tmp/hello...done.
+Reading symbols from /tmp/hello...
Computing the answer to the ultimate question ...
(gdb) python print gdb.current_progspace().expensive_computation
42
gdb.events.new_objfile.connect(new_objfile_handler)
end
(gdb) file ./hello
-Reading symbols from ./hello...done.
+Reading symbols from ./hello...
(gdb) python print gdb.objfiles()[0].time_loaded
2014-10-09 11:41:36.770345
@end smallexample
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
+ print ("An error occured: %s" % reason_str)
@end smallexample
@end table
@xref{Symbol Tables In Python}.
@end defun
+@anchor{gdbpy_frame_read_register}
@defun Frame.read_register (register)
-Return the value of @var{register} in this frame. The @var{register}
-argument must be a string (e.g., @code{'sp'} or @code{'rax'}).
-Returns a @code{Gdb.Value} object. Throws an exception if @var{register}
-does not exist.
+Return the value of @var{register} in this frame. Returns a
+@code{Gdb.Value} object. Throws an exception if @var{register} does
+not exist. The @var{register} argument must be one of the following:
+@enumerate
+@item
+A string that is the name of a valid register (e.g., @code{'sp'} or
+@code{'rax'}).
+@item
+A @code{gdb.RegisterDescriptor} object (@pxref{Registers In Python}).
+@item
+A @value{GDBN} internal, platform specific number. Using these
+numbers is supported for historic reasons, but is not recommended as
+future changes to @value{GDBN} could change the mapping between
+numbers and the registers they represent, breaking any Python code
+that uses the platform-specific numbers. The numbers are usually
+found in the corresponding @file{@var{platform}-tdep.h} file in the
+@value{GDBN} source tree.
+@end enumerate
+Using a string to access registers will be slightly slower than the
+other two methods as @value{GDBN} must look up the mapping between
+name and internal register number. If performance is critical
+consider looking up and caching a @code{gdb.RegisterDescriptor}
+object.
@end defun
@defun Frame.read_var (variable @r{[}, block@r{]})
Stack}.
@end defun
+@defun Frame.level ()
+Return an integer, the stack frame level for this frame. @xref{Frames, ,Stack Frames}.
+@end defun
+
@node Blocks In Python
@subsubsection Accessing blocks from Python
Value not used. Symbols in the domain @code{SYMBOL_STRUCT_DOMAIN} all
have this class.
+@vindex SYMBOL_LOC_LABEL
+@item gdb.SYMBOL_LOC_LABEL
+Value is a label.
+
@vindex SYMBOL_LOC_BLOCK
@item gdb.SYMBOL_LOC_BLOCK
Value is a block.
@item gdb.SYMBOL_LOC_COMPUTED
The value's address is a computed location.
-@vindex SYMBOL_LOC_COMPUTED
-@item gdb.SYMBOL_LOC_COMPUTED
+@vindex SYMBOL_LOC_COMMON_BLOCK
+@item gdb.SYMBOL_LOC_COMMON_BLOCK
The value's address is a symbol. This is only used for Fortran common
blocks.
@end vtable
symtab = gdb.selected_frame().find_sal().symtab
linetable = symtab.linetable()
for line in linetable:
- print "Line: "+str(line.line)+" Address: "+hex(line.pc)
+ print ("Line: "+str(line.line)+" Address: "+hex(line.pc))
@end smallexample
This will have the following output:
@item gdb.BP_BREAKPOINT
Normal code breakpoint.
+@vindex BP_HARDWARE_BREAKPOINT
+@item gdb.BP_HARDWARE_BREAKPOINT
+Hardware assisted code breakpoint.
+
@vindex BP_WATCHPOINT
@item gdb.BP_WATCHPOINT
Watchpoint breakpoint.
@vindex BP_ACCESS_WATCHPOINT
@item gdb.BP_ACCESS_WATCHPOINT
Hardware assisted access watchpoint.
+
+@vindex BP_CATCHPOINT
+@item gdb.BP_CATCHPOINT
+Catchpoint. Currently, this type can't be used when creating
+@code{gdb.Breakpoint} objects, but will be present in
+@code{gdb.Breakpoint} objects reported from
+@code{gdb.BreakpointEvent}s (@pxref{Events In Python}).
@end vtable
-The available watchpoint types represented by constants are defined in the
+The available watchpoint types are represented by constants defined in the
@code{gdb} module:
@vtable @code
@smallexample
class MyFinishBreakpoint (gdb.FinishBreakpoint)
def stop (self):
- print "normal finish"
+ print ("normal finish")
return True
def out_of_scope ():
- print "abnormal finish"
+ print ("abnormal finish")
@end smallexample
@end defun
@end table
@end defun
+@anchor{gdbpy_architecture_registers}
+@defun Architecture.registers (@r{[} @var{reggroup} @r{]})
+Return a @code{gdb.RegisterDescriptorIterator} (@pxref{Registers In
+Python}) for all of the registers in @var{reggroup}, a string that is
+the name of a register group. If @var{reggroup} is omitted, or is the
+empty string, then the register group @samp{all} is assumed.
+@end defun
+
+@anchor{gdbpy_architecture_reggroups}
+@defun Architecture.register_groups ()
+Return a @code{gdb.RegisterGroupsIterator} (@pxref{Registers In
+Python}) for all of the register groups available for the
+@code{gdb.Architecture}.
+@end defun
+
+@node Registers In Python
+@subsubsection Registers In Python
+@cindex Registers In Python
+
+Python code can request from a @code{gdb.Architecture} information
+about the set of registers available
+(@pxref{gdbpy_architecture_registers,,@code{Architecture.registers}}).
+The register information is returned as a
+@code{gdb.RegisterDescriptorIterator}, which is an iterator that in
+turn returns @code{gdb.RegisterDescriptor} objects.
+
+A @code{gdb.RegisterDescriptor} does not provide the value of a
+register (@pxref{gdbpy_frame_read_register,,@code{Frame.read_register}}
+for reading a register's value), instead the @code{RegisterDescriptor}
+is a way to discover which registers are available for a particular
+architecture.
+
+A @code{gdb.RegisterDescriptor} has the following read-only properties:
+
+@defvar RegisterDescriptor.name
+The name of this register.
+@end defvar
+
+It is also possible to lookup a register descriptor based on its name
+using the following @code{gdb.RegisterDescriptorIterator} function:
+
+@defun RegisterDescriptorIterator.find (@var{name})
+Takes @var{name} as an argument, which must be a string, and returns a
+@code{gdb.RegisterDescriptor} for the register with that name, or
+@code{None} if there is no register with that name.
+@end defun
+
+Python code can also request from a @code{gdb.Architecture}
+information about the set of register groups available on a given
+architecture
+(@pxref{gdbpy_architecture_reggroups,,@code{Architecture.register_groups}}).
+
+Every register can be a member of zero or more register groups. Some
+register groups are used internally within @value{GDBN} to control
+things like which registers must be saved when calling into the
+program being debugged (@pxref{Calling,,Calling Program Functions}).
+Other register groups exist to allow users to easily see related sets
+of registers in commands like @code{info registers}
+(@pxref{info_registers_reggroup,,@code{info registers
+@var{reggroup}}}).
+
+The register groups information is returned as a
+@code{gdb.RegisterGroupsIterator}, which is an iterator that in turn
+returns @code{gdb.RegisterGroup} objects.
+
+A @code{gdb.RegisterGroup} object has the following read-only
+properties:
+
+@defvar RegisterGroup.name
+A string that is the name of this register group.
+@end defvar
+
+@node TUI Windows In Python
+@subsubsection Implementing new TUI windows
+@cindex Python TUI Windows
+
+New TUI (@pxref{TUI}) windows can be implemented in Python.
+
+@findex gdb.register_window_type
+@defun gdb.register_window_type (@var{name}, @var{factory})
+Because TUI windows are created and destroyed depending on the layout
+the user chooses, new window types are implemented by registering a
+factory function with @value{GDBN}.
+
+@var{name} is the name of the new window. It's an error to try to
+replace one of the built-in windows, but other window types can be
+replaced.
+
+@var{function} is a factory function that is called to create the TUI
+window. This is called with a single argument of type
+@code{gdb.TuiWindow}, described below. It should return an object
+that implements the TUI window protocol, also described below.
+@end defun
+
+As mentioned above, when a factory function is called, it is passed
+an object of type @code{gdb.TuiWindow}. This object has these
+methods and attributes:
+
+@defun TuiWindow.is_valid ()
+This method returns @code{True} when this window is valid. When the
+user changes the TUI layout, windows no longer visible in the new
+layout will be destroyed. At this point, the @code{gdb.TuiWindow}
+will no longer be valid, and methods (and attributes) other than
+@code{is_valid} will throw an exception.
+
+When the TUI is disabled using @code{tui disable} (@pxref{TUI
+Commands,,tui disable}) the window is hidden rather than destroyed,
+but @code{is_valid} will still return @code{False} and other methods
+(and attributes) will still throw an exception.
+@end defun
+
+@defvar TuiWindow.width
+This attribute holds the width of the window. It is not writable.
+@end defvar
+
+@defvar TuiWindow.height
+This attribute holds the height of the window. It is not writable.
+@end defvar
+
+@defvar TuiWindow.title
+This attribute holds the window's title, a string. This is normally
+displayed above the window. This attribute can be modified.
+@end defvar
+
+@defun TuiWindow.erase ()
+Remove all the contents of the window.
+@end defun
+
+@defun TuiWindow.write (@var{string} @r{[}, @var{full_window}@r{]})
+Write @var{string} to the window. @var{string} can contain ANSI
+terminal escape styling sequences; @value{GDBN} will translate these
+as appropriate for the terminal.
+
+If the @var{full_window} parameter is @code{True}, then @var{string}
+contains the full contents of the window. This is similar to calling
+@code{erase} before @code{write}, but avoids the flickering.
+@end defun
+
+The factory function that you supply should return an object
+conforming to the TUI window protocol. These are the method that can
+be called on this object, which is referred to below as the ``window
+object''. The methods documented below are optional; if the object
+does not implement one of these methods, @value{GDBN} will not attempt
+to call it. Additional new methods may be added to the window
+protocol in the future. @value{GDBN} guarantees that they will begin
+with a lower-case letter, so you can start implementation methods with
+upper-case letters or underscore to avoid any future conflicts.
+
+@defun Window.close ()
+When the TUI window is closed, the @code{gdb.TuiWindow} object will be
+put into an invalid state. At this time, @value{GDBN} will call
+@code{close} method on the window object.
+
+After this method is called, @value{GDBN} will discard any references
+it holds on this window object, and will no longer call methods on
+this object.
+@end defun
+
+@defun Window.render ()
+In some situations, a TUI window can change size. For example, this
+can happen if the user resizes the terminal, or changes the layout.
+When this happens, @value{GDBN} will call the @code{render} method on
+the window object.
+
+If your window is intended to update in response to changes in the
+inferior, you will probably also want to register event listeners and
+send output to the @code{gdb.TuiWindow}.
+@end defun
+
+@defun Window.hscroll (@var{num})
+This is a request to scroll the window horizontally. @var{num} is the
+amount by which to scroll, with negative numbers meaning to scroll
+right. In the TUI model, it is the viewport that moves, not the
+contents. A positive argument should cause the viewport to move
+right, and so the content should appear to move to the left.
+@end defun
+
+@defun Window.vscroll (@var{num})
+This is a request to scroll the window vertically. @var{num} is the
+amount by which to scroll, with negative numbers meaning to scroll
+backward. In the TUI model, it is the viewport that moves, not the
+contents. A positive argument should cause the viewport to move down,
+and so the content should appear to move up.
+@end defun
+
+@defun Window.click (@var{x}, @var{y}, @var{button})
+This is called on a mouse click in this window. @var{x} and @var{y} are
+the mouse coordinates inside the window (0-based), and @var{button}
+specifies which mouse button was used, whose values can be 1 (left),
+2 (middle), or 3 (right).
+@end defun
+
@node Python Auto-loading
@subsection Python Auto-loading
@cindex Python auto-loading