Xmethod support in Python.
[deliverable/binutils-gdb.git] / gdb / doc / python.texi
CommitLineData
329baa95
DE
1@c Copyright (C) 2008-2014 Free Software Foundation, Inc.
2@c Permission is granted to copy, distribute and/or modify this document
3@c under the terms of the GNU Free Documentation License, Version 1.3 or
4@c any later version published by the Free Software Foundation; with the
5@c Invariant Sections being ``Free Software'' and ``Free Software Needs
6@c Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,''
7@c and with the Back-Cover Texts as in (a) below.
8@c
9@c (a) The FSF's Back-Cover Text is: ``You are free to copy and modify
10@c this GNU Manual. Buying copies from GNU Press supports the FSF in
11@c developing GNU and promoting software freedom.''
12
13@node Python
14@section Extending @value{GDBN} using Python
15@cindex python scripting
16@cindex scripting with python
17
18You can extend @value{GDBN} using the @uref{http://www.python.org/,
19Python programming language}. This feature is available only if
20@value{GDBN} was configured using @option{--with-python}.
21
22@cindex python directory
23Python scripts used by @value{GDBN} should be installed in
24@file{@var{data-directory}/python}, where @var{data-directory} is
25the data directory as determined at @value{GDBN} startup (@pxref{Data Files}).
26This directory, known as the @dfn{python directory},
27is automatically added to the Python Search Path in order to allow
28the Python interpreter to locate all scripts installed at this location.
29
30Additionally, @value{GDBN} commands and convenience functions which
31are written in Python and are located in the
32@file{@var{data-directory}/python/gdb/command} or
33@file{@var{data-directory}/python/gdb/function} directories are
34automatically imported when @value{GDBN} starts.
35
36@menu
37* Python Commands:: Accessing Python from @value{GDBN}.
38* Python API:: Accessing @value{GDBN} from Python.
39* Python Auto-loading:: Automatically loading Python code.
40* Python modules:: Python modules provided by @value{GDBN}.
41@end menu
42
43@node Python Commands
44@subsection Python Commands
45@cindex python commands
46@cindex commands to access python
47
48@value{GDBN} provides two commands for accessing the Python interpreter,
49and one related setting:
50
51@table @code
52@kindex python-interactive
53@kindex pi
54@item python-interactive @r{[}@var{command}@r{]}
55@itemx pi @r{[}@var{command}@r{]}
56Without an argument, the @code{python-interactive} command can be used
57to start an interactive Python prompt. To return to @value{GDBN},
58type the @code{EOF} character (e.g., @kbd{Ctrl-D} on an empty prompt).
59
60Alternatively, a single-line Python command can be given as an
61argument and evaluated. If the command is an expression, the result
62will be printed; otherwise, nothing will be printed. For example:
63
64@smallexample
65(@value{GDBP}) python-interactive 2 + 3
665
67@end smallexample
68
69@kindex python
70@kindex py
71@item python @r{[}@var{command}@r{]}
72@itemx py @r{[}@var{command}@r{]}
73The @code{python} command can be used to evaluate Python code.
74
75If given an argument, the @code{python} command will evaluate the
76argument as a Python command. For example:
77
78@smallexample
79(@value{GDBP}) python print 23
8023
81@end smallexample
82
83If you do not provide an argument to @code{python}, it will act as a
84multi-line command, like @code{define}. In this case, the Python
85script is made up of subsequent command lines, given after the
86@code{python} command. This command list is terminated using a line
87containing @code{end}. For example:
88
89@smallexample
90(@value{GDBP}) python
91Type python script
92End with a line saying just "end".
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}.
116
117@item python execfile ("script-name")
118This method is based on the @code{execfile} Python built-in function,
119and thus is always available.
120@end table
121
122@node Python API
123@subsection Python API
124@cindex python api
125@cindex programming in python
126
127You can get quick online help for @value{GDBN}'s Python API by issuing
128the command @w{@kbd{python help (gdb)}}.
129
130Functions and methods which have two or more optional arguments allow
131them to be specified using keyword syntax. This allows passing some
132optional arguments while skipping others. Example:
133@w{@code{gdb.some_function ('foo', bar = 1, baz = 2)}}.
134
135@menu
136* Basic Python:: Basic Python Functions.
137* Exception Handling:: How Python exceptions are translated.
138* Values From Inferior:: Python representation of values.
139* Types In Python:: Python representation of types.
140* Pretty Printing API:: Pretty-printing values.
141* Selecting Pretty-Printers:: How GDB chooses a pretty-printer.
142* Writing a Pretty-Printer:: Writing a Pretty-Printer.
143* Type Printing API:: Pretty-printing types.
144* Frame Filter API:: Filtering Frames.
145* Frame Decorator API:: Decorating Frames.
146* Writing a Frame Filter:: Writing a Frame Filter.
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.
150* Commands In Python:: Implementing new commands in Python.
151* Parameters In Python:: Adding new @value{GDBN} parameters.
152* Functions In Python:: Writing new convenience functions.
153* Progspaces In Python:: Program spaces.
154* Objfiles In Python:: Object files.
155* Frames In Python:: Accessing inferior stack frames from Python.
156* Blocks In Python:: Accessing blocks from Python.
157* Symbols In Python:: Python representation of symbols.
158* Symbol Tables In Python:: Python representation of symbol tables.
159* Line Tables In Python:: Python representation of line tables.
160* Breakpoints In Python:: Manipulating breakpoints using Python.
161* Finish Breakpoints in Python:: Setting Breakpoints on function return
162 using Python.
163* Lazy Strings In Python:: Python representation of lazy strings.
164* Architectures In Python:: Python representation of architectures.
165@end menu
166
167@node Basic Python
168@subsubsection Basic Python
169
170@cindex python stdout
171@cindex python pagination
172At startup, @value{GDBN} overrides Python's @code{sys.stdout} and
173@code{sys.stderr} to print using @value{GDBN}'s output-paging streams.
174A Python program which outputs to one of these streams may have its
175output interrupted by the user (@pxref{Screen Size}). In this
176situation, a Python @code{KeyboardInterrupt} exception is thrown.
177
178Some care must be taken when writing Python code to run in
179@value{GDBN}. Two things worth noting in particular:
180
181@itemize @bullet
182@item
183@value{GDBN} install handlers for @code{SIGCHLD} and @code{SIGINT}.
184Python code must not override these, or even change the options using
185@code{sigaction}. If your program changes the handling of these
186signals, @value{GDBN} will most likely stop working correctly. Note
187that it is unfortunately common for GUI toolkits to install a
188@code{SIGCHLD} handler.
189
190@item
191@value{GDBN} takes care to mark its internal file descriptors as
192close-on-exec. However, this cannot be done in a thread-safe way on
193all platforms. Your Python programs should be aware of this and
194should both create new file descriptors with the close-on-exec flag
195set and arrange to close unneeded file descriptors before starting a
196child process.
197@end itemize
198
199@cindex python functions
200@cindex python module
201@cindex gdb module
202@value{GDBN} introduces a new Python module, named @code{gdb}. All
203methods and classes added by @value{GDBN} are placed in this module.
204@value{GDBN} automatically @code{import}s the @code{gdb} module for
205use in all scripts evaluated by the @code{python} command.
206
207@findex gdb.PYTHONDIR
208@defvar gdb.PYTHONDIR
209A string containing the python directory (@pxref{Python}).
210@end defvar
211
212@findex gdb.execute
213@defun gdb.execute (command @r{[}, from_tty @r{[}, to_string@r{]]})
214Evaluate @var{command}, a string, as a @value{GDBN} CLI command.
215If a GDB exception happens while @var{command} runs, it is
216translated as described in @ref{Exception Handling,,Exception Handling}.
217
697aa1b7 218The @var{from_tty} flag specifies whether @value{GDBN} ought to consider this
329baa95
DE
219command as having originated from the user invoking it interactively.
220It must be a boolean value. If omitted, it defaults to @code{False}.
221
222By default, any output produced by @var{command} is sent to
b3ce5e5f
DE
223@value{GDBN}'s standard output (and to the log output if logging is
224turned on). If the @var{to_string} parameter is
329baa95
DE
225@code{True}, then output will be collected by @code{gdb.execute} and
226returned as a string. The default is @code{False}, in which case the
227return value is @code{None}. If @var{to_string} is @code{True}, the
228@value{GDBN} virtual terminal will be temporarily set to unlimited width
229and height, and its pagination will be disabled; @pxref{Screen Size}.
230@end defun
231
232@findex gdb.breakpoints
233@defun gdb.breakpoints ()
234Return a sequence holding all of @value{GDBN}'s breakpoints.
235@xref{Breakpoints In Python}, for more information.
236@end defun
237
238@findex gdb.parameter
239@defun gdb.parameter (parameter)
697aa1b7
EZ
240Return the value of a @value{GDBN} @var{parameter} given by its name,
241a string; the parameter name string may contain spaces if the parameter has a
242multi-part name. For example, @samp{print object} is a valid
243parameter name.
329baa95
DE
244
245If the named parameter does not exist, this function throws a
246@code{gdb.error} (@pxref{Exception Handling}). Otherwise, the
247parameter's value is converted to a Python value of the appropriate
248type, and returned.
249@end defun
250
251@findex gdb.history
252@defun gdb.history (number)
253Return a value from @value{GDBN}'s value history (@pxref{Value
697aa1b7 254History}). The @var{number} argument indicates which history element to return.
329baa95
DE
255If @var{number} is negative, then @value{GDBN} will take its absolute value
256and count backward from the last element (i.e., the most recent element) to
257find the value to return. If @var{number} is zero, then @value{GDBN} will
258return the most recent element. If the element specified by @var{number}
259doesn't exist in the value history, a @code{gdb.error} exception will be
260raised.
261
262If no exception is raised, the return value is always an instance of
263@code{gdb.Value} (@pxref{Values From Inferior}).
264@end defun
265
266@findex gdb.parse_and_eval
267@defun gdb.parse_and_eval (expression)
697aa1b7
EZ
268Parse @var{expression}, which must be a string, as an expression in
269the current language, evaluate it, and return the result as a
270@code{gdb.Value}.
329baa95
DE
271
272This function can be useful when implementing a new command
273(@pxref{Commands In Python}), as it provides a way to parse the
274command's argument as an expression. It is also useful simply to
275compute values, for example, it is the only way to get the value of a
276convenience variable (@pxref{Convenience Vars}) as a @code{gdb.Value}.
277@end defun
278
279@findex gdb.find_pc_line
280@defun gdb.find_pc_line (pc)
281Return the @code{gdb.Symtab_and_line} object corresponding to the
282@var{pc} value. @xref{Symbol Tables In Python}. If an invalid
283value of @var{pc} is passed as an argument, then the @code{symtab} and
284@code{line} attributes of the returned @code{gdb.Symtab_and_line} object
285will be @code{None} and 0 respectively.
286@end defun
287
288@findex gdb.post_event
289@defun gdb.post_event (event)
290Put @var{event}, a callable object taking no arguments, into
291@value{GDBN}'s internal event queue. This callable will be invoked at
292some later point, during @value{GDBN}'s event processing. Events
293posted using @code{post_event} will be run in the order in which they
294were posted; however, there is no way to know when they will be
295processed relative to other events inside @value{GDBN}.
296
297@value{GDBN} is not thread-safe. If your Python program uses multiple
298threads, you must be careful to only call @value{GDBN}-specific
b3ce5e5f 299functions in the @value{GDBN} thread. @code{post_event} ensures
329baa95
DE
300this. For example:
301
302@smallexample
303(@value{GDBP}) python
304>import threading
305>
306>class Writer():
307> def __init__(self, message):
308> self.message = message;
309> def __call__(self):
310> gdb.write(self.message)
311>
312>class MyThread1 (threading.Thread):
313> def run (self):
314> gdb.post_event(Writer("Hello "))
315>
316>class MyThread2 (threading.Thread):
317> def run (self):
318> gdb.post_event(Writer("World\n"))
319>
320>MyThread1().start()
321>MyThread2().start()
322>end
323(@value{GDBP}) Hello World
324@end smallexample
325@end defun
326
327@findex gdb.write
328@defun gdb.write (string @r{[}, stream{]})
329Print a string to @value{GDBN}'s paginated output stream. The
330optional @var{stream} determines the stream to print to. The default
331stream is @value{GDBN}'s standard output stream. Possible stream
332values are:
333
334@table @code
335@findex STDOUT
336@findex gdb.STDOUT
337@item gdb.STDOUT
338@value{GDBN}'s standard output stream.
339
340@findex STDERR
341@findex gdb.STDERR
342@item gdb.STDERR
343@value{GDBN}'s standard error stream.
344
345@findex STDLOG
346@findex gdb.STDLOG
347@item gdb.STDLOG
348@value{GDBN}'s log stream (@pxref{Logging Output}).
349@end table
350
351Writing to @code{sys.stdout} or @code{sys.stderr} will automatically
352call this function and will automatically direct the output to the
353relevant stream.
354@end defun
355
356@findex gdb.flush
357@defun gdb.flush ()
358Flush the buffer of a @value{GDBN} paginated stream so that the
359contents are displayed immediately. @value{GDBN} will flush the
360contents of a stream automatically when it encounters a newline in the
361buffer. The optional @var{stream} determines the stream to flush. The
362default stream is @value{GDBN}'s standard output stream. Possible
363stream values are:
364
365@table @code
366@findex STDOUT
367@findex gdb.STDOUT
368@item gdb.STDOUT
369@value{GDBN}'s standard output stream.
370
371@findex STDERR
372@findex gdb.STDERR
373@item gdb.STDERR
374@value{GDBN}'s standard error stream.
375
376@findex STDLOG
377@findex gdb.STDLOG
378@item gdb.STDLOG
379@value{GDBN}'s log stream (@pxref{Logging Output}).
380
381@end table
382
383Flushing @code{sys.stdout} or @code{sys.stderr} will automatically
384call this function for the relevant stream.
385@end defun
386
387@findex gdb.target_charset
388@defun gdb.target_charset ()
389Return the name of the current target character set (@pxref{Character
390Sets}). This differs from @code{gdb.parameter('target-charset')} in
391that @samp{auto} is never returned.
392@end defun
393
394@findex gdb.target_wide_charset
395@defun gdb.target_wide_charset ()
396Return the name of the current target wide character set
397(@pxref{Character Sets}). This differs from
398@code{gdb.parameter('target-wide-charset')} in that @samp{auto} is
399never returned.
400@end defun
401
402@findex gdb.solib_name
403@defun gdb.solib_name (address)
404Return the name of the shared library holding the given @var{address}
405as a string, or @code{None}.
406@end defun
407
408@findex gdb.decode_line
409@defun gdb.decode_line @r{[}expression@r{]}
410Return locations of the line specified by @var{expression}, or of the
411current line if no argument was given. This function returns a Python
412tuple containing two elements. The first element contains a string
413holding any unparsed section of @var{expression} (or @code{None} if
414the expression has been fully parsed). The second element contains
415either @code{None} or another tuple that contains all the locations
416that match the expression represented as @code{gdb.Symtab_and_line}
417objects (@pxref{Symbol Tables In Python}). If @var{expression} is
418provided, it is decoded the way that @value{GDBN}'s inbuilt
419@code{break} or @code{edit} commands do (@pxref{Specify Location}).
420@end defun
421
422@defun gdb.prompt_hook (current_prompt)
423@anchor{prompt_hook}
424
425If @var{prompt_hook} is callable, @value{GDBN} will call the method
426assigned to this operation before a prompt is displayed by
427@value{GDBN}.
428
429The parameter @code{current_prompt} contains the current @value{GDBN}
430prompt. This method must return a Python string, or @code{None}. If
431a string is returned, the @value{GDBN} prompt will be set to that
432string. If @code{None} is returned, @value{GDBN} will continue to use
433the current prompt.
434
435Some prompts cannot be substituted in @value{GDBN}. Secondary prompts
436such as those used by readline for command input, and annotation
437related prompts are prohibited from being changed.
438@end defun
439
440@node Exception Handling
441@subsubsection Exception Handling
442@cindex python exceptions
443@cindex exceptions, python
444
445When executing the @code{python} command, Python exceptions
446uncaught within the Python code are translated to calls to
447@value{GDBN} error-reporting mechanism. If the command that called
448@code{python} does not handle the error, @value{GDBN} will
449terminate it and print an error message containing the Python
450exception name, the associated value, and the Python call stack
451backtrace at the point where the exception was raised. Example:
452
453@smallexample
454(@value{GDBP}) python print foo
455Traceback (most recent call last):
456 File "<string>", line 1, in <module>
457NameError: name 'foo' is not defined
458@end smallexample
459
460@value{GDBN} errors that happen in @value{GDBN} commands invoked by
461Python code are converted to Python exceptions. The type of the
462Python exception depends on the error.
463
464@ftable @code
465@item gdb.error
466This is the base class for most exceptions generated by @value{GDBN}.
467It is derived from @code{RuntimeError}, for compatibility with earlier
468versions of @value{GDBN}.
469
470If an error occurring in @value{GDBN} does not fit into some more
471specific category, then the generated exception will have this type.
472
473@item gdb.MemoryError
474This is a subclass of @code{gdb.error} which is thrown when an
475operation tried to access invalid memory in the inferior.
476
477@item KeyboardInterrupt
478User interrupt (via @kbd{C-c} or by typing @kbd{q} at a pagination
479prompt) is translated to a Python @code{KeyboardInterrupt} exception.
480@end ftable
481
482In all cases, your exception handler will see the @value{GDBN} error
483message as its value and the Python call stack backtrace at the Python
484statement closest to where the @value{GDBN} error occured as the
485traceback.
486
487@findex gdb.GdbError
488When implementing @value{GDBN} commands in Python via @code{gdb.Command},
489it is useful to be able to throw an exception that doesn't cause a
490traceback to be printed. For example, the user may have invoked the
491command incorrectly. Use the @code{gdb.GdbError} exception
492to handle this case. Example:
493
494@smallexample
495(gdb) python
496>class HelloWorld (gdb.Command):
497> """Greet the whole world."""
498> def __init__ (self):
499> super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
500> def invoke (self, args, from_tty):
501> argv = gdb.string_to_argv (args)
502> if len (argv) != 0:
503> raise gdb.GdbError ("hello-world takes no arguments")
504> print "Hello, World!"
505>HelloWorld ()
506>end
507(gdb) hello-world 42
508hello-world takes no arguments
509@end smallexample
510
511@node Values From Inferior
512@subsubsection Values From Inferior
513@cindex values from inferior, with Python
514@cindex python, working with values from inferior
515
516@cindex @code{gdb.Value}
517@value{GDBN} provides values it obtains from the inferior program in
518an object of type @code{gdb.Value}. @value{GDBN} uses this object
519for its internal bookkeeping of the inferior's values, and for
520fetching values when necessary.
521
522Inferior values that are simple scalars can be used directly in
523Python expressions that are valid for the value's data type. Here's
524an example for an integer or floating-point value @code{some_val}:
525
526@smallexample
527bar = some_val + 2
528@end smallexample
529
530@noindent
531As result of this, @code{bar} will also be a @code{gdb.Value} object
f7bd0f78
SC
532whose values are of the same type as those of @code{some_val}. Valid
533Python operations can also be performed on @code{gdb.Value} objects
534representing a @code{struct} or @code{class} object. For such cases,
535the overloaded operator (if present), is used to perform the operation.
536For example, if @code{val1} and @code{val2} are @code{gdb.Value} objects
537representing instances of a @code{class} which overloads the @code{+}
538operator, then one can use the @code{+} operator in their Python script
539as follows:
540
541@smallexample
542val3 = val1 + val2
543@end smallexample
544
545@noindent
546The result of the operation @code{val3} is also a @code{gdb.Value}
547object corresponding to the value returned by the overloaded @code{+}
548operator. In general, overloaded operators are invoked for the
549following operations: @code{+} (binary addition), @code{-} (binary
550subtraction), @code{*} (multiplication), @code{/}, @code{%}, @code{<<},
551@code{>>}, @code{|}, @code{&}, @code{^}.
329baa95
DE
552
553Inferior values that are structures or instances of some class can
554be accessed using the Python @dfn{dictionary syntax}. For example, if
555@code{some_val} is a @code{gdb.Value} instance holding a structure, you
556can access its @code{foo} element with:
557
558@smallexample
559bar = some_val['foo']
560@end smallexample
561
562@cindex getting structure elements using gdb.Field objects as subscripts
563Again, @code{bar} will also be a @code{gdb.Value} object. Structure
564elements can also be accessed by using @code{gdb.Field} objects as
565subscripts (@pxref{Types In Python}, for more information on
566@code{gdb.Field} objects). For example, if @code{foo_field} is a
567@code{gdb.Field} object corresponding to element @code{foo} of the above
568structure, then @code{bar} can also be accessed as follows:
569
570@smallexample
571bar = some_val[foo_field]
572@end smallexample
573
574A @code{gdb.Value} that represents a function can be executed via
575inferior function call. Any arguments provided to the call must match
576the function's prototype, and must be provided in the order specified
577by that prototype.
578
579For example, @code{some_val} is a @code{gdb.Value} instance
580representing a function that takes two integers as arguments. To
581execute this function, call it like so:
582
583@smallexample
584result = some_val (10,20)
585@end smallexample
586
587Any values returned from a function call will be stored as a
588@code{gdb.Value}.
589
590The following attributes are provided:
591
592@defvar Value.address
593If this object is addressable, this read-only attribute holds a
594@code{gdb.Value} object representing the address. Otherwise,
595this attribute holds @code{None}.
596@end defvar
597
598@cindex optimized out value in Python
599@defvar Value.is_optimized_out
600This read-only boolean attribute is true if the compiler optimized out
601this value, thus it is not available for fetching from the inferior.
602@end defvar
603
604@defvar Value.type
605The type of this @code{gdb.Value}. The value of this attribute is a
606@code{gdb.Type} object (@pxref{Types In Python}).
607@end defvar
608
609@defvar Value.dynamic_type
610The dynamic type of this @code{gdb.Value}. This uses C@t{++} run-time
611type information (@acronym{RTTI}) to determine the dynamic type of the
612value. If this value is of class type, it will return the class in
613which the value is embedded, if any. If this value is of pointer or
614reference to a class type, it will compute the dynamic type of the
615referenced object, and return a pointer or reference to that type,
616respectively. In all other cases, it will return the value's static
617type.
618
619Note that this feature will only work when debugging a C@t{++} program
620that includes @acronym{RTTI} for the object in question. Otherwise,
621it will just return the static type of the value as in @kbd{ptype foo}
622(@pxref{Symbols, ptype}).
623@end defvar
624
625@defvar Value.is_lazy
626The value of this read-only boolean attribute is @code{True} if this
627@code{gdb.Value} has not yet been fetched from the inferior.
628@value{GDBN} does not fetch values until necessary, for efficiency.
629For example:
630
631@smallexample
632myval = gdb.parse_and_eval ('somevar')
633@end smallexample
634
635The value of @code{somevar} is not fetched at this time. It will be
636fetched when the value is needed, or when the @code{fetch_lazy}
637method is invoked.
638@end defvar
639
640The following methods are provided:
641
642@defun Value.__init__ (@var{val})
643Many Python values can be converted directly to a @code{gdb.Value} via
644this object initializer. Specifically:
645
646@table @asis
647@item Python boolean
648A Python boolean is converted to the boolean type from the current
649language.
650
651@item Python integer
652A Python integer is converted to the C @code{long} type for the
653current architecture.
654
655@item Python long
656A Python long is converted to the C @code{long long} type for the
657current architecture.
658
659@item Python float
660A Python float is converted to the C @code{double} type for the
661current architecture.
662
663@item Python string
b3ce5e5f
DE
664A Python string is converted to a target string in the current target
665language using the current target encoding.
666If a character cannot be represented in the current target encoding,
667then an exception is thrown.
329baa95
DE
668
669@item @code{gdb.Value}
670If @code{val} is a @code{gdb.Value}, then a copy of the value is made.
671
672@item @code{gdb.LazyString}
673If @code{val} is a @code{gdb.LazyString} (@pxref{Lazy Strings In
674Python}), then the lazy string's @code{value} method is called, and
675its result is used.
676@end table
677@end defun
678
679@defun Value.cast (type)
680Return a new instance of @code{gdb.Value} that is the result of
681casting this instance to the type described by @var{type}, which must
682be a @code{gdb.Type} object. If the cast cannot be performed for some
683reason, this method throws an exception.
684@end defun
685
686@defun Value.dereference ()
687For pointer data types, this method returns a new @code{gdb.Value} object
688whose contents is the object pointed to by the pointer. For example, if
689@code{foo} is a C pointer to an @code{int}, declared in your C program as
690
691@smallexample
692int *foo;
693@end smallexample
694
695@noindent
696then you can use the corresponding @code{gdb.Value} to access what
697@code{foo} points to like this:
698
699@smallexample
700bar = foo.dereference ()
701@end smallexample
702
703The result @code{bar} will be a @code{gdb.Value} object holding the
704value pointed to by @code{foo}.
705
706A similar function @code{Value.referenced_value} exists which also
707returns @code{gdb.Value} objects corresonding to the values pointed to
708by pointer values (and additionally, values referenced by reference
709values). However, the behavior of @code{Value.dereference}
710differs from @code{Value.referenced_value} by the fact that the
711behavior of @code{Value.dereference} is identical to applying the C
712unary operator @code{*} on a given value. For example, consider a
713reference to a pointer @code{ptrref}, declared in your C@t{++} program
714as
715
716@smallexample
717typedef int *intptr;
718...
719int val = 10;
720intptr ptr = &val;
721intptr &ptrref = ptr;
722@end smallexample
723
724Though @code{ptrref} is a reference value, one can apply the method
725@code{Value.dereference} to the @code{gdb.Value} object corresponding
726to it and obtain a @code{gdb.Value} which is identical to that
727corresponding to @code{val}. However, if you apply the method
728@code{Value.referenced_value}, the result would be a @code{gdb.Value}
729object identical to that corresponding to @code{ptr}.
730
731@smallexample
732py_ptrref = gdb.parse_and_eval ("ptrref")
733py_val = py_ptrref.dereference ()
734py_ptr = py_ptrref.referenced_value ()
735@end smallexample
736
737The @code{gdb.Value} object @code{py_val} is identical to that
738corresponding to @code{val}, and @code{py_ptr} is identical to that
739corresponding to @code{ptr}. In general, @code{Value.dereference} can
740be applied whenever the C unary operator @code{*} can be applied
741to the corresponding C value. For those cases where applying both
742@code{Value.dereference} and @code{Value.referenced_value} is allowed,
743the results obtained need not be identical (as we have seen in the above
744example). The results are however identical when applied on
745@code{gdb.Value} objects corresponding to pointers (@code{gdb.Value}
746objects with type code @code{TYPE_CODE_PTR}) in a C/C@t{++} program.
747@end defun
748
749@defun Value.referenced_value ()
750For pointer or reference data types, this method returns a new
751@code{gdb.Value} object corresponding to the value referenced by the
752pointer/reference value. For pointer data types,
753@code{Value.dereference} and @code{Value.referenced_value} produce
754identical results. The difference between these methods is that
755@code{Value.dereference} cannot get the values referenced by reference
756values. For example, consider a reference to an @code{int}, declared
757in your C@t{++} program as
758
759@smallexample
760int val = 10;
761int &ref = val;
762@end smallexample
763
764@noindent
765then applying @code{Value.dereference} to the @code{gdb.Value} object
766corresponding to @code{ref} will result in an error, while applying
767@code{Value.referenced_value} will result in a @code{gdb.Value} object
768identical to that corresponding to @code{val}.
769
770@smallexample
771py_ref = gdb.parse_and_eval ("ref")
772er_ref = py_ref.dereference () # Results in error
773py_val = py_ref.referenced_value () # Returns the referenced value
774@end smallexample
775
776The @code{gdb.Value} object @code{py_val} is identical to that
777corresponding to @code{val}.
778@end defun
779
780@defun Value.dynamic_cast (type)
781Like @code{Value.cast}, but works as if the C@t{++} @code{dynamic_cast}
782operator were used. Consult a C@t{++} reference for details.
783@end defun
784
785@defun Value.reinterpret_cast (type)
786Like @code{Value.cast}, but works as if the C@t{++} @code{reinterpret_cast}
787operator were used. Consult a C@t{++} reference for details.
788@end defun
789
790@defun Value.string (@r{[}encoding@r{[}, errors@r{[}, length@r{]]]})
791If this @code{gdb.Value} represents a string, then this method
792converts the contents to a Python string. Otherwise, this method will
793throw an exception.
794
b3ce5e5f
DE
795Values are interpreted as strings according to the rules of the
796current language. If the optional length argument is given, the
797string will be converted to that length, and will include any embedded
798zeroes that the string may contain. Otherwise, for languages
799where the string is zero-terminated, the entire string will be
800converted.
329baa95 801
b3ce5e5f
DE
802For example, in C-like languages, a value is a string if it is a pointer
803to or an array of characters or ints of type @code{wchar_t}, @code{char16_t},
804or @code{char32_t}.
329baa95
DE
805
806If the optional @var{encoding} argument is given, it must be a string
807naming the encoding of the string in the @code{gdb.Value}, such as
808@code{"ascii"}, @code{"iso-8859-6"} or @code{"utf-8"}. It accepts
809the same encodings as the corresponding argument to Python's
810@code{string.decode} method, and the Python codec machinery will be used
811to convert the string. If @var{encoding} is not given, or if
812@var{encoding} is the empty string, then either the @code{target-charset}
813(@pxref{Character Sets}) will be used, or a language-specific encoding
814will be used, if the current language is able to supply one.
815
816The optional @var{errors} argument is the same as the corresponding
817argument to Python's @code{string.decode} method.
818
819If the optional @var{length} argument is given, the string will be
820fetched and converted to the given length.
821@end defun
822
823@defun Value.lazy_string (@r{[}encoding @r{[}, length@r{]]})
824If this @code{gdb.Value} represents a string, then this method
825converts the contents to a @code{gdb.LazyString} (@pxref{Lazy Strings
826In Python}). Otherwise, this method will throw an exception.
827
828If the optional @var{encoding} argument is given, it must be a string
829naming the encoding of the @code{gdb.LazyString}. Some examples are:
830@samp{ascii}, @samp{iso-8859-6} or @samp{utf-8}. If the
831@var{encoding} argument is an encoding that @value{GDBN} does
832recognize, @value{GDBN} will raise an error.
833
834When a lazy string is printed, the @value{GDBN} encoding machinery is
835used to convert the string during printing. If the optional
836@var{encoding} argument is not provided, or is an empty string,
837@value{GDBN} will automatically select the encoding most suitable for
838the string type. For further information on encoding in @value{GDBN}
839please see @ref{Character Sets}.
840
841If the optional @var{length} argument is given, the string will be
842fetched and encoded to the length of characters specified. If
843the @var{length} argument is not provided, the string will be fetched
844and encoded until a null of appropriate width is found.
845@end defun
846
847@defun Value.fetch_lazy ()
848If the @code{gdb.Value} object is currently a lazy value
849(@code{gdb.Value.is_lazy} is @code{True}), then the value is
850fetched from the inferior. Any errors that occur in the process
851will produce a Python exception.
852
853If the @code{gdb.Value} object is not a lazy value, this method
854has no effect.
855
856This method does not return a value.
857@end defun
858
859
860@node Types In Python
861@subsubsection Types In Python
862@cindex types in Python
863@cindex Python, working with types
864
865@tindex gdb.Type
866@value{GDBN} represents types from the inferior using the class
867@code{gdb.Type}.
868
869The following type-related functions are available in the @code{gdb}
870module:
871
872@findex gdb.lookup_type
873@defun gdb.lookup_type (name @r{[}, block@r{]})
697aa1b7 874This function looks up a type by its @var{name}, which must be a string.
329baa95
DE
875
876If @var{block} is given, then @var{name} is looked up in that scope.
877Otherwise, it is searched for globally.
878
879Ordinarily, this function will return an instance of @code{gdb.Type}.
880If the named type cannot be found, it will throw an exception.
881@end defun
882
883If the type is a structure or class type, or an enum type, the fields
884of that type can be accessed using the Python @dfn{dictionary syntax}.
885For example, if @code{some_type} is a @code{gdb.Type} instance holding
886a structure type, you can access its @code{foo} field with:
887
888@smallexample
889bar = some_type['foo']
890@end smallexample
891
892@code{bar} will be a @code{gdb.Field} object; see below under the
893description of the @code{Type.fields} method for a description of the
894@code{gdb.Field} class.
895
896An instance of @code{Type} has the following attributes:
897
898@defvar Type.code
899The type code for this type. The type code will be one of the
900@code{TYPE_CODE_} constants defined below.
901@end defvar
902
903@defvar Type.name
904The name of this type. If this type has no name, then @code{None}
905is returned.
906@end defvar
907
908@defvar Type.sizeof
909The size of this type, in target @code{char} units. Usually, a
910target's @code{char} type will be an 8-bit byte. However, on some
911unusual platforms, this type may have a different size.
912@end defvar
913
914@defvar Type.tag
915The tag name for this type. The tag name is the name after
916@code{struct}, @code{union}, or @code{enum} in C and C@t{++}; not all
917languages have this concept. If this type has no tag name, then
918@code{None} is returned.
919@end defvar
920
921The following methods are provided:
922
923@defun Type.fields ()
924For structure and union types, this method returns the fields. Range
925types have two fields, the minimum and maximum values. Enum types
926have one field per enum constant. Function and method types have one
927field per parameter. The base types of C@t{++} classes are also
928represented as fields. If the type has no fields, or does not fit
929into one of these categories, an empty sequence will be returned.
930
931Each field is a @code{gdb.Field} object, with some pre-defined attributes:
932@table @code
933@item bitpos
934This attribute is not available for @code{enum} or @code{static}
935(as in C@t{++} or Java) fields. The value is the position, counting
936in bits, from the start of the containing type.
937
938@item enumval
939This attribute is only available for @code{enum} fields, and its value
940is the enumeration member's integer representation.
941
942@item name
943The name of the field, or @code{None} for anonymous fields.
944
945@item artificial
946This is @code{True} if the field is artificial, usually meaning that
947it was provided by the compiler and not the user. This attribute is
948always provided, and is @code{False} if the field is not artificial.
949
950@item is_base_class
951This is @code{True} if the field represents a base class of a C@t{++}
952structure. This attribute is always provided, and is @code{False}
953if the field is not a base class of the type that is the argument of
954@code{fields}, or if that type was not a C@t{++} class.
955
956@item bitsize
957If the field is packed, or is a bitfield, then this will have a
958non-zero value, which is the size of the field in bits. Otherwise,
959this will be zero; in this case the field's size is given by its type.
960
961@item type
962The type of the field. This is usually an instance of @code{Type},
963but it can be @code{None} in some situations.
964
965@item parent_type
966The type which contains this field. This is an instance of
967@code{gdb.Type}.
968@end table
969@end defun
970
971@defun Type.array (@var{n1} @r{[}, @var{n2}@r{]})
972Return a new @code{gdb.Type} object which represents an array of this
973type. If one argument is given, it is the inclusive upper bound of
974the array; in this case the lower bound is zero. If two arguments are
975given, the first argument is the lower bound of the array, and the
976second argument is the upper bound of the array. An array's length
977must not be negative, but the bounds can be.
978@end defun
979
980@defun Type.vector (@var{n1} @r{[}, @var{n2}@r{]})
981Return a new @code{gdb.Type} object which represents a vector of this
982type. If one argument is given, it is the inclusive upper bound of
983the vector; in this case the lower bound is zero. If two arguments are
984given, the first argument is the lower bound of the vector, and the
985second argument is the upper bound of the vector. A vector's length
986must not be negative, but the bounds can be.
987
988The difference between an @code{array} and a @code{vector} is that
989arrays behave like in C: when used in expressions they decay to a pointer
990to the first element whereas vectors are treated as first class values.
991@end defun
992
993@defun Type.const ()
994Return a new @code{gdb.Type} object which represents a
995@code{const}-qualified variant of this type.
996@end defun
997
998@defun Type.volatile ()
999Return a new @code{gdb.Type} object which represents a
1000@code{volatile}-qualified variant of this type.
1001@end defun
1002
1003@defun Type.unqualified ()
1004Return a new @code{gdb.Type} object which represents an unqualified
1005variant of this type. That is, the result is neither @code{const} nor
1006@code{volatile}.
1007@end defun
1008
1009@defun Type.range ()
1010Return a Python @code{Tuple} object that contains two elements: the
1011low bound of the argument type and the high bound of that type. If
1012the type does not have a range, @value{GDBN} will raise a
1013@code{gdb.error} exception (@pxref{Exception Handling}).
1014@end defun
1015
1016@defun Type.reference ()
1017Return a new @code{gdb.Type} object which represents a reference to this
1018type.
1019@end defun
1020
1021@defun Type.pointer ()
1022Return a new @code{gdb.Type} object which represents a pointer to this
1023type.
1024@end defun
1025
1026@defun Type.strip_typedefs ()
1027Return a new @code{gdb.Type} that represents the real type,
1028after removing all layers of typedefs.
1029@end defun
1030
1031@defun Type.target ()
1032Return a new @code{gdb.Type} object which represents the target type
1033of this type.
1034
1035For a pointer type, the target type is the type of the pointed-to
1036object. For an array type (meaning C-like arrays), the target type is
1037the type of the elements of the array. For a function or method type,
1038the target type is the type of the return value. For a complex type,
1039the target type is the type of the elements. For a typedef, the
1040target type is the aliased type.
1041
1042If the type does not have a target, this method will throw an
1043exception.
1044@end defun
1045
1046@defun Type.template_argument (n @r{[}, block@r{]})
1047If this @code{gdb.Type} is an instantiation of a template, this will
1048return a new @code{gdb.Type} which represents the type of the
1049@var{n}th template argument.
1050
1051If this @code{gdb.Type} is not a template type, this will throw an
1052exception. Ordinarily, only C@t{++} code will have template types.
1053
1054If @var{block} is given, then @var{name} is looked up in that scope.
1055Otherwise, it is searched for globally.
1056@end defun
1057
1058
1059Each type has a code, which indicates what category this type falls
1060into. The available type categories are represented by constants
1061defined in the @code{gdb} module:
1062
b3ce5e5f
DE
1063@vtable @code
1064@vindex TYPE_CODE_PTR
329baa95
DE
1065@item gdb.TYPE_CODE_PTR
1066The type is a pointer.
1067
b3ce5e5f 1068@vindex TYPE_CODE_ARRAY
329baa95
DE
1069@item gdb.TYPE_CODE_ARRAY
1070The type is an array.
1071
b3ce5e5f 1072@vindex TYPE_CODE_STRUCT
329baa95
DE
1073@item gdb.TYPE_CODE_STRUCT
1074The type is a structure.
1075
b3ce5e5f 1076@vindex TYPE_CODE_UNION
329baa95
DE
1077@item gdb.TYPE_CODE_UNION
1078The type is a union.
1079
b3ce5e5f 1080@vindex TYPE_CODE_ENUM
329baa95
DE
1081@item gdb.TYPE_CODE_ENUM
1082The type is an enum.
1083
b3ce5e5f 1084@vindex TYPE_CODE_FLAGS
329baa95
DE
1085@item gdb.TYPE_CODE_FLAGS
1086A bit flags type, used for things such as status registers.
1087
b3ce5e5f 1088@vindex TYPE_CODE_FUNC
329baa95
DE
1089@item gdb.TYPE_CODE_FUNC
1090The type is a function.
1091
b3ce5e5f 1092@vindex TYPE_CODE_INT
329baa95
DE
1093@item gdb.TYPE_CODE_INT
1094The type is an integer type.
1095
b3ce5e5f 1096@vindex TYPE_CODE_FLT
329baa95
DE
1097@item gdb.TYPE_CODE_FLT
1098A floating point type.
1099
b3ce5e5f 1100@vindex TYPE_CODE_VOID
329baa95
DE
1101@item gdb.TYPE_CODE_VOID
1102The special type @code{void}.
1103
b3ce5e5f 1104@vindex TYPE_CODE_SET
329baa95
DE
1105@item gdb.TYPE_CODE_SET
1106A Pascal set type.
1107
b3ce5e5f 1108@vindex TYPE_CODE_RANGE
329baa95
DE
1109@item gdb.TYPE_CODE_RANGE
1110A range type, that is, an integer type with bounds.
1111
b3ce5e5f 1112@vindex TYPE_CODE_STRING
329baa95
DE
1113@item gdb.TYPE_CODE_STRING
1114A string type. Note that this is only used for certain languages with
1115language-defined string types; C strings are not represented this way.
1116
b3ce5e5f 1117@vindex TYPE_CODE_BITSTRING
329baa95
DE
1118@item gdb.TYPE_CODE_BITSTRING
1119A string of bits. It is deprecated.
1120
b3ce5e5f 1121@vindex TYPE_CODE_ERROR
329baa95
DE
1122@item gdb.TYPE_CODE_ERROR
1123An unknown or erroneous type.
1124
b3ce5e5f 1125@vindex TYPE_CODE_METHOD
329baa95
DE
1126@item gdb.TYPE_CODE_METHOD
1127A method type, as found in C@t{++} or Java.
1128
b3ce5e5f 1129@vindex TYPE_CODE_METHODPTR
329baa95
DE
1130@item gdb.TYPE_CODE_METHODPTR
1131A pointer-to-member-function.
1132
b3ce5e5f 1133@vindex TYPE_CODE_MEMBERPTR
329baa95
DE
1134@item gdb.TYPE_CODE_MEMBERPTR
1135A pointer-to-member.
1136
b3ce5e5f 1137@vindex TYPE_CODE_REF
329baa95
DE
1138@item gdb.TYPE_CODE_REF
1139A reference type.
1140
b3ce5e5f 1141@vindex TYPE_CODE_CHAR
329baa95
DE
1142@item gdb.TYPE_CODE_CHAR
1143A character type.
1144
b3ce5e5f 1145@vindex TYPE_CODE_BOOL
329baa95
DE
1146@item gdb.TYPE_CODE_BOOL
1147A boolean type.
1148
b3ce5e5f 1149@vindex TYPE_CODE_COMPLEX
329baa95
DE
1150@item gdb.TYPE_CODE_COMPLEX
1151A complex float type.
1152
b3ce5e5f 1153@vindex TYPE_CODE_TYPEDEF
329baa95
DE
1154@item gdb.TYPE_CODE_TYPEDEF
1155A typedef to some other type.
1156
b3ce5e5f 1157@vindex TYPE_CODE_NAMESPACE
329baa95
DE
1158@item gdb.TYPE_CODE_NAMESPACE
1159A C@t{++} namespace.
1160
b3ce5e5f 1161@vindex TYPE_CODE_DECFLOAT
329baa95
DE
1162@item gdb.TYPE_CODE_DECFLOAT
1163A decimal floating point type.
1164
b3ce5e5f 1165@vindex TYPE_CODE_INTERNAL_FUNCTION
329baa95
DE
1166@item gdb.TYPE_CODE_INTERNAL_FUNCTION
1167A function internal to @value{GDBN}. This is the type used to represent
1168convenience functions.
b3ce5e5f 1169@end vtable
329baa95
DE
1170
1171Further support for types is provided in the @code{gdb.types}
1172Python module (@pxref{gdb.types}).
1173
1174@node Pretty Printing API
1175@subsubsection Pretty Printing API
b3ce5e5f 1176@cindex python pretty printing api
329baa95
DE
1177
1178An example output is provided (@pxref{Pretty Printing}).
1179
1180A pretty-printer is just an object that holds a value and implements a
1181specific interface, defined here.
1182
1183@defun pretty_printer.children (self)
1184@value{GDBN} will call this method on a pretty-printer to compute the
1185children of the pretty-printer's value.
1186
1187This method must return an object conforming to the Python iterator
1188protocol. Each item returned by the iterator must be a tuple holding
1189two elements. The first element is the ``name'' of the child; the
1190second element is the child's value. The value can be any Python
1191object which is convertible to a @value{GDBN} value.
1192
1193This method is optional. If it does not exist, @value{GDBN} will act
1194as though the value has no children.
1195@end defun
1196
1197@defun pretty_printer.display_hint (self)
1198The CLI may call this method and use its result to change the
1199formatting of a value. The result will also be supplied to an MI
1200consumer as a @samp{displayhint} attribute of the variable being
1201printed.
1202
1203This method is optional. If it does exist, this method must return a
1204string.
1205
1206Some display hints are predefined by @value{GDBN}:
1207
1208@table @samp
1209@item array
1210Indicate that the object being printed is ``array-like''. The CLI
1211uses this to respect parameters such as @code{set print elements} and
1212@code{set print array}.
1213
1214@item map
1215Indicate that the object being printed is ``map-like'', and that the
1216children of this value can be assumed to alternate between keys and
1217values.
1218
1219@item string
1220Indicate that the object being printed is ``string-like''. If the
1221printer's @code{to_string} method returns a Python string of some
1222kind, then @value{GDBN} will call its internal language-specific
1223string-printing function to format the string. For the CLI this means
1224adding quotation marks, possibly escaping some characters, respecting
1225@code{set print elements}, and the like.
1226@end table
1227@end defun
1228
1229@defun pretty_printer.to_string (self)
1230@value{GDBN} will call this method to display the string
1231representation of the value passed to the object's constructor.
1232
1233When printing from the CLI, if the @code{to_string} method exists,
1234then @value{GDBN} will prepend its result to the values returned by
1235@code{children}. Exactly how this formatting is done is dependent on
1236the display hint, and may change as more hints are added. Also,
1237depending on the print settings (@pxref{Print Settings}), the CLI may
1238print just the result of @code{to_string} in a stack trace, omitting
1239the result of @code{children}.
1240
1241If this method returns a string, it is printed verbatim.
1242
1243Otherwise, if this method returns an instance of @code{gdb.Value},
1244then @value{GDBN} prints this value. This may result in a call to
1245another pretty-printer.
1246
1247If instead the method returns a Python value which is convertible to a
1248@code{gdb.Value}, then @value{GDBN} performs the conversion and prints
1249the resulting value. Again, this may result in a call to another
1250pretty-printer. Python scalars (integers, floats, and booleans) and
1251strings are convertible to @code{gdb.Value}; other types are not.
1252
1253Finally, if this method returns @code{None} then no further operations
1254are peformed in this method and nothing is printed.
1255
1256If the result is not one of these types, an exception is raised.
1257@end defun
1258
1259@value{GDBN} provides a function which can be used to look up the
1260default pretty-printer for a @code{gdb.Value}:
1261
1262@findex gdb.default_visualizer
1263@defun gdb.default_visualizer (value)
1264This function takes a @code{gdb.Value} object as an argument. If a
1265pretty-printer for this value exists, then it is returned. If no such
1266printer exists, then this returns @code{None}.
1267@end defun
1268
1269@node Selecting Pretty-Printers
1270@subsubsection Selecting Pretty-Printers
b3ce5e5f 1271@cindex selecting python pretty-printers
329baa95
DE
1272
1273The Python list @code{gdb.pretty_printers} contains an array of
1274functions or callable objects that have been registered via addition
1275as a pretty-printer. Printers in this list are called @code{global}
1276printers, they're available when debugging all inferiors.
1277Each @code{gdb.Progspace} contains a @code{pretty_printers} attribute.
1278Each @code{gdb.Objfile} also contains a @code{pretty_printers}
1279attribute.
1280
1281Each function on these lists is passed a single @code{gdb.Value}
1282argument and should return a pretty-printer object conforming to the
1283interface definition above (@pxref{Pretty Printing API}). If a function
1284cannot create a pretty-printer for the value, it should return
1285@code{None}.
1286
1287@value{GDBN} first checks the @code{pretty_printers} attribute of each
1288@code{gdb.Objfile} in the current program space and iteratively calls
1289each enabled lookup routine in the list for that @code{gdb.Objfile}
1290until it receives a pretty-printer object.
1291If no pretty-printer is found in the objfile lists, @value{GDBN} then
1292searches the pretty-printer list of the current program space,
1293calling each enabled function until an object is returned.
1294After these lists have been exhausted, it tries the global
1295@code{gdb.pretty_printers} list, again calling each enabled function until an
1296object is returned.
1297
1298The order in which the objfiles are searched is not specified. For a
1299given list, functions are always invoked from the head of the list,
1300and iterated over sequentially until the end of the list, or a printer
1301object is returned.
1302
1303For various reasons a pretty-printer may not work.
1304For example, the underlying data structure may have changed and
1305the pretty-printer is out of date.
1306
1307The consequences of a broken pretty-printer are severe enough that
1308@value{GDBN} provides support for enabling and disabling individual
1309printers. For example, if @code{print frame-arguments} is on,
1310a backtrace can become highly illegible if any argument is printed
1311with a broken printer.
1312
1313Pretty-printers are enabled and disabled by attaching an @code{enabled}
1314attribute to the registered function or callable object. If this attribute
1315is present and its value is @code{False}, the printer is disabled, otherwise
1316the printer is enabled.
1317
1318@node Writing a Pretty-Printer
1319@subsubsection Writing a Pretty-Printer
1320@cindex writing a pretty-printer
1321
1322A pretty-printer consists of two parts: a lookup function to detect
1323if the type is supported, and the printer itself.
1324
1325Here is an example showing how a @code{std::string} printer might be
1326written. @xref{Pretty Printing API}, for details on the API this class
1327must provide.
1328
1329@smallexample
1330class StdStringPrinter(object):
1331 "Print a std::string"
1332
1333 def __init__(self, val):
1334 self.val = val
1335
1336 def to_string(self):
1337 return self.val['_M_dataplus']['_M_p']
1338
1339 def display_hint(self):
1340 return 'string'
1341@end smallexample
1342
1343And here is an example showing how a lookup function for the printer
1344example above might be written.
1345
1346@smallexample
1347def str_lookup_function(val):
1348 lookup_tag = val.type.tag
1349 if lookup_tag == None:
1350 return None
1351 regex = re.compile("^std::basic_string<char,.*>$")
1352 if regex.match(lookup_tag):
1353 return StdStringPrinter(val)
1354 return None
1355@end smallexample
1356
1357The example lookup function extracts the value's type, and attempts to
1358match it to a type that it can pretty-print. If it is a type the
1359printer can pretty-print, it will return a printer object. If not, it
1360returns @code{None}.
1361
1362We recommend that you put your core pretty-printers into a Python
1363package. If your pretty-printers are for use with a library, we
1364further recommend embedding a version number into the package name.
1365This practice will enable @value{GDBN} to load multiple versions of
1366your pretty-printers at the same time, because they will have
1367different names.
1368
1369You should write auto-loaded code (@pxref{Python Auto-loading}) such that it
1370can be evaluated multiple times without changing its meaning. An
1371ideal auto-load file will consist solely of @code{import}s of your
1372printer modules, followed by a call to a register pretty-printers with
1373the current objfile.
1374
1375Taken as a whole, this approach will scale nicely to multiple
1376inferiors, each potentially using a different library version.
1377Embedding a version number in the Python package name will ensure that
1378@value{GDBN} is able to load both sets of printers simultaneously.
1379Then, because the search for pretty-printers is done by objfile, and
1380because your auto-loaded code took care to register your library's
1381printers with a specific objfile, @value{GDBN} will find the correct
1382printers for the specific version of the library used by each
1383inferior.
1384
1385To continue the @code{std::string} example (@pxref{Pretty Printing API}),
1386this code might appear in @code{gdb.libstdcxx.v6}:
1387
1388@smallexample
1389def register_printers(objfile):
1390 objfile.pretty_printers.append(str_lookup_function)
1391@end smallexample
1392
1393@noindent
1394And then the corresponding contents of the auto-load file would be:
1395
1396@smallexample
1397import gdb.libstdcxx.v6
1398gdb.libstdcxx.v6.register_printers(gdb.current_objfile())
1399@end smallexample
1400
1401The previous example illustrates a basic pretty-printer.
1402There are a few things that can be improved on.
1403The printer doesn't have a name, making it hard to identify in a
1404list of installed printers. The lookup function has a name, but
1405lookup functions can have arbitrary, even identical, names.
1406
1407Second, the printer only handles one type, whereas a library typically has
1408several types. One could install a lookup function for each desired type
1409in the library, but one could also have a single lookup function recognize
1410several types. The latter is the conventional way this is handled.
1411If a pretty-printer can handle multiple data types, then its
1412@dfn{subprinters} are the printers for the individual data types.
1413
1414The @code{gdb.printing} module provides a formal way of solving these
1415problems (@pxref{gdb.printing}).
1416Here is another example that handles multiple types.
1417
1418These are the types we are going to pretty-print:
1419
1420@smallexample
1421struct foo @{ int a, b; @};
1422struct bar @{ struct foo x, y; @};
1423@end smallexample
1424
1425Here are the printers:
1426
1427@smallexample
1428class fooPrinter:
1429 """Print a foo object."""
1430
1431 def __init__(self, val):
1432 self.val = val
1433
1434 def to_string(self):
1435 return ("a=<" + str(self.val["a"]) +
1436 "> b=<" + str(self.val["b"]) + ">")
1437
1438class barPrinter:
1439 """Print a bar object."""
1440
1441 def __init__(self, val):
1442 self.val = val
1443
1444 def to_string(self):
1445 return ("x=<" + str(self.val["x"]) +
1446 "> y=<" + str(self.val["y"]) + ">")
1447@end smallexample
1448
1449This example doesn't need a lookup function, that is handled by the
1450@code{gdb.printing} module. Instead a function is provided to build up
1451the object that handles the lookup.
1452
1453@smallexample
1454import gdb.printing
1455
1456def build_pretty_printer():
1457 pp = gdb.printing.RegexpCollectionPrettyPrinter(
1458 "my_library")
1459 pp.add_printer('foo', '^foo$', fooPrinter)
1460 pp.add_printer('bar', '^bar$', barPrinter)
1461 return pp
1462@end smallexample
1463
1464And here is the autoload support:
1465
1466@smallexample
1467import gdb.printing
1468import my_library
1469gdb.printing.register_pretty_printer(
1470 gdb.current_objfile(),
1471 my_library.build_pretty_printer())
1472@end smallexample
1473
1474Finally, when this printer is loaded into @value{GDBN}, here is the
1475corresponding output of @samp{info pretty-printer}:
1476
1477@smallexample
1478(gdb) info pretty-printer
1479my_library.so:
1480 my_library
1481 foo
1482 bar
1483@end smallexample
1484
1485@node Type Printing API
1486@subsubsection Type Printing API
1487@cindex type printing API for Python
1488
1489@value{GDBN} provides a way for Python code to customize type display.
1490This is mainly useful for substituting canonical typedef names for
1491types.
1492
1493@cindex type printer
1494A @dfn{type printer} is just a Python object conforming to a certain
1495protocol. A simple base class implementing the protocol is provided;
1496see @ref{gdb.types}. A type printer must supply at least:
1497
1498@defivar type_printer enabled
1499A boolean which is True if the printer is enabled, and False
1500otherwise. This is manipulated by the @code{enable type-printer}
1501and @code{disable type-printer} commands.
1502@end defivar
1503
1504@defivar type_printer name
1505The name of the type printer. This must be a string. This is used by
1506the @code{enable type-printer} and @code{disable type-printer}
1507commands.
1508@end defivar
1509
1510@defmethod type_printer instantiate (self)
1511This is called by @value{GDBN} at the start of type-printing. It is
1512only called if the type printer is enabled. This method must return a
1513new object that supplies a @code{recognize} method, as described below.
1514@end defmethod
1515
1516
1517When displaying a type, say via the @code{ptype} command, @value{GDBN}
1518will compute a list of type recognizers. This is done by iterating
1519first over the per-objfile type printers (@pxref{Objfiles In Python}),
1520followed by the per-progspace type printers (@pxref{Progspaces In
1521Python}), and finally the global type printers.
1522
1523@value{GDBN} will call the @code{instantiate} method of each enabled
1524type printer. If this method returns @code{None}, then the result is
1525ignored; otherwise, it is appended to the list of recognizers.
1526
1527Then, when @value{GDBN} is going to display a type name, it iterates
1528over the list of recognizers. For each one, it calls the recognition
1529function, stopping if the function returns a non-@code{None} value.
1530The recognition function is defined as:
1531
1532@defmethod type_recognizer recognize (self, type)
1533If @var{type} is not recognized, return @code{None}. Otherwise,
1534return a string which is to be printed as the name of @var{type}.
697aa1b7
EZ
1535The @var{type} argument will be an instance of @code{gdb.Type}
1536(@pxref{Types In Python}).
329baa95
DE
1537@end defmethod
1538
1539@value{GDBN} uses this two-pass approach so that type printers can
1540efficiently cache information without holding on to it too long. For
1541example, it can be convenient to look up type information in a type
1542printer and hold it for a recognizer's lifetime; if a single pass were
1543done then type printers would have to make use of the event system in
1544order to avoid holding information that could become stale as the
1545inferior changed.
1546
1547@node Frame Filter API
1548@subsubsection Filtering Frames.
1549@cindex frame filters api
1550
1551Frame filters are Python objects that manipulate the visibility of a
1552frame or frames when a backtrace (@pxref{Backtrace}) is printed by
1553@value{GDBN}.
1554
1555Only commands that print a backtrace, or, in the case of @sc{gdb/mi}
1556commands (@pxref{GDB/MI}), those that return a collection of frames
1557are affected. The commands that work with frame filters are:
1558
1559@code{backtrace} (@pxref{backtrace-command,, The backtrace command}),
1560@code{-stack-list-frames}
1561(@pxref{-stack-list-frames,, The -stack-list-frames command}),
1562@code{-stack-list-variables} (@pxref{-stack-list-variables,, The
1563-stack-list-variables command}), @code{-stack-list-arguments}
1564@pxref{-stack-list-arguments,, The -stack-list-arguments command}) and
1565@code{-stack-list-locals} (@pxref{-stack-list-locals,, The
1566-stack-list-locals command}).
1567
1568A frame filter works by taking an iterator as an argument, applying
1569actions to the contents of that iterator, and returning another
1570iterator (or, possibly, the same iterator it was provided in the case
1571where the filter does not perform any operations). Typically, frame
1572filters utilize tools such as the Python's @code{itertools} module to
1573work with and create new iterators from the source iterator.
1574Regardless of how a filter chooses to apply actions, it must not alter
1575the underlying @value{GDBN} frame or frames, or attempt to alter the
1576call-stack within @value{GDBN}. This preserves data integrity within
1577@value{GDBN}. Frame filters are executed on a priority basis and care
1578should be taken that some frame filters may have been executed before,
1579and that some frame filters will be executed after.
1580
1581An important consideration when designing frame filters, and well
1582worth reflecting upon, is that frame filters should avoid unwinding
1583the call stack if possible. Some stacks can run very deep, into the
1584tens of thousands in some cases. To search every frame when a frame
1585filter executes may be too expensive at that step. The frame filter
1586cannot know how many frames it has to iterate over, and it may have to
1587iterate through them all. This ends up duplicating effort as
1588@value{GDBN} performs this iteration when it prints the frames. If
1589the filter can defer unwinding frames until frame decorators are
1590executed, after the last filter has executed, it should. @xref{Frame
1591Decorator API}, for more information on decorators. Also, there are
1592examples for both frame decorators and filters in later chapters.
1593@xref{Writing a Frame Filter}, for more information.
1594
1595The Python dictionary @code{gdb.frame_filters} contains key/object
1596pairings that comprise a frame filter. Frame filters in this
1597dictionary are called @code{global} frame filters, and they are
1598available when debugging all inferiors. These frame filters must
1599register with the dictionary directly. In addition to the
1600@code{global} dictionary, there are other dictionaries that are loaded
1601with different inferiors via auto-loading (@pxref{Python
1602Auto-loading}). The two other areas where frame filter dictionaries
1603can be found are: @code{gdb.Progspace} which contains a
1604@code{frame_filters} dictionary attribute, and each @code{gdb.Objfile}
1605object which also contains a @code{frame_filters} dictionary
1606attribute.
1607
1608When a command is executed from @value{GDBN} that is compatible with
1609frame filters, @value{GDBN} combines the @code{global},
1610@code{gdb.Progspace} and all @code{gdb.Objfile} dictionaries currently
1611loaded. All of the @code{gdb.Objfile} dictionaries are combined, as
1612several frames, and thus several object files, might be in use.
1613@value{GDBN} then prunes any frame filter whose @code{enabled}
1614attribute is @code{False}. This pruned list is then sorted according
1615to the @code{priority} attribute in each filter.
1616
1617Once the dictionaries are combined, pruned and sorted, @value{GDBN}
1618creates an iterator which wraps each frame in the call stack in a
1619@code{FrameDecorator} object, and calls each filter in order. The
1620output from the previous filter will always be the input to the next
1621filter, and so on.
1622
1623Frame filters have a mandatory interface which each frame filter must
1624implement, defined here:
1625
1626@defun FrameFilter.filter (iterator)
1627@value{GDBN} will call this method on a frame filter when it has
1628reached the order in the priority list for that filter.
1629
1630For example, if there are four frame filters:
1631
1632@smallexample
1633Name Priority
1634
1635Filter1 5
1636Filter2 10
1637Filter3 100
1638Filter4 1
1639@end smallexample
1640
1641The order that the frame filters will be called is:
1642
1643@smallexample
1644Filter3 -> Filter2 -> Filter1 -> Filter4
1645@end smallexample
1646
1647Note that the output from @code{Filter3} is passed to the input of
1648@code{Filter2}, and so on.
1649
1650This @code{filter} method is passed a Python iterator. This iterator
1651contains a sequence of frame decorators that wrap each
1652@code{gdb.Frame}, or a frame decorator that wraps another frame
1653decorator. The first filter that is executed in the sequence of frame
1654filters will receive an iterator entirely comprised of default
1655@code{FrameDecorator} objects. However, after each frame filter is
1656executed, the previous frame filter may have wrapped some or all of
1657the frame decorators with their own frame decorator. As frame
1658decorators must also conform to a mandatory interface, these
1659decorators can be assumed to act in a uniform manner (@pxref{Frame
1660Decorator API}).
1661
1662This method must return an object conforming to the Python iterator
1663protocol. Each item in the iterator must be an object conforming to
1664the frame decorator interface. If a frame filter does not wish to
1665perform any operations on this iterator, it should return that
1666iterator untouched.
1667
1668This method is not optional. If it does not exist, @value{GDBN} will
1669raise and print an error.
1670@end defun
1671
1672@defvar FrameFilter.name
1673The @code{name} attribute must be Python string which contains the
1674name of the filter displayed by @value{GDBN} (@pxref{Frame Filter
1675Management}). This attribute may contain any combination of letters
1676or numbers. Care should be taken to ensure that it is unique. This
1677attribute is mandatory.
1678@end defvar
1679
1680@defvar FrameFilter.enabled
1681The @code{enabled} attribute must be Python boolean. This attribute
1682indicates to @value{GDBN} whether the frame filter is enabled, and
1683should be considered when frame filters are executed. If
1684@code{enabled} is @code{True}, then the frame filter will be executed
1685when any of the backtrace commands detailed earlier in this chapter
1686are executed. If @code{enabled} is @code{False}, then the frame
1687filter will not be executed. This attribute is mandatory.
1688@end defvar
1689
1690@defvar FrameFilter.priority
1691The @code{priority} attribute must be Python integer. This attribute
1692controls the order of execution in relation to other frame filters.
1693There are no imposed limits on the range of @code{priority} other than
1694it must be a valid integer. The higher the @code{priority} attribute,
1695the sooner the frame filter will be executed in relation to other
1696frame filters. Although @code{priority} can be negative, it is
1697recommended practice to assume zero is the lowest priority that a
1698frame filter can be assigned. Frame filters that have the same
1699priority are executed in unsorted order in that priority slot. This
1700attribute is mandatory.
1701@end defvar
1702
1703@node Frame Decorator API
1704@subsubsection Decorating Frames.
1705@cindex frame decorator api
1706
1707Frame decorators are sister objects to frame filters (@pxref{Frame
1708Filter API}). Frame decorators are applied by a frame filter and can
1709only be used in conjunction with frame filters.
1710
1711The purpose of a frame decorator is to customize the printed content
1712of each @code{gdb.Frame} in commands where frame filters are executed.
1713This concept is called decorating a frame. Frame decorators decorate
1714a @code{gdb.Frame} with Python code contained within each API call.
1715This separates the actual data contained in a @code{gdb.Frame} from
1716the decorated data produced by a frame decorator. This abstraction is
1717necessary to maintain integrity of the data contained in each
1718@code{gdb.Frame}.
1719
1720Frame decorators have a mandatory interface, defined below.
1721
1722@value{GDBN} already contains a frame decorator called
1723@code{FrameDecorator}. This contains substantial amounts of
1724boilerplate code to decorate the content of a @code{gdb.Frame}. It is
1725recommended that other frame decorators inherit and extend this
1726object, and only to override the methods needed.
1727
1728@defun FrameDecorator.elided (self)
1729
1730The @code{elided} method groups frames together in a hierarchical
1731system. An example would be an interpreter, where multiple low-level
1732frames make up a single call in the interpreted language. In this
1733example, the frame filter would elide the low-level frames and present
1734a single high-level frame, representing the call in the interpreted
1735language, to the user.
1736
1737The @code{elided} function must return an iterable and this iterable
1738must contain the frames that are being elided wrapped in a suitable
1739frame decorator. If no frames are being elided this function may
1740return an empty iterable, or @code{None}. Elided frames are indented
1741from normal frames in a @code{CLI} backtrace, or in the case of
1742@code{GDB/MI}, are placed in the @code{children} field of the eliding
1743frame.
1744
1745It is the frame filter's task to also filter out the elided frames from
1746the source iterator. This will avoid printing the frame twice.
1747@end defun
1748
1749@defun FrameDecorator.function (self)
1750
1751This method returns the name of the function in the frame that is to
1752be printed.
1753
1754This method must return a Python string describing the function, or
1755@code{None}.
1756
1757If this function returns @code{None}, @value{GDBN} will not print any
1758data for this field.
1759@end defun
1760
1761@defun FrameDecorator.address (self)
1762
1763This method returns the address of the frame that is to be printed.
1764
1765This method must return a Python numeric integer type of sufficient
1766size to describe the address of the frame, or @code{None}.
1767
1768If this function returns a @code{None}, @value{GDBN} will not print
1769any data for this field.
1770@end defun
1771
1772@defun FrameDecorator.filename (self)
1773
1774This method returns the filename and path associated with this frame.
1775
1776This method must return a Python string containing the filename and
1777the path to the object file backing the frame, or @code{None}.
1778
1779If this function returns a @code{None}, @value{GDBN} will not print
1780any data for this field.
1781@end defun
1782
1783@defun FrameDecorator.line (self):
1784
1785This method returns the line number associated with the current
1786position within the function addressed by this frame.
1787
1788This method must return a Python integer type, or @code{None}.
1789
1790If this function returns a @code{None}, @value{GDBN} will not print
1791any data for this field.
1792@end defun
1793
1794@defun FrameDecorator.frame_args (self)
1795@anchor{frame_args}
1796
1797This method must return an iterable, or @code{None}. Returning an
1798empty iterable, or @code{None} means frame arguments will not be
1799printed for this frame. This iterable must contain objects that
1800implement two methods, described here.
1801
1802This object must implement a @code{argument} method which takes a
1803single @code{self} parameter and must return a @code{gdb.Symbol}
1804(@pxref{Symbols In Python}), or a Python string. The object must also
1805implement a @code{value} method which takes a single @code{self}
1806parameter and must return a @code{gdb.Value} (@pxref{Values From
1807Inferior}), a Python value, or @code{None}. If the @code{value}
1808method returns @code{None}, and the @code{argument} method returns a
1809@code{gdb.Symbol}, @value{GDBN} will look-up and print the value of
1810the @code{gdb.Symbol} automatically.
1811
1812A brief example:
1813
1814@smallexample
1815class SymValueWrapper():
1816
1817 def __init__(self, symbol, value):
1818 self.sym = symbol
1819 self.val = value
1820
1821 def value(self):
1822 return self.val
1823
1824 def symbol(self):
1825 return self.sym
1826
1827class SomeFrameDecorator()
1828...
1829...
1830 def frame_args(self):
1831 args = []
1832 try:
1833 block = self.inferior_frame.block()
1834 except:
1835 return None
1836
1837 # Iterate over all symbols in a block. Only add
1838 # symbols that are arguments.
1839 for sym in block:
1840 if not sym.is_argument:
1841 continue
1842 args.append(SymValueWrapper(sym,None))
1843
1844 # Add example synthetic argument.
1845 args.append(SymValueWrapper(``foo'', 42))
1846
1847 return args
1848@end smallexample
1849@end defun
1850
1851@defun FrameDecorator.frame_locals (self)
1852
1853This method must return an iterable or @code{None}. Returning an
1854empty iterable, or @code{None} means frame local arguments will not be
1855printed for this frame.
1856
1857The object interface, the description of the various strategies for
1858reading frame locals, and the example are largely similar to those
1859described in the @code{frame_args} function, (@pxref{frame_args,,The
1860frame filter frame_args function}). Below is a modified example:
1861
1862@smallexample
1863class SomeFrameDecorator()
1864...
1865...
1866 def frame_locals(self):
1867 vars = []
1868 try:
1869 block = self.inferior_frame.block()
1870 except:
1871 return None
1872
1873 # Iterate over all symbols in a block. Add all
1874 # symbols, except arguments.
1875 for sym in block:
1876 if sym.is_argument:
1877 continue
1878 vars.append(SymValueWrapper(sym,None))
1879
1880 # Add an example of a synthetic local variable.
1881 vars.append(SymValueWrapper(``bar'', 99))
1882
1883 return vars
1884@end smallexample
1885@end defun
1886
1887@defun FrameDecorator.inferior_frame (self):
1888
1889This method must return the underlying @code{gdb.Frame} that this
1890frame decorator is decorating. @value{GDBN} requires the underlying
1891frame for internal frame information to determine how to print certain
1892values when printing a frame.
1893@end defun
1894
1895@node Writing a Frame Filter
1896@subsubsection Writing a Frame Filter
1897@cindex writing a frame filter
1898
1899There are three basic elements that a frame filter must implement: it
1900must correctly implement the documented interface (@pxref{Frame Filter
1901API}), it must register itself with @value{GDBN}, and finally, it must
1902decide if it is to work on the data provided by @value{GDBN}. In all
1903cases, whether it works on the iterator or not, each frame filter must
1904return an iterator. A bare-bones frame filter follows the pattern in
1905the following example.
1906
1907@smallexample
1908import gdb
1909
1910class FrameFilter():
1911
1912 def __init__(self):
1913 # Frame filter attribute creation.
1914 #
1915 # 'name' is the name of the filter that GDB will display.
1916 #
1917 # 'priority' is the priority of the filter relative to other
1918 # filters.
1919 #
1920 # 'enabled' is a boolean that indicates whether this filter is
1921 # enabled and should be executed.
1922
1923 self.name = "Foo"
1924 self.priority = 100
1925 self.enabled = True
1926
1927 # Register this frame filter with the global frame_filters
1928 # dictionary.
1929 gdb.frame_filters[self.name] = self
1930
1931 def filter(self, frame_iter):
1932 # Just return the iterator.
1933 return frame_iter
1934@end smallexample
1935
1936The frame filter in the example above implements the three
1937requirements for all frame filters. It implements the API, self
1938registers, and makes a decision on the iterator (in this case, it just
1939returns the iterator untouched).
1940
1941The first step is attribute creation and assignment, and as shown in
1942the comments the filter assigns the following attributes: @code{name},
1943@code{priority} and whether the filter should be enabled with the
1944@code{enabled} attribute.
1945
1946The second step is registering the frame filter with the dictionary or
1947dictionaries that the frame filter has interest in. As shown in the
1948comments, this filter just registers itself with the global dictionary
1949@code{gdb.frame_filters}. As noted earlier, @code{gdb.frame_filters}
1950is a dictionary that is initialized in the @code{gdb} module when
1951@value{GDBN} starts. What dictionary a filter registers with is an
1952important consideration. Generally, if a filter is specific to a set
1953of code, it should be registered either in the @code{objfile} or
1954@code{progspace} dictionaries as they are specific to the program
1955currently loaded in @value{GDBN}. The global dictionary is always
1956present in @value{GDBN} and is never unloaded. Any filters registered
1957with the global dictionary will exist until @value{GDBN} exits. To
1958avoid filters that may conflict, it is generally better to register
1959frame filters against the dictionaries that more closely align with
1960the usage of the filter currently in question. @xref{Python
1961Auto-loading}, for further information on auto-loading Python scripts.
1962
1963@value{GDBN} takes a hands-off approach to frame filter registration,
1964therefore it is the frame filter's responsibility to ensure
1965registration has occurred, and that any exceptions are handled
1966appropriately. In particular, you may wish to handle exceptions
1967relating to Python dictionary key uniqueness. It is mandatory that
1968the dictionary key is the same as frame filter's @code{name}
1969attribute. When a user manages frame filters (@pxref{Frame Filter
1970Management}), the names @value{GDBN} will display are those contained
1971in the @code{name} attribute.
1972
1973The final step of this example is the implementation of the
1974@code{filter} method. As shown in the example comments, we define the
1975@code{filter} method and note that the method must take an iterator,
1976and also must return an iterator. In this bare-bones example, the
1977frame filter is not very useful as it just returns the iterator
1978untouched. However this is a valid operation for frame filters that
1979have the @code{enabled} attribute set, but decide not to operate on
1980any frames.
1981
1982In the next example, the frame filter operates on all frames and
1983utilizes a frame decorator to perform some work on the frames.
1984@xref{Frame Decorator API}, for further information on the frame
1985decorator interface.
1986
1987This example works on inlined frames. It highlights frames which are
1988inlined by tagging them with an ``[inlined]'' tag. By applying a
1989frame decorator to all frames with the Python @code{itertools imap}
1990method, the example defers actions to the frame decorator. Frame
1991decorators are only processed when @value{GDBN} prints the backtrace.
1992
1993This introduces a new decision making topic: whether to perform
1994decision making operations at the filtering step, or at the printing
1995step. In this example's approach, it does not perform any filtering
1996decisions at the filtering step beyond mapping a frame decorator to
1997each frame. This allows the actual decision making to be performed
1998when each frame is printed. This is an important consideration, and
1999well worth reflecting upon when designing a frame filter. An issue
2000that frame filters should avoid is unwinding the stack if possible.
2001Some stacks can run very deep, into the tens of thousands in some
2002cases. To search every frame to determine if it is inlined ahead of
2003time may be too expensive at the filtering step. The frame filter
2004cannot know how many frames it has to iterate over, and it would have
2005to iterate through them all. This ends up duplicating effort as
2006@value{GDBN} performs this iteration when it prints the frames.
2007
2008In this example decision making can be deferred to the printing step.
2009As each frame is printed, the frame decorator can examine each frame
2010in turn when @value{GDBN} iterates. From a performance viewpoint,
2011this is the most appropriate decision to make as it avoids duplicating
2012the effort that the printing step would undertake anyway. Also, if
2013there are many frame filters unwinding the stack during filtering, it
2014can substantially delay the printing of the backtrace which will
2015result in large memory usage, and a poor user experience.
2016
2017@smallexample
2018class InlineFilter():
2019
2020 def __init__(self):
2021 self.name = "InlinedFrameFilter"
2022 self.priority = 100
2023 self.enabled = True
2024 gdb.frame_filters[self.name] = self
2025
2026 def filter(self, frame_iter):
2027 frame_iter = itertools.imap(InlinedFrameDecorator,
2028 frame_iter)
2029 return frame_iter
2030@end smallexample
2031
2032This frame filter is somewhat similar to the earlier example, except
2033that the @code{filter} method applies a frame decorator object called
2034@code{InlinedFrameDecorator} to each element in the iterator. The
2035@code{imap} Python method is light-weight. It does not proactively
2036iterate over the iterator, but rather creates a new iterator which
2037wraps the existing one.
2038
2039Below is the frame decorator for this example.
2040
2041@smallexample
2042class InlinedFrameDecorator(FrameDecorator):
2043
2044 def __init__(self, fobj):
2045 super(InlinedFrameDecorator, self).__init__(fobj)
2046
2047 def function(self):
2048 frame = fobj.inferior_frame()
2049 name = str(frame.name())
2050
2051 if frame.type() == gdb.INLINE_FRAME:
2052 name = name + " [inlined]"
2053
2054 return name
2055@end smallexample
2056
2057This frame decorator only defines and overrides the @code{function}
2058method. It lets the supplied @code{FrameDecorator}, which is shipped
2059with @value{GDBN}, perform the other work associated with printing
2060this frame.
2061
2062The combination of these two objects create this output from a
2063backtrace:
2064
2065@smallexample
2066#0 0x004004e0 in bar () at inline.c:11
2067#1 0x00400566 in max [inlined] (b=6, a=12) at inline.c:21
2068#2 0x00400566 in main () at inline.c:31
2069@end smallexample
2070
2071So in the case of this example, a frame decorator is applied to all
2072frames, regardless of whether they may be inlined or not. As
2073@value{GDBN} iterates over the iterator produced by the frame filters,
2074@value{GDBN} executes each frame decorator which then makes a decision
2075on what to print in the @code{function} callback. Using a strategy
2076like this is a way to defer decisions on the frame content to printing
2077time.
2078
2079@subheading Eliding Frames
2080
2081It might be that the above example is not desirable for representing
2082inlined frames, and a hierarchical approach may be preferred. If we
2083want to hierarchically represent frames, the @code{elided} frame
2084decorator interface might be preferable.
2085
2086This example approaches the issue with the @code{elided} method. This
2087example is quite long, but very simplistic. It is out-of-scope for
2088this section to write a complete example that comprehensively covers
2089all approaches of finding and printing inlined frames. However, this
2090example illustrates the approach an author might use.
2091
2092This example comprises of three sections.
2093
2094@smallexample
2095class InlineFrameFilter():
2096
2097 def __init__(self):
2098 self.name = "InlinedFrameFilter"
2099 self.priority = 100
2100 self.enabled = True
2101 gdb.frame_filters[self.name] = self
2102
2103 def filter(self, frame_iter):
2104 return ElidingInlineIterator(frame_iter)
2105@end smallexample
2106
2107This frame filter is very similar to the other examples. The only
2108difference is this frame filter is wrapping the iterator provided to
2109it (@code{frame_iter}) with a custom iterator called
2110@code{ElidingInlineIterator}. This again defers actions to when
2111@value{GDBN} prints the backtrace, as the iterator is not traversed
2112until printing.
2113
2114The iterator for this example is as follows. It is in this section of
2115the example where decisions are made on the content of the backtrace.
2116
2117@smallexample
2118class ElidingInlineIterator:
2119 def __init__(self, ii):
2120 self.input_iterator = ii
2121
2122 def __iter__(self):
2123 return self
2124
2125 def next(self):
2126 frame = next(self.input_iterator)
2127
2128 if frame.inferior_frame().type() != gdb.INLINE_FRAME:
2129 return frame
2130
2131 try:
2132 eliding_frame = next(self.input_iterator)
2133 except StopIteration:
2134 return frame
2135 return ElidingFrameDecorator(eliding_frame, [frame])
2136@end smallexample
2137
2138This iterator implements the Python iterator protocol. When the
2139@code{next} function is called (when @value{GDBN} prints each frame),
2140the iterator checks if this frame decorator, @code{frame}, is wrapping
2141an inlined frame. If it is not, it returns the existing frame decorator
2142untouched. If it is wrapping an inlined frame, it assumes that the
2143inlined frame was contained within the next oldest frame,
2144@code{eliding_frame}, which it fetches. It then creates and returns a
2145frame decorator, @code{ElidingFrameDecorator}, which contains both the
2146elided frame, and the eliding frame.
2147
2148@smallexample
2149class ElidingInlineDecorator(FrameDecorator):
2150
2151 def __init__(self, frame, elided_frames):
2152 super(ElidingInlineDecorator, self).__init__(frame)
2153 self.frame = frame
2154 self.elided_frames = elided_frames
2155
2156 def elided(self):
2157 return iter(self.elided_frames)
2158@end smallexample
2159
2160This frame decorator overrides one function and returns the inlined
2161frame in the @code{elided} method. As before it lets
2162@code{FrameDecorator} do the rest of the work involved in printing
2163this frame. This produces the following output.
2164
2165@smallexample
2166#0 0x004004e0 in bar () at inline.c:11
2167#2 0x00400529 in main () at inline.c:25
2168 #1 0x00400529 in max (b=6, a=12) at inline.c:15
2169@end smallexample
2170
2171In that output, @code{max} which has been inlined into @code{main} is
2172printed hierarchically. Another approach would be to combine the
2173@code{function} method, and the @code{elided} method to both print a
2174marker in the inlined frame, and also show the hierarchical
2175relationship.
2176
2177@node Inferiors In Python
2178@subsubsection Inferiors In Python
2179@cindex inferiors in Python
2180
2181@findex gdb.Inferior
2182Programs which are being run under @value{GDBN} are called inferiors
2183(@pxref{Inferiors and Programs}). Python scripts can access
2184information about and manipulate inferiors controlled by @value{GDBN}
2185via objects of the @code{gdb.Inferior} class.
2186
2187The following inferior-related functions are available in the @code{gdb}
2188module:
2189
2190@defun gdb.inferiors ()
2191Return a tuple containing all inferior objects.
2192@end defun
2193
2194@defun gdb.selected_inferior ()
2195Return an object representing the current inferior.
2196@end defun
2197
2198A @code{gdb.Inferior} object has the following attributes:
2199
2200@defvar Inferior.num
2201ID of inferior, as assigned by GDB.
2202@end defvar
2203
2204@defvar Inferior.pid
2205Process ID of the inferior, as assigned by the underlying operating
2206system.
2207@end defvar
2208
2209@defvar Inferior.was_attached
2210Boolean signaling whether the inferior was created using `attach', or
2211started by @value{GDBN} itself.
2212@end defvar
2213
2214A @code{gdb.Inferior} object has the following methods:
2215
2216@defun Inferior.is_valid ()
2217Returns @code{True} if the @code{gdb.Inferior} object is valid,
2218@code{False} if not. A @code{gdb.Inferior} object will become invalid
2219if the inferior no longer exists within @value{GDBN}. All other
2220@code{gdb.Inferior} methods will throw an exception if it is invalid
2221at the time the method is called.
2222@end defun
2223
2224@defun Inferior.threads ()
2225This method returns a tuple holding all the threads which are valid
2226when it is called. If there are no valid threads, the method will
2227return an empty tuple.
2228@end defun
2229
2230@findex Inferior.read_memory
2231@defun Inferior.read_memory (address, length)
2232Read @var{length} bytes of memory from the inferior, starting at
2233@var{address}. Returns a buffer object, which behaves much like an array
2234or a string. It can be modified and given to the
2235@code{Inferior.write_memory} function. In @code{Python} 3, the return
2236value is a @code{memoryview} object.
2237@end defun
2238
2239@findex Inferior.write_memory
2240@defun Inferior.write_memory (address, buffer @r{[}, length@r{]})
2241Write the contents of @var{buffer} to the inferior, starting at
2242@var{address}. The @var{buffer} parameter must be a Python object
2243which supports the buffer protocol, i.e., a string, an array or the
2244object returned from @code{Inferior.read_memory}. If given, @var{length}
2245determines the number of bytes from @var{buffer} to be written.
2246@end defun
2247
2248@findex gdb.search_memory
2249@defun Inferior.search_memory (address, length, pattern)
2250Search a region of the inferior memory starting at @var{address} with
2251the given @var{length} using the search pattern supplied in
2252@var{pattern}. The @var{pattern} parameter must be a Python object
2253which supports the buffer protocol, i.e., a string, an array or the
2254object returned from @code{gdb.read_memory}. Returns a Python @code{Long}
2255containing the address where the pattern was found, or @code{None} if
2256the pattern could not be found.
2257@end defun
2258
2259@node Events In Python
2260@subsubsection Events In Python
2261@cindex inferior events in Python
2262
2263@value{GDBN} provides a general event facility so that Python code can be
2264notified of various state changes, particularly changes that occur in
2265the inferior.
2266
2267An @dfn{event} is just an object that describes some state change. The
2268type of the object and its attributes will vary depending on the details
2269of the change. All the existing events are described below.
2270
2271In order to be notified of an event, you must register an event handler
2272with an @dfn{event registry}. An event registry is an object in the
2273@code{gdb.events} module which dispatches particular events. A registry
2274provides methods to register and unregister event handlers:
2275
2276@defun EventRegistry.connect (object)
2277Add the given callable @var{object} to the registry. This object will be
2278called when an event corresponding to this registry occurs.
2279@end defun
2280
2281@defun EventRegistry.disconnect (object)
2282Remove the given @var{object} from the registry. Once removed, the object
2283will no longer receive notifications of events.
2284@end defun
2285
2286Here is an example:
2287
2288@smallexample
2289def exit_handler (event):
2290 print "event type: exit"
2291 print "exit code: %d" % (event.exit_code)
2292
2293gdb.events.exited.connect (exit_handler)
2294@end smallexample
2295
2296In the above example we connect our handler @code{exit_handler} to the
2297registry @code{events.exited}. Once connected, @code{exit_handler} gets
2298called when the inferior exits. The argument @dfn{event} in this example is
2299of type @code{gdb.ExitedEvent}. As you can see in the example the
2300@code{ExitedEvent} object has an attribute which indicates the exit code of
2301the inferior.
2302
2303The following is a listing of the event registries that are available and
2304details of the events they emit:
2305
2306@table @code
2307
2308@item events.cont
2309Emits @code{gdb.ThreadEvent}.
2310
2311Some events can be thread specific when @value{GDBN} is running in non-stop
2312mode. When represented in Python, these events all extend
2313@code{gdb.ThreadEvent}. Note, this event is not emitted directly; instead,
2314events which are emitted by this or other modules might extend this event.
2315Examples of these events are @code{gdb.BreakpointEvent} and
2316@code{gdb.ContinueEvent}.
2317
2318@defvar ThreadEvent.inferior_thread
2319In non-stop mode this attribute will be set to the specific thread which was
2320involved in the emitted event. Otherwise, it will be set to @code{None}.
2321@end defvar
2322
2323Emits @code{gdb.ContinueEvent} which extends @code{gdb.ThreadEvent}.
2324
2325This event indicates that the inferior has been continued after a stop. For
2326inherited attribute refer to @code{gdb.ThreadEvent} above.
2327
2328@item events.exited
2329Emits @code{events.ExitedEvent} which indicates that the inferior has exited.
2330@code{events.ExitedEvent} has two attributes:
2331@defvar ExitedEvent.exit_code
2332An integer representing the exit code, if available, which the inferior
2333has returned. (The exit code could be unavailable if, for example,
2334@value{GDBN} detaches from the inferior.) If the exit code is unavailable,
2335the attribute does not exist.
2336@end defvar
2337@defvar ExitedEvent inferior
2338A reference to the inferior which triggered the @code{exited} event.
2339@end defvar
2340
2341@item events.stop
2342Emits @code{gdb.StopEvent} which extends @code{gdb.ThreadEvent}.
2343
2344Indicates that the inferior has stopped. All events emitted by this registry
2345extend StopEvent. As a child of @code{gdb.ThreadEvent}, @code{gdb.StopEvent}
2346will indicate the stopped thread when @value{GDBN} is running in non-stop
2347mode. Refer to @code{gdb.ThreadEvent} above for more details.
2348
2349Emits @code{gdb.SignalEvent} which extends @code{gdb.StopEvent}.
2350
2351This event indicates that the inferior or one of its threads has received as
2352signal. @code{gdb.SignalEvent} has the following attributes:
2353
2354@defvar SignalEvent.stop_signal
2355A string representing the signal received by the inferior. A list of possible
2356signal values can be obtained by running the command @code{info signals} in
2357the @value{GDBN} command prompt.
2358@end defvar
2359
2360Also emits @code{gdb.BreakpointEvent} which extends @code{gdb.StopEvent}.
2361
2362@code{gdb.BreakpointEvent} event indicates that one or more breakpoints have
2363been hit, and has the following attributes:
2364
2365@defvar BreakpointEvent.breakpoints
2366A sequence containing references to all the breakpoints (type
2367@code{gdb.Breakpoint}) that were hit.
2368@xref{Breakpoints In Python}, for details of the @code{gdb.Breakpoint} object.
2369@end defvar
2370@defvar BreakpointEvent.breakpoint
2371A reference to the first breakpoint that was hit.
2372This function is maintained for backward compatibility and is now deprecated
2373in favor of the @code{gdb.BreakpointEvent.breakpoints} attribute.
2374@end defvar
2375
2376@item events.new_objfile
2377Emits @code{gdb.NewObjFileEvent} which indicates that a new object file has
2378been loaded by @value{GDBN}. @code{gdb.NewObjFileEvent} has one attribute:
2379
2380@defvar NewObjFileEvent.new_objfile
2381A reference to the object file (@code{gdb.Objfile}) which has been loaded.
2382@xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
2383@end defvar
2384
2385@end table
2386
2387@node Threads In Python
2388@subsubsection Threads In Python
2389@cindex threads in python
2390
2391@findex gdb.InferiorThread
2392Python scripts can access information about, and manipulate inferior threads
2393controlled by @value{GDBN}, via objects of the @code{gdb.InferiorThread} class.
2394
2395The following thread-related functions are available in the @code{gdb}
2396module:
2397
2398@findex gdb.selected_thread
2399@defun gdb.selected_thread ()
2400This function returns the thread object for the selected thread. If there
2401is no selected thread, this will return @code{None}.
2402@end defun
2403
2404A @code{gdb.InferiorThread} object has the following attributes:
2405
2406@defvar InferiorThread.name
2407The name of the thread. If the user specified a name using
2408@code{thread name}, then this returns that name. Otherwise, if an
2409OS-supplied name is available, then it is returned. Otherwise, this
2410returns @code{None}.
2411
2412This attribute can be assigned to. The new value must be a string
2413object, which sets the new name, or @code{None}, which removes any
2414user-specified thread name.
2415@end defvar
2416
2417@defvar InferiorThread.num
2418ID of the thread, as assigned by GDB.
2419@end defvar
2420
2421@defvar InferiorThread.ptid
2422ID of the thread, as assigned by the operating system. This attribute is a
2423tuple containing three integers. The first is the Process ID (PID); the second
2424is the Lightweight Process ID (LWPID), and the third is the Thread ID (TID).
2425Either the LWPID or TID may be 0, which indicates that the operating system
2426does not use that identifier.
2427@end defvar
2428
2429A @code{gdb.InferiorThread} object has the following methods:
2430
2431@defun InferiorThread.is_valid ()
2432Returns @code{True} if the @code{gdb.InferiorThread} object is valid,
2433@code{False} if not. A @code{gdb.InferiorThread} object will become
2434invalid if the thread exits, or the inferior that the thread belongs
2435is deleted. All other @code{gdb.InferiorThread} methods will throw an
2436exception if it is invalid at the time the method is called.
2437@end defun
2438
2439@defun InferiorThread.switch ()
2440This changes @value{GDBN}'s currently selected thread to the one represented
2441by this object.
2442@end defun
2443
2444@defun InferiorThread.is_stopped ()
2445Return a Boolean indicating whether the thread is stopped.
2446@end defun
2447
2448@defun InferiorThread.is_running ()
2449Return a Boolean indicating whether the thread is running.
2450@end defun
2451
2452@defun InferiorThread.is_exited ()
2453Return a Boolean indicating whether the thread is exited.
2454@end defun
2455
2456@node Commands In Python
2457@subsubsection Commands In Python
2458
2459@cindex commands in python
2460@cindex python commands
2461You can implement new @value{GDBN} CLI commands in Python. A CLI
2462command is implemented using an instance of the @code{gdb.Command}
2463class, most commonly using a subclass.
2464
2465@defun Command.__init__ (name, @var{command_class} @r{[}, @var{completer_class} @r{[}, @var{prefix}@r{]]})
2466The object initializer for @code{Command} registers the new command
2467with @value{GDBN}. This initializer is normally invoked from the
2468subclass' own @code{__init__} method.
2469
2470@var{name} is the name of the command. If @var{name} consists of
2471multiple words, then the initial words are looked for as prefix
2472commands. In this case, if one of the prefix commands does not exist,
2473an exception is raised.
2474
2475There is no support for multi-line commands.
2476
2477@var{command_class} should be one of the @samp{COMMAND_} constants
2478defined below. This argument tells @value{GDBN} how to categorize the
2479new command in the help system.
2480
2481@var{completer_class} is an optional argument. If given, it should be
2482one of the @samp{COMPLETE_} constants defined below. This argument
2483tells @value{GDBN} how to perform completion for this command. If not
2484given, @value{GDBN} will attempt to complete using the object's
2485@code{complete} method (see below); if no such method is found, an
2486error will occur when completion is attempted.
2487
2488@var{prefix} is an optional argument. If @code{True}, then the new
2489command is a prefix command; sub-commands of this command may be
2490registered.
2491
2492The help text for the new command is taken from the Python
2493documentation string for the command's class, if there is one. If no
2494documentation string is provided, the default value ``This command is
2495not documented.'' is used.
2496@end defun
2497
2498@cindex don't repeat Python command
2499@defun Command.dont_repeat ()
2500By default, a @value{GDBN} command is repeated when the user enters a
2501blank line at the command prompt. A command can suppress this
2502behavior by invoking the @code{dont_repeat} method. This is similar
2503to the user command @code{dont-repeat}, see @ref{Define, dont-repeat}.
2504@end defun
2505
2506@defun Command.invoke (argument, from_tty)
2507This method is called by @value{GDBN} when this command is invoked.
2508
2509@var{argument} is a string. It is the argument to the command, after
2510leading and trailing whitespace has been stripped.
2511
2512@var{from_tty} is a boolean argument. When true, this means that the
2513command was entered by the user at the terminal; when false it means
2514that the command came from elsewhere.
2515
2516If this method throws an exception, it is turned into a @value{GDBN}
2517@code{error} call. Otherwise, the return value is ignored.
2518
2519@findex gdb.string_to_argv
2520To break @var{argument} up into an argv-like string use
2521@code{gdb.string_to_argv}. This function behaves identically to
2522@value{GDBN}'s internal argument lexer @code{buildargv}.
2523It is recommended to use this for consistency.
2524Arguments are separated by spaces and may be quoted.
2525Example:
2526
2527@smallexample
2528print gdb.string_to_argv ("1 2\ \\\"3 '4 \"5' \"6 '7\"")
2529['1', '2 "3', '4 "5', "6 '7"]
2530@end smallexample
2531
2532@end defun
2533
2534@cindex completion of Python commands
2535@defun Command.complete (text, word)
2536This method is called by @value{GDBN} when the user attempts
2537completion on this command. All forms of completion are handled by
2538this method, that is, the @key{TAB} and @key{M-?} key bindings
2539(@pxref{Completion}), and the @code{complete} command (@pxref{Help,
2540complete}).
2541
697aa1b7
EZ
2542The arguments @var{text} and @var{word} are both strings; @var{text}
2543holds the complete command line up to the cursor's location, while
329baa95
DE
2544@var{word} holds the last word of the command line; this is computed
2545using a word-breaking heuristic.
2546
2547The @code{complete} method can return several values:
2548@itemize @bullet
2549@item
2550If the return value is a sequence, the contents of the sequence are
2551used as the completions. It is up to @code{complete} to ensure that the
2552contents actually do complete the word. A zero-length sequence is
2553allowed, it means that there were no completions available. Only
2554string elements of the sequence are used; other elements in the
2555sequence are ignored.
2556
2557@item
2558If the return value is one of the @samp{COMPLETE_} constants defined
2559below, then the corresponding @value{GDBN}-internal completion
2560function is invoked, and its result is used.
2561
2562@item
2563All other results are treated as though there were no available
2564completions.
2565@end itemize
2566@end defun
2567
2568When a new command is registered, it must be declared as a member of
2569some general class of commands. This is used to classify top-level
2570commands in the on-line help system; note that prefix commands are not
2571listed under their own category but rather that of their top-level
2572command. The available classifications are represented by constants
2573defined in the @code{gdb} module:
2574
2575@table @code
2576@findex COMMAND_NONE
2577@findex gdb.COMMAND_NONE
2578@item gdb.COMMAND_NONE
2579The command does not belong to any particular class. A command in
2580this category will not be displayed in any of the help categories.
2581
2582@findex COMMAND_RUNNING
2583@findex gdb.COMMAND_RUNNING
2584@item gdb.COMMAND_RUNNING
2585The command is related to running the inferior. For example,
2586@code{start}, @code{step}, and @code{continue} are in this category.
2587Type @kbd{help running} at the @value{GDBN} prompt to see a list of
2588commands in this category.
2589
2590@findex COMMAND_DATA
2591@findex gdb.COMMAND_DATA
2592@item gdb.COMMAND_DATA
2593The command is related to data or variables. For example,
2594@code{call}, @code{find}, and @code{print} are in this category. Type
2595@kbd{help data} at the @value{GDBN} prompt to see a list of commands
2596in this category.
2597
2598@findex COMMAND_STACK
2599@findex gdb.COMMAND_STACK
2600@item gdb.COMMAND_STACK
2601The command has to do with manipulation of the stack. For example,
2602@code{backtrace}, @code{frame}, and @code{return} are in this
2603category. Type @kbd{help stack} at the @value{GDBN} prompt to see a
2604list of commands in this category.
2605
2606@findex COMMAND_FILES
2607@findex gdb.COMMAND_FILES
2608@item gdb.COMMAND_FILES
2609This class is used for file-related commands. For example,
2610@code{file}, @code{list} and @code{section} are in this category.
2611Type @kbd{help files} at the @value{GDBN} prompt to see a list of
2612commands in this category.
2613
2614@findex COMMAND_SUPPORT
2615@findex gdb.COMMAND_SUPPORT
2616@item gdb.COMMAND_SUPPORT
2617This should be used for ``support facilities'', generally meaning
2618things that are useful to the user when interacting with @value{GDBN},
2619but not related to the state of the inferior. For example,
2620@code{help}, @code{make}, and @code{shell} are in this category. Type
2621@kbd{help support} at the @value{GDBN} prompt to see a list of
2622commands in this category.
2623
2624@findex COMMAND_STATUS
2625@findex gdb.COMMAND_STATUS
2626@item gdb.COMMAND_STATUS
2627The command is an @samp{info}-related command, that is, related to the
2628state of @value{GDBN} itself. For example, @code{info}, @code{macro},
2629and @code{show} are in this category. Type @kbd{help status} at the
2630@value{GDBN} prompt to see a list of commands in this category.
2631
2632@findex COMMAND_BREAKPOINTS
2633@findex gdb.COMMAND_BREAKPOINTS
2634@item gdb.COMMAND_BREAKPOINTS
2635The command has to do with breakpoints. For example, @code{break},
2636@code{clear}, and @code{delete} are in this category. Type @kbd{help
2637breakpoints} at the @value{GDBN} prompt to see a list of commands in
2638this category.
2639
2640@findex COMMAND_TRACEPOINTS
2641@findex gdb.COMMAND_TRACEPOINTS
2642@item gdb.COMMAND_TRACEPOINTS
2643The command has to do with tracepoints. For example, @code{trace},
2644@code{actions}, and @code{tfind} are in this category. Type
2645@kbd{help tracepoints} at the @value{GDBN} prompt to see a list of
2646commands in this category.
2647
2648@findex COMMAND_USER
2649@findex gdb.COMMAND_USER
2650@item gdb.COMMAND_USER
2651The command is a general purpose command for the user, and typically
2652does not fit in one of the other categories.
2653Type @kbd{help user-defined} at the @value{GDBN} prompt to see
2654a list of commands in this category, as well as the list of gdb macros
2655(@pxref{Sequences}).
2656
2657@findex COMMAND_OBSCURE
2658@findex gdb.COMMAND_OBSCURE
2659@item gdb.COMMAND_OBSCURE
2660The command is only used in unusual circumstances, or is not of
2661general interest to users. For example, @code{checkpoint},
2662@code{fork}, and @code{stop} are in this category. Type @kbd{help
2663obscure} at the @value{GDBN} prompt to see a list of commands in this
2664category.
2665
2666@findex COMMAND_MAINTENANCE
2667@findex gdb.COMMAND_MAINTENANCE
2668@item gdb.COMMAND_MAINTENANCE
2669The command is only useful to @value{GDBN} maintainers. The
2670@code{maintenance} and @code{flushregs} commands are in this category.
2671Type @kbd{help internals} at the @value{GDBN} prompt to see a list of
2672commands in this category.
2673@end table
2674
2675A new command can use a predefined completion function, either by
2676specifying it via an argument at initialization, or by returning it
2677from the @code{complete} method. These predefined completion
2678constants are all defined in the @code{gdb} module:
2679
b3ce5e5f
DE
2680@vtable @code
2681@vindex COMPLETE_NONE
329baa95
DE
2682@item gdb.COMPLETE_NONE
2683This constant means that no completion should be done.
2684
b3ce5e5f 2685@vindex COMPLETE_FILENAME
329baa95
DE
2686@item gdb.COMPLETE_FILENAME
2687This constant means that filename completion should be performed.
2688
b3ce5e5f 2689@vindex COMPLETE_LOCATION
329baa95
DE
2690@item gdb.COMPLETE_LOCATION
2691This constant means that location completion should be done.
2692@xref{Specify Location}.
2693
b3ce5e5f 2694@vindex COMPLETE_COMMAND
329baa95
DE
2695@item gdb.COMPLETE_COMMAND
2696This constant means that completion should examine @value{GDBN}
2697command names.
2698
b3ce5e5f 2699@vindex COMPLETE_SYMBOL
329baa95
DE
2700@item gdb.COMPLETE_SYMBOL
2701This constant means that completion should be done using symbol names
2702as the source.
2703
b3ce5e5f 2704@vindex COMPLETE_EXPRESSION
329baa95
DE
2705@item gdb.COMPLETE_EXPRESSION
2706This constant means that completion should be done on expressions.
2707Often this means completing on symbol names, but some language
2708parsers also have support for completing on field names.
b3ce5e5f 2709@end vtable
329baa95
DE
2710
2711The following code snippet shows how a trivial CLI command can be
2712implemented in Python:
2713
2714@smallexample
2715class HelloWorld (gdb.Command):
2716 """Greet the whole world."""
2717
2718 def __init__ (self):
2719 super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
2720
2721 def invoke (self, arg, from_tty):
2722 print "Hello, World!"
2723
2724HelloWorld ()
2725@end smallexample
2726
2727The last line instantiates the class, and is necessary to trigger the
2728registration of the command with @value{GDBN}. Depending on how the
2729Python code is read into @value{GDBN}, you may need to import the
2730@code{gdb} module explicitly.
2731
2732@node Parameters In Python
2733@subsubsection Parameters In Python
2734
2735@cindex parameters in python
2736@cindex python parameters
2737@tindex gdb.Parameter
2738@tindex Parameter
2739You can implement new @value{GDBN} parameters using Python. A new
2740parameter is implemented as an instance of the @code{gdb.Parameter}
2741class.
2742
2743Parameters are exposed to the user via the @code{set} and
2744@code{show} commands. @xref{Help}.
2745
2746There are many parameters that already exist and can be set in
2747@value{GDBN}. Two examples are: @code{set follow fork} and
2748@code{set charset}. Setting these parameters influences certain
2749behavior in @value{GDBN}. Similarly, you can define parameters that
2750can be used to influence behavior in custom Python scripts and commands.
2751
2752@defun Parameter.__init__ (name, @var{command-class}, @var{parameter-class} @r{[}, @var{enum-sequence}@r{]})
2753The object initializer for @code{Parameter} registers the new
2754parameter with @value{GDBN}. This initializer is normally invoked
2755from the subclass' own @code{__init__} method.
2756
2757@var{name} is the name of the new parameter. If @var{name} consists
2758of multiple words, then the initial words are looked for as prefix
2759parameters. An example of this can be illustrated with the
2760@code{set print} set of parameters. If @var{name} is
2761@code{print foo}, then @code{print} will be searched as the prefix
2762parameter. In this case the parameter can subsequently be accessed in
2763@value{GDBN} as @code{set print foo}.
2764
2765If @var{name} consists of multiple words, and no prefix parameter group
2766can be found, an exception is raised.
2767
2768@var{command-class} should be one of the @samp{COMMAND_} constants
2769(@pxref{Commands In Python}). This argument tells @value{GDBN} how to
2770categorize the new parameter in the help system.
2771
2772@var{parameter-class} should be one of the @samp{PARAM_} constants
2773defined below. This argument tells @value{GDBN} the type of the new
2774parameter; this information is used for input validation and
2775completion.
2776
2777If @var{parameter-class} is @code{PARAM_ENUM}, then
2778@var{enum-sequence} must be a sequence of strings. These strings
2779represent the possible values for the parameter.
2780
2781If @var{parameter-class} is not @code{PARAM_ENUM}, then the presence
2782of a fourth argument will cause an exception to be thrown.
2783
2784The help text for the new parameter is taken from the Python
2785documentation string for the parameter's class, if there is one. If
2786there is no documentation string, a default value is used.
2787@end defun
2788
2789@defvar Parameter.set_doc
2790If this attribute exists, and is a string, then its value is used as
2791the help text for this parameter's @code{set} command. The value is
2792examined when @code{Parameter.__init__} is invoked; subsequent changes
2793have no effect.
2794@end defvar
2795
2796@defvar Parameter.show_doc
2797If this attribute exists, and is a string, then its value is used as
2798the help text for this parameter's @code{show} command. The value is
2799examined when @code{Parameter.__init__} is invoked; subsequent changes
2800have no effect.
2801@end defvar
2802
2803@defvar Parameter.value
2804The @code{value} attribute holds the underlying value of the
2805parameter. It can be read and assigned to just as any other
2806attribute. @value{GDBN} does validation when assignments are made.
2807@end defvar
2808
2809There are two methods that should be implemented in any
2810@code{Parameter} class. These are:
2811
2812@defun Parameter.get_set_string (self)
2813@value{GDBN} will call this method when a @var{parameter}'s value has
2814been changed via the @code{set} API (for example, @kbd{set foo off}).
2815The @code{value} attribute has already been populated with the new
2816value and may be used in output. This method must return a string.
2817@end defun
2818
2819@defun Parameter.get_show_string (self, svalue)
2820@value{GDBN} will call this method when a @var{parameter}'s
2821@code{show} API has been invoked (for example, @kbd{show foo}). The
2822argument @code{svalue} receives the string representation of the
2823current value. This method must return a string.
2824@end defun
2825
2826When a new parameter is defined, its type must be specified. The
2827available types are represented by constants defined in the @code{gdb}
2828module:
2829
2830@table @code
2831@findex PARAM_BOOLEAN
2832@findex gdb.PARAM_BOOLEAN
2833@item gdb.PARAM_BOOLEAN
2834The value is a plain boolean. The Python boolean values, @code{True}
2835and @code{False} are the only valid values.
2836
2837@findex PARAM_AUTO_BOOLEAN
2838@findex gdb.PARAM_AUTO_BOOLEAN
2839@item gdb.PARAM_AUTO_BOOLEAN
2840The value has three possible states: true, false, and @samp{auto}. In
2841Python, true and false are represented using boolean constants, and
2842@samp{auto} is represented using @code{None}.
2843
2844@findex PARAM_UINTEGER
2845@findex gdb.PARAM_UINTEGER
2846@item gdb.PARAM_UINTEGER
2847The value is an unsigned integer. The value of 0 should be
2848interpreted to mean ``unlimited''.
2849
2850@findex PARAM_INTEGER
2851@findex gdb.PARAM_INTEGER
2852@item gdb.PARAM_INTEGER
2853The value is a signed integer. The value of 0 should be interpreted
2854to mean ``unlimited''.
2855
2856@findex PARAM_STRING
2857@findex gdb.PARAM_STRING
2858@item gdb.PARAM_STRING
2859The value is a string. When the user modifies the string, any escape
2860sequences, such as @samp{\t}, @samp{\f}, and octal escapes, are
2861translated into corresponding characters and encoded into the current
2862host charset.
2863
2864@findex PARAM_STRING_NOESCAPE
2865@findex gdb.PARAM_STRING_NOESCAPE
2866@item gdb.PARAM_STRING_NOESCAPE
2867The value is a string. When the user modifies the string, escapes are
2868passed through untranslated.
2869
2870@findex PARAM_OPTIONAL_FILENAME
2871@findex gdb.PARAM_OPTIONAL_FILENAME
2872@item gdb.PARAM_OPTIONAL_FILENAME
2873The value is a either a filename (a string), or @code{None}.
2874
2875@findex PARAM_FILENAME
2876@findex gdb.PARAM_FILENAME
2877@item gdb.PARAM_FILENAME
2878The value is a filename. This is just like
2879@code{PARAM_STRING_NOESCAPE}, but uses file names for completion.
2880
2881@findex PARAM_ZINTEGER
2882@findex gdb.PARAM_ZINTEGER
2883@item gdb.PARAM_ZINTEGER
2884The value is an integer. This is like @code{PARAM_INTEGER}, except 0
2885is interpreted as itself.
2886
2887@findex PARAM_ENUM
2888@findex gdb.PARAM_ENUM
2889@item gdb.PARAM_ENUM
2890The value is a string, which must be one of a collection string
2891constants provided when the parameter is created.
2892@end table
2893
2894@node Functions In Python
2895@subsubsection Writing new convenience functions
2896
2897@cindex writing convenience functions
2898@cindex convenience functions in python
2899@cindex python convenience functions
2900@tindex gdb.Function
2901@tindex Function
2902You can implement new convenience functions (@pxref{Convenience Vars})
2903in Python. A convenience function is an instance of a subclass of the
2904class @code{gdb.Function}.
2905
2906@defun Function.__init__ (name)
2907The initializer for @code{Function} registers the new function with
2908@value{GDBN}. The argument @var{name} is the name of the function,
2909a string. The function will be visible to the user as a convenience
2910variable of type @code{internal function}, whose name is the same as
2911the given @var{name}.
2912
2913The documentation for the new function is taken from the documentation
2914string for the new class.
2915@end defun
2916
2917@defun Function.invoke (@var{*args})
2918When a convenience function is evaluated, its arguments are converted
2919to instances of @code{gdb.Value}, and then the function's
2920@code{invoke} method is called. Note that @value{GDBN} does not
2921predetermine the arity of convenience functions. Instead, all
2922available arguments are passed to @code{invoke}, following the
2923standard Python calling convention. In particular, a convenience
2924function can have default values for parameters without ill effect.
2925
2926The return value of this method is used as its value in the enclosing
2927expression. If an ordinary Python value is returned, it is converted
2928to a @code{gdb.Value} following the usual rules.
2929@end defun
2930
2931The following code snippet shows how a trivial convenience function can
2932be implemented in Python:
2933
2934@smallexample
2935class Greet (gdb.Function):
2936 """Return string to greet someone.
2937Takes a name as argument."""
2938
2939 def __init__ (self):
2940 super (Greet, self).__init__ ("greet")
2941
2942 def invoke (self, name):
2943 return "Hello, %s!" % name.string ()
2944
2945Greet ()
2946@end smallexample
2947
2948The last line instantiates the class, and is necessary to trigger the
2949registration of the function with @value{GDBN}. Depending on how the
2950Python code is read into @value{GDBN}, you may need to import the
2951@code{gdb} module explicitly.
2952
2953Now you can use the function in an expression:
2954
2955@smallexample
2956(gdb) print $greet("Bob")
2957$1 = "Hello, Bob!"
2958@end smallexample
2959
2960@node Progspaces In Python
2961@subsubsection Program Spaces In Python
2962
2963@cindex progspaces in python
2964@tindex gdb.Progspace
2965@tindex Progspace
2966A program space, or @dfn{progspace}, represents a symbolic view
2967of an address space.
2968It consists of all of the objfiles of the program.
2969@xref{Objfiles In Python}.
2970@xref{Inferiors and Programs, program spaces}, for more details
2971about program spaces.
2972
2973The following progspace-related functions are available in the
2974@code{gdb} module:
2975
2976@findex gdb.current_progspace
2977@defun gdb.current_progspace ()
2978This function returns the program space of the currently selected inferior.
2979@xref{Inferiors and Programs}.
2980@end defun
2981
2982@findex gdb.progspaces
2983@defun gdb.progspaces ()
2984Return a sequence of all the progspaces currently known to @value{GDBN}.
2985@end defun
2986
2987Each progspace is represented by an instance of the @code{gdb.Progspace}
2988class.
2989
2990@defvar Progspace.filename
2991The file name of the progspace as a string.
2992@end defvar
2993
2994@defvar Progspace.pretty_printers
2995The @code{pretty_printers} attribute is a list of functions. It is
2996used to look up pretty-printers. A @code{Value} is passed to each
2997function in order; if the function returns @code{None}, then the
2998search continues. Otherwise, the return value should be an object
2999which is used to format the value. @xref{Pretty Printing API}, for more
3000information.
3001@end defvar
3002
3003@defvar Progspace.type_printers
3004The @code{type_printers} attribute is a list of type printer objects.
3005@xref{Type Printing API}, for more information.
3006@end defvar
3007
3008@defvar Progspace.frame_filters
3009The @code{frame_filters} attribute is a dictionary of frame filter
3010objects. @xref{Frame Filter API}, for more information.
3011@end defvar
3012
3013@node Objfiles In Python
3014@subsubsection Objfiles In Python
3015
3016@cindex objfiles in python
3017@tindex gdb.Objfile
3018@tindex Objfile
3019@value{GDBN} loads symbols for an inferior from various
3020symbol-containing files (@pxref{Files}). These include the primary
3021executable file, any shared libraries used by the inferior, and any
3022separate debug info files (@pxref{Separate Debug Files}).
3023@value{GDBN} calls these symbol-containing files @dfn{objfiles}.
3024
3025The following objfile-related functions are available in the
3026@code{gdb} module:
3027
3028@findex gdb.current_objfile
3029@defun gdb.current_objfile ()
3030When auto-loading a Python script (@pxref{Python Auto-loading}), @value{GDBN}
3031sets the ``current objfile'' to the corresponding objfile. This
3032function returns the current objfile. If there is no current objfile,
3033this function returns @code{None}.
3034@end defun
3035
3036@findex gdb.objfiles
3037@defun gdb.objfiles ()
3038Return a sequence of all the objfiles current known to @value{GDBN}.
3039@xref{Objfiles In Python}.
3040@end defun
3041
3042Each objfile is represented by an instance of the @code{gdb.Objfile}
3043class.
3044
3045@defvar Objfile.filename
3046The file name of the objfile as a string.
3047@end defvar
3048
3049@defvar Objfile.pretty_printers
3050The @code{pretty_printers} attribute is a list of functions. It is
3051used to look up pretty-printers. A @code{Value} is passed to each
3052function in order; if the function returns @code{None}, then the
3053search continues. Otherwise, the return value should be an object
3054which is used to format the value. @xref{Pretty Printing API}, for more
3055information.
3056@end defvar
3057
3058@defvar Objfile.type_printers
3059The @code{type_printers} attribute is a list of type printer objects.
3060@xref{Type Printing API}, for more information.
3061@end defvar
3062
3063@defvar Objfile.frame_filters
3064The @code{frame_filters} attribute is a dictionary of frame filter
3065objects. @xref{Frame Filter API}, for more information.
3066@end defvar
3067
3068A @code{gdb.Objfile} object has the following methods:
3069
3070@defun Objfile.is_valid ()
3071Returns @code{True} if the @code{gdb.Objfile} object is valid,
3072@code{False} if not. A @code{gdb.Objfile} object can become invalid
3073if the object file it refers to is not loaded in @value{GDBN} any
3074longer. All other @code{gdb.Objfile} methods will throw an exception
3075if it is invalid at the time the method is called.
3076@end defun
3077
3078@node Frames In Python
3079@subsubsection Accessing inferior stack frames from Python.
3080
3081@cindex frames in python
3082When the debugged program stops, @value{GDBN} is able to analyze its call
3083stack (@pxref{Frames,,Stack frames}). The @code{gdb.Frame} class
3084represents a frame in the stack. A @code{gdb.Frame} object is only valid
3085while its corresponding frame exists in the inferior's stack. If you try
3086to use an invalid frame object, @value{GDBN} will throw a @code{gdb.error}
3087exception (@pxref{Exception Handling}).
3088
3089Two @code{gdb.Frame} objects can be compared for equality with the @code{==}
3090operator, like:
3091
3092@smallexample
3093(@value{GDBP}) python print gdb.newest_frame() == gdb.selected_frame ()
3094True
3095@end smallexample
3096
3097The following frame-related functions are available in the @code{gdb} module:
3098
3099@findex gdb.selected_frame
3100@defun gdb.selected_frame ()
3101Return the selected frame object. (@pxref{Selection,,Selecting a Frame}).
3102@end defun
3103
3104@findex gdb.newest_frame
3105@defun gdb.newest_frame ()
3106Return the newest frame object for the selected thread.
3107@end defun
3108
3109@defun gdb.frame_stop_reason_string (reason)
3110Return a string explaining the reason why @value{GDBN} stopped unwinding
3111frames, as expressed by the given @var{reason} code (an integer, see the
3112@code{unwind_stop_reason} method further down in this section).
3113@end defun
3114
3115A @code{gdb.Frame} object has the following methods:
3116
3117@defun Frame.is_valid ()
3118Returns true if the @code{gdb.Frame} object is valid, false if not.
3119A frame object can become invalid if the frame it refers to doesn't
3120exist anymore in the inferior. All @code{gdb.Frame} methods will throw
3121an exception if it is invalid at the time the method is called.
3122@end defun
3123
3124@defun Frame.name ()
3125Returns the function name of the frame, or @code{None} if it can't be
3126obtained.
3127@end defun
3128
3129@defun Frame.architecture ()
3130Returns the @code{gdb.Architecture} object corresponding to the frame's
3131architecture. @xref{Architectures In Python}.
3132@end defun
3133
3134@defun Frame.type ()
3135Returns the type of the frame. The value can be one of:
3136@table @code
3137@item gdb.NORMAL_FRAME
3138An ordinary stack frame.
3139
3140@item gdb.DUMMY_FRAME
3141A fake stack frame that was created by @value{GDBN} when performing an
3142inferior function call.
3143
3144@item gdb.INLINE_FRAME
3145A frame representing an inlined function. The function was inlined
3146into a @code{gdb.NORMAL_FRAME} that is older than this one.
3147
3148@item gdb.TAILCALL_FRAME
3149A frame representing a tail call. @xref{Tail Call Frames}.
3150
3151@item gdb.SIGTRAMP_FRAME
3152A signal trampoline frame. This is the frame created by the OS when
3153it calls into a signal handler.
3154
3155@item gdb.ARCH_FRAME
3156A fake stack frame representing a cross-architecture call.
3157
3158@item gdb.SENTINEL_FRAME
3159This is like @code{gdb.NORMAL_FRAME}, but it is only used for the
3160newest frame.
3161@end table
3162@end defun
3163
3164@defun Frame.unwind_stop_reason ()
3165Return an integer representing the reason why it's not possible to find
3166more frames toward the outermost frame. Use
3167@code{gdb.frame_stop_reason_string} to convert the value returned by this
3168function to a string. The value can be one of:
3169
3170@table @code
3171@item gdb.FRAME_UNWIND_NO_REASON
3172No particular reason (older frames should be available).
3173
3174@item gdb.FRAME_UNWIND_NULL_ID
3175The previous frame's analyzer returns an invalid result. This is no
3176longer used by @value{GDBN}, and is kept only for backward
3177compatibility.
3178
3179@item gdb.FRAME_UNWIND_OUTERMOST
3180This frame is the outermost.
3181
3182@item gdb.FRAME_UNWIND_UNAVAILABLE
3183Cannot unwind further, because that would require knowing the
3184values of registers or memory that have not been collected.
3185
3186@item gdb.FRAME_UNWIND_INNER_ID
3187This frame ID looks like it ought to belong to a NEXT frame,
3188but we got it for a PREV frame. Normally, this is a sign of
3189unwinder failure. It could also indicate stack corruption.
3190
3191@item gdb.FRAME_UNWIND_SAME_ID
3192This frame has the same ID as the previous one. That means
3193that unwinding further would almost certainly give us another
3194frame with exactly the same ID, so break the chain. Normally,
3195this is a sign of unwinder failure. It could also indicate
3196stack corruption.
3197
3198@item gdb.FRAME_UNWIND_NO_SAVED_PC
3199The frame unwinder did not find any saved PC, but we needed
3200one to unwind further.
3201
53e8a631
AB
3202@item gdb.FRAME_UNWIND_MEMORY_ERROR
3203The frame unwinder caused an error while trying to access memory.
3204
329baa95
DE
3205@item gdb.FRAME_UNWIND_FIRST_ERROR
3206Any stop reason greater or equal to this value indicates some kind
3207of error. This special value facilitates writing code that tests
3208for errors in unwinding in a way that will work correctly even if
3209the list of the other values is modified in future @value{GDBN}
3210versions. Using it, you could write:
3211@smallexample
3212reason = gdb.selected_frame().unwind_stop_reason ()
3213reason_str = gdb.frame_stop_reason_string (reason)
3214if reason >= gdb.FRAME_UNWIND_FIRST_ERROR:
3215 print "An error occured: %s" % reason_str
3216@end smallexample
3217@end table
3218
3219@end defun
3220
3221@defun Frame.pc ()
3222Returns the frame's resume address.
3223@end defun
3224
3225@defun Frame.block ()
3226Return the frame's code block. @xref{Blocks In Python}.
3227@end defun
3228
3229@defun Frame.function ()
3230Return the symbol for the function corresponding to this frame.
3231@xref{Symbols In Python}.
3232@end defun
3233
3234@defun Frame.older ()
3235Return the frame that called this frame.
3236@end defun
3237
3238@defun Frame.newer ()
3239Return the frame called by this frame.
3240@end defun
3241
3242@defun Frame.find_sal ()
3243Return the frame's symtab and line object.
3244@xref{Symbol Tables In Python}.
3245@end defun
3246
3247@defun Frame.read_var (variable @r{[}, block@r{]})
3248Return the value of @var{variable} in this frame. If the optional
3249argument @var{block} is provided, search for the variable from that
3250block; otherwise start at the frame's current block (which is
697aa1b7
EZ
3251determined by the frame's current program counter). The @var{variable}
3252argument must be a string or a @code{gdb.Symbol} object; @var{block} must be a
329baa95
DE
3253@code{gdb.Block} object.
3254@end defun
3255
3256@defun Frame.select ()
3257Set this frame to be the selected frame. @xref{Stack, ,Examining the
3258Stack}.
3259@end defun
3260
3261@node Blocks In Python
3262@subsubsection Accessing blocks from Python.
3263
3264@cindex blocks in python
3265@tindex gdb.Block
3266
3267In @value{GDBN}, symbols are stored in blocks. A block corresponds
3268roughly to a scope in the source code. Blocks are organized
3269hierarchically, and are represented individually in Python as a
3270@code{gdb.Block}. Blocks rely on debugging information being
3271available.
3272
3273A frame has a block. Please see @ref{Frames In Python}, for a more
3274in-depth discussion of frames.
3275
3276The outermost block is known as the @dfn{global block}. The global
3277block typically holds public global variables and functions.
3278
3279The block nested just inside the global block is the @dfn{static
3280block}. The static block typically holds file-scoped variables and
3281functions.
3282
3283@value{GDBN} provides a method to get a block's superblock, but there
3284is currently no way to examine the sub-blocks of a block, or to
3285iterate over all the blocks in a symbol table (@pxref{Symbol Tables In
3286Python}).
3287
3288Here is a short example that should help explain blocks:
3289
3290@smallexample
3291/* This is in the global block. */
3292int global;
3293
3294/* This is in the static block. */
3295static int file_scope;
3296
3297/* 'function' is in the global block, and 'argument' is
3298 in a block nested inside of 'function'. */
3299int function (int argument)
3300@{
3301 /* 'local' is in a block inside 'function'. It may or may
3302 not be in the same block as 'argument'. */
3303 int local;
3304
3305 @{
3306 /* 'inner' is in a block whose superblock is the one holding
3307 'local'. */
3308 int inner;
3309
3310 /* If this call is expanded by the compiler, you may see
3311 a nested block here whose function is 'inline_function'
3312 and whose superblock is the one holding 'inner'. */
3313 inline_function ();
3314 @}
3315@}
3316@end smallexample
3317
3318A @code{gdb.Block} is iterable. The iterator returns the symbols
3319(@pxref{Symbols In Python}) local to the block. Python programs
3320should not assume that a specific block object will always contain a
3321given symbol, since changes in @value{GDBN} features and
3322infrastructure may cause symbols move across blocks in a symbol
3323table.
3324
3325The following block-related functions are available in the @code{gdb}
3326module:
3327
3328@findex gdb.block_for_pc
3329@defun gdb.block_for_pc (pc)
3330Return the innermost @code{gdb.Block} containing the given @var{pc}
3331value. If the block cannot be found for the @var{pc} value specified,
3332the function will return @code{None}.
3333@end defun
3334
3335A @code{gdb.Block} object has the following methods:
3336
3337@defun Block.is_valid ()
3338Returns @code{True} if the @code{gdb.Block} object is valid,
3339@code{False} if not. A block object can become invalid if the block it
3340refers to doesn't exist anymore in the inferior. All other
3341@code{gdb.Block} methods will throw an exception if it is invalid at
3342the time the method is called. The block's validity is also checked
3343during iteration over symbols of the block.
3344@end defun
3345
3346A @code{gdb.Block} object has the following attributes:
3347
3348@defvar Block.start
3349The start address of the block. This attribute is not writable.
3350@end defvar
3351
3352@defvar Block.end
3353The end address of the block. This attribute is not writable.
3354@end defvar
3355
3356@defvar Block.function
3357The name of the block represented as a @code{gdb.Symbol}. If the
3358block is not named, then this attribute holds @code{None}. This
3359attribute is not writable.
3360
3361For ordinary function blocks, the superblock is the static block.
3362However, you should note that it is possible for a function block to
3363have a superblock that is not the static block -- for instance this
3364happens for an inlined function.
3365@end defvar
3366
3367@defvar Block.superblock
3368The block containing this block. If this parent block does not exist,
3369this attribute holds @code{None}. This attribute is not writable.
3370@end defvar
3371
3372@defvar Block.global_block
3373The global block associated with this block. This attribute is not
3374writable.
3375@end defvar
3376
3377@defvar Block.static_block
3378The static block associated with this block. This attribute is not
3379writable.
3380@end defvar
3381
3382@defvar Block.is_global
3383@code{True} if the @code{gdb.Block} object is a global block,
3384@code{False} if not. This attribute is not
3385writable.
3386@end defvar
3387
3388@defvar Block.is_static
3389@code{True} if the @code{gdb.Block} object is a static block,
3390@code{False} if not. This attribute is not writable.
3391@end defvar
3392
3393@node Symbols In Python
3394@subsubsection Python representation of Symbols.
3395
3396@cindex symbols in python
3397@tindex gdb.Symbol
3398
3399@value{GDBN} represents every variable, function and type as an
3400entry in a symbol table. @xref{Symbols, ,Examining the Symbol Table}.
3401Similarly, Python represents these symbols in @value{GDBN} with the
3402@code{gdb.Symbol} object.
3403
3404The following symbol-related functions are available in the @code{gdb}
3405module:
3406
3407@findex gdb.lookup_symbol
3408@defun gdb.lookup_symbol (name @r{[}, block @r{[}, domain@r{]]})
3409This function searches for a symbol by name. The search scope can be
3410restricted to the parameters defined in the optional domain and block
3411arguments.
3412
3413@var{name} is the name of the symbol. It must be a string. The
3414optional @var{block} argument restricts the search to symbols visible
3415in that @var{block}. The @var{block} argument must be a
3416@code{gdb.Block} object. If omitted, the block for the current frame
3417is used. The optional @var{domain} argument restricts
3418the search to the domain type. The @var{domain} argument must be a
3419domain constant defined in the @code{gdb} module and described later
3420in this chapter.
3421
3422The result is a tuple of two elements.
3423The first element is a @code{gdb.Symbol} object or @code{None} if the symbol
3424is not found.
3425If the symbol is found, the second element is @code{True} if the symbol
3426is a field of a method's object (e.g., @code{this} in C@t{++}),
3427otherwise it is @code{False}.
3428If the symbol is not found, the second element is @code{False}.
3429@end defun
3430
3431@findex gdb.lookup_global_symbol
3432@defun gdb.lookup_global_symbol (name @r{[}, domain@r{]})
3433This function searches for a global symbol by name.
3434The search scope can be restricted to by the domain argument.
3435
3436@var{name} is the name of the symbol. It must be a string.
3437The optional @var{domain} argument restricts the search to the domain type.
3438The @var{domain} argument must be a domain constant defined in the @code{gdb}
3439module and described later in this chapter.
3440
3441The result is a @code{gdb.Symbol} object or @code{None} if the symbol
3442is not found.
3443@end defun
3444
3445A @code{gdb.Symbol} object has the following attributes:
3446
3447@defvar Symbol.type
3448The type of the symbol or @code{None} if no type is recorded.
3449This attribute is represented as a @code{gdb.Type} object.
3450@xref{Types In Python}. This attribute is not writable.
3451@end defvar
3452
3453@defvar Symbol.symtab
3454The symbol table in which the symbol appears. This attribute is
3455represented as a @code{gdb.Symtab} object. @xref{Symbol Tables In
3456Python}. This attribute is not writable.
3457@end defvar
3458
3459@defvar Symbol.line
3460The line number in the source code at which the symbol was defined.
3461This is an integer.
3462@end defvar
3463
3464@defvar Symbol.name
3465The name of the symbol as a string. This attribute is not writable.
3466@end defvar
3467
3468@defvar Symbol.linkage_name
3469The name of the symbol, as used by the linker (i.e., may be mangled).
3470This attribute is not writable.
3471@end defvar
3472
3473@defvar Symbol.print_name
3474The name of the symbol in a form suitable for output. This is either
3475@code{name} or @code{linkage_name}, depending on whether the user
3476asked @value{GDBN} to display demangled or mangled names.
3477@end defvar
3478
3479@defvar Symbol.addr_class
3480The address class of the symbol. This classifies how to find the value
3481of a symbol. Each address class is a constant defined in the
3482@code{gdb} module and described later in this chapter.
3483@end defvar
3484
3485@defvar Symbol.needs_frame
3486This is @code{True} if evaluating this symbol's value requires a frame
3487(@pxref{Frames In Python}) and @code{False} otherwise. Typically,
3488local variables will require a frame, but other symbols will not.
3489@end defvar
3490
3491@defvar Symbol.is_argument
3492@code{True} if the symbol is an argument of a function.
3493@end defvar
3494
3495@defvar Symbol.is_constant
3496@code{True} if the symbol is a constant.
3497@end defvar
3498
3499@defvar Symbol.is_function
3500@code{True} if the symbol is a function or a method.
3501@end defvar
3502
3503@defvar Symbol.is_variable
3504@code{True} if the symbol is a variable.
3505@end defvar
3506
3507A @code{gdb.Symbol} object has the following methods:
3508
3509@defun Symbol.is_valid ()
3510Returns @code{True} if the @code{gdb.Symbol} object is valid,
3511@code{False} if not. A @code{gdb.Symbol} object can become invalid if
3512the symbol it refers to does not exist in @value{GDBN} any longer.
3513All other @code{gdb.Symbol} methods will throw an exception if it is
3514invalid at the time the method is called.
3515@end defun
3516
3517@defun Symbol.value (@r{[}frame@r{]})
3518Compute the value of the symbol, as a @code{gdb.Value}. For
3519functions, this computes the address of the function, cast to the
3520appropriate type. If the symbol requires a frame in order to compute
3521its value, then @var{frame} must be given. If @var{frame} is not
3522given, or if @var{frame} is invalid, then this method will throw an
3523exception.
3524@end defun
3525
3526The available domain categories in @code{gdb.Symbol} are represented
3527as constants in the @code{gdb} module:
3528
b3ce5e5f
DE
3529@vtable @code
3530@vindex SYMBOL_UNDEF_DOMAIN
329baa95
DE
3531@item gdb.SYMBOL_UNDEF_DOMAIN
3532This is used when a domain has not been discovered or none of the
3533following domains apply. This usually indicates an error either
3534in the symbol information or in @value{GDBN}'s handling of symbols.
b3ce5e5f
DE
3535
3536@vindex SYMBOL_VAR_DOMAIN
329baa95
DE
3537@item gdb.SYMBOL_VAR_DOMAIN
3538This domain contains variables, function names, typedef names and enum
3539type values.
b3ce5e5f
DE
3540
3541@vindex SYMBOL_STRUCT_DOMAIN
329baa95
DE
3542@item gdb.SYMBOL_STRUCT_DOMAIN
3543This domain holds struct, union and enum type names.
b3ce5e5f
DE
3544
3545@vindex SYMBOL_LABEL_DOMAIN
329baa95
DE
3546@item gdb.SYMBOL_LABEL_DOMAIN
3547This domain contains names of labels (for gotos).
b3ce5e5f
DE
3548
3549@vindex SYMBOL_VARIABLES_DOMAIN
329baa95
DE
3550@item gdb.SYMBOL_VARIABLES_DOMAIN
3551This domain holds a subset of the @code{SYMBOLS_VAR_DOMAIN}; it
3552contains everything minus functions and types.
b3ce5e5f
DE
3553
3554@vindex SYMBOL_FUNCTIONS_DOMAIN
329baa95
DE
3555@item gdb.SYMBOL_FUNCTION_DOMAIN
3556This domain contains all functions.
b3ce5e5f
DE
3557
3558@vindex SYMBOL_TYPES_DOMAIN
329baa95
DE
3559@item gdb.SYMBOL_TYPES_DOMAIN
3560This domain contains all types.
b3ce5e5f 3561@end vtable
329baa95
DE
3562
3563The available address class categories in @code{gdb.Symbol} are represented
3564as constants in the @code{gdb} module:
3565
b3ce5e5f
DE
3566@vtable @code
3567@vindex SYMBOL_LOC_UNDEF
329baa95
DE
3568@item gdb.SYMBOL_LOC_UNDEF
3569If this is returned by address class, it indicates an error either in
3570the symbol information or in @value{GDBN}'s handling of symbols.
b3ce5e5f
DE
3571
3572@vindex SYMBOL_LOC_CONST
329baa95
DE
3573@item gdb.SYMBOL_LOC_CONST
3574Value is constant int.
b3ce5e5f
DE
3575
3576@vindex SYMBOL_LOC_STATIC
329baa95
DE
3577@item gdb.SYMBOL_LOC_STATIC
3578Value is at a fixed address.
b3ce5e5f
DE
3579
3580@vindex SYMBOL_LOC_REGISTER
329baa95
DE
3581@item gdb.SYMBOL_LOC_REGISTER
3582Value is in a register.
b3ce5e5f
DE
3583
3584@vindex SYMBOL_LOC_ARG
329baa95
DE
3585@item gdb.SYMBOL_LOC_ARG
3586Value is an argument. This value is at the offset stored within the
3587symbol inside the frame's argument list.
b3ce5e5f
DE
3588
3589@vindex SYMBOL_LOC_REF_ARG
329baa95
DE
3590@item gdb.SYMBOL_LOC_REF_ARG
3591Value address is stored in the frame's argument list. Just like
3592@code{LOC_ARG} except that the value's address is stored at the
3593offset, not the value itself.
b3ce5e5f
DE
3594
3595@vindex SYMBOL_LOC_REGPARM_ADDR
329baa95
DE
3596@item gdb.SYMBOL_LOC_REGPARM_ADDR
3597Value is a specified register. Just like @code{LOC_REGISTER} except
3598the register holds the address of the argument instead of the argument
3599itself.
b3ce5e5f
DE
3600
3601@vindex SYMBOL_LOC_LOCAL
329baa95
DE
3602@item gdb.SYMBOL_LOC_LOCAL
3603Value is a local variable.
b3ce5e5f
DE
3604
3605@vindex SYMBOL_LOC_TYPEDEF
329baa95
DE
3606@item gdb.SYMBOL_LOC_TYPEDEF
3607Value not used. Symbols in the domain @code{SYMBOL_STRUCT_DOMAIN} all
3608have this class.
b3ce5e5f
DE
3609
3610@vindex SYMBOL_LOC_BLOCK
329baa95
DE
3611@item gdb.SYMBOL_LOC_BLOCK
3612Value is a block.
b3ce5e5f
DE
3613
3614@vindex SYMBOL_LOC_CONST_BYTES
329baa95
DE
3615@item gdb.SYMBOL_LOC_CONST_BYTES
3616Value is a byte-sequence.
b3ce5e5f
DE
3617
3618@vindex SYMBOL_LOC_UNRESOLVED
329baa95
DE
3619@item gdb.SYMBOL_LOC_UNRESOLVED
3620Value is at a fixed address, but the address of the variable has to be
3621determined from the minimal symbol table whenever the variable is
3622referenced.
b3ce5e5f
DE
3623
3624@vindex SYMBOL_LOC_OPTIMIZED_OUT
329baa95
DE
3625@item gdb.SYMBOL_LOC_OPTIMIZED_OUT
3626The value does not actually exist in the program.
b3ce5e5f
DE
3627
3628@vindex SYMBOL_LOC_COMPUTED
329baa95
DE
3629@item gdb.SYMBOL_LOC_COMPUTED
3630The value's address is a computed location.
b3ce5e5f 3631@end vtable
329baa95
DE
3632
3633@node Symbol Tables In Python
3634@subsubsection Symbol table representation in Python.
3635
3636@cindex symbol tables in python
3637@tindex gdb.Symtab
3638@tindex gdb.Symtab_and_line
3639
3640Access to symbol table data maintained by @value{GDBN} on the inferior
3641is exposed to Python via two objects: @code{gdb.Symtab_and_line} and
3642@code{gdb.Symtab}. Symbol table and line data for a frame is returned
3643from the @code{find_sal} method in @code{gdb.Frame} object.
3644@xref{Frames In Python}.
3645
3646For more information on @value{GDBN}'s symbol table management, see
3647@ref{Symbols, ,Examining the Symbol Table}, for more information.
3648
3649A @code{gdb.Symtab_and_line} object has the following attributes:
3650
3651@defvar Symtab_and_line.symtab
3652The symbol table object (@code{gdb.Symtab}) for this frame.
3653This attribute is not writable.
3654@end defvar
3655
3656@defvar Symtab_and_line.pc
3657Indicates the start of the address range occupied by code for the
3658current source line. This attribute is not writable.
3659@end defvar
3660
3661@defvar Symtab_and_line.last
3662Indicates the end of the address range occupied by code for the current
3663source line. This attribute is not writable.
3664@end defvar
3665
3666@defvar Symtab_and_line.line
3667Indicates the current line number for this object. This
3668attribute is not writable.
3669@end defvar
3670
3671A @code{gdb.Symtab_and_line} object has the following methods:
3672
3673@defun Symtab_and_line.is_valid ()
3674Returns @code{True} if the @code{gdb.Symtab_and_line} object is valid,
3675@code{False} if not. A @code{gdb.Symtab_and_line} object can become
3676invalid if the Symbol table and line object it refers to does not
3677exist in @value{GDBN} any longer. All other
3678@code{gdb.Symtab_and_line} methods will throw an exception if it is
3679invalid at the time the method is called.
3680@end defun
3681
3682A @code{gdb.Symtab} object has the following attributes:
3683
3684@defvar Symtab.filename
3685The symbol table's source filename. This attribute is not writable.
3686@end defvar
3687
3688@defvar Symtab.objfile
3689The symbol table's backing object file. @xref{Objfiles In Python}.
3690This attribute is not writable.
3691@end defvar
3692
3693A @code{gdb.Symtab} object has the following methods:
3694
3695@defun Symtab.is_valid ()
3696Returns @code{True} if the @code{gdb.Symtab} object is valid,
3697@code{False} if not. A @code{gdb.Symtab} object can become invalid if
3698the symbol table it refers to does not exist in @value{GDBN} any
3699longer. All other @code{gdb.Symtab} methods will throw an exception
3700if it is invalid at the time the method is called.
3701@end defun
3702
3703@defun Symtab.fullname ()
3704Return the symbol table's source absolute file name.
3705@end defun
3706
3707@defun Symtab.global_block ()
3708Return the global block of the underlying symbol table.
3709@xref{Blocks In Python}.
3710@end defun
3711
3712@defun Symtab.static_block ()
3713Return the static block of the underlying symbol table.
3714@xref{Blocks In Python}.
3715@end defun
3716
3717@defun Symtab.linetable ()
3718Return the line table associated with the symbol table.
3719@xref{Line Tables In Python}.
3720@end defun
3721
3722@node Line Tables In Python
3723@subsubsection Manipulating line tables using Python
3724
3725@cindex line tables in python
3726@tindex gdb.LineTable
3727
3728Python code can request and inspect line table information from a
3729symbol table that is loaded in @value{GDBN}. A line table is a
3730mapping of source lines to their executable locations in memory. To
3731acquire the line table information for a particular symbol table, use
3732the @code{linetable} function (@pxref{Symbol Tables In Python}).
3733
3734A @code{gdb.LineTable} is iterable. The iterator returns
3735@code{LineTableEntry} objects that correspond to the source line and
3736address for each line table entry. @code{LineTableEntry} objects have
3737the following attributes:
3738
3739@defvar LineTableEntry.line
3740The source line number for this line table entry. This number
3741corresponds to the actual line of source. This attribute is not
3742writable.
3743@end defvar
3744
3745@defvar LineTableEntry.pc
3746The address that is associated with the line table entry where the
3747executable code for that source line resides in memory. This
3748attribute is not writable.
3749@end defvar
3750
3751As there can be multiple addresses for a single source line, you may
3752receive multiple @code{LineTableEntry} objects with matching
3753@code{line} attributes, but with different @code{pc} attributes. The
3754iterator is sorted in ascending @code{pc} order. Here is a small
3755example illustrating iterating over a line table.
3756
3757@smallexample
3758symtab = gdb.selected_frame().find_sal().symtab
3759linetable = symtab.linetable()
3760for line in linetable:
3761 print "Line: "+str(line.line)+" Address: "+hex(line.pc)
3762@end smallexample
3763
3764This will have the following output:
3765
3766@smallexample
3767Line: 33 Address: 0x4005c8L
3768Line: 37 Address: 0x4005caL
3769Line: 39 Address: 0x4005d2L
3770Line: 40 Address: 0x4005f8L
3771Line: 42 Address: 0x4005ffL
3772Line: 44 Address: 0x400608L
3773Line: 42 Address: 0x40060cL
3774Line: 45 Address: 0x400615L
3775@end smallexample
3776
3777In addition to being able to iterate over a @code{LineTable}, it also
3778has the following direct access methods:
3779
3780@defun LineTable.line (line)
3781Return a Python @code{Tuple} of @code{LineTableEntry} objects for any
697aa1b7
EZ
3782entries in the line table for the given @var{line}, which specifies
3783the source code line. If there are no entries for that source code
329baa95
DE
3784@var{line}, the Python @code{None} is returned.
3785@end defun
3786
3787@defun LineTable.has_line (line)
3788Return a Python @code{Boolean} indicating whether there is an entry in
3789the line table for this source line. Return @code{True} if an entry
3790is found, or @code{False} if not.
3791@end defun
3792
3793@defun LineTable.source_lines ()
3794Return a Python @code{List} of the source line numbers in the symbol
3795table. Only lines with executable code locations are returned. The
3796contents of the @code{List} will just be the source line entries
3797represented as Python @code{Long} values.
3798@end defun
3799
3800@node Breakpoints In Python
3801@subsubsection Manipulating breakpoints using Python
3802
3803@cindex breakpoints in python
3804@tindex gdb.Breakpoint
3805
3806Python code can manipulate breakpoints via the @code{gdb.Breakpoint}
3807class.
3808
3809@defun Breakpoint.__init__ (spec @r{[}, type @r{[}, wp_class @r{[},internal @r{[},temporary@r{]]]]})
697aa1b7
EZ
3810Create a new breakpoint according to @var{spec}, which is a string
3811naming the location of the breakpoint, or an expression that defines a
3812watchpoint. The contents can be any location recognized by the
3813@code{break} command, or in the case of a watchpoint, by the
3814@code{watch} command. The optional @var{type} denotes the breakpoint
3815to create from the types defined later in this chapter. This argument
3816can be either @code{gdb.BP_BREAKPOINT} or @code{gdb.BP_WATCHPOINT}; it
329baa95
DE
3817defaults to @code{gdb.BP_BREAKPOINT}. The optional @var{internal}
3818argument allows the breakpoint to become invisible to the user. The
3819breakpoint will neither be reported when created, nor will it be
3820listed in the output from @code{info breakpoints} (but will be listed
3821with the @code{maint info breakpoints} command). The optional
3822@var{temporary} argument makes the breakpoint a temporary breakpoint.
3823Temporary breakpoints are deleted after they have been hit. Any
3824further access to the Python breakpoint after it has been hit will
3825result in a runtime error (as that breakpoint has now been
3826automatically deleted). The optional @var{wp_class} argument defines
3827the class of watchpoint to create, if @var{type} is
3828@code{gdb.BP_WATCHPOINT}. If a watchpoint class is not provided, it
3829is assumed to be a @code{gdb.WP_WRITE} class.
3830@end defun
3831
3832@defun Breakpoint.stop (self)
3833The @code{gdb.Breakpoint} class can be sub-classed and, in
3834particular, you may choose to implement the @code{stop} method.
3835If this method is defined in a sub-class of @code{gdb.Breakpoint},
3836it will be called when the inferior reaches any location of a
3837breakpoint which instantiates that sub-class. If the method returns
3838@code{True}, the inferior will be stopped at the location of the
3839breakpoint, otherwise the inferior will continue.
3840
3841If there are multiple breakpoints at the same location with a
3842@code{stop} method, each one will be called regardless of the
3843return status of the previous. This ensures that all @code{stop}
3844methods have a chance to execute at that location. In this scenario
3845if one of the methods returns @code{True} but the others return
3846@code{False}, the inferior will still be stopped.
3847
3848You should not alter the execution state of the inferior (i.e.@:, step,
3849next, etc.), alter the current frame context (i.e.@:, change the current
3850active frame), or alter, add or delete any breakpoint. As a general
3851rule, you should not alter any data within @value{GDBN} or the inferior
3852at this time.
3853
3854Example @code{stop} implementation:
3855
3856@smallexample
3857class MyBreakpoint (gdb.Breakpoint):
3858 def stop (self):
3859 inf_val = gdb.parse_and_eval("foo")
3860 if inf_val == 3:
3861 return True
3862 return False
3863@end smallexample
3864@end defun
3865
3866The available watchpoint types represented by constants are defined in the
3867@code{gdb} module:
3868
b3ce5e5f
DE
3869@vtable @code
3870@vindex WP_READ
329baa95
DE
3871@item gdb.WP_READ
3872Read only watchpoint.
3873
b3ce5e5f 3874@vindex WP_WRITE
329baa95
DE
3875@item gdb.WP_WRITE
3876Write only watchpoint.
3877
b3ce5e5f 3878@vindex WP_ACCESS
329baa95
DE
3879@item gdb.WP_ACCESS
3880Read/Write watchpoint.
b3ce5e5f 3881@end vtable
329baa95
DE
3882
3883@defun Breakpoint.is_valid ()
3884Return @code{True} if this @code{Breakpoint} object is valid,
3885@code{False} otherwise. A @code{Breakpoint} object can become invalid
3886if the user deletes the breakpoint. In this case, the object still
3887exists, but the underlying breakpoint does not. In the cases of
3888watchpoint scope, the watchpoint remains valid even if execution of the
3889inferior leaves the scope of that watchpoint.
3890@end defun
3891
3892@defun Breakpoint.delete
3893Permanently deletes the @value{GDBN} breakpoint. This also
3894invalidates the Python @code{Breakpoint} object. Any further access
3895to this object's attributes or methods will raise an error.
3896@end defun
3897
3898@defvar Breakpoint.enabled
3899This attribute is @code{True} if the breakpoint is enabled, and
3900@code{False} otherwise. This attribute is writable.
3901@end defvar
3902
3903@defvar Breakpoint.silent
3904This attribute is @code{True} if the breakpoint is silent, and
3905@code{False} otherwise. This attribute is writable.
3906
3907Note that a breakpoint can also be silent if it has commands and the
3908first command is @code{silent}. This is not reported by the
3909@code{silent} attribute.
3910@end defvar
3911
3912@defvar Breakpoint.thread
3913If the breakpoint is thread-specific, this attribute holds the thread
3914id. If the breakpoint is not thread-specific, this attribute is
3915@code{None}. This attribute is writable.
3916@end defvar
3917
3918@defvar Breakpoint.task
3919If the breakpoint is Ada task-specific, this attribute holds the Ada task
3920id. If the breakpoint is not task-specific (or the underlying
3921language is not Ada), this attribute is @code{None}. This attribute
3922is writable.
3923@end defvar
3924
3925@defvar Breakpoint.ignore_count
3926This attribute holds the ignore count for the breakpoint, an integer.
3927This attribute is writable.
3928@end defvar
3929
3930@defvar Breakpoint.number
3931This attribute holds the breakpoint's number --- the identifier used by
3932the user to manipulate the breakpoint. This attribute is not writable.
3933@end defvar
3934
3935@defvar Breakpoint.type
3936This attribute holds the breakpoint's type --- the identifier used to
3937determine the actual breakpoint type or use-case. This attribute is not
3938writable.
3939@end defvar
3940
3941@defvar Breakpoint.visible
3942This attribute tells whether the breakpoint is visible to the user
3943when set, or when the @samp{info breakpoints} command is run. This
3944attribute is not writable.
3945@end defvar
3946
3947@defvar Breakpoint.temporary
3948This attribute indicates whether the breakpoint was created as a
3949temporary breakpoint. Temporary breakpoints are automatically deleted
3950after that breakpoint has been hit. Access to this attribute, and all
3951other attributes and functions other than the @code{is_valid}
3952function, will result in an error after the breakpoint has been hit
3953(as it has been automatically deleted). This attribute is not
3954writable.
3955@end defvar
3956
3957The available types are represented by constants defined in the @code{gdb}
3958module:
3959
b3ce5e5f
DE
3960@vtable @code
3961@vindex BP_BREAKPOINT
329baa95
DE
3962@item gdb.BP_BREAKPOINT
3963Normal code breakpoint.
3964
b3ce5e5f 3965@vindex BP_WATCHPOINT
329baa95
DE
3966@item gdb.BP_WATCHPOINT
3967Watchpoint breakpoint.
3968
b3ce5e5f 3969@vindex BP_HARDWARE_WATCHPOINT
329baa95
DE
3970@item gdb.BP_HARDWARE_WATCHPOINT
3971Hardware assisted watchpoint.
3972
b3ce5e5f 3973@vindex BP_READ_WATCHPOINT
329baa95
DE
3974@item gdb.BP_READ_WATCHPOINT
3975Hardware assisted read watchpoint.
3976
b3ce5e5f 3977@vindex BP_ACCESS_WATCHPOINT
329baa95
DE
3978@item gdb.BP_ACCESS_WATCHPOINT
3979Hardware assisted access watchpoint.
b3ce5e5f 3980@end vtable
329baa95
DE
3981
3982@defvar Breakpoint.hit_count
3983This attribute holds the hit count for the breakpoint, an integer.
3984This attribute is writable, but currently it can only be set to zero.
3985@end defvar
3986
3987@defvar Breakpoint.location
3988This attribute holds the location of the breakpoint, as specified by
3989the user. It is a string. If the breakpoint does not have a location
3990(that is, it is a watchpoint) the attribute's value is @code{None}. This
3991attribute is not writable.
3992@end defvar
3993
3994@defvar Breakpoint.expression
3995This attribute holds a breakpoint expression, as specified by
3996the user. It is a string. If the breakpoint does not have an
3997expression (the breakpoint is not a watchpoint) the attribute's value
3998is @code{None}. This attribute is not writable.
3999@end defvar
4000
4001@defvar Breakpoint.condition
4002This attribute holds the condition of the breakpoint, as specified by
4003the user. It is a string. If there is no condition, this attribute's
4004value is @code{None}. This attribute is writable.
4005@end defvar
4006
4007@defvar Breakpoint.commands
4008This attribute holds the commands attached to the breakpoint. If
4009there are commands, this attribute's value is a string holding all the
4010commands, separated by newlines. If there are no commands, this
4011attribute is @code{None}. This attribute is not writable.
4012@end defvar
4013
4014@node Finish Breakpoints in Python
4015@subsubsection Finish Breakpoints
4016
4017@cindex python finish breakpoints
4018@tindex gdb.FinishBreakpoint
4019
4020A finish breakpoint is a temporary breakpoint set at the return address of
4021a frame, based on the @code{finish} command. @code{gdb.FinishBreakpoint}
4022extends @code{gdb.Breakpoint}. The underlying breakpoint will be disabled
4023and deleted when the execution will run out of the breakpoint scope (i.e.@:
4024@code{Breakpoint.stop} or @code{FinishBreakpoint.out_of_scope} triggered).
4025Finish breakpoints are thread specific and must be create with the right
4026thread selected.
4027
4028@defun FinishBreakpoint.__init__ (@r{[}frame@r{]} @r{[}, internal@r{]})
4029Create a finish breakpoint at the return address of the @code{gdb.Frame}
4030object @var{frame}. If @var{frame} is not provided, this defaults to the
4031newest frame. The optional @var{internal} argument allows the breakpoint to
4032become invisible to the user. @xref{Breakpoints In Python}, for further
4033details about this argument.
4034@end defun
4035
4036@defun FinishBreakpoint.out_of_scope (self)
4037In some circumstances (e.g.@: @code{longjmp}, C@t{++} exceptions, @value{GDBN}
4038@code{return} command, @dots{}), a function may not properly terminate, and
4039thus never hit the finish breakpoint. When @value{GDBN} notices such a
4040situation, the @code{out_of_scope} callback will be triggered.
4041
4042You may want to sub-class @code{gdb.FinishBreakpoint} and override this
4043method:
4044
4045@smallexample
4046class MyFinishBreakpoint (gdb.FinishBreakpoint)
4047 def stop (self):
4048 print "normal finish"
4049 return True
4050
4051 def out_of_scope ():
4052 print "abnormal finish"
4053@end smallexample
4054@end defun
4055
4056@defvar FinishBreakpoint.return_value
4057When @value{GDBN} is stopped at a finish breakpoint and the frame
4058used to build the @code{gdb.FinishBreakpoint} object had debug symbols, this
4059attribute will contain a @code{gdb.Value} object corresponding to the return
4060value of the function. The value will be @code{None} if the function return
4061type is @code{void} or if the return value was not computable. This attribute
4062is not writable.
4063@end defvar
4064
4065@node Lazy Strings In Python
4066@subsubsection Python representation of lazy strings.
4067
4068@cindex lazy strings in python
4069@tindex gdb.LazyString
4070
4071A @dfn{lazy string} is a string whose contents is not retrieved or
4072encoded until it is needed.
4073
4074A @code{gdb.LazyString} is represented in @value{GDBN} as an
4075@code{address} that points to a region of memory, an @code{encoding}
4076that will be used to encode that region of memory, and a @code{length}
4077to delimit the region of memory that represents the string. The
4078difference between a @code{gdb.LazyString} and a string wrapped within
4079a @code{gdb.Value} is that a @code{gdb.LazyString} will be treated
4080differently by @value{GDBN} when printing. A @code{gdb.LazyString} is
4081retrieved and encoded during printing, while a @code{gdb.Value}
4082wrapping a string is immediately retrieved and encoded on creation.
4083
4084A @code{gdb.LazyString} object has the following functions:
4085
4086@defun LazyString.value ()
4087Convert the @code{gdb.LazyString} to a @code{gdb.Value}. This value
4088will point to the string in memory, but will lose all the delayed
4089retrieval, encoding and handling that @value{GDBN} applies to a
4090@code{gdb.LazyString}.
4091@end defun
4092
4093@defvar LazyString.address
4094This attribute holds the address of the string. This attribute is not
4095writable.
4096@end defvar
4097
4098@defvar LazyString.length
4099This attribute holds the length of the string in characters. If the
4100length is -1, then the string will be fetched and encoded up to the
4101first null of appropriate width. This attribute is not writable.
4102@end defvar
4103
4104@defvar LazyString.encoding
4105This attribute holds the encoding that will be applied to the string
4106when the string is printed by @value{GDBN}. If the encoding is not
4107set, or contains an empty string, then @value{GDBN} will select the
4108most appropriate encoding when the string is printed. This attribute
4109is not writable.
4110@end defvar
4111
4112@defvar LazyString.type
4113This attribute holds the type that is represented by the lazy string's
4114type. For a lazy string this will always be a pointer type. To
4115resolve this to the lazy string's character type, use the type's
4116@code{target} method. @xref{Types In Python}. This attribute is not
4117writable.
4118@end defvar
4119
4120@node Architectures In Python
4121@subsubsection Python representation of architectures
4122@cindex Python architectures
4123
4124@value{GDBN} uses architecture specific parameters and artifacts in a
4125number of its various computations. An architecture is represented
4126by an instance of the @code{gdb.Architecture} class.
4127
4128A @code{gdb.Architecture} class has the following methods:
4129
4130@defun Architecture.name ()
4131Return the name (string value) of the architecture.
4132@end defun
4133
4134@defun Architecture.disassemble (@var{start_pc} @r{[}, @var{end_pc} @r{[}, @var{count}@r{]]})
4135Return a list of disassembled instructions starting from the memory
4136address @var{start_pc}. The optional arguments @var{end_pc} and
4137@var{count} determine the number of instructions in the returned list.
4138If both the optional arguments @var{end_pc} and @var{count} are
4139specified, then a list of at most @var{count} disassembled instructions
4140whose start address falls in the closed memory address interval from
4141@var{start_pc} to @var{end_pc} are returned. If @var{end_pc} is not
4142specified, but @var{count} is specified, then @var{count} number of
4143instructions starting from the address @var{start_pc} are returned. If
4144@var{count} is not specified but @var{end_pc} is specified, then all
4145instructions whose start address falls in the closed memory address
4146interval from @var{start_pc} to @var{end_pc} are returned. If neither
4147@var{end_pc} nor @var{count} are specified, then a single instruction at
4148@var{start_pc} is returned. For all of these cases, each element of the
4149returned list is a Python @code{dict} with the following string keys:
4150
4151@table @code
4152
4153@item addr
4154The value corresponding to this key is a Python long integer capturing
4155the memory address of the instruction.
4156
4157@item asm
4158The value corresponding to this key is a string value which represents
4159the instruction with assembly language mnemonics. The assembly
4160language flavor used is the same as that specified by the current CLI
4161variable @code{disassembly-flavor}. @xref{Machine Code}.
4162
4163@item length
4164The value corresponding to this key is the length (integer value) of the
4165instruction in bytes.
4166
4167@end table
4168@end defun
4169
4170@node Python Auto-loading
4171@subsection Python Auto-loading
4172@cindex Python auto-loading
4173
4174When a new object file is read (for example, due to the @code{file}
4175command, or because the inferior has loaded a shared library),
4176@value{GDBN} will look for Python support scripts in several ways:
4177@file{@var{objfile}-gdb.py} and @code{.debug_gdb_scripts} section.
4178@xref{Auto-loading extensions}.
4179
4180The auto-loading feature is useful for supplying application-specific
4181debugging commands and scripts.
4182
4183Auto-loading can be enabled or disabled,
4184and the list of auto-loaded scripts can be printed.
4185
4186@table @code
4187@anchor{set auto-load python-scripts}
4188@kindex set auto-load python-scripts
4189@item set auto-load python-scripts [on|off]
4190Enable or disable the auto-loading of Python scripts.
4191
4192@anchor{show auto-load python-scripts}
4193@kindex show auto-load python-scripts
4194@item show auto-load python-scripts
4195Show whether auto-loading of Python scripts is enabled or disabled.
4196
4197@anchor{info auto-load python-scripts}
4198@kindex info auto-load python-scripts
4199@cindex print list of auto-loaded Python scripts
4200@item info auto-load python-scripts [@var{regexp}]
4201Print the list of all Python scripts that @value{GDBN} auto-loaded.
4202
4203Also printed is the list of Python scripts that were mentioned in
4204the @code{.debug_gdb_scripts} section and were not found
4205(@pxref{dotdebug_gdb_scripts section}).
4206This is useful because their names are not printed when @value{GDBN}
4207tries to load them and fails. There may be many of them, and printing
4208an error message for each one is problematic.
4209
4210If @var{regexp} is supplied only Python scripts with matching names are printed.
4211
4212Example:
4213
4214@smallexample
4215(gdb) info auto-load python-scripts
4216Loaded Script
4217Yes py-section-script.py
4218 full name: /tmp/py-section-script.py
4219No my-foo-pretty-printers.py
4220@end smallexample
4221@end table
4222
4223When reading an auto-loaded file, @value{GDBN} sets the
4224@dfn{current objfile}. This is available via the @code{gdb.current_objfile}
4225function (@pxref{Objfiles In Python}). This can be useful for
4226registering objfile-specific pretty-printers and frame-filters.
4227
4228@node Python modules
4229@subsection Python modules
4230@cindex python modules
4231
4232@value{GDBN} comes with several modules to assist writing Python code.
4233
4234@menu
4235* gdb.printing:: Building and registering pretty-printers.
4236* gdb.types:: Utilities for working with types.
4237* gdb.prompt:: Utilities for prompt value substitution.
4238@end menu
4239
4240@node gdb.printing
4241@subsubsection gdb.printing
4242@cindex gdb.printing
4243
4244This module provides a collection of utilities for working with
4245pretty-printers.
4246
4247@table @code
4248@item PrettyPrinter (@var{name}, @var{subprinters}=None)
4249This class specifies the API that makes @samp{info pretty-printer},
4250@samp{enable pretty-printer} and @samp{disable pretty-printer} work.
4251Pretty-printers should generally inherit from this class.
4252
4253@item SubPrettyPrinter (@var{name})
4254For printers that handle multiple types, this class specifies the
4255corresponding API for the subprinters.
4256
4257@item RegexpCollectionPrettyPrinter (@var{name})
4258Utility class for handling multiple printers, all recognized via
4259regular expressions.
4260@xref{Writing a Pretty-Printer}, for an example.
4261
4262@item FlagEnumerationPrinter (@var{name})
4263A pretty-printer which handles printing of @code{enum} values. Unlike
4264@value{GDBN}'s built-in @code{enum} printing, this printer attempts to
4265work properly when there is some overlap between the enumeration
697aa1b7
EZ
4266constants. The argument @var{name} is the name of the printer and
4267also the name of the @code{enum} type to look up.
329baa95
DE
4268
4269@item register_pretty_printer (@var{obj}, @var{printer}, @var{replace}=False)
4270Register @var{printer} with the pretty-printer list of @var{obj}.
4271If @var{replace} is @code{True} then any existing copy of the printer
4272is replaced. Otherwise a @code{RuntimeError} exception is raised
4273if a printer with the same name already exists.
4274@end table
4275
4276@node gdb.types
4277@subsubsection gdb.types
4278@cindex gdb.types
4279
4280This module provides a collection of utilities for working with
4281@code{gdb.Type} objects.
4282
4283@table @code
4284@item get_basic_type (@var{type})
4285Return @var{type} with const and volatile qualifiers stripped,
4286and with typedefs and C@t{++} references converted to the underlying type.
4287
4288C@t{++} example:
4289
4290@smallexample
4291typedef const int const_int;
4292const_int foo (3);
4293const_int& foo_ref (foo);
4294int main () @{ return 0; @}
4295@end smallexample
4296
4297Then in gdb:
4298
4299@smallexample
4300(gdb) start
4301(gdb) python import gdb.types
4302(gdb) python foo_ref = gdb.parse_and_eval("foo_ref")
4303(gdb) python print gdb.types.get_basic_type(foo_ref.type)
4304int
4305@end smallexample
4306
4307@item has_field (@var{type}, @var{field})
4308Return @code{True} if @var{type}, assumed to be a type with fields
4309(e.g., a structure or union), has field @var{field}.
4310
4311@item make_enum_dict (@var{enum_type})
4312Return a Python @code{dictionary} type produced from @var{enum_type}.
4313
4314@item deep_items (@var{type})
4315Returns a Python iterator similar to the standard
4316@code{gdb.Type.iteritems} method, except that the iterator returned
4317by @code{deep_items} will recursively traverse anonymous struct or
4318union fields. For example:
4319
4320@smallexample
4321struct A
4322@{
4323 int a;
4324 union @{
4325 int b0;
4326 int b1;
4327 @};
4328@};
4329@end smallexample
4330
4331@noindent
4332Then in @value{GDBN}:
4333@smallexample
4334(@value{GDBP}) python import gdb.types
4335(@value{GDBP}) python struct_a = gdb.lookup_type("struct A")
4336(@value{GDBP}) python print struct_a.keys ()
4337@{['a', '']@}
4338(@value{GDBP}) python print [k for k,v in gdb.types.deep_items(struct_a)]
4339@{['a', 'b0', 'b1']@}
4340@end smallexample
4341
4342@item get_type_recognizers ()
4343Return a list of the enabled type recognizers for the current context.
4344This is called by @value{GDBN} during the type-printing process
4345(@pxref{Type Printing API}).
4346
4347@item apply_type_recognizers (recognizers, type_obj)
4348Apply the type recognizers, @var{recognizers}, to the type object
4349@var{type_obj}. If any recognizer returns a string, return that
4350string. Otherwise, return @code{None}. This is called by
4351@value{GDBN} during the type-printing process (@pxref{Type Printing
4352API}).
4353
4354@item register_type_printer (locus, printer)
697aa1b7
EZ
4355This is a convenience function to register a type printer
4356@var{printer}. The printer must implement the type printer protocol.
4357The @var{locus} argument is either a @code{gdb.Objfile}, in which case
4358the printer is registered with that objfile; a @code{gdb.Progspace},
4359in which case the printer is registered with that progspace; or
4360@code{None}, in which case the printer is registered globally.
329baa95
DE
4361
4362@item TypePrinter
4363This is a base class that implements the type printer protocol. Type
4364printers are encouraged, but not required, to derive from this class.
4365It defines a constructor:
4366
4367@defmethod TypePrinter __init__ (self, name)
4368Initialize the type printer with the given name. The new printer
4369starts in the enabled state.
4370@end defmethod
4371
4372@end table
4373
4374@node gdb.prompt
4375@subsubsection gdb.prompt
4376@cindex gdb.prompt
4377
4378This module provides a method for prompt value-substitution.
4379
4380@table @code
4381@item substitute_prompt (@var{string})
4382Return @var{string} with escape sequences substituted by values. Some
4383escape sequences take arguments. You can specify arguments inside
4384``@{@}'' immediately following the escape sequence.
4385
4386The escape sequences you can pass to this function are:
4387
4388@table @code
4389@item \\
4390Substitute a backslash.
4391@item \e
4392Substitute an ESC character.
4393@item \f
4394Substitute the selected frame; an argument names a frame parameter.
4395@item \n
4396Substitute a newline.
4397@item \p
4398Substitute a parameter's value; the argument names the parameter.
4399@item \r
4400Substitute a carriage return.
4401@item \t
4402Substitute the selected thread; an argument names a thread parameter.
4403@item \v
4404Substitute the version of GDB.
4405@item \w
4406Substitute the current working directory.
4407@item \[
4408Begin a sequence of non-printing characters. These sequences are
4409typically used with the ESC character, and are not counted in the string
4410length. Example: ``\[\e[0;34m\](gdb)\[\e[0m\]'' will return a
4411blue-colored ``(gdb)'' prompt where the length is five.
4412@item \]
4413End a sequence of non-printing characters.
4414@end table
4415
4416For example:
4417
4418@smallexample
4419substitute_prompt (``frame: \f,
4420 print arguments: \p@{print frame-arguments@}'')
4421@end smallexample
4422
4423@exdent will return the string:
4424
4425@smallexample
4426"frame: main, print arguments: scalars"
4427@end smallexample
4428@end table
This page took 0.345518 seconds and 4 git commands to generate.