forked from bminor/binutils-gdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython.texi
5202 lines (4215 loc) · 185 KB
/
python.texi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
@c Copyright (C) 2008-2016 Free Software Foundation, Inc.
@c Permission is granted to copy, distribute and/or modify this document
@c under the terms of the GNU Free Documentation License, Version 1.3 or
@c any later version published by the Free Software Foundation; with the
@c Invariant Sections being ``Free Software'' and ``Free Software Needs
@c Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,''
@c and with the Back-Cover Texts as in (a) below.
@c
@c (a) The FSF's Back-Cover Text is: ``You are free to copy and modify
@c this GNU Manual. Buying copies from GNU Press supports the FSF in
@c developing GNU and promoting software freedom.''
@node Python
@section Extending @value{GDBN} using Python
@cindex python scripting
@cindex scripting with python
You can extend @value{GDBN} using the @uref{http://www.python.org/,
Python programming language}. This feature is available only if
@value{GDBN} was configured using @option{--with-python}.
@cindex python directory
Python scripts used by @value{GDBN} should be installed in
@file{@var{data-directory}/python}, where @var{data-directory} is
the data directory as determined at @value{GDBN} startup (@pxref{Data Files}).
This directory, known as the @dfn{python directory},
is automatically added to the Python Search Path in order to allow
the Python interpreter to locate all scripts installed at this location.
Additionally, @value{GDBN} commands and convenience functions which
are written in Python and are located in the
@file{@var{data-directory}/python/gdb/command} or
@file{@var{data-directory}/python/gdb/function} directories are
automatically imported when @value{GDBN} starts.
@menu
* Python Commands:: Accessing Python from @value{GDBN}.
* Python API:: Accessing @value{GDBN} from Python.
* Python Auto-loading:: Automatically loading Python code.
* Python modules:: Python modules provided by @value{GDBN}.
@end menu
@node Python Commands
@subsection Python Commands
@cindex python commands
@cindex commands to access python
@value{GDBN} provides two commands for accessing the Python interpreter,
and one related setting:
@table @code
@kindex python-interactive
@kindex pi
@item python-interactive @r{[}@var{command}@r{]}
@itemx pi @r{[}@var{command}@r{]}
Without an argument, the @code{python-interactive} command can be used
to start an interactive Python prompt. To return to @value{GDBN},
type the @code{EOF} character (e.g., @kbd{Ctrl-D} on an empty prompt).
Alternatively, a single-line Python command can be given as an
argument and evaluated. If the command is an expression, the result
will be printed; otherwise, nothing will be printed. For example:
@smallexample
(@value{GDBP}) python-interactive 2 + 3
5
@end smallexample
@kindex python
@kindex py
@item python @r{[}@var{command}@r{]}
@itemx py @r{[}@var{command}@r{]}
The @code{python} command can be used to evaluate Python code.
If given an argument, the @code{python} command will evaluate the
argument as a Python command. For example:
@smallexample
(@value{GDBP}) python print 23
23
@end smallexample
If you do not provide an argument to @code{python}, it will act as a
multi-line command, like @code{define}. In this case, the Python
script is made up of subsequent command lines, given after the
@code{python} command. This command list is terminated using a line
containing @code{end}. For example:
@smallexample
(@value{GDBP}) python
Type python script
End with a line saying just "end".
>print 23
>end
23
@end smallexample
@kindex set python print-stack
@item set python print-stack
By default, @value{GDBN} will print only the message component of a
Python exception when an error occurs in a Python script. This can be
controlled using @code{set python print-stack}: if @code{full}, then
full Python stack printing is enabled; if @code{none}, then Python stack
and message printing is disabled; if @code{message}, the default, only
the message component of the error is printed.
@end table
It is also possible to execute a Python script from the @value{GDBN}
interpreter:
@table @code
@item source @file{script-name}
The script name must end with @samp{.py} and @value{GDBN} must be configured
to recognize the script language based on filename extension using
the @code{script-extension} setting. @xref{Extending GDB, ,Extending GDB}.
@item python execfile ("script-name")
This method is based on the @code{execfile} Python built-in function,
and thus is always available.
@end table
@node Python API
@subsection Python API
@cindex python api
@cindex programming in python
You can get quick online help for @value{GDBN}'s Python API by issuing
the command @w{@kbd{python help (gdb)}}.
Functions and methods which have two or more optional arguments allow
them to be specified using keyword syntax. This allows passing some
optional arguments while skipping others. Example:
@w{@code{gdb.some_function ('foo', bar = 1, baz = 2)}}.
@menu
* Basic Python:: Basic Python Functions.
* Exception Handling:: How Python exceptions are translated.
* Values From Inferior:: Python representation of values.
* Types In Python:: Python representation of types.
* Pretty Printing API:: Pretty-printing values.
* Selecting Pretty-Printers:: How GDB chooses a pretty-printer.
* Writing a Pretty-Printer:: Writing a Pretty-Printer.
* Type Printing API:: Pretty-printing types.
* Frame Filter API:: Filtering Frames.
* Frame Decorator API:: Decorating Frames.
* Writing a Frame Filter:: Writing a Frame Filter.
* Unwinding Frames in Python:: Writing frame unwinder.
* Xmethods In Python:: Adding and replacing methods of C++ classes.
* Xmethod API:: Xmethod types.
* Writing an Xmethod:: Writing an xmethod.
* Inferiors In Python:: Python representation of inferiors (processes)
* Events In Python:: Listening for events from @value{GDBN}.
* Threads In Python:: Accessing inferior threads from Python.
* Commands In Python:: Implementing new commands in Python.
* Parameters In Python:: Adding new @value{GDBN} parameters.
* Functions In Python:: Writing new convenience functions.
* Progspaces In Python:: Program spaces.
* Objfiles In Python:: Object files.
* Frames In Python:: Accessing inferior stack frames from Python.
* Blocks In Python:: Accessing blocks from Python.
* Symbols In Python:: Python representation of symbols.
* Symbol Tables In Python:: Python representation of symbol tables.
* Line Tables In Python:: Python representation of line tables.
* Breakpoints In Python:: Manipulating breakpoints using Python.
* Finish Breakpoints in Python:: Setting Breakpoints on function return
using Python.
* Lazy Strings In Python:: Python representation of lazy strings.
* Architectures In Python:: Python representation of architectures.
@end menu
@node Basic Python
@subsubsection Basic Python
@cindex python stdout
@cindex python pagination
At startup, @value{GDBN} overrides Python's @code{sys.stdout} and
@code{sys.stderr} to print using @value{GDBN}'s output-paging streams.
A Python program which outputs to one of these streams may have its
output interrupted by the user (@pxref{Screen Size}). In this
situation, a Python @code{KeyboardInterrupt} exception is thrown.
Some care must be taken when writing Python code to run in
@value{GDBN}. Two things worth noting in particular:
@itemize @bullet
@item
@value{GDBN} install handlers for @code{SIGCHLD} and @code{SIGINT}.
Python code must not override these, or even change the options using
@code{sigaction}. If your program changes the handling of these
signals, @value{GDBN} will most likely stop working correctly. Note
that it is unfortunately common for GUI toolkits to install a
@code{SIGCHLD} handler.
@item
@value{GDBN} takes care to mark its internal file descriptors as
close-on-exec. However, this cannot be done in a thread-safe way on
all platforms. Your Python programs should be aware of this and
should both create new file descriptors with the close-on-exec flag
set and arrange to close unneeded file descriptors before starting a
child process.
@end itemize
@cindex python functions
@cindex python module
@cindex gdb module
@value{GDBN} introduces a new Python module, named @code{gdb}. All
methods and classes added by @value{GDBN} are placed in this module.
@value{GDBN} automatically @code{import}s the @code{gdb} module for
use in all scripts evaluated by the @code{python} command.
@findex gdb.PYTHONDIR
@defvar gdb.PYTHONDIR
A string containing the python directory (@pxref{Python}).
@end defvar
@findex gdb.execute
@defun gdb.execute (command @r{[}, from_tty @r{[}, to_string@r{]]})
Evaluate @var{command}, a string, as a @value{GDBN} CLI command.
If a GDB exception happens while @var{command} runs, it is
translated as described in @ref{Exception Handling,,Exception Handling}.
The @var{from_tty} flag specifies whether @value{GDBN} ought to consider this
command as having originated from the user invoking it interactively.
It must be a boolean value. If omitted, it defaults to @code{False}.
By default, any output produced by @var{command} is sent to
@value{GDBN}'s standard output (and to the log output if logging is
turned on). If the @var{to_string} parameter is
@code{True}, then output will be collected by @code{gdb.execute} and
returned as a string. The default is @code{False}, in which case the
return value is @code{None}. If @var{to_string} is @code{True}, the
@value{GDBN} virtual terminal will be temporarily set to unlimited width
and height, and its pagination will be disabled; @pxref{Screen Size}.
@end defun
@findex gdb.breakpoints
@defun gdb.breakpoints ()
Return a sequence holding all of @value{GDBN}'s breakpoints.
@xref{Breakpoints In Python}, for more information. In @value{GDBN}
version 7.11 and earlier, this function returned @code{None} if there
were no breakpoints. This peculiarity was subsequently fixed, and now
@code{gdb.breakpoints} returns an empty sequence in this case.
@end defun
@findex gdb.parameter
@defun gdb.parameter (parameter)
Return the value of a @value{GDBN} @var{parameter} given by its name,
a string; the parameter name string may contain spaces if the parameter has a
multi-part name. For example, @samp{print object} is a valid
parameter name.
If the named parameter does not exist, this function throws a
@code{gdb.error} (@pxref{Exception Handling}). Otherwise, the
parameter's value is converted to a Python value of the appropriate
type, and returned.
@end defun
@findex gdb.history
@defun gdb.history (number)
Return a value from @value{GDBN}'s value history (@pxref{Value
History}). The @var{number} argument indicates which history element to return.
If @var{number} is negative, then @value{GDBN} will take its absolute value
and count backward from the last element (i.e., the most recent element) to
find the value to return. If @var{number} is zero, then @value{GDBN} will
return the most recent element. If the element specified by @var{number}
doesn't exist in the value history, a @code{gdb.error} exception will be
raised.
If no exception is raised, the return value is always an instance of
@code{gdb.Value} (@pxref{Values From Inferior}).
@end defun
@findex gdb.parse_and_eval
@defun gdb.parse_and_eval (expression)
Parse @var{expression}, which must be a string, as an expression in
the current language, evaluate it, and return the result as a
@code{gdb.Value}.
This function can be useful when implementing a new command
(@pxref{Commands In Python}), as it provides a way to parse the
command's argument as an expression. It is also useful simply to
compute values, for example, it is the only way to get the value of a
convenience variable (@pxref{Convenience Vars}) as a @code{gdb.Value}.
@end defun
@findex gdb.find_pc_line
@defun gdb.find_pc_line (pc)
Return the @code{gdb.Symtab_and_line} object corresponding to the
@var{pc} value. @xref{Symbol Tables In Python}. If an invalid
value of @var{pc} is passed as an argument, then the @code{symtab} and
@code{line} attributes of the returned @code{gdb.Symtab_and_line} object
will be @code{None} and 0 respectively.
@end defun
@findex gdb.post_event
@defun gdb.post_event (event)
Put @var{event}, a callable object taking no arguments, into
@value{GDBN}'s internal event queue. This callable will be invoked at
some later point, during @value{GDBN}'s event processing. Events
posted using @code{post_event} will be run in the order in which they
were posted; however, there is no way to know when they will be
processed relative to other events inside @value{GDBN}.
@value{GDBN} is not thread-safe. If your Python program uses multiple
threads, you must be careful to only call @value{GDBN}-specific
functions in the @value{GDBN} thread. @code{post_event} ensures
this. For example:
@smallexample
(@value{GDBP}) python
>import threading
>
>class Writer():
> def __init__(self, message):
> self.message = message;
> def __call__(self):
> gdb.write(self.message)
>
>class MyThread1 (threading.Thread):
> def run (self):
> gdb.post_event(Writer("Hello "))
>
>class MyThread2 (threading.Thread):
> def run (self):
> gdb.post_event(Writer("World\n"))
>
>MyThread1().start()
>MyThread2().start()
>end
(@value{GDBP}) Hello World
@end smallexample
@end defun
@findex gdb.write
@defun gdb.write (string @r{[}, stream{]})
Print a string to @value{GDBN}'s paginated output stream. The
optional @var{stream} determines the stream to print to. The default
stream is @value{GDBN}'s standard output stream. Possible stream
values are:
@table @code
@findex STDOUT
@findex gdb.STDOUT
@item gdb.STDOUT
@value{GDBN}'s standard output stream.
@findex STDERR
@findex gdb.STDERR
@item gdb.STDERR
@value{GDBN}'s standard error stream.
@findex STDLOG
@findex gdb.STDLOG
@item gdb.STDLOG
@value{GDBN}'s log stream (@pxref{Logging Output}).
@end table
Writing to @code{sys.stdout} or @code{sys.stderr} will automatically
call this function and will automatically direct the output to the
relevant stream.
@end defun
@findex gdb.flush
@defun gdb.flush ()
Flush the buffer of a @value{GDBN} paginated stream so that the
contents are displayed immediately. @value{GDBN} will flush the
contents of a stream automatically when it encounters a newline in the
buffer. The optional @var{stream} determines the stream to flush. The
default stream is @value{GDBN}'s standard output stream. Possible
stream values are:
@table @code
@findex STDOUT
@findex gdb.STDOUT
@item gdb.STDOUT
@value{GDBN}'s standard output stream.
@findex STDERR
@findex gdb.STDERR
@item gdb.STDERR
@value{GDBN}'s standard error stream.
@findex STDLOG
@findex gdb.STDLOG
@item gdb.STDLOG
@value{GDBN}'s log stream (@pxref{Logging Output}).
@end table
Flushing @code{sys.stdout} or @code{sys.stderr} will automatically
call this function for the relevant stream.
@end defun
@findex gdb.target_charset
@defun gdb.target_charset ()
Return the name of the current target character set (@pxref{Character
Sets}). This differs from @code{gdb.parameter('target-charset')} in
that @samp{auto} is never returned.
@end defun
@findex gdb.target_wide_charset
@defun gdb.target_wide_charset ()
Return the name of the current target wide character set
(@pxref{Character Sets}). This differs from
@code{gdb.parameter('target-wide-charset')} in that @samp{auto} is
never returned.
@end defun
@findex gdb.solib_name
@defun gdb.solib_name (address)
Return the name of the shared library holding the given @var{address}
as a string, or @code{None}.
@end defun
@findex gdb.decode_line
@defun gdb.decode_line @r{[}expression@r{]}
Return locations of the line specified by @var{expression}, or of the
current line if no argument was given. This function returns a Python
tuple containing two elements. The first element contains a string
holding any unparsed section of @var{expression} (or @code{None} if
the expression has been fully parsed). The second element contains
either @code{None} or another tuple that contains all the locations
that match the expression represented as @code{gdb.Symtab_and_line}
objects (@pxref{Symbol Tables In Python}). If @var{expression} is
provided, it is decoded the way that @value{GDBN}'s inbuilt
@code{break} or @code{edit} commands do (@pxref{Specify Location}).
@end defun
@defun gdb.prompt_hook (current_prompt)
@anchor{prompt_hook}
If @var{prompt_hook} is callable, @value{GDBN} will call the method
assigned to this operation before a prompt is displayed by
@value{GDBN}.
The parameter @code{current_prompt} contains the current @value{GDBN}
prompt. This method must return a Python string, or @code{None}. If
a string is returned, the @value{GDBN} prompt will be set to that
string. If @code{None} is returned, @value{GDBN} will continue to use
the current prompt.
Some prompts cannot be substituted in @value{GDBN}. Secondary prompts
such as those used by readline for command input, and annotation
related prompts are prohibited from being changed.
@end defun
@node Exception Handling
@subsubsection Exception Handling
@cindex python exceptions
@cindex exceptions, python
When executing the @code{python} command, Python exceptions
uncaught within the Python code are translated to calls to
@value{GDBN} error-reporting mechanism. If the command that called
@code{python} does not handle the error, @value{GDBN} will
terminate it and print an error message containing the Python
exception name, the associated value, and the Python call stack
backtrace at the point where the exception was raised. Example:
@smallexample
(@value{GDBP}) python print foo
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'foo' is not defined
@end smallexample
@value{GDBN} errors that happen in @value{GDBN} commands invoked by
Python code are converted to Python exceptions. The type of the
Python exception depends on the error.
@ftable @code
@item gdb.error
This is the base class for most exceptions generated by @value{GDBN}.
It is derived from @code{RuntimeError}, for compatibility with earlier
versions of @value{GDBN}.
If an error occurring in @value{GDBN} does not fit into some more
specific category, then the generated exception will have this type.
@item gdb.MemoryError
This is a subclass of @code{gdb.error} which is thrown when an
operation tried to access invalid memory in the inferior.
@item KeyboardInterrupt
User interrupt (via @kbd{C-c} or by typing @kbd{q} at a pagination
prompt) is translated to a Python @code{KeyboardInterrupt} exception.
@end ftable
In all cases, your exception handler will see the @value{GDBN} error
message as its value and the Python call stack backtrace at the Python
statement closest to where the @value{GDBN} error occured as the
traceback.
@findex gdb.GdbError
When implementing @value{GDBN} commands in Python via @code{gdb.Command},
it is useful to be able to throw an exception that doesn't cause a
traceback to be printed. For example, the user may have invoked the
command incorrectly. Use the @code{gdb.GdbError} exception
to handle this case. Example:
@smallexample
(gdb) python
>class HelloWorld (gdb.Command):
> """Greet the whole world."""
> def __init__ (self):
> super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
> def invoke (self, args, from_tty):
> argv = gdb.string_to_argv (args)
> if len (argv) != 0:
> raise gdb.GdbError ("hello-world takes no arguments")
> print "Hello, World!"
>HelloWorld ()
>end
(gdb) hello-world 42
hello-world takes no arguments
@end smallexample
@node Values From Inferior
@subsubsection Values From Inferior
@cindex values from inferior, with Python
@cindex python, working with values from inferior
@cindex @code{gdb.Value}
@value{GDBN} provides values it obtains from the inferior program in
an object of type @code{gdb.Value}. @value{GDBN} uses this object
for its internal bookkeeping of the inferior's values, and for
fetching values when necessary.
Inferior values that are simple scalars can be used directly in
Python expressions that are valid for the value's data type. Here's
an example for an integer or floating-point value @code{some_val}:
@smallexample
bar = some_val + 2
@end smallexample
@noindent
As result of this, @code{bar} will also be a @code{gdb.Value} object
whose values are of the same type as those of @code{some_val}. Valid
Python operations can also be performed on @code{gdb.Value} objects
representing a @code{struct} or @code{class} object. For such cases,
the overloaded operator (if present), is used to perform the operation.
For example, if @code{val1} and @code{val2} are @code{gdb.Value} objects
representing instances of a @code{class} which overloads the @code{+}
operator, then one can use the @code{+} operator in their Python script
as follows:
@smallexample
val3 = val1 + val2
@end smallexample
@noindent
The result of the operation @code{val3} is also a @code{gdb.Value}
object corresponding to the value returned by the overloaded @code{+}
operator. In general, overloaded operators are invoked for the
following operations: @code{+} (binary addition), @code{-} (binary
subtraction), @code{*} (multiplication), @code{/}, @code{%}, @code{<<},
@code{>>}, @code{|}, @code{&}, @code{^}.
Inferior values that are structures or instances of some class can
be accessed using the Python @dfn{dictionary syntax}. For example, if
@code{some_val} is a @code{gdb.Value} instance holding a structure, you
can access its @code{foo} element with:
@smallexample
bar = some_val['foo']
@end smallexample
@cindex getting structure elements using gdb.Field objects as subscripts
Again, @code{bar} will also be a @code{gdb.Value} object. Structure
elements can also be accessed by using @code{gdb.Field} objects as
subscripts (@pxref{Types In Python}, for more information on
@code{gdb.Field} objects). For example, if @code{foo_field} is a
@code{gdb.Field} object corresponding to element @code{foo} of the above
structure, then @code{bar} can also be accessed as follows:
@smallexample
bar = some_val[foo_field]
@end smallexample
A @code{gdb.Value} that represents a function can be executed via
inferior function call. Any arguments provided to the call must match
the function's prototype, and must be provided in the order specified
by that prototype.
For example, @code{some_val} is a @code{gdb.Value} instance
representing a function that takes two integers as arguments. To
execute this function, call it like so:
@smallexample
result = some_val (10,20)
@end smallexample
Any values returned from a function call will be stored as a
@code{gdb.Value}.
The following attributes are provided:
@defvar Value.address
If this object is addressable, this read-only attribute holds a
@code{gdb.Value} object representing the address. Otherwise,
this attribute holds @code{None}.
@end defvar
@cindex optimized out value in Python
@defvar Value.is_optimized_out
This read-only boolean attribute is true if the compiler optimized out
this value, thus it is not available for fetching from the inferior.
@end defvar
@defvar Value.type
The type of this @code{gdb.Value}. The value of this attribute is a
@code{gdb.Type} object (@pxref{Types In Python}).
@end defvar
@defvar Value.dynamic_type
The dynamic type of this @code{gdb.Value}. This uses C@t{++} run-time
type information (@acronym{RTTI}) to determine the dynamic type of the
value. If this value is of class type, it will return the class in
which the value is embedded, if any. If this value is of pointer or
reference to a class type, it will compute the dynamic type of the
referenced object, and return a pointer or reference to that type,
respectively. In all other cases, it will return the value's static
type.
Note that this feature will only work when debugging a C@t{++} program
that includes @acronym{RTTI} for the object in question. Otherwise,
it will just return the static type of the value as in @kbd{ptype foo}
(@pxref{Symbols, ptype}).
@end defvar
@defvar Value.is_lazy
The value of this read-only boolean attribute is @code{True} if this
@code{gdb.Value} has not yet been fetched from the inferior.
@value{GDBN} does not fetch values until necessary, for efficiency.
For example:
@smallexample
myval = gdb.parse_and_eval ('somevar')
@end smallexample
The value of @code{somevar} is not fetched at this time. It will be
fetched when the value is needed, or when the @code{fetch_lazy}
method is invoked.
@end defvar
The following methods are provided:
@defun Value.__init__ (@var{val})
Many Python values can be converted directly to a @code{gdb.Value} via
this object initializer. Specifically:
@table @asis
@item Python boolean
A Python boolean is converted to the boolean type from the current
language.
@item Python integer
A Python integer is converted to the C @code{long} type for the
current architecture.
@item Python long
A Python long is converted to the C @code{long long} type for the
current architecture.
@item Python float
A Python float is converted to the C @code{double} type for the
current architecture.
@item Python string
A Python string is converted to a target string in the current target
language using the current target encoding.
If a character cannot be represented in the current target encoding,
then an exception is thrown.
@item @code{gdb.Value}
If @code{val} is a @code{gdb.Value}, then a copy of the value is made.
@item @code{gdb.LazyString}
If @code{val} is a @code{gdb.LazyString} (@pxref{Lazy Strings In
Python}), then the lazy string's @code{value} method is called, and
its result is used.
@end table
@end defun
@defun Value.cast (type)
Return a new instance of @code{gdb.Value} that is the result of
casting this instance to the type described by @var{type}, which must
be a @code{gdb.Type} object. If the cast cannot be performed for some
reason, this method throws an exception.
@end defun
@defun Value.dereference ()
For pointer data types, this method returns a new @code{gdb.Value} object
whose contents is the object pointed to by the pointer. For example, if
@code{foo} is a C pointer to an @code{int}, declared in your C program as
@smallexample
int *foo;
@end smallexample
@noindent
then you can use the corresponding @code{gdb.Value} to access what
@code{foo} points to like this:
@smallexample
bar = foo.dereference ()
@end smallexample
The result @code{bar} will be a @code{gdb.Value} object holding the
value pointed to by @code{foo}.
A similar function @code{Value.referenced_value} exists which also
returns @code{gdb.Value} objects corresonding to the values pointed to
by pointer values (and additionally, values referenced by reference
values). However, the behavior of @code{Value.dereference}
differs from @code{Value.referenced_value} by the fact that the
behavior of @code{Value.dereference} is identical to applying the C
unary operator @code{*} on a given value. For example, consider a
reference to a pointer @code{ptrref}, declared in your C@t{++} program
as
@smallexample
typedef int *intptr;
...
int val = 10;
intptr ptr = &val;
intptr &ptrref = ptr;
@end smallexample
Though @code{ptrref} is a reference value, one can apply the method
@code{Value.dereference} to the @code{gdb.Value} object corresponding
to it and obtain a @code{gdb.Value} which is identical to that
corresponding to @code{val}. However, if you apply the method
@code{Value.referenced_value}, the result would be a @code{gdb.Value}
object identical to that corresponding to @code{ptr}.
@smallexample
py_ptrref = gdb.parse_and_eval ("ptrref")
py_val = py_ptrref.dereference ()
py_ptr = py_ptrref.referenced_value ()
@end smallexample
The @code{gdb.Value} object @code{py_val} is identical to that
corresponding to @code{val}, and @code{py_ptr} is identical to that
corresponding to @code{ptr}. In general, @code{Value.dereference} can
be applied whenever the C unary operator @code{*} can be applied
to the corresponding C value. For those cases where applying both
@code{Value.dereference} and @code{Value.referenced_value} is allowed,
the results obtained need not be identical (as we have seen in the above
example). The results are however identical when applied on
@code{gdb.Value} objects corresponding to pointers (@code{gdb.Value}
objects with type code @code{TYPE_CODE_PTR}) in a C/C@t{++} program.
@end defun
@defun Value.referenced_value ()
For pointer or reference data types, this method returns a new
@code{gdb.Value} object corresponding to the value referenced by the
pointer/reference value. For pointer data types,
@code{Value.dereference} and @code{Value.referenced_value} produce
identical results. The difference between these methods is that
@code{Value.dereference} cannot get the values referenced by reference
values. For example, consider a reference to an @code{int}, declared
in your C@t{++} program as
@smallexample
int val = 10;
int &ref = val;
@end smallexample
@noindent
then applying @code{Value.dereference} to the @code{gdb.Value} object
corresponding to @code{ref} will result in an error, while applying
@code{Value.referenced_value} will result in a @code{gdb.Value} object
identical to that corresponding to @code{val}.
@smallexample
py_ref = gdb.parse_and_eval ("ref")
er_ref = py_ref.dereference () # Results in error
py_val = py_ref.referenced_value () # Returns the referenced value
@end smallexample
The @code{gdb.Value} object @code{py_val} is identical to that
corresponding to @code{val}.
@end defun
@defun Value.reference_value ()
Return a @code{gdb.Value} object which is a reference to the value
encapsulated by this instance.
@end defun
@defun Value.const_value ()
Return a @code{gdb.Value} object which is a @code{const} version of the
value encapsulated by this instance.
@end defun
@defun Value.dynamic_cast (type)
Like @code{Value.cast}, but works as if the C@t{++} @code{dynamic_cast}
operator were used. Consult a C@t{++} reference for details.
@end defun
@defun Value.reinterpret_cast (type)
Like @code{Value.cast}, but works as if the C@t{++} @code{reinterpret_cast}
operator were used. Consult a C@t{++} reference for details.
@end defun
@defun Value.string (@r{[}encoding@r{[}, errors@r{[}, length@r{]]]})
If this @code{gdb.Value} represents a string, then this method
converts the contents to a Python string. Otherwise, this method will
throw an exception.
Values are interpreted as strings according to the rules of the
current language. If the optional length argument is given, the
string will be converted to that length, and will include any embedded
zeroes that the string may contain. Otherwise, for languages
where the string is zero-terminated, the entire string will be
converted.
For example, in C-like languages, a value is a string if it is a pointer
to or an array of characters or ints of type @code{wchar_t}, @code{char16_t},
or @code{char32_t}.
If the optional @var{encoding} argument is given, it must be a string
naming the encoding of the string in the @code{gdb.Value}, such as
@code{"ascii"}, @code{"iso-8859-6"} or @code{"utf-8"}. It accepts
the same encodings as the corresponding argument to Python's
@code{string.decode} method, and the Python codec machinery will be used
to convert the string. If @var{encoding} is not given, or if
@var{encoding} is the empty string, then either the @code{target-charset}
(@pxref{Character Sets}) will be used, or a language-specific encoding
will be used, if the current language is able to supply one.
The optional @var{errors} argument is the same as the corresponding
argument to Python's @code{string.decode} method.
If the optional @var{length} argument is given, the string will be
fetched and converted to the given length.
@end defun
@defun Value.lazy_string (@r{[}encoding @r{[}, length@r{]]})
If this @code{gdb.Value} represents a string, then this method
converts the contents to a @code{gdb.LazyString} (@pxref{Lazy Strings
In Python}). Otherwise, this method will throw an exception.
If the optional @var{encoding} argument is given, it must be a string
naming the encoding of the @code{gdb.LazyString}. Some examples are:
@samp{ascii}, @samp{iso-8859-6} or @samp{utf-8}. If the
@var{encoding} argument is an encoding that @value{GDBN} does
recognize, @value{GDBN} will raise an error.
When a lazy string is printed, the @value{GDBN} encoding machinery is
used to convert the string during printing. If the optional
@var{encoding} argument is not provided, or is an empty string,
@value{GDBN} will automatically select the encoding most suitable for
the string type. For further information on encoding in @value{GDBN}
please see @ref{Character Sets}.
If the optional @var{length} argument is given, the string will be
fetched and encoded to the length of characters specified. If
the @var{length} argument is not provided, the string will be fetched
and encoded until a null of appropriate width is found.
@end defun
@defun Value.fetch_lazy ()
If the @code{gdb.Value} object is currently a lazy value
(@code{gdb.Value.is_lazy} is @code{True}), then the value is
fetched from the inferior. Any errors that occur in the process
will produce a Python exception.
If the @code{gdb.Value} object is not a lazy value, this method
has no effect.
This method does not return a value.
@end defun
@node Types In Python
@subsubsection Types In Python
@cindex types in Python
@cindex Python, working with types
@tindex gdb.Type
@value{GDBN} represents types from the inferior using the class
@code{gdb.Type}.
The following type-related functions are available in the @code{gdb}
module:
@findex gdb.lookup_type
@defun gdb.lookup_type (name @r{[}, block@r{]})
This function looks up a type by its @var{name}, which must be a string.
If @var{block} is given, then @var{name} is looked up in that scope.
Otherwise, it is searched for globally.
Ordinarily, this function will return an instance of @code{gdb.Type}.
If the named type cannot be found, it will throw an exception.
@end defun
If the type is a structure or class type, or an enum type, the fields
of that type can be accessed using the Python @dfn{dictionary syntax}.
For example, if @code{some_type} is a @code{gdb.Type} instance holding
a structure type, you can access its @code{foo} field with:
@smallexample
bar = some_type['foo']
@end smallexample
@code{bar} will be a @code{gdb.Field} object; see below under the
description of the @code{Type.fields} method for a description of the
@code{gdb.Field} class.
An instance of @code{Type} has the following attributes:
@defvar Type.code
The type code for this type. The type code will be one of the
@code{TYPE_CODE_} constants defined below.
@end defvar
@defvar Type.name
The name of this type. If this type has no name, then @code{None}
is returned.
@end defvar
@defvar Type.sizeof
The size of this type, in target @code{char} units. Usually, a
target's @code{char} type will be an 8-bit byte. However, on some
unusual platforms, this type may have a different size.
@end defvar
@defvar Type.tag
The tag name for this type. The tag name is the name after
@code{struct}, @code{union}, or @code{enum} in C and C@t{++}; not all
languages have this concept. If this type has no tag name, then
@code{None} is returned.
@end defvar
The following methods are provided:
@defun Type.fields ()
For structure and union types, this method returns the fields. Range
types have two fields, the minimum and maximum values. Enum types
have one field per enum constant. Function and method types have one
field per parameter. The base types of C@t{++} classes are also
represented as fields. If the type has no fields, or does not fit
into one of these categories, an empty sequence will be returned.
Each field is a @code{gdb.Field} object, with some pre-defined attributes:
@table @code
@item bitpos
This attribute is not available for @code{enum} or @code{static}
(as in C@t{++}) fields. The value is the position, counting
in bits, from the start of the containing type.
@item enumval
This attribute is only available for @code{enum} fields, and its value
is the enumeration member's integer representation.
@item name
The name of the field, or @code{None} for anonymous fields.
@item artificial
This is @code{True} if the field is artificial, usually meaning that
it was provided by the compiler and not the user. This attribute is
always provided, and is @code{False} if the field is not artificial.
@item is_base_class
This is @code{True} if the field represents a base class of a C@t{++}
structure. This attribute is always provided, and is @code{False}
if the field is not a base class of the type that is the argument of
@code{fields}, or if that type was not a C@t{++} class.
@item bitsize
If the field is packed, or is a bitfield, then this will have a
non-zero value, which is the size of the field in bits. Otherwise,
this will be zero; in this case the field's size is given by its type.
@item type
The type of the field. This is usually an instance of @code{Type},
but it can be @code{None} in some situations.
@item parent_type
The type which contains this field. This is an instance of
@code{gdb.Type}.
@end table
@end defun
@defun Type.array (@var{n1} @r{[}, @var{n2}@r{]})
Return a new @code{gdb.Type} object which represents an array of this
type. If one argument is given, it is the inclusive upper bound of
the array; in this case the lower bound is zero. If two arguments are
given, the first argument is the lower bound of the array, and the
second argument is the upper bound of the array. An array's length
must not be negative, but the bounds can be.
@end defun
@defun Type.vector (@var{n1} @r{[}, @var{n2}@r{]})
Return a new @code{gdb.Type} object which represents a vector of this
type. If one argument is given, it is the inclusive upper bound of
the vector; in this case the lower bound is zero. If two arguments are