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