[gdb/doc] Fix some typos
[deliverable/binutils-gdb.git] / gdb / doc / python.texi
1 @c Copyright (C) 2008-2019 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
18 You can extend @value{GDBN} using the @uref{http://www.python.org/,
19 Python programming language}. This feature is available only if
20 @value{GDBN} was configured using @option{--with-python}.
21 @value{GDBN} can be built against either Python 2 or Python 3; which
22 one you have depends on this configure-time option.
23
24 @cindex python directory
25 Python scripts used by @value{GDBN} should be installed in
26 @file{@var{data-directory}/python}, where @var{data-directory} is
27 the data directory as determined at @value{GDBN} startup (@pxref{Data Files}).
28 This directory, known as the @dfn{python directory},
29 is automatically added to the Python Search Path in order to allow
30 the Python interpreter to locate all scripts installed at this location.
31
32 Additionally, @value{GDBN} commands and convenience functions which
33 are written in Python and are located in the
34 @file{@var{data-directory}/python/gdb/command} or
35 @file{@var{data-directory}/python/gdb/function} directories are
36 automatically imported when @value{GDBN} starts.
37
38 @menu
39 * Python Commands:: Accessing Python from @value{GDBN}.
40 * Python API:: Accessing @value{GDBN} from Python.
41 * Python Auto-loading:: Automatically loading Python code.
42 * Python modules:: Python modules provided by @value{GDBN}.
43 @end menu
44
45 @node Python Commands
46 @subsection Python Commands
47 @cindex python commands
48 @cindex commands to access python
49
50 @value{GDBN} provides two commands for accessing the Python interpreter,
51 and one related setting:
52
53 @table @code
54 @kindex python-interactive
55 @kindex pi
56 @item python-interactive @r{[}@var{command}@r{]}
57 @itemx pi @r{[}@var{command}@r{]}
58 Without an argument, the @code{python-interactive} command can be used
59 to start an interactive Python prompt. To return to @value{GDBN},
60 type the @code{EOF} character (e.g., @kbd{Ctrl-D} on an empty prompt).
61
62 Alternatively, a single-line Python command can be given as an
63 argument and evaluated. If the command is an expression, the result
64 will be printed; otherwise, nothing will be printed. For example:
65
66 @smallexample
67 (@value{GDBP}) python-interactive 2 + 3
68 5
69 @end smallexample
70
71 @kindex python
72 @kindex py
73 @item python @r{[}@var{command}@r{]}
74 @itemx py @r{[}@var{command}@r{]}
75 The @code{python} command can be used to evaluate Python code.
76
77 If given an argument, the @code{python} command will evaluate the
78 argument as a Python command. For example:
79
80 @smallexample
81 (@value{GDBP}) python print 23
82 23
83 @end smallexample
84
85 If you do not provide an argument to @code{python}, it will act as a
86 multi-line command, like @code{define}. In this case, the Python
87 script is made up of subsequent command lines, given after the
88 @code{python} command. This command list is terminated using a line
89 containing @code{end}. For example:
90
91 @smallexample
92 (@value{GDBP}) python
93 >print 23
94 >end
95 23
96 @end smallexample
97
98 @kindex set python print-stack
99 @item set python print-stack
100 By default, @value{GDBN} will print only the message component of a
101 Python exception when an error occurs in a Python script. This can be
102 controlled using @code{set python print-stack}: if @code{full}, then
103 full Python stack printing is enabled; if @code{none}, then Python stack
104 and message printing is disabled; if @code{message}, the default, only
105 the message component of the error is printed.
106 @end table
107
108 It is also possible to execute a Python script from the @value{GDBN}
109 interpreter:
110
111 @table @code
112 @item source @file{script-name}
113 The script name must end with @samp{.py} and @value{GDBN} must be configured
114 to recognize the script language based on filename extension using
115 the @code{script-extension} setting. @xref{Extending GDB, ,Extending GDB}.
116 @end table
117
118 @node Python API
119 @subsection Python API
120 @cindex python api
121 @cindex programming in python
122
123 You can get quick online help for @value{GDBN}'s Python API by issuing
124 the command @w{@kbd{python help (gdb)}}.
125
126 Functions and methods which have two or more optional arguments allow
127 them to be specified using keyword syntax. This allows passing some
128 optional arguments while skipping others. Example:
129 @w{@code{gdb.some_function ('foo', bar = 1, baz = 2)}}.
130
131 @menu
132 * Basic Python:: Basic Python Functions.
133 * Exception Handling:: How Python exceptions are translated.
134 * Values From Inferior:: Python representation of values.
135 * Types In Python:: Python representation of types.
136 * Pretty Printing API:: Pretty-printing values.
137 * Selecting Pretty-Printers:: How GDB chooses a pretty-printer.
138 * Writing a Pretty-Printer:: Writing a Pretty-Printer.
139 * Type Printing API:: Pretty-printing types.
140 * Frame Filter API:: Filtering Frames.
141 * Frame Decorator API:: Decorating Frames.
142 * Writing a Frame Filter:: Writing a Frame Filter.
143 * Unwinding Frames in Python:: Writing frame unwinder.
144 * Xmethods In Python:: Adding and replacing methods of C++ classes.
145 * Xmethod API:: Xmethod types.
146 * Writing an Xmethod:: Writing an xmethod.
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 * Recordings In Python:: Accessing recordings from Python.
151 * Commands In Python:: Implementing new commands in Python.
152 * Parameters In Python:: Adding new @value{GDBN} parameters.
153 * Functions In Python:: Writing new convenience functions.
154 * Progspaces In Python:: Program spaces.
155 * Objfiles In Python:: Object files.
156 * Frames In Python:: Accessing inferior stack frames from Python.
157 * Blocks In Python:: Accessing blocks from Python.
158 * Symbols In Python:: Python representation of symbols.
159 * Symbol Tables In Python:: Python representation of symbol tables.
160 * Line Tables In Python:: Python representation of line tables.
161 * Breakpoints In Python:: Manipulating breakpoints using Python.
162 * Finish Breakpoints in Python:: Setting Breakpoints on function return
163 using Python.
164 * Lazy Strings In Python:: Python representation of lazy strings.
165 * Architectures In Python:: Python representation of architectures.
166 @end menu
167
168 @node Basic Python
169 @subsubsection Basic Python
170
171 @cindex python stdout
172 @cindex python pagination
173 At startup, @value{GDBN} overrides Python's @code{sys.stdout} and
174 @code{sys.stderr} to print using @value{GDBN}'s output-paging streams.
175 A Python program which outputs to one of these streams may have its
176 output interrupted by the user (@pxref{Screen Size}). In this
177 situation, a Python @code{KeyboardInterrupt} exception is thrown.
178
179 Some care must be taken when writing Python code to run in
180 @value{GDBN}. Two things worth noting in particular:
181
182 @itemize @bullet
183 @item
184 @value{GDBN} install handlers for @code{SIGCHLD} and @code{SIGINT}.
185 Python code must not override these, or even change the options using
186 @code{sigaction}. If your program changes the handling of these
187 signals, @value{GDBN} will most likely stop working correctly. Note
188 that it is unfortunately common for GUI toolkits to install a
189 @code{SIGCHLD} handler.
190
191 @item
192 @value{GDBN} takes care to mark its internal file descriptors as
193 close-on-exec. However, this cannot be done in a thread-safe way on
194 all platforms. Your Python programs should be aware of this and
195 should both create new file descriptors with the close-on-exec flag
196 set and arrange to close unneeded file descriptors before starting a
197 child process.
198 @end itemize
199
200 @cindex python functions
201 @cindex python module
202 @cindex gdb module
203 @value{GDBN} introduces a new Python module, named @code{gdb}. All
204 methods and classes added by @value{GDBN} are placed in this module.
205 @value{GDBN} automatically @code{import}s the @code{gdb} module for
206 use in all scripts evaluated by the @code{python} command.
207
208 Some types of the @code{gdb} module come with a textual representation
209 (accessible through the @code{repr} or @code{str} functions). These are
210 offered for debugging purposes only, expect them to change over time.
211
212 @findex gdb.PYTHONDIR
213 @defvar gdb.PYTHONDIR
214 A string containing the python directory (@pxref{Python}).
215 @end defvar
216
217 @findex gdb.execute
218 @defun gdb.execute (command @r{[}, from_tty @r{[}, to_string@r{]]})
219 Evaluate @var{command}, a string, as a @value{GDBN} CLI command.
220 If a GDB exception happens while @var{command} runs, it is
221 translated as described in @ref{Exception Handling,,Exception Handling}.
222
223 The @var{from_tty} flag specifies whether @value{GDBN} ought to consider this
224 command as having originated from the user invoking it interactively.
225 It must be a boolean value. If omitted, it defaults to @code{False}.
226
227 By default, any output produced by @var{command} is sent to
228 @value{GDBN}'s standard output (and to the log output if logging is
229 turned on). If the @var{to_string} parameter is
230 @code{True}, then output will be collected by @code{gdb.execute} and
231 returned as a string. The default is @code{False}, in which case the
232 return value is @code{None}. If @var{to_string} is @code{True}, the
233 @value{GDBN} virtual terminal will be temporarily set to unlimited width
234 and height, and its pagination will be disabled; @pxref{Screen Size}.
235 @end defun
236
237 @findex gdb.breakpoints
238 @defun gdb.breakpoints ()
239 Return a sequence holding all of @value{GDBN}'s breakpoints.
240 @xref{Breakpoints In Python}, for more information. In @value{GDBN}
241 version 7.11 and earlier, this function returned @code{None} if there
242 were no breakpoints. This peculiarity was subsequently fixed, and now
243 @code{gdb.breakpoints} returns an empty sequence in this case.
244 @end defun
245
246 @defun gdb.rbreak (regex @r{[}, minsyms @r{[}, throttle, @r{[}, symtabs @r{]]]})
247 Return a Python list holding a collection of newly set
248 @code{gdb.Breakpoint} objects matching function names defined by the
249 @var{regex} pattern. If the @var{minsyms} keyword is @code{True}, all
250 system functions (those not explicitly defined in the inferior) will
251 also be included in the match. The @var{throttle} keyword takes an
252 integer that defines the maximum number of pattern matches for
253 functions matched by the @var{regex} pattern. If the number of
254 matches exceeds the integer value of @var{throttle}, a
255 @code{RuntimeError} will be raised and no breakpoints will be created.
256 If @var{throttle} is not defined then there is no imposed limit on the
257 maximum number of matches and breakpoints to be created. The
258 @var{symtabs} keyword takes a Python iterable that yields a collection
259 of @code{gdb.Symtab} objects and will restrict the search to those
260 functions only contained within the @code{gdb.Symtab} objects.
261 @end defun
262
263 @findex gdb.parameter
264 @defun gdb.parameter (parameter)
265 Return the value of a @value{GDBN} @var{parameter} given by its name,
266 a string; the parameter name string may contain spaces if the parameter has a
267 multi-part name. For example, @samp{print object} is a valid
268 parameter name.
269
270 If the named parameter does not exist, this function throws a
271 @code{gdb.error} (@pxref{Exception Handling}). Otherwise, the
272 parameter's value is converted to a Python value of the appropriate
273 type, and returned.
274 @end defun
275
276 @findex gdb.history
277 @defun gdb.history (number)
278 Return a value from @value{GDBN}'s value history (@pxref{Value
279 History}). The @var{number} argument indicates which history element to return.
280 If @var{number} is negative, then @value{GDBN} will take its absolute value
281 and count backward from the last element (i.e., the most recent element) to
282 find the value to return. If @var{number} is zero, then @value{GDBN} will
283 return the most recent element. If the element specified by @var{number}
284 doesn't exist in the value history, a @code{gdb.error} exception will be
285 raised.
286
287 If no exception is raised, the return value is always an instance of
288 @code{gdb.Value} (@pxref{Values From Inferior}).
289 @end defun
290
291 @findex gdb.convenience_variable
292 @defun gdb.convenience_variable (name)
293 Return the value of the convenience variable (@pxref{Convenience
294 Vars}) named @var{name}. @var{name} must be a string. The name
295 should not include the @samp{$} that is used to mark a convenience
296 variable in an expression. If the convenience variable does not
297 exist, then @code{None} is returned.
298 @end defun
299
300 @findex gdb.set_convenience_variable
301 @defun gdb.set_convenience_variable (name, value)
302 Set the value of the convenience variable (@pxref{Convenience Vars})
303 named @var{name}. @var{name} must be a string. The name should not
304 include the @samp{$} that is used to mark a convenience variable in an
305 expression. If @var{value} is @code{None}, then the convenience
306 variable is removed. Otherwise, if @var{value} is not a
307 @code{gdb.Value} (@pxref{Values From Inferior}), it is is converted
308 using the @code{gdb.Value} constructor.
309 @end defun
310
311 @findex gdb.parse_and_eval
312 @defun gdb.parse_and_eval (expression)
313 Parse @var{expression}, which must be a string, as an expression in
314 the current language, evaluate it, and return the result as a
315 @code{gdb.Value}.
316
317 This function can be useful when implementing a new command
318 (@pxref{Commands In Python}), as it provides a way to parse the
319 command's argument as an expression. It is also useful simply to
320 compute values.
321 @end defun
322
323 @findex gdb.find_pc_line
324 @defun gdb.find_pc_line (pc)
325 Return the @code{gdb.Symtab_and_line} object corresponding to the
326 @var{pc} value. @xref{Symbol Tables In Python}. If an invalid
327 value of @var{pc} is passed as an argument, then the @code{symtab} and
328 @code{line} attributes of the returned @code{gdb.Symtab_and_line} object
329 will be @code{None} and 0 respectively. This is identical to
330 @code{gdb.current_progspace().find_pc_line(pc)} and is included for
331 historical compatibility.
332 @end defun
333
334 @findex gdb.post_event
335 @defun gdb.post_event (event)
336 Put @var{event}, a callable object taking no arguments, into
337 @value{GDBN}'s internal event queue. This callable will be invoked at
338 some later point, during @value{GDBN}'s event processing. Events
339 posted using @code{post_event} will be run in the order in which they
340 were posted; however, there is no way to know when they will be
341 processed relative to other events inside @value{GDBN}.
342
343 @value{GDBN} is not thread-safe. If your Python program uses multiple
344 threads, you must be careful to only call @value{GDBN}-specific
345 functions in the @value{GDBN} thread. @code{post_event} ensures
346 this. For example:
347
348 @smallexample
349 (@value{GDBP}) python
350 >import threading
351 >
352 >class Writer():
353 > def __init__(self, message):
354 > self.message = message;
355 > def __call__(self):
356 > gdb.write(self.message)
357 >
358 >class MyThread1 (threading.Thread):
359 > def run (self):
360 > gdb.post_event(Writer("Hello "))
361 >
362 >class MyThread2 (threading.Thread):
363 > def run (self):
364 > gdb.post_event(Writer("World\n"))
365 >
366 >MyThread1().start()
367 >MyThread2().start()
368 >end
369 (@value{GDBP}) Hello World
370 @end smallexample
371 @end defun
372
373 @findex gdb.write
374 @defun gdb.write (string @r{[}, stream{]})
375 Print a string to @value{GDBN}'s paginated output stream. The
376 optional @var{stream} determines the stream to print to. The default
377 stream is @value{GDBN}'s standard output stream. Possible stream
378 values are:
379
380 @table @code
381 @findex STDOUT
382 @findex gdb.STDOUT
383 @item gdb.STDOUT
384 @value{GDBN}'s standard output stream.
385
386 @findex STDERR
387 @findex gdb.STDERR
388 @item gdb.STDERR
389 @value{GDBN}'s standard error stream.
390
391 @findex STDLOG
392 @findex gdb.STDLOG
393 @item gdb.STDLOG
394 @value{GDBN}'s log stream (@pxref{Logging Output}).
395 @end table
396
397 Writing to @code{sys.stdout} or @code{sys.stderr} will automatically
398 call this function and will automatically direct the output to the
399 relevant stream.
400 @end defun
401
402 @findex gdb.flush
403 @defun gdb.flush ()
404 Flush the buffer of a @value{GDBN} paginated stream so that the
405 contents are displayed immediately. @value{GDBN} will flush the
406 contents of a stream automatically when it encounters a newline in the
407 buffer. The optional @var{stream} determines the stream to flush. The
408 default stream is @value{GDBN}'s standard output stream. Possible
409 stream values are:
410
411 @table @code
412 @findex STDOUT
413 @findex gdb.STDOUT
414 @item gdb.STDOUT
415 @value{GDBN}'s standard output stream.
416
417 @findex STDERR
418 @findex gdb.STDERR
419 @item gdb.STDERR
420 @value{GDBN}'s standard error stream.
421
422 @findex STDLOG
423 @findex gdb.STDLOG
424 @item gdb.STDLOG
425 @value{GDBN}'s log stream (@pxref{Logging Output}).
426
427 @end table
428
429 Flushing @code{sys.stdout} or @code{sys.stderr} will automatically
430 call this function for the relevant stream.
431 @end defun
432
433 @findex gdb.target_charset
434 @defun gdb.target_charset ()
435 Return the name of the current target character set (@pxref{Character
436 Sets}). This differs from @code{gdb.parameter('target-charset')} in
437 that @samp{auto} is never returned.
438 @end defun
439
440 @findex gdb.target_wide_charset
441 @defun gdb.target_wide_charset ()
442 Return the name of the current target wide character set
443 (@pxref{Character Sets}). This differs from
444 @code{gdb.parameter('target-wide-charset')} in that @samp{auto} is
445 never returned.
446 @end defun
447
448 @findex gdb.solib_name
449 @defun gdb.solib_name (address)
450 Return the name of the shared library holding the given @var{address}
451 as a string, or @code{None}. This is identical to
452 @code{gdb.current_progspace().solib_name(address)} and is included for
453 historical compatibility.
454 @end defun
455
456 @findex gdb.decode_line
457 @defun gdb.decode_line (@r{[}expression@r{]})
458 Return locations of the line specified by @var{expression}, or of the
459 current line if no argument was given. This function returns a Python
460 tuple containing two elements. The first element contains a string
461 holding any unparsed section of @var{expression} (or @code{None} if
462 the expression has been fully parsed). The second element contains
463 either @code{None} or another tuple that contains all the locations
464 that match the expression represented as @code{gdb.Symtab_and_line}
465 objects (@pxref{Symbol Tables In Python}). If @var{expression} is
466 provided, it is decoded the way that @value{GDBN}'s inbuilt
467 @code{break} or @code{edit} commands do (@pxref{Specify Location}).
468 @end defun
469
470 @defun gdb.prompt_hook (current_prompt)
471 @anchor{prompt_hook}
472
473 If @var{prompt_hook} is callable, @value{GDBN} will call the method
474 assigned to this operation before a prompt is displayed by
475 @value{GDBN}.
476
477 The parameter @code{current_prompt} contains the current @value{GDBN}
478 prompt. This method must return a Python string, or @code{None}. If
479 a string is returned, the @value{GDBN} prompt will be set to that
480 string. If @code{None} is returned, @value{GDBN} will continue to use
481 the current prompt.
482
483 Some prompts cannot be substituted in @value{GDBN}. Secondary prompts
484 such as those used by readline for command input, and annotation
485 related prompts are prohibited from being changed.
486 @end defun
487
488 @node Exception Handling
489 @subsubsection Exception Handling
490 @cindex python exceptions
491 @cindex exceptions, python
492
493 When executing the @code{python} command, Python exceptions
494 uncaught within the Python code are translated to calls to
495 @value{GDBN} error-reporting mechanism. If the command that called
496 @code{python} does not handle the error, @value{GDBN} will
497 terminate it and print an error message containing the Python
498 exception name, the associated value, and the Python call stack
499 backtrace at the point where the exception was raised. Example:
500
501 @smallexample
502 (@value{GDBP}) python print foo
503 Traceback (most recent call last):
504 File "<string>", line 1, in <module>
505 NameError: name 'foo' is not defined
506 @end smallexample
507
508 @value{GDBN} errors that happen in @value{GDBN} commands invoked by
509 Python code are converted to Python exceptions. The type of the
510 Python exception depends on the error.
511
512 @ftable @code
513 @item gdb.error
514 This is the base class for most exceptions generated by @value{GDBN}.
515 It is derived from @code{RuntimeError}, for compatibility with earlier
516 versions of @value{GDBN}.
517
518 If an error occurring in @value{GDBN} does not fit into some more
519 specific category, then the generated exception will have this type.
520
521 @item gdb.MemoryError
522 This is a subclass of @code{gdb.error} which is thrown when an
523 operation tried to access invalid memory in the inferior.
524
525 @item KeyboardInterrupt
526 User interrupt (via @kbd{C-c} or by typing @kbd{q} at a pagination
527 prompt) is translated to a Python @code{KeyboardInterrupt} exception.
528 @end ftable
529
530 In all cases, your exception handler will see the @value{GDBN} error
531 message as its value and the Python call stack backtrace at the Python
532 statement closest to where the @value{GDBN} error occured as the
533 traceback.
534
535
536 When implementing @value{GDBN} commands in Python via
537 @code{gdb.Command}, or functions via @code{gdb.Function}, it is useful
538 to be able to throw an exception that doesn't cause a traceback to be
539 printed. For example, the user may have invoked the command
540 incorrectly. @value{GDBN} provides a special exception class that can
541 be used for this purpose.
542
543 @ftable @code
544 @item gdb.GdbError
545 When thrown from a command or function, this exception will cause the
546 command or function to fail, but the Python stack will not be
547 displayed. @value{GDBN} does not throw this exception itself, but
548 rather recognizes it when thrown from user Python code. Example:
549
550 @smallexample
551 (gdb) python
552 >class HelloWorld (gdb.Command):
553 > """Greet the whole world."""
554 > def __init__ (self):
555 > super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
556 > def invoke (self, args, from_tty):
557 > argv = gdb.string_to_argv (args)
558 > if len (argv) != 0:
559 > raise gdb.GdbError ("hello-world takes no arguments")
560 > print "Hello, World!"
561 >HelloWorld ()
562 >end
563 (gdb) hello-world 42
564 hello-world takes no arguments
565 @end smallexample
566 @end ftable
567
568 @node Values From Inferior
569 @subsubsection Values From Inferior
570 @cindex values from inferior, with Python
571 @cindex python, working with values from inferior
572
573 @cindex @code{gdb.Value}
574 @value{GDBN} provides values it obtains from the inferior program in
575 an object of type @code{gdb.Value}. @value{GDBN} uses this object
576 for its internal bookkeeping of the inferior's values, and for
577 fetching values when necessary.
578
579 Inferior values that are simple scalars can be used directly in
580 Python expressions that are valid for the value's data type. Here's
581 an example for an integer or floating-point value @code{some_val}:
582
583 @smallexample
584 bar = some_val + 2
585 @end smallexample
586
587 @noindent
588 As result of this, @code{bar} will also be a @code{gdb.Value} object
589 whose values are of the same type as those of @code{some_val}. Valid
590 Python operations can also be performed on @code{gdb.Value} objects
591 representing a @code{struct} or @code{class} object. For such cases,
592 the overloaded operator (if present), is used to perform the operation.
593 For example, if @code{val1} and @code{val2} are @code{gdb.Value} objects
594 representing instances of a @code{class} which overloads the @code{+}
595 operator, then one can use the @code{+} operator in their Python script
596 as follows:
597
598 @smallexample
599 val3 = val1 + val2
600 @end smallexample
601
602 @noindent
603 The result of the operation @code{val3} is also a @code{gdb.Value}
604 object corresponding to the value returned by the overloaded @code{+}
605 operator. In general, overloaded operators are invoked for the
606 following operations: @code{+} (binary addition), @code{-} (binary
607 subtraction), @code{*} (multiplication), @code{/}, @code{%}, @code{<<},
608 @code{>>}, @code{|}, @code{&}, @code{^}.
609
610 Inferior values that are structures or instances of some class can
611 be accessed using the Python @dfn{dictionary syntax}. For example, if
612 @code{some_val} is a @code{gdb.Value} instance holding a structure, you
613 can access its @code{foo} element with:
614
615 @smallexample
616 bar = some_val['foo']
617 @end smallexample
618
619 @cindex getting structure elements using gdb.Field objects as subscripts
620 Again, @code{bar} will also be a @code{gdb.Value} object. Structure
621 elements can also be accessed by using @code{gdb.Field} objects as
622 subscripts (@pxref{Types In Python}, for more information on
623 @code{gdb.Field} objects). For example, if @code{foo_field} is a
624 @code{gdb.Field} object corresponding to element @code{foo} of the above
625 structure, then @code{bar} can also be accessed as follows:
626
627 @smallexample
628 bar = some_val[foo_field]
629 @end smallexample
630
631 A @code{gdb.Value} that represents a function can be executed via
632 inferior function call. Any arguments provided to the call must match
633 the function's prototype, and must be provided in the order specified
634 by that prototype.
635
636 For example, @code{some_val} is a @code{gdb.Value} instance
637 representing a function that takes two integers as arguments. To
638 execute this function, call it like so:
639
640 @smallexample
641 result = some_val (10,20)
642 @end smallexample
643
644 Any values returned from a function call will be stored as a
645 @code{gdb.Value}.
646
647 The following attributes are provided:
648
649 @defvar Value.address
650 If this object is addressable, this read-only attribute holds a
651 @code{gdb.Value} object representing the address. Otherwise,
652 this attribute holds @code{None}.
653 @end defvar
654
655 @cindex optimized out value in Python
656 @defvar Value.is_optimized_out
657 This read-only boolean attribute is true if the compiler optimized out
658 this value, thus it is not available for fetching from the inferior.
659 @end defvar
660
661 @defvar Value.type
662 The type of this @code{gdb.Value}. The value of this attribute is a
663 @code{gdb.Type} object (@pxref{Types In Python}).
664 @end defvar
665
666 @defvar Value.dynamic_type
667 The dynamic type of this @code{gdb.Value}. This uses the object's
668 virtual table and the C@t{++} run-time type information
669 (@acronym{RTTI}) to determine the dynamic type of the value. If this
670 value is of class type, it will return the class in which the value is
671 embedded, if any. If this value is of pointer or reference to a class
672 type, it will compute the dynamic type of the referenced object, and
673 return a pointer or reference to that type, respectively. In all
674 other cases, it will return the value's static type.
675
676 Note that this feature will only work when debugging a C@t{++} program
677 that includes @acronym{RTTI} for the object in question. Otherwise,
678 it will just return the static type of the value as in @kbd{ptype foo}
679 (@pxref{Symbols, ptype}).
680 @end defvar
681
682 @defvar Value.is_lazy
683 The value of this read-only boolean attribute is @code{True} if this
684 @code{gdb.Value} has not yet been fetched from the inferior.
685 @value{GDBN} does not fetch values until necessary, for efficiency.
686 For example:
687
688 @smallexample
689 myval = gdb.parse_and_eval ('somevar')
690 @end smallexample
691
692 The value of @code{somevar} is not fetched at this time. It will be
693 fetched when the value is needed, or when the @code{fetch_lazy}
694 method is invoked.
695 @end defvar
696
697 The following methods are provided:
698
699 @defun Value.__init__ (@var{val})
700 Many Python values can be converted directly to a @code{gdb.Value} via
701 this object initializer. Specifically:
702
703 @table @asis
704 @item Python boolean
705 A Python boolean is converted to the boolean type from the current
706 language.
707
708 @item Python integer
709 A Python integer is converted to the C @code{long} type for the
710 current architecture.
711
712 @item Python long
713 A Python long is converted to the C @code{long long} type for the
714 current architecture.
715
716 @item Python float
717 A Python float is converted to the C @code{double} type for the
718 current architecture.
719
720 @item Python string
721 A Python string is converted to a target string in the current target
722 language using the current target encoding.
723 If a character cannot be represented in the current target encoding,
724 then an exception is thrown.
725
726 @item @code{gdb.Value}
727 If @code{val} is a @code{gdb.Value}, then a copy of the value is made.
728
729 @item @code{gdb.LazyString}
730 If @code{val} is a @code{gdb.LazyString} (@pxref{Lazy Strings In
731 Python}), then the lazy string's @code{value} method is called, and
732 its result is used.
733 @end table
734 @end defun
735
736 @defun Value.__init__ (@var{val}, @var{type})
737 This second form of the @code{gdb.Value} constructor returns a
738 @code{gdb.Value} of type @var{type} where the value contents are taken
739 from the Python buffer object specified by @var{val}. The number of
740 bytes in the Python buffer object must be greater than or equal to the
741 size of @var{type}.
742 @end defun
743
744 @defun Value.cast (type)
745 Return a new instance of @code{gdb.Value} that is the result of
746 casting this instance to the type described by @var{type}, which must
747 be a @code{gdb.Type} object. If the cast cannot be performed for some
748 reason, this method throws an exception.
749 @end defun
750
751 @defun Value.dereference ()
752 For pointer data types, this method returns a new @code{gdb.Value} object
753 whose contents is the object pointed to by the pointer. For example, if
754 @code{foo} is a C pointer to an @code{int}, declared in your C program as
755
756 @smallexample
757 int *foo;
758 @end smallexample
759
760 @noindent
761 then you can use the corresponding @code{gdb.Value} to access what
762 @code{foo} points to like this:
763
764 @smallexample
765 bar = foo.dereference ()
766 @end smallexample
767
768 The result @code{bar} will be a @code{gdb.Value} object holding the
769 value pointed to by @code{foo}.
770
771 A similar function @code{Value.referenced_value} exists which also
772 returns @code{gdb.Value} objects corresponding to the values pointed to
773 by pointer values (and additionally, values referenced by reference
774 values). However, the behavior of @code{Value.dereference}
775 differs from @code{Value.referenced_value} by the fact that the
776 behavior of @code{Value.dereference} is identical to applying the C
777 unary operator @code{*} on a given value. For example, consider a
778 reference to a pointer @code{ptrref}, declared in your C@t{++} program
779 as
780
781 @smallexample
782 typedef int *intptr;
783 ...
784 int val = 10;
785 intptr ptr = &val;
786 intptr &ptrref = ptr;
787 @end smallexample
788
789 Though @code{ptrref} is a reference value, one can apply the method
790 @code{Value.dereference} to the @code{gdb.Value} object corresponding
791 to it and obtain a @code{gdb.Value} which is identical to that
792 corresponding to @code{val}. However, if you apply the method
793 @code{Value.referenced_value}, the result would be a @code{gdb.Value}
794 object identical to that corresponding to @code{ptr}.
795
796 @smallexample
797 py_ptrref = gdb.parse_and_eval ("ptrref")
798 py_val = py_ptrref.dereference ()
799 py_ptr = py_ptrref.referenced_value ()
800 @end smallexample
801
802 The @code{gdb.Value} object @code{py_val} is identical to that
803 corresponding to @code{val}, and @code{py_ptr} is identical to that
804 corresponding to @code{ptr}. In general, @code{Value.dereference} can
805 be applied whenever the C unary operator @code{*} can be applied
806 to the corresponding C value. For those cases where applying both
807 @code{Value.dereference} and @code{Value.referenced_value} is allowed,
808 the results obtained need not be identical (as we have seen in the above
809 example). The results are however identical when applied on
810 @code{gdb.Value} objects corresponding to pointers (@code{gdb.Value}
811 objects with type code @code{TYPE_CODE_PTR}) in a C/C@t{++} program.
812 @end defun
813
814 @defun Value.referenced_value ()
815 For pointer or reference data types, this method returns a new
816 @code{gdb.Value} object corresponding to the value referenced by the
817 pointer/reference value. For pointer data types,
818 @code{Value.dereference} and @code{Value.referenced_value} produce
819 identical results. The difference between these methods is that
820 @code{Value.dereference} cannot get the values referenced by reference
821 values. For example, consider a reference to an @code{int}, declared
822 in your C@t{++} program as
823
824 @smallexample
825 int val = 10;
826 int &ref = val;
827 @end smallexample
828
829 @noindent
830 then applying @code{Value.dereference} to the @code{gdb.Value} object
831 corresponding to @code{ref} will result in an error, while applying
832 @code{Value.referenced_value} will result in a @code{gdb.Value} object
833 identical to that corresponding to @code{val}.
834
835 @smallexample
836 py_ref = gdb.parse_and_eval ("ref")
837 er_ref = py_ref.dereference () # Results in error
838 py_val = py_ref.referenced_value () # Returns the referenced value
839 @end smallexample
840
841 The @code{gdb.Value} object @code{py_val} is identical to that
842 corresponding to @code{val}.
843 @end defun
844
845 @defun Value.reference_value ()
846 Return a @code{gdb.Value} object which is a reference to the value
847 encapsulated by this instance.
848 @end defun
849
850 @defun Value.const_value ()
851 Return a @code{gdb.Value} object which is a @code{const} version of the
852 value encapsulated by this instance.
853 @end defun
854
855 @defun Value.dynamic_cast (type)
856 Like @code{Value.cast}, but works as if the C@t{++} @code{dynamic_cast}
857 operator were used. Consult a C@t{++} reference for details.
858 @end defun
859
860 @defun Value.reinterpret_cast (type)
861 Like @code{Value.cast}, but works as if the C@t{++} @code{reinterpret_cast}
862 operator were used. Consult a C@t{++} reference for details.
863 @end defun
864
865 @defun Value.format_string (...)
866 Convert a @code{gdb.Value} to a string, similarly to what the @code{print}
867 command does. Invoked with no arguments, this is equivalent to calling
868 the @code{str} function on the @code{gdb.Value}. The representation of
869 the same value may change across different versions of @value{GDBN}, so
870 you shouldn't, for instance, parse the strings returned by this method.
871
872 All the arguments are keyword only. If an argument is not specified, the
873 current global default setting is used.
874
875 @table @code
876 @item raw
877 @code{True} if pretty-printers (@pxref{Pretty Printing}) should not be
878 used to format the value. @code{False} if enabled pretty-printers
879 matching the type represented by the @code{gdb.Value} should be used to
880 format it.
881
882 @item pretty_arrays
883 @code{True} if arrays should be pretty printed to be more convenient to
884 read, @code{False} if they shouldn't (see @code{set print array} in
885 @ref{Print Settings}).
886
887 @item pretty_structs
888 @code{True} if structs should be pretty printed to be more convenient to
889 read, @code{False} if they shouldn't (see @code{set print pretty} in
890 @ref{Print Settings}).
891
892 @item array_indexes
893 @code{True} if array indexes should be included in the string
894 representation of arrays, @code{False} if they shouldn't (see @code{set
895 print array-indexes} in @ref{Print Settings}).
896
897 @item symbols
898 @code{True} if the string representation of a pointer should include the
899 corresponding symbol name (if one exists), @code{False} if it shouldn't
900 (see @code{set print symbol} in @ref{Print Settings}).
901
902 @item unions
903 @code{True} if unions which are contained in other structures or unions
904 should be expanded, @code{False} if they shouldn't (see @code{set print
905 union} in @ref{Print Settings}).
906
907 @item deref_refs
908 @code{True} if C@t{++} references should be resolved to the value they
909 refer to, @code{False} (the default) if they shouldn't. Note that, unlike
910 for the @code{print} command, references are not automatically expanded
911 when using the @code{format_string} method or the @code{str}
912 function. There is no global @code{print} setting to change the default
913 behaviour.
914
915 @item actual_objects
916 @code{True} if the representation of a pointer to an object should
917 identify the @emph{actual} (derived) type of the object rather than the
918 @emph{declared} type, using the virtual function table. @code{False} if
919 the @emph{declared} type should be used. (See @code{set print object} in
920 @ref{Print Settings}).
921
922 @item static_fields
923 @code{True} if static members should be included in the string
924 representation of a C@t{++} object, @code{False} if they shouldn't (see
925 @code{set print static-members} in @ref{Print Settings}).
926
927 @item max_elements
928 Number of array elements to print, or @code{0} to print an unlimited
929 number of elements (see @code{set print elements} in @ref{Print
930 Settings}).
931
932 @item max_depth
933 The maximum depth to print for nested structs and unions, or @code{-1}
934 to print an unlimited number of elements (see @code{set print
935 max-depth} in @ref{Print Settings}).
936
937 @item repeat_threshold
938 Set the threshold for suppressing display of repeated array elements, or
939 @code{0} to represent all elements, even if repeated. (See @code{set
940 print repeats} in @ref{Print Settings}).
941
942 @item format
943 A string containing a single character representing the format to use for
944 the returned string. For instance, @code{'x'} is equivalent to using the
945 @value{GDBN} command @code{print} with the @code{/x} option and formats
946 the value as a hexadecimal number.
947 @end table
948 @end defun
949
950 @defun Value.string (@r{[}encoding@r{[}, errors@r{[}, length@r{]]]})
951 If this @code{gdb.Value} represents a string, then this method
952 converts the contents to a Python string. Otherwise, this method will
953 throw an exception.
954
955 Values are interpreted as strings according to the rules of the
956 current language. If the optional length argument is given, the
957 string will be converted to that length, and will include any embedded
958 zeroes that the string may contain. Otherwise, for languages
959 where the string is zero-terminated, the entire string will be
960 converted.
961
962 For example, in C-like languages, a value is a string if it is a pointer
963 to or an array of characters or ints of type @code{wchar_t}, @code{char16_t},
964 or @code{char32_t}.
965
966 If the optional @var{encoding} argument is given, it must be a string
967 naming the encoding of the string in the @code{gdb.Value}, such as
968 @code{"ascii"}, @code{"iso-8859-6"} or @code{"utf-8"}. It accepts
969 the same encodings as the corresponding argument to Python's
970 @code{string.decode} method, and the Python codec machinery will be used
971 to convert the string. If @var{encoding} is not given, or if
972 @var{encoding} is the empty string, then either the @code{target-charset}
973 (@pxref{Character Sets}) will be used, or a language-specific encoding
974 will be used, if the current language is able to supply one.
975
976 The optional @var{errors} argument is the same as the corresponding
977 argument to Python's @code{string.decode} method.
978
979 If the optional @var{length} argument is given, the string will be
980 fetched and converted to the given length.
981 @end defun
982
983 @defun Value.lazy_string (@r{[}encoding @r{[}, length@r{]]})
984 If this @code{gdb.Value} represents a string, then this method
985 converts the contents to a @code{gdb.LazyString} (@pxref{Lazy Strings
986 In Python}). Otherwise, this method will throw an exception.
987
988 If the optional @var{encoding} argument is given, it must be a string
989 naming the encoding of the @code{gdb.LazyString}. Some examples are:
990 @samp{ascii}, @samp{iso-8859-6} or @samp{utf-8}. If the
991 @var{encoding} argument is an encoding that @value{GDBN} does
992 recognize, @value{GDBN} will raise an error.
993
994 When a lazy string is printed, the @value{GDBN} encoding machinery is
995 used to convert the string during printing. If the optional
996 @var{encoding} argument is not provided, or is an empty string,
997 @value{GDBN} will automatically select the encoding most suitable for
998 the string type. For further information on encoding in @value{GDBN}
999 please see @ref{Character Sets}.
1000
1001 If the optional @var{length} argument is given, the string will be
1002 fetched and encoded to the length of characters specified. If
1003 the @var{length} argument is not provided, the string will be fetched
1004 and encoded until a null of appropriate width is found.
1005 @end defun
1006
1007 @defun Value.fetch_lazy ()
1008 If the @code{gdb.Value} object is currently a lazy value
1009 (@code{gdb.Value.is_lazy} is @code{True}), then the value is
1010 fetched from the inferior. Any errors that occur in the process
1011 will produce a Python exception.
1012
1013 If the @code{gdb.Value} object is not a lazy value, this method
1014 has no effect.
1015
1016 This method does not return a value.
1017 @end defun
1018
1019
1020 @node Types In Python
1021 @subsubsection Types In Python
1022 @cindex types in Python
1023 @cindex Python, working with types
1024
1025 @tindex gdb.Type
1026 @value{GDBN} represents types from the inferior using the class
1027 @code{gdb.Type}.
1028
1029 The following type-related functions are available in the @code{gdb}
1030 module:
1031
1032 @findex gdb.lookup_type
1033 @defun gdb.lookup_type (name @r{[}, block@r{]})
1034 This function looks up a type by its @var{name}, which must be a string.
1035
1036 If @var{block} is given, then @var{name} is looked up in that scope.
1037 Otherwise, it is searched for globally.
1038
1039 Ordinarily, this function will return an instance of @code{gdb.Type}.
1040 If the named type cannot be found, it will throw an exception.
1041 @end defun
1042
1043 If the type is a structure or class type, or an enum type, the fields
1044 of that type can be accessed using the Python @dfn{dictionary syntax}.
1045 For example, if @code{some_type} is a @code{gdb.Type} instance holding
1046 a structure type, you can access its @code{foo} field with:
1047
1048 @smallexample
1049 bar = some_type['foo']
1050 @end smallexample
1051
1052 @code{bar} will be a @code{gdb.Field} object; see below under the
1053 description of the @code{Type.fields} method for a description of the
1054 @code{gdb.Field} class.
1055
1056 An instance of @code{Type} has the following attributes:
1057
1058 @defvar Type.alignof
1059 The alignment of this type, in bytes. Type alignment comes from the
1060 debugging information; if it was not specified, then @value{GDBN} will
1061 use the relevant ABI to try to determine the alignment. In some
1062 cases, even this is not possible, and zero will be returned.
1063 @end defvar
1064
1065 @defvar Type.code
1066 The type code for this type. The type code will be one of the
1067 @code{TYPE_CODE_} constants defined below.
1068 @end defvar
1069
1070 @defvar Type.name
1071 The name of this type. If this type has no name, then @code{None}
1072 is returned.
1073 @end defvar
1074
1075 @defvar Type.sizeof
1076 The size of this type, in target @code{char} units. Usually, a
1077 target's @code{char} type will be an 8-bit byte. However, on some
1078 unusual platforms, this type may have a different size.
1079 @end defvar
1080
1081 @defvar Type.tag
1082 The tag name for this type. The tag name is the name after
1083 @code{struct}, @code{union}, or @code{enum} in C and C@t{++}; not all
1084 languages have this concept. If this type has no tag name, then
1085 @code{None} is returned.
1086 @end defvar
1087
1088 @defvar Type.objfile
1089 The @code{gdb.Objfile} that this type was defined in, or @code{None} if
1090 there is no associated objfile.
1091 @end defvar
1092
1093 The following methods are provided:
1094
1095 @defun Type.fields ()
1096 For structure and union types, this method returns the fields. Range
1097 types have two fields, the minimum and maximum values. Enum types
1098 have one field per enum constant. Function and method types have one
1099 field per parameter. The base types of C@t{++} classes are also
1100 represented as fields. If the type has no fields, or does not fit
1101 into one of these categories, an empty sequence will be returned.
1102
1103 Each field is a @code{gdb.Field} object, with some pre-defined attributes:
1104 @table @code
1105 @item bitpos
1106 This attribute is not available for @code{enum} or @code{static}
1107 (as in C@t{++}) fields. The value is the position, counting
1108 in bits, from the start of the containing type.
1109
1110 @item enumval
1111 This attribute is only available for @code{enum} fields, and its value
1112 is the enumeration member's integer representation.
1113
1114 @item name
1115 The name of the field, or @code{None} for anonymous fields.
1116
1117 @item artificial
1118 This is @code{True} if the field is artificial, usually meaning that
1119 it was provided by the compiler and not the user. This attribute is
1120 always provided, and is @code{False} if the field is not artificial.
1121
1122 @item is_base_class
1123 This is @code{True} if the field represents a base class of a C@t{++}
1124 structure. This attribute is always provided, and is @code{False}
1125 if the field is not a base class of the type that is the argument of
1126 @code{fields}, or if that type was not a C@t{++} class.
1127
1128 @item bitsize
1129 If the field is packed, or is a bitfield, then this will have a
1130 non-zero value, which is the size of the field in bits. Otherwise,
1131 this will be zero; in this case the field's size is given by its type.
1132
1133 @item type
1134 The type of the field. This is usually an instance of @code{Type},
1135 but it can be @code{None} in some situations.
1136
1137 @item parent_type
1138 The type which contains this field. This is an instance of
1139 @code{gdb.Type}.
1140 @end table
1141 @end defun
1142
1143 @defun Type.array (@var{n1} @r{[}, @var{n2}@r{]})
1144 Return a new @code{gdb.Type} object which represents an array of this
1145 type. If one argument is given, it is the inclusive upper bound of
1146 the array; in this case the lower bound is zero. If two arguments are
1147 given, the first argument is the lower bound of the array, and the
1148 second argument is the upper bound of the array. An array's length
1149 must not be negative, but the bounds can be.
1150 @end defun
1151
1152 @defun Type.vector (@var{n1} @r{[}, @var{n2}@r{]})
1153 Return a new @code{gdb.Type} object which represents a vector of this
1154 type. If one argument is given, it is the inclusive upper bound of
1155 the vector; in this case the lower bound is zero. If two arguments are
1156 given, the first argument is the lower bound of the vector, and the
1157 second argument is the upper bound of the vector. A vector's length
1158 must not be negative, but the bounds can be.
1159
1160 The difference between an @code{array} and a @code{vector} is that
1161 arrays behave like in C: when used in expressions they decay to a pointer
1162 to the first element whereas vectors are treated as first class values.
1163 @end defun
1164
1165 @defun Type.const ()
1166 Return a new @code{gdb.Type} object which represents a
1167 @code{const}-qualified variant of this type.
1168 @end defun
1169
1170 @defun Type.volatile ()
1171 Return a new @code{gdb.Type} object which represents a
1172 @code{volatile}-qualified variant of this type.
1173 @end defun
1174
1175 @defun Type.unqualified ()
1176 Return a new @code{gdb.Type} object which represents an unqualified
1177 variant of this type. That is, the result is neither @code{const} nor
1178 @code{volatile}.
1179 @end defun
1180
1181 @defun Type.range ()
1182 Return a Python @code{Tuple} object that contains two elements: the
1183 low bound of the argument type and the high bound of that type. If
1184 the type does not have a range, @value{GDBN} will raise a
1185 @code{gdb.error} exception (@pxref{Exception Handling}).
1186 @end defun
1187
1188 @defun Type.reference ()
1189 Return a new @code{gdb.Type} object which represents a reference to this
1190 type.
1191 @end defun
1192
1193 @defun Type.pointer ()
1194 Return a new @code{gdb.Type} object which represents a pointer to this
1195 type.
1196 @end defun
1197
1198 @defun Type.strip_typedefs ()
1199 Return a new @code{gdb.Type} that represents the real type,
1200 after removing all layers of typedefs.
1201 @end defun
1202
1203 @defun Type.target ()
1204 Return a new @code{gdb.Type} object which represents the target type
1205 of this type.
1206
1207 For a pointer type, the target type is the type of the pointed-to
1208 object. For an array type (meaning C-like arrays), the target type is
1209 the type of the elements of the array. For a function or method type,
1210 the target type is the type of the return value. For a complex type,
1211 the target type is the type of the elements. For a typedef, the
1212 target type is the aliased type.
1213
1214 If the type does not have a target, this method will throw an
1215 exception.
1216 @end defun
1217
1218 @defun Type.template_argument (n @r{[}, block@r{]})
1219 If this @code{gdb.Type} is an instantiation of a template, this will
1220 return a new @code{gdb.Value} or @code{gdb.Type} which represents the
1221 value of the @var{n}th template argument (indexed starting at 0).
1222
1223 If this @code{gdb.Type} is not a template type, or if the type has fewer
1224 than @var{n} template arguments, this will throw an exception.
1225 Ordinarily, only C@t{++} code will have template types.
1226
1227 If @var{block} is given, then @var{name} is looked up in that scope.
1228 Otherwise, it is searched for globally.
1229 @end defun
1230
1231 @defun Type.optimized_out ()
1232 Return @code{gdb.Value} instance of this type whose value is optimized
1233 out. This allows a frame decorator to indicate that the value of an
1234 argument or a local variable is not known.
1235 @end defun
1236
1237 Each type has a code, which indicates what category this type falls
1238 into. The available type categories are represented by constants
1239 defined in the @code{gdb} module:
1240
1241 @vtable @code
1242 @vindex TYPE_CODE_PTR
1243 @item gdb.TYPE_CODE_PTR
1244 The type is a pointer.
1245
1246 @vindex TYPE_CODE_ARRAY
1247 @item gdb.TYPE_CODE_ARRAY
1248 The type is an array.
1249
1250 @vindex TYPE_CODE_STRUCT
1251 @item gdb.TYPE_CODE_STRUCT
1252 The type is a structure.
1253
1254 @vindex TYPE_CODE_UNION
1255 @item gdb.TYPE_CODE_UNION
1256 The type is a union.
1257
1258 @vindex TYPE_CODE_ENUM
1259 @item gdb.TYPE_CODE_ENUM
1260 The type is an enum.
1261
1262 @vindex TYPE_CODE_FLAGS
1263 @item gdb.TYPE_CODE_FLAGS
1264 A bit flags type, used for things such as status registers.
1265
1266 @vindex TYPE_CODE_FUNC
1267 @item gdb.TYPE_CODE_FUNC
1268 The type is a function.
1269
1270 @vindex TYPE_CODE_INT
1271 @item gdb.TYPE_CODE_INT
1272 The type is an integer type.
1273
1274 @vindex TYPE_CODE_FLT
1275 @item gdb.TYPE_CODE_FLT
1276 A floating point type.
1277
1278 @vindex TYPE_CODE_VOID
1279 @item gdb.TYPE_CODE_VOID
1280 The special type @code{void}.
1281
1282 @vindex TYPE_CODE_SET
1283 @item gdb.TYPE_CODE_SET
1284 A Pascal set type.
1285
1286 @vindex TYPE_CODE_RANGE
1287 @item gdb.TYPE_CODE_RANGE
1288 A range type, that is, an integer type with bounds.
1289
1290 @vindex TYPE_CODE_STRING
1291 @item gdb.TYPE_CODE_STRING
1292 A string type. Note that this is only used for certain languages with
1293 language-defined string types; C strings are not represented this way.
1294
1295 @vindex TYPE_CODE_BITSTRING
1296 @item gdb.TYPE_CODE_BITSTRING
1297 A string of bits. It is deprecated.
1298
1299 @vindex TYPE_CODE_ERROR
1300 @item gdb.TYPE_CODE_ERROR
1301 An unknown or erroneous type.
1302
1303 @vindex TYPE_CODE_METHOD
1304 @item gdb.TYPE_CODE_METHOD
1305 A method type, as found in C@t{++}.
1306
1307 @vindex TYPE_CODE_METHODPTR
1308 @item gdb.TYPE_CODE_METHODPTR
1309 A pointer-to-member-function.
1310
1311 @vindex TYPE_CODE_MEMBERPTR
1312 @item gdb.TYPE_CODE_MEMBERPTR
1313 A pointer-to-member.
1314
1315 @vindex TYPE_CODE_REF
1316 @item gdb.TYPE_CODE_REF
1317 A reference type.
1318
1319 @vindex TYPE_CODE_RVALUE_REF
1320 @item gdb.TYPE_CODE_RVALUE_REF
1321 A C@t{++}11 rvalue reference type.
1322
1323 @vindex TYPE_CODE_CHAR
1324 @item gdb.TYPE_CODE_CHAR
1325 A character type.
1326
1327 @vindex TYPE_CODE_BOOL
1328 @item gdb.TYPE_CODE_BOOL
1329 A boolean type.
1330
1331 @vindex TYPE_CODE_COMPLEX
1332 @item gdb.TYPE_CODE_COMPLEX
1333 A complex float type.
1334
1335 @vindex TYPE_CODE_TYPEDEF
1336 @item gdb.TYPE_CODE_TYPEDEF
1337 A typedef to some other type.
1338
1339 @vindex TYPE_CODE_NAMESPACE
1340 @item gdb.TYPE_CODE_NAMESPACE
1341 A C@t{++} namespace.
1342
1343 @vindex TYPE_CODE_DECFLOAT
1344 @item gdb.TYPE_CODE_DECFLOAT
1345 A decimal floating point type.
1346
1347 @vindex TYPE_CODE_INTERNAL_FUNCTION
1348 @item gdb.TYPE_CODE_INTERNAL_FUNCTION
1349 A function internal to @value{GDBN}. This is the type used to represent
1350 convenience functions.
1351 @end vtable
1352
1353 Further support for types is provided in the @code{gdb.types}
1354 Python module (@pxref{gdb.types}).
1355
1356 @node Pretty Printing API
1357 @subsubsection Pretty Printing API
1358 @cindex python pretty printing api
1359
1360 A pretty-printer is just an object that holds a value and implements a
1361 specific interface, defined here. An example output is provided
1362 (@pxref{Pretty Printing}).
1363
1364 @defun pretty_printer.children (self)
1365 @value{GDBN} will call this method on a pretty-printer to compute the
1366 children of the pretty-printer's value.
1367
1368 This method must return an object conforming to the Python iterator
1369 protocol. Each item returned by the iterator must be a tuple holding
1370 two elements. The first element is the ``name'' of the child; the
1371 second element is the child's value. The value can be any Python
1372 object which is convertible to a @value{GDBN} value.
1373
1374 This method is optional. If it does not exist, @value{GDBN} will act
1375 as though the value has no children.
1376
1377 For efficiency, the @code{children} method should lazily compute its
1378 results. This will let @value{GDBN} read as few elements as
1379 necessary, for example when various print settings (@pxref{Print
1380 Settings}) or @code{-var-list-children} (@pxref{GDB/MI Variable
1381 Objects}) limit the number of elements to be displayed.
1382
1383 Children may be hidden from display based on the value of @samp{set
1384 print max-depth} (@pxref{Print Settings}).
1385 @end defun
1386
1387 @defun pretty_printer.display_hint (self)
1388 The CLI may call this method and use its result to change the
1389 formatting of a value. The result will also be supplied to an MI
1390 consumer as a @samp{displayhint} attribute of the variable being
1391 printed.
1392
1393 This method is optional. If it does exist, this method must return a
1394 string or the special value @code{None}.
1395
1396 Some display hints are predefined by @value{GDBN}:
1397
1398 @table @samp
1399 @item array
1400 Indicate that the object being printed is ``array-like''. The CLI
1401 uses this to respect parameters such as @code{set print elements} and
1402 @code{set print array}.
1403
1404 @item map
1405 Indicate that the object being printed is ``map-like'', and that the
1406 children of this value can be assumed to alternate between keys and
1407 values.
1408
1409 @item string
1410 Indicate that the object being printed is ``string-like''. If the
1411 printer's @code{to_string} method returns a Python string of some
1412 kind, then @value{GDBN} will call its internal language-specific
1413 string-printing function to format the string. For the CLI this means
1414 adding quotation marks, possibly escaping some characters, respecting
1415 @code{set print elements}, and the like.
1416 @end table
1417
1418 The special value @code{None} causes @value{GDBN} to apply the default
1419 display rules.
1420 @end defun
1421
1422 @defun pretty_printer.to_string (self)
1423 @value{GDBN} will call this method to display the string
1424 representation of the value passed to the object's constructor.
1425
1426 When printing from the CLI, if the @code{to_string} method exists,
1427 then @value{GDBN} will prepend its result to the values returned by
1428 @code{children}. Exactly how this formatting is done is dependent on
1429 the display hint, and may change as more hints are added. Also,
1430 depending on the print settings (@pxref{Print Settings}), the CLI may
1431 print just the result of @code{to_string} in a stack trace, omitting
1432 the result of @code{children}.
1433
1434 If this method returns a string, it is printed verbatim.
1435
1436 Otherwise, if this method returns an instance of @code{gdb.Value},
1437 then @value{GDBN} prints this value. This may result in a call to
1438 another pretty-printer.
1439
1440 If instead the method returns a Python value which is convertible to a
1441 @code{gdb.Value}, then @value{GDBN} performs the conversion and prints
1442 the resulting value. Again, this may result in a call to another
1443 pretty-printer. Python scalars (integers, floats, and booleans) and
1444 strings are convertible to @code{gdb.Value}; other types are not.
1445
1446 Finally, if this method returns @code{None} then no further operations
1447 are peformed in this method and nothing is printed.
1448
1449 If the result is not one of these types, an exception is raised.
1450 @end defun
1451
1452 @value{GDBN} provides a function which can be used to look up the
1453 default pretty-printer for a @code{gdb.Value}:
1454
1455 @findex gdb.default_visualizer
1456 @defun gdb.default_visualizer (value)
1457 This function takes a @code{gdb.Value} object as an argument. If a
1458 pretty-printer for this value exists, then it is returned. If no such
1459 printer exists, then this returns @code{None}.
1460 @end defun
1461
1462 @node Selecting Pretty-Printers
1463 @subsubsection Selecting Pretty-Printers
1464 @cindex selecting python pretty-printers
1465
1466 @value{GDBN} provides several ways to register a pretty-printer:
1467 globally, per program space, and per objfile. When choosing how to
1468 register your pretty-printer, a good rule is to register it with the
1469 smallest scope possible: that is prefer a specific objfile first, then
1470 a program space, and only register a printer globally as a last
1471 resort.
1472
1473 @findex gdb.pretty_printers
1474 @defvar gdb.pretty_printers
1475 The Python list @code{gdb.pretty_printers} contains an array of
1476 functions or callable objects that have been registered via addition
1477 as a pretty-printer. Printers in this list are called @code{global}
1478 printers, they're available when debugging all inferiors.
1479 @end defvar
1480
1481 Each @code{gdb.Progspace} contains a @code{pretty_printers} attribute.
1482 Each @code{gdb.Objfile} also contains a @code{pretty_printers}
1483 attribute.
1484
1485 Each function on these lists is passed a single @code{gdb.Value}
1486 argument and should return a pretty-printer object conforming to the
1487 interface definition above (@pxref{Pretty Printing API}). If a function
1488 cannot create a pretty-printer for the value, it should return
1489 @code{None}.
1490
1491 @value{GDBN} first checks the @code{pretty_printers} attribute of each
1492 @code{gdb.Objfile} in the current program space and iteratively calls
1493 each enabled lookup routine in the list for that @code{gdb.Objfile}
1494 until it receives a pretty-printer object.
1495 If no pretty-printer is found in the objfile lists, @value{GDBN} then
1496 searches the pretty-printer list of the current program space,
1497 calling each enabled function until an object is returned.
1498 After these lists have been exhausted, it tries the global
1499 @code{gdb.pretty_printers} list, again calling each enabled function until an
1500 object is returned.
1501
1502 The order in which the objfiles are searched is not specified. For a
1503 given list, functions are always invoked from the head of the list,
1504 and iterated over sequentially until the end of the list, or a printer
1505 object is returned.
1506
1507 For various reasons a pretty-printer may not work.
1508 For example, the underlying data structure may have changed and
1509 the pretty-printer is out of date.
1510
1511 The consequences of a broken pretty-printer are severe enough that
1512 @value{GDBN} provides support for enabling and disabling individual
1513 printers. For example, if @code{print frame-arguments} is on,
1514 a backtrace can become highly illegible if any argument is printed
1515 with a broken printer.
1516
1517 Pretty-printers are enabled and disabled by attaching an @code{enabled}
1518 attribute to the registered function or callable object. If this attribute
1519 is present and its value is @code{False}, the printer is disabled, otherwise
1520 the printer is enabled.
1521
1522 @node Writing a Pretty-Printer
1523 @subsubsection Writing a Pretty-Printer
1524 @cindex writing a pretty-printer
1525
1526 A pretty-printer consists of two parts: a lookup function to detect
1527 if the type is supported, and the printer itself.
1528
1529 Here is an example showing how a @code{std::string} printer might be
1530 written. @xref{Pretty Printing API}, for details on the API this class
1531 must provide.
1532
1533 @smallexample
1534 class StdStringPrinter(object):
1535 "Print a std::string"
1536
1537 def __init__(self, val):
1538 self.val = val
1539
1540 def to_string(self):
1541 return self.val['_M_dataplus']['_M_p']
1542
1543 def display_hint(self):
1544 return 'string'
1545 @end smallexample
1546
1547 And here is an example showing how a lookup function for the printer
1548 example above might be written.
1549
1550 @smallexample
1551 def str_lookup_function(val):
1552 lookup_tag = val.type.tag
1553 if lookup_tag == None:
1554 return None
1555 regex = re.compile("^std::basic_string<char,.*>$")
1556 if regex.match(lookup_tag):
1557 return StdStringPrinter(val)
1558 return None
1559 @end smallexample
1560
1561 The example lookup function extracts the value's type, and attempts to
1562 match it to a type that it can pretty-print. If it is a type the
1563 printer can pretty-print, it will return a printer object. If not, it
1564 returns @code{None}.
1565
1566 We recommend that you put your core pretty-printers into a Python
1567 package. If your pretty-printers are for use with a library, we
1568 further recommend embedding a version number into the package name.
1569 This practice will enable @value{GDBN} to load multiple versions of
1570 your pretty-printers at the same time, because they will have
1571 different names.
1572
1573 You should write auto-loaded code (@pxref{Python Auto-loading}) such that it
1574 can be evaluated multiple times without changing its meaning. An
1575 ideal auto-load file will consist solely of @code{import}s of your
1576 printer modules, followed by a call to a register pretty-printers with
1577 the current objfile.
1578
1579 Taken as a whole, this approach will scale nicely to multiple
1580 inferiors, each potentially using a different library version.
1581 Embedding a version number in the Python package name will ensure that
1582 @value{GDBN} is able to load both sets of printers simultaneously.
1583 Then, because the search for pretty-printers is done by objfile, and
1584 because your auto-loaded code took care to register your library's
1585 printers with a specific objfile, @value{GDBN} will find the correct
1586 printers for the specific version of the library used by each
1587 inferior.
1588
1589 To continue the @code{std::string} example (@pxref{Pretty Printing API}),
1590 this code might appear in @code{gdb.libstdcxx.v6}:
1591
1592 @smallexample
1593 def register_printers(objfile):
1594 objfile.pretty_printers.append(str_lookup_function)
1595 @end smallexample
1596
1597 @noindent
1598 And then the corresponding contents of the auto-load file would be:
1599
1600 @smallexample
1601 import gdb.libstdcxx.v6
1602 gdb.libstdcxx.v6.register_printers(gdb.current_objfile())
1603 @end smallexample
1604
1605 The previous example illustrates a basic pretty-printer.
1606 There are a few things that can be improved on.
1607 The printer doesn't have a name, making it hard to identify in a
1608 list of installed printers. The lookup function has a name, but
1609 lookup functions can have arbitrary, even identical, names.
1610
1611 Second, the printer only handles one type, whereas a library typically has
1612 several types. One could install a lookup function for each desired type
1613 in the library, but one could also have a single lookup function recognize
1614 several types. The latter is the conventional way this is handled.
1615 If a pretty-printer can handle multiple data types, then its
1616 @dfn{subprinters} are the printers for the individual data types.
1617
1618 The @code{gdb.printing} module provides a formal way of solving these
1619 problems (@pxref{gdb.printing}).
1620 Here is another example that handles multiple types.
1621
1622 These are the types we are going to pretty-print:
1623
1624 @smallexample
1625 struct foo @{ int a, b; @};
1626 struct bar @{ struct foo x, y; @};
1627 @end smallexample
1628
1629 Here are the printers:
1630
1631 @smallexample
1632 class fooPrinter:
1633 """Print a foo object."""
1634
1635 def __init__(self, val):
1636 self.val = val
1637
1638 def to_string(self):
1639 return ("a=<" + str(self.val["a"]) +
1640 "> b=<" + str(self.val["b"]) + ">")
1641
1642 class barPrinter:
1643 """Print a bar object."""
1644
1645 def __init__(self, val):
1646 self.val = val
1647
1648 def to_string(self):
1649 return ("x=<" + str(self.val["x"]) +
1650 "> y=<" + str(self.val["y"]) + ">")
1651 @end smallexample
1652
1653 This example doesn't need a lookup function, that is handled by the
1654 @code{gdb.printing} module. Instead a function is provided to build up
1655 the object that handles the lookup.
1656
1657 @smallexample
1658 import gdb.printing
1659
1660 def build_pretty_printer():
1661 pp = gdb.printing.RegexpCollectionPrettyPrinter(
1662 "my_library")
1663 pp.add_printer('foo', '^foo$', fooPrinter)
1664 pp.add_printer('bar', '^bar$', barPrinter)
1665 return pp
1666 @end smallexample
1667
1668 And here is the autoload support:
1669
1670 @smallexample
1671 import gdb.printing
1672 import my_library
1673 gdb.printing.register_pretty_printer(
1674 gdb.current_objfile(),
1675 my_library.build_pretty_printer())
1676 @end smallexample
1677
1678 Finally, when this printer is loaded into @value{GDBN}, here is the
1679 corresponding output of @samp{info pretty-printer}:
1680
1681 @smallexample
1682 (gdb) info pretty-printer
1683 my_library.so:
1684 my_library
1685 foo
1686 bar
1687 @end smallexample
1688
1689 @node Type Printing API
1690 @subsubsection Type Printing API
1691 @cindex type printing API for Python
1692
1693 @value{GDBN} provides a way for Python code to customize type display.
1694 This is mainly useful for substituting canonical typedef names for
1695 types.
1696
1697 @cindex type printer
1698 A @dfn{type printer} is just a Python object conforming to a certain
1699 protocol. A simple base class implementing the protocol is provided;
1700 see @ref{gdb.types}. A type printer must supply at least:
1701
1702 @defivar type_printer enabled
1703 A boolean which is True if the printer is enabled, and False
1704 otherwise. This is manipulated by the @code{enable type-printer}
1705 and @code{disable type-printer} commands.
1706 @end defivar
1707
1708 @defivar type_printer name
1709 The name of the type printer. This must be a string. This is used by
1710 the @code{enable type-printer} and @code{disable type-printer}
1711 commands.
1712 @end defivar
1713
1714 @defmethod type_printer instantiate (self)
1715 This is called by @value{GDBN} at the start of type-printing. It is
1716 only called if the type printer is enabled. This method must return a
1717 new object that supplies a @code{recognize} method, as described below.
1718 @end defmethod
1719
1720
1721 When displaying a type, say via the @code{ptype} command, @value{GDBN}
1722 will compute a list of type recognizers. This is done by iterating
1723 first over the per-objfile type printers (@pxref{Objfiles In Python}),
1724 followed by the per-progspace type printers (@pxref{Progspaces In
1725 Python}), and finally the global type printers.
1726
1727 @value{GDBN} will call the @code{instantiate} method of each enabled
1728 type printer. If this method returns @code{None}, then the result is
1729 ignored; otherwise, it is appended to the list of recognizers.
1730
1731 Then, when @value{GDBN} is going to display a type name, it iterates
1732 over the list of recognizers. For each one, it calls the recognition
1733 function, stopping if the function returns a non-@code{None} value.
1734 The recognition function is defined as:
1735
1736 @defmethod type_recognizer recognize (self, type)
1737 If @var{type} is not recognized, return @code{None}. Otherwise,
1738 return a string which is to be printed as the name of @var{type}.
1739 The @var{type} argument will be an instance of @code{gdb.Type}
1740 (@pxref{Types In Python}).
1741 @end defmethod
1742
1743 @value{GDBN} uses this two-pass approach so that type printers can
1744 efficiently cache information without holding on to it too long. For
1745 example, it can be convenient to look up type information in a type
1746 printer and hold it for a recognizer's lifetime; if a single pass were
1747 done then type printers would have to make use of the event system in
1748 order to avoid holding information that could become stale as the
1749 inferior changed.
1750
1751 @node Frame Filter API
1752 @subsubsection Filtering Frames
1753 @cindex frame filters api
1754
1755 Frame filters are Python objects that manipulate the visibility of a
1756 frame or frames when a backtrace (@pxref{Backtrace}) is printed by
1757 @value{GDBN}.
1758
1759 Only commands that print a backtrace, or, in the case of @sc{gdb/mi}
1760 commands (@pxref{GDB/MI}), those that return a collection of frames
1761 are affected. The commands that work with frame filters are:
1762
1763 @code{backtrace} (@pxref{backtrace-command,, The backtrace command}),
1764 @code{-stack-list-frames}
1765 (@pxref{-stack-list-frames,, The -stack-list-frames command}),
1766 @code{-stack-list-variables} (@pxref{-stack-list-variables,, The
1767 -stack-list-variables command}), @code{-stack-list-arguments}
1768 @pxref{-stack-list-arguments,, The -stack-list-arguments command}) and
1769 @code{-stack-list-locals} (@pxref{-stack-list-locals,, The
1770 -stack-list-locals command}).
1771
1772 A frame filter works by taking an iterator as an argument, applying
1773 actions to the contents of that iterator, and returning another
1774 iterator (or, possibly, the same iterator it was provided in the case
1775 where the filter does not perform any operations). Typically, frame
1776 filters utilize tools such as the Python's @code{itertools} module to
1777 work with and create new iterators from the source iterator.
1778 Regardless of how a filter chooses to apply actions, it must not alter
1779 the underlying @value{GDBN} frame or frames, or attempt to alter the
1780 call-stack within @value{GDBN}. This preserves data integrity within
1781 @value{GDBN}. Frame filters are executed on a priority basis and care
1782 should be taken that some frame filters may have been executed before,
1783 and that some frame filters will be executed after.
1784
1785 An important consideration when designing frame filters, and well
1786 worth reflecting upon, is that frame filters should avoid unwinding
1787 the call stack if possible. Some stacks can run very deep, into the
1788 tens of thousands in some cases. To search every frame when a frame
1789 filter executes may be too expensive at that step. The frame filter
1790 cannot know how many frames it has to iterate over, and it may have to
1791 iterate through them all. This ends up duplicating effort as
1792 @value{GDBN} performs this iteration when it prints the frames. If
1793 the filter can defer unwinding frames until frame decorators are
1794 executed, after the last filter has executed, it should. @xref{Frame
1795 Decorator API}, for more information on decorators. Also, there are
1796 examples for both frame decorators and filters in later chapters.
1797 @xref{Writing a Frame Filter}, for more information.
1798
1799 The Python dictionary @code{gdb.frame_filters} contains key/object
1800 pairings that comprise a frame filter. Frame filters in this
1801 dictionary are called @code{global} frame filters, and they are
1802 available when debugging all inferiors. These frame filters must
1803 register with the dictionary directly. In addition to the
1804 @code{global} dictionary, there are other dictionaries that are loaded
1805 with different inferiors via auto-loading (@pxref{Python
1806 Auto-loading}). The two other areas where frame filter dictionaries
1807 can be found are: @code{gdb.Progspace} which contains a
1808 @code{frame_filters} dictionary attribute, and each @code{gdb.Objfile}
1809 object which also contains a @code{frame_filters} dictionary
1810 attribute.
1811
1812 When a command is executed from @value{GDBN} that is compatible with
1813 frame filters, @value{GDBN} combines the @code{global},
1814 @code{gdb.Progspace} and all @code{gdb.Objfile} dictionaries currently
1815 loaded. All of the @code{gdb.Objfile} dictionaries are combined, as
1816 several frames, and thus several object files, might be in use.
1817 @value{GDBN} then prunes any frame filter whose @code{enabled}
1818 attribute is @code{False}. This pruned list is then sorted according
1819 to the @code{priority} attribute in each filter.
1820
1821 Once the dictionaries are combined, pruned and sorted, @value{GDBN}
1822 creates an iterator which wraps each frame in the call stack in a
1823 @code{FrameDecorator} object, and calls each filter in order. The
1824 output from the previous filter will always be the input to the next
1825 filter, and so on.
1826
1827 Frame filters have a mandatory interface which each frame filter must
1828 implement, defined here:
1829
1830 @defun FrameFilter.filter (iterator)
1831 @value{GDBN} will call this method on a frame filter when it has
1832 reached the order in the priority list for that filter.
1833
1834 For example, if there are four frame filters:
1835
1836 @smallexample
1837 Name Priority
1838
1839 Filter1 5
1840 Filter2 10
1841 Filter3 100
1842 Filter4 1
1843 @end smallexample
1844
1845 The order that the frame filters will be called is:
1846
1847 @smallexample
1848 Filter3 -> Filter2 -> Filter1 -> Filter4
1849 @end smallexample
1850
1851 Note that the output from @code{Filter3} is passed to the input of
1852 @code{Filter2}, and so on.
1853
1854 This @code{filter} method is passed a Python iterator. This iterator
1855 contains a sequence of frame decorators that wrap each
1856 @code{gdb.Frame}, or a frame decorator that wraps another frame
1857 decorator. The first filter that is executed in the sequence of frame
1858 filters will receive an iterator entirely comprised of default
1859 @code{FrameDecorator} objects. However, after each frame filter is
1860 executed, the previous frame filter may have wrapped some or all of
1861 the frame decorators with their own frame decorator. As frame
1862 decorators must also conform to a mandatory interface, these
1863 decorators can be assumed to act in a uniform manner (@pxref{Frame
1864 Decorator API}).
1865
1866 This method must return an object conforming to the Python iterator
1867 protocol. Each item in the iterator must be an object conforming to
1868 the frame decorator interface. If a frame filter does not wish to
1869 perform any operations on this iterator, it should return that
1870 iterator untouched.
1871
1872 This method is not optional. If it does not exist, @value{GDBN} will
1873 raise and print an error.
1874 @end defun
1875
1876 @defvar FrameFilter.name
1877 The @code{name} attribute must be Python string which contains the
1878 name of the filter displayed by @value{GDBN} (@pxref{Frame Filter
1879 Management}). This attribute may contain any combination of letters
1880 or numbers. Care should be taken to ensure that it is unique. This
1881 attribute is mandatory.
1882 @end defvar
1883
1884 @defvar FrameFilter.enabled
1885 The @code{enabled} attribute must be Python boolean. This attribute
1886 indicates to @value{GDBN} whether the frame filter is enabled, and
1887 should be considered when frame filters are executed. If
1888 @code{enabled} is @code{True}, then the frame filter will be executed
1889 when any of the backtrace commands detailed earlier in this chapter
1890 are executed. If @code{enabled} is @code{False}, then the frame
1891 filter will not be executed. This attribute is mandatory.
1892 @end defvar
1893
1894 @defvar FrameFilter.priority
1895 The @code{priority} attribute must be Python integer. This attribute
1896 controls the order of execution in relation to other frame filters.
1897 There are no imposed limits on the range of @code{priority} other than
1898 it must be a valid integer. The higher the @code{priority} attribute,
1899 the sooner the frame filter will be executed in relation to other
1900 frame filters. Although @code{priority} can be negative, it is
1901 recommended practice to assume zero is the lowest priority that a
1902 frame filter can be assigned. Frame filters that have the same
1903 priority are executed in unsorted order in that priority slot. This
1904 attribute is mandatory. 100 is a good default priority.
1905 @end defvar
1906
1907 @node Frame Decorator API
1908 @subsubsection Decorating Frames
1909 @cindex frame decorator api
1910
1911 Frame decorators are sister objects to frame filters (@pxref{Frame
1912 Filter API}). Frame decorators are applied by a frame filter and can
1913 only be used in conjunction with frame filters.
1914
1915 The purpose of a frame decorator is to customize the printed content
1916 of each @code{gdb.Frame} in commands where frame filters are executed.
1917 This concept is called decorating a frame. Frame decorators decorate
1918 a @code{gdb.Frame} with Python code contained within each API call.
1919 This separates the actual data contained in a @code{gdb.Frame} from
1920 the decorated data produced by a frame decorator. This abstraction is
1921 necessary to maintain integrity of the data contained in each
1922 @code{gdb.Frame}.
1923
1924 Frame decorators have a mandatory interface, defined below.
1925
1926 @value{GDBN} already contains a frame decorator called
1927 @code{FrameDecorator}. This contains substantial amounts of
1928 boilerplate code to decorate the content of a @code{gdb.Frame}. It is
1929 recommended that other frame decorators inherit and extend this
1930 object, and only to override the methods needed.
1931
1932 @tindex gdb.FrameDecorator
1933 @code{FrameDecorator} is defined in the Python module
1934 @code{gdb.FrameDecorator}, so your code can import it like:
1935 @smallexample
1936 from gdb.FrameDecorator import FrameDecorator
1937 @end smallexample
1938
1939 @defun FrameDecorator.elided (self)
1940
1941 The @code{elided} method groups frames together in a hierarchical
1942 system. An example would be an interpreter, where multiple low-level
1943 frames make up a single call in the interpreted language. In this
1944 example, the frame filter would elide the low-level frames and present
1945 a single high-level frame, representing the call in the interpreted
1946 language, to the user.
1947
1948 The @code{elided} function must return an iterable and this iterable
1949 must contain the frames that are being elided wrapped in a suitable
1950 frame decorator. If no frames are being elided this function may
1951 return an empty iterable, or @code{None}. Elided frames are indented
1952 from normal frames in a @code{CLI} backtrace, or in the case of
1953 @code{GDB/MI}, are placed in the @code{children} field of the eliding
1954 frame.
1955
1956 It is the frame filter's task to also filter out the elided frames from
1957 the source iterator. This will avoid printing the frame twice.
1958 @end defun
1959
1960 @defun FrameDecorator.function (self)
1961
1962 This method returns the name of the function in the frame that is to
1963 be printed.
1964
1965 This method must return a Python string describing the function, or
1966 @code{None}.
1967
1968 If this function returns @code{None}, @value{GDBN} will not print any
1969 data for this field.
1970 @end defun
1971
1972 @defun FrameDecorator.address (self)
1973
1974 This method returns the address of the frame that is to be printed.
1975
1976 This method must return a Python numeric integer type of sufficient
1977 size to describe the address of the frame, or @code{None}.
1978
1979 If this function returns a @code{None}, @value{GDBN} will not print
1980 any data for this field.
1981 @end defun
1982
1983 @defun FrameDecorator.filename (self)
1984
1985 This method returns the filename and path associated with this frame.
1986
1987 This method must return a Python string containing the filename and
1988 the path to the object file backing the frame, or @code{None}.
1989
1990 If this function returns a @code{None}, @value{GDBN} will not print
1991 any data for this field.
1992 @end defun
1993
1994 @defun FrameDecorator.line (self):
1995
1996 This method returns the line number associated with the current
1997 position within the function addressed by this frame.
1998
1999 This method must return a Python integer type, or @code{None}.
2000
2001 If this function returns a @code{None}, @value{GDBN} will not print
2002 any data for this field.
2003 @end defun
2004
2005 @defun FrameDecorator.frame_args (self)
2006 @anchor{frame_args}
2007
2008 This method must return an iterable, or @code{None}. Returning an
2009 empty iterable, or @code{None} means frame arguments will not be
2010 printed for this frame. This iterable must contain objects that
2011 implement two methods, described here.
2012
2013 This object must implement a @code{argument} method which takes a
2014 single @code{self} parameter and must return a @code{gdb.Symbol}
2015 (@pxref{Symbols In Python}), or a Python string. The object must also
2016 implement a @code{value} method which takes a single @code{self}
2017 parameter and must return a @code{gdb.Value} (@pxref{Values From
2018 Inferior}), a Python value, or @code{None}. If the @code{value}
2019 method returns @code{None}, and the @code{argument} method returns a
2020 @code{gdb.Symbol}, @value{GDBN} will look-up and print the value of
2021 the @code{gdb.Symbol} automatically.
2022
2023 A brief example:
2024
2025 @smallexample
2026 class SymValueWrapper():
2027
2028 def __init__(self, symbol, value):
2029 self.sym = symbol
2030 self.val = value
2031
2032 def value(self):
2033 return self.val
2034
2035 def symbol(self):
2036 return self.sym
2037
2038 class SomeFrameDecorator()
2039 ...
2040 ...
2041 def frame_args(self):
2042 args = []
2043 try:
2044 block = self.inferior_frame.block()
2045 except:
2046 return None
2047
2048 # Iterate over all symbols in a block. Only add
2049 # symbols that are arguments.
2050 for sym in block:
2051 if not sym.is_argument:
2052 continue
2053 args.append(SymValueWrapper(sym,None))
2054
2055 # Add example synthetic argument.
2056 args.append(SymValueWrapper(``foo'', 42))
2057
2058 return args
2059 @end smallexample
2060 @end defun
2061
2062 @defun FrameDecorator.frame_locals (self)
2063
2064 This method must return an iterable or @code{None}. Returning an
2065 empty iterable, or @code{None} means frame local arguments will not be
2066 printed for this frame.
2067
2068 The object interface, the description of the various strategies for
2069 reading frame locals, and the example are largely similar to those
2070 described in the @code{frame_args} function, (@pxref{frame_args,,The
2071 frame filter frame_args function}). Below is a modified example:
2072
2073 @smallexample
2074 class SomeFrameDecorator()
2075 ...
2076 ...
2077 def frame_locals(self):
2078 vars = []
2079 try:
2080 block = self.inferior_frame.block()
2081 except:
2082 return None
2083
2084 # Iterate over all symbols in a block. Add all
2085 # symbols, except arguments.
2086 for sym in block:
2087 if sym.is_argument:
2088 continue
2089 vars.append(SymValueWrapper(sym,None))
2090
2091 # Add an example of a synthetic local variable.
2092 vars.append(SymValueWrapper(``bar'', 99))
2093
2094 return vars
2095 @end smallexample
2096 @end defun
2097
2098 @defun FrameDecorator.inferior_frame (self):
2099
2100 This method must return the underlying @code{gdb.Frame} that this
2101 frame decorator is decorating. @value{GDBN} requires the underlying
2102 frame for internal frame information to determine how to print certain
2103 values when printing a frame.
2104 @end defun
2105
2106 @node Writing a Frame Filter
2107 @subsubsection Writing a Frame Filter
2108 @cindex writing a frame filter
2109
2110 There are three basic elements that a frame filter must implement: it
2111 must correctly implement the documented interface (@pxref{Frame Filter
2112 API}), it must register itself with @value{GDBN}, and finally, it must
2113 decide if it is to work on the data provided by @value{GDBN}. In all
2114 cases, whether it works on the iterator or not, each frame filter must
2115 return an iterator. A bare-bones frame filter follows the pattern in
2116 the following example.
2117
2118 @smallexample
2119 import gdb
2120
2121 class FrameFilter():
2122
2123 def __init__(self):
2124 # Frame filter attribute creation.
2125 #
2126 # 'name' is the name of the filter that GDB will display.
2127 #
2128 # 'priority' is the priority of the filter relative to other
2129 # filters.
2130 #
2131 # 'enabled' is a boolean that indicates whether this filter is
2132 # enabled and should be executed.
2133
2134 self.name = "Foo"
2135 self.priority = 100
2136 self.enabled = True
2137
2138 # Register this frame filter with the global frame_filters
2139 # dictionary.
2140 gdb.frame_filters[self.name] = self
2141
2142 def filter(self, frame_iter):
2143 # Just return the iterator.
2144 return frame_iter
2145 @end smallexample
2146
2147 The frame filter in the example above implements the three
2148 requirements for all frame filters. It implements the API, self
2149 registers, and makes a decision on the iterator (in this case, it just
2150 returns the iterator untouched).
2151
2152 The first step is attribute creation and assignment, and as shown in
2153 the comments the filter assigns the following attributes: @code{name},
2154 @code{priority} and whether the filter should be enabled with the
2155 @code{enabled} attribute.
2156
2157 The second step is registering the frame filter with the dictionary or
2158 dictionaries that the frame filter has interest in. As shown in the
2159 comments, this filter just registers itself with the global dictionary
2160 @code{gdb.frame_filters}. As noted earlier, @code{gdb.frame_filters}
2161 is a dictionary that is initialized in the @code{gdb} module when
2162 @value{GDBN} starts. What dictionary a filter registers with is an
2163 important consideration. Generally, if a filter is specific to a set
2164 of code, it should be registered either in the @code{objfile} or
2165 @code{progspace} dictionaries as they are specific to the program
2166 currently loaded in @value{GDBN}. The global dictionary is always
2167 present in @value{GDBN} and is never unloaded. Any filters registered
2168 with the global dictionary will exist until @value{GDBN} exits. To
2169 avoid filters that may conflict, it is generally better to register
2170 frame filters against the dictionaries that more closely align with
2171 the usage of the filter currently in question. @xref{Python
2172 Auto-loading}, for further information on auto-loading Python scripts.
2173
2174 @value{GDBN} takes a hands-off approach to frame filter registration,
2175 therefore it is the frame filter's responsibility to ensure
2176 registration has occurred, and that any exceptions are handled
2177 appropriately. In particular, you may wish to handle exceptions
2178 relating to Python dictionary key uniqueness. It is mandatory that
2179 the dictionary key is the same as frame filter's @code{name}
2180 attribute. When a user manages frame filters (@pxref{Frame Filter
2181 Management}), the names @value{GDBN} will display are those contained
2182 in the @code{name} attribute.
2183
2184 The final step of this example is the implementation of the
2185 @code{filter} method. As shown in the example comments, we define the
2186 @code{filter} method and note that the method must take an iterator,
2187 and also must return an iterator. In this bare-bones example, the
2188 frame filter is not very useful as it just returns the iterator
2189 untouched. However this is a valid operation for frame filters that
2190 have the @code{enabled} attribute set, but decide not to operate on
2191 any frames.
2192
2193 In the next example, the frame filter operates on all frames and
2194 utilizes a frame decorator to perform some work on the frames.
2195 @xref{Frame Decorator API}, for further information on the frame
2196 decorator interface.
2197
2198 This example works on inlined frames. It highlights frames which are
2199 inlined by tagging them with an ``[inlined]'' tag. By applying a
2200 frame decorator to all frames with the Python @code{itertools imap}
2201 method, the example defers actions to the frame decorator. Frame
2202 decorators are only processed when @value{GDBN} prints the backtrace.
2203
2204 This introduces a new decision making topic: whether to perform
2205 decision making operations at the filtering step, or at the printing
2206 step. In this example's approach, it does not perform any filtering
2207 decisions at the filtering step beyond mapping a frame decorator to
2208 each frame. This allows the actual decision making to be performed
2209 when each frame is printed. This is an important consideration, and
2210 well worth reflecting upon when designing a frame filter. An issue
2211 that frame filters should avoid is unwinding the stack if possible.
2212 Some stacks can run very deep, into the tens of thousands in some
2213 cases. To search every frame to determine if it is inlined ahead of
2214 time may be too expensive at the filtering step. The frame filter
2215 cannot know how many frames it has to iterate over, and it would have
2216 to iterate through them all. This ends up duplicating effort as
2217 @value{GDBN} performs this iteration when it prints the frames.
2218
2219 In this example decision making can be deferred to the printing step.
2220 As each frame is printed, the frame decorator can examine each frame
2221 in turn when @value{GDBN} iterates. From a performance viewpoint,
2222 this is the most appropriate decision to make as it avoids duplicating
2223 the effort that the printing step would undertake anyway. Also, if
2224 there are many frame filters unwinding the stack during filtering, it
2225 can substantially delay the printing of the backtrace which will
2226 result in large memory usage, and a poor user experience.
2227
2228 @smallexample
2229 class InlineFilter():
2230
2231 def __init__(self):
2232 self.name = "InlinedFrameFilter"
2233 self.priority = 100
2234 self.enabled = True
2235 gdb.frame_filters[self.name] = self
2236
2237 def filter(self, frame_iter):
2238 frame_iter = itertools.imap(InlinedFrameDecorator,
2239 frame_iter)
2240 return frame_iter
2241 @end smallexample
2242
2243 This frame filter is somewhat similar to the earlier example, except
2244 that the @code{filter} method applies a frame decorator object called
2245 @code{InlinedFrameDecorator} to each element in the iterator. The
2246 @code{imap} Python method is light-weight. It does not proactively
2247 iterate over the iterator, but rather creates a new iterator which
2248 wraps the existing one.
2249
2250 Below is the frame decorator for this example.
2251
2252 @smallexample
2253 class InlinedFrameDecorator(FrameDecorator):
2254
2255 def __init__(self, fobj):
2256 super(InlinedFrameDecorator, self).__init__(fobj)
2257
2258 def function(self):
2259 frame = fobj.inferior_frame()
2260 name = str(frame.name())
2261
2262 if frame.type() == gdb.INLINE_FRAME:
2263 name = name + " [inlined]"
2264
2265 return name
2266 @end smallexample
2267
2268 This frame decorator only defines and overrides the @code{function}
2269 method. It lets the supplied @code{FrameDecorator}, which is shipped
2270 with @value{GDBN}, perform the other work associated with printing
2271 this frame.
2272
2273 The combination of these two objects create this output from a
2274 backtrace:
2275
2276 @smallexample
2277 #0 0x004004e0 in bar () at inline.c:11
2278 #1 0x00400566 in max [inlined] (b=6, a=12) at inline.c:21
2279 #2 0x00400566 in main () at inline.c:31
2280 @end smallexample
2281
2282 So in the case of this example, a frame decorator is applied to all
2283 frames, regardless of whether they may be inlined or not. As
2284 @value{GDBN} iterates over the iterator produced by the frame filters,
2285 @value{GDBN} executes each frame decorator which then makes a decision
2286 on what to print in the @code{function} callback. Using a strategy
2287 like this is a way to defer decisions on the frame content to printing
2288 time.
2289
2290 @subheading Eliding Frames
2291
2292 It might be that the above example is not desirable for representing
2293 inlined frames, and a hierarchical approach may be preferred. If we
2294 want to hierarchically represent frames, the @code{elided} frame
2295 decorator interface might be preferable.
2296
2297 This example approaches the issue with the @code{elided} method. This
2298 example is quite long, but very simplistic. It is out-of-scope for
2299 this section to write a complete example that comprehensively covers
2300 all approaches of finding and printing inlined frames. However, this
2301 example illustrates the approach an author might use.
2302
2303 This example comprises of three sections.
2304
2305 @smallexample
2306 class InlineFrameFilter():
2307
2308 def __init__(self):
2309 self.name = "InlinedFrameFilter"
2310 self.priority = 100
2311 self.enabled = True
2312 gdb.frame_filters[self.name] = self
2313
2314 def filter(self, frame_iter):
2315 return ElidingInlineIterator(frame_iter)
2316 @end smallexample
2317
2318 This frame filter is very similar to the other examples. The only
2319 difference is this frame filter is wrapping the iterator provided to
2320 it (@code{frame_iter}) with a custom iterator called
2321 @code{ElidingInlineIterator}. This again defers actions to when
2322 @value{GDBN} prints the backtrace, as the iterator is not traversed
2323 until printing.
2324
2325 The iterator for this example is as follows. It is in this section of
2326 the example where decisions are made on the content of the backtrace.
2327
2328 @smallexample
2329 class ElidingInlineIterator:
2330 def __init__(self, ii):
2331 self.input_iterator = ii
2332
2333 def __iter__(self):
2334 return self
2335
2336 def next(self):
2337 frame = next(self.input_iterator)
2338
2339 if frame.inferior_frame().type() != gdb.INLINE_FRAME:
2340 return frame
2341
2342 try:
2343 eliding_frame = next(self.input_iterator)
2344 except StopIteration:
2345 return frame
2346 return ElidingFrameDecorator(eliding_frame, [frame])
2347 @end smallexample
2348
2349 This iterator implements the Python iterator protocol. When the
2350 @code{next} function is called (when @value{GDBN} prints each frame),
2351 the iterator checks if this frame decorator, @code{frame}, is wrapping
2352 an inlined frame. If it is not, it returns the existing frame decorator
2353 untouched. If it is wrapping an inlined frame, it assumes that the
2354 inlined frame was contained within the next oldest frame,
2355 @code{eliding_frame}, which it fetches. It then creates and returns a
2356 frame decorator, @code{ElidingFrameDecorator}, which contains both the
2357 elided frame, and the eliding frame.
2358
2359 @smallexample
2360 class ElidingInlineDecorator(FrameDecorator):
2361
2362 def __init__(self, frame, elided_frames):
2363 super(ElidingInlineDecorator, self).__init__(frame)
2364 self.frame = frame
2365 self.elided_frames = elided_frames
2366
2367 def elided(self):
2368 return iter(self.elided_frames)
2369 @end smallexample
2370
2371 This frame decorator overrides one function and returns the inlined
2372 frame in the @code{elided} method. As before it lets
2373 @code{FrameDecorator} do the rest of the work involved in printing
2374 this frame. This produces the following output.
2375
2376 @smallexample
2377 #0 0x004004e0 in bar () at inline.c:11
2378 #2 0x00400529 in main () at inline.c:25
2379 #1 0x00400529 in max (b=6, a=12) at inline.c:15
2380 @end smallexample
2381
2382 In that output, @code{max} which has been inlined into @code{main} is
2383 printed hierarchically. Another approach would be to combine the
2384 @code{function} method, and the @code{elided} method to both print a
2385 marker in the inlined frame, and also show the hierarchical
2386 relationship.
2387
2388 @node Unwinding Frames in Python
2389 @subsubsection Unwinding Frames in Python
2390 @cindex unwinding frames in Python
2391
2392 In @value{GDBN} terminology ``unwinding'' is the process of finding
2393 the previous frame (that is, caller's) from the current one. An
2394 unwinder has three methods. The first one checks if it can handle
2395 given frame (``sniff'' it). For the frames it can sniff an unwinder
2396 provides two additional methods: it can return frame's ID, and it can
2397 fetch registers from the previous frame. A running @value{GDBN}
2398 mantains a list of the unwinders and calls each unwinder's sniffer in
2399 turn until it finds the one that recognizes the current frame. There
2400 is an API to register an unwinder.
2401
2402 The unwinders that come with @value{GDBN} handle standard frames.
2403 However, mixed language applications (for example, an application
2404 running Java Virtual Machine) sometimes use frame layouts that cannot
2405 be handled by the @value{GDBN} unwinders. You can write Python code
2406 that can handle such custom frames.
2407
2408 You implement a frame unwinder in Python as a class with which has two
2409 attributes, @code{name} and @code{enabled}, with obvious meanings, and
2410 a single method @code{__call__}, which examines a given frame and
2411 returns an object (an instance of @code{gdb.UnwindInfo class)}
2412 describing it. If an unwinder does not recognize a frame, it should
2413 return @code{None}. The code in @value{GDBN} that enables writing
2414 unwinders in Python uses this object to return frame's ID and previous
2415 frame registers when @value{GDBN} core asks for them.
2416
2417 An unwinder should do as little work as possible. Some otherwise
2418 innocuous operations can cause problems (even crashes, as this code is
2419 not not well-hardened yet). For example, making an inferior call from
2420 an unwinder is unadvisable, as an inferior call will reset
2421 @value{GDBN}'s stack unwinding process, potentially causing re-entrant
2422 unwinding.
2423
2424 @subheading Unwinder Input
2425
2426 An object passed to an unwinder (a @code{gdb.PendingFrame} instance)
2427 provides a method to read frame's registers:
2428
2429 @defun PendingFrame.read_register (reg)
2430 This method returns the contents of the register @var{reg} in the
2431 frame as a @code{gdb.Value} object. @var{reg} can be either a
2432 register number or a register name; the values are platform-specific.
2433 They are usually found in the corresponding
2434 @file{@var{platform}-tdep.h} file in the @value{GDBN} source tree. If
2435 @var{reg} does not name a register for the current architecture, this
2436 method will throw an exception.
2437
2438 Note that this method will always return a @code{gdb.Value} for a
2439 valid register name. This does not mean that the value will be valid.
2440 For example, you may request a register that an earlier unwinder could
2441 not unwind---the value will be unavailable. Instead, the
2442 @code{gdb.Value} returned from this method will be lazy; that is, its
2443 underlying bits will not be fetched until it is first used. So,
2444 attempting to use such a value will cause an exception at the point of
2445 use.
2446
2447 The type of the returned @code{gdb.Value} depends on the register and
2448 the architecture. It is common for registers to have a scalar type,
2449 like @code{long long}; but many other types are possible, such as
2450 pointer, pointer-to-function, floating point or vector types.
2451 @end defun
2452
2453 It also provides a factory method to create a @code{gdb.UnwindInfo}
2454 instance to be returned to @value{GDBN}:
2455
2456 @defun PendingFrame.create_unwind_info (frame_id)
2457 Returns a new @code{gdb.UnwindInfo} instance identified by given
2458 @var{frame_id}. The argument is used to build @value{GDBN}'s frame ID
2459 using one of functions provided by @value{GDBN}. @var{frame_id}'s attributes
2460 determine which function will be used, as follows:
2461
2462 @table @code
2463 @item sp, pc
2464 The frame is identified by the given stack address and PC. The stack
2465 address must be chosen so that it is constant throughout the lifetime
2466 of the frame, so a typical choice is the value of the stack pointer at
2467 the start of the function---in the DWARF standard, this would be the
2468 ``Call Frame Address''.
2469
2470 This is the most common case by far. The other cases are documented
2471 for completeness but are only useful in specialized situations.
2472
2473 @item sp, pc, special
2474 The frame is identified by the stack address, the PC, and a
2475 ``special'' address. The special address is used on architectures
2476 that can have frames that do not change the stack, but which are still
2477 distinct, for example the IA-64, which has a second stack for
2478 registers. Both @var{sp} and @var{special} must be constant
2479 throughout the lifetime of the frame.
2480
2481 @item sp
2482 The frame is identified by the stack address only. Any other stack
2483 frame with a matching @var{sp} will be considered to match this frame.
2484 Inside gdb, this is called a ``wild frame''. You will never need
2485 this.
2486 @end table
2487
2488 Each attribute value should be an instance of @code{gdb.Value}.
2489
2490 @end defun
2491
2492 @subheading Unwinder Output: UnwindInfo
2493
2494 Use @code{PendingFrame.create_unwind_info} method described above to
2495 create a @code{gdb.UnwindInfo} instance. Use the following method to
2496 specify caller registers that have been saved in this frame:
2497
2498 @defun gdb.UnwindInfo.add_saved_register (reg, value)
2499 @var{reg} identifies the register. It can be a number or a name, just
2500 as for the @code{PendingFrame.read_register} method above.
2501 @var{value} is a register value (a @code{gdb.Value} object).
2502 @end defun
2503
2504 @subheading Unwinder Skeleton Code
2505
2506 @value{GDBN} comes with the module containing the base @code{Unwinder}
2507 class. Derive your unwinder class from it and structure the code as
2508 follows:
2509
2510 @smallexample
2511 from gdb.unwinders import Unwinder
2512
2513 class FrameId(object):
2514 def __init__(self, sp, pc):
2515 self.sp = sp
2516 self.pc = pc
2517
2518
2519 class MyUnwinder(Unwinder):
2520 def __init__(....):
2521 supe(MyUnwinder, self).__init___(<expects unwinder name argument>)
2522
2523 def __call__(pending_frame):
2524 if not <we recognize frame>:
2525 return None
2526 # Create UnwindInfo. Usually the frame is identified by the stack
2527 # pointer and the program counter.
2528 sp = pending_frame.read_register(<SP number>)
2529 pc = pending_frame.read_register(<PC number>)
2530 unwind_info = pending_frame.create_unwind_info(FrameId(sp, pc))
2531
2532 # Find the values of the registers in the caller's frame and
2533 # save them in the result:
2534 unwind_info.add_saved_register(<register>, <value>)
2535 ....
2536
2537 # Return the result:
2538 return unwind_info
2539
2540 @end smallexample
2541
2542 @subheading Registering a Unwinder
2543
2544 An object file, a program space, and the @value{GDBN} proper can have
2545 unwinders registered with it.
2546
2547 The @code{gdb.unwinders} module provides the function to register a
2548 unwinder:
2549
2550 @defun gdb.unwinder.register_unwinder (locus, unwinder, replace=False)
2551 @var{locus} is specifies an object file or a program space to which
2552 @var{unwinder} is added. Passing @code{None} or @code{gdb} adds
2553 @var{unwinder} to the @value{GDBN}'s global unwinder list. The newly
2554 added @var{unwinder} will be called before any other unwinder from the
2555 same locus. Two unwinders in the same locus cannot have the same
2556 name. An attempt to add a unwinder with already existing name raises
2557 an exception unless @var{replace} is @code{True}, in which case the
2558 old unwinder is deleted.
2559 @end defun
2560
2561 @subheading Unwinder Precedence
2562
2563 @value{GDBN} first calls the unwinders from all the object files in no
2564 particular order, then the unwinders from the current program space,
2565 and finally the unwinders from @value{GDBN}.
2566
2567 @node Xmethods In Python
2568 @subsubsection Xmethods In Python
2569 @cindex xmethods in Python
2570
2571 @dfn{Xmethods} are additional methods or replacements for existing
2572 methods of a C@t{++} class. This feature is useful for those cases
2573 where a method defined in C@t{++} source code could be inlined or
2574 optimized out by the compiler, making it unavailable to @value{GDBN}.
2575 For such cases, one can define an xmethod to serve as a replacement
2576 for the method defined in the C@t{++} source code. @value{GDBN} will
2577 then invoke the xmethod, instead of the C@t{++} method, to
2578 evaluate expressions. One can also use xmethods when debugging
2579 with core files. Moreover, when debugging live programs, invoking an
2580 xmethod need not involve running the inferior (which can potentially
2581 perturb its state). Hence, even if the C@t{++} method is available, it
2582 is better to use its replacement xmethod if one is defined.
2583
2584 The xmethods feature in Python is available via the concepts of an
2585 @dfn{xmethod matcher} and an @dfn{xmethod worker}. To
2586 implement an xmethod, one has to implement a matcher and a
2587 corresponding worker for it (more than one worker can be
2588 implemented, each catering to a different overloaded instance of the
2589 method). Internally, @value{GDBN} invokes the @code{match} method of a
2590 matcher to match the class type and method name. On a match, the
2591 @code{match} method returns a list of matching @emph{worker} objects.
2592 Each worker object typically corresponds to an overloaded instance of
2593 the xmethod. They implement a @code{get_arg_types} method which
2594 returns a sequence of types corresponding to the arguments the xmethod
2595 requires. @value{GDBN} uses this sequence of types to perform
2596 overload resolution and picks a winning xmethod worker. A winner
2597 is also selected from among the methods @value{GDBN} finds in the
2598 C@t{++} source code. Next, the winning xmethod worker and the
2599 winning C@t{++} method are compared to select an overall winner. In
2600 case of a tie between a xmethod worker and a C@t{++} method, the
2601 xmethod worker is selected as the winner. That is, if a winning
2602 xmethod worker is found to be equivalent to the winning C@t{++}
2603 method, then the xmethod worker is treated as a replacement for
2604 the C@t{++} method. @value{GDBN} uses the overall winner to invoke the
2605 method. If the winning xmethod worker is the overall winner, then
2606 the corresponding xmethod is invoked via the @code{__call__} method
2607 of the worker object.
2608
2609 If one wants to implement an xmethod as a replacement for an
2610 existing C@t{++} method, then they have to implement an equivalent
2611 xmethod which has exactly the same name and takes arguments of
2612 exactly the same type as the C@t{++} method. If the user wants to
2613 invoke the C@t{++} method even though a replacement xmethod is
2614 available for that method, then they can disable the xmethod.
2615
2616 @xref{Xmethod API}, for API to implement xmethods in Python.
2617 @xref{Writing an Xmethod}, for implementing xmethods in Python.
2618
2619 @node Xmethod API
2620 @subsubsection Xmethod API
2621 @cindex xmethod API
2622
2623 The @value{GDBN} Python API provides classes, interfaces and functions
2624 to implement, register and manipulate xmethods.
2625 @xref{Xmethods In Python}.
2626
2627 An xmethod matcher should be an instance of a class derived from
2628 @code{XMethodMatcher} defined in the module @code{gdb.xmethod}, or an
2629 object with similar interface and attributes. An instance of
2630 @code{XMethodMatcher} has the following attributes:
2631
2632 @defvar name
2633 The name of the matcher.
2634 @end defvar
2635
2636 @defvar enabled
2637 A boolean value indicating whether the matcher is enabled or disabled.
2638 @end defvar
2639
2640 @defvar methods
2641 A list of named methods managed by the matcher. Each object in the list
2642 is an instance of the class @code{XMethod} defined in the module
2643 @code{gdb.xmethod}, or any object with the following attributes:
2644
2645 @table @code
2646
2647 @item name
2648 Name of the xmethod which should be unique for each xmethod
2649 managed by the matcher.
2650
2651 @item enabled
2652 A boolean value indicating whether the xmethod is enabled or
2653 disabled.
2654
2655 @end table
2656
2657 The class @code{XMethod} is a convenience class with same
2658 attributes as above along with the following constructor:
2659
2660 @defun XMethod.__init__ (self, name)
2661 Constructs an enabled xmethod with name @var{name}.
2662 @end defun
2663 @end defvar
2664
2665 @noindent
2666 The @code{XMethodMatcher} class has the following methods:
2667
2668 @defun XMethodMatcher.__init__ (self, name)
2669 Constructs an enabled xmethod matcher with name @var{name}. The
2670 @code{methods} attribute is initialized to @code{None}.
2671 @end defun
2672
2673 @defun XMethodMatcher.match (self, class_type, method_name)
2674 Derived classes should override this method. It should return a
2675 xmethod worker object (or a sequence of xmethod worker
2676 objects) matching the @var{class_type} and @var{method_name}.
2677 @var{class_type} is a @code{gdb.Type} object, and @var{method_name}
2678 is a string value. If the matcher manages named methods as listed in
2679 its @code{methods} attribute, then only those worker objects whose
2680 corresponding entries in the @code{methods} list are enabled should be
2681 returned.
2682 @end defun
2683
2684 An xmethod worker should be an instance of a class derived from
2685 @code{XMethodWorker} defined in the module @code{gdb.xmethod},
2686 or support the following interface:
2687
2688 @defun XMethodWorker.get_arg_types (self)
2689 This method returns a sequence of @code{gdb.Type} objects corresponding
2690 to the arguments that the xmethod takes. It can return an empty
2691 sequence or @code{None} if the xmethod does not take any arguments.
2692 If the xmethod takes a single argument, then a single
2693 @code{gdb.Type} object corresponding to it can be returned.
2694 @end defun
2695
2696 @defun XMethodWorker.get_result_type (self, *args)
2697 This method returns a @code{gdb.Type} object representing the type
2698 of the result of invoking this xmethod.
2699 The @var{args} argument is the same tuple of arguments that would be
2700 passed to the @code{__call__} method of this worker.
2701 @end defun
2702
2703 @defun XMethodWorker.__call__ (self, *args)
2704 This is the method which does the @emph{work} of the xmethod. The
2705 @var{args} arguments is the tuple of arguments to the xmethod. Each
2706 element in this tuple is a gdb.Value object. The first element is
2707 always the @code{this} pointer value.
2708 @end defun
2709
2710 For @value{GDBN} to lookup xmethods, the xmethod matchers
2711 should be registered using the following function defined in the module
2712 @code{gdb.xmethod}:
2713
2714 @defun register_xmethod_matcher (locus, matcher, replace=False)
2715 The @code{matcher} is registered with @code{locus}, replacing an
2716 existing matcher with the same name as @code{matcher} if
2717 @code{replace} is @code{True}. @code{locus} can be a
2718 @code{gdb.Objfile} object (@pxref{Objfiles In Python}), or a
2719 @code{gdb.Progspace} object (@pxref{Progspaces In Python}), or
2720 @code{None}. If it is @code{None}, then @code{matcher} is registered
2721 globally.
2722 @end defun
2723
2724 @node Writing an Xmethod
2725 @subsubsection Writing an Xmethod
2726 @cindex writing xmethods in Python
2727
2728 Implementing xmethods in Python will require implementing xmethod
2729 matchers and xmethod workers (@pxref{Xmethods In Python}). Consider
2730 the following C@t{++} class:
2731
2732 @smallexample
2733 class MyClass
2734 @{
2735 public:
2736 MyClass (int a) : a_(a) @{ @}
2737
2738 int geta (void) @{ return a_; @}
2739 int operator+ (int b);
2740
2741 private:
2742 int a_;
2743 @};
2744
2745 int
2746 MyClass::operator+ (int b)
2747 @{
2748 return a_ + b;
2749 @}
2750 @end smallexample
2751
2752 @noindent
2753 Let us define two xmethods for the class @code{MyClass}, one
2754 replacing the method @code{geta}, and another adding an overloaded
2755 flavor of @code{operator+} which takes a @code{MyClass} argument (the
2756 C@t{++} code above already has an overloaded @code{operator+}
2757 which takes an @code{int} argument). The xmethod matcher can be
2758 defined as follows:
2759
2760 @smallexample
2761 class MyClass_geta(gdb.xmethod.XMethod):
2762 def __init__(self):
2763 gdb.xmethod.XMethod.__init__(self, 'geta')
2764
2765 def get_worker(self, method_name):
2766 if method_name == 'geta':
2767 return MyClassWorker_geta()
2768
2769
2770 class MyClass_sum(gdb.xmethod.XMethod):
2771 def __init__(self):
2772 gdb.xmethod.XMethod.__init__(self, 'sum')
2773
2774 def get_worker(self, method_name):
2775 if method_name == 'operator+':
2776 return MyClassWorker_plus()
2777
2778
2779 class MyClassMatcher(gdb.xmethod.XMethodMatcher):
2780 def __init__(self):
2781 gdb.xmethod.XMethodMatcher.__init__(self, 'MyClassMatcher')
2782 # List of methods 'managed' by this matcher
2783 self.methods = [MyClass_geta(), MyClass_sum()]
2784
2785 def match(self, class_type, method_name):
2786 if class_type.tag != 'MyClass':
2787 return None
2788 workers = []
2789 for method in self.methods:
2790 if method.enabled:
2791 worker = method.get_worker(method_name)
2792 if worker:
2793 workers.append(worker)
2794
2795 return workers
2796 @end smallexample
2797
2798 @noindent
2799 Notice that the @code{match} method of @code{MyClassMatcher} returns
2800 a worker object of type @code{MyClassWorker_geta} for the @code{geta}
2801 method, and a worker object of type @code{MyClassWorker_plus} for the
2802 @code{operator+} method. This is done indirectly via helper classes
2803 derived from @code{gdb.xmethod.XMethod}. One does not need to use the
2804 @code{methods} attribute in a matcher as it is optional. However, if a
2805 matcher manages more than one xmethod, it is a good practice to list the
2806 xmethods in the @code{methods} attribute of the matcher. This will then
2807 facilitate enabling and disabling individual xmethods via the
2808 @code{enable/disable} commands. Notice also that a worker object is
2809 returned only if the corresponding entry in the @code{methods} attribute
2810 of the matcher is enabled.
2811
2812 The implementation of the worker classes returned by the matcher setup
2813 above is as follows:
2814
2815 @smallexample
2816 class MyClassWorker_geta(gdb.xmethod.XMethodWorker):
2817 def get_arg_types(self):
2818 return None
2819
2820 def get_result_type(self, obj):
2821 return gdb.lookup_type('int')
2822
2823 def __call__(self, obj):
2824 return obj['a_']
2825
2826
2827 class MyClassWorker_plus(gdb.xmethod.XMethodWorker):
2828 def get_arg_types(self):
2829 return gdb.lookup_type('MyClass')
2830
2831 def get_result_type(self, obj):
2832 return gdb.lookup_type('int')
2833
2834 def __call__(self, obj, other):
2835 return obj['a_'] + other['a_']
2836 @end smallexample
2837
2838 For @value{GDBN} to actually lookup a xmethod, it has to be
2839 registered with it. The matcher defined above is registered with
2840 @value{GDBN} globally as follows:
2841
2842 @smallexample
2843 gdb.xmethod.register_xmethod_matcher(None, MyClassMatcher())
2844 @end smallexample
2845
2846 If an object @code{obj} of type @code{MyClass} is initialized in C@t{++}
2847 code as follows:
2848
2849 @smallexample
2850 MyClass obj(5);
2851 @end smallexample
2852
2853 @noindent
2854 then, after loading the Python script defining the xmethod matchers
2855 and workers into @code{GDBN}, invoking the method @code{geta} or using
2856 the operator @code{+} on @code{obj} will invoke the xmethods
2857 defined above:
2858
2859 @smallexample
2860 (gdb) p obj.geta()
2861 $1 = 5
2862
2863 (gdb) p obj + obj
2864 $2 = 10
2865 @end smallexample
2866
2867 Consider another example with a C++ template class:
2868
2869 @smallexample
2870 template <class T>
2871 class MyTemplate
2872 @{
2873 public:
2874 MyTemplate () : dsize_(10), data_ (new T [10]) @{ @}
2875 ~MyTemplate () @{ delete [] data_; @}
2876
2877 int footprint (void)
2878 @{
2879 return sizeof (T) * dsize_ + sizeof (MyTemplate<T>);
2880 @}
2881
2882 private:
2883 int dsize_;
2884 T *data_;
2885 @};
2886 @end smallexample
2887
2888 Let us implement an xmethod for the above class which serves as a
2889 replacement for the @code{footprint} method. The full code listing
2890 of the xmethod workers and xmethod matchers is as follows:
2891
2892 @smallexample
2893 class MyTemplateWorker_footprint(gdb.xmethod.XMethodWorker):
2894 def __init__(self, class_type):
2895 self.class_type = class_type
2896
2897 def get_arg_types(self):
2898 return None
2899
2900 def get_result_type(self):
2901 return gdb.lookup_type('int')
2902
2903 def __call__(self, obj):
2904 return (self.class_type.sizeof +
2905 obj['dsize_'] *
2906 self.class_type.template_argument(0).sizeof)
2907
2908
2909 class MyTemplateMatcher_footprint(gdb.xmethod.XMethodMatcher):
2910 def __init__(self):
2911 gdb.xmethod.XMethodMatcher.__init__(self, 'MyTemplateMatcher')
2912
2913 def match(self, class_type, method_name):
2914 if (re.match('MyTemplate<[ \t\n]*[_a-zA-Z][ _a-zA-Z0-9]*>',
2915 class_type.tag) and
2916 method_name == 'footprint'):
2917 return MyTemplateWorker_footprint(class_type)
2918 @end smallexample
2919
2920 Notice that, in this example, we have not used the @code{methods}
2921 attribute of the matcher as the matcher manages only one xmethod. The
2922 user can enable/disable this xmethod by enabling/disabling the matcher
2923 itself.
2924
2925 @node Inferiors In Python
2926 @subsubsection Inferiors In Python
2927 @cindex inferiors in Python
2928
2929 @findex gdb.Inferior
2930 Programs which are being run under @value{GDBN} are called inferiors
2931 (@pxref{Inferiors and Programs}). Python scripts can access
2932 information about and manipulate inferiors controlled by @value{GDBN}
2933 via objects of the @code{gdb.Inferior} class.
2934
2935 The following inferior-related functions are available in the @code{gdb}
2936 module:
2937
2938 @defun gdb.inferiors ()
2939 Return a tuple containing all inferior objects.
2940 @end defun
2941
2942 @defun gdb.selected_inferior ()
2943 Return an object representing the current inferior.
2944 @end defun
2945
2946 A @code{gdb.Inferior} object has the following attributes:
2947
2948 @defvar Inferior.num
2949 ID of inferior, as assigned by GDB.
2950 @end defvar
2951
2952 @defvar Inferior.pid
2953 Process ID of the inferior, as assigned by the underlying operating
2954 system.
2955 @end defvar
2956
2957 @defvar Inferior.was_attached
2958 Boolean signaling whether the inferior was created using `attach', or
2959 started by @value{GDBN} itself.
2960 @end defvar
2961
2962 @defvar Inferior.progspace
2963 The inferior's program space. @xref{Progspaces In Python}.
2964 @end defvar
2965
2966 A @code{gdb.Inferior} object has the following methods:
2967
2968 @defun Inferior.is_valid ()
2969 Returns @code{True} if the @code{gdb.Inferior} object is valid,
2970 @code{False} if not. A @code{gdb.Inferior} object will become invalid
2971 if the inferior no longer exists within @value{GDBN}. All other
2972 @code{gdb.Inferior} methods will throw an exception if it is invalid
2973 at the time the method is called.
2974 @end defun
2975
2976 @defun Inferior.threads ()
2977 This method returns a tuple holding all the threads which are valid
2978 when it is called. If there are no valid threads, the method will
2979 return an empty tuple.
2980 @end defun
2981
2982 @defun Inferior.architecture ()
2983 Return the @code{gdb.Architecture} (@pxref{Architectures In Python})
2984 for this inferior. This represents the architecture of the inferior
2985 as a whole. Some platforms can have multiple architectures in a
2986 single address space, so this may not match the architecture of a
2987 particular frame (@pxref{Frames In Python}).
2988 @end defun
2989
2990 @findex Inferior.read_memory
2991 @defun Inferior.read_memory (address, length)
2992 Read @var{length} addressable memory units from the inferior, starting at
2993 @var{address}. Returns a buffer object, which behaves much like an array
2994 or a string. It can be modified and given to the
2995 @code{Inferior.write_memory} function. In Python 3, the return
2996 value is a @code{memoryview} object.
2997 @end defun
2998
2999 @findex Inferior.write_memory
3000 @defun Inferior.write_memory (address, buffer @r{[}, length@r{]})
3001 Write the contents of @var{buffer} to the inferior, starting at
3002 @var{address}. The @var{buffer} parameter must be a Python object
3003 which supports the buffer protocol, i.e., a string, an array or the
3004 object returned from @code{Inferior.read_memory}. If given, @var{length}
3005 determines the number of addressable memory units from @var{buffer} to be
3006 written.
3007 @end defun
3008
3009 @findex gdb.search_memory
3010 @defun Inferior.search_memory (address, length, pattern)
3011 Search a region of the inferior memory starting at @var{address} with
3012 the given @var{length} using the search pattern supplied in
3013 @var{pattern}. The @var{pattern} parameter must be a Python object
3014 which supports the buffer protocol, i.e., a string, an array or the
3015 object returned from @code{gdb.read_memory}. Returns a Python @code{Long}
3016 containing the address where the pattern was found, or @code{None} if
3017 the pattern could not be found.
3018 @end defun
3019
3020 @findex Inferior.thread_from_handle
3021 @findex Inferior.thread_from_thread_handle
3022 @defun Inferior.thread_from_handle (handle)
3023 Return the thread object corresponding to @var{handle}, a thread
3024 library specific data structure such as @code{pthread_t} for pthreads
3025 library implementations.
3026
3027 The function @code{Inferior.thread_from_thread_handle} provides
3028 the same functionality, but use of @code{Inferior.thread_from_thread_handle}
3029 is deprecated.
3030 @end defun
3031
3032 @node Events In Python
3033 @subsubsection Events In Python
3034 @cindex inferior events in Python
3035
3036 @value{GDBN} provides a general event facility so that Python code can be
3037 notified of various state changes, particularly changes that occur in
3038 the inferior.
3039
3040 An @dfn{event} is just an object that describes some state change. The
3041 type of the object and its attributes will vary depending on the details
3042 of the change. All the existing events are described below.
3043
3044 In order to be notified of an event, you must register an event handler
3045 with an @dfn{event registry}. An event registry is an object in the
3046 @code{gdb.events} module which dispatches particular events. A registry
3047 provides methods to register and unregister event handlers:
3048
3049 @defun EventRegistry.connect (object)
3050 Add the given callable @var{object} to the registry. This object will be
3051 called when an event corresponding to this registry occurs.
3052 @end defun
3053
3054 @defun EventRegistry.disconnect (object)
3055 Remove the given @var{object} from the registry. Once removed, the object
3056 will no longer receive notifications of events.
3057 @end defun
3058
3059 Here is an example:
3060
3061 @smallexample
3062 def exit_handler (event):
3063 print "event type: exit"
3064 print "exit code: %d" % (event.exit_code)
3065
3066 gdb.events.exited.connect (exit_handler)
3067 @end smallexample
3068
3069 In the above example we connect our handler @code{exit_handler} to the
3070 registry @code{events.exited}. Once connected, @code{exit_handler} gets
3071 called when the inferior exits. The argument @dfn{event} in this example is
3072 of type @code{gdb.ExitedEvent}. As you can see in the example the
3073 @code{ExitedEvent} object has an attribute which indicates the exit code of
3074 the inferior.
3075
3076 The following is a listing of the event registries that are available and
3077 details of the events they emit:
3078
3079 @table @code
3080
3081 @item events.cont
3082 Emits @code{gdb.ThreadEvent}.
3083
3084 Some events can be thread specific when @value{GDBN} is running in non-stop
3085 mode. When represented in Python, these events all extend
3086 @code{gdb.ThreadEvent}. Note, this event is not emitted directly; instead,
3087 events which are emitted by this or other modules might extend this event.
3088 Examples of these events are @code{gdb.BreakpointEvent} and
3089 @code{gdb.ContinueEvent}.
3090
3091 @defvar ThreadEvent.inferior_thread
3092 In non-stop mode this attribute will be set to the specific thread which was
3093 involved in the emitted event. Otherwise, it will be set to @code{None}.
3094 @end defvar
3095
3096 Emits @code{gdb.ContinueEvent} which extends @code{gdb.ThreadEvent}.
3097
3098 This event indicates that the inferior has been continued after a stop. For
3099 inherited attribute refer to @code{gdb.ThreadEvent} above.
3100
3101 @item events.exited
3102 Emits @code{events.ExitedEvent} which indicates that the inferior has exited.
3103 @code{events.ExitedEvent} has two attributes:
3104 @defvar ExitedEvent.exit_code
3105 An integer representing the exit code, if available, which the inferior
3106 has returned. (The exit code could be unavailable if, for example,
3107 @value{GDBN} detaches from the inferior.) If the exit code is unavailable,
3108 the attribute does not exist.
3109 @end defvar
3110 @defvar ExitedEvent.inferior
3111 A reference to the inferior which triggered the @code{exited} event.
3112 @end defvar
3113
3114 @item events.stop
3115 Emits @code{gdb.StopEvent} which extends @code{gdb.ThreadEvent}.
3116
3117 Indicates that the inferior has stopped. All events emitted by this registry
3118 extend StopEvent. As a child of @code{gdb.ThreadEvent}, @code{gdb.StopEvent}
3119 will indicate the stopped thread when @value{GDBN} is running in non-stop
3120 mode. Refer to @code{gdb.ThreadEvent} above for more details.
3121
3122 Emits @code{gdb.SignalEvent} which extends @code{gdb.StopEvent}.
3123
3124 This event indicates that the inferior or one of its threads has received as
3125 signal. @code{gdb.SignalEvent} has the following attributes:
3126
3127 @defvar SignalEvent.stop_signal
3128 A string representing the signal received by the inferior. A list of possible
3129 signal values can be obtained by running the command @code{info signals} in
3130 the @value{GDBN} command prompt.
3131 @end defvar
3132
3133 Also emits @code{gdb.BreakpointEvent} which extends @code{gdb.StopEvent}.
3134
3135 @code{gdb.BreakpointEvent} event indicates that one or more breakpoints have
3136 been hit, and has the following attributes:
3137
3138 @defvar BreakpointEvent.breakpoints
3139 A sequence containing references to all the breakpoints (type
3140 @code{gdb.Breakpoint}) that were hit.
3141 @xref{Breakpoints In Python}, for details of the @code{gdb.Breakpoint} object.
3142 @end defvar
3143 @defvar BreakpointEvent.breakpoint
3144 A reference to the first breakpoint that was hit.
3145 This function is maintained for backward compatibility and is now deprecated
3146 in favor of the @code{gdb.BreakpointEvent.breakpoints} attribute.
3147 @end defvar
3148
3149 @item events.new_objfile
3150 Emits @code{gdb.NewObjFileEvent} which indicates that a new object file has
3151 been loaded by @value{GDBN}. @code{gdb.NewObjFileEvent} has one attribute:
3152
3153 @defvar NewObjFileEvent.new_objfile
3154 A reference to the object file (@code{gdb.Objfile}) which has been loaded.
3155 @xref{Objfiles In Python}, for details of the @code{gdb.Objfile} object.
3156 @end defvar
3157
3158 @item events.clear_objfiles
3159 Emits @code{gdb.ClearObjFilesEvent} which indicates that the list of object
3160 files for a program space has been reset.
3161 @code{gdb.ClearObjFilesEvent} has one attribute:
3162
3163 @defvar ClearObjFilesEvent.progspace
3164 A reference to the program space (@code{gdb.Progspace}) whose objfile list has
3165 been cleared. @xref{Progspaces In Python}.
3166 @end defvar
3167
3168 @item events.inferior_call
3169 Emits events just before and after a function in the inferior is
3170 called by @value{GDBN}. Before an inferior call, this emits an event
3171 of type @code{gdb.InferiorCallPreEvent}, and after an inferior call,
3172 this emits an event of type @code{gdb.InferiorCallPostEvent}.
3173
3174 @table @code
3175 @tindex gdb.InferiorCallPreEvent
3176 @item @code{gdb.InferiorCallPreEvent}
3177 Indicates that a function in the inferior is about to be called.
3178
3179 @defvar InferiorCallPreEvent.ptid
3180 The thread in which the call will be run.
3181 @end defvar
3182
3183 @defvar InferiorCallPreEvent.address
3184 The location of the function to be called.
3185 @end defvar
3186
3187 @tindex gdb.InferiorCallPostEvent
3188 @item @code{gdb.InferiorCallPostEvent}
3189 Indicates that a function in the inferior has just been called.
3190
3191 @defvar InferiorCallPostEvent.ptid
3192 The thread in which the call was run.
3193 @end defvar
3194
3195 @defvar InferiorCallPostEvent.address
3196 The location of the function that was called.
3197 @end defvar
3198 @end table
3199
3200 @item events.memory_changed
3201 Emits @code{gdb.MemoryChangedEvent} which indicates that the memory of the
3202 inferior has been modified by the @value{GDBN} user, for instance via a
3203 command like @w{@code{set *addr = value}}. The event has the following
3204 attributes:
3205
3206 @defvar MemoryChangedEvent.address
3207 The start address of the changed region.
3208 @end defvar
3209
3210 @defvar MemoryChangedEvent.length
3211 Length in bytes of the changed region.
3212 @end defvar
3213
3214 @item events.register_changed
3215 Emits @code{gdb.RegisterChangedEvent} which indicates that a register in the
3216 inferior has been modified by the @value{GDBN} user.
3217
3218 @defvar RegisterChangedEvent.frame
3219 A gdb.Frame object representing the frame in which the register was modified.
3220 @end defvar
3221 @defvar RegisterChangedEvent.regnum
3222 Denotes which register was modified.
3223 @end defvar
3224
3225 @item events.breakpoint_created
3226 This is emitted when a new breakpoint has been created. The argument
3227 that is passed is the new @code{gdb.Breakpoint} object.
3228
3229 @item events.breakpoint_modified
3230 This is emitted when a breakpoint has been modified in some way. The
3231 argument that is passed is the new @code{gdb.Breakpoint} object.
3232
3233 @item events.breakpoint_deleted
3234 This is emitted when a breakpoint has been deleted. The argument that
3235 is passed is the @code{gdb.Breakpoint} object. When this event is
3236 emitted, the @code{gdb.Breakpoint} object will already be in its
3237 invalid state; that is, the @code{is_valid} method will return
3238 @code{False}.
3239
3240 @item events.before_prompt
3241 This event carries no payload. It is emitted each time @value{GDBN}
3242 presents a prompt to the user.
3243
3244 @item events.new_inferior
3245 This is emitted when a new inferior is created. Note that the
3246 inferior is not necessarily running; in fact, it may not even have an
3247 associated executable.
3248
3249 The event is of type @code{gdb.NewInferiorEvent}. This has a single
3250 attribute:
3251
3252 @defvar NewInferiorEvent.inferior
3253 The new inferior, a @code{gdb.Inferior} object.
3254 @end defvar
3255
3256 @item events.inferior_deleted
3257 This is emitted when an inferior has been deleted. Note that this is
3258 not the same as process exit; it is notified when the inferior itself
3259 is removed, say via @code{remove-inferiors}.
3260
3261 The event is of type @code{gdb.InferiorDeletedEvent}. This has a single
3262 attribute:
3263
3264 @defvar NewInferiorEvent.inferior
3265 The inferior that is being removed, a @code{gdb.Inferior} object.
3266 @end defvar
3267
3268 @item events.new_thread
3269 This is emitted when @value{GDBN} notices a new thread. The event is of
3270 type @code{gdb.NewThreadEvent}, which extends @code{gdb.ThreadEvent}.
3271 This has a single attribute:
3272
3273 @defvar NewThreadEvent.inferior_thread
3274 The new thread.
3275 @end defvar
3276
3277 @end table
3278
3279 @node Threads In Python
3280 @subsubsection Threads In Python
3281 @cindex threads in python
3282
3283 @findex gdb.InferiorThread
3284 Python scripts can access information about, and manipulate inferior threads
3285 controlled by @value{GDBN}, via objects of the @code{gdb.InferiorThread} class.
3286
3287 The following thread-related functions are available in the @code{gdb}
3288 module:
3289
3290 @findex gdb.selected_thread
3291 @defun gdb.selected_thread ()
3292 This function returns the thread object for the selected thread. If there
3293 is no selected thread, this will return @code{None}.
3294 @end defun
3295
3296 A @code{gdb.InferiorThread} object has the following attributes:
3297
3298 @defvar InferiorThread.name
3299 The name of the thread. If the user specified a name using
3300 @code{thread name}, then this returns that name. Otherwise, if an
3301 OS-supplied name is available, then it is returned. Otherwise, this
3302 returns @code{None}.
3303
3304 This attribute can be assigned to. The new value must be a string
3305 object, which sets the new name, or @code{None}, which removes any
3306 user-specified thread name.
3307 @end defvar
3308
3309 @defvar InferiorThread.num
3310 The per-inferior number of the thread, as assigned by GDB.
3311 @end defvar
3312
3313 @defvar InferiorThread.global_num
3314 The global ID of the thread, as assigned by GDB. You can use this to
3315 make Python breakpoints thread-specific, for example
3316 (@pxref{python_breakpoint_thread,,The Breakpoint.thread attribute}).
3317 @end defvar
3318
3319 @defvar InferiorThread.ptid
3320 ID of the thread, as assigned by the operating system. This attribute is a
3321 tuple containing three integers. The first is the Process ID (PID); the second
3322 is the Lightweight Process ID (LWPID), and the third is the Thread ID (TID).
3323 Either the LWPID or TID may be 0, which indicates that the operating system
3324 does not use that identifier.
3325 @end defvar
3326
3327 @defvar InferiorThread.inferior
3328 The inferior this thread belongs to. This attribute is represented as
3329 a @code{gdb.Inferior} object. This attribute is not writable.
3330 @end defvar
3331
3332 A @code{gdb.InferiorThread} object has the following methods:
3333
3334 @defun InferiorThread.is_valid ()
3335 Returns @code{True} if the @code{gdb.InferiorThread} object is valid,
3336 @code{False} if not. A @code{gdb.InferiorThread} object will become
3337 invalid if the thread exits, or the inferior that the thread belongs
3338 is deleted. All other @code{gdb.InferiorThread} methods will throw an
3339 exception if it is invalid at the time the method is called.
3340 @end defun
3341
3342 @defun InferiorThread.switch ()
3343 This changes @value{GDBN}'s currently selected thread to the one represented
3344 by this object.
3345 @end defun
3346
3347 @defun InferiorThread.is_stopped ()
3348 Return a Boolean indicating whether the thread is stopped.
3349 @end defun
3350
3351 @defun InferiorThread.is_running ()
3352 Return a Boolean indicating whether the thread is running.
3353 @end defun
3354
3355 @defun InferiorThread.is_exited ()
3356 Return a Boolean indicating whether the thread is exited.
3357 @end defun
3358
3359 @defun InferiorThread.handle ()
3360 Return the thread object's handle, represented as a Python @code{bytes}
3361 object. A @code{gdb.Value} representation of the handle may be
3362 constructed via @code{gdb.Value(bufobj, type)} where @var{bufobj} is
3363 the Python @code{bytes} representation of the handle and @var{type} is
3364 a @code{gdb.Type} for the handle type.
3365 @end defun
3366
3367 @node Recordings In Python
3368 @subsubsection Recordings In Python
3369 @cindex recordings in python
3370
3371 The following recordings-related functions
3372 (@pxref{Process Record and Replay}) are available in the @code{gdb}
3373 module:
3374
3375 @defun gdb.start_recording (@r{[}method@r{]}, @r{[}format@r{]})
3376 Start a recording using the given @var{method} and @var{format}. If
3377 no @var{format} is given, the default format for the recording method
3378 is used. If no @var{method} is given, the default method will be used.
3379 Returns a @code{gdb.Record} object on success. Throw an exception on
3380 failure.
3381
3382 The following strings can be passed as @var{method}:
3383
3384 @itemize @bullet
3385 @item
3386 @code{"full"}
3387 @item
3388 @code{"btrace"}: Possible values for @var{format}: @code{"pt"},
3389 @code{"bts"} or leave out for default format.
3390 @end itemize
3391 @end defun
3392
3393 @defun gdb.current_recording ()
3394 Access a currently running recording. Return a @code{gdb.Record}
3395 object on success. Return @code{None} if no recording is currently
3396 active.
3397 @end defun
3398
3399 @defun gdb.stop_recording ()
3400 Stop the current recording. Throw an exception if no recording is
3401 currently active. All record objects become invalid after this call.
3402 @end defun
3403
3404 A @code{gdb.Record} object has the following attributes:
3405
3406 @defvar Record.method
3407 A string with the current recording method, e.g.@: @code{full} or
3408 @code{btrace}.
3409 @end defvar
3410
3411 @defvar Record.format
3412 A string with the current recording format, e.g.@: @code{bt}, @code{pts} or
3413 @code{None}.
3414 @end defvar
3415
3416 @defvar Record.begin
3417 A method specific instruction object representing the first instruction
3418 in this recording.
3419 @end defvar
3420
3421 @defvar Record.end
3422 A method specific instruction object representing the current
3423 instruction, that is not actually part of the recording.
3424 @end defvar
3425
3426 @defvar Record.replay_position
3427 The instruction representing the current replay position. If there is
3428 no replay active, this will be @code{None}.
3429 @end defvar
3430
3431 @defvar Record.instruction_history
3432 A list with all recorded instructions.
3433 @end defvar
3434
3435 @defvar Record.function_call_history
3436 A list with all recorded function call segments.
3437 @end defvar
3438
3439 A @code{gdb.Record} object has the following methods:
3440
3441 @defun Record.goto (instruction)
3442 Move the replay position to the given @var{instruction}.
3443 @end defun
3444
3445 The common @code{gdb.Instruction} class that recording method specific
3446 instruction objects inherit from, has the following attributes:
3447
3448 @defvar Instruction.pc
3449 An integer representing this instruction's address.
3450 @end defvar
3451
3452 @defvar Instruction.data
3453 A buffer with the raw instruction data. In Python 3, the return value is a
3454 @code{memoryview} object.
3455 @end defvar
3456
3457 @defvar Instruction.decoded
3458 A human readable string with the disassembled instruction.
3459 @end defvar
3460
3461 @defvar Instruction.size
3462 The size of the instruction in bytes.
3463 @end defvar
3464
3465 Additionally @code{gdb.RecordInstruction} has the following attributes:
3466
3467 @defvar RecordInstruction.number
3468 An integer identifying this instruction. @code{number} corresponds to
3469 the numbers seen in @code{record instruction-history}
3470 (@pxref{Process Record and Replay}).
3471 @end defvar
3472
3473 @defvar RecordInstruction.sal
3474 A @code{gdb.Symtab_and_line} object representing the associated symtab
3475 and line of this instruction. May be @code{None} if no debug information is
3476 available.
3477 @end defvar
3478
3479 @defvar RecordInstruction.is_speculative
3480 A boolean indicating whether the instruction was executed speculatively.
3481 @end defvar
3482
3483 If an error occured during recording or decoding a recording, this error is
3484 represented by a @code{gdb.RecordGap} object in the instruction list. It has
3485 the following attributes:
3486
3487 @defvar RecordGap.number
3488 An integer identifying this gap. @code{number} corresponds to the numbers seen
3489 in @code{record instruction-history} (@pxref{Process Record and Replay}).
3490 @end defvar
3491
3492 @defvar RecordGap.error_code
3493 A numerical representation of the reason for the gap. The value is specific to
3494 the current recording method.
3495 @end defvar
3496
3497 @defvar RecordGap.error_string
3498 A human readable string with the reason for the gap.
3499 @end defvar
3500
3501 A @code{gdb.RecordFunctionSegment} object has the following attributes:
3502
3503 @defvar RecordFunctionSegment.number
3504 An integer identifying this function segment. @code{number} corresponds to
3505 the numbers seen in @code{record function-call-history}
3506 (@pxref{Process Record and Replay}).
3507 @end defvar
3508
3509 @defvar RecordFunctionSegment.symbol
3510 A @code{gdb.Symbol} object representing the associated symbol. May be
3511 @code{None} if no debug information is available.
3512 @end defvar
3513
3514 @defvar RecordFunctionSegment.level
3515 An integer representing the function call's stack level. May be
3516 @code{None} if the function call is a gap.
3517 @end defvar
3518
3519 @defvar RecordFunctionSegment.instructions
3520 A list of @code{gdb.RecordInstruction} or @code{gdb.RecordGap} objects
3521 associated with this function call.
3522 @end defvar
3523
3524 @defvar RecordFunctionSegment.up
3525 A @code{gdb.RecordFunctionSegment} object representing the caller's
3526 function segment. If the call has not been recorded, this will be the
3527 function segment to which control returns. If neither the call nor the
3528 return have been recorded, this will be @code{None}.
3529 @end defvar
3530
3531 @defvar RecordFunctionSegment.prev
3532 A @code{gdb.RecordFunctionSegment} object representing the previous
3533 segment of this function call. May be @code{None}.
3534 @end defvar
3535
3536 @defvar RecordFunctionSegment.next
3537 A @code{gdb.RecordFunctionSegment} object representing the next segment of
3538 this function call. May be @code{None}.
3539 @end defvar
3540
3541 The following example demonstrates the usage of these objects and
3542 functions to create a function that will rewind a record to the last
3543 time a function in a different file was executed. This would typically
3544 be used to track the execution of user provided callback functions in a
3545 library which typically are not visible in a back trace.
3546
3547 @smallexample
3548 def bringback ():
3549 rec = gdb.current_recording ()
3550 if not rec:
3551 return
3552
3553 insn = rec.instruction_history
3554 if len (insn) == 0:
3555 return
3556
3557 try:
3558 position = insn.index (rec.replay_position)
3559 except:
3560 position = -1
3561 try:
3562 filename = insn[position].sal.symtab.fullname ()
3563 except:
3564 filename = None
3565
3566 for i in reversed (insn[:position]):
3567 try:
3568 current = i.sal.symtab.fullname ()
3569 except:
3570 current = None
3571
3572 if filename == current:
3573 continue
3574
3575 rec.goto (i)
3576 return
3577 @end smallexample
3578
3579 Another possible application is to write a function that counts the
3580 number of code executions in a given line range. This line range can
3581 contain parts of functions or span across several functions and is not
3582 limited to be contiguous.
3583
3584 @smallexample
3585 def countrange (filename, linerange):
3586 count = 0
3587
3588 def filter_only (file_name):
3589 for call in gdb.current_recording ().function_call_history:
3590 try:
3591 if file_name in call.symbol.symtab.fullname ():
3592 yield call
3593 except:
3594 pass
3595
3596 for c in filter_only (filename):
3597 for i in c.instructions:
3598 try:
3599 if i.sal.line in linerange:
3600 count += 1
3601 break;
3602 except:
3603 pass
3604
3605 return count
3606 @end smallexample
3607
3608 @node Commands In Python
3609 @subsubsection Commands In Python
3610
3611 @cindex commands in python
3612 @cindex python commands
3613 You can implement new @value{GDBN} CLI commands in Python. A CLI
3614 command is implemented using an instance of the @code{gdb.Command}
3615 class, most commonly using a subclass.
3616
3617 @defun Command.__init__ (name, @var{command_class} @r{[}, @var{completer_class} @r{[}, @var{prefix}@r{]]})
3618 The object initializer for @code{Command} registers the new command
3619 with @value{GDBN}. This initializer is normally invoked from the
3620 subclass' own @code{__init__} method.
3621
3622 @var{name} is the name of the command. If @var{name} consists of
3623 multiple words, then the initial words are looked for as prefix
3624 commands. In this case, if one of the prefix commands does not exist,
3625 an exception is raised.
3626
3627 There is no support for multi-line commands.
3628
3629 @var{command_class} should be one of the @samp{COMMAND_} constants
3630 defined below. This argument tells @value{GDBN} how to categorize the
3631 new command in the help system.
3632
3633 @var{completer_class} is an optional argument. If given, it should be
3634 one of the @samp{COMPLETE_} constants defined below. This argument
3635 tells @value{GDBN} how to perform completion for this command. If not
3636 given, @value{GDBN} will attempt to complete using the object's
3637 @code{complete} method (see below); if no such method is found, an
3638 error will occur when completion is attempted.
3639
3640 @var{prefix} is an optional argument. If @code{True}, then the new
3641 command is a prefix command; sub-commands of this command may be
3642 registered.
3643
3644 The help text for the new command is taken from the Python
3645 documentation string for the command's class, if there is one. If no
3646 documentation string is provided, the default value ``This command is
3647 not documented.'' is used.
3648 @end defun
3649
3650 @cindex don't repeat Python command
3651 @defun Command.dont_repeat ()
3652 By default, a @value{GDBN} command is repeated when the user enters a
3653 blank line at the command prompt. A command can suppress this
3654 behavior by invoking the @code{dont_repeat} method. This is similar
3655 to the user command @code{dont-repeat}, see @ref{Define, dont-repeat}.
3656 @end defun
3657
3658 @defun Command.invoke (argument, from_tty)
3659 This method is called by @value{GDBN} when this command is invoked.
3660
3661 @var{argument} is a string. It is the argument to the command, after
3662 leading and trailing whitespace has been stripped.
3663
3664 @var{from_tty} is a boolean argument. When true, this means that the
3665 command was entered by the user at the terminal; when false it means
3666 that the command came from elsewhere.
3667
3668 If this method throws an exception, it is turned into a @value{GDBN}
3669 @code{error} call. Otherwise, the return value is ignored.
3670
3671 @findex gdb.string_to_argv
3672 To break @var{argument} up into an argv-like string use
3673 @code{gdb.string_to_argv}. This function behaves identically to
3674 @value{GDBN}'s internal argument lexer @code{buildargv}.
3675 It is recommended to use this for consistency.
3676 Arguments are separated by spaces and may be quoted.
3677 Example:
3678
3679 @smallexample
3680 print gdb.string_to_argv ("1 2\ \\\"3 '4 \"5' \"6 '7\"")
3681 ['1', '2 "3', '4 "5', "6 '7"]
3682 @end smallexample
3683
3684 @end defun
3685
3686 @cindex completion of Python commands
3687 @defun Command.complete (text, word)
3688 This method is called by @value{GDBN} when the user attempts
3689 completion on this command. All forms of completion are handled by
3690 this method, that is, the @key{TAB} and @key{M-?} key bindings
3691 (@pxref{Completion}), and the @code{complete} command (@pxref{Help,
3692 complete}).
3693
3694 The arguments @var{text} and @var{word} are both strings; @var{text}
3695 holds the complete command line up to the cursor's location, while
3696 @var{word} holds the last word of the command line; this is computed
3697 using a word-breaking heuristic.
3698
3699 The @code{complete} method can return several values:
3700 @itemize @bullet
3701 @item
3702 If the return value is a sequence, the contents of the sequence are
3703 used as the completions. It is up to @code{complete} to ensure that the
3704 contents actually do complete the word. A zero-length sequence is
3705 allowed, it means that there were no completions available. Only
3706 string elements of the sequence are used; other elements in the
3707 sequence are ignored.
3708
3709 @item
3710 If the return value is one of the @samp{COMPLETE_} constants defined
3711 below, then the corresponding @value{GDBN}-internal completion
3712 function is invoked, and its result is used.
3713
3714 @item
3715 All other results are treated as though there were no available
3716 completions.
3717 @end itemize
3718 @end defun
3719
3720 When a new command is registered, it must be declared as a member of
3721 some general class of commands. This is used to classify top-level
3722 commands in the on-line help system; note that prefix commands are not
3723 listed under their own category but rather that of their top-level
3724 command. The available classifications are represented by constants
3725 defined in the @code{gdb} module:
3726
3727 @table @code
3728 @findex COMMAND_NONE
3729 @findex gdb.COMMAND_NONE
3730 @item gdb.COMMAND_NONE
3731 The command does not belong to any particular class. A command in
3732 this category will not be displayed in any of the help categories.
3733
3734 @findex COMMAND_RUNNING
3735 @findex gdb.COMMAND_RUNNING
3736 @item gdb.COMMAND_RUNNING
3737 The command is related to running the inferior. For example,
3738 @code{start}, @code{step}, and @code{continue} are in this category.
3739 Type @kbd{help running} at the @value{GDBN} prompt to see a list of
3740 commands in this category.
3741
3742 @findex COMMAND_DATA
3743 @findex gdb.COMMAND_DATA
3744 @item gdb.COMMAND_DATA
3745 The command is related to data or variables. For example,
3746 @code{call}, @code{find}, and @code{print} are in this category. Type
3747 @kbd{help data} at the @value{GDBN} prompt to see a list of commands
3748 in this category.
3749
3750 @findex COMMAND_STACK
3751 @findex gdb.COMMAND_STACK
3752 @item gdb.COMMAND_STACK
3753 The command has to do with manipulation of the stack. For example,
3754 @code{backtrace}, @code{frame}, and @code{return} are in this
3755 category. Type @kbd{help stack} at the @value{GDBN} prompt to see a
3756 list of commands in this category.
3757
3758 @findex COMMAND_FILES
3759 @findex gdb.COMMAND_FILES
3760 @item gdb.COMMAND_FILES
3761 This class is used for file-related commands. For example,
3762 @code{file}, @code{list} and @code{section} are in this category.
3763 Type @kbd{help files} at the @value{GDBN} prompt to see a list of
3764 commands in this category.
3765
3766 @findex COMMAND_SUPPORT
3767 @findex gdb.COMMAND_SUPPORT
3768 @item gdb.COMMAND_SUPPORT
3769 This should be used for ``support facilities'', generally meaning
3770 things that are useful to the user when interacting with @value{GDBN},
3771 but not related to the state of the inferior. For example,
3772 @code{help}, @code{make}, and @code{shell} are in this category. Type
3773 @kbd{help support} at the @value{GDBN} prompt to see a list of
3774 commands in this category.
3775
3776 @findex COMMAND_STATUS
3777 @findex gdb.COMMAND_STATUS
3778 @item gdb.COMMAND_STATUS
3779 The command is an @samp{info}-related command, that is, related to the
3780 state of @value{GDBN} itself. For example, @code{info}, @code{macro},
3781 and @code{show} are in this category. Type @kbd{help status} at the
3782 @value{GDBN} prompt to see a list of commands in this category.
3783
3784 @findex COMMAND_BREAKPOINTS
3785 @findex gdb.COMMAND_BREAKPOINTS
3786 @item gdb.COMMAND_BREAKPOINTS
3787 The command has to do with breakpoints. For example, @code{break},
3788 @code{clear}, and @code{delete} are in this category. Type @kbd{help
3789 breakpoints} at the @value{GDBN} prompt to see a list of commands in
3790 this category.
3791
3792 @findex COMMAND_TRACEPOINTS
3793 @findex gdb.COMMAND_TRACEPOINTS
3794 @item gdb.COMMAND_TRACEPOINTS
3795 The command has to do with tracepoints. For example, @code{trace},
3796 @code{actions}, and @code{tfind} are in this category. Type
3797 @kbd{help tracepoints} at the @value{GDBN} prompt to see a list of
3798 commands in this category.
3799
3800 @findex COMMAND_USER
3801 @findex gdb.COMMAND_USER
3802 @item gdb.COMMAND_USER
3803 The command is a general purpose command for the user, and typically
3804 does not fit in one of the other categories.
3805 Type @kbd{help user-defined} at the @value{GDBN} prompt to see
3806 a list of commands in this category, as well as the list of gdb macros
3807 (@pxref{Sequences}).
3808
3809 @findex COMMAND_OBSCURE
3810 @findex gdb.COMMAND_OBSCURE
3811 @item gdb.COMMAND_OBSCURE
3812 The command is only used in unusual circumstances, or is not of
3813 general interest to users. For example, @code{checkpoint},
3814 @code{fork}, and @code{stop} are in this category. Type @kbd{help
3815 obscure} at the @value{GDBN} prompt to see a list of commands in this
3816 category.
3817
3818 @findex COMMAND_MAINTENANCE
3819 @findex gdb.COMMAND_MAINTENANCE
3820 @item gdb.COMMAND_MAINTENANCE
3821 The command is only useful to @value{GDBN} maintainers. The
3822 @code{maintenance} and @code{flushregs} commands are in this category.
3823 Type @kbd{help internals} at the @value{GDBN} prompt to see a list of
3824 commands in this category.
3825 @end table
3826
3827 A new command can use a predefined completion function, either by
3828 specifying it via an argument at initialization, or by returning it
3829 from the @code{complete} method. These predefined completion
3830 constants are all defined in the @code{gdb} module:
3831
3832 @vtable @code
3833 @vindex COMPLETE_NONE
3834 @item gdb.COMPLETE_NONE
3835 This constant means that no completion should be done.
3836
3837 @vindex COMPLETE_FILENAME
3838 @item gdb.COMPLETE_FILENAME
3839 This constant means that filename completion should be performed.
3840
3841 @vindex COMPLETE_LOCATION
3842 @item gdb.COMPLETE_LOCATION
3843 This constant means that location completion should be done.
3844 @xref{Specify Location}.
3845
3846 @vindex COMPLETE_COMMAND
3847 @item gdb.COMPLETE_COMMAND
3848 This constant means that completion should examine @value{GDBN}
3849 command names.
3850
3851 @vindex COMPLETE_SYMBOL
3852 @item gdb.COMPLETE_SYMBOL
3853 This constant means that completion should be done using symbol names
3854 as the source.
3855
3856 @vindex COMPLETE_EXPRESSION
3857 @item gdb.COMPLETE_EXPRESSION
3858 This constant means that completion should be done on expressions.
3859 Often this means completing on symbol names, but some language
3860 parsers also have support for completing on field names.
3861 @end vtable
3862
3863 The following code snippet shows how a trivial CLI command can be
3864 implemented in Python:
3865
3866 @smallexample
3867 class HelloWorld (gdb.Command):
3868 """Greet the whole world."""
3869
3870 def __init__ (self):
3871 super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
3872
3873 def invoke (self, arg, from_tty):
3874 print "Hello, World!"
3875
3876 HelloWorld ()
3877 @end smallexample
3878
3879 The last line instantiates the class, and is necessary to trigger the
3880 registration of the command with @value{GDBN}. Depending on how the
3881 Python code is read into @value{GDBN}, you may need to import the
3882 @code{gdb} module explicitly.
3883
3884 @node Parameters In Python
3885 @subsubsection Parameters In Python
3886
3887 @cindex parameters in python
3888 @cindex python parameters
3889 @tindex gdb.Parameter
3890 @tindex Parameter
3891 You can implement new @value{GDBN} parameters using Python. A new
3892 parameter is implemented as an instance of the @code{gdb.Parameter}
3893 class.
3894
3895 Parameters are exposed to the user via the @code{set} and
3896 @code{show} commands. @xref{Help}.
3897
3898 There are many parameters that already exist and can be set in
3899 @value{GDBN}. Two examples are: @code{set follow fork} and
3900 @code{set charset}. Setting these parameters influences certain
3901 behavior in @value{GDBN}. Similarly, you can define parameters that
3902 can be used to influence behavior in custom Python scripts and commands.
3903
3904 @defun Parameter.__init__ (name, @var{command-class}, @var{parameter-class} @r{[}, @var{enum-sequence}@r{]})
3905 The object initializer for @code{Parameter} registers the new
3906 parameter with @value{GDBN}. This initializer is normally invoked
3907 from the subclass' own @code{__init__} method.
3908
3909 @var{name} is the name of the new parameter. If @var{name} consists
3910 of multiple words, then the initial words are looked for as prefix
3911 parameters. An example of this can be illustrated with the
3912 @code{set print} set of parameters. If @var{name} is
3913 @code{print foo}, then @code{print} will be searched as the prefix
3914 parameter. In this case the parameter can subsequently be accessed in
3915 @value{GDBN} as @code{set print foo}.
3916
3917 If @var{name} consists of multiple words, and no prefix parameter group
3918 can be found, an exception is raised.
3919
3920 @var{command-class} should be one of the @samp{COMMAND_} constants
3921 (@pxref{Commands In Python}). This argument tells @value{GDBN} how to
3922 categorize the new parameter in the help system.
3923
3924 @var{parameter-class} should be one of the @samp{PARAM_} constants
3925 defined below. This argument tells @value{GDBN} the type of the new
3926 parameter; this information is used for input validation and
3927 completion.
3928
3929 If @var{parameter-class} is @code{PARAM_ENUM}, then
3930 @var{enum-sequence} must be a sequence of strings. These strings
3931 represent the possible values for the parameter.
3932
3933 If @var{parameter-class} is not @code{PARAM_ENUM}, then the presence
3934 of a fourth argument will cause an exception to be thrown.
3935
3936 The help text for the new parameter is taken from the Python
3937 documentation string for the parameter's class, if there is one. If
3938 there is no documentation string, a default value is used.
3939 @end defun
3940
3941 @defvar Parameter.set_doc
3942 If this attribute exists, and is a string, then its value is used as
3943 the help text for this parameter's @code{set} command. The value is
3944 examined when @code{Parameter.__init__} is invoked; subsequent changes
3945 have no effect.
3946 @end defvar
3947
3948 @defvar Parameter.show_doc
3949 If this attribute exists, and is a string, then its value is used as
3950 the help text for this parameter's @code{show} command. The value is
3951 examined when @code{Parameter.__init__} is invoked; subsequent changes
3952 have no effect.
3953 @end defvar
3954
3955 @defvar Parameter.value
3956 The @code{value} attribute holds the underlying value of the
3957 parameter. It can be read and assigned to just as any other
3958 attribute. @value{GDBN} does validation when assignments are made.
3959 @end defvar
3960
3961 There are two methods that may be implemented in any @code{Parameter}
3962 class. These are:
3963
3964 @defun Parameter.get_set_string (self)
3965 If this method exists, @value{GDBN} will call it when a
3966 @var{parameter}'s value has been changed via the @code{set} API (for
3967 example, @kbd{set foo off}). The @code{value} attribute has already
3968 been populated with the new value and may be used in output. This
3969 method must return a string. If the returned string is not empty,
3970 @value{GDBN} will present it to the user.
3971
3972 If this method raises the @code{gdb.GdbError} exception
3973 (@pxref{Exception Handling}), then @value{GDBN} will print the
3974 exception's string and the @code{set} command will fail. Note,
3975 however, that the @code{value} attribute will not be reset in this
3976 case. So, if your parameter must validate values, it should store the
3977 old value internally and reset the exposed value, like so:
3978
3979 @smallexample
3980 class ExampleParam (gdb.Parameter):
3981 def __init__ (self, name):
3982 super (ExampleParam, self).__init__ (name,
3983 gdb.COMMAND_DATA,
3984 gdb.PARAM_BOOLEAN)
3985 self.value = True
3986 self.saved_value = True
3987 def validate(self):
3988 return False
3989 def get_set_string (self):
3990 if not self.validate():
3991 self.value = self.saved_value
3992 raise gdb.GdbError('Failed to validate')
3993 self.saved_value = self.value
3994 @end smallexample
3995 @end defun
3996
3997 @defun Parameter.get_show_string (self, svalue)
3998 @value{GDBN} will call this method when a @var{parameter}'s
3999 @code{show} API has been invoked (for example, @kbd{show foo}). The
4000 argument @code{svalue} receives the string representation of the
4001 current value. This method must return a string.
4002 @end defun
4003
4004 When a new parameter is defined, its type must be specified. The
4005 available types are represented by constants defined in the @code{gdb}
4006 module:
4007
4008 @table @code
4009 @findex PARAM_BOOLEAN
4010 @findex gdb.PARAM_BOOLEAN
4011 @item gdb.PARAM_BOOLEAN
4012 The value is a plain boolean. The Python boolean values, @code{True}
4013 and @code{False} are the only valid values.
4014
4015 @findex PARAM_AUTO_BOOLEAN
4016 @findex gdb.PARAM_AUTO_BOOLEAN
4017 @item gdb.PARAM_AUTO_BOOLEAN
4018 The value has three possible states: true, false, and @samp{auto}. In
4019 Python, true and false are represented using boolean constants, and
4020 @samp{auto} is represented using @code{None}.
4021
4022 @findex PARAM_UINTEGER
4023 @findex gdb.PARAM_UINTEGER
4024 @item gdb.PARAM_UINTEGER
4025 The value is an unsigned integer. The value of 0 should be
4026 interpreted to mean ``unlimited''.
4027
4028 @findex PARAM_INTEGER
4029 @findex gdb.PARAM_INTEGER
4030 @item gdb.PARAM_INTEGER
4031 The value is a signed integer. The value of 0 should be interpreted
4032 to mean ``unlimited''.
4033
4034 @findex PARAM_STRING
4035 @findex gdb.PARAM_STRING
4036 @item gdb.PARAM_STRING
4037 The value is a string. When the user modifies the string, any escape
4038 sequences, such as @samp{\t}, @samp{\f}, and octal escapes, are
4039 translated into corresponding characters and encoded into the current
4040 host charset.
4041
4042 @findex PARAM_STRING_NOESCAPE
4043 @findex gdb.PARAM_STRING_NOESCAPE
4044 @item gdb.PARAM_STRING_NOESCAPE
4045 The value is a string. When the user modifies the string, escapes are
4046 passed through untranslated.
4047
4048 @findex PARAM_OPTIONAL_FILENAME
4049 @findex gdb.PARAM_OPTIONAL_FILENAME
4050 @item gdb.PARAM_OPTIONAL_FILENAME
4051 The value is a either a filename (a string), or @code{None}.
4052
4053 @findex PARAM_FILENAME
4054 @findex gdb.PARAM_FILENAME
4055 @item gdb.PARAM_FILENAME
4056 The value is a filename. This is just like
4057 @code{PARAM_STRING_NOESCAPE}, but uses file names for completion.
4058
4059 @findex PARAM_ZINTEGER
4060 @findex gdb.PARAM_ZINTEGER
4061 @item gdb.PARAM_ZINTEGER
4062 The value is an integer. This is like @code{PARAM_INTEGER}, except 0
4063 is interpreted as itself.
4064
4065 @findex PARAM_ZUINTEGER
4066 @findex gdb.PARAM_ZUINTEGER
4067 @item gdb.PARAM_ZUINTEGER
4068 The value is an unsigned integer. This is like @code{PARAM_INTEGER},
4069 except 0 is interpreted as itself, and the value cannot be negative.
4070
4071 @findex PARAM_ZUINTEGER_UNLIMITED
4072 @findex gdb.PARAM_ZUINTEGER_UNLIMITED
4073 @item gdb.PARAM_ZUINTEGER_UNLIMITED
4074 The value is a signed integer. This is like @code{PARAM_ZUINTEGER},
4075 except the special value -1 should be interpreted to mean
4076 ``unlimited''. Other negative values are not allowed.
4077
4078 @findex PARAM_ENUM
4079 @findex gdb.PARAM_ENUM
4080 @item gdb.PARAM_ENUM
4081 The value is a string, which must be one of a collection string
4082 constants provided when the parameter is created.
4083 @end table
4084
4085 @node Functions In Python
4086 @subsubsection Writing new convenience functions
4087
4088 @cindex writing convenience functions
4089 @cindex convenience functions in python
4090 @cindex python convenience functions
4091 @tindex gdb.Function
4092 @tindex Function
4093 You can implement new convenience functions (@pxref{Convenience Vars})
4094 in Python. A convenience function is an instance of a subclass of the
4095 class @code{gdb.Function}.
4096
4097 @defun Function.__init__ (name)
4098 The initializer for @code{Function} registers the new function with
4099 @value{GDBN}. The argument @var{name} is the name of the function,
4100 a string. The function will be visible to the user as a convenience
4101 variable of type @code{internal function}, whose name is the same as
4102 the given @var{name}.
4103
4104 The documentation for the new function is taken from the documentation
4105 string for the new class.
4106 @end defun
4107
4108 @defun Function.invoke (@var{*args})
4109 When a convenience function is evaluated, its arguments are converted
4110 to instances of @code{gdb.Value}, and then the function's
4111 @code{invoke} method is called. Note that @value{GDBN} does not
4112 predetermine the arity of convenience functions. Instead, all
4113 available arguments are passed to @code{invoke}, following the
4114 standard Python calling convention. In particular, a convenience
4115 function can have default values for parameters without ill effect.
4116
4117 The return value of this method is used as its value in the enclosing
4118 expression. If an ordinary Python value is returned, it is converted
4119 to a @code{gdb.Value} following the usual rules.
4120 @end defun
4121
4122 The following code snippet shows how a trivial convenience function can
4123 be implemented in Python:
4124
4125 @smallexample
4126 class Greet (gdb.Function):
4127 """Return string to greet someone.
4128 Takes a name as argument."""
4129
4130 def __init__ (self):
4131 super (Greet, self).__init__ ("greet")
4132
4133 def invoke (self, name):
4134 return "Hello, %s!" % name.string ()
4135
4136 Greet ()
4137 @end smallexample
4138
4139 The last line instantiates the class, and is necessary to trigger the
4140 registration of the function with @value{GDBN}. Depending on how the
4141 Python code is read into @value{GDBN}, you may need to import the
4142 @code{gdb} module explicitly.
4143
4144 Now you can use the function in an expression:
4145
4146 @smallexample
4147 (gdb) print $greet("Bob")
4148 $1 = "Hello, Bob!"
4149 @end smallexample
4150
4151 @node Progspaces In Python
4152 @subsubsection Program Spaces In Python
4153
4154 @cindex progspaces in python
4155 @tindex gdb.Progspace
4156 @tindex Progspace
4157 A program space, or @dfn{progspace}, represents a symbolic view
4158 of an address space.
4159 It consists of all of the objfiles of the program.
4160 @xref{Objfiles In Python}.
4161 @xref{Inferiors and Programs, program spaces}, for more details
4162 about program spaces.
4163
4164 The following progspace-related functions are available in the
4165 @code{gdb} module:
4166
4167 @findex gdb.current_progspace
4168 @defun gdb.current_progspace ()
4169 This function returns the program space of the currently selected inferior.
4170 @xref{Inferiors and Programs}. This is identical to
4171 @code{gdb.selected_inferior().progspace} (@pxref{Inferiors In Python}) and is
4172 included for historical compatibility.
4173 @end defun
4174
4175 @findex gdb.progspaces
4176 @defun gdb.progspaces ()
4177 Return a sequence of all the progspaces currently known to @value{GDBN}.
4178 @end defun
4179
4180 Each progspace is represented by an instance of the @code{gdb.Progspace}
4181 class.
4182
4183 @defvar Progspace.filename
4184 The file name of the progspace as a string.
4185 @end defvar
4186
4187 @defvar Progspace.pretty_printers
4188 The @code{pretty_printers} attribute is a list of functions. It is
4189 used to look up pretty-printers. A @code{Value} is passed to each
4190 function in order; if the function returns @code{None}, then the
4191 search continues. Otherwise, the return value should be an object
4192 which is used to format the value. @xref{Pretty Printing API}, for more
4193 information.
4194 @end defvar
4195
4196 @defvar Progspace.type_printers
4197 The @code{type_printers} attribute is a list of type printer objects.
4198 @xref{Type Printing API}, for more information.
4199 @end defvar
4200
4201 @defvar Progspace.frame_filters
4202 The @code{frame_filters} attribute is a dictionary of frame filter
4203 objects. @xref{Frame Filter API}, for more information.
4204 @end defvar
4205
4206 A program space has the following methods:
4207
4208 @findex Progspace.block_for_pc
4209 @defun Progspace.block_for_pc (pc)
4210 Return the innermost @code{gdb.Block} containing the given @var{pc}
4211 value. If the block cannot be found for the @var{pc} value specified,
4212 the function will return @code{None}.
4213 @end defun
4214
4215 @findex Progspace.find_pc_line
4216 @defun Progspace.find_pc_line (pc)
4217 Return the @code{gdb.Symtab_and_line} object corresponding to the
4218 @var{pc} value. @xref{Symbol Tables In Python}. If an invalid value
4219 of @var{pc} is passed as an argument, then the @code{symtab} and
4220 @code{line} attributes of the returned @code{gdb.Symtab_and_line}
4221 object will be @code{None} and 0 respectively.
4222 @end defun
4223
4224 @findex Progspace.is_valid
4225 @defun Progspace.is_valid ()
4226 Returns @code{True} if the @code{gdb.Progspace} object is valid,
4227 @code{False} if not. A @code{gdb.Progspace} object can become invalid
4228 if the program space file it refers to is not referenced by any
4229 inferior. All other @code{gdb.Progspace} methods will throw an
4230 exception if it is invalid at the time the method is called.
4231 @end defun
4232
4233 @findex Progspace.objfiles
4234 @defun Progspace.objfiles ()
4235 Return a sequence of all the objfiles referenced by this program
4236 space. @xref{Objfiles In Python}.
4237 @end defun
4238
4239 @findex Progspace.solib_name
4240 @defun Progspace.solib_name (address)
4241 Return the name of the shared library holding the given @var{address}
4242 as a string, or @code{None}.
4243 @end defun
4244
4245 One may add arbitrary attributes to @code{gdb.Progspace} objects
4246 in the usual Python way.
4247 This is useful if, for example, one needs to do some extra record keeping
4248 associated with the program space.
4249
4250 In this contrived example, we want to perform some processing when
4251 an objfile with a certain symbol is loaded, but we only want to do
4252 this once because it is expensive. To achieve this we record the results
4253 with the program space because we can't predict when the desired objfile
4254 will be loaded.
4255
4256 @smallexample
4257 (gdb) python
4258 def clear_objfiles_handler(event):
4259 event.progspace.expensive_computation = None
4260 def expensive(symbol):
4261 """A mock routine to perform an "expensive" computation on symbol."""
4262 print "Computing the answer to the ultimate question ..."
4263 return 42
4264 def new_objfile_handler(event):
4265 objfile = event.new_objfile
4266 progspace = objfile.progspace
4267 if not hasattr(progspace, 'expensive_computation') or \
4268 progspace.expensive_computation is None:
4269 # We use 'main' for the symbol to keep the example simple.
4270 # Note: There's no current way to constrain the lookup
4271 # to one objfile.
4272 symbol = gdb.lookup_global_symbol('main')
4273 if symbol is not None:
4274 progspace.expensive_computation = expensive(symbol)
4275 gdb.events.clear_objfiles.connect(clear_objfiles_handler)
4276 gdb.events.new_objfile.connect(new_objfile_handler)
4277 end
4278 (gdb) file /tmp/hello
4279 Reading symbols from /tmp/hello...done.
4280 Computing the answer to the ultimate question ...
4281 (gdb) python print gdb.current_progspace().expensive_computation
4282 42
4283 (gdb) run
4284 Starting program: /tmp/hello
4285 Hello.
4286 [Inferior 1 (process 4242) exited normally]
4287 @end smallexample
4288
4289 @node Objfiles In Python
4290 @subsubsection Objfiles In Python
4291
4292 @cindex objfiles in python
4293 @tindex gdb.Objfile
4294 @tindex Objfile
4295 @value{GDBN} loads symbols for an inferior from various
4296 symbol-containing files (@pxref{Files}). These include the primary
4297 executable file, any shared libraries used by the inferior, and any
4298 separate debug info files (@pxref{Separate Debug Files}).
4299 @value{GDBN} calls these symbol-containing files @dfn{objfiles}.
4300
4301 The following objfile-related functions are available in the
4302 @code{gdb} module:
4303
4304 @findex gdb.current_objfile
4305 @defun gdb.current_objfile ()
4306 When auto-loading a Python script (@pxref{Python Auto-loading}), @value{GDBN}
4307 sets the ``current objfile'' to the corresponding objfile. This
4308 function returns the current objfile. If there is no current objfile,
4309 this function returns @code{None}.
4310 @end defun
4311
4312 @findex gdb.objfiles
4313 @defun gdb.objfiles ()
4314 Return a sequence of objfiles referenced by the current program space.
4315 @xref{Objfiles In Python}, and @ref{Progspaces In Python}. This is identical
4316 to @code{gdb.selected_inferior().progspace.objfiles()} and is included for
4317 historical compatibility.
4318 @end defun
4319
4320 @findex gdb.lookup_objfile
4321 @defun gdb.lookup_objfile (name @r{[}, by_build_id{]})
4322 Look up @var{name}, a file name or build ID, in the list of objfiles
4323 for the current program space (@pxref{Progspaces In Python}).
4324 If the objfile is not found throw the Python @code{ValueError} exception.
4325
4326 If @var{name} is a relative file name, then it will match any
4327 source file name with the same trailing components. For example, if
4328 @var{name} is @samp{gcc/expr.c}, then it will match source file
4329 name of @file{/build/trunk/gcc/expr.c}, but not
4330 @file{/build/trunk/libcpp/expr.c} or @file{/build/trunk/gcc/x-expr.c}.
4331
4332 If @var{by_build_id} is provided and is @code{True} then @var{name}
4333 is the build ID of the objfile. Otherwise, @var{name} is a file name.
4334 This is supported only on some operating systems, notably those which use
4335 the ELF format for binary files and the @sc{gnu} Binutils. For more details
4336 about this feature, see the description of the @option{--build-id}
4337 command-line option in @ref{Options, , Command Line Options, ld,
4338 The GNU Linker}.
4339 @end defun
4340
4341 Each objfile is represented by an instance of the @code{gdb.Objfile}
4342 class.
4343
4344 @defvar Objfile.filename
4345 The file name of the objfile as a string, with symbolic links resolved.
4346
4347 The value is @code{None} if the objfile is no longer valid.
4348 See the @code{gdb.Objfile.is_valid} method, described below.
4349 @end defvar
4350
4351 @defvar Objfile.username
4352 The file name of the objfile as specified by the user as a string.
4353
4354 The value is @code{None} if the objfile is no longer valid.
4355 See the @code{gdb.Objfile.is_valid} method, described below.
4356 @end defvar
4357
4358 @defvar Objfile.owner
4359 For separate debug info objfiles this is the corresponding @code{gdb.Objfile}
4360 object that debug info is being provided for.
4361 Otherwise this is @code{None}.
4362 Separate debug info objfiles are added with the
4363 @code{gdb.Objfile.add_separate_debug_file} method, described below.
4364 @end defvar
4365
4366 @defvar Objfile.build_id
4367 The build ID of the objfile as a string.
4368 If the objfile does not have a build ID then the value is @code{None}.
4369
4370 This is supported only on some operating systems, notably those which use
4371 the ELF format for binary files and the @sc{gnu} Binutils. For more details
4372 about this feature, see the description of the @option{--build-id}
4373 command-line option in @ref{Options, , Command Line Options, ld,
4374 The GNU Linker}.
4375 @end defvar
4376
4377 @defvar Objfile.progspace
4378 The containing program space of the objfile as a @code{gdb.Progspace}
4379 object. @xref{Progspaces In Python}.
4380 @end defvar
4381
4382 @defvar Objfile.pretty_printers
4383 The @code{pretty_printers} attribute is a list of functions. It is
4384 used to look up pretty-printers. A @code{Value} is passed to each
4385 function in order; if the function returns @code{None}, then the
4386 search continues. Otherwise, the return value should be an object
4387 which is used to format the value. @xref{Pretty Printing API}, for more
4388 information.
4389 @end defvar
4390
4391 @defvar Objfile.type_printers
4392 The @code{type_printers} attribute is a list of type printer objects.
4393 @xref{Type Printing API}, for more information.
4394 @end defvar
4395
4396 @defvar Objfile.frame_filters
4397 The @code{frame_filters} attribute is a dictionary of frame filter
4398 objects. @xref{Frame Filter API}, for more information.
4399 @end defvar
4400
4401 One may add arbitrary attributes to @code{gdb.Objfile} objects
4402 in the usual Python way.
4403 This is useful if, for example, one needs to do some extra record keeping
4404 associated with the objfile.
4405
4406 In this contrived example we record the time when @value{GDBN}
4407 loaded the objfile.
4408
4409 @smallexample
4410 (gdb) python
4411 import datetime
4412 def new_objfile_handler(event):
4413 # Set the time_loaded attribute of the new objfile.
4414 event.new_objfile.time_loaded = datetime.datetime.today()
4415 gdb.events.new_objfile.connect(new_objfile_handler)
4416 end
4417 (gdb) file ./hello
4418 Reading symbols from ./hello...done.
4419 (gdb) python print gdb.objfiles()[0].time_loaded
4420 2014-10-09 11:41:36.770345
4421 @end smallexample
4422
4423 A @code{gdb.Objfile} object has the following methods:
4424
4425 @defun Objfile.is_valid ()
4426 Returns @code{True} if the @code{gdb.Objfile} object is valid,
4427 @code{False} if not. A @code{gdb.Objfile} object can become invalid
4428 if the object file it refers to is not loaded in @value{GDBN} any
4429 longer. All other @code{gdb.Objfile} methods will throw an exception
4430 if it is invalid at the time the method is called.
4431 @end defun
4432
4433 @defun Objfile.add_separate_debug_file (file)
4434 Add @var{file} to the list of files that @value{GDBN} will search for
4435 debug information for the objfile.
4436 This is useful when the debug info has been removed from the program
4437 and stored in a separate file. @value{GDBN} has built-in support for
4438 finding separate debug info files (@pxref{Separate Debug Files}), but if
4439 the file doesn't live in one of the standard places that @value{GDBN}
4440 searches then this function can be used to add a debug info file
4441 from a different place.
4442 @end defun
4443
4444 @defun Objfile.lookup_global_symbol (name @r{[}, domain@r{]})
4445 Search for a global symbol named @var{name} in this objfile. Optionally, the
4446 search scope can be restricted with the @var{domain} argument.
4447 The @var{domain} argument must be a domain constant defined in the @code{gdb}
4448 module and described in @ref{Symbols In Python}. This function is similar to
4449 @code{gdb.lookup_global_symbol}, except that the search is limited to this
4450 objfile.
4451
4452 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
4453 is not found.
4454 @end defun
4455
4456 @defun Objfile.lookup_static_symbol (name @r{[}, domain@r{]})
4457 Like @code{Objfile.lookup_global_symbol}, but searches for a global
4458 symbol with static linkage named @var{name} in this objfile.
4459 @end defun
4460
4461 @node Frames In Python
4462 @subsubsection Accessing inferior stack frames from Python
4463
4464 @cindex frames in python
4465 When the debugged program stops, @value{GDBN} is able to analyze its call
4466 stack (@pxref{Frames,,Stack frames}). The @code{gdb.Frame} class
4467 represents a frame in the stack. A @code{gdb.Frame} object is only valid
4468 while its corresponding frame exists in the inferior's stack. If you try
4469 to use an invalid frame object, @value{GDBN} will throw a @code{gdb.error}
4470 exception (@pxref{Exception Handling}).
4471
4472 Two @code{gdb.Frame} objects can be compared for equality with the @code{==}
4473 operator, like:
4474
4475 @smallexample
4476 (@value{GDBP}) python print gdb.newest_frame() == gdb.selected_frame ()
4477 True
4478 @end smallexample
4479
4480 The following frame-related functions are available in the @code{gdb} module:
4481
4482 @findex gdb.selected_frame
4483 @defun gdb.selected_frame ()
4484 Return the selected frame object. (@pxref{Selection,,Selecting a Frame}).
4485 @end defun
4486
4487 @findex gdb.newest_frame
4488 @defun gdb.newest_frame ()
4489 Return the newest frame object for the selected thread.
4490 @end defun
4491
4492 @defun gdb.frame_stop_reason_string (reason)
4493 Return a string explaining the reason why @value{GDBN} stopped unwinding
4494 frames, as expressed by the given @var{reason} code (an integer, see the
4495 @code{unwind_stop_reason} method further down in this section).
4496 @end defun
4497
4498 @findex gdb.invalidate_cached_frames
4499 @defun gdb.invalidate_cached_frames
4500 @value{GDBN} internally keeps a cache of the frames that have been
4501 unwound. This function invalidates this cache.
4502
4503 This function should not generally be called by ordinary Python code.
4504 It is documented for the sake of completeness.
4505 @end defun
4506
4507 A @code{gdb.Frame} object has the following methods:
4508
4509 @defun Frame.is_valid ()
4510 Returns true if the @code{gdb.Frame} object is valid, false if not.
4511 A frame object can become invalid if the frame it refers to doesn't
4512 exist anymore in the inferior. All @code{gdb.Frame} methods will throw
4513 an exception if it is invalid at the time the method is called.
4514 @end defun
4515
4516 @defun Frame.name ()
4517 Returns the function name of the frame, or @code{None} if it can't be
4518 obtained.
4519 @end defun
4520
4521 @defun Frame.architecture ()
4522 Returns the @code{gdb.Architecture} object corresponding to the frame's
4523 architecture. @xref{Architectures In Python}.
4524 @end defun
4525
4526 @defun Frame.type ()
4527 Returns the type of the frame. The value can be one of:
4528 @table @code
4529 @item gdb.NORMAL_FRAME
4530 An ordinary stack frame.
4531
4532 @item gdb.DUMMY_FRAME
4533 A fake stack frame that was created by @value{GDBN} when performing an
4534 inferior function call.
4535
4536 @item gdb.INLINE_FRAME
4537 A frame representing an inlined function. The function was inlined
4538 into a @code{gdb.NORMAL_FRAME} that is older than this one.
4539
4540 @item gdb.TAILCALL_FRAME
4541 A frame representing a tail call. @xref{Tail Call Frames}.
4542
4543 @item gdb.SIGTRAMP_FRAME
4544 A signal trampoline frame. This is the frame created by the OS when
4545 it calls into a signal handler.
4546
4547 @item gdb.ARCH_FRAME
4548 A fake stack frame representing a cross-architecture call.
4549
4550 @item gdb.SENTINEL_FRAME
4551 This is like @code{gdb.NORMAL_FRAME}, but it is only used for the
4552 newest frame.
4553 @end table
4554 @end defun
4555
4556 @defun Frame.unwind_stop_reason ()
4557 Return an integer representing the reason why it's not possible to find
4558 more frames toward the outermost frame. Use
4559 @code{gdb.frame_stop_reason_string} to convert the value returned by this
4560 function to a string. The value can be one of:
4561
4562 @table @code
4563 @item gdb.FRAME_UNWIND_NO_REASON
4564 No particular reason (older frames should be available).
4565
4566 @item gdb.FRAME_UNWIND_NULL_ID
4567 The previous frame's analyzer returns an invalid result. This is no
4568 longer used by @value{GDBN}, and is kept only for backward
4569 compatibility.
4570
4571 @item gdb.FRAME_UNWIND_OUTERMOST
4572 This frame is the outermost.
4573
4574 @item gdb.FRAME_UNWIND_UNAVAILABLE
4575 Cannot unwind further, because that would require knowing the
4576 values of registers or memory that have not been collected.
4577
4578 @item gdb.FRAME_UNWIND_INNER_ID
4579 This frame ID looks like it ought to belong to a NEXT frame,
4580 but we got it for a PREV frame. Normally, this is a sign of
4581 unwinder failure. It could also indicate stack corruption.
4582
4583 @item gdb.FRAME_UNWIND_SAME_ID
4584 This frame has the same ID as the previous one. That means
4585 that unwinding further would almost certainly give us another
4586 frame with exactly the same ID, so break the chain. Normally,
4587 this is a sign of unwinder failure. It could also indicate
4588 stack corruption.
4589
4590 @item gdb.FRAME_UNWIND_NO_SAVED_PC
4591 The frame unwinder did not find any saved PC, but we needed
4592 one to unwind further.
4593
4594 @item gdb.FRAME_UNWIND_MEMORY_ERROR
4595 The frame unwinder caused an error while trying to access memory.
4596
4597 @item gdb.FRAME_UNWIND_FIRST_ERROR
4598 Any stop reason greater or equal to this value indicates some kind
4599 of error. This special value facilitates writing code that tests
4600 for errors in unwinding in a way that will work correctly even if
4601 the list of the other values is modified in future @value{GDBN}
4602 versions. Using it, you could write:
4603 @smallexample
4604 reason = gdb.selected_frame().unwind_stop_reason ()
4605 reason_str = gdb.frame_stop_reason_string (reason)
4606 if reason >= gdb.FRAME_UNWIND_FIRST_ERROR:
4607 print "An error occured: %s" % reason_str
4608 @end smallexample
4609 @end table
4610
4611 @end defun
4612
4613 @defun Frame.pc ()
4614 Returns the frame's resume address.
4615 @end defun
4616
4617 @defun Frame.block ()
4618 Return the frame's code block. @xref{Blocks In Python}. If the frame
4619 does not have a block -- for example, if there is no debugging
4620 information for the code in question -- then this will throw an
4621 exception.
4622 @end defun
4623
4624 @defun Frame.function ()
4625 Return the symbol for the function corresponding to this frame.
4626 @xref{Symbols In Python}.
4627 @end defun
4628
4629 @defun Frame.older ()
4630 Return the frame that called this frame.
4631 @end defun
4632
4633 @defun Frame.newer ()
4634 Return the frame called by this frame.
4635 @end defun
4636
4637 @defun Frame.find_sal ()
4638 Return the frame's symtab and line object.
4639 @xref{Symbol Tables In Python}.
4640 @end defun
4641
4642 @defun Frame.read_register (register)
4643 Return the value of @var{register} in this frame. The @var{register}
4644 argument must be a string (e.g., @code{'sp'} or @code{'rax'}).
4645 Returns a @code{Gdb.Value} object. Throws an exception if @var{register}
4646 does not exist.
4647 @end defun
4648
4649 @defun Frame.read_var (variable @r{[}, block@r{]})
4650 Return the value of @var{variable} in this frame. If the optional
4651 argument @var{block} is provided, search for the variable from that
4652 block; otherwise start at the frame's current block (which is
4653 determined by the frame's current program counter). The @var{variable}
4654 argument must be a string or a @code{gdb.Symbol} object; @var{block} must be a
4655 @code{gdb.Block} object.
4656 @end defun
4657
4658 @defun Frame.select ()
4659 Set this frame to be the selected frame. @xref{Stack, ,Examining the
4660 Stack}.
4661 @end defun
4662
4663 @node Blocks In Python
4664 @subsubsection Accessing blocks from Python
4665
4666 @cindex blocks in python
4667 @tindex gdb.Block
4668
4669 In @value{GDBN}, symbols are stored in blocks. A block corresponds
4670 roughly to a scope in the source code. Blocks are organized
4671 hierarchically, and are represented individually in Python as a
4672 @code{gdb.Block}. Blocks rely on debugging information being
4673 available.
4674
4675 A frame has a block. Please see @ref{Frames In Python}, for a more
4676 in-depth discussion of frames.
4677
4678 The outermost block is known as the @dfn{global block}. The global
4679 block typically holds public global variables and functions.
4680
4681 The block nested just inside the global block is the @dfn{static
4682 block}. The static block typically holds file-scoped variables and
4683 functions.
4684
4685 @value{GDBN} provides a method to get a block's superblock, but there
4686 is currently no way to examine the sub-blocks of a block, or to
4687 iterate over all the blocks in a symbol table (@pxref{Symbol Tables In
4688 Python}).
4689
4690 Here is a short example that should help explain blocks:
4691
4692 @smallexample
4693 /* This is in the global block. */
4694 int global;
4695
4696 /* This is in the static block. */
4697 static int file_scope;
4698
4699 /* 'function' is in the global block, and 'argument' is
4700 in a block nested inside of 'function'. */
4701 int function (int argument)
4702 @{
4703 /* 'local' is in a block inside 'function'. It may or may
4704 not be in the same block as 'argument'. */
4705 int local;
4706
4707 @{
4708 /* 'inner' is in a block whose superblock is the one holding
4709 'local'. */
4710 int inner;
4711
4712 /* If this call is expanded by the compiler, you may see
4713 a nested block here whose function is 'inline_function'
4714 and whose superblock is the one holding 'inner'. */
4715 inline_function ();
4716 @}
4717 @}
4718 @end smallexample
4719
4720 A @code{gdb.Block} is iterable. The iterator returns the symbols
4721 (@pxref{Symbols In Python}) local to the block. Python programs
4722 should not assume that a specific block object will always contain a
4723 given symbol, since changes in @value{GDBN} features and
4724 infrastructure may cause symbols move across blocks in a symbol
4725 table. You can also use Python's @dfn{dictionary syntax} to access
4726 variables in this block, e.g.:
4727
4728 @smallexample
4729 symbol = some_block['variable'] # symbol is of type gdb.Symbol
4730 @end smallexample
4731
4732 The following block-related functions are available in the @code{gdb}
4733 module:
4734
4735 @findex gdb.block_for_pc
4736 @defun gdb.block_for_pc (pc)
4737 Return the innermost @code{gdb.Block} containing the given @var{pc}
4738 value. If the block cannot be found for the @var{pc} value specified,
4739 the function will return @code{None}. This is identical to
4740 @code{gdb.current_progspace().block_for_pc(pc)} and is included for
4741 historical compatibility.
4742 @end defun
4743
4744 A @code{gdb.Block} object has the following methods:
4745
4746 @defun Block.is_valid ()
4747 Returns @code{True} if the @code{gdb.Block} object is valid,
4748 @code{False} if not. A block object can become invalid if the block it
4749 refers to doesn't exist anymore in the inferior. All other
4750 @code{gdb.Block} methods will throw an exception if it is invalid at
4751 the time the method is called. The block's validity is also checked
4752 during iteration over symbols of the block.
4753 @end defun
4754
4755 A @code{gdb.Block} object has the following attributes:
4756
4757 @defvar Block.start
4758 The start address of the block. This attribute is not writable.
4759 @end defvar
4760
4761 @defvar Block.end
4762 One past the last address that appears in the block. This attribute
4763 is not writable.
4764 @end defvar
4765
4766 @defvar Block.function
4767 The name of the block represented as a @code{gdb.Symbol}. If the
4768 block is not named, then this attribute holds @code{None}. This
4769 attribute is not writable.
4770
4771 For ordinary function blocks, the superblock is the static block.
4772 However, you should note that it is possible for a function block to
4773 have a superblock that is not the static block -- for instance this
4774 happens for an inlined function.
4775 @end defvar
4776
4777 @defvar Block.superblock
4778 The block containing this block. If this parent block does not exist,
4779 this attribute holds @code{None}. This attribute is not writable.
4780 @end defvar
4781
4782 @defvar Block.global_block
4783 The global block associated with this block. This attribute is not
4784 writable.
4785 @end defvar
4786
4787 @defvar Block.static_block
4788 The static block associated with this block. This attribute is not
4789 writable.
4790 @end defvar
4791
4792 @defvar Block.is_global
4793 @code{True} if the @code{gdb.Block} object is a global block,
4794 @code{False} if not. This attribute is not
4795 writable.
4796 @end defvar
4797
4798 @defvar Block.is_static
4799 @code{True} if the @code{gdb.Block} object is a static block,
4800 @code{False} if not. This attribute is not writable.
4801 @end defvar
4802
4803 @node Symbols In Python
4804 @subsubsection Python representation of Symbols
4805
4806 @cindex symbols in python
4807 @tindex gdb.Symbol
4808
4809 @value{GDBN} represents every variable, function and type as an
4810 entry in a symbol table. @xref{Symbols, ,Examining the Symbol Table}.
4811 Similarly, Python represents these symbols in @value{GDBN} with the
4812 @code{gdb.Symbol} object.
4813
4814 The following symbol-related functions are available in the @code{gdb}
4815 module:
4816
4817 @findex gdb.lookup_symbol
4818 @defun gdb.lookup_symbol (name @r{[}, block @r{[}, domain@r{]]})
4819 This function searches for a symbol by name. The search scope can be
4820 restricted to the parameters defined in the optional domain and block
4821 arguments.
4822
4823 @var{name} is the name of the symbol. It must be a string. The
4824 optional @var{block} argument restricts the search to symbols visible
4825 in that @var{block}. The @var{block} argument must be a
4826 @code{gdb.Block} object. If omitted, the block for the current frame
4827 is used. The optional @var{domain} argument restricts
4828 the search to the domain type. The @var{domain} argument must be a
4829 domain constant defined in the @code{gdb} module and described later
4830 in this chapter.
4831
4832 The result is a tuple of two elements.
4833 The first element is a @code{gdb.Symbol} object or @code{None} if the symbol
4834 is not found.
4835 If the symbol is found, the second element is @code{True} if the symbol
4836 is a field of a method's object (e.g., @code{this} in C@t{++}),
4837 otherwise it is @code{False}.
4838 If the symbol is not found, the second element is @code{False}.
4839 @end defun
4840
4841 @findex gdb.lookup_global_symbol
4842 @defun gdb.lookup_global_symbol (name @r{[}, domain@r{]})
4843 This function searches for a global symbol by name.
4844 The search scope can be restricted to by the domain argument.
4845
4846 @var{name} is the name of the symbol. It must be a string.
4847 The optional @var{domain} argument restricts the search to the domain type.
4848 The @var{domain} argument must be a domain constant defined in the @code{gdb}
4849 module and described later in this chapter.
4850
4851 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
4852 is not found.
4853 @end defun
4854
4855 @findex gdb.lookup_static_symbol
4856 @defun gdb.lookup_static_symbol (name @r{[}, domain@r{]})
4857 This function searches for a global symbol with static linkage by name.
4858 The search scope can be restricted to by the domain argument.
4859
4860 @var{name} is the name of the symbol. It must be a string.
4861 The optional @var{domain} argument restricts the search to the domain type.
4862 The @var{domain} argument must be a domain constant defined in the @code{gdb}
4863 module and described later in this chapter.
4864
4865 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
4866 is not found.
4867
4868 Note that this function will not find function-scoped static variables. To look
4869 up such variables, iterate over the variables of the function's
4870 @code{gdb.Block} and check that @code{block.addr_class} is
4871 @code{gdb.SYMBOL_LOC_STATIC}.
4872 @end defun
4873
4874 A @code{gdb.Symbol} object has the following attributes:
4875
4876 @defvar Symbol.type
4877 The type of the symbol or @code{None} if no type is recorded.
4878 This attribute is represented as a @code{gdb.Type} object.
4879 @xref{Types In Python}. This attribute is not writable.
4880 @end defvar
4881
4882 @defvar Symbol.symtab
4883 The symbol table in which the symbol appears. This attribute is
4884 represented as a @code{gdb.Symtab} object. @xref{Symbol Tables In
4885 Python}. This attribute is not writable.
4886 @end defvar
4887
4888 @defvar Symbol.line
4889 The line number in the source code at which the symbol was defined.
4890 This is an integer.
4891 @end defvar
4892
4893 @defvar Symbol.name
4894 The name of the symbol as a string. This attribute is not writable.
4895 @end defvar
4896
4897 @defvar Symbol.linkage_name
4898 The name of the symbol, as used by the linker (i.e., may be mangled).
4899 This attribute is not writable.
4900 @end defvar
4901
4902 @defvar Symbol.print_name
4903 The name of the symbol in a form suitable for output. This is either
4904 @code{name} or @code{linkage_name}, depending on whether the user
4905 asked @value{GDBN} to display demangled or mangled names.
4906 @end defvar
4907
4908 @defvar Symbol.addr_class
4909 The address class of the symbol. This classifies how to find the value
4910 of a symbol. Each address class is a constant defined in the
4911 @code{gdb} module and described later in this chapter.
4912 @end defvar
4913
4914 @defvar Symbol.needs_frame
4915 This is @code{True} if evaluating this symbol's value requires a frame
4916 (@pxref{Frames In Python}) and @code{False} otherwise. Typically,
4917 local variables will require a frame, but other symbols will not.
4918 @end defvar
4919
4920 @defvar Symbol.is_argument
4921 @code{True} if the symbol is an argument of a function.
4922 @end defvar
4923
4924 @defvar Symbol.is_constant
4925 @code{True} if the symbol is a constant.
4926 @end defvar
4927
4928 @defvar Symbol.is_function
4929 @code{True} if the symbol is a function or a method.
4930 @end defvar
4931
4932 @defvar Symbol.is_variable
4933 @code{True} if the symbol is a variable.
4934 @end defvar
4935
4936 A @code{gdb.Symbol} object has the following methods:
4937
4938 @defun Symbol.is_valid ()
4939 Returns @code{True} if the @code{gdb.Symbol} object is valid,
4940 @code{False} if not. A @code{gdb.Symbol} object can become invalid if
4941 the symbol it refers to does not exist in @value{GDBN} any longer.
4942 All other @code{gdb.Symbol} methods will throw an exception if it is
4943 invalid at the time the method is called.
4944 @end defun
4945
4946 @defun Symbol.value (@r{[}frame@r{]})
4947 Compute the value of the symbol, as a @code{gdb.Value}. For
4948 functions, this computes the address of the function, cast to the
4949 appropriate type. If the symbol requires a frame in order to compute
4950 its value, then @var{frame} must be given. If @var{frame} is not
4951 given, or if @var{frame} is invalid, then this method will throw an
4952 exception.
4953 @end defun
4954
4955 The available domain categories in @code{gdb.Symbol} are represented
4956 as constants in the @code{gdb} module:
4957
4958 @vtable @code
4959 @vindex SYMBOL_UNDEF_DOMAIN
4960 @item gdb.SYMBOL_UNDEF_DOMAIN
4961 This is used when a domain has not been discovered or none of the
4962 following domains apply. This usually indicates an error either
4963 in the symbol information or in @value{GDBN}'s handling of symbols.
4964
4965 @vindex SYMBOL_VAR_DOMAIN
4966 @item gdb.SYMBOL_VAR_DOMAIN
4967 This domain contains variables, function names, typedef names and enum
4968 type values.
4969
4970 @vindex SYMBOL_STRUCT_DOMAIN
4971 @item gdb.SYMBOL_STRUCT_DOMAIN
4972 This domain holds struct, union and enum type names.
4973
4974 @vindex SYMBOL_LABEL_DOMAIN
4975 @item gdb.SYMBOL_LABEL_DOMAIN
4976 This domain contains names of labels (for gotos).
4977
4978 @vindex SYMBOL_MODULE_DOMAIN
4979 @item gdb.SYMBOL_MODULE_DOMAIN
4980 This domain contains names of Fortran module types.
4981
4982 @vindex SYMBOL_COMMON_BLOCK_DOMAIN
4983 @item gdb.SYMBOL_COMMON_BLOCK_DOMAIN
4984 This domain contains names of Fortran common blocks.
4985 @end vtable
4986
4987 The available address class categories in @code{gdb.Symbol} are represented
4988 as constants in the @code{gdb} module:
4989
4990 @vtable @code
4991 @vindex SYMBOL_LOC_UNDEF
4992 @item gdb.SYMBOL_LOC_UNDEF
4993 If this is returned by address class, it indicates an error either in
4994 the symbol information or in @value{GDBN}'s handling of symbols.
4995
4996 @vindex SYMBOL_LOC_CONST
4997 @item gdb.SYMBOL_LOC_CONST
4998 Value is constant int.
4999
5000 @vindex SYMBOL_LOC_STATIC
5001 @item gdb.SYMBOL_LOC_STATIC
5002 Value is at a fixed address.
5003
5004 @vindex SYMBOL_LOC_REGISTER
5005 @item gdb.SYMBOL_LOC_REGISTER
5006 Value is in a register.
5007
5008 @vindex SYMBOL_LOC_ARG
5009 @item gdb.SYMBOL_LOC_ARG
5010 Value is an argument. This value is at the offset stored within the
5011 symbol inside the frame's argument list.
5012
5013 @vindex SYMBOL_LOC_REF_ARG
5014 @item gdb.SYMBOL_LOC_REF_ARG
5015 Value address is stored in the frame's argument list. Just like
5016 @code{LOC_ARG} except that the value's address is stored at the
5017 offset, not the value itself.
5018
5019 @vindex SYMBOL_LOC_REGPARM_ADDR
5020 @item gdb.SYMBOL_LOC_REGPARM_ADDR
5021 Value is a specified register. Just like @code{LOC_REGISTER} except
5022 the register holds the address of the argument instead of the argument
5023 itself.
5024
5025 @vindex SYMBOL_LOC_LOCAL
5026 @item gdb.SYMBOL_LOC_LOCAL
5027 Value is a local variable.
5028
5029 @vindex SYMBOL_LOC_TYPEDEF
5030 @item gdb.SYMBOL_LOC_TYPEDEF
5031 Value not used. Symbols in the domain @code{SYMBOL_STRUCT_DOMAIN} all
5032 have this class.
5033
5034 @vindex SYMBOL_LOC_BLOCK
5035 @item gdb.SYMBOL_LOC_BLOCK
5036 Value is a block.
5037
5038 @vindex SYMBOL_LOC_CONST_BYTES
5039 @item gdb.SYMBOL_LOC_CONST_BYTES
5040 Value is a byte-sequence.
5041
5042 @vindex SYMBOL_LOC_UNRESOLVED
5043 @item gdb.SYMBOL_LOC_UNRESOLVED
5044 Value is at a fixed address, but the address of the variable has to be
5045 determined from the minimal symbol table whenever the variable is
5046 referenced.
5047
5048 @vindex SYMBOL_LOC_OPTIMIZED_OUT
5049 @item gdb.SYMBOL_LOC_OPTIMIZED_OUT
5050 The value does not actually exist in the program.
5051
5052 @vindex SYMBOL_LOC_COMPUTED
5053 @item gdb.SYMBOL_LOC_COMPUTED
5054 The value's address is a computed location.
5055
5056 @vindex SYMBOL_LOC_COMPUTED
5057 @item gdb.SYMBOL_LOC_COMPUTED
5058 The value's address is a symbol. This is only used for Fortran common
5059 blocks.
5060 @end vtable
5061
5062 @node Symbol Tables In Python
5063 @subsubsection Symbol table representation in Python
5064
5065 @cindex symbol tables in python
5066 @tindex gdb.Symtab
5067 @tindex gdb.Symtab_and_line
5068
5069 Access to symbol table data maintained by @value{GDBN} on the inferior
5070 is exposed to Python via two objects: @code{gdb.Symtab_and_line} and
5071 @code{gdb.Symtab}. Symbol table and line data for a frame is returned
5072 from the @code{find_sal} method in @code{gdb.Frame} object.
5073 @xref{Frames In Python}.
5074
5075 For more information on @value{GDBN}'s symbol table management, see
5076 @ref{Symbols, ,Examining the Symbol Table}, for more information.
5077
5078 A @code{gdb.Symtab_and_line} object has the following attributes:
5079
5080 @defvar Symtab_and_line.symtab
5081 The symbol table object (@code{gdb.Symtab}) for this frame.
5082 This attribute is not writable.
5083 @end defvar
5084
5085 @defvar Symtab_and_line.pc
5086 Indicates the start of the address range occupied by code for the
5087 current source line. This attribute is not writable.
5088 @end defvar
5089
5090 @defvar Symtab_and_line.last
5091 Indicates the end of the address range occupied by code for the current
5092 source line. This attribute is not writable.
5093 @end defvar
5094
5095 @defvar Symtab_and_line.line
5096 Indicates the current line number for this object. This
5097 attribute is not writable.
5098 @end defvar
5099
5100 A @code{gdb.Symtab_and_line} object has the following methods:
5101
5102 @defun Symtab_and_line.is_valid ()
5103 Returns @code{True} if the @code{gdb.Symtab_and_line} object is valid,
5104 @code{False} if not. A @code{gdb.Symtab_and_line} object can become
5105 invalid if the Symbol table and line object it refers to does not
5106 exist in @value{GDBN} any longer. All other
5107 @code{gdb.Symtab_and_line} methods will throw an exception if it is
5108 invalid at the time the method is called.
5109 @end defun
5110
5111 A @code{gdb.Symtab} object has the following attributes:
5112
5113 @defvar Symtab.filename
5114 The symbol table's source filename. This attribute is not writable.
5115 @end defvar
5116
5117 @defvar Symtab.objfile
5118 The symbol table's backing object file. @xref{Objfiles In Python}.
5119 This attribute is not writable.
5120 @end defvar
5121
5122 @defvar Symtab.producer
5123 The name and possibly version number of the program that
5124 compiled the code in the symbol table.
5125 The contents of this string is up to the compiler.
5126 If no producer information is available then @code{None} is returned.
5127 This attribute is not writable.
5128 @end defvar
5129
5130 A @code{gdb.Symtab} object has the following methods:
5131
5132 @defun Symtab.is_valid ()
5133 Returns @code{True} if the @code{gdb.Symtab} object is valid,
5134 @code{False} if not. A @code{gdb.Symtab} object can become invalid if
5135 the symbol table it refers to does not exist in @value{GDBN} any
5136 longer. All other @code{gdb.Symtab} methods will throw an exception
5137 if it is invalid at the time the method is called.
5138 @end defun
5139
5140 @defun Symtab.fullname ()
5141 Return the symbol table's source absolute file name.
5142 @end defun
5143
5144 @defun Symtab.global_block ()
5145 Return the global block of the underlying symbol table.
5146 @xref{Blocks In Python}.
5147 @end defun
5148
5149 @defun Symtab.static_block ()
5150 Return the static block of the underlying symbol table.
5151 @xref{Blocks In Python}.
5152 @end defun
5153
5154 @defun Symtab.linetable ()
5155 Return the line table associated with the symbol table.
5156 @xref{Line Tables In Python}.
5157 @end defun
5158
5159 @node Line Tables In Python
5160 @subsubsection Manipulating line tables using Python
5161
5162 @cindex line tables in python
5163 @tindex gdb.LineTable
5164
5165 Python code can request and inspect line table information from a
5166 symbol table that is loaded in @value{GDBN}. A line table is a
5167 mapping of source lines to their executable locations in memory. To
5168 acquire the line table information for a particular symbol table, use
5169 the @code{linetable} function (@pxref{Symbol Tables In Python}).
5170
5171 A @code{gdb.LineTable} is iterable. The iterator returns
5172 @code{LineTableEntry} objects that correspond to the source line and
5173 address for each line table entry. @code{LineTableEntry} objects have
5174 the following attributes:
5175
5176 @defvar LineTableEntry.line
5177 The source line number for this line table entry. This number
5178 corresponds to the actual line of source. This attribute is not
5179 writable.
5180 @end defvar
5181
5182 @defvar LineTableEntry.pc
5183 The address that is associated with the line table entry where the
5184 executable code for that source line resides in memory. This
5185 attribute is not writable.
5186 @end defvar
5187
5188 As there can be multiple addresses for a single source line, you may
5189 receive multiple @code{LineTableEntry} objects with matching
5190 @code{line} attributes, but with different @code{pc} attributes. The
5191 iterator is sorted in ascending @code{pc} order. Here is a small
5192 example illustrating iterating over a line table.
5193
5194 @smallexample
5195 symtab = gdb.selected_frame().find_sal().symtab
5196 linetable = symtab.linetable()
5197 for line in linetable:
5198 print "Line: "+str(line.line)+" Address: "+hex(line.pc)
5199 @end smallexample
5200
5201 This will have the following output:
5202
5203 @smallexample
5204 Line: 33 Address: 0x4005c8L
5205 Line: 37 Address: 0x4005caL
5206 Line: 39 Address: 0x4005d2L
5207 Line: 40 Address: 0x4005f8L
5208 Line: 42 Address: 0x4005ffL
5209 Line: 44 Address: 0x400608L
5210 Line: 42 Address: 0x40060cL
5211 Line: 45 Address: 0x400615L
5212 @end smallexample
5213
5214 In addition to being able to iterate over a @code{LineTable}, it also
5215 has the following direct access methods:
5216
5217 @defun LineTable.line (line)
5218 Return a Python @code{Tuple} of @code{LineTableEntry} objects for any
5219 entries in the line table for the given @var{line}, which specifies
5220 the source code line. If there are no entries for that source code
5221 @var{line}, the Python @code{None} is returned.
5222 @end defun
5223
5224 @defun LineTable.has_line (line)
5225 Return a Python @code{Boolean} indicating whether there is an entry in
5226 the line table for this source line. Return @code{True} if an entry
5227 is found, or @code{False} if not.
5228 @end defun
5229
5230 @defun LineTable.source_lines ()
5231 Return a Python @code{List} of the source line numbers in the symbol
5232 table. Only lines with executable code locations are returned. The
5233 contents of the @code{List} will just be the source line entries
5234 represented as Python @code{Long} values.
5235 @end defun
5236
5237 @node Breakpoints In Python
5238 @subsubsection Manipulating breakpoints using Python
5239
5240 @cindex breakpoints in python
5241 @tindex gdb.Breakpoint
5242
5243 Python code can manipulate breakpoints via the @code{gdb.Breakpoint}
5244 class.
5245
5246 A breakpoint can be created using one of the two forms of the
5247 @code{gdb.Breakpoint} constructor. The first one accepts a string
5248 like one would pass to the @code{break}
5249 (@pxref{Set Breaks,,Setting Breakpoints}) and @code{watch}
5250 (@pxref{Set Watchpoints, , Setting Watchpoints}) commands, and can be used to
5251 create both breakpoints and watchpoints. The second accepts separate Python
5252 arguments similar to @ref{Explicit Locations}, and can only be used to create
5253 breakpoints.
5254
5255 @defun Breakpoint.__init__ (spec @r{[}, type @r{][}, wp_class @r{][}, internal @r{][}, temporary @r{][}, qualified @r{]})
5256 Create a new breakpoint according to @var{spec}, which is a string naming the
5257 location of a breakpoint, or an expression that defines a watchpoint. The
5258 string should describe a location in a format recognized by the @code{break}
5259 command (@pxref{Set Breaks,,Setting Breakpoints}) or, in the case of a
5260 watchpoint, by the @code{watch} command
5261 (@pxref{Set Watchpoints, , Setting Watchpoints}).
5262
5263 The optional @var{type} argument specifies the type of the breakpoint to create,
5264 as defined below.
5265
5266 The optional @var{wp_class} argument defines the class of watchpoint to create,
5267 if @var{type} is @code{gdb.BP_WATCHPOINT}. If @var{wp_class} is omitted, it
5268 defaults to @code{gdb.WP_WRITE}.
5269
5270 The optional @var{internal} argument allows the breakpoint to become invisible
5271 to the user. The breakpoint will neither be reported when created, nor will it
5272 be listed in the output from @code{info breakpoints} (but will be listed with
5273 the @code{maint info breakpoints} command).
5274
5275 The optional @var{temporary} argument makes the breakpoint a temporary
5276 breakpoint. Temporary breakpoints are deleted after they have been hit. Any
5277 further access to the Python breakpoint after it has been hit will result in a
5278 runtime error (as that breakpoint has now been automatically deleted).
5279
5280 The optional @var{qualified} argument is a boolean that allows interpreting
5281 the function passed in @code{spec} as a fully-qualified name. It is equivalent
5282 to @code{break}'s @code{-qualified} flag (@pxref{Linespec Locations} and
5283 @ref{Explicit Locations}).
5284
5285 @end defun
5286
5287 @defun Breakpoint.__init__ (@r{[} source @r{][}, function @r{][}, label @r{][}, line @r{]}, @r{][} internal @r{][}, temporary @r{][}, qualified @r{]})
5288 This second form of creating a new breakpoint specifies the explicit
5289 location (@pxref{Explicit Locations}) using keywords. The new breakpoint will
5290 be created in the specified source file @var{source}, at the specified
5291 @var{function}, @var{label} and @var{line}.
5292
5293 @var{internal}, @var{temporary} and @var{qualified} have the same usage as
5294 explained previously.
5295 @end defun
5296
5297 The available types are represented by constants defined in the @code{gdb}
5298 module:
5299
5300 @vtable @code
5301 @vindex BP_BREAKPOINT
5302 @item gdb.BP_BREAKPOINT
5303 Normal code breakpoint.
5304
5305 @vindex BP_WATCHPOINT
5306 @item gdb.BP_WATCHPOINT
5307 Watchpoint breakpoint.
5308
5309 @vindex BP_HARDWARE_WATCHPOINT
5310 @item gdb.BP_HARDWARE_WATCHPOINT
5311 Hardware assisted watchpoint.
5312
5313 @vindex BP_READ_WATCHPOINT
5314 @item gdb.BP_READ_WATCHPOINT
5315 Hardware assisted read watchpoint.
5316
5317 @vindex BP_ACCESS_WATCHPOINT
5318 @item gdb.BP_ACCESS_WATCHPOINT
5319 Hardware assisted access watchpoint.
5320 @end vtable
5321
5322 The available watchpoint types represented by constants are defined in the
5323 @code{gdb} module:
5324
5325 @vtable @code
5326 @vindex WP_READ
5327 @item gdb.WP_READ
5328 Read only watchpoint.
5329
5330 @vindex WP_WRITE
5331 @item gdb.WP_WRITE
5332 Write only watchpoint.
5333
5334 @vindex WP_ACCESS
5335 @item gdb.WP_ACCESS
5336 Read/Write watchpoint.
5337 @end vtable
5338
5339 @defun Breakpoint.stop (self)
5340 The @code{gdb.Breakpoint} class can be sub-classed and, in
5341 particular, you may choose to implement the @code{stop} method.
5342 If this method is defined in a sub-class of @code{gdb.Breakpoint},
5343 it will be called when the inferior reaches any location of a
5344 breakpoint which instantiates that sub-class. If the method returns
5345 @code{True}, the inferior will be stopped at the location of the
5346 breakpoint, otherwise the inferior will continue.
5347
5348 If there are multiple breakpoints at the same location with a
5349 @code{stop} method, each one will be called regardless of the
5350 return status of the previous. This ensures that all @code{stop}
5351 methods have a chance to execute at that location. In this scenario
5352 if one of the methods returns @code{True} but the others return
5353 @code{False}, the inferior will still be stopped.
5354
5355 You should not alter the execution state of the inferior (i.e.@:, step,
5356 next, etc.), alter the current frame context (i.e.@:, change the current
5357 active frame), or alter, add or delete any breakpoint. As a general
5358 rule, you should not alter any data within @value{GDBN} or the inferior
5359 at this time.
5360
5361 Example @code{stop} implementation:
5362
5363 @smallexample
5364 class MyBreakpoint (gdb.Breakpoint):
5365 def stop (self):
5366 inf_val = gdb.parse_and_eval("foo")
5367 if inf_val == 3:
5368 return True
5369 return False
5370 @end smallexample
5371 @end defun
5372
5373 @defun Breakpoint.is_valid ()
5374 Return @code{True} if this @code{Breakpoint} object is valid,
5375 @code{False} otherwise. A @code{Breakpoint} object can become invalid
5376 if the user deletes the breakpoint. In this case, the object still
5377 exists, but the underlying breakpoint does not. In the cases of
5378 watchpoint scope, the watchpoint remains valid even if execution of the
5379 inferior leaves the scope of that watchpoint.
5380 @end defun
5381
5382 @defun Breakpoint.delete ()
5383 Permanently deletes the @value{GDBN} breakpoint. This also
5384 invalidates the Python @code{Breakpoint} object. Any further access
5385 to this object's attributes or methods will raise an error.
5386 @end defun
5387
5388 @defvar Breakpoint.enabled
5389 This attribute is @code{True} if the breakpoint is enabled, and
5390 @code{False} otherwise. This attribute is writable. You can use it to enable
5391 or disable the breakpoint.
5392 @end defvar
5393
5394 @defvar Breakpoint.silent
5395 This attribute is @code{True} if the breakpoint is silent, and
5396 @code{False} otherwise. This attribute is writable.
5397
5398 Note that a breakpoint can also be silent if it has commands and the
5399 first command is @code{silent}. This is not reported by the
5400 @code{silent} attribute.
5401 @end defvar
5402
5403 @defvar Breakpoint.pending
5404 This attribute is @code{True} if the breakpoint is pending, and
5405 @code{False} otherwise. @xref{Set Breaks}. This attribute is
5406 read-only.
5407 @end defvar
5408
5409 @anchor{python_breakpoint_thread}
5410 @defvar Breakpoint.thread
5411 If the breakpoint is thread-specific, this attribute holds the
5412 thread's global id. If the breakpoint is not thread-specific, this
5413 attribute is @code{None}. This attribute is writable.
5414 @end defvar
5415
5416 @defvar Breakpoint.task
5417 If the breakpoint is Ada task-specific, this attribute holds the Ada task
5418 id. If the breakpoint is not task-specific (or the underlying
5419 language is not Ada), this attribute is @code{None}. This attribute
5420 is writable.
5421 @end defvar
5422
5423 @defvar Breakpoint.ignore_count
5424 This attribute holds the ignore count for the breakpoint, an integer.
5425 This attribute is writable.
5426 @end defvar
5427
5428 @defvar Breakpoint.number
5429 This attribute holds the breakpoint's number --- the identifier used by
5430 the user to manipulate the breakpoint. This attribute is not writable.
5431 @end defvar
5432
5433 @defvar Breakpoint.type
5434 This attribute holds the breakpoint's type --- the identifier used to
5435 determine the actual breakpoint type or use-case. This attribute is not
5436 writable.
5437 @end defvar
5438
5439 @defvar Breakpoint.visible
5440 This attribute tells whether the breakpoint is visible to the user
5441 when set, or when the @samp{info breakpoints} command is run. This
5442 attribute is not writable.
5443 @end defvar
5444
5445 @defvar Breakpoint.temporary
5446 This attribute indicates whether the breakpoint was created as a
5447 temporary breakpoint. Temporary breakpoints are automatically deleted
5448 after that breakpoint has been hit. Access to this attribute, and all
5449 other attributes and functions other than the @code{is_valid}
5450 function, will result in an error after the breakpoint has been hit
5451 (as it has been automatically deleted). This attribute is not
5452 writable.
5453 @end defvar
5454
5455 @defvar Breakpoint.hit_count
5456 This attribute holds the hit count for the breakpoint, an integer.
5457 This attribute is writable, but currently it can only be set to zero.
5458 @end defvar
5459
5460 @defvar Breakpoint.location
5461 This attribute holds the location of the breakpoint, as specified by
5462 the user. It is a string. If the breakpoint does not have a location
5463 (that is, it is a watchpoint) the attribute's value is @code{None}. This
5464 attribute is not writable.
5465 @end defvar
5466
5467 @defvar Breakpoint.expression
5468 This attribute holds a breakpoint expression, as specified by
5469 the user. It is a string. If the breakpoint does not have an
5470 expression (the breakpoint is not a watchpoint) the attribute's value
5471 is @code{None}. This attribute is not writable.
5472 @end defvar
5473
5474 @defvar Breakpoint.condition
5475 This attribute holds the condition of the breakpoint, as specified by
5476 the user. It is a string. If there is no condition, this attribute's
5477 value is @code{None}. This attribute is writable.
5478 @end defvar
5479
5480 @defvar Breakpoint.commands
5481 This attribute holds the commands attached to the breakpoint. If
5482 there are commands, this attribute's value is a string holding all the
5483 commands, separated by newlines. If there are no commands, this
5484 attribute is @code{None}. This attribute is writable.
5485 @end defvar
5486
5487 @node Finish Breakpoints in Python
5488 @subsubsection Finish Breakpoints
5489
5490 @cindex python finish breakpoints
5491 @tindex gdb.FinishBreakpoint
5492
5493 A finish breakpoint is a temporary breakpoint set at the return address of
5494 a frame, based on the @code{finish} command. @code{gdb.FinishBreakpoint}
5495 extends @code{gdb.Breakpoint}. The underlying breakpoint will be disabled
5496 and deleted when the execution will run out of the breakpoint scope (i.e.@:
5497 @code{Breakpoint.stop} or @code{FinishBreakpoint.out_of_scope} triggered).
5498 Finish breakpoints are thread specific and must be create with the right
5499 thread selected.
5500
5501 @defun FinishBreakpoint.__init__ (@r{[}frame@r{]} @r{[}, internal@r{]})
5502 Create a finish breakpoint at the return address of the @code{gdb.Frame}
5503 object @var{frame}. If @var{frame} is not provided, this defaults to the
5504 newest frame. The optional @var{internal} argument allows the breakpoint to
5505 become invisible to the user. @xref{Breakpoints In Python}, for further
5506 details about this argument.
5507 @end defun
5508
5509 @defun FinishBreakpoint.out_of_scope (self)
5510 In some circumstances (e.g.@: @code{longjmp}, C@t{++} exceptions, @value{GDBN}
5511 @code{return} command, @dots{}), a function may not properly terminate, and
5512 thus never hit the finish breakpoint. When @value{GDBN} notices such a
5513 situation, the @code{out_of_scope} callback will be triggered.
5514
5515 You may want to sub-class @code{gdb.FinishBreakpoint} and override this
5516 method:
5517
5518 @smallexample
5519 class MyFinishBreakpoint (gdb.FinishBreakpoint)
5520 def stop (self):
5521 print "normal finish"
5522 return True
5523
5524 def out_of_scope ():
5525 print "abnormal finish"
5526 @end smallexample
5527 @end defun
5528
5529 @defvar FinishBreakpoint.return_value
5530 When @value{GDBN} is stopped at a finish breakpoint and the frame
5531 used to build the @code{gdb.FinishBreakpoint} object had debug symbols, this
5532 attribute will contain a @code{gdb.Value} object corresponding to the return
5533 value of the function. The value will be @code{None} if the function return
5534 type is @code{void} or if the return value was not computable. This attribute
5535 is not writable.
5536 @end defvar
5537
5538 @node Lazy Strings In Python
5539 @subsubsection Python representation of lazy strings
5540
5541 @cindex lazy strings in python
5542 @tindex gdb.LazyString
5543
5544 A @dfn{lazy string} is a string whose contents is not retrieved or
5545 encoded until it is needed.
5546
5547 A @code{gdb.LazyString} is represented in @value{GDBN} as an
5548 @code{address} that points to a region of memory, an @code{encoding}
5549 that will be used to encode that region of memory, and a @code{length}
5550 to delimit the region of memory that represents the string. The
5551 difference between a @code{gdb.LazyString} and a string wrapped within
5552 a @code{gdb.Value} is that a @code{gdb.LazyString} will be treated
5553 differently by @value{GDBN} when printing. A @code{gdb.LazyString} is
5554 retrieved and encoded during printing, while a @code{gdb.Value}
5555 wrapping a string is immediately retrieved and encoded on creation.
5556
5557 A @code{gdb.LazyString} object has the following functions:
5558
5559 @defun LazyString.value ()
5560 Convert the @code{gdb.LazyString} to a @code{gdb.Value}. This value
5561 will point to the string in memory, but will lose all the delayed
5562 retrieval, encoding and handling that @value{GDBN} applies to a
5563 @code{gdb.LazyString}.
5564 @end defun
5565
5566 @defvar LazyString.address
5567 This attribute holds the address of the string. This attribute is not
5568 writable.
5569 @end defvar
5570
5571 @defvar LazyString.length
5572 This attribute holds the length of the string in characters. If the
5573 length is -1, then the string will be fetched and encoded up to the
5574 first null of appropriate width. This attribute is not writable.
5575 @end defvar
5576
5577 @defvar LazyString.encoding
5578 This attribute holds the encoding that will be applied to the string
5579 when the string is printed by @value{GDBN}. If the encoding is not
5580 set, or contains an empty string, then @value{GDBN} will select the
5581 most appropriate encoding when the string is printed. This attribute
5582 is not writable.
5583 @end defvar
5584
5585 @defvar LazyString.type
5586 This attribute holds the type that is represented by the lazy string's
5587 type. For a lazy string this is a pointer or array type. To
5588 resolve this to the lazy string's character type, use the type's
5589 @code{target} method. @xref{Types In Python}. This attribute is not
5590 writable.
5591 @end defvar
5592
5593 @node Architectures In Python
5594 @subsubsection Python representation of architectures
5595 @cindex Python architectures
5596
5597 @value{GDBN} uses architecture specific parameters and artifacts in a
5598 number of its various computations. An architecture is represented
5599 by an instance of the @code{gdb.Architecture} class.
5600
5601 A @code{gdb.Architecture} class has the following methods:
5602
5603 @defun Architecture.name ()
5604 Return the name (string value) of the architecture.
5605 @end defun
5606
5607 @defun Architecture.disassemble (@var{start_pc} @r{[}, @var{end_pc} @r{[}, @var{count}@r{]]})
5608 Return a list of disassembled instructions starting from the memory
5609 address @var{start_pc}. The optional arguments @var{end_pc} and
5610 @var{count} determine the number of instructions in the returned list.
5611 If both the optional arguments @var{end_pc} and @var{count} are
5612 specified, then a list of at most @var{count} disassembled instructions
5613 whose start address falls in the closed memory address interval from
5614 @var{start_pc} to @var{end_pc} are returned. If @var{end_pc} is not
5615 specified, but @var{count} is specified, then @var{count} number of
5616 instructions starting from the address @var{start_pc} are returned. If
5617 @var{count} is not specified but @var{end_pc} is specified, then all
5618 instructions whose start address falls in the closed memory address
5619 interval from @var{start_pc} to @var{end_pc} are returned. If neither
5620 @var{end_pc} nor @var{count} are specified, then a single instruction at
5621 @var{start_pc} is returned. For all of these cases, each element of the
5622 returned list is a Python @code{dict} with the following string keys:
5623
5624 @table @code
5625
5626 @item addr
5627 The value corresponding to this key is a Python long integer capturing
5628 the memory address of the instruction.
5629
5630 @item asm
5631 The value corresponding to this key is a string value which represents
5632 the instruction with assembly language mnemonics. The assembly
5633 language flavor used is the same as that specified by the current CLI
5634 variable @code{disassembly-flavor}. @xref{Machine Code}.
5635
5636 @item length
5637 The value corresponding to this key is the length (integer value) of the
5638 instruction in bytes.
5639
5640 @end table
5641 @end defun
5642
5643 @node Python Auto-loading
5644 @subsection Python Auto-loading
5645 @cindex Python auto-loading
5646
5647 When a new object file is read (for example, due to the @code{file}
5648 command, or because the inferior has loaded a shared library),
5649 @value{GDBN} will look for Python support scripts in several ways:
5650 @file{@var{objfile}-gdb.py} and @code{.debug_gdb_scripts} section.
5651 @xref{Auto-loading extensions}.
5652
5653 The auto-loading feature is useful for supplying application-specific
5654 debugging commands and scripts.
5655
5656 Auto-loading can be enabled or disabled,
5657 and the list of auto-loaded scripts can be printed.
5658
5659 @table @code
5660 @anchor{set auto-load python-scripts}
5661 @kindex set auto-load python-scripts
5662 @item set auto-load python-scripts [on|off]
5663 Enable or disable the auto-loading of Python scripts.
5664
5665 @anchor{show auto-load python-scripts}
5666 @kindex show auto-load python-scripts
5667 @item show auto-load python-scripts
5668 Show whether auto-loading of Python scripts is enabled or disabled.
5669
5670 @anchor{info auto-load python-scripts}
5671 @kindex info auto-load python-scripts
5672 @cindex print list of auto-loaded Python scripts
5673 @item info auto-load python-scripts [@var{regexp}]
5674 Print the list of all Python scripts that @value{GDBN} auto-loaded.
5675
5676 Also printed is the list of Python scripts that were mentioned in
5677 the @code{.debug_gdb_scripts} section and were either not found
5678 (@pxref{dotdebug_gdb_scripts section}) or were not auto-loaded due to
5679 @code{auto-load safe-path} rejection (@pxref{Auto-loading}).
5680 This is useful because their names are not printed when @value{GDBN}
5681 tries to load them and fails. There may be many of them, and printing
5682 an error message for each one is problematic.
5683
5684 If @var{regexp} is supplied only Python scripts with matching names are printed.
5685
5686 Example:
5687
5688 @smallexample
5689 (gdb) info auto-load python-scripts
5690 Loaded Script
5691 Yes py-section-script.py
5692 full name: /tmp/py-section-script.py
5693 No my-foo-pretty-printers.py
5694 @end smallexample
5695 @end table
5696
5697 When reading an auto-loaded file or script, @value{GDBN} sets the
5698 @dfn{current objfile}. This is available via the @code{gdb.current_objfile}
5699 function (@pxref{Objfiles In Python}). This can be useful for
5700 registering objfile-specific pretty-printers and frame-filters.
5701
5702 @node Python modules
5703 @subsection Python modules
5704 @cindex python modules
5705
5706 @value{GDBN} comes with several modules to assist writing Python code.
5707
5708 @menu
5709 * gdb.printing:: Building and registering pretty-printers.
5710 * gdb.types:: Utilities for working with types.
5711 * gdb.prompt:: Utilities for prompt value substitution.
5712 @end menu
5713
5714 @node gdb.printing
5715 @subsubsection gdb.printing
5716 @cindex gdb.printing
5717
5718 This module provides a collection of utilities for working with
5719 pretty-printers.
5720
5721 @table @code
5722 @item PrettyPrinter (@var{name}, @var{subprinters}=None)
5723 This class specifies the API that makes @samp{info pretty-printer},
5724 @samp{enable pretty-printer} and @samp{disable pretty-printer} work.
5725 Pretty-printers should generally inherit from this class.
5726
5727 @item SubPrettyPrinter (@var{name})
5728 For printers that handle multiple types, this class specifies the
5729 corresponding API for the subprinters.
5730
5731 @item RegexpCollectionPrettyPrinter (@var{name})
5732 Utility class for handling multiple printers, all recognized via
5733 regular expressions.
5734 @xref{Writing a Pretty-Printer}, for an example.
5735
5736 @item FlagEnumerationPrinter (@var{name})
5737 A pretty-printer which handles printing of @code{enum} values. Unlike
5738 @value{GDBN}'s built-in @code{enum} printing, this printer attempts to
5739 work properly when there is some overlap between the enumeration
5740 constants. The argument @var{name} is the name of the printer and
5741 also the name of the @code{enum} type to look up.
5742
5743 @item register_pretty_printer (@var{obj}, @var{printer}, @var{replace}=False)
5744 Register @var{printer} with the pretty-printer list of @var{obj}.
5745 If @var{replace} is @code{True} then any existing copy of the printer
5746 is replaced. Otherwise a @code{RuntimeError} exception is raised
5747 if a printer with the same name already exists.
5748 @end table
5749
5750 @node gdb.types
5751 @subsubsection gdb.types
5752 @cindex gdb.types
5753
5754 This module provides a collection of utilities for working with
5755 @code{gdb.Type} objects.
5756
5757 @table @code
5758 @item get_basic_type (@var{type})
5759 Return @var{type} with const and volatile qualifiers stripped,
5760 and with typedefs and C@t{++} references converted to the underlying type.
5761
5762 C@t{++} example:
5763
5764 @smallexample
5765 typedef const int const_int;
5766 const_int foo (3);
5767 const_int& foo_ref (foo);
5768 int main () @{ return 0; @}
5769 @end smallexample
5770
5771 Then in gdb:
5772
5773 @smallexample
5774 (gdb) start
5775 (gdb) python import gdb.types
5776 (gdb) python foo_ref = gdb.parse_and_eval("foo_ref")
5777 (gdb) python print gdb.types.get_basic_type(foo_ref.type)
5778 int
5779 @end smallexample
5780
5781 @item has_field (@var{type}, @var{field})
5782 Return @code{True} if @var{type}, assumed to be a type with fields
5783 (e.g., a structure or union), has field @var{field}.
5784
5785 @item make_enum_dict (@var{enum_type})
5786 Return a Python @code{dictionary} type produced from @var{enum_type}.
5787
5788 @item deep_items (@var{type})
5789 Returns a Python iterator similar to the standard
5790 @code{gdb.Type.iteritems} method, except that the iterator returned
5791 by @code{deep_items} will recursively traverse anonymous struct or
5792 union fields. For example:
5793
5794 @smallexample
5795 struct A
5796 @{
5797 int a;
5798 union @{
5799 int b0;
5800 int b1;
5801 @};
5802 @};
5803 @end smallexample
5804
5805 @noindent
5806 Then in @value{GDBN}:
5807 @smallexample
5808 (@value{GDBP}) python import gdb.types
5809 (@value{GDBP}) python struct_a = gdb.lookup_type("struct A")
5810 (@value{GDBP}) python print struct_a.keys ()
5811 @{['a', '']@}
5812 (@value{GDBP}) python print [k for k,v in gdb.types.deep_items(struct_a)]
5813 @{['a', 'b0', 'b1']@}
5814 @end smallexample
5815
5816 @item get_type_recognizers ()
5817 Return a list of the enabled type recognizers for the current context.
5818 This is called by @value{GDBN} during the type-printing process
5819 (@pxref{Type Printing API}).
5820
5821 @item apply_type_recognizers (recognizers, type_obj)
5822 Apply the type recognizers, @var{recognizers}, to the type object
5823 @var{type_obj}. If any recognizer returns a string, return that
5824 string. Otherwise, return @code{None}. This is called by
5825 @value{GDBN} during the type-printing process (@pxref{Type Printing
5826 API}).
5827
5828 @item register_type_printer (locus, printer)
5829 This is a convenience function to register a type printer
5830 @var{printer}. The printer must implement the type printer protocol.
5831 The @var{locus} argument is either a @code{gdb.Objfile}, in which case
5832 the printer is registered with that objfile; a @code{gdb.Progspace},
5833 in which case the printer is registered with that progspace; or
5834 @code{None}, in which case the printer is registered globally.
5835
5836 @item TypePrinter
5837 This is a base class that implements the type printer protocol. Type
5838 printers are encouraged, but not required, to derive from this class.
5839 It defines a constructor:
5840
5841 @defmethod TypePrinter __init__ (self, name)
5842 Initialize the type printer with the given name. The new printer
5843 starts in the enabled state.
5844 @end defmethod
5845
5846 @end table
5847
5848 @node gdb.prompt
5849 @subsubsection gdb.prompt
5850 @cindex gdb.prompt
5851
5852 This module provides a method for prompt value-substitution.
5853
5854 @table @code
5855 @item substitute_prompt (@var{string})
5856 Return @var{string} with escape sequences substituted by values. Some
5857 escape sequences take arguments. You can specify arguments inside
5858 ``@{@}'' immediately following the escape sequence.
5859
5860 The escape sequences you can pass to this function are:
5861
5862 @table @code
5863 @item \\
5864 Substitute a backslash.
5865 @item \e
5866 Substitute an ESC character.
5867 @item \f
5868 Substitute the selected frame; an argument names a frame parameter.
5869 @item \n
5870 Substitute a newline.
5871 @item \p
5872 Substitute a parameter's value; the argument names the parameter.
5873 @item \r
5874 Substitute a carriage return.
5875 @item \t
5876 Substitute the selected thread; an argument names a thread parameter.
5877 @item \v
5878 Substitute the version of GDB.
5879 @item \w
5880 Substitute the current working directory.
5881 @item \[
5882 Begin a sequence of non-printing characters. These sequences are
5883 typically used with the ESC character, and are not counted in the string
5884 length. Example: ``\[\e[0;34m\](gdb)\[\e[0m\]'' will return a
5885 blue-colored ``(gdb)'' prompt where the length is five.
5886 @item \]
5887 End a sequence of non-printing characters.
5888 @end table
5889
5890 For example:
5891
5892 @smallexample
5893 substitute_prompt (``frame: \f,
5894 print arguments: \p@{print frame-arguments@}'')
5895 @end smallexample
5896
5897 @exdent will return the string:
5898
5899 @smallexample
5900 "frame: main, print arguments: scalars"
5901 @end smallexample
5902 @end table
This page took 0.209798 seconds and 5 git commands to generate.