1 /* Python interface to values.
3 Copyright (C) 2008-2023 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
24 #include "target-float.h"
27 #include "expression.h"
31 #include "python-internal.h"
33 /* Even though Python scalar types directly map to host types, we use
34 target types here to remain consistent with the values system in
35 GDB (which uses target arithmetic). */
37 /* Python's integer type corresponds to C's long type. */
38 #define builtin_type_pyint \
39 builtin_type (gdbpy_enter::get_gdbarch ())->builtin_long
41 /* Python's float type corresponds to C's double type. */
42 #define builtin_type_pyfloat \
43 builtin_type (gdbpy_enter::get_gdbarch ())->builtin_double
45 /* Python's long type corresponds to C's long long type. */
46 #define builtin_type_pylong \
47 builtin_type (gdbpy_enter::get_gdbarch ())->builtin_long_long
49 /* Python's long type corresponds to C's long long type. Unsigned version. */
50 #define builtin_type_upylong builtin_type \
51 (gdbpy_enter::get_gdbarch ())->builtin_unsigned_long_long
53 #define builtin_type_pybool \
54 language_bool_type (current_language, gdbpy_enter::get_gdbarch ())
56 #define builtin_type_pychar \
57 language_string_char_type (current_language, gdbpy_enter::get_gdbarch ())
61 struct value_object
*next
;
62 struct value_object
*prev
;
66 PyObject
*dynamic_type
;
69 /* List of all values which are currently exposed to Python. It is
70 maintained so that when an objfile is discarded, preserve_values
71 can copy the values' types if needed. */
72 /* This variable is unnecessarily initialized to NULL in order to
73 work around a linker bug on MacOS. */
74 static value_object
*values_in_python
= NULL
;
76 /* Clear out an old GDB value stored within SELF, and reset the fields to
77 nullptr. This should be called when a gdb.Value is deallocated, and
78 also if a gdb.Value is reinitialized with a new value. */
81 valpy_clear_value (value_object
*self
)
83 /* Indicate we are no longer interested in the value object. */
84 value_decref (self
->value
);
85 self
->value
= nullptr;
87 Py_CLEAR (self
->address
);
88 Py_CLEAR (self
->type
);
89 Py_CLEAR (self
->dynamic_type
);
92 /* Called by the Python interpreter when deallocating a value object. */
94 valpy_dealloc (PyObject
*obj
)
96 value_object
*self
= (value_object
*) obj
;
98 /* If SELF failed to initialize correctly then it may not have a value
99 contained within it. */
100 if (self
->value
!= nullptr)
102 /* Remove SELF from the global list of values. */
103 if (self
->prev
!= nullptr)
104 self
->prev
->next
= self
->next
;
107 gdb_assert (values_in_python
== self
);
108 values_in_python
= self
->next
;
110 if (self
->next
!= nullptr)
111 self
->next
->prev
= self
->prev
;
113 /* Release the value object and any cached Python objects. */
114 valpy_clear_value (self
);
117 Py_TYPE (self
)->tp_free (self
);
120 /* Helper to push a gdb.Value object on to the global list of values. If
121 VALUE_OBJ is already on the lit then this does nothing. */
124 note_value (value_object
*value_obj
)
126 if (value_obj
->next
== nullptr)
128 gdb_assert (value_obj
->prev
== nullptr);
129 value_obj
->next
= values_in_python
;
130 if (value_obj
->next
!= nullptr)
131 value_obj
->next
->prev
= value_obj
;
132 values_in_python
= value_obj
;
136 /* Convert a python object OBJ with type TYPE to a gdb value. The
137 python object in question must conform to the python buffer
138 protocol. On success, return the converted value, otherwise
141 static struct value
*
142 convert_buffer_and_type_to_value (PyObject
*obj
, struct type
*type
)
144 Py_buffer_up buffer_up
;
147 if (PyObject_CheckBuffer (obj
)
148 && PyObject_GetBuffer (obj
, &py_buf
, PyBUF_SIMPLE
) == 0)
150 /* Got a buffer, py_buf, out of obj. Cause it to be released
151 when it goes out of scope. */
152 buffer_up
.reset (&py_buf
);
156 PyErr_SetString (PyExc_TypeError
,
157 _("Object must support the python buffer protocol."));
161 if (type
->length () > py_buf
.len
)
163 PyErr_SetString (PyExc_ValueError
,
164 _("Size of type is larger than that of buffer object."));
168 return value_from_contents (type
, (const gdb_byte
*) py_buf
.buf
);
171 /* Implement gdb.Value.__init__. */
174 valpy_init (PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
176 static const char *keywords
[] = { "val", "type", NULL
};
177 PyObject
*val_obj
= nullptr;
178 PyObject
*type_obj
= nullptr;
180 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kwds
, "O|O", keywords
,
181 &val_obj
, &type_obj
))
184 struct type
*type
= nullptr;
185 if (type_obj
!= nullptr && type_obj
!= Py_None
)
187 type
= type_object_to_type (type_obj
);
190 PyErr_SetString (PyExc_TypeError
,
191 _("type argument must be a gdb.Type."));
198 value
= convert_value_from_python (val_obj
);
200 value
= convert_buffer_and_type_to_value (val_obj
, type
);
201 if (value
== nullptr)
203 gdb_assert (PyErr_Occurred ());
207 /* There might be a previous value here. */
208 value_object
*value_obj
= (value_object
*) self
;
209 if (value_obj
->value
!= nullptr)
210 valpy_clear_value (value_obj
);
212 /* Store the value into this Python object. */
213 value_obj
->value
= release_value (value
).release ();
215 /* Ensure that this gdb.Value is in the set of all gdb.Value objects. If
216 we are already in the set then this is call does nothing. */
217 note_value (value_obj
);
222 /* Iterate over all the Value objects, calling preserve_one_value on
225 gdbpy_preserve_values (const struct extension_language_defn
*extlang
,
226 struct objfile
*objfile
, htab_t copied_types
)
230 for (iter
= values_in_python
; iter
; iter
= iter
->next
)
231 preserve_one_value (iter
->value
, objfile
, copied_types
);
234 /* Given a value of a pointer type, apply the C unary * operator to it. */
236 valpy_dereference (PyObject
*self
, PyObject
*args
)
238 PyObject
*result
= NULL
;
242 struct value
*res_val
;
243 scoped_value_mark free_values
;
245 res_val
= value_ind (((value_object
*) self
)->value
);
246 result
= value_to_value_object (res_val
);
248 catch (const gdb_exception
&except
)
250 GDB_PY_HANDLE_EXCEPTION (except
);
256 /* Given a value of a pointer type or a reference type, return the value
257 referenced. The difference between this function and valpy_dereference is
258 that the latter applies * unary operator to a value, which need not always
259 result in the value referenced. For example, for a value which is a reference
260 to an 'int' pointer ('int *'), valpy_dereference will result in a value of
261 type 'int' while valpy_referenced_value will result in a value of type
265 valpy_referenced_value (PyObject
*self
, PyObject
*args
)
267 PyObject
*result
= NULL
;
271 struct value
*self_val
, *res_val
;
272 scoped_value_mark free_values
;
274 self_val
= ((value_object
*) self
)->value
;
275 switch (check_typedef (self_val
->type ())->code ())
278 res_val
= value_ind (self_val
);
281 case TYPE_CODE_RVALUE_REF
:
282 res_val
= coerce_ref (self_val
);
285 error(_("Trying to get the referenced value from a value which is "
286 "neither a pointer nor a reference."));
289 result
= value_to_value_object (res_val
);
291 catch (const gdb_exception
&except
)
293 GDB_PY_HANDLE_EXCEPTION (except
);
299 /* Return a value which is a reference to the value. */
302 valpy_reference_value (PyObject
*self
, PyObject
*args
, enum type_code refcode
)
304 PyObject
*result
= NULL
;
308 struct value
*self_val
;
309 scoped_value_mark free_values
;
311 self_val
= ((value_object
*) self
)->value
;
312 result
= value_to_value_object (value_ref (self_val
, refcode
));
314 catch (const gdb_exception
&except
)
316 GDB_PY_HANDLE_EXCEPTION (except
);
323 valpy_lvalue_reference_value (PyObject
*self
, PyObject
*args
)
325 return valpy_reference_value (self
, args
, TYPE_CODE_REF
);
329 valpy_rvalue_reference_value (PyObject
*self
, PyObject
*args
)
331 return valpy_reference_value (self
, args
, TYPE_CODE_RVALUE_REF
);
334 /* Return a "const" qualified version of the value. */
337 valpy_const_value (PyObject
*self
, PyObject
*args
)
339 PyObject
*result
= NULL
;
343 struct value
*self_val
, *res_val
;
344 scoped_value_mark free_values
;
346 self_val
= ((value_object
*) self
)->value
;
347 res_val
= make_cv_value (1, 0, self_val
);
348 result
= value_to_value_object (res_val
);
350 catch (const gdb_exception
&except
)
352 GDB_PY_HANDLE_EXCEPTION (except
);
358 /* Return "&value". */
360 valpy_get_address (PyObject
*self
, void *closure
)
362 value_object
*val_obj
= (value_object
*) self
;
364 if (!val_obj
->address
)
368 struct value
*res_val
;
369 scoped_value_mark free_values
;
371 res_val
= value_addr (val_obj
->value
);
372 val_obj
->address
= value_to_value_object (res_val
);
374 catch (const gdb_exception
&except
)
376 val_obj
->address
= Py_None
;
381 Py_XINCREF (val_obj
->address
);
383 return val_obj
->address
;
386 /* Return type of the value. */
388 valpy_get_type (PyObject
*self
, void *closure
)
390 value_object
*obj
= (value_object
*) self
;
394 obj
->type
= type_to_type_object (obj
->value
->type ());
398 Py_INCREF (obj
->type
);
402 /* Return dynamic type of the value. */
405 valpy_get_dynamic_type (PyObject
*self
, void *closure
)
407 value_object
*obj
= (value_object
*) self
;
408 struct type
*type
= NULL
;
410 if (obj
->dynamic_type
!= NULL
)
412 Py_INCREF (obj
->dynamic_type
);
413 return obj
->dynamic_type
;
418 struct value
*val
= obj
->value
;
419 scoped_value_mark free_values
;
422 type
= check_typedef (type
);
424 if (type
->is_pointer_or_reference ()
425 && (type
->target_type ()->code () == TYPE_CODE_STRUCT
))
427 struct value
*target
;
428 int was_pointer
= type
->code () == TYPE_CODE_PTR
;
431 target
= value_ind (val
);
433 target
= coerce_ref (val
);
434 type
= value_rtti_type (target
, NULL
, NULL
, NULL
);
439 type
= lookup_pointer_type (type
);
441 type
= lookup_lvalue_reference_type (type
);
444 else if (type
->code () == TYPE_CODE_STRUCT
)
445 type
= value_rtti_type (val
, NULL
, NULL
, NULL
);
448 /* Re-use object's static type. */
452 catch (const gdb_exception
&except
)
454 GDB_PY_HANDLE_EXCEPTION (except
);
458 obj
->dynamic_type
= valpy_get_type (self
, NULL
);
460 obj
->dynamic_type
= type_to_type_object (type
);
462 Py_XINCREF (obj
->dynamic_type
);
463 return obj
->dynamic_type
;
466 /* Implementation of gdb.Value.lazy_string ([encoding] [, length]) ->
467 string. Return a PyObject representing a lazy_string_object type.
468 A lazy string is a pointer to a string with an optional encoding and
469 length. If ENCODING is not given, encoding is set to None. If an
470 ENCODING is provided the encoding parameter is set to ENCODING, but
471 the string is not encoded.
472 If LENGTH is provided then the length parameter is set to LENGTH.
473 Otherwise if the value is an array of known length then the array's length
474 is used. Otherwise the length will be set to -1 (meaning first null of
477 Note: In order to not break any existing uses this allows creating
478 lazy strings from anything. PR 20769. E.g.,
479 gdb.parse_and_eval("my_int_variable").lazy_string().
480 "It's easier to relax restrictions than it is to impose them after the
481 fact." So we should be flagging any unintended uses as errors, but it's
482 perhaps too late for that. */
485 valpy_lazy_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
487 gdb_py_longest length
= -1;
488 struct value
*value
= ((value_object
*) self
)->value
;
489 const char *user_encoding
= NULL
;
490 static const char *keywords
[] = { "encoding", "length", NULL
};
491 PyObject
*str_obj
= NULL
;
493 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "|s" GDB_PY_LL_ARG
,
494 keywords
, &user_encoding
, &length
))
499 PyErr_SetString (PyExc_ValueError
, _("Invalid length."));
505 scoped_value_mark free_values
;
506 struct type
*type
, *realtype
;
509 type
= value
->type ();
510 realtype
= check_typedef (type
);
512 switch (realtype
->code ())
514 case TYPE_CODE_ARRAY
:
516 LONGEST array_length
= -1;
517 LONGEST low_bound
, high_bound
;
519 /* PR 20786: There's no way to specify an array of length zero.
520 Record a length of [0,-1] which is how Ada does it. Anything
521 we do is broken, but this one possible solution. */
522 if (get_array_bounds (realtype
, &low_bound
, &high_bound
))
523 array_length
= high_bound
- low_bound
+ 1;
525 length
= array_length
;
526 else if (array_length
== -1)
528 type
= lookup_array_range_type (realtype
->target_type (),
531 else if (length
!= array_length
)
533 /* We need to create a new array type with the
535 if (length
> array_length
)
536 error (_("Length is larger than array size."));
537 type
= lookup_array_range_type (realtype
->target_type (),
539 low_bound
+ length
- 1);
541 addr
= value
->address ();
545 /* If a length is specified we defer creating an array of the
546 specified width until we need to. */
547 addr
= value_as_address (value
);
550 /* Should flag an error here. PR 20769. */
551 addr
= value
->address ();
555 str_obj
= gdbpy_create_lazy_string_object (addr
, length
, user_encoding
,
558 catch (const gdb_exception
&except
)
560 GDB_PY_HANDLE_EXCEPTION (except
);
566 /* Implementation of gdb.Value.string ([encoding] [, errors]
567 [, length]) -> string. Return Unicode string with value contents.
568 If ENCODING is not given, the string is assumed to be encoded in
569 the target's charset. If LENGTH is provided, only fetch string to
570 the length provided. */
573 valpy_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
576 gdb::unique_xmalloc_ptr
<gdb_byte
> buffer
;
577 struct value
*value
= ((value_object
*) self
)->value
;
578 const char *encoding
= NULL
;
579 const char *errors
= NULL
;
580 const char *user_encoding
= NULL
;
581 const char *la_encoding
= NULL
;
582 struct type
*char_type
;
583 static const char *keywords
[] = { "encoding", "errors", "length", NULL
};
585 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "|ssi", keywords
,
586 &user_encoding
, &errors
, &length
))
591 c_get_string (value
, &buffer
, &length
, &char_type
, &la_encoding
);
593 catch (const gdb_exception
&except
)
595 GDB_PY_HANDLE_EXCEPTION (except
);
598 encoding
= (user_encoding
&& *user_encoding
) ? user_encoding
: la_encoding
;
599 return PyUnicode_Decode ((const char *) buffer
.get (),
600 length
* char_type
->length (),
604 /* Given a Python object, copy its truth value to a C bool (the value
606 If src_obj is NULL, then *dest is not modified.
608 Return true in case of success (including src_obj being NULL), false
612 copy_py_bool_obj (bool *dest
, PyObject
*src_obj
)
616 int cmp
= PyObject_IsTrue (src_obj
);
625 /* Implementation of gdb.Value.format_string (...) -> string.
626 Return Unicode string with value contents formatted using the
627 keyword-only arguments. */
630 valpy_format_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
632 static const char *keywords
[] =
634 /* Basic C/C++ options. */
635 "raw", /* See the /r option to print. */
636 "pretty_arrays", /* See set print array on|off. */
637 "pretty_structs", /* See set print pretty on|off. */
638 "array_indexes", /* See set print array-indexes on|off. */
639 "symbols", /* See set print symbol on|off. */
640 "unions", /* See set print union on|off. */
641 "address", /* See set print address on|off. */
642 "styling", /* Should we apply styling. */
643 "nibbles", /* See set print nibbles on|off. */
644 "summary", /* Summary mode for non-scalars. */
646 "deref_refs", /* No corresponding setting. */
647 "actual_objects", /* See set print object on|off. */
648 "static_members", /* See set print static-members on|off. */
649 /* C non-bool options. */
650 "max_characters", /* See set print characters N. */
651 "max_elements", /* See set print elements N. */
652 "max_depth", /* See set print max-depth N. */
653 "repeat_threshold", /* See set print repeats. */
654 "format", /* The format passed to the print command. */
658 /* This function has too many arguments to be useful as positionals, so
659 the user should specify them all as keyword arguments.
660 Python 3.3 and later have a way to specify it (both in C and Python
661 itself), but we could be compiled with older versions, so we just
662 check that the args tuple is empty. */
663 Py_ssize_t positional_count
= PyObject_Length (args
);
664 if (positional_count
< 0)
666 else if (positional_count
> 0)
668 /* This matches the error message that Python 3.3 raises when
669 passing positionals to functions expecting keyword-only
671 PyErr_Format (PyExc_TypeError
,
672 "format_string() takes 0 positional arguments but %zu were given",
677 struct value_print_options opts
;
678 gdbpy_get_print_options (&opts
);
679 opts
.deref_ref
= false;
681 /* We need objects for booleans as the "p" flag for bools is new in
683 PyObject
*raw_obj
= NULL
;
684 PyObject
*pretty_arrays_obj
= NULL
;
685 PyObject
*pretty_structs_obj
= NULL
;
686 PyObject
*array_indexes_obj
= NULL
;
687 PyObject
*symbols_obj
= NULL
;
688 PyObject
*unions_obj
= NULL
;
689 PyObject
*address_obj
= NULL
;
690 PyObject
*styling_obj
= Py_False
;
691 PyObject
*nibbles_obj
= NULL
;
692 PyObject
*deref_refs_obj
= NULL
;
693 PyObject
*actual_objects_obj
= NULL
;
694 PyObject
*static_members_obj
= NULL
;
695 PyObject
*summary_obj
= NULL
;
697 if (!gdb_PyArg_ParseTupleAndKeywords (args
,
699 "|O!O!O!O!O!O!O!O!O!O!O!O!O!IIIIs",
701 &PyBool_Type
, &raw_obj
,
702 &PyBool_Type
, &pretty_arrays_obj
,
703 &PyBool_Type
, &pretty_structs_obj
,
704 &PyBool_Type
, &array_indexes_obj
,
705 &PyBool_Type
, &symbols_obj
,
706 &PyBool_Type
, &unions_obj
,
707 &PyBool_Type
, &address_obj
,
708 &PyBool_Type
, &styling_obj
,
709 &PyBool_Type
, &nibbles_obj
,
710 &PyBool_Type
, &summary_obj
,
711 &PyBool_Type
, &deref_refs_obj
,
712 &PyBool_Type
, &actual_objects_obj
,
713 &PyBool_Type
, &static_members_obj
,
714 &opts
.print_max_chars
,
717 &opts
.repeat_count_threshold
,
721 /* Set boolean arguments. */
722 if (!copy_py_bool_obj (&opts
.raw
, raw_obj
))
724 if (!copy_py_bool_obj (&opts
.prettyformat_arrays
, pretty_arrays_obj
))
726 if (!copy_py_bool_obj (&opts
.prettyformat_structs
, pretty_structs_obj
))
728 if (!copy_py_bool_obj (&opts
.print_array_indexes
, array_indexes_obj
))
730 if (!copy_py_bool_obj (&opts
.symbol_print
, symbols_obj
))
732 if (!copy_py_bool_obj (&opts
.unionprint
, unions_obj
))
734 if (!copy_py_bool_obj (&opts
.addressprint
, address_obj
))
736 if (!copy_py_bool_obj (&opts
.nibblesprint
, nibbles_obj
))
738 if (!copy_py_bool_obj (&opts
.deref_ref
, deref_refs_obj
))
740 if (!copy_py_bool_obj (&opts
.objectprint
, actual_objects_obj
))
742 if (!copy_py_bool_obj (&opts
.static_field_print
, static_members_obj
))
744 if (!copy_py_bool_obj (&opts
.summary
, summary_obj
))
747 /* Numeric arguments for which 0 means unlimited (which we represent as
748 UINT_MAX). Note that the max-depth numeric argument uses -1 as
749 unlimited, and 0 is a valid choice. */
750 if (opts
.print_max
== 0)
751 opts
.print_max
= UINT_MAX
;
752 if (opts
.repeat_count_threshold
== 0)
753 opts
.repeat_count_threshold
= UINT_MAX
;
755 /* Other arguments. */
758 if (strlen (format
) == 1)
759 opts
.format
= format
[0];
762 /* Mimic the message on standard Python ones for similar
764 PyErr_SetString (PyExc_ValueError
,
765 "a single character is required");
770 string_file
stb (PyObject_IsTrue (styling_obj
));
774 common_val_print (((value_object
*) self
)->value
, &stb
, 0,
775 &opts
, current_language
);
777 catch (const gdb_exception
&except
)
779 GDB_PY_HANDLE_EXCEPTION (except
);
782 return PyUnicode_Decode (stb
.c_str (), stb
.size (), host_charset (), NULL
);
785 /* A helper function that implements the various cast operators. */
788 valpy_do_cast (PyObject
*self
, PyObject
*args
, enum exp_opcode op
)
790 PyObject
*type_obj
, *result
= NULL
;
793 if (! PyArg_ParseTuple (args
, "O", &type_obj
))
796 type
= type_object_to_type (type_obj
);
799 PyErr_SetString (PyExc_RuntimeError
,
800 _("Argument must be a type."));
806 struct value
*val
= ((value_object
*) self
)->value
;
807 struct value
*res_val
;
808 scoped_value_mark free_values
;
810 if (op
== UNOP_DYNAMIC_CAST
)
811 res_val
= value_dynamic_cast (type
, val
);
812 else if (op
== UNOP_REINTERPRET_CAST
)
813 res_val
= value_reinterpret_cast (type
, val
);
816 gdb_assert (op
== UNOP_CAST
);
817 res_val
= value_cast (type
, val
);
820 result
= value_to_value_object (res_val
);
822 catch (const gdb_exception
&except
)
824 GDB_PY_HANDLE_EXCEPTION (except
);
830 /* Implementation of the "cast" method. */
833 valpy_cast (PyObject
*self
, PyObject
*args
)
835 return valpy_do_cast (self
, args
, UNOP_CAST
);
838 /* Implementation of the "dynamic_cast" method. */
841 valpy_dynamic_cast (PyObject
*self
, PyObject
*args
)
843 return valpy_do_cast (self
, args
, UNOP_DYNAMIC_CAST
);
846 /* Implementation of the "reinterpret_cast" method. */
849 valpy_reinterpret_cast (PyObject
*self
, PyObject
*args
)
851 return valpy_do_cast (self
, args
, UNOP_REINTERPRET_CAST
);
855 valpy_length (PyObject
*self
)
857 /* We don't support getting the number of elements in a struct / class. */
858 PyErr_SetString (PyExc_NotImplementedError
,
859 _("Invalid operation on gdb.Value."));
863 /* Return 1 if the gdb.Field object FIELD is present in the value V.
864 Returns 0 otherwise. If any Python error occurs, -1 is returned. */
867 value_has_field (struct value
*v
, PyObject
*field
)
869 struct type
*parent_type
, *val_type
;
870 enum type_code type_code
;
871 gdbpy_ref
<> type_object (PyObject_GetAttrString (field
, "parent_type"));
874 if (type_object
== NULL
)
877 parent_type
= type_object_to_type (type_object
.get ());
878 if (parent_type
== NULL
)
880 PyErr_SetString (PyExc_TypeError
,
881 _("'parent_type' attribute of gdb.Field object is not a"
882 "gdb.Type object."));
888 val_type
= v
->type ();
889 val_type
= check_typedef (val_type
);
890 if (val_type
->is_pointer_or_reference ())
891 val_type
= check_typedef (val_type
->target_type ());
893 type_code
= val_type
->code ();
894 if ((type_code
== TYPE_CODE_STRUCT
|| type_code
== TYPE_CODE_UNION
)
895 && types_equal (val_type
, parent_type
))
900 catch (const gdb_exception
&except
)
902 GDB_PY_SET_HANDLE_EXCEPTION (except
);
908 /* Return the value of a flag FLAG_NAME in a gdb.Field object FIELD.
909 Returns 1 if the flag value is true, 0 if it is false, and -1 if
910 a Python error occurs. */
913 get_field_flag (PyObject
*field
, const char *flag_name
)
915 gdbpy_ref
<> flag_object (PyObject_GetAttrString (field
, flag_name
));
917 if (flag_object
== NULL
)
920 return PyObject_IsTrue (flag_object
.get ());
923 /* Return the "type" attribute of a gdb.Field object.
924 Returns NULL on error, with a Python exception set. */
927 get_field_type (PyObject
*field
)
929 gdbpy_ref
<> ftype_obj (PyObject_GetAttrString (field
, "type"));
932 if (ftype_obj
== NULL
)
934 ftype
= type_object_to_type (ftype_obj
.get ());
936 PyErr_SetString (PyExc_TypeError
,
937 _("'type' attribute of gdb.Field object is not a "
938 "gdb.Type object."));
943 /* Given string name or a gdb.Field object corresponding to an element inside
944 a structure, return its value object. Returns NULL on error, with a python
948 valpy_getitem (PyObject
*self
, PyObject
*key
)
950 struct gdb_exception except
;
951 value_object
*self_value
= (value_object
*) self
;
952 gdb::unique_xmalloc_ptr
<char> field
;
953 struct type
*base_class_type
= NULL
, *field_type
= NULL
;
955 PyObject
*result
= NULL
;
957 if (gdbpy_is_string (key
))
959 field
= python_string_to_host_string (key
);
963 else if (gdbpy_is_field (key
))
965 int is_base_class
, valid_field
;
967 valid_field
= value_has_field (self_value
->value
, key
);
970 else if (valid_field
== 0)
972 PyErr_SetString (PyExc_TypeError
,
973 _("Invalid lookup for a field not contained in "
979 is_base_class
= get_field_flag (key
, "is_base_class");
980 if (is_base_class
< 0)
982 else if (is_base_class
> 0)
984 base_class_type
= get_field_type (key
);
985 if (base_class_type
== NULL
)
990 gdbpy_ref
<> name_obj (PyObject_GetAttrString (key
, "name"));
992 if (name_obj
== NULL
)
995 if (name_obj
!= Py_None
)
997 field
= python_string_to_host_string (name_obj
.get ());
1003 if (!PyObject_HasAttrString (key
, "bitpos"))
1005 PyErr_SetString (PyExc_AttributeError
,
1006 _("gdb.Field object has no name and no "
1007 "'bitpos' attribute."));
1011 gdbpy_ref
<> bitpos_obj (PyObject_GetAttrString (key
, "bitpos"));
1012 if (bitpos_obj
== NULL
)
1014 if (!gdb_py_int_as_long (bitpos_obj
.get (), &bitpos
))
1017 field_type
= get_field_type (key
);
1018 if (field_type
== NULL
)
1026 struct value
*tmp
= self_value
->value
;
1027 struct value
*res_val
= NULL
;
1028 scoped_value_mark free_values
;
1031 res_val
= value_struct_elt (&tmp
, {}, field
.get (), NULL
,
1032 "struct/class/union");
1033 else if (bitpos
>= 0)
1034 res_val
= value_struct_elt_bitpos (&tmp
, bitpos
, field_type
,
1035 "struct/class/union");
1036 else if (base_class_type
!= NULL
)
1038 struct type
*val_type
;
1040 val_type
= check_typedef (tmp
->type ());
1041 if (val_type
->code () == TYPE_CODE_PTR
)
1042 res_val
= value_cast (lookup_pointer_type (base_class_type
), tmp
);
1043 else if (val_type
->code () == TYPE_CODE_REF
)
1044 res_val
= value_cast (lookup_lvalue_reference_type (base_class_type
),
1046 else if (val_type
->code () == TYPE_CODE_RVALUE_REF
)
1047 res_val
= value_cast (lookup_rvalue_reference_type (base_class_type
),
1050 res_val
= value_cast (base_class_type
, tmp
);
1054 /* Assume we are attempting an array access, and let the
1055 value code throw an exception if the index has an invalid
1057 struct value
*idx
= convert_value_from_python (key
);
1061 /* Check the value's type is something that can be accessed via
1065 tmp
= coerce_ref (tmp
);
1066 type
= check_typedef (tmp
->type ());
1067 if (type
->code () != TYPE_CODE_ARRAY
1068 && type
->code () != TYPE_CODE_PTR
)
1069 error (_("Cannot subscript requested type."));
1071 res_val
= value_subscript (tmp
, value_as_long (idx
));
1076 result
= value_to_value_object (res_val
);
1078 catch (gdb_exception
&ex
)
1080 except
= std::move (ex
);
1083 GDB_PY_HANDLE_EXCEPTION (except
);
1089 valpy_setitem (PyObject
*self
, PyObject
*key
, PyObject
*value
)
1091 PyErr_Format (PyExc_NotImplementedError
,
1092 _("Setting of struct elements is not currently supported."));
1096 /* Called by the Python interpreter to perform an inferior function
1097 call on the value. Returns NULL on error, with a python exception set. */
1099 valpy_call (PyObject
*self
, PyObject
*args
, PyObject
*keywords
)
1101 Py_ssize_t args_count
;
1102 struct value
*function
= ((value_object
*) self
)->value
;
1103 struct value
**vargs
= NULL
;
1104 struct type
*ftype
= NULL
;
1105 PyObject
*result
= NULL
;
1109 ftype
= check_typedef (function
->type ());
1111 catch (const gdb_exception
&except
)
1113 GDB_PY_HANDLE_EXCEPTION (except
);
1116 if (ftype
->code () != TYPE_CODE_FUNC
)
1118 PyErr_SetString (PyExc_RuntimeError
,
1119 _("Value is not callable (not TYPE_CODE_FUNC)."));
1123 if (! PyTuple_Check (args
))
1125 PyErr_SetString (PyExc_TypeError
,
1126 _("Inferior arguments must be provided in a tuple."));
1130 args_count
= PyTuple_Size (args
);
1135 vargs
= XALLOCAVEC (struct value
*, args_count
);
1136 for (i
= 0; i
< args_count
; i
++)
1138 PyObject
*item
= PyTuple_GetItem (args
, i
);
1143 vargs
[i
] = convert_value_from_python (item
);
1144 if (vargs
[i
] == NULL
)
1151 scoped_value_mark free_values
;
1154 = call_function_by_hand (function
, NULL
,
1155 gdb::make_array_view (vargs
, args_count
));
1156 result
= value_to_value_object (return_value
);
1158 catch (const gdb_exception
&except
)
1160 GDB_PY_HANDLE_EXCEPTION (except
);
1166 /* Called by the Python interpreter to obtain string representation
1169 valpy_str (PyObject
*self
)
1171 struct value_print_options opts
;
1173 gdbpy_get_print_options (&opts
);
1174 opts
.deref_ref
= false;
1180 common_val_print (((value_object
*) self
)->value
, &stb
, 0,
1181 &opts
, current_language
);
1183 catch (const gdb_exception
&except
)
1185 GDB_PY_HANDLE_EXCEPTION (except
);
1188 return PyUnicode_Decode (stb
.c_str (), stb
.size (), host_charset (), NULL
);
1191 /* Implements gdb.Value.is_optimized_out. */
1193 valpy_get_is_optimized_out (PyObject
*self
, void *closure
)
1195 struct value
*value
= ((value_object
*) self
)->value
;
1200 opt
= value_optimized_out (value
);
1202 catch (const gdb_exception
&except
)
1204 GDB_PY_HANDLE_EXCEPTION (except
);
1213 /* Implements gdb.Value.is_lazy. */
1215 valpy_get_is_lazy (PyObject
*self
, void *closure
)
1217 struct value
*value
= ((value_object
*) self
)->value
;
1222 opt
= value
->lazy ();
1224 catch (const gdb_exception
&except
)
1226 GDB_PY_HANDLE_EXCEPTION (except
);
1235 /* Implements gdb.Value.fetch_lazy (). */
1237 valpy_fetch_lazy (PyObject
*self
, PyObject
*args
)
1239 struct value
*value
= ((value_object
*) self
)->value
;
1244 value
->fetch_lazy ();
1246 catch (const gdb_exception
&except
)
1248 GDB_PY_HANDLE_EXCEPTION (except
);
1254 /* Calculate and return the address of the PyObject as the value of
1255 the builtin __hash__ call. */
1257 valpy_hash (PyObject
*self
)
1259 return (intptr_t) self
;
1277 /* If TYPE is a reference, return the target; otherwise return TYPE. */
1278 #define STRIP_REFERENCE(TYPE) \
1279 (TYPE_IS_REFERENCE (TYPE) ? ((TYPE)->target_type ()) : (TYPE))
1281 /* Helper for valpy_binop. Returns a value object which is the result
1282 of applying the operation specified by OPCODE to the given
1283 arguments. Throws a GDB exception on error. */
1286 valpy_binop_throw (enum valpy_opcode opcode
, PyObject
*self
, PyObject
*other
)
1288 PyObject
*result
= NULL
;
1290 struct value
*arg1
, *arg2
;
1291 struct value
*res_val
= NULL
;
1292 enum exp_opcode op
= OP_NULL
;
1295 scoped_value_mark free_values
;
1297 /* If the gdb.Value object is the second operand, then it will be
1298 passed to us as the OTHER argument, and SELF will be an entirely
1299 different kind of object, altogether. Because of this, we can't
1300 assume self is a gdb.Value object and need to convert it from
1302 arg1
= convert_value_from_python (self
);
1306 arg2
= convert_value_from_python (other
);
1314 struct type
*ltype
= arg1
->type ();
1315 struct type
*rtype
= arg2
->type ();
1317 ltype
= check_typedef (ltype
);
1318 ltype
= STRIP_REFERENCE (ltype
);
1319 rtype
= check_typedef (rtype
);
1320 rtype
= STRIP_REFERENCE (rtype
);
1323 if (ltype
->code () == TYPE_CODE_PTR
1324 && is_integral_type (rtype
))
1325 res_val
= value_ptradd (arg1
, value_as_long (arg2
));
1326 else if (rtype
->code () == TYPE_CODE_PTR
1327 && is_integral_type (ltype
))
1328 res_val
= value_ptradd (arg2
, value_as_long (arg1
));
1338 struct type
*ltype
= arg1
->type ();
1339 struct type
*rtype
= arg2
->type ();
1341 ltype
= check_typedef (ltype
);
1342 ltype
= STRIP_REFERENCE (ltype
);
1343 rtype
= check_typedef (rtype
);
1344 rtype
= STRIP_REFERENCE (rtype
);
1347 if (ltype
->code () == TYPE_CODE_PTR
1348 && rtype
->code () == TYPE_CODE_PTR
)
1349 /* A ptrdiff_t for the target would be preferable here. */
1350 res_val
= value_from_longest (builtin_type_pyint
,
1351 value_ptrdiff (arg1
, arg2
));
1352 else if (ltype
->code () == TYPE_CODE_PTR
1353 && is_integral_type (rtype
))
1354 res_val
= value_ptradd (arg1
, - value_as_long (arg2
));
1381 op
= BINOP_BITWISE_AND
;
1384 op
= BINOP_BITWISE_IOR
;
1387 op
= BINOP_BITWISE_XOR
;
1393 if (binop_user_defined_p (op
, arg1
, arg2
))
1394 res_val
= value_x_binop (arg1
, arg2
, op
, OP_NULL
, EVAL_NORMAL
);
1396 res_val
= value_binop (arg1
, arg2
, op
);
1400 result
= value_to_value_object (res_val
);
1405 /* Returns a value object which is the result of applying the operation
1406 specified by OPCODE to the given arguments. Returns NULL on error, with
1407 a python exception set. */
1409 valpy_binop (enum valpy_opcode opcode
, PyObject
*self
, PyObject
*other
)
1411 PyObject
*result
= NULL
;
1415 result
= valpy_binop_throw (opcode
, self
, other
);
1417 catch (const gdb_exception
&except
)
1419 GDB_PY_HANDLE_EXCEPTION (except
);
1426 valpy_add (PyObject
*self
, PyObject
*other
)
1428 return valpy_binop (VALPY_ADD
, self
, other
);
1432 valpy_subtract (PyObject
*self
, PyObject
*other
)
1434 return valpy_binop (VALPY_SUB
, self
, other
);
1438 valpy_multiply (PyObject
*self
, PyObject
*other
)
1440 return valpy_binop (VALPY_MUL
, self
, other
);
1444 valpy_divide (PyObject
*self
, PyObject
*other
)
1446 return valpy_binop (VALPY_DIV
, self
, other
);
1450 valpy_remainder (PyObject
*self
, PyObject
*other
)
1452 return valpy_binop (VALPY_REM
, self
, other
);
1456 valpy_power (PyObject
*self
, PyObject
*other
, PyObject
*unused
)
1458 /* We don't support the ternary form of pow. I don't know how to express
1459 that, so let's just throw NotImplementedError to at least do something
1461 if (unused
!= Py_None
)
1463 PyErr_SetString (PyExc_NotImplementedError
,
1464 "Invalid operation on gdb.Value.");
1468 return valpy_binop (VALPY_POW
, self
, other
);
1472 valpy_negative (PyObject
*self
)
1474 PyObject
*result
= NULL
;
1478 /* Perhaps overkill, but consistency has some virtue. */
1479 scoped_value_mark free_values
;
1482 val
= value_neg (((value_object
*) self
)->value
);
1483 result
= value_to_value_object (val
);
1485 catch (const gdb_exception
&except
)
1487 GDB_PY_HANDLE_EXCEPTION (except
);
1494 valpy_positive (PyObject
*self
)
1496 return value_to_value_object (((value_object
*) self
)->value
);
1500 valpy_absolute (PyObject
*self
)
1502 struct value
*value
= ((value_object
*) self
)->value
;
1507 scoped_value_mark free_values
;
1509 if (value_less (value
, value::zero (value
->type (), not_lval
)))
1512 catch (const gdb_exception
&except
)
1514 GDB_PY_HANDLE_EXCEPTION (except
);
1518 return valpy_positive (self
);
1520 return valpy_negative (self
);
1523 /* Implements boolean evaluation of gdb.Value. */
1525 valpy_nonzero (PyObject
*self
)
1527 struct gdb_exception except
;
1528 value_object
*self_value
= (value_object
*) self
;
1530 int nonzero
= 0; /* Appease GCC warning. */
1534 type
= check_typedef (self_value
->value
->type ());
1536 if (is_integral_type (type
) || type
->code () == TYPE_CODE_PTR
)
1537 nonzero
= !!value_as_long (self_value
->value
);
1538 else if (is_floating_value (self_value
->value
))
1539 nonzero
= !target_float_is_zero
1540 (value_contents (self_value
->value
).data (), type
);
1542 /* All other values are True. */
1545 catch (gdb_exception
&ex
)
1547 except
= std::move (ex
);
1550 /* This is not documented in the Python documentation, but if this
1551 function fails, return -1 as slot_nb_nonzero does (the default
1552 Python nonzero function). */
1553 GDB_PY_SET_HANDLE_EXCEPTION (except
);
1558 /* Implements ~ for value objects. */
1560 valpy_invert (PyObject
*self
)
1562 struct value
*val
= NULL
;
1566 val
= value_complement (((value_object
*) self
)->value
);
1568 catch (const gdb_exception
&except
)
1570 GDB_PY_HANDLE_EXCEPTION (except
);
1573 return value_to_value_object (val
);
1576 /* Implements left shift for value objects. */
1578 valpy_lsh (PyObject
*self
, PyObject
*other
)
1580 return valpy_binop (VALPY_LSH
, self
, other
);
1583 /* Implements right shift for value objects. */
1585 valpy_rsh (PyObject
*self
, PyObject
*other
)
1587 return valpy_binop (VALPY_RSH
, self
, other
);
1590 /* Implements bitwise and for value objects. */
1592 valpy_and (PyObject
*self
, PyObject
*other
)
1594 return valpy_binop (VALPY_BITAND
, self
, other
);
1597 /* Implements bitwise or for value objects. */
1599 valpy_or (PyObject
*self
, PyObject
*other
)
1601 return valpy_binop (VALPY_BITOR
, self
, other
);
1604 /* Implements bitwise xor for value objects. */
1606 valpy_xor (PyObject
*self
, PyObject
*other
)
1608 return valpy_binop (VALPY_BITXOR
, self
, other
);
1611 /* Helper for valpy_richcompare. Implements comparison operations for
1612 value objects. Returns true/false on success. Returns -1 with a
1613 Python exception set if a Python error is detected. Throws a GDB
1614 exception on other errors (memory error, etc.). */
1617 valpy_richcompare_throw (PyObject
*self
, PyObject
*other
, int op
)
1620 struct value
*value_other
;
1621 struct value
*value_self
;
1623 scoped_value_mark free_values
;
1625 value_other
= convert_value_from_python (other
);
1626 if (value_other
== NULL
)
1629 value_self
= ((value_object
*) self
)->value
;
1634 result
= value_less (value_self
, value_other
);
1637 result
= value_less (value_self
, value_other
)
1638 || value_equal (value_self
, value_other
);
1641 result
= value_equal (value_self
, value_other
);
1644 result
= !value_equal (value_self
, value_other
);
1647 result
= value_less (value_other
, value_self
);
1650 result
= (value_less (value_other
, value_self
)
1651 || value_equal (value_self
, value_other
));
1655 PyErr_SetString (PyExc_NotImplementedError
,
1656 _("Invalid operation on gdb.Value."));
1665 /* Implements comparison operations for value objects. Returns NULL on error,
1666 with a python exception set. */
1668 valpy_richcompare (PyObject
*self
, PyObject
*other
, int op
)
1672 if (other
== Py_None
)
1673 /* Comparing with None is special. From what I can tell, in Python
1674 None is smaller than anything else. */
1686 PyErr_SetString (PyExc_NotImplementedError
,
1687 _("Invalid operation on gdb.Value."));
1693 result
= valpy_richcompare_throw (self
, other
, op
);
1695 catch (const gdb_exception
&except
)
1697 GDB_PY_HANDLE_EXCEPTION (except
);
1700 /* In this case, the Python exception has already been set. */
1710 /* Implements conversion to long. */
1712 valpy_long (PyObject
*self
)
1714 struct value
*value
= ((value_object
*) self
)->value
;
1715 struct type
*type
= value
->type ();
1720 if (is_floating_value (value
))
1722 type
= builtin_type_pylong
;
1723 value
= value_cast (type
, value
);
1726 type
= check_typedef (type
);
1728 if (!is_integral_type (type
)
1729 && type
->code () != TYPE_CODE_PTR
)
1730 error (_("Cannot convert value to long."));
1732 l
= value_as_long (value
);
1734 catch (const gdb_exception
&except
)
1736 GDB_PY_HANDLE_EXCEPTION (except
);
1739 if (type
->is_unsigned ())
1740 return gdb_py_object_from_ulongest (l
).release ();
1742 return gdb_py_object_from_longest (l
).release ();
1745 /* Implements conversion to float. */
1747 valpy_float (PyObject
*self
)
1749 struct value
*value
= ((value_object
*) self
)->value
;
1750 struct type
*type
= value
->type ();
1755 type
= check_typedef (type
);
1757 if (type
->code () == TYPE_CODE_FLT
&& is_floating_value (value
))
1758 d
= target_float_to_host_double (value_contents (value
).data (), type
);
1759 else if (type
->code () == TYPE_CODE_INT
)
1761 /* Note that valpy_long accepts TYPE_CODE_PTR and some
1762 others here here -- but casting a pointer or bool to a
1763 float seems wrong. */
1764 d
= value_as_long (value
);
1767 error (_("Cannot convert value to float."));
1769 catch (const gdb_exception
&except
)
1771 GDB_PY_HANDLE_EXCEPTION (except
);
1774 return PyFloat_FromDouble (d
);
1777 /* Returns an object for a value which is released from the all_values chain,
1778 so its lifetime is not bound to the execution of a command. */
1780 value_to_value_object (struct value
*val
)
1782 value_object
*val_obj
;
1784 val_obj
= PyObject_New (value_object
, &value_object_type
);
1785 if (val_obj
!= NULL
)
1787 val_obj
->value
= release_value (val
).release ();
1788 val_obj
->next
= nullptr;
1789 val_obj
->prev
= nullptr;
1790 val_obj
->address
= NULL
;
1791 val_obj
->type
= NULL
;
1792 val_obj
->dynamic_type
= NULL
;
1793 note_value (val_obj
);
1796 return (PyObject
*) val_obj
;
1799 /* Returns an object for a value, but without releasing it from the
1800 all_values chain. */
1802 value_to_value_object_no_release (struct value
*val
)
1804 value_object
*val_obj
;
1806 val_obj
= PyObject_New (value_object
, &value_object_type
);
1807 if (val_obj
!= NULL
)
1810 val_obj
->value
= val
;
1811 val_obj
->next
= nullptr;
1812 val_obj
->prev
= nullptr;
1813 val_obj
->address
= NULL
;
1814 val_obj
->type
= NULL
;
1815 val_obj
->dynamic_type
= NULL
;
1816 note_value (val_obj
);
1819 return (PyObject
*) val_obj
;
1822 /* Returns a borrowed reference to the struct value corresponding to
1823 the given value object. */
1825 value_object_to_value (PyObject
*self
)
1829 if (! PyObject_TypeCheck (self
, &value_object_type
))
1831 real
= (value_object
*) self
;
1835 /* Try to convert a Python value to a gdb value. If the value cannot
1836 be converted, set a Python exception and return NULL. Returns a
1837 reference to a new value on the all_values chain. */
1840 convert_value_from_python (PyObject
*obj
)
1842 struct value
*value
= NULL
; /* -Wall */
1845 gdb_assert (obj
!= NULL
);
1849 if (PyBool_Check (obj
))
1851 cmp
= PyObject_IsTrue (obj
);
1853 value
= value_from_longest (builtin_type_pybool
, cmp
);
1855 else if (PyLong_Check (obj
))
1857 LONGEST l
= PyLong_AsLongLong (obj
);
1859 if (PyErr_Occurred ())
1861 /* If the error was an overflow, we can try converting to
1862 ULONGEST instead. */
1863 if (PyErr_ExceptionMatches (PyExc_OverflowError
))
1865 gdbpy_err_fetch fetched_error
;
1866 gdbpy_ref
<> zero
= gdb_py_object_from_longest (0);
1868 /* Check whether obj is positive. */
1869 if (PyObject_RichCompareBool (obj
, zero
.get (), Py_GT
) > 0)
1873 ul
= PyLong_AsUnsignedLongLong (obj
);
1874 if (! PyErr_Occurred ())
1875 value
= value_from_ulongest (builtin_type_upylong
, ul
);
1879 /* There's nothing we can do. */
1880 fetched_error
.restore ();
1885 value
= value_from_longest (builtin_type_pylong
, l
);
1887 else if (PyFloat_Check (obj
))
1889 double d
= PyFloat_AsDouble (obj
);
1891 if (! PyErr_Occurred ())
1892 value
= value_from_host_double (builtin_type_pyfloat
, d
);
1894 else if (gdbpy_is_string (obj
))
1896 gdb::unique_xmalloc_ptr
<char> s
1897 = python_string_to_target_string (obj
);
1899 value
= value_cstring (s
.get (), strlen (s
.get ()),
1900 builtin_type_pychar
);
1902 else if (PyObject_TypeCheck (obj
, &value_object_type
))
1903 value
= value_copy (((value_object
*) obj
)->value
);
1904 else if (gdbpy_is_lazy_string (obj
))
1908 result
= PyObject_CallMethodObjArgs (obj
, gdbpy_value_cst
, NULL
);
1909 value
= value_copy (((value_object
*) result
)->value
);
1912 PyErr_Format (PyExc_TypeError
,
1913 _("Could not convert Python object: %S."), obj
);
1915 catch (const gdb_exception
&except
)
1917 gdbpy_convert_exception (except
);
1924 /* Returns value object in the ARGth position in GDB's history. */
1926 gdbpy_history (PyObject
*self
, PyObject
*args
)
1929 struct value
*res_val
= NULL
; /* Initialize to appease gcc warning. */
1931 if (!PyArg_ParseTuple (args
, "i", &i
))
1936 res_val
= access_value_history (i
);
1938 catch (const gdb_exception
&except
)
1940 GDB_PY_HANDLE_EXCEPTION (except
);
1943 return value_to_value_object (res_val
);
1946 /* Add a gdb.Value into GDB's history, and return (as an integer) the
1947 position of the newly added value. */
1949 gdbpy_add_history (PyObject
*self
, PyObject
*args
)
1951 PyObject
*value_obj
;
1953 if (!PyArg_ParseTuple (args
, "O", &value_obj
))
1956 struct value
*value
= convert_value_from_python (value_obj
);
1957 if (value
== nullptr)
1962 int idx
= record_latest_value (value
);
1963 return gdb_py_object_from_longest (idx
).release ();
1965 catch (const gdb_exception
&except
)
1967 GDB_PY_HANDLE_EXCEPTION (except
);
1973 /* Return an integer, the number of items in GDB's history. */
1976 gdbpy_history_count (PyObject
*self
, PyObject
*args
)
1978 return gdb_py_object_from_ulongest (value_history_count ()).release ();
1981 /* Return the value of a convenience variable. */
1983 gdbpy_convenience_variable (PyObject
*self
, PyObject
*args
)
1985 const char *varname
;
1986 struct value
*res_val
= NULL
;
1988 if (!PyArg_ParseTuple (args
, "s", &varname
))
1993 struct internalvar
*var
= lookup_only_internalvar (varname
);
1997 res_val
= value_of_internalvar (gdbpy_enter::get_gdbarch (), var
);
1998 if (res_val
->type ()->code () == TYPE_CODE_VOID
)
2002 catch (const gdb_exception
&except
)
2004 GDB_PY_HANDLE_EXCEPTION (except
);
2007 if (res_val
== NULL
)
2010 return value_to_value_object (res_val
);
2013 /* Set the value of a convenience variable. */
2015 gdbpy_set_convenience_variable (PyObject
*self
, PyObject
*args
)
2017 const char *varname
;
2018 PyObject
*value_obj
;
2019 struct value
*value
= NULL
;
2021 if (!PyArg_ParseTuple (args
, "sO", &varname
, &value_obj
))
2024 /* None means to clear the variable. */
2025 if (value_obj
!= Py_None
)
2027 value
= convert_value_from_python (value_obj
);
2036 struct internalvar
*var
= lookup_only_internalvar (varname
);
2039 clear_internalvar (var
);
2043 struct internalvar
*var
= lookup_internalvar (varname
);
2045 set_internalvar (var
, value
);
2048 catch (const gdb_exception
&except
)
2050 GDB_PY_HANDLE_EXCEPTION (except
);
2056 /* Returns 1 in OBJ is a gdb.Value object, 0 otherwise. */
2059 gdbpy_is_value_object (PyObject
*obj
)
2061 return PyObject_TypeCheck (obj
, &value_object_type
);
2065 gdbpy_initialize_values (void)
2067 if (PyType_Ready (&value_object_type
) < 0)
2070 return gdb_pymodule_addobject (gdb_module
, "Value",
2071 (PyObject
*) &value_object_type
);
2076 static gdb_PyGetSetDef value_object_getset
[] = {
2077 { "address", valpy_get_address
, NULL
, "The address of the value.",
2079 { "is_optimized_out", valpy_get_is_optimized_out
, NULL
,
2080 "Boolean telling whether the value is optimized "
2081 "out (i.e., not available).",
2083 { "type", valpy_get_type
, NULL
, "Type of the value.", NULL
},
2084 { "dynamic_type", valpy_get_dynamic_type
, NULL
,
2085 "Dynamic type of the value.", NULL
},
2086 { "is_lazy", valpy_get_is_lazy
, NULL
,
2087 "Boolean telling whether the value is lazy (not fetched yet\n\
2088 from the inferior). A lazy value is fetched when needed, or when\n\
2089 the \"fetch_lazy()\" method is called.", NULL
},
2090 {NULL
} /* Sentinel */
2093 static PyMethodDef value_object_methods
[] = {
2094 { "cast", valpy_cast
, METH_VARARGS
, "Cast the value to the supplied type." },
2095 { "dynamic_cast", valpy_dynamic_cast
, METH_VARARGS
,
2096 "dynamic_cast (gdb.Type) -> gdb.Value\n\
2097 Cast the value to the supplied type, as if by the C++ dynamic_cast operator."
2099 { "reinterpret_cast", valpy_reinterpret_cast
, METH_VARARGS
,
2100 "reinterpret_cast (gdb.Type) -> gdb.Value\n\
2101 Cast the value to the supplied type, as if by the C++\n\
2102 reinterpret_cast operator."
2104 { "dereference", valpy_dereference
, METH_NOARGS
, "Dereferences the value." },
2105 { "referenced_value", valpy_referenced_value
, METH_NOARGS
,
2106 "Return the value referenced by a TYPE_CODE_REF or TYPE_CODE_PTR value." },
2107 { "reference_value", valpy_lvalue_reference_value
, METH_NOARGS
,
2108 "Return a value of type TYPE_CODE_REF referencing this value." },
2109 { "rvalue_reference_value", valpy_rvalue_reference_value
, METH_NOARGS
,
2110 "Return a value of type TYPE_CODE_RVALUE_REF referencing this value." },
2111 { "const_value", valpy_const_value
, METH_NOARGS
,
2112 "Return a 'const' qualied version of the same value." },
2113 { "lazy_string", (PyCFunction
) valpy_lazy_string
,
2114 METH_VARARGS
| METH_KEYWORDS
,
2115 "lazy_string ([encoding] [, length]) -> lazy_string\n\
2116 Return a lazy string representation of the value." },
2117 { "string", (PyCFunction
) valpy_string
, METH_VARARGS
| METH_KEYWORDS
,
2118 "string ([encoding] [, errors] [, length]) -> string\n\
2119 Return Unicode string representation of the value." },
2120 { "fetch_lazy", valpy_fetch_lazy
, METH_NOARGS
,
2121 "Fetches the value from the inferior, if it was lazy." },
2122 { "format_string", (PyCFunction
) valpy_format_string
,
2123 METH_VARARGS
| METH_KEYWORDS
,
2124 "format_string (...) -> string\n\
2125 Return a string representation of the value using the specified\n\
2126 formatting options" },
2127 {NULL
} /* Sentinel */
2130 static PyNumberMethods value_object_as_number
= {
2135 NULL
, /* nb_divmod */
2136 valpy_power
, /* nb_power */
2137 valpy_negative
, /* nb_negative */
2138 valpy_positive
, /* nb_positive */
2139 valpy_absolute
, /* nb_absolute */
2140 valpy_nonzero
, /* nb_nonzero */
2141 valpy_invert
, /* nb_invert */
2142 valpy_lsh
, /* nb_lshift */
2143 valpy_rsh
, /* nb_rshift */
2144 valpy_and
, /* nb_and */
2145 valpy_xor
, /* nb_xor */
2146 valpy_or
, /* nb_or */
2147 valpy_long
, /* nb_int */
2148 NULL
, /* reserved */
2149 valpy_float
, /* nb_float */
2150 NULL
, /* nb_inplace_add */
2151 NULL
, /* nb_inplace_subtract */
2152 NULL
, /* nb_inplace_multiply */
2153 NULL
, /* nb_inplace_remainder */
2154 NULL
, /* nb_inplace_power */
2155 NULL
, /* nb_inplace_lshift */
2156 NULL
, /* nb_inplace_rshift */
2157 NULL
, /* nb_inplace_and */
2158 NULL
, /* nb_inplace_xor */
2159 NULL
, /* nb_inplace_or */
2160 NULL
, /* nb_floor_divide */
2161 valpy_divide
, /* nb_true_divide */
2162 NULL
, /* nb_inplace_floor_divide */
2163 NULL
, /* nb_inplace_true_divide */
2164 valpy_long
, /* nb_index */
2167 static PyMappingMethods value_object_as_mapping
= {
2173 PyTypeObject value_object_type
= {
2174 PyVarObject_HEAD_INIT (NULL
, 0)
2175 "gdb.Value", /*tp_name*/
2176 sizeof (value_object
), /*tp_basicsize*/
2178 valpy_dealloc
, /*tp_dealloc*/
2184 &value_object_as_number
, /*tp_as_number*/
2185 0, /*tp_as_sequence*/
2186 &value_object_as_mapping
, /*tp_as_mapping*/
2187 valpy_hash
, /*tp_hash*/
2188 valpy_call
, /*tp_call*/
2189 valpy_str
, /*tp_str*/
2193 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
2194 | Py_TPFLAGS_BASETYPE
, /*tp_flags*/
2195 "GDB value object", /* tp_doc */
2196 0, /* tp_traverse */
2198 valpy_richcompare
, /* tp_richcompare */
2199 0, /* tp_weaklistoffset */
2201 0, /* tp_iternext */
2202 value_object_methods
, /* tp_methods */
2204 value_object_getset
, /* tp_getset */
2207 0, /* tp_descr_get */
2208 0, /* tp_descr_set */
2209 0, /* tp_dictoffset */
2210 valpy_init
, /* tp_init */
2212 PyType_GenericNew
, /* tp_new */