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