]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/doc/python.texi
Update copyright year range in header of all files managed by GDB
[thirdparty/binutils-gdb.git] / gdb / doc / python.texi
CommitLineData
1d506c26 1@c Copyright (C) 2008--2024 Free Software Foundation, Inc.
329baa95
DE
2@c Permission is granted to copy, distribute and/or modify this document
3@c under the terms of the GNU Free Documentation License, Version 1.3 or
4@c any later version published by the Free Software Foundation; with the
5@c Invariant Sections being ``Free Software'' and ``Free Software Needs
6@c Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,''
7@c and with the Back-Cover Texts as in (a) below.
8@c
9@c (a) The FSF's Back-Cover Text is: ``You are free to copy and modify
10@c this GNU Manual. Buying copies from GNU Press supports the FSF in
11@c developing GNU and promoting software freedom.''
12
13@node Python
14@section Extending @value{GDBN} using Python
15@cindex python scripting
16@cindex scripting with python
17
18You can extend @value{GDBN} using the @uref{http://www.python.org/,
19Python programming language}. This feature is available only if
20@value{GDBN} was configured using @option{--with-python}.
21
22@cindex python directory
23Python scripts used by @value{GDBN} should be installed in
24@file{@var{data-directory}/python}, where @var{data-directory} is
25the data directory as determined at @value{GDBN} startup (@pxref{Data Files}).
26This directory, known as the @dfn{python directory},
27is automatically added to the Python Search Path in order to allow
28the Python interpreter to locate all scripts installed at this location.
29
30Additionally, @value{GDBN} commands and convenience functions which
31are written in Python and are located in the
32@file{@var{data-directory}/python/gdb/command} or
33@file{@var{data-directory}/python/gdb/function} directories are
34automatically imported when @value{GDBN} starts.
35
36@menu
37* Python Commands:: Accessing Python from @value{GDBN}.
38* Python API:: Accessing @value{GDBN} from Python.
39* Python Auto-loading:: Automatically loading Python code.
40* Python modules:: Python modules provided by @value{GDBN}.
41@end menu
42
43@node Python Commands
44@subsection Python Commands
45@cindex python commands
46@cindex commands to access python
47
48@value{GDBN} provides two commands for accessing the Python interpreter,
49and one related setting:
50
51@table @code
52@kindex python-interactive
53@kindex pi
54@item python-interactive @r{[}@var{command}@r{]}
55@itemx pi @r{[}@var{command}@r{]}
56Without an argument, the @code{python-interactive} command can be used
57to start an interactive Python prompt. To return to @value{GDBN},
58type the @code{EOF} character (e.g., @kbd{Ctrl-D} on an empty prompt).
59
60Alternatively, a single-line Python command can be given as an
61argument and evaluated. If the command is an expression, the result
62will be printed; otherwise, nothing will be printed. For example:
63
64@smallexample
65(@value{GDBP}) python-interactive 2 + 3
665
67@end smallexample
68
69@kindex python
70@kindex py
71@item python @r{[}@var{command}@r{]}
72@itemx py @r{[}@var{command}@r{]}
73The @code{python} command can be used to evaluate Python code.
74
75If given an argument, the @code{python} command will evaluate the
76argument as a Python command. For example:
77
78@smallexample
79(@value{GDBP}) python print 23
8023
81@end smallexample
82
83If you do not provide an argument to @code{python}, it will act as a
84multi-line command, like @code{define}. In this case, the Python
85script is made up of subsequent command lines, given after the
86@code{python} command. This command list is terminated using a line
87containing @code{end}. For example:
88
89@smallexample
90(@value{GDBP}) python
329baa95
DE
91>print 23
92>end
9323
94@end smallexample
95
740b42ce 96@anchor{set_python_print_stack}
329baa95
DE
97@kindex set python print-stack
98@item set python print-stack
99By default, @value{GDBN} will print only the message component of a
100Python exception when an error occurs in a Python script. This can be
101controlled using @code{set python print-stack}: if @code{full}, then
102full Python stack printing is enabled; if @code{none}, then Python stack
103and message printing is disabled; if @code{message}, the default, only
104the message component of the error is printed.
edeaceda
AB
105
106@kindex set python ignore-environment
107@item set python ignore-environment @r{[}on@r{|}off@r{]}
108By default this option is @samp{off}, and, when @value{GDBN}
109initializes its internal Python interpreter, the Python interpreter
110will check the environment for variables that will effect how it
111behaves, for example @env{PYTHONHOME}, and
112@env{PYTHONPATH}@footnote{See the ENVIRONMENT VARIABLES section of
113@command{man 1 python} for a comprehensive list.}.
114
115If this option is set to @samp{on} before Python is initialized then
116Python will ignore all such environment variables. As Python is
117initialized early during @value{GDBN}'s startup process, then this
118option must be placed into the early initialization file
119(@pxref{Initialization Files}) to have the desired effect.
120
121This option is equivalent to passing @option{-E} to the real
122@command{python} executable.
123
124@kindex set python dont-write-bytecode
125@item set python dont-write-bytecode @r{[}auto@r{|}on@r{|}off@r{]}
126When this option is @samp{off}, then, once @value{GDBN} has
127initialized the Python interpreter, the interpreter will byte-compile
128any Python modules that it imports and write the byte code to disk in
129@file{.pyc} files.
130
131If this option is set to @samp{on} before Python is initialized then
132Python will no longer write the byte code to disk. As Python is
133initialized early during @value{GDBN}'s startup process, then this
134option must be placed into the early initialization file
135(@pxref{Initialization Files}) to have the desired effect.
136
24d2cbc4
KB
137By default this option is set to @samp{auto}. In this mode, provided
138the @code{python ignore-environment} setting is @samp{off}, the
139environment variable @env{PYTHONDONTWRITEBYTECODE} is examined to see
edeaceda 140if it should write out byte-code or not.
24d2cbc4
KB
141@env{PYTHONDONTWRITEBYTECODE} is considered to be off/disabled either
142when set to the empty string or when the environment variable doesn't
143exist. All other settings, including those which don't seem to make
144sense, indicate that it's on/enabled.
edeaceda
AB
145
146This option is equivalent to passing @option{-B} to the real
147@command{python} executable.
329baa95
DE
148@end table
149
150It is also possible to execute a Python script from the @value{GDBN}
151interpreter:
152
153@table @code
154@item source @file{script-name}
155The script name must end with @samp{.py} and @value{GDBN} must be configured
156to recognize the script language based on filename extension using
157the @code{script-extension} setting. @xref{Extending GDB, ,Extending GDB}.
329baa95
DE
158@end table
159
75140e3b
AB
160The following commands are intended to help debug @value{GDBN} itself:
161
162@table @code
163@kindex set debug py-breakpoint
164@kindex show debug py-breakpoint
165@item set debug py-breakpoint on@r{|}off
166@itemx show debug py-breakpoint
167When @samp{on}, @value{GDBN} prints debug messages related to the
168Python breakpoint API. This is @samp{off} by default.
9dffa1aa
AB
169
170@kindex set debug py-unwind
171@kindex show debug py-unwind
172@item set debug py-unwind on@r{|}off
173@itemx show debug py-unwind
174When @samp{on}, @value{GDBN} prints debug messages related to the
175Python unwinder API. This is @samp{off} by default.
75140e3b
AB
176@end table
177
329baa95
DE
178@node Python API
179@subsection Python API
180@cindex python api
181@cindex programming in python
182
183You can get quick online help for @value{GDBN}'s Python API by issuing
184the command @w{@kbd{python help (gdb)}}.
185
186Functions and methods which have two or more optional arguments allow
187them to be specified using keyword syntax. This allows passing some
188optional arguments while skipping others. Example:
189@w{@code{gdb.some_function ('foo', bar = 1, baz = 2)}}.
190
191@menu
192* Basic Python:: Basic Python Functions.
560c121c 193* Threading in GDB:: Using Python threads in GDB.
329baa95
DE
194* Exception Handling:: How Python exceptions are translated.
195* Values From Inferior:: Python representation of values.
196* Types In Python:: Python representation of types.
197* Pretty Printing API:: Pretty-printing values.
198* Selecting Pretty-Printers:: How GDB chooses a pretty-printer.
199* Writing a Pretty-Printer:: Writing a Pretty-Printer.
cc81f07b 200* Type Printing API:: Pretty-printing types.
329baa95
DE
201* Frame Filter API:: Filtering Frames.
202* Frame Decorator API:: Decorating Frames.
203* Writing a Frame Filter:: Writing a Frame Filter.
d11916aa 204* Unwinding Frames in Python:: Writing frame unwinder.
0c6e92a5
SC
205* Xmethods In Python:: Adding and replacing methods of C++ classes.
206* Xmethod API:: Xmethod types.
207* Writing an Xmethod:: Writing an xmethod.
329baa95
DE
208* Inferiors In Python:: Python representation of inferiors (processes)
209* Events In Python:: Listening for events from @value{GDBN}.
210* Threads In Python:: Accessing inferior threads from Python.
0a0faf9f 211* Recordings In Python:: Accessing recordings from Python.
740b42ce 212* CLI Commands In Python:: Implementing new CLI commands in Python.
c96452ad 213* GDB/MI Commands In Python:: Implementing new @sc{gdb/mi} commands in Python.
4825fd2d 214* GDB/MI Notifications In Python:: Implementing new @sc{gdb/mi} notifications in Python.
329baa95
DE
215* Parameters In Python:: Adding new @value{GDBN} parameters.
216* Functions In Python:: Writing new convenience functions.
217* Progspaces In Python:: Program spaces.
218* Objfiles In Python:: Object files.
219* Frames In Python:: Accessing inferior stack frames from Python.
220* Blocks In Python:: Accessing blocks from Python.
221* Symbols In Python:: Python representation of symbols.
222* Symbol Tables In Python:: Python representation of symbol tables.
223* Line Tables In Python:: Python representation of line tables.
224* Breakpoints In Python:: Manipulating breakpoints using Python.
225* Finish Breakpoints in Python:: Setting Breakpoints on function return
226 using Python.
227* Lazy Strings In Python:: Python representation of lazy strings.
228* Architectures In Python:: Python representation of architectures.
0f767f94 229* Registers In Python:: Python representation of registers.
cc81f07b 230* Connections In Python:: Python representation of connections.
01b1af32 231* TUI Windows In Python:: Implementing new TUI windows.
15e15b2d 232* Disassembly In Python:: Instruction Disassembly In Python
8f6c452b 233* Missing Debug Info In Python:: Handle missing debug info from Python.
329baa95
DE
234@end menu
235
236@node Basic Python
237@subsubsection Basic Python
238
239@cindex python stdout
240@cindex python pagination
241At startup, @value{GDBN} overrides Python's @code{sys.stdout} and
242@code{sys.stderr} to print using @value{GDBN}'s output-paging streams.
243A Python program which outputs to one of these streams may have its
244output interrupted by the user (@pxref{Screen Size}). In this
245situation, a Python @code{KeyboardInterrupt} exception is thrown.
246
247Some care must be taken when writing Python code to run in
248@value{GDBN}. Two things worth noting in particular:
249
250@itemize @bullet
251@item
14432bde 252@value{GDBN} installs handlers for @code{SIGCHLD} and @code{SIGINT}.
329baa95
DE
253Python code must not override these, or even change the options using
254@code{sigaction}. If your program changes the handling of these
255signals, @value{GDBN} will most likely stop working correctly. Note
256that it is unfortunately common for GUI toolkits to install a
14432bde
TT
257@code{SIGCHLD} handler. When creating a new Python thread, you can
258use @code{gdb.block_signals} or @code{gdb.Thread} to handle this
259correctly; see @ref{Threading in GDB}.
329baa95
DE
260
261@item
262@value{GDBN} takes care to mark its internal file descriptors as
263close-on-exec. However, this cannot be done in a thread-safe way on
264all platforms. Your Python programs should be aware of this and
265should both create new file descriptors with the close-on-exec flag
266set and arrange to close unneeded file descriptors before starting a
267child process.
268@end itemize
269
270@cindex python functions
271@cindex python module
272@cindex gdb module
273@value{GDBN} introduces a new Python module, named @code{gdb}. All
274methods and classes added by @value{GDBN} are placed in this module.
275@value{GDBN} automatically @code{import}s the @code{gdb} module for
276use in all scripts evaluated by the @code{python} command.
277
1256af7d
SM
278Some types of the @code{gdb} module come with a textual representation
279(accessible through the @code{repr} or @code{str} functions). These are
280offered for debugging purposes only, expect them to change over time.
281
329baa95
DE
282@defvar gdb.PYTHONDIR
283A string containing the python directory (@pxref{Python}).
284@end defvar
285
329baa95
DE
286@defun gdb.execute (command @r{[}, from_tty @r{[}, to_string@r{]]})
287Evaluate @var{command}, a string, as a @value{GDBN} CLI command.
288If a GDB exception happens while @var{command} runs, it is
289translated as described in @ref{Exception Handling,,Exception Handling}.
290
697aa1b7 291The @var{from_tty} flag specifies whether @value{GDBN} ought to consider this
329baa95
DE
292command as having originated from the user invoking it interactively.
293It must be a boolean value. If omitted, it defaults to @code{False}.
294
295By default, any output produced by @var{command} is sent to
b3ce5e5f
DE
296@value{GDBN}'s standard output (and to the log output if logging is
297turned on). If the @var{to_string} parameter is
329baa95
DE
298@code{True}, then output will be collected by @code{gdb.execute} and
299returned as a string. The default is @code{False}, in which case the
300return value is @code{None}. If @var{to_string} is @code{True}, the
301@value{GDBN} virtual terminal will be temporarily set to unlimited width
302and height, and its pagination will be disabled; @pxref{Screen Size}.
303@end defun
304
329baa95
DE
305@defun gdb.breakpoints ()
306Return a sequence holding all of @value{GDBN}'s breakpoints.
1957f6b8
TT
307@xref{Breakpoints In Python}, for more information. In @value{GDBN}
308version 7.11 and earlier, this function returned @code{None} if there
309were no breakpoints. This peculiarity was subsequently fixed, and now
310@code{gdb.breakpoints} returns an empty sequence in this case.
329baa95
DE
311@end defun
312
d8ae99a7
PM
313@defun gdb.rbreak (regex @r{[}, minsyms @r{[}, throttle, @r{[}, symtabs @r{]]]})
314Return a Python list holding a collection of newly set
315@code{gdb.Breakpoint} objects matching function names defined by the
316@var{regex} pattern. If the @var{minsyms} keyword is @code{True}, all
317system functions (those not explicitly defined in the inferior) will
318also be included in the match. The @var{throttle} keyword takes an
319integer that defines the maximum number of pattern matches for
320functions matched by the @var{regex} pattern. If the number of
321matches exceeds the integer value of @var{throttle}, a
322@code{RuntimeError} will be raised and no breakpoints will be created.
323If @var{throttle} is not defined then there is no imposed limit on the
324maximum number of matches and breakpoints to be created. The
325@var{symtabs} keyword takes a Python iterable that yields a collection
326of @code{gdb.Symtab} objects and will restrict the search to those
327functions only contained within the @code{gdb.Symtab} objects.
328@end defun
329
329baa95 330@defun gdb.parameter (parameter)
697aa1b7
EZ
331Return the value of a @value{GDBN} @var{parameter} given by its name,
332a string; the parameter name string may contain spaces if the parameter has a
333multi-part name. For example, @samp{print object} is a valid
334parameter name.
329baa95
DE
335
336If the named parameter does not exist, this function throws a
337@code{gdb.error} (@pxref{Exception Handling}). Otherwise, the
338parameter's value is converted to a Python value of the appropriate
339type, and returned.
340@end defun
341
b583c328
TT
342@defun gdb.set_parameter (name, value)
343Sets the gdb parameter @var{name} to @var{value}. As with
344@code{gdb.parameter}, the parameter name string may contain spaces if
345the parameter has a multi-part name.
346@end defun
347
b583c328
TT
348@defun gdb.with_parameter (name, value)
349Create a Python context manager (for use with the Python
350@command{with} statement) that temporarily sets the gdb parameter
351@var{name} to @var{value}. On exit from the context, the previous
352value will be restored.
353
354This uses @code{gdb.parameter} in its implementation, so it can throw
355the same exceptions as that function.
356
357For example, it's sometimes useful to evaluate some Python code with a
358particular gdb language:
359
360@smallexample
361with gdb.with_parameter('language', 'pascal'):
362 ... language-specific operations
363@end smallexample
364@end defun
365
329baa95
DE
366@defun gdb.history (number)
367Return a value from @value{GDBN}'s value history (@pxref{Value
697aa1b7 368History}). The @var{number} argument indicates which history element to return.
329baa95
DE
369If @var{number} is negative, then @value{GDBN} will take its absolute value
370and count backward from the last element (i.e., the most recent element) to
371find the value to return. If @var{number} is zero, then @value{GDBN} will
372return the most recent element. If the element specified by @var{number}
373doesn't exist in the value history, a @code{gdb.error} exception will be
374raised.
375
376If no exception is raised, the return value is always an instance of
377@code{gdb.Value} (@pxref{Values From Inferior}).
378@end defun
379
540bf37b
AB
380@defun gdb.add_history (value)
381Takes @var{value}, an instance of @code{gdb.Value} (@pxref{Values From
382Inferior}), and appends the value this object represents to
383@value{GDBN}'s value history (@pxref{Value History}), and return an
384integer, its history number. If @var{value} is not a
385@code{gdb.Value}, it is is converted using the @code{gdb.Value}
386constructor. If @var{value} can't be converted to a @code{gdb.Value}
387then a @code{TypeError} is raised.
388
389When a command implemented in Python prints a single @code{gdb.Value}
390as its result, then placing the value into the history will allow the
391user convenient access to those values via CLI history facilities.
392@end defun
393
30a87e90
AB
394@defun gdb.history_count ()
395Return an integer indicating the number of values in @value{GDBN}'s
396value history (@pxref{Value History}).
397@end defun
398
7729052b
TT
399@defun gdb.convenience_variable (name)
400Return the value of the convenience variable (@pxref{Convenience
401Vars}) named @var{name}. @var{name} must be a string. The name
402should not include the @samp{$} that is used to mark a convenience
403variable in an expression. If the convenience variable does not
404exist, then @code{None} is returned.
405@end defun
406
7729052b
TT
407@defun gdb.set_convenience_variable (name, value)
408Set the value of the convenience variable (@pxref{Convenience Vars})
409named @var{name}. @var{name} must be a string. The name should not
410include the @samp{$} that is used to mark a convenience variable in an
411expression. If @var{value} is @code{None}, then the convenience
412variable is removed. Otherwise, if @var{value} is not a
413@code{gdb.Value} (@pxref{Values From Inferior}), it is is converted
414using the @code{gdb.Value} constructor.
415@end defun
416
125862f0 417@defun gdb.parse_and_eval (expression @r{[}, global_context@r{]})
697aa1b7
EZ
418Parse @var{expression}, which must be a string, as an expression in
419the current language, evaluate it, and return the result as a
420@code{gdb.Value}.
329baa95 421
125862f0
TT
422@var{global_context}, if provided, is a boolean indicating whether the
423parsing should be done in the global context. The default is
424@samp{False}, meaning that the current frame or current static context
425should be used.
426
329baa95 427This function can be useful when implementing a new command
740b42ce
AB
428(@pxref{CLI Commands In Python}, @pxref{GDB/MI Commands In Python}),
429as it provides a way to parse the
329baa95 430command's argument as an expression. It is also useful simply to
7729052b 431compute values.
329baa95
DE
432@end defun
433
329baa95
DE
434@defun gdb.find_pc_line (pc)
435Return the @code{gdb.Symtab_and_line} object corresponding to the
436@var{pc} value. @xref{Symbol Tables In Python}. If an invalid
437value of @var{pc} is passed as an argument, then the @code{symtab} and
438@code{line} attributes of the returned @code{gdb.Symtab_and_line} object
8743a9cd
TT
439will be @code{None} and 0 respectively. This is identical to
440@code{gdb.current_progspace().find_pc_line(pc)} and is included for
441historical compatibility.
329baa95
DE
442@end defun
443
b13d7831 444@defun gdb.write (string @r{[}, stream@r{]})
329baa95
DE
445Print a string to @value{GDBN}'s paginated output stream. The
446optional @var{stream} determines the stream to print to. The default
447stream is @value{GDBN}'s standard output stream. Possible stream
448values are:
449
450@table @code
451@findex STDOUT
452@findex gdb.STDOUT
453@item gdb.STDOUT
454@value{GDBN}'s standard output stream.
455
456@findex STDERR
457@findex gdb.STDERR
458@item gdb.STDERR
459@value{GDBN}'s standard error stream.
460
461@findex STDLOG
462@findex gdb.STDLOG
463@item gdb.STDLOG
464@value{GDBN}'s log stream (@pxref{Logging Output}).
465@end table
466
467Writing to @code{sys.stdout} or @code{sys.stderr} will automatically
468call this function and will automatically direct the output to the
469relevant stream.
470@end defun
471
dd083c65 472@defun gdb.flush (@r{[}, stream@r{]})
329baa95
DE
473Flush the buffer of a @value{GDBN} paginated stream so that the
474contents are displayed immediately. @value{GDBN} will flush the
475contents of a stream automatically when it encounters a newline in the
476buffer. The optional @var{stream} determines the stream to flush. The
477default stream is @value{GDBN}'s standard output stream. Possible
478stream values are:
479
480@table @code
481@findex STDOUT
482@findex gdb.STDOUT
483@item gdb.STDOUT
484@value{GDBN}'s standard output stream.
485
486@findex STDERR
487@findex gdb.STDERR
488@item gdb.STDERR
489@value{GDBN}'s standard error stream.
490
491@findex STDLOG
492@findex gdb.STDLOG
493@item gdb.STDLOG
494@value{GDBN}'s log stream (@pxref{Logging Output}).
495
496@end table
497
498Flushing @code{sys.stdout} or @code{sys.stderr} will automatically
499call this function for the relevant stream.
500@end defun
501
329baa95
DE
502@defun gdb.target_charset ()
503Return the name of the current target character set (@pxref{Character
504Sets}). This differs from @code{gdb.parameter('target-charset')} in
505that @samp{auto} is never returned.
506@end defun
507
329baa95
DE
508@defun gdb.target_wide_charset ()
509Return the name of the current target wide character set
510(@pxref{Character Sets}). This differs from
511@code{gdb.parameter('target-wide-charset')} in that @samp{auto} is
512never returned.
513@end defun
514
61671e97
AB
515@defun gdb.host_charset ()
516Return a string, the name of the current host character set
517(@pxref{Character Sets}). This differs from
518@code{gdb.parameter('host-charset')} in that @samp{auto} is never
519returned.
520@end defun
521
329baa95
DE
522@defun gdb.solib_name (address)
523Return the name of the shared library holding the given @var{address}
8743a9cd
TT
524as a string, or @code{None}. This is identical to
525@code{gdb.current_progspace().solib_name(address)} and is included for
526historical compatibility.
329baa95
DE
527@end defun
528
0d2a5839 529@defun gdb.decode_line (@r{[}expression@r{]})
329baa95
DE
530Return locations of the line specified by @var{expression}, or of the
531current line if no argument was given. This function returns a Python
532tuple containing two elements. The first element contains a string
533holding any unparsed section of @var{expression} (or @code{None} if
534the expression has been fully parsed). The second element contains
535either @code{None} or another tuple that contains all the locations
536that match the expression represented as @code{gdb.Symtab_and_line}
537objects (@pxref{Symbol Tables In Python}). If @var{expression} is
538provided, it is decoded the way that @value{GDBN}'s inbuilt
5541bfdc
PA
539@code{break} or @code{edit} commands do (@pxref{Location
540Specifications}).
329baa95
DE
541@end defun
542
543@defun gdb.prompt_hook (current_prompt)
544@anchor{prompt_hook}
545
546If @var{prompt_hook} is callable, @value{GDBN} will call the method
547assigned to this operation before a prompt is displayed by
548@value{GDBN}.
549
550The parameter @code{current_prompt} contains the current @value{GDBN}
551prompt. This method must return a Python string, or @code{None}. If
552a string is returned, the @value{GDBN} prompt will be set to that
553string. If @code{None} is returned, @value{GDBN} will continue to use
554the current prompt.
555
556Some prompts cannot be substituted in @value{GDBN}. Secondary prompts
557such as those used by readline for command input, and annotation
558related prompts are prohibited from being changed.
559@end defun
560
15e15b2d 561@anchor{gdb_architecture_names}
8b87fbe6
AB
562@defun gdb.architecture_names ()
563Return a list containing all of the architecture names that the
564current build of @value{GDBN} supports. Each architecture name is a
565string. The names returned in this list are the same names as are
566returned from @code{gdb.Architecture.name}
567(@pxref{gdbpy_architecture_name,,Architecture.name}).
568@end defun
569
0e3b7c25
AB
570@anchor{gdbpy_connections}
571@defun gdb.connections
572Return a list of @code{gdb.TargetConnection} objects, one for each
573currently active connection (@pxref{Connections In Python}). The
574connection objects are in no particular order in the returned list.
575@end defun
576
ebb83b77 577@defun gdb.format_address (address @r{[}, progspace, architecture@r{]})
25209e2c
AB
578Return a string in the format @samp{@var{addr}
579<@var{symbol}+@var{offset}>}, where @var{addr} is @var{address}
580formatted in hexadecimal, @var{symbol} is the symbol whose address is
581the nearest to @var{address} and below it in memory, and @var{offset}
582is the offset from @var{symbol} to @var{address} in decimal.
583
584If no suitable @var{symbol} was found, then the
585<@var{symbol}+@var{offset}> part is not included in the returned
586string, instead the returned string will just contain the
587@var{address} formatted as hexadecimal. How far @value{GDBN} looks
588back for a suitable symbol can be controlled with @kbd{set print
589max-symbolic-offset} (@pxref{Print Settings}).
590
591Additionally, the returned string can include file name and line
592number information when @kbd{set print symbol-filename on}
593(@pxref{Print Settings}), in this case the format of the returned
594string is @samp{@var{addr} <@var{symbol}+@var{offset}> at
595@var{filename}:@var{line-number}}.
596
597
598The @var{progspace} is the gdb.Progspace in which @var{symbol} is
599looked up, and @var{architecture} is used when formatting @var{addr},
600e.g.@: in order to determine the size of an address in bytes.
601
602If neither @var{progspace} or @var{architecture} are passed, then by
603default @value{GDBN} will use the program space and architecture of
604the currently selected inferior, thus, the following two calls are
605equivalent:
606
607@smallexample
608gdb.format_address(address)
609gdb.format_address(address,
610 gdb.selected_inferior().progspace,
611 gdb.selected_inferior().architecture())
612@end smallexample
613
614It is not valid to only pass one of @var{progspace} or
615@var{architecture}, either they must both be provided, or neither must
616be provided (and the defaults will be used).
617
618This method uses the same mechanism for formatting address, symbol,
619and offset information as core @value{GDBN} does in commands such as
620@kbd{disassemble}.
621
622Here are some examples of the possible string formats:
623
624@smallexample
6250x00001042
6260x00001042 <symbol+16>
6270x00001042 <symbol+16 at file.c:123>
628@end smallexample
629@end defun
630
80fa4b2a
TT
631@defun gdb.current_language ()
632Return the name of the current language as a string. Unlike
633@code{gdb.parameter('language')}, this function will never return
634@samp{auto}. If a @code{gdb.Frame} object is available (@pxref{Frames
635In Python}), the @code{language} method might be preferable in some
636cases, as that is not affected by the user's language setting.
637@end defun
638
560c121c
TT
639@node Threading in GDB
640@subsubsection Threading in GDB
641
642@value{GDBN} is not thread-safe. If your Python program uses multiple
643threads, you must be careful to only call @value{GDBN}-specific
644functions in the @value{GDBN} thread. @value{GDBN} provides some
645functions to help with this.
646
647@defun gdb.block_signals ()
648As mentioned earlier (@pxref{Basic Python}), certain signals must be
649delivered to the @value{GDBN} main thread. The @code{block_signals}
650function returns a context manager that will block these signals on
651entry. This can be used when starting a new thread to ensure that the
652signals are blocked there, like:
653
654@smallexample
655with gdb.block_signals():
656 start_new_thread()
657@end smallexample
658@end defun
659
660@deftp {class} gdb.Thread
661This is a subclass of Python's @code{threading.Thread} class. It
662overrides the @code{start} method to call @code{block_signals}, making
663this an easy-to-use drop-in replacement for creating threads that will
664work well in @value{GDBN}.
665@end deftp
666
3a12e74e
TT
667@defun gdb.interrupt ()
668This causes @value{GDBN} to react as if the user had typed a control-C
669character at the terminal. That is, if the inferior is running, it is
670interrupted; if a @value{GDBN} command is executing, it is stopped;
671and if a Python command is running, @code{KeyboardInterrupt} will be
672raised.
673
674Unlike most Python APIs in @value{GDBN}, @code{interrupt} is
675thread-safe.
676@end defun
677
560c121c
TT
678@defun gdb.post_event (event)
679Put @var{event}, a callable object taking no arguments, into
680@value{GDBN}'s internal event queue. This callable will be invoked at
681some later point, during @value{GDBN}'s event processing. Events
682posted using @code{post_event} will be run in the order in which they
683were posted; however, there is no way to know when they will be
684processed relative to other events inside @value{GDBN}.
685
686Unlike most Python APIs in @value{GDBN}, @code{post_event} is
687thread-safe. For example:
688
689@smallexample
690(@value{GDBP}) python
691>import threading
692>
693>class Writer():
694> def __init__(self, message):
695> self.message = message;
696> def __call__(self):
697> gdb.write(self.message)
698>
699>class MyThread1 (threading.Thread):
700> def run (self):
701> gdb.post_event(Writer("Hello "))
702>
703>class MyThread2 (threading.Thread):
704> def run (self):
705> gdb.post_event(Writer("World\n"))
706>
707>MyThread1().start()
708>MyThread2().start()
709>end
710(@value{GDBP}) Hello World
711@end smallexample
712@end defun
713
714
329baa95
DE
715@node Exception Handling
716@subsubsection Exception Handling
717@cindex python exceptions
718@cindex exceptions, python
719
720When executing the @code{python} command, Python exceptions
721uncaught within the Python code are translated to calls to
722@value{GDBN} error-reporting mechanism. If the command that called
723@code{python} does not handle the error, @value{GDBN} will
724terminate it and print an error message containing the Python
725exception name, the associated value, and the Python call stack
726backtrace at the point where the exception was raised. Example:
727
728@smallexample
729(@value{GDBP}) python print foo
730Traceback (most recent call last):
731 File "<string>", line 1, in <module>
732NameError: name 'foo' is not defined
733@end smallexample
734
735@value{GDBN} errors that happen in @value{GDBN} commands invoked by
736Python code are converted to Python exceptions. The type of the
737Python exception depends on the error.
738
739@ftable @code
740@item gdb.error
741This is the base class for most exceptions generated by @value{GDBN}.
742It is derived from @code{RuntimeError}, for compatibility with earlier
743versions of @value{GDBN}.
744
745If an error occurring in @value{GDBN} does not fit into some more
746specific category, then the generated exception will have this type.
747
748@item gdb.MemoryError
749This is a subclass of @code{gdb.error} which is thrown when an
750operation tried to access invalid memory in the inferior.
751
752@item KeyboardInterrupt
753User interrupt (via @kbd{C-c} or by typing @kbd{q} at a pagination
754prompt) is translated to a Python @code{KeyboardInterrupt} exception.
755@end ftable
756
757In all cases, your exception handler will see the @value{GDBN} error
758message as its value and the Python call stack backtrace at the Python
33b5899f 759statement closest to where the @value{GDBN} error occurred as the
329baa95
DE
760traceback.
761
4a5a194a
TT
762
763When implementing @value{GDBN} commands in Python via
764@code{gdb.Command}, or functions via @code{gdb.Function}, it is useful
765to be able to throw an exception that doesn't cause a traceback to be
766printed. For example, the user may have invoked the command
767incorrectly. @value{GDBN} provides a special exception class that can
768be used for this purpose.
769
770@ftable @code
771@item gdb.GdbError
772When thrown from a command or function, this exception will cause the
773command or function to fail, but the Python stack will not be
774displayed. @value{GDBN} does not throw this exception itself, but
775rather recognizes it when thrown from user Python code. Example:
329baa95
DE
776
777@smallexample
778(gdb) python
779>class HelloWorld (gdb.Command):
780> """Greet the whole world."""
781> def __init__ (self):
782> super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
783> def invoke (self, args, from_tty):
784> argv = gdb.string_to_argv (args)
785> if len (argv) != 0:
786> raise gdb.GdbError ("hello-world takes no arguments")
f3bdc2db 787> print ("Hello, World!")
329baa95
DE
788>HelloWorld ()
789>end
790(gdb) hello-world 42
791hello-world takes no arguments
792@end smallexample
4a5a194a 793@end ftable
329baa95
DE
794
795@node Values From Inferior
796@subsubsection Values From Inferior
797@cindex values from inferior, with Python
798@cindex python, working with values from inferior
799
800@cindex @code{gdb.Value}
801@value{GDBN} provides values it obtains from the inferior program in
802an object of type @code{gdb.Value}. @value{GDBN} uses this object
803for its internal bookkeeping of the inferior's values, and for
804fetching values when necessary.
805
806Inferior values that are simple scalars can be used directly in
807Python expressions that are valid for the value's data type. Here's
808an example for an integer or floating-point value @code{some_val}:
809
810@smallexample
811bar = some_val + 2
812@end smallexample
813
814@noindent
815As result of this, @code{bar} will also be a @code{gdb.Value} object
f7bd0f78
SC
816whose values are of the same type as those of @code{some_val}. Valid
817Python operations can also be performed on @code{gdb.Value} objects
818representing a @code{struct} or @code{class} object. For such cases,
819the overloaded operator (if present), is used to perform the operation.
820For example, if @code{val1} and @code{val2} are @code{gdb.Value} objects
821representing instances of a @code{class} which overloads the @code{+}
822operator, then one can use the @code{+} operator in their Python script
823as follows:
824
825@smallexample
826val3 = val1 + val2
827@end smallexample
828
829@noindent
830The result of the operation @code{val3} is also a @code{gdb.Value}
831object corresponding to the value returned by the overloaded @code{+}
832operator. In general, overloaded operators are invoked for the
833following operations: @code{+} (binary addition), @code{-} (binary
834subtraction), @code{*} (multiplication), @code{/}, @code{%}, @code{<<},
835@code{>>}, @code{|}, @code{&}, @code{^}.
329baa95
DE
836
837Inferior values that are structures or instances of some class can
838be accessed using the Python @dfn{dictionary syntax}. For example, if
839@code{some_val} is a @code{gdb.Value} instance holding a structure, you
840can access its @code{foo} element with:
841
842@smallexample
843bar = some_val['foo']
844@end smallexample
845
846@cindex getting structure elements using gdb.Field objects as subscripts
847Again, @code{bar} will also be a @code{gdb.Value} object. Structure
848elements can also be accessed by using @code{gdb.Field} objects as
849subscripts (@pxref{Types In Python}, for more information on
850@code{gdb.Field} objects). For example, if @code{foo_field} is a
851@code{gdb.Field} object corresponding to element @code{foo} of the above
852structure, then @code{bar} can also be accessed as follows:
853
854@smallexample
855bar = some_val[foo_field]
856@end smallexample
857
4f7d9afb
TT
858If a @code{gdb.Value} has array or pointer type, an integer index can
859be used to access elements.
860
861@smallexample
862result = some_array[23]
863@end smallexample
864
329baa95
DE
865A @code{gdb.Value} that represents a function can be executed via
866inferior function call. Any arguments provided to the call must match
867the function's prototype, and must be provided in the order specified
868by that prototype.
869
870For example, @code{some_val} is a @code{gdb.Value} instance
871representing a function that takes two integers as arguments. To
872execute this function, call it like so:
873
874@smallexample
875result = some_val (10,20)
876@end smallexample
877
878Any values returned from a function call will be stored as a
879@code{gdb.Value}.
880
881The following attributes are provided:
882
883@defvar Value.address
884If this object is addressable, this read-only attribute holds a
885@code{gdb.Value} object representing the address. Otherwise,
886this attribute holds @code{None}.
887@end defvar
888
889@cindex optimized out value in Python
890@defvar Value.is_optimized_out
891This read-only boolean attribute is true if the compiler optimized out
892this value, thus it is not available for fetching from the inferior.
893@end defvar
894
895@defvar Value.type
896The type of this @code{gdb.Value}. The value of this attribute is a
897@code{gdb.Type} object (@pxref{Types In Python}).
898@end defvar
899
900@defvar Value.dynamic_type
9da10427
TT
901The dynamic type of this @code{gdb.Value}. This uses the object's
902virtual table and the C@t{++} run-time type information
903(@acronym{RTTI}) to determine the dynamic type of the value. If this
904value is of class type, it will return the class in which the value is
905embedded, if any. If this value is of pointer or reference to a class
906type, it will compute the dynamic type of the referenced object, and
907return a pointer or reference to that type, respectively. In all
908other cases, it will return the value's static type.
329baa95
DE
909
910Note that this feature will only work when debugging a C@t{++} program
911that includes @acronym{RTTI} for the object in question. Otherwise,
912it will just return the static type of the value as in @kbd{ptype foo}
913(@pxref{Symbols, ptype}).
914@end defvar
915
916@defvar Value.is_lazy
917The value of this read-only boolean attribute is @code{True} if this
918@code{gdb.Value} has not yet been fetched from the inferior.
919@value{GDBN} does not fetch values until necessary, for efficiency.
920For example:
921
922@smallexample
923myval = gdb.parse_and_eval ('somevar')
924@end smallexample
925
926The value of @code{somevar} is not fetched at this time. It will be
927fetched when the value is needed, or when the @code{fetch_lazy}
928method is invoked.
929@end defvar
930
ef8cf909
AB
931@defvar Value.bytes
932The value of this attribute is a @code{bytes} object containing the
933bytes that make up this @code{Value}'s complete value in little endian
934order. If the complete contents of this value are not available then
935accessing this attribute will raise an exception.
936
937This attribute can also be assigned to. The new value should be a
938buffer object (e.g.@: a @code{bytes} object), the length of the new
939buffer must exactly match the length of this @code{Value}'s type. The
940bytes values in the new buffer should be in little endian order.
941
942As with @code{Value.assign} (@pxref{Value.assign}), if this value
943cannot be assigned to, then an exception will be thrown.
944@end defvar
945
329baa95
DE
946The following methods are provided:
947
ebb83b77 948@defun Value.__init__ (val)
329baa95
DE
949Many Python values can be converted directly to a @code{gdb.Value} via
950this object initializer. Specifically:
951
952@table @asis
953@item Python boolean
954A Python boolean is converted to the boolean type from the current
955language.
956
957@item Python integer
958A Python integer is converted to the C @code{long} type for the
959current architecture.
960
961@item Python long
962A Python long is converted to the C @code{long long} type for the
963current architecture.
964
965@item Python float
966A Python float is converted to the C @code{double} type for the
967current architecture.
968
969@item Python string
b3ce5e5f
DE
970A Python string is converted to a target string in the current target
971language using the current target encoding.
972If a character cannot be represented in the current target encoding,
973then an exception is thrown.
329baa95
DE
974
975@item @code{gdb.Value}
976If @code{val} is a @code{gdb.Value}, then a copy of the value is made.
977
978@item @code{gdb.LazyString}
979If @code{val} is a @code{gdb.LazyString} (@pxref{Lazy Strings In
980Python}), then the lazy string's @code{value} method is called, and
981its result is used.
982@end table
983@end defun
984
ebb83b77 985@defun Value.__init__ (val, type)
af54ade9
KB
986This second form of the @code{gdb.Value} constructor returns a
987@code{gdb.Value} of type @var{type} where the value contents are taken
988from the Python buffer object specified by @var{val}. The number of
989bytes in the Python buffer object must be greater than or equal to the
990size of @var{type}.
2988a360
AB
991
992If @var{type} is @code{None} then this version of @code{__init__}
993behaves as though @var{type} was not passed at all.
af54ade9
KB
994@end defun
995
ef8cf909 996@anchor{Value.assign}
ed801569
TT
997@defun Value.assign (rhs)
998Assign @var{rhs} to this value, and return @code{None}. If this value
999cannot be assigned to, or if the assignment is invalid for some reason
1000(for example a type-checking failure), an exception will be thrown.
1001@end defun
1002
329baa95
DE
1003@defun Value.cast (type)
1004Return a new instance of @code{gdb.Value} that is the result of
1005casting this instance to the type described by @var{type}, which must
1006be a @code{gdb.Type} object. If the cast cannot be performed for some
1007reason, this method throws an exception.
1008@end defun
1009
1010@defun Value.dereference ()
1011For pointer data types, this method returns a new @code{gdb.Value} object
1012whose contents is the object pointed to by the pointer. For example, if
1013@code{foo} is a C pointer to an @code{int}, declared in your C program as
1014
1015@smallexample
1016int *foo;
1017@end smallexample
1018
1019@noindent
1020then you can use the corresponding @code{gdb.Value} to access what
1021@code{foo} points to like this:
1022
1023@smallexample
1024bar = foo.dereference ()
1025@end smallexample
1026
1027The result @code{bar} will be a @code{gdb.Value} object holding the
1028value pointed to by @code{foo}.
1029
1030A similar function @code{Value.referenced_value} exists which also
760f7560 1031returns @code{gdb.Value} objects corresponding to the values pointed to
329baa95
DE
1032by pointer values (and additionally, values referenced by reference
1033values). However, the behavior of @code{Value.dereference}
1034differs from @code{Value.referenced_value} by the fact that the
1035behavior of @code{Value.dereference} is identical to applying the C
1036unary operator @code{*} on a given value. For example, consider a
1037reference to a pointer @code{ptrref}, declared in your C@t{++} program
1038as
1039
1040@smallexample
1041typedef int *intptr;
1042...
1043int val = 10;
1044intptr ptr = &val;
1045intptr &ptrref = ptr;
1046@end smallexample
1047
1048Though @code{ptrref} is a reference value, one can apply the method
1049@code{Value.dereference} to the @code{gdb.Value} object corresponding
1050to it and obtain a @code{gdb.Value} which is identical to that
1051corresponding to @code{val}. However, if you apply the method
1052@code{Value.referenced_value}, the result would be a @code{gdb.Value}
1053object identical to that corresponding to @code{ptr}.
1054
1055@smallexample
1056py_ptrref = gdb.parse_and_eval ("ptrref")
1057py_val = py_ptrref.dereference ()
1058py_ptr = py_ptrref.referenced_value ()
1059@end smallexample
1060
1061The @code{gdb.Value} object @code{py_val} is identical to that
1062corresponding to @code{val}, and @code{py_ptr} is identical to that
1063corresponding to @code{ptr}. In general, @code{Value.dereference} can
1064be applied whenever the C unary operator @code{*} can be applied
1065to the corresponding C value. For those cases where applying both
1066@code{Value.dereference} and @code{Value.referenced_value} is allowed,
1067the results obtained need not be identical (as we have seen in the above
1068example). The results are however identical when applied on
1069@code{gdb.Value} objects corresponding to pointers (@code{gdb.Value}
1070objects with type code @code{TYPE_CODE_PTR}) in a C/C@t{++} program.
1071@end defun
1072
1073@defun Value.referenced_value ()
1074For pointer or reference data types, this method returns a new
1075@code{gdb.Value} object corresponding to the value referenced by the
1076pointer/reference value. For pointer data types,
1077@code{Value.dereference} and @code{Value.referenced_value} produce
1078identical results. The difference between these methods is that
1079@code{Value.dereference} cannot get the values referenced by reference
1080values. For example, consider a reference to an @code{int}, declared
1081in your C@t{++} program as
1082
1083@smallexample
1084int val = 10;
1085int &ref = val;
1086@end smallexample
1087
1088@noindent
1089then applying @code{Value.dereference} to the @code{gdb.Value} object
1090corresponding to @code{ref} will result in an error, while applying
1091@code{Value.referenced_value} will result in a @code{gdb.Value} object
1092identical to that corresponding to @code{val}.
1093
1094@smallexample
1095py_ref = gdb.parse_and_eval ("ref")
1096er_ref = py_ref.dereference () # Results in error
1097py_val = py_ref.referenced_value () # Returns the referenced value
1098@end smallexample
1099
1100The @code{gdb.Value} object @code{py_val} is identical to that
1101corresponding to @code{val}.
1102@end defun
1103
4c082a81
SC
1104@defun Value.reference_value ()
1105Return a @code{gdb.Value} object which is a reference to the value
1106encapsulated by this instance.
1107@end defun
1108
1109@defun Value.const_value ()
1110Return a @code{gdb.Value} object which is a @code{const} version of the
1111value encapsulated by this instance.
1112@end defun
1113
329baa95
DE
1114@defun Value.dynamic_cast (type)
1115Like @code{Value.cast}, but works as if the C@t{++} @code{dynamic_cast}
1116operator were used. Consult a C@t{++} reference for details.
1117@end defun
1118
1119@defun Value.reinterpret_cast (type)
1120Like @code{Value.cast}, but works as if the C@t{++} @code{reinterpret_cast}
1121operator were used. Consult a C@t{++} reference for details.
1122@end defun
1123
52093e1b
MB
1124@defun Value.format_string (...)
1125Convert a @code{gdb.Value} to a string, similarly to what the @code{print}
1126command does. Invoked with no arguments, this is equivalent to calling
1127the @code{str} function on the @code{gdb.Value}. The representation of
1128the same value may change across different versions of @value{GDBN}, so
1129you shouldn't, for instance, parse the strings returned by this method.
1130
1131All the arguments are keyword only. If an argument is not specified, the
1132current global default setting is used.
1133
1134@table @code
1135@item raw
1136@code{True} if pretty-printers (@pxref{Pretty Printing}) should not be
1137used to format the value. @code{False} if enabled pretty-printers
1138matching the type represented by the @code{gdb.Value} should be used to
1139format it.
1140
1141@item pretty_arrays
1142@code{True} if arrays should be pretty printed to be more convenient to
1143read, @code{False} if they shouldn't (see @code{set print array} in
1144@ref{Print Settings}).
1145
1146@item pretty_structs
1147@code{True} if structs should be pretty printed to be more convenient to
1148read, @code{False} if they shouldn't (see @code{set print pretty} in
1149@ref{Print Settings}).
1150
1151@item array_indexes
1152@code{True} if array indexes should be included in the string
1153representation of arrays, @code{False} if they shouldn't (see @code{set
1154print array-indexes} in @ref{Print Settings}).
1155
1156@item symbols
1157@code{True} if the string representation of a pointer should include the
1158corresponding symbol name (if one exists), @code{False} if it shouldn't
1159(see @code{set print symbol} in @ref{Print Settings}).
1160
1161@item unions
1162@code{True} if unions which are contained in other structures or unions
1163should be expanded, @code{False} if they shouldn't (see @code{set print
1164union} in @ref{Print Settings}).
1165
4aea001f
HD
1166@item address
1167@code{True} if the string representation of a pointer should include the
1168address, @code{False} if it shouldn't (see @code{set print address} in
1169@ref{Print Settings}).
1170
3f52a090
EL
1171@item nibbles
1172@code{True} if binary values should be displayed in groups of four bits,
1173known as nibbles. @code{False} if it shouldn't (@pxref{Print Settings,
1174set print nibbles}).
1175
52093e1b
MB
1176@item deref_refs
1177@code{True} if C@t{++} references should be resolved to the value they
1178refer to, @code{False} (the default) if they shouldn't. Note that, unlike
1179for the @code{print} command, references are not automatically expanded
1180when using the @code{format_string} method or the @code{str}
1181function. There is no global @code{print} setting to change the default
1182behaviour.
1183
1184@item actual_objects
1185@code{True} if the representation of a pointer to an object should
1186identify the @emph{actual} (derived) type of the object rather than the
1187@emph{declared} type, using the virtual function table. @code{False} if
1188the @emph{declared} type should be used. (See @code{set print object} in
1189@ref{Print Settings}).
1190
9f121239 1191@item static_members
52093e1b
MB
1192@code{True} if static members should be included in the string
1193representation of a C@t{++} object, @code{False} if they shouldn't (see
1194@code{set print static-members} in @ref{Print Settings}).
1195
76b58849
AB
1196@item max_characters
1197Number of string characters to print, @code{0} to follow
1198@code{max_elements}, or @code{UINT_MAX} to print an unlimited number
1199of characters (see @code{set print characters} in @ref{Print Settings}).
1200
52093e1b
MB
1201@item max_elements
1202Number of array elements to print, or @code{0} to print an unlimited
1203number of elements (see @code{set print elements} in @ref{Print
1204Settings}).
1205
2e62ab40
AB
1206@item max_depth
1207The maximum depth to print for nested structs and unions, or @code{-1}
1208to print an unlimited number of elements (see @code{set print
1209max-depth} in @ref{Print Settings}).
1210
52093e1b
MB
1211@item repeat_threshold
1212Set the threshold for suppressing display of repeated array elements, or
1213@code{0} to represent all elements, even if repeated. (See @code{set
1214print repeats} in @ref{Print Settings}).
1215
1216@item format
1217A string containing a single character representing the format to use for
1218the returned string. For instance, @code{'x'} is equivalent to using the
1219@value{GDBN} command @code{print} with the @code{/x} option and formats
1220the value as a hexadecimal number.
0642912e
AB
1221
1222@item styling
1223@code{True} if @value{GDBN} should apply styling to the returned
1224string. When styling is applied, the returned string might contain
1225ANSI terminal escape sequences. Escape sequences will only be
1226included if styling is turned on, see @ref{Output Styling}.
1227Additionally, @value{GDBN} only styles some value contents, so not
1228every output string will contain escape sequences.
1229
1230When @code{False}, which is the default, no output styling is applied.
72be9d6b
TT
1231
1232@item summary
1233@code{True} when just a summary should be printed. In this mode,
1234scalar values are printed in their entirety, but aggregates such as
1235structures or unions are omitted. This mode is used by @code{set
1236print frame-arguments scalars} (@pxref{Print Settings}).
52093e1b
MB
1237@end table
1238@end defun
1239
59668c9d
TT
1240@defun Value.to_array ()
1241If this value is array-like (@pxref{Type.is_array_like}), then this
1242method converts it to an array, which is returned. If this value is
1243already an array, it is simply returned. Otherwise, an exception is
1244throw.
1245@end defun
1246
329baa95
DE
1247@defun Value.string (@r{[}encoding@r{[}, errors@r{[}, length@r{]]]})
1248If this @code{gdb.Value} represents a string, then this method
1249converts the contents to a Python string. Otherwise, this method will
1250throw an exception.
1251
b3ce5e5f
DE
1252Values are interpreted as strings according to the rules of the
1253current language. If the optional length argument is given, the
1254string will be converted to that length, and will include any embedded
1255zeroes that the string may contain. Otherwise, for languages
1256where the string is zero-terminated, the entire string will be
1257converted.
329baa95 1258
b3ce5e5f
DE
1259For example, in C-like languages, a value is a string if it is a pointer
1260to or an array of characters or ints of type @code{wchar_t}, @code{char16_t},
1261or @code{char32_t}.
329baa95
DE
1262
1263If the optional @var{encoding} argument is given, it must be a string
1264naming the encoding of the string in the @code{gdb.Value}, such as
1265@code{"ascii"}, @code{"iso-8859-6"} or @code{"utf-8"}. It accepts
1266the same encodings as the corresponding argument to Python's
1267@code{string.decode} method, and the Python codec machinery will be used
1268to convert the string. If @var{encoding} is not given, or if
1269@var{encoding} is the empty string, then either the @code{target-charset}
1270(@pxref{Character Sets}) will be used, or a language-specific encoding
1271will be used, if the current language is able to supply one.
1272
1273The optional @var{errors} argument is the same as the corresponding
1274argument to Python's @code{string.decode} method.
1275
1276If the optional @var{length} argument is given, the string will be
1277fetched and converted to the given length.
1278@end defun
1279
1280@defun Value.lazy_string (@r{[}encoding @r{[}, length@r{]]})
1281If this @code{gdb.Value} represents a string, then this method
1282converts the contents to a @code{gdb.LazyString} (@pxref{Lazy Strings
1283In Python}). Otherwise, this method will throw an exception.
1284
1285If the optional @var{encoding} argument is given, it must be a string
1286naming the encoding of the @code{gdb.LazyString}. Some examples are:
1287@samp{ascii}, @samp{iso-8859-6} or @samp{utf-8}. If the
1288@var{encoding} argument is an encoding that @value{GDBN} does
1289recognize, @value{GDBN} will raise an error.
1290
1291When a lazy string is printed, the @value{GDBN} encoding machinery is
1292used to convert the string during printing. If the optional
1293@var{encoding} argument is not provided, or is an empty string,
1294@value{GDBN} will automatically select the encoding most suitable for
1295the string type. For further information on encoding in @value{GDBN}
1296please see @ref{Character Sets}.
1297
1298If the optional @var{length} argument is given, the string will be
1299fetched and encoded to the length of characters specified. If
1300the @var{length} argument is not provided, the string will be fetched
1301and encoded until a null of appropriate width is found.
1302@end defun
1303
1304@defun Value.fetch_lazy ()
1305If the @code{gdb.Value} object is currently a lazy value
1306(@code{gdb.Value.is_lazy} is @code{True}), then the value is
1307fetched from the inferior. Any errors that occur in the process
1308will produce a Python exception.
1309
1310If the @code{gdb.Value} object is not a lazy value, this method
1311has no effect.
1312
1313This method does not return a value.
1314@end defun
1315
1316
1317@node Types In Python
1318@subsubsection Types In Python
1319@cindex types in Python
1320@cindex Python, working with types
1321
1322@tindex gdb.Type
1323@value{GDBN} represents types from the inferior using the class
1324@code{gdb.Type}.
1325
1326The following type-related functions are available in the @code{gdb}
1327module:
1328
329baa95 1329@defun gdb.lookup_type (name @r{[}, block@r{]})
697aa1b7 1330This function looks up a type by its @var{name}, which must be a string.
329baa95
DE
1331
1332If @var{block} is given, then @var{name} is looked up in that scope.
1333Otherwise, it is searched for globally.
1334
1335Ordinarily, this function will return an instance of @code{gdb.Type}.
1336If the named type cannot be found, it will throw an exception.
1337@end defun
1338
d3771fe2
TT
1339Integer types can be found without looking them up by name.
1340@xref{Architectures In Python}, for the @code{integer_type} method.
1341
329baa95
DE
1342If the type is a structure or class type, or an enum type, the fields
1343of that type can be accessed using the Python @dfn{dictionary syntax}.
1344For example, if @code{some_type} is a @code{gdb.Type} instance holding
1345a structure type, you can access its @code{foo} field with:
1346
1347@smallexample
1348bar = some_type['foo']
1349@end smallexample
1350
1351@code{bar} will be a @code{gdb.Field} object; see below under the
1352description of the @code{Type.fields} method for a description of the
1353@code{gdb.Field} class.
1354
1355An instance of @code{Type} has the following attributes:
1356
6d7bb824
TT
1357@defvar Type.alignof
1358The alignment of this type, in bytes. Type alignment comes from the
1359debugging information; if it was not specified, then @value{GDBN} will
1360use the relevant ABI to try to determine the alignment. In some
1361cases, even this is not possible, and zero will be returned.
1362@end defvar
1363
329baa95
DE
1364@defvar Type.code
1365The type code for this type. The type code will be one of the
1366@code{TYPE_CODE_} constants defined below.
1367@end defvar
1368
1acda803
TT
1369@defvar Type.dynamic
1370A boolean indicating whether this type is dynamic. In some
1371situations, such as Rust @code{enum} types or Ada variant records, the
45fc7c99
TT
1372concrete type of a value may vary depending on its contents. That is,
1373the declared type of a variable, or the type returned by
1374@code{gdb.lookup_type} may be dynamic; while the type of the
1375variable's value will be a concrete instance of that dynamic type.
1376
1377For example, consider this code:
1378@smallexample
1379int n;
1380int array[n];
1381@end smallexample
1382
1383Here, at least conceptually (whether your compiler actually does this
1384is a separate issue), examining @w{@code{gdb.lookup_symbol("array", ...).type}}
1385could yield a @code{gdb.Type} which reports a size of @code{None}.
1386This is the dynamic type.
1387
1388However, examining @code{gdb.parse_and_eval("array").type} would yield
1389a concrete type, whose length would be known.
1acda803
TT
1390@end defvar
1391
329baa95
DE
1392@defvar Type.name
1393The name of this type. If this type has no name, then @code{None}
1394is returned.
1395@end defvar
1396
1397@defvar Type.sizeof
1398The size of this type, in target @code{char} units. Usually, a
1399target's @code{char} type will be an 8-bit byte. However, on some
1acda803
TT
1400unusual platforms, this type may have a different size. A dynamic
1401type may not have a fixed size; in this case, this attribute's value
1402will be @code{None}.
329baa95
DE
1403@end defvar
1404
1405@defvar Type.tag
1406The tag name for this type. The tag name is the name after
1407@code{struct}, @code{union}, or @code{enum} in C and C@t{++}; not all
1408languages have this concept. If this type has no tag name, then
1409@code{None} is returned.
1410@end defvar
1411
e1f2e1a2
CB
1412@defvar Type.objfile
1413The @code{gdb.Objfile} that this type was defined in, or @code{None} if
1414there is no associated objfile.
1415@end defvar
1416
ee6a3d9e
AB
1417@defvar Type.is_scalar
1418This property is @code{True} if the type is a scalar type, otherwise,
1419this property is @code{False}. Examples of non-scalar types include
1420structures, unions, and classes.
1421@end defvar
1422
551b380f
AB
1423@defvar Type.is_signed
1424For scalar types (those for which @code{Type.is_scalar} is
1425@code{True}), this property is @code{True} if the type is signed,
1426otherwise this property is @code{False}.
1427
1428Attempting to read this property for a non-scalar type (a type for
1429which @code{Type.is_scalar} is @code{False}), will raise a
1430@code{ValueError}.
1431@end defvar
1432
59668c9d
TT
1433@defvar Type.is_array_like
1434@anchor{Type.is_array_like}
1435A boolean indicating whether this type is array-like.
1436
1437Some languages have array-like objects that are represented internally
1438as structures. For example, this is true for a Rust slice type, or
1439for an Ada unconstrained array. @value{GDBN} may know about these
1440types. This determination is done based on the language from which
1441the type originated.
1442@end defvar
1443
1444@defvar Type.is_string_like
1445A boolean indicating whether this type is string-like. Like
1446@code{Type.is_array_like}, this is determined based on the originating
1447language of the type.
1448@end defvar
1449
329baa95
DE
1450The following methods are provided:
1451
1452@defun Type.fields ()
fa94b3a7
SM
1453
1454Return the fields of this type. The behavior depends on the type code:
1455
1456@itemize @bullet
1457
1458@item
1459For structure and union types, this method returns the fields.
1460
fa94b3a7
SM
1461@item
1462Enum types have one field per enum constant.
1463
1464@item
1465Function and method types have one field per parameter. The base types of
1466C@t{++} classes are also represented as fields.
1467
1468@item
1469Array types have one field representing the array's range.
1470
1471@item
1472If the type does not fit into one of these categories, a @code{TypeError}
1473is raised.
1474
1475@end itemize
329baa95
DE
1476
1477Each field is a @code{gdb.Field} object, with some pre-defined attributes:
1478@table @code
1479@item bitpos
1480This attribute is not available for @code{enum} or @code{static}
9c37b5ae 1481(as in C@t{++}) fields. The value is the position, counting
1acda803
TT
1482in bits, from the start of the containing type. Note that, in a
1483dynamic type, the position of a field may not be constant. In this
45fc7c99
TT
1484case, the value will be @code{None}. Also, a dynamic type may have
1485fields that do not appear in a corresponding concrete type.
329baa95
DE
1486
1487@item enumval
1488This attribute is only available for @code{enum} fields, and its value
1489is the enumeration member's integer representation.
1490
1491@item name
1492The name of the field, or @code{None} for anonymous fields.
1493
1494@item artificial
1495This is @code{True} if the field is artificial, usually meaning that
1496it was provided by the compiler and not the user. This attribute is
1497always provided, and is @code{False} if the field is not artificial.
1498
1499@item is_base_class
1500This is @code{True} if the field represents a base class of a C@t{++}
1501structure. This attribute is always provided, and is @code{False}
1502if the field is not a base class of the type that is the argument of
1503@code{fields}, or if that type was not a C@t{++} class.
1504
1505@item bitsize
1506If the field is packed, or is a bitfield, then this will have a
1507non-zero value, which is the size of the field in bits. Otherwise,
1508this will be zero; in this case the field's size is given by its type.
1509
1510@item type
1511The type of the field. This is usually an instance of @code{Type},
1512but it can be @code{None} in some situations.
1513
1514@item parent_type
1515The type which contains this field. This is an instance of
1516@code{gdb.Type}.
1517@end table
1518@end defun
1519
ebb83b77 1520@defun Type.array (n1 @r{[}, n2@r{]})
329baa95
DE
1521Return a new @code{gdb.Type} object which represents an array of this
1522type. If one argument is given, it is the inclusive upper bound of
1523the array; in this case the lower bound is zero. If two arguments are
1524given, the first argument is the lower bound of the array, and the
1525second argument is the upper bound of the array. An array's length
1526must not be negative, but the bounds can be.
1527@end defun
1528
ebb83b77 1529@defun Type.vector (n1 @r{[}, n2@r{]})
329baa95
DE
1530Return a new @code{gdb.Type} object which represents a vector of this
1531type. If one argument is given, it is the inclusive upper bound of
1532the vector; in this case the lower bound is zero. If two arguments are
1533given, the first argument is the lower bound of the vector, and the
1534second argument is the upper bound of the vector. A vector's length
1535must not be negative, but the bounds can be.
1536
1537The difference between an @code{array} and a @code{vector} is that
1538arrays behave like in C: when used in expressions they decay to a pointer
1539to the first element whereas vectors are treated as first class values.
1540@end defun
1541
1542@defun Type.const ()
1543Return a new @code{gdb.Type} object which represents a
1544@code{const}-qualified variant of this type.
1545@end defun
1546
1547@defun Type.volatile ()
1548Return a new @code{gdb.Type} object which represents a
1549@code{volatile}-qualified variant of this type.
1550@end defun
1551
1552@defun Type.unqualified ()
1553Return a new @code{gdb.Type} object which represents an unqualified
1554variant of this type. That is, the result is neither @code{const} nor
1555@code{volatile}.
1556@end defun
1557
1558@defun Type.range ()
1559Return a Python @code{Tuple} object that contains two elements: the
1560low bound of the argument type and the high bound of that type. If
1561the type does not have a range, @value{GDBN} will raise a
1562@code{gdb.error} exception (@pxref{Exception Handling}).
1563@end defun
1564
1565@defun Type.reference ()
1566Return a new @code{gdb.Type} object which represents a reference to this
1567type.
1568@end defun
1569
1570@defun Type.pointer ()
1571Return a new @code{gdb.Type} object which represents a pointer to this
1572type.
1573@end defun
1574
1575@defun Type.strip_typedefs ()
1576Return a new @code{gdb.Type} that represents the real type,
1577after removing all layers of typedefs.
1578@end defun
1579
1580@defun Type.target ()
1581Return a new @code{gdb.Type} object which represents the target type
1582of this type.
1583
1584For a pointer type, the target type is the type of the pointed-to
1585object. For an array type (meaning C-like arrays), the target type is
1586the type of the elements of the array. For a function or method type,
1587the target type is the type of the return value. For a complex type,
1588the target type is the type of the elements. For a typedef, the
1589target type is the aliased type.
1590
1591If the type does not have a target, this method will throw an
1592exception.
1593@end defun
1594
1595@defun Type.template_argument (n @r{[}, block@r{]})
1596If this @code{gdb.Type} is an instantiation of a template, this will
1a6a384b
JL
1597return a new @code{gdb.Value} or @code{gdb.Type} which represents the
1598value of the @var{n}th template argument (indexed starting at 0).
329baa95 1599
1a6a384b
JL
1600If this @code{gdb.Type} is not a template type, or if the type has fewer
1601than @var{n} template arguments, this will throw an exception.
1602Ordinarily, only C@t{++} code will have template types.
329baa95
DE
1603
1604If @var{block} is given, then @var{name} is looked up in that scope.
1605Otherwise, it is searched for globally.
1606@end defun
1607
59fb7612
SS
1608@defun Type.optimized_out ()
1609Return @code{gdb.Value} instance of this type whose value is optimized
1610out. This allows a frame decorator to indicate that the value of an
1611argument or a local variable is not known.
1612@end defun
329baa95
DE
1613
1614Each type has a code, which indicates what category this type falls
1615into. The available type categories are represented by constants
1616defined in the @code{gdb} module:
1617
b3ce5e5f
DE
1618@vtable @code
1619@vindex TYPE_CODE_PTR
329baa95
DE
1620@item gdb.TYPE_CODE_PTR
1621The type is a pointer.
1622
b3ce5e5f 1623@vindex TYPE_CODE_ARRAY
329baa95
DE
1624@item gdb.TYPE_CODE_ARRAY
1625The type is an array.
1626
b3ce5e5f 1627@vindex TYPE_CODE_STRUCT
329baa95
DE
1628@item gdb.TYPE_CODE_STRUCT
1629The type is a structure.
1630
b3ce5e5f 1631@vindex TYPE_CODE_UNION
329baa95
DE
1632@item gdb.TYPE_CODE_UNION
1633The type is a union.
1634
b3ce5e5f 1635@vindex TYPE_CODE_ENUM
329baa95
DE
1636@item gdb.TYPE_CODE_ENUM
1637The type is an enum.
1638
b3ce5e5f 1639@vindex TYPE_CODE_FLAGS
329baa95
DE
1640@item gdb.TYPE_CODE_FLAGS
1641A bit flags type, used for things such as status registers.
1642
b3ce5e5f 1643@vindex TYPE_CODE_FUNC
329baa95
DE
1644@item gdb.TYPE_CODE_FUNC
1645The type is a function.
1646
b3ce5e5f 1647@vindex TYPE_CODE_INT
329baa95
DE
1648@item gdb.TYPE_CODE_INT
1649The type is an integer type.
1650
b3ce5e5f 1651@vindex TYPE_CODE_FLT
329baa95
DE
1652@item gdb.TYPE_CODE_FLT
1653A floating point type.
1654
b3ce5e5f 1655@vindex TYPE_CODE_VOID
329baa95
DE
1656@item gdb.TYPE_CODE_VOID
1657The special type @code{void}.
1658
b3ce5e5f 1659@vindex TYPE_CODE_SET
329baa95
DE
1660@item gdb.TYPE_CODE_SET
1661A Pascal set type.
1662
b3ce5e5f 1663@vindex TYPE_CODE_RANGE
329baa95
DE
1664@item gdb.TYPE_CODE_RANGE
1665A range type, that is, an integer type with bounds.
1666
b3ce5e5f 1667@vindex TYPE_CODE_STRING
329baa95
DE
1668@item gdb.TYPE_CODE_STRING
1669A string type. Note that this is only used for certain languages with
1670language-defined string types; C strings are not represented this way.
1671
b3ce5e5f 1672@vindex TYPE_CODE_BITSTRING
329baa95
DE
1673@item gdb.TYPE_CODE_BITSTRING
1674A string of bits. It is deprecated.
1675
b3ce5e5f 1676@vindex TYPE_CODE_ERROR
329baa95
DE
1677@item gdb.TYPE_CODE_ERROR
1678An unknown or erroneous type.
1679
b3ce5e5f 1680@vindex TYPE_CODE_METHOD
329baa95 1681@item gdb.TYPE_CODE_METHOD
9c37b5ae 1682A method type, as found in C@t{++}.
329baa95 1683
b3ce5e5f 1684@vindex TYPE_CODE_METHODPTR
329baa95
DE
1685@item gdb.TYPE_CODE_METHODPTR
1686A pointer-to-member-function.
1687
b3ce5e5f 1688@vindex TYPE_CODE_MEMBERPTR
329baa95
DE
1689@item gdb.TYPE_CODE_MEMBERPTR
1690A pointer-to-member.
1691
b3ce5e5f 1692@vindex TYPE_CODE_REF
329baa95
DE
1693@item gdb.TYPE_CODE_REF
1694A reference type.
1695
3fcf899d
AV
1696@vindex TYPE_CODE_RVALUE_REF
1697@item gdb.TYPE_CODE_RVALUE_REF
1698A C@t{++}11 rvalue reference type.
1699
b3ce5e5f 1700@vindex TYPE_CODE_CHAR
329baa95
DE
1701@item gdb.TYPE_CODE_CHAR
1702A character type.
1703
b3ce5e5f 1704@vindex TYPE_CODE_BOOL
329baa95
DE
1705@item gdb.TYPE_CODE_BOOL
1706A boolean type.
1707
b3ce5e5f 1708@vindex TYPE_CODE_COMPLEX
329baa95
DE
1709@item gdb.TYPE_CODE_COMPLEX
1710A complex float type.
1711
b3ce5e5f 1712@vindex TYPE_CODE_TYPEDEF
329baa95
DE
1713@item gdb.TYPE_CODE_TYPEDEF
1714A typedef to some other type.
1715
b3ce5e5f 1716@vindex TYPE_CODE_NAMESPACE
329baa95
DE
1717@item gdb.TYPE_CODE_NAMESPACE
1718A C@t{++} namespace.
1719
b3ce5e5f 1720@vindex TYPE_CODE_DECFLOAT
329baa95
DE
1721@item gdb.TYPE_CODE_DECFLOAT
1722A decimal floating point type.
1723
b3ce5e5f 1724@vindex TYPE_CODE_INTERNAL_FUNCTION
329baa95
DE
1725@item gdb.TYPE_CODE_INTERNAL_FUNCTION
1726A function internal to @value{GDBN}. This is the type used to represent
1727convenience functions.
4881fcd7
TT
1728
1729@vindex TYPE_CODE_XMETHOD
1730@item gdb.TYPE_CODE_XMETHOD
1731A method internal to @value{GDBN}. This is the type used to represent
1732xmethods (@pxref{Writing an Xmethod}).
1733
1734@vindex TYPE_CODE_FIXED_POINT
1735@item gdb.TYPE_CODE_FIXED_POINT
1736A fixed-point number.
1737
1738@vindex TYPE_CODE_NAMESPACE
1739@item gdb.TYPE_CODE_NAMESPACE
1740A Fortran namelist.
b3ce5e5f 1741@end vtable
329baa95
DE
1742
1743Further support for types is provided in the @code{gdb.types}
1744Python module (@pxref{gdb.types}).
1745
1746@node Pretty Printing API
1747@subsubsection Pretty Printing API
b3ce5e5f 1748@cindex python pretty printing api
329baa95 1749
329baa95 1750A pretty-printer is just an object that holds a value and implements a
27a9fec6
TT
1751specific interface, defined here. An example output is provided
1752(@pxref{Pretty Printing}).
329baa95 1753
fb282576
TT
1754Because @value{GDBN} did not document extensibility for
1755pretty-printers, by default @value{GDBN} will assume that only the
1756basic pretty-printer methods may be available. The basic methods are
1757marked as such, below.
1758
1759To allow extensibility, @value{GDBN} provides the
1760@code{gdb.ValuePrinter} base class. This class does not provide any
1761attributes or behavior, but instead serves as a tag that can be
1762recognized by @value{GDBN}. For such printers, @value{GDBN} reserves
1763all attributes starting with a lower-case letter. That is, in the
1764future, @value{GDBN} may add a new method or attribute to the
1765pretty-printer protocol, and @code{gdb.ValuePrinter}-based printers
1766are expected to handle this gracefully. A simple way to do this would
1767be to use a leading underscore (or two, following the Python
1768name-mangling scheme) to any attributes local to the implementation.
1769
329baa95
DE
1770@defun pretty_printer.children (self)
1771@value{GDBN} will call this method on a pretty-printer to compute the
1772children of the pretty-printer's value.
1773
1774This method must return an object conforming to the Python iterator
1775protocol. Each item returned by the iterator must be a tuple holding
1776two elements. The first element is the ``name'' of the child; the
1777second element is the child's value. The value can be any Python
1778object which is convertible to a @value{GDBN} value.
1779
fb282576
TT
1780This is a basic method, and is optional. If it does not exist,
1781@value{GDBN} will act as though the value has no children.
2e62ab40 1782
a97c8e56
TT
1783For efficiency, the @code{children} method should lazily compute its
1784results. This will let @value{GDBN} read as few elements as
1785necessary, for example when various print settings (@pxref{Print
1786Settings}) or @code{-var-list-children} (@pxref{GDB/MI Variable
1787Objects}) limit the number of elements to be displayed.
1788
2e62ab40
AB
1789Children may be hidden from display based on the value of @samp{set
1790print max-depth} (@pxref{Print Settings}).
329baa95
DE
1791@end defun
1792
1793@defun pretty_printer.display_hint (self)
1794The CLI may call this method and use its result to change the
1795formatting of a value. The result will also be supplied to an MI
1796consumer as a @samp{displayhint} attribute of the variable being
1797printed.
1798
fb282576
TT
1799This is a basic method, and is optional. If it does exist, this
1800method must return a string or the special value @code{None}.
329baa95
DE
1801
1802Some display hints are predefined by @value{GDBN}:
1803
1804@table @samp
1805@item array
1806Indicate that the object being printed is ``array-like''. The CLI
1807uses this to respect parameters such as @code{set print elements} and
1808@code{set print array}.
1809
1810@item map
1811Indicate that the object being printed is ``map-like'', and that the
1812children of this value can be assumed to alternate between keys and
1813values.
1814
1815@item string
1816Indicate that the object being printed is ``string-like''. If the
1817printer's @code{to_string} method returns a Python string of some
1818kind, then @value{GDBN} will call its internal language-specific
1819string-printing function to format the string. For the CLI this means
1820adding quotation marks, possibly escaping some characters, respecting
1821@code{set print elements}, and the like.
1822@end table
9f9aa852
AB
1823
1824The special value @code{None} causes @value{GDBN} to apply the default
1825display rules.
329baa95
DE
1826@end defun
1827
1828@defun pretty_printer.to_string (self)
1829@value{GDBN} will call this method to display the string
1830representation of the value passed to the object's constructor.
1831
fb282576
TT
1832This is a basic method, and is optional.
1833
329baa95
DE
1834When printing from the CLI, if the @code{to_string} method exists,
1835then @value{GDBN} will prepend its result to the values returned by
1836@code{children}. Exactly how this formatting is done is dependent on
1837the display hint, and may change as more hints are added. Also,
1838depending on the print settings (@pxref{Print Settings}), the CLI may
1839print just the result of @code{to_string} in a stack trace, omitting
1840the result of @code{children}.
1841
1842If this method returns a string, it is printed verbatim.
1843
1844Otherwise, if this method returns an instance of @code{gdb.Value},
1845then @value{GDBN} prints this value. This may result in a call to
1846another pretty-printer.
1847
1848If instead the method returns a Python value which is convertible to a
1849@code{gdb.Value}, then @value{GDBN} performs the conversion and prints
1850the resulting value. Again, this may result in a call to another
1851pretty-printer. Python scalars (integers, floats, and booleans) and
1852strings are convertible to @code{gdb.Value}; other types are not.
1853
1854Finally, if this method returns @code{None} then no further operations
1855are peformed in this method and nothing is printed.
1856
1857If the result is not one of these types, an exception is raised.
1858@end defun
1859
f35baff3
TT
1860@defun pretty_printer.num_children ()
1861This is not a basic method, so @value{GDBN} will only ever call it for
1862objects derived from @code{gdb.ValuePrinter}.
1863
1864If available, this method should return the number of children.
1865@code{None} may be returned if the number can't readily be computed.
1866@end defun
1867
1868@defun pretty_printer.child (n)
1869This is not a basic method, so @value{GDBN} will only ever call it for
1870objects derived from @code{gdb.ValuePrinter}.
1871
1872If available, this method should return the child value indicated by
1873@var{n}. Indices start at zero.
1874@end defun
1875
329baa95
DE
1876@value{GDBN} provides a function which can be used to look up the
1877default pretty-printer for a @code{gdb.Value}:
1878
329baa95
DE
1879@defun gdb.default_visualizer (value)
1880This function takes a @code{gdb.Value} object as an argument. If a
1881pretty-printer for this value exists, then it is returned. If no such
1882printer exists, then this returns @code{None}.
1883@end defun
1884
c4a3dbaf
TT
1885Normally, a pretty-printer can respect the user's print settings
1886(including temporarily applied settings, such as @samp{/x}) simply by
1887calling @code{Value.format_string} (@pxref{Values From Inferior}).
1888However, these settings can also be queried directly:
1889
c4a3dbaf
TT
1890@defun gdb.print_options ()
1891Return a dictionary whose keys are the valid keywords that can be
1892given to @code{Value.format_string}, and whose values are the user's
1893settings. During a @code{print} or other operation, the values will
1894reflect any flags that are temporarily in effect.
1895
1896@smallexample
1897(gdb) python print (gdb.print_options ()['max_elements'])
1898200
1899@end smallexample
1900@end defun
1901
329baa95
DE
1902@node Selecting Pretty-Printers
1903@subsubsection Selecting Pretty-Printers
b3ce5e5f 1904@cindex selecting python pretty-printers
329baa95 1905
48869a5f
TT
1906@value{GDBN} provides several ways to register a pretty-printer:
1907globally, per program space, and per objfile. When choosing how to
1908register your pretty-printer, a good rule is to register it with the
1909smallest scope possible: that is prefer a specific objfile first, then
1910a program space, and only register a printer globally as a last
1911resort.
1912
48869a5f 1913@defvar gdb.pretty_printers
329baa95
DE
1914The Python list @code{gdb.pretty_printers} contains an array of
1915functions or callable objects that have been registered via addition
1916as a pretty-printer. Printers in this list are called @code{global}
1917printers, they're available when debugging all inferiors.
48869a5f
TT
1918@end defvar
1919
329baa95
DE
1920Each @code{gdb.Progspace} contains a @code{pretty_printers} attribute.
1921Each @code{gdb.Objfile} also contains a @code{pretty_printers}
1922attribute.
1923
1924Each function on these lists is passed a single @code{gdb.Value}
1925argument and should return a pretty-printer object conforming to the
1926interface definition above (@pxref{Pretty Printing API}). If a function
1927cannot create a pretty-printer for the value, it should return
1928@code{None}.
1929
1930@value{GDBN} first checks the @code{pretty_printers} attribute of each
1931@code{gdb.Objfile} in the current program space and iteratively calls
1932each enabled lookup routine in the list for that @code{gdb.Objfile}
1933until it receives a pretty-printer object.
1934If no pretty-printer is found in the objfile lists, @value{GDBN} then
1935searches the pretty-printer list of the current program space,
1936calling each enabled function until an object is returned.
1937After these lists have been exhausted, it tries the global
1938@code{gdb.pretty_printers} list, again calling each enabled function until an
1939object is returned.
1940
1941The order in which the objfiles are searched is not specified. For a
1942given list, functions are always invoked from the head of the list,
1943and iterated over sequentially until the end of the list, or a printer
1944object is returned.
1945
1946For various reasons a pretty-printer may not work.
1947For example, the underlying data structure may have changed and
1948the pretty-printer is out of date.
1949
1950The consequences of a broken pretty-printer are severe enough that
1951@value{GDBN} provides support for enabling and disabling individual
1952printers. For example, if @code{print frame-arguments} is on,
1953a backtrace can become highly illegible if any argument is printed
1954with a broken printer.
1955
1956Pretty-printers are enabled and disabled by attaching an @code{enabled}
1957attribute to the registered function or callable object. If this attribute
1958is present and its value is @code{False}, the printer is disabled, otherwise
1959the printer is enabled.
1960
1961@node Writing a Pretty-Printer
1962@subsubsection Writing a Pretty-Printer
1963@cindex writing a pretty-printer
1964
1965A pretty-printer consists of two parts: a lookup function to detect
1966if the type is supported, and the printer itself.
1967
1968Here is an example showing how a @code{std::string} printer might be
1969written. @xref{Pretty Printing API}, for details on the API this class
fb282576
TT
1970must provide. Note that this example uses the @code{gdb.ValuePrinter}
1971base class, and is careful to use a leading underscore for its local
1972state.
329baa95
DE
1973
1974@smallexample
fb282576 1975class StdStringPrinter(gdb.ValuePrinter):
329baa95
DE
1976 "Print a std::string"
1977
1978 def __init__(self, val):
fb282576 1979 self.__val = val
329baa95
DE
1980
1981 def to_string(self):
fb282576 1982 return self.__val['_M_dataplus']['_M_p']
329baa95
DE
1983
1984 def display_hint(self):
1985 return 'string'
1986@end smallexample
1987
1988And here is an example showing how a lookup function for the printer
1989example above might be written.
1990
1991@smallexample
1992def str_lookup_function(val):
1993 lookup_tag = val.type.tag
f9e59d06 1994 if lookup_tag is None:
329baa95
DE
1995 return None
1996 regex = re.compile("^std::basic_string<char,.*>$")
1997 if regex.match(lookup_tag):
1998 return StdStringPrinter(val)
1999 return None
2000@end smallexample
2001
2002The example lookup function extracts the value's type, and attempts to
2003match it to a type that it can pretty-print. If it is a type the
2004printer can pretty-print, it will return a printer object. If not, it
2005returns @code{None}.
2006
2007We recommend that you put your core pretty-printers into a Python
2008package. If your pretty-printers are for use with a library, we
2009further recommend embedding a version number into the package name.
2010This practice will enable @value{GDBN} to load multiple versions of
2011your pretty-printers at the same time, because they will have
2012different names.
2013
2014You should write auto-loaded code (@pxref{Python Auto-loading}) such that it
2015can be evaluated multiple times without changing its meaning. An
2016ideal auto-load file will consist solely of @code{import}s of your
2017printer modules, followed by a call to a register pretty-printers with
2018the current objfile.
2019
2020Taken as a whole, this approach will scale nicely to multiple
2021inferiors, each potentially using a different library version.
2022Embedding a version number in the Python package name will ensure that
2023@value{GDBN} is able to load both sets of printers simultaneously.
2024Then, because the search for pretty-printers is done by objfile, and
2025because your auto-loaded code took care to register your library's
2026printers with a specific objfile, @value{GDBN} will find the correct
2027printers for the specific version of the library used by each
2028inferior.
2029
2030To continue the @code{std::string} example (@pxref{Pretty Printing API}),
2031this code might appear in @code{gdb.libstdcxx.v6}:
2032
2033@smallexample
2034def register_printers(objfile):
2035 objfile.pretty_printers.append(str_lookup_function)
2036@end smallexample
2037
2038@noindent
2039And then the corresponding contents of the auto-load file would be:
2040
2041@smallexample
2042import gdb.libstdcxx.v6
2043gdb.libstdcxx.v6.register_printers(gdb.current_objfile())
2044@end smallexample
2045
2046The previous example illustrates a basic pretty-printer.
2047There are a few things that can be improved on.
2048The printer doesn't have a name, making it hard to identify in a
2049list of installed printers. The lookup function has a name, but
2050lookup functions can have arbitrary, even identical, names.
2051
2052Second, the printer only handles one type, whereas a library typically has
2053several types. One could install a lookup function for each desired type
2054in the library, but one could also have a single lookup function recognize
2055several types. The latter is the conventional way this is handled.
2056If a pretty-printer can handle multiple data types, then its
2057@dfn{subprinters} are the printers for the individual data types.
2058
2059The @code{gdb.printing} module provides a formal way of solving these
2060problems (@pxref{gdb.printing}).
2061Here is another example that handles multiple types.
2062
2063These are the types we are going to pretty-print:
2064
2065@smallexample
2066struct foo @{ int a, b; @};
2067struct bar @{ struct foo x, y; @};
2068@end smallexample
2069
2070Here are the printers:
2071
2072@smallexample
fb282576 2073class fooPrinter(gdb.ValuePrinter):
329baa95
DE
2074 """Print a foo object."""
2075
2076 def __init__(self, val):
fb282576 2077 self.__val = val
329baa95
DE
2078
2079 def to_string(self):
fb282576
TT
2080 return ("a=<" + str(self.__val["a"]) +
2081 "> b=<" + str(self.__val["b"]) + ">")
329baa95 2082
fb282576 2083class barPrinter(gdb.ValuePrinter):
329baa95
DE
2084 """Print a bar object."""
2085
2086 def __init__(self, val):
fb282576 2087 self.__val = val
329baa95
DE
2088
2089 def to_string(self):
fb282576
TT
2090 return ("x=<" + str(self.__val["x"]) +
2091 "> y=<" + str(self.__val["y"]) + ">")
329baa95
DE
2092@end smallexample
2093
2094This example doesn't need a lookup function, that is handled by the
2095@code{gdb.printing} module. Instead a function is provided to build up
2096the object that handles the lookup.
2097
2098@smallexample
2099import gdb.printing
2100
2101def build_pretty_printer():
2102 pp = gdb.printing.RegexpCollectionPrettyPrinter(
2103 "my_library")
2104 pp.add_printer('foo', '^foo$', fooPrinter)
2105 pp.add_printer('bar', '^bar$', barPrinter)
2106 return pp
2107@end smallexample
2108
2109And here is the autoload support:
2110
2111@smallexample
2112import gdb.printing
2113import my_library
2114gdb.printing.register_pretty_printer(
2115 gdb.current_objfile(),
2116 my_library.build_pretty_printer())
2117@end smallexample
2118
2119Finally, when this printer is loaded into @value{GDBN}, here is the
2120corresponding output of @samp{info pretty-printer}:
2121
2122@smallexample
2123(gdb) info pretty-printer
2124my_library.so:
2125 my_library
2126 foo
2127 bar
2128@end smallexample
2129
2130@node Type Printing API
2131@subsubsection Type Printing API
2132@cindex type printing API for Python
2133
2134@value{GDBN} provides a way for Python code to customize type display.
2135This is mainly useful for substituting canonical typedef names for
2136types.
2137
2138@cindex type printer
2139A @dfn{type printer} is just a Python object conforming to a certain
2140protocol. A simple base class implementing the protocol is provided;
2141see @ref{gdb.types}. A type printer must supply at least:
2142
2143@defivar type_printer enabled
2144A boolean which is True if the printer is enabled, and False
2145otherwise. This is manipulated by the @code{enable type-printer}
2146and @code{disable type-printer} commands.
2147@end defivar
2148
2149@defivar type_printer name
2150The name of the type printer. This must be a string. This is used by
2151the @code{enable type-printer} and @code{disable type-printer}
2152commands.
2153@end defivar
2154
2155@defmethod type_printer instantiate (self)
2156This is called by @value{GDBN} at the start of type-printing. It is
2157only called if the type printer is enabled. This method must return a
2158new object that supplies a @code{recognize} method, as described below.
2159@end defmethod
2160
2161
2162When displaying a type, say via the @code{ptype} command, @value{GDBN}
2163will compute a list of type recognizers. This is done by iterating
2164first over the per-objfile type printers (@pxref{Objfiles In Python}),
2165followed by the per-progspace type printers (@pxref{Progspaces In
2166Python}), and finally the global type printers.
2167
2168@value{GDBN} will call the @code{instantiate} method of each enabled
2169type printer. If this method returns @code{None}, then the result is
2170ignored; otherwise, it is appended to the list of recognizers.
2171
2172Then, when @value{GDBN} is going to display a type name, it iterates
2173over the list of recognizers. For each one, it calls the recognition
2174function, stopping if the function returns a non-@code{None} value.
2175The recognition function is defined as:
2176
2177@defmethod type_recognizer recognize (self, type)
2178If @var{type} is not recognized, return @code{None}. Otherwise,
2179return a string which is to be printed as the name of @var{type}.
697aa1b7
EZ
2180The @var{type} argument will be an instance of @code{gdb.Type}
2181(@pxref{Types In Python}).
329baa95
DE
2182@end defmethod
2183
2184@value{GDBN} uses this two-pass approach so that type printers can
2185efficiently cache information without holding on to it too long. For
2186example, it can be convenient to look up type information in a type
2187printer and hold it for a recognizer's lifetime; if a single pass were
2188done then type printers would have to make use of the event system in
2189order to avoid holding information that could become stale as the
2190inferior changed.
2191
2192@node Frame Filter API
521b499b 2193@subsubsection Filtering Frames
329baa95
DE
2194@cindex frame filters api
2195
2196Frame filters are Python objects that manipulate the visibility of a
2197frame or frames when a backtrace (@pxref{Backtrace}) is printed by
2198@value{GDBN}.
2199
2200Only commands that print a backtrace, or, in the case of @sc{gdb/mi}
2201commands (@pxref{GDB/MI}), those that return a collection of frames
2202are affected. The commands that work with frame filters are:
2203
2204@code{backtrace} (@pxref{backtrace-command,, The backtrace command}),
2205@code{-stack-list-frames}
2206(@pxref{-stack-list-frames,, The -stack-list-frames command}),
2207@code{-stack-list-variables} (@pxref{-stack-list-variables,, The
2208-stack-list-variables command}), @code{-stack-list-arguments}
2209@pxref{-stack-list-arguments,, The -stack-list-arguments command}) and
2210@code{-stack-list-locals} (@pxref{-stack-list-locals,, The
2211-stack-list-locals command}).
2212
2213A frame filter works by taking an iterator as an argument, applying
2214actions to the contents of that iterator, and returning another
2215iterator (or, possibly, the same iterator it was provided in the case
2216where the filter does not perform any operations). Typically, frame
2217filters utilize tools such as the Python's @code{itertools} module to
2218work with and create new iterators from the source iterator.
2219Regardless of how a filter chooses to apply actions, it must not alter
2220the underlying @value{GDBN} frame or frames, or attempt to alter the
2221call-stack within @value{GDBN}. This preserves data integrity within
2222@value{GDBN}. Frame filters are executed on a priority basis and care
2223should be taken that some frame filters may have been executed before,
2224and that some frame filters will be executed after.
2225
2226An important consideration when designing frame filters, and well
2227worth reflecting upon, is that frame filters should avoid unwinding
2228the call stack if possible. Some stacks can run very deep, into the
2229tens of thousands in some cases. To search every frame when a frame
2230filter executes may be too expensive at that step. The frame filter
2231cannot know how many frames it has to iterate over, and it may have to
2232iterate through them all. This ends up duplicating effort as
2233@value{GDBN} performs this iteration when it prints the frames. If
2234the filter can defer unwinding frames until frame decorators are
2235executed, after the last filter has executed, it should. @xref{Frame
2236Decorator API}, for more information on decorators. Also, there are
2237examples for both frame decorators and filters in later chapters.
2238@xref{Writing a Frame Filter}, for more information.
2239
2240The Python dictionary @code{gdb.frame_filters} contains key/object
2241pairings that comprise a frame filter. Frame filters in this
2242dictionary are called @code{global} frame filters, and they are
2243available when debugging all inferiors. These frame filters must
2244register with the dictionary directly. In addition to the
2245@code{global} dictionary, there are other dictionaries that are loaded
2246with different inferiors via auto-loading (@pxref{Python
2247Auto-loading}). The two other areas where frame filter dictionaries
2248can be found are: @code{gdb.Progspace} which contains a
2249@code{frame_filters} dictionary attribute, and each @code{gdb.Objfile}
2250object which also contains a @code{frame_filters} dictionary
2251attribute.
2252
2253When a command is executed from @value{GDBN} that is compatible with
2254frame filters, @value{GDBN} combines the @code{global},
2255@code{gdb.Progspace} and all @code{gdb.Objfile} dictionaries currently
2256loaded. All of the @code{gdb.Objfile} dictionaries are combined, as
2257several frames, and thus several object files, might be in use.
2258@value{GDBN} then prunes any frame filter whose @code{enabled}
2259attribute is @code{False}. This pruned list is then sorted according
2260to the @code{priority} attribute in each filter.
2261
2262Once the dictionaries are combined, pruned and sorted, @value{GDBN}
2263creates an iterator which wraps each frame in the call stack in a
2264@code{FrameDecorator} object, and calls each filter in order. The
2265output from the previous filter will always be the input to the next
2266filter, and so on.
2267
2268Frame filters have a mandatory interface which each frame filter must
2269implement, defined here:
2270
2271@defun FrameFilter.filter (iterator)
2272@value{GDBN} will call this method on a frame filter when it has
2273reached the order in the priority list for that filter.
2274
2275For example, if there are four frame filters:
2276
2277@smallexample
2278Name Priority
2279
2280Filter1 5
2281Filter2 10
2282Filter3 100
2283Filter4 1
2284@end smallexample
2285
2286The order that the frame filters will be called is:
2287
2288@smallexample
2289Filter3 -> Filter2 -> Filter1 -> Filter4
2290@end smallexample
2291
2292Note that the output from @code{Filter3} is passed to the input of
2293@code{Filter2}, and so on.
2294
2295This @code{filter} method is passed a Python iterator. This iterator
2296contains a sequence of frame decorators that wrap each
2297@code{gdb.Frame}, or a frame decorator that wraps another frame
2298decorator. The first filter that is executed in the sequence of frame
2299filters will receive an iterator entirely comprised of default
2300@code{FrameDecorator} objects. However, after each frame filter is
2301executed, the previous frame filter may have wrapped some or all of
2302the frame decorators with their own frame decorator. As frame
2303decorators must also conform to a mandatory interface, these
2304decorators can be assumed to act in a uniform manner (@pxref{Frame
2305Decorator API}).
2306
2307This method must return an object conforming to the Python iterator
2308protocol. Each item in the iterator must be an object conforming to
2309the frame decorator interface. If a frame filter does not wish to
2310perform any operations on this iterator, it should return that
2311iterator untouched.
2312
2313This method is not optional. If it does not exist, @value{GDBN} will
2314raise and print an error.
2315@end defun
2316
2317@defvar FrameFilter.name
2318The @code{name} attribute must be Python string which contains the
2319name of the filter displayed by @value{GDBN} (@pxref{Frame Filter
2320Management}). This attribute may contain any combination of letters
2321or numbers. Care should be taken to ensure that it is unique. This
2322attribute is mandatory.
2323@end defvar
2324
2325@defvar FrameFilter.enabled
2326The @code{enabled} attribute must be Python boolean. This attribute
2327indicates to @value{GDBN} whether the frame filter is enabled, and
2328should be considered when frame filters are executed. If
2329@code{enabled} is @code{True}, then the frame filter will be executed
2330when any of the backtrace commands detailed earlier in this chapter
2331are executed. If @code{enabled} is @code{False}, then the frame
2332filter will not be executed. This attribute is mandatory.
2333@end defvar
2334
2335@defvar FrameFilter.priority
2336The @code{priority} attribute must be Python integer. This attribute
2337controls the order of execution in relation to other frame filters.
2338There are no imposed limits on the range of @code{priority} other than
2339it must be a valid integer. The higher the @code{priority} attribute,
2340the sooner the frame filter will be executed in relation to other
2341frame filters. Although @code{priority} can be negative, it is
2342recommended practice to assume zero is the lowest priority that a
2343frame filter can be assigned. Frame filters that have the same
2344priority are executed in unsorted order in that priority slot. This
521b499b 2345attribute is mandatory. 100 is a good default priority.
329baa95
DE
2346@end defvar
2347
2348@node Frame Decorator API
521b499b 2349@subsubsection Decorating Frames
329baa95
DE
2350@cindex frame decorator api
2351
2352Frame decorators are sister objects to frame filters (@pxref{Frame
2353Filter API}). Frame decorators are applied by a frame filter and can
2354only be used in conjunction with frame filters.
2355
2356The purpose of a frame decorator is to customize the printed content
2357of each @code{gdb.Frame} in commands where frame filters are executed.
2358This concept is called decorating a frame. Frame decorators decorate
2359a @code{gdb.Frame} with Python code contained within each API call.
2360This separates the actual data contained in a @code{gdb.Frame} from
2361the decorated data produced by a frame decorator. This abstraction is
2362necessary to maintain integrity of the data contained in each
2363@code{gdb.Frame}.
2364
2365Frame decorators have a mandatory interface, defined below.
2366
2367@value{GDBN} already contains a frame decorator called
2368@code{FrameDecorator}. This contains substantial amounts of
2369boilerplate code to decorate the content of a @code{gdb.Frame}. It is
2370recommended that other frame decorators inherit and extend this
2371object, and only to override the methods needed.
2372
521b499b
TT
2373@tindex gdb.FrameDecorator
2374@code{FrameDecorator} is defined in the Python module
2375@code{gdb.FrameDecorator}, so your code can import it like:
2376@smallexample
2377from gdb.FrameDecorator import FrameDecorator
2378@end smallexample
2379
329baa95
DE
2380@defun FrameDecorator.elided (self)
2381
2382The @code{elided} method groups frames together in a hierarchical
2383system. An example would be an interpreter, where multiple low-level
2384frames make up a single call in the interpreted language. In this
2385example, the frame filter would elide the low-level frames and present
2386a single high-level frame, representing the call in the interpreted
2387language, to the user.
2388
2389The @code{elided} function must return an iterable and this iterable
2390must contain the frames that are being elided wrapped in a suitable
2391frame decorator. If no frames are being elided this function may
2392return an empty iterable, or @code{None}. Elided frames are indented
2393from normal frames in a @code{CLI} backtrace, or in the case of
c96452ad 2394@sc{gdb/mi}, are placed in the @code{children} field of the eliding
329baa95
DE
2395frame.
2396
2397It is the frame filter's task to also filter out the elided frames from
2398the source iterator. This will avoid printing the frame twice.
2399@end defun
2400
2401@defun FrameDecorator.function (self)
2402
2403This method returns the name of the function in the frame that is to
2404be printed.
2405
2406This method must return a Python string describing the function, or
2407@code{None}.
2408
2409If this function returns @code{None}, @value{GDBN} will not print any
2410data for this field.
2411@end defun
2412
2413@defun FrameDecorator.address (self)
2414
2415This method returns the address of the frame that is to be printed.
2416
2417This method must return a Python numeric integer type of sufficient
2418size to describe the address of the frame, or @code{None}.
2419
2420If this function returns a @code{None}, @value{GDBN} will not print
2421any data for this field.
2422@end defun
2423
2424@defun FrameDecorator.filename (self)
2425
2426This method returns the filename and path associated with this frame.
2427
2428This method must return a Python string containing the filename and
2429the path to the object file backing the frame, or @code{None}.
2430
2431If this function returns a @code{None}, @value{GDBN} will not print
2432any data for this field.
2433@end defun
2434
2435@defun FrameDecorator.line (self):
2436
2437This method returns the line number associated with the current
2438position within the function addressed by this frame.
2439
2440This method must return a Python integer type, or @code{None}.
2441
2442If this function returns a @code{None}, @value{GDBN} will not print
2443any data for this field.
2444@end defun
2445
2446@defun FrameDecorator.frame_args (self)
2447@anchor{frame_args}
2448
2449This method must return an iterable, or @code{None}. Returning an
2450empty iterable, or @code{None} means frame arguments will not be
2451printed for this frame. This iterable must contain objects that
2452implement two methods, described here.
2453
6596a5d4 2454This object must implement a @code{symbol} method which takes a
329baa95
DE
2455single @code{self} parameter and must return a @code{gdb.Symbol}
2456(@pxref{Symbols In Python}), or a Python string. The object must also
2457implement a @code{value} method which takes a single @code{self}
2458parameter and must return a @code{gdb.Value} (@pxref{Values From
2459Inferior}), a Python value, or @code{None}. If the @code{value}
2460method returns @code{None}, and the @code{argument} method returns a
2461@code{gdb.Symbol}, @value{GDBN} will look-up and print the value of
2462the @code{gdb.Symbol} automatically.
2463
2464A brief example:
2465
2466@smallexample
2467class SymValueWrapper():
2468
2469 def __init__(self, symbol, value):
2470 self.sym = symbol
2471 self.val = value
2472
2473 def value(self):
2474 return self.val
2475
2476 def symbol(self):
2477 return self.sym
2478
2479class SomeFrameDecorator()
2480...
2481...
2482 def frame_args(self):
2483 args = []
2484 try:
2485 block = self.inferior_frame.block()
2486 except:
2487 return None
2488
2489 # Iterate over all symbols in a block. Only add
2490 # symbols that are arguments.
2491 for sym in block:
2492 if not sym.is_argument:
2493 continue
2494 args.append(SymValueWrapper(sym,None))
2495
2496 # Add example synthetic argument.
2497 args.append(SymValueWrapper(``foo'', 42))
2498
2499 return args
2500@end smallexample
2501@end defun
2502
2503@defun FrameDecorator.frame_locals (self)
2504
2505This method must return an iterable or @code{None}. Returning an
2506empty iterable, or @code{None} means frame local arguments will not be
2507printed for this frame.
2508
2509The object interface, the description of the various strategies for
2510reading frame locals, and the example are largely similar to those
2511described in the @code{frame_args} function, (@pxref{frame_args,,The
2512frame filter frame_args function}). Below is a modified example:
2513
2514@smallexample
2515class SomeFrameDecorator()
2516...
2517...
2518 def frame_locals(self):
2519 vars = []
2520 try:
2521 block = self.inferior_frame.block()
2522 except:
2523 return None
2524
2525 # Iterate over all symbols in a block. Add all
2526 # symbols, except arguments.
2527 for sym in block:
2528 if sym.is_argument:
2529 continue
2530 vars.append(SymValueWrapper(sym,None))
2531
2532 # Add an example of a synthetic local variable.
2533 vars.append(SymValueWrapper(``bar'', 99))
2534
2535 return vars
2536@end smallexample
2537@end defun
2538
2539@defun FrameDecorator.inferior_frame (self):
2540
2541This method must return the underlying @code{gdb.Frame} that this
2542frame decorator is decorating. @value{GDBN} requires the underlying
2543frame for internal frame information to determine how to print certain
2544values when printing a frame.
2545@end defun
2546
2547@node Writing a Frame Filter
2548@subsubsection Writing a Frame Filter
2549@cindex writing a frame filter
2550
2551There are three basic elements that a frame filter must implement: it
2552must correctly implement the documented interface (@pxref{Frame Filter
2553API}), it must register itself with @value{GDBN}, and finally, it must
2554decide if it is to work on the data provided by @value{GDBN}. In all
2555cases, whether it works on the iterator or not, each frame filter must
2556return an iterator. A bare-bones frame filter follows the pattern in
2557the following example.
2558
2559@smallexample
2560import gdb
2561
2562class FrameFilter():
2563
2564 def __init__(self):
2565 # Frame filter attribute creation.
2566 #
2567 # 'name' is the name of the filter that GDB will display.
2568 #
2569 # 'priority' is the priority of the filter relative to other
2570 # filters.
2571 #
2572 # 'enabled' is a boolean that indicates whether this filter is
2573 # enabled and should be executed.
2574
2575 self.name = "Foo"
2576 self.priority = 100
2577 self.enabled = True
2578
2579 # Register this frame filter with the global frame_filters
2580 # dictionary.
2581 gdb.frame_filters[self.name] = self
2582
2583 def filter(self, frame_iter):
2584 # Just return the iterator.
2585 return frame_iter
2586@end smallexample
2587
2588The frame filter in the example above implements the three
2589requirements for all frame filters. It implements the API, self
2590registers, and makes a decision on the iterator (in this case, it just
2591returns the iterator untouched).
2592
2593The first step is attribute creation and assignment, and as shown in
2594the comments the filter assigns the following attributes: @code{name},
2595@code{priority} and whether the filter should be enabled with the
2596@code{enabled} attribute.
2597
2598The second step is registering the frame filter with the dictionary or
2599dictionaries that the frame filter has interest in. As shown in the
2600comments, this filter just registers itself with the global dictionary
2601@code{gdb.frame_filters}. As noted earlier, @code{gdb.frame_filters}
2602is a dictionary that is initialized in the @code{gdb} module when
2603@value{GDBN} starts. What dictionary a filter registers with is an
2604important consideration. Generally, if a filter is specific to a set
2605of code, it should be registered either in the @code{objfile} or
2606@code{progspace} dictionaries as they are specific to the program
2607currently loaded in @value{GDBN}. The global dictionary is always
2608present in @value{GDBN} and is never unloaded. Any filters registered
2609with the global dictionary will exist until @value{GDBN} exits. To
2610avoid filters that may conflict, it is generally better to register
2611frame filters against the dictionaries that more closely align with
2612the usage of the filter currently in question. @xref{Python
2613Auto-loading}, for further information on auto-loading Python scripts.
2614
2615@value{GDBN} takes a hands-off approach to frame filter registration,
2616therefore it is the frame filter's responsibility to ensure
2617registration has occurred, and that any exceptions are handled
2618appropriately. In particular, you may wish to handle exceptions
2619relating to Python dictionary key uniqueness. It is mandatory that
2620the dictionary key is the same as frame filter's @code{name}
2621attribute. When a user manages frame filters (@pxref{Frame Filter
2622Management}), the names @value{GDBN} will display are those contained
2623in the @code{name} attribute.
2624
2625The final step of this example is the implementation of the
2626@code{filter} method. As shown in the example comments, we define the
2627@code{filter} method and note that the method must take an iterator,
2628and also must return an iterator. In this bare-bones example, the
2629frame filter is not very useful as it just returns the iterator
2630untouched. However this is a valid operation for frame filters that
2631have the @code{enabled} attribute set, but decide not to operate on
2632any frames.
2633
2634In the next example, the frame filter operates on all frames and
2635utilizes a frame decorator to perform some work on the frames.
2636@xref{Frame Decorator API}, for further information on the frame
2637decorator interface.
2638
2639This example works on inlined frames. It highlights frames which are
2640inlined by tagging them with an ``[inlined]'' tag. By applying a
2641frame decorator to all frames with the Python @code{itertools imap}
2642method, the example defers actions to the frame decorator. Frame
2643decorators are only processed when @value{GDBN} prints the backtrace.
2644
2645This introduces a new decision making topic: whether to perform
2646decision making operations at the filtering step, or at the printing
2647step. In this example's approach, it does not perform any filtering
2648decisions at the filtering step beyond mapping a frame decorator to
2649each frame. This allows the actual decision making to be performed
2650when each frame is printed. This is an important consideration, and
2651well worth reflecting upon when designing a frame filter. An issue
2652that frame filters should avoid is unwinding the stack if possible.
2653Some stacks can run very deep, into the tens of thousands in some
2654cases. To search every frame to determine if it is inlined ahead of
2655time may be too expensive at the filtering step. The frame filter
2656cannot know how many frames it has to iterate over, and it would have
2657to iterate through them all. This ends up duplicating effort as
2658@value{GDBN} performs this iteration when it prints the frames.
2659
2660In this example decision making can be deferred to the printing step.
2661As each frame is printed, the frame decorator can examine each frame
2662in turn when @value{GDBN} iterates. From a performance viewpoint,
2663this is the most appropriate decision to make as it avoids duplicating
2664the effort that the printing step would undertake anyway. Also, if
2665there are many frame filters unwinding the stack during filtering, it
2666can substantially delay the printing of the backtrace which will
2667result in large memory usage, and a poor user experience.
2668
2669@smallexample
2670class InlineFilter():
2671
2672 def __init__(self):
2673 self.name = "InlinedFrameFilter"
2674 self.priority = 100
2675 self.enabled = True
2676 gdb.frame_filters[self.name] = self
2677
2678 def filter(self, frame_iter):
2679 frame_iter = itertools.imap(InlinedFrameDecorator,
2680 frame_iter)
2681 return frame_iter
2682@end smallexample
2683
2684This frame filter is somewhat similar to the earlier example, except
2685that the @code{filter} method applies a frame decorator object called
2686@code{InlinedFrameDecorator} to each element in the iterator. The
2687@code{imap} Python method is light-weight. It does not proactively
2688iterate over the iterator, but rather creates a new iterator which
2689wraps the existing one.
2690
2691Below is the frame decorator for this example.
2692
2693@smallexample
2694class InlinedFrameDecorator(FrameDecorator):
2695
2696 def __init__(self, fobj):
2697 super(InlinedFrameDecorator, self).__init__(fobj)
2698
2699 def function(self):
3067d0b1 2700 frame = self.inferior_frame()
329baa95
DE
2701 name = str(frame.name())
2702
2703 if frame.type() == gdb.INLINE_FRAME:
2704 name = name + " [inlined]"
2705
2706 return name
2707@end smallexample
2708
2709This frame decorator only defines and overrides the @code{function}
2710method. It lets the supplied @code{FrameDecorator}, which is shipped
2711with @value{GDBN}, perform the other work associated with printing
2712this frame.
2713
2714The combination of these two objects create this output from a
2715backtrace:
2716
2717@smallexample
2718#0 0x004004e0 in bar () at inline.c:11
2719#1 0x00400566 in max [inlined] (b=6, a=12) at inline.c:21
2720#2 0x00400566 in main () at inline.c:31
2721@end smallexample
2722
2723So in the case of this example, a frame decorator is applied to all
2724frames, regardless of whether they may be inlined or not. As
2725@value{GDBN} iterates over the iterator produced by the frame filters,
2726@value{GDBN} executes each frame decorator which then makes a decision
2727on what to print in the @code{function} callback. Using a strategy
2728like this is a way to defer decisions on the frame content to printing
2729time.
2730
2731@subheading Eliding Frames
2732
2733It might be that the above example is not desirable for representing
2734inlined frames, and a hierarchical approach may be preferred. If we
2735want to hierarchically represent frames, the @code{elided} frame
2736decorator interface might be preferable.
2737
2738This example approaches the issue with the @code{elided} method. This
2739example is quite long, but very simplistic. It is out-of-scope for
2740this section to write a complete example that comprehensively covers
2741all approaches of finding and printing inlined frames. However, this
2742example illustrates the approach an author might use.
2743
2744This example comprises of three sections.
2745
2746@smallexample
2747class InlineFrameFilter():
2748
2749 def __init__(self):
2750 self.name = "InlinedFrameFilter"
2751 self.priority = 100
2752 self.enabled = True
2753 gdb.frame_filters[self.name] = self
2754
2755 def filter(self, frame_iter):
2756 return ElidingInlineIterator(frame_iter)
2757@end smallexample
2758
2759This frame filter is very similar to the other examples. The only
2760difference is this frame filter is wrapping the iterator provided to
2761it (@code{frame_iter}) with a custom iterator called
2762@code{ElidingInlineIterator}. This again defers actions to when
2763@value{GDBN} prints the backtrace, as the iterator is not traversed
2764until printing.
2765
2766The iterator for this example is as follows. It is in this section of
2767the example where decisions are made on the content of the backtrace.
2768
2769@smallexample
2770class ElidingInlineIterator:
2771 def __init__(self, ii):
2772 self.input_iterator = ii
2773
2774 def __iter__(self):
2775 return self
2776
2777 def next(self):
2778 frame = next(self.input_iterator)
2779
2780 if frame.inferior_frame().type() != gdb.INLINE_FRAME:
2781 return frame
2782
2783 try:
2784 eliding_frame = next(self.input_iterator)
2785 except StopIteration:
2786 return frame
2787 return ElidingFrameDecorator(eliding_frame, [frame])
2788@end smallexample
2789
2790This iterator implements the Python iterator protocol. When the
2791@code{next} function is called (when @value{GDBN} prints each frame),
2792the iterator checks if this frame decorator, @code{frame}, is wrapping
2793an inlined frame. If it is not, it returns the existing frame decorator
2794untouched. If it is wrapping an inlined frame, it assumes that the
2795inlined frame was contained within the next oldest frame,
2796@code{eliding_frame}, which it fetches. It then creates and returns a
2797frame decorator, @code{ElidingFrameDecorator}, which contains both the
2798elided frame, and the eliding frame.
2799
2800@smallexample
2801class ElidingInlineDecorator(FrameDecorator):
2802
2803 def __init__(self, frame, elided_frames):
2804 super(ElidingInlineDecorator, self).__init__(frame)
2805 self.frame = frame
2806 self.elided_frames = elided_frames
2807
2808 def elided(self):
2809 return iter(self.elided_frames)
2810@end smallexample
2811
2812This frame decorator overrides one function and returns the inlined
2813frame in the @code{elided} method. As before it lets
2814@code{FrameDecorator} do the rest of the work involved in printing
2815this frame. This produces the following output.
2816
2817@smallexample
2818#0 0x004004e0 in bar () at inline.c:11
2819#2 0x00400529 in main () at inline.c:25
2820 #1 0x00400529 in max (b=6, a=12) at inline.c:15
2821@end smallexample
2822
2823In that output, @code{max} which has been inlined into @code{main} is
2824printed hierarchically. Another approach would be to combine the
2825@code{function} method, and the @code{elided} method to both print a
2826marker in the inlined frame, and also show the hierarchical
2827relationship.
2828
d11916aa
SS
2829@node Unwinding Frames in Python
2830@subsubsection Unwinding Frames in Python
2831@cindex unwinding frames in Python
2832
2833In @value{GDBN} terminology ``unwinding'' is the process of finding
2834the previous frame (that is, caller's) from the current one. An
2835unwinder has three methods. The first one checks if it can handle
2836given frame (``sniff'' it). For the frames it can sniff an unwinder
2837provides two additional methods: it can return frame's ID, and it can
2838fetch registers from the previous frame. A running @value{GDBN}
2839mantains a list of the unwinders and calls each unwinder's sniffer in
2840turn until it finds the one that recognizes the current frame. There
2841is an API to register an unwinder.
2842
2843The unwinders that come with @value{GDBN} handle standard frames.
2844However, mixed language applications (for example, an application
2845running Java Virtual Machine) sometimes use frame layouts that cannot
2846be handled by the @value{GDBN} unwinders. You can write Python code
2847that can handle such custom frames.
2848
2849You implement a frame unwinder in Python as a class with which has two
2850attributes, @code{name} and @code{enabled}, with obvious meanings, and
2851a single method @code{__call__}, which examines a given frame and
2852returns an object (an instance of @code{gdb.UnwindInfo class)}
2853describing it. If an unwinder does not recognize a frame, it should
2854return @code{None}. The code in @value{GDBN} that enables writing
2855unwinders in Python uses this object to return frame's ID and previous
2856frame registers when @value{GDBN} core asks for them.
2857
e7b5068c
TT
2858An unwinder should do as little work as possible. Some otherwise
2859innocuous operations can cause problems (even crashes, as this code is
01312843 2860not well-hardened yet). For example, making an inferior call from
e7b5068c
TT
2861an unwinder is unadvisable, as an inferior call will reset
2862@value{GDBN}'s stack unwinding process, potentially causing re-entrant
2863unwinding.
2864
d11916aa
SS
2865@subheading Unwinder Input
2866
2867An object passed to an unwinder (a @code{gdb.PendingFrame} instance)
2868provides a method to read frame's registers:
2869
56fcb715
AB
2870@defun PendingFrame.read_register (register)
2871This method returns the contents of @var{register} in the
43d5901d 2872frame as a @code{gdb.Value} object. For a description of the
56fcb715
AB
2873acceptable values of @var{register} see
2874@ref{gdbpy_frame_read_register,,Frame.read_register}. If @var{register}
43d5901d
AB
2875does not name a register for the current architecture, this method
2876will throw an exception.
e7b5068c
TT
2877
2878Note that this method will always return a @code{gdb.Value} for a
2879valid register name. This does not mean that the value will be valid.
2880For example, you may request a register that an earlier unwinder could
2881not unwind---the value will be unavailable. Instead, the
2882@code{gdb.Value} returned from this method will be lazy; that is, its
2883underlying bits will not be fetched until it is first used. So,
2884attempting to use such a value will cause an exception at the point of
2885use.
2886
2887The type of the returned @code{gdb.Value} depends on the register and
2888the architecture. It is common for registers to have a scalar type,
2889like @code{long long}; but many other types are possible, such as
2890pointer, pointer-to-function, floating point or vector types.
d11916aa
SS
2891@end defun
2892
2893It also provides a factory method to create a @code{gdb.UnwindInfo}
2894instance to be returned to @value{GDBN}:
2895
3712e78c 2896@anchor{gdb.PendingFrame.create_unwind_info}
d11916aa
SS
2897@defun PendingFrame.create_unwind_info (frame_id)
2898Returns a new @code{gdb.UnwindInfo} instance identified by given
a8afc8a7
AB
2899@var{frame_id}. The @var{frame_id} is used internally by @value{GDBN}
2900to identify the frames within the current thread's stack. The
2901attributes of @var{frame_id} determine what type of frame is
2902created within @value{GDBN}:
d11916aa
SS
2903
2904@table @code
d11916aa 2905@item sp, pc
e7b5068c
TT
2906The frame is identified by the given stack address and PC. The stack
2907address must be chosen so that it is constant throughout the lifetime
2908of the frame, so a typical choice is the value of the stack pointer at
2909the start of the function---in the DWARF standard, this would be the
2910``Call Frame Address''.
d11916aa 2911
e7b5068c
TT
2912This is the most common case by far. The other cases are documented
2913for completeness but are only useful in specialized situations.
2914
2915@item sp, pc, special
2916The frame is identified by the stack address, the PC, and a
2917``special'' address. The special address is used on architectures
2918that can have frames that do not change the stack, but which are still
2919distinct, for example the IA-64, which has a second stack for
2920registers. Both @var{sp} and @var{special} must be constant
2921throughout the lifetime of the frame.
d11916aa
SS
2922
2923@item sp
e7b5068c
TT
2924The frame is identified by the stack address only. Any other stack
2925frame with a matching @var{sp} will be considered to match this frame.
2926Inside gdb, this is called a ``wild frame''. You will never need
2927this.
d11916aa 2928@end table
e7b5068c 2929
64826d05
AB
2930Each attribute value should either be an instance of @code{gdb.Value}
2931or an integer.
d11916aa 2932
3712e78c
AB
2933A helper class is provided in the @code{gdb.unwinder} module that can
2934be used to represent a frame-id
2935(@pxref{gdb.unwinder.FrameId}).
2936
d11916aa
SS
2937@end defun
2938
87dbc774
AB
2939@defun PendingFrame.architecture ()
2940Return the @code{gdb.Architecture} (@pxref{Architectures In Python})
2941for this @code{gdb.PendingFrame}. This represents the architecture of
2942the particular frame being unwound.
2943@end defun
2944
d52b8007
AB
2945@defun PendingFrame.level ()
2946Return an integer, the stack frame level for this frame.
2947@xref{Frames, ,Stack Frames}.
2948@end defun
2949
86b35b71
AB
2950@defun PendingFrame.name ()
2951Returns the function name of this pending frame, or @code{None} if it
2952can't be obtained.
2953@end defun
2954
2955@defun PendingFrame.is_valid ()
2956Returns true if the @code{gdb.PendingFrame} object is valid, false if
2957not. A pending frame object becomes invalid when the call to the
2958unwinder, for which the pending frame was created, returns.
2959
2960All @code{gdb.PendingFrame} methods, except this one, will raise an
2961exception if the pending frame object is invalid at the time the
2962method is called.
2963@end defun
2964
2965@defun PendingFrame.pc ()
2966Returns the pending frame's resume address.
2967@end defun
2968
2969@defun PendingFrame.block ()
2970Return the pending frame's code block (@pxref{Blocks In Python}). If
2971the frame does not have a block -- for example, if there is no
2972debugging information for the code in question -- then this will raise
2973a @code{RuntimeError} exception.
2974@end defun
2975
2976@defun PendingFrame.function ()
2977Return the symbol for the function corresponding to this pending frame.
2978@xref{Symbols In Python}.
2979@end defun
2980
2981@defun PendingFrame.find_sal ()
2982Return the pending frame's symtab and line object (@pxref{Symbol
2983Tables In Python}).
2984@end defun
2985
2986@defun PendingFrame.language ()
2987Return the language of this frame, as a string, or None.
2988@end defun
2989
d11916aa
SS
2990@subheading Unwinder Output: UnwindInfo
2991
2992Use @code{PendingFrame.create_unwind_info} method described above to
2993create a @code{gdb.UnwindInfo} instance. Use the following method to
2994specify caller registers that have been saved in this frame:
2995
d2d62da6
AB
2996@defun gdb.UnwindInfo.add_saved_register (register, value)
2997@var{register} identifies the register, for a description of the acceptable
43d5901d 2998values see @ref{gdbpy_frame_read_register,,Frame.read_register}.
d11916aa
SS
2999@var{value} is a register value (a @code{gdb.Value} object).
3000@end defun
3001
6bf5f25b
AB
3002@subheading The @code{gdb.unwinder} Module
3003
3004@value{GDBN} comes with a @code{gdb.unwinder} module which contains
3712e78c 3005the following classes:
6bf5f25b
AB
3006
3007@deftp {class} gdb.unwinder.Unwinder
3008The @code{Unwinder} class is a base class from which user created
3009unwinders can derive, though it is not required that unwinders derive
3010from this class, so long as any user created unwinder has the required
3011@code{name} and @code{enabled} attributes.
3012
ebb83b77 3013@defun gdb.unwinder.Unwinder.__init__(name)
6bf5f25b
AB
3014The @var{name} is a string used to reference this unwinder within some
3015@value{GDBN} commands (@pxref{Managing Registered Unwinders}).
3016@end defun
3017
3018@defvar gdb.unwinder.name
3019A read-only attribute which is a string, the name of this unwinder.
3020@end defvar
3021
3022@defvar gdb.unwinder.enabled
3023A modifiable attribute containing a boolean; when @code{True}, the
3024unwinder is enabled, and will be used by @value{GDBN}. When
3025@code{False}, the unwinder has been disabled, and will not be used.
3026@end defvar
3027@end deftp
3028
3712e78c
AB
3029@anchor{gdb.unwinder.FrameId}
3030@deftp {class} gdb.unwinder.FrameId
3031This is a class suitable for being used as the frame-id when calling
3032@code{gdb.PendingFrame.create_unwind_info}. It is not required to use
3033this class, any class with the required attribute
3034(@pxref{gdb.PendingFrame.create_unwind_info}) will be accepted, but in
3035most cases this class will be sufficient.
3036
3037@code{gdb.unwinder.FrameId} has the following method:
3038
ebb83b77 3039@defun gdb.unwinder.FrameId.__init__(sp, pc, special = @code{None})
3712e78c
AB
3040The @var{sp} and @var{pc} arguments are required and should be either
3041a @code{gdb.Value} object, or an integer.
3042
3043The @var{special} argument is optional; if specified, it should be a
3044@code{gdb.Value} object, or an integer.
3045@end defun
3046
3047@code{gdb.unwinder.FrameId} has the following read-only attributes:
3048
3049@defvar gdb.unwinder.sp
3050The @var{sp} value passed to the constructor.
3051@end defvar
3052
3053@defvar gdb.unwinder.pc
3054The @var{pc} value passed to the constructor.
3055@end defvar
3056
3057@defvar gdb.unwinder.special
3058The @var{special} value passed to the constructor, or @code{None} if
3059no such value was passed.
3060@end defvar
3061@end deftp
3062
a8afc8a7
AB
3063@subheading Registering an Unwinder
3064
3065Object files and program spaces can have unwinders registered with
3066them. In addition, you can register unwinders globally.
3067
3068The @code{gdb.unwinders} module provides the function to register an
3069unwinder:
3070
3071@defun gdb.unwinder.register_unwinder (locus, unwinder, replace=False)
3072@var{locus} specifies to which unwinder list to prepend the
3073@var{unwinder}. It can be either an object file (@pxref{Objfiles In
3074Python}), a program space (@pxref{Progspaces In Python}), or
3075@code{None}, in which case the unwinder is registered globally. The
3076newly added @var{unwinder} will be called before any other unwinder
3077from the same locus. Two unwinders in the same locus cannot have the
3078same name. An attempt to add an unwinder with an already existing
3079name raises an exception unless @var{replace} is @code{True}, in which
3080case the old unwinder is deleted and the new unwinder is registered in
3081its place.
3082
3083@value{GDBN} first calls the unwinders from all the object files in no
3084particular order, then the unwinders from the current program space,
3085then the globally registered unwinders, and finally the unwinders
3086builtin to @value{GDBN}.
3087@end defun
3088
d11916aa
SS
3089@subheading Unwinder Skeleton Code
3090
6bf5f25b 3091Here is an example of how to structure a user created unwinder:
d11916aa
SS
3092
3093@smallexample
3712e78c 3094from gdb.unwinder import Unwinder, FrameId
d11916aa
SS
3095
3096class MyUnwinder(Unwinder):
a8afc8a7
AB
3097 def __init__(self):
3098 super().__init___("MyUnwinder_Name")
d11916aa 3099
a8afc8a7 3100 def __call__(self, pending_frame):
d11916aa
SS
3101 if not <we recognize frame>:
3102 return None
a8afc8a7
AB
3103
3104 # Create a FrameID. Usually the frame is identified by a
3105 # stack pointer and the function address.
3106 sp = ... compute a stack address ...
3107 pc = ... compute function address ...
d11916aa
SS
3108 unwind_info = pending_frame.create_unwind_info(FrameId(sp, pc))
3109
a8afc8a7 3110 # Find the values of the registers in the caller's frame and
d11916aa 3111 # save them in the result:
a8afc8a7 3112 unwind_info.add_saved_register(<register-number>, <register-value>)
d11916aa
SS
3113 ....
3114
3115 # Return the result:
3116 return unwind_info
3117
a8afc8a7 3118gdb.unwinder.register_unwinder(<locus>, MyUnwinder(), <replace>)
d11916aa
SS
3119@end smallexample
3120
6bf5f25b
AB
3121@anchor{Managing Registered Unwinders}
3122@subheading Managing Registered Unwinders
3123@value{GDBN} defines 3 commands to manage registered unwinders. These
3124are:
3125
3126@table @code
3127@item info unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
3128Lists all registered unwinders. Arguments @var{locus} and
3129@var{name-regexp} are both optional and can be used to filter which
3130unwinders are listed.
3131
3132The @var{locus} argument should be either @kbd{global},
3133@kbd{progspace}, or the name of an object file. Only unwinders
3134registered for the specified locus will be listed.
3135
3136The @var{name-regexp} is a regular expression used to match against
3137unwinder names. When trying to match against unwinder names that
3138include a string enclose @var{name-regexp} in quotes.
3139@item disable unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
3140The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
3141unwinder} above, but instead of listing the matching unwinders, all of
3142the matching unwinders are disabled. The @code{enabled} field of each
3143matching unwinder is set to @code{False}.
3144@item enable unwinder @r{[} @var{locus} @r{[} @var{name-regexp} @r{]} @r{]}
3145The @var{locus} and @var{name-regexp} are interpreted as in @kbd{info
3146unwinder} above, but instead of listing the matching unwinders, all of
3147the matching unwinders are enabled. The @code{enabled} field of each
3148matching unwinder is set to @code{True}.
3149@end table
3150
0c6e92a5
SC
3151@node Xmethods In Python
3152@subsubsection Xmethods In Python
3153@cindex xmethods in Python
3154
3155@dfn{Xmethods} are additional methods or replacements for existing
3156methods of a C@t{++} class. This feature is useful for those cases
3157where a method defined in C@t{++} source code could be inlined or
3158optimized out by the compiler, making it unavailable to @value{GDBN}.
3159For such cases, one can define an xmethod to serve as a replacement
3160for the method defined in the C@t{++} source code. @value{GDBN} will
3161then invoke the xmethod, instead of the C@t{++} method, to
3162evaluate expressions. One can also use xmethods when debugging
3163with core files. Moreover, when debugging live programs, invoking an
3164xmethod need not involve running the inferior (which can potentially
3165perturb its state). Hence, even if the C@t{++} method is available, it
3166is better to use its replacement xmethod if one is defined.
3167
3168The xmethods feature in Python is available via the concepts of an
3169@dfn{xmethod matcher} and an @dfn{xmethod worker}. To
3170implement an xmethod, one has to implement a matcher and a
3171corresponding worker for it (more than one worker can be
3172implemented, each catering to a different overloaded instance of the
3173method). Internally, @value{GDBN} invokes the @code{match} method of a
3174matcher to match the class type and method name. On a match, the
3175@code{match} method returns a list of matching @emph{worker} objects.
3176Each worker object typically corresponds to an overloaded instance of
3177the xmethod. They implement a @code{get_arg_types} method which
3178returns a sequence of types corresponding to the arguments the xmethod
3179requires. @value{GDBN} uses this sequence of types to perform
3180overload resolution and picks a winning xmethod worker. A winner
3181is also selected from among the methods @value{GDBN} finds in the
3182C@t{++} source code. Next, the winning xmethod worker and the
3183winning C@t{++} method are compared to select an overall winner. In
3184case of a tie between a xmethod worker and a C@t{++} method, the
3185xmethod worker is selected as the winner. That is, if a winning
3186xmethod worker is found to be equivalent to the winning C@t{++}
3187method, then the xmethod worker is treated as a replacement for
3188the C@t{++} method. @value{GDBN} uses the overall winner to invoke the
3189method. If the winning xmethod worker is the overall winner, then
897c3d32 3190the corresponding xmethod is invoked via the @code{__call__} method
0c6e92a5
SC
3191of the worker object.
3192
3193If one wants to implement an xmethod as a replacement for an
3194existing C@t{++} method, then they have to implement an equivalent
3195xmethod which has exactly the same name and takes arguments of
3196exactly the same type as the C@t{++} method. If the user wants to
3197invoke the C@t{++} method even though a replacement xmethod is
3198available for that method, then they can disable the xmethod.
3199
3200@xref{Xmethod API}, for API to implement xmethods in Python.
3201@xref{Writing an Xmethod}, for implementing xmethods in Python.
3202
3203@node Xmethod API
3204@subsubsection Xmethod API
3205@cindex xmethod API
3206
3207The @value{GDBN} Python API provides classes, interfaces and functions
3208to implement, register and manipulate xmethods.
3209@xref{Xmethods In Python}.
3210
3211An xmethod matcher should be an instance of a class derived from
3212@code{XMethodMatcher} defined in the module @code{gdb.xmethod}, or an
3213object with similar interface and attributes. An instance of
3214@code{XMethodMatcher} has the following attributes:
3215
3216@defvar name
3217The name of the matcher.
3218@end defvar
3219
3220@defvar enabled
3221A boolean value indicating whether the matcher is enabled or disabled.
3222@end defvar
3223
3224@defvar methods
3225A list of named methods managed by the matcher. Each object in the list
3226is an instance of the class @code{XMethod} defined in the module
3227@code{gdb.xmethod}, or any object with the following attributes:
3228
3229@table @code
3230
3231@item name
3232Name of the xmethod which should be unique for each xmethod
3233managed by the matcher.
3234
3235@item enabled
3236A boolean value indicating whether the xmethod is enabled or
3237disabled.
3238
3239@end table
3240
3241The class @code{XMethod} is a convenience class with same
3242attributes as above along with the following constructor:
3243
dd5d5494 3244@defun XMethod.__init__ (self, name)
0c6e92a5
SC
3245Constructs an enabled xmethod with name @var{name}.
3246@end defun
3247@end defvar
3248
3249@noindent
3250The @code{XMethodMatcher} class has the following methods:
3251
dd5d5494 3252@defun XMethodMatcher.__init__ (self, name)
0c6e92a5
SC
3253Constructs an enabled xmethod matcher with name @var{name}. The
3254@code{methods} attribute is initialized to @code{None}.
3255@end defun
3256
dd5d5494 3257@defun XMethodMatcher.match (self, class_type, method_name)
0c6e92a5
SC
3258Derived classes should override this method. It should return a
3259xmethod worker object (or a sequence of xmethod worker
3260objects) matching the @var{class_type} and @var{method_name}.
3261@var{class_type} is a @code{gdb.Type} object, and @var{method_name}
3262is a string value. If the matcher manages named methods as listed in
3263its @code{methods} attribute, then only those worker objects whose
3264corresponding entries in the @code{methods} list are enabled should be
3265returned.
3266@end defun
3267
3268An xmethod worker should be an instance of a class derived from
3269@code{XMethodWorker} defined in the module @code{gdb.xmethod},
3270or support the following interface:
3271
dd5d5494 3272@defun XMethodWorker.get_arg_types (self)
0c6e92a5
SC
3273This method returns a sequence of @code{gdb.Type} objects corresponding
3274to the arguments that the xmethod takes. It can return an empty
3275sequence or @code{None} if the xmethod does not take any arguments.
3276If the xmethod takes a single argument, then a single
3277@code{gdb.Type} object corresponding to it can be returned.
3278@end defun
3279
2ce1cdbf
DE
3280@defun XMethodWorker.get_result_type (self, *args)
3281This method returns a @code{gdb.Type} object representing the type
3282of the result of invoking this xmethod.
3283The @var{args} argument is the same tuple of arguments that would be
3284passed to the @code{__call__} method of this worker.
3285@end defun
3286
dd5d5494 3287@defun XMethodWorker.__call__ (self, *args)
0c6e92a5
SC
3288This is the method which does the @emph{work} of the xmethod. The
3289@var{args} arguments is the tuple of arguments to the xmethod. Each
3290element in this tuple is a gdb.Value object. The first element is
3291always the @code{this} pointer value.
3292@end defun
3293
3294For @value{GDBN} to lookup xmethods, the xmethod matchers
3295should be registered using the following function defined in the module
3296@code{gdb.xmethod}:
3297
dd5d5494 3298@defun register_xmethod_matcher (locus, matcher, replace=False)
0c6e92a5
SC
3299The @code{matcher} is registered with @code{locus}, replacing an
3300existing matcher with the same name as @code{matcher} if
3301@code{replace} is @code{True}. @code{locus} can be a
3302@code{gdb.Objfile} object (@pxref{Objfiles In Python}), or a
1e47491b 3303@code{gdb.Progspace} object (@pxref{Progspaces In Python}), or
0c6e92a5
SC
3304@code{None}. If it is @code{None}, then @code{matcher} is registered
3305globally.
3306@end defun
3307
3308@node Writing an Xmethod
3309@subsubsection Writing an Xmethod
3310@cindex writing xmethods in Python
3311
3312Implementing xmethods in Python will require implementing xmethod
3313matchers and xmethod workers (@pxref{Xmethods In Python}). Consider
3314the following C@t{++} class:
3315
3316@smallexample
3317class MyClass
3318@{
3319public:
3320 MyClass (int a) : a_(a) @{ @}
3321
3322 int geta (void) @{ return a_; @}
3323 int operator+ (int b);
3324
3325private:
3326 int a_;
3327@};
3328
3329int
3330MyClass::operator+ (int b)
3331@{
3332 return a_ + b;
3333@}
3334@end smallexample
3335
3336@noindent
3337Let us define two xmethods for the class @code{MyClass}, one
3338replacing the method @code{geta}, and another adding an overloaded
3339flavor of @code{operator+} which takes a @code{MyClass} argument (the
3340C@t{++} code above already has an overloaded @code{operator+}
3341which takes an @code{int} argument). The xmethod matcher can be
3342defined as follows:
3343
3344@smallexample
3345class MyClass_geta(gdb.xmethod.XMethod):
3346 def __init__(self):
3347 gdb.xmethod.XMethod.__init__(self, 'geta')
3348
3349 def get_worker(self, method_name):
3350 if method_name == 'geta':
3351 return MyClassWorker_geta()
3352
3353
3354class MyClass_sum(gdb.xmethod.XMethod):
3355 def __init__(self):
3356 gdb.xmethod.XMethod.__init__(self, 'sum')
3357
3358 def get_worker(self, method_name):
3359 if method_name == 'operator+':
3360 return MyClassWorker_plus()
3361
3362
3363class MyClassMatcher(gdb.xmethod.XMethodMatcher):
3364 def __init__(self):
3365 gdb.xmethod.XMethodMatcher.__init__(self, 'MyClassMatcher')
3366 # List of methods 'managed' by this matcher
3367 self.methods = [MyClass_geta(), MyClass_sum()]
3368
3369 def match(self, class_type, method_name):
3370 if class_type.tag != 'MyClass':
3371 return None
3372 workers = []
3373 for method in self.methods:
3374 if method.enabled:
3375 worker = method.get_worker(method_name)
3376 if worker:
3377 workers.append(worker)
3378
3379 return workers
3380@end smallexample
3381
3382@noindent
3383Notice that the @code{match} method of @code{MyClassMatcher} returns
3384a worker object of type @code{MyClassWorker_geta} for the @code{geta}
3385method, and a worker object of type @code{MyClassWorker_plus} for the
3386@code{operator+} method. This is done indirectly via helper classes
3387derived from @code{gdb.xmethod.XMethod}. One does not need to use the
3388@code{methods} attribute in a matcher as it is optional. However, if a
3389matcher manages more than one xmethod, it is a good practice to list the
3390xmethods in the @code{methods} attribute of the matcher. This will then
3391facilitate enabling and disabling individual xmethods via the
3392@code{enable/disable} commands. Notice also that a worker object is
3393returned only if the corresponding entry in the @code{methods} attribute
3394of the matcher is enabled.
3395
3396The implementation of the worker classes returned by the matcher setup
3397above is as follows:
3398
3399@smallexample
3400class MyClassWorker_geta(gdb.xmethod.XMethodWorker):
3401 def get_arg_types(self):
3402 return None
2ce1cdbf
DE
3403
3404 def get_result_type(self, obj):
3405 return gdb.lookup_type('int')
0c6e92a5
SC
3406
3407 def __call__(self, obj):
3408 return obj['a_']
3409
3410
3411class MyClassWorker_plus(gdb.xmethod.XMethodWorker):
3412 def get_arg_types(self):
3413 return gdb.lookup_type('MyClass')
2ce1cdbf
DE
3414
3415 def get_result_type(self, obj):
3416 return gdb.lookup_type('int')
0c6e92a5
SC
3417
3418 def __call__(self, obj, other):
3419 return obj['a_'] + other['a_']
3420@end smallexample
3421
3422For @value{GDBN} to actually lookup a xmethod, it has to be
3423registered with it. The matcher defined above is registered with
3424@value{GDBN} globally as follows:
3425
3426@smallexample
3427gdb.xmethod.register_xmethod_matcher(None, MyClassMatcher())
3428@end smallexample
3429
3430If an object @code{obj} of type @code{MyClass} is initialized in C@t{++}
3431code as follows:
3432
3433@smallexample
3434MyClass obj(5);
3435@end smallexample
3436
3437@noindent
3438then, after loading the Python script defining the xmethod matchers
000f9cbe 3439and workers into @value{GDBN}, invoking the method @code{geta} or using
0c6e92a5
SC
3440the operator @code{+} on @code{obj} will invoke the xmethods
3441defined above:
3442
3443@smallexample
3444(gdb) p obj.geta()
3445$1 = 5
3446
3447(gdb) p obj + obj
3448$2 = 10
3449@end smallexample
3450
3451Consider another example with a C++ template class:
3452
3453@smallexample
3454template <class T>
3455class MyTemplate
3456@{
3457public:
3458 MyTemplate () : dsize_(10), data_ (new T [10]) @{ @}
3459 ~MyTemplate () @{ delete [] data_; @}
3460
3461 int footprint (void)
3462 @{
3463 return sizeof (T) * dsize_ + sizeof (MyTemplate<T>);
3464 @}
3465
3466private:
3467 int dsize_;
3468 T *data_;
3469@};
3470@end smallexample
3471
3472Let us implement an xmethod for the above class which serves as a
3473replacement for the @code{footprint} method. The full code listing
3474of the xmethod workers and xmethod matchers is as follows:
3475
3476@smallexample
3477class MyTemplateWorker_footprint(gdb.xmethod.XMethodWorker):
3478 def __init__(self, class_type):
3479 self.class_type = class_type
2ce1cdbf 3480
0c6e92a5
SC
3481 def get_arg_types(self):
3482 return None
2ce1cdbf
DE
3483
3484 def get_result_type(self):
3485 return gdb.lookup_type('int')
3486
0c6e92a5
SC
3487 def __call__(self, obj):
3488 return (self.class_type.sizeof +
3489 obj['dsize_'] *
3490 self.class_type.template_argument(0).sizeof)
3491
3492
3493class MyTemplateMatcher_footprint(gdb.xmethod.XMethodMatcher):
3494 def __init__(self):
3495 gdb.xmethod.XMethodMatcher.__init__(self, 'MyTemplateMatcher')
3496
3497 def match(self, class_type, method_name):
3498 if (re.match('MyTemplate<[ \t\n]*[_a-zA-Z][ _a-zA-Z0-9]*>',
3499 class_type.tag) and
3500 method_name == 'footprint'):
3501 return MyTemplateWorker_footprint(class_type)
3502@end smallexample
3503
3504Notice that, in this example, we have not used the @code{methods}
3505attribute of the matcher as the matcher manages only one xmethod. The
3506user can enable/disable this xmethod by enabling/disabling the matcher
3507itself.
3508
329baa95
DE
3509@node Inferiors In Python
3510@subsubsection Inferiors In Python
3511@cindex inferiors in Python
3512
3513@findex gdb.Inferior
3514Programs which are being run under @value{GDBN} are called inferiors
65c574f6 3515(@pxref{Inferiors Connections and Programs}). Python scripts can access
329baa95
DE
3516information about and manipulate inferiors controlled by @value{GDBN}
3517via objects of the @code{gdb.Inferior} class.
3518
3519The following inferior-related functions are available in the @code{gdb}
3520module:
3521
3522@defun gdb.inferiors ()
3523Return a tuple containing all inferior objects.
3524@end defun
3525
3526@defun gdb.selected_inferior ()
3527Return an object representing the current inferior.
3528@end defun
3529
3530A @code{gdb.Inferior} object has the following attributes:
3531
3532@defvar Inferior.num
b080fe54
AB
3533ID of inferior, as assigned by @value{GDBN}. You can use this to make
3534Python breakpoints inferior-specific, for example
3535(@pxref{python_breakpoint_inferior,,The Breakpoint.inferior
3536attribute}).
329baa95
DE
3537@end defvar
3538
0e3b7c25
AB
3539@anchor{gdbpy_inferior_connection}
3540@defvar Inferior.connection
3541The @code{gdb.TargetConnection} for this inferior (@pxref{Connections
3542In Python}), or @code{None} if this inferior has no connection.
3543@end defvar
3544
55789354
TBA
3545@defvar Inferior.connection_num
3546ID of inferior's connection as assigned by @value{GDBN}, or None if
0e3b7c25
AB
3547the inferior is not connected to a target. @xref{Inferiors Connections
3548and Programs}. This is equivalent to
3549@code{gdb.Inferior.connection.num} in the case where
3550@code{gdb.Inferior.connection} is not @code{None}.
55789354
TBA
3551@end defvar
3552
329baa95
DE
3553@defvar Inferior.pid
3554Process ID of the inferior, as assigned by the underlying operating
3555system.
3556@end defvar
3557
3558@defvar Inferior.was_attached
3559Boolean signaling whether the inferior was created using `attach', or
3560started by @value{GDBN} itself.
3561@end defvar
3562
31531132
TT
3563@defvar Inferior.main_name
3564A string holding the name of this inferior's ``main'' function, if it
3565can be determined. If the name of main is not known, this is
3566@code{None}.
3567@end defvar
3568
a40bf0c2
SM
3569@defvar Inferior.progspace
3570The inferior's program space. @xref{Progspaces In Python}.
3571@end defvar
3572
31531132
TT
3573@defvar Inferior.arguments
3574The inferior's command line arguments, if known. This corresponds to
3575the @code{set args} and @code{show args} commands. @xref{Arguments}.
3576
3577When accessed, the value is a string holding all the arguments. The
3578contents are quoted as they would be when passed to the shell. If
3579there are no arguments, the value is @code{None}.
3580
3581Either a string or a sequence of strings can be assigned to this
3582attribute. When a string is assigned, it is assumed to have any
3583necessary quoting for the shell; when a sequence is assigned, the
3584quoting is applied by @value{GDBN}.
3585@end defvar
3586
329baa95
DE
3587A @code{gdb.Inferior} object has the following methods:
3588
3589@defun Inferior.is_valid ()
3590Returns @code{True} if the @code{gdb.Inferior} object is valid,
3591@code{False} if not. A @code{gdb.Inferior} object will become invalid
3592if the inferior no longer exists within @value{GDBN}. All other
3593@code{gdb.Inferior} methods will throw an exception if it is invalid
3594at the time the method is called.
3595@end defun
3596
3597@defun Inferior.threads ()
3598This method returns a tuple holding all the threads which are valid
3599when it is called. If there are no valid threads, the method will
3600return an empty tuple.
3601@end defun
3602
add5ded5
TT
3603@defun Inferior.architecture ()
3604Return the @code{gdb.Architecture} (@pxref{Architectures In Python})
3605for this inferior. This represents the architecture of the inferior
3606as a whole. Some platforms can have multiple architectures in a
3607single address space, so this may not match the architecture of a
163cffef 3608particular frame (@pxref{Frames In Python}).
9e1698c6 3609@end defun
add5ded5 3610
15e15b2d 3611@anchor{gdbpy_inferior_read_memory}
329baa95 3612@defun Inferior.read_memory (address, length)
914a96d7
TT
3613Read @var{length} addressable memory units from the inferior, starting
3614at @var{address}. Returns a @code{memoryview} object, which behaves
3615much like an array or a string. It can be modified and given to the
3616@code{Inferior.write_memory} function.
329baa95
DE
3617@end defun
3618
329baa95
DE
3619@defun Inferior.write_memory (address, buffer @r{[}, length@r{]})
3620Write the contents of @var{buffer} to the inferior, starting at
3621@var{address}. The @var{buffer} parameter must be a Python object
3622which supports the buffer protocol, i.e., a string, an array or the
3623object returned from @code{Inferior.read_memory}. If given, @var{length}
a86c90e6
SM
3624determines the number of addressable memory units from @var{buffer} to be
3625written.
329baa95
DE
3626@end defun
3627
329baa95
DE
3628@defun Inferior.search_memory (address, length, pattern)
3629Search a region of the inferior memory starting at @var{address} with
3630the given @var{length} using the search pattern supplied in
3631@var{pattern}. The @var{pattern} parameter must be a Python object
3632which supports the buffer protocol, i.e., a string, an array or the
3633object returned from @code{gdb.read_memory}. Returns a Python @code{Long}
3634containing the address where the pattern was found, or @code{None} if
3635the pattern could not be found.
3636@end defun
3637
da2c323b 3638@findex Inferior.thread_from_thread_handle
2b0c8b01
KB
3639@defun Inferior.thread_from_handle (handle)
3640Return the thread object corresponding to @var{handle}, a thread
da2c323b
KB
3641library specific data structure such as @code{pthread_t} for pthreads
3642library implementations.
2b0c8b01
KB
3643
3644The function @code{Inferior.thread_from_thread_handle} provides
3645the same functionality, but use of @code{Inferior.thread_from_thread_handle}
3646is deprecated.
da2c323b
KB
3647@end defun
3648
31531132
TT
3649
3650The environment that will be passed to the inferior can be changed
3651from Python by using the following methods. These methods only take
3652effect when the inferior is started -- they will not affect an
3653inferior that is already executing.
3654
31531132
TT
3655@defun Inferior.clear_env ()
3656Clear the current environment variables that will be passed to this
3657inferior.
3658@end defun
3659
31531132
TT
3660@defun Inferior.set_env (name, value)
3661Set the environment variable @var{name} to have the indicated value.
3662Both parameters must be strings.
3663@end defun
3664
31531132
TT
3665@defun Inferior.unset_env (name)
3666Unset the environment variable @var{name}. @var{name} must be a
3667string.
3668@end defun
3669
13cd9bce
AB
3670One may add arbitrary attributes to @code{gdb.Inferior} objects in the
3671usual Python way. This is useful if, for example, one needs to do
3672some extra record keeping associated with the inferior.
3673
53d08890
AB
3674@anchor{choosing attribute names}
3675When selecting a name for a new attribute, avoid starting the new
3676attribute name with a lower case letter; future attributes added by
3677@value{GDBN} will start with a lower case letter. Additionally, avoid
3678starting attribute names with two underscore characters, as these
3679could clash with Python builtin attribute names.
3680
13cd9bce
AB
3681In this contrived example we record the time when an inferior last
3682stopped:
3683
3684@smallexample
3685@group
3686(@value{GDBP}) python
3687import datetime
3688
3689def thread_stopped(event):
3690 if event.inferior_thread is not None:
3691 thread = event.inferior_thread
3692 else:
3693 thread = gdb.selected_thread()
3694 inferior = thread.inferior
3695 inferior._last_stop_time = datetime.datetime.today()
3696
3697gdb.events.stop.connect(thread_stopped)
3698@end group
3699@group
3700(@value{GDBP}) file /tmp/hello
3701Reading symbols from /tmp/hello...
3702(@value{GDBP}) start
3703Temporary breakpoint 1 at 0x401198: file /tmp/hello.c, line 18.
3704Starting program: /tmp/hello
3705
3706Temporary breakpoint 1, main () at /tmp/hello.c:18
370718 printf ("Hello World\n");
3708(@value{GDBP}) python print(gdb.selected_inferior()._last_stop_time)
37092024-01-04 14:48:41.347036
3710@end group
3711@end smallexample
3712
329baa95
DE
3713@node Events In Python
3714@subsubsection Events In Python
3715@cindex inferior events in Python
3716
3717@value{GDBN} provides a general event facility so that Python code can be
3718notified of various state changes, particularly changes that occur in
3719the inferior.
3720
3721An @dfn{event} is just an object that describes some state change. The
3722type of the object and its attributes will vary depending on the details
3723of the change. All the existing events are described below.
3724
3725In order to be notified of an event, you must register an event handler
3726with an @dfn{event registry}. An event registry is an object in the
3727@code{gdb.events} module which dispatches particular events. A registry
3728provides methods to register and unregister event handlers:
3729
3730@defun EventRegistry.connect (object)
3731Add the given callable @var{object} to the registry. This object will be
3732called when an event corresponding to this registry occurs.
3733@end defun
3734
3735@defun EventRegistry.disconnect (object)
3736Remove the given @var{object} from the registry. Once removed, the object
3737will no longer receive notifications of events.
3738@end defun
3739
3740Here is an example:
3741
3742@smallexample
3743def exit_handler (event):
f3bdc2db 3744 print ("event type: exit")
1cb56ad3
AB
3745 if hasattr (event, 'exit_code'):
3746 print ("exit code: %d" % (event.exit_code))
3747 else:
3748 print ("exit code not available")
329baa95
DE
3749
3750gdb.events.exited.connect (exit_handler)
3751@end smallexample
3752
3753In the above example we connect our handler @code{exit_handler} to the
3754registry @code{events.exited}. Once connected, @code{exit_handler} gets
3755called when the inferior exits. The argument @dfn{event} in this example is
3756of type @code{gdb.ExitedEvent}. As you can see in the example the
3757@code{ExitedEvent} object has an attribute which indicates the exit code of
3758the inferior.
3759
77d97a0a
TT
3760Some events can be thread specific when @value{GDBN} is running in
3761non-stop mode. When represented in Python, these events all extend
3762@code{gdb.ThreadEvent}. This event is a base class and is never
3763emitted directly; instead, events which are emitted by this or other
3764modules might extend this event. Examples of these events are
3765@code{gdb.BreakpointEvent} and @code{gdb.ContinueEvent}.
3766@code{gdb.ThreadEvent} holds the following attributes:
329baa95
DE
3767
3768@defvar ThreadEvent.inferior_thread
3769In non-stop mode this attribute will be set to the specific thread which was
3770involved in the emitted event. Otherwise, it will be set to @code{None}.
3771@end defvar
3772
77d97a0a
TT
3773The following is a listing of the event registries that are available and
3774details of the events they emit:
329baa95 3775
77d97a0a
TT
3776@table @code
3777
3778@item events.cont
3779Emits @code{gdb.ContinueEvent}, which extends @code{gdb.ThreadEvent}.
3780This event indicates that the inferior has been continued after a
3781stop. For inherited attribute refer to @code{gdb.ThreadEvent} above.
329baa95
DE
3782
3783@item events.exited
77d97a0a
TT
3784Emits @code{events.ExitedEvent}, which indicates that the inferior has
3785exited. @code{events.ExitedEvent} has two attributes:
3786
329baa95
DE
3787@defvar ExitedEvent.exit_code
3788An integer representing the exit code, if available, which the inferior
3789has returned. (The exit code could be unavailable if, for example,
3790@value{GDBN} detaches from the inferior.) If the exit code is unavailable,
3791the attribute does not exist.
3792@end defvar
77d97a0a 3793
373832b6 3794@defvar ExitedEvent.inferior
329baa95
DE
3795A reference to the inferior which triggered the @code{exited} event.
3796@end defvar
3797
3798@item events.stop
77d97a0a 3799Emits @code{gdb.StopEvent}, which extends @code{gdb.ThreadEvent}.
329baa95 3800
77d97a0a
TT
3801Indicates that the inferior has stopped. All events emitted by this
3802registry extend @code{gdb.StopEvent}. As a child of
3803@code{gdb.ThreadEvent}, @code{gdb.StopEvent} will indicate the stopped
3804thread when @value{GDBN} is running in non-stop mode. Refer to
3805@code{gdb.ThreadEvent} above for more details.
329baa95 3806
e187e7c9
TT
3807@code{gdb.StopEvent} has the following additional attributes:
3808
3809@defvar StopEvent.details
3810A dictionary holding any details relevant to the stop. The exact keys
3811and values depend on the type of stop, but are identical to the
3812corresponding MI output (@pxref{GDB/MI Async Records}).
3813
3814A dictionary was used for this (rather than adding attributes directly
3815to the event object) so that the MI keys could be used unchanged.
3816@end defvar
3817
77d97a0a 3818Emits @code{gdb.SignalEvent}, which extends @code{gdb.StopEvent}.
329baa95 3819
77d97a0a
TT
3820This event indicates that the inferior or one of its threads has
3821received a signal. @code{gdb.SignalEvent} has the following
3822attributes:
329baa95
DE
3823
3824@defvar SignalEvent.stop_signal
3825A string representing the signal received by the inferior. A list of possible
3826signal values can be obtained by running the command @code{info signals} in
3827the @value{GDBN} command prompt.
3828@end defvar
3829
77d97a0a
TT
3830Also emits @code{gdb.BreakpointEvent}, which extends
3831@code{gdb.StopEvent}.
329baa95
DE
3832
3833@code{gdb.BreakpointEvent} event indicates that one or more breakpoints have
3834been hit, and has the following attributes:
3835
3836@defvar BreakpointEvent.breakpoints
3837A sequence containing references to all the breakpoints (type
3838@code{gdb.Breakpoint}) that were hit.
3839@xref{Breakpoints In Python}, for details of the @code{gdb.Breakpoint} object.
3840@end defvar
77d97a0a 3841
329baa95 3842@defvar BreakpointEvent.breakpoint
1c76a0e2
TT
3843A reference to the first breakpoint that was hit. This attribute is
3844maintained for backward compatibility and is now deprecated in favor
3845of the @code{gdb.BreakpointEvent.breakpoints} attribute.
329baa95
DE
3846@end defvar
3847
3848@item events.new_objfile
3849Emits @code{gdb.NewObjFileEvent} which indicates that a new object file has
3850been loaded by @value{GDBN}. @code{gdb.NewObjFileEvent} has one attribute:
3851
3852@defvar NewObjFileEvent.new_objfile
3853A reference to the object file (@code{gdb.Objfile}) which has been loaded.
3854@xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
3855@end defvar
3856
0b4fe76f
TT
3857@item events.free_objfile
3858Emits @code{gdb.FreeObjFileEvent} which indicates that an object file
3859is about to be removed from @value{GDBN}. One reason this can happen
3860is when the inferior calls @code{dlclose}.
3861@code{gdb.FreeObjFileEvent} has one attribute:
3862
079e7983 3863@defvar FreeObjFileEvent.objfile
0b4fe76f
TT
3864A reference to the object file (@code{gdb.Objfile}) which will be unloaded.
3865@xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
3866@end defvar
3867
4ffbba72
DE
3868@item events.clear_objfiles
3869Emits @code{gdb.ClearObjFilesEvent} which indicates that the list of object
3870files for a program space has been reset.
3871@code{gdb.ClearObjFilesEvent} has one attribute:
3872
3873@defvar ClearObjFilesEvent.progspace
3874A reference to the program space (@code{gdb.Progspace}) whose objfile list has
3875been cleared. @xref{Progspaces In Python}.
3876@end defvar
3877
fb5af5e3
TT
3878@item events.inferior_call
3879Emits events just before and after a function in the inferior is
3880called by @value{GDBN}. Before an inferior call, this emits an event
3881of type @code{gdb.InferiorCallPreEvent}, and after an inferior call,
3882this emits an event of type @code{gdb.InferiorCallPostEvent}.
3883
3884@table @code
3885@tindex gdb.InferiorCallPreEvent
3886@item @code{gdb.InferiorCallPreEvent}
3887Indicates that a function in the inferior is about to be called.
162078c8
NB
3888
3889@defvar InferiorCallPreEvent.ptid
3890The thread in which the call will be run.
3891@end defvar
3892
3893@defvar InferiorCallPreEvent.address
3894The location of the function to be called.
3895@end defvar
3896
fb5af5e3
TT
3897@tindex gdb.InferiorCallPostEvent
3898@item @code{gdb.InferiorCallPostEvent}
3899Indicates that a function in the inferior has just been called.
162078c8
NB
3900
3901@defvar InferiorCallPostEvent.ptid
3902The thread in which the call was run.
3903@end defvar
3904
3905@defvar InferiorCallPostEvent.address
3906The location of the function that was called.
3907@end defvar
fb5af5e3 3908@end table
162078c8
NB
3909
3910@item events.memory_changed
3911Emits @code{gdb.MemoryChangedEvent} which indicates that the memory of the
3912inferior has been modified by the @value{GDBN} user, for instance via a
3913command like @w{@code{set *addr = value}}. The event has the following
3914attributes:
3915
3916@defvar MemoryChangedEvent.address
3917The start address of the changed region.
3918@end defvar
3919
3920@defvar MemoryChangedEvent.length
3921Length in bytes of the changed region.
3922@end defvar
3923
3924@item events.register_changed
3925Emits @code{gdb.RegisterChangedEvent} which indicates that a register in the
3926inferior has been modified by the @value{GDBN} user.
3927
3928@defvar RegisterChangedEvent.frame
3929A gdb.Frame object representing the frame in which the register was modified.
3930@end defvar
3931@defvar RegisterChangedEvent.regnum
3932Denotes which register was modified.
3933@end defvar
3934
dac790e1
TT
3935@item events.breakpoint_created
3936This is emitted when a new breakpoint has been created. The argument
3937that is passed is the new @code{gdb.Breakpoint} object.
3938
3939@item events.breakpoint_modified
3940This is emitted when a breakpoint has been modified in some way. The
3941argument that is passed is the new @code{gdb.Breakpoint} object.
3942
3943@item events.breakpoint_deleted
3944This is emitted when a breakpoint has been deleted. The argument that
3945is passed is the @code{gdb.Breakpoint} object. When this event is
3946emitted, the @code{gdb.Breakpoint} object will already be in its
3947invalid state; that is, the @code{is_valid} method will return
3948@code{False}.
3949
3f77c769
TT
3950@item events.before_prompt
3951This event carries no payload. It is emitted each time @value{GDBN}
3952presents a prompt to the user.
3953
7c96f8c1
TT
3954@item events.new_inferior
3955This is emitted when a new inferior is created. Note that the
3956inferior is not necessarily running; in fact, it may not even have an
3957associated executable.
3958
3959The event is of type @code{gdb.NewInferiorEvent}. This has a single
3960attribute:
3961
3962@defvar NewInferiorEvent.inferior
3963The new inferior, a @code{gdb.Inferior} object.
3964@end defvar
3965
3966@item events.inferior_deleted
3967This is emitted when an inferior has been deleted. Note that this is
3968not the same as process exit; it is notified when the inferior itself
3969is removed, say via @code{remove-inferiors}.
3970
3971The event is of type @code{gdb.InferiorDeletedEvent}. This has a single
3972attribute:
3973
77d97a0a 3974@defvar InferiorDeletedEvent.inferior
7c96f8c1
TT
3975The inferior that is being removed, a @code{gdb.Inferior} object.
3976@end defvar
3977
3978@item events.new_thread
3979This is emitted when @value{GDBN} notices a new thread. The event is of
3980type @code{gdb.NewThreadEvent}, which extends @code{gdb.ThreadEvent}.
3981This has a single attribute:
3982
3983@defvar NewThreadEvent.inferior_thread
3984The new thread.
3985@end defvar
3986
28ab5960
SF
3987@item events.thread_exited
3988This is emitted when @value{GDBN} notices a thread has exited. The event
3989is of type @code{gdb.ThreadExitedEvent} which extends @code{gdb.ThreadEvent}.
3990This has a single attribute:
3991
3992@defvar ThreadExitedEvent.inferior_thread
3993The exiting thread.
3994@end defvar
3995
b1f0f284
AB
3996@item events.gdb_exiting
3997This is emitted when @value{GDBN} exits. This event is not emitted if
3998@value{GDBN} exits as a result of an internal error, or after an
3999unexpected signal. The event is of type @code{gdb.GdbExitingEvent},
4000which has a single attribute:
4001
4002@defvar GdbExitingEvent.exit_code
4003An integer, the value of the exit code @value{GDBN} will return.
4004@end defvar
4005
0e3b7c25
AB
4006@item events.connection_removed
4007This is emitted when @value{GDBN} removes a connection
4008(@pxref{Connections In Python}). The event is of type
4009@code{gdb.ConnectionEvent}. This has a single read-only attribute:
4010
4011@defvar ConnectionEvent.connection
4012The @code{gdb.TargetConnection} that is being removed.
4013@end defvar
4014
42f297ad
AB
4015@item events.executable_changed
4016Emits @code{gdb.ExecutableChangedEvent} which indicates that the
4017@code{gdb.Progspace.executable_filename} has changed.
4018
4019This event is emitted when either the value of
4020@code{gdb.Progspace.executable_filename } has changed to name a
4021different file, or the executable file named by
4022@code{gdb.Progspace.executable_filename} has changed on disk, and
4023@value{GDBN} has therefore reloaded it.
4024
4025@defvar ExecutableChangedEvent.progspace
4026The @code{gdb.Progspace} in which the current executable has changed.
4027The file name of the updated executable will be visible in
4028@code{gdb.Progspace.executable_filename} (@pxref{Progspaces In Python}).
4029@end defvar
4030@defvar ExecutableChangedEvent.reload
4031This attribute will be @code{True} if the value of
4032@code{gdb.Progspace.executable_filename} didn't change, but the file
4033it names changed on disk instead, and @value{GDBN} reloaded it.
4034
4035When this attribute is @code{False}, the value in
4036@code{gdb.Progspace.executable_filename} was changed to name a
4037different file.
4038@end defvar
4039
4040Remember that @value{GDBN} tracks the executable file and the symbol
4041file separately, these are visible as
4042@code{gdb.Progspace.executable_filename} and
4043@code{gdb.Progspace.filename} respectively. When using the @kbd{file}
4044command, @value{GDBN} updates both of these fields, but the executable
4045file is updated first, so when this event is emitted, the executable
4046filename will have changed, but the symbol filename might still hold
4047its previous value.
59912fb2
AB
4048
4049@item events.new_progspace
4050This is emitted when @value{GDBN} adds a new program space
4051(@pxref{Progspaces In Python,,Program Spaces In Python}). The event
4052is of type @code{gdb.NewProgspaceEvent}, and has a single read-only
4053attribute:
4054
4055@defvar NewProgspaceEvent.progspace
4056The @code{gdb.Progspace} that was added to @value{GDBN}.
4057@end defvar
4058
4059No @code{NewProgspaceEvent} is emitted for the very first program
4060space, which is assigned to the first inferior. This first program
4061space is created within @value{GDBN} before any Python scripts are
4062sourced.
4063
4064@item events.free_progspace
4065This is emitted when @value{GDBN} removes a program space
4066(@pxref{Progspaces In Python,,Program Spaces In Python}), for example
4067as a result of the @kbd{remove-inferiors} command
4068(@pxref{remove_inferiors_cli,,@kbd{remove-inferiors}}). The event is
4069of type @code{gdb.FreeProgspaceEvent}, and has a single read-only
4070attribute:
4071
4072@defvar FreeProgspaceEvent.progspace
4073The @code{gdb.Progspace} that is about to be removed from
4074@value{GDBN}.
4075@end defvar
4076
329baa95
DE
4077@end table
4078
4079@node Threads In Python
4080@subsubsection Threads In Python
4081@cindex threads in python
4082
4083@findex gdb.InferiorThread
4084Python scripts can access information about, and manipulate inferior threads
4085controlled by @value{GDBN}, via objects of the @code{gdb.InferiorThread} class.
4086
4087The following thread-related functions are available in the @code{gdb}
4088module:
4089
329baa95
DE
4090@defun gdb.selected_thread ()
4091This function returns the thread object for the selected thread. If there
4092is no selected thread, this will return @code{None}.
4093@end defun
4094
14796d29 4095To get the list of threads for an inferior, use the @code{Inferior.threads()}
0ca4866a 4096method. @xref{Inferiors In Python}.
14796d29 4097
329baa95
DE
4098A @code{gdb.InferiorThread} object has the following attributes:
4099
4100@defvar InferiorThread.name
4101The name of the thread. If the user specified a name using
4102@code{thread name}, then this returns that name. Otherwise, if an
4103OS-supplied name is available, then it is returned. Otherwise, this
4104returns @code{None}.
4105
4106This attribute can be assigned to. The new value must be a string
4107object, which sets the new name, or @code{None}, which removes any
4108user-specified thread name.
4109@end defvar
4110
4111@defvar InferiorThread.num
5d5658a1 4112The per-inferior number of the thread, as assigned by GDB.
329baa95
DE
4113@end defvar
4114
22a02324
PA
4115@defvar InferiorThread.global_num
4116The global ID of the thread, as assigned by GDB. You can use this to
4117make Python breakpoints thread-specific, for example
4118(@pxref{python_breakpoint_thread,,The Breakpoint.thread attribute}).
4119@end defvar
4120
28ab5960 4121@anchor{inferior_thread_ptid}
329baa95
DE
4122@defvar InferiorThread.ptid
4123ID of the thread, as assigned by the operating system. This attribute is a
4124tuple containing three integers. The first is the Process ID (PID); the second
4125is the Lightweight Process ID (LWPID), and the third is the Thread ID (TID).
4126Either the LWPID or TID may be 0, which indicates that the operating system
4127does not use that identifier.
4128@end defvar
4129
76118e16
AB
4130@defvar InferiorThread.ptid_string
4131This read-only attribute contains a string representing
4132@code{InferiorThread.ptid}. This is the string that @value{GDBN} uses
4133in the @samp{Target Id} column in the @kbd{info threads} output
4134(@pxref{info_threads,,@samp{info threads}}).
4135@end defvar
4136
84654457
PA
4137@defvar InferiorThread.inferior
4138The inferior this thread belongs to. This attribute is represented as
4139a @code{gdb.Inferior} object. This attribute is not writable.
4140@end defvar
4141
659971cb
AB
4142@defvar InferiorThread.details
4143A string containing target specific thread state information. The
4144format of this string varies by target. If there is no additional
4145state information for this thread, then this attribute contains
4146@code{None}.
4147
4148For example, on a @sc{gnu}/Linux system, a thread that is in the
4149process of exiting will return the string @samp{Exiting}. For remote
4150targets the @code{details} string will be obtained with the
4151@samp{qThreadExtraInfo} remote packet, if the target supports it
4152(@pxref{qThreadExtraInfo,,@samp{qThreadExtraInfo}}).
4153
4154@value{GDBN} displays the @code{details} string as part of the
4155@samp{Target Id} column, in the @code{info threads} output
4156(@pxref{info_threads,,@samp{info threads}}).
4157@end defvar
4158
329baa95
DE
4159A @code{gdb.InferiorThread} object has the following methods:
4160
4161@defun InferiorThread.is_valid ()
4162Returns @code{True} if the @code{gdb.InferiorThread} object is valid,
4163@code{False} if not. A @code{gdb.InferiorThread} object will become
4164invalid if the thread exits, or the inferior that the thread belongs
4165is deleted. All other @code{gdb.InferiorThread} methods will throw an
4166exception if it is invalid at the time the method is called.
4167@end defun
4168
4169@defun InferiorThread.switch ()
4170This changes @value{GDBN}'s currently selected thread to the one represented
4171by this object.
4172@end defun
4173
4174@defun InferiorThread.is_stopped ()
4175Return a Boolean indicating whether the thread is stopped.
4176@end defun
4177
4178@defun InferiorThread.is_running ()
4179Return a Boolean indicating whether the thread is running.
4180@end defun
4181
4182@defun InferiorThread.is_exited ()
4183Return a Boolean indicating whether the thread is exited.
4184@end defun
4185
c369f8f0
KB
4186@defun InferiorThread.handle ()
4187Return the thread object's handle, represented as a Python @code{bytes}
4188object. A @code{gdb.Value} representation of the handle may be
4189constructed via @code{gdb.Value(bufobj, type)} where @var{bufobj} is
4190the Python @code{bytes} representation of the handle and @var{type} is
4191a @code{gdb.Type} for the handle type.
4192@end defun
4193
1d586eda
AB
4194One may add arbitrary attributes to @code{gdb.InferiorThread} objects
4195in the usual Python way. This is useful if, for example, one needs to
4196do some extra record keeping associated with the thread.
4197
53d08890
AB
4198@xref{choosing attribute names}, for guidance on selecting a suitable
4199name for new attributes.
4200
1d586eda
AB
4201In this contrived example we record the time when a thread last
4202stopped:
4203
4204@smallexample
4205@group
4206(@value{GDBP}) python
4207import datetime
4208
4209def thread_stopped(event):
4210 if event.inferior_thread is not None:
4211 thread = event.inferior_thread
4212 else:
4213 thread = gdb.selected_thread()
4214 thread._last_stop_time = datetime.datetime.today()
4215
4216gdb.events.stop.connect(thread_stopped)
4217@end group
4218@group
4219(@value{GDBP}) file /tmp/hello
4220Reading symbols from /tmp/hello...
4221(@value{GDBP}) start
4222Temporary breakpoint 1 at 0x401198: file /tmp/hello.c, line 18.
4223Starting program: /tmp/hello
4224
4225Temporary breakpoint 1, main () at /tmp/hello.c:18
422618 printf ("Hello World\n");
4227(@value{GDBP}) python print(gdb.selected_thread()._last_stop_time)
42282024-01-04 14:48:41.347036
4229@end group
4230@end smallexample
4231
0a0faf9f
TW
4232@node Recordings In Python
4233@subsubsection Recordings In Python
4234@cindex recordings in python
4235
4236The following recordings-related functions
4237(@pxref{Process Record and Replay}) are available in the @code{gdb}
4238module:
4239
4240@defun gdb.start_recording (@r{[}method@r{]}, @r{[}format@r{]})
4241Start a recording using the given @var{method} and @var{format}. If
4242no @var{format} is given, the default format for the recording method
4243is used. If no @var{method} is given, the default method will be used.
4244Returns a @code{gdb.Record} object on success. Throw an exception on
4245failure.
4246
4247The following strings can be passed as @var{method}:
4248
4249@itemize @bullet
4250@item
4251@code{"full"}
4252@item
4253@code{"btrace"}: Possible values for @var{format}: @code{"pt"},
4254@code{"bts"} or leave out for default format.
4255@end itemize
4256@end defun
4257
4258@defun gdb.current_recording ()
4259Access a currently running recording. Return a @code{gdb.Record}
4260object on success. Return @code{None} if no recording is currently
4261active.
4262@end defun
4263
4264@defun gdb.stop_recording ()
4265Stop the current recording. Throw an exception if no recording is
4266currently active. All record objects become invalid after this call.
4267@end defun
4268
4269A @code{gdb.Record} object has the following attributes:
4270
0a0faf9f
TW
4271@defvar Record.method
4272A string with the current recording method, e.g.@: @code{full} or
4273@code{btrace}.
4274@end defvar
4275
4276@defvar Record.format
4277A string with the current recording format, e.g.@: @code{bt}, @code{pts} or
4278@code{None}.
4279@end defvar
4280
4281@defvar Record.begin
4282A method specific instruction object representing the first instruction
4283in this recording.
4284@end defvar
4285
4286@defvar Record.end
4287A method specific instruction object representing the current
4288instruction, that is not actually part of the recording.
4289@end defvar
4290
4291@defvar Record.replay_position
4292The instruction representing the current replay position. If there is
4293no replay active, this will be @code{None}.
4294@end defvar
4295
4296@defvar Record.instruction_history
4297A list with all recorded instructions.
4298@end defvar
4299
4300@defvar Record.function_call_history
4301A list with all recorded function call segments.
4302@end defvar
4303
4304A @code{gdb.Record} object has the following methods:
4305
4306@defun Record.goto (instruction)
4307Move the replay position to the given @var{instruction}.
4308@end defun
4309
d050f7d7
TW
4310The common @code{gdb.Instruction} class that recording method specific
4311instruction objects inherit from, has the following attributes:
0a0faf9f 4312
d050f7d7 4313@defvar Instruction.pc
913aeadd 4314An integer representing this instruction's address.
0a0faf9f
TW
4315@end defvar
4316
d050f7d7 4317@defvar Instruction.data
914a96d7 4318A @code{memoryview} object holding the raw instruction data.
0a0faf9f
TW
4319@end defvar
4320
d050f7d7 4321@defvar Instruction.decoded
913aeadd 4322A human readable string with the disassembled instruction.
0a0faf9f
TW
4323@end defvar
4324
d050f7d7 4325@defvar Instruction.size
913aeadd 4326The size of the instruction in bytes.
0a0faf9f
TW
4327@end defvar
4328
d050f7d7
TW
4329Additionally @code{gdb.RecordInstruction} has the following attributes:
4330
4331@defvar RecordInstruction.number
4332An integer identifying this instruction. @code{number} corresponds to
4333the numbers seen in @code{record instruction-history}
4334(@pxref{Process Record and Replay}).
4335@end defvar
4336
4337@defvar RecordInstruction.sal
4338A @code{gdb.Symtab_and_line} object representing the associated symtab
4339and line of this instruction. May be @code{None} if no debug information is
4340available.
4341@end defvar
4342
0ed5da75 4343@defvar RecordInstruction.is_speculative
d050f7d7 4344A boolean indicating whether the instruction was executed speculatively.
913aeadd
TW
4345@end defvar
4346
33b5899f 4347If an error occurred during recording or decoding a recording, this error is
913aeadd
TW
4348represented by a @code{gdb.RecordGap} object in the instruction list. It has
4349the following attributes:
4350
4351@defvar RecordGap.number
4352An integer identifying this gap. @code{number} corresponds to the numbers seen
4353in @code{record instruction-history} (@pxref{Process Record and Replay}).
4354@end defvar
4355
4356@defvar RecordGap.error_code
4357A numerical representation of the reason for the gap. The value is specific to
4358the current recording method.
4359@end defvar
4360
4361@defvar RecordGap.error_string
4362A human readable string with the reason for the gap.
0a0faf9f
TW
4363@end defvar
4364
14f819c8 4365A @code{gdb.RecordFunctionSegment} object has the following attributes:
0a0faf9f 4366
14f819c8
TW
4367@defvar RecordFunctionSegment.number
4368An integer identifying this function segment. @code{number} corresponds to
0a0faf9f
TW
4369the numbers seen in @code{record function-call-history}
4370(@pxref{Process Record and Replay}).
4371@end defvar
4372
14f819c8 4373@defvar RecordFunctionSegment.symbol
0a0faf9f 4374A @code{gdb.Symbol} object representing the associated symbol. May be
14f819c8 4375@code{None} if no debug information is available.
0a0faf9f
TW
4376@end defvar
4377
14f819c8 4378@defvar RecordFunctionSegment.level
0a0faf9f
TW
4379An integer representing the function call's stack level. May be
4380@code{None} if the function call is a gap.
4381@end defvar
4382
14f819c8 4383@defvar RecordFunctionSegment.instructions
0ed5da75 4384A list of @code{gdb.RecordInstruction} or @code{gdb.RecordGap} objects
913aeadd 4385associated with this function call.
0a0faf9f
TW
4386@end defvar
4387
14f819c8
TW
4388@defvar RecordFunctionSegment.up
4389A @code{gdb.RecordFunctionSegment} object representing the caller's
0a0faf9f
TW
4390function segment. If the call has not been recorded, this will be the
4391function segment to which control returns. If neither the call nor the
4392return have been recorded, this will be @code{None}.
4393@end defvar
4394
14f819c8
TW
4395@defvar RecordFunctionSegment.prev
4396A @code{gdb.RecordFunctionSegment} object representing the previous
0a0faf9f
TW
4397segment of this function call. May be @code{None}.
4398@end defvar
4399
14f819c8
TW
4400@defvar RecordFunctionSegment.next
4401A @code{gdb.RecordFunctionSegment} object representing the next segment of
0a0faf9f
TW
4402this function call. May be @code{None}.
4403@end defvar
4404
4405The following example demonstrates the usage of these objects and
4406functions to create a function that will rewind a record to the last
4407time a function in a different file was executed. This would typically
4408be used to track the execution of user provided callback functions in a
4409library which typically are not visible in a back trace.
4410
4411@smallexample
4412def bringback ():
4413 rec = gdb.current_recording ()
4414 if not rec:
4415 return
4416
4417 insn = rec.instruction_history
4418 if len (insn) == 0:
4419 return
4420
4421 try:
4422 position = insn.index (rec.replay_position)
4423 except:
4424 position = -1
4425 try:
4426 filename = insn[position].sal.symtab.fullname ()
4427 except:
4428 filename = None
4429
4430 for i in reversed (insn[:position]):
4431 try:
4432 current = i.sal.symtab.fullname ()
4433 except:
4434 current = None
4435
4436 if filename == current:
4437 continue
4438
4439 rec.goto (i)
4440 return
4441@end smallexample
4442
4443Another possible application is to write a function that counts the
4444number of code executions in a given line range. This line range can
4445contain parts of functions or span across several functions and is not
4446limited to be contiguous.
4447
4448@smallexample
4449def countrange (filename, linerange):
4450 count = 0
4451
4452 def filter_only (file_name):
4453 for call in gdb.current_recording ().function_call_history:
4454 try:
4455 if file_name in call.symbol.symtab.fullname ():
4456 yield call
4457 except:
4458 pass
4459
4460 for c in filter_only (filename):
4461 for i in c.instructions:
4462 try:
4463 if i.sal.line in linerange:
4464 count += 1
4465 break;
4466 except:
4467 pass
4468
4469 return count
4470@end smallexample
4471
740b42ce
AB
4472@node CLI Commands In Python
4473@subsubsection CLI Commands In Python
329baa95 4474
740b42ce
AB
4475@cindex CLI commands in python
4476@cindex commands in python, CLI
4477@cindex python commands, CLI
329baa95
DE
4478You can implement new @value{GDBN} CLI commands in Python. A CLI
4479command is implemented using an instance of the @code{gdb.Command}
4480class, most commonly using a subclass.
4481
ebb83b77 4482@defun Command.__init__ (name, command_class @r{[}, completer_class @r{[}, prefix@r{]]})
329baa95
DE
4483The object initializer for @code{Command} registers the new command
4484with @value{GDBN}. This initializer is normally invoked from the
4485subclass' own @code{__init__} method.
4486
4487@var{name} is the name of the command. If @var{name} consists of
4488multiple words, then the initial words are looked for as prefix
4489commands. In this case, if one of the prefix commands does not exist,
4490an exception is raised.
4491
4492There is no support for multi-line commands.
4493
4494@var{command_class} should be one of the @samp{COMMAND_} constants
4495defined below. This argument tells @value{GDBN} how to categorize the
4496new command in the help system.
4497
4498@var{completer_class} is an optional argument. If given, it should be
4499one of the @samp{COMPLETE_} constants defined below. This argument
4500tells @value{GDBN} how to perform completion for this command. If not
4501given, @value{GDBN} will attempt to complete using the object's
4502@code{complete} method (see below); if no such method is found, an
4503error will occur when completion is attempted.
4504
4505@var{prefix} is an optional argument. If @code{True}, then the new
4506command is a prefix command; sub-commands of this command may be
4507registered.
4508
4509The help text for the new command is taken from the Python
4510documentation string for the command's class, if there is one. If no
4511documentation string is provided, the default value ``This command is
4512not documented.'' is used.
4513@end defun
4514
4515@cindex don't repeat Python command
4516@defun Command.dont_repeat ()
4517By default, a @value{GDBN} command is repeated when the user enters a
4518blank line at the command prompt. A command can suppress this
285dfa0f
TT
4519behavior by invoking the @code{dont_repeat} method at some point in
4520its @code{invoke} method (normally this is done early in case of
4521exception). This is similar to the user command @code{dont-repeat},
4522see @ref{Define, dont-repeat}.
329baa95
DE
4523@end defun
4524
4525@defun Command.invoke (argument, from_tty)
4526This method is called by @value{GDBN} when this command is invoked.
4527
4528@var{argument} is a string. It is the argument to the command, after
4529leading and trailing whitespace has been stripped.
4530
4531@var{from_tty} is a boolean argument. When true, this means that the
4532command was entered by the user at the terminal; when false it means
4533that the command came from elsewhere.
4534
4535If this method throws an exception, it is turned into a @value{GDBN}
4536@code{error} call. Otherwise, the return value is ignored.
4537
4538@findex gdb.string_to_argv
4539To break @var{argument} up into an argv-like string use
4540@code{gdb.string_to_argv}. This function behaves identically to
4541@value{GDBN}'s internal argument lexer @code{buildargv}.
4542It is recommended to use this for consistency.
4543Arguments are separated by spaces and may be quoted.
4544Example:
4545
4546@smallexample
4547print gdb.string_to_argv ("1 2\ \\\"3 '4 \"5' \"6 '7\"")
4548['1', '2 "3', '4 "5', "6 '7"]
4549@end smallexample
4550
4551@end defun
4552
4553@cindex completion of Python commands
4554@defun Command.complete (text, word)
4555This method is called by @value{GDBN} when the user attempts
4556completion on this command. All forms of completion are handled by
4557this method, that is, the @key{TAB} and @key{M-?} key bindings
4558(@pxref{Completion}), and the @code{complete} command (@pxref{Help,
4559complete}).
4560
697aa1b7
EZ
4561The arguments @var{text} and @var{word} are both strings; @var{text}
4562holds the complete command line up to the cursor's location, while
329baa95
DE
4563@var{word} holds the last word of the command line; this is computed
4564using a word-breaking heuristic.
4565
4566The @code{complete} method can return several values:
4567@itemize @bullet
4568@item
4569If the return value is a sequence, the contents of the sequence are
4570used as the completions. It is up to @code{complete} to ensure that the
4571contents actually do complete the word. A zero-length sequence is
4572allowed, it means that there were no completions available. Only
4573string elements of the sequence are used; other elements in the
4574sequence are ignored.
4575
4576@item
4577If the return value is one of the @samp{COMPLETE_} constants defined
4578below, then the corresponding @value{GDBN}-internal completion
4579function is invoked, and its result is used.
4580
4581@item
4582All other results are treated as though there were no available
4583completions.
4584@end itemize
4585@end defun
4586
4587When a new command is registered, it must be declared as a member of
4588some general class of commands. This is used to classify top-level
4589commands in the on-line help system; note that prefix commands are not
4590listed under their own category but rather that of their top-level
4591command. The available classifications are represented by constants
4592defined in the @code{gdb} module:
4593
4594@table @code
4595@findex COMMAND_NONE
4596@findex gdb.COMMAND_NONE
4597@item gdb.COMMAND_NONE
4598The command does not belong to any particular class. A command in
4599this category will not be displayed in any of the help categories.
4600
4601@findex COMMAND_RUNNING
4602@findex gdb.COMMAND_RUNNING
4603@item gdb.COMMAND_RUNNING
4604The command is related to running the inferior. For example,
4605@code{start}, @code{step}, and @code{continue} are in this category.
4606Type @kbd{help running} at the @value{GDBN} prompt to see a list of
4607commands in this category.
4608
4609@findex COMMAND_DATA
4610@findex gdb.COMMAND_DATA
4611@item gdb.COMMAND_DATA
4612The command is related to data or variables. For example,
4613@code{call}, @code{find}, and @code{print} are in this category. Type
4614@kbd{help data} at the @value{GDBN} prompt to see a list of commands
4615in this category.
4616
4617@findex COMMAND_STACK
4618@findex gdb.COMMAND_STACK
4619@item gdb.COMMAND_STACK
4620The command has to do with manipulation of the stack. For example,
4621@code{backtrace}, @code{frame}, and @code{return} are in this
4622category. Type @kbd{help stack} at the @value{GDBN} prompt to see a
4623list of commands in this category.
4624
4625@findex COMMAND_FILES
4626@findex gdb.COMMAND_FILES
4627@item gdb.COMMAND_FILES
4628This class is used for file-related commands. For example,
4629@code{file}, @code{list} and @code{section} are in this category.
4630Type @kbd{help files} at the @value{GDBN} prompt to see a list of
4631commands in this category.
4632
4633@findex COMMAND_SUPPORT
4634@findex gdb.COMMAND_SUPPORT
4635@item gdb.COMMAND_SUPPORT
4636This should be used for ``support facilities'', generally meaning
4637things that are useful to the user when interacting with @value{GDBN},
4638but not related to the state of the inferior. For example,
4639@code{help}, @code{make}, and @code{shell} are in this category. Type
4640@kbd{help support} at the @value{GDBN} prompt to see a list of
4641commands in this category.
4642
4643@findex COMMAND_STATUS
4644@findex gdb.COMMAND_STATUS
4645@item gdb.COMMAND_STATUS
4646The command is an @samp{info}-related command, that is, related to the
4647state of @value{GDBN} itself. For example, @code{info}, @code{macro},
4648and @code{show} are in this category. Type @kbd{help status} at the
4649@value{GDBN} prompt to see a list of commands in this category.
4650
4651@findex COMMAND_BREAKPOINTS
4652@findex gdb.COMMAND_BREAKPOINTS
4653@item gdb.COMMAND_BREAKPOINTS
4654The command has to do with breakpoints. For example, @code{break},
4655@code{clear}, and @code{delete} are in this category. Type @kbd{help
4656breakpoints} at the @value{GDBN} prompt to see a list of commands in
4657this category.
4658
4659@findex COMMAND_TRACEPOINTS
4660@findex gdb.COMMAND_TRACEPOINTS
4661@item gdb.COMMAND_TRACEPOINTS
4662The command has to do with tracepoints. For example, @code{trace},
4663@code{actions}, and @code{tfind} are in this category. Type
4664@kbd{help tracepoints} at the @value{GDBN} prompt to see a list of
4665commands in this category.
4666
2b2fbab8
TT
4667@findex COMMAND_TUI
4668@findex gdb.COMMAND_TUI
4669@item gdb.COMMAND_TUI
4670The command has to do with the text user interface (@pxref{TUI}).
4671Type @kbd{help tui} at the @value{GDBN} prompt to see a list of
4672commands in this category.
4673
329baa95
DE
4674@findex COMMAND_USER
4675@findex gdb.COMMAND_USER
4676@item gdb.COMMAND_USER
4677The command is a general purpose command for the user, and typically
4678does not fit in one of the other categories.
4679Type @kbd{help user-defined} at the @value{GDBN} prompt to see
4680a list of commands in this category, as well as the list of gdb macros
4681(@pxref{Sequences}).
4682
4683@findex COMMAND_OBSCURE
4684@findex gdb.COMMAND_OBSCURE
4685@item gdb.COMMAND_OBSCURE
4686The command is only used in unusual circumstances, or is not of
4687general interest to users. For example, @code{checkpoint},
4688@code{fork}, and @code{stop} are in this category. Type @kbd{help
4689obscure} at the @value{GDBN} prompt to see a list of commands in this
4690category.
4691
4692@findex COMMAND_MAINTENANCE
4693@findex gdb.COMMAND_MAINTENANCE
4694@item gdb.COMMAND_MAINTENANCE
4695The command is only useful to @value{GDBN} maintainers. The
4696@code{maintenance} and @code{flushregs} commands are in this category.
4697Type @kbd{help internals} at the @value{GDBN} prompt to see a list of
4698commands in this category.
4699@end table
4700
4701A new command can use a predefined completion function, either by
4702specifying it via an argument at initialization, or by returning it
4703from the @code{complete} method. These predefined completion
4704constants are all defined in the @code{gdb} module:
4705
b3ce5e5f
DE
4706@vtable @code
4707@vindex COMPLETE_NONE
329baa95
DE
4708@item gdb.COMPLETE_NONE
4709This constant means that no completion should be done.
4710
b3ce5e5f 4711@vindex COMPLETE_FILENAME
329baa95
DE
4712@item gdb.COMPLETE_FILENAME
4713This constant means that filename completion should be performed.
4714
b3ce5e5f 4715@vindex COMPLETE_LOCATION
329baa95
DE
4716@item gdb.COMPLETE_LOCATION
4717This constant means that location completion should be done.
5541bfdc 4718@xref{Location Specifications}.
329baa95 4719
b3ce5e5f 4720@vindex COMPLETE_COMMAND
329baa95
DE
4721@item gdb.COMPLETE_COMMAND
4722This constant means that completion should examine @value{GDBN}
4723command names.
4724
b3ce5e5f 4725@vindex COMPLETE_SYMBOL
329baa95
DE
4726@item gdb.COMPLETE_SYMBOL
4727This constant means that completion should be done using symbol names
4728as the source.
4729
b3ce5e5f 4730@vindex COMPLETE_EXPRESSION
329baa95
DE
4731@item gdb.COMPLETE_EXPRESSION
4732This constant means that completion should be done on expressions.
4733Often this means completing on symbol names, but some language
4734parsers also have support for completing on field names.
b3ce5e5f 4735@end vtable
329baa95
DE
4736
4737The following code snippet shows how a trivial CLI command can be
4738implemented in Python:
4739
4740@smallexample
4741class HelloWorld (gdb.Command):
4742 """Greet the whole world."""
4743
4744 def __init__ (self):
4745 super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
4746
4747 def invoke (self, arg, from_tty):
f3bdc2db 4748 print ("Hello, World!")
329baa95
DE
4749
4750HelloWorld ()
4751@end smallexample
4752
4753The last line instantiates the class, and is necessary to trigger the
4754registration of the command with @value{GDBN}. Depending on how the
4755Python code is read into @value{GDBN}, you may need to import the
4756@code{gdb} module explicitly.
4757
740b42ce 4758@node GDB/MI Commands In Python
c96452ad 4759@subsubsection @sc{gdb/mi} Commands In Python
740b42ce
AB
4760
4761@cindex MI commands in python
4762@cindex commands in python, GDB/MI
4763@cindex python commands, GDB/MI
c96452ad
TT
4764It is possible to add @sc{gdb/mi} (@pxref{GDB/MI}) commands
4765implemented in Python. A @sc{gdb/mi} command is implemented using an
740b42ce
AB
4766instance of the @code{gdb.MICommand} class, most commonly using a
4767subclass.
4768
4769@defun MICommand.__init__ (name)
4770The object initializer for @code{MICommand} registers the new command
4771with @value{GDBN}. This initializer is normally invoked from the
4772subclass' own @code{__init__} method.
4773
4774@var{name} is the name of the command. It must be a valid name of a
c96452ad
TT
4775@sc{gdb/mi} command, and in particular must start with a hyphen
4776(@code{-}). Reusing the name of a built-in @sc{gdb/mi} is not
740b42ce 4777allowed, and a @code{RuntimeError} will be raised. Using the name
c96452ad 4778of an @sc{gdb/mi} command previously defined in Python is allowed, the
740b42ce
AB
4779previous command will be replaced with the new command.
4780@end defun
4781
4782@defun MICommand.invoke (arguments)
4783This method is called by @value{GDBN} when the new MI command is
4784invoked.
4785
4786@var{arguments} is a list of strings. Note, that @code{--thread}
4787and @code{--frame} arguments are handled by @value{GDBN} itself therefore
4788they do not show up in @code{arguments}.
4789
4790If this method raises an exception, then it is turned into a
c96452ad 4791@sc{gdb/mi} @code{^error} response. Only @code{gdb.GdbError}
740b42ce
AB
4792exceptions (or its sub-classes) should be used for reporting errors to
4793users, any other exception type is treated as a failure of the
4794@code{invoke} method, and the exception will be printed to the error
4795stream according to the @kbd{set python print-stack} setting
4796(@pxref{set_python_print_stack,,@kbd{set python print-stack}}).
4797
c96452ad 4798If this method returns @code{None}, then the @sc{gdb/mi} command will
740b42ce
AB
4799return a @code{^done} response with no additional values.
4800
4801Otherwise, the return value must be a dictionary, which is converted
c96452ad 4802to a @sc{gdb/mi} @var{result-record} (@pxref{GDB/MI Output Syntax}).
740b42ce
AB
4803The keys of this dictionary must be strings, and are used as
4804@var{variable} names in the @var{result-record}, these strings must
4805comply with the naming rules detailed below. The values of this
4806dictionary are recursively handled as follows:
4807
4808@itemize
4809@item
4810If the value is Python sequence or iterator, it is converted to
c96452ad 4811@sc{gdb/mi} @var{list} with elements converted recursively.
740b42ce
AB
4812
4813@item
4814If the value is Python dictionary, it is converted to
c96452ad 4815@sc{gdb/mi} @var{tuple}. Keys in that dictionary must be strings,
740b42ce
AB
4816which comply with the @var{variable} naming rules detailed below.
4817Values are converted recursively.
4818
4819@item
4820Otherwise, value is first converted to a Python string using
c96452ad 4821@code{str ()} and then converted to @sc{gdb/mi} @var{const}.
740b42ce
AB
4822@end itemize
4823
c96452ad 4824The strings used for @var{variable} names in the @sc{gdb/mi} output
740b42ce
AB
4825must follow the following rules; the string must be at least one
4826character long, the first character must be in the set
4827@code{[a-zA-Z]}, while every subsequent character must be in the set
4828@code{[-_a-zA-Z0-9]}.
4829@end defun
4830
4831An instance of @code{MICommand} has the following attributes:
4832
4833@defvar MICommand.name
c96452ad 4834A string, the name of this @sc{gdb/mi} command, as was passed to the
740b42ce
AB
4835@code{__init__} method. This attribute is read-only.
4836@end defvar
4837
4838@defvar MICommand.installed
4839A boolean value indicating if this command is installed ready for a
4840user to call from the command line. Commands are automatically
4841installed when they are instantiated, after which this attribute will
4842be @code{True}.
4843
4844If later, a new command is created with the same name, then the
4845original command will become uninstalled, and this attribute will be
4846@code{False}.
4847
4848This attribute is read-write, setting this attribute to @code{False}
4849will uninstall the command, removing it from the set of available
4850commands. Setting this attribute to @code{True} will install the
4851command for use. If there is already a Python command with this name
4852installed, the currently installed command will be uninstalled, and
a8afc8a7 4853this command installed in its stead.
740b42ce
AB
4854@end defvar
4855
12d290fb 4856The following code snippet shows how some trivial MI commands can be
740b42ce
AB
4857implemented in Python:
4858
4859@smallexample
4860class MIEcho(gdb.MICommand):
4861 """Echo arguments passed to the command."""
4862
4863 def __init__(self, name, mode):
4864 self._mode = mode
4865 super(MIEcho, self).__init__(name)
4866
4867 def invoke(self, argv):
4868 if self._mode == 'dict':
4869 return @{ 'dict': @{ 'argv' : argv @} @}
4870 elif self._mode == 'list':
4871 return @{ 'list': argv @}
4872 else:
4873 return @{ 'string': ", ".join(argv) @}
4874
4875
4876MIEcho("-echo-dict", "dict")
4877MIEcho("-echo-list", "list")
4878MIEcho("-echo-string", "string")
4879@end smallexample
4880
4881The last three lines instantiate the class three times, creating three
c96452ad 4882new @sc{gdb/mi} commands @code{-echo-dict}, @code{-echo-list}, and
740b42ce
AB
4883@code{-echo-string}. Each time a subclass of @code{gdb.MICommand} is
4884instantiated, the new command is automatically registered with
4885@value{GDBN}.
4886
4887Depending on how the Python code is read into @value{GDBN}, you may
4888need to import the @code{gdb} module explicitly.
4889
4890The following example shows a @value{GDBN} session in which the above
4891commands have been added:
4892
4893@smallexample
4894(@value{GDBP})
4895-echo-dict abc def ghi
4896^done,dict=@{argv=["abc","def","ghi"]@}
4897(@value{GDBP})
4898-echo-list abc def ghi
4899^done,list=["abc","def","ghi"]
4900(@value{GDBP})
4901-echo-string abc def ghi
4902^done,string="abc, def, ghi"
4903(@value{GDBP})
4904@end smallexample
4905
c97d123d
TT
4906Conversely, it is possible to execute @sc{gdb/mi} commands from
4907Python, with the results being a Python object and not a
4908specially-formatted string. This is done with the
4909@code{gdb.execute_mi} function.
4910
c97d123d
TT
4911@defun gdb.execute_mi (command @r{[}, arg @r{]}@dots{})
4912Invoke a @sc{gdb/mi} command. @var{command} is the name of the
4913command, a string. The arguments, @var{arg}, are passed to the
4914command. Each argument must also be a string.
4915
4916This function returns a Python dictionary whose contents reflect the
4917corresponding @sc{GDB/MI} command's output. Refer to the
4918documentation for these commands for details. Lists are represented
4919as Python lists, and tuples are represented as Python dictionaries.
4920
4921If the command fails, it will raise a Python exception.
4922@end defun
4923
4924Here is how this works using the commands from the example above:
4925
4926@smallexample
4927(@value{GDBP}) python print(gdb.execute_mi("-echo-dict", "abc", "def", "ghi"))
4928@{'dict': @{'argv': ['abc', 'def', 'ghi']@}@}
4929(@value{GDBP}) python print(gdb.execute_mi("-echo-list", "abc", "def", "ghi"))
4930@{'list': ['abc', 'def', 'ghi']@}
4931(@value{GDBP}) python print(gdb.execute_mi("-echo-string", "abc", "def", "ghi"))
4932@{'string': 'abc, def, ghi'@}
4933@end smallexample
4934
4825fd2d
JV
4935@node GDB/MI Notifications In Python
4936@subsubsection @sc{gdb/mi} Notifications In Python
4937
4938@cindex MI notifications in python
4939@cindex notifications in python, GDB/MI
4940@cindex python notifications, GDB/MI
4941
4942It is possible to emit @sc{gdb/mi} notifications from
4943Python. Use the @code{gdb.notify_mi} function to do that.
4944
4945@defun gdb.notify_mi (name @r{[}, data@r{]})
4946Emit a @sc{gdb/mi} asynchronous notification. @var{name} is the name of the
4947notification, consisting of alphanumeric characters and a hyphen (@code{-}).
4948@var{data} is any additional data to be emitted with the notification, passed
4949as a Python dictionary. This argument is optional. The dictionary is converted
4950to a @sc{gdb/mi} @var{result} records (@pxref{GDB/MI Output Syntax}) the same way
4951as result of Python MI command (@pxref{GDB/MI Commands In Python}).
4952
4953If @var{data} is @code{None} then no additional values are emitted.
4954@end defun
4955
4956While using existing notification names (@pxref{GDB/MI Async Records}) with
4957@code{gdb.notify_mi} is allowed, users are encouraged to prefix user-defined
4958notification with a hyphen (@code{-}) to avoid possible conflict.
4959@value{GDBN} will never introduce notification starting with hyphen.
4960
4961Here is how to emit @code{=-connection-removed} whenever a connection to remote
4962GDB server is closed (@pxref{Connections In Python}):
4963
4964@smallexample
4965def notify_connection_removed(event):
4966 data = @{"id": event.connection.num, "type": event.connection.type@}
4967 gdb.notify_mi("-connection-removed", data)
4968
4969
4970gdb.events.connection_removed.connect(notify_connection_removed)
4971@end smallexample
4972
4973Then, each time a connection is closed, there will be a notification on MI channel:
4974
4975@smallexample
4976=-connection-removed,id="1",type="remote"
4977@end smallexample
4978
329baa95
DE
4979@node Parameters In Python
4980@subsubsection Parameters In Python
4981
4982@cindex parameters in python
4983@cindex python parameters
4984@tindex gdb.Parameter
4985@tindex Parameter
4986You can implement new @value{GDBN} parameters using Python. A new
4987parameter is implemented as an instance of the @code{gdb.Parameter}
4988class.
4989
4990Parameters are exposed to the user via the @code{set} and
4991@code{show} commands. @xref{Help}.
4992
4993There are many parameters that already exist and can be set in
4994@value{GDBN}. Two examples are: @code{set follow fork} and
4995@code{set charset}. Setting these parameters influences certain
4996behavior in @value{GDBN}. Similarly, you can define parameters that
4997can be used to influence behavior in custom Python scripts and commands.
4998
ebb83b77 4999@defun Parameter.__init__ (name, command_class, parameter_class @r{[}, enum_sequence@r{]})
329baa95
DE
5000The object initializer for @code{Parameter} registers the new
5001parameter with @value{GDBN}. This initializer is normally invoked
5002from the subclass' own @code{__init__} method.
5003
5004@var{name} is the name of the new parameter. If @var{name} consists
5005of multiple words, then the initial words are looked for as prefix
5006parameters. An example of this can be illustrated with the
5007@code{set print} set of parameters. If @var{name} is
5008@code{print foo}, then @code{print} will be searched as the prefix
5009parameter. In this case the parameter can subsequently be accessed in
5010@value{GDBN} as @code{set print foo}.
5011
5012If @var{name} consists of multiple words, and no prefix parameter group
5013can be found, an exception is raised.
5014
ebb83b77 5015@var{command_class} should be one of the @samp{COMMAND_} constants
740b42ce 5016(@pxref{CLI Commands In Python}). This argument tells @value{GDBN} how to
329baa95
DE
5017categorize the new parameter in the help system.
5018
ebb83b77 5019@var{parameter_class} should be one of the @samp{PARAM_} constants
329baa95
DE
5020defined below. This argument tells @value{GDBN} the type of the new
5021parameter; this information is used for input validation and
5022completion.
5023
ebb83b77
TT
5024If @var{parameter_class} is @code{PARAM_ENUM}, then
5025@var{enum_sequence} must be a sequence of strings. These strings
329baa95
DE
5026represent the possible values for the parameter.
5027
ebb83b77 5028If @var{parameter_class} is not @code{PARAM_ENUM}, then the presence
329baa95
DE
5029of a fourth argument will cause an exception to be thrown.
5030
bbea6807
AB
5031The help text for the new parameter includes the Python documentation
5032string from the parameter's class, if there is one. If there is no
5033documentation string, a default value is used. The documentation
5034string is included in the output of the parameters @code{help set} and
5035@code{help show} commands, and should be written taking this into
5036account.
329baa95
DE
5037@end defun
5038
5039@defvar Parameter.set_doc
5040If this attribute exists, and is a string, then its value is used as
bbea6807
AB
5041the first part of the help text for this parameter's @code{set}
5042command. The second part of the help text is taken from the
5043documentation string for the parameter's class, if there is one.
5044
5045The value of @code{set_doc} should give a brief summary specific to
5046the set action, this text is only displayed when the user runs the
5047@code{help set} command for this parameter. The class documentation
5048should be used to give a fuller description of what the parameter
5049does, this text is displayed for both the @code{help set} and
5050@code{help show} commands.
5051
5052The @code{set_doc} value is examined when @code{Parameter.__init__} is
5053invoked; subsequent changes have no effect.
329baa95
DE
5054@end defvar
5055
5056@defvar Parameter.show_doc
5057If this attribute exists, and is a string, then its value is used as
bbea6807
AB
5058the first part of the help text for this parameter's @code{show}
5059command. The second part of the help text is taken from the
5060documentation string for the parameter's class, if there is one.
5061
5062The value of @code{show_doc} should give a brief summary specific to
5063the show action, this text is only displayed when the user runs the
5064@code{help show} command for this parameter. The class documentation
5065should be used to give a fuller description of what the parameter
5066does, this text is displayed for both the @code{help set} and
5067@code{help show} commands.
5068
5069The @code{show_doc} value is examined when @code{Parameter.__init__}
5070is invoked; subsequent changes have no effect.
329baa95
DE
5071@end defvar
5072
5073@defvar Parameter.value
5074The @code{value} attribute holds the underlying value of the
5075parameter. It can be read and assigned to just as any other
5076attribute. @value{GDBN} does validation when assignments are made.
5077@end defvar
5078
984ee559
TT
5079There are two methods that may be implemented in any @code{Parameter}
5080class. These are:
329baa95
DE
5081
5082@defun Parameter.get_set_string (self)
984ee559
TT
5083If this method exists, @value{GDBN} will call it when a
5084@var{parameter}'s value has been changed via the @code{set} API (for
5085example, @kbd{set foo off}). The @code{value} attribute has already
5086been populated with the new value and may be used in output. This
5087method must return a string. If the returned string is not empty,
5088@value{GDBN} will present it to the user.
ae778caf
TT
5089
5090If this method raises the @code{gdb.GdbError} exception
5091(@pxref{Exception Handling}), then @value{GDBN} will print the
5092exception's string and the @code{set} command will fail. Note,
5093however, that the @code{value} attribute will not be reset in this
5094case. So, if your parameter must validate values, it should store the
5095old value internally and reset the exposed value, like so:
5096
5097@smallexample
5098class ExampleParam (gdb.Parameter):
5099 def __init__ (self, name):
5100 super (ExampleParam, self).__init__ (name,
5101 gdb.COMMAND_DATA,
5102 gdb.PARAM_BOOLEAN)
5103 self.value = True
5104 self.saved_value = True
5105 def validate(self):
5106 return False
5107 def get_set_string (self):
5108 if not self.validate():
5109 self.value = self.saved_value
5110 raise gdb.GdbError('Failed to validate')
5111 self.saved_value = self.value
763b8efd 5112 return ""
ae778caf 5113@end smallexample
329baa95
DE
5114@end defun
5115
5116@defun Parameter.get_show_string (self, svalue)
5117@value{GDBN} will call this method when a @var{parameter}'s
5118@code{show} API has been invoked (for example, @kbd{show foo}). The
5119argument @code{svalue} receives the string representation of the
5120current value. This method must return a string.
5121@end defun
5122
5123When a new parameter is defined, its type must be specified. The
5124available types are represented by constants defined in the @code{gdb}
5125module:
5126
5127@table @code
5128@findex PARAM_BOOLEAN
5129@findex gdb.PARAM_BOOLEAN
5130@item gdb.PARAM_BOOLEAN
5131The value is a plain boolean. The Python boolean values, @code{True}
5132and @code{False} are the only valid values.
5133
5134@findex PARAM_AUTO_BOOLEAN
5135@findex gdb.PARAM_AUTO_BOOLEAN
5136@item gdb.PARAM_AUTO_BOOLEAN
5137The value has three possible states: true, false, and @samp{auto}. In
5138Python, true and false are represented using boolean constants, and
5139@samp{auto} is represented using @code{None}.
5140
5141@findex PARAM_UINTEGER
5142@findex gdb.PARAM_UINTEGER
5143@item gdb.PARAM_UINTEGER
7aeb03e2
MR
5144The value is an unsigned integer. The value of @code{None} should be
5145interpreted to mean ``unlimited'' (literal @code{'unlimited'} can also
5146be used to set that value), and the value of 0 is reserved and should
5147not be used.
329baa95
DE
5148
5149@findex PARAM_INTEGER
5150@findex gdb.PARAM_INTEGER
5151@item gdb.PARAM_INTEGER
7aeb03e2
MR
5152The value is a signed integer. The value of @code{None} should be
5153interpreted to mean ``unlimited'' (literal @code{'unlimited'} can also
5154be used to set that value), and the value of 0 is reserved and should
5155not be used.
329baa95
DE
5156
5157@findex PARAM_STRING
5158@findex gdb.PARAM_STRING
5159@item gdb.PARAM_STRING
5160The value is a string. When the user modifies the string, any escape
5161sequences, such as @samp{\t}, @samp{\f}, and octal escapes, are
5162translated into corresponding characters and encoded into the current
5163host charset.
5164
5165@findex PARAM_STRING_NOESCAPE
5166@findex gdb.PARAM_STRING_NOESCAPE
5167@item gdb.PARAM_STRING_NOESCAPE
5168The value is a string. When the user modifies the string, escapes are
5169passed through untranslated.
5170
5171@findex PARAM_OPTIONAL_FILENAME
5172@findex gdb.PARAM_OPTIONAL_FILENAME
5173@item gdb.PARAM_OPTIONAL_FILENAME
5174The value is a either a filename (a string), or @code{None}.
5175
5176@findex PARAM_FILENAME
5177@findex gdb.PARAM_FILENAME
5178@item gdb.PARAM_FILENAME
5179The value is a filename. This is just like
5180@code{PARAM_STRING_NOESCAPE}, but uses file names for completion.
5181
5182@findex PARAM_ZINTEGER
5183@findex gdb.PARAM_ZINTEGER
5184@item gdb.PARAM_ZINTEGER
7aeb03e2
MR
5185The value is a signed integer. This is like @code{PARAM_INTEGER},
5186except that 0 is allowed and the value of @code{None} is not supported.
329baa95 5187
0489430a
TT
5188@findex PARAM_ZUINTEGER
5189@findex gdb.PARAM_ZUINTEGER
5190@item gdb.PARAM_ZUINTEGER
7aeb03e2
MR
5191The value is an unsigned integer. This is like @code{PARAM_UINTEGER},
5192except that 0 is allowed and the value of @code{None} is not supported.
0489430a
TT
5193
5194@findex PARAM_ZUINTEGER_UNLIMITED
5195@findex gdb.PARAM_ZUINTEGER_UNLIMITED
5196@item gdb.PARAM_ZUINTEGER_UNLIMITED
7aeb03e2
MR
5197The value is a signed integer. This is like @code{PARAM_INTEGER}
5198including that the value of @code{None} should be interpreted to mean
5199``unlimited'' (literal @code{'unlimited'} can also be used to set that
5200value), except that 0 is allowed, and the value cannot be negative,
5201except the special value -1 is returned for the setting of ``unlimited''.
0489430a 5202
329baa95
DE
5203@findex PARAM_ENUM
5204@findex gdb.PARAM_ENUM
5205@item gdb.PARAM_ENUM
5206The value is a string, which must be one of a collection string
5207constants provided when the parameter is created.
5208@end table
5209
5210@node Functions In Python
5211@subsubsection Writing new convenience functions
5212
5213@cindex writing convenience functions
5214@cindex convenience functions in python
5215@cindex python convenience functions
5216@tindex gdb.Function
5217@tindex Function
5218You can implement new convenience functions (@pxref{Convenience Vars})
5219in Python. A convenience function is an instance of a subclass of the
5220class @code{gdb.Function}.
5221
5222@defun Function.__init__ (name)
5223The initializer for @code{Function} registers the new function with
5224@value{GDBN}. The argument @var{name} is the name of the function,
5225a string. The function will be visible to the user as a convenience
5226variable of type @code{internal function}, whose name is the same as
5227the given @var{name}.
5228
5229The documentation for the new function is taken from the documentation
5230string for the new class.
5231@end defun
5232
ebb83b77 5233@defun Function.invoke (*args)
329baa95
DE
5234When a convenience function is evaluated, its arguments are converted
5235to instances of @code{gdb.Value}, and then the function's
5236@code{invoke} method is called. Note that @value{GDBN} does not
5237predetermine the arity of convenience functions. Instead, all
5238available arguments are passed to @code{invoke}, following the
5239standard Python calling convention. In particular, a convenience
5240function can have default values for parameters without ill effect.
5241
5242The return value of this method is used as its value in the enclosing
5243expression. If an ordinary Python value is returned, it is converted
5244to a @code{gdb.Value} following the usual rules.
5245@end defun
5246
5247The following code snippet shows how a trivial convenience function can
5248be implemented in Python:
5249
5250@smallexample
5251class Greet (gdb.Function):
5252 """Return string to greet someone.
5253Takes a name as argument."""
5254
5255 def __init__ (self):
5256 super (Greet, self).__init__ ("greet")
5257
5258 def invoke (self, name):
5259 return "Hello, %s!" % name.string ()
5260
5261Greet ()
5262@end smallexample
5263
5264The last line instantiates the class, and is necessary to trigger the
5265registration of the function with @value{GDBN}. Depending on how the
5266Python code is read into @value{GDBN}, you may need to import the
5267@code{gdb} module explicitly.
5268
5269Now you can use the function in an expression:
5270
5271@smallexample
5272(gdb) print $greet("Bob")
5273$1 = "Hello, Bob!"
5274@end smallexample
5275
5276@node Progspaces In Python
5277@subsubsection Program Spaces In Python
5278
5279@cindex progspaces in python
5280@tindex gdb.Progspace
5281@tindex Progspace
5282A program space, or @dfn{progspace}, represents a symbolic view
5283of an address space.
5284It consists of all of the objfiles of the program.
5285@xref{Objfiles In Python}.
65c574f6 5286@xref{Inferiors Connections and Programs, program spaces}, for more details
329baa95
DE
5287about program spaces.
5288
5289The following progspace-related functions are available in the
5290@code{gdb} module:
5291
329baa95
DE
5292@defun gdb.current_progspace ()
5293This function returns the program space of the currently selected inferior.
65c574f6 5294@xref{Inferiors Connections and Programs}. This is identical to
a40bf0c2
SM
5295@code{gdb.selected_inferior().progspace} (@pxref{Inferiors In Python}) and is
5296included for historical compatibility.
329baa95
DE
5297@end defun
5298
329baa95
DE
5299@defun gdb.progspaces ()
5300Return a sequence of all the progspaces currently known to @value{GDBN}.
5301@end defun
5302
5303Each progspace is represented by an instance of the @code{gdb.Progspace}
5304class.
5305
5306@defvar Progspace.filename
ce65386d
AB
5307The file name, as a string, of the main symbol file (from which debug
5308symbols have been loaded) for the progspace, e.g.@: the argument to
5309the @kbd{symbol-file} or @kbd{file} commands.
5310
5311If there is no main symbol table currently loaded, then this attribute
5312will be @code{None}.
329baa95
DE
5313@end defvar
5314
5ce85461
AB
5315@defvar Progspace.symbol_file
5316The @code{gdb.Objfile} representing the main symbol file (from which
5317debug symbols have been loaded) for the @code{gdb.Progspace}. This is
5318the symbol file set by the @kbd{symbol-file} or @kbd{file} commands.
5319
5320This will be the @code{gdb.Objfile} representing
5321@code{Progspace.filename} when @code{Progspace.filename} is not
5322@code{None}.
5323
5324If there is no main symbol table currently loaded, then this attribute
5325will be @code{None}.
5326
5327If the @code{Progspace} is invalid, i.e.@:, when
5328@code{Progspace.is_valid()} returns @code{False}, then attempting to
5329access this attribute will raise a @code{RuntimeError} exception.
5330@end defvar
5331
4e02aca0
AB
5332@defvar Progspace.executable_filename
5333The file name, as a string, of the executable file in use by this
5334program space. The executable file is the file that @value{GDBN} will
5335invoke in order to start an inferior when using a native target. The
5336file name within this attribute is updated by the @kbd{exec-file} and
5337@kbd{file} commands.
5338
5339If no executable is currently set within this @code{Progspace} then
5340this attribute contains @code{None}.
5341
5342If the @code{Progspace} is invalid, i.e.@:, when
5343@code{Progspace.is_valid()} returns @code{False}, then attempting to
5344access this attribute will raise a @code{RuntimeError} exception.
5345@end defvar
5346
329baa95
DE
5347@defvar Progspace.pretty_printers
5348The @code{pretty_printers} attribute is a list of functions. It is
5349used to look up pretty-printers. A @code{Value} is passed to each
5350function in order; if the function returns @code{None}, then the
5351search continues. Otherwise, the return value should be an object
5352which is used to format the value. @xref{Pretty Printing API}, for more
5353information.
5354@end defvar
5355
5356@defvar Progspace.type_printers
5357The @code{type_printers} attribute is a list of type printer objects.
5358@xref{Type Printing API}, for more information.
5359@end defvar
5360
5361@defvar Progspace.frame_filters
5362The @code{frame_filters} attribute is a dictionary of frame filter
5363objects. @xref{Frame Filter API}, for more information.
5364@end defvar
5365
8f6c452b
AB
5366@defvar Progspace.missing_debug_handlers
5367The @code{missing_debug_handlers} attribute is a list of the missing
5368debug handler objects for this program space. @xref{Missing Debug
5369Info In Python}, for more information.
5370@end defvar
5371
8743a9cd
TT
5372A program space has the following methods:
5373
8743a9cd
TT
5374@defun Progspace.block_for_pc (pc)
5375Return the innermost @code{gdb.Block} containing the given @var{pc}
5376value. If the block cannot be found for the @var{pc} value specified,
5377the function will return @code{None}.
5378@end defun
5379
8743a9cd
TT
5380@defun Progspace.find_pc_line (pc)
5381Return the @code{gdb.Symtab_and_line} object corresponding to the
5382@var{pc} value. @xref{Symbol Tables In Python}. If an invalid value
5383of @var{pc} is passed as an argument, then the @code{symtab} and
5384@code{line} attributes of the returned @code{gdb.Symtab_and_line}
5385object will be @code{None} and 0 respectively.
5386@end defun
5387
8743a9cd
TT
5388@defun Progspace.is_valid ()
5389Returns @code{True} if the @code{gdb.Progspace} object is valid,
5390@code{False} if not. A @code{gdb.Progspace} object can become invalid
5391if the program space file it refers to is not referenced by any
5392inferior. All other @code{gdb.Progspace} methods will throw an
5393exception if it is invalid at the time the method is called.
5394@end defun
5395
8743a9cd
TT
5396@defun Progspace.objfiles ()
5397Return a sequence of all the objfiles referenced by this program
5398space. @xref{Objfiles In Python}.
5399@end defun
5400
8743a9cd
TT
5401@defun Progspace.solib_name (address)
5402Return the name of the shared library holding the given @var{address}
5403as a string, or @code{None}.
5404@end defun
5405
27b2eff1
TT
5406@defun Progspace.objfile_for_address (address)
5407Return the @code{gdb.Objfile} holding the given address, or
5408@code{None} if no objfile covers it.
5409@end defun
5410
02be9a71
DE
5411One may add arbitrary attributes to @code{gdb.Progspace} objects
5412in the usual Python way.
5413This is useful if, for example, one needs to do some extra record keeping
5414associated with the program space.
5415
53d08890
AB
5416@xref{choosing attribute names}, for guidance on selecting a suitable
5417name for new attributes.
5418
02be9a71
DE
5419In this contrived example, we want to perform some processing when
5420an objfile with a certain symbol is loaded, but we only want to do
5421this once because it is expensive. To achieve this we record the results
5422with the program space because we can't predict when the desired objfile
5423will be loaded.
5424
5425@smallexample
7ccdf9c0
AB
5426(@value{GDBP}) python
5427@group
02be9a71
DE
5428def clear_objfiles_handler(event):
5429 event.progspace.expensive_computation = None
5430def expensive(symbol):
5431 """A mock routine to perform an "expensive" computation on symbol."""
f3bdc2db 5432 print ("Computing the answer to the ultimate question ...")
02be9a71 5433 return 42
7ccdf9c0
AB
5434@end group
5435@group
02be9a71
DE
5436def new_objfile_handler(event):
5437 objfile = event.new_objfile
5438 progspace = objfile.progspace
5439 if not hasattr(progspace, 'expensive_computation') or \
5440 progspace.expensive_computation is None:
5441 # We use 'main' for the symbol to keep the example simple.
5442 # Note: There's no current way to constrain the lookup
5443 # to one objfile.
5444 symbol = gdb.lookup_global_symbol('main')
5445 if symbol is not None:
5446 progspace.expensive_computation = expensive(symbol)
5447gdb.events.clear_objfiles.connect(clear_objfiles_handler)
5448gdb.events.new_objfile.connect(new_objfile_handler)
5449end
7ccdf9c0
AB
5450@end group
5451@group
5452(@value{GDBP}) file /tmp/hello
0bab6cf1 5453Reading symbols from /tmp/hello...
02be9a71 5454Computing the answer to the ultimate question ...
7ccdf9c0 5455(@value{GDBP}) python print(gdb.current_progspace().expensive_computation)
02be9a71 545642
7ccdf9c0 5457(@value{GDBP}) run
02be9a71
DE
5458Starting program: /tmp/hello
5459Hello.
5460[Inferior 1 (process 4242) exited normally]
7ccdf9c0 5461@end group
02be9a71
DE
5462@end smallexample
5463
329baa95
DE
5464@node Objfiles In Python
5465@subsubsection Objfiles In Python
5466
5467@cindex objfiles in python
5468@tindex gdb.Objfile
5469@tindex Objfile
5470@value{GDBN} loads symbols for an inferior from various
5471symbol-containing files (@pxref{Files}). These include the primary
5472executable file, any shared libraries used by the inferior, and any
5473separate debug info files (@pxref{Separate Debug Files}).
5474@value{GDBN} calls these symbol-containing files @dfn{objfiles}.
5475
5476The following objfile-related functions are available in the
5477@code{gdb} module:
5478
329baa95
DE
5479@defun gdb.current_objfile ()
5480When auto-loading a Python script (@pxref{Python Auto-loading}), @value{GDBN}
5481sets the ``current objfile'' to the corresponding objfile. This
5482function returns the current objfile. If there is no current objfile,
5483this function returns @code{None}.
5484@end defun
5485
329baa95 5486@defun gdb.objfiles ()
74d3fbbb
SM
5487Return a sequence of objfiles referenced by the current program space.
5488@xref{Objfiles In Python}, and @ref{Progspaces In Python}. This is identical
5489to @code{gdb.selected_inferior().progspace.objfiles()} and is included for
5490historical compatibility.
329baa95
DE
5491@end defun
5492
b13d7831 5493@defun gdb.lookup_objfile (name @r{[}, by_build_id@r{]})
6dddd6a5
DE
5494Look up @var{name}, a file name or build ID, in the list of objfiles
5495for the current program space (@pxref{Progspaces In Python}).
5496If the objfile is not found throw the Python @code{ValueError} exception.
5497
5498If @var{name} is a relative file name, then it will match any
5499source file name with the same trailing components. For example, if
5500@var{name} is @samp{gcc/expr.c}, then it will match source file
5501name of @file{/build/trunk/gcc/expr.c}, but not
5502@file{/build/trunk/libcpp/expr.c} or @file{/build/trunk/gcc/x-expr.c}.
5503
5504If @var{by_build_id} is provided and is @code{True} then @var{name}
5505is the build ID of the objfile. Otherwise, @var{name} is a file name.
5506This is supported only on some operating systems, notably those which use
5507the ELF format for binary files and the @sc{gnu} Binutils. For more details
5508about this feature, see the description of the @option{--build-id}
f5a476a7 5509command-line option in @ref{Options, , Command Line Options, ld,
6dddd6a5
DE
5510The GNU Linker}.
5511@end defun
5512
329baa95
DE
5513Each objfile is represented by an instance of the @code{gdb.Objfile}
5514class.
5515
5516@defvar Objfile.filename
1b549396
DE
5517The file name of the objfile as a string, with symbolic links resolved.
5518
5519The value is @code{None} if the objfile is no longer valid.
5520See the @code{gdb.Objfile.is_valid} method, described below.
329baa95
DE
5521@end defvar
5522
3a8b707a
DE
5523@defvar Objfile.username
5524The file name of the objfile as specified by the user as a string.
5525
5526The value is @code{None} if the objfile is no longer valid.
5527See the @code{gdb.Objfile.is_valid} method, described below.
5528@end defvar
5529
99298c95
TT
5530@defvar Objfile.is_file
5531An objfile often comes from an ordinary file, but in some cases it may
5532be constructed from the contents of memory. This attribute is
5533@code{True} for file-backed objfiles, and @code{False} for other
5534kinds.
5535@end defvar
5536
a0be3e44
DE
5537@defvar Objfile.owner
5538For separate debug info objfiles this is the corresponding @code{gdb.Objfile}
5539object that debug info is being provided for.
5540Otherwise this is @code{None}.
5541Separate debug info objfiles are added with the
5542@code{gdb.Objfile.add_separate_debug_file} method, described below.
5543@end defvar
5544
7c50a931
DE
5545@defvar Objfile.build_id
5546The build ID of the objfile as a string.
5547If the objfile does not have a build ID then the value is @code{None}.
5548
5549This is supported only on some operating systems, notably those which use
5550the ELF format for binary files and the @sc{gnu} Binutils. For more details
5551about this feature, see the description of the @option{--build-id}
f5a476a7 5552command-line option in @ref{Options, , Command Line Options, ld,
7c50a931
DE
5553The GNU Linker}.
5554@end defvar
5555
d096d8c1
DE
5556@defvar Objfile.progspace
5557The containing program space of the objfile as a @code{gdb.Progspace}
5558object. @xref{Progspaces In Python}.
5559@end defvar
5560
329baa95
DE
5561@defvar Objfile.pretty_printers
5562The @code{pretty_printers} attribute is a list of functions. It is
5563used to look up pretty-printers. A @code{Value} is passed to each
5564function in order; if the function returns @code{None}, then the
5565search continues. Otherwise, the return value should be an object
5566which is used to format the value. @xref{Pretty Printing API}, for more
5567information.
5568@end defvar
5569
5570@defvar Objfile.type_printers
5571The @code{type_printers} attribute is a list of type printer objects.
5572@xref{Type Printing API}, for more information.
5573@end defvar
5574
5575@defvar Objfile.frame_filters
5576The @code{frame_filters} attribute is a dictionary of frame filter
5577objects. @xref{Frame Filter API}, for more information.
5578@end defvar
5579
02be9a71
DE
5580One may add arbitrary attributes to @code{gdb.Objfile} objects
5581in the usual Python way.
5582This is useful if, for example, one needs to do some extra record keeping
5583associated with the objfile.
5584
53d08890
AB
5585@xref{choosing attribute names}, for guidance on selecting a suitable
5586name for new attributes.
5587
02be9a71
DE
5588In this contrived example we record the time when @value{GDBN}
5589loaded the objfile.
5590
5591@smallexample
7ccdf9c0
AB
5592@group
5593(@value{GDBP}) python
02be9a71
DE
5594import datetime
5595def new_objfile_handler(event):
5596 # Set the time_loaded attribute of the new objfile.
5597 event.new_objfile.time_loaded = datetime.datetime.today()
5598gdb.events.new_objfile.connect(new_objfile_handler)
5599end
7ccdf9c0
AB
5600@end group
5601@group
5602(@value{GDBP}) file ./hello
0bab6cf1 5603Reading symbols from ./hello...
7ccdf9c0 5604(@value{GDBP}) python print(gdb.objfiles()[0].time_loaded)
02be9a71 56052014-10-09 11:41:36.770345
7ccdf9c0 5606@end group
02be9a71
DE
5607@end smallexample
5608
329baa95
DE
5609A @code{gdb.Objfile} object has the following methods:
5610
5611@defun Objfile.is_valid ()
5612Returns @code{True} if the @code{gdb.Objfile} object is valid,
5613@code{False} if not. A @code{gdb.Objfile} object can become invalid
5614if the object file it refers to is not loaded in @value{GDBN} any
5615longer. All other @code{gdb.Objfile} methods will throw an exception
5616if it is invalid at the time the method is called.
5617@end defun
5618
86e4ed39
DE
5619@defun Objfile.add_separate_debug_file (file)
5620Add @var{file} to the list of files that @value{GDBN} will search for
5621debug information for the objfile.
5622This is useful when the debug info has been removed from the program
5623and stored in a separate file. @value{GDBN} has built-in support for
5624finding separate debug info files (@pxref{Separate Debug Files}), but if
5625the file doesn't live in one of the standard places that @value{GDBN}
5626searches then this function can be used to add a debug info file
5627from a different place.
5628@end defun
5629
c620ed88
CB
5630@defun Objfile.lookup_global_symbol (name @r{[}, domain@r{]})
5631Search for a global symbol named @var{name} in this objfile. Optionally, the
5632search scope can be restricted with the @var{domain} argument.
5633The @var{domain} argument must be a domain constant defined in the @code{gdb}
5634module and described in @ref{Symbols In Python}. This function is similar to
5635@code{gdb.lookup_global_symbol}, except that the search is limited to this
5636objfile.
5637
5638The result is a @code{gdb.Symbol} object or @code{None} if the symbol
5639is not found.
5640@end defun
5641
5642@defun Objfile.lookup_static_symbol (name @r{[}, domain@r{]})
5643Like @code{Objfile.lookup_global_symbol}, but searches for a global
5644symbol with static linkage named @var{name} in this objfile.
5645@end defun
5646
329baa95 5647@node Frames In Python
849cba3b 5648@subsubsection Accessing inferior stack frames from Python
329baa95
DE
5649
5650@cindex frames in python
5651When the debugged program stops, @value{GDBN} is able to analyze its call
5652stack (@pxref{Frames,,Stack frames}). The @code{gdb.Frame} class
5653represents a frame in the stack. A @code{gdb.Frame} object is only valid
5654while its corresponding frame exists in the inferior's stack. If you try
5655to use an invalid frame object, @value{GDBN} will throw a @code{gdb.error}
5656exception (@pxref{Exception Handling}).
5657
5658Two @code{gdb.Frame} objects can be compared for equality with the @code{==}
5659operator, like:
5660
5661@smallexample
5662(@value{GDBP}) python print gdb.newest_frame() == gdb.selected_frame ()
5663True
5664@end smallexample
5665
5666The following frame-related functions are available in the @code{gdb} module:
5667
329baa95
DE
5668@defun gdb.selected_frame ()
5669Return the selected frame object. (@pxref{Selection,,Selecting a Frame}).
5670@end defun
5671
329baa95
DE
5672@defun gdb.newest_frame ()
5673Return the newest frame object for the selected thread.
5674@end defun
5675
5676@defun gdb.frame_stop_reason_string (reason)
5677Return a string explaining the reason why @value{GDBN} stopped unwinding
5678frames, as expressed by the given @var{reason} code (an integer, see the
5679@code{unwind_stop_reason} method further down in this section).
5680@end defun
5681
e0f3fd7c
TT
5682@defun gdb.invalidate_cached_frames
5683@value{GDBN} internally keeps a cache of the frames that have been
5684unwound. This function invalidates this cache.
5685
5686This function should not generally be called by ordinary Python code.
5687It is documented for the sake of completeness.
5688@end defun
5689
329baa95
DE
5690A @code{gdb.Frame} object has the following methods:
5691
5692@defun Frame.is_valid ()
5693Returns true if the @code{gdb.Frame} object is valid, false if not.
5694A frame object can become invalid if the frame it refers to doesn't
5695exist anymore in the inferior. All @code{gdb.Frame} methods will throw
5696an exception if it is invalid at the time the method is called.
5697@end defun
5698
5699@defun Frame.name ()
5700Returns the function name of the frame, or @code{None} if it can't be
5701obtained.
5702@end defun
5703
5704@defun Frame.architecture ()
5705Returns the @code{gdb.Architecture} object corresponding to the frame's
5706architecture. @xref{Architectures In Python}.
5707@end defun
5708
5709@defun Frame.type ()
5710Returns the type of the frame. The value can be one of:
5711@table @code
5712@item gdb.NORMAL_FRAME
5713An ordinary stack frame.
5714
5715@item gdb.DUMMY_FRAME
5716A fake stack frame that was created by @value{GDBN} when performing an
5717inferior function call.
5718
5719@item gdb.INLINE_FRAME
5720A frame representing an inlined function. The function was inlined
5721into a @code{gdb.NORMAL_FRAME} that is older than this one.
5722
5723@item gdb.TAILCALL_FRAME
5724A frame representing a tail call. @xref{Tail Call Frames}.
5725
5726@item gdb.SIGTRAMP_FRAME
5727A signal trampoline frame. This is the frame created by the OS when
5728it calls into a signal handler.
5729
5730@item gdb.ARCH_FRAME
5731A fake stack frame representing a cross-architecture call.
5732
5733@item gdb.SENTINEL_FRAME
5734This is like @code{gdb.NORMAL_FRAME}, but it is only used for the
5735newest frame.
5736@end table
5737@end defun
5738
5739@defun Frame.unwind_stop_reason ()
5740Return an integer representing the reason why it's not possible to find
5741more frames toward the outermost frame. Use
5742@code{gdb.frame_stop_reason_string} to convert the value returned by this
5743function to a string. The value can be one of:
5744
5745@table @code
5746@item gdb.FRAME_UNWIND_NO_REASON
5747No particular reason (older frames should be available).
5748
5749@item gdb.FRAME_UNWIND_NULL_ID
5750The previous frame's analyzer returns an invalid result. This is no
5751longer used by @value{GDBN}, and is kept only for backward
5752compatibility.
5753
5754@item gdb.FRAME_UNWIND_OUTERMOST
5755This frame is the outermost.
5756
5757@item gdb.FRAME_UNWIND_UNAVAILABLE
5758Cannot unwind further, because that would require knowing the
5759values of registers or memory that have not been collected.
5760
5761@item gdb.FRAME_UNWIND_INNER_ID
5762This frame ID looks like it ought to belong to a NEXT frame,
5763but we got it for a PREV frame. Normally, this is a sign of
5764unwinder failure. It could also indicate stack corruption.
5765
5766@item gdb.FRAME_UNWIND_SAME_ID
5767This frame has the same ID as the previous one. That means
5768that unwinding further would almost certainly give us another
5769frame with exactly the same ID, so break the chain. Normally,
5770this is a sign of unwinder failure. It could also indicate
5771stack corruption.
5772
5773@item gdb.FRAME_UNWIND_NO_SAVED_PC
5774The frame unwinder did not find any saved PC, but we needed
5775one to unwind further.
5776
53e8a631
AB
5777@item gdb.FRAME_UNWIND_MEMORY_ERROR
5778The frame unwinder caused an error while trying to access memory.
5779
329baa95
DE
5780@item gdb.FRAME_UNWIND_FIRST_ERROR
5781Any stop reason greater or equal to this value indicates some kind
5782of error. This special value facilitates writing code that tests
5783for errors in unwinding in a way that will work correctly even if
5784the list of the other values is modified in future @value{GDBN}
5785versions. Using it, you could write:
5786@smallexample
5787reason = gdb.selected_frame().unwind_stop_reason ()
5788reason_str = gdb.frame_stop_reason_string (reason)
5789if reason >= gdb.FRAME_UNWIND_FIRST_ERROR:
33b5899f 5790 print ("An error occurred: %s" % reason_str)
329baa95
DE
5791@end smallexample
5792@end table
5793
5794@end defun
5795
5796@defun Frame.pc ()
5797Returns the frame's resume address.
5798@end defun
5799
5800@defun Frame.block ()
60c0454d
TT
5801Return the frame's code block. @xref{Blocks In Python}. If the frame
5802does not have a block -- for example, if there is no debugging
5803information for the code in question -- then this will throw an
5804exception.
329baa95
DE
5805@end defun
5806
5807@defun Frame.function ()
5808Return the symbol for the function corresponding to this frame.
5809@xref{Symbols In Python}.
5810@end defun
5811
5812@defun Frame.older ()
3f33695b
TT
5813Return the frame that called this frame. If this is the oldest frame,
5814return @code{None}.
329baa95
DE
5815@end defun
5816
5817@defun Frame.newer ()
3f33695b
TT
5818Return the frame called by this frame. If this is the newest frame,
5819return @code{None}.
329baa95
DE
5820@end defun
5821
5822@defun Frame.find_sal ()
5823Return the frame's symtab and line object.
5824@xref{Symbol Tables In Python}.
5825@end defun
5826
0f767f94 5827@anchor{gdbpy_frame_read_register}
5f3b99cf 5828@defun Frame.read_register (register)
43d5901d
AB
5829Return the value of @var{register} in this frame. Returns a
5830@code{Gdb.Value} object. Throws an exception if @var{register} does
5831not exist. The @var{register} argument must be one of the following:
5832@enumerate
5833@item
5834A string that is the name of a valid register (e.g., @code{'sp'} or
5835@code{'rax'}).
5836@item
5837A @code{gdb.RegisterDescriptor} object (@pxref{Registers In Python}).
5838@item
5839A @value{GDBN} internal, platform specific number. Using these
5840numbers is supported for historic reasons, but is not recommended as
5841future changes to @value{GDBN} could change the mapping between
5842numbers and the registers they represent, breaking any Python code
5843that uses the platform-specific numbers. The numbers are usually
5844found in the corresponding @file{@var{platform}-tdep.h} file in the
5845@value{GDBN} source tree.
5846@end enumerate
5847Using a string to access registers will be slightly slower than the
5848other two methods as @value{GDBN} must look up the mapping between
5849name and internal register number. If performance is critical
5850consider looking up and caching a @code{gdb.RegisterDescriptor}
5851object.
5f3b99cf
SS
5852@end defun
5853
329baa95
DE
5854@defun Frame.read_var (variable @r{[}, block@r{]})
5855Return the value of @var{variable} in this frame. If the optional
5856argument @var{block} is provided, search for the variable from that
5857block; otherwise start at the frame's current block (which is
697aa1b7
EZ
5858determined by the frame's current program counter). The @var{variable}
5859argument must be a string or a @code{gdb.Symbol} object; @var{block} must be a
329baa95
DE
5860@code{gdb.Block} object.
5861@end defun
5862
5863@defun Frame.select ()
5864Set this frame to be the selected frame. @xref{Stack, ,Examining the
5865Stack}.
5866@end defun
5867
4ead09a2
TT
5868@defun Frame.static_link ()
5869In some languages (e.g., Ada, but also a GNU C extension), a nested
5870function can access the variables in the outer scope. This is done
5871via a ``static link'', which is a reference from the nested frame to
5872the appropriate outer frame.
5873
5874This method returns this frame's static link frame, if one exists. If
5875there is no static link, this method returns @code{None}.
5876@end defun
5877
d52b8007
AB
5878@defun Frame.level ()
5879Return an integer, the stack frame level for this frame. @xref{Frames, ,Stack Frames}.
5880@end defun
5881
80fa4b2a
TT
5882@defun Frame.language ()
5883Return a string, the source language for this frame.
5884@end defun
5885
329baa95 5886@node Blocks In Python
849cba3b 5887@subsubsection Accessing blocks from Python
329baa95
DE
5888
5889@cindex blocks in python
5890@tindex gdb.Block
5891
5892In @value{GDBN}, symbols are stored in blocks. A block corresponds
5893roughly to a scope in the source code. Blocks are organized
5894hierarchically, and are represented individually in Python as a
5895@code{gdb.Block}. Blocks rely on debugging information being
5896available.
5897
5898A frame has a block. Please see @ref{Frames In Python}, for a more
5899in-depth discussion of frames.
5900
5901The outermost block is known as the @dfn{global block}. The global
5902block typically holds public global variables and functions.
5903
5904The block nested just inside the global block is the @dfn{static
5905block}. The static block typically holds file-scoped variables and
5906functions.
5907
5908@value{GDBN} provides a method to get a block's superblock, but there
5909is currently no way to examine the sub-blocks of a block, or to
5910iterate over all the blocks in a symbol table (@pxref{Symbol Tables In
5911Python}).
5912
5913Here is a short example that should help explain blocks:
5914
5915@smallexample
5916/* This is in the global block. */
5917int global;
5918
5919/* This is in the static block. */
5920static int file_scope;
5921
5922/* 'function' is in the global block, and 'argument' is
5923 in a block nested inside of 'function'. */
5924int function (int argument)
5925@{
5926 /* 'local' is in a block inside 'function'. It may or may
5927 not be in the same block as 'argument'. */
5928 int local;
5929
5930 @{
5931 /* 'inner' is in a block whose superblock is the one holding
5932 'local'. */
5933 int inner;
5934
5935 /* If this call is expanded by the compiler, you may see
5936 a nested block here whose function is 'inline_function'
5937 and whose superblock is the one holding 'inner'. */
5938 inline_function ();
5939 @}
5940@}
5941@end smallexample
5942
5943A @code{gdb.Block} is iterable. The iterator returns the symbols
5944(@pxref{Symbols In Python}) local to the block. Python programs
5945should not assume that a specific block object will always contain a
5946given symbol, since changes in @value{GDBN} features and
5947infrastructure may cause symbols move across blocks in a symbol
0b27c27d
CB
5948table. You can also use Python's @dfn{dictionary syntax} to access
5949variables in this block, e.g.:
5950
5951@smallexample
5952symbol = some_block['variable'] # symbol is of type gdb.Symbol
5953@end smallexample
329baa95
DE
5954
5955The following block-related functions are available in the @code{gdb}
5956module:
5957
329baa95
DE
5958@defun gdb.block_for_pc (pc)
5959Return the innermost @code{gdb.Block} containing the given @var{pc}
5960value. If the block cannot be found for the @var{pc} value specified,
8743a9cd
TT
5961the function will return @code{None}. This is identical to
5962@code{gdb.current_progspace().block_for_pc(pc)} and is included for
5963historical compatibility.
329baa95
DE
5964@end defun
5965
5966A @code{gdb.Block} object has the following methods:
5967
5968@defun Block.is_valid ()
5969Returns @code{True} if the @code{gdb.Block} object is valid,
5970@code{False} if not. A block object can become invalid if the block it
5971refers to doesn't exist anymore in the inferior. All other
5972@code{gdb.Block} methods will throw an exception if it is invalid at
5973the time the method is called. The block's validity is also checked
5974during iteration over symbols of the block.
5975@end defun
5976
5977A @code{gdb.Block} object has the following attributes:
5978
5979@defvar Block.start
5980The start address of the block. This attribute is not writable.
5981@end defvar
5982
5983@defvar Block.end
22eb9e92
TT
5984One past the last address that appears in the block. This attribute
5985is not writable.
329baa95
DE
5986@end defvar
5987
5988@defvar Block.function
5989The name of the block represented as a @code{gdb.Symbol}. If the
5990block is not named, then this attribute holds @code{None}. This
5991attribute is not writable.
5992
5993For ordinary function blocks, the superblock is the static block.
5994However, you should note that it is possible for a function block to
5995have a superblock that is not the static block -- for instance this
5996happens for an inlined function.
5997@end defvar
5998
5999@defvar Block.superblock
6000The block containing this block. If this parent block does not exist,
6001this attribute holds @code{None}. This attribute is not writable.
6002@end defvar
6003
6004@defvar Block.global_block
6005The global block associated with this block. This attribute is not
6006writable.
6007@end defvar
6008
6009@defvar Block.static_block
6010The static block associated with this block. This attribute is not
6011writable.
6012@end defvar
6013
6014@defvar Block.is_global
6015@code{True} if the @code{gdb.Block} object is a global block,
6016@code{False} if not. This attribute is not
6017writable.
6018@end defvar
6019
6020@defvar Block.is_static
6021@code{True} if the @code{gdb.Block} object is a static block,
6022@code{False} if not. This attribute is not writable.
6023@end defvar
6024
6025@node Symbols In Python
849cba3b 6026@subsubsection Python representation of Symbols
329baa95
DE
6027
6028@cindex symbols in python
6029@tindex gdb.Symbol
6030
6031@value{GDBN} represents every variable, function and type as an
6032entry in a symbol table. @xref{Symbols, ,Examining the Symbol Table}.
6033Similarly, Python represents these symbols in @value{GDBN} with the
6034@code{gdb.Symbol} object.
6035
6036The following symbol-related functions are available in the @code{gdb}
6037module:
6038
329baa95
DE
6039@defun gdb.lookup_symbol (name @r{[}, block @r{[}, domain@r{]]})
6040This function searches for a symbol by name. The search scope can be
6041restricted to the parameters defined in the optional domain and block
6042arguments.
6043
6044@var{name} is the name of the symbol. It must be a string. The
6045optional @var{block} argument restricts the search to symbols visible
6046in that @var{block}. The @var{block} argument must be a
6047@code{gdb.Block} object. If omitted, the block for the current frame
6048is used. The optional @var{domain} argument restricts
6049the search to the domain type. The @var{domain} argument must be a
6050domain constant defined in the @code{gdb} module and described later
6051in this chapter.
6052
6053The result is a tuple of two elements.
6054The first element is a @code{gdb.Symbol} object or @code{None} if the symbol
6055is not found.
6056If the symbol is found, the second element is @code{True} if the symbol
6057is a field of a method's object (e.g., @code{this} in C@t{++}),
6058otherwise it is @code{False}.
6059If the symbol is not found, the second element is @code{False}.
6060@end defun
6061
329baa95
DE
6062@defun gdb.lookup_global_symbol (name @r{[}, domain@r{]})
6063This function searches for a global symbol by name.
6064The search scope can be restricted to by the domain argument.
6065
6066@var{name} is the name of the symbol. It must be a string.
6067The optional @var{domain} argument restricts the search to the domain type.
6068The @var{domain} argument must be a domain constant defined in the @code{gdb}
6069module and described later in this chapter.
6070
6071The result is a @code{gdb.Symbol} object or @code{None} if the symbol
6072is not found.
6073@end defun
6074
2906593f
CB
6075@defun gdb.lookup_static_symbol (name @r{[}, domain@r{]})
6076This function searches for a global symbol with static linkage by name.
6077The search scope can be restricted to by the domain argument.
6078
6079@var{name} is the name of the symbol. It must be a string.
6080The optional @var{domain} argument restricts the search to the domain type.
6081The @var{domain} argument must be a domain constant defined in the @code{gdb}
6082module and described later in this chapter.
6083
6084The result is a @code{gdb.Symbol} object or @code{None} if the symbol
6085is not found.
6086
6087Note that this function will not find function-scoped static variables. To look
6088up such variables, iterate over the variables of the function's
6089@code{gdb.Block} and check that @code{block.addr_class} is
6090@code{gdb.SYMBOL_LOC_STATIC}.
09ff83af
AB
6091
6092There can be multiple global symbols with static linkage with the same
6093name. This function will only return the first matching symbol that
6094it finds. Which symbol is found depends on where @value{GDBN} is
6095currently stopped, as @value{GDBN} will first search for matching
6096symbols in the current object file, and then search all other object
6097files. If the application is not yet running then @value{GDBN} will
6098search all object files in the order they appear in the debug
6099information.
2906593f
CB
6100@end defun
6101
086baaf1
AB
6102@defun gdb.lookup_static_symbols (name @r{[}, domain@r{]})
6103Similar to @code{gdb.lookup_static_symbol}, this function searches for
6104global symbols with static linkage by name, and optionally restricted
6105by the domain argument. However, this function returns a list of all
6106matching symbols found, not just the first one.
6107
6108@var{name} is the name of the symbol. It must be a string.
6109The optional @var{domain} argument restricts the search to the domain type.
6110The @var{domain} argument must be a domain constant defined in the @code{gdb}
6111module and described later in this chapter.
6112
6113The result is a list of @code{gdb.Symbol} objects which could be empty
6114if no matching symbols were found.
6115
6116Note that this function will not find function-scoped static variables. To look
6117up such variables, iterate over the variables of the function's
6118@code{gdb.Block} and check that @code{block.addr_class} is
6119@code{gdb.SYMBOL_LOC_STATIC}.
6120@end defun
6121
329baa95
DE
6122A @code{gdb.Symbol} object has the following attributes:
6123
6124@defvar Symbol.type
6125The type of the symbol or @code{None} if no type is recorded.
6126This attribute is represented as a @code{gdb.Type} object.
6127@xref{Types In Python}. This attribute is not writable.
6128@end defvar
6129
6130@defvar Symbol.symtab
6131The symbol table in which the symbol appears. This attribute is
6132represented as a @code{gdb.Symtab} object. @xref{Symbol Tables In
6133Python}. This attribute is not writable.
6134@end defvar
6135
6136@defvar Symbol.line
6137The line number in the source code at which the symbol was defined.
6138This is an integer.
6139@end defvar
6140
6141@defvar Symbol.name
6142The name of the symbol as a string. This attribute is not writable.
6143@end defvar
6144
6145@defvar Symbol.linkage_name
6146The name of the symbol, as used by the linker (i.e., may be mangled).
6147This attribute is not writable.
6148@end defvar
6149
6150@defvar Symbol.print_name
6151The name of the symbol in a form suitable for output. This is either
6152@code{name} or @code{linkage_name}, depending on whether the user
6153asked @value{GDBN} to display demangled or mangled names.
6154@end defvar
6155
6156@defvar Symbol.addr_class
6157The address class of the symbol. This classifies how to find the value
6158of a symbol. Each address class is a constant defined in the
6159@code{gdb} module and described later in this chapter.
6160@end defvar
6161
6162@defvar Symbol.needs_frame
6163This is @code{True} if evaluating this symbol's value requires a frame
6164(@pxref{Frames In Python}) and @code{False} otherwise. Typically,
6165local variables will require a frame, but other symbols will not.
6166@end defvar
6167
6168@defvar Symbol.is_argument
6169@code{True} if the symbol is an argument of a function.
6170@end defvar
6171
6172@defvar Symbol.is_constant
6173@code{True} if the symbol is a constant.
6174@end defvar
6175
6176@defvar Symbol.is_function
6177@code{True} if the symbol is a function or a method.
6178@end defvar
6179
6180@defvar Symbol.is_variable
5006ea55
TT
6181@code{True} if the symbol is a variable, as opposed to something like
6182a function or type. Note that this also returns @code{False} for
6183arguments.
329baa95
DE
6184@end defvar
6185
6186A @code{gdb.Symbol} object has the following methods:
6187
6188@defun Symbol.is_valid ()
6189Returns @code{True} if the @code{gdb.Symbol} object is valid,
6190@code{False} if not. A @code{gdb.Symbol} object can become invalid if
6191the symbol it refers to does not exist in @value{GDBN} any longer.
6192All other @code{gdb.Symbol} methods will throw an exception if it is
6193invalid at the time the method is called.
6194@end defun
6195
6196@defun Symbol.value (@r{[}frame@r{]})
6197Compute the value of the symbol, as a @code{gdb.Value}. For
6198functions, this computes the address of the function, cast to the
6199appropriate type. If the symbol requires a frame in order to compute
6200its value, then @var{frame} must be given. If @var{frame} is not
6201given, or if @var{frame} is invalid, then this method will throw an
6202exception.
6203@end defun
6204
6205The available domain categories in @code{gdb.Symbol} are represented
6206as constants in the @code{gdb} module:
6207
b3ce5e5f
DE
6208@vtable @code
6209@vindex SYMBOL_UNDEF_DOMAIN
329baa95
DE
6210@item gdb.SYMBOL_UNDEF_DOMAIN
6211This is used when a domain has not been discovered or none of the
6212following domains apply. This usually indicates an error either
6213in the symbol information or in @value{GDBN}'s handling of symbols.
b3ce5e5f
DE
6214
6215@vindex SYMBOL_VAR_DOMAIN
329baa95
DE
6216@item gdb.SYMBOL_VAR_DOMAIN
6217This domain contains variables, function names, typedef names and enum
6218type values.
b3ce5e5f
DE
6219
6220@vindex SYMBOL_STRUCT_DOMAIN
329baa95
DE
6221@item gdb.SYMBOL_STRUCT_DOMAIN
6222This domain holds struct, union and enum type names.
b3ce5e5f
DE
6223
6224@vindex SYMBOL_LABEL_DOMAIN
329baa95
DE
6225@item gdb.SYMBOL_LABEL_DOMAIN
6226This domain contains names of labels (for gotos).
b3ce5e5f 6227
51e78fc5
TT
6228@vindex SYMBOL_MODULE_DOMAIN
6229@item gdb.SYMBOL_MODULE_DOMAIN
6230This domain contains names of Fortran module types.
6231
6232@vindex SYMBOL_COMMON_BLOCK_DOMAIN
6233@item gdb.SYMBOL_COMMON_BLOCK_DOMAIN
6234This domain contains names of Fortran common blocks.
b3ce5e5f 6235@end vtable
329baa95
DE
6236
6237The available address class categories in @code{gdb.Symbol} are represented
6238as constants in the @code{gdb} module:
6239
b3ce5e5f
DE
6240@vtable @code
6241@vindex SYMBOL_LOC_UNDEF
329baa95
DE
6242@item gdb.SYMBOL_LOC_UNDEF
6243If this is returned by address class, it indicates an error either in
6244the symbol information or in @value{GDBN}'s handling of symbols.
b3ce5e5f
DE
6245
6246@vindex SYMBOL_LOC_CONST
329baa95
DE
6247@item gdb.SYMBOL_LOC_CONST
6248Value is constant int.
b3ce5e5f
DE
6249
6250@vindex SYMBOL_LOC_STATIC
329baa95
DE
6251@item gdb.SYMBOL_LOC_STATIC
6252Value is at a fixed address.
b3ce5e5f
DE
6253
6254@vindex SYMBOL_LOC_REGISTER
329baa95
DE
6255@item gdb.SYMBOL_LOC_REGISTER
6256Value is in a register.
b3ce5e5f
DE
6257
6258@vindex SYMBOL_LOC_ARG
329baa95
DE
6259@item gdb.SYMBOL_LOC_ARG
6260Value is an argument. This value is at the offset stored within the
6261symbol inside the frame's argument list.
b3ce5e5f
DE
6262
6263@vindex SYMBOL_LOC_REF_ARG
329baa95
DE
6264@item gdb.SYMBOL_LOC_REF_ARG
6265Value address is stored in the frame's argument list. Just like
6266@code{LOC_ARG} except that the value's address is stored at the
6267offset, not the value itself.
b3ce5e5f
DE
6268
6269@vindex SYMBOL_LOC_REGPARM_ADDR
329baa95
DE
6270@item gdb.SYMBOL_LOC_REGPARM_ADDR
6271Value is a specified register. Just like @code{LOC_REGISTER} except
6272the register holds the address of the argument instead of the argument
6273itself.
b3ce5e5f
DE
6274
6275@vindex SYMBOL_LOC_LOCAL
329baa95
DE
6276@item gdb.SYMBOL_LOC_LOCAL
6277Value is a local variable.
b3ce5e5f
DE
6278
6279@vindex SYMBOL_LOC_TYPEDEF
329baa95
DE
6280@item gdb.SYMBOL_LOC_TYPEDEF
6281Value not used. Symbols in the domain @code{SYMBOL_STRUCT_DOMAIN} all
6282have this class.
b3ce5e5f 6283
868027a4
HD
6284@vindex SYMBOL_LOC_LABEL
6285@item gdb.SYMBOL_LOC_LABEL
6286Value is a label.
6287
b3ce5e5f 6288@vindex SYMBOL_LOC_BLOCK
329baa95
DE
6289@item gdb.SYMBOL_LOC_BLOCK
6290Value is a block.
b3ce5e5f
DE
6291
6292@vindex SYMBOL_LOC_CONST_BYTES
329baa95
DE
6293@item gdb.SYMBOL_LOC_CONST_BYTES
6294Value is a byte-sequence.
b3ce5e5f
DE
6295
6296@vindex SYMBOL_LOC_UNRESOLVED
329baa95
DE
6297@item gdb.SYMBOL_LOC_UNRESOLVED
6298Value is at a fixed address, but the address of the variable has to be
6299determined from the minimal symbol table whenever the variable is
6300referenced.
b3ce5e5f
DE
6301
6302@vindex SYMBOL_LOC_OPTIMIZED_OUT
329baa95
DE
6303@item gdb.SYMBOL_LOC_OPTIMIZED_OUT
6304The value does not actually exist in the program.
b3ce5e5f
DE
6305
6306@vindex SYMBOL_LOC_COMPUTED
329baa95
DE
6307@item gdb.SYMBOL_LOC_COMPUTED
6308The value's address is a computed location.
51e78fc5 6309
2c5731b6
HD
6310@vindex SYMBOL_LOC_COMMON_BLOCK
6311@item gdb.SYMBOL_LOC_COMMON_BLOCK
51e78fc5
TT
6312The value's address is a symbol. This is only used for Fortran common
6313blocks.
b3ce5e5f 6314@end vtable
329baa95
DE
6315
6316@node Symbol Tables In Python
849cba3b 6317@subsubsection Symbol table representation in Python
329baa95
DE
6318
6319@cindex symbol tables in python
6320@tindex gdb.Symtab
6321@tindex gdb.Symtab_and_line
6322
6323Access to symbol table data maintained by @value{GDBN} on the inferior
6324is exposed to Python via two objects: @code{gdb.Symtab_and_line} and
6325@code{gdb.Symtab}. Symbol table and line data for a frame is returned
6326from the @code{find_sal} method in @code{gdb.Frame} object.
6327@xref{Frames In Python}.
6328
6329For more information on @value{GDBN}'s symbol table management, see
6330@ref{Symbols, ,Examining the Symbol Table}, for more information.
6331
6332A @code{gdb.Symtab_and_line} object has the following attributes:
6333
6334@defvar Symtab_and_line.symtab
6335The symbol table object (@code{gdb.Symtab}) for this frame.
6336This attribute is not writable.
6337@end defvar
6338
6339@defvar Symtab_and_line.pc
6340Indicates the start of the address range occupied by code for the
6341current source line. This attribute is not writable.
6342@end defvar
6343
6344@defvar Symtab_and_line.last
6345Indicates the end of the address range occupied by code for the current
6346source line. This attribute is not writable.
6347@end defvar
6348
6349@defvar Symtab_and_line.line
6350Indicates the current line number for this object. This
6351attribute is not writable.
6352@end defvar
6353
6354A @code{gdb.Symtab_and_line} object has the following methods:
6355
6356@defun Symtab_and_line.is_valid ()
6357Returns @code{True} if the @code{gdb.Symtab_and_line} object is valid,
6358@code{False} if not. A @code{gdb.Symtab_and_line} object can become
6359invalid if the Symbol table and line object it refers to does not
6360exist in @value{GDBN} any longer. All other
6361@code{gdb.Symtab_and_line} methods will throw an exception if it is
6362invalid at the time the method is called.
6363@end defun
6364
6365A @code{gdb.Symtab} object has the following attributes:
6366
6367@defvar Symtab.filename
6368The symbol table's source filename. This attribute is not writable.
6369@end defvar
6370
6371@defvar Symtab.objfile
6372The symbol table's backing object file. @xref{Objfiles In Python}.
6373This attribute is not writable.
6374@end defvar
6375
2b4fd423
DE
6376@defvar Symtab.producer
6377The name and possibly version number of the program that
6378compiled the code in the symbol table.
6379The contents of this string is up to the compiler.
6380If no producer information is available then @code{None} is returned.
6381This attribute is not writable.
6382@end defvar
6383
329baa95
DE
6384A @code{gdb.Symtab} object has the following methods:
6385
6386@defun Symtab.is_valid ()
6387Returns @code{True} if the @code{gdb.Symtab} object is valid,
6388@code{False} if not. A @code{gdb.Symtab} object can become invalid if
6389the symbol table it refers to does not exist in @value{GDBN} any
6390longer. All other @code{gdb.Symtab} methods will throw an exception
6391if it is invalid at the time the method is called.
6392@end defun
6393
6394@defun Symtab.fullname ()
6395Return the symbol table's source absolute file name.
6396@end defun
6397
6398@defun Symtab.global_block ()
6399Return the global block of the underlying symbol table.
6400@xref{Blocks In Python}.
6401@end defun
6402
6403@defun Symtab.static_block ()
6404Return the static block of the underlying symbol table.
6405@xref{Blocks In Python}.
6406@end defun
6407
6408@defun Symtab.linetable ()
6409Return the line table associated with the symbol table.
6410@xref{Line Tables In Python}.
6411@end defun
6412
6413@node Line Tables In Python
6414@subsubsection Manipulating line tables using Python
6415
6416@cindex line tables in python
6417@tindex gdb.LineTable
6418
6419Python code can request and inspect line table information from a
6420symbol table that is loaded in @value{GDBN}. A line table is a
6421mapping of source lines to their executable locations in memory. To
6422acquire the line table information for a particular symbol table, use
6423the @code{linetable} function (@pxref{Symbol Tables In Python}).
6424
6425A @code{gdb.LineTable} is iterable. The iterator returns
6426@code{LineTableEntry} objects that correspond to the source line and
6427address for each line table entry. @code{LineTableEntry} objects have
6428the following attributes:
6429
6430@defvar LineTableEntry.line
6431The source line number for this line table entry. This number
6432corresponds to the actual line of source. This attribute is not
6433writable.
6434@end defvar
6435
6436@defvar LineTableEntry.pc
6437The address that is associated with the line table entry where the
6438executable code for that source line resides in memory. This
6439attribute is not writable.
6440@end defvar
6441
6442As there can be multiple addresses for a single source line, you may
6443receive multiple @code{LineTableEntry} objects with matching
6444@code{line} attributes, but with different @code{pc} attributes. The
6445iterator is sorted in ascending @code{pc} order. Here is a small
6446example illustrating iterating over a line table.
6447
6448@smallexample
6449symtab = gdb.selected_frame().find_sal().symtab
6450linetable = symtab.linetable()
6451for line in linetable:
f3bdc2db 6452 print ("Line: "+str(line.line)+" Address: "+hex(line.pc))
329baa95
DE
6453@end smallexample
6454
6455This will have the following output:
6456
6457@smallexample
6458Line: 33 Address: 0x4005c8L
6459Line: 37 Address: 0x4005caL
6460Line: 39 Address: 0x4005d2L
6461Line: 40 Address: 0x4005f8L
6462Line: 42 Address: 0x4005ffL
6463Line: 44 Address: 0x400608L
6464Line: 42 Address: 0x40060cL
6465Line: 45 Address: 0x400615L
6466@end smallexample
6467
6468In addition to being able to iterate over a @code{LineTable}, it also
6469has the following direct access methods:
6470
6471@defun LineTable.line (line)
6472Return a Python @code{Tuple} of @code{LineTableEntry} objects for any
697aa1b7
EZ
6473entries in the line table for the given @var{line}, which specifies
6474the source code line. If there are no entries for that source code
329baa95
DE
6475@var{line}, the Python @code{None} is returned.
6476@end defun
6477
6478@defun LineTable.has_line (line)
6479Return a Python @code{Boolean} indicating whether there is an entry in
6480the line table for this source line. Return @code{True} if an entry
6481is found, or @code{False} if not.
6482@end defun
6483
6484@defun LineTable.source_lines ()
6485Return a Python @code{List} of the source line numbers in the symbol
6486table. Only lines with executable code locations are returned. The
6487contents of the @code{List} will just be the source line entries
6488represented as Python @code{Long} values.
6489@end defun
6490
6491@node Breakpoints In Python
6492@subsubsection Manipulating breakpoints using Python
6493
6494@cindex breakpoints in python
6495@tindex gdb.Breakpoint
6496
6497Python code can manipulate breakpoints via the @code{gdb.Breakpoint}
6498class.
6499
0b982d68
SM
6500A breakpoint can be created using one of the two forms of the
6501@code{gdb.Breakpoint} constructor. The first one accepts a string
6502like one would pass to the @code{break}
6503(@pxref{Set Breaks,,Setting Breakpoints}) and @code{watch}
6504(@pxref{Set Watchpoints, , Setting Watchpoints}) commands, and can be used to
6505create both breakpoints and watchpoints. The second accepts separate Python
6506arguments similar to @ref{Explicit Locations}, and can only be used to create
6507breakpoints.
6508
b89641ba 6509@defun Breakpoint.__init__ (spec @r{[}, type @r{][}, wp_class @r{][}, internal @r{][}, temporary @r{][}, qualified @r{]})
0b982d68
SM
6510Create a new breakpoint according to @var{spec}, which is a string naming the
6511location of a breakpoint, or an expression that defines a watchpoint. The
6512string should describe a location in a format recognized by the @code{break}
6513command (@pxref{Set Breaks,,Setting Breakpoints}) or, in the case of a
6514watchpoint, by the @code{watch} command
6515(@pxref{Set Watchpoints, , Setting Watchpoints}).
6516
6517The optional @var{type} argument specifies the type of the breakpoint to create,
6518as defined below.
6519
6520The optional @var{wp_class} argument defines the class of watchpoint to create,
6521if @var{type} is @code{gdb.BP_WATCHPOINT}. If @var{wp_class} is omitted, it
6522defaults to @code{gdb.WP_WRITE}.
6523
6524The optional @var{internal} argument allows the breakpoint to become invisible
6525to the user. The breakpoint will neither be reported when created, nor will it
6526be listed in the output from @code{info breakpoints} (but will be listed with
6527the @code{maint info breakpoints} command).
6528
6529The optional @var{temporary} argument makes the breakpoint a temporary
6530breakpoint. Temporary breakpoints are deleted after they have been hit. Any
6531further access to the Python breakpoint after it has been hit will result in a
6532runtime error (as that breakpoint has now been automatically deleted).
b89641ba
SM
6533
6534The optional @var{qualified} argument is a boolean that allows interpreting
6535the function passed in @code{spec} as a fully-qualified name. It is equivalent
6536to @code{break}'s @code{-qualified} flag (@pxref{Linespec Locations} and
6537@ref{Explicit Locations}).
6538
0b982d68
SM
6539@end defun
6540
b89641ba 6541@defun Breakpoint.__init__ (@r{[} source @r{][}, function @r{][}, label @r{][}, line @r{]}, @r{][} internal @r{][}, temporary @r{][}, qualified @r{]})
0b982d68
SM
6542This second form of creating a new breakpoint specifies the explicit
6543location (@pxref{Explicit Locations}) using keywords. The new breakpoint will
6544be created in the specified source file @var{source}, at the specified
6545@var{function}, @var{label} and @var{line}.
6546
b89641ba
SM
6547@var{internal}, @var{temporary} and @var{qualified} have the same usage as
6548explained previously.
329baa95
DE
6549@end defun
6550
cda75e70
TT
6551The available types are represented by constants defined in the @code{gdb}
6552module:
6553
6554@vtable @code
6555@vindex BP_BREAKPOINT
6556@item gdb.BP_BREAKPOINT
6557Normal code breakpoint.
6558
325d39e4
HD
6559@vindex BP_HARDWARE_BREAKPOINT
6560@item gdb.BP_HARDWARE_BREAKPOINT
6561Hardware assisted code breakpoint.
6562
cda75e70
TT
6563@vindex BP_WATCHPOINT
6564@item gdb.BP_WATCHPOINT
6565Watchpoint breakpoint.
6566
6567@vindex BP_HARDWARE_WATCHPOINT
6568@item gdb.BP_HARDWARE_WATCHPOINT
6569Hardware assisted watchpoint.
6570
6571@vindex BP_READ_WATCHPOINT
6572@item gdb.BP_READ_WATCHPOINT
6573Hardware assisted read watchpoint.
6574
6575@vindex BP_ACCESS_WATCHPOINT
6576@item gdb.BP_ACCESS_WATCHPOINT
6577Hardware assisted access watchpoint.
6b95f5ad
AB
6578
6579@vindex BP_CATCHPOINT
6580@item gdb.BP_CATCHPOINT
6581Catchpoint. Currently, this type can't be used when creating
6582@code{gdb.Breakpoint} objects, but will be present in
6583@code{gdb.Breakpoint} objects reported from
6584@code{gdb.BreakpointEvent}s (@pxref{Events In Python}).
cda75e70
TT
6585@end vtable
6586
802021d4 6587The available watchpoint types are represented by constants defined in the
cda75e70
TT
6588@code{gdb} module:
6589
6590@vtable @code
6591@vindex WP_READ
6592@item gdb.WP_READ
6593Read only watchpoint.
6594
6595@vindex WP_WRITE
6596@item gdb.WP_WRITE
6597Write only watchpoint.
6598
6599@vindex WP_ACCESS
6600@item gdb.WP_ACCESS
6601Read/Write watchpoint.
6602@end vtable
6603
329baa95
DE
6604@defun Breakpoint.stop (self)
6605The @code{gdb.Breakpoint} class can be sub-classed and, in
6606particular, you may choose to implement the @code{stop} method.
6607If this method is defined in a sub-class of @code{gdb.Breakpoint},
6608it will be called when the inferior reaches any location of a
6609breakpoint which instantiates that sub-class. If the method returns
6610@code{True}, the inferior will be stopped at the location of the
6611breakpoint, otherwise the inferior will continue.
6612
6613If there are multiple breakpoints at the same location with a
6614@code{stop} method, each one will be called regardless of the
6615return status of the previous. This ensures that all @code{stop}
6616methods have a chance to execute at that location. In this scenario
6617if one of the methods returns @code{True} but the others return
6618@code{False}, the inferior will still be stopped.
6619
6620You should not alter the execution state of the inferior (i.e.@:, step,
6621next, etc.), alter the current frame context (i.e.@:, change the current
6622active frame), or alter, add or delete any breakpoint. As a general
6623rule, you should not alter any data within @value{GDBN} or the inferior
6624at this time.
6625
6626Example @code{stop} implementation:
6627
6628@smallexample
6629class MyBreakpoint (gdb.Breakpoint):
6630 def stop (self):
6631 inf_val = gdb.parse_and_eval("foo")
6632 if inf_val == 3:
6633 return True
6634 return False
6635@end smallexample
6636@end defun
6637
329baa95
DE
6638@defun Breakpoint.is_valid ()
6639Return @code{True} if this @code{Breakpoint} object is valid,
6640@code{False} otherwise. A @code{Breakpoint} object can become invalid
6641if the user deletes the breakpoint. In this case, the object still
6642exists, but the underlying breakpoint does not. In the cases of
6643watchpoint scope, the watchpoint remains valid even if execution of the
6644inferior leaves the scope of that watchpoint.
6645@end defun
6646
fab3a15d 6647@defun Breakpoint.delete ()
329baa95
DE
6648Permanently deletes the @value{GDBN} breakpoint. This also
6649invalidates the Python @code{Breakpoint} object. Any further access
6650to this object's attributes or methods will raise an error.
6651@end defun
6652
6653@defvar Breakpoint.enabled
6654This attribute is @code{True} if the breakpoint is enabled, and
fab3a15d
SM
6655@code{False} otherwise. This attribute is writable. You can use it to enable
6656or disable the breakpoint.
329baa95
DE
6657@end defvar
6658
6659@defvar Breakpoint.silent
6660This attribute is @code{True} if the breakpoint is silent, and
6661@code{False} otherwise. This attribute is writable.
6662
6663Note that a breakpoint can also be silent if it has commands and the
6664first command is @code{silent}. This is not reported by the
6665@code{silent} attribute.
6666@end defvar
6667
93daf339
TT
6668@defvar Breakpoint.pending
6669This attribute is @code{True} if the breakpoint is pending, and
6670@code{False} otherwise. @xref{Set Breaks}. This attribute is
6671read-only.
6672@end defvar
6673
22a02324 6674@anchor{python_breakpoint_thread}
329baa95 6675@defvar Breakpoint.thread
b080fe54
AB
6676If the breakpoint is thread-specific (@pxref{Thread-Specific
6677Breakpoints}), this attribute holds the thread's global id. If the
6678breakpoint is not thread-specific, this attribute is @code{None}.
6679This attribute is writable.
6680
6681Only one of @code{Breakpoint.thread} or @code{Breakpoint.inferior} can
6682be set to a valid id at any time, that is, a breakpoint can be thread
6683specific, or inferior specific, but not both.
6684@end defvar
6685
6686@anchor{python_breakpoint_inferior}
6687@defvar Breakpoint.inferior
6688If the breakpoint is inferior-specific (@pxref{Inferior-Specific
6689Breakpoints}), this attribute holds the inferior's id. If the
6690breakpoint is not inferior-specific, this attribute is @code{None}.
6691
6692This attribute can be written for breakpoints of type
6693@code{gdb.BP_BREAKPOINT} and @code{gdb.BP_HARDWARE_BREAKPOINT}.
329baa95
DE
6694@end defvar
6695
6696@defvar Breakpoint.task
6697If the breakpoint is Ada task-specific, this attribute holds the Ada task
6698id. If the breakpoint is not task-specific (or the underlying
6699language is not Ada), this attribute is @code{None}. This attribute
6700is writable.
6701@end defvar
6702
6703@defvar Breakpoint.ignore_count
6704This attribute holds the ignore count for the breakpoint, an integer.
6705This attribute is writable.
6706@end defvar
6707
6708@defvar Breakpoint.number
6709This attribute holds the breakpoint's number --- the identifier used by
6710the user to manipulate the breakpoint. This attribute is not writable.
6711@end defvar
6712
6713@defvar Breakpoint.type
6714This attribute holds the breakpoint's type --- the identifier used to
6715determine the actual breakpoint type or use-case. This attribute is not
6716writable.
6717@end defvar
6718
6719@defvar Breakpoint.visible
6720This attribute tells whether the breakpoint is visible to the user
6721when set, or when the @samp{info breakpoints} command is run. This
6722attribute is not writable.
6723@end defvar
6724
6725@defvar Breakpoint.temporary
6726This attribute indicates whether the breakpoint was created as a
6727temporary breakpoint. Temporary breakpoints are automatically deleted
6728after that breakpoint has been hit. Access to this attribute, and all
6729other attributes and functions other than the @code{is_valid}
6730function, will result in an error after the breakpoint has been hit
6731(as it has been automatically deleted). This attribute is not
6732writable.
6733@end defvar
6734
329baa95
DE
6735@defvar Breakpoint.hit_count
6736This attribute holds the hit count for the breakpoint, an integer.
6737This attribute is writable, but currently it can only be set to zero.
6738@end defvar
6739
6740@defvar Breakpoint.location
6741This attribute holds the location of the breakpoint, as specified by
6742the user. It is a string. If the breakpoint does not have a location
6743(that is, it is a watchpoint) the attribute's value is @code{None}. This
6744attribute is not writable.
6745@end defvar
6746
e5213e2c
SF
6747@defvar Breakpoint.locations
6748Get the most current list of breakpoint locations that are inserted for this
6749breakpoint, with elements of type @code{gdb.BreakpointLocation}
6750(described below). This functionality matches that of the
6751@code{info breakpoint} command (@pxref{Set Breaks}), in that it only retrieves
6752the most current list of locations, thus the list itself when returned is
6753not updated behind the scenes. This attribute is not writable.
6754@end defvar
6755
329baa95
DE
6756@defvar Breakpoint.expression
6757This attribute holds a breakpoint expression, as specified by
6758the user. It is a string. If the breakpoint does not have an
6759expression (the breakpoint is not a watchpoint) the attribute's value
6760is @code{None}. This attribute is not writable.
6761@end defvar
6762
6763@defvar Breakpoint.condition
6764This attribute holds the condition of the breakpoint, as specified by
6765the user. It is a string. If there is no condition, this attribute's
6766value is @code{None}. This attribute is writable.
6767@end defvar
6768
6769@defvar Breakpoint.commands
6770This attribute holds the commands attached to the breakpoint. If
6771there are commands, this attribute's value is a string holding all the
6772commands, separated by newlines. If there are no commands, this
a913fffb 6773attribute is @code{None}. This attribute is writable.
329baa95
DE
6774@end defvar
6775
e5213e2c
SF
6776@subheading Breakpoint Locations
6777
6778A breakpoint location is one of the actual places where a breakpoint has been
6779set, represented in the Python API by the @code{gdb.BreakpointLocation}
6780type. This type is never instantiated by the user directly, but is retrieved
6781from @code{Breakpoint.locations} which returns a list of breakpoint
6782locations where it is currently set. Breakpoint locations can become
6783invalid if new symbol files are loaded or dynamically loaded libraries are
6784closed. Accessing the attributes of an invalidated breakpoint location will
6785throw a @code{RuntimeError} exception. Access the @code{Breakpoint.locations}
6786attribute again to retrieve the new and valid breakpoints location list.
6787
6788@defvar BreakpointLocation.source
6789This attribute returns the source file path and line number where this location
6790was set. The type of the attribute is a tuple of @var{string} and
6791@var{long}. If the breakpoint location doesn't have a source location,
6792it returns None, which is the case for watchpoints and catchpoints.
6793This will throw a @code{RuntimeError} exception if the location
6794has been invalidated. This attribute is not writable.
6795@end defvar
6796
6797@defvar BreakpointLocation.address
6798This attribute returns the address where this location was set.
6799This attribute is of type long. This will throw a @code{RuntimeError}
6800exception if the location has been invalidated. This attribute is
6801not writable.
6802@end defvar
6803
6804@defvar BreakpointLocation.enabled
6805This attribute holds the value for whether or not this location is enabled.
6806This attribute is writable (boolean). This will throw a @code{RuntimeError}
6807exception if the location has been invalidated.
6808@end defvar
6809
6810@defvar BreakpointLocation.owner
6811This attribute holds a reference to the @code{gdb.Breakpoint} owner object,
6812from which this @code{gdb.BreakpointLocation} was retrieved from.
6813This will throw a @code{RuntimeError} exception if the location has been
6814invalidated. This attribute is not writable.
6815@end defvar
6816
6817@defvar BreakpointLocation.function
6818This attribute gets the name of the function where this location was set.
6819If no function could be found this attribute returns @code{None}.
6820This will throw a @code{RuntimeError} exception if the location has
6821been invalidated. This attribute is not writable.
6822@end defvar
6823
6824@defvar BreakpointLocation.fullname
6825This attribute gets the full name of where this location was set. If no
6826full name could be found, this attribute returns @code{None}.
6827This will throw a @code{RuntimeError} exception if the location has
6828been invalidated. This attribute is not writable.
6829@end defvar
6830
6831@defvar BreakpointLocation.thread_groups
6832This attribute gets the thread groups it was set in. It returns a @code{List}
6833of the thread group ID's. This will throw a @code{RuntimeError}
6834exception if the location has been invalidated. This attribute
6835is not writable.
6836@end defvar
6837
329baa95
DE
6838@node Finish Breakpoints in Python
6839@subsubsection Finish Breakpoints
6840
6841@cindex python finish breakpoints
6842@tindex gdb.FinishBreakpoint
6843
6844A finish breakpoint is a temporary breakpoint set at the return address of
6845a frame, based on the @code{finish} command. @code{gdb.FinishBreakpoint}
6846extends @code{gdb.Breakpoint}. The underlying breakpoint will be disabled
6847and deleted when the execution will run out of the breakpoint scope (i.e.@:
6848@code{Breakpoint.stop} or @code{FinishBreakpoint.out_of_scope} triggered).
6849Finish breakpoints are thread specific and must be create with the right
6850thread selected.
6851
6852@defun FinishBreakpoint.__init__ (@r{[}frame@r{]} @r{[}, internal@r{]})
6853Create a finish breakpoint at the return address of the @code{gdb.Frame}
6854object @var{frame}. If @var{frame} is not provided, this defaults to the
6855newest frame. The optional @var{internal} argument allows the breakpoint to
6856become invisible to the user. @xref{Breakpoints In Python}, for further
6857details about this argument.
6858@end defun
6859
6860@defun FinishBreakpoint.out_of_scope (self)
6861In some circumstances (e.g.@: @code{longjmp}, C@t{++} exceptions, @value{GDBN}
6862@code{return} command, @dots{}), a function may not properly terminate, and
6863thus never hit the finish breakpoint. When @value{GDBN} notices such a
6864situation, the @code{out_of_scope} callback will be triggered.
6865
6866You may want to sub-class @code{gdb.FinishBreakpoint} and override this
6867method:
6868
6869@smallexample
6870class MyFinishBreakpoint (gdb.FinishBreakpoint)
6871 def stop (self):
f3bdc2db 6872 print ("normal finish")
329baa95
DE
6873 return True
6874
6875 def out_of_scope ():
f3bdc2db 6876 print ("abnormal finish")
329baa95
DE
6877@end smallexample
6878@end defun
6879
6880@defvar FinishBreakpoint.return_value
6881When @value{GDBN} is stopped at a finish breakpoint and the frame
6882used to build the @code{gdb.FinishBreakpoint} object had debug symbols, this
6883attribute will contain a @code{gdb.Value} object corresponding to the return
6884value of the function. The value will be @code{None} if the function return
6885type is @code{void} or if the return value was not computable. This attribute
6886is not writable.
6887@end defvar
6888
6889@node Lazy Strings In Python
849cba3b 6890@subsubsection Python representation of lazy strings
329baa95
DE
6891
6892@cindex lazy strings in python
6893@tindex gdb.LazyString
6894
6895A @dfn{lazy string} is a string whose contents is not retrieved or
6896encoded until it is needed.
6897
6898A @code{gdb.LazyString} is represented in @value{GDBN} as an
6899@code{address} that points to a region of memory, an @code{encoding}
6900that will be used to encode that region of memory, and a @code{length}
6901to delimit the region of memory that represents the string. The
6902difference between a @code{gdb.LazyString} and a string wrapped within
6903a @code{gdb.Value} is that a @code{gdb.LazyString} will be treated
6904differently by @value{GDBN} when printing. A @code{gdb.LazyString} is
6905retrieved and encoded during printing, while a @code{gdb.Value}
6906wrapping a string is immediately retrieved and encoded on creation.
6907
6908A @code{gdb.LazyString} object has the following functions:
6909
6910@defun LazyString.value ()
6911Convert the @code{gdb.LazyString} to a @code{gdb.Value}. This value
6912will point to the string in memory, but will lose all the delayed
6913retrieval, encoding and handling that @value{GDBN} applies to a
6914@code{gdb.LazyString}.
6915@end defun
6916
6917@defvar LazyString.address
6918This attribute holds the address of the string. This attribute is not
6919writable.
6920@end defvar
6921
6922@defvar LazyString.length
6923This attribute holds the length of the string in characters. If the
6924length is -1, then the string will be fetched and encoded up to the
6925first null of appropriate width. This attribute is not writable.
6926@end defvar
6927
6928@defvar LazyString.encoding
6929This attribute holds the encoding that will be applied to the string
6930when the string is printed by @value{GDBN}. If the encoding is not
6931set, or contains an empty string, then @value{GDBN} will select the
6932most appropriate encoding when the string is printed. This attribute
6933is not writable.
6934@end defvar
6935
6936@defvar LazyString.type
6937This attribute holds the type that is represented by the lazy string's
f8d99587 6938type. For a lazy string this is a pointer or array type. To
329baa95
DE
6939resolve this to the lazy string's character type, use the type's
6940@code{target} method. @xref{Types In Python}. This attribute is not
6941writable.
6942@end defvar
6943
6944@node Architectures In Python
6945@subsubsection Python representation of architectures
6946@cindex Python architectures
6947
6948@value{GDBN} uses architecture specific parameters and artifacts in a
6949number of its various computations. An architecture is represented
6950by an instance of the @code{gdb.Architecture} class.
6951
6952A @code{gdb.Architecture} class has the following methods:
6953
8b87fbe6 6954@anchor{gdbpy_architecture_name}
329baa95
DE
6955@defun Architecture.name ()
6956Return the name (string value) of the architecture.
6957@end defun
6958
ebb83b77 6959@defun Architecture.disassemble (start_pc @r{[}, end_pc @r{[}, count@r{]]})
329baa95
DE
6960Return a list of disassembled instructions starting from the memory
6961address @var{start_pc}. The optional arguments @var{end_pc} and
6962@var{count} determine the number of instructions in the returned list.
6963If both the optional arguments @var{end_pc} and @var{count} are
6964specified, then a list of at most @var{count} disassembled instructions
6965whose start address falls in the closed memory address interval from
6966@var{start_pc} to @var{end_pc} are returned. If @var{end_pc} is not
6967specified, but @var{count} is specified, then @var{count} number of
6968instructions starting from the address @var{start_pc} are returned. If
6969@var{count} is not specified but @var{end_pc} is specified, then all
6970instructions whose start address falls in the closed memory address
6971interval from @var{start_pc} to @var{end_pc} are returned. If neither
6972@var{end_pc} nor @var{count} are specified, then a single instruction at
6973@var{start_pc} is returned. For all of these cases, each element of the
6974returned list is a Python @code{dict} with the following string keys:
6975
6976@table @code
6977
6978@item addr
6979The value corresponding to this key is a Python long integer capturing
6980the memory address of the instruction.
6981
6982@item asm
6983The value corresponding to this key is a string value which represents
6984the instruction with assembly language mnemonics. The assembly
6985language flavor used is the same as that specified by the current CLI
6986variable @code{disassembly-flavor}. @xref{Machine Code}.
6987
6988@item length
6989The value corresponding to this key is the length (integer value) of the
6990instruction in bytes.
6991
6992@end table
6993@end defun
6994
d3771fe2
TT
6995@defun Architecture.integer_type (size @r{[}, signed@r{]})
6996This function looks up an integer type by its @var{size}, and
6997optionally whether or not it is signed.
6998
6999@var{size} is the size, in bits, of the desired integer type. Only
7000certain sizes are currently supported: 0, 8, 16, 24, 32, 64, and 128.
7001
7002If @var{signed} is not specified, it defaults to @code{True}. If
7003@var{signed} is @code{False}, the returned type will be unsigned.
7004
7005If the indicated type cannot be found, this function will throw a
7006@code{ValueError} exception.
7007@end defun
7008
0f767f94 7009@anchor{gdbpy_architecture_registers}
ebb83b77 7010@defun Architecture.registers (@r{[} reggroup @r{]})
0f767f94
AB
7011Return a @code{gdb.RegisterDescriptorIterator} (@pxref{Registers In
7012Python}) for all of the registers in @var{reggroup}, a string that is
7013the name of a register group. If @var{reggroup} is omitted, or is the
7014empty string, then the register group @samp{all} is assumed.
7015@end defun
7016
64cb3757
AB
7017@anchor{gdbpy_architecture_reggroups}
7018@defun Architecture.register_groups ()
7019Return a @code{gdb.RegisterGroupsIterator} (@pxref{Registers In
7020Python}) for all of the register groups available for the
7021@code{gdb.Architecture}.
7022@end defun
7023
0f767f94
AB
7024@node Registers In Python
7025@subsubsection Registers In Python
7026@cindex Registers In Python
7027
7028Python code can request from a @code{gdb.Architecture} information
7029about the set of registers available
7030(@pxref{gdbpy_architecture_registers,,@code{Architecture.registers}}).
7031The register information is returned as a
7032@code{gdb.RegisterDescriptorIterator}, which is an iterator that in
7033turn returns @code{gdb.RegisterDescriptor} objects.
7034
7035A @code{gdb.RegisterDescriptor} does not provide the value of a
7036register (@pxref{gdbpy_frame_read_register,,@code{Frame.read_register}}
7037for reading a register's value), instead the @code{RegisterDescriptor}
7038is a way to discover which registers are available for a particular
7039architecture.
7040
7041A @code{gdb.RegisterDescriptor} has the following read-only properties:
7042
7043@defvar RegisterDescriptor.name
7044The name of this register.
7045@end defvar
7046
14fa8fb3
AB
7047It is also possible to lookup a register descriptor based on its name
7048using the following @code{gdb.RegisterDescriptorIterator} function:
7049
ebb83b77 7050@defun RegisterDescriptorIterator.find (name)
14fa8fb3
AB
7051Takes @var{name} as an argument, which must be a string, and returns a
7052@code{gdb.RegisterDescriptor} for the register with that name, or
7053@code{None} if there is no register with that name.
7054@end defun
7055
64cb3757
AB
7056Python code can also request from a @code{gdb.Architecture}
7057information about the set of register groups available on a given
7058architecture
7059(@pxref{gdbpy_architecture_reggroups,,@code{Architecture.register_groups}}).
7060
7061Every register can be a member of zero or more register groups. Some
7062register groups are used internally within @value{GDBN} to control
7063things like which registers must be saved when calling into the
7064program being debugged (@pxref{Calling,,Calling Program Functions}).
7065Other register groups exist to allow users to easily see related sets
7066of registers in commands like @code{info registers}
7067(@pxref{info_registers_reggroup,,@code{info registers
7068@var{reggroup}}}).
7069
7070The register groups information is returned as a
7071@code{gdb.RegisterGroupsIterator}, which is an iterator that in turn
7072returns @code{gdb.RegisterGroup} objects.
7073
7074A @code{gdb.RegisterGroup} object has the following read-only
7075properties:
7076
7077@defvar RegisterGroup.name
7078A string that is the name of this register group.
7079@end defvar
7080
0e3b7c25
AB
7081@node Connections In Python
7082@subsubsection Connections In Python
7083@cindex connections in python
7084@value{GDBN} lets you run and debug multiple programs in a single
7085session. Each program being debugged has a connection, the connection
7086describes how @value{GDBN} controls the program being debugged.
7087Examples of different connection types are @samp{native} and
7088@samp{remote}. @xref{Inferiors Connections and Programs}.
7089
24b2de7b
AB
7090Connections in @value{GDBN} are represented as instances of
7091@code{gdb.TargetConnection}, or as one of its sub-classes. To get a
7092list of all connections use @code{gdb.connections}
0e3b7c25
AB
7093(@pxref{gdbpy_connections,,gdb.connections}).
7094
7095To get the connection for a single @code{gdb.Inferior} read its
7096@code{gdb.Inferior.connection} attribute
7097(@pxref{gdbpy_inferior_connection,,gdb.Inferior.connection}).
7098
24b2de7b
AB
7099Currently there is only a single sub-class of
7100@code{gdb.TargetConnection}, @code{gdb.RemoteTargetConnection},
7101however, additional sub-classes may be added in future releases of
7102@value{GDBN}. As a result you should avoid writing code like:
7103
7104@smallexample
7105conn = gdb.selected_inferior().connection
7106if type(conn) is gdb.RemoteTargetConnection:
7107 print("This is a remote target connection")
7108@end smallexample
7109
7110@noindent
7111as this may fail when more connection types are added. Instead, you
7112should write:
7113
7114@smallexample
7115conn = gdb.selected_inferior().connection
7116if isinstance(conn, gdb.RemoteTargetConnection):
7117 print("This is a remote target connection")
7118@end smallexample
7119
0e3b7c25
AB
7120A @code{gdb.TargetConnection} has the following method:
7121
7122@defun TargetConnection.is_valid ()
7123Return @code{True} if the @code{gdb.TargetConnection} object is valid,
7124@code{False} if not. A @code{gdb.TargetConnection} will become
7125invalid if the connection no longer exists within @value{GDBN}, this
7126might happen when no inferiors are using the connection, but could be
7127delayed until the user replaces the current target.
7128
7129Reading any of the @code{gdb.TargetConnection} properties will throw
7130an exception if the connection is invalid.
7131@end defun
7132
7133A @code{gdb.TargetConnection} has the following read-only properties:
7134
7135@defvar TargetConnection.num
7136An integer assigned by @value{GDBN} to uniquely identify this
7137connection. This is the same value as displayed in the @samp{Num}
7138column of the @code{info connections} command output (@pxref{Inferiors
7139Connections and Programs,,info connections}).
7140@end defvar
7141
7142@defvar TargetConnection.type
7143A string that describes what type of connection this is. This string
7144will be one of the valid names that can be passed to the @code{target}
7145command (@pxref{Target Commands,,target command}).
7146@end defvar
7147
7148@defvar TargetConnection.description
7149A string that gives a short description of this target type. This is
7150the same string that is displayed in the @samp{Description} column of
7151the @code{info connection} command output (@pxref{Inferiors
7152Connections and Programs,,info connections}).
7153@end defvar
7154
7155@defvar TargetConnection.details
7156An optional string that gives additional information about this
7157connection. This attribute can be @code{None} if there are no
7158additional details for this connection.
7159
7160An example of a connection type that might have additional details is
7161the @samp{remote} connection, in this case the details string can
7162contain the @samp{@var{hostname}:@var{port}} that was used to connect
7163to the remote target.
7164@end defvar
7165
24b2de7b
AB
7166The @code{gdb.RemoteTargetConnection} class is a sub-class of
7167@code{gdb.TargetConnection}, and is used to represent @samp{remote}
7168and @samp{extended-remote} connections. In addition to the attributes
7169and methods available from the @code{gdb.TargetConnection} base class,
7170a @code{gdb.RemoteTargetConnection} has the following method:
7171
7172@kindex maint packet
ebb83b77 7173@defun RemoteTargetConnection.send_packet (packet)
24b2de7b
AB
7174This method sends @var{packet} to the remote target and returns the
7175response. The @var{packet} should either be a @code{bytes} object, or
7176a @code{Unicode} string.
7177
7178If @var{packet} is a @code{Unicode} string, then the string is encoded
7179to a @code{bytes} object using the @sc{ascii} codec. If the string
7180can't be encoded then an @code{UnicodeError} is raised.
7181
7182If @var{packet} is not a @code{bytes} object, or a @code{Unicode}
7183string, then a @code{TypeError} is raised. If @var{packet} is empty
7184then a @code{ValueError} is raised.
7185
914a96d7
TT
7186The response is returned as a @code{bytes} object. If it is known
7187that the response can be represented as a string then this can be
7188decoded from the buffer. For example, if it is known that the
24b2de7b
AB
7189response is an @sc{ascii} string:
7190
7191@smallexample
7192remote_connection.send_packet("some_packet").decode("ascii")
7193@end smallexample
7194
24b2de7b
AB
7195The prefix, suffix, and checksum (as required by the remote serial
7196protocol) are automatically added to the outgoing packet, and removed
7197from the incoming packet before the contents of the reply are
7198returned.
7199
7200This is equivalent to the @code{maintenance packet} command
7201(@pxref{maint packet}).
7202@end defun
7203
01b1af32
TT
7204@node TUI Windows In Python
7205@subsubsection Implementing new TUI windows
7206@cindex Python TUI Windows
7207
7208New TUI (@pxref{TUI}) windows can be implemented in Python.
7209
ebb83b77 7210@defun gdb.register_window_type (name, factory)
01b1af32
TT
7211Because TUI windows are created and destroyed depending on the layout
7212the user chooses, new window types are implemented by registering a
7213factory function with @value{GDBN}.
7214
7215@var{name} is the name of the new window. It's an error to try to
7216replace one of the built-in windows, but other window types can be
7abc6ec0
AB
7217replaced. The @var{name} should match the regular expression
7218@code{[a-zA-Z][-_.a-zA-Z0-9]*}, it is an error to try and create a
7219window with an invalid name.
01b1af32
TT
7220
7221@var{function} is a factory function that is called to create the TUI
7222window. This is called with a single argument of type
7223@code{gdb.TuiWindow}, described below. It should return an object
7224that implements the TUI window protocol, also described below.
7225@end defun
7226
e8460459 7227As mentioned above, when a factory function is called, it is passed
01b1af32
TT
7228an object of type @code{gdb.TuiWindow}. This object has these
7229methods and attributes:
7230
7231@defun TuiWindow.is_valid ()
7232This method returns @code{True} when this window is valid. When the
7233user changes the TUI layout, windows no longer visible in the new
7234layout will be destroyed. At this point, the @code{gdb.TuiWindow}
7235will no longer be valid, and methods (and attributes) other than
7236@code{is_valid} will throw an exception.
29db1eb3
AB
7237
7238When the TUI is disabled using @code{tui disable} (@pxref{TUI
7239Commands,,tui disable}) the window is hidden rather than destroyed,
7240but @code{is_valid} will still return @code{False} and other methods
7241(and attributes) will still throw an exception.
01b1af32
TT
7242@end defun
7243
7244@defvar TuiWindow.width
7245This attribute holds the width of the window. It is not writable.
7246@end defvar
7247
7248@defvar TuiWindow.height
7249This attribute holds the height of the window. It is not writable.
7250@end defvar
7251
7252@defvar TuiWindow.title
7253This attribute holds the window's title, a string. This is normally
7254displayed above the window. This attribute can be modified.
7255@end defvar
7256
7257@defun TuiWindow.erase ()
7258Remove all the contents of the window.
7259@end defun
7260
ebb83b77 7261@defun TuiWindow.write (string @r{[}, full_window@r{]})
01b1af32
TT
7262Write @var{string} to the window. @var{string} can contain ANSI
7263terminal escape styling sequences; @value{GDBN} will translate these
7264as appropriate for the terminal.
bdef5723
HD
7265
7266If the @var{full_window} parameter is @code{True}, then @var{string}
7267contains the full contents of the window. This is similar to calling
7268@code{erase} before @code{write}, but avoids the flickering.
01b1af32
TT
7269@end defun
7270
7271The factory function that you supply should return an object
7272conforming to the TUI window protocol. These are the method that can
7273be called on this object, which is referred to below as the ``window
7274object''. The methods documented below are optional; if the object
7275does not implement one of these methods, @value{GDBN} will not attempt
7276to call it. Additional new methods may be added to the window
7277protocol in the future. @value{GDBN} guarantees that they will begin
7278with a lower-case letter, so you can start implementation methods with
7279upper-case letters or underscore to avoid any future conflicts.
7280
7281@defun Window.close ()
7282When the TUI window is closed, the @code{gdb.TuiWindow} object will be
7283put into an invalid state. At this time, @value{GDBN} will call
7284@code{close} method on the window object.
7285
7286After this method is called, @value{GDBN} will discard any references
7287it holds on this window object, and will no longer call methods on
7288this object.
7289@end defun
7290
7291@defun Window.render ()
7292In some situations, a TUI window can change size. For example, this
7293can happen if the user resizes the terminal, or changes the layout.
7294When this happens, @value{GDBN} will call the @code{render} method on
7295the window object.
7296
7297If your window is intended to update in response to changes in the
7298inferior, you will probably also want to register event listeners and
7299send output to the @code{gdb.TuiWindow}.
7300@end defun
7301
ebb83b77 7302@defun Window.hscroll (num)
01b1af32
TT
7303This is a request to scroll the window horizontally. @var{num} is the
7304amount by which to scroll, with negative numbers meaning to scroll
7305right. In the TUI model, it is the viewport that moves, not the
7306contents. A positive argument should cause the viewport to move
7307right, and so the content should appear to move to the left.
7308@end defun
7309
ebb83b77 7310@defun Window.vscroll (num)
01b1af32
TT
7311This is a request to scroll the window vertically. @var{num} is the
7312amount by which to scroll, with negative numbers meaning to scroll
7313backward. In the TUI model, it is the viewport that moves, not the
7314contents. A positive argument should cause the viewport to move down,
7315and so the content should appear to move up.
7316@end defun
7317
0f6a6994 7318@anchor{python-window-click}
ebb83b77 7319@defun Window.click (x, y, button)
a5375566 7320This is called on a mouse click in this window. @var{x} and @var{y} are
965c919f
AB
7321the mouse coordinates inside the window (0-based, from the top left
7322corner), and @var{button} specifies which mouse button was used, whose
7323values can be 1 (left), 2 (middle), or 3 (right).
0f6a6994
MG
7324
7325When TUI mouse events are disabled by turning off the @code{tui mouse-events}
7326setting (@pxref{tui-mouse-events,,set tui mouse-events}), then @code{click} will
7327not be called.
a5375566
HD
7328@end defun
7329
15e15b2d
AB
7330@node Disassembly In Python
7331@subsubsection Instruction Disassembly In Python
7332@cindex python instruction disassembly
7333
7334@value{GDBN}'s builtin disassembler can be extended, or even replaced,
7335using the Python API. The disassembler related features are contained
7336within the @code{gdb.disassembler} module:
7337
4de4e485 7338@anchor{DisassembleInfo Class}
15e15b2d
AB
7339@deftp {class} gdb.disassembler.DisassembleInfo
7340Disassembly is driven by instances of this class. Each time
7341@value{GDBN} needs to disassemble an instruction, an instance of this
7342class is created and passed to a registered disassembler. The
7343disassembler is then responsible for disassembling an instruction and
7344returning a result.
7345
7346Instances of this type are usually created within @value{GDBN},
7347however, it is possible to create a copy of an instance of this type,
7348see the description of @code{__init__} for more details.
7349
7350This class has the following properties and methods:
7351
7352@defvar DisassembleInfo.address
7353A read-only integer containing the address at which @value{GDBN}
7354wishes to disassemble a single instruction.
7355@end defvar
7356
7357@defvar DisassembleInfo.architecture
7358The @code{gdb.Architecture} (@pxref{Architectures In Python}) for
7359which @value{GDBN} is currently disassembling, this property is
7360read-only.
7361@end defvar
7362
7363@defvar DisassembleInfo.progspace
7364The @code{gdb.Progspace} (@pxref{Progspaces In Python,,Program Spaces
7365In Python}) for which @value{GDBN} is currently disassembling, this
7366property is read-only.
7367@end defvar
7368
7369@defun DisassembleInfo.is_valid ()
7370Returns @code{True} if the @code{DisassembleInfo} object is valid,
7371@code{False} if not. A @code{DisassembleInfo} object will become
7372invalid once the disassembly call for which the @code{DisassembleInfo}
7373was created, has returned. Calling other @code{DisassembleInfo}
7374methods, or accessing @code{DisassembleInfo} properties, will raise a
7375@code{RuntimeError} exception if it is invalid.
7376@end defun
7377
7378@defun DisassembleInfo.__init__ (info)
7379This can be used to create a new @code{DisassembleInfo} object that is
7380a copy of @var{info}. The copy will have the same @code{address},
7381@code{architecture}, and @code{progspace} values as @var{info}, and
7382will become invalid at the same time as @var{info}.
7383
7384This method exists so that sub-classes of @code{DisassembleInfo} can
7385be created, these sub-classes must be initialized as copies of an
7386existing @code{DisassembleInfo} object, but sub-classes might choose
7387to override the @code{read_memory} method, and so control what
7388@value{GDBN} sees when reading from memory
7389(@pxref{builtin_disassemble}).
7390@end defun
7391
7392@defun DisassembleInfo.read_memory (length, offset)
7393This method allows the disassembler to read the bytes of the
7394instruction to be disassembled. The method reads @var{length} bytes,
7395starting at @var{offset} from
7396@code{DisassembleInfo.address}.
7397
7398It is important that the disassembler read the instruction bytes using
7399this method, rather than reading inferior memory directly, as in some
7400cases @value{GDBN} disassembles from an internal buffer rather than
7401directly from inferior memory, calling this method handles this
7402detail.
7403
7404Returns a buffer object, which behaves much like an array or a string,
7405just as @code{Inferior.read_memory} does
7406(@pxref{gdbpy_inferior_read_memory,,Inferior.read_memory}). The
7407length of the returned buffer will always be exactly @var{length}.
7408
7409If @value{GDBN} is unable to read the required memory then a
7410@code{gdb.MemoryError} exception is raised (@pxref{Exception
7411Handling}).
7412
7413This method can be overridden by a sub-class in order to control what
7414@value{GDBN} sees when reading from memory
7415(@pxref{builtin_disassemble}). When overriding this method it is
7416important to understand how @code{builtin_disassemble} makes use of
7417this method.
7418
7419While disassembling a single instruction there could be multiple calls
7420to this method, and the same bytes might be read multiple times. Any
7421single call might only read a subset of the total instruction bytes.
7422
7423If an implementation of @code{read_memory} is unable to read the
7424requested memory contents, for example, if there's a request to read
7425from an invalid memory address, then a @code{gdb.MemoryError} should
7426be raised.
7427
7428Raising a @code{MemoryError} inside @code{read_memory} does not
7429automatically mean a @code{MemoryError} will be raised by
7430@code{builtin_disassemble}. It is possible the @value{GDBN}'s builtin
7431disassembler is probing to see how many bytes are available. When
7432@code{read_memory} raises the @code{MemoryError} the builtin
7433disassembler might be able to perform a complete disassembly with the
7434bytes it has available, in this case @code{builtin_disassemble} will
7435not itself raise a @code{MemoryError}.
7436
7437Any other exception type raised in @code{read_memory} will propagate
c6d20401 7438back and be re-raised by @code{builtin_disassemble}.
15e15b2d 7439@end defun
4de4e485
AB
7440
7441@defun DisassembleInfo.text_part (style, string)
7442Create a new @code{DisassemblerTextPart} representing a piece of a
7443disassembled instruction. @var{string} should be a non-empty string,
7444and @var{style} should be an appropriate style constant
7445(@pxref{Disassembler Style Constants}).
7446
7447Disassembler parts are used when creating a @code{DisassemblerResult}
7448in order to represent the styling within an instruction
7449(@pxref{DisassemblerResult Class}).
7450@end defun
7451
7452@defun DisassembleInfo.address_part (address)
7453Create a new @code{DisassemblerAddressPart}. @var{address} is the
7454value of the absolute address this part represents. A
7455@code{DisassemblerAddressPart} is displayed as an absolute address and
7456an associated symbol, the address and symbol are styled appropriately.
7457@end defun
7458
15e15b2d
AB
7459@end deftp
7460
773e2d29
AB
7461@anchor{Disassembler Class}
7462@deftp {class} gdb.disassembler.Disassembler
15e15b2d
AB
7463This is a base class from which all user implemented disassemblers
7464must inherit.
7465
7466@defun Disassembler.__init__ (name)
7467The constructor takes @var{name}, a string, which should be a short
7468name for this disassembler.
7469@end defun
7470
7471@defun Disassembler.__call__ (info)
7472The @code{__call__} method must be overridden by sub-classes to
7473perform disassembly. Calling @code{__call__} on this base class will
7474raise a @code{NotImplementedError} exception.
7475
7476The @var{info} argument is an instance of @code{DisassembleInfo}, and
7477describes the instruction that @value{GDBN} wants disassembling.
7478
7479If this function returns @code{None}, this indicates to @value{GDBN}
7480that this sub-class doesn't wish to disassemble the requested
7481instruction. @value{GDBN} will then use its builtin disassembler to
7482perform the disassembly.
7483
7484Alternatively, this function can return a @code{DisassemblerResult}
7485that represents the disassembled instruction, this type is described
7486in more detail below.
7487
7488The @code{__call__} method can raise a @code{gdb.MemoryError}
7489exception (@pxref{Exception Handling}) to indicate to @value{GDBN}
7490that there was a problem accessing the required memory, this will then
7491be displayed by @value{GDBN} within the disassembler output.
7492
7493Ideally, the only three outcomes from invoking @code{__call__} would
7494be a return of @code{None}, a successful disassembly returned in a
7495@code{DisassemblerResult}, or a @code{MemoryError} indicating that
7496there was a problem reading memory.
7497
7498However, as an implementation of @code{__call__} could fail due to
7499other reasons, e.g.@: some external resource required to perform
7500disassembly is temporarily unavailable, then, if @code{__call__}
7501raises a @code{GdbError}, the exception will be converted to a string
7502and printed at the end of the disassembly output, the disassembly
7503request will then stop.
7504
7505Any other exception type raised by the @code{__call__} method is
7506considered an error in the user code, the exception will be printed to
7507the error stream according to the @kbd{set python print-stack} setting
7508(@pxref{set_python_print_stack,,@kbd{set python print-stack}}).
7509@end defun
7510@end deftp
7511
4de4e485 7512@anchor{DisassemblerResult Class}
773e2d29
AB
7513@deftp {class} gdb.disassembler.DisassemblerResult
7514This class represents the result of disassembling a single
7515instruction. An instance of this class will be returned from
7516@code{builtin_disassemble} (@pxref{builtin_disassemble}), and an
7517instance of this class should be returned from
7518@w{@code{Disassembler.__call__}} (@pxref{Disassembler Class}) if an
7519instruction was successfully disassembled.
7520
0af2f233
AB
7521It is not possible to sub-class the @code{DisassemblerResult} class.
7522
773e2d29
AB
7523The @code{DisassemblerResult} class has the following properties and
7524methods:
15e15b2d 7525
4de4e485 7526@defun DisassemblerResult.__init__ (length, string, parts)
15e15b2d
AB
7527Initialize an instance of this class, @var{length} is the length of
7528the disassembled instruction in bytes, which must be greater than
4de4e485
AB
7529zero.
7530
7531Only one of @var{string} or @var{parts} should be used to initialize a
7532new @code{DisassemblerResult}; the other one should be passed the
7533value @code{None}. Alternatively, the arguments can be passed by
7534name, and the unused argument can be ignored.
7535
7536The @var{string} argument, if not @code{None}, is a non-empty string
7537that represents the entire disassembled instruction. Building a result
7538object using the @var{string} argument does not allow for any styling
7539information to be included in the result. @value{GDBN} will style the
7540result as a single @code{DisassemblerTextPart} with @code{STYLE_TEXT}
7541style (@pxref{Disassembler Styling Parts}).
7542
7543The @var{parts} argument, if not @code{None}, is a non-empty sequence
7544of @code{DisassemblerPart} objects. Each part represents a small part
7545of the disassembled instruction along with associated styling
7546information. A result object built using @var{parts} can be displayed
7547by @value{GDBN} with full styling information
7548(@pxref{style_disassembler_enabled,,@kbd{set style disassembler
7549enabled}}).
15e15b2d
AB
7550@end defun
7551
7552@defvar DisassemblerResult.length
7553A read-only property containing the length of the disassembled
7554instruction in bytes, this will always be greater than zero.
7555@end defvar
7556
7557@defvar DisassemblerResult.string
7558A read-only property containing a non-empty string representing the
4de4e485
AB
7559disassembled instruction. The @var{string} is a representation of the
7560disassembled instruction without any styling information. To see how
7561the instruction will be styled use the @var{parts} property.
7562
7563If this instance was initialized using separate
7564@code{DisassemblerPart} objects, the @var{string} property will still
7565be valid. The @var{string} value is created by concatenating the
7566@code{DisassemblerPart.string} values of each component part
7567(@pxref{Disassembler Styling Parts}).
7568@end defvar
7569
7570@defvar DisassemblerResult.parts
7571A read-only property containing a non-empty sequence of
7572@code{DisassemblerPart} objects. Each @code{DisassemblerPart} object
7573contains a small part of the instruction along with information about
7574how that part should be styled. @value{GDBN} uses this information to
7575create styled disassembler output
7576(@pxref{style_disassembler_enabled,,@kbd{set style disassembler
7577enabled}}).
7578
7579If this instance was initialized using a single string rather than
7580with a sequence of @code{DisassemblerPart} objects, the @var{parts}
7581property will still be valid. In this case the @var{parts} property
7582will hold a sequence containing a single @code{DisassemblerTextPart}
7583object, the string of which will represent the entire instruction, and
7584the style of which will be @code{STYLE_TEXT}.
7585@end defvar
7586@end deftp
7587
7588@anchor{Disassembler Styling Parts}
7589@deftp {class} gdb.disassembler.DisassemblerPart
7590This is a parent class from which the different part sub-classes
7591inherit. Only instances of the sub-classes detailed below will be
7592returned by the Python API.
7593
7594It is not possible to directly create instances of either this parent
7595class, or any of the sub-classes listed below. Instances of the
7596sub-classes listed below are created by calling
7597@code{builtin_disassemble} (@pxref{builtin_disassemble}) and are
7598returned within the @code{DisassemblerResult} object, or can be
7599created by calling the @code{text_part} and @code{address_part}
7600methods on the @code{DisassembleInfo} class (@pxref{DisassembleInfo
7601Class}).
7602
7603The @code{DisassemblerPart} class has a single property:
7604
7605@defvar DisassemblerPart.string
7606A read-only property that contains a non-empty string representing
7607this part of the disassembled instruction. The string within this
7608property doesn't include any styling information.
15e15b2d
AB
7609@end defvar
7610@end deftp
7611
4de4e485
AB
7612@deftp {class} gdb.disassembler.DisassemblerTextPart
7613The @code{DisassemblerTextPart} class represents a piece of the
7614disassembled instruction and the associated style for that piece.
7615Instances of this class can't be created directly, instead call
7616@code{DisassembleInfo.text_part} to create a new instance of this
7617class (@pxref{DisassembleInfo Class}).
7618
7619As well as the properties of its parent class, the
7620@code{DisassemblerTextPart} has the following additional property:
7621
7622@defvar DisassemblerTextPart.style
7623A read-only property that contains one of the defined style constants.
7624@value{GDBN} will use this style when styling this part of the
7625disassembled instruction (@pxref{Disassembler Style Constants}).
7626@end defvar
7627@end deftp
7628
7629@deftp {class} gdb.disassembler.DisassemblerAddressPart
7630The @code{DisassemblerAddressPart} class represents an absolute
7631address within a disassembled instruction. Using a
7632@code{DisassemblerAddressPart} instead of a
7633@code{DisassemblerTextPart} with @code{STYLE_ADDRESS} is preferred,
7634@value{GDBN} will display the address as both an absolute address, and
7635will look up a suitable symbol to display next to the address. Using
7636@code{DisassemblerAddressPart} also ensures that user settings such as
7637@code{set print max-symbolic-offset} are respected.
7638
7639Here is an example of an x86-64 instruction:
7640
7641@smallexample
7642call 0x401136 <foo>
7643@end smallexample
7644
7645@noindent
7646In this instruction the @code{0x401136 <foo>} was generated from a
7647single @code{DisassemblerAddressPart}. The @code{0x401136} will be
7648styled with @code{STYLE_ADDRESS}, and @code{foo} will be styled with
7649@code{STYLE_SYMBOL}. The @code{<} and @code{>} will be styled as
7650@code{STYLE_TEXT}.
7651
7652If the inclusion of the symbol name is not required then a
7653@code{DisassemblerTextPart} with style @code{STYLE_ADDRESS} can be
7654used instead.
7655
7656Instances of this class can't be created directly, instead call
7657@code{DisassembleInfo.address_part} to create a new instance of this
7658class (@pxref{DisassembleInfo Class}).
7659
7660As well as the properties of its parent class, the
7661@code{DisassemblerAddressPart} has the following additional property:
7662
7663@defvar DisassemblerAddressPart.address
7664A read-only property that contains the @var{address} passed to this
7665object's @code{__init__} method.
7666@end defvar
7667@end deftp
7668
7669@anchor{Disassembler Style Constants}
7670
7671The following table lists all of the disassembler styles that are
7672available. @value{GDBN} maps these style constants onto its style
7673settings (@pxref{Output Styling}). In some cases, several style
7674constants produce the same style settings, and thus will produce the
7675same visual effect on the screen. This could change in future
7676releases of @value{GDBN}, so care should be taken to select the
7677correct style constant to ensure correct output styling in future
7678releases of @value{GDBN}.
7679
7680@vtable @code
7681@vindex STYLE_TEXT
7682@item gdb.disassembler.STYLE_TEXT
7683This is the default style used by @value{GDBN} when styling
7684disassembler output. This style should be used for any parts of the
7685instruction that don't fit any of the other styles listed below.
7686@value{GDBN} styles text with this style using its default style.
7687
7688@vindex STYLE_MNEMONIC
7689@item gdb.disassembler.STYLE_MNEMONIC
7690This style is used for styling the primary instruction mnemonic, which
7691usually appears at, or near, the start of the disassembled instruction
7692string.
7693
7694@value{GDBN} styles text with this style using the @code{disassembler
7695mnemonic} style setting.
7696
7697@vindex STYLE_SUB_MNEMONIC
7698@item gdb.disassembler.STYLE_SUB_MNEMONIC
7699This style is used for styling any sub-mnemonics within a disassembled
7700instruction. A sub-mnemonic is any text within the instruction that
7701controls the function of the instruction, but which is disjoint from
7702the primary mnemonic (which will have styled @code{STYLE_MNEMONIC}).
7703
7704As an example, consider this AArch64 instruction:
7705
7706@smallexample
7707add w16, w7, w1, lsl #1
7708@end smallexample
7709
7710@noindent
7711The @code{add} is the primary instruction mnemonic, and would be given
7712style @code{STYLE_MNEMONIC}, while @code{lsl} is the sub-mnemonic, and
7713would be given the style @code{STYLE_SUB_MNEMONIC}.
7714
7715@value{GDBN} styles text with this style using the @code{disassembler
7716mnemonic} style setting.
7717
7718@vindex STYLE_ASSEMBLER_DIRECTIVE
7719@item gdb.disassembler.STYLE_ASSEMBLER_DIRECTIVE
7720Sometimes a series of bytes doesn't decode to a valid instruction. In
7721this case the disassembler may choose to represent the result of
7722disassembling using an assembler directive, for example:
7723
7724@smallexample
7725.word 0x1234
7726@end smallexample
7727
7728@noindent
7729In this case, the @code{.word} would be give the
7730@code{STYLE_ASSEMBLER_DIRECTIVE} style. An assembler directive is
7731similar to a mnemonic in many ways but is something that is not part
7732of the architecture's instruction set.
7733
7734@value{GDBN} styles text with this style using the @code{disassembler
7735mnemonic} style setting.
7736
7737@vindex STYLE_REGISTER
7738@item gdb.disassembler.STYLE_REGISTER
7739This style is used for styling any text that represents a register
7740name, or register number, within a disassembled instruction.
7741
7742@value{GDBN} styles text with this style using the @code{disassembler
7743register} style setting.
7744
7745@vindex STYLE_ADDRESS
7746@item gdb.disassembler.STYLE_ADDRESS
7747This style is used for styling numerical values that represent
7748absolute addresses within the disassembled instruction.
7749
7750When creating a @code{DisassemblerTextPart} with this style, you
7751should consider if a @code{DisassemblerAddressPart} would be more
7752appropriate. See @ref{Disassembler Styling Parts} for a description
7753of what each part offers.
7754
7755@value{GDBN} styles text with this style using the @code{disassembler
7756address} style setting.
7757
7758@vindex STYLE_ADDRESS_OFFSET
7759@item gdb.disassembler.STYLE_ADDRESS_OFFSET
7760This style is used for styling numerical values that represent offsets
7761to addresses within the disassembled instruction. A value is
7762considered an address offset when the instruction itself is going to
7763access memory, and the value is being used to offset which address is
7764accessed.
7765
7766For example, an architecture might have an instruction that loads from
7767memory using an address within a register. If that instruction also
7768allowed for an immediate offset to be encoded into the instruction,
7769this would be an address offset. Similarly, a branch instruction
7770might jump to an address in a register plus an address offset that is
7771encoded into the instruction.
7772
7773@value{GDBN} styles text with this style using the @code{disassembler
7774immediate} style setting.
7775
7776@vindex STYLE_IMMEDIATE
7777@item gdb.disassembler.STYLE_IMMEDIATE
7778Use @code{STYLE_IMMEDIATE} for any numerical values within a
7779disassembled instruction when those values are not addresses, address
7780offsets, or register numbers (The styles @code{STYLE_ADDRESS},
7781@code{STYLE_ADDRESS_OFFSET}, or @code{STYLE_REGISTER} can be used in
7782those cases).
7783
7784@value{GDBN} styles text with this style using the @code{disassembler
7785immediate} style setting.
7786
7787@vindex STYLE_SYMBOL
7788@item gdb.disassembler.STYLE_SYMBOL
7789This style is used for styling the textual name of a symbol that is
7790included within a disassembled instruction. A symbol name is often
7791included next to an absolute address within a disassembled instruction
7792to make it easier for the user to understand what the address is
7793referring too. For example:
7794
7795@smallexample
7796call 0x401136 <foo>
7797@end smallexample
7798
7799@noindent
7800Here @code{foo} is the name of a symbol, and should be given the
7801@code{STYLE_SYMBOL} style.
7802
7803Adding symbols next to absolute addresses like this is handled
7804automatically by the @code{DisassemblerAddressPart} class
7805(@pxref{Disassembler Styling Parts}).
7806
7807@value{GDBN} styles text with this style using the @code{disassembler
7808symbol} style setting.
7809
7810@vindex STYLE_COMMENT_START
7811@item gdb.disassembler.STYLE_COMMENT_START
7812This style is used to start a line comment in the disassembly output.
7813Unlike other styles, which only apply to the single
7814@code{DisassemblerTextPiece} to which they are applied, the comment
7815style is sticky, and overrides the style of any further pieces within
7816this instruction.
7817
7818This means that, after a @code{STYLE_COMMENT_START} piece has been
7819seen, @value{GDBN} will apply the comment style until the end of the
7820line, ignoring the specific style within a piece.
7821
7822@value{GDBN} styles text with this style using the @code{disassembler
7823comment} style setting.
7824@end vtable
7825
15e15b2d
AB
7826The following functions are also contained in the
7827@code{gdb.disassembler} module:
7828
7829@defun register_disassembler (disassembler, architecture)
7830The @var{disassembler} must be a sub-class of
7831@code{gdb.disassembler.Disassembler} or @code{None}.
7832
7833The optional @var{architecture} is either a string, or the value
7834@code{None}. If it is a string, then it should be the name of an
7835architecture known to @value{GDBN}, as returned either from
7836@code{gdb.Architecture.name}
7837(@pxref{gdbpy_architecture_name,,gdb.Architecture.name}), or from
7838@code{gdb.architecture_names}
7839(@pxref{gdb_architecture_names,,gdb.architecture_names}).
7840
7841The @var{disassembler} will be installed for the architecture named by
7842@var{architecture}, or if @var{architecture} is @code{None}, then
7843@var{disassembler} will be installed as a global disassembler for use
7844by all architectures.
7845
7846@cindex disassembler in Python, global vs.@: specific
7847@cindex search order for disassembler in Python
7848@cindex look up of disassembler in Python
7849@value{GDBN} only records a single disassembler for each architecture,
7850and a single global disassembler. Calling
7851@code{register_disassembler} for an architecture, or for the global
7852disassembler, will replace any existing disassembler registered for
7853that @var{architecture} value. The previous disassembler is returned.
7854
7855If @var{disassembler} is @code{None} then any disassembler currently
7856registered for @var{architecture} is deregistered and returned.
7857
7858When @value{GDBN} is looking for a disassembler to use, @value{GDBN}
7859first looks for an architecture specific disassembler. If none has
7860been registered then @value{GDBN} looks for a global disassembler (one
7861registered with @var{architecture} set to @code{None}). Only one
7862disassembler is called to perform disassembly, so, if there is both an
7863architecture specific disassembler, and a global disassembler
7864registered, it is the architecture specific disassembler that will be
7865used.
7866
7867@value{GDBN} tracks the architecture specific, and global
7868disassemblers separately, so it doesn't matter in which order
7869disassemblers are created or registered; an architecture specific
7870disassembler, if present, will always be used in preference to a
7871global disassembler.
7872
7873You can use the @kbd{maint info python-disassemblers} command
7874(@pxref{maint info python-disassemblers}) to see which disassemblers
7875have been registered.
7876@end defun
7877
7878@anchor{builtin_disassemble}
7879@defun builtin_disassemble (info)
7880This function calls back into @value{GDBN}'s builtin disassembler to
7881disassemble the instruction identified by @var{info}, an instance, or
7882sub-class, of @code{DisassembleInfo}.
7883
7884When the builtin disassembler needs to read memory the
7885@code{read_memory} method on @var{info} will be called. By
7886sub-classing @code{DisassembleInfo} and overriding the
7887@code{read_memory} method, it is possible to intercept calls to
7888@code{read_memory} from the builtin disassembler, and to modify the
7889values returned.
7890
7891It is important to understand that, even when
7892@code{DisassembleInfo.read_memory} raises a @code{gdb.MemoryError}, it
7893is the internal disassembler itself that reports the memory error to
7894@value{GDBN}. The reason for this is that the disassembler might
7895probe memory to see if a byte is readable or not; if the byte can't be
7896read then the disassembler may choose not to report an error, but
7897instead to disassemble the bytes that it does have available.
7898
7899If the builtin disassembler is successful then an instance of
7900@code{DisassemblerResult} is returned from @code{builtin_disassemble},
7901alternatively, if something goes wrong, an exception will be raised.
7902
7903A @code{MemoryError} will be raised if @code{builtin_disassemble} is
7904unable to read some memory that is required in order to perform
7905disassembly correctly.
7906
7907Any exception that is not a @code{MemoryError}, that is raised in a
7908call to @code{read_memory}, will pass through
7909@code{builtin_disassemble}, and be visible to the caller.
7910
7911Finally, there are a few cases where @value{GDBN}'s builtin
7912disassembler can fail for reasons that are not covered by
7913@code{MemoryError}. In these cases, a @code{GdbError} will be raised.
7914The contents of the exception will be a string describing the problem
7915the disassembler encountered.
7916@end defun
7917
7918Here is an example that registers a global disassembler. The new
7919disassembler invokes the builtin disassembler, and then adds a
7920comment, @code{## Comment}, to each line of disassembly output:
7921
7922@smallexample
7923class ExampleDisassembler(gdb.disassembler.Disassembler):
7924 def __init__(self):
7925 super().__init__("ExampleDisassembler")
7926
7927 def __call__(self, info):
7928 result = gdb.disassembler.builtin_disassemble(info)
7929 length = result.length
7930 text = result.string + "\t## Comment"
7931 return gdb.disassembler.DisassemblerResult(length, text)
7932
7933gdb.disassembler.register_disassembler(ExampleDisassembler())
7934@end smallexample
7935
7936The following example creates a sub-class of @code{DisassembleInfo} in
7937order to intercept the @code{read_memory} calls, within
7938@code{read_memory} any bytes read from memory have the two 4-bit
7939nibbles swapped around. This isn't a very useful adjustment, but
7940serves as an example.
7941
7942@smallexample
7943class MyInfo(gdb.disassembler.DisassembleInfo):
7944 def __init__(self, info):
7945 super().__init__(info)
7946
7947 def read_memory(self, length, offset):
7948 buffer = super().read_memory(length, offset)
7949 result = bytearray()
7950 for b in buffer:
7951 v = int.from_bytes(b, 'little')
7952 v = (v << 4) & 0xf0 | (v >> 4)
7953 result.append(v)
7954 return memoryview(result)
7955
7956class NibbleSwapDisassembler(gdb.disassembler.Disassembler):
7957 def __init__(self):
7958 super().__init__("NibbleSwapDisassembler")
7959
7960 def __call__(self, info):
7961 info = MyInfo(info)
7962 return gdb.disassembler.builtin_disassemble(info)
7963
7964gdb.disassembler.register_disassembler(NibbleSwapDisassembler())
7965@end smallexample
7966
8f6c452b
AB
7967@node Missing Debug Info In Python
7968@subsubsection Missing Debug Info In Python
7969@cindex python, handle missing debug information
7970
7971When @value{GDBN} encounters a new objfile (@pxref{Objfiles In
7972Python}), e.g.@: the primary executable, or any shared libraries used
7973by the inferior, @value{GDBN} will attempt to load the corresponding
7974debug information for that objfile. The debug information might be
7975found within the objfile itself, or within a separate objfile which
7976@value{GDBN} will automatically locate and load.
7977
7978Sometimes though, @value{GDBN} might not find any debug information
7979for an objfile, in this case the debugging experience will be
7980restricted.
7981
7982If @value{GDBN} fails to locate any debug information for a particular
7983objfile, there is an opportunity for a Python extension to step in. A
7984Python extension can potentially locate the missing debug information
7985using some platform- or project-specific steps, and inform
7986@value{GDBN} of its location. Or a Python extension might provide
7987some platform- or project-specific advice to the user about how to
7988obtain the missing debug information.
7989
7990A missing debug information Python extension consists of a handler
7991object which has the @code{name} and @code{enabled} attributes, and
7992implements the @code{__call__} method. When @value{GDBN} encounters
7993an objfile for which it is unable to find any debug information, it
7994invokes the @code{__call__} method. Full details of how handlers are
7995written can be found below.
7996
7997@subheading The @code{gdb.missing_debug} Module
7998
7999@value{GDBN} comes with a @code{gdb.missing_debug} module which
8000contains the following class and global function:
8001
8002@deftp{class} gdb.missing_debug.MissingDebugHandler
8003
8004@code{MissingDebugHandler} is a base class from which user-created
8005handlers can derive, though it is not required that handlers derive
8006from this class, so long as any user created handler has the
8007@code{name} and @code{enabled} attributes, and implements the
8008@code{__call__} method.
8009
8010@defun MissingDebugHandler.__init__ (name)
8011The @var{name} is a string used to reference this missing debug
8012handler within some @value{GDBN} commands. Valid names consist of the
8013characters @code{[-_a-zA-Z0-9]}, creating a handler with an invalid
8014name raises a @code{ValueError} exception.
8015@end defun
8016
8017@defun MissingDebugHandler.__call__ (objfile)
8018Sub-classes must override the @code{__call__} method. The
8019@var{objfile} argument will be a @code{gdb.Objfile}, this is the
8020objfile for which @value{GDBN} was unable to find any debug
8021information.
8022
8023The return value from the @code{__call__} method indicates what
8024@value{GDBN} should do next. The possible return values are:
8025
8026@itemize @bullet
8027@item @code{None}
8028
8029This indicates that this handler could not help with @var{objfile},
8030@value{GDBN} should call any other registered handlers.
8031
8032@item @code{True}
8033
8034This indicates that this handler has installed the debug information
8035into a location where @value{GDBN} would normally expect to find it
8036when looking for separate debug information files (@pxref{Separate
8037Debug Files}). @value{GDBN} will repeat the normal lookup process,
8038which should now find the separate debug file.
8039
8040If @value{GDBN} still doesn't find the separate debug information file
8041after this second attempt, then the Python missing debug information
8042handlers are not invoked a second time, this prevents a badly behaved
8043handler causing @value{GDBN} to get stuck in a loop. @value{GDBN}
8044will continue without any debug information for @var{objfile}.
8045
8046@item @code{False}
8047
8048This indicates that this handler has done everything that it intends
8049to do with @var{objfile}, but no separate debug information can be
8050found. @value{GDBN} will not call any other registered handlers for
8051@var{objfile}. @value{GDBN} will continue without debugging
8052information for @var{objfile}.
8053
8054@item A string
8055
8056The returned string should contain a filename. @value{GDBN} will not
8057call any further registered handlers, and will instead load the debug
8058information from the file identified by the returned filename.
8059@end itemize
8060
8061Invoking the @code{__call__} method from this base class will raise a
8062@code{NotImplementedError} exception.
8063@end defun
8064
8065@defvar MissingDebugHandler.name
8066A read-only attribute which is a string, the name of this handler
8067passed to the @code{__init__} method.
8068@end defvar
8069
8070@defvar MissingDebugHandler.enabled
8071A modifiable attribute containing a boolean; when @code{True}, the
8072handler is enabled, and will be used by @value{GDBN}. When
8073@code{False}, the handler has been disabled, and will not be used.
8074@end defvar
8075@end deftp
8076
8077@defun gdb.missing_debug.register_handler (locus, handler, replace=@code{False})
8078Register a new missing debug handler with @value{GDBN}.
8079
8080@var{handler} is an instance of a sub-class of
8081@code{MissingDebugHandler}, or at least an instance of an object that
8082has the same attributes and methods as @code{MissingDebugHandler}.
8083
8084@var{locus} specifies to which handler list to prepend @var{handler}.
8085It can be either a @code{gdb.Progspace} (@pxref{Progspaces In Python})
8086or @code{None}, in which case the handler is registered globally. The
8087newly registered @var{handler} will be called before any other handler
8088from the same locus. Two handlers in the same locus cannot have the
8089same name, an attempt to add a handler with an already existing name
8090raises an exception unless @var{replace} is @code{True}, in which case
8091the old handler is deleted and the new handler is prepended to the
8092selected handler list.
8093
8094@value{GDBN} first calls the handlers for the current program space,
8095and then the globally registered handlers. As soon as a handler
8096returns a value other than @code{None}, no further handlers are called
8097for this objfile.
8098@end defun
8099
329baa95
DE
8100@node Python Auto-loading
8101@subsection Python Auto-loading
8102@cindex Python auto-loading
8103
8104When a new object file is read (for example, due to the @code{file}
8105command, or because the inferior has loaded a shared library),
8106@value{GDBN} will look for Python support scripts in several ways:
8107@file{@var{objfile}-gdb.py} and @code{.debug_gdb_scripts} section.
8108@xref{Auto-loading extensions}.
8109
8110The auto-loading feature is useful for supplying application-specific
8111debugging commands and scripts.
8112
8113Auto-loading can be enabled or disabled,
8114and the list of auto-loaded scripts can be printed.
8115
8116@table @code
8117@anchor{set auto-load python-scripts}
8118@kindex set auto-load python-scripts
8119@item set auto-load python-scripts [on|off]
8120Enable or disable the auto-loading of Python scripts.
8121
8122@anchor{show auto-load python-scripts}
8123@kindex show auto-load python-scripts
8124@item show auto-load python-scripts
8125Show whether auto-loading of Python scripts is enabled or disabled.
8126
8127@anchor{info auto-load python-scripts}
8128@kindex info auto-load python-scripts
8129@cindex print list of auto-loaded Python scripts
8130@item info auto-load python-scripts [@var{regexp}]
8131Print the list of all Python scripts that @value{GDBN} auto-loaded.
8132
8133Also printed is the list of Python scripts that were mentioned in
9f050062
DE
8134the @code{.debug_gdb_scripts} section and were either not found
8135(@pxref{dotdebug_gdb_scripts section}) or were not auto-loaded due to
8136@code{auto-load safe-path} rejection (@pxref{Auto-loading}).
329baa95
DE
8137This is useful because their names are not printed when @value{GDBN}
8138tries to load them and fails. There may be many of them, and printing
8139an error message for each one is problematic.
8140
8141If @var{regexp} is supplied only Python scripts with matching names are printed.
8142
8143Example:
8144
8145@smallexample
8146(gdb) info auto-load python-scripts
8147Loaded Script
8148Yes py-section-script.py
8149 full name: /tmp/py-section-script.py
8150No my-foo-pretty-printers.py
8151@end smallexample
8152@end table
8153
9f050062 8154When reading an auto-loaded file or script, @value{GDBN} sets the
329baa95
DE
8155@dfn{current objfile}. This is available via the @code{gdb.current_objfile}
8156function (@pxref{Objfiles In Python}). This can be useful for
8157registering objfile-specific pretty-printers and frame-filters.
8158
8159@node Python modules
8160@subsection Python modules
8161@cindex python modules
8162
8163@value{GDBN} comes with several modules to assist writing Python code.
8164
8165@menu
8166* gdb.printing:: Building and registering pretty-printers.
8167* gdb.types:: Utilities for working with types.
8168* gdb.prompt:: Utilities for prompt value substitution.
8169@end menu
8170
8171@node gdb.printing
8172@subsubsection gdb.printing
8173@cindex gdb.printing
8174
8175This module provides a collection of utilities for working with
8176pretty-printers.
8177
8178@table @code
8179@item PrettyPrinter (@var{name}, @var{subprinters}=None)
8180This class specifies the API that makes @samp{info pretty-printer},
8181@samp{enable pretty-printer} and @samp{disable pretty-printer} work.
8182Pretty-printers should generally inherit from this class.
8183
8184@item SubPrettyPrinter (@var{name})
8185For printers that handle multiple types, this class specifies the
8186corresponding API for the subprinters.
8187
8188@item RegexpCollectionPrettyPrinter (@var{name})
8189Utility class for handling multiple printers, all recognized via
8190regular expressions.
8191@xref{Writing a Pretty-Printer}, for an example.
8192
8193@item FlagEnumerationPrinter (@var{name})
8194A pretty-printer which handles printing of @code{enum} values. Unlike
8195@value{GDBN}'s built-in @code{enum} printing, this printer attempts to
8196work properly when there is some overlap between the enumeration
697aa1b7
EZ
8197constants. The argument @var{name} is the name of the printer and
8198also the name of the @code{enum} type to look up.
329baa95
DE
8199
8200@item register_pretty_printer (@var{obj}, @var{printer}, @var{replace}=False)
8201Register @var{printer} with the pretty-printer list of @var{obj}.
8202If @var{replace} is @code{True} then any existing copy of the printer
8203is replaced. Otherwise a @code{RuntimeError} exception is raised
8204if a printer with the same name already exists.
8205@end table
8206
8207@node gdb.types
8208@subsubsection gdb.types
8209@cindex gdb.types
8210
8211This module provides a collection of utilities for working with
8212@code{gdb.Type} objects.
8213
8214@table @code
8215@item get_basic_type (@var{type})
8216Return @var{type} with const and volatile qualifiers stripped,
8217and with typedefs and C@t{++} references converted to the underlying type.
8218
8219C@t{++} example:
8220
8221@smallexample
8222typedef const int const_int;
8223const_int foo (3);
8224const_int& foo_ref (foo);
8225int main () @{ return 0; @}
8226@end smallexample
8227
8228Then in gdb:
8229
8230@smallexample
8231(gdb) start
8232(gdb) python import gdb.types
8233(gdb) python foo_ref = gdb.parse_and_eval("foo_ref")
8234(gdb) python print gdb.types.get_basic_type(foo_ref.type)
8235int
8236@end smallexample
8237
8238@item has_field (@var{type}, @var{field})
8239Return @code{True} if @var{type}, assumed to be a type with fields
8240(e.g., a structure or union), has field @var{field}.
8241
8242@item make_enum_dict (@var{enum_type})
8243Return a Python @code{dictionary} type produced from @var{enum_type}.
8244
8245@item deep_items (@var{type})
8246Returns a Python iterator similar to the standard
8247@code{gdb.Type.iteritems} method, except that the iterator returned
8248by @code{deep_items} will recursively traverse anonymous struct or
8249union fields. For example:
8250
8251@smallexample
8252struct A
8253@{
8254 int a;
8255 union @{
8256 int b0;
8257 int b1;
8258 @};
8259@};
8260@end smallexample
8261
8262@noindent
8263Then in @value{GDBN}:
8264@smallexample
8265(@value{GDBP}) python import gdb.types
8266(@value{GDBP}) python struct_a = gdb.lookup_type("struct A")
8267(@value{GDBP}) python print struct_a.keys ()
8268@{['a', '']@}
8269(@value{GDBP}) python print [k for k,v in gdb.types.deep_items(struct_a)]
8270@{['a', 'b0', 'b1']@}
8271@end smallexample
8272
8273@item get_type_recognizers ()
8274Return a list of the enabled type recognizers for the current context.
8275This is called by @value{GDBN} during the type-printing process
8276(@pxref{Type Printing API}).
8277
8278@item apply_type_recognizers (recognizers, type_obj)
8279Apply the type recognizers, @var{recognizers}, to the type object
8280@var{type_obj}. If any recognizer returns a string, return that
8281string. Otherwise, return @code{None}. This is called by
8282@value{GDBN} during the type-printing process (@pxref{Type Printing
8283API}).
8284
8285@item register_type_printer (locus, printer)
697aa1b7
EZ
8286This is a convenience function to register a type printer
8287@var{printer}. The printer must implement the type printer protocol.
8288The @var{locus} argument is either a @code{gdb.Objfile}, in which case
8289the printer is registered with that objfile; a @code{gdb.Progspace},
8290in which case the printer is registered with that progspace; or
8291@code{None}, in which case the printer is registered globally.
329baa95
DE
8292
8293@item TypePrinter
8294This is a base class that implements the type printer protocol. Type
8295printers are encouraged, but not required, to derive from this class.
8296It defines a constructor:
8297
8298@defmethod TypePrinter __init__ (self, name)
8299Initialize the type printer with the given name. The new printer
8300starts in the enabled state.
8301@end defmethod
8302
8303@end table
8304
8305@node gdb.prompt
8306@subsubsection gdb.prompt
8307@cindex gdb.prompt
8308
8309This module provides a method for prompt value-substitution.
8310
8311@table @code
8312@item substitute_prompt (@var{string})
8313Return @var{string} with escape sequences substituted by values. Some
8314escape sequences take arguments. You can specify arguments inside
8315``@{@}'' immediately following the escape sequence.
8316
8317The escape sequences you can pass to this function are:
8318
8319@table @code
8320@item \\
8321Substitute a backslash.
8322@item \e
8323Substitute an ESC character.
8324@item \f
8325Substitute the selected frame; an argument names a frame parameter.
8326@item \n
8327Substitute a newline.
8328@item \p
8329Substitute a parameter's value; the argument names the parameter.
8330@item \r
8331Substitute a carriage return.
8332@item \t
8333Substitute the selected thread; an argument names a thread parameter.
8334@item \v
8335Substitute the version of GDB.
8336@item \w
8337Substitute the current working directory.
8338@item \[
8339Begin a sequence of non-printing characters. These sequences are
8340typically used with the ESC character, and are not counted in the string
8341length. Example: ``\[\e[0;34m\](gdb)\[\e[0m\]'' will return a
8342blue-colored ``(gdb)'' prompt where the length is five.
8343@item \]
8344End a sequence of non-printing characters.
8345@end table
8346
8347For example:
8348
8349@smallexample
77bb17b6 8350substitute_prompt ("frame: \f, args: \p@{print frame-arguments@}")
329baa95
DE
8351@end smallexample
8352
8353@exdent will return the string:
8354
8355@smallexample
77bb17b6 8356"frame: main, args: scalars"
329baa95
DE
8357@end smallexample
8358@end table