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