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