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