Multi-target: NEWS and user manual
[deliverable/binutils-gdb.git] / gdb / doc / python.texi
CommitLineData
b811d2c2 1@c Copyright (C) 2008--2020 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
760f7560 772returns @code{gdb.Value} objects corresponding to the values pointed to
329baa95
DE
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__(....):
6b92c0d3 2521 super(MyUnwinder, self).__init___(<expects unwinder name argument>)
d11916aa
SS
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
65c574f6 2931(@pxref{Inferiors Connections and Programs}). Python scripts can access
329baa95
DE
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
14796d29
CB
3296To get the list of threads for an inferior, use the @code{Inferior.threads()}
3297method. @xref{Inferiors In Python}
3298
329baa95
DE
3299A @code{gdb.InferiorThread} object has the following attributes:
3300
3301@defvar InferiorThread.name
3302The name of the thread. If the user specified a name using
3303@code{thread name}, then this returns that name. Otherwise, if an
3304OS-supplied name is available, then it is returned. Otherwise, this
3305returns @code{None}.
3306
3307This attribute can be assigned to. The new value must be a string
3308object, which sets the new name, or @code{None}, which removes any
3309user-specified thread name.
3310@end defvar
3311
3312@defvar InferiorThread.num
5d5658a1 3313The per-inferior number of the thread, as assigned by GDB.
329baa95
DE
3314@end defvar
3315
22a02324
PA
3316@defvar InferiorThread.global_num
3317The global ID of the thread, as assigned by GDB. You can use this to
3318make Python breakpoints thread-specific, for example
3319(@pxref{python_breakpoint_thread,,The Breakpoint.thread attribute}).
3320@end defvar
3321
329baa95
DE
3322@defvar InferiorThread.ptid
3323ID of the thread, as assigned by the operating system. This attribute is a
3324tuple containing three integers. The first is the Process ID (PID); the second
3325is the Lightweight Process ID (LWPID), and the third is the Thread ID (TID).
3326Either the LWPID or TID may be 0, which indicates that the operating system
3327does not use that identifier.
3328@end defvar
3329
84654457
PA
3330@defvar InferiorThread.inferior
3331The inferior this thread belongs to. This attribute is represented as
3332a @code{gdb.Inferior} object. This attribute is not writable.
3333@end defvar
3334
329baa95
DE
3335A @code{gdb.InferiorThread} object has the following methods:
3336
3337@defun InferiorThread.is_valid ()
3338Returns @code{True} if the @code{gdb.InferiorThread} object is valid,
3339@code{False} if not. A @code{gdb.InferiorThread} object will become
3340invalid if the thread exits, or the inferior that the thread belongs
3341is deleted. All other @code{gdb.InferiorThread} methods will throw an
3342exception if it is invalid at the time the method is called.
3343@end defun
3344
3345@defun InferiorThread.switch ()
3346This changes @value{GDBN}'s currently selected thread to the one represented
3347by this object.
3348@end defun
3349
3350@defun InferiorThread.is_stopped ()
3351Return a Boolean indicating whether the thread is stopped.
3352@end defun
3353
3354@defun InferiorThread.is_running ()
3355Return a Boolean indicating whether the thread is running.
3356@end defun
3357
3358@defun InferiorThread.is_exited ()
3359Return a Boolean indicating whether the thread is exited.
3360@end defun
3361
c369f8f0
KB
3362@defun InferiorThread.handle ()
3363Return the thread object's handle, represented as a Python @code{bytes}
3364object. A @code{gdb.Value} representation of the handle may be
3365constructed via @code{gdb.Value(bufobj, type)} where @var{bufobj} is
3366the Python @code{bytes} representation of the handle and @var{type} is
3367a @code{gdb.Type} for the handle type.
3368@end defun
3369
0a0faf9f
TW
3370@node Recordings In Python
3371@subsubsection Recordings In Python
3372@cindex recordings in python
3373
3374The following recordings-related functions
3375(@pxref{Process Record and Replay}) are available in the @code{gdb}
3376module:
3377
3378@defun gdb.start_recording (@r{[}method@r{]}, @r{[}format@r{]})
3379Start a recording using the given @var{method} and @var{format}. If
3380no @var{format} is given, the default format for the recording method
3381is used. If no @var{method} is given, the default method will be used.
3382Returns a @code{gdb.Record} object on success. Throw an exception on
3383failure.
3384
3385The following strings can be passed as @var{method}:
3386
3387@itemize @bullet
3388@item
3389@code{"full"}
3390@item
3391@code{"btrace"}: Possible values for @var{format}: @code{"pt"},
3392@code{"bts"} or leave out for default format.
3393@end itemize
3394@end defun
3395
3396@defun gdb.current_recording ()
3397Access a currently running recording. Return a @code{gdb.Record}
3398object on success. Return @code{None} if no recording is currently
3399active.
3400@end defun
3401
3402@defun gdb.stop_recording ()
3403Stop the current recording. Throw an exception if no recording is
3404currently active. All record objects become invalid after this call.
3405@end defun
3406
3407A @code{gdb.Record} object has the following attributes:
3408
0a0faf9f
TW
3409@defvar Record.method
3410A string with the current recording method, e.g.@: @code{full} or
3411@code{btrace}.
3412@end defvar
3413
3414@defvar Record.format
3415A string with the current recording format, e.g.@: @code{bt}, @code{pts} or
3416@code{None}.
3417@end defvar
3418
3419@defvar Record.begin
3420A method specific instruction object representing the first instruction
3421in this recording.
3422@end defvar
3423
3424@defvar Record.end
3425A method specific instruction object representing the current
3426instruction, that is not actually part of the recording.
3427@end defvar
3428
3429@defvar Record.replay_position
3430The instruction representing the current replay position. If there is
3431no replay active, this will be @code{None}.
3432@end defvar
3433
3434@defvar Record.instruction_history
3435A list with all recorded instructions.
3436@end defvar
3437
3438@defvar Record.function_call_history
3439A list with all recorded function call segments.
3440@end defvar
3441
3442A @code{gdb.Record} object has the following methods:
3443
3444@defun Record.goto (instruction)
3445Move the replay position to the given @var{instruction}.
3446@end defun
3447
d050f7d7
TW
3448The common @code{gdb.Instruction} class that recording method specific
3449instruction objects inherit from, has the following attributes:
0a0faf9f 3450
d050f7d7 3451@defvar Instruction.pc
913aeadd 3452An integer representing this instruction's address.
0a0faf9f
TW
3453@end defvar
3454
d050f7d7 3455@defvar Instruction.data
913aeadd
TW
3456A buffer with the raw instruction data. In Python 3, the return value is a
3457@code{memoryview} object.
0a0faf9f
TW
3458@end defvar
3459
d050f7d7 3460@defvar Instruction.decoded
913aeadd 3461A human readable string with the disassembled instruction.
0a0faf9f
TW
3462@end defvar
3463
d050f7d7 3464@defvar Instruction.size
913aeadd 3465The size of the instruction in bytes.
0a0faf9f
TW
3466@end defvar
3467
d050f7d7
TW
3468Additionally @code{gdb.RecordInstruction} has the following attributes:
3469
3470@defvar RecordInstruction.number
3471An integer identifying this instruction. @code{number} corresponds to
3472the numbers seen in @code{record instruction-history}
3473(@pxref{Process Record and Replay}).
3474@end defvar
3475
3476@defvar RecordInstruction.sal
3477A @code{gdb.Symtab_and_line} object representing the associated symtab
3478and line of this instruction. May be @code{None} if no debug information is
3479available.
3480@end defvar
3481
0ed5da75 3482@defvar RecordInstruction.is_speculative
d050f7d7 3483A boolean indicating whether the instruction was executed speculatively.
913aeadd
TW
3484@end defvar
3485
3486If an error occured during recording or decoding a recording, this error is
3487represented by a @code{gdb.RecordGap} object in the instruction list. It has
3488the following attributes:
3489
3490@defvar RecordGap.number
3491An integer identifying this gap. @code{number} corresponds to the numbers seen
3492in @code{record instruction-history} (@pxref{Process Record and Replay}).
3493@end defvar
3494
3495@defvar RecordGap.error_code
3496A numerical representation of the reason for the gap. The value is specific to
3497the current recording method.
3498@end defvar
3499
3500@defvar RecordGap.error_string
3501A human readable string with the reason for the gap.
0a0faf9f
TW
3502@end defvar
3503
14f819c8 3504A @code{gdb.RecordFunctionSegment} object has the following attributes:
0a0faf9f 3505
14f819c8
TW
3506@defvar RecordFunctionSegment.number
3507An integer identifying this function segment. @code{number} corresponds to
0a0faf9f
TW
3508the numbers seen in @code{record function-call-history}
3509(@pxref{Process Record and Replay}).
3510@end defvar
3511
14f819c8 3512@defvar RecordFunctionSegment.symbol
0a0faf9f 3513A @code{gdb.Symbol} object representing the associated symbol. May be
14f819c8 3514@code{None} if no debug information is available.
0a0faf9f
TW
3515@end defvar
3516
14f819c8 3517@defvar RecordFunctionSegment.level
0a0faf9f
TW
3518An integer representing the function call's stack level. May be
3519@code{None} if the function call is a gap.
3520@end defvar
3521
14f819c8 3522@defvar RecordFunctionSegment.instructions
0ed5da75 3523A list of @code{gdb.RecordInstruction} or @code{gdb.RecordGap} objects
913aeadd 3524associated with this function call.
0a0faf9f
TW
3525@end defvar
3526
14f819c8
TW
3527@defvar RecordFunctionSegment.up
3528A @code{gdb.RecordFunctionSegment} object representing the caller's
0a0faf9f
TW
3529function segment. If the call has not been recorded, this will be the
3530function segment to which control returns. If neither the call nor the
3531return have been recorded, this will be @code{None}.
3532@end defvar
3533
14f819c8
TW
3534@defvar RecordFunctionSegment.prev
3535A @code{gdb.RecordFunctionSegment} object representing the previous
0a0faf9f
TW
3536segment of this function call. May be @code{None}.
3537@end defvar
3538
14f819c8
TW
3539@defvar RecordFunctionSegment.next
3540A @code{gdb.RecordFunctionSegment} object representing the next segment of
0a0faf9f
TW
3541this function call. May be @code{None}.
3542@end defvar
3543
3544The following example demonstrates the usage of these objects and
3545functions to create a function that will rewind a record to the last
3546time a function in a different file was executed. This would typically
3547be used to track the execution of user provided callback functions in a
3548library which typically are not visible in a back trace.
3549
3550@smallexample
3551def bringback ():
3552 rec = gdb.current_recording ()
3553 if not rec:
3554 return
3555
3556 insn = rec.instruction_history
3557 if len (insn) == 0:
3558 return
3559
3560 try:
3561 position = insn.index (rec.replay_position)
3562 except:
3563 position = -1
3564 try:
3565 filename = insn[position].sal.symtab.fullname ()
3566 except:
3567 filename = None
3568
3569 for i in reversed (insn[:position]):
3570 try:
3571 current = i.sal.symtab.fullname ()
3572 except:
3573 current = None
3574
3575 if filename == current:
3576 continue
3577
3578 rec.goto (i)
3579 return
3580@end smallexample
3581
3582Another possible application is to write a function that counts the
3583number of code executions in a given line range. This line range can
3584contain parts of functions or span across several functions and is not
3585limited to be contiguous.
3586
3587@smallexample
3588def countrange (filename, linerange):
3589 count = 0
3590
3591 def filter_only (file_name):
3592 for call in gdb.current_recording ().function_call_history:
3593 try:
3594 if file_name in call.symbol.symtab.fullname ():
3595 yield call
3596 except:
3597 pass
3598
3599 for c in filter_only (filename):
3600 for i in c.instructions:
3601 try:
3602 if i.sal.line in linerange:
3603 count += 1
3604 break;
3605 except:
3606 pass
3607
3608 return count
3609@end smallexample
3610
329baa95
DE
3611@node Commands In Python
3612@subsubsection Commands In Python
3613
3614@cindex commands in python
3615@cindex python commands
3616You can implement new @value{GDBN} CLI commands in Python. A CLI
3617command is implemented using an instance of the @code{gdb.Command}
3618class, most commonly using a subclass.
3619
3620@defun Command.__init__ (name, @var{command_class} @r{[}, @var{completer_class} @r{[}, @var{prefix}@r{]]})
3621The object initializer for @code{Command} registers the new command
3622with @value{GDBN}. This initializer is normally invoked from the
3623subclass' own @code{__init__} method.
3624
3625@var{name} is the name of the command. If @var{name} consists of
3626multiple words, then the initial words are looked for as prefix
3627commands. In this case, if one of the prefix commands does not exist,
3628an exception is raised.
3629
3630There is no support for multi-line commands.
3631
3632@var{command_class} should be one of the @samp{COMMAND_} constants
3633defined below. This argument tells @value{GDBN} how to categorize the
3634new command in the help system.
3635
3636@var{completer_class} is an optional argument. If given, it should be
3637one of the @samp{COMPLETE_} constants defined below. This argument
3638tells @value{GDBN} how to perform completion for this command. If not
3639given, @value{GDBN} will attempt to complete using the object's
3640@code{complete} method (see below); if no such method is found, an
3641error will occur when completion is attempted.
3642
3643@var{prefix} is an optional argument. If @code{True}, then the new
3644command is a prefix command; sub-commands of this command may be
3645registered.
3646
3647The help text for the new command is taken from the Python
3648documentation string for the command's class, if there is one. If no
3649documentation string is provided, the default value ``This command is
3650not documented.'' is used.
3651@end defun
3652
3653@cindex don't repeat Python command
3654@defun Command.dont_repeat ()
3655By default, a @value{GDBN} command is repeated when the user enters a
3656blank line at the command prompt. A command can suppress this
3657behavior by invoking the @code{dont_repeat} method. This is similar
3658to the user command @code{dont-repeat}, see @ref{Define, dont-repeat}.
3659@end defun
3660
3661@defun Command.invoke (argument, from_tty)
3662This method is called by @value{GDBN} when this command is invoked.
3663
3664@var{argument} is a string. It is the argument to the command, after
3665leading and trailing whitespace has been stripped.
3666
3667@var{from_tty} is a boolean argument. When true, this means that the
3668command was entered by the user at the terminal; when false it means
3669that the command came from elsewhere.
3670
3671If this method throws an exception, it is turned into a @value{GDBN}
3672@code{error} call. Otherwise, the return value is ignored.
3673
3674@findex gdb.string_to_argv
3675To break @var{argument} up into an argv-like string use
3676@code{gdb.string_to_argv}. This function behaves identically to
3677@value{GDBN}'s internal argument lexer @code{buildargv}.
3678It is recommended to use this for consistency.
3679Arguments are separated by spaces and may be quoted.
3680Example:
3681
3682@smallexample
3683print gdb.string_to_argv ("1 2\ \\\"3 '4 \"5' \"6 '7\"")
3684['1', '2 "3', '4 "5', "6 '7"]
3685@end smallexample
3686
3687@end defun
3688
3689@cindex completion of Python commands
3690@defun Command.complete (text, word)
3691This method is called by @value{GDBN} when the user attempts
3692completion on this command. All forms of completion are handled by
3693this method, that is, the @key{TAB} and @key{M-?} key bindings
3694(@pxref{Completion}), and the @code{complete} command (@pxref{Help,
3695complete}).
3696
697aa1b7
EZ
3697The arguments @var{text} and @var{word} are both strings; @var{text}
3698holds the complete command line up to the cursor's location, while
329baa95
DE
3699@var{word} holds the last word of the command line; this is computed
3700using a word-breaking heuristic.
3701
3702The @code{complete} method can return several values:
3703@itemize @bullet
3704@item
3705If the return value is a sequence, the contents of the sequence are
3706used as the completions. It is up to @code{complete} to ensure that the
3707contents actually do complete the word. A zero-length sequence is
3708allowed, it means that there were no completions available. Only
3709string elements of the sequence are used; other elements in the
3710sequence are ignored.
3711
3712@item
3713If the return value is one of the @samp{COMPLETE_} constants defined
3714below, then the corresponding @value{GDBN}-internal completion
3715function is invoked, and its result is used.
3716
3717@item
3718All other results are treated as though there were no available
3719completions.
3720@end itemize
3721@end defun
3722
3723When a new command is registered, it must be declared as a member of
3724some general class of commands. This is used to classify top-level
3725commands in the on-line help system; note that prefix commands are not
3726listed under their own category but rather that of their top-level
3727command. The available classifications are represented by constants
3728defined in the @code{gdb} module:
3729
3730@table @code
3731@findex COMMAND_NONE
3732@findex gdb.COMMAND_NONE
3733@item gdb.COMMAND_NONE
3734The command does not belong to any particular class. A command in
3735this category will not be displayed in any of the help categories.
3736
3737@findex COMMAND_RUNNING
3738@findex gdb.COMMAND_RUNNING
3739@item gdb.COMMAND_RUNNING
3740The command is related to running the inferior. For example,
3741@code{start}, @code{step}, and @code{continue} are in this category.
3742Type @kbd{help running} at the @value{GDBN} prompt to see a list of
3743commands in this category.
3744
3745@findex COMMAND_DATA
3746@findex gdb.COMMAND_DATA
3747@item gdb.COMMAND_DATA
3748The command is related to data or variables. For example,
3749@code{call}, @code{find}, and @code{print} are in this category. Type
3750@kbd{help data} at the @value{GDBN} prompt to see a list of commands
3751in this category.
3752
3753@findex COMMAND_STACK
3754@findex gdb.COMMAND_STACK
3755@item gdb.COMMAND_STACK
3756The command has to do with manipulation of the stack. For example,
3757@code{backtrace}, @code{frame}, and @code{return} are in this
3758category. Type @kbd{help stack} at the @value{GDBN} prompt to see a
3759list of commands in this category.
3760
3761@findex COMMAND_FILES
3762@findex gdb.COMMAND_FILES
3763@item gdb.COMMAND_FILES
3764This class is used for file-related commands. For example,
3765@code{file}, @code{list} and @code{section} are in this category.
3766Type @kbd{help files} at the @value{GDBN} prompt to see a list of
3767commands in this category.
3768
3769@findex COMMAND_SUPPORT
3770@findex gdb.COMMAND_SUPPORT
3771@item gdb.COMMAND_SUPPORT
3772This should be used for ``support facilities'', generally meaning
3773things that are useful to the user when interacting with @value{GDBN},
3774but not related to the state of the inferior. For example,
3775@code{help}, @code{make}, and @code{shell} are in this category. Type
3776@kbd{help support} at the @value{GDBN} prompt to see a list of
3777commands in this category.
3778
3779@findex COMMAND_STATUS
3780@findex gdb.COMMAND_STATUS
3781@item gdb.COMMAND_STATUS
3782The command is an @samp{info}-related command, that is, related to the
3783state of @value{GDBN} itself. For example, @code{info}, @code{macro},
3784and @code{show} are in this category. Type @kbd{help status} at the
3785@value{GDBN} prompt to see a list of commands in this category.
3786
3787@findex COMMAND_BREAKPOINTS
3788@findex gdb.COMMAND_BREAKPOINTS
3789@item gdb.COMMAND_BREAKPOINTS
3790The command has to do with breakpoints. For example, @code{break},
3791@code{clear}, and @code{delete} are in this category. Type @kbd{help
3792breakpoints} at the @value{GDBN} prompt to see a list of commands in
3793this category.
3794
3795@findex COMMAND_TRACEPOINTS
3796@findex gdb.COMMAND_TRACEPOINTS
3797@item gdb.COMMAND_TRACEPOINTS
3798The command has to do with tracepoints. For example, @code{trace},
3799@code{actions}, and @code{tfind} are in this category. Type
3800@kbd{help tracepoints} at the @value{GDBN} prompt to see a list of
3801commands in this category.
3802
3803@findex COMMAND_USER
3804@findex gdb.COMMAND_USER
3805@item gdb.COMMAND_USER
3806The command is a general purpose command for the user, and typically
3807does not fit in one of the other categories.
3808Type @kbd{help user-defined} at the @value{GDBN} prompt to see
3809a list of commands in this category, as well as the list of gdb macros
3810(@pxref{Sequences}).
3811
3812@findex COMMAND_OBSCURE
3813@findex gdb.COMMAND_OBSCURE
3814@item gdb.COMMAND_OBSCURE
3815The command is only used in unusual circumstances, or is not of
3816general interest to users. For example, @code{checkpoint},
3817@code{fork}, and @code{stop} are in this category. Type @kbd{help
3818obscure} at the @value{GDBN} prompt to see a list of commands in this
3819category.
3820
3821@findex COMMAND_MAINTENANCE
3822@findex gdb.COMMAND_MAINTENANCE
3823@item gdb.COMMAND_MAINTENANCE
3824The command is only useful to @value{GDBN} maintainers. The
3825@code{maintenance} and @code{flushregs} commands are in this category.
3826Type @kbd{help internals} at the @value{GDBN} prompt to see a list of
3827commands in this category.
3828@end table
3829
3830A new command can use a predefined completion function, either by
3831specifying it via an argument at initialization, or by returning it
3832from the @code{complete} method. These predefined completion
3833constants are all defined in the @code{gdb} module:
3834
b3ce5e5f
DE
3835@vtable @code
3836@vindex COMPLETE_NONE
329baa95
DE
3837@item gdb.COMPLETE_NONE
3838This constant means that no completion should be done.
3839
b3ce5e5f 3840@vindex COMPLETE_FILENAME
329baa95
DE
3841@item gdb.COMPLETE_FILENAME
3842This constant means that filename completion should be performed.
3843
b3ce5e5f 3844@vindex COMPLETE_LOCATION
329baa95
DE
3845@item gdb.COMPLETE_LOCATION
3846This constant means that location completion should be done.
3847@xref{Specify Location}.
3848
b3ce5e5f 3849@vindex COMPLETE_COMMAND
329baa95
DE
3850@item gdb.COMPLETE_COMMAND
3851This constant means that completion should examine @value{GDBN}
3852command names.
3853
b3ce5e5f 3854@vindex COMPLETE_SYMBOL
329baa95
DE
3855@item gdb.COMPLETE_SYMBOL
3856This constant means that completion should be done using symbol names
3857as the source.
3858
b3ce5e5f 3859@vindex COMPLETE_EXPRESSION
329baa95
DE
3860@item gdb.COMPLETE_EXPRESSION
3861This constant means that completion should be done on expressions.
3862Often this means completing on symbol names, but some language
3863parsers also have support for completing on field names.
b3ce5e5f 3864@end vtable
329baa95
DE
3865
3866The following code snippet shows how a trivial CLI command can be
3867implemented in Python:
3868
3869@smallexample
3870class HelloWorld (gdb.Command):
3871 """Greet the whole world."""
3872
3873 def __init__ (self):
3874 super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
3875
3876 def invoke (self, arg, from_tty):
3877 print "Hello, World!"
3878
3879HelloWorld ()
3880@end smallexample
3881
3882The last line instantiates the class, and is necessary to trigger the
3883registration of the command with @value{GDBN}. Depending on how the
3884Python code is read into @value{GDBN}, you may need to import the
3885@code{gdb} module explicitly.
3886
3887@node Parameters In Python
3888@subsubsection Parameters In Python
3889
3890@cindex parameters in python
3891@cindex python parameters
3892@tindex gdb.Parameter
3893@tindex Parameter
3894You can implement new @value{GDBN} parameters using Python. A new
3895parameter is implemented as an instance of the @code{gdb.Parameter}
3896class.
3897
3898Parameters are exposed to the user via the @code{set} and
3899@code{show} commands. @xref{Help}.
3900
3901There are many parameters that already exist and can be set in
3902@value{GDBN}. Two examples are: @code{set follow fork} and
3903@code{set charset}. Setting these parameters influences certain
3904behavior in @value{GDBN}. Similarly, you can define parameters that
3905can be used to influence behavior in custom Python scripts and commands.
3906
3907@defun Parameter.__init__ (name, @var{command-class}, @var{parameter-class} @r{[}, @var{enum-sequence}@r{]})
3908The object initializer for @code{Parameter} registers the new
3909parameter with @value{GDBN}. This initializer is normally invoked
3910from the subclass' own @code{__init__} method.
3911
3912@var{name} is the name of the new parameter. If @var{name} consists
3913of multiple words, then the initial words are looked for as prefix
3914parameters. An example of this can be illustrated with the
3915@code{set print} set of parameters. If @var{name} is
3916@code{print foo}, then @code{print} will be searched as the prefix
3917parameter. In this case the parameter can subsequently be accessed in
3918@value{GDBN} as @code{set print foo}.
3919
3920If @var{name} consists of multiple words, and no prefix parameter group
3921can be found, an exception is raised.
3922
3923@var{command-class} should be one of the @samp{COMMAND_} constants
3924(@pxref{Commands In Python}). This argument tells @value{GDBN} how to
3925categorize the new parameter in the help system.
3926
3927@var{parameter-class} should be one of the @samp{PARAM_} constants
3928defined below. This argument tells @value{GDBN} the type of the new
3929parameter; this information is used for input validation and
3930completion.
3931
3932If @var{parameter-class} is @code{PARAM_ENUM}, then
3933@var{enum-sequence} must be a sequence of strings. These strings
3934represent the possible values for the parameter.
3935
3936If @var{parameter-class} is not @code{PARAM_ENUM}, then the presence
3937of a fourth argument will cause an exception to be thrown.
3938
3939The help text for the new parameter is taken from the Python
3940documentation string for the parameter's class, if there is one. If
3941there is no documentation string, a default value is used.
3942@end defun
3943
3944@defvar Parameter.set_doc
3945If this attribute exists, and is a string, then its value is used as
3946the help text for this parameter's @code{set} command. The value is
3947examined when @code{Parameter.__init__} is invoked; subsequent changes
3948have no effect.
3949@end defvar
3950
3951@defvar Parameter.show_doc
3952If this attribute exists, and is a string, then its value is used as
3953the help text for this parameter's @code{show} command. The value is
3954examined when @code{Parameter.__init__} is invoked; subsequent changes
3955have no effect.
3956@end defvar
3957
3958@defvar Parameter.value
3959The @code{value} attribute holds the underlying value of the
3960parameter. It can be read and assigned to just as any other
3961attribute. @value{GDBN} does validation when assignments are made.
3962@end defvar
3963
984ee559
TT
3964There are two methods that may be implemented in any @code{Parameter}
3965class. These are:
329baa95
DE
3966
3967@defun Parameter.get_set_string (self)
984ee559
TT
3968If this method exists, @value{GDBN} will call it when a
3969@var{parameter}'s value has been changed via the @code{set} API (for
3970example, @kbd{set foo off}). The @code{value} attribute has already
3971been populated with the new value and may be used in output. This
3972method must return a string. If the returned string is not empty,
3973@value{GDBN} will present it to the user.
ae778caf
TT
3974
3975If this method raises the @code{gdb.GdbError} exception
3976(@pxref{Exception Handling}), then @value{GDBN} will print the
3977exception's string and the @code{set} command will fail. Note,
3978however, that the @code{value} attribute will not be reset in this
3979case. So, if your parameter must validate values, it should store the
3980old value internally and reset the exposed value, like so:
3981
3982@smallexample
3983class ExampleParam (gdb.Parameter):
3984 def __init__ (self, name):
3985 super (ExampleParam, self).__init__ (name,
3986 gdb.COMMAND_DATA,
3987 gdb.PARAM_BOOLEAN)
3988 self.value = True
3989 self.saved_value = True
3990 def validate(self):
3991 return False
3992 def get_set_string (self):
3993 if not self.validate():
3994 self.value = self.saved_value
3995 raise gdb.GdbError('Failed to validate')
3996 self.saved_value = self.value
3997@end smallexample
329baa95
DE
3998@end defun
3999
4000@defun Parameter.get_show_string (self, svalue)
4001@value{GDBN} will call this method when a @var{parameter}'s
4002@code{show} API has been invoked (for example, @kbd{show foo}). The
4003argument @code{svalue} receives the string representation of the
4004current value. This method must return a string.
4005@end defun
4006
4007When a new parameter is defined, its type must be specified. The
4008available types are represented by constants defined in the @code{gdb}
4009module:
4010
4011@table @code
4012@findex PARAM_BOOLEAN
4013@findex gdb.PARAM_BOOLEAN
4014@item gdb.PARAM_BOOLEAN
4015The value is a plain boolean. The Python boolean values, @code{True}
4016and @code{False} are the only valid values.
4017
4018@findex PARAM_AUTO_BOOLEAN
4019@findex gdb.PARAM_AUTO_BOOLEAN
4020@item gdb.PARAM_AUTO_BOOLEAN
4021The value has three possible states: true, false, and @samp{auto}. In
4022Python, true and false are represented using boolean constants, and
4023@samp{auto} is represented using @code{None}.
4024
4025@findex PARAM_UINTEGER
4026@findex gdb.PARAM_UINTEGER
4027@item gdb.PARAM_UINTEGER
4028The value is an unsigned integer. The value of 0 should be
4029interpreted to mean ``unlimited''.
4030
4031@findex PARAM_INTEGER
4032@findex gdb.PARAM_INTEGER
4033@item gdb.PARAM_INTEGER
4034The value is a signed integer. The value of 0 should be interpreted
4035to mean ``unlimited''.
4036
4037@findex PARAM_STRING
4038@findex gdb.PARAM_STRING
4039@item gdb.PARAM_STRING
4040The value is a string. When the user modifies the string, any escape
4041sequences, such as @samp{\t}, @samp{\f}, and octal escapes, are
4042translated into corresponding characters and encoded into the current
4043host charset.
4044
4045@findex PARAM_STRING_NOESCAPE
4046@findex gdb.PARAM_STRING_NOESCAPE
4047@item gdb.PARAM_STRING_NOESCAPE
4048The value is a string. When the user modifies the string, escapes are
4049passed through untranslated.
4050
4051@findex PARAM_OPTIONAL_FILENAME
4052@findex gdb.PARAM_OPTIONAL_FILENAME
4053@item gdb.PARAM_OPTIONAL_FILENAME
4054The value is a either a filename (a string), or @code{None}.
4055
4056@findex PARAM_FILENAME
4057@findex gdb.PARAM_FILENAME
4058@item gdb.PARAM_FILENAME
4059The value is a filename. This is just like
4060@code{PARAM_STRING_NOESCAPE}, but uses file names for completion.
4061
4062@findex PARAM_ZINTEGER
4063@findex gdb.PARAM_ZINTEGER
4064@item gdb.PARAM_ZINTEGER
4065The value is an integer. This is like @code{PARAM_INTEGER}, except 0
4066is interpreted as itself.
4067
0489430a
TT
4068@findex PARAM_ZUINTEGER
4069@findex gdb.PARAM_ZUINTEGER
4070@item gdb.PARAM_ZUINTEGER
4071The value is an unsigned integer. This is like @code{PARAM_INTEGER},
4072except 0 is interpreted as itself, and the value cannot be negative.
4073
4074@findex PARAM_ZUINTEGER_UNLIMITED
4075@findex gdb.PARAM_ZUINTEGER_UNLIMITED
4076@item gdb.PARAM_ZUINTEGER_UNLIMITED
4077The value is a signed integer. This is like @code{PARAM_ZUINTEGER},
4078except the special value -1 should be interpreted to mean
4079``unlimited''. Other negative values are not allowed.
4080
329baa95
DE
4081@findex PARAM_ENUM
4082@findex gdb.PARAM_ENUM
4083@item gdb.PARAM_ENUM
4084The value is a string, which must be one of a collection string
4085constants provided when the parameter is created.
4086@end table
4087
4088@node Functions In Python
4089@subsubsection Writing new convenience functions
4090
4091@cindex writing convenience functions
4092@cindex convenience functions in python
4093@cindex python convenience functions
4094@tindex gdb.Function
4095@tindex Function
4096You can implement new convenience functions (@pxref{Convenience Vars})
4097in Python. A convenience function is an instance of a subclass of the
4098class @code{gdb.Function}.
4099
4100@defun Function.__init__ (name)
4101The initializer for @code{Function} registers the new function with
4102@value{GDBN}. The argument @var{name} is the name of the function,
4103a string. The function will be visible to the user as a convenience
4104variable of type @code{internal function}, whose name is the same as
4105the given @var{name}.
4106
4107The documentation for the new function is taken from the documentation
4108string for the new class.
4109@end defun
4110
4111@defun Function.invoke (@var{*args})
4112When a convenience function is evaluated, its arguments are converted
4113to instances of @code{gdb.Value}, and then the function's
4114@code{invoke} method is called. Note that @value{GDBN} does not
4115predetermine the arity of convenience functions. Instead, all
4116available arguments are passed to @code{invoke}, following the
4117standard Python calling convention. In particular, a convenience
4118function can have default values for parameters without ill effect.
4119
4120The return value of this method is used as its value in the enclosing
4121expression. If an ordinary Python value is returned, it is converted
4122to a @code{gdb.Value} following the usual rules.
4123@end defun
4124
4125The following code snippet shows how a trivial convenience function can
4126be implemented in Python:
4127
4128@smallexample
4129class Greet (gdb.Function):
4130 """Return string to greet someone.
4131Takes a name as argument."""
4132
4133 def __init__ (self):
4134 super (Greet, self).__init__ ("greet")
4135
4136 def invoke (self, name):
4137 return "Hello, %s!" % name.string ()
4138
4139Greet ()
4140@end smallexample
4141
4142The last line instantiates the class, and is necessary to trigger the
4143registration of the function with @value{GDBN}. Depending on how the
4144Python code is read into @value{GDBN}, you may need to import the
4145@code{gdb} module explicitly.
4146
4147Now you can use the function in an expression:
4148
4149@smallexample
4150(gdb) print $greet("Bob")
4151$1 = "Hello, Bob!"
4152@end smallexample
4153
4154@node Progspaces In Python
4155@subsubsection Program Spaces In Python
4156
4157@cindex progspaces in python
4158@tindex gdb.Progspace
4159@tindex Progspace
4160A program space, or @dfn{progspace}, represents a symbolic view
4161of an address space.
4162It consists of all of the objfiles of the program.
4163@xref{Objfiles In Python}.
65c574f6 4164@xref{Inferiors Connections and Programs, program spaces}, for more details
329baa95
DE
4165about program spaces.
4166
4167The following progspace-related functions are available in the
4168@code{gdb} module:
4169
4170@findex gdb.current_progspace
4171@defun gdb.current_progspace ()
4172This function returns the program space of the currently selected inferior.
65c574f6 4173@xref{Inferiors Connections and Programs}. This is identical to
a40bf0c2
SM
4174@code{gdb.selected_inferior().progspace} (@pxref{Inferiors In Python}) and is
4175included for historical compatibility.
329baa95
DE
4176@end defun
4177
4178@findex gdb.progspaces
4179@defun gdb.progspaces ()
4180Return a sequence of all the progspaces currently known to @value{GDBN}.
4181@end defun
4182
4183Each progspace is represented by an instance of the @code{gdb.Progspace}
4184class.
4185
4186@defvar Progspace.filename
4187The file name of the progspace as a string.
4188@end defvar
4189
4190@defvar Progspace.pretty_printers
4191The @code{pretty_printers} attribute is a list of functions. It is
4192used to look up pretty-printers. A @code{Value} is passed to each
4193function in order; if the function returns @code{None}, then the
4194search continues. Otherwise, the return value should be an object
4195which is used to format the value. @xref{Pretty Printing API}, for more
4196information.
4197@end defvar
4198
4199@defvar Progspace.type_printers
4200The @code{type_printers} attribute is a list of type printer objects.
4201@xref{Type Printing API}, for more information.
4202@end defvar
4203
4204@defvar Progspace.frame_filters
4205The @code{frame_filters} attribute is a dictionary of frame filter
4206objects. @xref{Frame Filter API}, for more information.
4207@end defvar
4208
8743a9cd
TT
4209A program space has the following methods:
4210
4211@findex Progspace.block_for_pc
4212@defun Progspace.block_for_pc (pc)
4213Return the innermost @code{gdb.Block} containing the given @var{pc}
4214value. If the block cannot be found for the @var{pc} value specified,
4215the function will return @code{None}.
4216@end defun
4217
4218@findex Progspace.find_pc_line
4219@defun Progspace.find_pc_line (pc)
4220Return the @code{gdb.Symtab_and_line} object corresponding to the
4221@var{pc} value. @xref{Symbol Tables In Python}. If an invalid value
4222of @var{pc} is passed as an argument, then the @code{symtab} and
4223@code{line} attributes of the returned @code{gdb.Symtab_and_line}
4224object will be @code{None} and 0 respectively.
4225@end defun
4226
4227@findex Progspace.is_valid
4228@defun Progspace.is_valid ()
4229Returns @code{True} if the @code{gdb.Progspace} object is valid,
4230@code{False} if not. A @code{gdb.Progspace} object can become invalid
4231if the program space file it refers to is not referenced by any
4232inferior. All other @code{gdb.Progspace} methods will throw an
4233exception if it is invalid at the time the method is called.
4234@end defun
4235
4236@findex Progspace.objfiles
4237@defun Progspace.objfiles ()
4238Return a sequence of all the objfiles referenced by this program
4239space. @xref{Objfiles In Python}.
4240@end defun
4241
4242@findex Progspace.solib_name
4243@defun Progspace.solib_name (address)
4244Return the name of the shared library holding the given @var{address}
4245as a string, or @code{None}.
4246@end defun
4247
02be9a71
DE
4248One may add arbitrary attributes to @code{gdb.Progspace} objects
4249in the usual Python way.
4250This is useful if, for example, one needs to do some extra record keeping
4251associated with the program space.
4252
4253In this contrived example, we want to perform some processing when
4254an objfile with a certain symbol is loaded, but we only want to do
4255this once because it is expensive. To achieve this we record the results
4256with the program space because we can't predict when the desired objfile
4257will be loaded.
4258
4259@smallexample
4260(gdb) python
4261def clear_objfiles_handler(event):
4262 event.progspace.expensive_computation = None
4263def expensive(symbol):
4264 """A mock routine to perform an "expensive" computation on symbol."""
4265 print "Computing the answer to the ultimate question ..."
4266 return 42
4267def new_objfile_handler(event):
4268 objfile = event.new_objfile
4269 progspace = objfile.progspace
4270 if not hasattr(progspace, 'expensive_computation') or \
4271 progspace.expensive_computation is None:
4272 # We use 'main' for the symbol to keep the example simple.
4273 # Note: There's no current way to constrain the lookup
4274 # to one objfile.
4275 symbol = gdb.lookup_global_symbol('main')
4276 if symbol is not None:
4277 progspace.expensive_computation = expensive(symbol)
4278gdb.events.clear_objfiles.connect(clear_objfiles_handler)
4279gdb.events.new_objfile.connect(new_objfile_handler)
4280end
4281(gdb) file /tmp/hello
4282Reading symbols from /tmp/hello...done.
4283Computing the answer to the ultimate question ...
4284(gdb) python print gdb.current_progspace().expensive_computation
428542
4286(gdb) run
4287Starting program: /tmp/hello
4288Hello.
4289[Inferior 1 (process 4242) exited normally]
4290@end smallexample
4291
329baa95
DE
4292@node Objfiles In Python
4293@subsubsection Objfiles In Python
4294
4295@cindex objfiles in python
4296@tindex gdb.Objfile
4297@tindex Objfile
4298@value{GDBN} loads symbols for an inferior from various
4299symbol-containing files (@pxref{Files}). These include the primary
4300executable file, any shared libraries used by the inferior, and any
4301separate debug info files (@pxref{Separate Debug Files}).
4302@value{GDBN} calls these symbol-containing files @dfn{objfiles}.
4303
4304The following objfile-related functions are available in the
4305@code{gdb} module:
4306
4307@findex gdb.current_objfile
4308@defun gdb.current_objfile ()
4309When auto-loading a Python script (@pxref{Python Auto-loading}), @value{GDBN}
4310sets the ``current objfile'' to the corresponding objfile. This
4311function returns the current objfile. If there is no current objfile,
4312this function returns @code{None}.
4313@end defun
4314
4315@findex gdb.objfiles
4316@defun gdb.objfiles ()
74d3fbbb
SM
4317Return a sequence of objfiles referenced by the current program space.
4318@xref{Objfiles In Python}, and @ref{Progspaces In Python}. This is identical
4319to @code{gdb.selected_inferior().progspace.objfiles()} and is included for
4320historical compatibility.
329baa95
DE
4321@end defun
4322
6dddd6a5
DE
4323@findex gdb.lookup_objfile
4324@defun gdb.lookup_objfile (name @r{[}, by_build_id{]})
4325Look up @var{name}, a file name or build ID, in the list of objfiles
4326for the current program space (@pxref{Progspaces In Python}).
4327If the objfile is not found throw the Python @code{ValueError} exception.
4328
4329If @var{name} is a relative file name, then it will match any
4330source file name with the same trailing components. For example, if
4331@var{name} is @samp{gcc/expr.c}, then it will match source file
4332name of @file{/build/trunk/gcc/expr.c}, but not
4333@file{/build/trunk/libcpp/expr.c} or @file{/build/trunk/gcc/x-expr.c}.
4334
4335If @var{by_build_id} is provided and is @code{True} then @var{name}
4336is the build ID of the objfile. Otherwise, @var{name} is a file name.
4337This is supported only on some operating systems, notably those which use
4338the ELF format for binary files and the @sc{gnu} Binutils. For more details
4339about this feature, see the description of the @option{--build-id}
f5a476a7 4340command-line option in @ref{Options, , Command Line Options, ld,
6dddd6a5
DE
4341The GNU Linker}.
4342@end defun
4343
329baa95
DE
4344Each objfile is represented by an instance of the @code{gdb.Objfile}
4345class.
4346
4347@defvar Objfile.filename
1b549396
DE
4348The file name of the objfile as a string, with symbolic links resolved.
4349
4350The value is @code{None} if the objfile is no longer valid.
4351See the @code{gdb.Objfile.is_valid} method, described below.
329baa95
DE
4352@end defvar
4353
3a8b707a
DE
4354@defvar Objfile.username
4355The file name of the objfile as specified by the user as a string.
4356
4357The value is @code{None} if the objfile is no longer valid.
4358See the @code{gdb.Objfile.is_valid} method, described below.
4359@end defvar
4360
a0be3e44
DE
4361@defvar Objfile.owner
4362For separate debug info objfiles this is the corresponding @code{gdb.Objfile}
4363object that debug info is being provided for.
4364Otherwise this is @code{None}.
4365Separate debug info objfiles are added with the
4366@code{gdb.Objfile.add_separate_debug_file} method, described below.
4367@end defvar
4368
7c50a931
DE
4369@defvar Objfile.build_id
4370The build ID of the objfile as a string.
4371If the objfile does not have a build ID then the value is @code{None}.
4372
4373This is supported only on some operating systems, notably those which use
4374the ELF format for binary files and the @sc{gnu} Binutils. For more details
4375about this feature, see the description of the @option{--build-id}
f5a476a7 4376command-line option in @ref{Options, , Command Line Options, ld,
7c50a931
DE
4377The GNU Linker}.
4378@end defvar
4379
d096d8c1
DE
4380@defvar Objfile.progspace
4381The containing program space of the objfile as a @code{gdb.Progspace}
4382object. @xref{Progspaces In Python}.
4383@end defvar
4384
329baa95
DE
4385@defvar Objfile.pretty_printers
4386The @code{pretty_printers} attribute is a list of functions. It is
4387used to look up pretty-printers. A @code{Value} is passed to each
4388function in order; if the function returns @code{None}, then the
4389search continues. Otherwise, the return value should be an object
4390which is used to format the value. @xref{Pretty Printing API}, for more
4391information.
4392@end defvar
4393
4394@defvar Objfile.type_printers
4395The @code{type_printers} attribute is a list of type printer objects.
4396@xref{Type Printing API}, for more information.
4397@end defvar
4398
4399@defvar Objfile.frame_filters
4400The @code{frame_filters} attribute is a dictionary of frame filter
4401objects. @xref{Frame Filter API}, for more information.
4402@end defvar
4403
02be9a71
DE
4404One may add arbitrary attributes to @code{gdb.Objfile} objects
4405in the usual Python way.
4406This is useful if, for example, one needs to do some extra record keeping
4407associated with the objfile.
4408
4409In this contrived example we record the time when @value{GDBN}
4410loaded the objfile.
4411
4412@smallexample
4413(gdb) python
4414import datetime
4415def new_objfile_handler(event):
4416 # Set the time_loaded attribute of the new objfile.
4417 event.new_objfile.time_loaded = datetime.datetime.today()
4418gdb.events.new_objfile.connect(new_objfile_handler)
4419end
4420(gdb) file ./hello
4421Reading symbols from ./hello...done.
4422(gdb) python print gdb.objfiles()[0].time_loaded
44232014-10-09 11:41:36.770345
4424@end smallexample
4425
329baa95
DE
4426A @code{gdb.Objfile} object has the following methods:
4427
4428@defun Objfile.is_valid ()
4429Returns @code{True} if the @code{gdb.Objfile} object is valid,
4430@code{False} if not. A @code{gdb.Objfile} object can become invalid
4431if the object file it refers to is not loaded in @value{GDBN} any
4432longer. All other @code{gdb.Objfile} methods will throw an exception
4433if it is invalid at the time the method is called.
4434@end defun
4435
86e4ed39
DE
4436@defun Objfile.add_separate_debug_file (file)
4437Add @var{file} to the list of files that @value{GDBN} will search for
4438debug information for the objfile.
4439This is useful when the debug info has been removed from the program
4440and stored in a separate file. @value{GDBN} has built-in support for
4441finding separate debug info files (@pxref{Separate Debug Files}), but if
4442the file doesn't live in one of the standard places that @value{GDBN}
4443searches then this function can be used to add a debug info file
4444from a different place.
4445@end defun
4446
c620ed88
CB
4447@defun Objfile.lookup_global_symbol (name @r{[}, domain@r{]})
4448Search for a global symbol named @var{name} in this objfile. Optionally, the
4449search scope can be restricted with the @var{domain} argument.
4450The @var{domain} argument must be a domain constant defined in the @code{gdb}
4451module and described in @ref{Symbols In Python}. This function is similar to
4452@code{gdb.lookup_global_symbol}, except that the search is limited to this
4453objfile.
4454
4455The result is a @code{gdb.Symbol} object or @code{None} if the symbol
4456is not found.
4457@end defun
4458
4459@defun Objfile.lookup_static_symbol (name @r{[}, domain@r{]})
4460Like @code{Objfile.lookup_global_symbol}, but searches for a global
4461symbol with static linkage named @var{name} in this objfile.
4462@end defun
4463
329baa95 4464@node Frames In Python
849cba3b 4465@subsubsection Accessing inferior stack frames from Python
329baa95
DE
4466
4467@cindex frames in python
4468When the debugged program stops, @value{GDBN} is able to analyze its call
4469stack (@pxref{Frames,,Stack frames}). The @code{gdb.Frame} class
4470represents a frame in the stack. A @code{gdb.Frame} object is only valid
4471while its corresponding frame exists in the inferior's stack. If you try
4472to use an invalid frame object, @value{GDBN} will throw a @code{gdb.error}
4473exception (@pxref{Exception Handling}).
4474
4475Two @code{gdb.Frame} objects can be compared for equality with the @code{==}
4476operator, like:
4477
4478@smallexample
4479(@value{GDBP}) python print gdb.newest_frame() == gdb.selected_frame ()
4480True
4481@end smallexample
4482
4483The following frame-related functions are available in the @code{gdb} module:
4484
4485@findex gdb.selected_frame
4486@defun gdb.selected_frame ()
4487Return the selected frame object. (@pxref{Selection,,Selecting a Frame}).
4488@end defun
4489
4490@findex gdb.newest_frame
4491@defun gdb.newest_frame ()
4492Return the newest frame object for the selected thread.
4493@end defun
4494
4495@defun gdb.frame_stop_reason_string (reason)
4496Return a string explaining the reason why @value{GDBN} stopped unwinding
4497frames, as expressed by the given @var{reason} code (an integer, see the
4498@code{unwind_stop_reason} method further down in this section).
4499@end defun
4500
e0f3fd7c
TT
4501@findex gdb.invalidate_cached_frames
4502@defun gdb.invalidate_cached_frames
4503@value{GDBN} internally keeps a cache of the frames that have been
4504unwound. This function invalidates this cache.
4505
4506This function should not generally be called by ordinary Python code.
4507It is documented for the sake of completeness.
4508@end defun
4509
329baa95
DE
4510A @code{gdb.Frame} object has the following methods:
4511
4512@defun Frame.is_valid ()
4513Returns true if the @code{gdb.Frame} object is valid, false if not.
4514A frame object can become invalid if the frame it refers to doesn't
4515exist anymore in the inferior. All @code{gdb.Frame} methods will throw
4516an exception if it is invalid at the time the method is called.
4517@end defun
4518
4519@defun Frame.name ()
4520Returns the function name of the frame, or @code{None} if it can't be
4521obtained.
4522@end defun
4523
4524@defun Frame.architecture ()
4525Returns the @code{gdb.Architecture} object corresponding to the frame's
4526architecture. @xref{Architectures In Python}.
4527@end defun
4528
4529@defun Frame.type ()
4530Returns the type of the frame. The value can be one of:
4531@table @code
4532@item gdb.NORMAL_FRAME
4533An ordinary stack frame.
4534
4535@item gdb.DUMMY_FRAME
4536A fake stack frame that was created by @value{GDBN} when performing an
4537inferior function call.
4538
4539@item gdb.INLINE_FRAME
4540A frame representing an inlined function. The function was inlined
4541into a @code{gdb.NORMAL_FRAME} that is older than this one.
4542
4543@item gdb.TAILCALL_FRAME
4544A frame representing a tail call. @xref{Tail Call Frames}.
4545
4546@item gdb.SIGTRAMP_FRAME
4547A signal trampoline frame. This is the frame created by the OS when
4548it calls into a signal handler.
4549
4550@item gdb.ARCH_FRAME
4551A fake stack frame representing a cross-architecture call.
4552
4553@item gdb.SENTINEL_FRAME
4554This is like @code{gdb.NORMAL_FRAME}, but it is only used for the
4555newest frame.
4556@end table
4557@end defun
4558
4559@defun Frame.unwind_stop_reason ()
4560Return an integer representing the reason why it's not possible to find
4561more frames toward the outermost frame. Use
4562@code{gdb.frame_stop_reason_string} to convert the value returned by this
4563function to a string. The value can be one of:
4564
4565@table @code
4566@item gdb.FRAME_UNWIND_NO_REASON
4567No particular reason (older frames should be available).
4568
4569@item gdb.FRAME_UNWIND_NULL_ID
4570The previous frame's analyzer returns an invalid result. This is no
4571longer used by @value{GDBN}, and is kept only for backward
4572compatibility.
4573
4574@item gdb.FRAME_UNWIND_OUTERMOST
4575This frame is the outermost.
4576
4577@item gdb.FRAME_UNWIND_UNAVAILABLE
4578Cannot unwind further, because that would require knowing the
4579values of registers or memory that have not been collected.
4580
4581@item gdb.FRAME_UNWIND_INNER_ID
4582This frame ID looks like it ought to belong to a NEXT frame,
4583but we got it for a PREV frame. Normally, this is a sign of
4584unwinder failure. It could also indicate stack corruption.
4585
4586@item gdb.FRAME_UNWIND_SAME_ID
4587This frame has the same ID as the previous one. That means
4588that unwinding further would almost certainly give us another
4589frame with exactly the same ID, so break the chain. Normally,
4590this is a sign of unwinder failure. It could also indicate
4591stack corruption.
4592
4593@item gdb.FRAME_UNWIND_NO_SAVED_PC
4594The frame unwinder did not find any saved PC, but we needed
4595one to unwind further.
4596
53e8a631
AB
4597@item gdb.FRAME_UNWIND_MEMORY_ERROR
4598The frame unwinder caused an error while trying to access memory.
4599
329baa95
DE
4600@item gdb.FRAME_UNWIND_FIRST_ERROR
4601Any stop reason greater or equal to this value indicates some kind
4602of error. This special value facilitates writing code that tests
4603for errors in unwinding in a way that will work correctly even if
4604the list of the other values is modified in future @value{GDBN}
4605versions. Using it, you could write:
4606@smallexample
4607reason = gdb.selected_frame().unwind_stop_reason ()
4608reason_str = gdb.frame_stop_reason_string (reason)
4609if reason >= gdb.FRAME_UNWIND_FIRST_ERROR:
4610 print "An error occured: %s" % reason_str
4611@end smallexample
4612@end table
4613
4614@end defun
4615
4616@defun Frame.pc ()
4617Returns the frame's resume address.
4618@end defun
4619
4620@defun Frame.block ()
60c0454d
TT
4621Return the frame's code block. @xref{Blocks In Python}. If the frame
4622does not have a block -- for example, if there is no debugging
4623information for the code in question -- then this will throw an
4624exception.
329baa95
DE
4625@end defun
4626
4627@defun Frame.function ()
4628Return the symbol for the function corresponding to this frame.
4629@xref{Symbols In Python}.
4630@end defun
4631
4632@defun Frame.older ()
4633Return the frame that called this frame.
4634@end defun
4635
4636@defun Frame.newer ()
4637Return the frame called by this frame.
4638@end defun
4639
4640@defun Frame.find_sal ()
4641Return the frame's symtab and line object.
4642@xref{Symbol Tables In Python}.
4643@end defun
4644
5f3b99cf
SS
4645@defun Frame.read_register (register)
4646Return the value of @var{register} in this frame. The @var{register}
4647argument must be a string (e.g., @code{'sp'} or @code{'rax'}).
4648Returns a @code{Gdb.Value} object. Throws an exception if @var{register}
4649does not exist.
4650@end defun
4651
329baa95
DE
4652@defun Frame.read_var (variable @r{[}, block@r{]})
4653Return the value of @var{variable} in this frame. If the optional
4654argument @var{block} is provided, search for the variable from that
4655block; otherwise start at the frame's current block (which is
697aa1b7
EZ
4656determined by the frame's current program counter). The @var{variable}
4657argument must be a string or a @code{gdb.Symbol} object; @var{block} must be a
329baa95
DE
4658@code{gdb.Block} object.
4659@end defun
4660
4661@defun Frame.select ()
4662Set this frame to be the selected frame. @xref{Stack, ,Examining the
4663Stack}.
4664@end defun
4665
4666@node Blocks In Python
849cba3b 4667@subsubsection Accessing blocks from Python
329baa95
DE
4668
4669@cindex blocks in python
4670@tindex gdb.Block
4671
4672In @value{GDBN}, symbols are stored in blocks. A block corresponds
4673roughly to a scope in the source code. Blocks are organized
4674hierarchically, and are represented individually in Python as a
4675@code{gdb.Block}. Blocks rely on debugging information being
4676available.
4677
4678A frame has a block. Please see @ref{Frames In Python}, for a more
4679in-depth discussion of frames.
4680
4681The outermost block is known as the @dfn{global block}. The global
4682block typically holds public global variables and functions.
4683
4684The block nested just inside the global block is the @dfn{static
4685block}. The static block typically holds file-scoped variables and
4686functions.
4687
4688@value{GDBN} provides a method to get a block's superblock, but there
4689is currently no way to examine the sub-blocks of a block, or to
4690iterate over all the blocks in a symbol table (@pxref{Symbol Tables In
4691Python}).
4692
4693Here is a short example that should help explain blocks:
4694
4695@smallexample
4696/* This is in the global block. */
4697int global;
4698
4699/* This is in the static block. */
4700static int file_scope;
4701
4702/* 'function' is in the global block, and 'argument' is
4703 in a block nested inside of 'function'. */
4704int function (int argument)
4705@{
4706 /* 'local' is in a block inside 'function'. It may or may
4707 not be in the same block as 'argument'. */
4708 int local;
4709
4710 @{
4711 /* 'inner' is in a block whose superblock is the one holding
4712 'local'. */
4713 int inner;
4714
4715 /* If this call is expanded by the compiler, you may see
4716 a nested block here whose function is 'inline_function'
4717 and whose superblock is the one holding 'inner'. */
4718 inline_function ();
4719 @}
4720@}
4721@end smallexample
4722
4723A @code{gdb.Block} is iterable. The iterator returns the symbols
4724(@pxref{Symbols In Python}) local to the block. Python programs
4725should not assume that a specific block object will always contain a
4726given symbol, since changes in @value{GDBN} features and
4727infrastructure may cause symbols move across blocks in a symbol
0b27c27d
CB
4728table. You can also use Python's @dfn{dictionary syntax} to access
4729variables in this block, e.g.:
4730
4731@smallexample
4732symbol = some_block['variable'] # symbol is of type gdb.Symbol
4733@end smallexample
329baa95
DE
4734
4735The following block-related functions are available in the @code{gdb}
4736module:
4737
4738@findex gdb.block_for_pc
4739@defun gdb.block_for_pc (pc)
4740Return the innermost @code{gdb.Block} containing the given @var{pc}
4741value. If the block cannot be found for the @var{pc} value specified,
8743a9cd
TT
4742the function will return @code{None}. This is identical to
4743@code{gdb.current_progspace().block_for_pc(pc)} and is included for
4744historical compatibility.
329baa95
DE
4745@end defun
4746
4747A @code{gdb.Block} object has the following methods:
4748
4749@defun Block.is_valid ()
4750Returns @code{True} if the @code{gdb.Block} object is valid,
4751@code{False} if not. A block object can become invalid if the block it
4752refers to doesn't exist anymore in the inferior. All other
4753@code{gdb.Block} methods will throw an exception if it is invalid at
4754the time the method is called. The block's validity is also checked
4755during iteration over symbols of the block.
4756@end defun
4757
4758A @code{gdb.Block} object has the following attributes:
4759
4760@defvar Block.start
4761The start address of the block. This attribute is not writable.
4762@end defvar
4763
4764@defvar Block.end
22eb9e92
TT
4765One past the last address that appears in the block. This attribute
4766is not writable.
329baa95
DE
4767@end defvar
4768
4769@defvar Block.function
4770The name of the block represented as a @code{gdb.Symbol}. If the
4771block is not named, then this attribute holds @code{None}. This
4772attribute is not writable.
4773
4774For ordinary function blocks, the superblock is the static block.
4775However, you should note that it is possible for a function block to
4776have a superblock that is not the static block -- for instance this
4777happens for an inlined function.
4778@end defvar
4779
4780@defvar Block.superblock
4781The block containing this block. If this parent block does not exist,
4782this attribute holds @code{None}. This attribute is not writable.
4783@end defvar
4784
4785@defvar Block.global_block
4786The global block associated with this block. This attribute is not
4787writable.
4788@end defvar
4789
4790@defvar Block.static_block
4791The static block associated with this block. This attribute is not
4792writable.
4793@end defvar
4794
4795@defvar Block.is_global
4796@code{True} if the @code{gdb.Block} object is a global block,
4797@code{False} if not. This attribute is not
4798writable.
4799@end defvar
4800
4801@defvar Block.is_static
4802@code{True} if the @code{gdb.Block} object is a static block,
4803@code{False} if not. This attribute is not writable.
4804@end defvar
4805
4806@node Symbols In Python
849cba3b 4807@subsubsection Python representation of Symbols
329baa95
DE
4808
4809@cindex symbols in python
4810@tindex gdb.Symbol
4811
4812@value{GDBN} represents every variable, function and type as an
4813entry in a symbol table. @xref{Symbols, ,Examining the Symbol Table}.
4814Similarly, Python represents these symbols in @value{GDBN} with the
4815@code{gdb.Symbol} object.
4816
4817The following symbol-related functions are available in the @code{gdb}
4818module:
4819
4820@findex gdb.lookup_symbol
4821@defun gdb.lookup_symbol (name @r{[}, block @r{[}, domain@r{]]})
4822This function searches for a symbol by name. The search scope can be
4823restricted to the parameters defined in the optional domain and block
4824arguments.
4825
4826@var{name} is the name of the symbol. It must be a string. The
4827optional @var{block} argument restricts the search to symbols visible
4828in that @var{block}. The @var{block} argument must be a
4829@code{gdb.Block} object. If omitted, the block for the current frame
4830is used. The optional @var{domain} argument restricts
4831the search to the domain type. The @var{domain} argument must be a
4832domain constant defined in the @code{gdb} module and described later
4833in this chapter.
4834
4835The result is a tuple of two elements.
4836The first element is a @code{gdb.Symbol} object or @code{None} if the symbol
4837is not found.
4838If the symbol is found, the second element is @code{True} if the symbol
4839is a field of a method's object (e.g., @code{this} in C@t{++}),
4840otherwise it is @code{False}.
4841If the symbol is not found, the second element is @code{False}.
4842@end defun
4843
4844@findex gdb.lookup_global_symbol
4845@defun gdb.lookup_global_symbol (name @r{[}, domain@r{]})
4846This function searches for a global symbol by name.
4847The search scope can be restricted to by the domain argument.
4848
4849@var{name} is the name of the symbol. It must be a string.
4850The optional @var{domain} argument restricts the search to the domain type.
4851The @var{domain} argument must be a domain constant defined in the @code{gdb}
4852module and described later in this chapter.
4853
4854The result is a @code{gdb.Symbol} object or @code{None} if the symbol
4855is not found.
4856@end defun
4857
2906593f
CB
4858@findex gdb.lookup_static_symbol
4859@defun gdb.lookup_static_symbol (name @r{[}, domain@r{]})
4860This function searches for a global symbol with static linkage by name.
4861The search scope can be restricted to by the domain argument.
4862
4863@var{name} is the name of the symbol. It must be a string.
4864The optional @var{domain} argument restricts the search to the domain type.
4865The @var{domain} argument must be a domain constant defined in the @code{gdb}
4866module and described later in this chapter.
4867
4868The result is a @code{gdb.Symbol} object or @code{None} if the symbol
4869is not found.
4870
4871Note that this function will not find function-scoped static variables. To look
4872up such variables, iterate over the variables of the function's
4873@code{gdb.Block} and check that @code{block.addr_class} is
4874@code{gdb.SYMBOL_LOC_STATIC}.
09ff83af
AB
4875
4876There can be multiple global symbols with static linkage with the same
4877name. This function will only return the first matching symbol that
4878it finds. Which symbol is found depends on where @value{GDBN} is
4879currently stopped, as @value{GDBN} will first search for matching
4880symbols in the current object file, and then search all other object
4881files. If the application is not yet running then @value{GDBN} will
4882search all object files in the order they appear in the debug
4883information.
2906593f
CB
4884@end defun
4885
086baaf1
AB
4886@findex gdb.lookup_static_symbols
4887@defun gdb.lookup_static_symbols (name @r{[}, domain@r{]})
4888Similar to @code{gdb.lookup_static_symbol}, this function searches for
4889global symbols with static linkage by name, and optionally restricted
4890by the domain argument. However, this function returns a list of all
4891matching symbols found, not just the first one.
4892
4893@var{name} is the name of the symbol. It must be a string.
4894The optional @var{domain} argument restricts the search to the domain type.
4895The @var{domain} argument must be a domain constant defined in the @code{gdb}
4896module and described later in this chapter.
4897
4898The result is a list of @code{gdb.Symbol} objects which could be empty
4899if no matching symbols were found.
4900
4901Note that this function will not find function-scoped static variables. To look
4902up such variables, iterate over the variables of the function's
4903@code{gdb.Block} and check that @code{block.addr_class} is
4904@code{gdb.SYMBOL_LOC_STATIC}.
4905@end defun
4906
329baa95
DE
4907A @code{gdb.Symbol} object has the following attributes:
4908
4909@defvar Symbol.type
4910The type of the symbol or @code{None} if no type is recorded.
4911This attribute is represented as a @code{gdb.Type} object.
4912@xref{Types In Python}. This attribute is not writable.
4913@end defvar
4914
4915@defvar Symbol.symtab
4916The symbol table in which the symbol appears. This attribute is
4917represented as a @code{gdb.Symtab} object. @xref{Symbol Tables In
4918Python}. This attribute is not writable.
4919@end defvar
4920
4921@defvar Symbol.line
4922The line number in the source code at which the symbol was defined.
4923This is an integer.
4924@end defvar
4925
4926@defvar Symbol.name
4927The name of the symbol as a string. This attribute is not writable.
4928@end defvar
4929
4930@defvar Symbol.linkage_name
4931The name of the symbol, as used by the linker (i.e., may be mangled).
4932This attribute is not writable.
4933@end defvar
4934
4935@defvar Symbol.print_name
4936The name of the symbol in a form suitable for output. This is either
4937@code{name} or @code{linkage_name}, depending on whether the user
4938asked @value{GDBN} to display demangled or mangled names.
4939@end defvar
4940
4941@defvar Symbol.addr_class
4942The address class of the symbol. This classifies how to find the value
4943of a symbol. Each address class is a constant defined in the
4944@code{gdb} module and described later in this chapter.
4945@end defvar
4946
4947@defvar Symbol.needs_frame
4948This is @code{True} if evaluating this symbol's value requires a frame
4949(@pxref{Frames In Python}) and @code{False} otherwise. Typically,
4950local variables will require a frame, but other symbols will not.
4951@end defvar
4952
4953@defvar Symbol.is_argument
4954@code{True} if the symbol is an argument of a function.
4955@end defvar
4956
4957@defvar Symbol.is_constant
4958@code{True} if the symbol is a constant.
4959@end defvar
4960
4961@defvar Symbol.is_function
4962@code{True} if the symbol is a function or a method.
4963@end defvar
4964
4965@defvar Symbol.is_variable
4966@code{True} if the symbol is a variable.
4967@end defvar
4968
4969A @code{gdb.Symbol} object has the following methods:
4970
4971@defun Symbol.is_valid ()
4972Returns @code{True} if the @code{gdb.Symbol} object is valid,
4973@code{False} if not. A @code{gdb.Symbol} object can become invalid if
4974the symbol it refers to does not exist in @value{GDBN} any longer.
4975All other @code{gdb.Symbol} methods will throw an exception if it is
4976invalid at the time the method is called.
4977@end defun
4978
4979@defun Symbol.value (@r{[}frame@r{]})
4980Compute the value of the symbol, as a @code{gdb.Value}. For
4981functions, this computes the address of the function, cast to the
4982appropriate type. If the symbol requires a frame in order to compute
4983its value, then @var{frame} must be given. If @var{frame} is not
4984given, or if @var{frame} is invalid, then this method will throw an
4985exception.
4986@end defun
4987
4988The available domain categories in @code{gdb.Symbol} are represented
4989as constants in the @code{gdb} module:
4990
b3ce5e5f
DE
4991@vtable @code
4992@vindex SYMBOL_UNDEF_DOMAIN
329baa95
DE
4993@item gdb.SYMBOL_UNDEF_DOMAIN
4994This is used when a domain has not been discovered or none of the
4995following domains apply. This usually indicates an error either
4996in the symbol information or in @value{GDBN}'s handling of symbols.
b3ce5e5f
DE
4997
4998@vindex SYMBOL_VAR_DOMAIN
329baa95
DE
4999@item gdb.SYMBOL_VAR_DOMAIN
5000This domain contains variables, function names, typedef names and enum
5001type values.
b3ce5e5f
DE
5002
5003@vindex SYMBOL_STRUCT_DOMAIN
329baa95
DE
5004@item gdb.SYMBOL_STRUCT_DOMAIN
5005This domain holds struct, union and enum type names.
b3ce5e5f
DE
5006
5007@vindex SYMBOL_LABEL_DOMAIN
329baa95
DE
5008@item gdb.SYMBOL_LABEL_DOMAIN
5009This domain contains names of labels (for gotos).
b3ce5e5f 5010
51e78fc5
TT
5011@vindex SYMBOL_MODULE_DOMAIN
5012@item gdb.SYMBOL_MODULE_DOMAIN
5013This domain contains names of Fortran module types.
5014
5015@vindex SYMBOL_COMMON_BLOCK_DOMAIN
5016@item gdb.SYMBOL_COMMON_BLOCK_DOMAIN
5017This domain contains names of Fortran common blocks.
b3ce5e5f 5018@end vtable
329baa95
DE
5019
5020The available address class categories in @code{gdb.Symbol} are represented
5021as constants in the @code{gdb} module:
5022
b3ce5e5f
DE
5023@vtable @code
5024@vindex SYMBOL_LOC_UNDEF
329baa95
DE
5025@item gdb.SYMBOL_LOC_UNDEF
5026If this is returned by address class, it indicates an error either in
5027the symbol information or in @value{GDBN}'s handling of symbols.
b3ce5e5f
DE
5028
5029@vindex SYMBOL_LOC_CONST
329baa95
DE
5030@item gdb.SYMBOL_LOC_CONST
5031Value is constant int.
b3ce5e5f
DE
5032
5033@vindex SYMBOL_LOC_STATIC
329baa95
DE
5034@item gdb.SYMBOL_LOC_STATIC
5035Value is at a fixed address.
b3ce5e5f
DE
5036
5037@vindex SYMBOL_LOC_REGISTER
329baa95
DE
5038@item gdb.SYMBOL_LOC_REGISTER
5039Value is in a register.
b3ce5e5f
DE
5040
5041@vindex SYMBOL_LOC_ARG
329baa95
DE
5042@item gdb.SYMBOL_LOC_ARG
5043Value is an argument. This value is at the offset stored within the
5044symbol inside the frame's argument list.
b3ce5e5f
DE
5045
5046@vindex SYMBOL_LOC_REF_ARG
329baa95
DE
5047@item gdb.SYMBOL_LOC_REF_ARG
5048Value address is stored in the frame's argument list. Just like
5049@code{LOC_ARG} except that the value's address is stored at the
5050offset, not the value itself.
b3ce5e5f
DE
5051
5052@vindex SYMBOL_LOC_REGPARM_ADDR
329baa95
DE
5053@item gdb.SYMBOL_LOC_REGPARM_ADDR
5054Value is a specified register. Just like @code{LOC_REGISTER} except
5055the register holds the address of the argument instead of the argument
5056itself.
b3ce5e5f
DE
5057
5058@vindex SYMBOL_LOC_LOCAL
329baa95
DE
5059@item gdb.SYMBOL_LOC_LOCAL
5060Value is a local variable.
b3ce5e5f
DE
5061
5062@vindex SYMBOL_LOC_TYPEDEF
329baa95
DE
5063@item gdb.SYMBOL_LOC_TYPEDEF
5064Value not used. Symbols in the domain @code{SYMBOL_STRUCT_DOMAIN} all
5065have this class.
b3ce5e5f
DE
5066
5067@vindex SYMBOL_LOC_BLOCK
329baa95
DE
5068@item gdb.SYMBOL_LOC_BLOCK
5069Value is a block.
b3ce5e5f
DE
5070
5071@vindex SYMBOL_LOC_CONST_BYTES
329baa95
DE
5072@item gdb.SYMBOL_LOC_CONST_BYTES
5073Value is a byte-sequence.
b3ce5e5f
DE
5074
5075@vindex SYMBOL_LOC_UNRESOLVED
329baa95
DE
5076@item gdb.SYMBOL_LOC_UNRESOLVED
5077Value is at a fixed address, but the address of the variable has to be
5078determined from the minimal symbol table whenever the variable is
5079referenced.
b3ce5e5f
DE
5080
5081@vindex SYMBOL_LOC_OPTIMIZED_OUT
329baa95
DE
5082@item gdb.SYMBOL_LOC_OPTIMIZED_OUT
5083The value does not actually exist in the program.
b3ce5e5f
DE
5084
5085@vindex SYMBOL_LOC_COMPUTED
329baa95
DE
5086@item gdb.SYMBOL_LOC_COMPUTED
5087The value's address is a computed location.
51e78fc5
TT
5088
5089@vindex SYMBOL_LOC_COMPUTED
5090@item gdb.SYMBOL_LOC_COMPUTED
5091The value's address is a symbol. This is only used for Fortran common
5092blocks.
b3ce5e5f 5093@end vtable
329baa95
DE
5094
5095@node Symbol Tables In Python
849cba3b 5096@subsubsection Symbol table representation in Python
329baa95
DE
5097
5098@cindex symbol tables in python
5099@tindex gdb.Symtab
5100@tindex gdb.Symtab_and_line
5101
5102Access to symbol table data maintained by @value{GDBN} on the inferior
5103is exposed to Python via two objects: @code{gdb.Symtab_and_line} and
5104@code{gdb.Symtab}. Symbol table and line data for a frame is returned
5105from the @code{find_sal} method in @code{gdb.Frame} object.
5106@xref{Frames In Python}.
5107
5108For more information on @value{GDBN}'s symbol table management, see
5109@ref{Symbols, ,Examining the Symbol Table}, for more information.
5110
5111A @code{gdb.Symtab_and_line} object has the following attributes:
5112
5113@defvar Symtab_and_line.symtab
5114The symbol table object (@code{gdb.Symtab}) for this frame.
5115This attribute is not writable.
5116@end defvar
5117
5118@defvar Symtab_and_line.pc
5119Indicates the start of the address range occupied by code for the
5120current source line. This attribute is not writable.
5121@end defvar
5122
5123@defvar Symtab_and_line.last
5124Indicates the end of the address range occupied by code for the current
5125source line. This attribute is not writable.
5126@end defvar
5127
5128@defvar Symtab_and_line.line
5129Indicates the current line number for this object. This
5130attribute is not writable.
5131@end defvar
5132
5133A @code{gdb.Symtab_and_line} object has the following methods:
5134
5135@defun Symtab_and_line.is_valid ()
5136Returns @code{True} if the @code{gdb.Symtab_and_line} object is valid,
5137@code{False} if not. A @code{gdb.Symtab_and_line} object can become
5138invalid if the Symbol table and line object it refers to does not
5139exist in @value{GDBN} any longer. All other
5140@code{gdb.Symtab_and_line} methods will throw an exception if it is
5141invalid at the time the method is called.
5142@end defun
5143
5144A @code{gdb.Symtab} object has the following attributes:
5145
5146@defvar Symtab.filename
5147The symbol table's source filename. This attribute is not writable.
5148@end defvar
5149
5150@defvar Symtab.objfile
5151The symbol table's backing object file. @xref{Objfiles In Python}.
5152This attribute is not writable.
5153@end defvar
5154
2b4fd423
DE
5155@defvar Symtab.producer
5156The name and possibly version number of the program that
5157compiled the code in the symbol table.
5158The contents of this string is up to the compiler.
5159If no producer information is available then @code{None} is returned.
5160This attribute is not writable.
5161@end defvar
5162
329baa95
DE
5163A @code{gdb.Symtab} object has the following methods:
5164
5165@defun Symtab.is_valid ()
5166Returns @code{True} if the @code{gdb.Symtab} object is valid,
5167@code{False} if not. A @code{gdb.Symtab} object can become invalid if
5168the symbol table it refers to does not exist in @value{GDBN} any
5169longer. All other @code{gdb.Symtab} methods will throw an exception
5170if it is invalid at the time the method is called.
5171@end defun
5172
5173@defun Symtab.fullname ()
5174Return the symbol table's source absolute file name.
5175@end defun
5176
5177@defun Symtab.global_block ()
5178Return the global block of the underlying symbol table.
5179@xref{Blocks In Python}.
5180@end defun
5181
5182@defun Symtab.static_block ()
5183Return the static block of the underlying symbol table.
5184@xref{Blocks In Python}.
5185@end defun
5186
5187@defun Symtab.linetable ()
5188Return the line table associated with the symbol table.
5189@xref{Line Tables In Python}.
5190@end defun
5191
5192@node Line Tables In Python
5193@subsubsection Manipulating line tables using Python
5194
5195@cindex line tables in python
5196@tindex gdb.LineTable
5197
5198Python code can request and inspect line table information from a
5199symbol table that is loaded in @value{GDBN}. A line table is a
5200mapping of source lines to their executable locations in memory. To
5201acquire the line table information for a particular symbol table, use
5202the @code{linetable} function (@pxref{Symbol Tables In Python}).
5203
5204A @code{gdb.LineTable} is iterable. The iterator returns
5205@code{LineTableEntry} objects that correspond to the source line and
5206address for each line table entry. @code{LineTableEntry} objects have
5207the following attributes:
5208
5209@defvar LineTableEntry.line
5210The source line number for this line table entry. This number
5211corresponds to the actual line of source. This attribute is not
5212writable.
5213@end defvar
5214
5215@defvar LineTableEntry.pc
5216The address that is associated with the line table entry where the
5217executable code for that source line resides in memory. This
5218attribute is not writable.
5219@end defvar
5220
5221As there can be multiple addresses for a single source line, you may
5222receive multiple @code{LineTableEntry} objects with matching
5223@code{line} attributes, but with different @code{pc} attributes. The
5224iterator is sorted in ascending @code{pc} order. Here is a small
5225example illustrating iterating over a line table.
5226
5227@smallexample
5228symtab = gdb.selected_frame().find_sal().symtab
5229linetable = symtab.linetable()
5230for line in linetable:
5231 print "Line: "+str(line.line)+" Address: "+hex(line.pc)
5232@end smallexample
5233
5234This will have the following output:
5235
5236@smallexample
5237Line: 33 Address: 0x4005c8L
5238Line: 37 Address: 0x4005caL
5239Line: 39 Address: 0x4005d2L
5240Line: 40 Address: 0x4005f8L
5241Line: 42 Address: 0x4005ffL
5242Line: 44 Address: 0x400608L
5243Line: 42 Address: 0x40060cL
5244Line: 45 Address: 0x400615L
5245@end smallexample
5246
5247In addition to being able to iterate over a @code{LineTable}, it also
5248has the following direct access methods:
5249
5250@defun LineTable.line (line)
5251Return a Python @code{Tuple} of @code{LineTableEntry} objects for any
697aa1b7
EZ
5252entries in the line table for the given @var{line}, which specifies
5253the source code line. If there are no entries for that source code
329baa95
DE
5254@var{line}, the Python @code{None} is returned.
5255@end defun
5256
5257@defun LineTable.has_line (line)
5258Return a Python @code{Boolean} indicating whether there is an entry in
5259the line table for this source line. Return @code{True} if an entry
5260is found, or @code{False} if not.
5261@end defun
5262
5263@defun LineTable.source_lines ()
5264Return a Python @code{List} of the source line numbers in the symbol
5265table. Only lines with executable code locations are returned. The
5266contents of the @code{List} will just be the source line entries
5267represented as Python @code{Long} values.
5268@end defun
5269
5270@node Breakpoints In Python
5271@subsubsection Manipulating breakpoints using Python
5272
5273@cindex breakpoints in python
5274@tindex gdb.Breakpoint
5275
5276Python code can manipulate breakpoints via the @code{gdb.Breakpoint}
5277class.
5278
0b982d68
SM
5279A breakpoint can be created using one of the two forms of the
5280@code{gdb.Breakpoint} constructor. The first one accepts a string
5281like one would pass to the @code{break}
5282(@pxref{Set Breaks,,Setting Breakpoints}) and @code{watch}
5283(@pxref{Set Watchpoints, , Setting Watchpoints}) commands, and can be used to
5284create both breakpoints and watchpoints. The second accepts separate Python
5285arguments similar to @ref{Explicit Locations}, and can only be used to create
5286breakpoints.
5287
b89641ba 5288@defun Breakpoint.__init__ (spec @r{[}, type @r{][}, wp_class @r{][}, internal @r{][}, temporary @r{][}, qualified @r{]})
0b982d68
SM
5289Create a new breakpoint according to @var{spec}, which is a string naming the
5290location of a breakpoint, or an expression that defines a watchpoint. The
5291string should describe a location in a format recognized by the @code{break}
5292command (@pxref{Set Breaks,,Setting Breakpoints}) or, in the case of a
5293watchpoint, by the @code{watch} command
5294(@pxref{Set Watchpoints, , Setting Watchpoints}).
5295
5296The optional @var{type} argument specifies the type of the breakpoint to create,
5297as defined below.
5298
5299The optional @var{wp_class} argument defines the class of watchpoint to create,
5300if @var{type} is @code{gdb.BP_WATCHPOINT}. If @var{wp_class} is omitted, it
5301defaults to @code{gdb.WP_WRITE}.
5302
5303The optional @var{internal} argument allows the breakpoint to become invisible
5304to the user. The breakpoint will neither be reported when created, nor will it
5305be listed in the output from @code{info breakpoints} (but will be listed with
5306the @code{maint info breakpoints} command).
5307
5308The optional @var{temporary} argument makes the breakpoint a temporary
5309breakpoint. Temporary breakpoints are deleted after they have been hit. Any
5310further access to the Python breakpoint after it has been hit will result in a
5311runtime error (as that breakpoint has now been automatically deleted).
b89641ba
SM
5312
5313The optional @var{qualified} argument is a boolean that allows interpreting
5314the function passed in @code{spec} as a fully-qualified name. It is equivalent
5315to @code{break}'s @code{-qualified} flag (@pxref{Linespec Locations} and
5316@ref{Explicit Locations}).
5317
0b982d68
SM
5318@end defun
5319
b89641ba 5320@defun Breakpoint.__init__ (@r{[} source @r{][}, function @r{][}, label @r{][}, line @r{]}, @r{][} internal @r{][}, temporary @r{][}, qualified @r{]})
0b982d68
SM
5321This second form of creating a new breakpoint specifies the explicit
5322location (@pxref{Explicit Locations}) using keywords. The new breakpoint will
5323be created in the specified source file @var{source}, at the specified
5324@var{function}, @var{label} and @var{line}.
5325
b89641ba
SM
5326@var{internal}, @var{temporary} and @var{qualified} have the same usage as
5327explained previously.
329baa95
DE
5328@end defun
5329
cda75e70
TT
5330The available types are represented by constants defined in the @code{gdb}
5331module:
5332
5333@vtable @code
5334@vindex BP_BREAKPOINT
5335@item gdb.BP_BREAKPOINT
5336Normal code breakpoint.
5337
5338@vindex BP_WATCHPOINT
5339@item gdb.BP_WATCHPOINT
5340Watchpoint breakpoint.
5341
5342@vindex BP_HARDWARE_WATCHPOINT
5343@item gdb.BP_HARDWARE_WATCHPOINT
5344Hardware assisted watchpoint.
5345
5346@vindex BP_READ_WATCHPOINT
5347@item gdb.BP_READ_WATCHPOINT
5348Hardware assisted read watchpoint.
5349
5350@vindex BP_ACCESS_WATCHPOINT
5351@item gdb.BP_ACCESS_WATCHPOINT
5352Hardware assisted access watchpoint.
5353@end vtable
5354
5355The available watchpoint types represented by constants are defined in the
5356@code{gdb} module:
5357
5358@vtable @code
5359@vindex WP_READ
5360@item gdb.WP_READ
5361Read only watchpoint.
5362
5363@vindex WP_WRITE
5364@item gdb.WP_WRITE
5365Write only watchpoint.
5366
5367@vindex WP_ACCESS
5368@item gdb.WP_ACCESS
5369Read/Write watchpoint.
5370@end vtable
5371
329baa95
DE
5372@defun Breakpoint.stop (self)
5373The @code{gdb.Breakpoint} class can be sub-classed and, in
5374particular, you may choose to implement the @code{stop} method.
5375If this method is defined in a sub-class of @code{gdb.Breakpoint},
5376it will be called when the inferior reaches any location of a
5377breakpoint which instantiates that sub-class. If the method returns
5378@code{True}, the inferior will be stopped at the location of the
5379breakpoint, otherwise the inferior will continue.
5380
5381If there are multiple breakpoints at the same location with a
5382@code{stop} method, each one will be called regardless of the
5383return status of the previous. This ensures that all @code{stop}
5384methods have a chance to execute at that location. In this scenario
5385if one of the methods returns @code{True} but the others return
5386@code{False}, the inferior will still be stopped.
5387
5388You should not alter the execution state of the inferior (i.e.@:, step,
5389next, etc.), alter the current frame context (i.e.@:, change the current
5390active frame), or alter, add or delete any breakpoint. As a general
5391rule, you should not alter any data within @value{GDBN} or the inferior
5392at this time.
5393
5394Example @code{stop} implementation:
5395
5396@smallexample
5397class MyBreakpoint (gdb.Breakpoint):
5398 def stop (self):
5399 inf_val = gdb.parse_and_eval("foo")
5400 if inf_val == 3:
5401 return True
5402 return False
5403@end smallexample
5404@end defun
5405
329baa95
DE
5406@defun Breakpoint.is_valid ()
5407Return @code{True} if this @code{Breakpoint} object is valid,
5408@code{False} otherwise. A @code{Breakpoint} object can become invalid
5409if the user deletes the breakpoint. In this case, the object still
5410exists, but the underlying breakpoint does not. In the cases of
5411watchpoint scope, the watchpoint remains valid even if execution of the
5412inferior leaves the scope of that watchpoint.
5413@end defun
5414
fab3a15d 5415@defun Breakpoint.delete ()
329baa95
DE
5416Permanently deletes the @value{GDBN} breakpoint. This also
5417invalidates the Python @code{Breakpoint} object. Any further access
5418to this object's attributes or methods will raise an error.
5419@end defun
5420
5421@defvar Breakpoint.enabled
5422This attribute is @code{True} if the breakpoint is enabled, and
fab3a15d
SM
5423@code{False} otherwise. This attribute is writable. You can use it to enable
5424or disable the breakpoint.
329baa95
DE
5425@end defvar
5426
5427@defvar Breakpoint.silent
5428This attribute is @code{True} if the breakpoint is silent, and
5429@code{False} otherwise. This attribute is writable.
5430
5431Note that a breakpoint can also be silent if it has commands and the
5432first command is @code{silent}. This is not reported by the
5433@code{silent} attribute.
5434@end defvar
5435
93daf339
TT
5436@defvar Breakpoint.pending
5437This attribute is @code{True} if the breakpoint is pending, and
5438@code{False} otherwise. @xref{Set Breaks}. This attribute is
5439read-only.
5440@end defvar
5441
22a02324 5442@anchor{python_breakpoint_thread}
329baa95 5443@defvar Breakpoint.thread
5d5658a1
PA
5444If the breakpoint is thread-specific, this attribute holds the
5445thread's global id. If the breakpoint is not thread-specific, this
5446attribute is @code{None}. This attribute is writable.
329baa95
DE
5447@end defvar
5448
5449@defvar Breakpoint.task
5450If the breakpoint is Ada task-specific, this attribute holds the Ada task
5451id. If the breakpoint is not task-specific (or the underlying
5452language is not Ada), this attribute is @code{None}. This attribute
5453is writable.
5454@end defvar
5455
5456@defvar Breakpoint.ignore_count
5457This attribute holds the ignore count for the breakpoint, an integer.
5458This attribute is writable.
5459@end defvar
5460
5461@defvar Breakpoint.number
5462This attribute holds the breakpoint's number --- the identifier used by
5463the user to manipulate the breakpoint. This attribute is not writable.
5464@end defvar
5465
5466@defvar Breakpoint.type
5467This attribute holds the breakpoint's type --- the identifier used to
5468determine the actual breakpoint type or use-case. This attribute is not
5469writable.
5470@end defvar
5471
5472@defvar Breakpoint.visible
5473This attribute tells whether the breakpoint is visible to the user
5474when set, or when the @samp{info breakpoints} command is run. This
5475attribute is not writable.
5476@end defvar
5477
5478@defvar Breakpoint.temporary
5479This attribute indicates whether the breakpoint was created as a
5480temporary breakpoint. Temporary breakpoints are automatically deleted
5481after that breakpoint has been hit. Access to this attribute, and all
5482other attributes and functions other than the @code{is_valid}
5483function, will result in an error after the breakpoint has been hit
5484(as it has been automatically deleted). This attribute is not
5485writable.
5486@end defvar
5487
329baa95
DE
5488@defvar Breakpoint.hit_count
5489This attribute holds the hit count for the breakpoint, an integer.
5490This attribute is writable, but currently it can only be set to zero.
5491@end defvar
5492
5493@defvar Breakpoint.location
5494This attribute holds the location of the breakpoint, as specified by
5495the user. It is a string. If the breakpoint does not have a location
5496(that is, it is a watchpoint) the attribute's value is @code{None}. This
5497attribute is not writable.
5498@end defvar
5499
5500@defvar Breakpoint.expression
5501This attribute holds a breakpoint expression, as specified by
5502the user. It is a string. If the breakpoint does not have an
5503expression (the breakpoint is not a watchpoint) the attribute's value
5504is @code{None}. This attribute is not writable.
5505@end defvar
5506
5507@defvar Breakpoint.condition
5508This attribute holds the condition of the breakpoint, as specified by
5509the user. It is a string. If there is no condition, this attribute's
5510value is @code{None}. This attribute is writable.
5511@end defvar
5512
5513@defvar Breakpoint.commands
5514This attribute holds the commands attached to the breakpoint. If
5515there are commands, this attribute's value is a string holding all the
5516commands, separated by newlines. If there are no commands, this
a913fffb 5517attribute is @code{None}. This attribute is writable.
329baa95
DE
5518@end defvar
5519
5520@node Finish Breakpoints in Python
5521@subsubsection Finish Breakpoints
5522
5523@cindex python finish breakpoints
5524@tindex gdb.FinishBreakpoint
5525
5526A finish breakpoint is a temporary breakpoint set at the return address of
5527a frame, based on the @code{finish} command. @code{gdb.FinishBreakpoint}
5528extends @code{gdb.Breakpoint}. The underlying breakpoint will be disabled
5529and deleted when the execution will run out of the breakpoint scope (i.e.@:
5530@code{Breakpoint.stop} or @code{FinishBreakpoint.out_of_scope} triggered).
5531Finish breakpoints are thread specific and must be create with the right
5532thread selected.
5533
5534@defun FinishBreakpoint.__init__ (@r{[}frame@r{]} @r{[}, internal@r{]})
5535Create a finish breakpoint at the return address of the @code{gdb.Frame}
5536object @var{frame}. If @var{frame} is not provided, this defaults to the
5537newest frame. The optional @var{internal} argument allows the breakpoint to
5538become invisible to the user. @xref{Breakpoints In Python}, for further
5539details about this argument.
5540@end defun
5541
5542@defun FinishBreakpoint.out_of_scope (self)
5543In some circumstances (e.g.@: @code{longjmp}, C@t{++} exceptions, @value{GDBN}
5544@code{return} command, @dots{}), a function may not properly terminate, and
5545thus never hit the finish breakpoint. When @value{GDBN} notices such a
5546situation, the @code{out_of_scope} callback will be triggered.
5547
5548You may want to sub-class @code{gdb.FinishBreakpoint} and override this
5549method:
5550
5551@smallexample
5552class MyFinishBreakpoint (gdb.FinishBreakpoint)
5553 def stop (self):
5554 print "normal finish"
5555 return True
5556
5557 def out_of_scope ():
5558 print "abnormal finish"
5559@end smallexample
5560@end defun
5561
5562@defvar FinishBreakpoint.return_value
5563When @value{GDBN} is stopped at a finish breakpoint and the frame
5564used to build the @code{gdb.FinishBreakpoint} object had debug symbols, this
5565attribute will contain a @code{gdb.Value} object corresponding to the return
5566value of the function. The value will be @code{None} if the function return
5567type is @code{void} or if the return value was not computable. This attribute
5568is not writable.
5569@end defvar
5570
5571@node Lazy Strings In Python
849cba3b 5572@subsubsection Python representation of lazy strings
329baa95
DE
5573
5574@cindex lazy strings in python
5575@tindex gdb.LazyString
5576
5577A @dfn{lazy string} is a string whose contents is not retrieved or
5578encoded until it is needed.
5579
5580A @code{gdb.LazyString} is represented in @value{GDBN} as an
5581@code{address} that points to a region of memory, an @code{encoding}
5582that will be used to encode that region of memory, and a @code{length}
5583to delimit the region of memory that represents the string. The
5584difference between a @code{gdb.LazyString} and a string wrapped within
5585a @code{gdb.Value} is that a @code{gdb.LazyString} will be treated
5586differently by @value{GDBN} when printing. A @code{gdb.LazyString} is
5587retrieved and encoded during printing, while a @code{gdb.Value}
5588wrapping a string is immediately retrieved and encoded on creation.
5589
5590A @code{gdb.LazyString} object has the following functions:
5591
5592@defun LazyString.value ()
5593Convert the @code{gdb.LazyString} to a @code{gdb.Value}. This value
5594will point to the string in memory, but will lose all the delayed
5595retrieval, encoding and handling that @value{GDBN} applies to a
5596@code{gdb.LazyString}.
5597@end defun
5598
5599@defvar LazyString.address
5600This attribute holds the address of the string. This attribute is not
5601writable.
5602@end defvar
5603
5604@defvar LazyString.length
5605This attribute holds the length of the string in characters. If the
5606length is -1, then the string will be fetched and encoded up to the
5607first null of appropriate width. This attribute is not writable.
5608@end defvar
5609
5610@defvar LazyString.encoding
5611This attribute holds the encoding that will be applied to the string
5612when the string is printed by @value{GDBN}. If the encoding is not
5613set, or contains an empty string, then @value{GDBN} will select the
5614most appropriate encoding when the string is printed. This attribute
5615is not writable.
5616@end defvar
5617
5618@defvar LazyString.type
5619This attribute holds the type that is represented by the lazy string's
f8d99587 5620type. For a lazy string this is a pointer or array type. To
329baa95
DE
5621resolve this to the lazy string's character type, use the type's
5622@code{target} method. @xref{Types In Python}. This attribute is not
5623writable.
5624@end defvar
5625
5626@node Architectures In Python
5627@subsubsection Python representation of architectures
5628@cindex Python architectures
5629
5630@value{GDBN} uses architecture specific parameters and artifacts in a
5631number of its various computations. An architecture is represented
5632by an instance of the @code{gdb.Architecture} class.
5633
5634A @code{gdb.Architecture} class has the following methods:
5635
5636@defun Architecture.name ()
5637Return the name (string value) of the architecture.
5638@end defun
5639
5640@defun Architecture.disassemble (@var{start_pc} @r{[}, @var{end_pc} @r{[}, @var{count}@r{]]})
5641Return a list of disassembled instructions starting from the memory
5642address @var{start_pc}. The optional arguments @var{end_pc} and
5643@var{count} determine the number of instructions in the returned list.
5644If both the optional arguments @var{end_pc} and @var{count} are
5645specified, then a list of at most @var{count} disassembled instructions
5646whose start address falls in the closed memory address interval from
5647@var{start_pc} to @var{end_pc} are returned. If @var{end_pc} is not
5648specified, but @var{count} is specified, then @var{count} number of
5649instructions starting from the address @var{start_pc} are returned. If
5650@var{count} is not specified but @var{end_pc} is specified, then all
5651instructions whose start address falls in the closed memory address
5652interval from @var{start_pc} to @var{end_pc} are returned. If neither
5653@var{end_pc} nor @var{count} are specified, then a single instruction at
5654@var{start_pc} is returned. For all of these cases, each element of the
5655returned list is a Python @code{dict} with the following string keys:
5656
5657@table @code
5658
5659@item addr
5660The value corresponding to this key is a Python long integer capturing
5661the memory address of the instruction.
5662
5663@item asm
5664The value corresponding to this key is a string value which represents
5665the instruction with assembly language mnemonics. The assembly
5666language flavor used is the same as that specified by the current CLI
5667variable @code{disassembly-flavor}. @xref{Machine Code}.
5668
5669@item length
5670The value corresponding to this key is the length (integer value) of the
5671instruction in bytes.
5672
5673@end table
5674@end defun
5675
5676@node Python Auto-loading
5677@subsection Python Auto-loading
5678@cindex Python auto-loading
5679
5680When a new object file is read (for example, due to the @code{file}
5681command, or because the inferior has loaded a shared library),
5682@value{GDBN} will look for Python support scripts in several ways:
5683@file{@var{objfile}-gdb.py} and @code{.debug_gdb_scripts} section.
5684@xref{Auto-loading extensions}.
5685
5686The auto-loading feature is useful for supplying application-specific
5687debugging commands and scripts.
5688
5689Auto-loading can be enabled or disabled,
5690and the list of auto-loaded scripts can be printed.
5691
5692@table @code
5693@anchor{set auto-load python-scripts}
5694@kindex set auto-load python-scripts
5695@item set auto-load python-scripts [on|off]
5696Enable or disable the auto-loading of Python scripts.
5697
5698@anchor{show auto-load python-scripts}
5699@kindex show auto-load python-scripts
5700@item show auto-load python-scripts
5701Show whether auto-loading of Python scripts is enabled or disabled.
5702
5703@anchor{info auto-load python-scripts}
5704@kindex info auto-load python-scripts
5705@cindex print list of auto-loaded Python scripts
5706@item info auto-load python-scripts [@var{regexp}]
5707Print the list of all Python scripts that @value{GDBN} auto-loaded.
5708
5709Also printed is the list of Python scripts that were mentioned in
9f050062
DE
5710the @code{.debug_gdb_scripts} section and were either not found
5711(@pxref{dotdebug_gdb_scripts section}) or were not auto-loaded due to
5712@code{auto-load safe-path} rejection (@pxref{Auto-loading}).
329baa95
DE
5713This is useful because their names are not printed when @value{GDBN}
5714tries to load them and fails. There may be many of them, and printing
5715an error message for each one is problematic.
5716
5717If @var{regexp} is supplied only Python scripts with matching names are printed.
5718
5719Example:
5720
5721@smallexample
5722(gdb) info auto-load python-scripts
5723Loaded Script
5724Yes py-section-script.py
5725 full name: /tmp/py-section-script.py
5726No my-foo-pretty-printers.py
5727@end smallexample
5728@end table
5729
9f050062 5730When reading an auto-loaded file or script, @value{GDBN} sets the
329baa95
DE
5731@dfn{current objfile}. This is available via the @code{gdb.current_objfile}
5732function (@pxref{Objfiles In Python}). This can be useful for
5733registering objfile-specific pretty-printers and frame-filters.
5734
5735@node Python modules
5736@subsection Python modules
5737@cindex python modules
5738
5739@value{GDBN} comes with several modules to assist writing Python code.
5740
5741@menu
5742* gdb.printing:: Building and registering pretty-printers.
5743* gdb.types:: Utilities for working with types.
5744* gdb.prompt:: Utilities for prompt value substitution.
5745@end menu
5746
5747@node gdb.printing
5748@subsubsection gdb.printing
5749@cindex gdb.printing
5750
5751This module provides a collection of utilities for working with
5752pretty-printers.
5753
5754@table @code
5755@item PrettyPrinter (@var{name}, @var{subprinters}=None)
5756This class specifies the API that makes @samp{info pretty-printer},
5757@samp{enable pretty-printer} and @samp{disable pretty-printer} work.
5758Pretty-printers should generally inherit from this class.
5759
5760@item SubPrettyPrinter (@var{name})
5761For printers that handle multiple types, this class specifies the
5762corresponding API for the subprinters.
5763
5764@item RegexpCollectionPrettyPrinter (@var{name})
5765Utility class for handling multiple printers, all recognized via
5766regular expressions.
5767@xref{Writing a Pretty-Printer}, for an example.
5768
5769@item FlagEnumerationPrinter (@var{name})
5770A pretty-printer which handles printing of @code{enum} values. Unlike
5771@value{GDBN}'s built-in @code{enum} printing, this printer attempts to
5772work properly when there is some overlap between the enumeration
697aa1b7
EZ
5773constants. The argument @var{name} is the name of the printer and
5774also the name of the @code{enum} type to look up.
329baa95
DE
5775
5776@item register_pretty_printer (@var{obj}, @var{printer}, @var{replace}=False)
5777Register @var{printer} with the pretty-printer list of @var{obj}.
5778If @var{replace} is @code{True} then any existing copy of the printer
5779is replaced. Otherwise a @code{RuntimeError} exception is raised
5780if a printer with the same name already exists.
5781@end table
5782
5783@node gdb.types
5784@subsubsection gdb.types
5785@cindex gdb.types
5786
5787This module provides a collection of utilities for working with
5788@code{gdb.Type} objects.
5789
5790@table @code
5791@item get_basic_type (@var{type})
5792Return @var{type} with const and volatile qualifiers stripped,
5793and with typedefs and C@t{++} references converted to the underlying type.
5794
5795C@t{++} example:
5796
5797@smallexample
5798typedef const int const_int;
5799const_int foo (3);
5800const_int& foo_ref (foo);
5801int main () @{ return 0; @}
5802@end smallexample
5803
5804Then in gdb:
5805
5806@smallexample
5807(gdb) start
5808(gdb) python import gdb.types
5809(gdb) python foo_ref = gdb.parse_and_eval("foo_ref")
5810(gdb) python print gdb.types.get_basic_type(foo_ref.type)
5811int
5812@end smallexample
5813
5814@item has_field (@var{type}, @var{field})
5815Return @code{True} if @var{type}, assumed to be a type with fields
5816(e.g., a structure or union), has field @var{field}.
5817
5818@item make_enum_dict (@var{enum_type})
5819Return a Python @code{dictionary} type produced from @var{enum_type}.
5820
5821@item deep_items (@var{type})
5822Returns a Python iterator similar to the standard
5823@code{gdb.Type.iteritems} method, except that the iterator returned
5824by @code{deep_items} will recursively traverse anonymous struct or
5825union fields. For example:
5826
5827@smallexample
5828struct A
5829@{
5830 int a;
5831 union @{
5832 int b0;
5833 int b1;
5834 @};
5835@};
5836@end smallexample
5837
5838@noindent
5839Then in @value{GDBN}:
5840@smallexample
5841(@value{GDBP}) python import gdb.types
5842(@value{GDBP}) python struct_a = gdb.lookup_type("struct A")
5843(@value{GDBP}) python print struct_a.keys ()
5844@{['a', '']@}
5845(@value{GDBP}) python print [k for k,v in gdb.types.deep_items(struct_a)]
5846@{['a', 'b0', 'b1']@}
5847@end smallexample
5848
5849@item get_type_recognizers ()
5850Return a list of the enabled type recognizers for the current context.
5851This is called by @value{GDBN} during the type-printing process
5852(@pxref{Type Printing API}).
5853
5854@item apply_type_recognizers (recognizers, type_obj)
5855Apply the type recognizers, @var{recognizers}, to the type object
5856@var{type_obj}. If any recognizer returns a string, return that
5857string. Otherwise, return @code{None}. This is called by
5858@value{GDBN} during the type-printing process (@pxref{Type Printing
5859API}).
5860
5861@item register_type_printer (locus, printer)
697aa1b7
EZ
5862This is a convenience function to register a type printer
5863@var{printer}. The printer must implement the type printer protocol.
5864The @var{locus} argument is either a @code{gdb.Objfile}, in which case
5865the printer is registered with that objfile; a @code{gdb.Progspace},
5866in which case the printer is registered with that progspace; or
5867@code{None}, in which case the printer is registered globally.
329baa95
DE
5868
5869@item TypePrinter
5870This is a base class that implements the type printer protocol. Type
5871printers are encouraged, but not required, to derive from this class.
5872It defines a constructor:
5873
5874@defmethod TypePrinter __init__ (self, name)
5875Initialize the type printer with the given name. The new printer
5876starts in the enabled state.
5877@end defmethod
5878
5879@end table
5880
5881@node gdb.prompt
5882@subsubsection gdb.prompt
5883@cindex gdb.prompt
5884
5885This module provides a method for prompt value-substitution.
5886
5887@table @code
5888@item substitute_prompt (@var{string})
5889Return @var{string} with escape sequences substituted by values. Some
5890escape sequences take arguments. You can specify arguments inside
5891``@{@}'' immediately following the escape sequence.
5892
5893The escape sequences you can pass to this function are:
5894
5895@table @code
5896@item \\
5897Substitute a backslash.
5898@item \e
5899Substitute an ESC character.
5900@item \f
5901Substitute the selected frame; an argument names a frame parameter.
5902@item \n
5903Substitute a newline.
5904@item \p
5905Substitute a parameter's value; the argument names the parameter.
5906@item \r
5907Substitute a carriage return.
5908@item \t
5909Substitute the selected thread; an argument names a thread parameter.
5910@item \v
5911Substitute the version of GDB.
5912@item \w
5913Substitute the current working directory.
5914@item \[
5915Begin a sequence of non-printing characters. These sequences are
5916typically used with the ESC character, and are not counted in the string
5917length. Example: ``\[\e[0;34m\](gdb)\[\e[0m\]'' will return a
5918blue-colored ``(gdb)'' prompt where the length is five.
5919@item \]
5920End a sequence of non-printing characters.
5921@end table
5922
5923For example:
5924
5925@smallexample
77bb17b6 5926substitute_prompt ("frame: \f, args: \p@{print frame-arguments@}")
329baa95
DE
5927@end smallexample
5928
5929@exdent will return the string:
5930
5931@smallexample
77bb17b6 5932"frame: main, args: scalars"
329baa95
DE
5933@end smallexample
5934@end table
This page took 0.743076 seconds and 4 git commands to generate.