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