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