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