1 /* Python interface to values.
3 Copyright (C) 2008-2024 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"
32 #include "python-internal.h"
34 /* Even though Python scalar types directly map to host types, we use
35 target types here to remain consistent with the values system in
36 GDB (which uses target arithmetic). */
38 /* Python's integer type corresponds to C's long type. */
39 #define builtin_type_pyint \
40 builtin_type (gdbpy_enter::get_gdbarch ())->builtin_long
42 /* Python's float type corresponds to C's double type. */
43 #define builtin_type_pyfloat \
44 builtin_type (gdbpy_enter::get_gdbarch ())->builtin_double
46 /* Python's long type corresponds to C's long long type. */
47 #define builtin_type_pylong \
48 builtin_type (gdbpy_enter::get_gdbarch ())->builtin_long_long
50 /* Python's long type corresponds to C's long long type. Unsigned version. */
51 #define builtin_type_upylong builtin_type \
52 (gdbpy_enter::get_gdbarch ())->builtin_unsigned_long_long
54 #define builtin_type_pybool \
55 language_bool_type (current_language, gdbpy_enter::get_gdbarch ())
59 struct value_object
*next
;
60 struct value_object
*prev
;
64 PyObject
*dynamic_type
;
65 PyObject
*content_bytes
;
68 /* List of all values which are currently exposed to Python. It is
69 maintained so that when an objfile is discarded, preserve_values
70 can copy the values' types if needed. */
71 /* This variable is unnecessarily initialized to NULL in order to
72 work around a linker bug on MacOS. */
73 static value_object
*values_in_python
= NULL
;
75 /* Clear out an old GDB value stored within SELF, and reset the fields to
76 nullptr. This should be called when a gdb.Value is deallocated, and
77 also if a gdb.Value is reinitialized with a new value. */
80 valpy_clear_value (value_object
*self
)
82 /* Indicate we are no longer interested in the value object. */
83 self
->value
->decref ();
84 self
->value
= nullptr;
86 Py_CLEAR (self
->address
);
87 Py_CLEAR (self
->type
);
88 Py_CLEAR (self
->dynamic_type
);
89 Py_CLEAR (self
->content_bytes
);
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
139 nullptr. When REQUIRE_EXACT_SIZE_P is true the buffer OBJ must be the
140 exact length of TYPE. When REQUIRE_EXACT_SIZE_P is false then the
141 buffer OBJ can be longer than TYPE, in which case only the least
142 significant bytes from the buffer are used. */
144 static struct value
*
145 convert_buffer_and_type_to_value (PyObject
*obj
, struct type
*type
,
146 bool require_exact_size_p
)
148 Py_buffer_up buffer_up
;
151 if (PyObject_CheckBuffer (obj
)
152 && PyObject_GetBuffer (obj
, &py_buf
, PyBUF_SIMPLE
) == 0)
154 /* Got a buffer, py_buf, out of obj. Cause it to be released
155 when it goes out of scope. */
156 buffer_up
.reset (&py_buf
);
160 PyErr_SetString (PyExc_TypeError
,
161 _("Object must support the python buffer protocol."));
165 if (require_exact_size_p
&& type
->length () != py_buf
.len
)
167 PyErr_SetString (PyExc_ValueError
,
168 _("Size of type is not equal to that of buffer object."));
171 else if (!require_exact_size_p
&& type
->length () > py_buf
.len
)
173 PyErr_SetString (PyExc_ValueError
,
174 _("Size of type is larger than that of buffer object."));
178 return value_from_contents (type
, (const gdb_byte
*) py_buf
.buf
);
181 /* Implement gdb.Value.__init__. */
184 valpy_init (PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
186 static const char *keywords
[] = { "val", "type", NULL
};
187 PyObject
*val_obj
= nullptr;
188 PyObject
*type_obj
= nullptr;
190 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kwds
, "O|O", keywords
,
191 &val_obj
, &type_obj
))
194 struct type
*type
= nullptr;
195 if (type_obj
!= nullptr && type_obj
!= Py_None
)
197 type
= type_object_to_type (type_obj
);
200 PyErr_SetString (PyExc_TypeError
,
201 _("type argument must be a gdb.Type."));
208 value
= convert_value_from_python (val_obj
);
210 value
= convert_buffer_and_type_to_value (val_obj
, type
, false);
211 if (value
== nullptr)
213 gdb_assert (PyErr_Occurred ());
217 /* There might be a previous value here. */
218 value_object
*value_obj
= (value_object
*) self
;
219 if (value_obj
->value
!= nullptr)
220 valpy_clear_value (value_obj
);
222 /* Store the value into this Python object. */
223 value_obj
->value
= release_value (value
).release ();
225 /* Ensure that this gdb.Value is in the set of all gdb.Value objects. If
226 we are already in the set then this is call does nothing. */
227 note_value (value_obj
);
232 /* Iterate over all the Value objects, calling preserve_one_value on
235 gdbpy_preserve_values (const struct extension_language_defn
*extlang
,
236 struct objfile
*objfile
, htab_t copied_types
)
240 for (iter
= values_in_python
; iter
; iter
= iter
->next
)
241 iter
->value
->preserve (objfile
, copied_types
);
244 /* Given a value of a pointer type, apply the C unary * operator to it. */
246 valpy_dereference (PyObject
*self
, PyObject
*args
)
248 PyObject
*result
= NULL
;
252 struct value
*res_val
;
253 scoped_value_mark free_values
;
255 res_val
= value_ind (((value_object
*) self
)->value
);
256 result
= value_to_value_object (res_val
);
258 catch (const gdb_exception
&except
)
260 return gdbpy_handle_gdb_exception (nullptr, except
);
266 /* Given a value of a pointer type or a reference type, return the value
267 referenced. The difference between this function and valpy_dereference is
268 that the latter applies * unary operator to a value, which need not always
269 result in the value referenced. For example, for a value which is a reference
270 to an 'int' pointer ('int *'), valpy_dereference will result in a value of
271 type 'int' while valpy_referenced_value will result in a value of type
275 valpy_referenced_value (PyObject
*self
, PyObject
*args
)
277 PyObject
*result
= NULL
;
281 struct value
*self_val
, *res_val
;
282 scoped_value_mark free_values
;
284 self_val
= ((value_object
*) self
)->value
;
285 switch (check_typedef (self_val
->type ())->code ())
288 res_val
= value_ind (self_val
);
291 case TYPE_CODE_RVALUE_REF
:
292 res_val
= coerce_ref (self_val
);
295 error(_("Trying to get the referenced value from a value which is "
296 "neither a pointer nor a reference."));
299 result
= value_to_value_object (res_val
);
301 catch (const gdb_exception
&except
)
303 return gdbpy_handle_gdb_exception (nullptr, except
);
309 /* Return a value which is a reference to the value. */
312 valpy_reference_value (PyObject
*self
, PyObject
*args
, enum type_code refcode
)
314 PyObject
*result
= NULL
;
318 struct value
*self_val
;
319 scoped_value_mark free_values
;
321 self_val
= ((value_object
*) self
)->value
;
322 result
= value_to_value_object (value_ref (self_val
, refcode
));
324 catch (const gdb_exception
&except
)
326 return gdbpy_handle_gdb_exception (nullptr, except
);
333 valpy_lvalue_reference_value (PyObject
*self
, PyObject
*args
)
335 return valpy_reference_value (self
, args
, TYPE_CODE_REF
);
339 valpy_rvalue_reference_value (PyObject
*self
, PyObject
*args
)
341 return valpy_reference_value (self
, args
, TYPE_CODE_RVALUE_REF
);
344 /* Implement Value.to_array. */
347 valpy_to_array (PyObject
*self
, PyObject
*args
)
349 PyObject
*result
= nullptr;
353 struct value
*val
= ((value_object
*) self
)->value
;
354 struct type
*type
= check_typedef (val
->type ());
356 if (type
->code () == TYPE_CODE_ARRAY
)
363 val
= value_to_array (val
);
365 PyErr_SetString (PyExc_TypeError
, _("Value is not array-like."));
367 result
= value_to_value_object (val
);
370 catch (const gdb_exception
&except
)
372 return gdbpy_handle_gdb_exception (nullptr, except
);
378 /* Return a "const" qualified version of the value. */
381 valpy_const_value (PyObject
*self
, PyObject
*args
)
383 PyObject
*result
= NULL
;
387 struct value
*self_val
, *res_val
;
388 scoped_value_mark free_values
;
390 self_val
= ((value_object
*) self
)->value
;
391 res_val
= make_cv_value (1, 0, self_val
);
392 result
= value_to_value_object (res_val
);
394 catch (const gdb_exception
&except
)
396 return gdbpy_handle_gdb_exception (nullptr, except
);
402 /* Return "&value". */
404 valpy_get_address (PyObject
*self
, void *closure
)
406 value_object
*val_obj
= (value_object
*) self
;
408 if (!val_obj
->address
)
412 struct value
*res_val
;
413 scoped_value_mark free_values
;
415 res_val
= value_addr (val_obj
->value
);
416 val_obj
->address
= value_to_value_object (res_val
);
418 catch (const gdb_exception_forced_quit
&except
)
420 quit_force (NULL
, 0);
422 catch (const gdb_exception
&except
)
424 val_obj
->address
= Py_None
;
429 Py_XINCREF (val_obj
->address
);
431 return val_obj
->address
;
434 /* Return type of the value. */
436 valpy_get_type (PyObject
*self
, void *closure
)
438 value_object
*obj
= (value_object
*) self
;
442 obj
->type
= type_to_type_object (obj
->value
->type ());
446 Py_INCREF (obj
->type
);
450 /* Return dynamic type of the value. */
453 valpy_get_dynamic_type (PyObject
*self
, void *closure
)
455 value_object
*obj
= (value_object
*) self
;
456 struct type
*type
= NULL
;
458 if (obj
->dynamic_type
!= NULL
)
460 Py_INCREF (obj
->dynamic_type
);
461 return obj
->dynamic_type
;
466 struct value
*val
= obj
->value
;
467 scoped_value_mark free_values
;
470 type
= check_typedef (type
);
472 if (type
->is_pointer_or_reference ()
473 && (type
->target_type ()->code () == TYPE_CODE_STRUCT
))
475 struct value
*target
;
476 int was_pointer
= type
->code () == TYPE_CODE_PTR
;
479 target
= value_ind (val
);
481 target
= coerce_ref (val
);
482 type
= value_rtti_type (target
, NULL
, NULL
, NULL
);
487 type
= lookup_pointer_type (type
);
489 type
= lookup_lvalue_reference_type (type
);
492 else if (type
->code () == TYPE_CODE_STRUCT
)
493 type
= value_rtti_type (val
, NULL
, NULL
, NULL
);
496 /* Re-use object's static type. */
500 catch (const gdb_exception
&except
)
502 return gdbpy_handle_gdb_exception (nullptr, except
);
506 obj
->dynamic_type
= valpy_get_type (self
, NULL
);
508 obj
->dynamic_type
= type_to_type_object (type
);
510 Py_XINCREF (obj
->dynamic_type
);
511 return obj
->dynamic_type
;
514 /* Implementation of gdb.Value.lazy_string ([encoding] [, length]) ->
515 string. Return a PyObject representing a lazy_string_object type.
516 A lazy string is a pointer to a string with an optional encoding and
517 length. If ENCODING is not given, encoding is set to None. If an
518 ENCODING is provided the encoding parameter is set to ENCODING, but
519 the string is not encoded.
520 If LENGTH is provided then the length parameter is set to LENGTH.
521 Otherwise if the value is an array of known length then the array's length
522 is used. Otherwise the length will be set to -1 (meaning first null of
525 Note: In order to not break any existing uses this allows creating
526 lazy strings from anything. PR 20769. E.g.,
527 gdb.parse_and_eval("my_int_variable").lazy_string().
528 "It's easier to relax restrictions than it is to impose them after the
529 fact." So we should be flagging any unintended uses as errors, but it's
530 perhaps too late for that. */
533 valpy_lazy_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
535 gdb_py_longest length
= -1;
536 struct value
*value
= ((value_object
*) self
)->value
;
537 const char *user_encoding
= NULL
;
538 static const char *keywords
[] = { "encoding", "length", NULL
};
539 PyObject
*str_obj
= NULL
;
541 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "|s" GDB_PY_LL_ARG
,
542 keywords
, &user_encoding
, &length
))
547 PyErr_SetString (PyExc_ValueError
, _("Invalid length."));
553 scoped_value_mark free_values
;
554 struct type
*type
, *realtype
;
557 type
= value
->type ();
558 realtype
= check_typedef (type
);
560 switch (realtype
->code ())
562 case TYPE_CODE_ARRAY
:
564 LONGEST array_length
= -1;
565 LONGEST low_bound
, high_bound
;
567 /* PR 20786: There's no way to specify an array of length zero.
568 Record a length of [0,-1] which is how Ada does it. Anything
569 we do is broken, but this one possible solution. */
570 if (get_array_bounds (realtype
, &low_bound
, &high_bound
))
571 array_length
= high_bound
- low_bound
+ 1;
573 length
= array_length
;
574 else if (array_length
== -1)
576 type
= lookup_array_range_type (realtype
->target_type (),
579 else if (length
!= array_length
)
581 /* We need to create a new array type with the
583 if (length
> array_length
)
584 error (_("Length is larger than array size."));
585 type
= lookup_array_range_type (realtype
->target_type (),
587 low_bound
+ length
- 1);
589 addr
= value
->address ();
593 /* If a length is specified we defer creating an array of the
594 specified width until we need to. */
595 addr
= value_as_address (value
);
598 /* Should flag an error here. PR 20769. */
599 addr
= value
->address ();
603 str_obj
= gdbpy_create_lazy_string_object (addr
, length
, user_encoding
,
606 catch (const gdb_exception
&except
)
608 return gdbpy_handle_gdb_exception (nullptr, except
);
614 /* Implementation of gdb.Value.string ([encoding] [, errors]
615 [, length]) -> string. Return Unicode string with value contents.
616 If ENCODING is not given, the string is assumed to be encoded in
617 the target's charset. If LENGTH is provided, only fetch string to
618 the length provided. */
621 valpy_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
624 gdb::unique_xmalloc_ptr
<gdb_byte
> buffer
;
625 struct value
*value
= ((value_object
*) self
)->value
;
626 const char *encoding
= NULL
;
627 const char *errors
= NULL
;
628 const char *user_encoding
= NULL
;
629 const char *la_encoding
= NULL
;
630 struct type
*char_type
;
631 static const char *keywords
[] = { "encoding", "errors", "length", NULL
};
633 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "|ssi", keywords
,
634 &user_encoding
, &errors
, &length
))
639 c_get_string (value
, &buffer
, &length
, &char_type
, &la_encoding
);
641 catch (const gdb_exception
&except
)
643 return gdbpy_handle_gdb_exception (nullptr, except
);
646 encoding
= (user_encoding
&& *user_encoding
) ? user_encoding
: la_encoding
;
647 return PyUnicode_Decode ((const char *) buffer
.get (),
648 length
* char_type
->length (),
652 /* Given a Python object, copy its truth value to a C bool (the value
654 If src_obj is NULL, then *dest is not modified.
656 Return true in case of success (including src_obj being NULL), false
660 copy_py_bool_obj (bool *dest
, PyObject
*src_obj
)
664 int cmp
= PyObject_IsTrue (src_obj
);
673 /* Implementation of gdb.Value.format_string (...) -> string.
674 Return Unicode string with value contents formatted using the
675 keyword-only arguments. */
678 valpy_format_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
680 static const char *keywords
[] =
682 /* Basic C/C++ options. */
683 "raw", /* See the /r option to print. */
684 "pretty_arrays", /* See set print array on|off. */
685 "pretty_structs", /* See set print pretty on|off. */
686 "array_indexes", /* See set print array-indexes on|off. */
687 "symbols", /* See set print symbol on|off. */
688 "unions", /* See set print union on|off. */
689 "address", /* See set print address on|off. */
690 "styling", /* Should we apply styling. */
691 "nibbles", /* See set print nibbles on|off. */
692 "summary", /* Summary mode for non-scalars. */
694 "deref_refs", /* No corresponding setting. */
695 "actual_objects", /* See set print object on|off. */
696 "static_members", /* See set print static-members on|off. */
697 /* C non-bool options. */
698 "max_characters", /* See set print characters N. */
699 "max_elements", /* See set print elements N. */
700 "max_depth", /* See set print max-depth N. */
701 "repeat_threshold", /* See set print repeats. */
702 "format", /* The format passed to the print command. */
706 /* This function has too many arguments to be useful as positionals, so
707 the user should specify them all as keyword arguments.
708 Python 3.3 and later have a way to specify it (both in C and Python
709 itself), but we could be compiled with older versions, so we just
710 check that the args tuple is empty. */
711 Py_ssize_t positional_count
= PyObject_Length (args
);
712 if (positional_count
< 0)
714 else if (positional_count
> 0)
716 /* This matches the error message that Python 3.3 raises when
717 passing positionals to functions expecting keyword-only
719 PyErr_Format (PyExc_TypeError
,
720 "format_string() takes 0 positional arguments but %zu were given",
725 struct value_print_options opts
;
726 gdbpy_get_print_options (&opts
);
727 opts
.deref_ref
= false;
729 /* We need objects for booleans as the "p" flag for bools is new in
731 PyObject
*raw_obj
= NULL
;
732 PyObject
*pretty_arrays_obj
= NULL
;
733 PyObject
*pretty_structs_obj
= NULL
;
734 PyObject
*array_indexes_obj
= NULL
;
735 PyObject
*symbols_obj
= NULL
;
736 PyObject
*unions_obj
= NULL
;
737 PyObject
*address_obj
= NULL
;
738 PyObject
*styling_obj
= Py_False
;
739 PyObject
*nibbles_obj
= NULL
;
740 PyObject
*deref_refs_obj
= NULL
;
741 PyObject
*actual_objects_obj
= NULL
;
742 PyObject
*static_members_obj
= NULL
;
743 PyObject
*summary_obj
= NULL
;
745 if (!gdb_PyArg_ParseTupleAndKeywords (args
,
747 "|O!O!O!O!O!O!O!O!O!O!O!O!O!IIIIs",
749 &PyBool_Type
, &raw_obj
,
750 &PyBool_Type
, &pretty_arrays_obj
,
751 &PyBool_Type
, &pretty_structs_obj
,
752 &PyBool_Type
, &array_indexes_obj
,
753 &PyBool_Type
, &symbols_obj
,
754 &PyBool_Type
, &unions_obj
,
755 &PyBool_Type
, &address_obj
,
756 &PyBool_Type
, &styling_obj
,
757 &PyBool_Type
, &nibbles_obj
,
758 &PyBool_Type
, &summary_obj
,
759 &PyBool_Type
, &deref_refs_obj
,
760 &PyBool_Type
, &actual_objects_obj
,
761 &PyBool_Type
, &static_members_obj
,
762 &opts
.print_max_chars
,
765 &opts
.repeat_count_threshold
,
769 /* Set boolean arguments. */
770 if (!copy_py_bool_obj (&opts
.raw
, raw_obj
))
772 if (!copy_py_bool_obj (&opts
.prettyformat_arrays
, pretty_arrays_obj
))
774 if (!copy_py_bool_obj (&opts
.prettyformat_structs
, pretty_structs_obj
))
776 if (!copy_py_bool_obj (&opts
.print_array_indexes
, array_indexes_obj
))
778 if (!copy_py_bool_obj (&opts
.symbol_print
, symbols_obj
))
780 if (!copy_py_bool_obj (&opts
.unionprint
, unions_obj
))
782 if (!copy_py_bool_obj (&opts
.addressprint
, address_obj
))
784 if (!copy_py_bool_obj (&opts
.nibblesprint
, nibbles_obj
))
786 if (!copy_py_bool_obj (&opts
.deref_ref
, deref_refs_obj
))
788 if (!copy_py_bool_obj (&opts
.objectprint
, actual_objects_obj
))
790 if (!copy_py_bool_obj (&opts
.static_field_print
, static_members_obj
))
792 if (!copy_py_bool_obj (&opts
.summary
, summary_obj
))
795 /* Numeric arguments for which 0 means unlimited (which we represent as
796 UINT_MAX). Note that the max-depth numeric argument uses -1 as
797 unlimited, and 0 is a valid choice. */
798 if (opts
.print_max
== 0)
799 opts
.print_max
= UINT_MAX
;
800 if (opts
.repeat_count_threshold
== 0)
801 opts
.repeat_count_threshold
= UINT_MAX
;
803 /* Other arguments. */
806 if (strlen (format
) == 1)
807 opts
.format
= format
[0];
810 /* Mimic the message on standard Python ones for similar
812 PyErr_SetString (PyExc_ValueError
,
813 "a single character is required");
818 /* We force styling_obj to be a 'bool' when we parse the args above. */
819 gdb_assert (PyBool_Check (styling_obj
));
820 string_file
stb (styling_obj
== Py_True
);
824 common_val_print (((value_object
*) self
)->value
, &stb
, 0,
825 &opts
, current_language
);
827 catch (const gdb_exception
&except
)
829 return gdbpy_handle_gdb_exception (nullptr, except
);
832 return PyUnicode_Decode (stb
.c_str (), stb
.size (), host_charset (), NULL
);
835 /* A helper function that implements the various cast operators. */
838 valpy_do_cast (PyObject
*self
, PyObject
*args
, enum exp_opcode op
)
840 PyObject
*type_obj
, *result
= NULL
;
843 if (! PyArg_ParseTuple (args
, "O", &type_obj
))
846 type
= type_object_to_type (type_obj
);
849 PyErr_SetString (PyExc_RuntimeError
,
850 _("Argument must be a type."));
856 struct value
*val
= ((value_object
*) self
)->value
;
857 struct value
*res_val
;
858 scoped_value_mark free_values
;
860 if (op
== UNOP_DYNAMIC_CAST
)
861 res_val
= value_dynamic_cast (type
, val
);
862 else if (op
== UNOP_REINTERPRET_CAST
)
863 res_val
= value_reinterpret_cast (type
, val
);
866 gdb_assert (op
== UNOP_CAST
);
867 res_val
= value_cast (type
, val
);
870 result
= value_to_value_object (res_val
);
872 catch (const gdb_exception
&except
)
874 return gdbpy_handle_gdb_exception (nullptr, except
);
880 /* Implementation of the "cast" method. */
883 valpy_cast (PyObject
*self
, PyObject
*args
)
885 return valpy_do_cast (self
, args
, UNOP_CAST
);
888 /* Implementation of the "dynamic_cast" method. */
891 valpy_dynamic_cast (PyObject
*self
, PyObject
*args
)
893 return valpy_do_cast (self
, args
, UNOP_DYNAMIC_CAST
);
896 /* Implementation of the "reinterpret_cast" method. */
899 valpy_reinterpret_cast (PyObject
*self
, PyObject
*args
)
901 return valpy_do_cast (self
, args
, UNOP_REINTERPRET_CAST
);
904 /* Assign NEW_VALUE into SELF, handles 'struct value' reference counting,
905 and also clearing the bytes data cached within SELF. Return true if
906 the assignment was successful, otherwise return false, in which case a
907 Python exception will be set. */
910 valpy_assign_core (value_object
*self
, struct value
*new_value
)
914 new_value
= value_assign (self
->value
, new_value
);
916 /* value_as_address returns a new value with the same location
917 as the old one. Ensure that this gdb.Value is updated to
918 reflect the new value. */
919 new_value
->incref ();
920 self
->value
->decref ();
921 Py_CLEAR (self
->content_bytes
);
922 self
->value
= new_value
;
924 catch (const gdb_exception
&except
)
926 return gdbpy_handle_gdb_exception (false, except
);
932 /* Implementation of the "assign" method. */
935 valpy_assign (PyObject
*self_obj
, PyObject
*args
)
939 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
942 struct value
*val
= convert_value_from_python (val_obj
);
946 value_object
*self
= (value_object
*) self_obj
;
947 if (!valpy_assign_core (self
, val
))
954 valpy_length (PyObject
*self
)
956 /* We don't support getting the number of elements in a struct / class. */
957 PyErr_SetString (PyExc_NotImplementedError
,
958 _("Invalid operation on gdb.Value."));
962 /* Return 1 if the gdb.Field object FIELD is present in the value V.
963 Returns 0 otherwise. If any Python error occurs, -1 is returned. */
966 value_has_field (struct value
*v
, PyObject
*field
)
968 struct type
*parent_type
, *val_type
;
969 enum type_code type_code
;
970 gdbpy_ref
<> type_object (PyObject_GetAttrString (field
, "parent_type"));
973 if (type_object
== NULL
)
976 parent_type
= type_object_to_type (type_object
.get ());
977 if (parent_type
== NULL
)
979 PyErr_SetString (PyExc_TypeError
,
980 _("'parent_type' attribute of gdb.Field object is not a"
981 "gdb.Type object."));
987 val_type
= v
->type ();
988 val_type
= check_typedef (val_type
);
989 if (val_type
->is_pointer_or_reference ())
990 val_type
= check_typedef (val_type
->target_type ());
992 type_code
= val_type
->code ();
993 if ((type_code
== TYPE_CODE_STRUCT
|| type_code
== TYPE_CODE_UNION
)
994 && types_equal (val_type
, parent_type
))
999 catch (const gdb_exception
&except
)
1001 return gdbpy_handle_gdb_exception (-1, except
);
1007 /* Return the value of a flag FLAG_NAME in a gdb.Field object FIELD.
1008 Returns 1 if the flag value is true, 0 if it is false, and -1 if
1009 a Python error occurs. */
1012 get_field_flag (PyObject
*field
, const char *flag_name
)
1014 gdbpy_ref
<> flag_object (PyObject_GetAttrString (field
, flag_name
));
1016 if (flag_object
== NULL
)
1019 return PyObject_IsTrue (flag_object
.get ());
1022 /* Return the "type" attribute of a gdb.Field object.
1023 Returns NULL on error, with a Python exception set. */
1025 static struct type
*
1026 get_field_type (PyObject
*field
)
1028 gdbpy_ref
<> ftype_obj (PyObject_GetAttrString (field
, "type"));
1031 if (ftype_obj
== NULL
)
1033 ftype
= type_object_to_type (ftype_obj
.get ());
1035 PyErr_SetString (PyExc_TypeError
,
1036 _("'type' attribute of gdb.Field object is not a "
1037 "gdb.Type object."));
1042 /* Given string name or a gdb.Field object corresponding to an element inside
1043 a structure, return its value object. Returns NULL on error, with a python
1047 valpy_getitem (PyObject
*self
, PyObject
*key
)
1049 value_object
*self_value
= (value_object
*) self
;
1050 gdb::unique_xmalloc_ptr
<char> field
;
1051 struct type
*base_class_type
= NULL
, *field_type
= NULL
;
1053 PyObject
*result
= NULL
;
1055 if (gdbpy_is_string (key
))
1057 field
= python_string_to_host_string (key
);
1061 else if (gdbpy_is_field (key
))
1063 int is_base_class
, valid_field
;
1065 valid_field
= value_has_field (self_value
->value
, key
);
1066 if (valid_field
< 0)
1068 else if (valid_field
== 0)
1070 PyErr_SetString (PyExc_TypeError
,
1071 _("Invalid lookup for a field not contained in "
1077 is_base_class
= get_field_flag (key
, "is_base_class");
1078 if (is_base_class
< 0)
1080 else if (is_base_class
> 0)
1082 base_class_type
= get_field_type (key
);
1083 if (base_class_type
== NULL
)
1088 gdbpy_ref
<> name_obj (PyObject_GetAttrString (key
, "name"));
1090 if (name_obj
== NULL
)
1093 if (name_obj
!= Py_None
)
1095 field
= python_string_to_host_string (name_obj
.get ());
1101 if (!PyObject_HasAttrString (key
, "bitpos"))
1103 PyErr_SetString (PyExc_AttributeError
,
1104 _("gdb.Field object has no name and no "
1105 "'bitpos' attribute."));
1109 gdbpy_ref
<> bitpos_obj (PyObject_GetAttrString (key
, "bitpos"));
1110 if (bitpos_obj
== NULL
)
1112 if (!gdb_py_int_as_long (bitpos_obj
.get (), &bitpos
))
1115 field_type
= get_field_type (key
);
1116 if (field_type
== NULL
)
1124 struct value
*tmp
= self_value
->value
;
1125 struct value
*res_val
= NULL
;
1126 scoped_value_mark free_values
;
1129 res_val
= value_struct_elt (&tmp
, {}, field
.get (), NULL
,
1130 "struct/class/union");
1131 else if (bitpos
>= 0)
1132 res_val
= value_struct_elt_bitpos (&tmp
, bitpos
, field_type
,
1133 "struct/class/union");
1134 else if (base_class_type
!= NULL
)
1136 struct type
*val_type
;
1138 val_type
= check_typedef (tmp
->type ());
1139 if (val_type
->code () == TYPE_CODE_PTR
)
1140 res_val
= value_cast (lookup_pointer_type (base_class_type
), tmp
);
1141 else if (val_type
->code () == TYPE_CODE_REF
)
1142 res_val
= value_cast (lookup_lvalue_reference_type (base_class_type
),
1144 else if (val_type
->code () == TYPE_CODE_RVALUE_REF
)
1145 res_val
= value_cast (lookup_rvalue_reference_type (base_class_type
),
1148 res_val
= value_cast (base_class_type
, tmp
);
1152 /* Assume we are attempting an array access, and let the
1153 value code throw an exception if the index has an invalid
1155 struct value
*idx
= convert_value_from_python (key
);
1158 && binop_user_defined_p (BINOP_SUBSCRIPT
, tmp
, idx
))
1159 res_val
= value_x_binop (tmp
, idx
, BINOP_SUBSCRIPT
,
1160 OP_NULL
, EVAL_NORMAL
);
1161 else if (idx
!= NULL
)
1163 /* Check the value's type is something that can be accessed via
1167 tmp
= coerce_ref (tmp
);
1168 type
= check_typedef (tmp
->type ());
1169 if (type
->code () != TYPE_CODE_ARRAY
1170 && type
->code () != TYPE_CODE_PTR
)
1171 error (_("Cannot subscript requested type."));
1172 else if (ADA_TYPE_P (type
))
1173 res_val
= ada_value_subscript (tmp
, 1, &idx
);
1175 res_val
= value_subscript (tmp
, value_as_long (idx
));
1180 result
= value_to_value_object (res_val
);
1182 catch (const gdb_exception
&ex
)
1184 return gdbpy_handle_gdb_exception (nullptr, ex
);
1191 valpy_setitem (PyObject
*self
, PyObject
*key
, PyObject
*value
)
1193 PyErr_Format (PyExc_NotImplementedError
,
1194 _("Setting of struct elements is not currently supported."));
1198 /* Called by the Python interpreter to perform an inferior function
1199 call on the value. Returns NULL on error, with a python exception set. */
1201 valpy_call (PyObject
*self
, PyObject
*args
, PyObject
*keywords
)
1203 Py_ssize_t args_count
;
1204 struct value
*function
= ((value_object
*) self
)->value
;
1205 struct value
**vargs
= NULL
;
1206 struct type
*ftype
= NULL
;
1207 PyObject
*result
= NULL
;
1211 ftype
= check_typedef (function
->type ());
1213 catch (const gdb_exception
&except
)
1215 return gdbpy_handle_gdb_exception (nullptr, except
);
1218 if (ftype
->code () != TYPE_CODE_FUNC
&& ftype
->code () != TYPE_CODE_METHOD
1219 && ftype
->code () != TYPE_CODE_INTERNAL_FUNCTION
)
1221 PyErr_SetString (PyExc_RuntimeError
,
1222 _("Value is not callable (not TYPE_CODE_FUNC"
1223 " or TYPE_CODE_METHOD"
1224 " or TYPE_CODE_INTERNAL_FUNCTION)."));
1228 if (! PyTuple_Check (args
))
1230 PyErr_SetString (PyExc_TypeError
,
1231 _("Inferior arguments must be provided in a tuple."));
1235 args_count
= PyTuple_Size (args
);
1240 vargs
= XALLOCAVEC (struct value
*, args_count
);
1241 for (i
= 0; i
< args_count
; i
++)
1243 PyObject
*item
= PyTuple_GetItem (args
, i
);
1248 vargs
[i
] = convert_value_from_python (item
);
1249 if (vargs
[i
] == NULL
)
1256 scoped_value_mark free_values
;
1258 value
*return_value
;
1259 if (ftype
->code () == TYPE_CODE_INTERNAL_FUNCTION
)
1260 return_value
= call_internal_function (gdbpy_enter::get_gdbarch (),
1262 function
, args_count
, vargs
,
1266 = call_function_by_hand (function
, NULL
,
1267 gdb::make_array_view (vargs
, args_count
));
1268 result
= value_to_value_object (return_value
);
1270 catch (const gdb_exception
&except
)
1272 return gdbpy_handle_gdb_exception (nullptr, except
);
1278 /* Called by the Python interpreter to obtain string representation
1281 valpy_str (PyObject
*self
)
1283 struct value_print_options opts
;
1285 gdbpy_get_print_options (&opts
);
1286 opts
.deref_ref
= false;
1292 common_val_print (((value_object
*) self
)->value
, &stb
, 0,
1293 &opts
, current_language
);
1295 catch (const gdb_exception
&except
)
1297 return gdbpy_handle_gdb_exception (nullptr, except
);
1300 return PyUnicode_Decode (stb
.c_str (), stb
.size (), host_charset (), NULL
);
1303 /* Implements gdb.Value.is_optimized_out. */
1305 valpy_get_is_optimized_out (PyObject
*self
, void *closure
)
1307 struct value
*value
= ((value_object
*) self
)->value
;
1312 opt
= value
->optimized_out ();
1314 catch (const gdb_exception
&except
)
1316 return gdbpy_handle_gdb_exception (nullptr, except
);
1325 /* Implements gdb.Value.is_lazy. */
1327 valpy_get_is_lazy (PyObject
*self
, void *closure
)
1329 struct value
*value
= ((value_object
*) self
)->value
;
1334 opt
= value
->lazy ();
1336 catch (const gdb_exception
&except
)
1338 return gdbpy_handle_gdb_exception (nullptr, except
);
1347 /* Get gdb.Value.bytes attribute. */
1350 valpy_get_bytes (PyObject
*self
, void *closure
)
1352 value_object
*value_obj
= (value_object
*) self
;
1353 struct value
*value
= value_obj
->value
;
1355 if (value_obj
->content_bytes
!= nullptr)
1357 Py_INCREF (value_obj
->content_bytes
);
1358 return value_obj
->content_bytes
;
1361 gdb::array_view
<const gdb_byte
> contents
;
1364 contents
= value
->contents ();
1366 catch (const gdb_exception
&except
)
1368 return gdbpy_handle_gdb_exception (nullptr, except
);
1371 value_obj
->content_bytes
1372 = PyBytes_FromStringAndSize ((const char *) contents
.data (),
1374 Py_XINCREF (value_obj
->content_bytes
);
1375 return value_obj
->content_bytes
;
1378 /* Set gdb.Value.bytes attribute. */
1381 valpy_set_bytes (PyObject
*self_obj
, PyObject
*new_value_obj
, void *closure
)
1383 value_object
*self
= (value_object
*) self_obj
;
1385 /* Create a new value from the buffer NEW_VALUE_OBJ. We pass true here
1386 to indicate that NEW_VALUE_OBJ must match exactly the type length. */
1387 struct value
*new_value
1388 = convert_buffer_and_type_to_value (new_value_obj
, self
->value
->type (),
1390 if (new_value
== nullptr)
1393 if (!valpy_assign_core (self
, new_value
))
1399 /* Implements gdb.Value.fetch_lazy (). */
1401 valpy_fetch_lazy (PyObject
*self
, PyObject
*args
)
1403 struct value
*value
= ((value_object
*) self
)->value
;
1408 value
->fetch_lazy ();
1410 catch (const gdb_exception
&except
)
1412 return gdbpy_handle_gdb_exception (nullptr, except
);
1418 /* Calculate and return the address of the PyObject as the value of
1419 the builtin __hash__ call. */
1421 valpy_hash (PyObject
*self
)
1423 return (intptr_t) self
;
1441 /* If TYPE is a reference, return the target; otherwise return TYPE. */
1442 #define STRIP_REFERENCE(TYPE) \
1443 (TYPE_IS_REFERENCE (TYPE) ? ((TYPE)->target_type ()) : (TYPE))
1445 /* Helper for valpy_binop. Returns a value object which is the result
1446 of applying the operation specified by OPCODE to the given
1447 arguments. Throws a GDB exception on error. */
1450 valpy_binop_throw (enum valpy_opcode opcode
, PyObject
*self
, PyObject
*other
)
1452 PyObject
*result
= NULL
;
1454 struct value
*arg1
, *arg2
;
1455 struct value
*res_val
= NULL
;
1456 enum exp_opcode op
= OP_NULL
;
1459 scoped_value_mark free_values
;
1461 /* If the gdb.Value object is the second operand, then it will be
1462 passed to us as the OTHER argument, and SELF will be an entirely
1463 different kind of object, altogether. Because of this, we can't
1464 assume self is a gdb.Value object and need to convert it from
1466 arg1
= convert_value_from_python (self
);
1470 arg2
= convert_value_from_python (other
);
1478 struct type
*ltype
= arg1
->type ();
1479 struct type
*rtype
= arg2
->type ();
1481 ltype
= check_typedef (ltype
);
1482 ltype
= STRIP_REFERENCE (ltype
);
1483 rtype
= check_typedef (rtype
);
1484 rtype
= STRIP_REFERENCE (rtype
);
1487 if (ltype
->code () == TYPE_CODE_PTR
1488 && is_integral_type (rtype
))
1489 res_val
= value_ptradd (arg1
, value_as_long (arg2
));
1490 else if (rtype
->code () == TYPE_CODE_PTR
1491 && is_integral_type (ltype
))
1492 res_val
= value_ptradd (arg2
, value_as_long (arg1
));
1502 struct type
*ltype
= arg1
->type ();
1503 struct type
*rtype
= arg2
->type ();
1505 ltype
= check_typedef (ltype
);
1506 ltype
= STRIP_REFERENCE (ltype
);
1507 rtype
= check_typedef (rtype
);
1508 rtype
= STRIP_REFERENCE (rtype
);
1511 if (ltype
->code () == TYPE_CODE_PTR
1512 && rtype
->code () == TYPE_CODE_PTR
)
1513 /* A ptrdiff_t for the target would be preferable here. */
1514 res_val
= value_from_longest (builtin_type_pyint
,
1515 value_ptrdiff (arg1
, arg2
));
1516 else if (ltype
->code () == TYPE_CODE_PTR
1517 && is_integral_type (rtype
))
1518 res_val
= value_ptradd (arg1
, - value_as_long (arg2
));
1545 op
= BINOP_BITWISE_AND
;
1548 op
= BINOP_BITWISE_IOR
;
1551 op
= BINOP_BITWISE_XOR
;
1557 if (binop_user_defined_p (op
, arg1
, arg2
))
1558 res_val
= value_x_binop (arg1
, arg2
, op
, OP_NULL
, EVAL_NORMAL
);
1560 res_val
= value_binop (arg1
, arg2
, op
);
1564 result
= value_to_value_object (res_val
);
1569 /* Returns a value object which is the result of applying the operation
1570 specified by OPCODE to the given arguments. Returns NULL on error, with
1571 a python exception set. */
1573 valpy_binop (enum valpy_opcode opcode
, PyObject
*self
, PyObject
*other
)
1575 PyObject
*result
= NULL
;
1579 result
= valpy_binop_throw (opcode
, self
, other
);
1581 catch (const gdb_exception
&except
)
1583 return gdbpy_handle_gdb_exception (nullptr, except
);
1590 valpy_add (PyObject
*self
, PyObject
*other
)
1592 return valpy_binop (VALPY_ADD
, self
, other
);
1596 valpy_subtract (PyObject
*self
, PyObject
*other
)
1598 return valpy_binop (VALPY_SUB
, self
, other
);
1602 valpy_multiply (PyObject
*self
, PyObject
*other
)
1604 return valpy_binop (VALPY_MUL
, self
, other
);
1608 valpy_divide (PyObject
*self
, PyObject
*other
)
1610 return valpy_binop (VALPY_DIV
, self
, other
);
1614 valpy_remainder (PyObject
*self
, PyObject
*other
)
1616 return valpy_binop (VALPY_REM
, self
, other
);
1620 valpy_power (PyObject
*self
, PyObject
*other
, PyObject
*unused
)
1622 /* We don't support the ternary form of pow. I don't know how to express
1623 that, so let's just throw NotImplementedError to at least do something
1625 if (unused
!= Py_None
)
1627 PyErr_SetString (PyExc_NotImplementedError
,
1628 "Invalid operation on gdb.Value.");
1632 return valpy_binop (VALPY_POW
, self
, other
);
1636 valpy_negative (PyObject
*self
)
1638 PyObject
*result
= NULL
;
1642 /* Perhaps overkill, but consistency has some virtue. */
1643 scoped_value_mark free_values
;
1646 val
= value_neg (((value_object
*) self
)->value
);
1647 result
= value_to_value_object (val
);
1649 catch (const gdb_exception
&except
)
1651 return gdbpy_handle_gdb_exception (nullptr, except
);
1658 valpy_positive (PyObject
*self
)
1660 return value_to_value_object (((value_object
*) self
)->value
);
1664 valpy_absolute (PyObject
*self
)
1666 struct value
*value
= ((value_object
*) self
)->value
;
1671 scoped_value_mark free_values
;
1673 if (value_less (value
, value::zero (value
->type (), not_lval
)))
1676 catch (const gdb_exception
&except
)
1678 return gdbpy_handle_gdb_exception (nullptr, except
);
1682 return valpy_positive (self
);
1684 return valpy_negative (self
);
1687 /* Implements boolean evaluation of gdb.Value. */
1689 valpy_nonzero (PyObject
*self
)
1691 value_object
*self_value
= (value_object
*) self
;
1693 int nonzero
= 0; /* Appease GCC warning. */
1697 type
= check_typedef (self_value
->value
->type ());
1699 if (is_integral_type (type
) || type
->code () == TYPE_CODE_PTR
)
1700 nonzero
= !!value_as_long (self_value
->value
);
1701 else if (is_floating_value (self_value
->value
))
1702 nonzero
= !target_float_is_zero
1703 (self_value
->value
->contents ().data (), type
);
1705 /* All other values are True. */
1708 catch (const gdb_exception
&ex
)
1710 /* This is not documented in the Python documentation, but if
1711 this function fails, return -1 as slot_nb_nonzero does (the
1712 default Python nonzero function). */
1713 return gdbpy_handle_gdb_exception (-1, ex
);
1719 /* Implements ~ for value objects. */
1721 valpy_invert (PyObject
*self
)
1723 PyObject
*result
= nullptr;
1727 scoped_value_mark free_values
;
1728 struct value
*val
= value_complement (((value_object
*) self
)->value
);
1729 result
= value_to_value_object (val
);
1731 catch (const gdb_exception
&except
)
1733 return gdbpy_handle_gdb_exception (nullptr, except
);
1739 /* Implements left shift for value objects. */
1741 valpy_lsh (PyObject
*self
, PyObject
*other
)
1743 return valpy_binop (VALPY_LSH
, self
, other
);
1746 /* Implements right shift for value objects. */
1748 valpy_rsh (PyObject
*self
, PyObject
*other
)
1750 return valpy_binop (VALPY_RSH
, self
, other
);
1753 /* Implements bitwise and for value objects. */
1755 valpy_and (PyObject
*self
, PyObject
*other
)
1757 return valpy_binop (VALPY_BITAND
, self
, other
);
1760 /* Implements bitwise or for value objects. */
1762 valpy_or (PyObject
*self
, PyObject
*other
)
1764 return valpy_binop (VALPY_BITOR
, self
, other
);
1767 /* Implements bitwise xor for value objects. */
1769 valpy_xor (PyObject
*self
, PyObject
*other
)
1771 return valpy_binop (VALPY_BITXOR
, self
, other
);
1774 /* Helper for valpy_richcompare. Implements comparison operations for
1775 value objects. Returns true/false on success. Returns -1 with a
1776 Python exception set if a Python error is detected. Throws a GDB
1777 exception on other errors (memory error, etc.). */
1780 valpy_richcompare_throw (PyObject
*self
, PyObject
*other
, int op
)
1783 struct value
*value_other
;
1784 struct value
*value_self
;
1786 scoped_value_mark free_values
;
1788 value_other
= convert_value_from_python (other
);
1789 if (value_other
== NULL
)
1792 value_self
= ((value_object
*) self
)->value
;
1797 result
= value_less (value_self
, value_other
);
1800 result
= value_less (value_self
, value_other
)
1801 || value_equal (value_self
, value_other
);
1804 result
= value_equal (value_self
, value_other
);
1807 result
= !value_equal (value_self
, value_other
);
1810 result
= value_less (value_other
, value_self
);
1813 result
= (value_less (value_other
, value_self
)
1814 || value_equal (value_self
, value_other
));
1818 PyErr_SetString (PyExc_NotImplementedError
,
1819 _("Invalid operation on gdb.Value."));
1828 /* Implements comparison operations for value objects. Returns NULL on error,
1829 with a python exception set. */
1831 valpy_richcompare (PyObject
*self
, PyObject
*other
, int op
)
1835 if (other
== Py_None
)
1836 /* Comparing with None is special. From what I can tell, in Python
1837 None is smaller than anything else. */
1849 PyErr_SetString (PyExc_NotImplementedError
,
1850 _("Invalid operation on gdb.Value."));
1856 result
= valpy_richcompare_throw (self
, other
, op
);
1858 catch (const gdb_exception
&except
)
1860 return gdbpy_handle_gdb_exception (nullptr, except
);
1863 /* In this case, the Python exception has already been set. */
1873 /* Implements conversion to long. */
1875 valpy_long (PyObject
*self
)
1877 struct value
*value
= ((value_object
*) self
)->value
;
1878 struct type
*type
= value
->type ();
1883 if (is_floating_value (value
))
1885 type
= builtin_type_pylong
;
1886 value
= value_cast (type
, value
);
1889 type
= check_typedef (type
);
1891 if (!is_integral_type (type
)
1892 && type
->code () != TYPE_CODE_PTR
)
1893 error (_("Cannot convert value to long."));
1895 l
= value_as_long (value
);
1897 catch (const gdb_exception
&except
)
1899 return gdbpy_handle_gdb_exception (nullptr, except
);
1902 if (type
->is_unsigned ())
1903 return gdb_py_object_from_ulongest (l
).release ();
1905 return gdb_py_object_from_longest (l
).release ();
1908 /* Implements conversion to float. */
1910 valpy_float (PyObject
*self
)
1912 struct value
*value
= ((value_object
*) self
)->value
;
1913 struct type
*type
= value
->type ();
1918 type
= check_typedef (type
);
1920 if (type
->code () == TYPE_CODE_FLT
&& is_floating_value (value
))
1921 d
= target_float_to_host_double (value
->contents ().data (), type
);
1922 else if (type
->code () == TYPE_CODE_INT
)
1924 /* Note that valpy_long accepts TYPE_CODE_PTR and some
1925 others here here -- but casting a pointer or bool to a
1926 float seems wrong. */
1927 d
= value_as_long (value
);
1930 error (_("Cannot convert value to float."));
1932 catch (const gdb_exception
&except
)
1934 return gdbpy_handle_gdb_exception (nullptr, except
);
1937 return PyFloat_FromDouble (d
);
1940 /* Returns an object for a value, without releasing it from the
1941 all_values chain. */
1943 value_to_value_object (struct value
*val
)
1945 value_object
*val_obj
;
1947 val_obj
= PyObject_New (value_object
, &value_object_type
);
1948 if (val_obj
!= NULL
)
1951 val_obj
->value
= val
;
1952 val_obj
->next
= nullptr;
1953 val_obj
->prev
= nullptr;
1954 val_obj
->address
= NULL
;
1955 val_obj
->type
= NULL
;
1956 val_obj
->dynamic_type
= NULL
;
1957 val_obj
->content_bytes
= nullptr;
1958 note_value (val_obj
);
1961 return (PyObject
*) val_obj
;
1964 /* Returns a borrowed reference to the struct value corresponding to
1965 the given value object. */
1967 value_object_to_value (PyObject
*self
)
1971 if (! PyObject_TypeCheck (self
, &value_object_type
))
1973 real
= (value_object
*) self
;
1977 /* Try to convert a Python value to a gdb value. If the value cannot
1978 be converted, set a Python exception and return NULL. Returns a
1979 reference to a new value on the all_values chain. */
1982 convert_value_from_python (PyObject
*obj
)
1984 struct value
*value
= NULL
; /* -Wall */
1987 gdb_assert (obj
!= NULL
);
1991 if (PyBool_Check (obj
))
1993 cmp
= obj
== Py_True
? 1 : 0;
1994 value
= value_from_longest (builtin_type_pybool
, cmp
);
1996 else if (PyLong_Check (obj
))
1998 LONGEST l
= PyLong_AsLongLong (obj
);
2000 if (PyErr_Occurred ())
2002 /* If the error was an overflow, we can try converting to
2003 ULONGEST instead. */
2004 if (PyErr_ExceptionMatches (PyExc_OverflowError
))
2006 gdbpy_err_fetch fetched_error
;
2007 gdbpy_ref
<> zero
= gdb_py_object_from_longest (0);
2009 /* Check whether obj is positive. */
2010 if (PyObject_RichCompareBool (obj
, zero
.get (), Py_GT
) > 0)
2014 ul
= PyLong_AsUnsignedLongLong (obj
);
2015 if (! PyErr_Occurred ())
2016 value
= value_from_ulongest (builtin_type_upylong
, ul
);
2020 /* There's nothing we can do. */
2021 fetched_error
.restore ();
2026 value
= value_from_longest (builtin_type_pylong
, l
);
2028 else if (PyFloat_Check (obj
))
2030 double d
= PyFloat_AsDouble (obj
);
2032 if (! PyErr_Occurred ())
2033 value
= value_from_host_double (builtin_type_pyfloat
, d
);
2035 else if (gdbpy_is_string (obj
))
2037 gdb::unique_xmalloc_ptr
<char> s
2038 = python_string_to_target_string (obj
);
2041 = current_language
->value_string (gdbpy_enter::get_gdbarch (),
2042 s
.get (), strlen (s
.get ()));
2044 else if (PyObject_TypeCheck (obj
, &value_object_type
))
2045 value
= ((value_object
*) obj
)->value
->copy ();
2046 else if (gdbpy_is_lazy_string (obj
))
2050 result
= PyObject_CallMethodObjArgs (obj
, gdbpy_value_cst
, NULL
);
2051 value
= ((value_object
*) result
)->value
->copy ();
2054 PyErr_Format (PyExc_TypeError
,
2055 _("Could not convert Python object: %S."), obj
);
2057 catch (const gdb_exception
&except
)
2059 return gdbpy_handle_gdb_exception (nullptr, except
);
2065 /* Returns value object in the ARGth position in GDB's history. */
2067 gdbpy_history (PyObject
*self
, PyObject
*args
)
2071 if (!PyArg_ParseTuple (args
, "i", &i
))
2074 PyObject
*result
= nullptr;
2077 scoped_value_mark free_values
;
2078 struct value
*res_val
= access_value_history (i
);
2079 result
= value_to_value_object (res_val
);
2081 catch (const gdb_exception
&except
)
2083 return gdbpy_handle_gdb_exception (nullptr, except
);
2089 /* Add a gdb.Value into GDB's history, and return (as an integer) the
2090 position of the newly added value. */
2092 gdbpy_add_history (PyObject
*self
, PyObject
*args
)
2094 PyObject
*value_obj
;
2096 if (!PyArg_ParseTuple (args
, "O", &value_obj
))
2099 struct value
*value
= convert_value_from_python (value_obj
);
2100 if (value
== nullptr)
2105 int idx
= value
->record_latest ();
2106 return gdb_py_object_from_longest (idx
).release ();
2108 catch (const gdb_exception
&except
)
2110 return gdbpy_handle_gdb_exception (nullptr, except
);
2116 /* Return an integer, the number of items in GDB's history. */
2119 gdbpy_history_count (PyObject
*self
, PyObject
*args
)
2121 return gdb_py_object_from_ulongest (value_history_count ()).release ();
2124 /* Return the value of a convenience variable. */
2126 gdbpy_convenience_variable (PyObject
*self
, PyObject
*args
)
2128 const char *varname
;
2129 struct value
*res_val
= NULL
;
2131 if (!PyArg_ParseTuple (args
, "s", &varname
))
2134 PyObject
*result
= nullptr;
2138 struct internalvar
*var
= lookup_only_internalvar (varname
);
2142 scoped_value_mark free_values
;
2143 res_val
= value_of_internalvar (gdbpy_enter::get_gdbarch (), var
);
2144 if (res_val
->type ()->code () == TYPE_CODE_VOID
)
2149 result
= value_to_value_object (res_val
);
2153 catch (const gdb_exception
&except
)
2155 return gdbpy_handle_gdb_exception (nullptr, except
);
2158 if (result
== nullptr && !found
)
2164 /* Set the value of a convenience variable. */
2166 gdbpy_set_convenience_variable (PyObject
*self
, PyObject
*args
)
2168 const char *varname
;
2169 PyObject
*value_obj
;
2170 struct value
*value
= NULL
;
2172 if (!PyArg_ParseTuple (args
, "sO", &varname
, &value_obj
))
2175 /* None means to clear the variable. */
2176 if (value_obj
!= Py_None
)
2178 value
= convert_value_from_python (value_obj
);
2187 struct internalvar
*var
= lookup_only_internalvar (varname
);
2190 clear_internalvar (var
);
2194 struct internalvar
*var
= lookup_internalvar (varname
);
2196 set_internalvar (var
, value
);
2199 catch (const gdb_exception
&except
)
2201 return gdbpy_handle_gdb_exception (nullptr, except
);
2207 /* Returns 1 in OBJ is a gdb.Value object, 0 otherwise. */
2210 gdbpy_is_value_object (PyObject
*obj
)
2212 return PyObject_TypeCheck (obj
, &value_object_type
);
2215 static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
2216 gdbpy_initialize_values (void)
2218 return gdbpy_type_ready (&value_object_type
);
2221 GDBPY_INITIALIZE_FILE (gdbpy_initialize_values
);
2225 static gdb_PyGetSetDef value_object_getset
[] = {
2226 { "address", valpy_get_address
, NULL
, "The address of the value.",
2228 { "is_optimized_out", valpy_get_is_optimized_out
, NULL
,
2229 "Boolean telling whether the value is optimized "
2230 "out (i.e., not available).",
2232 { "type", valpy_get_type
, NULL
, "Type of the value.", NULL
},
2233 { "dynamic_type", valpy_get_dynamic_type
, NULL
,
2234 "Dynamic type of the value.", NULL
},
2235 { "is_lazy", valpy_get_is_lazy
, NULL
,
2236 "Boolean telling whether the value is lazy (not fetched yet\n\
2237 from the inferior). A lazy value is fetched when needed, or when\n\
2238 the \"fetch_lazy()\" method is called.", NULL
},
2239 { "bytes", valpy_get_bytes
, valpy_set_bytes
,
2240 "Return a bytearray containing the bytes of this value.", nullptr },
2241 {NULL
} /* Sentinel */
2244 static PyMethodDef value_object_methods
[] = {
2245 { "cast", valpy_cast
, METH_VARARGS
, "Cast the value to the supplied type." },
2246 { "dynamic_cast", valpy_dynamic_cast
, METH_VARARGS
,
2247 "dynamic_cast (gdb.Type) -> gdb.Value\n\
2248 Cast the value to the supplied type, as if by the C++ dynamic_cast operator."
2250 { "reinterpret_cast", valpy_reinterpret_cast
, METH_VARARGS
,
2251 "reinterpret_cast (gdb.Type) -> gdb.Value\n\
2252 Cast the value to the supplied type, as if by the C++\n\
2253 reinterpret_cast operator."
2255 { "dereference", valpy_dereference
, METH_NOARGS
, "Dereferences the value." },
2256 { "referenced_value", valpy_referenced_value
, METH_NOARGS
,
2257 "Return the value referenced by a TYPE_CODE_REF or TYPE_CODE_PTR value." },
2258 { "reference_value", valpy_lvalue_reference_value
, METH_NOARGS
,
2259 "Return a value of type TYPE_CODE_REF referencing this value." },
2260 { "rvalue_reference_value", valpy_rvalue_reference_value
, METH_NOARGS
,
2261 "Return a value of type TYPE_CODE_RVALUE_REF referencing this value." },
2262 { "const_value", valpy_const_value
, METH_NOARGS
,
2263 "Return a 'const' qualified version of the same value." },
2264 { "lazy_string", (PyCFunction
) valpy_lazy_string
,
2265 METH_VARARGS
| METH_KEYWORDS
,
2266 "lazy_string ([encoding] [, length]) -> lazy_string\n\
2267 Return a lazy string representation of the value." },
2268 { "string", (PyCFunction
) valpy_string
, METH_VARARGS
| METH_KEYWORDS
,
2269 "string ([encoding] [, errors] [, length]) -> string\n\
2270 Return Unicode string representation of the value." },
2271 { "fetch_lazy", valpy_fetch_lazy
, METH_NOARGS
,
2272 "Fetches the value from the inferior, if it was lazy." },
2273 { "format_string", (PyCFunction
) valpy_format_string
,
2274 METH_VARARGS
| METH_KEYWORDS
,
2275 "format_string (...) -> string\n\
2276 Return a string representation of the value using the specified\n\
2277 formatting options" },
2278 { "assign", (PyCFunction
) valpy_assign
, METH_VARARGS
,
2279 "assign (VAL) -> None\n\
2280 Assign VAL to this value." },
2281 { "to_array", valpy_to_array
, METH_NOARGS
,
2282 "to_array () -> Value\n\
2283 Return value as an array, if possible." },
2284 {NULL
} /* Sentinel */
2287 static PyNumberMethods value_object_as_number
= {
2292 NULL
, /* nb_divmod */
2293 valpy_power
, /* nb_power */
2294 valpy_negative
, /* nb_negative */
2295 valpy_positive
, /* nb_positive */
2296 valpy_absolute
, /* nb_absolute */
2297 valpy_nonzero
, /* nb_nonzero */
2298 valpy_invert
, /* nb_invert */
2299 valpy_lsh
, /* nb_lshift */
2300 valpy_rsh
, /* nb_rshift */
2301 valpy_and
, /* nb_and */
2302 valpy_xor
, /* nb_xor */
2303 valpy_or
, /* nb_or */
2304 valpy_long
, /* nb_int */
2305 NULL
, /* reserved */
2306 valpy_float
, /* nb_float */
2307 NULL
, /* nb_inplace_add */
2308 NULL
, /* nb_inplace_subtract */
2309 NULL
, /* nb_inplace_multiply */
2310 NULL
, /* nb_inplace_remainder */
2311 NULL
, /* nb_inplace_power */
2312 NULL
, /* nb_inplace_lshift */
2313 NULL
, /* nb_inplace_rshift */
2314 NULL
, /* nb_inplace_and */
2315 NULL
, /* nb_inplace_xor */
2316 NULL
, /* nb_inplace_or */
2317 NULL
, /* nb_floor_divide */
2318 valpy_divide
, /* nb_true_divide */
2319 NULL
, /* nb_inplace_floor_divide */
2320 NULL
, /* nb_inplace_true_divide */
2321 valpy_long
, /* nb_index */
2324 static PyMappingMethods value_object_as_mapping
= {
2330 PyTypeObject value_object_type
= {
2331 PyVarObject_HEAD_INIT (NULL
, 0)
2332 "gdb.Value", /*tp_name*/
2333 sizeof (value_object
), /*tp_basicsize*/
2335 valpy_dealloc
, /*tp_dealloc*/
2341 &value_object_as_number
, /*tp_as_number*/
2342 0, /*tp_as_sequence*/
2343 &value_object_as_mapping
, /*tp_as_mapping*/
2344 valpy_hash
, /*tp_hash*/
2345 valpy_call
, /*tp_call*/
2346 valpy_str
, /*tp_str*/
2350 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
2351 | Py_TPFLAGS_BASETYPE
, /*tp_flags*/
2352 "GDB value object", /* tp_doc */
2353 0, /* tp_traverse */
2355 valpy_richcompare
, /* tp_richcompare */
2356 0, /* tp_weaklistoffset */
2358 0, /* tp_iternext */
2359 value_object_methods
, /* tp_methods */
2361 value_object_getset
, /* tp_getset */
2364 0, /* tp_descr_get */
2365 0, /* tp_descr_set */
2366 0, /* tp_dictoffset */
2367 valpy_init
, /* tp_init */
2369 PyType_GenericNew
, /* tp_new */