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