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