Multi-target: NEWS and user manual
[deliverable/binutils-gdb.git] / gdb / doc / python.texi
1 @c Copyright (C) 2008--2020 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 super(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 Connections 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 To get the list of threads for an inferior, use the @code{Inferior.threads()}
3297 method. @xref{Inferiors In Python}
3298
3299 A @code{gdb.InferiorThread} object has the following attributes:
3300
3301 @defvar InferiorThread.name
3302 The name of the thread. If the user specified a name using
3303 @code{thread name}, then this returns that name. Otherwise, if an
3304 OS-supplied name is available, then it is returned. Otherwise, this
3305 returns @code{None}.
3306
3307 This attribute can be assigned to. The new value must be a string
3308 object, which sets the new name, or @code{None}, which removes any
3309 user-specified thread name.
3310 @end defvar
3311
3312 @defvar InferiorThread.num
3313 The per-inferior number of the thread, as assigned by GDB.
3314 @end defvar
3315
3316 @defvar InferiorThread.global_num
3317 The global ID of the thread, as assigned by GDB. You can use this to
3318 make Python breakpoints thread-specific, for example
3319 (@pxref{python_breakpoint_thread,,The Breakpoint.thread attribute}).
3320 @end defvar
3321
3322 @defvar InferiorThread.ptid
3323 ID of the thread, as assigned by the operating system. This attribute is a
3324 tuple containing three integers. The first is the Process ID (PID); the second
3325 is the Lightweight Process ID (LWPID), and the third is the Thread ID (TID).
3326 Either the LWPID or TID may be 0, which indicates that the operating system
3327 does not use that identifier.
3328 @end defvar
3329
3330 @defvar InferiorThread.inferior
3331 The inferior this thread belongs to. This attribute is represented as
3332 a @code{gdb.Inferior} object. This attribute is not writable.
3333 @end defvar
3334
3335 A @code{gdb.InferiorThread} object has the following methods:
3336
3337 @defun InferiorThread.is_valid ()
3338 Returns @code{True} if the @code{gdb.InferiorThread} object is valid,
3339 @code{False} if not. A @code{gdb.InferiorThread} object will become
3340 invalid if the thread exits, or the inferior that the thread belongs
3341 is deleted. All other @code{gdb.InferiorThread} methods will throw an
3342 exception if it is invalid at the time the method is called.
3343 @end defun
3344
3345 @defun InferiorThread.switch ()
3346 This changes @value{GDBN}'s currently selected thread to the one represented
3347 by this object.
3348 @end defun
3349
3350 @defun InferiorThread.is_stopped ()
3351 Return a Boolean indicating whether the thread is stopped.
3352 @end defun
3353
3354 @defun InferiorThread.is_running ()
3355 Return a Boolean indicating whether the thread is running.
3356 @end defun
3357
3358 @defun InferiorThread.is_exited ()
3359 Return a Boolean indicating whether the thread is exited.
3360 @end defun
3361
3362 @defun InferiorThread.handle ()
3363 Return the thread object's handle, represented as a Python @code{bytes}
3364 object. A @code{gdb.Value} representation of the handle may be
3365 constructed via @code{gdb.Value(bufobj, type)} where @var{bufobj} is
3366 the Python @code{bytes} representation of the handle and @var{type} is
3367 a @code{gdb.Type} for the handle type.
3368 @end defun
3369
3370 @node Recordings In Python
3371 @subsubsection Recordings In Python
3372 @cindex recordings in python
3373
3374 The following recordings-related functions
3375 (@pxref{Process Record and Replay}) are available in the @code{gdb}
3376 module:
3377
3378 @defun gdb.start_recording (@r{[}method@r{]}, @r{[}format@r{]})
3379 Start a recording using the given @var{method} and @var{format}. If
3380 no @var{format} is given, the default format for the recording method
3381 is used. If no @var{method} is given, the default method will be used.
3382 Returns a @code{gdb.Record} object on success. Throw an exception on
3383 failure.
3384
3385 The following strings can be passed as @var{method}:
3386
3387 @itemize @bullet
3388 @item
3389 @code{"full"}
3390 @item
3391 @code{"btrace"}: Possible values for @var{format}: @code{"pt"},
3392 @code{"bts"} or leave out for default format.
3393 @end itemize
3394 @end defun
3395
3396 @defun gdb.current_recording ()
3397 Access a currently running recording. Return a @code{gdb.Record}
3398 object on success. Return @code{None} if no recording is currently
3399 active.
3400 @end defun
3401
3402 @defun gdb.stop_recording ()
3403 Stop the current recording. Throw an exception if no recording is
3404 currently active. All record objects become invalid after this call.
3405 @end defun
3406
3407 A @code{gdb.Record} object has the following attributes:
3408
3409 @defvar Record.method
3410 A string with the current recording method, e.g.@: @code{full} or
3411 @code{btrace}.
3412 @end defvar
3413
3414 @defvar Record.format
3415 A string with the current recording format, e.g.@: @code{bt}, @code{pts} or
3416 @code{None}.
3417 @end defvar
3418
3419 @defvar Record.begin
3420 A method specific instruction object representing the first instruction
3421 in this recording.
3422 @end defvar
3423
3424 @defvar Record.end
3425 A method specific instruction object representing the current
3426 instruction, that is not actually part of the recording.
3427 @end defvar
3428
3429 @defvar Record.replay_position
3430 The instruction representing the current replay position. If there is
3431 no replay active, this will be @code{None}.
3432 @end defvar
3433
3434 @defvar Record.instruction_history
3435 A list with all recorded instructions.
3436 @end defvar
3437
3438 @defvar Record.function_call_history
3439 A list with all recorded function call segments.
3440 @end defvar
3441
3442 A @code{gdb.Record} object has the following methods:
3443
3444 @defun Record.goto (instruction)
3445 Move the replay position to the given @var{instruction}.
3446 @end defun
3447
3448 The common @code{gdb.Instruction} class that recording method specific
3449 instruction objects inherit from, has the following attributes:
3450
3451 @defvar Instruction.pc
3452 An integer representing this instruction's address.
3453 @end defvar
3454
3455 @defvar Instruction.data
3456 A buffer with the raw instruction data. In Python 3, the return value is a
3457 @code{memoryview} object.
3458 @end defvar
3459
3460 @defvar Instruction.decoded
3461 A human readable string with the disassembled instruction.
3462 @end defvar
3463
3464 @defvar Instruction.size
3465 The size of the instruction in bytes.
3466 @end defvar
3467
3468 Additionally @code{gdb.RecordInstruction} has the following attributes:
3469
3470 @defvar RecordInstruction.number
3471 An integer identifying this instruction. @code{number} corresponds to
3472 the numbers seen in @code{record instruction-history}
3473 (@pxref{Process Record and Replay}).
3474 @end defvar
3475
3476 @defvar RecordInstruction.sal
3477 A @code{gdb.Symtab_and_line} object representing the associated symtab
3478 and line of this instruction. May be @code{None} if no debug information is
3479 available.
3480 @end defvar
3481
3482 @defvar RecordInstruction.is_speculative
3483 A boolean indicating whether the instruction was executed speculatively.
3484 @end defvar
3485
3486 If an error occured during recording or decoding a recording, this error is
3487 represented by a @code{gdb.RecordGap} object in the instruction list. It has
3488 the following attributes:
3489
3490 @defvar RecordGap.number
3491 An integer identifying this gap. @code{number} corresponds to the numbers seen
3492 in @code{record instruction-history} (@pxref{Process Record and Replay}).
3493 @end defvar
3494
3495 @defvar RecordGap.error_code
3496 A numerical representation of the reason for the gap. The value is specific to
3497 the current recording method.
3498 @end defvar
3499
3500 @defvar RecordGap.error_string
3501 A human readable string with the reason for the gap.
3502 @end defvar
3503
3504 A @code{gdb.RecordFunctionSegment} object has the following attributes:
3505
3506 @defvar RecordFunctionSegment.number
3507 An integer identifying this function segment. @code{number} corresponds to
3508 the numbers seen in @code{record function-call-history}
3509 (@pxref{Process Record and Replay}).
3510 @end defvar
3511
3512 @defvar RecordFunctionSegment.symbol
3513 A @code{gdb.Symbol} object representing the associated symbol. May be
3514 @code{None} if no debug information is available.
3515 @end defvar
3516
3517 @defvar RecordFunctionSegment.level
3518 An integer representing the function call's stack level. May be
3519 @code{None} if the function call is a gap.
3520 @end defvar
3521
3522 @defvar RecordFunctionSegment.instructions
3523 A list of @code{gdb.RecordInstruction} or @code{gdb.RecordGap} objects
3524 associated with this function call.
3525 @end defvar
3526
3527 @defvar RecordFunctionSegment.up
3528 A @code{gdb.RecordFunctionSegment} object representing the caller's
3529 function segment. If the call has not been recorded, this will be the
3530 function segment to which control returns. If neither the call nor the
3531 return have been recorded, this will be @code{None}.
3532 @end defvar
3533
3534 @defvar RecordFunctionSegment.prev
3535 A @code{gdb.RecordFunctionSegment} object representing the previous
3536 segment of this function call. May be @code{None}.
3537 @end defvar
3538
3539 @defvar RecordFunctionSegment.next
3540 A @code{gdb.RecordFunctionSegment} object representing the next segment of
3541 this function call. May be @code{None}.
3542 @end defvar
3543
3544 The following example demonstrates the usage of these objects and
3545 functions to create a function that will rewind a record to the last
3546 time a function in a different file was executed. This would typically
3547 be used to track the execution of user provided callback functions in a
3548 library which typically are not visible in a back trace.
3549
3550 @smallexample
3551 def bringback ():
3552 rec = gdb.current_recording ()
3553 if not rec:
3554 return
3555
3556 insn = rec.instruction_history
3557 if len (insn) == 0:
3558 return
3559
3560 try:
3561 position = insn.index (rec.replay_position)
3562 except:
3563 position = -1
3564 try:
3565 filename = insn[position].sal.symtab.fullname ()
3566 except:
3567 filename = None
3568
3569 for i in reversed (insn[:position]):
3570 try:
3571 current = i.sal.symtab.fullname ()
3572 except:
3573 current = None
3574
3575 if filename == current:
3576 continue
3577
3578 rec.goto (i)
3579 return
3580 @end smallexample
3581
3582 Another possible application is to write a function that counts the
3583 number of code executions in a given line range. This line range can
3584 contain parts of functions or span across several functions and is not
3585 limited to be contiguous.
3586
3587 @smallexample
3588 def countrange (filename, linerange):
3589 count = 0
3590
3591 def filter_only (file_name):
3592 for call in gdb.current_recording ().function_call_history:
3593 try:
3594 if file_name in call.symbol.symtab.fullname ():
3595 yield call
3596 except:
3597 pass
3598
3599 for c in filter_only (filename):
3600 for i in c.instructions:
3601 try:
3602 if i.sal.line in linerange:
3603 count += 1
3604 break;
3605 except:
3606 pass
3607
3608 return count
3609 @end smallexample
3610
3611 @node Commands In Python
3612 @subsubsection Commands In Python
3613
3614 @cindex commands in python
3615 @cindex python commands
3616 You can implement new @value{GDBN} CLI commands in Python. A CLI
3617 command is implemented using an instance of the @code{gdb.Command}
3618 class, most commonly using a subclass.
3619
3620 @defun Command.__init__ (name, @var{command_class} @r{[}, @var{completer_class} @r{[}, @var{prefix}@r{]]})
3621 The object initializer for @code{Command} registers the new command
3622 with @value{GDBN}. This initializer is normally invoked from the
3623 subclass' own @code{__init__} method.
3624
3625 @var{name} is the name of the command. If @var{name} consists of
3626 multiple words, then the initial words are looked for as prefix
3627 commands. In this case, if one of the prefix commands does not exist,
3628 an exception is raised.
3629
3630 There is no support for multi-line commands.
3631
3632 @var{command_class} should be one of the @samp{COMMAND_} constants
3633 defined below. This argument tells @value{GDBN} how to categorize the
3634 new command in the help system.
3635
3636 @var{completer_class} is an optional argument. If given, it should be
3637 one of the @samp{COMPLETE_} constants defined below. This argument
3638 tells @value{GDBN} how to perform completion for this command. If not
3639 given, @value{GDBN} will attempt to complete using the object's
3640 @code{complete} method (see below); if no such method is found, an
3641 error will occur when completion is attempted.
3642
3643 @var{prefix} is an optional argument. If @code{True}, then the new
3644 command is a prefix command; sub-commands of this command may be
3645 registered.
3646
3647 The help text for the new command is taken from the Python
3648 documentation string for the command's class, if there is one. If no
3649 documentation string is provided, the default value ``This command is
3650 not documented.'' is used.
3651 @end defun
3652
3653 @cindex don't repeat Python command
3654 @defun Command.dont_repeat ()
3655 By default, a @value{GDBN} command is repeated when the user enters a
3656 blank line at the command prompt. A command can suppress this
3657 behavior by invoking the @code{dont_repeat} method. This is similar
3658 to the user command @code{dont-repeat}, see @ref{Define, dont-repeat}.
3659 @end defun
3660
3661 @defun Command.invoke (argument, from_tty)
3662 This method is called by @value{GDBN} when this command is invoked.
3663
3664 @var{argument} is a string. It is the argument to the command, after
3665 leading and trailing whitespace has been stripped.
3666
3667 @var{from_tty} is a boolean argument. When true, this means that the
3668 command was entered by the user at the terminal; when false it means
3669 that the command came from elsewhere.
3670
3671 If this method throws an exception, it is turned into a @value{GDBN}
3672 @code{error} call. Otherwise, the return value is ignored.
3673
3674 @findex gdb.string_to_argv
3675 To break @var{argument} up into an argv-like string use
3676 @code{gdb.string_to_argv}. This function behaves identically to
3677 @value{GDBN}'s internal argument lexer @code{buildargv}.
3678 It is recommended to use this for consistency.
3679 Arguments are separated by spaces and may be quoted.
3680 Example:
3681
3682 @smallexample
3683 print gdb.string_to_argv ("1 2\ \\\"3 '4 \"5' \"6 '7\"")
3684 ['1', '2 "3', '4 "5', "6 '7"]
3685 @end smallexample
3686
3687 @end defun
3688
3689 @cindex completion of Python commands
3690 @defun Command.complete (text, word)
3691 This method is called by @value{GDBN} when the user attempts
3692 completion on this command. All forms of completion are handled by
3693 this method, that is, the @key{TAB} and @key{M-?} key bindings
3694 (@pxref{Completion}), and the @code{complete} command (@pxref{Help,
3695 complete}).
3696
3697 The arguments @var{text} and @var{word} are both strings; @var{text}
3698 holds the complete command line up to the cursor's location, while
3699 @var{word} holds the last word of the command line; this is computed
3700 using a word-breaking heuristic.
3701
3702 The @code{complete} method can return several values:
3703 @itemize @bullet
3704 @item
3705 If the return value is a sequence, the contents of the sequence are
3706 used as the completions. It is up to @code{complete} to ensure that the
3707 contents actually do complete the word. A zero-length sequence is
3708 allowed, it means that there were no completions available. Only
3709 string elements of the sequence are used; other elements in the
3710 sequence are ignored.
3711
3712 @item
3713 If the return value is one of the @samp{COMPLETE_} constants defined
3714 below, then the corresponding @value{GDBN}-internal completion
3715 function is invoked, and its result is used.
3716
3717 @item
3718 All other results are treated as though there were no available
3719 completions.
3720 @end itemize
3721 @end defun
3722
3723 When a new command is registered, it must be declared as a member of
3724 some general class of commands. This is used to classify top-level
3725 commands in the on-line help system; note that prefix commands are not
3726 listed under their own category but rather that of their top-level
3727 command. The available classifications are represented by constants
3728 defined in the @code{gdb} module:
3729
3730 @table @code
3731 @findex COMMAND_NONE
3732 @findex gdb.COMMAND_NONE
3733 @item gdb.COMMAND_NONE
3734 The command does not belong to any particular class. A command in
3735 this category will not be displayed in any of the help categories.
3736
3737 @findex COMMAND_RUNNING
3738 @findex gdb.COMMAND_RUNNING
3739 @item gdb.COMMAND_RUNNING
3740 The command is related to running the inferior. For example,
3741 @code{start}, @code{step}, and @code{continue} are in this category.
3742 Type @kbd{help running} at the @value{GDBN} prompt to see a list of
3743 commands in this category.
3744
3745 @findex COMMAND_DATA
3746 @findex gdb.COMMAND_DATA
3747 @item gdb.COMMAND_DATA
3748 The command is related to data or variables. For example,
3749 @code{call}, @code{find}, and @code{print} are in this category. Type
3750 @kbd{help data} at the @value{GDBN} prompt to see a list of commands
3751 in this category.
3752
3753 @findex COMMAND_STACK
3754 @findex gdb.COMMAND_STACK
3755 @item gdb.COMMAND_STACK
3756 The command has to do with manipulation of the stack. For example,
3757 @code{backtrace}, @code{frame}, and @code{return} are in this
3758 category. Type @kbd{help stack} at the @value{GDBN} prompt to see a
3759 list of commands in this category.
3760
3761 @findex COMMAND_FILES
3762 @findex gdb.COMMAND_FILES
3763 @item gdb.COMMAND_FILES
3764 This class is used for file-related commands. For example,
3765 @code{file}, @code{list} and @code{section} are in this category.
3766 Type @kbd{help files} at the @value{GDBN} prompt to see a list of
3767 commands in this category.
3768
3769 @findex COMMAND_SUPPORT
3770 @findex gdb.COMMAND_SUPPORT
3771 @item gdb.COMMAND_SUPPORT
3772 This should be used for ``support facilities'', generally meaning
3773 things that are useful to the user when interacting with @value{GDBN},
3774 but not related to the state of the inferior. For example,
3775 @code{help}, @code{make}, and @code{shell} are in this category. Type
3776 @kbd{help support} at the @value{GDBN} prompt to see a list of
3777 commands in this category.
3778
3779 @findex COMMAND_STATUS
3780 @findex gdb.COMMAND_STATUS
3781 @item gdb.COMMAND_STATUS
3782 The command is an @samp{info}-related command, that is, related to the
3783 state of @value{GDBN} itself. For example, @code{info}, @code{macro},
3784 and @code{show} are in this category. Type @kbd{help status} at the
3785 @value{GDBN} prompt to see a list of commands in this category.
3786
3787 @findex COMMAND_BREAKPOINTS
3788 @findex gdb.COMMAND_BREAKPOINTS
3789 @item gdb.COMMAND_BREAKPOINTS
3790 The command has to do with breakpoints. For example, @code{break},
3791 @code{clear}, and @code{delete} are in this category. Type @kbd{help
3792 breakpoints} at the @value{GDBN} prompt to see a list of commands in
3793 this category.
3794
3795 @findex COMMAND_TRACEPOINTS
3796 @findex gdb.COMMAND_TRACEPOINTS
3797 @item gdb.COMMAND_TRACEPOINTS
3798 The command has to do with tracepoints. For example, @code{trace},
3799 @code{actions}, and @code{tfind} are in this category. Type
3800 @kbd{help tracepoints} at the @value{GDBN} prompt to see a list of
3801 commands in this category.
3802
3803 @findex COMMAND_USER
3804 @findex gdb.COMMAND_USER
3805 @item gdb.COMMAND_USER
3806 The command is a general purpose command for the user, and typically
3807 does not fit in one of the other categories.
3808 Type @kbd{help user-defined} at the @value{GDBN} prompt to see
3809 a list of commands in this category, as well as the list of gdb macros
3810 (@pxref{Sequences}).
3811
3812 @findex COMMAND_OBSCURE
3813 @findex gdb.COMMAND_OBSCURE
3814 @item gdb.COMMAND_OBSCURE
3815 The command is only used in unusual circumstances, or is not of
3816 general interest to users. For example, @code{checkpoint},
3817 @code{fork}, and @code{stop} are in this category. Type @kbd{help
3818 obscure} at the @value{GDBN} prompt to see a list of commands in this
3819 category.
3820
3821 @findex COMMAND_MAINTENANCE
3822 @findex gdb.COMMAND_MAINTENANCE
3823 @item gdb.COMMAND_MAINTENANCE
3824 The command is only useful to @value{GDBN} maintainers. The
3825 @code{maintenance} and @code{flushregs} commands are in this category.
3826 Type @kbd{help internals} at the @value{GDBN} prompt to see a list of
3827 commands in this category.
3828 @end table
3829
3830 A new command can use a predefined completion function, either by
3831 specifying it via an argument at initialization, or by returning it
3832 from the @code{complete} method. These predefined completion
3833 constants are all defined in the @code{gdb} module:
3834
3835 @vtable @code
3836 @vindex COMPLETE_NONE
3837 @item gdb.COMPLETE_NONE
3838 This constant means that no completion should be done.
3839
3840 @vindex COMPLETE_FILENAME
3841 @item gdb.COMPLETE_FILENAME
3842 This constant means that filename completion should be performed.
3843
3844 @vindex COMPLETE_LOCATION
3845 @item gdb.COMPLETE_LOCATION
3846 This constant means that location completion should be done.
3847 @xref{Specify Location}.
3848
3849 @vindex COMPLETE_COMMAND
3850 @item gdb.COMPLETE_COMMAND
3851 This constant means that completion should examine @value{GDBN}
3852 command names.
3853
3854 @vindex COMPLETE_SYMBOL
3855 @item gdb.COMPLETE_SYMBOL
3856 This constant means that completion should be done using symbol names
3857 as the source.
3858
3859 @vindex COMPLETE_EXPRESSION
3860 @item gdb.COMPLETE_EXPRESSION
3861 This constant means that completion should be done on expressions.
3862 Often this means completing on symbol names, but some language
3863 parsers also have support for completing on field names.
3864 @end vtable
3865
3866 The following code snippet shows how a trivial CLI command can be
3867 implemented in Python:
3868
3869 @smallexample
3870 class HelloWorld (gdb.Command):
3871 """Greet the whole world."""
3872
3873 def __init__ (self):
3874 super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
3875
3876 def invoke (self, arg, from_tty):
3877 print "Hello, World!"
3878
3879 HelloWorld ()
3880 @end smallexample
3881
3882 The last line instantiates the class, and is necessary to trigger the
3883 registration of the command with @value{GDBN}. Depending on how the
3884 Python code is read into @value{GDBN}, you may need to import the
3885 @code{gdb} module explicitly.
3886
3887 @node Parameters In Python
3888 @subsubsection Parameters In Python
3889
3890 @cindex parameters in python
3891 @cindex python parameters
3892 @tindex gdb.Parameter
3893 @tindex Parameter
3894 You can implement new @value{GDBN} parameters using Python. A new
3895 parameter is implemented as an instance of the @code{gdb.Parameter}
3896 class.
3897
3898 Parameters are exposed to the user via the @code{set} and
3899 @code{show} commands. @xref{Help}.
3900
3901 There are many parameters that already exist and can be set in
3902 @value{GDBN}. Two examples are: @code{set follow fork} and
3903 @code{set charset}. Setting these parameters influences certain
3904 behavior in @value{GDBN}. Similarly, you can define parameters that
3905 can be used to influence behavior in custom Python scripts and commands.
3906
3907 @defun Parameter.__init__ (name, @var{command-class}, @var{parameter-class} @r{[}, @var{enum-sequence}@r{]})
3908 The object initializer for @code{Parameter} registers the new
3909 parameter with @value{GDBN}. This initializer is normally invoked
3910 from the subclass' own @code{__init__} method.
3911
3912 @var{name} is the name of the new parameter. If @var{name} consists
3913 of multiple words, then the initial words are looked for as prefix
3914 parameters. An example of this can be illustrated with the
3915 @code{set print} set of parameters. If @var{name} is
3916 @code{print foo}, then @code{print} will be searched as the prefix
3917 parameter. In this case the parameter can subsequently be accessed in
3918 @value{GDBN} as @code{set print foo}.
3919
3920 If @var{name} consists of multiple words, and no prefix parameter group
3921 can be found, an exception is raised.
3922
3923 @var{command-class} should be one of the @samp{COMMAND_} constants
3924 (@pxref{Commands In Python}). This argument tells @value{GDBN} how to
3925 categorize the new parameter in the help system.
3926
3927 @var{parameter-class} should be one of the @samp{PARAM_} constants
3928 defined below. This argument tells @value{GDBN} the type of the new
3929 parameter; this information is used for input validation and
3930 completion.
3931
3932 If @var{parameter-class} is @code{PARAM_ENUM}, then
3933 @var{enum-sequence} must be a sequence of strings. These strings
3934 represent the possible values for the parameter.
3935
3936 If @var{parameter-class} is not @code{PARAM_ENUM}, then the presence
3937 of a fourth argument will cause an exception to be thrown.
3938
3939 The help text for the new parameter is taken from the Python
3940 documentation string for the parameter's class, if there is one. If
3941 there is no documentation string, a default value is used.
3942 @end defun
3943
3944 @defvar Parameter.set_doc
3945 If this attribute exists, and is a string, then its value is used as
3946 the help text for this parameter's @code{set} command. The value is
3947 examined when @code{Parameter.__init__} is invoked; subsequent changes
3948 have no effect.
3949 @end defvar
3950
3951 @defvar Parameter.show_doc
3952 If this attribute exists, and is a string, then its value is used as
3953 the help text for this parameter's @code{show} command. The value is
3954 examined when @code{Parameter.__init__} is invoked; subsequent changes
3955 have no effect.
3956 @end defvar
3957
3958 @defvar Parameter.value
3959 The @code{value} attribute holds the underlying value of the
3960 parameter. It can be read and assigned to just as any other
3961 attribute. @value{GDBN} does validation when assignments are made.
3962 @end defvar
3963
3964 There are two methods that may be implemented in any @code{Parameter}
3965 class. These are:
3966
3967 @defun Parameter.get_set_string (self)
3968 If this method exists, @value{GDBN} will call it when a
3969 @var{parameter}'s value has been changed via the @code{set} API (for
3970 example, @kbd{set foo off}). The @code{value} attribute has already
3971 been populated with the new value and may be used in output. This
3972 method must return a string. If the returned string is not empty,
3973 @value{GDBN} will present it to the user.
3974
3975 If this method raises the @code{gdb.GdbError} exception
3976 (@pxref{Exception Handling}), then @value{GDBN} will print the
3977 exception's string and the @code{set} command will fail. Note,
3978 however, that the @code{value} attribute will not be reset in this
3979 case. So, if your parameter must validate values, it should store the
3980 old value internally and reset the exposed value, like so:
3981
3982 @smallexample
3983 class ExampleParam (gdb.Parameter):
3984 def __init__ (self, name):
3985 super (ExampleParam, self).__init__ (name,
3986 gdb.COMMAND_DATA,
3987 gdb.PARAM_BOOLEAN)
3988 self.value = True
3989 self.saved_value = True
3990 def validate(self):
3991 return False
3992 def get_set_string (self):
3993 if not self.validate():
3994 self.value = self.saved_value
3995 raise gdb.GdbError('Failed to validate')
3996 self.saved_value = self.value
3997 @end smallexample
3998 @end defun
3999
4000 @defun Parameter.get_show_string (self, svalue)
4001 @value{GDBN} will call this method when a @var{parameter}'s
4002 @code{show} API has been invoked (for example, @kbd{show foo}). The
4003 argument @code{svalue} receives the string representation of the
4004 current value. This method must return a string.
4005 @end defun
4006
4007 When a new parameter is defined, its type must be specified. The
4008 available types are represented by constants defined in the @code{gdb}
4009 module:
4010
4011 @table @code
4012 @findex PARAM_BOOLEAN
4013 @findex gdb.PARAM_BOOLEAN
4014 @item gdb.PARAM_BOOLEAN
4015 The value is a plain boolean. The Python boolean values, @code{True}
4016 and @code{False} are the only valid values.
4017
4018 @findex PARAM_AUTO_BOOLEAN
4019 @findex gdb.PARAM_AUTO_BOOLEAN
4020 @item gdb.PARAM_AUTO_BOOLEAN
4021 The value has three possible states: true, false, and @samp{auto}. In
4022 Python, true and false are represented using boolean constants, and
4023 @samp{auto} is represented using @code{None}.
4024
4025 @findex PARAM_UINTEGER
4026 @findex gdb.PARAM_UINTEGER
4027 @item gdb.PARAM_UINTEGER
4028 The value is an unsigned integer. The value of 0 should be
4029 interpreted to mean ``unlimited''.
4030
4031 @findex PARAM_INTEGER
4032 @findex gdb.PARAM_INTEGER
4033 @item gdb.PARAM_INTEGER
4034 The value is a signed integer. The value of 0 should be interpreted
4035 to mean ``unlimited''.
4036
4037 @findex PARAM_STRING
4038 @findex gdb.PARAM_STRING
4039 @item gdb.PARAM_STRING
4040 The value is a string. When the user modifies the string, any escape
4041 sequences, such as @samp{\t}, @samp{\f}, and octal escapes, are
4042 translated into corresponding characters and encoded into the current
4043 host charset.
4044
4045 @findex PARAM_STRING_NOESCAPE
4046 @findex gdb.PARAM_STRING_NOESCAPE
4047 @item gdb.PARAM_STRING_NOESCAPE
4048 The value is a string. When the user modifies the string, escapes are
4049 passed through untranslated.
4050
4051 @findex PARAM_OPTIONAL_FILENAME
4052 @findex gdb.PARAM_OPTIONAL_FILENAME
4053 @item gdb.PARAM_OPTIONAL_FILENAME
4054 The value is a either a filename (a string), or @code{None}.
4055
4056 @findex PARAM_FILENAME
4057 @findex gdb.PARAM_FILENAME
4058 @item gdb.PARAM_FILENAME
4059 The value is a filename. This is just like
4060 @code{PARAM_STRING_NOESCAPE}, but uses file names for completion.
4061
4062 @findex PARAM_ZINTEGER
4063 @findex gdb.PARAM_ZINTEGER
4064 @item gdb.PARAM_ZINTEGER
4065 The value is an integer. This is like @code{PARAM_INTEGER}, except 0
4066 is interpreted as itself.
4067
4068 @findex PARAM_ZUINTEGER
4069 @findex gdb.PARAM_ZUINTEGER
4070 @item gdb.PARAM_ZUINTEGER
4071 The value is an unsigned integer. This is like @code{PARAM_INTEGER},
4072 except 0 is interpreted as itself, and the value cannot be negative.
4073
4074 @findex PARAM_ZUINTEGER_UNLIMITED
4075 @findex gdb.PARAM_ZUINTEGER_UNLIMITED
4076 @item gdb.PARAM_ZUINTEGER_UNLIMITED
4077 The value is a signed integer. This is like @code{PARAM_ZUINTEGER},
4078 except the special value -1 should be interpreted to mean
4079 ``unlimited''. Other negative values are not allowed.
4080
4081 @findex PARAM_ENUM
4082 @findex gdb.PARAM_ENUM
4083 @item gdb.PARAM_ENUM
4084 The value is a string, which must be one of a collection string
4085 constants provided when the parameter is created.
4086 @end table
4087
4088 @node Functions In Python
4089 @subsubsection Writing new convenience functions
4090
4091 @cindex writing convenience functions
4092 @cindex convenience functions in python
4093 @cindex python convenience functions
4094 @tindex gdb.Function
4095 @tindex Function
4096 You can implement new convenience functions (@pxref{Convenience Vars})
4097 in Python. A convenience function is an instance of a subclass of the
4098 class @code{gdb.Function}.
4099
4100 @defun Function.__init__ (name)
4101 The initializer for @code{Function} registers the new function with
4102 @value{GDBN}. The argument @var{name} is the name of the function,
4103 a string. The function will be visible to the user as a convenience
4104 variable of type @code{internal function}, whose name is the same as
4105 the given @var{name}.
4106
4107 The documentation for the new function is taken from the documentation
4108 string for the new class.
4109 @end defun
4110
4111 @defun Function.invoke (@var{*args})
4112 When a convenience function is evaluated, its arguments are converted
4113 to instances of @code{gdb.Value}, and then the function's
4114 @code{invoke} method is called. Note that @value{GDBN} does not
4115 predetermine the arity of convenience functions. Instead, all
4116 available arguments are passed to @code{invoke}, following the
4117 standard Python calling convention. In particular, a convenience
4118 function can have default values for parameters without ill effect.
4119
4120 The return value of this method is used as its value in the enclosing
4121 expression. If an ordinary Python value is returned, it is converted
4122 to a @code{gdb.Value} following the usual rules.
4123 @end defun
4124
4125 The following code snippet shows how a trivial convenience function can
4126 be implemented in Python:
4127
4128 @smallexample
4129 class Greet (gdb.Function):
4130 """Return string to greet someone.
4131 Takes a name as argument."""
4132
4133 def __init__ (self):
4134 super (Greet, self).__init__ ("greet")
4135
4136 def invoke (self, name):
4137 return "Hello, %s!" % name.string ()
4138
4139 Greet ()
4140 @end smallexample
4141
4142 The last line instantiates the class, and is necessary to trigger the
4143 registration of the function with @value{GDBN}. Depending on how the
4144 Python code is read into @value{GDBN}, you may need to import the
4145 @code{gdb} module explicitly.
4146
4147 Now you can use the function in an expression:
4148
4149 @smallexample
4150 (gdb) print $greet("Bob")
4151 $1 = "Hello, Bob!"
4152 @end smallexample
4153
4154 @node Progspaces In Python
4155 @subsubsection Program Spaces In Python
4156
4157 @cindex progspaces in python
4158 @tindex gdb.Progspace
4159 @tindex Progspace
4160 A program space, or @dfn{progspace}, represents a symbolic view
4161 of an address space.
4162 It consists of all of the objfiles of the program.
4163 @xref{Objfiles In Python}.
4164 @xref{Inferiors Connections and Programs, program spaces}, for more details
4165 about program spaces.
4166
4167 The following progspace-related functions are available in the
4168 @code{gdb} module:
4169
4170 @findex gdb.current_progspace
4171 @defun gdb.current_progspace ()
4172 This function returns the program space of the currently selected inferior.
4173 @xref{Inferiors Connections and Programs}. This is identical to
4174 @code{gdb.selected_inferior().progspace} (@pxref{Inferiors In Python}) and is
4175 included for historical compatibility.
4176 @end defun
4177
4178 @findex gdb.progspaces
4179 @defun gdb.progspaces ()
4180 Return a sequence of all the progspaces currently known to @value{GDBN}.
4181 @end defun
4182
4183 Each progspace is represented by an instance of the @code{gdb.Progspace}
4184 class.
4185
4186 @defvar Progspace.filename
4187 The file name of the progspace as a string.
4188 @end defvar
4189
4190 @defvar Progspace.pretty_printers
4191 The @code{pretty_printers} attribute is a list of functions. It is
4192 used to look up pretty-printers. A @code{Value} is passed to each
4193 function in order; if the function returns @code{None}, then the
4194 search continues. Otherwise, the return value should be an object
4195 which is used to format the value. @xref{Pretty Printing API}, for more
4196 information.
4197 @end defvar
4198
4199 @defvar Progspace.type_printers
4200 The @code{type_printers} attribute is a list of type printer objects.
4201 @xref{Type Printing API}, for more information.
4202 @end defvar
4203
4204 @defvar Progspace.frame_filters
4205 The @code{frame_filters} attribute is a dictionary of frame filter
4206 objects. @xref{Frame Filter API}, for more information.
4207 @end defvar
4208
4209 A program space has the following methods:
4210
4211 @findex Progspace.block_for_pc
4212 @defun Progspace.block_for_pc (pc)
4213 Return the innermost @code{gdb.Block} containing the given @var{pc}
4214 value. If the block cannot be found for the @var{pc} value specified,
4215 the function will return @code{None}.
4216 @end defun
4217
4218 @findex Progspace.find_pc_line
4219 @defun Progspace.find_pc_line (pc)
4220 Return the @code{gdb.Symtab_and_line} object corresponding to the
4221 @var{pc} value. @xref{Symbol Tables In Python}. If an invalid value
4222 of @var{pc} is passed as an argument, then the @code{symtab} and
4223 @code{line} attributes of the returned @code{gdb.Symtab_and_line}
4224 object will be @code{None} and 0 respectively.
4225 @end defun
4226
4227 @findex Progspace.is_valid
4228 @defun Progspace.is_valid ()
4229 Returns @code{True} if the @code{gdb.Progspace} object is valid,
4230 @code{False} if not. A @code{gdb.Progspace} object can become invalid
4231 if the program space file it refers to is not referenced by any
4232 inferior. All other @code{gdb.Progspace} methods will throw an
4233 exception if it is invalid at the time the method is called.
4234 @end defun
4235
4236 @findex Progspace.objfiles
4237 @defun Progspace.objfiles ()
4238 Return a sequence of all the objfiles referenced by this program
4239 space. @xref{Objfiles In Python}.
4240 @end defun
4241
4242 @findex Progspace.solib_name
4243 @defun Progspace.solib_name (address)
4244 Return the name of the shared library holding the given @var{address}
4245 as a string, or @code{None}.
4246 @end defun
4247
4248 One may add arbitrary attributes to @code{gdb.Progspace} objects
4249 in the usual Python way.
4250 This is useful if, for example, one needs to do some extra record keeping
4251 associated with the program space.
4252
4253 In this contrived example, we want to perform some processing when
4254 an objfile with a certain symbol is loaded, but we only want to do
4255 this once because it is expensive. To achieve this we record the results
4256 with the program space because we can't predict when the desired objfile
4257 will be loaded.
4258
4259 @smallexample
4260 (gdb) python
4261 def clear_objfiles_handler(event):
4262 event.progspace.expensive_computation = None
4263 def expensive(symbol):
4264 """A mock routine to perform an "expensive" computation on symbol."""
4265 print "Computing the answer to the ultimate question ..."
4266 return 42
4267 def new_objfile_handler(event):
4268 objfile = event.new_objfile
4269 progspace = objfile.progspace
4270 if not hasattr(progspace, 'expensive_computation') or \
4271 progspace.expensive_computation is None:
4272 # We use 'main' for the symbol to keep the example simple.
4273 # Note: There's no current way to constrain the lookup
4274 # to one objfile.
4275 symbol = gdb.lookup_global_symbol('main')
4276 if symbol is not None:
4277 progspace.expensive_computation = expensive(symbol)
4278 gdb.events.clear_objfiles.connect(clear_objfiles_handler)
4279 gdb.events.new_objfile.connect(new_objfile_handler)
4280 end
4281 (gdb) file /tmp/hello
4282 Reading symbols from /tmp/hello...done.
4283 Computing the answer to the ultimate question ...
4284 (gdb) python print gdb.current_progspace().expensive_computation
4285 42
4286 (gdb) run
4287 Starting program: /tmp/hello
4288 Hello.
4289 [Inferior 1 (process 4242) exited normally]
4290 @end smallexample
4291
4292 @node Objfiles In Python
4293 @subsubsection Objfiles In Python
4294
4295 @cindex objfiles in python
4296 @tindex gdb.Objfile
4297 @tindex Objfile
4298 @value{GDBN} loads symbols for an inferior from various
4299 symbol-containing files (@pxref{Files}). These include the primary
4300 executable file, any shared libraries used by the inferior, and any
4301 separate debug info files (@pxref{Separate Debug Files}).
4302 @value{GDBN} calls these symbol-containing files @dfn{objfiles}.
4303
4304 The following objfile-related functions are available in the
4305 @code{gdb} module:
4306
4307 @findex gdb.current_objfile
4308 @defun gdb.current_objfile ()
4309 When auto-loading a Python script (@pxref{Python Auto-loading}), @value{GDBN}
4310 sets the ``current objfile'' to the corresponding objfile. This
4311 function returns the current objfile. If there is no current objfile,
4312 this function returns @code{None}.
4313 @end defun
4314
4315 @findex gdb.objfiles
4316 @defun gdb.objfiles ()
4317 Return a sequence of objfiles referenced by the current program space.
4318 @xref{Objfiles In Python}, and @ref{Progspaces In Python}. This is identical
4319 to @code{gdb.selected_inferior().progspace.objfiles()} and is included for
4320 historical compatibility.
4321 @end defun
4322
4323 @findex gdb.lookup_objfile
4324 @defun gdb.lookup_objfile (name @r{[}, by_build_id{]})
4325 Look up @var{name}, a file name or build ID, in the list of objfiles
4326 for the current program space (@pxref{Progspaces In Python}).
4327 If the objfile is not found throw the Python @code{ValueError} exception.
4328
4329 If @var{name} is a relative file name, then it will match any
4330 source file name with the same trailing components. For example, if
4331 @var{name} is @samp{gcc/expr.c}, then it will match source file
4332 name of @file{/build/trunk/gcc/expr.c}, but not
4333 @file{/build/trunk/libcpp/expr.c} or @file{/build/trunk/gcc/x-expr.c}.
4334
4335 If @var{by_build_id} is provided and is @code{True} then @var{name}
4336 is the build ID of the objfile. Otherwise, @var{name} is a file name.
4337 This is supported only on some operating systems, notably those which use
4338 the ELF format for binary files and the @sc{gnu} Binutils. For more details
4339 about this feature, see the description of the @option{--build-id}
4340 command-line option in @ref{Options, , Command Line Options, ld,
4341 The GNU Linker}.
4342 @end defun
4343
4344 Each objfile is represented by an instance of the @code{gdb.Objfile}
4345 class.
4346
4347 @defvar Objfile.filename
4348 The file name of the objfile as a string, with symbolic links resolved.
4349
4350 The value is @code{None} if the objfile is no longer valid.
4351 See the @code{gdb.Objfile.is_valid} method, described below.
4352 @end defvar
4353
4354 @defvar Objfile.username
4355 The file name of the objfile as specified by the user as a string.
4356
4357 The value is @code{None} if the objfile is no longer valid.
4358 See the @code{gdb.Objfile.is_valid} method, described below.
4359 @end defvar
4360
4361 @defvar Objfile.owner
4362 For separate debug info objfiles this is the corresponding @code{gdb.Objfile}
4363 object that debug info is being provided for.
4364 Otherwise this is @code{None}.
4365 Separate debug info objfiles are added with the
4366 @code{gdb.Objfile.add_separate_debug_file} method, described below.
4367 @end defvar
4368
4369 @defvar Objfile.build_id
4370 The build ID of the objfile as a string.
4371 If the objfile does not have a build ID then the value is @code{None}.
4372
4373 This is supported only on some operating systems, notably those which use
4374 the ELF format for binary files and the @sc{gnu} Binutils. For more details
4375 about this feature, see the description of the @option{--build-id}
4376 command-line option in @ref{Options, , Command Line Options, ld,
4377 The GNU Linker}.
4378 @end defvar
4379
4380 @defvar Objfile.progspace
4381 The containing program space of the objfile as a @code{gdb.Progspace}
4382 object. @xref{Progspaces In Python}.
4383 @end defvar
4384
4385 @defvar Objfile.pretty_printers
4386 The @code{pretty_printers} attribute is a list of functions. It is
4387 used to look up pretty-printers. A @code{Value} is passed to each
4388 function in order; if the function returns @code{None}, then the
4389 search continues. Otherwise, the return value should be an object
4390 which is used to format the value. @xref{Pretty Printing API}, for more
4391 information.
4392 @end defvar
4393
4394 @defvar Objfile.type_printers
4395 The @code{type_printers} attribute is a list of type printer objects.
4396 @xref{Type Printing API}, for more information.
4397 @end defvar
4398
4399 @defvar Objfile.frame_filters
4400 The @code{frame_filters} attribute is a dictionary of frame filter
4401 objects. @xref{Frame Filter API}, for more information.
4402 @end defvar
4403
4404 One may add arbitrary attributes to @code{gdb.Objfile} objects
4405 in the usual Python way.
4406 This is useful if, for example, one needs to do some extra record keeping
4407 associated with the objfile.
4408
4409 In this contrived example we record the time when @value{GDBN}
4410 loaded the objfile.
4411
4412 @smallexample
4413 (gdb) python
4414 import datetime
4415 def new_objfile_handler(event):
4416 # Set the time_loaded attribute of the new objfile.
4417 event.new_objfile.time_loaded = datetime.datetime.today()
4418 gdb.events.new_objfile.connect(new_objfile_handler)
4419 end
4420 (gdb) file ./hello
4421 Reading symbols from ./hello...done.
4422 (gdb) python print gdb.objfiles()[0].time_loaded
4423 2014-10-09 11:41:36.770345
4424 @end smallexample
4425
4426 A @code{gdb.Objfile} object has the following methods:
4427
4428 @defun Objfile.is_valid ()
4429 Returns @code{True} if the @code{gdb.Objfile} object is valid,
4430 @code{False} if not. A @code{gdb.Objfile} object can become invalid
4431 if the object file it refers to is not loaded in @value{GDBN} any
4432 longer. All other @code{gdb.Objfile} methods will throw an exception
4433 if it is invalid at the time the method is called.
4434 @end defun
4435
4436 @defun Objfile.add_separate_debug_file (file)
4437 Add @var{file} to the list of files that @value{GDBN} will search for
4438 debug information for the objfile.
4439 This is useful when the debug info has been removed from the program
4440 and stored in a separate file. @value{GDBN} has built-in support for
4441 finding separate debug info files (@pxref{Separate Debug Files}), but if
4442 the file doesn't live in one of the standard places that @value{GDBN}
4443 searches then this function can be used to add a debug info file
4444 from a different place.
4445 @end defun
4446
4447 @defun Objfile.lookup_global_symbol (name @r{[}, domain@r{]})
4448 Search for a global symbol named @var{name} in this objfile. Optionally, the
4449 search scope can be restricted with the @var{domain} argument.
4450 The @var{domain} argument must be a domain constant defined in the @code{gdb}
4451 module and described in @ref{Symbols In Python}. This function is similar to
4452 @code{gdb.lookup_global_symbol}, except that the search is limited to this
4453 objfile.
4454
4455 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
4456 is not found.
4457 @end defun
4458
4459 @defun Objfile.lookup_static_symbol (name @r{[}, domain@r{]})
4460 Like @code{Objfile.lookup_global_symbol}, but searches for a global
4461 symbol with static linkage named @var{name} in this objfile.
4462 @end defun
4463
4464 @node Frames In Python
4465 @subsubsection Accessing inferior stack frames from Python
4466
4467 @cindex frames in python
4468 When the debugged program stops, @value{GDBN} is able to analyze its call
4469 stack (@pxref{Frames,,Stack frames}). The @code{gdb.Frame} class
4470 represents a frame in the stack. A @code{gdb.Frame} object is only valid
4471 while its corresponding frame exists in the inferior's stack. If you try
4472 to use an invalid frame object, @value{GDBN} will throw a @code{gdb.error}
4473 exception (@pxref{Exception Handling}).
4474
4475 Two @code{gdb.Frame} objects can be compared for equality with the @code{==}
4476 operator, like:
4477
4478 @smallexample
4479 (@value{GDBP}) python print gdb.newest_frame() == gdb.selected_frame ()
4480 True
4481 @end smallexample
4482
4483 The following frame-related functions are available in the @code{gdb} module:
4484
4485 @findex gdb.selected_frame
4486 @defun gdb.selected_frame ()
4487 Return the selected frame object. (@pxref{Selection,,Selecting a Frame}).
4488 @end defun
4489
4490 @findex gdb.newest_frame
4491 @defun gdb.newest_frame ()
4492 Return the newest frame object for the selected thread.
4493 @end defun
4494
4495 @defun gdb.frame_stop_reason_string (reason)
4496 Return a string explaining the reason why @value{GDBN} stopped unwinding
4497 frames, as expressed by the given @var{reason} code (an integer, see the
4498 @code{unwind_stop_reason} method further down in this section).
4499 @end defun
4500
4501 @findex gdb.invalidate_cached_frames
4502 @defun gdb.invalidate_cached_frames
4503 @value{GDBN} internally keeps a cache of the frames that have been
4504 unwound. This function invalidates this cache.
4505
4506 This function should not generally be called by ordinary Python code.
4507 It is documented for the sake of completeness.
4508 @end defun
4509
4510 A @code{gdb.Frame} object has the following methods:
4511
4512 @defun Frame.is_valid ()
4513 Returns true if the @code{gdb.Frame} object is valid, false if not.
4514 A frame object can become invalid if the frame it refers to doesn't
4515 exist anymore in the inferior. All @code{gdb.Frame} methods will throw
4516 an exception if it is invalid at the time the method is called.
4517 @end defun
4518
4519 @defun Frame.name ()
4520 Returns the function name of the frame, or @code{None} if it can't be
4521 obtained.
4522 @end defun
4523
4524 @defun Frame.architecture ()
4525 Returns the @code{gdb.Architecture} object corresponding to the frame's
4526 architecture. @xref{Architectures In Python}.
4527 @end defun
4528
4529 @defun Frame.type ()
4530 Returns the type of the frame. The value can be one of:
4531 @table @code
4532 @item gdb.NORMAL_FRAME
4533 An ordinary stack frame.
4534
4535 @item gdb.DUMMY_FRAME
4536 A fake stack frame that was created by @value{GDBN} when performing an
4537 inferior function call.
4538
4539 @item gdb.INLINE_FRAME
4540 A frame representing an inlined function. The function was inlined
4541 into a @code{gdb.NORMAL_FRAME} that is older than this one.
4542
4543 @item gdb.TAILCALL_FRAME
4544 A frame representing a tail call. @xref{Tail Call Frames}.
4545
4546 @item gdb.SIGTRAMP_FRAME
4547 A signal trampoline frame. This is the frame created by the OS when
4548 it calls into a signal handler.
4549
4550 @item gdb.ARCH_FRAME
4551 A fake stack frame representing a cross-architecture call.
4552
4553 @item gdb.SENTINEL_FRAME
4554 This is like @code{gdb.NORMAL_FRAME}, but it is only used for the
4555 newest frame.
4556 @end table
4557 @end defun
4558
4559 @defun Frame.unwind_stop_reason ()
4560 Return an integer representing the reason why it's not possible to find
4561 more frames toward the outermost frame. Use
4562 @code{gdb.frame_stop_reason_string} to convert the value returned by this
4563 function to a string. The value can be one of:
4564
4565 @table @code
4566 @item gdb.FRAME_UNWIND_NO_REASON
4567 No particular reason (older frames should be available).
4568
4569 @item gdb.FRAME_UNWIND_NULL_ID
4570 The previous frame's analyzer returns an invalid result. This is no
4571 longer used by @value{GDBN}, and is kept only for backward
4572 compatibility.
4573
4574 @item gdb.FRAME_UNWIND_OUTERMOST
4575 This frame is the outermost.
4576
4577 @item gdb.FRAME_UNWIND_UNAVAILABLE
4578 Cannot unwind further, because that would require knowing the
4579 values of registers or memory that have not been collected.
4580
4581 @item gdb.FRAME_UNWIND_INNER_ID
4582 This frame ID looks like it ought to belong to a NEXT frame,
4583 but we got it for a PREV frame. Normally, this is a sign of
4584 unwinder failure. It could also indicate stack corruption.
4585
4586 @item gdb.FRAME_UNWIND_SAME_ID
4587 This frame has the same ID as the previous one. That means
4588 that unwinding further would almost certainly give us another
4589 frame with exactly the same ID, so break the chain. Normally,
4590 this is a sign of unwinder failure. It could also indicate
4591 stack corruption.
4592
4593 @item gdb.FRAME_UNWIND_NO_SAVED_PC
4594 The frame unwinder did not find any saved PC, but we needed
4595 one to unwind further.
4596
4597 @item gdb.FRAME_UNWIND_MEMORY_ERROR
4598 The frame unwinder caused an error while trying to access memory.
4599
4600 @item gdb.FRAME_UNWIND_FIRST_ERROR
4601 Any stop reason greater or equal to this value indicates some kind
4602 of error. This special value facilitates writing code that tests
4603 for errors in unwinding in a way that will work correctly even if
4604 the list of the other values is modified in future @value{GDBN}
4605 versions. Using it, you could write:
4606 @smallexample
4607 reason = gdb.selected_frame().unwind_stop_reason ()
4608 reason_str = gdb.frame_stop_reason_string (reason)
4609 if reason >= gdb.FRAME_UNWIND_FIRST_ERROR:
4610 print "An error occured: %s" % reason_str
4611 @end smallexample
4612 @end table
4613
4614 @end defun
4615
4616 @defun Frame.pc ()
4617 Returns the frame's resume address.
4618 @end defun
4619
4620 @defun Frame.block ()
4621 Return the frame's code block. @xref{Blocks In Python}. If the frame
4622 does not have a block -- for example, if there is no debugging
4623 information for the code in question -- then this will throw an
4624 exception.
4625 @end defun
4626
4627 @defun Frame.function ()
4628 Return the symbol for the function corresponding to this frame.
4629 @xref{Symbols In Python}.
4630 @end defun
4631
4632 @defun Frame.older ()
4633 Return the frame that called this frame.
4634 @end defun
4635
4636 @defun Frame.newer ()
4637 Return the frame called by this frame.
4638 @end defun
4639
4640 @defun Frame.find_sal ()
4641 Return the frame's symtab and line object.
4642 @xref{Symbol Tables In Python}.
4643 @end defun
4644
4645 @defun Frame.read_register (register)
4646 Return the value of @var{register} in this frame. The @var{register}
4647 argument must be a string (e.g., @code{'sp'} or @code{'rax'}).
4648 Returns a @code{Gdb.Value} object. Throws an exception if @var{register}
4649 does not exist.
4650 @end defun
4651
4652 @defun Frame.read_var (variable @r{[}, block@r{]})
4653 Return the value of @var{variable} in this frame. If the optional
4654 argument @var{block} is provided, search for the variable from that
4655 block; otherwise start at the frame's current block (which is
4656 determined by the frame's current program counter). The @var{variable}
4657 argument must be a string or a @code{gdb.Symbol} object; @var{block} must be a
4658 @code{gdb.Block} object.
4659 @end defun
4660
4661 @defun Frame.select ()
4662 Set this frame to be the selected frame. @xref{Stack, ,Examining the
4663 Stack}.
4664 @end defun
4665
4666 @node Blocks In Python
4667 @subsubsection Accessing blocks from Python
4668
4669 @cindex blocks in python
4670 @tindex gdb.Block
4671
4672 In @value{GDBN}, symbols are stored in blocks. A block corresponds
4673 roughly to a scope in the source code. Blocks are organized
4674 hierarchically, and are represented individually in Python as a
4675 @code{gdb.Block}. Blocks rely on debugging information being
4676 available.
4677
4678 A frame has a block. Please see @ref{Frames In Python}, for a more
4679 in-depth discussion of frames.
4680
4681 The outermost block is known as the @dfn{global block}. The global
4682 block typically holds public global variables and functions.
4683
4684 The block nested just inside the global block is the @dfn{static
4685 block}. The static block typically holds file-scoped variables and
4686 functions.
4687
4688 @value{GDBN} provides a method to get a block's superblock, but there
4689 is currently no way to examine the sub-blocks of a block, or to
4690 iterate over all the blocks in a symbol table (@pxref{Symbol Tables In
4691 Python}).
4692
4693 Here is a short example that should help explain blocks:
4694
4695 @smallexample
4696 /* This is in the global block. */
4697 int global;
4698
4699 /* This is in the static block. */
4700 static int file_scope;
4701
4702 /* 'function' is in the global block, and 'argument' is
4703 in a block nested inside of 'function'. */
4704 int function (int argument)
4705 @{
4706 /* 'local' is in a block inside 'function'. It may or may
4707 not be in the same block as 'argument'. */
4708 int local;
4709
4710 @{
4711 /* 'inner' is in a block whose superblock is the one holding
4712 'local'. */
4713 int inner;
4714
4715 /* If this call is expanded by the compiler, you may see
4716 a nested block here whose function is 'inline_function'
4717 and whose superblock is the one holding 'inner'. */
4718 inline_function ();
4719 @}
4720 @}
4721 @end smallexample
4722
4723 A @code{gdb.Block} is iterable. The iterator returns the symbols
4724 (@pxref{Symbols In Python}) local to the block. Python programs
4725 should not assume that a specific block object will always contain a
4726 given symbol, since changes in @value{GDBN} features and
4727 infrastructure may cause symbols move across blocks in a symbol
4728 table. You can also use Python's @dfn{dictionary syntax} to access
4729 variables in this block, e.g.:
4730
4731 @smallexample
4732 symbol = some_block['variable'] # symbol is of type gdb.Symbol
4733 @end smallexample
4734
4735 The following block-related functions are available in the @code{gdb}
4736 module:
4737
4738 @findex gdb.block_for_pc
4739 @defun gdb.block_for_pc (pc)
4740 Return the innermost @code{gdb.Block} containing the given @var{pc}
4741 value. If the block cannot be found for the @var{pc} value specified,
4742 the function will return @code{None}. This is identical to
4743 @code{gdb.current_progspace().block_for_pc(pc)} and is included for
4744 historical compatibility.
4745 @end defun
4746
4747 A @code{gdb.Block} object has the following methods:
4748
4749 @defun Block.is_valid ()
4750 Returns @code{True} if the @code{gdb.Block} object is valid,
4751 @code{False} if not. A block object can become invalid if the block it
4752 refers to doesn't exist anymore in the inferior. All other
4753 @code{gdb.Block} methods will throw an exception if it is invalid at
4754 the time the method is called. The block's validity is also checked
4755 during iteration over symbols of the block.
4756 @end defun
4757
4758 A @code{gdb.Block} object has the following attributes:
4759
4760 @defvar Block.start
4761 The start address of the block. This attribute is not writable.
4762 @end defvar
4763
4764 @defvar Block.end
4765 One past the last address that appears in the block. This attribute
4766 is not writable.
4767 @end defvar
4768
4769 @defvar Block.function
4770 The name of the block represented as a @code{gdb.Symbol}. If the
4771 block is not named, then this attribute holds @code{None}. This
4772 attribute is not writable.
4773
4774 For ordinary function blocks, the superblock is the static block.
4775 However, you should note that it is possible for a function block to
4776 have a superblock that is not the static block -- for instance this
4777 happens for an inlined function.
4778 @end defvar
4779
4780 @defvar Block.superblock
4781 The block containing this block. If this parent block does not exist,
4782 this attribute holds @code{None}. This attribute is not writable.
4783 @end defvar
4784
4785 @defvar Block.global_block
4786 The global block associated with this block. This attribute is not
4787 writable.
4788 @end defvar
4789
4790 @defvar Block.static_block
4791 The static block associated with this block. This attribute is not
4792 writable.
4793 @end defvar
4794
4795 @defvar Block.is_global
4796 @code{True} if the @code{gdb.Block} object is a global block,
4797 @code{False} if not. This attribute is not
4798 writable.
4799 @end defvar
4800
4801 @defvar Block.is_static
4802 @code{True} if the @code{gdb.Block} object is a static block,
4803 @code{False} if not. This attribute is not writable.
4804 @end defvar
4805
4806 @node Symbols In Python
4807 @subsubsection Python representation of Symbols
4808
4809 @cindex symbols in python
4810 @tindex gdb.Symbol
4811
4812 @value{GDBN} represents every variable, function and type as an
4813 entry in a symbol table. @xref{Symbols, ,Examining the Symbol Table}.
4814 Similarly, Python represents these symbols in @value{GDBN} with the
4815 @code{gdb.Symbol} object.
4816
4817 The following symbol-related functions are available in the @code{gdb}
4818 module:
4819
4820 @findex gdb.lookup_symbol
4821 @defun gdb.lookup_symbol (name @r{[}, block @r{[}, domain@r{]]})
4822 This function searches for a symbol by name. The search scope can be
4823 restricted to the parameters defined in the optional domain and block
4824 arguments.
4825
4826 @var{name} is the name of the symbol. It must be a string. The
4827 optional @var{block} argument restricts the search to symbols visible
4828 in that @var{block}. The @var{block} argument must be a
4829 @code{gdb.Block} object. If omitted, the block for the current frame
4830 is used. The optional @var{domain} argument restricts
4831 the search to the domain type. The @var{domain} argument must be a
4832 domain constant defined in the @code{gdb} module and described later
4833 in this chapter.
4834
4835 The result is a tuple of two elements.
4836 The first element is a @code{gdb.Symbol} object or @code{None} if the symbol
4837 is not found.
4838 If the symbol is found, the second element is @code{True} if the symbol
4839 is a field of a method's object (e.g., @code{this} in C@t{++}),
4840 otherwise it is @code{False}.
4841 If the symbol is not found, the second element is @code{False}.
4842 @end defun
4843
4844 @findex gdb.lookup_global_symbol
4845 @defun gdb.lookup_global_symbol (name @r{[}, domain@r{]})
4846 This function searches for a global symbol by name.
4847 The search scope can be restricted to by the domain argument.
4848
4849 @var{name} is the name of the symbol. It must be a string.
4850 The optional @var{domain} argument restricts the search to the domain type.
4851 The @var{domain} argument must be a domain constant defined in the @code{gdb}
4852 module and described later in this chapter.
4853
4854 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
4855 is not found.
4856 @end defun
4857
4858 @findex gdb.lookup_static_symbol
4859 @defun gdb.lookup_static_symbol (name @r{[}, domain@r{]})
4860 This function searches for a global symbol with static linkage by name.
4861 The search scope can be restricted to by the domain argument.
4862
4863 @var{name} is the name of the symbol. It must be a string.
4864 The optional @var{domain} argument restricts the search to the domain type.
4865 The @var{domain} argument must be a domain constant defined in the @code{gdb}
4866 module and described later in this chapter.
4867
4868 The result is a @code{gdb.Symbol} object or @code{None} if the symbol
4869 is not found.
4870
4871 Note that this function will not find function-scoped static variables. To look
4872 up such variables, iterate over the variables of the function's
4873 @code{gdb.Block} and check that @code{block.addr_class} is
4874 @code{gdb.SYMBOL_LOC_STATIC}.
4875
4876 There can be multiple global symbols with static linkage with the same
4877 name. This function will only return the first matching symbol that
4878 it finds. Which symbol is found depends on where @value{GDBN} is
4879 currently stopped, as @value{GDBN} will first search for matching
4880 symbols in the current object file, and then search all other object
4881 files. If the application is not yet running then @value{GDBN} will
4882 search all object files in the order they appear in the debug
4883 information.
4884 @end defun
4885
4886 @findex gdb.lookup_static_symbols
4887 @defun gdb.lookup_static_symbols (name @r{[}, domain@r{]})
4888 Similar to @code{gdb.lookup_static_symbol}, this function searches for
4889 global symbols with static linkage by name, and optionally restricted
4890 by the domain argument. However, this function returns a list of all
4891 matching symbols found, not just the first one.
4892
4893 @var{name} is the name of the symbol. It must be a string.
4894 The optional @var{domain} argument restricts the search to the domain type.
4895 The @var{domain} argument must be a domain constant defined in the @code{gdb}
4896 module and described later in this chapter.
4897
4898 The result is a list of @code{gdb.Symbol} objects which could be empty
4899 if no matching symbols were found.
4900
4901 Note that this function will not find function-scoped static variables. To look
4902 up such variables, iterate over the variables of the function's
4903 @code{gdb.Block} and check that @code{block.addr_class} is
4904 @code{gdb.SYMBOL_LOC_STATIC}.
4905 @end defun
4906
4907 A @code{gdb.Symbol} object has the following attributes:
4908
4909 @defvar Symbol.type
4910 The type of the symbol or @code{None} if no type is recorded.
4911 This attribute is represented as a @code{gdb.Type} object.
4912 @xref{Types In Python}. This attribute is not writable.
4913 @end defvar
4914
4915 @defvar Symbol.symtab
4916 The symbol table in which the symbol appears. This attribute is
4917 represented as a @code{gdb.Symtab} object. @xref{Symbol Tables In
4918 Python}. This attribute is not writable.
4919 @end defvar
4920
4921 @defvar Symbol.line
4922 The line number in the source code at which the symbol was defined.
4923 This is an integer.
4924 @end defvar
4925
4926 @defvar Symbol.name
4927 The name of the symbol as a string. This attribute is not writable.
4928 @end defvar
4929
4930 @defvar Symbol.linkage_name
4931 The name of the symbol, as used by the linker (i.e., may be mangled).
4932 This attribute is not writable.
4933 @end defvar
4934
4935 @defvar Symbol.print_name
4936 The name of the symbol in a form suitable for output. This is either
4937 @code{name} or @code{linkage_name}, depending on whether the user
4938 asked @value{GDBN} to display demangled or mangled names.
4939 @end defvar
4940
4941 @defvar Symbol.addr_class
4942 The address class of the symbol. This classifies how to find the value
4943 of a symbol. Each address class is a constant defined in the
4944 @code{gdb} module and described later in this chapter.
4945 @end defvar
4946
4947 @defvar Symbol.needs_frame
4948 This is @code{True} if evaluating this symbol's value requires a frame
4949 (@pxref{Frames In Python}) and @code{False} otherwise. Typically,
4950 local variables will require a frame, but other symbols will not.
4951 @end defvar
4952
4953 @defvar Symbol.is_argument
4954 @code{True} if the symbol is an argument of a function.
4955 @end defvar
4956
4957 @defvar Symbol.is_constant
4958 @code{True} if the symbol is a constant.
4959 @end defvar
4960
4961 @defvar Symbol.is_function
4962 @code{True} if the symbol is a function or a method.
4963 @end defvar
4964
4965 @defvar Symbol.is_variable
4966 @code{True} if the symbol is a variable.
4967 @end defvar
4968
4969 A @code{gdb.Symbol} object has the following methods:
4970
4971 @defun Symbol.is_valid ()
4972 Returns @code{True} if the @code{gdb.Symbol} object is valid,
4973 @code{False} if not. A @code{gdb.Symbol} object can become invalid if
4974 the symbol it refers to does not exist in @value{GDBN} any longer.
4975 All other @code{gdb.Symbol} methods will throw an exception if it is
4976 invalid at the time the method is called.
4977 @end defun
4978
4979 @defun Symbol.value (@r{[}frame@r{]})
4980 Compute the value of the symbol, as a @code{gdb.Value}. For
4981 functions, this computes the address of the function, cast to the
4982 appropriate type. If the symbol requires a frame in order to compute
4983 its value, then @var{frame} must be given. If @var{frame} is not
4984 given, or if @var{frame} is invalid, then this method will throw an
4985 exception.
4986 @end defun
4987
4988 The available domain categories in @code{gdb.Symbol} are represented
4989 as constants in the @code{gdb} module:
4990
4991 @vtable @code
4992 @vindex SYMBOL_UNDEF_DOMAIN
4993 @item gdb.SYMBOL_UNDEF_DOMAIN
4994 This is used when a domain has not been discovered or none of the
4995 following domains apply. This usually indicates an error either
4996 in the symbol information or in @value{GDBN}'s handling of symbols.
4997
4998 @vindex SYMBOL_VAR_DOMAIN
4999 @item gdb.SYMBOL_VAR_DOMAIN
5000 This domain contains variables, function names, typedef names and enum
5001 type values.
5002
5003 @vindex SYMBOL_STRUCT_DOMAIN
5004 @item gdb.SYMBOL_STRUCT_DOMAIN
5005 This domain holds struct, union and enum type names.
5006
5007 @vindex SYMBOL_LABEL_DOMAIN
5008 @item gdb.SYMBOL_LABEL_DOMAIN
5009 This domain contains names of labels (for gotos).
5010
5011 @vindex SYMBOL_MODULE_DOMAIN
5012 @item gdb.SYMBOL_MODULE_DOMAIN
5013 This domain contains names of Fortran module types.
5014
5015 @vindex SYMBOL_COMMON_BLOCK_DOMAIN
5016 @item gdb.SYMBOL_COMMON_BLOCK_DOMAIN
5017 This domain contains names of Fortran common blocks.
5018 @end vtable
5019
5020 The available address class categories in @code{gdb.Symbol} are represented
5021 as constants in the @code{gdb} module:
5022
5023 @vtable @code
5024 @vindex SYMBOL_LOC_UNDEF
5025 @item gdb.SYMBOL_LOC_UNDEF
5026 If this is returned by address class, it indicates an error either in
5027 the symbol information or in @value{GDBN}'s handling of symbols.
5028
5029 @vindex SYMBOL_LOC_CONST
5030 @item gdb.SYMBOL_LOC_CONST
5031 Value is constant int.
5032
5033 @vindex SYMBOL_LOC_STATIC
5034 @item gdb.SYMBOL_LOC_STATIC
5035 Value is at a fixed address.
5036
5037 @vindex SYMBOL_LOC_REGISTER
5038 @item gdb.SYMBOL_LOC_REGISTER
5039 Value is in a register.
5040
5041 @vindex SYMBOL_LOC_ARG
5042 @item gdb.SYMBOL_LOC_ARG
5043 Value is an argument. This value is at the offset stored within the
5044 symbol inside the frame's argument list.
5045
5046 @vindex SYMBOL_LOC_REF_ARG
5047 @item gdb.SYMBOL_LOC_REF_ARG
5048 Value address is stored in the frame's argument list. Just like
5049 @code{LOC_ARG} except that the value's address is stored at the
5050 offset, not the value itself.
5051
5052 @vindex SYMBOL_LOC_REGPARM_ADDR
5053 @item gdb.SYMBOL_LOC_REGPARM_ADDR
5054 Value is a specified register. Just like @code{LOC_REGISTER} except
5055 the register holds the address of the argument instead of the argument
5056 itself.
5057
5058 @vindex SYMBOL_LOC_LOCAL
5059 @item gdb.SYMBOL_LOC_LOCAL
5060 Value is a local variable.
5061
5062 @vindex SYMBOL_LOC_TYPEDEF
5063 @item gdb.SYMBOL_LOC_TYPEDEF
5064 Value not used. Symbols in the domain @code{SYMBOL_STRUCT_DOMAIN} all
5065 have this class.
5066
5067 @vindex SYMBOL_LOC_BLOCK
5068 @item gdb.SYMBOL_LOC_BLOCK
5069 Value is a block.
5070
5071 @vindex SYMBOL_LOC_CONST_BYTES
5072 @item gdb.SYMBOL_LOC_CONST_BYTES
5073 Value is a byte-sequence.
5074
5075 @vindex SYMBOL_LOC_UNRESOLVED
5076 @item gdb.SYMBOL_LOC_UNRESOLVED
5077 Value is at a fixed address, but the address of the variable has to be
5078 determined from the minimal symbol table whenever the variable is
5079 referenced.
5080
5081 @vindex SYMBOL_LOC_OPTIMIZED_OUT
5082 @item gdb.SYMBOL_LOC_OPTIMIZED_OUT
5083 The value does not actually exist in the program.
5084
5085 @vindex SYMBOL_LOC_COMPUTED
5086 @item gdb.SYMBOL_LOC_COMPUTED
5087 The value's address is a computed location.
5088
5089 @vindex SYMBOL_LOC_COMPUTED
5090 @item gdb.SYMBOL_LOC_COMPUTED
5091 The value's address is a symbol. This is only used for Fortran common
5092 blocks.
5093 @end vtable
5094
5095 @node Symbol Tables In Python
5096 @subsubsection Symbol table representation in Python
5097
5098 @cindex symbol tables in python
5099 @tindex gdb.Symtab
5100 @tindex gdb.Symtab_and_line
5101
5102 Access to symbol table data maintained by @value{GDBN} on the inferior
5103 is exposed to Python via two objects: @code{gdb.Symtab_and_line} and
5104 @code{gdb.Symtab}. Symbol table and line data for a frame is returned
5105 from the @code{find_sal} method in @code{gdb.Frame} object.
5106 @xref{Frames In Python}.
5107
5108 For more information on @value{GDBN}'s symbol table management, see
5109 @ref{Symbols, ,Examining the Symbol Table}, for more information.
5110
5111 A @code{gdb.Symtab_and_line} object has the following attributes:
5112
5113 @defvar Symtab_and_line.symtab
5114 The symbol table object (@code{gdb.Symtab}) for this frame.
5115 This attribute is not writable.
5116 @end defvar
5117
5118 @defvar Symtab_and_line.pc
5119 Indicates the start of the address range occupied by code for the
5120 current source line. This attribute is not writable.
5121 @end defvar
5122
5123 @defvar Symtab_and_line.last
5124 Indicates the end of the address range occupied by code for the current
5125 source line. This attribute is not writable.
5126 @end defvar
5127
5128 @defvar Symtab_and_line.line
5129 Indicates the current line number for this object. This
5130 attribute is not writable.
5131 @end defvar
5132
5133 A @code{gdb.Symtab_and_line} object has the following methods:
5134
5135 @defun Symtab_and_line.is_valid ()
5136 Returns @code{True} if the @code{gdb.Symtab_and_line} object is valid,
5137 @code{False} if not. A @code{gdb.Symtab_and_line} object can become
5138 invalid if the Symbol table and line object it refers to does not
5139 exist in @value{GDBN} any longer. All other
5140 @code{gdb.Symtab_and_line} methods will throw an exception if it is
5141 invalid at the time the method is called.
5142 @end defun
5143
5144 A @code{gdb.Symtab} object has the following attributes:
5145
5146 @defvar Symtab.filename
5147 The symbol table's source filename. This attribute is not writable.
5148 @end defvar
5149
5150 @defvar Symtab.objfile
5151 The symbol table's backing object file. @xref{Objfiles In Python}.
5152 This attribute is not writable.
5153 @end defvar
5154
5155 @defvar Symtab.producer
5156 The name and possibly version number of the program that
5157 compiled the code in the symbol table.
5158 The contents of this string is up to the compiler.
5159 If no producer information is available then @code{None} is returned.
5160 This attribute is not writable.
5161 @end defvar
5162
5163 A @code{gdb.Symtab} object has the following methods:
5164
5165 @defun Symtab.is_valid ()
5166 Returns @code{True} if the @code{gdb.Symtab} object is valid,
5167 @code{False} if not. A @code{gdb.Symtab} object can become invalid if
5168 the symbol table it refers to does not exist in @value{GDBN} any
5169 longer. All other @code{gdb.Symtab} methods will throw an exception
5170 if it is invalid at the time the method is called.
5171 @end defun
5172
5173 @defun Symtab.fullname ()
5174 Return the symbol table's source absolute file name.
5175 @end defun
5176
5177 @defun Symtab.global_block ()
5178 Return the global block of the underlying symbol table.
5179 @xref{Blocks In Python}.
5180 @end defun
5181
5182 @defun Symtab.static_block ()
5183 Return the static block of the underlying symbol table.
5184 @xref{Blocks In Python}.
5185 @end defun
5186
5187 @defun Symtab.linetable ()
5188 Return the line table associated with the symbol table.
5189 @xref{Line Tables In Python}.
5190 @end defun
5191
5192 @node Line Tables In Python
5193 @subsubsection Manipulating line tables using Python
5194
5195 @cindex line tables in python
5196 @tindex gdb.LineTable
5197
5198 Python code can request and inspect line table information from a
5199 symbol table that is loaded in @value{GDBN}. A line table is a
5200 mapping of source lines to their executable locations in memory. To
5201 acquire the line table information for a particular symbol table, use
5202 the @code{linetable} function (@pxref{Symbol Tables In Python}).
5203
5204 A @code{gdb.LineTable} is iterable. The iterator returns
5205 @code{LineTableEntry} objects that correspond to the source line and
5206 address for each line table entry. @code{LineTableEntry} objects have
5207 the following attributes:
5208
5209 @defvar LineTableEntry.line
5210 The source line number for this line table entry. This number
5211 corresponds to the actual line of source. This attribute is not
5212 writable.
5213 @end defvar
5214
5215 @defvar LineTableEntry.pc
5216 The address that is associated with the line table entry where the
5217 executable code for that source line resides in memory. This
5218 attribute is not writable.
5219 @end defvar
5220
5221 As there can be multiple addresses for a single source line, you may
5222 receive multiple @code{LineTableEntry} objects with matching
5223 @code{line} attributes, but with different @code{pc} attributes. The
5224 iterator is sorted in ascending @code{pc} order. Here is a small
5225 example illustrating iterating over a line table.
5226
5227 @smallexample
5228 symtab = gdb.selected_frame().find_sal().symtab
5229 linetable = symtab.linetable()
5230 for line in linetable:
5231 print "Line: "+str(line.line)+" Address: "+hex(line.pc)
5232 @end smallexample
5233
5234 This will have the following output:
5235
5236 @smallexample
5237 Line: 33 Address: 0x4005c8L
5238 Line: 37 Address: 0x4005caL
5239 Line: 39 Address: 0x4005d2L
5240 Line: 40 Address: 0x4005f8L
5241 Line: 42 Address: 0x4005ffL
5242 Line: 44 Address: 0x400608L
5243 Line: 42 Address: 0x40060cL
5244 Line: 45 Address: 0x400615L
5245 @end smallexample
5246
5247 In addition to being able to iterate over a @code{LineTable}, it also
5248 has the following direct access methods:
5249
5250 @defun LineTable.line (line)
5251 Return a Python @code{Tuple} of @code{LineTableEntry} objects for any
5252 entries in the line table for the given @var{line}, which specifies
5253 the source code line. If there are no entries for that source code
5254 @var{line}, the Python @code{None} is returned.
5255 @end defun
5256
5257 @defun LineTable.has_line (line)
5258 Return a Python @code{Boolean} indicating whether there is an entry in
5259 the line table for this source line. Return @code{True} if an entry
5260 is found, or @code{False} if not.
5261 @end defun
5262
5263 @defun LineTable.source_lines ()
5264 Return a Python @code{List} of the source line numbers in the symbol
5265 table. Only lines with executable code locations are returned. The
5266 contents of the @code{List} will just be the source line entries
5267 represented as Python @code{Long} values.
5268 @end defun
5269
5270 @node Breakpoints In Python
5271 @subsubsection Manipulating breakpoints using Python
5272
5273 @cindex breakpoints in python
5274 @tindex gdb.Breakpoint
5275
5276 Python code can manipulate breakpoints via the @code{gdb.Breakpoint}
5277 class.
5278
5279 A breakpoint can be created using one of the two forms of the
5280 @code{gdb.Breakpoint} constructor. The first one accepts a string
5281 like one would pass to the @code{break}
5282 (@pxref{Set Breaks,,Setting Breakpoints}) and @code{watch}
5283 (@pxref{Set Watchpoints, , Setting Watchpoints}) commands, and can be used to
5284 create both breakpoints and watchpoints. The second accepts separate Python
5285 arguments similar to @ref{Explicit Locations}, and can only be used to create
5286 breakpoints.
5287
5288 @defun Breakpoint.__init__ (spec @r{[}, type @r{][}, wp_class @r{][}, internal @r{][}, temporary @r{][}, qualified @r{]})
5289 Create a new breakpoint according to @var{spec}, which is a string naming the
5290 location of a breakpoint, or an expression that defines a watchpoint. The
5291 string should describe a location in a format recognized by the @code{break}
5292 command (@pxref{Set Breaks,,Setting Breakpoints}) or, in the case of a
5293 watchpoint, by the @code{watch} command
5294 (@pxref{Set Watchpoints, , Setting Watchpoints}).
5295
5296 The optional @var{type} argument specifies the type of the breakpoint to create,
5297 as defined below.
5298
5299 The optional @var{wp_class} argument defines the class of watchpoint to create,
5300 if @var{type} is @code{gdb.BP_WATCHPOINT}. If @var{wp_class} is omitted, it
5301 defaults to @code{gdb.WP_WRITE}.
5302
5303 The optional @var{internal} argument allows the breakpoint to become invisible
5304 to the user. The breakpoint will neither be reported when created, nor will it
5305 be listed in the output from @code{info breakpoints} (but will be listed with
5306 the @code{maint info breakpoints} command).
5307
5308 The optional @var{temporary} argument makes the breakpoint a temporary
5309 breakpoint. Temporary breakpoints are deleted after they have been hit. Any
5310 further access to the Python breakpoint after it has been hit will result in a
5311 runtime error (as that breakpoint has now been automatically deleted).
5312
5313 The optional @var{qualified} argument is a boolean that allows interpreting
5314 the function passed in @code{spec} as a fully-qualified name. It is equivalent
5315 to @code{break}'s @code{-qualified} flag (@pxref{Linespec Locations} and
5316 @ref{Explicit Locations}).
5317
5318 @end defun
5319
5320 @defun Breakpoint.__init__ (@r{[} source @r{][}, function @r{][}, label @r{][}, line @r{]}, @r{][} internal @r{][}, temporary @r{][}, qualified @r{]})
5321 This second form of creating a new breakpoint specifies the explicit
5322 location (@pxref{Explicit Locations}) using keywords. The new breakpoint will
5323 be created in the specified source file @var{source}, at the specified
5324 @var{function}, @var{label} and @var{line}.
5325
5326 @var{internal}, @var{temporary} and @var{qualified} have the same usage as
5327 explained previously.
5328 @end defun
5329
5330 The available types are represented by constants defined in the @code{gdb}
5331 module:
5332
5333 @vtable @code
5334 @vindex BP_BREAKPOINT
5335 @item gdb.BP_BREAKPOINT
5336 Normal code breakpoint.
5337
5338 @vindex BP_WATCHPOINT
5339 @item gdb.BP_WATCHPOINT
5340 Watchpoint breakpoint.
5341
5342 @vindex BP_HARDWARE_WATCHPOINT
5343 @item gdb.BP_HARDWARE_WATCHPOINT
5344 Hardware assisted watchpoint.
5345
5346 @vindex BP_READ_WATCHPOINT
5347 @item gdb.BP_READ_WATCHPOINT
5348 Hardware assisted read watchpoint.
5349
5350 @vindex BP_ACCESS_WATCHPOINT
5351 @item gdb.BP_ACCESS_WATCHPOINT
5352 Hardware assisted access watchpoint.
5353 @end vtable
5354
5355 The available watchpoint types represented by constants are defined in the
5356 @code{gdb} module:
5357
5358 @vtable @code
5359 @vindex WP_READ
5360 @item gdb.WP_READ
5361 Read only watchpoint.
5362
5363 @vindex WP_WRITE
5364 @item gdb.WP_WRITE
5365 Write only watchpoint.
5366
5367 @vindex WP_ACCESS
5368 @item gdb.WP_ACCESS
5369 Read/Write watchpoint.
5370 @end vtable
5371
5372 @defun Breakpoint.stop (self)
5373 The @code{gdb.Breakpoint} class can be sub-classed and, in
5374 particular, you may choose to implement the @code{stop} method.
5375 If this method is defined in a sub-class of @code{gdb.Breakpoint},
5376 it will be called when the inferior reaches any location of a
5377 breakpoint which instantiates that sub-class. If the method returns
5378 @code{True}, the inferior will be stopped at the location of the
5379 breakpoint, otherwise the inferior will continue.
5380
5381 If there are multiple breakpoints at the same location with a
5382 @code{stop} method, each one will be called regardless of the
5383 return status of the previous. This ensures that all @code{stop}
5384 methods have a chance to execute at that location. In this scenario
5385 if one of the methods returns @code{True} but the others return
5386 @code{False}, the inferior will still be stopped.
5387
5388 You should not alter the execution state of the inferior (i.e.@:, step,
5389 next, etc.), alter the current frame context (i.e.@:, change the current
5390 active frame), or alter, add or delete any breakpoint. As a general
5391 rule, you should not alter any data within @value{GDBN} or the inferior
5392 at this time.
5393
5394 Example @code{stop} implementation:
5395
5396 @smallexample
5397 class MyBreakpoint (gdb.Breakpoint):
5398 def stop (self):
5399 inf_val = gdb.parse_and_eval("foo")
5400 if inf_val == 3:
5401 return True
5402 return False
5403 @end smallexample
5404 @end defun
5405
5406 @defun Breakpoint.is_valid ()
5407 Return @code{True} if this @code{Breakpoint} object is valid,
5408 @code{False} otherwise. A @code{Breakpoint} object can become invalid
5409 if the user deletes the breakpoint. In this case, the object still
5410 exists, but the underlying breakpoint does not. In the cases of
5411 watchpoint scope, the watchpoint remains valid even if execution of the
5412 inferior leaves the scope of that watchpoint.
5413 @end defun
5414
5415 @defun Breakpoint.delete ()
5416 Permanently deletes the @value{GDBN} breakpoint. This also
5417 invalidates the Python @code{Breakpoint} object. Any further access
5418 to this object's attributes or methods will raise an error.
5419 @end defun
5420
5421 @defvar Breakpoint.enabled
5422 This attribute is @code{True} if the breakpoint is enabled, and
5423 @code{False} otherwise. This attribute is writable. You can use it to enable
5424 or disable the breakpoint.
5425 @end defvar
5426
5427 @defvar Breakpoint.silent
5428 This attribute is @code{True} if the breakpoint is silent, and
5429 @code{False} otherwise. This attribute is writable.
5430
5431 Note that a breakpoint can also be silent if it has commands and the
5432 first command is @code{silent}. This is not reported by the
5433 @code{silent} attribute.
5434 @end defvar
5435
5436 @defvar Breakpoint.pending
5437 This attribute is @code{True} if the breakpoint is pending, and
5438 @code{False} otherwise. @xref{Set Breaks}. This attribute is
5439 read-only.
5440 @end defvar
5441
5442 @anchor{python_breakpoint_thread}
5443 @defvar Breakpoint.thread
5444 If the breakpoint is thread-specific, this attribute holds the
5445 thread's global id. If the breakpoint is not thread-specific, this
5446 attribute is @code{None}. This attribute is writable.
5447 @end defvar
5448
5449 @defvar Breakpoint.task
5450 If the breakpoint is Ada task-specific, this attribute holds the Ada task
5451 id. If the breakpoint is not task-specific (or the underlying
5452 language is not Ada), this attribute is @code{None}. This attribute
5453 is writable.
5454 @end defvar
5455
5456 @defvar Breakpoint.ignore_count
5457 This attribute holds the ignore count for the breakpoint, an integer.
5458 This attribute is writable.
5459 @end defvar
5460
5461 @defvar Breakpoint.number
5462 This attribute holds the breakpoint's number --- the identifier used by
5463 the user to manipulate the breakpoint. This attribute is not writable.
5464 @end defvar
5465
5466 @defvar Breakpoint.type
5467 This attribute holds the breakpoint's type --- the identifier used to
5468 determine the actual breakpoint type or use-case. This attribute is not
5469 writable.
5470 @end defvar
5471
5472 @defvar Breakpoint.visible
5473 This attribute tells whether the breakpoint is visible to the user
5474 when set, or when the @samp{info breakpoints} command is run. This
5475 attribute is not writable.
5476 @end defvar
5477
5478 @defvar Breakpoint.temporary
5479 This attribute indicates whether the breakpoint was created as a
5480 temporary breakpoint. Temporary breakpoints are automatically deleted
5481 after that breakpoint has been hit. Access to this attribute, and all
5482 other attributes and functions other than the @code{is_valid}
5483 function, will result in an error after the breakpoint has been hit
5484 (as it has been automatically deleted). This attribute is not
5485 writable.
5486 @end defvar
5487
5488 @defvar Breakpoint.hit_count
5489 This attribute holds the hit count for the breakpoint, an integer.
5490 This attribute is writable, but currently it can only be set to zero.
5491 @end defvar
5492
5493 @defvar Breakpoint.location
5494 This attribute holds the location of the breakpoint, as specified by
5495 the user. It is a string. If the breakpoint does not have a location
5496 (that is, it is a watchpoint) the attribute's value is @code{None}. This
5497 attribute is not writable.
5498 @end defvar
5499
5500 @defvar Breakpoint.expression
5501 This attribute holds a breakpoint expression, as specified by
5502 the user. It is a string. If the breakpoint does not have an
5503 expression (the breakpoint is not a watchpoint) the attribute's value
5504 is @code{None}. This attribute is not writable.
5505 @end defvar
5506
5507 @defvar Breakpoint.condition
5508 This attribute holds the condition of the breakpoint, as specified by
5509 the user. It is a string. If there is no condition, this attribute's
5510 value is @code{None}. This attribute is writable.
5511 @end defvar
5512
5513 @defvar Breakpoint.commands
5514 This attribute holds the commands attached to the breakpoint. If
5515 there are commands, this attribute's value is a string holding all the
5516 commands, separated by newlines. If there are no commands, this
5517 attribute is @code{None}. This attribute is writable.
5518 @end defvar
5519
5520 @node Finish Breakpoints in Python
5521 @subsubsection Finish Breakpoints
5522
5523 @cindex python finish breakpoints
5524 @tindex gdb.FinishBreakpoint
5525
5526 A finish breakpoint is a temporary breakpoint set at the return address of
5527 a frame, based on the @code{finish} command. @code{gdb.FinishBreakpoint}
5528 extends @code{gdb.Breakpoint}. The underlying breakpoint will be disabled
5529 and deleted when the execution will run out of the breakpoint scope (i.e.@:
5530 @code{Breakpoint.stop} or @code{FinishBreakpoint.out_of_scope} triggered).
5531 Finish breakpoints are thread specific and must be create with the right
5532 thread selected.
5533
5534 @defun FinishBreakpoint.__init__ (@r{[}frame@r{]} @r{[}, internal@r{]})
5535 Create a finish breakpoint at the return address of the @code{gdb.Frame}
5536 object @var{frame}. If @var{frame} is not provided, this defaults to the
5537 newest frame. The optional @var{internal} argument allows the breakpoint to
5538 become invisible to the user. @xref{Breakpoints In Python}, for further
5539 details about this argument.
5540 @end defun
5541
5542 @defun FinishBreakpoint.out_of_scope (self)
5543 In some circumstances (e.g.@: @code{longjmp}, C@t{++} exceptions, @value{GDBN}
5544 @code{return} command, @dots{}), a function may not properly terminate, and
5545 thus never hit the finish breakpoint. When @value{GDBN} notices such a
5546 situation, the @code{out_of_scope} callback will be triggered.
5547
5548 You may want to sub-class @code{gdb.FinishBreakpoint} and override this
5549 method:
5550
5551 @smallexample
5552 class MyFinishBreakpoint (gdb.FinishBreakpoint)
5553 def stop (self):
5554 print "normal finish"
5555 return True
5556
5557 def out_of_scope ():
5558 print "abnormal finish"
5559 @end smallexample
5560 @end defun
5561
5562 @defvar FinishBreakpoint.return_value
5563 When @value{GDBN} is stopped at a finish breakpoint and the frame
5564 used to build the @code{gdb.FinishBreakpoint} object had debug symbols, this
5565 attribute will contain a @code{gdb.Value} object corresponding to the return
5566 value of the function. The value will be @code{None} if the function return
5567 type is @code{void} or if the return value was not computable. This attribute
5568 is not writable.
5569 @end defvar
5570
5571 @node Lazy Strings In Python
5572 @subsubsection Python representation of lazy strings
5573
5574 @cindex lazy strings in python
5575 @tindex gdb.LazyString
5576
5577 A @dfn{lazy string} is a string whose contents is not retrieved or
5578 encoded until it is needed.
5579
5580 A @code{gdb.LazyString} is represented in @value{GDBN} as an
5581 @code{address} that points to a region of memory, an @code{encoding}
5582 that will be used to encode that region of memory, and a @code{length}
5583 to delimit the region of memory that represents the string. The
5584 difference between a @code{gdb.LazyString} and a string wrapped within
5585 a @code{gdb.Value} is that a @code{gdb.LazyString} will be treated
5586 differently by @value{GDBN} when printing. A @code{gdb.LazyString} is
5587 retrieved and encoded during printing, while a @code{gdb.Value}
5588 wrapping a string is immediately retrieved and encoded on creation.
5589
5590 A @code{gdb.LazyString} object has the following functions:
5591
5592 @defun LazyString.value ()
5593 Convert the @code{gdb.LazyString} to a @code{gdb.Value}. This value
5594 will point to the string in memory, but will lose all the delayed
5595 retrieval, encoding and handling that @value{GDBN} applies to a
5596 @code{gdb.LazyString}.
5597 @end defun
5598
5599 @defvar LazyString.address
5600 This attribute holds the address of the string. This attribute is not
5601 writable.
5602 @end defvar
5603
5604 @defvar LazyString.length
5605 This attribute holds the length of the string in characters. If the
5606 length is -1, then the string will be fetched and encoded up to the
5607 first null of appropriate width. This attribute is not writable.
5608 @end defvar
5609
5610 @defvar LazyString.encoding
5611 This attribute holds the encoding that will be applied to the string
5612 when the string is printed by @value{GDBN}. If the encoding is not
5613 set, or contains an empty string, then @value{GDBN} will select the
5614 most appropriate encoding when the string is printed. This attribute
5615 is not writable.
5616 @end defvar
5617
5618 @defvar LazyString.type
5619 This attribute holds the type that is represented by the lazy string's
5620 type. For a lazy string this is a pointer or array type. To
5621 resolve this to the lazy string's character type, use the type's
5622 @code{target} method. @xref{Types In Python}. This attribute is not
5623 writable.
5624 @end defvar
5625
5626 @node Architectures In Python
5627 @subsubsection Python representation of architectures
5628 @cindex Python architectures
5629
5630 @value{GDBN} uses architecture specific parameters and artifacts in a
5631 number of its various computations. An architecture is represented
5632 by an instance of the @code{gdb.Architecture} class.
5633
5634 A @code{gdb.Architecture} class has the following methods:
5635
5636 @defun Architecture.name ()
5637 Return the name (string value) of the architecture.
5638 @end defun
5639
5640 @defun Architecture.disassemble (@var{start_pc} @r{[}, @var{end_pc} @r{[}, @var{count}@r{]]})
5641 Return a list of disassembled instructions starting from the memory
5642 address @var{start_pc}. The optional arguments @var{end_pc} and
5643 @var{count} determine the number of instructions in the returned list.
5644 If both the optional arguments @var{end_pc} and @var{count} are
5645 specified, then a list of at most @var{count} disassembled instructions
5646 whose start address falls in the closed memory address interval from
5647 @var{start_pc} to @var{end_pc} are returned. If @var{end_pc} is not
5648 specified, but @var{count} is specified, then @var{count} number of
5649 instructions starting from the address @var{start_pc} are returned. If
5650 @var{count} is not specified but @var{end_pc} is specified, then all
5651 instructions whose start address falls in the closed memory address
5652 interval from @var{start_pc} to @var{end_pc} are returned. If neither
5653 @var{end_pc} nor @var{count} are specified, then a single instruction at
5654 @var{start_pc} is returned. For all of these cases, each element of the
5655 returned list is a Python @code{dict} with the following string keys:
5656
5657 @table @code
5658
5659 @item addr
5660 The value corresponding to this key is a Python long integer capturing
5661 the memory address of the instruction.
5662
5663 @item asm
5664 The value corresponding to this key is a string value which represents
5665 the instruction with assembly language mnemonics. The assembly
5666 language flavor used is the same as that specified by the current CLI
5667 variable @code{disassembly-flavor}. @xref{Machine Code}.
5668
5669 @item length
5670 The value corresponding to this key is the length (integer value) of the
5671 instruction in bytes.
5672
5673 @end table
5674 @end defun
5675
5676 @node Python Auto-loading
5677 @subsection Python Auto-loading
5678 @cindex Python auto-loading
5679
5680 When a new object file is read (for example, due to the @code{file}
5681 command, or because the inferior has loaded a shared library),
5682 @value{GDBN} will look for Python support scripts in several ways:
5683 @file{@var{objfile}-gdb.py} and @code{.debug_gdb_scripts} section.
5684 @xref{Auto-loading extensions}.
5685
5686 The auto-loading feature is useful for supplying application-specific
5687 debugging commands and scripts.
5688
5689 Auto-loading can be enabled or disabled,
5690 and the list of auto-loaded scripts can be printed.
5691
5692 @table @code
5693 @anchor{set auto-load python-scripts}
5694 @kindex set auto-load python-scripts
5695 @item set auto-load python-scripts [on|off]
5696 Enable or disable the auto-loading of Python scripts.
5697
5698 @anchor{show auto-load python-scripts}
5699 @kindex show auto-load python-scripts
5700 @item show auto-load python-scripts
5701 Show whether auto-loading of Python scripts is enabled or disabled.
5702
5703 @anchor{info auto-load python-scripts}
5704 @kindex info auto-load python-scripts
5705 @cindex print list of auto-loaded Python scripts
5706 @item info auto-load python-scripts [@var{regexp}]
5707 Print the list of all Python scripts that @value{GDBN} auto-loaded.
5708
5709 Also printed is the list of Python scripts that were mentioned in
5710 the @code{.debug_gdb_scripts} section and were either not found
5711 (@pxref{dotdebug_gdb_scripts section}) or were not auto-loaded due to
5712 @code{auto-load safe-path} rejection (@pxref{Auto-loading}).
5713 This is useful because their names are not printed when @value{GDBN}
5714 tries to load them and fails. There may be many of them, and printing
5715 an error message for each one is problematic.
5716
5717 If @var{regexp} is supplied only Python scripts with matching names are printed.
5718
5719 Example:
5720
5721 @smallexample
5722 (gdb) info auto-load python-scripts
5723 Loaded Script
5724 Yes py-section-script.py
5725 full name: /tmp/py-section-script.py
5726 No my-foo-pretty-printers.py
5727 @end smallexample
5728 @end table
5729
5730 When reading an auto-loaded file or script, @value{GDBN} sets the
5731 @dfn{current objfile}. This is available via the @code{gdb.current_objfile}
5732 function (@pxref{Objfiles In Python}). This can be useful for
5733 registering objfile-specific pretty-printers and frame-filters.
5734
5735 @node Python modules
5736 @subsection Python modules
5737 @cindex python modules
5738
5739 @value{GDBN} comes with several modules to assist writing Python code.
5740
5741 @menu
5742 * gdb.printing:: Building and registering pretty-printers.
5743 * gdb.types:: Utilities for working with types.
5744 * gdb.prompt:: Utilities for prompt value substitution.
5745 @end menu
5746
5747 @node gdb.printing
5748 @subsubsection gdb.printing
5749 @cindex gdb.printing
5750
5751 This module provides a collection of utilities for working with
5752 pretty-printers.
5753
5754 @table @code
5755 @item PrettyPrinter (@var{name}, @var{subprinters}=None)
5756 This class specifies the API that makes @samp{info pretty-printer},
5757 @samp{enable pretty-printer} and @samp{disable pretty-printer} work.
5758 Pretty-printers should generally inherit from this class.
5759
5760 @item SubPrettyPrinter (@var{name})
5761 For printers that handle multiple types, this class specifies the
5762 corresponding API for the subprinters.
5763
5764 @item RegexpCollectionPrettyPrinter (@var{name})
5765 Utility class for handling multiple printers, all recognized via
5766 regular expressions.
5767 @xref{Writing a Pretty-Printer}, for an example.
5768
5769 @item FlagEnumerationPrinter (@var{name})
5770 A pretty-printer which handles printing of @code{enum} values. Unlike
5771 @value{GDBN}'s built-in @code{enum} printing, this printer attempts to
5772 work properly when there is some overlap between the enumeration
5773 constants. The argument @var{name} is the name of the printer and
5774 also the name of the @code{enum} type to look up.
5775
5776 @item register_pretty_printer (@var{obj}, @var{printer}, @var{replace}=False)
5777 Register @var{printer} with the pretty-printer list of @var{obj}.
5778 If @var{replace} is @code{True} then any existing copy of the printer
5779 is replaced. Otherwise a @code{RuntimeError} exception is raised
5780 if a printer with the same name already exists.
5781 @end table
5782
5783 @node gdb.types
5784 @subsubsection gdb.types
5785 @cindex gdb.types
5786
5787 This module provides a collection of utilities for working with
5788 @code{gdb.Type} objects.
5789
5790 @table @code
5791 @item get_basic_type (@var{type})
5792 Return @var{type} with const and volatile qualifiers stripped,
5793 and with typedefs and C@t{++} references converted to the underlying type.
5794
5795 C@t{++} example:
5796
5797 @smallexample
5798 typedef const int const_int;
5799 const_int foo (3);
5800 const_int& foo_ref (foo);
5801 int main () @{ return 0; @}
5802 @end smallexample
5803
5804 Then in gdb:
5805
5806 @smallexample
5807 (gdb) start
5808 (gdb) python import gdb.types
5809 (gdb) python foo_ref = gdb.parse_and_eval("foo_ref")
5810 (gdb) python print gdb.types.get_basic_type(foo_ref.type)
5811 int
5812 @end smallexample
5813
5814 @item has_field (@var{type}, @var{field})
5815 Return @code{True} if @var{type}, assumed to be a type with fields
5816 (e.g., a structure or union), has field @var{field}.
5817
5818 @item make_enum_dict (@var{enum_type})
5819 Return a Python @code{dictionary} type produced from @var{enum_type}.
5820
5821 @item deep_items (@var{type})
5822 Returns a Python iterator similar to the standard
5823 @code{gdb.Type.iteritems} method, except that the iterator returned
5824 by @code{deep_items} will recursively traverse anonymous struct or
5825 union fields. For example:
5826
5827 @smallexample
5828 struct A
5829 @{
5830 int a;
5831 union @{
5832 int b0;
5833 int b1;
5834 @};
5835 @};
5836 @end smallexample
5837
5838 @noindent
5839 Then in @value{GDBN}:
5840 @smallexample
5841 (@value{GDBP}) python import gdb.types
5842 (@value{GDBP}) python struct_a = gdb.lookup_type("struct A")
5843 (@value{GDBP}) python print struct_a.keys ()
5844 @{['a', '']@}
5845 (@value{GDBP}) python print [k for k,v in gdb.types.deep_items(struct_a)]
5846 @{['a', 'b0', 'b1']@}
5847 @end smallexample
5848
5849 @item get_type_recognizers ()
5850 Return a list of the enabled type recognizers for the current context.
5851 This is called by @value{GDBN} during the type-printing process
5852 (@pxref{Type Printing API}).
5853
5854 @item apply_type_recognizers (recognizers, type_obj)
5855 Apply the type recognizers, @var{recognizers}, to the type object
5856 @var{type_obj}. If any recognizer returns a string, return that
5857 string. Otherwise, return @code{None}. This is called by
5858 @value{GDBN} during the type-printing process (@pxref{Type Printing
5859 API}).
5860
5861 @item register_type_printer (locus, printer)
5862 This is a convenience function to register a type printer
5863 @var{printer}. The printer must implement the type printer protocol.
5864 The @var{locus} argument is either a @code{gdb.Objfile}, in which case
5865 the printer is registered with that objfile; a @code{gdb.Progspace},
5866 in which case the printer is registered with that progspace; or
5867 @code{None}, in which case the printer is registered globally.
5868
5869 @item TypePrinter
5870 This is a base class that implements the type printer protocol. Type
5871 printers are encouraged, but not required, to derive from this class.
5872 It defines a constructor:
5873
5874 @defmethod TypePrinter __init__ (self, name)
5875 Initialize the type printer with the given name. The new printer
5876 starts in the enabled state.
5877 @end defmethod
5878
5879 @end table
5880
5881 @node gdb.prompt
5882 @subsubsection gdb.prompt
5883 @cindex gdb.prompt
5884
5885 This module provides a method for prompt value-substitution.
5886
5887 @table @code
5888 @item substitute_prompt (@var{string})
5889 Return @var{string} with escape sequences substituted by values. Some
5890 escape sequences take arguments. You can specify arguments inside
5891 ``@{@}'' immediately following the escape sequence.
5892
5893 The escape sequences you can pass to this function are:
5894
5895 @table @code
5896 @item \\
5897 Substitute a backslash.
5898 @item \e
5899 Substitute an ESC character.
5900 @item \f
5901 Substitute the selected frame; an argument names a frame parameter.
5902 @item \n
5903 Substitute a newline.
5904 @item \p
5905 Substitute a parameter's value; the argument names the parameter.
5906 @item \r
5907 Substitute a carriage return.
5908 @item \t
5909 Substitute the selected thread; an argument names a thread parameter.
5910 @item \v
5911 Substitute the version of GDB.
5912 @item \w
5913 Substitute the current working directory.
5914 @item \[
5915 Begin a sequence of non-printing characters. These sequences are
5916 typically used with the ESC character, and are not counted in the string
5917 length. Example: ``\[\e[0;34m\](gdb)\[\e[0m\]'' will return a
5918 blue-colored ``(gdb)'' prompt where the length is five.
5919 @item \]
5920 End a sequence of non-printing characters.
5921 @end table
5922
5923 For example:
5924
5925 @smallexample
5926 substitute_prompt ("frame: \f, args: \p@{print frame-arguments@}")
5927 @end smallexample
5928
5929 @exdent will return the string:
5930
5931 @smallexample
5932 "frame: main, args: scalars"
5933 @end smallexample
5934 @end table
This page took 0.169049 seconds and 4 git commands to generate.