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/>. */
21 #include "top.h" /* For quit_force (). */
25 #include "target-float.h"
28 #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
;
67 /* List of all values which are currently exposed to Python. It is
68 maintained so that when an objfile is discarded, preserve_values
69 can copy the values' types if needed. */
70 /* This variable is unnecessarily initialized to NULL in order to
71 work around a linker bug on MacOS. */
72 static value_object
*values_in_python
= NULL
;
74 /* Clear out an old GDB value stored within SELF, and reset the fields to
75 nullptr. This should be called when a gdb.Value is deallocated, and
76 also if a gdb.Value is reinitialized with a new value. */
79 valpy_clear_value (value_object
*self
)
81 /* Indicate we are no longer interested in the value object. */
82 self
->value
->decref ();
83 self
->value
= nullptr;
85 Py_CLEAR (self
->address
);
86 Py_CLEAR (self
->type
);
87 Py_CLEAR (self
->dynamic_type
);
90 /* Called by the Python interpreter when deallocating a value object. */
92 valpy_dealloc (PyObject
*obj
)
94 value_object
*self
= (value_object
*) obj
;
96 /* If SELF failed to initialize correctly then it may not have a value
97 contained within it. */
98 if (self
->value
!= nullptr)
100 /* Remove SELF from the global list of values. */
101 if (self
->prev
!= nullptr)
102 self
->prev
->next
= self
->next
;
105 gdb_assert (values_in_python
== self
);
106 values_in_python
= self
->next
;
108 if (self
->next
!= nullptr)
109 self
->next
->prev
= self
->prev
;
111 /* Release the value object and any cached Python objects. */
112 valpy_clear_value (self
);
115 Py_TYPE (self
)->tp_free (self
);
118 /* Helper to push a gdb.Value object on to the global list of values. If
119 VALUE_OBJ is already on the lit then this does nothing. */
122 note_value (value_object
*value_obj
)
124 if (value_obj
->next
== nullptr)
126 gdb_assert (value_obj
->prev
== nullptr);
127 value_obj
->next
= values_in_python
;
128 if (value_obj
->next
!= nullptr)
129 value_obj
->next
->prev
= value_obj
;
130 values_in_python
= value_obj
;
134 /* Convert a python object OBJ with type TYPE to a gdb value. The
135 python object in question must conform to the python buffer
136 protocol. On success, return the converted value, otherwise
139 static struct value
*
140 convert_buffer_and_type_to_value (PyObject
*obj
, struct type
*type
)
142 Py_buffer_up buffer_up
;
145 if (PyObject_CheckBuffer (obj
)
146 && PyObject_GetBuffer (obj
, &py_buf
, PyBUF_SIMPLE
) == 0)
148 /* Got a buffer, py_buf, out of obj. Cause it to be released
149 when it goes out of scope. */
150 buffer_up
.reset (&py_buf
);
154 PyErr_SetString (PyExc_TypeError
,
155 _("Object must support the python buffer protocol."));
159 if (type
->length () > py_buf
.len
)
161 PyErr_SetString (PyExc_ValueError
,
162 _("Size of type is larger than that of buffer object."));
166 return value_from_contents (type
, (const gdb_byte
*) py_buf
.buf
);
169 /* Implement gdb.Value.__init__. */
172 valpy_init (PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
174 static const char *keywords
[] = { "val", "type", NULL
};
175 PyObject
*val_obj
= nullptr;
176 PyObject
*type_obj
= nullptr;
178 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kwds
, "O|O", keywords
,
179 &val_obj
, &type_obj
))
182 struct type
*type
= nullptr;
183 if (type_obj
!= nullptr && type_obj
!= Py_None
)
185 type
= type_object_to_type (type_obj
);
188 PyErr_SetString (PyExc_TypeError
,
189 _("type argument must be a gdb.Type."));
196 value
= convert_value_from_python (val_obj
);
198 value
= convert_buffer_and_type_to_value (val_obj
, type
);
199 if (value
== nullptr)
201 gdb_assert (PyErr_Occurred ());
205 /* There might be a previous value here. */
206 value_object
*value_obj
= (value_object
*) self
;
207 if (value_obj
->value
!= nullptr)
208 valpy_clear_value (value_obj
);
210 /* Store the value into this Python object. */
211 value_obj
->value
= release_value (value
).release ();
213 /* Ensure that this gdb.Value is in the set of all gdb.Value objects. If
214 we are already in the set then this is call does nothing. */
215 note_value (value_obj
);
220 /* Iterate over all the Value objects, calling preserve_one_value on
223 gdbpy_preserve_values (const struct extension_language_defn
*extlang
,
224 struct objfile
*objfile
, htab_t copied_types
)
228 for (iter
= values_in_python
; iter
; iter
= iter
->next
)
229 iter
->value
->preserve (objfile
, copied_types
);
232 /* Given a value of a pointer type, apply the C unary * operator to it. */
234 valpy_dereference (PyObject
*self
, PyObject
*args
)
236 PyObject
*result
= NULL
;
240 struct value
*res_val
;
241 scoped_value_mark free_values
;
243 res_val
= value_ind (((value_object
*) self
)->value
);
244 result
= value_to_value_object (res_val
);
246 catch (const gdb_exception
&except
)
248 GDB_PY_HANDLE_EXCEPTION (except
);
254 /* Given a value of a pointer type or a reference type, return the value
255 referenced. The difference between this function and valpy_dereference is
256 that the latter applies * unary operator to a value, which need not always
257 result in the value referenced. For example, for a value which is a reference
258 to an 'int' pointer ('int *'), valpy_dereference will result in a value of
259 type 'int' while valpy_referenced_value will result in a value of type
263 valpy_referenced_value (PyObject
*self
, PyObject
*args
)
265 PyObject
*result
= NULL
;
269 struct value
*self_val
, *res_val
;
270 scoped_value_mark free_values
;
272 self_val
= ((value_object
*) self
)->value
;
273 switch (check_typedef (self_val
->type ())->code ())
276 res_val
= value_ind (self_val
);
279 case TYPE_CODE_RVALUE_REF
:
280 res_val
= coerce_ref (self_val
);
283 error(_("Trying to get the referenced value from a value which is "
284 "neither a pointer nor a reference."));
287 result
= value_to_value_object (res_val
);
289 catch (const gdb_exception
&except
)
291 GDB_PY_HANDLE_EXCEPTION (except
);
297 /* Return a value which is a reference to the value. */
300 valpy_reference_value (PyObject
*self
, PyObject
*args
, enum type_code refcode
)
302 PyObject
*result
= NULL
;
306 struct value
*self_val
;
307 scoped_value_mark free_values
;
309 self_val
= ((value_object
*) self
)->value
;
310 result
= value_to_value_object (value_ref (self_val
, refcode
));
312 catch (const gdb_exception
&except
)
314 GDB_PY_HANDLE_EXCEPTION (except
);
321 valpy_lvalue_reference_value (PyObject
*self
, PyObject
*args
)
323 return valpy_reference_value (self
, args
, TYPE_CODE_REF
);
327 valpy_rvalue_reference_value (PyObject
*self
, PyObject
*args
)
329 return valpy_reference_value (self
, args
, TYPE_CODE_RVALUE_REF
);
332 /* Return a "const" qualified version of the value. */
335 valpy_const_value (PyObject
*self
, PyObject
*args
)
337 PyObject
*result
= NULL
;
341 struct value
*self_val
, *res_val
;
342 scoped_value_mark free_values
;
344 self_val
= ((value_object
*) self
)->value
;
345 res_val
= make_cv_value (1, 0, self_val
);
346 result
= value_to_value_object (res_val
);
348 catch (const gdb_exception
&except
)
350 GDB_PY_HANDLE_EXCEPTION (except
);
356 /* Return "&value". */
358 valpy_get_address (PyObject
*self
, void *closure
)
360 value_object
*val_obj
= (value_object
*) self
;
362 if (!val_obj
->address
)
366 struct value
*res_val
;
367 scoped_value_mark free_values
;
369 res_val
= value_addr (val_obj
->value
);
370 val_obj
->address
= value_to_value_object (res_val
);
372 catch (const gdb_exception_forced_quit
&except
)
374 quit_force (NULL
, 0);
376 catch (const gdb_exception
&except
)
378 val_obj
->address
= Py_None
;
383 Py_XINCREF (val_obj
->address
);
385 return val_obj
->address
;
388 /* Return type of the value. */
390 valpy_get_type (PyObject
*self
, void *closure
)
392 value_object
*obj
= (value_object
*) self
;
396 obj
->type
= type_to_type_object (obj
->value
->type ());
400 Py_INCREF (obj
->type
);
404 /* Return dynamic type of the value. */
407 valpy_get_dynamic_type (PyObject
*self
, void *closure
)
409 value_object
*obj
= (value_object
*) self
;
410 struct type
*type
= NULL
;
412 if (obj
->dynamic_type
!= NULL
)
414 Py_INCREF (obj
->dynamic_type
);
415 return obj
->dynamic_type
;
420 struct value
*val
= obj
->value
;
421 scoped_value_mark free_values
;
424 type
= check_typedef (type
);
426 if (type
->is_pointer_or_reference ()
427 && (type
->target_type ()->code () == TYPE_CODE_STRUCT
))
429 struct value
*target
;
430 int was_pointer
= type
->code () == TYPE_CODE_PTR
;
433 target
= value_ind (val
);
435 target
= coerce_ref (val
);
436 type
= value_rtti_type (target
, NULL
, NULL
, NULL
);
441 type
= lookup_pointer_type (type
);
443 type
= lookup_lvalue_reference_type (type
);
446 else if (type
->code () == TYPE_CODE_STRUCT
)
447 type
= value_rtti_type (val
, NULL
, NULL
, NULL
);
450 /* Re-use object's static type. */
454 catch (const gdb_exception
&except
)
456 GDB_PY_HANDLE_EXCEPTION (except
);
460 obj
->dynamic_type
= valpy_get_type (self
, NULL
);
462 obj
->dynamic_type
= type_to_type_object (type
);
464 Py_XINCREF (obj
->dynamic_type
);
465 return obj
->dynamic_type
;
468 /* Implementation of gdb.Value.lazy_string ([encoding] [, length]) ->
469 string. Return a PyObject representing a lazy_string_object type.
470 A lazy string is a pointer to a string with an optional encoding and
471 length. If ENCODING is not given, encoding is set to None. If an
472 ENCODING is provided the encoding parameter is set to ENCODING, but
473 the string is not encoded.
474 If LENGTH is provided then the length parameter is set to LENGTH.
475 Otherwise if the value is an array of known length then the array's length
476 is used. Otherwise the length will be set to -1 (meaning first null of
479 Note: In order to not break any existing uses this allows creating
480 lazy strings from anything. PR 20769. E.g.,
481 gdb.parse_and_eval("my_int_variable").lazy_string().
482 "It's easier to relax restrictions than it is to impose them after the
483 fact." So we should be flagging any unintended uses as errors, but it's
484 perhaps too late for that. */
487 valpy_lazy_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
489 gdb_py_longest length
= -1;
490 struct value
*value
= ((value_object
*) self
)->value
;
491 const char *user_encoding
= NULL
;
492 static const char *keywords
[] = { "encoding", "length", NULL
};
493 PyObject
*str_obj
= NULL
;
495 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "|s" GDB_PY_LL_ARG
,
496 keywords
, &user_encoding
, &length
))
501 PyErr_SetString (PyExc_ValueError
, _("Invalid length."));
507 scoped_value_mark free_values
;
508 struct type
*type
, *realtype
;
511 type
= value
->type ();
512 realtype
= check_typedef (type
);
514 switch (realtype
->code ())
516 case TYPE_CODE_ARRAY
:
518 LONGEST array_length
= -1;
519 LONGEST low_bound
, high_bound
;
521 /* PR 20786: There's no way to specify an array of length zero.
522 Record a length of [0,-1] which is how Ada does it. Anything
523 we do is broken, but this one possible solution. */
524 if (get_array_bounds (realtype
, &low_bound
, &high_bound
))
525 array_length
= high_bound
- low_bound
+ 1;
527 length
= array_length
;
528 else if (array_length
== -1)
530 type
= lookup_array_range_type (realtype
->target_type (),
533 else if (length
!= array_length
)
535 /* We need to create a new array type with the
537 if (length
> array_length
)
538 error (_("Length is larger than array size."));
539 type
= lookup_array_range_type (realtype
->target_type (),
541 low_bound
+ length
- 1);
543 addr
= value
->address ();
547 /* If a length is specified we defer creating an array of the
548 specified width until we need to. */
549 addr
= value_as_address (value
);
552 /* Should flag an error here. PR 20769. */
553 addr
= value
->address ();
557 str_obj
= gdbpy_create_lazy_string_object (addr
, length
, user_encoding
,
560 catch (const gdb_exception
&except
)
562 GDB_PY_HANDLE_EXCEPTION (except
);
568 /* Implementation of gdb.Value.string ([encoding] [, errors]
569 [, length]) -> string. Return Unicode string with value contents.
570 If ENCODING is not given, the string is assumed to be encoded in
571 the target's charset. If LENGTH is provided, only fetch string to
572 the length provided. */
575 valpy_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
578 gdb::unique_xmalloc_ptr
<gdb_byte
> buffer
;
579 struct value
*value
= ((value_object
*) self
)->value
;
580 const char *encoding
= NULL
;
581 const char *errors
= NULL
;
582 const char *user_encoding
= NULL
;
583 const char *la_encoding
= NULL
;
584 struct type
*char_type
;
585 static const char *keywords
[] = { "encoding", "errors", "length", NULL
};
587 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "|ssi", keywords
,
588 &user_encoding
, &errors
, &length
))
593 c_get_string (value
, &buffer
, &length
, &char_type
, &la_encoding
);
595 catch (const gdb_exception
&except
)
597 GDB_PY_HANDLE_EXCEPTION (except
);
600 encoding
= (user_encoding
&& *user_encoding
) ? user_encoding
: la_encoding
;
601 return PyUnicode_Decode ((const char *) buffer
.get (),
602 length
* char_type
->length (),
606 /* Given a Python object, copy its truth value to a C bool (the value
608 If src_obj is NULL, then *dest is not modified.
610 Return true in case of success (including src_obj being NULL), false
614 copy_py_bool_obj (bool *dest
, PyObject
*src_obj
)
618 int cmp
= PyObject_IsTrue (src_obj
);
627 /* Implementation of gdb.Value.format_string (...) -> string.
628 Return Unicode string with value contents formatted using the
629 keyword-only arguments. */
632 valpy_format_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
634 static const char *keywords
[] =
636 /* Basic C/C++ options. */
637 "raw", /* See the /r option to print. */
638 "pretty_arrays", /* See set print array on|off. */
639 "pretty_structs", /* See set print pretty on|off. */
640 "array_indexes", /* See set print array-indexes on|off. */
641 "symbols", /* See set print symbol on|off. */
642 "unions", /* See set print union on|off. */
643 "address", /* See set print address on|off. */
644 "styling", /* Should we apply styling. */
645 "nibbles", /* See set print nibbles on|off. */
646 "summary", /* Summary mode for non-scalars. */
648 "deref_refs", /* No corresponding setting. */
649 "actual_objects", /* See set print object on|off. */
650 "static_members", /* See set print static-members on|off. */
651 /* C non-bool options. */
652 "max_characters", /* See set print characters N. */
653 "max_elements", /* See set print elements N. */
654 "max_depth", /* See set print max-depth N. */
655 "repeat_threshold", /* See set print repeats. */
656 "format", /* The format passed to the print command. */
660 /* This function has too many arguments to be useful as positionals, so
661 the user should specify them all as keyword arguments.
662 Python 3.3 and later have a way to specify it (both in C and Python
663 itself), but we could be compiled with older versions, so we just
664 check that the args tuple is empty. */
665 Py_ssize_t positional_count
= PyObject_Length (args
);
666 if (positional_count
< 0)
668 else if (positional_count
> 0)
670 /* This matches the error message that Python 3.3 raises when
671 passing positionals to functions expecting keyword-only
673 PyErr_Format (PyExc_TypeError
,
674 "format_string() takes 0 positional arguments but %zu were given",
679 struct value_print_options opts
;
680 gdbpy_get_print_options (&opts
);
681 opts
.deref_ref
= false;
683 /* We need objects for booleans as the "p" flag for bools is new in
685 PyObject
*raw_obj
= NULL
;
686 PyObject
*pretty_arrays_obj
= NULL
;
687 PyObject
*pretty_structs_obj
= NULL
;
688 PyObject
*array_indexes_obj
= NULL
;
689 PyObject
*symbols_obj
= NULL
;
690 PyObject
*unions_obj
= NULL
;
691 PyObject
*address_obj
= NULL
;
692 PyObject
*styling_obj
= Py_False
;
693 PyObject
*nibbles_obj
= NULL
;
694 PyObject
*deref_refs_obj
= NULL
;
695 PyObject
*actual_objects_obj
= NULL
;
696 PyObject
*static_members_obj
= NULL
;
697 PyObject
*summary_obj
= NULL
;
699 if (!gdb_PyArg_ParseTupleAndKeywords (args
,
701 "|O!O!O!O!O!O!O!O!O!O!O!O!O!IIIIs",
703 &PyBool_Type
, &raw_obj
,
704 &PyBool_Type
, &pretty_arrays_obj
,
705 &PyBool_Type
, &pretty_structs_obj
,
706 &PyBool_Type
, &array_indexes_obj
,
707 &PyBool_Type
, &symbols_obj
,
708 &PyBool_Type
, &unions_obj
,
709 &PyBool_Type
, &address_obj
,
710 &PyBool_Type
, &styling_obj
,
711 &PyBool_Type
, &nibbles_obj
,
712 &PyBool_Type
, &summary_obj
,
713 &PyBool_Type
, &deref_refs_obj
,
714 &PyBool_Type
, &actual_objects_obj
,
715 &PyBool_Type
, &static_members_obj
,
716 &opts
.print_max_chars
,
719 &opts
.repeat_count_threshold
,
723 /* Set boolean arguments. */
724 if (!copy_py_bool_obj (&opts
.raw
, raw_obj
))
726 if (!copy_py_bool_obj (&opts
.prettyformat_arrays
, pretty_arrays_obj
))
728 if (!copy_py_bool_obj (&opts
.prettyformat_structs
, pretty_structs_obj
))
730 if (!copy_py_bool_obj (&opts
.print_array_indexes
, array_indexes_obj
))
732 if (!copy_py_bool_obj (&opts
.symbol_print
, symbols_obj
))
734 if (!copy_py_bool_obj (&opts
.unionprint
, unions_obj
))
736 if (!copy_py_bool_obj (&opts
.addressprint
, address_obj
))
738 if (!copy_py_bool_obj (&opts
.nibblesprint
, nibbles_obj
))
740 if (!copy_py_bool_obj (&opts
.deref_ref
, deref_refs_obj
))
742 if (!copy_py_bool_obj (&opts
.objectprint
, actual_objects_obj
))
744 if (!copy_py_bool_obj (&opts
.static_field_print
, static_members_obj
))
746 if (!copy_py_bool_obj (&opts
.summary
, summary_obj
))
749 /* Numeric arguments for which 0 means unlimited (which we represent as
750 UINT_MAX). Note that the max-depth numeric argument uses -1 as
751 unlimited, and 0 is a valid choice. */
752 if (opts
.print_max
== 0)
753 opts
.print_max
= UINT_MAX
;
754 if (opts
.repeat_count_threshold
== 0)
755 opts
.repeat_count_threshold
= UINT_MAX
;
757 /* Other arguments. */
760 if (strlen (format
) == 1)
761 opts
.format
= format
[0];
764 /* Mimic the message on standard Python ones for similar
766 PyErr_SetString (PyExc_ValueError
,
767 "a single character is required");
772 string_file
stb (PyObject_IsTrue (styling_obj
));
776 common_val_print (((value_object
*) self
)->value
, &stb
, 0,
777 &opts
, current_language
);
779 catch (const gdb_exception
&except
)
781 GDB_PY_HANDLE_EXCEPTION (except
);
784 return PyUnicode_Decode (stb
.c_str (), stb
.size (), host_charset (), NULL
);
787 /* A helper function that implements the various cast operators. */
790 valpy_do_cast (PyObject
*self
, PyObject
*args
, enum exp_opcode op
)
792 PyObject
*type_obj
, *result
= NULL
;
795 if (! PyArg_ParseTuple (args
, "O", &type_obj
))
798 type
= type_object_to_type (type_obj
);
801 PyErr_SetString (PyExc_RuntimeError
,
802 _("Argument must be a type."));
808 struct value
*val
= ((value_object
*) self
)->value
;
809 struct value
*res_val
;
810 scoped_value_mark free_values
;
812 if (op
== UNOP_DYNAMIC_CAST
)
813 res_val
= value_dynamic_cast (type
, val
);
814 else if (op
== UNOP_REINTERPRET_CAST
)
815 res_val
= value_reinterpret_cast (type
, val
);
818 gdb_assert (op
== UNOP_CAST
);
819 res_val
= value_cast (type
, val
);
822 result
= value_to_value_object (res_val
);
824 catch (const gdb_exception
&except
)
826 GDB_PY_HANDLE_EXCEPTION (except
);
832 /* Implementation of the "cast" method. */
835 valpy_cast (PyObject
*self
, PyObject
*args
)
837 return valpy_do_cast (self
, args
, UNOP_CAST
);
840 /* Implementation of the "dynamic_cast" method. */
843 valpy_dynamic_cast (PyObject
*self
, PyObject
*args
)
845 return valpy_do_cast (self
, args
, UNOP_DYNAMIC_CAST
);
848 /* Implementation of the "reinterpret_cast" method. */
851 valpy_reinterpret_cast (PyObject
*self
, PyObject
*args
)
853 return valpy_do_cast (self
, args
, UNOP_REINTERPRET_CAST
);
857 valpy_length (PyObject
*self
)
859 /* We don't support getting the number of elements in a struct / class. */
860 PyErr_SetString (PyExc_NotImplementedError
,
861 _("Invalid operation on gdb.Value."));
865 /* Return 1 if the gdb.Field object FIELD is present in the value V.
866 Returns 0 otherwise. If any Python error occurs, -1 is returned. */
869 value_has_field (struct value
*v
, PyObject
*field
)
871 struct type
*parent_type
, *val_type
;
872 enum type_code type_code
;
873 gdbpy_ref
<> type_object (PyObject_GetAttrString (field
, "parent_type"));
876 if (type_object
== NULL
)
879 parent_type
= type_object_to_type (type_object
.get ());
880 if (parent_type
== NULL
)
882 PyErr_SetString (PyExc_TypeError
,
883 _("'parent_type' attribute of gdb.Field object is not a"
884 "gdb.Type object."));
890 val_type
= v
->type ();
891 val_type
= check_typedef (val_type
);
892 if (val_type
->is_pointer_or_reference ())
893 val_type
= check_typedef (val_type
->target_type ());
895 type_code
= val_type
->code ();
896 if ((type_code
== TYPE_CODE_STRUCT
|| type_code
== TYPE_CODE_UNION
)
897 && types_equal (val_type
, parent_type
))
902 catch (const gdb_exception
&except
)
904 GDB_PY_SET_HANDLE_EXCEPTION (except
);
910 /* Return the value of a flag FLAG_NAME in a gdb.Field object FIELD.
911 Returns 1 if the flag value is true, 0 if it is false, and -1 if
912 a Python error occurs. */
915 get_field_flag (PyObject
*field
, const char *flag_name
)
917 gdbpy_ref
<> flag_object (PyObject_GetAttrString (field
, flag_name
));
919 if (flag_object
== NULL
)
922 return PyObject_IsTrue (flag_object
.get ());
925 /* Return the "type" attribute of a gdb.Field object.
926 Returns NULL on error, with a Python exception set. */
929 get_field_type (PyObject
*field
)
931 gdbpy_ref
<> ftype_obj (PyObject_GetAttrString (field
, "type"));
934 if (ftype_obj
== NULL
)
936 ftype
= type_object_to_type (ftype_obj
.get ());
938 PyErr_SetString (PyExc_TypeError
,
939 _("'type' attribute of gdb.Field object is not a "
940 "gdb.Type object."));
945 /* Given string name or a gdb.Field object corresponding to an element inside
946 a structure, return its value object. Returns NULL on error, with a python
950 valpy_getitem (PyObject
*self
, PyObject
*key
)
952 struct gdb_exception except
;
953 value_object
*self_value
= (value_object
*) self
;
954 gdb::unique_xmalloc_ptr
<char> field
;
955 struct type
*base_class_type
= NULL
, *field_type
= NULL
;
957 PyObject
*result
= NULL
;
959 if (gdbpy_is_string (key
))
961 field
= python_string_to_host_string (key
);
965 else if (gdbpy_is_field (key
))
967 int is_base_class
, valid_field
;
969 valid_field
= value_has_field (self_value
->value
, key
);
972 else if (valid_field
== 0)
974 PyErr_SetString (PyExc_TypeError
,
975 _("Invalid lookup for a field not contained in "
981 is_base_class
= get_field_flag (key
, "is_base_class");
982 if (is_base_class
< 0)
984 else if (is_base_class
> 0)
986 base_class_type
= get_field_type (key
);
987 if (base_class_type
== NULL
)
992 gdbpy_ref
<> name_obj (PyObject_GetAttrString (key
, "name"));
994 if (name_obj
== NULL
)
997 if (name_obj
!= Py_None
)
999 field
= python_string_to_host_string (name_obj
.get ());
1005 if (!PyObject_HasAttrString (key
, "bitpos"))
1007 PyErr_SetString (PyExc_AttributeError
,
1008 _("gdb.Field object has no name and no "
1009 "'bitpos' attribute."));
1013 gdbpy_ref
<> bitpos_obj (PyObject_GetAttrString (key
, "bitpos"));
1014 if (bitpos_obj
== NULL
)
1016 if (!gdb_py_int_as_long (bitpos_obj
.get (), &bitpos
))
1019 field_type
= get_field_type (key
);
1020 if (field_type
== NULL
)
1028 struct value
*tmp
= self_value
->value
;
1029 struct value
*res_val
= NULL
;
1030 scoped_value_mark free_values
;
1033 res_val
= value_struct_elt (&tmp
, {}, field
.get (), NULL
,
1034 "struct/class/union");
1035 else if (bitpos
>= 0)
1036 res_val
= value_struct_elt_bitpos (&tmp
, bitpos
, field_type
,
1037 "struct/class/union");
1038 else if (base_class_type
!= NULL
)
1040 struct type
*val_type
;
1042 val_type
= check_typedef (tmp
->type ());
1043 if (val_type
->code () == TYPE_CODE_PTR
)
1044 res_val
= value_cast (lookup_pointer_type (base_class_type
), tmp
);
1045 else if (val_type
->code () == TYPE_CODE_REF
)
1046 res_val
= value_cast (lookup_lvalue_reference_type (base_class_type
),
1048 else if (val_type
->code () == TYPE_CODE_RVALUE_REF
)
1049 res_val
= value_cast (lookup_rvalue_reference_type (base_class_type
),
1052 res_val
= value_cast (base_class_type
, tmp
);
1056 /* Assume we are attempting an array access, and let the
1057 value code throw an exception if the index has an invalid
1059 struct value
*idx
= convert_value_from_python (key
);
1063 /* Check the value's type is something that can be accessed via
1067 tmp
= coerce_ref (tmp
);
1068 type
= check_typedef (tmp
->type ());
1069 if (type
->code () != TYPE_CODE_ARRAY
1070 && type
->code () != TYPE_CODE_PTR
)
1071 error (_("Cannot subscript requested type."));
1073 res_val
= value_subscript (tmp
, value_as_long (idx
));
1078 result
= value_to_value_object (res_val
);
1080 catch (gdb_exception
&ex
)
1082 except
= std::move (ex
);
1085 GDB_PY_HANDLE_EXCEPTION (except
);
1091 valpy_setitem (PyObject
*self
, PyObject
*key
, PyObject
*value
)
1093 PyErr_Format (PyExc_NotImplementedError
,
1094 _("Setting of struct elements is not currently supported."));
1098 /* Called by the Python interpreter to perform an inferior function
1099 call on the value. Returns NULL on error, with a python exception set. */
1101 valpy_call (PyObject
*self
, PyObject
*args
, PyObject
*keywords
)
1103 Py_ssize_t args_count
;
1104 struct value
*function
= ((value_object
*) self
)->value
;
1105 struct value
**vargs
= NULL
;
1106 struct type
*ftype
= NULL
;
1107 PyObject
*result
= NULL
;
1111 ftype
= check_typedef (function
->type ());
1113 catch (const gdb_exception
&except
)
1115 GDB_PY_HANDLE_EXCEPTION (except
);
1118 if (ftype
->code () != TYPE_CODE_FUNC
)
1120 PyErr_SetString (PyExc_RuntimeError
,
1121 _("Value is not callable (not TYPE_CODE_FUNC)."));
1125 if (! PyTuple_Check (args
))
1127 PyErr_SetString (PyExc_TypeError
,
1128 _("Inferior arguments must be provided in a tuple."));
1132 args_count
= PyTuple_Size (args
);
1137 vargs
= XALLOCAVEC (struct value
*, args_count
);
1138 for (i
= 0; i
< args_count
; i
++)
1140 PyObject
*item
= PyTuple_GetItem (args
, i
);
1145 vargs
[i
] = convert_value_from_python (item
);
1146 if (vargs
[i
] == NULL
)
1153 scoped_value_mark free_values
;
1156 = call_function_by_hand (function
, NULL
,
1157 gdb::make_array_view (vargs
, args_count
));
1158 result
= value_to_value_object (return_value
);
1160 catch (const gdb_exception
&except
)
1162 GDB_PY_HANDLE_EXCEPTION (except
);
1168 /* Called by the Python interpreter to obtain string representation
1171 valpy_str (PyObject
*self
)
1173 struct value_print_options opts
;
1175 gdbpy_get_print_options (&opts
);
1176 opts
.deref_ref
= false;
1182 common_val_print (((value_object
*) self
)->value
, &stb
, 0,
1183 &opts
, current_language
);
1185 catch (const gdb_exception
&except
)
1187 GDB_PY_HANDLE_EXCEPTION (except
);
1190 return PyUnicode_Decode (stb
.c_str (), stb
.size (), host_charset (), NULL
);
1193 /* Implements gdb.Value.is_optimized_out. */
1195 valpy_get_is_optimized_out (PyObject
*self
, void *closure
)
1197 struct value
*value
= ((value_object
*) self
)->value
;
1202 opt
= value
->optimized_out ();
1204 catch (const gdb_exception
&except
)
1206 GDB_PY_HANDLE_EXCEPTION (except
);
1215 /* Implements gdb.Value.is_lazy. */
1217 valpy_get_is_lazy (PyObject
*self
, void *closure
)
1219 struct value
*value
= ((value_object
*) self
)->value
;
1224 opt
= value
->lazy ();
1226 catch (const gdb_exception
&except
)
1228 GDB_PY_HANDLE_EXCEPTION (except
);
1237 /* Implements gdb.Value.fetch_lazy (). */
1239 valpy_fetch_lazy (PyObject
*self
, PyObject
*args
)
1241 struct value
*value
= ((value_object
*) self
)->value
;
1246 value
->fetch_lazy ();
1248 catch (const gdb_exception
&except
)
1250 GDB_PY_HANDLE_EXCEPTION (except
);
1256 /* Calculate and return the address of the PyObject as the value of
1257 the builtin __hash__ call. */
1259 valpy_hash (PyObject
*self
)
1261 return (intptr_t) self
;
1279 /* If TYPE is a reference, return the target; otherwise return TYPE. */
1280 #define STRIP_REFERENCE(TYPE) \
1281 (TYPE_IS_REFERENCE (TYPE) ? ((TYPE)->target_type ()) : (TYPE))
1283 /* Helper for valpy_binop. Returns a value object which is the result
1284 of applying the operation specified by OPCODE to the given
1285 arguments. Throws a GDB exception on error. */
1288 valpy_binop_throw (enum valpy_opcode opcode
, PyObject
*self
, PyObject
*other
)
1290 PyObject
*result
= NULL
;
1292 struct value
*arg1
, *arg2
;
1293 struct value
*res_val
= NULL
;
1294 enum exp_opcode op
= OP_NULL
;
1297 scoped_value_mark free_values
;
1299 /* If the gdb.Value object is the second operand, then it will be
1300 passed to us as the OTHER argument, and SELF will be an entirely
1301 different kind of object, altogether. Because of this, we can't
1302 assume self is a gdb.Value object and need to convert it from
1304 arg1
= convert_value_from_python (self
);
1308 arg2
= convert_value_from_python (other
);
1316 struct type
*ltype
= arg1
->type ();
1317 struct type
*rtype
= arg2
->type ();
1319 ltype
= check_typedef (ltype
);
1320 ltype
= STRIP_REFERENCE (ltype
);
1321 rtype
= check_typedef (rtype
);
1322 rtype
= STRIP_REFERENCE (rtype
);
1325 if (ltype
->code () == TYPE_CODE_PTR
1326 && is_integral_type (rtype
))
1327 res_val
= value_ptradd (arg1
, value_as_long (arg2
));
1328 else if (rtype
->code () == TYPE_CODE_PTR
1329 && is_integral_type (ltype
))
1330 res_val
= value_ptradd (arg2
, value_as_long (arg1
));
1340 struct type
*ltype
= arg1
->type ();
1341 struct type
*rtype
= arg2
->type ();
1343 ltype
= check_typedef (ltype
);
1344 ltype
= STRIP_REFERENCE (ltype
);
1345 rtype
= check_typedef (rtype
);
1346 rtype
= STRIP_REFERENCE (rtype
);
1349 if (ltype
->code () == TYPE_CODE_PTR
1350 && rtype
->code () == TYPE_CODE_PTR
)
1351 /* A ptrdiff_t for the target would be preferable here. */
1352 res_val
= value_from_longest (builtin_type_pyint
,
1353 value_ptrdiff (arg1
, arg2
));
1354 else if (ltype
->code () == TYPE_CODE_PTR
1355 && is_integral_type (rtype
))
1356 res_val
= value_ptradd (arg1
, - value_as_long (arg2
));
1383 op
= BINOP_BITWISE_AND
;
1386 op
= BINOP_BITWISE_IOR
;
1389 op
= BINOP_BITWISE_XOR
;
1395 if (binop_user_defined_p (op
, arg1
, arg2
))
1396 res_val
= value_x_binop (arg1
, arg2
, op
, OP_NULL
, EVAL_NORMAL
);
1398 res_val
= value_binop (arg1
, arg2
, op
);
1402 result
= value_to_value_object (res_val
);
1407 /* Returns a value object which is the result of applying the operation
1408 specified by OPCODE to the given arguments. Returns NULL on error, with
1409 a python exception set. */
1411 valpy_binop (enum valpy_opcode opcode
, PyObject
*self
, PyObject
*other
)
1413 PyObject
*result
= NULL
;
1417 result
= valpy_binop_throw (opcode
, self
, other
);
1419 catch (const gdb_exception
&except
)
1421 GDB_PY_HANDLE_EXCEPTION (except
);
1428 valpy_add (PyObject
*self
, PyObject
*other
)
1430 return valpy_binop (VALPY_ADD
, self
, other
);
1434 valpy_subtract (PyObject
*self
, PyObject
*other
)
1436 return valpy_binop (VALPY_SUB
, self
, other
);
1440 valpy_multiply (PyObject
*self
, PyObject
*other
)
1442 return valpy_binop (VALPY_MUL
, self
, other
);
1446 valpy_divide (PyObject
*self
, PyObject
*other
)
1448 return valpy_binop (VALPY_DIV
, self
, other
);
1452 valpy_remainder (PyObject
*self
, PyObject
*other
)
1454 return valpy_binop (VALPY_REM
, self
, other
);
1458 valpy_power (PyObject
*self
, PyObject
*other
, PyObject
*unused
)
1460 /* We don't support the ternary form of pow. I don't know how to express
1461 that, so let's just throw NotImplementedError to at least do something
1463 if (unused
!= Py_None
)
1465 PyErr_SetString (PyExc_NotImplementedError
,
1466 "Invalid operation on gdb.Value.");
1470 return valpy_binop (VALPY_POW
, self
, other
);
1474 valpy_negative (PyObject
*self
)
1476 PyObject
*result
= NULL
;
1480 /* Perhaps overkill, but consistency has some virtue. */
1481 scoped_value_mark free_values
;
1484 val
= value_neg (((value_object
*) self
)->value
);
1485 result
= value_to_value_object (val
);
1487 catch (const gdb_exception
&except
)
1489 GDB_PY_HANDLE_EXCEPTION (except
);
1496 valpy_positive (PyObject
*self
)
1498 return value_to_value_object (((value_object
*) self
)->value
);
1502 valpy_absolute (PyObject
*self
)
1504 struct value
*value
= ((value_object
*) self
)->value
;
1509 scoped_value_mark free_values
;
1511 if (value_less (value
, value::zero (value
->type (), not_lval
)))
1514 catch (const gdb_exception
&except
)
1516 GDB_PY_HANDLE_EXCEPTION (except
);
1520 return valpy_positive (self
);
1522 return valpy_negative (self
);
1525 /* Implements boolean evaluation of gdb.Value. */
1527 valpy_nonzero (PyObject
*self
)
1529 struct gdb_exception except
;
1530 value_object
*self_value
= (value_object
*) self
;
1532 int nonzero
= 0; /* Appease GCC warning. */
1536 type
= check_typedef (self_value
->value
->type ());
1538 if (is_integral_type (type
) || type
->code () == TYPE_CODE_PTR
)
1539 nonzero
= !!value_as_long (self_value
->value
);
1540 else if (is_floating_value (self_value
->value
))
1541 nonzero
= !target_float_is_zero
1542 (self_value
->value
->contents ().data (), type
);
1544 /* All other values are True. */
1547 catch (gdb_exception
&ex
)
1549 except
= std::move (ex
);
1552 /* This is not documented in the Python documentation, but if this
1553 function fails, return -1 as slot_nb_nonzero does (the default
1554 Python nonzero function). */
1555 GDB_PY_SET_HANDLE_EXCEPTION (except
);
1560 /* Implements ~ for value objects. */
1562 valpy_invert (PyObject
*self
)
1564 PyObject
*result
= nullptr;
1568 scoped_value_mark free_values
;
1569 struct value
*val
= value_complement (((value_object
*) self
)->value
);
1570 result
= value_to_value_object (val
);
1572 catch (const gdb_exception
&except
)
1574 GDB_PY_HANDLE_EXCEPTION (except
);
1580 /* Implements left shift for value objects. */
1582 valpy_lsh (PyObject
*self
, PyObject
*other
)
1584 return valpy_binop (VALPY_LSH
, self
, other
);
1587 /* Implements right shift for value objects. */
1589 valpy_rsh (PyObject
*self
, PyObject
*other
)
1591 return valpy_binop (VALPY_RSH
, self
, other
);
1594 /* Implements bitwise and for value objects. */
1596 valpy_and (PyObject
*self
, PyObject
*other
)
1598 return valpy_binop (VALPY_BITAND
, self
, other
);
1601 /* Implements bitwise or for value objects. */
1603 valpy_or (PyObject
*self
, PyObject
*other
)
1605 return valpy_binop (VALPY_BITOR
, self
, other
);
1608 /* Implements bitwise xor for value objects. */
1610 valpy_xor (PyObject
*self
, PyObject
*other
)
1612 return valpy_binop (VALPY_BITXOR
, self
, other
);
1615 /* Helper for valpy_richcompare. Implements comparison operations for
1616 value objects. Returns true/false on success. Returns -1 with a
1617 Python exception set if a Python error is detected. Throws a GDB
1618 exception on other errors (memory error, etc.). */
1621 valpy_richcompare_throw (PyObject
*self
, PyObject
*other
, int op
)
1624 struct value
*value_other
;
1625 struct value
*value_self
;
1627 scoped_value_mark free_values
;
1629 value_other
= convert_value_from_python (other
);
1630 if (value_other
== NULL
)
1633 value_self
= ((value_object
*) self
)->value
;
1638 result
= value_less (value_self
, value_other
);
1641 result
= value_less (value_self
, value_other
)
1642 || value_equal (value_self
, value_other
);
1645 result
= value_equal (value_self
, value_other
);
1648 result
= !value_equal (value_self
, value_other
);
1651 result
= value_less (value_other
, value_self
);
1654 result
= (value_less (value_other
, value_self
)
1655 || value_equal (value_self
, value_other
));
1659 PyErr_SetString (PyExc_NotImplementedError
,
1660 _("Invalid operation on gdb.Value."));
1669 /* Implements comparison operations for value objects. Returns NULL on error,
1670 with a python exception set. */
1672 valpy_richcompare (PyObject
*self
, PyObject
*other
, int op
)
1676 if (other
== Py_None
)
1677 /* Comparing with None is special. From what I can tell, in Python
1678 None is smaller than anything else. */
1690 PyErr_SetString (PyExc_NotImplementedError
,
1691 _("Invalid operation on gdb.Value."));
1697 result
= valpy_richcompare_throw (self
, other
, op
);
1699 catch (const gdb_exception
&except
)
1701 GDB_PY_HANDLE_EXCEPTION (except
);
1704 /* In this case, the Python exception has already been set. */
1714 /* Implements conversion to long. */
1716 valpy_long (PyObject
*self
)
1718 struct value
*value
= ((value_object
*) self
)->value
;
1719 struct type
*type
= value
->type ();
1724 if (is_floating_value (value
))
1726 type
= builtin_type_pylong
;
1727 value
= value_cast (type
, value
);
1730 type
= check_typedef (type
);
1732 if (!is_integral_type (type
)
1733 && type
->code () != TYPE_CODE_PTR
)
1734 error (_("Cannot convert value to long."));
1736 l
= value_as_long (value
);
1738 catch (const gdb_exception
&except
)
1740 GDB_PY_HANDLE_EXCEPTION (except
);
1743 if (type
->is_unsigned ())
1744 return gdb_py_object_from_ulongest (l
).release ();
1746 return gdb_py_object_from_longest (l
).release ();
1749 /* Implements conversion to float. */
1751 valpy_float (PyObject
*self
)
1753 struct value
*value
= ((value_object
*) self
)->value
;
1754 struct type
*type
= value
->type ();
1759 type
= check_typedef (type
);
1761 if (type
->code () == TYPE_CODE_FLT
&& is_floating_value (value
))
1762 d
= target_float_to_host_double (value
->contents ().data (), type
);
1763 else if (type
->code () == TYPE_CODE_INT
)
1765 /* Note that valpy_long accepts TYPE_CODE_PTR and some
1766 others here here -- but casting a pointer or bool to a
1767 float seems wrong. */
1768 d
= value_as_long (value
);
1771 error (_("Cannot convert value to float."));
1773 catch (const gdb_exception
&except
)
1775 GDB_PY_HANDLE_EXCEPTION (except
);
1778 return PyFloat_FromDouble (d
);
1781 /* Returns an object for a value, without releasing it from the
1782 all_values chain. */
1784 value_to_value_object (struct value
*val
)
1786 value_object
*val_obj
;
1788 val_obj
= PyObject_New (value_object
, &value_object_type
);
1789 if (val_obj
!= NULL
)
1792 val_obj
->value
= val
;
1793 val_obj
->next
= nullptr;
1794 val_obj
->prev
= nullptr;
1795 val_obj
->address
= NULL
;
1796 val_obj
->type
= NULL
;
1797 val_obj
->dynamic_type
= NULL
;
1798 note_value (val_obj
);
1801 return (PyObject
*) val_obj
;
1804 /* Returns a borrowed reference to the struct value corresponding to
1805 the given value object. */
1807 value_object_to_value (PyObject
*self
)
1811 if (! PyObject_TypeCheck (self
, &value_object_type
))
1813 real
= (value_object
*) self
;
1817 /* Try to convert a Python value to a gdb value. If the value cannot
1818 be converted, set a Python exception and return NULL. Returns a
1819 reference to a new value on the all_values chain. */
1822 convert_value_from_python (PyObject
*obj
)
1824 struct value
*value
= NULL
; /* -Wall */
1827 gdb_assert (obj
!= NULL
);
1831 if (PyBool_Check (obj
))
1833 cmp
= PyObject_IsTrue (obj
);
1835 value
= value_from_longest (builtin_type_pybool
, cmp
);
1837 else if (PyLong_Check (obj
))
1839 LONGEST l
= PyLong_AsLongLong (obj
);
1841 if (PyErr_Occurred ())
1843 /* If the error was an overflow, we can try converting to
1844 ULONGEST instead. */
1845 if (PyErr_ExceptionMatches (PyExc_OverflowError
))
1847 gdbpy_err_fetch fetched_error
;
1848 gdbpy_ref
<> zero
= gdb_py_object_from_longest (0);
1850 /* Check whether obj is positive. */
1851 if (PyObject_RichCompareBool (obj
, zero
.get (), Py_GT
) > 0)
1855 ul
= PyLong_AsUnsignedLongLong (obj
);
1856 if (! PyErr_Occurred ())
1857 value
= value_from_ulongest (builtin_type_upylong
, ul
);
1861 /* There's nothing we can do. */
1862 fetched_error
.restore ();
1867 value
= value_from_longest (builtin_type_pylong
, l
);
1869 else if (PyFloat_Check (obj
))
1871 double d
= PyFloat_AsDouble (obj
);
1873 if (! PyErr_Occurred ())
1874 value
= value_from_host_double (builtin_type_pyfloat
, d
);
1876 else if (gdbpy_is_string (obj
))
1878 gdb::unique_xmalloc_ptr
<char> s
1879 = python_string_to_target_string (obj
);
1882 = current_language
->value_string (gdbpy_enter::get_gdbarch (),
1883 s
.get (), strlen (s
.get ()));
1885 else if (PyObject_TypeCheck (obj
, &value_object_type
))
1886 value
= ((value_object
*) obj
)->value
->copy ();
1887 else if (gdbpy_is_lazy_string (obj
))
1891 result
= PyObject_CallMethodObjArgs (obj
, gdbpy_value_cst
, NULL
);
1892 value
= ((value_object
*) result
)->value
->copy ();
1895 PyErr_Format (PyExc_TypeError
,
1896 _("Could not convert Python object: %S."), obj
);
1898 catch (const gdb_exception
&except
)
1900 gdbpy_convert_exception (except
);
1907 /* Returns value object in the ARGth position in GDB's history. */
1909 gdbpy_history (PyObject
*self
, PyObject
*args
)
1913 if (!PyArg_ParseTuple (args
, "i", &i
))
1916 PyObject
*result
= nullptr;
1919 scoped_value_mark free_values
;
1920 struct value
*res_val
= access_value_history (i
);
1921 result
= value_to_value_object (res_val
);
1923 catch (const gdb_exception
&except
)
1925 GDB_PY_HANDLE_EXCEPTION (except
);
1931 /* Add a gdb.Value into GDB's history, and return (as an integer) the
1932 position of the newly added value. */
1934 gdbpy_add_history (PyObject
*self
, PyObject
*args
)
1936 PyObject
*value_obj
;
1938 if (!PyArg_ParseTuple (args
, "O", &value_obj
))
1941 struct value
*value
= convert_value_from_python (value_obj
);
1942 if (value
== nullptr)
1947 int idx
= value
->record_latest ();
1948 return gdb_py_object_from_longest (idx
).release ();
1950 catch (const gdb_exception
&except
)
1952 GDB_PY_HANDLE_EXCEPTION (except
);
1958 /* Return an integer, the number of items in GDB's history. */
1961 gdbpy_history_count (PyObject
*self
, PyObject
*args
)
1963 return gdb_py_object_from_ulongest (value_history_count ()).release ();
1966 /* Return the value of a convenience variable. */
1968 gdbpy_convenience_variable (PyObject
*self
, PyObject
*args
)
1970 const char *varname
;
1971 struct value
*res_val
= NULL
;
1973 if (!PyArg_ParseTuple (args
, "s", &varname
))
1976 PyObject
*result
= nullptr;
1980 struct internalvar
*var
= lookup_only_internalvar (varname
);
1984 scoped_value_mark free_values
;
1985 res_val
= value_of_internalvar (gdbpy_enter::get_gdbarch (), var
);
1986 if (res_val
->type ()->code () == TYPE_CODE_VOID
)
1991 result
= value_to_value_object (res_val
);
1995 catch (const gdb_exception
&except
)
1997 GDB_PY_HANDLE_EXCEPTION (except
);
2000 if (result
== nullptr && !found
)
2006 /* Set the value of a convenience variable. */
2008 gdbpy_set_convenience_variable (PyObject
*self
, PyObject
*args
)
2010 const char *varname
;
2011 PyObject
*value_obj
;
2012 struct value
*value
= NULL
;
2014 if (!PyArg_ParseTuple (args
, "sO", &varname
, &value_obj
))
2017 /* None means to clear the variable. */
2018 if (value_obj
!= Py_None
)
2020 value
= convert_value_from_python (value_obj
);
2029 struct internalvar
*var
= lookup_only_internalvar (varname
);
2032 clear_internalvar (var
);
2036 struct internalvar
*var
= lookup_internalvar (varname
);
2038 set_internalvar (var
, value
);
2041 catch (const gdb_exception
&except
)
2043 GDB_PY_HANDLE_EXCEPTION (except
);
2049 /* Returns 1 in OBJ is a gdb.Value object, 0 otherwise. */
2052 gdbpy_is_value_object (PyObject
*obj
)
2054 return PyObject_TypeCheck (obj
, &value_object_type
);
2057 static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
2058 gdbpy_initialize_values (void)
2060 if (PyType_Ready (&value_object_type
) < 0)
2063 return gdb_pymodule_addobject (gdb_module
, "Value",
2064 (PyObject
*) &value_object_type
);
2067 GDBPY_INITIALIZE_FILE (gdbpy_initialize_values
);
2071 static gdb_PyGetSetDef value_object_getset
[] = {
2072 { "address", valpy_get_address
, NULL
, "The address of the value.",
2074 { "is_optimized_out", valpy_get_is_optimized_out
, NULL
,
2075 "Boolean telling whether the value is optimized "
2076 "out (i.e., not available).",
2078 { "type", valpy_get_type
, NULL
, "Type of the value.", NULL
},
2079 { "dynamic_type", valpy_get_dynamic_type
, NULL
,
2080 "Dynamic type of the value.", NULL
},
2081 { "is_lazy", valpy_get_is_lazy
, NULL
,
2082 "Boolean telling whether the value is lazy (not fetched yet\n\
2083 from the inferior). A lazy value is fetched when needed, or when\n\
2084 the \"fetch_lazy()\" method is called.", NULL
},
2085 {NULL
} /* Sentinel */
2088 static PyMethodDef value_object_methods
[] = {
2089 { "cast", valpy_cast
, METH_VARARGS
, "Cast the value to the supplied type." },
2090 { "dynamic_cast", valpy_dynamic_cast
, METH_VARARGS
,
2091 "dynamic_cast (gdb.Type) -> gdb.Value\n\
2092 Cast the value to the supplied type, as if by the C++ dynamic_cast operator."
2094 { "reinterpret_cast", valpy_reinterpret_cast
, METH_VARARGS
,
2095 "reinterpret_cast (gdb.Type) -> gdb.Value\n\
2096 Cast the value to the supplied type, as if by the C++\n\
2097 reinterpret_cast operator."
2099 { "dereference", valpy_dereference
, METH_NOARGS
, "Dereferences the value." },
2100 { "referenced_value", valpy_referenced_value
, METH_NOARGS
,
2101 "Return the value referenced by a TYPE_CODE_REF or TYPE_CODE_PTR value." },
2102 { "reference_value", valpy_lvalue_reference_value
, METH_NOARGS
,
2103 "Return a value of type TYPE_CODE_REF referencing this value." },
2104 { "rvalue_reference_value", valpy_rvalue_reference_value
, METH_NOARGS
,
2105 "Return a value of type TYPE_CODE_RVALUE_REF referencing this value." },
2106 { "const_value", valpy_const_value
, METH_NOARGS
,
2107 "Return a 'const' qualified version of the same value." },
2108 { "lazy_string", (PyCFunction
) valpy_lazy_string
,
2109 METH_VARARGS
| METH_KEYWORDS
,
2110 "lazy_string ([encoding] [, length]) -> lazy_string\n\
2111 Return a lazy string representation of the value." },
2112 { "string", (PyCFunction
) valpy_string
, METH_VARARGS
| METH_KEYWORDS
,
2113 "string ([encoding] [, errors] [, length]) -> string\n\
2114 Return Unicode string representation of the value." },
2115 { "fetch_lazy", valpy_fetch_lazy
, METH_NOARGS
,
2116 "Fetches the value from the inferior, if it was lazy." },
2117 { "format_string", (PyCFunction
) valpy_format_string
,
2118 METH_VARARGS
| METH_KEYWORDS
,
2119 "format_string (...) -> string\n\
2120 Return a string representation of the value using the specified\n\
2121 formatting options" },
2122 {NULL
} /* Sentinel */
2125 static PyNumberMethods value_object_as_number
= {
2130 NULL
, /* nb_divmod */
2131 valpy_power
, /* nb_power */
2132 valpy_negative
, /* nb_negative */
2133 valpy_positive
, /* nb_positive */
2134 valpy_absolute
, /* nb_absolute */
2135 valpy_nonzero
, /* nb_nonzero */
2136 valpy_invert
, /* nb_invert */
2137 valpy_lsh
, /* nb_lshift */
2138 valpy_rsh
, /* nb_rshift */
2139 valpy_and
, /* nb_and */
2140 valpy_xor
, /* nb_xor */
2141 valpy_or
, /* nb_or */
2142 valpy_long
, /* nb_int */
2143 NULL
, /* reserved */
2144 valpy_float
, /* nb_float */
2145 NULL
, /* nb_inplace_add */
2146 NULL
, /* nb_inplace_subtract */
2147 NULL
, /* nb_inplace_multiply */
2148 NULL
, /* nb_inplace_remainder */
2149 NULL
, /* nb_inplace_power */
2150 NULL
, /* nb_inplace_lshift */
2151 NULL
, /* nb_inplace_rshift */
2152 NULL
, /* nb_inplace_and */
2153 NULL
, /* nb_inplace_xor */
2154 NULL
, /* nb_inplace_or */
2155 NULL
, /* nb_floor_divide */
2156 valpy_divide
, /* nb_true_divide */
2157 NULL
, /* nb_inplace_floor_divide */
2158 NULL
, /* nb_inplace_true_divide */
2159 valpy_long
, /* nb_index */
2162 static PyMappingMethods value_object_as_mapping
= {
2168 PyTypeObject value_object_type
= {
2169 PyVarObject_HEAD_INIT (NULL
, 0)
2170 "gdb.Value", /*tp_name*/
2171 sizeof (value_object
), /*tp_basicsize*/
2173 valpy_dealloc
, /*tp_dealloc*/
2179 &value_object_as_number
, /*tp_as_number*/
2180 0, /*tp_as_sequence*/
2181 &value_object_as_mapping
, /*tp_as_mapping*/
2182 valpy_hash
, /*tp_hash*/
2183 valpy_call
, /*tp_call*/
2184 valpy_str
, /*tp_str*/
2188 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
2189 | Py_TPFLAGS_BASETYPE
, /*tp_flags*/
2190 "GDB value object", /* tp_doc */
2191 0, /* tp_traverse */
2193 valpy_richcompare
, /* tp_richcompare */
2194 0, /* tp_weaklistoffset */
2196 0, /* tp_iternext */
2197 value_object_methods
, /* tp_methods */
2199 value_object_getset
, /* tp_getset */
2202 0, /* tp_descr_get */
2203 0, /* tp_descr_set */
2204 0, /* tp_dictoffset */
2205 valpy_init
, /* tp_init */
2207 PyType_GenericNew
, /* tp_new */