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