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